text
stringlengths 8
6.88M
|
|---|
#ifndef INCLUDED_NETWORK_MESSAGE_SENDER_SYSTEM_H
#define INCLUDED_NETWORK_MESSAGE_SENDER_SYSTEM_H
#include "engine/system.h"
#include "messsage_holder.h"
#include "core/scene.h"
#include "core/program_state.h"
#include <set>
#include "platform/frequency_timer.h"
using core::ProgramState;
namespace network {
class ActorFrequencyTimer : public FrequencyTimer
{
int32_t mActorId;
public:
ActorFrequencyTimer( double frequency, int32_t actorId );
int32_t GetActorId() const;
};
class ActorFrequencyTimerHolder
{
typedef std::list<ActorFrequencyTimer> ActorFrequencyTimers_t;
ActorFrequencyTimers_t mActorFrequencyTimers;
typedef std::set<int32_t> ActorIds_t;
public:
void Add( ActorFrequencyTimer const& actorFrequencyTimer );
void Update( double DeltaTime );
ActorIds_t GetActorIds();
};
class MessageSenderSystem: public engine::System
{
protected:
FrequencyTimer mFrequencyTimer;
MessageHolder& mMessageHolder;
Scene& mScene;
ProgramState& mProgramState;
bool mIsClient;
bool IsClient();
bool mIsServer;
bool IsServer();
bool IsTime();
void SetFrequency( double frequency );
public:
MessageSenderSystem();
virtual void Init();
virtual void Update( double DeltaTime );
};
} // namespace network
#endif//INCLUDED_NETWORK_MESSAGE_SENDER_SYSTEM_H
|
#include <iostream>
#include <list>
#include <deque>
#include <algorithm>
#include <sequtils.h>
#include <countptr.h>
using namespace std;
ostream& operator<<(ostream& os, const CountedPtr<int>& elem) {
os << *elem << ' ';
return os;
}
int main(int argc, char *argv[])
{
static int v[]= {3,5,9,1,6,4};
typedef CountedPtr<int> IntPtr;
deque<IntPtr> col1;
list<IntPtr> col2;
for (int i =0 ; i < (sizeof(v) / sizeof(v[0])); ++i) {
IntPtr ptr(new int(v[i]));
col1.push_back(ptr);
col2.push_front(ptr);
}
print_seq(col1);
print_seq(col2);
// square 3rd element
*col1[2] *= *col1[2];
// negate first element
(**col1.begin()) *= -1;
(**col2.begin()) = 0;
print_seq(col1);
print_seq(col2);
return 0;
}
|
#include<iostream>
using namespace std;
const int N = 2500;
int a[N];
int main(){
int n, m;
cin >> n;
n = (n*n-n)/2;
m = 0;
a[m++] = 1;
for(int k=1;k<=n;++k)
for(int i=0, o=0;i<m || o;++i){
o = a[i] * 3 + o;
a[i] = o % 10;
o /= 10;
m = max(m, i+1);
}
for(int i=m-1;i>=0;--i) cout<<a[i];
return 0;
}
|
#pragma once
#include <string>
#include <cstdint>
#include <vector>
#include <glm/glm.hpp>
class Shader {
// mostly for debug purpose
static uint32_t currentId;
uint32_t id = 0;
public:
Shader() = default;
~Shader() { Reset(); }
Shader(Shader&& other) noexcept;
Shader& operator=(Shader&& other) noexcept;
Shader(const Shader&) = delete;
Shader& operator=(const Shader&) = delete;
enum class Type {
Vertex,
Fragment,
Compute
};
void Load(const std::string& vertexFile, const std::string& fragmentFile);
void Load(const std::string& computeFile);
void Reset();
void Select() const;
void SetBool(const std::string& name, bool value) const;
void SetInt32(const std::string& name, int32_t value) const;
void SetFloat(const std::string& name, float value) const;
void SetVec2(const std::string& name, const glm::vec2& value) const;
void SetVec3(const std::string& name, const glm::vec3& value) const;
void SetVec4(const std::string& name, const glm::vec4& value) const;
void SetMat2(const std::string& name, const glm::mat2& value) const;
void SetMat3(const std::string& name, const glm::mat3& value) const;
void SetMat4(const std::string& name, const glm::mat4& value) const;
void SetIVec2Vec(const std::string& name, const std::vector<glm::ivec2>& vec) const;
template <typename T>
void SetBool(const std::string& name, T value) const = delete;
template <typename T>
void SetInt32(const std::string& name, T value) const = delete;
template <typename T>
void SetFloat(const std::string& name, T value) const = delete;
template <typename T>
void SetVec2(const std::string& name, const T& value) const = delete;
template <typename T>
void SetVec3(const std::string& name, const T& value) const = delete;
template <typename T>
void SetVec4(const std::string& name, const T& value) const = delete;
template <typename T>
void SetMat2(const std::string& name, const T& value) const = delete;
template <typename T>
void SetMat3(const std::string& name, const T& value) const = delete;
template <typename T>
void SetMat4(const std::string& name, const T& value) const = delete;
template <typename T>
void SetIVec2Vec(const std::string& name, const T& vec) const = delete;
void UpdateProjection(glm::vec2 size, bool flip) const;
uint32_t GetId() const;
void Link(const std::vector<uint32_t>& ids);
static uint32_t LoadShader(const std::string& fileName, Shader::Type type);
static void DeleteShader(uint32_t shader);
private:
static std::string ReadShader(const std::string& fileName);
static uint32_t CompileShader(const std::string& code, Shader::Type type);
};
|
// http://oj.leetcode.com/problems/restore-ip-addresses/
class Solution {
void do_restore(string& str, int beg, vector<string>& ret, string tmp, int remaining) {
int size = str.size() - beg;
if (remaining == 0 && size == 0) {
string r = tmp;
ret.push_back(r);
return;
}
if (size < remaining || size > 3 * remaining) {
return;
}
for (int i = 1; i <= 3; i++) {
// eliminate the unnecessary head zero
if (i != 1 && str[beg] == '0') {
continue;
}
string part = str.substr(beg, i);
int num = stoi(part, nullptr);
if (num <= 255 && num >= 0) {
if (remaining > 1) {
part += ".";
}
do_restore(str, beg + i, ret, tmp + part, remaining - 1);
}
}
}
public:
vector<string> restoreIpAddresses(string s) {
vector<string> ret;
string tmp = "";
do_restore(s, 0, ret, tmp, 4);
return ret;
}
};
|
#pragma once
#include<iostream>
using namespace std;
template<class T>
struct CircLinkNode
{
T data;
CircLinkNode<T>* next;
};
template<class T>
class CircLinkList
{
public:
CircLinkList(); //构造函数
~CircLinkList(); //析构函数
void Head_Insert(); //头插法创建链表
void Tail_Insert(); //尾插法创建链表
int Is_Empty(); //链表是否为空
int Insert_pos(int pos, T val); //按位置插入
int Delete_pos(int pos); //按位置删除
int Search_val(int pos, T& ser); //查看链表的值
int Is_Exist(T val); //查看val是否在单链表中
int Change_val(int pos, T val); //修改链表的值
void Show(); //输出链表
int LinkList_length(); //获取链表的长度
void Destory(); //销毁链表
private:
CircLinkNode<T>* first;
CircLinkNode<T>* last;
};
template<class T>
CircLinkList<T>::CircLinkList()
{
first = new CircLinkNode<T>;
last = first;
first->next = first;
}
template<class T>
CircLinkList<T>::~CircLinkList()
{
while (first != last)
{
CircLinkNode<T>* p = first;
last->next = first->next;
first = first->next;
delete p;
}
}
template<class T>
void CircLinkList<T>::Head_Insert() //头插法创建链表
{
int n;
cout << "请输入循环链表长度:";
cin >> n;
for (int i = 0; i < n; i++)
{
CircLinkNode<T>* temp = new CircLinkNode<T>;
cout << "请输入第" << i + 1 << "个元素:";
cin >> temp->data;
temp->next = first->next;
first->next = temp;
if (first == last)
{
last = temp;
}
}
}
template<class T>
void CircLinkList<T>::Tail_Insert() //尾插法创建链表
{
int n;
cout << "请输入循环链表的长度:";
cin >> n;
for (int i = 0; i < n; i++)
{
CircLinkNode<T>* temp = new CircLinkNode<T>;
cout << "请输入第" << i + 1 << "个元素:";
cin >> temp->data;
temp->next = first;
last->next = temp;
last = temp;
}
}
template<class T>
int CircLinkList<T>::Is_Empty() //链表是否为空
{
return first == last ? 1 : 0;
}
template<class T>
int CircLinkList<T>::Insert_pos(int pos, T val) //按位置插入
{
if (pos > LinkList_length() + 1) //位置不合适
{
return 0;
}
int j = 0;
CircLinkNode<T>* p = first;
while (p->next != first && j < pos - 1) //找到前一个
{
p = p->next;
j++;
}
CircLinkNode<T>* temp = new CircLinkNode<T>;
temp->data = val;
temp->next = p->next;
p->next = temp;
if (p == last) //在链尾的时候处理与前面不太一样
{
temp = last;
}
return 1;
}
template<class T>
int CircLinkList<T>::Delete_pos(int pos) //按位置删除
{
if (pos > LinkList_length()) //位置不合适
{
return 0;
}
int j = 0;
CircLinkNode<T>* p = first;
while (p->next != first && j < pos - 1)
{
p = p->next;
j++;
}
CircLinkNode<T>* t = p->next;
p->next = p->next->next;
delete t;
if (p->next == first)
{
last = p;
}
return 1;
}
template<class T>
int CircLinkList<T>::Search_val(int pos, T& ser) //查看链表的值
{
if (pos > LinkList_length()) //位置不合适
{
return 0;
}
int j = 1;
CircLinkNode<T>* p = first->next;
while (p->next != first && j < pos)
{
p = p->next;
j++;
}
ser = p->data;
return 1;
}
template<class T>
int CircLinkList<T>::Is_Exist(T val) //查看val是否在单链表中
{
int flag = 0;
CircLinkNode<T>* p = first->next;
while (p != first)
{
if (p->data == val)
{
flag = 1;
break;
}
p = p->next;
}
return flag;
}
template<class T>
int CircLinkList<T>::Change_val(int pos, T val) //修改链表的值
{
if (pos > LinkList_length()) //位置不合适
{
return 0;
}
int j = 1;
CircLinkNode<T>* p = first->next;
while (p->next != first && j < pos)
{
p = p->next;
j++;
}
p->data = val;
return 1;
}
template<class T>
void CircLinkList<T>::Show() //输出链表
{
if (first == last)
{
cout << "循环链表为空" << endl;
}
CircLinkNode<T>* p = first->next;
while (p != first)
{
cout << p->data << "\t";
p = p->next;
}
}
template<class T>
int CircLinkList<T>::LinkList_length() //获取链表的长度
{
int len = 0;
CircLinkNode<T>* p = first->next;
while (p != first)
{
len++;
p = p->next;
}
return len;
}
template<class T>
void CircLinkList<T>::Destory() //销毁链表
{
while (!Is_Empty())
{
Delete_pos(1);
}
}
|
#include <iostream>
struct Date {
int day;
int month;
int year;
};
bool check(int day,int month) {
if(1 > month || 12 < month || 1 > day) {
return false;
}
if((1 == month || 3 == month || 5 == month || 7 == month || 8 == month || 10 == month || 12 == month) && 31 < day) {
return false;
} else if(2 == month && 28 < day) {
return false;
} else if((4 == month || 6 == month || 9 == month || 11 == month) && 30 < day) {
return false;
} else {
return true;
}
}
int daysCount(Date firstDate, Date secondDate) {
int daysOfMonths[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int daysCount = (secondDate.year - firstDate.year - 1) * 365 - firstDate.day + secondDate.day;
for(int i = firstDate.month; i < 12; ++i) {
daysCount += daysOfMonths[i];
}
for(int i = 0; i < secondDate.month; ++i) {
daysCount += daysOfMonths[i];
}
return daysCount;
}
int main() {
int year;
int month;
int day;
std::cout << "Input the first date- DAY MONTH YEAR (ex. 12 01 2018) : ";
std::cin >> day >> month >> year;
std::cout << "\n";
Date firstDate = { day, month, year };
if(check(day, month) ) {
std::cout << "Input the second date- DAY MONTH YEAR (ex. 20 01 2018) : ";
std::cin >> day >> month >> year;
std::cout << "\n";
Date secondDate = {day, month, year};
if(check(day, month)) {
if(firstDate.year > secondDate.year || (firstDate.year == secondDate.year && firstDate.month > secondDate.month) ||
(firstDate.year == secondDate.year && firstDate.month == secondDate.month && firstDate.day > secondDate.day)) {
std::cout << "The first date is leter than the second\n";
} else {
std::cout << "The count of the days is : " << daysCount(firstDate, secondDate) << std::endl;
}
} else {
std::cout << "Wrong input\n";
}
} else {
std::cout << "Wrong input\n";
}
return 0;
}
|
/*****************************************************************************
Copyright (c) 2008, Hangzhou H3C Technologies Co., Ltd. All rights reserved.
------------------------------------------------------------------------------
list.h
Project Code: Comware Leopard
Module Name:
Date Created: 2008-3-28
Author: c02254
Description: This file defines four types of data structures: singly-linked
lists, singly-linked tail queues, doubly-linked lists and
doubly-linked tail queues.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
2009-8-5 Y01604 Add RCU supporting
*****************************************************************************/
#ifndef _SYS_LIST_H_
#define _SYS_LIST_H_
#ifdef __cplusplus
extern "C"{
#endif
/*
* Singly-linked List
*
* A singly-linked list is headed by a single forward pointer. The elements
* are singly linked for minimum space and pointer manipulation overhead at
* the expense of O(n) removal for arbitrary elements. New elements can be
* added to the list after an existing element or at the head of the list.
* Elements being removed from the head of the list should use the explicit
* macro for this purpose for optimum efficiency. A singly-linked list may
* only be traversed in the forward direction. Singly-linked lists are ideal
* for applications with large datasets and few or no removals or for
* implementing a LIFO queue.
+--------------+ +--------------+
|user structure| |user structure|
+--------------+ +--------------+
| ...... | | ...... |
+--------------+ +--------------+
+------------+ +-->|+------------+| +-->|+------------+|
| SL_HEAD_S | | || SL_NODE_S || | || SL_NODE_S ||
+------------+ | |+------------+| | |+------------+|
| pstFirst |--+ || pstNext ||--+ || pstNext ||----+
+------------+ |+------------+| |+------------+| -+-
+--------------+ +--------------+
| ...... | | ...... |
+--------------+ +--------------+
*/
typedef struct tagSL_NODE
{
struct tagSL_NODE* pstNext; /* the next element */
} SL_NODE_S;
#define SL_ENTRY(ptr, type, member) (container_of(ptr, type, member))
typedef struct tagSL_HEAD
{
SL_NODE_S* pstFirst;
} SL_HEAD_S;
static inline VOID SL_Init(IN SL_HEAD_S* pstList);
static inline VOID SL_NodeInit(IN SL_NODE_S* pstNode);
static inline BOOL_T SL_IsEmpty(IN SL_HEAD_S* pstList);
static inline SL_NODE_S* SL_First(IN SL_HEAD_S* pstList);
static inline SL_NODE_S* SL_Next(IN SL_NODE_S* pstNode);
static inline VOID SL_AddHead(IN SL_HEAD_S* pstList, IN SL_NODE_S* pstNode);
static inline SL_NODE_S* SL_DelHead(IN SL_HEAD_S* pstList);
static inline VOID SL_AddAfter(IN SL_HEAD_S* pstList,
IN SL_NODE_S* pstPrev,
IN SL_NODE_S* pstInst);
static inline SL_NODE_S* SL_DelAfter(IN SL_HEAD_S* pstList,
IN SL_NODE_S* pstPrev);
static inline VOID SL_Del(IN SL_HEAD_S* pstList, IN SL_NODE_S* pstNode);
static inline VOID SL_Append(IN SL_HEAD_S* pstDstList, IN SL_HEAD_S* pstSrcList);
static inline VOID SL_FreeAll(IN SL_HEAD_S *pstList, IN VOID (*pfFree)(VOID *));
/*****************************************************************************
Func Name: SL_Init
Date Created: 2008/3/28
Author: c02254
Description: Initialize the singly-linked list head
Input: SL_HEAD_S* pstList the pointer to the list head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID SL_Init(IN SL_HEAD_S* pstList)
{
pstList->pstFirst = (SL_NODE_S *)NULL;
return;
}
/*****************************************************************************
Func Name: SL_NodeInit
Date Created: 2008/8/6
Author: c02254
Description: Initialize the singly-linked list node
Input: IN SL_NODE_S* pstNode List node pointer
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID SL_NodeInit(IN SL_NODE_S* pstNode)
{
pstNode->pstNext = (SL_NODE_S *)NULL;
}
/*****************************************************************************
Func Name: SL_IsEmpty
Date Created: 2008/3/28
Author: c02254
Description: Whether the singly-linked list is empty
Input: SL_HEAD_S* pstList the pointer to the list head
Output: No output
Return: BOOL_TRUE or BOOL_FLASE
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline BOOL_T SL_IsEmpty(IN SL_HEAD_S* pstList)
{
return (pstList->pstFirst == NULL);
}
/*****************************************************************************
Func Name: SL_First
Date Created: 2008/3/28
Author: c02254
Description: Get the first element of a singly-linked list
Input: SL_HEAD_S* pstList the pointer to the list head
Output: No output
Return: the pointer to first element of the singly-linked list
NULL if the list is empty
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline SL_NODE_S* SL_First(IN SL_HEAD_S* pstList)
{
return (pstList->pstFirst);
}
/*****************************************************************************
Func Name: SL_Next
Date Created: 2008/3/28
Author: c02254
Description: Get the next element of current one
Input: SL_NODE_S* pstNode the pointer to current element
Output: No output
Return: the pointer to next element of current element
NULL if the current element is the last one
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline SL_NODE_S* SL_Next(IN SL_NODE_S* pstNode)
{
return (pstNode->pstNext);
}
/*****************************************************************************
Func Name: SL_AddHead
Date Created: 2008/3/28
Author: c02254
Description: Add an element to the head of the list
Input: SL_HEAD_S* pstList the pointer to the list head
SL_NODE_S* pstNode the pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID SL_AddHead(IN SL_HEAD_S* pstList, IN SL_NODE_S* pstNode)
{
pstNode->pstNext = pstList->pstFirst;
pstList->pstFirst = pstNode;
return;
}
/*****************************************************************************
Func Name: SL_DelHead
Date Created: 2008/3/28
Author: c02254
Description: Delete the first element from the list
Input: SL_HEAD_S* pstList the pointer to the list head
Output: No output
Return: the pointer to the deleted element, NULL if no element is deleted
Caution: This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline SL_NODE_S* SL_DelHead(IN SL_HEAD_S* pstList)
{
SL_NODE_S* pstNode = pstList->pstFirst;
if (NULL != pstNode)
{
pstList->pstFirst = pstNode->pstNext;
}
return pstNode;
}
/*****************************************************************************
Func Name: SL_AddAfter
Date Created: 2008/3/28
Author: c02254
Description: Add an element after another one
Input: SL_HEAD_S* pstList the pointer to the list head
SL_NODE_S* pstPrev pointer to the previous element
SL_NODE_S* pstInst pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID SL_AddAfter(IN SL_HEAD_S* pstList,
IN SL_NODE_S* pstPrev,
IN SL_NODE_S* pstInst)
{
if (NULL == pstPrev)
{
SL_AddHead (pstList, pstInst);
}
else
{
pstInst->pstNext = pstPrev->pstNext;
pstPrev->pstNext = pstInst;
}
return;
}
/*****************************************************************************
Func Name: SL_DelAfter
Date Created: 2008/3/28
Author: c02254
Description: Delete the element after the specified one
Input: SL_HEAD_S* pstList the pointer to the list head
SL_NODE_S* pstPrev pointer to the element before the one
to be deleted
Output: No output
Return: the pointer to the deleted element, NULL if no element is deleted
Caution: This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline SL_NODE_S* SL_DelAfter(IN SL_HEAD_S* pstList,
IN SL_NODE_S* pstPrev)
{
SL_NODE_S* pstNode;
if (NULL == pstPrev)
{
pstNode = SL_DelHead (pstList);
}
else
{
pstNode = pstPrev->pstNext;
if (NULL != pstNode)
{
pstPrev->pstNext = pstNode->pstNext;
}
}
return pstNode;
}
/* macro for walk the singly-linked list */
#define SL_FOREACH(pstList, pstNode) \
for ((pstNode) = SL_First(pstList); \
NULL != (pstNode); \
(pstNode) = SL_Next(pstNode))
#define SL_FOREACH_SAFE(pstList, pstNode, pstNext) \
for ((pstNode) = SL_First((pstList)); \
(NULL != (pstNode)) && ({(pstNext) = SL_Next(pstNode); BOOL_TRUE;}); \
(pstNode) = (pstNext))
#define SL_FOREACH_PREVPTR(pstList, pstNode, pstPrev) \
for ((pstNode) = SL_First(pstList), (pstPrev) = (SL_NODE_S *)NULL; \
NULL != (pstNode); \
(VOID)({(pstPrev) = (pstNode); (pstNode) = SL_Next(pstNode);}))
#define SL_ENTRY_FIRST(pstList, type, member) \
(SL_IsEmpty(pstList) ? NULL : SL_ENTRY(SL_First(pstList), type, member))
#define SL_ENTRY_NEXT(pstEntry, member) \
(NULL == (pstEntry) ? NULL : \
(NULL == SL_Next(&((pstEntry)->member))) ? NULL : \
SL_ENTRY(SL_Next(&((pstEntry)->member)), typeof(*(pstEntry)), member))
#define SL_FOREACH_ENTRY(pstList, pstEntry, member) \
for ((pstEntry) = SL_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member); \
NULL != (pstEntry); \
(pstEntry) = SL_ENTRY_NEXT(pstEntry, member))
#define SL_FOREACH_ENTRY_SAFE(pstList, pstEntry, pstNextEntry, member) \
for ((pstEntry) = SL_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member); \
(NULL != (pstEntry)) && \
({(pstNextEntry) = SL_ENTRY_NEXT(pstEntry, member); BOOL_TRUE;}); \
(pstEntry) = (pstNextEntry))
#define SL_FOREACH_ENTRY_PREVPTR(pstList, pstEntry, pstPrevEntry, member) \
for ((pstEntry) = SL_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member), \
(pstPrevEntry) = NULL; \
NULL != (pstEntry); \
(VOID)({(pstPrevEntry) = (pstEntry); \
(pstEntry) = SL_ENTRY_NEXT(pstEntry, member);}))
/*****************************************************************************
Func Name: SL_Del
Date Created: 2008/3/28
Author: c02254
Description: Delete an element from the list
Input: SL_HEAD_S* pstList the pointer to the list head
SL_NODE_S* pstNode the pointer to the element to be deleted
Output: No output
Return: No return
Caution: It takes the expense of O(n). If you have got a pointer to the
previous element, you'd better use SL_AddAfter whitch takes
the expense of O(1).
This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID SL_Del(IN SL_HEAD_S* pstList, IN SL_NODE_S* pstNode)
{
SL_NODE_S *pstCur, *pstPrev;
SL_FOREACH_PREVPTR (pstList, pstCur, pstPrev)
{
if (pstCur == pstNode)
{
(VOID) SL_DelAfter(pstList, pstPrev);
break;
}
}
return;
}
/*****************************************************************************
Func Name: SL_Append
Date Created: 2008/3/28
Author: c02254
Description: Append pstSrcList to pstDstList
Input: SL_HEAD_S* pstDstList the list to be appended to
SL_HEAD_S* pstSrcList the list to be append
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID SL_Append(IN SL_HEAD_S* pstDstList, INOUT SL_HEAD_S* pstSrcList)
{
SL_NODE_S *pstNode, *pstPrev;
if (BOOL_TRUE != SL_IsEmpty(pstSrcList))
{
SL_FOREACH_PREVPTR(pstDstList, pstNode, pstPrev)
{
; /* do nothing */
}
if (NULL == pstPrev)
{
pstDstList->pstFirst = SL_First(pstSrcList);
}
else
{
pstPrev->pstNext = SL_First(pstSrcList);
}
SL_Init(pstSrcList);
}
return;
}
/*****************************************************************************
Func Name: SL_FreeAll
Date Created: 2009/10/27
Author: Yang Yiquan
Description: Remove and free all nodes from SL list
Input: IN SL_HEAD_S *pstList
IN VOID (*pfFree)(VOID *)
Output:
Return: STATIC
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID SL_FreeAll(IN SL_HEAD_S *pstList, IN VOID (*pfFree)(VOID *))
{
SL_NODE_S *pstCurNode;
SL_NODE_S *pstNextNode;
/* Free all node from list */
SL_FOREACH_SAFE(pstList, pstCurNode, pstNextNode)
{
pfFree(pstCurNode);
}
SL_Init(pstList);
return;
}
/*
* Singly-linked Tail queue
*
* A singly-linked tail queue is headed by a pair of pointers, one to the
* head of the list and the other to the tail of the list. The elements are
* singly linked for minimum space and pointer manipulation overhead at the
* expense of O(n) removal for arbitrary elements. New elements can be added
* to the list after an existing element, at the head of the list, or at the
* end of the list. Elements being removed from the head of the tail queue
* should use the explicit macro for this purpose for optimum efficiency.
* A singly-linked tail queue may only be traversed in the forward direction.
* Singly-linked tail queues are ideal for applications with large datasets
* and few or no removals or for implementing a FIFO queue.
+---------------+ +---------------+
|user structure | |user structure |
+---------------+ +---------------+
| ...... | | ...... |
+---------------+ +---------------+
+-------------+ +-->|+-------------+| +-->|+-------------+|<-------+
| STQ_HEAD_S | | || STQ_NODE_S || | || STQ_NODE_S || |
+-------------+ | |+-------------+| | |+-------------+| |
| pstFirst |--+ || pstNext ||--+ || pstNext ||----+ |
+-------------+ |+-------------+| |+-------------+| -+- |
| pstLast |--+ +---------------+ +---------------+ |
+-------------+ | | ...... | | ...... | |
| +---------------+ +---------------+ |
+---------------------------------------------------+
*/
typedef struct tagSTQ_NODE
{
struct tagSTQ_NODE* pstNext; /* the next element */
} STQ_NODE_S;
#define STQ_ENTRY(ptr, type, member) (container_of(ptr, type, member))
typedef struct tagSTQ_HEAD
{
STQ_NODE_S *pstFirst; /* the first element */
STQ_NODE_S *pstLast; /* the last element */
} STQ_HEAD_S;
static inline VOID STQ_Init(IN STQ_HEAD_S* pstList);
static inline VOID STQ_NodeInit(IN STQ_NODE_S* pstNode);
static inline BOOL_T STQ_IsEmpty(IN STQ_HEAD_S* pstList);
static inline STQ_NODE_S* STQ_First(IN STQ_HEAD_S* pstList);
static inline STQ_NODE_S* STQ_Last(IN STQ_HEAD_S* pstList);
static inline STQ_NODE_S* STQ_Next(IN STQ_NODE_S* pstNode);
static inline VOID STQ_AddHead(IN STQ_HEAD_S* pstList, IN STQ_NODE_S* pstNode);
static inline STQ_NODE_S* STQ_DelHead(STQ_HEAD_S* pstList);
static inline VOID STQ_AddTail(STQ_HEAD_S* pstList, STQ_NODE_S* pstNode);
static inline VOID STQ_AddAfter(IN STQ_HEAD_S* pstList,
IN STQ_NODE_S* pstPrev,
IN STQ_NODE_S* pstInst);
static inline STQ_NODE_S* STQ_DelAfter(IN STQ_HEAD_S* pstList,
IN STQ_NODE_S* pstPrev);
static inline VOID STQ_Del(IN STQ_HEAD_S* pstList, IN STQ_NODE_S* pstNode);
static inline VOID STQ_Append(IN STQ_HEAD_S* pstDstList,
IN STQ_HEAD_S* pstSrcList);
static inline VOID STQ_FreeAll(IN STQ_HEAD_S *pstList, IN VOID (*pfFree)(VOID *));
/*****************************************************************************
Func Name: STQ_Init
Date Created: 2008/3/28
Author: c02254
Description: Initial a singly-linked tail queue head
Input: STQ_HEAD_S* pstList the singly-linked tail queue head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID STQ_Init(IN STQ_HEAD_S* pstList)
{
pstList->pstFirst = (STQ_NODE_S *)NULL;
pstList->pstLast = (STQ_NODE_S *)NULL;
return;
}
/*****************************************************************************
Func Name: STQ_NodeInit
Date Created: 2008/8/6
Author: c02254
Description: Initial a singly-linked tail queue node
Input: IN STQ_NODE_S* pstNode list node pointer
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID STQ_NodeInit(IN STQ_NODE_S* pstNode)
{
pstNode->pstNext = (STQ_NODE_S *)NULL;
}
/*****************************************************************************
Func Name: STQ_IsEmpty
Date Created: 2008/3/28
Author: c02254
Description: Whether the singly-linked tail queue is empty
Input: STQ_HEAD_S* pstList the pointer to the queue head
Output: No output
Return: BOOL_TRUE or BOOL_FLASE
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline BOOL_T STQ_IsEmpty(IN STQ_HEAD_S* pstList)
{
return (pstList->pstFirst == NULL);
}
/*****************************************************************************
Func Name: STQ_First
Date Created: 2008/3/28
Author: c02254
Description: Get the first element of a singly-linked tail queue
Input: STQ_HEAD_S* pstList the pointer to the queue head
Output: No output
Return: the pointer to first element of the singly-linked tail queue
NULL if the list is empty
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline STQ_NODE_S* STQ_First(IN STQ_HEAD_S* pstList)
{
return pstList->pstFirst;
}
/*****************************************************************************
Func Name: STQ_Last
Date Created: 2008/3/28
Author: c02254
Description: Get the last element of a singly-linked tail queue
Input: STQ_HEAD_S* pstList the pointer to the queue head
Output: No output
Return: the pointer to last element of the singly-linked tail queue
NULL if the list is empty
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline STQ_NODE_S* STQ_Last(IN STQ_HEAD_S* pstList)
{
return pstList->pstLast;
}
/*****************************************************************************
Func Name: STQ_Next
Date Created: 2008/3/28
Author: c02254
Description: Get the next element of current one
Input: STQ_NODE_S* pstNode the pointer to current element
Output: No output
Return: the pointer to next element of current element
NULL if the current element is the last one
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline STQ_NODE_S* STQ_Next(IN STQ_NODE_S* pstNode)
{
return pstNode->pstNext;
}
/*****************************************************************************
Func Name: STQ_AddHead
Date Created: 2008/3/28
Author: c02254
Description: Add an element to the head of the queue
Input: STQ_HEAD_S* pstList the pointer to the queue head
STQ_NODE_S* pstNode the pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID STQ_AddHead(IN STQ_HEAD_S* pstList, IN STQ_NODE_S* pstNode)
{
pstNode->pstNext = pstList->pstFirst;
pstList->pstFirst = pstNode;
if (NULL == pstList->pstLast)
{
pstList->pstLast = pstNode;
}
return;
}
/*****************************************************************************
Func Name: STQ_DelHead
Date Created: 2008/3/28
Author: c02254
Description: Delete the first element from the queue
Input: STQ_HEAD_S* pstList the pointer to the queue head
Output: No output
Return: the pointer to the deleted element, NULL if no element is deleted
Caution: This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline STQ_NODE_S* STQ_DelHead(STQ_HEAD_S* pstList)
{
STQ_NODE_S* pstNode = pstList->pstFirst;
if (NULL != pstNode)
{
pstList->pstFirst = pstNode->pstNext;
}
if (NULL == pstList->pstFirst)
{
pstList->pstLast = (STQ_NODE_S *)NULL;
}
return pstNode;
}
/*****************************************************************************
Func Name: STQ_AddTail
Date Created: 2008/3/28
Author: c02254
Description: Add an element to the tail of the queue
Input: STQ_HEAD_S* pstList the pointer to the queue tail
STQ_NODE_S* pstNode the pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID STQ_AddTail(STQ_HEAD_S* pstList, STQ_NODE_S* pstNode)
{
pstNode->pstNext = (STQ_NODE_S *)NULL;
if (NULL != pstList->pstLast)
{
pstList->pstLast->pstNext = pstNode;
pstList->pstLast = pstNode;
}
else
{
pstList->pstLast = pstNode;
pstList->pstFirst = pstNode;
}
return;
}
/*****************************************************************************
Func Name: STQ_AddAfter
Date Created: 2008/3/28
Author: c02254
Description: Add an element after another one
Input: STQ_HEAD_S* pstList the pointer to the queue head
STQ_NODE_S* pstPrev pointer to the previous element
STQ_NODE_S* pstInst pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID STQ_AddAfter(IN STQ_HEAD_S* pstList,
IN STQ_NODE_S* pstPrev,
IN STQ_NODE_S* pstInst)
{
if (NULL == pstPrev)
{
STQ_AddHead (pstList, pstInst);
}
else
{
pstInst->pstNext = pstPrev->pstNext;
pstPrev->pstNext = pstInst;
if (pstList->pstLast == pstPrev)
{
pstList->pstLast = pstInst;
}
}
return;
}
/*****************************************************************************
Func Name: STQ_DelAfter
Date Created: 2008/3/28
Author: c02254
Description: Delete the element after the specified one
Input: STQ_NODE_S* pstPrev pointer to the element before the one
to be deleted
Output: No output
Return: the pointer to the deleted element, NULL if no element is deleted
Caution: This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline STQ_NODE_S* STQ_DelAfter(IN STQ_HEAD_S* pstList,
IN STQ_NODE_S* pstPrev)
{
STQ_NODE_S* pstNode;
if (NULL == pstPrev)
{
pstNode = STQ_DelHead (pstList);
}
else
{
pstNode = pstPrev->pstNext;
if (NULL != pstNode)
{
pstPrev->pstNext = pstNode->pstNext;
}
if (pstList->pstLast == pstNode)
{
pstList->pstLast = pstPrev;
}
}
return pstNode;
}
/* macro for walk the singly-linked tail queue */
#define STQ_FOREACH(pstList, pstNode) \
for((pstNode) = STQ_First(pstList); \
NULL != (pstNode); \
(pstNode) = STQ_Next(pstNode))
#define STQ_FOREACH_SAFE(pstList, pstNode, pstNext) \
for ((pstNode) = STQ_First(pstList); \
(NULL != (pstNode)) && ({(pstNext) = STQ_Next(pstNode); BOOL_TRUE;}); \
(pstNode) = (pstNext))
#define STQ_FOREACH_PREVPTR(pstList, pstNode, pstPrev) \
for ((pstNode) = STQ_First(pstList), (pstPrev) = (STQ_NODE_S *)NULL; \
NULL != (pstNode); \
(VOID)({(pstPrev) = (pstNode); (pstNode) = STQ_Next(pstNode);}))
#define STQ_ENTRY_FIRST(pstList, type, member) \
(STQ_IsEmpty(pstList) ? NULL : STQ_ENTRY(STQ_First(pstList), type, member))
#define STQ_ENTRY_LAST(pstList, type, member) \
(STQ_IsEmpty(pstList) ? NULL : STQ_ENTRY(STQ_Last(pstList), type, member))
#define STQ_ENTRY_NEXT(pstEntry, member) \
(NULL == (pstEntry) ? NULL : \
(NULL == STQ_Next(&((pstEntry)->member)) ? NULL : \
STQ_ENTRY(STQ_Next(&((pstEntry)->member)), typeof(*(pstEntry)), member)))
#define STQ_FOREACH_ENTRY(pstList, pstEntry, member) \
for ((pstEntry) = STQ_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member); \
NULL != (pstEntry); \
(pstEntry) = STQ_ENTRY_NEXT(pstEntry, member))
#define STQ_FOREACH_ENTRY_SAFE(pstList, pstEntry, pstNextEntry, member) \
for ((pstEntry) = STQ_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member); \
(NULL != (pstEntry)) && \
({(pstNextEntry) = STQ_ENTRY_NEXT(pstEntry, member); BOOL_TRUE;}); \
(pstEntry) = (pstNextEntry))
#define STQ_FOREACH_ENTRY_PREVPTR(pstList, pstEntry, pstPrevEntry, member) \
for ((pstEntry) = STQ_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member), \
(pstPrevEntry) = NULL; \
NULL != (pstEntry); \
(VOID)({(pstPrevEntry) = (pstEntry); \
(pstEntry) = STQ_ENTRY_NEXT(pstEntry, member);}))
/*****************************************************************************
Func Name: STQ_Del
Date Created: 2008/3/28
Author: c02254
Description: Delete an element from the tail queue
Input: STQ_HEAD_S* pstList the pointer to the queue head
STQ_NODE_S* pstNode the pointer to the element to be deleted
Output: No output
Return: No return
Caution: It takes the expense of O(n). If you have got a pointer to the
previous element, you'd better use STQ_DelAfter whitch takes
the expense of O(1).
This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID STQ_Del(IN STQ_HEAD_S* pstList, IN STQ_NODE_S* pstNode)
{
STQ_NODE_S *pstPrev, *pstCur;
STQ_FOREACH_PREVPTR (pstList, pstCur, pstPrev)
{
if (pstCur == pstNode)
{
(VOID)STQ_DelAfter (pstList, pstPrev);
break;
}
}
return;
}
/*****************************************************************************
Func Name: STQ_Append
Date Created: 2008/3/28
Author: c02254
Description: Append pstSrcList to pstDstList
Input: STQ_HEAD_S* pstDstList the list to be appended to
STQ_HEAD_S* pstSrcList the list to be append
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID STQ_Append(IN STQ_HEAD_S* pstDstList,
INOUT STQ_HEAD_S* pstSrcList)
{
if (BOOL_TRUE != STQ_IsEmpty(pstSrcList))
{
if (NULL != pstDstList->pstLast)
{
pstDstList->pstLast->pstNext = STQ_First(pstSrcList);
}
else
{
pstDstList->pstFirst = STQ_First(pstSrcList);
}
pstDstList->pstLast = STQ_Last(pstSrcList);
STQ_Init(pstSrcList);
}
return;
}
/*****************************************************************************
Func Name: STQ_FreeAll
Date Created: 2009/10/27
Author: Yang Yiquan
Description: Remove and free all nodes from STQ list
Input: IN STQ_HEAD_S *pstList
IN VOID (*pfFree)(VOID *)
Output:
Return: STATIC
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID STQ_FreeAll(IN STQ_HEAD_S *pstList, IN VOID (*pfFree)(VOID *))
{
STQ_NODE_S *pstCurNode;
STQ_NODE_S *pstNextNode;
/* Free all node from list */
STQ_FOREACH_SAFE(pstList, pstCurNode, pstNextNode)
{
pfFree(pstCurNode);
}
STQ_Init(pstList);
return;
}
/*
* Doubly-linked List
*
* A doubly-linked list is headed by a single forward pointer (or an array of
* forward pointers for a hash table header). The elements are doubly linked
* so that an arbitrary element can be removed without a need to traverse the
* list. New elements can be added to the list before or after an existing
* element or at the head of the list. A doubly-linked list may only be
* traversed in the forward direction.
+--------------+ +--------------+
|user structure| |user structure|
+--------------+ +--------------+
| ...... | | ...... |
+--------------+ +--------------+
+------------+ +--->|+------------+| +-->|+------------+|
| DL_HEAD_S | | || DL_NODE_S || | || DL_NODE_S ||
+------------+ | +->|+------------+| | |+------------+|
+->| pstFirst |--+ | || pstNext ||--+ || pstNext ||----+
| +------------+ | |+------------+| |+------------+| -+-
+--------------------C--|| ppstPre || +---|| ppstPre ||
| |+------------+| | |+------------+|
| +--------------+ | +--------------+
| | ...... | | | ...... |
| +--------------+ | +--------------+
+--------------------+
*/
typedef struct tagDL_NODE
{
struct tagDL_NODE* pstNext; /* the next element */
struct tagDL_NODE** ppstPre; /* the address of previous element's pstNext */
} DL_NODE_S;
#define DL_ENTRY(ptr, type, member) (container_of(ptr, type, member))
#define DL_NODE_FROM_PPRE(ppstPre) (container_of(ppstPre, DL_NODE_S, pstNext))
#define DL_ENTRY_FROM_PPRE(ppstPre, type, member) \
DL_ENTRY(DL_NODE_FROM_PPRE(ppstPre), type, member)
typedef struct tagDL_HEAD
{
DL_NODE_S* pstFirst; /* the first element */
} DL_HEAD_S;
static inline VOID DL_Init(IN DL_HEAD_S* pstList);
static inline VOID DL_NodeInit(IN DL_NODE_S* pstNode);
static inline BOOL_T DL_IsEmpty(IN DL_HEAD_S* pstList);
static inline DL_NODE_S* DL_First(IN DL_HEAD_S* pstList);
static inline DL_NODE_S* DL_Next(IN DL_NODE_S* pstNode);
static inline DL_NODE_S* DL_Prev(IN DL_NODE_S* pstNode);
static inline VOID DL_Del(IN DL_NODE_S* pstNode);
static inline VOID DL_AddHead(IN DL_HEAD_S* pstList, IN DL_NODE_S* pstNode);
static inline DL_NODE_S* DL_DelHead(IN DL_HEAD_S* pstList);
static inline VOID DL_AddAfter(IN DL_NODE_S* pstPrev, IN DL_NODE_S* pstInst);
static inline VOID DL_AddAfterPtr (IN DL_NODE_S **ppstPre, IN DL_NODE_S *pstInst);
static inline VOID DL_AddBefore(IN DL_NODE_S* pstNext, IN DL_NODE_S* pstInst);
static inline VOID DL_Append(IN DL_HEAD_S* pstDstList, IN DL_HEAD_S* pstSrcList);
static inline VOID DL_FreeAll(IN DL_HEAD_S *pstList, IN VOID (*pfFree)(VOID *));
/*****************************************************************************
Func Name: DL_Init
Date Created: 2008/3/28
Author: c02254
Description: Initial a doubly-linked list head
Input: DL_HEAD_S* pstList the doubly-linked list head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DL_Init(IN DL_HEAD_S* pstList)
{
pstList->pstFirst = (DL_NODE_S*)NULL;
return;
}
/*****************************************************************************
Func Name: DL_NodeInit
Date Created: 2008/8/6
Author: c02254
Description: Initialize a doubly-linked list node
Input: IN DL_NODE_S* pstNode list node pointer
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DL_NodeInit(IN DL_NODE_S* pstNode)
{
pstNode->pstNext = (DL_NODE_S*)NULL;
pstNode->ppstPre = (DL_NODE_S**)NULL;
}
/*****************************************************************************
Func Name: DL_IsEmpty
Date Created: 2008/3/28
Author: c02254
Description: Whether the singly-linked list is empty
Input: DL_HEAD_S* pstList the pointer to the list head
Output: No output
Return: BOOL_TRUE or BOOL_FLASE
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline BOOL_T DL_IsEmpty(IN DL_HEAD_S* pstList)
{
return (pstList->pstFirst == NULL);
}
/*****************************************************************************
Func Name: DL_First
Date Created: 2008/3/28
Author: c02254
Description: Get the first element of a doubly-linked list
Input: DL_HEAD_S* pstList the pointer to the list head
Output: No output
Return: the pointer to first element of the doubly-linked list
NULL if the list is empty
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline DL_NODE_S* DL_First(IN DL_HEAD_S* pstList)
{
return (pstList->pstFirst);
}
/*****************************************************************************
Func Name: DL_Next
Date Created: 2008/3/28
Author: c02254
Description: Get the next element of current one
Input: DL_NODE_S* pstNode the pointer to current element
Output: No output
Return: the pointer to next element of current element
NULL if the current element is the last one
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline DL_NODE_S* DL_Next(IN DL_NODE_S* pstNode)
{
return pstNode->pstNext;
}
/*****************************************************************************
Func Name: DL_Prev
Date Created: 2008/3/28
Author: c02254
Description: Get the previous element of current one
Input: DL_NODE_S* pstNode the pointer to current element
Output: No output
Return: the pointer to previous element of current element
NULL if the current element is the first one
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline DL_NODE_S* DL_Prev(IN DL_NODE_S* pstNode)
{
return DL_NODE_FROM_PPRE(pstNode->ppstPre);
}
/*****************************************************************************
Func Name: DL_Del
Date Created: 2008/3/28
Author: c02254
Description: Delete an element from the list
Input: DL_NODE_S* pstNode the pointer to the element to be deleted
Output: No output
Return: No return
Caution: It takes the expense of O(1).
This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DL_Del(IN DL_NODE_S* pstNode)
{
if (NULL != pstNode->ppstPre)
{
*pstNode->ppstPre = pstNode->pstNext;
}
if (NULL != pstNode->pstNext)
{
pstNode->pstNext->ppstPre = pstNode->ppstPre;
}
return;
}
/*****************************************************************************
Func Name: DL_AddHead
Date Created: 2008/3/28
Author: c02254
Description: Add an element to the head of the list
Input: DL_HEAD_S* pstList the pointer to the list head
DL_NODE_S* pstNode the pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DL_AddHead(IN DL_HEAD_S* pstList, IN DL_NODE_S* pstNode)
{
pstNode->ppstPre = &pstList->pstFirst;
pstNode->pstNext = pstList->pstFirst;
if (NULL != pstNode->pstNext)
{
pstNode->pstNext->ppstPre = &pstNode->pstNext;
}
pstList->pstFirst = pstNode;
return;
}
/*****************************************************************************
Func Name: DL_DelHead
Date Created: 2008/3/28
Author: c02254
Description: Delete the first element from the list
Input: DL_HEAD_S* pstList the pointer to the list head
Output: No output
Return: the pointer to the deleted element, NULL if no element is deleted
Caution: This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline DL_NODE_S* DL_DelHead(IN DL_HEAD_S* pstList)
{
DL_NODE_S* pstNode = DL_First(pstList);
if (NULL != pstNode)
{
DL_Del (pstNode);
}
return pstNode;
}
/*****************************************************************************
Func Name: DL_AddAfter
Date Created: 2008/3/28
Author: c02254
Description: Add an element after another one
Input: DL_NODE_S* pstPrev pointer to the previous element
DL_NODE_S* pstInst pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DL_AddAfter(IN DL_NODE_S* pstPrev, IN DL_NODE_S* pstInst)
{
pstInst->ppstPre = &pstPrev->pstNext;
pstInst->pstNext = pstPrev->pstNext;
pstPrev->pstNext = pstInst;
if (NULL != pstInst->pstNext)
{
pstInst->pstNext->ppstPre = &pstInst->pstNext;
}
return;
}
/*****************************************************************************
Func Name: DL_AddAfterPtr
Date Created: 2008/8/6
Author: c02254
Description: Add an element after another one
Input: DL_NODE_S** ppstPre address of the previous element's pstNext
DL_NODE_S* pstInst pointer to the element to be added
Output: No output
Return: No return
Caution: ppstPre is not the address of a pointer to previous element's
but is the address of previous element's pstNext.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DL_AddAfterPtr (IN DL_NODE_S **ppstPre, IN DL_NODE_S *pstInst)
{
pstInst->ppstPre = ppstPre;
pstInst->pstNext = *ppstPre;
*ppstPre = pstInst;
if (NULL != pstInst->pstNext)
{
pstInst->pstNext->ppstPre = &pstInst->pstNext;
}
return;
}
/*****************************************************************************
Func Name: DL_AddBefore
Date Created: 2008/3/28
Author: c02254
Description: Add an element after another one
Input: DL_HEAD_S* pstList the pointer to the list head
DL_NODE_S* pstPrev pointer to the previous element
DL_NODE_S* pstInst pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DL_AddBefore(IN DL_NODE_S* pstNext, IN DL_NODE_S* pstInst)
{
pstInst->ppstPre = pstNext->ppstPre;
pstInst->pstNext = pstNext;
if (NULL != pstInst->ppstPre)
{
*pstInst->ppstPre = pstInst;
}
pstInst->pstNext->ppstPre = &pstInst->pstNext;
return;
}
/* macro for walk the doubly-linked list */
#define DL_FOREACH(pstList, pstNode) \
for ((pstNode) = DL_First((pstList)); \
NULL != (pstNode); \
(pstNode) = DL_Next(pstNode))
#define DL_FOREACH_SAFE(pstList, pstNode, pstNext) \
for ((pstNode) = DL_First((pstList)); \
(NULL != (pstNode)) && ({(pstNext) = DL_Next(pstNode); BOOL_TRUE;}); \
(pstNode) = (pstNext))
#define DL_FOREACH_PREVPTR(pstList, pstNode, ppstPre) \
for ((pstNode) = DL_First(pstList), (ppstPre) = &((pstList)->pstFirst); \
NULL != (pstNode); \
(VOID)({(ppstPre) = &((pstNode)->pstNext); \
(pstNode) = DL_Next(pstNode);}))
#define DL_ENTRY_FIRST(pstList, type, member) \
(DL_IsEmpty(pstList) ? NULL : DL_ENTRY(DL_First(pstList), type, member))
#define DL_ENTRY_NEXT(pstEntry, member) \
(NULL == (pstEntry) ? NULL : \
(NULL == DL_Next(&((pstEntry)->member)) ? NULL : \
DL_ENTRY(DL_Next(&((pstEntry)->member)), typeof(*(pstEntry)), member)))
#define DL_ENTRY_PREV(pstEntry, member) \
(NULL == (pstEntry) ? NULL : \
(NULL == DL_Prev(&((pstEntry)->member)) ? NULL : \
DL_ENTRY(DL_Prev(&((pstEntry)->member)), typeof(*(pstEntry)), member)))
#define DL_FOREACH_ENTRY(pstList, pstEntry, member) \
for ((pstEntry) = DL_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member); \
NULL != (pstEntry); \
(pstEntry) = DL_ENTRY_NEXT(pstEntry, member))
#define DL_FOREACH_ENTRY_SAFE(pstList, pstEntry, pstNextEntry, member) \
for ((pstEntry) = DL_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member); \
(NULL != (pstEntry)) && \
({(pstNextEntry) = DL_ENTRY_NEXT(pstEntry, member); BOOL_TRUE;}); \
(pstEntry) = (pstNextEntry))
#define DL_FOREACH_ENTRY_PREVPTR(pstList, pstEntry, ppstPre, member) \
for ((pstEntry) = DL_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member), \
(ppstPre) = &((pstList)->pstFirst); \
NULL != (pstEntry); \
(VOID)({(ppstPre) = &((pstEntry)->member.pstNext); \
(pstEntry) = DL_ENTRY_NEXT(pstEntry, member);}))
/*****************************************************************************
Func Name: DL_Append
Date Created: 2008/3/28
Author: c02254
Description: Append pstSrcList to pstDstList
Input: DL_HEAD_S* pstDstList the list to be appended to
DL_HEAD_S* pstSrcList the list to be append
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DL_Append(IN DL_HEAD_S* pstDstList, INOUT DL_HEAD_S* pstSrcList)
{
DL_NODE_S *pstNode, **ppstPre;
if (BOOL_TRUE != DL_IsEmpty (pstSrcList))
{
/* seek pstPrev to the tail of pstDstList */
DL_FOREACH_PREVPTR (pstDstList, pstNode, ppstPre)
{
; /* do nothing */
}
*ppstPre = pstSrcList->pstFirst;
pstSrcList->pstFirst->ppstPre = ppstPre;
DL_Init(pstSrcList);
}
return;
}
/*****************************************************************************
Func Name: DL_FreeAll
Date Created: 2009/10/27
Author: Yang Yiquan
Description: Remove and free all nodes from DL list
Input: IN DL_HEAD_S *pstList
IN VOID (*pfFree)(VOID *)
Output:
Return: STATIC
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DL_FreeAll(IN DL_HEAD_S *pstList, IN VOID (*pfFree)(VOID *))
{
DL_NODE_S *pstCurNode;
DL_NODE_S *pstNextNode;
/* Free all node from list */
DL_FOREACH_SAFE(pstList, pstCurNode, pstNextNode)
{
pfFree(pstCurNode);
}
DL_Init(pstList);
return;
}
/*
* Doubly-linked Tail queue
*
* A doubly-linked tail queue is headed by a pair of pointers, one to the head
* of the list and the other to the tail of the list. The elements are doubly
* linked so that an arbitrary element can be removed without a need to
* traverse the list. New elements can be added to the list before or after
* an existing element, at the head of the list, or at the end of the list.
* A doubly-linked tail queue may be traversed in either direction.
+-------------------------------------------------------------------------+
| +---------------+ +---------------+ |
| |user structure | |user structure | |
| +---------------+ +---------------+ +---------------+ |
| | DTQ_HEAD_S | | ...... | | ...... | |
| +---------------+ +---------------+ +---------------+ |
| +->|+-------------+|<-+ +->|+-------------+|<-+ +->|+-------------+|<-+
| | || DTQ_NODE_S || | | || DTQ_NODE_S || | | || DTQ_NODE_S ||
| | |+-------------+| | | |+-------------+| | | |+-------------+|
+-C--|| pstPrev || +--C--|| pstPrev || +--C--|| pstPrev ||
| |+-------------+| | |+-------------+| | |+-------------+|
| || pstNext ||-----+ || pstNext ||-----+ || pstNext ||--+
| |+-------------+| |+-------------+| |+-------------+| |
| +---------------+ +---------------+ +---------------+ |
| | ...... | | ...... | |
| +---------------+ +---------------+ |
|-----------------------------------------------------------------------+
*/
typedef struct tagDTQ_NODE
{
struct tagDTQ_NODE* pstPrev; /* the previous element */
struct tagDTQ_NODE* pstNext; /* the next element */
} DTQ_NODE_S;
#define DTQ_ENTRY(ptr, type, member) (container_of(ptr, type, member))
typedef struct tagDTQ_HEAD
{
DTQ_NODE_S stHead; /* stHead.pstNext is the head of list
stHead.pstPrev is the tail of list */
} DTQ_HEAD_S;
static inline VOID DTQ_Init(IN DTQ_HEAD_S* pstList);
static inline VOID DTQ_NodeInit(IN DTQ_NODE_S* pstNode);
static inline BOOL_T DTQ_IsEmpty(IN DTQ_HEAD_S* pstList);
static inline DTQ_NODE_S* DTQ_First(IN DTQ_HEAD_S* pstList);
static inline DTQ_NODE_S* DTQ_Last(IN DTQ_HEAD_S* pstList);
static inline BOOL_T DTQ_IsEndOfQ(IN DTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode);
static inline DTQ_NODE_S* DTQ_Prev(IN DTQ_NODE_S* pstNode);
static inline DTQ_NODE_S* DTQ_Next(IN DTQ_NODE_S* pstNode);
static inline VOID DTQ_AddAfter(IN DTQ_NODE_S* pstPrev, IN DTQ_NODE_S* pstInst);
static inline VOID DTQ_AddBefore(IN DTQ_NODE_S* pstNext, IN DTQ_NODE_S* pstInst);
static inline VOID DTQ_Del(IN DTQ_NODE_S* pstNode);
static inline VOID DTQ_AddHead(IN DTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode);
static inline DTQ_NODE_S* DTQ_DelHead(IN DTQ_HEAD_S* pstList);
static inline VOID DTQ_AddTail(IN DTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode);
static inline DTQ_NODE_S* DTQ_DelTail(IN DTQ_HEAD_S* pstList);
static inline VOID DTQ_Append(IN DTQ_HEAD_S* pstDstList, IN DTQ_HEAD_S* pstSrcList);
static inline VOID DTQ_FreeAll(IN DTQ_HEAD_S *pstList, IN VOID (*pfFree)(VOID *));
/*****************************************************************************
Func Name: DTQ_Init
Date Created: 2008/3/28
Author: c02254
Description: Initial a doubly-linked tail queue head
Input: STQ_HEAD_S* pstList the doubly-linked tail queue head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DTQ_Init(IN DTQ_HEAD_S* pstList)
{
pstList->stHead.pstNext = &pstList->stHead;
pstList->stHead.pstPrev = &pstList->stHead;
return;
}
/*****************************************************************************
Func Name: DTQ_NodeInit
Date Created: 2008/8/6
Author: c02254
Description: Initialize a doubly-linked tail queue node
Input: IN DTQ_NODE_S* pstNode pointer to node
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DTQ_NodeInit(IN DTQ_NODE_S* pstNode)
{
pstNode->pstNext = (DTQ_NODE_S*)NULL;
pstNode->pstPrev = (DTQ_NODE_S*)NULL;
return;
}
/*****************************************************************************
Func Name: DTQ_IsEmpty
Date Created: 2008/3/28
Author: c02254
Description: Whether the doubly-linked tail queue is empty
Input: STQ_HEAD_S* pstList the pointer to the queue head
Output: No output
Return: BOOL_TRUE or BOOL_FLASE
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline BOOL_T DTQ_IsEmpty(IN DTQ_HEAD_S* pstList)
{
return (pstList->stHead.pstNext == &pstList->stHead);
}
/*****************************************************************************
Func Name: DTQ_First
Date Created: 2008/3/28
Author: c02254
Description: Get the first element of a doubly-linked tail queue
Input: DTQ_HEAD_S* pstList the pointer to the queue head
Output: No output
Return: the pointer to first element of the doubly-linked tail queue
NULL if the list is empty
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline DTQ_NODE_S* DTQ_First(IN DTQ_HEAD_S* pstList)
{
if (DTQ_IsEmpty(pstList))
{
return (DTQ_NODE_S*)NULL;
}
return (pstList->stHead.pstNext);
}
/*****************************************************************************
Func Name: DTQ_Last
Date Created: 2008/3/28
Author: c02254
Description: Get the last element of a doubly-linked tail queue
Input: DTQ_HEAD_S* pstList the pointer to the queue head
Output: No output
Return: the pointer to last element of the doubly-linked tail queue
NULL if the list is empty
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline DTQ_NODE_S* DTQ_Last(IN DTQ_HEAD_S* pstList)
{
if (DTQ_IsEmpty(pstList))
{
return (DTQ_NODE_S*)NULL;
}
return (pstList->stHead.pstPrev);
}
/*****************************************************************************
Func Name: DTQ_IsEndOfQ
Date Created: 2008/8/6
Author: c02254
Description: Wether the node is the end of the queue
Input: DTQ_HEAD_S* pstList the pointer to the queue head
DTQ_NODE_S* pstNode the pointer to the node
Output: No output
Return: BOOL_TURE if is end of the queue, BOOL_FALSE is not
Caution: DTQ is a circle doubly link list, we can not use NULL to
decide wether reaching the end of list
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline BOOL_T DTQ_IsEndOfQ(IN DTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode)
{
if (DTQ_IsEmpty(pstList))
{
return BOOL_TRUE;
}
if (NULL == pstNode)
{
return BOOL_TRUE;
}
return (pstNode == &pstList->stHead);
}
/*****************************************************************************
Func Name: DTQ_Prev
Date Created: 2008/3/28
Author: c02254
Description: Get the previous element of current one
Input: DTQ_NODE_S* pstNode the pointer to current element
Output: No output
Return: the pointer to previous element of current element
NULL if the current element is the last one
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline DTQ_NODE_S* DTQ_Prev(IN DTQ_NODE_S* pstNode)
{
return (pstNode->pstPrev);
}
/*****************************************************************************
Func Name: DTQ_Next
Date Created: 2008/3/28
Author: c02254
Description: Get the next element of current one
Input: DTQ_NODE_S* pstNode the pointer to current element
Output: No output
Return: the pointer to next element of current element
NULL if the current element is the last one
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline DTQ_NODE_S* DTQ_Next(IN DTQ_NODE_S* pstNode)
{
return (pstNode->pstNext);
}
/*****************************************************************************
Func Name: DTQ_AddAfter
Date Created: 2008/3/28
Author: c02254
Description: Add an element after another one
Input: DTQ_NODE_S* pstPrev pointer to the previous element
DTQ_NODE_S* pstInst pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DTQ_AddAfter(IN DTQ_NODE_S* pstPrev, IN DTQ_NODE_S* pstInst)
{
pstInst->pstPrev = pstPrev;
pstInst->pstNext = pstPrev->pstNext;
pstPrev->pstNext = pstInst;
pstInst->pstNext->pstPrev = pstInst;
return;
}
/*****************************************************************************
Func Name: DTQ_AddBefore
Date Created: 2008/3/28
Author: c02254
Description: Add an element before another one
Input: DTQ_NODE_S* pstNext pointer to the next element
DTQ_NODE_S* pstInst pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DTQ_AddBefore(IN DTQ_NODE_S* pstNext, IN DTQ_NODE_S* pstInst)
{
pstInst->pstPrev = pstNext->pstPrev;
pstInst->pstNext = pstNext;
pstInst->pstPrev->pstNext = pstInst;
pstInst->pstNext->pstPrev = pstInst;
return;
}
/*****************************************************************************
Func Name: DTQ_Del
Date Created: 2008/3/28
Author: c02254
Description: Delete an element from the tail queue
Input: DTQ_NODE_S* pstNode the pointer to the element to be deleted
Output: No output
Return: No return
Caution: This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DTQ_Del(IN DTQ_NODE_S* pstNode)
{
pstNode->pstPrev->pstNext = pstNode->pstNext;
pstNode->pstNext->pstPrev = pstNode->pstPrev;
return;
}
/*****************************************************************************
Func Name: DTQ_AddHead
Date Created: 2008/3/28
Author: c02254
Description: Add an element to the head of the queue
Input: DTQ_HEAD_S* pstList the pointer to the queue head
DTQ_NODE_S* pstNode the pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DTQ_AddHead(IN DTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode)
{
DTQ_AddAfter (&pstList->stHead, pstNode);
return;
}
/*****************************************************************************
Func Name: DTQ_DelHead
Date Created: 2008/3/28
Author: c02254
Description: Delete the first element from the queue
Input: DTQ_HEAD_S* pstList the pointer to the queue head
Output: No output
Return: the pointer to the deleted element, NULL if no element is deleted
Caution: This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline DTQ_NODE_S* DTQ_DelHead(IN DTQ_HEAD_S* pstList)
{
DTQ_NODE_S* pstNode = DTQ_First(pstList);
if (DTQ_IsEndOfQ(pstList, pstNode))
{
pstNode = (DTQ_NODE_S*)NULL;
}
else
{
DTQ_Del (pstNode);
}
return pstNode;
}
/*****************************************************************************
Func Name: DTQ_AddTail
Date Created: 2008/3/28
Author: c02254
Description: Add an element to the tail of the queue
Input: DTQ_HEAD_S* pstList the pointer to the queue head
DTQ_NODE_S* pstNode the pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DTQ_AddTail(IN DTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode)
{
DTQ_AddBefore (&pstList->stHead, pstNode);
return;
}
/*****************************************************************************
Func Name: DTQ_DelTail
Date Created: 2008/3/28
Author: c02254
Description: Delete the last element from the queue
Input: DTQ_HEAD_S* pstList the pointer to the queue head
Output: No output
Return: the pointer to the deleted element, NULL if no element is deleted
Caution: This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline DTQ_NODE_S* DTQ_DelTail(IN DTQ_HEAD_S* pstList)
{
DTQ_NODE_S* pstNode = DTQ_Last (pstList);
if (DTQ_IsEndOfQ(pstList, pstNode))
{
pstNode = (DTQ_NODE_S*)NULL;
}
else
{
DTQ_Del (pstNode);
}
return pstNode;
}
/* macro for walk the doubly-linked tail queue */
#define DTQ_FOREACH(pstList, pstNode) \
for ((pstNode) = DTQ_First(pstList); \
(BOOL_TRUE != DTQ_IsEndOfQ(pstList, pstNode)); \
(pstNode) = DTQ_Next(pstNode))
#define DTQ_FOREACH_SAFE(pstList, pstNode, pstNext) \
for ((pstNode) = DTQ_First((pstList)); \
(BOOL_TRUE != DTQ_IsEndOfQ(pstList, pstNode)) && \
({(pstNext) = DTQ_Next(pstNode); BOOL_TRUE;}); \
(pstNode) = (pstNext))
#define DTQ_FOREACH_REVERSE(pstList, pstNode) \
for ((pstNode) = DTQ_Last(pstList); \
(BOOL_TRUE != DTQ_IsEndOfQ(pstList, pstNode)); \
(pstNode) = DTQ_Prev(pstNode))
#define DTQ_FOREACH_REVERSE_SAFE(pstList, pstNode, pstPrev) \
for ((pstNode) = DTQ_Last(pstList); \
(BOOL_TRUE != DTQ_IsEndOfQ(pstList, pstNode)) && \
({(pstPrev) = DTQ_Prev(pstNode); BOOL_TRUE;}); \
(pstNode) = (pstPrev))
#define DTQ_ENTRY_FIRST(pstList, type, member) \
(DTQ_IsEmpty(pstList) ? NULL : DTQ_ENTRY(DTQ_First(pstList), type, member))
#define DTQ_ENTRY_LAST(pstList, type, member) \
(DTQ_IsEmpty(pstList) ? NULL : DTQ_ENTRY(DTQ_Last(pstList), type, member))
#define DTQ_ENTRY_NEXT(pstList, pstEntry, member) \
(DTQ_IsEndOfQ(pstList, (NULL == (pstEntry) ? NULL : DTQ_Next(&((pstEntry)->member)))) ? \
NULL : \
DTQ_ENTRY(DTQ_Next(&((pstEntry)->member)), typeof(*(pstEntry)), member))
#define DTQ_ENTRY_PREV(pstList, pstEntry, member) \
(DTQ_IsEndOfQ(pstList, (NULL == (pstEntry) ? NULL : DTQ_Prev(&((pstEntry)->member)))) ? \
NULL : \
DTQ_ENTRY(DTQ_Prev(&((pstEntry)->member)), typeof(*(pstEntry)), member))
#define DTQ_FOREACH_ENTRY(pstList, pstEntry, member) \
for ((pstEntry) = DTQ_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member); \
NULL != (pstEntry); \
(pstEntry) = DTQ_ENTRY_NEXT(pstList, pstEntry, member))
#define DTQ_FOREACH_ENTRY_SAFE(pstList, pstEntry, pstNextEntry, member) \
for ((pstEntry) = DTQ_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member); \
(NULL != (pstEntry)) && \
({(pstNextEntry) = DTQ_ENTRY_NEXT(pstList, pstEntry, member); BOOL_TRUE;}); \
(pstEntry) = (pstNextEntry))
#define DTQ_FOREACH_ENTRY_REVERSE(pstList, pstEntry, member) \
for ((pstEntry) = DTQ_ENTRY_LAST(pstList, typeof(*(pstEntry)), member); \
NULL != (pstEntry); \
(pstEntry) = DTQ_ENTRY_PREV(pstList, pstEntry, member))
#define DTQ_FOREACH_ENTRY_REVERSE_SAFE(pstList, pstEntry, pstPrevEntry, member) \
for ((pstEntry) = DTQ_ENTRY_LAST(pstList, typeof(*(pstEntry)), member); \
(NULL != (pstEntry)) && \
({(pstPrevEntry) = DTQ_ENTRY_PREV(pstList, pstEntry, member); BOOL_TRUE;}); \
(pstEntry) = (pstPrevEntry))
/*****************************************************************************
Func Name: DTQ_Append
Date Created: 2008/3/28
Author: c02254
Description: Append pstSrcList to pstDstList
Input: DTQ_HEAD_S* pstDstList the list to be appended to
DTQ_HEAD_S* pstSrcList the list to be append
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DTQ_Append(IN DTQ_HEAD_S* pstDstList, INOUT DTQ_HEAD_S* pstSrcList)
{
if (BOOL_TRUE != DTQ_IsEmpty (pstSrcList))
{
pstSrcList->stHead.pstNext->pstPrev = pstDstList->stHead.pstPrev;
pstSrcList->stHead.pstPrev->pstNext = pstDstList->stHead.pstPrev->pstNext;
pstDstList->stHead.pstPrev->pstNext = pstSrcList->stHead.pstNext;
pstDstList->stHead.pstPrev = pstSrcList->stHead.pstPrev;
DTQ_Init(pstSrcList);
}
return;
}
/*****************************************************************************
Func Name: DTQ_FreeAll
Date Created: 2009/10/27
Author: Yang Yiquan
Description: Remove and free all nodes from DTQ list
Input: IN DTQ_HEAD_S *pstList
IN VOID (*pfFree)(VOID *)
Output:
Return: STATIC
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID DTQ_FreeAll(IN DTQ_HEAD_S *pstList, IN VOID (*pfFree)(VOID *))
{
DTQ_NODE_S *pstCurNode;
DTQ_NODE_S *pstNextNode;
/* Free all node from list */
DTQ_FOREACH_SAFE(pstList, pstCurNode, pstNextNode)
{
pfFree(pstCurNode);
}
DTQ_Init(pstList);
return;
}
/* Rcu supporting, used in kernel only */
#ifdef __KERNEL__
#include <sys/rcu.h>
static inline VOID SL_AddHead_Rcu(IN SL_HEAD_S* pstList, IN SL_NODE_S* pstNode)
{
pstNode->pstNext = pstList->pstFirst;
smp_wmb();
pstList->pstFirst = pstNode;
return;
}
static inline VOID SL_AddAfter_Rcu(IN SL_HEAD_S* pstList,
IN SL_NODE_S* pstPrev,
IN SL_NODE_S* pstInst)
{
if (NULL == pstPrev)
{
SL_AddHead (pstList, pstInst);
}
else
{
pstInst->pstNext = pstPrev->pstNext;
smp_wmb();
pstPrev->pstNext = pstInst;
}
return;
}
#define SL_FOREACH_RCU(pstList, pstNode) \
for ((pstNode) = RCU_DeRef((pstList)->pstFirst); \
(NULL != (pstNode)) && ({Prefetch((pstNode)->pstNext); BOOL_TRUE;}); \
(pstNode) = RCU_DeRef((pstNode)->pstNext))
#define SL_FOREACH_SAFE_RCU(pstList, pstNode, pstNextNode) \
for ((pstNode) = RCU_DeRef((pstList)->pstFirst); \
(NULL != (pstNode)) && ({(pstNextNode) = RCU_DeRef((pstNode)->pstNext); BOOL_TRUE;}); \
(pstNode) = (pstNextNode))
#define SL_FOREACH_PREVPTR_RCU(pstList, pstNode, pstPrev) \
for ((pstNode) = RCU_DeRef((pstList)->pstFirst), (pstPrev) = (SL_NODE_S *)NULL; \
(NULL != (pstNode)) && ({Prefetch((pstNode)->pstNext); BOOL_TRUE;}); \
(VOID)({(pstPrev) = (pstNode); (pstNode) = RCU_DeRef((pstNode)->pstNext);}))
#define SL_ENTRY_NEXT_Prefetch(pstEntry, member) \
((NULL == SL_Next(&((pstEntry)->member))) ? NULL : \
Prefetch(SL_ENTRY(SL_Next(&((pstEntry)->member)), typeof(*(pstEntry)), member)))
#define SL_FOREACH_ENTRY_RCU(pstList, pstEntry, member) \
for ((pstEntry) = SL_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member), (pstEntry) = RCU_DeRef(pstEntry); \
(NULL != (pstEntry)) && ({SL_ENTRY_NEXT_Prefetch(pstEntry, member); BOOL_TRUE;}); \
(pstEntry) = SL_ENTRY_NEXT(pstEntry, member), (pstEntry) = RCU_DeRef(pstEntry))
#define SL_FOREACH_ENTRY_SAFE_RCU(pstList, pstEntry, pstNextEntry, member) \
for ((pstEntry) = SL_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member), (pstEntry) = RCU_DeRef(pstEntry); \
(NULL != (pstEntry)) && \
({(pstNextEntry) = SL_ENTRY_NEXT(pstEntry, member), (pstNextEntry) = RCU_DeRef(pstNextEntry); BOOL_TRUE;}); \
(pstEntry) = (pstNextEntry))
#define SL_FOREACH_ENTRY_PREVPTR_RCU(pstList, pstEntry, pstPrevEntry, member) \
for ((pstEntry) = SL_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member), \
(pstEntry) = RCU_DeRef(pstEntry), (pstPrevEntry) = NULL; \
(NULL != (pstEntry)) && ({SL_ENTRY_NEXT_Prefetch(pstEntry, member); BOOL_TRUE;}); \
(VOID)({(pstPrevEntry) = (pstEntry); \
(pstEntry) = SL_ENTRY_NEXT(pstEntry, member), (pstEntry) = RCU_DeRef(pstEntry);}))
static inline VOID SL_Del_Rcu(IN SL_HEAD_S* pstList, IN SL_NODE_S* pstNode)
{
SL_NODE_S *pstCur, *pstPrev;
SL_FOREACH_PREVPTR_RCU(pstList, pstCur, pstPrev)
{
if (pstCur == pstNode)
{
(VOID) SL_DelAfter(pstList, pstPrev);
break;
}
}
return;
}
static inline VOID SL_Append_Rcu(IN SL_HEAD_S* pstDstList, INOUT SL_HEAD_S* pstSrcList)
{
SL_NODE_S *pstNode, *pstPrev;
if (BOOL_TRUE != SL_IsEmpty (pstSrcList))
{
SL_FOREACH_PREVPTR_RCU(pstDstList, pstNode, pstPrev)
{
; /* do nothing */
}
if (NULL == pstPrev)
{
pstDstList->pstFirst = SL_First(pstSrcList);
}
else
{
pstPrev->pstNext = SL_First(pstSrcList);
}
SL_Init(pstSrcList);
}
return;
}
static inline VOID STQ_AddHead_Rcu(IN STQ_HEAD_S* pstList, IN STQ_NODE_S* pstNode)
{
pstNode->pstNext = pstList->pstFirst;
smp_wmb();
pstList->pstFirst = pstNode;
if (NULL == pstList->pstLast)
{
pstList->pstLast = pstNode;
}
return;
}
static inline VOID STQ_AddTail_Rcu(STQ_HEAD_S* pstList, STQ_NODE_S* pstNode)
{
pstNode->pstNext = (STQ_NODE_S *)NULL;
if (NULL != pstList->pstLast)
{
pstList->pstLast->pstNext = pstNode;
smp_wmb();
pstList->pstLast = pstNode;
}
else
{
pstList->pstLast = pstNode;
pstList->pstFirst = pstNode;
}
return;
}
static inline VOID STQ_AddAfter_Rcu(IN STQ_HEAD_S* pstList,
IN STQ_NODE_S* pstPrev,
IN STQ_NODE_S* pstInst)
{
if (NULL == pstPrev)
{
STQ_AddHead_Rcu(pstList, pstInst);
}
else
{
pstInst->pstNext = pstPrev->pstNext;
smp_wmb();
pstPrev->pstNext = pstInst;
if (pstList->pstLast == pstPrev)
{
pstList->pstLast = pstInst;
}
}
return;
}
#define STQ_FOREACH_RCU(pstList, pstNode) \
for((pstNode) = RCU_DeRef((pstList)->pstFirst); \
(NULL != (pstNode)) && ({Prefetch((pstNode)->pstNext); BOOL_TRUE;}); \
(pstNode) = RCU_DeRef((pstNode)->pstNext))
#define STQ_FOREACH_SAFE_RCU(pstList, pstNode, pstNextNode) \
for ((pstNode) = RCU_DeRef((pstList)->pstFirst); \
(NULL != (pstNode)) && ({(pstNextNode) = RCU_DeRef((pstNode)->pstNext); BOOL_TRUE;}); \
(pstNode) = (pstNextNode))
#define STQ_FOREACH_PREVPTR_RCU(pstList, pstNode, pstPrev) \
for ((pstNode) = RCU_DeRef((pstList)->pstFirst), (pstPrev) = NULL; \
(NULL != (pstNode)) && ({Prefetch((pstNode)->pstNext); BOOL_TRUE;}); \
(VOID)({(pstPrev) = (pstNode); (pstNode) = RCU_DeRef((pstNode)->pstNext);}))
#define STQ_ENTRY_NEXT_Prefetch(pstEntry, member) \
(NULL == STQ_Next(&((pstEntry)->member)) ? NULL : \
Prefetch(STQ_ENTRY(STQ_Next(&((pstEntry)->member)), typeof(*(pstEntry)), member)))
#define STQ_FOREACH_ENTRY_RCU(pstList, pstEntry, member) \
for ((pstEntry) = STQ_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member), pstEntry = RCU_DeRef(pstEntry); \
(NULL != (pstEntry)) && ({STQ_ENTRY_NEXT_Prefetch(pstEntry, member), BOOL_TRUE;}); \
(pstEntry) = STQ_ENTRY_NEXT(pstEntry, member), pstEntry = RCU_DeRef(pstEntry))
#define STQ_FOREACH_ENTRY_SAFE_RCU(pstList, pstEntry, pstNextEntry, member) \
for ((pstEntry) = STQ_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member), pstEntry = RCU_DeRef(pstEntry); \
(NULL != (pstEntry)) && \
({(pstNextEntry) = STQ_ENTRY_NEXT(pstEntry, member), pstNextEntry = RCU_DeRef(pstNextEntry); BOOL_TRUE;}); \
(pstEntry) = (pstNextEntry))
#define STQ_FOREACH_ENTRY_PREVPTR_RCU(pstList, pstEntry, pstPrevEntry, member) \
for ((pstEntry) = STQ_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member), \
pstEntry = RCU_DeRef(pstEntry), (pstPrevEntry) = NULL; \
(NULL != (pstEntry)) && ({STQ_ENTRY_NEXT_Prefetch(pstEntry, member); BOOL_TRUE;}); \
(VOID)({(pstPrevEntry) = (pstEntry); \
(pstEntry) = STQ_ENTRY_NEXT(pstEntry, member), pstEntry = RCU_DeRef(pstEntry);}))
static inline VOID STQ_Del_Rcu(IN STQ_HEAD_S* pstList, IN STQ_NODE_S* pstNode)
{
STQ_NODE_S *pstPrev, *pstCur;
STQ_FOREACH_PREVPTR_RCU(pstList, pstCur, pstPrev)
{
if (pstCur == pstNode)
{
(VOID)STQ_DelAfter (pstList, pstPrev);
break;
}
}
return;
}
static inline VOID DL_AddHead_Rcu(IN DL_HEAD_S* pstList, IN DL_NODE_S* pstNode)
{
pstNode->ppstPre = &pstList->pstFirst;
pstNode->pstNext = pstList->pstFirst;
smp_wmb();
if (NULL != pstNode->pstNext)
{
pstNode->pstNext->ppstPre = &pstNode->pstNext;
}
pstList->pstFirst = pstNode;
return;
}
static inline VOID DL_AddAfter_Rcu(IN DL_NODE_S* pstPrev, IN DL_NODE_S* pstInst)
{
pstInst->ppstPre = &pstPrev->pstNext;
pstInst->pstNext = pstPrev->pstNext;
smp_wmb();
pstPrev->pstNext = pstInst;
if (NULL != pstInst->pstNext)
{
pstInst->pstNext->ppstPre = &pstInst->pstNext;
}
return;
}
static inline VOID DL_AddAfterPtr_Rcu(IN DL_NODE_S **ppstPre, IN DL_NODE_S *pstInst)
{
pstInst->ppstPre = ppstPre;
pstInst->pstNext = *ppstPre;
smp_wmb();
*ppstPre = pstInst;
if (NULL != pstInst->pstNext)
{
pstInst->pstNext->ppstPre = &pstInst->pstNext;
}
return;
}
static inline VOID DL_AddBefore_Rcu(IN DL_NODE_S* pstNext, IN DL_NODE_S* pstInst)
{
pstInst->ppstPre = pstNext->ppstPre;
pstInst->pstNext = pstNext;
smp_wmb();
pstNext->ppstPre = &pstInst->pstNext;
if (NULL != pstInst->ppstPre)
{
*pstInst->ppstPre = pstInst;
}
return;
}
#define DL_FOREACH_RCU(pstList, pstNode) \
for ((pstNode) = RCU_DeRef((pstList)->pstFirst); \
(NULL != (pstNode)) && ({Prefetch(pstNode->pstNext); BOOL_TRUE;}); \
(pstNode) = RCU_DeRef(pstNode->pstNext))
#define DL_FOREACH_SAFE_RCU(pstList, pstNode, pstNextNode) \
for ((pstNode) = RCU_DeRef((pstList)->pstFirst); \
(NULL != (pstNode)) && ({(pstNextNode) = RCU_DeRef((pstNode)->pstNext); BOOL_TRUE;}); \
(pstNode) = (pstNextNode))
#define DL_FOREACH_PREVPTR_RCU(pstList, pstNode, ppstPre) \
for ((pstNode) = RCU_DeRef((pstList)->pstFirst), (ppstPre) = &((pstList)->pstFirst); \
(NULL != (pstNode)) && ({Prefetch((pstNode)->pstNext); BOOL_TRUE;}); \
(VOID)({(ppstPre) = &((pstNode)->pstNext); \
(pstNode) = RCU_DeRef((pstNode)->pstNext);}))
#define DL_ENTRY_NEXT_Prefetch(pstEntry, member) \
(NULL == DL_Next(&((pstEntry)->member)) ? NULL : \
Prefetch(DL_ENTRY(DL_Next(&((pstEntry)->member)), typeof(*(pstEntry)), member)))
#define DL_FOREACH_ENTRY_RCU(pstList, pstEntry, member) \
for ((pstEntry) = DL_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member), (pstEntry) = RCU_DeRef(pstEntry); \
(NULL != (pstEntry)) && ({DL_ENTRY_NEXT_Prefetch(pstEntry, member); BOOL_TRUE;}); \
(pstEntry) = DL_ENTRY_NEXT(pstEntry, member), (pstEntry) = RCU_DeRef(pstEntry))
#define DL_FOREACH_ENTRY_SAFE_RCU(pstList, pstEntry, pstNextEntry, member) \
for ((pstEntry) = DL_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member), (pstEntry) = RCU_DeRef(pstEntry); \
(NULL != (pstEntry)) && \
({(pstNextEntry) = DL_ENTRY_NEXT(pstEntry, member), (pstNextEntry) = RCU_DeRef(pstNextEntry); BOOL_TRUE;}); \
(pstEntry) = (pstNextEntry))
#define DL_FOREACH_ENTRY_PREVPTR_RCU(pstList, pstEntry, ppstPre, member) \
for ((pstEntry) = DL_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member), (pstEntry) = RCU_DeRef(pstEntry), \
(ppstPre) = &((pstList)->pstFirst); \
(NULL != (pstEntry)) && ({DL_ENTRY_NEXT_Prefetch(pstEntry, member); BOOL_TRUE;}); \
(VOID)({(ppstPre) = &((pstEntry)->member.pstNext); \
(pstEntry) = DL_ENTRY_NEXT(pstEntry, member), (pstEntry) = RCU_DeRef(pstEntry);}))
static inline VOID DL_Append_Rcu(IN DL_HEAD_S* pstDstList, INOUT DL_HEAD_S* pstSrcList)
{
DL_NODE_S *pstNode, **ppstPre;
if (BOOL_TRUE != DL_IsEmpty (pstSrcList))
{
/* seek pstPrev to the tail of pstDstList */
DL_FOREACH_PREVPTR_RCU(pstDstList, pstNode, ppstPre)
{
; /* do nothing */
}
*ppstPre = pstSrcList->pstFirst;
pstSrcList->pstFirst->ppstPre = ppstPre;
DL_Init(pstSrcList);
}
return;
}
static inline VOID DTQ_AddAfter_Rcu(IN DTQ_NODE_S* pstPrev, IN DTQ_NODE_S* pstInst)
{
pstInst->pstPrev = pstPrev;
pstInst->pstNext = pstPrev->pstNext;
smp_wmb();
pstPrev->pstNext = pstInst;
pstInst->pstNext->pstPrev = pstInst;
return;
}
static inline VOID DTQ_AddBefore_Rcu(IN DTQ_NODE_S* pstNext, IN DTQ_NODE_S* pstInst)
{
pstInst->pstPrev = pstNext->pstPrev;
pstInst->pstNext = pstNext;
smp_wmb();
pstInst->pstPrev->pstNext = pstInst;
pstInst->pstNext->pstPrev = pstInst;
return;
}
static inline VOID DTQ_AddHead_Rcu(IN DTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode)
{
DTQ_AddAfter_Rcu(&pstList->stHead, pstNode);
return;
}
static inline VOID DTQ_AddTail_Rcu(IN DTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode)
{
DTQ_AddBefore_Rcu(&pstList->stHead, pstNode);
return;
}
#define DTQ_FOREACH_RCU(pstList, pstNode) \
for ((pstNode) = RCU_DeRef((pstList)->stHead.pstNext); \
(BOOL_TRUE != DTQ_IsEndOfQ(pstList, pstNode)) && ({Prefetch((pstNode)->pstNext);BOOL_TRUE;}); \
(pstNode) = RCU_DeRef((pstNode)->pstNext))
#define DTQ_FOREACH_SAFE_RCU(pstList, pstNode, pstNextNode) \
for ((pstNode) = RCU_DeRef((pstList)->stHead.pstNext); \
(BOOL_TRUE != DTQ_IsEndOfQ(pstList, pstNode)) && \
({(pstNextNode) = RCU_DeRef((pstNode)->pstNext); BOOL_TRUE;}); \
(pstNode) = (pstNextNode))
#define DTQ_FOREACH_REVERSE_RCU(pstList, pstNode) \
for ((pstNode) = RCU_DeRef((pstList)->stHead.pstPrev); \
(BOOL_TRUE != DTQ_IsEndOfQ(pstList, pstNode)) && ({Prefetch((pstNode)->pstPrev);BOOL_TRUE;}); \
(pstNode) = RCU_DeRef((pstNode)->pstPrev))
#define DTQ_FOREACH_REVERSE_SAFE_RCU(pstList, pstNode, pstPrev) \
for ((pstNode) = RCU_DeRef((pstList)->stHead.pstPrev); \
(BOOL_TRUE != DTQ_IsEndOfQ(pstList, pstNode)) && \
({(pstPrev) = RCU_DeRef((pstNode)->pstPrev); BOOL_TRUE;}); \
(pstNode) = (pstPrev))
#define DTQ_ENTRY_NEXT_Prefetch(pstList, pstEntry, member) \
(DTQ_IsEndOfQ(pstList, DTQ_Next(&((pstEntry)->member))) ? \
NULL : Prefetch(DTQ_ENTRY(DTQ_Next(&((pstEntry)->member)), typeof(*(pstEntry)), member)))
#define DTQ_FOREACH_ENTRY_RCU(pstList, pstEntry, member) \
for ((pstEntry) = DTQ_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member), (pstEntry) = RCU_DeRef(pstEntry); \
(NULL != (pstEntry)) && ({DTQ_ENTRY_NEXT_Prefetch(pstList, pstEntry, member); BOOL_TRUE;}); \
(pstEntry) = DTQ_ENTRY_NEXT(pstList, pstEntry, member), (pstEntry) = RCU_DeRef(pstEntry))
#define DTQ_FOREACH_ENTRY_SAFE_RCU(pstList, pstEntry, pstNextEntry, member) \
for ((pstEntry) = DTQ_ENTRY_FIRST(pstList, typeof(*(pstEntry)), member), (pstEntry) = RCU_DeRef(pstEntry); \
(NULL != (pstEntry)) && \
({(pstNextEntry) = DTQ_ENTRY_NEXT(pstList, pstEntry, member), \
(pstNextEntry) = RCU_DeRef(pstNextEntry); BOOL_TRUE;}); \
(pstEntry) = (pstNextEntry))
#define DTQ_ENTRY_PREV_Prefetch(pstList, pstEntry, member) \
(DTQ_IsEndOfQ(pstList, DTQ_Prev(&((pstEntry)->member))) ? \
NULL : Prefetch(DTQ_ENTRY(DTQ_Prev(&((pstEntry)->member)), typeof(*(pstEntry)), member)))
#define DTQ_FOREACH_ENTRY_REVERSE_RCU(pstList, pstEntry, member) \
for ((pstEntry) = DTQ_ENTRY_LAST(pstList, typeof(*(pstEntry)), member), (pstEntry) = RCU_DeRef(pstEntry); \
(NULL != (pstEntry)) && ({DTQ_ENTRY_PREV_Prefetch(pstList, pstEntry, member); BOOL_TRUE;})\
(pstEntry) = DTQ_ENTRY_PREV(pstList, pstEntry, member), (pstEntry) = RCU_DeRef(pstEntry))
#define DTQ_FOREACH_ENTRY_REVERSE_SAFE_RCU(pstList, pstEntry, pstPrevEntry, member) \
for ((pstEntry) = DTQ_ENTRY_LAST(pstList, typeof(*(pstEntry)), member), (pstEntry) = RCU_DeRef(pstEntry); \
(NULL != (pstEntry)) && \
({(pstPrevEntry) = DTQ_ENTRY_PREV(pstList, pstEntry, member), \
(pstPrevEntry) = RCU_DeRef(pstPrevEntry); BOOL_TRUE;}); \
(pstEntry) = (pstPrevEntry))
static inline VOID DTQ_Append_Rcu(IN DTQ_HEAD_S* pstDstList, INOUT DTQ_HEAD_S* pstSrcList)
{
if (BOOL_TRUE != DTQ_IsEmpty(pstSrcList))
{
pstSrcList->stHead.pstNext->pstPrev = pstDstList->stHead.pstPrev;
pstSrcList->stHead.pstPrev->pstNext = pstDstList->stHead.pstPrev->pstNext;
smp_wmb();
pstDstList->stHead.pstPrev->pstNext = pstSrcList->stHead.pstNext;
pstDstList->stHead.pstPrev = pstSrcList->stHead.pstPrev;
DTQ_Init(pstSrcList);
}
return;
}
#else /* USER SPACE */
#include <pthread.h>
typedef struct tagRWSTQ_HEAD
{
STQ_HEAD_S stHead;
pthread_rwlock_t stRwLock;
} RWSTQ_HEAD_S;
static inline VOID RWSTQ_ReadLock (IN RWSTQ_HEAD_S* pstNode);
static inline BOOL_T RWSTQ_ReadTryLock (IN RWSTQ_HEAD_S* pstNode);
static inline VOID RWSTQ_ReadUnlock (IN RWSTQ_HEAD_S* pstNode);
static inline VOID RWSTQ_WriteLock (IN RWSTQ_HEAD_S* pstNode);
static inline BOOL_T RWSTQ_WriteTryLock (IN RWSTQ_HEAD_S* pstNode);
static inline VOID RWSTQ_WriteUnlock (IN RWSTQ_HEAD_S* pstNode);
static inline VOID RWSTQ_DeInit (IN RWSTQ_HEAD_S* pstNode);
static inline VOID RWSTQ_Init(IN RWSTQ_HEAD_S* pstList);
static inline BOOL_T RWSTQ_IsEmpty(IN RWSTQ_HEAD_S* pstList);
static inline VOID RWSTQ_AddHead(IN RWSTQ_HEAD_S* pstList, IN STQ_NODE_S* pstNode);
static inline STQ_NODE_S* RWSTQ_DelHead(IN RWSTQ_HEAD_S* pstList);
static inline VOID RWSTQ_AddTail(IN RWSTQ_HEAD_S* pstList, IN STQ_NODE_S* pstNode);
static inline VOID RWSTQ_Del(IN RWSTQ_HEAD_S* pstList, IN STQ_NODE_S* pstNode);
static inline VOID RWSTQ_FreeAll(IN RWSTQ_HEAD_S *pstList, IN VOID (*pfFree)(VOID *));
/*****************************************************************************
Func Name: RWSTQ_ReadLock
Date Created: 2010/12/03
Author: s07542
Description: lock RWSTQ for reading
Input: RWSTQ_HEAD_S* pstNode RWSTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWSTQ_ReadLock (IN RWSTQ_HEAD_S* pstNode)
{
(VOID)pthread_rwlock_rdlock(&pstNode->stRwLock);
return;
}
/*****************************************************************************
Func Name: RWSTQ_ReadTryLock
Date Created: 2010/12/03
Author: s07542
Description: try lock RWSTQ for reading
Input: RWSTQ_HEAD_S* pstNode RWSTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline BOOL_T RWSTQ_ReadTryLock (IN RWSTQ_HEAD_S* pstNode)
{
return (0 == pthread_rwlock_tryrdlock(&pstNode->stRwLock));
}
/*****************************************************************************
Func Name: RWSTQ_ReadUnlock
Date Created: 2010/12/03
Author: s07542
Description: unlock RWSTQ
Input: RWSTQ_HEAD_S* pstNode RWSTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWSTQ_ReadUnlock (IN RWSTQ_HEAD_S* pstNode)
{
(VOID)pthread_rwlock_unlock(&pstNode->stRwLock);
return;
}
/*****************************************************************************
Func Name: RWSTQ_WriteLock
Date Created: 2010/12/03
Author: s07542
Description: lock RWSTQ for write
Input: RWSTQ_HEAD_S* pstNode RWSTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWSTQ_WriteLock (IN RWSTQ_HEAD_S* pstNode)
{
(VOID)pthread_rwlock_wrlock(&pstNode->stRwLock);
return;
}
/*****************************************************************************
Func Name: RWSTQ_WriteTryLock
Date Created: 2010/12/03
Author: s07542
Description: try lock RWSTQ for write
Input: RWSTQ_HEAD_S* pstNode RWSTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline BOOL_T RWSTQ_WriteTryLock (IN RWSTQ_HEAD_S* pstNode)
{
return (0 == pthread_rwlock_trywrlock(&pstNode->stRwLock));
}
/*****************************************************************************
Func Name: RWSTQ_WriteUnlock
Date Created: 2010/12/03
Author: s07542
Description: unlock RWSTQ for write
Input: RWSTQ_HEAD_S* pstNode RWSTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWSTQ_WriteUnlock (IN RWSTQ_HEAD_S* pstNode)
{
(VOID)pthread_rwlock_unlock(&pstNode->stRwLock);
return;
}
/*****************************************************************************
Func Name: RWSTQ_DeInit
Date Created: 2010/12/03
Author: s07542
Description: Destroy RWSTQ lock
Input: RWSTQ_HEAD_S* pstNode RWSTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWSTQ_DeInit (IN RWSTQ_HEAD_S* pstNode)
{
(VOID)pthread_rwlock_destroy(&pstNode->stRwLock);
return;
}
/*****************************************************************************
Func Name: RWSTQ_Init
Date Created: 2010/12/03
Author: s07542
Description: RWSTQ init
Input: RWSTQ_HEAD_S* pstList RWSTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWSTQ_Init(IN RWSTQ_HEAD_S* pstList)
{
STQ_Init(&pstList->stHead);
(VOID)pthread_rwlock_init(&pstList->stRwLock,NULL);
return;
}
/*****************************************************************************
Func Name: RWSTQ_IsEmpty
Date Created: 2010/12/03
Author: s07542
Description: Whether the singly-linked tail queue is empty
Input: RWSTQ_HEAD_S* pstList the pointer to the queue head
Output: No output
Return: BOOL_TRUE or BOOL_FLASE
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline BOOL_T RWSTQ_IsEmpty(IN RWSTQ_HEAD_S* pstList)
{
BOOL_T bIsemp;
RWSTQ_ReadLock(pstList);
bIsemp = STQ_IsEmpty(&pstList->stHead);
RWSTQ_ReadUnlock(pstList);
return bIsemp;
}
/*****************************************************************************
Func Name: RWSTQ_AddHead
Date Created: 2010/12/03
Author: s07542
Description: Add an element to the head of the queue
Input: RWSTQ_HEAD_S* pstList the pointer to the queue head
STQ_NODE_S* pstNode the pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWSTQ_AddHead(IN RWSTQ_HEAD_S* pstList, IN STQ_NODE_S* pstNode)
{
RWSTQ_WriteLock(pstList);
STQ_AddHead(&pstList->stHead, pstNode);
RWSTQ_WriteUnlock(pstList);
return;
}
/*****************************************************************************
Func Name: RWSTQ_DelHead
Date Created: 2010/12/03
Author: s07542
Description: Delete the first element from the queue
Input: RWSTQ_HEAD_S* pstList the pointer to the queue head
Output: No output
Return: the pointer to the deleted element, NULL if no element is deleted
Caution: This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline STQ_NODE_S* RWSTQ_DelHead(IN RWSTQ_HEAD_S* pstList)
{
STQ_NODE_S *pstNode = NULL;
RWSTQ_WriteLock(pstList);
pstNode = STQ_DelHead(&pstList->stHead);
RWSTQ_WriteUnlock(pstList);
return pstNode;
}
/*****************************************************************************
Func Name: RWSTQ_AddTail
Date Created: 2010/12/03
Author: s07542
Description: Add an element to the tail of the queue
Input: RWSTQ_HEAD_S* pstList the pointer to the queue tail
STQ_NODE_S* pstNode the pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWSTQ_AddTail(IN RWSTQ_HEAD_S* pstList, IN STQ_NODE_S* pstNode)
{
RWSTQ_WriteLock(pstList);
STQ_AddTail(&pstList->stHead, pstNode);
RWSTQ_WriteUnlock(pstList);
return;
}
/*****************************************************************************
Func Name: RWSTQ_Del
Date Created: 2010/12/03
Author: s07542
Description: Delete an element from the tail queue
Input: RWSTQ_HEAD_S* pstList the pointer to the queue head
STQ_NODE_S* pstNode the pointer to the element to be deleted
Output: No output
Return: No return
Caution: It takes the expense of O(n). If you have got a pointer to the
previous element, you'd better use STQ_DelAfter whitch takes
the expense of O(1).
This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWSTQ_Del(IN RWSTQ_HEAD_S* pstList, IN STQ_NODE_S* pstNode)
{
RWSTQ_WriteLock(pstList);
STQ_Del(&pstList->stHead, pstNode);
RWSTQ_WriteUnlock(pstList);
return;
}
/*****************************************************************************
Func Name: RWSTQ_FreeAll
Date Created: 2010/12/03
Author: s07542
Description: Remove and free all nodes from STQ list
Input: IN STQ_HEAD_S *pstList
IN VOID (*pfFree)(VOID *)
Output:
Return: STATIC
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWSTQ_FreeAll(IN RWSTQ_HEAD_S *pstList, IN VOID (*pfFree)(VOID *))
{
RWSTQ_WriteLock(pstList);
STQ_FreeAll(&pstList->stHead, pfFree);
RWSTQ_WriteUnlock(pstList);
return;
}
typedef struct tagRWDTQ_HEAD
{
DTQ_HEAD_S stHead;
pthread_rwlock_t stRwLock;
} RWDTQ_HEAD_S;
static inline VOID RWDTQ_ReadLock (IN RWDTQ_HEAD_S* pstNode);
static inline BOOL_T RWDTQ_ReadTryLock (IN RWDTQ_HEAD_S* pstNode);
static inline VOID RWDTQ_ReadUnlock (IN RWDTQ_HEAD_S* pstNode);
static inline VOID RWDTQ_WriteLock (IN RWDTQ_HEAD_S* pstNode);
static inline BOOL_T RWDTQ_WriteTryLock (IN RWDTQ_HEAD_S* pstNode);
static inline VOID RWDTQ_WriteUnlock (IN RWDTQ_HEAD_S* pstNode);
static inline VOID RWDTQ_DeInit (IN RWDTQ_HEAD_S* pstNode);
static inline VOID RWDTQ_Init(IN RWDTQ_HEAD_S* pstList);
static inline BOOL_T RWDTQ_IsEmpty(IN RWDTQ_HEAD_S* pstList);
static inline BOOL_T RWDTQ_IsEndOfQ(IN RWDTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode);
static inline VOID RWDTQ_AddHead(IN RWDTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode);
static inline DTQ_NODE_S* RWDTQ_DelHead(IN RWDTQ_HEAD_S* pstList);
static inline VOID RWDTQ_AddTail(IN RWDTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode);
static inline DTQ_NODE_S* RWDTQ_DelTail(IN RWDTQ_HEAD_S* pstList);
static inline VOID RWDTQ_FreeAll(IN RWDTQ_HEAD_S *pstList, IN VOID (*pfFree)(VOID *));
static inline VOID RWDTQ_Del(IN RWDTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode);
/*****************************************************************************
Func Name: RWDTQ_ReadLock
Date Created: 2010/12/03
Author: s07542
Description: lock RWDTQ for reading
Input: RWDTQ_HEAD_S* pstNode RWDTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWDTQ_ReadLock (IN RWDTQ_HEAD_S* pstNode)
{
(VOID)pthread_rwlock_rdlock(&pstNode->stRwLock);
return;
}
/*****************************************************************************
Func Name: RWDTQ_ReadTryLock
Date Created: 2010/12/03
Author: s07542
Description: try lock RWDTQ for reading
Input: RWDTQ_HEAD_S* pstNode RWDTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline BOOL_T RWDTQ_ReadTryLock (IN RWDTQ_HEAD_S* pstNode)
{
return (0 == pthread_rwlock_tryrdlock(&pstNode->stRwLock));
}
/*****************************************************************************
Func Name: RWDTQ_ReadUnlock
Date Created: 2010/12/03
Author: s07542
Description: unlock RWDTQ
Input: RWDTQ_HEAD_S* pstNode RWDTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWDTQ_ReadUnlock (IN RWDTQ_HEAD_S* pstNode)
{
(VOID)pthread_rwlock_unlock(&pstNode->stRwLock);
return;
}
/*****************************************************************************
Func Name: RWDTQ_WriteLock
Date Created: 2010/12/03
Author: s07542
Description: lock RWDTQ for write
Input: RWDTQ_HEAD_S* pstNode RWDTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWDTQ_WriteLock (IN RWDTQ_HEAD_S* pstNode)
{
(VOID)pthread_rwlock_wrlock(&pstNode->stRwLock);
return;
}
/*****************************************************************************
Func Name: RWDTQ_WriteTryLock
Date Created: 2010/12/03
Author: s07542
Description: try lock RWDTQ for write
Input: RWDTQ_HEAD_S* pstNode RWDTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline BOOL_T RWDTQ_WriteTryLock (IN RWDTQ_HEAD_S* pstNode)
{
return (0 == pthread_rwlock_trywrlock(&pstNode->stRwLock));
}
/*****************************************************************************
Func Name: RWDTQ_WriteUnlock
Date Created: 2010/12/03
Author: s07542
Description: unlock RWDTQ for write
Input: RWDTQ_HEAD_S* pstNode RWDTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWDTQ_WriteUnlock (IN RWDTQ_HEAD_S* pstNode)
{
(VOID)pthread_rwlock_unlock(&pstNode->stRwLock);
return;
}
/*****************************************************************************
Func Name: RWDTQ_DeInit
Date Created: 2010/12/03
Author: s07542
Description: Destroy RWDTQ lock
Input: RWDTQ_HEAD_S* pstNode RWDTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWDTQ_DeInit (IN RWDTQ_HEAD_S* pstNode)
{
(VOID)pthread_rwlock_destroy(&pstNode->stRwLock);
return;
}
/*****************************************************************************
Func Name: RWDTQ_Init
Date Created: 2010/12/03
Author: s07542
Description: RWDTQ init
Input: RWDTQ_HEAD_S* pstList RWDTQ head
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWDTQ_Init(IN RWDTQ_HEAD_S* pstList)
{
DTQ_Init(&pstList->stHead);
(VOID)pthread_rwlock_init(&pstList->stRwLock,NULL);
return;
}
/*****************************************************************************
Func Name: RWDTQ_IsEmpty
Date Created: 2010/12/03
Author: s07542
Description: Whether the DTQ tail queue is empty
Input: RWDTQ_HEAD_S* pstList the pointer to the queue head
Output: No output
Return: BOOL_TRUE or BOOL_FLASE
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline BOOL_T RWDTQ_IsEmpty(IN RWDTQ_HEAD_S* pstList)
{
BOOL_T bIsemp;
RWDTQ_ReadLock(pstList);
bIsemp = DTQ_IsEmpty(&pstList->stHead);
RWDTQ_ReadUnlock(pstList);
return bIsemp;
}
/*****************************************************************************
Func Name: RWDTQ_IsEndOfQ
Date Created: 2010/12/03
Author: s07542
Description: Wether the node is the end of the queue
Input: RWDTQ_HEAD_S* pstList the pointer to the queue head
DTQ_NODE_S* pstNode the pointer to the node
Output: No output
Return: BOOL_TURE if is end of the queue, BOOL_FALSE is not
Caution: RWDTQ is a circle doubly link list, we can not use NULL to
decide wether reaching the end of list
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline BOOL_T RWDTQ_IsEndOfQ(IN RWDTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode)
{
BOOL_T bIsemp;
RWDTQ_ReadLock(pstList);
bIsemp = DTQ_IsEndOfQ(&pstList->stHead, pstNode);
RWDTQ_ReadUnlock(pstList);
return bIsemp;
}
/*****************************************************************************
Func Name: RWDTQ_AddHead
Date Created: 2010/12/03
Author: s07542
Description: Add an element to the head of the queue
Input: RWDTQ_HEAD_S* pstList the pointer to the queue head
DTQ_NODE_S* pstNode the pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWDTQ_AddHead(IN RWDTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode)
{
RWDTQ_WriteLock(pstList);
DTQ_AddHead(&pstList->stHead, pstNode);
RWDTQ_WriteUnlock(pstList);
return;
}
/*****************************************************************************
Func Name: RWDTQ_DelHead
Date Created: 2010/12/03
Author: s07542
Description: Delete the first element from the queue
Input: RWDTQ_HEAD_S* pstList the pointer to the queue head
Output: No output
Return: the pointer to the deleted element, NULL if no element is deleted
Caution: This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline DTQ_NODE_S* RWDTQ_DelHead(IN RWDTQ_HEAD_S* pstList)
{
DTQ_NODE_S *pstNode = NULL;
RWDTQ_WriteLock(pstList);
pstNode = DTQ_DelHead(&pstList->stHead);
RWDTQ_WriteUnlock(pstList);
return pstNode;
}
/*****************************************************************************
Func Name: RWDTQ_Del
Date Created: 2008/3/28
Author: c02254
Description: Delete an element from the tail queue
Input: DTQ_NODE_S* pstNode the pointer to the element to be deleted
Output: No output
Return: No return
Caution: This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWDTQ_Del(IN RWDTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode)
{
RWDTQ_WriteLock(pstList);
pstNode->pstPrev->pstNext = pstNode->pstNext;
pstNode->pstNext->pstPrev = pstNode->pstPrev;
RWDTQ_WriteUnlock(pstList);
return;
}
/*****************************************************************************
Func Name: RWDTQ_AddTail
Date Created: 2010/12/03
Author: s07542
Description: Add an element to the tail of the queue
Input: RWDTQ_HEAD_S* pstList the pointer to the queue head
DTQ_NODE_S* pstNode the pointer to the element to be added
Output: No output
Return: No return
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWDTQ_AddTail(IN RWDTQ_HEAD_S* pstList, IN DTQ_NODE_S* pstNode)
{
RWDTQ_WriteLock(pstList);
DTQ_AddTail(&pstList->stHead, pstNode);
RWDTQ_WriteUnlock(pstList);
return;
}
/*****************************************************************************
Func Name: RWDTQ_DelTail
Date Created: 2010/12/03
Author: s07542
Description: Delete the last element from the queue
Input: RWDTQ_HEAD_S* pstList the pointer to the queue head
Output: No output
Return: the pointer to the deleted element, NULL if no element is deleted
Caution: This function only delete the element from the list, and does
NOT free the memory of the element.
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline DTQ_NODE_S* RWDTQ_DelTail(IN RWDTQ_HEAD_S* pstList)
{
DTQ_NODE_S *pstNode = NULL;
RWDTQ_WriteLock(pstList);
pstNode = DTQ_DelTail(&pstList->stHead);
RWDTQ_WriteUnlock(pstList);
return pstNode;
}
/*****************************************************************************
Func Name: RWDTQ_FreeAll
Date Created: 2010/12/03
Author: s07542
Description: Remove and free all nodes from DTQ list
Input: IN RWDTQ_HEAD_S *pstList
IN VOID (*pfFree)(VOID *)
Output:
Return: STATIC
Caution:
------------------------------------------------------------------------------
Modification History
DATE NAME DESCRIPTION
--------------------------------------------------------------------------
*****************************************************************************/
static inline VOID RWDTQ_FreeAll(IN RWDTQ_HEAD_S *pstList, IN VOID (*pfFree)(VOID *))
{
RWDTQ_WriteLock(pstList);
DTQ_FreeAll(&pstList->stHead, pfFree);
RWDTQ_WriteUnlock(pstList);
return;
}
#endif
#ifdef __cplusplus
}
#endif
#endif /* _SYS_LIST_H_ */
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef SELECTIONPOINT_H
#define SELECTIONPOINT_H
class HTML_Element;
/**
* Selection boundary point. Specifies a selected point in a document,
* using the same format as DOM Ranges (element + offset) with the
* bonus of a "binding direction" to solve the rendering problem of
* points of a document that exists at multiple places.
*/
class SelectionBoundaryPoint
{
private:
HTML_Element* m_element;
signed int m_offset:31;
/**
* Indicator for what this selection point binds hardest to. In case of line breaks
* and BiDi a text like A|B might have the A and B rendered far apart and
* then it is important to know whether the point is associated mostly with the
* A or the B to determine where to render it. If this is TRUE then we bind
* harder forward and in the case of a linebreak the caret would show on the next line.
*/
unsigned int m_bind_forward:1;
public:
/**
* @see SetBindDirection()
* @see GetBindDirection()
*/
enum BindDirection
{
BIND_BACKWARD,
BIND_FORWARD
};
/**
* Default constructor.
*/
SelectionBoundaryPoint()
: m_element(NULL),
m_offset(0),
m_bind_forward(0)
{}
/**
* Constructor.
*/
SelectionBoundaryPoint(HTML_Element* element, int offset)
: m_element(element),
m_offset(offset),
m_bind_forward(0)
{}
/**
* Other Constructor.
*/
SelectionBoundaryPoint(HTML_Element* element, HTML_Element* indicated_child)
: m_element(element),
m_offset(CalculateOffset(indicated_child)),
m_bind_forward(0)
{}
/**
* Copy constructor.
*/
SelectionBoundaryPoint(const SelectionBoundaryPoint& other)
: m_element(other.m_element),
m_offset(other.m_offset),
m_bind_forward(other.m_bind_forward)
{}
/**
* Empties the selection point.
*/
void Reset() { m_element = NULL; m_offset = 0; m_bind_forward = 0; }
/**
* Are these selection points equal? Only position is used in the
* camparison. Not bind direction.
*/
BOOL operator==(const SelectionBoundaryPoint& other_selection) const;
/**
* Copy constructor.
*/
void operator=(const SelectionBoundaryPoint& X);
/**
* Get the element.
*/
HTML_Element* GetElement() const { return m_element; }
/**
* Get character offset in text element. backwards compatible
* name. Use GetOffset() in new code.
*/
int GetTextElementCharacterOffset() const { return GetOffset(); }
/**
* Get the offset. For a text element this is the offset into the
* character string. For other elements it's the offset into the
* list of ActualStyle visible children. See the
* DOM Range specification for a more complete description including
* examples.
*/
int GetOffset() const { return m_offset; }
/** Set the logical position. This is an element and an offset
* into the element. The offset refers to the children or if
* it's a text node, the characters in the text.
*
* @see GetOffset()
*/
void SetLogicalPosition(HTML_Element* element, int offset);
/** Set the logical position just before an element.
*
* @param element The element before which selection point should point to.
*/
void SetLogicalPositionBeforeElement(HTML_Element* element);
/** Set the logical position just after an element.
*
* @param element The element after which selection point should point to.
*/
void SetLogicalPositionAfterElement(HTML_Element* element);
/**
* If a selection point has multiple visual positions (BiDi and line breaks
* make that happen), then this flag says which is preferred in rendering.
*
* For a line break, if the rendering should be on the previous line, the
* direction should be BIND_BACKWARD. If the rendering should be at the start
* of the new line, then the direction should be BIND_FORWARD.
*
* @param[in] direction The new bind direction.
*/
void SetBindDirection(BindDirection direction) { m_bind_forward = (direction == BIND_FORWARD); }
/**
* If a selection point has multiple visual positions (BiDi and line breaks
* make that happen), then this flag says which is preferred in rendering.
*
* @returns The direction. The default is BIND_BACKWARD.
*/
BindDirection GetBindDirection() const { return m_bind_forward ? BIND_FORWARD : BIND_BACKWARD; }
/**
* Get character offset in text element. backwards compatible
* name. Use GetOffset() in new code.
*/
int GetElementCharacterOffset() const { return GetOffset(); }
/**
* Does this text selection point precede other selection point? Slow
* method if called often (for every element or similar).
*/
BOOL Precedes(const SelectionBoundaryPoint& other_selection) const;
private:
static int CalculateOffset(HTML_Element* element);
};
#endif // !SELECTIONPOINT_H
|
#include "CGetGameSwitch.h"
#include "json/json.h"
#include "Logger.h"
#include "threadres.h"
#include "Lib_Ip.h"
#include <set>
#include "CConfig.h"
#include "RedisLogic.h"
#include "Helper.h"
int CGetGameSwitch::do_request(const Json::Value& root, char *client_ip, HttpResult& out)
{
//Json::Value ret;
//LOGGER(E_LOG_WARNING) <<"Begin CGetGameSwitch";
//int i = 1;
//MySqlDBAccess* dbMaster = ThreadResource::getInstance().getDBConnMgr()->DBMaster();
//if(dbMaster != NULL)
//{
// std::string sql = StrFormatA("SELECT * FROM logchip.log_member3 where mid = 22");
// MySqlResultSet* res = dbMaster->Query(sql.c_str());
// //for (; res->hasNext();)
// {
// LOGGER(E_LOG_WARNING) <<"Count:" << i;
// if (res && res->getRowNum() > 0)
// {
// LOGGER(E_LOG_WARNING) <<"111111111111111111111111111111";
// LOGGER(E_LOG_WARNING) <<res->getIntValue("id");
// LOGGER(E_LOG_WARNING) <<res->getIntValue("gameid");
// LOGGER(E_LOG_WARNING) <<res->getIntValue("mid");
// LOGGER(E_LOG_WARNING) <<res->getIntValue("money");
// LOGGER(E_LOG_WARNING) <<"2222222222222222222222222222222222222";
// int LandMoney = res->getIntValue("mid");
// //LandCount = res2->getIntValue("LandCount");
// LOGGER(E_LOG_WARNING) << "LandMoney" << LandMoney;
// }
// i++;
// }
//}
//Json::FastWriter jWriter;
out["status"] = 1;
CConfig& config = CConfig::getInstance();
Json::Value& paymentInfo = config.m_jvPaymentInfo;
out["phoneRegister"] = paymentInfo["phoneRegister"];
out["otherpay"] = paymentInfo["otherpay"];
out["pmode"] = paymentInfo["pmode"];
out["paytype"] = paymentInfo["paytype"];
out["othertype"] = paymentInfo["othertype"];
out["bank"] = paymentInfo["bank"];
out["bankinfo"]["bankno"] = paymentInfo["bankinfo"]["bankno"];
out["bankinfo"]["bankname"] = paymentInfo["bankinfo"]["bankname"];
out["bankinfo"]["username"] = paymentInfo["bankinfo"]["username"];
out["qrcodeinfo"][0] = "";
out["qrcodeinfo"][1] = "";
RedisAccess* rdMoney = RedisLogic::GetRdMoney();
if(rdMoney != NULL)
{
std::string strActivityOpen;
if (rdMoney->GET("ActivityOpen",strActivityOpen))
{
uint32_t ActivityOpen = atoi(strActivityOpen.c_str());
//为1 是打开
if(ActivityOpen == 1)
{
out["activityOpen"] = 1;
std::string strActivityBeginTime;
std::string strActivityEndTime;
if(rdMoney->GET("ActivityBeginTime",strActivityBeginTime) && rdMoney->GET("ActivityEndTime",strActivityEndTime))
{
int32_t ActivityBeginTime = atoi(strActivityBeginTime.c_str());
int32_t ActivityEndTime = atoi(strActivityEndTime.c_str());
int CurTime = time(NULL);
if(CurTime >= ActivityBeginTime && CurTime <= ActivityEndTime)
{
out["activityOpen"] = 1;
}
else
{
out["activityOpen"] = 0;
}
}
}
else
{
out["activityOpen"] = 0;
}
}
std::string strDrawOpen;
if (rdMoney->GET("DrawOpen",strDrawOpen))
{
uint32_t DrawOpen = atoi(strDrawOpen.c_str());
if(DrawOpen == 1)
{
out["darwOpen"] = 1;
}
else
{
out["darwOpen"] = 0;
}
}
}
else
{
out["darwOpen"] = 1;
}
int ctype, productid, version;
try {
ctype = root["ctype"].asInt();
productid = root["productid"].asInt();
version = root["versions"].asInt();
} catch (...) {
out["msg"] = "参数不正确";
//out = jWriter.write(ret);
LOGGER(E_LOG_INFO) << "client 参数不正确!!! pmode:" << out["pmode"].asString() << " ;otherpay: " << out["otherpay"].asString()<<" othertype:"<<out["othertype"].asString();
return status_param_error;
}
std::string strKey = StrFormatA("GameSwitch|%d" , productid);
std::string strField = StrFormatA("%d" , version);
std::string strRet;
RedisAccess* rdCommon = RedisLogic::GetRdCommon("slave");
if (NULL == rdCommon)
{
out["msg"] = "缓存服务器出错了";
LOGGER(E_LOG_INFO) << "client 缓存服务器出错了!!! pmode:" << out["pmode"].asString() << " ;otherpay: " << out["otherpay"].asString()<<" othertype:"<<out["othertype"].asString();
//return status_param_error;
}
else
{
if (rdCommon->HGET(strKey.c_str() , strField.c_str() , strRet) && !strRet.empty())
{
Json::Reader jReader;
Json::Value jsonconf;
jReader.parse(strRet , jsonconf);
out["phoneRegister"] = Json::SafeConverToInt32(jsonconf["phoneRegister"]);
out["paytype"] = Json::SafeConverToInt32(jsonconf["paytype"] , Json::SafeConverToInt32(out["paytype"]));
out["pmode"] = Json::SafeConverToInt32(jsonconf["pmode"] , Json::SafeConverToInt32(out["pmode"]));
out["othertype"] = Json::SafeConverToInt32(jsonconf["othertype"] , Json::SafeConverToInt32(out["othertype"]));
out["otherpay"] = Json::SafeConverToInt32(jsonconf["otherpay"] , Json::SafeConverToInt32(out["otherpay"]));
out["bank"] = Json::SafeConverToInt32(jsonconf["bank"] , Json::SafeConverToInt32(out["bank"]));
LOGGER(E_LOG_INFO) << "read common redis return is[ip:" << rdCommon->GetIp() << ",port:" << rdCommon->GetPort()
<< "]; msg : " << strRet << "; HGET Key Is : " << strKey << "; Field Is :" << strField
<< ";phoneRegister: " << out["phoneRegister"].asString() << ";otherpay: " << out["otherpay"].asString();
}
else
{
LOGGER(E_LOG_INFO) << "read common redis return false[ip:" << rdCommon->GetIp() << ",port:" << rdCommon->GetPort() << "]";
}
//新增支付方式二维码扫描下载
std::string strSetting1 , strSetting2;
Json::Value jvSetting1 , jvSetting2;
Json::Reader jrTmp;
if (rdCommon->HGET("RechargeQrcodeSetting|1" , "1" , strSetting1)) jrTmp.parse(strSetting1 , jvSetting1);
if (rdCommon->HGET("RechargeQrcodeSetting|2" , "1" , strSetting2)) jrTmp.parse(strSetting2 , jvSetting2);
out["qrcodeinfo"][0] = jvSetting1;
out["qrcodeinfo"][1] = jvSetting2;
}
vector<string> ip_arr = Lib_Ip::find(client_ip);
if(ip_arr.size() > 0)
{
LOGGER(E_LOG_INFO) << client_ip << " you country is:" << ip_arr[0];
/*
if (ip_arr[0] == "中国" || ip_arr[0] == "局域网" || ip_arr[0] == "柬埔寨")
{
is_china_ip = 1;
}*/
int is_china_ip = 0;
std::string strField = "xzip";
std::string strRet;
if(rdCommon->HGET(strKey.c_str(), strField.c_str(), strRet) && !strRet.empty())
{
vector<string> vsCountries = Helper::explode(strRet.c_str(), ",");
for (int i = 0 ; i < vsCountries.size(); i++)
{
if (vsCountries[i] == ip_arr[0])
{
is_china_ip = 1;
break;
}
}
}
if (strRet.empty())
{
is_china_ip = 1;
}
if (is_china_ip == 0)
{
LOGGER(E_LOG_INFO) << client_ip << " is_china_ip == 0";
out["otherpay"] = 0;
out["pmode"] = 8;
}
}
LOGGER(E_LOG_INFO) << "pmode:" << out["pmode"].asString() << " ;otherpay: " << out["otherpay"].asString()<<" othertype:"<<out["othertype"].asString();
// // 安卓默认汇支付
// if (ctype == 1)
// {
// out["otherpay"] = 2;
// }
return status_ok;
}
|
#include <stdio.h>
int main(void)
{
int rate=25;
float km;
float meter;
float total;
int bayad=1;
printf("enter kM\n");
scanf("%f",&km);
meter=km*1000;
while(meter>=280)
{
meter=meter-280;
bayad=bayad++;
}
total=bayad*2+rate-2;
printf("the amount due is: %.2f",total);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#ifdef _MAC_DEBUG
#include "platforms/mac/debug/OnScreen.h"
#include "platforms/mac/util/MachOCompatibility.h"
#ifdef NO_CARBON
extern short GetMenuBarHeight();
#define GetMBarHeight GetMenuBarHeight
#endif
#ifndef SIXTY_FOUR_BIT
static char gC1tab[] = {255, 210, 35, 30, 185, 180, 5, 0};
static short gC2tab[] = {0x000, 0x001f, 0x7c00, 0x7c1f, 0x03e0, 0x03ff, 0x7fe0, 0x7fff};
static long gC4tab[] = {0x00000000, 0x000000ff, 0x00ff0000, 0x00ff00ff, 0x0000ff00, 0x0000ffff, 0x00ffff00, 0x00ffffff};
static char gCharSet8[] =
{
0x00, // 0
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 1
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 2
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 3
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 4
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 5
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 6
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 7
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 8
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 9
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 10
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 11
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 12
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 13
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 14
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 15
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 16
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 17
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 18
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 19
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 20
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 21
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 22
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 23
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 24
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 25
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 26
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 27
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 28
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 29
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 30
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 31
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 32
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00, // 33
0x10,
0x10,
0x10,
0x10,
0x00,
0x10,
0x00,
0x00, // 34
0x24,
0x24,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00, // 35
0x24,
0x7E,
0x24,
0x24,
0x7E,
0x24,
0x00,
0x00, // 36
0x08,
0x3E,
0x28,
0x3E,
0x0A,
0x3E,
0x08,
0x00, // 37
0x62,
0x64,
0x08,
0x10,
0x26,
0x46,
0x00,
0x00, // 38
0x10,
0x28,
0x10,
0x2A,
0x44,
0x3A,
0x00,
0x00, // 39
0x08,
0x10,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00, // 40
0x04,
0x08,
0x08,
0x08,
0x08,
0x04,
0x00,
0x00, // 41
0x20,
0x10,
0x10,
0x10,
0x10,
0x20,
0x00,
0x00, // 42
0x00,
0x14,
0x08,
0x3E,
0x08,
0x14,
0x00,
0x00, // 43
0x00,
0x08,
0x08,
0x3E,
0x08,
0x08,
0x00,
0x00, // 44
0x00,
0x00,
0x00,
0x00,
0x08,
0x08,
0x10,
0x00, // 45
0x00,
0x00,
0x00,
0x3E,
0x00,
0x00,
0x00,
0x00, // 46
0x00,
0x00,
0x00,
0x00,
0x18,
0x18,
0x00,
0x00, // 47
0x00,
0x02,
0x04,
0x08,
0x10,
0x20,
0x00,
0x00, // 48
0x3C,
0x46,
0x4A,
0x52,
0x62,
0x3C,
0x00,
0x00, // 49
0x08,
0x18,
0x08,
0x08,
0x08,
0x3E,
0x00,
0x00, // 50
0x3C,
0x42,
0x02,
0x3C,
0x40,
0x7E,
0x00,
0x00, // 51
0x3C,
0x42,
0x0C,
0x02,
0x42,
0x3C,
0x00,
0x00, // 52
0x0C,
0x14,
0x24,
0x44,
0x7E,
0x04,
0x00,
0x00, // 53
0x7E,
0x40,
0x7C,
0x02,
0x42,
0x3C,
0x00,
0x00, // 54
0x3C,
0x40,
0x7C,
0x42,
0x42,
0x3C,
0x00,
0x00, // 55
0x7E,
0x02,
0x04,
0x08,
0x10,
0x10,
0x00,
0x00, // 56
0x3C,
0x42,
0x3C,
0x42,
0x42,
0x3C,
0x00,
0x00, // 57
0x3C,
0x42,
0x42,
0x3E,
0x02,
0x3C,
0x00,
0x00, // 58
0x00,
0x00,
0x10,
0x00,
0x00,
0x10,
0x00,
0x00, // 59
0x00,
0x10,
0x00,
0x00,
0x10,
0x10,
0x20,
0x00, // 60
0x00,
0x04,
0x08,
0x10,
0x08,
0x04,
0x00,
0x00, // 61
0x00,
0x00,
0x3E,
0x00,
0x3E,
0x00,
0x00,
0x00, // 62
0x00,
0x10,
0x08,
0x04,
0x08,
0x10,
0x00,
0x00, // 63
0x3C,
0x42,
0x04,
0x08,
0x00,
0x08,
0x00,
0x00, // 64
0x3C,
0x4A,
0x56,
0x5E,
0x40,
0x3C,
0x00,
0x00, // 65
0x3C,
0x42,
0x42,
0x7E,
0x42,
0x42,
0x00,
0x00, // 66
0x7C,
0x42,
0x7C,
0x42,
0x42,
0x7C,
0x00,
0x00, // 67
0x3C,
0x42,
0x40,
0x40,
0x42,
0x3C,
0x00,
0x00, // 68
0x78,
0x44,
0x42,
0x42,
0x44,
0x78,
0x00,
0x00, // 69
0x7E,
0x40,
0x7C,
0x40,
0x40,
0x7E,
0x00,
0x00, // 70
0x7E,
0x40,
0x7C,
0x40,
0x40,
0x40,
0x00,
0x00, // 71
0x3C,
0x42,
0x40,
0x4E,
0x42,
0x3C,
0x00,
0x00, // 72
0x42,
0x42,
0x7E,
0x42,
0x42,
0x42,
0x00,
0x00, // 73
0x3E,
0x08,
0x08,
0x08,
0x08,
0x3E,
0x00,
0x00, // 74
0x02,
0x02,
0x02,
0x42,
0x42,
0x3C,
0x00,
0x00, // 75
0x44,
0x48,
0x70,
0x48,
0x44,
0x42,
0x00,
0x00, // 76
0x40,
0x40,
0x40,
0x40,
0x40,
0x7E,
0x00,
0x00, // 77
0x42,
0x66,
0x5A,
0x42,
0x42,
0x42,
0x00,
0x00, // 78
0x42,
0x62,
0x52,
0x4A,
0x46,
0x42,
0x00,
0x00, // 79
0x3C,
0x42,
0x42,
0x42,
0x42,
0x3C,
0x00,
0x00, // 80
0x7C,
0x42,
0x42,
0x7C,
0x40,
0x40,
0x00,
0x00, // 81
0x3C,
0x42,
0x42,
0x52,
0x4A,
0x3C,
0x00,
0x00, // 82
0x7C,
0x42,
0x42,
0x7C,
0x44,
0x42,
0x00,
0x00, // 83
0x3C,
0x40,
0x3C,
0x02,
0x42,
0x3C,
0x00,
0x00, // 84
0xFE,
0x10,
0x10,
0x10,
0x10,
0x10,
0x00,
0x00, // 85
0x42,
0x42,
0x42,
0x42,
0x42,
0x3C,
0x00,
0x00, // 86
0x42,
0x42,
0x42,
0x42,
0x24,
0x18,
0x00,
0x00, // 87
0x42,
0x42,
0x42,
0x42,
0x5A,
0x24,
0x00,
0x00, // 88
0x42,
0x24,
0x18,
0x18,
0x24,
0x42,
0x00,
0x00, // 89
0x82,
0x44,
0x28,
0x10,
0x10,
0x10,
0x00,
0x00, // 90
0x7E,
0x04,
0x08,
0x10,
0x20,
0x7E,
0x00,
0x00, // 91
0x0E,
0x08,
0x08,
0x08,
0x08,
0x0E,
0x00,
0x00, // 92
0x00,
0x40,
0x20,
0x10,
0x08,
0x04,
0x00,
0x00, // 93
0x70,
0x10,
0x10,
0x10,
0x10,
0x70,
0x00,
0x00, // 94
0x10,
0x38,
0x54,
0x10,
0x10,
0x10,
0x00,
0x00, // 95
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0xFF,
0x00, // 96
0x1C,
0x22,
0x78,
0x20,
0x20,
0x7E,
0x00,
0x00, // 97
0x00,
0x38,
0x04,
0x3C,
0x44,
0x3C,
0x00,
0x00, // 98
0x20,
0x20,
0x3C,
0x22,
0x22,
0x3C,
0x00,
0x00, // 99
0x00,
0x1C,
0x20,
0x20,
0x20,
0x1C,
0x00,
0x00, // 100
0x04,
0x04,
0x3C,
0x44,
0x44,
0x3C,
0x00,
0x00, // 101
0x00,
0x38,
0x44,
0x78,
0x40,
0x3C,
0x00,
0x00, // 102
0x0C,
0x10,
0x18,
0x10,
0x10,
0x10,
0x00,
0x00, // 103
0x00,
0x3C,
0x44,
0x44,
0x3C,
0x04,
0x38,
0x00, // 104
0x40,
0x40,
0x78,
0x44,
0x44,
0x44,
0x00,
0x00, // 105
0x10,
0x00,
0x30,
0x10,
0x10,
0x38,
0x00,
0x00, // 106
0x04,
0x00,
0x04,
0x04,
0x04,
0x24,
0x18,
0x00, // 107
0x20,
0x28,
0x30,
0x30,
0x28,
0x24,
0x00,
0x00, // 108
0x10,
0x10,
0x10,
0x10,
0x10,
0x0C,
0x00,
0x00, // 109
0x00,
0x68,
0x54,
0x54,
0x54,
0x54,
0x00,
0x00, // 110
0x00,
0x78,
0x44,
0x44,
0x44,
0x44,
0x00,
0x00, // 111
0x00,
0x38,
0x44,
0x44,
0x44,
0x38,
0x00,
0x00, // 112
0x00,
0x78,
0x44,
0x44,
0x78,
0x40,
0x40,
0x00, // 113
0x00,
0x3C,
0x44,
0x44,
0x3C,
0x04,
0x06,
0x00, // 114
0x00,
0x1C,
0x20,
0x20,
0x20,
0x20,
0x00,
0x00, // 115
0x00,
0x38,
0x40,
0x38,
0x04,
0x78,
0x00,
0x00, // 116
0x10,
0x38,
0x10,
0x10,
0x10,
0x0C,
0x00,
0x00, // 117
0x00,
0x44,
0x44,
0x44,
0x44,
0x38,
0x00,
0x00, // 118
0x00,
0x44,
0x44,
0x28,
0x28,
0x10,
0x00,
0x00, // 119
0x00,
0x44,
0x54,
0x54,
0x54,
0x28,
0x00,
0x00, // 120
0x00,
0x44,
0x28,
0x10,
0x28,
0x44,
0x00,
0x00, // 121
0x00,
0x44,
0x44,
0x44,
0x3C,
0x04,
0x38,
0x00, // 122
0x00,
0x7C,
0x08,
0x10,
0x20,
0x7C,
0x00,
0x00, // 123
0x0E,
0x08,
0x30,
0x08,
0x08,
0x0E,
0x00,
0x00, // 124
0x08,
0x08,
0x08,
0x08,
0x08,
0x08,
0x00,
0x00, // 125
0x70,
0x10,
0x0C,
0x10,
0x10,
0x70,
0x00,
0x00, // 126
0x14,
0x28,
0x00,
0x00,
0x00,
0x00,
0x00,
0x3C, // 127
0x42,
0x99,
0xA1,
0xA1,
0x99,
0x42,
0x3C,
0x00, // 128
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x0F, // 129
0x0F,
0x0F,
0x0F,
0x00,
0x00,
0x00,
0x00,
0xF0, // 130
0xF0,
0xF0,
0xF0,
0x00,
0x00,
0x00,
0x00,
0xFF, // 131
0xFF,
0xFF,
0xFF,
0x00,
0x00,
0x00,
0x00,
0x00, // 132
0x00,
0x00,
0x00,
0x0F,
0x0F,
0x0F,
0x0F,
0x0F, // 133
0x0F,
0x0F,
0x0F,
0x0F,
0x0F,
0x0F,
0x0F,
0xF0, // 134
0xF0,
0xF0,
0xF0,
0x0F,
0x0F,
0x0F,
0x0F,
0xFF, // 135
0xFF,
0xFF,
0xFF,
0x0F,
0x0F,
0x0F,
0x0F,
0x00, // 136
0x00,
0x00,
0x00,
0xF0,
0xF0,
0xF0,
0xF0,
0x0F, // 137
0x0F,
0x0F,
0x0F,
0xF0,
0xF0,
0xF0,
0xF0,
0xF0, // 138
0xF0,
0xF0,
0xF0,
0xF0,
0xF0,
0xF0,
0xF0,
0xFF, // 139
0xFF,
0xFF,
0xFF,
0xF0,
0xF0,
0xF0,
0xF0,
0x00, // 140
0x00,
0x00,
0x00,
0xFF,
0xFF,
0xFF,
0xFF,
0x0F, // 141
0x0F,
0x0F,
0x0F,
0xFF,
0xFF,
0xFF,
0xFF,
0xF0, // 142
0xF0,
0xF0,
0xF0,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF, // 143
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0xFF,
0
};
static char gDigits8[] =
{
0x00,
0x3C,
0x46,
0x4A,
0x52,
0x62,
0x3C,
0x00,
0x00,
0x08,
0x18,
0x08,
0x08,
0x08,
0x3E,
0x00,
0x00,
0x3C,
0x42,
0x02,
0x3C,
0x40,
0x7E,
0x00,
0x00,
0x3C,
0x42,
0x0C,
0x02,
0x42,
0x3C,
0x00,
0x00,
0x0C,
0x14,
0x24,
0x44,
0x7E,
0x04,
0x00,
0x00,
0x7E,
0x40,
0x7C,
0x02,
0x42,
0x3C,
0x00,
0x00,
0x3C,
0x40,
0x7C,
0x42,
0x42,
0x3C,
0x00,
0x00,
0x7E,
0x02,
0x04,
0x08,
0x10,
0x10,
0x00,
0x00,
0x3C,
0x42,
0x3C,
0x42,
0x42,
0x3C,
0x00,
0x00,
0x3C,
0x42,
0x42,
0x3E,
0x02,
0x3C,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
0x7E,
0x00,
0x00,
0x00,
0x00,
0x00, // scratch
0x00, // scratch
0x00, // scratch
0x00 // scratch
};
static long gDigits5[] =
{
0x726AB270,
0x10C1047C,
0x3813907C,
0x39119138,
0x18A49F08,
0x7D078138,
0x39079138,
0x7C108410,
0x39139138,
0x3913C138,
0x00000000,
0x0007C000
};
/*
static long gDigits4[] =
{
0b01101011100111010110000000000000,
0b00100110001000100111000000000000,
0b11100001011010001111000000000000,
0b11100001011000011110000000000000,
0b00100110101011110010000000000000,
0b11111000111000011110000000000000,
0b01101000111010010110000000000000,
0b11110001001001000100000000000000,
0b01101001011010010110000000000000,
0b01101001011100010110000000000000,
0b00000000000000000000000000000000
};
*/
static long gDigits3[] =
{
0x4AAA4000,
0x4C44E000,
0xC248E000,
0xC242C000,
0x26AE2000,
0xE8C2C000,
0x48CA4000,
0xE2444000,
0x4A4A4000,
0x4A624000,
0x00000000,
0x00E00000
};
void DecOnScreen(int x, int y, int fgcolor, int bkcolor, long value)
{
enum
{
// kDigits = 10
kDigits = 6,
kHeight = 8
// kHeight = 6 // temporary changed for speeding up alittle
};
// static long oldValue = -1;
PixMapHandle mainPixMap;
register Ptr baseAddr;
short rowBytes;
register short gap;
register char bits;
register char *src;
register int v;
register int i;
register long d;
register char spaceflag;
register long pixelSizeB;
register long *p;
Boolean minus;
register int ex;
register int ey;
// if(oldValue == value)
// {
// return;
// }
// oldValue = value;
mainPixMap = (*LMGetMainDevice())->gdPMap;
ex = (*mainPixMap)->bounds.right;
ey = (*mainPixMap)->bounds.bottom;
if(x < 0)
{
x += ex;
}
if(y < 0)
{
y += ey;
}
else
{
y += GetMBarHeight();
}
if(x >= 0 && x < ex && y >= 0 && y < ey - 6)
{
rowBytes = (*mainPixMap)->rowBytes & 0x7fff;
baseAddr = (y * rowBytes) + (*mainPixMap)->baseAddr;
x += 8 * kDigits; // max. 10 digits
minus = value < 0;
if(minus)
{
value = -value;
}
switch((*mainPixMap)->pixelSize)
{
case 8:
{
register unsigned char set = gC1tab[fgcolor];
register unsigned char clr = gC1tab[bkcolor];
pixelSizeB = 1;
gap = rowBytes / sizeof(long);
spaceflag = false;
for(i = kDigits; i; i--)
{
x -= 8;
if(spaceflag)
{
d = 10;
if(minus)
{
minus = false;
d = 11;
}
}
else
{
d = value % 10;
value /= 10;
if(0 == value)
{
spaceflag = true;
}
}
src = &gDigits8[8 * d];
p = (long *) ((x * pixelSizeB) + baseAddr);
for(v = kHeight; v; v--)
{
bits = *src++;
p[0] = ((bits & 0x80 ? set : clr) << 24) | ((bits & 0x40 ? set : clr) << 16) | ((bits & 0x20 ? set : clr) << 8) | (bits & 0x10 ? set : clr);
p[1] = ((bits & 0x08 ? set : clr) << 24) | ((bits & 0x04 ? set : clr) << 16) | ((bits & 0x02 ? set : clr) << 8) | (bits & 0x01 ? set : clr);
p += gap;
}
}
}
break;
case 16:
{
register unsigned short set = gC2tab[fgcolor];
register unsigned short clr = gC2tab[bkcolor];
pixelSizeB = 2;
gap = rowBytes / sizeof(long);
spaceflag = false;
for(i = kDigits; i; i--)
{
x -= 8;
if(spaceflag)
{
d = 10;
if(minus)
{
minus = false;
d = 11;
}
}
else
{
d = value % 10;
value /= 10;
if(0 == value)
{
spaceflag = true;
}
}
src = &gDigits8[8 * d];
p = (long *) ((x * pixelSizeB) + baseAddr);
for(v = kHeight; v; v--)
{
bits = *src++;
p[0] = ((bits & 0x80 ? set : clr) << 16) | (bits & 0x40 ? set : clr);
p[1] = ((bits & 0x20 ? set : clr) << 16) | (bits & 0x10 ? set : clr);
p[2] = ((bits & 0x08 ? set : clr) << 16) | (bits & 0x04 ? set : clr);
p[3] = ((bits & 0x02 ? set : clr) << 16) | (bits & 0x01 ? set : clr);
p += gap;
}
}
}
break;
case 24:
case 32:
{
register long set = gC4tab[fgcolor];
register long clr = gC4tab[bkcolor];
pixelSizeB = 4;
gap = rowBytes / sizeof(long);
spaceflag = false;
for(i = kDigits; i; i--)
{
x -= 8;
if(spaceflag)
{
d = 10;
if(minus)
{
minus = false;
d = 11;
}
}
else
{
d = value % 10;
value /= 10;
if(0 == value)
{
spaceflag = true;
}
}
src = &gDigits8[8 * d];
p = (long *) ((x * pixelSizeB) + baseAddr);
for(v = kHeight; v; v--)
{
bits = *src++;
p[0] = bits & 0x80 ? set : clr;
p[1] = bits & 0x40 ? set : clr;
p[2] = bits & 0x20 ? set : clr;
p[3] = bits & 0x10 ? set : clr;
p[4] = bits & 0x08 ? set : clr;
p[5] = bits & 0x04 ? set : clr;
p[6] = bits & 0x02 ? set : clr;
p[7] = bits & 0x01 ? set : clr;
p += gap;
}
}
}
break;
}
}
}
void Str8OnScreen(int x, int y, int fgcolor, int bkcolor, char *format, ...)
{
enum
{
// kDigits = 10
kDigits = 6,
kHeight = 8
// kHeight = 6 // temporary changed for speeding up alittle
};
va_list marker;
PixMapHandle mainPixMap;
register Ptr baseAddr;
short rowBytes;
register short gap;
register char bits;
register char *src;
register char *s;
register int h;
register int v;
register int i;
register long c;
register long pixelSizeB;
register long *p;
char buf[513];
register int ex;
register int ey;
va_start(marker, format);
i = vsnprintf(buf, 512, format, marker);
buf[512] = '\0';
mainPixMap = (*LMGetMainDevice())->gdPMap;
ex = (*mainPixMap)->bounds.right;
ey = (*mainPixMap)->bounds.bottom;
if(x < 0)
{
x += ex;
}
if(y < 0)
{
y += ey;
}
else
{
y += GetMBarHeight();
}
if ((x < 0) || (y < 0) || ((x + 8) > ex) || ((y + 8) > ey))
return;
rowBytes = (*mainPixMap)->rowBytes & 0x7fff;
baseAddr = (y * rowBytes) + (*mainPixMap)->baseAddr;
h = (ex - x) / 8; // max string length
if(i > h)
{
i = h;
}
// x += 8 * kDigits; // max. 10 digits
s = buf;
switch((*mainPixMap)->pixelSize)
{
case 8:
{
register unsigned char set = gC1tab[fgcolor];
register unsigned char clr = gC1tab[bkcolor];
pixelSizeB = 1;
gap = rowBytes / sizeof(long);
while(i--)
{
c = 0xff & *s++;
p = (long *) ((x * pixelSizeB) + baseAddr);
src = &gCharSet8[8 * c];
for(v = kHeight; v; v--)
{
bits = *src++;
p[0] = ((bits & 0x80 ? set : clr) << 24) | ((bits & 0x40 ? set : clr) << 16) | ((bits & 0x20 ? set : clr) << 8) | (bits & 0x10 ? set : clr);
p[1] = ((bits & 0x08 ? set : clr) << 24) | ((bits & 0x04 ? set : clr) << 16) | ((bits & 0x02 ? set : clr) << 8) | (bits & 0x01 ? set : clr);
p += gap;
}
x += 8;
}
}
break;
case 16:
{
register unsigned short set = gC2tab[fgcolor];
register unsigned short clr = gC2tab[bkcolor];
pixelSizeB = 2;
gap = rowBytes / sizeof(long);
while(i--)
{
c = 0xff & *s++;
p = (long *) ((x * pixelSizeB) + baseAddr);
src = &gCharSet8[8 * c];
for(v = kHeight; v; v--)
{
bits = *src++;
p[0] = ((bits & 0x80 ? set : clr) << 16) | (bits & 0x40 ? set : clr);
p[1] = ((bits & 0x20 ? set : clr) << 16) | (bits & 0x10 ? set : clr);
p[2] = ((bits & 0x08 ? set : clr) << 16) | (bits & 0x04 ? set : clr);
p[3] = ((bits & 0x02 ? set : clr) << 16) | (bits & 0x01 ? set : clr);
p += gap;
}
x += 8;
}
}
break;
case 24:
case 32:
{
register long set = gC4tab[fgcolor];
register long clr = gC4tab[bkcolor];
pixelSizeB = 4;
gap = rowBytes / sizeof(long);
while(i--)
{
c = 0xff & *s++;
p = (long *) ((x * pixelSizeB) + baseAddr);
src = &gCharSet8[8 * c];
for(v = kHeight; v; v--)
{
bits = *src++;
p[0] = bits & 0x80 ? set : clr;
p[1] = bits & 0x40 ? set : clr;
p[2] = bits & 0x20 ? set : clr;
p[3] = bits & 0x10 ? set : clr;
p[4] = bits & 0x08 ? set : clr;
p[5] = bits & 0x04 ? set : clr;
p[6] = bits & 0x02 ? set : clr;
p[7] = bits & 0x01 ? set : clr;
p += gap;
}
x += 8;
}
}
break;
}
va_end(marker);
}
void Dec8OnScreen(int x, int y, int fgcolor, int bkcolor, long value) // just an alias for DecOnScreen
{
DecOnScreen(x, y, fgcolor, value, bkcolor);
}
void Dec3OnScreen(int x, int y, int fgcolor, int bkcolor, long value)
{
enum
{
// kDigits = 10
kDigits = 6,
kCellWidth = 4,
kCellHeight = 5,
kHeight = 5
};
// static long oldValue = -1;
PixMapHandle mainPixMap;
register Ptr baseAddr;
short rowBytes;
register short gap;
register long bits;
register int i;
register long d;
register char spaceflag;
register long pixelSizeB;
register long *p;
register int ex;
register int ey;
Boolean minus;
// if(oldValue == value)
// {
// return;
// }
// oldValue = value;
mainPixMap = (*LMGetMainDevice())->gdPMap;
ex = (*mainPixMap)->bounds.right;
ey = (*mainPixMap)->bounds.bottom;
if(x < 0)
{
x += ex;
}
if(y < 0)
{
y += ey;
}
else
{
y += GetMBarHeight();
}
if(x > 0 && x < ex && y > 0 && y < ey - 6)
{
rowBytes = (*mainPixMap)->rowBytes & 0x7fff;
baseAddr = (y * rowBytes) + (*mainPixMap)->baseAddr;
x += kCellWidth * kDigits; // max. 10 digits
minus = value < 0;
if(minus)
{
value = -value;
}
switch((*mainPixMap)->pixelSize)
{
case 8:
{
register unsigned char set = gC1tab[fgcolor];
register unsigned char clr = gC1tab[bkcolor];
pixelSizeB = 1;
gap = rowBytes / sizeof(long);
spaceflag = false;
for(i = kDigits; i; i--)
{
x -= kCellWidth;
if(spaceflag)
{
d = 10;
if(minus)
{
minus = false;
d = 11;
}
}
else
{
d = value % 10;
value /= 10;
if(0 == value)
{
spaceflag = true;
}
}
bits = gDigits3[d];
p = (long *) ((x * pixelSizeB) + baseAddr);
p[0] = ((bits & 0x80000000 ? set : clr) << 24) | ((bits & 0x40000000 ? set : clr) << 16) | ((bits & 0x20000000 ? set : clr) << 8) | (bits & 0x10000000 ? set : clr);
p += gap;
p[0] = ((bits & 0x08000000 ? set : clr) << 24) | ((bits & 0x04000000 ? set : clr) << 16) | ((bits & 0x02000000 ? set : clr) << 8) | (bits & 0x01000000 ? set : clr);
p += gap;
p[0] = ((bits & 0x00800000 ? set : clr) << 24) | ((bits & 0x00400000 ? set : clr) << 16) | ((bits & 0x00200000 ? set : clr) << 8) | (bits & 0x00100000 ? set : clr);
p += gap;
p[0] = ((bits & 0x00080000 ? set : clr) << 24) | ((bits & 0x00040000 ? set : clr) << 16) | ((bits & 0x00020000 ? set : clr) << 8) | (bits & 0x00010000 ? set : clr);
p += gap;
p[0] = ((bits & 0x00008000 ? set : clr) << 24) | ((bits & 0x00004000 ? set : clr) << 16) | ((bits & 0x00002000 ? set : clr) << 8) | (bits & 0x00001000 ? set : clr);
p[gap] = clr;
}
}
break;
case 16:
{
register unsigned short set = gC2tab[fgcolor];
register unsigned short clr = gC2tab[bkcolor];
pixelSizeB = 2;
gap = rowBytes / sizeof(long);
spaceflag = false;
for(i = kDigits; i; i--)
{
x -= kCellWidth;
if(spaceflag)
{
d = 10;
if(minus)
{
minus = false;
d = 11;
}
}
else
{
d = value % 10;
value /= 10;
if(0 == value)
{
spaceflag = true;
}
}
bits = gDigits3[d];
p = (long *) ((x * pixelSizeB) + baseAddr);
p[0] = ((bits & 0x80000000 ? set : clr) << 16) | (bits & 0x40000000 ? set : clr);
p[1] = ((bits & 0x20000000 ? set : clr) << 16) | (bits & 0x10000000 ? set : clr);
p += gap;
p[0] = ((bits & 0x08000000 ? set : clr) << 16) | (bits & 0x04000000 ? set : clr);
p[1] = ((bits & 0x02000000 ? set : clr) << 16) | (bits & 0x01000000 ? set : clr);
p += gap;
p[0] = ((bits & 0x00800000 ? set : clr) << 16) | (bits & 0x00400000 ? set : clr),
p[1] = ((bits & 0x00200000 ? set : clr) << 16) | (bits & 0x00100000 ? set : clr);
p += gap;
p[0] = ((bits & 0x00080000 ? set : clr) << 16) | (bits & 0x00040000 ? set : clr);
p[1] = ((bits & 0x00020000 ? set : clr) << 16) | (bits & 0x00010000 ? set : clr);
p += gap;
p[0] = ((bits & 0x00008000 ? set : clr) << 16) | (bits & 0x00004000 ? set : clr);
p[1] = ((bits & 0x00002000 ? set : clr) << 16) | (bits & 0x00001000 ? set : clr);
p[gap+0] = clr;
p[gap+1] = clr;
}
}
break;
case 24:
case 32:
{
register long set = gC4tab[fgcolor];
register long clr = gC4tab[bkcolor];
pixelSizeB = 4;
gap = rowBytes / sizeof(long);
spaceflag = false;
for(i = kDigits; i; i--)
{
x -= kCellWidth;
if(spaceflag)
{
d = 10;
if(minus)
{
minus = false;
d = 11;
}
}
else
{
d = value % 10;
value /= 10;
if(0 == value)
{
spaceflag = true;
}
}
bits = gDigits3[d];
p = (long *) ((x * pixelSizeB) + baseAddr);
p[0] = (bits & 0x80000000 ? set : clr);
p[1] = (bits & 0x40000000 ? set : clr);
p[2] = (bits & 0x20000000 ? set : clr);
p[3] = (bits & 0x10000000 ? set : clr);
p += gap;
p[0] = (bits & 0x08000000 ? set : clr);
p[1] = (bits & 0x04000000 ? set : clr);
p[2] = (bits & 0x02000000 ? set : clr);
p[3] = (bits & 0x01000000 ? set : clr);
p += gap;
p[0] = (bits & 0x00800000 ? set : clr);
p[1] = (bits & 0x00400000 ? set : clr);
p[2] = (bits & 0x00200000 ? set : clr);
p[3] = (bits & 0x00100000 ? set : clr);
p += gap;
p[0] = (bits & 0x00080000 ? set : clr);
p[1] = (bits & 0x00040000 ? set : clr);
p[2] = (bits & 0x00020000 ? set : clr);
p[3] = (bits & 0x00010000 ? set : clr);
p += gap;
p[0] = (bits & 0x00008000 ? set : clr);
p[1] = (bits & 0x00004000 ? set : clr);
p[2] = (bits & 0x00002000 ? set : clr);
p[3] = (bits & 0x00001000 ? set : clr);
p[gap+0] = clr;
p[gap+1] = clr;
p[gap+2] = clr;
p[gap+3] = clr;
}
}
break;
}
}
}
void Dec5OnScreen(int x, int y, int fgcolor, int bkcolor, long value)
{
enum
{
// kDigits = 10
kDigits = 6,
kCellWidth = 6 /* 4 */,
kCellHeight = 5,
kHeight = 5
};
// static long oldValue = -1;
PixMapHandle mainPixMap;
register Ptr baseAddr;
short rowBytes;
register short gap;
register long bits;
register int i;
register long d;
register char spaceflag;
register long pixelSizeB;
register long *p;
register int ex;
register int ey;
Boolean minus;
// if(oldValue == value)
// {
// return;
// }
// oldValue = value;
mainPixMap = (*LMGetMainDevice())->gdPMap;
ex = (*mainPixMap)->bounds.right;
ey = (*mainPixMap)->bounds.bottom;
if(x < 0)
{
x += ex;
if(x < 0)
{
x = 0;
}
}
if(y < 0)
{
y += ey;
if(y < 0)
{
y = 0;
}
}
else
{
y += GetMBarHeight();
}
if(y + 6 > ey)
{
y = 0;
}
if(x > 0 && x < ex && y > 0 && y < ey)
{
rowBytes = (*mainPixMap)->rowBytes & 0x7fff;
baseAddr = (y * rowBytes) + (*mainPixMap)->baseAddr;
x += kCellWidth * kDigits; // max. 10 digits
minus = value < 0;
if(minus)
{
value = -value;
}
switch((*mainPixMap)->pixelSize)
{
case 8:
{
register unsigned char set = gC1tab[fgcolor];
register unsigned char clr = gC1tab[bkcolor];
pixelSizeB = 1;
gap = rowBytes / sizeof(long);
spaceflag = false;
for(i = kDigits; i; i--)
{
x -= kCellWidth;
if(spaceflag)
{
d = 10;
if(minus)
{
minus = false;
d = 11;
}
}
else
{
d = value % 10;
value /= 10;
if(0 == value)
{
spaceflag = true;
}
}
bits = gDigits5[d];
p = (long *) ((x * pixelSizeB) + baseAddr);
p[0] = ((bits & 0x80000000 ? set : clr) << 24) | ((bits & 0x40000000 ? set : clr) << 16) | ((bits & 0x20000000 ? set : clr) << 8) | (bits & 0x10000000 ? set : clr);
*((short *) &p[1]) = ((bits & 0x08000000 ? set : clr) << 8) | (bits & 0x04000000 ? set : clr);
p += gap;
p[0] = ((bits & 0x02000000 ? set : clr) << 24) | ((bits & 0x01000000 ? set : clr) << 16) | ((bits & 0x08000000 ? set : clr) << 8) | (bits & 0x04000000 ? set : clr);
*((short *) &p[1]) = ((bits & 0x02000000 ? set : clr) << 8) | (bits & 0x01000000 ? set : clr);
p += gap;
p[0] = ((bits & 0x00800000 ? set : clr) << 24) | ((bits & 0x00400000 ? set : clr) << 16) | ((bits & 0x00200000 ? set : clr) << 8) | (bits & 0x00100000 ? set : clr);
*((short *) &p[1]) = ((bits & 0x00080000 ? set : clr) << 8) | (bits & 0x00040000 ? set : clr);
p += gap;
p[0] = ((bits & 0x00020000 ? set : clr) << 24) | ((bits & 0x00010000 ? set : clr) << 16) | ((bits & 0x00080000 ? set : clr) << 8) | (bits & 0x00040000 ? set : clr);
*((short *) &p[1]) = ((bits & 0x00020000 ? set : clr) << 8) | (bits & 0x00010000 ? set : clr);
p += gap;
p[0] = ((bits & 0x00008000 ? set : clr) << 24) | ((bits & 0x00004000 ? set : clr) << 16) | ((bits & 0x00002000 ? set : clr) << 8) | (bits & 0x00001000 ? set : clr);
*((short *) &p[1]) = ((bits & 0x00000800 ? set : clr) << 8) | (bits & 0x00000400 ? set : clr);
p[gap] = clr;
*((short *) &p[1]) = clr;
}
}
break;
case 16:
{
register unsigned short set = gC2tab[fgcolor];
register unsigned short clr = gC2tab[bkcolor];
pixelSizeB = 2;
gap = rowBytes / sizeof(long);
spaceflag = false;
for(i = kDigits; i; i--)
{
x -= kCellWidth;
if(spaceflag)
{
d = 10;
if(minus)
{
minus = false;
d = 11;
}
}
else
{
d = value % 10;
value /= 10;
if(0 == value)
{
spaceflag = true;
}
}
bits = gDigits5[d];
p = (long *) ((x * pixelSizeB) + baseAddr);
p[0] = ((bits & 0x80000000 ? set : clr) << 16) | (bits & 0x40000000 ? set : clr);
p[1] = ((bits & 0x20000000 ? set : clr) << 16) | (bits & 0x10000000 ? set : clr);
p[2] = ((bits & 0x08000000 ? set : clr) << 16) | (bits & 0x04000000 ? set : clr);
p += gap;
p[0] = ((bits & 0x02000000 ? set : clr) << 16) | (bits & 0x01000000 ? set : clr);
p[1] = ((bits & 0x00800000 ? set : clr) << 16) | (bits & 0x00400000 ? set : clr);
p[2] = ((bits & 0x00200000 ? set : clr) << 16) | (bits & 0x00100000 ? set : clr);
p += gap;
p[0] = ((bits & 0x00080000 ? set : clr) << 16) | (bits & 0x00040000 ? set : clr),
p[1] = ((bits & 0x00020000 ? set : clr) << 16) | (bits & 0x00010000 ? set : clr);
p[2] = ((bits & 0x00008000 ? set : clr) << 16) | (bits & 0x00004000 ? set : clr),
p += gap;
p[0] = ((bits & 0x00002000 ? set : clr) << 16) | (bits & 0x00001000 ? set : clr);
p[1] = ((bits & 0x00000800 ? set : clr) << 16) | (bits & 0x00000400 ? set : clr);
p[2] = ((bits & 0x00000200 ? set : clr) << 16) | (bits & 0x00000100 ? set : clr);
p += gap;
p[0] = ((bits & 0x00000080 ? set : clr) << 16) | (bits & 0x00000040 ? set : clr);
p[1] = ((bits & 0x00000020 ? set : clr) << 16) | (bits & 0x00000010 ? set : clr);
p[2] = ((bits & 0x00000008 ? set : clr) << 16) | (bits & 0x00000004 ? set : clr);
p[gap+0] = clr;
p[gap+1] = clr;
}
}
break;
case 24:
case 32:
{
register long set = gC4tab[fgcolor];
register long clr = gC4tab[bkcolor];
pixelSizeB = 4;
gap = rowBytes / sizeof(long);
spaceflag = false;
for(i = kDigits; i; i--)
{
x -= kCellWidth;
if(spaceflag)
{
d = 10;
if(minus)
{
minus = false;
d = 11;
}
}
else
{
d = value % 10;
value /= 10;
if(0 == value)
{
spaceflag = true;
}
}
bits = gDigits5[d];
p = (long *) ((x * pixelSizeB) + baseAddr);
p[0] = (bits & 0x80000000 ? set : clr);
p[1] = (bits & 0x40000000 ? set : clr);
p[2] = (bits & 0x20000000 ? set : clr);
p[3] = (bits & 0x10000000 ? set : clr);
p[4] = (bits & 0x08000000 ? set : clr);
p[5] = (bits & 0x04000000 ? set : clr);
p += gap;
p[0] = (bits & 0x02000000 ? set : clr);
p[1] = (bits & 0x01000000 ? set : clr);
p[2] = (bits & 0x00800000 ? set : clr);
p[3] = (bits & 0x00400000 ? set : clr);
p[4] = (bits & 0x00200000 ? set : clr);
p[5] = (bits & 0x00100000 ? set : clr);
p += gap;
p[0] = (bits & 0x00080000 ? set : clr);
p[1] = (bits & 0x00040000 ? set : clr);
p[2] = (bits & 0x00020000 ? set : clr);
p[3] = (bits & 0x00010000 ? set : clr);
p[4] = (bits & 0x00008000 ? set : clr);
p[5] = (bits & 0x00004000 ? set : clr);
p += gap;
p[0] = (bits & 0x00002000 ? set : clr);
p[1] = (bits & 0x00001000 ? set : clr);
p[2] = (bits & 0x00000800 ? set : clr);
p[3] = (bits & 0x00000400 ? set : clr);
p[4] = (bits & 0x00000200 ? set : clr);
p[5] = (bits & 0x00000100 ? set : clr);
p += gap;
p[0] = (bits & 0x00000080 ? set : clr);
p[1] = (bits & 0x00000040 ? set : clr);
p[2] = (bits & 0x00000020 ? set : clr);
p[3] = (bits & 0x00000010 ? set : clr);
p[4] = (bits & 0x00000008 ? set : clr);
p[5] = (bits & 0x00000004 ? set : clr);
p[gap+0] = clr;
p[gap+1] = clr;
p[gap+2] = clr;
p[gap+3] = clr;
p[gap+4] = clr;
p[gap+5] = clr;
}
}
break;
}
}
}
void PutPixel(int x, int y, int color)
{
PixMapHandle mainPixMap;
short rowBytes;
char *cp;
short *sp;
long *lp;
mainPixMap = (*LMGetMainDevice())->gdPMap;
rowBytes = (*mainPixMap)->rowBytes & 0x7fff;
y += GetMBarHeight();
switch((*mainPixMap)->pixelSize)
{
case 8:
cp = ((x) + (y * rowBytes) + (*mainPixMap)->baseAddr);
*cp = gC1tab[color];
break;
case 16:
sp = (short *) ((x << 1) + (y * rowBytes) + (*mainPixMap)->baseAddr);
*sp = gC2tab[color];
break;
case 24:
case 32:
lp = (long *) ((x << 2) + (y * rowBytes) + (*mainPixMap)->baseAddr);
*lp = gC4tab[color];
break;
}
}
void Put4Pixel(int x, int y, int color)
{
PixMapHandle mainPixMap;
short rowBytes;
char *cp;
short *sp;
long *lp;
mainPixMap = (*LMGetMainDevice())->gdPMap;
rowBytes = (*mainPixMap)->rowBytes & 0x7fff;
y += GetMBarHeight();
switch((*mainPixMap)->pixelSize)
{
case 8:
cp = ((x) + (y * rowBytes) + (*mainPixMap)->baseAddr);
// cp[0] = gC1tab[color];
// cp[1] = gC1tab[color];
cp[0] = gC1tab[kOnScreenBlack];
cp[1] = gC1tab[kOnScreenWhite];
cp = (char *) ((long) cp + rowBytes);
cp[0] = gC1tab[color];
cp[1] = gC1tab[color];
break;
case 16:
sp = (short *) ((x << 1) + (y * rowBytes) + (*mainPixMap)->baseAddr);
// sp[0] = gC2tab[color];
// sp[1] = gC2tab[color];
sp[0] = gC2tab[kOnScreenBlack];
sp[1] = gC2tab[kOnScreenWhite];
sp = (short *) ((long) sp + rowBytes);
sp[0] = gC2tab[color];
sp[1] = gC2tab[color];
break;
case 24:
case 32:
lp = (long *) ((x << 2) + (y * rowBytes) + (*mainPixMap)->baseAddr);
// lp[0] = gC4tab[color];
// lp[1] = gC4tab[color];
lp[0] = gC4tab[kOnScreenBlack];
lp[1] = gC4tab[kOnScreenWhite];
lp = (long *) ((long) lp + rowBytes);
lp[0] = gC4tab[color];
lp[1] = gC4tab[color];
break;
}
}
static short gLockupMark[] =
{
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x0000,
0x07E0,
0x0C30,
0x0C30,
0x0C30,
0x0C30,
0x3FFC,
0x3FFC,
0x3FFC,
0x3FFC,
0x3FFC,
0x3FFC,
0x0000,
0x0000,
0x0000
};
void LockupMark()
{
PixMapHandle mainPixMap;
short rowBytes;
register char *cp;
register short *sp;
register long *lp;
register short *src, data;
register char cset, cclr;
register short sset, sclr;
register long lset, lclr;
int x;
int y;
int color;
src = &gLockupMark[16];
mainPixMap = (*LMGetMainDevice())->gdPMap;
rowBytes = (*mainPixMap)->rowBytes & 0x7fff;
x = 640;
y = 1;
color = kOnScreenRed;
// y += GetMBarHeight();
switch((*mainPixMap)->pixelSize)
{
case 8:
cclr = gC1tab[kOnScreenBlack];
cset = gC1tab[color];
cp = ((x) + (y * rowBytes) + (*mainPixMap)->baseAddr);
for(y = 0; y < 16; y++)
{
data = *src++;
for(x = 0; x < 16; x++)
{
if(data & 0x8000)
{
*cp++ = cset;
}
else
{
*cp++ = cclr;
}
data = data << 1;
}
}
break;
case 16:
sclr = gC2tab[kOnScreenBlack];
sset = gC2tab[color];
sp = (short *) ((x << 1) + (y * rowBytes) + (*mainPixMap)->baseAddr);
for(y = 0; y < 16; y++)
{
data = *src++;
for(x = 0; x < 16; x++)
{
if(data & 0x8000)
{
*sp++ = sset;
}
else
{
*sp++ = sclr;
}
data = data << 1;
}
}
break;
case 24:
case 32:
lclr = gC4tab[kOnScreenBlack];
lset = gC4tab[color];
lp = (long *) ((x << 2) + (y * rowBytes) + (*mainPixMap)->baseAddr);
for(y = 0; y < 16; y++)
{
data = *src++;
for(x = 0; x < 16; x++)
{
if(data & 0x8000)
{
*lp++ = lset;
}
else
{
*lp++ = lclr;
}
data = data << 1;
}
}
break;
}
}
#endif // SIXTY_FOUR_BIT
#endif // MAC_DEBUG
|
#include<cstdio>
#include<algorithm>
using namespace std;
int n,k;
int e[11];
struct per
{
int data;
int bian;
}w[20100];
bool cmp(per x,per y)
{
if(x.data==y.data)
return x.bian<y.bian;
return x.data>y.data;
}
int main()
{
scanf("%d%d",&n,&k);
for(int i=1;i<=10;i++)
scanf("%d",&e[i]);
for(int j=1;j<=n;j++)
{
w[j].bian=j;
scanf("%d",&w[j].data);
}
sort(w+1,w+n+1,cmp);
for(int j=1;j<=n;j++)
w[w[j].bian].data+=e[(w[j].bian-1)%10+1];
sort(w+1,w+n+1,cmp);
for(int i=1;i<=k;i++)
printf("%d ",w[i].bian);
}
|
#pragma once
#include "Command.h"
class MoveCommand : public Command
{
private:
int mX, mY;
MoveCommand();
public:
MoveCommand(int x, int y);
~MoveCommand();
void enter();
void execute(MovableObject* obj);
void exit();
};
|
/*
Author: Manish Kumar
Username: manicodebits
Created: 11:04:31 11-04-2021
*/
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define PI 3.141592653589
#define MOD 1000000007
#define FAST_IO ios_base::sync_with_stdio(false), cin.tie(0)
#define deb(x) cout<<"[ "<<#x<<" = "<<x<<"] "
void solve(){
map<int,int> mp;
int n;cin>>n;
vector<int> arr(n);
for(int i=0;i<n;i++)
cin>>arr[i],mp[arr[i]]++;
for(int i=0;i<n;i++)
{
if(mp[arr[i]]==1)
{
cout<<i+1<<"\n";
return;
}
}
}
signed main(){
FAST_IO;
int t=1;
cin>>t;
while(t--)
solve();
return 0;
}
|
//
// serial.cpp
// serialowabaza
//
// Created by Julia on 06.11.2018.
// Copyright © 2018 Julia. All rights reserved.
//
#include <stdio.h>
#include "serial.h"
void serial::prezentujsie(){
ogladadlo::prezentujsie();
std::cout<<"Jest to serial o średniej ocen "<<ocena<<". Czas trwania pojedynczego odcinka wynosi "<<CzasTrwania<<"h.";
}
void serial::save(std::fstream &plik){
ogladadlo::save(plik);
}
|
/*
* Copyright (c) 2014-2017 Detlef Vollmann, vollmann engineering gmbh
*
* 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 CANVAS_HH_SEEN_
#define CANVAS_HH_SEEN_
#include "shape.hh"
#include "extgraph.hh"
#include "xwin.hh"
#include <optional>
#include <vector>
#include <string>
namespace exercise
{
struct CanvasHelperClass
{
~CanvasHelperClass()
{
fn();
}
std::function<void()> fn = [](){};
};
class CanvasImpl
{
public:
CanvasImpl(CanvasImpl&& other);
CanvasImpl(CanvasImpl const&) = delete;
CanvasImpl& operator=(CanvasImpl&& other);
CanvasImpl& operator=(CanvasImpl const&) = delete;
CanvasImpl(int width, int height, std::string const &name);
void operator+=(Shape *);
void draw() const;
void show() const;
void startLoop();
OptionalShapeRef getShape(const std::string& name);
private:
std::unique_ptr<GuiWin> win;
std::unique_ptr<cairo_surface_t, std::function<void(cairo_surface_t *)>> surface;
std::unique_ptr<cairo_t, std::function<void(cairo_t *)>> cr;
std::vector<UPShape> elems;
std::unordered_map<std::string, Shape*> shapeMap; // name is key, val is the address from vector of unique_ptr
// CanvasHelperClass helperCallback;
CanvasHelperClass helperClass;
};
class Canvas
{
public:
Canvas(int width, int height, std::string const &name);
Canvas() = default;
Canvas(Canvas&) = default;
Canvas(Canvas&&) = default;
Canvas& operator=(Canvas&) = default;
Canvas& operator=(Canvas&&) = default;
~Canvas() = default;
Canvas(Canvas const&) = delete;
Canvas& operator=(Canvas const&) = delete;
OptionalShapeRef getShape(const std::string& name);
void operator+=(Shape *);
void draw() const;
void show() const;
void startLoop();
private:
std::unique_ptr<CanvasImpl> pImpl;
};
} // namespace exercise
#endif /* CANVAS_HH_SEEN_ */
|
/*
Question => Given a square martix A and its numbers of rows (or columns) N,
return the transpose of A.
The transpose of a matrix is the matrix flipped over it's main
diagonals, swithching the row and column indices of the matrix.
Suppose in the original matrix 2 is present at (0,1) then in the transposed matrix it will come
at (1,0) position. Which means that (row, cloumn) = (column, row)
So we swap (row, cloumn) with (column, row) then we will get the desired answer
But we will only swap the elements of the uper triangle, or else we will get the same matrix again.
*/
#include<iostream>
using namespace std;
int main(){
int A[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
for(int i=0; i<3; i++){
for(int j=i; j<3; j++){
// Swap
int temp = A[i][j];
A[i][j] = A[j][i];
A[j][i] = temp;
}
}
// Print
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
cout<<A[i][j] <<" ";
}
cout<<"\n";
}
return 0;
}
|
#pragma once
#include <thread>
/////////////////////////////////////////////////////////////////////
// MsgClient.h - Starts Client Sender and Receivers //
// ver 1.0 //
// Lanaguage: C++ Visual Studio 2015 //
// Platform: Dell XPS L510X - Windows 10 //
// Application: Project#4 - CSE 687-Object Oriented Design //
// Author: Rohit Sharma, Syracuse University //
// (315) 935-1323, rshar102@syr.edu //
/////////////////////////////////////////////////////////////////////
/*
* Required Files:
* MsgClient.cpp
* HttpMessage.h, HttpMessage.cpp
* Cpp11-BlockingQueue.h
* Sockets.h, Sockets.cpp
* FileSystem.h, FileSystem.cpp
* Logger.h, Logger.cpp
* Utilities.h, Utilities.cpp
Module Operations:
==================
This class defines startClientSenderThread and startClientSenderThread and void startClient();to start client threads.
Public Interface:
=================
void startClientSenderThread();
void startClientReceiverThread();
void startClient();
Build Process:
==============
Required files
Build commands (either one)
- devenv CommPrototype.sln /rebuild debug
Maintenance History:
====================
ver 1.0 : 03 May 16
- first release
*/
class MsgClient
{
public:
std::thread startClientSenderThread();
std::thread startClientReceiverThread();
void startClient();
};
|
// Created on: 1998-07-28
// Created by: LECLERE Florence
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TopOpeBRepBuild_FuseFace_HeaderFile
#define _TopOpeBRepBuild_FuseFace_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <TopTools_ListOfShape.hxx>
#include <Standard_Boolean.hxx>
class TopOpeBRepBuild_FuseFace
{
public:
DEFINE_STANDARD_ALLOC
TopOpeBRepBuild_FuseFace();
TopOpeBRepBuild_FuseFace(const TopTools_ListOfShape& LIF, const TopTools_ListOfShape& LRF, const Standard_Integer CXM);
Standard_EXPORT void Init (const TopTools_ListOfShape& LIF, const TopTools_ListOfShape& LRF, const Standard_Integer CXM);
Standard_EXPORT void PerformFace();
Standard_EXPORT void PerformEdge();
Standard_EXPORT void ClearEdge();
Standard_EXPORT void ClearVertex();
Standard_Boolean IsDone() const;
Standard_Boolean IsModified() const;
const TopTools_ListOfShape& LFuseFace() const;
const TopTools_ListOfShape& LInternEdge() const;
const TopTools_ListOfShape& LExternEdge() const;
const TopTools_ListOfShape& LModifEdge() const;
const TopTools_ListOfShape& LInternVertex() const;
const TopTools_ListOfShape& LExternVertex() const;
const TopTools_ListOfShape& LModifVertex() const;
protected:
TopTools_ListOfShape myLIE;
TopTools_ListOfShape myLEE;
TopTools_ListOfShape myLME;
TopTools_ListOfShape myLIV;
TopTools_ListOfShape myLEV;
TopTools_ListOfShape myLMV;
private:
TopTools_ListOfShape myLIF;
TopTools_ListOfShape myLRF;
TopTools_ListOfShape myLFF;
Standard_Boolean myInternal;
Standard_Boolean myModified;
Standard_Boolean myDone;
};
#include <TopOpeBRepBuild_FuseFace.lxx>
#endif // _TopOpeBRepBuild_FuseFace_HeaderFile
|
// Implements
#include "ThrottleController.h"
// For: std::abs
#include <complex>
ThrottleController::ThrottleController(double Kp_, double Ki_, double Kd_, bool optimize)
: pid{Kp_, Ki_, Kd_}, is_optimized{optimize} { }
ThrottleController::~ThrottleController() { }
double ThrottleController::update(double cte) {
if(is_optimized) opt.run(pid);
pid.UpdateError(cte);
double throttle_value = pid.TotalError();
if (throttle_value < 0) return 0.0;
if (throttle_value > 1.0) return 0.95;
return throttle_value;
}
|
#ifndef LEVELMODEL_H
#define LEVELMODEL_H
#include <SFML\System\Vector2.hpp>
//RHYTHMS: Density, RhythmType, Length
enum Density
{
low, // = 0, 3, 4
medium, // = 1, 5, 8
high // = 2, 10, 16
};
enum RhythmType
{
regular,
swing,
random
};
//ACTIONS: Verb, Direction, Starttime, Stoptime
enum Verb
{
move,
brake,
wait
};
enum Direction
{
left,
right
};
enum keyword
{
move_left_ledge,
move_right_ledge,
moving_block_single,
platform_left,
platform_right,
move_left_hinder,
move_right_hinder,
other
};
//A rhythm is the pre-stage to a level-segment
struct rhythm
{
int length = 20; //{5,10,15,20}
Density density = Density::medium;
RhythmType type = RhythmType::regular;
};
struct action
{
Verb word;
Direction direction;
double starttime;
double stoptime;
};
struct geometry
{
keyword type;
sf::Vector2f position;
sf::Vector2f size = sf::Vector2f();
};
struct rhythmgroup
{
//std::list<state> states;
//std::queue<brake> brakes;
};
struct player
{
sf::Vector2f speed = sf::Vector2f(30, 30);
sf::Vector2f scale = sf::Vector2f(5, 5);
sf::Vector2f position = sf::Vector2f();
};
class MyEnums
{
public:
static std::string ToString(Density value)
{
std::string outString;
switch (value)
{
case low:
outString = "low";
break;
case medium:
outString = "medium";
break;
case high:
outString = "high";
break;
default:
break;
}
return outString;
}
static std::string ToString(RhythmType value)
{
std::string outString;
switch (value)
{
case regular:
outString = "regular";
break;
case swing:
outString = "swing";
break;
case random:
outString = "random";
break;
default:
break;
}
return outString;
}
static std::string ToString(Verb value)
{
std::string outString;
switch (value)
{
case move:
outString = "move";
break;
case brake:
outString = "brake";
break;
case wait:
outString = "wait";
break;
default:
break;
}
return outString;
}
static std::string ToString(keyword value)
{
std::string outString;
switch (value)
{
case move_left_ledge:
outString = "move_left_ledge";
break;
case move_right_ledge:
outString = "move_right_ledge";
break;
case moving_block_single:
outString = "moving_block_single";
break;
case platform_left:
case platform_right:
outString = "resting_platform";
break;
case move_left_hinder:
outString = "move_left_hinder";
break;
case move_right_hinder:
outString = "move_left_hinder";
break;
case other:
outString = "other";
break;
default:
break;
}
return outString;
}
};
#endif
|
#include "wali/graph/RegExp.hpp"
#include "wali/graph/GraphCommon.hpp"
#include <math.h>
#include <algorithm>
#include <iterator>
#include <cassert>
#include <sstream>
#if defined(PPP_DBG)
#include "wali/SemElemTensor.hpp"
#endif
namespace wali {
namespace graph {
RegExpDag::RegExpDag()
{
currentSatProcess = 0;
extend_backwards = false;
saturation_complete = false;
executing_poststar = true;
initialized = false;
top_down_eval = true;
}
reg_exp_t RegExpDag::updatable(node_no_t nno, sem_elem_t se)
{
if(saturation_complete) {
cerr << "RegExp: Error: cannot create updatable nodes when saturation is complete\n";
assert(!initialized);
assert(0);
}
if(updatable_nodes.size() > nno) {
#if defined(PPP_DBG) && PPP_DBG >= 0
// This node will likely get used now.
reg_exp_key_t insKey(updatable_nodes[nno]->type, updatable_nodes[nno]);
rootsInSatProcess.insert(insKey, updatable_nodes[nno]);
#endif
return updatable_nodes[nno];
}
for(size_t i = updatable_nodes.size(); i < nno; i++) {
// These nodes are being created proactively. They aren't referenced in the
// graphs yet, so don't add them to roots.
RegExp * r = new RegExp(currentSatProcess, this, i,se->zero());
updatable_nodes.push_back(r);
}
// Create the desired updatable node, and add it to roots
reg_exp_t r = new RegExp(currentSatProcess, this, nno, se);
#if defined(PPP_DBG) && PPP_DBG >= 0
reg_exp_key_t insKey(r->type, r);
rootsInSatProcess.insert(insKey, r);
#endif
updatable_nodes.push_back(r);
return updatable_nodes[nno];
}
int RegExp::updatableNumber() {
assert(type == Updatable);
return (int)updatable_node_no;
}
#if defined(PUSH_EVAL)
void RegExp::setDirty()
{
if(dirty)
return;
dirty = true;
for(wali::util::unordered_set<RegExp*>::iterator
pit = parents.begin(); pit != parents.end(); ++pit)
{
(*pit)->setDirty();
}
}
#endif
// Updates all the updatable edgses given in the list together, so that all of them
// get the same update_count.
void RegExpDag::update(std::vector<node_no_t> nnos, std::vector<sem_elem_t> ses)
{
//Make sure that correct number of weights were passed in.
assert(nnos.size() == ses.size() && "[RegExp::update] Sizes of input vectors must match\n");
if(saturation_complete) {
cerr << "RegExp: Error: cannot update nodes when saturation is complete\n";
assert(!initialized);
assert(0);
}
unsigned int &update_count = satProcesses[currentSatProcess].update_count;
for(unsigned i = 0; i < nnos.size(); ++i){
node_no_t nno = nnos[i];
sem_elem_t se = ses[i];
updatable(nno,se); // make sure that this node exists
if(!updatable_nodes[nno]->value->equal(se)) {
#ifdef DWPDS
updatable_nodes[nno]->delta[update_count+1] = se->diff(updatable_nodes[nno]->value);
#endif
updatable_nodes[nno]->value = se;
updatable_nodes[nno]->last_change = update_count + 1;
updatable_nodes[nno]->last_seen = update_count + 1;
#if defined(PUSH_EVAL)
updatable_nodes[nno]->setDirty();
#endif
updatable_nodes[nno]->eval_map.clear();
updatable_nodes[nno]->updates.push_back(update_count);
}
}
update_count = update_count + 1;
}
void RegExpDag::update(node_no_t nno, sem_elem_t se) {
if(saturation_complete) {
cerr << "RegExp: Error: cannot update nodes when saturation is complete\n";
assert(!initialized);
assert(0);
}
updatable(nno,se); // make sure that this node exists
if(!updatable_nodes[nno]->value->equal(se)) {
unsigned int &update_count = satProcesses[currentSatProcess].update_count;
updatable_nodes[nno]->updates.push_back(update_count);
#ifdef DWPDS
updatable_nodes[nno]->delta[update_count+1] = se->diff(updatable_nodes[nno]->value);
#endif
update_count = update_count + 1;
updatable_nodes[nno]->value = se;
updatable_nodes[nno]->last_change = update_count;
updatable_nodes[nno]->last_seen = update_count;
#if defined(PUSH_EVAL)
updatable_nodes[nno]->setDirty();
#endif
updatable_nodes[nno]->eval_map.clear();
}
//updates.push_back(nno);
}
ostream &operator << (ostream &out, const RegExpStats &s) {
out << "Semiring Extend : " << s.nextend << "\n";
out << "Semiring Combine : " << s.ncombine << "\n";
out << "Semiring Star : " << s.nstar << "\n";
out << "Semiring Ops : " << (s.nstar + s.ncombine + s.nextend) << "\n";
out << "HashMap hits : "<< s.hashmap_hits << "\n";
out << "HashMap misses : " << s.hashmap_misses << "\n";
return out;
}
ostream &RegExp::print(ostream &out) {
switch(type) {
case Constant:
value->print(out);
break;
case Updatable:
out << "U" << updatable_node_no << "(";
value->print(out) << ")";
break;
case Star:
out << "(";
(children.front())->print(out);
out << ")*";
break;
case Extend: {
list<reg_exp_t>::iterator it;
it = children.begin();
out << "(";
(*it)->print(out) << ")";
it++;
for(; it != children.end(); it++) {
out << " x (";
(*it)->print(out) << ")";
}
break;
}
case Combine: {
list<reg_exp_t>::iterator it;
it = children.begin();
out << "(";
(*it)->print(out) << ")";
it++;
for(; it != children.end(); it++) {
out << " + (";
(*it)->print(out) << ")";
}
break;
}
}
return out;
}
// nextLbl is the next label *to be used*
// The returned label is the *last label used* and the label for the *returning node*.
long RegExp::toDot(ostream& out, std::set<long>& seen, bool printUpdates, bool isRoot)
{
hash_sem_elem hse;
long me;
bool isZero = false, isOne = false;
if(value != NULL){
isZero = value->equal(value->zero());
isOne = value->equal(value->one());
}else{
isZero = true;
}
const long myptr = (const long) this;
stringstream updatess;
switch(type){
case Constant:
me = hse(value);
if(seen.find(me) != seen.end())
return me;
if(isRoot)
out << "n" << me << "[label = \""
<< "constant \\n "
<< "(root)\\n "
<< "zero: " << isZero << "\\n "
<< "one: " << isOne << "\\n "
<< "\" color=red];\n";
else
out << "n" << me << "[label = \""
<< "constant \\n "
<< "zero: " << isZero << "\\n "
<< "one: " << isOne << "\\n "
<< "\"];\n";
seen.insert(me);
return me;
case Updatable:
//me = hse(value);
me = updatable_node_no;
//updates
if(printUpdates){
updatess << "updates: ";
for(vector<unsigned>::iterator it = updates.begin(); it != updates.end(); ++it)
updatess << *it << " ";
}
if(seen.find(me) != seen.end())
return me;
if(isRoot)
out << "n" << me << "[label = \""
<< "updatable\\n "
<< "(root) \\n "
<< "zero: " << isZero << "\\n "
<< "one: " << isOne << "\\n "
<< updatess.str() << "\\n"
<< "\" color=red];\n";
else
out << "n" << me << "[label = \""
<< "updatable\\n "
<< "zero: " << isZero << "\\n "
<< "one: " << isOne << "\\n "
<< updatess.str() << "\\n"
<< "\" color=brown];\n";
seen.insert(me);
return me;
case Combine:
case Extend:
case Star:
default:
break;
}
vector<long int> others;
reg_exp_key_t rkey(type, this);
hash_reg_exp_key hrek;
me = hrek(rkey);
if(seen.find(me) != seen.end()){
return me;
}
seen.insert(me);
//evaluations
stringstream evaluatess;
if(printUpdates){
evaluatess << "evaluations: ";
for(vector<unsigned>::iterator it = evaluations.begin(); it != evaluations.end(); ++it)
evaluatess << *it << " ";
}
for(list<reg_exp_t>::iterator it = children.begin(); it != children.end(); it++)
others.push_back((*it)->toDot(out, seen, printUpdates));
switch(type){
case Constant:
case Updatable:
break;
case Star:
if(isRoot)
out << "n" << me << "[label = \""
<< "*\\n "
<< "(root)\\n "<< myptr << "\\n "
<< "zero: " << isZero << "\\n "
<< "one: " << isOne << "\\n "
<< evaluatess.str() << "\\n"
<< "\" color=red];\n";
else
out << "n" << me << "[label = \""
<< "*\\n " << myptr << "\\n "
<< "zero: " << isZero << "\\n "
<< "one: " << isOne << "\\n "
<< evaluatess.str() << "\\n"
<< "\" color=aquamarine];\n";
break;
case Combine:
if(isRoot)
out << "n" << me << "[label = \""
<< "+\\n "
<< "(root)\\n "<< myptr << "\\n "
<< "zero: " << isZero << "\\n "
<< "one: " << isOne << "\\n "
<< evaluatess.str() << "\\n"
<< "\" color=red];\n";
else
out << "n" << me << "[label = \""
<< "+\\n " << myptr << "\\n "
<< "zero: " << isZero << "\\n "
<< "one: " << isOne << "\\n "
<< evaluatess.str() << "\\n"
<< "\" color=blue];\n";
break;
case Extend:
if(isRoot)
out << "n" << me << "[label = \""
<< "x\\n "
<< "(root)\\n "<< myptr << "\\n "
<< "zero: " << isZero << "\\n "
<< "one: " << isOne << "\\n "
<< evaluatess.str() << "\\n"
<< "\" color=red];\n";
else
out << "n" << me << "[label = \""
<< "x\\n " << myptr << "\\n "
<< "zero: " << isZero << "\\n "
<< "one: " << isOne << "\\n "
<< evaluatess.str() << "\\n"
<< "\" color=green];\n";
break;
default:
assert(false && "[RegExp::toDot] Unknown RegExp Type.\n");
}
for(vector<long>::iterator it = others.begin(); it != others.end(); it++)
out << "n" << me << " -> n" << *it << "\n";
return me;
}
// need not return an evaluated reg_exp
reg_exp_t RegExpDag::star(reg_exp_t r) {
if(r->type == Star) {
return r;
}
#ifndef REGEXP_CACHING
reg_exp_t res;
if(r->type == Constant && r->value->equal(r->value->zero()))
res = new RegExp(currentSatProcess, this, r->value->one());
else
res = new RegExp(currentSatProcess, this, Star, r);
#if defined(PPP_DBG) && PPP_DBG >= 0
// Manipulate the set of root nodes.
// remove r from roots.
reg_exp_key_t delkey(r->type, r);
rootsInSatProcess.erase(delkey);
// Add the new regexp to roots
reg_exp_key_t inskey(res->type, res);
rootsInSatProcess.insert(inskey, res);
#endif
return res;
#else // REGEXP_CACHING
if(r->type == Constant) {
if(r->value->equal(r->value->one()) || r->value->equal(r->value->zero())) {
assert(r == reg_exp_one || r == reg_exp_zero);
return reg_exp_one;
}
}
reg_exp_key_t rkey(Star, r);
reg_exp_hash_t::iterator it = reg_exp_hash.find(rkey);
if(it == reg_exp_hash.end()) {
reg_exp_t res = new RegExp(currentSatProcess, this, Star, r);
reg_exp_hash.insert(rkey, res);
#if defined(PPP_DBG) && PPP_DBG >= 0
// Manipulate the set of root nodes.
// remove r from roots.
reg_exp_key_t delkey(r->type, r);
rootsInSatProcess.erase(delkey);
// Add the new regexp to roots
reg_exp_key_t inskey(res->type, res);
rootsInSatProcess.insert(inskey, res);
#endif
STAT(stats.hashmap_misses++);
return res;
}
STAT(stats.hashmap_hits++);
return it->second;
#endif // REGEXP_CACHING
}
reg_exp_t RegExpDag::combine(std::list<reg_exp_t> & rlist)
{
if(rlist.size() == 0)
return reg_exp_zero;
if(rlist.size() == 1)
return *(rlist.begin());
std::list<reg_exp_t>::iterator it = rlist.begin();
reg_exp_t res = *it;
it++;
for(;it != rlist.end(); ++it)
res = combine(res, *it);
return res;
}
reg_exp_t RegExpDag::combine(reg_exp_t r1, reg_exp_t r2) {
if(r1.get_ptr() == r2.get_ptr())
return r1;
if(r1->type == Constant && r1->value->equal(r1->value->zero())) {
return r2;
} else if(r2->type == Constant && r2->value->equal(r2->value->zero())) {
return r1;
}
#ifndef REGEXP_CACHING
reg_exp_t res = new RegExp(currentSatProcess, this, Combine, r1, r2);
#if defined(PPP_DBG) && PPP_DBG >= 0
// Manipulate the set of root nodes.
// remove r1,r2 from roots.
reg_exp_key_t del1key(r1->type, r1);
rootsInSatProcess.erase(del1key);
reg_exp_key_t del2key(r2->type, r2);
rootsInSatProcess.erase(del2key);
// Add the new regexp to roots
reg_exp_key_t inskey(res->type, res);
rootsInSatProcess.insert(inskey, res);
#endif
return res;
#else
reg_exp_key_t rkey1(Combine, r1, r2);
reg_exp_hash_t::iterator it = reg_exp_hash.find(rkey1);
if(it == reg_exp_hash.end()) {
STAT(stats.hashmap_misses++);
reg_exp_key_t rkey2(Combine, r2, r1);
it = reg_exp_hash.find(rkey2);
// NAK - fold this if underneath the upper one
// - didn't make sense the other way.
if(it == reg_exp_hash.end()) {
reg_exp_t res = new RegExp(currentSatProcess, this, Combine, r1, r2);
reg_exp_hash.insert(rkey2, res);
#if defined(PPP_DBG) && PPP_DBG >= 0
// Manipulate the set of root nodes.
// remove r1,r2 from roots.
reg_exp_key_t del1key(r1->type, r1);
rootsInSatProcess.erase(del1key);
reg_exp_key_t del2key(r2->type, r2);
rootsInSatProcess.erase(del2key);
// Add the new regexp to roots
reg_exp_key_t inskey(res->type, res);
rootsInSatProcess.insert(inskey, res);
#endif
STAT(stats.hashmap_misses++);
return res;
}
}
STAT(stats.hashmap_hits++);
return it->second;
#endif // REGEXP_CACHING
}
reg_exp_t RegExpDag::extend(reg_exp_t r1, reg_exp_t r2) {
if(extend_backwards) {
reg_exp_t tmp = r1;
r1 = r2;
r2 = tmp;
}
if(r1->type == Constant && r1->value->equal(r1->value->zero())) {
return r1;
} else if(r2->type == Constant && r2->value->equal(r2->value->zero())) {
return r2;
}
#ifndef REGEXP_CACHING
reg_exp_t res = new RegExp(currentSatProcess, this, Extend, r1, r2);
#if defined(PPP_DBG) && PPP_DBG >= 0
// Manipulate the set of root nodes.
// remove r1,r2 from roots.
reg_exp_key_t del1key(r1->type, r1);
rootsInSatProcess.erase(del1key);
reg_exp_key_t del2key(r2->type, r2);
rootsInSatProcess.erase(del2key);
// Add the new regexp to roots
reg_exp_key_t inskey(res->type, res);
rootsInSatProcess.insert(inskey, res);
#endif
return res;
#else
if(r1->type == Constant && r1->value->equal(r1->value->one())) {
return r2;
} else if(r2->type == Constant && r2->value->equal(r2->value->one())) {
return r1;
}
reg_exp_key_t rkey(Extend, r1, r2);
reg_exp_hash_t::iterator it = reg_exp_hash.find(rkey);
if(it == reg_exp_hash.end()) {
reg_exp_t res = new RegExp(currentSatProcess, this, Extend, r1, r2);
reg_exp_hash.insert(rkey, res);
#if defined(PPP_DBG) && PPP_DBG >= 0
// Manipulate the set of root nodes.
// remove r1,r2 from roots.
reg_exp_key_t del1key(r1->type, r1);
rootsInSatProcess.erase(del1key);
reg_exp_key_t del2key(r2->type, r2);
rootsInSatProcess.erase(del2key);
// Add the new regexp to roots
reg_exp_key_t inskey(res->type, res);
rootsInSatProcess.insert(inskey, res);
#endif
STAT(stats.hashmap_misses++);
return res;
}
STAT(stats.hashmap_hits++);
return it->second;
#endif // REGEXP_CACHING
}
reg_exp_t RegExpDag::constant(sem_elem_t se) {
if(se->equal(se->zero()))
return reg_exp_zero;
#ifndef REGEXP_CACHING
reg_exp_t res = new RegExp(currentSatProcess, this, se);
#if defined(PPP_DBG) && PPP_DBG >= 0
reg_exp_key_t insKey(res->type, res);
rootsInSatProcess.insert(insKey, res);
#endif
return res;
#else
if(se->equal(se->one()))
return reg_exp_one;
const_reg_exp_hash_t::iterator it = const_reg_exp_hash.find(se);
if(it == const_reg_exp_hash.end()) {
reg_exp_t res = new RegExp(currentSatProcess, this, se);
const_reg_exp_hash.insert(se, res);
#if defined(PPP_DBG) && PPP_DBG >= 0
reg_exp_key_t insKey(res->type, res);
rootsInSatProcess.insert(insKey, res);
#endif
return res;
}
return it->second;
#endif // REGEXP_CACHING
}
void RegExpDag::startSatProcess(const sem_elem_t se) {
if(initialized) {
cerr << "Error: RegExp initialized twice\n";
assert(0);
}
initialized = true;
satProcesses.push_back(RegExpSatProcess());
currentSatProcess = satProcesses.size() - 1;
reg_exp_hash.clear();
const_reg_exp_hash.clear();
#if defined(PPP_DBG) && PPP_DBG >= 0
// The set of root nodes is cleared between saturation phases.
// but only after transferring the set to rootsAcrossSatProcesses
for(reg_exp_hash_t::iterator it = rootsInSatProcess.begin(); it != rootsInSatProcess.end(); ++it)
rootsAcrossSatProcesses.insert(*it);
rootsInSatProcess.clear();
#endif
for(reg_exp_hash_t::iterator it = graphLabelsInSatProcess.begin(); it != graphLabelsInSatProcess.end(); ++it)
graphLabelsAcrossSatProcesses.insert(*it);
graphLabelsInSatProcess.clear();
updatable_nodes.clear();
reg_exp_zero = new RegExp(currentSatProcess, this, se->zero());
reg_exp_key_t insZeroKey(reg_exp_zero->type, reg_exp_zero);
reg_exp_one = new RegExp(currentSatProcess, this, se->one());
reg_exp_key_t insOneKey(reg_exp_one->type, reg_exp_one);
#if defined(PPP_DBG) && PPP_DBG >= 0
rootsInSatProcess.insert(insZeroKey, reg_exp_zero);
rootsInSatProcess.insert(insOneKey, reg_exp_one);
#endif
saturation_complete = false;
executing_poststar = true;
}
void RegExpDag::stopSatProcess() {
if(!initialized) {
cerr << "Error: RegExp reset twice without being init-ed\n";
assert(0);
}
initialized = false;
saturation_complete = true;
updatable_nodes.clear();
}
#if defined(PPP_DBG) && PPP_DBG >= 0
const reg_exp_hash_t& RegExpDag::getRoots()
{
return rootsInSatProcess;
}
#endif
// a = a union b
void my_set_union(std::set<long int> &a, std::set<long int> &b) {
std::set<long int> c;
insert_iterator< set<long int> > ii(c, c.begin());
std::set_union(a.begin(), a.end(), b.begin(), b.end(), ii);
a = c;
}
typedef pair<int, reg_exp_t> heap_t;
struct cmp_heap_t {
bool operator() (heap_t e1, heap_t e2) const {
return (e1.first < e2.first) ? true :
(e1.first > e2.first) ? false :
(e1.second.get_ptr() < e2.second.get_ptr());
}
};
// This is a wrapper to manipulate the roots data structure only once
// per call to minimize_height
reg_exp_t RegExpDag::minimize_height(reg_exp_t r, reg_exp_cache_t& cache)
{
reg_exp_t res = _minimize_height(r,cache);
#if defined(PPP_DBG) && PPP_DBG >= 0
// If r was a root, replace it with res
reg_exp_key_t delKey(r->type, r);
if(rootsInSatProcess.find(delKey) != rootsInSatProcess.end()){
rootsInSatProcess.erase(delKey);
reg_exp_key_t insKey(res->type, res);
rootsInSatProcess.insert(insKey, res);
}
#endif
return res;
}
reg_exp_t RegExpDag::_minimize_height(reg_exp_t r, reg_exp_cache_t &cache) {
reg_exp_cache_t::iterator cpos = cache.find(r);
if(cpos != cache.end()) {
return cpos->second;
}
if(r->type == Constant) {
return r;
}
if(r->type == Updatable) {
r->outnodes.insert(r->updatable_node_no);
return r;
}
if(r->type == Star || r->type == Combine) {
reg_exp_t res = new RegExp(currentSatProcess, this, r->value->zero());
list<reg_exp_t>::iterator it;
for(it = r->children.begin(); it != r->children.end(); it++) {
reg_exp_t temp = minimize_height(*it, cache);
res->children.push_back(temp);
my_set_union(res->outnodes, temp->outnodes);
}
res->type = r->type;
res->value = r->value;
res->last_seen = r->last_seen;
res->last_change = r->last_change;
cache[r] = res;
return res;
}
// Now r->type == Extend
#define MINIMIZE_HEIGHT 2
#if MINIMIZE_HEIGHT==1 // Commutative Huffman-style tree
list<reg_exp_t>::iterator it;
multiset< heap_t, cmp_heap_t > heap;
for(it = r->children.begin(); it != r->children.end(); it++) {
reg_exp_t temp = minimize_height(*it, cache);
heap.insert(heap_t(temp->outnodes.size(), temp));
}
while(heap.size() != 1) {
heap_t e1 = *heap.begin();
heap.erase(heap.begin());
heap_t e2 = *heap.begin();
heap.erase(heap.begin());
reg_exp_t res = new RegExp(currentSatProcess, this, Extend, e1.second, e2.second);
res->value = r->value;
res->last_seen = r->last_seen;
res->last_change = r->last_change;
my_set_union(res->outnodes, e1.second->outnodes);
my_set_union(res->outnodes, e2.second->outnodes);
heap.insert(heap_t(e1.second->outnodes.size() + e2.second->outnodes.size(), res));
}
reg_exp_t ans = (*heap.begin()).second;
#elif MINIMIZE_HEIGHT==2 // Non-Commutative Huffman-style tree
list<reg_exp_t>::iterator it;
list<reg_exp_t> heap;
for(it = r->children.begin(); it != r->children.end(); it++) {
reg_exp_t temp = minimize_height(*it, cache);
heap.push_back(temp);
}
while(heap.size() != 1) {
list<reg_exp_t>::iterator min_pos = heap.begin(), next_it;
size_t min = (*min_pos)->outnodes.size();
it = heap.begin();
it++;
min += (*it)->outnodes.size();
for(; it != heap.end(); it++) {
next_it = it;
next_it++;
if(next_it == heap.end())
break;
if( (*it)->outnodes.size() + (*next_it)->outnodes.size() < min) {
min_pos = it;
min = (*it)->outnodes.size() + (*next_it)->outnodes.size();
}
}
next_it = min_pos; next_it++;
reg_exp_t r1 = (*min_pos);
heap.erase(min_pos);
min_pos = next_it; next_it++;
reg_exp_t r2 = (*min_pos);
heap.erase(min_pos);
min_pos = next_it;
reg_exp_t res = new RegExp(currentSatProcess, this, Extend, r1, r2);
res->value = r->value;
res->last_seen = r->last_seen;
res->last_change = r->last_change;
my_set_union(res->outnodes, r1->outnodes);
my_set_union(res->outnodes, r2->outnodes);
heap.insert(min_pos,res);
}
reg_exp_t ans = heap.front();
#elif MINIMIZE_HEIGHT==3 // Binary tree
list<reg_exp_t>::iterator it, next_it;
list<reg_exp_t> *list1 = new list<reg_exp_t>;
list<reg_exp_t> *list2 = new list<reg_exp_t>;
list<reg_exp_t> *temp;
for(it = r->children.begin(); it != r->children.end(); it++) {
reg_exp_t temp = minimize_height(*it, cache);
list1->push_back(temp);
}
while(list1->size() != 1) {
for(it = list1->begin(); it != list1->end(); it++) {
next_it = it; next_it++;
if(next_it == list1->end()) {
list2->push_back(*it);
} else {
reg_exp_t r1 = *it, r2 = *next_it;
reg_exp_t res = new RegExp(currentSatProcess, this, Extend, r1, r2);
res->value = r->value;
res->last_seen = r->last_seen;
res->last_change = r->last_change;
list2->push_back(res);
it++;
}
}
list1->clear();
temp = list1; list1 = list2; list2 = temp;
}
reg_exp_t ans = list1->front();
#endif
cache[r] = ans;
return ans;
}
// This is a wrapper around _compress to manipulate the roots
// hashmap only once per call to compress
reg_exp_t RegExpDag::compress(reg_exp_t r, reg_exp_cache_t &cache)
{
reg_exp_t res = _compress(r,cache);
#if defined(PPP_DBG) && PPP_DBG >= 0
// If r was a root, replace it with res
reg_exp_key_t delKey(r->type, r);
if(rootsInSatProcess.find(delKey) != rootsInSatProcess.end()){
rootsInSatProcess.erase(delKey);
reg_exp_key_t insKey(res->type, res);
rootsInSatProcess.insert(insKey, res);
}
#endif
return res;
}
// precond: Extend and Combine have 2 successors and Star has 1
// postcond: r is not changed
reg_exp_t RegExpDag::_compress(reg_exp_t r, reg_exp_cache_t &cache) {
reg_exp_cache_t::iterator cpos = cache.find(r);
if(cpos != cache.end()) {
return cpos->second;
}
if(r->type == Constant || r->type == Updatable) {
// no need to cache these
return r;
}
if(r->type == Star) {
reg_exp_t ch = r->children.front();
ch = compress(ch, cache);
if(ch->type == Star) {
cache[r] = ch;
return ch;
}
reg_exp_t res = new RegExp(currentSatProcess, this, Star,ch);
res->last_seen = r->last_seen;
res->last_change = r->last_change;
res->value = r->value;
cache[r] = res;
return res;
}
reg_exp_t res;
if(r->type == Extend) {
assert(r->children.size() == 2);
list<reg_exp_t>::iterator it = r->children.begin();
reg_exp_t r1 = *it;
it++;
reg_exp_t r2 = *it;
r1 = compress(r1, cache);
r2 = compress(r2, cache);
res = compressExtend(r1,r2);
} else if(r->type == Combine) {
list<reg_exp_t>::iterator it = r->children.begin();
reg_exp_t r1 = *it;
it++;
reg_exp_t r2 = *it;
r1 = compress(r1, cache);
r2 = compress(r2, cache);
res = compressCombine(r1,r2);
}
if(res->type == Constant || res->type == Updatable) {
res->last_seen = 1;
res->last_change = 1;
} else {
res->last_seen = r->last_seen;
res->last_change = r->last_change;
res->value = r->value;
}
cache[r] = res;
return res;
}
reg_exp_t RegExpDag::compressCombine(reg_exp_t r1, reg_exp_t r2) {
if(r1.get_ptr() == r2.get_ptr()) {
return r1;
}
if(r1->type == Constant && r2->type == Constant) {
reg_exp_t res = new RegExp(currentSatProcess, this, r1->value->combine(r2->value));
STAT(stats.ncombine++);
return res;
}
reg_exp_t res = new RegExp(currentSatProcess, this, r1->value->zero());
res->type = Combine;
if(r1->type == Combine && r2->type == Combine) {
reg_exp_t fc1 = r1->children.front();
reg_exp_t fc2 = r2->children.front();
if(fc1->type == Constant && fc2->type == Constant) {
reg_exp_t fc = new RegExp(currentSatProcess, this, fc1->value->combine(fc2->value));
STAT(stats.ncombine++);
res->children.push_back(fc);
res->children.insert(res->children.end(), ++r1->children.begin(), r1->children.end());
res->children.insert(res->children.end(), ++r2->children.begin(), r2->children.end());
} else if(fc2->type == Constant) {
res->children.push_back(fc2);
res->children.insert(res->children.end(), r1->children.begin(), r1->children.end());
res->children.insert(res->children.end(), ++r2->children.begin(), r2->children.end());
} else {
res->children.insert(res->children.end(), r1->children.begin(), r1->children.end());
res->children.insert(res->children.end(), r2->children.begin(), r2->children.end());
}
return res;
}
if(r1->type == Constant && r2->type == Combine) {
reg_exp_t fc2 = r2->children.front();
if(fc2->type == Constant) {
reg_exp_t fc = new RegExp(currentSatProcess, this, fc2->value->combine(r1->value));
STAT(stats.ncombine++);
res->children.push_back(fc);
res->children.insert(res->children.end(), ++r2->children.begin(), r2->children.end());
return res;
}
}
if(r1->type == Combine && r2->type == Constant) {
reg_exp_t fc1 = r1->children.front();
if(fc1->type == Constant) {
reg_exp_t fc = new RegExp(currentSatProcess, this, fc1->value->combine(r2->value));
STAT(stats.ncombine++);
res->children.push_back(fc);
res->children.insert(res->children.end(), ++r1->children.begin(), r1->children.end());
return res;
}
}
if(r1->type == Combine) {
res->children.insert(res->children.end(), r1->children.begin(), r1->children.end());
res->children.push_back(r2);
return res;
}
if(r2->type == Combine) {
res->children.insert(res->children.end(), r2->children.begin(), r2->children.end());
res->children.push_back(r1);
return res;
}
if(r2->type == Constant) {
res->children.push_back(r2);
res->children.push_back(r1);
} else {
res->children.push_back(r1);
res->children.push_back(r2);
}
return res;
}
reg_exp_t RegExpDag::compressExtend(reg_exp_t r1, reg_exp_t r2) {
#ifndef COMMUTATIVE_EXTEND
if(r1->type == Constant && r2->type == Constant) {
reg_exp_t res = new RegExp(currentSatProcess, this, r1->value->extend(r2->value));
STAT(stats.nextend++);
return res;
}
reg_exp_t res = new RegExp(currentSatProcess, this, r1->value->zero());
res->type = Extend;
if(r1->type == Extend && r2->type == Extend) {
reg_exp_t lc = r1->children.back();
reg_exp_t fc = r2->children.front();
if(lc->type == Constant && fc->type == Constant) {
reg_exp_t mc = new RegExp(currentSatProcess, this, lc->value->extend(fc->value));
STAT(stats.nextend++);
res->children.insert(res->children.end(), r1->children.begin(), --r1->children.end());
res->children.push_back(mc);
res->children.insert(res->children.end(), ++r2->children.begin(), r2->children.end());
} else {
res->children.insert(res->children.end(), r1->children.begin(), r1->children.end());
res->children.insert(res->children.end(), r2->children.begin(), r2->children.end());
}
return res;
}
if(r1->type == Constant && r2->type == Extend) {
reg_exp_t fc = r2->children.front();
if(fc->type == Constant) {
reg_exp_t f = new RegExp(currentSatProcess, this, r1->value->extend(fc->value));
STAT(stats.nextend++);
res->children.push_back(f);
res->children.insert(res->children.end(), ++r2->children.begin(), r2->children.end());
return res;
}
}
if(r1->type == Extend && r2->type == Constant) {
reg_exp_t lc = r1->children.back();
if(lc->type == Constant) {
reg_exp_t l = new RegExp(currentSatProcess, this, lc->value->extend(r2->value));
STAT(stats.nextend++);
res->children.insert(res->children.end(), r1->children.begin(), --r1->children.end());
res->children.push_back(l);
return res;
}
}
if(r1->type == Extend) {
res->children.insert(res->children.end(), r1->children.begin(), r1->children.end());
res->children.push_back(r2);
return res;
}
if(r2->type == Extend) {
res->children.insert(res->children.end(), r2->children.begin(), r2->children.end());
res->children.push_front(r1);
return res;
}
res->children.push_back(r1);
res->children.push_back(r2);
return res;
#else // COMMUTATIVE_EXTEND
if(r1->type == Constant && r2->type == Constant) {
reg_exp_t res = new RegExp(currentSatProcess, this, r1->value->extend(r2->value));
STAT(stats.nextend++);
return res;
}
reg_exp_t res = new RegExp(currentSatProcess, this, r1->value->zero());
res->type = Extend;
if(r1->type == Extend && r2->type == Extend) {
reg_exp_t fc1 = r1->children.front();
reg_exp_t fc2 = r2->children.front();
if(fc1->type == Constant && fc2->type == Constant) {
reg_exp_t fc = new RegExp(currentSatProcess, this, fc1->value->extend(fc2->value));
STAT(stats.nextend++);
res->children.push_back(fc);
res->children.insert(res->children.end(), ++r1->children.begin(), r1->children.end());
res->children.insert(res->children.end(), ++r2->children.begin(), r2->children.end());
} else if(fc2->type == Constant) {
res->children.push_back(fc2);
res->children.insert(res->children.end(), r1->children.begin(), r1->children.end());
res->children.insert(res->children.end(), ++r2->children.begin(), r2->children.end());
} else {
res->children.insert(res->children.end(), r1->children.begin(), r1->children.end());
res->children.insert(res->children.end(), r2->children.begin(), r2->children.end());
}
return res;
}
if(r1->type == Constant && r2->type == Extend) {
reg_exp_t fc2 = r2->children.front();
if(fc2->type == Constant) {
reg_exp_t fc = new RegExp(currentSatProcess, this, fc2->value->extend(r1->value));
STAT(stats.nextend++);
res->children.push_back(fc);
res->children.insert(res->children.end(), ++r2->children.begin(), r2->children.end());
return res;
}
}
if(r1->type == Extend && r2->type == Constant) {
reg_exp_t fc1 = r1->children.front();
if(fc1->type == Constant) {
reg_exp_t fc = new RegExp(currentSatProcess, this, fc1->value->extend(r2->value));
STAT(stats.nextend++);
res->children.push_back(fc);
res->children.insert(res->children.end(), ++r1->children.begin(), r1->children.end());
return res;
}
}
if(r1->type == Extend) {
res->children.insert(res->children.end(), r1->children.begin(), r1->children.end());
res->children.push_back(r2);
return res;
}
if(r2->type == Extend) {
res->children.insert(res->children.end(), r2->children.begin(), r2->children.end());
res->children.push_back(r1);
return res;
}
if(r2->type == Constant) {
res->children.push_back(r2);
res->children.push_back(r1);
} else {
res->children.push_back(r1);
res->children.push_back(r2);
}
return res;
#endif
}
int RegExp::calculate_height(set<RegExp *> &visited, out_node_stat_t &stat_map) {
assert(stat_map.size() == 0);
if(visited.find(this) != visited.end()) {
stat_map = outnode_height;
out_node_stat_t::iterator it;
for(it = stat_map.begin(); it != stat_map.end(); it++) {
it->second = out_node_height_t(0,0); // reset value because visited=true
}
return 0;
}
int changestat = samechange; // (samechange - differentchange) + 1;
visited.insert(this);
switch(type) {
case Constant:
break;
case Updatable:
stat_map[updatable_node_no] = out_node_height_t(0,0);
break;
case Star: {
assert(children.size() == 1);
list<reg_exp_t>::iterator ch = children.begin();
out_node_stat_t stat_map_ch;
changestat += (*ch)->calculate_height(visited,stat_map_ch);
out_node_stat_t::iterator it;
for(it = stat_map_ch.begin(); it != stat_map_ch.end(); it++) {
stat_map[it->first] = out_node_height_t(it->second.first + 1, it->second.second + 1);
}
break;
}
case Extend: {
list<reg_exp_t>::iterator ch;
for(ch = children.begin(); ch != children.end(); ch++) {
out_node_stat_t stat_map_ch;
changestat += (*ch)->calculate_height(visited,stat_map_ch);
out_node_stat_t::iterator it;
for(it = stat_map_ch.begin(); it != stat_map_ch.end(); it++) {
if(stat_map.find(it->first) == stat_map.end()) {
stat_map[it->first] = out_node_height_t(it->second.first + (children.size() -1), it->second.second);
} else {
out_node_height_t h = stat_map[it->first];
stat_map[it->first] = out_node_height_t(h.first + it->second.first, h.second + it->second.second);
}
}
}
break;
}
case Combine: {
list<reg_exp_t>::iterator ch;
for(ch = children.begin(); ch != children.end(); ch++) {
out_node_stat_t stat_map_ch;
changestat += (*ch)->calculate_height(visited,stat_map_ch);
out_node_stat_t::iterator it;
for(it = stat_map_ch.begin(); it != stat_map_ch.end(); it++) {
if(stat_map.find(it->first) == stat_map.end()) {
stat_map[it->first] = out_node_height_t(it->second.first + 1, it->second.second);
} else {
out_node_height_t h = stat_map[it->first];
stat_map[it->first] = out_node_height_t(h.first + it->second.first, h.second + it->second.second);
}
}
}
break;
}
}
outnode_height = stat_map;
return changestat;
}
int RegExpDag::out_node_height(set<RegExp *> reg_equations) {
set<RegExp *> visited;
out_node_stat_t stat_map;
set<RegExp *>::iterator it;
int changestat = 0;
for(it = reg_equations.begin(); it != reg_equations.end(); it++) {
visited.clear();
stat_map.clear();
changestat += (*it)->calculate_height(visited,stat_map);
out_node_stat_t::iterator it2;
for(it2 = stat_map.begin(); it2 != stat_map.end(); it2++) {
stats.height += it2->second.first;
stats.lnd += it2->second.second;
stats.out_nodes++;
}
}
return changestat;
}
void RegExpDag::markReachable(reg_exp_t const r)
{
reg_exp_key_t ekey(r->type, r);
if(visited.find(ekey) != visited.end())
return;
visited.insert(ekey, r);
for(list<reg_exp_t>::iterator it = r->children.begin(); it != r->children.end(); ++it)
markReachable(*it);
}
void RegExpDag::computeMinimalRoots()
{
visited.clear();
// Get the set of regexp nodes that are reachable from some node labelling the
// IntraGraph in one or more steps.
for(reg_exp_hash_t::iterator it = graphLabelsInSatProcess.begin(); it != graphLabelsInSatProcess.end(); ++it){
reg_exp_t root = it->second;
for(list<reg_exp_t>::iterator cit = root->children.begin(); cit != root->children.end(); ++cit){
reg_exp_t child = *cit;
markReachable(child);
}
}
// collect a subset of regexp nodes that were not covered in the search above.
for(reg_exp_hash_t::iterator it = graphLabelsInSatProcess.begin(); it != graphLabelsInSatProcess.end(); ++it){
if(visited.find(it->first) == visited.end())
minimalRoots.insert(*it);
}
visited.clear();
}
// @see RegExpDag::evaluate -- originally copied from there
// @see computeMinimalRoots to set up the 'roots'
// Evaluate the regexp dag under current 'roots' in one fell swoop.
void RegExpDag::evaluateRoots()
{
for(reg_exp_hash_t::const_iterator iter = minimalRoots.begin(); iter != minimalRoots.end(); ++iter){
reg_exp_t regexp = iter->second;
#if defined(PUSH_EVAL)
if(!regexp->dirty)
continue;
#else
if(regexp->last_seen == satProcesses[regexp->satProcess].update_count && regexp->last_change != (unsigned)-1) // evaluate(w) sets last_change to -1
#endif
continue;
if(!top_down_eval || !saturation_complete)
regexp->evaluate();
else if(executing_poststar)
regexp->evaluate(regexp->value->one());
else
// Executing prestar
regexp->evaluate();
}
}
void RegExp::evaluate_iteratively() {
#if defined(PUSH_EVAL)
assert(0 && "evaluate_iteratively not implemented for PUSH_EVAL mode");
#endif
typedef list<reg_exp_t>::iterator iter_t;
typedef pair<reg_exp_t, iter_t > stack_el;
if(last_seen == dag->satProcesses[satProcess].update_count)
return;
list<stack_el> stack;
stack.push_front(stack_el(this, children.begin()));
while(!stack.empty()) {
stack_el sel = stack.front();
stack.pop_front();
reg_exp_t re = sel.first;
iter_t cit = sel.second;
while( cit != re->children.end() && (*cit)->last_seen == dag->satProcesses[satProcess].update_count) {
cit++;
}
if(cit == re->children.end()) {
switch(re->type) {
case Constant:
case Updatable:
break;
case Star: {
reg_exp_t ch = re->children.front();
if(ch->last_change <= re->last_seen) { // child did not change
re->last_seen = dag->satProcesses[satProcess].update_count;
} else {
sem_elem_t w = ch->value->star();
STAT(dag->stats.nstar++);
re->last_seen = dag->satProcesses[satProcess].update_count;
if(!re->value->equal(w)) {
//last_change = update_count;
re->last_change = ch->last_change;
re->value = w;
}
}
break;
}
case Extend: {
list<reg_exp_t>::iterator ch;
sem_elem_t wnew = re->value->one();
bool changed = false;
unsigned max = re->last_change;
for(ch = re->children.begin(); ch != re->children.end() && !changed; ch++) {
changed = changed | ((*ch)->last_change > re->last_seen);
}
re->last_seen = dag->satProcesses[satProcess].update_count;
if(changed) {
for(ch = re->children.begin(); ch != re->children.end(); ch++) {
wnew = wnew->extend( (*ch)->value);
max = ((*ch)->last_change > max) ? (*ch)->last_change : max;
STAT(dag->stats.nextend++);
}
if(!re->value->equal(wnew)) {
re->last_change = max;
re->value = wnew;
}
}
break;
}
case Combine: {
list<reg_exp_t>::iterator ch;
sem_elem_t wnew = re->value;
unsigned max = re->last_change;
for(ch = re->children.begin(); ch != re->children.end(); ch++) {
if((*ch)->last_change > re->last_seen) {
wnew = wnew->combine((*ch)->value);
max = ((*ch)->last_change > max) ? (*ch)->last_change : max;
STAT(dag->stats.ncombine++);
}
}
re->last_seen = dag->satProcesses[satProcess].update_count;
if(!re->value->equal(wnew)) {
re->last_change = max;
re->value = wnew;
}
break;
}
}
re->last_change = (re->last_change > 1) ? re->last_change : 1;
} else { // cit != re->children.end()
iter_t cit2 = cit;
stack.push_front(stack_el(re, ++cit2));
stack.push_front(stack_el(*cit, (*cit)->children.begin()));
}
}
}
sem_elem_t RegExp::evaluate(sem_elem_t w) {
map<sem_elem_t, sem_elem_t,sem_elem_less>::iterator it;
sem_elem_t ret;
#if defined(PUSH_EVAL)
if(dirty){
eval_map.clear();
dirty = false;
}else{
it = eval_map.find(w);
if(it != eval_map.end()){
return it->second;
}
}
#else
if(last_seen == dag->satProcesses[satProcess].update_count) {
it = eval_map.find(w);
if(it != eval_map.end()) {
return it->second;
} else {
#if 0
if(false && last_change != (unsigned)-1) {// "value" is available
ret = w->extend(value);
eval_map[w] = ret;
return ret;
}
#endif
}
} else {
eval_map.clear();
}
#endif //#if defined(PUSH_EVAL)
unsigned int &update_count = dag->satProcesses[dag->currentSatProcess].update_count;
evaluations.push_back(update_count);
switch(type) {
case Constant:
case Updatable:
ret = w->extend(value);
STAT(dag->stats.nextend++);
break;
case Star: {
reg_exp_t ch = children.front();
sem_elem_t ans = w->zero(), nans = w;
sem_elem_t temp = w;
while(!ans->equal(nans)) {
ans = nans;
temp = ch->evaluate(temp);
nans = nans->combine(temp);
STAT(dag->stats.ncombine++);
}
/*
nans = ch->evaluate(w);
while(!ans->equal(nans)) {
ans = nans;
nans = nans->combine(ans->extend(ans));
STAT(dag->stats.ncombine++);
STAT(dag->stats.nextend++);
}
*/
ret = nans;
break;
}
case Extend: {
list<reg_exp_t>::iterator ch;
sem_elem_t temp = w;
for(ch = children.begin(); ch != children.end(); ch++) {
temp = (*ch)->evaluate(temp);
}
ret = temp;
break;
}
case Combine: {
list<reg_exp_t>::iterator ch;
sem_elem_t temp = w->zero();
for(ch = children.begin(); ch != children.end(); ch++) {
temp = temp->combine((*ch)->evaluate(w));
STAT(dag->stats.ncombine++);
}
ret = temp;
break;
}
}
eval_map[w] = ret;
last_seen = dag->satProcesses[satProcess].update_count; last_change = (unsigned)-1;
return ret;
}
// Evaluate in reverse
sem_elem_t RegExp::evaluateRev(sem_elem_t w) {
map<sem_elem_t, sem_elem_t,sem_elem_less>::iterator it;
sem_elem_t ret;
if(last_seen == dag->satProcesses[satProcess].update_count) {
it = eval_map.find(w);
if(it != eval_map.end()) {
return it->second;
} else {
#if 0
if(false && last_change != (unsigned)-1) {// "value" is available
ret = w->extend(value);
eval_map[w] = ret;
return ret;
}
#endif
}
} else {
eval_map.clear();
}
unsigned int &update_count = dag->satProcesses[dag->currentSatProcess].update_count;
evaluations.push_back(update_count);
switch(type) {
case Constant:
case Updatable:
ret = value->extend(w);
STAT(dag->stats.nextend++);
break;
case Star: {
reg_exp_t ch = children.front();
sem_elem_t ans = w->zero(), nans = w;
sem_elem_t temp = w;
while(!ans->equal(nans)) {
ans = nans;
temp = ch->evaluateRev(temp);
nans = nans->combine(temp);
STAT(dag->stats.ncombine++);
}
ret = nans;
break;
}
case Extend: {
list<reg_exp_t>::reverse_iterator ch;
sem_elem_t temp = w;
for(ch = children.rbegin(); ch != children.rend(); ch++) {
temp = (*ch)->evaluateRev(temp);
}
ret = temp;
break;
}
case Combine: {
list<reg_exp_t>::iterator ch;
sem_elem_t temp = w->zero();
for(ch = children.begin(); ch != children.end(); ch++) {
temp = temp->combine((*ch)->evaluateRev(w));
STAT(dag->stats.ncombine++);
}
ret = temp;
break;
}
}
eval_map[w] = ret;
last_seen = dag->satProcesses[satProcess].update_count; last_change = (unsigned)-1;
return ret;
}
#ifdef DWPDS
sem_elem_t RegExp::get_delta(unsigned int ls) {
if(type == Constant) {
if(ls == 0) {
return value; // Constants are assumed to get their value at update 1
} else {
return value->zero();
}
}
delta_map_t::iterator it = delta.upper_bound(ls);
sem_elem_t del = value->zero();
if(it == delta.end()) {
return del;
}
//int cnt=0;
while(it != delta.end()) {
del = del->combine(it->second);
it++;
//cnt++;
}
//if(cnt > 1) {
// return value;
//}
return del;
}
#endif
sem_elem_t RegExp::get_weight() {
if(last_seen == dag->satProcesses[satProcess].update_count && last_change != (unsigned)-1) // evaluate(w) sets last_change to -1
return value;
if(!dag->top_down_eval || !dag->saturation_complete) {
evaluate();
return value;
}
if(dag->executing_poststar) {
return evaluate(value->one());
}
// Executing prestar
evaluate();
return value;
#if 0
// EvaluateRev does not seem to do a better job than evaluate()
return evaluateRev(value->one());
#endif
}
void RegExp::evaluate() {
#if defined(PUSH_EVAL)
if(!dirty){
last_seen = dag->satProcesses[satProcess].update_count;
return;
}
#endif
if(last_seen == dag->satProcesses[satProcess].update_count) return;
unsigned int &update_count = dag->satProcesses[dag->currentSatProcess].update_count;
evaluations.push_back(update_count);
nevals++;
switch(type) {
case Constant:
case Updatable:
return;
case Star: {
reg_exp_t ch = children.front();
ch->evaluate();
if(ch->last_change > last_seen) { // child did not change
#ifdef DWPDS
sem_elem_t w = value->one(),del = value->one(),temp;
while(!del->equal(value->zero())) {
temp = del->extend(ch->value);
del = temp->diff(w);
w = w->combine(temp);
}
#else
sem_elem_t w = ch->value->star();
#endif
STAT(dag->stats.nstar++);
if(!value->equal(w)) {
last_change = ch->last_change;
#ifdef DWPDS
sem_elem_t dval = w->diff(value);
delta[last_change] = dval;
#endif
value = w;
}
}
last_seen = dag->satProcesses[satProcess].update_count;
break;
}
case Combine: {
list<reg_exp_t>::iterator ch;
sem_elem_t wnew = value;
sem_elem_t wchange = value->zero();
unsigned max = last_change;
for(ch = children.begin(); ch != children.end(); ch++) {
(*ch)->evaluate();
if((*ch)->last_change > last_seen) {
#ifdef DWPDS
wchange = wchange->combine((*ch)->get_delta(last_seen));
#else
wchange = wchange->combine((*ch)->value);
#endif
max = ((*ch)->last_change > max) ? (*ch)->last_change : max;
STAT(dag->stats.ncombine++);
}
}
wnew = wnew->combine(wchange);
if(!value->equal(wnew)) {
last_change = max;
#ifdef DWPDS
sem_elem_t dval = wchange->diff(value);
delta[last_change] = dval; // wchange->diff(value)
#endif
value = wnew;
}
last_seen = dag->satProcesses[satProcess].update_count;
break;
}
case Extend: {
list<reg_exp_t>::iterator ch;
sem_elem_t wnew;
bool changed = false;
unsigned max = last_change;
int thechange = 0, cnt=1;
/*
for(ch = children.begin(); ch != children.end(); ch++) {
(*ch)->evaluate();
changed = changed | ((*ch)->last_change > last_seen);
if((*ch)->last_change > last_seen) thechange += cnt;
cnt *= 2;
}
*/
list<reg_exp_t>::reverse_iterator rch;
for(rch = children.rbegin(); rch != children.rend(); rch++) {
(*rch)->evaluate();
changed = changed | ((*rch)->last_change > last_seen);
if((*rch)->last_change > last_seen) thechange += cnt;
cnt *= 2;
}
if(changed) {
if(lastchange == -1 || thechange != lastchange) differentchange++;
else samechange++;
lastchange=thechange;
}
if(changed) {
#ifdef DWPDS
list<reg_exp_t>::iterator sel;
sem_elem_t del;
wnew = value->zero();
for(sel = children.begin(); sel != children.end(); sel++) {
del = value->one();
for(ch = children.begin(); ch != children.end(); ch++) {
if(ch == sel) {
del = del->extend((*ch)->get_delta(last_seen));
} else {
del = del->extend((*ch)->value);
}
}
wnew = wnew->combine(del);
max = ((*sel)->last_change > max) ? (*sel)->last_change : max;
}
del = wnew->diff(value);
wnew = wnew->combine(value);
#else
wnew = value->one();
for(ch = children.begin(); ch != children.end(); ch++) {
wnew = wnew->extend( (*ch)->value);
max = ((*ch)->last_change > max) ? (*ch)->last_change : max;
STAT(dag->stats.nextend++);
}
#endif
if(!value->equal(wnew)) {
last_change = max;
#ifdef DWPDS
delta[last_change] = wnew->diff(value); // del;
#endif
value = wnew;
}
}
last_seen = dag->satProcesses[satProcess].update_count;
break;
}
}
last_change = (last_change > 1) ? last_change : 1;
assert(last_seen == dag->satProcesses[satProcess].update_count);
#if defined(PUSH_EVAL)
dirty = false;
#endif
}
sem_elem_t RegExp::reevaluate() {
// reset uptodate
set<RegExp *> gray;
set<RegExp *> black;
dfs(gray,black);
set<RegExp *>::iterator it;
vector<sem_elem_t> vals;
for(it = black.begin(); it != black.end(); it++) {
(*it)->uptodate = false;
vals.push_back((*it)->value);
}
sem_elem_t ret = reevaluateIter();
int i=0;
for(it = black.begin(); it != black.end(); it++) {
if((*it)->type == Constant || (*it)->type == Updatable) {
assert((*it)->value->equal(vals[i]));
}
(*it)->value = vals[i];
i++;
}
return ret;
}
sem_elem_t RegExp::reevaluateIter() {
if(type == Constant || type == Updatable) {
return value;
}
if(uptodate) {
return value;
}
list<reg_exp_t>::iterator it = children.begin();
for(; it != children.end(); it++) {
(*it)->reevaluateIter();
}
uptodate = true;
if(type == Star) {
it = children.begin();
value = (*it)->value->star();
STAT(dag->stats.nstar++);
} else if(type == Extend) {
it = children.begin();
value = value->one();
for(; it != children.end(); it++) {
value = value->extend((*it)->value);
STAT(dag->stats.nextend++);
}
} else {
it = children.begin();
value = value->zero();
for(; it != children.end(); it++) {
value = value->combine((*it)->value);
STAT(dag->stats.ncombine++);
}
}
return value;
}
// for debugging
bool RegExp::isCyclic() {
set<RegExp *> gray;
set<RegExp *> black;
return dfs(gray,black);
}
bool RegExp::dfs(set<RegExp *> &gray, set<RegExp *> &black) {
if(type == Constant || type == Updatable) {
black.insert(this);
return false;
}
gray.insert(this);
list<reg_exp_t>::iterator ch = children.begin();
for(; ch != children.end(); ch++) {
set<RegExp *>::iterator it = gray.find((*ch).get_ptr());
if(it != gray.end()) { // cycle
return true;
}
it = black.find((*ch).get_ptr());
if(it == black.end()) {
bool r = (*ch)->dfs(gray,black);
if(r) return true;
}
}
gray.erase(this);
black.insert(this);
return false;
}
RegExpDag::~RegExpDag()
{
satProcesses.clear();
currentSatProcess = 0;
extend_backwards = false;
reg_exp_hash.clear();
const_reg_exp_hash.clear();
#if defined(PPP_DBG) && PPP_DBG >= 0
rootsInSatProcess.clear();
rootsAcrossSatProcesses.clear();
#endif
graphLabelsInSatProcess.clear();
graphLabelsAcrossSatProcesses.clear();
stats.reset();
reg_exp_one = NULL;
reg_exp_zero = NULL;
saturation_complete = false;
executing_poststar = true;
initialized = false;
top_down_eval = true;
visited.clear();
}
#if defined(PPP_DBG) && PPP_DBG >= 0
void RegExpDag::printStructureInformation()
{
long nodes = countTotalNodes();
long leaves = countTotalLeaves();
long height = getHeight();
long splines = countSpline();
long frontiers = countFrontier();
long graphls = graphLabelsAcrossSatProcesses.size();
long roots = rootsAcrossSatProcesses.size();
long errorls = countLabelsUnderNonLabelRoots();
// Find roots that are also labels
reg_exp_hash_t rootsThatAreLabels;
for(reg_exp_hash_t::iterator it = rootsAcrossSatProcesses.begin();
it != rootsAcrossSatProcesses.end();
++it)
if(graphLabelsAcrossSatProcesses.find(it->first) != graphLabelsAcrossSatProcesses.end())
rootsThatAreLabels[it->first] = it->second;
long rootsNgraphls = rootsThatAreLabels.size();
cout << "RegExp statistics:" << endl;
cout << "#Nodes: " << nodes << endl;
cout << "#Leaves: " << leaves << endl;
cout << "#Spline: " << splines << endl;
cout << "#Frontiers: " << frontiers << endl;
cout << "#Labels: " << graphls << endl;
cout << "#Labels ^ Roots: " << rootsNgraphls << endl;
cout << "#Labels under non-label roots: " << errorls << endl;
if(nodes > 0){
cout << "Spline/nodes %: " << ((double) splines * 100) / ((double) nodes) << endl;
cout << "Frontier/nodes %: " << ((double) frontiers * 100) / ((double) nodes) << endl;
cout << "label nodes/nodes %: " << ((double) graphls * 100) / ((double) nodes) << endl;
cout << "Height/log(nodes) %: " << ((double) height * 100) * log10(2) / log10((double) nodes) << endl;
cout << "roots/nodes %: " << ((double) roots * 100) /((double) nodes) << endl;
cout << "(roots intersect labels)/nodes %: " << ((double) rootsNgraphls * 100) /((double) nodes) << endl;
cout << "(labels under non-label roots) / nodes %: " << ((double) errorls * 100) / ((double) nodes) << endl;
}
}
long RegExpDag::countLabelsUnderNonLabelRoots()
{
long count = 0;
visited.clear();
reg_exp_hash_t rootsThatAreLabels;
for(reg_exp_hash_t::iterator it = rootsAcrossSatProcesses.begin();
it != rootsAcrossSatProcesses.end();
++it){
if(graphLabelsAcrossSatProcesses.find(it->first) != graphLabelsAcrossSatProcesses.end()){
count += countLabels(it->second);
}
}
visited.clear();
return count;
}
long RegExpDag::countLabels(reg_exp_t const e)
{
reg_exp_key_t ekey(e->type, e);
reg_exp_hash_t::iterator it = visited.find(ekey);
if(it != visited.end())
return 0;
visited.insert(ekey, e);
long total = 0;
for(list<reg_exp_t>::iterator cit = e->children.begin(); cit != e->children.end(); ++cit)
total += countLabels(*cit);
if(graphLabelsAcrossSatProcesses.find(ekey) != graphLabelsAcrossSatProcesses.end())
total += 1;
return total;
}
long RegExpDag::getHeight()
{
long max = 0;
height.clear();
for(reg_exp_hash_t::const_iterator rit = rootsAcrossSatProcesses.begin(); rit != rootsAcrossSatProcesses.end(); ++rit){
long cur = getHeight(rit->second);
max = cur > max ? cur : max;
}
return max;
}
// Relies on the dag actually being a dag
// Will go into an infinite loop otherwise
long RegExpDag::getHeight(reg_exp_t const e)
{
reg_exp_key_t ekey(e->type, e);
wali::HashMap<reg_exp_key_t, long, hash_reg_exp_key, reg_exp_key_t>::iterator it = height.find(ekey);
if(it != height.end())
return it->second;
long max = 0;
if(e->children.size() == 0){
max = 1;
}else{
for(list<reg_exp_t>::iterator cit = e->children.begin(); cit != e->children.end(); ++cit){
long cur = getHeight(*cit);
max = cur > max ? cur : max;
}
}
height[ekey] = max;
return max;
}
long RegExpDag::countSpline(){
markSpline();
return (long) spline.size();
}
void RegExpDag::markSpline()
{
visited.clear();
spline.clear();
for(reg_exp_hash_t::const_iterator rit = rootsAcrossSatProcesses.begin(); rit != rootsAcrossSatProcesses.end(); ++rit)
markSpline(rit->second);
}
// Relies on dag actually being a dag
// will give incorrect answers (will not mark all) otherwise.
bool RegExpDag::markSpline(reg_exp_t const e)
{
reg_exp_key_t ekey(e->type, e);
reg_exp_hash_t::iterator it = visited.find(ekey);
if(it != visited.end()){
return spline.find(ekey) != spline.end();
}
visited.insert(ekey, e);
bool onSpline = false;
for(list<reg_exp_t>::iterator cit = e->children.begin(); cit != e->children.end(); ++cit)
onSpline |= markSpline(*cit);
if(e->type == Updatable)
onSpline = true;
if(onSpline)
spline.insert(ekey, e);
return onSpline;
}
long RegExpDag::countFrontier()
{
markSpline();
visited.clear();
long count = 0;
for(reg_exp_hash_t::const_iterator rit = rootsAcrossSatProcesses.begin(); rit != rootsAcrossSatProcesses.end(); ++rit)
count += countFrontier(rit->second);
return count;
}
long RegExpDag::countFrontier(reg_exp_t const e)
{
reg_exp_key_t ekey(e->type, e);
reg_exp_hash_t::iterator it = visited.find(ekey);
if(it != visited.end())
return 0;
visited.insert(ekey, e);
it = spline.find(ekey);
if(it == spline.end())
return 0;
long count = 0;
for(list<reg_exp_t>::iterator cit = e->children.begin(); cit != e->children.end(); ++cit){
reg_exp_key_t ckey((*cit)->type, *cit);
if(spline.find(ckey) != spline.end()){
count += countFrontier(*cit);
}else{
if(visited.find(ckey) == visited.end()){
count += 1;
visited.insert(ckey, *cit);
}
}
}
return count;
}
long RegExpDag::countTotalLeaves()
{
long total = 0;
visited.clear();
for(reg_exp_hash_t::const_iterator rit = rootsAcrossSatProcesses.begin(); rit != rootsAcrossSatProcesses.end(); ++rit)
total += countTotalLeaves(rit->second);
return total;
}
long RegExpDag::countTotalLeaves(reg_exp_t const e)
{
reg_exp_key_t ekey(e->type, e);
reg_exp_hash_t::iterator it = visited.find(ekey);
if(it != visited.end())
return 0;
visited.insert(ekey, e);
if(e->children.size() == 0)
return 1;
long total = 0;
for(list<reg_exp_t>::iterator cit = e->children.begin(); cit != e->children.end(); ++cit)
total += countTotalLeaves(*cit);
return total;
}
long RegExpDag::countTotalCombines()
{
long total = 0;
visited.clear();
for(reg_exp_hash_t::const_iterator rit = rootsAcrossSatProcesses.begin(); rit != rootsAcrossSatProcesses.end(); ++rit)
total += countTotalCombines(rit->second);
return total;
}
long RegExpDag::countTotalCombines(reg_exp_t const e)
{
reg_exp_key_t ekey(e->type, e);
reg_exp_hash_t::iterator it = visited.find(ekey);
if(it != visited.end())
return 0;
visited.insert(ekey, e);
long total = 0;
if(e->type == wali::graph::Combine)
++total;
for(list<reg_exp_t>::iterator cit = e->children.begin(); cit != e->children.end(); ++cit)
total += countTotalCombines(*cit);
return total;
}
long RegExpDag::countTotalExtends()
{
long total = 0;
visited.clear();
for(reg_exp_hash_t::const_iterator rit = rootsAcrossSatProcesses.begin(); rit != rootsAcrossSatProcesses.end(); ++rit){
total += countTotalExtends(rit->second);
}
return total;
}
long RegExpDag::countTotalExtends(reg_exp_t const e)
{
reg_exp_key_t ekey(e->type, e);
reg_exp_hash_t::iterator it = visited.find(ekey);
if(it != visited.end())
return 0;
visited.insert(ekey, e);
long total = 0;
if(e->type == wali::graph::Extend)
++total;
for(list<reg_exp_t>::iterator cit = e->children.begin(); cit != e->children.end(); ++cit)
total += countTotalExtends(*cit);
return total;
}
long RegExpDag::countTotalStars()
{
long total = 0;
visited.clear();
for(reg_exp_hash_t::const_iterator rit = rootsAcrossSatProcesses.begin(); rit != rootsAcrossSatProcesses.end(); ++rit)
total += countTotalStars(rit->second);
return total;
}
long RegExpDag::countTotalStars(reg_exp_t const e)
{
reg_exp_key_t ekey(e->type, e);
reg_exp_hash_t::iterator it = visited.find(ekey);
if(it != visited.end())
return 0;
visited.insert(ekey, e);
long total = 0;
if(e->type == wali::graph::Star)
++total;
for(list<reg_exp_t>::iterator cit = e->children.begin(); cit != e->children.end(); ++cit)
total += countTotalStars(*cit);
return total;
}
long RegExpDag::countExcept(std::vector<reg_exp_t>& exceptions)
{
visited.clear();
for(vector<reg_exp_t>::const_iterator cit = exceptions.begin(); cit != exceptions.end(); ++cit)
excludeFromCountReachable(*cit);
long total = 0;
for(reg_exp_hash_t::const_iterator cit = rootsAcrossSatProcesses.begin(); cit != rootsAcrossSatProcesses.end(); ++cit)
total += countTotalNodes(cit->second);
return total;
}
void RegExpDag::excludeFromCountReachable(reg_exp_t const e)
{
reg_exp_key_t ekey(e->type, e);
reg_exp_hash_t::iterator it = visited.find(ekey);
if(it != visited.end())
return;
visited.insert(ekey, e);
for(list<reg_exp_t>::iterator cit = e->children.begin(); cit != e->children.end(); ++cit)
excludeFromCountReachable(*cit);
}
long RegExpDag::countTotalNodes()
{
long total = 0;
visited.clear();
for(reg_exp_hash_t::const_iterator rit = rootsAcrossSatProcesses.begin(); rit != rootsAcrossSatProcesses.end(); ++rit){
total += countTotalNodes(rit->second);
}
return total;
}
long RegExpDag::countTotalNodes(reg_exp_t const e)
{
reg_exp_key_t ekey(e->type, e);
reg_exp_hash_t::iterator it = visited.find(ekey);
if(it != visited.end())
return 0;
visited.insert(ekey, e);
long total = 0;
//if(e->type == Combine || e->type == Extend || e->type == Star)
++total;
for(list<reg_exp_t>::iterator cit = e->children.begin(); cit != e->children.end(); ++cit)
total += countTotalNodes(*cit);
return total;
}
// Relies on the dag actually being a dag.
// If not, a circular path has no root.
void RegExpDag::sanitizeRootsAcrossSatProcesses()
{
for(reg_exp_hash_t::const_iterator rit = rootsAcrossSatProcesses.begin(); rit != rootsAcrossSatProcesses.end(); ++rit){
visited.clear();
reg_exp_t const e = rit->second;
reg_exp_key_t ekey(e->type, e);
visited.insert(ekey, e);
for(list<reg_exp_t>::iterator cit = e->children.begin(); cit != e->children.end(); ++cit)
removeDagFromRoots(*cit);
}
}
void RegExpDag::removeDagFromRoots(reg_exp_t const e)
{
reg_exp_key_t ekey(e->type, e);
reg_exp_hash_t::iterator it = visited.find(ekey);
if(it != visited.end())
return;
visited.insert(ekey, e);
rootsAcrossSatProcesses.erase(ekey);
for(list<reg_exp_t>::iterator cit = e->children.begin(); cit != e->children.end(); ++cit)
removeDagFromRoots(*cit);
}
#endif //#if defined(PPP_DBG) && PPP_DBG >= 0
void RegExpDag::markAsLabel(reg_exp_t e)
{
reg_exp_key_t ekey(e->type, e);
graphLabelsInSatProcess.insert(ekey,e);
}
} // namespace graph
} // namespace wali
|
#include <bits/stdc++.h>
using namespace std;
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 1000000
#define INF 0x3f3f3f3f
#define DEVIATION 0.00000005
typedef long long LL;
bool table[MAXN+10];
int main(int argc, char const *argv[])
{
int num;
int x,y,z;
while( ~scanf("%d",&num) && num ){
memset(table, 0, sizeof(table));
int tuple = 0;
for(int i = 1 ; i <= sqrt(num) ; i++ ){
for(int j = i+1 ; ; j+=2 ){
if( __gcd(i,j) != 1 ) continue;
x = j*j-i*i;
y = 2*j*i;
z = j*j+i*i;
if( x > num || y > num || z > num ) break;
tuple++;
int a = x,b = y,c = z;
while( a <= num && b <= num && c <= num ){
table[a] = table[b] = table[c] = true;
a += x;
b += y;
c += z;
}
}
}
int notused = num;
for(int i = 1 ; i <= num ; i++ )
if( table[i] ) notused--;
printf("%d %d\n",tuple,notused);
}
return 0;
}
|
#include <iostream>
#include <opencv2/opencv.hpp> // include OpenCV header file
#include <librealsense2/rs.hpp> // include the librealsense C++ header file
using namespace std;
using namespace cv;
using namespace rs2;
int main(int argc, char* argv[]) try
{
// Contruct a pipeline which abstracts the device
rs2::pipeline pipe;
// Create a configuration for configuring the pipeline with a non default profile
rs2::config cfg;
// Add desired streams to configuration
cfg.enable_stream(RS2_STREAM_COLOR, 640, 480, RS2_FORMAT_BGR8, 30);
cfg.enable_stream(RS2_STREAM_INFRARED, 640, 480, RS2_FORMAT_Y8, 30);
cfg.enable_stream(RS2_STREAM_DEPTH, 640, 480, RS2_FORMAT_Z16, 30);
// Instruct pipeline to start streaming with the requested configuration
pipe.start(cfg);
// Camera warmup - dropping several first frames to let auto-exposure stabilize
rs2::frameset frames;
for (int i = 0; i < 30; i++)
frames = pipe.wait_for_frames(); // Wait for all configured streams to produce a frame
// Get each frame
rs2::frame color_frame = frames.get_color_frame();
rs2::frame ir_frame = frames.first(RS2_STREAM_INFRARED);
rs2::frame depth_frame = frames.get_depth_frame();
// Creating OpenCV Matrix from a color image, IR image and depth image
Mat color(Size(640, 480), CV_8UC3, (void*)color_frame.get_data(), Mat::AUTO_STEP);
Mat ir(Size(640, 480), CV_8UC1, (void*)ir_frame.get_data(), Mat::AUTO_STEP);
Mat depth(Size(640, 480), CV_16UC1, (void*)depth_frame.get_data(), Mat::AUTO_STEP);
// Display in a GUI
imshow("Color Image", color);
imshow("Infrared Image", ir);
imshow("Depth Image", depth);
waitKey(0);
return EXIT_SUCCESS;
}
catch (const rs2::error & e)
{
std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n " << e.what() << std::endl;
return EXIT_FAILURE;
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
|
#include <catch2/catch.hpp>
#include <replay/rle_vector.hpp>
using namespace replay;
TEST_CASE("can create an empty rle_vector")
{
REQUIRE(rle_vector<double>().empty() == true);
}
TEST_CASE("push increases size according to count")
{
rle_vector<int> rle;
rle.push(4, 7);
rle.push(8, 11);
REQUIRE(rle.size() == 18);
}
TEST_CASE("push defaults to one count")
{
rle_vector<double> rle;
rle.push(3.24);
REQUIRE(rle.size() == 1);
}
TEST_CASE("can initialize using an initializer list")
{
rle_vector<std::string> rle = { { "three", 2 }, { "seven", 1 }, { "four", 2 } };
REQUIRE(!rle.empty());
}
TEST_CASE("can unpack using the copy algorithm")
{
rle_vector<std::string> rle = { { "three", 2 }, { "seven", 1 }, { "four", 2 } };
std::vector<std::string> unpacked;
std::copy(rle.begin(), rle.end(), std::back_inserter(unpacked));
REQUIRE(unpacked == std::vector<std::string>{ "three", "three", "seven", "four", "four" });
}
TEST_CASE("can use the iterators arrow operator")
{
rle_vector<std::vector<int>> rle;
rle.push({ 1, 2, 3 });
REQUIRE(rle.begin()->size() == 3);
}
TEST_CASE("equally constructed rle_vectors compare as equal")
{
rle_vector<float> a{ { 3.f, 2 }, { 4.f, 7 } };
rle_vector<float> b{ { 3.f, 2 }, { 4.f, 7 } };
REQUIRE(a == b);
}
TEST_CASE("move retains backing memory")
{
rle_vector<float> v{ { 9.f, 2 }, { 8.f, 1 }, { 7.f, 2 }, { 6.f, 1 } };
auto Before = v.data();
auto x = std::move(v);
REQUIRE(v.empty());
REQUIRE(x.data() == Before);
}
TEST_CASE("iterator can report repetitions")
{
rle_vector<float> v(11, 77.7f);
auto i = v.begin();
++i;
++i;
REQUIRE(i.repetition_count() == 9);
}
TEST_CASE("iterator has in-place addition")
{
rle_vector<float> v{ { 56.7f, 6 }, { 123.4f, 7 } };
auto i = v.begin();
i += 10;
REQUIRE(*i == 123.4f);
REQUIRE(i.repetition_count() == 3);
}
TEST_CASE("iterator has out-of-place addition")
{
rle_vector<float> v{ { 56.78f, 11 }, { 123.45f, 4 } };
auto b = v.begin() + std::size_t(6);
REQUIRE(*b == 56.78f);
REQUIRE(b.repetition_count() == 5);
}
TEST_CASE("can use suffix increment")
{
rle_vector<std::uint64_t> v{ { 0xffaaffaaffaaffaaUL, 1 }, { 0x2277227722772277UL, 3 } };
auto i = v.begin();
REQUIRE(*i++ == 0xffaaffaaffaaffaaUL);
REQUIRE(*i == 0x2277227722772277UL);
}
|
#include "iomode.h"
#include "iomodeutils.h"
#include <fstream>
#include "iostream"
void setInputMode(Config& config) {
Mode readMode = config.getInputMode();
if (readMode == Mode::FILE)
freopen("input.txt", "r", stdin);
return;
}
void setOutputMode(Config& config) {
Mode writeMode = config.getOutputMode();
if (writeMode == Mode::FILE)
freopen("output.txt", "w", stdout);
return;
}
|
//This is a header file intended to be used with the G12 data stream.
//Purpose: Output if track passes G12 fiducial cuts
//Input: Lab Mometum (Pmom), Lab angle theta (Theta), Lab angle phi (Phi), charge of track (q), directory of fiducail parameter .txt file and type of cut (type_of_cut)
//type_of_cut: Loose, Tight, Nominal
//Output: pass/fail
//Updated: March 27, 2014
//Corrections were done by Jason Bono
//Program written by Michael C. Kunkel
//mkunkel@jlab.org
//######################### NOTE ##########################
//ALL VARIABLES IN LAB FRAME, ALL ANGLES IN DEGREES!!!!!!
//#########################################################
#ifndef __CLAS_G12_NEGPARTICLE_FIDUCIALCUTS_HPP__
#define __CLAS_G12_NEGPARTICLE_FIDUCIALCUTS_HPP__
#include <fstream>
#include <iostream>
#include <map>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <cmath>
#define DEG_2_RAD_CONV 0.01745328
float FidFunc_neg(float *, float *);
using namespace std;
namespace clas
{
namespace g12 {
bool g12_NegParticle_fiducial_cuts(float Pmom, float Theta, float Phi, const std::string& type_of_cut ){
const int Ns = 6; //number of sectors
float parL[Ns][9];
float parH[Ns][9];
parL[0][0] = -15810.2; parL[0][1] = 9.9663e-05; parL[0][2] = 15783.2;
parL[0][3] = -538215; parL[0][4] = 9.84788e-05; parL[0][5] = 538135;
parL[0][6] = -678156; parL[0][7] = 1.42357e-05; parL[0][8] = 678167;
parL[1][0] = -15810.7; parL[1][1] = 0.0001; parL[1][2] = 15783.7;
parL[1][3] = -538209; parL[1][4] = 8.31014e-05; parL[1][5] = 538141;
parL[1][6] = -678155; parL[1][7] = 1.32519e-05; parL[1][8] = 678167;
parL[2][0] = -37808.6; parL[2][1] = 4.38676e-05; parL[2][2] = 37782.3;
parL[2][3] = -678187; parL[2][4] = 3.0748e-05; parL[2][5] = 678136;
parL[2][6] = -678155; parL[2][7] = 1.13289e-05; parL[2][8] = 678168;
parL[3][0] = -37809.1; parL[3][1] = 5.52776e-05; parL[3][2] = 37781.8;
parL[3][3] = -678197; parL[3][4] = 4.21772e-05; parL[3][5] = 678126;
parL[3][6] = -678156; parL[3][7] = 9.59678e-06; parL[3][8] = 678167;
parL[4][0] = -37809.2; parL[4][1] = 5.79073e-05; parL[4][2] = 37781.7;
parL[4][3] = -678207; parL[4][4] = 7.72987e-05; parL[4][5] = 678115;
parL[4][6] = -678156; parL[4][7] = 1.63781e-05; parL[4][8] = 678166;
//real from Jason Bono
// parL[5][0] = -37808.9; parL[5][1] = 4.70858e-05; parL[5][2] = 37781.9;
// parL[5][3] = -678198; parL[5][4] = 9.27108e-05; parL[5][5] = 678125;
// parL[5][6] = -678155; parL[5][7] = 7.45841e-06; parL[5][8] = 678167;
//End real
//test parameters: changed par[5][7] to par[4][7]
parL[5][0] = -37808.9; parL[5][1] = 4.70858e-05; parL[5][2] = 37781.9;
parL[5][3] = -678198; parL[5][4] = 9.27108e-05; parL[5][5] = 678125;
parL[5][6] = -678155; parL[5][7] = 1.63781e-05; parL[5][8] = 678167;
// // end test
parH[0][0] = -15783.8; parH[0][1] = -0.0001; parH[0][2] = 15809.5;
parH[0][3] = -538148; parH[0][4] = -8.77852e-05; parH[0][5] = 538201;
parH[0][6] = -678155; parH[0][7] = 1.67856e-05; parH[0][8] = 678168;
parH[1][0] = -37782.2; parH[1][1] = -9.78359e-05; parH[1][2] = 37808.7;
parH[1][3] = -678123; parH[1][4] = -9.99919e-05; parH[1][5] = 678199;
parH[1][6] = -678155; parH[1][7] = 1.71348e-05; parH[1][8] = 678168;
parH[2][0] = -37782.3; parH[2][1] = -6.62596e-05; parH[2][2] = 37808.6;
parH[2][3] = -678133; parH[2][4] = -4.84207e-05; parH[2][5] = 678190;
parH[2][6] = -678155; parH[2][7] = 1.47442e-05; parH[2][8] = 678168;
parH[3][0] = -37782.5; parH[3][1] = -3.18908e-05; parH[3][2] = 37808.4;
parH[3][3] = -678135; parH[3][4] = -1.21321e-05; parH[3][5] = 678188;
parH[3][6] = -678155; parH[3][7] = 1.22068e-05; parH[3][8] = 678168;
parH[4][0] = -37782.3; parH[4][1] = -6.28596e-05; parH[4][2] = 37808.5;
parH[4][3] = -678136; parH[4][4] = -0.0001; parH[4][5] = 678187;
parH[4][6] = -678154; parH[4][7] = 1.79547e-05; parH[4][8] = 678168;
parH[5][0] = -37782.4; parH[5][1] = -6.08308e-05; parH[5][2] = 37808.4;
parH[5][3] = -678131; parH[5][4] = -5.88378e-05; parH[5][5] = 678192;
parH[5][6] = -678155; parH[5][7] = 1.44427e-05; parH[5][8] = 678168;
float phi_clas;
int sector;
if (Phi < -30){phi_clas = 360 + Phi;}
else{phi_clas = Phi;}
//get sectors
if ( (phi_clas > -30) && (phi_clas <= 30 )){sector = 1;}
else if ( (phi_clas > 30) && (phi_clas <= 90 )){sector = 2;}
else if ( (phi_clas > 90) && (phi_clas <= 150 )){sector = 3;}
else if ( (phi_clas > 150) && (phi_clas <= 210 )){sector = 4;}
else if ( (phi_clas > 210) && (phi_clas <= 270 )){sector = 5;}
else if ( (phi_clas > 270) && (phi_clas <= 330 )){sector = 6;}
else{cout<<"UNDEFINED SECTOR"<<endl; return false;}
//get phidiff
float phidiff = (60.*(float)(sector - 1)) - phi_clas;
float fidvar[2] = {Pmom,Theta};
float lowReg = 0;
lowReg = FidFunc_neg(fidvar,parL[sector - 1]);
float highReg = 0;
highReg = FidFunc_neg(fidvar,parH[sector - 1]);
//Now its time to determine true false based on the input of tight, loose, nominal
float pass_low, pass_high;
if(type_of_cut=="tight"){
pass_low = lowReg + 2;
pass_high = highReg - 2;
if ((phidiff > pass_low) && (phidiff < pass_high))
{
return true;
}else{return false;}
}
else if(type_of_cut=="loose"){
pass_low = lowReg - 2;
pass_high = highReg + 2;
if ((phidiff > pass_low) && (phidiff < pass_high))
{
return true;
}else{return false;}
}
else if(type_of_cut=="nominal"){
pass_low = lowReg;
pass_high = highReg;
if ((phidiff > pass_low) && (phidiff < pass_high))
{
return true;
}else{return false;}
}
else{cout<<"Did not enter correct type of cut "<<endl;return false;}
}
}
}
#endif /* __CLAS_G12_NEGPARTICLE_FIDUCIALCUTS_HPP__*/
//////////////////////////////////////////////////
//c style 2d function
float FidFunc_neg(float *x, float *par)
{
float xx = x[0]; //momentum
float yy = x[1]; //theta
float a = (par[0]*pow(xx,par[1]) + par[2]);
float b = (par[3]*pow(xx,par[4]) + par[5]);
float c = (par[6]*pow(xx,par[7]) + par[8]);
float f = a - b/(yy - c);
return f;
}
|
// Created on: 2015-06-26
// Created by: Andrey Betenev
// Copyright (c) 2015 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef NCollection_Shared_HeaderFile
#define NCollection_Shared_HeaderFile
#include <NCollection_DefineAlloc.hxx>
//! Template defining a class derived from the specified base class and
//! Standard_Transient, and supporting OCCT RTTI.
//!
//! This provides possibility to use Handes for types not initially intended
//! to be dynamically allocated.
//!
//! Current limitation is that only copy and constructors with 1-3 arguments are defined,
//! calling those of the argument class (default constructor must be available).
//! It can be improved when perfect forwarding of template arguments is supported
//! by all compilers used for OCCT.
//!
//! The intent is similar to std::make_shared<> in STL, except that this
//! implementation defines a separate type.
template <class T, typename = typename opencascade::std::enable_if<! opencascade::std::is_base_of<Standard_Transient, T>::value>::type>
class NCollection_Shared : public Standard_Transient, public T
{
public:
DEFINE_STANDARD_ALLOC
DEFINE_NCOLLECTION_ALLOC
//! Default constructor
NCollection_Shared () {}
//! Constructor with single argument
template<typename T1> NCollection_Shared (const T1& arg1) : T(arg1) {}
//! Constructor with single argument
template<typename T1> NCollection_Shared (T1& arg1) : T(arg1) {}
//! Constructor with two arguments
template<typename T1, typename T2> NCollection_Shared (const T1& arg1, const T2& arg2) : T(arg1, arg2) {}
//! Constructor with two arguments
template<typename T1, typename T2> NCollection_Shared (T1& arg1, const T2& arg2) : T(arg1, arg2) {}
//! Constructor with two arguments
template<typename T1, typename T2> NCollection_Shared (const T1& arg1, T2& arg2) : T(arg1, arg2) {}
//! Constructor with two arguments
template<typename T1, typename T2> NCollection_Shared (T1& arg1, T2& arg2) : T(arg1, arg2) {}
/* this could work...
//! Forwarding constructor
template<typename... Args>
NCollection_Shared (Args&&... args)
: T (std::forward<Args>(args)...)
{}
*/
};
#endif
|
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> strings;
std::string str = "denmark,sweden,india,us;";
if(str.size() > 0) str.resize( str.size() - 1);
istringstream f(str);
string s;
while (getline(f, s, ',')) {
cout << s << endl;
strings.push_back(s);
}
}
|
/* Main driver file to run threading tests.*/
#include "cc/shared/common.h"
#include "cc/shared/atomic_int.h"
#include "cc/shared/mutex.h"
#include "cc/shared/rand_utils.h"
#include "cc/shared/thread_pool.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
namespace cc_shared {
class ThreadingTest {
public:
ThreadingTest(int bucket_count)
: bucket_count_(bucket_count),
buckets_(new(std::nothrow) AtomicInt64 [bucket_count]) {
RT_ASSERT(bucket_count_ >= 2);
}
void execute(int max_iters, int thread_count) {
ThreadPool thread_pool(thread_count);
printf("Starting.\n");
wait_for_convergence();
for (int i = 0; i < max_iters; ++i) {
printf(".");
fflush(stdout);
enqueue_random_requests(&thread_pool);
if (0 == (i % 7)) {
wait_for_convergence();
}
// Sleep a little.
usleep(1000 * 200);
}
wait_for_convergence();
printf("\nFinished successfully.\n");
}
private:
int bucket_count_;
ScopedArray<AtomicInt64> buckets_;
int64 pending_task_count() {
int64 result = 0;
for (int i = 0; i < bucket_count_; ++i) {
result += buckets_[i].get_snapshot();
}
return result;
}
void wait_for_convergence() {
while (0 != pending_task_count()) {
usleep(10);
}
}
static void thread_func(void* parameter) {
AtomicInt64* atomic_int = static_cast<AtomicInt64*>(parameter);
atomic_int->decrement_and_get();
if (0 == rand_range(0, 2)) {
// Sleep a little, let another thread from the pool pick up another job.
usleep(10);
}
}
void enqueue_random_requests(ThreadPool* thread_pool) {
static const int kMaxRequests = 100;
for (int i = 0; i < kMaxRequests; ++i) {
int task_bucket = rand_range(0, bucket_count_ - 1);
buckets_[task_bucket].increment_and_get();
thread_pool->enqueue(
ThreadPoolPayload(
thread_func,
static_cast<void*>(buckets_.get() + task_bucket)));
}
}
};
} // cc_shared
int main(int argc, char* argv[]) {
srand(time(NULL));
cc_shared::ThreadingTest test_object(21);
test_object.execute(100, 8);
return 0;
}
|
/* -*-C++-*-
*/
/*
* Copyright 2016 EU Project ASAP 619706.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDED_ASAP_UTILS_H
#define INCLUDED_ASAP_UTILS_H
#include <cerrno>
#include <cstring>
#include <iostream>
namespace asap {
#define fatale(fn,...) asap::fatale_fn((fn),__FILE__,__LINE__,__VA_ARGS__)
#define fatal(...) asap::fatal_fn(__FILE__,__LINE__,__VA_ARGS__)
void print_args( std::ostream & os ) {
}
template<typename T, typename... Tn>
void print_args( std::ostream & os, T arg, Tn... args) {
os << arg;
print_args( os, args... );
}
template<typename... Tn>
void __attribute__((noreturn, noinline))
fatale_fn( const char * fn, const char * srcfile, unsigned lineno,
Tn... args ) {
const char * es = strerror( errno );
std::cerr << srcfile << ':' << lineno << ": " << fn
<< ": " << es << ": ";
print_args( std::cerr, args... );
std::cerr << std::endl;
exit( 1 );
}
template<typename... Tn>
void __attribute__((noreturn,noinline))
fatal_fn( const char * srcfile, unsigned lineno, Tn... args ) {
std::cerr << srcfile << ':' << lineno << ": ";
print_args( std::cerr, args... );
std::cerr << std::endl;
exit( 1 );
}
}
#endif // INCLUDED_ASAP_UTILS_H
|
#ifndef VEHICLE_H
#define VEHICLE_H
#include <iostream>
#include <random>
#include <sstream>
#include <fstream>
#include <math.h>
#include <vector>
#include <map>
#include <string>
#include <iterator>
using namespace std;
enum State {
KL, // keep lane
LCL, // lane change left
LCR, // lane change right
PLCL, // prepare lane change left
PLCR // prepare lane change right
};
class Vehicle {
public:
// car state
State state = KL;
struct collider {
bool collision = false;
double distance = 0;
double closest_approach = 1000;
double target_speed = 0;
} collider;
struct trajectory {
int lane_start = 0;
int lane_end = 0;
double target_speed = 0;
} trajectory;
struct reference {
double ref_v = 0;
double target_v = 49.50;
int lane = 0;
} reference;
double ref_speed = 0;
int ref_lane = 0;
double x = 0;
double y = 0;
double s = 0;
double d = 0;
double yaw = 0;
double speed = 0;
double delta_time = 0;
/**
* Constructor
*/
Vehicle(int lane, double target_speed);
// reset data
void reset_data();
// update car
void update_data(double ax, double ay, double as, double ad, double ayaw, double aspeed,
int lane, double target_speed, double delta);
// get next state
void choose_next_state(vector<vector<double>> sensor);
// realize next state
void realize_next_state(State state, vector<vector<double>> sensor_fusion);
};
#endif
|
#include <bits/stdc++.h>
using namespace std;
#define TESTC ""
#define PROBLEM "11879"
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
bool solve(string num ){
if( num.size() < 10 ){
int ans = 0;
for(int i = 0 ; i < num.size() ; i++ )
ans = ans*10 + num[i]-'0';
return ans%17 == 0;
}
char tmp = num[num.size()-1];
num = num.substr(0,num.size()-1);
for(int i = 0 ; i < 5 ; i++ ){
int j = num.size()-1;
bool overflow = false;
if( num[j] >= tmp )
num[j] = num[j]-tmp+'0';
else{
num[j] = num[j]-tmp+10+'0';
overflow = true;
}
while( overflow ){
j--;
num[j] = num[j]-1;
if( num[j] < '0' )
num[j] = num[j]+10;
else
overflow = false;
}
}
return solve(num);
}
int main(int argc, char const *argv[])
{
#ifdef DBG
freopen("uva" PROBLEM TESTC ".in", "r", stdin);
freopen("uva" PROBLEM ".out", "w", stdout);
#endif
string num;
while( cin >> num ){
if( num == "0" )
break;
if( solve(num) )
printf("1\n");
else
printf("0\n");
}
return 0;
}
|
#ifndef WORLDOBJECT_H
#define WORLDOBJECT_H
#include "SpriteObject.h"
#include "ICollideable.h"
class WorldObject : public SpriteObject, public ICollideable
{
public:
WorldObject(SpriteInfo& info, sf::Vector2f pos, bool _static = false);
~WorldObject();
void update();
void draw(sf::RenderTarget& target, float alpha);
private:
};
#endif // WORLDOBJECT_H
|
#include <stdlib.h>
#include <string.h>
#include "HallManager.h"
#include "ClientHandler.h"
#include "Packet.h"
using namespace std;
static HallManager* instance = NULL;
HallManager* HallManager::getInstance()
{
if(instance==NULL)
{
instance = new HallManager();
}
return instance;
}
int HallManager::sendToHall(int hallid, OutputPacket* outPacket, bool isEncrypt)
{
ClientHandler* hall = getHallHandler(hallid);
if(hall && outPacket)
{
return hall->Send(outPacket, isEncrypt);
}
else
return -1;
return 0;
}
int HallManager::addHallHandler(int hallid,ClientHandler* hall)
{
hall->setID(hallid);
hallMap[hallid] = hall;
return 0;
}
ClientHandler* HallManager::getHallHandler(int hallid)
{
map<int , ClientHandler*>::iterator it = hallMap.find(hallid);
if(it == hallMap.end())
return NULL;
else
return it->second;
}
void HallManager::delHallHandler(int hallid)
{
hallMap.erase(hallid);
}
|
#include <bits/stdc++.h>
using namespace std;
string divide(int num, int dem){
if(num == 0)
return "0";
if(num % dem == 0)
return to_string(num / dem);
string result;
if(num*dem < 0)
result.insert(0,1,'-');
num = abs(num);
dem = abs(dem);
result.insert(0,to_string(num/dem));
num %= dem;
result.insert(result.end(), ',');
map<int, int> mp;
mp.insert(make_pair(num, result.length()));
while(num != 0) {
num *= 10;
result.insert(result.length(),to_string(num/dem));
num %= dem;
if(mp.find(num) != mp.end()){
result.insert(mp[num], "(");
result.push_back(')');
break;
}
else
mp.insert(make_pair(num, result.length()));
}
return result;
}
int main() {
int m, n;
cin >> m >> n;
cout << divide(m, n);
return 0;
}
|
#include <SoftwareSerial.h>
#include <Servo.h>
Servo myservo;
int bluetoothTx = 10;
int bluetoothRx = 11;
char junk;
String inputString="";
int sensorPin1 = A0; // select the input pin for the LDR
int sensorValue1 = 0; // variable to store the value coming from the sensor
int led1 = 3;
SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);
void setup1() // run once, when the sketch starts
{pinMode(led1, OUTPUT);
Serial.begin(9600); // set the baud rate to 9600, same should be of your Serial Monitor
pinMode(13, OUTPUT);
}
void setup2()
{
myservo.attach(9);
Serial.begin(9600);
bluetooth.begin(9600);
}
void loop1()
{
Serial.println("hi");
sensorValue1 = analogRead(sensorPin1);
Serial.println(sensorValue1);
if (sensorValue1 < 100)
{
Serial.println("LED light on");
digitalWrite(led1,HIGH);
delay(1000);
}
digitalWrite(led1,LOW);
delay(sensorValue1);
if(Serial.available()){
while(Serial.available())
{
char inChar = (char)Serial.read(); //read the input
inputString += inChar; //make a string of the characters coming on serial
}
Serial.println(inputString);
while (Serial.available() > 0)
{ junk = Serial.read() ; } // clear the serial buffer
if(inputString == "a"){ //in case of 'a' turn the LED on
digitalWrite(13, HIGH);
}else if(inputString == "b"){ //incase of 'b' turn the LED off
digitalWrite(13, LOW);
}
inputString = "";
}
}
int sensorPin2 = A0; // select the input pin for the LDR
int sensorValue2 = 0; // variable to store the value coming from the sensor
int led2 = 3;
void setup3() { // declare the ledPin as an OUTPUT:
pinMode(led2, OUTPUT);
Serial.begin(9600); }
void loop2()
{
Serial.println("Welcome to TechPonder LDR Tutorial");
sensorValue2 = analogRead(sensorPin2);
Serial.println(sensorValue2);
if (sensorValue2 < 100)
{
Serial.println("LED light on");
digitalWrite(led2,HIGH);
delay(1000);
}
digitalWrite(led2,LOW);
delay(sensorValue2);
}
void loop3()
{
if(bluetooth.available()> 0 )
{
int servopos = bluetooth.read();
Serial.println(servopos);
myservo.write(servopos);
}
}
|
#include "RFM95.h"
// Singleton instance of the radio driver. Managed by preprocessor directives
RH_RF95 radio();
// Class to manage message delivery and receipt, using the driver declared above
RHReliableDatagram manager(rf95, SERVER_ADDRESS);
RFM95::RFM95()
{
}
void RFM95::initRadio()
{
Serial.begin(9600);
pinMode(LED, OUTPUT);
pinMode(RFM95_RST, OUTPUT);
digitalWrite(RFM95_RST, HIGH);
// manual reset
digitalWrite(RFM95_RST, LOW);
delay(10);
digitalWrite(RFM95_RST, HIGH);
delay(10);
// Defaults after init are 434.0MHz, 13dBm, Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on
if (!manager.init())
Serial.println("init failed");
if (!rf95.setFrequency(RF95_FREQ))
Serial.println("setFrequency failed");
rf95.setTxPower(23, false);
}
void RFM95::waitForMessage()
{
uint8_t data[] = "Acknowledged";
uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
char *vals;
if (manager.available())
{
// Wait for a message addressed to us from the client
uint8_t len = sizeof(buf);
uint8_t from;
if (manager.recvfromAck(buf, &len, &from))
{
vals = strtok((char *)buf, ",:");
char temp[10];
itoa(rf95.lastRssi(),temp,10);
// For every sensor type sent.
Serial.print("DHN/");
Serial.print(SERVER_ADDRESS, DEC);
Serial.print('/');
Serial.print(from, DEC);
while (vals != NULL && vals != temp)
{
Serial.print('/');
Serial.print(vals);
Serial.print('/');
vals = strtok(NULL, ",:");
Serial.print(vals);
vals = strtok(NULL, ",:");
}
Serial.print('\n');
// Serial.print("DHN/");
// Serial.print(SERVER_ADDRESS, DEC);
// Serial.print('/');
// Serial.print(from, DEC);
// Serial.print('/');
// Serial.print("RSSI/");
// Serial.print(rf95.lastRssi(), DEC);
// Serial.print('\n');
// Send a reply back to the originator client
if (!manager.sendtoWait(data, sizeof(data), from))
Serial.println("Ack failed");
}
}
}
// TODO: Make function return boolean on pass/fail
void RFM95::sendMessage(char *message, uint8_t length)
{
if (sizeof(message) > RH_RF95_MAX_MESSAGE_LEN)
{
Serial.println("Sending failed. Message too large for RFM95\n");
}
uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
// Send a message to manager_server
if (manager.sendtoWait((uint8_t *)message, length, SERVER_ADDRESS))
{
// Now wait for a reply from the server
uint8_t len = sizeof(buf);
uint8_t from;
if (manager.recvfromAckTimeout(buf, &len, 2000, &from))
{
Serial.print("Recieved reply from node ");
Serial.print(from, DEC);
Serial.print(": \n");
Serial.println((char *)buf);
blink(LED, 50, 3);
}
else
{
Serial.println("No reply, is gateway running?\n");
}
}
else
Serial.println("Sending failed.\n");
}
void RFM95::publishLogMsg(String msg)
{
Serial.print(F("/log:"));
Serial.print(msg);
Serial.print('\n');
}
void RFM95::blink(byte PIN, byte DELAY_MS, byte loops)
{
for (byte i = 0; i < loops; i++)
{
digitalWrite(PIN, HIGH);
delay(DELAY_MS);
digitalWrite(PIN, LOW);
delay(DELAY_MS);
}
}
|
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <algorithm>
#include <memory.h>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <string>
#include <string.h>
#include <vector>
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
const ld PI = acos(-1.);
using namespace std;
const int N = 505;
const int M = N * N / 2;
vector<int> g[N];
struct cell {
int sum;
int l, r;
} a[M + M + M + M];
int wh[M];
pair<int, int> edges[M];
int A[M], B[M];
void build(int x, int l, int r) {
a[x].l = l; a[x].r = r; a[x].sum = r - l + 1;
if (l != r) {
build(x + x, l, (l + r) >> 1);
build(x + x + 1, ((l + r) >> 1) + 1, r);
} else {
wh[l] = x;
}
}
inline void modify(int x) {
x = wh[x];
int add = 1 - a[x].sum - a[x].sum;
do {
a[x].sum += add;
x >>= 1;
} while (x);
}
inline int findk(int k) {
if (a[1].sum < k) return -1;
int x = 1;
while (a[x].l != a[x].r) {
if (a[x + x].sum < k) {
k -= a[x + x].sum;
x = x + x + 1;
} else {
x <<= 1;
}
}
return a[x].l;
}
int n, m, q;
inline void readi(int& x) {
char c = getchar();
while (c < '0' || c > '9') c = getchar();
do {
x = x * 10 + c - '0';
c = getchar();
} while (c >= '0' && c <= '9');
}
int main() {
freopen("roads.in", "r", stdin);
freopen("roads.out", "w", stdout);
readi(n); readi(m); readi(q);
for (int i = 0; i < m; ++i) {
readi(A[i]);
readi(B[i]);
readi(edges[i].first);
edges[i].second = i + 1;
}
sort(edges, edges + m);
for (int i = 0; i < m; ++i) {
g[ A[ edges[i].second - 1 ] ].push_back(i);
g[ B[ edges[i].second - 1 ] ].push_back(i);
}
build(1, 0, m - 1);
while (q--) {
int x = 0, k = 0;
readi(x); readi(k);
if (x == 1) {
for (int i = 0; i < g[k].size(); ++i)
modify(g[k][i]);
} else {
int res = findk(k);
if (res == -1) puts("-1");
else printf("%d\n", edges[res].second);
}
}
return 0;
}
|
/*
Petar 'PetarV' Velickovic
Algorithm: Segment Intersection
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
using namespace std;
typedef long long lld;
struct Point
{
double X, Y;
Point(double x, double y)
{
this->X = x;
this->Y = y;
}
};
//Algoritam koji odredjuje da li postoji presek izmedju dve 2D duzi (AB i CD)
//Slozenost: O(1)
inline double crossProduct(Point a, Point b, Point c)
{
return ((b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X));
}
inline bool isLeft(Point a, Point b, Point c)
{
return (crossProduct(a, b, c) > 0);
}
inline bool isCollinear(Point a, Point b, Point c)
{
return (crossProduct(a, b, c) == 0);
}
inline bool oppositeSides(Point a, Point b, Point c, Point d)
{
return (isLeft(a, b, c) != isLeft(a, b, d));
}
inline bool isBetween(Point a, Point b, Point c)
{
return (min(a.X, b.X) <= c.X && c.X <= max(a.X, b.X) && min(a.Y, b.Y) <= c.Y && c.Y <= max(a.Y,b.Y));
}
inline bool intersect(Point a, Point b, Point c, Point d)
{
if (isCollinear(a, b, c) && isBetween(a, b, c)) return true;
if (isCollinear(a, b, d) && isBetween(a, b, d)) return true;
if (isCollinear(c, d, a) && isBetween(c, d, a)) return true;
if (isCollinear(c, d, b) && isBetween(c, d, b)) return true;
return (oppositeSides(a, b, c, d) && oppositeSides(c, d, a, b));
}
int main()
{
Point A(0.0, 0.0), B(0.0, 2.0), C(-1.0, 2.0), D(1.0, 2.0);
printf(intersect(A,B,C,D) ? "YES" : "NO");
printf("\n");
return 0;
}
|
/**
* @file test.cpp
*
*
* @author Fan Kai(fk), Peking University
* @date 2008年03月31日 22时42分21秒 CST
*
*/
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/array.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_io.hpp>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem/operations.hpp>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
using namespace boost;
namespace fs=boost::filesystem;
class NC : public noncopyable {
public:
NC() { cout <<"Construct " <<endl; }
~NC() {cout <<"Destruct " <<endl; }
};
struct C {
friend class boost::serialization::access;
private:
template <class Archive>
void serialize(Archive &ar, const unsigned int) {
ar &i;
ar &s;
}
public:
C() {
s = "fuck";
cout <<"Construct " <<endl; }
~C() {cout <<"Destruct " <<endl; }
int i;
string s;
char c[50];
static void save(const C &cc, ofstream &fout) {
archive::text_oarchive bo(fout);
bo <<cc;
}
};
void test_serialization() {
shared_ptr<C> pp(new C());
C cc;
ofstream fout("a.txt");
//archive::text_oarchive oa(fout);
const C* ptr = &cc;
for (int i = 0; i < 10; ++i)
C::save(cc, fout);
}
void test_array() {
array<int, 5> ai;
for (array<int, 5>::iterator it = ai.begin();
it != ai.end(); ++it)
cout <<*it <<" ";
cout <<endl;
ai.assign(6);
for (int i = 0; i < ai.size(); ++i)
cout <<ai[i] <<" ";
cout <<endl;
array<double, 0> ad;
cout <<ad.size() <<endl;
}
void test_tuple() {
tuple<int, double, string> t(1, 2, "fuck");
cout <<t.get<0>() <<" " <<t.get<2>() <<endl;
cout <<t <<endl;
int i;
string s;
tie(i, tuples::ignore, s) = make_tuple(8, 9, "fuck");
cout <<i <<" " <<s <<endl;
vector<reference_wrapper<int> > rv;
int a[3] = {1,2,3};
for (int i = 0; i < 3; ++i)
rv.push_back(ref(a[i]));
for (int i = 0; i < 3; ++i)
cout <<rv[i] <<" ";
cout <<endl;
a[1] = 4;
for (int i = 0; i < 3; ++i)
cout <<rv[i] <<" ";
cout <<endl;
}
void test_regex() {
string s = "(f(u)(ck))";
string ss = "fuckk";
regex r(s);
smatch m;
cout <<regex_match(ss, m, r) <<endl;
cout <<m.size() <<" " <<r.mark_count() <<endl;
for (int i = 0; i < m.size(); ++i)
cout <<m[i] <<endl;
regex_search(ss, m, r);
cout <<m.size() <<" " <<r.mark_count() <<endl;
for (int i = 0; i < m.size(); ++i)
cout <<m[i] <<endl;
}
void test_string() {
string str("fuck the world, FUCK");
vector<string> sv;
split(sv, str, is_any_of(" "));
for (int i = 0; i < sv.size(); ++i)
cout <<sv[i] <<endl;
vector<iterator_range<string::iterator> > fv;
find_all(sv, str, "fuck");
for (int i = 0; i < sv.size(); ++i)
cout <<sv[i] <<endl;
ifind_all(sv, str, "fuck");
for (int i = 0; i < sv.size(); ++i)
cout <<sv[i] <<endl;
to_upper(str);
cout <<str <<endl;
}
void test_fs() {
cout <<fs::current_path().string() <<endl;
cout <<fs::initial_path().string() <<endl;
fs::path p(".");
cout <<p.root_name() <<endl;
cout <<p.leaf() <<endl;
cout <<p.is_complete() <<endl;
cout <<p.root_directory() <<endl;
cout <<getenv("HOME") <<endl;
}
int main() {
//test_array();
//test_tuple();
//test_regex();
//test_string();
//shared_ptr<int> pi(new int);
//shared_ptr<long long> pl(new long long);
shared_ptr<C> pc(new C());
//cout <<sizeof(pi) <<endl;
//cout <<sizeof(pl) <<endl;
cout <<sizeof(pc) <<endl;
test_fs();
return 0;
}
|
// Created on: 1997-02-12
// Created by: Alexander BRIVIN
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Vrml_PointLight_HeaderFile
#define _Vrml_PointLight_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Quantity_Color.hxx>
#include <gp_Vec.hxx>
#include <Standard_OStream.hxx>
//! defines a point light node of VRML specifying
//! properties of lights.
//! This node defines a point light source at a fixed 3D location
//! A point source illuminates equally in all directions;
//! that is omni-directional.
//! Color is written as an RGB triple.
//! Light intensity must be in the range 0.0 to 1.0, inclusive.
class Vrml_PointLight
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT Vrml_PointLight();
Standard_EXPORT Vrml_PointLight(const Standard_Boolean aOnOff, const Standard_Real aIntensity, const Quantity_Color& aColor, const gp_Vec& aLocation);
Standard_EXPORT void SetOnOff (const Standard_Boolean aOnOff);
Standard_EXPORT Standard_Boolean OnOff() const;
Standard_EXPORT void SetIntensity (const Standard_Real aIntensity);
Standard_EXPORT Standard_Real Intensity() const;
Standard_EXPORT void SetColor (const Quantity_Color& aColor);
Standard_EXPORT Quantity_Color Color() const;
Standard_EXPORT void SetLocation (const gp_Vec& aLocation);
Standard_EXPORT gp_Vec Location() const;
Standard_EXPORT Standard_OStream& Print (Standard_OStream& anOStream) const;
protected:
private:
Standard_Boolean myOnOff;
Standard_Real myIntensity;
Quantity_Color myColor;
gp_Vec myLocation;
};
#endif // _Vrml_PointLight_HeaderFile
|
// Created by: Nikolai BUKHALOV
// Copyright (c) 2015 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _GeomLib_CheckCurveOnSurface_HeaderFile
#define _GeomLib_CheckCurveOnSurface_HeaderFile
#include <Adaptor3d_Curve.hxx>
#include <Precision.hxx>
#include <Standard.hxx>
class Adaptor3d_CurveOnSurface;
//! Computes the max distance between 3D-curve and 2D-curve
//! in some surface.
class GeomLib_CheckCurveOnSurface
{
public:
DEFINE_STANDARD_ALLOC
//! Default constructor
Standard_EXPORT GeomLib_CheckCurveOnSurface(void);
//! Constructor
Standard_EXPORT
GeomLib_CheckCurveOnSurface(const Handle(Adaptor3d_Curve)& theCurve,
const Standard_Real theTolRange =
Precision::PConfusion());
//! Sets the data for the algorithm
Standard_EXPORT void Init (const Handle(Adaptor3d_Curve)& theCurve,
const Standard_Real theTolRange = Precision::PConfusion());
//! Initializes all members by default values
Standard_EXPORT void Init();
//! Computes the max distance for the 3d curve <myCurve>
//! and 2d curve <theCurveOnSurface>
//! If isMultiThread == Standard_True then computation will be performed in parallel.
Standard_EXPORT void Perform(const Handle(Adaptor3d_CurveOnSurface)& theCurveOnSurface);
//! Sets parallel flag
void SetParallel(const Standard_Boolean theIsParallel)
{
myIsParallel = theIsParallel;
}
//! Returns true if parallel flag is set
Standard_Boolean IsParallel()
{
return myIsParallel;
}
//! Returns true if the max distance has been found
Standard_Boolean IsDone() const
{
return (myErrorStatus == 0);
}
//! Returns error status
//! The possible values are:
//! 0 - OK;
//! 1 - null curve or surface or 2d curve;
//! 2 - invalid parametric range;
//! 3 - error in calculations.
Standard_Integer ErrorStatus() const
{
return myErrorStatus;
}
//! Returns max distance
Standard_Real MaxDistance() const
{
return myMaxDistance;
}
//! Returns parameter in which the distance is maximal
Standard_Real MaxParameter() const
{
return myMaxParameter;
}
private:
Handle(Adaptor3d_Curve) myCurve;
Standard_Integer myErrorStatus;
Standard_Real myMaxDistance;
Standard_Real myMaxParameter;
Standard_Real myTolRange;
Standard_Boolean myIsParallel;
};
#endif // _BRepLib_CheckCurveOnSurface_HeaderFile
|
#include <deque>
#include "Token.h"
#include "Lexer.h"
#ifndef ORDER_H
#define ORDER_H
class Order
{
public:
std::deque < Token > tokens;
enum Type { term, text, declar, loop_start, loop_stop, if_statement, if_stop, print, printValues, revalue, revalueSTR, skip};
Type type;
std::string GetTypeSTR()
{
switch (type)
{
case term:
return "term";
case declar:
return "declar";
case loop_start:
return "loop_start";
case loop_stop:
return "loop_stop";
case if_statement:
return "if_statement";
case if_stop:
return "if_stop";
case print:
return "print";
case revalue:
return "revalue";
default:
return "Unknown type";
}
}
void printTokens(std::unordered_map<std::string, Token> variables)
{
Lexer lexer("", "");
for (int i = 0; i < tokens.size(); i++)
{
if (tokens[i].Type == lexer.TT_VARNAME)
{
std::cout << variables[tokens[i].Value].Value;
}
else if (tokens[i].Value != "None")
std::cout << tokens[i].Value << ' ';
else
{
bool found = false;
Lexer lexer("", "");
for (auto const& x : lexer.GetOpSymb())
{
if (x.second == tokens[i].Type)
{
std::cout << x.first << ' ';
found = true;
break;
}
}
if (!found)
for (auto const& x : lexer.GetKeyWords())
{
if (x.second == tokens[i].Type)
{
std::cout << x.first << ' ';
break;
}
}
}
}
std::cout << std::endl;
}
};
#endif
|
#include <algorithm>
#include <array>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <vector>
uint32_t add(uint32_t a, uint32_t b) { return a + b; }
void round(std::array<uint32_t, 32>& state) {
// 1. add
for (uint32_t i = 0; i < 16; i++) {
state[16 + i] = add(state[16 + i], state[i]);
}
// 2. rotate 7
for (uint32_t i = 0; i < 16; i++) {
state[i] = (state[i] << 7) | (state[i] >> 25);
}
// 3. swap
for (uint32_t i = 0; i < 8; i++) {
std::swap(state[i], state[i + 8]);
}
// 4. xor
for (uint32_t i = 0; i < 16; i++) {
state[i] ^= state[16 + i];
}
// 5. swap
for (uint32_t i = 0; i < 4; i++) {
std::swap(state[16 + i * 4], state[18 + i * 4]);
std::swap(state[17 + i * 4], state[19 + i * 4]);
}
// 6. add == 1
for (uint32_t i = 0; i < 16; i++) {
state[16 + i] = add(state[16 + i], state[i]);
}
// 7. rotate 11
for (uint32_t i = 0; i < 16; i++) {
state[i] = (state[i] << 11) | (state[i] >> 21);
}
// 8. swap
for (uint32_t i = 0; i < 2; i++) {
for (uint32_t j = 0; j < 4; j++) {
std::swap(state[i * 8 + j], state[i * 8 + j + 4]);
}
}
// 9. xor
for (uint32_t i = 0; i < 16; i++) {
state[i] ^= state[16 + i];
}
// 10. swap
for (uint32_t i = 0; i < 8; i++) {
std::swap(state[16 + i * 2], state[i * 2 + 17]);
}
}
template <uint32_t I, uint32_t R, uint32_t B, uint32_t F, uint32_t H>
void cubehash(const uint8_t* in, uint8_t* out, uint64_t len) {
std::array<uint32_t, 32> state_4byte;
uint8_t* state_1byte = reinterpret_cast<uint8_t*>(state_4byte.data());
// init
for (size_t i = 0; i < 32; i++) {
state_4byte[i] = 0;
}
state_4byte[0] = H / 8;
state_4byte[1] = B;
state_4byte[2] = R;
for (uint32_t i = 0; i < I; i++) {
round(state_4byte);
}
auto nlen = B * (len / B + 1);
std::vector<uint8_t> nin(nlen);
std::memcpy(nin.data(), in, len);
nin[len] = 1 << 7;
// working
for (uint64_t i = 0; i < nlen; i += B) {
// mix message with state
for (uint32_t j = 0; j < B; j++) {
state_1byte[j] ^= nin[i + j];
}
// roundit
for (uint32_t i = 0; i < R; i++) {
round(state_4byte);
}
}
// final
state_4byte[31] ^= 1;
for (uint32_t i = 0; i < F; i++) {
round(state_4byte);
}
// writing result
std::memcpy(out, state_1byte, H / 8);
}
template <uint32_t I, uint32_t R, uint32_t B, uint32_t F, uint32_t H>
std::string cubehash(std::string const& s) {
uint8_t res[H / 8];
cubehash<I, R, B, F, H>(reinterpret_cast<const uint8_t*>(s.c_str()), res,
s.length());
std::stringstream ss;
for (size_t i = 0; i < H / 8; i++) {
ss << std::hex << std::setw(2) << std::setfill('0')
<< static_cast<uint32_t>(res[i]);
}
return ss.str();
}
template <uint32_t I, uint32_t R, uint32_t B, uint32_t F, uint32_t H>
void test(std::string const& mes, std::string const& exp) {
auto got = cubehash<I, R, B, F, H>(mes);
if (got != exp) {
throw std::runtime_error("Test failed \n" + exp + "\n" + got);
}
}
void test_them_all() {
test<80, 8, 1, 80, 512>(
"Hello",
"7ce309a25e2e1603ca0fc369267b4d43f0b1b744ac45d6213ca08e75675664448e2"
"f62fdbf7bbd637ce40fc293286d75b9d09e8dda31bd029113e02ecccfd39b");
test<80, 8, 1, 80, 512>(
"hello",
"01ee7f4eb0e0ebfdb8bf77460f64993faf13afce01b55b0d3d2a63690d25010f712710"
"9455a7c143ef12254183e762b15575e0fcc49c79a0471a970ba8a66638");
test<160, 16, 32, 160, 512>(
"", "4a1d00bbcfcb5a9562fb981e7f7db3350fe2658639d948b9d57452c22328bb32"
"f468b072208450bad5ee178271408be0b16e5633ac8a1e3cf9864cfbfc8e043a");
test<80, 8, 1, 80, 512>(
"", "90bc3f2948f7374065a811f1e47a208a53b1a2f3be1c0072759ed49c9c6c7f28"
"f26eb30d5b0658c563077d599da23f97df0c2c0ac6cce734ffe87b2e76ff7294");
test<10, 1, 1, 10, 512>(
"", "3f917707df9acd9b94244681b3812880e267d204f1fdf795d398799b584fa8f1f4"
"a0b2dbd52fd1c4b6c5e020dc7a96192397dd1bce9b6d16484049f85bb71f2f");
test<160, 16, 32, 160, 256>(
"", "44c6de3ac6c73c391bf0906cb7482600ec06b216c7c54a2a8688a6a42676577d");
test<80, 8, 1, 80, 256>(
"", "38d1e8a22d7baac6fd5262d83de89cacf784a02caa866335299987722aeabc59");
test<10, 1, 1, 10, 256>(
"", "80f72e07d04ddadb44a78823e0af2ea9f72ef3bf366fd773aa1fa33fc030e5cb");
auto message = "The quick brown fox jumps over the lazy dog";
test<160, 16, 32, 160, 512>(
message,
"bdba44a28cd16b774bdf3c9511def1a2baf39d4ef98b92c27cf5e37beb8990b7"
"cdb6575dae1a548330780810618b8a5c351c1368904db7ebdf8857d596083a86");
test<80, 8, 1, 80, 512>(
message,
"ca942b088ed9103726af1fa87b4deb59e50cf3b5c6dcfbcebf5bba22fb39a6be"
"9936c87bfdd7c52fc5e71700993958fa4e7b5e6e2a3672122475c40f9ec816ba");
}
int main(int argc, char* argv[]) {
try {
test_them_all();
} catch (std::runtime_error const& e) {
std::cout << e.what();
return -1;
}
std::cout << "All tests passed!" << std::endl;
if (argc < 2)
return -1;
std::cout << "CubeHash 80+8/1+80-512 of \"" << argv[1]
<< "\" is:" << std::endl;
std::cout << cubehash<80, 8, 1, 80, 512>(argv[1]) << std::endl;
}
|
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
#include "cmListCommand.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdio>
#include <cstdlib> // required for atoi
#include <functional>
#include <iterator>
#include <set>
#include <sstream>
#include <stdexcept>
#include <utility>
#include <vector>
#include <cm/memory>
#include "cmsys/RegularExpression.hxx"
#include "cm_static_string_view.hxx"
#include "cmAlgorithms.h"
#include "cmExecutionStatus.h"
#include "cmGeneratorExpression.h"
#include "cmMakefile.h"
#include "cmMessageType.h"
#include "cmPolicies.h"
#include "cmRange.h"
#include "cmStringAlgorithms.h"
#include "cmStringReplaceHelper.h"
#include "cmSubcommandTable.h"
#include "cmSystemTools.h"
namespace {
bool FilterRegex(std::vector<std::string> const& args, bool includeMatches,
std::string const& listName,
std::vector<std::string>& varArgsExpanded,
cmExecutionStatus& status);
bool GetListString(std::string& listString, const std::string& var,
const cmMakefile& makefile)
{
// get the old value
const char* cacheValue = makefile.GetDefinition(var);
if (!cacheValue) {
return false;
}
listString = cacheValue;
return true;
}
bool GetList(std::vector<std::string>& list, const std::string& var,
const cmMakefile& makefile)
{
std::string listString;
if (!GetListString(listString, var, makefile)) {
return false;
}
// if the size of the list
if (listString.empty()) {
return true;
}
// expand the variable into a list
cmExpandList(listString, list, true);
// if no empty elements then just return
if (!cmContains(list, std::string())) {
return true;
}
// if we have empty elements we need to check policy CMP0007
switch (makefile.GetPolicyStatus(cmPolicies::CMP0007)) {
case cmPolicies::WARN: {
// Default is to warn and use old behavior
// OLD behavior is to allow compatibility, so recall
// ExpandListArgument without the true which will remove
// empty values
list.clear();
cmExpandList(listString, list);
std::string warn =
cmStrCat(cmPolicies::GetPolicyWarning(cmPolicies::CMP0007),
" List has value = [", listString, "].");
makefile.IssueMessage(MessageType::AUTHOR_WARNING, warn);
return true;
}
case cmPolicies::OLD:
// OLD behavior is to allow compatibility, so recall
// ExpandListArgument without the true which will remove
// empty values
list.clear();
cmExpandList(listString, list);
return true;
case cmPolicies::NEW:
return true;
case cmPolicies::REQUIRED_IF_USED:
case cmPolicies::REQUIRED_ALWAYS:
makefile.IssueMessage(
MessageType::FATAL_ERROR,
cmPolicies::GetRequiredPolicyError(cmPolicies::CMP0007));
return false;
}
return true;
}
bool HandleLengthCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
if (args.size() != 3) {
status.SetError("sub-command LENGTH requires two arguments.");
return false;
}
const std::string& listName = args[1];
const std::string& variableName = args.back();
std::vector<std::string> varArgsExpanded;
// do not check the return value here
// if the list var is not found varArgsExpanded will have size 0
// and we will return 0
GetList(varArgsExpanded, listName, status.GetMakefile());
size_t length = varArgsExpanded.size();
char buffer[1024];
sprintf(buffer, "%d", static_cast<int>(length));
status.GetMakefile().AddDefinition(variableName, buffer);
return true;
}
bool HandleGetCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
if (args.size() < 4) {
status.SetError("sub-command GET requires at least three arguments.");
return false;
}
const std::string& listName = args[1];
const std::string& variableName = args.back();
// expand the variable
std::vector<std::string> varArgsExpanded;
if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
status.GetMakefile().AddDefinition(variableName, "NOTFOUND");
return true;
}
// FIXME: Add policy to make non-existing lists an error like empty lists.
if (varArgsExpanded.empty()) {
status.SetError("GET given empty list");
return false;
}
std::string value;
size_t cc;
const char* sep = "";
size_t nitem = varArgsExpanded.size();
for (cc = 2; cc < args.size() - 1; cc++) {
int item = atoi(args[cc].c_str());
value += sep;
sep = ";";
if (item < 0) {
item = static_cast<int>(nitem) + item;
}
if (item < 0 || nitem <= static_cast<size_t>(item)) {
status.SetError(cmStrCat("index: ", item, " out of range (-", nitem,
", ", nitem - 1, ")"));
return false;
}
value += varArgsExpanded[item];
}
status.GetMakefile().AddDefinition(variableName, value);
return true;
}
bool HandleAppendCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
assert(args.size() >= 2);
// Skip if nothing to append.
if (args.size() < 3) {
return true;
}
cmMakefile& makefile = status.GetMakefile();
std::string const& listName = args[1];
// expand the variable
std::string listString;
GetListString(listString, listName, makefile);
// If `listString` or `args` is empty, no need to append `;`,
// then index is going to be `1` and points to the end-of-string ";"
auto const offset =
std::string::size_type(listString.empty() || args.empty());
listString += &";"[offset] + cmJoin(cmMakeRange(args).advance(2), ";");
makefile.AddDefinition(listName, listString);
return true;
}
bool HandlePrependCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
assert(args.size() >= 2);
// Skip if nothing to prepend.
if (args.size() < 3) {
return true;
}
cmMakefile& makefile = status.GetMakefile();
std::string const& listName = args[1];
// expand the variable
std::string listString;
GetListString(listString, listName, makefile);
// If `listString` or `args` is empty, no need to append `;`,
// then `offset` is going to be `1` and points to the end-of-string ";"
auto const offset =
std::string::size_type(listString.empty() || args.empty());
listString.insert(0,
cmJoin(cmMakeRange(args).advance(2), ";") + &";"[offset]);
makefile.AddDefinition(listName, listString);
return true;
}
bool HandlePopBackCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
assert(args.size() >= 2);
cmMakefile& makefile = status.GetMakefile();
auto ai = args.cbegin();
++ai; // Skip subcommand name
std::string const& listName = *ai++;
std::vector<std::string> varArgsExpanded;
if (!GetList(varArgsExpanded, listName, makefile)) {
// Can't get the list definition... undefine any vars given after.
for (; ai != args.cend(); ++ai) {
makefile.RemoveDefinition(*ai);
}
return true;
}
if (!varArgsExpanded.empty()) {
if (ai == args.cend()) {
// No variables are given... Just remove one element.
varArgsExpanded.pop_back();
} else {
// Ok, assign elements to be removed to the given variables
for (; !varArgsExpanded.empty() && ai != args.cend(); ++ai) {
assert(!ai->empty());
makefile.AddDefinition(*ai, varArgsExpanded.back());
varArgsExpanded.pop_back();
}
// Undefine the rest variables if the list gets empty earlier...
for (; ai != args.cend(); ++ai) {
makefile.RemoveDefinition(*ai);
}
}
makefile.AddDefinition(listName, cmJoin(varArgsExpanded, ";"));
} else if (ai !=
args.cend()) { // The list is empty, but some args were given
// Need to *undefine* 'em all, cuz there are no items to assign...
for (; ai != args.cend(); ++ai) {
makefile.RemoveDefinition(*ai);
}
}
return true;
}
bool HandlePopFrontCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
assert(args.size() >= 2);
cmMakefile& makefile = status.GetMakefile();
auto ai = args.cbegin();
++ai; // Skip subcommand name
std::string const& listName = *ai++;
std::vector<std::string> varArgsExpanded;
if (!GetList(varArgsExpanded, listName, makefile)) {
// Can't get the list definition... undefine any vars given after.
for (; ai != args.cend(); ++ai) {
makefile.RemoveDefinition(*ai);
}
return true;
}
if (!varArgsExpanded.empty()) {
if (ai == args.cend()) {
// No variables are given... Just remove one element.
varArgsExpanded.erase(varArgsExpanded.begin());
} else {
// Ok, assign elements to be removed to the given variables
auto vi = varArgsExpanded.begin();
for (; vi != varArgsExpanded.end() && ai != args.cend(); ++ai, ++vi) {
assert(!ai->empty());
makefile.AddDefinition(*ai, *vi);
}
varArgsExpanded.erase(varArgsExpanded.begin(), vi);
// Undefine the rest variables if the list gets empty earlier...
for (; ai != args.cend(); ++ai) {
makefile.RemoveDefinition(*ai);
}
}
makefile.AddDefinition(listName, cmJoin(varArgsExpanded, ";"));
} else if (ai !=
args.cend()) { // The list is empty, but some args were given
// Need to *undefine* 'em all, cuz there are no items to assign...
for (; ai != args.cend(); ++ai) {
makefile.RemoveDefinition(*ai);
}
}
return true;
}
bool HandleFindCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
if (args.size() != 4) {
status.SetError("sub-command FIND requires three arguments.");
return false;
}
const std::string& listName = args[1];
const std::string& variableName = args.back();
// expand the variable
std::vector<std::string> varArgsExpanded;
if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
status.GetMakefile().AddDefinition(variableName, "-1");
return true;
}
auto it = std::find(varArgsExpanded.begin(), varArgsExpanded.end(), args[2]);
if (it != varArgsExpanded.end()) {
status.GetMakefile().AddDefinition(
variableName,
std::to_string(std::distance(varArgsExpanded.begin(), it)));
return true;
}
status.GetMakefile().AddDefinition(variableName, "-1");
return true;
}
bool HandleInsertCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
if (args.size() < 4) {
status.SetError("sub-command INSERT requires at least three arguments.");
return false;
}
const std::string& listName = args[1];
// expand the variable
int item = atoi(args[2].c_str());
std::vector<std::string> varArgsExpanded;
if ((!GetList(varArgsExpanded, listName, status.GetMakefile()) ||
varArgsExpanded.empty()) &&
item != 0) {
status.SetError(cmStrCat("index: ", item, " out of range (0, 0)"));
return false;
}
if (!varArgsExpanded.empty()) {
size_t nitem = varArgsExpanded.size();
if (item < 0) {
item = static_cast<int>(nitem) + item;
}
if (item < 0 || nitem < static_cast<size_t>(item)) {
status.SetError(cmStrCat("index: ", item, " out of range (-",
varArgsExpanded.size(), ", ",
varArgsExpanded.size(), ")"));
return false;
}
}
varArgsExpanded.insert(varArgsExpanded.begin() + item, args.begin() + 3,
args.end());
std::string value = cmJoin(varArgsExpanded, ";");
status.GetMakefile().AddDefinition(listName, value);
return true;
}
bool HandleJoinCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
if (args.size() != 4) {
status.SetError(cmStrCat("sub-command JOIN requires three arguments (",
args.size() - 1, " found)."));
return false;
}
const std::string& listName = args[1];
const std::string& glue = args[2];
const std::string& variableName = args[3];
// expand the variable
std::vector<std::string> varArgsExpanded;
if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
status.GetMakefile().AddDefinition(variableName, "");
return true;
}
std::string value =
cmJoin(cmMakeRange(varArgsExpanded.begin(), varArgsExpanded.end()), glue);
status.GetMakefile().AddDefinition(variableName, value);
return true;
}
bool HandleRemoveItemCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
if (args.size() < 3) {
status.SetError("sub-command REMOVE_ITEM requires two or more arguments.");
return false;
}
const std::string& listName = args[1];
// expand the variable
std::vector<std::string> varArgsExpanded;
if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
return true;
}
std::vector<std::string> remove(args.begin() + 2, args.end());
std::sort(remove.begin(), remove.end());
auto remEnd = std::unique(remove.begin(), remove.end());
auto remBegin = remove.begin();
auto argsEnd =
cmRemoveMatching(varArgsExpanded, cmMakeRange(remBegin, remEnd));
auto argsBegin = varArgsExpanded.cbegin();
std::string value = cmJoin(cmMakeRange(argsBegin, argsEnd), ";");
status.GetMakefile().AddDefinition(listName, value);
return true;
}
bool HandleReverseCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
assert(args.size() >= 2);
if (args.size() > 2) {
status.SetError("sub-command REVERSE only takes one argument.");
return false;
}
const std::string& listName = args[1];
// expand the variable
std::vector<std::string> varArgsExpanded;
if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
return true;
}
std::string value = cmJoin(cmReverseRange(varArgsExpanded), ";");
status.GetMakefile().AddDefinition(listName, value);
return true;
}
bool HandleRemoveDuplicatesCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
assert(args.size() >= 2);
if (args.size() > 2) {
status.SetError("sub-command REMOVE_DUPLICATES only takes one argument.");
return false;
}
const std::string& listName = args[1];
// expand the variable
std::vector<std::string> varArgsExpanded;
if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
return true;
}
auto argsEnd = cmRemoveDuplicates(varArgsExpanded);
auto argsBegin = varArgsExpanded.cbegin();
std::string value = cmJoin(cmMakeRange(argsBegin, argsEnd), ";");
status.GetMakefile().AddDefinition(listName, value);
return true;
}
// Helpers for list(TRANSFORM <list> ...)
using transform_type = std::function<std::string(const std::string&)>;
class transform_error : public std::runtime_error
{
public:
transform_error(const std::string& error)
: std::runtime_error(error)
{
}
};
class TransformSelector
{
public:
virtual ~TransformSelector() = default;
std::string Tag;
virtual bool Validate(std::size_t count = 0) = 0;
virtual bool InSelection(const std::string&) = 0;
virtual void Transform(std::vector<std::string>& list,
const transform_type& transform)
{
std::transform(list.begin(), list.end(), list.begin(), transform);
}
protected:
TransformSelector(std::string&& tag)
: Tag(std::move(tag))
{
}
};
class TransformNoSelector : public TransformSelector
{
public:
TransformNoSelector()
: TransformSelector("NO SELECTOR")
{
}
bool Validate(std::size_t) override { return true; }
bool InSelection(const std::string&) override { return true; }
};
class TransformSelectorRegex : public TransformSelector
{
public:
TransformSelectorRegex(const std::string& regex)
: TransformSelector("REGEX")
, Regex(regex)
{
}
bool Validate(std::size_t) override { return this->Regex.is_valid(); }
bool InSelection(const std::string& value) override
{
return this->Regex.find(value);
}
cmsys::RegularExpression Regex;
};
class TransformSelectorIndexes : public TransformSelector
{
public:
std::vector<int> Indexes;
bool InSelection(const std::string&) override { return true; }
void Transform(std::vector<std::string>& list,
const transform_type& transform) override
{
this->Validate(list.size());
for (auto index : this->Indexes) {
list[index] = transform(list[index]);
}
}
protected:
TransformSelectorIndexes(std::string&& tag)
: TransformSelector(std::move(tag))
{
}
TransformSelectorIndexes(std::string&& tag, std::vector<int>&& indexes)
: TransformSelector(std::move(tag))
, Indexes(indexes)
{
}
int NormalizeIndex(int index, std::size_t count)
{
if (index < 0) {
index = static_cast<int>(count) + index;
}
if (index < 0 || count <= static_cast<std::size_t>(index)) {
throw transform_error(cmStrCat(
"sub-command TRANSFORM, selector ", this->Tag, ", index: ", index,
" out of range (-", count, ", ", count - 1, ")."));
}
return index;
}
};
class TransformSelectorAt : public TransformSelectorIndexes
{
public:
TransformSelectorAt(std::vector<int>&& indexes)
: TransformSelectorIndexes("AT", std::move(indexes))
{
}
bool Validate(std::size_t count) override
{
decltype(Indexes) indexes;
for (auto index : Indexes) {
indexes.push_back(this->NormalizeIndex(index, count));
}
this->Indexes = std::move(indexes);
return true;
}
};
class TransformSelectorFor : public TransformSelectorIndexes
{
public:
TransformSelectorFor(int start, int stop, int step)
: TransformSelectorIndexes("FOR")
, Start(start)
, Stop(stop)
, Step(step)
{
}
bool Validate(std::size_t count) override
{
this->Start = this->NormalizeIndex(this->Start, count);
this->Stop = this->NormalizeIndex(this->Stop, count);
// compute indexes
auto size = (this->Stop - this->Start + 1) / this->Step;
if ((this->Stop - this->Start + 1) % this->Step != 0) {
size += 1;
}
this->Indexes.resize(size);
auto start = this->Start;
auto step = this->Step;
std::generate(this->Indexes.begin(), this->Indexes.end(),
[&start, step]() -> int {
auto r = start;
start += step;
return r;
});
return true;
}
private:
int Start, Stop, Step;
};
class TransformAction
{
public:
virtual ~TransformAction() = default;
virtual std::string Transform(const std::string& input) = 0;
};
class TransformReplace : public TransformAction
{
public:
TransformReplace(const std::vector<std::string>& arguments,
cmMakefile* makefile)
: ReplaceHelper(arguments[0], arguments[1], makefile)
{
makefile->ClearMatches();
if (!this->ReplaceHelper.IsRegularExpressionValid()) {
throw transform_error(
cmStrCat("sub-command TRANSFORM, action REPLACE: Failed to compile "
"regex \"",
arguments[0], "\"."));
}
if (!this->ReplaceHelper.IsReplaceExpressionValid()) {
throw transform_error(cmStrCat("sub-command TRANSFORM, action REPLACE: ",
this->ReplaceHelper.GetError(), "."));
}
}
std::string Transform(const std::string& input) override
{
// Scan through the input for all matches.
std::string output;
if (!this->ReplaceHelper.Replace(input, output)) {
throw transform_error(cmStrCat("sub-command TRANSFORM, action REPLACE: ",
this->ReplaceHelper.GetError(), "."));
}
return output;
}
private:
cmStringReplaceHelper ReplaceHelper;
};
bool HandleTransformCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
if (args.size() < 3) {
status.SetError(
"sub-command TRANSFORM requires an action to be specified.");
return false;
}
// Structure collecting all elements of the command
struct Command
{
Command(const std::string& listName)
: ListName(listName)
, OutputName(listName)
{
}
std::string Name;
std::string ListName;
std::vector<std::string> Arguments;
std::unique_ptr<TransformAction> Action;
std::unique_ptr<TransformSelector> Selector;
std::string OutputName;
} command(args[1]);
// Descriptor of action
// Arity: number of arguments required for the action
// Transform: lambda function implementing the action
struct ActionDescriptor
{
ActionDescriptor(std::string name)
: Name(std::move(name))
{
}
ActionDescriptor(std::string name, int arity, transform_type transform)
: Name(std::move(name))
, Arity(arity)
#if defined(__GNUC__) && __GNUC__ == 6 && defined(__aarch64__)
// std::function move constructor miscompiles on this architecture
, Transform(transform)
#else
, Transform(std::move(transform))
#endif
{
}
operator const std::string&() const { return Name; }
std::string Name;
int Arity = 0;
transform_type Transform;
};
// Build a set of supported actions.
std::set<ActionDescriptor,
std::function<bool(const std::string&, const std::string&)>>
descriptors(
[](const std::string& x, const std::string& y) { return x < y; });
descriptors = { { "APPEND", 1,
[&command](const std::string& s) -> std::string {
if (command.Selector->InSelection(s)) {
return s + command.Arguments[0];
}
return s;
} },
{ "PREPEND", 1,
[&command](const std::string& s) -> std::string {
if (command.Selector->InSelection(s)) {
return command.Arguments[0] + s;
}
return s;
} },
{ "TOUPPER", 0,
[&command](const std::string& s) -> std::string {
if (command.Selector->InSelection(s)) {
return cmSystemTools::UpperCase(s);
}
return s;
} },
{ "TOLOWER", 0,
[&command](const std::string& s) -> std::string {
if (command.Selector->InSelection(s)) {
return cmSystemTools::LowerCase(s);
}
return s;
} },
{ "STRIP", 0,
[&command](const std::string& s) -> std::string {
if (command.Selector->InSelection(s)) {
return cmTrimWhitespace(s);
}
return s;
} },
{ "GENEX_STRIP", 0,
[&command](const std::string& s) -> std::string {
if (command.Selector->InSelection(s)) {
return cmGeneratorExpression::Preprocess(
s,
cmGeneratorExpression::StripAllGeneratorExpressions);
}
return s;
} },
{ "REPLACE", 2,
[&command](const std::string& s) -> std::string {
if (command.Selector->InSelection(s)) {
return command.Action->Transform(s);
}
return s;
} } };
using size_type = std::vector<std::string>::size_type;
size_type index = 2;
// Parse all possible function parameters
auto descriptor = descriptors.find(args[index]);
if (descriptor == descriptors.end()) {
status.SetError(
cmStrCat(" sub-command TRANSFORM, ", args[index], " invalid action."));
return false;
}
// Action arguments
index += 1;
if (args.size() < index + descriptor->Arity) {
status.SetError(cmStrCat("sub-command TRANSFORM, action ",
descriptor->Name, " expects ", descriptor->Arity,
" argument(s)."));
return false;
}
command.Name = descriptor->Name;
index += descriptor->Arity;
if (descriptor->Arity > 0) {
command.Arguments =
std::vector<std::string>(args.begin() + 3, args.begin() + index);
}
if (command.Name == "REPLACE") {
try {
command.Action = cm::make_unique<TransformReplace>(
command.Arguments, &status.GetMakefile());
} catch (const transform_error& e) {
status.SetError(e.what());
return false;
}
}
const std::string REGEX{ "REGEX" };
const std::string AT{ "AT" };
const std::string FOR{ "FOR" };
const std::string OUTPUT_VARIABLE{ "OUTPUT_VARIABLE" };
// handle optional arguments
while (args.size() > index) {
if ((args[index] == REGEX || args[index] == AT || args[index] == FOR) &&
command.Selector) {
status.SetError(
cmStrCat("sub-command TRANSFORM, selector already specified (",
command.Selector->Tag, ")."));
return false;
}
// REGEX selector
if (args[index] == REGEX) {
if (args.size() == ++index) {
status.SetError("sub-command TRANSFORM, selector REGEX expects "
"'regular expression' argument.");
return false;
}
command.Selector = cm::make_unique<TransformSelectorRegex>(args[index]);
if (!command.Selector->Validate()) {
status.SetError(
cmStrCat("sub-command TRANSFORM, selector REGEX failed to compile "
"regex \"",
args[index], "\"."));
return false;
}
index += 1;
continue;
}
// AT selector
if (args[index] == AT) {
// get all specified indexes
std::vector<int> indexes;
while (args.size() > ++index) {
std::size_t pos;
int value;
try {
value = std::stoi(args[index], &pos);
if (pos != args[index].length()) {
// this is not a number, stop processing
break;
}
indexes.push_back(value);
} catch (const std::invalid_argument&) {
// this is not a number, stop processing
break;
}
}
if (indexes.empty()) {
status.SetError(
"sub-command TRANSFORM, selector AT expects at least one "
"numeric value.");
return false;
}
command.Selector =
cm::make_unique<TransformSelectorAt>(std::move(indexes));
continue;
}
// FOR selector
if (args[index] == FOR) {
if (args.size() <= ++index + 1) {
status.SetError(
"sub-command TRANSFORM, selector FOR expects, at least,"
" two arguments.");
return false;
}
int start = 0;
int stop = 0;
int step = 1;
bool valid = true;
try {
std::size_t pos;
start = std::stoi(args[index], &pos);
if (pos != args[index].length()) {
// this is not a number
valid = false;
} else {
stop = std::stoi(args[++index], &pos);
if (pos != args[index].length()) {
// this is not a number
valid = false;
}
}
} catch (const std::invalid_argument&) {
// this is not numbers
valid = false;
}
if (!valid) {
status.SetError("sub-command TRANSFORM, selector FOR expects, "
"at least, two numeric values.");
return false;
}
// try to read a third numeric value for step
if (args.size() > ++index) {
try {
std::size_t pos;
step = std::stoi(args[index], &pos);
if (pos != args[index].length()) {
// this is not a number
step = 1;
} else {
index += 1;
}
} catch (const std::invalid_argument&) {
// this is not number, ignore exception
}
}
if (step < 0) {
status.SetError("sub-command TRANSFORM, selector FOR expects "
"non negative numeric value for <step>.");
}
command.Selector =
cm::make_unique<TransformSelectorFor>(start, stop, step);
continue;
}
// output variable
if (args[index] == OUTPUT_VARIABLE) {
if (args.size() == ++index) {
status.SetError("sub-command TRANSFORM, OUTPUT_VARIABLE "
"expects variable name argument.");
return false;
}
command.OutputName = args[index++];
continue;
}
status.SetError(cmStrCat("sub-command TRANSFORM, '",
cmJoin(cmMakeRange(args).advance(index), " "),
"': unexpected argument(s)."));
return false;
}
// expand the list variable
std::vector<std::string> varArgsExpanded;
if (!GetList(varArgsExpanded, command.ListName, status.GetMakefile())) {
status.GetMakefile().AddDefinition(command.OutputName, "");
return true;
}
if (!command.Selector) {
// no selector specified, apply transformation to all elements
command.Selector = cm::make_unique<TransformNoSelector>();
}
try {
command.Selector->Transform(varArgsExpanded, descriptor->Transform);
} catch (const transform_error& e) {
status.SetError(e.what());
return false;
}
status.GetMakefile().AddDefinition(command.OutputName,
cmJoin(varArgsExpanded, ";"));
return true;
}
class cmStringSorter
{
public:
enum class Order
{
UNINITIALIZED,
ASCENDING,
DESCENDING,
};
enum class Compare
{
UNINITIALIZED,
STRING,
FILE_BASENAME,
};
enum class CaseSensitivity
{
UNINITIALIZED,
SENSITIVE,
INSENSITIVE,
};
protected:
using StringFilter = std::string (*)(const std::string&);
StringFilter GetCompareFilter(Compare compare)
{
return (compare == Compare::FILE_BASENAME) ? cmSystemTools::GetFilenameName
: nullptr;
}
StringFilter GetCaseFilter(CaseSensitivity sensitivity)
{
return (sensitivity == CaseSensitivity::INSENSITIVE)
? cmSystemTools::LowerCase
: nullptr;
}
public:
cmStringSorter(Compare compare, CaseSensitivity caseSensitivity,
Order desc = Order::ASCENDING)
: filters{ GetCompareFilter(compare), GetCaseFilter(caseSensitivity) }
, descending(desc == Order::DESCENDING)
{
}
std::string ApplyFilter(const std::string& argument)
{
std::string result = argument;
for (auto filter : filters) {
if (filter != nullptr) {
result = filter(result);
}
}
return result;
}
bool operator()(const std::string& a, const std::string& b)
{
std::string af = ApplyFilter(a);
std::string bf = ApplyFilter(b);
bool result;
if (descending) {
result = bf < af;
} else {
result = af < bf;
}
return result;
}
protected:
StringFilter filters[2] = { nullptr, nullptr };
bool descending;
};
bool HandleSortCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
assert(args.size() >= 2);
if (args.size() > 8) {
status.SetError("sub-command SORT only takes up to six arguments.");
return false;
}
auto sortCompare = cmStringSorter::Compare::UNINITIALIZED;
auto sortCaseSensitivity = cmStringSorter::CaseSensitivity::UNINITIALIZED;
auto sortOrder = cmStringSorter::Order::UNINITIALIZED;
size_t argumentIndex = 2;
const std::string messageHint = "sub-command SORT ";
while (argumentIndex < args.size()) {
const std::string option = args[argumentIndex++];
if (option == "COMPARE") {
if (sortCompare != cmStringSorter::Compare::UNINITIALIZED) {
std::string error = cmStrCat(messageHint, "option \"", option,
"\" has been specified multiple times.");
status.SetError(error);
return false;
}
if (argumentIndex < args.size()) {
const std::string argument = args[argumentIndex++];
if (argument == "STRING") {
sortCompare = cmStringSorter::Compare::STRING;
} else if (argument == "FILE_BASENAME") {
sortCompare = cmStringSorter::Compare::FILE_BASENAME;
} else {
std::string error =
cmStrCat(messageHint, "value \"", argument, "\" for option \"",
option, "\" is invalid.");
status.SetError(error);
return false;
}
} else {
status.SetError(cmStrCat(messageHint, "missing argument for option \"",
option, "\"."));
return false;
}
} else if (option == "CASE") {
if (sortCaseSensitivity !=
cmStringSorter::CaseSensitivity::UNINITIALIZED) {
status.SetError(cmStrCat(messageHint, "option \"", option,
"\" has been specified multiple times."));
return false;
}
if (argumentIndex < args.size()) {
const std::string argument = args[argumentIndex++];
if (argument == "SENSITIVE") {
sortCaseSensitivity = cmStringSorter::CaseSensitivity::SENSITIVE;
} else if (argument == "INSENSITIVE") {
sortCaseSensitivity = cmStringSorter::CaseSensitivity::INSENSITIVE;
} else {
status.SetError(cmStrCat(messageHint, "value \"", argument,
"\" for option \"", option,
"\" is invalid."));
return false;
}
} else {
status.SetError(cmStrCat(messageHint, "missing argument for option \"",
option, "\"."));
return false;
}
} else if (option == "ORDER") {
if (sortOrder != cmStringSorter::Order::UNINITIALIZED) {
status.SetError(cmStrCat(messageHint, "option \"", option,
"\" has been specified multiple times."));
return false;
}
if (argumentIndex < args.size()) {
const std::string argument = args[argumentIndex++];
if (argument == "ASCENDING") {
sortOrder = cmStringSorter::Order::ASCENDING;
} else if (argument == "DESCENDING") {
sortOrder = cmStringSorter::Order::DESCENDING;
} else {
status.SetError(cmStrCat(messageHint, "value \"", argument,
"\" for option \"", option,
"\" is invalid."));
return false;
}
} else {
status.SetError(cmStrCat(messageHint, "missing argument for option \"",
option, "\"."));
return false;
}
} else {
status.SetError(
cmStrCat(messageHint, "option \"", option, "\" is unknown."));
return false;
}
}
// set Default Values if Option is not given
if (sortCompare == cmStringSorter::Compare::UNINITIALIZED) {
sortCompare = cmStringSorter::Compare::STRING;
}
if (sortCaseSensitivity == cmStringSorter::CaseSensitivity::UNINITIALIZED) {
sortCaseSensitivity = cmStringSorter::CaseSensitivity::SENSITIVE;
}
if (sortOrder == cmStringSorter::Order::UNINITIALIZED) {
sortOrder = cmStringSorter::Order::ASCENDING;
}
const std::string& listName = args[1];
// expand the variable
std::vector<std::string> varArgsExpanded;
if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
return true;
}
if ((sortCompare == cmStringSorter::Compare::STRING) &&
(sortCaseSensitivity == cmStringSorter::CaseSensitivity::SENSITIVE) &&
(sortOrder == cmStringSorter::Order::ASCENDING)) {
std::sort(varArgsExpanded.begin(), varArgsExpanded.end());
} else {
cmStringSorter sorter(sortCompare, sortCaseSensitivity, sortOrder);
std::sort(varArgsExpanded.begin(), varArgsExpanded.end(), sorter);
}
std::string value = cmJoin(varArgsExpanded, ";");
status.GetMakefile().AddDefinition(listName, value);
return true;
}
bool HandleSublistCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
if (args.size() != 5) {
status.SetError(cmStrCat("sub-command SUBLIST requires four arguments (",
args.size() - 1, " found)."));
return false;
}
const std::string& listName = args[1];
const std::string& variableName = args.back();
// expand the variable
std::vector<std::string> varArgsExpanded;
if (!GetList(varArgsExpanded, listName, status.GetMakefile()) ||
varArgsExpanded.empty()) {
status.GetMakefile().AddDefinition(variableName, "");
return true;
}
const int start = atoi(args[2].c_str());
const int length = atoi(args[3].c_str());
using size_type = decltype(varArgsExpanded)::size_type;
if (start < 0 || size_type(start) >= varArgsExpanded.size()) {
status.SetError(cmStrCat("begin index: ", start, " is out of range 0 - ",
varArgsExpanded.size() - 1));
return false;
}
if (length < -1) {
status.SetError(cmStrCat("length: ", length, " should be -1 or greater"));
return false;
}
const size_type end =
(length == -1 || size_type(start + length) > varArgsExpanded.size())
? varArgsExpanded.size()
: size_type(start + length);
std::vector<std::string> sublist(varArgsExpanded.begin() + start,
varArgsExpanded.begin() + end);
status.GetMakefile().AddDefinition(variableName, cmJoin(sublist, ";"));
return true;
}
bool HandleRemoveAtCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
if (args.size() < 3) {
status.SetError("sub-command REMOVE_AT requires at least "
"two arguments.");
return false;
}
const std::string& listName = args[1];
// expand the variable
std::vector<std::string> varArgsExpanded;
if (!GetList(varArgsExpanded, listName, status.GetMakefile()) ||
varArgsExpanded.empty()) {
std::ostringstream str;
str << "index: ";
for (size_t i = 1; i < args.size(); ++i) {
str << args[i];
if (i != args.size() - 1) {
str << ", ";
}
}
str << " out of range (0, 0)";
status.SetError(str.str());
return false;
}
size_t cc;
std::vector<size_t> removed;
size_t nitem = varArgsExpanded.size();
for (cc = 2; cc < args.size(); ++cc) {
int item = atoi(args[cc].c_str());
if (item < 0) {
item = static_cast<int>(nitem) + item;
}
if (item < 0 || nitem <= static_cast<size_t>(item)) {
status.SetError(cmStrCat("index: ", item, " out of range (-", nitem,
", ", nitem - 1, ")"));
return false;
}
removed.push_back(static_cast<size_t>(item));
}
std::sort(removed.begin(), removed.end());
auto remEnd = std::unique(removed.begin(), removed.end());
auto remBegin = removed.begin();
auto argsEnd =
cmRemoveIndices(varArgsExpanded, cmMakeRange(remBegin, remEnd));
auto argsBegin = varArgsExpanded.cbegin();
std::string value = cmJoin(cmMakeRange(argsBegin, argsEnd), ";");
status.GetMakefile().AddDefinition(listName, value);
return true;
}
bool HandleFilterCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
if (args.size() < 2) {
status.SetError("sub-command FILTER requires a list to be specified.");
return false;
}
if (args.size() < 3) {
status.SetError(
"sub-command FILTER requires an operator to be specified.");
return false;
}
if (args.size() < 4) {
status.SetError("sub-command FILTER requires a mode to be specified.");
return false;
}
const std::string& op = args[2];
bool includeMatches;
if (op == "INCLUDE") {
includeMatches = true;
} else if (op == "EXCLUDE") {
includeMatches = false;
} else {
status.SetError("sub-command FILTER does not recognize operator " + op);
return false;
}
const std::string& listName = args[1];
// expand the variable
std::vector<std::string> varArgsExpanded;
if (!GetList(varArgsExpanded, listName, status.GetMakefile())) {
return true;
}
const std::string& mode = args[3];
if (mode == "REGEX") {
if (args.size() != 5) {
status.SetError("sub-command FILTER, mode REGEX "
"requires five arguments.");
return false;
}
return FilterRegex(args, includeMatches, listName, varArgsExpanded,
status);
}
status.SetError("sub-command FILTER does not recognize mode " + mode);
return false;
}
class MatchesRegex
{
public:
MatchesRegex(cmsys::RegularExpression& in_regex, bool in_includeMatches)
: regex(in_regex)
, includeMatches(in_includeMatches)
{
}
bool operator()(const std::string& target)
{
return regex.find(target) ^ includeMatches;
}
private:
cmsys::RegularExpression& regex;
const bool includeMatches;
};
bool FilterRegex(std::vector<std::string> const& args, bool includeMatches,
std::string const& listName,
std::vector<std::string>& varArgsExpanded,
cmExecutionStatus& status)
{
const std::string& pattern = args[4];
cmsys::RegularExpression regex(pattern);
if (!regex.is_valid()) {
std::string error =
cmStrCat("sub-command FILTER, mode REGEX failed to compile regex \"",
pattern, "\".");
status.SetError(error);
return false;
}
auto argsBegin = varArgsExpanded.begin();
auto argsEnd = varArgsExpanded.end();
auto newArgsEnd =
std::remove_if(argsBegin, argsEnd, MatchesRegex(regex, includeMatches));
std::string value = cmJoin(cmMakeRange(argsBegin, newArgsEnd), ";");
status.GetMakefile().AddDefinition(listName, value);
return true;
}
} // namespace
bool cmListCommand(std::vector<std::string> const& args,
cmExecutionStatus& status)
{
if (args.size() < 2) {
status.SetError("must be called with at least two arguments.");
return false;
}
static cmSubcommandTable const subcommand{
{ "LENGTH"_s, HandleLengthCommand },
{ "GET"_s, HandleGetCommand },
{ "APPEND"_s, HandleAppendCommand },
{ "PREPEND"_s, HandlePrependCommand },
{ "POP_BACK"_s, HandlePopBackCommand },
{ "POP_FRONT"_s, HandlePopFrontCommand },
{ "FIND"_s, HandleFindCommand },
{ "INSERT"_s, HandleInsertCommand },
{ "JOIN"_s, HandleJoinCommand },
{ "REMOVE_AT"_s, HandleRemoveAtCommand },
{ "REMOVE_ITEM"_s, HandleRemoveItemCommand },
{ "REMOVE_DUPLICATES"_s, HandleRemoveDuplicatesCommand },
{ "TRANSFORM"_s, HandleTransformCommand },
{ "SORT"_s, HandleSortCommand },
{ "SUBLIST"_s, HandleSublistCommand },
{ "REVERSE"_s, HandleReverseCommand },
{ "FILTER"_s, HandleFilterCommand },
};
return subcommand(args[0], args, status);
}
|
//#include "UIButton.h"
//#include "Platy.Game.Core/Postmaster/Message.h"
//#include "Platy.Game.Core/Containers/AssetContainer.h"
//#include "Platy.Game.Core/Graphics/Colors.h"
//
//
//template <class C>
//UIButton<C>::UIButton()
//{
// Subscribe(Message::EMessageType::MOUSE_LEFT_PRESSED);
// Subscribe(Message::EMessageType::MOUSE_MOVED);
//}
//
//template <class C>
//UIButton<C>::UIButton(const char* aText, void (C::* aFunc)(), C* aClassPtr, const sf::Vector2f aPosition,
// const bool isActive) :
// myIsActive(isActive),
// myFunction(aFunc),
// myClassPtr(aClassPtr),
// myText(aText, *AssetContainer::GetFont("firstorder")),
// myRect(sf::Vector2f(DEFAULT_BUTTON_WIDTH, DEFAULT_BUTTON_HEIGHT))
//{
// Subscribe(Message::EMessageType::MOUSE_LEFT_PRESSED);
// Subscribe(Message::EMessageType::MOUSE_MOVED);
//
// myText.setPosition(aPosition.x + TEXT_OFFSET_X, aPosition.y + TEXT_OFFSET_Y);
// myText.setFillColor(C_BLACK);
//
// myRect.setPosition(aPosition);
// myRect.setOutlineColor(C_RÅSA);
// myRect.setFillColor(C_RÅSA);
// myRect.setOutlineThickness(OUTLINE_THICKNESS);
//}
//
//template <class C>
//UIButton<C>::~UIButton()
//{
// myFunction = NULL;
// myClassPtr = NULL;
// RemoveAllSubscriptions();
//}
//
//template <class C>
//void UIButton<C>::ReceiveMessage(const Message& aMessage, const Message::EMessageType& aMessageType)
//{
// if (myIsActive)
// {
// switch (aMessageType)
// {
// case Message::EMessageType::MOUSE_LEFT_PRESSED:
// if ((sf::IntRect(myRect.getPosition().x, myRect.getPosition().y, myRect.getSize().x, myRect.getSize().y)).
// intersects(sf::IntRect(aMessage.GetPosition(), sf::Vector2i(1, 1))))
// {
// (myClassPtr->*myFunction)();
// }
// break;
//
// case Message::EMessageType::MOUSE_MOVED:
// if ((sf::IntRect(myRect.getPosition().x, myRect.getPosition().y, myRect.getSize().x, myRect.getSize().y)).
// intersects(sf::IntRect(aMessage.GetPosition(), sf::Vector2i(1, 1))))
// {
// myRect.setOutlineColor(C_AMETIST);
// }
// else
// {
// myRect.setOutlineColor(C_RÅSA);
// }
//
// default:
// break;
// }
// }
//}
//
//template <class C>
//void UIButton<C>::SetActive(const bool aValue)
//{
// myIsActive = aValue;
//}
//
//template <class C>
//void UIButton<C>::draw(sf::RenderTarget& target, sf::RenderStates states) const
//{
// states.texture = nullptr;
// target.draw(myRect, states);
// target.draw(myText, states);
//}
|
#include "Configure.h"
#include "Logger.h"
#include "BaseClientHandler.h"
#include "Room.h"
#include "HallManager.h"
#include "GameApp.h"
#include "CoinConf.h"
#include "AllocSvrConnect.h"
#include "game_version.h"
typedef SocketServer<BaseClientHandler> GameAcceptor;
class GameServerApp : public GameApp
{
public:
virtual bool InitRoom()
{
Room::getInstance()->init();
return true;
}
virtual CDL_TCP_Server *NewTCPServer()
{
return NewGameAcceptor<GameAcceptor>();
}
};
int main(int argc, char* argv[])
{
GameServerApp app;
app.Register(Configure::getInstance(), CoinConf::getInstance());
if (!app.InitConfig(argc, argv))
{
return -1;
}
LOGGER(E_LOG_INFO) << "base git version:" << BASE_SHORT_VERSION;
LOGGER(E_LOG_INFO) << "comm git version:" << COMM_SHORT_VERSION;
LOGGER(E_LOG_INFO) << "game git version:" << GAME_SHORT_VERSION;
LOGGER(E_LOG_INFO) << "game build time:" << GAME_BUILD_TIME;
AllocSvrConnect::getInstance()->connect(Configure::getInstance()->alloc_ip, Configure::getInstance()->alloc_port);
return app.RunLoop();
}
|
//===========================================================================
//! @file shader_manager.cpp
//! @brief シェーダー管理
//===========================================================================
namespace {
std::unordered_map<std::string, std::unique_ptr<ShaderVs>> shaderVs_;
std::unordered_map<std::string, std::unique_ptr<gpu::ShaderPs>> shaderPs_;
std::unordered_map<std::string, std::unique_ptr<gpu::ShaderGs>> shaderGs_;
std::unordered_map<std::string, std::unique_ptr<gpu::ShaderHs>> shaderHs_;
std::unordered_map<std::string, std::unique_ptr<gpu::ShaderDs>> shaderDs_;
} // namespace
//---------------------------------------------------------------------------
//! デストラクタ
//---------------------------------------------------------------------------
ShaderManager::~ShaderManager()
{
shaderHs_.clear();
shaderDs_.clear();
shaderPs_.clear();
shaderVs_.clear();
}
//---------------------------------------------------------------------------
//! 入力レイアウト取得
//---------------------------------------------------------------------------
gpu::InputLayout* const ShaderManager::getInputLayout(const std::string& fileName)
{
// ない場合作成
if(!shaderVs_.count(fileName)) {
getShaderVs(fileName);
}
return shaderVs_[fileName]->inputLayout_.get();
}
//---------------------------------------------------------------------------
//! 頂点シェーダーを取得
//---------------------------------------------------------------------------
gpu::ShaderVs* const ShaderManager::getShaderVs(const std::string& fileName)
{
// ない場合作成
if(!shaderVs_.count(fileName)) {
// 頂点シェーダー作成
gpu::ShaderVs* shaderVs = gpu::ShaderVs::create(fileName.c_str());
if(!shaderVs) {
return nullptr;
}
// 入力レイアウト作成
auto inputLayout = createInputLayout(fileName);
if(!inputLayout) {
GM_ASSERT_MESSAGE(false, "入力レイアウトを生成できませんでした。");
GM_SAFE_DELETE(shaderVs);
return nullptr;
}
if(!inputLayout->create(*shaderVs))
return nullptr;
//
// // マップに追加
ShaderVs* shader = new ShaderVs();
if(!shader) {
GM_ASSERT_MESSAGE(false, "頂点シェーダーを生成できませんでした。");
GM_SAFE_DELETE(shaderVs);
GM_SAFE_DELETE(inputLayout);
return nullptr;
}
shader->inputLayout_.reset(inputLayout);
shader->shaderVs_.reset(shaderVs);
shaderVs_.insert(std::make_pair(fileName, shader));
shader = nullptr;
}
//}
return shaderVs_[fileName]->shaderVs_.get();
}
//---------------------------------------------------------------------------
//! ピクセルシェーダーを取得
//---------------------------------------------------------------------------
gpu::ShaderPs* const ShaderManager::getShaderPs(const std::string& fileName)
{
// ない場合作成
if(!shaderPs_.count(fileName)) {
gpu::ShaderPs* shaderPs = gpu::ShaderPs::create(fileName.c_str());
if(!shaderPs) {
GM_ASSERT_MESSAGE(false, "ピクセルシェーダーを生成できませんでした。");
return nullptr;
}
shaderPs_.insert(std::make_pair(fileName, shaderPs));
}
return shaderPs_[fileName].get();
}
//---------------------------------------------------------------------------
//! ジオメトリシェーダーを取得
//---------------------------------------------------------------------------
gpu::ShaderGs* const ShaderManager::getShaderGs(const std::string& fileName)
{
// ない場合作成B
if(!shaderGs_.count(fileName)) {
gpu::ShaderGs* shaderGs = gpu::ShaderGs::create(fileName.c_str());
if(!shaderGs) {
GM_ASSERT_MESSAGE(false, "ジオメトリシェーダー生成できませんでした。");
return nullptr;
}
shaderGs_.insert(std::make_pair(fileName, shaderGs));
}
return shaderGs_[fileName].get();
}
//---------------------------------------------------------------------------
//! ハルシェーダーを取得
//---------------------------------------------------------------------------
gpu::ShaderHs* const ShaderManager::getShaderHs(const std::string& fileName)
{
// ない場合作成
if(!shaderHs_.count(fileName)) {
gpu::ShaderHs* shaderHs = gpu::ShaderHs::create(fileName.c_str());
if(!shaderHs) {
GM_ASSERT_MESSAGE(false, "ハルシェーダー生成できませんでした。");
return nullptr;
}
shaderHs_.insert(std::make_pair(fileName, shaderHs));
}
return shaderHs_[fileName].get();
}
//---------------------------------------------------------------------------
//! ドメインシェーダーを取得
//---------------------------------------------------------------------------
gpu::ShaderDs* const ShaderManager::getShaderDs(const std::string& fileName)
{
// ない場合作成
if(!shaderDs_.count(fileName)) {
gpu::ShaderDs* shaderDs = gpu::ShaderDs::create(fileName.c_str());
if(!shaderDs) {
GM_ASSERT_MESSAGE(false, "ドメインシェーダー生成できませんでした。");
return nullptr;
}
shaderDs_.insert(std::make_pair(fileName, shaderDs));
}
return shaderDs_[fileName].get();
}
//---------------------------------------------------------------------------
//!
//---------------------------------------------------------------------------
gpu::InputLayout* ShaderManager::createInputLayout(const std::string& fileName)
{
gpu::InputLayout* inputLayout = nullptr;
// clang-format off
if(fileName == "vsAnimationModel") {
D3D11_INPUT_ELEMENT_DESC layout[]{
{ "POSITION" , 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(VertexModel, position_ ), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL" , 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(VertexModel, normal_ ), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR" , 0, DXGI_FORMAT_R8G8B8A8_UNORM , 0, offsetof(VertexModel, color_ ), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD" , 0, DXGI_FORMAT_R32G32_FLOAT , 0, offsetof(VertexModel, uv_ ), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "BONE_INDEX" , 0, DXGI_FORMAT_R32_SINT , 0, offsetof(VertexModel, boneIndex_ ), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "BONE_INFL_INDEX" , 0, DXGI_FORMAT_R32_SINT , 0, offsetof(VertexModel, boneInflIndex_), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "BONE_WEIGHT", 0, DXGI_FORMAT_R32_FLOAT , 0, offsetof(VertexModel, boneWeight_), D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
inputLayout = new gpu::InputLayout(layout);
}
else if(fileName == "vsTexture2D") {
D3D11_INPUT_ELEMENT_DESC layout[]{
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, offsetof(VertexTexture2D, position_), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, offsetof(VertexTexture2D, uv_), D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
inputLayout = new gpu::InputLayout(layout);
}
else {
D3D11_INPUT_ELEMENT_DESC layout[]{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex, position_), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL" , 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex, normal_) , D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TANGENT" , 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex, tangent_) , D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "BINORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(Vertex, binormal_), D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR" , 0, DXGI_FORMAT_R8G8B8A8_UNORM , 0, offsetof(Vertex, color_) , D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT , 0, offsetof(Vertex, uv_) , D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
inputLayout = new gpu::InputLayout(layout);
}
// clang-format on
return inputLayout;
}
|
#include "Light.hpp"
Light::Light(GLenum lightNumber, Color ambient, Color diffuse, Color specular, Vector3 position)
{
this->lightNumber = lightNumber;
this->ambient[0] = ambient.getRed() / 255.0;
this->ambient[1] = ambient.getGreen() / 255.0;
this->ambient[2] = ambient.getBlue() / 255.0;
this->ambient[3] = ambient.getAlpha() / 255.0;
this->diffuse[0] = diffuse.getRed() / 255.0;
this->diffuse[1] = diffuse.getGreen() / 255.0;
this->diffuse[2] = diffuse.getBlue() / 255.0;
this->diffuse[3] = diffuse.getAlpha() / 255.0;
this->specular[0] = specular.getRed() / 255.0;
this->specular[1] = specular.getGreen() / 255.0;
this->specular[2] = specular.getBlue() / 255.0;
this->specular[3] = specular.getAlpha() / 255.0;
this->position = position;
positionv[0] = position.x;
positionv[1] = position.y;
positionv[2] = position.z;
positionv[3] = 1;
}
Light::Light(GLenum lightNumber, Color lightColor, Vector3 position)
{
this->lightNumber = lightNumber;
this->ambient[0] = lightColor.getRed() / 255.0;
this->ambient[1] = lightColor.getGreen() / 255.0;
this->ambient[2] = lightColor.getBlue() / 255.0;
this->ambient[3] = lightColor.getAlpha() / 255.0;
this->diffuse[0] = lightColor.getRed() / 255.0 * 0.2;
this->diffuse[1] = lightColor.getGreen() / 255.0 * 0.2;
this->diffuse[2] = lightColor.getBlue() / 255.0 * 0.2;
this->diffuse[3] = lightColor.getAlpha() / 255.0 * 0.2;
this->specular[0] = lightColor.getRed() / 255.0 * 0.2;
this->specular[1] = lightColor.getGreen() / 255.0 * 0.2;
this->specular[2] = lightColor.getBlue() / 255.0 * 0.2;
this->specular[3] = lightColor.getAlpha() / 255.0 * 0.2;
this->position = position;
positionv[0] = position.x;
positionv[1] = position.y;
positionv[2] = position.z;
positionv[3] = 1;
}
Light::Light(GLenum lightNumber, float ambient[4], float diffuse[4], float specular[4],
Vector3 position)
{
this->lightNumber = lightNumber;
this->ambient[0] = ambient[0];
this->ambient[1] = ambient[1];
this->ambient[2] = ambient[2];
this->ambient[3] = ambient[3];
this->diffuse[0] = diffuse[0];
this->diffuse[1] = diffuse[1];
this->diffuse[2] = diffuse[2];
this->diffuse[3] = diffuse[3];
this->specular[0] = specular[0];
this->specular[1] = specular[1];
this->specular[2] = specular[2];
this->specular[3] = specular[3];
this->position = position;
positionv[0] = position.x;
positionv[1] = position.y;
positionv[2] = position.z;
positionv[3] = 1;
}
void Light::applyLight()
{
glLightfv(lightNumber, GL_AMBIENT, ambient);
glLightfv(lightNumber, GL_DIFFUSE, diffuse);
glLightfv(lightNumber, GL_SPECULAR, specular);
glLightfv(lightNumber, GL_POSITION, positionv);
glEnable(GL_LIGHTING);
glEnable(lightNumber);
}
void Light::setPosition(Vector3 position)
{
this->position = position;
positionv[0] = position.x;
positionv[1] = position.y;
positionv[2] = position.z;
}
Vector3 Light::getPosition() { return position; }
float *Light::getPositionv() { return positionv; }
|
/* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2012-2013.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
#include <boost/foreach.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <fwGui/Cursor.hpp>
#include <fwGui/dialog/MessageDialog.hpp>
#include <fwGui/dialog/SelectorDialog.hpp>
#include <fwGui/dialog/LocationDialog.hpp>
#include <fwGui/dialog/ProgressDialog.hpp>
#include <fwTools/fwID.hpp>
#include <fwTools/System.hpp>
#include <fwData/location/Folder.hpp>
#include <fwData/PatientDB.hpp>
#include <fwData/Vector.hpp>
#include <fwData/String.hpp>
#include <fwData/Integer.hpp>
#include <fwData/location/MultiFiles.hpp>
#include "vtkGdcmIO/DicomPatientDBReader.hpp"
// Defined QT_NO_KEYWORDS because of conflict with boost::signals namespace.
#ifndef QT_NO_KEYWORDS
#define QT_NO_KEYWORDS
#define QT_NO_KEYWORDS_FWDEF
#endif
#include <QVBoxLayout>
#include <QGridLayout>
#include <QLabel>
#include <QTreeWidgetItem>
#ifdef QT_NO_KEYWORDS_FWDEF
#undef QT_NO_KEYWORDS
#undef QT_NO_KEYWORDS_FWDEF
#endif
#include <fwServices/Base.hpp>
#include <fwComEd/PatientDBMsg.hpp>
#include <fwComEd/Dictionary.hpp>
#include <fwComEd/fieldHelper/MedicalImageHelpers.hpp>
#include "ioGdcmQt/ui/DicomdirEditor.hpp"
#include "gdcmIO/Dicomdir.hpp"
namespace ioGdcm
{
namespace ui
{
DicomdirEditor::DicomdirEditor(QWidget* parent, ::boost::filesystem::path& dicomdirPath) throw() : QDialog( parent)
, m_dicomdirPath(dicomdirPath), m_bServiceIsConfigured(false)
{
this->createContent();
}
//------------------------------------------------------------------------------
DicomdirEditor::~DicomdirEditor() throw()
{
SLM_TRACE_FUNC();
QObject::disconnect(m_open, SIGNAL(clicked()), this, SLOT(accept()));
QObject::disconnect(m_DicomdirStructure, SIGNAL(clicked()), this, SLOT(onSelection()));
}
//------------------------------------------------------------------------------
void DicomdirEditor::createContent() throw(::fwTools::Failed)
{
SLM_TRACE_FUNC();
if(!m_dicomdirPath.empty())
{
// Get the data
::gdcmIO::Dicomdir dicomdir(m_dicomdirPath);
setWindowTitle("DICOM Tree Viewer");
setMinimumSize(600, 400);
QVBoxLayout* layout = new QVBoxLayout(this);
setLayout(layout);
m_DicomdirStructure = new QTreeWidget(this);
m_DicomdirStructure->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_DicomdirStructure->setAlternatingRowColors(true);
m_DicomdirStructure->setColumnCount(1);
m_DicomdirStructure->setHeaderLabels(QStringList()<< tr("Dicomdir hierarchy"));
BOOST_FOREACH( ::gdcmIO::Dicomdir::PatientListType::value_type patient, dicomdir.getPatients())
{
QTreeWidgetItem *patientItem = new QTreeWidgetItem();
patientItem->setText(0, QString::fromStdString(patient.name));
patientItem->setData(0, Qt::UserRole, QString::fromStdString(patient.id));
patientItem->setSelected(false);
patientItem->setData(0, Qt::ToolTipRole, QString("PATIENT"));
m_DicomdirStructure->addTopLevelItem(patientItem);
BOOST_FOREACH( ::gdcmIO::Dicomdir::StudyListType::value_type study, dicomdir.getStudies(patient.id))
{
QTreeWidgetItem *studyItem = new QTreeWidgetItem(patientItem);
studyItem->setText(0, QString::fromStdString(study.description));
studyItem->setData(0, Qt::UserRole, QString::fromStdString(study.instanceUID));
studyItem->setData(0, Qt::ToolTipRole, QString("STUDY"));
patientItem->addChild(studyItem);
BOOST_FOREACH( ::gdcmIO::Dicomdir::SerieListType::value_type serie, dicomdir.getSeries(study.instanceUID))
{
const ::gdcmIO::Dicomdir::ImageListType& imageList = dicomdir.getImages(serie.instanceUID);
QTreeWidgetItem *serieItem = new QTreeWidgetItem(studyItem);
QString info = QString::fromStdString(serie.description) + QString(" - ( %1, %2 images)").arg(QString::fromStdString(serie.modality)).arg(imageList.size());
serieItem->setText(0, info);
serieItem->setData(0, Qt::UserRole, QString::fromStdString(serie.instanceUID));
serieItem->setData(0, Qt::ToolTipRole, QString("SERIE"));
studyItem->addChild(serieItem);
BOOST_FOREACH( ::gdcmIO::Dicomdir::ImageListType::value_type image, imageList)
{
QTreeWidgetItem *imageItem = new QTreeWidgetItem(serieItem);
imageItem->setText(0, QString::fromStdString(image.fileID));
imageItem->setData(0, Qt::UserRole, QString::fromStdString(serie.instanceUID));
::boost::filesystem::path dicomdirParentPath(m_dicomdirPath.parent_path());
dicomdirParentPath/="/";
imageItem->setData(0, Qt::ToolTipRole, QString::fromStdString(dicomdirParentPath.string() + image.fileID));
serieItem->addChild(serieItem);
}
}
}
}
m_DicomdirStructure->expandAll();
QHBoxLayout* bottomToolsLayout = new QHBoxLayout();
QPushButton* closeButton = new QPushButton(tr("Close"), this);
m_open = new QPushButton(tr("Open"), this);
m_readers = new QComboBox();
bottomToolsLayout->addItem(new QSpacerItem(10, 0, QSizePolicy::Expanding, QSizePolicy::Minimum));
bottomToolsLayout->addWidget(m_open);
bottomToolsLayout->addWidget(closeButton);
layout->addWidget(m_DicomdirStructure);
layout->addWidget(m_readers);
layout->addLayout(bottomToolsLayout);
QObject::connect(closeButton, SIGNAL(clicked()), this, SLOT(reject()));
QObject::connect(m_open, SIGNAL(clicked()), this, SLOT(accept()));
QObject::connect(m_DicomdirStructure, SIGNAL(itemSelectionChanged()), this, SLOT(onSelection() ));
}
else
{
std::stringstream ss;
ss << "Empty DICOMDIR path.";
::fwGui::dialog::MessageDialog::showMessageDialog("Warning",
ss.str(),
::fwGui::dialog::IMessageDialog::WARNING);
}
}
//------------------------------------------------------------------------------
void DicomdirEditor::onSelection()
{
SLM_TRACE_FUNC();
QTreeWidgetItem *item = m_DicomdirStructure->currentItem();
}
//------------------------------------------------------------------------------
void DicomdirEditor::setReader(const std::map < ::ioGdcm::DicomReader, std::string >& readerList)
{
SLM_TRACE_FUNC();
BOOST_FOREACH( readerListType reader, readerList )
{
m_readers->addItem(QString::fromStdString(reader.second), QVariant(reader.first));
}
}
//------------------------------------------------------------------------------
std::vector< ::boost::filesystem::path > DicomdirEditor::getDicomFiles(QTreeWidgetItem *item)
{
std::vector< ::boost::filesystem::path > filenames;
QTreeWidgetItemIterator it(item);
std::string selectedRole = item->data(0, Qt::ToolTipRole).toString().toStdString();
std::string currentRole;
if(item->childCount()!=0)
{
// A patient, a study or a serie item hhas been chosen.
++it;
while (*it) {
currentRole = (*it)->data(0, Qt::ToolTipRole).toString().toStdString();
if(currentRole != selectedRole)
{
if(currentRole != "PATIENT" && currentRole != "STUDY" && currentRole != "SERIE")
{
// For an image, role gives the path of the image.
::boost::filesystem::path path(currentRole);
filenames.push_back(path);
}
}
else
{
// We treat only the selected patient, study or serie.
break;
}
++it;
}
}
else
{
// The selected item is a file.
std::string filename;
filename = (*it)->data(0, Qt::ToolTipRole).toString().toStdString();
::boost::filesystem::path path(filename);
filenames.push_back(path);
}
return filenames;
}
//------------------------------------------------------------------------------
std::pair < ::ioGdcm::DicomReader, std::vector< ::boost::filesystem::path > > DicomdirEditor::show()
{
std::pair< ::ioGdcm::DicomReader, std::vector< ::boost::filesystem::path > > readerAndFilenames;
if(this->exec())
{
// Get the name of the reader.
int index = m_readers->currentIndex();
::ioGdcm::DicomReader reader = ::ioGdcm::toDicomReader (m_readers->itemData(index).toInt());
// Get the list of file
QTreeWidgetItem *item = m_DicomdirStructure->currentItem();
std::vector< ::boost::filesystem::path > filenames;
filenames = this->getDicomFiles(item);
readerAndFilenames = std::make_pair(reader, filenames);
}
return readerAndFilenames;
}
} //namespace ui
} //namespace ioGdcm
|
#ifndef APPLICATION_CHATITEM_H
#define APPLICATION_CHATITEM_H
#include <string>
#include "BaseObject.h"
#include "KeyWords.h"
// Chat item for view chat in chat list
class ChatItem : public BaseObject {
public:
ChatItem();
ChatItem(int id, const std::string& chatName);
~ChatItem() override = default;
// Get encode string
std::string encode() const override;
// Set string for decoding
void decode(const std::string& jsonStr) override;
public:
int chatId;
std::string chatName;
};
#endif //APPLICATION_CHATITEM_H
|
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
#include <Servo.h>
SoftwareSerial mySerial(D5,D6);
const char* ssid = "your SSID";
const char* password = "password";
const char* host = "api.thingspeak.com";
const char* privateKey = "thingspeak write API";
const String talkBackAPIKey = "talkback API";
const String talkBackID = "talkback ID";
const unsigned int getTalkBackInterval = 10 * 1000;
String talkBackCommand;
long lastConnectionTimeChannels = 0;
boolean lastConnectedChannels = false;
int failedCounterChannels = 0;
long lastConnectionTimeTalkBack = 0;
boolean lastConnectedTalkBack = false;
int failedCounterTalkBack = 0;
WiFiClient client;
int temperature,temp,vibration;
int tMSB,tLSB,vibMSB,vibLSB;
String readString;
Servo myservo;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
mySerial.begin(9600);
myservo.attach(D2);
myservo.write(0);
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
startWiFi();
}
void loop() {
readValues();
getTalkBack();
delay(1000);
if(talkBackCommand == "MOTORON") myservo.write(180);
if(talkBackCommand == "MOTOROFF") myservo.write(0);
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
// We now create a URI for the request
String url = "/update";
url += "?api_key=";
url += privateKey;
url += "&field1=";
url += temperature;
url += "&field2=";
url += vibration;
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
delay(10);
while(client.connected() && !client.available()) delay(1); //waits for data
while (client.connected() || client.available())
{
char charIn = client.read();
//Serial.print(charIn);
}
Serial.println();
Serial.println("closing connection");
client.stop();
}
void readValues()
{
if(mySerial.available()>=25){
if(mySerial.read() == 0x7E){
for (int i=1;i<20;i++) {
byte discardByte = mySerial.read();
// Serial.println(discardByte);
}
tMSB = mySerial.read();
tLSB = mySerial.read();
temp= tLSB + (tMSB * 256);
// Serial.println(moisture);
temperature=(5*temp*100)/1024;//Converting digital value to analog value
Serial.println("temperature:");
Serial.println(temperature);
vibMSB = mySerial.read();
vibLSB = mySerial.read();
vibration= vibLSB + (vibMSB * 256);
Serial.println("vibration:");
Serial.println(vibration);
delay(1000);
}
}
logic();
}
void logic()
{
if((temperature>=30)&&(vibration<=500))
{
Serial.println("servo on");
myservo.write(180);
delay(2000);
}
else
{Serial.println("servo off");
myservo.write(0);
delay(15);
}
}
void getTalkBack()
{
String tsData="";
tsData=talkBackID + "/commands/execute?api_key=" + talkBackAPIKey;
if((!client.connected() && (millis() - lastConnectionTimeTalkBack > getTalkBackInterval)))
{
if (client.connect("api.thingspeak.com", 80))
{
//client.println("GET /talkbacks/"+tsData+" HTTP/1.0");
client.println("GET /talkbacks/13346/commands/execute?api_key=TCCN1G2YIBKQLLPO");
//client.println();
Serial.println("GET /talkbacks/"+tsData+" HTTP/1.0");
lastConnectionTimeTalkBack = millis();
if (client.connected())
{
Serial.println(".........................");
Serial.println("GET TalkBack command");
Serial.println();
Serial.println("Connecting to ThingsApp...");
Serial.println();
Serial.println();
Serial.println("Server response ->");
Serial.println();
failedCounterTalkBack = 0;
talkBackCommand="";
while(client.connected() && !client.available()) delay(10); //waits for data
while (client.connected() || client.available())
{
char charIn = client.read();
Serial.print(charIn);
talkBackCommand += charIn;
}
//talkBackCommand=talkBackCommand.substring(talkBackCommand.indexOf("open")+5);
//Serial.println();
//Serial.println();
//Serial.println("...disconnected");
Serial.println();
Serial.println("-----------------------");
Serial.print("Command -> ");
Serial.println(talkBackCommand);
Serial.println("-----------------------");
Serial.println();
}
else
{
failedCounterTalkBack++;
Serial.println("Connection to ThingSpeak failed ("+String(failedCounterTalkBack, DEC)+")");
Serial.println();
lastConnectionTimeChannels = millis();
}
}
else
{
failedCounterTalkBack++;
Serial.println("Connection to ThingSpeak Failed ("+String(failedCounterTalkBack, DEC)+")");
Serial.println();
lastConnectionTimeTalkBack = millis();
}
}
if (failedCounterTalkBack > 3 ) {startWiFi();}
client.stop();
Serial.flush();
}
void startWiFi()
{
client.stop();
Serial.println();
Serial.println("Connecting to network...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
delay(1000);
}
|
#include "conv_3x3.h"
#include "hw_classes.h"
struct diff_d_cache {
// Capacity: 1
fifo<hw_uint<32> , 1> f;
inline hw_uint<32> peek(const int offset) {
return f.peek(0 - offset);
}
inline hw_uint<32> peek_0() {
return f.peek(0);
}
inline void push(const hw_uint<32> value) {
#ifdef __VIVADO_SYNTH__
#pragma HLS dependence array inter false
#endif //__VIVADO_SYNTH__
return f.push(value);
}
};
inline void diff_d_write(hw_uint<32> & diff_d, diff_d_cache& diff_d_delay) {
diff_d_delay.push(diff_d);
}
inline hw_uint<32> denoise2d_rd0_select(diff_d_cache& diff_d_delay
, int d0, int d1) {
hw_uint<32> value_diff_d = diff_d_delay.peek_0();
return value_diff_d;
}
// # of bundles = 2
// denoise2d_comp_read
// denoise2d_rd0
inline hw_uint<32> diff_d_denoise2d_comp_read_bundle_read(diff_d_cache& diff_d_delay, int d0, int d1) {
hw_uint<32> result;
hw_uint<32> denoise2d_rd0_res = denoise2d_rd0_select(diff_d_delay, d0, d1);
set_at<0, 32>(result, denoise2d_rd0_res);
return result;
}
// diff_d_comp_write
// diff_d
inline void diff_d_diff_d_comp_write_bundle_write(hw_uint<32> & diff_d_comp_write, diff_d_cache& diff_d_delay) {
diff_d_write(diff_d_comp_write, diff_d_delay);
}
#include "hw_classes.h"
struct diff_qwe_cache {
// Capacity: 2
fifo<hw_uint<32> , 2> f;
inline hw_uint<32> peek(const int offset) {
return f.peek(1 - offset);
}
inline hw_uint<32> peek_0() {
return f.peek(0);
}
inline hw_uint<32> peek_1() {
return f.peek(1);
}
inline void push(const hw_uint<32> value) {
#ifdef __VIVADO_SYNTH__
#pragma HLS dependence array inter false
#endif //__VIVADO_SYNTH__
return f.push(value);
}
};
inline void diff_qwe_write(hw_uint<32> & diff_qwe, diff_qwe_cache& diff_qwe_delay) {
diff_qwe_delay.push(diff_qwe);
}
inline hw_uint<32> denoise2d_rd0_select(diff_qwe_cache& diff_qwe_delay
, int d0, int d1) {
hw_uint<32> value_diff_qwe = diff_qwe_delay.peek((d0 >= 0 && 28 - d0 >= 0 && d1 >= 0 && 29 - d1 >= 0) ? (1) : 0);
return value_diff_qwe;
}
// # of bundles = 2
// denoise2d_comp_read
// denoise2d_rd0
inline hw_uint<32> diff_qwe_denoise2d_comp_read_bundle_read(diff_qwe_cache& diff_qwe_delay, int d0, int d1) {
hw_uint<32> result;
hw_uint<32> denoise2d_rd0_res = denoise2d_rd0_select(diff_qwe_delay, d0, d1);
set_at<0, 32>(result, denoise2d_rd0_res);
return result;
}
// diff_qwe_comp_write
// diff_qwe
inline void diff_qwe_diff_qwe_comp_write_bundle_write(hw_uint<32> & diff_qwe_comp_write, diff_qwe_cache& diff_qwe_delay) {
diff_qwe_write(diff_qwe_comp_write, diff_qwe_delay);
}
#include "hw_classes.h"
struct u_cache {
// Capacity: 3
// Parition [0, 1) capacity = 1
fifo<hw_uint<32> , 1> f0;
// Parition [1, 2) capacity = 1
fifo<hw_uint<32> , 1> f2;
// Parition [2, 2] capacity = 1
fifo<hw_uint<32> , 1> f4;
inline hw_uint<32> peek_0() {
return f0.back();
}
inline hw_uint<32> peek_1() {
return f2.back();
}
inline hw_uint<32> peek_2() {
return f4.back();
}
inline hw_uint<32> peek(const int offset) {
if (offset == 0) {
return f0.back();
}
if (offset == 1) {
return f2.back();
}
if (offset == 2) {
return f4.back();
}
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offset in u: " << offset << endl;
#endif // __VIVADO_SYNTH__
assert(false);
return 0;
}
inline void push(const hw_uint<32> value) {
#ifdef __VIVADO_SYNTH__
#pragma HLS dependence array inter false
#endif //__VIVADO_SYNTH__
f4.push(f2.back());
f2.push(f0.back());
f0.push(value);
}
};
inline void u_write(hw_uint<32> & u, u_cache& u_delay) {
u_delay.push(u);
}
inline hw_uint<32> diff_d_rd0_select(u_cache& u_delay
, int d0, int d1) {
hw_uint<32> value_u = u_delay.peek_2();
return value_u;
}
inline hw_uint<32> diff_d_rd1_select(u_cache& u_delay
, int d0, int d1) {
hw_uint<32> value_u = u_delay.peek_0();
return value_u;
}
inline hw_uint<32> diff_qwe_rd0_select(u_cache& u_delay
, int d0, int d1) {
hw_uint<32> value_u = u_delay.peek_1();
return value_u;
}
inline hw_uint<32> diff_qwe_rd1_select(u_cache& u_delay
, int d0, int d1) {
hw_uint<32> value_u = u_delay.peek_0();
return value_u;
}
// # of bundles = 3
// diff_d_comp_read
// diff_d_rd0
// diff_d_rd1
inline hw_uint<64> u_diff_d_comp_read_bundle_read(u_cache& u_delay, int d0, int d1) {
hw_uint<64> result;
hw_uint<32> diff_d_rd0_res = diff_d_rd0_select(u_delay, d0, d1);
set_at<0, 64>(result, diff_d_rd0_res);
hw_uint<32> diff_d_rd1_res = diff_d_rd1_select(u_delay, d0, d1);
set_at<32, 64>(result, diff_d_rd1_res);
return result;
}
// diff_qwe_comp_read
// diff_qwe_rd0
// diff_qwe_rd1
inline hw_uint<64> u_diff_qwe_comp_read_bundle_read(u_cache& u_delay, int d0, int d1) {
hw_uint<64> result;
hw_uint<32> diff_qwe_rd0_res = diff_qwe_rd0_select(u_delay, d0, d1);
set_at<0, 64>(result, diff_qwe_rd0_res);
hw_uint<32> diff_qwe_rd1_res = diff_qwe_rd1_select(u_delay, d0, d1);
set_at<32, 64>(result, diff_qwe_rd1_res);
return result;
}
// u_comp_write
// u
inline void u_u_comp_write_bundle_write(hw_uint<32> & u_comp_write, u_cache& u_delay) {
u_write(u_comp_write, u_delay);
}
// Operation logic
inline void u_comp(HWStream<hw_uint<32> >& u_off_chip, u_cache& u, int d0, int d1) {
// Consume: u_off_chip
auto u_off_chip_0_c__0_value = u_off_chip.read();
auto compute_result = id(u_off_chip_0_c__0_value);
// Produce: u
// Buffer: u, Op: u_comp
// Possible ports...
// u
u_u_comp_write_bundle_write(compute_result, u /* output src_delay */);
}
inline void diff_qwe_comp(u_cache& u, diff_qwe_cache& diff_qwe, int d0, int d1) {
// Consume: u
auto u_0_c__0_value = u_diff_qwe_comp_read_bundle_read(u/* source_delay */, d0, d1);
auto compute_result = diff_b(u_0_c__0_value);
// Produce: diff_qwe
// Buffer: diff_qwe, Op: diff_qwe_comp
// Possible ports...
// diff_qwe
diff_qwe_diff_qwe_comp_write_bundle_write(compute_result, diff_qwe /* output src_delay */);
}
inline void diff_d_comp(u_cache& u, diff_d_cache& diff_d, int d0, int d1) {
// Consume: u
auto u_0_c__0_value = u_diff_d_comp_read_bundle_read(u/* source_delay */, d0, d1);
auto compute_result = diff_b(u_0_c__0_value);
// Produce: diff_d
// Buffer: diff_d, Op: diff_d_comp
// Possible ports...
// diff_d
diff_d_diff_d_comp_write_bundle_write(compute_result, diff_d /* output src_delay */);
}
inline void denoise2d_comp(diff_qwe_cache& diff_qwe, diff_d_cache& diff_d, HWStream<hw_uint<32> >& denoise2d, int d0, int d1) {
// Consume: diff_d
auto diff_d_0_c__0_value = diff_d_denoise2d_comp_read_bundle_read(diff_d/* source_delay */, d0, d1);
// Consume: diff_qwe
auto diff_qwe_0_c__0_value = diff_qwe_denoise2d_comp_read_bundle_read(diff_qwe/* source_delay */, d0, d1);
auto compute_result = diff(diff_d_0_c__0_value, diff_qwe_0_c__0_value);
// Produce: denoise2d
denoise2d.write(compute_result);
}
// Driver function
void denoise2d(HWStream<hw_uint<32> >& u_off_chip, HWStream<hw_uint<32> >& denoise2d) {
diff_d_cache diff_d;
diff_qwe_cache diff_qwe;
u_cache u;
for (int c0 = 0; c0 <= 29; c0 += 1)
for (int c1 = 0; c1 <= 31; c1 += 1) {
u_comp(u_off_chip, u, c1, c0);
if (c1 >= 1 && c1 <= 30)
diff_qwe_comp(u, diff_qwe, c1 - 1, c0);
if (c1 >= 2) {
diff_d_comp(u, diff_d, c1 - 2, c0);
denoise2d_comp(diff_qwe, diff_d, denoise2d, c1 - 2, c0);
}
}
}
|
#include "Ak_Transform.h"
Ak_CTransform::Ak_CTransform()
: m_posX(0.0f)
, m_posY(0.0f)
, m_scaleX(1.0f)
, m_scaleY(1.0f)
, m_rotation(0.0f)
, m_isModifyTransform(false)
{
}
Ak_CTransform::~Ak_CTransform()
{
}
void Ak_CTransform::UpdateTransform()
{
if (!m_isModifyTransform)
return;
OnModifyTransform();
m_isModifyTransform = false;
}
void Ak_CTransform::SetPositionX(float posX)
{
m_posX = posX;
m_isModifyTransform = true;
}
void Ak_CTransform::SetPositionY(float posY)
{
m_posY = posY;
m_isModifyTransform = true;
}
void Ak_CTransform::SetScaleX(float scaleX)
{
m_scaleX = scaleX;
m_isModifyTransform = true;
}
void Ak_CTransform::SetScaleY(float scaleY)
{
m_scaleY = scaleY;
m_isModifyTransform = true;
}
void Ak_CTransform::SetRotation(float rotation)
{
m_rotation = rotation;
m_isModifyTransform = true;
}
float Ak_CTransform::GetPositionX()
{
return m_posX;
}
float Ak_CTransform::GetPositionY()
{
return m_posY;
}
float Ak_CTransform::GetScaleX()
{
return m_scaleX;
}
float Ak_CTransform::GetScaleY()
{
return m_scaleY;
}
float Ak_CTransform::GetRotation()
{
return m_rotation;
}
void Ak_CTransform::OnModifyTransform()
{
}
|
//算法:DP/二分查找
//思路:先按一边城市的序号升序排序
//然后找另外一边的最长上升子序列
/*
原因:
按一边城市的序号升序排序后,
理想情况便是另一边也是上升的序列
这样可以保证所有的路径都不相交
但理想很丰满,现实很骨感,
所以要找到最多的不相交的路径
即找到另一边最长上升子序列的长度
*/
#include<cstdio>
#include<algorithm>
using namespace std;
struct baka9
{
int c1,c2;
}a[200010];
int n;
int st1[200010]={-10000000};//二分查找
int marx;
bool cmp(baka9 aa,baka9 bb)//排序
{
return aa.c1<bb.c1;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d%d",&a[i].c1,&a[i].c2);
sort(a+1,a+n+1,cmp);
for(int i=1;i<=n;i++)
{
if(a[i].c2>st1[marx])
st1[++marx]=a[i].c2;//比顶头元素大,直接加入
else//二分查找第一个比它大的,并放在前面
{
int l=1,r=marx,mid;
while(l<=r)
{
mid=(l+r)/2;
if(a[i].c2>st1[mid])
l=mid+1;
else
r=mid-1;
}
st1[l]=a[i].c2;
}
}
printf("%d",marx);
}
/*
50分TLE DP代码
#include<cstdio>
#include<algorithm>
using namespace std;
struct baka9
{
int c1,c2;
}a[200010];
int n;
int f[200010];
int ans;
bool cmp(baka9 aa,baka9 bb)
{
return aa.c1<bb.c1;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d%d",&a[i].c1,&a[i].c2);
sort(a+1,a+n+1,cmp);
for(int i=1;i<=n;i++)
{
f[i]=1;
for(int j=1;j<i;j++)
if(a[j].c2<=a[i].c2)
f[i]=max(f[j],f[j]+1);
if(f[i]>ans) ans=f[i];
}
printf("%d",ans);
}
*/
|
#ifndef __CURSES_TERMINAL_HPP_INCLUDED__
#define __CURSES_TERMINAL_HPP_INCLUDED__
#include "config.hpp"
#ifdef CURSES_WIN
# include "win/WinTerm.hpp"
#endif // include windows implementation
#endif // __CURSES_TERMINAL_HPP_INCLUDED__
|
#include "OpenGL/OpenGLFrameBuffer.h"
#include <glad/glad.h>
using namespace Rocket;
static const uint32_t s_MaxFramebufferSize = 8192;
OpenGLFrameBuffer::OpenGLFrameBuffer(const FramebufferSpec& spec) : m_Specification(spec)
{
Invalidate();
}
OpenGLFrameBuffer::~OpenGLFrameBuffer()
{
if(m_ColorAttachments.size() > 0)
glDeleteTextures(m_ColorAttachments.size(), m_ColorAttachments.data());
if(m_DepthAttachment)
glDeleteTextures(1, &m_DepthAttachment);
glDeleteFramebuffers(1, &m_RendererID);
}
void OpenGLFrameBuffer::Invalidate()
{
if (m_RendererID)
{
if(m_ColorAttachments.size() > 0)
glDeleteTextures(m_ColorAttachments.size(), m_ColorAttachments.data());
if(m_DepthAttachment)
glDeleteTextures(1, &m_DepthAttachment);
glDeleteFramebuffers(1, &m_RendererID);
m_ColorAttachments.clear();
m_ColorSpecifications.clear();
m_DepthAttachment = 0;
m_RendererID = 0;
}
// Gen Frame Buffer
glGenFramebuffers(1, &m_RendererID);
glBindFramebuffer(GL_FRAMEBUFFER, m_RendererID);
// Bind Color Texture
if (m_Specification.ColorAttachment.size())
{
auto sz = m_Specification.ColorAttachment.size();
m_ColorAttachments.resize(sz);
m_ColorSpecifications.resize(sz);
glGenTextures(sz, m_ColorAttachments.data());
//glActiveTexture(GL_TEXTURE0);
for (size_t i = 0; i < m_ColorAttachments.size(); i++)
{
if(m_Specification.Samples > 1)
{
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, m_ColorAttachments[i]);
switch (m_Specification.ColorAttachment[i])
{
case FRAME_TEXTURE_FORMAT::RGB8:
glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, m_Specification.Samples, GL_RGB8, m_Specification.ColorWidth, m_Specification.ColorHeight, GL_TRUE);
break;
case FRAME_TEXTURE_FORMAT::RGBA8:
glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, m_Specification.Samples, GL_RGBA8, m_Specification.ColorWidth, m_Specification.ColorHeight, GL_TRUE);
break;
case FRAME_TEXTURE_FORMAT::RGBA16:
glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, m_Specification.Samples, GL_RGBA16, m_Specification.ColorWidth, m_Specification.ColorHeight, GL_TRUE);
break;
case FRAME_TEXTURE_FORMAT::RGB16F:
glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, m_Specification.Samples, GL_RGB16F, m_Specification.ColorWidth, m_Specification.ColorHeight, GL_TRUE);
break;
case FRAME_TEXTURE_FORMAT::RGBA16F:
glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, m_Specification.Samples, GL_RGBA16F, m_Specification.ColorWidth, m_Specification.ColorHeight, GL_TRUE);
break;
default:
RK_GRAPHICS_ERROR("Frame Buffer Color Attachment Format Error");
break;
}
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D_MULTISAMPLE, m_ColorAttachments[i], 0);
}
else
{
glBindTexture(GL_TEXTURE_2D, m_ColorAttachments[i]);
switch (m_Specification.ColorAttachment[i])
{
case FRAME_TEXTURE_FORMAT::RGB8:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB8, m_Specification.ColorWidth, m_Specification.ColorHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
break;
case FRAME_TEXTURE_FORMAT::RGBA8:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_Specification.ColorWidth, m_Specification.ColorHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
break;
case FRAME_TEXTURE_FORMAT::RGBA16:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16, m_Specification.ColorWidth, m_Specification.ColorHeight, 0, GL_RGBA, GL_UNSIGNED_INT, NULL);
break;
case FRAME_TEXTURE_FORMAT::RGB16F:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, m_Specification.ColorWidth, m_Specification.ColorHeight, 0, GL_RGB, GL_FLOAT, NULL);
break;
case FRAME_TEXTURE_FORMAT::RGBA16F:
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, m_Specification.ColorWidth, m_Specification.ColorHeight, 0, GL_RGBA, GL_FLOAT, NULL);
break;
default:
RK_GRAPHICS_ERROR("Frame Buffer Color Attachment Format Error");
break;
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + i, GL_TEXTURE_2D, m_ColorAttachments[i], 0);
}
m_ColorSpecifications.push_back(GL_COLOR_ATTACHMENT0 + i);
}
if (m_ColorSpecifications.size() > 0)
{
glDrawBuffers(m_ColorSpecifications.size(), m_ColorSpecifications.data());
}
else
{
glDrawBuffer(GL_NONE);
}
}
// Bind Depth Texture
if(m_Specification.DepthAttachment != FRAME_TEXTURE_FORMAT::NONE)
{
glGenTextures(1, &m_DepthAttachment);
//glActiveTexture(GL_TEXTURE0);
if (m_Specification.Samples > 1)
{
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, m_DepthAttachment);
switch (m_Specification.DepthAttachment)
{
case FRAME_TEXTURE_FORMAT::DEPTH24:
glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, m_Specification.Samples, GL_RGB8, m_Specification.DepthWidth, m_Specification.DepthHeight, GL_TRUE);
break;
case FRAME_TEXTURE_FORMAT::DEPTH24STENCIL8:
glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, m_Specification.Samples, GL_RGBA8, m_Specification.DepthWidth, m_Specification.DepthHeight, GL_TRUE);
break;
default:
RK_GRAPHICS_ERROR("Frame Buffer Color Attachment Format Error");
break;
}
glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0);
switch (m_Specification.DepthAttachment)
{
case FRAME_TEXTURE_FORMAT::DEPTH24:
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, m_DepthAttachment, 0);
break;
case FRAME_TEXTURE_FORMAT::DEPTH24STENCIL8:
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D_MULTISAMPLE, m_DepthAttachment, 0);
break;
default:
RK_GRAPHICS_ERROR("Frame Buffer Color Attachment Format Error");
break;
}
}
else
{
glBindTexture(GL_TEXTURE_2D, m_DepthAttachment);
switch (m_Specification.DepthAttachment)
{
case FRAME_TEXTURE_FORMAT::DEPTH24:
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, m_Specification.ColorWidth, m_Specification.ColorHeight, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
break;
case FRAME_TEXTURE_FORMAT::DEPTH24STENCIL8:
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_STENCIL_ATTACHMENT, m_Specification.ColorWidth, m_Specification.ColorHeight, 0, GL_DEPTH_STENCIL_ATTACHMENT, GL_UNSIGNED_BYTE, NULL);
break;
default:
RK_GRAPHICS_ERROR("Frame Buffer Color Attachment Format Error");
break;
}
//glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, 0);
switch (m_Specification.DepthAttachment)
{
case FRAME_TEXTURE_FORMAT::DEPTH24:
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_DepthAttachment, 0);
break;
case FRAME_TEXTURE_FORMAT::DEPTH24STENCIL8:
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, m_DepthAttachment, 0);
break;
default:
RK_GRAPHICS_ERROR("Frame Buffer Color Attachment Format Error");
break;
}
}
}
RK_GRAPHICS_ASSERT(glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE, "Framebuffer is incomplete!");
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void OpenGLFrameBuffer::Bind(FRAME_BIND_MODE mode)
{
switch (mode)
{
case FRAME_BIND_MODE::FRAMEBUFFER:
glBindFramebuffer(GL_FRAMEBUFFER, m_RendererID);
break;
case FRAME_BIND_MODE::DRAW_FRAMEBUFFER:
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_RendererID);
break;
case FRAME_BIND_MODE::READ_FRAMEBUFFER:
glBindFramebuffer(GL_READ_FRAMEBUFFER, m_RendererID);
break;
}
glViewport(0, 0, m_Specification.ColorWidth, m_Specification.ColorHeight);
}
void OpenGLFrameBuffer::Unbind()
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void OpenGLFrameBuffer::Resize(uint32_t width, uint32_t height)
{
if (width == 0 || height == 0 || width > s_MaxFramebufferSize || height > s_MaxFramebufferSize)
{
RK_GRAPHICS_WARN("Attempted to rezize framebuffer to {0}, {1}", width, height);
return;
}
m_Specification.ColorWidth = width;
m_Specification.ColorHeight = height;
m_Specification.DepthWidth = width;
m_Specification.DepthHeight = height;
Invalidate();
}
|
#ifndef VEC_HPP
#define VEC_HPP
class Vect {
private:
int* arr;
int size;
public:
Vect ();
Vect (int a);
Vect (Vect& obj);
~Vect ();
Vect(Vect&& object);
int getSize();
int getElement(int i);
void setElement(int i, int num);
void pushBack (int a);
void popBack ();
void pushFront (int a);
void popFront ();
void pushIndex (int index, int a);
void popIndex (int index);
#endif
};
|
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
const int INF = 2e9;
int n, m;
cin >> n >> m;
vector<int> a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
unordered_map<int, int> last;
vector<int> prev(n, -INF);
for (int i = 0; i < n; ++i) {
if (last.count(a[i])) {
prev[i] = last[a[i]];
}
last[a[i]] = i;
}
vector< vector<int> > ans(n);
for (int i = 0; i < n; ++i) {
ans[i].reserve(n - i);
int curans = INF;
for (int j = i; j < n; ++j) {
if (prev[j] >= i)
curans = min(curans, j - prev[j]);
if (curans == INF)
ans[i].push_back(-1);
else
ans[i].push_back(curans);
}
}
for (int i = 0; i < m; ++i) {
int l, r;
cin >> l >> r;
cout << ans[l - 1][r - l] << "\n";
}
return 0;
}
|
#include <Arduino.h>
#include <AnalogDisplay.h>
#include <NetworkController.h>
#define PIN_THERMISTOR 0
#define THERMISTOR_UPDATE_FREQUENZ 1500
#define WIFI_UPDATE_FREQUENZ 10000
//#define WIFI_SSID "Zum Einhornland"
//#define WIFI_PW "Butterbreadcoffee23"
#define WIFI_SSID "KabelBox-89F4"
#define WIFI_PW "39499327547949706742"
float readThermistor();
void doStuff();
void showSerialData();
void logSerialAvailable();
String text;
long lastUpdate = 0;
long lastWifiUpdate = 0;
AnalogDisplay analogDisplay(11,9,12,5,2,3,4);
NetworkController networkController(6,7,WIFI_SSID,WIFI_PW);
void setup() {
networkController.establishConnection(WIFI_SSID,WIFI_PW);
Serial.begin(9600);
Serial.println("setup done.");
}
void loop() {
if(millis()-lastUpdate>THERMISTOR_UPDATE_FREQUENZ){
text = (String)readThermistor();
networkController.uploadTemperature(text);
lastUpdate = millis();
}
/*if(millis()-lastWifiUpdate>WIFI_UPDATE_FREQUENZ){
Serial.println("Testing Connection...");
networkController.testConnection();
lastWifiUpdate = millis();
}*/
analogDisplay.printAnalogText(text);
}
float readThermistor(){
float temp = analogRead(PIN_THERMISTOR);
temp = log(10000.0 * ((1024.0 / temp -1)));
temp = 1/(0.001129148+(0.000234125+(0.0000000876741 * temp * temp)) * temp);
temp = temp - 273.15;
return temp;
}
|
// Copyright (c) 2017-2022, University of Cincinnati, developed by Henry Schreiner
// under NSF AWARD 1414736 and by the respective contributors.
// All rights reserved.
//
// SPDX-License-Identifier: BSD-3-Clause
#pragma once
// [CLI11:public_includes:set]
#include <algorithm>
#include <cstdint>
#include <functional>
#include <iostream>
#include <iterator>
#include <memory>
#include <numeric>
#include <set>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
// [CLI11:public_includes:end]
// CLI Library includes
#include "ConfigFwd.hpp"
#include "Error.hpp"
#include "FormatterFwd.hpp"
#include "Macros.hpp"
#include "Option.hpp"
#include "Split.hpp"
#include "StringTools.hpp"
#include "TypeTools.hpp"
namespace CLI {
// [CLI11:app_hpp:verbatim]
#ifndef CLI11_PARSE
#define CLI11_PARSE(app, argc, argv) \
try { \
(app).parse((argc), (argv)); \
} catch(const CLI::ParseError &e) { \
return (app).exit(e); \
}
#endif
namespace detail {
enum class Classifier { NONE, POSITIONAL_MARK, SHORT, LONG, WINDOWS_STYLE, SUBCOMMAND, SUBCOMMAND_TERMINATOR };
struct AppFriend;
} // namespace detail
namespace FailureMessage {
std::string simple(const App *app, const Error &e);
std::string help(const App *app, const Error &e);
} // namespace FailureMessage
/// enumeration of modes of how to deal with extras in config files
enum class config_extras_mode : char { error = 0, ignore, ignore_all, capture };
class App;
using App_p = std::shared_ptr<App>;
namespace detail {
/// helper functions for adding in appropriate flag modifiers for add_flag
template <typename T, enable_if_t<!std::is_integral<T>::value || (sizeof(T) <= 1U), detail::enabler> = detail::dummy>
Option *default_flag_modifiers(Option *opt) {
return opt->always_capture_default();
}
/// summing modifiers
template <typename T, enable_if_t<std::is_integral<T>::value && (sizeof(T) > 1U), detail::enabler> = detail::dummy>
Option *default_flag_modifiers(Option *opt) {
return opt->multi_option_policy(MultiOptionPolicy::Sum)->default_str("0")->force_callback();
}
} // namespace detail
class Option_group;
/// Creates a command line program, with very few defaults.
/** To use, create a new `Program()` instance with `argc`, `argv`, and a help description. The templated
* add_option methods make it easy to prepare options. Remember to call `.start` before starting your
* program, so that the options can be evaluated and the help option doesn't accidentally run your program. */
class App {
friend Option;
friend detail::AppFriend;
protected:
// This library follows the Google style guide for member names ending in underscores
/// @name Basics
///@{
/// Subcommand name or program name (from parser if name is empty)
std::string name_{};
/// Description of the current program/subcommand
std::string description_{};
/// If true, allow extra arguments (ie, don't throw an error). INHERITABLE
bool allow_extras_{false};
/// If ignore, allow extra arguments in the ini file (ie, don't throw an error). INHERITABLE
/// if error error on an extra argument, and if capture feed it to the app
config_extras_mode allow_config_extras_{config_extras_mode::ignore};
/// If true, return immediately on an unrecognized option (implies allow_extras) INHERITABLE
bool prefix_command_{false};
/// If set to true the name was automatically generated from the command line vs a user set name
bool has_automatic_name_{false};
/// If set to true the subcommand is required to be processed and used, ignored for main app
bool required_{false};
/// If set to true the subcommand is disabled and cannot be used, ignored for main app
bool disabled_{false};
/// Flag indicating that the pre_parse_callback has been triggered
bool pre_parse_called_{false};
/// Flag indicating that the callback for the subcommand should be executed immediately on parse completion which is
/// before help or ini files are processed. INHERITABLE
bool immediate_callback_{false};
/// This is a function that runs prior to the start of parsing
std::function<void(std::size_t)> pre_parse_callback_{};
/// This is a function that runs when parsing has finished.
std::function<void()> parse_complete_callback_{};
/// This is a function that runs when all processing has completed
std::function<void()> final_callback_{};
///@}
/// @name Options
///@{
/// The default values for options, customizable and changeable INHERITABLE
OptionDefaults option_defaults_{};
/// The list of options, stored locally
std::vector<Option_p> options_{};
///@}
/// @name Help
///@{
/// Footer to put after all options in the help output INHERITABLE
std::string footer_{};
/// This is a function that generates a footer to put after all other options in help output
std::function<std::string()> footer_callback_{};
/// A pointer to the help flag if there is one INHERITABLE
Option *help_ptr_{nullptr};
/// A pointer to the help all flag if there is one INHERITABLE
Option *help_all_ptr_{nullptr};
/// A pointer to a version flag if there is one
Option *version_ptr_{nullptr};
/// This is the formatter for help printing. Default provided. INHERITABLE (same pointer)
std::shared_ptr<FormatterBase> formatter_{new Formatter()};
/// The error message printing function INHERITABLE
std::function<std::string(const App *, const Error &e)> failure_message_{FailureMessage::simple};
///@}
/// @name Parsing
///@{
using missing_t = std::vector<std::pair<detail::Classifier, std::string>>;
/// Pair of classifier, string for missing options. (extra detail is removed on returning from parse)
///
/// This is faster and cleaner than storing just a list of strings and reparsing. This may contain the -- separator.
missing_t missing_{};
/// This is a list of pointers to options with the original parse order
std::vector<Option *> parse_order_{};
/// This is a list of the subcommands collected, in order
std::vector<App *> parsed_subcommands_{};
/// this is a list of subcommands that are exclusionary to this one
std::set<App *> exclude_subcommands_{};
/// This is a list of options which are exclusionary to this App, if the options were used this subcommand should
/// not be
std::set<Option *> exclude_options_{};
/// this is a list of subcommands or option groups that are required by this one, the list is not mutual, the
/// listed subcommands do not require this one
std::set<App *> need_subcommands_{};
/// This is a list of options which are required by this app, the list is not mutual, listed options do not need the
/// subcommand not be
std::set<Option *> need_options_{};
///@}
/// @name Subcommands
///@{
/// Storage for subcommand list
std::vector<App_p> subcommands_{};
/// If true, the program name is not case sensitive INHERITABLE
bool ignore_case_{false};
/// If true, the program should ignore underscores INHERITABLE
bool ignore_underscore_{false};
/// Allow subcommand fallthrough, so that parent commands can collect commands after subcommand. INHERITABLE
bool fallthrough_{false};
/// Allow '/' for options for Windows like options. Defaults to true on Windows, false otherwise. INHERITABLE
bool allow_windows_style_options_{
#ifdef _WIN32
true
#else
false
#endif
};
/// specify that positional arguments come at the end of the argument sequence not inheritable
bool positionals_at_end_{false};
enum class startup_mode : char { stable, enabled, disabled };
/// specify the startup mode for the app
/// stable=no change, enabled= startup enabled, disabled=startup disabled
startup_mode default_startup{startup_mode::stable};
/// if set to true the subcommand can be triggered via configuration files INHERITABLE
bool configurable_{false};
/// If set to true positional options are validated before assigning INHERITABLE
bool validate_positionals_{false};
/// If set to true optional vector arguments are validated before assigning INHERITABLE
bool validate_optional_arguments_{false};
/// indicator that the subcommand is silent and won't show up in subcommands list
/// This is potentially useful as a modifier subcommand
bool silent_{false};
/// Counts the number of times this command/subcommand was parsed
std::uint32_t parsed_{0U};
/// Minimum required subcommands (not inheritable!)
std::size_t require_subcommand_min_{0};
/// Max number of subcommands allowed (parsing stops after this number). 0 is unlimited INHERITABLE
std::size_t require_subcommand_max_{0};
/// Minimum required options (not inheritable!)
std::size_t require_option_min_{0};
/// Max number of options allowed. 0 is unlimited (not inheritable)
std::size_t require_option_max_{0};
/// A pointer to the parent if this is a subcommand
App *parent_{nullptr};
/// The group membership INHERITABLE
std::string group_{"Subcommands"};
/// Alias names for the subcommand
std::vector<std::string> aliases_{};
///@}
/// @name Config
///@{
/// Pointer to the config option
Option *config_ptr_{nullptr};
/// This is the formatter for help printing. Default provided. INHERITABLE (same pointer)
std::shared_ptr<Config> config_formatter_{new ConfigTOML()};
///@}
/// Special private constructor for subcommand
App(std::string app_description, std::string app_name, App *parent)
: name_(std::move(app_name)), description_(std::move(app_description)), parent_(parent) {
// Inherit if not from a nullptr
if(parent_ != nullptr) {
if(parent_->help_ptr_ != nullptr)
set_help_flag(parent_->help_ptr_->get_name(false, true), parent_->help_ptr_->get_description());
if(parent_->help_all_ptr_ != nullptr)
set_help_all_flag(parent_->help_all_ptr_->get_name(false, true),
parent_->help_all_ptr_->get_description());
/// OptionDefaults
option_defaults_ = parent_->option_defaults_;
// INHERITABLE
failure_message_ = parent_->failure_message_;
allow_extras_ = parent_->allow_extras_;
allow_config_extras_ = parent_->allow_config_extras_;
prefix_command_ = parent_->prefix_command_;
immediate_callback_ = parent_->immediate_callback_;
ignore_case_ = parent_->ignore_case_;
ignore_underscore_ = parent_->ignore_underscore_;
fallthrough_ = parent_->fallthrough_;
validate_positionals_ = parent_->validate_positionals_;
validate_optional_arguments_ = parent_->validate_optional_arguments_;
configurable_ = parent_->configurable_;
allow_windows_style_options_ = parent_->allow_windows_style_options_;
group_ = parent_->group_;
footer_ = parent_->footer_;
formatter_ = parent_->formatter_;
config_formatter_ = parent_->config_formatter_;
require_subcommand_max_ = parent_->require_subcommand_max_;
}
}
public:
/// @name Basic
///@{
/// Create a new program. Pass in the same arguments as main(), along with a help string.
explicit App(std::string app_description = "", std::string app_name = "")
: App(app_description, app_name, nullptr) {
set_help_flag("-h,--help", "Print this help message and exit");
}
App(const App &) = delete;
App &operator=(const App &) = delete;
/// virtual destructor
virtual ~App() = default;
/// Set a callback for execution when all parsing and processing has completed
///
/// Due to a bug in c++11,
/// it is not possible to overload on std::function (fixed in c++14
/// and backported to c++11 on newer compilers). Use capture by reference
/// to get a pointer to App if needed.
App *callback(std::function<void()> app_callback) {
if(immediate_callback_) {
parse_complete_callback_ = std::move(app_callback);
} else {
final_callback_ = std::move(app_callback);
}
return this;
}
/// Set a callback for execution when all parsing and processing has completed
/// aliased as callback
App *final_callback(std::function<void()> app_callback) {
final_callback_ = std::move(app_callback);
return this;
}
/// Set a callback to execute when parsing has completed for the app
///
App *parse_complete_callback(std::function<void()> pc_callback) {
parse_complete_callback_ = std::move(pc_callback);
return this;
}
/// Set a callback to execute prior to parsing.
///
App *preparse_callback(std::function<void(std::size_t)> pp_callback) {
pre_parse_callback_ = std::move(pp_callback);
return this;
}
/// Set a name for the app (empty will use parser to set the name)
App *name(std::string app_name = "") {
if(parent_ != nullptr) {
auto oname = name_;
name_ = app_name;
auto &res = _compare_subcommand_names(*this, *_get_fallthrough_parent());
if(!res.empty()) {
name_ = oname;
throw(OptionAlreadyAdded(app_name + " conflicts with existing subcommand names"));
}
} else {
name_ = app_name;
}
has_automatic_name_ = false;
return this;
}
/// Set an alias for the app
App *alias(std::string app_name) {
if(app_name.empty() || !detail::valid_alias_name_string(app_name)) {
throw IncorrectConstruction("Aliases may not be empty or contain newlines or null characters");
}
if(parent_ != nullptr) {
aliases_.push_back(app_name);
auto &res = _compare_subcommand_names(*this, *_get_fallthrough_parent());
if(!res.empty()) {
aliases_.pop_back();
throw(OptionAlreadyAdded("alias already matches an existing subcommand: " + app_name));
}
} else {
aliases_.push_back(app_name);
}
return this;
}
/// Remove the error when extras are left over on the command line.
App *allow_extras(bool allow = true) {
allow_extras_ = allow;
return this;
}
/// Remove the error when extras are left over on the command line.
App *required(bool require = true) {
required_ = require;
return this;
}
/// Disable the subcommand or option group
App *disabled(bool disable = true) {
disabled_ = disable;
return this;
}
/// silence the subcommand from showing up in the processed list
App *silent(bool silence = true) {
silent_ = silence;
return this;
}
/// Set the subcommand to be disabled by default, so on clear(), at the start of each parse it is disabled
App *disabled_by_default(bool disable = true) {
if(disable) {
default_startup = startup_mode::disabled;
} else {
default_startup = (default_startup == startup_mode::enabled) ? startup_mode::enabled : startup_mode::stable;
}
return this;
}
/// Set the subcommand to be enabled by default, so on clear(), at the start of each parse it is enabled (not
/// disabled)
App *enabled_by_default(bool enable = true) {
if(enable) {
default_startup = startup_mode::enabled;
} else {
default_startup =
(default_startup == startup_mode::disabled) ? startup_mode::disabled : startup_mode::stable;
}
return this;
}
/// Set the subcommand callback to be executed immediately on subcommand completion
App *immediate_callback(bool immediate = true) {
immediate_callback_ = immediate;
if(immediate_callback_) {
if(final_callback_ && !(parse_complete_callback_)) {
std::swap(final_callback_, parse_complete_callback_);
}
} else if(!(final_callback_) && parse_complete_callback_) {
std::swap(final_callback_, parse_complete_callback_);
}
return this;
}
/// Set the subcommand to validate positional arguments before assigning
App *validate_positionals(bool validate = true) {
validate_positionals_ = validate;
return this;
}
/// Set the subcommand to validate optional vector arguments before assigning
App *validate_optional_arguments(bool validate = true) {
validate_optional_arguments_ = validate;
return this;
}
/// ignore extras in config files
App *allow_config_extras(bool allow = true) {
if(allow) {
allow_config_extras_ = config_extras_mode::capture;
allow_extras_ = true;
} else {
allow_config_extras_ = config_extras_mode::error;
}
return this;
}
/// ignore extras in config files
App *allow_config_extras(config_extras_mode mode) {
allow_config_extras_ = mode;
return this;
}
/// Do not parse anything after the first unrecognized option and return
App *prefix_command(bool allow = true) {
prefix_command_ = allow;
return this;
}
/// Ignore case. Subcommands inherit value.
App *ignore_case(bool value = true) {
if(value && !ignore_case_) {
ignore_case_ = true;
auto *p = (parent_ != nullptr) ? _get_fallthrough_parent() : this;
auto &match = _compare_subcommand_names(*this, *p);
if(!match.empty()) {
ignore_case_ = false; // we are throwing so need to be exception invariant
throw OptionAlreadyAdded("ignore case would cause subcommand name conflicts: " + match);
}
}
ignore_case_ = value;
return this;
}
/// Allow windows style options, such as `/opt`. First matching short or long name used. Subcommands inherit
/// value.
App *allow_windows_style_options(bool value = true) {
allow_windows_style_options_ = value;
return this;
}
/// Specify that the positional arguments are only at the end of the sequence
App *positionals_at_end(bool value = true) {
positionals_at_end_ = value;
return this;
}
/// Specify that the subcommand can be triggered by a config file
App *configurable(bool value = true) {
configurable_ = value;
return this;
}
/// Ignore underscore. Subcommands inherit value.
App *ignore_underscore(bool value = true) {
if(value && !ignore_underscore_) {
ignore_underscore_ = true;
auto *p = (parent_ != nullptr) ? _get_fallthrough_parent() : this;
auto &match = _compare_subcommand_names(*this, *p);
if(!match.empty()) {
ignore_underscore_ = false;
throw OptionAlreadyAdded("ignore underscore would cause subcommand name conflicts: " + match);
}
}
ignore_underscore_ = value;
return this;
}
/// Set the help formatter
App *formatter(std::shared_ptr<FormatterBase> fmt) {
formatter_ = fmt;
return this;
}
/// Set the help formatter
App *formatter_fn(std::function<std::string(const App *, std::string, AppFormatMode)> fmt) {
formatter_ = std::make_shared<FormatterLambda>(fmt);
return this;
}
/// Set the config formatter
App *config_formatter(std::shared_ptr<Config> fmt) {
config_formatter_ = fmt;
return this;
}
/// Check to see if this subcommand was parsed, true only if received on command line.
bool parsed() const { return parsed_ > 0; }
/// Get the OptionDefault object, to set option defaults
OptionDefaults *option_defaults() { return &option_defaults_; }
///@}
/// @name Adding options
///@{
/// Add an option, will automatically understand the type for common types.
///
/// To use, create a variable with the expected type, and pass it in after the name.
/// After start is called, you can use count to see if the value was passed, and
/// the value will be initialized properly. Numbers, vectors, and strings are supported.
///
/// ->required(), ->default, and the validators are options,
/// The positional options take an optional number of arguments.
///
/// For example,
///
/// std::string filename;
/// program.add_option("filename", filename, "description of filename");
///
Option *add_option(std::string option_name,
callback_t option_callback,
std::string option_description = "",
bool defaulted = false,
std::function<std::string()> func = {}) {
Option myopt{option_name, option_description, option_callback, this};
if(std::find_if(std::begin(options_), std::end(options_), [&myopt](const Option_p &v) {
return *v == myopt;
}) == std::end(options_)) {
options_.emplace_back();
Option_p &option = options_.back();
option.reset(new Option(option_name, option_description, option_callback, this));
// Set the default string capture function
option->default_function(func);
// For compatibility with CLI11 1.7 and before, capture the default string here
if(defaulted)
option->capture_default_str();
// Transfer defaults to the new option
option_defaults_.copy_to(option.get());
// Don't bother to capture if we already did
if(!defaulted && option->get_always_capture_default())
option->capture_default_str();
return option.get();
}
// we know something matches now find what it is so we can produce more error information
for(auto &opt : options_) {
auto &matchname = opt->matching_name(myopt);
if(!matchname.empty()) {
throw(OptionAlreadyAdded("added option matched existing option name: " + matchname));
}
}
// this line should not be reached the above loop should trigger the throw
throw(OptionAlreadyAdded("added option matched existing option name")); // LCOV_EXCL_LINE
}
/// Add option for assigning to a variable
template <typename AssignTo,
typename ConvertTo = AssignTo,
enable_if_t<!std::is_const<ConvertTo>::value, detail::enabler> = detail::dummy>
Option *add_option(std::string option_name,
AssignTo &variable, ///< The variable to set
std::string option_description = "") {
auto fun = [&variable](const CLI::results_t &res) { // comment for spacing
return detail::lexical_conversion<AssignTo, ConvertTo>(res, variable);
};
Option *opt = add_option(option_name, fun, option_description, false, [&variable]() {
return CLI::detail::checked_to_string<AssignTo, ConvertTo>(variable);
});
opt->type_name(detail::type_name<ConvertTo>());
// these must be actual lvalues since (std::max) sometimes is defined in terms of references and references
// to structs used in the evaluation can be temporary so that would cause issues.
auto Tcount = detail::type_count<AssignTo>::value;
auto XCcount = detail::type_count<ConvertTo>::value;
opt->type_size(detail::type_count_min<ConvertTo>::value, (std::max)(Tcount, XCcount));
opt->expected(detail::expected_count<ConvertTo>::value);
opt->run_callback_for_default();
return opt;
}
/// Add option for assigning to a variable
template <typename AssignTo, enable_if_t<!std::is_const<AssignTo>::value, detail::enabler> = detail::dummy>
Option *add_option_no_stream(std::string option_name,
AssignTo &variable, ///< The variable to set
std::string option_description = "") {
auto fun = [&variable](const CLI::results_t &res) { // comment for spacing
return detail::lexical_conversion<AssignTo, AssignTo>(res, variable);
};
Option *opt = add_option(option_name, fun, option_description, false, []() { return std::string{}; });
opt->type_name(detail::type_name<AssignTo>());
opt->type_size(detail::type_count_min<AssignTo>::value, detail::type_count<AssignTo>::value);
opt->expected(detail::expected_count<AssignTo>::value);
opt->run_callback_for_default();
return opt;
}
/// Add option for a callback of a specific type
template <typename ArgType>
Option *add_option_function(std::string option_name,
const std::function<void(const ArgType &)> &func, ///< the callback to execute
std::string option_description = "") {
auto fun = [func](const CLI::results_t &res) {
ArgType variable;
bool result = detail::lexical_conversion<ArgType, ArgType>(res, variable);
if(result) {
func(variable);
}
return result;
};
Option *opt = add_option(option_name, std::move(fun), option_description, false);
opt->type_name(detail::type_name<ArgType>());
opt->type_size(detail::type_count_min<ArgType>::value, detail::type_count<ArgType>::value);
opt->expected(detail::expected_count<ArgType>::value);
return opt;
}
/// Add option with no description or variable assignment
Option *add_option(std::string option_name) {
return add_option(option_name, CLI::callback_t{}, std::string{}, false);
}
/// Add option with description but with no variable assignment or callback
template <typename T,
enable_if_t<std::is_const<T>::value && std::is_constructible<std::string, T>::value, detail::enabler> =
detail::dummy>
Option *add_option(std::string option_name, T &option_description) {
return add_option(option_name, CLI::callback_t(), option_description, false);
}
/// Set a help flag, replace the existing one if present
Option *set_help_flag(std::string flag_name = "", const std::string &help_description = "") {
// take flag_description by const reference otherwise add_flag tries to assign to help_description
if(help_ptr_ != nullptr) {
remove_option(help_ptr_);
help_ptr_ = nullptr;
}
// Empty name will simply remove the help flag
if(!flag_name.empty()) {
help_ptr_ = add_flag(flag_name, help_description);
help_ptr_->configurable(false);
}
return help_ptr_;
}
/// Set a help all flag, replaced the existing one if present
Option *set_help_all_flag(std::string help_name = "", const std::string &help_description = "") {
// take flag_description by const reference otherwise add_flag tries to assign to flag_description
if(help_all_ptr_ != nullptr) {
remove_option(help_all_ptr_);
help_all_ptr_ = nullptr;
}
// Empty name will simply remove the help all flag
if(!help_name.empty()) {
help_all_ptr_ = add_flag(help_name, help_description);
help_all_ptr_->configurable(false);
}
return help_all_ptr_;
}
/// Set a version flag and version display string, replace the existing one if present
Option *set_version_flag(std::string flag_name = "",
const std::string &versionString = "",
const std::string &version_help = "Display program version information and exit") {
// take flag_description by const reference otherwise add_flag tries to assign to version_description
if(version_ptr_ != nullptr) {
remove_option(version_ptr_);
version_ptr_ = nullptr;
}
// Empty name will simply remove the version flag
if(!flag_name.empty()) {
version_ptr_ = add_flag_callback(
flag_name, [versionString]() { throw(CLI::CallForVersion(versionString, 0)); }, version_help);
version_ptr_->configurable(false);
}
return version_ptr_;
}
/// Generate the version string through a callback function
Option *set_version_flag(std::string flag_name,
std::function<std::string()> vfunc,
const std::string &version_help = "Display program version information and exit") {
if(version_ptr_ != nullptr) {
remove_option(version_ptr_);
version_ptr_ = nullptr;
}
// Empty name will simply remove the version flag
if(!flag_name.empty()) {
version_ptr_ = add_flag_callback(
flag_name, [vfunc]() { throw(CLI::CallForVersion(vfunc(), 0)); }, version_help);
version_ptr_->configurable(false);
}
return version_ptr_;
}
private:
/// Internal function for adding a flag
Option *_add_flag_internal(std::string flag_name, CLI::callback_t fun, std::string flag_description) {
Option *opt;
if(detail::has_default_flag_values(flag_name)) {
// check for default values and if it has them
auto flag_defaults = detail::get_default_flag_values(flag_name);
detail::remove_default_flag_values(flag_name);
opt = add_option(std::move(flag_name), std::move(fun), std::move(flag_description), false);
for(const auto &fname : flag_defaults)
opt->fnames_.push_back(fname.first);
opt->default_flag_values_ = std::move(flag_defaults);
} else {
opt = add_option(std::move(flag_name), std::move(fun), std::move(flag_description), false);
}
// flags cannot have positional values
if(opt->get_positional()) {
auto pos_name = opt->get_name(true);
remove_option(opt);
throw IncorrectConstruction::PositionalFlag(pos_name);
}
opt->multi_option_policy(MultiOptionPolicy::TakeLast);
opt->expected(0);
opt->required(false);
return opt;
}
public:
/// Add a flag with no description or variable assignment
Option *add_flag(std::string flag_name) { return _add_flag_internal(flag_name, CLI::callback_t(), std::string{}); }
/// Add flag with description but with no variable assignment or callback
/// takes a constant string, if a variable string is passed that variable will be assigned the results from the
/// flag
template <typename T,
enable_if_t<std::is_const<T>::value && std::is_constructible<std::string, T>::value, detail::enabler> =
detail::dummy>
Option *add_flag(std::string flag_name, T &flag_description) {
return _add_flag_internal(flag_name, CLI::callback_t(), flag_description);
}
/// Other type version accepts all other types that are not vectors such as bool, enum, string or other classes
/// that can be converted from a string
template <typename T,
enable_if_t<!detail::is_mutable_container<T>::value && !std::is_const<T>::value &&
!std::is_constructible<std::function<void(int)>, T>::value,
detail::enabler> = detail::dummy>
Option *add_flag(std::string flag_name,
T &flag_result, ///< A variable holding the flag result
std::string flag_description = "") {
CLI::callback_t fun = [&flag_result](const CLI::results_t &res) {
return CLI::detail::lexical_cast(res[0], flag_result);
};
auto *opt = _add_flag_internal(flag_name, std::move(fun), std::move(flag_description));
return detail::default_flag_modifiers<T>(opt);
}
/// Vector version to capture multiple flags.
template <typename T,
enable_if_t<!std::is_assignable<std::function<void(std::int64_t)> &, T>::value, detail::enabler> =
detail::dummy>
Option *add_flag(std::string flag_name,
std::vector<T> &flag_results, ///< A vector of values with the flag results
std::string flag_description = "") {
CLI::callback_t fun = [&flag_results](const CLI::results_t &res) {
bool retval = true;
for(const auto &elem : res) {
flag_results.emplace_back();
retval &= detail::lexical_cast(elem, flag_results.back());
}
return retval;
};
return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description))
->multi_option_policy(MultiOptionPolicy::TakeAll)
->run_callback_for_default();
}
/// Add option for callback that is triggered with a true flag and takes no arguments
Option *add_flag_callback(std::string flag_name,
std::function<void(void)> function, ///< A function to call, void(void)
std::string flag_description = "") {
CLI::callback_t fun = [function](const CLI::results_t &res) {
bool trigger{false};
auto result = CLI::detail::lexical_cast(res[0], trigger);
if(result && trigger) {
function();
}
return result;
};
return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description));
}
/// Add option for callback with an integer value
Option *add_flag_function(std::string flag_name,
std::function<void(std::int64_t)> function, ///< A function to call, void(int)
std::string flag_description = "") {
CLI::callback_t fun = [function](const CLI::results_t &res) {
std::int64_t flag_count{0};
CLI::detail::lexical_cast(res[0], flag_count);
function(flag_count);
return true;
};
return _add_flag_internal(flag_name, std::move(fun), std::move(flag_description))
->multi_option_policy(MultiOptionPolicy::Sum);
}
#ifdef CLI11_CPP14
/// Add option for callback (C++14 or better only)
Option *add_flag(std::string flag_name,
std::function<void(std::int64_t)> function, ///< A function to call, void(std::int64_t)
std::string flag_description = "") {
return add_flag_function(std::move(flag_name), std::move(function), std::move(flag_description));
}
#endif
/// Set a configuration ini file option, or clear it if no name passed
Option *set_config(std::string option_name = "",
std::string default_filename = "",
const std::string &help_message = "Read an ini file",
bool config_required = false) {
// Remove existing config if present
if(config_ptr_ != nullptr) {
remove_option(config_ptr_);
config_ptr_ = nullptr; // need to remove the config_ptr completely
}
// Only add config if option passed
if(!option_name.empty()) {
config_ptr_ = add_option(option_name, help_message);
if(config_required) {
config_ptr_->required();
}
if(!default_filename.empty()) {
config_ptr_->default_str(std::move(default_filename));
}
config_ptr_->configurable(false);
}
return config_ptr_;
}
/// Removes an option from the App. Takes an option pointer. Returns true if found and removed.
bool remove_option(Option *opt) {
// Make sure no links exist
for(Option_p &op : options_) {
op->remove_needs(opt);
op->remove_excludes(opt);
}
if(help_ptr_ == opt)
help_ptr_ = nullptr;
if(help_all_ptr_ == opt)
help_all_ptr_ = nullptr;
auto iterator =
std::find_if(std::begin(options_), std::end(options_), [opt](const Option_p &v) { return v.get() == opt; });
if(iterator != std::end(options_)) {
options_.erase(iterator);
return true;
}
return false;
}
/// creates an option group as part of the given app
template <typename T = Option_group>
T *add_option_group(std::string group_name, std::string group_description = "") {
if(!detail::valid_alias_name_string(group_name)) {
throw IncorrectConstruction("option group names may not contain newlines or null characters");
}
auto option_group = std::make_shared<T>(std::move(group_description), group_name, this);
auto ptr = option_group.get();
// move to App_p for overload resolution on older gcc versions
App_p app_ptr = std::dynamic_pointer_cast<App>(option_group);
add_subcommand(std::move(app_ptr));
return ptr;
}
///@}
/// @name Subcommands
///@{
/// Add a subcommand. Inherits INHERITABLE and OptionDefaults, and help flag
App *add_subcommand(std::string subcommand_name = "", std::string subcommand_description = "") {
if(!subcommand_name.empty() && !detail::valid_name_string(subcommand_name)) {
if(!detail::valid_first_char(subcommand_name[0])) {
throw IncorrectConstruction(
"Subcommand name starts with invalid character, '!' and '-' are not allowed");
}
for(auto c : subcommand_name) {
if(!detail::valid_later_char(c)) {
throw IncorrectConstruction(std::string("Subcommand name contains invalid character ('") + c +
"'), all characters are allowed except"
"'=',':','{','}', and ' '");
}
}
}
CLI::App_p subcom = std::shared_ptr<App>(new App(std::move(subcommand_description), subcommand_name, this));
return add_subcommand(std::move(subcom));
}
/// Add a previously created app as a subcommand
App *add_subcommand(CLI::App_p subcom) {
if(!subcom)
throw IncorrectConstruction("passed App is not valid");
auto ckapp = (name_.empty() && parent_ != nullptr) ? _get_fallthrough_parent() : this;
auto &mstrg = _compare_subcommand_names(*subcom, *ckapp);
if(!mstrg.empty()) {
throw(OptionAlreadyAdded("subcommand name or alias matches existing subcommand: " + mstrg));
}
subcom->parent_ = this;
subcommands_.push_back(std::move(subcom));
return subcommands_.back().get();
}
/// Removes a subcommand from the App. Takes a subcommand pointer. Returns true if found and removed.
bool remove_subcommand(App *subcom) {
// Make sure no links exist
for(App_p &sub : subcommands_) {
sub->remove_excludes(subcom);
sub->remove_needs(subcom);
}
auto iterator = std::find_if(
std::begin(subcommands_), std::end(subcommands_), [subcom](const App_p &v) { return v.get() == subcom; });
if(iterator != std::end(subcommands_)) {
subcommands_.erase(iterator);
return true;
}
return false;
}
/// Check to see if a subcommand is part of this command (doesn't have to be in command line)
/// returns the first subcommand if passed a nullptr
App *get_subcommand(const App *subcom) const {
if(subcom == nullptr)
throw OptionNotFound("nullptr passed");
for(const App_p &subcomptr : subcommands_)
if(subcomptr.get() == subcom)
return subcomptr.get();
throw OptionNotFound(subcom->get_name());
}
/// Check to see if a subcommand is part of this command (text version)
App *get_subcommand(std::string subcom) const {
auto subc = _find_subcommand(subcom, false, false);
if(subc == nullptr)
throw OptionNotFound(subcom);
return subc;
}
/// Get a pointer to subcommand by index
App *get_subcommand(int index = 0) const {
if(index >= 0) {
auto uindex = static_cast<unsigned>(index);
if(uindex < subcommands_.size())
return subcommands_[uindex].get();
}
throw OptionNotFound(std::to_string(index));
}
/// Check to see if a subcommand is part of this command and get a shared_ptr to it
CLI::App_p get_subcommand_ptr(App *subcom) const {
if(subcom == nullptr)
throw OptionNotFound("nullptr passed");
for(const App_p &subcomptr : subcommands_)
if(subcomptr.get() == subcom)
return subcomptr;
throw OptionNotFound(subcom->get_name());
}
/// Check to see if a subcommand is part of this command (text version)
CLI::App_p get_subcommand_ptr(std::string subcom) const {
for(const App_p &subcomptr : subcommands_)
if(subcomptr->check_name(subcom))
return subcomptr;
throw OptionNotFound(subcom);
}
/// Get an owning pointer to subcommand by index
CLI::App_p get_subcommand_ptr(int index = 0) const {
if(index >= 0) {
auto uindex = static_cast<unsigned>(index);
if(uindex < subcommands_.size())
return subcommands_[uindex];
}
throw OptionNotFound(std::to_string(index));
}
/// Check to see if an option group is part of this App
App *get_option_group(std::string group_name) const {
for(const App_p &app : subcommands_) {
if(app->name_.empty() && app->group_ == group_name) {
return app.get();
}
}
throw OptionNotFound(group_name);
}
/// No argument version of count counts the number of times this subcommand was
/// passed in. The main app will return 1. Unnamed subcommands will also return 1 unless
/// otherwise modified in a callback
std::size_t count() const { return parsed_; }
/// Get a count of all the arguments processed in options and subcommands, this excludes arguments which were
/// treated as extras.
std::size_t count_all() const {
std::size_t cnt{0};
for(auto &opt : options_) {
cnt += opt->count();
}
for(auto &sub : subcommands_) {
cnt += sub->count_all();
}
if(!get_name().empty()) { // for named subcommands add the number of times the subcommand was called
cnt += parsed_;
}
return cnt;
}
/// Changes the group membership
App *group(std::string group_name) {
group_ = group_name;
return this;
}
/// The argumentless form of require subcommand requires 1 or more subcommands
App *require_subcommand() {
require_subcommand_min_ = 1;
require_subcommand_max_ = 0;
return this;
}
/// Require a subcommand to be given (does not affect help call)
/// The number required can be given. Negative values indicate maximum
/// number allowed (0 for any number). Max number inheritable.
App *require_subcommand(int value) {
if(value < 0) {
require_subcommand_min_ = 0;
require_subcommand_max_ = static_cast<std::size_t>(-value);
} else {
require_subcommand_min_ = static_cast<std::size_t>(value);
require_subcommand_max_ = static_cast<std::size_t>(value);
}
return this;
}
/// Explicitly control the number of subcommands required. Setting 0
/// for the max means unlimited number allowed. Max number inheritable.
App *require_subcommand(std::size_t min, std::size_t max) {
require_subcommand_min_ = min;
require_subcommand_max_ = max;
return this;
}
/// The argumentless form of require option requires 1 or more options be used
App *require_option() {
require_option_min_ = 1;
require_option_max_ = 0;
return this;
}
/// Require an option to be given (does not affect help call)
/// The number required can be given. Negative values indicate maximum
/// number allowed (0 for any number).
App *require_option(int value) {
if(value < 0) {
require_option_min_ = 0;
require_option_max_ = static_cast<std::size_t>(-value);
} else {
require_option_min_ = static_cast<std::size_t>(value);
require_option_max_ = static_cast<std::size_t>(value);
}
return this;
}
/// Explicitly control the number of options required. Setting 0
/// for the max means unlimited number allowed. Max number inheritable.
App *require_option(std::size_t min, std::size_t max) {
require_option_min_ = min;
require_option_max_ = max;
return this;
}
/// Stop subcommand fallthrough, so that parent commands cannot collect commands after subcommand.
/// Default from parent, usually set on parent.
App *fallthrough(bool value = true) {
fallthrough_ = value;
return this;
}
/// Check to see if this subcommand was parsed, true only if received on command line.
/// This allows the subcommand to be directly checked.
explicit operator bool() const { return parsed_ > 0; }
///@}
/// @name Extras for subclassing
///@{
/// This allows subclasses to inject code before callbacks but after parse.
///
/// This does not run if any errors or help is thrown.
virtual void pre_callback() {}
///@}
/// @name Parsing
///@{
//
/// Reset the parsed data
void clear() {
parsed_ = 0;
pre_parse_called_ = false;
missing_.clear();
parsed_subcommands_.clear();
for(const Option_p &opt : options_) {
opt->clear();
}
for(const App_p &subc : subcommands_) {
subc->clear();
}
}
/// Parses the command line - throws errors.
/// This must be called after the options are in but before the rest of the program.
void parse(int argc, const char *const *argv) {
// If the name is not set, read from command line
if(name_.empty() || has_automatic_name_) {
has_automatic_name_ = true;
name_ = argv[0];
}
std::vector<std::string> args;
args.reserve(static_cast<std::size_t>(argc) - 1U);
for(auto i = static_cast<std::size_t>(argc) - 1U; i > 0U; --i)
args.emplace_back(argv[i]);
parse(std::move(args));
}
/// Parse a single string as if it contained command line arguments.
/// This function splits the string into arguments then calls parse(std::vector<std::string> &)
/// the function takes an optional boolean argument specifying if the programName is included in the string to
/// process
void parse(std::string commandline, bool program_name_included = false) {
if(program_name_included) {
auto nstr = detail::split_program_name(commandline);
if((name_.empty()) || (has_automatic_name_)) {
has_automatic_name_ = true;
name_ = nstr.first;
}
commandline = std::move(nstr.second);
} else {
detail::trim(commandline);
}
// the next section of code is to deal with quoted arguments after an '=' or ':' for windows like operations
if(!commandline.empty()) {
commandline = detail::find_and_modify(commandline, "=", detail::escape_detect);
if(allow_windows_style_options_)
commandline = detail::find_and_modify(commandline, ":", detail::escape_detect);
}
auto args = detail::split_up(std::move(commandline));
// remove all empty strings
args.erase(std::remove(args.begin(), args.end(), std::string{}), args.end());
std::reverse(args.begin(), args.end());
parse(std::move(args));
}
/// The real work is done here. Expects a reversed vector.
/// Changes the vector to the remaining options.
void parse(std::vector<std::string> &args) {
// Clear if parsed
if(parsed_ > 0)
clear();
// parsed_ is incremented in commands/subcommands,
// but placed here to make sure this is cleared when
// running parse after an error is thrown, even by _validate or _configure.
parsed_ = 1;
_validate();
_configure();
// set the parent as nullptr as this object should be the top now
parent_ = nullptr;
parsed_ = 0;
_parse(args);
run_callback();
}
/// The real work is done here. Expects a reversed vector.
void parse(std::vector<std::string> &&args) {
// Clear if parsed
if(parsed_ > 0)
clear();
// parsed_ is incremented in commands/subcommands,
// but placed here to make sure this is cleared when
// running parse after an error is thrown, even by _validate or _configure.
parsed_ = 1;
_validate();
_configure();
// set the parent as nullptr as this object should be the top now
parent_ = nullptr;
parsed_ = 0;
_parse(std::move(args));
run_callback();
}
void parse_from_stream(std::istream &input) {
if(parsed_ == 0) {
_validate();
_configure();
// set the parent as nullptr as this object should be the top now
}
_parse_stream(input);
run_callback();
}
/// Provide a function to print a help message. The function gets access to the App pointer and error.
void failure_message(std::function<std::string(const App *, const Error &e)> function) {
failure_message_ = function;
}
/// Print a nice error message and return the exit code
int exit(const Error &e, std::ostream &out = std::cout, std::ostream &err = std::cerr) const {
/// Avoid printing anything if this is a CLI::RuntimeError
if(e.get_name() == "RuntimeError")
return e.get_exit_code();
if(e.get_name() == "CallForHelp") {
out << help();
return e.get_exit_code();
}
if(e.get_name() == "CallForAllHelp") {
out << help("", AppFormatMode::All);
return e.get_exit_code();
}
if(e.get_name() == "CallForVersion") {
out << e.what() << std::endl;
return e.get_exit_code();
}
if(e.get_exit_code() != static_cast<int>(ExitCodes::Success)) {
if(failure_message_)
err << failure_message_(this, e) << std::flush;
}
return e.get_exit_code();
}
///@}
/// @name Post parsing
///@{
/// Counts the number of times the given option was passed.
std::size_t count(std::string option_name) const { return get_option(option_name)->count(); }
/// Get a subcommand pointer list to the currently selected subcommands (after parsing by default, in command
/// line order; use parsed = false to get the original definition list.)
std::vector<App *> get_subcommands() const { return parsed_subcommands_; }
/// Get a filtered subcommand pointer list from the original definition list. An empty function will provide all
/// subcommands (const)
std::vector<const App *> get_subcommands(const std::function<bool(const App *)> &filter) const {
std::vector<const App *> subcomms(subcommands_.size());
std::transform(std::begin(subcommands_), std::end(subcommands_), std::begin(subcomms), [](const App_p &v) {
return v.get();
});
if(filter) {
subcomms.erase(std::remove_if(std::begin(subcomms),
std::end(subcomms),
[&filter](const App *app) { return !filter(app); }),
std::end(subcomms));
}
return subcomms;
}
/// Get a filtered subcommand pointer list from the original definition list. An empty function will provide all
/// subcommands
std::vector<App *> get_subcommands(const std::function<bool(App *)> &filter) {
std::vector<App *> subcomms(subcommands_.size());
std::transform(std::begin(subcommands_), std::end(subcommands_), std::begin(subcomms), [](const App_p &v) {
return v.get();
});
if(filter) {
subcomms.erase(
std::remove_if(std::begin(subcomms), std::end(subcomms), [&filter](App *app) { return !filter(app); }),
std::end(subcomms));
}
return subcomms;
}
/// Check to see if given subcommand was selected
bool got_subcommand(const App *subcom) const {
// get subcom needed to verify that this was a real subcommand
return get_subcommand(subcom)->parsed_ > 0;
}
/// Check with name instead of pointer to see if subcommand was selected
bool got_subcommand(std::string subcommand_name) const { return get_subcommand(subcommand_name)->parsed_ > 0; }
/// Sets excluded options for the subcommand
App *excludes(Option *opt) {
if(opt == nullptr) {
throw OptionNotFound("nullptr passed");
}
exclude_options_.insert(opt);
return this;
}
/// Sets excluded subcommands for the subcommand
App *excludes(App *app) {
if(app == nullptr) {
throw OptionNotFound("nullptr passed");
}
if(app == this) {
throw OptionNotFound("cannot self reference in needs");
}
auto res = exclude_subcommands_.insert(app);
// subcommand exclusion should be symmetric
if(res.second) {
app->exclude_subcommands_.insert(this);
}
return this;
}
App *needs(Option *opt) {
if(opt == nullptr) {
throw OptionNotFound("nullptr passed");
}
need_options_.insert(opt);
return this;
}
App *needs(App *app) {
if(app == nullptr) {
throw OptionNotFound("nullptr passed");
}
if(app == this) {
throw OptionNotFound("cannot self reference in needs");
}
need_subcommands_.insert(app);
return this;
}
/// Removes an option from the excludes list of this subcommand
bool remove_excludes(Option *opt) {
auto iterator = std::find(std::begin(exclude_options_), std::end(exclude_options_), opt);
if(iterator == std::end(exclude_options_)) {
return false;
}
exclude_options_.erase(iterator);
return true;
}
/// Removes a subcommand from the excludes list of this subcommand
bool remove_excludes(App *app) {
auto iterator = std::find(std::begin(exclude_subcommands_), std::end(exclude_subcommands_), app);
if(iterator == std::end(exclude_subcommands_)) {
return false;
}
auto other_app = *iterator;
exclude_subcommands_.erase(iterator);
other_app->remove_excludes(this);
return true;
}
/// Removes an option from the needs list of this subcommand
bool remove_needs(Option *opt) {
auto iterator = std::find(std::begin(need_options_), std::end(need_options_), opt);
if(iterator == std::end(need_options_)) {
return false;
}
need_options_.erase(iterator);
return true;
}
/// Removes a subcommand from the needs list of this subcommand
bool remove_needs(App *app) {
auto iterator = std::find(std::begin(need_subcommands_), std::end(need_subcommands_), app);
if(iterator == std::end(need_subcommands_)) {
return false;
}
need_subcommands_.erase(iterator);
return true;
}
///@}
/// @name Help
///@{
/// Set footer.
App *footer(std::string footer_string) {
footer_ = std::move(footer_string);
return this;
}
/// Set footer.
App *footer(std::function<std::string()> footer_function) {
footer_callback_ = std::move(footer_function);
return this;
}
/// Produce a string that could be read in as a config of the current values of the App. Set default_also to
/// include default arguments. write_descriptions will print a description for the App and for each option.
std::string config_to_str(bool default_also = false, bool write_description = false) const {
return config_formatter_->to_config(this, default_also, write_description, "");
}
/// Makes a help message, using the currently configured formatter
/// Will only do one subcommand at a time
std::string help(std::string prev = "", AppFormatMode mode = AppFormatMode::Normal) const {
if(prev.empty())
prev = get_name();
else
prev += " " + get_name();
// Delegate to subcommand if needed
auto selected_subcommands = get_subcommands();
if(!selected_subcommands.empty()) {
return selected_subcommands.at(0)->help(prev, mode);
}
return formatter_->make_help(this, prev, mode);
}
/// Displays a version string
std::string version() const {
std::string val;
if(version_ptr_ != nullptr) {
auto rv = version_ptr_->results();
version_ptr_->clear();
version_ptr_->add_result("true");
try {
version_ptr_->run_callback();
} catch(const CLI::CallForVersion &cfv) {
val = cfv.what();
}
version_ptr_->clear();
version_ptr_->add_result(rv);
}
return val;
}
///@}
/// @name Getters
///@{
/// Access the formatter
std::shared_ptr<FormatterBase> get_formatter() const { return formatter_; }
/// Access the config formatter
std::shared_ptr<Config> get_config_formatter() const { return config_formatter_; }
/// Access the config formatter as a configBase pointer
std::shared_ptr<ConfigBase> get_config_formatter_base() const {
// This is safer as a dynamic_cast if we have RTTI, as Config -> ConfigBase
#if CLI11_USE_STATIC_RTTI == 0
return std::dynamic_pointer_cast<ConfigBase>(config_formatter_);
#else
return std::static_pointer_cast<ConfigBase>(config_formatter_);
#endif
}
/// Get the app or subcommand description
std::string get_description() const { return description_; }
/// Set the description of the app
App *description(std::string app_description) {
description_ = std::move(app_description);
return this;
}
/// Get the list of options (user facing function, so returns raw pointers), has optional filter function
std::vector<const Option *> get_options(const std::function<bool(const Option *)> filter = {}) const {
std::vector<const Option *> options(options_.size());
std::transform(std::begin(options_), std::end(options_), std::begin(options), [](const Option_p &val) {
return val.get();
});
if(filter) {
options.erase(std::remove_if(std::begin(options),
std::end(options),
[&filter](const Option *opt) { return !filter(opt); }),
std::end(options));
}
return options;
}
/// Non-const version of the above
std::vector<Option *> get_options(const std::function<bool(Option *)> filter = {}) {
std::vector<Option *> options(options_.size());
std::transform(std::begin(options_), std::end(options_), std::begin(options), [](const Option_p &val) {
return val.get();
});
if(filter) {
options.erase(
std::remove_if(std::begin(options), std::end(options), [&filter](Option *opt) { return !filter(opt); }),
std::end(options));
}
return options;
}
/// Get an option by name (noexcept non-const version)
Option *get_option_no_throw(std::string option_name) noexcept {
for(Option_p &opt : options_) {
if(opt->check_name(option_name)) {
return opt.get();
}
}
for(auto &subc : subcommands_) {
// also check down into nameless subcommands
if(subc->get_name().empty()) {
auto opt = subc->get_option_no_throw(option_name);
if(opt != nullptr) {
return opt;
}
}
}
return nullptr;
}
/// Get an option by name (noexcept const version)
const Option *get_option_no_throw(std::string option_name) const noexcept {
for(const Option_p &opt : options_) {
if(opt->check_name(option_name)) {
return opt.get();
}
}
for(const auto &subc : subcommands_) {
// also check down into nameless subcommands
if(subc->get_name().empty()) {
auto opt = subc->get_option_no_throw(option_name);
if(opt != nullptr) {
return opt;
}
}
}
return nullptr;
}
/// Get an option by name
const Option *get_option(std::string option_name) const {
auto opt = get_option_no_throw(option_name);
if(opt == nullptr) {
throw OptionNotFound(option_name);
}
return opt;
}
/// Get an option by name (non-const version)
Option *get_option(std::string option_name) {
auto opt = get_option_no_throw(option_name);
if(opt == nullptr) {
throw OptionNotFound(option_name);
}
return opt;
}
/// Shortcut bracket operator for getting a pointer to an option
const Option *operator[](const std::string &option_name) const { return get_option(option_name); }
/// Shortcut bracket operator for getting a pointer to an option
const Option *operator[](const char *option_name) const { return get_option(option_name); }
/// Check the status of ignore_case
bool get_ignore_case() const { return ignore_case_; }
/// Check the status of ignore_underscore
bool get_ignore_underscore() const { return ignore_underscore_; }
/// Check the status of fallthrough
bool get_fallthrough() const { return fallthrough_; }
/// Check the status of the allow windows style options
bool get_allow_windows_style_options() const { return allow_windows_style_options_; }
/// Check the status of the allow windows style options
bool get_positionals_at_end() const { return positionals_at_end_; }
/// Check the status of the allow windows style options
bool get_configurable() const { return configurable_; }
/// Get the group of this subcommand
const std::string &get_group() const { return group_; }
/// Generate and return the footer.
std::string get_footer() const { return (footer_callback_) ? footer_callback_() + '\n' + footer_ : footer_; }
/// Get the required min subcommand value
std::size_t get_require_subcommand_min() const { return require_subcommand_min_; }
/// Get the required max subcommand value
std::size_t get_require_subcommand_max() const { return require_subcommand_max_; }
/// Get the required min option value
std::size_t get_require_option_min() const { return require_option_min_; }
/// Get the required max option value
std::size_t get_require_option_max() const { return require_option_max_; }
/// Get the prefix command status
bool get_prefix_command() const { return prefix_command_; }
/// Get the status of allow extras
bool get_allow_extras() const { return allow_extras_; }
/// Get the status of required
bool get_required() const { return required_; }
/// Get the status of disabled
bool get_disabled() const { return disabled_; }
/// Get the status of silence
bool get_silent() const { return silent_; }
/// Get the status of disabled
bool get_immediate_callback() const { return immediate_callback_; }
/// Get the status of disabled by default
bool get_disabled_by_default() const { return (default_startup == startup_mode::disabled); }
/// Get the status of disabled by default
bool get_enabled_by_default() const { return (default_startup == startup_mode::enabled); }
/// Get the status of validating positionals
bool get_validate_positionals() const { return validate_positionals_; }
/// Get the status of validating optional vector arguments
bool get_validate_optional_arguments() const { return validate_optional_arguments_; }
/// Get the status of allow extras
config_extras_mode get_allow_config_extras() const { return allow_config_extras_; }
/// Get a pointer to the help flag.
Option *get_help_ptr() { return help_ptr_; }
/// Get a pointer to the help flag. (const)
const Option *get_help_ptr() const { return help_ptr_; }
/// Get a pointer to the help all flag. (const)
const Option *get_help_all_ptr() const { return help_all_ptr_; }
/// Get a pointer to the config option.
Option *get_config_ptr() { return config_ptr_; }
/// Get a pointer to the config option. (const)
const Option *get_config_ptr() const { return config_ptr_; }
/// Get a pointer to the version option.
Option *get_version_ptr() { return version_ptr_; }
/// Get a pointer to the version option. (const)
const Option *get_version_ptr() const { return version_ptr_; }
/// Get the parent of this subcommand (or nullptr if main app)
App *get_parent() { return parent_; }
/// Get the parent of this subcommand (or nullptr if main app) (const version)
const App *get_parent() const { return parent_; }
/// Get the name of the current app
const std::string &get_name() const { return name_; }
/// Get the aliases of the current app
const std::vector<std::string> &get_aliases() const { return aliases_; }
/// clear all the aliases of the current App
App *clear_aliases() {
aliases_.clear();
return this;
}
/// Get a display name for an app
std::string get_display_name(bool with_aliases = false) const {
if(name_.empty()) {
return std::string("[Option Group: ") + get_group() + "]";
}
if(aliases_.empty() || !with_aliases) {
return name_;
}
std::string dispname = name_;
for(const auto &lalias : aliases_) {
dispname.push_back(',');
dispname.push_back(' ');
dispname.append(lalias);
}
return dispname;
}
/// Check the name, case insensitive and underscore insensitive if set
bool check_name(std::string name_to_check) const {
std::string local_name = name_;
if(ignore_underscore_) {
local_name = detail::remove_underscore(name_);
name_to_check = detail::remove_underscore(name_to_check);
}
if(ignore_case_) {
local_name = detail::to_lower(name_);
name_to_check = detail::to_lower(name_to_check);
}
if(local_name == name_to_check) {
return true;
}
for(auto les : aliases_) {
if(ignore_underscore_) {
les = detail::remove_underscore(les);
}
if(ignore_case_) {
les = detail::to_lower(les);
}
if(les == name_to_check) {
return true;
}
}
return false;
}
/// Get the groups available directly from this option (in order)
std::vector<std::string> get_groups() const {
std::vector<std::string> groups;
for(const Option_p &opt : options_) {
// Add group if it is not already in there
if(std::find(groups.begin(), groups.end(), opt->get_group()) == groups.end()) {
groups.push_back(opt->get_group());
}
}
return groups;
}
/// This gets a vector of pointers with the original parse order
const std::vector<Option *> &parse_order() const { return parse_order_; }
/// This returns the missing options from the current subcommand
std::vector<std::string> remaining(bool recurse = false) const {
std::vector<std::string> miss_list;
for(const std::pair<detail::Classifier, std::string> &miss : missing_) {
miss_list.push_back(std::get<1>(miss));
}
// Get from a subcommand that may allow extras
if(recurse) {
if(!allow_extras_) {
for(const auto &sub : subcommands_) {
if(sub->name_.empty() && !sub->missing_.empty()) {
for(const std::pair<detail::Classifier, std::string> &miss : sub->missing_) {
miss_list.push_back(std::get<1>(miss));
}
}
}
}
// Recurse into subcommands
for(const App *sub : parsed_subcommands_) {
std::vector<std::string> output = sub->remaining(recurse);
std::copy(std::begin(output), std::end(output), std::back_inserter(miss_list));
}
}
return miss_list;
}
/// This returns the missing options in a form ready for processing by another command line program
std::vector<std::string> remaining_for_passthrough(bool recurse = false) const {
std::vector<std::string> miss_list = remaining(recurse);
std::reverse(std::begin(miss_list), std::end(miss_list));
return miss_list;
}
/// This returns the number of remaining options, minus the -- separator
std::size_t remaining_size(bool recurse = false) const {
auto remaining_options = static_cast<std::size_t>(std::count_if(
std::begin(missing_), std::end(missing_), [](const std::pair<detail::Classifier, std::string> &val) {
return val.first != detail::Classifier::POSITIONAL_MARK;
}));
if(recurse) {
for(const App_p &sub : subcommands_) {
remaining_options += sub->remaining_size(recurse);
}
}
return remaining_options;
}
///@}
protected:
/// Check the options to make sure there are no conflicts.
///
/// Currently checks to see if multiple positionals exist with unlimited args and checks if the min and max options
/// are feasible
void _validate() const {
// count the number of positional only args
auto pcount = std::count_if(std::begin(options_), std::end(options_), [](const Option_p &opt) {
return opt->get_items_expected_max() >= detail::expected_max_vector_size && !opt->nonpositional();
});
if(pcount > 1) {
auto pcount_req = std::count_if(std::begin(options_), std::end(options_), [](const Option_p &opt) {
return opt->get_items_expected_max() >= detail::expected_max_vector_size && !opt->nonpositional() &&
opt->get_required();
});
if(pcount - pcount_req > 1) {
throw InvalidError(name_);
}
}
std::size_t nameless_subs{0};
for(const App_p &app : subcommands_) {
app->_validate();
if(app->get_name().empty())
++nameless_subs;
}
if(require_option_min_ > 0) {
if(require_option_max_ > 0) {
if(require_option_max_ < require_option_min_) {
throw(InvalidError("Required min options greater than required max options",
ExitCodes::InvalidError));
}
}
if(require_option_min_ > (options_.size() + nameless_subs)) {
throw(InvalidError("Required min options greater than number of available options",
ExitCodes::InvalidError));
}
}
}
/// configure subcommands to enable parsing through the current object
/// set the correct fallthrough and prefix for nameless subcommands and manage the automatic enable or disable
/// makes sure parent is set correctly
void _configure() {
if(default_startup == startup_mode::enabled) {
disabled_ = false;
} else if(default_startup == startup_mode::disabled) {
disabled_ = true;
}
for(const App_p &app : subcommands_) {
if(app->has_automatic_name_) {
app->name_.clear();
}
if(app->name_.empty()) {
app->fallthrough_ = false; // make sure fallthrough_ is false to prevent infinite loop
app->prefix_command_ = false;
}
// make sure the parent is set to be this object in preparation for parse
app->parent_ = this;
app->_configure();
}
}
/// Internal function to run (App) callback, bottom up
void run_callback(bool final_mode = false, bool suppress_final_callback = false) {
pre_callback();
// in the main app if immediate_callback_ is set it runs the main callback before the used subcommands
if(!final_mode && parse_complete_callback_) {
parse_complete_callback_();
}
// run the callbacks for the received subcommands
for(App *subc : get_subcommands()) {
if(subc->parent_ == this) {
subc->run_callback(true, suppress_final_callback);
}
}
// now run callbacks for option_groups
for(auto &subc : subcommands_) {
if(subc->name_.empty() && subc->count_all() > 0) {
subc->run_callback(true, suppress_final_callback);
}
}
// finally run the main callback
if(final_callback_ && (parsed_ > 0) && (!suppress_final_callback)) {
if(!name_.empty() || count_all() > 0 || parent_ == nullptr) {
final_callback_();
}
}
}
/// Check to see if a subcommand is valid. Give up immediately if subcommand max has been reached.
bool _valid_subcommand(const std::string ¤t, bool ignore_used = true) const {
// Don't match if max has been reached - but still check parents
if(require_subcommand_max_ != 0 && parsed_subcommands_.size() >= require_subcommand_max_) {
return parent_ != nullptr && parent_->_valid_subcommand(current, ignore_used);
}
auto com = _find_subcommand(current, true, ignore_used);
if(com != nullptr) {
return true;
}
// Check parent if exists, else return false
return parent_ != nullptr && parent_->_valid_subcommand(current, ignore_used);
}
/// Selects a Classifier enum based on the type of the current argument
detail::Classifier _recognize(const std::string ¤t, bool ignore_used_subcommands = true) const {
std::string dummy1, dummy2;
if(current == "--")
return detail::Classifier::POSITIONAL_MARK;
if(_valid_subcommand(current, ignore_used_subcommands))
return detail::Classifier::SUBCOMMAND;
if(detail::split_long(current, dummy1, dummy2))
return detail::Classifier::LONG;
if(detail::split_short(current, dummy1, dummy2)) {
if(dummy1[0] >= '0' && dummy1[0] <= '9') {
if(get_option_no_throw(std::string{'-', dummy1[0]}) == nullptr) {
return detail::Classifier::NONE;
}
}
return detail::Classifier::SHORT;
}
if((allow_windows_style_options_) && (detail::split_windows_style(current, dummy1, dummy2)))
return detail::Classifier::WINDOWS_STYLE;
if((current == "++") && !name_.empty() && parent_ != nullptr)
return detail::Classifier::SUBCOMMAND_TERMINATOR;
return detail::Classifier::NONE;
}
// The parse function is now broken into several parts, and part of process
/// Read and process a configuration file (main app only)
void _process_config_file() {
if(config_ptr_ != nullptr) {
bool config_required = config_ptr_->get_required();
auto file_given = config_ptr_->count() > 0;
auto config_files = config_ptr_->as<std::vector<std::string>>();
if(config_files.empty() || config_files.front().empty()) {
if(config_required) {
throw FileError::Missing("no specified config file");
}
return;
}
for(auto rit = config_files.rbegin(); rit != config_files.rend(); ++rit) {
const auto &config_file = *rit;
auto path_result = detail::check_path(config_file.c_str());
if(path_result == detail::path_type::file) {
try {
std::vector<ConfigItem> values = config_formatter_->from_file(config_file);
_parse_config(values);
if(!file_given) {
config_ptr_->add_result(config_file);
}
} catch(const FileError &) {
if(config_required || file_given)
throw;
}
} else if(config_required || file_given) {
throw FileError::Missing(config_file);
}
}
}
}
/// Get envname options if not yet passed. Runs on *all* subcommands.
void _process_env() {
for(const Option_p &opt : options_) {
if(opt->count() == 0 && !opt->envname_.empty()) {
char *buffer = nullptr;
std::string ename_string;
#ifdef _MSC_VER
// Windows version
std::size_t sz = 0;
if(_dupenv_s(&buffer, &sz, opt->envname_.c_str()) == 0 && buffer != nullptr) {
ename_string = std::string(buffer);
free(buffer);
}
#else
// This also works on Windows, but gives a warning
buffer = std::getenv(opt->envname_.c_str());
if(buffer != nullptr)
ename_string = std::string(buffer);
#endif
if(!ename_string.empty()) {
opt->add_result(ename_string);
}
}
}
for(App_p &sub : subcommands_) {
if(sub->get_name().empty() || !sub->parse_complete_callback_)
sub->_process_env();
}
}
/// Process callbacks. Runs on *all* subcommands.
void _process_callbacks() {
for(App_p &sub : subcommands_) {
// process the priority option_groups first
if(sub->get_name().empty() && sub->parse_complete_callback_) {
if(sub->count_all() > 0) {
sub->_process_callbacks();
sub->run_callback();
}
}
}
for(const Option_p &opt : options_) {
if((*opt) && !opt->get_callback_run()) {
opt->run_callback();
}
}
for(App_p &sub : subcommands_) {
if(!sub->parse_complete_callback_) {
sub->_process_callbacks();
}
}
}
/// Run help flag processing if any are found.
///
/// The flags allow recursive calls to remember if there was a help flag on a parent.
void _process_help_flags(bool trigger_help = false, bool trigger_all_help = false) const {
const Option *help_ptr = get_help_ptr();
const Option *help_all_ptr = get_help_all_ptr();
if(help_ptr != nullptr && help_ptr->count() > 0)
trigger_help = true;
if(help_all_ptr != nullptr && help_all_ptr->count() > 0)
trigger_all_help = true;
// If there were parsed subcommands, call those. First subcommand wins if there are multiple ones.
if(!parsed_subcommands_.empty()) {
for(const App *sub : parsed_subcommands_)
sub->_process_help_flags(trigger_help, trigger_all_help);
// Only the final subcommand should call for help. All help wins over help.
} else if(trigger_all_help) {
throw CallForAllHelp();
} else if(trigger_help) {
throw CallForHelp();
}
}
/// Verify required options and cross requirements. Subcommands too (only if selected).
void _process_requirements() {
// check excludes
bool excluded{false};
std::string excluder;
for(auto &opt : exclude_options_) {
if(opt->count() > 0) {
excluded = true;
excluder = opt->get_name();
}
}
for(auto &subc : exclude_subcommands_) {
if(subc->count_all() > 0) {
excluded = true;
excluder = subc->get_display_name();
}
}
if(excluded) {
if(count_all() > 0) {
throw ExcludesError(get_display_name(), excluder);
}
// if we are excluded but didn't receive anything, just return
return;
}
// check excludes
bool missing_needed{false};
std::string missing_need;
for(auto &opt : need_options_) {
if(opt->count() == 0) {
missing_needed = true;
missing_need = opt->get_name();
}
}
for(auto &subc : need_subcommands_) {
if(subc->count_all() == 0) {
missing_needed = true;
missing_need = subc->get_display_name();
}
}
if(missing_needed) {
if(count_all() > 0) {
throw RequiresError(get_display_name(), missing_need);
}
// if we missing something but didn't have any options, just return
return;
}
std::size_t used_options = 0;
for(const Option_p &opt : options_) {
if(opt->count() != 0) {
++used_options;
}
// Required but empty
if(opt->get_required() && opt->count() == 0) {
throw RequiredError(opt->get_name());
}
// Requires
for(const Option *opt_req : opt->needs_)
if(opt->count() > 0 && opt_req->count() == 0)
throw RequiresError(opt->get_name(), opt_req->get_name());
// Excludes
for(const Option *opt_ex : opt->excludes_)
if(opt->count() > 0 && opt_ex->count() != 0)
throw ExcludesError(opt->get_name(), opt_ex->get_name());
}
// check for the required number of subcommands
if(require_subcommand_min_ > 0) {
auto selected_subcommands = get_subcommands();
if(require_subcommand_min_ > selected_subcommands.size())
throw RequiredError::Subcommand(require_subcommand_min_);
}
// Max error cannot occur, the extra subcommand will parse as an ExtrasError or a remaining item.
// run this loop to check how many unnamed subcommands were actually used since they are considered options
// from the perspective of an App
for(App_p &sub : subcommands_) {
if(sub->disabled_)
continue;
if(sub->name_.empty() && sub->count_all() > 0) {
++used_options;
}
}
if(require_option_min_ > used_options || (require_option_max_ > 0 && require_option_max_ < used_options)) {
auto option_list = detail::join(options_, [this](const Option_p &ptr) {
if(ptr.get() == help_ptr_ || ptr.get() == help_all_ptr_) {
return std::string{};
}
return ptr->get_name(false, true);
});
auto subc_list = get_subcommands([](App *app) { return ((app->get_name().empty()) && (!app->disabled_)); });
if(!subc_list.empty()) {
option_list += "," + detail::join(subc_list, [](const App *app) { return app->get_display_name(); });
}
throw RequiredError::Option(require_option_min_, require_option_max_, used_options, option_list);
}
// now process the requirements for subcommands if needed
for(App_p &sub : subcommands_) {
if(sub->disabled_)
continue;
if(sub->name_.empty() && sub->required_ == false) {
if(sub->count_all() == 0) {
if(require_option_min_ > 0 && require_option_min_ <= used_options) {
continue;
// if we have met the requirement and there is nothing in this option group skip checking
// requirements
}
if(require_option_max_ > 0 && used_options >= require_option_min_) {
continue;
// if we have met the requirement and there is nothing in this option group skip checking
// requirements
}
}
}
if(sub->count() > 0 || sub->name_.empty()) {
sub->_process_requirements();
}
if(sub->required_ && sub->count_all() == 0) {
throw(CLI::RequiredError(sub->get_display_name()));
}
}
}
/// Process callbacks and such.
void _process() {
try {
// the config file might generate a FileError but that should not be processed until later in the process
// to allow for help, version and other errors to generate first.
_process_config_file();
// process env shouldn't throw but no reason to process it if config generated an error
_process_env();
} catch(const CLI::FileError &) {
// callbacks and help_flags can generate exceptions which should take priority
// over the config file error if one exists.
_process_callbacks();
_process_help_flags();
throw;
}
_process_callbacks();
_process_help_flags();
_process_requirements();
}
/// Throw an error if anything is left over and should not be.
void _process_extras() {
if(!(allow_extras_ || prefix_command_)) {
std::size_t num_left_over = remaining_size();
if(num_left_over > 0) {
throw ExtrasError(name_, remaining(false));
}
}
for(App_p &sub : subcommands_) {
if(sub->count() > 0)
sub->_process_extras();
}
}
/// Throw an error if anything is left over and should not be.
/// Modifies the args to fill in the missing items before throwing.
void _process_extras(std::vector<std::string> &args) {
if(!(allow_extras_ || prefix_command_)) {
std::size_t num_left_over = remaining_size();
if(num_left_over > 0) {
args = remaining(false);
throw ExtrasError(name_, args);
}
}
for(App_p &sub : subcommands_) {
if(sub->count() > 0)
sub->_process_extras(args);
}
}
/// Internal function to recursively increment the parsed counter on the current app as well unnamed subcommands
void increment_parsed() {
++parsed_;
for(App_p &sub : subcommands_) {
if(sub->get_name().empty())
sub->increment_parsed();
}
}
/// Internal parse function
void _parse(std::vector<std::string> &args) {
increment_parsed();
_trigger_pre_parse(args.size());
bool positional_only = false;
while(!args.empty()) {
if(!_parse_single(args, positional_only)) {
break;
}
}
if(parent_ == nullptr) {
_process();
// Throw error if any items are left over (depending on settings)
_process_extras(args);
// Convert missing (pairs) to extras (string only) ready for processing in another app
args = remaining_for_passthrough(false);
} else if(parse_complete_callback_) {
_process_env();
_process_callbacks();
_process_help_flags();
_process_requirements();
run_callback(false, true);
}
}
/// Internal parse function
void _parse(std::vector<std::string> &&args) {
// this can only be called by the top level in which case parent == nullptr by definition
// operation is simplified
increment_parsed();
_trigger_pre_parse(args.size());
bool positional_only = false;
while(!args.empty()) {
_parse_single(args, positional_only);
}
_process();
// Throw error if any items are left over (depending on settings)
_process_extras();
}
/// Internal function to parse a stream
void _parse_stream(std::istream &input) {
auto values = config_formatter_->from_config(input);
_parse_config(values);
increment_parsed();
_trigger_pre_parse(values.size());
_process();
// Throw error if any items are left over (depending on settings)
_process_extras();
}
/// Parse one config param, return false if not found in any subcommand, remove if it is
///
/// If this has more than one dot.separated.name, go into the subcommand matching it
/// Returns true if it managed to find the option, if false you'll need to remove the arg manually.
void _parse_config(const std::vector<ConfigItem> &args) {
for(const ConfigItem &item : args) {
if(!_parse_single_config(item) && allow_config_extras_ == config_extras_mode::error)
throw ConfigError::Extras(item.fullname());
}
}
/// Fill in a single config option
bool _parse_single_config(const ConfigItem &item, std::size_t level = 0) {
if(level < item.parents.size()) {
try {
auto subcom = get_subcommand(item.parents.at(level));
auto result = subcom->_parse_single_config(item, level + 1);
return result;
} catch(const OptionNotFound &) {
return false;
}
}
// check for section open
if(item.name == "++") {
if(configurable_) {
increment_parsed();
_trigger_pre_parse(2);
if(parent_ != nullptr) {
parent_->parsed_subcommands_.push_back(this);
}
}
return true;
}
// check for section close
if(item.name == "--") {
if(configurable_) {
_process_callbacks();
_process_requirements();
run_callback();
}
return true;
}
Option *op = get_option_no_throw("--" + item.name);
if(op == nullptr) {
if(item.name.size() == 1) {
op = get_option_no_throw("-" + item.name);
}
}
if(op == nullptr) {
op = get_option_no_throw(item.name);
}
if(op == nullptr) {
// If the option was not present
if(get_allow_config_extras() == config_extras_mode::capture)
// Should we worry about classifying the extras properly?
missing_.emplace_back(detail::Classifier::NONE, item.fullname());
return false;
}
if(!op->get_configurable()) {
if(get_allow_config_extras() == config_extras_mode::ignore_all) {
return false;
}
throw ConfigError::NotConfigurable(item.fullname());
}
if(op->empty()) {
if(op->get_expected_min() == 0) {
// Flag parsing
auto res = config_formatter_->to_flag(item);
res = op->get_flag_value(item.name, res);
op->add_result(res);
} else {
op->add_result(item.inputs);
op->run_callback();
}
}
return true;
}
/// Parse "one" argument (some may eat more than one), delegate to parent if fails, add to missing if missing
/// from main return false if the parse has failed and needs to return to parent
bool _parse_single(std::vector<std::string> &args, bool &positional_only) {
bool retval = true;
detail::Classifier classifier = positional_only ? detail::Classifier::NONE : _recognize(args.back());
switch(classifier) {
case detail::Classifier::POSITIONAL_MARK:
args.pop_back();
positional_only = true;
if((!_has_remaining_positionals()) && (parent_ != nullptr)) {
retval = false;
} else {
_move_to_missing(classifier, "--");
}
break;
case detail::Classifier::SUBCOMMAND_TERMINATOR:
// treat this like a positional mark if in the parent app
args.pop_back();
retval = false;
break;
case detail::Classifier::SUBCOMMAND:
retval = _parse_subcommand(args);
break;
case detail::Classifier::LONG:
case detail::Classifier::SHORT:
case detail::Classifier::WINDOWS_STYLE:
// If already parsed a subcommand, don't accept options_
_parse_arg(args, classifier);
break;
case detail::Classifier::NONE:
// Probably a positional or something for a parent (sub)command
retval = _parse_positional(args, false);
if(retval && positionals_at_end_) {
positional_only = true;
}
break;
// LCOV_EXCL_START
default:
throw HorribleError("unrecognized classifier (you should not see this!)");
// LCOV_EXCL_STOP
}
return retval;
}
/// Count the required remaining positional arguments
std::size_t _count_remaining_positionals(bool required_only = false) const {
std::size_t retval = 0;
for(const Option_p &opt : options_) {
if(opt->get_positional() && (!required_only || opt->get_required())) {
if(opt->get_items_expected_min() > 0 &&
static_cast<int>(opt->count()) < opt->get_items_expected_min()) {
retval += static_cast<std::size_t>(opt->get_items_expected_min()) - opt->count();
}
}
}
return retval;
}
/// Count the required remaining positional arguments
bool _has_remaining_positionals() const {
for(const Option_p &opt : options_) {
if(opt->get_positional() && ((static_cast<int>(opt->count()) < opt->get_items_expected_min()))) {
return true;
}
}
return false;
}
/// Parse a positional, go up the tree to check
/// @param haltOnSubcommand if set to true the operation will not process subcommands merely return false
/// Return true if the positional was used false otherwise
bool _parse_positional(std::vector<std::string> &args, bool haltOnSubcommand) {
const std::string &positional = args.back();
if(positionals_at_end_) {
// deal with the case of required arguments at the end which should take precedence over other arguments
auto arg_rem = args.size();
auto remreq = _count_remaining_positionals(true);
if(arg_rem <= remreq) {
for(const Option_p &opt : options_) {
if(opt->get_positional() && opt->required_) {
if(static_cast<int>(opt->count()) < opt->get_items_expected_min()) {
if(validate_positionals_) {
std::string pos = positional;
pos = opt->_validate(pos, 0);
if(!pos.empty()) {
continue;
}
}
parse_order_.push_back(opt.get());
/// if we require a separator add it here
if(opt->get_inject_separator()) {
if(!opt->results().empty() && !opt->results().back().empty()) {
opt->add_result(std::string{});
}
}
if(opt->get_trigger_on_parse() &&
opt->current_option_state_ == Option::option_state::callback_run) {
opt->clear();
}
opt->add_result(positional);
if(opt->get_trigger_on_parse()) {
opt->run_callback();
}
args.pop_back();
return true;
}
}
}
}
}
for(const Option_p &opt : options_) {
// Eat options, one by one, until done
if(opt->get_positional() &&
(static_cast<int>(opt->count()) < opt->get_items_expected_min() || opt->get_allow_extra_args())) {
if(validate_positionals_) {
std::string pos = positional;
pos = opt->_validate(pos, 0);
if(!pos.empty()) {
continue;
}
}
if(opt->get_inject_separator()) {
if(!opt->results().empty() && !opt->results().back().empty()) {
opt->add_result(std::string{});
}
}
if(opt->get_trigger_on_parse() && opt->current_option_state_ == Option::option_state::callback_run) {
opt->clear();
}
opt->add_result(positional);
if(opt->get_trigger_on_parse()) {
opt->run_callback();
}
parse_order_.push_back(opt.get());
args.pop_back();
return true;
}
}
for(auto &subc : subcommands_) {
if((subc->name_.empty()) && (!subc->disabled_)) {
if(subc->_parse_positional(args, false)) {
if(!subc->pre_parse_called_) {
subc->_trigger_pre_parse(args.size());
}
return true;
}
}
}
// let the parent deal with it if possible
if(parent_ != nullptr && fallthrough_)
return _get_fallthrough_parent()->_parse_positional(args, static_cast<bool>(parse_complete_callback_));
/// Try to find a local subcommand that is repeated
auto com = _find_subcommand(args.back(), true, false);
if(com != nullptr && (require_subcommand_max_ == 0 || require_subcommand_max_ > parsed_subcommands_.size())) {
if(haltOnSubcommand) {
return false;
}
args.pop_back();
com->_parse(args);
return true;
}
/// now try one last gasp at subcommands that have been executed before, go to root app and try to find a
/// subcommand in a broader way, if one exists let the parent deal with it
auto parent_app = (parent_ != nullptr) ? _get_fallthrough_parent() : this;
com = parent_app->_find_subcommand(args.back(), true, false);
if(com != nullptr && (com->parent_->require_subcommand_max_ == 0 ||
com->parent_->require_subcommand_max_ > com->parent_->parsed_subcommands_.size())) {
return false;
}
if(positionals_at_end_) {
throw CLI::ExtrasError(name_, args);
}
/// If this is an option group don't deal with it
if(parent_ != nullptr && name_.empty()) {
return false;
}
/// We are out of other options this goes to missing
_move_to_missing(detail::Classifier::NONE, positional);
args.pop_back();
if(prefix_command_) {
while(!args.empty()) {
_move_to_missing(detail::Classifier::NONE, args.back());
args.pop_back();
}
}
return true;
}
/// Locate a subcommand by name with two conditions, should disabled subcommands be ignored, and should used
/// subcommands be ignored
App *_find_subcommand(const std::string &subc_name, bool ignore_disabled, bool ignore_used) const noexcept {
for(const App_p &com : subcommands_) {
if(com->disabled_ && ignore_disabled)
continue;
if(com->get_name().empty()) {
auto subc = com->_find_subcommand(subc_name, ignore_disabled, ignore_used);
if(subc != nullptr) {
return subc;
}
}
if(com->check_name(subc_name)) {
if((!*com) || !ignore_used)
return com.get();
}
}
return nullptr;
}
/// Parse a subcommand, modify args and continue
///
/// Unlike the others, this one will always allow fallthrough
/// return true if the subcommand was processed false otherwise
bool _parse_subcommand(std::vector<std::string> &args) {
if(_count_remaining_positionals(/* required */ true) > 0) {
_parse_positional(args, false);
return true;
}
auto com = _find_subcommand(args.back(), true, true);
if(com != nullptr) {
args.pop_back();
if(!com->silent_) {
parsed_subcommands_.push_back(com);
}
com->_parse(args);
auto parent_app = com->parent_;
while(parent_app != this) {
parent_app->_trigger_pre_parse(args.size());
if(!com->silent_) {
parent_app->parsed_subcommands_.push_back(com);
}
parent_app = parent_app->parent_;
}
return true;
}
if(parent_ == nullptr)
throw HorribleError("Subcommand " + args.back() + " missing");
return false;
}
/// Parse a short (false) or long (true) argument, must be at the top of the list
/// return true if the argument was processed or false if nothing was done
bool _parse_arg(std::vector<std::string> &args, detail::Classifier current_type) {
std::string current = args.back();
std::string arg_name;
std::string value;
std::string rest;
switch(current_type) {
case detail::Classifier::LONG:
if(!detail::split_long(current, arg_name, value))
throw HorribleError("Long parsed but missing (you should not see this):" + args.back());
break;
case detail::Classifier::SHORT:
if(!detail::split_short(current, arg_name, rest))
throw HorribleError("Short parsed but missing! You should not see this");
break;
case detail::Classifier::WINDOWS_STYLE:
if(!detail::split_windows_style(current, arg_name, value))
throw HorribleError("windows option parsed but missing! You should not see this");
break;
case detail::Classifier::SUBCOMMAND:
case detail::Classifier::SUBCOMMAND_TERMINATOR:
case detail::Classifier::POSITIONAL_MARK:
case detail::Classifier::NONE:
default:
throw HorribleError("parsing got called with invalid option! You should not see this");
}
auto op_ptr =
std::find_if(std::begin(options_), std::end(options_), [arg_name, current_type](const Option_p &opt) {
if(current_type == detail::Classifier::LONG)
return opt->check_lname(arg_name);
if(current_type == detail::Classifier::SHORT)
return opt->check_sname(arg_name);
// this will only get called for detail::Classifier::WINDOWS_STYLE
return opt->check_lname(arg_name) || opt->check_sname(arg_name);
});
// Option not found
if(op_ptr == std::end(options_)) {
for(auto &subc : subcommands_) {
if(subc->name_.empty() && !subc->disabled_) {
if(subc->_parse_arg(args, current_type)) {
if(!subc->pre_parse_called_) {
subc->_trigger_pre_parse(args.size());
}
return true;
}
}
}
// don't capture missing if this is a nameless subcommand and nameless subcommands can't fallthrough
if(parent_ != nullptr && name_.empty()) {
return false;
}
// If a subcommand, try the main command
if(parent_ != nullptr && fallthrough_)
return _get_fallthrough_parent()->_parse_arg(args, current_type);
// Otherwise, add to missing
args.pop_back();
_move_to_missing(current_type, current);
return true;
}
args.pop_back();
// Get a reference to the pointer to make syntax bearable
Option_p &op = *op_ptr;
/// if we require a separator add it here
if(op->get_inject_separator()) {
if(!op->results().empty() && !op->results().back().empty()) {
op->add_result(std::string{});
}
}
if(op->get_trigger_on_parse() && op->current_option_state_ == Option::option_state::callback_run) {
op->clear();
}
int min_num = (std::min)(op->get_type_size_min(), op->get_items_expected_min());
int max_num = op->get_items_expected_max();
// check container like options to limit the argument size to a single type if the allow_extra_flags argument is
// set. 16 is somewhat arbitrary (needs to be at least 4)
if(max_num >= detail::expected_max_vector_size / 16 && !op->get_allow_extra_args()) {
auto tmax = op->get_type_size_max();
max_num = detail::checked_multiply(tmax, op->get_expected_min()) ? tmax : detail::expected_max_vector_size;
}
// Make sure we always eat the minimum for unlimited vectors
int collected = 0; // total number of arguments collected
int result_count = 0; // local variable for number of results in a single arg string
// deal with purely flag like things
if(max_num == 0) {
auto res = op->get_flag_value(arg_name, value);
op->add_result(res);
parse_order_.push_back(op.get());
} else if(!value.empty()) { // --this=value
op->add_result(value, result_count);
parse_order_.push_back(op.get());
collected += result_count;
// -Trest
} else if(!rest.empty()) {
op->add_result(rest, result_count);
parse_order_.push_back(op.get());
rest = "";
collected += result_count;
}
// gather the minimum number of arguments
while(min_num > collected && !args.empty()) {
std::string current_ = args.back();
args.pop_back();
op->add_result(current_, result_count);
parse_order_.push_back(op.get());
collected += result_count;
}
if(min_num > collected) { // if we have run out of arguments and the minimum was not met
throw ArgumentMismatch::TypedAtLeast(op->get_name(), min_num, op->get_type_name());
}
// now check for optional arguments
if(max_num > collected || op->get_allow_extra_args()) { // we allow optional arguments
auto remreqpos = _count_remaining_positionals(true);
// we have met the minimum now optionally check up to the maximum
while((collected < max_num || op->get_allow_extra_args()) && !args.empty() &&
_recognize(args.back(), false) == detail::Classifier::NONE) {
// If any required positionals remain, don't keep eating
if(remreqpos >= args.size()) {
break;
}
if(validate_optional_arguments_) {
std::string optarg = args.back();
optarg = op->_validate(optarg, 0);
if(!optarg.empty()) {
break;
}
}
op->add_result(args.back(), result_count);
parse_order_.push_back(op.get());
args.pop_back();
collected += result_count;
}
// Allow -- to end an unlimited list and "eat" it
if(!args.empty() && _recognize(args.back()) == detail::Classifier::POSITIONAL_MARK)
args.pop_back();
// optional flag that didn't receive anything now get the default value
if(min_num == 0 && max_num > 0 && collected == 0) {
auto res = op->get_flag_value(arg_name, std::string{});
op->add_result(res);
parse_order_.push_back(op.get());
}
}
// if we only partially completed a type then add an empty string if allowed for later processing
if(min_num > 0 && (collected % op->get_type_size_max()) != 0) {
if(op->get_type_size_max() != op->get_type_size_min()) {
op->add_result(std::string{});
} else {
throw ArgumentMismatch::PartialType(op->get_name(), op->get_type_size_min(), op->get_type_name());
}
}
if(op->get_trigger_on_parse()) {
op->run_callback();
}
if(!rest.empty()) {
rest = "-" + rest;
args.push_back(rest);
}
return true;
}
/// Trigger the pre_parse callback if needed
void _trigger_pre_parse(std::size_t remaining_args) {
if(!pre_parse_called_) {
pre_parse_called_ = true;
if(pre_parse_callback_) {
pre_parse_callback_(remaining_args);
}
} else if(immediate_callback_) {
if(!name_.empty()) {
auto pcnt = parsed_;
auto extras = std::move(missing_);
clear();
parsed_ = pcnt;
pre_parse_called_ = true;
missing_ = std::move(extras);
}
}
}
/// Get the appropriate parent to fallthrough to which is the first one that has a name or the main app
App *_get_fallthrough_parent() {
if(parent_ == nullptr) {
throw(HorribleError("No Valid parent"));
}
auto fallthrough_parent = parent_;
while((fallthrough_parent->parent_ != nullptr) && (fallthrough_parent->get_name().empty())) {
fallthrough_parent = fallthrough_parent->parent_;
}
return fallthrough_parent;
}
/// Helper function to run through all possible comparisons of subcommand names to check there is no overlap
const std::string &_compare_subcommand_names(const App &subcom, const App &base) const {
static const std::string estring;
if(subcom.disabled_) {
return estring;
}
for(auto &subc : base.subcommands_) {
if(subc.get() != &subcom) {
if(subc->disabled_) {
continue;
}
if(!subcom.get_name().empty()) {
if(subc->check_name(subcom.get_name())) {
return subcom.get_name();
}
}
if(!subc->get_name().empty()) {
if(subcom.check_name(subc->get_name())) {
return subc->get_name();
}
}
for(const auto &les : subcom.aliases_) {
if(subc->check_name(les)) {
return les;
}
}
// this loop is needed in case of ignore_underscore or ignore_case on one but not the other
for(const auto &les : subc->aliases_) {
if(subcom.check_name(les)) {
return les;
}
}
// if the subcommand is an option group we need to check deeper
if(subc->get_name().empty()) {
auto &cmpres = _compare_subcommand_names(subcom, *subc);
if(!cmpres.empty()) {
return cmpres;
}
}
// if the test subcommand is an option group we need to check deeper
if(subcom.get_name().empty()) {
auto &cmpres = _compare_subcommand_names(*subc, subcom);
if(!cmpres.empty()) {
return cmpres;
}
}
}
}
return estring;
}
/// Helper function to place extra values in the most appropriate position
void _move_to_missing(detail::Classifier val_type, const std::string &val) {
if(allow_extras_ || subcommands_.empty()) {
missing_.emplace_back(val_type, val);
return;
}
// allow extra arguments to be places in an option group if it is allowed there
for(auto &subc : subcommands_) {
if(subc->name_.empty() && subc->allow_extras_) {
subc->missing_.emplace_back(val_type, val);
return;
}
}
// if we haven't found any place to put them yet put them in missing
missing_.emplace_back(val_type, val);
}
public:
/// function that could be used by subclasses of App to shift options around into subcommands
void _move_option(Option *opt, App *app) {
if(opt == nullptr) {
throw OptionNotFound("the option is NULL");
}
// verify that the give app is actually a subcommand
bool found = false;
for(auto &subc : subcommands_) {
if(app == subc.get()) {
found = true;
}
}
if(!found) {
throw OptionNotFound("The Given app is not a subcommand");
}
if((help_ptr_ == opt) || (help_all_ptr_ == opt))
throw OptionAlreadyAdded("cannot move help options");
if(config_ptr_ == opt)
throw OptionAlreadyAdded("cannot move config file options");
auto iterator =
std::find_if(std::begin(options_), std::end(options_), [opt](const Option_p &v) { return v.get() == opt; });
if(iterator != std::end(options_)) {
const auto &opt_p = *iterator;
if(std::find_if(std::begin(app->options_), std::end(app->options_), [&opt_p](const Option_p &v) {
return (*v == *opt_p);
}) == std::end(app->options_)) {
// only erase after the insertion was successful
app->options_.push_back(std::move(*iterator));
options_.erase(iterator);
} else {
throw OptionAlreadyAdded("option was not located: " + opt->get_name());
}
} else {
throw OptionNotFound("could not locate the given Option");
}
}
}; // namespace CLI
/// Extension of App to better manage groups of options
class Option_group : public App {
public:
Option_group(std::string group_description, std::string group_name, App *parent)
: App(std::move(group_description), "", parent) {
group(group_name);
// option groups should have automatic fallthrough
}
using App::add_option;
/// Add an existing option to the Option_group
Option *add_option(Option *opt) {
if(get_parent() == nullptr) {
throw OptionNotFound("Unable to locate the specified option");
}
get_parent()->_move_option(opt, this);
return opt;
}
/// Add an existing option to the Option_group
void add_options(Option *opt) { add_option(opt); }
/// Add a bunch of options to the group
template <typename... Args> void add_options(Option *opt, Args... args) {
add_option(opt);
add_options(args...);
}
using App::add_subcommand;
/// Add an existing subcommand to be a member of an option_group
App *add_subcommand(App *subcom) {
App_p subc = subcom->get_parent()->get_subcommand_ptr(subcom);
subc->get_parent()->remove_subcommand(subcom);
add_subcommand(std::move(subc));
return subcom;
}
};
/// Helper function to enable one option group/subcommand when another is used
inline void TriggerOn(App *trigger_app, App *app_to_enable) {
app_to_enable->enabled_by_default(false);
app_to_enable->disabled_by_default();
trigger_app->preparse_callback([app_to_enable](std::size_t) { app_to_enable->disabled(false); });
}
/// Helper function to enable one option group/subcommand when another is used
inline void TriggerOn(App *trigger_app, std::vector<App *> apps_to_enable) {
for(auto &app : apps_to_enable) {
app->enabled_by_default(false);
app->disabled_by_default();
}
trigger_app->preparse_callback([apps_to_enable](std::size_t) {
for(auto &app : apps_to_enable) {
app->disabled(false);
}
});
}
/// Helper function to disable one option group/subcommand when another is used
inline void TriggerOff(App *trigger_app, App *app_to_enable) {
app_to_enable->disabled_by_default(false);
app_to_enable->enabled_by_default();
trigger_app->preparse_callback([app_to_enable](std::size_t) { app_to_enable->disabled(); });
}
/// Helper function to disable one option group/subcommand when another is used
inline void TriggerOff(App *trigger_app, std::vector<App *> apps_to_enable) {
for(auto &app : apps_to_enable) {
app->disabled_by_default(false);
app->enabled_by_default();
}
trigger_app->preparse_callback([apps_to_enable](std::size_t) {
for(auto &app : apps_to_enable) {
app->disabled();
}
});
}
/// Helper function to mark an option as deprecated
inline void deprecate_option(Option *opt, const std::string &replacement = "") {
Validator deprecate_warning{[opt, replacement](std::string &) {
std::cout << opt->get_name() << " is deprecated please use '" << replacement
<< "' instead\n";
return std::string();
},
"DEPRECATED"};
deprecate_warning.application_index(0);
opt->check(deprecate_warning);
if(!replacement.empty()) {
opt->description(opt->get_description() + " DEPRECATED: please use '" + replacement + "' instead");
}
}
/// Helper function to mark an option as deprecated
inline void deprecate_option(App *app, const std::string &option_name, const std::string &replacement = "") {
auto opt = app->get_option(option_name);
deprecate_option(opt, replacement);
}
/// Helper function to mark an option as deprecated
inline void deprecate_option(App &app, const std::string &option_name, const std::string &replacement = "") {
auto opt = app.get_option(option_name);
deprecate_option(opt, replacement);
}
/// Helper function to mark an option as retired
inline void retire_option(App *app, Option *opt) {
App temp;
auto option_copy = temp.add_option(opt->get_name(false, true))
->type_size(opt->get_type_size_min(), opt->get_type_size_max())
->expected(opt->get_expected_min(), opt->get_expected_max())
->allow_extra_args(opt->get_allow_extra_args());
app->remove_option(opt);
auto opt2 = app->add_option(option_copy->get_name(false, true), "option has been retired and has no effect")
->type_name("RETIRED")
->default_str("RETIRED")
->type_size(option_copy->get_type_size_min(), option_copy->get_type_size_max())
->expected(option_copy->get_expected_min(), option_copy->get_expected_max())
->allow_extra_args(option_copy->get_allow_extra_args());
Validator retired_warning{[opt2](std::string &) {
std::cout << "WARNING " << opt2->get_name() << " is retired and has no effect\n";
return std::string();
},
""};
retired_warning.application_index(0);
opt2->check(retired_warning);
}
/// Helper function to mark an option as retired
inline void retire_option(App &app, Option *opt) { retire_option(&app, opt); }
/// Helper function to mark an option as retired
inline void retire_option(App *app, const std::string &option_name) {
auto opt = app->get_option_no_throw(option_name);
if(opt != nullptr) {
retire_option(app, opt);
return;
}
auto opt2 = app->add_option(option_name, "option has been retired and has no effect")
->type_name("RETIRED")
->expected(0, 1)
->default_str("RETIRED");
Validator retired_warning{[opt2](std::string &) {
std::cout << "WARNING " << opt2->get_name() << " is retired and has no effect\n";
return std::string();
},
""};
retired_warning.application_index(0);
opt2->check(retired_warning);
}
/// Helper function to mark an option as retired
inline void retire_option(App &app, const std::string &option_name) { retire_option(&app, option_name); }
namespace FailureMessage {
/// Printout a clean, simple message on error (the default in CLI11 1.5+)
inline std::string simple(const App *app, const Error &e) {
std::string header = std::string(e.what()) + "\n";
std::vector<std::string> names;
// Collect names
if(app->get_help_ptr() != nullptr)
names.push_back(app->get_help_ptr()->get_name());
if(app->get_help_all_ptr() != nullptr)
names.push_back(app->get_help_all_ptr()->get_name());
// If any names found, suggest those
if(!names.empty())
header += "Run with " + detail::join(names, " or ") + " for more information.\n";
return header;
}
/// Printout the full help string on error (if this fn is set, the old default for CLI11)
inline std::string help(const App *app, const Error &e) {
std::string header = std::string("ERROR: ") + e.get_name() + ": " + e.what() + "\n";
header += app->help();
return header;
}
} // namespace FailureMessage
namespace detail {
/// This class is simply to allow tests access to App's protected functions
struct AppFriend {
#ifdef CLI11_CPP14
/// Wrap _parse_short, perfectly forward arguments and return
template <typename... Args> static decltype(auto) parse_arg(App *app, Args &&...args) {
return app->_parse_arg(std::forward<Args>(args)...);
}
/// Wrap _parse_subcommand, perfectly forward arguments and return
template <typename... Args> static decltype(auto) parse_subcommand(App *app, Args &&...args) {
return app->_parse_subcommand(std::forward<Args>(args)...);
}
#else
/// Wrap _parse_short, perfectly forward arguments and return
template <typename... Args>
static auto parse_arg(App *app, Args &&...args) ->
typename std::result_of<decltype (&App::_parse_arg)(App, Args...)>::type {
return app->_parse_arg(std::forward<Args>(args)...);
}
/// Wrap _parse_subcommand, perfectly forward arguments and return
template <typename... Args>
static auto parse_subcommand(App *app, Args &&...args) ->
typename std::result_of<decltype (&App::_parse_subcommand)(App, Args...)>::type {
return app->_parse_subcommand(std::forward<Args>(args)...);
}
#endif
/// Wrap the fallthrough parent function to make sure that is working correctly
static App *get_fallthrough_parent(App *app) { return app->_get_fallthrough_parent(); }
};
} // namespace detail
// [CLI11:app_hpp:end]
} // namespace CLI
|
#include<iostream>
#include<vector>
#include<algorithm>
#include<set>
#include<map>
using namespace std;
class Solution {
public:
bool isSelfCrossing(vector<int>& x){
//基本思想:数学,交叉只有三种可能
for (int i = 3; i < x.size(); ++i){
if(x[i]>=x[i-2]&&x[i-3]>=x[i-1]){
return true;
}
if(i>=4&&x[i-1]==x[i-3]&&x[i]>=x[i-2]-x[i-4]){
return true;
}
if(i>=5&&x[i-2]>=x[i-4]&&x[i-3]>=x[i-1]&&x[i-1]>=x[i-3]-x[i-5]&&x[i]>=x[i-2]-x[i-4]){
return true;
}
}
return false;
}
};
int main()
{
Solution solute;
vector<int> x{2,1,1,2};
cout<<solute.isSelfCrossing(x)<<endl;
return 0;
}
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int T, N;
cin >> T;
vector<int> list;
vector<int>::iterator iter;
for(int i = 0; i < T; i++){
cin >> N;
list.push_back(N);
}
for(iter = list.begin(); iter != list.end(); iter++){
cout << *iter + 1 << endl;
}
return 0;
}
|
#include "scene_flow_constructor.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "scene_flow_constructor");
scene_flow_constructor::SceneFlowConstructor scene_flow_constructor;
ros::spin();
return 0;
}
|
#pragma once
namespace qp
{
class CTypeInQuestionState;
typedef std::shared_ptr<CTypeInQuestionState> CTypeInQuestionStatePtr;
typedef std::shared_ptr<const CTypeInQuestionState> CConstTypeInQuestionState;
class ITypeInQuestionState;
typedef std::shared_ptr<ITypeInQuestionState> ITypeInQuestionStatePtr;
}
|
#include "GameScene.h"
#include "Constant.h"
#include "OverScene.h"
#include "AudioEngine.h"
#include <time.h>
using namespace experimental;
Scene* GameScene::createScene() {
return GameScene::create();
}
bool GameScene::init() {
if (!Scene::init())
return false;
time_count = 0;
isChallange = false;
this->m_isVoiceOn = true;
count = 1;
AudioEngine::play2d("game_music.mp3", true, 0.4f);
auto director = Director::getInstance();
auto spriteCache = SpriteFrameCache::getInstance();
auto origin = director->getVisibleOrigin();
auto size = director->getVisibleSize();
// 读入图集
// 迁移到LoadingScene spriteCache->addSpriteFramesWithFile("shoot_background.plist");
// 从图集中取得精灵
auto background = Sprite::createWithSpriteFrame(
spriteCache->getSpriteFrameByName("background.png"));
auto otherBg = Sprite::createWithSpriteFrame(
spriteCache->getSpriteFrameByName("background.png"));
// 锚点: 将精灵本地坐标转为全局坐标的基准点
// 默认为(0.5,0.5)即将精灵的中心对正Position
// 设置为(0,0) 那么setPosition即是设置精灵左下角的位置
background->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT);
otherBg->setAnchorPoint(Vec2::ANCHOR_BOTTOM_LEFT);
otherBg->setPositionY(background->getContentSize().height-1);
// 不使用锚点的方式
//background->setPosition(director->getVisibleSize().width / 2,
// background->getContentSize().height / 2);
// 开启抗锯齿
background->getTexture()->setAntiAliasTexParameters();
otherBg->getTexture()->setAntiAliasTexParameters();
this->addChild(background, BACKGROUND_ZORDER, BACKGROUND_TAG_1);
this->addChild(otherBg, BACKGROUND_ZORDER, BACKGROUND_TAG_2);
// spriteCache->addSpriteFramesWithFile("shoot.plist");
/*auto hero = Sprite::createWithSpriteFrame(
spriteCache->getSpriteFrameByName("hero1.png"));*/
m_hero = Hero::createHero();
m_hero->setScale(0.8);
m_hero->setPosition(size.width / 2, size.height / 5);
if (HERO_COLOR == 1)
{
m_hero->setColor(Color3B::RED);
}
else if (HERO_COLOR == 2)
{
m_hero->setColor(Color3B::BLUE);
}
this->addChild(m_hero, FOREGROUND_ZORDER, HERO_TAG);
////////////////////////////// 添加触摸事件的处理(创建监听对象,编写逻辑,注册监听器)
auto listener = EventListenerTouchOneByOne::create();
// lambda表达式 [](){};
// []中表示对外部变量的控制,=:所有按值传递,&:所有按引用传递, 或者手动加上变量名,按值传递
auto hero = this->m_hero;
listener->onTouchBegan = [hero, this](Touch* touch, Event* event) {
auto touchPos = touch->getLocation();
//log("Touch Began...[%f,%f]", touchPos.x, touchPos.y);
//auto move = MoveTo::create(0.5f, touchPos);
//hero->runAction(move);
// 判断触摸位置是否在hero上
auto isContains = this->getBoundingBox().containsPoint(touchPos);
this->m_offset = m_hero->getPosition() - touchPos;
return isContains;
};
listener->onTouchMoved = [=](Touch *t, Event* e) {
if (Director::getInstance()->isPaused() && this->m_isOver) return;
Vec2 touchPos = t->getLocation();
//Vec2 deltaPos = t->getDelta(); //上一次触摸点与这一次触摸点之间的向量差
//log("Touch Moved");
hero->move(touchPos + m_offset);
//hero->setPosition(deltaPos + hero->getPosition());
};
listener->onTouchEnded = [](Touch *touch, Event* event) {
//auto touchPos = touch->getLocation();
//log("Touch Ended...[%f,%f]", touchPos.x, touchPos.y);
};
getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, m_hero);
/////////////////////////// UI
// 计分
auto lblScore = Label::createWithBMFont("font.fnt",
StringUtils::format("%d", this->m_totalScore));
lblScore->setAnchorPoint(Vec2(0.5, 1));
lblScore->setPositionX(SIZE.width/2);
lblScore->setPositionY(SIZE.height - lblScore->getContentSize().height / 2);
lblScore->setColor(Color3B::BLACK);
this->addChild(lblScore, UI_ZORDER, LABEL_SCORE_TAG);
// 炸弹UI
//炸弹菜单
auto spBomb = Sprite::createWithSpriteFrameName("bomb.png");
auto itemBomb = MenuItemSprite::create(spBomb, spBomb, [this, lblScore](Ref *) {
//如果游戏处于暂停状态,就不响应
if (Director::getInstance()->isPaused() || this->m_isOver) return;
if (this->m_bombCount <= 0) return;
for (auto enemy : this->m_enemies)
{
enemy->hit(10000);
this->m_totalScore += enemy->getScore();
}
this->m_enemies.clear();
lblScore->setString(StringUtils::format("%d", this->m_totalScore));
this->m_bombCount--;
this->changeBomb();
});
itemBomb->setPosition(itemBomb->getContentSize());
//暂停菜单
auto spPauseNormal = Sprite::createWithSpriteFrameName("game_pause_nor.png");
auto spPauseSelected = Sprite::createWithSpriteFrameName("game_pause_pressed.png");
auto spResumeNormal = Sprite::createWithSpriteFrameName("game_resume_nor.png");
auto spResumeSelected = Sprite::createWithSpriteFrameName("game_resume_pressed.png");
auto itemPause = MenuItemSprite::create(spPauseNormal, spPauseSelected);
auto itemResume = MenuItemSprite::create(spResumeNormal, spResumeSelected);
auto toggle = MenuItemToggle::createWithCallback([this](Ref *sender) {
//获取当前选择项的下标(从0开始)
int index = dynamic_cast<MenuItemToggle *>(sender)->getSelectedIndex();
if (index)
{
Director::getInstance()->pause();
m_hero->setPause(true);
//listener->setEnabled(false);
//itemBomb->setEnabled(false);
}
else
{
Director::getInstance()->resume();
m_hero->setPause(false);
//listener->setEnabled(true);
//itemBomb->setEnabled(true);
}
}, itemPause, itemResume, nullptr);
toggle->setPosition(SIZE - toggle->getContentSize());
auto notQuiet = Sprite::createWithSpriteFrameName("voice.png");
auto Quiet = Sprite::createWithSpriteFrameName("no_voice.png");
auto itemQuiet = MenuItemSprite::create(Quiet, Quiet);
auto itemNotQuiet = MenuItemSprite::create(notQuiet, notQuiet);
auto tog = MenuItemToggle::createWithCallback([this](Ref *sender) {
int index = dynamic_cast<MenuItemToggle *>(sender)->getSelectedIndex();
if (index)
{
this->m_isVoiceOn = false;
}
else
{
this->m_isVoiceOn = true;
}
}, itemQuiet, itemNotQuiet, nullptr);
tog->setPosition(tog->getContentSize().width, SIZE.height - 50);
//炸弹菜单
auto menu = Menu::create();
menu->addChild(itemBomb, FOREGROUND_ZORDER, ITEM_BOMB_TAG);
menu->addChild(toggle);
menu->addChild(tog);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, UI_ZORDER, MENU_TAG);
auto lblBomb = Label::createWithBMFont("font.fnt", StringUtils::format("X%d", this->m_bombCount));
lblBomb->setPosition(itemBomb->getPosition() + Vec2(40, 0));
this->addChild(lblBomb, UI_ZORDER, LABEL_BOMB_TAG);
lblBomb->setColor(Color3B(100, 10, 10));
lblBomb->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
//初始化菜单项和标签的显示
this->changeBomb();
scheduleUpdate();
/////////////////////////// 子弹
// auto bullet = Sprite::createWithSpriteFrameName("bullet1.png");
// bullet->setPosition(hero->getPositionX(), hero->getPositionY() + hero->getContentSize().height / 2);
// this->addChild(bullet, 1, 4);
//新的定时器-定时创建子弹(在update中移动和删除)
schedule(schedule_selector(GameScene::createBullets), CREATE_BULLET_INTERVAL);
schedule(schedule_selector(GameScene::createSmallEnemy), CREATE_SMALLENEMY_INTERVAL, CC_REPEAT_FOREVER, CREATE_SMALLENEMY_DELAY);
schedule(schedule_selector(GameScene::createMiddleEnemy), CREATE_MIDDLEENEMY_INTERVAL, CC_REPEAT_FOREVER, CREATE_MIDDLEENEMY_DELAY);
schedule(schedule_selector(GameScene::createBigEnemy), CREATE_BIGENEMY_INTERVAL, CC_REPEAT_FOREVER, CREATE_BIGENEMY_DELAY);
schedule(schedule_selector(GameScene::createUfo), CREATE_UFO_1_INTERVAL, CC_REPEAT_FOREVER,1.0f);
schedule(schedule_selector(GameScene::createSorMEnemyByBigEnemy), CREATE_SORMENEMYBYBIGENEMY_INTERVAL, CC_REPEAT_FOREVER, CREATE_SORMENEMYBYBIGENEMY_DELAY);
schedule(schedule_selector(GameScene::createAerolite), CREATE_BIGENEMY_INTERVAL*1.5, CC_REPEAT_FOREVER, CREATE_BIGENEMY_DELAY*1.5);
//动态难度
schedule(schedule_selector(GameScene::increasingDifficulty), CREATE_INCREASINGDIFFICLUTY_INTERVAL, CC_REPEAT_FOREVER,1.0f);
srand((unsigned int)time(NULL));
return true;
}
void GameScene::update(float delta) {
float speed = 1.5f;
cycleBackground(1, 2, speed);
//auto bullet = getChildByTag(4);
//shoot(3*speed);
m_hero->moveBullets(delta);
if (isChallange)
{
schedule(schedule_selector(GameScene::createSmallEnemy),0.3f, CHALLANGE_LOOPS,0);
schedule(schedule_selector(GameScene::createMiddleEnemy),2.0f, CHALLANGE_LOOPS, 0);
schedule(schedule_selector(GameScene::createBigEnemy),3.0f, CHALLANGE_LOOPS, 0);
this->time_count++;
if (time_count == 1800)
{
log("30s later....");
this->isChallange = false;
this->time_count = 0;
}
}
if (this->m_isVoiceOn)
{
AudioEngine::resumeAll();
}
else if (!this->m_isVoiceOn)
{
AudioEngine::pauseAll();
}
// 遍历敌机
Vector<Enemy *> removableEnemies;
for (auto enemy : m_enemies) {
enemy->move();
if (enemy->getPositionY() <= -enemy->getContentSize().height / 2) {
this->removeChild(enemy);
removableEnemies.pushBack(enemy);
}
}
// 碰撞检测
for (auto enemy : m_enemies) {
if (removableEnemies.contains(enemy))
continue;
// 与子弹碰撞检测
if (m_hero->isHit(enemy))
{
if (enemy->getHealth() <= 0)
{
removableEnemies.pushBack(enemy);
this->m_totalScore += enemy->getScore();
auto lblScore = static_cast<Label*>(this->getChildByTag(LABEL_SCORE_TAG));
lblScore->setString(StringUtils::format("%d", m_totalScore));
lblScore->setPositionY(SIZE.height - lblScore->getContentSize().height / 2);
}
else
{
//
}
}
//for (auto bullet : m_bullets) {
// if (removableBullets.contains(bullet))
// continue;
// if (enemy->getBoundingBox().intersectsRect(bullet->getBoundingBox())) {
// removableBullets.pushBack(bullet);
// this->removeChild(bullet);
// if (enemy->hit(HERO_DAMAGE)) {
// removableEnemies.pushBack(enemy);
// this->m_totalScore += enemy->getScore();
// auto lblScore = static_cast<Label*>(this->getChildByTag(LABEL_SCORE_TAG));
// lblScore->setString(StringUtils::format("%d", m_totalScore));
// lblScore->setPositionY(SIZE.height - lblScore->getContentSize().height / 2);
// break;
// }
// }
//}
// 与hero碰撞检测
if (m_hero->isStrike(enemy))
{
this->gameOver();
enemy->hit(10000);
}
}
for (auto enemy : removableEnemies) {
m_enemies.eraseObject(enemy);
}
removableEnemies.clear();
Vector<Ufo *>removableUFO;
for (auto Ufo : m_Ufos)
{
if (Ufo->getPositionY() + Ufo->getContentSize().height / 2 <= 0) //道具越界
{
removableUFO.pushBack(Ufo);
this->removeChild(Ufo);
}
if (Ufo->getBoundingBox().intersectsRect(m_hero->getBoundingBox())) //道具与飞机碰撞
{
switch (Ufo->getType())
{
case UfoType::BOMB_UFO: if (m_bombCount < 3) {
this->m_bombCount++;
this->changeBomb();
}
break;
case UfoType::FLASH_UFO:
m_hero->heroUp(UfoType::FLASH_UFO);
break;
case UfoType::MONSTER_UFO:
this->challangeStart();
break;
case UfoType::MULTIPLY_UFO:
m_hero->heroUp(UfoType::MULTIPLY_UFO);
break;
default:
break;
}
removableUFO.pushBack(Ufo);
this->removeChild(Ufo);
}
}
for (auto Ufo : removableUFO)
{
m_Ufos.eraseObject(Ufo);
}
removableUFO.clear();
}
void GameScene::createBigEnemy(float) {
auto bigEnemy = BigEnemy::create();
bigEnemy->playFlyAnimation();
bigEnemy->setDefaultPositon();
this->addChild(bigEnemy);
m_enemies.pushBack(bigEnemy);
}
void GameScene::createMiddleEnemy(float) {
auto middleEnemy = MiddleEnemy::create();
middleEnemy->playFlyAnimation();
middleEnemy->setDefaultPositon();
this->addChild(middleEnemy);
m_enemies.pushBack(middleEnemy);
}
void GameScene::createSmallEnemy(float) {
auto smallEnemy = SmallEnemy::create();
smallEnemy->playFlyAnimation();
smallEnemy->setDefaultPositon();
this->addChild(smallEnemy);
m_enemies.pushBack(smallEnemy);
}
void GameScene::createMiddleEnemyByBigEnemy(Enemy* enemy) {
auto middleEnemy = MiddleEnemy::create();
middleEnemy->playFlyAnimation();
middleEnemy->setPositionX(enemy->getPosition().x);
middleEnemy->setPositionY(enemy->getPosition().y - enemy->getContentSize().height / 2);
this->addChild(middleEnemy);
m_enemies.pushBack(middleEnemy);
}
void GameScene::createSmallEnemyByBigEnemy(Enemy* enemy) {
auto smallEnemy1 = SmallEnemy::create();
smallEnemy1->playFlyAnimation();
smallEnemy1->setPositionY(enemy->getPosition().y - enemy->getContentSize().height / 2);
smallEnemy1->setPositionX(enemy->getPositionX());
this->addChild(smallEnemy1);
m_enemies.pushBack(smallEnemy1);
auto smallEnemy2 = SmallEnemy::create();
smallEnemy2->playFlyAnimation();
smallEnemy2->setPositionY(enemy->getPosition().y - enemy->getContentSize().height / 2);
smallEnemy2->setPositionX(enemy->getPositionX() - enemy->getContentSize().width / 2);
this->addChild(smallEnemy2);
m_enemies.pushBack(smallEnemy2);
auto smallEnemy3 = SmallEnemy::create();
smallEnemy3->playFlyAnimation();
smallEnemy3->setPositionY(enemy->getPosition().y - enemy->getContentSize().height / 2);
smallEnemy3->setPositionX(enemy->getPositionX() + enemy->getContentSize().width / 2);
this->addChild(smallEnemy3);
m_enemies.pushBack(smallEnemy3);
}
void GameScene::createAerolite(float delta) {
auto aero = Aerolite::create();
aero->setDefaultPositon();
this->addChild(aero);
m_enemies.pushBack(aero);
}
void GameScene::createSorMEnemyByBigEnemy(float delta) {
for (auto enemy : m_enemies) {
if (enemy->isAbilityCallEnemy() && enemy->getPositionY() < SIZE.height - enemy->getContentSize().height)
{
auto randNum = rand() % 2;
switch (randNum)
{
case 0:
this->createSmallEnemyByBigEnemy(enemy);
break;
case 1:
this->createMiddleEnemyByBigEnemy(enemy);
break;
default:
break;
}
break;
}
}
}
void GameScene::cycleBackground(int bg1_tag, int bg2_tag, float speed) {
auto bg1 = this->getChildByTag(bg1_tag);
auto bg2 = this->getChildByTag(bg2_tag);
float HEIGHT = bg1->getContentSize().height;
float bg1Y = bg1->getPositionY();
// 在屏幕以外则无需移动
if (bg1Y > -HEIGHT)
bg1->setPositionY(bg1Y - speed);
float bg2Y = bg2->getPositionY();
if (bg2Y <= 0){
// 重置为初始位置
bg1->setPositionY(0);
bg2->setPositionY(HEIGHT - 1);
}
else bg2->setPositionY(bg2Y - speed);
}
/*
1.当炸弹数为0时,菜单项和标签都不显示
2.当炸弹数为1时,只显示菜单项
3.当炸弹数大于1时,显示菜单项和标签,且更新标签显示内容
*/
void GameScene::changeBomb()
{
auto menu = this->getChildByTag(MENU_TAG);
auto itemBomb = menu->getChildByTag(ITEM_BOMB_TAG);
auto lblBomb = this->getChildByTag(LABEL_BOMB_TAG);
if (this->m_bombCount <= 0)
{
itemBomb->setVisible(false);
lblBomb->setVisible(false);
}
else if (this->m_bombCount == 1)
{
itemBomb->setVisible(true);
lblBomb->setVisible(false);
}
else
{
itemBomb->setVisible(true);
lblBomb->setVisible(true);
dynamic_cast<Label*>(lblBomb)->setString(StringUtils::format("X%d", this->m_bombCount));
}
}
void GameScene::gameOver()
{
m_hero->setPause(true);
//1.设置成员变量m_isOver为true
this->m_isOver = true;
//2.道具还在跑
for (auto node : this->getChildren())
{
node->stopAllActions();
}
//3.执行爆炸动画
auto aniHero = AnimationCache::getInstance()->getAnimation(HERO_DIE_ANIMATION);
auto seq = Sequence::create(Animate::create(aniHero), CallFunc::create([this]() {
//4.跳转场景
auto scene = OverScene::createScene(this->m_totalScore);
Director::getInstance()->replaceScene(scene);
}), nullptr);
m_hero->runAction(seq);
//5.停止所有定时器
this->unscheduleAllCallbacks();
}
void GameScene::createBullets(float a)
{
m_hero->creatBullets(a,this);
}
void GameScene::createUfo(float)
{
int Ufo_rand = rand() % 4;
std::string frameName;
int X_RAND; //道具出现的随机范围
UfoType type;
switch (Ufo_rand)
{
case 0:
type = UfoType::BOMB_UFO;
frameName = "ufo2.png";
break;
case 1: type = UfoType::FLASH_UFO;
frameName = "flash.png";
break;
case 2: type = UfoType::MONSTER_UFO;
frameName = "kulo.png";
break;
case 3: type = UfoType::MULTIPLY_UFO;
frameName = "ufo1.png";
break;
default:
break;
}
auto Ufo = Ufo::create(type);
X_RAND = rand() % (UFO_RAND_RANGE + 1) - UFO_RAND_RANGE;
float minX = Ufo->getContentSize().width / 2 + fabs(X_RAND);
float maxX = SIZE.width - minX - fabs(X_RAND);
float x = rand() % (int)(maxX - minX) + minX;
Ufo->setPosition(x, SIZE.height + Ufo->getContentSize().height / 2); //随机产生位置
this->addChild(Ufo, UI_ZORDER);
this->m_Ufos.pushBack(Ufo);
//通过顺序序列 让道具先下来再上去
//log("RAND_X is %d", X_RAND);
auto movedown = MoveTo::create(UFO_FIRSTDOWN_TIME, Vec2(Ufo->getPositionX(), (SIZE.height - SIZE.height / 2)));
Ufo->setPositionX(Ufo->getPositionX() + X_RAND);
auto moveup = MoveTo::create(UFO_UP_TIME, Vec2(Ufo->getPositionX(), (SIZE.height + SIZE.height / 4)));
Ufo->setPositionX(Ufo->getPositionX() + X_RAND);
auto Ufodown = MoveTo::create(UFO_SECONDDOWN_TIME, Vec2(Ufo->getPositionX(), (0 - Ufo->getContentSize().height)));
auto seq = Sequence::create(movedown, moveup, Ufodown, RemoveSelf::create(), nullptr);
Ufo->runAction(seq);
}
void GameScene::challangeStart() {
this->isChallange = true;
}
void GameScene::increasingDifficulty(float delta)
{
if (GameScene::isLevelUp())
{
ConfigUtil::getInstance()->setFloat("BACKGROUND_SPEED_DEFAULT", BACKGROUND_SPEED * 1.1);
ConfigUtil::getInstance()->setFloat("SMALL_ENEMY_SPEED_DEFAULT", SMALL_ENEMY_SPEED * 1.1);
ConfigUtil::getInstance()->setFloat("MIDDLE_ENEMY_SPEED_DEFAULT", MIDDLE_ENEMY_SPEED * 1.1);
ConfigUtil::getInstance()->setFloat("BIG_ENEMY_SPEED_DEFAULT", BIG_ENEMY_SPEED * 1.1);
ConfigUtil::getInstance()->setFloat("SMALL_ENEMY_HEALTH_DEFAULT", SMALL_ENEMY_HEALTH * 1.1);
ConfigUtil::getInstance()->setFloat("MIDDLE_ENEMY_HEALTH_DEFAULT", MIDDLE_ENEMY_HEALTH * 1.1);
ConfigUtil::getInstance()->setFloat("BIG_ENEMY_HEALTH_DEFAULT", BIG_ENEMY_HEALTH * 1.1);
ConfigUtil::getInstance()->setFloat("CREATE_SMALLENEMY_INTERVAL_DEFAULT", CREATE_SMALLENEMY_INTERVAL * 0.9);
ConfigUtil::getInstance()->setFloat("CREATE_MIDDLEENEMY_INTERVAL_DEFAULT", CREATE_MIDDLEENEMY_INTERVAL * 0.9);
ConfigUtil::getInstance()->setFloat("CREATE_BIGENEMY_INTERVAL_DEFAULT", CREATE_BIGENEMY_INTERVAL * 0.9);
}
}
bool GameScene::isLevelUp()
{
if (this->m_totalScore - 20 * count >= 0)
{
count += 1;
return true;
}
return false;
}
|
#include<bits/stdc++.h>
using namespace std;
class ComplexNumbers{
private:
int real;
int imaginary;
public:
ComplexNumbers(int real,int imaginary){
this -> real = real;
this -> imaginary = imaginary;
}
void plus(ComplexNumbers c2){
int r = this -> real + c2.real;
int i = this -> imaginary + c2.imaginary;
this -> real = r;
this -> imaginary = i;
}
void multiply(ComplexNumbers c2){
int r = (this -> real * c2.real) - (this -> imaginary * c2.imaginary);
int i = (this -> real * c2.imaginary) + (c2.real * this -> imaginary);
this -> real = r;
this -> imaginary = i;
}
void print(){
cout << this -> real << " + " << this -> imaginary << "i" << endl;
}
};
int main(){
//Addition of two complex numbers.
ComplexNumbers c1(3,2);
ComplexNumbers c2(4,3);
cout << "c1 : ";
c1.print();
cout << "c2 : ";
c2.print();
c1.plus(c2);
cout << "Sum : ";
c1.print();
//Product of two complex numbers.
ComplexNumbers c3(4,2);
ComplexNumbers c4(6,3);
cout << "c3 : ";
c3.print();
cout << "c4 : ";
c4.print();
c3.multiply(c4);
cout << "Product : ";
c3.print();
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin >> s;
int p;
vector<char> v;
for (int i = 0; i < s.length(); i++)
{
p = 0;
for (int j = 0; j < v.size(); j++)
{
if (s[i] == v[j])
{
p += 1;
break;
}
}
if (p == 0)
{
v.push_back(s[i]);
}
}
if (v.size() % 2 != 0)
{
cout << "IGNORE HIM!";
}
else
{
cout << "CHAT WITH HER!";
}
return 0;
}
|
/* Task 4 – Students Information
Write a program, use a class that has params:
Student Name
Student Surname
Total Average
The class should have Print method that for a given object prints all the information
Make a vector in main that for a given number ( passed thru user ) saves the objects
Again with Static meber and metod
*/
#include <utility>
#include <iostream>
#include <vector>
#include <string>
class Student{
private:
std::string name;
std::string surName;
double average;
static std::vector<Student> students;
public:
Student(std::string name, std::string surName, double average, double allAverage)
: name(std::move(name)), surName(std::move(surName)),
average(average) {
}
virtual ~Student() {
}
static void setStudents(const std::vector<Student> &students) {
Student::students = students;
}
public:
static void PtintStudentInfo(){
for ( auto &i : students ) {
std::cout<< i.name<<" "<< i.surName<<" "<< i.average<<std::endl;
}
}
};
std::vector<Student> Student::students;
int main() {
int numberofstudents=0;
std::cin>>numberofstudents;
std::string name="";
std::string surName="";
double average=0;
std::vector<Student> studentVectors;
for ( int i = 0; i < numberofstudents; ++i ) {
std::cin>>name;
std::cin>>surName;
std::cin>>average;
Student student(name, surName, average, 0);
studentVectors.push_back(student);
}
Student::setStudents(studentVectors);
Student::PtintStudentInfo();
return 0;
}
|
#include "stdafx.h"
class SoundGenerator;
HINSTANCE hInst;
HWND hWnd;
SoundGenerator*generator;
HFONT hFontStatus;
#pragma comment(lib, "Winmm.lib")
|
#ifndef TP_PPROJECT_BASECONNECTION_H
#define TP_PPROJECT_BASECONNECTION_H
#include <iostream>
#include <deque>
#include <boost/asio/detail/array.hpp>
/*
* Base class of connection
*/
class BaseConnection {
public:
virtual ~BaseConnection() {}
/*
* Sending a response to the client
*/
virtual void onMessage(std::string &msg) = 0;
};
#endif
|
// testDll.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
#include <string>
extern "C"
{
__declspec(dllexport) int my_add(int a, int b);
}
int my_add(int a,int b)
{
return a+b;
}
|
/*
* This file contains the heading files for the lidar interface
* using the Adafruit VL53L0X libary
*
* Creation date: 2019 06 10
* Author: Pascal Pfeiffer
*/
#ifndef LIDAR_H
#define LIDAR_H
#include "Adafruit_VL53L0X.h"
// port expander I2C adress
#define EXP_ADDRESS 0x20
/*
* Port expander pinning:
* P0 -> lidar back 0x35 LOX5 measureLidar[5]
* P1 -> lidar right 0x34 LOX4 measureLidar[4]
* P2 -> front left down 0x32 LOX1 measureLidar[1]
* P3 -> Links left 0x36 LOX6 measureLidar[6]
* P4 -> lidar front left up 0x30 LOX0 measureLidar[0]
* P5 -> lidar front right down 0x31 LOX2 measureLidar[2]
* P6 -> lidar front right up 0x33 LOX3 measureLidar[3]
*/
// sensor I2C adresses
#define LOX0_ADDRESS 0x30
#define LOX1_ADDRESS 0x31
#define LOX2_ADDRESS 0x32
#define LOX3_ADDRESS 0x33
#define LOX4_ADDRESS 0x34
#define LOX5_ADDRESS 0x35
#define LOX6_ADDRESS 0x36
// Assign lox shutdown pin to port expander
#define SHT_LOX0 0x10 // expander port P4
#define SHT_LOX1 0x04 // expander port P2
#define SHT_LOX2 0x20 // expander port P5
#define SHT_LOX3 0x40 // expander port P6
#define SHT_LOX4 0x02 // expander port P1
#define SHT_LOX5 0x01 // expander port P0
#define SHT_LOX6 0x08 // expander port P3
class lidar {
private:
bool isInit = false;
// objects for the vl53l0x (Lidar sensors)
Adafruit_VL53L0X lox0 = Adafruit_VL53L0X();
Adafruit_VL53L0X lox1 = Adafruit_VL53L0X();
Adafruit_VL53L0X lox2 = Adafruit_VL53L0X();
Adafruit_VL53L0X lox3 = Adafruit_VL53L0X();
Adafruit_VL53L0X lox4 = Adafruit_VL53L0X();
Adafruit_VL53L0X lox5 = Adafruit_VL53L0X();
Adafruit_VL53L0X lox6 = Adafruit_VL53L0X();
void setID();
public:
// this holds the measurements
VL53L0X_RangingMeasurementData_t measureLidar[7];
void expanderWrite(int, uint8_t);
void initLox();
void readLOXSensors();
int printLOXValues();
};
#endif
|
#include"../include/knn_handwriteDigitsClassifyer.h"
int main(int argc, char** argv)
{
HD_Classify_KNN classifer_knn;
//string data = "D:/CODEing/OpenCV_codeSources/knn_handwriteDigitsClassify/data/cv_sample_png/digits.png";
//classifer_knn.loadTrainDataFromImg(data);
//classifer_knn.trainAndTestKNN();
string knndata = "D:/CODEing/OpenCV_codeSources/knn_handwriteDigitsClassify/saveKNN/knn_digits.xml";
classifer_knn.getTrainedKNN(knndata);
Mat test = imread("D:/CODEing/OpenCV_codeSources/knn_handwriteDigitsClassify/data/cv_sample_png/8.jpg");
imshow("testImage_8", test);
cout << "the predict result is :" << classifer_knn.predict(test) << endl;
test = imread("D:/CODEing/OpenCV_codeSources/knn_handwriteDigitsClassify/data/cv_sample_png/4.jpg");
imshow("testImage_4", test);
cout << "the predict result is :" << classifer_knn.predict(test) << endl;
test = imread("D:/CODEing/OpenCV_codeSources/knn_handwriteDigitsClassify/data/cv_sample_png/5.jpg");
imshow("testImage_5", test);
cout << "the predict result is :" << classifer_knn.predict(test) << endl;
waitKey(0);
return 0;
}
|
//
// Created by 钟奇龙 on 2019-05-18.
//
#include <iostream>
#include <vector>
using namespace std;
int maxABS(vector<int> arr){
int maxValue = INT_MIN;
for(int i=0; i<arr.size(); ++i){
maxValue = max(maxValue,arr[i]);
}
return max(maxValue-arr[0],maxValue-arr[arr.size()-1]);
}
int main(){
cout<<maxABS({2,7,3,1,1})<<endl;
cout<<maxABS({7,1,1,9,8})<<endl;
return 0;
}
|
/**
* @file AudioDevice.h
* @brief Header file for Engine::AudioDevice
*
* @author Gemuele (Gem) Aludino
* @date 09 Dec 2019
*/
/**
* Copyright © 2019 Gemuele Aludino
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
* THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef AUDIODEVICE_H
#define AUDIODEVICE_H
#include <QtMultimedia>
#include <QIODevice>
namespace Engine {
class AudioDevice;
};
/**
* @brief The Engine::AudioDevice class
*/
class Engine::AudioDevice : public QIODevice {
public:
AudioDevice(const QAudioFormat newFormat);
~AudioDevice() override;
void setMinAmplitude(qreal minAmplitude);
QAudioFormat &getQAudioFormat();
qreal &getDeviceLevel();
qreal &getMinAmplitude();
quint32 &getMaxAmplitude();
static quint32 getMin(quint32 a, quint32 b);
public slots:
qint64 readData(char *data, qint64 maxlen) override;
qint64 writeData(const char *data, qint64 len) override;
private:
QAudioFormat qAudioFormat;
qreal deviceLevel;
qreal minAmplitude;
quint32 maxAmplitude;
};
#endif // AUDIODEVICE_H
|
#include <iostream>
#include <cstddef>
using namespace std;
class Nod{
private:
char info;
Nod *next;
public:
Nod *GetNext(){return next;}
char GetInfo(){return info;}
void setNext(Nod *next1){this->next=next1;}
Nod()//constructor neparametrizat
{
this->info=0;
this->next=nullptr;}
Nod(char info1,Nod *urm);//constructor param
~Nod(){
info = '\0';
next = nullptr;
}
friend ostream &operator <<(ostream &out,const Nod &nod );
friend void citire_n(int n);
};
Nod::Nod(char info1, Nod *urm) {
this->info=info1;
this->next=urm;
}
ostream & operator <<(ostream &out, const Nod &nod){
out<<nod.info<<" ";
return out;
}
class Coada_de_caractere{
private:
Nod *first,*last;
size_t sz = 0;
public:
Coada_de_caractere();
~Coada_de_caractere();
void push(char c);
void pop();
bool isEmpty();
friend ostream &operator <<(ostream &out,const Coada_de_caractere &coada);
friend istream &operator >> (istream &in,Coada_de_caractere &coada);
Coada_de_caractere operator +(Coada_de_caractere &caractere);
Nod *GetFirst(){return first;}
Coada_de_caractere operator -(Coada_de_caractere &queue);
};
Coada_de_caractere::Coada_de_caractere() {
sz = 0;
this->first=nullptr;
this->last=nullptr;
}
Coada_de_caractere::~Coada_de_caractere() {
Nod *index=this->first;
while(index!=nullptr)
{
Nod *urm=index->GetNext();
delete index;
index=urm;
}
sz = 0;
}
void Coada_de_caractere::push(char c) {
if(this->last==nullptr)
this->first=this->last=new Nod(c,nullptr);
else
{
Nod *p=new Nod(c,nullptr);
this->last->setNext(p);
this->last = p;
}
sz++;
}
void Coada_de_caractere::pop() {
if(first!=nullptr)
{
Nod *p=first;
first=first->GetNext();
delete p;
sz--;
}
}
bool Coada_de_caractere::isEmpty() {
return sz == 0;
}
ostream &operator<<(ostream &out, const Coada_de_caractere &coada) {
Nod *p=coada.first;
while(p!=nullptr)
{out<<p->GetInfo()<<" ";
p=p->GetNext();}
return out;
}
istream &operator>>(istream &in, Coada_de_caractere &coada) {
size_t n;
char p;
cout<<"Dati nr de elemente pe care le veti citi de la tastatura "<<" ";
in>>n;
while(n)
{in >> p;
coada.push(p);
n--;}
return in;
}
Coada_de_caractere Coada_de_caractere::operator+(Coada_de_caractere &caractere) {
Nod *p=new Nod();
p=first;
Coada_de_caractere cd;
while(p!=nullptr)
{
cd.push(p->GetInfo());
p=p->GetNext();
}
p=caractere.GetFirst();
while(p!=nullptr)
{
cd.push(p->GetInfo());
p=p->GetNext();
}
return cd;
}
Coada_de_caractere Coada_de_caractere::operator-(Coada_de_caractere &queue) {
Nod *p=new Nod();
Nod *q=new Nod();
p=first;
q=queue.GetFirst();
static Coada_de_caractere cd;
while(p!=nullptr && q!=nullptr)
{ if(p->GetInfo()>q->GetInfo())
{cd.push(p->GetInfo());}
else
{cd.push(q->GetInfo());}
p=p->GetNext();
q=q->GetNext();}
return cd;
}
void citire_n(int n)
{Coada_de_caractere x[100];
for(int i=0;i<n;i++)
cin>>x[i];
for(int i=0;i<n;i++)
cout<<x[i]<<endl;}
int main()
{
Coada_de_caractere ob1;
Coada_de_caractere ob2;
cin >> ob1;
cin>>ob2;
ob1.push('c');
ob1.push('b');
ob2.push('a');
ob2.push('z');
ob1.pop(); ob2.pop();
cout<<ob1.isEmpty()<<endl;
cout <<ob1<<endl;
cout<<ob2<<endl;
cout<<ob1+ob2<<endl;
cout<<ob1-ob2<<endl;
int n;
cin>>n;
citire_n(n);
return 0;
}
|
#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
class Solution {
public:
int maxSubArrayLen(vector<int>& nums, int k) {
//基本思想:前缀和+哈希表HashMap,HashMap[i]表示前缀和为i时的最小下标处,pre[i]-pre[j-1]==k,pre[j-1]==pre[i]-k
//遍历数组nums,计算从第0个元素到当前元素的和sum,用哈希表Map保存出现过的累积和sum的最小下标处;
//如果sum-k在哈希表中出现过,则代表从当前下标i往前有连续的子数组的和为sum,res=max(res,i-Map[sum-k])
unordered_map<int,int> Map;
int sum=0;
int res=0;
Map[0]=-1;
for(int i=0;i<nums.size();i++)
{
sum+=nums[i];
if(Map.find(sum-k)!=Map.end())
{
res=max(res,i-Map[sum-k]);
}
if(Map.find(sum)==Map.end())
Map[sum]=i;
}
return res;
}
};
inr main()
{
Solution solute;
vector<int> nums{1, -1, 5, -2, 3};
int k=3;
cout<<solute.maxSubArrayLen(nums,k)<<endl;
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
using ii = pair<ll,ll>;
using iii = pair<ll,ii>;
#define F first
#define S second
#define MP make_pair
#define PB push_back
vector<pair<ll,ll> > v[10002]; // v[i].F->node connnected to i & v[i].S-> distance b/w them...
ll dist[1002][1002]; // dist[i][j]->cost to reach node i with fuel j still left...
ll price[1002];
ll vst[1002][102]; // whether the state (i,j) is visited or not...
class prioritize {
public: bool operator()(iii &p1,iii &p2){
return p1.F>p2.F;
}
};
ll dijkstra(ll s,ll e,ll c,ll n)
{
for(ll i=0;i<n;i++)
{
for(ll j=0;j<=c;j++)
{
vst[i][j]=0;
dist[i][j]=1e9;
}
}
dist[s][0]=0; // cost to reach source with 0 fuel left is 0....
priority_queue<iii,vector<iii>,prioritize > pq; // iii->(min_cost,(node i,fuel j));
pq.push(MP(0,MP(s,0))); // iii.F->cost,iii.S.F-> node,iii.S.S-> fuel level.....
while(!pq.empty())
{
iii h= pq.top();
pq.pop();
ll node= h.S.F;
ll fuel= h.S.S;
if(vst[node][fuel]) continue;
vst[node][fuel]=1;
for(ll u=0;u<v[node].size();u++) // transition TO NEW neighbours.....
{
ll neigh= v[node][u].F;
ll len= v[node][u].S;
if(fuel>=len)
{
if(dist[neigh][fuel-len]>dist[node][fuel])
{
dist[neigh][fuel-len]=dist[node][fuel];
pq.push(MP(dist[neigh][fuel-len],MP(neigh,fuel-len)));
}
}
}
if(fuel+1<=c) // TRANSITION TO A NEW FUEL STATE OF SAME NODE......
{
if(dist[node][fuel+1]>dist[node][fuel]+price[node])
{
dist[node][fuel+1]=dist[node][fuel]+price[node];
pq.push(MP(dist[node][fuel+1],MP(node,fuel+1)));
}
}
}
return dist[e][0];
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
ll n,m;
cin>>n>>m;
for(ll i=0;i<n;i++){
cin>>price[i];
}
while(m--){
ll u,ne,d;
cin>>u>>ne>>d; // d-> length of road b/w u and v....
v[u].push_back(make_pair(ne,d));
v[ne].push_back(make_pair(u,d));
}
ll q;
cin>>q;
while(q--){
ll c,s,e; // s-> start,e-> end, c-> fuel capacity of the tank....
cin>>c>>s>>e;
ll d=dijkstra(s,e,c,n);
//dist[e][0];
if(d==1e9){
cout<<"impossible\n";
}
else{
cout<<d<<"\n";
}
}
}
|
#include <string>
class Student
{
public:
Student(std::string name)
: student_name{name},
exam_sum{0},
exam_num_grades{0}
{ }
std::string name()
{ return student_name; }
void exam(double grade)
{
exam_sum += grade;
exam_num_grades++;
}
double average()
{
if (exam_num_grades == 0)
return 100;
else
return exam_sum / exam_num_grades;
}
private:
std::string student_name;
double exam_sum;
double exam_num_grades;
};
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Arjan van Leeuwen (arjanl)
*/
#include "core/pch.h"
#include "adjunct/m2/src/backend/imap/commands/MessageSetCommand.h"
#include "adjunct/m2/src/backend/imap/commands/MailboxCommand.h"
#include "adjunct/m2/src/backend/imap/imap-protocol.h"
#include "adjunct/m2/src/backend/imap/imapmodule.h"
#include "adjunct/m2/src/engine/account.h"
#include "adjunct/m2/src/engine/engine.h"
#include "adjunct/m2/src/engine/index.h"
#include "adjunct/m2/src/engine/indexer.h"
#include "adjunct/m2/src/engine/message.h"
#include "adjunct/m2/src/engine/offlinelog.h"
///////////////////////////////////////////
// MessageSetCommand
///////////////////////////////////////////
/***********************************************************************************
**
**
** MessageSetCommand::CanExtendWith
***********************************************************************************/
BOOL ImapCommands::MessageSetCommand::CanExtendWith(const MessageSetCommand* command) const
{
return command->GetExtendableType() == GetExtendableType() &&
m_mailbox == command->m_mailbox &&
m_flags == command->m_flags;
}
/***********************************************************************************
**
**
** MessageSetCommand::ExtendWith
***********************************************************************************/
OP_STATUS ImapCommands::MessageSetCommand::ExtendWith(const MessageSetCommand* command, IMAP4& protocol)
{
unsigned count_before_merge = m_message_set.Count();
RETURN_IF_ERROR(m_message_set.Merge(command->m_message_set));
// Update progress, now that count has changed
protocol.GetBackend().IncreaseProgressTotal(GetProgressAction(), m_message_set.Count() - count_before_merge);
return OpStatus::OK;
}
/***********************************************************************************
**
**
** MessageSetCommand::PrepareSetForOffline
***********************************************************************************/
OP_STATUS ImapCommands::MessageSetCommand::PrepareSetForOffline(OpINT32Vector& message_ids)
{
if (m_message_set.IsInvalid() ||
!(m_flags & USE_UID))
{
return OpStatus::OK;
}
RETURN_IF_ERROR(m_message_set.ToVector(message_ids));
return m_mailbox->ConvertUIDToM2Id(message_ids);
}
///////////////////////////////////////////
// Copy
///////////////////////////////////////////
/***********************************************************************************
**
**
** Copy::OnSuccessfulComplete
***********************************************************************************/
OP_STATUS ImapCommands::Copy::OnSuccessfulComplete(IMAP4& protocol)
{
if (m_to_mailbox->GetIndex())
RETURN_IF_ERROR(m_to_mailbox->GetIndex()->DecreaseNewMessageCount(m_message_set.Count()));
return protocol.GetBackend().SyncFolder(m_to_mailbox);
}
/***********************************************************************************
**
**
** Copy::OnCopyUid
***********************************************************************************/
OP_STATUS ImapCommands::Copy::OnCopyUid(IMAP4& protocol, unsigned uid_validity, OpINT32Vector& source_set, OpINT32Vector& dest_set)
{
// Source set should be just as big as dest set, else we're not going to do this
if (source_set.GetCount() != dest_set.GetCount())
return OpStatus::OK;
// We try to copy the original messages and save their UIDs
for (unsigned i = 0; i < source_set.GetCount(); i++)
{
message_gid_t message_id = m_mailbox->GetMessageByUID(source_set.Get(i));
int dest_uid = dest_set.Get(i);
protocol.GetBackend().OnMessageCopied(message_id, m_to_mailbox, dest_uid, FALSE);
}
return OpStatus::OK;
}
/***********************************************************************************
**
**
** Copy::WriteToOfflineLog
***********************************************************************************/
OP_STATUS ImapCommands::Copy::WriteToOfflineLog(OfflineLog& offline_log)
{
OpINT32Vector message_ids;
RETURN_IF_ERROR(PrepareSetForOffline(message_ids));
return offline_log.CopyMessages(message_ids, m_mailbox->GetIndexId(), m_to_mailbox->GetIndexId());
}
/***********************************************************************************
**
**
** Copy::AppendCommand
***********************************************************************************/
OP_STATUS ImapCommands::Copy::AppendCommand(OpString8& command, IMAP4& protocol)
{
OpINT32Vector uids;
RETURN_IF_ERROR(m_message_set.ToVector(uids));
for (UINT32 i = 0; i < uids.GetCount(); i++)
{
message_gid_t* message_id = OP_NEW(message_gid_t,(m_mailbox->GetMessageByUID(uids.Get(i))));
RETURN_OOM_IF_NULL(message_id);
RETURN_IF_ERROR(m_uid_m2id_map.Add(uids.Get(i), message_id ));
}
OpString8 message_set_string;
RETURN_IF_ERROR(m_message_set.GetString(message_set_string));
return command.AppendFormat("%sCOPY %s %s",
m_flags & USE_UID ? "UID " : "",
message_set_string.CStr(),
m_to_mailbox->GetQuotedName().CStr());
}
///////////////////////////////////////////
// Move
///////////////////////////////////////////
/***********************************************************************************
** Move: first copy, then delete
**
** Move::GetExpandedQueue
***********************************************************************************/
ImapCommandItem* ImapCommands::Move::GetExpandedQueue(IMAP4& protocol)
{
// Create COPY command
OpAutoPtr<ImapCommands::MoveCopy> expanded_queue (OP_NEW(ImapCommands::MoveCopy, (m_mailbox,
m_to_mailbox,
0, 0)));
if (!expanded_queue.get() || OpStatus::IsError(expanded_queue->GetMessageSet().Copy(m_message_set)))
return NULL;
// Create message delete command
ImapCommands::MessageDelete* delete_command = OP_NEW(ImapCommands::MessageDelete, (m_mailbox, 0, 0));
if (!delete_command || OpStatus::IsError(delete_command->GetMessageSet().Copy(m_message_set)))
return NULL;
delete_command->DependsOn(expanded_queue.get(), protocol);
return expanded_queue.release();
}
/***********************************************************************************
**
**
** Move::WriteToOfflineLog
***********************************************************************************/
OP_STATUS ImapCommands::Move::WriteToOfflineLog(OfflineLog& offline_log)
{
OpINT32Vector message_ids;
RETURN_IF_ERROR(PrepareSetForOffline(message_ids));
return offline_log.MoveMessages(message_ids, m_mailbox->GetIndexId(), m_to_mailbox->GetIndexId());
}
/***********************************************************************************
**
**
** MoveCopy::OnCopyUid
***********************************************************************************/
OP_STATUS ImapCommands::MoveCopy::OnCopyUid(IMAP4& protocol, unsigned uid_validity, OpINT32Vector& source_set, OpINT32Vector& dest_set)
{
// This Copy is actually a Move
// We need to move the message locally as well, and remove the old internet location
if (source_set.GetCount() != dest_set.GetCount())
return OpStatus::OK;
// We try to move the original messages and save their UIDs
for (unsigned i = 0; i < source_set.GetCount(); i++)
{
message_gid_t *message_id;
RETURN_IF_ERROR(m_uid_m2id_map.GetData(source_set.Get(i), &message_id));
int dest_uid = dest_set.Get(i);
// remove from source folder
RETURN_IF_ERROR(protocol.GetBackend().GetUIDManager().RemoveUID(m_mailbox->GetIndexId(), source_set.Get(i)));
RETURN_IF_ERROR(m_mailbox->GetIndex()->RemoveMessage(*message_id));
RETURN_IF_ERROR(protocol.GetBackend().OnMessageCopied(*message_id, m_to_mailbox, dest_uid, TRUE));
}
return OpStatus::OK;
}
/***********************************************************************************
**
**
** MoveCopy::AppendCommand
***********************************************************************************/
OP_STATUS ImapCommands::MoveCopy::AppendCommand(OpString8& command, IMAP4& protocol)
{
RETURN_IF_ERROR(Copy::AppendCommand(command, protocol));
if (protocol.GetCapabilities() & ImapFlags::CAP_UIDPLUS)
{
for (INT32HashIterator<message_gid_t> it(m_uid_m2id_map); it; it++)
{
RETURN_IF_ERROR(protocol.GetBackend().GetUIDManager().RemoveUID(m_mailbox->GetIndexId(), it.GetKey()));
}
}
return OpStatus::OK;
}
///////////////////////////////////////////
// Fetch
///////////////////////////////////////////
/***********************************************************************************
**
**
** Fetch::PrepareToSend
***********************************************************************************/
OP_STATUS ImapCommands::Fetch::PrepareToSend(IMAP4& protocol)
{
// Special: check if fetch contains too many messages to do in one go, split in
// that case
if (m_flags & (BODY | HEADERS | ALL_HEADERS | COMPLETE))
{
unsigned max_msg = (m_flags & (BODY | COMPLETE)) ? 20 : 50;
if (m_message_set.ContainsMoreThan(max_msg))
{
// Split off a new command
ImapCommands::Fetch* split = CreateNewCopy();
if (!split)
return OpStatus::ERR_NO_MEMORY;
split->Follow(this, protocol);
// Do the split
return m_message_set.SplitOff(max_msg, split->m_message_set);
}
}
return OpStatus::OK;
}
/***********************************************************************************
**
**
** Fetch::GetProgressAction
***********************************************************************************/
ProgressInfo::ProgressAction ImapCommands::Fetch::GetProgressAction() const
{
if (m_flags & (HEADERS | ALL_HEADERS))
return ProgressInfo::FETCHING_HEADERS;
else if (m_flags & (BODY | TEXTPART | COMPLETE))
return ProgressInfo::FETCHING_MESSAGES;
else
return ProgressInfo::SYNCHRONIZING;
}
/***********************************************************************************
**
**
** Fetch::AppendCommand
***********************************************************************************/
OP_STATUS ImapCommands::Fetch::AppendCommand(OpString8& command, IMAP4& protocol)
{
OpString8 commands;
RETURN_IF_ERROR(GetFetchCommands(commands));
OpString8 message_set_string;
RETURN_IF_ERROR(m_message_set.GetString(message_set_string));
RETURN_IF_ERROR(command.AppendFormat("%sFETCH %s (UID %s%sFLAGS)",
m_flags & USE_UID ? "UID " : "",
message_set_string.CStr(),
protocol.GetCapabilities() & ImapFlags::CAP_QRESYNC ? "MODSEQ " : "",
commands.HasContent() ? commands.CStr() : ""
));
if (m_flags & CHANGED)
{
RETURN_IF_ERROR(command.AppendFormat(" (CHANGEDSINCE %lld VANISHED)", m_mailbox->LastKnownModSeq()));
}
return OpStatus::OK;
}
/***********************************************************************************
** Gets the string for commands (e.g. "RFC822.HEADER BODY.PEEK[]"
** Empty string allowed
** If content exists, should end in a space
**
** Fetch::GetFetchCommands
***********************************************************************************/
OP_STATUS ImapCommands::Fetch::GetFetchCommands(OpString8& commands) const
{
if (m_flags & BODY)
RETURN_IF_ERROR(commands.Append("BODY.PEEK[TEXT] "));
if (m_flags & COMPLETE)
RETURN_IF_ERROR(commands.Append("BODY.PEEK[] "));
if (m_flags & HEADERS)
{
OpString8 needed_headers;
RETURN_IF_ERROR(MessageEngine::GetInstance()->GetIndexer()->GetNeededHeaders(needed_headers));
RETURN_IF_ERROR(commands.AppendFormat("RFC822.SIZE BODY.PEEK[HEADER.FIELDS (%s%s%s)] ",
GetDefaultHeaders(),
needed_headers.HasContent() ? " " : "",
needed_headers.HasContent() ? needed_headers.CStr() : ""));
}
if (m_flags & ALL_HEADERS)
RETURN_IF_ERROR(commands.Append("RFC822.SIZE BODY.PEEK[HEADER] "));
if (m_flags & BODYSTRUCTURE)
RETURN_IF_ERROR(commands.Append("BODYSTRUCTURE "));
return OpStatus::OK;
}
/***********************************************************************************
** Gets default headers in space-separated format, e.g. "SUBJECT FROM"
**
** Fetch::GetDefaultHeaders
***********************************************************************************/
const char* ImapCommands::Fetch::GetDefaultHeaders() const
{
return "SUBJECT FROM TO CC REPLY-TO DATE MESSAGE-ID REFERENCES IN-REPLY-TO LIST-ID LIST-POST X-MAILING-LIST DELIVERED-TO";
}
/***********************************************************************************
** Gets the string for commands (e.g. "RFC822.HEADER BODY.PEEK[]"
** Empty string allowed
** If content exists, should end in a space
**
** Fetch::CreateNewCopy
***********************************************************************************/
ImapCommands::Fetch* ImapCommands::Fetch::CreateNewCopy() const
{
return OP_NEW(ImapCommands::Fetch, (m_mailbox, 0, 0, m_flags));
}
///////////////////////////////////////////
// TextPartFetch
///////////////////////////////////////////
/***********************************************************************************
** Received the text part depth
**
** TextPartFetch::OnTextPartDepth
***********************************************************************************/
OP_STATUS ImapCommands::TextPartFetch::OnTextPartDepth(unsigned uid, unsigned textpart_depth, IMAP4& protocol)
{
TextPartBodyFetch* body_fetch = OP_NEW(TextPartBodyFetch, (m_mailbox, uid, textpart_depth));
if (!body_fetch)
return OpStatus::ERR_NO_MEMORY;
body_fetch->DependsOn(this, protocol);
return OpStatus::OK;
}
/***********************************************************************************
** Gets default headers in space-separated format, e.g. "SUBJECT FROM"
**
** TextPartFetch::GetDefaultHeaders
***********************************************************************************/
const char* ImapCommands::TextPartFetch::GetDefaultHeaders() const
{
return "SUBJECT FROM TO CC REPLY-TO DATE MESSAGE-ID REFERENCES IN-REPLY-TO LIST-ID LIST-POST X-MAILING-LIST DELIVERED-TO CONTENT-TYPE CONTENT-TRANSFER-ENCODING";
}
/***********************************************************************************
**
**
** TextPartFetch::CreateNewCopy
***********************************************************************************/
ImapCommands::Fetch* ImapCommands::TextPartFetch::CreateNewCopy() const
{
return OP_NEW(TextPartFetch, (m_mailbox, 0, 0, m_flags & USE_UID));
}
/***********************************************************************************
** Gets the string for commands (e.g. "RFC822.HEADER BODY.PEEK[]"
** Empty string allowed
** If content exists, should end in a space
**
** TextPartFetch::TextPartBodyFetch::GetFetchCommands
***********************************************************************************/
OP_STATUS ImapCommands::TextPartFetch::TextPartBodyFetch::GetFetchCommands(OpString8& commands) const
{
OpString8 part;
RETURN_IF_ERROR(part.Set("1"));
// For depth deeper than 1, we add .1 ("1" works for both single part and the first part of a multipart)
for (unsigned i = 1; i < m_textpart_depth; i++)
RETURN_IF_ERROR(part.Append(".1"));
return commands.AppendFormat("BODY.PEEK[%s.MIME] BODY.PEEK[%s] ", part.CStr(), part.CStr());
}
///////////////////////////////////////////
// Search
///////////////////////////////////////////
/***********************************************************************************
**
**
** Search::OnSearchResults
***********************************************************************************/
OP_STATUS ImapCommands::Search::OnSearchResults(OpINT32Vector& search_results)
{
// propagate to children, they might use the result
for (ImapCommandItem* child = FirstChild(); child; child = child->FirstChild())
RETURN_IF_ERROR(child->OnSearchResults(search_results));
return OpStatus::OK;
}
/***********************************************************************************
**
**
** Search::AppendCommand
***********************************************************************************/
OP_STATUS ImapCommands::Search::AppendCommand(OpString8& command, IMAP4& protocol)
{
OpString8 message_set_string;
RETURN_IF_ERROR(m_message_set.GetString(message_set_string));
return command.AppendFormat("%sSEARCH%s%s %s%s",
m_flags & FOR_UID ? "UID " : "",
m_flags & NOT ? " NOT" : "",
m_flags & BY_UID ? " UID" : "",
message_set_string.CStr(),
m_flags & DELETED ? " DELETED" : "");
}
///////////////////////////////////////////
// Store
///////////////////////////////////////////
/***********************************************************************************
**
**
** Store::IsUnnecessary
***********************************************************************************/
BOOL ImapCommands::Store::IsUnnecessary(const IMAP4& protocol) const
{
return ((m_flags & KEYWORDS) && !(m_mailbox->GetPermanentFlags() & ImapFlags::FLAG_STAR)) ||
MessageSetCommand::IsUnnecessary(protocol);
}
/***********************************************************************************
**
**
** Store::CanExtendWith
***********************************************************************************/
BOOL ImapCommands::Store::CanExtendWith(const MessageSetCommand* command) const
{
// Store can only be extended if keyword value is the same
return MessageSetCommand::CanExtendWith(command) &&
!static_cast<const ImapCommands::Store*>(command)->m_keyword.Compare(m_keyword);
}
/***********************************************************************************
**
**
** Store::PrepareToSend
***********************************************************************************/
OP_STATUS ImapCommands::Store::PrepareToSend(IMAP4& protocol)
{
// Cut up sequences to small pieces, to prevent command lines that are too long (bug #289140)
if (m_message_set.RangeCount() > 300)
{
ImapCommands::Store* split = OP_NEW(Store, (m_mailbox, 0, 0, m_flags, m_keyword));
if (!split)
return OpStatus::ERR_NO_MEMORY;
split->DependsOn(this, protocol);
return m_message_set.SplitOffRanges(300, split->m_message_set);
}
return OpStatus::OK;
}
/***********************************************************************************
**
**
** Store::WriteToOfflineLog
***********************************************************************************/
OP_STATUS ImapCommands::Store::WriteToOfflineLog(OfflineLog& offline_log)
{
OpINT32Vector message_ids;
RETURN_IF_ERROR(PrepareSetForOffline(message_ids));
if (m_flags & FLAG_DELETED)
{
if (m_flags & ADD_FLAGS)
RETURN_IF_ERROR(offline_log.RemoveMessages(message_ids, FALSE));
else
RETURN_IF_ERROR(offline_log.MessagesMovedFromTrash(message_ids));
}
if (m_flags & FLAG_SEEN)
{
RETURN_IF_ERROR(offline_log.ReadMessages(message_ids, m_flags & ADD_FLAGS));
}
if (m_flags & FLAG_ANSWERED)
{
for (unsigned i = 0; i < message_ids.GetCount(); i++)
RETURN_IF_ERROR(offline_log.ReplyToMessage(message_ids.Get(i)));
}
if (m_flags & KEYWORDS)
{
for (unsigned i = 0; i < message_ids.GetCount(); i++)
{
if (m_flags & ADD_FLAGS)
RETURN_IF_ERROR(offline_log.KeywordAdded(message_ids.Get(i), m_keyword));
else
RETURN_IF_ERROR(offline_log.KeywordRemoved(message_ids.Get(i), m_keyword));
}
}
return OpStatus::OK;
}
/***********************************************************************************
**
**
** Store::AppendCommand
***********************************************************************************/
OP_STATUS ImapCommands::Store::AppendCommand(OpString8& command, IMAP4& protocol)
{
OpString8 tmp_string;
OpString8 message_set_string;
RETURN_IF_ERROR(m_message_set.GetString(message_set_string));
return command.AppendFormat("%sSTORE %s %s%sFLAGS%s (%s)",
m_flags & USE_UID ? "UID " : "",
message_set_string.CStr(),
m_flags & ADD_FLAGS ? "+" : "",
m_flags & REMOVE_FLAGS ? "-" : "",
m_flags & SILENT ? ".SILENT" : "",
GetStoreFlags(tmp_string));
}
/***********************************************************************************
**
**
** Store::GetStoreFlags
***********************************************************************************/
const char* ImapCommands::Store::GetStoreFlags(OpString8& tmp_string)
{
if (m_flags & FLAG_ANSWERED)
OpStatus::Ignore(tmp_string.Append("\\Answered"));
if (m_flags & FLAG_FLAGGED)
OpStatus::Ignore(tmp_string.AppendFormat("%s\\Flagged", tmp_string.HasContent() ? " " : ""));
if (m_flags & FLAG_SEEN)
OpStatus::Ignore(tmp_string.AppendFormat("%s\\Seen", tmp_string.HasContent() ? " " : ""));
if (m_flags & FLAG_DELETED)
OpStatus::Ignore(tmp_string.AppendFormat("%s\\Deleted", tmp_string.HasContent() ? " " : ""));
if (m_flags & KEYWORDS)
OpStatus::Ignore(tmp_string.AppendFormat("%s%s", tmp_string.HasContent() ? " " : "", m_keyword.CStr()));
return tmp_string.CStr();
}
///////////////////////////////////////////
// MessageDelete
///////////////////////////////////////////
/***********************************************************************************
** Permanently deleting messages
** - Mark message deleted
** - If UIDPLUS available
** - If IMAP Trash folder
** 1) copy to trash (with SpecialExpungeCopy)
** 2) flag as \deleted in source folder and UID expunge from source folder
** 3) flag as \deleted in trash folder and UID expunge from trash folder (done in SpecialExpungeCopy::OnCopyUID)
** - Else
** 1) flag as \deleted
** 2) do UID EXPUNGE
** - Else
** 0) Search for messages that are deleted and have a UID that's not in the set we're deleting
** i.e. the messages in trash that we don't want to delete
** 1) Remove the \Deleted flag from the messages found in 0)
** 2) Do an EXPUNGE
** 3) Add the \Deleted flag back to the messages found in 0)
**
** MessageDelete::GetExpandedQueue
***********************************************************************************/
ImapCommandItem* ImapCommands::MessageDelete::GetExpandedQueue(IMAP4& protocol)
{
// Flag messages as \deleted
OpAutoPtr<ImapCommands::Store> flag_as_deleted (OP_NEW(ImapCommands::Store, (m_mailbox, 0, 0,
USE_UID | Store::ADD_FLAGS | Store::SILENT | Store::FLAG_DELETED)));
if (!flag_as_deleted.get() || OpStatus::IsError(flag_as_deleted->GetMessageSet().Copy(m_message_set)))
return NULL;
// Check if UIDPLUS is available
if (protocol.GetCapabilities() & ImapFlags::CAP_UIDPLUS)
{
// do UID EXPUNGE to remove the message from the source folder
ImapCommands::UidExpunge * uid_expunge = OP_NEW(ImapCommands::UidExpunge, (m_mailbox, 0, 0));
if (!uid_expunge || OpStatus::IsError(uid_expunge->GetMessageSet().Copy(m_message_set)))
{
OP_DELETE(uid_expunge);
return NULL;
}
uid_expunge->DependsOn(flag_as_deleted.get(), protocol);
if (m_trash_folder && m_mailbox != m_trash_folder)
{
// copy to trash
ImapCommands::SpecialExpungeCopy *special_expunge_copy = OP_NEW(ImapCommands::SpecialExpungeCopy, (m_mailbox, m_trash_folder, 0, 0));
if (!special_expunge_copy || OpStatus::IsError(special_expunge_copy->GetMessageSet().Copy(m_message_set)))
{
OP_DELETE(special_expunge_copy);
return NULL;
}
flag_as_deleted->DependsOn(special_expunge_copy, protocol);
flag_as_deleted.release();
return special_expunge_copy;
}
}
else
{
// Search for messages that are deleted and have a UID that's not in the set we're deleting
ImapCommands::Search* search = OP_NEW(ImapCommands::Search, (m_mailbox, 0, 0,
Search::FOR_UID | Search::BY_UID | Search::NOT | Search::DELETED));
if (!search || OpStatus::IsError(search->GetMessageSet().Copy(m_message_set)))
return NULL;
search->DependsOn(flag_as_deleted.get(), protocol);
// Remove the \Deleted flag from the messages found in 1)
ImapCommandItem* undelete = OP_NEW(ImapCommands::StoreResults, (m_mailbox,
USE_UID | Store::REMOVE_FLAGS | Store::SILENT | Store::FLAG_DELETED));
if (!undelete)
return NULL;
undelete->DependsOn(search, protocol);
// Do an EXPUNGE
ImapCommandItem* expunge = OP_NEW(ImapCommands::Expunge, (m_mailbox));
if (!expunge)
return NULL;
expunge->DependsOn(undelete, protocol);
// Add the \Deleted flag back to the messages found in 1)
ImapCommandItem* add_delete = OP_NEW(ImapCommands::StoreResults, (m_mailbox,
USE_UID | Store::ADD_FLAGS | Store::SILENT | Store::FLAG_DELETED));
if (!add_delete)
return NULL;
add_delete->DependsOn(expunge, protocol);
}
return flag_as_deleted.release();
}
/***********************************************************************************
**
**
** MessageDelete::WriteToOfflineLog
***********************************************************************************/
OP_STATUS ImapCommands::MessageDelete::WriteToOfflineLog(OfflineLog& offline_log)
{
OpINT32Vector message_ids;
RETURN_IF_ERROR(PrepareSetForOffline(message_ids));
for (unsigned i = 0; i < message_ids.GetCount(); i++)
{
OpString8 internet_location;
if (OpStatus::IsSuccess(MessageEngine::GetInstance()->GetStore()->GetMessageInternetLocation(message_ids.Get(i), internet_location)))
RETURN_IF_ERROR(offline_log.RemoveMessage(internet_location));
}
return OpStatus::OK;
}
///////////////////////////////////////////
// UidExpunge
///////////////////////////////////////////
/***********************************************************************************
**
**
** UidExpunge::AppendCommand
***********************************************************************************/
OP_STATUS ImapCommands::UidExpunge::AppendCommand(OpString8& command, IMAP4& protocol)
{
OpString8 message_set_string;
RETURN_IF_ERROR(m_message_set.GetString(message_set_string));
return command.AppendFormat("UID EXPUNGE %s", message_set_string.CStr());
}
///////////////////////////////////////////
// SpecialDeleteCopy
///////////////////////////////////////////
/***********************************************************************************
**
**
** SpecialDeleteCopy::OnCopyUid
***********************************************************************************/
OP_STATUS ImapCommands::SpecialExpungeCopy::OnCopyUid(IMAP4& protocol, unsigned uid_validity, OpINT32Vector& source_set, OpINT32Vector& dest_set)
{
OpStatus::Ignore(MoveCopy::OnCopyUid(protocol, uid_validity, source_set, dest_set));
ImapCommands::MessageSet destination_set;
for (unsigned i = 0; i < dest_set.GetCount(); i++)
{
destination_set.InsertRange(dest_set.Get(i), dest_set.Get(i));
}
// permanently delete the messages from trash
OpAutoPtr<ImapCommands::MessageDelete> delete_messages (OP_NEW(ImapCommands::MessageDelete, (m_to_mailbox, 0, 0)));
if (!delete_messages.get() || OpStatus::IsError(delete_messages->GetMessageSet().Copy(destination_set)))
return OpStatus::ERR;
return protocol.GetBackend().GetConnection(m_to_mailbox).InsertCommand(delete_messages.release());
}
///////////////////////////////////////////
// MessageMarkAsDeleted
///////////////////////////////////////////
/***********************************************************************************
**
**
** MessageMarkAsDeleted::GetExpandedQueue
***********************************************************************************/
ImapCommandItem* ImapCommands::MessageMarkAsDeleted::GetExpandedQueue(IMAP4& protocol)
{
if (m_trash_folder)
{
OpAutoPtr<ImapCommands::SpecialMarkAsDeleteCopy> copy_to_trash (OP_NEW(ImapCommands::SpecialMarkAsDeleteCopy, (m_mailbox, m_trash_folder, 0, 0)));
if (!copy_to_trash.get() || OpStatus::IsError(copy_to_trash->GetMessageSet().Copy(m_message_set)))
return NULL;
ImapCommands::MessageDelete* delete_command = OP_NEW(ImapCommands::MessageDelete, (m_mailbox, 0, 0));
if (!delete_command || OpStatus::IsError(delete_command->GetMessageSet().Copy(m_message_set)))
{
OP_DELETE(delete_command);
return NULL;
}
delete_command->DependsOn(copy_to_trash.get(), protocol);
return copy_to_trash.release();
}
else
{
ImapCommands::Store* queue = OP_NEW(ImapCommands::Store, (m_mailbox, 0, 0,
ImapCommands::USE_UID | ImapCommands::Store::ADD_FLAGS | Store::SILENT | ImapCommands::Store::FLAG_DELETED | ImapCommands::Store::FLAG_SEEN));
if (!queue || OpStatus::IsError(queue->GetMessageSet().Copy(m_message_set)))
{
OP_DELETE(queue);
return NULL;
}
return queue;
}
}
/***********************************************************************************
**
**
** MessageMarkAsDeleted::WriteToOfflineLog
***********************************************************************************/
OP_STATUS ImapCommands::MessageMarkAsDeleted::WriteToOfflineLog(OfflineLog& offline_log)
{
OpINT32Vector message_ids;
RETURN_IF_ERROR(PrepareSetForOffline(message_ids));
return offline_log.RemoveMessages(message_ids, FALSE);
}
///////////////////////////////////////////
// SpecialMarkAsDeleteCopy
///////////////////////////////////////////
/***********************************************************************************
**
**
** SpecialMarkAsDeleteCopy::OnCopyUid
***********************************************************************************/
OP_STATUS ImapCommands::SpecialMarkAsDeleteCopy::OnCopyUid(IMAP4& protocol, unsigned uid_validity, OpINT32Vector& source_set, OpINT32Vector& dest_set)
{
OpStatus::Ignore(MoveCopy::OnCopyUid(protocol, uid_validity, source_set, dest_set));
// mark the messages as \seen in the Trash folder
OpAutoPtr<ImapCommands::Store> mark_seen (OP_NEW(ImapCommands::Store, (m_to_mailbox, 0, 0,
ImapCommands::USE_UID | ImapCommands::Store::ADD_FLAGS | Store::SILENT | ImapCommands::Store::FLAG_SEEN)));
RETURN_OOM_IF_NULL(mark_seen.get());
for (unsigned i = 0; i < dest_set.GetCount(); i++)
{
RETURN_IF_ERROR(mark_seen->GetMessageSet().InsertRange(dest_set.Get(i), dest_set.Get(i)));
}
return protocol.GetBackend().GetConnection(m_to_mailbox).InsertCommand(mark_seen.release());
}
///////////////////////////////////////////
// MessageMarkAsSpam
///////////////////////////////////////////
/***********************************************************************************
**
**
** MessageMarkAsSpam::GetExpandedQueue
***********************************************************************************/
ImapCommandItem* ImapCommands::MessageMarkAsSpam::GetExpandedQueue(IMAP4& protocol)
{
const char* keyword_spam = "$Junk";
const char* keyword_not_spam = "$NotJunk";
OpAutoPtr<ImapCommands::Store> remove_keyword (OP_NEW(ImapCommands::Store, (m_mailbox, 0, 0,
ImapCommands::USE_UID | ImapCommands::Store::REMOVE_FLAGS | ImapCommands::Store::SILENT | ImapCommands::Store::KEYWORDS, m_mark_as_spam ? keyword_not_spam : keyword_spam)));
OpAutoPtr<ImapCommands::Store> add_keyword (OP_NEW(ImapCommands::Store, (m_mailbox, 0, 0,
ImapCommands::USE_UID | ImapCommands::Store::ADD_FLAGS | ImapCommands::Store::SILENT | ImapCommands::Store::KEYWORDS, m_mark_as_spam ? keyword_spam : keyword_not_spam)));
if (!add_keyword.get() || !remove_keyword.get() ||
OpStatus::IsError(remove_keyword->GetMessageSet().Copy(m_message_set)) ||
OpStatus::IsError(add_keyword->GetMessageSet().Copy(m_message_set)))
return NULL;
add_keyword->DependsOn(remove_keyword.get(), protocol);
if (m_to_folder)
{
ImapCommands::Move * move_to_folder = OP_NEW(ImapCommands::Move, (m_mailbox, m_to_folder, 0, 0));
if (!move_to_folder || OpStatus::IsError(move_to_folder->GetMessageSet().Copy(m_message_set)))
{
OP_DELETE(move_to_folder);
return NULL;
}
move_to_folder->DependsOn(add_keyword.get(), protocol);
}
add_keyword.release();
return remove_keyword.release();
}
/***********************************************************************************
**
**
** MessageMarkAsSpam::WriteToOfflineLog
***********************************************************************************/
OP_STATUS ImapCommands::MessageMarkAsSpam::WriteToOfflineLog(OfflineLog& offline_log)
{
OpINT32Vector message_ids;
RETURN_IF_ERROR(PrepareSetForOffline(message_ids));
return offline_log.MarkMessagesAsSpam(message_ids, m_mark_as_spam);
}
///////////////////////////////////////////
// MessageUndelete
///////////////////////////////////////////
/***********************************************************************************
**
**
** MessageUndelete::GetExpandedQueue
***********************************************************************************/
ImapCommandItem* ImapCommands::MessageUndelete::GetExpandedQueue(IMAP4& protocol)
{
OpAutoPtr<ImapCommands::Store> remove_deleted_flag (OP_NEW(ImapCommands::Store, (m_mailbox, 0, 0,
ImapCommands::USE_UID | ImapCommands::Store::REMOVE_FLAGS | Store::SILENT | ImapCommands::Store::FLAG_DELETED)));
RETURN_VALUE_IF_NULL(remove_deleted_flag.get(), NULL);
RETURN_VALUE_IF_ERROR(remove_deleted_flag->GetMessageSet().Copy(m_message_set), NULL);
if (m_to_folder)
{
OpAutoPtr<ImapCommands::Move> move_from_trash_to_inbox (OP_NEW(ImapCommands::Move, (m_mailbox, m_to_folder, 0, 0)));
RETURN_VALUE_IF_NULL(move_from_trash_to_inbox.get(), NULL);
RETURN_VALUE_IF_ERROR(move_from_trash_to_inbox->GetMessageSet().Copy(m_message_set), NULL);
move_from_trash_to_inbox->DependsOn(remove_deleted_flag.get(), protocol);
move_from_trash_to_inbox.release();
}
return remove_deleted_flag.release();
}
/***********************************************************************************
**
**
** MessageUndelete::WriteToOfflineLog
***********************************************************************************/
OP_STATUS ImapCommands::MessageUndelete::WriteToOfflineLog(OfflineLog& offline_log)
{
OpINT32Vector message_ids;
RETURN_IF_ERROR(PrepareSetForOffline(message_ids));
return offline_log.MessagesMovedFromTrash(message_ids);
}
|
#include "randomzie.h"
#include "utilities.h"
uint32_t randomize::rangeInt(uint32_t min, uint32_t max)
{
uint32_t bufVal = 0;
getrandom(&bufVal, sizeof(uint32_t), GRND_NONBLOCK);
return bufVal % (max - min) + min;
}
string randomize::cookie(uint32_t min, uint32_t max)
{
stringstream buffer("");
uint32_t len = randomize::rangeInt(min, max);
for (uint32_t i = 0; i < len; i++)
{
buffer << randomize::paramName(6, 12)
<< "="
<< randomize::paramName(12, 32)
<< "; ";
}
return buffer.str();
}
string randomize::queryString(uint32_t min, uint32_t max)
{
stringstream buffer("");
uint32_t len = randomize::rangeInt(min, max);
for (uint32_t i = 0; i < len; i++)
{
if (i > 0)
{
buffer << "&";
}
buffer << randomize::paramName(6, 12)
<< "="
<< randomize::escapedValue(64, 128);
}
return buffer.str();
}
string randomize::path(uint32_t min, uint32_t max)
{
stringstream buffer("");
uint32_t len = randomize::rangeInt(min, max);
for (uint32_t i = 0; i < len; i++)
{
buffer << "/" << randomize::paramName(4, 12);
}
return buffer.str();
}
string randomize::paramName(uint32_t min, uint32_t max)
{
stringstream buffer("");
uint32_t len = randomize::rangeInt(min, max);
uint32_t tick = 0;
for (uint32_t i = 0; i < len; i++)
{
tick = randomize::rangeInt(0, 100);
if (tick < 40)
{
buffer << (char)randomize::rangeInt('a', 'z');
}
else if (tick > 60)
{
buffer << (char)randomize::rangeInt('A', 'Z');
}
else
{
buffer << (char)randomize::rangeInt('0', '9');
}
}
return buffer.str();
}
string randomize::escapedValue(uint32_t min, uint32_t max)
{
stringstream buffer("");
uint32_t len = randomize::rangeInt(min, max);
char *buf = new char[len];
getrandom(buf, len, GRND_NONBLOCK);
uint32_t charRead = 0;
for (uint32_t i = 0; i < len; i++)
{
charRead = (0xff & buf[i]);
if ((charRead >= 48 && charRead <= 57) || (charRead >= 65 && charRead <= 90) || (charRead >= 97 && charRead <= 122) || charRead == 64)
{
buffer << buf[i];
}
else if (charRead == 0)
{
buffer << "%20";
}
else
{
if (charRead <= 0xf)
{
buffer << "%0" << hex << charRead;
}
else
{
buffer << "%" << hex << charRead;
}
}
}
delete buf;
return buffer.str();
}
string randomize::json(uint32_t min, uint32_t max)
{
stringstream buffer("");
stringstream close("");
uint32_t len = randomize::rangeInt(min, max);
for (uint32_t i = 0; i < len; i++)
{
buffer << "{\"" << randomize::paramName(6, 12) << "\":";
close << "}";
}
buffer << "1" << close.str();
return buffer.str();
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<cmath>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define pi acos(-1.0)
using namespace std;
typedef long long LL;
LL k[310],v[310],f[310][310][2];
bool a[310][310];
bool gcd(LL a,LL b) {
while (b) {
LL t = a;a = b;b = t%b;
}
return (a > 1);
}
int main() {
int t,n;
scanf("%d",&t);
while (t--) {
scanf("%d",&n);
for (int i = 1;i <= n; i++) scanf("%I64d",&k[i]);
for (int i = 1;i <= n; i++) scanf("%I64d",&v[i]);
for (int i = 1;i <= n; i++)
for (int j = i+1;j <= n; j++)
a[i][j] = gcd(k[i],k[j]);
memset(f,0,sizeof(f));
for (int len = 1;len < n;len++)
for (int i = 1;i+len <= n; i++) {
int j = i+len;
if (a[i][j] && (f[i+1][j-1][1] > 0 || i+1 > j-1)) f[i][j][1] = f[i+1][j-1][1] + v[i] + v[j];
for (int k = i;k < j; k++) {
if (f[i][k][1] > 0 && f[k+1][j][1] > 0) f[i][j][1] = max(f[i][j][1],f[i][k][1]+f[k+1][j][1]);
f[i][j][0] = max(f[i][j][0],f[i][k][0]+f[k+1][j][0]);
}
f[i][j][0] = max(f[i][j][1],f[i][j][0]);
}
printf("%I64d\n",f[1][n][0]);
}
return 0;
}
|
/*
* terrain.h
* 02564_Framework
*
* Created by J. Andreas Bærentzen on 02/02/10.
* Copyright 2010 __MyCompanyName__. All rights reserved.
*
*/
#ifndef __TERRAIN_H__
#define __TERRAIN_H__
#include <CGLA/Vec3f.h>
#include <GLGraphics/User.h>
#include <GLGraphics/ShaderProgram.h>
/** This class represents a terrain. It is very simple: The terrain is synthesized using noise
and once created we can query height and normal at a given 2D location or render the thing. */
class Terrain: public GLGraphics::HeightMap
{
float A = 150;
float delta = 0.035;
float x0=12.231, y0=7.91;
const int GridXMin = 0;
const int GridYMin = 0;
const int GridXMax = 512;
const int GridYMax = 512;
public:
/// Construct terrain with amplitude A and scaling delta.
Terrain() {}
/// Returns height at given 2D location
float height(const CGLA::Vec3f&) const;
/// Returns normal at given 2D location
CGLA::Vec3f normal(const CGLA::Vec3f&) const;
/// Draw using OpenGL: Assumes a reasonable shading program is used.
void draw(GLGraphics::ShaderProgramDraw&);
// The dummy functions below don't do anything but allow the terrain to be a
// replacement for an editable terrain.
void edit(const CGLA::Vec3f&, float amplitude, int n=5) {}
void smooth(const CGLA::Vec3f&, float amplitude, int n=5) {}
void reinit() {}
void smooth() {}
CGLA::Vec3f ray_trace(const CGLA::Vec3f &p0, const CGLA::Vec3f &dir) const {}
};
#endif
|
# define size 50000
# include <stdio.h>
# include <stdlib.h>
# include <time.h>
# include <locale.h>
#include<iostream>
using namespace std;
class masiv
{int mas1[size],mas[size];
public :
void masiv::zapoln(){int i;
for (i=0;i<size;i++)
{
mas1[i]=rand()%100 ;
mas[i]=mas1[i];
}
return ; }
void rewrite(){
int i;
for (i=0;i<size;i++)
mas[i]=mas1[i];
return ;
}
void masiv::print(int n)
{
int i ;
for(i=0;i<n;i++)
cout<<"\n"<<mas[i];
}
int poiskvub(int n, int p,int *iter);
int poisklin(int n,int p,int *iter);
void sortbuble(int *iter,int *obmen,int n);
void sortmin(int *iter,int *obmen,int n);
void sort(int *iter,int *obmen,int n);
void sortsl(int *iter,int *obmen,int mast[size],int n ,int k);
};
int masiv:: poiskvub(int n, int p,int *iter)
{
iter=0;
int l=0,r=n-1,m;
while(l<=r)
{iter++;
m=(r+l)/2;
if ( mas[m]==p)
{return m;
break;}
else
if (mas[m]>p)
r=m-1;
if (mas[m]<p)
l=m+1;
}
return(-1);}
int masiv ::poisklin(int n,int p,int *iter)
{iter=0;int i;
for(i=0;i<n;i++){
iter++;
if (mas[i]==p)
return i ;}
return (-1);}
void masiv::sortbuble(int *iter,int *obmen,int n)
{iter=0;obmen=0;
int i,j,k;
for(i=n;i>0;i--)
{
for (j=0;(i-1)>j;j++)
{ iter++;
if (mas[j]>mas[j+1])
{ obmen++;
k=mas[j+1];
mas[j+1]=mas[j];
mas[j]=k;
}
}
}
return;
}
void masiv::sortmin(int *iter,int *obmen,int n)
{iter=0;obmen=0;
int i,j,d,c,min;
for(i=0;i<n-1;i++)
{
min=mas[i];
d=i;
for (j=i;n>j;j++)
{iter++;
if (min > mas[j])
{ obmen++;
min=mas[j];
d=j;
}
}
c = mas[i];
mas[i] = min;
mas[d] = c;
} return;
}
void masiv::sort(int *iter,int *obmen,int n)
{iter=0;obmen=0;int i,j,pos,a1;
for (i=1;i<n;i++)
{
pos=-1;
for (j=i-1;j>=0;j--)
{iter++;
if (mas[i]>mas[j])
{obmen++;
pos=j;
break;
}
}
a1=mas[i];
for(j=i-1;pos<j;j--)
{
mas[j+1]=mas[j];
}
mas[pos+1]=a1;
}
}
void sl(int *iter,int *obmen,int mas[size],int mast[size],int n1 ,int k1, int n2 ,int k2)
{iter=0;obmen=0; n1-=1;n2-=1;k1-=1;k2-=1;
int i=n1 ,j= n2 ,k=n1,l ;
while((i<=k1)&&(j<=k2))
{ iter++;
if( mas[i]<mas[j])
{
mast[k] = mas[i];
i++;
k++;
obmen++;
}
else
{
mast[k]= mas[j];
j++;
k++;
obmen++;}
}if (i<=k1)
for (i;i<=k1;i++)
{
mast[k]=mas[i];
k++;obmen++;
}
else
for (j;j<=k2;j++)
{mast[k]=mas[j];
k++;obmen++;
}for (l=n1;l<=k2;l++)
mas[l]=mast[l];
}
void masiv::sortsl(int *iter,int *obmen,int mast[size],int n ,int k)
{int s ;
if(n==k) {return ;}
s=(n+k)/2;
masiv.sortsl( iter,obmen,mast,n,s);
masiv.sortsl( iter,obmen,mast,s+1,k);
sl(iter,obmen,mas,mast,n,s,s+1,k);
}
void main ()
{
clock_t start, finish;
int n=20,g=1,t=size,j,p,mast[size],k,m,*iter,*obmen;
double duration1,duration2,duration3,duration4;
masiv M ;
setlocale(LC_CTYPE,"Russian");
cout<<"1-заполнение массива\n2-запись массива\n3-сортировка массива\n4-сортировка минимальными\n5-сортировка вставкой\n6-перезапись\n7-поиск бинарного\n8-поиск линейный\n9-сортировка слиянием\n10-очистка экрана\n11-выход\n";
while (g!=0){
cin>>g;
switch(g)
{
case 1: M.zapoln();
break;
case 2:cout<<"введите номер до которого хотите записать но учтите что массив будет записываться до 25 элемента\n";
cin>>n;
if (n<=25)
M.print(n);
else
cout<<"введите другой номер\n";
break;
case 3 :
cout<<"введите позицию до которой хотите сортировать массив\n";
cin>>n;
start = clock();
M.sortbuble(iter,obmen,n);
finish = clock();duration1 = (double)(finish - start) / CLOCKS_PER_SEC;
cout<<"seconds\n"<<duration1;
cout<<"число сравнений "<<iter<< "\n число обменов "<<obmen <<"\n";
break;
case 4:
cout<<"введите позицию до которой хотите сортировать массив \n ";
cin>>n ;
start = clock();
M.sortmin(iter,obmen,n);
finish = clock();duration2 = (double)(finish - start) / CLOCKS_PER_SEC;
cout<<"seconds\n"<<duration2;
cout<<"число сравнений "<<iter<< "\n число обменов "<<obmen <<"\n";
break;
case 5 :
cout<<"введите позицию до которой хотите сортировать массив\n";
cin>>n;
start = clock();
M.sort(iter,obmen,n);
finish = clock();
duration3 = (double)(finish - start) / CLOCKS_PER_SEC;
cout<<"seconds\n"<<duration3;
cout<<"число сравнений "<<iter<< "\n число обменов "<<obmen <<"\n";
break;
case 6:
M.rewrite();
break;
case 7:
cout<<"перед поиском сортируйте массив ,введите число и введите до какой позиции искать\n ";
cin>>p>>n;
j=M.poiskvub(n,p,iter);
if (j!=-1)
{ cout<<"даное число находиться под номером"<<j+1<<" \n" ;
cout<<"число сравнений "<<iter<<" \n ";}
else
cout<<"данного числа нет\n ";
break;
case 8:
cout<<"введите число и введите до какой позиции искать ";
cin>>p>>n;
j=M.poisklin(n,p,iter);
if (j!=-1)
{cout<<"даное число находиться под номером"<<j+1<<" \n" ;
cout<<"число сравнений "<<iter<<" \n ";
}
else
cout<<"данного числа нет ";break;
case 9:cout<<"введите позицию с которой хотите сортировать массив и до которой хотите сортировать массив \n "; cin>>m>>k;
start = clock();
M.sortsl(iter,obmen,mast,m,k);
finish = clock();duration4 = (double)(finish - start) / CLOCKS_PER_SEC;
cout<<"seconds\n"<<duration4;
cout<<"число сравнений "<<iter<< "\n число обменов "<<obmen <<"\n";
break;
case 10:system("cls");
cout<<"1-заполнение массива\n2-запись массива\n3-сортировка массива\n4-сортировка минимальными\n5-сортировка вставкой\n6-перезапись\n7-поиск бинарного\n8-поиск линейный\n9-сортировка слиянием\n10-очистка экрана\n11-выход\n";
break;
case 11: g=0 ;break;
default:
cout<<"введите номер\n";
break;
}
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef DESKTOP_DRAG_OBJECT_H
#define DESKTOP_DRAG_OBJECT_H
#ifdef DRAG_SUPPORT
#include "modules/dragdrop/dragdrop_data_utils.h"
#include "modules/inputmanager/inputaction.h"
#include "modules/util/adt/opvector.h"
#include "modules/util/opstring.h"
#include "modules/pi/OpDragObject.h"
class DesktopDragObject;
class DesktopDragDataIterator : public OpDragDataIterator
{
public:
DesktopDragDataIterator(DesktopDragObject *obj) : object(obj), current_data_idx(0) {}
BOOL First();
BOOL Next();
BOOL IsFileData() const;
BOOL IsStringData() const;
const OpFile* GetFileData();
const uni_char* GetStringData();
const uni_char* GetMimeType();
void Remove();
private:
DesktopDragObject* object;
unsigned current_data_idx;
};
class DesktopDragObject : public OpDragObject
{
private:
friend class DesktopDragDataIterator;
class DragDataElm
{
public:
enum DataType
{
DND_DATATYPE_NONE,
DND_DATATYPE_FILE,
DND_DATATYPE_STRING
};
union
{
OpFile* m_file;
OpString* m_string;
};
DataType m_type;
OpString m_mime;
OP_STATUS Construct(const uni_char* path_or_data, const uni_char* mime, BOOL is_file = FALSE);
DragDataElm() : m_type(DND_DATATYPE_NONE) {}
~DragDataElm()
{
if(m_type == DND_DATATYPE_STRING)
OP_DELETE(m_string);
else if(m_type == DND_DATATYPE_FILE)
OP_DELETE(m_file);
}
};
DesktopDragDataIterator iterator;
void RemoveIfExists(const uni_char* format, BOOL is_file);
public:
// Drop stuff
enum InsertType
{
INSERT_INTO,
INSERT_BEFORE,
INSERT_AFTER,
INSERT_BETWEEN
};
DesktopDragObject(OpTypedObject::Type type) :
iterator(this),
m_type(type),
m_action(NULL),
m_object(NULL),
m_source(NULL),
m_bitmap(NULL),
m_drop_type(DROP_NONE),
m_visual_drop_type(DROP_NONE),
m_suggested_drop_type(DROP_UNINITIALIZED),
m_effects_allowed(DROP_UNINITIALIZED),
m_protected_mode(FALSE),
m_read_only(FALSE),
m_id(0),
m_insert_type(INSERT_INTO),
m_suggested_insert_type(INSERT_INTO),
m_drop_capture_locked(false),
m_restore_capture_when_lost(false)
{
}
virtual ~DesktopDragObject();
// OpDragObject overrides
OpDragDataIterator& GetDataIterator() { return iterator; }
OpTypedObject::Type GetType() { return m_type; }
virtual void SetBitmap(OpBitmap* bitmap);
virtual const OpBitmap* GetBitmap() const { return m_bitmap; }
virtual void SetBitmapPoint(const OpPoint& bitmap_point) { m_bitmap_point = bitmap_point; }
virtual const OpPoint& GetBitmapPoint() const { return m_bitmap_point; }
virtual void SetSource(OpTypedObject* source) { m_source = source; }
virtual OpTypedObject* GetSource() const { return m_source; }
virtual OP_STATUS SetData(const uni_char *path_or_data, const uni_char *format, BOOL is_file, BOOL remove_if_exists);
virtual void ClearData() { m_data.DeleteAll(); }
virtual unsigned GetDataCount() { return m_data.GetCount(); }
virtual void SetEffectsAllowed(unsigned effects) { m_effects_allowed = effects; }
virtual unsigned GetEffectsAllowed() const { return m_effects_allowed; }
virtual void SetVisualDropType(DropType drop_type);
virtual DropType GetVisualDropType() const { return m_visual_drop_type; }
virtual void SetDropType(DropType drop_type) { m_drop_type = drop_type; }
virtual DropType GetDropType() const { return m_drop_type; }
virtual void SetProtectedMode(BOOL protected_mode) { m_protected_mode = protected_mode; }
virtual BOOL IsInProtectedMode() { return m_protected_mode; }
virtual void SetReadOnly(BOOL read_only) { m_read_only = read_only; }
virtual BOOL IsReadOnly() { return m_read_only; }
virtual void SetSuggestedDropType(DropType drop_type) { m_suggested_drop_type = drop_type; }
virtual DropType GetSuggestedDropType() const { return m_suggested_drop_type; }
// desktop extensions
// Set BOTH drop types at the same time
void SetDesktopDropType(DropType drop_type)
{
m_drop_type = drop_type;
m_visual_drop_type = drop_type; // set the visual type as well, to keep the two in sync
}
/*
* Set/Get a unique id to be associated with this drag object
*/
void SetID(int32 id) { m_id = id; }
INT32 GetID() { return m_id; }
/*
* Set/Get a object (typically a OpWidget-derived class) to be associated with this drag object
*/
void SetObject(OpTypedObject* object) { m_object = object; }
OpTypedObject* GetObject() const { return m_object; }
OP_STATUS SetURL(const uni_char* url)
{
RETURN_IF_ERROR(DragDrop_Data_Utils::AddURL(this, url));
return OpStatus::OK;
}
const uni_char* GetURL() const
{
if (m_urls.GetCount() == 0)
return NULL;
return m_urls.Get(0)->CStr();
}
OP_STATUS AddURL(OpString* url)
{
RETURN_IF_ERROR(DragDrop_Data_Utils::AddURL(this, *url));
OP_DELETE(url);
url = NULL;
return OpStatus::OK;
}
const OpVector<OpString>& GetURLs() const { return m_urls; }
OP_STATUS SetTitle(const uni_char* title)
{
return DragDrop_Data_Utils::SetDescription(this, title);
}
const uni_char* GetTitle()
{
return DragDrop_Data_Utils::GetDescription(this);
}
/**
* Update the desktop part of the content so that it is the same
* as the core part. Desktop code does not always access the core
* part so a synchronization is needed. Should be called in the
* platform implementation of OpDragManager::SetDragObject()
*/
OP_STATUS SynchronizeCoreContent();
OP_STATUS SetImageURL(const uni_char* image_url) { return m_image_url.Set(image_url); }
const uni_char* GetImageURL() { return m_image_url.CStr(); }
OP_STATUS SetAction(OpInputAction* action) { m_action = OpInputAction::CopyInputActions(action); return m_action ? OpStatus::OK : OpStatus::ERR_NO_MEMORY; }
OpInputAction* GetAction() { return m_action; }
/*
* Set/Get multiple unique ids to be associated with this drag object.
*/
OP_STATUS AddID(INT32 id) { return m_ids.Add(id); }
INT32 GetIDCount() { return m_ids.GetCount(); }
INT32 GetID(INT32 index) { return m_ids.Get(index); }
const OpINT32Vector& GetIDs() { return m_ids; }
void ResetDrop()
{
m_drop_type = DROP_NOT_AVAILABLE;
m_visual_drop_type = DROP_NOT_AVAILABLE;
m_suggested_drop_type = DROP_NOT_AVAILABLE;
m_insert_type = INSERT_INTO;
m_suggested_insert_type = INSERT_INTO;
}
void SetInsertType(InsertType insert_type) { m_insert_type = insert_type; }
InsertType GetInsertType() const { return m_insert_type; }
void SetSuggestedInsertType(InsertType insert_type) { m_suggested_insert_type = insert_type; }
InsertType GetSuggestedInsertType() const { return m_suggested_insert_type; }
BOOL IsDropAvailable() const { return m_drop_type != DROP_NOT_AVAILABLE; }
BOOL IsDropCopy() const { return m_drop_type == DROP_COPY; }
BOOL IsDropMove() const { return m_drop_type == DROP_MOVE; }
BOOL IsInsertInto() const { return m_insert_type == INSERT_INTO; }
BOOL IsInsertBefore() const { return m_insert_type == INSERT_BEFORE; }
BOOL IsInsertAfter() const { return m_insert_type == INSERT_AFTER; }
/**
* Some platforms need to know if a lost drag'n'drop event capture should be ignored or not.
* They can check on this flag. The flag is set when the drop happens, and cleared when the drop
* has been completed.
*/
void SetDropCaptureLocked(bool capture_locked) { m_drop_capture_locked = capture_locked; }
bool HasDropCaptureLock() { return m_drop_capture_locked; }
void SetRestoreCaptureWhenLost(bool restore) { m_restore_capture_when_lost = restore; }
bool GetRestoreCaptureWhenLost() { return m_restore_capture_when_lost; }
private:
OpTypedObject::Type m_type;
OpInputAction* m_action;
OpTypedObject* m_object;
OpTypedObject* m_source;
OpBitmap* m_bitmap;
OpPoint m_bitmap_point;
OpAutoVector<OpString> m_urls;
OpString m_image_url;
OpAutoVector<DragDataElm> m_data;
DropType m_drop_type;
DropType m_visual_drop_type;
DropType m_suggested_drop_type;
unsigned m_effects_allowed;
BOOL m_protected_mode;
BOOL m_read_only;
INT32 m_id;
OpINT32Vector m_ids;
InsertType m_insert_type;
InsertType m_suggested_insert_type;
bool m_drop_capture_locked; // true when a capture should not be lost. Used by Windows.
bool m_restore_capture_when_lost; // true when capture should be set back if it changes during a drag
};
#endif // DRAG_SUPPORT
#endif // DESKTOP_DRAG_OBJECT_H
|
#include <iostream>
#include "CmdMessenger.h"
using namespace std;
using namespace serial;
class Oi
{
public:
oi(){}
void cb(cmd::CmdReceived& m){}
};
int main(int argc, char *argv[])
{
cmd::CmdMessenger oi;
Oi haha;
oi.teste(haha, &Oi::cb);
return 0;
}
|
//Declaración de constantes
const int boton = 2; //Da el nombre “boton” al pin 2
void setup()
{
//Inicializa la comunicación serial a 9600 bits por segundo
Serial.begin(9600);
pinMode(boton, INPUT); //Configura el pin "boton" como entrada digital
}
void loop()
{
//Almacena la información de la entrada digital en la variable “estadoDeBoton”
int estadoDeBoton = digitalRead(boton);
//Envia por el puerto serial la información almacenada en “estadoDeBoton”,
//esta información será visualizada en el monitor serial.
Serial.println(estadoDeBoton);
//Espera 100 milisegundos entre cada lectura
delay(100);
}
|
/*
* 题目:740. 删除并获得点数
* 链接:https://leetcode-cn.com/problems/delete-and-earn/
* 知识点:动态规划
*/
class Solution {
private:
int rob(vector<int>& nums) {
int n = nums.size();
if (n == 1) {
return nums[0];
}
int first = nums[0], second = max(nums[0], nums[1]);
for (int i = 2; i < n; i++) {
int temp = second;
second = max(first + nums[i], second);
first = temp;
}
return second;
}
public:
// 转化为打家劫舍,未优化版本(nums 中元素范围比较小时,效率比较高)
int deleteAndEarn(vector<int>& nums) {
if (nums.size() == 1) {
return nums[0];
}
int maxVal = 0;
for (int num : nums) {
maxVal = max(maxVal, num);
}
vector<int> sum(maxVal + 1, 0), dp(maxVal + 1, 0);
for (int num : nums) {
sum[num] += num;
}
dp[1] = sum[1], dp[2] = max(sum[1], sum[2]);
for (int i = 3; i <= maxVal; i++) {
dp[i] = max(dp[i - 1], dp[i - 2] + sum[i]);
}
return dp[maxVal];
}
// 优化版,当 nums 中元素的范围比较大时,这种方法比较好用
int deleteAndEarn(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end());
vector<int> sum = {nums[0]};
int ans = 0;
for (int i = 1; i < n; i++) {
if (nums[i] == nums[i - 1]) {
sum.back() += nums[i];
} else if (nums[i] == nums[i - 1] + 1) {
sum.push_back(nums[i]);
} else {
ans += rob(sum);
sum = {nums[i]};
}
}
ans += rob(sum);
return ans;
}
};
|
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
#include<sstream>
#include<fstream>
#include<iomanip>
#include<time.h>
#include <iostream>
#include "IA.h"
#include "GameDimens.h"
#include "Game.h"
using namespace std;
int main()
{
Game game(WIDTH, HEIGHT, "Ignis");
return 0;
}
|
#include "serverSNFS.h"
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
path server_directory;
int main(int argc, char* argv[]){
if(argc != 5){
cout << "Usage is ./serverSNFS -port port# -mount directory" << endl;
exit(EXIT_FAILURE);
}
check_values(argv[1], "-port");
check_port(argv[2], "port#");
int serverPort = stoi(argv[2]);
check_values(argv[3], "-mount");
//get path of mountable file
path curr_path = current_path(); //gets current path
path p = argv[4];
server_directory = curr_path / p;
check_directory(server_directory);
//Create variables
int serverSocket;
int newSocket;
int rc;
struct sockaddr_in serverAddress;
struct sockaddr_storage serverStorage;
socklen_t addr_size;
//Create socket.
if((serverSocket = socket(PF_INET, SOCK_STREAM, 0)) < 0){
cout << "Server socket error" << endl;
exit(EXIT_FAILURE);
}
else{
cout << "Server socket successful." << endl;
}
// Configure settings of the server address struct
serverAddress.sin_family = AF_INET; // Address = Internet
serverAddress.sin_port = htons(serverPort); // Set port Number
//Set IP to localhost 127.0.0.1 is the local host
serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1");
//Set bits of the padding field to 0
memset(serverAddress.sin_zero, '\0', sizeof(serverAddress.sin_zero));
//Bind to the socket
if ((rc = bind(serverSocket, (struct sockaddr *) &serverAddress, sizeof(serverAddress))) < 0){
cout << "Server bind error" << endl;
exit(EXIT_FAILURE);
}
else{
cout << "Server bind success" << endl;
}
//Listen on the socket, max of 20 connections to be queued
if ((rc = listen(serverSocket, 20)) < 0) {
cout << "Server-listen() error" << endl;
close(serverSocket);
exit(EXIT_FAILURE);
}
else{
cout << "Server-Ready for client connection..." << endl;
}
//Make threads and accept calls to create new sockets for incoming connections
pthread_t tid[50];
int i = 0;
while(1){
addr_size = sizeof(serverStorage);
if((newSocket = accept(serverSocket, (struct sockaddr *) &serverStorage, &addr_size)) < 0){
cout << "Server-accept() error" << endl;
close(serverSocket);
exit(EXIT_FAILURE);
}
else{
cout << "Server-accept() worked" << endl;
}
if( pthread_create(&tid[i], NULL, socketThread, &newSocket) != 0){
cout << "Failed to create new thread" << endl;
}
if(i >= 20){
i = 0;
while(i < 20){
pthread_join(tid[i++],NULL);
}
i = 0;
}
}
}
void * socketThread(void *arg){
char server_msg[5000];
char client_msg[5000];
int newSocket = *((int *)arg);
fstream inFile;
string openfilename = "";
while(1){
memset(client_msg, 0, sizeof(client_msg));
memset(server_msg, 0, sizeof(server_msg));
if(recv(newSocket , client_msg , sizeof(client_msg) , 0) <= 0){
cout << "Receive from client failed\n" << endl;
break;
}
if(strncmp(client_msg, "readdir ", 8) == 0){
cout << "Returning all filenames from the given directory" << endl;
cout << "Recieved from Client: " << client_msg << endl;
if(client_msg[8] != '/'){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server no '/': ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be readdir /test");
}
else{
string readdir;
int i = 8;
while(client_msg[i] != '\0'){
readdir += client_msg[i];
i++;
}
string getNames = getDirectories(readdir);
const char * fileNames = getNames.c_str();
strcpy(server_msg, fileNames);
}
}
else if (strncmp(client_msg, "read ", 5) == 0) {
cout << "Reading bytes from file" << endl;
cout << "Recieved from Client: " << client_msg << endl;
if(client_msg[5] != '/'){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server no '/': ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be read /test.txt");
}
string readFile;
string size;
string offset;
int i = 5;
while(client_msg[i] != ' '){
readFile += client_msg[i];
i++;
}
i += 1;
while(client_msg[i] != ' ' && client_msg[i] != '\0'){
size += client_msg[i];
i++;
}
//cout << size << endl;
i += 1;
while(client_msg[i] != ' ' && client_msg[i] != '\0'){
offset += client_msg[i];
i++;
}
if(!is_digits(size) || !is_digits(offset) || size.empty() || offset.empty()){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server digit error: ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be read /test.txt 100 10");
}
else if(readFile.substr( readFile.length() - 4 ) != ".txt"){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server no '.txt': ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be read /test.txt 100 10");
}
else if(!inFile.is_open()){
cout << "No File is open" << endl;
strcpy(server_msg,"No File is open: ");
strcat(server_msg, readFile.c_str());
}
else{
cout << "Current file is not open we will open it! " << endl;
cout << openfilename << endl;
inFile.close();
path temp = server_directory / readFile;
string fileLocation = temp.string();
inFile.open(fileLocation);
openfilename = readFile;
int total = stoi(size);
int start = stoi(offset);
cout << "Starting at: " << offset << ", total is: " << total << endl;
if(total > (sizeof(server_msg) - 25)){
strcpy(server_msg, "Size is larger than the buffer of the message");
}
else{
inFile.seekg(start, ios::beg);
inFile.read(server_msg, total);
cout <<"Server msg: " << server_msg <<endl;
}
}
}
else if(strncmp(client_msg, "write ", 6) == 0){
cout << "Writing data to the file" << endl;
cout << "Recieved from Client: " << client_msg << endl;
if(client_msg[6] != '/'){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server no '/': ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be write /test.txt 100 example input");
}
string writeFile;
string writeInfo;
string offset;
int i = 6;
while(client_msg[i] != ' '){
writeFile += client_msg[i];
i++;
}
i += 1;
while(client_msg[i] != ' ' && client_msg[i] != '\0'){
offset += client_msg[i];
i++;
}
//cout << size << endl;
i += 1;
while(client_msg[i] != '\0'){
writeInfo += client_msg[i];
i++;
}
if(!is_digits(offset)){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server digit error: ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be write /test.txt 100 text to write in");
}
else if(writeFile.substr( writeFile.length() - 4 ) != ".txt"){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server no '.txt': ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be write /test.txt 100 text to write in");
}
else if(!inFile.is_open()){
cout << "No File is open" << endl;
strcpy(server_msg,"No File is open: ");
strcat(server_msg, writeFile.c_str());
}
else{
if(writeFile.compare(openfilename) != 0){
cout << "Current file is not open we will open it! " << endl;
cout << openfilename << endl;
inFile.close();
path temp = server_directory / writeFile;
string fileLocation = temp.string();
inFile.open(fileLocation);
openfilename = writeFile;
}
int start = stoi(offset);
cout << "Starting at: " << offset << ", write data is: \n" << writeInfo << endl;
int length = writeInfo.length();
char writeArray[length+1];
int fileLength;
int begin = inFile.tellg();
inFile.seekg(0, ios::end);
int end = inFile.tellg();
fileLength = end - begin;
cout << "Start is: " << start << " Filelength is: " << fileLength << endl;
if(start > fileLength){
strcat(server_msg, "Offset too large");
}else{
strcpy(writeArray, writeInfo.c_str());
inFile.seekp(start, ios::beg);
inFile.write(writeArray, length);
strcat(server_msg, "\nWrote to file");
inFile.close();
path temp = server_directory / openfilename;
string fileLocation = temp.string();
inFile.open(fileLocation);
}
}
}
else if(strncmp(client_msg, "opendir ", 8) == 0){
cout << "Recieved from Client: " << client_msg << endl;
strcpy(server_msg,"Opening Directory");
}
else if(strncmp(client_msg, "open ", 5) == 0){
cout << "Opening the file with given directory" << endl;
cout << "Recieved from Client: " << client_msg << endl;
if(client_msg[5] != '/'){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server no '/': ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be open /test.txt");
}
else{
string openFile;
int i = 5;
while(client_msg[i] != '\0'){
openFile += client_msg[i];
i++;
}
if(openFile.substr( openFile.length() - 4 ) != ".txt"){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server no '.txt': ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be open /test.txt");
}
else{
path temp = server_directory / openFile;
string fileLocation = temp.string();
cout << fileLocation << endl;
if (inFile.is_open()) {
cout << "File is already open: " << openfilename << endl;
cout << openfilename << endl;
inFile.close();
inFile.open(fileLocation);
openfilename = openFile;
}
else{
inFile.open(fileLocation);
if(!inFile){
cout << "Cannot open file, file does not exist. Creating new file" << endl;
strcpy(server_msg,"Cannot open file, file does not exist. Creating new file: ");
strcat(server_msg, openFile.c_str());
inFile.open(fileLocation, fstream::in | fstream::out | fstream::trunc);
openfilename = openFile;
}
else{
cout << "Successfully opened file" << endl;
strcpy(server_msg,"Successfully opened file: ");
strcat(server_msg, openFile.c_str());
openfilename = openFile;
}
}
}
}
}
else if(strncmp(client_msg, "close ", 6) == 0){
inFile.close();
/*
cout << "Closing file with given pathname" << endl;
cout << "Recieved from Client: " << client_msg << endl;
if(client_msg[6] != '/'){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server no '/': ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be close /test.txt");
}
else{
string openFile;
int i = 6;
while(client_msg[i] != '\0'){
openFile += client_msg[i];
i++;
}
if(openFile.substr( openFile.length() - 4 ) != ".txt"){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server no '.txt': ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be close /test.txt");
}
else{
if(!inFile.is_open()){
cout << "No File is open" << endl;
strcpy(server_msg,"No File is open, tried to close: ");
strcat(server_msg, openFile.c_str());
}
else{
string closeFileName = openFile;
if(closeFileName.compare(openfilename) == 0){
cout << "Closing file" << endl;
cout << openfilename << endl;
strcpy(server_msg,"Closed: ");
strcat(server_msg, openfilename.c_str());
inFile.close();
openfilename = "";
}
else{
cout << "File :" << endl;
cout << openfilename << " not currently open" <<endl;
strcpy(server_msg,"No File named: ");
strcat(server_msg, closeFileName.c_str());
strcat(server_msg, " is open. Current open file is: ");
strcat(server_msg, openfilename.c_str());
}
}
}
} */
}
else if(strncmp(client_msg, "releasedir ", 11) == 0){
cout << "Recieved from Client: " << client_msg << endl;
strcpy(server_msg,"Releasing Directory");
}
else if(strncmp(client_msg, "create ", 7) == 0){
cout << "Create the file with given name" << endl;
cout << "Recieved from Client: " << client_msg << endl;
if(client_msg[7] != '/'){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server no '/': ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be create /test.txt");
}
else{
string newFile;
int i = 7;
while(client_msg[i] != '\0'){
newFile += client_msg[i];
i++;
}
if(newFile.substr( newFile.length() - 4 ) != ".txt"){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server no '.txt': ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be create /test.txt");
}
else if(inFile.is_open()){
cout << "A File is open" << endl;
strcpy(server_msg,"Please close file before you create: ");
strcat(server_msg, openfilename.c_str());
}
else{
int val = createFile(newFile);
if(val == -1){
strcpy(server_msg,"Failure creating directory: ");
strcat(server_msg, "-1");
}
else{
strcpy(server_msg,"Success creating directory: ");
strcat(server_msg, "1");
}
}
}
}
else if(strncmp(client_msg, "flush ", 6) == 0){
cout << "Recieved from Client: " << client_msg << endl;
strcpy(server_msg,"Recieved flush");
}
else if(strncmp(client_msg, "release ", 8) == 0){
cout << "Recieved from Client: " << client_msg << endl;
strcpy(server_msg,"Recieved release");
}
else if(strncmp(client_msg, "mkdir ", 6) == 0){
cout << "Making directory with given pathname" << endl;
cout << "Recieved from Client: " << client_msg << endl;
if(client_msg[6] != '/' || client_msg[7] == '\0' || client_msg[7] == ' '){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server no '/': ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be mkdir /test");
}
else{
string mkdirName;
int i = 6;
while(client_msg[i] != '\0'){
mkdirName += client_msg[i];
i++;
}
int val = make_directory(mkdirName);
if(val == -1){
strcpy(server_msg,"Failure creating directory: ");
strcat(server_msg, "-1");
}
else{
strcpy(server_msg,"Success creating directory: ");
strcat(server_msg, "1");
}
}
}
else if(strncmp(client_msg, "truncate ", 9) == 0){
cout << "Truncating file" << endl;
cout << "Recieved from Client: " << client_msg << endl;
if(client_msg[9] != '/'){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server no '/': ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be truncate /test.txt 10");
}
else{
string trunFile;
string offsetTrunc;
int i = 9;
while(client_msg[i] != ' '){
trunFile += client_msg[i];
i++;
}
i += 1;
while(client_msg[i] != '\0'){
offsetTrunc += client_msg[i];
i++;
}
if(!is_digits(offsetTrunc) || offsetTrunc.empty()){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server digit error: ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be truncate /test.txt 10");
}
else if(trunFile.substr( trunFile.length() - 4 ) != ".txt"){
cout << "Incorrect format" << endl;
strcpy(server_msg,"Incorrect format recieved by server no '.txt': ");
strcat(server_msg, client_msg);
strcat(server_msg, "\nExample should be truncate /test.txt 10");
}
else if(!inFile.is_open()){
cout << "No File is open" << endl;
strcpy(server_msg,"No File is open: ");
strcat(server_msg, trunFile.c_str());
}
else if(trunFile.compare(openfilename) != 0){
cout << "Current file is not open! " << endl;
cout << openfilename << endl;
strcpy(server_msg,"Written file is not open, current file open: ");
strcat(server_msg, openfilename.c_str());
}
else{
int end = stoi(offsetTrunc);
path p = server_directory / trunFile;
int truncVal = truncate((p.string()).c_str(), end);
cout << truncVal << endl;
if(truncVal == 0){
strcpy(server_msg,"Successfully truncated file");
}
else{
strcpy(server_msg,"Truncating failure");
}
}
}
}
else if(strncmp(client_msg, "getattr ", 8) == 0){
cout << "Getting attributes" << endl;
cout << "Recieved from Client: " << client_msg << endl;
strcpy(server_msg,"getattr success! ");
//strcat(server_msg, client_msg);
}
else{
cout << "Incorrect input" << endl;
strcpy(server_msg,"Incorrect input recieved by server: ");
strcat(server_msg, client_msg);
}
// Send message to the client socket
//if(strncmp(client_msg, "read ", 5) == 0){
if(send(newSocket,server_msg,sizeof(server_msg),0) <= 0){
cout << "Send to client failed\n" << endl;
break;
}
//}
}
cout << "Exit socketThread" << endl;
close(newSocket);
}
//checks to see if two values are the same
void check_values(string value, string correct){
if(value.compare(correct) != 0){
cout << "\nUsage is ./serverSNFS -port port# -mount directory" << endl;
cout << "Error was in the argument " << correct << endl;
cout << "You wrote: " << value << "\n" << endl;
exit(EXIT_FAILURE);
}
}
//checks to see if the port is a valid port number and whether the input is an integer
void check_port(string number, string correct){
try {
int test = stoi(number);
if(test < 1024 || test > 65535){
cout << "\nUsage is ./serverSNFS -port port# -mount directory" << endl;
cout << "Error was in the argument " << correct << endl;
cout << "Not a nonnegative digit greater than or equal to 0 and less than 65535! You wrote: " << number << endl;
cout << "Try something like 12345" << endl;
exit(EXIT_FAILURE);
}
else{
cout << "\nValid port number" << endl;
}
}
catch(std::exception const & e){
cout << "\nUsage is ./serverSNFS -port port# -mount directory" << endl;
cout << "Error was in the argument " << correct << endl;
cout << "Not a nonnegative digit greater than or equal to 0 and less than 65535! You wrote: " << number << endl;
cout << "Try something like 12345" << endl;
exit(EXIT_FAILURE);
}
}
//check to see whether the directory exists, if it doesnt then create it,
void check_directory(path directory){
path p = directory;
//cout << p;
if(exists(p)){ //checks to see whether path p exists
if (is_regular_file(p)){ //checks to see whether this is a file
cout << "\nUsage is ./serverSNFS -port port# -mount directory" << endl;
cout << "Error was in the argument directory" << endl;
cout << p << " is a file not a directory" << endl;
exit(EXIT_FAILURE);
}
else if (is_directory(p)){ // checks if p is directory?
cout << p << " is a valid directory" << endl;
}
else{
cout << "\nUsage is ./serverSNFS -port port# -mount directory" << endl;
cout << "Error was in the argument directory" << endl;
cout << p << " is neither a file nor a directory" << endl;
exit(EXIT_FAILURE);
}
}
//the given path does not exist so we will create
else{
cout << "Given directory does not exist would you like to create it? Please Type Y for yes, N for no" << endl;
string val;
cin >> val;
while(val.compare("Y") != 0 && val.compare("N") != 0){
cout << "Please Type Y for yes, N for no" << endl;
cin >> val;
}
if(val.compare("Y") == 0){
cout << "Creating Directory" << endl;
try{
create_directories(p);
cout << "Created Directory" << endl;
}
catch(std::exception const & e){
cout << "Failure creating Directory" << endl;
exit(EXIT_FAILURE);
}
}
else{
cout << "Typed N exiting program, Directory will not be created." << endl;
exit(EXIT_FAILURE);
}
}
}
//mkdir function
int make_directory(string mkdirName){
path newDir = server_directory / mkdirName;
cout << "Given path: " << newDir << endl;
if(exists(newDir)){ //checks to see whether path p exists
if (is_regular_file(newDir)){ //checks to see whether this is a file
cout << "This is already a file\n" << endl;
return -1;
}
else if (is_directory(newDir)){ // checks if p is directory?
cout << "Already a directory\n" << endl;
return -1;
}
else{
cout << "Neither file nor directory but exists\n" << endl;
return -1;
}
}
try{
create_directories(newDir);
cout << "Created Directory\n" << endl;
}catch(std::exception const & e){
cout << "Failure creating Directory\n" << endl;
return -1;
}
return 1;
}
string getDirectories(string readdirName){
path p = server_directory / readdirName;
string newPath = p.string();
string contains;
DIR *d;
const char * c = newPath.c_str();
struct dirent *dir;
d = opendir(c);
if (d) {
while ((dir = readdir(d)) != NULL) {
contains = contains + dir->d_name + " ";
}
closedir(d);
}
else{
contains = "Directory doesn't exist";
}
return contains;
}
int createFile(string createFile){
path newFile = server_directory / createFile;
ifstream tempFile;
cout << "Given path: " << newFile << endl;
if(exists(newFile)){ //checks to see whether path p exists
if (is_regular_file(newFile)){ //checks to see whether this is a file
cout << "This is already a file\n" << endl;
return -1;
}
else if (is_directory(newFile)){ // checks if p is directory?
cout << "Already a directory\n" << endl;
return -1;
}
else{
cout << "Neither file nor directory but exists\n" << endl;
return -1;
}
}
string newpath = newFile.string();
tempFile.open(newpath);
if(!tempFile){
tempFile.open(newpath, fstream::in | fstream::out | fstream::trunc);
tempFile.close();
return 1;
}
return -1;
}
bool is_digits(string str){
if(str.empty()){
return false;
}
return str.find_first_not_of("0123456789") == std::string::npos;
}
|
#ifndef DOOR_H
#define DOOR_H
#include <string>
#include "UsableObject.h"
namespace ld
{
struct Door : public UsableObject
{
Door(int x_, int y_, std::string type_, std::string name_, double rotation_)
: x(x_),
y(y_),
type(type_),
name(name_),
rotation(rotation_),
locked(false),
open(false)
{}
int x, y;
std::string type, name;
float rotation;
bool locked, open;
};
}
#endif /* DOOR_H */
|
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <fstream>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
struct BankAccount {
int balance{0};
int overdraft_limit{-500};
void deposit(int amount) {
balance += amount;
std::cout << "deposited: " << amount << " balance: " << balance
<< std::endl;
}
bool withdraw(int amount) {
if (balance - amount >= overdraft_limit) {
balance -= amount;
std::cout << "withdrew: " << amount << " balance: " << balance
<< std::endl;
return true;
}
return false;
}
};
struct Command {
bool succeeded;
virtual void call() = 0;
virtual void undo() = 0;
};
struct BankAccountCommand : Command {
BankAccount &account;
enum Action { deposit, withdraw} action;
int amount;
BankAccountCommand(BankAccount &account, Action action, int amount)
: account(account), action(action), amount(amount)
{
succeeded = false;
}
void call() override {
switch (action) {
case deposit:
account.deposit(amount);
succeeded = true;
break;
case withdraw:
succeeded = account.withdraw(amount);
break;
}
}
void undo() override {
if (!succeeded) return;
switch (action) {
case deposit:
account.withdraw(amount);
break;
case withdraw:
account.deposit(amount);
break;
}
}
};
struct CompositeBankAccountCommand : std::vector<BankAccountCommand>, Command {
CompositeBankAccountCommand(std::initializer_list<BankAccountCommand> const& ilist)
: std::vector<BankAccountCommand>(ilist)
{}
void call() override {
for (auto& cmd : *this)
cmd.call();
}
void undo() override {
for (auto it=this->rbegin(); it!=this->rend(); ++it)
it->undo();
}
};
struct DependentCompositeCommand : CompositeBankAccountCommand {
DependentCompositeCommand(std::initializer_list<BankAccountCommand> const& ilist)
: CompositeBankAccountCommand(ilist) {}
void call() override {
bool ok = true;
for (auto &cmd : *this) {
if (ok) {
cmd.call();
ok = cmd.succeeded;
} else {
cmd.succeeded = false;
}
}
}
};
struct MoneyTransferCommand : DependentCompositeCommand {
MoneyTransferCommand(BankAccount &from, BankAccount &to, int amount)
: DependentCompositeCommand({
BankAccountCommand{from, BankAccountCommand::withdraw, amount},
BankAccountCommand{to, BankAccountCommand::deposit, amount}
}) {
}
};
int main() {
BankAccount ba;
std::vector<BankAccountCommand> cmds {
BankAccountCommand{ba, BankAccountCommand::deposit, 100},
BankAccountCommand{ba, BankAccountCommand::withdraw, 200}
};
std::cout << ba.balance << std::endl;
for (auto& cmd : cmds)
cmd.call();
std::cout << ba.balance << std::endl;
for (auto it=cmds.rbegin(); it!=cmds.rend(); ++it)
it->undo();
std::cout << ba.balance << std::endl;
BankAccount ba1, ba2;
ba1.deposit(100);
MoneyTransferCommand mtc {ba1, ba2, 5000};
mtc.call();
std::cout << ba1.balance << " " << ba2.balance << std::endl;
mtc.undo();
std::cout << ba1.balance << " " << ba2.balance << std::endl;
return 0;
}
|
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*-
*
* Copyright (C) 1995-2005 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef XPNODESET_H
#define XPNODESET_H
#include "modules/xpath/src/xpnode.h"
#include "modules/xpath/src/xpnodelist.h"
class XPath_NodeSet
: public XPath_NodeList
{
protected:
friend class XPath_NodeList;
XPath_Node **hashed;
unsigned capacity;
void InitL ();
void GrowL ();
static void TreeSort (XMLTreeAccessor *tree, XPath_NodeSet *nodeset);
XPath_Node *Find (XPath_Node *node);
public:
XPath_NodeSet ();
BOOL AddL (XPath_Context *context, XPath_Node *node);
void SortL ();
void Clear (XPath_Context *context);
BOOL Contains (XPath_Node *node);
};
#endif // XPNODESET_H
|
#ifndef STRING_TRIM_HPP
#define STRING_TRIM_HPP
#include <string>
namespace String
{
static std::string trimStart(std::string source, const std::string &trimChars = " \t\n\r\v\f")
{
return source.erase(0, source.find_first_not_of(trimChars));
}
static std::string trimEnd(std::string source, const std::string &trimChars = " \t\n\r\v\f")
{
return source.erase(source.find_last_not_of(trimChars) + 1);
}
static std::string trim(std::string source, const std::string &trimChars = " \t\n\r\v\f")
{
return trimStart(trimEnd(source, trimChars), trimChars);
}
}
#endif /* end of include guard : STRING_TRIM_HPP */
|
#ifndef HASH_MAP_HPP
#define HASH_MAP_HPP
// Pedro Escoboza
// A01251531
// TCB1004.500
// 21/11/2020
#include <memory>
#include <vector>
/**
* Implementation a hash table of constant size.
*
* @param T Type of the entry value
* @param K Type of the entry key
* @param Size Constant size of the hash table
* @param Hash Struct with overloaded operator() as with hash function
*/
template <class K, class T, class Hasher = std::hash<K>>
class HashMap {
using Entry = std::pair<const K, T>;
using EntryUPtr = std::unique_ptr<Entry>;
std::vector<EntryUPtr> m_table; // Associative table container for key value pairs
Hasher m_hasher; // Hashing struct with overloaded operator()
size_t m_bucketCount; // Number of buckets in the table
size_t m_size; // Number of entries in the table
public:
/**
* Default constructor for HastMap.
* Time: O(1)
* Space: O(1)
*
* @return HashMap
*/
HashMap(size_t bucket_count) : m_table{}, m_hasher{ Hasher{} }, m_bucketCount{ bucket_count }, m_size{0U} {
m_table.resize(m_bucketCount);
m_table.shrink_to_fit();
}
/**
* Insert a new element in the hash table if no element already has the key.
* Time: O(1)
* Space: O(1)
*
* @param key Key to insert
* @param value Value to map to the key
* @return Pointer to the newly inserted pair OR the previously mapped element
*/
const std::pair<bool, Entry*> insert(const K& key, const T& value);
/**
* Finds an element on the hash table.
* Time: O(1)
* Space: O(1)
*
* @param key Key to insert
* @return Pointer to the found entry or nullptr if not found
*/
Entry* find(const K& key);
/**
* Erases an entry with a given key.
* Time: O(1)
* Space: O(1)
*
* @param key Key of the entry to erase
*/
void erase(const K& key);
/**
* Returns the number of entries in the container.
* Time: O(1)
* Space: O(1)
*
* @return Container size
*/
size_t size() const { return m_size; }
/**
* Tells if the table is empty.
* Time: O(1)
* Space: O(1)
*
* @return Wether the table has elements
*/
bool empty() const { return m_size == 0U; }
/**
* Clears the content of the hash map.
* Time: O(1)
* Space: O(1)
*
* @return void
*/
void clear() {
m_table.clear();
m_table.resize(m_bucketCount);
}
/*
* Gets the number of filled buckets in the container.
* Time: O(1)
* Space: O(1)
*
* @return Number of filled buckets
*/
size_t bucket_count() const { return m_bucketCount; }
private:
/**
* Generates a container index mapped to the key.
* Time: O(1)
* Space: O(1)
*
* @param key Key of the entry to hash
* @return Index of the table mapped to the key
*/
size_t hash(const K& key) const;
/**
* Finds the node element of the given key.
* Protected helper for other functions
* Time: O(1)
* Space: O(1)
*
* @param key Key of the entry to hash
* @param [out] Node found found at the position
* @return Index of the table mapped to the key
*/
size_t findNode(const K& key, EntryUPtr*& node);
};
template<class K, class T, class Hasher>
inline const std::pair<bool, typename HashMap<K, T, Hasher>::Entry*> HashMap<K, T, Hasher>::insert(const K& key, const T& value){
EntryUPtr* res{nullptr};
size_t i{ findNode(key, res) };
// Check if the given position is
if (res != nullptr && *res != nullptr) {
// The key is occupied, return the element
return { false, m_table[i].get() };
}
else {
// Position was empty, insert
m_table[i] = std::make_unique<Entry>(key, value);
m_size++;
return { true, m_table[i].get() };
}
}
template<class K, class T, class Hasher>
inline typename HashMap<K, T, Hasher>::Entry* HashMap<K, T, Hasher>::find(const K& key){
EntryUPtr* res{ nullptr };
findNode(key, res);
return ((res != nullptr && *res != nullptr) ? res->get() : nullptr);
}
template<class K, class T, class Hasher>
inline void HashMap<K, T, Hasher>::erase(const K& key){
// Find the node
EntryUPtr* res{nullptr};
findNode(key, res);
// If it is found, delete it
if (res != nullptr && *res != nullptr) {
m_size--;
res->reset();
}
}
template<class K, class T, class Hasher>
inline size_t HashMap<K, T, Hasher>::hash(const K& key) const{
return m_hasher(key) % (m_bucketCount -1);
}
template<class K, class T, class Hasher>
inline size_t HashMap<K, T, Hasher>::findNode(const K& key, EntryUPtr*& node){
size_t startPos{ hash(key) };
if (m_table[startPos] == nullptr) {
// Not found
node = nullptr;
return startPos;
}
// Something found, compare the key to check for match
if (m_table[startPos]->first == key) {
// The X marks the spot!
node = &m_table[startPos];
return startPos;
}
// We got a collision, iterate until you get the key or null
// Get the starting position and wrap around the array looking for the key
for (size_t i{ 0U }; i < m_bucketCount; ++i) {
size_t wrapPos{ (startPos + i) % m_bucketCount };
if (m_table[wrapPos] == nullptr) {
// Not found
node = nullptr;
return wrapPos;
}
if (m_table[wrapPos]->first == key) {
// The mark was off, still got the treasure
node = &m_table[wrapPos];
return wrapPos;
}
}
// Worst case: full iteration
node = nullptr;
return -1;
}
#endif // !HASH_MAP_HPP
|
//
// GCastleEnemy.h
// Core
//
// Created by Max Yoon on 11. 7. 20..
// Copyright 2011년 __MyCompanyName__. All rights reserved.
//
#ifndef __Core__GCastleEnemy__
#define __Core__GCastleEnemy__
#include "GCastle.h"
class GIconGage;
class GCastleEnemy : public GCastle
{
public:
static GCastleEnemy* CreateCastle(GLayer* pInterfaceLayer, GLayer* pCastleLayer
, GStageInfo* pStageInfo, GStageInfo::GCastleFiles* pFiles
, GStageInfo::GCastlePositions* pPositions);
protected:
static bool CreateCastleGage(GLayer* pInterfaceLayer, GIconGage& cOutGage);
};
#endif
|
#pragma GCC optimize("Ofast")
#include <algorithm>
#include <bitset>
#include <deque>
#include <iostream>
#include <iterator>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
struct Node {
int data;
Node* next;
};
Node* head;
void insert(int x, int n) {
Node* temp = new Node();
temp->data = x;
temp->next = NULL;
if(n == 1) {
temp->next = head;
head = temp;
return;
}
Node* temp1 = head;
for(int i=1; i<n-1; i++) {
temp1 = temp1->next;
}
temp->next = temp1->next;
temp1->next = temp;
}
void print() {
Node* temp2=head;
while(temp2 != NULL) {
cout << temp2->data << " ";
temp2 = temp2->next;
}
cout << endl;
}
void reverseIterative() {
Node *dummy = NULL;
while(head != NULL) {
Node *Next = head->next;
head->next = dummy;
dummy = head;
head = Next;
}
head = dummy;
}
void reverseRecursive(Node* p) {
if(p->next == NULL) {
head = p;
return;
}
reverseRecursive(p->next);
Node *q = p->next;
q->next = p;
p->next = NULL;
}
int main(int argc, char* argv[]) {
abhisheknaiidu();
head = NULL;
insert(1,1);
insert(2,2);
insert(3,3);
insert(4,4);
print();
reverseIterative();
print();
// reverseRecursive(head);
print();
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.