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
6bd5efebbca9cba7e32250e15310165039007aa5
d89416321d948eef709cd348db982fcdd1627fd0
/src/runtime/eval/parser/scanner.h
f2c74f0fc867564f658c13d5afd9617e41944b9e
[ "PHP-3.01", "Zend-2.0" ]
permissive
huichen/hiphop-php
0d0cce0feefdd4f7fe62a02aa80081e3b076cb2e
dff69a5f46dec5e51de301c726e383a171b2cda9
refs/heads/master
2021-01-20T23:40:41.807364
2010-07-22T00:29:37
2010-07-28T06:36:19
696,720
9
2
null
null
null
null
UTF-8
C++
false
false
5,569
h
scanner.h
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #ifndef __EVAL_SCANNER_H__ #define __EVAL_SCANNER_H__ #include <runtime/eval/parser/parser_defines.h> #include <util/ylmm/basic_scanner.hh> #include <sstream> #include <runtime/eval/base/eval_base.h> #include <runtime/eval/ast/statement.h> #include <runtime/eval/ast/expression.h> namespace HPHP { namespace Eval { /////////////////////////////////////////////////////////////////////////////// DECLARE_BOOST_TYPES(TokenPayload); DECLARE_AST_PTR(IfBranch); DECLARE_AST_PTR(StatementListStatement); DECLARE_AST_PTR(CaseStatement); DECLARE_AST_PTR(ListElement); DECLARE_AST_PTR(ArrayPair); DECLARE_AST_PTR(CatchBlock); DECLARE_AST_PTR(Parameter); DECLARE_AST_PTR(Name); DECLARE_AST_PTR(StaticVariable); class TokenPayload { public: enum Mode { None, SingleExpression, SingleStatement, SingleName, IfBranch, CaseStatement, Expression, ListElement, ArrayPair, CatchBlock, Parameter, Name, StaticVariable, Strings }; TokenPayload(); ~TokenPayload(); void release(); template<class T> AstPtr<T> getExp() const { return m_exp ? m_exp->cast<T>() : AstPtr<T>(); } template<class T> AstPtr<T> getStmt() const { return m_stmt ? m_stmt->cast<T>() : AstPtr<T>(); } StatementListStatementPtr getStmtList() const; ExpressionPtr &exp(); StatementPtr &stmt(); NamePtr &name(); #define GETTER(type, data) std::vector<type##Ptr> &data(); GETTER(IfBranch, ifBranches); GETTER(Expression, exprs); GETTER(CaseStatement, cases); GETTER(ListElement, listElems); GETTER(ArrayPair, arrayPairs); GETTER(CatchBlock, catches); GETTER(Parameter, params); GETTER(Name, names); GETTER(StaticVariable, staticVars); #undef GETTER std::vector<String> &strings(); Mode getMode() const { return m_mode; } private: ExpressionPtr m_exp; StatementPtr m_stmt; NamePtr m_name; Mode m_mode; union { std::vector<IfBranchPtr> *ifBranches; std::vector<CaseStatementPtr> *cases; std::vector<ExpressionPtr> *exprs; std::vector<ListElementPtr> *listElems; std::vector<ArrayPairPtr> *arrayPairs; std::vector<CatchBlockPtr> *catches; std::vector<ParameterPtr> *params; std::vector<NamePtr> *names; std::vector<StaticVariablePtr> *staticVars; std::vector<String> *strings; } m_data; }; class Token { public: Token() : num(0) {} ~Token() { reset(); } // token text after lexical analysis boost::shared_ptr<std::string> text; int num; // internal token id const std::string &getText() const { if (text.get()) return *text.get(); else return s_empty; } void setText(const char *t); TokenPayloadPtr &operator->(); Token &operator=(Token &other); Token &operator=(int num) { this->num = num; return *this;} void operator++(int) { this->num++;} void reset(); private: TokenPayloadPtr m_payload; const static std::string s_empty; }; inline std::ostream &operator<< (std::ostream &o, const Token &e) { return o; } class Scanner : public ylmm::basic_scanner<Token> { public: Scanner(ylmm::basic_buffer* buf, bool bShortTags, bool bASPTags, bool full = false); ~Scanner() { switch_buffer(0);} void setToken(const char *rawText, int rawLeng, const char *yytext, int yyleng, bool save = true); bool shortTags() const { return m_shortTags;} bool aspTags() const { return m_aspTags;} void setHeredocLabel(const char *label, int len); int getHeredocLabelLen() const; const char *getHeredocLabel() const; void resetHeredoc(); int wrap() { return 1;} int getNextToken(token_type& t, location_type& l); std::string scanEscapeString(char *str, int len, char quote_type) const; std::string getError() const { return m_err.str();} std::string getMessage() const { return m_msg.str();} int getLine() const { return m_line;} int getColumn() const { return m_column;} void setDocComment(const char *yytext, int yyleng); std::string getDocComment() { std::string dc = m_docComment; m_docComment = ""; return dc; } void flushFlex(); protected: std::ostringstream m_err; std::ostringstream m_msg; ylmm::basic_messenger<ylmm::basic_lock> m_messenger; bool m_shortTags; bool m_aspTags; bool m_full; std::string m_heredocLabel; int m_line; // last token line int m_column; // last token column std::string m_docComment; void incLoc(const char *yytext, int yyleng); }; } } extern void _eval_scanner_init(); /////////////////////////////////////////////////////////////////////////////// #endif // __EVAL_SCANNER_H__
4829063c52820408fb2e684ea6d463e3b74a683b
3ae80dbc18ed3e89bedf846d098b2a98d8e4b776
/src/SSWR/SMonitor/SMonitorWebHandler.cpp
4650cf039492e5c261264f163eb6797d370cbf7a
[]
no_license
sswroom/SClass
deee467349ca249a7401f5d3c177cdf763a253ca
9a403ec67c6c4dfd2402f19d44c6573e25d4b347
refs/heads/main
2023-09-01T07:24:58.907606
2023-08-31T11:24:34
2023-08-31T11:24:34
329,970,172
10
7
null
null
null
null
UTF-8
C++
false
false
75,408
cpp
SMonitorWebHandler.cpp
#include "Stdafx.h" #include "Data/ByteTool.h" #include "Data/LineChart.h" #include "Exporter/GUIPNGExporter.h" #include "IO/MemoryStream.h" #include "Math/Math.h" #include "Math/Unit/Pressure.h" #include "Media/ImageList.h" #include "Media/StaticImage.h" #include "SSWR/SMonitor/SMonitorWebHandler.h" #include "SSWR/SMonitor/SAnalogSensor.h" #include "Sync/RWMutexUsage.h" #include "Text/JSText.h" #include "Text/MyStringFloat.h" #include "Text/StringBuilderUTF8.h" #include "Text/XML.h" #include "Text/UTF8Writer.h" Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::OnSessDeleted(Net::WebServer::IWebSession* sess, void *userObj) { // SSWR::SMonitor::SMonitorWebHandler *me = (SSWR::SMonitor::SMonitorWebHandler*)userObj; return false; } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::OnSessCheck(Net::WebServer::IWebSession* sess, void *userObj) { // SSWR::SMonitor::SMonitorWebHandler *me = (SSWR::SMonitor::SMonitorWebHandler*)userObj; Data::DateTime dt; dt.SetCurrTimeUTC(); Int64 t = dt.ToTicks() - sess->GetValueInt64(UTF8STRC("LastSessTime")); if (t > 900000) { return true; } return false; } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::DefaultReq(SSWR::SMonitor::SMonitorWebHandler *me, NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp) { return resp->RedirectURL(req, CSTR("/monitor/index"), -2); } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::IndexReq(SSWR::SMonitor::SMonitorWebHandler *me, NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp) { Text::UTF8Writer *writer; UInt8 *buff; UOSInt buffSize; UTF8Char sbuff[64]; UTF8Char *sptr; IO::MemoryStream mstm; if (!me->core->UserExist()) { if (req->GetReqMethod() == Net::WebUtil::RequestMethod::HTTP_POST) { req->ParseHTTPForm(); Text::String *pwd = req->GetHTTPFormStr(CSTR("password")); Text::String *retype = req->GetHTTPFormStr(CSTR("password")); if (pwd && retype) { if (pwd->leng >= 3 && pwd->Equals(retype)) { me->core->UserAdd((const UTF8Char*)"admin", pwd->v, 1); return resp->RedirectURL(req, CSTR("index"), 0); } } } NEW_CLASS(writer, Text::UTF8Writer(mstm)); WriteHeaderBegin(writer); WriteHeaderEnd(writer); writer->WriteLineC(UTF8STRC("<body onload=\"document.getElementById('pwd').focus()\"><center>")); writer->WriteLineC(UTF8STRC("<form name=\"createForm\" method=\"POST\" action=\"index\">")); writer->WriteLineC(UTF8STRC("<table>")); writer->WriteLineC(UTF8STRC("<tr><td></td><td>Password for admin</td></tr>")); writer->WriteLineC(UTF8STRC("<tr><td>Password</td><td><input type=\"password\" name=\"password\" id=\"pwd\"/></td></tr>")); writer->WriteLineC(UTF8STRC("<tr><td>Retype</td><td><input type=\"password\" name=\"retype\"/></td></tr>")); writer->WriteLineC(UTF8STRC("<tr><td></td><td><input type=\"submit\"/></td></tr>")); writer->WriteLineC(UTF8STRC("</table>")); writer->WriteLineC(UTF8STRC("</form")); writer->WriteLineC(UTF8STRC("</center></body>")); writer->WriteLineC(UTF8STRC("</html>")); } else { Net::WebServer::IWebSession *sess = me->sessMgr->GetSession(req, resp); NEW_CLASS(writer, Text::UTF8Writer(mstm)); WriteHeaderBegin(writer); WriteHeaderEnd(writer); writer->WriteLineC(UTF8STRC("<body onload=\"window.setTimeout(new Function('document.location.replace(\\'index\\')'), 60000)\">")); writer->WriteLineC(UTF8STRC("<table width=\"100%\"><tr><td width=\"100\" class=\"menu\">")); me->WriteMenu(writer, sess); writer->WriteLineC(UTF8STRC("</td><td>")); Int32 userId; Int32 userType; if (sess) { userId = sess->GetValueInt32(UTF8STRC("UserId")); userType = sess->GetValueInt32(UTF8STRC("UserType")); } else { userId = 0; userType = 0; } Text::String *reqDevId = req->GetQueryValue(CSTR("devid")); Text::String *reqOutput = req->GetQueryValue(CSTR("output")); if (reqDevId && reqOutput) { Int64 idevId = reqDevId->ToInt64(); if (me->core->UserHasDevice(userId, userType, idevId)) { Text::StringBuilderUTF8 sb; sb.Append(reqOutput); UTF8Char *sarr[3]; UOSInt i; i = Text::StrSplit(sarr, 3, sb.v, ','); if (i == 2) { me->core->DeviceSetOutput(idevId, Text::StrToUInt32(sarr[0]), Text::StrToInt32(sarr[1]) != 0); } } } Data::ArrayList<ISMonitorCore::DeviceInfo *> devList; ISMonitorCore::DeviceInfo *dev; Data::DateTime dt; me->core->UserGetDevices(userId, userType, &devList); UOSInt i; UOSInt j; UOSInt k; UOSInt l; writer->WriteLineC(UTF8STRC("<h2>Home</h2>")); writer->WriteLineC(UTF8STRC("<table width=\"100%\" border=\"1\"><tr><td>Device Name</td><td>Last Reading Time</td><td>Readings Today</td><td>Digitals</td><td>Output</td></tr>")); i = 0; j = devList.GetCount(); while (i < j) { dev = devList.GetItem(i); Sync::RWMutexUsage mutUsage(dev->mut, false); writer->WriteStrC(UTF8STRC("<tr><td>")); if (dev->devName) { WriteHTMLText(writer, Text::String::OrEmpty(dev->devName)); } else { WriteHTMLText(writer, dev->platformName); } writer->WriteStrC(UTF8STRC("</td><td>")); if (dev->readingTime == 0) { writer->WriteStrC(UTF8STRC("-")); } else { dt.SetTicks(dev->readingTime); dt.ToLocalTime(); sptr = dt.ToString(sbuff, "yyyy-MM-dd HH:mm:ss.fff zzzz"); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); } writer->WriteStrC(UTF8STRC("</td><td>")); k = 0; l = dev->nReading; while (k < l) { writer->WriteStrC(UTF8STRC("<img src=\"devreadingimg?id=")); sptr = Text::StrInt64(sbuff, dev->cliId); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("&sensor=")); sptr = Text::StrInt32(sbuff, ReadInt16(dev->readings[k].status)); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("&reading=")); sptr = Text::StrInt32(sbuff, ReadInt16(&dev->readings[k].status[4])); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("&readingType=")); sptr = Text::StrInt32(sbuff, ReadInt16(&dev->readings[k].status[6])); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("\"/>")); if (ReadInt16(&dev->readings[k].status[6]) == SSWR::SMonitor::SAnalogSensor::RT_RHUMIDITY) { writer->WriteStrC(UTF8STRC("<br/>")); writer->WriteStrC(UTF8STRC("<img src=\"devreadingimg?id=")); sptr = Text::StrInt64(sbuff, dev->cliId); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("&sensor=")); sptr = Text::StrInt32(sbuff, ReadInt16(dev->readings[k].status)); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("&reading=")); sptr = Text::StrInt32(sbuff, ReadInt16(&dev->readings[k].status[4])); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("&readingType=")); sptr = Text::StrInt32(sbuff, SSWR::SMonitor::SAnalogSensor::RT_AHUMIDITY); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("\"/>")); } k++; if (k != l) { writer->WriteStrC(UTF8STRC("<br/>")); } } writer->WriteStrC(UTF8STRC("</td><td>")); k = 0; l = dev->ndigital; while (k < l) { if (dev->digitalNames[k]) { WriteHTMLText(writer, dev->digitalNames[k]); } else { writer->WriteStrC(UTF8STRC("Digital ")); sptr = Text::StrUOSInt(sbuff, k); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); } writer->WriteStrC(UTF8STRC(": ")); writer->WriteStrC((dev->digitalVals & (UInt32)(1 << k))?(const UTF8Char*)"1":(const UTF8Char*)"0", 1); k++; if (k != l) { writer->WriteStrC(UTF8STRC("<br/>")); } } writer->WriteStrC(UTF8STRC("</td><td>")); k = 0; l = dev->nOutput; while (k < l) { writer->WriteStrC(UTF8STRC("Output ")); sptr = Text::StrUOSInt(sbuff, k); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC(": ")); writer->WriteStrC(UTF8STRC("<a href=\"index?devid=")); sptr = Text::StrInt64(sbuff, dev->cliId); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("&output=")); sptr = Text::StrUOSInt(sbuff, k); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC(",1\">On</a> <a href=\"index?devid=")); sptr = Text::StrInt64(sbuff, dev->cliId); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("&output=")); sptr = Text::StrUOSInt(sbuff, k); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC(",0\">Off</a>")); k++; if (k != l) { writer->WriteStrC(UTF8STRC("<br/>")); } } mutUsage.EndUse(); writer->WriteLineC(UTF8STRC("</td></tr>")); i++; } writer->WriteLineC(UTF8STRC("</table>")); writer->WriteLineC(UTF8STRC("</td></tr></table>")); writer->WriteLineC(UTF8STRC("</body>")); writer->WriteLineC(UTF8STRC("</html>")); if (sess) { sess->EndUse(); } } DEL_CLASS(writer); buff = mstm.GetBuff(&buffSize); resp->AddDefHeaders(req); resp->AddContentType(CSTR("text/html")); resp->AddContentLength(buffSize); resp->AddHeader(CSTR("Cache-Control"), CSTR("no-cache")); resp->Write(buff, buffSize); return true; } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::LoginReq(SSWR::SMonitor::SMonitorWebHandler *me, NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp) { Text::UTF8Writer *writer; UInt8 *buff; UOSInt buffSize; Net::WebServer::IWebSession *sess = me->sessMgr->GetSession(req, resp); const UTF8Char *msg = 0; if (sess) { sess->EndUse(); return resp->RedirectURL(req, CSTR("index"), 0); } if (req->GetReqMethod() == Net::WebUtil::RequestMethod::HTTP_POST) { req->ParseHTTPForm(); Text::String *s = req->GetHTTPFormStr(CSTR("action")); Text::String *s2 = req->GetHTTPFormStr(CSTR("user")); Text::String *s3 = req->GetHTTPFormStr(CSTR("pwd")); if (s && s2 && s3 && s->Equals(UTF8STRC("login"))) { if (s2->v[0]) { SSWR::SMonitor::ISMonitorCore::LoginInfo *login = me->core->UserLogin(s2->v, s3->v); if (login != 0) { sess = me->sessMgr->CreateSession(req, resp); sess->SetValueInt32(UTF8STRC("UserId"), login->userId); sess->SetValueInt32(UTF8STRC("LoginId"), login->loginId); sess->SetValueInt32(UTF8STRC("UserType"), login->userType); sess->EndUse(); me->core->UserFreeLogin(login); return resp->VirtualRedirectURL(req, CSTR("/monitor/index"), 0); } else { msg = (const UTF8Char*)"User name or password not correct"; } } } } IO::MemoryStream mstm; NEW_CLASS(writer, Text::UTF8Writer(mstm)); WriteHeaderBegin(writer); WriteHeaderEnd(writer); writer->WriteLineC(UTF8STRC("<body onload=\"document.getElementById('user').focus()\">")); writer->WriteLineC(UTF8STRC("<table width=\"100%\"><tr><td width=\"100\" class=\"menu\">")); me->WriteMenu(writer, sess); writer->WriteLineC(UTF8STRC("</td><td><center>")); writer->WriteLineC(UTF8STRC("<form name=\"loginForm\" method=\"POST\" action=\"login\">")); writer->WriteLineC(UTF8STRC("<input type=\"hidden\" name=\"action\" value=\"login\"/>")); writer->WriteLineC(UTF8STRC("<table>")); writer->WriteLineC(UTF8STRC("<tr><td>User name</td><td><input type=\"text\" name=\"user\" id=\"user\" /></td></tr>")); writer->WriteLineC(UTF8STRC("<tr><td>Password</td><td><input type=\"password\" name=\"pwd\" id=\"pwd\"/></td></tr>")); writer->WriteLineC(UTF8STRC("<tr><td></td><td><input type=\"submit\"/></td></tr>")); if (msg) { writer->WriteLineC(UTF8STRC("<tr><td></td><td>")); WriteHTMLText(writer, msg); writer->WriteLineC(UTF8STRC("</td></tr>")); } writer->WriteLineC(UTF8STRC("</table>")); writer->WriteLineC(UTF8STRC("</form>")); writer->WriteLineC(UTF8STRC("</center></td></tr></table></body>")); writer->WriteLineC(UTF8STRC("</html>")); DEL_CLASS(writer); buff = mstm.GetBuff(&buffSize); resp->AddDefHeaders(req); resp->AddContentType(CSTR("text/html")); resp->AddContentLength(buffSize); resp->AddHeader(CSTR("Cache-Control"), CSTR("no-cache")); resp->Write(buff, buffSize); return true; } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::LogoutReq(SSWR::SMonitor::SMonitorWebHandler *me, NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp) { Net::WebServer::IWebSession *sess = me->sessMgr->GetSession(req, resp); if (sess) { sess->EndUse(); me->sessMgr->DeleteSession(req, resp); } return resp->RedirectURL(req, CSTR("/monitor/index"), 0); } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::DeviceReq(SSWR::SMonitor::SMonitorWebHandler *me, NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp) { Text::UTF8Writer *writer; UInt8 *buff; UOSInt buffSize; UTF8Char sbuff[64]; UTF8Char *sptr; Int64 devId; Net::WebServer::IWebSession *sess = me->sessMgr->GetSession(req, resp); if (sess == 0) { return resp->RedirectURL(req, CSTR("/monitor/index"), 0); } if (req->GetQueryValueI64(CSTR("photo"), devId)) { if (me->core->UserHasDevice(sess->GetValueInt32(UTF8STRC("UserId")), sess->GetValueInt32(UTF8STRC("UserType")), devId)) { me->core->SendCapturePhoto(devId); } } IO::MemoryStream mstm; NEW_CLASS(writer, Text::UTF8Writer(mstm)); WriteHeaderBegin(writer); WriteHeaderEnd(writer); writer->WriteLineC(UTF8STRC("<body onload=\"window.setTimeout(new Function('document.location.reload()'), 60000)\">")); writer->WriteLineC(UTF8STRC("<table width=\"100%\"><tr><td width=\"100\" class=\"menu\">")); me->WriteMenu(writer, sess); writer->WriteLineC(UTF8STRC("</td><td>")); Data::ArrayList<ISMonitorCore::DeviceInfo *> devList; ISMonitorCore::DeviceInfo *dev; Data::DateTime dt; me->core->UserGetDevices(sess->GetValueInt32(UTF8STRC("UserId")), sess->GetValueInt32(UTF8STRC("UserType")), &devList); UOSInt i; UOSInt j; UOSInt k; UOSInt l; writer->WriteLineC(UTF8STRC("<h2>Device</h2>")); writer->WriteLineC(UTF8STRC("<table width=\"100%\" border=\"1\"><tr><td>Device Name</td><td>Platform Name</td><td>CPU Name</td><td>Version</td><td>Reading Time</td><td>Readings</td><td>Digitals</td><td>Action</td></tr>")); i = 0; j = devList.GetCount(); while (i < j) { dev = devList.GetItem(i); writer->WriteStrC(UTF8STRC("<tr><td>")); Sync::RWMutexUsage mutUsage(dev->mut, false); if (dev->devName) { WriteHTMLText(writer, Text::String::OrEmpty(dev->devName)); } else { WriteHTMLText(writer, dev->platformName); } writer->WriteStrC(UTF8STRC("</a></td><td>")); WriteHTMLText(writer, dev->platformName); writer->WriteStrC(UTF8STRC("</td><td>")); WriteHTMLText(writer, dev->cpuName); writer->WriteStrC(UTF8STRC("</td><td>")); if (dev->version == 0) { writer->WriteStrC(UTF8STRC("-")); } else { dt.SetTicks(dev->version); dt.ToLocalTime(); sptr = dt.ToString(sbuff, "yyyy-MM-dd HH:mm:ss.fff"); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); } writer->WriteStrC(UTF8STRC("</td><td>")); if (dev->readingTime == 0) { writer->WriteStrC(UTF8STRC("-")); } else { dt.SetTicks(dev->readingTime); dt.ToLocalTime(); sptr = dt.ToString(sbuff, "yyyy-MM-dd HH:mm:ss.fff zzzz"); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); } writer->WriteStrC(UTF8STRC("</td><td>")); k = 0; l = dev->nReading; while (k < l) { if (dev->readingNames[k]) { WriteHTMLText(writer, dev->readingNames[k]); } else { writer->WriteStrC(UTF8STRC("Sensor ")); sptr = Text::StrInt32(sbuff, ReadInt16(dev->readings[k].status)); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC(" ")); writer->WriteStr(SSWR::SMonitor::SAnalogSensor::GetReadingTypeName((SSWR::SMonitor::SAnalogSensor::ReadingType)ReadUInt16(&dev->readings[k].status[6]))); } writer->WriteStrC(UTF8STRC(" = ")); sptr = Text::StrDouble(sbuff, dev->readings[k].reading); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); k++; if (k != l) { writer->WriteStrC(UTF8STRC("<br/>")); } } writer->WriteStrC(UTF8STRC("</td><td>")); k = 0; l = dev->ndigital; while (k < l) { if (dev->digitalNames[k]) { WriteHTMLText(writer, dev->digitalNames[k]); } else { writer->WriteStrC(UTF8STRC("Digital ")); sptr = Text::StrUOSInt(sbuff, k); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); } writer->WriteStrC(UTF8STRC(": ")); writer->WriteStrC((dev->digitalVals & (UInt32)(1 << k))?(const UTF8Char*)"1":(const UTF8Char*)"0", 1); k++; if (k != l) { writer->WriteStrC(UTF8STRC("<br/>")); } } writer->WriteStrC(UTF8STRC("</td><td><a href=\"devedit?id=")); sptr = Text::StrInt64(sbuff, dev->cliId); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("\">Edit</a><br/>")); writer->WriteStrC(UTF8STRC("<a href=\"devreading?id=")); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("\">Reading Names</a><br/>")); writer->WriteStrC(UTF8STRC("<a href=\"devdigitals?id=")); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("\">Digital Names</a><br/>")); writer->WriteStrC(UTF8STRC("<a href=\"device?photo=")); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("\">Capture Photo</a>")); mutUsage.EndUse(); writer->WriteLineC(UTF8STRC("</td></tr>")); i++; } writer->WriteLineC(UTF8STRC("</table>")); writer->WriteLineC(UTF8STRC("</td></tr></table></body>")); writer->WriteLineC(UTF8STRC("</html>")); sess->EndUse(); DEL_CLASS(writer); buff = mstm.GetBuff(&buffSize); resp->AddDefHeaders(req); resp->AddContentType(CSTR("text/html")); resp->AddContentLength(buffSize); resp->AddHeader(CSTR("Cache-Control"), CSTR("no-cache")); resp->Write(buff, buffSize); return true; } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::DeviceEditReq(SSWR::SMonitor::SMonitorWebHandler *me, NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp) { Text::UTF8Writer *writer; UInt8 *buff; UOSInt buffSize; UTF8Char sbuff[64]; UTF8Char *sptr; Net::WebServer::IWebSession *sess = me->sessMgr->GetSession(req, resp); if (sess == 0) { return resp->RedirectURL(req, CSTR("/monitor/index"), 0); } Text::String *cid = req->GetQueryValue(CSTR("id")); Int64 cliId = 0; if (cid) { cliId = cid->ToInt64(); } if (cliId == 0) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/device"), 0); } if (!me->core->UserHasDevice(sess->GetValueInt32(UTF8STRC("UserId")), sess->GetValueInt32(UTF8STRC("UserType")), cliId)) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/device"), 0); } if (req->GetReqMethod() == Net::WebUtil::RequestMethod::HTTP_POST) { req->ParseHTTPForm(); Text::String *action = req->GetHTTPFormStr(CSTR("action")); if (action && action->Equals(UTF8STRC("modify"))) { Text::String *devName = req->GetHTTPFormStr(CSTR("devName")); Int32 flags = 0; Text::String *s; s = req->GetHTTPFormStr(CSTR("anonymous")); if (s && s->v[0] == '1') { flags |= 1; } s = req->GetHTTPFormStr(CSTR("removed")); if (s && s->v[0] == '1') { flags |= 2; } if (devName) { if (me->core->DeviceModify(cliId, devName->ToCString(), flags)) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/device"), 0); } } } } IO::MemoryStream mstm; NEW_CLASS(writer, Text::UTF8Writer(mstm)); WriteHeaderBegin(writer); WriteHeaderEnd(writer); writer->WriteLineC(UTF8STRC("<body onload=\"document.forms[0].devName.focus()\">")); writer->WriteLineC(UTF8STRC("<table width=\"100%\"><tr><td width=\"100\" class=\"menu\">")); me->WriteMenu(writer, sess); writer->WriteLineC(UTF8STRC("</td><td>")); writer->WriteLineC(UTF8STRC("<h2>Edit Device</h2>")); ISMonitorCore::DeviceInfo *dev = me->core->DeviceGet(cliId); writer->WriteStrC(UTF8STRC("<form name=\"modifyForm\" method=\"POST\" action=\"devedit?id=")); sptr = Text::StrInt64(sbuff, cliId); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteLineC(UTF8STRC("\">")); writer->WriteLineC(UTF8STRC("<table width=\"100%\" border=\"1\">")); writer->WriteStrC(UTF8STRC("<input type=\"hidden\" name=\"action\" value=\"modify\"/>")); Sync::RWMutexUsage mutUsage(dev->mut, false); writer->WriteStrC(UTF8STRC("<tr><td>Platform Name</td><td>")); WriteHTMLText(writer, dev->platformName); writer->WriteLineC(UTF8STRC("</td></tr>")); writer->WriteStrC(UTF8STRC("<tr><td>CPU Name</td><td>")); WriteHTMLText(writer, dev->cpuName); writer->WriteLineC(UTF8STRC("</td></tr>")); writer->WriteStrC(UTF8STRC("<tr><td>Device Name</td><td><input type=\"text\" name=\"devName\" ")); if (dev->devName) { writer->WriteStrC(UTF8STRC(" value=")); WriteAttrText(writer, dev->devName); } writer->WriteLineC(UTF8STRC("/></td></tr>")); writer->WriteStrC(UTF8STRC("<tr><td>Flags</td><td><input type=\"checkbox\" name=\"anonymous\" id=\"anonymous\" value=\"1\"")); if (dev->flags & 1) { writer->WriteStrC(UTF8STRC(" checked")); } writer->WriteLineC(UTF8STRC("/><label for=\"anonymous\">Anonymous Access</label><br/><input type=\"checkbox\" name=\"removed\" id=\"removed\" value=\"1\"")); if (dev->flags & 2) { writer->WriteStrC(UTF8STRC(" checked")); } writer->WriteStrC(UTF8STRC("/><label for=\"removed\">Removed</label></td></tr>")); writer->WriteLineC(UTF8STRC("<tr><td></td><td><input type=\"submit\"/></td></tr>")); writer->WriteLineC(UTF8STRC("</table></form>")); mutUsage.EndUse(); writer->WriteLineC(UTF8STRC("</td></tr></table></body>")); writer->WriteLineC(UTF8STRC("</html>")); sess->EndUse(); DEL_CLASS(writer); buff = mstm.GetBuff(&buffSize); resp->AddDefHeaders(req); resp->AddContentType(CSTR("text/html")); resp->AddContentLength(buffSize); resp->AddHeader(CSTR("Cache-Control"), CSTR("no-cache")); resp->Write(buff, buffSize); return true; } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::DeviceReadingReq(SSWR::SMonitor::SMonitorWebHandler *me, NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp) { Text::UTF8Writer *writer; UInt8 *buff; UOSInt buffSize; UTF8Char sbuff[64]; UTF8Char *sptr; UOSInt i; UOSInt j; ISMonitorCore::DeviceInfo *dev; Net::WebServer::IWebSession *sess = me->sessMgr->GetSession(req, resp); if (sess == 0) { return resp->RedirectURL(req, CSTR("/monitor/index"), 0); } Text::String *cid = req->GetQueryValue(CSTR("id")); Int64 cliId = 0; if (cid) { cliId = cid->ToInt64(); } if (cliId == 0) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/device"), 0); } if (!me->core->UserHasDevice(sess->GetValueInt32(UTF8STRC("UserId")), sess->GetValueInt32(UTF8STRC("UserType")), cliId)) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/device"), 0); } dev = me->core->DeviceGet(cliId); if (req->GetReqMethod() == Net::WebUtil::RequestMethod::HTTP_POST) { req->ParseHTTPForm(); Text::String *action = req->GetHTTPFormStr(CSTR("action")); if (action && action->Equals(UTF8STRC("reading"))) { Text::StringBuilderUTF8 sb; Text::String *s; i = 0; j = dev->nReading; while (i < j) { if (i > 0) { sb.AppendC(UTF8STRC("|")); } sptr = Text::StrUOSInt(Text::StrConcatC(sbuff, UTF8STRC("readingName")), i); s = req->GetHTTPFormStr(CSTRP(sbuff, sptr)); if (s) { sb.Append(s); } i++; } if (me->core->DeviceSetReadings(dev, sb.ToString())) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/device"), 0); } } } if (dev->nReading <= 0) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/device"), 0); } IO::MemoryStream mstm; NEW_CLASS(writer, Text::UTF8Writer(mstm)); WriteHeaderBegin(writer); WriteHeaderEnd(writer); writer->WriteLineC(UTF8STRC("<body onload=\"document.forms[0].readingName0.focus()\">")); writer->WriteLineC(UTF8STRC("<table width=\"100%\"><tr><td width=\"100\" class=\"menu\">")); me->WriteMenu(writer, sess); writer->WriteLineC(UTF8STRC("</td><td>")); writer->WriteLineC(UTF8STRC("<h2>Reading Names</h2>")); writer->WriteStrC(UTF8STRC("<form name=\"modifyForm\" method=\"POST\" action=\"devreading?id=")); sptr = Text::StrInt64(sbuff, cliId); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteLineC(UTF8STRC("\">")); writer->WriteStrC(UTF8STRC("<input type=\"hidden\" name=\"action\" value=\"reading\"/>")); writer->WriteLineC(UTF8STRC("<table width=\"100%\" border=\"1\">")); Sync::RWMutexUsage mutUsage(dev->mut, false); j = dev->nReading; i = 0; while (i < j) { writer->WriteStrC(UTF8STRC("<tr><td>Reading ")); sptr = Text::StrUOSInt(sbuff, i); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("</td><td><input type=\"text\" name=\"readingName")); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("\" ")); if (dev->readingNames[i]) { writer->WriteStrC(UTF8STRC(" value=")); WriteAttrText(writer, dev->readingNames[i]); } writer->WriteStrC(UTF8STRC("/></td><td>Sensor ")); sptr = Text::StrInt32(sbuff, ReadInt16(&dev->readings[i].status[0])); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); if (ReadInt16(&dev->readings[i].status[2]) != SSWR::SMonitor::SAnalogSensor::ST_UNKNOWN) { writer->WriteStrC(UTF8STRC(" (")); writer->WriteStr(SSWR::SMonitor::SAnalogSensor::GetSensorTypeName((SSWR::SMonitor::SAnalogSensor::SensorType)ReadInt16(&dev->readings[i].status[2]))); writer->WriteStrC(UTF8STRC(")")); } writer->WriteStrC(UTF8STRC(" Reading ")); sptr = Text::StrInt32(sbuff, ReadInt16(&dev->readings[i].status[4])); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); if (ReadInt16(&dev->readings[i].status[6]) != SSWR::SMonitor::SAnalogSensor::RT_UNKNOWN) { writer->WriteStrC(UTF8STRC(" ")); writer->WriteStr(SSWR::SMonitor::SAnalogSensor::GetReadingTypeName((SSWR::SMonitor::SAnalogSensor::ReadingType)ReadInt16(&dev->readings[i].status[6]))); } writer->WriteLineC(UTF8STRC("</td></tr>")); i++; } writer->WriteLineC(UTF8STRC("<tr><td></td><td><input type=\"submit\"/></td></tr>")); writer->WriteLineC(UTF8STRC("</table></form>")); mutUsage.EndUse(); writer->WriteLineC(UTF8STRC("</td></tr></table></body>")); writer->WriteLineC(UTF8STRC("</html>")); sess->EndUse(); DEL_CLASS(writer); buff = mstm.GetBuff(&buffSize); resp->AddDefHeaders(req); resp->AddContentType(CSTR("text/html")); resp->AddContentLength(buffSize); resp->AddHeader(CSTR("Cache-Control"), CSTR("no-cache")); resp->Write(buff, buffSize); return true; } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::DeviceDigitalsReq(SSWR::SMonitor::SMonitorWebHandler *me, NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp) { Text::UTF8Writer *writer; UInt8 *buff; UOSInt buffSize; UTF8Char sbuff[64]; UTF8Char *sptr; UOSInt i; UOSInt j; ISMonitorCore::DeviceInfo *dev; Net::WebServer::IWebSession *sess = me->sessMgr->GetSession(req, resp); if (sess == 0) { return resp->RedirectURL(req, CSTR("/monitor/index"), 0); } Text::String *cid = req->GetQueryValue(CSTR("id")); Int64 cliId = 0; if (cid) { cliId = cid->ToInt64(); } if (cliId == 0) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/device"), 0); } if (!me->core->UserHasDevice(sess->GetValueInt32(UTF8STRC("UserId")), sess->GetValueInt32(UTF8STRC("UserType")), cliId)) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/device"), 0); } dev = me->core->DeviceGet(cliId); if (req->GetReqMethod() == Net::WebUtil::RequestMethod::HTTP_POST) { req->ParseHTTPForm(); Text::String *action = req->GetHTTPFormStr(CSTR("action")); if (action && action->Equals(UTF8STRC("digitals"))) { Text::StringBuilderUTF8 sb; Text::String *s; i = 0; j = dev->ndigital; while (i < j) { if (i > 0) { sb.AppendC(UTF8STRC("|")); } sptr = Text::StrUOSInt(Text::StrConcatC(sbuff, UTF8STRC("digitalName")), i); s = req->GetHTTPFormStr(CSTRP(sbuff, sptr)); if (s) { sb.Append(s); } i++; } if (me->core->DeviceSetDigitals(dev, sb.ToString())) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/device"), 0); } } } if (dev->ndigital <= 0) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/device"), 0); } IO::MemoryStream mstm; NEW_CLASS(writer, Text::UTF8Writer(mstm)); WriteHeaderBegin(writer); WriteHeaderEnd(writer); writer->WriteLineC(UTF8STRC("<body onload=\"document.forms[0].digitalName0.focus()\">")); writer->WriteLineC(UTF8STRC("<table width=\"100%\"><tr><td width=\"100\" class=\"menu\">")); me->WriteMenu(writer, sess); writer->WriteLineC(UTF8STRC("</td><td>")); writer->WriteLineC(UTF8STRC("<h2>Digital Names</h2>")); writer->WriteStrC(UTF8STRC("<form name=\"modifyForm\" method=\"POST\" action=\"devdigitals?id=")); sptr = Text::StrInt64(sbuff, cliId); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteLineC(UTF8STRC("\">")); writer->WriteStrC(UTF8STRC("<input type=\"hidden\" name=\"action\" value=\"digitals\"/>")); writer->WriteLineC(UTF8STRC("<table width=\"100%\" border=\"1\">")); Sync::RWMutexUsage mutUsage(dev->mut, false); j = dev->ndigital; i = 0; while (i < j) { writer->WriteStrC(UTF8STRC("<tr><td>Digital ")); sptr = Text::StrUOSInt(sbuff, i); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("</td><td><input type=\"text\" name=\"digitalName")); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("\" ")); if (dev->digitalNames[i]) { writer->WriteStrC(UTF8STRC(" value=")); WriteAttrText(writer, dev->digitalNames[i]); } writer->WriteStrC(UTF8STRC("/></td></tr>")); i++; } writer->WriteLineC(UTF8STRC("<tr><td></td><td><input type=\"submit\"/></td></tr>")); writer->WriteLineC(UTF8STRC("</table></form>")); mutUsage.EndUse(); writer->WriteLineC(UTF8STRC("</td></tr></table></body>")); writer->WriteLineC(UTF8STRC("</html>")); sess->EndUse(); DEL_CLASS(writer); buff = mstm.GetBuff(&buffSize); resp->AddDefHeaders(req); resp->AddContentType(CSTR("text/html")); resp->AddContentLength(buffSize); resp->AddHeader(CSTR("Cache-Control"), CSTR("no-cache")); resp->Write(buff, buffSize); return true; } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::DeviceReadingImgReq(SSWR::SMonitor::SMonitorWebHandler *me, NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp) { Text::String *s; Int64 cliId = 0; Int32 userId = 0; Int32 userType = 0; Int32 sensorId = 0; Int32 readingId = 0; Int32 readingType = 0; Bool valid = true; s = req->GetQueryValue(CSTR("id")); if (s == 0) { valid = false; } else if (!s->ToInt64(cliId)) { valid = false; } s = req->GetQueryValue(CSTR("sensor")); if (s == 0) { valid = false; } else if (!s->ToInt32(sensorId)) { valid = false; } s = req->GetQueryValue(CSTR("reading")); if (s == 0) { valid = false; } else if (!s->ToInt32(readingId)) { valid = false; } s = req->GetQueryValue(CSTR("readingType")); if (s == 0) { valid = false; } else if (!s->ToInt32(readingType)) { valid = false; } if (!valid) { resp->ResponseError(req, Net::WebStatus::SC_NOT_FOUND); return true; } Net::WebServer::IWebSession *sess = me->sessMgr->GetSession(req, resp); if (sess) { userId = sess->GetValueInt32(UTF8STRC("UserId")); userType = sess->GetValueInt32(UTF8STRC("UserType")); sess->EndUse(); } if (!me->core->UserHasDevice(userId, userType, cliId)) { resp->ResponseError(req, Net::WebStatus::SC_NOT_FOUND); return true; } SSWR::SMonitor::ISMonitorCore::DeviceInfo *dev = me->core->DeviceGet(cliId); UOSInt i; UOSInt j; UOSInt k; IO::MemoryStream *mstm; UInt8 *buff; UOSInt buffSize; if (dev->valUpdated) { Sync::RWMutexUsage mutUsage(dev->mut, true); dev->valUpdated = false; i = dev->imgCaches.GetCount(); while (i-- > 0) { mstm = dev->imgCaches.GetItem(i); DEL_CLASS(mstm); } dev->imgCaches.Clear(); } Sync::RWMutexUsage mutUsage(dev->mut, false); mstm = dev->imgCaches.Get((sensorId << 16) + (readingId << 8) + (readingType)); if (mstm) { buff = mstm->GetBuff(&buffSize); resp->AddDefHeaders(req); resp->AddContentType(CSTR("image/png")); resp->AddContentLength(buffSize); resp->AddHeader(CSTR("Cache-Control"), CSTR("no-cache")); resp->Write(buff, buffSize); return true; } NotNullPtr<Media::DrawEngine> deng = me->core->GetDrawEngine(); Media::DrawImage *dimg = deng->CreateImage32(Math::Size2D<UOSInt>(640, 120), Media::AT_NO_ALPHA); Media::DrawFont *f; Media::DrawBrush *b; UOSInt readingIndex = (UOSInt)-1; Int32 readingTypeD; Data::LineChart *chart; j = dev->nReading; i = 0; while (i < j) { if (ReadInt16(&dev->readings[i].status[0]) == sensorId && ReadInt16(&dev->readings[i].status[4]) == readingId) { if (readingType == ReadInt16(&dev->readings[i].status[6])) { readingIndex = i; readingTypeD = ReadInt16(&dev->readings[i].status[6]); break; } else if (readingType == SSWR::SMonitor::SAnalogSensor::RT_AHUMIDITY && ReadInt16(&dev->readings[i].status[6]) == SSWR::SMonitor::SAnalogSensor::RT_RHUMIDITY) { readingIndex = i; readingTypeD = ReadInt16(&dev->readings[i].status[6]); break; } } i++; } if (readingIndex == (UOSInt)-1) { f = dimg->NewFontPx(CSTR("Arial"), 12, Media::DrawEngine::DFS_ANTIALIAS, 0); b = dimg->NewBrushARGB(0xffffffff); dimg->DrawRect(Math::Coord2DDbl(0, 0), dimg->GetSize().ToDouble(), 0, b); dimg->DelBrush(b); b = dimg->NewBrushARGB(0xff000000); dimg->DrawString(Math::Coord2DDbl(0, 0), CSTR("Sensor not found"), f, b); dimg->DelBrush(b); dimg->DelFont(f); } else { Data::ArrayListInt64 dateList; Data::ArrayListDbl valList; SSWR::SMonitor::ISMonitorCore::DevRecord2 *rec; if (readingType == SSWR::SMonitor::SAnalogSensor::RT_AHUMIDITY && readingTypeD == SSWR::SMonitor::SAnalogSensor::RT_RHUMIDITY) { UOSInt treadingIndex = (UOSInt)-1; Double tempDeg; Double rh; Bool hasTemp; Bool hasRH; i = 0; j = dev->nReading; while (i < j) { if (ReadInt16(&dev->readings[i].status[0]) == sensorId && ReadInt16(&dev->readings[i].status[6]) == SSWR::SMonitor::SAnalogSensor::RT_TEMPERATURE) { treadingIndex = i; break; } i++; } i = 0; j = dev->todayRecs.GetCount(); while (i < j) { rec = dev->todayRecs.GetItem(i); hasTemp = false; hasRH = false; if (rec->nreading > readingIndex && ReadInt16(&rec->readings[readingIndex].status[0]) == sensorId && ReadInt16(&rec->readings[readingIndex].status[4]) == readingId) { if (ReadInt16(&rec->readings[readingIndex].status[6]) == readingTypeD) { hasRH = true; rh = rec->readings[readingIndex].reading; } } else { k = rec->nreading; while (k-- > 0) { if (ReadInt16(&rec->readings[k].status[0]) == sensorId && ReadInt16(&rec->readings[k].status[4]) == readingId && ReadInt16(&rec->readings[k].status[6]) == readingTypeD) { hasRH = true; rh = rec->readings[k].reading; break; } } } if (treadingIndex != (UOSInt)-1 && rec->nreading > treadingIndex && ReadInt16(&rec->readings[treadingIndex].status[0]) == sensorId && ReadInt16(&rec->readings[treadingIndex].status[6]) == SSWR::SMonitor::SAnalogSensor::RT_TEMPERATURE) { hasTemp = true; tempDeg = rec->readings[treadingIndex].reading; } else { k = rec->nreading; while (k-- > 0) { if (ReadInt16(&rec->readings[k].status[0]) == sensorId && ReadInt16(&rec->readings[k].status[6]) == SSWR::SMonitor::SAnalogSensor::RT_TEMPERATURE) { hasTemp = true; tempDeg = rec->readings[k].reading; break; } } } if (hasTemp && hasRH) { dateList.Add(rec->recTime); valList.Add(Math::Unit::Pressure::WaterVapourPressure(Math::Unit::Pressure::PU_PASCAL, Math::Unit::Temperature::TU_CELSIUS, tempDeg, rh)); } i++; } } else { i = 0; j = dev->todayRecs.GetCount(); while (i < j) { rec = dev->todayRecs.GetItem(i); if (rec->nreading > readingIndex && ReadInt16(&rec->readings[readingIndex].status[0]) == sensorId && ReadInt16(&rec->readings[readingIndex].status[4]) == readingId) { if (ReadInt16(&rec->readings[readingIndex].status[6]) == readingType) { dateList.Add(rec->recTime); valList.Add(rec->readings[readingIndex].reading); } } else { k = rec->nreading; while (k-- > 0) { if (ReadInt16(&rec->readings[k].status[0]) == sensorId && ReadInt16(&rec->readings[k].status[4]) == readingId) { if (ReadInt16(&rec->readings[k].status[6]) == readingType) { dateList.Add(rec->recTime); valList.Add(rec->readings[k].reading); } break; } } } i++; } } Text::StringBuilderUTF8 sb; if (dev->readingNames[readingIndex]) { sb.AppendSlow(dev->readingNames[readingIndex]); } else { sb.AppendC(UTF8STRC("Sensor ")); sb.AppendI32(ReadInt16(dev->readings[readingIndex].status)); if (ReadInt16(&dev->readings[readingIndex].status[6]) != SSWR::SMonitor::SAnalogSensor::RT_UNKNOWN) { sb.AppendC(UTF8STRC(" ")); sb.Append(SSWR::SMonitor::SAnalogSensor::GetReadingTypeName((SSWR::SMonitor::SAnalogSensor::ReadingType)ReadInt16(&dev->readings[readingIndex].status[6]))); } } Double currVal; if (readingType == SSWR::SMonitor::SAnalogSensor::RT_AHUMIDITY && readingTypeD == SSWR::SMonitor::SAnalogSensor::RT_RHUMIDITY) { currVal = 0; i = 0; j = dev->nReading; while (i < j) { if (ReadInt16(&dev->readings[i].status[0]) == sensorId && ReadInt16(&dev->readings[i].status[6]) == SSWR::SMonitor::SAnalogSensor::RT_TEMPERATURE) { currVal = Math::Unit::Pressure::WaterVapourPressure(Math::Unit::Pressure::PU_PASCAL, Math::Unit::Temperature::TU_CELSIUS, dev->readings[i].reading, dev->readings[readingIndex].reading); break; } i++; } } else { currVal = dev->readings[readingIndex].reading; } sb.AppendC(UTF8STRC(" (")); sb.AppendDouble(currVal); sb.AppendC(UTF8STRC(")")); if (dateList.GetCount() >= 2) { Int64 maxTime; Int64 thisTime; Double yesterdayVal = 0; Int64 yesterdayMaxTime = 0; Data::ArrayListInt64 dateList2; Data::ArrayListDbl valList2; maxTime = dateList.GetItem(dateList.GetCount() - 1); if (readingType == SSWR::SMonitor::SAnalogSensor::RT_AHUMIDITY && readingTypeD == SSWR::SMonitor::SAnalogSensor::RT_RHUMIDITY) { UOSInt treadingIndex = (UOSInt)-1; Double tempDeg; Double rh; Bool hasTemp; Bool hasRH; i = 0; j = dev->nReading; while (i < j) { if (ReadInt16(&dev->readings[i].status[0]) == sensorId && ReadInt16(&dev->readings[i].status[6]) == SSWR::SMonitor::SAnalogSensor::RT_TEMPERATURE) { treadingIndex = i; break; } i++; } i = 0; j = dev->yesterdayRecs.GetCount(); while (i < j) { rec = dev->yesterdayRecs.GetItem(i); hasTemp = false; hasRH = false; if (rec->nreading > readingIndex && ReadInt16(&rec->readings[readingIndex].status[0]) == sensorId && ReadInt16(&rec->readings[readingIndex].status[4]) == readingId) { if (ReadInt16(&rec->readings[readingIndex].status[6]) == readingTypeD) { hasRH = true; rh = rec->readings[readingIndex].reading; } } else { k = rec->nreading; while (k-- > 0) { if (ReadInt16(&rec->readings[k].status[0]) == sensorId && ReadInt16(&rec->readings[k].status[4]) == readingId) { if (ReadInt16(&rec->readings[k].status[6]) == readingTypeD) { hasRH = true; rh = rec->readings[readingIndex].reading; } break; } } } if (treadingIndex != (UOSInt)-1 && rec->nreading > treadingIndex && ReadInt16(&rec->readings[treadingIndex].status[0]) == sensorId && ReadInt16(&rec->readings[treadingIndex].status[6]) == SSWR::SMonitor::SAnalogSensor::RT_TEMPERATURE) { hasTemp = true; tempDeg = rec->readings[treadingIndex].reading; } else { k = rec->nreading; while (k-- > 0) { if (ReadInt16(&rec->readings[k].status[0]) == sensorId && ReadInt16(&rec->readings[k].status[6]) == SSWR::SMonitor::SAnalogSensor::RT_TEMPERATURE) { hasTemp = true; tempDeg = rec->readings[k].reading; break; } } } if (hasTemp && hasRH) { thisTime = rec->recTime + 86400000LL; if (thisTime <= maxTime) { Double pres = Math::Unit::Pressure::WaterVapourPressure(Math::Unit::Pressure::PU_PASCAL, Math::Unit::Temperature::TU_CELSIUS, tempDeg, rh); dateList2.Add(thisTime); valList2.Add(pres); if (thisTime > yesterdayMaxTime) { yesterdayMaxTime = thisTime; yesterdayVal = pres; } } } i++; } if (yesterdayMaxTime != 0) { if (yesterdayVal < currVal) { sb.AppendC(UTF8STRC(" +")); } else { sb.AppendC(UTF8STRC(" ")); } sb.AppendDouble(currVal - yesterdayVal); } } else { i = 0; j = dev->yesterdayRecs.GetCount(); while (i < j) { rec = dev->yesterdayRecs.GetItem(i); if (rec->nreading > readingIndex && ReadInt16(&rec->readings[readingIndex].status[0]) == sensorId && ReadInt16(&rec->readings[readingIndex].status[4]) == readingId) { if (ReadInt16(&rec->readings[readingIndex].status[6]) == readingType) { thisTime = rec->recTime + 86400000LL; if (thisTime <= maxTime) { dateList2.Add(thisTime); valList2.Add(rec->readings[readingIndex].reading); if (thisTime > yesterdayMaxTime) { yesterdayMaxTime = thisTime; yesterdayVal = rec->readings[readingIndex].reading; } } } } else { k = rec->nreading; while (k-- > 0) { if (ReadInt16(&rec->readings[k].status[0]) == sensorId && ReadInt16(&rec->readings[k].status[4]) == readingId) { if (ReadInt16(&rec->readings[k].status[6]) == readingType) { thisTime = rec->recTime + 86400000LL; if (thisTime <= maxTime) { dateList2.Add(thisTime); valList2.Add(rec->readings[k].reading); if (thisTime > yesterdayMaxTime) { yesterdayMaxTime = thisTime; yesterdayVal = rec->readings[k].reading; } } } break; } } } i++; } if (yesterdayMaxTime != 0) { if (yesterdayVal < dev->readings[readingIndex].reading) { sb.AppendC(UTF8STRC(" +")); } else { sb.AppendC(UTF8STRC(" ")); } sb.AppendDouble(dev->readings[readingIndex].reading - yesterdayVal); } } NEW_CLASS(chart, Data::LineChart(sb.ToCString())); if (dateList2.GetCount() >= 2) { chart->AddXDataDate(dateList2.Ptr(), dateList2.GetCount()); chart->AddYData(CSTR("Yesterday"), valList2.Ptr(), valList2.GetCount(), 0xffcccccc, Data::LineChart::LS_LINE); } chart->AddXDataDate(dateList.Ptr(), dateList.GetCount()); chart->AddYData(CSTR("Reading"), valList.Ptr(), valList.GetCount(), 0xffff0000, Data::LineChart::LS_LINE); chart->SetDateFormat(CSTR("")); chart->SetFontHeightPt(10); chart->SetTimeZoneQHR(32); chart->SetTimeFormat(CSTR("HH:mm")); chart->Plot(dimg, 0, 0, UOSInt2Double(dimg->GetWidth()), UOSInt2Double(dimg->GetHeight())); DEL_CLASS(chart); } else { f = dimg->NewFontPx(CSTR("Arial"), 12, Media::DrawEngine::DFS_ANTIALIAS, 0); b = dimg->NewBrushARGB(0xffffffff); dimg->DrawRect(Math::Coord2DDbl(0, 0), dimg->GetSize().ToDouble(), 0, b); dimg->DelBrush(b); b = dimg->NewBrushARGB(0xff000000); dimg->DrawString(Math::Coord2DDbl(0, 0), sb.ToCString(), f, b); dimg->DrawString(Math::Coord2DDbl(0, 12), CSTR("Data not enough"), f, b); dimg->DelBrush(b); dimg->DelFont(f); } } mutUsage.EndUse(); Exporter::GUIPNGExporter *exporter; Media::ImageList *imgList; NEW_CLASS(imgList, Media::ImageList(CSTR("temp.png"))); imgList->AddImage(dimg->ToStaticImage(), 0); deng->DeleteImage(dimg); NotNullPtr<IO::MemoryStream> nnmstm; NEW_CLASSNN(nnmstm, IO::MemoryStream()); NEW_CLASS(exporter, Exporter::GUIPNGExporter()); exporter->ExportFile(nnmstm, CSTR("temp.png"), imgList, 0); DEL_CLASS(exporter); DEL_CLASS(imgList); buff = nnmstm->GetBuff(&buffSize); resp->AddDefHeaders(req); resp->AddContentType(CSTR("image/png")); resp->AddContentLength(buffSize); resp->AddHeader(CSTR("Cache-Control"), CSTR("no-cache")); resp->Write(buff, buffSize); mutUsage.ReplaceMutex(dev->mut, true); mstm = dev->imgCaches.Put((sensorId << 16) + (readingId << 8) + (readingType), nnmstm.Ptr()); mutUsage.EndUse(); if (mstm) { DEL_CLASS(mstm); } return true; } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::DevicePastDataReq(SSWR::SMonitor::SMonitorWebHandler *me, NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp) { Text::UTF8Writer *writer; Int32 userId = 0; Int32 userType = 0; UInt8 *buff; UOSInt buffSize; UTF8Char sbuff[64]; UTF8Char *sptr; Net::WebServer::IWebSession *sess = me->sessMgr->GetSession(req, resp); if (sess) { userId = sess->GetValueInt32(UTF8STRC("UserId")); userType = sess->GetValueInt32(UTF8STRC("UserType")); } UOSInt i; UOSInt j; UOSInt k; UOSInt l; Data::ArrayList<SSWR::SMonitor::ISMonitorCore::DeviceInfo *> devList; SSWR::SMonitor::ISMonitorCore::DeviceInfo *dev; IO::MemoryStream mstm; NEW_CLASS(writer, Text::UTF8Writer(mstm)); WriteHeaderBegin(writer); writer->WriteLineC(UTF8STRC("<script type=\"text/javascript\">")); writer->WriteLineC(UTF8STRC("var clients = new Object();")); writer->WriteLineC(UTF8STRC("var cli;")); writer->WriteLineC(UTF8STRC("var reading;")); me->core->UserGetDevices(userId, userType, &devList); i = 0; j = devList.GetCount(); while (i < j) { dev = devList.GetItem(i); writer->WriteLineC(UTF8STRC("cli = new Object();")); writer->WriteStrC(UTF8STRC("cli.cliId = ")); sptr = Text::StrInt64(sbuff, dev->cliId); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteLineC(UTF8STRC(";")); Sync::RWMutexUsage mutUsage(dev->mut, false); writer->WriteStrC(UTF8STRC("cli.name = ")); if (dev->devName) { WriteJSText(writer, dev->devName); } else { WriteJSText(writer, dev->platformName); } writer->WriteLineC(UTF8STRC(";")); writer->WriteLineC(UTF8STRC("cli.readings = new Array();")); k = 0; l = dev->nReading; while (k < l) { writer->WriteLineC(UTF8STRC("reading = new Object();")); writer->WriteStrC(UTF8STRC("reading.name = ")); if (dev->readingNames[k]) { WriteJSText(writer, dev->readingNames[k]); } else { Text::StrInt32(Text::StrConcatC(Text::StrInt32(Text::StrConcatC(sbuff, UTF8STRC("Sensor ")), ReadInt16(dev->readings[k].status)), UTF8STRC(" Reading ")), ReadInt16(&dev->readings[k].status[4])); WriteJSText(writer, sbuff); } writer->WriteLineC(UTF8STRC(";")); writer->WriteStrC(UTF8STRC("reading.sensor = ")); sptr = Text::StrInt32(sbuff, ReadInt16(dev->readings[k].status)); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteLineC(UTF8STRC(";")); writer->WriteStrC(UTF8STRC("reading.reading = ")); sptr = Text::StrInt32(sbuff, ReadInt16(&dev->readings[k].status[4])); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteLineC(UTF8STRC(";")); writer->WriteLineC(UTF8STRC("cli.readings.push(reading);")); k++; } writer->WriteLineC(UTF8STRC("clients[cli.cliId] = cli;")); mutUsage.EndUse(); i++; } writer->WriteLineC(UTF8STRC("</script>")); writer->WriteLineC(UTF8STRC("<script type=\"text/javascript\" src=\"files/pastdata.js\">")); writer->WriteLineC(UTF8STRC("</script>")); WriteHeaderEnd(writer); writer->WriteLineC(UTF8STRC("<body onload=\"afterLoad()\">")); writer->WriteLineC(UTF8STRC("<table width=\"100%\"><tr><td width=\"100\" class=\"menu\">")); me->WriteMenu(writer, sess); writer->WriteLineC(UTF8STRC("</td><td>")); writer->WriteLineC(UTF8STRC("<h2>Past Data</h2>")); writer->WriteLineC(UTF8STRC("Device Name<select name=\"cliId\" id=\"cliId\" onchange=\"devChg()\"></select><br/>")); writer->WriteLineC(UTF8STRC("Reading<select name=\"reading\" id=\"reading\" onchange=\"selChg()\"></select><br/>")); writer->WriteLineC(UTF8STRC("Date<select name=\"year\" id=\"year\" onchange=\"selChg()\"></select><select name=\"month\" id=\"month\" onchange=\"selChg()\"></select><select name=\"day\" id=\"day\" onchange=\"selChg()\"></select><br/>")); writer->WriteLineC(UTF8STRC("<img src=\"about:blank\" id=\"dataimg\"/>")); writer->WriteLineC(UTF8STRC("</td></tr></table></body>")); writer->WriteLineC(UTF8STRC("</html>")); if (sess) { sess->EndUse(); } DEL_CLASS(writer); buff = mstm.GetBuff(&buffSize); resp->AddDefHeaders(req); resp->AddContentType(CSTR("text/html")); resp->AddContentLength(buffSize); resp->AddHeader(CSTR("Cache-Control"), CSTR("no-cache")); resp->Write(buff, buffSize); return true; } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::DevicePastDataImgReq(SSWR::SMonitor::SMonitorWebHandler *me, NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp) { Text::String *s; Int64 cliId = 0; Int64 startTime = 0; Int32 userId = 0; Int32 userType = 0; Int32 sensorId = 0; Int32 readingId = 0; Bool valid = true; s = req->GetQueryValue(CSTR("id")); if (s == 0) { valid = false; } else if (!s->ToInt64(cliId)) { valid = false; } s = req->GetQueryValue(CSTR("sensor")); if (s == 0) { valid = false; } else if (!s->ToInt32(sensorId)) { valid = false; } s = req->GetQueryValue(CSTR("reading")); if (s == 0) { valid = false; } else if (!s->ToInt32(readingId)) { valid = false; } s = req->GetQueryValue(CSTR("starttime")); if (s == 0) { valid = false; } else if (!s->ToInt64(startTime)) { valid = false; } if (!valid) { resp->ResponseError(req, Net::WebStatus::SC_NOT_FOUND); return true; } Net::WebServer::IWebSession *sess = me->sessMgr->GetSession(req, resp); if (sess) { userId = sess->GetValueInt32(UTF8STRC("UserId")); userType = sess->GetValueInt32(UTF8STRC("UserType")); sess->EndUse(); } if (!me->core->UserHasDevice(userId, userType, cliId)) { resp->ResponseError(req, Net::WebStatus::SC_NOT_FOUND); return true; } SSWR::SMonitor::ISMonitorCore::DeviceInfo *dev = me->core->DeviceGet(cliId); Data::ArrayList<SSWR::SMonitor::ISMonitorCore::DevRecord2*> recList; UOSInt i; UOSInt j; UOSInt k; UInt8 *buff; UOSInt buffSize; NotNullPtr<Media::DrawEngine> deng = me->core->GetDrawEngine(); Media::DrawImage *dimg = deng->CreateImage32(Math::Size2D<UOSInt>(640, 120), Media::AT_NO_ALPHA); Media::DrawFont *f; Media::DrawBrush *b; UOSInt readingIndex = (UOSInt)-1; Int32 readingType = 0; Data::LineChart *chart; Sync::RWMutexUsage mutUsage(dev->mut, false); i = dev->nReading; while (i-- > 0) { if (ReadInt16(&dev->readings[i].status[0]) == sensorId && ReadInt16(&dev->readings[i].status[4]) == readingId) { readingIndex = i; readingType = ReadInt16(&dev->readings[i].status[6]); break; } } mutUsage.EndUse(); if (readingIndex == (UOSInt)-1) { f = dimg->NewFontPx(CSTR("Arial"), 12, Media::DrawEngine::DFS_ANTIALIAS, 0); b = dimg->NewBrushARGB(0xffffffff); dimg->DrawRect(Math::Coord2DDbl(0, 0), dimg->GetSize().ToDouble(), 0, b); dimg->DelBrush(b); b = dimg->NewBrushARGB(0xff000000); dimg->DrawString(Math::Coord2DDbl(0, 0), CSTR("Sensor not found"), f, b); dimg->DelBrush(b); dimg->DelFont(f); } else { UTF8Char sbuff[64]; UTF8Char *sptr; Data::ArrayListInt64 dateList; Data::ArrayListDbl valList; SSWR::SMonitor::ISMonitorCore::DevRecord2 *rec; me->core->DeviceQueryRec(cliId, startTime, startTime + 86400000, &recList); i = 0; j = recList.GetCount(); while (i < j) { rec = recList.GetItem(i); if (rec->nreading > readingIndex && ReadInt16(&rec->readings[readingIndex].status[0]) == sensorId && ReadInt16(&rec->readings[readingIndex].status[4]) == readingId) { if (ReadInt16(&rec->readings[readingIndex].status[6]) == readingType) { dateList.Add(rec->recTime); valList.Add(rec->readings[readingIndex].reading); } } else { k = rec->nreading; while (k-- > 0) { if (ReadInt16(&rec->readings[k].status[0]) == sensorId && ReadInt16(&rec->readings[k].status[4]) == readingId) { if (ReadInt16(&rec->readings[k].status[6]) == readingType) { dateList.Add(rec->recTime); valList.Add(rec->readings[k].reading); } break; } } } MemFree(rec); i++; } Text::StringBuilderUTF8 sb; Sync::RWMutexUsage mutUsage(dev->mut, false); if (dev->readingNames[readingIndex]) { sb.AppendSlow(dev->readingNames[readingIndex]); } else { sb.AppendC(UTF8STRC("Sensor ")); sb.AppendI32(ReadInt16(dev->readings[readingIndex].status)); if (ReadInt16(&dev->readings[readingIndex].status[6]) != SSWR::SMonitor::SAnalogSensor::RT_UNKNOWN) { sb.AppendC(UTF8STRC(" ")); sb.Append(SSWR::SMonitor::SAnalogSensor::GetReadingTypeName((SSWR::SMonitor::SAnalogSensor::ReadingType)ReadInt16(&dev->readings[readingIndex].status[6]))); } } mutUsage.EndUse(); Data::DateTime dt; dt.SetTicks(startTime); dt.ToLocalTime(); sptr = dt.ToString(sbuff, "yyyy-MM-dd"); sb.AppendC(UTF8STRC(" ")); sb.AppendP(sbuff, sptr); if (dateList.GetCount() >= 2) { NEW_CLASS(chart, Data::LineChart(sb.ToCString())); chart->AddXDataDate(dateList.Ptr(), dateList.GetCount()); chart->AddYData(CSTR("Reading"), valList.Ptr(), valList.GetCount(), 0xffff0000, Data::LineChart::LS_LINE); chart->SetDateFormat(CSTR("")); chart->SetFontHeightPt(10); chart->SetTimeZoneQHR(32); chart->SetTimeFormat(CSTR("HH:mm")); chart->Plot(dimg, 0, 0, UOSInt2Double(dimg->GetWidth()), UOSInt2Double(dimg->GetHeight())); DEL_CLASS(chart); } else { f = dimg->NewFontPx(CSTR("Arial"), 12, Media::DrawEngine::DFS_ANTIALIAS, 0); b = dimg->NewBrushARGB(0xffffffff); dimg->DrawRect(Math::Coord2DDbl(0, 0), dimg->GetSize().ToDouble(), 0, b); dimg->DelBrush(b); b = dimg->NewBrushARGB(0xff000000); dimg->DrawString(Math::Coord2DDbl(0, 0), sb.ToCString(), f, b); dimg->DrawString(Math::Coord2DDbl(0, 12), CSTR("Data not enough"), f, b); dimg->DelBrush(b); dimg->DelFont(f); } } Exporter::GUIPNGExporter *exporter; Media::ImageList *imgList; NEW_CLASS(imgList, Media::ImageList(CSTR("temp.png"))); imgList->AddImage(dimg->ToStaticImage(), 0); deng->DeleteImage(dimg); IO::MemoryStream mstm; NEW_CLASS(exporter, Exporter::GUIPNGExporter()); exporter->ExportFile(mstm, CSTR("temp.png"), imgList, 0); DEL_CLASS(exporter); DEL_CLASS(imgList); buff = mstm.GetBuff(&buffSize); resp->AddDefHeaders(req); resp->AddContentType(CSTR("image/png")); resp->AddContentLength(buffSize); resp->AddHeader(CSTR("Cache-Control"), CSTR("no-cache")); resp->Write(buff, buffSize); return true; } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::UserPasswordReq(SSWR::SMonitor::SMonitorWebHandler *me, NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp) { Text::UTF8Writer *writer; UInt8 *buff; UOSInt buffSize; Net::WebServer::IWebSession *sess = me->sessMgr->GetSession(req, resp); Text::CString msg = CSTR_NULL; if (sess == 0) { return resp->RedirectURL(req, CSTR("/monitor/index"), 0); } if (req->GetReqMethod() == Net::WebUtil::RequestMethod::HTTP_POST) { req->ParseHTTPForm(); Text::String *pwd = req->GetHTTPFormStr(CSTR("password")); Text::String *retype = req->GetHTTPFormStr(CSTR("retype")); if (pwd == 0 || pwd->v[0] == 0) { msg = CSTR("Password is empty"); } else if (retype == 0 || retype->v[0] == 0) { msg = CSTR("Retype is empty"); } else if (!pwd->Equals(retype)) { msg = CSTR("Password and retype do not match"); } else { UOSInt len = pwd->leng; if (len < 3) { msg = CSTR("Password is too short"); } else { if (me->core->UserSetPassword(sess->GetValueInt32(UTF8STRC("UserId")), pwd->v)) { msg = CSTR("Password is changed successfully"); } else { msg = CSTR("Error in changing password"); } } } } IO::MemoryStream mstm; NEW_CLASS(writer, Text::UTF8Writer(mstm)); WriteHeaderBegin(writer); WriteHeaderEnd(writer); writer->WriteLineC(UTF8STRC("<body onload=\"document.getElementById('password').focus()\">")); writer->WriteLineC(UTF8STRC("<table width=\"100%\"><tr><td width=\"100\" class=\"menu\">")); me->WriteMenu(writer, sess); writer->WriteLineC(UTF8STRC("</td><td>")); writer->WriteLineC(UTF8STRC("<h2>Modify Password</h2>")); writer->WriteLineC(UTF8STRC("<center>")); writer->WriteLineC(UTF8STRC("<form method=\"POST\" action=\"userpassword\">")); writer->WriteLineC(UTF8STRC("<table border=\"0\"><tr><td>Password</td><td><input type=\"password\" name=\"password\" id=\"password\"/></td></tr>")); writer->WriteLineC(UTF8STRC("<tr><td>Retype</td><td><input type=\"password\" name=\"retype\" id=\"retype\"/></td></tr>")); writer->WriteLineC(UTF8STRC("<tr><td></td><td><input type=\"submit\"/></td></tr>")); writer->WriteLineC(UTF8STRC("</table>")); if (msg.v) { WriteHTMLText(writer, msg); } writer->WriteLineC(UTF8STRC("</form></center>")); writer->WriteLineC(UTF8STRC("</td></tr></table></body>")); writer->WriteLineC(UTF8STRC("</html>")); sess->EndUse(); DEL_CLASS(writer); buff = mstm.GetBuff(&buffSize); resp->AddDefHeaders(req); resp->AddContentType(CSTR("text/html")); resp->AddContentLength(buffSize); resp->AddHeader(CSTR("Cache-Control"), CSTR("no-cache")); resp->Write(buff, buffSize); return true; } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::UsersReq(SSWR::SMonitor::SMonitorWebHandler *me, NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp) { Text::UTF8Writer *writer; UInt8 *buff; UOSInt buffSize; UTF8Char sbuff[64]; UTF8Char *sptr; Net::WebServer::IWebSession *sess = me->sessMgr->GetSession(req, resp); if (sess == 0) { return resp->RedirectURL(req, CSTR("/monitor/index"), 0); } if (sess->GetValueInt32(UTF8STRC("UserType")) != 1) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/index"), 0); } Data::ArrayList<SSWR::SMonitor::ISMonitorCore::WebUser*> userList; SSWR::SMonitor::ISMonitorCore::WebUser *user; UOSInt i; UOSInt j; me->core->UserGetList(&userList); IO::MemoryStream mstm; NEW_CLASS(writer, Text::UTF8Writer(mstm)); WriteHeaderBegin(writer); WriteHeaderEnd(writer); writer->WriteLineC(UTF8STRC("<body>")); writer->WriteLineC(UTF8STRC("<table width=\"100%\"><tr><td width=\"100\" class=\"menu\">")); me->WriteMenu(writer, sess); writer->WriteLineC(UTF8STRC("</td><td>")); writer->WriteLineC(UTF8STRC("<h2>Users</h2>")); writer->WriteLineC(UTF8STRC("<a href=\"useradd\">Add User</a><br/>")); writer->WriteLineC(UTF8STRC("<table border=\"1\"><tr><td>User Name</td><td>Action</td></tr>")); i = 0; j = userList.GetCount(); while (i < j) { user = userList.GetItem(i); writer->WriteStrC(UTF8STRC("<tr><td>")); Sync::RWMutexUsage mutUsage(user->mut, false); sptr = Text::StrInt32(sbuff, user->userId); WriteHTMLText(writer, user->userName); mutUsage.EndUse(); writer->WriteStrC(UTF8STRC("</td><td><a href=\"userreset?id=")); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("\">Reset Password</a>")); writer->WriteStrC(UTF8STRC("<br/><a href=\"userassign?id=")); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("\">Assign Devices</a>")); writer->WriteLineC(UTF8STRC("</td></tr>")); i++; } writer->WriteLineC(UTF8STRC("</table>")); writer->WriteLineC(UTF8STRC("</td></tr></table></body>")); writer->WriteLineC(UTF8STRC("</html>")); sess->EndUse(); DEL_CLASS(writer); buff = mstm.GetBuff(&buffSize); resp->AddDefHeaders(req); resp->AddContentType(CSTR("text/html")); resp->AddContentLength(buffSize); resp->AddHeader(CSTR("Cache-Control"), CSTR("no-cache")); resp->Write(buff, buffSize); return true; } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::UserAddReq(SSWR::SMonitor::SMonitorWebHandler *me, NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp) { Text::UTF8Writer *writer; UInt8 *buff; UOSInt buffSize; Net::WebServer::IWebSession *sess = me->sessMgr->GetSession(req, resp); if (sess == 0) { return resp->RedirectURL(req, CSTR("/monitor/index"), 0); } if (sess->GetValueInt32(UTF8STRC("UserType")) != 1) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/index"), 0); } if (req->GetReqMethod() == Net::WebUtil::RequestMethod::HTTP_POST) { req->ParseHTTPForm(); Text::String *action; Text::String *userName; action = req->GetHTTPFormStr(CSTR("action")); userName = req->GetHTTPFormStr(CSTR("username")); if (action && userName && action->Equals(UTF8STRC("adduser"))) { UOSInt len = userName->leng; if (len >= 3 && len < 128) { if (me->core->UserAdd(userName->v, userName->v, 2)) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/users"), 0); } } } } IO::MemoryStream mstm; NEW_CLASS(writer, Text::UTF8Writer(mstm)); WriteHeaderBegin(writer); WriteHeaderEnd(writer); writer->WriteLineC(UTF8STRC("<body onload=\"document.getElementById('username').focus()\">")); writer->WriteLineC(UTF8STRC("<table width=\"100%\"><tr><td width=\"100\" class=\"menu\">")); me->WriteMenu(writer, sess); writer->WriteLineC(UTF8STRC("</td><td>")); writer->WriteLineC(UTF8STRC("<h2>Add User</h2>")); writer->WriteLineC(UTF8STRC("<form name=\"adduser\" method=\"POST\" action=\"useradd\">")); writer->WriteLineC(UTF8STRC("<input type=\"hidden\" name=\"action\" value=\"adduser\"/>")); writer->WriteLineC(UTF8STRC("<table border=\"1\"><tr><td>User Name</td><td><input type=\"text\" name=\"username\" id=\"username\" /></td></tr>")); writer->WriteLineC(UTF8STRC("<tr><td></td><td><input type=\"submit\" /></td></tr>")); writer->WriteLineC(UTF8STRC("</table>")); writer->WriteLineC(UTF8STRC("</td></tr></table></body>")); writer->WriteLineC(UTF8STRC("</html>")); sess->EndUse(); DEL_CLASS(writer); buff = mstm.GetBuff(&buffSize); resp->AddDefHeaders(req); resp->AddContentType(CSTR("text/html")); resp->AddContentLength(buffSize); resp->AddHeader(CSTR("Cache-Control"), CSTR("no-cache")); resp->Write(buff, buffSize); return true; } Bool __stdcall SSWR::SMonitor::SMonitorWebHandler::UserAssignReq(SSWR::SMonitor::SMonitorWebHandler *me, NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp) { Text::UTF8Writer *writer; UInt8 *buff; UOSInt buffSize; UTF8Char sbuff[64]; UTF8Char *sptr; Net::WebServer::IWebSession *sess = me->sessMgr->GetSession(req, resp); SSWR::SMonitor::ISMonitorCore::WebUser *user; Int32 userId; UOSInt i; UOSInt j; if (!req->GetQueryValueI32(CSTR("id"), userId)) { return resp->RedirectURL(req, CSTR("/monitor/users"), 0); } user = me->core->UserGet(userId); if (user == 0 || user->userType != 2) { return resp->RedirectURL(req, CSTR("/monitor/users"), 0); } if (sess == 0) { return resp->RedirectURL(req, CSTR("/monitor/index"), 0); } if (sess->GetValueInt32(UTF8STRC("UserType")) != 1) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/index"), 0); } if (req->GetReqMethod() == Net::WebUtil::RequestMethod::HTTP_POST) { req->ParseHTTPForm(); Text::String *action; Text::String *devicestr; action = req->GetHTTPFormStr(CSTR("action")); devicestr = req->GetHTTPFormStr(CSTR("device")); if (action && devicestr && action->Equals(UTF8STRC("userassign"))) { Data::ArrayListInt64 devIds; UTF8Char *sarr[2]; Text::StringBuilderUTF8 sb; Int64 cliId; Bool valid = true; sb.Append(devicestr); sarr[1] = sb.v; while (true) { i = Text::StrSplit(sarr, 2, sarr[1], ','); if (!Text::StrToInt64(sarr[0], cliId)) { valid = false; break; } devIds.Add(cliId); if (i != 2) break; } if (valid && me->core->UserAssign(userId, &devIds)) { sess->EndUse(); return resp->RedirectURL(req, CSTR("/monitor/users"), 0); } } } Data::ArrayList<SSWR::SMonitor::ISMonitorCore::DeviceInfo *> devList; SSWR::SMonitor::ISMonitorCore::DeviceInfo *dev; me->core->UserGetDevices(sess->GetValueInt32(UTF8STRC("UserId")), 1, &devList); IO::MemoryStream mstm; NEW_CLASS(writer, Text::UTF8Writer(mstm)); WriteHeaderBegin(writer); WriteHeaderEnd(writer); writer->WriteLineC(UTF8STRC("<body onload=\"document.getElementById('username').focus()\">")); writer->WriteLineC(UTF8STRC("<table width=\"100%\"><tr><td width=\"100\" class=\"menu\">")); me->WriteMenu(writer, sess); writer->WriteLineC(UTF8STRC("</td><td>")); writer->WriteLineC(UTF8STRC("<h2>User Assign</h2>")); writer->WriteStrC(UTF8STRC("User Name: ")); Sync::RWMutexUsage userMutUsage(user->mut, false); WriteHTMLText(writer, user->userName); writer->WriteLineC(UTF8STRC("<br/>")); writer->WriteStrC(UTF8STRC("<form name=\"userassign\" method=\"POST\" action=\"userassign?id=")); sptr = Text::StrInt32(sbuff, user->userId); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteLineC(UTF8STRC("\">")); writer->WriteLineC(UTF8STRC("<input type=\"hidden\" name=\"action\" value=\"userassign\"/>")); writer->WriteLineC(UTF8STRC("Device List<br/>")); i = 0; j = devList.GetCount(); while (i < j) { dev = devList.GetItem(i); Sync::RWMutexUsage devMutUsage(dev->mut, false); writer->WriteStrC(UTF8STRC("<input type=\"checkbox\" name=\"device\" id=\"device")); sptr = Text::StrInt64(sbuff, dev->cliId); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("\" value=\"")); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("\"")); if (user->devMap.Get(dev->cliId)) { writer->WriteStrC(UTF8STRC(" checked")); } writer->WriteStrC(UTF8STRC("/><label for=\"device")); writer->WriteStrC(sbuff, (UOSInt)(sptr - sbuff)); writer->WriteStrC(UTF8STRC("\">")); if (dev->devName) { WriteHTMLText(writer, Text::String::OrEmpty(dev->devName)); } else { WriteHTMLText(writer, dev->platformName); } writer->WriteStrC(UTF8STRC("</label><br/>")); devMutUsage.EndUse(); i++; } userMutUsage.EndUse(); writer->WriteLineC(UTF8STRC("<input type=\"submit\" />")); writer->WriteLineC(UTF8STRC("</td></tr></table></body>")); writer->WriteLineC(UTF8STRC("</html>")); sess->EndUse(); DEL_CLASS(writer); buff = mstm.GetBuff(&buffSize); resp->AddDefHeaders(req); resp->AddContentType(CSTR("text/html")); resp->AddContentLength(buffSize); resp->AddHeader(CSTR("Cache-Control"), CSTR("no-cache")); resp->Write(buff, buffSize); return true; } void __stdcall SSWR::SMonitor::SMonitorWebHandler::WriteHeaderBegin(IO::Writer *writer) { writer->WriteLineC(UTF8STRC("<html><head><title>Monitor</title>")); writer->WriteLineC(UTF8STRC("<style>")); writer->WriteLineC(UTF8STRC(".menu {")); writer->WriteLineC(UTF8STRC(" vertical-align: top;")); writer->WriteLineC(UTF8STRC("}")); writer->WriteLineC(UTF8STRC("</style>")); } void __stdcall SSWR::SMonitor::SMonitorWebHandler::WriteHeaderEnd(IO::Writer *writer) { writer->WriteLineC(UTF8STRC("</head>")); } void __stdcall SSWR::SMonitor::SMonitorWebHandler::WriteMenu(IO::Writer *writer, Net::WebServer::IWebSession *sess) { Int32 userType = 0; if (sess) { Data::DateTime dt; dt.SetCurrTimeUTC(); sess->SetValueInt64(UTF8STRC("LastSessTime"), dt.ToTicks()); userType = sess->GetValueInt32(UTF8STRC("UserType")); } if (userType == 0) { writer->WriteLineC(UTF8STRC("<a href=\"login\">Login</a><br/>")); } if (userType != 0) { writer->WriteLineC(UTF8STRC("<a href=\"logout\">Logout</a><br/>")); } writer->WriteLineC(UTF8STRC("<br/>")); writer->WriteLineC(UTF8STRC("<a href=\"index\">Home</a><br/>")); if (userType != 0) { writer->WriteLineC(UTF8STRC("<a href=\"device\">Devices</a><br/>")); writer->WriteLineC(UTF8STRC("<a href=\"userpassword\">Password</a><br/>")); } writer->WriteLineC(UTF8STRC("<a href=\"pastdata\">Past Data</a><br/>")); if (userType == 1) { writer->WriteLineC(UTF8STRC("<a href=\"users\">Users</a><br/>")); } } void __stdcall SSWR::SMonitor::SMonitorWebHandler::WriteHTMLText(IO::Writer *writer, const UTF8Char *txt) { NotNullPtr<Text::String> xmlTxt = Text::XML::ToNewHTMLBodyText(txt); writer->WriteStrC(xmlTxt->v, xmlTxt->leng); xmlTxt->Release(); } void __stdcall SSWR::SMonitor::SMonitorWebHandler::WriteHTMLText(IO::Writer *writer, NotNullPtr<Text::String> txt) { NotNullPtr<Text::String> xmlTxt = Text::XML::ToNewHTMLBodyText(txt->v); writer->WriteStrC(xmlTxt->v, xmlTxt->leng); xmlTxt->Release(); } void __stdcall SSWR::SMonitor::SMonitorWebHandler::WriteHTMLText(IO::Writer *writer, Text::CString txt) { NotNullPtr<Text::String> xmlTxt = Text::XML::ToNewHTMLBodyText(txt.v); writer->WriteStrC(xmlTxt->v, xmlTxt->leng); xmlTxt->Release(); } void __stdcall SSWR::SMonitor::SMonitorWebHandler::WriteAttrText(IO::Writer *writer, const UTF8Char *txt) { NotNullPtr<Text::String> xmlTxt = Text::XML::ToNewAttrText(txt); writer->WriteStrC(xmlTxt->v, xmlTxt->leng); xmlTxt->Release(); } void __stdcall SSWR::SMonitor::SMonitorWebHandler::WriteAttrText(IO::Writer *writer, Text::String *txt) { NotNullPtr<Text::String> xmlTxt = Text::XML::ToNewAttrText(STR_PTR(txt)); writer->WriteStrC(xmlTxt->v, xmlTxt->leng); xmlTxt->Release(); } void __stdcall SSWR::SMonitor::SMonitorWebHandler::WriteAttrText(IO::Writer *writer, NotNullPtr<Text::String> txt) { NotNullPtr<Text::String> xmlTxt = Text::XML::ToNewAttrText(txt->v); writer->WriteStrC(xmlTxt->v, xmlTxt->leng); xmlTxt->Release(); } void __stdcall SSWR::SMonitor::SMonitorWebHandler::WriteJSText(IO::Writer *writer, const UTF8Char *txt) { NotNullPtr<Text::String> jsTxt = Text::JSText::ToNewJSText(txt); writer->WriteStrC(jsTxt->v, jsTxt->leng); jsTxt->Release(); } void __stdcall SSWR::SMonitor::SMonitorWebHandler::WriteJSText(IO::Writer *writer, Text::String *txt) { NotNullPtr<Text::String> jsTxt = Text::JSText::ToNewJSText(txt); writer->WriteStrC(jsTxt->v, jsTxt->leng); jsTxt->Release(); } void __stdcall SSWR::SMonitor::SMonitorWebHandler::WriteJSText(IO::Writer *writer, NotNullPtr<Text::String> txt) { NotNullPtr<Text::String> jsTxt = Text::JSText::ToNewJSText(txt); writer->WriteStrC(jsTxt->v, jsTxt->leng); jsTxt->Release(); } Bool SSWR::SMonitor::SMonitorWebHandler::ProcessRequest(NotNullPtr<Net::WebServer::IWebRequest> req, NotNullPtr<Net::WebServer::IWebResponse> resp, Text::CString subReq) { if (this->DoRequest(req, resp, subReq)) { return true; } RequestHandler reqHdlr = this->reqMap->GetC(subReq); if (reqHdlr) { return reqHdlr(this, req, resp); } resp->ResponseError(req, Net::WebStatus::SC_NOT_FOUND); return true; } SSWR::SMonitor::SMonitorWebHandler::SMonitorWebHandler(SSWR::SMonitor::ISMonitorCore *core) { this->core = core; NEW_CLASS(this->reqMap, Data::FastStringMap<RequestHandler>()); NEW_CLASS(this->sessMgr, Net::WebServer::MemoryWebSessionManager(CSTR("/monitor"), OnSessDeleted, this, 60000, OnSessCheck, this, CSTR("SMonSessId"))); this->reqMap->PutC(CSTR(""), DefaultReq); this->reqMap->PutC(CSTR("/index"), IndexReq); this->reqMap->PutC(CSTR("/login"), LoginReq); this->reqMap->PutC(CSTR("/logout"), LogoutReq); this->reqMap->PutC(CSTR("/device"), DeviceReq); this->reqMap->PutC(CSTR("/devedit"), DeviceEditReq); this->reqMap->PutC(CSTR("/devreading"), DeviceReadingReq); this->reqMap->PutC(CSTR("/devdigitals"), DeviceDigitalsReq); this->reqMap->PutC(CSTR("/devreadingimg"), DeviceReadingImgReq); this->reqMap->PutC(CSTR("/pastdata"), DevicePastDataReq); this->reqMap->PutC(CSTR("/pastdataimg"), DevicePastDataImgReq); this->reqMap->PutC(CSTR("/userpassword"), UserPasswordReq); this->reqMap->PutC(CSTR("/users"), UsersReq); this->reqMap->PutC(CSTR("/useradd"), UserAddReq); // this->reqMap->PutC(CSTR("/userreset"), UserResetReq); this->reqMap->PutC(CSTR("/userassign"), UserAssignReq); } SSWR::SMonitor::SMonitorWebHandler::~SMonitorWebHandler() { DEL_CLASS(this->sessMgr); DEL_CLASS(this->reqMap); }
d0a5e05cc9e4a3217838fb2b1837d8d63452bdc3
ac5e6a759c266f5315c56f45f71cc7cc6a58eeb4
/src/IslaCanvas.cpp
8f3b2c60fa0c300cab126cb87bc63a91593b72c4
[]
no_license
ian-ross/isla
aecd6a3722fa7a8f702d2e3c4453d39ba15097df
a6c7aece1ead4902ba47ecd47fb6bb5f91bfd9cf
refs/heads/master
2021-03-12T20:46:03.473180
2013-05-25T13:52:08
2013-05-25T13:52:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
28,257
cpp
IslaCanvas.cpp
//---------------------------------------------------------------------- // FILE: IslaCanvas.cpp // DATE: 23-FEB-2013 // AUTHOR: Ian Ross // // Canvas class for main map view of Isla island editor. //---------------------------------------------------------------------- #include <wx/wx.h> #include <wx/colour.h> #include <iostream> using namespace std; #include "IslaCanvas.hh" #include "IslaModel.hh" #include "IslaFrame.hh" #include "IslaPreferences.hh" #include "ids.hh" // Canvas event table. BEGIN_EVENT_TABLE(IslaCanvas, wxWindow) EVT_PAINT (IslaCanvas::OnPaint) EVT_SIZE (IslaCanvas::OnSize) EVT_MOTION (IslaCanvas::OnMouse) EVT_LEFT_DOWN (IslaCanvas::OnMouse) EVT_LEFT_UP (IslaCanvas::OnMouse) EVT_MOUSEWHEEL (IslaCanvas::OnMouse) EVT_ERASE_BACKGROUND (IslaCanvas::OnEraseBackground) EVT_CONTEXT_MENU (IslaCanvas::OnContextMenu) EVT_KEY_DOWN (IslaCanvas::OnKey) EVT_MENU (ID_CTX_TOGGLE_ISLAND, IslaCanvas::OnContextMenuEvent) EVT_MENU (ID_CTX_COARSEN_ISLAND, IslaCanvas::OnContextMenuEvent) EVT_MENU (ID_CTX_REFINE_ISLAND, IslaCanvas::OnContextMenuEvent) EVT_MENU (ID_CTX_RESET_ISLAND, IslaCanvas::OnContextMenuEvent) END_EVENT_TABLE() // Constructor sets up border sizing, all model-dependent values and // canvas size parameters. IslaCanvas::IslaCanvas(wxWindow *parent, IslaModel *m) : wxWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE), #ifdef ISLA_DEBUG sizingOverlay(false), regionOverlay(false), ismaskOverlay(false), isIslandOverlay(false), #endif frame(0), mouse(MOUSE_NOTHING), panning(false), zoom_selection(false), edit(false), show_islands(true), show_comparison(true) { // Calculate border width and border text offset. wxPaintDC dc(this); wxCoord th; dc.GetTextExtent(_("888"), &celllablimit, &th); bw = static_cast<int>(1.5 * th); boff = static_cast<int>(0.25 * th); // Model grid. GridPtr g = m->grid(); // Set up initial sizing. We start with a nominal width, take off // the space required for the axis borders, then calculate a map // aspect ratio based on the padding we need to add to have full // grid cells at the top and bottom. We can then use this to // calculate the map height, and add the border widths to get // requested canvas dimensions. int nomw = 1000; mapw = nomw - 2 * bw; double tmpscale = mapw / 360.0; scale = -1; double maplat = 180.0 + g->lat(1) - g->lat(0); maph = maplat * tmpscale; canw = mapw + 2 * bw; canh = maph + 2 * bw; xoff = static_cast<int>((canw - mapw) / 2); yoff = static_cast<int>((canh - maph) / 2); // Reset view. clon = 180.0; clat = 0.0; // Set up model-dependent values. ModelReset(m, false); // UI setup. SetSize(wxDefaultCoord, wxDefaultCoord, static_cast<int>(canw), static_cast<int>(canh)); mouse = MOUSE_NOTHING; SetCursor(wxCursor(wxCURSOR_ARROW)); SetBackgroundColour(*wxLIGHT_GREY); // Create context menu. popup = new wxMenu(); popup->Append(ID_CTX_TOGGLE_ISLAND, _("Landmass island toggle")); popup->AppendSeparator(); island_actions.push_back(popup->Append(ID_CTX_COARSEN_ISLAND, _("Coarsen island segmentation"))); island_actions.push_back(popup->Append(ID_CTX_REFINE_ISLAND, _("Refine island segmentation"))); island_actions.push_back(popup->Append(ID_CTX_RESET_ISLAND, _("Reset island segmentation"))); } // Load island comparison data. void IslaCanvas::loadComparisonIslands(wxString fname) { bool ok = model->loadIslands(fname, compisles); Refresh(); if (!ok) { wxMessageDialog msg(frame, _("There may be a problem with the island data.\n" "Some grid cell coordinate values " "were out of range."), _("Potential island data problem"), wxICON_WARNING); msg.ShowModal(); } } // Change of model. void IslaCanvas::ModelReset(IslaModel *m, bool refresh) { model = m; GridPtr g = model->grid(); // Find minimum longitude and latitude step used in the model grid // (used for determining scales for enabling and disabling zoom // in/out). for (unsigned int i = 0; i < g->nlon(); ++i) { double dlon = fabs(fmod(g->lon((i+1)%g->nlon()) - g->lon(i), 360.0)); minDlon = i == 0 ? dlon : min(minDlon, dlon); } for (unsigned int i = 0; i < g->nlat()-1; ++i) { double dlat = fabs(g->lat(i+1) - g->lat(i)); minDlat = i == 0 ? dlat : min(minDlat, dlat); } // Determine inter-grid cell latitudes and longitudes (used for // bounds of grid cells and for drawing grid lines). int n = g->nlon(); iclons.resize(n + 1); for (int i = 0; i < n; ++i) iclons[i+1] = g->lon(i) + fmod(360.0 + g->lon((i+1) % n) - g->lon(i), 360.0) / 2; iclons[0] = -fmod(360.0 + g->lon(0) - g->lon(n-1), 360.0) / 2; iclats.resize(g->nlat() + 1); n = g->nlat(); for (int i = 0; i < n-1; ++i) iclats[i+1] = (g->lat(i) + g->lat(i+1)) / 2; iclats[0] = g->lat(0) - (iclats[2] - iclats[1]) / 2; iclats[n] = g->lat(n-1) + (iclats[n-1] - iclats[n-2]) / 2; // Trigger other required canvas recalculations. if (refresh) { SizeRecalc(); Refresh(); } } // Main paint callback. In order, renders: grid cells, grid (if // visible), axes, borders and any debug overlays. // // THIS WILL NEED TO BE OPTIMISED. AT THE MOMENT, IT DOES THE DUMBEST // POSSIBLE THING... void IslaCanvas::OnPaint(wxPaintEvent &WXUNUSED(event)) { // Setup: determine minimum region to redraw. GridPtr g = model->grid(); int nlon = g->nlon(), nlat = g->nlat(); int nhor = static_cast<int>(min(static_cast<double>(nlon), mapw / (minDlon * scale) + 1) + 1); int nver = static_cast<int>(min(static_cast<double>(nlat), maph / (minDlat * scale) + 6)); int lon0 = static_cast<int>(XToLon(0)), lat0 = static_cast<int>(YToLat(maph)); int ilon0 = 0, ilat0 = 0; double loni = g->lon(ilon0), loni1 = g->lon((ilon0 + 1) % nlon); while (!(lon0 >= loni && lon0 < loni1 + (loni1 >= loni ? 0 : 360.0))) { ilon0 = (ilon0 + 1) % nlon; loni = g->lon(ilon0); loni1 = g->lon((ilon0 + 1) % nlon); } while (g->lat(ilat0) < lat0) ++ilat0; ilat0 = max(0, ilat0 - 3); wxPaintDC dc(this); // Clear grid cell and axis areas. dc.SetBrush(*wxWHITE_BRUSH); int imapw = static_cast<int>(mapw), imaph = static_cast<int>(maph); dc.DrawRectangle(xoff, yoff - bw, imapw, bw); dc.DrawRectangle(xoff, yoff + imaph, imapw, bw); dc.DrawRectangle(xoff - bw, yoff, bw, imaph); dc.DrawRectangle(xoff + imapw, yoff, bw, imaph); dc.SetBrush(wxBrush(IslaPreferences::get()->getOceanColour())); dc.DrawRectangle(xoff, yoff, imapw, imaph); // Set clip region for grid cells and grid. dc.SetClippingRegion(xoff, yoff, imapw, imaph); // Fill grid cells. dc.SetPen(*wxTRANSPARENT_PEN); wxBrush land(IslaPreferences::get()->getLandColour()); wxBrush island(IslaPreferences::get()->getIslandColour()); for (int i = 0, c = ilon0; i < nhor; ++i, c = (c + 1) % nlon) for (int j = 0, r = ilat0; j < nver && r < nlat; ++j, ++r) if (model->maskVal(r, c)) { dc.SetBrush(model->isIsland(r, c) ? island : land); int xl = static_cast<int>(lonToX(iclons[c])); int xr = static_cast<int>(lonToX(iclons[(c+1)%nlon])); int yt = static_cast<int>(max(0.0, latToY(iclats[r]))); int yb = static_cast<int>(min(latToY(iclats[r+1]), canh)); if (xl <= xr) dc.DrawRectangle(xoff + xl, yoff + yt, xr-xl, yb-yt); else { dc.DrawRectangle(xoff + xl, yoff + yt, imapw-xl, yb-yt); dc.DrawRectangle(xoff, yoff + yt, xr, yb-yt); } } dc.SetBrush(*wxTRANSPARENT_BRUSH); // Draw grid. if (MinCellSize() >= 4) { dc.SetPen(wxPen(IslaPreferences::get()->getGridColour())); for (int i = 0, c = ilon0; i <= nhor; ++i, c = (c + 1) % nlon) { int x = static_cast<int>(lonToX(iclons[c])); if (x >= 0 && x <= mapw) dc.DrawLine(xoff + x, yoff, xoff + x, yoff + imaph); } for (int i = 0, r = ilat0; i <= nver && r <= nlat; ++i, ++r) { int y = static_cast<int>(latToY(iclats[r])); if (y >= 0 && y <= maph) dc.DrawLine(xoff, yoff + y, xoff + imapw, yoff + y); } } // Draw island segments. if (show_islands && model->islands().size() > 0) { const map<LMass, IslaModel::IslandInfo> &isles = model->islands(); wxPen p(IslaPreferences::get()->getIslandOutlineColour(), 3); wxBrush vb(IslaPreferences::get()->getIslandOutlineColour(), wxHORIZONTAL_HATCH); wxBrush hb(IslaPreferences::get()->getIslandOutlineColour(), wxVERTICAL_HATCH); for (map<LMass, IslaModel::IslandInfo>::const_iterator it = isles.begin(); it != isles.end(); ++it) drawIsland(dc, p, vb, hb, it->second); } // Draw island comparison segments. if (show_comparison && compisles.size() > 0) { wxPen p(IslaPreferences::get()->getCompOutlineColour(), 3, wxSHORT_DASH); wxBrush vb(IslaPreferences::get()->getCompOutlineColour(), wxHORIZONTAL_HATCH); wxBrush hb(IslaPreferences::get()->getCompOutlineColour(), wxVERTICAL_HATCH); for (vector<IslaModel::IslandInfo>::const_iterator it = compisles.begin(); it != compisles.end(); ++it) drawIsland(dc, p, vb, hb, *it); } // Draw axes. dc.DestroyClippingRegion(); dc.SetClippingRegion(taxis); axisLabels(dc, true, yoff - bw + boff, taxpos, taxlab); dc.DestroyClippingRegion(); dc.SetClippingRegion(baxis); axisLabels(dc, true, static_cast<int>(canh - yoff + boff), baxpos, baxlab); dc.DestroyClippingRegion(); dc.SetClippingRegion(laxis); axisLabels(dc, false, static_cast<int>(xoff - bw + 1.5 * boff), laxpos, laxlab); dc.DestroyClippingRegion(); dc.SetClippingRegion(raxis); axisLabels(dc, false, static_cast<int>(canw - xoff + 1.5 * boff), raxpos, raxlab); // Draw borders. dc.DestroyClippingRegion(); dc.SetBrush(*wxTRANSPARENT_BRUSH); dc.SetPen(*wxBLACK_PEN); dc.DrawRectangle(xoff, yoff - bw, imapw, imaph + bw * 2); dc.DrawRectangle(xoff - bw, yoff, imapw + bw * 2, imaph); #ifdef ISLA_DEBUG // Debug overlays. int cs = static_cast<int>(MinCellSize()); wxCoord tw, th; dc.SetFont(*wxSWISS_FONT); dc.GetTextExtent(_("XX"), &tw, &th); wxFont font(*wxSWISS_FONT); if (th > 0.9 * cs) { font.SetPointSize(static_cast<int>(font.GetPointSize() * 0.9 * cs / th)); dc.SetFont(font); } dc.SetClippingRegion(xoff, yoff, imapw, imaph); if (regionOverlay) { dc.SetTextForeground(*wxBLUE); wxString txt; GridPtr g = model->grid(); for (int i = 0, c = ilon0; i < nhor; ++i, c = (c + 1) % nlon) { int x = static_cast<int>(xoff + lonToX(g->lon(c)) - tw / 2); for (int j = 0, r = ilat0; j < nver && r < nlat; ++j, ++r) { txt.Printf(_("%d"), model->landMass(r, c)); int y = static_cast<int>(latToY(g->lat(r))); dc.DrawText(txt, x, yoff + y - th / 2); } } } if (ismaskOverlay) { dc.SetTextForeground(*wxRED); wxString txt; GridPtr g = model->grid(); for (int i = 0, c = ilon0; i < nhor; ++i, c = (c + 1) % nlon) { int x = static_cast<int>(xoff + lonToX(iclons[c]) - tw / 2); for (int j = 0, r = ilat0; j < nver && r < nlat; ++j, ++r) { txt.Printf(_("%d"), model->isMask(r, c)); int y = static_cast<int>(latToY(iclats[r])); dc.DrawText(txt, x, yoff + y - th / 2); } } } if (isIslandOverlay) { dc.SetTextForeground(*wxGREEN); wxString txt; GridPtr g = model->grid(); for (int i = 0, c = ilon0; i < nhor; ++i, c = (c + 1) % nlon) { int x = static_cast<int>(xoff + lonToX(g->lon(c)) - tw / 2); for (int j = 0, r = ilat0; j < nver && r < nlat; ++j, ++r) { txt = model->isIsland(r, c) ? _("X") : _(""); int y = static_cast<int>(latToY(g->lat(r))); dc.DrawText(txt, x, yoff + y - th / 2); } } } if (sizingOverlay) { dc.SetTextForeground(*wxRED); int x = 50, y = 30, l = 0; wxString txt; txt.Printf(_("nlon=%d nlat=%d"), g->nlon(), g->nlat()); dc.DrawText(txt, x, y + th * l++); txt.Printf(_("minDlon=%.2f minDlat=%.2f"), minDlon, minDlat); dc.DrawText(txt, x, y + th * l++); txt.Printf(_("canw=%d canh=%d"), static_cast<int>(canw), static_cast<int>(canh)); dc.DrawText(txt, x, y + th * l++); txt.Printf(_("mapw=%d maph=%d"), imapw, imaph); dc.DrawText(txt, x, y + th * l++); } #endif } // Draw a single island. void IslaCanvas::drawIsland(wxDC &dc, wxPen &p, wxBrush &vb, wxBrush &hb, const IslaModel::IslandInfo &isl) { GridPtr g = model->grid(); int nlon = g->nlon(), nlat = g->nlat(); const vector<wxRect> &segs = isl.segments; dc.SetPen(p); for (vector<wxRect>::const_iterator jt = segs.begin(); jt != segs.end(); ++jt) { int xl = static_cast<int>(lonToX(g->lon((jt->x-1 + nlon) % nlon))); int xr = static_cast<int>(lonToX(g->lon((jt->x-1 + jt->width) % nlon))); int yb = static_cast<int>(min(latToY(g->lat(max(0, jt->y-1))), canh)); int yt = jt->y-1 + jt->height >= nlat ? 0 : static_cast<int>(max(0.0, latToY(g->lat(jt->y-1 + jt->height)))); if (xl < xr) dc.DrawRectangle(xoff + xl, yoff + yt, xr-xl, yb-yt); else { dc.DrawRectangle(xoff + xl, yoff + yt, static_cast<int>(mapw)-xl+5, yb-yt); dc.DrawRectangle(xoff, yoff + yt, xr, yb-yt); } } dc.SetPen(*wxTRANSPARENT_PEN); dc.SetBrush(vb); const IslaModel::CoincInfo &vhatch = isl.vcoinc; int dx = static_cast<int>(lonToX(iclons[2]) - lonToX(iclons[1])); for (IslaModel::CoincInfo::const_iterator vit = vhatch.begin(); vit != vhatch.end(); ++vit) { int x = static_cast<int>(lonToX(g->lon((vit->first-1 + nlon) % nlon))); int yb = static_cast<int>(min(latToY(g->lat(vit->second.first-1)), canh)); int yt = vit->second.second >= nlat ? 0 : static_cast<int>(latToY(g->lat(vit->second.second-1))); int xl = x - dx / 2, xr = x + dx / 2; if (xl < xr) dc.DrawRectangle(xoff + xl, yoff + yt, xr-xl, yb-yt); else { dc.DrawRectangle(xoff + xl, yoff + yt, static_cast<int>(mapw)-xl+5, yb-yt); dc.DrawRectangle(xoff, yoff + yt, xr, yb-yt); } } dc.SetBrush(hb); const IslaModel::CoincInfo &hhatch = isl.hcoinc; for (IslaModel::CoincInfo::const_iterator hit = hhatch.begin(); hit != hhatch.end(); ++hit) { int y = static_cast<int>(min(latToY(g->lat(hit->first-1)), canh)); int dy = static_cast<int>(latToY(g->lat(hit->first-1)) - latToY(g->lat(hit->first))); int xl = static_cast<int>(lonToX(g->lon((hit->second.first-1 + nlon) % nlon))); int xr = static_cast<int>(lonToX(g->lon((hit->second.second-1 + nlon) % nlon))); int yt = y - dy / 2, yb = y + dy / 2; if (xl < xr) dc.DrawRectangle(xoff + xl, yoff + yt, xr-xl, yb-yt); else { dc.DrawRectangle(xoff + xl, yoff + yt, static_cast<int>(mapw)-xl+5, yb-yt); dc.DrawRectangle(xoff, yoff + yt, xr, yb-yt); } } dc.SetBrush(*wxTRANSPARENT_BRUSH); } // Mouse handler. Deals with: // // * Dragging in the axis borders: pans view. // * Mousewheel events anywhere in the canvas: pan view. // * Dragging anywhere in the canvas while the pan tool is active: // pans view. // * Dragging anywhere in the canvas while "zoom to selection" is // active: rubberbands zoom box then triggers zoom when done. void IslaCanvas::OnMouse(wxMouseEvent &event) { int x = event.GetX(), y = event.GetY(); bool ypanevent = laxis.Contains(x, y) || raxis.Contains(x, y); bool xpanevent = taxis.Contains(x, y) || baxis.Contains(x, y); if (event.GetEventType() == wxEVT_MOUSEWHEEL) { if (xpanevent) Pan(static_cast<int>(0.25 * event.GetWheelRotation()), 0); else Pan(0, static_cast<int>(0.25 * event.GetWheelRotation())); } else if (xpanevent || ypanevent || panning) ProcessPan(event, xpanevent, ypanevent); else if (zoom_selection) ProcessZoomSelection(event); else if (edit) ProcessEdit(event); if (x < bw || x > canw - bw || y < bw || y > canh - bw) return; double lon = XToLon(x - bw), lat = YToLat(y - bw); int col = lonToCol(lon) + 1, row = latToRow(lat) + 1; frame->SetLocation(lon, lat, col, row); } void IslaCanvas::ProcessPan(wxMouseEvent &event, bool xpan, bool ypan) { int x = event.GetX(), y = event.GetY(); if (event.LeftDown()) { // Start a new action. mousex = x; mousey = y; if (panning && !xpan && !ypan) mouse = MOUSE_PAN_2D; else mouse = xpan ? MOUSE_PAN_X : MOUSE_PAN_Y; } else if (!event.LeftIsDown()) { mouse = MOUSE_NOTHING; return; } else { switch(mouse) { case MOUSE_NOTHING: return; case MOUSE_PAN_X: Pan(x - mousex, 0); break; case MOUSE_PAN_Y: Pan(0, y - mousey); break; case MOUSE_PAN_2D: Pan(x - mousex, y - mousey); break; default: break; } } mousex = x; mousey = y; } void IslaCanvas::ProcessZoomSelection(wxMouseEvent &event) { if (!event.LeftDown() && mouse == MOUSE_NOTHING) return; int x = event.GetX(), y = event.GetY(); wxPaintDC dc(this); wxPen pen(*wxBLACK, 2, wxLONG_DASH); dc.SetLogicalFunction(wxINVERT); dc.SetPen(pen); dc.SetBrush(*wxTRANSPARENT_BRUSH); if (event.LeftDown()) { // Start a new action. zoom_x0 = x; zoom_y0 = y; mouse = MOUSE_ZOOM_SELECTION; } else { // Erase rubber band rectangle if this isn't the start of a // new drag. int l = min(mousex, zoom_x0), t = min(mousey, zoom_y0); int w = abs(zoom_x0 - mousex), h = abs(zoom_y0 - mousey); dc.DrawRectangle(l, t, w, h); } if (!event.LeftIsDown()) { // Zoom selection complete. zoom_selection = false; mouse = MOUSE_NOTHING; SetCursor(wxCursor(wxCURSOR_ARROW)); DoZoomToSelection(zoom_x0, zoom_y0, x, y); } else { // Draw rubber band rectangle. int l = min(zoom_x0, x), t = min(zoom_y0, y); int w = abs(zoom_x0 - x), h = abs(zoom_y0 - y); dc.DrawRectangle(l, t, w, h); mousex = x; mousey = y; } } void IslaCanvas::ProcessEdit(wxMouseEvent &event) { int x = event.GetX(), y = event.GetY(); if (x < bw || x > canw - bw || y < bw || y > canh - bw) return; if (event.LeftDown()) { double edlon = XToLon(x - bw), edlat = YToLat(y - bw); edcol = lonToCol(edlon); edrow = latToRow(edlat); model->setMask(edrow, edcol, !model->maskVal(edrow, edcol)); edval = model->maskVal(edrow, edcol); mouse = MOUSE_EDIT; Refresh(); } else if (event.LeftIsDown() && mouse == MOUSE_EDIT) { double edlon = XToLon(x - bw), edlat = YToLat(y - bw); int newedcol = lonToCol(edlon), newedrow = latToRow(edlat); if (newedcol != edcol || newedrow != edrow) { edcol = newedcol; edrow = newedrow; model->setMask(edrow, edcol, edval); Refresh(); } } else { mouse = MOUSE_NOTHING; return; } } // Right click menu. void IslaCanvas::OnContextMenu(wxContextMenuEvent &event) { wxPoint pos = ScreenToClient(event.GetPosition()); if (pos.y < yoff || pos.y > canh - yoff || pos.x < xoff || pos.x > canw - yoff) return; popup_col = lonToCol(XToLon(pos.x - xoff)); popup_row = latToRow(YToLat(pos.y - yoff)); if (!model->maskVal(popup_row, popup_col)) return; bool island_active = model->isIsland(popup_row, popup_col); for (vector<wxMenuItem *>::iterator it = island_actions.begin(); it != island_actions.end(); ++it) (*it)->Enable(island_active); PopupMenu(popup); } void IslaCanvas::OnContextMenuEvent(wxCommandEvent &event) { switch (event.GetId()) { case ID_CTX_TOGGLE_ISLAND: model->setIsIsland(popup_row, popup_col, !model->isIsland(popup_row, popup_col)); break; case ID_CTX_COARSEN_ISLAND: model->coarsenIsland(popup_row, popup_col); break; case ID_CTX_REFINE_ISLAND: model->refineIsland(popup_row, popup_col); break; case ID_CTX_RESET_ISLAND: model->resetIsland(popup_row, popup_col); break; } Refresh(); } // Resize handler. Just hands off to SizeRecalc then triggers a // refresh. void IslaCanvas::OnSize(wxSizeEvent &event) { wxSize sz = event.GetSize(); canw = sz.GetWidth(); canh = sz.GetHeight(); SizeRecalc(); Refresh(); if (frame) frame->UpdateUI(); } // Set up border axis label positions and strings. void IslaCanvas::SetupAxes(bool dox, bool doy) { GridPtr g = model->grid(); int nlon = g->nlon(), nlat = g->nlat(); wxPaintDC dc(this); wxString txt; int tw, th; if (dox) { taxis = wxRect(xoff, yoff - bw, static_cast<int>(mapw), bw); baxis = wxRect(xoff, static_cast<int>(canh - yoff), static_cast<int>(mapw), bw); vector<int> tws(nlon); vector<int> poss(nlon); for (int i = 0; i < nlon; ++i) { txt.Printf(_("%d"), i == 0 ? nlon : i); dc.GetTextExtent(txt, &tw, &th); tws[i] = tw; poss[i] = xoff + static_cast<int>(lonToX(g->lon((i - 1 + nlon) % nlon))); } int mindpos, maxtw; for (int i = 0; i < nlon; ++i) { int dpos = static_cast<int>(fabs(poss[(i+1)%nlon] - poss[i])); if (i == 0 || (dpos > 0 && dpos < mindpos)) mindpos = dpos; if (i == 0 || tws[i] > maxtw) maxtw = tws[i]; } int skip = 2; while (skip * mindpos < 3 * maxtw) skip += 2; taxpos.resize(nlon / skip); taxlab.resize(nlon / skip); for (int i = 0; i < nlon / skip; ++i) { taxpos[i] = xoff + static_cast<int>(lonToX(g->lon((i * skip - 1 + nlon) % nlon))); taxlab[i].Printf(_("%d"), i * skip == 0 ? nlon : i * skip); } baxpos.resize(9); baxlab.resize(9); for (int i = 0; i < 9; ++i) baxpos[i] = xoff + static_cast<int>(lonToX(i * 45.0)); baxlab[0] = _("0"); baxlab[1] = _("45E"); baxlab[2] = _("90E"); baxlab[3] = _("135E"); baxlab[4] = _("180"); baxlab[5] = _("135W"); baxlab[6] = _("90W"); baxlab[7] = _("45W"); baxlab[8] = _("0"); } if (doy) { laxis = wxRect(xoff - bw, yoff, bw, static_cast<int>(maph)); raxis = wxRect(static_cast<int>(canw - xoff), yoff, bw, static_cast<int>(maph)); vector<int> tws(nlat); vector<int> poss(nlat); for (int i = 0; i < nlat; ++i) { txt.Printf(_("%d"), i + 1); dc.GetTextExtent(txt, &tw, &th); tws[i] = tw; poss[i] = xoff + static_cast<int>(latToY(g->lat(i))); } int mindpos, maxtw; for (int i = 0; i < nlat; ++i) { int dpos = i < nlat-1 ? static_cast<int>(fabs(poss[i+1] - poss[i])) : static_cast<int>(fabs(poss[i] - poss[i-1])); if (i == 0 || (dpos > 0 && dpos < mindpos)) mindpos = dpos; if (i == 0 || tws[i] > maxtw) maxtw = tws[i]; } int skip = 2; while (skip * mindpos < 3 * maxtw) skip += 2; laxpos.resize(nlat / skip - (nlat % skip == 0 ? 1 : 0)); laxlab.resize(nlat / skip - (nlat % skip == 0 ? 1 : 0)); for (int i = skip; i < nlat; i += skip) { laxpos[i/skip-1] = yoff + static_cast<int>(latToY(g->lat(i - 1))); laxlab[i/skip-1].Printf(_("%d"), i); } raxpos.resize(5); raxlab.resize(5); for (int i = 0; i < 5; ++i) raxpos[i] = yoff + static_cast<int>(latToY(60 - i * 30.0)); raxlab[0] = _("60N"); raxlab[1] = _("30N"); raxlab[2] = _("0"); raxlab[3] = _("30S"); raxlab[4] = _("60S"); } } // Render axis labels for one axis. void IslaCanvas::axisLabels(wxDC &dc, bool horiz, int yOrX, const vector<int> &xOrYs, const vector<wxString> &labs) { wxCoord tw, th; for (unsigned int i = 0; i < xOrYs.size(); ++i) { dc.GetTextExtent(labs[i], &tw, &th); if (horiz) { dc.DrawText(labs[i], xOrYs[i] - tw / 2, yOrX); } else { dc.DrawRotatedText(labs[i], yOrX, xOrYs[i] + tw / 2, 90.0); } } } // Find cell coordinates. int IslaCanvas::lonToCol(double lon) { lon = fmod(360.0 + lon, 360.0); int n = model->grid()->nlon(); if (lon >= iclons[n]) return 0; for (int i = 0; i < n; ++i) if (lon >= iclons[i] && lon < iclons[i+1]) return i; return -1; } int IslaCanvas::latToRow(double lat) { for (unsigned int i = 0; i < iclats.size() - 1; ++i) if (iclats[i] <= lat && lat < iclats[i + 1]) return i; return -1; } // Pan handler. void IslaCanvas::Pan(int dx, int dy) { GridPtr g = model->grid(); double halfh = maph / 2 / scale; double clatb = clat; clon = fmod(360.0 + clon - dx / scale, 360.0); clat += dy / scale; clat = max(clat, iclats[0] + halfh); clat = min(clat, iclats[iclats.size()-1] - halfh); if (fabs(clat - clatb) * scale < 1) clat = clatb; SetupAxes(dx != 0, dy != 0); Refresh(); } // Key handler. void IslaCanvas::OnKey(wxKeyEvent &e) { int d = static_cast<int>(MinCellSize()); switch (e.GetKeyCode()) { case WXK_LEFT: Pan(d, 0); e.Skip(); break; case WXK_RIGHT: Pan(-d, 0); e.Skip(); break; case WXK_DOWN: Pan(0, -d); e.Skip(); break; case WXK_UP: Pan(0, d); e.Skip(); break; } } // Zoom in or out by given scale factor. void IslaCanvas::ZoomScale(double zfac) { scale *= zfac; double fitscale = FitScale(); if (scale < fitscale) scale = fitscale; if (MinCellSize() > 64) SetMinCellSize(64); SizeRecalc(); Refresh(); } // Zoom to fit map within available canvas area. void IslaCanvas::ZoomToFit(void) { scale = FitScale(); SizeRecalc(); Refresh(); } // Find scale to fit map to canvas. double IslaCanvas::FitScale(void) const { GridPtr g = model->grid(); double possmapw = canw - 2 * bw, possmaph = canh - 2 * bw; double fitwscale = possmapw / 360.0; double fithscale = possmaph / (180.0 + g->lat(1) - g->lat(0)); return min(fitwscale, fithscale); } // Zoom to a given x,y rectangle (in canvas coordinates). void IslaCanvas::DoZoomToSelection(int x0, int y0, int x1, int y1) { // Adjust for border offsets and limit longitude to within canvas. x0 -= bw; x0 = static_cast<int>(max(0.0, min(static_cast<double>(x0), mapw))); x1 -= bw; x1 = static_cast<int>(max(0.0, min(static_cast<double>(x1), mapw))); y0 -= bw; y1 -= bw; // Convert latitude to model (lat/lon) coordinate and limit to // within the acceptable range. double lat0 = YToLat(y0), lat1 = YToLat(y1); lat0 = min(max(lat0, iclats[0]), iclats[iclats.size()-1]); lat1 = min(max(lat1, iclats[0]), iclats[iclats.size()-1]); // Calculate new centre point and scale and redisplay. The // longitude calculation is done in canvas coordinates to avoid // problems with wraparound, and the latitude calculation is done in // model coordinates to take account of the extra half-cell padding // at the top and bottom of the map. clon = XToLon((x0 + x1) / 2); clat = (lat0 + lat1) / 2; double possmapw = canw - 2 * bw, possmaph = canh - 2 * bw; double fitwscale = possmapw / (fabs(x1 - x0) / scale); double fithscale = possmaph / fabs(lat1 - lat0); scale = min(fitwscale, fithscale); if (MinCellSize() < 2) SetMinCellSize(2); if (MinCellSize() > 64) SetMinCellSize(64); SizeRecalc(); Refresh(); if (frame) frame->UpdateUI(); } // Recalculate scaling information for canvas after resize, zoom, or // other event. void IslaCanvas::SizeRecalc(void) { if (scale < 0) { mapw = canw - bw * 2; scale = FitScale(); } else { if (360.0 * scale < canw - bw * 2) scale = FitScale(); mapw = min(360.0 * scale, canw - bw * 2); } xoff = static_cast<int>((canw - mapw) / 2); GridPtr g = model->grid(); maph = min((180.0 + g->lat(1) - g->lat(0)) * scale, canh - bw * 2.0); yoff = static_cast<int>((canh - maph) / 2); double halfh = maph / 2 / scale; clat = max(clat, iclats[0] + halfh); clat = min(clat, iclats[iclats.size()-1] - halfh); SetupAxes(); }
9f083a31360061e9d55237fb0804ce2fa7ccea4e
c99944ec00d7359ff365dc7af023ca2815f0c3bf
/sources/write.cpp
6c168d3f136db68f42f568c789ecf22654c62feb
[]
no_license
terpsihora96/art-scene
f18d95c5a8b999bb4e90de85e5cc10a552fb2d2b
e84c85db1d1bd84e92f4766294ee8d4a3bc86acd
refs/heads/master
2021-07-10T07:50:48.790150
2020-12-02T21:50:58
2020-12-02T21:50:58
214,654,496
0
0
null
null
null
null
UTF-8
C++
false
false
897
cpp
write.cpp
#include <GL/glut.h> #include <iostream> // Function for drawing string name on the screen // The position is controlled by double x, double y parameters void draw_name(std::string name, double x, double y) { int current_width = glutGet(GLUT_WINDOW_WIDTH); int current_height = glutGet(GLUT_WINDOW_HEIGHT); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glDisable(GL_LIGHTING); glDisable(GL_LIGHT0); gluOrtho2D(0.0, current_width, current_height, 0.0); glRasterPos2i(current_width - x, current_height - y); for (char letter : name) { glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, letter); } glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); }
6524023f8ebcbcf7eaa37ebf79a6ad69b9c9150c
69ed848d81b3fddfb3cb91162a70556547052d8a
/骨骼动作编辑器/骨骼制作器/windows_Class.cpp
7d7fa6bf8bd63d4dd99fb12d24b509fb6037cbcc
[]
no_license
JunC74/PYX
7c4fb7911d2b39cf1a310f29d36a7d38abdb23c8
0717a4b7f7bfad25ff820d01395e0bb7bf5505fe
refs/heads/master
2016-08-05T14:56:31.346241
2014-10-23T03:26:55
2014-10-23T03:26:55
25,617,079
1
0
null
null
null
null
GB18030
C++
false
false
24,208
cpp
windows_Class.cpp
#include "windows_class.h" #include <time.h> #include <windows.h> // include all the windows headers #include <windowsx.h> // include useful macros #include <cstring> #include "resource.h" WindowsClass::WindowsClass(HDC source_dc, RECT rect) :UIObject(source_dc, rect, NULL) { bk_bitmap = Bitmap::CreateBitmap(hdc_, "Res/bk.bmp"); focus_ui_object = NULL; b_add_point = NULL; b_delete = NULL; b_file_out = NULL; b_insert = NULL; b_next_frame = NULL; b_new_file = NULL; b_open_file = NULL; b_play = NULL; b_previous_frame = NULL; b_save_key = NULL; focus_ui_object = NULL; compute_info = NULL; sb_direction = NULL; workspace_info = NULL; frames_compute.SetFramesDataStringObject(&frame_string); frames_compute.SetOutSize(500); frames_compute.SetStep(10); } WindowsClass::~WindowsClass(void) { focus_ui_object = NULL; Delete(b_add_point); Delete(b_delete); Delete(b_file_out); Delete(b_insert); Delete(b_next_frame); Delete(b_new_file); Delete(b_open_file); Delete(b_play); Delete(b_previous_frame); Delete(b_save_key); Delete(compute_info); Delete(sb_direction); Delete(workspace_info); Delete(bk_bitmap); } void WindowsClass::OrderControl(int object_id) { switch(object_id) { case CB_NEW_FILE: // 新建文件 { // workspace设置状态失败 if(work_space->SetState(WORK_STATE_MOVE_FIND) == false){ ////////////////////////////////////////////////////////////////////////// // 提示用户操作失败 ////////////////////////////////////////////////////////////////////////// MessageBox(hwnd_, "workspace无法转换状态。", "错误!", NULL); b_new_file->SetState(0); break; } //获取系统时间,确定文件名 time_t t = time(0); char file_name[100]; strftime( file_name, sizeof(file_name), "%Y_%W_%a_%H_%M",localtime(&t)); if(frames_compute.CreateNewFile(file_name) == false) { // 创建文件失败的处理 MessageBox(hwnd_, "创建文件失败!", "错误!", NULL); } else { Frame frame, previous_frome; frame = frames_compute.GetFrame(frames_compute.GetFrameId()); work_space->SetTempFrameData(frame); sb_direction->SetState(frame.direction); previous_frome = frames_compute.GetFrame(frames_compute.GetFrameId() - 1); work_space->SetPreviousFrameBmp(previous_frome); // 创建文件成功的处理 // 设置按钮状态 b_add_point->SetState(0); b_previous_frame->SetState(IS_LOCK); b_next_frame->SetState(IS_LOCK); b_delete->SetState(IS_LOCK); b_insert->SetState(IS_LOCK); b_play->SetState(IS_LOCK); b_play_rectangle->SetState(IS_LOCK); b_file_out->SetState(IS_LOCK); } } break; case CB_OPEN_FILE: // 打开文件 { // workspace设置状态失败 if(work_space->SetState(WORK_STATE_MOVE_FIND) == false) { ////////////////////////////////////////////////////////////////////////// // 提示用户操作失败 ////////////////////////////////////////////////////////////////////////// MessageBox(hwnd_, "workspace无法转换状态。", "错误!", NULL); b_open_file->SetState(0); break; } // 如果帧串里面有数据 char file_name[100]; if (frame_string.GetFrameNum() != 0) { strcpy(file_name, "~"); strcat(file_name, frames_compute.GetFileName()); frames_compute.SaveFile(file_name); } strcpy(file_name, "open"); if (frames_compute.OpenFile(file_name) == false) { MessageBox(hwnd_, "open.fds无法加载。", "错误!", NULL); b_open_file->SetState(0); break; } Frame temp_frame = frames_compute.GetFrame(frames_compute.GetFrameId()); work_space->SetTempFrameData(temp_frame); sb_direction->SetState(temp_frame.direction); Frame previous = frames_compute.GetFrame(frames_compute.GetFrameId() - 1); work_space->SetPreviousFrameBmp(previous); // 设置按钮状态 b_add_point->SetState(IS_LOCK); b_previous_frame->SetState(0); b_next_frame->SetState(0); //b_alter->SetState(0); b_delete->SetState(0); b_insert->SetState(0); b_play->SetState(0); b_play_rectangle->SetState(0); b_file_out->SetState(0); } break; case CB_ADD_POINT: // 添加顶点 { // workspace状态转换失败W if(work_space->SetState(WORK_STATE_ADD_FIND) == false) { ////////////////////////////////////////////////////////////////////////// // 提示用户操作失败 ////////////////////////////////////////////////////////////////////////// MessageBox(hwnd_, "workspace无法转换状态。", "错误!", NULL); b_add_point->SetState(0); break; } int length = nb_length->GetNumber(); if(work_space->SetLength(length) == false) { ////////////////////////////////////////////////////////////////////////// // 提示用户长度不符合要求,并提示范围 ////////////////////////////////////////////////////////////////////////// char message[200]; sprintf(message, "长度不符合要求[%d~%d]\n", MIN_LENGTH, MAX_LENGTH); MessageBox(hwnd_, message, "错误!", NULL); break; } // 按钮状态保存 } break; case CB_SVAE_KEY_FRAME: // 保存为关键帧 { // workspace状态转换失败 if(work_space->SetState(WORK_STATE_MOVE_FIND) == false){ MessageBox(hwnd_, "workspace无法转换状态。", "错误!", NULL); b_save_key->SetState(0); } Frame temp_frame = work_space->GetTempFrame(); temp_frame.direction = sb_direction->GetState(); if (frames_compute.SaveFrame(temp_frame) == false) { MessageBox(hwnd_, "无法保存关键帧。", "错误!", NULL); b_save_key->SetState(0); break; } MessageBox(hwnd_, "保存关键帧成功。", "成功!", NULL); b_delete->SetState(0); b_insert->SetState(0); b_play->SetState(0); b_file_out->SetState(0); b_next_frame->SetState(0); b_previous_frame->SetState(0); b_play_rectangle->SetState(0); work_space->SetPreviousFrameBmp( frames_compute.GetFrame(frames_compute.GetFrameId() - 1)); } break; case CB_PREVIOUS_FRMAE: // 上一帧 { if(work_space->SetState(WORK_STATE_MOVE_FIND) == false) { ////////////////////////////////////////////////////////////////////////// // 提示用户操作失败 ////////////////////////////////////////////////////////////////////////// MessageBox(hwnd_, "workspace无法转换状态。", "错误!", NULL); b_previous_frame->SetState(0); break; } Frame temp_frame = frames_compute.PreviousFrame(); if(temp_frame.number <= 0) { ////////////////////////////////////////////////////////////////////////// // 提示用户,已经是第一张关键帧 ////////////////////////////////////////////////////////////////////////// MessageBox(hwnd_, "已经是第一张关键帧。", "错误!", NULL); b_previous_frame->SetState(0); break; } work_space->SetTempFrameData(temp_frame); sb_direction->SetState(temp_frame.direction); work_space->SetPreviousFrameBmp( frames_compute.GetFrame(frames_compute.GetFrameId() - 1)); //b_alter->SetState(0); b_delete->SetState(0); b_insert->SetState(0); } break; case CB_NEXT_FRAME: // 下一帧 { if(work_space->SetState(WORK_STATE_MOVE_FIND) == false) { ////////////////////////////////////////////////////////////////////////// // 提示用户操作失败 ////////////////////////////////////////////////////////////////////////// MessageBox(hwnd_, "workspace无法转换状态。", "错误!", NULL); b_next_frame->SetState(0); break; } Frame temp_frame = frames_compute.NextFrame(); if(temp_frame.number <= 0) { ////////////////////////////////////////////////////////////////////////// // 提示用户,已经是最后一关键帧 ////////////////////////////////////////////////////////////////////////// MessageBox(hwnd_, "已经是最后一关键帧", "错误!", NULL); b_next_frame->SetState(IS_LOCK); break; } work_space->SetTempFrameData(temp_frame); sb_direction->SetState(temp_frame.direction); work_space->SetPreviousFrameBmp( frames_compute.GetFrame(frames_compute.GetFrameId() - 1)); // b_alter->SetState(0); b_delete->SetState(0); b_insert->SetState(0); } break; case CB_DELETE: // 删除 { if (frames_compute.DeleteFrame() == false) { MessageBox(hwnd_, "删除关键帧失败!", "错误!", NULL); } else { MessageBox(hwnd_, "删除关键帧成功!", "操作成功!", NULL); // b_alter->SetState(IS_LOCK); Frame temp_frame = frames_compute.GetFrame(frames_compute.GetFrameId()); work_space->SetTempFrameData(temp_frame); sb_direction->SetState(temp_frame.direction); work_space->SetPreviousFrameBmp(frames_compute.GetFrame(frames_compute.GetFrameId() - 1)); } b_delete->SetState(0); if (frames_compute.GetFramesNumber() == 1) { b_play->SetState(IS_LOCK); b_play_rectangle->SetState(IS_LOCK); } } break; case CB_INSERT: // 插入 { Frame temp_frame, previous_frame; temp_frame = work_space->GetTempFrame(); temp_frame.direction = sb_direction->GetState(); if (frames_compute.InsertFrame(temp_frame) == false) { MessageBox(hwnd_, "插入关键帧失败!", "错误!", NULL); } else { MessageBox(hwnd_, "插入关键帧成功!", "操作成功!", NULL); } // 设置按钮状态 b_add_point->SetState(IS_LOCK); b_next_frame->SetState(0); b_delete->SetState(0); b_insert->SetState(0); b_play->SetState(0); b_play_rectangle->SetState(0); b_file_out->SetState(0); } break; case CB_PLAY: // 演示 { int frame_number = 0; Frame* temp_frames_string = frames_compute.GetInterpolationFrames(&frame_number); if (temp_frames_string == NULL) { ////////////////////////////////////////////////////////////////////////// // 提示用户获取帧序列操作失败 ////////////////////////////////////////////////////////////////////////// MessageBox(hwnd_, "取帧序列操作失败", "错误!", NULL); b_play->SetState(0); break; } work_space->SetPlay(frame_number, temp_frames_string); if(work_space->SetState(WORK_STATE_PLAY_ACTION) == false) { ////////////////////////////////////////////////////////////////////////// // 提示用户操作失败 ////////////////////////////////////////////////////////////////////////// MessageBox(hwnd_, "workspace无法转换状态。", "错误!", NULL); b_play->SetState(0); break; } } break; case CB_PALY_RECTANGLE: // 矩阵演示 { vector< vector<VERTEX> > v = frames_compute.GetRectangleString(); if (v.empty()) { ////////////////////////////////////////////////////////////////////////// // 提示用户获取帧序列操作失败 ///////////////////////////////s/////////////////////////////////////////// MessageBox(hwnd_, "取帧序列操作失败", "错误!", NULL); b_play->SetState(WORK_STATE_MOVE_FIND); break; } work_space->SetVertex(v); if(work_space->SetState(WORK_STATE_DRAW_RECTANGLE) == false) { ////////////////////////////////////////////////////////////////////////// // 提示用户操作失败 ////////////////////////////////////////////////////////////////////////// MessageBox(hwnd_, "workspace无法转换状态。", "错误!", NULL); b_play->SetState(0); break; } } break; case CB_FILE_OUT: // 输出 { if (frames_compute.SaveFile() == false) { ////////////////////////////////////////////////////////////////////////// // 提示用户保存失败 ////////////////////////////////////////////////////////////////////////// MessageBox(hwnd_, "文件保存失败", "错误!", NULL); break; } MessageBox(hwnd_, "文件输出成功", "成功!", NULL); } break; default: break; } } void WindowsClass::Event(MSG msg) { int x = LOWORD(msg.lParam); int y = HIWORD(msg.lParam); UINT message = msg.message; short zDelta = (short) HIWORD(msg.wParam); // wheel rotation LPARAM lparam; UIObject * ui_object = NULL; // 寻找鼠标下的控件 ui_object = CheckObjectWhenMouseAction(x, y); // 处理 switch(message) { case WM_KEYDOWN: switch (WM_CHAR) { default: break; } work_space->SetState(WORK_STATE_MOVE_FIND); break; case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: { if(ui_object != NULL) { focus_ui_object = ui_object; lparam = MAKELONG(x - focus_ui_object->GetPostionRect().left, y - focus_ui_object->GetPostionRect().top); MSG t_msg = msg; t_msg.lParam = lparam; focus_ui_object->Event(t_msg); { // 对于按钮的响应处理 int object_id = focus_ui_object->GetUIID(); CJButton *p = (CJButton*)focus_ui_object; if(object_id != 0 && object_id != CB_LENGHT && p->GetState() == true) { OrderControl(object_id); } } } } break; case WM_LBUTTONUP: case WM_RBUTTONUP: if (focus_ui_object != NULL) { lparam = MAKELONG(x - focus_ui_object->GetPostionRect().left, y - focus_ui_object->GetPostionRect().top); MSG t_msg = msg; t_msg.lParam = lparam; focus_ui_object->Event(t_msg); focus_ui_object = NULL; } break; default: // 如果存在焦点控件,则把信息传递给焦点控件 if (focus_ui_object != NULL) { lparam = MAKELONG(x - focus_ui_object->GetPostionRect().left, y - focus_ui_object->GetPostionRect().top); MSG t_msg = msg; t_msg.lParam = lparam; focus_ui_object->Event(t_msg); } else if(ui_object != NULL){ lparam = MAKELONG(x - ui_object->GetPostionRect().left, y - ui_object->GetPostionRect().top); MSG t_msg = msg; t_msg.lParam = lparam; ui_object->Event(t_msg); } break; } } void WindowsClass::MouseKeyEvent (int x, int y, UINT message){ UIObject * ui_object = NULL; // 寻找鼠标下的控件 ui_object = CheckObjectWhenMouseAction(x, y); // 处理 switch(message) { case WM_KEYDOWN: switch (WM_CHAR) { default: break; } work_space->SetState(WORK_STATE_MOVE_FIND); break; case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: { if(ui_object != NULL) { focus_ui_object = ui_object; focus_ui_object->MouseKeyEvent(x - focus_ui_object->GetPostionRect().left, y - focus_ui_object->GetPostionRect().top, message); { // 对于按钮的响应处理 int object_id = focus_ui_object->GetUIID(); CJButton *p = (CJButton*)focus_ui_object; if(object_id != 0 && object_id != CB_LENGHT && p->GetState() == true) { OrderControl(object_id); } } } } break; case WM_LBUTTONUP: case WM_RBUTTONUP: if (focus_ui_object != NULL) { focus_ui_object->MouseKeyEvent(x - focus_ui_object->GetPostionRect().left, y - focus_ui_object->GetPostionRect().top, message); focus_ui_object = NULL; } break; default: // 如果存在焦点控件,则把信息传递给焦点控件 if (focus_ui_object != NULL) { focus_ui_object->MouseKeyEvent(x - focus_ui_object->GetPostionRect().left, y - focus_ui_object->GetPostionRect().top, message); } else if(ui_object != NULL){ ui_object->MouseKeyEvent(x - ui_object->GetPostionRect().left, y - ui_object->GetPostionRect().top, message); } break; } } void WindowsClass::Draw ( HDC target_hdc ){ //清屏(使用背景图片或用一个灰色刷子重新刷一下窗口) RECT rect = {0, 0, position_rect_.right, position_rect_.bottom}; if (bk_bitmap != NULL) { FillRect(hdc_, &position_rect_, (HBRUSH)GetStockObject(GRAY_BRUSH)); bk_bitmap->Draw(hdc_, 0, 0); } else { FillRect(hdc_, &position_rect_, (HBRUSH)GetStockObject(GRAY_BRUSH)); } // 更新workspace的状态信息 char str[1000]; sprintf(str, "WorkSpace状态:%s\n", work_space->GetState().c_str()); workspace_info->SetString(str); // 更新compute的信息 sprintf(str, "Compute信息:\n文件名:%s\n关键帧的总数:%d 当前的帧序号:%d\n", frames_compute.GetFileName(), frames_compute.GetFramesNumber(), frames_compute.GetFrameId() + 1); compute_info->SetString(str); //绘制对象在离屏 DrawObject(hdc_); //复制到目标设备 BitBlt(target_hdc, 0, 0, rect.right, rect.bottom, hdc_, 0, 0, SRCCOPY); return ; } void WindowsClass::Initialization ( HDC source_dc , HINSTANCE hInstance, HWND hwnd) { hInstance_ = hInstance; hwnd_ = hwnd; char str[100]; RECT rectPointButton1 = {600, 20, 690, 70}; LoadString(hInstance, IDS_STR_NEW_FILE, str, 100); b_new_file = new CJButton (source_dc, str, rectPointButton1, CB_NEW_FILE); AddUIObject(b_new_file); RECT rectPointButton2 = {700, 20, 790, 70}; LoadString(hInstance, IDS_STR_OPEN_FILE, str, 100); b_open_file = new CJButton (source_dc, str, rectPointButton2, CB_OPEN_FILE); AddUIObject(b_open_file); RECT rectPointButton3 = {600, 90, 690, 140}; LoadString(hInstance, IDS_STR_ADD_POINT, str, 100); b_add_point = new CJButton (source_dc, str, rectPointButton3, CB_ADD_POINT); AddUIObject(b_add_point); RECT rectPointButton14 = {700, 90, 790, 140}; LoadString(hInstance, IDS_STR_SVAE_KEY_FRAME, str, 100); b_save_key = new CJButton (source_dc, str, rectPointButton14, CB_SVAE_KEY_FRAME); AddUIObject(b_save_key); RECT rectPointButton4 = {600, 160, 790, 210}; LoadString(hInstance, IDS_STR_LENGTH, str, 100); nb_length = new NumButton (source_dc, str,rectPointButton4, CB_LENGHT); AddUIObject(nb_length); RECT rectPointButton7 = {600, 230, 690, 280}; LoadString(hInstance, IDS_STR_PREVIOUS_FRMAE, str, 100); b_previous_frame = new CJButton (source_dc, str, rectPointButton7, CB_PREVIOUS_FRMAE); AddUIObject(b_previous_frame); RECT rectPointButton8 = {700, 230, 790, 280}; LoadString(hInstance, IDS_STR_NEXT_FRAME, str, 100); b_next_frame = new CJButton (source_dc, str, rectPointButton8, CB_NEXT_FRAME); AddUIObject(b_next_frame); RECT rectPointButton9 = {600, 300, 650, 350}; vector<string> v_str; LoadString(hInstance, IDS_STR_DIRECTION_lEFT, str, 100); v_str.push_back(str); LoadString(hInstance, IDS_STR_DIRECTION_RIGHT, str, 100); v_str.push_back(str); sb_direction = new JStateButton (source_dc, rectPointButton9, SB_DIRECTION); sb_direction->InitState(v_str); AddUIObject(sb_direction); RECT rectPointButton10 = {660, 300, 720, 350}; LoadString(hInstance, IDS_STR_DELETE, str, 100); b_delete = new CJButton (source_dc, str, rectPointButton10, CB_DELETE); AddUIObject(b_delete); RECT rectPointButton11 = {730, 300, 790, 350}; LoadString(hInstance, IDS_STR_INSERT, str, 100); b_insert = new CJButton (source_dc, str, rectPointButton11, CB_INSERT); AddUIObject(b_insert); RECT rectPointButton12 = {600, 370, 790, 420}; LoadString(hInstance, IDS_STR_PLAY, str, 100); b_play= new CJButton (source_dc, str, rectPointButton12, CB_PLAY); AddUIObject(b_play); RECT rectPointButton13 = {600, 440, 790, 490}; LoadString(hInstance, IDS_STR_FILE_OUT, str, 100); b_file_out= new CJButton (source_dc, str, rectPointButton13, CB_FILE_OUT); AddUIObject(b_file_out); RECT play_rectangle_rect = {600, 510, 790, 560}; LoadString(hInstance, IDS_STR_PALY_RECTANGLE, str, 100); b_play_rectangle = new CJButton(source_dc, str, play_rectangle_rect, CB_PALY_RECTANGLE); AddUIObject(b_play_rectangle); RECT work_rect = {50,50,550,550}; work_space = new WorkSpace(source_dc, work_rect); Frame temp_frome = frames_compute.GetFrame(frames_compute.GetFrameId()); work_space->SetTempFrameData(temp_frome); sb_direction->SetState(temp_frome.direction); AddUIObject(work_space); work_space->SetTempFrameData(frames_compute.GetFrame(frames_compute.GetFrameId())); RECT workspace_info_rect = {0, 0, 300, 50}; workspace_info = new TextBox(source_dc, NULL, workspace_info_rect, 0); AddUIObject(workspace_info); RECT compute_info_rect = {0, 550, 550, 600}; compute_info = new TextBox(source_dc, NULL, compute_info_rect, 0); AddUIObject(compute_info); b_previous_frame->SetState(IS_LOCK); b_next_frame->SetState(IS_LOCK); b_delete->SetState(IS_LOCK); b_insert->SetState(IS_LOCK); b_play->SetState(IS_LOCK); b_play_rectangle->SetState(IS_LOCK); b_file_out->SetState(IS_LOCK); }
4edf62e1453569134f1795e58da35d3655cde4b4
0a688a8b2c973962f45b07d3f3b50acab40c4e8f
/LeetCode/332. Reconstruct Itinerary.cpp
882bd12ba0b81a5315b917de86a487c9404e783e
[]
no_license
Rajanpandey/Coding-Practice
2184c1b0ff8b10847abfe2f36091a7239aca2671
75d81fdf581fe870dac45c59ba3d20a406e2f4b8
refs/heads/master
2021-11-28T08:07:12.859609
2021-11-24T15:45:01
2021-11-24T15:45:01
191,540,122
3
1
null
null
null
null
UTF-8
C++
false
false
987
cpp
332. Reconstruct Itinerary.cpp
// Hierholzer's Algorithm to find Eulers's Path class Solution { public: void DFS(string source, map<string, priority_queue<string, vector<string>, greater<string>>>& adjList, vector<string>& ans) { while (!adjList[source].empty()) { string destination = adjList[source].top(); adjList[source].pop(); DFS(destination, adjList, ans); } ans.push_back(source); } vector<string> findItinerary(vector<vector<string>>& tickets) { vector<string> ans; map<string, priority_queue<string, vector<string>, greater<string>>> adjList; for (auto ticket : tickets) { adjList[ticket[0]].push(ticket[1]); } DFS("JFK", adjList, ans); reverse(ans.begin(), ans.end()); return ans; } }; // For an Eulerian path, at most 1 vertx has outdegree-indegree=1 // and at most 1 vertex has indegree-outfegdree=1. // All other vertices have equal in and out degree!
8abe2e66bbb12f4485853cdc24b97755252da159
0e3cab0ba4802bf611323fb121e9d149bc121b5f
/Solutions/CHEFELEC4.cpp
3f659f8032fd26923b5c6f2d1f24ec396be63803
[ "MIT" ]
permissive
nikramakrishnan/codechef-solutions
e8ba0bf4def856ef0f46807726b46c72eececea9
f7ab2199660275e972a387541ecfc24fd358e03e
refs/heads/master
2020-06-01T23:13:27.072740
2017-06-16T08:10:38
2017-06-16T08:10:38
94,087,034
2
0
null
null
null
null
UTF-8
C++
false
false
1,075
cpp
CHEFELEC4.cpp
#include<iostream> using namespace std; int main(){ int t,n,first,second; string s; cin>>t; while(t--){ cin>>n; long long int x[n]; long long int totalc=0; cin>>s; for(int i=0;i<n;i++){ cin>>x[i]; } int j=0; //This will be the pos of first 1; if(s[0]=='0'){ //cout<<"Counting distance of 0s before first 1"<<endl; while(s[j]!='1') j++; totalc+=x[j]-x[0]; //cout<<"Distance of 0s before first 1="<<totalc<<endl; } first=j; second=j+1; while(second<n-1){ //cout<<"LOOP NUM 1"<<endl; while(s[second]!='1' && second<n) second++; //cout<<"Second="<<second<<endl; if(s[second]=='1'){ //cout<<"Entered IF"<<endl; while(x[j+1]-x[first]<=x[second]-x[j+1] && j<second) j++; //cout<<"Breakpos="<<j<<endl; totalc+=x[j]-x[first]; totalc+=x[second]-x[j+1]; first=second; } else break; second++; } //cout<<"First="<<first<<"\nSecond="<<second<<endl; if(s[n-1]=='0') totalc+=x[n-1]-x[first]; cout<<totalc<<endl; } }
2e607a671b8fc429027fdd5eb136729d03d1a29c
5885fd1418db54cc4b699c809cd44e625f7e23fc
/ucla-codesprint-2022/team/f.cpp
0f6427e4b86cf4ec0411ca39c948ee7154f21dbc
[]
no_license
ehnryx/acm
c5f294a2e287a6d7003c61ee134696b2a11e9f3b
c706120236a3e55ba2aea10fb5c3daa5c1055118
refs/heads/master
2023-08-31T13:19:49.707328
2023-08-29T01:49:32
2023-08-29T01:49:32
131,941,068
2
0
null
null
null
null
UTF-8
C++
false
false
891
cpp
f.cpp
#include <bits/stdc++.h> using namespace std; //%:include "utility/fast_input.h" //%:include "utility/output.h" %:include "graph/dinic.h" using ll = long long; using ld = long double; using pt = complex<ld>; constexpr char nl = '\n'; constexpr int MOD = 998244353; constexpr ld EPS = 1e-9L; random_device _rd; mt19937 rng(_rd()); int main() { cin.tie(0)->sync_with_stdio(0); cout << fixed << setprecision(10); #ifdef USING_FAST_INPUT fast_input cin; #endif int n, m; cin >> n >> m; dinic<int> g(2*m + 2); const int source = 2*m; const int sink = source + 1; set<pair<int, int>> have; for(int i=0; i<n; i++) { int x, y; cin >> x >> y; if(have.insert(pair(x, y)).second) { g.add_edge(x, m + y); } } for(int i=0; i<m; i++) { g.add_edge(source, i); g.add_edge(m + i, sink); } cout << g.flow(source, sink) << nl; return 0; }
d33c9c5e4c8b00ad8c827bcaf8aa86ee4dc61b1f
cc946931436d89e95d312327ba50cf7d0104a0d2
/game/engine/widgets/Widget.cpp
81291512d607acb142730ac85256c5ed6721c1e6
[]
no_license
groepF/game
a42eb063825e73451511a86c18820a2ddc7ebb89
d285098d6ff47924ca97334282bf40555c0be12c
refs/heads/develop
2021-01-11T00:49:48.844678
2017-01-17T01:27:13
2017-01-17T01:27:13
70,483,312
6
0
null
2017-01-17T12:08:32
2016-10-10T11:56:06
C++
UTF-8
C++
false
false
151
cpp
Widget.cpp
#include "Widget.h" Widget::Widget() { } std::string Widget::getId() const { return id; } void Widget::setId(std::string id) { this->id = id; }
5c8a91d444c0b564c0ad9fe88d6e28fa6824b851
30d565ab1a62eca47a03f207af180104482853db
/Nodes/BasicNodes/createmesh.cpp
77530bb2274fcf64e338b319b1e9daaef6407490
[]
no_license
YAXo-O/PEW
e7e811c498b9ac9d76f386a7c95eb0c2dc1d7aeb
92756a915ad54c28bcca60e8748eafb6cadc4743
refs/heads/master
2019-06-29T03:06:43.422383
2018-05-29T21:46:40
2018-05-29T21:46:40
101,887,095
0
0
null
2017-11-04T18:56:52
2017-08-30T13:49:18
null
UTF-8
C++
false
false
1,172
cpp
createmesh.cpp
#include "createmesh.h" #include "../externalvariablefactory.h" #include "../Data/wireframemeshinstancedata.h" #include "../../worldinfo.h" #include "../NodesWidgets/createmeshwidget.h" CreateMesh::CreateMesh(QString nodeName, QWidget *parent): BaseNode(nodeName, parent), wid(new CreateMeshParamsContainer(new CreateMeshWidget)) { mesh = ExternalVariableFactory::createExternal(WireframeMeshInstanceData::dataType_s(), "WireframeMeshInstance", DFF_WRITE); addDataPin(mesh->getPin()); rearangePins(); appendParamsWidget(wid->getParamsPanel()); } void CreateMesh::enable(BaseNode *caller) { if(!mesh->isDataPresent() && mesh->isConnected()) { WorldInfo &info = WorldInfo::getInstance(); QString name = *((QString *)wid->getValue()); WireframeMesh *m = info.meshManager().getMesh(name); WireframeMeshInstance *instance = new WireframeMeshInstance(m); Material *mat = info.getDefaultMaterial(); instance->changeMaterial(mat); mesh->setValue(instance); info.registerObject(instance); } BaseNode::enable(caller); }
99b4b53f9c76700703e8befe00f17cd1d77767dc
2dad597ecec01408675867cadf3bbfd6ddfdfbc1
/Preparing for test/template_stack.cpp
9b351125f8d3d74e14870f054c1bce970c7db14b
[]
no_license
AroSwift/CS1020
76202c83ca9081e5e0736351e02a2415e9977ca7
1b2f3f7bf2267c4cfb1a6eb2f4d4a3eae6fcbb04
refs/heads/master
2021-05-02T11:01:43.188974
2018-09-28T18:50:08
2018-09-28T18:50:08
50,745,648
0
0
null
null
null
null
UTF-8
C++
false
false
502
cpp
template_stack.cpp
const int MAX_DATA = 100; temtemplate <class T> class STack { T data[MAX_DATA]; int top; public: Stack(); void push(T d); T pop(); bool is_empty(); }; Stack::Stack() { top = -1; } template<class T> void Stack::push(T d) { if( top == MAX_DATA ) return; data[++top] = d; } template<class T> T Stack::pop() { if( is_empty() ) return; T temp_data = data[top--]; delete data; return temp_data; } template<class T> bool Stack::is_empty() { return(top == -1) ? true : false; }
dde23bcbf130e37c45ec8a050080186b658d1a78
abd16947bf4f91af9d096d55a0067179f75b6718
/414b.cpp
5180e3f1911bf1e40a54a56e648f2db664b309c5
[]
no_license
05Khushboo/Codeforces
69522864f3f5daf4e77066c78fb27fbe21b60570
8b16f65f51a110f2f1efa592d9d3f1dbb778c8d7
refs/heads/master
2021-01-19T16:42:09.403754
2017-08-22T21:37:30
2017-08-22T21:38:11
88,280,481
1
1
null
2017-11-03T20:08:48
2017-04-14T15:40:48
C++
UTF-8
C++
false
false
523
cpp
414b.cpp
#include<bits/stdc++.h> using namespace std; #define ll long long int ll dp[2002][2002]; int main() { ll n,k; cin>>n>>k; ll mod = 1E9 + 7; for(ll i = 0;i<=k;i++) { for(ll j=0;j<=n;j++) { dp[i][j] =0; if(i==1) dp[i][j] = 1; } } for(ll ik=1;ik<=k;ik++) { for(ll i = 1;i<=n;i++) { for(ll j =i;j<=n;j+=i) { if(ik!=1) dp[ik][j]+=dp[ik-1][i]; dp[ik][j]%=mod; } } } ll ans =0; for(ll i = 1;i<=n;i++) ans+=dp[k][i],ans%=mod; cout<<ans; return 0; }
e87ece3af101d92bcd424a3808e9ee9638512c80
95f86a8f769d480494e1a70ea5efdf2262b30ff5
/templateArray.cpp
930bb878e696594683460c8c35f276632d535d1d
[]
no_license
aorji/CPP_Training
46dddd6c3891471c828dadafca4016f1c0b4354c
a30a9f6c2f2520654c27031db5d66187eda405f0
refs/heads/master
2020-04-08T20:42:06.153969
2018-11-29T19:09:51
2018-11-29T19:09:51
159,711,347
1
0
null
null
null
null
UTF-8
C++
false
false
1,309
cpp
templateArray.cpp
/* Реализуйте шаблонную версию класса Array. Список всех операций, которые должен поддерживать класс Array, приведен в шаблоне кода. */ #include <cstddef> template <typename T> class Array { // Список операций: // public: explicit Array(size_t size = 0, const T& value = T()):size_(size), value_(new T[size]){ for(size_t i = 0; i < size; ++i){ value_[i] = value; } } Array(const Array & rhs):size_(rhs.size()), value_(new T[rhs.size()]){ for(size_t i = 0; i < size_; ++i){ value_[i] = rhs.value_[i]; } } ~Array(){ delete [] value_; } Array& operator=(Array const & rhs){ if (this != &rhs){ delete [] value_; size_ = rhs.size(); value_ = new T[rhs.size()]; for(size_t i = 0; i < size_; ++i){ value_[i] = rhs.value_[i]; } } return *this; } size_t size() const {return size_;} T * value() const { return value_; } T& operator[](size_t i){ return value_[i]; } const T& operator[](size_t i) const { return value_[i]; } private: size_t size_; T *value_; };
f22a6b7ffaab01d9010dff8feca94e2cbad4aa89
d4f9f10df1b7718ea4083fc7da6e1214372769f0
/SpectrometerPackage/KromekDriver/include/Lock.h
4e1f92fb520d421c34bee757d7b414660256fe3d
[]
no_license
rustam-lantern/LanternSpectrometer
7f04f31824fcbe59dfadac84f101dfef5612c413
93e3733fc2da2f80df6b76c1064bfec317331b76
refs/heads/master
2020-07-31T11:37:23.591981
2019-09-24T13:27:16
2019-09-24T13:27:16
210,591,863
0
0
null
null
null
null
UTF-8
C++
false
false
564
h
Lock.h
#pragma once #include "CriticalSection.h" namespace kmk { /** @brief A synchronisation mechanism using critical sections. Example: // declare critical section as class attribute somewhere... CriticalSection csObject; void MyClass::ProtectedFunction () { Lock protect (csObject); // work on data... // destructor releases at end of scope or on exception. } */ class Lock { public: Lock (CriticalSection &cs); ~Lock (); private: CriticalSection &m_cs; }; } // namespace kmk
34efbb359e96d61809ec56f0ea2592969bc2802f
6e1fb1b65eb53f973363c33bb5614d3d6e976df2
/string/char_arr3.cpp
0a4769dbf3e729be889bdf143f8bd6f1c60c5fbb
[]
no_license
tranleduy2000/learncpp_
abae6c758232dc4671a337638c0359fe13bae27c
86f1c91fcd9797b38857cb79b454d9314712266d
refs/heads/master
2021-05-08T10:35:47.233918
2018-02-15T09:32:53
2018-02-15T09:32:53
119,848,322
1
0
null
null
null
null
UTF-8
C++
false
false
208
cpp
char_arr3.cpp
#include <iostream> #include <cstring> using namespace std; int main() { char foo[] = "Almost every programmer should know memset!"; cout << foo << endl; memset(foo, '-', 10); cout << foo; return 0; }
29eb50a7784f22cf61030bca008b4147aaa95ca3
c51d7d3d453ad1e831e625cc3a0ac1df67fc1e93
/2.2-linkedLists.cpp
ce2f893e96827c40703626c611c9d93f65bfdb77
[]
no_license
schliffen/cracking-the-coding-interview
3553ed8b3e3458cd9a40b48365beb28dba327d9d
4fa5dead78c526731069ee972777c97c3f9a92ac
refs/heads/master
2021-06-13T23:21:10.600481
2019-10-06T13:40:50
2019-10-06T13:40:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
772
cpp
2.2-linkedLists.cpp
#include "lib/LinkedList.h" #include <assert.h> #include <iostream> /* * 2.2 * Implement an algorithm to find the kth to * last element of a singly linked list. */ Node<int>* find_k_from_end(Node<int>* head, int k) { int num_covered = 0; Node<int>* current = head; Node<int>* desired = head; while (current->m_pNext) { num_covered++; if (num_covered >= k) { desired = desired->m_pNext; } current = current->m_pNext; } if (num_covered >= k) return desired; return 0; } void test2_2() { int data[] = {0, 1, 2, 3, 4, 5, 6, 7}; Node<int> head(data, 8); Node<int>* kth = find_k_from_end(&head, 2); assert(kth->m_data == 6); std::cout << "2.2 passed" << std::endl; }
d55955457304f957749f2e1847f5faf299bf61ac
ef15a4a77b6e1fbb3220a5047885ba7568a80b74
/src/triggersnortsam/Trigger/SnortSam/Exception.cpp
88d183633aba5571e9f54649f9467507713bcfc3
[]
no_license
el-bart/ACARM-ng
22ad5a40dc90a2239206f18dacbd4329ff8377de
de277af4b1c54e52ad96cbe4e1f574bae01b507d
refs/heads/master
2020-12-27T09:24:14.591095
2014-01-28T19:24:34
2014-01-28T19:24:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
42
cpp
Exception.cpp
#include "Trigger/SnortSam/Exception.hpp"
b35bc13c1477d3bbe3aed916217fb7eb44acd3d6
0bf8cdde9562a400fe1604237a658fae5a170982
/ext/openMVG/dependencies/osi_clp/CoinUtils/src/CoinPresolveDual.hpp
b021ce0c1da45fa4035de25ecda1a03858232f8c
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "EPL-1.0" ]
permissive
AIBluefisher/EGSfM
64c2108c037a7e730a81690598022586d6ae90aa
e2e505353cdc525b8e814e0019bd0dc67be75fea
refs/heads/master
2021-06-19T02:06:22.904219
2021-02-28T03:11:14
2021-02-28T03:11:14
187,424,684
91
19
BSD-3-Clause
2020-03-03T07:33:47
2019-05-19T02:20:18
C++
UTF-8
C++
false
false
2,846
hpp
CoinPresolveDual.hpp
/* $Id: CoinPresolveDual.hpp 1510 2011-12-08 23:56:01Z lou $ */ // Copyright (C) 2002, International Business Machines // Corporation and others. All Rights Reserved. // This code is licensed under the terms of the Eclipse Public License (EPL). #ifndef CoinPresolveDual_H #define CoinPresolveDual_H /*! \class remove_dual_action \brief Attempt to fix variables by bounding reduced costs The reduced cost of x_j is d_j = c_j - y*a_j (1). Assume minimization, so that at optimality d_j >= 0 for x_j nonbasic at lower bound, and d_j <= 0 for x_j nonbasic at upper bound. For a slack variable s_i, c_(n+i) = 0 and a_(n+i) is a unit vector, hence d_(n+i) = -y_i. If s_i has a finite lower bound and no upper bound, we must have y_i <= 0 at optimality. Similarly, if s_i has no lower bound and a finite upper bound, we must have y_i >= 0. For a singleton variable x_j, d_j = c_j - y_i*a_ij. Given x_j with a single finite bound, we can bound d_j greater or less than 0 at optimality, and that allows us to calculate an upper or lower bound on y_i (depending on the bound on d_j and the sign of a_ij). Now we have bounds on some subset of the y_i, and we can use these to calculate upper and lower bounds on the d_j, using bound propagation on (1). If we can manage to bound some d_j as strictly positive or strictly negative, then at optimality the corresponding variable must be nonbasic at its lower or upper bound, respectively. If the required bound is lacking, the problem is unbounded. */ class remove_dual_action : public CoinPresolveAction { public: /// Destructor ~remove_dual_action () ; /// Name inline const char *name () const { return ("remove_dual_action") ; } /*! \brief Attempt to fix variables by bounding reduced costs Always scans all variables. Propagates bounds on reduced costs until there's no change or until some set of variables can be fixed. */ static const CoinPresolveAction *presolve(CoinPresolveMatrix *prob, const CoinPresolveAction *next) ; /*! \brief Postsolve In addition to fixing variables (handled by make_fixed_action), we may need use our own postsolve to restore constraint bounds. */ void postsolve (CoinPostsolveMatrix *prob) const ; private: /// Postsolve (bound restore) instruction struct action { double rlo_ ; ///< restored row lower bound double rup_ ; ///< restored row upper bound int ndx_ ; ///< row index } ; /// Constructor with postsolve actions. remove_dual_action(int nactions, const action *actions, const CoinPresolveAction *next) : CoinPresolveAction(next), nactions_(nactions), actions_(actions) {} /// Count of bound restore entries const int nactions_ ; /// Bound restore entries const action *actions_ ; } ; #endif
bf743ae98fada7633aaf1810888341b3b8d3c652
f871e593a589958f45d930d4dbf8f182a03709e8
/ShaGang/view/Frame.cpp
593c89c0de626c722a13306aafba04d9e2706058
[]
no_license
Leroy888/ShaGang
7dac80411861c2d13c11085ad48a3016f86063e2
cd1bcbd0383d465eafd25a080b995628508ed7c0
refs/heads/master
2023-09-05T07:33:15.379500
2021-11-19T09:44:54
2021-11-19T09:44:54
258,710,360
0
0
null
null
null
null
UTF-8
C++
false
false
54
cpp
Frame.cpp
#include "Frame.h" Frame::Frame(QFrame *parent) { }
78073b1261192785af3a876c24edffdb2c9aa25d
6ec96ccaed2fd3805c009faa982e0c0d565a9f57
/DcMotorLib.h
371e86cd7ca1beb56cd8aef71d2da82f2a5526d8
[]
no_license
ugurgudelek/Kinetic-Sculpture
df293dea5d7e50f8c524b9979f530fa368ade4fb
dede43ca21de9f5ded7f58ca7e8f9de001e1401d
refs/heads/master
2020-05-25T14:22:27.953838
2017-03-14T11:07:11
2017-03-14T11:07:11
84,939,169
0
0
null
null
null
null
UTF-8
C++
false
false
3,954
h
DcMotorLib.h
/* Name: DcMotorLib.h Created: 11/3/2015 3:21:02 PM Author: Ugur Gudelek Editor: http://www.visualmicro.com */ #ifndef _DcMotorLib_h #define _DcMotorLib_h #if defined(ARDUINO) && ARDUINO >= 100 #include "arduino.h" #else #include "WProgram.h" #endif #define PROBLEM_ON_START 1 #define PROBLEM_USER_DEFINED 2 #define PROBLEM_RUN_TILL_THE_END_SWITCH 3 #define PROBLEM_END_SWITCH_PUSHED 4 #define PROBLEM_ENCODER_MISSED 5 class DcMotorLib{ public: DcMotorLib(uint8_t cwPin, uint8_t ccwPin, uint8_t encoderPin, uint8_t motorEnablePin, uint8_t endSwitchPin); //CwPin : in1 , CcwPin : in2 uint8_t problemCode; typedef enum { DIRECTION_CCW = 1, ///< Counter-Clockwise DIRECTION_CW = 0 ///< Clockwise } Direction; typedef enum { NO_CHANGE_UP = 0, NO_CHANGE_DOWN, STALL, DECELERATION_QUICK_UP, ACCELERATION_UP, DECELERATION_UP, DECELERATION_QUICK_DOWN, ACCELERATION_DOWN, DECELERATION_DOWN, } Acceleration; void enableOutputs(); long distanceToGo(); long targetPosition(); long currentPosition(); float speed(); bool direction(); int encoderCounter(); long lastSavedPosition(); void setCurrentPosition(long position); void setMinSpeedUp(float speed); void setMinSpeedDown(float speed); void setMaxSpeed(float speed); void setStallSpeed(float speed); void setGoBaseSpeed(uint8_t speed); void setHoldSpeed(uint8_t speed); float minSpeedUp(); float minSpeedDown(); uint8_t goBaseSpeed(); Acceleration accelerationMode(); void move(long relative); void moveTo(long absolute); void run(); void stall(); void runToTheOutputs(); void encoderRead(); bool runTillEndSwitch(); void posCalibration(); void runEndlesslyWithoutAcceleration(uint8_t speed, Direction direction); void accelerationWithTime(); void computeAccelerationMode(); void setAcceleration(float step, unsigned long minToMax); void setAccelerationCoef(); void setAccelerationStep(float step); void setAccelerationMinToMaxTime(unsigned long minToMaxTime); void setEndSwithRespondTime(unsigned long time); void setMaxPos(long maxPos); void setQuickSlowDownDistanceDown(uint8_t distance); void setQuickSlowDownDistanceUp(uint8_t distance); void setQuickSlowDownSpeedDown(uint8_t speed); void setMinSpeedAfterEndSwitch(uint8_t speed); float getMinSpeedAfterEndSwitch(); bool isEnabled; bool isEndSwitchEnabled; uint8_t getPosAcceptanceMode(); void setPosAcceptanceMode(uint8_t posAcceptanceMode); void doNotLetMotorGoesInfinity(); void setSlipTime(unsigned long time); void setSlipDistance(uint8_t distance); void setEnableDoNotLetMotorGoesInfinity(bool value); void setTargetPosition(uint8_t distance); private: volatile int _currentPos; long _targetPos; float _speed; Direction _direction; float _maxSpeed; float _minSpeedUp; float _minSpeedDown; float _stallSpeed; uint8_t _goBaseSpeed; uint8_t _holdSpeed; float _accelerationWithTimeStep; uint8_t _ccwPin; uint8_t _cwPin; uint8_t _encoderPin; uint8_t _motorEnablePin; uint8_t _endSwitchPin; volatile int _encoderCounter; bool _encoderFlag; bool _encoderValue; bool _encoderOldValue; double _accelerationWithTimeTimer; bool _accelerateWithTimeFlag; Acceleration _accelerationMode; float _accelerationWithTimeCoef; unsigned long _accelerationWithTimePeriod; unsigned long _minToMaxTime; unsigned long _endSwithRespondTime; long _maxPos; uint8_t _quickSlowDownDistanceDown; uint8_t _quickSlowDownDistanceUp; uint8_t _quickSlowDownSpeedDown; float _minSpeedAfterEndSwitch; uint8_t _posAcceptanceMode; long _waitingTarget; double _slipTimer; unsigned long _slipTime; uint8_t _slipDistance; bool _enableDoNotLetMotorGoesInfinity; }; #endif
70dcf70f14fabc6a60df546e5448135d79551982
37456072056864466b9ab856e4a02a28e38b322c
/Zamiana.cpp
6cb8bf8ff8faad813f43992f69a9494cd9d3f76e
[]
no_license
mikolaj2002k02/Zamiana
3faf5824185fd09fd25b8a27435396957717468f
cf34930224fdd7d9bbea0cd46f2d78a9514563df
refs/heads/master
2023-01-01T04:32:28.067021
2020-10-22T12:46:40
2020-10-22T12:46:40
306,333,813
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
3,873
cpp
Zamiana.cpp
#include <iostream> #include <fstream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <bitset> using namespace std; long minimumZPliku(string nazwaPliku, int system) { long minimum; //otwórz plik źródłowy do zmiennej ifstream //wyszukaj minimum w pętli wczytując jw. tylko zamiast w main() tutaj //zamknij plik źródłowy return minimum; } int main(int argc, char** argv) { ifstream file; //plik wejsciowy ofstream fileOut; //plik wynikowy do zapisu char* endptr; // to jest wskaźnik na miejsce, gdzie przy konwersji z systemu czworkowego wystąpi błąd - nieużywana zmienna long liczba, liczba1, liczba2, min; //liczba dziesietna, minimum z pliku long minimum; long min1 = minimumZPliku("nazwa_pliku.txt", 2); //z pliku o tej nazwie system dwójkowy odczyta i minimum policzy long min2 = minimumZPliku("druga_nazwa.txt",8);//system 8 string liczba3, liczba4; //dwie liczby w systemie czworkowym wczytujemy jako "string" bo mogą być dłuższe od long long file.open("dane_systemy2.txt"); //otworz plik liczb fileOut.open("wyjscie1.txt"); //otworz plik do wynikow bool pierwszy = true; //do algorytmu MINIMUM - zakładamy, że pierwsza liczba jest najmniejsza z dotychczas przeczytanych if(file.good()) //sprawdzenie czy plik istnieje while(!file.eof()) //petla wykonuje sie az program dojedzie do konca pliku { file>>liczba3 >> liczba4; // wczyta dwie liczby z pliku (w wierszu) do 2 stringów liczba = strtol(liczba4.c_str(), &endptr, 2); liczba1 = strtol(liczba4.c_str(), &endptr, 4); liczba2 = strtol(liczba4.c_str(), &endptr, 8); //^konwersja z systemu czworkowego do dziesietnego, string (C++) trzeba zamienić na char * (C) funkcja .c_str() //zmienna endptr wskazuje na znak w stringu, który nie pasuje do systemu czwórkowego - tu niesprawdzone, bo zakładamy, że dane są poprawne! if(pierwszy) //jeśli to pierwsza liczba z pliku - będzie nowym MINIMUM { min = liczba; pierwszy = false; } else //jeśli to kolejna liczba z pliku... if(liczba < min) //... i jest mniejsza od dotychczasowego minimum... min = liczba; // ... to nadpisz min //////////////////////////////////////////////////////////////////////////////////////////////////////////////// if(pierwszy) //jeśli to pierwsza liczba z pliku - będzie nowym MINIMUM { min1 = liczba1; pierwszy = false; } else //jeśli to kolejna liczba z pliku... if(liczba1 < min1) //... i jest mniejsza od dotychczasowego minimum... min1 = liczba1; //////////////////////////////////////////////////////////////////////////////////////////////////////////// if(pierwszy) //jeśli to pierwsza liczba z pliku - będzie nowym MINIMUM { min2 = liczba2; pierwszy = false; } else //jeśli to kolejna liczba z pliku... if(liczba2 < min2) //... i jest mniejsza od dotychczasowego minimum... min2 = liczba2; }//eof() koniec pliku fileOut<< "Plik zerowy min: " << min <<endl; //zapisanie najmniejszej liczby z pliku czworkowego do pliku wynikowego fileOut << "Plik pierwszy min:" << min1 <<"\n"; fileOut << "Plik drugi min:" << min2 <<"\n"; file.close(); fileOut.close(); return 0; }
d73a31517a5f77e5942f6ebb2015ebbfef7a9939
31b94ff7ed6c481701f16de8e8feaf641bbc90d0
/master-firmware/src/arms/arm.cpp
706d88285446ce38a0655a8181ff9b03f0670d23
[]
no_license
robotics-seminar/robot-software
9364d867297a8d4f327cc4e7e514cc02883a7965
4e1842c598416eef8b5db7c86da5be6245eca09a
refs/heads/master
2020-03-19T04:49:00.600530
2018-06-02T19:11:12
2018-06-02T19:11:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,363
cpp
arm.cpp
#include "arm.h" ArmTrajectory::ArmTrajectory(scara_t* arm) : m_arm(arm), m_duration(0.) { scara_trajectory_init(&m_trajectory); } size_t ArmTrajectory::size() const { return m_trajectory.frame_count; } ArmTrajectoryFrame ArmTrajectory::frame(int index) const { return {m_trajectory.frames[index].position, m_trajectory.frames[index].coordinate_type}; } float ArmTrajectory::duration() const { return m_duration; } ArmTrajectory& ArmTrajectory::startAt(const ArmTrajectoryFrame& frame) { scara_trajectory_init(&m_trajectory); scara_trajectory_append_point(&m_trajectory, frame.position, frame.coordinate, {.x=500.f, .y=500.f, .z=1000.f}, m_arm->length); m_duration = 0.f; return *this; } ArmTrajectory& ArmTrajectory::goThrough(const ArmTrajectoryFrame& frame) { scara_trajectory_append_point(&m_trajectory, frame.position, frame.coordinate, {.x=500.f, .y=500.f, .z=1000.f}, m_arm->length); m_duration += 1.f; return *this; } ArmTrajectoryFrame ArmTrajectory::execute() const { if (size() > 0) { return frame(size() - 1); } else { return ArmTrajectoryFrame(); } }
022c4977987b68f630bf723408c3cff04da88614
c3d5bdedfbf5f1b801e1b1f6c7a2ee39d2813f24
/DisjunktniSkupListe.cpp
12c050b492d4018cc6ff54b229e157378378fc58
[]
no_license
adisabolic/traveling_salesman
5fac5cd3b3b86dd09ff0bc936985ffb3d007d932
6b4f41151d3118bc3a331ae8c0f99ea2248ada73
refs/heads/master
2022-10-16T17:42:36.347836
2020-06-10T11:47:19
2020-06-10T11:47:19
271,260,777
0
0
null
null
null
null
UTF-8
C++
false
false
918
cpp
DisjunktniSkupListe.cpp
#include "DisjunktniSkupListe.h" #include <iostream> using namespace std; DisjunktniSkupListe::DisjunktniSkupListe(int n):n(n) { pripadnost.resize(n); for(int i=0;i<n;i++) { pripadnost[i] = new Lista(1, i); } } Lista* DisjunktniSkupListe::Nadji(int v) { return pripadnost[v]; } void DisjunktniSkupListe::Unija(int v1, int v2) { Lista* skup1 = Nadji(v1); Lista* skup2 = Nadji(v2); if(skup1 != skup2) { if(skup1->n < skup2->n) SpojiListe(skup2, skup1); else SpojiListe(skup1, skup2); } } //Spaja l2 na l1 void DisjunktniSkupListe::SpojiListe(Lista* l1, Lista* l2) { l1->n += l2->n; l1->rep->sljedeci = l2->glava; l1->rep = l2->rep; for(auto i = l2->glava ; i != nullptr ; i = i->sljedeci) pripadnost[i->element] = l1; delete l2->glava; delete l2->rep; }
b47c31e27ac5820f51fe34587f7013c67050e190
4eedf651b55998027fb01840625d35fbf3020560
/pcsx2/Netplay/IOPHook.cpp
7f8499dbb8a20ff1b744f71ef5ddf00a7641b6c3
[]
no_license
alexsharoff/pcsx2-online
01e516aa4ad13059144dd04c909817bdf76d3ea4
41e28a154342c81be3927d0085eb457166f1271f
refs/heads/master
2020-04-06T04:30:20.207787
2019-10-27T23:40:20
2019-10-27T23:40:20
1,702,614
16
14
null
null
null
null
UTF-8
C++
false
false
3,228
cpp
IOPHook.cpp
#include "PrecompiledHeader.h" #include "IOPHook.h" #include <fstream> #include <iostream> #include <iomanip> IOPHook* g_IOPHook = 0; //#define LOG_IOP namespace { _PADupdate PADupdateBackup; _PADopen PADopenBackup; _PADstartPoll PADstartPollBackup; _PADpoll PADpollBackup; _PADquery PADqueryBackup; _PADkeyEvent PADkeyEventBackup; _PADsetSlot PADsetSlotBackup; _PADqueryMtap PADqueryMtapBackup; int g_cmd42Counter = -1; int g_pollSide = -1; int g_pollIndex = -1; bool g_active = false; #ifdef LOG_IOP std::fstream g_log; #endif s32 CALLBACK NETPADopen(void *pDsp) { return PADopenBackup(pDsp); } u8 CALLBACK NETPADstartPoll(int pad) { return PADstartPollBackup(pad); } u32 CALLBACK NETPADquery(int pad) { return PADqueryBackup(pad); } keyEvent* CALLBACK NETPADkeyEvent() { return PADkeyEventBackup(); } s32 CALLBACK NETPADqueryMtap(u8 port) { return PADqueryMtapBackup(port); } void CALLBACK NETPADupdate(int pad) { return PADupdateBackup(pad); } u8 CALLBACK NETPADpoll(u8 value) { if(g_pollIndex == 0 && g_pollSide == 0) { if( value == 0x42 ) { if(g_cmd42Counter < 10) g_cmd42Counter++; } else g_cmd42Counter = 0; } #ifdef LOG_IOP using namespace std; g_log << hex << setw(2) << (int)value << '='; #endif value = PADpollBackup(value); #ifdef LOG_IOP g_log << hex << setw(2) << (int)value << ' '; #endif if(g_cmd42Counter > 2 && g_pollIndex > 1) { if(g_pollIndex <= 3) { if(g_IOPHook) value = g_IOPHook->HandleIO(g_pollSide, g_pollIndex-2,value); if(g_IOPHook && g_pollIndex == 3) g_IOPHook->AcceptInput(g_pollSide); } else value = g_pollIndex <= 7 ? 0x7f : 0xff; } g_pollIndex++; return value; } s32 CALLBACK NETPADsetSlot(u8 port, u8 slot) { g_pollSide = port - 1; g_pollIndex = 0; if(g_pollSide == 0) { if(g_IOPHook && g_cmd42Counter > 2) g_IOPHook->NextFrame(); } #ifdef LOG_IOP using namespace std; g_log << endl << setw(2) << (int)port << '-' << setw(2) << (int)slot << ": "; #endif return PADsetSlotBackup(port, slot); } } void HookIOP(IOPHook* hook) { g_IOPHook = hook; g_cmd42Counter = 0; g_pollSide = 0; g_pollIndex = 0; if(g_active) return; g_active = true; #ifdef LOG_IOP g_log.open("iop.log", std::ios_base::trunc | std::ios_base::out); g_log.fill('0'); #endif PADopenBackup = PADopen; PADstartPollBackup = PADstartPoll; PADpollBackup = PADpoll; PADqueryBackup = PADquery; PADkeyEventBackup = PADkeyEvent; PADsetSlotBackup = PADsetSlot; PADqueryMtapBackup = PADqueryMtap; PADupdateBackup = PADupdate; PADopen = NETPADopen; PADstartPoll = NETPADstartPoll; PADpoll = NETPADpoll; PADquery = NETPADquery; PADkeyEvent = NETPADkeyEvent; PADsetSlot = NETPADsetSlot; PADqueryMtap = NETPADqueryMtap; PADupdate = NETPADupdate; } void UnhookIOP() { g_IOPHook = 0; #ifdef LOG_IOP g_log.close(); #endif PADopen = PADopenBackup; PADstartPoll = PADstartPollBackup; PADpoll = PADpollBackup; PADquery = PADqueryBackup; PADkeyEvent = PADkeyEventBackup; PADsetSlot = PADsetSlotBackup; PADqueryMtap = PADqueryMtapBackup; PADupdate = PADupdateBackup; g_active = false; }
b552c048f30696de3804107eba296b15ac61bf6a
28d049067beee963b8e282ed6883028be8c62630
/Baekjoon/recursion/factorial.cpp
7e7e688fdb7d1202f872f33cd98b2b7d6c7b5d29
[]
no_license
GwangYeol-Im/Algorithm
966446018beb226789b3e28eb83117bc72f5537c
749a9ce7d7a43f694a4d2b7ef2d00a65fbc00d6b
refs/heads/master
2023-01-14T05:46:20.084294
2020-11-25T05:40:52
2020-11-25T05:40:52
292,158,845
0
0
null
null
null
null
UTF-8
C++
false
false
304
cpp
factorial.cpp
#include <iostream> using namespace std; int factorial(int n) { if (n == 1) return (1); return n * factorial(n - 1); } int main(void) { int n, result; cin >> n; if (n == 0) { cout << 1 << endl; return (0); } result = factorial(n); cout << result << endl; return (0); }
fad8fa24ddbf875424e12ba635541c61643605e4
9a797f9a9c1c9fc8d94f7d87bbf49a021f7f499e
/runtime/engine/asr/nnet/u2_onnx_nnet.cc
d5e2fdb6f206ea17c1330adb623be8111475f4fc
[ "Apache-2.0" ]
permissive
anniyanvr/DeepSpeech-1
38fb0764c18ef4ee54a5b4bcc1430b69b1434318
17854a04d43c231eff66bfed9d6aa55e94a29e79
refs/heads/develop
2023-09-01T20:02:07.336091
2023-08-14T02:11:45
2023-08-14T02:11:45
218,518,285
0
0
Apache-2.0
2023-09-13T09:54:36
2019-10-30T12:04:59
Python
UTF-8
C++
false
false
16,735
cc
u2_onnx_nnet.cc
// Copyright 2022 Horizon Robotics. All Rights Reserved. // Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // modified from // https://github.com/wenet-e2e/wenet/blob/main/runtime/core/decoder/onnx_asr_model.cc #include "nnet/u2_onnx_nnet.h" #include "common/base/config.h" namespace ppspeech { void U2OnnxNnet::LoadModel(const std::string& model_dir) { std::string encoder_onnx_path = model_dir + "/encoder.onnx"; std::string rescore_onnx_path = model_dir + "/decoder.onnx"; std::string ctc_onnx_path = model_dir + "/ctc.onnx"; std::string param_path = model_dir + "/param.onnx"; // 1. Load sessions try { encoder_ = std::make_shared<fastdeploy::Runtime>(); ctc_ = std::make_shared<fastdeploy::Runtime>(); rescore_ = std::make_shared<fastdeploy::Runtime>(); fastdeploy::RuntimeOption runtime_option; runtime_option.UseOrtBackend(); runtime_option.UseCpu(); runtime_option.SetCpuThreadNum(1); runtime_option.SetModelPath(encoder_onnx_path.c_str(), "", fastdeploy::ModelFormat::ONNX); assert(encoder_->Init(runtime_option)); runtime_option.SetModelPath(rescore_onnx_path.c_str(), "", fastdeploy::ModelFormat::ONNX); assert(rescore_->Init(runtime_option)); runtime_option.SetModelPath(ctc_onnx_path.c_str(), "", fastdeploy::ModelFormat::ONNX); assert(ctc_->Init(runtime_option)); } catch (std::exception const& e) { LOG(ERROR) << "error when load onnx model: " << e.what(); exit(0); } Config conf(param_path); encoder_output_size_ = conf.Read("output_size", encoder_output_size_); num_blocks_ = conf.Read("num_blocks", num_blocks_); head_ = conf.Read("head", head_); cnn_module_kernel_ = conf.Read("cnn_module_kernel", cnn_module_kernel_); subsampling_rate_ = conf.Read("subsampling_rate", subsampling_rate_); right_context_ = conf.Read("right_context", right_context_); sos_= conf.Read("sos_symbol", sos_); eos_= conf.Read("eos_symbol", eos_); is_bidecoder_= conf.Read("is_bidirectional_decoder", is_bidecoder_); chunk_size_= conf.Read("chunk_size", chunk_size_); num_left_chunks_ = conf.Read("left_chunks", num_left_chunks_); LOG(INFO) << "Onnx Model Info:"; LOG(INFO) << "\tencoder_output_size " << encoder_output_size_; LOG(INFO) << "\tnum_blocks " << num_blocks_; LOG(INFO) << "\thead " << head_; LOG(INFO) << "\tcnn_module_kernel " << cnn_module_kernel_; LOG(INFO) << "\tsubsampling_rate " << subsampling_rate_; LOG(INFO) << "\tright_context " << right_context_; LOG(INFO) << "\tsos " << sos_; LOG(INFO) << "\teos " << eos_; LOG(INFO) << "\tis bidirectional decoder " << is_bidecoder_; LOG(INFO) << "\tchunk_size " << chunk_size_; LOG(INFO) << "\tnum_left_chunks " << num_left_chunks_; // 3. Read model nodes LOG(INFO) << "Onnx Encoder:"; GetInputOutputInfo(encoder_, &encoder_in_names_, &encoder_out_names_); LOG(INFO) << "Onnx CTC:"; GetInputOutputInfo(ctc_, &ctc_in_names_, &ctc_out_names_); LOG(INFO) << "Onnx Rescore:"; GetInputOutputInfo(rescore_, &rescore_in_names_, &rescore_out_names_); } U2OnnxNnet::U2OnnxNnet(const ModelOptions& opts) : opts_(opts) { LoadModel(opts_.model_path); } // shallow copy U2OnnxNnet::U2OnnxNnet(const U2OnnxNnet& other) { // metadatas encoder_output_size_ = other.encoder_output_size_; num_blocks_ = other.num_blocks_; head_ = other.head_; cnn_module_kernel_ = other.cnn_module_kernel_; right_context_ = other.right_context_; subsampling_rate_ = other.subsampling_rate_; sos_ = other.sos_; eos_ = other.eos_; is_bidecoder_ = other.is_bidecoder_; chunk_size_ = other.chunk_size_; num_left_chunks_ = other.num_left_chunks_; offset_ = other.offset_; // session encoder_ = other.encoder_; ctc_ = other.ctc_; rescore_ = other.rescore_; // node names encoder_in_names_ = other.encoder_in_names_; encoder_out_names_ = other.encoder_out_names_; ctc_in_names_ = other.ctc_in_names_; ctc_out_names_ = other.ctc_out_names_; rescore_in_names_ = other.rescore_in_names_; rescore_out_names_ = other.rescore_out_names_; } void U2OnnxNnet::GetInputOutputInfo(const std::shared_ptr<fastdeploy::Runtime>& runtime, std::vector<std::string>* in_names, std::vector<std::string>* out_names) { std::vector<fastdeploy::TensorInfo> inputs_info = runtime->GetInputInfos(); (*in_names).resize(inputs_info.size()); for (int i = 0; i < inputs_info.size(); ++i){ fastdeploy::TensorInfo info = inputs_info[i]; std::stringstream shape; for(int j = 0; j < info.shape.size(); ++j){ shape << info.shape[j]; shape << " "; } LOG(INFO) << "\tInput " << i << " : name=" << info.name << " type=" << info.dtype << " dims=" << shape.str(); (*in_names)[i] = info.name; } std::vector<fastdeploy::TensorInfo> outputs_info = runtime->GetOutputInfos(); (*out_names).resize(outputs_info.size()); for (int i = 0; i < outputs_info.size(); ++i){ fastdeploy::TensorInfo info = outputs_info[i]; std::stringstream shape; for(int j = 0; j < info.shape.size(); ++j){ shape << info.shape[j]; shape << " "; } LOG(INFO) << "\tOutput " << i << " : name=" << info.name << " type=" << info.dtype << " dims=" << shape.str(); (*out_names)[i] = info.name; } } std::shared_ptr<NnetBase> U2OnnxNnet::Clone() const { auto asr_model = std::make_shared<U2OnnxNnet>(*this); // reset inner state for new decoding asr_model->Reset(); return asr_model; } void U2OnnxNnet::Reset() { offset_ = 0; encoder_outs_.clear(); cached_feats_.clear(); // Reset att_cache if (num_left_chunks_ > 0) { int required_cache_size = chunk_size_ * num_left_chunks_; offset_ = required_cache_size; att_cache_.resize(num_blocks_ * head_ * required_cache_size * encoder_output_size_ / head_ * 2, 0.0); const std::vector<int64_t> att_cache_shape = {num_blocks_, head_, required_cache_size, encoder_output_size_ / head_ * 2}; att_cache_ort_.SetExternalData(att_cache_shape, fastdeploy::FDDataType::FP32, att_cache_.data()); } else { att_cache_.resize(0, 0.0); const std::vector<int64_t> att_cache_shape = {num_blocks_, head_, 0, encoder_output_size_ / head_ * 2}; att_cache_ort_.SetExternalData(att_cache_shape, fastdeploy::FDDataType::FP32, att_cache_.data()); } // Reset cnn_cache cnn_cache_.resize( num_blocks_ * encoder_output_size_ * (cnn_module_kernel_ - 1), 0.0); const std::vector<int64_t> cnn_cache_shape = {num_blocks_, 1, encoder_output_size_, cnn_module_kernel_ - 1}; cnn_cache_ort_.SetExternalData(cnn_cache_shape, fastdeploy::FDDataType::FP32, cnn_cache_.data()); } void U2OnnxNnet::FeedForward(const std::vector<BaseFloat>& features, const int32& feature_dim, NnetOut* out) { kaldi::Timer timer; std::vector<kaldi::BaseFloat> ctc_probs; ForwardEncoderChunkImpl( features, feature_dim, &out->logprobs, &out->vocab_dim); VLOG(1) << "FeedForward cost: " << timer.Elapsed() << " sec. " << features.size() / feature_dim << " frames."; } void U2OnnxNnet::ForwardEncoderChunkImpl( const std::vector<kaldi::BaseFloat>& chunk_feats, const int32& feat_dim, std::vector<kaldi::BaseFloat>* out_prob, int32* vocab_dim) { // 1. Prepare onnx required data, splice cached_feature_ and chunk_feats // chunk int num_frames = chunk_feats.size() / feat_dim; VLOG(3) << "num_frames: " << num_frames; VLOG(3) << "feat_dim: " << feat_dim; const int feature_dim = feat_dim; std::vector<float> feats; feats.insert(feats.end(), chunk_feats.begin(), chunk_feats.end()); fastdeploy::FDTensor feats_ort; const std::vector<int64_t> feats_shape = {1, num_frames, feature_dim}; feats_ort.SetExternalData(feats_shape, fastdeploy::FDDataType::FP32, feats.data()); // offset int64_t offset_int64 = static_cast<int64_t>(offset_); fastdeploy::FDTensor offset_ort; offset_ort.SetExternalData({}, fastdeploy::FDDataType::INT64, &offset_int64); // required_cache_size int64_t required_cache_size = chunk_size_ * num_left_chunks_; fastdeploy::FDTensor required_cache_size_ort(""); required_cache_size_ort.SetExternalData({}, fastdeploy::FDDataType::INT64, &required_cache_size); // att_mask fastdeploy::FDTensor att_mask_ort; std::vector<uint8_t> att_mask(required_cache_size + chunk_size_, 1); if (num_left_chunks_ > 0) { int chunk_idx = offset_ / chunk_size_ - num_left_chunks_; if (chunk_idx < num_left_chunks_) { for (int i = 0; i < (num_left_chunks_ - chunk_idx) * chunk_size_; ++i) { att_mask[i] = 0; } } const std::vector<int64_t> att_mask_shape = {1, 1, required_cache_size + chunk_size_}; att_mask_ort.SetExternalData(att_mask_shape, fastdeploy::FDDataType::BOOL, reinterpret_cast<bool*>(att_mask.data())); } // 2. Encoder chunk forward std::vector<fastdeploy::FDTensor> inputs(encoder_in_names_.size()); for (int i = 0; i < encoder_in_names_.size(); ++i) { std::string name = encoder_in_names_[i]; if (!strcmp(name.data(), "chunk")) { inputs[i] = std::move(feats_ort); inputs[i].name = "chunk"; } else if (!strcmp(name.data(), "offset")) { inputs[i] = std::move(offset_ort); inputs[i].name = "offset"; } else if (!strcmp(name.data(), "required_cache_size")) { inputs[i] = std::move(required_cache_size_ort); inputs[i].name = "required_cache_size"; } else if (!strcmp(name.data(), "att_cache")) { inputs[i] = std::move(att_cache_ort_); inputs[i].name = "att_cache"; } else if (!strcmp(name.data(), "cnn_cache")) { inputs[i] = std::move(cnn_cache_ort_); inputs[i].name = "cnn_cache"; } else if (!strcmp(name.data(), "att_mask")) { inputs[i] = std::move(att_mask_ort); inputs[i].name = "att_mask"; } } std::vector<fastdeploy::FDTensor> ort_outputs; assert(encoder_->Infer(inputs, &ort_outputs)); offset_ += static_cast<int>(ort_outputs[0].shape[1]); att_cache_ort_ = std::move(ort_outputs[1]); cnn_cache_ort_ = std::move(ort_outputs[2]); std::vector<fastdeploy::FDTensor> ctc_inputs; ctc_inputs.emplace_back(std::move(ort_outputs[0])); // ctc_inputs[0] = std::move(ort_outputs[0]); ctc_inputs[0].name = ctc_in_names_[0]; std::vector<fastdeploy::FDTensor> ctc_ort_outputs; assert(ctc_->Infer(ctc_inputs, &ctc_ort_outputs)); encoder_outs_.emplace_back(std::move(ctc_inputs[0])); // ***** float* logp_data = reinterpret_cast<float*>(ctc_ort_outputs[0].Data()); // Copy to output, (B=1,T,D) std::vector<int64_t> ctc_log_probs_shape = ctc_ort_outputs[0].shape; CHECK_EQ(ctc_log_probs_shape.size(), 3); int B = ctc_log_probs_shape[0]; CHECK_EQ(B, 1); int T = ctc_log_probs_shape[1]; int D = ctc_log_probs_shape[2]; *vocab_dim = D; out_prob->resize(T * D); std::memcpy( out_prob->data(), logp_data, T * D * sizeof(kaldi::BaseFloat)); return; } float U2OnnxNnet::ComputeAttentionScore(const float* prob, const std::vector<int>& hyp, int eos, int decode_out_len) { float score = 0.0f; for (size_t j = 0; j < hyp.size(); ++j) { score += *(prob + j * decode_out_len + hyp[j]); } score += *(prob + hyp.size() * decode_out_len + eos); return score; } void U2OnnxNnet::AttentionRescoring(const std::vector<std::vector<int>>& hyps, float reverse_weight, std::vector<float>* rescoring_score) { CHECK(rescoring_score != nullptr); int num_hyps = hyps.size(); rescoring_score->resize(num_hyps, 0.0f); if (num_hyps == 0) { return; } // No encoder output if (encoder_outs_.size() == 0) { return; } std::vector<int64_t> hyps_lens; int max_hyps_len = 0; for (size_t i = 0; i < num_hyps; ++i) { int length = hyps[i].size() + 1; max_hyps_len = std::max(length, max_hyps_len); hyps_lens.emplace_back(static_cast<int64_t>(length)); } std::vector<float> rescore_input; int encoder_len = 0; for (int i = 0; i < encoder_outs_.size(); i++) { float* encoder_outs_data = reinterpret_cast<float*>(encoder_outs_[i].Data()); for (int j = 0; j < encoder_outs_[i].Numel(); j++) { rescore_input.emplace_back(encoder_outs_data[j]); } encoder_len += encoder_outs_[i].shape[1]; } std::vector<int64_t> hyps_pad; for (size_t i = 0; i < num_hyps; ++i) { const std::vector<int>& hyp = hyps[i]; hyps_pad.emplace_back(sos_); size_t j = 0; for (; j < hyp.size(); ++j) { hyps_pad.emplace_back(hyp[j]); } if (j == max_hyps_len - 1) { continue; } for (; j < max_hyps_len - 1; ++j) { hyps_pad.emplace_back(0); } } const std::vector<int64_t> hyps_pad_shape = {num_hyps, max_hyps_len}; const std::vector<int64_t> hyps_lens_shape = {num_hyps}; const std::vector<int64_t> decode_input_shape = {1, encoder_len, encoder_output_size_}; fastdeploy::FDTensor hyps_pad_tensor_; hyps_pad_tensor_.SetExternalData(hyps_pad_shape, fastdeploy::FDDataType::INT64, hyps_pad.data()); fastdeploy::FDTensor hyps_lens_tensor_; hyps_lens_tensor_.SetExternalData(hyps_lens_shape, fastdeploy::FDDataType::INT64, hyps_lens.data()); fastdeploy::FDTensor decode_input_tensor_; decode_input_tensor_.SetExternalData(decode_input_shape, fastdeploy::FDDataType::FP32, rescore_input.data()); std::vector<fastdeploy::FDTensor> rescore_inputs(3); rescore_inputs[0] = std::move(hyps_pad_tensor_); rescore_inputs[0].name = rescore_in_names_[0]; rescore_inputs[1] = std::move(hyps_lens_tensor_); rescore_inputs[1].name = rescore_in_names_[1]; rescore_inputs[2] = std::move(decode_input_tensor_); rescore_inputs[2].name = rescore_in_names_[2]; std::vector<fastdeploy::FDTensor> rescore_outputs; assert(rescore_->Infer(rescore_inputs, &rescore_outputs)); float* decoder_outs_data = reinterpret_cast<float*>(rescore_outputs[0].Data()); float* r_decoder_outs_data = reinterpret_cast<float*>(rescore_outputs[1].Data()); int decode_out_len = rescore_outputs[0].shape[2]; for (size_t i = 0; i < num_hyps; ++i) { const std::vector<int>& hyp = hyps[i]; float score = 0.0f; // left to right decoder score score = ComputeAttentionScore( decoder_outs_data + max_hyps_len * decode_out_len * i, hyp, eos_, decode_out_len); // Optional: Used for right to left score float r_score = 0.0f; if (is_bidecoder_ && reverse_weight > 0) { std::vector<int> r_hyp(hyp.size()); std::reverse_copy(hyp.begin(), hyp.end(), r_hyp.begin()); // right to left decoder score r_score = ComputeAttentionScore( r_decoder_outs_data + max_hyps_len * decode_out_len * i, r_hyp, eos_, decode_out_len); } // combined left-to-right and right-to-left score (*rescoring_score)[i] = score * (1 - reverse_weight) + r_score * reverse_weight; } } void U2OnnxNnet::EncoderOuts( std::vector<std::vector<kaldi::BaseFloat>>* encoder_out) const { } } //namepace ppspeech
50c3025ee940e9095cde875e8351e22d7394f1d3
085242ce442d9d4ad0cf6df9464b3b35e54bbe4c
/test/libponyc-run/small-finalisers/additional.cc
cc8ee55a60155c35da1a946a028d7bde0d9befff
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
ponylang/ponyc
4c0a0b4a138b4213b4d67424ed313f322d17a87a
c393500e8f8222d648f803f78a705baf452bce05
refs/heads/main
2023-08-19T03:26:37.611328
2023-08-18T13:22:12
2023-08-18T14:27:49
6,667,084
4,901
572
BSD-2-Clause
2023-09-12T18:17:34
2012-11-13T07:38:25
C
UTF-8
C++
false
false
427
cc
additional.cc
#include <stdint.h> #include <pony.h> #ifdef _MSC_VER # define EXPORT_SYMBOL __declspec(dllexport) #else # define EXPORT_SYMBOL #endif extern "C" { static uint32_t num_objects = 0; EXPORT_SYMBOL extern void codegentest_small_finalisers_increment_num_objects() { num_objects++; pony_exitcode((int)num_objects); } #ifndef _MSC_VER void Main_runtime_override_defaults_oo(void* opt) { (void)opt; return; } #endif }
7f253565c0f26607929b4c017621c8a3c6b7a668
efe1f40381251930cb71c8316b5554ef0d5a20ae
/src/locate.cpp
d34bd708e1708ee2bc36b1e09cb06668d1df68ab
[]
no_license
gary-robotics/locate
6ad76c90074659f98688e4651f9ca8082724c67b
dfd2a7020986c360f8bf917b1d3e1bf5a2c5ff8c
refs/heads/master
2023-04-06T14:03:15.467980
2018-04-20T13:05:39
2018-04-20T13:05:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,658
cpp
locate.cpp
// // Created by waxz on 18-4-18. // #include <locate/locate.h> #include <string> using namespace std; Locate_Fusion::Locate_Fusion(ros::NodeHandle nh,ros::NodeHandle nh_private):nh_private_(nh_private), nh_(nh) { } void Locate_Fusion::init_params() { if(!nh_private_.getParam("base_frame_id",base_frame_id_)) base_frame_id_ = "base_link"; if(!nh_private_.getParam("laser_frame_id",laser_frame_id_)) laser_frame_id_ = "laser"; if(!nh_private_.getParam("pose_topic",pose_topic_)) pose_topic_ = "amcl_pose"; if(!nh_private_.getParam("enable_csm",enable_csm_)) enable_csm_ = true; if(!nh_private_.getParam("enable_fft",enable_fft_)) enable_fft_ = true; if(!nh_private_.getParam("transform_tolerance",tmp_tol)) tmp_tol = 0.1; if(!nh_private_.getParam("global_frame_id",global_frame_id_)) global_frame_id_ = "map"; if(!nh_private_.getParam("odom_frame_id",odom_frame_id_)) odom_frame_id_ = "odom"; if(!nh_private_.getParam("tf_broadcast",tf_broadcast_)) tf_broadcast_ = true; if(!nh_private_.getParam("pub_pose",pub_pose_)) pub_pose_ = true; if(!nh_private_.getParam("stddev_x",stddev_x)) stddev_x = 0.1; if(!nh_private_.getParam("stddev_y",stddev_y)) stddev_y = 0.1; if(!nh_private_.getParam("stddev_yaw",stddev_yaw)) stddev_yaw = 0.1; if(!nh_private_.getParam("match_prob_thresh",match_prob_thresh)) match_prob_thresh = 0.3; } void Locate_Fusion::call_back() { /* compute match error, only update odom when match error low enough * if one step's match error reach limitation * goto next step, or stop match use latest pose to update odom * * */ // get base_pose and laser_scan // get base_pose, generate scan_ref // ***** 1) check amcl match_error // compute match_error between scan_ref with scan_sens // if match_error > thresh, END match, return, not update odom // how to recovery amcl !!! // if match_error < thresh, save base_pose to lasted_match_pose // send pose to csm_matcher // ***** 2) check csm match_error // compute match_error between scan_ref with scan_sens // if match_error > thresh, END match, update odom with lasted_match_pose // if match_error < thresh, save base_pose to lasted_match_pose // send pose to fftw // compute match_error between scan_ref with scan_sens // ***** 3) check fftw match_error // if match_error > thresh, END match, update odom with lasted_match_pose // if match_error < thresh, save base_pose to lasted_match_pose }
bbf40a4f471302c9182234169a27b4ec19508880
c315b5e6023775bbc75e446e57851f95a79dd54b
/Students.h
1a0a61daf42d4469de522f326237923ea7b9442b
[]
no_license
foleykt/CSC331_Program6
3cb16780d5269166c9a585c27d56de5011ec2444
3ad5c491387a4fbbb39ca9b5cfb9a73373ab5125
refs/heads/master
2021-01-11T05:27:26.777411
2017-06-21T18:43:48
2017-06-21T18:43:48
95,035,338
0
0
null
null
null
null
UTF-8
C++
false
false
474
h
Students.h
/* * File: Students.h * Author: Kyle * * Created on October 29, 2015, 8:24 PM */ #ifndef STUDENTS_H #define STUDENTS_H using namespace std; #include "SFASU.h" class Students : public SFASU{ public: Students(); Students(string newName, long IDnum, int hrs, string coll, int tHrs, string maj); ~Students(); int hours; string college; int totalHours; string major; private: }; #endif /* STUDENTS_H */
0460c68adf7e3e459e450c835ac8e27ca1ce5ab0
74f4020128ad5fd0f7850c3077c367d0e9c3d04d
/1088 - Points in Segments.cpp
2e0866f58087faf7d0d9e6fadc12faa0d0728ad0
[]
no_license
lsiddiqsunny/Solved-problem-from-lightoj
236272496d1317e89219e1f92700248fa78ce841
d5d5722c50f1dd28168691a29fa7ea7890469b5b
refs/heads/master
2020-09-27T21:44:46.828861
2020-05-28T17:52:41
2020-05-28T17:52:41
226,616,572
0
0
null
null
null
null
UTF-8
C++
false
false
646
cpp
1088 - Points in Segments.cpp
#include<bits/stdc++.h> using namespace std; vector<int>a; int main() { int test; scanf("%d",&test); int n,q; for(int i=0; i<test; i++) { a.clear(); scanf("%d%d",&n,&q); int x; for(int j=0; j<n; j++) { scanf("%d",&x); a.push_back(x); } printf("Case %d:\n",i+1); int y,z; for(int j=0; j<q; j++) { scanf("%d%d",&y,&z); y = (int)(lower_bound(a.begin(),a.end(), y) - a.begin()); z = (int)(upper_bound(a.begin(),a.end(), z) - a.begin()); printf("%d\n",z-y); } } }
4053d151f94fa246db111a45938ccf81aebe6e5f
1abf985d2784efce3196976fc1b13ab91d6a2a9e
/opentracker/src/input/ARTDataTrackerChomp.cxx
1bf3d3a9c7bd30f66f03a5d2ed5b173e672f19bd
[ "BSD-3-Clause" ]
permissive
dolphinking/mirror-studierstube
2550e246f270eb406109d4c3a2af7885cd7d86d0
57249d050e4195982c5380fcf78197073d3139a5
refs/heads/master
2021-01-11T02:19:48.803878
2012-09-14T13:01:15
2012-09-14T13:01:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,213
cxx
ARTDataTrackerChomp.cxx
/* ======================================================================== * Copyright (c) 2006, * Institute for Computer Graphics and Vision * Graz University of Technology * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Graz University of Technology nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. * ======================================================================== * PROJECT: OpenTracker * ======================================================================== */ /** source file for ARTDataTrackerChomp class. * * @author Christopher Schmidt * * $Id: ARTDataTrackerChomp.cxx 1590 2006-10-31 17:31:17Z mendez $ * @file */ /* ======================================================================= */ // this will remove the warning 4786 #include <OpenTracker/tool/disable4786.h> #include <cstdlib> #include <OpenTracker/input/ARTDataTrackerChomp.h> #include <cstdlib> #include <sys/types.h> #include <cstdio> #include <iostream> #include <sstream> #include <ace/Log_Msg.h> #ifndef OT_NO_ARTDATATRACKER_SUPPORT namespace ot { // Destructor method ARTDataTrackerChomp::~ARTDataTrackerChomp() { } ARTDataTrackerChomp::ARTDataTrackerChomp() { } void ARTDataTrackerChomp::chomp(std::string datagramm) { using namespace std; istringstream iss(datagramm); int linenumber = 0; int station = -1; double timestamp = 0.0; std::map<int, BodyRecord>::iterator bdit; std::map<int, MarkerRecord>::iterator mkit; std::map<int, FlystickRecord>::iterator fsit; std::map<int, MeasuretargetRecord>::iterator mtit; for ( bdit = tempBodyRecord.begin(); bdit != tempBodyRecord.end(); bdit++) { ((*bdit).second).valid = false; } for ( mkit = tempMarkerRecord.begin(); mkit != tempMarkerRecord.end(); mkit++) { ((*mkit).second).valid = false; } for ( fsit = tempFlystickRecord.begin(); fsit != tempFlystickRecord.end(); fsit++) { ((*fsit).second).valid = false; } for ( mtit = tempMeasuretargetRecord.begin(); mtit != tempMeasuretargetRecord.end(); mtit++) { ((*mtit).second).valid = false; } numberTrackedBodies = 0; numberTrackedMarkers = 0; numberTrackedFlysticks = 0; numberTrackedMeasuretargets = 0; while (!iss.eof()) { stringbuf linetype; stringbuf linecontent; iss.get(linetype,' '); if ((linenumber == 0) && (linetype.str() != "fr")) { logPrintD("Error receiving correct Data [#001]\n"); logPrintD("Check if Format in ARTTracker Software is set to ASCII\n"); //ACE_DEBUG((LM_ERROR, ACE_TEXT("ot:Error receiving correct Data!!! [#001]\n"))); //ACE_DEBUG((LM_ERROR, ACE_TEXT("ot:Check if Format in ARTTracker Software is set to ASCII !!!\n"))); return; } //ACE_DEBUG((LM_INFO, ACE_TEXT("%d linetype |%s|\n"), linenumber, linetype.str().c_str() )); if (linetype.str() == "fr") { iss >> frameNumber; iss.get(linecontent); if (static_cast<int>(iss.peek()) == 10) { iss.ignore(1); } } else if (linetype.str() == "ts") { iss >> timestamp; //ACE_DEBUG((LM_INFO, ACE_TEXT("%d timestamp |%f|\n"), linenumber, timestamp )); iss.get(linecontent); if (static_cast<int>(iss.peek()) == 10) { iss.ignore(1); } } else if (linetype.str() == "6d") { iss >> numberTrackedBodies; //ACE_DEBUG((LM_INFO, ACE_TEXT("%d 6dcount |%d|\n"), linenumber, numberTrackedBodies )); if (numberTrackedBodies > 0) iss.ignore(2); int i; for (i=0; i<numberTrackedBodies; i++) { iss >> station; //ACE_DEBUG((LM_INFO, ACE_TEXT("%d station |%d|\n"), linenumber, station )); tempBodyRecord[station].id = station; iss >> tempBodyRecord[station].quality; iss.ignore(2); iss >> tempBodyRecord[station].location[0]; iss >> tempBodyRecord[station].location[1]; iss >> tempBodyRecord[station].location[2]; iss >> tempBodyRecord[station].eulerAngles[0]; iss >> tempBodyRecord[station].eulerAngles[1]; iss >> tempBodyRecord[station].eulerAngles[2]; iss.ignore(2); iss >> tempBodyRecord[station].rotationMatrix[0]; iss >> tempBodyRecord[station].rotationMatrix[1]; iss >> tempBodyRecord[station].rotationMatrix[2]; iss >> tempBodyRecord[station].rotationMatrix[3]; iss >> tempBodyRecord[station].rotationMatrix[4]; iss >> tempBodyRecord[station].rotationMatrix[5]; iss >> tempBodyRecord[station].rotationMatrix[6]; iss >> tempBodyRecord[station].rotationMatrix[7]; iss >> tempBodyRecord[station].rotationMatrix[8]; tempBodyRecord[station].valid = true; if (i < numberTrackedBodies-1) iss.ignore(3); else iss.ignore(1); } iss.get(linecontent); if (static_cast<int>(iss.peek()) == 10) { iss.ignore(1); } } else if (linetype.str() == "3d") { iss >> numberTrackedMarkers; //ACE_DEBUG((LM_INFO, ACE_TEXT("%d 3dcount |%d|\n"), linenumber, numberTrackedMarkers )); if (numberTrackedMarkers > 0) iss.ignore(2); int i; for (i=0; i<numberTrackedMarkers; i++) { iss >> station; //ACE_DEBUG((LM_INFO, ACE_TEXT("%d station |%d|\n"), linenumber, station )); tempMarkerRecord[station].id = station; iss >> tempMarkerRecord[station].quality; iss.ignore(2); iss >> tempMarkerRecord[station].location[0]; iss >> tempMarkerRecord[station].location[1]; iss >> tempMarkerRecord[station].location[2]; tempMarkerRecord[station].valid = true; if (i < numberTrackedMarkers-1) iss.ignore(3); else iss.ignore(1); } iss.get(linecontent); if (static_cast<int>(iss.peek()) == 10) { iss.ignore(1); } } else if (linetype.str() == "6df") { iss >> numberTrackedFlysticks; //ACE_DEBUG((LM_INFO, ACE_TEXT("%d 6dfcount |%d|\n"), linenumber, numberTrackedFlysticks )); if (numberTrackedFlysticks > 0) iss.ignore(2); int i; for (i=0; i<numberTrackedFlysticks; i++) { iss >> station; //ACE_DEBUG((LM_INFO, ACE_TEXT("%d station |%d|\n"), linenumber, station )); tempFlystickRecord[station].id = station; iss >> tempFlystickRecord[station].quality; iss >> tempFlystickRecord[station].buttons; iss.ignore(2); iss >> tempFlystickRecord[station].location[0]; iss >> tempFlystickRecord[station].location[1]; iss >> tempFlystickRecord[station].location[2]; iss >> tempFlystickRecord[station].eulerAngles[0]; iss >> tempFlystickRecord[station].eulerAngles[1]; iss >> tempFlystickRecord[station].eulerAngles[2]; iss.ignore(2); iss >> tempFlystickRecord[station].rotationMatrix[0]; iss >> tempFlystickRecord[station].rotationMatrix[1]; iss >> tempFlystickRecord[station].rotationMatrix[2]; iss >> tempFlystickRecord[station].rotationMatrix[3]; iss >> tempFlystickRecord[station].rotationMatrix[4]; iss >> tempFlystickRecord[station].rotationMatrix[5]; iss >> tempFlystickRecord[station].rotationMatrix[6]; iss >> tempFlystickRecord[station].rotationMatrix[7]; iss >> tempFlystickRecord[station].rotationMatrix[8]; tempFlystickRecord[station].valid = true; if (i < numberTrackedFlysticks-1) iss.ignore(3); else iss.ignore(1); } iss.get(linecontent); if (static_cast<int>(iss.peek()) == 10) { iss.ignore(1); } } else if (linetype.str() == "6dmt") { iss >> numberTrackedMeasuretargets; //ACE_DEBUG((LM_INFO, ACE_TEXT("%d 6dmtcount |%d|\n"), linenumber, numberTrackedMeasuretargets )); if (numberTrackedMeasuretargets > 0) iss.ignore(2); int i; for (i=0; i<numberTrackedMeasuretargets; i++) { iss >> station; //ACE_DEBUG((LM_INFO, ACE_TEXT("%d station |%d|\n"), linenumber, station )); tempMeasuretargetRecord[station].id = station; iss >> tempMeasuretargetRecord[station].quality; iss >> tempMeasuretargetRecord[station].buttons; iss.ignore(2); iss >> tempMeasuretargetRecord[station].location[0]; iss >> tempMeasuretargetRecord[station].location[1]; iss >> tempMeasuretargetRecord[station].location[2]; iss.ignore(2); iss >> tempMeasuretargetRecord[station].rotationMatrix[0]; iss >> tempMeasuretargetRecord[station].rotationMatrix[1]; iss >> tempMeasuretargetRecord[station].rotationMatrix[2]; iss >> tempMeasuretargetRecord[station].rotationMatrix[3]; iss >> tempMeasuretargetRecord[station].rotationMatrix[4]; iss >> tempMeasuretargetRecord[station].rotationMatrix[5]; iss >> tempMeasuretargetRecord[station].rotationMatrix[6]; iss >> tempMeasuretargetRecord[station].rotationMatrix[7]; iss >> tempMeasuretargetRecord[station].rotationMatrix[8]; tempMeasuretargetRecord[station].valid = true; if (i < numberTrackedMeasuretargets-1) iss.ignore(3); else iss.ignore(1); } iss.get(linecontent); if (static_cast<int>(iss.peek()) == 10) { iss.ignore(1); } } else if (linetype.str() == "6dcal") { iss >> numberTrackedCalBodies; //ACE_DEBUG((LM_INFO, ACE_TEXT("%d 6dcalcount |%d|\n"), linenumber, numberTrackedCalBodies )); iss.get(linecontent); if (static_cast<int>(iss.peek()) == 10) { iss.ignore(1); } } else { iss.get(linecontent); if (static_cast<int>(iss.peek()) == 10) { iss.ignore(1); } } ++linenumber; } } void ARTDataTrackerChomp::displayRecords() { // Output logPrintD("Contents of tempBodyRecord, tempMarkerRecord, tempFlystickRecord and tempMeasuretargetRecord\n"); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:Contents of tempBodyRecord, tempMarkerRecord, tempFlystickRecord and tempMeasuretargetRecord\n"))); logPrintD("Number of Tracked Bodies for 6d: %d\n", tempBodyRecord.size()); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:Number of Tracked Bodies for 6d: %d\n"), tempBodyRecord.size() )); std::map<int, BodyRecord>::iterator itb; for ( itb = tempBodyRecord.begin(); itb != tempBodyRecord.end(); itb++) { logPrintD("Framenumber of Datagramm is: %d\n", frameNumber); logPrintD("Number of Tracked Bodies for 6d: %d\n", numberTrackedBodies); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:Framenumber of Datagramm is: %d\n"), frameNumber)); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:Number of Tracked Bodies for 6d: %d\n"), numberTrackedBodies)); if ( itb->second.valid == true ) { logPrintD("tempBodyRecord[%d].id %d\n", itb->first, itb->second.id); logPrintD("tempBodyRecord[%d].quality %f\n", itb->first, itb->second.quality); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempBodyRecord[%d].id %d\n"), itb->first, itb->second.id)); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempBodyRecord[%d].quality %f\n"), itb->first, itb->second.quality)); int j; for(j=0; j < 3; j++) { logPrintD("tempBodyRecord[%d].location[%d]: \n",itb->first, j, itb->second.location[j]); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempBodyRecord[%d].location[%d]: \n"), //itb->first, j, itb->second.location[j])); } for(j=0; j < 3; j++) { logPrintD("tempBodyRecord[%d].eulerAngles[%d]: \n", itb->first, j, itb->second.eulerAngles[j]); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempBodyRecord[%d].eulerAngles[%d]: \n"), //itb->first, j, itb->second.eulerAngles[j])); } for(j=0; j < 9; j++) { logPrintD("ot:tempBodyRecord[%d].rotationMatrix[%d]: \n", itb->first, j, itb->second.rotationMatrix[j]); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempBodyRecord[%d].rotationMatrix[%d]: \n"), //itb->first, j, itb->second.rotationMatrix[j])); } }// END if else { logPrintD("#### No Valid DATA for this Body ####\n"); //ACE_DEBUG((LM_ERROR, ACE_TEXT("ot:#### No Valid DATA for this Body ####"))); }// END else } std::map<int, MarkerRecord>::iterator itm; for(itm = tempMarkerRecord.begin(); itm != tempMarkerRecord.end(); itm++) { logPrintD("Number of Markers for 3d: %d\n", numberTrackedMarkers); //ACE_DEBUG((LM_ERROR, ACE_TEXT("ot:Number of Markers for 3d: %d\n"), numberTrackedMarkers)); if ( itm->second.valid == true ) { logPrintD("tempMarkerRecord[%d].id %d\n", itm->first, itm->second.id); logPrintD("tempMarkerRecord[%d].quality %f\n", itm->first, itm->second.quality); //ACE_DEBUG((LM_ERROR, ACE_TEXT("ot:tempMarkerRecord[%d].id %d\n"), itm->first, itm->second.id)); //ACE_DEBUG((LM_ERROR, ACE_TEXT("ot:tempMarkerRecord[%d].quality %d\n"), itm->first, itm->second.quality)); for(int j=0; j < 3; j++) { logPrintD("tempBodyRecord[%d].location[%d]: \n",itm->first, j, itm->second.location[j]); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempBodyRecord[%d].location[%d]: \n"), itm->first, j, itm->second.location[j])); } } else { logPrintD("#### No Valid DATA for this Marker ####\n"); //ACE_DEBUG((LM_ERROR, ACE_TEXT("ot:#### No Valid DATA for this Marker ####"))); } } std::map<int, FlystickRecord>::iterator itf; for ( itf = tempFlystickRecord.begin(); itf != tempFlystickRecord.end(); itf++) { logPrintD("Framenumber of Datagramm is: %d\n", frameNumber); logPrintD("Number of Tracked Flysticks: %d\n", numberTrackedFlysticks); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:Framenumber of Datagramm is: %d\n"), frameNumber)); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:Number of Tracked Flysticks: %d\n"), numberTrackedFlysticks)); if ( itf->second.valid == true ) { logPrintD("tempFlystickRecord[%d].id %d\n", itf->first, itf->second.id); logPrintD("tempFlystickRecord[%d].quality %f\n", itf->first, itf->second.quality); logPrintD("tempFlystickRecord[%d].buttons %d\n", itf->first, itf->second.buttons); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempFlystickRecord[%d].id %d\n"), itf->first, itf->second.id)); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempFlystickRecord[%d].quality %f\n"), itf->first, itf->second.quality)); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempFlystickRecord[%d].buttons %d\n"), itf->first, itf->second.buttons)); int j; for(j=0; j < 3; j++) { logPrintD("tempFlystickRecord[%d].location[%d]: \n",itf->first, j, itf->second.location[j]); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempFlystickRecord[%d].location[%d]: \n"), //itf->first, j, itf->second.location[j])); } for(j=0; j < 3; j++) { logPrintD("tempFlystickRecord[%d].eulerAngles[%d]: \n",itf->first, j, itf->second.eulerAngles[j]); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempFlystickRecord[%d].eulerAngles[%d]: \n"), //itf->first, j, itf->second.eulerAngles[j])); } for(j=0; j < 9; j++) { logPrintD("tempFlystickRecord[%d].rotationMatrix[%d]: \n",itf->first, j, itf->second.rotationMatrix[j]); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempFlystickRecord[%d].rotationMatrix[%d]: \n"), //itf->first, j, itf->second.rotationMatrix[j])); } }// END if else { logPrintD("#### No Valid DATA for this Flystick ####\n"); //ACE_DEBUG((LM_ERROR, ACE_TEXT("ot:#### No Valid DATA for this Flystick ####"))); }// END else } std::map<int, MeasuretargetRecord>::iterator itmt; for ( itmt = tempMeasuretargetRecord.begin(); itmt != tempMeasuretargetRecord.end(); itmt++) { logPrintD("Framenumber of Datagramm is: %d\n", frameNumber); logPrintD("Number of Tracked Measurement Targets: %d\n", numberTrackedMeasuretargets); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:Framenumber of Datagramm is: %d\n"), frameNumber)); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:Number of Tracked Measurement Targets: %d\n"), numberTrackedMeasuretargets)); if ( itmt->second.valid == true ) { logPrintD("tempMeasureTargetRecord[%d].id %d\n", itmt->first, itmt->second.id); logPrintD("tempMeasureTargetRecord[%d].quality %f\n", itmt->first, itmt->second.quality); logPrintD("tempMeasureTargetRecord[%d].buttons %d\n", itmt->first, itmt->second.buttons); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempMeasureTargetRecord[%d].id %d\n"), itmt->first, itmt->second.id)); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempMeasureTargetRecord[%d].quality %f\n"), itmt->first, itmt->second.quality)); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempMeasureTargetRecord[%d].buttons %d\n"), itmt->first, itmt->second.buttons)); int j; for(j=0; j < 3; j++) { logPrintD("tempMeasureTargetRecord[%d].location[%d]: \n",itmt->first, j, itmt->second.location[j]); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempMeasureTargetRecord[%d].location[%d]: \n"), // itmt->first, j, itmt->second.location[j])); } for(j=0; j < 9; j++) { logPrintD("tempMeasureTargetRecord[%d].rotationMatrix[%d]: \n",itmt->first, j, itmt->second.rotationMatrix[j]); //ACE_DEBUG((LM_INFO, ACE_TEXT("ot:tempMeasureTargetRecord[%d].rotationMatrix[%d]: \n"), // itmt->first, j, itmt->second.rotationMatrix[j])); } }// END if else { logPrintD("#### No Valid DATA for this Measurement Target ####\n"); //ACE_DEBUG((LM_ERROR, ACE_TEXT("ot:#### No Valid DATA for this Measurement Target ####"))); }// END else } if(numberTrackedCalBodies != 0) { logPrintD("Number of calibrated Bodies: %d\n", numberTrackedCalBodies); //ACE_DEBUG((LM_ERROR, ACE_TEXT("ot:Number of calibrated Bodies: %d\n"), numberTrackedCalBodies)); } //assert(0); //assert(tempBodyRecord.size() != 0); } int ARTDataTrackerChomp::getFrameNumber() { return frameNumber; } int ARTDataTrackerChomp::getTrackedBodyNumber() { return numberTrackedBodies; } std::map<int, ARTDataTrackerChomp::BodyRecord > & ARTDataTrackerChomp::getBodyRecord() { return tempBodyRecord; } int ARTDataTrackerChomp::getTrackedMarkerNumber() { return numberTrackedMarkers; } std::map<int, ARTDataTrackerChomp::MarkerRecord > &ARTDataTrackerChomp::getMarkerRecord() { return tempMarkerRecord; } int ARTDataTrackerChomp::getTrackedFlystickNumber() { return numberTrackedFlysticks; } std::map<int, ARTDataTrackerChomp::FlystickRecord > &ARTDataTrackerChomp::getFlystickRecord() { return tempFlystickRecord; } int ARTDataTrackerChomp::getTrackedMeasuretargetNumber() { return numberTrackedMeasuretargets; } std::map<int, ARTDataTrackerChomp::MeasuretargetRecord > &ARTDataTrackerChomp::getMeasuretargetRecord() { return tempMeasuretargetRecord; } int ARTDataTrackerChomp::getCalibratedTrackedBodyNumber() { return numberTrackedCalBodies; } } // namespace ot #else #pragma message(">>> OT_NO_ARTDATATRACKER_SUPPORT") #endif // OT_NO_ARTDATATRACKER_SUPPORT /* =========================================================================== End of ARTDataTrackerChomp.cxx =========================================================================== Automatic Emacs configuration follows. Local Variables: mode:c++ c-basic-offset: 4 eval: (c-set-offset 'subeventment-open 0) eval: (c-set-offset 'case-label '+) eval: (c-set-offset 'eventment 'c-lineup-runin-eventments) eval: (setq indent-tabs-mode nil) End: =========================================================================== */
bc036a52b4b5e020688d064e6bd18c3029181add
188fb8ded33ad7a2f52f69975006bb38917437ef
/Fluid/processor5/0.66/p
f36296e8726b881e12e6b1981a742d8a07794eb2
[]
no_license
abarcaortega/Tuto_2
34a4721f14725c20471ff2dc8d22b52638b8a2b3
4a84c22efbb9cd2eaeda92883343b6910e0941e2
refs/heads/master
2020-08-05T16:11:57.674940
2019-10-04T09:56:09
2019-10-04T09:56:09
212,573,883
0
0
null
null
null
null
UTF-8
C++
false
false
6,199
p
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: dev | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.66"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 465 ( -8.05203 -19.2458 -30.0842 -40.2903 -49.5694 -57.6142 -64.1171 -68.7775 -71.2985 -71.3918 -68.8124 -63.4007 -55.1112 -44.0557 -30.5121 -14.8336 2.42545 19.1033 28.6311 21.046 -8.81321 -20.0698 -30.9735 -41.2432 -50.5824 -58.6843 -65.2456 -69.9775 -72.6012 -72.8347 -70.4334 -65.2625 -57.3014 -46.6806 -33.706 -18.8292 -2.76988 12.5594 21.9659 15.2174 -10.5903 -21.8144 -32.7051 -42.9777 -52.3325 -60.4598 -67.0558 -71.838 -74.5401 -74.8866 -72.6425 -67.6929 -60.0444 -49.8442 -37.4216 -23.3208 -8.40638 5.64521 14.8195 10.4789 -13.5291 -24.7214 -35.6022 -45.8836 -55.2627 -63.4267 -70.0708 -74.9158 -77.7074 -78.1942 -76.1533 -71.4786 -64.1985 -54.4673 -42.6151 -29.2125 -15.1471 -1.85658 7.57737 6.51786 -17.3047 -28.3994 -39.2068 -49.4391 -58.7918 -66.9508 -73.6106 -78.4943 -81.36 -81.981 -80.1454 -75.7536 -68.8526 -59.5982 -48.305 -35.5178 -22.0624 -9.14236 0.911886 3.20013 -21.8968 -32.8518 -43.5535 -53.712 -63.0185 -71.1545 -77.8089 -82.7013 -85.598 -86.3031 -84.6239 -80.4663 -73.8915 -65.0503 -54.2257 -41.9004 -28.7947 -15.904 -4.98996 0.402948 -27.1112 -37.869 -48.4113 -58.4461 -67.6609 -75.7323 -82.3435 -87.2083 -90.0983 -90.8453 -89.2767 -85.304 -79.0007 -70.5069 -60.0621 -48.0633 -35.1037 -22.0005 -10.1145 -1.96469 -32.7122 -43.2301 -53.5729 -63.4475 -72.5378 -80.5147 -87.0525 -91.8554 -94.695 -95.4285 -93.9075 -90.0543 -83.9544 -75.7356 -65.5864 -53.8069 -40.8545 -27.3923 -14.5116 -3.96945 -38.4204 -48.6755 -58.7943 -68.4848 -77.4277 -85.2875 -91.7284 -96.4419 -99.1949 -99.8646 -98.3293 -94.5289 -88.564 -80.5521 -70.63 -58.9975 -45.9761 -32.0895 -18.2475 -5.66046 -43.9269 -53.9193 -63.8123 -73.3158 -82.1073 -89.8453 -96.1822 -100.794 -103.436 -103.999 -102.391 -98.579 -92.6847 -84.8205 -75.0748 -63.5501 -50.436 -36.1229 -21.3867 -7.07414 -48.9159 -58.672 -68.3645 -77.7039 -86.364 -93.9965 -100.242 -104.757 -107.28 -107.704 -105.973 -102.096 -96.2167 -88.4523 -78.8492 -67.4189 -54.2266 -39.5311 -23.9889 -8.23878 -53.0885 -62.6655 -72.2107 -81.4349 -90.0056 -97.5693 -103.756 -108.2 -110.618 -110.882 -108.992 -105.016 -99.1084 -91.4067 -81.9251 -70.5933 -57.3609 -42.3573 -26.1103 -9.17793 -56.1931 -65.681 -75.1533 -84.3303 -92.8686 -100.413 -106.588 -111.003 -113.343 -113.463 -111.414 -107.316 -101.349 -93.6818 -84.3103 -73.0938 -59.8723 -44.6477 -27.8043 -9.91308 -58.0299 -67.5396 -77.0453 -86.2499 -94.8127 -102.385 -108.598 -113.045 -115.367 -115.386 -113.198 -108.977 -102.945 -95.2997 -86.0368 -74.9603 -61.801 -46.4436 -29.1228 -10.4686 -58.5685 -68.2102 -77.8198 -87.0911 -95.7103 -103.334 -109.6 -114.114 -116.475 -116.459 -114.216 -109.964 -103.907 -96.292 -87.1397 -76.22 -63.1698 -47.7843 -30.1243 -10.8776 -48.2588 -57.962 -67.7989 -77.5275 -86.8748 -95.5451 -103.207 -109.512 -114.085 -116.526 -116.562 -114.365 -110.187 -104.199 -96.672 -87.6502 -76.8964 -64.0256 -48.7442 -30.8874 -11.2024 -46.3437 -56.3937 -66.4474 -76.2933 -85.6927 -94.3764 -102.038 -108.344 -112.939 -115.454 -115.612 -113.557 -109.545 -103.765 -96.4371 -87.6126 -77.0703 -64.4208 -49.2871 -31.3709 -11.5053 -64.3515 -74.2627 -83.6632 -92.3108 -99.924 -106.191 -110.781 -113.369 -113.709 -111.854 -108.089 -102.656 -95.6535 -87.1158 -76.8285 -64.3879 -49.4036 -31.6034 -11.7761 -80.936 -89.4798 -96.9888 -103.176 -107.744 -110.408 -110.964 -109.374 -105.946 -100.942 -94.3639 -86.1881 -76.1958 -63.9934 -49.203 -31.6014 -11.892 -86.0652 -93.4061 -99.4764 -104.006 -106.747 -107.523 -106.277 -103.27 -98.7258 -92.6264 -84.857 -75.1811 -63.2334 -48.6764 -31.3477 -11.8775 -95.2964 -99.7649 -102.579 -103.586 -102.736 -100.164 -96.0841 -90.488 -83.1299 -73.764 -62.0758 -47.7923 -30.8216 -11.7441 -98.0932 -99.3182 -98.8417 -96.7083 -93.1 -87.9553 -80.9606 -71.8752 -60.4508 -46.4971 -29.9966 -11.4997 -94.8065 -94.6466 -92.9141 -89.7159 -84.9267 -78.2191 -69.3854 -58.2539 -44.7226 -28.8449 -11.1536 -88.6281 -85.7197 -81.171 -74.6922 -66.125 -55.3704 -42.4074 -27.3491 -10.7167 -80.7975 -76.4122 -70.1703 -61.9574 -51.7295 -39.5293 -25.515 -10.1968 -64.5734 -56.8692 -47.361 -36.136 -23.3826 -9.59583 -51.0145 -42.4171 -32.3534 -21.0275 -8.91178 -28.3597 -18.5495 -8.14647 -16.0534 -7.31306 -6.43728 ) ; boundaryField { inlet { type zeroGradient; } outlet { type fixedValue; value uniform 0; } flap { type zeroGradient; } upperWall { type zeroGradient; } lowerWall { type zeroGradient; } frontAndBack { type empty; } procBoundary5to2 { type processor; value nonuniform List<scalar> 34 ( -43.8006 -54.1372 -54.1372 -61.7456 -71.6174 -71.6174 -77.7152 -77.7152 -82.2864 -89.3901 -89.3901 -90.8412 -95.2221 -95.2221 -93.4002 -93.4002 -89.957 -90.046 -90.046 -83.5266 -83.5266 -74.6953 -70.4844 -70.4844 -58.0326 -58.0326 -44.6814 -37.1388 -37.1388 -24.3444 -24.3444 -13.6314 -13.6314 -5.55338 ) ; } procBoundary5to4 { type processor; value nonuniform List<scalar> 18 ( 3.24645 2.53826 0.704693 -2.28784 -6.1833 -10.9489 -16.3991 -22.2779 -28.2814 -34.0799 -39.3375 -43.7254 -46.9493 -48.7752 -49.1516 -49.1516 -38.9211 -36.4939 ) ; } } // ************************************************************************* //
f9d9f770cd1daaa54d54f1f52e84209b8c14fd56
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/old_hunk_7937.cpp
689adf2235a8702f4b71c4eb9459588960ff6673
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
242
cpp
old_hunk_7937.cpp
if (PATH_MAX - 40 < strlen(gitdirenv)) die("'$%s' too big", GIT_DIR_ENVIRONMENT); if (is_git_directory(gitdirenv)) { if (!work_tree_env) return set_work_tree(gitdirenv); return NULL; } if (nongit_ok) { *nongit_ok = 1;
7ed99e404edc7532fa39e3e437bd8eee84549680
4860e7ccb92cd5782e5056ec2bfc6ac6fa3ac783
/TGS/ProjectData/GameSources/MyUI.cpp
0ea5d6d042dfb59402a367c7e9abb1da60469cb3
[]
no_license
KobayashiHaruya/ZyuZyu
f265c543a0695ec8a9e494957a0cad1266ed21c6
7a0c0284afe5527b18ef3159d7bd5a2d19008132
refs/heads/master
2021-01-08T16:53:09.546276
2020-06-13T09:32:02
2020-06-13T09:32:02
242,076,336
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
55,416
cpp
MyUI.cpp
#include "stdafx.h" #include "Project.h" namespace basecross { void UI_Base::Draw() { float X = m_Vertex.x / 2.0f; float Y = m_Vertex.y / 2.0f; vector<VertexPositionColorTexture> vertices; Col4 color = Col4(1.0f, 1.0f, 1.0f, 1.0f); vertices.push_back(VertexPositionColorTexture(Vec3(-X, Y, 0), color, Vec2(0.0f, 0.0f))); vertices.push_back(VertexPositionColorTexture(Vec3(X, Y, 0), color, Vec2(1.0f, 0.0f))); vertices.push_back(VertexPositionColorTexture(Vec3(-X, -Y, 0), color, Vec2(0.0f, 1.0f))); vertices.push_back(VertexPositionColorTexture(Vec3(X, -Y, 0), color, Vec2(1.0f, 1.0f))); vector<uint16_t> indices = { 0, 1, 2, 1, 3, 2 }; auto ptrDraw = AddComponent<PCTSpriteDraw>(vertices, indices); ptrDraw->SetDiffuse(m_color); ptrDraw->SetTextureResource(m_textures); SetDrawLayer(m_layer); auto ptrTrans = GetComponent<Transform>(); ptrTrans->SetPosition(m_pos); ptrTrans->SetScale(m_scale); SetAlphaActive(true); } void Title_UI::OnCreate() { Draw(); } void Operation_UI::OnCreate() { Draw(); } //------------------------------------------------------------------------------------------------ //テキスト : Class //------------------------------------------------------------------------------------------------ void UI_Sprite_Text::OnCreate() { SetDrawLayer(m_layer); auto text = AddComponent<StringSprite>(); text->SetTextAlignment(m_textAlignment); text->SetFont(m_fontName, m_fontSize); text->SetTextRect(m_rect); text->SetFontColor(m_color); text->SetText(m_text); if (m_isBk) text->SetBackColor(Col4(0.0f, 0.0f, 0.0f, 1.0f)); } void UI_Sprite_Text::UpdateText(const wstring value) { auto text = GetComponent<StringSprite>(); text->SetText(value); } void UI_Sprite_Text::Remove() { GetStage()->RemoveGameObject<GameObject>(GetThis<UI_Sprite_Text>()); } //------------------------------------------------------------------------------------------------ //スタティックな画像 : Class //------------------------------------------------------------------------------------------------ void UI_Static_Image::OnCreate() { Draw(); } void UI_Static_Image::Draw() { Col4 color = Col4(1.0f, 1.0f, 1.0f, 1.0f); m_vertices.push_back(VertexPositionColorTexture(Vec3(-m_xHalf, m_yHalf, 0.0f), color, Vec2(0.0f, 0.0f))); m_vertices.push_back(VertexPositionColorTexture(Vec3(m_xHalf, m_yHalf, 0.0f), color, Vec2(1.0f, 0.0f))); m_vertices.push_back(VertexPositionColorTexture(Vec3(-m_xHalf, -m_yHalf, 0.0f), color, Vec2(0.0f, 1.0f))); m_vertices.push_back(VertexPositionColorTexture(Vec3(m_xHalf, -m_yHalf, 0.0f), color, Vec2(1.0f, 1.0f))); vector<uint16_t> indices = { 0, 1, 2, 1, 3, 2 }; auto ptrDraw = AddComponent<PCTSpriteDraw>(m_vertices, indices); ptrDraw->SetDiffuse(m_color); ptrDraw->SetTextureResource(m_textures); SetDrawLayer(m_layer); auto ptrTrans = GetComponent<Transform>(); ptrTrans->SetPosition(m_pos); ptrTrans->SetScale(m_scale); SetAlphaActive(true); } void UI_Static_Image::SetTexture(const wstring& texture) { auto ptrDraw = GetComponent<PCTSpriteDraw>(); ptrDraw->SetTextureResource(texture); } void UI_Static_Image::SetTexture(const wstring& texture, Vec2& vertex) { m_xHalf = vertex.x / 2.0f; m_yHalf = vertex.y / 2.0f; m_vertices[0].position = Vec3(-m_xHalf, m_yHalf, 0.0f); m_vertices[1].position = Vec3(m_xHalf, m_yHalf, 0.0f); m_vertices[2].position = Vec3(-m_xHalf, -m_yHalf, 0.0f); m_vertices[3].position = Vec3(m_xHalf, -m_yHalf, 0.0f); auto ptrDraw = GetComponent<PCTSpriteDraw>(); ptrDraw->UpdateVertices(m_vertices); SetTexture(texture); } void UI_Static_Image::SetTexture(const wstring& texture, Vec2& vertex, const Vec3& scale) { SetScale(scale); SetTexture(texture, vertex); } void UI_Static_Image::SetPosition(const Vec3& pos) { m_pos = pos; auto ptrTrans = GetComponent<Transform>(); ptrTrans->SetPosition(pos); } void UI_Static_Image::SetScale(const Vec3& scale) { m_scale = scale; auto ptrTrans = GetComponent<Transform>(); ptrTrans->SetScale(scale); } void UI_Static_Image::SetColor(const Col4& color) { auto ptrDraw = GetComponent<PCTSpriteDraw>(); ptrDraw->SetDiffuse(color); } void UI_Static_Image::Hidden(bool e) { SetDrawActive(!e); SetUpdateActive(!e); } //------------------------------------------------------------------------------------------------ //水平なスプライト画像 : Class //------------------------------------------------------------------------------------------------ void UI_Horizontal_Sprite_Image::Draw() { Col4 color = Col4(1.0f, 1.0f, 1.0f, 1.0f); m_vertices.push_back(VertexPositionColorTexture(Vec3(-m_xHalf, m_yHalf, 0.0f), color, Vec2(0.0f, 0.0f))); m_vertices.push_back(VertexPositionColorTexture(Vec3(m_xHalf, m_yHalf, 0.0f), color, Vec2(1.0f, 0.0f))); m_vertices.push_back(VertexPositionColorTexture(Vec3(-m_xHalf, -m_yHalf, 0.0f), color, Vec2(0.0f, 1.0f))); m_vertices.push_back(VertexPositionColorTexture(Vec3(m_xHalf, -m_yHalf, 0.0f), color, Vec2(1.0f, 1.0f))); vector<uint16_t> indices = { 0, 1, 2, 1, 3, 2 }; auto ptrDraw = AddComponent<PCTSpriteDraw>(m_vertices, indices); ptrDraw->SetDiffuse(m_color); ptrDraw->SetTextureResource(m_textures); SetDrawLayer(m_layer); auto ptrTrans = GetComponent<Transform>(); ptrTrans->SetPosition(m_pos); ptrTrans->SetScale(m_scale); SetAlphaActive(true); UpdateVertices(); } void UI_Horizontal_Sprite_Image::SetIndex(int index) { if (index < 0) m_index = 0; if (index > GetMaxIndex()) m_index = GetMaxIndex(); m_index = index; UpdateVertices(); } void UI_Horizontal_Sprite_Image::UpdateVertices() { m_vertices[0].textureCoordinate = Vec2((m_index * m_cutOut.x) / m_vertex.x, 0.0f); m_vertices[1].textureCoordinate = Vec2(((m_index * m_cutOut.x) + m_cutOut.x) / m_vertex.x, 0.0f); m_vertices[2].textureCoordinate = Vec2((m_index * m_cutOut.x) / m_vertex.x, 1.0f); m_vertices[3].textureCoordinate = Vec2(((m_index * m_cutOut.x) + m_cutOut.x) / m_vertex.x, 1.0f); auto ptrDraw = GetComponent<PCTSpriteDraw>(); ptrDraw->UpdateVertices(m_vertices); } void UI_Horizontal_Sprite_Image::SetColor(const Col4& color) { auto ptrDraw = GetComponent<PCTSpriteDraw>(); ptrDraw->SetDiffuse(color); } void UI_Horizontal_Sprite_Image::Hidden(const bool e) { SetDrawActive(!e); SetUpdateActive(!e); } //------------------------------------------------------------------------------------------------ //キャラクターセレクトの選択マスク : Class //------------------------------------------------------------------------------------------------ void UI_Character_Select_Mask_Image::OnCreate() { Draw(); SetMaskIndex(m_maskIndex); } void UI_Character_Select_Mask_Image::OnUpdate() { MaskMove(); } void Result_UI::OnCreate() { Draw(); } void Score_UI::OnCreate() { float score = static_cast<float>(m_Score / m_place % 10); float Width = 69.1f / 691.0f; //各数字の幅をテクスチャ座標に変換 Col4 color = Col4(1.0f, 1.0f, 1.0f, 1.0f); vertices = { {Vec3(0, 0, 0), color, Vec2((score + 0) * Width, 0.0f)}, // 頂点1 {Vec3(50, 0, 0), color, Vec2((score + 1) * Width, 0.0f)}, // 頂点2 {Vec3(0, -100, 0), color, Vec2((score + 0) * Width, 1.0f)}, // 頂点3 {Vec3(50, -100, 0), color, Vec2((score + 1) * Width, 1.0f)}, // 頂点4 }; indices = {0, 1, 2, 2, 1, 3 }; auto ptrDraw = AddComponent<PCTSpriteDraw>(vertices, indices); ptrDraw->SetDiffuse(m_color); ptrDraw->SetTextureResource(m_textures); SetDrawLayer(m_layer); auto ptrTrans = GetComponent<Transform>(); ptrTrans->SetPosition(m_pos); ptrTrans->SetScale(m_scale); SetAlphaActive(true); } void Score_UI::OnUpdate2() { auto resultstage = dynamic_pointer_cast<ResultStage>(GetStage()); float n = static_cast<float>(resultstage->GetScore() / m_place % 10); // 表示したい数字 float w = 69.1f / 691.0f; // 各数字の幅をテクスチャ座標に変換する vertices[0].textureCoordinate.x = (n + 0) * w; vertices[1].textureCoordinate.x = (n + 1) * w; vertices[2].textureCoordinate.x = (n + 0) * w; vertices[3].textureCoordinate.x = (n + 1) * w; auto drawComp = GetComponent<PCTSpriteDraw>(); drawComp->UpdateVertices(vertices); // 頂点データを更新する } void UI_Character_Select_Mask_Image::MaskMove() { auto KeyState = App::GetApp()->GetInputDevice().GetKeyState(); auto cntlVec = App::GetApp()->GetInputDevice().GetControlerVec(); float fThumbLX = 0.0f; if (cntlVec[0].bConnected) { fThumbLX = cntlVec[0].fThumbLX; } if (KeyState.m_bPressedKeyTbl['A'] || (fThumbLX < 0.0f && m_oldFThumbLX == 0.0f)) { SetMaskIndex(--m_maskIndex); } if (KeyState.m_bPressedKeyTbl['D'] || (fThumbLX > 0.0f && m_oldFThumbLX == 0.0f)) { SetMaskIndex(++m_maskIndex); } m_oldFThumbLX = fThumbLX; } void UI_Character_Select_Mask_Image::SetMaskIndex(int& index) { if (index < m_indexMin) index = m_indexMax; if (index > m_indexMax) index = m_indexMin; auto trans = GetComponent<Transform>(); auto pos = trans->GetPosition(); pos.x = m_startPosX + (index * m_movingValue); trans->SetPosition(pos); } //------------------------------------------------------------------------------------------------ //タブ : Class //------------------------------------------------------------------------------------------------ void UI_Tab::OnCreate() { CreateTab(); CreateMasks(); SetMaskIndex(m_maskIndex); } void UI_Tab::OnUpdate() { MaskMove(); } void UI_Tab::Show(bool e) { Hidden(!e); if(e) SetMaskIndex(m_maskIndex); } void UI_Tab::Hidden(bool e) { if (!m_tab) return; m_tab->SetDrawActive(!e); for (auto& mask : m_masks) mask->SetDrawActive(!e); SetUpdateActive(!e); } void UI_Tab::CreateTab() { m_tab = GetStage()->AddGameObject<UI_Static_Image>( /*Vec2(1337.05f, 41.6f),*/ Vec2(2048.0f * m_magnification, 64.0f * m_magnification), m_pos, Vec3(1.0f, 1.0f, 1.0f), m_layer, Col4(1.0f, 1.0f, 1.0f, 1.0f), m_tabImageName ); } void UI_Tab::CreateMasks() { Vec2 size = Vec2(512.0f, 64.0f) * m_magnification; for (int i = 0; i <= m_indexMax; i++) { auto mask = GetStage()->AddGameObject<UI_Static_Image>( size, /*Vec3(m_pos.x - ((size.x + (size.x / 2.0f) + m_space + m_space) - ((size.x + m_space) * i)), m_pos.y, m_pos.z),*/ Vec3(m_pos.x - ((size.x + (size.x / 2.0f)) - (size.x * i)), m_pos.y, m_pos.z), Vec3(1.0f, 1.0f, 1.0f), m_layer, Col4(1.0f, 1.0f, 1.0f, 0.85f), m_tabMaskImageName ); m_masks.push_back(mask); } } void UI_Tab::MaskMove() { auto cntlVec = App::GetApp()->GetInputDevice().GetControlerVec(); float fThumbLX = 0.0f; if (cntlVec[0].bConnected) { fThumbLX = cntlVec[0].fThumbLX; } auto KeyState = App::GetApp()->GetInputDevice().GetKeyState(); if (KeyState.m_bPressedKeyTbl['A'] || (fThumbLX < 0.0f && m_oldFThumbLX == 0.0f)) { SetMaskIndex(--m_maskIndex); } if (KeyState.m_bPressedKeyTbl['D'] || (fThumbLX > 0.0f && m_oldFThumbLX == 0.0f)) { SetMaskIndex(++m_maskIndex); } m_oldFThumbLX = fThumbLX; } void UI_Tab::SetMaskIndex(int& index) { if (index < m_indexMin) index = m_indexMax; if (index > m_indexMax) index = m_indexMin; for (int i = 0; i <= m_indexMax; i++) m_masks[i]->SetDrawActive(true); auto& mask = m_masks[index]; mask->SetDrawActive(false); } //------------------------------------------------------------------------------------------------ //食材アイコン : Class //------------------------------------------------------------------------------------------------ void UI_Food_Icon::OnCreate() { Draw(); } void UI_Food_Icon::SetCharacter(CharacterType type, int level) { if (level < 1) level = 1; if (level > 3) level = 3; m_type = type; m_level = level - 1; int index = 0; switch (m_type) { case CharacterType::SHRIMP: index = 3; break; case CharacterType::CHICKEN: index = 6; break; case CharacterType::DOUGHNUT: index = 9; break; } index += m_level; SetIndex(index); } //------------------------------------------------------------------------------------------------ //スコア表 : Class //------------------------------------------------------------------------------------------------ void UI_Score_Table::Show(bool e) { m_isShow = e; Hidden(!e); if (!e) return; UpdateTable(); if (!m_isCreate) { CreateTableHeader(); m_isCreate = true; } Sort(); for (int i = m_lines.size(); i < m_characterStatuses.size(); i++) { CreateLine(m_characterStatuses[i], i); } } void UI_Score_Table::SetCharacterStatus(const CharacterStatus_s& status) { vector<CharacterStatus_s>::iterator it = find_if(m_characterStatuses.begin(), m_characterStatuses.end(), [status](const CharacterStatus_s& i) { return i.unique == status.unique; }); it->type = status.type; it->kill = status.kill; it->death = status.death; it->score = status.score; it->isPlayer = status.isPlayer; UpdateTable(); } void UI_Score_Table::ChangeLogo(const shared_ptr<UI_Static_Image>& image, const CharacterType& type) { switch (type) { case CharacterType::CHICKEN: image->SetTexture(L"ChickenLogo.png", Vec2(631.0f, 278.0f), Vec3(0.2f)); break; case CharacterType::DOUGHNUT: image->SetTexture(L"DoughnutLogo.png", Vec2(631.0f, 264.0f), Vec3(0.2f)); break; case CharacterType::POTATO: image->SetTexture(L"PotatoLogo.png", Vec2(621.0f, 285.0f), Vec3(0.2f)); break; case CharacterType::SHRIMP: image->SetTexture(L"ShrimpLogo.png", Vec2(631.0f, 298.0f), Vec3(0.2f)); break; default: break; } } void UI_Score_Table::CreateTableHeader() { float i = 363.0f; float iPlus = 330.0f; float t = 250.0f; float b = 380.0f; auto stage = GetStage(); auto text = stage->AddGameObject<UI_Sprite_Text>( m_fontName, m_headerFontSize, m_white, Rect2D<float>(i + (iPlus * 0 - 500.0f), t, 1000.0f, b), StringSprite::TextAlignment::m_Center, L"ランク", m_layer, false ); m_headerTexts.push_back(text); text = stage->AddGameObject<UI_Sprite_Text>( m_fontName, m_headerFontSize, m_white, Rect2D<float>(i + (iPlus * 1 + 250.0f), t, 1080.0f, b), StringSprite::TextAlignment::m_Center, L"キル", m_layer, false ); m_headerTexts.push_back(text); text = stage->AddGameObject<UI_Sprite_Text>( m_fontName, m_headerFontSize, m_white, Rect2D<float>(i + (iPlus * 2 + 125.0f), t, 1330.0f, b), StringSprite::TextAlignment::m_Center, L"デス", m_layer, false ); m_headerTexts.push_back(text); text = stage->AddGameObject<UI_Sprite_Text>( m_fontName, m_headerFontSize, m_white, Rect2D<float>(i + (iPlus * 3), t, 1620.0f, b), StringSprite::TextAlignment::m_Center, L"スコア", m_layer, false ); m_headerTexts.push_back(text); } void UI_Score_Table::CreateLine(CharacterStatus_s& status, int index) { float space = 80.0f; float i = 363.0f; float iPlus = 337.0f; float t = 330.0f; float b = 330.0f; auto stage = GetStage(); ScoreTableLine_s line; if (index) { auto separator = stage->AddGameObject<UI_Static_Image>( Vec2(1200.0f, 1.0f), Vec3(0.0f, 220.0f - (index * space), 0.0f), Vec3(1.0f, 1.0f, 1.0f), m_layer, m_white, m_separatorImageName ); line.separator = separator; } else { auto separator = stage->AddGameObject<UI_Static_Image>( Vec2(1200.0f, 3.0f), Vec3(0.0f, 220.0f - (index * space), 0.0f), Vec3(1.0f, 1.0f, 1.0f), m_layer, m_white, m_separatorImageName ); line.separator = separator; } auto rank = stage->AddGameObject<UI_Number>( Vec2(-525.0f, 180.0f - (index * 80.0f)), 1, Col4(1.0f), Number::NumberAlign::CENTER, 0.0f, Vec2(0.4f), m_layer ); rank->SetValue(index + 1); m_ranks.push_back(rank); auto playerBadge = stage->AddGameObject<UI_Static_Image>( Vec2(64.0f, 32.0f), Vec3(-650.0f, 175.0f - (index * space), 0.0f), Vec3(1.0f, 1.0f, 1.0f), m_layer, m_white, m_playerBadgeImageName ); playerBadge->Hidden(!status.isPlayer); line.playerBadge = playerBadge; shared_ptr<UI_Static_Image> logo = stage->AddGameObject<UI_Static_Image>( Vec2(64.0f, 32.0f), Vec3(-260.0f, 180.0f - (index * space), 0.0f), Vec3(0.2f), m_layer, m_white, L"dot.png" ); ChangeLogo(logo, status.type); line.logo = logo; /* auto text = stage->AddGameObject<UI_Sprite_Text>( m_fontName, m_lineFontSize, m_white, Rect2D<float>(i + 180.0f, t + (index * space), 1556.0f, b + (index * space)), StringSprite::TextAlignment::m_Left, GetCharacterTypeToString(status.type), m_layer, false ); line.name = text;*/ auto number = stage->AddGameObject<UI_Number>( Vec2(50.0f, 180.0f - (index * 80.0f)), 5, Col4(1.0f), Number::NumberAlign::CENTER, 10.0f, Vec2(0.4f), m_layer ); number->SetValue(status.kill); line.kill = number; number = stage->AddGameObject<UI_Number>( Vec2(280.0f, 180.0f - (index * 80.0f)), 5, Col4(1.0f), Number::NumberAlign::CENTER, 10.0f, Vec2(0.4f), m_layer ); number->SetValue(status.death); line.death = number; number = stage->AddGameObject<UI_Number>( Vec2(520.0f, 180.0f - (index * 80.0f)), 5, Col4(1.0f), Number::NumberAlign::CENTER, 10.0f, Vec2(0.4f), m_layer ); number->SetValue(status.score); line.score = number; m_lines.push_back(line); } void UI_Score_Table::UpdateTable() { if (!m_isShow) return; Sort(); for (int i = 0; i < m_lines.size(); i++) { auto& status = m_characterStatuses[i]; auto& line = m_lines[i]; ChangeLogo(line.logo, status.type); //line.name->UpdateText(GetCharacterTypeToString(status.type)); line.kill->SetValue(status.kill); line.death->SetValue(status.death); line.score->SetValue(status.score); line.playerBadge->Hidden(!status.isPlayer); } } void UI_Score_Table::Sort() { sort(m_characterStatuses.begin(), m_characterStatuses.end(), [](const CharacterStatus_s& a, const CharacterStatus_s& b) { return a.score > b.score; }); } void UI_Score_Table::Hidden(bool e) { for (auto& text : m_headerTexts) text->SetDrawActive(!e); for (auto& rank : m_ranks) rank->Hidden(e); for (auto& line : m_lines) { line.logo->Hidden(e); line.kill->Hidden(e); line.death->Hidden(e); line.score->Hidden(e); line.playerBadge->SetDrawActive(!e); line.separator->SetDrawActive(!e); } } //------------------------------------------------------------------------------------------------ //キル詳細 : Class //------------------------------------------------------------------------------------------------ void UI_Kill_Details::Show(bool e) { m_isShow = e; Hidden(!e); if (!e || !m_characterStatusKillDetails.size()) { return; } UpdateInfo(); if (!m_isCreate) { CreateInfo(); m_isCreate = true; } for (int i = m_icons.size(); i < m_characterStatusKillDetails.size(); i++) { CreateKillIcon(m_characterStatusKillDetails[i], i); } } void UI_Kill_Details::CreateKillIcon(CharacterKillDetails_s& details, int index) { Vec3 pos = Vec3(-625.0f, -215.0f, 0.0f); Vec2 size = Vec2(256.0f, 256.0f); Vec3 scale = Vec3(0.5f, 0.5f, 0.5f); int digit = GetDigit(index); if (digit > 1) digit--; auto icon = GetStage()->AddGameObject<UI_Food_Icon>( Vec3(pos.x + ((size.x * scale.x + 10.0f) * (index % (int)pow(10, digit))), -(pos.y + ((index / 10) * (size.x * scale.x + 10.0f))), pos.z), scale, m_layer ); icon->SetCharacter(details.type, details.level); m_icons.push_back(icon); } void UI_Kill_Details::CreateInfo() { auto stage = GetStage(); m_killText = stage->AddGameObject<UI_Sprite_Text>( m_fontName, m_infoFontSize, m_white, Rect2D<float>(900.0f, 1000.0f, 1300.0f, m_infoFontSize + 18.0f + 1000.0f), StringSprite::TextAlignment::m_Center, L"キル: " + to_wstring(m_characterStatusKillDetails.size()), m_layer, false ); m_scoreText = stage->AddGameObject<UI_Sprite_Text>( m_fontName, m_infoFontSize, m_white, Rect2D<float>(1300.0f, 1000.0f, 1700.0f, m_infoFontSize + 18.0f + 1000.0f), StringSprite::TextAlignment::m_Left, L"スコア: " + to_wstring(m_score), m_layer, false ); } void UI_Kill_Details::UpdateInfo() { if (!m_killText || !m_scoreText || !m_isShow) return; m_killText->UpdateText(L"キル: " + to_wstring(m_characterStatusKillDetails.size())); m_scoreText->UpdateText(L"スコア: " + to_wstring(m_score)); } void UI_Kill_Details::Hidden(bool e) { for (auto& icon : m_icons) icon->SetDrawActive(!e); if (!m_killText || !m_scoreText) return; m_killText->SetDrawActive(!e); m_scoreText->SetDrawActive(!e); } int UI_Kill_Details::GetDigit(int num) { int digit = 0; while (num != 0) { num /= 10; digit++; } return digit; } //------------------------------------------------------------------------------------------------ //ポーズ画面 : Class //------------------------------------------------------------------------------------------------ void UI_The_World::OnCreate() { auto stage = GetStage(); m_scoreTable = stage->AddGameObject<UI_Score_Table>(8, m_layer); m_scoreTable->SetCharacterStatuses(m_characterStatuses); m_killDetails = stage->AddGameObject<UI_Kill_Details>(m_layer); } void UI_The_World::OnUpdate() { Key(); } void UI_The_World::OnUpdate2() { ChangeTab(); } void UI_The_World::Show(bool e) { m_isShow = e; if (!e) { AllHidden(!e); m_oldIndex = -1; return; } ShowBase(e); ShowTitle(e); ShowTab(e); ShowBack(e); } void UI_The_World::AllHidden(bool e) { ShowBase(!e); ShowTitle(!e); ShowTab(!e); m_scoreTable->Show(!e); ShowOperation(!e); m_killDetails->Show(!e); ShowTitleback(!e); ShowBack(!e); } void UI_The_World::ChangeTab() { if (!m_isShow) return; m_index = m_tab->GetIndex(); if (m_index == m_oldIndex) return; switch (m_index) { case 0: m_scoreTable->Show(true); ShowOperation(false); m_killDetails->Show(false); ShowTitleback(false); break; case 1: m_scoreTable->Show(false); ShowOperation(true); m_killDetails->Show(false); ShowTitleback(false); break; case 2: m_scoreTable->Show(false); ShowOperation(false); m_killDetails->Show(true); m_killDetails->SetScore(m_scoreTable->GetPlayerStatus().score); ShowTitleback(false); break; case 3: m_scoreTable->Show(false); ShowOperation(false); m_killDetails->Show(false); ShowTitleback(true); break; } m_oldIndex = m_index; } void UI_The_World::ShowBase(bool e) { if (!m_base && !e) return; if (m_base) { m_base->Hidden(!e); } else { m_base = GetStage()->AddGameObject<UI_Static_Image>( Vec2(1920.0f, 1080.0f), Vec3(0.0f, 0.0f, 0.0f), Vec3(1.0f, 1.0f, 1.0f), m_baseLayer, Col4(1.0f, 1.0f, 1.0f, 0.9f), m_baseImageName ); } } void UI_The_World::ShowTab(bool e) { if (!m_tab && !e) return; if (m_tab) { m_tab->Show(e); } else { m_tab = GetStage()->AddGameObject<UI_Tab>(Vec3(0.0f, 400.0f, 0.0f), 0.7f, m_layer); } } void UI_The_World::ShowTitle(bool e) { if (!m_title && !e) return; if (m_title) { m_title->Hidden(!e); } else { m_title = GetStage()->AddGameObject<UI_Static_Image>( Vec2(531.0f, 171.0f), Vec3(0.0f, 485.0f, 0.0f), Vec3(0.4f), m_layer, m_white, m_titleImageName ); } } void UI_The_World::ShowOperation(bool e) { if (m_operation) { m_operation->Hidden(!e); } else { m_operation = GetStage()->AddGameObject<UI_Static_Image>( Vec2(1280.0f, 720.0f), Vec3(0.0f, -80.0f, 0.0f), Vec3(1.0f), m_layer, m_white, m_operationImageName ); ShowOperation(e); } } void UI_The_World::ShowTitleback(bool e) { if (m_titleback) { m_titleback->Hidden(!e); m_selectback->Hidden(!e); } else { m_titleback = GetStage()->AddGameObject<UI_Static_Image>( Vec2(532.0f, 147.0f), Vec3(0.0f, -180.0f, 0.0f), Vec3(0.8f), m_layer, m_white, m_titlebackImageName ); m_selectback = GetStage()->AddGameObject<UI_Static_Image>( Vec2(524.0f, 147.0f), Vec3(0.0f, 100.0f, 0.0f), Vec3(0.8f), m_layer, m_white, m_selectbackImageName ); ShowTitleback(e); } } void UI_The_World::ShowBack(bool e) { if (m_return && m_move) { m_return->Hidden(!e); m_move->Hidden(!e); } else { m_return = GetStage()->AddGameObject<UI_Static_Image>( Vec2(614.0f, 82.0f), Vec3(-820.0f, -450.0f, 0.0f), Vec3(0.4f, 0.4f, 0.4f), m_layer, m_white, m_returnImageName ); m_move = GetStage()->AddGameObject<UI_Static_Image>( Vec2(825.0f, 83.0f), Vec3(-779.0f, -500.0f, 0.0f), Vec3(0.4f, 0.4f, 0.4f), m_layer, m_white, m_moveImageName ); ShowBack(e); } } void UI_The_World::Key() { auto KeyState = App::GetApp()->GetInputDevice().GetKeyState(); auto cntlVec = App::GetApp()->GetInputDevice().GetControlerVec(); if (m_index == 3 && (KeyState.m_bPressedKeyTbl['Q'] || cntlVec[0].wPressedButtons & XINPUT_GAMEPAD_A)) { //App::GetApp()->GetScene<Scene>()->SetGameStage(GameStageKey::title); } if (m_index == 3 && (KeyState.m_bPressedKeyTbl['E'] || cntlVec[0].wPressedButtons & XINPUT_GAMEPAD_B)) { //App::GetApp()->GetScene<Scene>()->SetGameStage(GameStageKey::charSelect); } /*if (KeyState.m_bPressedKeyTbl['P'] || cntlVec[0].wPressedButtons & XINPUT_GAMEPAD_X) { Show(false); }*/ } //------------------------------------------------------------------------------------------------ //キャラクターステータス : Class //------------------------------------------------------------------------------------------------ void UI_Character_Status::OnCreate() { SetDrawLayer(m_layer); Mat4x4 mat; mat.affineTransformation( Vec3(1.0f, 1.0f, 1.0f), Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f) ); SetToAnimeMatrix(mat); auto PtrTrans = GetComponent<Transform>(); PtrTrans->SetScale(m_scale); PtrTrans->SetPosition(m_pos); SS5ssae::OnCreate(); } void UI_Character_Status::OnUpdate() { float time = App::GetApp()->GetElapsedTime(); UpdateAnimeTime(time); } void UI_Character_Status::ChangeCharacterStatus(CharacterType type) { wstring animName = L""; float time = 0.0f; switch (type) { case basecross::POTATO: animName = L"Status_ver2_Potato"; break; case basecross::SHRIMP: animName = L"Status_ver2_Shrimp"; break; case basecross::CHICKEN: animName = L"Status_ver2_Chicken"; break; case basecross::DOUGHNUT: animName = L"Status_ver2_Doughnut"; break; } ChangeAnimation(animName, time); SetFps(15.0f); SetLooped(false); } //------------------------------------------------------------------------------------------------ //PinP : Class //------------------------------------------------------------------------------------------------ void PinP::OnCreate() { CreateCamera(); if (m_isEdge && !m_edgeImage) CreateEdge(); m_oldShowViewTopLeftPos = m_showViewTopLeftPos; m_oldHideViewTopLeftPos = m_hideViewTopLeftPos; Hidden(true); } void PinP::OnUpdate() { if (m_isEdge && !m_edgeImage) CreateEdge(); m_camera->OnUpdate(); Move(); } Vec2 PinP::GetResolution() { switch (m_aspectType) { case PinPAspectType::SQUARE: return Vec2(1.0f, 1.0f); case PinPAspectType::HD: return Vec2(16.0f, 9.0f); case PinPAspectType::SD: return Vec2(4.0f, 3.0f); } } void PinP::In(const PinPAction action) { m_mode = true; m_active = true; m_action = action; m_showViewTopLeftPos = m_oldShowViewTopLeftPos; m_hideViewTopLeftPos = GetHideTopLeftPos(action); //UpdateEdge(Vec2(m_hideViewTopLeftPos.x, m_hideViewTopLeftPos.y)); //if(m_edgeImage) m_edgeImage->Hidden(false); SetViewTopLeftPos(m_hideViewTopLeftPos); } void PinP::Out(const PinPAction action) { m_mode = false; m_active = true; m_action = action; m_showViewTopLeftPos = m_oldShowViewTopLeftPos; m_hideViewTopLeftPos = GetHideTopLeftPos(action); SetViewTopLeftPos(m_showViewTopLeftPos); } void PinP::Hidden(const bool e) { m_active = !e; auto& app = App::GetApp(); m_edgeImage->Hidden(e); if (e) { auto zero = Vec2(app->GetGameWidth(), app->GetGameHeight()); m_showViewTopLeftPos = zero; m_hideViewTopLeftPos = zero; SetViewTopLeftPos(zero); } else { if (m_useCharacter.unique != 0) In(m_action); } } void PinP::SetAt(const Vec3& at) { m_camera->SetAt(at); } void PinP::SetEye(const Vec3& eye) { m_camera->SetEye(eye); } void PinP::CreateCamera() { auto resolution = GetResolution(); resolution.x *= m_scale; resolution.y *= m_scale; m_view = { m_showViewTopLeftPos.x, m_showViewTopLeftPos.y, resolution.x, resolution.y, 0.0f, 1.0f }; m_camera = ObjectFactory::Create<Camera>(); m_camera->SetViewPort(m_view); m_camera->CalculateMatrix(); m_camera->SetNear(2); auto viewPort = dynamic_pointer_cast<MultiView>(GetStage()->GetView()); m_viewIndex = viewPort->AddView(m_view, m_camera); } void PinP::CreateEdge() { auto resolution = GetResolution(); resolution.x *= m_scale; resolution.y *= m_scale; m_edgeImage = GetStage()->AddGameObject<UI_Static_Image>( resolution, Vec3(0.0f), Vec3(m_edgeScale), m_edgeLayer, m_edgeColor, m_edgeImageName ); m_edgeImage->Hidden(true); } void PinP::UpdateEdge(const Vec2& pos) { if (!m_edgeImage || !m_active) return; if (!m_edgeImage->GetDrawActive()) m_edgeImage->Hidden(false); auto& app = App::GetApp(); auto halfGame = Vec2(app->GetGameWidth() / 2.0f, app->GetGameHeight() / 2.0f); auto resolution = GetResolution(); resolution.x *= m_scale; resolution.y *= m_scale; auto halfResolution = Vec2(resolution.x / 2.0f, resolution.y / 2.0f); auto movePos = Vec3(0.0f); if (pos.x <= halfGame.x) movePos.x = (pos.x + halfResolution.x) - halfGame.x; if (pos.x >= halfGame.x) movePos.x = halfGame.x + pos.x; if (pos.y <= halfGame.y) movePos.y = halfGame.y - (pos.y + halfResolution.y); if (pos.y >= halfGame.y) movePos.y = pos.y + halfGame.y; m_edgeImage->SetPosition(movePos); } Vec2 PinP::GetHideTopLeftPos(const PinPAction action) { auto& app = App::GetApp(); auto w = app->GetGameWidth(); auto h = app->GetGameHeight(); switch (action) { case PinPAction::LEFT: return Vec2(-(m_view.Width + m_showViewTopLeftPos.x), m_showViewTopLeftPos.y); case PinPAction::RIGHT: return Vec2(w, m_showViewTopLeftPos.y); case PinPAction::TOP: return Vec2(m_showViewTopLeftPos.x, -(m_view.Height + m_showViewTopLeftPos.y)); case PinPAction::UNDER: return Vec2(m_showViewTopLeftPos.x, h); case PinPAction::NONE: return Vec2(m_showViewTopLeftPos.x, m_showViewTopLeftPos.y); } } void PinP::SetViewTopLeftPos(Vec2& pos) { auto viewPort = dynamic_pointer_cast<MultiView>(GetStage()->GetView()); m_view.TopLeftX = pos.x; m_view.TopLeftY = pos.y; viewPort->SetViewport(m_viewIndex, m_view); } Viewport PinP::GetView() { return dynamic_pointer_cast<MultiView>(GetStage()->GetView())->GetViewport(m_viewIndex); } void PinP::Move() { auto time = App::GetApp()->GetElapsedTime(); Easing<Vec2> easing; //現在のTopLeftPosを取得する Vec2 nowTopLeftPos(m_view.TopLeftX, m_view.TopLeftY); Vec2 movePos(0.0f); if (m_active && m_mode) { movePos = easing.Linear(Vec2(nowTopLeftPos.x, nowTopLeftPos.y), m_showViewTopLeftPos, time, 0.4); SetViewTopLeftPos(movePos); UpdateEdge(movePos); } if(m_active && !m_mode) { movePos = easing.Linear(Vec2(nowTopLeftPos.x, nowTopLeftPos.y), m_hideViewTopLeftPos, time, 0.4); SetViewTopLeftPos(movePos); UpdateEdge(movePos); } } //------------------------------------------------------------------------------------------------ //数字 : Class //------------------------------------------------------------------------------------------------ void UI_Number::OnCreate() { CreateNumberImagies(); } void UI_Number::SetValue(const unsigned int value) { m_value = value; UpdateNumberImagies(); } void UI_Number::SetColor(const Col4& color) { m_color = color; UpdateNumberImagies(); } void UI_Number::Hidden(const bool e) { for (auto& image : m_numberImagies) { image->Hidden(e); } SetDrawActive(!e); SetUpdateActive(!e); } void UI_Number::CreateNumberImagies() { auto stage = GetStage(); for (int i = 0; i < m_digit; i++) { auto pos = GetImagePosition(m_digit, i, m_position, m_align); auto number = GetNumber(m_value, (m_digit - 1) - i); auto image = stage->AddGameObject<UI_Horizontal_Sprite_Image>( m_vertex, Vec3(pos), Vec3(m_scale), m_layer, m_color, m_numberImageName, m_cutOut ); image->Draw(); image->SetIndex(number); m_numberImagies.push_back(image); } UpdateNumberImagies(); } void UI_Number::UpdateNumberImagies() { for (int i = 0; i < m_numberImagies.size(); i++) { auto number = GetNumber(m_value, (m_digit - 1) - i); auto image = m_numberImagies[i]; image->SetColor(m_color); image->SetIndex(number); image->Hidden(false); } if (m_align == Number::NumberAlign::LEFT || m_align == Number::NumberAlign::CENTER || m_align == Number::NumberAlign::RIGHT) { auto zeroEndIndex = 0; for (auto& image : m_numberImagies) { if (!image->GetIndex() && zeroEndIndex + 1 != m_numberImagies.size()) { image->Hidden(true); zeroEndIndex++; } else { break; } } if (m_align == Number::NumberAlign::CENTER || m_align == Number::NumberAlign::RIGHT) { for (int i = zeroEndIndex, j = 0; i < m_numberImagies.size(); i++, j++) { auto image = m_numberImagies[i]; auto trans = image->GetComponent<Transform>(); auto pos = GetImagePosition(m_digit - zeroEndIndex ,j, m_position, m_align); trans->SetPosition(Vec3(pos)); } } } } unsigned int UI_Number::CheckDigit(const unsigned int value) { unsigned int digit = 0; unsigned int target = value; while (target) { target /= 10; digit++; } return digit; } Vec2 UI_Number::GetImagePosition(const unsigned int digit, const unsigned int index, const Vec2& startPosition, const Number::NumberAlign align) { auto res = Vec2(startPosition.x, startPosition.y); float c, d, t, e; switch (align) { case Number::NumberAlign::LEFT: case Number::NumberAlign::ZERO_LEFT: c = (digit - 1); d = c * m_cutOut.x; t = index * m_cutOut.x + (m_space * index); e = t - d; res.x += (e * m_scale.x) - (m_space * c * (m_scale.x)); break; case Number::NumberAlign::CENTER: case Number::NumberAlign::ZERO_CENTER: c = ((digit - 1) / 2.0f); d = c * m_cutOut.x; t = index * m_cutOut.x + (m_space * index); e = t - d; res.x += (e * m_scale.x) - (m_space * c * (m_scale.x)); break; case Number::NumberAlign::RIGHT: case Number::NumberAlign::ZERO_RIGHT: res.x += ((m_cutOut.x + m_space) * m_scale.x) * index; break; } return res; } unsigned int UI_Number::GetNumber(const unsigned int value, const unsigned int index) { auto res = 0; res = (value / pow(10, index)); res %= 10; return res; } //------------------------------------------------------------------------------------------------ //プレイヤーUI : Class //------------------------------------------------------------------------------------------------ void UI_Player::OnCreate() { Draw(); } void UI_PlayerGun::OnCreate() { Draw(); } void UI_PlayerGun::OnUpdate() { bool weapon = GetStage()->GetSharedGameObject<Player>(L"Player")->GetGun(); auto trans = GetComponent<Transform>(); if (weapon) { trans->SetScale(m_scale); } else { trans->SetScale(Vec3(-m_scale.x, m_scale.y, m_scale.z)); } } void UI_PlayerWeapon::OnCreate() { Draw(); } void UI_PlayerWeapon::OnUpdate() { int index; if (m_weapon) { index = GetStage()->GetSharedGameObject<Player>(L"Player")->GetWeaponO(); } else { index = GetStage()->GetSharedGameObject<Player>(L"Player")->GetWeaponT(); } SetIndex(index); } void UI_PlayerGrenade::OnCreate() { Draw(); X = Vec2(1.0f,-1.0f) * m_Vertex.x / 2.0f; Y = m_Vertex.y / 2.0f; } void UI_PlayerGrenade::OnUpdate() { float time; if (m_type) { time = GetStage()->GetSharedGameObject<Player>(L"Player")->GetSGTime(); } else { time = GetStage()->GetSharedGameObject<Player>(L"Player")->GetTGTime(); } if (time < m_time) { X.y = time / m_time; X.y = (m_Vertex.x * X.y) - X.x; vector<VertexPositionColorTexture> vertices; Col4 color = Col4(1.0f, 1.0f, 1.0f, 1.0f); vertices.push_back(VertexPositionColorTexture(Vec3(-X.y, Y, 0), color, Vec2(0.0f, 0.0f))); vertices.push_back(VertexPositionColorTexture(Vec3(X.x, Y, 0), color, Vec2(1.0f, 0.0f))); vertices.push_back(VertexPositionColorTexture(Vec3(-X.y, -Y, 0), color, Vec2(0.0f, 1.0f))); vertices.push_back(VertexPositionColorTexture(Vec3(X.x, -Y, 0), color, Vec2(1.0f, 1.0f))); auto ptrDraw = GetComponent<PCTSpriteDraw>(); ptrDraw->UpdateVertices(vertices); } } void UI_PlayerAmmo::OnCreate() { float xPiecesize = 1.0f / (float)m_NumberOfDigits; float helfSize = 0.5f; vector<uint16_t> indices; for (UINT i = 0; i < m_NumberOfDigits; i++) { float vertex0 = -helfSize + xPiecesize * (float)i; float vertex1 = vertex0 + xPiecesize; m_BackupVertices.push_back(VertexPositionTexture(Vec3(vertex0, helfSize, 0), Vec2(0.0f, 0.0f))); m_BackupVertices.push_back(VertexPositionTexture(Vec3(vertex1, helfSize, 0), Vec2(0.1f, 0.0f))); m_BackupVertices.push_back(VertexPositionTexture(Vec3(vertex0, -helfSize, 0), Vec2(0.0f, 1.0f))); m_BackupVertices.push_back(VertexPositionTexture(Vec3(vertex1, -helfSize, 0), Vec2(0.1f, 1.0f))); indices.push_back(i * 4 + 0); indices.push_back(i * 4 + 1); indices.push_back(i * 4 + 2); indices.push_back(i * 4 + 1); indices.push_back(i * 4 + 3); indices.push_back(i * 4 + 2); } auto ptrTrans = GetComponent<Transform>(); ptrTrans->SetPosition(m_pos); ptrTrans->SetScale(m_scale); auto ptrDraw = AddComponent<PTSpriteDraw>(m_BackupVertices, indices); ptrDraw->SetTextureResource(m_TextureKey); ptrDraw->SetDiffuse(Col4(0.2f, 0.2f, 0.2f, 1.0f)); SetDrawLayer(15); SetAlphaActive(true); } void UI_PlayerAmmo::OnUpdate() { vector<VertexPositionTexture> newVertices; UINT num; int verNum = 0; auto player = GetStage()->GetSharedGameObject<Player>(L"Player"); float ammo; m_gun = player->GetGun(); if (m_rem) { if (m_gun) { ammo = player->GetAmmoO(); } else { ammo = player->GetAmmoT(); } } else { if (m_gun) { ammo = player->GetDAmmoO(); } else { ammo = player->GetDAmmoT(); } } if (ammo < 10) { m_NumberOfDigits = 1; } else if (ammo < 100) { m_NumberOfDigits = 2; } else if(ammo < 1000) { m_NumberOfDigits = 3; } else { m_NumberOfDigits = 4; } for (UINT i = m_NumberOfDigits; i > 0; i--) { UINT base = (UINT)pow(10, i); num = ((UINT)ammo) % base; num = num / (base / 10); Vec2 uv0 = m_BackupVertices[verNum].textureCoordinate; uv0.x = (float)num / 10.0f; auto v = VertexPositionTexture(m_BackupVertices[verNum].position, uv0); newVertices.push_back(v); Vec2 uv1 = m_BackupVertices[verNum + 1].textureCoordinate; uv1.x = uv0.x + 0.1f; v = VertexPositionTexture(m_BackupVertices[verNum + 1].position, uv1); newVertices.push_back(v); Vec2 uv2 = m_BackupVertices[verNum + 2].textureCoordinate; uv2.x = uv0.x; v = VertexPositionTexture(m_BackupVertices[verNum + 2].position, uv2); newVertices.push_back(v); Vec2 uv3 = m_BackupVertices[verNum + 3].textureCoordinate; uv3.x = uv0.x + 0.1f; v = VertexPositionTexture(m_BackupVertices[verNum + 3].position, uv3); newVertices.push_back(v); verNum += 4; } auto ptrDraw = GetComponent<PTSpriteDraw>(); ptrDraw->UpdateVertices(newVertices); } void UI_PlayerGatling::OnCreate() { Draw(); } void UI_PlayerGatlingAmmo::OnCreate() { float xPiecesize = 1.0f / (float)m_NumberOfDigits; float helfSize = 0.5f; vector<uint16_t> indices; for (UINT i = 0; i < m_NumberOfDigits; i++) { float vertex0 = -helfSize + xPiecesize * (float)i; float vertex1 = vertex0 + xPiecesize; m_BackupVertices.push_back(VertexPositionTexture(Vec3(vertex0, helfSize, 0), Vec2(0.0f, 0.0f))); m_BackupVertices.push_back(VertexPositionTexture(Vec3(vertex1, helfSize, 0), Vec2(0.1f, 0.0f))); m_BackupVertices.push_back(VertexPositionTexture(Vec3(vertex0, -helfSize, 0), Vec2(0.0f, 1.0f))); m_BackupVertices.push_back(VertexPositionTexture(Vec3(vertex1, -helfSize, 0), Vec2(0.1f, 1.0f))); indices.push_back(i * 4 + 0); indices.push_back(i * 4 + 1); indices.push_back(i * 4 + 2); indices.push_back(i * 4 + 1); indices.push_back(i * 4 + 3); indices.push_back(i * 4 + 2); } auto ptrTrans = GetComponent<Transform>(); ptrTrans->SetPosition(m_pos); ptrTrans->SetScale(m_scale); auto ptrDraw = AddComponent<PTSpriteDraw>(m_BackupVertices, indices); ptrDraw->SetTextureResource(m_TextureKey); ptrDraw->SetDiffuse(Col4(1.0f, 1.0f, 1.0f, 1.0f)); SetDrawLayer(15); SetAlphaActive(true); } void UI_PlayerGatlingAmmo::OnUpdate() { vector<VertexPositionTexture> newVertices; UINT num; int verNum = 0; auto player = GetStage()->GetSharedGameObject<Player>(L"Player"); float ammo = player->GetGatlingAmmo(); for (UINT i = m_NumberOfDigits; i > 0; i--) { UINT base = (UINT)pow(10, i); num = ((UINT)ammo) % base; num = num / (base / 10); Vec2 uv0 = m_BackupVertices[verNum].textureCoordinate; uv0.x = (float)num / 10.0f; auto v = VertexPositionTexture(m_BackupVertices[verNum].position, uv0); newVertices.push_back(v); Vec2 uv1 = m_BackupVertices[verNum + 1].textureCoordinate; uv1.x = uv0.x + 0.1f; v = VertexPositionTexture(m_BackupVertices[verNum + 1].position, uv1); newVertices.push_back(v); Vec2 uv2 = m_BackupVertices[verNum + 2].textureCoordinate; uv2.x = uv0.x; v = VertexPositionTexture(m_BackupVertices[verNum + 2].position, uv2); newVertices.push_back(v); Vec2 uv3 = m_BackupVertices[verNum + 3].textureCoordinate; uv3.x = uv0.x + 0.1f; v = VertexPositionTexture(m_BackupVertices[verNum + 3].position, uv3); newVertices.push_back(v); verNum += 4; } auto ptrDraw = GetComponent<PTSpriteDraw>(); ptrDraw->UpdateVertices(newVertices); } void UI_PlayerDamage::OnCreate() { float xPiecesize = 1.0f / (float)m_NumberOfDigits; float helfSize = 0.5f; vector<uint16_t> indices; for (UINT i = 0; i < m_NumberOfDigits; i++) { float vertex0 = -helfSize + xPiecesize * (float)i; float vertex1 = vertex0 + xPiecesize; m_BackupVertices.push_back(VertexPositionTexture(Vec3(vertex0, helfSize, 0), Vec2(0.0f, 0.0f))); m_BackupVertices.push_back(VertexPositionTexture(Vec3(vertex1, helfSize, 0), Vec2(0.1f, 0.0f))); m_BackupVertices.push_back(VertexPositionTexture(Vec3(vertex0, -helfSize, 0), Vec2(0.0f, 1.0f))); m_BackupVertices.push_back(VertexPositionTexture(Vec3(vertex1, -helfSize, 0), Vec2(0.1f, 1.0f))); indices.push_back(i * 4 + 0); indices.push_back(i * 4 + 1); indices.push_back(i * 4 + 2); indices.push_back(i * 4 + 1); indices.push_back(i * 4 + 3); indices.push_back(i * 4 + 2); } auto ptrTrans = GetComponent<Transform>(); ptrTrans->SetPosition(m_pos); ptrTrans->SetScale(m_scale); auto ptrDraw = AddComponent<PTSpriteDraw>(m_BackupVertices, indices); ptrDraw->SetTextureResource(m_TextureKey); ptrDraw->SetDiffuse(Col4(1.0f, 1.0f, 1.0f, 1.0f)); SetDrawLayer(12); SetAlphaActive(true); } void UI_PlayerDamage::OnUpdate() { vector<VertexPositionTexture> newVertices; UINT num; int verNum = 0; int damage = GetStage()->GetSharedGameObject<Player>(L"Player")->GetDamage(); for (UINT i = m_NumberOfDigits; i > 0; i--) { UINT base = (UINT)pow(10, i); num = ((UINT)damage) % base; num = num / (base / 10); Vec2 uv0 = m_BackupVertices[verNum].textureCoordinate; uv0.x = (float)num / 10.0f; auto v = VertexPositionTexture(m_BackupVertices[verNum].position, uv0); newVertices.push_back(v); Vec2 uv1 = m_BackupVertices[verNum + 1].textureCoordinate; uv1.x = uv0.x + 0.1f; v = VertexPositionTexture(m_BackupVertices[verNum + 1].position, uv1); newVertices.push_back(v); Vec2 uv2 = m_BackupVertices[verNum + 2].textureCoordinate; uv2.x = uv0.x; v = VertexPositionTexture(m_BackupVertices[verNum + 2].position, uv2); newVertices.push_back(v); Vec2 uv3 = m_BackupVertices[verNum + 3].textureCoordinate; uv3.x = uv0.x + 0.1f; v = VertexPositionTexture(m_BackupVertices[verNum + 3].position, uv3); newVertices.push_back(v); verNum += 4; } auto ptrDraw = GetComponent<PTSpriteDraw>(); ptrDraw->UpdateVertices(newVertices); } void UI_CountdownTimer::OnCreate() { auto stage = GetStage(); auto pos = Vec2(60.0f * m_scale.x, 0.0f * m_scale.y); m_second = stage->AddGameObject<UI_Number>( m_pos + pos, m_digit, m_color, Number::NumberAlign::ZERO_RIGHT, m_space, m_scale, m_layer ); m_minute = stage->AddGameObject<UI_Number>( m_pos - pos, m_digit, m_color, Number::NumberAlign::ZERO_LEFT, m_space, m_scale, m_layer ); m_colon = stage->AddGameObject<UI_Static_Image>( Vec2(64.0f, 128.0f), Vec3(m_pos), Vec3(m_scale), m_layer, m_color, m_colonImageName ); UpdateTime(); } void UI_CountdownTimer::OnUpdate2() { if (!m_isStart) return; auto eTime = App::GetApp()->GetElapsedTime(); m_count += eTime; if (m_count >= 1.0f && m_time > 0) { m_count = NULL; m_time--; if (m_time < m_showingTime) { m_showingTime--; UpdateTime(); } } } void UI_CountdownTimer::UpdateTime() { auto a = m_showingTime / 60; auto b = m_showingTime % 60; m_second->SetValue(b); m_minute->SetValue(a); } //------------------------------------------------------------------------------------------------ //キルアイコン : Class //------------------------------------------------------------------------------------------------ void UI_Kill_Icon::OnCreate() { if (m_level < 1) m_level = 1; if (m_level > 3) m_level = 3; m_level = m_level - 1; int index = 0; switch (m_type) { case CharacterType::CHICKEN: index = 3; break; case CharacterType::POTATO: index = 6; break; case CharacterType::DOUGHNUT: index = 9; break; } index += m_level; Draw(); SetIndex(index); } void UI_Kill_Icon::OnUpdate() { auto ptrDraw = GetComponent<PCTSpriteDraw>(); float time = App::GetApp()->GetElapsedTime(); m_disTime -= time; if (m_color.w <= 0.0f) { GetStage()->RemoveGameObject<GameObject>(GetThis<GameObject>()); } if (m_disTime <= 0.0f) { m_color.w -= time * 5.0f; } ptrDraw->SetDiffuse(m_color); } void Result_Curtain::OnCreate() { SetDrawLayer(m_layer); Mat4x4 mat; mat.affineTransformation( Vec3(1.0f, 1.0f, 1.0f), Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f) ); SetToAnimeMatrix(mat); auto PtrTrans = GetComponent<Transform>(); PtrTrans->SetScale(m_scale); PtrTrans->SetPosition(m_pos); SS5ssae::OnCreate(); SetLooped(false); } void Result_Curtain::OnUpdate() { auto KeyState = App::GetApp()->GetInputDevice().GetKeyState(); auto cntlVec = App::GetApp()->GetInputDevice().GetControlerVec(); float time = App::GetApp()->GetElapsedTime()*2.5f; int flame = 70; if (m_time <= 32.0f / 24.0f) { UpdateAnimeTime(time); } else { UpdateAnimeTime(0); } m_count += 1; m_time += time; if (KeyState.m_bPressedKeyTbl[VK_SPACE] || KeyState.m_bPushKeyTbl['W'] || (cntlVec[0].wPressedButtons & XINPUT_GAMEPAD_A)) { m_time = -10; } } //------------------------------------------------------------------------------------------------ //UI_Flash_Image : Class //------------------------------------------------------------------------------------------------ void UI_Flash_Image::OnCreate() { Draw(); auto color = GetColor(); color.setW(0.0f); SetColor(color); } void UI_Flash_Image::OnUpdate2() { if (m_in) In(); else Out(); } void UI_Flash_Image::In() { auto time = App::GetApp()->GetElapsedTime(); auto color = GetColor(); if (m_count <= m_flashinterval) { m_count += time; auto alpha = m_count / m_flashinterval; color.w = alpha; SetColor(color); } else { m_in = false; } } void UI_Flash_Image::Out() { auto time = App::GetApp()->GetElapsedTime(); auto color = GetColor(); if (m_count >= 0.0f) { m_count -= time; auto alpha = m_count / m_flashinterval; color.w = alpha; SetColor(color); } else { m_in = true; } } void Result_Icon_UI::OnCreate() { if (m_level < 1) m_level = 1; if (m_level > 3) m_level = 3; m_level = m_level - 1; int index = 0; switch (m_type) { case CharacterType::SHRIMP: index = 3; break; case CharacterType::CHICKEN: index = 6; break; case CharacterType::DOUGHNUT: index = 9; break; } index += m_level; Draw(); SetIndex(index); } //------------------------------------------------------------------------------------------------ //リザルトアニメーション3 : Class //------------------------------------------------------------------------------------------------ void UI_Result_Three::OnCreate() { SetDrawLayer(m_layer); Mat4x4 mat; mat.affineTransformation( Vec3(1.0f, 1.0f, 1.0f), Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f) ); SetToAnimeMatrix(mat); auto PtrTrans = GetComponent<Transform>(); PtrTrans->SetScale(m_scale); PtrTrans->SetPosition(m_pos); SS5ssae::OnCreate(); SetLooped(false); } void UI_Result_Three::OnUpdate() { if (m_isPlay) { float time = App::GetApp()->GetElapsedTime(); UpdateAnimeTime(time); } } //------------------------------------------------------------------------------------------------ //リザルトアニメーション2 : Class //------------------------------------------------------------------------------------------------ void UI_Result_Two::OnCreate() { SetDrawLayer(m_layer); Mat4x4 mat; mat.affineTransformation( Vec3(1.0f, 1.0f, 1.0f), Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f) ); SetToAnimeMatrix(mat); auto PtrTrans = GetComponent<Transform>(); PtrTrans->SetScale(m_scale); PtrTrans->SetPosition(m_pos); SS5ssae::OnCreate(); } void UI_Result_Two::OnUpdate() { if (m_isPlay) { float time = App::GetApp()->GetElapsedTime(); UpdateAnimeTime(time); } } void UI_Result_Two::ChangeCharacter(const CharacterType type) { wstring animName = L""; float time = 0.0f; switch (type) { case basecross::POTATO: animName = L"anime_Potato"; break; case basecross::SHRIMP: animName = L"anime_Shrimp"; break; case basecross::CHICKEN: animName = L"anime_Chicken"; break; case basecross::DOUGHNUT: animName = L"anime_Doughnut"; break; } ChangeAnimation(animName, time); SetFps(30.0f); SetLooped(false); } //------------------------------------------------------------------------------------------------ //コピーライトスプラッシュ : Class //------------------------------------------------------------------------------------------------ void UI_Copyright_Splash::OnCreate() { SetDrawLayer(m_layer); Mat4x4 mat; mat.affineTransformation( Vec3(1.0f, 1.0f, 1.0f), Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f) ); SetToAnimeMatrix(mat); auto PtrTrans = GetComponent<Transform>(); PtrTrans->SetScale(m_scale); PtrTrans->SetPosition(m_pos); SS5ssae::OnCreate(); SetFps(60.0f); SetLooped(false); } void UI_Copyright_Splash::OnUpdate() { if (m_isPlay) { float time = App::GetApp()->GetElapsedTime(); UpdateAnimeTime(time); //Out(); /* if (m_frame >= 10.0f) { m_count += time; } else { m_frame += time; } if (m_count >= m_outTime) Out();*/ } } void UI_Copyright_Splash::Out() { ChangeAnimation(L"out", 0.0f); } //デバックテキスト void DebugText::OnCreate() { auto sp = AddComponent<StringSprite>(); sp->SetStartPosition(Point2D<float>(300, 10)); } void DebugText::OnUpdate2() { auto sp = GetComponent<StringSprite>(); sp->SetText(m_text); } //------------------------------------------------------------------------------------------------ //CountSignal : Class //------------------------------------------------------------------------------------------------ void UI_Count_Signal::OnCreate() { if (m_isStart) { CreateStart(); } else { CreateEnd(); } m_signalImage->Hidden(true); m_number = GetStage()->AddGameObject<UI_Number>( Vec2(m_numberPos.x, m_numberPos.y), 1, Col4(1.0f), Number::NumberAlign::ZERO_CENTER, 0.0f, Vec2(m_numberScale.x, m_numberScale.y), 1000 ); m_number->Hidden(true); } void UI_Count_Signal::CreateStart() { m_signalImage = GetStage()->AddGameObject<UI_Static_Image>( Vec2(1024.0f, 256.0f), m_signalPos, m_signalScale, m_layer, Col4(1.0f), m_startSignalImageName ); } void UI_Count_Signal::CreateEnd() { m_signalImage = GetStage()->AddGameObject<UI_Static_Image>( Vec2(1472.0f, 256.0f), m_signalPos, m_signalScale, m_layer, Col4(1.0f), m_endSignalImageName ); } void UI_Count_Signal::SignalUpdate() { if (m_isStart) { int num = m_nowTime - m_endTime; if (num > 0) { m_number->Hidden(false); m_number->SetValue(num); } else if (num == 0) { m_number->Hidden(true); m_signalImage->Hidden(false); } else { m_number->Hidden(true); m_signalImage->Hidden(true); } } else { int num = m_startTime - m_nowTime; if (num < 0) return; if (m_nowTime > 0) { m_number->Hidden(false); m_number->SetValue(m_nowTime); } else if (m_nowTime == 0) { m_number->Hidden(true); m_signalImage->Hidden(false); } } } //------------------------------------------------------------------------------------------------ //カーテン : Class //------------------------------------------------------------------------------------------------ void UI_Curtain::FrameUpdate() { auto time = App::GetApp()->GetElapsedTime(); if (m_frameCount <= m_endFrame / m_baseFps) { UpdateAnimeTime(time); m_frameCount += time; } else { m_finished = true; } } void UI_Curtain::OnCreate() { SetDrawLayer(m_layer); Mat4x4 mat; mat.affineTransformation( Vec3(1.0f, 1.0f, 1.0f), Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f), Vec3(0.0f, 0.0f, 0.0f) ); SetToAnimeMatrix(mat); auto PtrTrans = GetComponent<Transform>(); PtrTrans->SetScale(m_scale); PtrTrans->SetPosition(m_pos); SS5ssae::OnCreate(); SetFps(m_baseFps); SetLooped(false); } void UI_Curtain::OnUpdate() { FrameUpdate(); } }
056e190deef275d867745e6e3bf6d55c0809f57d
aa7f65ccd694db86300dc15e5cd798d15925fd67
/src/keyboard.h
83fcc1f0c21aa57068f2f587f43c9b11a7851376
[ "MIT" ]
permissive
laxa88/wyngine-sdl
b28030a745a512b042749d4100592f9c6fa4e075
a2739abcb51dca7c5f2c80f268aaf54b6d6437bf
refs/heads/master
2022-11-15T10:58:07.773007
2020-07-05T18:18:39
2020-07-05T18:18:39
268,315,594
0
0
null
2020-07-05T06:21:43
2020-05-31T16:09:49
C++
UTF-8
C++
false
false
2,105
h
keyboard.h
// Reference: // https://www.falukdevelop.com/2016/08/18/simple-sdl-2-keyboard-key-status/ #include <SDL2/SDL.h> #include <stdio.h> #include <string> #include <map> class WY_Keyboard { Uint8 prevKeystate[SDL_NUM_SCANCODES]; Uint8 currKeystate[SDL_NUM_SCANCODES]; unsigned char charPressed; public: WY_Keyboard() { memset(prevKeystate, 0, sizeof(Uint8) * SDL_NUM_SCANCODES); memcpy(currKeystate, SDL_GetKeyboardState(NULL), sizeof(Uint8) * SDL_NUM_SCANCODES); } bool isKeyPressed(const SDL_Keycode keycode) { SDL_Scancode code = SDL_GetScancodeFromKey(keycode); return (prevKeystate[code] == 0 && currKeystate[code] == 1); } bool isKeyReleased(const SDL_Keycode keycode) { SDL_Scancode code = SDL_GetScancodeFromKey(keycode); return (prevKeystate[code] == 1 && currKeystate[code] == 0); } bool isKeyDown(const SDL_Keycode keycode) { SDL_Scancode code = SDL_GetScancodeFromKey(keycode); return (currKeystate[code] == 1); } bool isKeyUp(const SDL_Keycode keycode) { SDL_Scancode code = SDL_GetScancodeFromKey(keycode); return (currKeystate[code] == 0); } bool isAnyKeyDown() { for (int i = 0; i < SDL_NUM_SCANCODES; i++) { if (currKeystate[i] == 1) { return true; } } return false; } char getLastCharPressed() { return charPressed; } void update(SDL_Event *windowEvent) { if (windowEvent->key.repeat == 1) { return; } memcpy(prevKeystate, currKeystate, sizeof(Uint8) * SDL_NUM_SCANCODES); memcpy(currKeystate, SDL_GetKeyboardState(NULL), sizeof(Uint8) * SDL_NUM_SCANCODES); if (windowEvent->type == SDL_KEYDOWN) { int keycode = windowEvent->key.keysym.sym; SDL_TextInputEvent keytext = windowEvent->text; // capitalized chars are handled as input-text in WY_IO charPressed = keycode; } } };
53a880c8e8e8fea94e0eb901f56ca8ef341d625f
0fefa37e79119600c684f7b1fdaced4ea4e1cdb3
/src/table/writer.cpp
50ee7c690758a3a18da9330f56793b5e31aece05
[]
no_license
snu5mumr1k/mapreduce_toolkit
cc8e78567fa9c5432af67b9697e72ff272c5cc7f
9cfaa35e61a18e42acb3fcd2d9dd6bec53e38271
refs/heads/master
2021-01-20T06:23:23.756057
2017-05-18T12:42:55
2017-05-18T12:42:55
89,872,439
0
0
null
null
null
null
UTF-8
C++
false
false
982
cpp
writer.cpp
#include <table/writer.h> #include <helpers/singleton.h> #include <params.h> #include <iostream> TableWriter::TableWriter(const std::string &filename, const std::vector<std::string> &columns): out_(Singleton<Params>()->Get("tables_dir") + filename), columns_(columns) { if (!out_.is_open()) { throw std::runtime_error("Didn't manage to open " + filename + " for writing"); } std::string sep; std::string real_sep = Singleton<Params>()->Get("sep"); for (const auto &col : columns_) { out_ << sep << col; sep = real_sep; } out_ << std::endl; } void TableWriter::WriteRow(const Row &row) { file_mutex_.lock(); RealWriteRow(row); file_mutex_.unlock(); } void TableWriter::RealWriteRow(const Row &row) { std::string sep; std::string real_sep = Singleton<Params>()->Get("sep"); for (const auto &col : columns_) { out_ << sep << row[col]; sep = real_sep; } out_ << std::endl; }
eae481849d400b208d6f893a61285b1790b2c795
ae4942ed4819508a39201d697aa43d69dd675414
/ProcessPool.cpp
cc0a7f349d66afdab96badf438d5d2ba3d4f63b9
[]
no_license
uestchuangtao/Practice
55c1e07bc01cbe67f1bf6a18ee3808a26c88573c
ef588f7b151e1e8a522b2fccc62ec8f83c9f0b20
refs/heads/master
2021-01-02T00:59:36.072246
2017-08-01T07:45:36
2017-08-01T07:45:36
98,948,119
0
0
null
null
null
null
UTF-8
C++
false
false
1,055
cpp
ProcessPool.cpp
// // Created by ht on 17-7-31. // #include "ProcessPool.h" void detail::setNonBlocking(int fd) { int flag = fcntl(fd, F_GETFL); flag |= O_NONBLOCK; int ret = fcntl(fd, F_SETFL, flag); assert(ret == 0); } void detail::addFd(int epollfd, int fd) { struct epoll_event event; event.data.fd = fd; event.events = EPOLLIN | EPOLLET; epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event); detail::setNonBlocking(fd); } void detail::deleteFd(int epollfd, int fd) { epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, 0); close(fd); } void detail::sigHandler(void *sig) { int save_errno = errno; int *ptr = sig; int msg = static_cast<int>(*ptr); send(detail::sigPipeFd[1], (void *) &msg, 1, 0); errno = save_errno; } void detail::addSignal(int sig, void(*handler)(void *), bool restart) { struct sigaction sa; bzero(&sa, sizeof(sa)); //sa.sa_handler = handler; if (restart) { sa.sa_flags |= SA_RESTART; } sigfillset(&sa.sa_mask); assert(sigaction(sig, &sa, NULL) != -1); }
719571d59a345129b86653815372f326dc395a38
3201a80841d6183ab35e1eb8071d8acf0c4f715a
/src/include/course.hh
8363d5aa5196b2bfc7473f3df3bf520541578287
[]
no_license
icalamesa/Practica-PRO2
3ca5ca8853ccd7fb7dfbea60cafd866c8489044f
f927f00c74fb21080fe2880aa9a82dedf33e41c6
refs/heads/main
2023-05-04T07:57:27.674909
2021-05-20T08:05:37
2021-05-20T08:05:37
355,328,165
0
0
null
null
null
null
UTF-8
C++
false
false
6,473
hh
course.hh
/** @file @brief Course class specification. @author Ivan Cala Mesa @date 15th of May of 2021 */ /** @cond */ #include <string> #include <map> #include <vector> /** @endcond */ #include "sessions.hh" using namespace std; #ifndef COURSE_HH #define COURSE_HH /** @brief Repository of @ref Session instances identified by an unique id. The Course class behaves as a wrapper of uniquely identified by an id combinations Session instances. */ class Course { /** @brief Set of problems retrieved from every Session in the Course.*/ map<string, string> problem_set; /** @brief Integer that is increased after every problem session_insertion. Allows an easy way to check whether the Course follows the no intersection rule between problems from sessions. */ int expected_size = 0; /** @brief List of sessions, contained in an std::set in a lexicographically sorted fashion*/ set<string> session_list_ordered; /** @brief List of sessions, contained in an std::vector in the same order they were inserted on Course initialization*/ vector<string> session_list; /** @brief Number of active users coursing the given Course.*/ int are_coursing = 0; /** @brief Number of total active and past users that have completed the Course.*/ int have_coursed = 0; /** @brief Inserts Session ids inside the Course session id container. @param session_id Id of session. @pre Always true. @post The given @p session_id has been inserted in the list of session ids. */ void session_insertion(const string& session_id); public: Course(); /** @brief Course size getter. @pre Always true. @return Integer with the amount of sessions that form the implicit parameter. */ int size() const; /** @brief Getter of the size of the Course's problem list. @pre Always true. @return Integer with the amount of problems contained in the Course instance(total number of problems from every contained session). */ int amount_problems() const; /** @brief Validity checker of a Course instance. @return True if there is no repeated problem across the different sessions stored in the implicit parameter. False otherwise. */ bool is_legal(); /** @brief Session belonging to the Course checker. @param session_id Id of the Session instance to search for. @pre Always true. @return Boolean True if a Session with @p session_id as its identifier exists. False otherwise. */ bool session_exists(const string& session_id) const; //reads n sessions, each with their specific id /** @brief Course's session list initializer from standard input. @param session_list List of Session instances. @pre Always true. @post Session ids are read from standard input, and the problems contained in the sessions by the given ids are pushed into the implicit parameter. */ void read_course(const Session_repo& session_list); /** @brief Printer of the ids of sessions that form the Course. @pre Always true @post Ids of sessions that form the implicit parameter are printed in stantard output. */ void info_course() const; /** @brief Getter of active coursing users. @pre Always true. @return Integer with the amount of active users currently coursing the course. */ int users_coursing() const; /** @brief Getter of total completions of the course. @pre Always true. @return Integer with the amount of users that have completed the course at some point. */ int have_completed() const; /** @brief Increaser of counter of active User_repo coursing the given Course. @pre Always true. @return Increases by one unit the counter of active users coursing the Course. */ void increase_coursing(); /** @brief Increaser of counter of total completions of the given Course. @pre Always true. @return Increases by one unit the counter of users that have completed the Course. */ void increase_completed(); /** @brief Decreaser of counter of active User_repo coursing the given Course. @pre Always true. @return Decreases by one unit the counter of active users coursing the Course. */ void decrease_coursing(); /** @brief Index-based (vector-like) Session id getter. @param i Integer that performs as an index @pre @p i is lesser that the implicit parameter size. @return Id of the session in the given (sorted) position set by the @p i index. */ string get_session_id(int i) const; /** @brief Index-based (vector-like) Problem id getter. @param i Integer that performs as an index @pre @p i is lesser that the implicit parameter problem list size. @return Id of the problem in the given (sorted) position set by the @p i index. */ string get_problem_id(int i) const; /** @brief Insertion of Problem ids into the Course. @param problem_id Id of a problem. @pre Always true. @post The id of a given problem @p problem_id has been individually pushed into the Course problem list. */ void insert_problem(const string& problem_id, const string& session_id); /** @brief Checker of existence of a problem within the Course. @param problem_id Id of a problem. @pre Always true. @return True if an id with the given @p problem_id exists in the Course problem list. */ bool find_problem(const string& problem_id) const; //we assume the problem exists /** @brief Finder of the id of the Session that contains the given problem. @param problem_id Id of a problem @param session_list List of Session instances to search for the problem in. @pre Problem with the given @p problem_id exists inside the Course's problem list. @post An std::string that contains the id of the Session instance where the problem_id has been found to be in. */ string session_of_problem(const string& problem_id, const Session_repo& session_list); /** @brief User solvable problems initializer (used on sign in). @param session_list List of Session instances. @param user_id Id of a User instance which is to be referred @param user_list List of User instances @pre User with the given @p user_id exists in the @p user_list. @post For each session contained inside the implicit parameter, problems from inside it are pushed into the solvable problems list of the User by the id of @p user_id. */ void init_solvable_from_sessions(Session_repo& session_list, const string& user_id, User_repo& user_list); ~Course(); }; #endif
665f118cbe319d489259c3b6eb9c86865933cc46
ff3351eab980e9f6b8eda2ba2a59631ad965ed58
/Player.cpp
d9cd12669451ee316e177d9bb002384f0f9853e8
[]
no_license
dab-bot/Qwirkle
8249f30394b60cbf25a1407e409f7b8eb52c78f0
bad213c1b4a8af01d074f44dbb169fada312ec4b
refs/heads/main
2023-09-01T14:40:41.535916
2021-11-03T13:24:36
2021-11-03T13:24:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,597
cpp
Player.cpp
#include "Player.h" #include <iostream> #define MAX_PLAYER_HAND_SIZE 6 // Construct Player object with specified name and score of 0 Player::Player(string n) : name(n), score(0), aiStatus(false) { hand = new LinkedList(); } Player::Player(bool ai) : name("QuirkleBot"), score(0), aiStatus(true) { hand = new LinkedList(); } Player::~Player() { delete hand; } Player::Player(Player& other) { name = other.getName(); score = other.getScore(); aiStatus = other.getAIStatus(); hand = new LinkedList(*other.getHand()); } string Player::getName() { return name; } int Player::getScore() { return score; } void Player::setScore(int s) { score = s; } void Player::setAIStatus(bool s) { aiStatus = s; } bool Player::getAIStatus() { return aiStatus; } LinkedList* Player::getHand() { return hand; } /* * checks if player's hand contains specified tile * returns false if tile does not exist in player hand */ bool Player::hasTile(Tile* t) { return hand->contains(t); } /* * removes specified string representation of tile from player hand if it exists * returns false if tile does not exist in hand */ bool Player::removeFromHand(string s) { bool tileExistence = false; int index = -1; for (int i = 0; i < hand->getSize(); ++i) { // this relies on `s` being correctly formatted/validated after input to coincide with tilecode definition if (hand->get(i)->toString().compare(s) == 0) { index = i; tileExistence = true; } } if (tileExistence) { // removes last instance of `s` in player hand (can be maximum of 2) hand->remove(index); } return tileExistence; } /* * removes specified tile if it exists in player's hand * returns false if tile does not exist in hand */ bool Player::removeFromHand(Tile* t) { bool successful = false; if (hasTile(t)) { int i = hand->findTileIndex(t); hand->remove(i); successful = true; } return successful; } /* * adds to hand only if hand is not currently full (6 tile limit) * returns false on unsuccessful addition of specified tile */ bool Player::addToHand(Tile* t) { bool successful = false; if (hand->getSize() < MAX_PLAYER_HAND_SIZE) { hand->addBack(t); successful = true; } return successful; } string Player::serialise() { string str = name + "\n"; str += ((aiStatus)?"AI\n":"HUMAN\n"); str += std::to_string(score) + "\n"; str+= hand->toString() + "\n"; return str; }
a0d21123906b1b574a2b8751147fad557e63c049
51ceded9b6fc4c51cb91863e59d9a79c6d1a6e65
/src/kbblevelconfigurationwidget.cpp
6be17d275537fbb9c216a8093ffc57c2dcc3cac4
[ "BSD-3-Clause", "CC0-1.0" ]
permissive
KDE/kblackbox
671ce7d62ddfd1c3abec63d40b9fcdd0f4723bf4
425a65b680dd3cdf3e7a233e463ecdd99c5ba65a
refs/heads/master
2023-07-20T02:46:24.424874
2023-07-19T02:11:10
2023-07-19T02:11:10
42,717,334
6
0
null
null
null
null
UTF-8
C++
false
false
2,623
cpp
kbblevelconfigurationwidget.cpp
/* SPDX-FileCopyrightText: 2006, 2007 Nicolas Roffet <nicolas-kde@roffet.com> SPDX-License-Identifier: GPL-2.0-or-later */ #include "kbblevelconfigurationwidget.h" #include <QGridLayout> #include <KLocalizedString> #include <KPluralHandlingSpinBox> #include "kbblevelconfigurationpreview.h" #include "kbbscalablegraphicwidget.h" #include "kbbthememanager.h" KBBLevelConfigurationWidget::KBBLevelConfigurationWidget(QWidget *parent, int c, int r, int b, KBBThemeManager* themeManager) : QWidget(parent) { QGridLayout *l = new QGridLayout(this); kcfg_balls = new KPluralHandlingSpinBox(this); kcfg_balls->setObjectName( QStringLiteral("kcfg_balls" )); l->addWidget(kcfg_balls, 0, 0, 1, 2); kcfg_balls->setMinimum(1); kcfg_balls->setValue(b); kcfg_balls->setSuffix(ki18ncp("A number between 1 and 99 is displayed in front of it.", " ball", " balls")); connect(kcfg_balls, static_cast<void (KPluralHandlingSpinBox::*)(int)>(&KPluralHandlingSpinBox::valueChanged), this, &KBBLevelConfigurationWidget::boxSizeChanged); kcfg_columns = new KPluralHandlingSpinBox(this); kcfg_columns->setObjectName( QStringLiteral("kcfg_columns" )); l->addWidget(kcfg_columns, 1, 1); kcfg_columns->setMinimum(2); kcfg_columns->setMaximum(30); kcfg_columns->setValue(c); kcfg_columns->setSuffix(ki18ncp("A number between 2 and 30 is displayed in front of it.", " column", " columns")); connect(kcfg_columns, static_cast<void (KPluralHandlingSpinBox::*)(int)>(&KPluralHandlingSpinBox::valueChanged), this, &KBBLevelConfigurationWidget::boxSizeChanged); kcfg_rows = new KPluralHandlingSpinBox(this); kcfg_rows->setObjectName( QStringLiteral("kcfg_rows" )); l->addWidget(kcfg_rows, 2, 0); kcfg_rows->setMinimum(2); kcfg_rows->setMaximum(30); kcfg_rows->setValue(r); kcfg_rows->setSuffix(ki18ncp("A number between 2 and 30 is displayed in front of it.", " row", " rows")); connect(kcfg_rows, static_cast<void (KPluralHandlingSpinBox::*)(int)>(&KPluralHandlingSpinBox::valueChanged), this, &KBBLevelConfigurationWidget::boxSizeChanged); m_view = new KBBLevelConfigurationPreview(this, themeManager); l->addWidget(m_view, 2, 1); boxSizeChanged(); } int KBBLevelConfigurationWidget::balls() const { return kcfg_balls->value(); } int KBBLevelConfigurationWidget::columns() const { return kcfg_columns->value(); } int KBBLevelConfigurationWidget::rows() const { return kcfg_rows->value(); } void KBBLevelConfigurationWidget::boxSizeChanged() { kcfg_balls->setMaximum(qMin(99, columns()*rows() - 1)); m_view->preview(balls(), columns(), rows()); } #include "moc_kbblevelconfigurationwidget.cpp"
7accdda4f8b885f47bd0c8499fcab86f01407f8c
6e13654afad97df5b8edac5586e2aee150574da2
/src/menustate.cc
ca24aca5beabe386553bc2c21f4b23c1687e7d9b
[]
no_license
arethsu/breakout
0addecfdd9ced79210d181a90c82f0816e340eb9
eb7b33ad2454738646a15040271b149c65432739
refs/heads/master
2020-04-20T08:46:33.568153
2019-02-01T19:25:34
2019-02-01T19:25:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,885
cc
menustate.cc
#include "menustate.h" extern const int SCREEN_WIDTH; extern const int SCREEN_HEIGHT; MenuState::MenuState( SDL_Renderer* renderer, map<string, SDL_Texture*>& all_textures ) :renderer{ renderer } { filter_textures( all_textures ); init(); } MenuState::~MenuState() { for ( Sprite* sprite : sprites ) { delete sprite; } } void MenuState::filter_textures( map<string, SDL_Texture*>& all_textures ) { textures[ "menu_start" ] = all_textures[ "menu_start" ]; textures[ "menu_highscore" ] = all_textures[ "menu_highscore" ]; textures[ "menu_start_selected" ] = all_textures[ "menu_start_selected" ]; textures[ "menu_highscore_selected" ] = all_textures[ "menu_highscore_selected" ]; textures[ "none" ] = all_textures[ "none" ]; } void MenuState::init() { load_objects(); load_sprites(); for ( Sprite* obj : sprites ) { // extract menu_items if ( dynamic_cast<MenuItem*>(obj) ) { menu_items.push_back( dynamic_cast<MenuItem*>(obj) ); } } } void MenuState::move_down() { bool found_something{ false }; for ( unsigned int i{ 0 }; i < menu_items.size(); i++ ) { if ( menu_items.at( i )->get_selected() == true ) { found_something = true; if ( i < ( menu_items.size() - 1 ) ) { menu_items.at( i )->set_selected( false ); menu_items.at( i+1 )->set_selected( true ); break; } } } if ( ! found_something ) { menu_items.at(0)->set_selected( true ); } } void MenuState::move_up() { bool found_something{ false }; for ( unsigned int i{ 0 }; i < menu_items.size(); i++ ) { if ( menu_items.at( i )->get_selected() == true ) { found_something = true; if ( i != 0 ) { menu_items.at( i )->set_selected( false ); menu_items.at( i-1 )->set_selected( true ); break; } } } if ( ! found_something ) { menu_items.at(0)->set_selected( true ); } } void MenuState::select_current_menu_item( int& choosen ) { for ( MenuItem* menuitem : menu_items ) { if ( menuitem->get_selected() == true ) { if ( menuitem->get_true_type() == "menu_start" ) { choosen = 1; } if ( menuitem->get_true_type() == "menu_highscore" ) { choosen = 3; } } } } /** * MenuState is the selection screen that appears when the game starts. This is * how it handles itself: * * * Checks if we need to quit the game, if so, it sets `choosen` to 0 which in turn quits the game. * * Checks whether we pressed "W", "S", or "RETURN", and uses `move_up()`, `move_down()`, and `select_current_menu_item()` accordingly. * * Clears the screen, updates, and draws all sprites. */ void MenuState::run( int& choosen ) { // handle events SDL_Event event; while ( SDL_PollEvent(&event) ) { if ( event.type == SDL_QUIT ) { choosen = 0; return; } switch ( event.type ) { case SDL_KEYDOWN: switch ( event.key.keysym.sym ) { // move up case SDLK_w: move_up(); break; // move down case SDLK_s: move_down(); break; case SDLK_RETURN: select_current_menu_item( choosen ); break; } } } /* player->move( key ); */ // move menu-item with keys. // clear screen SDL_SetRenderDrawColor( renderer, 0, 0, 0, 255 ); SDL_RenderClear( renderer ); // Draw sprites for ( Sprite* sprite : sprites ) { sprite->update_sprite( textures ); sprite->draw( renderer ); } // show renderer SDL_RenderPresent( renderer ); } void MenuState::load_objects() { // in order sprites.push_back( new MenuItem{ SCREEN_WIDTH / 2 - 300, 400, 600, 100, "menu_start" } ); sprites.push_back( new MenuItem{ SCREEN_WIDTH / 2 - 300, 600, 600, 100, "menu_highscore" } ); } void MenuState::load_sprites() { for ( Sprite* obj : sprites ) { obj->update_sprite( textures ); } }
f209064dea13a562c4733f27357f58798c7148ef
8914a336ae91f0af00bceeffcc00fbb265308684
/FireController/tests/MotorCalibration/MotorCalibration.ino
a5212ebc274cb5056c5f96d519ff1d3077100bf6
[]
no_license
jawshv/kiwi
3b939bbd25c01cb302538c2985cc7d1df423ea66
969da41466fb2f6da5449abb47d6fa40eb0cc1c5
refs/heads/master
2023-02-22T22:28:14.430908
2020-10-19T05:30:55
2020-10-19T05:30:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,639
ino
MotorCalibration.ino
#include <RoboClaw.h> RoboClaw motor = RoboClaw(&Serial4, 10000); int encoder_value = 0; int motor_address = 0x80; int motor_baud = 460800; float position = 0; int t = 0; void setup() { Serial.begin(115200); motor.begin(motor_baud); char v[48]; motor.ReadVersion(motor_address, v); Serial.write(v); encoder_value = motor.ReadEncM1(motor_address); motor.SetEncM1(motor_address, 660); motor.ReadEncM1(motor_address); t = millis(); // motor.SpeedAccelDeccelPositionM1(motor_address, 1000, 500, 1000, 0, 1); pinMode(20, OUTPUT); digitalWrite(20, HIGH); } void loop() { if (Serial.available()) { char c; c = Serial.read(); if (c == 'w') { position += 50; motor.SpeedAccelDeccelPositionM1(motor_address, 1000, 500, 1000, position, 1); } else if (c == 's') { position -= 50; motor.SpeedAccelDeccelPositionM1(motor_address, 1000, 500, 1000, position, 1); } else if (c == 'q') { motor.SpeedAccelDeccelPositionM1(motor_address, 0, 0, 0, 0, 1); } else { Serial.write(c); } Serial.print(position); } encoder_value = motor.ReadEncM1(motor_address); if (millis() - t > 10) { // Serial.print("encoder: "); Serial.print(encoder_value); Serial.print(" "); int16_t current1; int16_t current2; motor.ReadCurrents(motor_address, current1, current2); // Serial.print("current: "); Serial.print(current1); // Serial.print(" "); Serial.println(); t = millis(); } }
b6a528c717e55a32510c1681485ea2de430751f4
77b8be7809f6305b063ebfa6f5ef30434c418156
/Algorithms/Easy/MonotonicArray.cpp
1623b4aeb68e51ba5b9402ea10df89587e040dfc
[]
no_license
aj211y/LeetCode
ce6ea5ae7243d203c5ff682e95b7fc1b9c0d868a
7e1cd2cb366a64e0d392559679dfd158c20fe1cc
refs/heads/master
2020-03-27T04:37:21.380235
2018-09-19T07:35:09
2018-09-19T07:35:09
145,955,420
0
0
null
null
null
null
UTF-8
C++
false
false
796
cpp
MonotonicArray.cpp
//No.896 - AC #include <iostream> #include <cstdio> #include <vector> #include <algorithm> using namespace std; class Solution { public: bool isMonotonic(vector<int>& A) { bool allSame = true; for(int i=0; i<A.size()-1; i++) { if(A[i]!=A[i+1]) { allSame = false; if(A[i]>A[i+1]) reverse(A.begin(), A.end()); break; } } if(allSame) return true; for(int i=0; i<A.size()-1; i++) { if(A[i]>A[i+1]) return false; } return true; } }; int main() { int n, tmp; Solution sol; vector<int> A; scanf("%d", &n); while(n--) { scanf("%d", &tmp); A.push_back(tmp); } if(sol.isMonotonic(A)) cout << "True" << endl; else cout << "No" << endl; return 0; }
cac0549e9957e62ccebb7082126fdb877d277996
efb739bb2dd3c9dd07cc26d62ffa46973760b7f2
/src/fheroes2/castle/castle_tavern.cpp
2496c31dbd107408850ef155dc09348237d32528
[]
no_license
infsega/fheroes2-playbook
a6c2bb632ac1582a6acd056326fd14831d9bdb44
a1c2e43b6f7ce72a3e3eec29aad95ea6613200a9
refs/heads/master
2020-06-02T07:42:52.494152
2012-06-28T23:09:43
2012-06-28T23:09:43
4,770,518
5
1
null
null
null
null
UTF-8
C++
false
false
4,080
cpp
castle_tavern.cpp
/*************************************************************************** * Copyright (C) 2009 by Andrey Afletdinov <fheroes2@gmail.com> * * * * Part of the Free Heroes2 Engine: * * http://sourceforge.net/projects/fheroes2 * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include <string> #include "agg.h" #include "button.h" #include "world.h" #include "cursor.h" #include "settings.h" #include "resource.h" #include "castle.h" #include "heroes.h" #include "kingdom.h" #include "text.h" void Castle::OpenTavern(void) { const std::string & header = _("A generous tip for the barkeep yields the following rumor:"); const ICN::icn_t system = (Settings::Get().ExtGameEvilInterface() ? ICN::SYSTEME : ICN::SYSTEM); const ICN::icn_t tavwin = ICN::TAVWIN; const std::string & tavern = GetStringBuilding(BUILD_TAVERN); const std::string & message = world.GetRumors(); Display & display = Display::Get(); Cursor & cursor = Cursor::Get(); cursor.Hide(); Text text(tavern, Font::BIG); const Sprite & s1 = AGG::GetICN(tavwin, 0); TextBox box1(header, Font::BIG, BOXAREA_WIDTH); TextBox box2(message, Font::BIG, BOXAREA_WIDTH); Dialog::Box box(text.h() + 10 + s1.h() + 13 + box1.h() + 20 + box2.h(), true); const Rect & pos = box.GetArea(); Point dst_pt(pos.x, pos.y); text.Blit(pos.x + (pos.w - text.w()) / 2, dst_pt.y); dst_pt.x = pos.x + (pos.w - s1.w()) / 2; dst_pt.y += 10 + text.h(); s1.Blit(dst_pt); dst_pt.x += 3; dst_pt.y += 3; const Sprite & s20 = AGG::GetICN(tavwin, 1); s20.Blit(dst_pt); if(const u16 index = ICN::AnimationFrame(tavwin, 0, 0)) { const Sprite & s21 = AGG::GetICN(tavwin, index); s21.Blit(dst_pt.x + s21.x(), dst_pt.y + s21.y()); } box1.Blit(pos.x, dst_pt.y + s1.h() + 10); box2.Blit(pos.x, dst_pt.y + s1.h() + 10 + box1.h() + 20); // button yes const Sprite & s4 = AGG::GetICN(system, 5); Button buttonYes(pos.x + (pos.w - s4.w()) / 2, pos.y + pos.h - s4.h(), system, 5, 6); buttonYes.Draw(); cursor.Show(); display.Flip(); LocalEvent & le = LocalEvent::Get(); u32 frame = 0; // message loop while(le.HandleEvents()) { le.MousePressLeft(buttonYes) ? buttonYes.PressDraw() : buttonYes.ReleaseDraw(); if(le.MouseClickLeft(buttonYes) || HotKeyCloseWindow) break; // animation if(Game::AnimateInfrequent(Game::CASTLE_TAVERN_DELAY)) { cursor.Hide(); s20.Blit(dst_pt); if(const u16 index = ICN::AnimationFrame(tavwin, 0, frame++)) { const Sprite & s22 = AGG::GetICN(tavwin, index); s22.Blit(dst_pt.x + s22.x(), dst_pt.y + s22.y()); } cursor.Show(); display.Flip(); } } }
4c994aecc52221a61dd0ff9fd8ae2f6e091329dd
e1f3172d7a034930e4fbc66b2560868a0d18bbf2
/Chapter3/ConstructorOver2.cpp
a5fad2d994b5e2003fc9576355a16ef277bf363f
[]
no_license
vallisneria/hknu2-programming-to-cpp
1cace2d40de741ec0f94083f4910adda1cea8502
4c76f91cb349bb1c48cf8adf94cb7c174227ebd1
refs/heads/master
2023-03-08T09:59:02.282119
2019-08-31T13:40:08
2019-08-31T13:40:08
342,198,642
0
0
null
null
null
null
UTF-8
C++
false
false
959
cpp
ConstructorOver2.cpp
#include<iostream> #include<tchar.h> using namespace std; class CMyPoint{ private: int m_x=0; int m_y=0; public: CMyPoint(int x){ cout <<"CMyPoint(int)"<<endl; //x값이 100이 넘는지 검사하고 넘으면 100으로 맞춘다 if (x > 100) { x=100; } m_x=100; } CMyPoint(int x, int y):CMyPoint(x){ cout<<"CMyPoint(int, int)"<<endl; //y값이 200이 넘는지 검사하고 넘으면 200으로 맞춘다. if (y > 200) { y=200; } m_y=200; } void Print(){ cout << "X: " << m_x << endl; cout << "Y: " << m_y << endl; } }; int _tmain(int argc, _TCHAR *argv[]){ //매개변수가 하나인 생성자만 호출한다. CMyPoint ptBegin(110); ptBegin.Print(); //이번엔 두 생성자 모두 호출한다. CMyPoint ptEnd(50,250); ptEnd.Print(); return 0; }
b171f52813e1d466b30dbbf3f048229cd21c1feb
45468c31f0bf28a52ec8a28a30b585683b511491
/this_Keyword.cpp
d4f6c2f5351e9cf4e8f8d06d787314a5961b7b30
[]
no_license
hrishi77/Logic_Building_CPP
6ba9e1262c6cf8c2e8a454e3944ee4c3451f8560
b358f562a04ae8a3d186cfa7093cd689642bb861
refs/heads/master
2020-12-23T13:53:08.116730
2020-04-10T18:10:43
2020-04-10T18:10:43
237,171,954
0
0
null
null
null
null
UTF-8
C++
false
false
765
cpp
this_Keyword.cpp
//this keyword use in cpp demo #include <iostream> using namespace std; class Demo { public: //acess specifier int i; int j; Demo() { i= 20; this->j = 10; } Demo(int i,int j) { this->i = i; this->j = j; this->fun(11); } Demo(Demo &ref) { this->i = ref.i; this->j = ref.j; } //void fun(Demo *const this,int no) void fun(int No) { cout<<i; cout<<this->i; // cout<<this; } void gun() { this->fun(51); } };//end of the class int main() { Demo obj1; Demo obj2(11,21); Demo obj3(obj2); obj1.fun(101); obj2.fun(201); obj1.gun(); }
b6f57ea42be9316dbc7b2b3ed4b3d4a11d97e54e
376fd6e86290050719798c7d8ea8252b2c0bc8c3
/src/setup/SetupFileLoader.h
a886fb82d1334fbf6aa994b18f528db153a3ce7f
[ "MIT" ]
permissive
QichenW/ArticulatedFigure
b460ab0244007c663ee839a0e372564cc1970f8c
eb211861a5280384732c63b271f31778c42c6987
refs/heads/master
2020-04-11T08:03:13.605037
2017-04-07T09:19:57
2017-04-07T09:19:57
70,967,619
0
0
null
null
null
null
UTF-8
C++
false
false
421
h
SetupFileLoader.h
// // Created by Qichen on 9/25/16. // #ifndef GLUTPROJECT_SETUPFILELOADER_H #define GLUTPROJECT_SETUPFILELOADER_H #include <string> #include <articulated/ArticulatedMan.h> #if defined(__APPLE__) #include <GLUT/glut.h> #else #include <GL/glut.h> #endif class SetupFileLoader { public: static void loadPreferencesFromTextFile(char *path, ArticulatedMan *pPreferences); }; #endif //GLUTPROJECT_SETUPFILELOADER_H
c25a9d06a28bb655f675d995f014da9fe3a51fcc
5360403baa4640073c94a4ff36a8b0deb160e163
/src/Feeder.cpp
20d4bd1c5e0758d3eb17c21e7e7316e3660faa25
[]
no_license
junsoopark/sp
0f2792f076af1c386994877261bd9373c3196c15
2f1e72e0e75ce6ed238b51630e6c58cc54e315cd
refs/heads/master
2016-08-03T21:52:24.113400
2013-05-28T05:11:38
2013-05-28T05:11:38
9,953,684
1
0
null
null
null
null
UTF-8
C++
false
false
234
cpp
Feeder.cpp
#include "Feeder.h" Feeder::Feeder(char* a_pName) { m_strName = a_pName; } bool Feeder::Feed(Buffer* a_pBuffer) { SetChanged(); NotifyObservers((long)a_pBuffer, 0); } const char* Feeder::GetName() { return m_strName.data(); }
bf908951b29153d98989bd769e787f6bae6ad07a
8a08c5b95580e07ae48c298ad2d4082874d9bde0
/yootMarbleEngine/User.cpp
2ab4b81209e0d1eadb87d7bed0e48637928d3f68
[]
no_license
pcsewj14/OOP
064658e20cbcd858357a3d97af114a2f4331b54e
af630f485390f567c1c6ea3331f521dfcc7fdb69
refs/heads/master
2021-01-22T05:38:36.481383
2017-05-27T10:40:55
2017-05-27T10:40:55
92,483,661
0
0
null
null
null
null
UHC
C++
false
false
23,367
cpp
User.cpp
#include "User.h" #include "GameDisplay.h" //#include "ui_User.h" //#include "showyout.h" #include <QtGlobal> #include <QTime> #include <QDebug> #include <qimage.h> #include <qpixmap.h> extern GameDisplay* d; User::User(int team) { yout = 0; this->team = team; //말들을 초기환다. for(int i = 0; i < PIECE_NUM; i++) { pieces[i] = new Piece; } sound = new QMediaPlayer; } void User::movePiece(int i) { int j; if(i < 0 || i > PIECE_NUM) //i가 유효한 숫자인지 확인 { return; } pieces[i]->move(randomYout); //두 말이 겹쳤을 때, 그 두 말을 합친다. for(j = 0; j < PIECE_NUM; j++) { if(pieces[i]->getPosition() == pieces[j]->getPosition()) { if((pieces[i] != pieces[j]) && (!pieces[i]->isFinished() && !pieces[j]->isFinished())) { if(pieces[i]->getNum() + pieces[j]->getNum() <= 3) { if(pieces[i]->getNum() + pieces[j]->getNum() == 3) { if(pieces[i]->getNum() == 2) { unite(i, j); } else { unite(j, i); } } else { unite(i, j); if(i > j) i = j; } } } } } //상대방 팀의 말을 잡았을 때 for(j = 0; j < PIECE_NUM; j++) { if(pieces[i]->getPosition() == rival->getPiece(j)->getPosition()) { if(!pieces[i]->isFinished() && !rival->getPiece(j)->isFinished()) { if(pieces[i]->getPosition() != 0) { rival->resetPiece(j); emit caughtPiece(true); } } } } emit thrown(); if(!pieces[i]->isFinished()) { std::string spaceType = gameBoard->getSpace(pieces[i]->getPosition())->getSpaceType(); if(spaceType == "Building") OnBuildingSpace(i); else if(spaceType == "Healing") OnHealingSpace(i); } else { emit updateDisplay(); } } Piece* User::getPiece(int i) { if(i < 0 || i > PIECE_NUM) //check if i is valid { return 0; } return pieces[i]; } //두 말을 합친다. void User::unite(int pieceIndex1, int pieceIndex2) { //첫번째 말의 최대체력을 늘려주고, 체력을 합친다. int resultNum = pieces[pieceIndex1]->getNum() + pieces[pieceIndex2]->getNum(); pieces[pieceIndex1]->setMaxHP(100*resultNum); pieces[pieceIndex1]->get_heal(pieces[pieceIndex2]->getHP()); pieces[pieceIndex1]->setNum(resultNum); //두 번째 말이 첫번째 말을 가리키도록한다. pieces[pieceIndex2] = pieces[pieceIndex1]; emit uniteSignal(); } //말이 죽었을 때 처음으로 돌려보낸다. void User::resetPiece(int i) { if(pieces[i]->getNum() == 2) { for(int j = 0; j < PIECE_NUM; j++) { if(i != j && pieces[i] == pieces[j]) { delete pieces[i]; pieces[i] = new Piece; pieces[j] = new Piece; break; } } } if(pieces[i]->getNum() == 3) { delete pieces[i]; for(int j = 0; j < PIECE_NUM; j++) { pieces[j] = new Piece; } } else { delete pieces[i]; pieces[i] = new Piece; } } //말이 건물 칸에 도착했을 때 void User::OnBuildingSpace(int i) { current = i; int position = pieces[current]->getPosition(); BuildingSpace* space = dynamic_cast<BuildingSpace*>(gameBoard->getSpace(position)); bool death_check; int owner = space->getTeam(); //말이 가운데에 있는 칸에 걸리면, 체력을 랜덤으로 깎는다. if(position == 22) { sound->setMedia(QUrl::fromLocalFile("./sounds/paperAlert.wav")); sound->setVolume(FX_VOLUME); sound->play(); //체력이 깎였다는 메세지를 띄운다. label = new QLabel(); label->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); QImage *info = new QImage(); QString filename = "./draw/info/reducedLife.png"; info->load(filename); label->setPixmap(QPixmap::fromImage(*info)); yes = new QPushButton(); yes->setCursor(Qt::PointingHandCursor); QPixmap yeap("./draw/info/confirm.png"); yes->setIcon(QIcon(yeap)); yes->setIconSize(yeap.rect().size()); yes->setFixedSize(yeap.rect().size()); yes->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); d->getScene()->addWidget(label); d->getScene()->addWidget(yes); label->setFixedSize(330, 275); label->move(-(label->width()/2), -(label->height()/2)); yes->move(-(yes->width()/2), 30); connect(yes, SIGNAL(clicked()), this, SLOT(PostechConfirm())); return; } if(owner == team) //자기 건물에 도착했을 때 아무일도 안 일어난다. { emit updateDisplay(); } else if(owner == !team) //상대방 건물에 도착했을 때 체력을 깎는다. { death_check = pieces[current]->get_damage(space->getDamagecost()); d->setHPText(current, team, pieces[current]->getHP(), pieces[current]->getNum()*100); emit lostHP(space->getDamagecost()); if(death_check == true) //말이 죽었을 때 { if(current == 1) { sound->setMedia(QUrl::fromLocalFile("./sounds/girlDie.mp3")); } else { sound->setMedia(QUrl::fromLocalFile("./sounds/boyDie.wav")); } sound->setVolume(FX_VOLUME); sound->play(); resetPiece(current); label = new QLabel(); label->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); QImage *info = new QImage(); QString filename = "./draw/info/die.png"; info->load(filename); label->setPixmap(QPixmap::fromImage(*info)); yes = new QPushButton(); yes->setCursor(Qt::PointingHandCursor); QPixmap yeap("./draw/info/confirm.png"); yes->setIcon(QIcon(yeap)); yes->setIconSize(yeap.rect().size()); yes->setFixedSize(yeap.rect().size()); yes->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); d->getScene()->addWidget(label); d->getScene()->addWidget(yes); label->setFixedSize(330, 275); label->move(-(label->width()/2), -(label->height()/2)); yes->move(-(yes->width()/2), 30); connect(yes, SIGNAL(clicked()), this, SLOT(dieconfirm())); } else //말이 안 죽으면, 땅을 뺏을 수 있는 옵션을 준다. { sound->setMedia(QUrl::fromLocalFile("./sounds/paperAlert.wav")); sound->setVolume(FX_VOLUME); sound->play(); label = new QLabel(); label->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); QImage *info = new QImage(); QString filename = "./draw/info/steal.png"; info->load(filename); label->setPixmap(QPixmap::fromImage(*info)); yes = new QPushButton(); yes->setCursor(Qt::PointingHandCursor); QPixmap yeap("./draw/info/yes.png"); yes->setIcon(QIcon(yeap)); yes->setIconSize(yeap.rect().size()); yes->setFixedSize(yeap.rect().size()); yes->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); no = new QPushButton(); no->setCursor(Qt::PointingHandCursor); QPixmap nope("./draw/info/no.png"); no->setIcon(QIcon(nope)); no->setIconSize(nope.rect().size()); no->setFixedSize(nope.rect().size()); no->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); d->getScene()->addWidget(label); d->getScene()->addWidget(yes); d->getScene()->addWidget(no); label->setFixedSize(330, 275); label->move(-(label->width()/2), -(label->height()/2)); yes->move(-35 - 275/4, 30); no->move(-20 + 275/4, 30); connect(yes, SIGNAL(clicked()), this, SLOT(stealSpace())); connect(no, SIGNAL(clicked()), this, SLOT(donothing())); } } else //건물의 주인이 없을 때, 살 수 있는 옵션을 준다. { sound->setMedia(QUrl::fromLocalFile("./sounds/paperAlert.wav")); sound->setVolume(FX_VOLUME); sound->play(); label = new QLabel(); label->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); QImage *info = new QImage(); QString filename = "./draw/info/buy.png"; info->load(filename); label->setPixmap(QPixmap::fromImage(*info)); yes = new QPushButton(); yes->setCursor(Qt::PointingHandCursor); QPixmap yeap("./draw/info/yes.png"); yes->setIcon(QIcon(yeap)); yes->setIconSize(yeap.rect().size()); yes->setFixedSize(yeap.rect().size()); yes->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); no = new QPushButton(); no->setCursor(Qt::PointingHandCursor); QPixmap nope("./draw/info/no.png"); no->setIcon(QIcon(nope)); no->setIconSize(nope.rect().size()); no->setFixedSize(nope.rect().size()); no->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); label->setFixedSize(330, 275); label->move(-(label->width()/2), -(label->height()/2)); yes->move(-35 - 275/4, 30); no->move(-20 + 275/4, 30); d->getScene()->addWidget(label); d->getScene()->addWidget(yes); d->getScene()->addWidget(no); connect(yes, SIGNAL(clicked()), this, SLOT(buySpace())); connect(no, SIGNAL(clicked()), this, SLOT(donothing())); } } //말이 체력회복칸에 도착했을 때 void User::OnHealingSpace(int i) { current = i; int position = pieces[current]->getPosition(); HealingSpace* space = dynamic_cast<HealingSpace*>(gameBoard->getSpace(position)); //말이 황금열쇠 칸에 도착했을 때 if(position == 6 || position == 16) { sound->setMedia(QUrl::fromLocalFile("./sounds/onGoldenKey.mp3")); sound->setVolume(FX_VOLUME); sound->play(); label = new QLabel(); label->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); QImage *info = new QImage(); QString filename = "./draw/info/goldenKey.png"; info->load(filename); label->setPixmap(QPixmap::fromImage(*info)); yes = new QPushButton(); yes->setCursor(Qt::PointingHandCursor); QPixmap yeap("./draw/info/confirm.png"); yes->setIcon(QIcon(yeap)); yes->setIconSize(yeap.rect().size()); yes->setFixedSize(yeap.rect().size()); yes->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); d->getScene()->addWidget(label); d->getScene()->addWidget(yes); label->setFixedSize(330, 275); label->move(-(label->width()/2), -(label->height()/2)); yes->move(-(yes->width()/2), 30); //황금열쇠 효과를 실행한다. connect(yes, SIGNAL(clicked()), this, SLOT(keyEffect())); return; } sound->setMedia(QUrl::fromLocalFile("./sounds/paperAlert.wav")); sound->setVolume(FX_VOLUME); sound->play(); //체력을 회복하고, 메세지를 띄운다. pieces[current]->get_heal(space->getheal()); d->setHPText(current, team, pieces[current]->getHP(), pieces[current]->getNum()*100); label = new QLabel(); label->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); QImage *info = new QImage(); QString filename; if(position == 5) filename = "./draw/info/10healed.png"; else filename = "./draw/info/30healed.png"; info->load(filename); label->setPixmap(QPixmap::fromImage(*info)); yes = new QPushButton(); yes->setCursor(Qt::PointingHandCursor); QPixmap yeap("./draw/info/confirm.png"); yes->setIcon(QIcon(yeap)); yes->setIconSize(yeap.rect().size()); yes->setFixedSize(yeap.rect().size()); yes->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); label->setFixedSize(330, 275); label->move(-(label->width()/2), -(label->height()/2)); yes->move(-(yes->width()/2), 30); d->getScene()->addWidget(label); d->getScene()->addWidget(yes); connect(yes, SIGNAL(clicked()), this, SLOT(confirm())); } //말 세개가 다 끝난 상태면, true를 반환한다. bool User::win() { bool win = true; for(int i = 0; i < PIECE_NUM; i++) { win &= pieces[i]->isFinished(); } return win; } //건물을 살 때 부르는 함수 void User::buySpace() { disconnect(yes, SIGNAL(clicked()), 0, 0); disconnect(no, SIGNAL(clicked()), 0, 0); label->close(); yes->close(); no->close(); int position = pieces[current]->getPosition(); BuildingSpace* space = dynamic_cast<BuildingSpace*>(gameBoard->getSpace(position)); if(pieces[current]->getHP() > space->getBuycost()) { sound->setMedia(QUrl::fromLocalFile("./sounds/getBuilding.mp3")); sound->setVolume(FX_VOLUME); sound->play(); QPixmap region("./draw/update" + QString::number(team) + "/" + QString::number(position) + ".png"); d->getImage(position)->setIcon(QIcon(region)); d->getScene()->addWidget(d->getImage(position)); pieces[current]->get_damage(space->getBuycost()); d->setHPText(current, team, pieces[current]->getHP(), pieces[current]->getNum()*100); space->setTeam(team); emit updateDisplay(); } else { label = new QLabel(); label->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); QImage *info = new QImage(); QString filename = "./draw/info/can'tBuy.png"; info->load(filename); label->setPixmap(QPixmap::fromImage(*info)); yes = new QPushButton(); yes->setCursor(Qt::PointingHandCursor); QPixmap yeap("./draw/info/confirm.png"); yes->setIcon(QIcon(yeap)); yes->setIconSize(yeap.rect().size()); yes->setFixedSize(yeap.rect().size()); yes->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); d->getScene()->addWidget(label); d->getScene()->addWidget(yes); label->setFixedSize(330, 275); label->move(-(label->width()/2), -(label->height()/2)); yes->move(-(yes->width()/2), 30); connect(yes, SIGNAL(clicked()), this, SLOT(confirm())); } } //건물을 뺏을 때 부르는 함수 void User::stealSpace() { disconnect(yes, SIGNAL(clicked()), 0, 0); disconnect(no, SIGNAL(clicked()), 0, 0); label->close(); yes->close(); no->close(); int position = pieces[current]->getPosition(); BuildingSpace* space = dynamic_cast<BuildingSpace*>(gameBoard->getSpace(position)); if(pieces[current]->getHP() > space->getStealcost()) { sound->setMedia(QUrl::fromLocalFile("./sounds/getBuilding.mp3")); sound->setVolume(FX_VOLUME); sound->play(); disconnect(yes, SIGNAL(clicked()), 0, 0); disconnect(no, SIGNAL(clicked()), 0, 0); yes->close(); no->close(); QPixmap region("./draw/update" + QString::number(team) + "/" + QString::number(position) + ".png"); d->getImage(position)->setIcon(QIcon(region)); d->getScene()->addWidget(d->getImage(position)); pieces[current]->get_damage(space->getStealcost()); d->setHPText(current, team, pieces[current]->getHP(), pieces[current]->getNum()*100); space->setTeam(team); emit updateDisplay(); } else //체력이 부족해서 건물을 못 뺏는 경우 { label = new QLabel(); label->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); QImage *info = new QImage(); QString filename = "./draw/info/can'tSteal.png"; info->load(filename); label->setPixmap(QPixmap::fromImage(*info)); yes = new QPushButton(); yes->setCursor(Qt::PointingHandCursor); QPixmap yeap("./draw/info/confirm.png"); yes->setIcon(QIcon(yeap)); yes->setIconSize(yeap.rect().size()); yes->setFixedSize(yeap.rect().size()); yes->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); d->getScene()->addWidget(label); d->getScene()->addWidget(yes); label->setFixedSize(330, 275); label->move(-(label->width()/2), -(label->height()/2)); yes->move(-(yes->width()/2), 30); connect(yes, SIGNAL(clicked()), this, SLOT(confirm())); } } //아무런 액션을 취하지 않고, 턴을 다음으로 넘긴다. void User::donothing() { disconnect(yes, SIGNAL(clicked()), 0, 0); disconnect(no, SIGNAL(clicked()), 0, 0); label->close(); yes->close(); no->close(); //emit turnEnd(); emit updateDisplay(); } void User::confirm() { disconnect(yes, SIGNAL(clicked()), 0, 0); label->close(); yes->close(); //emit turnEnd(); emit updateDisplay(); } void User::confirm1() { disconnect(yes, SIGNAL(clicked()), 0, 0); yes->close(); emit updateDisplay(); } //황금열쇠 효과 void User::keyEffect() { bool death_check = false; disconnect(yes, SIGNAL(clicked()), 0, 0); label->close(); yes->close(); yes = new QPushButton(); yes->setFixedSize(1200, 730); yes->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); yes->move(-H_LIMIT, -V_LIMIT); srand(time(0)); int effectNum = rand() % 14; if(effectNum < 2) { QPixmap pix("./draw/info/0.png"); yes->setIconSize(pix.rect().size()); yes->setIcon(QIcon(pix)); d->getScene()->addWidget(yes); death_check = hackathon(); } else if(effectNum < 4) { QPixmap pix("./draw/info/1.png"); yes->setIconSize(pix.rect().size()); yes->setIcon(QIcon(pix)); d->getScene()->addWidget(yes); festival(); } else if(effectNum < 6) { QPixmap pix("./draw/info/2.png"); yes->setIconSize(pix.rect().size()); yes->setIcon(QIcon(pix)); d->getScene()->addWidget(yes); RAtalk(); } else if(effectNum < 10) { QPixmap pix("./draw/info/3.png"); yes->setIconSize(pix.rect().size()); yes->setIcon(QIcon(pix)); d->getScene()->addWidget(yes); lostMemory(); } else if(effectNum < 13) { QPixmap pix("./draw/info/4.png"); yes->setIconSize(pix.rect().size()); yes->setIcon(QIcon(pix)); d->getScene()->addWidget(yes); //rival->resetPiece(0); postechKaistScienceWar(); } else if(effectNum == 13) { QPixmap pix("./draw/info/5.png"); yes->setIconSize(pix.rect().size()); yes->setIcon(QIcon(pix)); d->getScene()->addWidget(yes); phoenix(); } if(death_check == false) connect(yes, SIGNAL(clicked()), this, SLOT(confirm1())); else connect(yes, SIGNAL(clicked()), this, SLOT(HackathonDie())); return; } //말이 죽었을 때 메세지를 띄운다. void User::dieconfirm() { disconnect(yes, SIGNAL(clicked()), 0, 0); label->close(); yes->close(); emit die(false); emit updateDisplay(); } User::~User() { } //////황금열쇠 효과///// //말의 체력을 깎는 효과 bool User::hackathon() { sound->setMedia(QUrl::fromLocalFile("./sounds/hackathon.wav")); sound->setVolume(FX_VOLUME); sound->play(); srand(time(0)); int damage = 50; bool death_check = pieces[current]->get_damage(damage * pieces[current]->getNum()); d->setHPText(current, team, pieces[current]->getHP(), pieces[current]->getNum()*100); //emit lostHP(randomDamage); return death_check; } //말의 체력을 회복한다. void User::RAtalk() { sound->setMedia(QUrl::fromLocalFile("./sounds/RAtalk.wav")); sound->setVolume(FX_VOLUME); sound->play(); pieces[current]->get_heal(60); d->setHPText(current, team, pieces[current]->getHP(), pieces[current]->getNum()*100); } //한 팀의 말의 체력을 다 올린다. void User::festival() { sound->setMedia(QUrl::fromLocalFile("./sounds/festival.wav")); sound->setVolume(FX_VOLUME); sound->play(); for(int i = 0; i < PIECE_NUM; i++) { pieces[i]->get_heal(40); d->setHPText(i, team, pieces[i]->getHP(), pieces[i]->getNum()*100); } } //모든 말을 랜덤한 장소로 보낸다. void User::lostMemory() { sound->setMedia(QUrl::fromLocalFile("./sounds/lostMemory.wav")); sound->setVolume(FX_VOLUME); sound->play(); srand(time(0)); int randomPosition; bool canChange = false; for(int i = 0; i < PIECE_NUM; i++) { canChange = false; randomPosition = rand() % 28 + 1; while(!canChange) { canChange = true; for(int i = 0; i < PIECE_NUM; i++) { if(pieces[i]->getPosition() == randomPosition && !pieces[i]->isFinished()) { canChange = false; } } for(int i = 0; i < PIECE_NUM; i++) { if(rival->getPiece(i)->getPosition() == randomPosition && !rival->getPiece(i)->isFinished()) { canChange = false; } } if(!canChange) { randomPosition = rand() % 28 + 1; } } pieces[i]->setPosition(randomPosition); } for(int i = 0; i < PIECE_NUM; i++) { canChange = false; randomPosition = rand() % 28 + 1; while(!canChange) { canChange = true; for(int i = 0; i < PIECE_NUM; i++) { if(pieces[i]->getPosition() == randomPosition && !pieces[i]->isFinished()) { canChange = false; } } for(int i = 0; i < PIECE_NUM; i++) { if(rival->getPiece(i)->getPosition() == randomPosition && !rival->getPiece(i)->isFinished()) { canChange = false; } } if(!canChange) { randomPosition = rand() % 28 + 1; } } rival->getPiece(i)->setPosition(randomPosition); } emit thrown(); } //상대방 말 하나를 시작점으로 보낸다. void User::postechKaistScienceWar() { sound->setMedia(QUrl::fromLocalFile("./sounds/poKaBattle.wav")); sound->setVolume(FX_VOLUME); sound->play(); srand(time(0)); int randomIndex = rand() % 3; bool valid = false; bool canReset = false; for(int i = 0; i < PIECE_NUM; i++) { if(!rival->getPiece(i)->isFinished() && rival->getPiece(i)->getPosition() > 0) { canReset = true; } } if(!canReset) { return; } while(!valid) { if(!rival->getPiece(randomIndex)->isFinished() && rival->getPiece(randomIndex)->getPosition() > 0) { valid = true; } else { randomIndex = rand() % 3; } } rival->resetPiece(randomIndex); emit caughtPiece(false); //emit thrown(); } //한쪽 팀이 승리한다. void User::phoenix() { bgm->pause(); sound->setMedia(QUrl::fromLocalFile("./sounds/pheonix.wav")); sound->setVolume(FX_VOLUME); sound->play(); for(int i = 0; i < PIECE_NUM; i++) { pieces[i]->finish(); } } //해카톤 때문에 말이 죽었을 때 메세지를 띄운다. void User::HackathonDie() { if(current == 1) { sound->setMedia(QUrl::fromLocalFile("./sounds/girlDie.mp3")); } else { sound->setMedia(QUrl::fromLocalFile("./sounds/boyDie.wav")); } sound->setVolume(FX_VOLUME); sound->play(); disconnect(yes, SIGNAL(clicked()), 0, 0); label->close(); yes->close(); resetPiece(current); label = new QLabel(); label->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); QImage *info = new QImage(); QString filename = "./draw/info/die.png"; info->load(filename); label->setPixmap(QPixmap::fromImage(*info)); yes = new QPushButton(); yes->setCursor(Qt::PointingHandCursor); QPixmap yeap("./draw/info/confirm.png"); yes->setIcon(QIcon(yeap)); yes->setIconSize(yeap.rect().size()); yes->setFixedSize(yeap.rect().size()); yes->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); d->getScene()->addWidget(label); d->getScene()->addWidget(yes); label->setFixedSize(330, 275); label->move(-(label->width()/2), -(label->height()/2)); yes->move(-(yes->width()/2), 30); connect(yes, SIGNAL(clicked()), this, SLOT(dieconfirm())); } void User::PostechConfirm() { disconnect(yes, SIGNAL(clicked()), 0, 0); label->close(); yes->close(); srand(time(0)); int randomDamage = rand() % 50 + 30; bool death_check = pieces[current]->get_damage(randomDamage * pieces[current]->getNum()); d->setHPText(current, team, pieces[current]->getHP(), pieces[current]->getNum()*100); //말이 죽었을 때, 처음으로 돌려보내고, 메세지를 띄운다. if(death_check == true) { if(current == 1) { sound->setMedia(QUrl::fromLocalFile("./sounds/girlDie.mp3")); } else { sound->setMedia(QUrl::fromLocalFile("./sounds/boyDie.wav")); } sound->setVolume(FX_VOLUME); sound->play(); resetPiece(current); label = new QLabel(); label->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); QImage *info = new QImage(); QString filename = "./draw/info/die.png"; info->load(filename); label->setPixmap(QPixmap::fromImage(*info)); yes = new QPushButton(); yes->setCursor(Qt::PointingHandCursor); QPixmap yeap("./draw/info/confirm.png"); yes->setIcon(QIcon(yeap)); yes->setIconSize(yeap.rect().size()); yes->setFixedSize(yeap.rect().size()); yes->setStyleSheet("background-color: rgba(0, 0, 0, 0%);"); d->getScene()->addWidget(label); d->getScene()->addWidget(yes); label->setFixedSize(330, 275); label->move(-(label->width()/2), -(label->height()/2)); yes->move(-(yes->width()/2), 30); connect(yes, SIGNAL(clicked()), this, SLOT(dieconfirm())); } else emit updateDisplay(); }
26ae15903b7c0e76c4a7cb8b200a41b5432f5f0f
f61e971b402c99864899f9c4762fceeeb5300f74
/test/Vector2_test.cpp
0cd78a669acd8c2eb1b988416ba552a93c9b9418
[ "MIT" ]
permissive
lwesterl/PhysicsEngine
5c7d85c1f23932880604c11c90e3ed21711657d1
b528145a6b570a7bbb42c31552d8d8a99beb8d43
refs/heads/master
2020-04-15T18:09:58.252610
2019-08-30T08:43:24
2019-08-30T08:43:24
164,903,736
0
0
null
null
null
null
UTF-8
C++
false
false
4,750
cpp
Vector2_test.cpp
/** * @file Vector2_test.cpp * @author Lauri Westerholm * @brief Test main for Vector2 class */ #include "../utils/Vector2.hpp" #include <iostream> #include <cassert> /** * @brief Test main */ int main() { // constructor test std::cout << "Constructor Test" << std::endl; pe::Vector2f vectf(3.f, 10.f); pe::Vector2f vectf2 = pe::Vector2<float>(3.00, 10.000); pe::Vector2u vector2u; assert(vector2u.getX() == 0 && vector2u.getY() == 0); vector2u = pe::Vector2u(200, 100); std::cout << vector2u; std::cout << vector2u; assert(vectf == vectf2); pe::Vector2f vectf3 = vectf2; assert(vectf3 == vectf2); std::cout << "Test successful" << std::endl; // getX and getY test std::cout << std::endl << "getX() and getY() test" << std::endl; pe::Vector2d test1(10.00, 100.00); pe::Vector2d test2 = pe::Vector2d(test1.getX(), test1.getY()); assert(test2 == test1); assert(test2.getX() == test1.getX()); assert(test2.getY() == test1.getY()); std::cout << "Test successful" << std::endl; // update test std::cout << std::endl << "update() test" << std::endl; pe::Vector2i test3(10, 5); int val1 = 122; int val2 = 300; pe::Vector2i test4 = pe::Vector2i(val1, val2); assert(test3.getX() == 10 && test3.getY() == 5); test3.update(val1, val2); assert(test3.getX() == val1 && test3.getY() == val2); assert(test3 == test4); std::cout << "Test successful" << std::endl; // assignment test std::cout << std::endl << "Assignment test" << std::endl; pe::Vector2f test5(100.f, 100.f); pe::Vector2f test6(200.f, 200.f); pe::Vector2f test7; test7 = test5 + test6; assert(test7.getX() == 300.f && test7.getY() == 300.f); std::cout << "Test successful" << std::endl; // multiplication and sum test std::cout << std::endl << "Multiplication and sum test" << std::endl; pe::Vector2i test8(20, 40); pe::Vector2i test9 = pe::Vector2i(80, 60); test9 *= 100; assert(test9.getX() == 8000 && test9.getY() == 6000); test9 = test9 + test8; assert(test9.getX() == 8020 && test9.getY() == 6040); pe::Vector2i test10(10, 10); test9 = test9 * test10; assert(test9.getX() == 80200 && test9.getY() == 60400); assert(test10.getX() == 10 && test10.getY() == 10); std::cout << "Test successful" << std::endl; // greater than and smaller than operator tests std::cout << std::endl << "Greater and smaller than tests" << std::endl; pe::Vector2u test11(20, 40); pe::Vector2u test12(18, 41); pe::Vector2u test13(130, 45); assert(test13 > test11 && test13 > test12); assert(test12 < test13); assert(!(test12 < test11)); pe::Vector2u test14(20, 10); assert(test11 >= test14); pe::Vector2u test15(3, 10); assert(test15 <= test14); pe::Vector2u test16 = test15; assert(test16 >= test15 && test16 <= test15); std::cout << "Test successful" << std::endl; // dot product test std::cout << std::endl << "dotProduct tests" << std::endl; pe::Vector2i test17(10, 10); pe::Vector2i test18(2, 3); assert(test17.dotProduct(test18) == 50 && 50 == test18.dotProduct(test17)); pe::Vector2f test19(25.f, 5.f); pe::Vector2f test20(4.f, -8.f); assert(dotProduct(test19, test20) == test19.dotProduct(test20)); std::cout << dotProduct(test19, test20) << " == 60" << std::endl; std::cout << "Test successful" << std::endl; // normalize test std::cout << std::endl << "normaze test" << std::endl; pe::Vector2f test21(23.f, 39.f); test21.normalize(); std::cout << "after normalized: " << test21; assert(test21.getX() * test21.getX() + test21.getY() * test21.getY() == 1.f); std::cout << "Test successful" << std::endl; // rotation test std::cout << std::endl << "rotate test" << std::endl; pe::Vector2f test22(0.f, 1.f); test22.rotate(M_PI); std::cout << "After rotation (x = 0.f and y = -1.f): " << test22; pe::Vector2f test23(20.f, 23.f); test23.rotate(M_PI * 2.f); std::cout << "After rotation (x = 20.f, y = 23.f): " << test23; //assert(test23.getX() == 20.f && test23.getY() == 23.f); std::cout << "Test successful" << std::endl; // += and -= -operator tests std::cout << std::endl << "+= and -= -operator tests" << std::endl; pe::Vector2f test24(10.f, 20.f); test24 += pe::Vector2f(10.f, -10.f); assert(test24 == pe::Vector2f(20.f, 10.f)); test24 -= pe::Vector2f(20.f, 10.f); assert(test24.getX() == 0.f && test24.getY() == 0.f); pe::Vector2f test25(100.f, 100.f); test24.update(10.f, 10.f); assert(test24 == pe::Vector2f(10.f, 10.f)); test25 += test24; assert(test24 == pe::Vector2f(10.f, 10.f)); assert(test25 == pe::Vector2f(110.f, 110.f)); std::cout << "Test successful" << std::endl; std::cout << std::endl << "All tests passed" << std::endl; return 0; }
20b07993fbb3e42a46696db3e2a1b8fbee393ce4
b09a8f45f3491e7b5590fd5f7b971528e03aa8f2
/src/Tests/TestFunctional.cpp
077f4176bad5dc20387bea7fe880685d398e3624
[]
no_license
PoiXP/WhatIBuild
f27ca8c66c5b7cbe14ffeab14c69fae829f8002f
ac310bb8cdf7891fd5887461ed8f46ece97354ff
refs/heads/master
2021-01-22T20:25:53.772189
2012-11-11T15:12:34
2012-11-11T15:12:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,914
cpp
TestFunctional.cpp
#include <UnitTest++\src\UnitTest++.h> #include "Build.h" #include "BuildParser.h" #include "ReturnCode.h" using namespace WhatIBuild; SUITE(Test_ParseMSVCSolution) { TEST(testFileNotFound) { Build build; CHECK_EQUAL(e_Return_FileNotFound, Parser::ParseVSSolution("invlid_path", build)); } TEST(testFunctional) { Build build; CHECK_EQUAL(e_Return_OK, Parser::ParseVSSolution("..\\src\\Tests\\TestData\\Test.sln", build)); CHECK_EQUAL(2, build.GetModulesCount()); { const Module& module = build.GetModule(0u); CHECK_EQUAL("ProjectA", module.GetName()); CHECK_EQUAL("ProjectA\\ProjectA.vcxproj", module.GetPath()); CHECK_EQUAL(6, module.GetUnitsCount()); // CHECK_EQUAL("src\\CutsomBuilt1.file", module.GetUnit(0).GetFileName()); CHECK_EQUAL("ExcludedFile.cpp", module.GetUnit(0).GetFileName()); CHECK_EQUAL("File1.cpp", module.GetUnit(1).GetFileName()); CHECK_EQUAL("File2.cpp", module.GetUnit(2).GetFileName()); CHECK_EQUAL("common.h", module.GetUnit(3).GetFileName()); CHECK_EQUAL("File1.h", module.GetUnit(4).GetFileName()); CHECK_EQUAL("File2.h", module.GetUnit(5).GetFileName()); CHECK_EQUAL(2, module.GetProperty(Module::e_ProjectConfigurations).GetCount()); { const Property& prop = module.GetProperty(Module::e_ProjectConfigurations).GetProperty(0); CHECK_EQUAL("ProjectConfiguration", prop.GetName()); CHECK_EQUAL("Debug|Win32", prop.GetValue()); CHECK_EQUAL(2, prop.GetCount()); } { const Property& prop = module.GetProperty(Module::e_ProjectConfigurations).GetProperty(1); CHECK_EQUAL("ProjectConfiguration", prop.GetName()); CHECK_EQUAL("Release|Win32", prop.GetValue()); CHECK_EQUAL(2, prop.GetCount()); } CHECK_EQUAL(1, module.GetProperty(Module::e_Globals).GetCount()); { const Property& prop = module.GetProperty(Module::e_Globals).GetProperty(0); CHECK_EQUAL("Globals", prop.GetName()); CHECK_EQUAL("", prop.GetValue()); CHECK_EQUAL(3, prop.GetCount()); { struct Props { char name[64]; char value[64]; } props[] = { {"ProjectGuid", "{06D38399-0152-4053-B8A5-228AE55CC1BC}" }, {"Keyword", "Win32Proj" }, {"RootNamespace", "ProjectA" }, }; const size_t count = sizeof(props)/sizeof(props[0]); CHECK_EQUAL(count, prop.GetCount()); for (size_t i = 0; i < count; ++i) { CHECK_EQUAL(props[i].name, prop.GetProperty(i).GetName()); CHECK_EQUAL(props[i].value, prop.GetProperty(i).GetValue()); } } } CHECK_EQUAL(2, module.GetProperty(Module::e_ConfigurationSettings).GetCount()); { const Property& prop = module.GetProperty(Module::e_ConfigurationSettings).GetProperty(0); CHECK_EQUAL("Condition", prop.GetName()); CHECK_EQUAL("'$(Configuration)|$(Platform)'=='Debug|Win32'", prop.GetValue()); CHECK_EQUAL(2, prop.GetCount()); { const Property& compileProps = prop.GetProperty(0); CHECK_EQUAL("ClCompile", compileProps.GetName()); CHECK_EQUAL("", compileProps.GetValue()); struct Props { char name[64]; char value[64]; } props[] = { {"PrecompiledHeader", "" }, {"WarningLevel", "Level3" }, {"Optimization", "Disabled" }, {"PreprocessorDefinitions", "WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)" }, }; const size_t count = sizeof(props)/sizeof(props[0]); CHECK_EQUAL(count, compileProps.GetCount()); for (size_t i = 0; i < count; ++i) { CHECK_EQUAL(props[i].name, compileProps.GetProperty(i).GetName()); CHECK_EQUAL(props[i].value, compileProps.GetProperty(i).GetValue()); } } { const Property& linkerProps = prop.GetProperty(1); CHECK_EQUAL("Link", linkerProps.GetName()); CHECK_EQUAL("", linkerProps.GetValue()); struct Props { char name[64]; char value[64]; } props[] = { {"SubSystem", "Console" }, {"GenerateDebugInformation","true" }, }; const size_t count = sizeof(props)/sizeof(props[0]); CHECK_EQUAL(count, linkerProps.GetCount()); for (size_t i = 0; i < count; ++i) { CHECK_EQUAL(props[i].name, linkerProps.GetProperty(i).GetName()); CHECK_EQUAL(props[i].value, linkerProps.GetProperty(i).GetValue()); } } } { const Property& prop = module.GetProperty(Module::e_ConfigurationSettings).GetProperty(1); CHECK_EQUAL("Condition", prop.GetName()); CHECK_EQUAL("'$(Configuration)|$(Platform)'=='Release|Win32'", prop.GetValue()); CHECK_EQUAL(2, prop.GetCount()); { const Property& compileProps = prop.GetProperty(0); CHECK_EQUAL("ClCompile", compileProps.GetName()); CHECK_EQUAL("", compileProps.GetValue()); struct Props { char name[64]; char value[64]; } props[] = { {"WarningLevel", "Level3" }, {"PrecompiledHeader", "" }, {"Optimization", "MaxSpeed" }, {"FunctionLevelLinking", "true" }, {"IntrinsicFunctions", "true" }, {"PreprocessorDefinitions", "WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)" }, }; const size_t count = sizeof(props)/sizeof(props[0]); CHECK_EQUAL(count, compileProps.GetCount()); for (size_t i = 0; i < count; ++i) { CHECK_EQUAL(props[i].name, compileProps.GetProperty(i).GetName()); CHECK_EQUAL(props[i].value, compileProps.GetProperty(i).GetValue()); } } { const Property& linkerProps = prop.GetProperty(1); CHECK_EQUAL("Link", linkerProps.GetName()); CHECK_EQUAL("", linkerProps.GetValue()); struct Props { char name[64]; char value[64]; } props[] = { {"SubSystem", "Console" }, {"GenerateDebugInformation","true" }, {"EnableCOMDATFolding", "true" }, {"OptimizeReferences", "true" }, }; const size_t count = sizeof(props)/sizeof(props[0]); CHECK_EQUAL(count, linkerProps.GetCount()); for (size_t i = 0; i < count; ++i) { CHECK_EQUAL(props[i].name, linkerProps.GetProperty(i).GetName()); CHECK_EQUAL(props[i].value, linkerProps.GetProperty(i).GetValue()); } } } CHECK_EQUAL(2, module.GetProperty(Module::e_PropertySheets).GetCount()); { const Property& prop = module.GetProperty(Module::e_PropertySheets).GetProperty(0); CHECK_EQUAL("PropertySheets", prop.GetName()); CHECK_EQUAL("'$(Configuration)|$(Platform)'=='Debug|Win32'", prop.GetValue()); CHECK_EQUAL(1, prop.GetCount()); CHECK_EQUAL("Import", prop.GetProperty(0).GetName()); CHECK_EQUAL("$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props", prop.GetProperty(0).GetValue()); } { const Property& prop = module.GetProperty(Module::e_PropertySheets).GetProperty(1); CHECK_EQUAL("PropertySheets", prop.GetName()); CHECK_EQUAL("'$(Configuration)|$(Platform)'=='Release|Win32'", prop.GetValue()); CHECK_EQUAL(1, prop.GetCount()); CHECK_EQUAL("Import", prop.GetProperty(0).GetName()); CHECK_EQUAL("$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props", prop.GetProperty(0).GetValue()); } } CHECK_EQUAL(2, build.GetModulesCount()); { const Module& module = build.GetModule(1u); CHECK_EQUAL("ProjectB", module.GetName()); CHECK_EQUAL("ProjectB\\ProjectB.vcxproj", module.GetPath()); CHECK_EQUAL(5, module.GetUnitsCount()); CHECK_EQUAL("File1.cpp", module.GetUnit(0).GetFileName()); CHECK_EQUAL("File2.cpp", module.GetUnit(1).GetFileName()); CHECK_EQUAL("common.h", module.GetUnit(2).GetFileName()); CHECK_EQUAL("File1.h", module.GetUnit(3).GetFileName()); CHECK_EQUAL("File2.h", module.GetUnit(4).GetFileName()); } } }
c7081dd52683bbb4a5d80ec7ea859924d2086009
b4af26ef6994f4cbb738cdfd182e0a992d2e5baa
/source/CodeJam/2022_1_Round_C/2_Squary/hyo.cpp
9fb8f9906b72deca53365738e11284de24ee752b
[]
no_license
wisest30/AlgoStudy
6819b193c8e9245104fc52df5852cd487ae7a26e
112de912fc10933445c2ad36ce30fd404c493ddf
refs/heads/master
2023-08-08T17:01:12.324470
2023-08-06T11:54:15
2023-08-06T11:54:15
246,302,438
10
17
null
2021-09-26T13:52:18
2020-03-10T13:02:56
C++
UTF-8
C++
false
false
970
cpp
hyo.cpp
#include<bits/stdc++.h> using namespace std; using ll = long long; void solve(int TestCase) { int n, k; cin >> n >> k; long long s = 0, s2 = 0; for(auto i = 0; i < n; ++i) { long long x; cin >> x; s += x, s2 += x * x; } if(k == 1) { if(s == 0) { if(s2 != 0) cout << "IMPOSSIBLE" << endl; else cout << 1 << endl; return; } long long x = (s2 - s * s) / s; if(x % 2 == 1) { cout << "IMPOSSIBLE" << endl; return; } x /= 2; cout << x << endl; } else { long long x = 1 - s; long long y = (s2 - s * s - 2 * s * x) / 2; cout << x << " " << y << endl; } } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t = 1; cin >> t; for(auto i = 1; i <= t; ++i) { cout << "Case #"<< i << ": "; solve(i); } }
447ee8fcb3d05a62eec1aaad8f4a15e83fac99b6
45795f5735cfff4c83a83aa726b7483eb5a7e8c0
/smixx_v47r1/x86/src/translator/createobjectins.cxx
dcf7e1878c0f24cc6e3e84987cdfa0e81192f6f5
[]
no_license
wmoore28/clas12-epics-third-party-libs
260286981c57167f1852cff13b975e6c9ba5a907
b8701fee2638b5a0b6dcd7da5b5fd7aa3413b2ce
refs/heads/master
2020-03-16T22:48:44.195456
2018-05-11T14:56:13
2018-05-11T14:56:13
133,053,317
0
0
null
null
null
null
UTF-8
C++
false
false
3,944
cxx
createobjectins.cxx
// CreateObjectins.cxx: implementation of the CreateObjectIns class. // // B. Franek // April 2010 ////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include <assert.h> #include <string.h> #include "smlunit.hxx" #include "smlline.hxx" #include "name.hxx" #include "utilities.hxx" #include "createobjectins.hxx" #include "registrar.hxx" #include "errorwarning.hxx" extern Registrar allUnits; extern Registrar allClasses; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CreateObjectIns::CreateObjectIns() { _name = "CreateObject"; return; } CreateObjectIns::~CreateObjectIns() { delete _pSMLcode; } void CreateObjectIns::translate() { Name token; int idel,jdel; int inext,jnext; Name ofClass; SMLline lineBeingTranslated; lineBeingTranslated = (*_pSMLcode)[0]; char del = getNextToken(_pSMLcode,0,0," ",token,idel,jdel,inext,jnext); token.upCase(); token.trim(); if ( token == "CREATE_OBJECT" ) { lineBeingTranslated = (*_pSMLcode)[inext]; del = getNextToken(_pSMLcode,inext,jnext," ",_objectIdentifier,idel,jdel,inext,jnext); } else { ErrorWarning::printHead("ERROR",lineBeingTranslated); cout << "Expected CREATE_OBJECT instruction" << endl; exit(2); } if (_objectIdentifier[0] == '$') { Name tmpName="\0"; char* ptn = _objectIdentifier.getString(); int length = strlen(ptn); if ( *(ptn+1) == '(' && *(ptn+length-1) == ')') { *(ptn+length-1) = '\0'; tmpName = (ptn+2); _objectIdentifier = "&VAL_OF_"; _objectIdentifier += tmpName; } } _objectIdentifier.upCase(); _objectIdentifier.trim(); if (!check_name(_objectIdentifier)) { ErrorWarning::printHead("ERROR",lineBeingTranslated); cout << " Object identifier " << _objectIdentifier << " is not a name" << endl; exit(2); } lineBeingTranslated = (*_pSMLcode)[inext]; del = getNextToken(_pSMLcode,inext,jnext," ",ofClass,idel,jdel,inext,jnext); ofClass.upCase(); if ( ofClass == "OF_CLASS" ) {} else { ErrorWarning::printHead("ERROR",lineBeingTranslated ,"OF_CLASS keyword not found"); exit(2); } lineBeingTranslated = (*_pSMLcode)[inext]; del = getNextToken(_pSMLcode,inext,jnext," ",_className,idel,jdel,inext,jnext); _className.upCase(); _className.trim(); if (!check_name(_className)) { ErrorWarning::printHead("ERROR",lineBeingTranslated); cout << " Class name : " << _className << " is not a name" << endl; exit(2); } void *ptn = allClasses.gimePointer(_className); if (!ptn) { ErrorWarning::printHead("ERROR",lineBeingTranslated); cout << " Class : " << _className << " has not been declared" << endl; exit(2); } if (inext>0) { ErrorWarning::printHead("ERROR",lineBeingTranslated ,"Some crap is following CREATE_OBJECT instruction"); exit(2); } return; } //-------------------------------------------------------------------------- void CreateObjectIns::out(const Name offset) const { SMLUnit::out(offset); char* ptn=offset.getString(); cout << ptn ; cout << "createObject " << _objectIdentifier << " of_class " << _className << endl; return; } //------------------------------------------ BF April 2010 ----------- void CreateObjectIns::outSobj(int&,int,ofstream& sobj,Registrar&) const { sobj << "create_object" << endl; sobj << _objectIdentifier.getString() << endl; // The following line makes it look like declaration of an object belonging // to class and also having no attributes of its own... see isofclassobject.cxx int n1,n2,n3; char line[80]; n1 = 1; n2 = 0; n3 = 0; sprintf(line,"%5d%5d%5d",n1,n2,n3); sobj << line << endl; //---------------------------------------------------------------- sobj << _className.getString() << endl; return; }
c2041dd6cb34e944f62e4cb955f3ac586108a1da
9eb4f472070b39db09e7088b173edb24d2af4652
/Hadrons/Graph.hpp
65c741069fdb3703616d8e0962657a207f5b51bc
[]
no_license
guelpers/Hadrons
55dd3b2e5e87605e459f5066f47238ab452aeae0
735e5c0f10bbfaaf52e2efc5ead1010f5ac50bc6
refs/heads/master
2023-02-23T12:13:29.085574
2020-03-27T17:53:07
2020-03-27T17:53:07
252,408,759
0
0
null
2020-04-02T09:17:12
2020-04-02T09:17:11
null
UTF-8
C++
false
false
18,275
hpp
Graph.hpp
/************************************************************************************* Grid physics library, www.github.com/paboyle/Grid Source file: Hadrons/Graph.hpp Copyright (C) 2015-2019 Author: Antonin Portelli <antonin.portelli@me.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. See the full license in the file "LICENSE" in the top level distribution directory *************************************************************************************/ /* END LEGAL */ #ifndef Hadrons_Graph_hpp_ #define Hadrons_Graph_hpp_ #include <Hadrons/Global.hpp> BEGIN_HADRONS_NAMESPACE /****************************************************************************** * Oriented graph class * ******************************************************************************/ // I/O for edges template <typename T> std::ostream & operator<<(std::ostream &out, const std::pair<T, T> &e) { out << "\"" << e.first << "\" -> \"" << e.second << "\""; return out; } // main class template <typename T> class Graph { public: typedef std::pair<T, T> Edge; public: // constructor Graph(void); // destructor virtual ~Graph(void) = default; // access void addVertex(const T &value); void addEdge(const Edge &e); void addEdge(const T &start, const T &end); std::vector<T> getVertices(void) const; void removeVertex(const T &value); void removeEdge(const Edge &e); void removeEdge(const T &start, const T &end); unsigned int size(void) const; // tests bool gotValue(const T &value) const; // graph topological manipulations std::vector<T> getAdjacentVertices(const T &value) const; std::vector<T> getChildren(const T &value) const; std::vector<T> getParents(const T &value) const; std::vector<T> getRoots(void) const; std::vector<Graph<T>> getConnectedComponents(void) const; std::vector<T> topoSort(void); template <typename Gen> std::vector<T> topoSort(Gen &gen); std::vector<std::vector<T>> allTopoSort(void); // I/O friend std::ostream & operator<<(std::ostream &out, const Graph<T> &g) { out << "{"; for (auto &e: g.edgeSet_) { out << e << ", "; } if (g.edgeSet_.size() != 0) { out << "\b\b"; } out << "}"; return out; } private: // vertex marking void mark(const T &value, const bool doMark = true); void markAll(const bool doMark = true); void unmark(const T &value); void unmarkAll(void); bool isMarked(const T &value) const; const T * getFirstMarked(const bool isMarked = true) const; template <typename Gen> const T * getRandomMarked(const bool isMarked, Gen &gen); const T * getFirstUnmarked(void) const; template <typename Gen> const T * getRandomUnmarked(Gen &gen); // prune marked/unmarked vertices void removeMarked(const bool isMarked = true); void removeUnmarked(void); // depth-first search marking void depthFirstSearch(void); void depthFirstSearch(const T &root); private: std::map<T, bool> isMarked_; std::set<Edge> edgeSet_; }; // build depedency matrix from topological sorts template <typename T> std::map<T, std::map<T, bool>> makeDependencyMatrix(const std::vector<std::vector<T>> &topSort); /****************************************************************************** * template implementation * ****************************************************************************** * in all the following V is the number of vertex and E is the number of edge * in the worst case E = V^2 */ // constructor ///////////////////////////////////////////////////////////////// template <typename T> Graph<T>::Graph(void) {} // access ////////////////////////////////////////////////////////////////////// // complexity: log(V) template <typename T> void Graph<T>::addVertex(const T &value) { isMarked_[value] = false; } // complexity: O(log(V)) template <typename T> void Graph<T>::addEdge(const Edge &e) { addVertex(e.first); addVertex(e.second); edgeSet_.insert(e); } // complexity: O(log(V)) template <typename T> void Graph<T>::addEdge(const T &start, const T &end) { addEdge(Edge(start, end)); } template <typename T> std::vector<T> Graph<T>::getVertices(void) const { std::vector<T> vertex; for (auto &v: isMarked_) { vertex.push_back(v.first); } return vertex; } // complexity: O(V*log(V)) template <typename T> void Graph<T>::removeVertex(const T &value) { // remove vertex from the mark table auto vIt = isMarked_.find(value); if (vIt != isMarked_.end()) { isMarked_.erase(vIt); } else { HADRONS_ERROR(Range, "vertex does not exists"); } // remove all edges containing the vertex auto pred = [&value](const Edge &e) { return ((e.first == value) or (e.second == value)); }; auto eIt = find_if(edgeSet_.begin(), edgeSet_.end(), pred); while (eIt != edgeSet_.end()) { edgeSet_.erase(eIt); eIt = find_if(edgeSet_.begin(), edgeSet_.end(), pred); } } // complexity: O(log(V)) template <typename T> void Graph<T>::removeEdge(const Edge &e) { auto eIt = edgeSet_.find(e); if (eIt != edgeSet_.end()) { edgeSet_.erase(eIt); } else { HADRONS_ERROR(Range, "edge does not exists"); } } // complexity: O(log(V)) template <typename T> void Graph<T>::removeEdge(const T &start, const T &end) { removeEdge(Edge(start, end)); } // complexity: O(1) template <typename T> unsigned int Graph<T>::size(void) const { return isMarked_.size(); } // tests /////////////////////////////////////////////////////////////////////// // complexity: O(log(V)) template <typename T> bool Graph<T>::gotValue(const T &value) const { auto it = isMarked_.find(value); if (it == isMarked_.end()) { return false; } else { return true; } } // vertex marking ////////////////////////////////////////////////////////////// // complexity: O(log(V)) template <typename T> void Graph<T>::mark(const T &value, const bool doMark) { if (gotValue(value)) { isMarked_[value] = doMark; } else { HADRONS_ERROR(Range, "vertex does not exists"); } } // complexity: O(V*log(V)) template <typename T> void Graph<T>::markAll(const bool doMark) { for (auto &v: isMarked_) { mark(v.first, doMark); } } // complexity: O(log(V)) template <typename T> void Graph<T>::unmark(const T &value) { mark(value, false); } // complexity: O(V*log(V)) template <typename T> void Graph<T>::unmarkAll(void) { markAll(false); } // complexity: O(log(V)) template <typename T> bool Graph<T>::isMarked(const T &value) const { if (gotValue(value)) { return isMarked_.at(value); } else { HADRONS_ERROR(Range, "vertex does not exists"); return false; } } // complexity: O(log(V)) template <typename T> const T * Graph<T>::getFirstMarked(const bool isMarked) const { auto pred = [&isMarked](const std::pair<T, bool> &v) { return (v.second == isMarked); }; auto vIt = std::find_if(isMarked_.begin(), isMarked_.end(), pred); if (vIt != isMarked_.end()) { return &(vIt->first); } else { return nullptr; } } // complexity: O(log(V)) template <typename T> template <typename Gen> const T * Graph<T>::getRandomMarked(const bool isMarked, Gen &gen) { auto pred = [&isMarked](const std::pair<T, bool> &v) { return (v.second == isMarked); }; std::uniform_int_distribution<unsigned int> dis(0, size() - 1); auto rIt = isMarked_.begin(); std::advance(rIt, dis(gen)); auto vIt = std::find_if(rIt, isMarked_.end(), pred); if (vIt != isMarked_.end()) { return &(vIt->first); } else { vIt = std::find_if(isMarked_.begin(), rIt, pred); if (vIt != rIt) { return &(vIt->first); } else { return nullptr; } } } // complexity: O(log(V)) template <typename T> const T * Graph<T>::getFirstUnmarked(void) const { return getFirstMarked(false); } // complexity: O(log(V)) template <typename T> template <typename Gen> const T * Graph<T>::getRandomUnmarked(Gen &gen) { return getRandomMarked(false, gen); } // prune marked/unmarked vertices ////////////////////////////////////////////// // complexity: O(V^2*log(V)) template <typename T> void Graph<T>::removeMarked(const bool isMarked) { auto isMarkedCopy = isMarked_; for (auto &v: isMarkedCopy) { if (v.second == isMarked) { removeVertex(v.first); } } } // complexity: O(V^2*log(V)) template <typename T> void Graph<T>::removeUnmarked(void) { removeMarked(false); } // depth-first search marking ////////////////////////////////////////////////// // complexity: O(V*log(V)) template <typename T> void Graph<T>::depthFirstSearch(void) { depthFirstSearch(isMarked_.begin()->first); } // complexity: O(V*log(V)) template <typename T> void Graph<T>::depthFirstSearch(const T &root) { std::vector<T> adjacentVertex; mark(root); adjacentVertex = getAdjacentVertices(root); for (auto &v: adjacentVertex) { if (!isMarked(v)) { depthFirstSearch(v); } } } // graph topological manipulations ///////////////////////////////////////////// // complexity: O(V*log(V)) template <typename T> std::vector<T> Graph<T>::getAdjacentVertices(const T &value) const { std::vector<T> adjacentVertex; auto pred = [&value](const Edge &e) { return ((e.first == value) or (e.second == value)); }; auto eIt = std::find_if(edgeSet_.begin(), edgeSet_.end(), pred); while (eIt != edgeSet_.end()) { if (eIt->first == value) { adjacentVertex.push_back((*eIt).second); } else if (eIt->second == value) { adjacentVertex.push_back((*eIt).first); } eIt = std::find_if(++eIt, edgeSet_.end(), pred); } return adjacentVertex; } // complexity: O(V*log(V)) template <typename T> std::vector<T> Graph<T>::getChildren(const T &value) const { std::vector<T> child; auto pred = [&value](const Edge &e) { return (e.first == value); }; auto eIt = std::find_if(edgeSet_.begin(), edgeSet_.end(), pred); while (eIt != edgeSet_.end()) { child.push_back((*eIt).second); eIt = std::find_if(++eIt, edgeSet_.end(), pred); } return child; } // complexity: O(V*log(V)) template <typename T> std::vector<T> Graph<T>::getParents(const T &value) const { std::vector<T> parent; auto pred = [&value](const Edge &e) { return (e.second == value); }; auto eIt = std::find_if(edgeSet_.begin(), edgeSet_.end(), pred); while (eIt != edgeSet_.end()) { parent.push_back((*eIt).first); eIt = std::find_if(++eIt, edgeSet_.end(), pred); } return parent; } // complexity: O(V^2*log(V)) template <typename T> std::vector<T> Graph<T>::getRoots(void) const { std::vector<T> root; for (auto &v: isMarked_) { auto parent = getParents(v.first); if (parent.size() == 0) { root.push_back(v.first); } } return root; } // complexity: O(V^2*log(V)) template <typename T> std::vector<Graph<T>> Graph<T>::getConnectedComponents(void) const { std::vector<Graph<T>> res; Graph<T> copy(*this); while (copy.size() > 0) { copy.depthFirstSearch(); res.push_back(copy); res.back().removeUnmarked(); res.back().unmarkAll(); copy.removeMarked(); copy.unmarkAll(); } return res; } // topological sort using a directed DFS algorithm // complexity: O(V*log(V)) template <typename T> std::vector<T> Graph<T>::topoSort(void) { std::stack<T> buf; std::vector<T> res; const T *vPt; std::map<T, bool> tmpMarked(isMarked_); // visit function std::function<void(const T &)> visit = [&](const T &v) { if (tmpMarked.at(v)) { HADRONS_ERROR(Range, "cannot topologically sort a cyclic graph"); } if (!isMarked(v)) { std::vector<T> child = getChildren(v); tmpMarked[v] = true; for (auto &c: child) { visit(c); } mark(v); tmpMarked[v] = false; buf.push(v); } }; // reset temporary marks for (auto &v: tmpMarked) { tmpMarked.at(v.first) = false; } // loop on unmarked vertices unmarkAll(); vPt = getFirstUnmarked(); while (vPt) { visit(*vPt); vPt = getFirstUnmarked(); } unmarkAll(); // create result vector while (!buf.empty()) { res.push_back(buf.top()); buf.pop(); } return res; } // random version of the topological sort // complexity: O(V*log(V)) template <typename T> template <typename Gen> std::vector<T> Graph<T>::topoSort(Gen &gen) { std::stack<T> buf; std::vector<T> res; const T *vPt; std::map<T, bool> tmpMarked(isMarked_); // visit function std::function<void(const T &)> visit = [&](const T &v) { if (tmpMarked.at(v)) { HADRONS_ERROR(Range, "cannot topologically sort a cyclic graph"); } if (!isMarked(v)) { std::vector<T> child = getChildren(v); tmpMarked[v] = true; std::shuffle(child.begin(), child.end(), gen); for (auto &c: child) { visit(c); } mark(v); tmpMarked[v] = false; buf.push(v); } }; // reset temporary marks for (auto &v: tmpMarked) { tmpMarked.at(v.first) = false; } // loop on unmarked vertices unmarkAll(); vPt = getRandomUnmarked(gen); while (vPt) { visit(*vPt); vPt = getRandomUnmarked(gen); } unmarkAll(); // create result vector while (!buf.empty()) { res.push_back(buf.top()); buf.pop(); } return res; } // generate all possible topological sorts // Y. L. Varol & D. Rotem, Comput. J. 24(1), pp. 83–84, 1981 // http://comjnl.oupjournals.org/cgi/doi/10.1093/comjnl/24.1.83 // complexity: O(V*log(V)) (from the paper, but really ?) template <typename T> std::vector<std::vector<T>> Graph<T>::allTopoSort(void) { std::vector<std::vector<T>> res; std::map<T, std::map<T, bool>> iMat; // create incidence matrix for (auto &v1: isMarked_) for (auto &v2: isMarked_) { iMat[v1.first][v2.first] = false; } for (auto &v: isMarked_) { auto cVec = getChildren(v.first); for (auto &c: cVec) { iMat[v.first][c] = true; } } // generate initial topological sort res.push_back(topoSort()); // generate all other topological sorts by permutation std::vector<T> p = res[0]; const unsigned int n = size(); std::vector<unsigned int> loc(n); unsigned int i, k, k1; T obj_k, obj_k1; bool isFinal; for (unsigned int j = 0; j < n; ++j) { loc[j] = j; } i = 0; while (i < n-1) { k = loc[i]; k1 = k + 1; obj_k = p[k]; if (k1 >= n) { isFinal = true; obj_k1 = obj_k; } else { isFinal = false; obj_k1 = p[k1]; } if (iMat[res[0][i]][obj_k1] or isFinal) { for (unsigned int l = k; l >= i + 1; --l) { p[l] = p[l-1]; } p[i] = obj_k; loc[i] = i; i++; } else { p[k] = obj_k1; p[k1] = obj_k; loc[i] = k1; i = 0; res.push_back(p); } } return res; } // build depedency matrix from topological sorts /////////////////////////////// // complexity: something like O(V^2*log(V!)) template <typename T> std::map<T, std::map<T, bool>> makeDependencyMatrix(const std::vector<std::vector<T>> &topSort) { std::map<T, std::map<T, bool>> m; const std::vector<T> &vList = topSort[0]; for (auto &v1: vList) for (auto &v2: vList) { bool dep = true; for (auto &t: topSort) { auto i1 = std::find(t.begin(), t.end(), v1); auto i2 = std::find(t.begin(), t.end(), v2); dep = dep and (i1 - i2 > 0); if (!dep) break; } m[v1][v2] = dep; } return m; } END_HADRONS_NAMESPACE #endif // Hadrons_Graph_hpp_
f606fb5cdb9919379ae16d9a024fc6fd7f70155c
833e2e24593e85f4d48c4e4b5a5fd468378088ce
/ip_packet.h
a042b04b413bc002934f1f63d8a1b754feb4df7a
[]
no_license
FMX/packet_flip
8955035ef0a43c5e98ca23b69417d5e0fcb4f95f
7710968851173097888f4ee07284388a1d7cb677
refs/heads/master
2021-06-02T16:41:47.976489
2016-09-05T03:08:38
2016-09-05T03:08:38
67,197,067
0
0
null
null
null
null
UTF-8
C++
false
false
637
h
ip_packet.h
// // Created by MINX Feng on 16/9/2. // #ifndef PACKET_FLIP_IP_PACKET_H #define PACKET_FLIP_IP_PACKET_H #include "commonheader.h" #include "structs.h" class ip_packet { private: unsigned short version; unsigned short headerlen; unsigned char tos; unsigned short totallen; unsigned char identifier; unsigned short flag; unsigned short offset; unsigned char ttl; unsigned char proto; unsigned short checksum; ip_addr src; ip_addr dst; boost::shared_array<char> packet; public: ip_packet(); void setData(boost::shared_array<char> data); }; #endif //PACKET_FLIP_IP_PACKET_H
b89c6151bc005b8d0d0dc9e0566fc578b2e6ba67
890eb8e28dab8463138d6ae80359c80c4cf03ddd
/SMPF/SMPFProtocol/Core/Channel/RSM/smpf_RsmEventSchedInfoCtrl.cpp
1c91dc9f27892c9939cf82cc6bdb680757b57951
[]
no_license
grant-h/shannon_S5123
d8c8dd1a2b49a9fe08268487b0af70ec3a19a5b2
8f7acbfdcf198779ed2734635990b36974657b7b
refs/heads/master
2022-06-17T05:43:03.224087
2020-05-06T15:39:39
2020-05-06T15:39:39
261,804,799
7
1
null
null
null
null
UTF-8
C++
false
false
6,303
cpp
smpf_RsmEventSchedInfoCtrl.cpp
Line 141: [RSM(API),%s] : ESI table is registred to RSIG in CreateESIT (RAT:%s) Line 146: [RSM(API),%s] : (F) Unknown Rat type is set on ESIC creation. (RAT:%s) Line 154: [RSM(API),%s] : ESI table is registred to RSIG in CreateESIT (RAT:%s) Line 159: [RSM(API),%s] : (F) Unknown Rat type is set on ESIC creation. (RAT:%s) Line 164: [RSM(API),%s] : (F) Unknown Domain type is set on ESIC creation. (RAT:%s) Line 190: [RSM(ESIC),%s] : CreateEventSchedInfo (%u:%s) Line 201: [RSM(ESIC),%s] : (F) Need to check !!!!!!!CreateEventSchedInfo! Line 213: [RSM(ESIC),%s] : CreateEventSchedInfoTable Line 235: [RSM(ESIC),%s] : MappingExceptionObjId - EventName: %s, EventId: %d, ObjId: 0x%x Line 239: [RSM(ESIC),%s] : (F) MappingExceptionObjId - pEventSchedInfo is null ptr!! Line 297: [RSM(ESIC),%s] : ESIC Initialize complete. Domain type = %u, Rat type = %s. Line 317: ID:%3u:%15s, Weight:%u, Pending:%u, State:%s, S:%10u, E:%10u Line 372: ID:%3u:%15s, Weight:%u, Pending:%u, State:%s, S:%10u, E:%10u Line 404: [RSM(ESIC),%s] : (DP) SetIsInConnected(false) Line 562: [RSM(ESIC),%s] : GetNearestEventTime(Error case) - EventId: %s, CurPaltime Time: %u, StartTime: %u, RemainTime: %u Line 569: [RSM(ESIC),%s] : GetNearestEventTime(Roll over) - EventId: %s, CurPaltime Time: %u, StartTime: %u, RemainTime: %u Line 579: [RSM(ESIC),%s] : GetNearestEventTime(Error case) - EventId: %s, CurPaltime Time: %u, StartTime: %u, RemainTime: %u Line 582: [RSM(ESIC),%s] : GetNearestEventTime - EventId: %s, CurPaltime Time: %u, StartTime: %u, RemainTime: %u Line 605: [RSM(ESIC),%s] : GetNearestEventTime - Nearest Event Time: %u Line 616: [RSM(ESIC),%s] : Start EsicEmptyEventGuardTimer Rat:%s Line 621: [RSM(ESIC),%s] : Already started Esic Empty Event Guard timer Rat:%s Line 629: [RSM(ESIC),%s] : Stop EsicEmptyEventGuardTimer Rat:%s Line 648: [RSM(ESIC),%s] : ESIC ===> L1C, Confirm RUN: %s Line 662: [RSM(ESIC),%s] : 1xPaging Sending result is fail (%s on HSCH run, Req_EventId(%s), 1xPagingState(%u)) Line 666: [RSM(ESIC),%s] : 1xPaging Sending result is true (%s on HSCH run, Req_EventId(%s), 1xPagingState(%u)) Line 671: [RSM(ESIC),%s] : 1xPaging is not EVENT_IDLE (%s on HSCH run, Req_EventId(%s), 1xPagingState(%u)) Line 676: [RSM(ESIC),%s] : 1xESIC is nullptr (%s on HSCH run, Req_EventId(%s)) Line 690: [RSM(ESIC),%s] : ESIC ===> L1C, Request %s: %s Line 699: [RSM(ESIC),%s] : ESIC ===> L1C, Request %s: %s Line 716: [RSM(ESIC),%s] : (F) Error !!!!!SendConfirmEventResult!!!!!! Line 755: [RSM(ESIC),%s] : (I) ESIC <=== RSIG, %s. Event:%s, m_ESICProcedureState:%s Line 795: [RSM(ESIC),%s] : Skip Trigger Stop message rat:%s, id:%s Line 857: [RSM(ESIC),%s] : SendExceptionMsg - ExceptionObjId: 0x%x, EventId: %s, ExceptionCause: %s Line 863: [RSM(ESIC),%s] : SendExceptionMsg - internal msg fail, Send external msg Line 900: [RSM(ESIC),%s] : SendExeptionCauseToCtrler(STOP) -> WakeUpCause(%s), Reject Exception Msg Pending Line 911: [RSM(ESIC),%s] : (F) Error !!!!!SendExeptionCauseToCtrler ID:%u, result:%u !!!!!! Line 965: [RSM(ESIC),%s] : EventSchedInfoCtrl::ESIC_STATE_Handler state:%s, Rat:%s, event id:%s Line 1025: [RSM(ESIC),%s] : (I) SetModemState(%s): %s -> %s, ActiveRAT(%d) Line 1043: [RSM(ESIC),%s] : (F) Need to check Active Rat(%s), ModemState:%s Line 1115: [RSM(ESIC),%s] : (F) Modem state error !!! (%d) Line 1157: [RSM(ESIC),%s] : (F) Modem state error !!! (%d) Line 1207: [RSM(ESIC),%s] : %s event Hold state, Pass Sleep check Line 1218: [RSM(ESIC),%s] : Check sleep: %s Line 1297: [RSM(ESIC),%s] : (I) Rat:%s, Power down guard timer is started. Nearest Event Time %u, Paging time margin %u Line 1368: [RSM(ESIC),%s] : Already Modem Hold state rat:%s(%s), id:%s Line 1377: [RSM(ESIC),%s] : EsicHoldProc during EsicEmptyEventGuardTimer running, Rat:%s Line 1407: [RSM(ESIC),%s] : Skip Trigger Hold message rat:%s, id:%s Line 1439: [RSM(ESIC),%s] : (I) SetHoldCause. %s -> %s Line 1443: [RSM(ESIC),%s] : ESIC's hold cause is only support MSD driven hold Line 1479: [RSM(ESIC),%s] : Start RetryEventTmr(100ms) Rat:%s, RetryEventId:%s Line 1485: [RSM(ESIC),%s] : Already started Retry timer Rat:%s, RetryEventId:%s Line 1488: [RSM(ESIC),%s] : Change Retry EventId Rat:%s, RetryEventId:%s Line 1498: [RSM(ESIC),%s] : Arleady started Hold Procedure. Rat:%s, HoldCause:%s Line 1502: [RSM(ESIC),%s] : Start HoldDelayTimerStart(20ms) Rat:%s, HoldCause:%s Line 1509: [RSM(ESIC),%s] : Already started Hold Delay timer Rat:%s, HoldCause:%s Line 1568: [RSM(ESIC),%s] : ResumeTriggerHoldEvent Line 1586: [RSM(ESIC),%s] : ResumeRunngingHoldEvent Line 1682: [RSM(ESIC),%s] : ESIC priority:%s, event %s Line 1698: [RSM(ESIC),%s] : WakeUpCause[%s] is higher priority than highest priority event[%s]. Line 1728: [RSM(ESIC),%s] : Stop HoldDelayTimer Rat:%s Line 1733: [RSM(ESIC),%s] : Already stopped Hold Delay timer Rat:%s Line 1759: [RSM(ESIC),%s] : ESIC ===> L1C, Confirm TRIGGER RESUME: %s Line 1772: [RSM(ESIC),%s] : (I) PwrDwnGuardCbFunc is called by timer. Rat:%s Line 1781: [RSM(ESIC),%s] : (I) RetryEventCbFunc is called by timer. Rat:%s, RetryEventId:%s, EventState:%s, m_ESICState:%d Line 1791: [RSM(ESIC),%s] : (I) HoldDelayCbFunc is called by timer. Rat:%s Line 1814: [RSM(ESIC),%s] : (I) EsicEmptyEventGuardCbFunc is called by timer. Rat:%s, Prev Highest Event ID:%s, ESIC State:%s Line 1837: [RSM(ESIC),%s] : (I) Event(%s) is Updated while RAT(%s) is suspended!!. Line 1847: [RSM(ESIC),%s] : (I) Skip Resume Done, Latest WaitCause is %s Line 1853: [RSM(ESIC),%s] : (I) Skip Hold Done, Latest WaitCause is %s Line 1872: [RSM(ESIC),%s] : ESIC <=== L1C, Request: %s, start: %u, end:%u, Status:%s, WakeUpCause:%s Line 1883: [RSM(ESIC),%s] : ESIC <=== L1C, Request: %s, start: %u, end:%u, Status:%s Line 1925: [RSM(ESIC),%s] : (F) UpdateSchedInfo, ERROR: Unknown property(%u) had been inputed. Line 1935: [RSM(ESIC),%s] : ESIC <=== L1C, Stop: %s, start: %u, end:%u, Status:%s, WakeUpCause:%s Line 1973: [RSM(ESIC),%s] : ESIC <=== L1C, Hold(%s) done: %s, start: %u, end:%u, Status:%s, WakeUpCause:%s Line 1981: [RSM(ESIC),%s] : ESIC <=== L1C, Hold(%s) done: %s, start: %u, end:%u, Status:%s, WakeUpCause:%s Line 1993: [RSM(ESIC),%s] : ESIC <=== L1C, Resume done: %s, start: %u, end:%u, Status:%s, WakeUp:%s Line 2002: [RSM(ESIC),%s] : (F) UpdateSchedInfo, ERROR: Unknown request(%u) had been inputed.
b81676f4e681e0d8af7e2960375a741f81dfad1d
a4a03d391f0c911e5b0aed27fe21e4eb36624609
/HDU/6298/14830812_AC_670ms_1372kB.cpp
7693e3f8239bf6f9d20fe23c0418d68548467d43
[]
no_license
jiaaaaaaaqi/ACM_Code
5e689bed9261ba768cfbfa01b39bd8fb0992e560
66b222d15544f6477cd04190c0d7397f232ed15e
refs/heads/master
2020-05-21T21:38:57.727420
2019-12-11T14:30:52
2019-12-11T14:30:52
186,153,816
0
0
null
null
null
null
UTF-8
C++
false
false
894
cpp
14830812_AC_670ms_1372kB.cpp
#include<map> #include<set> #include<ctime> #include<cmath> #include<stack> #include<queue> #include<string> #include<vector> #include<cstdio> #include<cstdlib> #include<cstring> #include<iostream> #include<algorithm> #define lowbit(x) (x & (-x)) typedef unsigned long long int ull; typedef long long int ll; const double pi = 4.0*atan(1.0); const int inf = 0x3f3f3f3f; const int maxn = 1005; const int maxm = 30005; const int mod = 1000000007; using namespace std; ll n, m, tol; int main() { int T; scanf("%d", &T); while(T--) { ll ans = -1; scanf("%lld", &n); if(n % 3 == 0) { m = n / 3; ans = m * m * m; } else if (n % 2 == 0) { m = n / 2; if(m % 2 == 0) { ll z = m / 2; ans = m * z * z; } } printf("%lld\n", ans); } return 0; }
7cf3d3db04d00269c0fdace68ccaf681b0372cae
3cdaaf8200e983388b349325fa2aeedf17d801d6
/settingdialog.cpp
40031f540b3664dd9004a3ac2119dfa18ab4368e
[]
no_license
welter/qt_phoneremoter
59aff00da18dbf8a1fd186052fa9111372daa1c0
8d2f99467292512ad866964d34e2e72fa3218ed9
refs/heads/master
2021-08-08T12:33:53.802171
2017-11-10T09:20:45
2017-11-10T09:20:45
107,765,169
0
0
null
null
null
null
UTF-8
C++
false
false
614
cpp
settingdialog.cpp
#include "settingdialog.h" #include "ui_settingdialog.h" #include <mainwindow.h> settingDialog::settingDialog(QWidget *parent) : QDialog(parent), ui(new Ui::settingDialog) { // char * _p=parent; p=dynamic_cast <MainWindow *>(parent); ui->setupUi(this); ui->edPhoneAddr->setText(dynamic_cast <MainWindow *>(parent)->_phoneAddr); ui->edPhonePort->setText(QString::number(p->_phonePort)); } settingDialog::~settingDialog() { } void settingDialog::on_buttonBox_accepted() { p->_phoneAddr=ui->edPhoneAddr->text(); p->_phonePort=ui->edPhonePort->text().toShort(); delete ui; }
a656cf3e7447d63ebc8772c7cbd70e6928622342
2f043c25112654d72a09ba8f0c1bfaba9a846b1b
/toltec/ui/commands/createCube.cpp
48c25a8381774a7aa1ccd270e788d74f8afb329a
[]
no_license
fsanges/toltec
79636833935fcc80447c7df939f2f8437acf3665
164e80bca4c72adb405e567db6c6703540edf00b
refs/heads/master
2020-06-11T22:11:19.424655
2017-09-30T08:32:01
2017-09-30T08:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,050
cpp
createCube.cpp
/*----------------------------------------------------------------------------- * CREATED: * 03 VIII 2017 * CONTRIBUTORS: * Piotr Makal *-----------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------- * IMPORTS *-----------------------------------------------------------------------------*/ #include "creationCommands.hpp" #include <memory> #include <vector> #include <glm/glm.hpp> #include "guiManager.hpp" #include "nodes/attributes/attributeShaderProgramID.hpp" #include "nodes/shaders/shaderProgramNode.hpp" #include "nodes/transformNode.hpp" #include "toltecPolygonMeshLibrary/mesh.hpp" #include "resourceManager.hpp" /*----------------------------------------------------------------------------- * NAMESPACE: UI (USER ITERFACE) *-----------------------------------------------------------------------------*/ namespace ui { /*----------------------------------------------------------------------------- * NAMESPACE: CMDS (COMMANDS) *-----------------------------------------------------------------------------*/ namespace cmds { /*----------------------------------------------------------------------------- * FUNCTION DEFINITIONS * CREATE CUBE *-----------------------------------------------------------------------------*/ core::nodes::PolygonMeshNode* createCube() { //CREATE TRANSFORM NODE auto p_transformNode = std::make_unique<core::nodes::TransformNode>(); p_transformNode->setName("polyCube"); //DEFINE CUBE POINTS std::vector<glm::vec3> point3DList = { glm::vec3{ -0.5f, -0.5f, 0.5f }, //0 glm::vec3{ 0.5f, -0.5f, 0.5f }, //1 glm::vec3{ 0.5f, 0.5f, 0.5f }, //2 glm::vec3{ -0.5f, 0.5f, 0.5f }, //3 glm::vec3{ -0.5f, -0.5f, -0.5f }, //4 glm::vec3{ 0.5f, -0.5f, -0.5f }, //5 glm::vec3{ 0.5f, 0.5f, -0.5f }, //6 glm::vec3{ -0.5f, 0.5f, -0.5f } //7 }; //DEFINE VERTEX SEQUENCE std::vector<unsigned int> faceVertexSequence = { 0, 1, 2, 3, 7, 6, 5, 4, 1, 0, 4, 5, 2, 1, 5, 6, 3, 2, 6, 7, 0, 3, 7, 4 }; //DEFINE POLYGON OFFSET LIST std::vector<unsigned int> polygonOffsetList = { 4, 4, 4, 4, 4, 4 }; //CREATE POLYGON MESH NODE auto p_polygonMeshNode = std::make_unique<core::nodes::PolygonMeshNode>(); p_polygonMeshNode->setName("polyCube"); p_polygonMeshNode->createMesh(point3DList, faceVertexSequence, polygonOffsetList); //SET SCENE TREE p_polygonMeshNode->setParent(p_transformNode.get()); p_transformNode->setParent(ResourceManager::getInstance().getRootTransformNode()); //ATTRIBUTE CONNECTIONS //get shaderProgramID core::nodes::ShaderProgramNode* p_shaderProgramNode = ResourceManager::getInstance().getDedicatedShaderProgramNode( ResourceManager::DedicatedShaderProgram::DEFAULT_SURFACE); core::nodes::AttributeShaderProgramID* p_aShaderProgramID = static_cast<core::nodes::AttributeShaderProgramID*>( p_shaderProgramNode->getAttribute(core::nodes::ShaderProgramNode::aID_shaderProgramID)); //get inputShaderProgramID core::nodes::AttributeShaderProgramID* p_aInputShaderProgramID = static_cast<core::nodes::AttributeShaderProgramID*>( p_polygonMeshNode->getAttribute(core::nodes::PolygonMeshNode::aID_inputShaderProgramID)); //shaderProgramID -> shaderProgramID ResourceManager::getInstance().createAttributeConnection(p_aShaderProgramID, p_aInputShaderProgramID); //ADD TO THE RESOURCE MANAGER core::nodes::PolygonMeshNode* p_returnPointer = p_polygonMeshNode.get(); ResourceManager::getInstance().addTransformNode(std::move(p_transformNode)); ResourceManager::getInstance().addPolygonMeshNode(std::move(p_polygonMeshNode)); //UPDATE GUI GUIManager::getInstance().updateNodeWidgets(); return p_returnPointer; } } //NAMESPACE: CMDS } //NAMESPACE: UI
3815740633fe6cd08d6e75991c626acfc4be3d34
13798217d6576d7c544d95fd0f66dd9407c09198
/include/JE/GRAPHIC/jeTilemap.h
cc5d703030af3a14e02a4da4435d83328550c3f1
[]
no_license
Jellonator/jeEngine
95de8b7eebc5c11203813b88ffbb6b3cdf3dc809
1241c624fc0ac70e1a111d841ffb9c4c4485794f
refs/heads/master
2021-01-17T09:19:02.498438
2016-04-11T11:27:37
2016-04-11T11:27:37
14,193,632
1
0
null
null
null
null
UTF-8
C++
false
false
6,072
h
jeTilemap.h
#pragma once #include "jeCanvas.h" #include "../jeMain.h" #include "../jeUtil.h" #include <memory> #include <map> #include <vector> namespace JE{namespace GRAPHICS{ class Tileset; class Tilemap; class Tileset{ public: Tileset(std::string file, int twidth, int theight, int offsetX = 0, int offsetY = 0, int spaceX = 0, int spaceY = 0); //Tileset(Tilemap* parent, std::string file, int twidth, int theight, int offsetX = 0, int offsetY = 0, int spaceX = 0, int spaceY = 0); void load(std::string file, int twidth, int theight, int offsetX = 0, int offsetY = 0, int spaceX = 0, int spaceY = 0); virtual ~Tileset(); int tileWidth;/**< \brief Width of each tile. */ int tileHeight;/**< \brief Height of each tile. */ int tileOffsetX;/**< \brief X offset of the tileset. */ int tileOffsetY;/**< \brief Y offset of the tileset. */ int tileSpaceX;/**< \brief X spacing between tiles. */ int tileSpaceY;/**< \brief Y spacing between tiles. */ void newTile(int x, int y, int ID = -1); void newFreeformTile(int x, int y, int w, int h, int ID = -1); void drawFreeformTile(int tile, int x, int y, float sx = 1, float sy = 1); void drawTileID(int tile, int x, int y, int parentTileWidth = -1, int parentTileHeight = -1); void drawTile(int tilex, int tiley, int x, int y, int parentTileWidth = -1, int parentTileHeight = -1); void drawTileRect(int tilex, int tiley, int x, int y, int w, int h, int parentTileWidth = -1, int parentTileHeight = -1); void drawTileRectID(int tile, int x, int y, int w, int h, int parentTileWidth = -1, int parentTileHeight = -1); Image image;/**< \brief The tileset's image. */ std::vector<SDL_Rect> tiles;/**< \brief A list of tiles in the tileset. */ }; class Tilemap : public Canvas { public: std::vector<std::shared_ptr<Tileset>> tilesets;/**< */ int tileWidth;/**< \brief Width of each tile. */ int tileHeight;/**< \brief Height of each tile. */ int tileOffsetX;/**< \brief X offset of the tileset. */ int tileOffsetY;/**< \brief Y offset of the tileset. */ int tileSpaceX;/**< \brief X spacing between tiles. */ int tileSpaceY;/**< \brief Y spacing between tiles. */ int widthInTiles;/**< \brief Width of the tileset, in tiles. */ int heightInTiles;/**< \brief Height of the tileset, in tiles. */ /** \brief A class used to represent a map of tiles * \param width int, width of the tilemap, in tiles. * \param height int, height of the tilemap, in tiles. * \param 1 int twidth, default width of each tile. * \param 1 int theight, default height of each tile. * \param 0 int offsetX, default X offset of tiles in the tileset. * \param 0 int offsetY, default Y offset of tiles in the tileset. * \param 0 int spaceX, default X spacing between tiles in the tileset. * \param 0 int spaceY, default Y spacing between tiles in the tileset. */ Tilemap(int width, int height, int twidth = 1, int theight = 1, int offsetX = 0, int offsetY = 0, int spaceX = 0, int spaceY = 0); /** \brief Creates a new tileset for the tilemap. * \param file std::string, the file to load. * \param -1 int ID, the ID of the tileset. Defaults to appending to the back. * \param -1 int twidth, width of each tile. * \param -1 int theight, height of each tile. * \param -1 int offsetX, X offset of tiles in the tileset. * \param -1 int offsetY, Y offset of tiles in the tileset. * \param -1 int spaceX, X spacing between tiles in the tileset. * \param -1 int spaceY, Y spacing between tiles in the tileset. */ std::shared_ptr<Tileset> newTileset(std::string file, int tWidth = -1, int tHeight = -1, int offsetX = -1, int offsetY = -1, int spaceX = -1, int spaceY = -1, int ID = -1); std::shared_ptr<Tileset> addTileset(std::shared_ptr<Tileset> tileset, int ID = -1); /** \brief Creates a new tile. * \param tileset int, the tileset to use. * \param x int, the X position of the tile, in tiles. * \param y int, the Y position of the tile, in tiles. * \param 1 int w, the width of the tile, in tiles. * \param 1 int h, the height of the tile, in tiles. * \param -1 int ID, the ID of the tile. Defaults to appending to the back. */ void newTile(int tileset, int x, int y, int ID = -1); /** \brief Creates a new tile, without using a grid. * \param tileset int, the tileset to use. * \param x int, the X position of the tile. * \param y int, the Y posiiton of the tile. * \param w int, the width of the tile. * \param h int, the height of the tile. * \param -1 int ID, the ID of the tile. Defaults to appending to the back. */ void newFreeformTile(int tileset, int x, int y, int w, int h, int ID = -1); /** \brief Draws a tile to the tilemap. * \param tileset int, the ID of the tileset to use. * \param tile int, the ID of the tile to draw. * \param x float, the X position to draw to, in tiles. * \param y float, the Y position to draw to, in tiles. */ void drawTile(int tileset, int tile, int x, int y); void drawTile(int tileset, int tilex, int tiley, int x, int y); void drawTileRect(int tileset, int tilex, int tiley, int x, int y, int w, int h); void drawTileRect(int tileset, int tile, int x, int y, int w, int h); //void drawTile(int tileset, int tx, int ty, float x, float y); /** \brief Draw a freeform tile to the tilemap. * \param tileset int, the ID of the tileset to use. * \param tile int, the ID of the tile to draw. * \param x float * \param y float * \param NULL Camera* camera, the camera to use. * \param NULL Entity* parent, the parent entity to use. * \param 1 float sx, the X scaling factor. * \param 1 float sy, the Y scaling factor. */ void drawFreeformTile(int tileset, int tile, float x, float y, float sx = 1, float sy = 1); virtual ~Tilemap(); protected: private: }; };};
4a5e1ea8f3855f78ff9005b60e05ea601c1409f7
a14d4121c5a690d2b86f11e9114fcdf907a187da
/BaseFramework/Src/System/Shader/EffectShader/KdEffectShader.cpp
35907712772a61c20a8e026a169ebb3ebe1b5800
[]
no_license
TN11111/findWork
ae470c612240061fe389b4c9bb860b3dd103c367
2da49fc42d816e62acb80648c337f8d9bda9fd53
refs/heads/master
2023-08-14T05:43:38.397894
2021-10-17T06:10:40
2021-10-17T06:10:40
413,187,655
0
0
null
null
null
null
UTF-8
C++
false
false
7,499
cpp
KdEffectShader.cpp
#include "System/KdSystem.h" #include "KdEffectShader.h" void KdEffectShader::DrawLine(const Math::Vector3 & p1, const Math::Vector3 & p2, const Math::Color & color) { // 定数バッファ書き込み m_cb0.Write(); // 頂点レイアウトをセット D3D.WorkDevContext()->IASetInputLayout(m_inputLayout); // Vertex vertex[2] = { {p1, {0,0}, color}, {p2, {1,0}, color}, }; // 頂点を描画 D3D.DrawVertices(D3D_PRIMITIVE_TOPOLOGY_LINESTRIP, 2, &vertex[0], sizeof(Vertex)); } void KdEffectShader::DrawVertices(const std::vector<Vertex>& vertices, D3D_PRIMITIVE_TOPOLOGY topology) { // 定数バッファ書き込み m_cb0.Write(); // 頂点レイアウトをセット D3D.WorkDevContext()->IASetInputLayout(m_inputLayout); // 頂点を描画 D3D.DrawVertices(topology, vertices.size(), &vertices[0], sizeof(Vertex)); } void KdEffectShader::DrawMesh(const KdMesh* mesh, const std::vector<KdMaterial>& materials) { if (mesh == nullptr)return; // 定数バッファ書き込み m_cb0.Write(); // メッシュ情報をセット mesh->SetToDevice(); // 頂点レイアウトをセット D3D.WorkDevContext()->IASetInputLayout(m_inputLayout_Model); // 全サブセット for (UINT subi = 0; subi < mesh->GetSubsets().size(); subi++) { // 面が1枚も無い場合はスキップ if (mesh->GetSubsets()[subi].FaceCount == 0)continue; // マテリアルセット const KdMaterial& material = materials[ mesh->GetSubsets()[subi].MaterialNo ]; //----------------------- // マテリアル情報を定数バッファへ書き込む //----------------------- m_cb1_Material.Work().BaseColor = material.BaseColor; m_cb1_Material.Write(); //----------------------- // テクスチャセット //----------------------- ID3D11ShaderResourceView* srvs[1] = {}; // BaseColor srvs[0] = material.BaseColorTex->WorkSRView(); // セット D3D.WorkDevContext()->PSSetShaderResources(0, _countof(srvs), srvs); //----------------------- // サブセット描画 //----------------------- mesh->DrawSubset(subi); } } void KdEffectShader::DrawModel(const KdModelWork& rModel, const Math::Matrix& mWorld) { // 有効じゃないときはスキップ if (!rModel.IsEnable()) { return; } const std::shared_ptr<KdModelData>& data = rModel.GetData(); // モデルがないときはスキップ if (data == nullptr) { return; } // 全メッシュノードを描画 for (auto& nodeIdx : data->GetMeshNodeIndices()) { auto& rWorkNode = rModel.GetNodes()[nodeIdx]; const std::shared_ptr<KdMesh>& spMesh = rModel.GetMesh(nodeIdx); // 行列セット SetWorldMatrix(rWorkNode.m_worldTransform * mWorld); // 描画 DrawMesh(spMesh.get(), data->GetMaterials()); } } void KdEffectShader::DrawSquarePolygon(const KdSquarePolygon& rSquarePolygon, const Math::Matrix& mWorld, int textureIndex) { //頂点レイアウトをセット D3D.WorkDevContext()->IASetInputLayout(m_inputLayout); m_cb1_Material.Work().BaseColor = kWhiteColor; //行列セット SetWorldMatrix(mWorld); WriteToCB(); rSquarePolygon.Draw(textureIndex); } void KdEffectShader::DrawTrailPolygon(const KdTrailPolygon rKrailPolygon, int TextureIndex) { D3D.WorkDevContext()->IASetInputLayout(m_inputLayout); m_cb1_Material.Work().BaseColor = kWhiteColor; SetWorldMatrix(Math::Matrix::Identity); WriteToCB(); rKrailPolygon.Draw(TextureIndex); } bool KdEffectShader::Init() { //------------------------------------- // 頂点シェーダ //------------------------------------- { // コンパイル済みのシェーダーヘッダーファイルをインクルード #include "KdEffectShader_VS.inc" // 頂点シェーダー作成 if (FAILED(D3D.WorkDev()->CreateVertexShader(compiledBuffer, sizeof(compiledBuffer), nullptr, &m_VS))) { assert(0 && "頂点シェーダー作成失敗"); Release(); return false; } { // 1頂点の詳細な情報 std::vector<D3D11_INPUT_ELEMENT_DESC> layout = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; // 頂点入力レイアウト作成 if (FAILED(D3D.WorkDev()->CreateInputLayout( &layout[0], // 入力エレメント先頭アドレス layout.size(), // 入力エレメント数 &compiledBuffer[0], // 頂点バッファのバイナリデータ sizeof(compiledBuffer), // 上記のバッファサイズ &m_inputLayout)) // ) { assert(0 && "CreateInputLayout失敗"); Release(); return false; } } // DrawModel用 { // 1頂点の詳細な情報 std::vector<D3D11_INPUT_ELEMENT_DESC> layout = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, 32, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; // 頂点入力レイアウト作成 if (FAILED(D3D.WorkDev()->CreateInputLayout( &layout[0], // 入力エレメント先頭アドレス layout.size(), // 入力エレメント数 &compiledBuffer[0], // 頂点バッファのバイナリデータ sizeof(compiledBuffer), // 上記のバッファサイズ &m_inputLayout_Model)) // ) { assert(0 && "CreateInputLayout失敗"); Release(); return false; } } } //------------------------------------- // ピクセルシェーダ //------------------------------------- { // コンパイル済みのシェーダーヘッダーファイルをインクルード #include "KdEffectShader_PS.inc" if (FAILED(D3D.WorkDev()->CreatePixelShader(compiledBuffer, sizeof(compiledBuffer), nullptr, &m_PS))) { assert(0 && "ピクセルシェーダー作成失敗"); Release(); return false; } } //------------------------------------- // 定数バッファ作成 //------------------------------------- m_cb0.Create(); m_cb1_Material.Create(); return true; } void KdEffectShader::Release() { KdSafeRelease(m_VS); KdSafeRelease(m_PS); KdSafeRelease(m_inputLayout); KdSafeRelease(m_inputLayout_Model); m_cb0.Release(); m_cb1_Material.Release(); } void KdEffectShader::SetToDevice() { // 頂点シェーダをセット D3D.WorkDevContext()->VSSetShader(m_VS, 0, 0); // 頂点レイアウトをセット D3D.WorkDevContext()->IASetInputLayout(m_inputLayout); // ピクセルシェーダをセット D3D.WorkDevContext()->PSSetShader(m_PS, 0, 0); // 定数バッファをセット D3D.WorkDevContext()->VSSetConstantBuffers(0, 1, m_cb0.GetAddress()); D3D.WorkDevContext()->PSSetConstantBuffers(0, 1, m_cb0.GetAddress()); D3D.WorkDevContext()->VSSetConstantBuffers(1, 1, m_cb1_Material.GetAddress()); D3D.WorkDevContext()->PSSetConstantBuffers(1, 1, m_cb1_Material.GetAddress()); } // テクスチャセット void KdEffectShader::SetTexture(ID3D11ShaderResourceView * srv) { if (srv) { D3D.WorkDevContext()->PSSetShaderResources(0, 1, &srv); } else { // テクスチャが無い場合は、白テクスチャをセットする D3D.WorkDevContext()->PSSetShaderResources(0, 1, D3D.GetWhiteTex()->WorkSRViewAddress()); } }
4ce21c3a38736022d49358961496b2cc966dcba1
742841d8bdb699b88a72ff264cb0d08b5152e3a0
/src/Abstraction.hpp
6943ecd6ae8fd1932b991ccf5ef304bc03b953c0
[]
no_license
daviidsiilva/mpi-system-dynamics
99a72e1a2337f018fcfdcf4d54622f544cd21758
470a46226d4194e4135923bc2cc4850e4495cad6
refs/heads/master
2020-06-24T16:22:02.177581
2019-07-26T12:41:56
2019-07-26T12:41:56
199,014,330
0
0
null
null
null
null
UTF-8
C++
false
false
1,628
hpp
Abstraction.hpp
#ifndef ABSTRACTION_HPP #define ABSTRACTION_HPP #include <stdexcept> namespace Abstraction{ typedef enum{ type_unknown = 0, type_char, type_unsigned_char, type_short, type_unsigned_short, type_int, type_unsigned_int, type_long, type_unsigned_long, type_float, type_double } DataType; } template <class T> Abstraction::DataType getAbstractionDataType(){ throw std::runtime_error("Intrinsic type not supported by the abstraction."); } template <> inline Abstraction::DataType getAbstractionDataType<char>(){ return Abstraction::type_char; } template <> inline Abstraction::DataType getAbstractionDataType<unsigned char>(){ return Abstraction::type_unsigned_char; } template <> inline Abstraction::DataType getAbstractionDataType<short>(){ return Abstraction::type_short; } template <> inline Abstraction::DataType getAbstractionDataType<unsigned short>(){ return Abstraction::type_unsigned_short; } template <> inline Abstraction::DataType getAbstractionDataType<int>(){ return Abstraction::type_int; } template <> inline Abstraction::DataType getAbstractionDataType<unsigned int>(){ return Abstraction::type_unsigned_int; } template <> inline Abstraction::DataType getAbstractionDataType<long>(){ return Abstraction::type_long; } template <> inline Abstraction::DataType getAbstractionDataType<unsigned long>(){ return Abstraction::type_unsigned_long; } template <> inline Abstraction::DataType getAbstractionDataType<float>(){ return Abstraction::type_float; } template <> inline Abstraction::DataType getAbstractionDataType<double>(){ return Abstraction::type_double; } #endif
4632d0e1230a830cc2be4cfa1f2abdae6bdd6baf
2bf8d40eacf28a4c64c818e3aa4cc75b95028eaf
/src/set_graph.cpp
244443834d3a891506b54bc67044bccfceb06d4e
[]
no_license
mark-by/graph
f7da2298829013ad78c6f92df5e9d4b3610a1455
a7245b6f7eb0c667c3b06289a43caca89de115bc
refs/heads/master
2022-09-13T21:29:09.830826
2020-05-20T18:34:00
2020-05-20T18:34:00
265,077,107
0
0
null
null
null
null
UTF-8
C++
false
false
758
cpp
set_graph.cpp
#include <set_graph.h> void SetGraph::addEdge(int from, int to) { _vertices[from].insert(to); } int SetGraph::verticesCount() const { return _vertices.size(); } std::vector<int> SetGraph::getNextVertices(int vertex) const { std::vector<int> result; for (auto &v : _vertices[vertex]) { result.push_back(v); } return result; } std::vector<int> SetGraph::getPrevVertices(int vertex) const { std::vector<int> result; for (int i = 0; i < verticesCount(); i++) { for (auto & v : _vertices[i]) { if (v == vertex) { result.push_back(i); } } } return result; } SetGraph::SetGraph(const IGraph &other) : _vertices(other.verticesCount()) { copy(other); }
02daede0072e677ca5d9eb640aa731eecade6715
97478e6083db1b7ec79680cfcfd78ed6f5895c7d
/chrome/browser/vr/model/model.h
4ac415eceeaa93d4a3800a91b78dfbf8cba58fe2
[ "BSD-3-Clause" ]
permissive
zeph1912/milkomeda_chromium
94e81510e1490d504b631a29af2f1fef76110733
7b29a87147c40376bcdd1742f687534bcd0e4c78
refs/heads/master
2023-03-15T11:05:27.924423
2018-12-19T07:58:08
2018-12-19T07:58:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,608
h
model.h
// Copyright 2017 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_VR_MODEL_MODEL_H_ #define CHROME_BROWSER_VR_MODEL_MODEL_H_ #include "chrome/browser/vr/model/color_scheme.h" #include "chrome/browser/vr/model/controller_model.h" #include "chrome/browser/vr/model/modal_prompt_type.h" #include "chrome/browser/vr/model/omnibox_suggestions.h" #include "chrome/browser/vr/model/permissions_model.h" #include "chrome/browser/vr/model/reticle_model.h" #include "chrome/browser/vr/model/speech_recognition_model.h" #include "chrome/browser/vr/model/toolbar_state.h" #include "chrome/browser/vr/model/web_vr_timeout_state.h" #include "chrome/browser/vr/ui_element_renderer.h" #include "ui/gfx/transform.h" namespace vr { struct Model { Model(); ~Model(); // VR browsing state. bool browsing_disabled = false; bool loading = false; float load_progress = 0.0f; bool fullscreen = false; bool incognito = false; bool in_cct = false; bool can_navigate_back = false; ToolbarState toolbar_state; std::vector<OmniboxSuggestion> omnibox_suggestions; bool omnibox_input_active = false; SpeechRecognitionModel speech; const ColorScheme& color_scheme() const; gfx::Transform projection_matrix; unsigned int content_texture_id = 0; UiElementRenderer::TextureLocation content_location = UiElementRenderer::kTextureLocationLocal; // WebVR state. bool web_vr_mode = false; bool web_vr_show_toast = false; bool web_vr_show_splash_screen = false; // Indicates that we're waiting for the first WebVR frame to show up before we // hide the splash screen. This is used in the case of WebVR auto- // presentation. bool web_vr_started_for_autopresentation = false; bool should_render_web_vr() const { return web_vr_mode && !web_vr_show_splash_screen; } bool browsing_mode() const { return !web_vr_mode && !web_vr_show_splash_screen; } bool web_vr_has_produced_frames() const { return web_vr_mode && web_vr_timeout_state == kWebVrNoTimeoutPending; } WebVrTimeoutState web_vr_timeout_state = kWebVrNoTimeoutPending; // Controller state. ControllerModel controller; ReticleModel reticle; // State affecting both VR browsing and WebVR. ModalPromptType active_modal_prompt_type = kModalPromptTypeNone; PermissionsModel permissions; bool experimental_features_enabled = false; bool skips_redraw_when_not_dirty = false; bool exiting_vr = false; }; } // namespace vr #endif // CHROME_BROWSER_VR_MODEL_MODEL_H_
dcb442d84061d11ec2b2245d4d090f31e5e7c6f7
98278b136825a0cf170bcb2d419ff72c5f28e435
/svf/SVF/tests/cpp_tests/member-variable.cpp
f1ec57dd023850e2d0aa7ff8db2d8e4d2db74906
[ "Apache-2.0", "GPL-3.0-or-later", "NCSA" ]
permissive
cponcelets/savior-source
b3a687430270593f75b82e9f00249bdb4e4ffe13
ac553cafba66663399eebccec58d16277bd1718e
refs/heads/master
2021-05-23T18:35:33.358488
2020-09-30T08:18:29
2020-09-30T08:18:29
299,001,996
1
0
Apache-2.0
2020-09-27T09:57:26
2020-09-27T09:57:25
null
UTF-8
C++
false
false
581
cpp
member-variable.cpp
#include "aliascheck.h" int global_obj_a; int *global_ptr_a = &global_obj_a; int global_obj_b; int *global_ptr_b = &global_obj_b; class A { public: virtual void f(int *i) { MUSTALIAS(global_ptr_a, i); NOALIAS(global_ptr_b, i); } }; class B { public: B(A *a): _a(a) {} virtual void f(int *i) { NOALIAS(global_ptr_a, i); MUSTALIAS(global_ptr_b, i); } A *_a; }; int main(int argc, char **argv) { int *i = &global_obj_a; int *j = &global_obj_b; A *a = new A; B *b = new B(a); b->f(j); b->_a->f(i); return 0; }
055d47d9e04b71f0f3c7bdffdabf35686f4b13c5
7f16497d6eb7ea596ec26bee5215ed92a28c11b8
/alphastar/alphastar-cs501ab-usaco-platinum-summer-2018-s2/14-advanced-dynamic-programming-1/05 - Buying Feed.cpp
c2a15e7baa6fcfd37da7bba8b9fbfed1f002dc28
[]
no_license
thecodingwizard/competitive-programming
6c088dc15116409583429486951a94a87f6c316b
76f8659dbb935604a31fad26967fdfa413141244
refs/heads/master
2022-05-27T02:25:34.593546
2022-05-19T06:00:00
2022-05-19T06:00:00
159,700,280
83
25
null
2021-10-01T15:26:22
2018-11-29T17:03:04
C++
UTF-8
C++
false
false
4,409
cpp
05 - Buying Feed.cpp
/* Buying Feed =========== Farmer John needs to travel to town to pick up K (1 <= K <= 10,000) pounds of feed. Driving a mile with K pounds of feed costs FJ K*K cents; driving D miles with K pounds of feed in his truck costs FJ D*K*K cents. FJ can purchase feed from any of N (1 <= N <= 500) stores (conveniently numbered 1..N) that sell feed. Each store is located on a segment of the X axis whose length is E (1 <= E <= 500) miles. Store i is at location X_i (0 < X_i < E) on the number line and can sell FJ as much as F_i (1 <= F_i <= 10,000) pounds of feed at a cost of C_i (1 <= C_i <= 10,000,000) cents per pound. Surprisingly, a given point on the X axis might have more than one store. FJ starts driving at location 0 on this number line and can drive only in the positive direction, ultimately arriving at location E with at least K pounds of feed. He can stop at any of the feed stores along the way and buy any amount of feed up to the the store's limit. What is the minimum amount FJ must pay to buy and transport the K pounds of feed? FJ knows he can purchase enough feed. Consider this example where FJ needs two pounds of feed which he must purchase from some of the three stores at locations 1, 3, and 4 on a number line whose range is 0..5: 0 1 2 3 4 5 X +---|---+---|---|---+ 1 1 1 Available pounds of feed 1 2 2 Cents per pound It is most economical for FJ to buy one pound of feed from both the second and third stores. He must pay two cents to buy each pound of feed for a total cost of 4. FJ's driving from location 0 to location 3 costs nothing, since he is carrying no feed. When FJ travels from 3 to 4 he moves 1 mile with 1 pound of feed, so he must pay 1*1*1 = 1 cents. When FJ travels from 4 to 5 he moves one mile with 2 pounds of feed, so he must pay 1*2*2 = 4 cents. His feed cost is 2 + 2 cents; his travel cost is 1 + 4 cents. The total cost is 2 + 2 + 1 + 4 = 9 cents. PROBLEM NAME: feed INPUT FORMAT: * Line 1: Three space-separated integers: K, E, and N * Lines 2..N+1: Line i+1 contains three space-separated integers: X_i, F_i, and C_i SAMPLE INPUT: 2 5 3 3 1 2 4 1 2 1 1 1 OUTPUT FORMAT: * Line 1: A single integer that is the minimum cost for FJ to buy and transport the feed SAMPLE OUTPUT: 9 */ #include <iostream> #include <string> #include <utility> #include <sstream> #include <algorithm> #include <stack> #include <vector> #include <queue> #include <map> #include <set> #include <bitset> #include <cmath> #include <cstring> #include <iomanip> #include <math.h> #include <assert.h> using namespace std; #define INF 1000000000 #define LL_INF 0xfffffffffffffffLL #define LSOne(S) (S & (-S)) #define EPS 1e-9 #define A first #define B second #define mp make_pair #define PI acos(-1.0) typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; struct Store { long long x, feedAvail, cost; bool operator<(Store other) const { return x < other.x; } }; struct MinQueue { // value, index deque<pair<long long, int >> dq; int L = 0, R = -1; void insert(long long x) { while (!dq.empty() && dq.back().A >= x) { dq.pop_back(); } dq.emplace_back(x, ++R); } int size() { return R - L + 1; } void del() { if (dq.front().B == L++) dq.pop_front(); } long long query() { return dq.front().A; } }; int main() { long long k, e, n; cin >> k >> e >> n; Store stores[n]; for (int i = 0; i < n; i++) { cin >> stores[i].x >> stores[i].feedAvail >> stores[i].cost; } sort(stores, stores+n); long long dp[2][10001]; for (int i = 0; i <= 10000; i++) dp[0][i] = LL_INF; dp[0][0] = 0; int curDP = 1; for (int i = 0; i < n; i++) { Store store = stores[i]; MinQueue mq; long long dist = (i == 0 ? store.x : store.x - stores[i - 1].x); for (int j = 0; j <= k; j++) dp[curDP][j] = LL_INF; for (int j = 0; j <= k; j++) { if (dp[!curDP][j] != LL_INF) mq.insert(dp[!curDP][j] + dist*j*j - j*store.cost); if (j > store.feedAvail) mq.del(); if (mq.size() == 0) break; dp[curDP][j] = mq.query() + j*store.cost; } curDP = !curDP; } cout << dp[!curDP][k] + k*k*(e-stores[n-1].x) << endl; return 0; }
4b14bd1bf6ca4e7d31072a15bb5d044875b475ef
5a6dba6e78965d9bb4ad78a605e771a19d8c7186
/src/cpp_pop_modeler/MatPowerBus.hxx
1b1ad024ab460bacf1a4501c8c1c5040739e4ed1
[]
no_license
klorel/ddd
0b162348d6d089c65b0c329bcc94c7933f6f3aa6
1a1d501a36e8a96303ab2fe188b01169fe7afd61
refs/heads/master
2020-05-21T21:01:27.935993
2016-10-06T10:54:01
2016-10-06T10:54:01
61,387,923
0
0
null
null
null
null
UTF-8
C++
false
false
315
hxx
MatPowerBus.hxx
__MAT_POWER_DATA__(bus_i) __MAT_POWER_DATA__(type) __MAT_POWER_DATA__(Pd) __MAT_POWER_DATA__(Qd) __MAT_POWER_DATA__(Gs) __MAT_POWER_DATA__(Bs) __MAT_POWER_DATA__(area) __MAT_POWER_DATA__(Vm) __MAT_POWER_DATA__(Va) __MAT_POWER_DATA__(baseKV) __MAT_POWER_DATA__(zone) __MAT_POWER_DATA__(Vmax) __MAT_POWER_DATA__(Vmin)
e6919eeb1d3153b5bfacbca880afa58580dbefe9
a5a04c9377fa7d405788045ea4d3ae49eaa74ec5
/tests/check_model.cpp
5671fe0195117ec9fe9546241a00cc8e8028cce9
[]
no_license
bonnefoa/bull
895256852b0f06d5c749252f4e2b59724a1007d5
8ffb35819bd3f6dc42dff75c221e8ca84f34cfc7
refs/heads/master
2020-03-30T17:22:49.790294
2013-07-12T08:02:27
2013-07-12T08:02:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
774
cpp
check_model.cpp
#include <stdlib.h> #include <check.h> #include <bl_model.h> #include <bl_loader.h> START_TEST (test_model) { BlModel *blModel = loadModelFile("tests/cubeTextured.dae")[0]; printf("Uvs size is %zu\n", blModel->uvs.size()); fail_unless(blModel->uvs.size() == 1); } END_TEST Suite *model_suite (void) { Suite *s = suite_create ("Model suite"); TCase *tc_core = tcase_create ("Model case"); tcase_add_test (tc_core, test_model); suite_add_tcase (s, tc_core); return s; } int main (void) { int number_failed; Suite *s = model_suite (); SRunner *sr = srunner_create (s); srunner_run_all (sr, CK_NORMAL); number_failed = srunner_ntests_failed (sr); srunner_free (sr); return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
e2fd80fdb39a08468c4c24285cf46e5054b0a7a5
f335d085aa484fbe617430e3fbd50b28747df045
/SrcLib/core/arData/test/tu/include/GenericTLTest.hpp
347a36e28795a5ade142e5f87a246ddfd403b078
[]
no_license
fw4spl-org/fw4spl-ar
60f5e7fc57e42c15bd8f6dbd57dbcb6c62ed6b46
d2a35bf368373f232d09c26f168eaa363c6ae197
refs/heads/master
2021-01-24T06:35:33.113302
2018-09-05T12:44:58
2018-09-05T12:44:58
31,675,795
5
0
null
null
null
null
UTF-8
C++
false
false
977
hpp
GenericTLTest.hpp
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2009-2016. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ #ifndef __ARDATA_UT_GENERICTLTEST_HPP__ #define __ARDATA_UT_GENERICTLTEST_HPP__ #include <cppunit/extensions/HelperMacros.h> namespace arData { namespace ut { class GenericTLTest : public CPPUNIT_NS::TestFixture { public: CPPUNIT_TEST_SUITE( GenericTLTest ); CPPUNIT_TEST( pushPopTest ); CPPUNIT_TEST( pushClassTest ); CPPUNIT_TEST( copyTest ); CPPUNIT_TEST( iteratorTest ); CPPUNIT_TEST( objectValid ); CPPUNIT_TEST_SUITE_END(); public: // interface void setUp(); void tearDown(); void pushPopTest(); void pushClassTest(); void copyTest(); void iteratorTest(); void objectValid(); }; } //namespace ut } //namespace arData #endif // __ARDATA_UT_GENERICTLTEST_HPP__
e268f4f9116f32a6ea53d9f6870a803e5ddeefb2
232157c2066d929c48f460d50f8fcaed67df0425
/Classes/MenuLayer.cpp
4e09a4aaa94c7919cdc40101cf8364719f15a89e
[]
no_license
UenoTAKAFUMI/BaseGame
2437d80849f4a8dd974a39b08e9ecf92d7d5ea27
994d0e2656f759827ba9e2ba07e4f5267a41593c
refs/heads/master
2016-09-01T16:53:20.279415
2014-07-19T04:12:14
2014-07-19T04:12:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,046
cpp
MenuLayer.cpp
// // MenuLayer.cpp // BaseGame02 // // Created by P on 2014/07/17. // // #include "MenuLayer.h" #include "TitleScene.h" using namespace cocos2d; // staticメンバ変数の初期化 Layer* MenuLayer::mFromLayer = 0; // メニュー画面レイヤ作成関数 MenuLayer* MenuLayer::create(cocos2d::Layer* const pFromLayer) { // 呼び出し元のレイヤ mFromLayer = pFromLayer; // メニュー画面呼び出し元を一時停止 // まず小要素すべてを一時停止 Vector<Node*> vec = mFromLayer->getChildren(); for (Vector<Node*>::iterator it = vec.begin(); it != vec.end(); ++it) { Node *node = *it; node->pause(); } // メニュー画面呼び出し元を一時停止 mFromLayer->pause(); // CREATE_FUNC()の中で実行される内容を記載 // コンストラクタ呼び出しやメモリ自動開放処理など MenuLayer *pRet = new MenuLayer(); if (pRet && pRet->init()) { pRet->autorelease(); return pRet; } else { delete pRet; pRet = NULL; return NULL; } } // メニュー画面初期処理 bool MenuLayer::init(){ if (!Layer::init()) { return false; } // 画像描画用に画面のサイズと座標開始位置を取得(レイアウトを決める他にいい方法はないか?) Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); // レイヤーの背景色を設定 // DeprecationWarnning: // ccc4()は非推奨のため、Color4B()を使用(中身はinline関数で、ccc4を実行していた) LayerColor *color = LayerColor::create(Color4B(0.0f,0.0f,0.0f,100.0f)); this->addChild(color); // タイトルへ戻るボタンの作成 MenuItemImage* startButton = MenuItemImage::create( "titlebutton.png", "titlebutton.png", // DeprecationWarnning: // Objectクラスが非推奨のため、Refクラスを使用 [this](Ref *pSender){ // タイトル画面へ遷移 Director::getInstance()->replaceScene(TitleScene::createScene()); }); startButton->setPosition(Vec2(origin.x + ( visibleSize.width / 2 ) , origin.y + ( visibleSize.height / 5) * 3)); // つづけるボタンの作成 MenuItemImage* resumeButton = MenuItemImage::create( "buttonContinue.png", "buttonContinue.png", // DeprecationWarnning: // Objectクラスが非推奨のため、Refクラスを使用 [this](Ref *pSender){ // メニュー画面の削除 this->removeFromParentAndCleanup(true); // プレイ中レイヤーの小要素取得 cocos2d::Vector<Node*> vec = mFromLayer->getChildren(); for (cocos2d::Vector<Node*>::iterator it = vec.begin(); it != vec.end(); ++it) { Node *node = *it; node->resume(); } // プレイ中レイヤーの復帰処理 mFromLayer->resume(); }); // つづけるボタンのポジション resumeButton->setPosition(Vec2(origin.x + ( visibleSize.width / 2 ) , origin.y + ( visibleSize.height / 5) * 4)); // 作成したボタンの設置 Menu* menu = Menu::create(startButton, resumeButton, NULL); menu->setPosition(0,0); this->addChild(menu); // ゲームオブジェクトの追加とそのアニメーション処理 schedule(schedule_selector(MenuLayer::addGameObject), 2.0); return true; } // ゲームオブジェクトの追加(ポーズ状態確認用) void MenuLayer::addGameObject(float delta){ // 画像描画用に画面のサイズと座標開始位置を取得 // こいつはローカル変数として持つべき値じゃないよな。どうすべきか。 Size visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); // ゲームオブジェクト画像の追加(スプライト生成) auto gameObjectSprite = Sprite::create("tomato.png"); // ゲームオブジェクトのサイズ拡縮(比率を指定して縮小) gameObjectSprite->setScale(0.1f); // 画面中央ちょい左へ配置 gameObjectSprite->setPosition(Vec2(visibleSize.width/3 + origin.x, visibleSize.height/3 + origin.y)); // レイヤーへスプライト追加 this->addChild(gameObjectSprite, 0); // ゲームオブジェクトの移動アニメーション float duration = 2.0f; MoveTo* actionMove = MoveTo::create(duration, Vec2(origin.x + visibleSize.width, origin.y + visibleSize.height)); gameObjectSprite->runAction(actionMove); }
fdf5487af49927053e068eed5c0f34d5d60da484
14582f8c74c28d346399f877b9957d0332ba1c3c
/branches/pstade_1_03_5_head/pstade_subversive/pstade/oven/counting.hpp
eafc451506206aeb9a9986da0e4e9c9da2420bf2
[]
no_license
svn2github/p-stade
c7b421be9eeb8327ddd04d3cb36822ba1331a43e
909b46567aa203d960fe76055adafc3fdc48e8a5
refs/heads/master
2016-09-05T22:14:09.460711
2014-08-22T08:16:11
2014-08-22T08:16:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,057
hpp
counting.hpp
#ifndef PSTADE_OVEN_COUNTING_HPP #define PSTADE_OVEN_COUNTING_HPP // PStade.Oven // // Copyright Shunsuke Sogame 2005-2007. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // Note: // // '__w64 int'(msvc) and 'ptrdiff_t'(gcc) behavior seems undefined. // Through metafunctions, they are occasionally turned into 'int'. #include <limits> // numeric_limits #include <boost/assert.hpp> #include <boost/iterator/counting_iterator.hpp> #include <boost/iterator/iterator_categories.hpp> #include <boost/type.hpp> #include <boost/utility/result_of.hpp> #include <pstade/callable.hpp> #include <pstade/constant.hpp> #include <pstade/copy_construct.hpp> #include <pstade/function.hpp> #include <pstade/pass_by.hpp> #include <pstade/unused.hpp> #include "./iter_range.hpp" namespace pstade { namespace oven { namespace counting_detail { namespace here = counting_detail; template< class Incrementable1, class Incrementable2 > inline bool is_valid(Incrementable1 i, Incrementable2 j, boost::single_pass_traversal_tag) { unused(i, j); return true; } template< class Incrementable1, class Incrementable2 > inline bool is_valid(Incrementable1 i, Incrementable2 j, boost::random_access_traversal_tag) { return pstade::copy_construct<Incrementable2>(i) <= j; } template< class Traversal, class Difference, class Incrementable1, class Incrementable2 > struct baby { // Prefer 'Incrementable2'; [0:int, size():uint) often happens. typedef typename pass_by_value<Incrementable2>::type inc_t; typedef boost::counting_iterator<inc_t, Traversal, Difference> iter_t; typedef iter_range<iter_t> const result_type; result_type operator()(Incrementable1& i, Incrementable2& j) const { BOOST_ASSERT(here::is_valid(i, j, typename boost::iterator_traversal<iter_t>::type())); return result_type( iter_t(pstade::copy_construct<inc_t>(i)), iter_t(j) ); } }; struct max_count_tag { }; struct min_count_tag { }; } // namespace counting_detail template< class Traversal = boost::use_default, class Difference = boost::use_default > struct op_counting : callable< op_counting<Traversal, Difference> > { template< class Incrementable1, class Incrementable2 > struct apply_aux { typedef typename counting_detail::baby<Traversal, Difference, Incrementable1, Incrementable2>::result_type type; }; template< class Result, class Incrementable1, class Incrementable2 > Result call_aux(Incrementable1 i, Incrementable2 j, boost::type<Result>) const { return counting_detail::baby<Traversal, Difference, Incrementable1, Incrementable2>()(i, j); } template< class Incrementable > struct apply_aux<Incrementable, counting_detail::max_count_tag> { typedef typename counting_detail::baby<Traversal, Difference, Incrementable, Incrementable const>::result_type type; }; template< class Result, class Incrementable > Result call_aux(Incrementable i, counting_detail::max_count_tag, boost::type<Result>) const { return counting_detail::baby<Traversal, Difference, Incrementable, Incrementable const>()(i, (std::numeric_limits<Incrementable>::max)()); } template< class Incrementable > struct apply_aux<counting_detail::min_count_tag, Incrementable> { typedef typename counting_detail::baby<Traversal, Difference, Incrementable const, Incrementable>::result_type type; }; template< class Result, class Incrementable > Result call_aux(counting_detail::min_count_tag, Incrementable j, boost::type<Result>) const { return counting_detail::baby<Traversal, Difference, Incrementable const, Incrementable>()((std::numeric_limits<Incrementable>::min)(), j); } template< class Myself, class Incrementable1, class Incrementable2 > struct apply : apply_aux< typename pass_by_value<Incrementable1>::type, typename pass_by_value<Incrementable2>::type > { }; template< class Result, class Incrementable1, class Incrementable2 > Result call(Incrementable1& i, Incrementable2& j) const { // Use type2type for GCC; see <pstade/const_overloaded.hpp>. return call_aux(i, j, boost::type<Result>()); } }; PSTADE_CONSTANT(counting, (op_counting<>)) PSTADE_CONSTANT(max_count, (counting_detail::max_count_tag)) PSTADE_CONSTANT(min_count, (counting_detail::min_count_tag)) } } // namespace pstade::oven #endif
71657b963b6bb918323cac3690155da61f311a9b
7baaa939f59eb0dadb07b663a72ac842863a2f8a
/anul1/ASD/liste_dublu_inlantuite.cpp
91f42fa97a5ef6d79c8a5d3facc430fce7dae4c8
[]
no_license
cosmin-d/FMI
4457b734227181501060e9e29a543a02d322ae2f
bc079c03fecf457e4694bc1fa27daba2a4fb80fb
refs/heads/master
2020-06-25T17:45:20.626278
2017-08-09T15:02:53
2017-08-09T15:02:53
96,980,317
1
1
null
null
null
null
UTF-8
C++
false
false
3,287
cpp
liste_dublu_inlantuite.cpp
#include<iostream> #include<conio.h> using namespace std; struct nod{ int nr; nod* ls,*ld; }; nod *s,*d,*c,*e; int n,m,i,val; void creare(nod*& s,nod*& d){ cout<<"info=";cin>>n; s= new nod; s->nr=n; s->ld=0; s->ls=0; d=s; } void adaug_s(nod*& s,nod* d){ nod*c; cout<<"info:";cin>>n; c=new nod; c->nr=n; c->ls=0; c->ld=s; s->ls=c; s=c; } void adaug_d(nod* s,nod*& d){ cout<<"info=";cin>>n; c=new nod; c->nr=n; c->ld=0; d->ld=c; c->ls=d; d=c; } void adaug_i(nod* s,nod*& d){ cout<<"Dupa care inregistrare adaugam?";cin>>val; cout<<"info=";cin>>n; nod* c=s; while (c->nr!=val) c=c->ld; if (c==d){ e=new nod; e->nr=n; e->ld=0; d->ld=e; e->ls=d; d=e; }else{ e=new nod; e->nr=n; e->ld=c->ld; c->ld->ls=e; e->ls=c; c->ld=e; } } void sterg_s(nod*& s,nod*& d){ c=s; s=s->ld; s->ls=0; delete c; } void sterg_d(nod*& s,nod*& d){ c=d; d=d->ls; d->ld=0; delete c; } void sterg_i(nod*& s,nod*& d){ nod* c=s,*f; int st; cout<<"Ce valoare din interiorul listei stergeti?";cin>>st; if (s->nr==st) sterg_s(s,d); else if (d->nr==st) sterg_d(s,d); else { while(c->ld->nr!=st) c=c->ld; f=c->ld; f->ld->ls=c; c->ld=f->ld; delete f; } } void sterg(nod*& s,nod*& d,int n){ if (s==d){ e=s; s=d=0; }else{ if (s->nr==n){ e=s; s=s->ld; e->ld=0; s->ls=0; } else if (d->nr==n){ e=d; d=d->ls; e->ls=0; d->ld=0; }else{ c=s; while(c->ld->nr!=n)c=c->ld; e=c->ld; e->ld->ls=c; c->ld=e->ld; e->ld=0;e->ls=0; if (e=d) d=c; } } delete e; } void listare_s(nod* s,nod *d){ if (!s){ cout<<"Lista este vida!"; }else{ c=s; cout<<"Listez de la stanga la dreapta: "; while(c){ cout<<c->nr<<" "; c=c->ld; } } cout<<endl; } void listare_d(nod*s ,nod* d){ if (!s){ cout<<"Lista este vida!"; }else{ c=d; cout<<"Listez de la dreapta la stanga: "; while(c){ cout<<c->nr<<" "; c=c->ls; } } cout<<endl; } int main(int argc,char *argv[]){ int val0,val1; cout<<"Creez primul nod al listei."<<endl; creare(s,d); do{ cout<<"Cate inregistari adaugam la dreapta?"; cin>>val0; }while (val0<1); for (i=1;i<=val0;i++){adaug_d(s,d);} do{ cout<<"Cate inregistrari adaugam la stanga?"; cin>>val1; }while (val1<1); for (i=1;i<=val1;i++) {adaug_s(s,d);} listare_s(s,d); listare_d(s,d); cout<<endl; cout<<"Inseram un nod in interiorul listei:"<<endl; adaug_i(s,d); listare_s(s,d); listare_d(s,d); cout<<endl; getch(); cout<<"Stergem un nod din stanga listei:"<<endl; sterg_s(s,d); listare_s(s,d); listare_d(s,d); cout<<endl; getch(); cout<<"Stergem un nod din dreapta listei:"<<endl; sterg_d(s,d); listare_s(s,d); listare_d(s,d); cout<<endl; getch(); cout<<"Stergem un nod din interiorul listei:"<<endl; sterg_i(s,d); listare_s(s,d); listare_d(s,d); cout<<endl; getch(); cout<<"Stergem un nod oarecare al listei:"<<endl; cout<<"Ce nod stergem?";cin>>n; sterg(s,d,n); listare_s(s,d); listare_d(s,d); getch(); return 0; }
6a4d8636bfed487fb240810e7e70d7b53a2b48b5
536365a8e772f4729915af1f7970ec858fc2bca6
/Graph/Lec5_Topological_Sorting_Using_DFS_Algorithm.cc
229ee0179cb958f5defe8b950624360c41c99372
[]
no_license
ajaysharma388/Compititive_Programming_CB
1451ba2b7fafeb098e958e3c95f6a1505bb91cf3
601a9a212cbb2ac9b618284c4d868f4c3643250b
refs/heads/master
2021-05-18T11:13:40.290446
2021-04-17T23:13:14
2021-04-17T23:13:14
251,222,534
0
1
null
null
null
null
UTF-8
C++
false
false
1,587
cc
Lec5_Topological_Sorting_Using_DFS_Algorithm.cc
#include <bits/stdc++.h> using namespace std; #define ll long long int #define endl "\n" void fastio(bool read = false) { if(read) { #ifndef ONLINE_JUGDE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); freopen("error.txt","w",stderr); #endif } ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); return; } template<typename T> class Graph { map<T,list<T>> AdjList; public: void addEdge(T src, T dest, bool bidir = true) { this->AdjList[src].push_back(dest); if(bidir) this->AdjList[dest].push_back(src); } void printAdjList() { for(auto node : this->AdjList) { cout << node.first << " -> "; for(auto nbr : node.second) cout << nbr << " ,"; cout << endl; } } void dfs(T src,unordered_map<T,bool> &visited,list<T> &order) { // setting up the source node as visited. visited[src] = true; for(auto nbr : this->AdjList[src]) if(!visited[nbr]) dfs(nbr,visited,order); order.push_front(src); return; } void topologicalSort() { unordered_map<T,bool> visited; list<T> order; for(auto node : this->AdjList) visited[node.first] = false; for(auto node : this->AdjList) if(!visited[node.first]) dfs(node.first,visited,order); for(T e : order) cout << e << " ,"; cout << endl; return; } }; int main(){ fastio(true); Graph<int> g; int e; cin >> e; while(e--) { int u, v; cin >> u >> v; g.addEdge(u,v,false); } g.topologicalSort(); return 0; } // Sample Input : // 7 // 1 2 // 1 3 // 2 4 // 4 5 // 3 5 // 6 7 // 5 7 // Sample Output : // 6 ,1 ,3 ,2 ,4 ,5 ,7 ,
3e8f8b720bdde9062aa5b1fe2775259e563a189f
1149701f3d1c2e2601b6d4ff081709e68e7aa2b2
/src/trash_measurement.cpp
56500f10d6a1796ec02570680295ebc7771e19c3
[]
no_license
qianlima8888/obstacle_measurement
e5da9bff7d27a136a06831c538e4172682d69ce1
2bf12be0d6e09c72bb744fe341b2ae04ec52ddd0
refs/heads/master
2023-03-20T22:18:01.252856
2021-03-17T11:51:27
2021-03-17T11:51:27
290,915,804
2
0
null
null
null
null
UTF-8
C++
false
false
17,733
cpp
trash_measurement.cpp
#include <ctime> #include <string> #include <math.h> #include <algorithm> #include <vector> #include <iostream> #include <iterator> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/dnn.hpp> #include <opencv2/dnn/shape_utils.hpp> #include <ros/ros.h> #include <message_filters/subscriber.h> #include <message_filters/synchronizer.h> #include <message_filters/sync_policies/approximate_time.h> #include <sensor_msgs/Image.h> #include <image_transport/image_transport.h> #include <sensor_msgs/image_encodings.h> #include <sensor_msgs/LaserScan.h> #include <cv_bridge/cv_bridge.h> using namespace std; using namespace cv; using namespace cv::dnn; #define pi 3.1415926 typedef struct PPoint_ { double x; double y; double z; } ppoint; typedef struct Point_ { double x; double y; Point_(double a, double b) { x = a; y = b; } Point_() { x = 0; y = 0; } } spoint; Rect show; //储存雷达点的像素坐标和二维坐标 poin2i为像素坐标 bool表示是否为边缘点 第二个Point2i储存空间坐标 typedef pair<pair<Point2i, bool>, spoint> laser_coor; Point2i camera_2_rgb(ppoint point_camera); Point getCrossPoint(vector<int> LineA, vector<int> LineB); vector<int> getLineParam(Point start, Point end); float lines_orientation(Point begin, Point end, int flag); void laser_to_rgb(const sensor_msgs::LaserScanConstPtr &scan, vector<laser_coor> &laserPoint); bool pointInRoi(Rect roi, vector<laser_coor> &allPoint, vector<laser_coor> &inPoint); void combineCallback(const sensor_msgs::ImageConstPtr &rgb_image_qhd, const sensor_msgs::LaserScanConstPtr &laser_data); void computerPiexDistance(vector<laser_coor> &Point, float result[2]); void measurement(Mat &roiImg, vector<laser_coor> &laserPoint, int label, int x, int w); void getEdge(Mat &roiImg, vector<vector<Point>>& H_Line, vector<vector<Point>>& V_Line); void CannyAndResult(Mat &roiImg, vector<vector<Point>>& H_Line, vector<vector<Point>>& V_Line); string modelConfiguration = "/home/wode/configuration_folder/trash_ssd/newindoor_bob/deploy.prototxt"; string modelBinary = "/home/wode/configuration_folder/trash_ssd/newindoor_bob/_iter_90109.caffemodel"; //string *class_array = new string[9]{"background", "window", "bed", "aricondition", "sofa", "chair", "cabinet", "trash", "door"}; string *class_array = new string[12]{"background", "bed", "cabinet", "chair", "table", "sofa", "closestool", "door", "refrigerator", "washer", "corner", "trash"}; Net net = readNetFromCaffe(modelConfiguration, modelBinary); double cx_ = 239.9 * 2; double cy_ = 131.975 * 2; double fx_ = 268.225 * 2; double fy_ = 268.575 * 2; //double laser2robot_x = 0.16; //double laser2robot_y = 0.0; double kinect2robot_x = 0.132; double kinect2robot_y = -0.08; double laser2kinect_x = 0.01; double laser2kinect_y = -0.095; double laser2kinect_z = 0.5; //计算每个像素点的实际距离(cm) void computerPiexDistance(vector<laser_coor> &Point, float result[2]) { // //float result[2]; double dis = 0; double all_piex = 0; // int begin = Point.size()*0.2; // int end = Point.size()*0.8; // if((end-begin) < 10) // { // begin = 1; // end = Point.size(); // } //截取中间激光点进行单位像素距离计算 for (int i = 2; i < Point.size(); i++) { all_piex += sqrt(pow((Point[i - 2].first.first.x - Point[i].first.first.x), 2) + pow((Point[i - 2].first.first.y - Point[i].first.first.y), 2)); dis += sqrt(pow((Point[i - 2].second.x - Point[i].second.x), 2) + pow((Point[i - 2].second.y - Point[i].second.y), 2)); } result[0] = dis / all_piex * 100; result[1] = result[0]; } //相机坐标系转像素坐标系 Point2i camera_2_rgb(ppoint point_camera) { Point2i point_; point_.x = (fx_ * point_camera.x / point_camera.z + cx_); point_.y = (fy_ * point_camera.y / point_camera.z + cy_); return point_; } //获得两直线交点 //传入的参数为两条直线的参数 Point getCrossPoint(vector<int> LineA, vector<int> LineB) { int m = LineA[0] * LineB[1] - LineA[1] * LineB[0]; if (m == 0) { cout << "无交点" << endl; return Point(-1, -1); } else { int x = (LineB[2] * LineA[1] - LineA[2] * LineB[1]) / m; int y = (LineA[2] * LineB[0] - LineB[2] * LineA[0]) / m; return Point(x, y); } } //获得直线的一般式方程参数Ax+By+C=0 vector<int> getLineParam(Point start, Point end) { vector<int> result; result.push_back(end.y - start.y); result.push_back(start.x - end.x); result.push_back(end.x * start.y - start.x * end.y); return result; } //识别物体轮廓并画框显示 //利用霍夫变换检测直线然后选择最外侧的直线作为轮廓线 void CannyAndResult(Mat &roiImg, vector<vector<Point>>& H_Line, vector<vector<Point>>& V_Line) { int threshold_value = 30; Mat dst; //使用边缘检测将图片二值化 Canny(roiImg, dst, 10, 50, 3, false); vector<Vec4i> lines; //存储直线数据 HoughLinesP(dst, lines, 1, CV_PI / 180.0, 30, 30, 10); //源图需要是二值图像,HoughLines也是一样 Mat cannyShow = dst(show); getEdge(dst, H_Line, V_Line); imshow("canny", cannyShow); } void getEdge(Mat &roiImg, vector<vector<Point>>& H_Line, vector<vector<Point>>& V_Line) { //查找最上面轮廓线 int i = 0; for(; i<roiImg.rows; i++) { int count = 0; int j=0; for(; j<roiImg.cols; j++) { if(roiImg.at<uchar>(i, j) == 255) { count++; } } if(count>30) { vector<Point> tmp; Point begin(j/2-2, i), end(j/2+2, i); tmp.push_back(begin); tmp.push_back(end); tmp.push_back(Point((begin.x + end.x) / 2, (begin.y + end.y) / 2)); H_Line.push_back(tmp); break; } } //查找最下面轮廓线 i = roiImg.rows-1; for( ; i>=0; i--) { int count = 0; int j=0; for(; j<roiImg.cols; j++) { if(roiImg.at<uchar>(i, j) == 255) { count++; } } if(count>10) { vector<Point> tmp; Point begin(j/2-2, i), end(j/2+2, i); tmp.push_back(begin); tmp.push_back(end); tmp.push_back(Point((begin.x + end.x) / 2, (begin.y + end.y) / 2)); H_Line.push_back(tmp); break; } } //查找最右面轮廓线 i = roiImg.cols-1; for( ; i>=0; i--) { int count = 0; int j=0; for(; j<roiImg.rows; j++) { if(roiImg.at<uchar>(j, i) == 255) { count++; } } if(count>10) { vector<Point> tmp; Point begin(i, j/2-2), end(i, j/2+2); tmp.push_back(begin); tmp.push_back(end); tmp.push_back(Point((begin.x + end.x) / 2, (begin.y + end.y) / 2)); V_Line.push_back(tmp); break; } } //查找最左面轮廓线 i = 0; for( ; i<roiImg.cols; i++) { int count = 0; int j=0; for(; j<roiImg.rows; j++) { if(roiImg.at<uchar>(j, i) == 255) { count++; } } if(count>10) { vector<Point> tmp; Point begin(i, j/2-2), end(i, j/2+2); tmp.push_back(begin); tmp.push_back(end); tmp.push_back(Point((begin.x + end.x) / 2, (begin.y + end.y) / 2)); V_Line.push_back(tmp); break; } } } void measurement(Mat &roiImg, vector<laser_coor> &laserPoint, int label, int x, int w) { int rangeXMIN, rangeXMAX; auto di = laserPoint; if (di.size() == 0) { ROS_INFO_STREAM("-------------------------------"); ROS_INFO_STREAM("连续平面激光点数过少"); ROS_INFO_STREAM("无法进行有效测量,结束该帧测量"); ROS_INFO_STREAM("-------------------------------\n"); return; } float dis[2]; computerPiexDistance(di, dis); vector<vector<Point>> H_Line, V_Line; //储存水平线与竖直线 储存每条线的起点 中点和终点 ROS_INFO_STREAM("-------------------------------"); ROS_INFO_STREAM("检测到" << class_array[label] << ",开始测量......"); CannyAndResult(roiImg, H_Line, V_Line); int top =0, left = 1, right = 0, bottom =1; //将边缘线延长 vector<int> paramA = getLineParam(H_Line[top][0], H_Line[top][1]); vector<int> paramB = getLineParam(V_Line[left][0], V_Line[left][1]); vector<int> paramC = getLineParam(H_Line[bottom][0], H_Line[bottom][1]); vector<int> paramD = getLineParam(V_Line[right][0], V_Line[right][1]); Mat gray_dst = roiImg.clone(); //绘制轮廓 auto crossPointTL = getCrossPoint(paramA, paramB); auto crossPointTR = getCrossPoint(paramA, paramD); auto crossPointBL = getCrossPoint(paramC, paramB); auto crossPointBR = getCrossPoint(paramC, paramD); line(gray_dst, crossPointTL, crossPointTR, Scalar(0, 0, 255), 1, LINE_AA); line(gray_dst, crossPointTL, crossPointBL, Scalar(0, 0, 255), 1, LINE_AA); line(gray_dst, crossPointTR, crossPointBR, Scalar(0, 0, 255), 1, LINE_AA); line(gray_dst, crossPointBR, crossPointBL, Scalar(0, 0, 255), 1, LINE_AA); float hi = sqrt((crossPointTL - crossPointBL).dot(crossPointTL - crossPointBL)) * dis[1]; float wh = sqrt((crossPointBL - crossPointBR).dot(crossPointBL - crossPointBR)) * dis[0]; ROS_INFO_STREAM("higet is " << hi << "cm, width is " << wh << "cm"); ROS_INFO_STREAM("-------------------------------\n"); char tx[20]; sprintf(tx, "%.2f", hi); putText(gray_dst, tx, (crossPointTL + crossPointBL) / 2, FONT_HERSHEY_SIMPLEX, 0.3, Scalar(0, 0, 255), 1.8); memset(tx, 0, 20); sprintf(tx, "%.2f", wh); putText(gray_dst, tx, (crossPointBR + crossPointBL) / 2, FONT_HERSHEY_SIMPLEX, 0.3, Scalar(0, 0, 255), 1.8); Mat lunkuoMat = gray_dst(show); imshow("lines", lunkuoMat); //显示霍夫变换检测后框选的物体轮廓图 } //激光雷达坐标系转换为像素坐标系 并判断激光点是否为边缘点 void laser_to_rgb(const sensor_msgs::LaserScanConstPtr &scan, vector<laser_coor> &laserPoint) { double angle = 0; double increment_angle = 0.5 / 180 * 3.1415; //每一束激光 for (int id = scan->ranges.size() - 1; id >= 0; id--) //倒置 { double dist = scan->ranges[id]; if (std::isinf(dist) || std::isnan(dist)) { angle += increment_angle; continue; } double laser_x = dist * sin(angle); double laser_y = -dist * cos(angle); angle += increment_angle; ppoint point_camera; point_camera.z = (laser_x + laser2kinect_x); point_camera.x = -laser_y + laser2kinect_y; point_camera.y = laser2kinect_z; Point2i point_ = camera_2_rgb(point_camera); if ((point_.x > 0) && (point_.y > 0)) { laserPoint.push_back(make_pair(make_pair(point_, false), spoint(laser_x, laser_y))); } } } //判断哪些激光点位于识别到的物体上 //并判断激光线在照片中的倾斜角度 bool pointInRoi(Rect roi, vector<laser_coor> &allPoint, vector<laser_coor> &inPoint) { int Xmin = roi.tl().x , Ymin = roi.tl().y; int Xmax = roi.br().x , Ymax = roi.br().y; for (int i = 0; i < allPoint.size(); ++i) { if (allPoint[i].first.first.x >= Xmin && allPoint[i].first.first.x <= Xmax) { inPoint.push_back(allPoint[i]); } } double maxDis = 0.1; int begin, end; for(int i = 1; i<inPoint.size(); i++) { auto dis = pow((inPoint[i].second.x - inPoint[i-1].second.x), 2) + pow((inPoint[i].second.y - inPoint[i-1].second.y), 2); //cout<<dis<<endl; if( dis > (maxDis * maxDis) ) { begin = i; //ROS_INFO_STREAM("begin is "<<begin); break; } } //cout<<endl<<endl; for(int i = inPoint.size() - 1; i>0; i--) { auto dis = pow((inPoint[i].second.x - inPoint[i-1].second.x), 2) + pow((inPoint[i].second.y - inPoint[i-1].second.y), 2); //cout<<dis<<endl; if( dis > maxDis * maxDis ) { end = i; //ROS_INFO_STREAM("end is "<<end); break; } } if(end == begin) { begin; end = inPoint.size()-1; //ROS_INFO_STREAM("begin is "<<begin<<" end is "<<end); //ROS_INFO_STREAM("有效激光点太少 无法测量"); //return false; } vector<laser_coor> tmp; for(int i = begin+1; i<end; i++) { tmp.push_back(inPoint[i]); } inPoint.swap(tmp); if(inPoint.size()<6) { ROS_INFO_STREAM("point size is "<<inPoint.size()); ROS_INFO_STREAM("有效激光点太少 无法测量"); return true; } for(int i = 0; i<3; i++) { //中值滤波 double x, y; for(int i =2; i<inPoint.size()-2;i++) { x = 0; y = 0; x += inPoint[i-2].first.first.x + inPoint[i-1].first.first.x + inPoint[i].first.first.x + inPoint[i+1].first.first.x + inPoint[i+2].first.first.x; y += inPoint[i-2].first.first.y + inPoint[i-1].first.first.y + inPoint[i].first.first.y + inPoint[i+1].first.first.y + inPoint[i+2].first.first.y; inPoint[i].first.first.x = x/5; inPoint[i].first.first.y = y/5; x = 0; y = 0; x += inPoint[i-2].second.x + inPoint[i-1].second.x + inPoint[i].second.x + inPoint[i+1].second.x + inPoint[i+2].second.x; y += inPoint[i-2].second.y + inPoint[i-1].second.y + inPoint[i].second.y + inPoint[i+1].second.y + inPoint[i+2].second.y; inPoint[i].second.x = x/5; inPoint[i].second.y = y/5; } } return true; } //接收到传感器数据后的回调函数 void combineCallback(const sensor_msgs::ImageConstPtr &rgb_image_qhd, const sensor_msgs::LaserScanConstPtr &laser_data) { //ROS_INFO("----------------------------"); //ROS_INFO("得到一帧同步数据, 开始处理......"); //clock_t time_old = clock(); vector<laser_coor> laserPoint; laser_to_rgb(laser_data, laserPoint); cv_bridge::CvImagePtr rgb_ptr; cv::Mat resize_rgb_mat; //缩小尺寸后的图片 int height; int width; try { rgb_ptr = cv_bridge::toCvCopy(rgb_image_qhd, sensor_msgs::image_encodings::BGR8); width = rgb_ptr->image.cols / 2; height = rgb_ptr->image.rows / 2; cv::resize(rgb_ptr->image, resize_rgb_mat, cv::Size(width, height), 0, 0, cv::INTER_NEAREST); } catch (cv_bridge::Exception &e) { ROS_ERROR("cv_bridge exception: %s", e.what()); ROS_INFO("结束该帧数据处理, 等待下帧数据....."); return; } //运行深度学习检测图片中的物体 Mat delframe; resize(rgb_ptr->image, delframe, Size(300, 300)); Mat inputBlob = blobFromImage(delframe, 1, Size(300, 300), 127.5, false, false); net.setInput(inputBlob, "data"); Mat detection = net.forward("detection_out"); Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<float>()); //记录新帧中有哪些类别的识别 std::vector<int> detection_record_new; //记录上面的识别对应detectionMat中的哪一行 std::vector<int> detection_record_i; //新的一帧对应的识别, for (int i = 0; i < detectionMat.rows; i++) { float confidence = detectionMat.at<float>(i, 2); //置信度 //ROS_INFO_STREAM("confidence is "<<confidence); if (confidence > 0.5) { int labelidx = detectionMat.at<float>(i, 1); //识别物体类别 if (labelidx==11) { detection_record_new.push_back(labelidx); //图片中的框索引 detection_record_i.push_back(i); } } } //对新物体进行添加, std::vector<int>::iterator new_detection_iterator = detection_record_new.begin(); int detection_i = 0; for (; new_detection_iterator != detection_record_new.end(); new_detection_iterator++, detection_i++) { int xLeftTop = static_cast<int>(detectionMat.at<float>(detection_record_i[detection_i], 3) * width); int yLeftTop = static_cast<int>(detectionMat.at<float>(detection_record_i[detection_i], 4) * height); int xRightBottom = static_cast<int>(detectionMat.at<float>(detection_record_i[detection_i], 5) * width); int yRightBottom = static_cast<int>(detectionMat.at<float>(detection_record_i[detection_i], 6) * height); //抑制边界 if (xLeftTop < 0) xLeftTop = 0; if (yLeftTop < 0) yLeftTop = 0; if (xRightBottom > width) xRightBottom = width - 1; if (yRightBottom > height) yRightBottom = height - 1; int x = xLeftTop * 2; int y = yLeftTop * 2; int w = (xRightBottom - xLeftTop) * 2; int h = (yRightBottom - yLeftTop) * 2+10; if ((x + w) > rgb_ptr->image.cols) w = rgb_ptr->image.cols - x; if ((y + h) > rgb_ptr->image.rows) h = rgb_ptr->image.rows - y; Rect object_rect(x, y, w, h); show = object_rect; //ROS_INFO("运行grabcut函数......"); //抠图 去除背景干扰 Mat cut, bg, fg; grabCut(rgb_ptr->image, cut, object_rect, bg, fg, 4, GC_INIT_WITH_RECT); compare(cut, GC_PR_FGD, cut, CMP_EQ); Mat foreGround(rgb_ptr->image.size(), CV_8UC3, Scalar(255, 255, 255)); rgb_ptr->image.copyTo(foreGround, cut); imshow("grab", foreGround); //ROS_INFO("grabcut函数完成"); //rectangle(rgb_ptr->image, object_rect, Scalar(0, 0, 255)); imshow("original", rgb_ptr->image); vector<laser_coor> inPoint; Mat LaserMat = foreGround.clone(); try { if(pointInRoi(object_rect, laserPoint, inPoint)) { //ROS_INFO_STREAM(" size is "<<inPoint.size()); measurement(foreGround, inPoint, *new_detection_iterator, x, w); } for (int i = 0; i < inPoint.size(); i++) { circle(LaserMat, inPoint[i].first.first, 1, Scalar(0, 255, 0), 1, 1); //红色显示边缘点 } imshow("laser", LaserMat(show)); } catch(...) { waitKey(1000); continue; } waitKey(1000); } } int main(int argc, char **argv) { ros::init(argc, argv, "occ_xc"); ros::NodeHandle nh_; typedef message_filters::sync_policies::ApproximateTime<sensor_msgs::Image, sensor_msgs::LaserScan> rgb_laser_syncpolicy; //原图为1920*1080,rect为/2之后的了 message_filters::Subscriber<sensor_msgs::Image> *rgb_image_sub_ = new message_filters::Subscriber<sensor_msgs::Image>(nh_, "kinect2/qhd/image_color_rect", 1); message_filters::Subscriber<sensor_msgs::LaserScan> *laser_sub_ = new message_filters::Subscriber<sensor_msgs::LaserScan>(nh_, "/scan", 1); message_filters::Synchronizer<rgb_laser_syncpolicy> *sync_ = new message_filters::Synchronizer<rgb_laser_syncpolicy>(rgb_laser_syncpolicy(20), *rgb_image_sub_, *laser_sub_); sync_->registerCallback(boost::bind(&combineCallback, _1, _2)); ros::spin(); return 0; }
d9971aa8ceeb1ffd6cb0053d242a7c132b938d9e
0bef9637ea35797a1e23f72cb3900be59b5a790f
/HardwareSensor/Processor.cpp
003d2262f6790719b216a40c3519587adb8320e9
[]
no_license
Agile2018/HardwareSensor
72635739cb2c8c2a32474ebcb1bc2b06bcae2910
8503fb4c828601b2fcd838580c88128e60279a76
refs/heads/master
2020-05-18T14:27:42.833469
2019-05-13T18:34:36
2019-05-13T18:34:36
184,472,348
0
0
null
null
null
null
UTF-8
C++
false
false
370
cpp
Processor.cpp
#include "Processor.h" Processor::Processor() { } Processor::~Processor() { } void Processor::SetConsumption(int consumption) { _consumption = consumption; } int Processor::GetConsumption() { return _consumption; } void Processor::SetDescription(string description) { _description = description; } string Processor::GetDescription() { return _description; }
c4d1d76d2cb743a82cb5dfcc82a13a3164d34e7a
b04636f31f716c21a6c0d77bc49b876bc496fff7
/Olympiad/CST 2018/Thầy Hùng/NK1/WEDDING.CPP
0991909cadf22d6e09a697eadb79daa48cfb0e58
[]
no_license
khanhvu207/competitiveprogramming
736b15d46a24b93829f47e5a7dbcf461f4c30e9e
ae104488ec605a3d197740a270058401bc9c83df
refs/heads/master
2021-12-01T00:52:43.729734
2021-11-23T23:29:31
2021-11-23T23:29:31
158,355,181
19
1
null
null
null
null
UTF-8
C++
false
false
1,546
cpp
WEDDING.CPP
#include <bits/stdc++.h> using namespace std; typedef long long ll; int x[30000], ans[30000], h[30000]; vector<int> a[30000]; bool blank[30000], fre[30000]; int n,m,s,t; void dfs(int u, int i) { x[i] = u; if (u == t) { for (int j = 1; j<=i; j++) { ans[j] = x[j]; h[ans[j]] = 1; blank[ans[j]] = false; } m = i; return; } fre[u] = false; for (ll v = 0; v < a[u].size(); v++) if (fre[a[u][v]]) dfs(a[u][v], i+1); } int dfs2(int u) { int re = 0; fre[u] = false; for (int i = 0; i < a[u].size(); i++) if (fre[a[u][i]]) re = max(re, dfs2(a[u][i])); return re+1; } int main() { freopen("wedding.inp","r",stdin); freopen("wedding.out","w",stdout); cin >> n; for (int i = 1; i<n; i++) { int u,v; cin >> u >> v; a[u].push_back(v); a[v].push_back(u); } cin >> s >> t; memset(fre,true,sizeof(fre)); memset(blank,true,sizeof(blank)); dfs(s,1); memset(fre,true,sizeof(fre)); for (int i = 1; i<=m; i++) { fre[ans[i]] = false; for (int j = 0; j < a[ans[i]].size(); j++) if (fre[a[ans[i]][j]] && blank[a[ans[i]][j]]) h[ans[i]] = max( h[ans[i]] , dfs2(a[ans[i]][j])+1 ); } int smax = 0; for (int i = 1; i < m; i++) for (int j = i+1; j <= m; j++) smax = max( smax , min(h[i]+i-1 , h[j]+m-j) ); cout << smax << endl; return 0; }
275b6f9ebe0ffbc05ac26cf5158ad2f9c4e6a17e
891867ba393ad09d6902402d5b6199ec2f760704
/Source/ProtoAI/AISense_Smell.h
7fbf8856ea0f6476534ec2039a5144451396460c
[]
no_license
CorentinGaut/ProtoAI
fbaa54e9bb5fb7af255c917f5ba5588d7b112f17
8923b47db1b1b1f3d1ad284a1302f526bc3dd6d8
refs/heads/master
2022-04-03T10:55:41.419327
2020-02-18T08:19:47
2020-02-18T08:19:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
864
h
AISense_Smell.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Perception/AISense_Blueprint.h" #include "AISense_Smell.generated.h" /** * */ class UAISenseConfig_Smell; UCLASS(meta=(DisplayName="AI Smell Config")) class PROTOAI_API UAISense_Smell : public UAISense_Blueprint { GENERATED_BODY() public: struct FDigestedSmellProperties { float Radius; bool DisplayDebugSphere; FDigestedSmellProperties(); FDigestedSmellProperties(const UAISenseConfig_Smell& SenseConfig); }; TArray<FDigestedSmellProperties> DigestedProperties; UAISense_Smell(); protected: virtual float Update() override; void OnNewListenerImpl(const FPerceptionListener& NewListener); void OnListenerRemovedImpl(const FPerceptionListener& UpdatedListener); };
c2bd27b38d17d18adc2d3808a88adf4c41b687e9
23c7dfdfce59bd7bb9675d150f2b52b27fe1061f
/widgets/KeyDetail.cpp
a502fcf286eb01a5c91274eba2d308138d18f7df
[ "BSD-3-Clause" ]
permissive
chris2511/xca
6d0d0e0d277b2a13897a88c0458186dd86ec924e
96ca26cc83f0b684b36be54bb303cbcc1c415c1b
refs/heads/main
2023-09-05T16:27:54.681428
2023-09-03T19:47:49
2023-09-03T20:37:02
649,898
1,122
213
NOASSERTION
2023-09-03T20:12:55
2010-05-06T07:54:43
C++
UTF-8
C++
false
false
4,437
cpp
KeyDetail.cpp
/* vi: set sw=4 ts=4: * * Copyright (C) 2001 - 2010 Christian Hohnstaedt. * * All rights reserved. */ #include "lib/main.h" #include "lib/pki_evp.h" #include "lib/pki_scard.h" #include "KeyDetail.h" #include "MainWindow.h" #include "Help.h" #include "distname.h" #include "clicklabel.h" #include "XcaApplication.h" #include "OidResolver.h" #include <QLabel> #include <QPushButton> #include <QLineEdit> KeyDetail::KeyDetail(QWidget *w) : QDialog(w ? w : mainwin) , keySqlId() { setupUi(this); setWindowTitle(XCA_TITLE); image->setPixmap(QPixmap(":keyImg")); mainwin->helpdlg->register_ctxhelp_button(this, "keydetail"); keyModulus->setFont(XcaApplication::tableFont); tabWidget->setCurrentIndex(0); Database.connectToDbChangeEvt(this, SLOT(itemChanged(pki_base*))); } #ifndef OPENSSL_NO_EC static QString CurveComment(int nid) { foreach(builtin_curve curve, builtinCurves) { if (curve.nid == nid) return curve.comment; } return QString(); } #endif void KeyDetail::setupFingerprints(pki_key *key) { int pos = 0; QWidget *widget = new QWidget(fingerprint); QVBoxLayout *v = new QVBoxLayout(fingerprint); QGridLayout *grid = new QGridLayout(widget); v->addStretch(); v->addWidget(widget); v->addStretch(); QStringList sl; sl << "ssh MD5" << "ssh SHA256 B64" << "x509 SHA1" << "DER SHA256"; foreach(QString type, sl) { qDebug() << type << key->fingerprint(type); QLabel *left = new QLabel(widget); CopyLabel *right = new CopyLabel(widget); left->setTextFormat(Qt::PlainText); left->setText(type); right->setText(key->fingerprint(type)); grid->addWidget(left, pos, 0); grid->addWidget(right, pos, 1); pos++; } } void KeyDetail::setKey(pki_key *key) { keySqlId = key->getSqlItemId(); keyDesc->setText(key->getIntName()); keyLength->setText(key->length()); keyPrivEx->disableToolTip(); if (!key->isToken()) tabWidget->removeTab(1); tlHeader->setText(tr("Details of the %1 key").arg(key->getTypeString())); comment->setPlainText(key->getComment()); setupFingerprints(key); if (key->isPubKey()) { keyPrivEx->setText(tr("Not available")); keyPrivEx->setRed(); } else if (key->isToken()) { image->setPixmap(QPixmap(":scardImg")); pki_scard *card = static_cast<pki_scard *>(key); cardLabel->setText(card->getCardLabel()); cardModel->setText(card->getModel()); cardManufacturer->setText(card->getManufacturer()); cardSerial->setText(card->getSerial()); slotLabel->setText(card->getLabel()); cardId->setText(card->getId()); keyPrivEx->setText(tr("Security token")); } else { keyPrivEx->setText(tr("Available")); keyPrivEx->setGreen(); } switch (key->getKeyType()) { case EVP_PKEY_RSA: keyPubEx->setText(key->pubEx()); keyModulus->setText(key->modulus()); break; case EVP_PKEY_DSA: tlPubEx->setText(tr("Sub prime")); tlModulus->setTitle(tr("Public key")); tlPrivEx->setText(tr("Private key")); keyPubEx->setText(key->subprime()); keyModulus->setText(key->pubkey()); break; #ifndef OPENSSL_NO_EC case EVP_PKEY_EC: int nid; nid = key->ecParamNid(); tlModulus->setTitle(tr("Public key")); tlPrivEx->setText(tr("Private key")); tlPubEx->setText(tr("Curve name")); keyPubEx->setText(OBJ_nid2sn(nid)); connect(keyPubEx, SIGNAL(doubleClicked(QString)), MainWindow::getResolver(), SLOT(searchOid(QString))); keyPubEx->setToolTip(CurveComment(nid)); keyModulus->setText(key->ecPubKey()); break; #ifdef EVP_PKEY_ED25519 case EVP_PKEY_ED25519: tlModulus->setTitle(tr("Public key")); tlPrivEx->setText(tr("Private key")); tlPubEx->setText(tr("Curve name")); keyPubEx->setText("ed25519"); keyModulus->setText(key->ed25519PubKey().toHex()); break; #endif #endif default: tlHeader->setText(tr("Unknown key")); } } void KeyDetail::itemChanged(pki_base *pki) { if (pki->getSqlItemId() == keySqlId) keyDesc->setText(pki->getIntName()); } void KeyDetail::showKey(QWidget *parent, pki_key *key, bool ro) { if (!key) return; KeyDetail *dlg = new KeyDetail(parent); if (!dlg) return; dlg->setKey(key); dlg->keyDesc->setReadOnly(ro); dlg->comment->setReadOnly(ro); if (dlg->exec()) { db_base *db = Database.modelForPki(key); if (!db) { key->setIntName(dlg->keyDesc->text()); key->setComment(dlg->comment->toPlainText()); } else { db->updateItem(key, dlg->keyDesc->text(), dlg->comment->toPlainText()); } } delete dlg; }
80d285db705540a553030d80049a1c2574c7504c
539c3be133f2139e64e4d50d4074021a68d97e36
/src/lexical_parser.cpp
b2c454d638b2d61af8875577c2c7895da8c35479
[ "MIT" ]
permissive
FredericDT/c89-lexical-parser
8380d3ead158c0c01ed27eb9ae94887ee96b67f1
fff85ce3320031d9e92b681653f956a6bb911f00
refs/heads/master
2020-08-07T05:36:01.979056
2019-10-20T08:25:42
2019-10-20T08:25:42
213,319,248
0
0
null
null
null
null
UTF-8
C++
false
false
25,846
cpp
lexical_parser.cpp
// // Created by FredericDT on 10/5/2019. // #include "lexical_parser.h" #include "re2/re2.h" #include <iostream> #include <sstream> namespace fdt { namespace lexical_parser { const std::string KEYWORD_STRING = "keyword"; const std::string IDENTIFIER_STRING = "identifier"; const std::string FLOATING_CONSTANT_STRING = "floating_constant"; const std::string INTEGER_CONSTANT_STRING = "integer_constant"; const std::string ENUMERATION_CONSTANT_STRING = "enumeration_constant"; const std::string CHARACTER_CONSTANT_STRING = "character_constant"; const std::string STRING_LITERAL_STRING = "string_literal"; const std::string OPERATOR_STRING = "operator"; const std::string PUNCTUATOR_STRING = "punctuator"; const std::string HEADER_NAME = "header_name"; const std::string PREPROESSING_NUMBER_STRING = "preprocessing_number"; const std::string COMMENT_STRING = "comment"; const std::string UNKNOWN_STRING = "unknown"; inline const std::string to_string(const enum lexical_element::type &v) { switch (v) { case lexical_element::KEYWORD: return KEYWORD_STRING; case lexical_element::IDENTIFIER: return IDENTIFIER_STRING; case lexical_element::FLOATING_CONSTANT: return FLOATING_CONSTANT_STRING; case lexical_element::INTEGER_CONSTANT: return INTEGER_CONSTANT_STRING; case lexical_element::ENUMERATION_CONSTANT: return ENUMERATION_CONSTANT_STRING; case lexical_element::CHARACTER_CONSTANT: return CHARACTER_CONSTANT_STRING; case lexical_element::STRING_LITERAL: return STRING_LITERAL_STRING; case lexical_element::OPERATOR: return OPERATOR_STRING; case lexical_element::PUNCTUATOR: return PUNCTUATOR_STRING; case lexical_element::HEADER_NAME: return HEADER_NAME; case lexical_element::PREPROESSING_NUMBER: return PREPROESSING_NUMBER_STRING; case lexical_element::COMMENT: return COMMENT_STRING; default: return UNKNOWN_STRING; } } const std::string lexical_element::to_string() const { return "<" + lexical_parser::to_string(this->type) + ", " + this->property + ">"; } enum lexical_element::type lexical_element::get_type() const { return type; } lexical_element &lexical_element::set_type(enum lexical_element::type type) { lexical_element::type = type; return *this; } const std::string &lexical_element::get_raw() const { return raw; } lexical_element &lexical_element::set_raw(const std::string &raw) { lexical_element::raw = raw; return *this; } const std::string &lexical_element::get_property() const { return property; } lexical_element &lexical_element::set_property(const std::string &property) { lexical_element::property = property; return *this; } const RE2 KEYWORD_REGEX( "^(auto|break|case|char|const|continue|default|do|double|int|else|long|enum|register|extern|return|float|short|for|signed|goto|sizeof|if|static|struct|switch|typedef|union|unsigned|void|volatile|while)"); const RE2 IDENTIFIER_REGEX("^([_a-zA-Z][_a-zA-Z0-9]*)"); const RE2 FLOATING_CONSTANT_REGEX( "^((([0-9]*\\.[0-9]+|[0-9]+)([eE][+-]?[0-9]+)?|[0-9]+([eE][+-]?[0-9]+))([flFL])?)"); const RE2 INTEGER_CONSTANT_REGEX( "^((([1-9][0-9]*)|(0[xX][0-9a-fA-F]+)|(0([0-7])*))(([uU][lL]?)|([lL][uU]?))?)"); const RE2 ENUMERATION_CONSTANT_REGEX( "^([_a-zA-Z][_a-zA-Z0-9]*)"); // same as identifier, see reference http://www.open-std.org/Jtc1/sc22/wg14/www/docs/n1124.pdf const RE2 CHARACTER_CONSTANT_REGEX( "^(L?'([^'\\\n]|\\\\['\"?\\abfnrtv]|\\\\[0-7]{1,3}|\\\\x[0-9a-fA-F]+)')"); const RE2 STRING_LITERAL_REGEX( "^(L?\"([^\"\\\n]|(\\\\['\"?\\abfnrtv]|\\\\[0-7]{1,3}|\\\\x[0-9a-fA-F]+)+)*\")"); const RE2 OPERATOR_REGEX( "^((\\[)|(\\])|(\\()|(\\))|(\\.)|->|(\\+\\+)|(--)|&|(\\*)|(\\+)|-|~|!|(sizeof)|(\\/)|%|(<<)|(>>)|<|>|(<=)|(>=)|(==)|(!=)|\\^|(\\|)|(&&)|(\\|\\|)|(\\?)|:|=|(\\*=)|(\\/=)|(%=)|(\\+=)|(-=)|(<<=)|(>>=)|(&=)|(\\^=)|\\|=|,|#{1,2})"); const RE2 PUNCTUATOR_REGEX("^(\\[|\\]|\\(|\\)|\\{|\\}|\\*|,|:|=|;|\\.\\.\\.|#)"); const RE2 HEADER_NAME_REGEX("^((<([^>]+)>)|(\"([^\"]+)\"))"); const RE2 PREPROCESSING_NUMBER_REGEX("^([0-9]|\\.[0-9])([0-9a-zA-Z_]|e[+-]|E[+-])?"); const RE2 COMMENT_START_REGEX("^(\\/\\*)"); const RE2 COMMENT_REGEX("(?s)^(\\/\\*(.*)\\*\\/)"); const RE2 INCLUDE_PREPROCESSING_REGEX("^(#include)"); const RE2 UNKNOWN_REGEX("^(\\\\)"); const std::string to_string(const std::vector<lexical_element> &v) { std::stringstream ss; for (auto i = v.begin(); i != v.end(); ++i) { ss << i->to_string() << std::endl; } return std::string(ss.str()); } long get_identifier_id(std::map<std::string, long> &map, std::string &id) { if (!map[id]) { map[id] = map.size(); } return map[id]; } void parse_match_result(std::string &buffer, std::string &match, std::vector<lexical_element> &result, lexical_element &e, enum lexical_element::type type, std::map<std::string, long> &identifier_map, bool &excep, bool verbose, long &line_count, long &char_count, bool include_comments) { excep = false; e.set_type(type); std::string property = match; if (type == lexical_element::IDENTIFIER) { // property = "id" + std::to_string(get_identifier_id(identifier_map, match)); property = match; } e.set_property(property); e.set_raw(match); if (type == lexical_element::COMMENT) { long tmp_line_count = 0; long last_line_char_index = 0; for (long i = 0; i < match.length(); ++i) { if (match[i] == '\n') { last_line_char_index = i + 1; ++tmp_line_count; } } char_count = match.length() - last_line_char_index; line_count += tmp_line_count; } else { char_count += match.length(); } buffer = buffer.substr(match.length(), buffer.length() - match.length()); while (buffer[0] == '\n' || buffer[0] == '\t' || buffer[0] == ' ') { if (buffer[0] == '\n') { char_count = 0; ++line_count; } else { ++char_count; } buffer = buffer.substr(1); } if (type != lexical_element::COMMENT || include_comments) { result.emplace_back(e); } if (verbose) { std::cout << __FILE__ << ":" << __LINE__ << " match:" << match << std::endl; std::cout << __FILE__ << ":" << __LINE__ << " e:" << e.to_string() << std::endl; } } lexical_parse_result lexical_parse(std::istream &input_stream, bool verbose, bool include_comments) { lexical_parse_result parse_result = lexical_parse_result(); std::vector<lexical_element> lexical_element_vector = std::vector<lexical_element>(); long parsed_line_count = 1; long parsed_char_count = 0; long total_line_count = 0; long total_char_count = 0; bool excep = false; std::string buffer; std::map<std::string, long> identifier_map = std::map<std::string, long>(); enum automata_state::state automata_state = automata_state::NEUTRAL; do { if (input_stream) { int t = input_stream.get(); switch (t) { case EOF: break; case '\n': ++total_char_count; ++total_line_count; if (!buffer.empty()) { buffer += (char) t; } else { ++parsed_line_count; parsed_char_count = 0; } break; case ' ': case '\t': ++total_char_count; if (!buffer.empty()) { buffer += (char) t; } else { ++parsed_char_count; } break; default: input_stream.unget(); std::string tmp; input_stream >> tmp; if (verbose) { std::cout << __FILE__ << ":" << __LINE__ << " tmp:" << tmp << std::endl; } buffer += tmp; total_char_count += tmp.length(); } } if (buffer.length()) { if (verbose) { std::cout << __FILE__ << ":" << __LINE__ << " buffer:" << buffer << std::endl; } lexical_element e = lexical_element(); std::string re_match; if (automata_state == automata_state::COMMENT) { if (RE2::PartialMatch(buffer, COMMENT_REGEX, &re_match)) { automata_state = automata_state::NEUTRAL; if (verbose) { std::cout << __FILE__ << ":" << __LINE__ << " exited COMMENT mode" << std::endl; } parse_match_result(buffer, re_match, lexical_element_vector, e, lexical_element::COMMENT, identifier_map, excep, verbose, parsed_line_count, parsed_char_count, include_comments); } } else { std::string int_re_match; std::string comment_re_match; std::string header_name_re_match; std::string include_re_match; std::string identifier_re_match; if (RE2::PartialMatch(buffer, KEYWORD_REGEX, &re_match) | RE2::PartialMatch(buffer, IDENTIFIER_REGEX, &identifier_re_match)) { if (identifier_re_match.length() > re_match.length()) { parse_match_result(buffer, identifier_re_match, lexical_element_vector, e, lexical_element::IDENTIFIER, identifier_map, excep, verbose, parsed_line_count, parsed_char_count, include_comments); } else { parse_match_result(buffer, re_match, lexical_element_vector, e, lexical_element::KEYWORD, identifier_map, excep, verbose, parsed_line_count, parsed_char_count, include_comments); } } else if (RE2::PartialMatch(buffer, FLOATING_CONSTANT_REGEX, &re_match) | RE2::PartialMatch(buffer, INTEGER_CONSTANT_REGEX, &int_re_match)) { if (int_re_match.length() >= re_match.length()) { parse_match_result(buffer, int_re_match, lexical_element_vector, e, lexical_element::INTEGER_CONSTANT, identifier_map, excep, verbose, parsed_line_count, parsed_char_count, include_comments); } else { parse_match_result(buffer, re_match, lexical_element_vector, e, lexical_element::FLOATING_CONSTANT, identifier_map, excep, verbose, parsed_line_count, parsed_char_count, include_comments); } } else if (RE2::PartialMatch(buffer, ENUMERATION_CONSTANT_REGEX, &re_match)) { // TODO: figure out what is this parse_match_result(buffer, re_match, lexical_element_vector, e, lexical_element::ENUMERATION_CONSTANT, identifier_map, excep, verbose, parsed_line_count, parsed_char_count, include_comments); } else if (RE2::PartialMatch(buffer, CHARACTER_CONSTANT_REGEX, &re_match)) { parse_match_result(buffer, re_match, lexical_element_vector, e, lexical_element::CHARACTER_CONSTANT, identifier_map, excep, verbose, parsed_line_count, parsed_char_count, include_comments); } else if (automata_state == automata_state::NEUTRAL && RE2::PartialMatch(buffer, STRING_LITERAL_REGEX, &re_match)) { parse_match_result(buffer, re_match, lexical_element_vector, e, lexical_element::STRING_LITERAL, identifier_map, excep, verbose, parsed_line_count, parsed_char_count, include_comments); } else if (automata_state == automata_state::INCLUDE && RE2::PartialMatch(buffer, HEADER_NAME_REGEX, &header_name_re_match)) { automata_state = automata_state::NEUTRAL; if (verbose) { std::cout << __FILE__ << ":" << __LINE__ << " exited INCLUDE mode" << std::endl; } parse_match_result(buffer, header_name_re_match, lexical_element_vector, e, lexical_element::HEADER_NAME, identifier_map, excep, verbose, parsed_line_count, parsed_char_count, include_comments); } else if (RE2::PartialMatch(buffer, COMMENT_START_REGEX, &comment_re_match) | RE2::PartialMatch(buffer, OPERATOR_REGEX, &re_match) | RE2::PartialMatch(buffer, INCLUDE_PREPROCESSING_REGEX, &include_re_match) ) { if (include_re_match.length() && automata_state == automata_state::NEUTRAL) { automata_state = automata_state::INCLUDE; if (verbose) { std::cout << __FILE__ << ":" << __LINE__ << " entered INCLUDE mode" << std::endl; } parse_match_result(buffer, re_match, lexical_element_vector, e, lexical_element::PUNCTUATOR, identifier_map, excep, verbose, parsed_line_count, parsed_char_count, include_comments); RE2::PartialMatch(buffer, IDENTIFIER_REGEX, &re_match); parse_match_result(buffer, re_match, lexical_element_vector, e, lexical_element::IDENTIFIER, identifier_map, excep, verbose, parsed_line_count, parsed_char_count, include_comments); } else if (comment_re_match.length() >= re_match.length()) { automata_state = automata_state::COMMENT; if (verbose) { std::cout << __FILE__ << ":" << __LINE__ << " matched: " << comment_re_match << std::endl; std::cout << __FILE__ << ":" << __LINE__ << " entered COMMENT mode" << std::endl; } // parse_match_result(buffer, comment_re_match, lexical_element_vector, e, lexical_element::COMMENT, // identifier_map, line_count, char_count, verbose); } else { parse_match_result(buffer, re_match, lexical_element_vector, e, lexical_element::OPERATOR, identifier_map, excep, verbose, parsed_line_count, parsed_char_count, include_comments); } } else if (RE2::PartialMatch(buffer, PUNCTUATOR_REGEX, &re_match)) { parse_match_result(buffer, re_match, lexical_element_vector, e, lexical_element::PUNCTUATOR, identifier_map, excep, verbose, parsed_line_count, parsed_char_count, include_comments); } else if (RE2::PartialMatch(buffer, PREPROCESSING_NUMBER_REGEX, &re_match)) { parse_match_result(buffer, re_match, lexical_element_vector, e, lexical_element::PREPROESSING_NUMBER, identifier_map, excep, verbose, parsed_line_count, parsed_char_count, include_comments); } else if (RE2::PartialMatch(buffer, UNKNOWN_REGEX, &re_match)) { // This category should belong to preprocessing-token parse_match_result(buffer, re_match, lexical_element_vector, e, lexical_element::UNKNOWN, identifier_map, excep, verbose, parsed_line_count, parsed_char_count, include_comments); } else if (!input_stream) { break; } } } if (verbose) { std::cout << __FILE__ << ":" << __LINE__ << " line_count:" << parsed_line_count << std::endl; std::cout << __FILE__ << ":" << __LINE__ << " char_count:" << parsed_char_count << std::endl; std::cout << __FILE__ << ":" << __LINE__ << " automate_state:" << automata_state << std::endl; } } while (input_stream || buffer.length()); // if (buffer.length()) { // std::cout << "Parse exception at " << line_count << ":" << char_count << // std::endl; // std::cout << buffer << // std::endl; // } parse_result.set_lexical_element_vector(lexical_element_vector); parse_result.set_exception_occur(!buffer.empty()); parse_result.set_total_lines(total_line_count); parse_result.set_total_chars(total_char_count); parse_result.set_exception_line(parsed_line_count); parse_result.set_exception_char_index(parsed_char_count); return parse_result; } void output_lexical_element_vector_to_output_stream(const std::vector<lexical_element> &v, std::ostream &stream) { stream << to_string(v); } void output_lexical_parse_result_to_output_stream(const lexical_parse_result &v, std::ostream &stream) { if (v.is_exception_occur()) { stream << "Parse exception at " << v.get_exception_line() << ":" << v.get_exception_char_index() << std::endl; } else { output_lexical_element_vector_to_output_stream(v.get_lexical_element_vector(), stream); } } const std::vector<lexical_element> &lexical_parse_result::get_lexical_element_vector() const { return lexical_element_vector; } lexical_parse_result & lexical_parse_result::set_lexical_element_vector(const std::vector<lexical_element> &lexical_element_vector) { lexical_parse_result::lexical_element_vector = lexical_element_vector; return *this; } bool lexical_parse_result::is_exception_occur() const { return exception_occur; } lexical_parse_result &lexical_parse_result::set_exception_occur(bool exception_occur) { lexical_parse_result::exception_occur = exception_occur; return *this; } long lexical_parse_result::get_exception_line() const { return exception_line; } lexical_parse_result &lexical_parse_result::set_exception_line(long exception_line) { lexical_parse_result::exception_line = exception_line; return *this; } long lexical_parse_result::get_exception_char_index() const { return exception_char_index; } lexical_parse_result &lexical_parse_result::set_exception_char_index(long exception_char_index) { lexical_parse_result::exception_char_index = exception_char_index; return *this; } long lexical_parse_result::get_total_lines() const { return total_lines; } lexical_parse_result &lexical_parse_result::set_total_lines(long total_lines) { lexical_parse_result::total_lines = total_lines; return *this; } long lexical_parse_result::get_total_chars() const { return total_chars; } lexical_parse_result &lexical_parse_result::set_total_chars(long total_chars) { lexical_parse_result::total_chars = total_chars; return *this; } lexical_parse_result::lexical_parse_result(const std::vector<lexical_element> &lexical_element_vector, bool exception_occur, long exception_line, long exception_char_index, long total_lines, long total_chars) : lexical_element_vector( lexical_element_vector), exception_occur(exception_occur), exception_line(exception_line), exception_char_index( exception_char_index), total_lines(total_lines), total_chars(total_chars) {} lexical_parse_result::lexical_parse_result() : lexical_element_vector( {}), exception_occur(false), exception_line(-1), exception_char_index(-1), total_lines(-1), total_chars(-1) {} } }
62cbf6e9fff79ca63db4fa5e563ca6320d654789
d9d50a557bec92763ffceb8dc5622e2a5a828077
/src/Parameters.h
dbea2f1752f4e264faec582b15b6716a974aad6d
[ "MIT" ]
permissive
skerit/Node-OpenMAX
77082f070aa483566891a385f45ad3d9ad542463
cd7120a478a941360ea0d305a13d8009c6550310
refs/heads/master
2021-01-19T13:19:48.590323
2016-09-17T18:34:03
2016-09-17T18:34:03
82,385,496
0
0
MIT
2020-05-01T07:20:22
2017-02-18T12:33:25
C++
UTF-8
C++
false
false
1,619
h
Parameters.h
#pragma once #include <nan.h> #include "bcm_host.h" #include "IL/OMX_Broadcom.h" #include "IL/OMX_ILCS.h" #include "IL/OMX_Types.h" #include "OMX_consts.h" class Parameters { public: static v8::Local<v8::Object> GetParameter(OMX_HANDLETYPE *handle, int port, OMX_INDEXTYPE nParamIndex); static void SetParameter(OMX_HANDLETYPE *handle, int port, OMX_INDEXTYPE nParamIndex, v8::Local<v8::Object> param); private: template<class T> static inline void GetParameter(OMX_HANDLETYPE *handle, OMX_INDEXTYPE nParamIndex, T *format) { OMX_ERRORTYPE rc = OMX_GetParameter(*handle, nParamIndex, format); if (rc != OMX_ErrorNone) { char buf[255]; sprintf(buf, "getParameter() returned error: %s", OMX_consts::err2str(rc)); Nan::ThrowError(buf); return; } } template<class T> static void GetParameterTemplate(T *format, OMX_HANDLETYPE *handle, OMX_INDEXTYPE nParamIndex) { OMX_consts::InitOMXParams(format); GetParameter<T>(handle, nParamIndex, format); } template<class T> static void GetParameterTemplate(T *format, int port, OMX_HANDLETYPE *handle, OMX_INDEXTYPE nParamIndex) { OMX_consts::InitOMXParams(format, port); GetParameter<T>(handle, nParamIndex, format); } template<class T> static void SetParameterTemplate(T *format, OMX_HANDLETYPE *handle, OMX_INDEXTYPE nParamIndex) { OMX_ERRORTYPE rc = OMX_SetParameter(*handle, nParamIndex, format); if (rc != OMX_ErrorNone) { char buf[255]; sprintf(buf, "setParameter() returned error: %s", OMX_consts::err2str(rc)); Nan::ThrowError(buf); return; } } };
59101dc041c9237f36d5b1c13ce4a70ed85e2189
5918a09f1d8d36286662f55a05f1f239fc4c6040
/sparta/sparta/report/format/CSV.hpp
4e3a47f1bff9312c10385af7c258f4ca0abeed1b
[ "Apache-2.0" ]
permissive
sparcians/map
ad10249cc2f33ae660ca2f54fc710c379f3977bd
c2d5db768967ba604c4747ec5e172ff78de95e47
refs/heads/master
2023-09-01T17:56:53.978492
2023-08-28T21:40:12
2023-08-28T21:40:12
227,639,638
107
40
Apache-2.0
2023-09-06T01:17:39
2019-12-12T15:37:36
C++
UTF-8
C++
false
false
10,061
hpp
CSV.hpp
// <CSV> -*- C++ -*- /*! * \file CSV.hpp * \brief CSV Report output formatter */ #pragma once #include <iostream> #include <sstream> #include <math.h> #include "sparta/report/format/BaseOstreamFormatter.hpp" #include "sparta/report/format/ReportHeader.hpp" #include "sparta/utils/SpartaException.hpp" #include "sparta/utils/SpartaAssert.hpp" namespace sparta { namespace report { namespace format { /*! * \brief Report formatter for CSV output * \note Non-Copyable */ class CSV : public BaseOstreamFormatter { public: /*! * \brief Constructor * \param r Report to provide output formatting for * \param output Ostream to write to when write() is called */ CSV(const Report* r, std::ostream& output) : BaseOstreamFormatter(r, output) { } /*! * \brief Constructor * \param r Report to provide output formatting for * \param filename File which will be opened and appended to when write() is * called * \param mode. Optional open mode. Should be std::ios::out or * std::ios::app. Other values cause undefined behavior */ CSV(const Report* r, const std::string& filename, std::ios::openmode mode=std::ios::app) : BaseOstreamFormatter(r, filename, mode) { } /*! * \brief Constructor * \param r Report to provide output formatting for */ CSV(const Report* r) : BaseOstreamFormatter(r) { } /*! * \brief Virtual Destructor */ virtual ~CSV() { } /*! * \brief Override from BaseFormatter */ virtual bool supportsUpdate() const override { return true; } protected: //! \name Output //! @{ //////////////////////////////////////////////////////////////////////// /*! * \brief Writes a header to some output based on the report */ virtual void writeHeaderToStream_(std::ostream& out) const override { writeCSVHeader_(out, report_); } /*! * \brief Writes the content of this report to some output */ virtual void writeContentToStream_(std::ostream& out) const override { writeRow_(out, report_); } /*! * \brief Writes updated information to the stream * \param out Stream to which output data will be written */ virtual void updateToStream_(std::ostream& out) const override { writeRow_(out, report_); } /*! * \brief Writes out a special 'Skipped' message to the CSV file (exact message * will depend on how the SkippedAnnotator subclass wants to annotate this gap * in the report) */ virtual void skipOverStream_(std::ostream& out, const sparta::trigger::SkippedAnnotatorBase * annotator) const override { skipRows_(out, annotator, report_); } //////////////////////////////////////////////////////////////////////// //! @} /*! * \brief Write formatted csv for the report to the output */ void dump_(std::ostream& out, const Report* r) const { writeCSVHeader_(out, r); writeRow_(out, r); } /*! * \brief Write a header line to the report */ void writeCSVHeader_(std::ostream& out, const Report* r) const { out << "# report=\"" << r->getName() << "\",start=" << r->getStart() << ",end="; if (r->getEnd() == Scheduler::INDEFINITE) { out << "SIMULATION_END"; } else { out << r->getEnd(); } if (!metadata_kv_pairs_.empty()) { //Combine metadata key-value map into a single comma- //separated string to be added to the header row of //the CSV report file. out << "," << stringizeRunMetadata_(); } out << '\n'; if (! r->getInfoString().empty()) { out << "# " << r->getInfoString() << "\n"; } if (r->hasHeader()) { auto & header = r->getHeader(); header.attachToStream(out); header.writeHeaderToStreams(); } const bool preceded_by_value = false; writeSubReportPartialHeader_(out, r, "", preceded_by_value); out << "\n"; } /*! * \brief Write a subreport header on the current row * \param[in] out Ostream to which output will be written * \param[in] r Report to print to \a out (recursively) * \param[in] prefix Prefix to prepend to any names written * \param[in] preceded_by_value Is this call preceded by a value on the same * line in \a out, thus requiring a leading comma? * \return Returns true if a value was written, false if not. */ bool writeSubReportPartialHeader_(std::ostream& out, const Report* r, const std::string& prefix, bool preceded_by_value) const { bool wrote_value = false; // Did this function write a value (this is the result of this function) auto itr = r->getStatistics().begin(); if (itr != r->getStatistics().end()) { while(1){ if(itr == r->getStatistics().begin() && preceded_by_value){ out << ","; // Insert comma following last data (which has no trailing comma) before the first value here. } const Report::stat_pair_t& si = *itr; if(si.first != ""){ // Print name = value out << prefix + si.first; }else{ // Print location = value out << prefix + si.second->getLocation(); } wrote_value = true; itr++; if(itr == r->getStatistics().end()){ break; } out << ","; } } else { // The previous subreport didn't have stats, but that // doesn't mean subsequent reports won't. They need to // know that a previous, previous report wrote a value wrote_value = preceded_by_value; } for(const Report& sr : r->getSubreports()){ const bool sr_wrote_value = writeSubReportPartialHeader_(out, &sr, sr.getName() + ".", wrote_value); wrote_value |= sr_wrote_value; } return wrote_value; } /*! * \brief Write a single row of data */ void writeRow_(std::ostream& out, const Report* r) const { const bool preceded_by_value = false; writeSubReportPartialRow_(out, r, preceded_by_value); out << "\n"; } /*! * \brief Writes out a special 'Skipped' message to the CSV file (exact message * will depend on how the SkippedAnnotator subclass wants to annotate this gap * in the report) */ void skipRows_(std::ostream& out, const sparta::trigger::SkippedAnnotatorBase * annotator, const Report* r) const; void getTotalNumStatsForReport_(const Report* r, uint32_t & total_num_stats) const { total_num_stats += r->getStatistics().size(); for (const Report & sr : r->getSubreports()) { getTotalNumStatsForReport_(&sr, total_num_stats); } }; /*! * \brief Write a subreport on the current row * \param[in] out Ostream to which output will be written * \param[in] r Report to print to \a out (recursively) * \param[in] preceded_by_value Is this call preceded by a value on the same * line in \a out, thus requiring a leading comma? * \return Returns true if a value was written, false if not. */ bool writeSubReportPartialRow_(std::ostream& out, const Report* r, bool preceded_by_value) const { bool wrote_value = false; // Did this function write a value (this is the result of this function) auto itr = r->getStatistics().begin(); if (itr != r->getStatistics().end()) { while(1){ if(itr == r->getStatistics().begin() && preceded_by_value){ out << ","; // Insert comma following last data (which has no trailing comma) before the first value here. } // Print the value const Report::stat_pair_t& si = *itr; out << Report::formatNumber(si.second->getValue()); wrote_value = true; // 1 or more values written here itr++; if(itr == r->getStatistics().end()){ break; } out << ","; } } else { // The previous subreport didn't have stats, but that // doesn't mean subsequent reports won't. They need to // know that a previous, previous report wrote a value wrote_value = preceded_by_value; } for (const Report& sr : r->getSubreports()){ const bool sr_wrote_value = writeSubReportPartialRow_(out, &sr, wrote_value); wrote_value |= sr_wrote_value; } return wrote_value; } /*! * \brief Combine metadata key-value map into a single * comma-separated string. */ std::string stringizeRunMetadata_() const { if (metadata_kv_pairs_.empty()) { return ""; } std::ostringstream oss; for (const auto & md : metadata_kv_pairs_) { oss << md.first << "=" << md.second << ","; } std::string stringized = oss.str(); stringized.pop_back(); return stringized; } }; //! \brief CSV stream operator inline std::ostream& operator<< (std::ostream& out, CSV & f) { out << &f; return out; } } // namespace format } // namespace report } // namespace sparta
3d8d80b6e64b490cf792593478aa86eff59315fd
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5670465267826688_0/C++/Progbeat/C.cpp
1841f401b39c58dfe993c1442bd164e940bed04d
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,570
cpp
C.cpp
#include <bits/stdc++.h> #define UN(v) sort(all(v)), (v).erase(unique(all(v)), (v).end()) #define FOR(i, a, b) for (int i(a), _B_##i(b); i < _B_##i; ++i) #define CL(a, b) memset(a, b, sizeof a) #define all(a) (a).begin(), (a).end() #define REP(i, n) FOR(i, 0, n) #define sz(a) int((a).size()) #define long int64_t #define pb push_back #define Y second #define X first #ifndef LOCAL #define NDEBUG #endif using namespace std; typedef pair<int, int> pii; int adj[4][4] = { {0, 1, 2, 3}, {1, ~0, 3, ~2}, {2, ~3, ~0, 1}, {3, 2, ~1, ~0} }; int f(int x, int y) { int sign = (x ^ y) >> 31; assert(sign == 0 || sign == ~0); return adj[x ^ (x >> 31)][y ^ (y >> 31)] ^ sign; } int main() { int tests, tc; for (cin >> tests; tc++ < tests; ) { int n, times; string w; cin >> n >> times >> w; assert(sz(w) == n); // if (times >= 64) // times = 64 + (times % 64); string s; REP (k, times) s += w; int state = 0, p = 0; for (char c : s) { int x; switch (c) { case 'i': x = 1; break; case 'j': x = 2; break; case 'k': x = 3; break; default: assert(false); } p = f(p, x); if (p == state + 1) { ++state; p = 0; } } printf("Case #%d: %s\n", tc, p == 0 && state == 3 ? "YES" : "NO"); } return 0; }
1ce0f684f48c43e9e7aad72b1f3b28094b66da9a
a86e02e2d77ec6ab4a7da09df0262b363690b55e
/Inheritance(Extending Classes)/eg8_8.cpp
91f384b37bfefddc993ab40a6e7c9c112dc727bc
[]
no_license
rajaniket/Cpp_programs
59e20ef7c0918b0dfad1ed9468a479c49bd7ccc0
6528a5bff5c58dd734d46cf8a6aa5363b90219d9
refs/heads/master
2021-06-18T11:19:51.830199
2021-06-08T17:26:59
2021-06-08T17:26:59
215,588,831
5
0
null
2020-01-04T18:15:40
2019-10-16T16:00:09
C++
UTF-8
C++
false
false
1,171
cpp
eg8_8.cpp
//initialization list in constructors #include<iostream> using namespace std; class alpha{ protected: int x,q; // x will initialized first then q will be (initialization list) public: alpha(int c):x(c),q(2*x){ // alpha(int c):q(2),x(q) , will be wrong because x will be initialize first then q will initialize as per // deceleration in data segment cout<<"alpha initialized"<<endl; } void show(){ cout<<"X="<<x<<endl; cout<<"Q="<<q<<endl; } }; class beta{ protected: int y,w; public: beta(int c):y(3*c),w(c+y){ // initializing y and w cout<<"beta initialized"<<endl; } void show(){ cout<<"Y="<<y<<endl; cout<<"W="<<w<<endl;} }; class gamma:public beta,public alpha{ protected: int z,e; public: gamma(int a,int b,int c):alpha(a),beta(b),z(x*4) { e=c; cout<<"gamma initialized"<<endl; } void show(){ alpha::show(); beta::show(); cout<<"Z="<<z<<endl; cout<<"E="<<e<<endl;} }; int main(){ gamma kk(1,2,3); kk.show(); }
d6a8dd4576cca561820bf31c37cde046ebba1c0d
f92db40e105623caba96a33582ab53c333676cde
/src/sina/sinaweibo.h
a2c63f6bb2280d7a54c81273e292d50578ee4558
[]
no_license
xiongwang/USense
383870e224d521f7cb88afc9b2b1332f3ba6042c
1b9a06ca337d036f1e092450ed1d4f9fcd1f1573
refs/heads/master
2021-01-01T05:47:53.200207
2013-02-09T20:24:32
2013-02-09T20:24:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,794
h
sinaweibo.h
#ifndef SINAWEIBO_H #define SINAWEIBO_H #include <QObject> #include <QIcon> #include <QtNetwork> #include "account.h" #include "sinaparserxml.h" #include "sinaservices.h" #include "status.h" #include "configuration.h" #include "oauth.h" #include <src/mynetworkcookiejar.h> /*! \class SinaWeibo * \brief 微博信息处理与显示 * * */ class SinaWeibo : public QObject { Q_OBJECT public: SinaWeibo(Account* account); ~SinaWeibo(); bool verifyCredentials(); QIcon getProfileIcon(const QString &urlString); enum DMType{ List = 1, Session = 2 }; public: QString getFriendsTimeline( qint64 sinceId=0, qint64 maxId=0, int count=20, \ int page=1, int baseApp=0, int feature=0); QString getMentions(qint64 sinceId=0, qint64 maxId=0, int count=20, int page=1); QString getUserTimeline(QString userId="0", int count=20, int page=1, int baseApp=0, int feature=0 ); QString getUserTimelineByScreenName(QString screenName, int count=20, int page=1, int baseApp=0, int feature=0); QString getFavorites(int page=1); QString getCommentTimeline(qint64 sinceId=0, qint64 maxId=0, int count=20, int page=1); QString getDirectMessage(qint64 sinceId=0, qint64 maxId=0, int count=20, int page=1); QString getSendDirectMessage(qint64 sinceId=0, qint64 maxId=0, int count=20, int page=1); QString getEmotions(); QString getUnread(QString sinceId); QString getStatusCountsByJson(QList<Status> &statusList); QString statusTextFormat(QString statusText); QString timeFormatHtml(QDateTime datetime); QString getCommentsList(QString id, int page=1, int count=20); QString getPublicStatus(int count=20); QString getDailyTrends(); QString getFollowers(QString); QString getFriends(QString); QString getSingleStatus(QString); QString getSquareHtml(); QString getLongUrl(const QList<QString>& shortUrlList); QString getImgAndVedioHtml(const Status& status); void getDMSessionStatus(QList<Status> &statusList,QString senderId); void setCommentsAndRetweetNum(QList<Status> &statusList); void setVedioPic(QList<Status> &statusList); void setVedioPic(QMap<QString,Status> &retwStatusMap); bool getSinaAccountByID(Account &account,QString id); static bool compareDateTime(const Status &statusOne,const Status &statusTwo); public: QString homePageStatusToHtml(QList<Status> &statusList, QMap<QString,Status> &retwStatusMap); QString atMePageStatusToHtml(QList<Status> &statusList, QMap<QString,Status> &retwStatusMap); QString userWeiboPageStatusToHtml(QList<Status> &statusList, QMap<QString,Status> &retwStatusMap); QString favoritePageStatusToHtml(QList<Status> &statusList, QMap<QString,Status> &retwStatusMap); QString commentPageStatusToHtml(QList<Status> &statusList, QMap<QString,Status> &retwStatusMap); QString directMessagePageStatusToHtml(QList<Status> &statusList,DMType dmType); QString commentsListToHtml(QList<Status> &statusList); QString statusToHtmlForNotifier(Status &status, Status &retwStatus); QString statusToHtmlForNotifier(Status &status); QString FriendsAndFollowersToHtml(QList<Account>&); QString othersCommentsToHtml(QList<Status>&); QString dailyTrendsToHtml(QStringList& nameList,QStringList& queryList); void initHomePageStatus(); void initAtMePageStatus(); void initUserWeiboPageStatus(); void initFavoritePageStatus(); void initCommentPageStatus(); void initDirectMessagePageStatus(); void initPublicStatus(); void initEmotions(); int sendStatusWithoutPicture(QString statusContent); int sendStatusWithPicture(QString statusContent, QByteArray pictureInByteArray, QString fileName); int repost(QString id, QString status); int commentStatus(QString id, QString status); int addFavorite(QString id); int deleteFavorite(QString id); int deleteStatus(QString id); void getUnreadInfo(int &statusUnread, int &atMeMentionsUnread, int &commentsUnread, int &directMessageUnread, int &newFollower); int resetCount(int type); int replyComment(QString cid, QString id, QString statusText); int sendDirectMessage(QString uid, QString statusText); public: QString contentFrame; signals: public slots: private: Account *account; SinaServices *servicesInstance; QString basicAuthInfo; Configuration *conf; /* QString contentFrame; */ QString everyStatusHtml; QString retwStatusHtml; private: void setBasicAuth(QNetworkRequest &request); void setOAuthAuthorize( QNetworkRequest &request, OAuth::HttpMethod httpMethod, QString url, QMap<QString,QString> &params); }; #endif // SINAWEIBO_H
3ac542e7ce93427f3a8d1424c31daf5c9bb11dd6
1bdec5db3dc305b8c668ea789aeb289799856056
/Ch12/ex12.30.cpp
53eae0c9983cdd483a37f74293673046cb85759e
[]
no_license
fanqo/CppPrimer
e0fee2346f6c0bd78623421e6dc9926e79cfcddd
525205160b0a0a43932d7789e9c77b05f558a299
refs/heads/master
2021-02-27T04:58:05.981272
2020-03-07T07:22:06
2020-03-07T07:22:06
245,581,412
0
0
null
null
null
null
UTF-8
C++
false
false
529
cpp
ex12.30.cpp
#include <iostream> using std::cout; using std::endl; using std::cin; #include <fstream> using std::ifstream; #include <string> using std::string; #include "TextQuery.h" void runQueries(ifstream &infile) { TextQuery tq(infile); while (true) { cout << "enter word to look for, or q to quit: "; string s; if (!(cin >> s) || s == "q") break; print(cout, tq.query(s)) << endl; } } int main(int argc, char **argv) { ifstream input(argv[1]); runQueries(input); return 0; }
1807fdb4fca047413b883c5888aa951704f106d8
d4ab2fac1673f0de7c1bc5a1ea643959c1123a44
/multi-run/prepare/prepare1.cpp
6bfd059a3199987ccc636e218a5ce6fef8043835
[]
no_license
teoionescu/mini-judge
667c06503b4c75841222f5be57868575e806a9d0
f68fed2c29edaac19afd20de16bbe284b3015fe9
refs/heads/master
2021-01-25T06:56:34.022627
2018-04-10T22:13:16
2018-04-10T22:13:16
93,631,335
0
0
null
null
null
null
UTF-8
C++
false
false
595
cpp
prepare1.cpp
#include <cstdio> using namespace std; #define maxn 10000010 int n, m, k, lim; FILE *in, *out, *in2; char s[maxn]; int main() { in = fopen("op.in", "r"); out = fopen("op.out.0", "r"); in2 = fopen("op.in.1", "w"); fscanf(in, "%d%d%d%d", &k, &n, &m, &lim); fscanf(out, "%s", s); fprintf(in2, "2 %d %d %d\n", k, n, m); fprintf(in2, "%s\n", s); for(int i = 0; i < n; ++i) { int x; fscanf(in, "%d", &x); } for(int i = 0; i < m; ++i) { int x; fscanf(in, "%d", &x); fprintf(in2, "%d\n", x); } return 0; }
685b7e9b5d0c96a49641ece17273e0a4838e29e5
95b6f1d2fd32936eb6df3b2fb0b59647da39c6df
/Card Game (L5R)/Holding.cpp
1a201354f89163a2489496384df9f2a01e80330e
[]
no_license
IliasBarmpar/Object-Oriented-Programming-uni-course
b10f0ea6695844a5d5f806624b3bdc1aab6c83e3
a34445e491f3cfe470d0c2595329f413b432c2d1
refs/heads/master
2022-04-06T10:22:26.749214
2020-02-18T13:52:17
2020-02-18T13:52:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,083
cpp
Holding.cpp
#include "Holding.hpp" Plain :: Plain(string n){ name = n; int stats[2]; readStats("Personalities_and_Holdings.txt", "PLAIN:", 2, stats); cost = stats[0]; harvestValue = stats[1]; } Mine :: Mine(string n){ name = n; upperHolding = NULL; int stats[2]; readStats("Personalities_and_Holdings.txt", "MINE:", 2, stats); cost = stats[0]; harvestValue = stats[1]; } int Mine :: getHarvestValue(){ if(upperHolding) return harvestValue+2; else return harvestValue; } GoldMine :: GoldMine(string n){ name = n; upperHolding = NULL; subHolding = NULL; int stats[2]; readStats("Personalities_and_Holdings.txt", "GOLD_MINE:", 2, stats); cost = stats[0]; harvestValue = stats[1]; } int GoldMine :: getHarvestValue(){ if(upperHolding && subHolding) return harvestValue*3; else if(subHolding) return harvestValue+4; else if(upperHolding) return harvestValue+5; else return harvestValue; } bool GoldMine :: chainComplete(){ if(subHolding && upperHolding) return true; else return false; } CrystalMine :: CrystalMine(string n){ name = n; subHolding = NULL; int stats[2]; readStats("Personalities_and_Holdings.txt", "CRYSTAL_MINE:", 2, stats); cost = stats[0]; harvestValue = stats[1]; } int CrystalMine :: getHarvestValue(){ if(subHolding){ if(subHolding->chainComplete()) return harvestValue*4; return harvestValue*2; } return harvestValue; } Farmland :: Farmland(string n){ name = n; int stats[2]; readStats("Personalities_and_Holdings.txt", "FARMS:", 2, stats); cost = stats[0]; harvestValue = stats[1]; } GiftsandFavour :: GiftsandFavour(string n){ name = n; int stats[2]; readStats("Personalities_and_Holdings.txt", "SOLO:", 2, stats); cost = stats[0]; harvestValue = stats[1]; } StrongHold :: StrongHold(string n){ name = n; isRevealed = true; int stats[3]; readStats("Personalities_and_Holdings.txt", "STRONGHOLD:", 3, stats); startingHonour = stats[0]; harvestValue = stats[1]; initialDefence = stats[2]; } /* int main(){ // Holding *bcard; // // bcard = new Plain("Footsoldier"); // bcard->print(); // bcard = new Mine("Footsoldier"); // bcard->print(); // bcard = new GoldMine("Footsoldier"); // bcard->print(); // bcard = new CrystalMine("Footsoldier"); // bcard->print(); // bcard = new Farmland("Footsoldier"); // bcard->print(); // bcard = new GiftsandFavour("Footsoldier"); // bcard->print(); // bcard = new StrongHold("StrongHold"); // bcard->print(); BlackCard *card1, *card2, *card3 ,*card4; card1 = new Mine("Mine"); card2 = new GoldMine("GoldMine"); card3 = new CrystalMine("CrystalMine"); card4 = new Farmland("FarmL"); card1->setUpperHolding(card2); card2->setSubHolding(card1); Holdings card2->setUpperHolding(card3); card3->setSubHolding(card2); card1->print(); card2->print(); card3->print(); // cout << card1->getHarvestValue() << " "<< card2->getHarvestValue() << " "<< card3->getHarvestValue() << endl; int i; }*/
442c88860959c142b8aea9dff2e68ac2b28001c0
40d371136f2d7de9c95bfe40fd3c0437095e9819
/devel/include/api_msgs/GetMapFile.h
d943a5c7959c9ed404d6a09ddee012a8e9373bd3
[]
no_license
marine0131/ros_ws
b4e6c5cf317260eaae1c406fb3ee234b3a3e67d5
6ddded3a92a717879bb646e7f2df1fea1a2d46b2
refs/heads/master
2021-07-05T06:29:43.054275
2017-09-28T08:29:14
2017-09-28T08:29:14
100,458,679
1
0
null
null
null
null
UTF-8
C++
false
false
2,607
h
GetMapFile.h
// Generated by gencpp from file api_msgs/GetMapFile.msg // DO NOT EDIT! #ifndef API_MSGS_MESSAGE_GETMAPFILE_H #define API_MSGS_MESSAGE_GETMAPFILE_H #include <ros/service_traits.h> #include <api_msgs/GetMapFileRequest.h> #include <api_msgs/GetMapFileResponse.h> namespace api_msgs { struct GetMapFile { typedef GetMapFileRequest Request; typedef GetMapFileResponse Response; Request request; Response response; typedef Request RequestType; typedef Response ResponseType; }; // struct GetMapFile } // namespace api_msgs namespace ros { namespace service_traits { template<> struct MD5Sum< ::api_msgs::GetMapFile > { static const char* value() { return "2baa25a9186e1f428009e476983334ce"; } static const char* value(const ::api_msgs::GetMapFile&) { return value(); } }; template<> struct DataType< ::api_msgs::GetMapFile > { static const char* value() { return "api_msgs/GetMapFile"; } static const char* value(const ::api_msgs::GetMapFile&) { return value(); } }; // service_traits::MD5Sum< ::api_msgs::GetMapFileRequest> should match // service_traits::MD5Sum< ::api_msgs::GetMapFile > template<> struct MD5Sum< ::api_msgs::GetMapFileRequest> { static const char* value() { return MD5Sum< ::api_msgs::GetMapFile >::value(); } static const char* value(const ::api_msgs::GetMapFileRequest&) { return value(); } }; // service_traits::DataType< ::api_msgs::GetMapFileRequest> should match // service_traits::DataType< ::api_msgs::GetMapFile > template<> struct DataType< ::api_msgs::GetMapFileRequest> { static const char* value() { return DataType< ::api_msgs::GetMapFile >::value(); } static const char* value(const ::api_msgs::GetMapFileRequest&) { return value(); } }; // service_traits::MD5Sum< ::api_msgs::GetMapFileResponse> should match // service_traits::MD5Sum< ::api_msgs::GetMapFile > template<> struct MD5Sum< ::api_msgs::GetMapFileResponse> { static const char* value() { return MD5Sum< ::api_msgs::GetMapFile >::value(); } static const char* value(const ::api_msgs::GetMapFileResponse&) { return value(); } }; // service_traits::DataType< ::api_msgs::GetMapFileResponse> should match // service_traits::DataType< ::api_msgs::GetMapFile > template<> struct DataType< ::api_msgs::GetMapFileResponse> { static const char* value() { return DataType< ::api_msgs::GetMapFile >::value(); } static const char* value(const ::api_msgs::GetMapFileResponse&) { return value(); } }; } // namespace service_traits } // namespace ros #endif // API_MSGS_MESSAGE_GETMAPFILE_H
56c30d0cda12dca69726e8bfd4945d0f8fbc714d
473fc28d466ddbe9758ca49c7d4fb42e7d82586e
/app/src/main/java/com/syd/source/aosp/sdk/find_java2/src/FindJava2Dlg.cpp
a9c815319da8a78012955778451be5c520f59b14
[]
no_license
lz-purple/Source
a7788070623f2965a8caa3264778f48d17372bab
e2745b756317aac3c7a27a4c10bdfe0921a82a1c
refs/heads/master
2020-12-23T17:03:12.412572
2020-01-31T01:54:37
2020-01-31T01:54:37
237,205,127
4
2
null
null
null
null
UTF-8
C++
false
false
9,044
cpp
FindJava2Dlg.cpp
/* * Copyright (C) 2014 The Android Open Source Project * * 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 "stdafx.h" #include "utils.h" #include "FindJava2Dlg.h" #include "afxdialogex.h" #include <atlpath.h> // ATL CPath #ifdef _DEBUG #define new DEBUG_NEW #endif #define COL_PATH 1 CFindJava2Dlg::CFindJava2Dlg(CWnd* pParent /*=NULL*/) : CDialog(CFindJava2Dlg::IDD, pParent), mSelectedIndex(-1) { m_hIcon = AfxGetApp()->LoadIcon(IDI_ANDROID_ICON); } void CFindJava2Dlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_PATH_LIST, mPathsListCtrl); DDX_Control(pDX, IDOK, mOkButton); } BEGIN_MESSAGE_MAP(CFindJava2Dlg, CDialog) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON_ADD, &CFindJava2Dlg::OnBnClickedButtonAdd) ON_NOTIFY(NM_CLICK, IDC_PATH_LIST, &CFindJava2Dlg::OnNMClickPathList) ON_NOTIFY(LVN_ITEMCHANGED, IDC_PATH_LIST, &CFindJava2Dlg::OnLvnItemchangedPathList) END_MESSAGE_MAP() // ----- // CFindJava2Dlg message handlers BOOL CFindJava2Dlg::OnInitDialog() { CDialog::OnInitDialog(); SetWindowText(getAppName()); // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // Initialize list controls mPathsListCtrl.SetExtendedStyle( mPathsListCtrl.GetExtendedStyle() | LVS_EX_CHECKBOXES | LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES); // We want 2 columns: Java version and path mPathsListCtrl.InsertColumn(0, _T("Version"), LVCFMT_RIGHT, 60, 0); mPathsListCtrl.InsertColumn(1, _T("Path"), LVCFMT_LEFT, 386, 0); mJavaFinder->findJavaPaths(&mPaths); fillPathsList(); adjustButtons(); return TRUE; // return TRUE unless you set the focus to a control } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. // [Note: MFC boilerplate, keep as-is] void CFindJava2Dlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. [Note: MFC boilerplate, keep as-is] HCURSOR CFindJava2Dlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } // Button add has been pressed; use file dialog and add path if it's a valid java.exe void CFindJava2Dlg::OnBnClickedButtonAdd() { CFileDialog fileDlg( TRUE, // true=open dialog, false=save-as dialog _T("exe"), // lpszDefExt _T("java.exe"), // lpszFileName OFN_FILEMUSTEXIST || OFN_PATHMUSTEXIST, NULL, // lpszFilter this); // pParentWnd if (fileDlg.DoModal() == IDOK) { CString path = fileDlg.GetPathName(); CJavaPath javaPath; if (!mJavaFinder->checkJavaPath(path, &javaPath)) { CString msg; if (javaPath.mVersion > 0) { msg.Format(_T("Insufficient Java Version found: expected %s, got %s"), CJavaPath(mJavaFinder->getMinVersion(), CPath()).getVersion(), javaPath.getVersion()); } else { msg.Format(_T("No valid Java Version found for %s"), path); } AfxMessageBox(msg, MB_OK); } else { if (mPaths.find(javaPath) == mPaths.end()) { // Path isn't known yet so add it and refresh the list. mPaths.insert(javaPath); fillPathsList(); } // Select item in list and set mSelectedIndex selectPath(-1 /*index*/, &javaPath); } } } // An item in the list has been selected, select checkmark and set mSelectedIndex. void CFindJava2Dlg::OnNMClickPathList(NMHDR *pNMHDR, LRESULT *pResult) { LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR); int index = pNMItemActivate->iItem; selectPath(index, nullptr); *pResult = TRUE; } // An item in the list has changed, toggle checkmark as needed. void CFindJava2Dlg::OnLvnItemchangedPathList(NMHDR *pNMHDR, LRESULT *pResult) { *pResult = FALSE; LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR); if ((pNMLV->uChanged & LVIF_STATE) != 0) { // Item's state has changed. Check the selection to see if it needs to be adjusted. int index = pNMLV->iItem; UINT oldState = pNMLV->uOldState; UINT newState = pNMLV->uNewState; if ((oldState & LVIS_STATEIMAGEMASK) != 0 || (newState & LVIS_STATEIMAGEMASK) != 0) { // Checkbox uses the STATEIMAGE: 1 for unchecked, 2 for checked. // Checkbox is checked when (old/new-state & state-image-mask) == INDEXTOSTATEIMAGEMASK(2). bool oldChecked = (oldState & LVIS_STATEIMAGEMASK) == INDEXTOSTATEIMAGEMASK(2); bool newChecked = (newState & LVIS_STATEIMAGEMASK) == INDEXTOSTATEIMAGEMASK(2); if (oldChecked && !newChecked && index == mSelectedIndex) { mSelectedIndex = -1; adjustButtons(); } else if (!oldChecked && newChecked && index != mSelectedIndex) { // Uncheck any checked rows if any for (int n = mPathsListCtrl.GetItemCount() - 1; n >= 0; --n) { if (n != index && mPathsListCtrl.GetCheck(n)) { mPathsListCtrl.SetCheck(n, FALSE); } } mSelectedIndex = index; adjustButtons(); } // We handled this case, don't dispatch it further *pResult = TRUE; } } } // ----- const CJavaPath& CFindJava2Dlg::getSelectedPath() { int i = 0; for (const CJavaPath &p : mPaths) { if (i == mSelectedIndex) { return p; } ++i; } return CJavaPath::sEmpty; } void CFindJava2Dlg::fillPathsList() { mPathsListCtrl.DeleteAllItems(); int index = 0; for (const CJavaPath& pv : mPaths) { mPathsListCtrl.InsertItem(index, pv.getVersion()); // column 0 = version mPathsListCtrl.SetItemText(index, COL_PATH, pv.mPath); // column 1 = path mPathsListCtrl.SetCheck(index, mSelectedIndex == index); ++index; } } // Checks the given index if valid. Unchecks all other items. // // If index >= 0, it is used to select that item from the ListControl. // Otherwise if path != nullptr, it is used to find the item and select it. // // Side effect: in both cases, mSelectedIndex is set to the matching index or -1. // // If index is invalid and path isn't in the mPaths list, all items are unselected // so calling this with (0, nullptr) will clear the current selection. void CFindJava2Dlg::selectPath(int index, const CJavaPath *path) { const CJavaPath *foundPath; // If index is not defined, find the given path in the internal list. // If path is not defined, find its index in the internal list. int i = 0; int n = mPathsListCtrl.GetItemCount(); for (const CJavaPath &p : mPaths) { if (index < 0 && path != nullptr && p == *path) { index = i; foundPath = path; } else if (index == i) { foundPath = &p; } // uncheck any marked path if (i != index && i < n && mPathsListCtrl.GetCheck(i)) { mPathsListCtrl.SetCheck(i, FALSE); } ++i; } mSelectedIndex = index; if (index >= 0 && index <= n) { mPathsListCtrl.SetCheck(index, TRUE); } adjustButtons(); } void CFindJava2Dlg::adjustButtons() { int n = mPathsListCtrl.GetItemCount(); mOkButton.EnableWindow(mSelectedIndex >= 0 && mSelectedIndex < n); }
dda728b5dc2e1278b6436aa90e55f8b16afbe88b
77861deda8b3046bdda221d3cb80b77e84b14523
/avx512-utf8-to-utf32/validate/avx512-validate-utf8.constants.cpp
0606923df000846b0fb60487368627c0a917647b
[ "BSD-2-Clause" ]
permissive
WojciechMula/toys
b73f09212ca19f1e76bbf2afaa5ad2efcea95175
6110b59de45dc1ce44388b21c6437eff49a7655c
refs/heads/master
2023-08-18T12:54:25.919406
2023-08-05T09:20:14
2023-08-05T09:20:14
14,905,115
302
44
BSD-2-Clause
2020-04-17T17:10:42
2013-12-03T20:35:37
C++
UTF-8
C++
false
false
589
cpp
avx512-validate-utf8.constants.cpp
namespace { const __m512i v_0f = _mm512_set1_epi8(0x0f); const __m512i v_10 = _mm512_set1_epi8(0x10); const __m512i v_40 = _mm512_set1_epi8(0x40); const __m512i v_80 = _mm512_set1_epi8(char(0x80)); const __m512i v_1f = _mm512_set1_epi8(0x1f); const __m512i v_3f = _mm512_set1_epi8(0x3f); const __m512i v_c0 = _mm512_set1_epi8(char(0xc0)); const __m512i v_c2 = _mm512_set1_epi8(char(0xc2)); const __m512i v_e0 = _mm512_set1_epi8(char(0xe0)); const __m512i v_f0 = _mm512_set1_epi8(char(0xf0)); const __m512i v_f8 = _mm512_set1_epi8(char(0xf8)); }
583de968c7ba6efbe9c5a3f00861cb575837cdad
16aa15ad6651c51d86a7d1459a7ea4aa1eaacfc2
/celula/src/Poisson.h
ef869cad1a1b44017c3c2ebf29983e6223df88ab
[]
no_license
MauricioA/membrana
15fe79d093a02d881b5789cfa90e8bf78ee1a8dc
7872e254baaabb11206e59c805876c39d89c743a
refs/heads/master
2021-01-23T12:22:24.036200
2015-05-12T20:50:59
2015-05-12T20:50:59
22,731,666
0
0
null
null
null
null
ISO-8859-13
C++
false
false
460
h
Poisson.h
#ifndef POISSON_H_ #define POISSON_H_ #include "Celula.h" //TODO no deberķa ser static! class Poisson { public: static int estado; static bool lastOff; static void iteracion(Celula& celula); private: static VectorXd global_rhs; static SparseMatrix<double> matriz; static void campo(Celula& celula); static void campo3(Celula& celula); static void campo4(Celula& celula); static void corriente(Celula& celula); }; #endif /* POISSON_H_ */
dfdcc661abd0cfe15def51dc32fabda1cb21c5b3
63bdee29ac1d4bb8fd425b75003a10fa98506b27
/lib/src/blas1/reduce-operators.h
6835000f972dbf75fada0790f05f1f9ab8422c99
[]
no_license
rocmarchive/HcSPARSE
ad273991409d9c24b6ed013ca5b4328988cdb90a
ddfe7da9c7b0a41ccf30fbc9eea6debcb1567df2
refs/heads/master
2021-10-24T04:37:43.079874
2019-03-21T22:41:45
2019-03-21T22:41:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,135
h
reduce-operators.h
#ifndef _REDUCE_OPERATORS_H_ #define _REDUCE_OPERATORS_H_ enum ReduceOperator { RO_PLUS = 0, RO_SQR, RO_SQRT, RO_FABS, RO_DUMMY //does nothing }; template <typename T> T plus (T a, T b) __attribute__((hc, cpu)) { return a + b; } template <typename T> T sqr (T a, T b) __attribute__((hc, cpu)) { return a + b * b; } template <typename T> T fabs (T a, T b) __attribute__((hc, cpu)) { return a + hc::precise_math::fabsf((float)b); } template <typename T> T sqr_root (T a) __attribute__((hc, cpu)) { return hc::precise_math::sqrtf((float)a); } template <typename T> T reduce_dummy (T a) __attribute__((hc, cpu)) { return a; } template <typename T, ReduceOperator OP> T reduceOperation (T a, T b) __attribute__((hc, cpu)) { if (OP == RO_PLUS) return plus<T>(a, b); else if (OP == RO_SQR) return sqr<T>(a, b); else if (OP == RO_FABS) return fabs<T>(a, b); } template <typename T, ReduceOperator OP> T reduceOperation (T a) __attribute__((hc, cpu)) { if (OP == RO_SQRT) return sqr_root<T>(a); else return reduce_dummy<T>(a); } #endif
b845c92c5974f7f8987cda534cb69b8e887723aa
4b538d7e26f795220312190d4f134c166bd769d6
/worldtimer.cpp
74b4ba653fbea618dea59c60bb1a4dd3e7210e2f
[]
no_license
neohung/neosoccer
bb659d595107adf1d5e103b5f75ff015a0b406e3
a2b1665f9ce2a7400802c76652236d0f4bb93bca
refs/heads/master
2021-01-25T10:05:49.647329
2015-07-17T09:54:51
2015-07-17T09:54:51
39,179,202
0
0
null
null
null
null
UTF-8
C++
false
false
2,247
cpp
worldtimer.cpp
#include "worldtimer.h" #include "stdio.h" WorldTimer::WorldTimer(): m_bSmoothUpdates(false) { //how many ticks per sec do we get //求出每秒的ticks數: m_PerfCountFreq QueryPerformanceFrequency( (LARGE_INTEGER*) &m_PerfCountFreq); m_TimeScale = 1.0/m_PerfCountFreq; //wprintf(L"m_FrameTime: %e\n",m_FrameTime); } WorldTimer::WorldTimer(double fps): m_NormalFPS(fps), m_bSmoothUpdates(false) { //how many ticks per sec do we get //求出每秒的ticks數: m_PerfCountFreq QueryPerformanceFrequency( (LARGE_INTEGER*) &m_PerfCountFreq); m_TimeScale = 1.0/m_PerfCountFreq; m_FrameTime = (LONGLONG)(m_PerfCountFreq / m_NormalFPS); //wprintf(L"m_FrameTime: %e\n",m_FrameTime); } //m_StartTime: 紀錄開始時的tick數 //m_LastTime: 紀錄上個frame時的tick數 //m_NextTime: 預估達到下個frame的tick數 void WorldTimer::Start() { m_bStarted = true; m_TimeElapsed = 0.0; //get the time QueryPerformanceCounter( (LARGE_INTEGER*) &m_LastTime); //keep a record of when the timer was started m_StartTime = m_LastTimeInTimeElapsed = m_LastTime; //update time to render next frame m_NextTime = m_LastTime + m_FrameTime; return; } //m_CurrentTime: 每次執行WorldTimer::TimeElapsed()得到的當前tick數 //m_LastTimeInTimeElapsed: 上次執行WorldTimer::TimeElapsed()得到的上次tick數 //m_LastTimeElapsed 上上次執行到上次執行中間經過的時間,單位秒 //m_TimeElapsed: 上次執行到這次執行中間經過的時間,單位秒 //m_TimeScale: 一個tick的時間長度,單位秒 double WorldTimer::TimeElapsed() { m_LastTimeElapsed = m_TimeElapsed; QueryPerformanceCounter( (LARGE_INTEGER*) &m_CurrentTime); m_TimeElapsed = (m_CurrentTime - m_LastTimeInTimeElapsed) * m_TimeScale; m_LastTimeInTimeElapsed = m_CurrentTime; //wprintf(L"m_TimeElapsed: %f\n",m_TimeElapsed); const double Smoothness = 5.0; if (m_bSmoothUpdates) { if (m_TimeElapsed < (m_LastTimeElapsed * Smoothness)) { return m_TimeElapsed; } else { //當m_TimeElapsed大時5倍的之前執行時間時,傳回0 return 0.0; } } else { return m_TimeElapsed; } }
6e49c4ee7f2a4306c7a7c3aff01e99b5ee9e5204
549729e902d3eb24112d88cc1428eb287c2107b8
/QuantFacialRecognition/tests/ConnectionFileReaderTest.cpp
50112e45d8861d8b8e78bee3ff3533257924b0e6
[]
no_license
u12206050/Andrologists2014
94ef039b70eb3e26753b7cfdbfdf5ede330ef8d3
9daa4e993ed8e9e28e1f02d342b0a38724499bee
refs/heads/master
2020-05-31T04:01:33.413553
2014-10-19T20:55:21
2014-10-19T20:55:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
814
cpp
ConnectionFileReaderTest.cpp
#include "ConnectionFileReaderTest.h" void ConnectionFileReaderTest::parseTest() { ConnectionFileReader reader(QString("../../testFiles/connectionTest.txt")); DatabaseConnection* connection = reader.getDatabaseConnection(); QString type = connection->getDatabase().driverName(); QString host = connection->getDatabase().hostName(); QString name = connection->getDatabase().databaseName(); QString username = connection->getDatabase().userName(); QString password = connection->getDatabase().password(); int port = connection->getDatabase().port(); QCOMPARE(type, QString("QPSQL")); QCOMPARE(host, QString("localhost")); QCOMPARE(name, QString("quant")); QCOMPARE(username, QString("postgre")); QCOMPARE(password, QString("root")); QCOMPARE(port, 5432); }
f8a5d69bba1e955d8d674e4a9ecbb409176d0b1c
950e056aa31594566c39ec00d4f44e15a552d6b1
/drken/ARC096/D-StaticSushi/D_fast.cpp
89ab3c1bdc8a32f6c44065b08d85c15b82814696
[]
no_license
ratta0622/competitive
4868c88ab1c7c96b65fac50f4b130b244f56335b
509851cd884bc8cd89091c290e3d5f819450c2c7
refs/heads/master
2023-02-20T08:36:46.258725
2021-01-19T07:45:10
2021-01-19T07:45:10
319,899,234
0
0
null
null
null
null
UTF-8
C++
false
false
1,131
cpp
D_fast.cpp
#include <bits/stdc++.h> #include <climits> using namespace std; using ll = long long; int main(){ int N; ll C; cin >> N >> C; ll x[N+2], v[N+2]; x[0] = 0; v[0] = 0; x[N+1] = C; v[N+1] = 0; for(int i=1; i<=N; ++i){ cin >> x[i] >> v[i]; } ll f_a[N+2]; ll f_b[N+2]; f_a[0] = 0; f_a[N+1] = 0; for(int i=1; i<=N; ++i){ f_a[i] = f_a[i-1] + v[i] + x[i-1] - x[i]; } f_b[N+1] = 0; f_b[0] = 0; for(int i=N; i>=1; --i){ f_b[i] = f_b[i+1] + v[i] + (C-x[i+1]) - (C-x[i]); } ll max_f_a[N+2]; ll max_f_b[N+2]; max_f_a[0] = 0; max_f_b[0] = 0; max_f_a[N+1] = 0; max_f_b[N+1] = 0; for(int i=1; i<=N; ++i){ max_f_a[i] = max(max_f_a[i-1], f_a[i]); } for(int i=N; i>=1; --i){ max_f_b[i] = max(max_f_b[i+1], f_b[i]); } ll max_v = 0; ll sum_v = 0; /* A which is turning point clockwise is fixed */ for(int i=0; i<=N; ++i){ max_v = max(max_v, max_f_b[i+1]+f_a[i]-x[i]); } /* B which is turning point clockwise is fixed */ for(int i=N+1; i>=1; --i){ max_v = max(max_v, max_f_a[i-1]+f_b[i]-(C-x[i])); } cout << max_v << endl; return 0; }
ab122511fef269762caa076b0b3b4ddbc30b4fc2
ab921b3276f0572b86b5996a5c02e9cc47141aef
/C++/path-sum-iii.cpp
5d20da082fd17ed47e019f09f47dab860b5b23ab
[ "MIT" ]
permissive
anishrai919/LeetCode
cc4b219d788ed2c8d1237a6505dfd9c6dbe235f5
da61c97a6f9440295f4e477442ccfc469985cd0b
refs/heads/master
2020-05-01T14:29:09.768584
2019-11-21T01:32:56
2019-11-21T01:32:56
177,521,680
0
0
MIT
2019-03-25T05:42:51
2019-03-25T05:42:51
null
UTF-8
C++
false
false
732
cpp
path-sum-iii.cpp
// Time: O(n^2) // Space: O(h) /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int pathSum(TreeNode* root, int sum) { if (!root) { return 0; } return pathSumHelper(root, 0, sum) + pathSum(root->left, sum) + pathSum(root->right, sum); } private: int pathSumHelper(TreeNode* root, int prev, int sum) { if (!root) { return 0; } int curr = prev + root->val; return (curr == sum) + pathSumHelper(root->left, curr, sum) + pathSumHelper(root->right, curr, sum); } };
7975aa29fbfd6d5016a629195819e50b300847a5
da1500e0d3040497614d5327d2461a22e934b4d8
/third_party/skia/src/gpu/text/GrAtlasManager.cpp
8255c7c6f1e15654290d2af9ee536c23c1e6ef60
[ "BSD-3-Clause", "GPL-1.0-or-later", "LGPL-2.0-or-later", "Apache-2.0", "MIT" ]
permissive
youtube/cobalt
34085fc93972ebe05b988b15410e99845efd1968
acefdaaadd3ef46f10f63d1acae2259e4024d383
refs/heads/main
2023-09-01T13:09:47.225174
2023-09-01T08:54:54
2023-09-01T08:54:54
50,049,789
169
80
BSD-3-Clause
2023-09-14T21:50:50
2016-01-20T18:11:34
null
UTF-8
C++
false
false
6,679
cpp
GrAtlasManager.cpp
/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/text/GrAtlasManager.h" #include "src/gpu/GrGlyph.h" #include "src/gpu/GrImageInfo.h" #include "src/gpu/text/GrStrikeCache.h" #if defined(STARBOARD) #include "starboard/file.h" #define remove(path) SbFileDelete(path) #endif GrAtlasManager::GrAtlasManager(GrProxyProvider* proxyProvider, GrStrikeCache* glyphCache, size_t maxTextureBytes, GrDrawOpAtlas::AllowMultitexturing allowMultitexturing) : fAllowMultitexturing{allowMultitexturing} , fProxyProvider{proxyProvider} , fCaps{fProxyProvider->refCaps()} , fGlyphCache{glyphCache} , fAtlasConfig{fCaps->maxTextureSize(), maxTextureBytes} { } GrAtlasManager::~GrAtlasManager() = default; static GrColorType mask_format_to_gr_color_type(GrMaskFormat format) { switch (format) { case kA8_GrMaskFormat: return GrColorType::kAlpha_8; case kA565_GrMaskFormat: return GrColorType::kBGR_565; case kARGB_GrMaskFormat: return GrColorType::kRGBA_8888; default: SkDEBUGFAIL("unsupported GrMaskFormat"); return GrColorType::kAlpha_8; } } void GrAtlasManager::freeAll() { for (int i = 0; i < kMaskFormatCount; ++i) { fAtlases[i] = nullptr; } } bool GrAtlasManager::hasGlyph(GrGlyph* glyph) { SkASSERT(glyph); return this->getAtlas(glyph->fMaskFormat)->hasID(glyph->fID); } // add to texture atlas that matches this format GrDrawOpAtlas::ErrorCode GrAtlasManager::addToAtlas( GrResourceProvider* resourceProvider, GrStrikeCache* glyphCache, GrTextStrike* strike, GrDrawOpAtlas::AtlasID* id, GrDeferredUploadTarget* target, GrMaskFormat format, int width, int height, const void* image, SkIPoint16* loc) { glyphCache->setStrikeToPreserve(strike); return this->getAtlas(format)->addToAtlas(resourceProvider, id, target, width, height, image, loc); } void GrAtlasManager::addGlyphToBulkAndSetUseToken(GrDrawOpAtlas::BulkUseTokenUpdater* updater, GrGlyph* glyph, GrDeferredUploadToken token) { SkASSERT(glyph); if (updater->add(glyph->fID)) { this->getAtlas(glyph->fMaskFormat)->setLastUseToken(glyph->fID, token); } } #ifdef SK_DEBUG #include "src/gpu/GrContextPriv.h" #include "src/gpu/GrSurfaceContext.h" #include "src/gpu/GrSurfaceProxy.h" #include "src/gpu/GrTextureProxy.h" #include "include/core/SkBitmap.h" #include "include/core/SkImageEncoder.h" #include "include/core/SkStream.h" #include <stdio.h> /** * Write the contents of the surface proxy to a PNG. Returns true if successful. * @param filename Full path to desired file */ static bool save_pixels(GrContext* context, GrSurfaceProxy* sProxy, GrColorType colorType, const char* filename) { if (!sProxy) { return false; } SkImageInfo ii = SkImageInfo::Make(sProxy->width(), sProxy->height(), kRGBA_8888_SkColorType, kPremul_SkAlphaType); SkBitmap bm; if (!bm.tryAllocPixels(ii)) { return false; } auto sContext = context->priv().makeWrappedSurfaceContext(sk_ref_sp(sProxy), colorType, kUnknown_SkAlphaType); if (!sContext || !sContext->asTextureProxy()) { return false; } bool result = sContext->readPixels(ii, bm.getPixels(), bm.rowBytes(), {0, 0}); if (!result) { SkDebugf("------ failed to read pixels for %s\n", filename); return false; } // remove any previous version of this file remove(filename); SkFILEWStream file(filename); if (!file.isValid()) { SkDebugf("------ failed to create file: %s\n", filename); remove(filename); // remove any partial file return false; } if (!SkEncodeImage(&file, bm, SkEncodedImageFormat::kPNG, 100)) { SkDebugf("------ failed to encode %s\n", filename); remove(filename); // remove any partial file return false; } return true; } void GrAtlasManager::dump(GrContext* context) const { static int gDumpCount = 0; for (int i = 0; i < kMaskFormatCount; ++i) { if (fAtlases[i]) { const sk_sp<GrTextureProxy>* proxies = fAtlases[i]->getProxies(); for (uint32_t pageIdx = 0; pageIdx < fAtlases[i]->numActivePages(); ++pageIdx) { SkASSERT(proxies[pageIdx]); SkString filename; #ifdef SK_BUILD_FOR_ANDROID filename.printf("/sdcard/fontcache_%d%d%d.png", gDumpCount, i, pageIdx); #else filename.printf("fontcache_%d%d%d.png", gDumpCount, i, pageIdx); #endif auto ct = mask_format_to_gr_color_type(AtlasIndexToMaskFormat(i)); save_pixels(context, proxies[pageIdx].get(), ct, filename.c_str()); } } } ++gDumpCount; } #endif void GrAtlasManager::setAtlasSizesToMinimum_ForTesting() { // Delete any old atlases. // This should be safe to do as long as we are not in the middle of a flush. for (int i = 0; i < kMaskFormatCount; i++) { fAtlases[i] = nullptr; } // Set all the atlas sizes to 1x1 plot each. new (&fAtlasConfig) GrDrawOpAtlasConfig{}; } bool GrAtlasManager::initAtlas(GrMaskFormat format) { int index = MaskFormatToAtlasIndex(format); if (fAtlases[index] == nullptr) { GrColorType grColorType = mask_format_to_gr_color_type(format); SkISize atlasDimensions = fAtlasConfig.atlasDimensions(format); SkISize plotDimensions = fAtlasConfig.plotDimensions(format); const GrBackendFormat format = fCaps->getDefaultBackendFormat(grColorType, GrRenderable::kNo); fAtlases[index] = GrDrawOpAtlas::Make( fProxyProvider, format, grColorType, atlasDimensions.width(), atlasDimensions.height(), plotDimensions.width(), plotDimensions.height(), fAllowMultitexturing, &GrStrikeCache::HandleEviction, fGlyphCache); if (!fAtlases[index]) { return false; } } return true; }
ff7d885ab388f7ecaf4f5e1e91ea8e434e0f7eb7
f45a450972efd98785ccf65f1dfa5a08ac832bc7
/Engine/Source Files/Resources/InputLayout.cpp
43c3c4528bab9e25e11387acd5a4c8a571bd3757
[]
no_license
Donnay-Splash/Engine-D3D11
159389dc816ed0dc6932f1c459f5d6bbc9a348f6
f1f00161d5686e31e43367f31e4f0431bf093b38
refs/heads/master
2022-01-29T19:01:12.189418
2020-07-24T16:33:52
2020-07-24T16:33:52
67,720,427
7
0
null
null
null
null
UTF-8
C++
false
false
3,590
cpp
InputLayout.cpp
#include "pch.h" #include <Resources\InputLayout.h> namespace Engine { InputLayout::InputLayout(const uint32_t& inputFlags) { EngineAssert(inputFlags != 0); UINT inputSlot = 0; if (inputFlags & InputElement::Position) { D3D11_INPUT_ELEMENT_DESC element; SecureZeroMemory(&element, sizeof(element)); element.SemanticName = "POSITION"; element.SemanticIndex = 0; element.Format = DXGI_FORMAT_R32G32B32_FLOAT; element.InputSlot = inputSlot; element.AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; element.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; element.InstanceDataStepRate = 0; m_inputElements.push_back(element); inputSlot++; } if (inputFlags & InputElement::Normal0) { D3D11_INPUT_ELEMENT_DESC element; SecureZeroMemory(&element, sizeof(element)); element.SemanticName = "NORMAL"; element.SemanticIndex = 0; element.Format = DXGI_FORMAT_R32G32B32_FLOAT; element.InputSlot = inputSlot; element.AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; element.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; element.InstanceDataStepRate = 0; m_inputElements.push_back(element); inputSlot++; } if (inputFlags & InputElement::TexCoord0) { D3D11_INPUT_ELEMENT_DESC element; SecureZeroMemory(&element, sizeof(element)); element.SemanticName = "TEXCOORD"; element.SemanticIndex = 0; element.Format = DXGI_FORMAT_R32G32_FLOAT; element.InputSlot = inputSlot; element.AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; element.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; element.InstanceDataStepRate = 0; m_inputElements.push_back(element); inputSlot++; } if (inputFlags & InputElement::Tangents) { D3D11_INPUT_ELEMENT_DESC tangentsDesc; SecureZeroMemory(&tangentsDesc, sizeof(tangentsDesc)); tangentsDesc.SemanticName = "TANGENT"; tangentsDesc.SemanticIndex = 0; tangentsDesc.Format = DXGI_FORMAT_R32G32B32_FLOAT; tangentsDesc.InputSlot = inputSlot; tangentsDesc.AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; tangentsDesc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; tangentsDesc.InstanceDataStepRate = 0; m_inputElements.push_back(tangentsDesc); inputSlot++; D3D11_INPUT_ELEMENT_DESC bitangentsDesc; SecureZeroMemory(&bitangentsDesc, sizeof(bitangentsDesc)); bitangentsDesc.SemanticName = "BINORMAL"; bitangentsDesc.SemanticIndex = 0; bitangentsDesc.Format = DXGI_FORMAT_R32G32B32_FLOAT; bitangentsDesc.InputSlot = inputSlot; bitangentsDesc.AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; bitangentsDesc.InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; bitangentsDesc.InstanceDataStepRate = 0; m_inputElements.push_back(bitangentsDesc); inputSlot++; } // The input cannot be emptty. EngineAssert(!m_inputElements.empty()); } void InputLayout::UploadData(ID3D11DeviceContext* deviceContext) { deviceContext->IASetInputLayout(m_inputLayout.Get()); } }
6c68ca84f4a226c787763371315ec4043a09e7e2
63c386bad8878612dafaad6ba63845b62959c70f
/Important_Practice_Problems/Dynamic_Programming/Nth_Fibonacci.cpp
6f9da0c7429ebd570e584d59be724f78fca758b4
[]
no_license
himankurgoyal/DSA-Algo
15488d82b3d7cf6f5eab2a2dfb790204f80a88fb
53da7c546c93e27fb9373b885a513683c0aa7975
refs/heads/master
2022-11-23T19:12:57.104127
2020-07-17T21:38:57
2020-07-17T21:38:57
279,695,851
0
0
null
null
null
null
UTF-8
C++
false
false
453
cpp
Nth_Fibonacci.cpp
//1.FIBONACCI USING MEMO #include<bits/stdc++.h> using namespace std; #define modulo 1000000007 #define max 1001 int dp[max]; int print(int n) { if(dp[n]==-1) { if(n<=1) dp[n]=n; else dp[n]=print(n-1)+print(n-2); } return dp[n]%modulo; } int main() { int T; cin>>T; while(T--) { int N; cin>>N; for(int i=0;i<max;i++) dp[i]=-1; cout<<print(N)<<endl; } } //TC:O(n) //SC: O(n)
9acb8a346a896d4d6ef428b89443b95614cd21a8
bf7fe9c190e45d80200706bf39359716ba41587d
/Particles/ParticleSystem.h
8520cbe10bc3c813e882f91285416dc2ab5f19a4
[]
no_license
VladislavKoleda/CosmicDefender--master
de1a34f9ebe0bff764152b94d170710642809a98
042097567af4a3e6eba147971ce067a3a982907a
refs/heads/master
2020-11-23T21:04:17.911131
2019-12-13T10:53:43
2019-12-13T10:53:43
227,819,746
0
0
null
null
null
null
UTF-8
C++
false
false
731
h
ParticleSystem.h
#pragma once #define _USE_MATH_DEFINES #include <string> #include <vector> #include <cmath> //C# TO C++ CONVERTER NOTE: Forward class declarations: namespace ComicDefender { class Particle; } using namespace SFML::Graphics; using namespace SFML::System; namespace ComicDefender { class ParticleSystem : public Transformable, public Drawable { protected: static const std::wstring CONTENT_DIRICTORY; public: VertexArray *m_vertices; std::vector<Particle*> m_particles; int _count = 0; Random *R = new Random(); virtual ~ParticleSystem() { delete m_vertices; delete R; } ParticleSystem(unsigned int count); void Draw(RenderTarget *target, RenderStates states) override; void Update(); }; }