blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 117 | path stringlengths 3 268 | src_encoding stringclasses 34
values | length_bytes int64 6 4.23M | score float64 2.52 5.19 | int_score int64 3 5 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | text stringlengths 13 4.23M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
e74fbd94e3fcfb5d8ae67d9356d04cc29cc6a8d3 | C++ | wzit/CPP-Actor-framework | /MyActor/actor/async_buffer.h | GB18030 | 19,822 | 2.890625 | 3 | [] | no_license | #ifndef __ASYNC_BUFFER_H
#define __ASYNC_BUFFER_H
#include <memory>
#include "my_actor.h"
struct async_buffer_close_exception {};
template <typename T>
class fixed_buffer
{
struct node
{
void destroy()
{
((T*)space)->~T();
#if (_DEBUG || DEBUG)
memset(space, 0xcf, sizeof(space));
#endif
}
template <typename Arg>
void set(Arg&& arg)
{
new(space)T(TRY_MOVE(arg));
}
T& get()
{
return *(T*)space;
}
__space_align char space[sizeof(T)];
};
public:
fixed_buffer(size_t maxSize)
{
assert(0 != maxSize);
_size = 0;
_index = 0;
_maxSize = maxSize;
_buffer = (node*)malloc(sizeof(node)*maxSize);
}
~fixed_buffer()
{
clear();
free(_buffer);
}
public:
size_t size() const
{
return _size;
}
size_t max_size() const
{
return _maxSize;
}
bool empty() const
{
return 0 == _size;
}
bool full() const
{
return _maxSize == _size;
}
void clear()
{
for (size_t i = 0; i < _size; i++)
{
const size_t t = _index + i;
_buffer[(t < _maxSize) ? t : (t - _maxSize)].destroy();
}
_index = 0;
_size = 0;
}
T& front()
{
assert(!empty());
const size_t i = _index + _size - 1;
return _buffer[(i < _maxSize) ? i : (i - _maxSize)].get();
}
void pop_front()
{
assert(!empty());
_size--;
const size_t i = _index + _size;
_buffer[(i < _maxSize) ? i : (i - _maxSize)].destroy();
}
template <typename Arg>
void push_back(Arg&& arg)
{
assert(!full());
const size_t i = (0 != _index) ? (_index - 1) : (_maxSize - 1);
_buffer[i].set(TRY_MOVE(arg));
_index = i;
_size++;
}
private:
size_t _maxSize;
size_t _size;
size_t _index;
node* _buffer;
};
/*!
@brief 첽Уд/ɫת
*/
template <typename T>
class async_buffer
{
struct push_pck
{
void operator ()(bool closed)
{
notified = true;
ntf(closed);
}
bool& notified;
trig_notifer<bool> ntf;
};
struct pop_pck
{
void operator ()(bool closed)
{
notified = true;
ntf(closed);
}
bool& notified;
trig_notifer<bool> ntf;
};
struct buff_push
{
template <typename Fst, typename... Args>
inline void operator ()(Fst&& fst, Args&&... args)
{
if (0 == _i)
{
_this->_buffer.push_back(TRY_MOVE(fst));
}
else
{
buff_push bp = { _this, _i - 1 };
bp(TRY_MOVE(args)...);
}
}
inline void operator ()()
{
assert(false);
}
async_buffer* const _this;
const size_t _i;
};
struct buff_pop
{
template <typename Fst, typename... Outs>
inline void operator ()(Fst& fst, Outs&... outs)
{
if (0 == _i)
{
fst = std::move(_this->_buffer.front());
}
else
{
buff_pop bp = { _this, _i - 1 };
bp(outs...);
}
}
inline void operator ()()
{
assert(false);
}
async_buffer* const _this;
const size_t _i;
};
public:
struct close_exception : public async_buffer_close_exception {};
public:
async_buffer(const shared_strand& strand, size_t buffLength, size_t halfLength = 0)
:_strand(strand), _closed(false), _buffer(buffLength)//, _pushWait(4), _popWait(4)
{
_halfLength = halfLength ? halfLength : buffLength / 2;
}
public:
/*!
@brief Ӷݣ͵ȴֱɹ
*/
template <typename... TMS>
void push(my_actor* host, TMS&&... msgs)
{
static_assert(sizeof...(TMS) > 0, "");
size_t pushCount = 0;
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
std::tuple<TMS&&...> msgsTup(TRY_MOVE(msgs)...);
#endif
_push(host, [&]()->bool
{
buff_push bp = { this, pushCount };
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
tuple_invoke(bp, msgsTup);
#else
bp((TMS&&)(msgs)...);
#endif
return sizeof...(TMS) == ++pushCount;
});
}
/*!
@brief ݣͷ
@return true ӳɹ
*/
template <typename TM>
bool try_push(my_actor* host, TM&& msg)
{
return !!_try_push(host, [&]()->bool
{
_buffer.push_back((TM&&)msg);
return true;
});
}
/*!
@brief ҳݣзŲ¾ͷ
@return ҳɹ˼
*/
template <typename... TMS>
size_t try_push(my_actor* host, TMS&&... msgs)
{
static_assert(sizeof...(TMS) > 1, "");
size_t pushCount = 0;
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
std::tuple<TMS&&...> msgsTup(TRY_MOVE(msgs)...);
#endif
return _try_push(host, [&]()->bool
{
buff_push bp = { this, pushCount };
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
tuple_invoke(bp, msgsTup);
#else
bp((TMS&&)(msgs)...);
#endif
return sizeof...(TMS) == ++pushCount;
});
}
/*!
@brief һʱڳݣеʱӾͷ
@return true ӳɹ
*/
template <typename TM>
bool timed_push(int tm, my_actor* host, TM&& msg)
{
return !!_timed_push(tm, host, [&]()->bool
{
_buffer.push_back((TM&&)msg);
return true;
});
}
/*!
@brief һʱڳӶݣеʱӾͷ
@return ҳɹ˼
*/
template <typename... TMS>
size_t timed_push(int tm, my_actor* host, TMS&&... msgs)
{
static_assert(sizeof...(TMS) > 1, "");
size_t pushCount = 0;
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
std::tuple<TMS&&...> msgsTup(TRY_MOVE(msgs)...);
#endif
return _timed_push(tm, host, [&]()->bool
{
buff_push bp = { this, pushCount };
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
tuple_invoke(bp, msgsTup);
#else
bp((TMS&&)(msgs)...);
#endif
return sizeof...(TMS) == ++pushCount;
});
}
/*!
@brief ǿӶݣоͶǰ
@return ˼
*/
template <typename... TMS>
size_t force_push(my_actor* host, TMS&&... msgs)
{
static_assert(sizeof...(TMS) > 0, "");
size_t pushCount = 0;
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
std::tuple<TMS&&...> msgsTup(TRY_MOVE(msgs)...);
#endif
return _force_push(host, [&]()->bool
{
buff_push bp = { this, pushCount };
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
tuple_invoke(bp, msgsTup);
#else
bp((TMS&&)(msgs)...);
#endif
return sizeof...(TMS) == ++pushCount;
}, [](const T&){});
}
template <typename Recovery, typename... TMS>
size_t force_push_recovery(my_actor* host, Recovery&& recovery, TMS&&... msgs)
{
static_assert(sizeof...(TMS) > 0, "");
size_t pushCount = 0;
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
std::tuple<TMS&&...> msgsTup(TRY_MOVE(msgs)...);
#endif
return _force_push(host, [&]()->bool
{
buff_push bp = { this, pushCount };
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
tuple_invoke(bp, msgsTup);
#else
bp((TMS&&)(msgs)...);
#endif
return sizeof...(TMS) == ++pushCount;
}, TRY_MOVE(recovery));
}
/*!
@brief һݣпվ͵ȴֱ
*/
T pop(my_actor* host)
{
__space_align char resBuf[sizeof(T)];
_pop(host, [&]()->bool
{
new(resBuf)T(std::move(_buffer.front()));
_buffer.pop_front();
return true;
});
BREAK_OF_SCOPE(
{
typedef T TP_;
((TP_*)resBuf)->~TP_();
});
return std::move(*(T*)resBuf);
}
/*!
@brief ҵݣв͵ȴֱɹ
*/
template <typename... OTMS>
void pop(my_actor* host, OTMS&... outs)
{
static_assert(sizeof...(OTMS) > 0, "");
size_t popCount = 0;
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
std::tuple<OTMS&...> outsTup(TRY_MOVE(outs)...);
#endif
_pop(host, [&]()->bool
{
buff_pop bp = { this, popCount };
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
tuple_invoke(bp, outsTup);
#else
bp(outs...);
#endif
_buffer.pop_front();
return sizeof...(OTMS) == ++popCount;
});
}
/*!
@brief ԵһݣΪվͷ
@return ɹõϢ
*/
template <typename OTM>
bool try_pop(my_actor* host, OTM& out)
{
size_t popCount = 0;
return !!_try_pop(host, [&]()->bool
{
out = std::move(_buffer.front());
_buffer.pop_front();
return true;
});
}
/*!
@brief ҳԵݣвʣµ
@return ҵõ
*/
template <typename... OTMS>
size_t try_pop(my_actor* host, OTMS&... outs)
{
static_assert(sizeof...(OTMS) > 1, "");
size_t popCount = 0;
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
std::tuple<OTMS&...> outsTup(TRY_MOVE(outs)...);
#endif
return _try_pop(host, [&]()->bool
{
buff_pop bp = { this, popCount };
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
tuple_invoke(bp, outsTup);
#else
bp(outs...);
#endif
_buffer.pop_front();
return sizeof...(OTMS) == ++popCount;
});
}
/*!
@brief һʱڳԵһݣеʱݾͷ
@return true ɹõϢ
*/
template <typename OTM>
bool timed_pop(int tm, my_actor* host, OTM& out)
{
return !!_timed_pop(tm, host, [&]()->bool
{
out = std::move(_buffer.front());
_buffer.pop_front();
return true;
});
}
/*!
@brief һʱڳԵݣеʱͷʣµ
@return ɹõϢ
*/
template <typename... OTMS>
size_t timed_pop(int tm, my_actor* host, OTMS&... outs)
{
static_assert(sizeof...(OTMS) > 1, "");
size_t popCount = 0;
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
std::tuple<OTMS&...> outsTup(TRY_MOVE(outs)...);
#endif
return _timed_pop(tm, host, [&]()->bool
{
buff_pop bp = { this, popCount };
#if (_MSC_VER >= 1900 || (__GNUG__*10 + __GNUC_MINOR__) <= 48)
tuple_invoke(bp, outsTup);
#else
bp(outs...);
#endif
_buffer.pop_front();
return sizeof...(OTMS) == ++popCount;
});
}
/*!
@brief עһpopϢֻ֪ͨһ
*/
template <typename Ntf>
void regist_pop_ntf(my_actor* host, Ntf&& ntf)
{
host->lock_quit();
host->send(_strand, [&]
{
if (!_buffer.empty())
{
ntf();
}
else
{
_popNtfQueue.push_back((Ntf&&)ntf);
}
});
host->unlock_quit();
}
/*!
@brief עһpushϢֻ֪ͨһ
*/
template <typename Ntf>
void regist_push_ntf(my_actor* host, Ntf&& ntf)
{
host->lock_quit();
host->send(_strand, [&]
{
if (_buffer.size() <= _halfLength)
{
ntf();
}
else
{
_pushNtfQueue.push_back((Ntf&&)ntf);
}
});
host->unlock_quit();
}
void close(my_actor* host, bool clearBuff = true)
{
host->lock_quit();
host->send(_strand, [&]
{
_closed = true;
if (clearBuff)
{
_buffer.clear();
}
while (!_pushWait.empty())
{
_pushWait.front()(true);
_pushWait.pop_front();
}
while (!_popWait.empty())
{
_popWait.front()(true);
_popWait.pop_front();
}
_pushNtfQueue.clear();
_popNtfQueue.clear();
});
host->unlock_quit();
}
size_t length(my_actor* host)
{
host->lock_quit();
size_t l = 0;
host->send(_strand, [&]
{
l = _buffer.size();
});
host->unlock_quit();
return l;
}
size_t snap_length()
{
return _buffer.size();
}
void reset()
{
assert(_closed);
_closed = false;
}
private:
async_buffer(const async_buffer&){};
void operator=(const async_buffer&){};
template <typename Func>
void _push(my_actor* host, Func&& h)
{
host->lock_quit();
while (true)
{
trig_handle<bool> ath;
bool notified = false;
bool isFull = false;
bool closed = false;
host->send(_strand, [&]
{
closed = _closed;
if (!_closed)
{
while (true)
{
bool break_ = true;
isFull = _buffer.full();
if (!isFull)
{
break_ = h();
if (!_popWait.empty())
{
_popWait.back()(false);
_popWait.pop_back();
}
else if (!_popNtfQueue.empty())
{
_popNtfQueue.front()();
_popNtfQueue.pop_front();
}
}
else
{
_pushWait.push_front({ notified });
_pushWait.front().ntf = host->make_trig_notifer_to_self(ath);
}
if (break_)
{
break;
}
}
}
});
if (closed)
{
host->unlock_quit();
throw close_exception();
}
if (!isFull)
{
host->unlock_quit();
return;
}
if (host->wait_trig(ath))
{
host->unlock_quit();
throw close_exception();
}
}
host->unlock_quit();
}
template <typename Func>
size_t _try_push(my_actor* host, Func&& h)
{
host->lock_quit();
bool closed = false;
size_t pushCount = 0;
host->send(_strand, [&]
{
closed = _closed;
if (!_closed)
{
while (true)
{
bool break_ = true;
if (!_buffer.full())
{
pushCount++;
break_ = h();
if (!_popWait.empty())
{
_popWait.back()(false);
_popWait.pop_back();
}
else if (!_popNtfQueue.empty())
{
_popNtfQueue.front()();
_popNtfQueue.pop_front();
}
}
if (break_)
{
break;
}
}
}
});
if (closed)
{
host->unlock_quit();
throw close_exception();
}
host->unlock_quit();
return pushCount;
}
template <typename Func>
size_t _timed_push(int tm, my_actor* host, Func&& h)
{
host->lock_quit();
long long utm = (long long)tm * 1000;
size_t pushCount = 0;
while (true)
{
trig_handle<bool> ath;
typename msg_list<push_pck>::iterator mit;
bool notified = false;
bool isFull = false;
bool closed = false;
host->send(_strand, [&]
{
closed = _closed;
if (!_closed)
{
while (true)
{
bool break_ = true;
isFull = _buffer.full();
if (!isFull)
{
pushCount++;
break_ = h();
if (!_popWait.empty())
{
_popWait.back()(false);
_popWait.pop_back();
}
else if (!_popNtfQueue.empty())
{
_popNtfQueue.front()();
_popNtfQueue.pop_front();
}
}
else
{
_pushWait.push_front({ notified });
_pushWait.front().ntf = host->make_trig_notifer_to_self(ath);
mit = _pushWait.begin();
}
if (break_)
{
break;
}
}
}
});
if (!closed)
{
if (!isFull)
{
host->unlock_quit();
return pushCount;
}
long long bt = get_tick_us();
if (!host->timed_wait_trig(utm / 1000, ath, closed))
{
host->send(_strand, [&]
{
if (!notified)
{
_pushWait.erase(mit);
}
});
if (notified)
{
closed = host->wait_trig(ath);
}
}
utm -= get_tick_us() - bt;
if (utm < 1000)
{
host->unlock_quit();
return pushCount;
}
}
if (closed)
{
host->unlock_quit();
throw close_exception();
}
}
host->unlock_quit();
return pushCount;
}
template <typename Func, typename Recovery>
size_t _force_push(my_actor* host, Func&& h, Recovery&& rf)
{
host->lock_quit();
bool closed = false;
size_t lostCount = 0;
host->send(_strand, [&]
{
closed = _closed;
if (!_closed)
{
while (true)
{
if (_buffer.full())
{
lostCount++;
rf(_buffer.front());
_buffer.pop_front();
}
bool break_ = h();
if (!_popWait.empty())
{
_popWait.back()(false);
_popWait.pop_back();
}
else if (!_popNtfQueue.empty())
{
_popNtfQueue.front()();
_popNtfQueue.pop_front();
}
if (break_)
{
break;
}
}
}
});
if (closed)
{
host->unlock_quit();
throw close_exception();
}
host->unlock_quit();
return lostCount;
}
template <typename Func>
void _pop(my_actor* host, Func&& out)
{
host->lock_quit();
while (true)
{
trig_handle<bool> ath;
bool notified = false;
bool isEmpty = false;
bool closed = false;
host->send(_strand, [&]
{
closed = _closed;
if (!_closed)
{
while (true)
{
bool break_ = true;
isEmpty = _buffer.empty();
if (!isEmpty)
{
break_ = out();
}
else
{
_popWait.push_front({ notified });
_popWait.front().ntf = host->make_trig_notifer_to_self(ath);
}
if (_buffer.size() <= _halfLength)
{
if (!_pushWait.empty())
{
_pushWait.back()(false);
_pushWait.pop_back();
}
else if (!_pushNtfQueue.empty())
{
_pushNtfQueue.front()();
_pushNtfQueue.pop_front();
}
}
if (break_)
{
break;
}
}
}
});
if (closed)
{
host->unlock_quit();
throw close_exception();
}
if (!isEmpty)
{
host->unlock_quit();
return;
}
if (host->wait_trig(ath))
{
host->unlock_quit();
throw close_exception();
}
}
host->unlock_quit();
}
template <typename Func>
size_t _try_pop(my_actor* host, Func&& out)
{
host->lock_quit();
bool closed = false;
bool popCount = 0;
host->send(_strand, [&]
{
closed = _closed;
if (!_closed)
{
while (true)
{
bool break_ = true;
if (!_buffer.empty())
{
popCount++;
break_ = out();
}
if (_buffer.size() <= _halfLength)
{
if (!_pushWait.empty())
{
_pushWait.back()(false);
_pushWait.pop_back();
}
else if (!_pushNtfQueue.empty())
{
_pushNtfQueue.front()();
_pushNtfQueue.pop_front();
}
}
if (break_)
{
break;
}
}
}
});
if (closed)
{
host->unlock_quit();
throw close_exception();
}
host->unlock_quit();
return popCount;
}
template <typename Func>
size_t _timed_pop(int tm, my_actor* host, Func&& out)
{
host->lock_quit();
long long utm = (long long)tm * 1000;
size_t popCount = 0;
while (true)
{
trig_handle<bool> ath;
typename msg_list<pop_pck>::iterator mit;
bool notified = false;
bool isEmpty = false;
bool closed = false;
host->send(_strand, [&]
{
closed = _closed;
if (!_closed)
{
while (true)
{
bool break_ = true;
isEmpty = _buffer.empty();
if (!isEmpty)
{
popCount++;
break_ = out();
}
else
{
_popWait.push_front({ notified });
_popWait.front().ntf = host->make_trig_notifer_to_self(ath);
mit = _popWait.begin();
}
if (_buffer.size() <= _halfLength)
{
if (!_pushWait.empty())
{
_pushWait.back()(false);
_pushWait.pop_back();
}
else if (!_pushNtfQueue.empty())
{
_pushNtfQueue.front()();
_pushNtfQueue.pop_front();
}
}
if (break_)
{
break;
}
}
}
});
if (!closed)
{
if (!isEmpty)
{
host->unlock_quit();
return popCount;
}
long long bt = get_tick_us();
if (!host->timed_wait_trig(utm / 1000, ath, closed))
{
host->send(_strand, [&]
{
if (!notified)
{
_popWait.erase(mit);
}
});
if (notified)
{
closed = host->wait_trig(ath);
}
}
utm -= get_tick_us() - bt;
if (utm < 1000)
{
host->unlock_quit();
return popCount;
}
}
if (closed)
{
host->unlock_quit();
throw close_exception();
}
}
host->unlock_quit();
return popCount;
}
private:
shared_strand _strand;
fixed_buffer<T> _buffer;
msg_list<push_pck> _pushWait;
msg_list<pop_pck> _popWait;
msg_queue<std::function<void()>> _popNtfQueue;
msg_queue<std::function<void()>> _pushNtfQueue;
size_t _halfLength;
bool _closed;
};
#endif | true |
04cd5b2cc78c3d8fb714f0e6e317c18f36760917 | C++ | SherlockUnknowEn/leetcode | /字符串/1234.替换子串得到平衡字符串.cpp | UTF-8 | 2,834 | 3.53125 | 4 | [] | no_license | /*
* @lc app=leetcode.cn id=1234 lang=cpp
*
* [1234] 替换子串得到平衡字符串
*/
// @lc code=start
class Solution {
public:
int balancedString(string s) {
unordered_map<char, int> memo;
for (int i = 0; i < s.size(); i++) {
memo[s[i]]++;
}
int avg = s.size() / 4;
unordered_map<char, int> need;
if (memo['A'] > avg) need['A'] = memo['A'] - avg;
if (memo['S'] > avg) need['S'] = memo['S'] - avg;
if (memo['D'] > avg) need['D'] = memo['D'] - avg;
if (memo['F'] > avg) need['F'] = memo['F'] - avg;
int len = need['A'] + need['S'] + need['D'] + need['F'];
if (len == 0) return 0;
// 滑动窗口法
int left = 0, right = 0;
unordered_map<char, int> window; // 记录窗口里字符个数
int ans = s.size();
for (; right < s.size(); right++) // right++ 扩大窗口
{
window[s[right]]++; // 新字符入窗
while (window['A'] >= need['A']
&& window['S'] >= need['S']
&& window['D'] >= need['D']
&& window['F'] >= need['F']) // 符合条件,缩小窗口直到不符合
{
ans = min(ans, right - left + 1);
window[s[left]]--;
left++; // 缩小窗口, 窗口左边界右移
}
}
return ans;
}
int balancedString(string s) {
unordered_map<char, int> memo;
for (int i = 0; i < s.size(); i++) {
memo[s[i]]++;
}
int avg = s.size() / 4;
unordered_map<char, int> need;
// 大于 size / 4 的需要变成别的字符
if (memo['A'] > avg) need['A'] = memo['A'] - avg;
if (memo['S'] > avg) need['S'] = memo['S'] - avg;
if (memo['D'] > avg) need['D'] = memo['D'] - avg;
if (memo['F'] > avg) need['F'] = memo['F'] - avg;
int len = need['A'] + need['S'] + need['D'] + need['F'];
if (len == 0) return 0; // 平衡,不需要更新字串
// 滑动窗口法
int left = 0, right = 0;
unordered_map<char, int> window; // 记录窗口里字符个数
int ans = s.size();
for (; right < s.size(); right++) // right++ 扩大窗口
{
window[s[right]]++; // 新字符入窗
while (window['A'] >= need['A']
&& window['S'] >= need['S']
&& window['D'] >= need['D']
&& window['F'] >= need['F']) // 符合条件,缩小窗口直到不符合
{
ans = min(ans, right - left + 1);
window[s[left]]--;
left++; // 缩小窗口, 窗口左边界右移
}
}
return ans;
}
};
// @lc code=end
| true |
0848e8561756570937a315d3ab7834b55cddc583 | C++ | Ethiraric/demangler | /include/demangler/details/node/Decltype.hh | UTF-8 | 840 | 2.59375 | 3 | [
"MIT"
] | permissive | #ifndef DEMANGLER_DETAILS_NODE_DECLTYPE_HH_
#define DEMANGLER_DETAILS_NODE_DECLTYPE_HH_
#include <demangler/details/Node.hh>
namespace demangler
{
namespace details
{
namespace node
{
class Decltype : public Node
{
public:
Decltype() noexcept;
Decltype(clone_tag, Decltype const& b);
Decltype(Decltype const& b) noexcept = delete;
Decltype(Decltype&& b) noexcept = default;
~Decltype() noexcept override = default;
Decltype& operator=(Decltype const& rhs) noexcept = delete;
Decltype& operator=(Decltype&& rhs) noexcept = default;
std::ostream& print(PrintOptions const& opt,
std::ostream& out) const override final;
std::unique_ptr<Node> deepClone() const override final;
static std::unique_ptr<Decltype> parse(State& s);
private:
};
}
}
}
#endif /* !DEMANGLER_DETAILS_NODE_DECLTYPE_HH_ */
| true |
7874fffe3062ba7ec577a18bd3ab15dfb871ad34 | C++ | IIvexII/Noodle | /lib/core/student.h | UTF-8 | 6,836 | 3.28125 | 3 | [] | no_license | #include "header.h"
#include "customInput.h"
#include "question.h"
#pragma once
#define FILENAME "resources/student.bin"
class Student{
public:
char name[50];
int rollNo;
char password[100];
double marks=-1;
};
class StudentManagement{
private:
Student student, tmpStudent;
QuestionHandler question;
char choice;
int marks;
// Take input from user
void input();
// Write student data to file
void writeFile();
// Read student data from file
// print in the form of table
void readFile();
// print student data
void output(Student);
// set marks
void setMarks(double);
public:
void banner();
void header();
void footer();
void newRegistration();
void listAll();
void rusticate();
void updateMarks(int, int);
void updatePasswd(int);
bool login();
void mainMenu();
void menuHandler();
};
void StudentManagement::banner(){
system("cls");
cout << "***********************************" << endl;
cout << " Student Panel" << endl;
cout << "***********************************" << endl;
}
// Public
/***********************
newRegistration()
************************/
void StudentManagement::newRegistration(){
input();
writeFile();
}
/***********************
listAll()
************************/
void StudentManagement::listAll(){
header();
readFile();
footer();
}
/**********************
rusticate()
***********************/
void StudentManagement::rusticate(){
int rn;
bool isDeleted=0;
char tempFilename[] = "resources/tmp.bin";
cout << "Enter Roll Number: "; cin >> rn;
ifstream inFile(FILENAME);
ofstream outFile(tempFilename);
while(inFile.read((char*)&student, sizeof(student))){
if(student.rollNo != rn){
outFile.write((char*)&student, sizeof(student));
}else{
isDeleted = 1;
}
}
inFile.close();
outFile.close();
// delete the old file
remove(FILENAME);
// rename new file to the older file
rename(tempFilename, FILENAME);
if(isDeleted)
cout << "Rusticated sucessfuly!";
else
cout <<"Unable to rusticate.";
cout << endl;
}
void StudentManagement::updateMarks(int rn, int mk){
fstream file(FILENAME, ios::binary | ios::in | ios::out);
int pos;
bool isSucessful=0;
while(file.read((char*)&student, sizeof(student))){
pos = file.tellg();
if(student.rollNo == rn){
student.marks = mk;
isSucessful=1;
break;
}
}
file.seekp(pos-sizeof(student));
file.write((char*)&student, sizeof(Student));
if(isSucessful)
cout << "Marks updated!" << endl;
else
cout << "Failed to update marks." << endl;
file.close();
}
void StudentManagement::updatePasswd(int rn){
fstream file(FILENAME, ios::binary | ios::in | ios::out);
int pos;
bool isSucessful=0;
while(file.read((char*)&student, sizeof(student))){
pos = file.tellg();
if(student.rollNo == rn){
cout << "Old Password: " << student.password << endl;
cout << "New Password: ";passwdInput(student.password);
isSucessful=1;
break;
}
}
file.seekp(pos-sizeof(student));
file.write((char*)&student, sizeof(student));
if(isSucessful)
cout << "Password Updated!" << endl;
else
cout << "Failed to update password." << endl;
file.close();
}
bool StudentManagement::login(){
int rn;
char password[100];
cin.clear();
cin.ignore(124,'\n');
banner();
cout << "Enter Roll Number: "; cin >> rn;
cout << "Password: "; passwdInput(password);
ifstream inFile(FILENAME);
while(inFile.read((char*)&tmpStudent,sizeof(Student))){
if(rn == tmpStudent.rollNo){
if(!strcmp(password, tmpStudent.password)){
cout << "Logged in as " << tmpStudent.name << "...." << endl;
return 1;
}else{
cout << "Username or Password is wrong." << endl;
}
}
}
inFile.close();
return 0;
}
void StudentManagement::mainMenu(){
banner();
cout << "Name: " << tmpStudent.name << endl;
cout << "Roll Number: " << tmpStudent.rollNo << endl;
cout << "Marks: " << tmpStudent.marks << endl;
cout << "***********************************" << endl;
cout << "1. Solve Quiz" << endl;
cout << "2. Change Password" << endl;
cout << "3. Display Your Information" << endl;
cout << "4. List all the Quiz Results" << endl;
cout << "0. Logout" << endl;
do{
choice = getch();
}while(choice!='1' && choice!='2' && choice!='3' && choice!='4' && choice!='0');
}
void StudentManagement::menuHandler(){
mainMenu();
switch(choice){
case '1':
banner();
marks = question.quiz()*10;
updateMarks(tmpStudent.rollNo, marks);
tmpStudent.marks = marks;
getch();
menuHandler();
break;
case '2':
banner();
updatePasswd(tmpStudent.rollNo);
getch();
menuHandler();
break;
case '3':
banner();
header();
output(tmpStudent);
footer();
getch();
menuHandler();
break;
case '4':
banner();
listAll();
getch();
menuHandler();
break;
}
}
// Private
void StudentManagement::input(){
// For the weird behaviour of getline()
cin.clear();
cin.ignore(124,'\n');
cout << "Name: "; cin.getline(student.name, 50);
cout << "Roll Number: "; cin >> student.rollNo;
// For the weird behaviour of getline()
cin.clear();
cin.ignore(124,'\n');
cout << "Password: "; passwdInput(student.password);
}
void StudentManagement::writeFile(){
ofstream outFile(FILENAME, ios::app);
if(outFile.is_open()){
outFile.write((char*)&student, sizeof(student));
outFile.close();
}
}
void StudentManagement::readFile(){
Student st;
ifstream inFile(FILENAME, ios::in);
if(inFile.is_open()){
while(inFile.read((char*)&st, sizeof(st))){
output(st);
}
}
inFile.close();
}
void StudentManagement::output(Student st){
cout << "|" << setw(30) << left << st.name << right << "|";
cout << setw(5) << right << st.rollNo << setw(5) << "|";
cout << setw(20) << right;
if(st.marks==-1)
cout << "NULL";
else
cout << st.marks;
cout << setw(5) << "|" << endl;
}
void StudentManagement::setMarks(double marks){
student.marks = marks;
}
void StudentManagement::header(){
cout << " _________________________________________________________________" << endl;
cout << "|" << setw(30) << left << "Name"
<< setw(10) << "Roll Number"
<< setw(20) << right << "Marks"
<< setw(5) << right << "|" << endl;
cout << "|_________________________________________________________________|" << endl;
}
void StudentManagement::footer(){
cout << "|_________________________________________________________________|" << endl;
}
#undef FILENAME | true |
ff0d175a54cfa450c4177a82846bd5f671c6d37c | C++ | YiheWang/ECE4320Robotics | /project3/project3.ino | UTF-8 | 6,155 | 2.8125 | 3 | [] | no_license | int chairState;
int button = 6;
int buttonState;
int pressSensor = A8;
int smDirectionPin1 = 24; //Direction pin
int smStepPin1 = 26; //Stepper pin
int smEnablePin1 = 22; //Motor enable pin
int smDirectionPin2 = 32; //Direction pin
int smStepPin2 = 30; //Stepper pin
int smEnablePin2 = 28; //Motor enable pin
int smDirectionPin3 = 34; //Direction pin
int smStepPin3 = 36; //Stepper pin
int smEnablePin3 = 38; //Motor enable pin
int smDirectionPin4 = 40; //Direction pin
int smStepPin4 = 42; //Stepper pin
int smEnablePin4 = 44; //Motor enable pin
void setup(){
pinMode(pressSensor, INPUT);
pinMode(button, INPUT);
buttonState = 0;
/*Sets all pin to output; the microcontroller will send them(the pins) bits, it will not expect to receive any bits from thiese pins.*/
pinMode(smDirectionPin1, OUTPUT);
pinMode(smStepPin1, OUTPUT);
pinMode(smEnablePin1, OUTPUT);
digitalWrite(smEnablePin1, HIGH); //Disbales the motor, so it can rest untill it is called uppond
pinMode(smDirectionPin2, OUTPUT);
pinMode(smStepPin2, OUTPUT);
pinMode(smEnablePin2, OUTPUT);
digitalWrite(smEnablePin2, HIGH); //Disbales the motor, so it can rest untill it is called uppond
pinMode(smDirectionPin3, OUTPUT);
pinMode(smStepPin3, OUTPUT);
pinMode(smEnablePin3, OUTPUT);
digitalWrite(smEnablePin3, HIGH); //Disbales the motor, so it can rest untill it is called uppond
pinMode(smDirectionPin4, OUTPUT);
pinMode(smStepPin4, OUTPUT);
pinMode(smEnablePin4, OUTPUT);
digitalWrite(smEnablePin4, HIGH); //Disbales the motor, so it can rest untill it is called uppond
Serial.begin(9600);
initialResetChair();// anyway transform to sit case
}
void loop(){
//moveUpAndDown1(-3000, 0.5);
//moveUpAndDown2(3000, 0.5);
buttonLiftChair();
pressDownChair();
}
void pressDownChair()
{
//press sensor only work in stand case
if(chairState == 1){
if(analogRead(pressSensor) > 10){
resetChair();
}
}
}
void buttonLiftChair()
{
//lift the chair up
buttonState = digitalRead(button);
if(buttonState == 1){
chairState = 1;// stand case
for(int i = 0; i < 27; ++i){
moveUpAndDown1(1000,0.5);
moveUpAndDown2(1000,0.5);
moveUpAndDown3(1000,0.5);
moveUpAndDown4(1000,0.5);
}
}
buttonState = 0;
}
void initialResetChair()
{
chairState = 0; //back to sit case
for(int i = 0; i < 27; ++i){
moveUpAndDown1(-1000,0.5);
moveUpAndDown2(-1000,0.5);
moveUpAndDown3(-1000,0.5);
moveUpAndDown4(-1000,0.5);
}
}
void resetChair()
{
if(chairState == 1){
chairState = 0;// back to sit case
//reset chair to the original position
for(int i = 0; i < 27; ++i){
moveUpAndDown1(-1000,0.5);
moveUpAndDown2(-1000,0.5);
moveUpAndDown3(-1000,0.5);
moveUpAndDown4(-1000,0.5);
}
}
}
/*The rotate function turns the stepper motor. Tt accepts two arguments: 'steps' and 'speed'*/
void moveUpAndDown1(int steps, float speed){
digitalWrite(smEnablePin1, LOW); //Enabling the motor, so it will move when asked to
int direction;
if (steps > 0){
direction = HIGH;
}else{
direction = LOW;
}
speed = 1/speed * 70; //Calculating speed
steps = abs(steps); //Stores the absolute value of the content in 'steps' back into the 'steps' variable
digitalWrite(smDirectionPin1, direction); //Writes the direction (from our if statement above), to the EasyDriver DIR pin
/*Steppin'*/
for (int i = 0; i < steps; i++){
digitalWrite(smStepPin1, HIGH);
delayMicroseconds(speed);
digitalWrite(smStepPin1, LOW);
delayMicroseconds(speed);
}
digitalWrite(smEnablePin1, HIGH); //Disbales the motor, so it can rest untill the next time it is called uppond
}
void moveUpAndDown2(int steps, float speed){
digitalWrite(smEnablePin2, LOW); //Enabling the motor, so it will move when asked to
int direction;
if (steps > 0){
direction = HIGH;
}else{
direction = LOW;
}
speed = 1/speed * 70; //Calculating speed
steps = abs(steps); //Stores the absolute value of the content in 'steps' back into the 'steps' variable
digitalWrite(smDirectionPin2, direction); //Writes the direction (from our if statement above), to the EasyDriver DIR pin
/*Steppin'*/
for (int i = 0; i < steps; i++){
digitalWrite(smStepPin2, HIGH);
delayMicroseconds(speed);
digitalWrite(smStepPin2, LOW);
delayMicroseconds(speed);
}
digitalWrite(smEnablePin2, HIGH); //Disbales the motor, so it can rest untill the next time it is called uppond
}
void moveUpAndDown3(int steps, float speed){
digitalWrite(smEnablePin3, LOW); //Enabling the motor, so it will move when asked to
int direction;
if (steps > 0){
direction = HIGH;
}else{
direction = LOW;
}
speed = 1/speed * 70; //Calculating speed
steps = abs(steps); //Stores the absolute value of the content in 'steps' back into the 'steps' variable
digitalWrite(smDirectionPin3, direction); //Writes the direction (from our if statement above), to the EasyDriver DIR pin
/*Steppin'*/
for (int i = 0; i < steps; i++){
digitalWrite(smStepPin3, HIGH);
delayMicroseconds(speed);
digitalWrite(smStepPin3, LOW);
delayMicroseconds(speed);
}
digitalWrite(smEnablePin3, HIGH); //Disbales the motor, so it can rest untill the next time it is called uppond
}
void moveUpAndDown4(int steps, float speed){
digitalWrite(smEnablePin4, LOW); //Enabling the motor, so it will move when asked to
int direction;
if (steps > 0){
direction = HIGH;
}else{
direction = LOW;
}
speed = 1/speed * 70; //Calculating speed
steps = abs(steps); //Stores the absolute value of the content in 'steps' back into the 'steps' variable
digitalWrite(smDirectionPin4, direction); //Writes the direction (from our if statement above), to the EasyDriver DIR pin
/*Steppin'*/
for (int i = 0; i < steps; i++){
digitalWrite(smStepPin4, HIGH);
delayMicroseconds(speed);
digitalWrite(smStepPin4, LOW);
delayMicroseconds(speed);
}
digitalWrite(smEnablePin4, HIGH); //Disbales the motor, so it can rest untill the next time it is called uppond
}
| true |
d33cad431d9d60cfba4614b07bd97e33b8655f4c | C++ | JosephFoster118/TPPDatabase | /DBPopulate/src/main.cpp | UTF-8 | 2,980 | 3.09375 | 3 | [] | no_license |
#include <stdio.h>
#include <string.h>
#include <mysql.h>
#include <unistd.h>
#include <ctype.h>
#include "Pokemon.h"
#define BUFFER_SIZE 16384
int deleteTable(MYSQL *db, const char* table)
{
int result = 0;
char output[BUFFER_SIZE];
memset(output,0,BUFFER_SIZE);
sprintf(output,"DROP TABLE %s;",table);
result = mysql_query(db,output);
return result;
}
int addEntry(MYSQL *db, const char* table, const char* data)
{
int result = 0;
char output[BUFFER_SIZE];
memset(output,0,BUFFER_SIZE);
sprintf(output,"INSERT INTO %s VALUES (%s);",table,data);
result = mysql_query(db,output);
return result;
}
int createTable(MYSQL *db, const char* table, const char* datatypes)
{
int result = 0;
char output[BUFFER_SIZE];
memset(output,0,BUFFER_SIZE);
sprintf(output,"CREATE TABLE IF NOT EXISTS %s(%s);",table,datatypes);
result = mysql_query(db,output);
return result;
}
int buildMoveList(MYSQL *database, const char* file_name)
{
FILE *list_file = NULL;
list_file = fopen(file_name,"r");
if(list_file == NULL)
{
printf("ERROR: Could not open file \"%s\"\n",file_name);
return -5;
}
int result = 0;
int id = 0;
char data[512];
char species[32];
char move_a[32];
char move_b[32];
char move_c[32];
char move_d[32];
memset(data,0,512);
memset(move_a,0,32);
memset(move_b,0,32);
memset(move_c,0,32);
memset(move_d,0,32);
while(fgets(data,512,list_file))
{
Pokemon* pokemon = new Pokemon(data);
id = pokemon->getId();
pokemon->getSpecies(species);
pokemon->getMoveA(move_a);
pokemon->getMoveB(move_b);
pokemon->getMoveC(move_c);
pokemon->getMoveD(move_d);
for(uint16_t i = 0; i < strlen(species); i++)
{
species[i] = toupper(species[i]);
}
printf("DATA: %3d %16s %14s %14s %14s %14s\n",id,species,move_a,move_b,move_c,move_d);
sprintf(data,"%d,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\"",id,species,move_a,move_b,move_c,move_d);
printf("COMPILED: %s\n",data);
result = addEntry(database,"MoveList",data);
printf("Was Successful: %s\n",result?"NO":"YES");
delete pokemon;
}
}
int main()
{
printf("Data Base Populate\n");
printf("MySQL Client Version: %s\n",mysql_get_client_info());
MYSQL *database = mysql_init(NULL);
if(mysql_real_connect(database,"localhost","root","000104178700512546","Pokemon",0,NULL,0) == NULL)
{
printf("Error connecting to database!\n");
return -1;
}
int result = -3;
result = deleteTable(database,"MoveList");
printf("Result: %d\n",result);
result = createTable(database,"MoveList",
"ID int NOT NULL, Pokemon varchar(32) PRIMARY KEY,MoveA varchar(16),MoveB varchar(16),MoveC varchar(16),MoveD varchar(16)");
printf("Result: %d\n",result);
char buffer[BUFFER_SIZE];
memset(buffer,0,BUFFER_SIZE);
for(int i = 0; i < 100; i++)
{
sprintf(buffer,"%d,\"Poops %d\",\"123\",\"123\",\"123\",\"123\"",i,i);
result = addEntry(database,"MoveList",buffer);
printf("Result: %d %d\n",i,result);
}
buildMoveList(database,"movelist.txt");
return 0;
} | true |
33d2634b57212834ce8ea544e42c4a3ac8674d24 | C++ | iRail/libqtrail | /api/reader/vehiclereader.h | UTF-8 | 1,023 | 2.515625 | 3 | [] | no_license | //
// Configuration
//
// Include guard
#ifndef VEHICLEREADER_H
#define VEHICLEREADER_H
// Includes
#include <QHash>
#include <QDateTime>
#include "api/reader.h"
#include "api/data/stop.h"
#include "api/data/vehicle.h"
namespace iRail
{
class VehicleReader : public Reader
{
Q_OBJECT
public:
// Construction and destruction
VehicleReader();
// Reader interface
void readDocument();
// Basic I/O
double version() const;
QDateTime timestamp() const;
Vehicle const* vehicle() const;
QList<Stop*> stops() const;
private:
// Member data
double mVersion;
QDateTime mTimestamp;
Vehicle const* mVehicle;
QList<Stop*> mStops;
// Tag readers
void readVehicleInformation();
Vehicle const* readVehicle();
QList<Stop*> readStops();
Stop* readStop();
Station const* readStation();
QDateTime readDatetime();
};
}
#endif // VEHICLEREADER_H
| true |
ac0668661b143c460a6910453adcdfdc71850e62 | C++ | lips-hci/ae400-realsense-sdk | /unit-tests/utilities/number/stabilized/test-empty.cpp | UTF-8 | 767 | 2.53125 | 3 | [
"GPL-1.0-or-later",
"OFL-1.1",
"GPL-2.0-only",
"GPL-3.0-only",
"BSL-1.0",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"LicenseRef-scancode-public-domain",
"Zlib",
"BSD-2-Clause",
"BSD-3-Clause",
"BSD-1-Clause",
"Unlicense"
] | permissive | // License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2020 Intel Corporation. All Rights Reserved.
//#cmake:add-file ../../../../common/utilities/number/stabilized-value.h
#include "../../../test.h"
#include <../common/utilities/number/stabilized-value.h>
using namespace utilities::number;
// Test group description:
// * This tests group verifies stabilized_value class.
//
// Current test description:
// * Verify that empty function works as expected
TEST_CASE( "empty test", "[stabilized value]" )
{
stabilized_value< float > stab_value( 5 );
CHECK( stab_value.empty() );
CHECK_NOTHROW( stab_value.add( 1.0f ) );
CHECK_FALSE( stab_value.empty() );
stab_value.clear();
CHECK( stab_value.empty() );
}
| true |
52500c88a6bb8c068e70bd135b34947599590c05 | C++ | ruisebastiao/LibGairp | /LibGairP/LibGairP/Polygon.h | UTF-8 | 1,651 | 2.71875 | 3 | [] | no_license | //
// Polygon.h
// LibGairP
//
// Created by Giorgi Pataraia on 27/12/2013.
// Copyright (c) 2013 Giorgi Pataraia LLC. All rights reserved.
//
#ifndef LibGairP_Polygon_h
#define LibGairP_Polygon_h
#include "DrawableObject.h"
const int MaxPointCount = 4;
class Polygon : public DrawableObject {
protected:
int n; // number of points
Vector3D points[MaxPointCount];
void initialise() {
transform = Matrix4().identity();
}
public:
Polygon(int nVectors = 2) : n(nVectors) { initialise(); }
Polygon(const Polygon & p) : DrawableObject(p) {
n = p.n;
forinc(i, 0, n-1)
points[i] = Vector3D(p.points[i]);
}
Polygon & operator = (const Polygon & p) {
DrawableObject::operator=(p);
n = p.n;
forinc(i, 0, n-1)
points[i] = Vector3D(p.points[i]);
return *this;
}
int size() const { return n; }
void draw() {
glPushMatrix();
glMultMatrixf(transform.A());
glLineWidth(2);
if (material.materialType == MaterialTypeNone) {
glEnable(GL_COLOR_MATERIAL);
glColor3fv(color.V());
glDisable(GL_COLOR_MATERIAL);
}
else
setMaterial();
glBegin(GL_POLYGON);
forinc(i,0,n-1) {
glNormal3fv(points[i].V());
glVertex3fv(points[i].V());
}
glEnd();
//
// glColor3d(0, 0, 0);
// glBegin(GL_LINE_LOOP);
// forinc(i,0,n-1) {
// glVertex3dv(points[i].V());
// }
// glEnd();
glPopMatrix();
}
};
#endif
| true |
01ce27100db2cf5cb8e8beaddb8732e5b8fd7796 | C++ | boyuandong/C-Practice | /C++/file_stream/bookstore/bookstore_manage.cpp | UTF-8 | 923 | 3.25 | 3 | [] | no_license | // bookstore_manage.cpp
// create main menu and choos option
#include "bookstore_manage.h"
const char *fileDat = "booksFile.dat";
int main()
{
char choice;
while(1)
{
cout<<"************ 书库管理 *************\n请输入操作选择\n"
<<"1: 入库\t2: 售出\t3: 查询\t4: 建立文本\t0: 初始化\tQ: 退出\n";
cin>>choice;
switch (choice)
{
case '1':
Append(fileDat);
break;
case '2':
Sale(fileDat);
break;
case '3':
Inquire(fileDat);
break;
case '4':
CreateTxt(fileDat);
break;
case '0':
Initial(fileDat);
break;
case 'q':
case 'Q':
cout<<" 退出系统\n";
return 0;
default:
cout<<"输入错误, 请再输入\n";
}
}
} | true |
e57c13c04326f8ab6a084db3830d7898da2adf49 | C++ | jmlien/shepherding | /simulator/release/release-Nov-04-2009/include/behaviors/behaviors.c/multi_herding/distributeShepherds.h | UTF-8 | 3,703 | 2.59375 | 3 | [
"MIT"
] | permissive | #ifndef SHEPHERD_DISTRIBUTION_H
#define SHEPHERD_DISTRIBUTION_H
#include "sh_ForceRules.h"
#include "sh_BehaviorRules.h"
#include "sh_MapBasedFlockState.h"
#include "func/sh_FlockFunc.h"
#include "simple_herding.h"
#include "sh_dyPRM.h"
#include "sh_CollisionDetection.h"
#include "simple_herding.h"
//# Here the shepherds will be distributed among groups based on
//# the size of each group
//# if num groups is bigger than num shepherds
//# the groups closer to big group center will be assigned a shepherd
class DistributeShepherdsGroupSizeClose
{
public:
void findDistributionPerGroup(FSLIST& shepherds, vector<FlockGroup>& groups)
{
typedef vector<FlockGroup>::iterator IT;
int shepherd_size = shepherds.size();
int group_size=groups.size();
if( groups.size()==1){
groups.front().shepherd_number=shepherd_size;
return;
}
else{
for(int i=0;i<group_size;i++) groups[i].shepherd_number=0;
}
if( shepherd_size >= group_size ){ // more shepherds than groups
// compute total number of flock (can't we get this somewhere else?)
int flock_size = 0;
for(IT g=groups.begin();g!=groups.end();g++) flock_size+=g->states.size();
//assign shepherds to groups
int sheps_assigned=0;
for(IT g=groups.begin();g!=groups.end();g++){
g->shepherd_number=int((group_size/flock_size)*shepherd_size)+1;
sheps_assigned += g->shepherd_number;
}
//# assign the rest..
if( sheps_assigned < shepherd_size ){
int diff=shepherd_size-sheps_assigned;
for(int i=0;i<diff;i++){
int gid=i%group_size;
groups[gid].shepherd_number++;
}//end for
}
}
else{//more group than shepherds
// decide which group the shepherd should go to based on their distance
for(int i=0;i<shepherd_size;i++){
int closest_id = farGroup(groups);
groups[closest_id].shepherd_number=1;
}
}//end else
}
//assuming groups are sorted from small to large
int farGroup(vector<FlockGroup>& groups)
{
int closest_id = -1;
float dist = -1e10f;
Point2d pos=groups[0].center;
int size=groups.size();
for(int id=0;id<size;id++){
if(groups[id].shepherd_number>0) continue;
float d = (groups[id].center-pos).norm()-groups[id].radius;
if (d>dist){
dist = d;
closest_id = id;
}
}
return closest_id;
}
};
/*
//This is another function from py
# Here the shepherds will be distributed among groups based on
# the size of each group
# based on size only order comes from getcc...I think
class DistributeShepherdsGroupSize:
# return (1) # of shepherds for each group (2) groups that will have shepherds
def findDistributionPerGroup(self,shepherds,groups):
if( len(groups) == 1 ):
groups[0].shepherd_number=shepherds.size();
return;
shepherd_size = shepherds.size();
if( shepherd_size >= len(groups) ): # more shepherds than groups
flock_size = 0.0; #total number of flock
for g in groups: flock_size = flock_size + len(g.members);
#assign shepherds to groups
sheps_assigned=0;
for g in groups:
sa = int((len(groups)/flock_size)*shepherd_size)+ 1;
g.shepherd_number=sa;
sheps_assigned = sheps_assigned + sa;
# assign the rest..
if( sheps_assigned < shepherd_size ):
for i in range(shepherd_size-sheps_assigned):
groups[i].shepherd_number=groups[i].shepherd_number+1;
else: # more group than shepherds
for i in range(shepherd_size):
groups[i].shepherd_number=1;
*/
#endif //SHEPHERD_DISTRIBUTION_H
| true |
b10c4393323222b5d607a6bc3721789580fcef4a | C++ | tangxifan/libOpenFPGA | /libs/EXTERNAL/libtatum/libtatum/tatum/SetupHoldAnalysis.hpp | UTF-8 | 4,117 | 2.515625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "SetupAnalysis.hpp"
#include "HoldAnalysis.hpp"
#include "tatum/delay_calc/DelayCalculator.hpp"
#include "tatum/graph_visitors/GraphVisitor.hpp"
namespace tatum {
/** \class SetupHoldAnalysis
*
* The SetupHoldAnalysis class defines the operations needed by a timing analyzer
* to perform a combinded setup (max/long path) and hold (min/shortest path) analysis.
*
* Performing both analysis simultaneously tends to be more efficient than performing
* them sperately due to cache locality.
*
* \see SetupAnalysis
* \see HoldAnalysis
* \see TimingAnalyzer
*/
class SetupHoldAnalysis : public GraphVisitor {
public:
SetupHoldAnalysis(size_t num_tags, size_t num_slacks)
: setup_visitor_(num_tags, num_slacks)
, hold_visitor_(num_tags, num_slacks) {}
void do_reset_node(const NodeId node_id) override {
setup_visitor_.do_reset_node(node_id);
hold_visitor_.do_reset_node(node_id);
}
void do_reset_edge(const EdgeId edge_id) override {
setup_visitor_.do_reset_edge(edge_id);
hold_visitor_.do_reset_edge(edge_id);
}
bool do_arrival_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id) override {
bool setup_unconstrained = setup_visitor_.do_arrival_pre_traverse_node(tg, tc, node_id);
bool hold_unconstrained = hold_visitor_.do_arrival_pre_traverse_node(tg, tc, node_id);
return setup_unconstrained || hold_unconstrained;
}
bool do_required_pre_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const NodeId node_id) override {
bool setup_unconstrained = setup_visitor_.do_required_pre_traverse_node(tg, tc, node_id);
bool hold_unconstrained = hold_visitor_.do_required_pre_traverse_node(tg, tc, node_id);
return setup_unconstrained || hold_unconstrained;
}
void do_arrival_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalculator& dc, const NodeId node_id) override {
setup_visitor_.do_arrival_traverse_node(tg, tc, dc, node_id);
hold_visitor_.do_arrival_traverse_node(tg, tc, dc, node_id);
}
void do_required_traverse_node(const TimingGraph& tg, const TimingConstraints& tc, const DelayCalculator& dc, const NodeId node_id) override {
setup_visitor_.do_required_traverse_node(tg, tc, dc, node_id);
hold_visitor_.do_required_traverse_node(tg, tc, dc, node_id);
}
void do_slack_traverse_node(const TimingGraph& tg, const DelayCalculator& dc, const NodeId node) override {
setup_visitor_.do_slack_traverse_node(tg, dc, node);
hold_visitor_.do_slack_traverse_node(tg, dc, node);
}
TimingTags::tag_range setup_tags(const NodeId node_id) const { return setup_visitor_.setup_tags(node_id); }
TimingTags::tag_range setup_tags(const NodeId node_id, TagType type) const { return setup_visitor_.setup_tags(node_id, type); }
TimingTags::tag_range setup_edge_slacks(const EdgeId edge_id) const { return setup_visitor_.setup_edge_slacks(edge_id); }
TimingTags::tag_range setup_node_slacks(const NodeId node_id) const { return setup_visitor_.setup_node_slacks(node_id); }
TimingTags::tag_range hold_tags(const NodeId node_id) const { return hold_visitor_.hold_tags(node_id); }
TimingTags::tag_range hold_tags(const NodeId node_id, TagType type) const { return hold_visitor_.hold_tags(node_id, type); }
TimingTags::tag_range hold_edge_slacks(const EdgeId edge_id) const { return hold_visitor_.hold_edge_slacks(edge_id); }
TimingTags::tag_range hold_node_slacks(const NodeId node_id) const { return hold_visitor_.hold_node_slacks(node_id); }
SetupAnalysis& setup_visitor() { return setup_visitor_; }
HoldAnalysis& hold_visitor() { return hold_visitor_; }
private:
SetupAnalysis setup_visitor_;
HoldAnalysis hold_visitor_;
};
} //namepsace
| true |
1a7a4a3aa526d163c3ce05e7c63340f7e61e91e2 | C++ | AnkurSheel/codingame_old | /c++/tests/Medium/MayanCalculationTest.cpp | UTF-8 | 5,365 | 2.6875 | 3 | [] | no_license | #include <fstream>
#include "Common/Includes.h"
#include "Common/RedirectIO.h"
#include "Medium/MayanCalculation.h"
#include "gtest/gtest.h"
using namespace std;
class MayanCalculationTest : public ::testing::Test
{
virtual void SetUp() override
{
Common::RedirectCin(inputFile);
Common::RedirectCout(outputstream);
}
virtual void TearDown() override
{
Common::ResetCin();
Common::ResetCout();
}
protected:
ifstream inputFile;
ifstream resultFile;
stringstream outputstream;
};
TEST_F(MayanCalculationTest, SimpleAddition)
{
inputFile = ifstream("./c++/tests/DataFiles/Medium/MayanCalculation/SimpleAddition_in.txt");
MayanCalculation::main();
resultFile.open("./c++/tests/DataFiles/Medium/MayanCalculation/SimpleAddition_out.txt");
stringstream expectedStream;
expectedStream << resultFile.rdbuf();
EXPECT_STREQ(expectedStream.str().data(), outputstream.str().data());
}
TEST_F(MayanCalculationTest, AdditionWithCarry)
{
inputFile = ifstream("./c++/tests/DataFiles/Medium/MayanCalculation/AdditionWithCarry_in.txt");
MayanCalculation::main();
resultFile.open("./c++/tests/DataFiles/Medium/MayanCalculation/AdditionWithCarry_out.txt");
stringstream expectedStream;
expectedStream << resultFile.rdbuf();
EXPECT_STREQ(expectedStream.str().data(), outputstream.str().data());
}
TEST_F(MayanCalculationTest, Multiplication)
{
inputFile = ifstream("./c++/tests/DataFiles/Medium/MayanCalculation/Multiplication_in.txt");
MayanCalculation::main();
resultFile.open("./c++/tests/DataFiles/Medium/MayanCalculation/Multiplication_out.txt");
stringstream expectedStream;
expectedStream << resultFile.rdbuf();
EXPECT_STREQ(expectedStream.str().data(), outputstream.str().data());
}
TEST_F(MayanCalculationTest, SimpleSubtraction)
{
inputFile = ifstream("./c++/tests/DataFiles/Medium/MayanCalculation/SimpleSubtraction_in.txt");
MayanCalculation::main();
resultFile.open("./c++/tests/DataFiles/Medium/MayanCalculation/SimpleSubtraction_out.txt");
stringstream expectedStream;
expectedStream << resultFile.rdbuf();
EXPECT_STREQ(expectedStream.str().data(), outputstream.str().data());
}
TEST_F(MayanCalculationTest, Subtraction)
{
inputFile = ifstream("./c++/tests/DataFiles/Medium/MayanCalculation/Subtraction_in.txt");
MayanCalculation::main();
resultFile.open("./c++/tests/DataFiles/Medium/MayanCalculation/Subtraction_out.txt");
stringstream expectedStream;
expectedStream << resultFile.rdbuf();
EXPECT_STREQ(expectedStream.str().data(), outputstream.str().data());
}
TEST_F(MayanCalculationTest, SimpleDivision)
{
inputFile = ifstream("./c++/tests/DataFiles/Medium/MayanCalculation/SimpleDivision_in.txt");
MayanCalculation::main();
resultFile.open("./c++/tests/DataFiles/Medium/MayanCalculation/SimpleDivision_out.txt");
stringstream expectedStream;
expectedStream << resultFile.rdbuf();
EXPECT_STREQ(expectedStream.str().data(), outputstream.str().data());
}
TEST_F(MayanCalculationTest, Division)
{
inputFile = ifstream("./c++/tests/DataFiles/Medium/MayanCalculation/Division_in.txt");
MayanCalculation::main();
resultFile.open("./c++/tests/DataFiles/Medium/MayanCalculation/Division_out.txt");
stringstream expectedStream;
expectedStream << resultFile.rdbuf();
EXPECT_STREQ(expectedStream.str().data(), outputstream.str().data());
}
TEST_F(MayanCalculationTest, GreatMultiplication)
{
inputFile = ifstream("./c++/tests/DataFiles/Medium/MayanCalculation/GreatMultiplication_in.txt");
MayanCalculation::main();
resultFile.open("./c++/tests/DataFiles/Medium/MayanCalculation/GreatMultiplication_out.txt");
stringstream expectedStream;
expectedStream << resultFile.rdbuf();
EXPECT_STREQ(expectedStream.str().data(), outputstream.str().data());
}
TEST_F(MayanCalculationTest, Zero)
{
inputFile = ifstream("./c++/tests/DataFiles/Medium/MayanCalculation/Zero_in.txt");
MayanCalculation::main();
resultFile.open("./c++/tests/DataFiles/Medium/MayanCalculation/Zero_out.txt");
stringstream expectedStream;
expectedStream << resultFile.rdbuf();
EXPECT_STREQ(expectedStream.str().data(), outputstream.str().data());
}
TEST_F(MayanCalculationTest, MissingPower)
{
inputFile = ifstream("./c++/tests/DataFiles/Medium/MayanCalculation/MissingPower_in.txt");
MayanCalculation::main();
resultFile.open("./c++/tests/DataFiles/Medium/MayanCalculation/MissingPower_out.txt");
stringstream expectedStream;
expectedStream << resultFile.rdbuf();
EXPECT_STREQ(expectedStream.str().data(), outputstream.str().data());
}
TEST_F(MayanCalculationTest, Base20)
{
inputFile = ifstream("./c++/tests/DataFiles/Medium/MayanCalculation/Base20_in.txt");
MayanCalculation::main();
resultFile.open("./c++/tests/DataFiles/Medium/MayanCalculation/Base20_out.txt");
stringstream expectedStream;
expectedStream << resultFile.rdbuf();
EXPECT_STREQ(expectedStream.str().data(), outputstream.str().data());
}
TEST_F(MayanCalculationTest, OtherSymbols)
{
inputFile = ifstream("./c++/tests/DataFiles/Medium/MayanCalculation/OtherSymbols_in.txt");
MayanCalculation::main();
resultFile.open("./c++/tests/DataFiles/Medium/MayanCalculation/OtherSymbols_out.txt");
stringstream expectedStream;
expectedStream << resultFile.rdbuf();
EXPECT_STREQ(expectedStream.str().data(), outputstream.str().data());
}
| true |
12c811cd02ba64aaba98ededf2315328b01c8d98 | C++ | kks227/BOJ | /6100/6125.cpp | UTF-8 | 447 | 2.578125 | 3 | [] | no_license | #include <cstdio>
#include <stack>
using namespace std;
int main(){
int P, NS, T, p[5000], l[5000], r[5000];
scanf("%d %d %d", &P, &NS, &T);
T--;
for(int i=0; i<NS; i++){
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
u--; v--; w--;
l[u] = v; r[u] = w;
p[v] = p[w] = u;
}
stack<int> S;
S.push(T);
while(S.top() != 0)
S.push(p[S.top()]);
printf("%d\n", S.size());
while(!S.empty()){
printf("%d\n", S.top()+1);
S.pop();
}
} | true |
c4a3d4c6f3420acb0f1024ad320280ff451468b7 | C++ | JuliaYu2002/HunterDE | /Comp Sci 127 hw/tempConvert_jy.cpp | UTF-8 | 474 | 3.734375 | 4 | [] | no_license | // Name: Julia Yu
// Date: November 8, 2019
// Email: julia.yu83@myhunter.cuny.edu
// This program takes in a temperature in farenheit and converts it to celsius
#include <iostream>
using namespace std;
int main()
{
float temp;
cout << "Enter temperature in farenheit: ";
cin >> temp;
temp = (temp - 32);
temp = temp * 5 / 9;
if (temp == 0)
cout << "Temp in Celsius: 0.00";
else
cout << "Temp in Celsius: " << temp;
return 0;
} | true |
9743953a7e77f83496f02cc52895a1658616408a | C++ | vienbk91/gunbound | /Classes/Object/Character/Character.cpp | UTF-8 | 6,285 | 2.671875 | 3 | [] | no_license | #include "Object/Character/Character.h"
//////////////////////////////////////////////////////////////////////////////////////////////
// KHOI TAO DOI TUONG CHARACTER
//////////////////////////////////////////////////////////////////////////////////////////////
Character* Character::createCharacterWithId(int characterId)
{
Character* character = new (std::nothrow) Character();
if (character && character->initWithId(characterId))
{
character->autorelease();
return character;
}
CC_SAFE_DELETE(character);
return nullptr;
}
bool Character::initWithId(int characterId)
{
if (!Sprite::init())
{
return false;
}
createImagePathByUnitId(characterId);
string imagePath =_imagePath;
imagePath.append("unit_00_08_1.png");
this->initWithFile(imagePath.c_str());
return true;
}
void Character::createImagePathByUnitId(int characterId)
{
switch (characterId)
{
case 1:
_imagePath = "image/unit_new/move/red/";
break;
case 2:
_imagePath = "image/unit_new/move/purple/";
break;
case 3:
_imagePath = "image/unit_new/move/green/";
break;
case 4:
_imagePath = "image/unit_new/move/blue/";
break;
case 5:
_imagePath = "image/unit_new/move/black/";
break;
default:
_imagePath = "image/unit_new/move/red/";
break;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////
// Thuc hien moveAction method
//////////////////////////////////////////////////////////////////////////////////////////////
void Character::actionMoveByVector(Vec2 moveVector)
{
int direction = getDirectionWithAngle(-(moveVector.getAngle() * RAD_DEG) + 90);
switch (this->getMoveMode())
{
case 1: // MOVE_AUTO
break;
case 2: // MOVE_MANUAL
case 3: // MOVE_CIRCLE_MANUAL
case 4: // MOVE_CIRCLE_LONGTAP
this->getPhysicsBody()->setVelocity(Vect(this->getCharacterMoveSpeed() * cos(moveVector.getAngle()), this->getCharacterMoveSpeed() * sin(moveVector.getAngle())));
if (direction != 0)
{
actionRotateWithDirection(direction);
}
break;
case 5: // MOVE_CIRCLE_ONETAP
{
this->stopActionByTag(101);
auto actionOneTap = Sequence::create(DelayTime::create(this->getMoveOneTapTime()), CallFuncN::create([&](Ref* pSender){
this->actionStopMove();
}), nullptr);
actionOneTap->setTag(101);
this->runAction(actionOneTap);
if (this->getPhysicsBody() != nullptr)
{
this->getPhysicsBody()->setVelocity(Vect(this->getCharacterMoveSpeed() * cos(moveVector.getAngle()), this->getCharacterMoveSpeed() * sin(moveVector.getAngle())));
}
if (direction != 0)
{
actionRotateWithDirection(direction);
}
break;
}
default:
break;
}
}
void Character::actionStopMove()
{
if (this->getPhysicsBody() != nullptr)
{
this->getPhysicsBody()->setVelocity(Vect::ZERO);
}
this->stopActionByTag(this->getCurrentMoveAnimation());
}
//////////////////////////////////////////////////////////////////////////////////////////////
//XU LY LAY GOC
//////////////////////////////////////////////////////////////////////////////////////////////
/* Lay chi so direction tuong ung voi goc */
int Character::getDirectionWithAngle(float angle)
{
if (getDetectAngleFlg(0, angle)) return 8; // if(angle < 22 && angle > -22) return 8
if (getDetectAngleFlg(45, angle)) return 9; // if(angle < 45+22 && angle > 45-22) return 9
if (getDetectAngleFlg(90, angle)) return 6;
if (getDetectAngleFlg(135, angle)) return 3;
if (getDetectAngleFlg(180, angle)) return 2;
if (getDetectAngleFlg(-45, angle)) return 7;
if (getDetectAngleFlg(-90, angle)) return 4;
if (getDetectAngleFlg(255, angle)) return 1;
return 0;
}
/* Flag dung de xac dinh goc */
bool Character::getDetectAngleFlg(int offset, float angle)
{
if ((angle < (offset + 22)) && (angle >(offset - 22)))
{
return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////////////////////////////
//XU LY MOVE & ATTACK ANIMATION
//////////////////////////////////////////////////////////////////////////////////////////////
void Character::actionRotateWithDirection(int directionIndex)
{
log("Direct: %d ", directionIndex);
/* Kiem tra neu van la action cu thi ko stop no lai*/
if (this->getNumberOfRunningActions() > 0) {
if (this->getActionByTag(directionIndex) != nullptr) {
return;
}
}
// Thuc hien stop action cu khi chuyen huong(direct thay doi)
this->stopAllActionsByTag(this->getCurrentMoveAnimation());
log("Stop action with tag: %d ", this->getCurrentMoveAnimation());
// thuc hien animation repeat forever
auto action = Animate::create(createMoveAnimationCharacterWithImage(directionIndex , _imagePath));
auto repeat = RepeatForever::create(action);
repeat->setTag(directionIndex);
this->setCurrentMoveAnimation(directionIndex);
this->runAction(repeat);
}
// Tao 1 doi tuong animation thuc hien hanh dong di chuyen duoc xay dung bang anh
/*
Neu khong truyen imagePath vao thi cu moi lan no se thuc hien getImagePath de lay _imagePath
nhu the se bi giat khi di chuyen do _imagePath phai duoc tim lien tuc
*/
Animation* Character::createMoveAnimationCharacterWithImage(int imageId , string imagePath)
{
// Tao animation bang sprite sheet
auto moveAnimation = Animation::create();
for (int i = 1; i < 3; i++)
{
char szName[100] = { 0 };
sprintf(szName, "unit_00_0%d_%d.png", imageId, i);
string p = imagePath;
p.append(szName);
moveAnimation->addSpriteFrameWithFile(p.c_str());
}
// Thoi gian animation thuc hien
moveAnimation->setDelayPerUnit(0.2f);
// Restore lai diem dat cua cac frame moi khi animate thuc hien
moveAnimation->setRestoreOriginalFrame(true);
// Thuc hien lap
moveAnimation->setLoops(true);
return moveAnimation;
}
// create attack animation object using sprite sheet
Animation* Character::createAttackAnimationCharacterWithImage(int imageId)
{
auto attackAnimation = Animation::create();
for (int i = 0; i < 3; i++)
{
char szName[100] = { 0 };
sprintf(szName, "unit_00_0%d_attack_%d.png", imageId, i);
string p = getImagePath();
p.append(szName);
attackAnimation->addSpriteFrameWithFile(p.c_str());
}
attackAnimation->setDelayPerUnit(0.25f);
attackAnimation->setRestoreOriginalFrame(true);
attackAnimation->setLoops(true);
return attackAnimation;
}
| true |
fa10f687a6cb60ccd9a7d8441d46b0622781d073 | C++ | MarqSevadera/InBetween | /RockPaperScissor.cpp | UTF-8 | 7,958 | 2.828125 | 3 | [] | no_license | #include "stdafx.h"
#include "RockPaperScissor.h"
#include <iostream>
RockPaperScissor::RPSWinner RockPaperScissor::PlayRPS(sf::RenderWindow& renderWindow) {
bgImg.loadFromFile("images/rps-bg.png");
InitializeWeapons();
LoadImages();
InitializeSprites();
srand(time(NULL));
sf::Event event;
while (true) {
DrawSprites(renderWindow);
while (renderWindow.pollEvent(event)) {
if (event.type == sf::Event::Closed) return Quit;
if (event.type == sf::Event::MouseButtonPressed) {
RPSPicked playerPick = HandleClick(event.mouseButton.x , event.mouseButton.y);
if (playerPick != Nothing) {
RPSPicked aiPick = GetAIPick();
UpdateRightSprites(renderWindow , aiPick);
RPSWinner winner = GetRPSWinner(aiPick, playerPick);
UpdateBgSprite(renderWindow , winner);
DisplayPicks(renderWindow, aiPick, playerPick);
sf::sleep(sf::milliseconds(1000));
return winner;
}
}
}
}
}
RockPaperScissor::RPSWinner RockPaperScissor::GetRPSWinner(RPSPicked aiPicked, RPSPicked playerPicked) {
if (aiPicked == playerPicked)
return Draw;
else if ( (aiPicked == Rock && playerPicked == Scissor )|| (aiPicked == Paper && playerPicked == Rock) || (aiPicked == Scissor && playerPicked == Paper) )
return CPU;
else
return Player;
}
void RockPaperScissor::DrawSprites(sf::RenderWindow& window) {
RPSPicked hoveredItem = GetHoveredItem(window);
if (hoveredItem == Rock) {
L_RockSprite.setTexture(rockGlow);
L_PaperSprite.setTexture(paperImg);
L_ScissorSprite.setTexture(scissorImg);
}
else if (hoveredItem == Paper) {
L_PaperSprite.setTexture(paperGlow);
L_RockSprite.setTexture(rockImg);
L_ScissorSprite.setTexture(scissorImg);
}
else if (hoveredItem == Scissor) {
L_ScissorSprite.setTexture(scissorGlow);
L_RockSprite.setTexture(rockImg);
L_PaperSprite.setTexture(paperImg);
}
else {
L_RockSprite.setTexture(rockImg);
L_PaperSprite.setTexture(paperImg);
L_ScissorSprite.setTexture(scissorImg);
}
window.clear();
window.draw(bgSprite);
window.draw(L_RockSprite);
window.draw(L_PaperSprite);
window.draw(L_ScissorSprite);
window.draw(R_RockSprite);
window.draw(R_PaperSprite);
window.draw(R_ScissorSprite);
window.display();
}
RockPaperScissor::RPSPicked RockPaperScissor::GetAIPick() {
int aipick = 1 + (rand() % 3);
if (aipick == 1) return Rock;
else if (aipick == 2) return Paper;
else return Scissor;
}
RockPaperScissor::RPSPicked RockPaperScissor::HandleClick(int x, int y) {
std::list<Weapon>::iterator i;
for (i = weapon.begin(); i != weapon.end(); i++) {
sf::Rect<int> weaponRect= i->rect;
//check if the x and y axis of the mousepress is in the area of our weaponRect
if (weaponRect.height > y && weaponRect.top < y && weaponRect.width > x && weaponRect.left < x) {
return i -> type;
}
}
return Nothing;
}
RockPaperScissor::RPSPicked RockPaperScissor::GetHoveredItem(sf::RenderWindow& renderWindow ) {
std::list<Weapon>::iterator i;
for (i = weapon.begin(); i != weapon.end(); i++) {
sf::Rect<int> weaponRect = i->rect;
//check if the x and y axis of the mousepress is in the area of our weaponRect
if (weaponRect.height > mouse.getPosition(renderWindow).y && weaponRect.top < mouse.getPosition(renderWindow).y && weaponRect.width > mouse.getPosition(renderWindow).x
&& weaponRect.left < mouse.getPosition(renderWindow).x) {
return i -> type;
}
}
return Nothing;
}
void RockPaperScissor::InitializeSprites() {
//background
bgSprite.setTexture(bgImg);
//left side
L_RockSprite.setTexture(rockImg);
L_RockSprite.setPosition(sf::Vector2f(185, 270));
L_PaperSprite.setTexture(paperImg);
L_PaperSprite.setPosition(sf::Vector2f(112, 385));
L_ScissorSprite.setTexture(scissorImg);
L_ScissorSprite.setPosition(sf::Vector2f(275, 388));
//right side
R_RockSprite.setTexture(rockImg);
R_RockSprite.setPosition(sf::Vector2f(735, 270));
R_PaperSprite.setTexture(paperImg);
R_PaperSprite.setPosition(sf::Vector2f(665, 385));
R_ScissorSprite.setTexture(scissorImg);
R_ScissorSprite.setPosition(sf::Vector2f(825, 388));
}
void RockPaperScissor :: InitializeWeapons() {
//initialize rock's invisible rectangle
RockPaperScissor::Weapon rock;
rock.rect.top = 305;
rock.rect.height = 395;
rock.rect.left = 207;
rock.rect.width = 289;
rock.type = Rock;
//initialize paper's invisible rectangle
RockPaperScissor::Weapon paper;
paper.rect.top = 398;
paper.rect.height = 525;
paper.rect.left = 123;
paper.rect.width = 215;
paper.type = Paper;
//initialize scissor's invisible rectangle
RockPaperScissor::Weapon scissor;
scissor.rect.top = 401;
scissor.rect.height = 527;
scissor.rect.left = 290;
scissor.rect.width = 375;
scissor.type = Scissor;
weapon.push_back(rock);
weapon.push_back(paper);
weapon.push_back(scissor);
}
void RockPaperScissor::LoadImages() {
bgLose.loadFromFile("images/bg-lose.png");
bgWin.loadFromFile("images/bg-win.png");
bgDraw.loadFromFile("images/bg-draw.png");
rockImg.loadFromFile("images/spritesheet.png", sf::IntRect(0, imgHeight * 1, imgWidth, imgHeight));
paperImg.loadFromFile("images/spritesheet.png", sf::IntRect(0, imgHeight * 2, imgWidth, imgHeight));
scissorImg.loadFromFile("images/spritesheet.png", sf::IntRect(0, imgHeight * 0, imgWidth, imgHeight));
rockGlow.loadFromFile("images/spritesheet.png", sf::IntRect(imgWidth * 1, imgHeight * 1, imgWidth, imgHeight));
paperGlow.loadFromFile("images/spritesheet.png", sf::IntRect(imgWidth * 1, imgHeight * 2, imgWidth, imgHeight));
scissorGlow.loadFromFile("images/spritesheet.png", sf::IntRect(imgWidth * 1, imgHeight * 0, imgWidth, imgHeight));
}
void RockPaperScissor::UpdateRightSprites(sf::RenderWindow& window , RockPaperScissor::RPSPicked aiPick) {
if (aiPick == Rock) {
R_RockSprite.setTexture(rockGlow);
window.draw(R_RockSprite);
window.display();
sf::sleep(sf::milliseconds(500));
}
else if (aiPick == Paper) {
R_PaperSprite.setTexture(paperGlow);
window.draw(R_PaperSprite);
window.display();
sf::sleep(sf::milliseconds(500));
}
else {
R_ScissorSprite.setTexture(scissorGlow);
window.draw(R_ScissorSprite);
window.display();
sf::sleep(sf::milliseconds(500));
}
}
void RockPaperScissor::UpdateBgSprite(sf::RenderWindow& window, RockPaperScissor::RPSWinner winner) {
if (winner == Player) {
bgSprite.setTexture(bgWin);
window.clear();
window.draw(bgSprite);
}
else if (winner == CPU) {
bgSprite.setTexture(bgLose);
window.clear();
window.draw(bgSprite);
}
else {
bgSprite.setTexture(bgDraw);
window.clear();
window.draw(bgSprite);
}
}
void RockPaperScissor::DisplayPicks(sf::RenderWindow& window, RockPaperScissor::RPSPicked ai, RockPaperScissor::RPSPicked player) {
sf::Texture l_img, r_img;
sf::Sprite l_sprite, r_sprite;
//left side
if(player == Rock)
l_img.loadFromFile("images/spritesheet.png", sf::IntRect(imgWidth * 2, imgHeight * 1, imgWidth, imgHeight));
else if(player == Paper)
l_img.loadFromFile("images/spritesheet.png", sf::IntRect(imgWidth * 2, imgHeight * 2, imgWidth, imgHeight));
else if (player == Scissor)
l_img.loadFromFile("images/spritesheet.png", sf::IntRect(imgWidth * 2, imgHeight * 0, imgWidth, imgHeight));
//right side
if (ai == Rock)
r_img.loadFromFile("images/spritesheet.png", sf::IntRect(imgWidth * 3, imgHeight * 1, imgWidth, imgHeight));
else if (ai == Paper)
r_img.loadFromFile("images/spritesheet.png", sf::IntRect(imgWidth * 3, imgHeight * 2, imgWidth, imgHeight));
else if (ai == Scissor)
r_img.loadFromFile("images/spritesheet.png", sf::IntRect(imgWidth * 3, imgHeight * 0, imgWidth, imgHeight));
l_sprite.setTexture(l_img);
l_sprite.setPosition(sf::Vector2f(317, 245));
r_sprite.setTexture(r_img);
r_sprite.setPosition(558, 245);
window.draw(l_sprite);
window.draw(r_sprite);
window.display();
} | true |
2a62b8c1b5e5e7b415db23344e3cd782d8ee37b3 | C++ | hardikvaniya/Operating-System-Lab | /6-deadlock_detection.cpp | UTF-8 | 5,273 | 2.640625 | 3 | [] | no_license |
#include <iostream>
using namespace std;
#define res 1
int Allocation[10][2] , Max[10][2] , Available[2], Need[10][2] , c_Available[2]; // 2 resources
int Request[10][2], n , i , j , flag=0 , counter=0, pcom=0 , rp;
int safety_check();
void resource_request();
int req_allo();
int req_need();
int main()
{
cout<<endl<<"Enter number of process: ";
cin>>n;
cout<<endl;
for(i=0;i<n;i++)
{
cout<<"Enter Allocation for Process "<<i+1<<endl;
for(j=0;j<res;j++)
{
cin>>Allocation[i][j];
}
cout<<"Enter Max for Process "<<i+1<<endl;
for(j=0;j<res;j++)
{
cin>>Max[i][j];
}
}
cout<<"Enter total Available resources \n";
for(j=0;j<res;j++)
{
cin>>Available[j];
}
// request and need matrix
for(i=0;i<n;i++)
{
for(j=0;j<res;j++)
{
Need[i][j] = Max[i][j] - Allocation[i][j];
// cout<<endl<<Request[i][j];
}
}
//Currently available resource matrix
for(j=0;j<res;j++)
{
for(i=0;i<n;i++)
{
Available[j] = Available[j] - Allocation[i][j];
}
c_Available[j] = Available[j];
// cout<<"Available "<<j+1<<" = "<<c_Available[j];
}
//Deadlock detection
int result = safety_check();
int select=0;
// Start allocating resources
if(result==1)
{
while(1)
{
cout<<endl<<"Press 1 for resource allocation: ";
cout<<endl<<"Press 2 to exit"<<endl;
cin>>select;
if(select == 2)
{
break;
}
else
{
cout<<endl<<"Enter Requesting Process : ";
cin>>rp;
rp=rp-1;
cout<<endl<<rp;
cout<<"Enter number of instances of resouces requested\n";
for(j=0;j<res;j++)
{
cin>>Request[rp][j];
cout<<Request[rp][j];
}
cout<<endl<<"Reached";
cout<<endl<<Need[rp];
if(req_need())
{
if(req_allo())
{
for(j=0;j<res;j++)
{
c_Available[j] = c_Available[j] - Request[rp][j];
Allocation[rp][j] = Allocation[rp][j] + Request[rp][j];
Need[rp][j] = Need[rp][j] - Request[rp][j];
}
resource_request();
}
else
{
cout<<endl<<"Request greater than allocation";
}
}
else
{
cout<<endl<<"Request is greater than need";
}
}
}
}
return 0;
}
int safety_check()
{
pcom=0;
while(pcom<n)
{
flag=0;
for(i=0;i<n;i++)
{
counter=0;
for(j=0;j<res;j++)
{
if(Need[i][j] > c_Available[j])
{
flag++;
break;
}
else
{
counter++;
}
}
if(counter == res)
{
c_Available[j] = c_Available[j] + Allocation[i][j];
pcom++;
break;
}
}
if(flag == n )
{
cout<<endl<<"Deadlock found!!! It's Unsafe here";
return 0;
}
else
{
// cout<<"Entered for loop";
}
}
cout<<endl<<pcom;
if(pcom == n)
{
cout<<endl<<"It's absolutely safe here : )";
return 1;
}
else
{
//cout<<"ENtered while loop";
}
}
void resource_request()
{
pcom=0;
while(pcom<n)
{
flag=0;
for(i=0;i<n;i++)
{
counter=0;
for(j=0;j<res;j++)
{
if(Need[i][j] > c_Available[j])
{
flag++;
break;
}
else
{
counter++;
}
}
if(counter == res)
{
c_Available[j] = c_Available[j] + Allocation[i][j];
pcom++;
break;
}
}
if(flag == n )
{
cout<<endl<<"Cannot allocate requested resource!!!";
for(j=0;j<2;j++)
{
c_Available[j] = c_Available[j] + Request[rp][j];
Allocation[rp][j] = Allocation[rp][j] - Request[rp][j];
Need[rp][j] = Need[rp][j] + Request[rp][j];
}
break;
}
else
{
// cout<<"Entered for loop";
}
}
cout<<endl<<pcom;
if(pcom == n)
{
cout<<endl<<"Resource successfully allocated : )";
}
else
{
//cout<<"ENtered while loop";
}
}
int req_need()
{
int success=0;
for(j=0;j<res;j++)
{
if(Request[rp][j]<Need[rp][j])
{
success++;
}
}
if(success==res)
return 1;
else
return 0;
}
int req_allo()
{
int success=0;
for(j=0;j<res;j++)
{
if(Request[rp][j]<Allocation[rp][j])
{
success++;
}
}
if(success==res)
return 1;
else
return 0;
}
| true |
ba707e7d8d5e390ca8754e558d2e72f6bc7d991d | C++ | kimngoc58131350/TTCS58-Nhom1 | /Bai3/bai4kimngoc58131350.cpp | UTF-8 | 1,545 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <conio.h>
#include <iomanip>
#include <vector>
#include <fstream>
using namespace std;
int dem=0, n;
vector< int > cachTang;
vector< vector< int > > xuat;
void docFile(int &n, int &m, vector< int > &a){
ifstream infile;
infile.open("input4.txt");
infile>>n; infile.ignore(255, ' ');
infile>>m; infile.ignore(255, '\n');
a.resize(n);
for(int i=0; i<n-1; i++)
{
int temp;
infile>>temp;
a[i]=temp;
infile.ignore(255, ' ');
}
infile>>a[n-1];
}
void QLui(vector< int > a, int control, int m)
{
if (control==n and m==0)
{
// t/h dung
dem++;
xuat.push_back(cachTang);
}
if (control<n and m>=0) // chay tu 0 toi n-1
{
//vet can tat ca cac truong hop
cachTang[control] = 1;
QLui (a, control+1, m-a[control]);
cachTang[control] = 0;
QLui (a, control+1, m);
}
}
void Ghifile(){
ofstream outfile;
outfile.open("output4.txt", ios::out | ios::trunc);
if (dem==0)
{
cout<<"Khong chon duoc.";
outfile<<"Khong chon duoc.";
}
else
{
cout<<"So cach chon : "<<dem<<"\n";
outfile<<"So cach chon : "<<dem<<"\n";
for (int i=0; i<dem; i++)
{
for (int j=0;j<n;j++)
{
cout<<setw(3)<<xuat[i][j];
outfile<<setw(3)<<xuat[i][j];
}
cout<<"\n";
outfile<<endl;
}
}
outfile.close();
}
int main()
{
int M;
vector< int > GTMonQua;
docFile(n, M, GTMonQua);
cachTang.resize(n);
QLui(GTMonQua, 0, M);
Ghifile();
}
| true |
ffd8fe6b66409f3402b8a6b23ec0021daddcc104 | C++ | bmw147/dictionary | /program1/src/second/Timer.cc | UTF-8 | 940 | 2.765625 | 3 | [] | no_license |
#include "Timer.h"
#include "Mylogger.h"
#include <unistd.h>
#include <sys/timerfd.h>
namespace mysp
{
Timer::Timer(int initialTime, int intervalTime, TimerCallBack cb)
: _timerfd(createTimerfd())
, _initialTime(initialTime)
, _intervalTime(intervalTime)
, _isStarted(false)
, _cb(cb){
}
void Timer::start(){
_isStarted = true;
//添加到epoll读
}
void Timer::stop(){
if (_isStarted){
_isStarted = false;
setTimerfd(0, 0);
}
}
int Timer::createTimerfd(){
int fd = timerfd_create(CLOCK_REALTIME, 0);
if (fd == -1){
LogError("timerfd_create error");
}
return fd;
}
void Timer::setTimerfd(int initialTime, int intervalTime){
struct itimerspec value = {{initialTime, 0},
{intervalTime, 0}
};
if (-1 == timerfd_settime(_timerfd, 0, &value, NULL)){
LogError("timerfd_settime error");
}
}
void Timer::handleRead(){
uint64_t u;
if (sizeof(u) != read(_timerfd, &u, sizeof(u))){
LogError("read error");
}
}
}
| true |
e1c10add09ab1efcbe9b31eb3348c53a6abfb4c3 | C++ | nathan-tagg/asteroids | /superSpacer.h | UTF-8 | 2,089 | 2.84375 | 3 | [
"MIT"
] | permissive | #ifndef SUPERSPACER_H
#define SUPERSPACER_H
#include <math.h>
#include "uiDraw.h"
#include "ship.h"
class SuperSpacer : public Ship
{
private:
bool thrust;
bool scope;
public:
/***********************************************
* Constructors.
***********************************************/
SuperSpacer()
{
scope = false;
type = 10;
rotation = 0;
point.setX(0);
point.setY(0);
alive = true;
flip = true;
}
/***********************************************
* Apply meathods: These meathods call the mutators for the velocity variable.
***********************************************/
void up() { velocity.addDY(-.8 * sin((rotation - 90) / 57.2958)); velocity.addDX(-.8 * cos((rotation - 90) / 57.2958)); thrust = true; };
void down()
{
if (velocity.getDX() < -0.4)
velocity.addDX(.4);
else if (velocity.getDX() > 0.4)
velocity.addDX(-.4);
if (velocity.getDY() < -0.4)
velocity.addDY(.4);
else if (velocity.getDY() > 0.4)
velocity.addDY(-.4);
if (velocity.getDX() <= .4 && velocity.getDX() >= -.4)
velocity.setDX(0);
if (velocity.getDY() <= .4 && velocity.getDY() >= -.4)
velocity.setDY(0);
};
void left()
{
if (scope)
{
if ( flip )
rotation -= 0.5;
else
rotation += 0.5;
}
else
{
if ( flip )
rotation -= 5.0;
else
rotation += 5.0;
}
scope = false;
};
void right()
{
if (scope)
{
if ( flip )
rotation += 0.5;
else
rotation -= 0.5;
}
else
{
if ( flip )
rotation += 5.0;
else
rotation -= 5.0;
}
scope = false;
};
void constant() { thrust = false;};
/*********************************************
* Draw: This meathod will draw the lander in the environment.
*********************************************/
virtual void draw() { drawSuper(point, rotation, thrust, scope); };
void activateScope() { scope = true; };
};
#endif | true |
438c4305458659111abff0ad138461438b551e2e | C++ | organicmaps/organicmaps | /platform/battery_tracker.hpp | UTF-8 | 664 | 2.78125 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <chrono>
#include <cstdint>
#include <vector>
namespace platform
{
// Note: this class is NOT thread-safe.
class BatteryLevelTracker
{
public:
class Subscriber
{
public:
virtual void OnBatteryLevelReceived(uint8_t level) = 0;
protected:
virtual ~Subscriber() = default;
};
void Subscribe(Subscriber * subscriber);
void Unsubscribe(Subscriber * subscriber);
void UnsubscribeAll();
private:
void RequestBatteryLevel();
std::vector<Subscriber *> m_subscribers;
std::chrono::system_clock::time_point m_lastRequestTime;
uint8_t m_lastReceivedLevel = 0;
bool m_isTrackingInProgress = false;
};
} // platform
| true |
6d2fb6547314f0db395c195d745df1dd3dcbeb99 | C++ | pxie08/WAR-Card-Game | /hw7/cards.cpp | UTF-8 | 3,357 | 3.65625 | 4 | [] | no_license | /***************************************************
** cards.cpp
** Definitions of the Card and Player class member functions.
** Patrick Xie, 2/26/10
****************************************************/
#include "cards.h"
#include <string>
#include <ctime>
/***************************************************
** Card
** default constructor
** assigns random rank and suit to card
****************************************************/
Card::Card() {
int rand_numR = 1 + rand () % 13; //Random # between 1 and 13. rand_numR for rank
switch (rand_numR) { //switch used to pick a random rank
case 1: rank = "Ace"; break;
case 2: rank = "Two"; break;
case 3: rank = "Three"; break;
case 4: rank = "Four"; break;
case 5: rank = "Five"; break;
case 6: rank = "Six"; break;
case 7: rank = "Seven"; break;
case 8: rank = "Eight"; break;
case 9: rank = "Nine"; break;
case 10: rank = "Ten"; break;
case 11: rank = "Jack"; break;
case 12: rank = "Queen"; break;
case 13: rank = "King"; break;
}
int rand_numS = 1 + rand() % 4; //Random # between 1 and 4. rand_numS for suit
switch(rand_numS) { //switch used to pic a random suit
case 1: suit = "Hearts"; break;
case 2: suit = "Diamonds"; break;
case 3: suit = "Clubs"; break;
case 4: suit = "Spades"; break;
}
}
/***************************************************
** get_rank
** returns the rank of the card
****************************************************/
string Card::get_rank() const {
return rank;
}
/***************************************************
** get_suit
** returns the suit of the card
****************************************************/
string Card::get_suit() const {
return suit;
}
/***************************************************
** rank2num
** converts card rank into a int number
** used to compare cards
****************************************************/
int Card::rank2num() const {
int value;
if (get_rank() == "Ace")
value = 1;
if (get_rank() == "Two")
value = 2;
if (get_rank() == "Three")
value = 3;
if (get_rank() == "Four")
value = 4;
if (get_rank() == "Five")
value = 5;
if (get_rank() == "Six")
value = 6;
if (get_rank() == "Seven")
value = 7;
if (get_rank() == "Eight")
value = 8;
if (get_rank() == "Nine")
value = 9;
if (get_rank() == "Ten")
value = 10;
if (get_rank() == "Jack")
value = 11;
if (get_rank() == "Queen")
value = 12;
if (get_rank() == "King")
value = 13;
return value;
}
/***************************************************
** operator<
** compares the rank of two cards
****************************************************/
bool Card::operator< (Card card2) const {
return rank2num() < card2.rank2num();
}
/***************************************************
** Player
** constructs Player with intial amount of money
****************************************************/
Player::Player(int start_money) {
money = start_money;
}
/***************************************************
** get_money
** returns the current amount of money
****************************************************/
int Player::get_money() const {
return money;
}
/***************************************************
** change_money
** adds an amount to total amount of money
****************************************************/
void Player::change_money(int update) {
money += update;
} | true |
d7c605ba3749c8f8be0abcab79529249f40e76de | C++ | greggS/QEES-ROS2-Labs | /src/test_score/test_score.cpp | UTF-8 | 4,266 | 2.53125 | 3 | [] | no_license | #include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/float32.hpp"
#include "std_msgs/msg/bool.hpp"
#include <sensor_msgs/msg/laser_scan.hpp>
#include <sys/time.h>
using std::placeholders::_1;
#define TEST_PASS_ODOMETRY_DISTANCE 100
#define TEST_FAILE_SAFETY_DISTANCE 0.3
#define EFFICIENCY_WEIGHT 0.2
#define SAFETY_WEIGHT 0.8
#define OPTIMAL_TIME 70.0
#define OPTIMAL_SAFETY_DISTANCE 1.0
class TestScore : public rclcpp::Node
{
public:
TestScore() : Node("test_score")
{
current_odometry_ = 0;
current_minimum_distance_ = 999;
current_test_time_ = 0;
current_score_ = 0;
// Test time start
start_time_ = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
// Subscribe to car trip meter
odometry_subscription_ = this->create_subscription<std_msgs::msg::Float32>(
"/demo/distance_demo",
rclcpp::QoS(rclcpp::SystemDefaultsQoS()),
std::bind(&TestScore::odometry_subscription_callback, this, _1));
// Subscribe to Lidar data
laser_subscription_ = this->create_subscription<sensor_msgs::msg::LaserScan>(
"/ray/laserscan",
rclcpp::QoS(rclcpp::SystemDefaultsQoS()),
std::bind(&TestScore::laser_subscription_callback, this, _1));
// Create the final test result publisher
test_result_publisher_ = this->create_publisher<std_msgs::msg::Bool>("test_result",
rclcpp::QoS(rclcpp::SystemDefaultsQoS()));
}
void odometry_subscription_callback(const std_msgs::msg::Float32::SharedPtr _msg)
{
current_odometry_ = _msg->data;
check_test_passed();
}
void laser_subscription_callback(const sensor_msgs::msg::LaserScan::SharedPtr _msg)
{
float min_range = _msg->range_max + 1;
for (auto i = 0u; i < _msg->ranges.size(); ++i) {
auto range = _msg->ranges[i];
if (range > _msg->range_min && range < _msg->range_max && range < min_range) {
min_range = range;
}
}
if (min_range < current_minimum_distance_) {
current_minimum_distance_ = min_range;
}
calculate_score();
check_safety_test_failed();
}
// calculating the final test score
void calculate_score()
{
unsigned long now_time = std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
current_test_time_ = now_time - start_time_;
float efficiency_score = 1;
if (current_test_time_ > OPTIMAL_TIME) {
efficiency_score = OPTIMAL_TIME / current_test_time_;
}
float safety_score = 1;
if (current_minimum_distance_ < OPTIMAL_SAFETY_DISTANCE) {
safety_score = current_minimum_distance_ / OPTIMAL_SAFETY_DISTANCE;
}
RCLCPP_INFO(this->get_logger(), "time: %d, efficiency_score: %f", current_test_time_, efficiency_score);
current_score_ = EFFICIENCY_WEIGHT * efficiency_score + SAFETY_WEIGHT * safety_score;
}
void check_safety_test_failed()
{
if (current_minimum_distance_ <= TEST_FAILE_SAFETY_DISTANCE) {
RCLCPP_INFO(this->get_logger(), "Test failed!");
auto test_result_msg = std::make_unique<std_msgs::msg::Bool>();
test_result_msg->data = false;
test_result_publisher_->publish(std::move(test_result_msg));
rclcpp::shutdown();
}
}
void check_test_passed()
{
if (current_odometry_ >= TEST_PASS_ODOMETRY_DISTANCE) {
calculate_score();
RCLCPP_INFO(this->get_logger(), "Test passed! Score: %.2f", current_score_);
// Communicating to other nodes the result of the test
auto test_result_msg = std::make_unique<std_msgs::msg::Bool>();
test_result_msg->data = true;
test_result_publisher_->publish(std::move(test_result_msg));
rclcpp::shutdown();
}
}
rclcpp::Subscription<std_msgs::msg::Float32>::SharedPtr odometry_subscription_;
rclcpp::Subscription<sensor_msgs::msg::LaserScan>::SharedPtr laser_subscription_;
rclcpp::Publisher<std_msgs::msg::Bool>::SharedPtr test_result_publisher_;
private:
float current_odometry_;
float current_minimum_distance_;
unsigned int current_test_time_;
unsigned long start_time_;
float current_score_;
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<TestScore>());
rclcpp::shutdown();
return 0;
} | true |
3c5bedf6daf8746d3dddb1f1747df0dc683893be | C++ | KevinThelly/Code-Chef | /January 2020/Breaking_bricks.cpp | UTF-8 | 487 | 2.5625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int t,s,w[3];
cin>>t;
for(int i=0;i<t;i++){
cin>>s>>w[0]>>w[1]>>w[2];
int ans=0;
if(w[0]+w[1]>s){
if(w[1]+w[2]>s){
ans=3;
}
else{
ans=2;
}
}
else if(w[2]+w[1]>s){
if(w[1]+w[0]>s){
ans=3;
}
else{
ans=2;
}
}
else if(w[0]+w[1]+w[2]>s){
ans=2;
}
else{
ans =1;
}
cout<<ans<<endl;
}
} | true |
17dc27143e25316bcbfa3e8e4542e2bb6d6e6ca9 | C++ | prakharR534/GFG-Practice- | /Krishnamurthy number .cpp | UTF-8 | 716 | 3.21875 | 3 | [] | no_license | // { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution {
public:
int fact(int n){
if(n==0)
return 1;
return n*fact(n-1);
}
string isKrishnamurthy(int N) {
// code here
int n=N,r,sum=0;
while(n){
r = n%10;
sum += fact(r);
n/=10;
}
if(sum==N)
return "YES";
else
return "NO";
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int N;
cin>>N;
Solution ob;
cout << ob.isKrishnamurthy(N) << endl;
}
return 0;
} // } Driver Code Ends
| true |
d8480a6f7f8130110bdcfc9216e9aadb32864c10 | C++ | isl-org/Open3D | /examples/cpp/Image.cpp | UTF-8 | 6,440 | 2.734375 | 3 | [
"MIT"
] | permissive | // ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// Copyright (c) 2018-2023 www.open3d.org
// SPDX-License-Identifier: MIT
// ----------------------------------------------------------------------------
#include <cstdio>
#include "open3d/Open3D.h"
void PrintHelp() {
using namespace open3d;
PrintOpen3DVersion();
// clang-format off
utility::LogInfo("Usage:");
utility::LogInfo(" > Image [image filename] [depth filename]");
utility::LogInfo(" The program will :");
utility::LogInfo(" 1) Read 8bit RGB and 16bit depth image");
utility::LogInfo(" 2) Convert RGB image to single channel float image");
utility::LogInfo(" 3) 3x3, 5x5, 7x7 Gaussian filters are applied");
utility::LogInfo(" 4) 3x3 Sobel filter for x-and-y-directions are applied");
utility::LogInfo(" 5) Make image pyramid that includes Gaussian blur and downsampling");
utility::LogInfo(" 6) Will save all the layers in the image pyramid");
// clang-format on
utility::LogInfo("");
}
int main(int argc, char *argv[]) {
using namespace open3d;
utility::SetVerbosityLevel(utility::VerbosityLevel::Debug);
if (argc != 3 ||
utility::ProgramOptionExistsAny(argc, argv, {"-h", "--help"})) {
PrintHelp();
return 1;
}
const std::string filename_rgb(argv[1]);
const std::string filename_depth(argv[2]);
geometry::Image color_image_8bit;
if (io::ReadImage(filename_rgb, color_image_8bit)) {
utility::LogDebug("RGB image size : {:d} x {:d}",
color_image_8bit.width_, color_image_8bit.height_);
auto gray_image = color_image_8bit.CreateFloatImage();
io::WriteImage("gray.png",
*gray_image->CreateImageFromFloatImage<uint8_t>());
utility::LogDebug("Gaussian Filtering");
auto gray_image_b3 =
gray_image->Filter(geometry::Image::FilterType::Gaussian3);
io::WriteImage("gray_blur3.png",
*gray_image_b3->CreateImageFromFloatImage<uint8_t>());
auto gray_image_b5 =
gray_image->Filter(geometry::Image::FilterType::Gaussian5);
io::WriteImage("gray_blur5.png",
*gray_image_b5->CreateImageFromFloatImage<uint8_t>());
auto gray_image_b7 =
gray_image->Filter(geometry::Image::FilterType::Gaussian7);
io::WriteImage("gray_blur7.png",
*gray_image_b7->CreateImageFromFloatImage<uint8_t>());
utility::LogDebug("Sobel Filtering");
auto gray_image_dx =
gray_image->Filter(geometry::Image::FilterType::Sobel3Dx);
// make [-1,1] to [0,1].
gray_image_dx->LinearTransform(0.5, 0.5);
gray_image_dx->ClipIntensity();
io::WriteImage("gray_sobel_dx.png",
*gray_image_dx->CreateImageFromFloatImage<uint8_t>());
auto gray_image_dy =
gray_image->Filter(geometry::Image::FilterType::Sobel3Dy);
gray_image_dy->LinearTransform(0.5, 0.5);
gray_image_dy->ClipIntensity();
io::WriteImage("gray_sobel_dy.png",
*gray_image_dy->CreateImageFromFloatImage<uint8_t>());
utility::LogDebug("Build Pyramid");
auto pyramid = gray_image->CreatePyramid(4);
for (int i = 0; i < 4; i++) {
auto level = pyramid[i];
auto level_8bit = level->CreateImageFromFloatImage<uint8_t>();
std::string outputname =
"gray_pyramid_level" + std::to_string(i) + ".png";
io::WriteImage(outputname, *level_8bit);
}
} else {
utility::LogWarning("Failed to read {}", filename_rgb);
return 1;
}
geometry::Image depth_image_16bit;
if (io::ReadImage(filename_depth, depth_image_16bit)) {
utility::LogDebug("Depth image size : {:d} x {:d}",
depth_image_16bit.width_, depth_image_16bit.height_);
auto depth_image = depth_image_16bit.CreateFloatImage();
io::WriteImage("depth.png",
*depth_image->CreateImageFromFloatImage<uint16_t>());
utility::LogDebug("Gaussian Filtering");
auto depth_image_b3 =
depth_image->Filter(geometry::Image::FilterType::Gaussian3);
io::WriteImage("depth_blur3.png",
*depth_image_b3->CreateImageFromFloatImage<uint16_t>());
auto depth_image_b5 =
depth_image->Filter(geometry::Image::FilterType::Gaussian5);
io::WriteImage("depth_blur5.png",
*depth_image_b5->CreateImageFromFloatImage<uint16_t>());
auto depth_image_b7 =
depth_image->Filter(geometry::Image::FilterType::Gaussian7);
io::WriteImage("depth_blur7.png",
*depth_image_b7->CreateImageFromFloatImage<uint16_t>());
utility::LogDebug("Sobel Filtering");
auto depth_image_dx =
depth_image->Filter(geometry::Image::FilterType::Sobel3Dx);
// make [-65536,65536] to [0,13107.2]. // todo: need to test this
depth_image_dx->LinearTransform(0.1, 6553.6);
depth_image_dx->ClipIntensity(0.0, 13107.2);
io::WriteImage("depth_sobel_dx.png",
*depth_image_dx->CreateImageFromFloatImage<uint16_t>());
auto depth_image_dy =
depth_image->Filter(geometry::Image::FilterType::Sobel3Dy);
depth_image_dy->LinearTransform(0.1, 6553.6);
depth_image_dx->ClipIntensity(0.0, 13107.2);
io::WriteImage("depth_sobel_dy.png",
*depth_image_dy->CreateImageFromFloatImage<uint16_t>());
utility::LogDebug("Build Pyramid");
auto pyramid = depth_image->CreatePyramid(4);
for (int i = 0; i < 4; i++) {
auto level = pyramid[i];
auto level_16bit = level->CreateImageFromFloatImage<uint16_t>();
std::string outputname =
"depth_pyramid_level" + std::to_string(i) + ".png";
io::WriteImage(outputname, *level_16bit);
}
} else {
utility::LogWarning("Failed to read {}", filename_depth);
return 1;
}
return 0;
}
| true |
516d4d7cad64e229d02272a12d598a14df58f531 | C++ | AbiterVX/In-ClassLearning | /数据结构/实习4/第二题/MST/mstheap.h | UTF-8 | 2,943 | 3.71875 | 4 | [] | no_license | #ifndef MSTHEAP_H
#define MSTHEAP_H
#endif // MSTHEAP_H
#include<algorithm>
#include<iostream>
using namespace std;
#define Max 2147483647
struct Node
{
int FirstAddress;
int SecondAddress;
int Weight;
Node(int first=-1, int second=-1, int weight= Max)
{
FirstAddress = first;
second = second;
weight = weight;
}
};
class Heap
{
private:
Node*Data; //数组
int Length; //长度
int MaxLength;
public:
Heap(int TotalNumber) //构造
{
Length = 0;
MaxLength = TotalNumber; //舍弃第【0】个,将下标对应。
Data = new Node[TotalNumber + 1];
}
void HeapAdjust(int CurrentNumber, int length) //调整一次,得到最小值,即顶部
{
int CurrentMin = CurrentNumber; //当前最大
int LeftChild = CurrentNumber * 2; //左child
int RightChild = CurrentNumber * 2 + 1; //右child
if (CurrentNumber <= length / 2) //如果当前小于总长
{
if (LeftChild <= length && Data[LeftChild].Weight < Data[CurrentMin].Weight) //如果左child不为叶节点,
{ //且大于当前的数值,
CurrentMin = LeftChild; //则当前最大变为左child
}
if (RightChild <= length && Data[RightChild].Weight < Data[CurrentMin].Weight)//如果右child不为叶节点,
{ //且大于当前的数值,
CurrentMin = RightChild; //则当前最大变为右child
}
if (CurrentMin != CurrentNumber) //交换数值
{
swap(Data[CurrentMin], Data[CurrentNumber]);
HeapAdjust(CurrentMin, length);
}
}
}
void BuildHeap()
{
for (int i = Length / 2; i >= 1; i--)
{
HeapAdjust(i, Length);
}
}
Node GetTop()
{
return Data[1];
}
bool PopTop()
{
if (Length > 1)
{
Data[1] = Data[Length];
HeapAdjust(1, Length--);
return true;
}
else if (Length = 1)
{
Length = 0;
}
else
{
return false;
}
}
void Insert(Node NewNode)
{
if (Length < MaxLength)
{
Data[Length+1] = NewNode;
Length++;
}
}
void OutPut()
{
for (int i = Length; i > 0; i--)
{
cout << Data[i].Weight << " ";
}
cout << endl;
}
};
| true |
8b63baaa2f52bbd72bba411f3196a57eecfe1538 | C++ | RobbieCyy/Computational_Physics | /Exercise_1/src/cpp/Problem_3/main.cpp | UTF-8 | 3,163 | 3 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
double a, b, tau_a, tau_b, t, delta;
double a_prev;
double b_prev;
ofstream out("result.txt");
// The core of the ODE solver, where magic happens (lol)
void solve_core() {
// Method 1
// Naive iteration
/*
a -= delta * a_prev / tau_a;
b += delta * (a_prev / tau_a - b_prev / tau_b);
*/
// Method 2
// Naive iteration for a, a small correction for b
/*
a -= delta * a_prev / tau_a;
b += delta * ((a_prev + a) / (2 * tau_a) - b_prev / tau_b);
*/
// Method 3
// RK4 for a, no correction for b
/*
double k[4];
k[0] = - delta * a_prev / tau_a;
k[1] = - delta * (a_prev + k[0] / 2) / tau_a;
k[2] = - delta * (a_prev + k[1] / 2) / tau_a;
k[3] = - delta * (a_prev + k[2]) / tau_a;
a += (k[0] + 2 * k[1] + 2 * k[2] + k[3]) / 6;
b += delta * ((a_prev + a) / (2 * tau_a) - b_prev / tau_b);
*/
// Method 4
// RK4 for a, after that, RK4 for b
double k[4];
k[0] = -delta * a_prev / tau_a;
k[1] = -delta * (a_prev + k[0] / 2) / tau_a;
k[2] = -delta * (a_prev + k[1] / 2) / tau_a;
k[3] = -delta * (a_prev + k[2]) / tau_a;
a += (k[0] + 2 * k[1] + 2 * k[2] + k[3]) / 6;
k[0] = delta * (a_prev / tau_a - b_prev / tau_b);
k[1] = delta * ((a_prev + a) / (2 * tau_a) - (b_prev + k[0] / 2) / tau_b); // Explicit time dependent in N_A, linear intrapolate
k[2] = delta * ((a_prev + a) / (2 * tau_a) - (b_prev + k[1] / 2) / tau_b); // Explicit time dependent in N_A, linear intrapolate
k[3] = delta * (a / tau_a - (b_prev + k[2]) / tau_b);
b += (k[0] + 2 * k[1] + 2 * k[2] + k[3]) / 6;
}
// The outer wrapper of the ODE solver
void solver() {
double t_now = 0;
int n = 0;
// Get the parameters
cin >> t;
cin >> delta;
// Print parameters into the output file
out << "a = " << setw(16) << setprecision(4) << a << endl;
out << "b = " << setw(16) << setprecision(4) << b << endl;
out << "tau_a = " << setw(16) << setprecision(4) << tau_a << endl;
out << "tau_b = " << setw(16) << setprecision(4) << tau_b << endl;
out << "t = " << setw(16) << setprecision(4) << t << endl;
out << "delta = " << setw(16) << setprecision(4) << delta << endl;
// In actual implementation, it suffices to restore only the results of this iteration and the previes iteration
a_prev = a;
b_prev = b;
// Iteration
while (t_now <= t) {
n++;
out << setw(16) << setprecision(4) << t_now << setw(16) << setprecision(4) << a << setw(16) << setprecision(4) << b << endl;
// Different methods vary here.
solve_core();
t_now += delta;
// Update the results
a_prev = a;
b_prev = b;
}
out << setw(16) << setprecision(6) << t_now << setw(16) << setprecision(4) << a << setw(16) << setprecision(4) << b << endl;
// Linear intrapolate for the result, if t is not a multiple of Delta t
a = ((t - t_now) / delta + 1) * (a - a_prev) + a;
b = ((t - t_now) / delta + 1) * (b - b_prev) + b;
}
int main() {
a = b = 1;
cout << "Input the parameters in the following order: tau_a, tau_b, t, Delta t" << endl;
cin >> tau_a >> tau_b;
// Solve the ODE
solver();
cout << setw(16) << setprecision(4) << a << setw(16) << setprecision(4) << b << endl;
getchar();
getchar();
return 0;
} | true |
476335e1054fa5e97b2e91d2f1a4e1847b5c873e | C++ | 80mdelccc/Programas-2do-parcial | /programa 24/main.cpp | UTF-8 | 893 | 3.40625 | 3 | [] | no_license | #include <iostream>
using namespace std;
char nombre[30];
int turno;
double ventas, comis, pcomis;
void Datos(char nombre[], int &turno, double &ventas)
{
cout<<"Ingresar nombre....";
cin>>nombre;
do
{
cout<<"Ingresar turno 1-3....";
cin>>turno;
}
while (!(turno==1 or turno==2 or turno==3));
cout<<"Ingresar ventas....";
cin>>ventas;
}
double porcomis(int turno)
{
if(turno==1)
{
return 0.05;
}
else if(turno==2)
{
return 0.06;
}
else
{
return 0.04;
}
}
void calcular(double ventas, double &comis, double &pcomis, int turno)
{
pcomis= porcomis(turno);
comis= ventas*pcomis;
}
int main()
{
Datos(nombre, turno, ventas);
calcular(ventas, comis, pcomis, turno);
cout<<"Comision...."<<pcomis<<"\n";
cout<<"Comision ganada...."<<comis<<"\n";
return 0;
}
| true |
7375cab6fc72807f9d618328000498d0ed3ec5e2 | C++ | Owenyang1997/Cproject | /数据结构/ConsoleApplication3/ConsoleApplication3/Dog.cpp | GB18030 | 269 | 2.578125 | 3 | [] | no_license | #include "stdafx.h"
#include "Dog.h"
#include<iostream>
using namespace std;
Dog::Dog()
{
cout << "Dog캯" << endl;
}
Dog::~Dog()
{
cout << "Dog캯xiaoshi" << endl;
}
void main() {
Dog b;
b.setName("");
b.SetAge(6);
b.print();
} | true |
37df3a38b81030f7761fdc9aa4c0f337956f4c79 | C++ | ErikHorus1249/SPOJ-MS | /May/bai9.cpp | UTF-8 | 287 | 2.703125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
bool check = true;
for (int i = 2; i <= sqrt(n); i++) {
if(n % i == 0) check = false;
}
if(check) cout << " So n la so nguyen to : " ;
else cout << " So n khong phai la so nguyen to : " ;
}
| true |
2351338a716da8cb3b62e1bab71fa5057a40707b | C++ | Tomelinski/Snake | /Source.cpp | UTF-8 | 9,166 | 2.9375 | 3 | [] | no_license | /*
Author: Tom Zielinski
Date: 3/23/2020
Program: Snake
Program Description:
*/
#include "iostream"
#include "windows.h" // For colours, Beep(), and Sleep()
#include "conio.h" // For using the arrow keys
#include "Random.cpp"
#include "Console.cpp"
#include "fstream"
#include "vector"
#include "Users.cpp"
#include "algorithm"
using namespace std;
//ascii char for snake and boarder
const char wall = 219;
const char snake = 207;
const char fruit = 208;
const int winner = 120;
//map size
const int height = 20;
const int width = 40;
//variable
bool gameOver;
bool exitGame;
int snakeX, snakeY;
int fruitX, fruitY;
int tailX[winner], tailY[winner];
int tail;
int score;
int prevScore;
int UserChoise;
int deathChoise;
string username;
string save = "HighScore.save";
vector<Users> player;
enum eDirection { STOP = 0, UP, DOWN, RIGHT, LEFT };
eDirection dir;
void setup() {
UserChoise = 1;
deathChoise = 1;
gameOver = false;
exitGame = false;
dir = STOP;
snakeX = width / 2;
snakeY = height / 2;
fruitX = Random::Next(width - 2) + 1;
fruitY = Random::Next(height - 2) + 1;
tail = 0;
prevScore = score;
score = 0;
}
void draw() {
Console::Clear();
string board = "";
cout << "Score: " << score;
cout << "\n\n";
for (int i = 0; i <= height; i++)
{
for (int f = 0; f <= width; f++)
{
if (f == 0 || f == width || i == 0 || i == height) {
board += wall;
}
else {
if (f == snakeX && i == snakeY)
{
board += snake;
}
else if (f == fruitX && i == fruitY)
{
board += fruit;
}
else
{
bool print = false;
for (int j = 0; j < tail; j++)
{
if (tailX[j] == f && tailY[j] == i)
{
board += snake;
print = true;
}
}
if (!print)
{
board += " ";
}
}
}
}
board += "\n";
}
cout << board;
}
void input() {
if (_kbhit()) {
switch (_getch()) {
case'a':
dir = LEFT;
break;
case'd':
dir = RIGHT;
break;
case'w':
dir = UP;
break;
case's':
dir = DOWN;
break;
case'x':
//gameOver = true;
exitGame = true;
break;
}
}
}
void logic() {
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = snakeX;
tailY[0] = snakeY;
for (int i = 1; i < tail; i++)
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch (dir)
{
case UP:
snakeY--;
break;
case DOWN:
snakeY++;
break;
case RIGHT:
snakeX++;
break;
case LEFT:
snakeX--;
break;
default:
break;
}
if (snakeX <= 0 || snakeX >= width || snakeY <= 0 || snakeY >= height)
{
gameOver = true;
}
for (int i = 0; i < tail; i++)
{
if (snakeX == tailX[i] && snakeY == tailY[i])
{
gameOver = true;
}
}
if(snakeX == fruitX && snakeY == fruitY)
{
score += 10;
bool fruitSnake = false;
do
{
fruitX = Random::Next(width - 2) + 1;
fruitY = Random::Next(height - 2) + 1;
for (int i = 0; i < tail; i++)
{
fruitSnake = false;
if (fruitX == tailX[i] && fruitY == tailY[i])
{
fruitX = Random::Next(width - 2) + 1;
fruitY = Random::Next(height - 2) + 1;
fruitSnake = true;
break;
}
}
} while (fruitSnake);
tail++;
}
}
void sort() {
}
void saveGame() {
char uInput;
do
{
Console::Clear();
Console::Write(R"(
_____ __ __ ______ ____ __ __ ______ _____
/ ____| /\ | \/ | | ____| / __ \ \ \ / / | ____| | __ \
| | __ / \ | \ / | | |__ | | | | \ \ / / | |__ | |__) |
| | |_ | / /\ \ | |\/| | | __| | | | | \ \/ / | __| | _ /
| |__| | / ____ \ | | | | | |____ | |__| | \ / | |____ | | \ \
\_____| /_/ \_\ |_| |_| |______| \____/ \/ |______| |_| \_\)", Colour::Green);
cout << "\n your Score: " << score;
cout << "\nWould you like to save?";
if (deathChoise == 1)
{
Console::Write("[Yes] ", Colour::DarkGreen);
Console::Write("[No]", Colour::White);
}
else if (deathChoise == 2)
{
Console::Write("[Yes] ", Colour::White);
Console::Write("[No]", Colour::DarkGreen);
}
uInput = _getch();
if (uInput == 'a')
{
if (deathChoise == 1)
{
deathChoise = 2;
}
else
{
deathChoise--;
}
}
else if (uInput == 'd')
{
if (deathChoise == 2)
{
deathChoise = 1;
}
else
{
deathChoise++;
}
}
} while (uInput != (char)13);
char uName[4];
if (deathChoise == 1)
{
cout << "\nEnter Username: ";
cin.getline(uName, 4);
username = uName;
player.insert(player.end(), Users(username, score));
if (score > player[10].score)
{
ofstream outputFile;
sort(player.begin(), player.end(), Users::SortScore);
outputFile.open(save, ios::out);
outputFile << player[0].name << " " << player[0].score << "\n";
outputFile.close();
outputFile.open(save, ios::app);
for (int i = 1; i <= 9; i++)
{
outputFile << player[i].name << " " << player[i].score << "\n";
}
outputFile.close();
}
}
}
void HighScore() {
ifstream inputFile;
Console::Clear();
Console::Write(R"(
_ _ _____ _____ _ _ _____ _____ ____ _____ ______
| | | | |_ _| / ____| | | | | / ____| / ____| / __ \ | __ \ | ____|
| |__| | | | | | __ | |__| | | (___ | | | | | | | |__) | | |__
| __ | | | | | |_ | | __ | \___ \ | | | | | | | _ / | __|
| | | | _| |_ | |__| | | | | | ____) | | |____ | |__| | | | \ \ | |____
|_| |_| |_____| \_____| |_| |_| |_____/ \_____| \____/ |_| \_\ |______|)", Colour::DarkBlue);
cout << "\n";
inputFile.open(save);
string fileUserName;
int fileScore;
//if file does not exist
if (inputFile.fail())
{
Console::WriteError("Could not open " + save);
}
else
{
cout << " Username | Score\n";
for (int i = 1; i <= 10; i++)
{
inputFile >> fileUserName >> fileScore;
if (i < 10)
cout << i << ". " << fileUserName << " | " << fileScore << "\n";
else
cout << i << ". " << fileUserName << " | " << fileScore << "\n";
}
}
inputFile.close();
cout << "\nPress any key to Exit";
_getch();
}
void Dashboard() {
char uInput;
do
{
Console::Clear();
Console::Write(R"(
_____ _ _ _ __ ______ ______ __ __ ______
/ ____| | \ | | /\ | |/ / | ____| / ____| /\ | \/ | | ____|
| (___ | \| | / \ | ' / | |__ | | __ / \ | \ / | | |__
\___ \ | . ` | / /\ \ | < | __| | | |_ | / /\ \ | |\/| | | __|
____) | | |\ | / ____ \ | . \ | |____ | |__| | / ____ \ | | | | | |____
|_____/ |_| \_| /_/ \_\ |_|\_\ |______| \______| /_/ \_\ |_| |_| |______|)", Colour::Green);
cout << "\n";
cout << snake << " is your snake\n";
cout << wall << " is a wall\n";
cout << fruit << " is a fruit\n";
cout << "Use W-A-S-D to move\n";
cout << "Press x to exit\n";
cout << "\nYour Score: " << prevScore;
cout << "\n\n";
if (UserChoise == 1)
{
Console::WriteLine("Play Snake", Colour::DarkGreen);
Console::WriteLine("High Score", Colour::White);
Console::WriteLine("Exit", Colour::White);
}
else if (UserChoise == 2)
{
Console::WriteLine("Play Snake", Colour::White);
Console::WriteLine("High Score", Colour::DarkGreen);
Console::WriteLine("Exit", Colour::White);
}
else if (UserChoise == 3)
{
Console::WriteLine("Play Snake", Colour::White);
Console::WriteLine("High Score", Colour::White);
Console::WriteLine("Exit", Colour::DarkGreen);
}
uInput = _getch();
if (uInput == 'w')
{
if (UserChoise == 1)
{
UserChoise = 3;
}
else
{
UserChoise--;
}
}
else if (uInput == 's')
{
if (UserChoise == 3)
{
UserChoise = 1;
}
else
{
UserChoise++;
}
}
else if(uInput == 'x')
{
//gameOver = true;
exitGame = true;
UserChoise = 3;
break;
}
if (uInput == (char)13 && UserChoise == 3)
{
//gameOver = true;
exitGame = true;
break;
}
} while (uInput != (char)13);
}
// Program execution begins and ends here.
int main()
{
system("title Snake - Tom Zielinski");
ifstream inputFile;
inputFile.open(save);
string fileUserName;
int fileScore;
//if file does not exist
if (inputFile.fail())
{
Console::WriteError("Could not open " + save);
}
else
{
//inputFile >> fileUserName >> fileScore;
//player.insert(player.begin(), Users(fileUserName, fileScore));
for (int i = 0; i <= 10; i++)
{
inputFile >> fileUserName >> fileScore;
player.insert(player.end(), Users(fileUserName, fileScore));
}
}
inputFile.close();
do {
Random::Seed();
setup();
Dashboard();
if (UserChoise == 1)
{
do {
draw();
input();
logic();
Sleep(50);
} while (gameOver == false && exitGame == false);
if (gameOver == true && exitGame == false)
{
saveGame();
}
}
else if (UserChoise == 2)
{
HighScore();
}
} while (UserChoise != 3);
}
| true |
92c00810c56e2a902e8d5e7adf59f6cb7ba4a5a6 | C++ | opencv/opencv_contrib | /modules/cvv/src/qtutil/matchview/falsecolorkeypointpen.hpp | UTF-8 | 929 | 2.6875 | 3 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | #ifndef CVVISUAL_FALSE_COLOR_KEY_POINT_PEN
#define CVVISUAL_FALSE_COLOR_KEY_POINT_PEN
#include <vector>
#include "opencv2/features2d.hpp"
#include "keypointvaluechooser.hpp"
#include "keypointsettings.hpp"
namespace cvv
{
namespace qtutil
{
/**
* @brief this pen gives the falsecolor of the distance value to the key point
*/
class FalseColorKeyPointPen : public KeyPointSettings
{
Q_OBJECT
public:
/**
* @brief the constructor
* @param univers all keypoints (for max value)
* @param parent the parent Widget
*/
FalseColorKeyPointPen(std::vector<cv::KeyPoint> univers, QWidget *parent = nullptr);
/**
* @brief set the falseColor to the given keypoint
*/
virtual void setSettings(CVVKeyPoint &key) override;
private slots:
void updateMinMax();
private:
KeyPointValueChooser* valueChooser_;
std::vector<cv::KeyPoint> univers_;
double maxDistance_;
double minDistance_=0.0;//always 0
};
}
}
#endif
| true |
455f4eca58cbb246f24878f7e1d66c7720f18943 | C++ | skagnihotri/algorithm | /basics/100 door problem.cpp | UTF-8 | 241 | 2.8125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int flag;
for(int i = 1; i<101; i++){
flag = 0;
for(int j = 1; j <= i; j++){
if(i % j == 0){
flag += 1;
}
}
if(flag % 2 != 0){
cout<<i<<endl;
}
}
return 0;
} | true |
bbd1c096799f8ef6e007931368b07c6c3a207b2e | C++ | Keeganfn/CS-162 | /assignment5/linked_list.cpp | UTF-8 | 9,669 | 3.875 | 4 | [] | no_license | /******************************************************
** Program: linked_list.cpp
** Author: Keegan Nave
** Date: 06/09/2019
** Description: This is the implementation of my linked list class, it does all list functions and has sorting
** Input: takes input through push_back, push_front, and insert
** Output: outputs the list, length, prime numbers, and sorting
******************************************************/
#include "linked_list.h"
using namespace std;
/*********************************************************************
* ** Function: Constructor
* ** Description: sets values when object created
* ** Parameters: none
* *********************************************************************/
Linked_List::Linked_List(){
length = 0;
first = NULL;
}
/*********************************************************************
* ** Function: destructor
* ** Description: destructs object when it leaves scope, checks to make sure the list length is above 0
* ** Parameters: none
* *********************************************************************/
Linked_List::~Linked_List(){
if(length != 0){
clear();
}
}
/*********************************************************************
* ** Function: get_length
* ** Description: returns the length of the list
* ** Parameters: none
* *********************************************************************/
int Linked_List::get_length(){
return length;
}
/*********************************************************************
* ** Function: sort_ascending
* ** Description: Sorts the list ascending by calling the private sort functions then calling get_prime
* ** Parameters: none
* *********************************************************************/
void Linked_List::sort_ascending(){
if(length != 0){
first = ascending(first);
get_prime();
}
}
/*********************************************************************
* ** Function: get_prime
* ** Description: prints out the number of prime numbers found in the list
* ** Parameters:none
* *********************************************************************/
void Linked_List::get_prime(){
Linked_List_Node *temp;
temp = first;
int count = 0;
bool check;
while(temp != NULL){
if(temp->val <= 1){
temp = temp->next;
}
else{
check = true;
for(int i = 2; i < temp->val; i++){
if(temp->val % i == 0){
check = false;
}
}
if(check == true){
count++;
}
temp = temp->next;
}
}
cout << "You have " << count << " prime number(s) in your list" << endl;
}
/*********************************************************************
* ** Function: sort_descending
* ** Description: sorts by calling descending and then get_prime private functions
* ** Parameters: none
* *********************************************************************/
void Linked_List::sort_descending(){
if(length != 0){
first = descending(first);
get_prime();
}
}
/*********************************************************************
* ** Function:get_length_split
* ** Description:returns the length of the split list nodes to the recursive ascending and descending functions
* ** Parameters: A pointer to a Linked_List_Node
* *********************************************************************/
int Linked_List::get_length_split(Linked_List_Node *a){
int count = 0;
Linked_List_Node *temp = a;
while(temp != NULL){
count++;
temp = temp->next;
}
return count;
}
/*********************************************************************
* ** Function: ascending
* ** Description: recursively splits the linked list into smaller linked lists then calls the merge_ascending function
returns the head of the sorted linked list
* ** Parameters: The current head of the linked list
* *********************************************************************/
Linked_List_Node* Linked_List::ascending(Linked_List_Node *head){
Linked_List_Node *old = head;
int mid = get_length_split(head) / 2;
if(head->next == NULL){
return head;
}
while(mid - 1 > 0){
old = old->next;
mid--;
}
Linked_List_Node *new_head = old->next;
old->next = NULL;
old = head;
Linked_List_Node *n1 = ascending(old);
Linked_List_Node *n2 = ascending(new_head);
return merge_ascending(n1,n2);
}
/*********************************************************************
* ** Function: merge_ascending
* ** Description: recursively compares the values of the split nodes and puts them in order, returns the head of new list
* ** Parameters: pointer to node1 and node2
* *********************************************************************/
Linked_List_Node* Linked_List::merge_ascending(Linked_List_Node *n1, Linked_List_Node *n2){
Linked_List_Node *result = NULL;
if(n1 == NULL){
return n2;
}
if(n2 == NULL){
return n1;
}
if(n1->val > n2->val){
result = n2;
result->next = merge_ascending(n1, n2->next);
}
else{
result = n1;
result->next = merge_ascending(n1->next, n2);
}
return result;
}
/*********************************************************************
* ** Function: descending
* ** Description: recursively splits the linked list into smaller linked lists then calls the merge_descending function
returns the head of the sorted linked list
* ** Parameters: The current head of the linked list
* *********************************************************************/
Linked_List_Node* Linked_List::descending(Linked_List_Node *head){
Linked_List_Node *old = head;
int mid = get_length_split(head) / 2;
if(head->next == NULL){
return head;
}
while(mid - 1 > 0){
old = old->next;
mid--;
}
Linked_List_Node *new_head = old->next;
old->next = NULL;
old = head;
Linked_List_Node *n1 = descending(old);
Linked_List_Node *n2 = descending(new_head);
return merge_descending(n1,n2);
}
/*********************************************************************
* ** Function: merge_descending
* ** Description: recursively compares the values of the split nodes and puts them in order, returns the head of new list
* ** Parameters: pointer to node1 and node2
* *********************************************************************/
Linked_List_Node* Linked_List::merge_descending(Linked_List_Node *n1, Linked_List_Node *n2){
Linked_List_Node *result = NULL;
if(n1 == NULL){
return n2;
}
if(n2 == NULL){
return n1;
}
if(n1->val < n2->val){
result = n2;
result->next = merge_descending(n1, n2->next);
}
else{
result = n1;
result->next = merge_descending(n1->next, n2);
}
return result;
}
/*********************************************************************
* ** Function:insert
* ** Description:Inserts a new Linked list node at a specified index
* ** Parameters:value for the new node and the index to be placed at
* *********************************************************************/
unsigned int Linked_List::insert(int val, unsigned int index){
if(index > length || index < 0){
cout << "That is not a valid index" << endl;
return length;
}
if(index == 0){
push_front(val);
return length;
}
if(index == length){
push_back(val);
return length;
}
Linked_List_Node *temp;
Linked_List_Node *new_node;
Linked_List_Node *pushed_node;
temp = first;
for(unsigned int i = 0; i < length; i++){
if(i == index-1){
new_node = new Linked_List_Node();
new_node->val = val;
pushed_node = temp->next;
temp->next = new_node;
new_node->next = pushed_node;
}
temp = temp->next;
}
length++;
return length;
}
/*********************************************************************
* ** Function: push_back
* ** Description: pushes a new node to the back of the list and sets its value
* ** Parameters: value of the new node
* *********************************************************************/
unsigned int Linked_List::push_back(int node_val){
if(first == NULL){
first = new Linked_List_Node();
first->val = node_val;
length++;
}
else{
Linked_List_Node *temp;
temp = first;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = new Linked_List_Node();
temp = temp->next;
temp->val = node_val;
length++;
}
return length;
}
/*********************************************************************
* ** Function: push_front
* ** Description: pushes a new node to the front of the list making it the new head
* ** Parameters: value for the new node
* *********************************************************************/
unsigned int Linked_List::push_front(int node_val){
Linked_List_Node *temp;
temp = first;
first = new Linked_List_Node();
first->next = temp;
first->val = node_val;
length++;
return length;
}
/*********************************************************************
* ** Function:clear
* ** Description:Clears the linked list and frees all memory, sets head back to null and length to 0
* ** Parameters: none
* *********************************************************************/
void Linked_List::clear(){
Linked_List_Node *temp;
temp = first->next;
Linked_List_Node *temp2;
for(unsigned int i = 0; i < length-1; i++){
temp2 = temp->next;
delete temp;
temp = temp2;
}
delete first;
first = NULL;
length = 0;
}
/*********************************************************************
* ** Function: print
* ** Description: Prints the full list
* ** Parameters: none
* *********************************************************************/
void Linked_List::print(){
Linked_List_Node *temp;
temp = first;
for(unsigned int i = 0; i < length; i++){
cout << temp->val << " ";
temp = temp->next;
}
cout << endl;
}
| true |
ba4093337924957700f497e0094feac5ffcc94fb | C++ | flyq/datastruct-algorithm | /others/fast_sqrt/c_version/test.cpp | UTF-8 | 2,654 | 2.984375 | 3 | [
"MIT"
] | permissive | // TestC.cpp : 定义控制台应用程序的入口点。
//
//#include <stdafx.h>
#include <math.h>
//#include <windows.h>
#define eps 1e-7
float InvSqrt(float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x; // get bits for floating VALUE
i = 0x5f375a86- (i>>1); // gives initial guess y0
x = *(float*)&i; // convert bits BACK to float
x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy
x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy
x = x*(1.5f-xhalf*x*x); // Newton step, repeating increases accuracy
return 1/x;
}
float SqrtByNewton(float x)
{
float val = x;//最终
float last;//保存上一个计算的值
do
{
last = val;
val =(val + x/val) / 2;
}while(abs(val-last) > eps);
return val;
}
float SqrtByBisection(float n) //用二分法
{
if(n<0) //小于0的按照你需要的处理
return n;
float mid,last;
float low,up;
low=0,up=n;
mid=(low+up)/2;
do
{
if(mid*mid>n)
up=mid;
else
low=mid;
last=mid;
mid=(up+low)/2;
}while(abs(mid-last) > eps);//精度控制
return mid;
}
int _tmain(int argc, _TCHAR* argv[])
{
unsigned int LoopCount = 1000;
float x = 65535;
LARGE_INTEGER d1,d2,d3,d4,d5;
QueryPerformanceCounter(&d1);
for(unsigned int i=0;i<LoopCount;i++)
SqrtByBisection(x);
QueryPerformanceCounter(&d2);
for(unsigned int i=0;i<LoopCount;i++)
SqrtByNewton(x);
QueryPerformanceCounter(&d3);
for(unsigned int i=0;i<LoopCount;i++)
InvSqrt(x);
QueryPerformanceCounter(&d4);
for(unsigned int i=0;i<LoopCount;i++)
sqrt(x);
QueryPerformanceCounter(&d5);
printf("下面是计算sqrt(65535)结果的对比\n");
printf("-----------------------------------------\n");
printf(" 方法 \t时间\t计算结果\n");
printf("二分法 : %8.2f\t%8.8f\n",((float)d2.QuadPart - (float)d1.QuadPart)/LoopCount,SqrtByBisection(x));
//printf("牛顿迭代法 : %8.2f\t%8.8f\n",((float)d3.QuadPart - (float)d2.QuadPart)/LoopCount,SqrtByNewton(x));
//printf("神奇的方法 : %8.2f\t%8.8f\n",((float)d4.QuadPart - (float)d3.QuadPart)/LoopCount,InvSqrt(x));
//printf("System方法 : %8.2f\t%8.8f\n",((float)d5.QuadPart - (float)d4.QuadPart)/LoopCount,sqrt(x));
printf("二分法 : %8.2f\t%8.8f\n",((float)d2.QuadPart - (float)d1.QuadPart),SqrtByBisection(x));
printf("牛顿迭代法 : %8.2f\t%8.8f\n",((float)d3.QuadPart - (float)d2.QuadPart),SqrtByNewton(x));
printf("神奇的方法 : %8.2f\t%8.8f\n",((float)d4.QuadPart - (float)d3.QuadPart),InvSqrt(x));
printf("System方法 : %8.2f\t%8.8f\n",((float)d5.QuadPart - (float)d4.QuadPart),sqrt(x));
printf("-----------------------------------------\n");
return 0;
}
| true |
7a8ef73e9f6d2684e4e7d7576448bfbf0797f3e5 | C++ | du0002in/stereovision-on-road-detection | /P_RANSAC.cpp | UTF-8 | 11,720 | 2.5625 | 3 | [
"MIT"
] | permissive | // mex file to run RANSAC to improve speed
// input: 2xn matrix with 1st row being x and 2nd row being y. n refers to the number of points
// ouput: 1xn matrix (or row vector) to indicate whether the corresponding points are inliers (1) or not (0)
// fitting left and right img seperately
#include "mex.h"
#include <math.h>
#include <time.h>
#include <string.h>
#include <omp.h>
#include <vector>
void CallInv(double *v, double *u, double *bedf)
{
mxArray *A, *invA, *B;
mxArray *ppLhs[1];
double *ptr, *A_ptr, *B_ptr; int i;
A=mxCreateDoubleMatrix(4,4,mxREAL);
A_ptr=mxGetPr(A);
B=mxCreateDoubleMatrix(4,1,mxREAL);
B_ptr=mxGetPr(B);
for (i=0;i<4;i++) {
*(A_ptr+i)=pow(*(v+i),2);
*(A_ptr+i+4)=*(v+i);
*(A_ptr+i+8)=*(u+i);
*(A_ptr+i+12)=1;
*(B_ptr+i)=(*(u+i))*(*(v+i));
}
// memcpy(mxGetPr(A), Data, sizeof(double)*4*4);
mexCallMATLAB(1, ppLhs, 1, &A, "inv");
invA=ppLhs[0];
ptr=mxGetPr(invA);
for (i=0; i<4; i++) {
bedf[i]=(*(ptr+i))*(*B_ptr)+(*(ptr+i+4))*(*(B_ptr+1))+(*(ptr+i+8))*(*(B_ptr+2))+(*(ptr+i+12))*(*(B_ptr+3));
}
mxDestroyArray(A);
mxDestroyArray(B);
mxDestroyArray(invA);
}
void Invert2(double *v,double *u, double *bedf)
{
double mat[16];
double tmp[12]; /* temp array for pairs */
double src[16]; /* array of transpose source matrix */
double dst[16];
double B[4];
double det; /* determinant */
for (int i=0; i<4; i++) {
mat[i]=pow(*(v+i),2);
mat[i+4]=*(v+i);
mat[i+8]=*(u+i);
mat[i+12]=1;
B[i]=(*(u+i))*(*(v+i));
}
/* transpose matrix */
for (int i = 0; i < 4; i++) {
src[i] = mat[i*4];
src[i + 4] = mat[i*4 + 1];
src[i + 8] = mat[i*4 + 2];
src[i + 12] = mat[i*4 + 3];
}
/* calculate pairs for first 8 elements (cofactors) */
tmp[0] = src[10] * src[15];
tmp[1] = src[11] * src[14];
tmp[2] = src[9] * src[15];
tmp[3] = src[11] * src[13];
tmp[4] = src[9] * src[14];
tmp[5] = src[10] * src[13];
tmp[6] = src[8] * src[15];
tmp[7] = src[11] * src[12];
tmp[8] = src[8] * src[14];
tmp[9] = src[10] * src[12];
tmp[10] = src[8] * src[13];
tmp[11] = src[9] * src[12];
/* calculate first 8 elements (cofactors) */
dst[0] = tmp[0]*src[5] + tmp[3]*src[6] + tmp[4]*src[7];
dst[0] -= tmp[1]*src[5] + tmp[2]*src[6] + tmp[5]*src[7];
dst[1] = tmp[1]*src[4] + tmp[6]*src[6] + tmp[9]*src[7];
dst[1] -= tmp[0]*src[4] + tmp[7]*src[6] + tmp[8]*src[7];
dst[2] = tmp[2]*src[4] + tmp[7]*src[5] + tmp[10]*src[7];
dst[2] -= tmp[3]*src[4] + tmp[6]*src[5] + tmp[11]*src[7];
dst[3] = tmp[5]*src[4] + tmp[8]*src[5] + tmp[11]*src[6];
dst[3] -= tmp[4]*src[4] + tmp[9]*src[5] + tmp[10]*src[6];
dst[4] = tmp[1]*src[1] + tmp[2]*src[2] + tmp[5]*src[3];
dst[4] -= tmp[0]*src[1] + tmp[3]*src[2] + tmp[4]*src[3];
dst[5] = tmp[0]*src[0] + tmp[7]*src[2] + tmp[8]*src[3];
dst[5] -= tmp[1]*src[0] + tmp[6]*src[2] + tmp[9]*src[3];
dst[6] = tmp[3]*src[0] + tmp[6]*src[1] + tmp[11]*src[3];
dst[6] -= tmp[2]*src[0] + tmp[7]*src[1] + tmp[10]*src[3];
dst[7] = tmp[4]*src[0] + tmp[9]*src[1] + tmp[10]*src[2];
dst[7] -= tmp[5]*src[0] + tmp[8]*src[1] + tmp[11]*src[2];
/* calculate pairs for second 8 elements (cofactors) */
tmp[0] = src[2]*src[7];
tmp[1] = src[3]*src[6];
tmp[2] = src[1]*src[7];
tmp[3] = src[3]*src[5];
tmp[4] = src[1]*src[6];
tmp[5] = src[2]*src[5];
tmp[6] = src[0]*src[7];
tmp[7] = src[3]*src[4];
tmp[8] = src[0]*src[6];
tmp[9] = src[2]*src[4];
tmp[10] = src[0]*src[5];
tmp[11] = src[1]*src[4];
/* calculate second 8 elements (cofactors) */
dst[8] = tmp[0]*src[13] + tmp[3]*src[14] + tmp[4]*src[15];
dst[8] -= tmp[1]*src[13] + tmp[2]*src[14] + tmp[5]*src[15];
dst[9] = tmp[1]*src[12] + tmp[6]*src[14] + tmp[9]*src[15];
dst[9] -= tmp[0]*src[12] + tmp[7]*src[14] + tmp[8]*src[15];
dst[10] = tmp[2]*src[12] + tmp[7]*src[13] + tmp[10]*src[15];
dst[10]-= tmp[3]*src[12] + tmp[6]*src[13] + tmp[11]*src[15];
dst[11] = tmp[5]*src[12] + tmp[8]*src[13] + tmp[11]*src[14];
dst[11]-= tmp[4]*src[12] + tmp[9]*src[13] + tmp[10]*src[14];
dst[12] = tmp[2]*src[10] + tmp[5]*src[11] + tmp[1]*src[9];
dst[12]-= tmp[4]*src[11] + tmp[0]*src[9] + tmp[3]*src[10];
dst[13] = tmp[8]*src[11] + tmp[0]*src[8] + tmp[7]*src[10];
dst[13]-= tmp[6]*src[10] + tmp[9]*src[11] + tmp[1]*src[8];
dst[14] = tmp[6]*src[9] + tmp[11]*src[11] + tmp[3]*src[8];
dst[14]-= tmp[10]*src[11] + tmp[2]*src[8] + tmp[7]*src[9];
dst[15] = tmp[10]*src[10] + tmp[4]*src[8] + tmp[9]*src[9];
dst[15]-= tmp[8]*src[9] + tmp[11]*src[10] + tmp[5]*src[8];
/* calculate determinant */
det=src[0]*dst[0]+src[1]*dst[1]+src[2]*dst[2]+src[3]*dst[3];
/* calculate matrix inverse */
det = ((det==0)?0:1/det);
for (int j = 0; j < 16; j++)
dst[j] *= det;
for (int i=0; i<4; i++) {
bedf[i]=(*(dst+i))*(*B)+(*(dst+i+4))*(*(B+1))+(*(dst+i+8))*(*(B+2))+(*(dst+i+12))*(*(B+3));
}
}
/*
void LRegression(double *v,double *u, double *cefp)
{
double vbar=0, ubar=0, vubar=0, u2bar=0;
for (int i=0;i<4;i++) {
ubar=ubar+*(u+i);
vbar=vbar+*(v+i);
vubar=vubar+*(u+i)**(v+i);
u2bar=u2bar+*(u+i)**(u+i);
}
ubar=ubar/4; vbar=vbar/4; vubar=vubar/2; u2bar=u2bar/4;
*(cefp+1)=1.0;
*cefp=-(vubar-vbar*ubar)/(u2bar-ubar*ubar);
*(cefp+2)=-(vbar+*cefp*ubar);
}
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double *Datapoint, *FinalLine, *SubDatapoint, *hypo_ptr;
size_t ncols, sub_ncols;
//size_t Randpoint[4];
int j;
int tcon_pre=0;
//mxArray *hypo;
//double Cp1, Cp2, Cp3, x, y, x1, deno,t_dist;
/*
v=mxGetPr(prhs[0]);
u=mxGetPr(prhs[1]);
plhs[0]=mxCreateDoubleMatrix(4,1,mxREAL);
FinalLine=mxGetPr(plhs[0]);
CallInv(v,u, FinalLine);
if (~mxIsDouble(bedf))
mexPrintf("no solution");
*/
srand(time(NULL));
Datapoint=mxGetPr(prhs[0]);
SubDatapoint=mxGetPr(prhs[1]);
ncols=mxGetN(prhs[0]);
sub_ncols=mxGetN(prhs[1]);
plhs[0]=mxCreateDoubleMatrix(1,ncols,mxREAL);
FinalLine=mxGetPr(plhs[0]);
plhs[1]=mxCreateDoubleMatrix(7,1,mxREAL);
hypo_ptr=mxGetPr(plhs[1]);
//plhs[2]=mxCreateDoubleMatrix(1,1,mxREAL);
//total_num_ptr=mxGetPr(plhs[2]);
//plhs[2]=mxCreateDoubleMatrix(1,1,mxREAL);
//dumy=mxGetPr(plhs[2]);
// Randpoint[0]=0; Randpoint[1]=0; Randpoint[2]=0; Randpoint[3]=0;
// distsqr=mxCreateDoubleMatrix(1,(int)ncols,mxREAL);
//distsqr_ptr=mxGetPr(distsqr);
//line=mxCreateDoubleMatrix(1,ncols,mxREAL);
//line_ptr=mxGetPr(line);
//distsqr1=mxCreateDoubleMatrix(1,(int)ncols,mxREAL);
//distsqr_ptr1=mxGetPr(distsqr1);
//line1=mxCreateDoubleMatrix(1,ncols,mxREAL);
//line_ptr1=mxGetPr(line1);
//V=mxCreateDoubleMatrix(4,1,mxREAL);
//U=mxCreateDoubleMatrix(4,1,mxREAL);
//v=mxGetPr(V);
//u=mxGetPr(U);
//BEDF=mxCreateDoubleMatrix(4,1,mxREAL);
//bedf=mxGetPr(BEDF);
#pragma omp parallel for num_threads(4)
for(j=0;j<960;j++)
{
int tcon=0; int tcon1=0;
//for (int i=0;i<4;i++) {
// Randpoint[i]=rand() % sub_ncols;
// *(v+i)=*(SubDatapoint+2*Randpoint[i]);
// *(u+i)=*(SubDatapoint+2*Randpoint[i]+1);
//}
//*v=-227; *(v+1)=-156; *(v+2)=-91; *(v+3)=-22;
//*u=15; *(u+1)=116; *(u+2)=207; *(u+3)=305;
int rand1=rand() % sub_ncols;
//mxArray *V=mxCreateDoubleMatrix(4,1,mxREAL);
//mxArray *U=mxCreateDoubleMatrix(4,1,mxREAL);
//double *v=mxGetPr(V);
//double *u=mxGetPr(U);
double v[4],u[4];
*v=*(SubDatapoint+2*rand1);
*u=*(SubDatapoint+2*rand1+1);
rand1=rand() % sub_ncols;
*(v+1)=*(SubDatapoint+2*rand1);
*(u+1)=*(SubDatapoint+2*rand1+1);
rand1=rand() % sub_ncols;
*(v+2)=*(SubDatapoint+2*rand1);
*(u+2)=*(SubDatapoint+2*rand1+1);
rand1=rand() % sub_ncols;
*(v+3)=*(SubDatapoint+2*rand1);
*(u+3)=*(SubDatapoint+2*rand1+1);
//mxArray *BEDF=mxCreateDoubleMatrix(4,1,mxREAL);
//double *bedf=mxGetPr(BEDF);
double bedf[4];
//CallInv(v,u,bedf);
Invert2(v,u,bedf);
double B=*bedf;double E=*(bedf+1); double D=*(bedf+2);double F=*(bedf+3);
double C=E+B*D; double A=F+C*D;
double e,c,f,fp;
if (*u==*(u+3))
{
e=0; c=1; f=-2**u; fp=f/2;
}
else
{
c=-(*v-*(v+3))/(*u-*(u+3));
e=1;
f=2*(-c**u-*v);
fp=f/2;
}
//double cefp[3];
//LRegression(v,u,cefp);
//c=cefp[0]; e=cefp[1]; fp=cefp[2];
double deno=c*c+e*e;
double Cp1, Cp2, Cp3, x, y, x1,t_dist,dist;
//mxArray *line1=mxCreateDoubleMatrix(1,ncols,mxREAL);
//double *line_ptr1=mxGetPr(line1);
double *line_ptr1=new double[ncols];
//mxArray *line=mxCreateDoubleMatrix(1,ncols,mxREAL);
//double *line_ptr=mxGetPr(line);
//double line_ptr[ncols];
double *line_ptr=new double[ncols];
//D=-300;
if (D>-120) {
for (int i=0; i<ncols; i++) {
x=*(Datapoint+2*i+1);
y=*(Datapoint+2*i);
if (tcon1+ncols-i>tcon_pre) {
t_dist=1.0-(y+20.0)/55;
dist=pow(c*x+e*y+fp,2)/deno;
if (dist<t_dist){
tcon1++;
*(line_ptr1+i)=1;}
else
*(line_ptr1+i)=0;
}
if (tcon+ncols-i>tcon_pre) {
if (y>=D) {
*(line_ptr+i)=0;
continue;
}
x1=A/(y-D)+B*y+C;
if (abs(x-x1)>10) {
*(line_ptr+i)=0;
continue;
}
Cp1=(D-y)*0.5;
Cp2=(E-x1)*0.5+B*y;
Cp3=F+(D*x1+E*y)*0.5;
dist=pow(x*Cp1+y*Cp2+Cp3,2)/4.0/(Cp1*Cp1+Cp2*Cp2);
t_dist=0.5-(y+20.0)/110;
if (dist<t_dist){
tcon++;
*(line_ptr+i)=1;}
else
*(line_ptr+i)=0;
}
if (tcon1+ncols-i<=tcon_pre && tcon+ncols-i<=tcon_pre)
break;
}
}
else {
for (int i=0; i<ncols; i++) {
if (tcon1+ncols-i>tcon_pre) {
x=*(Datapoint+2*i+1);
y=*(Datapoint+2*i);
t_dist=1.0-(y+20.0)/55;
dist=pow(c*x+e*y+fp,2)/deno;
if (dist<t_dist) {
tcon1++;
*(line_ptr1+i)=1;}
else
*(line_ptr1+i)=0;
*(line_ptr+i)=0;
}
else
break;
}
}
#pragma omp critical
{
if (tcon>tcon_pre || tcon1>tcon_pre)
{
if (tcon>tcon1) {
tcon_pre=tcon;
//*total_num_ptr=tcon_pre;
*(hypo_ptr)=B;*(hypo_ptr+1)=E;*(hypo_ptr+2)=D;*(hypo_ptr+3)=F;
*(hypo_ptr+4)=0;*(hypo_ptr+5)=0;*(hypo_ptr+6)=0;
for (int i=0;i<ncols;i++)
*(FinalLine+i)=*(line_ptr+i);
//if (tcon>0.9*ncols)
// j=250;
}
else {
tcon_pre=tcon1;
//*total_num_ptr=tcon_pre;
*(hypo_ptr)=0;*(hypo_ptr+1)=0;*(hypo_ptr+2)=0;*(hypo_ptr+3)=0;
*(hypo_ptr+4)=c;*(hypo_ptr+5)=e;*(hypo_ptr+6)=f;
for (int i=0;i<ncols;i++)
*(FinalLine+i)=*(line_ptr1+i);
//if (tcon1>0.9*ncols)
// j=250;
}
}
}
delete [] line_ptr1;
delete [] line_ptr;
}
//mxDestroyArray(line);
//mxDestroyArray(distsqr);
//mxDestroyArray(V);
//mxDestroyArray(U);
//mxDestroyArray(BEDF);
}
/*
if (u[0]==u[1])
{
e=0; c=1; f=-2*u[0]; fp=f/2;
}
else
{
c=-(v[0]-v[1])/(u[0]-u[1]);
e=1;
f=2*(-c*u[0]-v[0]);
fp=f/2;
}
deno=c*c+e*e;
for (i=0;i<ncols;i++)
{
*(distsqr_ptr+i)=pow(c**(Datapoint+2*i)+e*(*(Datapoint+2*i+1))+fp,2)/deno;
if (*(distsqr_ptr+i)<10){
tcon++;
*(line_ptr+i)=1;}
else
*(line_ptr+i)=0;
}
if (tcon<50)
continue;
if (tcon>tcon_pre)
{
tcon_pre=tcon;
for (i=0;i<ncols;i++)
*(FinalLine+i)=*(line_ptr+i);
if (tcon>0.9*ncols)
break;
}
}
mxDestroyArray(line);
mxDestroyArray(distsqr);
}
*/ | true |
8b8f0a142eb80dd27bde2b8b899285d0c48448b8 | C++ | jhemdan/collision | /collision/src/world.cpp | UTF-8 | 2,834 | 2.703125 | 3 | [] | no_license | #include "world.h"
#include "entity.h"
#include "jaw_macros.h"
#include "cam_ent.h"
#include <algorithm>
namespace jaw
{
World::World()
{
layer_flag = false;
cam_ent = new CamEnt();
cam_ent->size = { 400.0f, 300.0f };
add_entity(cam_ent);
}
World::~World()
{
delete cam_ent;
}
void World::add_entity(Entity* e)
{
if(e)
_to_add.push_back(e);
}
void World::remove_entity(Entity* e)
{
if(e)
_to_remove.push_back(e);
}
void World::flush()
{
//go through pending added entities and add them to main list
//calling on_added() and giving them this world
if (!_to_add.empty())
{
for (int i = 0; i < (int)_to_add.size(); ++i)
{
auto e = _to_add[i];
//make sure the world for this entity is null or this world
//the reason I allow "this" to be the world of the entity is so if we add it multiple times it doesn't matter
JAW_ASSERT_MSG(e->world == nullptr || e->world == this, "Bad entity world value for World::flush()");
if (!e->world)
{
entities.push_back(e);
e->world = this;
//need to sort by layers everytime a new entity is added
layer_flag = true;
_buffer.push_back(e);
}
}
_to_add.clear();
for (auto e : _buffer)
{
e->on_added();
}
_buffer.clear();
}
//go through pending removed entities and remove them from the main list
//calling on_removed() and changing their world to nullptr
if (!_to_remove.empty())
{
for (int i = 0; i < (int)_to_remove.size(); ++i)
{
auto e = _to_remove[i];
if (e->world == this)
{
auto it = std::find(entities.begin(), entities.end(), e);
if (it != entities.end())
{
entities.erase(it);
e->world = nullptr;
_buffer.push_back(e);
}
}
}
_to_remove.clear();
for (auto e : _buffer)
{
//give them back this world real quick so they can work with it in on_removed()
e->world = this;
e->on_removed();
//take away the world again
e->world = nullptr;
if (e->destroy_on_remove)
delete e;
}
_buffer.clear();
}
}
void World::update(float dt)
{
flush();
//update all entities
for (auto e : entities)
{
e->update(dt);
}
//sort the entities by their layer number
if (layer_flag)
{
auto sorter = [](Entity* a, Entity* b)
{
return a->_layer < b->_layer;
};
std::sort(entities.begin(), entities.end(), sorter);
layer_flag = false;
}
cam_tran = cam_ent->get_cam_tran();
}
void World::render(Renderer* renderer)
{
for (auto e : entities)
{
e->render(renderer);
}
}
void World::clear()
{
//call on_removed() on all entities
for (auto e : entities)
{
e->on_removed();
if (e->destroy_on_remove)
delete e;
}
_to_add.clear();
_to_remove.clear();
entities.clear();
}
} | true |
b7895e0ac23a5d5e2f8a365454c9562d9bc4fb05 | C++ | George-Tech/cpp_stl | /data_search.cpp | GB18030 | 1,523 | 3.5 | 4 | [] | no_license | #include "data_struct_head.h"
#include <vector>
void proc_search()
{
vector<int> seq{ 2, 4, 1, 3, 6, 8 };
vector<int> hal{ 1, 2, 3, 4, 5, 6, 9 };
cout << "˳ң3 = " << seq_search(seq, 3) << endl;
cout << "ң3 = " << half_search(hal, 2) << endl;
cout << "ң6 = " << half_res_search(hal, 2, 0, 6) << endl;
vector<int> mon{ 1, 2, 3, 4, 5, 6, 2, 0};
cout << "moutain_search = " << moutain_search(mon) << endl;
}
int seq_search(vector<int> a, int key)
{
int k = -1;
for (int i = 0; i < a.size(); i++) {
if (key == a[i]) {
k = i;
break;
}
}
return k;
}
int half_search(vector<int> a, int key)
{
int low, mid, high;
low = 0;
high = a.size() - 1;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == key)
return mid;
else if (key < a[mid])
high = mid - 1;
else if (key > a[mid])
low = mid + 1;
}
return -1;
}
int half_res_search(vector<int> a, int key, int low, int high)
{
if (low > high)
return -1;
int mid = (low + high) / 2;
if (a[mid] == key)
return mid;
if (key < a[mid])
return half_res_search(a, key, low, mid-1);
if (key > a[mid])
return half_res_search(a, key, mid+1, high);
}
int moutain_search(vector<int> a)
{
int low, mid, high;
low = 0;
high = a.size();
while (low <= high)
{
int mid = (low + high) / 2;
if (a[mid] >= a[mid - 1] && a[mid] >= a[mid + 1])
return a[mid];
else if (a[mid] < a[mid - 1])
high = mid;
else if (a[mid] < a[mid + 1])
low = mid;
}
return a[(low + high) / 2];
} | true |
b93e07799496d48ec3f4113435bfa712d0c3c4c0 | C++ | dmoa/vision-blurry | /Depricated/_StateMachine/State.hpp | UTF-8 | 403 | 2.53125 | 3 | [] | no_license | namespace
{
class State
{
private:
Draw(sf::RenderWindow* window);
Update(sf::Int32* dt, sf::Event* event);
// we don't need to pass the window (into update), because we already polled the window for events and filled "event" up
// with things such as keys pressed, so there's no need to poll again.
// now we can just cycle through the keypressed events contained inside event.
};
} | true |
6dd3a9acea50c244fad449697074dfb273da4586 | C++ | xiaochun-yang/19-ID | /RobotDHS/src/activeObject.cpp | UTF-8 | 1,369 | 2.609375 | 3 | [] | no_license | #include "activeObject.h"
#include "XOSSingleLock.h"
activeObject::activeObject( ):
m_Status(STOPPED),
m_CmdStop(FALSE),
m_CmdReset(FALSE),
m_FlagEmergency(FALSE),
m_ObserverList( 10 )
{
xos_mutex_create( &m_ObserverQLock );
}
activeObject::~activeObject( )
{
xos_mutex_close( &m_ObserverQLock );
}
BOOL activeObject::Attach( Observer* pObserver )
{
if (pObserver == NULL) return FALSE;
XOSSingleLock holdLock( &m_ObserverQLock );
return m_ObserverList.AddHead( pObserver );
}
BOOL activeObject::Detach( Observer* pObserver )
{
if (pObserver == NULL) return TRUE;
XOSSingleLock holdLock( &m_ObserverQLock );
return m_ObserverList.RemoveElement( pObserver );
}
//help function for derived class
void activeObject::SetStatus( Status newStatus )
{
//check to see if any change
if (newStatus == m_Status) return;
//set new status
m_Status = newStatus;
//broad cast to interested threads to wake up
XOSSingleLock holdLock( &m_ObserverQLock );
for (int pos = m_ObserverList.GetFirst( ); pos != LIST_ELEMENT_NOT_FOUND; pos = m_ObserverList.GetNext( pos ))
{
Observer* pObserver = m_ObserverList.GetAt( pos );
if (pObserver)
{
pObserver->ChangeNotification( this );
}
}
}
| true |
33623bd5ff8e10ed9bb59e778ca7ec6e4d138bd4 | C++ | Xu-Xihe/codes-and-docs-xxh | /openjudge/1.2/10.cpp | UTF-8 | 143 | 2.578125 | 3 | [] | no_license | #include<iostream>
#include<cstring>
using namespace std;
int main()
{
char d[]="Hello, World!";
int a;
a=sizeof(d);
cout<<a;
}
| true |
ec949c2802a793e97cc0a243ffb7762177e3e5d8 | C++ | vshyshkin/pwr | /semester-3/tep/lab11/diffindividual.h | UTF-8 | 834 | 2.703125 | 3 | [] | no_license | #ifndef DIFFINDIVIDUAL_H
#define DIFFINDIVIDUAL_H
#include "mscnproblem.h"
class DiffIndividual
{
public:
DiffIndividual();
DiffIndividual(double fitness, Table<double> &genotype, bool areConstraintsSatisfied);
double getFitness() const;
void setFitness(double value);
Table<double> getGenotype() const;
void setGenotype(const Table<double> &value);
void setGenotypeAt(const double value, const int offset) const;
bool getAreContraintsSatisfied() const;
void setAreContraintsSatisfied(bool value);
friend std::ostream& operator<< (std::ostream &os, const DiffIndividual &ind)
{
os << "[ " << ind.genotype << " ]\n" << std::endl;
return os;
}
private:
Table<double> genotype;
double fitness;
bool areConstraintsSatisfied;
};
#endif // DIFFINDIVIDUAL_H
| true |
b7739f1d927402bb6c5336f4d0dd98a2a64fdc32 | C++ | Kallaf/UVA | /MATHEMATICS/NUMBER THEORY/Functions involving Prime Factors/UVa 00294.cpp | UTF-8 | 1,412 | 2.609375 | 3 | [] | no_license | #include<bits/stdc++.h>
#define ll long long int
#define vi vector<int>
using namespace std;
ll _sieve_size;
bitset<1000000010> bs;
vi primes;
void sieve(ll upperbound) {
_sieve_size = upperbound + 1;
bs.set();
bs[0] = bs[1] = 0;
for (ll i = 2; i <= _sieve_size; i++)
if (bs[i]) {
for (ll j = i * i; j <= _sieve_size; j += i)
bs[j] = 0;
primes.push_back((int)i);
}
}
ll numDiv(ll N) {
ll PF_idx = 0, PF = primes[PF_idx], ans = 1;
// start from ans = 1
while (PF * PF <= N) {
ll power = 0;
// count the power
while (N % PF == 0) { N /= PF; power++; }
ans *= (power + 1);
// according to the formula
PF = primes[++PF_idx];
}
if (N != 1) ans *= 2;
// (last factor has pow = 1, we add 1 to it)
return ans;
}
ll n,k,m;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
//--------------------------
sieve(1000000);
scanf("%lld",&n);
while(n--)
{
scanf("%lld%lld",&k,&m);
ll mx = 0,mxI;
for(ll i=k;i<=m;i++)
{
ll curr = numDiv(i);
if(curr > mx)
{
mx = curr;
mxI = i;
}
}
printf("Between %lld and %lld, %lld has a maximum of %lld divisors.\n",k,m,mxI,mx);
}
return 0;
}
| true |
2238f064c5318d0acb542bf79d78be05fc716797 | C++ | clwyatt/CTC | /Reference/HongLi/src/common/Dicom.cc | UTF-8 | 5,945 | 2.859375 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /********************************************************
File: Dicom.cc
Abstract: Implementation for Dicom
See header (Dicom.hh) for documentation
Last Revision ($Revision: 1.1.1.1 $)
by $Author: hongli $
on $Date: 2002/12/06 21:49:32 $
*********************************************************/
#include "Dicom.hh"
#include <fstream>
#include <cstdio>
IMTK::Dicom::Dicom()
{
dcmObj = NULL;
contents = NULL;
}
IMTK::Dicom::Dicom(const Dicom & D)
{
}
IMTK::Dicom::~Dicom()
{
close();
}
bool IMTK::Dicom::open(const std::string &theFile)
{
ifstream infile;
int length = 0;
infile.open( theFile.c_str() );
if(!infile){
cerr << "Error opening file: " << theFile.c_str() << endl;
return false;
}
// get length of file:
infile.seekg(0, ios::end);
length = infile.tellg();
infile.seekg(0, ios::beg);
// allocate space
contents = new unsigned char[length];
//read the entire file into a char buffer
infile.read(contents, length);
infile.close();
if(length == 0) return false;
// if the CTN DICOM object exists, close it first
if(dcmObj != NULL) close();
// use the CTN code to load the DICOM object
CONDITION cond;
cond = DCM_ImportStream(contents, length, DCM_ORDERLITTLEENDIAN, &dcmObj);
if(cond != DCM_NORMAL){
dcmObj = NULL;
return false;
}
// everything is OK if we got here
return true;
}
void IMTK::Dicom::close()
{
if(dcmObj != NULL)
DCM_CloseObject(&dcmObj);
if(contents != NULL)
delete [] contents;
dcmObj = NULL; //reset so it can be reused
contents = NULL;
}
bool IMTK::Dicom::getCharElement(DCM_TAG tag, char * & pChar)
{
assert(dcmObj != NULL);
// get the tag
CONDITION cond;
DCM_ELEMENT element;
cond = DCM_GetElement(&dcmObj, tag, &element);
if(cond != DCM_NORMAL) return false;
// allocate the space
pChar = new char[element.length+1];
// get the char array
element.d.string = pChar;
void *ctx = NULL;
U32 size;
cond = DCM_GetElementValue(&dcmObj, &element, &size, &ctx);
if(cond != DCM_NORMAL){
delete [] pChar;
pChar = NULL;
return false;
}
// make char array a well formed string
pChar[element.length] = '\0';
// if we got here, everything is OK
return true;
}
bool IMTK::Dicom::getUShortElement(DCM_TAG tag, unsigned short & value)
{
assert(dcmObj != NULL);
// get the tag
CONDITION cond;
DCM_ELEMENT element;
cond = DCM_GetElement(&dcmObj, tag, &element);
if(cond != DCM_NORMAL) return false;
// check the length matches an unsigned short
if( element.length != sizeof(value) ) return false;
// get the value
element.d.us = &value;
void *ctx = NULL;
U32 size;
cond = DCM_GetElementValue(&dcmObj, &element, &size, &ctx);
if(cond != DCM_NORMAL){
value = 0;
return false;
}
// if we got here, everything is OK
return true;
}
bool IMTK::Dicom::getOrigin(float & xo, float &yo, float &zo)
{
bool opOK;
char * pChar = NULL;
opOK = getCharElement(DCM_RELIMAGEPOSITIONPATIENT, pChar);
if(!opOK){ //try a different tag
opOK = getCharElement(DCM_RELSLICELOCATION, pChar);
if(!opOK) return false;
xo = 0.0; // these are not defined if used DCM_RELSLICELOCATION
yo = 0.0; // fill in with these default values
zo = atof(pChar);
// free up pChar
delete [] pChar;
return true;
}
// numbers are seperated by "\\", split up
char *temp;
temp = strtok(pChar, "\\");
if(temp == 0){
delete [] pChar;
return false;
}
xo = atof(temp);
temp = strtok(NULL, "\\");
if(temp == 0){
delete [] pChar;
return false;
}
yo = atof(temp);
temp = strtok(NULL, "\\");
if(temp == 0){
delete [] pChar;
return false;
}
zo = atof(temp);
delete [] pChar;
return true;
}
bool IMTK::Dicom::getDims(unsigned short &xdim, unsigned short &ydim)
{
bool opOK;
opOK = getUShortElement(DCM_IMGCOLUMNS, xdim);
if(!opOK) return false;
opOK = getUShortElement(DCM_IMGROWS, ydim);
if(!opOK) return false;
return true;
}
bool IMTK::Dicom:: getImageOrientP(float &x_x, float &x_y, float &x_z, float &y_x, float &y_y, float &y_z)
{
bool opOK;
char * pChar = NULL;
opOK = getCharElement(DCM_RELIMAGEORIENTATIONPATIENT, pChar);
if(!opOK) return false;
// numbers are seperated by "\\", split up
char *temp;
temp = strtok(pChar, "\\");
if(temp == 0){
delete [] pChar;
return false;
}
x_x = atof(temp);
temp = strtok(NULL, "\\");
if(temp == 0){
delete [] pChar;
return false;
}
x_y = atof(temp);
temp = strtok(NULL, "\\");
if(temp == 0){
delete [] pChar;
return false;
}
x_z = atof(temp);
temp = strtok(NULL, "\\");
if(temp == 0){
delete [] pChar;
return false;
}
y_x = atof(temp);
temp = strtok(NULL, "\\");
if(temp == 0){
delete [] pChar;
return false;
}
y_y = atof(temp);
temp = strtok(NULL, "\\");
if(temp == 0){
delete [] pChar;
return false;
}
y_z = atof(temp);
delete [] pChar;
return true;
}
bool IMTK::Dicom::getPxlSize(float &dx, float &dy)
{
bool opOK;
char * pChar = NULL;
opOK = getCharElement(DCM_IMGPIXELSPACING, pChar);
if(!opOK) return false;
// numbers are seperated by "\\", split up
char *temp;
temp = strtok(pChar, "\\");
if(temp == 0){
delete [] pChar;
return false;
}
dx = atof(temp);
temp = strtok(NULL, "\\");
if(temp == 0){
delete [] pChar;
return false;
}
dy = atof(temp);
delete [] pChar;
return true;
}
bool IMTK::Dicom::getSliceNum(int &slice)
{
bool opOK;
char * pChar = NULL;
opOK = getCharElement(DCM_RELIMAGENUMBER, pChar);
if(!opOK) return false;
slice = atoi(pChar);
delete [] pChar;
return true;
}
bool IMTK::Dicom::getData(unsigned short *data)
{
assert(dcmObj != NULL);
// get the tag
CONDITION cond;
DCM_ELEMENT element;
cond = DCM_GetElement(&dcmObj, DCM_PXLPIXELDATA, &element);
if(cond != DCM_NORMAL) return false;
// get the data
element.d.ot = data;
void *ctx = NULL;
U32 size;
cond = DCM_GetElementValue(&dcmObj, &element, &size, &ctx);
if(cond != DCM_NORMAL) return false;
// if we got here, everything is OK
return true;
}
| true |
c12a712e0d580640594c1ca56f7b4a6ff7d49be6 | C++ | BitJetKit/FastHumanDetection | /src/fhd_block_allocator.cpp | UTF-8 | 2,641 | 2.953125 | 3 | [
"MIT"
] | permissive | #include "fhd_block_allocator.h"
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
struct fhd_alloc_slot {
void* ptr;
int idx;
};
struct fhd_block_allocator {
int block_size;
int num_bytes;
int num_blocks;
uint8_t* memory;
int free_indices_len;
int* free_indices;
int full_slots_len;
fhd_alloc_slot* full_slots;
};
fhd_block_allocator* fhd_block_allocator_create(int block_size,
int num_blocks) {
fhd_block_allocator* block_alloc =
(fhd_block_allocator*)calloc(1, sizeof(fhd_block_allocator));
block_alloc->block_size = block_size;
block_alloc->num_bytes = block_size * num_blocks;
block_alloc->num_blocks = num_blocks;
block_alloc->memory = (uint8_t*)calloc(block_alloc->num_bytes, 1);
block_alloc->free_indices_len = num_blocks;
block_alloc->free_indices = (int*)calloc(num_blocks, sizeof(int));
block_alloc->full_slots_len = 0;
block_alloc->full_slots =
(fhd_alloc_slot*)calloc(num_blocks, sizeof(fhd_alloc_slot));
for (int i = 0; i < num_blocks; i++) {
block_alloc->free_indices[i] = i;
}
return block_alloc;
}
void fhd_block_allocator_destroy(fhd_block_allocator* block_alloc) {
free(block_alloc->memory);
free(block_alloc->free_indices);
free(block_alloc->full_slots);
free(block_alloc);
}
void* fhd_block_allocator_acquire(fhd_block_allocator* block_alloc) {
if (block_alloc->free_indices_len == 0) return NULL;
const int free_idx =
block_alloc->free_indices[block_alloc->free_indices_len - 1];
const int offset = free_idx * block_alloc->block_size;
uint8_t* block = block_alloc->memory + offset;
const fhd_alloc_slot slot = {block, free_idx};
block_alloc->full_slots[block_alloc->full_slots_len++] = slot;
block_alloc->free_indices_len--;
return block;
}
void fhd_block_allocator_release(fhd_block_allocator* block_alloc, void* ptr) {
for (int i = 0; i < block_alloc->full_slots_len; i++) {
fhd_alloc_slot slot = block_alloc->full_slots[i];
if (ptr == slot.ptr) {
block_alloc->free_indices[block_alloc->free_indices_len] = slot.idx;
for (int j = i; j < block_alloc->full_slots_len - 1; j++) {
block_alloc->full_slots[j] = block_alloc->full_slots[j + 1];
}
block_alloc->free_indices_len++;
block_alloc->full_slots_len--;
return;
}
}
}
void fhd_block_allocator_clear(fhd_block_allocator* block_alloc) {
for (int i = 0; i < block_alloc->full_slots_len; i++) {
block_alloc->free_indices[block_alloc->free_indices_len++] =
block_alloc->full_slots[i].idx;
}
block_alloc->full_slots_len = 0;
}
| true |
23010bd98cb6b4a94bf877163300727f704568da | C++ | VoronovaMasha/nrtl | /core/meshalgorithm/MeshAlgorithm.h | UTF-8 | 3,753 | 2.546875 | 3 | [] | no_license | #ifndef MESHALGORITHM_H
#define MESHALGORITHM_H
#include "meshmodel.h"
#include <QMatrix4x4>
#include <string>
#include <QMutex>
struct MeshTopology
{
static QString errorString()
{
return _error_string;
}
static PolygonMatrix makePolygonMatrix(MeshModel* mesh);
static MeshBorder makeBorder(MeshModel* mesh);
static MeshModel* makeSurface(MeshModel* a , MeshModel* b);
private:
static QString _error_string;
};
class MeshCutter
{
public:
static MeshModel* cutFromMesh(DataId mesh_id);
static QString errorString()
{
return _error_string;
}
class CutVertexes
{
public:
static QVector<QVector3D>& get()
{
return cutVertexes;
}
static bool set(QVector<QVector3D> new_cutVertexes,QVector<QVector3D> new_tr_cutVertexes)
{
if(new_tr_cutVertexes.size()>0)
cutVertexes=new_cutVertexes+new_tr_cutVertexes;
else
cutVertexes=new_cutVertexes;
if(cutVertexes.size()<3)
_error_string=QString("You must choose at least 3 vertexes.");
else
_error_string=QString("No error");
return true;
}
};
class ViewMatrix
{
public:
static QMatrix4x4 get()
{
return ViewMatrix2;
}
static bool set(QMatrix4x4 ViewMatrix)
{
ViewMatrix2=ViewMatrix;
return true;
}
};
private:
static QString _error_string;
static QVector<QVector3D> cutVertexes;
static QMatrix4x4 ViewMatrix2;
};
struct SimpleMesh
{
SimpleMesh(QVector<VertexData> dat, QVector<GLuint> ind, QImage img) :
vertData(dat), indexes(ind), texture(img)
{}
QVector<VertexData> vertData;
QVector<GLuint> indexes;
QImage texture;
QVector<QVector<unsigned int>> polygons;
QVector<QVector<unsigned int>> texpolygons;
QVector<QVector3D> coords;
QVector<QVector2D> texcoords;
};
class MeshModelLoader
{
public:
class OBJ
{
public:
static void loadMesh();
};
enum Status { RUN, WAIT };
static QString errorString()
{
return _error_string;
}
static Status getStatus()
{
return _status;
}
static int getProgress()
{
return _progress;
}
static void setPath(QString path)
{
_path = path;
}
static QString getPath()
{
return _path;
}
static MeshModel* getMesh()
{
if(mesh != nullptr)
{
meshModel = new MeshModel(mesh->vertData, mesh->indexes, mesh->texture);
meshModel->polygons = mesh->polygons;
meshModel->coords = mesh->coords;
meshModel->texcoords=mesh->texcoords;
meshModel->texpolygons=mesh->texpolygons;
double x=0.f,y=0.f,z=0.f;
for(int i=0;i<mesh->coords.size();i++)
{
x+=mesh->coords[i].x()/mesh->coords.size();
y+=mesh->coords[i].y()/mesh->coords.size();
z+=mesh->coords[i].z()/mesh->coords.size();
}
meshModel->translate(QVector3D(-x,-y,-z));
delete mesh;
mesh = nullptr;
return meshModel;
}
else return nullptr;
}
private:
static QString _error_string;
static volatile Status _status;
static volatile int _progress; //from 0 to 100
static QString _path;
static bool centerize;
static SimpleMesh* mesh;
static MeshModel* meshModel;
};
class AlignMesh
{
public:
static QMatrix4x4 getAlignMatrix(QVector<QVector3D> dst, QVector<QVector3D> src);
};
#endif // MESHALGORITHM_H
| true |
e008ca371892535f664ab3f5986649cc373d15e3 | C++ | IanFeldman/dungeon-crawler | /dungeon.cpp | UTF-8 | 15,598 | 3 | 3 | [] | no_license | #include "dungeon.h"
#include "game.h"
#include "node.h"
#include "room.h"
#include "wall.h"
#include "collisioncomponent.h"
#include "spritecomponent.h" // unneeded
#include "player.h" // unneeded
#include <vector>
#include <set>
#include <iostream>
#include <string>
#include <map>
Dungeon::Dungeon(Game* game)
:mGame(game)
,mRoomCount(10)
,mDungeonSize(3200, 3200)
,mCsvSize(mGame->GetCsvSize())
{
}
void Dungeon::GenerateLevel()
{
PlaceNodes();
PickRooms();
PlaceRooms();
ConnectRooms();
FindPaths();
}
void Dungeon::PlaceNodes()
{
// set up node grid with as many nodes as can fit in the dungeon size
// nodes are each 3 csv tiles by 3 csv tiles (96 world units)
std::cout << "Placing Nodes..." << std::endl;
// offset start by a little bit, and go up by three wall tiles
for (int j = int(mCsvSize.y * 1.5f); j < mDungeonSize.y; j += int(3.0f * mCsvSize.y))
{
std::vector<Node*> row;
for (float i = int(mCsvSize.x * 1.5f); i < mDungeonSize.x; i += int(3.0f * mCsvSize.x))
{
Node* node = new Node(mGame);
node->SetPosition(Vector2(i, j));
row.push_back(node);
// initialize the node map
mNodesUsed.emplace(node, false);
}
mNodeGrid.push_back(row);
}
// get node neighbors
for (int j = 0; j < mNodeGrid.size(); j++)
{
for (int i = 0; i < mNodeGrid[0].size(); i++)
{
if (mNodeGrid[j][i] != nullptr) {
if (i > 0)
{
if (mNodeGrid[j][i - 1] != nullptr)
{
mNodeGrid[j][i]->AddNeighbor(mNodeGrid[j][i - 1]);
}
}
if (i < mNodeGrid[0].size() - 1)
{
if (mNodeGrid[j][i + 1] != nullptr)
{
mNodeGrid[j][i]->AddNeighbor(mNodeGrid[j][i + 1]);
}
}
if (j > 0)
{
if (mNodeGrid[j - 1][i] != nullptr)
{
mNodeGrid[j][i]->AddNeighbor(mNodeGrid[j - 1][i]);
}
}
if (j < mNodeGrid.size() - 1)
{
if (mNodeGrid[j + 1][i] != nullptr)
{
mNodeGrid[j][i]->AddNeighbor(mNodeGrid[j + 1][i]);
}
}
}
}
}
std::cout << "Done!" << std::endl;
}
void Dungeon::PickRooms()
{
// create mRoomCount number of rooms, and make each one a clone of a random room type initialized in mgame
std::cout << "Picking Rooms..." << std::endl;
std::vector<Room*> roomTypes = mGame->GetRoomTypes();
// entrance
// exit
// boss
// shop
// normal
for (int i = 0; i < mRoomCount; i++)
{
int random = rand() % roomTypes.size();
mInitialRooms.push_back(Clone(roomTypes[random]));
}
std::cout << "Done!" << std::endl;
}
Room* Dungeon::Clone(Room* room)
{
// create a new room that is nearly identical to room
Room* newRoom = new Room(mGame, room->GetSize(), nullptr);
newRoom->SetSprite(room->GetSprite());
// clone walls also
for (Wall* w : room->GetWalls())
{
Wall* newWall = new Wall(mGame, w->GetRelativePos(), room);
newRoom->AddWall(newWall);
}
return newRoom;
}
void Dungeon::PlaceRooms()
{
// place each room at a random position that lines up with node grid
// avoid overlapping rooms and delete rooms that can't be fit in
// associate each room with the nodes that are in it
std::cout << "Placing Rooms..." << std::endl;
std::vector<Room*> positionedRooms;
bool dungeonFull = false;
// for each room
for (Room* r : mInitialRooms)
{
// delete the extra rooms
if (dungeonFull)
{
// destroy room and its walls
DestroyRoom(r);
continue;
}
bool intersect = true;
int placeAttempts = 0;
while (intersect)
{
int nodeGridWidth = mNodeGrid[0].size();
int nodeGridHeight = mNodeGrid.size();
// pick random position
int xIndex = rand() % (int)(nodeGridWidth - (r->GetSize().x / 3.0f)); // row length
int yIndex = rand() % (int)(nodeGridHeight - (r->GetSize().y / 3.0f)); // number of columns
Vector2 roomPos = mNodeGrid[yIndex][xIndex]->GetPosition();
// set corner to node position
roomPos += (Vector2((r->GetSize().x * 0.5f - 1.5f) * mCsvSize.x, (r->GetSize().y * 0.5f - 1.5f) * mCsvSize.y));
r->SetPosition(roomPos);
// check overlap
intersect = false;
for (Room* other : positionedRooms)
{
CollisionComponent* thisCC = r->GetComponent<CollisionComponent>();
CollisionComponent* otherCC = other->GetComponent<CollisionComponent>();
intersect = thisCC->Intersect(otherCC);
if (intersect)
break;
}
// check if dungeon is full
if (intersect)
placeAttempts++;
if (placeAttempts > 500)
{
std::cerr << "Error: over 500 room placement attempts" << std::endl;
std::cout << "Stopping at " + std::to_string(positionedRooms.size()) + " rooms" << std::endl;
// destroy this room and its walls
DestroyRoom(r);
// continue to all the next rooms and destroy them
dungeonFull = true;
intersect = false; // just to break out of the while loop
}
}
// on the first loop that dungeonfull, make sure to skip adding room to vector
if (dungeonFull)
continue;
// associate rooms and nodes
FindNodes(r);
positionedRooms.push_back(r);
mRooms.push_back(r);
// position walls (for debugging)
for (Wall* w : r->GetWalls())
w->SetPosition(w->GetRelativePos() + r->GetPosition());
}
mInitialRooms.clear();
std::cout << "Done!" << std::endl;
}
void Dungeon::DestroyRoom(Room* room)
{
// destroy room's walls
for (Wall* w : room->GetWalls())
w->SetState(ActorState::Destroy);
// destroy room
room->SetState(ActorState::Destroy);
}
void Dungeon::FindNodes(Room* room)
{
// finds all the nodes within a room's bounds
// adds nodes to a vector in room
// adds room to variable in nodes
// x coord of left edge
int leftEdge = room->GetPosition().x - room->GetSize().x * 0.5f * mCsvSize.x;
// x coord in node lengths (three csv sizes)
// the left edge is in between nodes so we always want to round up
int minNodeX = ceil(leftEdge / (3.0f * mCsvSize.x));
// y coord of top edge
int topEdge = room->GetPosition().y - room->GetSize().y * 0.5f * mCsvSize.y;
// y coord in node lengths (three csv sizes)
// the top edge is in between nodes so we always want to round up
int minNodeY = ceil(topEdge / (3.0f * mCsvSize.y));
// set max nodes
int maxNodeX = minNodeX + floor(room->GetSize().x / 3.0f); // divide room size because it is in csv units and nodes are 3 csv units long
if (maxNodeX > mNodeGrid[0].size())
maxNodeX = mNodeGrid[0].size();
int maxNodeY = minNodeY + floor(room->GetSize().y / 3.0f);
if (maxNodeY > mNodeGrid.size())
maxNodeY = mNodeGrid.size();
// set nodes
for (int j = minNodeY; j < maxNodeY; j++)
{
for (int i = minNodeX; i < maxNodeX; i++)
{
Node* node = mNodeGrid[j][i];
node->SetRoom(room);
node->GetComponent<SpriteComponent>()->SetTexture(mGame->GetTexture("assets/debug/blue.png"));
room->AddNode(node);
}
}
}
void Dungeon::ConnectRooms()
{
// connect all rooms with minimum spanning tree
std::cout << "Connecting Rooms..." << std::endl;
// construct initial graph
std::set<Room*> graphVertices; // set of rooms
std::map <std::set<Room*>, float> graphEdges; // map of edges as keys, and cost as entry
for (Room* r : mRooms)
{
// add all rooms to vertex set
graphVertices.emplace(r);
// create edges
for (Room* other : mRooms)
{
// ignore if rooms are the same
if (other == r)
continue;
// create edge
std::set<Room*> edge;
edge.emplace(r);
edge.emplace(other);
// cost is distance
float cost = (other->GetPosition() - r->GetPosition()).Length();
// add to edges map
graphEdges.emplace(edge, cost);
}
}
// prims algorithm finds min spanning tree
std::set<std::set<Room*>> tree; // set of edges that will be the final tree
std::set<Room*> treeVerts; // set of vertices in the tree
// start with a vertex
Room* initVertex = *graphVertices.begin();
treeVerts.emplace(initVertex);
while (tree.size() < graphVertices.size() - 1)
{
std::set<std::set<Room*>> potentialEdges;
// for every vertex in the tree
for (Room* v : treeVerts)
{
// for every edge in the graph
for (auto it = graphEdges.begin(); it != graphEdges.end(); it++)
{
std::set<Room*> graphEdge = it->first;
if (graphEdge.find(v) != graphEdge.end()) // if edge contains init vertex, add edge to potential edges
potentialEdges.emplace(graphEdge);
}
}
// weed out the edges that are already in the tree
std::set<std::set<Room*>> tempEdges = potentialEdges;
potentialEdges.clear();
// for all potential edges
for (std::set<Room*> edge : tempEdges)
{
bool inTree = (tree.find(edge) != tree.end());
int vertsInTree = 0;
for (Room* v : edge)
{
// find edge in tree verts
if (treeVerts.find(v) != treeVerts.end())
vertsInTree++;
}
// if the edge is not in the tree and only one vertex is part of the tree, keep it
if (!inTree && vertsInTree == 1)
potentialEdges.emplace(edge);
}
// pick cheapest potential edge
int minCost = INT32_MAX;
std::set<Room*> cheapestEdge;
for (std::set<Room*> edge : potentialEdges) // iterate over potential edges to find the cheapest one
{
if (graphEdges[edge] < minCost)
{
cheapestEdge = edge;
minCost = graphEdges[edge];
}
}
if (!cheapestEdge.empty())
{
// add edge to tree and add verts to treeVerts
tree.emplace(cheapestEdge);
for (Room* v : cheapestEdge)
treeVerts.emplace(v);
}
else
{
std::cerr << "Could not find cheapest edge" << std::endl;
return;
}
}
// add back in some edges
/*
int addedEdgeCount = 0.1f * graphEdges.size();
for (int i = 0; i < addedEdgeCount; i++)
{
int random = rand() % graphEdges.size();
auto it = graphEdges.begin();
std::advance(it, random);
std::set<Room*> edge = it->first;
// only add it if it isn't already in tree
if (tree.find(edge) == tree.end())
tree.emplace(edge);
}
*/
mMinSpanningTree = tree;
std::cout << "Done!" << std::endl;
}
void Dungeon::FindPaths()
{
std::cout << "Pathfinding..." << std::endl;
for (std::set<Room*> edge : mMinSpanningTree)
{
std::vector<Node*> path;
auto it = edge.begin();
Room* a = *it;
it++;
Room* b = *it;
std::pair<Node*, Node*> nodes = GetStartAndEndNodes(a, b);
if (nodes.first == nullptr || nodes.second == nullptr)
continue;
path = Pathfind(nodes.first, nodes.second);
for (Node* n : path)
{
n->GetComponent<SpriteComponent>()->SetTexture(mGame->GetTexture("assets/debug/green.png"));
}
}
std::cout << "Done!" << std::endl;
}
std::pair<Node*, Node*> Dungeon::GetStartAndEndNodes(class Room* start, class Room* end)
{
std::pair<Node*, Node*> nodes = std::make_pair(nullptr, nullptr);
// get potential starting nodes
std::vector<Node*> potentialStartNodes;
for (Node* n : start->GetNodes())
{
// the node has to be unused and have a usable neighbor
bool nodeUsed = true;
bool usableNeighbors = false;
nodeUsed = mNodesUsed[n];
for (Node* neighbor : n->GetNeighbors())
{
// at least one of the neighbors is not part of the room and isn't used
if (neighbor->GetRoom() == nullptr && !mNodesUsed[neighbor])
{
usableNeighbors = true;
break;
}
}
if (!nodeUsed && usableNeighbors)
potentialStartNodes.push_back(n);
}
if (potentialStartNodes.empty())
{
std::cerr << "No available starting nodes" << std::endl;
return nodes;
}
// same process for end nodes
std::vector<Node*> potentialEndNodes;
for (Node* n : end->GetNodes())
{
// the node has to be unused and on the edge
bool nodeUsed = true;
bool usableNeighbors = false;
nodeUsed = mNodesUsed[n];
for (Node* neighbor : n->GetNeighbors())
{
// at least one of the neighbors is not part of the room and isn't used
if (neighbor->GetRoom() == nullptr && !mNodesUsed[neighbor])
usableNeighbors = true;
}
if (!nodeUsed && usableNeighbors)
potentialEndNodes.push_back(n);
}
if (potentialEndNodes.empty())
{
std::cerr << "No available starting nodes" << std::endl;
return nodes;
}
// get closest combination of start and end node
float minDist = INT32_MAX;
Node* startNode = nullptr;
Node* endNode = nullptr;
for (Node* start : potentialStartNodes)
{
for (Node* end : potentialEndNodes)
{
float dist = (end->GetPosition() - start->GetPosition()).Length();
if (dist < minDist)
{
minDist = dist;
startNode = start;
endNode = end;
}
}
}
if (startNode == nullptr || endNode == nullptr)
{
std::cerr << "Start and/or end node are null" << std::endl;
return nodes;
}
startNode->GetComponent<SpriteComponent>()->SetTexture(mGame->GetTexture("assets/debug/yellow.png"));
endNode->GetComponent<SpriteComponent>()->SetTexture(mGame->GetTexture("assets/debug/yellow.png"));
nodes = std::make_pair(startNode, endNode);
return nodes;
}
// a star
std::vector<Node*> Dungeon::Pathfind(Node* startNode, Node* endNode)
{
// to push back if there is an error
std::vector<Node*> emptyPath;
// open set
std::set<Node*> openSet;
openSet.emplace(startNode);
std::set<Node*> closedSet;
// initialize starting node
startNode->SetFScore(0.0f);
while (!openSet.empty())
{
// current node is the one with the lowest total cost
// find node in open set with lowest score
Node* currentNode = nullptr;
int minScore = INT32_MAX;
for (Node* n : openSet)
{
if (n->GetFScore() < minScore) {
currentNode = n;
minScore = n->GetFScore();
}
}
// remove current node from open set
if (openSet.find(currentNode) != openSet.end())
openSet.erase(currentNode);
// add current to closed set
closedSet.emplace(currentNode);
// check if end
if (currentNode == endNode)
{
// the end
// reconstruct path
std::vector<Node*> path;
path.push_back(currentNode);
Node* tempNode = currentNode;
while (tempNode->GetPreviousNode() != nullptr)
{
tempNode = tempNode->GetPreviousNode();
path.push_back(tempNode);
}
for (Node* n : path)
{
mNodesUsed[n] = true;
}
return path;
}
// look through neighbors
for (Node* neighbor : currentNode->GetNeighbors())
{
// if neighbor is in closed set, skip
if (closedSet.find(neighbor) != closedSet.end())
continue;
// if neighbor is associated with a room and that neighbor is not the final node, then skip this neighbor
if (neighbor->GetRoom() != nullptr && neighbor != endNode)
{
closedSet.emplace(neighbor);
continue;
}
// if the neighbor is already used, skip to next neighbor
if (mNodesUsed[neighbor])
{
closedSet.emplace(neighbor);
continue;
}
int gScore = currentNode->GetGScore() + mCsvSize.x * 3.0f;
int hScore = abs(endNode->GetPosition().x - neighbor->GetPosition().x) + abs(endNode->GetPosition().y - neighbor->GetPosition().y);
neighbor->SetGScore(gScore);
neighbor->SetHScore(hScore);
neighbor->SetFScore(gScore + hScore);
neighbor->SetPreviousNode(currentNode);
// if neighbor is not in open set, add him
if (openSet.find(neighbor) == openSet.end())
{
openSet.emplace(neighbor);
}
}
}
std::cerr << "No path found" << std::endl;
return emptyPath;
} | true |
46e3144ca15a00fbaa5a4cfd038c59bfef814ab9 | C++ | simeonfilev/Tickets | /sources/Event.cpp | UTF-8 | 2,468 | 3.390625 | 3 | [] | no_license | //
// Created by Moni on 04-May-20.
//
#include "../headers/Event.h"
const std::string &Event::getName() const {
return name;
}
void Event::setName(const std::string &name) {
Event::name = name;
}
const Hall Event::getHall() const {
return this->hall;
}
void Event::setHall(const Hall hall) {
Event::hall = hall;
}
Event::Event() {
int seatsCount = (this->getHall().getSeats() * this->getHall().getRows());
for (int i = 0; i < seatsCount; i++) {
this->seats.push_back(-1);
}
}
Event::Event(const std::string &name, const Hall &hall, const Date &date) {
int seatsCount = ((hall.getRows()) * (hall.getSeats()));
for (int i = 0; i < seatsCount; i++) {
this->seats.push_back(-1);
}
this->setName(name);
this->setHall(hall);
this->setDate(date);
}
int Event::getDay() const {
return this->date.getDay();
}
int Event::getMonth() const {
return this->date.getMonth();
}
int Event::getYear() const {
return this->date.getYear();
}
const std::vector<int> &Event::getSeats() const {
return seats;
}
//! books a ticket on given row and seat and if adds a note if exist
void Event::bookTicket(int row, int seat, const std::string ¬e) {
Hall h = this->getHall();
int seatToBook = ((row - 1) * h.getSeats()) + (seat - 1);
this->seats[seatToBook] = 0;
this->notes.insert(std::pair<std::pair<int, int>, std::string>(std::make_pair(row, seat), note));
}
//! unbooks a note on given row and seat
void Event::unbookTicket(int row, int seat) {
Hall h = this->getHall();
int seatToUnBook = ((row - 1) * h.getSeats()) + (seat - 1);
this->seats[seatToUnBook] = -1;
this->notes.erase(std::make_pair(row, seat)); //delete old note
}
//! buys a ticket on given row and seat
void Event::buyTicket(int row, int seat) {
Hall h = this->getHall();
int seatToUnBook = ((row - 1) * h.getSeats()) + (seat - 1);
this->seats[seatToUnBook] = 1;
}
//! return the number of tickets bought
int Event::getBoughtTicketsCount() const {
int counter = 0;
for (int i = 0; i < this->getSeats().size(); i++) {
if (this->getSeats()[i] == 1) {
counter++;
}
}
return counter;
}
bool Event::operator<(const Event &other) const {
return getBoughtTicketsCount() > other.getBoughtTicketsCount();
}
const Date &Event::getDate() const {
return date;
}
void Event::setDate(const Date &date) {
Event::date = date;
}
| true |
484d7a54e534f673c98b6a6943d3080dcc6444ff | C++ | HaikuArchives/Paladin | /Paladin/PreviewFeatures/CommandOutputHandler.cpp | UTF-8 | 2,064 | 2.796875 | 3 | [
"MIT"
] | permissive | #include "CommandOutputHandler.h"
#include <string>
#include <iostream>
#include <Handler.h>
#include "CommandThread.h"
CommandOutputHandler::CommandOutputHandler(bool reto)
: BHandler(),
out(),
err(),
redirectErrToOut(reto),
exited(false),
failed(false)
{
;
}
CommandOutputHandler::~CommandOutputHandler()
{
;
}
std::string
CommandOutputHandler::GetOut() const
{
return std::string(out);
}
std::string
CommandOutputHandler::GetErr() const
{
return std::string(err);
}
bool
CommandOutputHandler::IsErrRedirectedToOut() const
{
return redirectErrToOut;
}
bool
CommandOutputHandler::HasExited() const
{
return exited;
}
void
CommandOutputHandler::WaitForExit() const
{
while (!HasExited()) {
snooze(100000);
}
}
bool
CommandOutputHandler::HasFailed() const
{
return failed;
}
void
CommandOutputHandler::MessageReceived(BMessage* msg)
{
//std::cout << "CommandOutputHandler::MessageReceived" << std::endl;
BString content;
switch (msg->what)
{
case M_COMMAND_RECEIVE_STDOUT:
{
//std::cout << "received std out" << std::endl;
if (B_OK == msg->FindString("output", &content))
{
//std::cout << "Content: " << content << std::endl;
out += content;
}
}
case M_COMMAND_RECEIVE_STDERR:
{
//std::cout << "received std err" << std::endl;
if (redirectErrToOut)
{
if (B_OK == msg->FindString("error", &content))
{
//std::cout << "Content: " << content << std::endl;
out += content;
}
} else {
if (B_OK == msg->FindString("error", &content))
{
//std::cout << "Content: " << content << std::endl;
err += content;
}
}
break;
}
case M_COMMAND_AWAITING_QUIT:
{
std::cout << "Awaiting quit" << std::endl;
break;
}
case M_COMMAND_EXITED:
{
exited = true;
std::cout << "Command exited normally" << std::endl;
break;
}
case M_COMMAND_EXITED_IN_ERROR:
{
exited = true;
failed = true;
std::cout << "Command exited in error" << std::endl;
break;
}
default:
{
BHandler::MessageReceived(msg);
}
}
}
| true |
5d1403a2e0bc223bc36c8d6cb0686764f3459f6f | C++ | P79N6A/mygoodcoder | /src/util.h | UTF-8 | 1,576 | 3.140625 | 3 | [] | no_license | /*
* @File_name: utin.h
* @Description:
* @Author: liuyuan21@baidu.com
* @Date: 2019-08-28 10:53:16
* @LastEditTime: 2019-08-28 11:30:17
*/
#ifndef GOODCODER_UTIL_H
#define GOODCODER_UTIL_H
#include <string>
#include <vector>
#include <sstream>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
namespace dp{
enum ErrorCode{
OK,
EMPTY_STR,
OVER_MAX_LEN,
TYPEMAP_NOT_FOUND
};
class Util{
public:
template <typename T>
static void split_string(const std::string str, const std::string separator, \
std::vector<T>* ret_vec);
};
/**
* @brief 分割字符串并添加到指定类型的vector中
* @param string 被分割字符串
* @param string 分割符
* @param vector 存放容器
* @return void
*/
template <typename T>
void Util::split_string(const std::string str, const std::string separator, \
std::vector<T>* ret_vec){
if (str.empty() || ret_vec == NULL) {
return;
}
std::vector<std::string> tmp_vec;
boost::split(tmp_vec, str, boost::is_any_of(separator));
for (std::vector<std::string>::iterator it = tmp_vec.begin(); it != tmp_vec.end(); ++it) {
//换成auto?
T tmp_value;
std::stringstream stream;
stream << *it;
stream >> tmp_value;
ret_vec->push_back(tmp_value);
//用cast代替?
}
}
}
#endif
//GOODCODER_UTIL_H
| true |
552f9ecd59731e13f09900b4e98605a286911551 | C++ | rmfmd1345/Philosopher-s-Stone | /Win32APIGameBase/System.cpp | UHC | 2,546 | 2.53125 | 3 | [] | no_license | #include "stdafx.h"
#include "System.h"
void ApiSystem::Initialize() //ʱȭ
{
DrawManager::Initialize();
FrameManager::Initilaize();
SetFramePerSec(60.0f); // 60
ApiSystem::CreateApiWindow(); // (= BaseWindow )
ObjPool->CreateObject(m_hWnd); //ƮǮ Ʈ ʱȭ
m_bIsActive = true;
}
void ApiSystem::Run()
{
MSG msg;
PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
//
while (1)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
if (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else return;
}
else if (m_bIsActive) // ʾ ̸
{
Update();
}
else
{
WaitMessage();
}
}
}
void ApiSystem::Terminate() //
{
DrawManager::Terminate();
FrameManager::Terminate();
ObjPool->DeleteObject();
}
void ApiSystem::Update() //
{
InputManager::InputUpdate(); // ƴ Dz (ex. Ű)
if (FrameManager::Update()) // 60 ʰ false true ȯؼ ŵ
DrawManager::Drawing(m_hWnd);
}
void ApiSystem::CreateApiWindow() // ..
{
HINSTANCE hInst = GetModuleHandle(NULL);
TCHAR szTitle[MAX_LOADSTRING];
TCHAR szWindowClass[MAX_LOADSTRING];
LoadStringW(hInst, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInst, IDC_WIN32APIGAMEBASE, szWindowClass, MAX_LOADSTRING);
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = (WNDPROC)MainWndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInst;
wcex.hIcon = LoadIcon(hInst, (LPCTSTR)IDI_WIN32APIGAMEBASE);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = NULL;
wcex.lpszClassName = szTitle;
wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);
RegisterClassEx(&wcex);
m_hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, SCREEN_WIDTH, SCREEN_HEIGHT, nullptr, nullptr, hInst, nullptr);
RECT rt = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT };
AdjustWindowRect(&rt, WS_BORDER | WS_CAPTION | WS_SYSMENU, false);
SetWindowPos(m_hWnd, nullptr, 0, 0, rt.right - rt.left, rt.bottom - rt.top, SWP_SHOWWINDOW);
if (!m_hWnd)
{
return;
}
ShowWindow(m_hWnd, SW_SHOWDEFAULT);
UpdateWindow(m_hWnd);
return;
}
| true |
7402a8e9ead4aa510352ec15241d6d96cf2fba15 | C++ | kumarNith/ProblemSolving | /c++/Cracking the Coding Interviw/urlify.cpp | UTF-8 | 665 | 3.40625 | 3 | [] | no_license | #include<iostream>
#include<cstring>
using namespace std;
void urlify(char *s1){
int length;
length = strlen(s1);
int spaceCount = 0;
for(int i =0; i < length;i++){
if(s1[i] == ' ')
spaceCount++;
}
int newLen = length + (spaceCount * 2);
cout<<"space count"<<spaceCount<<endl;
s1[newLen--] ='\n';
for(int i = length -1; i >= 0; i--){
if(s1[i] == ' '){
s1[newLen--] = '0';
s1[newLen--] = '2';
s1[newLen--] = '%' ;
}
else
s1[newLen--] = s1[i];
}
}
int main(){
char str[] = "Mr John Smith ";
cout<<"input string : "<<str<<endl;
urlify(str);
cout<<"output string : "<<str<<endl;
return 0;
} | true |
84a1d02a8d0cb8acb88187bba59038af17434c46 | C++ | Bohdashga/OOP_6 | /Date.cpp | UTF-8 | 1,789 | 3.921875 | 4 | [] | no_license | #include "Date.h"
Date::Date()
{
day = 0;
month = 0;
year = 0;
hours = 0;
minutes = 0;
}
Date::Date(int day, int month, int year, int hours, int minutes)
{
this->day = day;
this->month = month;
this->year = year;
this->hours = hours;
this->minutes = minutes;
}
Date::Date(const Date& date)
{
day = date.day;
month = date.month;
year = date.year;
hours = date.hours;
minutes = date.minutes;
}
int Date::getDay()const { return day; }
int Date::getMonth()const { return month; }
int Date::getYear()const { return year; }
int Date::getHours() const { return hours; }
int Date::getMinutes() const { return minutes; }
void Date::setDay(int day) {
if (day > 0 && day < 32)
this->day = day;
}
void Date::setMonth(int month) {
if (month > 0 && month < 13)
this->month = month;
}
void Date::setYear(int year) {
if (year > 0)
this->year = year;
}
void Date::setHours(int hours) {
if (hours >= 0 && hours < 24)
this->hours = hours;
}
void Date::setMinutes(int minutes) {
if (minutes >= 0 && minutes <= 60)
this->minutes = minutes;
}
string Date::toString()const
{
return to_string(day) + "/" + to_string(month) + "/" + to_string(year) +
" " + to_string(hours) + ":" + to_string(minutes);
}
void Date::inputFromKeyboard()
{
cout << "Year > ";
cin >> year;
cout << "Month > ";
cin >> month;
cout << "Day > ";
cin >> day;
cout << "Hours > ";
cin >> hours;
cout << "Minutes > ";
cin >> minutes;
}
string Date::objectToString()const
{
return to_string(day) + ";" + to_string(month) + ";" + to_string(year) +
";" + to_string(hours) + ";" + to_string(minutes);
}
void Date::stringToObject(string str)
{
}
| true |
1ed76f513016d3046bc04a2b0aea04d2edc5cf11 | C++ | WazeAzure/C-Projects | /ALC/cotest/F.cpp | UTF-8 | 286 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
int temp;
for(int i=0;i<n;i++){
cin >> temp;
cout << temp/2 + 1 << endl;
}
return 0;
}
| true |
0310be2d246da3922f43710c36a9680f82af7a15 | C++ | caiush/DataView | /dataview.h | UTF-8 | 8,669 | 2.890625 | 3 | [] | no_license | #ifndef _DATAVIEW_H_
#define _DATAVIEW_H_
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <vector>
using std::vector;
#include "timeStamp.h"
//
// TODO: strip out colMajor stuff again.
//
class DataContainer{
//
// This class just takes care of the polymorphism, at some point
// the memory management will get promoted to here, but not today!
public:
DataContainer(){ return; }
virtual ~DataContainer(){return;}
virtual const std::string& GetName()const=0;
virtual const TimeStamp& GetTimeStamp()const=0;
virtual void SetName(const std::string& name)=0;
virtual void SetTimeStamp(const TimeStamp& ts)=0;
private:
};
template<typename T>
class DataView: public DataContainer
{
protected:
struct header
{
T* data;
void* owner;
long size;
long magic;
unsigned nref;
char memmode;
std::string name;
TimeStamp time;
};
// disable public use of the derfault ctor
//
DataView():
_header(NULL), _data(NULL), _colMajor(false), _offset(0)
{
}
// create a non-owned view on some data
//
DataView(header* hdr,const vector<int>& dims, const vector<int>& strides, bool colMajor=false, int offset=0)
:_header(hdr),
_data(hdr->data),
_colMajor(colMajor),
_offset(offset)
{
_header->nref++;
const unsigned ndims = dims.size();
for (std::size_t k=0; k<dims.size(); k++)
{
_dims.push_back(dims[k]);
_strides.push_back(strides[k]);
}
_nentries = 1;
for (unsigned i=0; i<_dims.size() ; ++i) _nentries *=dims[i] ;
}
// creates an owned dataview from precomputed values, use owr own strides, this should go away soon.
DataView(T* data, const vector<int>& dims, const vector<int>& strides, bool colMajor=false, int offset=0)
: _data (data),
_colMajor(colMajor),
_offset(offset)
{
std::cout << "making " << this << std::endl;
_header = new header;
_header->data = _data;
_header->owner = (void*)this;
_header->magic = 0x8BADF00D;
_header->nref = 1;
_header->memmode = 0; //"0wner" controlled
const unsigned ndims = dims.size();
for (std::size_t k=0; k<dims.size(); k++)
{
_dims.push_back(dims[k]);
_strides.push_back(strides[k]);
}
_nentries = 1;
for (unsigned i=0; i<_dims.size() ; ++i) _nentries *=dims[i] ;
_header->size = _nentries;
std::cout << "made " << this << std::endl;
}
DataView(T* data, const vector<int>& dims, bool colMajor=false, int offset=0)
: _header ( new header),
_data (data),
_colMajor(colMajor),
_offset(offset)
{
std::cout << "making " << this << std::endl;
const unsigned ndims = dims.size();
_header->data = _data;
_header->owner = (void*)this;
_header->magic = 0x8BADF00D;
_header->nref = 1;
_header->memmode = 0; //"0wner" controlled
for (std::size_t k=0; k<dims.size(); k++)
{
_dims.push_back(dims[k]);
int s = 1;
if (colMajor)
for (int j=0; j<k-1; ++j) s*=dims[j];
else
for (int j=k+1; j<ndims; ++j)s*=dims[j];
_strides.push_back(s);
}
_nentries = 1;
for (unsigned i=0; i<_dims.size() ; ++i) _nentries *=dims[i];
_header->size = _nentries;
std::cout << "made " << this << std::endl;
}
//
// Helper fuctions
//
//
unsigned idx2offset(const int x, const int y, const int z)const
{
//FIXME, negative index?
return (_strides[0]*x + _strides[1]*y + _strides[2]*z );
}
unsigned idx2offset(const int x)const
{
//FIXME, negative index?
return (_strides[0]*x);
}
unsigned idx2offset(const int x, const int y)const
{
return (_strides[0]*((x<0)?_dims[0]+x:x) +
_strides[1]*((y<0)?_dims[0]+y:y) );
}
unsigned idx2offset(const int* idx)const
{
unsigned x = 0;
for (std::size_t k=0; k<_dims.size(); k++)
{
const int i = (idx[k]<0)?_dims[k]+idx[k]:idx[k];
x += (_strides[k]*i);
}
return x;
}
public:
const std::string& GetName()const{
return (_header->name);
}
const TimeStamp& GetTimeStamp()const{
return (_header->time);
}
void SetName(const std::string& name){
_header->name = name;
}
void SetTimeStamp(const TimeStamp& ts){
_header->time = time;
}
const T* GetDataPtr()const
{
return _header->data;
}
// ctor and dtor should be protected and friends of the data manager
DataView(const vector<int>& dims, const std::string& name, const TimeStamp& ts, bool colMajor=false)
: _header(new header)
{
_nentries = 1;
_colMajor = colMajor;
const unsigned ndims = dims.size();
for (std::size_t k=0; k<dims.size(); k++)
{
_dims.push_back(dims[k]);
int s = 1;
if (colMajor)
for (int j=0; j<k-1; ++j) s*=dims[j];
else
for (int j=k+1; j<ndims; ++j)s*=dims[j];
_strides.push_back(s);
}
for (unsigned i=0; i<_dims.size() ; ++i) _nentries *=dims[i] ;
_data = (T*)malloc(sizeof(T)*_nentries);
_header->data = _data;
_header->owner = (void*)this;
_header->magic = 0x8BADF00D;
_header->nref = 1;
_header->memmode = 0; //"0wner" controlled
_header->size = _nentries;
_header->name = name;
_header->time = ts;
}
DataView(const vector<int>& dims, const std::string& name, const TimeStamp& ts, T* data)
: _header(new header)
{
_nentries = 1;
const unsigned ndims = dims.size();
for (std::size_t k=0; k<dims.size(); k++)
{
_dims.push_back(dims[k]);
int s = 1;
for (int j=k+1; j<ndims; ++j)s*=dims[j];
_strides.push_back(s);
}
for (unsigned i=0; i<_dims.size() ; ++i) _nentries *=dims[i] ;
_data = data;
_header->data = _data;
_header->owner = (void*)this;
_header->magic = 0x8BADF00D;
_header->nref = 1;
_header->memmode = 0; //"0wner" controlled
_header->size = _nentries;
_header->name = name;
_header->time = ts;
}
~DataView()
{
std::cout << "Deleteing "<< this << std::endl;
if ((this->owner() && this->memMode()==0) ||
(this->memMode()==1 && _header->nref ==1 )){
free((void*)(_header->data));
_header->magic = 0;
_header->data = 0;
delete _header;
}
}
//
// memory mamangement functions
//
bool owner()const
{
return ((void*)this) == _header->owner;
}
bool valid()const{
return ((long)(this->_header->magic) == 0x8BADF00D);
}
char memMode()const{
return _header->memmode;
}
void setMemMode(const char mode){
_header->memmode = mode;
}
const DataView<T>& operator=(const T& rhs)
{
// this needs generatixing to the iterator
T* p = _data + _offset ;
int jump = 0;
for (unsigned i=0; i<_nentries; ++i)
{
jump = 0;
for (int k=_dims.size()-1; k>=0;--k)
{
jump += (i % _dims[k])*_strides[k];
}
*(p+jump) = rhs;
}
return (*this);
}
unsigned rank()const
{
return _dims.size();
}
unsigned size(const unsigned i)const
{
return _dims[i];
}
const T& get(const vector<int>& idx)const
{
return _data[_offset+idx2offset(&(idx[0]))];
}
const T& get( int x, int y)const
{
return _data[_offset+idx2offset(x, y)];
}
const T& get( int x, int y, int z)const
{
return _data[_offset+idx2offset(x, y, z)];
}
const T& get( int x)const
{
return _data[_offset+idx2offset(x)];
}
T& get(const vector<int>& idx)
{
return _data[_offset+idx2offset(&(idx[0]))];
}
T& get( int x, int y)
{
return _data[_offset+idx2offset(x, y)];
}
T& get( int x, int y, int z)
{
return _data[_offset+idx2offset(x, y, z)];
}
T& get( int x)
{
return _data[_offset+idx2offset(x)];
}
protected:
T* _data; // for now this is legacy/premature optimization : we should go to header to check, as that does the BADFOOD check
mutable header* _header; // this needs to be mutable to allow coping a copy
std::vector<int> _dims;
std::vector<int> _strides;
bool _colMajor; //should be moved to the header
int _offset; //
int _nentries; //cache
};
#endif /* _DATAVIEW_H_ */
| true |
1abb33ce669e9645248e1464eaffd6b5995b628d | C++ | Aisore/LABS_MAI_2 | /OOP/1/pentagon.cpp | UTF-8 | 634 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include "pentagon.h"
using namespace std;
Pentagon::Pentagon(double len) : lenght(len) {
cout << "Pentagon created:" << endl;
this->Print();
}
Pentagon::Pentagon(std::istream &is) {
is >> this->lenght;
}
Pentagon::Pentagon(const Pentagon &orig) {
this->lenght = orig.lenght;
cout << "Pentagon copy created" << std::endl;
}
double Pentagon::Square() {
return ((sqrt(5)*(sqrt(5+(2*sqrt(5)))))/4)*pow(this->lenght,2);
}
void Pentagon::Print() {
cout << "Side lengths: " << endl;
cout << "A: " << this->lenght << endl;
}
Pentagon::~Pentagon() {
cout << "Pentagon deleted" << std::endl;
} | true |
e3dd9832bd23bc5eadeb0f1f7f8a7acff9c8fffb | C++ | AlanLee97/Study_C_CPP | /C-C++/xt10.2/xt10.2/xt10.2.cpp | GB18030 | 1,620 | 3.828125 | 4 | [] | no_license | #include<iostream>
using namespace std;
class Complex
{
protected:
double real;
double imag;
public:
Complex();
Complex(double r,double i);
void show();
Complex operator+(Complex&c2);
Complex operator-(Complex&c2);
Complex operator*(Complex&c2);
Complex operator/(Complex&c2);
};
Complex::Complex()
{
real = 0;
imag = 0;
}
Complex::Complex(double r, double i)
{
real = r;
imag = i;
}
void Complex::show()
{
cout << "(" << real << "," << imag << ")" << endl;
}
//+
Complex Complex::operator+(Complex&c2)
{
Complex c;
c.real = real + c2.real;
c.imag = imag + c2.imag;
return c;
}
//-
Complex Complex::operator-(Complex&c2)
{
Complex c;
c.real = real - c2.real;
c.imag = imag - c2.imag;
return c;
}
//*
Complex Complex::operator*(Complex&c2)
{
Complex c;
c.real = real * c2.real - imag * c2.imag;
// a c b d
//ʽ(a+bi)(c+di)=(ac-bd)+(bc+ad)i.
c.imag = imag * c2.real + real * c2.imag;
return c;
}
///
Complex Complex::operator/(Complex&c2)
{
Complex c;
//ʽ(a+bi)/(c+di)=(ac+bd)/(c^2+d^2) +((bc-ad)/(c^2+d^2))i
c.real = (real * c2.real + imag * c2.imag) / (c2.real*c2.real + c2.imag*c2.imag);
c.imag = ((imag*c2.real - real* c2.imag) / (c2.real*c2.real + c2.imag*c2.imag));
return c;
}
int main()
{
Complex c1(2, 3), c2(3, 4), c3,c4,c5,c6;
c3 = c1 + c2;
c4 = c1 - c2;
c5 = c1 * c2;
c6 = c1 / c2;
cout << "c1=";
c1.show();
cout << "c2=";
c2.show();
cout << "c3=";
c3.show();
cout << "c4=";
c4.show();
cout << "c5=";
c5.show();
cout << "c6=";
c6.show();
system("pause");
return 0;
} | true |
2d7b1a8c8967535f40f5cbc5022431ae601138cc | C++ | orange08160394/2021-CG | /6-2-hand.cpp | BIG5 | 1,590 | 2.59375 | 3 | [] | no_license | #include <GL/glut.h>
#include <stdio.h>
float angle=0;
void hand(){
glPushMatrix();
glScaled(0.5,0.1,0.1);
glutSolidCube(1);
glPopMatrix();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glPushMatrix();//
glTranslated(-0.25,0,0);//Twhandm
glRotated(angle,0,0,1);//
glColor3f(0.2,0.3,1.0);
glTranslated(-0.25,0,0);//NbTw
hand();
glPushMatrix();
glTranslated(-0.25,0,0);//Twhandm
glRotated(angle,0,0,1);//
glColor3f(0.2,0.3,1.0);
glTranslated(-0.25,0,0);//NbTw
hand();
glPopMatrix();
glPopMatrix();
glPushMatrix();//k
glTranslated(+0.25,0,0);//Twhandm
glRotated(-angle,0,0,1);//
glColor3f(0.2,0.3,1.0);
glTranslated(+0.25,0,0);//NbTw
hand();
glPushMatrix();
glTranslated(+0.25,0,0);//Twhandm
glRotated(-angle,0,0,1);//
glColor3f(0.2,0.3,1.0);
glTranslated(+0.25,0,0);//NbTw
hand();
glPopMatrix();
glPopMatrix();
glutSwapBuffers();
angle++;
}
int main(int argc, char**argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutCreateWindow("08160394");
glutDisplayFunc(display);
glutIdleFunc(display);//@
glutMainLoop();
}
| true |
888fdfbbb72dda20ead8e76f2ea6f11e07be3bd1 | C++ | MathieuAndrade/Arduino-Programs | /433Mhz/Recepteur_LED/Recepteur_LED.ino | UTF-8 | 1,342 | 2.78125 | 3 | [] | no_license | #include <VirtualWire.h> // Vous devez télécharger et installer la librairie VirtualWire.h dans votre dossier "/libraries" !
int led=13;
void setup()
{
Serial.begin(9600);
vw_setup(2000); // Bits par seconde (vous pouvez le modifier mais cela modifiera la portée). Voir la documentation de la librairie VirtualWire.
vw_set_rx_pin(2); // C'est sur cette broche que l'on reliera les broches DATA du récepteur, vous pouvez changez de broche si vous le désirez.
vw_rx_start(); // On démarre le récepteur.
}
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_wait_rx_max(200)) // Si un message est reçu dans les 200ms qui viennent
{
if (vw_get_message(buf, &buflen)) // On copie le message, qu'il soit corrompu ou non
{
Serial.print("RX : ");
for (byte i = 0; i < buflen; i++) // Si il n'est pas corrompu on l'affiche via Serial
//Serial.print(buf[i]); //Conversion ASCII
{Serial.print(buf[i]- '0'); //Conversion ASCII des chiffres 0-9
}
Serial.println("");
}
if (buf[1] == '1' ){
digitalWrite(led, HIGH);
}
if (buf[1] == '2' ){
digitalWrite(led, LOW);
}
}
}
| true |
b42d1408853d2951bc5fe45aba0c0a3455d3c3c2 | C++ | venkatdeepak12/CodeChefProblems | /November Long Challenge/Hard Sequence.cpp | UTF-8 | 2,173 | 3.640625 | 4 | [] | no_license | /*
Chef decided to write an infinite sequence.
Initially, he wrote 0, and then he started repeating the following process:
Look at the last element written so far (the l-th element if the sequence has length l so far);
let's denote it by x.
If x does not occur anywhere earlier in the sequence, the next element in the sequence is 0.
Otherwise, look at the previous occurrence of x in the sequence,
i.e. the k-th element, where k<l, this element is equal to x and all elements between the k+1-th and l−1-th are different from x.
The next element is l−k, i.e. the distance between the last two occurrences of x.
The resulting sequence is (0,0,1,0,2,0,2,2,1,…): the second element is 0 since 0 occurs only once in the sequence (0),
the third element is 1 since the distance between the two occurrences of 0 in the sequence (0,0) is 1,
the fourth element is 0 since 1 occurs only once in the sequence (0,0,1), and so on.
Chef has given you a task to perform.
Consider the N-th element of the sequence (denoted by x) and the first N elements of the sequence.
Find the number of occurrences of x among these N elements.
Example Input
1
2
Example Output
2
Explanation
Example case 1: The 2-nd element is 0.
It occurs twice among the first two elements,
since the first two elements are both 0.
*/
//Code:
#include <iostream>
using namespace std;
int check(int a[],int n,int k)
{
int i;
for(i=k-1;i>=0;i--)
{
if(a[i]==n)
{
return i;
}
}
return 0;
}
int countnumber(int a[],int n,int k)
{
int c=0,i;
for(i=0;i<=k;i++)
{
if(a[i]==n)
{
c++;
}
}
return c;
}
int main() {
int t,n,i,j,seq[130],count[130];
cin>>t;
seq[0]=-1;
seq[1]=0;
for(i=2;i<130;i++)
{
if(check(seq,seq[i-1],i-1)==0)
{
seq[i]=0;
}
else
{
seq[i]=(i-1)-check(seq,seq[i-1],i-1);
}
}
for(i=0;i<130;i++)
{
count[i]=countnumber(seq,seq[i],i);
}
// for(i=0;i<129;i++) cout<<seq[i]<<" ";
while(t--)
{
cin>>n;
cout<<count[n]<<endl;
}
return 0;
}
| true |
7d490f80edeaf9e50e512ec7d528677ebd4d68c9 | C++ | sjfjoel/CPP | /INHDESDE.CPP | UTF-8 | 741 | 3.765625 | 4 | [] | no_license | // Default destructor in inheritance
/*
when the object is created for derived class
1st derived class destuctor is invoked
after that base class destructor will be invoked
*/
#include<iostream.h>
#include<conio.h>
// classe
class Base // base class
{
public:
// default destructor
~Base()
{
cout<<"\nThen, Base class default destructor will be invoked"<<endl;
}
};
class Derived : public Base // derived class of Base
{
public:
// default constructor
Derived()
{
cout<<"when object creation of derived class,\n\nDerived class default destructor is invoked first."<<endl;
}
};
// main()
int main()
{
clrscr();
// object creation of derived class
Derived d;
return 0;
} | true |
8954601ee8646bb969226ebd988e938f50673e09 | C++ | devilzCough/Algorithm | /DP/C++/acm2225.cpp | UTF-8 | 537 | 2.546875 | 3 | [] | no_license | #include <stdio.h>
int n, k;
int dp[201][201];
void init();
int main()
{
scanf("%d %d", &n, &k);
init();
for (int k_i = 3; k_i <= k; k_i++) {
dp[k_i][0] = 1;
for (int n_i = 1; n_i <= n; n_i++) {
for (int i = 0; i <= n_i; i++) {
dp[k_i][n_i] = (dp[k_i][n_i] + dp[k_i - 1][n_i - i]) % 1000000000;
}
}
}
printf("%d\n", dp[k][n]);
return 0;
}
void init()
{
for (int i = 0; i <= n; i++) {
dp[1][i] = 1;
dp[2][i] = i+1;
}
}
| true |
2a2409af3ccfa18299418baecb5627e70a51a3ad | C++ | Vegctrp/AOJ_courses | /NTL/1e.cpp | UTF-8 | 719 | 2.890625 | 3 | [] | no_license | #include<stdio.h>
#include<vector>
#include<iostream>
#include<map>
#include<tuple>
using namespace std;
typedef long long ll;
#define REP(i,n) for(int i=0;i<(int)(n);i++)
std::vector<ll> extended_gcd(ll a, ll b){ //ax+by=zとなる(x,y,z)
ll s=0;
ll old_s=1;
ll t=1;
ll old_t=0;
ll r=b;
ll old_r=a;
while(r){
long q =old_r / r;
std::swap(s, old_s); s-=q*old_s;
std::swap(t, old_t); t-=q*old_t;
std::swap(r, old_r); r-=q*old_r;
}
std::vector<ll> ans = {old_r, old_s, old_t};
return ans;
}
int main(){
ll a,b;
cin >> a >> b;
auto ans = extended_gcd(a,b);
cout << ans[1] << " " << ans[2] << endl;
} | true |
bcea24fa661910abf1a2c6efc6dfd685cbe16e1c | C++ | alexandraback/datacollection | /solutions_5631572862566400_0/C++/B12040331/k.cpp | UTF-8 | 1,558 | 2.671875 | 3 | [] | no_license |
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int MAXN = 1e3+10;
int ia[MAXN];
int n, ans;
bool used[MAXN];
void dfs(int root, int pre, int cur, int cnt);
int main(){
freopen("C-small-attempt0.in", "r", stdin);
freopen("C-small-attempt0.out", "w", stdout);
int icase;
scanf("%d", &icase);
for(int k=1; k<=icase; ++k){
ans = 1;
scanf("%d",&n);
memset(ia, 0, sizeof(ia));
for(int i=1; i<=n; ++i){
scanf("%d", &ia[i]);
}
for(int i=1; i<=n; ++i){
memset(used, false, sizeof(used));
used[i] = true;
dfs(i, -1, i, 1);
used[i] = false;
}
printf("Case #%d: %d\n", k, ans);
}
return 0;
}
void dfs(int root, int pre, int cur, int cnt){
if(ia[cur] == pre || ia[cur] == root){
if(cnt > ans) {
ans = cnt;
}
}
if(pre == ia[cur]){
for(int i=1; i<=n; ++i){
if(!used[i])
{
used[i] = true;
dfs(root, cur, i, cnt+1);
used[i] = false;
}
}
}
int ib = ia[cur];
if(!used[ib]){
used[ib] = true;
dfs(root, cur, ib, cnt+1);
used[ib] = false;
}
}
/*
1->2->3->4->1
1->3->4->1
2->3->4->1->3
1->3->4->3
2->3->4->3
2->8->6->2
1->7->9->3<->10<-4
*/
| true |
69bdfe62f2b03ed6621592d8bec9dfaa757b8bc9 | C++ | 1ukash/makeblock-sketches | /gripper_robot.xcf/gripper_robot.xcf.ino | UTF-8 | 2,516 | 2.640625 | 3 | [
"MIT"
] | permissive | #include <Makeblock.h>
#include <Arduino.h>
#include <SoftwareSerial.h>
#include <Wire.h>
MeDCMotor MotorL(M1);
MeDCMotor MotorR(M2);
MeDCMotor MotorG(PORT_1);
MeDCMotor MotorM(PORT_2);
MeInfraredReceiver infraredReceiverDecode(PORT_6);
int moveSpeed = 190;
boolean leftflag,rightflag;
int minSpeed = 55;
int factor = 23;
void setup()
{
infraredReceiverDecode.begin();
}
void loop()
{
if(infraredReceiverDecode.available()||infraredReceiverDecode.buttonState())
{
switch(infraredReceiverDecode.read())
{
case IR_BUTTON_PLUS:
Forward();
break;
case IR_BUTTON_MINUS:
Backward();
break;
case IR_BUTTON_NEXT:
TurnRight();
break;
case IR_BUTTON_PREVIOUS:
TurnLeft();
break;
case IR_BUTTON_9:
ChangeSpeed(factor*9+minSpeed);
break;
case IR_BUTTON_8:
ChangeSpeed(factor*8+minSpeed);
break;
case IR_BUTTON_7:
ChangeSpeed(factor*7+minSpeed);
break;
case IR_BUTTON_6:
ChangeSpeed(factor*6+minSpeed);
break;
case IR_BUTTON_5:
ChangeSpeed(factor*5+minSpeed);
break;
case IR_BUTTON_4:
ChangeSpeed(factor*4+minSpeed);
break;
case IR_BUTTON_3:
ChangeSpeed(factor*3+minSpeed);
break;
case IR_BUTTON_2:
ChangeSpeed(factor*2+minSpeed);
break;
case IR_BUTTON_1:
ChangeSpeed(factor*1+minSpeed);
break;
case IR_BUTTON_A:
MotorG.run(moveSpeed);
break;
case IR_BUTTON_C:
MotorG.run(-moveSpeed);
break;
case IR_BUTTON_D:
MotorM.run(moveSpeed);
break;
case IR_BUTTON_E:
MotorM.run(moveSpeed);
break;
}
}
else
{
Stop();
}
}
void Forward()
{
MotorL.run(moveSpeed);
MotorR.run(moveSpeed);
}
void Backward()
{
MotorL.run(-moveSpeed);
MotorR.run(-moveSpeed);
}
void TurnLeft()
{
MotorL.run(-moveSpeed);
MotorR.run(moveSpeed);
}
void TurnRight()
{
MotorL.run(moveSpeed);
MotorR.run(-moveSpeed);
}
void Stop()
{
MotorL.run(0);
MotorR.run(0);
}
void ChangeSpeed(int spd)
{
moveSpeed = spd;
}
| true |
7cfd96b135e38ca7af27631f550c1b361c8e3937 | C++ | sriram20/thingspeak-dotnet-weatherstation | /ArduinoEnvironmental/Arduino Sketch/DigioleLCD.ino | UTF-8 | 2,504 | 2.9375 | 3 | [] | no_license | #include <DigoleSerialDisp.h>
#include <Wire.h>
//DigoleSerialDisp_UART mydisp(&Serial, 9600); //Pin 1(TX)on arduino to RX on module
DigoleSerialDisp_I2C mydisp(&Wire,'\x27'); //SDA (data line) is on analog input pin 4, and SCL (clock line) is on analog input pin 5
//DigoleSerialDisp_SPI mydisp(8,9,10); //Pin 8: data, 9:clock, 10: SS, you can assign 255 to SS, and hard ground SS pin on module
#define LCDCol 2
#define LCDRow 16
void setuplcd()
{
//Due to zero in a string was treated as a end string mark, so if you want send 0 to device, you need send it seperately using print method
//Text Function
mydisp.begin();
}
void lcdtitle(){
// mydisp.print("STCR\x14\x04\x80\xC0\x94\xD4"); //set up Text Cols and Rows and Col addresses of LCD
//delay(5000);
//mydisp.print("CS0"); //disable cursor
mydisp.print("CL"); //CLear screen
//Text Function
//lcdPositionCursor(0,0);
mydisp.print("TP"); //set Text Position to
mydisp.print((uint8_t)0); //x=0;
mydisp.print((uint8_t)0); //y=0;
////////////// //1234567890123456
mydisp.println("TT Temp Press Hum"); //display TexT: "Hello World!"
//mydisp.print("CS0"); //enable cursor
}
void lcdPositionCursor(uint8_t coll, uint8_t row)
{
mydisp.print("TP"); //set Text Position to
mydisp.print((uint8_t)row); //x=0;
mydisp.print((uint8_t)coll); //y=0;
}
void lcdprint(char* p){
mydisp.print("TT"); //y=0;
mydisp.println(p); // Serial.read() reads always 1 character
}
void lcdPrintFloat( float value,uint8_t width,uint8_t precision,uint8_t row,uint8_t coll){
//mydisp.print("CS0"); //disable cursor
//mydisp.print("CL"); //CLear screen
lcdPositionCursor(coll,row);
char ascii[(width+precision)+1];// needs to be this big to hold a type float
//dtostrf(FLOAT,WIDTH,PRECSISION,BUFFER);
dtostrf(value,width,precision,ascii);
mydisp.print("TT");
mydisp.println(ascii);
}
void lcdprint( int value,uint8_t row,uint8_t coll){
//mydisp.print("CS0"); //disable cursor
//mydisp.print("CL"); //CLear screen
lcdPositionCursor(coll,row);
mydisp.print("TT");
char ascii[10];// needs to be this big to hold a type float
itoa((int)value,ascii,10);
mydisp.println(ascii);
}
void lcdprint( long value,int8_t row,uint8_t coll){
//mydisp.print("CS0"); //disable cursor
//mydisp.print("CL"); //CLear screen
lcdPositionCursor(coll,row);
mydisp.print("TT");
char ascii[10];// needs to be this big to hold a type float
itoa((long)value,ascii,10);
mydisp.println(ascii);
}
| true |
5c617a023f25c8be021fecfc774b91e7076ecee2 | C++ | Malory9/data-structure | /CPP/JpBinaryHeap.h | WINDOWS-1252 | 1,834 | 3.546875 | 4 | [] | no_license | //д2016.3.19
#pragma once
#include<vector>
#include <iostream>
#include<initializer_list>
namespace CjpSTL{
template<typename ComparableT>
class JpBinaryHeap
{
private:
enum{DEFAULTCAP = 100};
std::vector<ComparableT>array;
int currentSize;
public:
explicit JpBinaryHeap(int cap = DEFAULTCAP);
JpBinaryHeap(std::initializer_list<ComparableT> lis);
void insert(const ComparableT& val);
bool isEmpty()
{
return array.count() <= 1 ? true : false;
}
void deleteMin();
int findMin()const
{
return array[1];
}
void clear();
};
template <typename ComparableT>
JpBinaryHeap<ComparableT>::JpBinaryHeap(int cap): currentSize(0){
array.resize(cap);
}
template <typename ComparableT>
JpBinaryHeap<ComparableT>::JpBinaryHeap(std::initializer_list<ComparableT> lis): currentSize(0)
{
array.resize(lis.count()*2);
array[0] = -1;
for (const auto& i : lis)
insert(i);
}
template <typename ComparableT>
void JpBinaryHeap<ComparableT>::insert(const ComparableT& val)
{
if (currentSize == array.count() - 1)
array.resize(array.count() * 2);
int hole = ++currentSize;
for (; hole > 1 && val < array[hole / 2]; hole /= 2)
array[hole] = array[hole / 2];
array[hole] = val;
}
template <typename ComparableT>
void JpBinaryHeap<ComparableT>::deleteMin()
{
if (isEmpty())
throw new std::exception("don't contains enough elements");
else
{
auto lastEle = array[currentSize--];
int hole = 1;
int child;
for (; hole*2<=currentSize;hole = child )
{
child = hole * 2;
if (array[child] > array[child + 1])
child += 1;
if(array[child]<lastEle)
array[hole] = array[child];
else break;
}
array[hole ] = lastEle;
}
}
template <typename ComparableT>
void JpBinaryHeap<ComparableT>::clear()
{
array.clear();
}
}
| true |
2e32616a3332f6328d1c0a30f96217109fb952af | C++ | namelessvoid/qrwar | /include/gui/ng/signal.hpp | UTF-8 | 2,465 | 3.734375 | 4 | [
"MIT"
] | permissive | #ifndef NAMELESSGUI_SIGNAL_HPP
#define NAMELESSGUI_SIGNAL_HPP
#include <functional>
#include <vector>
namespace namelessgui
{
/**
* A generic Signal class.
*
* A Signal can be used to register callback methods which are notified
* when the Signal is emitted using emit(). The parameters that are passed
* are specified by the variadic template Params. Registered methods
* have to match this interface.
*
* Example: To declare a Signal that passes an integer and a float to its registered
* callbacks,
*
* @code
* Signal<int, float> mySignal;
* @endcode
*
* can be used.
*
* @tparam Params A set of parameters which are passed to the registered callback
* methods.
*/
template<typename... Params>
class Signal
{
public:
/**
* Convenience typedef for a slot.
*
* A slot basically is a std::function object
* which maches the Signal interface of Params.
*/
typedef std::function<void(Params... parameters)> slot;
/**
* Connect a new function to the Signal.
*
* This adds an new callback function to the Signal. On emit(), this function is
* called together with all the other registered functions. Note, that the interface
* (Signal::slot) of the function has to match the Signal interface Params.
*
* @param function The function to connect to this Signal.
*/
void connect(slot function);
/**
* Disconnect all callbacks.
*
* This method disconnects all callbacks previously added via Signal::connect().
*/
void disconnectAll();
/**
* Emit the signal with a set of parameters.
*
* This emits the Signal with given parameters. For example, to emit
*
* @code
* Signal<int, float> mySignal;
* @endcode
*
* you can use
*
* @code
* mySignal.emit(100, 2.3);
* @endcode
*
* @param parameters The parameters that are passed to the registered callback functions.
*/
void emit(Params... parameters) const;
private:
/**
* Vector that contains all slots registered to this Signal.
*/
std::vector<slot> mSlots;
};
template<typename... Params>
void Signal<Params...>::connect(slot function)
{
mSlots.push_back(function);
}
template<typename... Params>
void Signal<Params...>::disconnectAll()
{
mSlots.clear();
}
template<typename... Params>
void Signal<Params...>::emit(Params... parameters) const
{
for(auto iter = mSlots.begin(); iter != mSlots.end(); ++iter)
(*iter)(parameters...);
}
} // namespace namelessgui
#endif // NAMELESSGUI_SIGNAL_HPP
| true |
f9fd60c59a267b27e72d7cec2cb36a03f00fb3a6 | C++ | Rock-and-Stone/academyStorage | /31.이미지 뿌리기/20210611_0/playGround.cpp | UHC | 3,104 | 2.625 | 3 | [] | no_license | #include "pch.h"
#include "playGround.h"
playGround::playGround()
{
}
playGround::~playGround()
{
}
//ʱȭ ض!!!
HRESULT playGround::init()
{
gameNode::init();
_background = new image;
_background->init(".bmp", WINSIZEX, WINSIZEY, true, RGB(255, 0, 255));
_smile = new image;
_smile->init(".bmp", 50, 45, true, RGB(255, 0, 255));
for (int i = 0; i < SNAKEBODY; ++i)
{
_snake[i].radius = 20;
_snake[i].speed = 5;
//밡?
if (i == 0)
{
_snake[i].angle = RND->getFloat(PI2);//?
_snake[i].x = RND->getFromFloatTo(100, WINSIZEX - 100);
_snake[i].y = RND->getFromFloatTo(100, WINSIZEY - 100);
}
else //̴?
{
_snake[i].angle = _snake[i - 1].angle;
_snake[i].x = _snake[i - 1].x - cosf(_snake[i].angle) * (_snake[i].radius * 2);
_snake[i].y = _snake[i - 1].y - (-sinf(_snake[i].angle) * (_snake[i].radius * 2));
}
}
return S_OK;
}
// ض!!!!
void playGround::release()
{
gameNode::release();
}
//ó ٰ!
void playGround::update()
{
gameNode::update();
if (KEYMANAGER->isStayKeyDown(VK_LEFT)) _snake[0].angle += 0.04f;
if (KEYMANAGER->isStayKeyDown(VK_RIGHT)) _snake[0].angle -= 0.04f;
snakeMove();
}
// !!!
void playGround::render(HDC hdc)
{
HDC backDC = this->getBackBuffer()->getMemDC();
PatBlt(backDC, 0, 0, WINSIZEX, WINSIZEY, WHITENESS);
//============== ǵ帮 ============
_background->render(backDC, 0, 0);
for (int i = 0; i < SNAKEBODY; ++i)
{
_smile->render(backDC, _snake[i].x, _snake[i].y);
//EllipseMakeCenter(backDC, _snake[i].x, _snake[i].y, _snake[i].radius * 2, _snake[i].radius * 2);
}
//=============== ؿ ǵ ================
this->getBackBuffer()->render(hdc, 0, 0);
}
void playGround::snakeMove()
{
for (int i = 0; i < SNAKEBODY; ++i)
{
//ӷ?
if (i == 0)
{
_snake[i].x += cosf(_snake[i].angle) * _snake[i].speed;
_snake[i].y += -sinf(_snake[i].angle) * _snake[i].speed;
if (_snake[i].x - _snake[i].radius < 0)
{
_snake[i].angle = PI - _snake[i].angle;
}
if (_snake[i].x + _snake[i].radius >= WINSIZEX)
{
_snake[i].angle = PI - _snake[i].angle;
}
if (_snake[i].y - _snake[i].radius < 0)
{
_snake[i].angle = PI2 - _snake[i].angle;
}
if (_snake[i].y + _snake[i].radius >= WINSIZEY)
{
_snake[i].angle = PI2 - _snake[i].angle;
}
}
else //̴?
{
//տ ְ ȸ
if (_snake[i].radius * 2 <= getDistance(_snake[i].x, _snake[i].y, _snake[i - 1].x, _snake[i - 1].y))
{
_snake[i].angle = getAngle(_snake[i].x, _snake[i].y, _snake[i - 1].x, _snake[i - 1].y);
// ݽô
_snake[i].x = _snake[i - 1].x - (cosf(_snake[i].angle) * _snake[i].radius * 2);
_snake[i].y = _snake[i - 1].y - (-sinf(_snake[i].angle) * _snake[i].radius * 2);
}
_snake[i].x += cosf(_snake[i].angle) * _snake[i].speed;
_snake[i].y += -sinf(_snake[i].angle) * _snake[i].speed;
}
}
}
| true |
8dba46a2bd30867a96ac73de4066c5951069fce3 | C++ | mamunhpath/leet-code | /find-all-anagrams-in-a-string-1.cpp | UTF-8 | 855 | 3.1875 | 3 | [] | no_license | // https://leetcode.com/problems/find-all-anagrams-in-a-string/description/
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> S(26, 0), P(26, 0), ans;
int m = s.length(), n = p.length();
for(char c : p)
P[c-'a']++;
int j = 0;
for(; j < n; j++)
S[s[j] - 'a']++;
int i = 0;
while(j < m){
if (cmp(S, P))
ans.push_back(i);
S[s[i++] - 'a']--;
S[s[j++] - 'a']++;
}
if (cmp(S, P))
ans.push_back(i);
return ans;
}
bool cmp(vector<int>& v1, vector<int>& v2){
int n = v1.size();
for(int i = 0; i < n; i++)
if (v1[i] != v2[i])
return false;
return true;
}
};
| true |
d08e19026e02131ef4a1b692a29145e740b3a41b | C++ | marcobarlo/greenhouse | /greenhouseArduino/Greenhouse/func.cpp | UTF-8 | 1,919 | 3.0625 | 3 | [] | no_license | #include "func.h"
void array_to_string(byte array[], unsigned int len, char buffer[])
{
for (unsigned int i = 0; i < len; i++)
{
byte nib1 = (array[i] >> 4) & 0x0F;
byte nib2 = (array[i] >> 0) & 0x0F;
buffer[i * 2 + 0] = nib1 < 0xA ? '0' + nib1 : 'A' + nib1 - 0xA;
buffer[i * 2 + 1] = nib2 < 0xA ? '0' + nib2 : 'A' + nib2 - 0xA;
}
buffer[len * 2] = '\0';
}
void str2byte( char array [], byte array2[]){
byte val1=0;
byte val2=0;
char letter1;
char letter2;
for (int i=0;i<6;i++){
letter1=array[2*i];
if(letter1 >= '0' && letter1 <= '9')
val1 = letter1 - '0';
else if(letter1 >= 'A' && letter1 <= 'F')
val1 = letter1 - 'A' + 10;
letter2=array[2*i+1];
if(letter2 >= '0' && letter2 <= '9')
val2 = letter2 - '0';
else if(letter2 >= 'A' && letter2 <= 'F')
val2 = letter2 - 'A' + 10;
array2[i]=val1*16+val2;
}
}
long Convert_byte_to_long(byte array [], unsigned int start) {
templong templ;
for (int i = start; i < start + 4; i++) {
// ID_B[i - 6] = payload[i];
templ.b[3 - i + start] = array[i];
}
return templ.l;
};
float Convert_byte_to_float(byte array[], unsigned int start) {
tempfloat tempf;
for (int i = start; i < start + 4; i++) {
tempf.b[3 - i + start] = array[i];
}
return tempf.f;
};
void Convert_long_to_byte(byte array [], unsigned int start, long l) {
array[start+3] = l & 0xFF;
array[start+2] = (l >> 8) & 0xFF;
array[start+1] = (l >> 16) & 0xFF;
array[start] = (l >> 24) & 0xFF;
};
void Convert_float_to_byte(byte array[],unsigned int start, float f){
tempfloat tempf;
tempf.f=f;
array[start+3] = tempf.b[0];
array[start+2] = tempf.b[1];
array[start+1] = tempf.b[2];
array[start] = tempf.b[3];
};
| true |
0624aa5912285fb904b61a66422de97838fc32a4 | C++ | taekout/fast_raytracer | /fast_raytrace/Sphere.cpp | UTF-8 | 2,213 | 3.03125 | 3 | [] | no_license | // implementation code for Sphere object class
// include this class include file FIRST to ensure that it has
// everything it needs for internal self-consistency
#include "Sphere.hpp"
// other classes used directly in the implementation
#include "Ray.hpp"
#include "aabb.hpp"
// sphere-ray intersection
float
Sphere::intersect(const Ray &r) const
{
// solve p=r.start-center + t*r.direction; p*p -radius^2=0
float a = r.directionLengthSquared();
Vec3 dc = r.start() - d_center;
float b = 2*(r.direction() * dc);
float c = dc*dc - d_radius*d_radius;
float discriminant = b*b - 4*a*c;
if (discriminant < 0) // no intersection
return r.far();
// solve quadratic equation for desired surface
float dsq = sqrt(discriminant);
float t = (-b - dsq) / (2*a); // first intersection in front of start?
if (t > r.near()) return t;
t = (-b + dsq) / (2*a); // second intersection in front of start?
if (t > r.near()) return t;
return r.far(); // sphere entirely behind start point
}
// appearance of sphere at position t on ray r
const Vec3
Sphere::appearance(World &w, const Ray &r, float t) const
{
Vec3 p = r.start() + r.direction() * t; // intersection point
Vec3 n = (p - d_center).normalize();
return d_appearance.eval(w, p, n, r);
}
aabb Sphere::GetAABB()
{
Vec3 size( d_radius, d_radius, d_radius );
return aabb( d_center - size, size * 2 );
}
bool Sphere::IntersectBox(aabb & a_Box)
{
float dmin = 0;
Vec3 v1 = a_Box.GetPos(), v2 = a_Box.GetPos() + a_Box.GetSize();
if (d_center.x() < v1.x())
{
dmin = dmin + (d_center.x() - v1.x()) * (d_center.x() - v1.x());
}
else if (d_center.x() > v2.x())
{
dmin = dmin + (d_center.x() - v2.x()) * (d_center.x() - v2.x());
}
if (d_center.y() < v1.y())
{
dmin = dmin + (d_center.y() - v1.y()) * (d_center.y() - v1.y());
}
else if (d_center.y() > v2.y())
{
dmin = dmin + (d_center.y() - v2.y()) * (d_center.y() - v2.y());
}
if (d_center.z() < v1.z())
{
dmin = dmin + (d_center.z() - v1.z()) * (d_center.z() - v1.z());
}
else if (d_center.z() > v2.z())
{
dmin = dmin + (d_center.z() - v2.z()) * (d_center.z() - v2.z());
}
return (dmin <= d_radius * d_radius);
} | true |
44d703feb0aaf6e9e03bdd4025fa92167455ad73 | C++ | DK-s-C-Project/Chapter-02 | /Chapter 2-8.cpp | WINDOWS-1253 | 978 | 3.765625 | 4 | [] | no_license | /* Literal Constants ͷ */
#include<iostream>
using namespace std;
int main()
{
float pi = 3.14f; // pi is a memory that it is changeable.
//const float pi = 3.14; // with the const the pi is unchangeable.
unsigned int n = 5u;
long n2 = 5L;
double d = 6.0e-10; // review the sign&unsigned.
int x = 012; // it is the octal number.
int y = 0xF; // it is the Hexa number. --> it is very common number in code, cuse of shorting sentance.
//int z = 0d1011'11111'1010; --> in version over 2014 it could be used like this.
// Decimal : 0.1.2.3.4.5.6.7.8.9.10
// Octal : 0.1.2.3.4.5.6.7.8.10.11.12.13.14
// Hexa : 0.1.2.3.4.5.6.7.8.9.A.B.C.D.E.F.10
const int price_per_item = 10; // --> so make a unchangeable value not to make a magic number. 2
int num_items = 123;
int price = num_items * 10; // it is no good in codenig, makeing a magic number. --> a magic number is a Constant that is changeable. 1
return 0;
} | true |
609a63559e9531937d6216096705ad876b716e44 | C++ | jpbida/MiSeq_Scripts | /cpp/docs/iterator.cpp | UTF-8 | 696 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <seqan/sequence.h>
#include <seqan/file.h>
int main()
{
seqan::String<char> str = "admn";
seqan::Iterator<seqan::String<char> >::Type it = begin(str);
seqan::Iterator<seqan::String<char> >::Type itEnd = end(str);
while (it != itEnd) {
::std::cout << *it;
++it;
}
::std::cout << ::std::endl;
seqan::Iterator<seqan::String<char>, seqan::Rooted >::Type it2 = begin(str);
for (goBegin(it2); !atEnd(it2); goNext(it2))
{
++value(it2);
}
goEnd(it2);
while (!atBegin(it2))
{
goPrevious(it2);
::std::cout << getValue(it2);
}
::std::cout << ::std::endl;
assignValue(begin(str), 'X');
::std::cout << str << ::std::endl;
return 0;
}
| true |
60a52f8aa655963cb9defebdb7a469e3a02c7cc7 | C++ | kmhofmann/selene | /selene/img/typed/access/GetPixel.hpp | UTF-8 | 4,070 | 3.078125 | 3 | [
"MIT"
] | permissive | // This file is part of the `Selene` library.
// Copyright 2017-2019 Michael Hofmann (https://github.com/kmhofmann).
// Distributed under MIT license. See accompanying LICENSE file in the top-level directory.
#ifndef SELENE_IMG_ACCESS_GET_PIXEL_HPP
#define SELENE_IMG_ACCESS_GET_PIXEL_HPP
/// @file
#include <selene/img/typed/access/BorderAccessors.hpp>
#include <selene/img/typed/access/Interpolators.hpp>
#include <type_traits>
namespace sln {
// The following function definitions employ some tricks to coerce Visual C++ into choosing the right overloads
// (tested with Visual Studio v15.5.2). The std::integral_constant<> parameters should not be needed.
/** \brief Returns the pixel value of the image at the specified (floating point) location, using the specified
* interpolation method and border access mode.
*
* @tparam InterpolationMode The interpolation mode to use. Defaults to `ImageInterpolationMode::Bilinear`.
* @tparam AccessMode The border access mode to use. Defaults to BorderAccessMode::Unchecked.
* @tparam ImageType The image type, i.e. `Image<...>`.
* @tparam Index The index type. Must be floating point for this overload.
* @param img The image to return the pixel value from.
* @param x The floating point x-coordinate.
* @param y The floating point y-coordinate.
* @return Interpolated pixel value at the specified (x, y) location.
*/
template <ImageInterpolationMode InterpolationMode = ImageInterpolationMode::Bilinear,
BorderAccessMode AccessMode = BorderAccessMode::Unchecked,
typename ImageType,
typename Index,
typename = std::enable_if_t<sln::impl::is_floating_point_v<Index>>>
[[nodiscard]]
inline decltype(auto) get(const ImageType& img,
Index x,
Index y,
std::integral_constant<ImageInterpolationMode, InterpolationMode> = {}) noexcept
{
return ImageInterpolator<InterpolationMode, AccessMode>::interpolate(img, x, y);
}
/** \brief Returns the pixel value of the image at the specified (floating point) location, using bilinear interpolation
* and the specified border access mode.
*
* This is a function overload where the border access mode can be selected, but the interpolation method is the default
* (bilinear interpolation).
*
* @tparam AccessMode The border access mode to use.
* @tparam ImageType The image type, i.e. `Image<...>`.
* @tparam Index The index type. Must be floating point for this overload.
* @param img The image to return the pixel value from.
* @param x The floating point x-coordinate.
* @param y The floating point y-coordinate.
* @return Interpolated pixel value at the specified (x, y) location.
*/
template <BorderAccessMode AccessMode,
typename ImageType,
typename Index,
typename = std::enable_if_t<sln::impl::is_floating_point_v<Index>>>
[[nodiscard]]
inline decltype(auto) get(const ImageType& img,
Index x,
Index y,
std::integral_constant<BorderAccessMode, AccessMode> = {}) noexcept
{
return get<ImageInterpolationMode::Bilinear, AccessMode>(img, x, y);
}
/** \brief Returns the pixel value of the image at the specified (integral) location, using the specified border access
* mode.
*
* @tparam AccessMode The border access mode to use. Defaults to BorderAccessMode::Unchecked.
* @tparam ImageType The image type, i.e. `Image<...>`.
* @tparam Index The index type. Must be floating point for this overload.
* @param img The image to return the pixel value from.
* @param x The floating point x-coordinate.
* @param y The floating point y-coordinate.
* @return Pixel value at the specified (x, y) location.
*/
template <BorderAccessMode AccessMode = BorderAccessMode::Unchecked, typename ImageType>
[[nodiscard]]
inline decltype(auto) get(const ImageType& img, PixelIndex x, PixelIndex y) noexcept
{
return ImageBorderAccessor<AccessMode>::access(img, x, y);
}
} // namespace sln
#endif // SELENE_IMG_ACCESS_GET_PIXEL_HPP
| true |
a03a03c309e4bc1c776bc40b50c2f4198ccaca86 | C++ | Girl-Code-It/Beginner-CPP-Submissions | /Urvashi/milestone-03&04(while loops)/product of digits of a no.cpp | UTF-8 | 275 | 3.453125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int num, mul = 1;
cout << "enter the number";
cin >> num;
while (num != 0)
{
mul *= num % 10;
num = num / 10;
}
cout << "product of digits of the number is :" << mul << endl;
}
| true |
7a829c5d7582a3dac11632a8adc0c665cedc1935 | C++ | nxvu699134/Radix_sort_GPU | /test_sort/sort0.cpp | UTF-8 | 3,330 | 3.015625 | 3 | [] | no_license | #include <stdio.h>
#include <algorithm>
#include <cstring> //memset
#include <ctime>
#define MAX_INT_BITS 32
void printArray(unsigned int* const h_input, const size_t numElems)
{
for (unsigned int i = 0; i < numElems; ++i)
printf("%u ", h_input[i]);
printf("\n");
}
unsigned int getMaxNumOfBits(unsigned int* h_input, const size_t numElems)
{
unsigned int maxElem = *std::max_element(h_input, h_input + numElems);
unsigned int mask = 1 << 31;
unsigned int count = 0;
while (! (mask & maxElem))
{
++count;
mask >>= 1;
}
return MAX_INT_BITS - count;
}
void radix_sort(unsigned int* h_inputVals,
unsigned int* h_inputPos,
unsigned int* h_outputVals,
unsigned int* h_outputPos,
const size_t numElems,
const unsigned int numBits)
{
unsigned int numBins = 1 << numBits;
unsigned int* h_hist = (unsigned int*) malloc (sizeof(unsigned int) * numBins);
unsigned int* h_histScan = (unsigned int*) malloc (sizeof(unsigned int) * numBins);
unsigned int* pInVals = h_inputVals;
unsigned int* pInPos = h_inputPos;
unsigned int* pOutVals = h_outputVals;
unsigned int* pOutPos = h_outputPos;
unsigned int maxBits = getMaxNumOfBits(h_inputVals, numElems);
if (maxBits % numBits)
maxBits += numBits;
// loop through digits
for (unsigned int i = 0; i <= maxBits; i += numBits)
{
unsigned int mask = (numBins - 1) << i;
//init bin histogram
memset(h_hist, 0, sizeof(unsigned int) * numBins);
memset(h_histScan, 0, sizeof(unsigned int) * numBins);
//histogram
for (unsigned int j = 0; j < numElems; ++j)
{
unsigned int bin = (pInVals[j] & mask) >> i;
++h_hist[bin];
}
printArray(h_hist, numBins);
// exclusive scan hist
for (unsigned int j = 1; j < numBins; ++j)
{
h_histScan[j] += h_histScan[j - 1] + h_hist[j - 1];
}
printArray(h_histScan, numBins);
for (int j = 0; j < numElems; ++j)
{
unsigned int bin = (pInVals[j] & mask) >> i;
pOutVals[h_histScan[bin]] = pInVals[j];
pOutPos[h_histScan[bin]] = pInPos[j];
++h_histScan[bin];
}
std::swap(pInVals, pOutVals);
std::swap(pInPos, pOutPos);
}
if (pInVals == h_outputVals)
{
std::copy(h_inputVals, h_inputVals + numElems, h_outputVals);
std::copy(h_inputPos, h_inputPos + numElems, h_outputPos);
}
}
int main()
{
srand(time(NULL));
const size_t numElems = 97;
const unsigned int numBits = 2;
unsigned int* h_inputVals = (unsigned int*) malloc(sizeof(unsigned int) * numElems);
unsigned int* h_inputPos = (unsigned int*) malloc(sizeof(unsigned int) * numElems);
for (int i = 0; i < numElems; ++i)
{
h_inputVals[i] = rand() % 1000000000 + 1;
h_inputPos[i] = i;
}
unsigned int* h_outputVals = (unsigned int*) malloc(sizeof(unsigned int) * numElems);
unsigned int* h_outputPos = (unsigned int*) malloc(sizeof(unsigned int) * numElems);
// printArray(h_inputVals, numElems);
radix_sort(h_inputVals, h_inputPos, h_outputVals, h_outputPos, numElems, numBits);
//printArray(h_outputVals, numElems);
bool check = true;
for (int i = 1; i < numElems; ++i)
{
if (h_outputVals[i] < h_outputVals[i - 1])
{
printf("\nfalse at index : %d\n", i);
check = false;
break;
}
}
if (check)
printf("\nTRUE\n");
else
printf("\nFALSE\n");
// free(h_inputVals);
free(h_inputPos);
free(h_outputVals);
free(h_outputPos);
return 0;
}
| true |
441721adc7f9d7fed83999380a9c28805a3785f7 | C++ | poxiaowu/introduction-to-algorithm | /堆栈和队列实现二叉树的层次和递归排序.cpp | UTF-8 | 2,590 | 3.546875 | 4 | [] | no_license | #include<iostream>
#include <limits>
#include <ctime>
using namespace std;
typedef struct node{//二叉树节点
int value;
node *left;
node *right;
}node,*pnode;
typedef struct list{//队列的基本结构
pnode pn;
list *next;
}list,*plist;
typedef struct queue{//层次遍历时存储节点
list *head;
list *tail;
}queue,*pqueue;
typedef struct stack{//栈-模拟递归遍历
list *top;
}stack,*pstack;
void build_binary_tree(pnode &pn,int depth,int maxDep)//创建一个二叉树
{
if(depth<maxDep){
//创建根节点
pn=new node;
pn->value=rand()%101-50;
pn->left=NULL;
pn->right=NULL;
cout<<pn->value<<"\t";
build_binary_tree(pn->left,depth+1,maxDep);
build_binary_tree(pn->right,depth+1,maxDep);
}
}
void travel_recursive_binary_tree(pnode pn)//递归遍历二叉树
{
if(pn!=NULL){
cout<<pn->value<<"\t";
travel_recursive_binary_tree(pn->left);
travel_recursive_binary_tree(pn->right);
}
}
void travel_stack_binary_tree(pnode pn)//利用堆栈模拟递归遍历
{
if(pn!=NULL){
pstack ps=new stack;//栈
plist pl;//链表
ps->top=NULL;
while(pn||ps->top){
if(pn){
cout<<pn->value<<"\t";//输出元素值
pl=new list;
pl->pn=pn;//根节点入栈
pl->next=ps->top;
ps->top=pl;
pn=pn->left;//左节点
}
else{
pl=ps->top;
ps->top=ps->top->next;//弹出栈中左结点元素
pn=pl->pn->right;
delete pl;//删除左结点
}
}
}
cout<<endl;
}
void travel_level_binary_tree(pnode pn)//二叉树层次遍历
{
if(pn!=NULL){//队列初始信息设置
pqueue pq=new queue;//队列
plist pl=new list;//链表
pl->pn=pn;
pq->head=pl;
pq->tail=NULL;//链表尾部
pq->head->next=pq->tail;
plist pltmp=pl;//用在存放最有一个有用的地址指针
while(pq->head!=pq->tail){
cout<<pq->head->pn->value<<"\t";
if(pq->head->pn->left){
pl=new list;
pl->pn=pq->head->pn->left;
pltmp->next=pl;
pltmp=pl;
pltmp->next=pq->tail;
}
if(pq->head->pn->right){
pl=new list;
pl->pn=pq->head->pn->right;
pltmp->next=pl;
pltmp=pl;
pltmp->next=pq->tail;
}
pl=pq->head;
pq->head=pq->head->next;
delete pl;
}
cout<<endl;
}
}
int main()
{
srand((unsigned int)time(NULL));
int maxDep;
while(maxDep=rand()%10,maxDep<3);
pnode pn;
maxDep=2;
build_binary_tree(pn,0,maxDep);//构建二叉树
cout<<endl;
travel_level_binary_tree(pn);//层次遍历-队列实现
travel_recursive_binary_tree(pn);//前序遍历
cout<<endl;
travel_stack_binary_tree(pn);//递归遍历-堆栈实现
}
| true |
9db65098fe0188e899a574e540ca5f70929e650f | C++ | KDE/kdiamond | /src/board.h | UTF-8 | 2,032 | 2.515625 | 3 | [
"BSD-3-Clause",
"CC0-1.0"
] | permissive | /*
SPDX-FileCopyrightText: 2008-2010 Stefan Majewsky <majewsky@gmx.net>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#ifndef KDIAMOND_BOARD_H
#define KDIAMOND_BOARD_H
class Diamond;
class QAbstractAnimation;
#include <QGraphicsItem>
class KGameRenderer;
namespace KDiamond
{
class Board : public QGraphicsObject
{
Q_OBJECT
public:
explicit Board(KGameRenderer *renderer);
int gridSize() const;
Diamond *diamond(const QPoint &point) const;
bool hasDiamond(const QPoint &point) const;
bool hasRunningAnimations() const;
QList<QPoint> selections() const;
bool hasSelection(const QPoint &point) const;
void setSelection(const QPoint &point, bool selected);
void clearSelection();
void removeDiamond(const QPoint &point);
void swapDiamonds(const QPoint &point1, const QPoint &point2);
void fillGaps();
KGameRenderer *renderer() const;
QRectF boundingRect() const override;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override;
public Q_SLOTS:
void setPaused(bool paused);
Q_SIGNALS:
void animationsFinished();
void clicked(const QPoint &point);
void dragged(const QPoint &point, const QPoint &direction);
private Q_SLOTS:
void slotAnimationFinished();
void slotClicked();
void slotDragged(const QPoint &direction);
private:
struct MoveAnimSpec {
Diamond *diamond;
QPointF from, to;
};
QPoint findDiamond(Diamond *diamond) const;
Diamond *&rDiamond(const QPoint &point);
Diamond *spawnDiamond(int color);
void spawnMoveAnimations(const QList<MoveAnimSpec> &specs);
static const int MoveDuration;
static const int RemoveDuration;
int m_difficultyIndex, m_size, m_colorCount;
QList<QPoint> m_selections;
bool m_paused;
KGameRenderer *m_renderer;
QVector<Diamond *> m_diamonds;
QList<Diamond *> m_activeSelectors, m_inactiveSelectors;
QList<QAbstractAnimation *> m_runningAnimations;
};
}
#endif // KDIAMOND_BOARD_H
| true |
8aa48ebb3abc403c5ab96bb38527db5af4e2d178 | C++ | q349wang/SE-101-Project | /Testing/ArduinoRecieverTest/ArduinoRecieverTest.ino | UTF-8 | 912 | 2.96875 | 3 | [] | no_license | #define rfReceivePin A0 //RF Receiver pin = Analog pin 0
#define ledPin 13 //Onboard LED = digital pin 13
unsigned int data = 0; // variable used to store received data
const unsigned int upperThreshold = 70; //upper threshold value
const unsigned int lowerThreshold = 50; //lower threshold value
void setup(){
pinMode(rfReceivePin, INPUT);
Serial.begin(9600);
}
void loop(){
data = analogRead(rfReceivePin); //listen for data on Analog pin 0
int count = 1;
/* for(int i = 0; i < 500; i++) {
count++;
data +=digitalRead(rfReceivePin);
}*/
//data= round(data/count);
if(data>upperThreshold){
//analogRead(rfReceivePin); //If a LOW signal is received, turn LED OFF
Serial.println("OFF");
}else if(data<lowerThreshold){
//analogRead(rfReceivePin); //If a HIGH signal is received, turn LED ON
Serial.println("ON");
}
}
| true |
fb7edafff596867ca0c131a32855857e82a6e513 | C++ | anant-pushkar/competetive_programming_codes | /cpp/Delete_N_nodes_after_M_nodes_of_a_linked_list/main.cpp | UTF-8 | 1,849 | 3.078125 | 3 | [] | no_license | /*
Project name : Delete_N_nodes_after_M_nodes_of_a_linked_list
Created on : Thu Oct 2 21:37:30 2014
Author : Anant Pushkar
http://www.geeksforgeeks.org/delete-n-nodes-after-m-nodes-of-a-linked-list/
*/
#include<iostream>
#include<cstring>
#include<cstdio>
#include<deque>
#include<queue>
#include<utility>
#include<vector>
#include<climits>
#include<algorithm>
#include<stack>
using namespace std;
bool debug=false;
typedef long long int lld;
typedef unsigned long long int llu;
struct ListNode{
int val;
ListNode *next;
ListNode *child;
ListNode():next(NULL),child(NULL),val(INT_MIN){}
ListNode(int x):next(NULL),child(NULL),val(x){}
};
class Solver{
int n;
ListNode *head;
public:
Solver(int x):
n(x),
head(new ListNode(INT_MIN)){
ListNode *ptr = head;
int val;
for(int i=0;i<n;++i){
cin>>val;
ptr->next = new ListNode(val);
ptr = ptr->next;
}
ptr = head->next;
free(head);
head = ptr;
}
ListNode *solve(){
int m,n,x,y;
cin>>m>>n;
--m;
ListNode *node = head , *ptr;
while(node!=NULL){
x=m;
y=n;
while(node!=NULL && x>0){
if(debug)cout<<"accepting "<<node->val<<endl;
node = node->next;
--x;
}
if(debug)cout<<"NODE : "<<(node!=NULL?node->val:-1)<<endl;
if(node==NULL){
break;
}
while(node->next!=NULL && y>0){
if(debug)cout<<"rejecting "<<node->next->val<<endl;
ptr = node->next->next;
free(node->next);
node->next = ptr;
--y;
}
node = node->next;
if(debug)cout<<"NODE : "<<(node!=NULL?node->val:-1)<<endl;
}
return head;
}
};
int main(int argc , char **argv)
{
if(argc>1 && strcmp(argv[1],"DEBUG")==0) debug=true;
int t;
cin>>t;
int n;
ListNode *node;
while(t--){
cin>>n;
Solver s(n);
node = s.solve();
while(node!=NULL){
cout<<node->val<<" ";
node=node->next;
}
cout<<endl;
}
return 0;
}
| true |
183aeb0852ed548253ca3ad4f746dd5bfee21f2c | C++ | XiaoyangXu1988/CFI-Benchmark-Suite | /veh.cpp | UTF-8 | 1,297 | 2.84375 | 3 | [] | no_license | #include "helper.h"
NANOSECOND start_time;
NANOSECOND end_time;
NANOSECOND total_time;
LONG WINAPI VectoredHandlerSkip(struct _EXCEPTION_POINTERS *ExceptionInfo);
int main()
{
DWORD loop_count = 10000L;
PVOID pv = NULL;
// record starting time
start_time = get_wall_time();
// Register a vectored exception handler
pv = AddVectoredExceptionHandler(0, VectoredHandlerSkip);
// Triger a hardware exception by writing to DS:[0]
__asm {
mov eax, 0
mov ecx, loop_count
L : mov [eax], 0
loop L
}
// Remove the vectored exception handler
RemoveVectoredExceptionHandler(pv);
// record ending time
end_time = get_wall_time();
total_time = end_time - start_time;
// print results
printf("total time in nanoseconds is %llu\n", (long long unsigned int) total_time);
return 0;
}
LONG WINAPI
VectoredHandlerSkip(struct _EXCEPTION_POINTERS *ExceptionInfo)
{
PCONTEXT Context;
Context = ExceptionInfo->ContextRecord;
// The instruction "mov [eax], 0" has length of 3, eip += 3 will redirect
// the control flow to the next "loop L" instruction.
Context->Eip = Context->Eip + 3;
return EXCEPTION_CONTINUE_EXECUTION;
} | true |
335dd7e9efb506ad7129ea009891b61297d1a69c | C++ | Manuelacosta98/competitive-programing | /spoj/CDC12_B.cpp | UTF-8 | 1,126 | 2.84375 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
class Rutina
{
public:
string nombre;
int energia;
Rutina(){};
Rutina(string cadena, int valor)
{
nombre= cadena;
energia= valor;
}
bool operator< (const Rutina &otro)const
{
if (energia==otro.energia)
{
return nombre< otro.nombre;
}else
{
return energia<otro.energia;
}
}
};
vector<Rutina> rutinas;
int main()
{
int t, n,k;
string nombre;
int valor;
vector<string> ans;
scanf("%d",&t);
for (int tt = 1; tt <= t; ++tt)
{
ans.clear();
rutinas.clear();
scanf("%d %d",&n,&k);
for (int i = 0; i < n; ++i)
{
cin>>nombre>>valor;
rutinas.push_back( Rutina(nombre,valor) );
}
sort(rutinas.begin(),rutinas.end());
int aux=0;
for (int i = 0; i < n; ++i)
{
k-= rutinas[i].energia;
if (k<0)
{
break;
}
aux++;
ans.push_back(rutinas[i].nombre);
k+=aux;
}
sort(ans.begin(),ans.end());
printf("Scenario #%d: %d\n",tt,(int)ans.size());
for (int i = 0; i < ans.size()-1; ++i)
{
printf("%s ",ans[i].c_str());
}
printf("%s\n",ans.back().c_str());
}
return 0;
}
| true |
ce3a7a060007777bd37dfc6d50b5e130c7480b4b | C++ | yangyiko/esp32_4 | /src/example/网络服务器/webserver.cpp | UTF-8 | 5,601 | 2.8125 | 3 | [] | no_license | // #include <Arduino.h>
// /**********************************************************************
// * 按flash键读取 D3
// * http://www.taichi-maker.com/homepage/-nodemcu-iot/iot-c/-nodemcu-web-server/pin-state/
// 项目名称/Project : 零基础入门学用物联网
// 程序名称/Program name : 3_2_3_Pin_State_Display
// 团队/Team : 太极创客团队 / Taichi-Maker (www.taichi-maker.com)
// 作者/Author : CYNO朔
// 日期/Date(YYYYMMDD) : 20191107
// 程序目的/Purpose : 使用NodeMCU建立基本服务器。该页面将会自动刷新并且显示NodeMCU
// 的D3引脚状态。NodeMCU开发板上的FLASH按键可以控制D3引脚的电平。
// 没有按下该按键时D3引脚将会保持高电平状态。当按下该按键后,
// D3引脚会变为低电平。
// -----------------------------------------------------------------------
// 修订历史/Revision History
// 日期/Date 作者/Author 参考号/Ref 修订说明/Revision Description
// ***********************************************************************/
// #include <WiFi.h> // 本程序使用 WiFi库
// #include <WiFiMulti.h> // WiFiMulti库
// #include <WebServer.h> // WebServer库
// #define buttonPin 0 // flash按钮
// WiFiMulti wifiMulti; // 建立WiFiMulti对象,对象名称是'wifiMulti'
// WebServer _server(80);// 建立网络服务器对象,该对象用于响应HTTP请求。监听端口(80)
// bool pinState; // 存储引脚状态用变量
// /*
// 建立用于发送给客户端浏览器的HTML代码。此代码将会每隔5秒刷新页面。
// 通过页面刷新,引脚的最新状态也会显示于页面中
// */
// String sendHTML(bool buttonState){
// String htmlCode = "<!DOCTYPE html> <html>\n";
// htmlCode +="<head><meta http-equiv='refresh' content='5'/>\n";
// htmlCode +="<title>ESP8266 Butoon State</title>\n";
// htmlCode +="<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}\n";
// htmlCode +="body{margin-top: 50px;} h1 {color: #444444;margin: 50px auto 30px;} h3 {color: #444444;margin-bottom: 50px;}\n";
// htmlCode +="</style>\n";
// htmlCode +="</head>\n";
// htmlCode +="<body>\n";
// htmlCode +="<h1>ESP8266 BUTTON STATE</h1>\n";
// if(buttonState)
// {htmlCode +="<p>Button Status: HIGH</p>\n";}
// else
// {htmlCode +="<p>Button Status: LOW</p>\n";}
// htmlCode +="</body>\n";
// htmlCode +="</html>\n";
// return htmlCode;
// }
// /* 以下函数处理网站首页的访问请求。此函数为本示例程序重点1
// 详细讲解请参见太极创客网站《零基础入门学用物联网》
// 第3章-第2节“通过网络服务将开发板引脚状态显示在网页中”的说明讲解。*/
// void handleRoot() { //处理网站目录“/”的访问请求
// _server.send(200, "text/html", sendHTML(pinState));
// }
// // 设置处理404情况的函数'handleNotFound'
// void handleNotFound(){ // 当浏览器请求的网络资源无法在服务器找到时,
// _server.send(404, "text/plain", "404: Not found"); // NodeMCU将调用此函数。
// }
// void setup(){
// Serial.begin(9600); // 启动串口通讯
// pinMode(buttonPin, INPUT_PULLUP); // 将按键引脚设置为输入上拉模式
// // //通过addAp函数存储 WiFi名称 WiFi密码
// wifiMulti.addAP("TP-LINK_yangyi", "acwkxq9k"); // 这三条语句通过调用函数addAP来记录3个不同的WiFi网络信息。
// wifiMulti.addAP("TP-LINK_yangyi_5G", "acwkxq9k"); // 这3个WiFi网络名称分别是taichi-maker, taichi-maker2, taichi-maker3。
// Serial.println("Connecting ..."); // 则尝试使用此处存储的密码进行连接。
// int i = 0;
// while (wifiMulti.run() != WL_CONNECTED) { // 此处的wifiMulti.run()是重点。通过wifiMulti.run(),NodeMCU将会在当前
// delay(1000); // 环境中搜索addAP函数所存储的WiFi。如果搜到多个存储的WiFi那么NodeMCU
// Serial.print(i++); Serial.print(' '); // 将会连接信号最强的那一个WiFi信号。
// } // 一旦连接WiFI成功,wifiMulti.run()将会返回“WL_CONNECTED”。这也是
// // 此处while循环判断是否跳出循环的条件。
// // WiFi连接成功后将通过串口监视器输出连接成功信息
// Serial.println('\n'); // WiFi连接成功后
// Serial.print("Connected to "); // NodeMCU将通过串口监视器输出。
// Serial.println(WiFi.SSID()); // 连接的WiFI名称
// Serial.print("IP address:\t"); // 以及
// Serial.println(WiFi.localIP()); // NodeMCU的IP地址
// _server.begin(); // 启动网站服务
// _server.on("/", handleRoot); // 设置服务器根目录即'/'的函数'handleRoot'
// _server.onNotFound(handleNotFound);// 设置处理404情况的函数'handleNotFound'
// Serial.println("HTTP _server started");// 告知用户网络服务功能已经启动
// }
// void loop(){
// _server.handleClient(); // 处理http服务器访问
// pinState = digitalRead(buttonPin); // 获取引脚状态
// }
| true |
258e4f4ecc5dffa19a27b3a0142a001e0143a789 | C++ | FRC900/2020RobotCode | /zebROS_ws/src/talon_interface/include/talon_interface/sensor_initialization_strategy.h | UTF-8 | 330 | 2.515625 | 3 | [
"BSD-3-Clause"
] | permissive | #pragma once
namespace hardware_interface
{
enum SensorInitializationStrategy
{
/**
* On boot up, set position to zero.
*/
BootToZero,
/**
* On boot up, sync to the Absolute Position signal. The Absolute position signal will be signed according to the selected Absolute Sensor Range.
*/
BootToAbsolutePosition,
};
}
| true |
b4279424140a929ea2ef526a750972b36b099efe | C++ | ds759/Data-Structures | /SingularLinkedList.cpp | UTF-8 | 1,882 | 4.40625 | 4 | [] | no_license | #include <iostream>
class LinkedList
{
public:
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = nullptr;
}
};
Node *head;
Node *tail;
int length;
LinkedList()
{
this->head = nullptr;
this->tail = nullptr;
this->length = 0;
}
void add(int data);
void add(int data, int position);
void delete_node(int position);
int get_length();
void print();
int get_first();
};
void LinkedList::add(int data)
{
Node *node = new Node(data);
if (this->head == nullptr)
{
this->head = node;
}
else
{
this->tail->next = node;
}
this->tail = node;
this->length = this->length + 1;
}
void LinkedList::add(int data, int position)
{
Node *temp_head = this->head;
Node *node = new Node(data);
int i = 0;
while (i < this->length)
{
if (i == position - 1)
{
node->next = this->head->next;
this->head->next = node;
}
this->head = this->head->next;
i++;
}
this->head = temp_head;
this->length = this->length + 1;
}
void LinkedList::print()
{
Node *temp_head = this->head;
while (this->head != nullptr)
{
std::cout << this->head->data << '\n';
this->head = this->head->next;
}
this->head = temp_head;
}
int LinkedList::get_length()
{
return this->length;
}
int LinkedList::get_first()
{
return this->head->data;
}
int main()
{
LinkedList *llist = new LinkedList();
llist->add(0);
llist->add(1);
llist->add(3);
llist->add(4);
llist->add(2, 2);
llist->print();
std::cout << "Length: " << llist->get_length() << '\n';
std::cout << "First Element : " << llist->get_first() << '\n';
} | true |
58a3fee29d1b9c7d4c7a0d2b5b5b0fb08d16c925 | C++ | LeyuGao/ncat-comp280-repository | /COMP280_Assignment5/COMP280_Assignment5/COMP280_Assignment5/main.cpp | UTF-8 | 3,109 | 3.6875 | 4 | [
"LicenseRef-scancode-public-domain",
"Unlicense"
] | permissive | //
// main.cpp
// COMP280_Assignment5
//
// Created by Christopher Cannon on 6/26/16.
//
#include <iostream>
#include "Graph.h"
int main() {
int n = 0;
std::cout<<"Undirected Graph Program"<<std::endl;
std::cout<<std::endl;
std::cout<<"Enter the number of verticies for your graph:"<<std::endl;
std::cin>>n;
std::cout<<std::endl;
std::cout<<std::endl;
Graph myGraph(n);
int exitCode = 0;
int selection = 0;
while(exitCode != 1){
selection = 0;
std::cout<<"Undirected Graph Program"<<std::endl;
std::cout<<std::endl;
std::cout<<"Select an item from the menu below:"<<std::endl;
std::cout<<"1. Insert an edge."<<std::endl;
std::cout<<"2. Delete an edge."<<std::endl;
std::cout<<"3. Print adjacency matrix."<<std::endl;
std::cout<<"4. List all verticies that are adjacent to a specific vertex."<<std::endl;
std::cout<<"5. Print out verticies using depth first search."<<std::endl;
std::cout<<"6. Print out verticies using depth first search."<<std::endl;
std::cout<<"7. Check for connectivity."<<std::endl;
std::cout<<"8. Check for completeness."<<std::endl;
std::cout<<"9. Exit program."<<std::endl;
std::cin>>selection;
int v, w;
switch (selection) {
case 1:
std::cout<<std::endl;
std::cout<<"Enter the verticies you would like to connect:"<<std::endl;
std::cin>>v>>w;
myGraph.AddEdge(v, w);
break;
case 2:
std::cout<<std::endl;
std::cout<<"Enter the verticies you would like to disconnect:"<<std::endl;
std::cin>>v>>w;
myGraph.DeleteEdge(v, w);
break;
case 3:
std::cout<<std::endl;
myGraph.PrintMatrix();
break;
case 4:
std::cout<<std::endl;
std::cout<<"Enter the vertex you would like to examine:"<<std::endl;
std::cin>>v;
myGraph.PrintAdjacent(v);
break;
case 5:
std::cout<<std::endl;
std::cout<<"Sorry, this feature isn't implemented";
//TODO option 5
break;
case 6:
std::cout<<std::endl;
std::cout<<"Sorry, this feature isn't implemented";
//TODO option 6
break;
case 7:
std::cout<<std::endl;
std::cout<<"Sorry, this feature isn't implemented";
//TODO option 7
break;
case 8:
std::cout<<std::endl;
std::cout<<"Sorry, this feature isn't implemented";
//TODO option 8
break;
case 9:
exitCode = 1;
break;
default:
break;
}
std::cout<<std::endl;
std::cout<<std::endl;
}
}
| true |
67c9a546b527c0354d788e903aeaea3416b8799c | C++ | lisendong/ACM | /usaco/1/transform.cpp | UTF-8 | 2,782 | 3.09375 | 3 | [] | no_license | /*
ID:lisendo1
PROG:transform
LANG:C++
*/
#include <iostream>
#include <fstream>
using namespace std;
char a[20][20], b[20][20], temp[20][20];
int N;
int equals(char a[20][20], char b[20][20]) {
int flag = 1;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (a[i][j] != b[i][j]) {
flag = 0;
break;
}
}
}
return flag;
}
int init() {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
temp[i][j] = a[i][j];
}
}
}
void num1() {
int temp1[20][20];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
temp1[j][N - 1 - i] = temp[i][j];
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
temp[i][j] = temp1[i][j];
}
}
}
void num2() {
int temp1[20][20];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
temp1[N - 1 - i][N - 1 - j] = temp[i][j];
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
temp[i][j] = temp1[i][j];
}
}
}
void num3() {
int temp1[20][20];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
temp1[N - 1 - j][i] = temp[i][j];
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
temp[i][j] = temp1[i][j];
}
}
}
void num4() {
int temp1[20][20];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
temp1[i][N - 1 - j] = temp[i][j];
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
temp[i][j] = temp1[i][j];
}
}
}
int main() {
ifstream in("transform.in");
ofstream out("transform.out");
in >> N;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
in >> a[i][j];
}
}
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
in >> b[i][j];
}
}
init();
num1();
if (equals(b, temp)) {out << 1 << endl; return 0;}
init();
num2();
if (equals(b, temp)) {out << 2 << endl; return 0;}
init();
num3();
if (equals(b, temp)) {out << 3 << endl; return 0;}
init();
num4();
if (equals(b, temp)) {out << 4 << endl; return 0;}
init();
num4();num1();
if (equals(b, temp)) {out << 5 << endl; return 0;}
init();
num4();num2();
if (equals(b, temp)) {out << 5 << endl; return 0;}
init();
num4();num3();
if (equals(b, temp)) {out << 5 << endl; return 0;}
init();
if (equals(b, temp)) {out << 6 << endl; return 0;}
out << 7 << endl;
return 0;
}
| true |
bdbd07eb3ae1899d03cd406c6b0c08104bc0942c | C++ | skyformat99/fidelity | /fidelity/base/Thread.cpp | UTF-8 | 6,365 | 2.640625 | 3 | [] | no_license | #include "Thread.hpp"
#include <sched.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <contract/contract_assert.hpp>
#include <algorithm>
#include <climits>
#include <cstdlib>
#include <memory>
#include <mutex>
#include <thread>
#include "PrioMutex.hpp"
#include "SystemAdapter.hpp"
using namespace std::chrono_literals;
constexpr int SCHED_RT = SCHED_FIFO;
constexpr int SCHED_NON_RT = SCHED_OTHER;
// monitor realtime behavior
// assert if new is called in rt thread
void* operator new(size_t size) { // NOLINT
pthread_attr_t attr{};
ENSURE(pthread_attr_init(&attr) == 0);
ENSURE(pthread_getattr_np(pthread_self(), &attr) == 0);
int policy{0};
ENSURE(pthread_attr_getschedpolicy(&attr, &policy) == 0);
ENSURE(pthread_attr_destroy(&attr) == 0);
ENSURE(policy == SCHED_NON_RT, "Memory allocation not allowed in realtime thread.");
return std::malloc(size); // NOLINT
}
namespace fdl {
std::shared_ptr<SystemAdapter> Thread::m_system_di{nullptr};
Thread::Thread(const std::string& name, Thread::Type type, int prio, int affinity,
std::function<void()> update)
: m_name(name), m_type(type), m_prio(prio), m_affinity(affinity), m_update(std::move(update)) {
EXPECT(!name.empty(), "Thread needs to be named.");
if (Thread::m_system_di != nullptr) {
m_system = Thread::m_system_di;
} else {
m_system = std::make_shared<SystemAdapter>();
ENSURE(m_system != nullptr);
}
if (m_type == Thread::Type::RT) {
EXPECT(prio > 0 && prio < 99, "realtime threads priority needs a be between 0 and 99.");
}
ENSURE(m_affinity < static_cast<int>(m_system->thread->hardware_concurrency()),
"Affinity does not match available CPUs.");
ENSURE(m_system->pthread->pthread_attr_init(&m_pthread_attr) == 0,
"Could not initialize thread attributes.");
rlimit limit{};
ENSURE(m_system->resource->getrlimit(RLIMIT_STACK, &limit) == 0);
ENSURE(limit.rlim_cur > PTHREAD_STACK_MIN);
m_max_stack_size = limit.rlim_cur - PTHREAD_STACK_MIN;
setStackSize(Thread::DEFAULT_STACK_SIZE);
}
void Thread::setPeriod(std::chrono::microseconds period) {
EXPECT(period > 0ms);
// only set if thread is not created
if (!m_created) {
m_period = period;
}
}
void Thread::setStackSize(size_t size) {
// only set if thread is not created
if (!m_created) {
ENSURE(size <= m_max_stack_size, "Could not set stack size.");
ENSURE(m_system->pthread->pthread_attr_setstacksize(&m_pthread_attr,
size + PTHREAD_STACK_MIN) == 0,
"Could not set stack size.");
}
}
void Thread::setSched() {
if (m_type == Type::RT) {
struct sched_param param {};
param.sched_priority = m_prio;
ENSURE(m_system->pthread->pthread_attr_setschedpolicy(&m_pthread_attr, SCHED_RT) == 0,
"Could not set rt scheduler.");
ENSURE(m_system->pthread->pthread_attr_setschedparam(&m_pthread_attr, ¶m) == 0,
"Could not set thread priority.");
} else {
ENSURE(m_system->pthread->pthread_attr_setschedpolicy(&m_pthread_attr, SCHED_NON_RT) == 0,
"Could not set non rt scheduler");
}
}
void Thread::setAffinity() {
// negative value means no affinity wanted
if (m_affinity >= 0) {
cpu_set_t set{};
CPU_ZERO(&set);
CPU_SET(m_affinity, &set); // NOLINT
ENSURE(m_system->pthread->pthread_attr_setaffinity_np(&m_pthread_attr, sizeof(set), &set) == 0,
"Could not set CPU affinity.");
}
}
void Thread::create() {
if (m_created) {
return;
}
ENSURE(m_thread == 0, "Pthread already created.");
setSched();
setAffinity();
// commit pthread attributes
ENSURE(m_system->pthread->pthread_attr_setinheritsched(&m_pthread_attr, PTHREAD_EXPLICIT_SCHED) ==
0,
"Could not set pthread attributes.");
// lock all already mapped pages
// don't use MCL_FUTURE cause then even NRT pages will be locked in future
if (m_type == Type::RT) {
ENSURE(m_system->mman->mlockall(MCL_CURRENT) == 0, "Could not lock pages.");
}
// create pthread
m_is_running = true;
ENSURE(m_system->pthread->pthread_create(&m_thread, &m_pthread_attr, &Thread::threadRun, this) ==
0,
"Could not create pthread.");
// set name
const char* name = m_name.substr(0, 15).c_str();
ENSURE(m_system->pthread->pthread_setname_np(m_thread, name) == 0, "Could not set thread name.");
// clear pthread attributes
ENSURE(m_system->pthread->pthread_attr_destroy(&m_pthread_attr) == 0,
"Could not destroy attribute.");
// lock all pages afterwards cause now thread is created and uses new pages
if (m_type == Type::RT) {
ENSURE(m_system->mman->mlockall(MCL_CURRENT) == 0, "Could not lock pages.");
}
m_created = true;
// TODO(sk) check thread properties as post condition
}
void Thread::cancel() {
if (m_created) {
if (m_thread != 0) {
ENSURE(m_system->pthread->pthread_cancel(m_thread) == 0, "Could not cancel thread.");
}
m_created = false;
}
}
void Thread::wake() {
std::unique_lock<std::mutex> lock(m_prio_mutex);
if (!m_got_wake_up) {
m_got_wake_up = true;
lock.unlock();
m_wake_up_cond_var.notify_one();
// TODO(sk) wake up sleeping non rt thread too
}
}
void* Thread::threadRun(void* thread) {
static_cast<Thread*>(thread)->run();
return thread;
}
void Thread::run() {
auto tick = std::chrono::steady_clock::now();
auto next_tick = tick;
while (m_is_running) {
m_update();
std::unique_lock<std::mutex> lock(m_prio_mutex);
if (m_is_running && !m_got_wake_up) {
if (m_period > 0us) {
next_tick = tick + m_period; // get relative sleep time
while (!m_got_wake_up) {
if (m_wake_up_cond_var.wait_until(lock, next_tick) == std::cv_status::timeout) {
m_got_wake_up = true;
}
}
tick = next_tick;
} else {
m_wake_up_cond_var.wait(lock, [&] { return m_got_wake_up.load(); });
}
m_got_wake_up = false; // clear for next wait
}
}
}
void Thread::stop() {
m_is_running = false;
wake();
}
void Thread::join() {
if (!m_is_running && m_thread != 0) {
ENSURE(m_system->pthread->pthread_join(m_thread, nullptr) == 0, "Could not join thread.");
m_created = false;
m_thread = 0;
}
}
} // namespace fdl
| true |
a1625102b9fee338ff5c4f59ebcbd4ca89fec4fa | C++ | nalualvarez/tp1t1 | /testes_dominios.h | UTF-8 | 2,535 | 2.625 | 3 | [] | no_license | #ifndef TESTES_DOMINIOS_H_INCLUDED
#define TESTES_DOMINIOS_H_INCLUDED
#include "dominios.h"
using namespace std;
class TUNome{ /**teste da classe do nome*/
private:
char valido[20], invalido[25];
const static int LIMITEVALIDO = 20, LIMITEINVALIDO = 25;
Nome *nome; /**referencia ao objeto que sera testado*/
int estado;
void setUp(); /**metodos para executar o teste*/
void tearDown();
void testarCenarioSucesso();
void testarCenarioFalha();
public:
const static int SUCESSO = 0; /**constantes para executar o teste*/
const static int FALHA = -1;
int run();
};
class TUSenha{ /**teste da classe senha*/
private:
char valido[6], invalido[10];
const static int LIMITEVALIDO = 6, LIMITEINVALIDO = 10;
Senha *senha;
int estado;
void setUp(); /**metodos para executar o teste*/
void tearDown();
void testarCenarioSucesso();
void testarCenarioFalha();
public:
const static int SUCESSO = 0; /**constantes para executar o teste*/
const static int FALHA = -1;
int run();
};
class TUEmail{ /**teste da classe do email*/
private:
char valido[20], invalido[20];
const static char arroba='@', ponto='.';
Email *email;
int estado;
void setUp(); /**metodos para executar o teste*/
void tearDown();
void testarCenarioSucesso();
void testarCenarioFalha();
public:
const static int SUCESSO = 0; /**constantes para executar o teste*/
const static int FALHA = -1;
int run();
};
class TUAvaliacao{ /**teste da classe do avaliacao*/
private:
const static int VALIDO=3, INVALIDO=6;
Avaliacao *avaliacao;
int estado;
void setUp(); //metodos para executar o teste
void tearDown();
void testarCenarioSucesso();
void testarCenarioFalha();
public:
const static int SUCESSO = 0; /**constantes para executar o teste*/
const static int FALHA = -1;
int run();
};
class TUTexto{
private:
char valido[50], invalido[60];
const static int LIMITEVALIDO=50, LIMITEINVALIDO=60;
Texto *texto;
int estado;
void setUp(); //metodos para executar o teste
void tearDown();
void testarCenarioSucesso();
void testarCenarioFalha();
public:
const static int SUCESSO = 0;
const static int FALHA = -1;
int run();
};
#endif // TESTES_H_INCLUDED
| true |
5794ea5dafca23b691ed80243e73421d24a8c686 | C++ | SeongHwanJin/2013440148 | /HW1-4/4번.cpp | UHC | 635 | 3.703125 | 4 | [] | no_license | /*4. () Է Ƽ (A, B, C, D, E) ϴ α ۼϽÿ.
(A : 100-80, B: 79-60, C: 59-40, D: 39-20, E: 19-0) */
#include <stdio.h>
int main () {
int a;
printf(" ԷϽÿ(0 100̿) : " );
scanf("%d", &a);
if (a >= 80 && a <=100)
printf(" AԴϴ. ");
else if (a <= 79 && a >= 60 )
printf(" BԴϴ. ");
else if (a <= 59 && a >= 40 )
printf(" CԴϴ. ");
else if (a <= 39 && a >= 20 )
printf(" DԴϴ. ");
else if (a <= 19 && a >= 0 )
printf(" EԴϴ. ");
} | true |
1d72b254a844448de401bab4f40c91c54078ba5e | C++ | brucewillis13/Filter | /Source.cpp | UTF-8 | 2,907 | 2.890625 | 3 | [] | no_license | //libraries
#include <stdio.h>
//for sqrt (square root)
#include <math.h>
#include "allegro5/allegro.h"
//use image addon for loading images, dialog boxes, and primitive shapes
#include <allegro5/allegro_image.h>
//global variable for display
ALLEGRO_DISPLAY* display = NULL; //ALLEGRO_DISPLAY is a "user defined type" in Allegro. * shows a pointer
//initialzie Allegro components
void InitAllegro(int W, int H)
{
//initialize allegro
if (!al_init())
{
printf("failed to initialize allegro!\n");
}
//initialize display screen
display = al_create_display(W, H);
if (!display)
{
printf("failed to create display!\n");
exit(0);
}
else
{
printf("ok");
al_clear_to_color(al_map_rgb(0, 0, 0));
}
//initialize keyboard
if (!al_install_keyboard())
{
printf("failed to install keyboard!\n");
exit(0);
}
//initialize image addon
if (!al_init_image_addon())
{
printf("failed to initialize image addon!\n");
exit(0);
}
}
//End and clean up Allegro components
void EndAllegro()
{
al_destroy_display(display);
}
//main function
void main()
{
///////////////////////////////////
// INITIALIZE
///////////////////////////////////
//initialize allegro
int sw = 640;
int sh = 480;
InitAllegro(sw, sh);
//use a temporart target bitmap and lock it so put-pixel is fast
ALLEGRO_BITMAP* bmp = al_create_bitmap(640, 480);
ALLEGRO_BITMAP* target = al_get_target_bitmap();
al_set_target_bitmap(bmp);
al_lock_bitmap(bmp, al_get_bitmap_format(bmp), ALLEGRO_LOCK_READWRITE);
//clear screen
al_clear_to_color(al_map_rgb(0, 0, 0));
//doall the drawings
for (int x = 0; x < 640; x++)
{
//formula for calculating the parameters of a line (y=m*x+b)
//based on two points on that line x1/y1 and x2/y2
//m = (y1-y2)/(x1-x2)
//b = y1 � m*x1
//range of X
int x1 = 0;
int x2 = 640;
//range of Y (in this case Y represents red component of gradient)
//we use float so the calculations are done in float
float y1 = 10;
float y2 = 200;
float m = (y2 - y1) / (x2 - x1);
float b = y1 - m * x1;
// int r = 255 * x / 600;
int r = m*x + b;
//g = b = 0;
for (int y = 0; y < 480; y++)
{
al_put_pixel(x, y, al_map_rgb(r, 0, 0));
}
//int y1 = x;
//al_put_pixel(x, y1, al_map_rgb(255, 0, 0));
//int y2 = 2 * x + 7;
//al_put_pixel(x, y2, al_map_rgb(0, 255, 0));
//
//int y3 = x * x;
//al_put_pixel(x, y3, al_map_rgb(255, 255, 255));
}
//unlock the target and flip display
al_set_target_bitmap(target);
al_unlock_bitmap(bmp);
al_draw_bitmap(bmp, 0, 0, 0);
al_flip_display();
//stay in a loop and wait
ALLEGRO_KEYBOARD_STATE key_state;
while (true)
{
al_get_keyboard_state(&key_state);
if (al_key_down(&key_state, ALLEGRO_KEY_ESCAPE))
{
exit(0);
}
}
} | true |
325d63e33366e5a4783ca6dc2566429a14e5a4fc | C++ | pick56/ACMTemplet | /制作模板/归并排序函数.cpp | UTF-8 | 478 | 2.953125 | 3 | [] | no_license | void merge_sort(int *A,int x,int y,int *T){
if(y-x>1){
int m = x +(y-x)/2 ;
int p = x ;
int q = m ;
int i = x ;
merge_sort(A,x,m,T) ;
merge_sort(A,m,y,T) ;
while(p<m||q<y){
if(q>=y||(p<m && A[p] <= A[q])) {
T[i++] = A[p++] ;
}
else {
T[i++] = A[q++] ;
}
}
for(int i=x;i<y;i++){
A[i] = T[i] ;
}
}
}
| true |
a2a8b2554c32e64074cef8de127f2b31c8d115af | C++ | Priya2410/Competetive_Programming | /BinarySearch.com/powerOfTwo.cpp | UTF-8 | 261 | 2.984375 | 3 | [] | no_license | // https://binarysearch.com/problems/Check-Power-of-Two
bool solve(int n) {
int rem,sum=0;
if(n==0)
return false;
while(n>0){
rem=n%2;
sum=sum+rem;
if(sum>1)
return false;
n=n/2;
}
return true;
}
| true |
c6a43cd084981bd05295e87b12bb60dcbcd3ccb6 | C++ | DekhanFraser/Galaxians_clone_in_C- | /Source/GD1P04 3DGame - Alex (Valeriy) Ruzhitskiy/Player.cpp | UTF-8 | 6,092 | 2.515625 | 3 | [] | no_license | //
// Bachelor of Software Engineering
// Media Design School
// Auckland
// New Zealand
//
// (c)2005 - 2016 Media Design School
//
// File Name : Player.cpp
// Description: Player gameobject implementation
// Author: Alex (Valeriy) Ruzhitskiy
// Mail: alexander.izmaylov@gmail.com
//
#include "Player.h"
#include "ResourceManager.h"
/*
* Function - Player()
* Default constructor
* Author - Alex (Valeriy) Ruzhitskiy
*/
Player::Player()
{
}
/*
* Function - Player(@param)
* Parametrized constructor
* Author - Alex (Valeriy) Ruzhitskiy
* @param :
* glm::vec2 pos -player position
* Texture2D sprite - player sprite
* Engine *engine - pointer to game engine
*/
Player::Player(glm::vec2 pos, Texture2D sprite, Engine *engine)
:GameObject(pos, glm::vec2(sprite.Width, sprite.Height), sprite), maxSpeed(300.0f), m_engine(engine), fireTimer(0.1f), lastShot(0.0f)
{
iff = Friend;
}
/*
* Function - ~Player()
* Default destructor
* Author - Alex (Valeriy) Ruzhitskiy
*/
Player::~Player()
{
m_engine = 0;
}
/*
* Function - Update(@param)
* Update function
* Author - Alex (Valeriy) Ruzhitskiy
* @param :
* GLfloat dt - deltatime per frame
*/
void Player::Update(GLfloat dt)
{
lastShot += dt;
Velocity *= 0.95;
if (Velocity.x > maxSpeed)
{
Velocity.x = maxSpeed;
}
if (Velocity.x < -maxSpeed)
{
Velocity.x = -maxSpeed;
}
if (Velocity.y > maxSpeed)
{
Velocity.y = maxSpeed;
}
if (Velocity.y < -maxSpeed)
{
Velocity.y = -maxSpeed;
}
Position += Velocity * dt;
KeepInBounds();
UpdateRotation();
}
/*
* Function - Render(@param)
* Rendering function
* Author - Alex (Valeriy) Ruzhitskiy
* @param :
* SpriteRenderer - reference to renderer
*/
void Player::Render(SpriteRenderer &renderer)
{
GameObject::Render(renderer);
}
/*
* Function - ProcessInput(@param)
* Update input function
* Author - Alex (Valeriy) Ruzhitskiy
* @param :
* GLfloat dt - deltatime per frame
*/
void Player::ProcessInput(GLboolean Keys[1024], GLfloat dt)
{
if (Keys[GLFW_KEY_A] || Keys[GLFW_KEY_LEFT])
{
ApplyForce(glm::vec2(-50.0f, 0.0f));
}
if (Keys[GLFW_KEY_D] || Keys[GLFW_KEY_RIGHT])
{
ApplyForce(glm::vec2(50.0f, 0.0f));
}
if (Keys[GLFW_KEY_W] || Keys[GLFW_KEY_UP])
{
ApplyForce(glm::vec2(0.0f, -50.0f));
}
if (Keys[GLFW_KEY_S] || Keys[GLFW_KEY_DOWN])
{
ApplyForce(glm::vec2(0.0f, 50.0f));
}
if (Keys[GLFW_KEY_SPACE])
{
Fire();
}
//Update player rotation
if ((Keys[GLFW_KEY_A] || Keys[GLFW_KEY_LEFT]) && (Keys[GLFW_KEY_W] || Keys[GLFW_KEY_UP]))
{
dir = AW;
}
else if ((Keys[GLFW_KEY_W] || Keys[GLFW_KEY_UP]) && (Keys[GLFW_KEY_D] || Keys[GLFW_KEY_RIGHT]))
{
dir = WD;
}
else if ((Keys[GLFW_KEY_D] || Keys[GLFW_KEY_RIGHT]) && (Keys[GLFW_KEY_S] || Keys[GLFW_KEY_DOWN]))
{
dir = DS;
}
else if ((Keys[GLFW_KEY_S] || Keys[GLFW_KEY_DOWN]) && (Keys[GLFW_KEY_A] || Keys[GLFW_KEY_LEFT]))
{
dir = SA;
}
else if ((Keys[GLFW_KEY_A] || Keys[GLFW_KEY_LEFT]))
{
dir = A;
}
else if ((Keys[GLFW_KEY_W] || Keys[GLFW_KEY_UP]))
{
dir = W;
}
else if ((Keys[GLFW_KEY_D] || Keys[GLFW_KEY_RIGHT]))
{
dir = D;
}
else if ((Keys[GLFW_KEY_S] || Keys[GLFW_KEY_DOWN]))
{
dir = S;
}
}
/*
* Function - UpdateRotation()
* Update object sprite rotation
* Author - Alex (Valeriy) Ruzhitskiy
*/
void Player::UpdateRotation()
{
switch (dir)
{
case A:
Rotation = glm::radians(-90.0f);
break;
case AW:
Rotation = glm::radians(-45.0f);
break;
case W:
Rotation = glm::radians(0.0f);
break;
case WD:
Rotation = glm::radians(45.0f);
break;
case D:
Rotation = glm::radians(90.0f);
break;
case DS:
Rotation = glm::radians(135.0f);
break;
case S:
Rotation = glm::radians(180.0f);
break;
case SA:
Rotation = glm::radians(-135.0f);
break;
default:
break;
}
}
/*
* Function - ApplyForce(@param)
* Apply steering force to object
* Author - Alex (Valeriy) Ruzhitskiy
* @param :
* glm::vec2 force - force to apply
*/
void Player::ApplyForce(glm::vec2 _force)
{
Velocity += _force;
}
/*
* Function - Fire()
* Fire weapon
* Author - Alex (Valeriy) Ruzhitskiy
*/
void Player::Fire()
{
if (lastShot > fireTimer)
{
Bullet bullet(Position, glm::vec2(0.0f, 0.0f), ResourceManager::GetTexture("bullet1"));
switch (dir)
{
case A:
bullet.Position.x += -15.0f;
bullet.Position.y += 25.0f;
bullet.Velocity = glm::vec2(-1000.0f, 0.0f);
break;
case AW:
bullet.Position.x += -5.0f;
bullet.Position.y += -5.0f;
bullet.Velocity = glm::vec2(-1000.0f, -1000.0f);
break;
case W:
bullet.Position.x += 25.0f;
bullet.Position.y += -10.0f;
bullet.Velocity = glm::vec2(0.0f, -1000.0f);
break;
case WD:
bullet.Position.x += Size.x - 5.0f;
bullet.Position.y += - 5.0f;
bullet.Velocity = glm::vec2(1000.0f, -1000.0f);
break;
case D:
bullet.Position.x += Size.x;
bullet.Position.y += 25.0f;
bullet.Velocity = glm::vec2(1000.0f, 0.0f);
break;
case DS:
bullet.Position.x += Size.x -10.0f;
bullet.Position.y += Size.y -10.0f;
bullet.Velocity = glm::vec2(1000.0f, 1000.0f);
break;
case S:
bullet.Position.x += 25.0f;
bullet.Position.y += Size.y;
bullet.Velocity = glm::vec2(0.0f, 1000.0f);
break;
case SA:
bullet.Position.x += -5.0f;
bullet.Position.y += Size.y -10.0f;
bullet.Velocity = glm::vec2(-1000.0f, 1000.0f);
break;
default:
break;
}
bullet.iff = Friend;
m_engine->Bullets.push_back(bullet);
m_engine->PlaySound("assets/audio/laser_shoot.wav", GL_FALSE);
lastShot = 0;
}
}
/*
* Function - KeepInBounds()
* Restrict player position to onscreen
* Author - Alex (Valeriy) Ruzhitskiy
*/
void Player::KeepInBounds()
{
if (Position.y < 0.0f)
{
Position.y = 0.0f;
}
if (Position.y > m_engine->Height - Size.y)
{
Position.y = m_engine->Height - Size.y;
}
if (Position.x < 0.0f)
{
Position.x = 0.0f;
}
if (Position.x > m_engine->Width - Size.x)
{
Position.x = m_engine->Width - Size.x;
}
} | true |
41c5a486557fe7635caff34525fbf309183c7ce4 | C++ | RedBeard0531/mongo_utils | /base/data_type_terminated_test.cpp | UTF-8 | 8,516 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | /**
* Copyright (C) 2015 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mongo/base/data_type_terminated.h"
#include "mongo/base/data_range.h"
#include "mongo/base/data_range_cursor.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/stringutils.h"
#include <string>
namespace mongo {
namespace {
// For testing purposes, a type that has a fixed load and store size, and some
// arbitrary serialization format of 'd' repeated N times.
template <size_t N>
struct Dummy {
static constexpr size_t extent = N;
};
} // namespace
// Pop the anonymous namespace to specialize mongo::DataType::Handler.
// Template specialization is a drag.
template <size_t N>
struct DataType::Handler<Dummy<N>> {
using handledType = Dummy<N>;
static constexpr size_t extent = handledType::extent;
static Status load(handledType* sdata,
const char* ptr,
size_t length,
size_t* advanced,
std::ptrdiff_t debug_offset) {
if (length < extent) {
return Status(ErrorCodes::Overflow, "too short for Dummy");
}
for (size_t i = 0; i < extent; ++i) {
if (*ptr++ != 'd') {
return Status(ErrorCodes::Overflow, "load of invalid Dummy object");
}
}
*advanced = extent;
return Status::OK();
}
static Status store(const handledType& sdata,
char* ptr,
size_t length,
size_t* advanced,
std::ptrdiff_t debug_offset) {
if (length < extent) {
return Status(ErrorCodes::Overflow, "insufficient space for Dummy");
}
for (size_t i = 0; i < extent; ++i) {
*ptr++ = 'd';
}
*advanced = extent;
return Status::OK();
}
static handledType defaultConstruct() {
return {};
}
};
// Re-push the anonymous namespace.
namespace {
/**
* Tests specifically for Terminated, unrelated to the DataRange
* or DataRangeCursor classes that call it.
*/
TEST(DataTypeTerminated, StringDataNormalStore) {
const StringData writes[] = {StringData("a"), StringData("bb"), StringData("ccc")};
std::string buf(100, '\xff');
char* const bufBegin = &*buf.begin();
char* ptr = bufBegin;
size_t avail = buf.size();
std::string expected;
for (const auto& w : writes) {
size_t adv;
ASSERT_OK(
DataType::store(Terminated<'\0', StringData>(w), ptr, avail, &adv, ptr - bufBegin));
ASSERT_EQ(adv, w.size() + 1);
ptr += adv;
avail -= adv;
expected += w.toString();
expected += '\0';
}
ASSERT_EQUALS(expected, buf.substr(0, buf.size() - avail));
}
TEST(DataTypeTerminated, StringDataNormalLoad) {
const StringData writes[] = {StringData("a"), StringData("bb"), StringData("ccc")};
std::string buf;
for (const auto& w : writes) {
buf += w.toString();
buf += '\0';
}
const char* const bufBegin = &*buf.begin();
const char* ptr = bufBegin;
size_t avail = buf.size();
for (const auto& w : writes) {
size_t adv;
auto term = Terminated<'\0', StringData>{};
ASSERT_OK(DataType::load(&term, ptr, avail, &adv, ptr - bufBegin));
ASSERT_EQ(adv, term.value.size() + 1);
ptr += adv;
avail -= adv;
ASSERT_EQUALS(term.value, w);
}
}
TEST(DataTypeTerminated, LoadStatusOkPropagation) {
// Test that the nested type's .load complaints are surfaced.
const char buf[] = {'d', 'd', 'd', '\0'};
size_t advanced = 123;
auto x = Terminated<'\0', Dummy<3>>();
Status s = DataType::load(&x, buf, sizeof(buf), &advanced, 0);
ASSERT_OK(s);
ASSERT_EQUALS(advanced, 4u); // OK must overwrite advanced
}
TEST(DataTypeTerminated, StoreStatusOkAdvanced) {
// Test that an OK .store sets proper 'advanced'.
char buf[4] = {};
size_t advanced = 123; // should be overwritten
Status s = DataType::store(Terminated<'\0', Dummy<3>>(), buf, sizeof(buf), &advanced, 0);
ASSERT_OK(s);
ASSERT_EQ(StringData(buf, 4), StringData(std::string{'d', 'd', 'd', '\0'}));
ASSERT_EQUALS(advanced, 4u); // OK must overwrite advanced
}
TEST(DataTypeTerminated, ErrorUnterminatedRead) {
const char buf[] = {'h', 'e', 'l', 'l', 'o'};
size_t advanced = 123;
auto x = Terminated<'\0', StringData>();
Status s = DataType::load(&x, buf, sizeof(buf), &advanced, 0);
ASSERT_EQ(s.codeString(), "Overflow");
ASSERT_STRING_CONTAINS(s.reason(), "couldn't locate");
ASSERT_STRING_CONTAINS(s.reason(), "terminal char (\\u0000)");
ASSERT_EQUALS(advanced, 123u); // fails must not overwrite advanced
}
TEST(DataTypeTerminated, LoadStatusPropagation) {
// Test that the nested type's .load complaints are surfaced.
const char buf[] = {'d', 'd', '\0'};
size_t advanced = 123;
auto x = Terminated<'\0', Dummy<3>>();
Status s = DataType::load(&x, buf, sizeof(buf), &advanced, 0);
ASSERT_EQ(s.codeString(), "Overflow");
ASSERT_STRING_CONTAINS(s.reason(), "too short for Dummy");
// ASSERT_STRING_CONTAINS(s.reason(), "terminal char (\\u0000)");
ASSERT_EQUALS(advanced, 123u); // fails must not overwrite advanced
}
TEST(DataTypeTerminated, StoreStatusPropagation) {
// Test that the nested type's .store complaints are surfaced.
char in[2]; // Not big enough to hold a Dummy<3>.
size_t advanced = 123;
Status s = DataType::store(Terminated<'\0', Dummy<3>>(), in, sizeof(in), &advanced, 0);
ASSERT_EQ(s.codeString(), "Overflow");
ASSERT_STRING_CONTAINS(s.reason(), "insufficient space for Dummy");
ASSERT_EQUALS(advanced, 123u); // fails must not overwrite advanced
}
TEST(DataTypeTerminated, ErrorShortRead) {
// The span before the '\0' is passed to Dummy<3>'s load.
// This consumes only the first 3 bytes, so Terminated complains
// about the unconsumed 'X'.
const char buf[] = {'d', 'd', 'd', 'X', '\0'};
size_t advanced = 123;
auto x = Terminated<'\0', Dummy<3>>();
Status s = DataType::load(&x, buf, sizeof(buf), &advanced, 0);
ASSERT_EQ(s.codeString(), "Overflow");
ASSERT_STRING_CONTAINS(s.reason(), "only read");
ASSERT_STRING_CONTAINS(s.reason(), "terminal char (\\u0000)");
ASSERT_EQUALS(advanced, 123u); // fails must not overwrite advanced
}
TEST(DataTypeTerminated, ErrorShortWrite) {
char in[3] = {};
auto x = Terminated<'\0', Dummy<3>>();
size_t advanced = 123;
Status s = DataType::store(x, in, sizeof(in), &advanced, 0);
ASSERT_EQ(s.codeString(), "Overflow");
ASSERT_STRING_CONTAINS(s.reason(), "couldn't write");
ASSERT_STRING_CONTAINS(s.reason(), "terminal char (\\u0000)");
ASSERT_EQUALS(advanced, 123u); // fails must not overwrite advanced
}
TEST(DataTypeTerminated, ThroughDataRangeCursor) {
char buf[100];
const std::string parts[] = {"a", "bb", "ccc"};
std::string serialized;
for (const std::string& s : parts) {
serialized += s + '\0';
}
{
auto buf_writer = DataRangeCursor(buf, buf + sizeof(buf));
for (const std::string& s : parts) {
Terminated<'\0', ConstDataRange> tcdr(ConstDataRange(s.data(), s.data() + s.size()));
ASSERT_OK(buf_writer.writeAndAdvance(tcdr));
}
const auto written = std::string(static_cast<const char*>(buf), buf_writer.data());
ASSERT_EQUALS(written, serialized);
}
{
auto buf_source = ConstDataRangeCursor(buf, buf + sizeof(buf));
for (const std::string& s : parts) {
Terminated<'\0', ConstDataRange> tcdr;
ASSERT_OK(buf_source.readAndAdvance(&tcdr));
std::string read(tcdr.value.data(), tcdr.value.data() + tcdr.value.length());
ASSERT_EQUALS(s, read);
}
}
}
} // namespace
} // namespace mongo
| true |
5cf65efd5f0cd635f89d7dec494831ae72d7f117 | C++ | goodcodedev/lang-base | /test-lang.hpp | UTF-8 | 1,140 | 2.734375 | 3 | [
"MIT"
] | permissive | enum Type {
INT, VOID
};
static std::string enumTypeToString(Type item) {
switch (item) {
case INT:return "int";
case VOID:return "void";
default: return "";
}
}
class Expression {
};
class Function {
Type Type;
std::vector<Expression*>* argExprs;
std::string identifier;
Function(Type Type, std::string identifier, std::vector<Expression*>* argExprs) : Type(Type), identifier(identifier), argExprs(argExprs) {}
};
class IdExpr : public Expression {
std::string identifier;
IdExpr(std::string identifier) : identifier(identifier) {}
};
class IntExpr : public Expression {
int intConst;
IntExpr(int intConst) : intConst(intConst) {}
};
Function* parseFile(std::string fileName) {
FILE *sourceFile;
errno = 0;
string fullFile = std::string(PROJECT_ROOT) + fileName;
#ifdef _WIN32
fopen_s(&sourceFile, fullFile.c_str(), "r");
#else
sourceFile = fopen(fullFile.c_str(), "r");
#endif
if (!sourceFile) {
printf("Can't open file %d", errno);
exit(1);
}
yyin = sourceFile;
do {
yyparse();
} while (!feof(yyin));
return result;
}
| true |
1deceda2b062a489c01bcea39a99476cd87807ef | C++ | wildparky/materialXToArnold | /src/materialx_to_arnold/implementation.h | UTF-8 | 1,446 | 2.5625 | 3 | [] | no_license | #ifndef MTLX_TO_A_IMPLEMENTATION_H
#define MTLX_TO_A_IMPLEMENTATION_H
#include "arnold/facade.h"
//
// These functions:
// - Facilitate the dependency injection (template method) of the Arnold and
// MaterialX facade classes into the implementation
// - Handle the Arnold User Data resource management
// - Dispatch calls to the required functions in this library to perform the
// MaterialX to Arnold translation during the procedural initialization
//
// Recall that Dependency Injection (Template Method) makes the code more
// friendly to unit testing. Google calls this hi-perf dependency injection. See
// the section Mocking Nonvirtual Methods at:
// https://github.com/google/googletest/blob/master/googlemock/docs/CookBook.md
//
namespace MaterialXToArnold
{
void ParametersImpl(typename ArnoldFacade::AtListT* params,
typename ArnoldFacade::AtNodeEntryT* nentry);
int ProceduralInitImpl(const typename ArnoldFacade::AtNodeT* node,
void** user_ptr);
int ProceduralCleanupImpl(const typename ArnoldFacade::AtNodeT* node,
void* user_ptr);
int ProceduralNumNodesImpl(const typename ArnoldFacade::AtNodeT* node,
void* user_ptr);
AtNode* ProceduralGetNodeImpl(const typename ArnoldFacade::AtNodeT* node,
void* user_ptr, int i);
} // namespce MaterialXToArnold
#endif // MTLX_TO_A_IMPLEMENTATION_H
| true |