blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
177a8c1caf5be1d7c5d67be4fcda619d48db57ab
|
fba78ec1c0edffc3a4f3fa2604ff700d47dea954
|
/DLL_Sources/CvPlotGroup.h
|
0bd78f422ebaba390e90cf0adab80821e9eadf83
|
[] |
no_license
|
Nightinggale/Medieval_Tech
|
3e0207b34368c49ac81c72abe8b8876064080407
|
20c945b0697134bb9d8ba9da255eb63c3bdc4b29
|
refs/heads/master
| 2016-09-06T11:34:52.396842
| 2014-04-29T01:12:31
| 2014-04-29T01:12:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,229
|
h
|
CvPlotGroup.h
|
#pragma once
// plotGroup.h
#ifndef CIV4_PLOT_GROUP_H
#define CIV4_PLOT_GROUP_H
//#include "CvStructs.h"
#include "LinkedList.h"
class CvPlot;
class CvPlotGroup
{
public:
CvPlotGroup();
virtual ~CvPlotGroup();
void init(int iID, PlayerTypes eOwner, CvPlot* pPlot);
void uninit();
void reset(int iID = 0, PlayerTypes eOwner = NO_PLAYER, bool bConstructorCall=false);
void addPlot(CvPlot* pPlot);
void removePlot(CvPlot* pPlot);
void recalculatePlots();
int getID() const;
void setID(int iID);
PlayerTypes getOwner() const;
#ifdef _USRDLL
inline PlayerTypes getOwnerINLINE() const
{
return m_eOwner;
}
#endif
#ifdef USE_PLOTGROUP_RESOURCES
int getNumBonuses(BonusTypes eBonus) const;
bool hasBonus(BonusTypes eBonus) const;
void changeNumBonuses(BonusTypes eBonus, int iChange);
#endif
void insertAtEndPlots(XYCoords xy);
CLLNode<XYCoords>* deletePlotsNode(CLLNode<XYCoords>* pNode);
CLLNode<XYCoords>* nextPlotsNode(CLLNode<XYCoords>* pNode);
int getLengthPlots();
CLLNode<XYCoords>* headPlotsNode();
// for serialization
void read(FDataStreamBase* pStream);
void write(FDataStreamBase* pStream);
// homemade function - Nightinggale
void deleteAllPlots();
protected:
int m_iID;
PlayerTypes m_eOwner;
#ifdef USE_PLOTGROUP_RESOURCES
BonusArray<int> m_aiNumBonuses;
#endif
CLinkList<XYCoords> m_plots;
};
inline int CvPlotGroup::getID() const
{
return m_iID;
}
inline void CvPlotGroup::setID(int iID)
{
m_iID = iID;
}
inline PlayerTypes CvPlotGroup::getOwner() const
{
return getOwnerINLINE();
}
#ifdef USE_PLOTGROUP_RESOURCES
inline int CvPlotGroup::getNumBonuses(BonusTypes eBonus) const
{
return m_aiNumBonuses.get(eBonus);
}
// Nightinggale note: getNumBonuses() always be used instead of hasBonus()
// the reason is that when an int is used as a bool, the compiler will assume != 0 to turn it into a bool
// I added it anyway for completeness because it's part of vanilla Civ4BTS
// both functions should be equally fast due to inlining
// Civ4 doesn't have hasBonus() inlined meaning it adds overhead as an extra function call
inline bool CvPlotGroup::hasBonus(BonusTypes eBonus) const
{
return(getNumBonuses(eBonus) > 0);
}
#endif
#endif
|
912311a37b690259796c89ed55774db24c1ceaec
|
808a6d2a71645dfe6bda0fe61fe37b7f4acab095
|
/src/search_2d_array.cpp
|
c9aa3bb6738789e29e72711d62c35c7c9b6141da
|
[] |
no_license
|
ilija-s/algorithms
|
4836bb48c5eea28b7a45b146ae40233fa485e56d
|
2838c155f8939d11b1693939bcac013818e432e2
|
refs/heads/main
| 2023-06-02T09:29:22.515701
| 2021-06-21T20:01:02
| 2021-06-21T20:01:02
| 304,848,461
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 996
|
cpp
|
search_2d_array.cpp
|
#include <iostream>
#include <vector>
using namespace std;
/*
* Time complexity O(rows + cols)
* Space complexity O(1)
*/
bool find_element(vector< vector<int>> matrix, int target) {
int rows = matrix.size();
int cols = matrix[0].size();
int start_row = 0;
int start_col = cols - 1;
while (start_row < rows && start_col >= 0) {
if (target == matrix[start_row][start_col])
return true;
else if (target < matrix[start_row][start_col])
start_col--;
else
start_row++;
}
return false;
}
int main(){
int target;
int rows, cols;
cin >> target >> rows >> cols;
vector< vector<int>> matrix(rows, vector<int>(cols));
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
cin >> matrix[i][j];
bool element_found = find_element(matrix, target);
if (element_found)
cout << "1";
else
cout << "0";
cout << endl;
return 0;
}
|
ba2aec1ca15c61b19b1a95038ce69479d863b56c
|
c9bdac4dc757ce861c247baddca0011b48a7e7cd
|
/src/BufferPointRecord.cpp
|
02915ec7dfb57e38380f9b6b6905b16c90a271aa
|
[
"BSD-2-Clause"
] |
permissive
|
Ansarian83/epanet-rtx
|
d0a380b63b58da4103d928e9508ff0461ce815e9
|
c2e78f030f644d3696a9313f24f3dc134db6af6b
|
refs/heads/master
| 2020-07-17T18:33:46.935892
| 2014-07-10T14:54:53
| 2014-07-10T14:54:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 13,247
|
cpp
|
BufferPointRecord.cpp
|
//
// BufferPointRecord.cpp
// epanet-rtx
//
// Created by the EPANET-RTX Development Team
// See README.md and license.txt for more information
//
#include "BufferPointRecord.h"
#include "boost/foreach.hpp"
using namespace RTX;
using namespace std;
//bool compareTimePointPair(const BufferPointRecord::TimePointPair_t& lhs, const BufferPointRecord::TimePointPair_t& rhs);
BufferPointRecord::BufferPointRecord() {
_defaultCapacity = 100;
}
std::ostream& RTX::operator<< (std::ostream &out, BufferPointRecord &pr) {
return pr.toStream(out);
}
std::ostream& BufferPointRecord::toStream(std::ostream &stream) {
stream << "Buffered Point Record" << std::endl;
return stream;
}
std::string BufferPointRecord::registerAndGetIdentifier(std::string recordName) {
// register the recordName internally and generate a buffer and mutex
// check to see if it's there first
if (_keyedBufferMutex.find(recordName) == _keyedBufferMutex.end()) {
PointBuffer_t buffer;
buffer.set_capacity(_defaultCapacity);
// shared pointer since it's not copy-constructable.
boost::shared_ptr< boost::signals2::mutex >mutexPtr(new boost::signals2::mutex );
BufferMutexPair_t bmPair(buffer, mutexPtr);
_keyedBufferMutex.insert(make_pair(recordName, bmPair));
}
return recordName;
}
std::vector<std::string> BufferPointRecord::identifiers() {
typedef std::map<std::string, BufferMutexPair_t >::value_type& nameMapValue_t;
vector<string> names;
BOOST_FOREACH(nameMapValue_t name, _keyedBufferMutex) {
names.push_back(name.first);
}
return names;
}
/*
bool compareTimePointPair(const BufferPointRecord::TimePointPair_t& lhs, const BufferPointRecord::TimePointPair_t& rhs) {
return lhs.first < rhs.first;
}
*/
/*
// convenience method for making a new point from a buffer iterator
Point BufferPointRecord::makePoint(PointBuffer_t::const_iterator iterator) {
return Point((*iterator).first, (*iterator).second.first, Point::good, (*iterator).second.second);
}
*/
Point BufferPointRecord::point(const string& identifier, time_t time) {
bool isAvailable = false;
// quick check for repeated calls
if (_cachedPoint.time == time && RTX_STRINGS_ARE_EQUAL_CS(_cachedPointId, identifier) ) {
return _cachedPoint;
}
KeyedBufferMutexMap_t::iterator it = _keyedBufferMutex.find(identifier);
if (it == _keyedBufferMutex.end()) {
// nobody here by that name
return Point();
}
// get the constituents
boost::signals2::mutex *mutex = (it->second.second.get());
PointBuffer_t& buffer = (it->second.first);
if (buffer.empty()) {
return Point();
}
// lock the buffer
mutex->lock();
Point pFirst = buffer.front();
Point pLast = buffer.back();
if (pFirst.time <= time && time <= pLast.time) {
// search the buffer
//TimePointPair_t finder(time, PointPair_t(0,0));
Point finder(time, 0);
PointBuffer_t::const_iterator pbIt = std::lower_bound(buffer.begin(), buffer.end(), finder, &Point::comparePointTime);
if (pbIt != buffer.end() && pbIt->time == time) {
isAvailable = true;
_cachedPoint = *pbIt;
_cachedPointId = identifier;
}
else {
//cerr << "whoops, not found" << endl;
// try brute-force (debug)
PointBuffer_t::const_iterator pbIt = buffer.begin();
while (pbIt != buffer.end()) {
time_t foundTime = pbIt->time;
if (foundTime == time) {
cout << "found it anyway!!" << endl;
Point aPoint = *pbIt;
_cachedPoint = aPoint;
}
++pbIt;
}
}
}
// ok, all done
mutex->unlock();
if (isAvailable) {
return _cachedPoint;
}
else {
return Point();//this->pointBefore(identifier, time);
}
}
Point BufferPointRecord::pointBefore(const string& identifier, time_t time) {
Point foundPoint;
//TimePointPair_t finder(time, PointPair_t(0,0));
Point finder(time, 0);
KeyedBufferMutexMap_t::iterator it = _keyedBufferMutex.find(identifier);
if (it != _keyedBufferMutex.end()) {
// get the constituents
boost::signals2::mutex *mutex = (it->second.second.get());
PointBuffer_t& buffer = (it->second.first);
// lock the buffer
mutex->lock();
PointBuffer_t::const_iterator it = lower_bound(buffer.begin(), buffer.end(), finder, &Point::comparePointTime);
if (it != buffer.end() && it != buffer.begin()) {
if (--it != buffer.end()) {
foundPoint = *it;
_cachedPoint = foundPoint;
_cachedPointId = identifier;
}
}
// all done.
mutex->unlock();
}
return foundPoint;
}
Point BufferPointRecord::pointAfter(const string& identifier, time_t time) {
Point foundPoint;
//TimePointPair_t finder(time, PointPair_t(0,0));
Point finder(time, 0);
KeyedBufferMutexMap_t::iterator it = _keyedBufferMutex.find(identifier);
if (it != _keyedBufferMutex.end()) {
// get the constituents
boost::signals2::mutex *mutex = (it->second.second.get());
PointBuffer_t& buffer = (it->second.first);
// lock the buffer
mutex->lock();
PointBuffer_t::const_iterator it = upper_bound(buffer.begin(), buffer.end(), finder, &Point::comparePointTime);
if (it != buffer.end()) {
foundPoint = *it;
_cachedPoint = foundPoint;
_cachedPointId = identifier;
}
// all done.
mutex->unlock();
}
return foundPoint;
}
std::vector<Point> BufferPointRecord::pointsInRange(const string& identifier, time_t startTime, time_t endTime) {
std::vector<Point> pointVector;
//TimePointPair_t finder(startTime, PointPair_t(0,0));
Point finder(startTime, 0);
KeyedBufferMutexMap_t::iterator it = _keyedBufferMutex.find(identifier);
if (it != _keyedBufferMutex.end()) {
// get the constituents
boost::signals2::mutex *mutex = (it->second.second.get());
PointBuffer_t& buffer = (it->second.first);
// lock the buffer
mutex->lock();
PointBuffer_t::const_iterator it = lower_bound(buffer.begin(), buffer.end(), finder, &Point::comparePointTime);
while ( (it != buffer.end()) && (it->time <= endTime) ) {
Point newPoint = *it;
pointVector.push_back(newPoint);
it++;
}
// all done.
mutex->unlock();
}
return pointVector;
}
void BufferPointRecord::addPoint(const string& identifier, Point point) {
//if (BufferPointRecord::isPointAvailable(identifier, point.time)) {
//cout << "skipping duplicate point" << endl;
// return;
//}
/*
vector<Point> single;
single.push_back(point);
BufferPointRecord::addPoints(identifier, single);
*/
/*
bool unordered = false;
// test for continuity
KeyedBufferMutexMap_t::iterator kbmmit = _keyedBufferMutex.find(identifier);
if (kbmmit != _keyedBufferMutex.end()) {
// get the constituents
boost::signals2::mutex *mutex = (kbmmit->second.second.get());
PointBuffer_t& buffer = (kbmmit->second.first);
// lock the buffer
mutex->lock();
// check for monotonically increasing time values.
PointBuffer_t::const_iterator pIt = buffer.begin();
while (pIt != buffer.end()) {
time_t t1 = pIt->first;
++pIt;
if (pIt == buffer.end()) { break; }
time_t t2 = pIt->first;
if (t1 >= t2) {
cerr << "Points unordered" << endl;
unordered = true;
break;
}
}
if (unordered) {
// make sure the points are in order.
sort(buffer.begin(), buffer.end(), compareTimePointPair);
}
mutex->unlock();
}
*/
double value, confidence;
time_t time;
bool skipped = true;
time = point.time;
value = point.value;
confidence = point.confidence;
//PointPair_t newPoint(value, confidence);
KeyedBufferMutexMap_t::iterator it = _keyedBufferMutex.find(identifier);
if (it != _keyedBufferMutex.end()) {
// get the constituents
boost::signals2::mutex *mutex = (it->second.second.get());
PointBuffer_t& buffer = (it->second.first);
// lock the buffer
mutex->lock();
if (buffer.size() == buffer.capacity()) {
//cout << "buffer full" << endl;
}
time_t firstTime = BufferPointRecord::firstPoint(identifier).time;
time_t lastTime = BufferPointRecord::lastPoint(identifier).time;
if (time == lastTime || time == firstTime) {
// skip it
skipped = false;
}
if (time > lastTime) {
// end of the buffer
buffer.push_back(point);
skipped = false;
}
else if (time < firstTime) {
// front of the buffer
buffer.push_front(point);
skipped = false;
}
if (skipped) {
//cout << "point skipped: " << identifier;
//TimePointPair_t finder(time, PointPair_t(0,0));
Point finder(time, 0);
PointBuffer_t::const_iterator it = lower_bound(buffer.begin(), buffer.end(), finder, &Point::comparePointTime);
if (it->time != time) {
// if the time is not found here, then it's a new point.
buffer.push_front(point);
// make sure the points are in order.
sort(buffer.begin(), buffer.end(), &Point::comparePointTime);
}
}
// all done.
mutex->unlock();
}
if (skipped) {
//cout << "(" << isPointAvailable(identifier, time) << ")" << endl;
}
}
void BufferPointRecord::addPoints(const string& identifier, std::vector<Point> points) {
if (points.size() == 0) {
return;
}
// check the cache size, and upgrade if needed.
KeyedBufferMutexMap_t::iterator it = _keyedBufferMutex.find(identifier);
if (it != _keyedBufferMutex.end()) {
PointBuffer_t& buffer = (it->second.first);
size_t capacity = buffer.capacity();
if (capacity < points.size()) {
// plenty of room
buffer.set_capacity(points.size() + capacity);
}
// figure out the insert order...
// if the set we're inserting has to be prepended to the buffer...
time_t insertFirst = points.front().time;
time_t insertLast = points.back().time;
PointRecord::time_pair_t range = BufferPointRecord::range(identifier);
// make sure they're in order
std::sort(points.begin(), points.end(), &Point::comparePointTime);
bool gap = true;
if (insertFirst < range.second && range.second < insertLast) {
// insert onto end.
gap = false;
Point finder(range.second, 0);
vector<Point>::const_iterator pIt = upper_bound(points.begin(), points.end(), finder, &Point::comparePointTime);
while (pIt != points.end()) {
// skip points that fall before the end of the buffer.
if (pIt->time > range.second) {
BufferPointRecord::addPoint(identifier, *pIt);
}
++pIt;
}
}
if (insertFirst < range.first && range.first < insertLast) {
// insert onto front (reverse iteration)
gap = false;
vector<Point>::const_reverse_iterator pIt = points.rbegin();
while (pIt != points.rend()) {
// skip overlapping points.
if (pIt->time < range.first) {
BufferPointRecord::addPoint(identifier, *pIt);
}
// else { /* skip */ }
++pIt;
}
}
if (range.first <= insertFirst && insertLast <= range.second) {
// complete overlap -- why did we even try to add these?
gap = false;
}
if (gap) {
// clear the buffer first.
buffer.clear();
// add new points.
BOOST_FOREACH(Point p, points) {
BufferPointRecord::addPoint(identifier, p);
}
}
}
}
void BufferPointRecord::reset() {
_keyedBufferMutex.clear();
}
void BufferPointRecord::reset(const string& identifier) {
KeyedBufferMutexMap_t::iterator it = _keyedBufferMutex.find(identifier);
if (it != _keyedBufferMutex.end()) {
PointBuffer_t& buffer = (it->second.first);
buffer.clear();
}
}
Point BufferPointRecord::firstPoint(const string& id) {
Point foundPoint;
KeyedBufferMutexMap_t::iterator it = _keyedBufferMutex.find(id);
if (it != _keyedBufferMutex.end()) {
// get the constituents
//boost::signals2::mutex *mutex = (it->second.second.get());
PointBuffer_t& buffer = (it->second.first);
if (buffer.empty()) {
return foundPoint;
}
//TimePointPair_t tpPair = buffer.front();
foundPoint = buffer.front(); // Point(tpPair.first, tpPair.second.first);
}
return foundPoint;
}
Point BufferPointRecord::lastPoint(const string& id) {
Point foundPoint;
KeyedBufferMutexMap_t::iterator it = _keyedBufferMutex.find(id);
if (it != _keyedBufferMutex.end()) {
// get the constituents
//boost::signals2::mutex *mutex = (it->second.second.get());
PointBuffer_t& buffer = (it->second.first);
if (buffer.empty()) {
return foundPoint;
}
//TimePointPair_t tpPair = buffer.back();
foundPoint = buffer.back(); // Point(tpPair.first, tpPair.second.first);
}
return foundPoint;
}
PointRecord::time_pair_t BufferPointRecord::range(const string& id) {
return make_pair(BufferPointRecord::firstPoint(id).time, BufferPointRecord::lastPoint(id).time);
}
|
066de6c35b6e384b8e04786b06b7c4625f3c2962
|
799f7938856a320423625c6a6a3881eacdd0e039
|
/lldb/source/Plugins/Trace/intel-pt/TraceIntelPTSessionFileParser.h
|
6a896de09d000e8f0027f11ffc80ddc286e84249
|
[
"NCSA",
"Apache-2.0",
"LLVM-exception"
] |
permissive
|
shabalind/llvm-project
|
3b90d1d8f140efe1b4f32390f68218c02c95d474
|
d06e94031bcdfa43512bf7b0cdfd4b4bad3ca4e1
|
refs/heads/main
| 2022-10-18T04:13:17.818838
| 2021-02-04T13:06:43
| 2021-02-04T14:23:33
| 237,532,515
| 0
| 0
|
Apache-2.0
| 2020-01-31T23:17:24
| 2020-01-31T23:17:23
| null |
UTF-8
|
C++
| false
| false
| 2,636
|
h
|
TraceIntelPTSessionFileParser.h
|
//===-- TraceIntelPTSessionFileParser.h -----------------------*- C++ //-*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLDB_SOURCE_PLUGINS_TRACE_INTEL_PT_TRACEINTELPTSESSIONFILEPARSER_H
#define LLDB_SOURCE_PLUGINS_TRACE_INTEL_PT_TRACEINTELPTSESSIONFILEPARSER_H
#include "TraceIntelPT.h"
#include "lldb/Target/TraceSessionFileParser.h"
namespace lldb_private {
namespace trace_intel_pt {
class TraceIntelPT;
class TraceIntelPTSessionFileParser : public TraceSessionFileParser {
public:
struct JSONPTCPU {
std::string vendor;
int64_t family;
int64_t model;
int64_t stepping;
};
struct JSONTraceIntelPTSettings
: TraceSessionFileParser::JSONTracePluginSettings {
JSONPTCPU pt_cpu;
};
/// See \a TraceSessionFileParser::TraceSessionFileParser for the description
/// of these fields.
TraceIntelPTSessionFileParser(Debugger &debugger,
const llvm::json::Value &trace_session_file,
llvm::StringRef session_file_dir)
: TraceSessionFileParser(debugger, session_file_dir, GetSchema()),
m_trace_session_file(trace_session_file) {}
/// \return
/// The JSON schema for the session data.
static llvm::StringRef GetSchema();
/// Parse the structured data trace session and create the corresponding \a
/// Target objects. In case of an error, no targets are created.
///
/// \return
/// A \a lldb::TraceSP instance with the trace session data. In case of
/// errors, return a null pointer.
llvm::Expected<lldb::TraceSP> Parse();
lldb::TraceSP
CreateTraceIntelPTInstance(const pt_cpu &pt_cpu,
std::vector<ParsedProcess> &parsed_processes);
private:
pt_cpu ParsePTCPU(const JSONPTCPU &pt_cpu);
const llvm::json::Value &m_trace_session_file;
};
} // namespace trace_intel_pt
} // namespace lldb_private
namespace llvm {
namespace json {
bool fromJSON(
const Value &value,
lldb_private::trace_intel_pt::TraceIntelPTSessionFileParser::JSONPTCPU
&pt_cpu,
Path path);
bool fromJSON(const Value &value,
lldb_private::trace_intel_pt::TraceIntelPTSessionFileParser::
JSONTraceIntelPTSettings &plugin_settings,
Path path);
} // namespace json
} // namespace llvm
#endif // LLDB_SOURCE_PLUGINS_TRACE_INTEL_PT_TRACEINTELPTSESSIONFILEPARSER_H
|
9d193be98fe284fad36ca97aa2eaf16be5dbdf23
|
2cc43d7b84767459c87878c500327802c08aff60
|
/src/GraphUtils.cpp
|
a371b0a606ddcd22917a27125c192641aa154f93
|
[] |
no_license
|
tyler-lovelace1/rCausalMGM
|
104cd8e1d5e351904dce495231619bc5afc6c249
|
dfb7a3c99c1520c3cac83baeaba82a78431a3400
|
refs/heads/master
| 2023-02-14T18:58:45.992657
| 2023-02-03T20:45:52
| 2023-02-03T20:45:52
| 235,115,115
| 3
| 6
| null | 2021-04-13T16:35:13
| 2020-01-20T14:04:45
|
C++
|
UTF-8
|
C++
| false
| false
| 14,869
|
cpp
|
GraphUtils.cpp
|
// [[Rcpp::depends(BH)]]
#include "GraphUtils.hpp"
std::vector<std::string> GraphUtils::splitString(std::string s, const std::string& delim) {
std::vector<std::string> tokens;
std::size_t find;
while ((find = s.find(delim)) != std::string::npos) {
std::string token = s.substr(0, find);
tokens.push_back(token);
s.erase(0, find + delim.length());
}
tokens.push_back(s);
return tokens;
}
/**
* Constructs a list of nodes from the given <code>nodes</code> list at the
* given indices in that list.
*
* @param indices The indices of the desired nodes in <code>nodes</code>.
* @param nodes The list of nodes from which we select a sublist.
* @return the The sublist selected.
*/
std::vector<Node> GraphUtils::asList(std::vector<int>& indices, std::vector<Node>& nodes) {
std::vector<Node> list;
for (int i : indices) {
list.push_back(nodes[i]);
}
return list;
}
std::unordered_set<Node> GraphUtils::asSet(std::vector<int>& indices, std::vector<Node>& nodes) {
std::unordered_set<Node> set;
for (int i : indices) {
set.insert(nodes[i]);
}
return set;
}
EdgeListGraph GraphUtils::completeGraph(EdgeListGraph& graph) {
EdgeListGraph graph2(graph.getNodes());
graph2.removeEdges();
std::vector<Node> nodes = graph2.getNodes();
for (int i = 0; i < nodes.size(); i++) {
for (int j = i+1; j < nodes.size(); j++) {
Node node1 = nodes[i];
Node node2 = nodes[j];
graph2.addUndirectedEdge(node1, node2);
}
}
return graph2;
}
EdgeListGraph GraphUtils::undirectedGraph(EdgeListGraph& graph) {
EdgeListGraph graph2(graph.getNodes());
for (Edge edge : graph.getEdges()) {
graph2.addUndirectedEdge(edge.getNode1(), edge.getNode2());
}
return graph2;
}
std::unordered_set<Node> GraphUtils::possibleDsep(Node x, Node y, EdgeListGraph& graph, int maxPathLength) {
std::unordered_set<Node> dsep;
std::queue<boost::optional<std::pair<Node,Node>>> Q;
std::unordered_set<std::pair<Node,Node>, boost::hash<std::pair<Node, Node> > > V;
std::unordered_map<Node, std::vector<Node>> previous;
std::vector<Node> null_vector = {};
previous.insert(std::pair<Node, std::vector<Node>>(x, null_vector));
boost::optional<std::pair<Node,Node>> e = {};
int distance = 0;
for (Node b : graph.getAdjacentNodes(x)) {
if (b == y) {
continue;
}
boost::optional<std::pair<Node,Node> > edge = std::pair<Node,Node>(x, b);
if (!e) {
e = edge;
}
Q.push(edge);
V.insert(*edge);
addToList(previous, b, x);
dsep.insert(b);
}
while (!Q.empty()) {
boost::optional<std::pair<Node, Node> > t = Q.front();
Q.pop();
if (e == t) {
e = {};
distance++;
if (distance > 0 && distance > (maxPathLength == -1 ? 1000 : maxPathLength)) {
break;
}
}
Node a = t->first;
Node b = t->second;
if (existOnePathWithPossibleParents(previous, b, x, b, graph)) {
dsep.insert(b);
}
for (Node c : graph.getAdjacentNodes(b)) {
if (c == a) {
continue;
}
if (c == x) {
continue;
}
if (c == y) {
continue;
}
addToList(previous, b, c);
if (graph.isDefCollider(a, b, c) || graph.isAdjacentTo(a, c)) {
boost::optional<std::pair<Node, Node> > u = std::pair<Node, Node>(a,c);
if (std::count(V.begin(), V.end(), *u) != 0) {
continue;
}
V.insert(*u);
Q.push(u);
if (!e) {
e = u;
}
}
}
}
dsep.erase(x);
dsep.erase(y);
return dsep;
}
void GraphUtils::addToList(std::unordered_map<Node, std::vector<Node>> previous, Node b, Node c) {
std::vector<Node> list = previous[c];
if (list.empty()) {
std::vector<Node> null_list = {};
list = null_list;
}
list.push_back(b);
}
bool GraphUtils::existOnePathWithPossibleParents(std::unordered_map<Node, std::vector<Node>> previous, Node w, Node x, Node b, EdgeListGraph& graph) {
if (w == x) {
return true;
}
const std::vector<Node> p = previous[w];
if (p.empty()) {
return false;
}
for (Node r : p) {
if (r == b || r == x) {
continue;
}
if ((existsSemidirectedPath(r, x, graph))
|| existsSemidirectedPath(r, b, graph)) {
if (existOnePathWithPossibleParents(previous, r, x, b, graph)) {
return true;
}
}
}
return false;
}
bool GraphUtils::existsSemidirectedPath(Node from, Node to, EdgeListGraph& G) {
std::queue<Node> Q;
std::unordered_set<Node> V;
Q.push(from);
V.insert(from);
while (!Q.empty()) {
Node t = Q.front();
Q.pop();
if (t == to) {
return true;
}
for (Node u : G.getAdjacentNodes(t)) {
Edge edge = G.getEdge(t, u);
Node c = Edge::traverseSemiDirected(t, edge);
if (c.isNull()) {
continue;
}
if (std::count(V.begin(), V.end(), c) != 0) {
continue;
}
V.insert(c);
Q.push(c);
}
}
return false;
}
std::vector<Node> GraphUtils::getSepset(const Node& x, const Node& y, EdgeListGraph& graph) {
if (!x.isObserved())
throw std::runtime_error(x.getName() + " is an unobserved variable");
if (!y.isObserved())
throw std::runtime_error(y.getName() + " is an unobserved variable");
std::vector<Node> sepset = { Node() };
if (x == y) return sepset;
std::vector<Node> z, oldZ;
std::set<Node> path;
std::set<Triple> colliders;
bool first = true;
while (first || z != oldZ) {
first = false;
oldZ = z;
path = { x };
colliders = {};
for (const Node& b : graph.getAdjacentNodes(x)) {
if (sepsetPathFound(x, b, y, path, z, colliders, graph)) {
return sepset;
}
}
// Rcpp::Rcout << "z for " << x << " and " << y << ":\n ";
// for (const Node& node : z) {
// Rcpp::Rcout << node.getName() << " ";
// }
// Rcpp::Rcout << std::endl;
}
// // std::unordered_set<Triple> colliders;
// std::list<Node> path;
// std::vector<Node> z, oldZ;
// std::set<std::pair<std::list<Node>,std::vector<Node>>> visited;
// std::stack<Node> nodeStack;
// std::stack<std::list<Node>> pathStack;
// std::stack<std::vector<Node>> sepsetStack;
// // bool first = true;
// // while (z != oldZ || first) {
// // oldZ = z;
// // first = false;
// // visited.clear();
// for (Node b : graph.getAdjacentNodes(x)) {
// path = {x};
// nodeStack.push(b);
// pathStack.push(path);
// sepsetStack.push(z);
// visited.insert(std::pair<std::list<Node>,std::vector<Node>>(path, z));
// }
// while (!nodeStack.empty()) {
// Node b = nodeStack.top();
// nodeStack.pop();
// path = pathStack.top();
// pathStack.pop();
// z = sepsetStack.top();
// sepsetStack.pop();
// Node a = path.back();
// // Rcpp::Rcout << "nodeStack size = " << nodeStack.size()
// // << "\nNode " << b << std::endl;
// if (std::find(path.begin(), path.end(), b) != path.end()) continue;
// path.push_back(b);
// if (visited.count(std::pair<std::list<Node>,std::vector<Node>>(path, z)) > 0)
// continue;
// visited.insert(std::pair<std::list<Node>,std::vector<Node>>(path, z));
// if (b == y) {
// Rcpp::Rcout << "Node y reached" << std::endl;
// break;
// }
// std::vector<Node> passNodes = getPassNodes(a, b, z, graph);
// // Rcpp::Rcout << "Pass Nodes from " << x << " to " << y << " with z = [ ";
// // for (const Node& node : z) {
// // Rcpp::Rcout << node.getName() << " ";
// // }
// // Rcpp::Rcout << "] :\n ";
// // for (const Node& node : passNodes) {
// // Rcpp::Rcout << node.getName() << " ";
// // }
// if (!b.isObserved() || std::find(z.begin(), z.end(), b) != z.end()) {
// for (const Node& c : passNodes) {
// nodeStack.push(c);
// pathStack.push(path);
// sepsetStack.push(z);
// }
// } else {
// for (const Node& c : passNodes) {
// nodeStack.push(c);
// pathStack.push(path);
// sepsetStack.push(z);
// }
// path.pop_back();
// z.push_back(b);
// passNodes = getPassNodes(a, b, z, graph);
// // Rcpp::Rcout << "Pass Nodes from " << x << " to " << y << " with z = [ ";
// // for (const Node& node : z) {
// // Rcpp::Rcout << node.getName() << " ";
// // }
// // Rcpp::Rcout << "] :\n ";
// // for (const Node& node : passNodes) {
// // Rcpp::Rcout << node.getName() << " ";
// // }
// for (const Node& c : passNodes) {
// nodeStack.push(c);
// pathStack.push(path);
// sepsetStack.push(z);
// }
// }
// }
// if (path.back() == y)
// sepset = z;
// }
// Rcpp::Rcout << "Final z for " << x << " and " << y << ":\n ";
// for (const Node& node : z) {
// Rcpp::Rcout << node.getName() << " ";
// }
// Rcpp::Rcout << std::endl;
// if (path.count(y))
// sepset = z;
return z;
}
bool GraphUtils::sepsetPathFound(const Node& a, const Node& b, const Node& y,
std::set<Node>& path, std::vector<Node>& z,
std::set<Triple>& colliders, EdgeListGraph& graph) {
if (b==y) return true;
if (path.count(b)) return false;
if (path.size() > 10) return false;
path.insert(b);
std::vector<Node> passNodes;
if (!b.isObserved() || std::find(z.begin(), z.end(), b) != z.end()) {
passNodes = getPassNodes(a, b, z, graph);
for (const Node& c : passNodes) {
if (sepsetPathFound(b, c, y, path, z, colliders, graph)) {
path.erase(b);
return true;
}
}
path.erase(b);
return false;
} else {
bool found1 = false;
std::set<Triple> colliders1;
passNodes = getPassNodes(a, b, z, graph);
for (const Node& c : passNodes) {
if (sepsetPathFound(b, c, y, path, z, colliders1, graph)) {
found1 = true;
break;
}
}
if (!found1) {
path.erase(b);
colliders.insert(colliders1.begin(), colliders1.end());
return false;
}
z.push_back(b);
bool found2 = false;
std::set<Triple> colliders2;
passNodes = getPassNodes(a, b, z, graph);
for (const Node& c : passNodes) {
if (sepsetPathFound(b, c, y, path, z, colliders2, graph)) {
found2 = true;
break;
}
}
if (!found2) {
path.erase(b);
colliders.insert(colliders2.begin(), colliders2.end());
return false;
}
path.erase(b);
z.pop_back();
return true;
}
}
std::vector<Node> GraphUtils::getPassNodes(const Node& a, const Node& b,
std::vector<Node>& z,
EdgeListGraph& graph) {
std::vector<Node> passNodes;
for (Node c : graph.getAdjacentNodes(b)) {
if (a == c) continue;
if (reachable(a, b, c, z, graph)) {
passNodes.push_back(c);
}
}
return passNodes;
}
bool GraphUtils::reachable(const Node& a, const Node& b, const Node& c,
std::vector<Node>& z,
EdgeListGraph& graph) {
bool collider = graph.isDefCollider(a,b,c);
if (!collider && std::find(z.begin(), z.end(), b) == z.end()) {
return true;
}
bool ancestor = isAncestor(b, z, graph);
// Rcpp::Rcout << "Is " << b << " an ancestor of [ ";
// for (const Node& node : z) {
// Rcpp::Rcout << node.getName() << " ";
// }
// Rcpp::Rcout << "] : " << ancestor << std::endl;
return collider && ancestor;
}
bool GraphUtils::isAncestor(const Node& b, std::vector<Node>& z, EdgeListGraph& graph) {
if (std::find(z.begin(), z.end(), b) != z.end()) return true;
std::queue<Node> nodeQueue;
std::unordered_set<Node> visited;
for (const Node& node : z) {
nodeQueue.push(node);
visited.insert(node);
}
while (!nodeQueue.empty()) {
Node t = nodeQueue.front();
nodeQueue.pop();
if (t==b) return true;
for (Node c : graph.getParents(t)) {
if (visited.count(c) == 0) {
nodeQueue.push(c);
visited.insert(c);
}
}
}
return false;
}
std::vector<Node> GraphUtils::getInducingPath(const Node& x, const Node& y,
EdgeListGraph& graph) {
if (!x.isObserved())
throw std::runtime_error(x.getName() + " is an unobserved variable");
if (!y.isObserved())
throw std::runtime_error(y.getName() + " is an unobserved variable");
std::vector<Node> inducingPath = {};
if (x == y) return inducingPath;
if (graph.getAdjacentNodes(x).size() == 0) return inducingPath;
if (graph.getAdjacentNodes(y).size() == 0) return inducingPath;
std::list<Node> path;
std::set<std::list<Node>> visited;
std::stack<Node> nodeStack;
std::stack<std::list<Node>> pathStack;
for (Node b : graph.getAdjacentNodes(x)) {
path = {x};
nodeStack.push(b);
pathStack.push(path);
visited.insert(path);
}
while (!nodeStack.empty()) {
Node b = nodeStack.top();
nodeStack.pop();
path = pathStack.top();
pathStack.pop();
Node a = path.back();
path.push_back(b);
if (visited.count(path) > 0) continue;
visited.insert(path);
if (b == y) break;
for (Node c : graph.getAdjacentNodes(b)) {
if (c == a) continue;
if (b.isObserved()) {
if (!graph.isDefCollider(a, b, c)) {
continue;
}
}
if (graph.isDefCollider(a, b, c)) {
if (!(graph.isAncestorOf(b, x) || graph.isAncestorOf(b, y))) {
continue;
}
}
if (std::find(path.begin(), path.end(), c) != path.end()) continue;
nodeStack.push(c);
pathStack.push(path);
}
// path.pop_back();
}
if (path.back() == y)
inducingPath = std::vector<Node>(path.begin(), path.end());
return inducingPath;
}
|
116a06e138070190c2eefd3f777160f7ffe74f4d
|
9d364070c646239b2efad7abbab58f4ad602ef7b
|
/platform/external/chromium_org/chrome/browser/ui/app_list/app_list_shower_views.h
|
355e1df6a0680b9b16b7043a51621884d8c90b38
|
[
"BSD-3-Clause"
] |
permissive
|
denix123/a32_ul
|
4ffe304b13c1266b6c7409d790979eb8e3b0379c
|
b2fd25640704f37d5248da9cc147ed267d4771c2
|
refs/heads/master
| 2021-01-17T20:21:17.196296
| 2016-08-16T04:30:53
| 2016-08-16T04:30:53
| 65,786,970
| 0
| 2
| null | 2020-03-06T22:00:52
| 2016-08-16T04:15:54
| null |
UTF-8
|
C++
| false
| false
| 1,575
|
h
|
app_list_shower_views.h
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_APP_LIST_APP_LIST_SHOWER_VIEWS_H_
#define CHROME_BROWSER_UI_APP_LIST_APP_LIST_SHOWER_VIEWS_H_
#include "base/memory/scoped_ptr.h"
#include "ui/gfx/native_widget_types.h"
namespace app_list {
class AppListView;
}
class AppListShowerDelegate;
class AppListShowerUnitTest;
class Profile;
class ScopedKeepAlive;
class AppListShower {
public:
explicit AppListShower(AppListShowerDelegate* delegate);
virtual ~AppListShower();
void ShowForProfile(Profile* requested_profile);
gfx::NativeWindow GetWindow();
app_list::AppListView* app_list() { return app_list_; }
Profile* profile() const { return profile_; }
void CreateViewForProfile(Profile* requested_profile);
void DismissAppList();
virtual void HandleViewBeingDestroyed();
virtual bool IsAppListVisible() const;
void WarmupForProfile(Profile* profile);
virtual bool HasView() const;
protected:
virtual app_list::AppListView* MakeViewForCurrentProfile();
virtual void UpdateViewForNewProfile();
virtual void Show();
virtual void Hide();
private:
friend class ::AppListShowerUnitTest;
void ResetKeepAliveSoon();
void ResetKeepAlive();
AppListShowerDelegate* delegate_;
Profile* profile_;
app_list::AppListView* app_list_;
scoped_ptr<ScopedKeepAlive> keep_alive_;
bool window_icon_updated_;
DISALLOW_COPY_AND_ASSIGN(AppListShower);
};
#endif
|
90f0fd064dac9138f47c0c6fe642158d835e252e
|
911e3637b46b08bf82607fe46ff783f2cd9fe3a6
|
/2020/Round-E/1-Longest-Arithmetic.cpp
|
f8c6713f0a70b756d0d1e1217a23f3d4feaec5df
|
[] |
no_license
|
KHvic/Google-Kickstart-Solution
|
10f26938d7b657a5ab250826bcddfbcd5f1f4e33
|
a3adfd4b2dcc6261b36775af9e021347c4cbbf83
|
refs/heads/master
| 2021-07-17T20:45:31.691997
| 2021-03-21T15:48:44
| 2021-03-21T15:48:44
| 243,707,477
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 755
|
cpp
|
1-Longest-Arithmetic.cpp
|
#include <bits/stdc++.h>
using namespace std;
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);
#define ll long long
int main(){
fastio
int tc,n;
cin >> tc;
for(int t=1;t<=tc;t++) {
cin >> n;
int res = 2;
vector<ll> vals(n);
for(int i=0;i<n;i++) cin >> vals[i];
vector<ll> diff;
for(int i=1;i<n;i++) {
ll d = vals[i] - vals[i-1];
diff.push_back(d);
}
// groupby
int idx = 0;
while(idx<diff.size()) {
int j=idx;
while(j+1<diff.size() && diff[j+1] == diff[idx]) j++;
res = max(res, j-idx+2);
idx = j+1;
}
cout << "Case #"<<t << ": " << res << "\n";
}
}
|
982d1f08fd630efccba6d024ae2fff39ef027982
|
79ca1707e6b3e22262a9710d74e7de7368525792
|
/Darkness of Planet/Darkness of Planet/Darkness of Planet/cMainGame.cpp
|
1adf0cbf1a40673bf56a20e5b30fb45b183cc310
|
[] |
no_license
|
ggondols/TeamOfEalryAccess
|
0645b419b649c075ed03881921bf5cefe754680d
|
4219a2a0ae9644069e0d6743961a9987bfb17957
|
refs/heads/master
| 2021-01-21T12:16:30.626470
| 2017-10-15T08:52:09
| 2017-10-15T08:52:09
| 102,056,526
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 2,686
|
cpp
|
cMainGame.cpp
|
#include "stdafx.h"
#include "cMainGame.h"
#include "cJustTestScene.h"
#include "TeicJustTestScene.h"
#include "LDYcJustTestScene.h"
#include "LJHcJustTestScene.h"
#include "HankcJustTestScene.h"
#include "cTestMain.h"
#include "LoadingScene.h"
#include "HankcDefferedRenderTest.h"
#include "DarknessofPlanetMainScene.h"
#include "StartScene.h"
#include "EndingScene.h"
cMainGame::cMainGame()
{
}
cMainGame::~cMainGame()
{
}
HRESULT cMainGame::Setup()
{
cGameNode::Setup(true);
//씬 생성하고
SCENEMANAGER->addScene("cJustTestScene", new cJustTestScene);
SCENEMANAGER->addScene("TeicJustTestScene", new TeicJustTestScene);
SCENEMANAGER->addScene("LDYcJustTestScene", new LDYcJustTestScene);
SCENEMANAGER->addScene("LJHcJustTestScene", new LJHcJustTestScene);
SCENEMANAGER->addScene("HankcDefferedRederTest", new HankcDefferedRenderTest);
SCENEMANAGER->addScene("cTestMain", new cTestMain);
SCENEMANAGER->addScene("DarknessofPlanetMainScene", new DarknessofPlanetMainScene);
SCENEMANAGER->addScene("LoadingScene", new LoadingScene);
SCENEMANAGER->addScene("StartScene", new StartScene);
SCENEMANAGER->addScene("EndingScene", new EndingScene);
//////////////////커밋 전에 항상 저스트 테스트 씬으로 바꾸세요~~
//여기서 씬 교체
SCENEMANAGER->changeScene("LoadingScene");
GETDEVICE->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
GETDEVICE->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
GETDEVICE->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
GETDEVICE->SetRenderState(D3DRS_ALPHABLENDENABLE, true);
GETDEVICE->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
GETDEVICE->SetRenderState(D3DRS_ALPHAREF, 0);
GETDEVICE->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER);
return S_OK;
}
void cMainGame::Release()
{
cGameNode::Release();
}
void cMainGame::Update()
{
cGameNode::Update();
if (KEYMANAGER->isToggleKey('0'))
{
TIMEMANAGER->SetShowFrame(true);
}
else
{
TIMEMANAGER->SetShowFrame(false);
}
/*if (KEYMANAGER->isOnceKeyDown('1'))
{
SCENEMANAGER->changeScene("HankcDefferedRenderTest");
}
if (KEYMANAGER->isOnceKeyDown('2'))
{
SCENEMANAGER->changeScene("LDYcJustTestScene");
}
if (KEYMANAGER->isOnceKeyDown('3'))
{
SCENEMANAGER->changeScene("LJHcJustTestScene");
}
if (KEYMANAGER->isOnceKeyDown('4'))
{
SCENEMANAGER->changeScene("TeicJustTestScene");
}*/
SCENEMANAGER->Update();
//AUTORELEASEPOOL->Drain();
}
void cMainGame::Render()
{
GETDEVICE->Clear(NULL, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(47, 121, 112), 1.0f, 1);
GETDEVICE->BeginScene();
SCENEMANAGER->Render();
TIMEMANAGER->Render();
GETDEVICE->EndScene();
GETDEVICE->Present(0, 0, 0, 0);
}
|
ac4b2a9c77544b6084ed82258c0ed839b112a36b
|
2aa7856793719892acaea34138f26f11f5f6a1cd
|
/protocol/TeepAgentLib/TeepAgent.cpp
|
bf00f839f3b47bdbc0d5e85a652f019be71dfb1d
|
[
"MIT"
] |
permissive
|
zcf1810/OTrP
|
554153eb8bc522a204724e95ac3d7cd3e6be6c4e
|
96e6dc21904470c764f3396fbcc366d8525311ef
|
refs/heads/master
| 2023-01-30T07:40:34.540530
| 2023-01-20T04:49:52
| 2023-01-20T04:49:52
| 175,146,489
| 1
| 0
| null | 2019-03-12T06:09:48
| 2019-03-12T06:09:43
|
C++
|
UTF-8
|
C++
| false
| false
| 39,465
|
cpp
|
TeepAgent.cpp
|
// Copyright (c) TEEP contributors
// SPDX-License-Identifier: MIT
#include <dirent.h>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <string.h>
#include <string>
#include "TrustedComponent.h"
#include "teep_protocol.h"
#include "TeepAgentLib.h"
#include "openssl/bio.h"
#include "openssl/evp.h"
#include "openssl/x509.h"
#include "qcbor/qcbor_decode.h"
#include "qcbor/qcbor_encode.h"
#include "t_cose/t_cose_common.h"
#include "t_cose/t_cose_sign1_verify.h"
#include "TeepDeviceEcallHandler.h"
#include "SuitParser.h"
#include "AgentKeys.h"
static teep_error_code_t TeepAgentComposeError(UsefulBufC token, teep_error_code_t errorCode, const std::string& errorMessage, UsefulBufC* encoded);
// List of requested Trusted Components.
TrustedComponent* g_RequestedComponentList = nullptr;
// List of installed Trusted Components.
TrustedComponent* g_InstalledComponentList = nullptr;
// List of unneeded Trusted Components.
TrustedComponent* g_UnneededComponentList = nullptr;
teep_error_code_t
TeepAgentSignMessage(
_In_ const UsefulBufC* unsignedMessage,
_In_ UsefulBuf signedMessageBuffer,
_Out_ UsefulBufC* signedMessage)
{
struct t_cose_key key_pair;
teep_signature_kind_t signatureKind;
TeepAgentGetSigningKeyPair(&key_pair, &signatureKind);
return teep_sign1_cbor_message(&key_pair, unsignedMessage, signedMessageBuffer, signatureKind, signedMessage);
}
// Process a transport error.
teep_error_code_t TeepAgentProcessError(_In_ void* sessionHandle)
{
(void)sessionHandle;
return TEEP_ERR_TEMPORARY_ERROR;
}
teep_error_code_t TeepAgentRequestPolicyCheck(_In_z_ const char* tamUri)
{
teep_error_code_t err = TEEP_ERR_SUCCESS;
// TODO: we may want to modify the TAM URI here.
// TODO: see whether we already have a TAM cert we trust.
// For now we skip this step and say we don't.
bool haveTrustedTamCert = false;
if (!haveTrustedTamCert) {
// Pass back a TAM URI with no buffer.
TeepLogMessage("Sending an empty message...\n");
const char* acceptMediaType = TEEP_CBOR_MEDIA_TYPE;
teep_error_code_t error = TeepAgentConnect(tamUri, acceptMediaType);
if (error != TEEP_ERR_SUCCESS) {
return error;
}
} else {
// TODO: implement going on to the next message.
TEEP_ASSERT(false);
}
return err;
}
static void AddComponentIdToMap(_Inout_ QCBOREncodeContext* context, _In_ TrustedComponent* tc)
{
QCBOREncode_OpenArrayInMapN(context, TEEP_LABEL_COMPONENT_ID);
{
UsefulBuf tc_id = UsefulBuf_FROM_BYTE_ARRAY(tc->ID.b);
QCBOREncode_AddBytes(context, UsefulBuf_Const(tc_id));
}
QCBOREncode_CloseArray(context);
}
// Parse QueryRequest and compose QueryResponse.
static teep_error_code_t TeepAgentComposeQueryResponse(_Inout_ QCBORDecodeContext* decodeContext, _Out_ UsefulBufC* encodedResponse, _Out_ UsefulBufC* errorResponse)
{
UsefulBufC challenge = NULLUsefulBufC;
*encodedResponse = NULLUsefulBufC;
UsefulBufC errorToken = NULLUsefulBufC;
std::ostringstream errorMessage;
size_t maxBufferLength = 4096;
char* rawBuffer = (char*)malloc(maxBufferLength);
if (rawBuffer == nullptr) {
return TeepAgentComposeError(errorToken, TEEP_ERR_TEMPORARY_ERROR, "Out of memory", errorResponse);
}
QCBOREncodeContext context;
UsefulBuf buffer{ rawBuffer, maxBufferLength };
QCBOREncode_Init(&context, buffer);
QCBOREncode_OpenArray(&context);
{
// Add TYPE.
QCBOREncode_AddInt64(&context, TEEP_MESSAGE_QUERY_RESPONSE);
QCBORItem item;
// Parse the QueryRequest options map.
QCBORDecode_GetNext(decodeContext, &item);
if (item.uDataType != QCBOR_TYPE_MAP) {
REPORT_TYPE_ERROR(errorMessage, "options", QCBOR_TYPE_MAP, item);
return TeepAgentComposeError(errorToken, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), errorResponse);
}
QCBOREncode_OpenMap(&context);
{
uint16_t mapEntryCount = item.val.uCount;
for (uint16_t mapIndex = 0; mapIndex < mapEntryCount; mapIndex++) {
QCBORDecode_GetNext(decodeContext, &item);
if (item.uLabelType != QCBOR_TYPE_INT64) {
return TEEP_ERR_PERMANENT_ERROR;
}
switch (item.label.int64) {
case TEEP_LABEL_TOKEN:
// Copy token from QueryRequest into QueryResponse.
if (item.uDataType != QCBOR_TYPE_BYTE_STRING) {
REPORT_TYPE_ERROR(errorMessage, "token", QCBOR_TYPE_BYTE_STRING, item);
return TeepAgentComposeError(errorToken, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), errorResponse);
}
errorToken = item.val.string;
QCBOREncode_AddBytesToMapN(&context, TEEP_LABEL_TOKEN, item.val.string);
break;
case TEEP_LABEL_SUPPORTED_FRESHNESS_MECHANISMS:
{
if (item.uDataType != QCBOR_TYPE_ARRAY) {
REPORT_TYPE_ERROR(errorMessage, "supported-freshness-mechanisms", QCBOR_TYPE_ARRAY, item);
return TeepAgentComposeError(errorToken, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), errorResponse);
}
uint16_t arrayEntryCount = item.val.uCount;
bool isNonceSupported = false;
for (uint16_t arrayIndex = 0; arrayIndex < arrayEntryCount; arrayIndex++) {
QCBORDecode_GetNext(decodeContext, &item);
if (item.uDataType != QCBOR_TYPE_INT64) {
REPORT_TYPE_ERROR(errorMessage, "freshness-mechanism", QCBOR_TYPE_INT64, item);
return TeepAgentComposeError(errorToken, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), errorResponse);
}
if (item.val.int64 == TEEP_FRESHNESS_MECHANISM_NONCE) {
isNonceSupported = true;
TeepLogMessage("Choosing Nonce freshness mechanism\n");
}
}
if (!isNonceSupported) {
errorMessage << "No freshness mechanism in common, TEEP Agent only supports Nonce" << std::endl;
return TeepAgentComposeError(errorToken, TEEP_ERR_UNSUPPORTED_FRESHNESS_MECHANISMS, errorMessage.str(), errorResponse);
}
break;
}
case TEEP_LABEL_CHALLENGE:
// Save challenge for use with attestation call.
challenge = item.val.string;
break;
case TEEP_LABEL_VERSIONS:
{
if (item.uDataType != QCBOR_TYPE_ARRAY) {
REPORT_TYPE_ERROR(errorMessage, "versions", QCBOR_TYPE_ARRAY, item);
return TeepAgentComposeError(errorToken, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), errorResponse);
}
uint16_t arrayEntryCount = item.val.uCount;
bool isVersion0Supported = false;
for (uint16_t arrayIndex = 0; arrayIndex < arrayEntryCount; arrayIndex++) {
QCBORDecode_GetNext(decodeContext, &item);
if (item.uDataType != QCBOR_TYPE_INT64) {
REPORT_TYPE_ERROR(errorMessage, "freshness-mechanism", QCBOR_TYPE_INT64, item);
return TeepAgentComposeError(errorToken, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), errorResponse);
}
if (item.val.int64 == 0) {
isVersion0Supported = true;
}
}
if (!isVersion0Supported) {
errorMessage << "No TEEP version in common, TEEP Agent only supports version 0" << std::endl;
return TeepAgentComposeError(errorToken, TEEP_ERR_UNSUPPORTED_MSG_VERSION, errorMessage.str(), errorResponse);
}
break;
}
}
}
// Parse the supported-cipher-suites.
{
bool found = false;
QCBORDecode_GetNext(decodeContext, &item);
if (item.uDataType != QCBOR_TYPE_ARRAY) {
REPORT_TYPE_ERROR(errorMessage, "supported-cipher-suites", QCBOR_TYPE_ARRAY, item);
return TeepAgentComposeError(errorToken, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), errorResponse);
}
uint16_t cipherSuiteCount = item.val.uCount;
for (uint16_t cipherSuiteIndex = 0; cipherSuiteIndex < cipherSuiteCount; cipherSuiteIndex++) {
// Parse an array of cipher suite operations.
QCBORDecode_GetNext(decodeContext, &item);
if (item.uDataType != QCBOR_TYPE_ARRAY) {
REPORT_TYPE_ERROR(errorMessage, "cipher suite operations", QCBOR_TYPE_ARRAY, item);
return TeepAgentComposeError(errorToken, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), errorResponse);
}
uint16_t operationCount = item.val.uCount;
for (uint16_t operationIndex = 0; operationIndex < operationCount; operationIndex++) {
// Parse an array that specifies an operation.
QCBORDecode_GetNext(decodeContext, &item);
if (item.uDataType != QCBOR_TYPE_ARRAY || item.val.uCount != 2) {
REPORT_TYPE_ERROR(errorMessage, "cipher suite operation pair", QCBOR_TYPE_ARRAY, item);
return TeepAgentComposeError(errorToken, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), errorResponse);
}
QCBORDecode_GetNext(decodeContext, &item);
if (item.uDataType != QCBOR_TYPE_INT64) {
REPORT_TYPE_ERROR(errorMessage, "cose type", QCBOR_TYPE_INT64, item);
return TeepAgentComposeError(errorToken, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), errorResponse);
}
int64_t coseType = item.val.int64;
QCBORDecode_GetNext(decodeContext, &item);
if (item.uDataType != QCBOR_TYPE_INT64) {
REPORT_TYPE_ERROR(errorMessage, "cose algorithm", QCBOR_TYPE_INT64, item);
return TeepAgentComposeError(errorToken, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), errorResponse);
}
int64_t coseAlgorithm = item.val.int64;
if (coseType == CBOR_TAG_COSE_SIGN1 &&
coseAlgorithm == T_COSE_ALGORITHM_ES256) {
found = true;
}
}
}
if (!found) {
// TODO: include teep-cipher-suite-sign1-es256 or eddsa depending on configuration.
return TEEP_ERR_UNSUPPORTED_CIPHER_SUITES;
}
// Add selected-cipher-suite to the QueryResponse.
QCBOREncode_OpenArrayInMapN(&context, TEEP_LABEL_SELECTED_CIPHER_SUITE);
{
// Add teep-operation-sign1-es256.
QCBOREncode_OpenArray(&context);
{
QCBOREncode_AddInt64(&context, CBOR_TAG_COSE_SIGN1);
QCBOREncode_AddInt64(&context, T_COSE_ALGORITHM_ES256);
}
QCBOREncode_CloseArray(&context);
}
QCBOREncode_CloseArray(&context);
}
// Parse the data-item-requested.
QCBORDecode_GetNext(decodeContext, &item);
if (item.uDataType != QCBOR_TYPE_INT64) {
REPORT_TYPE_ERROR(errorMessage, "data-item-requested", QCBOR_TYPE_INT64, item);
return TeepAgentComposeError(errorToken, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), errorResponse);
}
if (item.val.int64 & TEEP_ATTESTATION) {
// Add evidence.
// TODO(issue #9): get actual evidence via ctoken library or OE.
QCBOREncode_AddSZStringToMapN(&context, TEEP_LABEL_ATTESTATION_PAYLOAD_FORMAT, "text/plain");
UsefulBufC evidence = UsefulBuf_FROM_SZ_LITERAL("dummy value");
QCBOREncode_AddBytesToMapN(&context, TEEP_LABEL_ATTESTATION_PAYLOAD, evidence);
}
if (item.val.int64 & TEEP_TRUSTED_COMPONENTS) {
// Add tc-list.
QCBOREncode_OpenArrayInMapN(&context, TEEP_LABEL_TC_LIST);
{
for (TrustedComponent* ta = g_InstalledComponentList; ta != nullptr; ta = ta->Next) {
QCBOREncode_OpenMap(&context);
{
AddComponentIdToMap(&context, ta);
}
QCBOREncode_CloseMap(&context);
}
}
QCBOREncode_CloseArray(&context);
}
if (item.val.int64 & TEEP_EXTENSIONS) {
// Add ext-list to QueryResponse
QCBOREncode_OpenArrayInMapN(&context, TEEP_LABEL_EXT_LIST);
{
// We don't support any extensions currently.
}
QCBOREncode_CloseArray(&context);
}
if (g_RequestedComponentList != nullptr)
{
// Add requested-tc-list.
QCBOREncode_OpenArrayInMapN(&context, TEEP_LABEL_REQUESTED_TC_LIST);
{
for (TrustedComponent* ta = g_RequestedComponentList; ta != nullptr; ta = ta->Next) {
QCBOREncode_OpenMap(&context);
{
AddComponentIdToMap(&context, ta);
}
QCBOREncode_CloseMap(&context);
}
}
QCBOREncode_CloseArray(&context);
}
if (g_UnneededComponentList != nullptr)
{
// Add unneeded-manifest-list.
QCBOREncode_OpenArrayInMapN(&context, TEEP_LABEL_UNNEEDED_MANIFEST_LIST);
{
for (TrustedComponent* tc = g_UnneededComponentList; tc != nullptr; tc = tc->Next) {
QCBOREncode_OpenArray(&context);
{
UsefulBuf tc_id = UsefulBuf_FROM_BYTE_ARRAY(tc->ID.b);
QCBOREncode_AddBytes(&context, UsefulBuf_Const(tc_id));
}
QCBOREncode_CloseArray(&context);
}
}
QCBOREncode_CloseArray(&context);
}
}
QCBOREncode_CloseMap(&context);
}
QCBOREncode_CloseArray(&context);
UsefulBufC const_buffer = UsefulBuf_Const(buffer);
QCBORError err = QCBOREncode_Finish(&context, &const_buffer);
if (err != QCBOR_SUCCESS) {
return TEEP_ERR_TEMPORARY_ERROR;
}
*encodedResponse = const_buffer;
return TEEP_ERR_SUCCESS;
}
static teep_error_code_t TeepAgentSendMessage(
_In_ void* sessionHandle,
_In_z_ const char* mediaType,
_In_ const UsefulBufC* unsignedMessage)
{
#ifdef TEEP_USE_COSE
UsefulBufC signedMessage;
Q_USEFUL_BUF_MAKE_STACK_UB(signed_cose_buffer, 1000);
teep_error_code_t error = TeepAgentSignMessage(unsignedMessage, signed_cose_buffer, &signedMessage);
if (error != TEEP_ERR_SUCCESS) {
return error;
}
const char* output_buffer = (const char*)signedMessage.ptr;
size_t output_buffer_length = signedMessage.len;
#else
const char* output_buffer = (const char*)unsignedMessage->ptr;
size_t output_buffer_length = unsignedMessage->len;
#endif
return TeepAgentQueueOutboundTeepMessage(
sessionHandle,
mediaType,
output_buffer,
output_buffer_length);
}
/* Compose a raw Success message to be signed. */
static teep_error_code_t TeepAgentComposeSuccess(UsefulBufC token, UsefulBufC* encoded)
{
encoded->ptr = nullptr;
encoded->len = 0;
int maxBufferLength = 4096;
char* rawBuffer = (char*)malloc(maxBufferLength);
if (rawBuffer == nullptr) {
return TEEP_ERR_TEMPORARY_ERROR;
}
encoded->ptr = rawBuffer;
encoded->len = maxBufferLength;
QCBOREncodeContext context;
UsefulBuf buffer = UsefulBuf_Unconst(*encoded);
QCBOREncode_Init(&context, buffer);
QCBOREncode_OpenArray(&context);
{
// Add TYPE.
QCBOREncode_AddInt64(&context, TEEP_MESSAGE_SUCCESS);
// Add option map.
QCBOREncode_OpenMap(&context);
{
if (!UsefulBuf_IsNULLC(token)) {
// Copy token from request.
QCBOREncode_AddBytesToMapN(&context, TEEP_LABEL_TOKEN, token);
}
}
QCBOREncode_CloseMap(&context);
}
QCBOREncode_CloseArray(&context);
QCBORError err = QCBOREncode_Finish(&context, encoded);
return (err == QCBOR_SUCCESS) ? TEEP_ERR_SUCCESS : TEEP_ERR_TEMPORARY_ERROR;
}
static teep_error_code_t TeepAgentComposeError(UsefulBufC token, teep_error_code_t errorCode, const std::string& errorMessage, UsefulBufC* encoded)
{
*encoded = NULLUsefulBufC;
int maxBufferLength = 4096;
char* rawBuffer = (char*)malloc(maxBufferLength);
if (rawBuffer == nullptr) {
return TEEP_ERR_TEMPORARY_ERROR;
}
encoded->ptr = rawBuffer;
encoded->len = maxBufferLength;
QCBOREncodeContext context;
UsefulBuf buffer = UsefulBuf_Unconst(*encoded);
QCBOREncode_Init(&context, buffer);
QCBOREncode_OpenArray(&context);
{
// Add TYPE.
QCBOREncode_AddInt64(&context, TEEP_MESSAGE_ERROR);
QCBOREncode_OpenMap(&context);
{
if (!UsefulBuf_IsNULLC(token)) {
// Copy token from request.
QCBOREncode_AddBytesToMapN(&context, TEEP_LABEL_TOKEN, token);
}
// Add error message.
if (!errorMessage.empty()) {
QCBOREncode_AddSZStringToMapN(&context, TEEP_LABEL_ERR_MSG, errorMessage.c_str());
}
// Add suit-reports if Update failed.
// TODO(issue #11): Add suit-reports.
}
QCBOREncode_CloseMap(&context);
// Add err-code uint.
QCBOREncode_AddInt64(&context, errorCode);
}
QCBOREncode_CloseArray(&context);
QCBORError err = QCBOREncode_Finish(&context, encoded);
// On success we return the original errorCode here, which the caller
// can propogate.
return (err == QCBOR_SUCCESS) ? errorCode : TEEP_ERR_TEMPORARY_ERROR;
}
static void TeepAgentSendError(UsefulBufC reply, void* sessionHandle)
{
if (reply.len == 0) {
return;
}
HexPrintBuffer("Sending CBOR message: ", reply.ptr, reply.len);
(void)TeepAgentSendMessage(sessionHandle, TEEP_CBOR_MEDIA_TYPE, &reply);
free((void*)reply.ptr);
}
static teep_error_code_t TeepAgentHandleInvalidMessage(_In_ void* sessionHandle, _In_ QCBORDecodeContext* context)
{
TEEP_UNUSED(context);
TeepLogMessage("TeepAgentHandleInvalidMessage\n");
UsefulBufC errorResponse;
UsefulBufC errorToken = NULLUsefulBufC;
TeepAgentComposeError(errorToken, TEEP_ERR_PERMANENT_ERROR, "Invalid message", &errorResponse);
if (errorResponse.len > 0) {
TeepAgentSendError(errorResponse, sessionHandle);
}
return TEEP_ERR_PERMANENT_ERROR;
}
static teep_error_code_t TeepAgentHandleQueryRequest(void* sessionHandle, QCBORDecodeContext* context)
{
TeepLogMessage("TeepAgentHandleQueryRequest\n");
/* Compose a raw response. */
UsefulBufC queryResponse;
UsefulBufC errorResponse;
teep_error_code_t errorCode = TeepAgentComposeQueryResponse(context, &queryResponse, &errorResponse);
if (errorCode != TEEP_ERR_SUCCESS) {
TeepAgentSendError(errorResponse, sessionHandle);
return errorCode;
}
if (queryResponse.len == 0) {
return TEEP_ERR_PERMANENT_ERROR;
}
HexPrintBuffer("Sending CBOR message: ", queryResponse.ptr, queryResponse.len);
TeepLogMessage("Sending QueryResponse...\n");
errorCode = TeepAgentSendMessage(sessionHandle, TEEP_CBOR_MEDIA_TYPE, &queryResponse);
free((void*)queryResponse.ptr);
return errorCode;
}
static teep_error_code_t TeepAgentParseComponentId(
_Inout_ QCBORDecodeContext* context,
_In_ const QCBORItem* arrayItem,
_Out_ UsefulBufC* componentId,
_Out_ std::ostringstream& errorMessage)
{
if (arrayItem->uDataType != QCBOR_TYPE_ARRAY) {
REPORT_TYPE_ERROR(errorMessage, "component-id", QCBOR_TYPE_ARRAY, *arrayItem);
return TEEP_ERR_PERMANENT_ERROR;
}
// Get array size.
uint16_t componentIdEntryCount = arrayItem->val.uCount;
if (componentIdEntryCount != 1) {
// TODO: support more general component ids.
return TEEP_ERR_PERMANENT_ERROR;
}
// Read bstr from component id array.
QCBORItem item;
QCBORDecode_GetNext(context, &item);
if (item.uDataType != QCBOR_TYPE_BYTE_STRING) {
REPORT_TYPE_ERROR(errorMessage, "component-id", QCBOR_TYPE_BYTE_STRING, item);
return TEEP_ERR_PERMANENT_ERROR;
}
*componentId = item.val.string;
return TEEP_ERR_SUCCESS;
}
static teep_error_code_t TeepAgentHandleUpdate(void* sessionHandle, QCBORDecodeContext* context)
{
TeepLogMessage("TeepAgentHandleUpdate\n");
std::ostringstream errorMessage;
QCBORItem item;
UsefulBufC token = NULLUsefulBufC;
teep_error_code_t teep_error = TEEP_ERR_SUCCESS;
UsefulBufC errorResponse = NULLUsefulBufC;
// Parse the options map.
QCBORDecode_GetNext(context, &item);
if (item.uDataType != QCBOR_TYPE_MAP) {
REPORT_TYPE_ERROR(errorMessage, "options", QCBOR_TYPE_MAP, item);
teep_error = TeepAgentComposeError(token, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), &errorResponse);
TeepAgentSendError(errorResponse, sessionHandle);
return teep_error;
}
teep_error_code_t errorCode = TEEP_ERR_SUCCESS;
uint16_t mapEntryCount = item.val.uCount;
for (int mapEntryIndex = 0; mapEntryIndex < mapEntryCount; mapEntryIndex++) {
QCBORDecode_GetNext(context, &item);
teep_label_t label = (teep_label_t)item.label.int64;
switch (label) {
case TEEP_LABEL_TOKEN:
{
// Get token from request.
if (item.uDataType != QCBOR_TYPE_BYTE_STRING) {
REPORT_TYPE_ERROR(errorMessage, "token", QCBOR_TYPE_BYTE_STRING, item);
teep_error = TeepAgentComposeError(token, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), &errorResponse);
TeepAgentSendError(errorResponse, sessionHandle);
return teep_error;
}
token = item.val.string;
break;
}
case TEEP_LABEL_UNNEEDED_MANIFEST_LIST:
{
if (item.uDataType != QCBOR_TYPE_ARRAY) {
REPORT_TYPE_ERROR(errorMessage, "unneeded-manifest-list", QCBOR_TYPE_ARRAY, item);
teep_error = TeepAgentComposeError(token, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), &errorResponse);
TeepAgentSendError(errorResponse, sessionHandle);
return teep_error;
}
uint16_t arrayEntryCount = item.val.uCount;
#ifdef _DEBUG
TeepLogMessage("Parsing %d unneeded-manifest-list entries...\n", item.val.uCount);
#endif
for (int arrayEntryIndex = 0; arrayEntryIndex < arrayEntryCount; arrayEntryIndex++) {
QCBORDecode_GetNext(context, &item);
UsefulBufC componentId;
teep_error = TeepAgentParseComponentId(context, &item, &componentId, errorMessage);
if (teep_error != TEEP_ERR_SUCCESS) {
teep_error = TeepAgentComposeError(token, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), &errorResponse);
TeepAgentSendError(errorResponse, sessionHandle);
return teep_error;
}
errorCode = SuitUninstallComponent(componentId);
if (errorCode != TEEP_ERR_SUCCESS) {
break;
}
}
break;
}
case TEEP_LABEL_MANIFEST_LIST:
{
if (item.uDataType != QCBOR_TYPE_ARRAY) {
REPORT_TYPE_ERROR(errorMessage, "manifest-list", QCBOR_TYPE_ARRAY, item);
teep_error = TeepAgentComposeError(token, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), &errorResponse);
TeepAgentSendError(errorResponse, sessionHandle);
return teep_error;
}
uint16_t arrayEntryCount = item.val.uCount;
#ifdef _DEBUG
TeepLogMessage("Parsing %d manifest-list entries...\n", item.val.uCount);
#endif
for (int arrayEntryIndex = 0; arrayEntryIndex < arrayEntryCount; arrayEntryIndex++) {
QCBORDecode_GetNext(context, &item);
if (item.uDataType != QCBOR_TYPE_BYTE_STRING) {
REPORT_TYPE_ERROR(errorMessage, "SUIT_Envelope", QCBOR_TYPE_BYTE_STRING, item);
teep_error = TeepAgentComposeError(token, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), &errorResponse);
TeepAgentSendError(errorResponse, sessionHandle);
return teep_error;
}
if (errorCode == TEEP_ERR_SUCCESS) {
// Try until we hit the first error.
errorCode = TryProcessSuitEnvelope(item.val.string, errorMessage);
if (errorCode != TEEP_ERR_SUCCESS) {
break;
}
}
}
break;
}
case TEEP_LABEL_ATTESTATION_PAYLOAD_FORMAT:
{
if (item.uDataType != QCBOR_TYPE_TEXT_STRING) {
REPORT_TYPE_ERROR(errorMessage, "attestation-payload-format", QCBOR_TYPE_TEXT_STRING, item);
teep_error = TeepAgentComposeError(token, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), &errorResponse);
TeepAgentSendError(errorResponse, sessionHandle);
return teep_error;
}
// TODO: use Attestation Result.
break;
}
case TEEP_LABEL_ATTESTATION_PAYLOAD:
{
if (item.uDataType != QCBOR_TYPE_BYTE_STRING) {
REPORT_TYPE_ERROR(errorMessage, "attestation-payload", QCBOR_TYPE_BYTE_STRING, item);
teep_error = TeepAgentComposeError(token, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), &errorResponse);
TeepAgentSendError(errorResponse, sessionHandle);
return teep_error;
}
// TODO: use Attestation Result.
break;
}
default:
errorMessage << "Unrecognized option label " << label;
teep_error = TeepAgentComposeError(token, TEEP_ERR_PERMANENT_ERROR, errorMessage.str(), &errorResponse);
TeepAgentSendError(errorResponse, sessionHandle);
return teep_error;
}
}
/* Compose a Success reply. */
UsefulBufC reply;
teep_error = TeepAgentComposeSuccess(token, &reply);
if (teep_error != TEEP_ERR_SUCCESS) {
return teep_error;
}
if (reply.len == 0) {
return TEEP_ERR_TEMPORARY_ERROR;
}
HexPrintBuffer("Sending CBOR message: ", reply.ptr, reply.len);
teep_error = TeepAgentSendMessage(sessionHandle, TEEP_CBOR_MEDIA_TYPE, &reply);
free((void*)reply.ptr);
return teep_error;
}
static teep_error_code_t TeepAgentVerifyMessageSignature(
_In_ void* sessionHandle,
_In_reads_(messageLength) const char* message,
size_t messageLength,
_Out_ UsefulBufC* pencoded)
{
TEEP_UNUSED(sessionHandle);
UsefulBufC signed_cose;
signed_cose.ptr = message;
signed_cose.len = messageLength;
for (auto key_pair : TeepAgentGetTamKeys()) {
teep_error_code_t teeperr = teep_verify_cbor_message(&key_pair, &signed_cose, pencoded);
if (teeperr == TEEP_ERR_SUCCESS) {
// TODO(#114): save key_pair in session
return TEEP_ERR_SUCCESS;
}
}
TeepLogMessage("TEEP agent failed verification of TAM key\n");
return TEEP_ERR_PERMANENT_ERROR;
#if 0
#ifdef TEEP_USE_COSE
// Determine whether message is COSE_Sign1 or not.
if ((messageLength >= 2) && (message[0] == (char)0x84) && (message[1] == TEEP_MESSAGE_QUERY_REQUEST)) {
// The only message that isn't is a query request where
// the first byte means array of size 4 and the second byte is a 1.
#endif
encoded.ptr = message;
encoded.len = messageLength;
#ifdef TEEP_USE_COSE
} else {
struct t_cose_key key_pair;
teeperr = TeepAgentGetTamKey(&key_pair);
if (teeperr != TEEP_ERR_SUCCESS) {
return teeperr;
}
UsefulBufC signed_cose;
signed_cose.ptr = message;
signed_cose.len = messageLength;
teeperr = teep_verify_cbor_message(&key_pair, &signed_cose, pencoded);
if (teeperr != TEEP_ERR_SUCCESS) {
return teeperr;
}
}
#endif
#endif
}
/* Handle an incoming message from a TAM. */
static teep_error_code_t TeepAgentHandleMessage(
_In_ void* sessionHandle,
_In_reads_(messageLength) const char* message,
size_t messageLength)
{
QCBORDecodeContext context;
QCBORItem item;
std::ostringstream errorMessage;
HexPrintBuffer("TeepAgentHandleCborMessage got COSE message:\n", message, messageLength);
TeepLogMessage("\n");
// Verify signature and save which signing key was used.
UsefulBufC encoded;
teep_error_code_t teeperr = TeepAgentVerifyMessageSignature(sessionHandle, message, messageLength, &encoded);
if (teeperr != TEEP_ERR_SUCCESS) {
return teeperr;
}
HexPrintBuffer("Received CBOR message: ", encoded.ptr, encoded.len);
QCBORDecode_Init(&context, encoded, QCBOR_DECODE_MODE_NORMAL);
QCBORDecode_GetNext(&context, &item);
if (item.uDataType != QCBOR_TYPE_ARRAY) {
REPORT_TYPE_ERROR(errorMessage, "message", QCBOR_TYPE_ARRAY, item);
return TeepAgentHandleInvalidMessage(sessionHandle, &context);
}
QCBORDecode_GetNext(&context, &item);
if (item.uDataType != QCBOR_TYPE_INT64) {
REPORT_TYPE_ERROR(errorMessage, "TYPE", QCBOR_TYPE_INT64, item);
return TeepAgentHandleInvalidMessage(sessionHandle, &context);
}
teep_message_type_t messageType = (teep_message_type_t)item.val.uint64;
TeepLogMessage("Received CBOR TEEP message type=%d\n", messageType);
switch (messageType) {
case TEEP_MESSAGE_QUERY_REQUEST:
teeperr = TeepAgentHandleQueryRequest(sessionHandle, &context);
break;
case TEEP_MESSAGE_UPDATE:
teeperr = TeepAgentHandleUpdate(sessionHandle, &context);
break;
default:
teeperr = TeepAgentHandleInvalidMessage(sessionHandle, &context);
break;
}
QCBORError err = QCBORDecode_Finish(&context);
if (teeperr != TEEP_ERR_SUCCESS) {
return teeperr;
}
return (err == QCBOR_SUCCESS) ? TEEP_ERR_SUCCESS : TEEP_ERR_TEMPORARY_ERROR;
}
teep_error_code_t TeepAgentProcessTeepMessage(
_In_ void* sessionHandle,
_In_z_ const char* mediaType,
_In_reads_(messageLength) const char* message,
size_t messageLength)
{
teep_error_code_t err = TEEP_ERR_SUCCESS;
TeepLogMessage("Received contentType='%s' messageLength=%zd\n", mediaType, messageLength);
if (messageLength < 1) {
return TEEP_ERR_PERMANENT_ERROR;
}
if (strncmp(mediaType, TEEP_CBOR_MEDIA_TYPE, strlen(TEEP_CBOR_MEDIA_TYPE)) == 0) {
err = TeepAgentHandleMessage(sessionHandle, message, messageLength);
} else {
return TEEP_ERR_PERMANENT_ERROR;
}
return err;
}
static _Ret_maybenull_ TrustedComponent* FindComponentInList(_In_opt_ TrustedComponent* head, teep_uuid_t taid)
{
for (TrustedComponent* ta = head; ta != nullptr; ta = ta->Next) {
if (memcmp(&ta->ID, &taid, sizeof(taid)) == 0) {
return ta;
}
}
return nullptr;
}
teep_error_code_t TeepAgentRequestTA(
teep_uuid_t requestedTaid,
_In_z_ const char* tamUri)
{
teep_error_code_t err = TEEP_ERR_SUCCESS;
// See whether requestedTaid is already installed.
TrustedComponent* found = FindComponentInList(g_InstalledComponentList, requestedTaid);
if (found != nullptr) {
// Already installed, nothing to do.
// This counts as "pass no data back" in the broker spec.
return TEEP_ERR_SUCCESS;
}
// See whether requestedTaid has already been requested.
TrustedComponent* tc;
for (tc = g_RequestedComponentList; tc != nullptr; tc = tc->Next) {
if (memcmp(tc->ID.b, requestedTaid.b, TEEP_UUID_SIZE) == 0) {
// Already requested, nothing to do.
// This counts as "pass no data back" in the broker spec.
return TEEP_ERR_SUCCESS;
}
}
// Add requestedTaid to the request list.
tc = new TrustedComponent(requestedTaid);
tc->Next = g_RequestedComponentList;
g_RequestedComponentList = tc;
// TODO: we may want to modify the TAM URI here.
// TODO: see whether we already have a TAM cert we trust.
// For now we skip this step and say we don't.
bool haveTrustedTamCert = false;
if (!haveTrustedTamCert) {
// Pass back a TAM URI with no buffer.
TeepLogMessage("Sending an empty message...\n");
const char* acceptMediaType = TEEP_CBOR_MEDIA_TYPE;
err = TeepAgentConnect(tamUri, acceptMediaType);
if (err != TEEP_ERR_SUCCESS) {
return err;
}
} else {
// TODO: implement going on to the next message.
TEEP_ASSERT(false);
}
return err;
}
teep_error_code_t TeepAgentUnrequestTA(
teep_uuid_t unneededTaid,
_In_z_ const char* tamUri)
{
teep_error_code_t teep_error = TEEP_ERR_SUCCESS;
// See whether unneededTaid is installed.
TrustedComponent* found = FindComponentInList(g_InstalledComponentList, unneededTaid);
if (found == nullptr) {
// Already not installed, nothing to do.
// This counts as "pass no data back" in the broker spec.
return TEEP_ERR_SUCCESS;
}
// See whether unneededTaid has already been notified to the TAM.
TrustedComponent* tc = FindComponentInList(g_UnneededComponentList, unneededTaid);
if (tc != nullptr) {
// Already requested, nothing to do.
// This counts as "pass no data back" in the broker spec.
return TEEP_ERR_SUCCESS;
}
// Add unneededTaid to the unneeded list.
tc = new TrustedComponent(unneededTaid);
tc->Next = g_UnneededComponentList;
g_UnneededComponentList = tc;
// TODO: we may want to modify the TAM URI here.
// TODO: see whether we already have a TAM cert we trust.
// For now we skip this step and say we don't.
bool haveTrustedTamCert = false;
if (!haveTrustedTamCert) {
// Pass back a TAM URI with no buffer.
TeepLogMessage("Sending an empty message...\n");
teep_error = TeepAgentConnect(tamUri, TEEP_CBOR_MEDIA_TYPE);
if (teep_error != TEEP_ERR_SUCCESS) {
return teep_error;
}
} else {
// TODO: implement going on to the next message.
TEEP_ASSERT(false);
}
return teep_error;
}
/* TODO: This is just a placeholder for a real implementation.
* Currently we provide untrusted manifests into the TEEP Agent.
* In a real implementation, the TEEP Agent would instead either load
* manifests from a trusted location, or use sealed storage
* (decrypting the contents inside the TEE).
*/
teep_error_code_t TeepAgentConfigureManifests(
_In_z_ const char* directory_name)
{
teep_error_code_t result = TEEP_ERR_SUCCESS;
DIR* dir = opendir(directory_name);
if (dir == NULL) {
return TEEP_ERR_TEMPORARY_ERROR;
}
for (;;) {
struct dirent* dirent = readdir(dir);
if (dirent == NULL) {
break;
}
char* filename = dirent->d_name;
size_t filename_length = strlen(filename);
if (filename_length < 6 ||
strcmp(filename + filename_length - 5, ".cbor") != 0) {
continue;
}
// Convert filename to a uuid.
teep_uuid_t component_id;
result = GetUuidFromFilename(filename, &component_id);
if (result != TEEP_ERR_SUCCESS) {
break;
}
TrustedComponent* tc = new TrustedComponent(component_id);
if (tc == nullptr) {
result = TEEP_ERR_TEMPORARY_ERROR;
break;
}
tc->Next = g_InstalledComponentList;
g_InstalledComponentList = tc;
}
closedir(dir);
return result;
}
filesystem::path g_agent_data_directory;
teep_error_code_t TeepAgentLoadConfiguration(_In_z_ const char* dataDirectory)
{
g_agent_data_directory = std::filesystem::current_path();
g_agent_data_directory /= dataDirectory;
std::filesystem::path manifest_path = g_agent_data_directory / "manifests";
return TeepAgentConfigureManifests(manifest_path.string().c_str());
}
static void ClearComponentList(_Inout_ TrustedComponent** componentList)
{
while (*componentList != nullptr) {
TrustedComponent* ta = *componentList;
*componentList = ta->Next;
ta->Next = nullptr;
delete ta;
}
}
void TeepAgentShutdown()
{
ClearComponentList(&g_InstalledComponentList);
ClearComponentList(&g_UnneededComponentList);
ClearComponentList(&g_RequestedComponentList);
}
#define TOXDIGIT(x) ("0123456789abcdef"[x])
void TeepAgentMakeManifestFilename(_Out_ filesystem::path& manifestPath, _In_reads_(buffer_len) const char* buffer, size_t buffer_len)
{
manifestPath = g_agent_data_directory;
manifestPath /= "manifests";
char filename[_MAX_PATH];
#if 1
// Hex encode buffer.
for (size_t i = 0, fi = 0; i < buffer_len; i++) {
uint8_t ch = buffer[i];
if (i == 4 || i == 6 || i == 8 || i == 10) {
filename[fi++] = '-';
}
filename[fi++] = TOXDIGIT(ch >> 4);
filename[fi++] = TOXDIGIT(ch & 0xf);
filename[fi] = 0;
}
#else
// Escape illegal characters.
size_t i;
for (i = 0; (i < buffer_len) && (i < filename_len - 1) && buffer[i]; i++) {
filename[i] = (isalnum(buffer[i]) || (strchr("-_", buffer[i]) != nullptr)) ? buffer[i] : '-';
}
filename[i] = 0;
#endif
manifestPath /= filename;
manifestPath += ".cbor";
}
|
e51a3174159bf471a7a7fffc3949ea2fb724e257
|
fdb5bd8c4dec2dd4c300c1f3fe03c786f82355b1
|
/DP/Number of paths in a matrix with k coins/program.cpp
|
69e653637204d614f3500a2e4d45ef3917be75a0
|
[] |
no_license
|
vermakriti/GfG
|
cef8ab6be744eeba107cf1e4880ca215c897281d
|
0e311bfd0f6056c7ace551a7fe346a64d7d3f2e9
|
refs/heads/master
| 2023-09-03T03:52:13.694106
| 2021-11-08T09:57:22
| 2021-11-08T09:57:22
| 389,953,342
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 601
|
cpp
|
program.cpp
|
class Solution {
public:
long long dp[55][55][55];
long long fun(int i,int j,int n,int k,vector<vector<int>> &a){
if(i==n-1 && j==n-1){
return (k==a[i][j]);
}
if(i>=n || j>=n || k<0)
return 0;
if(dp[i][j][k]!=-1)
return dp[i][j][k];
long long ans=fun(i+1,j,n,k-a[i][j],a) + fun(i,j+1,n,k-a[i][j],a);
return dp[i][j][k]=ans;
}
long long numberOfPath(int n, int k, vector<vector<int>> arr){
memset(dp,-1,sizeof dp);
return fun(0,0,n,k,arr);
}
};
|
e32dbd105a91f1326b4154322e582974f39b3933
|
c77555dcb039877e1e62899d6319f4a0b2e23091
|
/test1/source/main.cpp
|
fb851e3aa28d712285e9fc6d21922b46098cc989
|
[] |
no_license
|
RoyalTux/BounceTravel
|
e5b43196b018ac641da1184da9ed9eb79a57dda4
|
953c9f31d9e74f5e014a464f4ab96705f64669c8
|
refs/heads/master
| 2020-04-26T09:29:11.537692
| 2019-03-02T14:18:25
| 2019-03-02T14:18:25
| 173,456,399
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 257
|
cpp
|
main.cpp
|
#include "game.h"
int main()
{
ShowWindow(GetConsoleWindow(), SW_HIDE);
RenderWindow window(VideoMode(900, 480), "Bounce Travel");
window.setVerticalSyncEnabled(true);
menu(window);
auto numberLevel = 1;
gameRunning(window, numberLevel);
return 0;
}
|
be015103b38d11e003005b3e7ac310cc833221b4
|
15d9395e396ff48ac9788fd4ad085ce807a4c477
|
/MyGame.hpp
|
59a376f70152eea9e5b446c1c1e93be264628ecd
|
[
"MIT"
] |
permissive
|
legau1000/MyGameEngine
|
2a8aae3a4dd4be73e999ab1c5db1ebe116d7a78f
|
11457e4f8428b4ef4548dbe7fbe0cbce24171ad0
|
refs/heads/master
| 2023-02-23T00:01:57.007233
| 2021-01-29T14:47:52
| 2021-01-29T14:47:52
| 327,371,406
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 532
|
hpp
|
MyGame.hpp
|
#pragma once
#include <utility>
#include <memory>
#include "GameEngine.hpp"
#include "Entity.hpp"
class MyGame
{
public:
MyGame(GameEngine*);
~MyGame();
void start();
private:
void createPlayer(std::string name);
void createBloc(std::string name, std::vector<int> pos, std::vector<float> scale);
void createIA(std::string name, std::vector<int> startPos, std::vector<int> endPos, float orientation);
GameEngine* _gameEngine;
std::unordered_map<std::string, std::shared_ptr<Entity>> _entity;
};
|
438d209908efb98de149d867868d3c4dc7466041
|
51635684d03e47ebad12b8872ff469b83f36aa52
|
/external/gcc-12.1.0/libstdc++-v3/testsuite/util/io/prog_bar.cc
|
477180be3ec94fc487b3420d7b1a6b2c31d7c516
|
[
"Zlib",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-only",
"GPL-3.0-only",
"GCC-exception-3.1",
"GPL-2.0-only",
"LGPL-3.0-only",
"LGPL-2.0-or-later"
] |
permissive
|
zhmu/ananas
|
8fb48ddfe3582f85ff39184fc7a3c58725fe731a
|
30850c1639f03bccbfb2f2b03361792cc8fae52e
|
refs/heads/master
| 2022-06-25T10:44:46.256604
| 2022-06-12T17:04:40
| 2022-06-12T17:04:40
| 30,108,381
| 59
| 8
|
Zlib
| 2021-09-26T17:30:30
| 2015-01-31T09:44:33
|
C
|
UTF-8
|
C++
| false
| false
| 2,167
|
cc
|
prog_bar.cc
|
// -*- C++ -*-
// Copyright (C) 2005-2022 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, or (at your option) any later
// version.
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file prog_bar.cpp
* Contains a progress bar - idea taken from boost::timer by Beman Dawes.
*/
#include <util/io/prog_bar.hpp>
namespace __gnu_pbds
{
namespace test
{
prog_bar::
prog_bar(std::size_t max, std::ostream& r_os, bool display/*= true*/) :
m_cur(0),
m_max(max),
m_cur_disp(0),
m_r_os(r_os),
m_display(display)
{
if (m_display == false)
return;
for (std::size_t i = 0; i < num_disp; ++i)
m_r_os << "-";
m_r_os << std::endl;
}
void
prog_bar::
inc()
{
++m_cur;
if (m_display == false)
return;
while (m_cur * num_disp >= m_max * m_cur_disp && m_cur_disp < num_disp)
{
m_r_os << '*';
m_r_os.flush();
++m_cur_disp;
}
}
} // namespace test
} // namespace __gnu_pbds
|
cbdc4824639ca70a0ca8223b6ab106cef1e09fd2
|
c584cff5e148b9345347109e92c1727d59fec331
|
/122PA7/122PA7/Simpletron.h
|
f9ef132ba6b2ada8426ffec2b98a724c3645b712
|
[] |
no_license
|
Stefy-M/SimpleTron-
|
5dbd8a3cfd480775389391caa4ce6db7772f56f9
|
44d416048c33c3c605341cf4ee9517d80c656a13
|
refs/heads/master
| 2021-01-12T12:03:34.653417
| 2016-10-03T22:58:45
| 2016-10-03T22:58:45
| 69,917,795
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,313
|
h
|
Simpletron.h
|
#pragma once
#include <iostream>
#include <string>
#include <fstream>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::ostream;
using std::fstream;
using std::ofstream;
using std::ifstream;
using std::ios;
class Simpletron {
public:
Simpletron();
~Simpletron();
// setters
void setAccumalator(int &aCC);
void setInstructionCounter(int &instrCount);
void setInstructionRegister(int &InstrReg);
void setOperationCode(int &opCode);
void setOperand(int &operand);
//getters
int getAccumaltor();
int getInstructionCounter();
int getInstructionRegister();
int getOperationCode();
int getOperand();
void fetch();
void decode();
void execute();
void display();
void Run();
private:
int Accumalator;
int InstructionCounter;
int InstructionRegister;
int OperationCode;
int Operand;
int ProgramMem[100];
int DataMem[10][10];
fstream SML;
void fetch(fstream &SML, int ProgramMem[]);
void decode(int ProgramMem[], int &OperationCode, int &Operand, int &InstructionRegister, int &Accumalator,
int &InstructionCounter);
void execute(int ProgramMem[],int DataMem[][10],int &InstructionRegister, int &OperationCode, int &Operand,
int &InstructionCounter, int &Accumalator);
};
|
d0366b80cc64875230ec4176a8b262b6546ff076
|
b897bb9a48fc8afc951ed4e8efaa3fe24fa22564
|
/Parser.h
|
1faa885509bb52c042026762ea0734d46500f027
|
[
"MIT"
] |
permissive
|
waynelin567/Register_Clustering
|
abd27b1d8cb3e2808615cb03c6af5e24cdd13b3d
|
bad8f27056661cb63d55c41b54b79bfe9664dbc0
|
refs/heads/master
| 2021-02-10T06:49:39.670849
| 2020-05-23T06:45:06
| 2020-05-23T06:45:30
| 244,357,940
| 0
| 1
|
MIT
| 2020-05-10T02:31:53
| 2020-03-02T11:48:44
|
C++
|
UTF-8
|
C++
| false
| false
| 397
|
h
|
Parser.h
|
#ifndef _PARSER_H_
#define _PARSER_H_
#pragma GCC system_header
#include "def.h"
#include "boost/tokenizer.hpp"
namespace clustering
{
class Parser
{
public:
bool readInFile(const std::string& reg_file);
private:
void readArea(std::ifstream& infile);
void readRegisters(std::ifstream& infile);
int countTokenSize(boost::tokenizer<boost::char_separator<char> >& tok);
};
}
#endif
|
47f772235e1529dd40f41ef6b69abb0100f97d45
|
48b58fe10fcf51d8b093ff90db585172a9774dda
|
/C++/HappyGoLucky/Tester2/game_data.h
|
c7b4485173b24e68880a76fe92aa7b746a1e2f8f
|
[] |
no_license
|
edoabraham/Portfolio
|
b4a6dceedb2e498f1996ee9e2a431136e1bd262a
|
bd9a028c26e207c575d06e99134a5eb4ac717d5e
|
refs/heads/master
| 2021-01-01T16:34:11.732479
| 2013-09-01T07:35:02
| 2013-09-01T07:35:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,111
|
h
|
game_data.h
|
#ifndef _H_GAME_DATA
#define _H_GAME_DATA
#define _SECURE_SCL 1
#include "graphics.h"
#include "scroll.h"
#include "characterOBJ.h"
#include "entity.h"
#include "dependencies.h"
extern const int MIN_CONST_LIST_SIZE;
class Game_Data {
public:
Game_Data();
~Game_Data();
// Root File that Contains the File Names of Individual Data Files
// Consolidates All Individual Files and Parses Them
void parse_data(string fileName);
void store_const(string fileName);
vector<Entity> entity_list_;
private:
void parse_file(string fileName);
void parse_entities(const string line);
void parse_items(const string line);
void parse_graphics(const string line, int val);
void parse_status(const string line, int val);
void parse_animations(const string line, int val);
bool comment(string line);
string constant(const int val);
string int_to_str(const int val);
int str_to_int(const string line);
string get_line(string &destination, istringstream &source, const int val, const int range);
vector<string> const_str_;
string default_;
Entity temp_;
};
#endif
|
772743f671a91a825f635107a8d4fc8e5f6e97a7
|
06aa3647ea9caf1e5fe6cd37c76651f6fece1a3b
|
/src/mxHidenPanel.h
|
2b256b52b9c0de32b8b5013c8079b443f4cec86f
|
[] |
no_license
|
SoftwareIDE/ZinjaI
|
6731dc9a5a67a9f138f547f02f8c62a67d42f8d5
|
a3d752bf5fa971a726fc4ba036d860edf6588b5f
|
refs/heads/master
| 2020-12-24T19:46:21.098172
| 2016-05-04T20:45:52
| 2016-05-04T20:45:52
| 58,789,743
| 3
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,000
|
h
|
mxHidenPanel.h
|
#ifndef MXHIDENPANEL_H
#define MXHIDENPANEL_H
#include <wx/panel.h>
#include <wx/timer.h>
enum hp_pos {HP_LEFT, HP_BOTTOM, HP_RIGHT};
class mxHidenPanel : public wxPanel {
private:
wxString label;
bool selected;
bool mouse_in;
bool showing;
bool forced_show;
hp_pos pos;
static int used_bottom, used_right,used_left;
static int used_bottom_right, used_bottom_left, used_right_bottom ,used_left_bottom;
public:
static bool ignore_autohide;
wxTimer *timer;
wxWindow *control;
mxHidenPanel(wxWindow *parent, wxWindow *acontrol, hp_pos apos, wxString alabel);
void OnPaint(wxPaintEvent &evt);
void ProcessClose();
void Hide();
void Select();
void ShowFloat(bool set_focus);
void ShowDock();
void ToggleFull();
void ToggleDock();
void ForceShow(bool set_focus);
void ProcessParentResize();
void OnClick(wxMouseEvent &evt);
void OnMotion(wxMouseEvent &evt);
void OnTimer(wxTimerEvent &evt);
void OnResize(wxSizeEvent &evt);
bool IsDocked();
DECLARE_EVENT_TABLE();
};
#endif
|
6102fd269d2022846245766f7f4535c0ec47a00f
|
cde6405ebf729e43c3acc99f6cc827565e25964f
|
/GradiusVI/Helios/Include/Core/InputManager.h
|
204d5e46be13642c719365b34f4ec0dfb4d29642
|
[] |
no_license
|
boschman32/Helios
|
bd071c5e54671a8f7f072b8634e9d850c9719ad6
|
bdc31ef362038750e5dcde3caffa914c658369ac
|
refs/heads/main
| 2023-03-10T21:28:25.138368
| 2021-02-27T12:27:45
| 2021-02-27T12:27:45
| 342,838,003
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,535
|
h
|
InputManager.h
|
#pragma once
#include "Renderer/KeyCodes.h"
#include "Renderer/InputEvents.h"
using Key = KeyCode::Key;
namespace Helios
{
class Axis
{
void SetName(const std::string& a_name);
public:
float m_value = 0.0f;
std::string m_name;
};
class Button
{
std::vector<Key> m_keyboardKeys;
std::vector<unsigned int> m_joystickButtons;
std::string m_name;
unsigned int m_joystick = 0;
bool m_isPressed = false;
bool m_hasBeenDown = false;
public:
void SetJoystick(unsigned int a_joystick);
void AddKey(const Key& a_key);
void AddJoystickButton(unsigned int a_joystickButton);
void SetName(const std::string& a_name);
const std::string& GetName() const;
bool IsAnyKeDown() const;
bool HasBeenDown() const;
void ResetHasBeenDown();
void OnKeyPressed(KeyEventArgs& e);
void OnKeyReleased(KeyEventArgs& e);
};
class Controller
{
public:
void AddButton(const Button& a_button);
void AddAxis(const Axis& a_axis);
bool GetButtonDown(const std::string& a_buttonName);
bool GetButtonUp(const std::string& a_buttonName);
bool GetButtonOnce(const std::string& a_buttonName);
float GetAxis(const std::string& a_axisName);
std::vector<Button> m_buttons;
std::vector<Axis> m_axises;
};
class InputManager
{
static std::vector <std::unique_ptr<Controller>> m_controllers;
public:
static Controller* GetController(int a_id);
static void AddController(std::unique_ptr<Controller> a_controller);
static const std::vector<std::unique_ptr<Controller>>& GetAllControllers();
};
}
|
511ac49861b2934dfcdfa3bd24d3f2745eed1f62
|
84ea17552c2fd77bc85af22f755ae04326486bb5
|
/Ablaze-Core/src/Utils/Files/ImageFile.h
|
023de9042ddc7ef8fb09a9131e55bc90415b660a
|
[] |
no_license
|
Totomosic/Ablaze
|
98159c0897b85b236cf18fc8362501c3873e49f4
|
e2313602d80d8622c810d3d0d55074cda037d287
|
refs/heads/master
| 2020-06-25T20:58:29.377957
| 2017-08-18T07:42:20
| 2017-08-18T07:42:20
| 96,988,561
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 261
|
h
|
ImageFile.h
|
#pragma once
#include "DataFile.h"
namespace Ablaze
{
class VFS;
class ImageFile : public DataFile
{
protected:
ImageFile(const String& physicalPath);
public:
byte* ReadImage(GLsizei* width, GLsizei* height, uint* bpp);
friend class VFS;
};
}
|
efc49de7d07e4a8ae56290486a6c1eb53081988a
|
b9917f00c799c7c95f0a045359c18bf4f657d377
|
/midterm-examination-mreece813/task-01/main.cpp
|
91fed508a89367bab9281b5d516b329d5495a29b
|
[] |
no_license
|
mreece813/CPP_Codes
|
13b5d97f75142fcb00ca88cf34fa579c6140392d
|
c2920c902185758e61c86f0588b98c851bdd19bf
|
refs/heads/main
| 2023-03-02T16:23:19.534670
| 2021-02-08T21:53:47
| 2021-02-08T21:53:47
| 337,216,587
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 615
|
cpp
|
main.cpp
|
#include <iostream>
using namespace std;
int main()
{
// -------------------------------------------------------------------------
// Uncomment the line that is the correct answer!
//
// Which of the following properly prints all integers from 0 to 9?
// -------------------------------------------------------------------------
for (auto i = 0; i < 10; i += 1)
// for (i = 0; i < 10; i++)
// for (auto i = 0; i > 10; i++)
// for (auto i = 0; i < 10;)
// -------------------------------------------------------------------------
{
cout << i << endl;
}
}
|
55d2406a6624e1beef40b9560aef5f14c88ad665
|
27e2dff8dcc7cbec15540070f1a99e79d369a991
|
/hello/m_2.h
|
327bbbe8a7e13476ee3d139f9c8a564c68b928c2
|
[] |
no_license
|
cxxclean/cxx-clean-include
|
78e6cd97579f7f6839747731e0f789bce459fdcc
|
dc775133337ca277a3f40c425e6188ef762960d8
|
refs/heads/master
| 2022-06-04T00:02:49.239424
| 2022-04-27T16:28:57
| 2022-04-27T16:28:57
| 53,064,107
| 81
| 26
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 113
|
h
|
m_2.h
|
#ifndef _m_2_h_
#define _m_2_h_
#include "m_1.h"
using namespace ns_m0::ns_m1::ns_m2;
#endif // _m_2_h_
|
978b4509e1e8b545f6f94c77d0f52380fed22006
|
6063dbe18617be9188053986cf8d42ec98472e3a
|
/libraries/TILLAnalysis/TFipps/LinkDef.h
|
330ce36919025a1ad9e8477509fa9725dd1fb9cd
|
[] |
no_license
|
UoG-Nuclear-Physics-Group/ILLData
|
f48ca24a1155a16ddf7a1a3db6b42aaa10eec627
|
6f2f469f9d8da982748b2307b622a3382c5b3c6c
|
refs/heads/main
| 2023-04-29T01:49:42.953884
| 2023-04-26T21:46:34
| 2023-04-26T21:46:34
| 146,425,659
| 0
| 3
| null | 2023-09-13T19:36:54
| 2018-08-28T09:43:54
|
C++
|
UTF-8
|
C++
| false
| false
| 488
|
h
|
LinkDef.h
|
//TFipps.h TFippsHit.h TFippsBgo.h TFippsBgoHit.h
#ifdef __CINT__
#pragma link off all globals;
#pragma link off all classes;
#pragma link off all functions;
#pragma link off nestedclasses;
//#pragma link C++ class std::vector<Short_t>+;
#pragma link C++ class TFippsHit+;
#pragma link C++ class std::vector<TFippsHit>+;
#pragma link C++ class std::vector<TFippsHit*>+;
#pragma link C++ class TFipps+;
#pragma link C++ class TFippsBgoHit+;
#pragma link C++ class TFippsBgo+;
#endif
|
8e45af672494eaf3b7b31f50b998513551c7dbff
|
776f5892f1395bb8d30731a60466e4c756a44c8c
|
/contests/abc067/arc078_b/main.cc
|
6a040079993ab9c52f602f4f3e6332171b0953b6
|
[] |
no_license
|
kkishi/atcoder
|
fae494af4b47a9f39f05e7536e93d5c4dd21555b
|
f21d22095699dbf064c0d084a5ce5a09a252dc6b
|
refs/heads/master
| 2023-08-31T18:37:13.293499
| 2023-08-27T21:33:43
| 2023-08-27T21:33:43
| 264,760,383
| 0
| 0
| null | 2023-03-10T05:24:07
| 2020-05-17T21:30:14
|
C++
|
UTF-8
|
C++
| false
| false
| 398
|
cc
|
main.cc
|
#include <bits/stdc++.h>
#include "atcoder.h"
#include "dijkstra.h"
#include "graph.h"
void Main() {
ints(n);
WeightedGraph<int> g(n);
rep(n - 1) {
ints(a, b);
--a, --b;
g[a].eb(b, 1);
g[b].eb(a, 1);
}
V<optional<int>> df = Dijkstra(g, 0).dist, ds = Dijkstra(g, n - 1).dist;
int f = 0;
rep(i, n) f += (*df[i] <= *ds[i]) ? 1 : -1;
wt(f > 0 ? "Fennec" : "Snuke");
}
|
5eeb75cb4447409499fd92fe80ccee4c55a1249c
|
90e46b80788f2e77eb68825011c682500cabc59c
|
/Codeforces/1141B.cpp
|
193524d903e782f8c69d643f60cd23e9cbd0c951
|
[] |
no_license
|
yashsoni501/Competitive-Programming
|
87a112e681ab0a134b345a6ceb7e817803bee483
|
3b228e8f9a64ef5f7a8df4af8c429ab17697133c
|
refs/heads/master
| 2023-05-05T13:40:15.451558
| 2021-05-31T10:04:26
| 2021-05-31T10:04:26
| 298,651,663
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 360
|
cpp
|
1141B.cpp
|
#include<iostream>
using namespace std;
typedef long long int ll;
int main()
{
ll n;
cin>>n;
int arr[2*n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
arr[n+i]=arr[i];
}
ll ma=0;
for(int i=0;i<2*n;i++)
{
ll cnt=0;
int j=i;
if(arr[i])
{
while(arr[j]==arr[i]&&i<2*n)
{
cnt++;
i++;
}
ma=max(cnt,ma);
}
}
cout<<ma<<endl;
}
|
9d721f61d018a01883343a7ce6d7817b958e4727
|
90ef88fa0e525b195983a445b0ce2781eb826f5d
|
/src/SettingsPages/AudioAndVideoPage.cpp
|
5a5ba6a9ea4636aee1ca1d150e6a71b78ebfab10
|
[] |
no_license
|
wku/ViberDesktop
|
22e0c2425e9d2e6c997754e5704a46ae2e89169f
|
d28970245e1d5157f788e4a365b20d1840a9ac54
|
refs/heads/master
| 2016-02-28T19:19:43.605885
| 2012-06-12T12:01:06
| 2012-06-12T12:01:06
| 6,839,020
| 4
| 5
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,405
|
cpp
|
AudioAndVideoPage.cpp
|
#include "AudioAndVideoPage.h"
#include "ui_AudioAndVideoPage.h"
#include <globals>
#include "VolumeDefines.h"
namespace
{
const char msg_videoHwNotFound[] = QT_TRANSLATE_NOOP("AudioAndVideoPage", "Video hardware not found");
const char msg_audioInputHwNotFound[] = QT_TRANSLATE_NOOP("AudioAndVideoPage", "Audio input device not found");
const char msg_audioOutputHwNotFound[] = QT_TRANSLATE_NOOP("AudioAndVideoPage", "Audio output device not found");
}
AudioAndVideoPage::AudioAndVideoPage (QWidget* parent )
: QWidget(parent)
, m_audioAndVideo(new Ui::AudioAndVideoForm)
{
m_audioAndVideo->setupUi(this);
//real maximum defined in mediasettings
//and init in updateForm
m_audioAndVideo->inputVolumeHorizontalSlider->setMaximum (255);
m_audioAndVideo->outputVolumeHorizontalSlider->setMaximum (255);
}
void AudioAndVideoPage::changeEvent(QEvent * event)
{
if (event->type() == QEvent::LanguageChange)
{
m_audioAndVideo->retranslateUi(this);
if (m_devicesVideo.empty())
{
if (m_audioAndVideo->videoDeviceComboBox->count() > 0)
m_audioAndVideo->videoDeviceComboBox->setItemText(0, tr(msg_videoHwNotFound));
}
if (m_devicesInput.empty())
{
if (m_audioAndVideo->inputDeviceComboBox->count() > 0)
m_audioAndVideo->inputDeviceComboBox->setItemText(0, tr(msg_audioInputHwNotFound));
}
if (m_devicesOutput.empty())
{
if (m_audioAndVideo->outputDeviceComboBox->count() > 0)
m_audioAndVideo->outputDeviceComboBox->setItemText(0, tr(msg_audioOutputHwNotFound));
}
}
else
{
QWidget::changeEvent(event);
}
}
void AudioAndVideoPage::initCombo ( QComboBox* combo, const Devices& items, const QString& savedDevice, const QString& messageNotFound )
{
combo->clear();
if ( !items.empty() )
{
const int count = items.size();
for(int i = 0; i < count; i++)
{
QString strDevItem = qtsti::PooledStringToQString(items[i].second);
if ( !strDevItem.trimmed().isEmpty() )
{
combo->addItem(strDevItem);
}
}
QString savedVideoDevice = savedDevice;
int index = combo->findText (savedVideoDevice);
//set default 1st device in list in case item from settings isn't found in device list
combo->setCurrentIndex((-1 == index) ? (count ? 0 : index) : index);
}
else
{
combo->addItem(messageNotFound);
combo->setCurrentIndex(0);
}
}
void AudioAndVideoPage::updateForm( AudioAndVideoSettingPointer audioAndVideo,
const Devices& devVideoList, const Devices& devInputList, const Devices& devOutputList,
int maximumVolumePhone, int maximumVolumeMicrophone )
{
m_audioAndVideo->inputVolumeHorizontalSlider->setMaximum ( maximumVolumeMicrophone );
m_audioAndVideo->outputVolumeHorizontalSlider->setMaximum ( maximumVolumePhone );
initCombo (m_audioAndVideo->videoDeviceComboBox, devVideoList, audioAndVideo->getVideoDevice(), tr(msg_videoHwNotFound) );
initCombo (m_audioAndVideo->inputDeviceComboBox, devInputList,audioAndVideo->getInputDevice(), tr(msg_audioInputHwNotFound) );
m_audioAndVideo->inputVolumeHorizontalSlider->setValue ( audioAndVideo->getInputVolume() );
initCombo (m_audioAndVideo->outputDeviceComboBox, devOutputList,audioAndVideo->getOutputDevice(), tr(msg_audioOutputHwNotFound) );
m_audioAndVideo->outputVolumeHorizontalSlider->setValue ( audioAndVideo->getOutputVolume() );
m_audioAndVideo->unmuteSpeackersCheckBox->setChecked ( audioAndVideo->getUnmuteSpeackers() );
m_audioAndVideo->acceptVideoCheckBox->setChecked ( audioAndVideo->getAcceptedVideo() );
// Save devices
m_devicesVideo = devVideoList;
m_devicesInput = devInputList;
m_devicesOutput = devOutputList;
}
void AudioAndVideoPage::updateDevices( AudioAndVideoSettingPointer audioAndVideo,
const Devices& devVideoList, const Devices& devInputList, const Devices& devOutputList )
{
// Update combos only if devices changed
if (devVideoList != m_devicesVideo)
{
m_devicesVideo = devVideoList;
initCombo(m_audioAndVideo->videoDeviceComboBox, devVideoList, audioAndVideo->getVideoDevice(), tr(msg_videoHwNotFound));
}
if (devInputList != m_devicesInput)
{
m_devicesInput = devInputList;
initCombo(m_audioAndVideo->inputDeviceComboBox, devInputList, audioAndVideo->getInputDevice(), tr(msg_audioInputHwNotFound));
}
if (devOutputList != m_devicesOutput)
{
m_devicesOutput = devOutputList;
initCombo(m_audioAndVideo->outputDeviceComboBox, devOutputList, audioAndVideo->getOutputDevice(), tr(msg_audioOutputHwNotFound));
}
}
AudioAndVideoSettingPointer AudioAndVideoPage::updateData()
{
AudioAndVideoSettingPointer audioAndVideoSettingPointer(new AudioAndVideoSetting());
audioAndVideoSettingPointer->setVideoDevice ( m_audioAndVideo->videoDeviceComboBox->currentText() );
audioAndVideoSettingPointer->setInputDevice ( m_audioAndVideo->inputDeviceComboBox->currentText() );
audioAndVideoSettingPointer->setInputVolume ( m_audioAndVideo->inputVolumeHorizontalSlider->value() );
audioAndVideoSettingPointer->setOutputDevice ( m_audioAndVideo->outputDeviceComboBox->currentText() );
audioAndVideoSettingPointer->setOutputVolume ( m_audioAndVideo->outputVolumeHorizontalSlider->value() );
audioAndVideoSettingPointer->setUnmuteSpeackers ( m_audioAndVideo->unmuteSpeackersCheckBox->isChecked() );
audioAndVideoSettingPointer->setAcceptedVideo ( m_audioAndVideo->acceptVideoCheckBox->isChecked() );
return audioAndVideoSettingPointer;
}
void AudioAndVideoPage::on_videoDeviceComboBox_currentIndexChanged ( int index )
{
emit controlStateChanged ( SettingNames::videoDevice_audioAndVideo, QVariant (index) );
}
void AudioAndVideoPage::on_inputDeviceComboBox_currentIndexChanged ( int index )
{
emit controlStateChanged ( SettingNames::inputDevice_audioAndVideo, QVariant (index) );
}
void AudioAndVideoPage::on_outputDeviceComboBox_currentIndexChanged ( int index )
{
emit controlStateChanged ( SettingNames::outputDevice_audioAndVideo, QVariant (index) );
}
void AudioAndVideoPage::on_unmuteSpeackersCheckBox_stateChanged ( int state )
{
emit controlStateChanged ( SettingNames::isUnmuteSpeakers_audioAndVideo, QVariant (Qt::Checked == state) );
}
void AudioAndVideoPage::on_acceptVideoCheckBox_stateChanged ( int state )
{
emit controlStateChanged ( SettingNames::isAcceptedVideo_audioAndVideo, QVariant (Qt::Checked == state) );
}
void AudioAndVideoPage::on_inputVolumeHorizontalSlider_valueChanged ( int value )
{
emit controlStateChanged ( SettingNames::inputVolume_audioAndVideo, QVariant (value) );
}
void AudioAndVideoPage::on_outputVolumeHorizontalSlider_valueChanged ( int value )
{
emit controlStateChanged ( SettingNames::outputVolume_audioAndVideo, QVariant (value) );
}
void AudioAndVideoPage::setVolumeLevel (int level)
{
if (m_audioAndVideo->outputVolumeHorizontalSlider->value() != level)
{
m_audioAndVideo->outputVolumeHorizontalSlider->blockSignals (true);
int maxLevel = m_audioAndVideo->outputVolumeHorizontalSlider->maximum();
//look in VolumeControl
//maximum count item volume in UI
const int countItems = MAXCOUNTVOLUMEITEMS;
//if ( level>=countItems )
{
m_audioAndVideo->outputVolumeHorizontalSlider->setValue ( level );
}/*
else
{
int sizeLevel = maxLevel/countItems;
m_audioAndVideo->outputVolumeHorizontalSlider->setValue (level*sizeLevel);
}*/
m_audioAndVideo->outputVolumeHorizontalSlider->blockSignals (false);
}
}
AudioAndVideoPage::~AudioAndVideoPage()
{
delete m_audioAndVideo;
}
|
fe9e9e30a72a90aef61b298c212f62ca90c62b05
|
c57b7d6240642f451148c8faa4460392915b6420
|
/Lab 5: Inheritance/Lab 5: Inheritance/Person.cpp
|
7c7540949e9ad7b2d12a5fe798c77632f4c89aa0
|
[] |
no_license
|
william86370/Capitol-Tech-CS-230
|
61742d3763686bafa5be8b638eb6eede37b1ee91
|
fdd6592acb2a1452e40e27ec5203946568f08408
|
refs/heads/master
| 2021-08-14T07:54:54.407050
| 2017-11-15T01:28:33
| 2017-11-15T01:28:33
| 104,091,353
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,468
|
cpp
|
Person.cpp
|
//Person.cpp
#include <iostream>
#include "Person.h"
#include "Faculty.h"
Person::Person()
{
fname = "";
lname = "";
id = "";
email = "";
dob = "";
date_hired = "";
termination_date = "";
title = "";
}
Person::Person(std::string pk)
{
fname = "";
lname = "";
id = pk;
email = "";
dob = "";
date_hired = "";
termination_date = "";
title = "";
}
void Person::setName(std::string f, std::string l)
{
fname = f;
lname = l;
}
void Person::setID(std::string pk) { id = pk; }
void Person::setEmail(std::string em) { email = em; }
void Person::setTitle(std::string t) { title = t; }
void Person::setStartDate(std::string dh) { date_hired = dh; }
void Person::setTerminationDate(std::string td) { termination_date = td; }
void Person::setDateOfBorth(std::string db) { dob = db; }
void Person::printPersonnelInfo()
{
std::cout << "Name: " << fname << " " << lname <<
"\nID: " << id << std::endl;
}
void Person::printPersonnelInfo(std::string newID)
{
Person::setID(newID);
std::cout << "Name: " << fname << " " << lname <<
"\nID: " << id << std::endl;
}
void Person::printPersonnelInfo(std::string newFName, std::string newLName, std::string newID)
{
Person::setName(newFName, newLName);
Person::setID(newID);
std::cout << "Name: " << fname << " " << lname <<
"\nID: " << id << std::endl;
}
|
c34ab61b36cbffb5a232b34340955d991b1baf2f
|
345b17ff2af20bcd0cda91bfdcbb15a84eaa32d9
|
/custgview.cpp
|
aa0ccd9432da746f2673650f38e281537638a6ec
|
[] |
no_license
|
sevaserg/QHexView
|
77c17f886f3133b9cb38d873afa2e4e020ba6a88
|
497752cbbe033a40b3ac54accadf0b1026410b6c
|
refs/heads/main
| 2023-02-27T14:18:20.665078
| 2021-02-04T11:13:46
| 2021-02-04T11:13:46
| 324,168,749
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,268
|
cpp
|
custgview.cpp
|
#include "custgview.h"
#include <iostream>
using namespace std;
custGView::custGView()
{
isTextDisplayed_ = false;
for (int i = 0; i < 2; i++)
{
tab[i] = 0;
col[i] = 0;
col2[i] = 0;
}
}
void custGView::switchViews(bool val)
{
isTextDisplayed_ = val;
}
void custGView::clear()
{
qreal w = this->scene()->width();
qreal h = this->scene()->height();
this->scene()->clear();
this->scene()->setSceneRect(0,0,w,h);
this->initRect();
}
void custGView::initRect()
{
if (!isTextDisplayed_)
hexChoice = new QGraphicsRectItem(0,0,20,12);
asciiChoice = new QGraphicsRectItem(0,0,7,12);
printRects();
if (!isTextDisplayed_)
this->scene()->addItem(hexChoice);
this->scene()->addItem(asciiChoice);
}
void custGView::printRects()
{
if(!isTextDisplayed_)
{
hexChoice->setX(col[0]);
hexChoice->setY(tab[0]);
}
asciiChoice->setX(col[1]);
asciiChoice->setY(tab[1]);
}
qreal custGView::getHexX()
{
return hexChoice->x();
}
qreal custGView::getHexY()
{
return hexChoice->y();
}
qreal custGView::getX()
{
if (isTextDisplayed_)
return(col[1] / 8);
else
return(col[0] / 30);
}
qreal custGView::getY()
{
if (isTextDisplayed_)
return(tab[1] / 20);
else
return(tab[0] / 20);
}
void custGView::mouseMoveEvent(QMouseEvent *event)
{
if (!isTextDisplayed_)
{
if (event->pos().x() < 600)
{
col[0] = event->pos().x() - event->pos().x() % 30;
col[1] = static_cast<int>((col[0] - 50)/4.3+(this->width() > 755 ? 615 : 755));
hexChoice->setX(col[0]);
asciiChoice->setX(col[1]);
}
tab[0] = event->pos().y() - event->pos().y() % 20;
tab[1] = tab[0];
hexChoice->setY(tab[0]);
asciiChoice->setY(tab[1]);
printRects();
}
else
{
if (event->pos().x() > 5)
col[1] = event->pos().x() - event->pos().x() % 8;
tab[1] = event->pos().y() - event->pos().y() % 20;
printRects();
}
}
custGView::~custGView()
{
this->scene()->clear();
}
|
4b06a71f01083879adf87b462597e2fabef36b62
|
3cd3872acbc8b1a79a70b89b2fd58a171e7adc82
|
/test/vp8_fragments_test.cc
|
6e5baf229d2408abaae045f575c3685d3d6a0e97
|
[] |
permissive
|
webmproject/libvpx
|
58ab97861063cb521ec0d00ef9cb222ca97873b1
|
6fd360c684736e351160b131827dfbb207841164
|
refs/heads/main
| 2023-04-09T15:32:34.688724
| 2023-04-07T22:19:18
| 2023-04-07T22:19:18
| 22,927,608
| 889
| 376
|
BSD-3-Clause
| 2023-03-24T13:37:34
| 2014-08-13T19:03:21
|
C
|
UTF-8
|
C++
| false
| false
| 1,152
|
cc
|
vp8_fragments_test.cc
|
/*
* Copyright (c) 2014 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/video_source.h"
namespace {
class VP8FragmentsTest : public ::libvpx_test::EncoderTest,
public ::testing::Test {
protected:
VP8FragmentsTest() : EncoderTest(&::libvpx_test::kVP8) {}
virtual ~VP8FragmentsTest() {}
virtual void SetUp() {
const unsigned long init_flags = // NOLINT(runtime/int)
VPX_CODEC_USE_OUTPUT_PARTITION;
InitializeConfig();
SetMode(::libvpx_test::kRealTime);
set_init_flags(init_flags);
}
};
TEST_F(VP8FragmentsTest, TestFragmentsEncodeDecode) {
::libvpx_test::RandomVideoSource video;
ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
}
} // namespace
|
98417592bb70869b6203e1b9268b1d7bf871e0a8
|
6ef8c88ab5aed03a4e597b50da4704bd73782cd1
|
/src/lexer.hpp
|
bbff2e03ebd48c1ee10124450772392b75d9afda
|
[
"MIT"
] |
permissive
|
diamond-lang/diamond
|
75e958d1f7c3931b997fd9d039db2468951f2112
|
7a05e7fc73b350c868488ee2e7f6d0d859c8cf79
|
refs/heads/main
| 2023-09-01T17:04:35.150133
| 2023-08-30T22:01:36
| 2023-08-30T22:01:36
| 334,794,638
| 4
| 1
|
MIT
| 2023-07-22T20:40:16
| 2021-02-01T01:10:53
|
C++
|
UTF-8
|
C++
| false
| false
| 207
|
hpp
|
lexer.hpp
|
#include <vector>
#include <filesystem>
#include "shared.hpp"
#include "errors.hpp"
#include "tokens.hpp"
namespace lexer {
Result<std::vector<token::Token>, Errors> lex(std::filesystem::path path);
};
|
6f06852de79b00f8d0743d0f2c80b3e47f94f6db
|
e6f967c7af649dd43925d10e469f2488ae645b8a
|
/雕刻时光酒店管理系统-田园/DazongTui.h
|
6dd58cab03797d7f29e2856737ce9d5c460050c0
|
[] |
no_license
|
YvonneTian2016/HotelSystem
|
862233a5ee08466bf17367c0ea43208a6d76cf31
|
3189d6471c7f7137f4a340cb7b3d3404f071abac
|
refs/heads/master
| 2020-07-21T23:10:34.742959
| 2016-11-15T17:59:16
| 2016-11-15T17:59:16
| 73,838,958
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 511
|
h
|
DazongTui.h
|
#pragma once
// DazongTui 对话框
class CHotel;
class DazongTui : public CDialog
{
DECLARE_DYNAMIC(DazongTui)
public:
DazongTui(CWnd* pParent = NULL); // 标准构造函数
virtual ~DazongTui();
// 对话框数据
enum { IDD = IDD_DAZONGTUI };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
CString name_tui;
afx_msg void OnBnClickedOk();
void sethotel(CHotel *p);
private:
CHotel* Dazongtui;
};
|
b45c417fe69983c3aa3dfbbe393aefa7e5c57f84
|
10d63c0b22fa42e4c990668e0edccbefc9f18c14
|
/srchybrid/ATLServer/source/SProxy/WSDLBindingParser.h
|
0c3ef016d6cf14f67bb1d94e2a296c5f5fa55499
|
[
"MS-PL"
] |
permissive
|
e1z0/sMule
|
ce0fdc8e3c876d24fc68be35ff3871f865ff190c
|
f303e8d1a667eeb975f31e589e69c20a4c246a4d
|
refs/heads/master
| 2021-05-04T11:25:55.756394
| 2018-08-19T08:55:38
| 2018-08-19T08:55:38
| 55,499,230
| 5
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,834
|
h
|
WSDLBindingParser.h
|
//
// WSDLBindingParser.h
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
#pragma once
#include "stdafx.h"
#include "Parser.h"
class CWSDLBinding;
class CWSDLBindingParser : public CParserBase
{
private:
CWSDLBinding *m_pBinding;
public:
inline CWSDLBindingParser(ISAXXMLReader *pReader, CParserBase *pParent, DWORD dwLevel, CWSDLBinding *pBinding = NULL)
:CParserBase(pReader, pParent, dwLevel), m_pBinding(pBinding)
{
}
BEGIN_XMLTAG_MAP()
XMLTAG_ENTRY_EX("binding", SOAP_NAMESPACEA, OnSoapBinding)
XMLTAG_ENTRY_EX("operation", WSDL_NAMESPACEA, OnOperation)
XMLTAG_ENTRY_EX("binding", HTTP_NAMESPACEA, OnHttpBinding)
XMLTAG_ENTRY_EX("documentation", WSDL_NAMESPACEA, OnDocumentation)
// extensibility elements
// XMLTAG_ENTRY_EX("class", SUDS_NAMESPACEA, OnSudsClass)
// XMLTAG_ENTRY_EX("binding", STK_PREFERREDENCODING_NAMESPACEA, OnStkPreferredBinding)
END_XMLTAG_MAP()
BEGIN_XMLATTR_MAP()
XMLATTR_ENTRY("name", OnName)
XMLATTR_ENTRY("type", OnType)
END_XMLATTR_MAP()
TAG_METHOD_DECL(OnDocumentation);
TAG_METHOD_DECL(OnOperation);
TAG_METHOD_DECL(OnSoapBinding);
TAG_METHOD_DECL(OnHttpBinding);
// TAG_METHOD_DECL(OnSudsClass);
// TAG_METHOD_DECL(OnStkPreferredBinding);
ATTR_METHOD_DECL(OnName);
ATTR_METHOD_DECL(OnType);
inline CWSDLBinding * GetBinding()
{
return m_pBinding;
}
inline void SetBinding(CWSDLBinding * pBinding)
{
ATLASSERT( pBinding != NULL );
m_pBinding = pBinding;
}
HRESULT __stdcall startPrefixMapping(
const wchar_t *wszPrefix,
int cchPrefix,
const wchar_t *wszUri,
int cchUri);
HRESULT OnUnrecognizedTag(
const wchar_t *wszNamespaceUri, int cchNamespaceUri,
const wchar_t *wszLocalName, int cchLocalName,
const wchar_t *wszQName, int cchQName,
ISAXAttributes *pAttributes) throw();
};
|
027d374a752fc28a5afac0cb6c96b6b475ccecc1
|
927aef49c7ad31827a5eedd64bd3649d3144af2f
|
/sample.cpp
|
65fd7368ce29a1349be514211641fd541c5828a9
|
[] |
no_license
|
aryan5602/project2
|
fdc4b0dd27d9719684633a5809a2a5351394a7b0
|
4133199de3fba0255ec49f7cb7f3ac7bb9067e78
|
refs/heads/main
| 2023-07-29T15:18:02.781594
| 2021-09-09T05:15:46
| 2021-09-09T05:15:46
| 404,594,475
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,257
|
cpp
|
sample.cpp
|
#include <iostream>
#include <string.h>
#include <fstream>
using namespace std;
int main()
{
int a[10];
int s;
int n;
string tp[10], conv[10];
ifstream file("input.txt");
string str;
int i = 0;
while (getline(file, str))
{
string b = str.substr(0, 3);
string c = str.substr(4, 4);
c = c.substr(0, 3);
string d = str.substr(8, 12);
s = stoi(b);
a[i] = s;
tp[i] = c;
conv[i] = d;
i++;
}
for (int j = 0; j < i; j++)
{
for (int k = j + 1; k < i; k++)
{
if (a[j] == a[k])
{
string p = tp[j] + ">" + tp[k];
tp[k] = "";
tp[j] = p;
a[k] = 9956;
}
}
}
ofstream f;
string q;
f.open("output.txt");
for (int l = 0; l < 5; l++)
{
if (a[l] != 9956)
{
q = to_string(a[l]) + "-start>" + tp[l] + ">" + conv[l];
f << q;
f << endl;
}
}
cout << "Data converted and inserted to output.txt file\n";
f.close();
cout << "Press any key and then press enter to quit\n";
cin >> n;
}
|
eb6a28b53c175982d5f4044e1381501d6722298c
|
6ea2685ec9aa4be984ea0febb7eefc2f3bc544c9
|
/NetGen.h
|
687ba0e55eac0ef5976c72bf68172e2cf05f9d43
|
[] |
no_license
|
vpatrinica/pernute
|
f047445a373f79209f0e32c1bf810d90c3d6289f
|
e2c0bf4161ccb4e768e7b64ecd2a021e51319383
|
refs/heads/master
| 2021-01-02T22:31:07.174479
| 2010-05-13T21:13:34
| 2010-05-13T21:13:34
| 39,997,926
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,111
|
h
|
NetGen.h
|
#pragma once
#if defined(_DEBUG) && !defined(AC_FULL_DEBUG)
#error _DEBUG should not be defined except in internal Adesk debug builds
#endif
#include "aced.h"
#include "dbsymtb.h"
#include "dbapserv.h"
#include "acgi.h"
#include "tchar.h"
#include <list>
#include <stdio.h>
#include <iostream>
#include <ADSLIB.H>
#include "ResbufPtr.h"
#include "FramePointsBuilder.h"
#include "LineFrameBuilder.h"
#include "dbobjptr.h"
#include "dbspline.h"
#include "FramePointsConstructor.h"
#include "InteriorPointsConstructor.h"
#include "InputReader.h"
class NetGen: public AcDbEntity
{
public:
ACRX_DECLARE_MEMBERS(NetGen);
NetGen();
virtual ~NetGen();
void readInput();
Acad::ErrorStatus processInput(AcDbObjectIdArray& );
Acad::ErrorStatus doNet();
Acad::ErrorStatus outputNet();
protected:
virtual Adesk::Boolean subWorldDraw(AcGiWorldDraw* );
Acad::ErrorStatus subTransformBy(const AcGeMatrix3d& );
private:
InputReader* _inputReader;
FramePointsConstructor * _fpConstructor;
InteriorPointsConstructor * _ipConstructor;
};
|
0e89ca7c5c1f1a17565c55864b4d151097048d97
|
7138b963e54e46d37ac89ed6c2cd748200f8eed7
|
/PopulatingNextRightPointersInEachNodeII/PopulatingNextRightPointersInEachNode2/PopulatingNextRightPointersInEachNode2/PopulatingNextRightPointersInEachNode2.cpp
|
5a4d8f1d93ca85087c3f82efdc20f0a716343bc1
|
[] |
no_license
|
zhumj13/LeetCode
|
5c94b1db739f10d2cc3fe40233a8dd45dbe9759d
|
4fe327f14e271c85d1b5e1c08721bac4f56ee5cc
|
refs/heads/master
| 2020-05-26T07:13:26.888917
| 2014-11-22T04:49:24
| 2014-11-22T04:49:24
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 2,432
|
cpp
|
PopulatingNextRightPointersInEachNode2.cpp
|
// PopulatingNextRightPointersInEachNode2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <queue>
//解题思路:如果右孩子不为空 则next 为右孩子。
// 否则,找父亲的next(uncle) 有左孩子则找左孩子,没有左孩子则找右孩子,都没有则找下一个uncle .
// 因为少考虑了一种情况(和父亲相连的uncle可能是没有孩子的,应该加个while)导致一直没过
using namespace std;
struct TreeLinkNode
{
int val;
TreeLinkNode *left,*right,*next;
TreeLinkNode(int x):val(x),left(NULL),right(NULL),next(NULL){}
};
class Solution {
public:
void connect(TreeLinkNode *root)
{
if(root==NULL)
return;
queue<TreeLinkNode*> nodeQueue;
TreeLinkNode *parent = new TreeLinkNode(0);
nodeQueue.push(root);
while(!nodeQueue.empty())
{
parent = nodeQueue.front();
nodeQueue.pop();
if(parent==NULL)
return;
TreeLinkNode *left=parent->left;
TreeLinkNode *right=parent->right;
if(left!=NULL)
{
if(right!=NULL)
{
left->next=right;
}else if(parent->next!=NULL)
{
TreeLinkNode *uncle= parent->next;
while(uncle!=NULL&&!GetNextFromUncle(uncle, left))
{
uncle=uncle->next;
if(uncle!=NULL)
GetNextFromUncle(uncle,left);
}
}
nodeQueue.push(left);
}
if(right!=NULL)
{
if(parent->next!=NULL)
{
TreeLinkNode *uncle= parent->next;
while(uncle!=NULL&&!GetNextFromUncle(uncle, right))
{
uncle=uncle->next;
if(uncle!=NULL)
GetNextFromUncle(uncle,right);
}
}
nodeQueue.push(right);
}
}
}
bool GetNextFromUncle( TreeLinkNode * uncle, TreeLinkNode * now )
{
TreeLinkNode *uncleLeft=uncle->left;
TreeLinkNode *uncleRight=uncle->right;
if(uncleLeft!=NULL)
{
now->next=uncleLeft;
return true;
}else if(uncleRight!=NULL)
{
now->next=uncleRight;
return true;
}
return false;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
TreeLinkNode *a=new TreeLinkNode(1);
TreeLinkNode *b=new TreeLinkNode(2);
TreeLinkNode *c=new TreeLinkNode(3);
TreeLinkNode *d=new TreeLinkNode(4);
TreeLinkNode *e=new TreeLinkNode(5);
TreeLinkNode *f=new TreeLinkNode(6);
TreeLinkNode *g=new TreeLinkNode(7);
a->left=b;
a->right=c;
b->left=d;
b->right=e;
c->right=f;
d->left=g;
Solution solution;
solution.connect(a);
return 0;
}
|
625a782f67e9586c75846e8ac7964fa9fb5ec9b1
|
63c71060f36866bca4ac27304cef6d5755fdc35c
|
/src/WebServerTorturer/WebCltReq.h
|
a98c5bf46988ec269dece7093b3e9daf2a6042e7
|
[] |
no_license
|
15831944/barry_dev
|
bc8441cbfbd4b62fbb42bee3dcb79ff7f5fcaf8a
|
d4a83421458aa28ca293caa7a5567433e9358596
|
refs/heads/master
| 2022-03-24T07:00:26.810732
| 2015-12-22T07:19:58
| 2015-12-22T07:19:58
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 819
|
h
|
WebCltReq.h
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2005
// Packet Engineering, Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification is not permitted unless authorized in writing by a duly
// appointed officer of Packet Engineering, Inc. or its derivatives
//
//
// Modification History:
// Created: 10/18/2010 by Jozhi
////////////////////////////////////////////////////////////////////////////
#ifndef AOS_WebServerTorturer_WebCltReq_h
#define AOS_WebServerTorturer_WebCltReq_h
#include "Util/RCObject.h"
#include "Util/RCObjImp.h"
#include "WebServerTorturer/Ptrs.h"
class AosWebCltReq : virtual public OmnRCObject
{
public:
virtual bool repReceived(const OmnConnBuffPtr &buff) = 0;
};
#endif
|
d2d682b2a9fd7ff12c2153706bc9c8a34bb6b91f
|
d4c71bc2797d54131b30a0f24af2d13b2f068927
|
/POSD_ERDiagram/ER_GUIAddEntityState.h
|
3b6066ed18e3e4d7054cd1cfdc2b82427f3adf2e
|
[] |
no_license
|
candybaby/posd-project
|
ecf04459a6a3b62b9e8d5365d76ab6a02cd74a81
|
afa3d39f9f8d9457ed462fd9a224687a150424d6
|
refs/heads/master
| 2020-05-29T16:35:25.637248
| 2013-12-29T13:30:43
| 2013-12-29T13:30:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 290
|
h
|
ER_GUIAddEntityState.h
|
#pragma once
#ifndef _ER_GUIADDENTITYSTATE_
#define _ER_GUIADDENTITYSTATE_
#include "ER_GUIAddNodeState.h"
class ER_GUIAddEntityState : public ER_GUIAddNodeState
{
public:
ER_GUIAddEntityState(ER_DiagramScene*, QGraphicsItem*);
void mousePressEvent(QGraphicsSceneMouseEvent*);
};
#endif
|
7de5116cddd22600b1c888b5fbb86e0f1a26cdac
|
fd8a4a41873c63e656f9961d976edee282c9a97a
|
/auduino/auduino.ino
|
48b52fdc9ba3c1b0290610e37052e7013f81e441
|
[] |
no_license
|
Maushimo/AirFlute_-PhysicalComputingFinal-
|
f51d635af01a5bf552d57146dd2dfe8780ec97d5
|
b8e1d80bfa471954928899838f46017dfee47c8e
|
refs/heads/master
| 2021-01-19T21:15:28.146681
| 2017-04-18T14:16:42
| 2017-04-18T14:16:42
| 88,632,336
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,847
|
ino
|
auduino.ino
|
/* ====Set analog pins==== */
const int tempSensorPin = A0;
const int ldrPin1 = A1;
const int ldrPin2 = A2;
const int ldrPin3 = A3;
/* ====Calibration Variables==== */
/* Temp Sensor Values */
int tempSensorVal;
// variable to calibrate low value
int tempSensorLow = 1023;
// variable to calibrate high value
int tempSensorHigh = 0;
/* LDR Values */
int ldr1Val;
int ldr1Low = 1023;
int ldr1High = 0;
int ldr2Val;
int ldr2Low = 1023;
int ldr2High = 0;
int ldr3Val;
int ldr3Low = 1023;
int ldr3High = 0;
//Light PINs
const int greenLEDPin = 10;
const int blueLEDPin = 9;
const int redLEDPin = 11;
void setup() {
Serial.begin(9600); //Set data rate for serial
//LED pin setup
pinMode(greenLEDPin, OUTPUT);
pinMode(blueLEDPin, OUTPUT);
pinMode(redLEDPin, OUTPUT);
/* Calibrate BLOWEY */
while (millis() < 5000) {
/* TEMP SENSOR CALIBRATION */
// record the maximum sensor value
tempSensorVal = analogRead(tempSensorPin);
if (tempSensorVal > tempSensorHigh) {
tempSensorHigh = tempSensorVal;
}
// record the minimum sensor value
if (tempSensorVal < tempSensorLow) {
tempSensorLow = tempSensorVal;
}
/* LDR CALIBRATION */
ldr1Val = analogRead(ldrPin1);
if(ldr1Val > ldr1High){
ldr1High = ldr1Val;
}
if(ldr1Val < ldr1Low){
ldr1Low = ldr1Val;
}
ldr2Val = analogRead(ldrPin2);
if(ldr2Val > ldr2High){
ldr2High = ldr2Val;
}
if(ldr2Val < ldr2Low){
ldr2Low = ldr2Val;
}
ldr3Val = analogRead(ldrPin3);
if(ldr3Val > ldr3High){
ldr3High = ldr3Val;
}
if(ldr3Val < ldr3Low){
ldr3Low = ldr3Val;
}
}
}
void loop() {
/* Temperature sensor (BLOWEY) stuff */
tempSensorVal = analogRead(tempSensorPin);
int blow = map(tempSensorVal, tempSensorLow, tempSensorHigh, 0, 50);
/* LDR (HOLEY) stuff */
int ldr1Val = analogRead(ldrPin1);
int ldr2Val = analogRead(ldrPin2);
int ldr3Val = analogRead(ldrPin3);
int note1 = (map(ldr1Val, ldr1Low, ldr1High, 50, 100))*0.5;
int note2 = (map(ldr2Val, ldr2Low, ldr2High, 50, 100));
int note3 = (map(ldr3Val, ldr3Low, ldr3High, 50, 100))*1.5;
//combined value used to pass in frequency data to max
int allLdr = (note1 + note2 + note3);
//LED brightness
int blueBrightness = ldr1Val/8;
int greenBrightness = ldr2Val/8;
int redBrightness = ldr3Val/8;
//LED values
int blueLedVal = (ldr1Val/2)+redBrightness;
delay(10);
int greenLedVal = (ldr2Val/2)+greenBrightness;
delay(10);
int redLedVal = (ldr3Val/2)+blueBrightness;
delay(10);
//Write values to LEDs
analogWrite(redLEDPin, redLedVal);
analogWrite(greenLEDPin, greenLedVal);
analogWrite(blueLEDPin, blueLedVal);
Serial.print(blow);
Serial.print(" ");
Serial.print(abs(allLdr));
Serial.print(" ");
Serial.print("\r");
delay(50);
}
|
b6c0828ceaa40fdf96dd1075aaa4c336a98b633e
|
8bb4f45aaa8b5ab078edc42a881e2c2325b98227
|
/368.cpp
|
6df4906e968d1baaf9a12bc4c249f46f1e6d3e7e
|
[] |
no_license
|
chinawch007/LeetCode
|
7b6c219441da4d003111240622a92835720c1ac8
|
8fd6827a1252cffc71c53a0809728e3bd8fba139
|
refs/heads/master
| 2021-07-06T12:34:13.417269
| 2020-11-23T11:26:44
| 2020-11-23T11:26:44
| 208,131,573
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,113
|
cpp
|
368.cpp
|
//又快速筛出整除数的数吗
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
int sz = nums.size();
int* dp = new int[sz];
int* link = new int[sz];
int maxv = 0, maxi = 0;
sort(nums.begin(), nums.end());
for(int i = 0; i < sz; ++i)
{
dp[i] = 1;
link[i] = -1;
for(int j = i-1; j >= 0; --j)
{
if(nums[i] % nums[j] == 0 && dp[j] + 1 > dp[i])
{
dp[i] = dp[j] + 1;
link[i] = j;
}
}
if(dp[i] > maxv)
{
maxv = dp[i];
maxi = i;
}
}
int* res = new int[maxv];
for(int i = maxi, j = maxv-1; i != -1 && j >= 0; i = link[i], --j)
{
res[j] = nums[i];
}
vector<int> ret;
for(int i = 0; i < maxv; ++i)
ret.push_back(res[i]);
return ret;
}
};
|
bfaa21ee55237b3c6028b483c30300d5c1ec4c24
|
cf4b30d6a41318674a997408413ca009d47ed1f7
|
/Code/Dx11_2D/SquadEdditScene.cpp
|
8d22e12815d90b5dfae6f35f8feb1dd8d3909054
|
[] |
no_license
|
FXfireKR/GFL_Project_DX11
|
d6799f74e2c2820881090fefe42463bb43939531
|
2dd932f398f2f83472d8c57478c41674c71985ca
|
refs/heads/master
| 2022-11-10T20:30:25.514786
| 2020-06-30T16:28:33
| 2020-06-30T16:28:33
| 217,483,471
| 1
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 17,179
|
cpp
|
SquadEdditScene.cpp
|
#include "stdafx.h"
#include "SquadEdditScene.h"
SquadEdditScene::SquadEdditScene()
{
}
SquadEdditScene::~SquadEdditScene()
{
}
void SquadEdditScene::init()
{
LOAD->Add_LoadTray("Squad_1_Already", "Texture2D/Squad1Already.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE); // 1 제대 배치중
LOAD->Add_LoadTray("Squad_2_Already", "Texture2D/Squad2Already.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE); // 2 제대 배치중
LOAD->Add_LoadTray("Squad_3_Already", "Texture2D/Squad3Already.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE); // 3 제대 배치중
LOAD->Add_LoadTray("Squad_1_Leader", "Texture2D/Squad1Leader.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("Squad_2_Leader", "Texture2D/Squad2Leader.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("Squad_3_Leader", "Texture2D/Squad3Leader.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("TurnBack", "Texture2D/TurnBack.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("SquadEmit", "Texture2D/SquadEmit.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("SquadBar", "Texture2D/SquadBar.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("SquadBar_s", "Texture2D/SquadBar_select.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("editSceneBk", "Texture2D/editSceneBk.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("gradiantBlack", "Texture2D/gradiantBlack.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("SlotSquad", "Texture2D/SlotSquad.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("HomeButton", "Texture2D/HomeButton.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("AllCard", "Texture2D/AllCard.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("SG_icon", "Texture2D/SG_icon.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("SMG_icon", "Texture2D/SMG_icon.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("AR_icon", "Texture2D/AR_icon.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("SR_icon", "Texture2D/SR_icon.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("RF_icon", "Texture2D/RF_icon.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("MG_icon", "Texture2D/MG_icon.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
LOAD->Add_LoadTray("HG_icon", "Texture2D/HG_icon.ab", LOADRESOURCE_TYPE::RESOURCE_IMAGE);
worldColor.a = 0.0f;
mode = SQUAD;
FocusSquad = 1;
FocusBox = -1;
showEquip = false;
virtualHeight = 0.0f;
virtualLimit = 0.0f;
asixVirtual = 0;
mouseDrag = false;
DWRITE->Create_TextField("SQUAD", L"맑은고딕", "NULL", 36, DWRITE_FONT_WEIGHT_BOLD);
DWRITE->Create_TextField("CHARA_NAME", L"맑은고딕", "NULL", 28, DWRITE_FONT_WEIGHT_MEDIUM);
DWRITE->Create_TextField("TITLE_NAME", L"맑은고딕", "NULL", 65, DWRITE_FONT_WEIGHT_BOLD);
mButton.insert(make_pair(SBUTTONS::HOME_BACK, Button(10, 10, 100, 85, ReturnBase_Select)));
mButton.insert(make_pair(SBUTTONS::TURN_BACK, Button(10, 0, 150, 90, ReturnSquad_Select)));
mButton.insert(make_pair(SBUTTONS::SELECT_SQUAD_1, Button(0, 200, 150, 100, ChangeSquad_Select)));
mButton.insert(make_pair(SBUTTONS::SELECT_SQUAD_2, Button(0, 320, 150, 100, ChangeSquad_Select)));
mButton.insert(make_pair(SBUTTONS::SELECT_SQUAD_3, Button(0, 440, 150, 100, ChangeSquad_Select)));
mButton.insert(make_pair(SBUTTONS::SELECT_CHARA_1, Button(180, 200, SQUAD_BOX_WIDTH, SQUAD_BOX_HEIGHT, InsertSelect)));
mButton.insert(make_pair(SBUTTONS::SELECT_CHARA_2, Button(400, 200, SQUAD_BOX_WIDTH, SQUAD_BOX_HEIGHT, InsertSelect)));
mButton.insert(make_pair(SBUTTONS::SELECT_CHARA_3, Button(620, 200, SQUAD_BOX_WIDTH, SQUAD_BOX_HEIGHT, InsertSelect)));
mButton.insert(make_pair(SBUTTONS::SELECT_CHARA_4, Button(840, 200, SQUAD_BOX_WIDTH, SQUAD_BOX_HEIGHT, InsertSelect)));
mButton.insert(make_pair(SBUTTONS::SELECT_CHARA_5, Button(1060, 200, SQUAD_BOX_WIDTH, SQUAD_BOX_HEIGHT, InsertSelect)));
vBox.clear();
vCharacter.clear();
vCharacter.resize(5, "");
for (auto& it : PLAYER->getPlayerTaticDoll().getAllDolls()) // get List of Player's TacticalDoll
it.second->LoadTray_ImageList();
changeScene = false;
// UnLoad List
vLoadList.clear();
for (auto& it : LOAD->getLoadList())
vLoadList.push_back(LoadResourceData(it->key, it->type));
for (int i = 0; i < vCharacter.size(); ++i)
{
if (i < PLAYER->getPlayerSquad(FocusSquad)->squadMember.size())
vCharacter[i] = PLAYER->getPlayerSquad(FocusSquad)->squadMember[i]->keys.cardNormalKey;
else
vCharacter[i] = "";
}
atlas = nullptr;
// Loading Setting
LOAD->setAutoInit(false);
LOAD->setNextScene("SQUAD");
LOAD->setLoadImageKey("ShootRange");
LOAD->mallocThread();
SCENE->changeScene("LOAD");
SOUND->setVolume(SOUND_CHANNEL::CH_SOUND1, 0.0f);
CAMERA->CameraReset();
}
void SquadEdditScene::release()
{
}
void SquadEdditScene::update()
{
CAMERA->setCameraFix(true);
if (!changeScene)
{
SOUND->Play_Sound(SOUND_CHANNEL::CH_SOUND1, "FormationLoop", 0.25f);
SOUND->setVolume(SOUND_CHANNEL::CH_SOUND1, worldColor.a < 0.15f ? worldColor.a : 0.15f);
worldColor.a = worldColor.a < 1.0f ? worldColor.a + DELTA() : 1.0f;
switch (mode)
{
case ALL:
All_Update();
break;
case SQUAD:
Squad_Update();
break;
}
}
else
{
if (worldColor.a > 0.0f)
worldColor.a -= DELTA() * 2.0f;
else
{
worldColor.a = 0.0f;
LOAD->insertUnLoadList(vLoadList);
SOUND->Stop_Sound(SOUND_CHANNEL::CH_SOUND1, "FormationLoop");
SOUND->setVolume(SOUND_CHANNEL::CH_SOUND1, 0.0f);
LOAD->setAutoInit(true);
LOAD->setNextScene("LOBBY");
LOAD->setLoadImageKey("ShootRange");
SCENE->changeScene("UNLOAD");
SOUND->setVolume(SOUND_CHANNEL::CH_SOUND1, 0.0f);
}
}
}
void SquadEdditScene::render()
{
switch (mode)
{
case ALL:
All_Render();
break;
case SQUAD:
Squad_Render();
break;
}
}
void SquadEdditScene::Squad_Update()
{
if (KEYMANAGER->isKeyDown(VK_LBUTTON))
{
for (auto& it : mButton) {
if (ptInRect(it.second.box, g_ptMouse))
it.second.ClickAction(this);
}
}
KeyInputAction();
}
void SquadEdditScene::Squad_Render()
{
DRAW->render("editSceneBk", Vector2(WINSIZEX, WINSIZEY), Vector2(WINSIZEX*0.5f, WINSIZEY*0.5f));
DRAW->render("gradiantBlack", Vector2(WINSIZEX, 100), Vector2(WINSIZEX*0.5f, 50));
DWRITE->ChangeText("TITLE_NAME", "SQUAD");
DWRITE->TextRender("TITLE_NAME", 1045.0f, 0.0f, ColorF(0.8, 0.8, 0.8));
for (int i = 0; i < vCharacter.size(); ++i) {
auto key = vCharacter[i];
if (key.size() < 2) continue;
DRAW->render(PLAYER->getPlayerSquad(FocusSquad)->squadMember[i]->keys.cardNormalKey,
Vector2((SQUAD_BOX_H_WIDTH * 2) - 4, (SQUAD_BOX_H_HEIGHT * 2) - 4),
Vector2(180 + (i * (SQUAD_BOX_H_WIDTH + 130) + SQUAD_BOX_H_WIDTH), 200 + SQUAD_BOX_H_HEIGHT));
}
DRAW->render("HomeButton", Vector2(100, 85),
Vector2(mButton[SBUTTONS::HOME_BACK].box.left + 50, mButton[SBUTTONS::HOME_BACK].box.top + 40));
for (int i = (int)SBUTTONS::SELECT_SQUAD_1; i < (int)SBUTTONS::SELECT_CHARA_1; ++i) {
DRAW->render(FocusSquad == i ? "SquadBar_s" : "SquadBar",
Vector2(150, 100), Vector2(mButton[(SBUTTONS)i].box.left + 75, mButton[(SBUTTONS)i].box.top + 50));
DWRITE->ChangeText("SQUAD", "%d제대", (SBUTTONS)i);
DWRITE->TextRender("SQUAD", mButton[(SBUTTONS)i].box.left, mButton[(SBUTTONS)i].box.top + 25, 150, 100,
ColorF(0, 0, 0), DWRITE_TEXT_ALIGNMENT::DWRITE_TEXT_ALIGNMENT_CENTER);
}
Squad_render_Character();
}
void SquadEdditScene::Squad_render_Character()
{
for (int i = (int)SBUTTONS::SELECT_CHARA_1; i < (int)SBUTTONS::END; ++i) {
D2D->renderRect(mButton[(SBUTTONS)i].box.left, mButton[(SBUTTONS)i].box.top,
mButton[(SBUTTONS)i].box.right - mButton[(SBUTTONS)i].box.left,
mButton[(SBUTTONS)i].box.bottom - mButton[(SBUTTONS)i].box.top, ColorF(0, 0, 0));
atlas = PLAYER->getPlayerSquad(FocusSquad)->squadMember.count(i - 4) ?
IMAGEMAP->getUiAtlas("InstOvSlot") : IMAGEMAP->getUiAtlas("InstSlot");
DRAW->render(atlas->textureKey, atlas->alphaTexKey, Vector2(SQUAD_BOX_H_WIDTH, SQUAD_BOX_H_HEIGHT),
Vector2(mButton[(SBUTTONS)i].box.left + SQUAD_BOX_H_WIDTH, mButton[(SBUTTONS)i].box.top + SQUAD_BOX_H_HEIGHT),
atlas->mixTexCoord, atlas->maxTexCoord);
}
for (auto& it : PLAYER->getPlayerSquad(FocusSquad)->squadMember) {
int chara = (int)SBUTTONS::SELECT_CHARA_1;
DWRITE->Change_Text("CHARA_NAME", it.second->getName());
chara += it.second->getID()->SquadMem_ID;
DWRITE->TextRender("CHARA_NAME", mButton[(SBUTTONS)chara].box.left, mButton[(SBUTTONS)chara].box.bottom -
(SQUAD_BOX_H_HEIGHT * 0.74f) + 5, 180, 40, ColorF(1, 1, 1), DWRITE_TEXT_ALIGNMENT_CENTER);
string key;
switch (it.second->getWeaponType())
{
case TWT_AR:
key = "AR_icon";
break;
case TWT_RF:
key = "RF_icon";
break;
case TWT_SR:
key = "SR_icon";
break;
case TWT_MG:
key = "MG_icon";
break;
case TWT_SG:
key = "SG_icon";
break;
case TWT_HG:
key = "HG_icon";
break;
case TWT_SMG:
key = "SMG_icon";
break;
}
DRAW->render(key, Vector2(70, 35),
Vector2(mButton[(SBUTTONS)chara].box.left + 38, mButton[(SBUTTONS)chara].box.top + 20), COLR(1, 1, 1, 0.7));
}
}
void SquadEdditScene::All_Update()
{
// Wheel Use Code
if (whlCount > 0) {
virtualHeight -= DELTA() * 1000.0f;
whlCount = 0;
}
else if (whlCount < 0) {
virtualHeight += DELTA() * 1000.0f;
whlCount = 0;
}
// Moude Use Code
if (g_ptMouse.x > 1150) {
if (KEYMANAGER->isKeyDown(VK_LBUTTON)) {
asixVirtual = g_ptMouse.y;
mouseDrag = true;
}
if (KEYMANAGER->isKeyUp(VK_LBUTTON))
mouseDrag = false;
if (mouseDrag) {
if (asixVirtual > g_ptMouse.y)
virtualHeight -= DELTA() * 700.0f;
else if (asixVirtual < g_ptMouse.y)
virtualHeight += DELTA() * 700.0f;
asixVirtual = g_ptMouse.y;
}
}
if (virtualHeight > 0)
virtualHeight = 0.0f;
else if (virtualHeight < virtualLimit)
virtualHeight = virtualLimit;
for (size_t i = 0; i < vBox.size(); ++i) {
vBox[i].box = D2DRectMake(vBox[i].pos.x, vBox[i].pos.y + virtualHeight,
CHARACTER_BOX_WID, CHARACTER_BOX_HEI);
}
if (KEYMANAGER->isKeyDown(VK_LBUTTON)) {
for (size_t i = 0; i < vBox.size(); ++i) {
if (ptInRect(vBox[i].box, g_ptMouse)) {
if (vBox[i].adress != nullptr) {
if (PLAYER->getPlayerSquad(FocusSquad)->squadMember.count(FocusBox)) {
if (PLAYER->getPlayerSquad(FocusSquad)->squadMember[FocusBox]->getID()->All_ID != i - 1) {
if (PLAYER->getPlayerTaticDoll().changeSquadTacDoll(FocusSquad, i - 1, FocusBox) != E_FAIL)
SOUND->Play_Effect(CH_VOICE,
PLAYER->getPlayerTaticDoll().getAllDolls().at(i - 1)->keys.SOUND_FORMATION, 0.15f);
}
}
else {
if (PLAYER->getPlayerSquad(FocusSquad)->squadMember.size() < 5) {
if (PLAYER->getPlayerTaticDoll().insertSquadTacDoll(FocusSquad, i - 1) != E_FAIL) {
SOUND->Play_Effect(CH_VOICE,
PLAYER->getPlayerTaticDoll().getAllDolls().at(i - 1)->keys.SOUND_FORMATION, 0.15f);
}
else {
}
}
}
}
else {
if (PLAYER->getPlayerTaticDoll().getSquadMember(FocusSquad, FocusBox) != nullptr)
PLAYER->getPlayerTaticDoll().exitSquadTacDoll(FocusSquad, FocusBox);
}
for (int i = 0; i < vCharacter.size(); ++i)
{
if (i < PLAYER->getPlayerSquad(FocusSquad)->squadMember.size())
vCharacter[i] = PLAYER->getPlayerSquad(FocusSquad)->squadMember[i]->keys.cardNormalKey;
else
vCharacter[i] = "";
}
mode = SHOWMODE::SQUAD;
mouseDrag = false;
break;
}
}
if (mode == ALL) {
if (ptInRect(mButton[SBUTTONS::TURN_BACK].box, g_ptMouse))
mButton[SBUTTONS::TURN_BACK].ClickAction(this);
}
}
}
void SquadEdditScene::All_Render()
{
DRAW->render("editSceneBk", Vector2(WINSIZEX, WINSIZEY), Vector2(WINSIZEX*0.5f, WINSIZEY*0.5f));
for (size_t i = 0; i < vBox.size(); ++i) {
FLOAT wid = vBox[i].box.right - vBox[i].box.left;
FLOAT hei = vBox[i].box.bottom - vBox[i].box.top;
FLOAT halfWid = wid * 0.5f;
FLOAT halfHei = hei * 0.5f;
Vector2 rendPos;
if (vBox[i].adress != nullptr) {
BaseTaticDoll* focusedTdoll = ((BaseTaticDoll*)vBox[i].adress);
rendPos = Vector2(vBox[i].pos.x + halfWid, vBox[i].pos.y + halfHei + virtualHeight);
DRAW->render(focusedTdoll->keys.cardNormalKey, Vector2(wid, hei), rendPos);
DRAW->render("AllCard", Vector2(wid, hei), rendPos);
DWRITE->ChangeText("CHARA_NAME", focusedTdoll->keys.name);
DWRITE->TextRender("CHARA_NAME", rendPos.x - halfWid, rendPos.y + halfHei - 60, wid, 40, ColorF(1, 1, 1),
DWRITE_TEXT_ALIGNMENT_CENTER);
string key;
switch (focusedTdoll->getWeaponType())
{
case TWT_AR:
key = "AR_icon";
break;
case TWT_RF:
key = "RF_icon";
break;
case TWT_SR:
key = "SR_icon";
break;
case TWT_MG:
key = "MG_icon";
break;
case TWT_SG:
key = "SG_icon";
break;
case TWT_HG:
key = "HG_icon";
break;
case TWT_SMG:
key = "SMG_icon";
break;
}
DRAW->render(key, Vector2(74, 43),
Vector2(vBox[i].pos.x + 37 + 2, vBox[i].pos.y + 21 + 2), COLR(1, 1, 1, 0.8));
if (focusedTdoll->getID()->Squad_ID != -1) {
DRAW->render("bkGuard", Vector2(wid, hei), rendPos, COLR(1, 1, 1, 0.4f));
string key = ConvertFormat("Squad_%d_Already", focusedTdoll->getID()->Squad_ID);
DRAW->render(key, Vector2(65, 70), Vector2(rendPos.x + halfWid - 32, rendPos.y - halfHei + 35));
}
}
else {
DRAW->render("SquadEmit", Vector2(wid, hei),
Vector2(vBox[i].pos.x + halfWid, vBox[i].pos.y + halfHei + virtualHeight));
}
}
DRAW->render("gradiantBlack", Vector2(WINSIZEX, 100), Vector2(WINSIZEX*0.5f, 50));
DRAW->render("TurnBack", Vector2(150, 90), Vector2(mButton[SBUTTONS::TURN_BACK].box.left + 75,
mButton[SBUTTONS::TURN_BACK].box.top + 45));
DWRITE->ChangeText("TITLE_NAME", "T-DOLL");
DWRITE->TextRender("TITLE_NAME", 1045.0f, 0.0f, ColorF(0.8, 0.8, 0.8));
}
void SquadEdditScene::KeyInputAction()
{
// 장착된 장비 확인
if (KEYMANAGER->isKeyUp(VK_TAB))
showEquip = showEquip ? false : true;
}
void SquadEdditScene::Allocate_Box_All()
{
auto& pTacDoll = PLAYER->getPlayerTaticDoll().getAllDolls();
size_t counter = 0;
vBox.clear();
vBox.reserve(pTacDoll.size() + 1);
// Insert Null Character For Out of Character
selectBox outer;
outer.pos = Vector2(20 + (counter % WIDTH_COUNT) * CHARACTER_BLANK_WID,
120 + (counter / WIDTH_COUNT) * CHARACTER_BLANK_HEI);
outer.box = D2DRectMake(outer.pos.x, outer.pos.y, CHARACTER_BOX_WID, CHARACTER_BOX_HEI);
outer.adress = nullptr;
vBox.push_back(outer);
++counter;
for (auto& iter : pTacDoll) {
selectBox _new;
_new.pos = Vector2(20 + (counter % WIDTH_COUNT) * CHARACTER_BLANK_WID,
120 + (counter / WIDTH_COUNT) * CHARACTER_BLANK_HEI);
_new.box = D2DRectMake(_new.pos.x, _new.pos.y, CHARACTER_BOX_WID, CHARACTER_BOX_HEI);
_new.adress = iter.second;
vBox.push_back(_new);
++counter;
}
virtualLimit = (float)(((int)vBox.size()) / WIDTH_COUNT) * CHARACTER_BLANK_HEI;
if (vBox.size() > WIDTH_COUNT)
virtualLimit -= (CHARACTER_BLANK_HEI * 0.5f);
virtualLimit *= -1.0f;
}
void SquadEdditScene::InsertSelect(void * obj)
{
SquadEdditScene* object = (SquadEdditScene*)obj;
for (auto& it : object->mButton) {
if (it.first < SBUTTONS::SELECT_CHARA_1 || it.first > SBUTTONS::SELECT_CHARA_5) continue;
if (ptInRect(it.second.box, g_ptMouse)) {
object->FocusBox = (int)(it.first) - (int)(SBUTTONS::SELECT_CHARA_1);
break;
}
}
object->mode = SHOWMODE::ALL;
object->showEquip = false;
object->Allocate_Box_All();
}
void SquadEdditScene::DeleteSelect(void * obj)
{
SquadEdditScene* object = (SquadEdditScene*)obj;
if (object->FocusBox != -1)
{
if (PLAYER->getPlayerTaticDoll().getSquadMember(object->FocusSquad, object->FocusBox) != nullptr)
{
PLAYER->getPlayerTaticDoll().exitSquadTacDoll(object->FocusSquad, object->FocusBox);
object->vBox.pop_back();
object->FocusBox = -1;
}
}
}
void SquadEdditScene::ChangeSquad_Select(void * obj)
{
SquadEdditScene* object = (SquadEdditScene*)obj;
for (auto& it : object->mButton) {
if (it.first < SBUTTONS::SELECT_SQUAD_1 || it.first > SBUTTONS::SELECT_SQUAD_3) continue;
if (ptInRect(it.second.box, g_ptMouse)) {
switch (it.first)
{
case SBUTTONS::SELECT_SQUAD_1:
case SBUTTONS::SELECT_SQUAD_2:
case SBUTTONS::SELECT_SQUAD_3:
object->FocusSquad = (int)it.first;
break;
default:
break;
}
for (int i = 0; i < object->vCharacter.size(); ++i)
{
if (i < PLAYER->getPlayerSquad(object->FocusSquad)->squadMember.size())
object->vCharacter[i] =
PLAYER->getPlayerSquad(object->FocusSquad)->squadMember[i]->keys.cardNormalKey;
else
object->vCharacter[i] = "";
}
break;
}
}
}
void SquadEdditScene::ReturnBase_Select(void * obj)
{
SquadEdditScene* object = (SquadEdditScene*)obj;
object->changeScene = true;
}
void SquadEdditScene::ReturnSquad_Select(void * obj)
{
SquadEdditScene* object = (SquadEdditScene*)obj;
if (object->mode == ALL)
object->mode = SQUAD;
}
|
818e7ff5d2411b81de538cfe1bcedcff765efc14
|
a3bb5629105cb51fcbc995434fd4cc07127ea406
|
/Aladdin/Aladdin/TileMap.cpp
|
8c1002ea6dff4fc642492f3709554454ac194f67
|
[] |
no_license
|
bachsoda326/directxGame
|
0aab196061ae9787e3033edaee0e06934564e226
|
769c237d1df5b6a515d1896d0813cdffa96a4e16
|
refs/heads/master
| 2022-03-21T04:47:19.256477
| 2019-12-27T17:43:27
| 2019-12-27T17:43:27
| 212,519,316
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,185
|
cpp
|
TileMap.cpp
|
#include "TileMap.h"
TileMap::TileMap()
{
}
TileMap::~TileMap()
{
}
void TileMap::LoadTileMap(int id, LPCSTR texMapPath, string txtMapPath)
{
this->id = id;
// tạo texture map
Textures::GetInstance()->Add(id, texMapPath, D3DCOLOR_XRGB(255, 255, 255));
fstream fs;
fs.open(txtMapPath);
fs >> numXTiles;
fs >> numYTiles;
// đặt lại size cho listTiles
listTiles.resize(numXTiles*numYTiles);
// set các tile = các số trong file
for (int i = 0; i < listTiles.size(); i++)
{
fs >> listTiles[i];
}
LPDIRECT3DTEXTURE9 texture = Textures::GetInstance()->Get(id);
D3DSURFACE_DESC desc;
texture->GetLevelDesc(0, &desc);
int numColumns = desc.Width / 32; // 32
//int numRows = desc.Height / 32; // 76
LPSPRITE sprite;
int tileIndex;
int xIndex, yIndex, left, top;
int xDrawIndex, yDrawIndex, xDraw, yDraw;
for (int i = 0; i < listTiles.size(); i++)
{
tileIndex = listTiles[i];
yIndex = tileIndex / numColumns;
xIndex = tileIndex - yIndex * numColumns;
left = xIndex * 32;
top = yIndex * 32;
// tạo sprite tương ứng vs các tile từ texture map
sprite = new Sprite(i, left, top, 32, 32, 0, 0, texture);
listSprites.push_back(sprite);
}
}
void TileMap::Render(Camera *camera)
{
// tính vị trí topleft và botright của camera
int xTopLeftCamera = camera->GetPosition().x - SCREEN_WIDTH / 2;
int yTopLeftCamera = camera->GetPosition().y - SCREEN_HEIGHT / 2;
int xBotRightCamera = camera->GetPosition().x + SCREEN_WIDTH / 2;
int yBotRightCamera = camera->GetPosition().y + SCREEN_HEIGHT / 2;
// tính vị trí topleft và botright của cell
int xTopLeftCell = xTopLeftCamera / CELL_SIZE;
int yTopLeftCell = yTopLeftCamera / CELL_SIZE;
int xBotRightCell = xBotRightCamera / CELL_SIZE;
int yBotRightCell = yBotRightCamera / CELL_SIZE;
// tính vị trí topleft và botright của tile
int xTopLeft = xTopLeftCell * CELL_SIZE / 32;
int yTopLeft = yTopLeftCell * CELL_SIZE / 32;
int xBotRight = ((xBotRightCell * CELL_SIZE) + CELL_SIZE) / 32;
int yBotRight = ((yBotRightCell * CELL_SIZE) + CELL_SIZE) / 32;
if (xBotRight >= numXTiles - 1)
xBotRight = numXTiles - 1;
if (yBotRight >= numYTiles - 1)
yBotRight = numYTiles - 1;
for (int x = xTopLeft; x <= xBotRight; x++)
{
for (int y = yTopLeft; y <= yBotRight; y++)
{
int xDrawIndex, yDrawIndex, xDraw, yDraw, i;
i = x + y * numXTiles;
yDrawIndex = i / numXTiles;
xDrawIndex = i - yDrawIndex * numXTiles;
xDraw = xDrawIndex * 32;
yDraw = yDrawIndex * 32;
D3DXVECTOR2 trans = D3DXVECTOR2(floor(SCREEN_WIDTH / 2 - Camera::GetInstance()->GetPosition().x), floor(SCREEN_HEIGHT / 2 - Camera::GetInstance()->GetPosition().y));
listSprites[i]->Draw(xDraw, yDraw, trans);
}
}
/*int xDrawIndex, yDrawIndex, xDraw, yDraw;
for (int i = 0; i < listSprites.size(); i++)
{
yDrawIndex = i / numXTiles;
xDrawIndex = i - yDrawIndex*numXTiles;
xDraw = xDrawIndex * 32;
yDraw = yDrawIndex * 32;
D3DXVECTOR2 trans = D3DXVECTOR2(floor(SCREEN_WIDTH / 2 - Camera::GetInstance()->GetPosition().x), floor(SCREEN_HEIGHT / 2 - Camera::GetInstance()->GetPosition().y));
listSprites[i]->Draw(xDraw, yDraw, trans);
}*/
}
|
a288b0d3f0b1c2b3c5e6c3153cee42a643888862
|
d3755489a99929208831865a853f1df264f79ac4
|
/pomelo-lua.h
|
09a71d54708eab55d73ef5bb8367d736ef59120c
|
[
"MIT"
] |
permissive
|
aimelo-io/lua
|
04c328fe25dc561fb5592a51f4a486ff85343f43
|
33c98e2cbdd58eb01acf397a959d9810619eca4f
|
refs/heads/main
| 2023-02-18T09:46:16.624329
| 2021-01-16T03:34:55
| 2021-01-16T03:34:55
| 329,841,374
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 562
|
h
|
pomelo-lua.h
|
#include <napi.h>
#include <lua.hpp>
class PomeloLua: public Napi::ObjectWrap<PomeloLua> {
public:
static Napi::Object init(Napi::Env env, Napi::Object exports);
PomeloLua(const Napi::CallbackInfo &info);
~PomeloLua();
private:
static Napi::FunctionReference m_constructor;
lua_State* m_luaState;
Napi::Value DoString(const Napi::CallbackInfo& info);
// Napi::Value Status(const Napi::CallbackInfo& info);
// Napi::Value CallGlobalFunction(const Napi::CallbackInfo& info);
Napi::Value Close(const Napi::CallbackInfo &info);
};
|
0bdac5e690b654373ec3d2bfdde0fa0ec12e4eca
|
8771e88358923f0a2d1b92911644dfaf01017c69
|
/c/largest_sum/largestsum.cpp
|
7f438c22d15f42387f8b5bf9318c873fb70c52ba
|
[] |
no_license
|
ggauravr/projects
|
7272cfa47f76276018353ee35ef41254b8565fe7
|
749b2cef981dc3749c3f0ca84e3138c45cfd3c5d
|
refs/heads/master
| 2020-06-04T15:19:28.563399
| 2015-04-07T02:30:53
| 2015-04-07T02:30:53
| 13,154,710
| 4
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 236
|
cpp
|
largestsum.cpp
|
#include <iostream>
using namespace std;
int main(){
int input;
// take an array of numbers as input
cout << "Please enter an array of numbers, including some negatives .. " << endl;
while(cin >> input){
}
return 0;
}
|
f290323fafc55815f787d3c4c44b740f357b807d
|
45f0baa7793cffa1af5d30573c1c824f698bbe5d
|
/lib/runtime/main.cpp
|
0b4efbd2d21379ec715de7f43115d06b5a638413
|
[
"MIT"
] |
permissive
|
rohitmaurya-png/Infinity-Programing-Langauge
|
766baa7b4f9085fec845633615f4335236711e14
|
396dae993e174d190a2b58031eb0ec51fd10cc97
|
refs/heads/main
| 2023-03-19T05:30:21.883682
| 2021-03-18T19:45:25
| 2021-03-18T19:45:25
| 349,195,589
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,853
|
cpp
|
main.cpp
|
//
//Created by Rohit Maurya 2/10/2020.
//
#include <cstring>
#include <cstdio>
#include "../../stdimports.h"
#include "../util/File.h"
#include "symbols/string.h"
#include "List.h"
#include "main.h"
#include "symbols/Object.h"
#include "VirtualMachine.h"
#include "Thread.h"
#include "Exe.h"
#include "register.h"
#include "memory/GarbageCollector.h"
#include "Manifest.h"
#include "jit/_BaseAssembler.h"
options c_options;
int startApplication(string &e, std::list<string> &appArgs);
void pushArgumentsToStack(std::list<string>& appArgs);
void pushArgumentsToStack(Object *object, std::list<string> &appArgs);
uInt getMemBytes(const char *argv, string option);
void version() {
cout << progname << " " << progvers << " build-" << BUILD_VERS << endl;
}
void error(string message) {
cout << "infinity: error: " << message << endl;
exit(1);
}
void help() {
#ifndef infinity_PROF_
std::cerr << "Usage: infinity" << " {OPTIONS} EXECUTABLE" << std::endl;
#endif
#ifdef infinity_PROF_
std::cerr << "Usage: " << PROFILER_NAME << " {OPTIONS} EXECUTABLE" << std::endl;
#endif
cout << "Executable must be built with infinityc to be executed\n" << endl;
cout << "[-options]\n\n -V print the version number and exit" << endl;
#ifdef infinity_PROF_
cout << " -sort<id> sort by time(tm), avg time(avgt), calls(calls), or ir(ir)." << endl;
#endif
cout << " -showversion print the version number and continue." << endl;
cout << " -mem<size:type> set the maximum memory allowed to the virtual machine." << endl;
cout << " -stack<size:type> set the default physical stack size allowed to threads." << endl;
cout << " -istack<size:type> set the default internal stack size allotted to the virtual machine." << endl;
cout << " -t<size:type> set the minimum memory allowed to trigger the garbage collector." << endl;
cout << " -nojit disable runtime JIT compilation." << endl;
cout << " -slowboot compile entire codebase at startup." << endl;
cout << " -h -? display this help message." << endl;
}
#define opt(v) strcmp(argv[i], v) == 0
int runtimeStart(int argc, const char* argv[])
{
if (argc < 2) { // We expect at least 1 argument: the executable
help();
return 1;
}
string executable;
std::list<string> appArgs;
/**
* We start off with allowing 64 megabytes of memory to be under
* mangement
*/
GarbageCollector::initilize();
GarbageCollector::setMemoryLimit(GC_HEAP_LIMIT);
GarbageCollector::setMemoryThreshold(MB_TO_BYTES(12));
for (int i = 1; i < argc; ++i) {
if(opt("-V")){
version();
exit(0);
}
else if(opt("-h") || opt("-?")){
help();
exit(0);
}
else if(opt("-showversion")){
version();
}
else if(opt("-nojit")){
c_options.jit = false;
}
else if(opt("-slowboot")){
c_options.slowBoot = true;
}
else if(opt("-debug")) {
c_options.debugMode = true;
}
else if(opt("-threshold") || opt("-t")) {
if((i+1) >= argc)
error("expected argument after option `" + string(argv[i]) + "`");
GarbageCollector::setMemoryThreshold(getMemBytes(argv[i+1], argv[i]));
i++;
}
#ifdef infinity_PROF_
else if(opt("-sort") || opt("-sortby")) {
if((i+1) >= argc)
error("expected argument after option `-sort`");
i++;
if(opt("tm")) {
c_options.sortBy = profilerSort::tm;
} else if(opt("avgt") || opt("avgtm")) {
c_options.sortBy = avgt;
} else if(opt("calls")) {
c_options.sortBy = calls;
} else if(opt("ir")) {
c_options.sortBy = ir;
} else {
error("invalid argument after option `-sort`");
}
}
#endif
else if(opt("-maxlmt") || opt("-mem")){
if(i+1 >= argc)
error("maximum memory limit required after option `" + string(argv[i]) + "`");
else {
GarbageCollector::setMemoryLimit(getMemBytes(argv[i+1], argv[i]));
i++;
}
}
else if(opt("-stack")){
if(i+1 >= argc)
error("maximum stack limit required after option `-stack`");
else {
size_t sz = getMemBytes(argv[i+1], argv[i]);
i++;
if(Thread::validStackSize(sz)) {
threadStackSize = sz;
} else {
stringstream ss;
ss << "default stack size must be greater than " << STACK_MIN << " bytes \n";
error(ss.str());
}
}
}
else if(opt("-istack")){
if(i+1 >= argc)
error("internal stack limit required after option `-istack`");
else {
size_t memoryLimit = getMemBytes(argv[i+1], argv[i]);
size_t stackSize = memoryLimit / sizeof(StackElement);
i++;
if(Thread::validInternalStackSize(memoryLimit)) {
internalStackSize = stackSize;
} else {
stringstream ss;
ss << "default internal stack size must be at least " << INTERNAL_STACK_MIN << " bytes \n";
error(ss.str());
}
}
}
else if(string(argv[i]).at(0) == '-'){
error("invalid option `" + string(argv[i]) + "`, try infinity -h");
}
else {
executable = argv[i++];
while(i < argc) {
appArgs.emplace_back(argv[i++]);
}
break;
}
}
if(executable.empty()){
help();
return 1;
}
if(!File::exists(executable.c_str())){
error("file `" + executable + "` doesnt exist!");
}
return startApplication(executable, appArgs);
}
uInt getMemBytes(const char *str, string option) {
string size = string(str);
stringstream ss;
bool parsedDigit = false;
for(unsigned int i = 0; i < size.size(); i++) {
if(isdigit(size.at(i))) {
parsedDigit = true;
ss << size.at(i);
} else if(isalpha(size.at(i))) {
string num = ss.str(); // 1028M
unsigned long limit = strtoul(ss.str().c_str(), NULL, 0);
switch(size.at(i)) {
case 'k':
case 'K':
return KB_TO_BYTES(limit);
case 'm':
case 'M':
return MB_TO_BYTES(limit);
case 'G':
case 'g':
return GB_TO_BYTES(limit);
default:
error("expected postfix 'K', 'M', or 'G' after number with option `" + option + "`");
break;
}
} else {
if(parsedDigit)
error("expected postfix 'K', 'M', or 'G' after number with option `" + option + "`");
else
error("expected number option `" + option + "`");
}
}
return 0;
}
int startApplication(string &exe, std::list<string>& appArgs) {
int result;
if((result = CreateVirtualMachine(exe)) != 0) {
fprintf(stderr, "Could not start the infinity virtual machine. Failed with code: %d\n", result);
goto bail;
}
pushArgumentsToStack(appArgs);
Thread::start(main_threadid, 0);
Thread *main;
Thread::threads.get(main_threadid, main);
Thread::threadjoin(main);
result=vm.exitVal;
return result;
bail:
vm.destroy();
return result;
}
void pushArgumentsToStack(std::list<string>& appArgs) {
Thread *main;
Thread::threads.get(main_threadid, main);
pushArgumentsToStack(&(++main->sp)->object, appArgs);
}
void pushArgumentsToStack(Object *object, std::list<string> &appArgs) {
const short MIN_ARGS = 5;
Int size = MIN_ARGS+appArgs.size();
Int iter=0;
stringstream ss;
ss << vm.manifest.target;
native_string str(ss.str());
*object = gc.newObjectArray(size);
gc.createStringArray(&object->object->node[iter++],vm.manifest.application);
gc.createStringArray(&object->object->node[iter++],vm.manifest.version);
gc.createStringArray(&object->object->node[iter++], str); /* target platform also the platform version */
#ifdef WIN32_
str.set("win");
#endif
#ifdef POSIX_
str.set("posix");
#endif
gc.createStringArray(&object->object->node[iter++], str); /* operating system currently running on */
infinityObject *mainThread = gc.newObject(vm.ThreadClass);
object->object->node[iter++] = mainThread;
vm.setFieldVar("native_handle", mainThread, 0, 0);
vm.setFieldClass("name", mainThread, vm.StringClass);
Object* field;
if((field = vm.resolveField("name", mainThread)) != NULL && field->object) {
str.set("main");
gc.createStringArray(vm.resolveField("data", field->object), str);
}
vm.setFieldVar("started", mainThread, 0, 1);
vm.setFieldVar("stack_size", mainThread, 0, threadStackSize);
/*
* Assign program args to be passed to main
*/
for(unsigned int i = 0; i < appArgs.size(); i++) {
runtime::String argStr(*std::next(appArgs.begin(), i));
gc.createStringArray(&object->object->node[iter++], argStr);
}
appArgs.clear();
}
|
c70e58d81614b942e700d355cb86d2c8de15ba10
|
f76bf9fe835800bf84a7fbde30b4fc3bfa40565f
|
/samples/pitchshifter_sample.cpp
|
20d8e6b4396c215fb941b08d958b22db320bcd8a
|
[
"MIT"
] |
permissive
|
shunsukeaihara/ssp
|
e4c12a7521568c30370a3ea9875cd16157482369
|
ba562000c9c51109a68eb905ef01e5666ef9f484
|
refs/heads/master
| 2020-05-05T04:55:11.365019
| 2019-04-24T05:52:49
| 2019-04-24T05:52:49
| 179,730,102
| 8
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,945
|
cpp
|
pitchshifter_sample.cpp
|
#include <unistd.h>
#include <biquad_filter.hpp>
#include <butterworth_filter.hpp>
#include <common.hpp>
#include <compressor.hpp>
#include <iostream>
#include <limitter.hpp>
#include <noisegate.hpp>
#include <pitchshifter.hpp>
using namespace ssp;
#define INSIZE 2048
#define OUTSIZE 2048
#define FS 48000.0
int main() {
PitchShifter<double> shifter = PitchShifter<double>(0.7, 1.0, 20.0, INSIZE, 620, FS);
NoiseGate<double> gate = NoiseGate<double>(5, 50, -50.0, FS);
Compressor<double> comp = Compressor<double>(1, 100, -1, 1.0, FS);
Limitter<double> limit = Limitter<double>(1, 100, -1, FS);
BiquadFilter<double> *hpf = BiquadFilter<double>::createHighPassfilter(FS, 40, 1.0);
BiquadFilter<double> *shelf = BiquadFilter<double>::createLowShelfFilter(FS, 400, 1.5, 15.0);
ButterworthFilter<double> *lpfilter = ButterworthFilter<double>::createLowPassFilter(FS, 5500, 8);
short in[INSIZE];
double f[INSIZE];
double fout[OUTSIZE];
short out[OUTSIZE];
while (true) {
size_t nread = read(0, (char *)in, sizeof(in));
for (int i = 0; i < INSIZE; i++) {
double x = ((double)in[i]) / 32768.0;
x = hpf->filterOne(x);
x = shelf->filterOne(x);
f[i] = x;
}
shifter.process(f, INSIZE);
while (true) {
int readCount = shifter.read(fout, OUTSIZE);
if (readCount < 0) {
break;
}
for (int i = 0; i < OUTSIZE; i++) {
double x = fout[i];
x = lpfilter->filterOne(x);
x = gate.filterOne(x);
x *= 6;
x = comp.filterOne(x);
x = limit.filterOne(x);
out[i] = short(x * 32767.0);
}
write(1, (char *)out, OUTSIZE * 2);
}
if (nread < INSIZE * 2) break;
}
delete hpf;
delete shelf;
delete lpfilter;
}
|
7c31ad719f9a0b03d9dea4f57d80584532646d76
|
792b76c112fce67165d6e80f18c1bd1945698da8
|
/include/harps/compornent/normalize.hpp
|
236df44364957d7d0aa30a6483c5e338ce047a4e
|
[
"BSD-2-Clause"
] |
permissive
|
Fadis/harps
|
8345a225fbec44c541bc5e7fd77f20ed0d025c08
|
4ba67125be310415f06fc528e6b48a6d858eb044
|
refs/heads/master
| 2021-01-10T19:51:44.817253
| 2011-08-25T18:09:09
| 2011-08-25T18:09:09
| 2,269,600
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,417
|
hpp
|
normalize.hpp
|
/***************************************************************************
* Copyright (C) 2009 by Naomasa Matsubayashi *
* harps@quaternion.sakura.ne.jp *
* *
* All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* * Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* * Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in *
* the documentation and/or other materials provided with the *
* distribution. *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR *
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT *
* OWNER OR *
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, *
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, *
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR *
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY *
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE *
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
***************************************************************************/
#ifndef HARPS_COMPORNENT_NORMALIZE
#define HARPS_COMPORNENT_NORMALIZE
#include <harps/utils.hpp>
#include <harps/clock.hpp>
#include <harps/buffer.hpp>
#include <harps/note.hpp>
#include <harps/normalize.hpp>
#include <harps/config.hpp>
namespace harps {
namespace compornent {
/*!
* 入力の音量を正規化します。
*/
template< typename ModuleType >
class Normalize {
public:
template< typename SampleType >
inline void operator() ( Buffer< SampleType > &_buffer, CurrentTime &_clock, Note &_note ) {
module ( _buffer, _clock, _note );
Buffer< SampleType > amp_buffer;
int index;
typename Buffer< SampleType >::SampleType *raw_buffer = _buffer.get();
typename Buffer< SampleType >::SampleType *raw_amp_buffer = amp_buffer.get();
for ( index = 0; index != SAMPLE_COUNT; index++ ) {
normalizer.setValue ( raw_buffer[ index ] );
raw_amp_buffer[ index ] = normalizer.getAmp();
}
reduceNormalizingNoize ( amp_buffer );
for ( index = 0; index != SAMPLE_COUNT; index++ )
raw_buffer[ index ] /= raw_amp_buffer[ index ];
}
private:
Normalizer< SAMPLING_RATE * 10 > normalizer;
ModuleType module;
};
}
}
#endif
|
7efc81c84678de03312870a6904d63be9c588dfd
|
7eb5c8149187c43fcd941db9fc53f7dc6f7d7a87
|
/opdracht/headers/melody copy.hpp
|
52914d8e41fdbd8ba8b93b7094b43aed0433445d
|
[
"MIT"
] |
permissive
|
sanderBoot0/2A_TD
|
941302e20c5afc8e0a5e281366d1fa4362d5dc9f
|
bde3e25ea86ec9d2601fadf501e991009b3d58b4
|
refs/heads/master
| 2020-08-02T08:37:18.274315
| 2019-11-06T14:07:27
| 2019-11-06T14:07:27
| 211,290,798
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 332
|
hpp
|
melody copy.hpp
|
// /**
// * @file melody_copy.hpp
// * @brief This file has been taken from the v2cpse1 repository so that the beeper will work
// */
// #ifndef _MELODY_HPP
// #define _MELODY_HPP
// #include "note_player.hpp"
// // an abstract melody
// class melody {
// public:
// virtual void play( note_player & p );
// };
// #endif
|
d5d49d8bdf12b989c9c0ea5f1b478f998c41a348
|
dd14e6ad61309c493bed15e5cdc5855609139b94
|
/d02/ex02/Fixed.class.hpp
|
9fce1a4ebf209cb304b29b236492aaeb51bcac8f
|
[] |
no_license
|
GlThibault/Piscine-CPP
|
be9da6458cff411ff21772ad90050c9b344bddd1
|
7295f94912a65e987998b1bdea44ee4656aeb01e
|
refs/heads/master
| 2021-04-12T10:58:05.504981
| 2018-04-04T09:47:11
| 2018-04-04T09:47:11
| 126,483,098
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,487
|
hpp
|
Fixed.class.hpp
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Fixed.class.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: tglandai <tglandai@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/03/28 11:58:35 by tglandai #+# #+# */
/* Updated: 2018/03/29 18:07:32 by tglandai ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FIXED_CLASS_HPP
#define FIXED_CLASS_HPP
#include <iostream>
#include <cmath>
class Fixed {
public:
Fixed(void);
Fixed(const int n);
Fixed(const float n);
Fixed(Fixed const & src);
~Fixed(void);
static Fixed & max(Fixed & a, Fixed & b);
static const Fixed & max(Fixed const & a, Fixed const & b);
static Fixed & min(Fixed & a, Fixed & b);
static const Fixed & min(Fixed const & a, Fixed const & b);
Fixed & operator=(Fixed const & rhs );
Fixed operator+(Fixed const & rhs ) const;
Fixed operator-(Fixed const & rhs ) const;
Fixed operator*(Fixed const & rhs ) const;
Fixed operator/(Fixed const & rhs ) const;
Fixed & operator++(void);
Fixed operator++(int);
Fixed & operator--(void);
Fixed operator--(int);
bool operator>(Fixed const & rhs ) const;
bool operator>=(Fixed const & rhs ) const;
bool operator<(Fixed const & rhs ) const;
bool operator<=(Fixed const & rhs ) const;
bool operator==(Fixed const & rhs ) const;
bool operator!=(Fixed const & rhs ) const;
int getRawBits(void) const;
void setRawBits(int const raw);
float toFloat(void) const;
int toInt(void) const;
private:
int _n;
static const int _fractBits = 8;
};
std::ostream & operator<<(std::ostream & o, Fixed const & rhs );
#endif
|
51b32e91bf5cd69e31c791a2fec7efb1a8bf5cfd
|
219b5cfb7ae924d52a92e15e642974b082e5a7f4
|
/src/Map.h
|
a9ecfdee60358e079b2e835b6fedb78043a9e2bb
|
[] |
no_license
|
iAndu/2D-RPG
|
b841904e63e4cf8c59aa259117264651d80ff537
|
085358ac1e1ec7c16901353f5e3bba62a677d7e0
|
refs/heads/master
| 2021-01-19T09:06:00.864279
| 2017-05-12T00:55:56
| 2017-05-12T00:55:56
| 87,723,202
| 0
| 2
| null | 2017-05-11T16:46:09
| 2017-04-09T16:39:46
|
Makefile
|
UTF-8
|
C++
| false
| false
| 897
|
h
|
Map.h
|
#pragma once
#include "oxygine-framework.h"
DECLARE_SMART(Map, spMap);
class Map : public oxygine::Sprite
{
public:
Map(const std::string& tmx, const std::string& texture);
int GetWidth() const { return width; };
void SetWidth(const int _width) { width = _width; };
int GetHeight() const { return height; };
void SetHeight(const int _height) { height = _height; };
int GetCols() const { return cols; };
void SetCols(const int _cols) { cols = _cols; };
int GetRows() const { return rows; };
void SetRows(const int _rows) { rows = _rows; };
void drawLayer(int startX, int startY, int endX, int endY, const std::vector<unsigned int>& layer);
void createTileSetTexture(oxygine::Image& src);
void doRender(const oxygine::RenderState& rs);
private:
std::list< std::vector<unsigned int> > layers;
int width, height, tileWidth, tileHeight, cols, rows;
oxygine::spNativeTexture nt;
};
|
b2950aecabee2fe1e5f66b70a8be015c75697618
|
e6872c0af906bbc87da114b6e0846002504f6ff3
|
/Encryption/ui_mainwindow.h
|
a41a8bc8ebf0b93cac50f5705c77a37996c9d3dd
|
[] |
no_license
|
davchrand/CyberSecurity
|
c690f76ffd011ef28af1cd8bf24167f86a65d0b4
|
893a67af1cafb57a6f897c5bb03071aaef0dd44e
|
refs/heads/master
| 2021-01-10T22:44:34.624597
| 2016-12-01T03:39:40
| 2016-12-01T03:39:40
| 70,361,766
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,624
|
h
|
ui_mainwindow.h
|
/********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.7.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QAction *actionExit;
QWidget *centralWidget;
QLabel *label;
QTextEdit *encryptText;
QPushButton *pushButton;
QLabel *label_2;
QTextEdit *detailsBox;
QPushButton *fileDialog;
QPushButton *generateKeys;
QPushButton *pushButton_2;
QPushButton *pushButton_3;
QMenuBar *menuBar;
QMenu *menuFile;
QToolBar *mainToolBar;
QStatusBar *statusBar;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QStringLiteral("MainWindow"));
MainWindow->resize(700, 791);
QFont font;
font.setPointSize(12);
MainWindow->setFont(font);
actionExit = new QAction(MainWindow);
actionExit->setObjectName(QStringLiteral("actionExit"));
centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
label = new QLabel(centralWidget);
label->setObjectName(QStringLiteral("label"));
label->setGeometry(QRect(10, 40, 281, 31));
label->setFont(font);
encryptText = new QTextEdit(centralWidget);
encryptText->setObjectName(QStringLiteral("encryptText"));
encryptText->setGeometry(QRect(10, 80, 681, 301));
pushButton = new QPushButton(centralWidget);
pushButton->setObjectName(QStringLiteral("pushButton"));
pushButton->setGeometry(QRect(10, 390, 681, 31));
pushButton->setFont(font);
label_2 = new QLabel(centralWidget);
label_2->setObjectName(QStringLiteral("label_2"));
label_2->setGeometry(QRect(10, 430, 71, 20));
label_2->setFont(font);
detailsBox = new QTextEdit(centralWidget);
detailsBox->setObjectName(QStringLiteral("detailsBox"));
detailsBox->setGeometry(QRect(10, 460, 681, 261));
QFont font1;
font1.setPointSize(10);
detailsBox->setFont(font1);
fileDialog = new QPushButton(centralWidget);
fileDialog->setObjectName(QStringLiteral("fileDialog"));
fileDialog->setGeometry(QRect(290, 40, 211, 31));
fileDialog->setFont(font);
generateKeys = new QPushButton(centralWidget);
generateKeys->setObjectName(QStringLiteral("generateKeys"));
generateKeys->setGeometry(QRect(10, 0, 681, 31));
pushButton_2 = new QPushButton(centralWidget);
pushButton_2->setObjectName(QStringLiteral("pushButton_2"));
pushButton_2->setGeometry(QRect(600, 430, 93, 21));
pushButton_2->setFont(font1);
pushButton_3 = new QPushButton(centralWidget);
pushButton_3->setObjectName(QStringLiteral("pushButton_3"));
pushButton_3->setGeometry(QRect(600, 40, 93, 28));
pushButton_3->setFont(font1);
MainWindow->setCentralWidget(centralWidget);
menuBar = new QMenuBar(MainWindow);
menuBar->setObjectName(QStringLiteral("menuBar"));
menuBar->setGeometry(QRect(0, 0, 700, 26));
menuFile = new QMenu(menuBar);
menuFile->setObjectName(QStringLiteral("menuFile"));
MainWindow->setMenuBar(menuBar);
mainToolBar = new QToolBar(MainWindow);
mainToolBar->setObjectName(QStringLiteral("mainToolBar"));
MainWindow->addToolBar(Qt::TopToolBarArea, mainToolBar);
statusBar = new QStatusBar(MainWindow);
statusBar->setObjectName(QStringLiteral("statusBar"));
MainWindow->setStatusBar(statusBar);
menuBar->addAction(menuFile->menuAction());
menuFile->addAction(actionExit);
retranslateUi(MainWindow);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0));
actionExit->setText(QApplication::translate("MainWindow", "Exit", 0));
label->setText(QApplication::translate("MainWindow", "Text to be encrypted below or", 0));
pushButton->setText(QApplication::translate("MainWindow", "Encrypt", 0));
label_2->setText(QApplication::translate("MainWindow", "Details:", 0));
fileDialog->setText(QApplication::translate("MainWindow", "Choose Text from File", 0));
generateKeys->setText(QApplication::translate("MainWindow", "Generate Keys", 0));
pushButton_2->setText(QApplication::translate("MainWindow", "CLEAR", 0));
pushButton_3->setText(QApplication::translate("MainWindow", "CLEAR", 0));
menuFile->setTitle(QApplication::translate("MainWindow", "File", 0));
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
|
19efa123d9bd81f86d3a8678c6ade4420435b3d0
|
a70b968124d6686b11786ef255aaf58d5e46fbb9
|
/A. Mashmokh and Numbers.cpp
|
7abb91d4444abb8279b1582be1fdd9f7260d311d
|
[] |
no_license
|
ashraf-pavel/Since-nov-20
|
dc4f5cd23cf0bd76e4035e284adf8cff7ebc7695
|
a95c4d5e405aaeb91f4a59fb6deb6ed5dc3e0b9c
|
refs/heads/main
| 2023-01-18T19:10:25.053398
| 2020-11-23T17:38:30
| 2020-11-23T17:38:30
| 315,389,016
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,478
|
cpp
|
A. Mashmokh and Numbers.cpp
|
#include<bits/stdc++.h>
#define pi acos(-1.0)
#define bsort(v) sort(v.begin(),v.end())
#define pb push_back
#define mp make_pair
#define FAST ios_base::sync_with_stdio(false);cin.tie(NULL);
#define MOD 1000000007
#define N 10000001
#define F first
#define S second
#define MAX 500050
#define ALL(v) v.begin(),v.end()
using namespace std;
typedef long long int ll;
typedef long double ld;
typedef unsigned long long ull;
typedef pair<int,int> pii;
int gcd(int a,int b)
{
if(b==0)
return a;
return gcd(b,a%b);
}
int main()
{
FAST
int tc=1;
//cin>>tc;
while(tc--)
{
int n,k;
cin>>n>>k;
int cc=n;
if(n==1)
{
if(!k)
cout<<1<<endl;
else
cout<<-1<<endl;
continue;
}
//cout<<(n+1)/2<<endl;
if(n/2>k)
cout<<-1<<endl;
else
{
int x=k-(n-2)/2;
cout<<x<<" "<<2*x<<" ";
if(n&1)
{
n-=3;
int val=2*x+1;
while(n--)
cout<<val++<<" ";
cout<<2*cc+1<<" ";
}
else
{
n-=2;
int val=2*x+1;
while(n--)
cout<<val++<<" ";
}
cout<<endl;
}
}
return 0;
}
|
3be089b8902fe294bc9cc61709efe3d645a6a779
|
a7d65cf5e43f94eb99a43c13607edd6c52ab06d2
|
/Problems/zeroOneKnapsack.cpp
|
46d5db522115afdf6d44257d62bea75e9fb6bf4c
|
[] |
no_license
|
Kamil-Jan/CppAlgorithms
|
530dd251a14dc71107b8facd8e39ea48b3321fe8
|
f464ab031b763312a5833717bec1887b2c2ce24f
|
refs/heads/master
| 2022-12-11T18:32:23.193118
| 2020-09-07T15:49:45
| 2020-09-07T15:49:45
| 293,079,191
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,393
|
cpp
|
zeroOneKnapsack.cpp
|
#include <iostream>
#include <cmath>
using namespace std;
int max(int a, int b)
{
if (a > b) { return a; }
return b;
}
void printMatrix(int** V, size_t rows, size_t cols)
{
for (size_t i=0; i < rows; i++) {
for (size_t j=0; j < cols; j++) {
if (V[i][j] < 10) {
cout << " " << V[i][j] << " ";
} else {
cout << V[i][j] << " ";
}
}
cout << endl;
}
}
int** knapsackProblem(int n, int profits[], int weights[], int W)
{
int** V = 0;
V = new int *[n + 1];
for (int i=0; i <= n; i++) {
V[i] = new int[W + 1];
for (int w=0; w <= W; w++) {
if (i == 0 || w == 0) {
V[i][w] = 0;
} else if (weights[i - 1] <= w) {
int product_weight = weights[i - 1];
V[i][w] = max(V[i - 1][w - product_weight] + profits[i - 1],
V[i - 1][w]);
} else {
V[i][w] = V[i - 1][w];
}
}
}
return V;
}
int main()
{
int p[] = { 1, 2, 5, 6 };
int w[] = { 2, 3, 4, 5 };
int n = sizeof(p) / sizeof(p[0]);
int W = 8;
int** V = knapsackProblem(n, p, w, W);
printMatrix(V, n + 1, W + 1);
cout << "\nMax Profit: " << V[n][W];
return 0;
}
|
b8b751457ca91592ebbd47c3949d3e12d221bc6d
|
fbd9436fcbdc22a413c5f85d375e7028aef6fd6e
|
/lanqiaobei/2WinterVocationHomework/16蓝桥OJ算法训练-结点选择.cpp
|
dac8cabff835cbecde896dec66e2828612377ed0
|
[] |
no_license
|
IoveSunny/ojproblems
|
55c4daf224f1a201d7e0faf310c4129f64efa29a
|
4b3599116a3aa94b321eb66560cd03593773a303
|
refs/heads/master
| 2021-01-01T20:41:35.554761
| 2014-02-26T09:13:47
| 2014-02-26T09:13:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,856
|
cpp
|
16蓝桥OJ算法训练-结点选择.cpp
|
/*
算法训练 结点选择
时间限制:1.0s 内存限制:256.0MB
问题描述
有一棵 n 个节点的树,树上每个节点都有一个正整数权值。如果一个点被选择了,那么在树上和它相邻的点都不能被选择。求选出的点的权值和最大是多少?
输入格式
第一行包含一个整数 n 。
接下来的一行包含 n 个正整数,第 i 个正整数代表点 i 的权值。
接下来一共 n-1 行,每行描述树上的一条边。
输出格式
输出一个整数,代表选出的点的权值和的最大值。
样例输入
5
1 2 3 4 5
1 2
1 3
2 4
2 5
样例输出
12
样例说明
选择3、4、5号点,权值和为 3+4+5 = 12 。
数据规模与约定
对于20%的数据, n <= 20。
对于50%的数据, n <= 1000。
对于100%的数据, n <= 100000。
权值均为不超过1000的正整数。
*/
/*
解题思路:
1、贪心算法
*/
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
struct dot {
int value;
int place;
};
int cmp(struct dot a, struct dot b) {
return a.value > b.value;
}
int main(void) {
struct dot a[100000];
bool vis[100000];
bool side[1000][1000];
int n;
scanf("%d", &n);
for(int i=1; i<=n; i++) {
scanf("%d", &a[i].value);
a[i].place = i;
vis[i] = 0;
}
sort(a+1, a+n+1, cmp);
for(int i=1; i<=n-1; i++) {
int y, x;
scanf("%d%d", &y, &x);
side[y][x] = 1;
side[x][y] = 1;
}
int maxvalue = 0;
for(int i=1; i<=n; i++) {
// 这个结点是否可用; ==0可用, 1不可用
if(vis[a[i].place] == 0) {
maxvalue += a[i].value;
// 标记与a[j].place相连的点
for(int j=1; j<n-1; j++) {
if(side[a[i].place][j])
vis[j] = 1;
}
}
}
printf("%d\n", maxvalue);
return 0;
}
|
15ca6b96d81c6739bf589519f43ffebf73af2136
|
bc17b47315bf09081b0aefcf46d5113c31f24a33
|
/374.cpp
|
e7dbf57c0191cae93f12dcf19b9f32a18c69b1d1
|
[] |
no_license
|
IshanX111/UVA_Problem_Solution
|
ece9b4d45c56c613bd8b786424060d183946b7bf
|
9f4e15e1210400d62192915e476c8741ecbce1da
|
refs/heads/master
| 2023-05-12T08:27:34.384826
| 2023-05-01T18:28:25
| 2023-05-01T18:28:25
| 231,390,534
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 920
|
cpp
|
374.cpp
|
#include<bits/stdc++.h>
#define PI acos(-1.0)
#define rep1(i,n) for(i=1;i<n;i++)
#define rep0(i,n) for(i=0;i<n;i++)
#define rep(i,a,n) for(i=a;i<n;i++)
#define repe1(i,n) for(i=1;i<=n;i++)
#define repe0(i,n) for(i=0;i<=n;i++)
#define repe(i,a,n) for(i=a;i<=n;i++)
#define fr freopen("input.txt","r",stdin)
#define fw freopen("output.txt","w",stdout)
#define FAST ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
typedef long long ll;
using namespace std;
ll m;
ll f(ll b1,ll p1){
ll b=b1;
ll p=p1;
ll r;
if(p==0){
return 1;
}
else if(p%2==0){
r=f(b,p/2);
return (((r%m)*(r%m))%m);
}
else{
return (((b%m)*(f(b,p-1)%m))%m);
}
}
int main(){
FAST;
ll b,p,r;
while(cin>>b>>p>>m){
ll res=f(b,p);
cout<<res<<endl;
}
}
|
abaede97b69c565ff2e675f65d9162b7ec793c43
|
c3077fa4fa7921196d0b603c9733caeae19ae9c8
|
/datatag.h
|
154e9cdc0e62bb4809f61f8bb7d97f0517ff0421
|
[] |
no_license
|
helioz2000/mbbridge
|
73256c82b759fd4cf8b816964dc4f7628f63d68e
|
c27a3cf9dec95f5403c96df035c178f1ff386f6d
|
refs/heads/master
| 2023-08-05T04:58:08.056356
| 2023-07-23T05:50:53
| 2023-07-23T05:50:53
| 228,374,578
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,939
|
h
|
datatag.h
|
/**
* @file datatag.h
-----------------------------------------------------------------------------
Two classes provide encapsulation for typical use of a data tag in an
automation oriented user interface.
This implementation is targeted data which is based on the MQTT protocol
and stores the data access information as a topic path (see MQTT details)
Class "Tag" encapsulates a single data unit
Class "TagList" provides a facility to manage a list of tags
The Tag class provides for a callback interface which is intended to update
a user interface element (e.g. display value) only when data changes
The "publish" member defines if a tag's value is published (written)
to an mqtt broker or if it is subscribed (read from MQTT broker).
This information is used outside this class.
-----------------------------------------------------------------------------
*/
#ifndef _DATATAG_H_
#define _DATATAG_H_
/*********************
* INCLUDES
*********************/
#include <stdint.h>
#include <iostream>
#include <string>
/*********************
* DEFINES
*********************/
#define MAX_TAG_NUM 100 // The mximum number of tags which can be stored in TagList
/**********************
* TYPEDEFS
**********************/
typedef enum
{
TAG_TYPE_NUMERIC = 0,
TAG_TYPE_BOOL = 1
}tag_type_t;
class Tag {
public:
/**
* Invalid - Empty constructor throws runtime error
*/
Tag();
/**
* Constructor
* @param topic: tag topic
*/
Tag(const char* topicStr);
/**
* Destructor
*/
~Tag();
/**
* Get topic CRC
* @return the CRC for the topic string
*/
uint16_t getTopicCrc(void);
/**
* Get the topic string
* @return the topic string
*/
const char* getTopic(void);
/**
* Register a callback function to notify value changes
* @param updatePtr a pointer to the upadate function
*/
void registerCallback(void (*updateCallback) (int,Tag*), int callBackID );
/**
* Set the value
* @return the callback ID set with registerCallback
*/
int valueUpdateID();
void testCallback();
/**
* Set the value
* @param doubleValue: the new value
*/
void setValue(double doubleValue);
/**
* Set the value
* @param floatValue: the new value
*/
void setValue(float floatValue);
/**
* Set the value
* @param intValue: the new value
*/
void setValue(int intValue);
/**
* Set the value
* @param strValue: new value as a string
* @returns true on success
*/
bool setValue(const char* strValue);
/**
* Get value
* @return value as double
*/
double doubleValue(void);
/**
* Get value
* @return value as float
*/
float floatValue(void);
/**
* Get value
* @return value as int
*/
int intValue(void);
/**
* is tag "publish"
* @return true if publish or false if subscribe
*/
bool isPublish();
/**
* is tag "subscribe"
* @return false if publish or true if subscribe
*/
bool isSubscribe();
/**
* Mark tag as "publish"
*/
void setPublish(void);
/**
* Mark tag as "subscribe" (NOT publish)
*/
void setSubscribe(void);
/**
* assign mqtt retain value
*/
void setPublishRetain(bool newRetain);
/**
* get mqtt retain value
*/
bool getPublishRetain(void);
/**
* set value is retained
*/
void setValueIsRetained(bool newValue);
bool getValueIsRetained(void);
/**
* Set tag type (see tag_type_t)
*/
void setType(tag_type_t newType);
/**
* Get tag type (see tag_type_t)
*/
tag_type_t type(void);
// public members used to store data which is not used inside this class
int readInterval; // seconds between reads
time_t nextReadTime; // next scheduled read
int publishInterval; // seconds between publish
time_t nextPublishTime; // next publish time
private:
// All properties of this class are private
// Use setters & getters to access these values
std::string _topic; // storage for topic path
uint16_t _topicCRC; // CRC on topic path
double _topicDoubleValue; // storage numeric value
time_t _lastUpdateTime; // last update time (change of value)
void (*_valueUpdate) (int,Tag*); // callback for value update
int _valueUpdateID; // ID for value update
bool _publish; // true = we publish, false = we subscribe
bool _publishRetain; // mqtt publish retain
bool _valueIsRetained; // indicate that the current value is retained
tag_type_t _type; // data type
};
class TagStore {
public:
TagStore();
~TagStore();
/**
* Add a tag
* @param tagTopic: the topic as a string
* @return reference to new tag or NULL on failure
*/
Tag* addTag(const char* tagTopic);
/**
* Delete all tags from tag list
*/
void deleteAll(void);
/**
* Find tag in the list and return reference
* @param tagTopic: the topic as a string
* @return reference to tag or NULL is if not found
*/
Tag* getTag(const char* tagTopic);
/**
* Get first tag from store
* use in conjunction with getNextTag to iterate over all tags
* @return reference to first tag or NULL if tagList is empty
*/
Tag* getFirstTag(void);
/**
* Get next tag from store
* use in conjunction with getFirstTag to iterate over all tags
* @return reference to next tag or NULL if end of tagList
*/
Tag* getNextTag(void);
private:
Tag *_tagList[MAX_TAG_NUM]; // An array references to Tags
int _iterateIndex; // to interate over all tags in store
};
#endif /* _DATATAG_H_ */
|
336a70333c29e4df698f607454f1c075b45e7561
|
27ebc7adb261225341eaf995ae181e5530f311f9
|
/Code/BZOJ/1106.cpp
|
ec8b112fb4f343712c53e0827f9c9cb4a05d5029
|
[] |
no_license
|
Hermera/OI
|
9ecf1d5545701afeb3273d9be720cf3e16643c14
|
d8a79de409065c790ca0ad3019ca1d2ea7550b34
|
refs/heads/master
| 2021-06-21T05:44:34.805477
| 2021-06-09T17:17:11
| 2021-06-09T17:17:11
| 93,643,345
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 750
|
cpp
|
1106.cpp
|
#include <cstdio>
#include <algorithm>
using namespace std;
inline int read()
{
char ch = getchar(); int sum = 0;
while(ch < '0' || ch > '9') ch = getchar();
while(ch >= '0' && ch <= '9') sum = sum*10+ch-'0', ch = getchar();
return sum;
}
const int maxn = 1e5+5;
int N, sum, a[maxn], tree[maxn], check[maxn];
void add(int x, int v) { while(x <= (N<<1)) tree[x] += v, x += x&-x; }
int query(int x)
{
int ans = 0;
while(x) ans += tree[x], x -= x&-x;
return ans;
}
int main()
{
freopen("data.in", "r", stdin);
N = read();
for(int i = 1; i <= (N<<1); ++i) a[i] = read();
for(int i = 1; i <= (N<<1); ++i)
if(!check[a[i]]) check[a[i]] = i, add(i, 1);
else sum += query(i)-query(check[a[i]]), add(check[a[i]], -1);
printf("%d\n", sum);
}
|
0b1bf222696f75e637431e75c8b06bb94f92b5c4
|
e867728ca76653f87da789dd5f0a287ea37aafc0
|
/wndproc.h
|
7795264665d17f798c6b6b64d19e51e8bdb65da5
|
[
"MIT"
] |
permissive
|
bl222/win32-wrapper
|
7a900aac9a7af0dd95f6f25fe9c2ad31bcd45728
|
90a055d9623375259d15f937bf12a1d2897c2e86
|
refs/heads/master
| 2021-01-19T14:04:27.677362
| 2017-08-20T19:18:44
| 2017-08-20T19:18:44
| 100,883,113
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 16,244
|
h
|
wndproc.h
|
//---------------------------------------------------------------------------
// This file contains the predefined window procedure as well as
// some classes encapsulating parameters for some messages.
//---------------------------------------------------------------------------
#if !defined (WNDPROC_H)
#define WNDPROC_H
#include "useunicode.h"
#include "winunicodehelper.h"
#include "win.h"
#include "winencapsulation.h"
#include "wincanvas.h"
#include "winmenu.h"
namespace Win
{
//---------------------------------------------------------------------------
// Win::CreationData encapsulates a CREATESTRUCT through private inheritance
// The parameter of the WM_CREATE message is a CREATESTRUCT.
//
// Dara members of CREATESTRUCT:
//
// lpCreateParams -> Additional data, contains the lpParam of the
// CreateWindowEx call.
// x -> X coordinate of the window.
// y -> Y coordinate of the window.
// cx -> Width of the window.
// cy -> Height of the window.
// lpszClass -> Name of the Win::Class object used to create the window.
// lpszName -> Title of the window.
// hInstance -> Instance of the program.
// hMenu -> Handle of the menu.
// hwndParent -> Handle of the parent of the window.
// style -> Style of the window.
// dwExStyle -> Extended style of the window.
//---------------------------------------------------------------------------
class CreationData : private CREATESTRUCT
{
public :
//----------------------------------------------------------------
// Obtains a pointer on the additional creation data.
//
// Return value: Void pointer on the creation data.
//----------------------------------------------------------------
void * GetCreationData () const
{
return lpCreateParams ;
}
//----------------------------------------------------------------
// Obtains the initial x coordinate of the window.
//
// Return value: Initial x coordinate of the window.
//----------------------------------------------------------------
int GetX () const
{
return x ;
}
//----------------------------------------------------------------
// Obtains the initial y coordinate of the window.
//
// Return value: Initial y coordinate of the window.
//----------------------------------------------------------------
int GetY () const
{
return y ;
}
//----------------------------------------------------------------
// Obtains the initial width of the window.
//
// Return value: Initial width of the window.
//----------------------------------------------------------------
int GetWidth () const
{
return cx ;
}
//----------------------------------------------------------------
// Obtains the initial height of the window.
//
// Return value: Initial height of the window.
//----------------------------------------------------------------
int GetHeight () const
{
return cy ;
}
//----------------------------------------------------------------
// Obtains the name of the Win::Class object used to create the
// window.
//
// Return value: The name of the Win::Class object.
//----------------------------------------------------------------
const std::tstring GetClassName () const
{
return lpszClass ;
}
//----------------------------------------------------------------
// Obtains the title of the window.
//
// Return value: The title of the window.
//----------------------------------------------------------------
const std::tstring GetWindowName () const
{
return lpszName ;
}
//----------------------------------------------------------------
// Obtains the instance of the program.
//
// Return value: The instance of the program.
//----------------------------------------------------------------
HINSTANCE GetInstance () const
{
return hInstance ;
}
//----------------------------------------------------------------
// Obtains a weak handle on the menu of the window.
//
// Return value: A weak handle on the menu of the window.
//----------------------------------------------------------------
Win::Menu::Handle GetMenu () const
{
return hMenu ;
}//----------------------------------------------------------------
// Obtains the parent of the window.
//
// Return value: The parent of the window.
//----------------------------------------------------------------
Win::dow::Handle GetParent () const
{
return hwndParent ;
}
//----------------------------------------------------------------
// Obtains the style of the window.
//
// Return value: The style of the window.
//----------------------------------------------------------------
LONG GetStyle () const
{
return style ;
}
//----------------------------------------------------------------
// Obtains the extended style of the window.
//
// Return value: The extended style of the window.
//----------------------------------------------------------------
DWORD GetStyleEX () const
{
return dwExStyle ;
}
private:
CreationData (CreationData & data) ;
CreationData operator = (CreationData & data) ;
} ;
//----------------------------------------------------------------
// Win::ActivateAction encapsulates the flag that come with the
// WM_ACTIVATE message in the wParam parameter.
//----------------------------------------------------------------
class ActivateAction
{
public:
//--------------------------------------------------------------------
// Constructor. Creates the Win::ActivateAction object with the
// lParam from WM_ACTIVATE messages.
//
// Parameters:
//
// const LPARAM flag -> The information on the window that is shown.
//--------------------------------------------------------------------
ActivateAction (int action)
: _action (action)
{}
//----------------------------------------------------------------------
// Determines if the window is being activated but not by a mouse click.
//
// Return value: True if the window is being activated but not by a
// mouse click, else false.
//----------------------------------------------------------------------
bool isActive () const
{
return _action == WA_ACTIVE ;
}
//----------------------------------------------------------------------
// Determines if the window is being deactivated.
//
// Return value: True if the window is being deactivated, else false.
//----------------------------------------------------------------------
bool isInactive () const
{
return _action == WA_INACTIVE ;
}
//----------------------------------------------------------------------
// Determines if the window is being activated by a mouse click.
//
// Return value: True if the window is being activated by a
// mouse click, else false.
//----------------------------------------------------------------------
bool isClickActive () const
{
return _action == WA_CLICKACTIVE ;
}
//--------------------------------------------------------------------
// Converts the ActivateAction object into a int
// Used for compatibility with the WinAPI.
//--------------------------------------------------------------------
operator int () const
{
return _action ;
}
private:
int _action ; // The action accomplished on the window.
} ;
//---------------------------------------------------------------
// Win::ShowWindowStatus encapsulate the flag that comes with the
// WM_SHOWWINDOW message in the lParam parameters
//---------------------------------------------------------------
class ShowWindowStatus
{
public:
//--------------------------------------------------------------------
// Constructor. Creates the Win::ShowWindowStatus object with the
// lParam from WM_SHOWWINDOW messages.
//
// Parameters:
//
// const LPARAM flag -> The information on the window that is shown.
//--------------------------------------------------------------------
ShowWindowStatus (int status)
: _status(status)
{}
//--------------------------------------------------------------------
// Determines if the message was received due to a call to ShowWindow.
//
// Return value: True if ShowWindow was called, else false.
//--------------------------------------------------------------------
bool ShowWindowWasCalled () const
{
return _status == 0 ;
}
//--------------------------------------------------------------------
// Determines if the message was received due to the fact that the
// window was uncovered.
//
// Return value: True if the window was uncovered, else false.
//--------------------------------------------------------------------
bool WindowIsUncovered () const
{
return _status == SW_OTHERUNZOOM ;
}
//--------------------------------------------------------------------
// Determines if the message was received due to the fact that the
// window was covered.
//
// Return value: True if the window was covered, else false.
//--------------------------------------------------------------------
bool WindowIsCovered () const
{
return _status == SW_OTHERZOOM ;
}
//--------------------------------------------------------------------
// Determines if the message was received due to the fact that the
// parent was minimized.
//
// Return value: True if the parent was minimized, else false.
//--------------------------------------------------------------------
bool ParentBeingMinimised () const
{
return _status == SW_PARENTCLOSING ;
}
//--------------------------------------------------------------------
// Determines if the message was received due to the fact that the
// parent was maximised.
//
// Return value: True if the parent was maximised, else false.
//--------------------------------------------------------------------
bool ParentBeingRestored () const
{
return _status == SW_PARENTOPENING ;
}
//--------------------------------------------------------------------
// Converts the ShowWindowStatus object into a int
// Used for compatibility with the WinAPI.
//--------------------------------------------------------------------
operator int () const
{
return _status ;
}
private:
int _status ; // Status of the window that was shown/hidden.
} ;
//-----------------------------------------------------------------
// Win::SizeType encapsulating the flag that comes with the WM_SIZE
// message in the wParam parameters
//-----------------------------------------------------------------
class SizeType
{
public:
//--------------------------------------------------------------------
// Constructor. Creates the Win::SizeType object with the
// wParam from WM_SIZE messages.
//
// Parameters:
//
// const LPARAM flag -> The information on the window that is resized.
//--------------------------------------------------------------------
SizeType (WPARAM style)
: _style(style)
{}
//--------------------------------------------------------------------
// Determines if the message was received due to the fact that
// another window was maximized.
//
// Return value: True if another window was maximized, else false.
//--------------------------------------------------------------------
bool OtherWindowMaximised () const
{
return _style == SIZE_MAXHIDE ;
}
//--------------------------------------------------------------------
// Determines if the message was received due to the fact that
// another window was restored to its previous size.
//
// Return value: True if another window was restored to its previous
// size, else false.
//--------------------------------------------------------------------
bool OtherWindowRestoreSize () const
{
return _style == SIZE_MAXSHOW ;
}
//--------------------------------------------------------------------
// Determines if the message was received due to the fact that the
// window was minimized
//
// Return value: True if the window was minimized, else false.
//--------------------------------------------------------------------
bool IsBeingMinimised () const
{
return _style == SIZE_MINIMIZED ;
}
//--------------------------------------------------------------------
// Determines if the message was received due to the fact that the
// window was maximized
//
// Return value: True if the window was maximized, else false.
//--------------------------------------------------------------------
bool IsBeingMaximised () const
{
return _style == SIZE_MAXIMIZED ;
}
//--------------------------------------------------------------------
// Determines if the message was received due to the fact that the
// window was resized
//
// Return value: True if the window was resized, else false.
//--------------------------------------------------------------------
bool isBeingResized () const
{
return _style == SIZE_RESTORED ;
}
//--------------------------------------------------------------------
// Converts the SizeType object into a WPARAM
// Used for compatibility with the WinAPI.
//--------------------------------------------------------------------
operator WPARAM () const
{
return _style ;
}
private:
WPARAM _style ; // Style of the window that was resized.
} ;
typedef LRESULT (CALLBACK * ProcPtr)
(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
// The predefined window procedure.
LRESULT CALLBACK Proc ( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) ;
// The predefined window procedure for frame window.
LRESULT CALLBACK FrameProc ( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) ;
// The predefined window procedure for MDI child.
LRESULT CALLBACK MDIChildProc ( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) ;
// The predefined window procedure used for window subclasing.
LRESULT CALLBACK SubProcedure
(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
class ControlColor
{
public:
friend LRESULT CALLBACK Win::Proc ( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) ;
friend LRESULT CALLBACK FrameProc ( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) ;
friend LRESULT CALLBACK MDIChildProc ( HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam ) ;
friend LRESULT CALLBACK SubProcedure (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
ControlColor ()
{
_brush = NULL ;
_flag = 0 ;
}
void SetBrush (HBRUSH brush)
{
_brush = brush ;
}
void SetTextColor (Win::Color & textColor)
{
_flag |= 0x01 ;
_textColor = textColor ;
}
void SetBackgroundColor (Win::Color & backColor)
{
_flag |= 0x02 ;
_backColor = backColor ;
}
private:
bool ChangedTextColor ()
{
return (_flag & 0x01) != 0 ;
}
bool ChangedBackgroundColor ()
{
return (_flag & 0x02) != 0 ;
}
HBRUSH _brush ;
Win::Color _textColor ;
Win::Color _backColor ;
BYTE _flag ;
} ;
}
#endif
|
7af63471a4022611996a4515de5c7f89d0a837e5
|
6ab9a3229719f457e4883f8b9c5f1d4c7b349362
|
/uva/Volume I/00191.cpp
|
fbb44a8c9ce4677c01058e7d99e0468c32c24de2
|
[] |
no_license
|
ajmarin/coding
|
77c91ee760b3af34db7c45c64f90b23f6f5def16
|
8af901372ade9d3d913f69b1532df36fc9461603
|
refs/heads/master
| 2022-01-26T09:54:38.068385
| 2022-01-09T11:26:30
| 2022-01-09T11:26:30
| 2,166,262
| 33
| 15
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,300
|
cpp
|
00191.cpp
|
#include <cstdio>
#define MIN(a,b) ((a)<(b)?(a):(b))
#define MAX(a,b) ((a)>(b)?(a):(b))
struct point {
int x, y;
point(int _x=0, int _y=0):x(_x),y(_y){}
point operator-(const point k){
return point(x - k.x, y - k.y);
}
int operator*(const point k){
return x * k.y - y * k.x;
}
} p[6];
int dx, dy, maxx, maxy, minx, miny;
bool inside(point k){
if(k.x > maxx || k.x < minx || k.y > maxy || k.y < miny) return 0;
return 1;
}
bool lsi(point c, point d){
int da = d.x - c.x;
int db = d.y - c.y;
double s = (dx * (c.y - p[0].y) + dy * (p[0].x - c.x)) /
(double)(da * dy - db * dx);
double t = (da * (p[0].y - c.y) + db * (c.x - p[0].x)) /
(double)(db * dx - da * dy);
return (s >= 0 && s <= 1 && t >= 0 && t <= 1);
}
int main(void){
int T;
scanf("%d",&T);
while(T--){
scanf("%d%d%d%d%d%d%d%d",&p[0].x,&p[0].y,&p[1].x,
&p[1].y,&p[2].x,&p[2].y,&p[3].x,&p[3].y);
minx = MIN(p[2].x, p[3].x);
maxx = MAX(p[2].x, p[3].x);
miny = MIN(p[2].y, p[3].y);
maxy = MAX(p[2].y, p[3].y);
p[4].x = p[3].x;
p[4].y = p[2].y;
p[5].x = p[2].x;
p[5].y = p[3].y;
dx = p[1].x - p[0].x;
dy = p[1].y - p[0].y;
if(inside(p[0]) || inside(p[1]) ||
lsi(p[2],p[4]) || lsi(p[2],p[5]) ||
lsi(p[3],p[4]) || lsi(p[3],p[5]))
puts("T");
else puts("F");
}
return 0;
}
|
fcd2f1b5f59c629b819cf48c839500468fb6f5d4
|
f2c3fcc3543b7f1120cd0599aa03844fabb936bf
|
/plugins/conditions/battery/batterycondition.cpp
|
7209507e7c7a62626830b1cb6e1e6e704fdf9b69
|
[
"Unlicense"
] |
permissive
|
pastillilabs/situations-symbian
|
2ed6397ef2d50e3e17de356bd7abb2776b7d4338
|
909da8a2067ad33ab8d290a6420a9e8f0abd96e6
|
refs/heads/master
| 2021-01-19T00:55:22.370919
| 2018-04-22T16:34:06
| 2018-04-22T16:34:06
| 60,176,343
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,707
|
cpp
|
batterycondition.cpp
|
#include "batterycondition.h"
#include <identifiers.h>
static const char* KEY_LESS_THAN("lessThan");
BatteryCondition::BatteryCondition(QObject *parent)
: Condition(parent)
, mLessThan(true)
, mValue(50)
, mSystemDeviceInfo(0)
{
}
BatteryCondition::~BatteryCondition()
{
doStop();
}
bool BatteryCondition::lessThan() const
{
return mLessThan;
}
void BatteryCondition::setLessThan(bool lessThan)
{
if(lessThan != mLessThan)
{
mLessThan = lessThan;
emit lessThanChanged(lessThan);
}
}
int BatteryCondition::value() const
{
return mValue;
}
void BatteryCondition::setValue(const int value)
{
if(value != mValue)
{
mValue = value;
emit valueChanged(value);
}
}
void BatteryCondition::resolveActive()
{
const int level(mSystemDeviceInfo->batteryLevel());
const bool active(mLessThan ? level < mValue : level > mValue);
setActive(active);
}
void BatteryCondition::batteryLevelChanged(int /*level*/)
{
resolveActive();
}
void BatteryCondition::doStart()
{
if(!mSystemDeviceInfo)
{
mSystemDeviceInfo = new QSystemDeviceInfo(this);
connect(mSystemDeviceInfo, SIGNAL(batteryLevelChanged(int)), this, SLOT(batteryLevelChanged(int)));
}
resolveActive();
}
void BatteryCondition::doStop()
{
delete mSystemDeviceInfo;
mSystemDeviceInfo = 0;
setActive(false);
}
void BatteryCondition::doStore(QVariantMap& data) const
{
data[Identifiers::keyValue] = mValue;
data[KEY_LESS_THAN] = mLessThan;
}
void BatteryCondition::doRestore(const QVariantMap& data)
{
setValue(data[Identifiers::keyValue].toInt());
setLessThan(data[KEY_LESS_THAN].toBool());
}
|
7e3d22ef1de179a9450c270817ac74643b395f2a
|
c73d67bf5aa1adcb50dfc3c67540dc0ad34d62cd
|
/height of generic tree.cpp
|
67c926baca112ab9eb4630b91eb7ed4c3eef3757
|
[] |
no_license
|
GiteshWadhwa/Data-Structures-with-CPP
|
88a834a2e23137d6a67e709209c549784f2ad1ea
|
16cb70669d55d531e7b5989337b4a8ddd9ec1bcc
|
refs/heads/master
| 2020-04-01T22:59:53.730658
| 2019-04-04T12:47:00
| 2019-04-04T12:47:00
| 153,736,427
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,267
|
cpp
|
height of generic tree.cpp
|
#include<queue>
#include<iostream>
using namespace std;
#include "Tree 04 maximum data node.h"
Tree<int>* input(){
int rootData;
cout<<"enter root node:";
cin>>rootData;
Tree<int>* root=new Tree<int>(rootData);
queue<Tree<int>*>pendingNode;
pendingNode.push(root);
while(pendingNode.size()!=0)
{
Tree<int>* front=pendingNode.front();
pendingNode.pop();
cout<<"enter the number of children of"<<front->data<<endl;
int numChild;
cin>>numChild;
for(int i=0;i<numChild;i++)
{
int childData;
cout<<"enter"<<i<<"th child of "<<front->data<<endl;
cin>>childData;
Tree<int>* child=new Tree<int>(childData);
front->children.push_back(child);
pendingNode.push(child);
}
}
return root;
}
void print(Tree<int>* root){
if(root==NULL)
{
return ;
}
cout<<root->data<<":";
for(int i=0;i<root->children.size();i++)
{
cout<<root->children[i]->data<<",";
}
cout<<endl;
for(int i=0;i<root->children.size();i++)
{
print(root->children[i]);
}
}
int countNodes(Tree<int>* root)
{
int ans=1;
for(int i=0;i<root->children.size();i++)
{
ans+=countNodes(root->children[i]);
}
return ans;
}
int sum(Tree<int>* root)
{
int s=0;
if(root!=NULL)
{
s+=root->data;
for(int i=0;i<root->children.size();i++)
{
s= s+sum(root->children[i]);
}
return s;
}
}
int maximumDataNode(Tree<int>* root)
{
int max=root->data;
for(int i=0;i<root->children.size();i++)
{
int ans= maximumDataNode(root->children[i]);
if(max < ans)
{
max=ans;
}
}
return max;
}
int height(Tree<int>* root)
{
int h=0;
if(root!=NULL)
{
for(int i=0;i<root->children.size();i++)
{
h=max(h,height(root->children[i]));
}
}
return h+1;
}
int main()
{
Tree<int>* root=input();
print(root);
int ans=countNodes(root);
cout<<"Total Nodes are: " <<ans<<endl;
int s=sum(root);
cout<<"Sum of all nodes :"<<s<<endl;
int m= maximumDataNode(root);
cout<<"maximum data node is"<<" "<<m<<endl;
int h=height(root);
cout<<"height of tree is:"<<h;
}
|
976a079e9dd06fcd52c207ccf8488aed8bb7b26a
|
6e13da744ae9c809ff35e2a123d0c8650d3b3989
|
/tests/log/test_log.cc
|
912fd708eddf11efe6093422b8e281e752d9dff1
|
[
"BSD-2-Clause",
"Apache-2.0"
] |
permissive
|
ecmwf/eckit
|
1e6026fa1791e7c4aaa51109afed010c4a5b1ed3
|
de68dd7b5e8d4d06005b6856a648cceb5cf43827
|
refs/heads/develop
| 2023-08-16T16:48:14.426020
| 2023-08-03T06:48:36
| 2023-08-03T06:48:36
| 122,974,453
| 20
| 29
|
Apache-2.0
| 2023-09-01T10:01:43
| 2018-02-26T13:33:38
|
C++
|
UTF-8
|
C++
| false
| false
| 3,077
|
cc
|
test_log.cc
|
/*
* (C) Copyright 1996- ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
#include "eckit/config/LibEcKit.h"
#include "eckit/filesystem/LocalPathName.h"
#include "eckit/log/Bytes.h"
#include "eckit/log/Log.h"
#include "eckit/runtime/Tool.h"
#include "eckit/testing/Test.h"
using namespace std;
using namespace eckit;
using namespace eckit::testing;
namespace eckit::test {
//----------------------------------------------------------------------------------------------------------------------
CASE("test_debug") {
Log::debug() << "debug message 1" << std::endl;
}
CASE("test_debug_library") {
Log::debug<LibEcKit>() << "debug message 2" << std::endl;
}
CASE("test_debug_macro") {
LOG_DEBUG(true, LibEcKit) << "debug message 3" << std::endl;
LOG_DEBUG(false, LibEcKit) << "debug message 4" << std::endl;
}
CASE("test_info") {
Log::info() << "info message 1" << std::endl;
}
CASE("test_warning") {
Log::warning() << "warning message 1" << std::endl;
}
CASE("test_error") {
Log::error() << "error message 1" << std::endl;
}
CASE("test_panic") {
Log::panic() << "panic message 1" << std::endl;
}
CASE("test_strerr") {
LocalPathName p("/tmp/edfpmjq3480hfnsribnzasdfibv");
p.unlink();
}
CASE("test_bytes") {
eckit::Bytes b(1.);
EXPECT("1 byte" == std::string(b));
EXPECT("1 " == b.shorten());
b = -1.;
EXPECT("-1 byte" == std::string(b));
EXPECT("-1 " == b.shorten());
b = 1024.;
EXPECT("1 Kbyte" == std::string(b));
EXPECT("1K" == b.shorten());
b = 1024. * 1024.;
EXPECT("1 Mbyte" == std::string(b));
EXPECT("1M" == b.shorten());
b = 1024. * 1024. * 1024.;
EXPECT("1 Gbyte" == std::string(b));
EXPECT("1G" == b.shorten());
b = 1024. * 1024. * 1024. * 1024.;
EXPECT("1 Tbyte" == std::string(b));
EXPECT("1T" == b.shorten());
b = 1024. * 1024. * 1024. * 1024. * 1024.;
EXPECT("1 Pbyte" == std::string(b));
EXPECT("1P" == b.shorten());
b = 1024. * 1024. * 1024. * 1024. * 1024. * 1024.;
EXPECT("1 Ebyte" == std::string(b));
EXPECT("1E" == b.shorten());
b = 1024. * 1024. * 1024. * 1024. * 1024. * 1024. * 1024.;
EXPECT("1 Zbyte" == std::string(b));
EXPECT("1Z" == b.shorten());
b = 1024. * 1024. * 1024. * 1024. * 1024. * 1024. * 1024. * 1024.;
EXPECT("1 Ybyte" == std::string(b));
EXPECT("1Y" == b.shorten());
b = 1024. * 1024. * 1024. * 1024. * 1024. * 1024. * 1024. * 1024. * 1024.;
EXPECT("1024 Ybytes" == std::string(b));
EXPECT("99Y" == b.shorten());
}
//----------------------------------------------------------------------------------------------------------------------
} // namespace eckit::test
int main(int argc, char** argv) {
return run_tests(argc, argv);
}
|
a9504893a76f3c06edb1b7ceda5b48f935a57be6
|
fdf164b8336cb36c4b351bf6630cdc90c59111a5
|
/include/sweater/RangeTree/BinaryRT.hpp
|
8293cccb9f480b780ab0dd45744888ca21faeab3
|
[] |
no_license
|
sportdeath/Chainmail
|
57da02d492ad08bccac475334f93ffcb57224008
|
eeb1f784acdd07f1929d8442916bad87f6f0ca03
|
refs/heads/master
| 2021-01-12T08:14:36.949935
| 2018-10-29T02:08:13
| 2018-10-29T02:08:13
| 76,519,180
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 952
|
hpp
|
BinaryRT.hpp
|
#ifndef BINARYRT_HPP
#define BINARYRT_HPP
#include "sweater/RangeTree/RT.hpp"
template <typename T, typename Node, typename Derived>
class BinaryRT : public RT<T, Derived> {
public:
typedef typename std::vector<T>::iterator iterator;
BinaryRT(){
leftChild = nullptr;
rightChild = nullptr;
node = nullptr;
};
/**
* Assigns max and min and sorts
*/
BinaryRT (
iterator begin,
iterator end,
bool sorted);
static iterator rightMin(iterator begin, iterator end);
/**
* Deletes children
*/
~BinaryRT();
Node * getNode();
Derived * getChild(bool left);
const T & getMax() const;
const T & getMin() const;
bool chooseBranch(const T & e, bool left) const;
protected:
Derived * leftChild;
Derived * rightChild;
Node * node;
private:
T min;
T max;
};
#include "../../../src/RangeTree/BinaryRT.cpp"
#endif
|
fcc506e8b9354cba0c18b75a2394837bbcb3a9e4
|
2cd5288a26b969775c59be81d71c2ae2ad995070
|
/Compilation/TransactSQL/ChainSyntax.cpp
|
cddd67c8d26e6a5621c7c100e04837e73b516e26
|
[] |
no_license
|
ArcaneSoftware/Dominion.Lexyacc
|
3f30cccf6f409e818d9cd1314c07d0999c8310c2
|
1f6035a03dfb28b3811997a3d33093af6c9f0700
|
refs/heads/master
| 2022-06-16T10:26:54.003065
| 2017-03-10T01:53:31
| 2017-03-10T01:53:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,367
|
cpp
|
ChainSyntax.cpp
|
//*******************************************************************************************************************//
//ORGANIZATION:
//AUTHOR:
//SUMMARY:
//*******************************************************************************************************************//
#include "ChainAST.h"
using namespace Dominion::Compilation::TransactSQL;;
//*******************************************************************************************************************//
//CChainAST
//*******************************************************************************************************************//
CChainAST::CChainAST() :
CTransactSQLSyntax(ESyntaxType::Chain),
_currentID(NONE_ID),
_nextID(NONE_ID)
{
}
CChainAST::CChainAST(C_CHAIN_AST& that) :
CTransactSQLSyntax(that),
_currentID(that._currentID),
_nextID(that._nextID)
{
}
CChainAST::CChainAST(C_CHAIN_AST&& that) :
CTransactSQLSyntax(that),
_currentID(move(that._currentID)),
_nextID(move(that._nextID))
{
}
CChainAST::CChainAST(int32_t liveLine, int32_t currentID, int32_t nextID) :
CTransactSQLSyntax(ESyntaxType::Chain, liveLine),
_currentID(currentID),
_nextID(nextID)
{
}
CChainAST::~CChainAST()
{
}
C_CHAIN_AST& CChainAST::operator=(C_CHAIN_AST& that)
{
CTransactSQLSyntax::operator=(that);
_currentID = that._currentID;
_nextID = that._nextID;
return *this;
}
|
1e7a4875d950910e618c93d10503c6f8c992bde1
|
6e001354cb76c94b4ce064487b5b3ba938d3a935
|
/managers/visualiser/src/control/CRecognition.h
|
c0c019b3184d3a6a218465163aab05aade5d0f74
|
[] |
no_license
|
SilentButeo2/equids
|
4f42f26bca432e9f799487c629a8b7d5cc127e30
|
5a001a7cc50091052aa21d81ddc79af3e142689a
|
refs/heads/master
| 2021-05-26T23:13:23.419500
| 2013-10-01T09:46:30
| 2013-10-01T09:46:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,299
|
h
|
CRecognition.h
|
/*
* File name: CRecognition.h
* Date: 2010
* Author: Tom Krajnik
*/
#ifndef __CRECOGNITION_H__
#define __CRECOGNITION_H__
#include "CRawImage.h"
#include "CTimer.h"
#include <math.h>
#define MAX_SEGMENTS 10000
#define COLOR_PRECISION 32
#define COLOR_STEP 8
typedef struct{
int x;
int y;
int size;
}SSegment;
typedef struct{
int x;
int y;
}SPixelPosition;
class CRecognition
{
public:
CRecognition();
~CRecognition();
SPixelPosition findMean(CRawImage* image);
SPixelPosition findSegment(CRawImage* image);
void learnPixel(unsigned char* a);
void addPixel(unsigned char* a);
void increaseTolerance();
void decreaseTolerance();
void resetColorMap();
SPixelPosition findPath(CRawImage* image);
private:
int tolerance;
float evaluatePixel1(unsigned char* a);
float evaluatePixel2(unsigned char* a);
float evaluatePixel3(unsigned char* a);
int evaluatePixelFast(unsigned char *a);
void rgbToHsv(unsigned char r, unsigned char g, unsigned char b, unsigned int *h, unsigned char *s, unsigned char *v );
unsigned char learned[3];
unsigned int learnedHue;
unsigned char learnedSaturation,learnedValue;
unsigned char *colorArray;
SSegment *segmentArray;
bool debug;
int *stack;
int *buffer;
};
#endif
/* end of CRecognition.h */
|
3c7982fa2636bad67a8e03119800f7c73bb0af85
|
5faa3860f404e8b86d0840cdfa118e2bd82af10b
|
/Advanced Level- Practice/1020. Tree Traversals (25).cpp
|
3c360b4122afd4befd98d1b358ded7be3f66be74
|
[] |
no_license
|
Mrhuangyi/PAT-Solutions
|
d54a65bfe7ea9b1c9435e5a94c995111f3a63e5c
|
cf8faef8ca167a015708ec7ed6db1bfdad46b75b
|
refs/heads/master
| 2021-04-15T10:18:46.323283
| 2018-09-04T10:17:55
| 2018-09-04T10:17:55
| 126,486,769
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,182
|
cpp
|
1020. Tree Traversals (25).cpp
|
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn=50;
struct node{
int data;
node* lchild;
node* rchild;
};
int pre[maxn],in[maxn],post[maxn];
int n;
node* create(int postl,int postr,int inl,int inr){
if(postl>postr){
return NULL;
}
node* root = new node;
root->data=post[postr];
int k;
for(k=inl;k<=inr;k++){
if(in[k]==post[postr]){
break;
}
}
int numLeft=k-inl;
root->lchild=create(postl,postl+numLeft-1,inl,k-1);
root->rchild=create(postl+numLeft,postr-1,k+1,inr);
return root;
}
int num=0;
void bfs(node* root){
queue<node*> q;
q.push(root);
while(!q.empty()){
node* now=q.front();
q.pop();
printf("%d",now->data);
num++;
if(num<n) printf(" ");
if(now->lchild!=NULL) q.push(now->lchild);
if(now->rchild!=NULL) q.push(now->rchild);
}
}
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&post[i]);
}
for(int i=0;i<n;i++){
scanf("%d",&in[i]);
}
node* root=create(0,n-1,0,n-1);
bfs(root);
return 0;
}
|
b1d43c0f4e1a7280ed7238ff5d570e496e030048
|
b35dbd265b93ea142f27e3a787436d4925430bfc
|
/ReadConsole/ProcessHandler.cpp
|
cd3df8726c07a8f9218e18cbd17162aedc1c995d
|
[] |
no_license
|
flice/ReadConsole
|
f4dc22dab3c5e058bdbede90e8a15ca082d6d4b0
|
28761fd811bd2c76bbf9cc974fbfc4bda39d806b
|
refs/heads/master
| 2021-05-29T22:57:23.150195
| 2015-11-20T12:59:15
| 2015-11-20T12:59:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 899
|
cpp
|
ProcessHandler.cpp
|
#include "ProcessHandler.h"
CProcessHandler::CProcessHandler(QObject *parent)
: QObject(parent)
{
//QString program = "C:/Users/Fabian/Documents/Tests/ConsolePrinter/Win32/Debug/ConsolePrinter.exe";
myProcess = new QProcess(this);
//myProcess->setProcessChannelMode(QProcess::ForwardedChannels);
//connect(myProcess, SIGNAL(readyReadStandardOutput()), this, SLOT(processOutput()));
//myProcess->execute(program);
//myProcess->setWorkingDirectory("~/SMA");
myProcess->start("/home/pi/SMA/SMAspot/SMAspot", QStringList() << "-v");
if (!myProcess->waitForStarted())
qDebug() << "Cant start the programm";
if (!myProcess->waitForFinished())
{
qCritical() << "wait-for-finished timeout";
}
qDebug() << myProcess->readAllStandardOutput();
}
CProcessHandler::~CProcessHandler()
{
}
void CProcessHandler::processOutput()
{
//qDebug() << myProcess->readAllStandardOutput();
}
|
c9120e729be83ee9f08e53bd18cea5c839c74415
|
c327c5704336723ab194a4c6d003d2bbf90241b8
|
/2 Курс/Lab-1/Lab-1б/Lab-1б.cpp
|
7d1832c729f49c93fe8d878135463c96fec5d3bb
|
[] |
no_license
|
feest-y/Projects
|
edaa3cf522174bdbd0c26d0cf1881e07848ea9db
|
ff1f4aed5e3312dfda4db59fa5b8f4115a1f1cca
|
refs/heads/master
| 2023-07-09T23:26:18.016514
| 2021-08-18T20:51:41
| 2021-08-18T20:51:41
| 304,871,056
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 709
|
cpp
|
Lab-1б.cpp
|
#define _USE_MATH_DEFINES
#include <iostream>
#include <cmath>
class Figure
{
unsigned int A, B, C, R;
public:
Figure(unsigned int R) {
this->R = R;
A = B = C = 0;
};
Figure() {
A = B = C = R = 0;
};
Figure(unsigned int A, unsigned int B, unsigned int C, unsigned int R = 0) {
this->A = A;
this->B = B;
this->C = C;
this->R = R;
};
double SquareOfTriangle() {
float p = (A + B + C) / 2;
return sqrt((p * (p - A) * (p - B) * (p - C)));
}
double SquareOfCircle() {
return M_PI * R * R;
}
};
int main()
{
Figure A(3, 2, 3, 4);
std::cout << "SquareOfTriangle > " << A.SquareOfTriangle() << std::endl;
std::cout << "SquareOfCircle > " << A.SquareOfCircle();
return 0;
}
|
265850110c401c3df33728c5a5291a8cdca52aea
|
da501178032375b6bde5559f83674a506908be86
|
/source/GameLoop.cpp
|
896c6c40ccf77005c7c1af7e762aba38fc2d4d46
|
[] |
no_license
|
banysk/term3_Roguelike
|
98e7443420d246dc268261519815a946b5daac6b
|
e3000094f509c45a6e390ef0ef87d3f6d3e9dbde
|
refs/heads/main
| 2023-02-22T23:56:11.789341
| 2021-01-24T13:01:46
| 2021-01-24T13:01:46
| 332,427,402
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,680
|
cpp
|
GameLoop.cpp
|
#pragma once
#include "../Headers/GameLoop.h"
#include <curses.h>
#include <fstream>
#include <iostream>
#define LEFT 260
#define UP 259
#define RIGHT 261
#define DOWN 258
void GameLoop::parse_cfg() {
std::string file_line, parameter_name, parameter_argument;
int equals_sign_position;
std::ifstream cfg_in("settings.cfg");
while (cfg_in >> file_line) {
equals_sign_position = file_line.find('=');
parameter_name = file_line.substr(0, equals_sign_position);
parameter_argument = file_line.substr(equals_sign_position + 1, file_line.length() - 1);
(*args)[parameter_name] = parameter_argument;
}
cfg_in.close();
std::ofstream cfg_out("settings.cfg");
for (auto parameter_pair : *args) {
cfg_out << parameter_pair.first << "=" << parameter_pair.second << "\n";
}
cfg_out.close();
}
GameLoop::GameLoop() : args(std::unique_ptr<std::map<std::string, std::string>>(new std::map<std::string, std::string>())) {
// get settings
parse_cfg();
// generate map pattern
MapGenerator map_generator(std::stoi((*args)["DIMENSIONS"]), std::stoi((*args)["MAX_TUNNELS"]), std::stoi((*args)["MAX_LENGTH"]));
map_generator.generate_map(*args);
map_generator.save_pattern();
// create map
map = Map(std::stoi((*args)["DIMENSIONS"]), std::stoi((*args)["OVERVIEW"]), std::stoi((*args)["FOG"]));
map.init_vectors();
map.load_map_pattern(*args);
}
void GameLoop::init_window() {
int d = std::stoi((*args)["DIMENSIONS"]);
initscr();
keypad(stdscr, TRUE);
resize_term(d + 2, d + 50 + 2);
noecho();
curs_set(0);
nodelay(stdscr, true);
start_color();
init_pair(1, COLOR_BLACK, COLOR_YELLOW); // WALL
init_pair(2, COLOR_WHITE, COLOR_BLACK); // FLOOR
init_pair(3, COLOR_MAGENTA, COLOR_BLACK); // KNIGHT
init_pair(4, COLOR_CYAN, COLOR_BLACK); // PRINCESS
init_pair(5, COLOR_GREEN, COLOR_BLACK); // ZOMBIE
init_pair(6, COLOR_RED, COLOR_BLACK); // DRAGON && HP
init_pair(7, COLOR_GREEN, COLOR_WHITE); // AID_BUFF
init_pair(8, COLOR_BLUE, COLOR_WHITE); // MANA_BUFF
init_pair(9, COLOR_RED, COLOR_BLACK); // FIREBALL
init_pair(10, COLOR_BLUE, COLOR_BLACK); // MANA
init_pair(11, COLOR_YELLOW, COLOR_BLACK); // POINTS
}
void GameLoop::start_game() {
long long fireball_time = clock();
long long monster_time = fireball_time;
long long player_time = monster_time;
bool player_moved = false;
int ch;
init_window();
while (map.status() == PLAY) {
if (clock() - fireball_time >= std::stoi((*args)["TIK"]) / 3) {
map.move_fireballs();
fireball_time = clock();
}
if (clock() - monster_time >= 2 * std::stoi((*args)["TIK"])) {
map.move_monsters();
monster_time = clock();
}
if ((ch = getch(stdscr)) == ERR) {
}
else if (clock() - player_time >= std::stoi((*args)["TIK"])) {
switch (ch) {
case 'W':
case 'w':
player_moved = true;
map.move_knight(0, -1);
break;
case 'S':
case 's':
player_moved = true;
map.move_knight(0, 1);
break;
case 'A':
case 'a':
player_moved = true;
map.move_knight(-1, 0);
break;
case 'D':
case 'd':
player_moved = true;
map.move_knight(1, 0);
break;
case UP:
player_moved = true;
map.try_cast_fireball(0, -1);
break;
case DOWN:
player_moved = true;
map.try_cast_fireball(0, 1);
break;
case LEFT:
player_moved = true;
map.try_cast_fireball(-1, 0);
break;
case RIGHT:
player_moved = true;
map.try_cast_fireball(1, 0);
break;
default:
player_moved = false;
break;
}
if (player_moved) {
player_time = clock();
player_moved = false;
}
}
map.render();
}
map.print_center(31, std::string(30, '='));
switch (map.status())
{
case VICTORY:
color_set(11, NULL);
map.print_center(33, "VICTORY!!!");
break;
case LOSE:
color_set(6, NULL);
map.print_center(33, "LOSE...");
break;
}
nodelay(stdscr, false);
getch();
endwin();
}
|
9ffd050253828fada7f42b9ab273b66ac4e9996c
|
c3bfd0eb01cf69b4f35c3309de43ef9820e5f8d6
|
/test/aoj_ALDS1_14_B_l61m1.test.cpp
|
57b821acf993e1b35eefb0182407c23e127eb3c3
|
[
"MIT"
] |
permissive
|
kmyk/rsk0315-library
|
deae1609691e7651bafc5c9bb393a00ff552dd19
|
344f8f8c6c8c8951637154d6cb87cfb3dbc50376
|
refs/heads/master
| 2023-02-26T17:24:31.796182
| 2021-02-01T14:50:34
| 2021-02-01T14:50:34
| 292,615,801
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 931
|
cpp
|
aoj_ALDS1_14_B_l61m1.test.cpp
|
#define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_14_B"
#include <cstdio>
#include <chrono>
#include <random>
#include <string>
#include "String/rolling_hash_l61m1.cpp"
int main() {
char buf[1048576];
scanf("%s", buf);
std::string t = buf;
scanf("%s", buf);
std::string p = buf;
std::seed_seq ss{
static_cast<uintmax_t>(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now().time_since_epoch()).count()),
static_cast<uintmax_t>(__builtin_ia32_rdtsc()),
};
std::mt19937 rng(ss);
uintmax_t base = std::uniform_int_distribution<uintmax_t>(0, rolling_hash_l61m1::mod-1)(rng);
uintmax_t crit = rolling_hash_l61m1(p.begin(), p.end(), base).substr(0);
rolling_hash_l61m1 rt(t.begin(), t.end(), base);
for (size_t i = 0; i + p.length() <= t.length(); ++i) {
if (rt.substr(i, p.length()) == crit)
printf("%zu\n", i);
}
}
|
ebd8c8a9d35f1f2a94ac9f690d32842c1e95261f
|
e272a9c0b27f445a21c007723b821a262a43531a
|
/SimplePhotoViewer/Win2D/winrt/impl/Microsoft.Graphics.Canvas.Printing.1.h
|
b349f5fe04cb5fdef08b37acc0c9e0ab173103ec
|
[
"MIT"
] |
permissive
|
Hearwindsaying/SimplePhotoViewer
|
777facb3b6c18e0747da2f70b02fff6c481a2168
|
12d9cd383d379ebce6696263af58c93a2769073b
|
refs/heads/master
| 2021-11-05T17:41:29.288860
| 2021-10-31T11:04:36
| 2021-10-31T11:04:36
| 176,699,093
| 3
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,771
|
h
|
Microsoft.Graphics.Canvas.Printing.1.h
|
// WARNING: Please don't edit this file. It was generated by C++/WinRT v1.0.180821.2
#pragma once
#include "Microsoft.Graphics.Canvas.0.h"
#include "winrt/impl/Windows.Graphics.Printing.0.h"
#include "winrt/impl/Windows.Foundation.0.h"
#include "Microsoft.Graphics.Canvas.Printing.0.h"
WINRT_EXPORT namespace winrt::Microsoft::Graphics::Canvas::Printing {
struct WINRT_EBO ICanvasPreviewEventArgs :
Windows::Foundation::IInspectable,
impl::consume_t<ICanvasPreviewEventArgs>
{
ICanvasPreviewEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct WINRT_EBO ICanvasPrintDeferral :
Windows::Foundation::IInspectable,
impl::consume_t<ICanvasPrintDeferral>
{
ICanvasPrintDeferral(std::nullptr_t = nullptr) noexcept {}
};
struct WINRT_EBO ICanvasPrintDocument :
Windows::Foundation::IInspectable,
impl::consume_t<ICanvasPrintDocument>,
impl::require<ICanvasPrintDocument, Microsoft::Graphics::Canvas::ICanvasResourceCreator, Windows::Foundation::IClosable, Windows::Graphics::Printing::IPrintDocumentSource>
{
ICanvasPrintDocument(std::nullptr_t = nullptr) noexcept {}
};
struct WINRT_EBO ICanvasPrintDocumentFactory :
Windows::Foundation::IInspectable,
impl::consume_t<ICanvasPrintDocumentFactory>
{
ICanvasPrintDocumentFactory(std::nullptr_t = nullptr) noexcept {}
};
struct WINRT_EBO ICanvasPrintEventArgs :
Windows::Foundation::IInspectable,
impl::consume_t<ICanvasPrintEventArgs>
{
ICanvasPrintEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct WINRT_EBO ICanvasPrintTaskOptionsChangedEventArgs :
Windows::Foundation::IInspectable,
impl::consume_t<ICanvasPrintTaskOptionsChangedEventArgs>
{
ICanvasPrintTaskOptionsChangedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
}
|
a710ca1de44d3f9ce735e16389e719560cbc4bc4
|
a64300f3f43944c3f57053232ab1c8a9c9cfe356
|
/Hzoj_Code/242-最大平均值.cpp
|
c41e29ad6553bf752d09ce98080d8bb064cef44e
|
[] |
no_license
|
Remote0/Mynotes-1
|
5e84de95163b076c802e39b8a2a097dd9e61adb2
|
4314db4c3845d53f58e4fd0a2c2c90e355b21751
|
refs/heads/master
| 2022-11-26T19:47:20.441530
| 2020-08-06T18:05:06
| 2020-08-06T18:05:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,324
|
cpp
|
242-最大平均值.cpp
|
/*************************************************************************
> File Name: 242-最大平均值.cpp
> Author:fangsong
> Mail:
> Created Time: 2020年05月17日 星期日 15时56分28秒
************************************************************************/
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<iomanip>
#include<algorithm>
#include<map>
#include<vector>
using namespace std;
#define MAX_N 100000
#define INF 0x3f3f3f3f
long long a[MAX_N + 5];
long long b[MAX_N + 5];
long long sum[MAX_N + 5];
long long n, m;
bool check(long long A) {
for(long long i = 1; i <= n; i++) {
b[i] = a[i] - A;
sum[i] = b[i] + sum[i - 1];
}
long long Y = 0;
for(long long j = m; j <= n; j++) {
Y = min(Y, sum[j - m]);
if(sum[j] - Y >= 0) return true;
}
return false;
}
long long bs(long long l, long long r) {
if(l == r) return l;
long long mid = (l + r + 1) >> 1;
if(check(mid)) return bs(mid, r);
return bs(l, mid - 1);
}
int main() {
ios::sync_with_stdio(false);
cin >> n >> m;
long long l = INF, r = -INF;
for(long long i = 1; i <= n; i++) {
cin >> a[i];
a[i] *= 1000;
l = min(l, a[i]);
r = max(r, a[i]);
}
cout << bs(l, r) << endl;
return 0;
}
|
c016697aa090cecec1dbfede7dd2584d0a2398c8
|
454184c9d6bc7a80e2ee2c7a0515009199ecbaa8
|
/main.cpp
|
d4c0d1b59102bf9221eb8f00a7eaf83d5d98d90a
|
[] |
no_license
|
rinthel/rttr_sol_lua_test
|
905a7286ce0149d0a0b5ce6876afcf1bbd32bd6d
|
d0d7b37afc9c60bfecf3cac335a65a9094f5f32a
|
refs/heads/master
| 2020-04-10T00:22:00.411012
| 2018-12-07T14:14:20
| 2018-12-07T14:14:20
| 160,683,343
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,282
|
cpp
|
main.cpp
|
#include <sol.hpp>
#include <rttr/type>
#include <rttr/registration>
#include <rttr/visitor.h>
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include "RttrSolBinder.h"
#include <iostream>
#include <math.h>
static auto console = spdlog::stdout_color_mt("console");
namespace test {
class Vec {
public:
static void declare(sol::state& state) {
console->info("declare test::Vec");
state.new_usertype<Vec>("Vec",
sol::constructors<Vec(), Vec(float, float)>(),
"x", &Vec::x,
"y", &Vec::y,
"add", &Vec::add,
"length", &Vec::length
);
}
Vec() {}
Vec(float _x, float _y): x(_x), y(_y) {}
float x {0.0f};
float y {0.0f};
const Vec add(const Vec& v) const { return Vec(x + v.x, y + v.y); }
float length() const { return sqrtf(x*x + y*y); }
RTTR_ENABLE()
};
class Rigidbody {
public:
static void declare(sol::state& state) {
console->info("declare test::Rigidbody");
state.new_usertype<Rigidbody>("Rigidbody",
"pos", &Rigidbody::pos,
"rot", &Rigidbody::rot
);
}
Vec pos {Vec(0.0f, 0.0f)};
Vec rot {Vec(0.0f, 0.0f)};
RTTR_ENABLE()
};
}
using namespace test;
RTTR_REGISTRATION
{
rttr::registration::class_<Vec>("Vec")
.property("x", &Vec::x)
.property("y", &Vec::y)
.method("add", &Vec::add)
.method("length", &Vec::length)
;
rttr::registration::class_<Rigidbody>("Rigidbody")
.property("pos", &Rigidbody::pos)
.property("rot", &Rigidbody::rot)
;
}
int main() {
auto solTypeToString = [](sol::type solType) {
switch (solType) {
default:
case sol::type::none: return "none";
case sol::type::nil: return "nil";
case sol::type::number: return "number";
case sol::type::boolean: return "bool";
case sol::type::function: return "function";
case sol::type::string: return "string";
case sol::type::userdata: return "userdata";
case sol::type::lightuserdata: return "lightuserdata";
case sol::type::table: return "table";
case sol::type::poly: return "poly";
}
};
console->info("start rttr+sol+lua test...");
sol::state lua;
lua.open_libraries(sol::lib::base);
const char* showGlobal = R"(
local function showGlobalTable()
for k, v in pairs(_G) do
print(k)
end
end
showGlobalTable()
)";
BindRttrToSol(lua);
console->info("----------------");
lua.script(showGlobal);
// Vec::declare(lua);
console->info("----------------");
lua.script(showGlobal);
// Rigidbody::declare(lua);
// lua.new_usertype<Vec>("Vec");
auto startsWith = [](const std::string &key, const std::string &prefix) -> bool {
return (key.size() >= prefix.size()) && (key.compare(0, prefix.size(), prefix) == 0);
};
auto solMembers = [&](std::string&& name) {
sol::table metaTable = lua[name][sol::metatable_key];
std::vector<std::string> keys = {};
for (const auto &pair : metaTable) {
const std::string key = pair.first.as<std::string>();
if (!startsWith(key, "__")) {
keys.push_back(key);
std::cout << key << ", ";
}
else
{
// The Meta Methods and stuff here
}
}
return keys;
};
Vec vec(1.0f, 2.0f);
lua["v"] = vec;
lua.script("v.x = 3.0");
solMembers("v");
lua.script(R"( print("Hello from lua!") )");
lua.script(R"( print("type of Vec is " .. type(Vec)) )");
lua.script(R"( print("vec: [" .. v.x .. ", " .. v.y .. "]") )");
lua.script(R"( print("type of Vec's instance is " .. type(v)) )");
console->info("mod vec: [{}, {}]", vec.x, vec.y);
// Vec luaVec = lua["v"];
// console->info("lua vec: [{}, {}]", luaVec.x, luaVec.y);
// Rigidbody rb;
// rb.pos = Vec(1.0, 2.0);
// rb.rot = Vec(30.0, 60.0);
// // lua["rb"] = rb;
// // sol::table
// console->info("mod Rigidbody pos: [{}, {}]", rb.pos.x, rb.pos.y);
return 0;
}
|
88b396664a97702d019de4dfb4d2606530995d00
|
c7a4cde53c0cb8c34be8b66f57ebda0e68517750
|
/seconds.cpp
|
a76677dfb6579981c8f41b525486dbba5a30faf6
|
[] |
no_license
|
Joshua-Salvador/cpp-primer
|
58ad4ccf66b41764be440e9128c0469ed01e91c0
|
df846ebc292bcc5a8b5b4feb0ee4533b4568e472
|
refs/heads/main
| 2023-04-08T09:14:48.490879
| 2021-04-15T08:06:33
| 2021-04-15T08:06:33
| 358,188,664
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 992
|
cpp
|
seconds.cpp
|
// seconds.cpp -- get number of seconds to days, hours, minutes, seconds
#include <iostream>
int main()
{
using namespace std;
cout.setf(ios_base::fixed, ios_base::floatfield);
const double hours_day = 24.0;
const double minutes_hour = 60.0;
const double seconds_minute = 60.0;
long long seconds;
cout << "Enter the number of seconds:________\b\b\b\b\b\b\b";
cin >> seconds;
long double d_days = seconds / minutes_hour / seconds_minute / hours_day;
int i_days = static_cast<int> (d_days);
long double d_hours = (d_days - i_days) * hours_day;
int i_hours = static_cast<int> (d_hours);
long double d_minutes = (d_hours - i_hours) * minutes_hour;
int i_minutes = static_cast<int> (d_minutes);
long double d_seconds = (d_minutes - i_minutes) * seconds_minute;
int i_seconds = static_cast<int> (d_seconds);
cout << seconds << " seconds = " << i_days << " days, " << i_hours << " hours, ";
cout << i_minutes << " minutes, " << i_seconds << " seconds" << endl;
return 0;
}
|
b20f637ceb6d12803a3c1fe34c51700f789f10ef
|
8e3c901d5d15a7c437e26e04d86dd5ef5ae06b70
|
/CastleVania/CastleVania/DoubleShotItem.h
|
0e6cbed3ffd2372d32704630da705af27378672e
|
[] |
no_license
|
hoangvinh121299/CastleVaina2
|
f90f00801a03ab5fff86dee9d3fc29ce6c45f8db
|
8c6a27fd2fadb52faf501daf59db9cbfc117d1bd
|
refs/heads/master
| 2023-02-15T12:08:34.816487
| 2021-01-11T07:51:45
| 2021-01-11T07:51:45
| 289,404,037
| 1
| 0
| null | 2021-01-10T18:57:26
| 2020-08-22T02:25:16
|
C++
|
UTF-8
|
C++
| false
| false
| 329
|
h
|
DoubleShotItem.h
|
#pragma once
#ifndef __ITEMDOUBLESHOT_H__
#define __ITEMDOUBLESHOT_H__
#define ITEMDOUBLESHOT_GRAVITY 0.25f
#define ITEMDOUBLESHOT_TIMEDISPLAYMAX 5000
#define ITEMDOUBLESHOT_TIMEWAITMAX 300
#include "Item.h"
class DoubleShotItem :
public Item
{
public:
DoubleShotItem(float X, float Y);
virtual ~DoubleShotItem();
};
#endif
|
fd7fd06802540ad1400d485981d1d23e4c10ebde
|
79a01ae53772070f422a9788e7307789bdafe24f
|
/mandelbrot.cpp
|
40990d8785d400cbd7b904b40f6eadc39e3738d6
|
[
"Unlicense"
] |
permissive
|
ridespirals/mandelbrot
|
f574e6d97aa1fa4d7a4cf6e6ef826891cf4dc530
|
882c4cd26ec27a4586654e56815395f31b867b12
|
refs/heads/master
| 2021-01-25T14:04:29.245839
| 2019-03-06T04:08:08
| 2019-03-06T04:08:08
| 123,650,282
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,660
|
cpp
|
mandelbrot.cpp
|
#include <SDL2/SDL.h>
#include <stdio.h>
const int SCREEN_WIDTH = 1200;
const int SCREEN_HEIGHT = 800;
const int W = 800;
const int H = 800;
long double min, max, factor;
int ITERATIONS;
long double start_min = -2.87;
long double start_max = 1.0;
long double start_factor = 1;
int start_iterations = 200;
void reset() {
min = start_min;
max = start_max;
factor = start_factor;
ITERATIONS = start_iterations;
}
long double map(long double val, long double in_min, long double in_max, long double out_min, long double out_max) {
return (val - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
int main(int argc, char* argv[]) {
SDL_Window* window = NULL;
SDL_Renderer* renderer = NULL;
bool quit = false;
int count = 0;
SDL_Event e;
reset();
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
printf("Could not init SDL: %s\n", SDL_GetError());
return 1;
}
if (SDL_CreateWindowAndRenderer(
SCREEN_WIDTH, SCREEN_HEIGHT,
SDL_WINDOW_SHOWN | SDL_WINDOW_FULLSCREEN_DESKTOP,
&window, &renderer)) {
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't create window and renderer: %s", SDL_GetError());
}
SDL_RenderSetLogicalSize(renderer, W, H);
while (!quit) {
while (SDL_PollEvent(&e) != 0) {
if (e.type == SDL_QUIT) {
quit = true;
break;
}
}
const Uint8 *state = SDL_GetKeyboardState(NULL);
if (state[SDL_SCANCODE_Q]) {
quit = true;
break;
}
if (state[SDL_SCANCODE_ESCAPE] || state[SDL_SCANCODE_DELETE]) {
reset();
count = 0;
}
if (state[SDL_SCANCODE_SPACE]) {
// zoom
max -= 0.1 * factor;
min += 0.15 * factor;
factor *= 0.9349;
ITERATIONS += 5;
if (count > 30) {
// bump iterations for better accuracy as we zoom in
ITERATIONS += 5;
}
SDL_SetRenderDrawColor(renderer, 0x37, 0x2f, 0xbe, 0xff);
SDL_RenderClear(renderer);
#pragma omp parallel for
for (int x = 0; x < W; x++) {
for (int y = 0; y < H; y++) {
long double cr = map(x, 0, W, min, max);
long double ci = map(y, 0, H, min, max);
long double zr = 0.0;
long double zi = 0.0;
long double zrsq = zr * zr;
long double zisq = zi * zi;
int n = 0;
while (n < ITERATIONS && zrsq + zisq <= 4.0) {
zi = (zr + zi) * (zr + zi) - zrsq - zisq;
zi += ci;
zr = zrsq - zisq + cr;
zrsq = zr * zr;
zisq = zi * zi;
n++;
}
int bright = map(n, 0, ITERATIONS, 0, 255);
if (n == ITERATIONS || bright < 20) {
bright = 0;
}
int red = map(bright * bright, 0, 6502, 0, 255);
int green = bright;
int blue = map(sqrt(bright), 0, sqrt(255), 0, 255);
SDL_SetRenderDrawColor(renderer, red, green, blue, 255);
SDL_RenderDrawPoint(renderer, x, y);
}
}
SDL_RenderPresent(renderer);
}
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
|
fbb270b0c53e3842b4e02a3d292f8117dd643f51
|
c8dae092e52dc66a2efeb58692f4d1008d66dff2
|
/CPSC 350/Assignment-5/Student.cpp
|
df2887e4aed9f8aa7460a905a59ecc426862affc
|
[] |
no_license
|
tetsu100/Undergrad-Assignments
|
378d5290c77915d96a5a216aec5d9e6ce7bcd7b7
|
da2e80d48acc29bab8e8117d25c0ad3085bd449c
|
refs/heads/master
| 2021-01-17T18:11:42.728137
| 2016-10-18T06:42:20
| 2016-10-18T06:42:20
| 71,215,558
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,081
|
cpp
|
Student.cpp
|
#include "Student.h"
#include <iostream>
Student::~Student()
{}
Student::Student()
{
studentID = -1;
}
Student::Student(int id, string m_name, string m_year, string m_major, double gpa, int aid)
{
studentID = id;
name = m_name;
year = m_year;
major = m_major;
GPA = gpa;
advisorID = aid;
}
void Student::printDetails()
{
cout << "ID:" << studentID << endl;
cout << "Name:" << name << endl;
cout << "Year:" << year << endl;
cout << "Major:" << major << endl;
cout << "GPA:" << GPA << endl;
cout << "Advisor ID:" << advisorID << endl;
}
int Student::getAdvisorID()
{
return advisorID;
}
int Student::getStudentID()
{
return studentID;
}
void Student::setAdvisorID(int advisorID)
{
this->advisorID = advisorID;
}
bool operator > (Student s1, Student s2)
{
return (s1.studentID > s2.studentID);
}
bool operator < (Student s1, Student s2)
{
return (s1.studentID < s2.studentID);
}
bool operator == (Student s1, Student s2)
{
return (s1.studentID == s2.studentID);
}
bool operator != (Student s1, Student s2)
{
return (s1.studentID != s2.studentID);
}
|
23356c823c791cf8948eabd8b616f105044517a8
|
97dba80026128e9296e575bb58b9cc7867bbc77f
|
/leetcode/MaximumProductOfThreeNumbers.cpp
|
e5c57643d50cca1d302e93ca4f5420c6e737af38
|
[] |
no_license
|
intfloat/AlgoSolutions
|
5272be3dfd72485ff78888325a98c25b2623e3cb
|
2f7b2f3c4c8a25eb46322e7f8894263ecd286248
|
refs/heads/master
| 2021-12-23T08:18:32.176193
| 2021-11-01T05:53:27
| 2021-11-01T05:53:27
| 9,474,989
| 18
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,225
|
cpp
|
MaximumProductOfThreeNumbers.cpp
|
class Solution {
public:
int maximumProduct(vector<int>& nums) {
int sz = nums.size();
vector<vector<int> > dp_mx(sz, vector<int>(3));
vector<vector<int> > dp_mn(sz, vector<int>(3));
for (int i = 0; i < nums.size(); ++i) {
if (i == 0) {
dp_mx[i][0] = dp_mn[i][0] = nums[i];
} else {
dp_mx[i][0] = max(nums[i], dp_mx[i-1][0]);
dp_mn[i][0] = min(nums[i], dp_mn[i-1][0]);
}
if (i == 1) {
dp_mx[i][1] = dp_mn[i][1] = nums[i]*nums[i-1];
} else if (i > 1) {
dp_mx[i][1] = max(dp_mx[i-1][1], max(dp_mx[i-1][0]*nums[i], dp_mn[i-1][0]*nums[i]));
dp_mn[i][1] = min(dp_mn[i-1][1], min(dp_mx[i-1][0]*nums[i], dp_mn[i-1][0]*nums[i]));
}
if (i == 2) {
dp_mx[i][2] = dp_mn[i][2] = nums[i]*nums[i-1]*nums[i-2];
} else if (i > 2) {
dp_mx[i][2] = max(dp_mx[i-1][2], max(dp_mx[i-1][1]*nums[i], dp_mn[i-1][1]*nums[i]));
dp_mn[i][2] = min(dp_mn[i-1][2], min(dp_mx[i-1][1]*nums[i], dp_mn[i-1][1]*nums[i]));
}
}
return dp_mx[sz-1][2];
}
};
|
546e888519d3faf962bdf60f17f81b198151db76
|
164a38a1469029eccb7c3a796ae6aa608153bd1d
|
/boost/boost-unit-Test/str.h
|
05fd2c03b073f10495a2669a084edaa408709211
|
[] |
no_license
|
dariuskylin/test
|
09393efad398d5e5ba88a58da4d7401161e3dcd4
|
17b6884e3007aed35586e29187360eabb4b12cb1
|
refs/heads/master
| 2016-09-05T15:39:04.526373
| 2012-12-17T03:25:24
| 2012-12-17T03:25:24
| 5,806,685
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 828
|
h
|
str.h
|
/*
* =====================================================================================
*
* Filename: str.h
*
* Description:
*
* Version: 1.0
* Created: 07/16/2012 11:06:01 PM
* Revision: none
* Compiler: gcc
*
* Author: dongyuchi (dongyuchi), dongyuchi@gmail.com
* Company: UESTC
*
* =====================================================================================
*/
#ifndef _MYSTRING_H
#define _MYSTRING_H
#include<string.h>
class mystring{
char* buffer;
int length;
public:
void setbuffer(char* s){
buffer = s;
length = strlen(s);
}
char& operator[](const int index){
return buffer[index];
}
int size(){
return length;
}
};
#endif
|
7f1cd0f29c8703926aa733e5f10eedb611380af5
|
03cece0871cb07da0887ff2c0ff633b12bf9c251
|
/A1/src/main.cpp
|
8085134c1df1ad7a6d989ff5c77bcd7947e22620
|
[] |
no_license
|
FreakingBarbarians/DGPCompFab
|
38f12eb39dc531c5d6665ca22b3cc59465964461
|
87a9b68b702e0058aa5909701375c9227e777444
|
refs/heads/master
| 2020-04-02T03:17:38.532220
| 2018-10-20T23:16:30
| 2018-10-20T23:16:30
| 153,956,419
| 1
| 0
| null | 2018-10-20T23:14:33
| 2018-10-20T23:14:33
| null |
UTF-8
|
C++
| false
| false
| 1,992
|
cpp
|
main.cpp
|
//#include "util/shapes.hpp"
#include <igl/opengl/glfw/Viewer.h>
#include <igl/opengl/glfw/imgui/ImGuiMenu.h>
#include <igl/opengl/glfw/imgui/ImGuiHelpers.h>
#include <imgui/imgui.h>
#include <igl/readDMAT.h>
//assignment files
#include <csgOps.h>
//Global variables for UI
igl::opengl::glfw::Viewer viewer;
Eigen::MatrixXd V;
Eigen::MatrixXi F;
//interpreter
std::string currentFilename;
std::string currentObject;
//convert preprocessor define into a string
#define STRINGIFY(s) #s
#define DataDir(s) STRINGIFY(s)
int main(int argc, char **argv) {
//custom menu to just-in-time compile libfive script
// Attach a menu plugin
igl::opengl::glfw::imgui::ImGuiMenu menu;
viewer.plugins.push_back(&menu);
currentObject = "";
menu.callback_draw_custom_window = [&]()
{
// Define next window position + size
ImGui::SetNextWindowPos(ImVec2(180.f * menu.menu_scaling(), 10), ImGuiSetCond_FirstUseEver);
ImGui::SetNextWindowSize(ImVec2(200, 160), ImGuiSetCond_FirstUseEver);
ImGui::Begin(
"New Window", nullptr,
ImGuiWindowFlags_NoSavedSettings
);
// Expose the same variable directly ...
// Add a button
if (ImGui::Button("Load Script", ImVec2(-1,0)))
{
currentFilename = igl::file_dialog_open();
}
if (ImGui::Button("Recompile", ImVec2(-1,0)))
{
if(currentFilename.length() != 0) {
currentObject = "";
//compile using command line interpreter and load mesh
system((std::string("../interpreter/bin/Interpreter ") + currentFilename).c_str());
igl::readDMAT("./outputV.dmat", V);
igl::readDMAT("./outputF.dmat", F);
}
viewer.data().clear();
viewer.data().set_mesh(V, F);
}
};
viewer.launch();
}
|
ffe606ddf14524a7d0c81def55445d25d7ff971e
|
17e62b549499c33f19c6a6ca7b007c3e9ac4ecfa
|
/Engine/Src/InputManager.h
|
589c9ff73dc844fc392fdd234416747df0b0e10c
|
[] |
no_license
|
mathias234/3DGameCpp
|
04f8daf0015d2394b0af5cf8a607201b1e5454b7
|
995492460918fda8cb184edb20aaa70abd634d06
|
refs/heads/master
| 2021-04-03T05:03:23.550926
| 2019-05-09T20:07:56
| 2019-05-09T20:07:56
| 124,404,300
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 696
|
h
|
InputManager.h
|
#pragma once
#include <vector>
#include "GLFW\glfw3.h"
class InputManager
{
public:
static bool GetKeyDown(int GLFWKeyCode);
static bool GetKeyUp(int GLFWKeyCode);
static bool GetKey(int GLFWKeyCode);
static bool GetMouseDown(int GLFWKeyCode);
static bool GetMouseUp(int GLFWKeyCode);
static bool GetMouse(int GLFWKeyCode);
static void Update();
static void Init(GLFWwindow *pWwindow);
private:
static GLFWwindow* m_window;
// Values grabbed from GLFW api
static const int KeyCodesOffset = 32;
static const int MouseCodesOffset = 0;
static const int NumKeyCodes = 130;
static const int NumMouseButtons = 8;
static int* m_lastKeysFrame;
static int* m_lastMouseFrame;
};
|
ddf35dfbca5af817e739300230b3950e5eda179d
|
4898f2f6988f67d832c515915a7898e476c54633
|
/OpenGl_Sample/main/gameReseau/gameObject/gameBoard/gr_gameBoard.cpp
|
fb53c80642b8ed42f5d8c19228298ba77744b17c
|
[] |
no_license
|
OlivierArgentieri/CPP_Fred
|
b31f00e1787ed15d498d0f36fcc2cdf46c038b58
|
84c4bc9bb6ea04907d44164dd4d18796a0d7c0c0
|
refs/heads/master
| 2022-04-08T01:23:54.314428
| 2020-03-10T12:25:17
| 2020-03-10T12:25:17
| 238,685,793
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,302
|
cpp
|
gr_gameBoard.cpp
|
#include "gr_gameBoard.hpp"
#include "main/gameReseau/window/gr_window.hpp"
#include "plane/gr_planeGameBoard.hpp"
#include "topBorder/gr_topBorderGameBoard.hpp"
#define WALL_HEIGHT 10
#define WIDTH 100
#define HEIGHT 100
void gr_gameBoard::CreatePlane()
{
plane = new gr_planeGameBoard(glm::vec3(), glm::vec3(), glm::vec3(WIDTH, 0, HEIGHT), gr_bounds(), "", "TransformVertexShader.vertexshader", "TextureFragmentShader.fragmentshader", gr_color(65,105,225));
}
void gr_gameBoard::CreateBorders()
{
leftBorder = new gr_leftBorderGameBoard(glm::vec3(-50,0,0), glm::vec3(), glm::vec3(10, WALL_HEIGHT, 100), gr_bounds(glm::vec3(10, WALL_HEIGHT, 100), glm::vec3()), "uvChecker.dds", "TransformVertexShader.vertexshader", "TextureFragmentShader.fragmentshader", gr_color(0, 1, 0));
rightBorder = new gr_rightBorderGameBoard(glm::vec3(50,0,0), glm::vec3(), glm::vec3(10, WALL_HEIGHT, 100), gr_bounds(glm::vec3(10, WALL_HEIGHT, 100), glm::vec3()), "","TransformVertexShader.vertexshader", "TextureFragmentShader.fragmentshader", gr_color(1, 1, 0));
bottomBorder = new gr_bottomBorderGameBoard(glm::vec3(0,0,50), glm::vec3(), glm::vec3(100, WALL_HEIGHT, 10), gr_bounds(glm::vec3(100, WALL_HEIGHT, 10), glm::vec3()), "","TransformVertexShader.vertexshader", "TextureFragmentShader.fragmentshader", gr_color(0.5f, 0.3f, 0));
topBorder = new gr_topBorderGameBoard(glm::vec3(0,0,-50), glm::vec3(), glm::vec3(100, WALL_HEIGHT, 10), gr_bounds(glm::vec3(100, WALL_HEIGHT, 10), glm::vec3()),"" , "TransformVertexShader.vertexshader", "TextureFragmentShader.fragmentshader", gr_color(1, 0.5, 0));
}
gr_gameBoard::gr_gameBoard() : gr_gameObject(glm::vec3(), glm::vec3(), glm::vec3(), gr_bounds(), "", "TransformVertexShader.vertexshader", "TextureFragmentShader.fragmentshader", gr_color(0, 0, 0))
{
CreatePlane();
CreateBorders();
}
gr_gameBoard::gr_gameBoard(const gr_gameBoard& _gameBoard) : gr_gameObject(_gameBoard)
{
}
void gr_gameBoard::draw(gr_window* _window)
{
if (!_window) return;
plane->draw(_window);
leftBorder->draw(_window);
rightBorder->draw(_window);
bottomBorder->draw(_window);
topBorder->draw(_window);
}
std::vector<gr_gameObject*> gr_gameBoard::getElementComposed()
{
return std::vector<gr_gameObject*>
{
leftBorder,
rightBorder,
bottomBorder,
topBorder
};
}
|
6f01b911e3d3f4c6d36f394790727e26c07b4aad
|
a3d6556180e74af7b555f8d47d3fea55b94bcbda
|
/components/sessions/core/session_id.cc
|
27e68b601b6f3e3bd317d7556d01c7a1ee8bc0d2
|
[
"BSD-3-Clause"
] |
permissive
|
chromium/chromium
|
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
|
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
|
refs/heads/main
| 2023-08-24T00:35:12.585945
| 2023-08-23T22:01:11
| 2023-08-23T22:01:11
| 120,360,765
| 17,408
| 7,102
|
BSD-3-Clause
| 2023-09-10T23:44:27
| 2018-02-05T20:55:32
| null |
UTF-8
|
C++
| false
| false
| 483
|
cc
|
session_id.cc
|
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sessions/core/session_id.h"
#include <ostream>
#include "components/sessions/core/session_id_generator.h"
// static
SessionID SessionID::NewUnique() {
return sessions::SessionIdGenerator::GetInstance()->NewUnique();
}
std::ostream& operator<<(std::ostream& out, SessionID id) {
out << id.id();
return out;
}
|
4f9863ce41186685f0ec0720b288603f1bee4c04
|
9aae4b46b34488b024500b9294d09920aaaa851b
|
/plugin/AdminPlugin.cpp
|
843148d6c26cd5361d8daa340bc88a141fb56165
|
[] |
no_license
|
jamesoff/bmotion-lib
|
f1d8f76464bb71dc778837c5a7e9a378d7be9e2f
|
0bd3480e870edb7c17ff44c41f01e2ef683a125e
|
refs/heads/master
| 2021-01-22T11:20:50.966355
| 2017-05-28T20:02:29
| 2017-05-28T20:02:29
| 92,683,981
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,440
|
cpp
|
AdminPlugin.cpp
|
#include <AdminPlugin.h>
#include <bMotion.h>
#include <Output.h>
#include <DynamicLoader.h>
/*
* Constructor for Admin Plugin type.
* @param source Pointer to the library that contains the callback function
* required.
* @param name The name assigned to the plugin. Must be unique in the system.
* @param funcName The name of the callback function.
* @param command the admin command that invokes this plugin
* @param lang The language of the plugin. Details of Language are in System.
*/
AdminPlugin::AdminPlugin(Library* source, const String& name,
const String& funcName, const String& command,
Language lang)
: Plugin(source, Admin, name, funcName, command, 100, lang)
, _callback(NULL)
{
}
/*
* Destructor
*/
AdminPlugin::~AdminPlugin()
{
}
/*
* Admin Plugin specific invocation method.
* @param nick The nick associated with invoking the plugin.
* @param host The host associated with invoking the plugin.
* @param handle The handle associated with invoking the plugin.
* @param channel The channel in which the plugin was invoked.
* @param text The invoking text matching the plugin regular expression.
* @return true or false. will return false if the execution fails (either that
* there is no callback, or it's not enabled), or if the callback
* returns false which will be viewed as a failed run.
*/
bool AdminPlugin::execute(const String& nick, const String& host,
const String& handle, const String& channel,
const String& text)
{
if (!_callback || !_enabled)
return false;
bool success = false;
Library* oldLib = bMotionSystem().getActiveLibrary();
if (bMotionSystem().startDangerousCode() == 0)
{
bMotionSystem().setActiveLibrary(_source);
success = _callback(nick, host, handle, channel, text);
}
bMotionSystem().setActiveLibrary(oldLib);
if (bMotionSystem().endDangerousCode())
{
bMotionLog(1, "plugin \"%s\" has caused a serious error",
(const char*)_name);
return false;
}
return success;
}
/*
* Refresh the callback method to the library.
* This is used because the library can be loaded and unloaded if the libraries
* plugins are all disabled. This will attempt to get a new callback pointer.
* @return true or false if the callback function can be refreshed from the
* library or not.
*/
bool AdminPlugin::refreshCallback()
{
_callback = (AdminPluginFunc)dlSymbol(_source->getHandle(), _funcName);
return (_callback != NULL);
}
|
e2bfb91ff8205a9bd8e6e03afc2708213b9713ca
|
989b34c46586ce2b769afc334e53ad310ccf4ed7
|
/Vanity/VScene/VSceneItemComponentRotation.h
|
bcfd5a41acdfa91c395d838f3a6457f07a1f8fa1
|
[
"Unlicense"
] |
permissive
|
DavidCoenFish/ancient-code-1
|
ed51ae1cc75cea7ed77db111d46846d36aac7975
|
8d76c810209b737bfc1ce996611807f62122fb41
|
refs/heads/master
| 2020-03-21T10:18:51.234695
| 2018-06-24T01:24:48
| 2018-06-24T01:24:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,218
|
h
|
VSceneItemComponentRotation.h
|
//file: Vanity/VScene/VSceneItemComponentRotation.h
#ifndef _V_SCENE_ITEM_COMPONENT_ROTATION_H_
#define _V_SCENE_ITEM_COMPONENT_ROTATION_H_
#include< Hubris/HCommon/HCommon_Export.h >
namespace Vanity
{
///////////////////////////////////////////////////////
// forward declarations
/**/
///////////////////////////////////////////////////////
// class
/**/
class VSceneItemComponentRotation
{
EMEMENTO_FACTORY_HEADER( VSceneItemComponentRotation );
///////////////////////////////////////////////////////
// creation
public:
VSceneItemComponentRotation(
const VSceneItemComponentRotation& in_src
);
VSceneItemComponentRotation(
const Hubris::HQuaternionREAL& in_rotation = Hubris::HQuaternionREAL()
);
~VSceneItemComponentRotation();
///////////////////////////////////////////////////////
// operators
public:
const VSceneItemComponentRotation& operator=( const VSceneItemComponentRotation& in_rhs );
const Hubris::HBOOL operator==( const VSceneItemComponentRotation& in_rhs )const;
const Hubris::HBOOL operator!=( const VSceneItemComponentRotation& in_rhs )const;
///////////////////////////////////////////////////////
// public methods
public:
const Hubris::HVectorR3 RotateVector(
const Hubris::HVectorR3& in_vector
)const;
const Hubris::HVectorR3 RotateVectorInverse(
const Hubris::HVectorR3& in_vector
)const;
///////////////////////////////////////////////////////
// public accessors
public:
const Hubris::HQuaternionREAL& RotationGet()const{ return m_rotation; }
Hubris::HVOID RotationSet( const Hubris::HQuaternionREAL& in_rotation );
///////////////////////////////////////////////////////
// private accessors
public:
const Hubris::HMatrixR3& RotationMatrixGet()const;
const Hubris::HMatrixR3& RotationMatrixInvertedGet()const;
///////////////////////////////////////////////////////
// private members
private:
Hubris::HQuaternionREAL m_rotation;
mutable Hubris::HMatrixR3 m_rotationMatrix;
mutable Hubris::HMatrixR3 m_rotationMatrixInverted;
mutable Hubris::HBOOL m_dirtyMatrix;
mutable Hubris::HBOOL m_dirtyMatrixInverted;
};
/**/
};
#endif // _V_SCENE_ITEM_COMPONENT_ROTATION_H_
|
eca592e43390be82b159ac55cdd6fbd4956bcc27
|
43b8cc4c6f6b8f9abf65bb9e35210f886f9399ec
|
/pandaapp/src/indexify/photo.h
|
6c7486dd357a4047ace3dd227e66a69531b577d2
|
[] |
no_license
|
PlumpMath/panda3d-1
|
48f819c6a9cd7dd9b364e2f06e6f4d8e1c3cbd93
|
c2bcbfcb567d9f72911c0cf030cc4ab6ccdbe85b
|
refs/heads/master
| 2021-01-25T06:55:36.738522
| 2013-03-13T23:04:40
| 2013-03-13T23:04:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,646
|
h
|
photo.h
|
// Filename: photo.h
// Created by: drose (03Apr02)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#ifndef PHOTO_H
#define PHOTO_H
#include "pandatoolbase.h"
#include "filename.h"
class RollDirectory;
////////////////////////////////////////////////////////////////////
// Class : Photo
// Description : A single photo image within a roll directory.
////////////////////////////////////////////////////////////////////
class Photo {
public:
Photo(RollDirectory *dir, const Filename &basename,
const string &movie_extension, const string &sound_extension);
const Filename &get_basename() const;
const Filename &get_movie() const;
const Filename &get_sound() const;
const Filename &get_cm() const;
const string &get_name() const;
const string &get_frame_number() const;
void output(ostream &out) const;
public:
int _full_x_size;
int _full_y_size;
int _reduced_x_size;
int _reduced_y_size;
bool _has_reduced;
bool _has_movie;
bool _has_sound;
bool _has_cm;
private:
RollDirectory *_dir;
Filename _basename;
Filename _movie;
Filename _sound;
Filename _cm;
string _name;
string _frame_number;
};
INLINE ostream &operator << (ostream &out, const Photo &p) {
p.output(out);
return out;
}
#endif
|
54809e31ce6697e4102e8f7c592b694158867a66
|
5bb0a22fc4046023700657230fa4f860803c9d45
|
/locomotion_framework/point_handling/include/mwoibn/point_handling/force.h
|
3cba5edd0344959ffe37412b8f24ff669beeb1bf
|
[
"Zlib"
] |
permissive
|
mkamedula/Software-for-Robotic-Control
|
f953d0a9c3b22716db30f92c16f47fd21da61989
|
fc3f7b344d56aa238d77c22c5804831941fcba24
|
refs/heads/master
| 2022-07-07T18:21:09.001800
| 2022-06-12T23:10:55
| 2022-06-12T23:10:55
| 306,434,538
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,982
|
h
|
force.h
|
#ifndef __MWOIBN__POINT_HANDLING__FORCE_H
#define __MWOIBN__POINT_HANDLING__FORCE_H
#include "mwoibn/point_handling/state.h"
#include "mwoibn/point_handling/frame_plus.h"
namespace mwoibn
{
namespace point_handling
{
// Computes the actuation torques component to excert given force at the point
class Force: public State
{
public:
Force(point_handling::FramePlus& frame, std::string name = "")
: State(frame, 3, name)
{ }
Force(const Point::Current& current,
point_handling::FramePlus& frame, std::string name = "")
: State(current, frame, name)
{
_size = 3;
}
Force( Force&& other,point_handling::FramePlus& frame)
: State(other, frame)
{ }
Force(const Force& other,point_handling::FramePlus& frame)
: State(other, frame)
{ }
Force( Force&& other)
: State(other)
{ }
Force(const Force& other)
: State(other)
{ }
virtual ~Force() {}
virtual Force* clone_impl() const {return new Force(*this);}
/** @brief get Position in a world frame */
virtual const Point::Current&
getWorld(bool update = false);
// virtual Point::Current
// getWorld(bool update = false) const;
virtual void
getWorld(Point::Current& current, bool update = false) const;
/** @brief set new tracked point giving data in a world frame*/
virtual void setWorld(const Point::Current& current,
bool update = false);
/** @brief get Position in a user-defined reference frame */
// virtual Point::Current
// getReference(unsigned int refernce_id, bool update = false) const;
virtual void
getReference(Point::Current& current, unsigned int refernce_id, bool update = false) const;
virtual void setReference(const Point::Current& current,
unsigned int reference_id,
bool update = false);
using State::getReference;
using State::setReference;
};
} // namespace package
} // namespace library
#endif
|
aeaa5b26e2e9ea4c4c48e9934d57269b67969f4f
|
19d961aa754ae0062cd259f971c365ae108f9c07
|
/Simon/MorningStar.h
|
cbd50ee817a7e61e0a837eff2632a56f64532159
|
[] |
no_license
|
huyvu050596/CastleVania_14521189_NguyenAnhHuyVu
|
0e782ca405620b530d0285f694b39b6a5dd38306
|
7a1f9f14203506d46c3bf0a27d315f3bf4e43d6a
|
refs/heads/master
| 2020-04-14T23:41:18.776971
| 2019-01-05T12:14:26
| 2019-01-05T12:14:26
| 164,211,985
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 654
|
h
|
MorningStar.h
|
#ifndef _MORNINGSTAR_H_
#define _MORNINGSTAR_H_
#include <d3dx9.h>
#include "GameSprite.h"
#include "Weapon.h"
#include "Global.h"
#define MORNINGSTAR_IMAGE "Resources/weapon/morningstar.png"
#define MORNINGSTAR_FRAME 70
class MorningStar : public Weapon
{
int TypeMorningStar;
public:
MorningStar();
~MorningStar();
virtual void Update(GameCamera *camera, int t);
virtual Box GetBox(GameCamera *camera);
virtual void DrawWeapon(GameCamera *camera);
virtual void SetXY(float x, float y);
virtual void SetTypeMorningStar(int i = -1);
virtual int GetTypeMorningStar();
virtual void Create(float sm_x, float sm_y, int sm_trend);
};
#endif
|
6e43d921d38113ec103183a4c0a232ee801392d0
|
31155acd49915b9d0ce0731670c2b2e86d087953
|
/CameraControl/CameraAdjunct/Widgets/Move.cpp
|
39ffc5cbc537ba95d31b228130b9c0ff073ad9f7
|
[] |
no_license
|
rudi-c/computational-photography-research
|
2660d507ba2329d819f3eb5850b066d8b1f9c289
|
24ac27f6686afea7e1396f4caa5507ac59f42240
|
refs/heads/master
| 2020-04-28T21:28:28.273609
| 2014-11-11T07:35:42
| 2014-11-11T07:35:42
| 13,477,775
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,097
|
cpp
|
Move.cpp
|
/*
* Widget for moving around in image by stepping zoom rectangle
* left, right, up, and down. Also centers zoom rectangle.
*/
#include <QtGui>
#include <QTimer>
#include "Move.h"
Move::Move( QWidget *parent )
: QWidget( parent )
{
quadrant = 0;
viewRect.setRect( 0, 0, 42, 42 );
worldRect.setRect( -50, -50, 100, 100 );
/*
* Auto repeat
*/
timer.setInterval( 250 ); // milliseconds
QObject::connect( &timer, SIGNAL(timeout()), this, SLOT(processMove()) );
setMouseTracking( true );
setStatusTip(tr("Center or move navigation window" ));
setFixedSize( viewRect.size() );
setFocusPolicy( Qt::TabFocus );
}
Move::~Move()
{
}
void
Move::processMove()
{
if( quadrant != 0 ) { // set in mouseMoveEvent or keyPressEvent
emit moveDirection( quadrant );
}
}
void
Move::mousePressEvent( QMouseEvent *event )
{
if( event->button() == Qt::LeftButton ) {
processMove();
if( (quadrant != 0) && (quadrant != Qt::Key_Home) ) {
timer.start();
}
}
}
void
Move::mouseMoveEvent( QMouseEvent *event )
{
timer.stop();
QPoint p = event->pos() - viewRect.center();
if( (qAbs(p.x()) < 8) && (qAbs(p.y()) < 8) ) {
quadrant = Qt::Key_Home; // approx. as a rectangle is accurate enough
}
else {
QMatrix matrix;
matrix.rotate( 45 );
QPoint q = matrix.map( p );
if( (q.x() <= 0) && (q.y() < 0) ) quadrant = Qt::Key_Left;
else if( (q.x() > 0) && (q.y() <= 0) ) quadrant = Qt::Key_Up;
else if( (q.x() < 0) && (q.y() >= 0) ) quadrant = Qt::Key_Down;
else quadrant = Qt::Key_Right;
}
update();
}
void
Move::mouseReleaseEvent( QMouseEvent *event )
{
timer.stop();
}
void
Move::leaveEvent( QEvent *event )
{
timer.stop();
quadrant = 0;
event->accept();
update();
}
void
Move::keyPressEvent( QKeyEvent *event )
{
if( (event->key() == Qt::Key_Home) ||
(event->key() == Qt::Key_Left) ||
(event->key() == Qt::Key_Right) ||
(event->key() == Qt::Key_Up) ||
(event->key() == Qt::Key_Down) ) {
quadrant = event->key();
processMove();
update();
}
else {
QWidget::keyPressEvent( event );
}
}
void
Move::keyReleaseEvent( QKeyEvent *event )
{
if( (event->key() == Qt::Key_Home) ||
(event->key() == Qt::Key_Left) ||
(event->key() == Qt::Key_Right) ||
(event->key() == Qt::Key_Up) ||
(event->key() == Qt::Key_Down) ) {
quadrant = 0;
update();
}
else {
QWidget::keyPressEvent( event );
}
}
void
Move::paintEvent( QPaintEvent *event )
{
QPainter painter( this );
painter.setRenderHints( QPainter::Antialiasing, true );
painter.setWindow( worldRect );
painter.setViewport( viewRect );
painter.setPen( Qt::NoPen );
QBrush brushMedium( QColor( 127, 127, 127 ) );
painter.setBrush( brushMedium );
painter.drawEllipse( worldRect );
/*
* Highlight the direction the mouse is hovering over
* or the key that was pressed.
*/
if( (quadrant != 0) /*&& underMouse()*/ ) {
QBrush brushLight( QColor( 165, 165, 165 ) );
painter.setBrush( brushLight );
switch( quadrant ) {
case Qt::Key_Home:
painter.drawEllipse( QPoint( 0, 0 ), 16, 16 );
break;
case Qt::Key_Left:
painter.drawPie( worldRect, 135*16, 90*16 );
break;
case Qt::Key_Right:
painter.drawPie( worldRect, -45*16, 90*16 );
break;
case Qt::Key_Up:
painter.drawPie( worldRect, 45*16, 90*16 );
break;
case Qt::Key_Down:
painter.drawPie( worldRect, -135*16, 90*16 );
break;
}
}
/*
* Show the centering button if it wasn't drawn
* highlighted above.
*/
if( (quadrant != Qt::Key_Home) /*|| !underMouse()*/ ) {
QBrush brushDark( QColor( 93, 93, 93 ) );
painter.setBrush( brushDark );
painter.drawEllipse( QPoint( 0, 0 ), 16, 16 );
}
QPen pen;
pen.setWidth( 3 );
pen.setColor( Qt::white );
painter.setPen( pen );
/*
* Draw the angles indicating direction.
*/
const int r = 35;
const int l = 6;
static const int line[8][4] = {
{ r, 0, r-l, -l },
{ r, 0, r-l, l },
{ -r, 0, -r+l, l },
{ -r, 0, -r+l, -l },
{ 0, r, -l, r-l },
{ 0, r, l, r-l },
{ 0, -r, -l, -r+l },
{ 0, -r, l, -r+l }
};
for( int i = 0; i < 8; i++ ) {
painter.drawLine( line[i][0], line[i][1], line[i][2], line[i][3] );
}
/*
* Indicate whether the widget has keyboard focus
* (has been tabbed to).
*/
if( hasFocus() ) {
pen.setWidth( 2 );
pen.setStyle( Qt::DotLine );
pen.setColor( Qt::black );
painter.setPen( pen );
painter.setBrush( Qt::NoBrush );
painter.drawRoundedRect( -50, -50, 100, 100, 20, 20, Qt::RelativeSize );
}
/*
* Indicate whether the widget is disabled.
*/
if( !isEnabled() ) {
painter.fillRect( worldRect, QColor(214,214,214,128) );
}
}
|
89e6a4385e0263e2bb6c866b06f9dce320832326
|
64589428b06258be0b9b82a7e7c92c0b3f0778f1
|
/Codeforces/Rounds/1027/F.cpp
|
c3709b03792ecee57b750ae53f8b596dc3671fdb
|
[] |
no_license
|
splucs/Competitive-Programming
|
b6def1ec6be720c6fbf93f2618e926e1062fdc48
|
4f41a7fbc71aa6ab8cb943d80e82d9149de7c7d6
|
refs/heads/master
| 2023-08-31T05:10:09.573198
| 2023-08-31T00:40:32
| 2023-08-31T00:40:32
| 85,239,827
| 141
| 27
| null | 2023-01-08T20:31:49
| 2017-03-16T20:42:37
|
C++
|
UTF-8
|
C++
| false
| false
| 26,015
|
cpp
|
F.cpp
|
// `
//
//
// `
// ` `
//
// ` `
// ` `
// `
// ` `
// `
// . `
// ` `
// . `
// ` `
// ` . `
// ` ` `
// . `
// ` `
// ` `
// ` `
// ` ``
// . `,
// , ,
// . ..
// , .` `
// ,` ``..
// ``` ```.
// .`. . ..`
// ` ` ` `..
// `. `,;,,`. `
// ```,,;;::` ..
// ``...` `,, `:`,,;:,``
// `.,:.` `,,.;;;:..::.`.,,`
// `.,;;::. `.::;;;;;:::;,;,,,,.```
// `.,;';;;:::::;;;;;::::;:;;:,.``
// `.,:,,;;::,,:::::::;;;;;;:,,:,::,.```
// `.,:,,,,,::,::::::::::::::,:,.,.```
// `...,,,,.,,,:,:::,::;:,::::,::::;;,``
// `.........,,,:,,:,,,,,:::::,,.`.````,,,:;.
// ``........,,..,,,,,,,:::'''';;;::.``` ` .,.
// ``...........,,.,,,,,,,,::;;;;;;''''';,..` ````
// ```..............,:,,::;;''''';;:;;;;;;:';; ` `
// ``````..`...........,,::;::;;;'';'';:;;;;:..:`...``` ``
// ``````````..........,,,:,:,::::;;;;;;;;;:;;'+,,`.` ..
// ````````````..........,,,,,,,:,:::::;;;';;;:;;:,;.` ` ```
// ````````````............,.,,,,,:;;;;;'''''''';:;, `.` `
// ````````````............,..,.,,,,::,::;''''''''';', `
// ````````````````.``.........,.,.,,,::,:::;;;'''''+;', `
// ````````````````.```..............,,:;;;;;';;;;;;''';':
// ````````````````.````...............:;:::::::'''';;:,;';
// `````````````````````........,.........,,,:'';;;+''';'';;;`
// ````````````````````.`......,............,,,:;;'''''''''';;:`
// ```````````````````.`......,....,...,......,,,,::;;:::'+''';:`
// `` `````````````````..`....,..,..,.`.,.......,,,,,,,,,,:;'''';:
// `````````````````````.`.....,,,,,,.,,,,......,,,...,,,,:;;;''';:
// ` ``````````````````.`...,.,,,:::;;;,,:....,,,..,.,,,::;;';''';:
// ```````````````````````.,..,:,;::;:';:,::...,,...,,,,,,::;;''''';,
// ````````````.`````````.,.`.,;:;:,:;;':,,,..,,,,,,,,,..,,::;;;'''';.
// ``````..````.`````..``.,``.;';,;+##++;:,:,,,,,,,,,,,..,,:;;;;;;'';;`
// `.````....`....`.`..`.,,`.,;':+##+#++;;:,:,,,,,,,,,,...,,,;;;;;;'';:
// ```````....`,....`,...,...:';+;####+++;;:::,.,,,,,,......,,:;;;;'';;.
// ``.````.....,.,,,.,..,,`.,'''::####+++';;:,,,,,,,,,,,....,,,:;;;;'';:
// ``.````..`...,,,:,.,,:,,,.:';+,:####+++''';::,,,,:,:,,.....,,:::;;'';;:
// ```.``.''.`..,,,:,,,:::,.,:';+,;####+++'';::,,,::;::;:,.....,,.:;;;:::;.
// ``````:';..,,,::,:,:;::,:,:;;++#####+++'';,:,::;;;:;;::::,......,:::;;;:`
// .```.`.';..,.:,::;::;;,,,,,:;+######++#';:::::;;;;;;::::::,....,,,::;;;;:
// ````.`.,..,,,;:':::;::,,,,;:'########+'::::;;';;:;;:::::::,,...,::;;'';;,
// ` ``...,,,:,,;;':,;;:::,,::;:++######'',:;;;;;;;:;;;;;;;::,,....,,:;;;;':`
// `````..,,,::,;;';';':,,,,,:::,'####+'';:;;;:;;;;''';';;';;:,,,.,,,,:;;;':.
// `...`...,:::,:;;;;::;..,,,,,::::;;;;;';,::;;;;;''''';;;';;;;:,,..,,,,::'';:
// .`.,,`,:::::,:;;;:,;,.,,;,:::;;;::;;'::;;;;;;;'';;';;;:;:::;:,,...,,:;:''';.
// ,`,,,,`.:,,,,::;;,,,.,.,,;.,,:,:;:::::;::;;;;';';;;;;:,::,,::,,...,,::;;''':
// .`,,::,,,....,:;...,.....,.:,,,,,.,,::::::;::;;;;:::::::::,:::,...,,,::'''';,
// ``.,::,,,.,,,,.,:..,...`.`.,,,,,.,::;.,,,:;;;;;''';;;;;;;;;:::::,..,,,::'''';;`
// .`,,,::,,,,..,:,:,`.,.,.`.`.,..:,,..,,,:::;;;;;;;;;::;;;;;::::::,,...,,:;'''';:
// ,`,:::,,,,,..,,,:,``,..`.`..,...,.`..,,,,::;::::;;;;;:;;;;;;:::,,....,,:;;''';;`
// ,.:::;:,,,,..,,,,,.`..```.``...,..,,.....,,::::,:;;';;;;;;::::,,,......:;''''';:
// ,.::;;;:,,,.,,,,:...`.`,``...`.......,.,,,,,:::::;;;;;;;;';;;;;:,,....,:;'''''';.
// .,:.:;;;::,.,,,,:.`````.```,.``.`.,.....,,,:;;:::;;''';'''''';:,,.....,,;'+'''';:
// .,:::;;;::,,.,,,:.````````...``````......,,::::::::;;;::;;;;;::,,.....,,:''+'''';,
// ,,:;;;;:::,,.,,,,.`````````.`.`.````.....,,,,,:;:;::::;;;;;;::::,,....,,:;''''''':`
// ,,:;;;;:::..:,,,,.`````````.`.`..```....,,,::::;::;;;:::;;;;:::::,....,:;;;++'''';:
// ,:::;;;::::,::,,,```````````..``........,:::::;;:;;;;;::;';;;;;::,....::;''''''''';.
// ,::;;;;:,:::::,.````````````..```.......,::::::;;;:::;;;:;';;;;;:,....,;;'''+''''';;`
// ,::;;;;:;:;:::`..```````````...```...`...,,:;;;::::::;;;;;;:;;;;:,...,,;'''++'''''':,`
// :::;;';':;;;:`...``````````````````......,,:;;::::;:;::;;;;;;;::,,...,:;''''++'''''';,
// ,::;;';;':,...,..`````````````````.......,,,,;:::::::;;;::::::,,,..,,:::';''++'''''';:.
// ,::;;';;+;,..,,,,``````````````..........,,,,,;::;:;;;;:::::;:,....,,,;;;'''''''''''';:`
// .;;;'';;;;;:,,,,.`````````````............,,,,,:;,:;;;;:::::::,....,,::;;'''''''''''';;:
// ;;;;;;+,:;::,,,`````````````............,.,,,,,,::::::::,,,,,,....,,::;;'+''''''''''';;,
// :;;;:;+::::;:::```````````............`....,,.,,,:,:,,,,,,.........,,:';'''''''''''''';;.
// .:::,;''::;;:::``````````....................,.,,,,,,,,.............,:''''''''''''''''';:.
// ,,,,:`;;;;;;:.`.```````........................,,,.,,,..```````....,,';'''''''''''''''';;`
// .,,:, :';;;:.``.``````...`.....................,..,...``````.``...,,:;''''''''''''''''';:`
// ,.,, .;;;,.....`````...`.......`````..................```````...,,;;'''''''''''''''''';:`
// `.', .,:::......`````..``......``````.............```````````.`.,,:;'''''''''''''''''';;,
// ,:: `.,,:......``````.``......``````.............``````````.....,:;;''''''''''''''''';;;,
// :: .,,:.......``.``.````....````................`````````...,,.:;'''''''';'''''''''';;:,
// . `,,,......```.``..```....````..`........`..````````````...,,,;;'''''''';''''''''';;;:.
// .,.,......`````````......````.........````.`..```.`.``...,,:,;''''''';''''''''''';;;:.
// `.........``````.``......````.`.......`````..````..`......,:::';''''''';'''''''''';;;,.
// ...,....```````.````....```........```````...```.```....,,:::;''''''';';'''''''''''';,.
// `.......``.````.````.....```..`..`...``````..````......,,,:::;;'''';;';'''''''''''''';,`
// ```.....```````.`````....```.....``..```````````........,,:;:;''''''''';'''''''''''''';,
// ``.....```````.`````......`...````.````````````.......,.:::;;'''''';;';'''''''''''''';:,
// ``.....```````..````......`.....````````````.`........,:,;::;;'''';''''''''''''''''';';:,
// ```....```````..`````.......`..``.```````````.`.....,.,:::;;;'''''''''''''''''''''''';;;,.
// ````...```````...`````.`...``...````````......`......,,::;:''''''';;;''''''''''''''''';;:..
// ```...```````...`````....``.```.````.`...`.....`..,,::::;';''''';;';;';'''''''''''''''';:,`
// ```.`````````...`````.....```...````.`....`....,.,,,,::;;''''''';;';;''';''''''''''''''';:.`
// ```...``````....`````.....```````````..`.........,:::;:;;'+'';;'';'';;;''''''''''''''''';;:.
// ```..``````....````......``````.```....,.....,,,,,;:;'''''''';';;;';;';'''''''''''''''''';:`
// ````.``````....``.`......````.``````.....`..,,:;:;::;';''''';';;;;;';''''''''''''''''''''';:`
// ````````.`.....``........`````````..,..,..,,:::;,'';;'';;';;;;;;;;;'''''''''''''''''''''';;,`
// ```.`.``.......`......`````````.```...,,,.,,,::'';;;;'';;;;;;;;;;;;'''''''''''''''+''''''';:.
// ````.``......```...``````.``.`.``...,,,:,,,;:;;;';;';';;;;';;;;;;'''''''''''''''''+''''''';:.
// ````..`......``.....`.`.`.`.`...`...:,,,,::;;:;;';;;;;;;;'';;';';;''''''''''+''''''+''''''';:`
// ```..........``.....`.`.```.......,,:::,;;;;;:;;;;;;;'';'';;;;;;';';'''''''''''''+'++''''''';,
// `...........``.....```.......,.,.,::,:::;;;;;;';;;;;;';''';;';;';''''''''''''+'+''+''''''''';,
// `...........`.....,.``,,,.,...,:,:::;::::;;;;'''';;;';''';';;;'';''''''''''''+''''''''''''';;:.
// `.....,...........,...,,,.:.,,,,;:::;:;,:;;;';';';;';''';'';'';''''''+''''''''+'+'''''''''';;:,`
// `.....,.........,..,.,,,,.:,,,:,:;::::;::;;;';;;';''''';'';'''''''''''''''''''++''''''''''''';:.
// ...............,:.,,,,,:,,,;:::,::;:;::;:;;;;;;;;'';'''';;'';''''''''+'''''''''''''''''''''''';:.
// ....,...,,,,.,,,:,,,::,::::;,::::;;::::::;;:;;;;;;;';';;;;'''''+'+''''''''+++''+'''''''''''';'';,.
#include <bits/stdc++.h>
#define DEBUG false
#define debugf if (DEBUG) printf
#define MAXN 1000009
#define MAXM 900009
#define ALFA 256
#define MOD 1000000007
#define INF 0x3f3f3f3f
#define INFLL 0x3f3f3f3f3f3f3f3f
#define EPS 1e-9
#define PI 3.141592653589793238462643383279502884
#define FOR(x,n) for(int x=0; (x)<int(n); (x)++)
#define FOR1(x,n) for(int x=1; (x)<=int(n); (x)++)
#define REP(x,n) for(int x=int(n)-1; (x)>=0; (x)--)
#define REP1(x,n) for(int x=(n); (x)>0; (x)--)
#define pb push_back
#define pf push_front
#define fi first
#define se second
#define mp make_pair
#define all(x) x.begin(), x.end()
#define mset(x,y) memset(&x, (y), sizeof(x));
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef unsigned int uint;
typedef vector<int> vi;
typedef pair<int, int> ii;
int n, m, a[MAXN], b[MAXN];
int x[2*MAXN];
bool taken[2*MAXN], done[MAXN];
vi g[2*MAXN];
bool take(int d, int u, int j) {
if (done[u]) return true;
if (taken[j] || x[j] > d) return false;
//printf("%d taking day %d\n", u, x[j]);
taken[j] = true;
done[u] = true;
for(int v : g[j]) {
if (u == v) continue;
if (!take(d, v, a[v]+b[v]-j)) return false;
}
return true;
}
bool check(int d) {
//printf("d = %d\n", d);
mset(done, false);
mset(taken, false);
FOR1(i, n) {
if (done[i]) continue;
if (x[a[i]] > d) return false;
if (x[b[i]] > d) {
if (!take(d, i, a[i])) return false;
}
}
FOR1(j, m) {
if (x[j] > d || taken[j]) continue;
int cnt = 0;
for(int v : g[j]) {
if (!done[v]) cnt++;
}
if (cnt == 1) {
for(int v : g[j]) {
if (!done[v] && !take(d, v, j)) return false;
}
}
}
FOR1(i, n) {
if (done[i]) continue;
if (taken[a[i]] && taken[b[i]]) return false;
else if (!taken[a[i]]) {
if (!take(d, i, a[i])) return false;
}
else if (!taken[b[i]]) {
if (!take(d, i, b[i])) return false;
}
}
return true;
}
int main() {
scanf("%d", &n);
map<int, int> reduce;
FOR1(i, n) {
scanf("%d %d", &a[i], &b[i]);
reduce[a[i]] = 0;
reduce[b[i]] = 0;
}
m = 0;
for(auto & pp : reduce) {
pp.se = ++m;
x[m] = pp.fi;
}
FOR1(i, n) {
a[i] = reduce[a[i]];
b[i] = reduce[b[i]];
g[a[i]].pb(i);
g[b[i]].pb(i);
}
int lo = 0;
int hi = INF;
while(hi > lo + 1) {
int mid = (hi + lo) / 2;
if (check(mid)) hi = mid;
else lo = mid;
}
printf("%d\n", hi == INF ? -1 : hi);
return 0;
}
|
9c58c1b9caf37e8b7e840851f8dfb227d59906f2
|
60970683e8851b54ca0b8cf33459355b28ab0664
|
/tests/CommentsTest.cpp
|
5150a5c865201ebe0b208795d8d2ae5be1b263c0
|
[] |
no_license
|
kapilash/quarry
|
2a7bdc26a2859a0c7890011b30892b8aaa5bbb07
|
fa9679780cedf8adfc7af92e3f0c1b269d863518
|
refs/heads/master
| 2021-01-01T05:33:25.384923
| 2018-12-31T20:06:28
| 2018-12-31T20:06:28
| 7,463,970
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,696
|
cpp
|
CommentsTest.cpp
|
#define BOOST_TEST_MODULE comments_test test
#include <boost/test/unit_test.hpp>
#define QUARRY_EXPORT
#include "QReader.h"
#include "QInternal.h"
#include <string>
#include <fstream>
#include <iostream>
#include <set>
#include <algorithm>
#include <cstdlib>
#include <locale>
static void createFile(const char *fileName, const std::string &str, char begin, char second, char end) {
std::ofstream commentsFile(fileName);
commentsFile << begin << second;
int line = 0;
for(auto it=str.begin(); it != str.end(); ++it){
for(int i=0; i<100; i++) {
commentsFile << (*it);
}
if (line % 7 == 0) {
commentsFile << '\r';
}
if(((*it) != begin) && ((*it) != second) && ((*it) != end))
commentsFile << (std::endl);
line++;
}
commentsFile << second << end ;
commentsFile << "XXXXXXXXXX";
}
BOOST_AUTO_TEST_CASE (simpleBlockComment)
{
std::string str = std::string("abcdefghijklmnopqrstuvwxyz1234567890A");
const char *testFile = "comments1.txt";
createFile(testFile, str, '/','*','/');
Quarry::QReader qr(testFile);
BOOST_CHECK(qr.hasMore());
Quarry::Lexer comments = Quarry::csComments;
Quarry::QContext context(Quarry::C);
auto slab = comments(qr, context);
BOOST_CHECK(slab != nullptr);
BOOST_CHECK(slab->tokenType == Quarry::COMMENT);
std::string leftOver;
while(qr.hasMore()) {
leftOver.append(1, qr.next());
}
BOOST_CHECK_EQUAL(leftOver.c_str(), "XXXXXXXXXX");
delete slab;
}
BOOST_AUTO_TEST_CASE (nestedBlockComment)
{
std::string str = std::string("abcdefghi/*jklm/*n*/oo*/pqrstuvwxyz1234567890A");
const char *testFile = "comments3.txt";
createFile(testFile, str, '/','*','/');
Quarry::QReader qr(testFile);
BOOST_CHECK(qr.hasMore());
Quarry::Lexer comments = Quarry::csComments;
Quarry::QContext context(Quarry::C);
auto slab = comments(qr, context);
BOOST_CHECK(slab != nullptr);
BOOST_CHECK(slab->tokenType == Quarry::COMMENT);
std::string leftOver;
while(qr.hasMore()) {
leftOver.append(1, qr.next());
}
BOOST_CHECK_EQUAL(leftOver.c_str(), "XXXXXXXXXX");
delete slab;
}
BOOST_AUTO_TEST_CASE(java_comments)
{
Quarry::QReader qr("ManualComments.txt");
Quarry::QContext context(Quarry::C);
Quarry::Lexer spaces = Quarry::spaceLexer;
Quarry::Lexer comments = Quarry::csComments;
int commentCount = 0;
while(qr.hasMore()) {
auto slab = comments(qr, context);
BOOST_CHECK(slab != nullptr);
BOOST_CHECK(slab->tokenType == Quarry::COMMENT);
commentCount++;
delete spaces(qr, context);
delete slab;
}
std::cout << "validated " << commentCount << " comments " << std::endl;
}
|
690486e95e6bb9c9b556da504eecc2be0072bf00
|
c2cfafab4b6ac9636ceed490669f27af537e2e17
|
/openfpga/src/utils/rr_gsb_utils.cpp
|
90b63bff41f4ef975966f47a383c93fe711b987e
|
[
"MIT"
] |
permissive
|
stevecorey/OpenFPGA
|
0dfe32d2816e2cf5acbc3b0704c7c63a0b5890bf
|
20af542f32f0d8ab056c73d52978e76a7a1be1c4
|
refs/heads/master
| 2023-03-07T06:33:41.033989
| 2022-05-24T02:05:50
| 2022-05-24T02:05:50
| 139,053,155
| 0
| 0
|
MIT
| 2023-03-01T08:05:49
| 2018-06-28T18:12:18
|
C
|
UTF-8
|
C++
| false
| false
| 2,321
|
cpp
|
rr_gsb_utils.cpp
|
/********************************************************************
* This file includes most utilized functions for data structure
* DeviceRRGSB
*******************************************************************/
/* Headers from vtrutil library */
#include "vtr_assert.h"
/* Headers from openfpgautil library */
#include "openfpga_side_manager.h"
#include "rr_gsb_utils.h"
/* begin namespace openfpga */
namespace openfpga {
/********************************************************************
* Find if a X-direction or Y-direction Connection Block contains
* routing tracks only (zero configuration bits and routing multiplexers)
*******************************************************************/
bool connection_block_contain_only_routing_tracks(const RRGSB& rr_gsb,
const t_rr_type& cb_type) {
bool routing_track_only = true;
/* Find routing multiplexers on the sides of a Connection block where IPIN nodes locate */
std::vector<enum e_side> cb_sides = rr_gsb.get_cb_ipin_sides(cb_type);
for (size_t side = 0; side < cb_sides.size(); ++side) {
enum e_side cb_ipin_side = cb_sides[side];
SideManager side_manager(cb_ipin_side);
if (0 < rr_gsb.get_num_ipin_nodes(cb_ipin_side)) {
routing_track_only = false;
break;
}
}
return routing_track_only;
}
/************************************************************************
* Find the configurable driver nodes for a node in the rr_graph
***********************************************************************/
std::vector<RRNodeId> get_rr_gsb_chan_node_configurable_driver_nodes(const RRGraph& rr_graph,
const RRGSB& rr_gsb,
const e_side& chan_side,
const size_t& track_id) {
std::vector<RRNodeId> driver_nodes;
for (const RREdgeId& edge : rr_gsb.get_chan_node_in_edges(rr_graph, chan_side, track_id)) {
/* Bypass non-configurable edges */
if (false == rr_graph.edge_is_configurable(edge)) {
continue;
}
driver_nodes.push_back(rr_graph.edge_src_node(edge));
}
return driver_nodes;
}
} /* end namespace openfpga */
|
9152d726481b4c4319d1ee1ab3d3f9ad49f4b711
|
1b12e6096c47312b67fa6ff223216945d2efb70c
|
/apps/GenMAI/src/gmElement.cpp
|
8b472baf712d469c16d45c2193d9792ef9384f54
|
[
"Apache-2.0"
] |
permissive
|
rboman/progs
|
6e3535bc40f78d692f1f63b1a43193deb60d8d24
|
03eea35771e37d4b3111502c002e74014ec65dc3
|
refs/heads/master
| 2023-09-02T17:12:18.272518
| 2023-08-31T15:40:04
| 2023-08-31T15:40:04
| 32,989,349
| 5
| 2
|
Apache-2.0
| 2022-06-22T10:58:38
| 2015-03-27T14:04:01
|
MATLAB
|
UTF-8
|
C++
| false
| false
| 988
|
cpp
|
gmElement.cpp
|
// Copyright 2003-2019 Romain Boman
//
// 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 "gmElement.h"
using namespace genmai;
Element::Element(int n1, int n2, int n3, int n4) : Object(), nodes(4)
{
nodes[0] = n1;
nodes[1] = n2;
nodes[2] = n3;
nodes[3] = n4;
}
void
Element::write(std::ostream &out) const
{
out << '(' << this->nodes[0] << ',' << this->nodes[1] << ','
<< this->nodes[2] << ',' << this->nodes[3] << ')';
}
|
785d48512bbbd6289d7c4e6e6d6301004dcd6a27
|
a3d6556180e74af7b555f8d47d3fea55b94bcbda
|
/chrome/test/chromedriver/chrome/devtools_http_client_unittest.cc
|
e0d9a9ab60c4ad18252457bb735e596448a502fa
|
[
"BSD-3-Clause"
] |
permissive
|
chromium/chromium
|
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
|
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
|
refs/heads/main
| 2023-08-24T00:35:12.585945
| 2023-08-23T22:01:11
| 2023-08-23T22:01:11
| 120,360,765
| 17,408
| 7,102
|
BSD-3-Clause
| 2023-09-10T23:44:27
| 2018-02-05T20:55:32
| null |
UTF-8
|
C++
| false
| false
| 4,612
|
cc
|
devtools_http_client_unittest.cc
|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "chrome/test/chromedriver/chrome/devtools_http_client.h"
#include "chrome/test/chromedriver/chrome/status.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
void ExpectEqual(const WebViewInfo& info1, const WebViewInfo& info2) {
EXPECT_EQ(info1.id, info2.id);
EXPECT_EQ(info1.type, info2.type);
EXPECT_EQ(info1.url, info2.url);
EXPECT_EQ(info1.debugger_url, info2.debugger_url);
}
} // namespace
TEST(ParseWebViewsInfo, Normal) {
WebViewsInfo views_info;
Status status = DevToolsHttpClient::ParseWebViewsInfo(
"[{\"type\": \"page\", \"id\": \"1\", \"url\": \"http://page1\","
" \"webSocketDebuggerUrl\": \"ws://debugurl1\"}]",
views_info);
ASSERT_TRUE(status.IsOk());
ASSERT_EQ(1u, views_info.GetSize());
ExpectEqual(
WebViewInfo("1", "ws://debugurl1", "http://page1", WebViewInfo::kPage),
*views_info.GetForId("1"));
}
TEST(ParseWebViewsInfo, Multiple) {
WebViewsInfo views_info;
Status status = DevToolsHttpClient::ParseWebViewsInfo(
"[{\"type\": \"page\", \"id\": \"1\", \"url\": \"http://page1\","
" \"webSocketDebuggerUrl\": \"ws://debugurl1\"},"
" {\"type\": \"other\", \"id\": \"2\", \"url\": \"http://page2\","
" \"webSocketDebuggerUrl\": \"ws://debugurl2\"}]",
views_info);
ASSERT_TRUE(status.IsOk());
ASSERT_EQ(2u, views_info.GetSize());
ExpectEqual(
WebViewInfo("1", "ws://debugurl1", "http://page1", WebViewInfo::kPage),
views_info.Get(0));
ExpectEqual(
WebViewInfo("2", "ws://debugurl2", "http://page2", WebViewInfo::kOther),
views_info.Get(1));
}
TEST(ParseWebViewsInfo, WithoutDebuggerUrl) {
WebViewsInfo views_info;
Status status = DevToolsHttpClient::ParseWebViewsInfo(
"[{\"type\": \"page\", \"id\": \"1\", \"url\": \"http://page1\"}]",
views_info);
ASSERT_TRUE(status.IsOk());
ASSERT_EQ(1u, views_info.GetSize());
ExpectEqual(
WebViewInfo("1", std::string(), "http://page1", WebViewInfo::kPage),
views_info.Get(0));
}
namespace {
void AssertTypeIsOk(const std::string& type_as_string, WebViewInfo::Type type) {
WebViewsInfo views_info;
std::string data = "[{\"type\": \"" + type_as_string +
"\", \"id\": \"1\", \"url\": \"http://page1\"}]";
Status status = DevToolsHttpClient::ParseWebViewsInfo(data, views_info);
ASSERT_TRUE(status.IsOk());
ASSERT_EQ(1u, views_info.GetSize());
ExpectEqual(WebViewInfo("1", std::string(), "http://page1", type),
views_info.Get(0));
}
void AssertFails(const std::string& data) {
WebViewsInfo views_info;
Status status = DevToolsHttpClient::ParseWebViewsInfo(data, views_info);
ASSERT_FALSE(status.IsOk());
ASSERT_EQ(0u, views_info.GetSize());
}
} // namespace
TEST(ParseWebViewsInfo, Types) {
AssertTypeIsOk("app", WebViewInfo::kApp);
AssertTypeIsOk("background_page", WebViewInfo::kBackgroundPage);
AssertTypeIsOk("page", WebViewInfo::kPage);
AssertTypeIsOk("worker", WebViewInfo::kWorker);
AssertTypeIsOk("webview", WebViewInfo::kWebView);
AssertTypeIsOk("iframe", WebViewInfo::kIFrame);
AssertTypeIsOk("other", WebViewInfo::kOther);
AssertTypeIsOk("service_worker", WebViewInfo::kServiceWorker);
AssertFails("[{\"type\": \"\", \"id\": \"1\", \"url\": \"http://page1\"}]");
}
TEST(ParseWebViewsInfo, NonList) {
AssertFails("{\"id\": \"1\"}");
}
TEST(ParseWebViewsInfo, NonDictionary) {
AssertFails("[1]");
}
TEST(ParseWebViewsInfo, NoId) {
AssertFails(
"[{\"type\": \"page\", \"url\": \"http://page1\","
" \"webSocketDebuggerUrl\": \"ws://debugurl1\"}]");
}
TEST(ParseWebViewsInfo, InvalidId) {
AssertFails(
"[{\"type\": \"page\", \"id\": 1, \"url\": \"http://page1\","
" \"webSocketDebuggerUrl\": \"ws://debugurl1\"}]");
}
TEST(ParseWebViewsInfo, NoType) {
AssertFails(
"[{\"id\": \"1\", \"url\": \"http://page1\","
" \"webSocketDebuggerUrl\": \"ws://debugurl1\"}]");
}
TEST(ParseWebViewsInfo, InvalidType) {
AssertFails(
"[{\"type\": \"123\", \"id\": \"1\", \"url\": \"http://page1\","
" \"webSocketDebuggerUrl\": \"ws://debugurl1\"}]");
}
TEST(ParseWebViewsInfo, NoUrl) {
AssertFails(
"[{\"type\": \"page\", \"id\": \"1\","
" \"webSocketDebuggerUrl\": \"ws://debugurl1\"}]");
}
TEST(ParseWebViewsInfo, InvalidUrl) {
AssertFails(
"[{\"type\": \"page\", \"id\": \"1\", \"url\": 1,"
" \"webSocketDebuggerUrl\": \"ws://debugurl1\"}]");
}
|
07f332ba617a37b3bd18961ba71ea4aca45ee6c3
|
b74e96c9a0741fe8376123b7f604dea46c21a6a4
|
/2-3.cpp
|
2d0b5e94d01721e0a040d6662be0cb4c5015da7b
|
[] |
no_license
|
ddt-sawa/meikai_mid_cpp_sawa
|
e7fc2c27618207213e3d7135196c9a789d001056
|
b51e1c1ef7853c462d93bd6b1a7a6df4997c86f8
|
refs/heads/master
| 2020-03-24T20:57:57.929410
| 2018-09-13T11:33:15
| 2018-09-13T11:33:15
| 143,006,294
| 0
| 0
| null | 2018-09-20T09:28:05
| 2018-07-31T11:39:39
|
C++
|
UTF-8
|
C++
| false
| false
| 5,735
|
cpp
|
2-3.cpp
|
/*演習2-3 符号なし整数xの第posビットを、1にした値を返す関数set、0にした値を返す関数set、反転した値を返す関数inverseを作成せよ。
unsigned set(unsigned x, int pos);
unsigned reset(unsigned x, int pos);
unsigned inverse(unsigned x, int pos);
*/
#include<iostream>
using namespace std;
//最下位ビットのみが1の符号なし整数
const unsigned int leastBit = 1;
//2進数における基数
const int binaryNumber = 2;
//unsigend int型のビット数
const int unsignedDigits = numeric_limits<unsigned int>::digits;
/**
* 値のビット配列を表示する
* @param integerValue 値
* @author Sawa
* @since 7.27
*/
void printBit(unsigned int integerValue)
{
//ビット配列を表示するループ
for (int firstCounter = unsignedDigits - 1; firstCounter >= 0; --firstCounter) {
//カウンタ変数ぶん右シフトした値が1だった場合'1'を、0だった場合'0'を表示する
cout << ((integerValue >> firstCounter) & leastBit ? '1' : '0');
}
//改行
cout << '\n';
}
/**
* 第nビットのみが1である値を返却する
* @param bitPosition nの値
* @return oneBit 第nビットのみが1である値
* @author Sawa
* @since 7.27
*/
unsigned getOneBit(int bitPosition) {
//第nビットのみが1である値
unsigned int oneBit = 1;
//nの値が適切な場合
if (bitPosition >= 0 && bitPosition <= unsignedDigits - 1) {
//最下位ビットが第nビットに移動するまで値に進数の基数を乗算するループ
for (int firstCounter = 0; firstCounter < bitPosition; ++firstCounter) {
//基数を乗算(2)
oneBit *= binaryNumber;
}
}
//nの値が不適切な場合
else {
//例外処理を告知
cout << "変更ビットの参照が不適切です。入力値をそのまま返却します。\n";
}
//第nビットのみが1である値を返却
return oneBit;
}
/**
* 値の第nビットを1にして返却
* @param integerValue 値, bitPosition nの値
* @return integerValue 第nビットを1にした値
* @author Sawa
* @since 7.27
*/
unsigned int setBit(unsigned int integerValue, int bitPosition)
{
//nの値が適切な場合
if (bitPosition >= 0 && bitPosition <= unsignedDigits - 1) {
//引数に第nビットのみが1である整数を論理和代入
integerValue |= getOneBit(bitPosition);
}
//nの値が不適切な場合
else {
//例外処理を告知
cout << "変更ビットの参照が不適切です。入力値をそのまま返却します。\n";
}
//第nビットを1にした値を返却
return integerValue;
}
/**
* 値の第nビットを0にして返却
* @param integerValue 値, bitPosition nの値
* @return integerValue 第nビットを0にした値
* @author Sawa
* @since 7.27
*/
unsigned resetBit(unsigned integerValue, int bitPosition)
{
//nの値が適切な場合
if (bitPosition >= 0 && bitPosition <= unsignedDigits - 1) {
//第nビットが1の場合
if (integerValue >> (bitPosition) & leastBit) {
//第nビットを0にする
integerValue -= getOneBit(bitPosition);
}
}
//nの値が不適切な場合
else {
//例外処理を告知
cout << "変更ビットの参照が不適切です。入力値をそのまま返却します。\n";
}
//値を返却
return integerValue;
}
/**
* 値の第nビットを反転して返却
* @param integerValue 値, bitPosition nの値
* @return integerValue 第nビットを反転した値
* @author Sawa
* @since 7.27
*/
unsigned inverseBit(unsigned integerValue, int bitPosition)
{
//nの値が適切な場合
if (bitPosition >= 0 && bitPosition <= unsignedDigits - 1) {
//第nビットが1の場合
if (integerValue >> (bitPosition) & leastBit) {
//第nビットのみが1である値を減算代入
integerValue -= getOneBit(bitPosition);
}
//第nビットが0の場合
else {
//第nビットのみが1である値を加算代入
integerValue += getOneBit(bitPosition);
}
}
//nの値が不適切な場合
else {
//例外処理を告知
cout << "変更ビットの参照が不適切です。入力値をそのまま返却します。\n";
}
//第nビットを反転した値を返却
return integerValue;
}
int main()
{
//表示する値の概要を告知
cout << "入力した符号無し整数値の第nビットを変化させた値を表示します。";
//ビット回転したい整数
unsigned integerValue = 0;
//符号無し整数値の入力告知
cout << "符号無し整数値 : ";
//入力
cin >> integerValue;
//入力値のビット配列表示を告知
cout << "その値のビット配列は : ";
//ビット配列を表示
printBit(integerValue);
//何ビット目を変化させるかを表す整数
int bitPosition = 0;
//入力を促す
cout << "n : ";
//適切なビット数を参照するためのループ
do {
//入力
cin >> bitPosition;
//入力値が0より小さいまたはunsigend int型のビット数 - 1より大きい場合再入力
} while (!(bitPosition >= 0 && bitPosition <= unsignedDigits - 1));
//値の表示
cout << "第nビットを1にした値は" << setBit(integerValue, bitPosition) << "です。\n";
cout << "第nビットを0にした値は" << resetBit(integerValue, bitPosition) << "です。\n";
cout << "第nビットを反転した値は" << inverseBit(integerValue, bitPosition) << "です。\n";
//確認のためビット構成の表示
printBit(setBit(integerValue, bitPosition)); //第nビットを1にしたビット構成
printBit(resetBit(integerValue, bitPosition)); //第nビットを0にしたビット構成
printBit(inverseBit(integerValue, bitPosition));//第nビットを反転したビット構成
}
|
0e9ca0dbb292ade0bf8153796450fe420827f4b0
|
1bf835479687802eb884da2a36ef780fddbd8717
|
/manager.hpp
|
500526ec52606246eb988488bab042a20b25ae48
|
[] |
no_license
|
damirbar/cpp_ex1
|
6694d0607ee4521eac877241a7c1ea3c9b6243b1
|
09bba0af3154dd4ae71113700b0a807dcb88f000
|
refs/heads/master
| 2021-05-07T18:14:12.661338
| 2017-10-30T18:09:58
| 2017-10-30T18:09:58
| 108,762,342
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 750
|
hpp
|
manager.hpp
|
/*
* manager.hpp
*
* Created on: Oct 30, 2017
* Author: damir
*/
#ifndef MANAGER_HPP_
#define MANAGER_HPP_
#include <iostream>
#include <string>
#include <vector>
#include "worker.hpp"
using namespace std;
class Manager : public Worker {
//protected:
// vector<Worker> workerList;
public:
vector<Worker> workerList;
Manager(string name, long id, double salary)
: Worker(name, id, salary) {}
Manager(const Manager &other);
bool addWorker(const Worker &w);
bool removeWorker(const Worker &w);
const string toString() const;
inline bool operator==(const Manager& rhs) {
return this->_name == rhs._name && this->_id == rhs._id
&& this->_salary == rhs._salary;
}
~Manager(){}
};
#endif /* MANAGER_HPP_ */
|
b6b234e85192a86cc4a7ba5d3abb8fdd772bc550
|
2e6a65aa5065293e693eadd1f0e8918c0be69557
|
/SLAM_Demo/Frontend/LASER_Projection/src/Spherical_View_Projection.cpp
|
f9dbf6981a58725c6fa7b386dbd7379ef29247b8
|
[] |
no_license
|
NLS-SP/SLAM_Basics
|
dece764f7a95862dab4747b0c6d2f3f89b1a959b
|
23fb7417e75f955b640170a8cabeab4ed8d68b7a
|
refs/heads/master
| 2022-11-17T00:34:37.168785
| 2021-03-21T13:55:08
| 2021-03-21T13:55:08
| 229,234,194
| 3
| 3
| null | 2022-11-04T07:42:26
| 2019-12-20T09:33:43
|
C++
|
UTF-8
|
C++
| false
| false
| 3,072
|
cpp
|
Spherical_View_Projection.cpp
|
//
// Created by Robotics_qi on 2020/7/16.
//
#include <math.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <Spherical_View_Projection.h>
#include <opencv2/core/mat.hpp>
#include <opencv/cv.hpp>
SphericalConversion::SphericalConversion(const Configuration& config):
config_(config){
spherical_img_.assign(config_.num_lasers, std::vector<std::vector<double>>(config_.img_length, std::vector<double>(5, 0.0)));
cloud_ = pcl::PointCloud<pcl::PointXYZI>::Ptr(new pcl::PointCloud<pcl::PointXYZI>);
}
int SphericalConversion::loadCloud(const std::string& path){
// loading from Bin File.
if(pcl::io::loadPCDFile<pcl::PointXYZI>(path, *cloud_) == -1){
std::cout << "Couldn't read cloud file at: " << path << std::endl;
return -1;
}
return 1;
}
int SphericalConversion::MakeImage(){
// 首先转换成弧度
double fov_up_rad = (config_.fov_up / 180) * M_PI;
double fov_down_rad = (config_.fov_down / 180) * M_PI;
// Getting total field of view.
double fov_rad = std::abs(fov_up_rad) + std::abs(fov_down_rad);
if(cloud_->size() == 0){
std::cerr << "Empty Point Cloud." << std::endl;
return -1;
}
for(auto point : *cloud_) {
// Getting Pixel from Point.
int pixel_u = 0;
int pixel_v = 0;
double range = 0.0;
GetProjection(point, fov_rad, fov_down_rad, &pixel_v, &pixel_u, &range);
spherical_img_.at(pixel_u).at(pixel_v) = std::vector<double>{point.x, point.y, point.z, range, point.intensity};
}
return 1;
}
void SphericalConversion::GetProjection(const pcl::PointXYZI& point, const double& fov_rad, const double& fov_down_rad, int* pixel_v, int* pixel_u,
double* range) const{
*range = sqrt(point.x * point.x + point.y * point.y + point.z * point.z);
// Geting the angle of all points.
auto yaw = atan2(point.y, point.x);
auto pitch = asin(point.z / *range);
// Get projection in image coords and normalizing
// Basic Implementation
double v = 0.5 * (1.0 - yaw / M_PI);
double u = 1.0 - (pitch + std::abs(fov_down_rad)) / fov_rad;
// Scaling as per the lidar config given.
v *= config_.img_length;
u *= config_.num_lasers;
// round and clamp for use as index.
v = floor(v);
v = std::min(config_.img_length - 1, v);
v = std::max(0.0, v);
*pixel_v = int(v);
u = floor(u);
u = std::min(config_.num_lasers - 1, u);
u = std::max(0.0, u);
*pixel_u = int(u);
}
std::vector<std::vector<std::vector<double>>> SphericalConversion::GetImage() const { return spherical_img_; }
void SphericalConversion::ShowImg(const std::vector<std::vector<std::vector<double>>>& img) const{
cv::Mat sp_img(img.size(), img.at(0).size(), CV_64FC1);
for(int i = 0; i < sp_img.rows; ++i)
for(int j = 0; j < sp_img.cols; ++j)
sp_img.at<double>(i, j) = img.at(i).at(j).at(4);
cv::imshow("Intensity Image", sp_img);
cv::waitKey(0);
}
|
60558ea099ca7997b2018aa5ad6a143969d671e3
|
53949c99097623c2064662e7284eafd7584726cf
|
/10019 - Funny Encryption Method.cpp
|
2aaacee41153439afff3fca960c8368a851435e4
|
[] |
no_license
|
jimmylin1017/UVA
|
f65ccb40042f631770b5796121e3908188f64786
|
c8fdd5c64caff091a0ecb997794ffeb458ac0cad
|
refs/heads/master
| 2021-01-06T20:42:08.121440
| 2015-12-22T16:23:11
| 2015-12-22T16:23:11
| 37,203,303
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 668
|
cpp
|
10019 - Funny Encryption Method.cpp
|
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int dec(int n)
{
int count=0;
while(n!=0)
{
if(n%2 == 1)
count++;
n/=2;
}
return count;
}
int hex(int n)
{
int count=0;
while(n!=0)
{
int m = n%10;
while(m!=0)
{
if(m%2 == 1)
count++;
m/=2;
}
n/=10;
}
return count;
}
int main(void)
{
int input;
cin>>input;
while(input--)
{
int n;
cin>>n;
cout<<dec(n)<<" "<<hex(n)<<endl;
}
return 0;
}
|
477e452825b7aa8206cfb4f43a02bae60df58a5b
|
a0c0806da43293cc516d7bec429714a279ddf2ec
|
/exercise3.cpp
|
72864e2b5d1fb3a44dbe0ef8b0ff9ff4f9d8f61c
|
[] |
no_license
|
marianastoiovici/AP-Module-C-Wednesday-Exercises
|
8abb031f20c68c7b8a6a64b8f33432aee087256f
|
7f001ce5846c28b90e283c558d1203fb6a8c968a
|
refs/heads/main
| 2023-02-17T13:26:28.243823
| 2021-01-13T16:10:15
| 2021-01-13T16:10:15
| 329,306,834
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,334
|
cpp
|
exercise3.cpp
|
// C++ program that takes a filename from the user and checks if it exists. If it exists it display and add a count to each line and display the total number of lines at the end; an appropriate indication should be given if the file specified does not exist.
// https://repl.it/@mstoiovici/FileReader#main.cpp
#include <iostream>
#include <fstream> // provides ofstream and ifstream
#include <sys/stat.h>
using namespace std;
string getResponse(string message) {
//this function askes the user to provide some information
string response; //declare a variable to hold the user response
cout << message; //output the provided message
getline (cin, response); //get the user's input
return response; //return the response
}
int main() {
struct stat buf;
string line;
ifstream ifstreamObject;
string filename = getResponse("Please enter a valid filename: ");
if (stat(filename.c_str(), &buf) == 0){
ifstreamObject.open(filename);
int count = 0;
// while you're not at the end of file
while(!ifstreamObject.eof()){
getline(ifstreamObject, line);
count++;
cout << count << ":" << line << endl;
}
cout << "\n\nTotal number of lines read: " << count;
ifstreamObject.close();
} else {
cout << "Sorry, \'"<< filename << "\' does not exist." << endl;
}
return 0;
}
|
761e5093914a8f160710c3380d9052251f2b4c3d
|
07a25efb5c0a978a26db6564c9dd26a26ec543df
|
/Classes/Views/Layout/Base/BaseLayoutParams.h
|
3393e989e5154ac110e699196f621d9d1bfeb769
|
[] |
no_license
|
gorkem-oktay/cocosdroid
|
3c41d77e3863f1f9ce1308358ab31f5f4ee68583
|
95c7d80f555136b9bf385897df304a5810f0d6da
|
refs/heads/master
| 2020-06-03T01:30:52.304252
| 2019-06-13T19:27:36
| 2019-06-13T19:27:36
| 191,377,469
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 771
|
h
|
BaseLayoutParams.h
|
//
// BaseLayoutParams.h
// Cocosdroid
//
// Created by Görkem Oktay on 5.06.2019.
//
#ifndef BaseLayoutParams_h
#define BaseLayoutParams_h
#include "cocos2d.h"
namespace cocosdroid {
namespace BaseLayout {
const float MATCH_PARENT = -1.f;
const float WRAP_CONTENT = 0.f;
struct Margin {
float bottom = 0.f;
float top = 0.f;
float left = 0.f;
float right = 0.f;
};
struct Params {
int id = 0;
std::string tag = "";
float width = 0.f;
float height = 0.f;
cocos2d::Vec2 position;
Margin margin;
};
};
};
#endif /* BaseLayoutParams_h */
|
8561924504bc2528f6f82b2a29d722ff749d5575
|
f2cb3ab01b3b8097e26d779737e876f6d7e3b226
|
/src/SchedulerModule/service/SchedulerService.h
|
e47a99f1323893585eaa9b1318e5324014c69d85
|
[] |
no_license
|
ism-hub/WaterSystemBackend
|
f8b979815229e8299f85871c21254181d12a3202
|
7ef706f6709d718cd721a1815b62b4b11b5395d4
|
refs/heads/master
| 2020-07-18T21:19:51.734652
| 2019-09-11T15:33:25
| 2019-09-11T15:33:25
| 206,313,929
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,216
|
h
|
SchedulerService.h
|
/*
* SchedulerService.h
*
* Created on: 6 ���� 2018
* Author: rina
*/
#ifndef SCHEDULERMODULE_SERVICE_SCHEDULERSERVICE_H_
#define SCHEDULERMODULE_SERVICE_SCHEDULERSERVICE_H_
#include <GardenModule/model/TimePattern.h>
#include <functional>
//************ task schedule stuff
#define _TASK_WDT_IDS
#define _TASK_STD_FUNCTION
#include <TaskScheduler.h>
#include <TimeModule\timeService\TimeService.h>
namespace sched {
//The API - I will decide on the interface while building the thing which uses it,
// suppose to be straight forward (just calling the the scheduler lib for most parts)
// (so no much of a complex logic here)
class SchedulerService {
Scheduler ts;
std::shared_ptr<tsm::TimeService> _timeService;
public:
SchedulerService(std::shared_ptr<tsm::TimeService> timeService) : _timeService(timeService) {
}
~SchedulerService() {}
//TODO: change the hour to time
std::shared_ptr<Task> addTaskAtHour(garden::Hour hour, int frequency, std::function<void()> taskFnc){
std::shared_ptr<Task> tsk = std::make_shared<Task>(TASK_HOUR*24*frequency, TASK_FOREVER, taskFnc);
ts.addTask(*tsk);
auto currTime = _timeService->getCurrentDateTime();
garden::Hour hourNow;
hourNow.hour = currTime.hours().count();
hourNow.min = currTime.minutes().count();
hourNow.sec = currTime.seconds().count();
unsigned long int delayInSec = hour - hourNow > 0 ? hour - hourNow : 24*60*60 + (hour - hourNow);
Serial.print(F(" Delay in sec - "));Serial.println(delayInSec);
tsk->enableDelayed(delayInSec*TASK_SECOND);
return tsk;
}
void removeTask(std::shared_ptr<Task> task) {
// Serial.print("Deleting task with id - ");//Serial.println(task->id_);
ts.deleteTask(*task);
}
void execute() {
ts.execute();
}
//Repeats the task every interval; TASK_FOREVER is to run it infinite time intervals
std::shared_ptr<Task> addTaskWithInterval(std::chrono::seconds interval, int aIterations, std::function<void()> taskFnc){
std::shared_ptr<Task> tsk = std::make_shared<Task>(interval.count()*TASK_SECOND, aIterations, taskFnc);
ts.addTask(*tsk);
tsk->enable();
return tsk;
}
};
} /* namespace sched */
#endif /* SCHEDULERMODULE_SERVICE_SCHEDULERSERVICE_H_ */
|
bedba7f77a4a394c9a63d07a5e763479fcd3bf96
|
bec4ce7862948e5057b9573dd82a4aa0733ff485
|
/src/ch2/ce_demo_01.cc
|
91f01c0c3899f0df644f129db0d71436a5deeef1
|
[
"MIT"
] |
permissive
|
HerculesShek/cpp-practise
|
27b850a9c446a6571a95629cb6045e18957e6071
|
aa0cdc3101c831c1c677f0de46a2f85a4b407bc3
|
refs/heads/master
| 2016-09-06T13:05:04.184703
| 2014-09-23T01:41:38
| 2014-09-23T01:41:38
| 17,898,200
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 331
|
cc
|
ce_demo_01.cc
|
#include <iostream>
using namespace std;
int main()
{
const int max_files = 20; //max_files is a constant expression
const int limit = max_files + 1; //limit is a constant expression
int staff_size = 27; //staff_size is not a constant expression
const int sz = get_size(); //sz is not a constant expression
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.