text
stringlengths
8
6.88M
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <cmath> #include <queue> #include <stack> #include <string> #define inf 1<<30 #define maxn 10005 #define LOOP(a,b,c) for(int a=b;a<=c;a++) using namespace std; string ch; void clear_first_zero() { string::iterator it = ch.begin(); if (*it == '.'){ ch.insert(it, '0'); return; } int t=0; for (int i = 0; i < ch.size(); i++) { if (ch[i] == '0'&&ch[i+1]!='.') t++; else break; } ch = ch.erase(0, t); if (!ch.size()) ch = "0"; } void clear_last_zero() { int pos = ch.find('.', 0); if (pos == -1) { //ch += '.'; return; } int t = ch.size(); for (int i = ch.size() - 1; i >= 0; i--) { if (ch[i] == '0') t--; else if (ch[i] == '.') { t--; break; } else break; } ch = ch.erase(t, ch.size()); } int move() { int pos = ch.find('.', 0), change = 0; if (ch.size() == 1) return 0; if (pos == -1 ) { ch += '.'; pos = ch.find('.', 0); } if (pos >= 2) { for (int i = pos; i >= 2; i--) { swap(ch[i], ch[i - 1]); //Right = sum(Right, add); change++; } //clear_first_zero(); clear_last_zero(); } else { string::iterator it = ch.begin(); if (*it != '0'&&*(it+1)=='.'&&(it+2)!=ch.end()||ch=="0") return 0; for (int i = 0; i < ch.size(); i++) { if (ch[i] != '0'&& ch[i] != '.') break; if (ch[i] != '.') change--; } ch=ch.erase(0, -change+1); if(ch.size()>1) ch.insert(ch.begin() + 1, '.'); } return change; } int main() { //freopen("Text.txt", "r", stdin); cin >> ch; clear_first_zero(); clear_last_zero(); int t = move(); if (t > 0) cout << ch << "E" << t << endl; else if (t < 0) else cout << ch << endl; }
#include "stdafx.h" #include "Engine/graphics/TScopedResource.h"
/* leetcode 416 * * * */ #include <vector> #include <algorithm> #include <string> #include <unordered_set> #include <algorithm> #include <map> using namespace std; class Solution { public: bool canPartition(vector<int>& nums) { int sum = 0; for (int num : nums) { sum += num; } if (sum % 2 != 0) { return false; } sum >>= 1; int n = nums.size(); vector<vector<bool>>dp(n+1, vector<bool>(sum + 1, false)); for (int i = 0; i <= n; i++) { dp[i][0] = true; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { if (nums[i - 1] > j) { dp[i][j] = dp[i - 1][j]; } else { dp[i][j] = dp[i - 1][j] | dp[i - 1][j - nums[i - 1]]; } } } return dp[n][sum]; } }; /************************** run solution **************************/ bool _solution_run(vector<int>& nums) { Solution leetcode_416; bool ans = leetcode_416.canPartition(nums); return ans; } #ifdef USE_SOLUTION_CUSTOM string _solution_custom(TestCases &tc) { } #endif /************************** get testcase **************************/ #ifdef USE_GET_TEST_CASES_IN_CPP vector<string> _get_test_cases_string() { return {}; } #endif
#include <iostream> #include "function.h" int chooseMenu() { int inputChoose{}; std::cin >> inputChoose; return inputChoose; } int userInputInt() { int inputNumber{}; std::cin >> inputNumber; return inputNumber; } char userInputChar() { char inputChar{}; std::cin >> inputChar; return inputChar; } void menu() { using namespace std; cout << "1. Convert char to int\n"; cout << "2. Convert int to char\n"; cout << "3. Exit\n"; }
// ---------------------------------------------------------------------------- // Copyright (C) 2002-2006 Marcin Kalicinski // // 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) // // For more information, see www.boost.org // ---------------------------------------------------------------------------- #ifndef LIBLAS_BOOST_PROPERTY_TREE_DETAIL_JSON_PARSER_READ_HPP_INCLUDED #define LIBLAS_BOOST_PROPERTY_TREE_DETAIL_JSON_PARSER_READ_HPP_INCLUDED //#define BOOST_SPIRIT_DEBUG #include <liblas/external/property_tree/ptree.hpp> #include <liblas/external/property_tree/detail/ptree_utils.hpp> #include <liblas/external/property_tree/detail/json_parser_error.hpp> #include <boost/spirit/include/classic.hpp> #include <boost/limits.hpp> #include <string> #include <locale> #include <istream> #include <vector> #include <algorithm> namespace liblas { namespace property_tree { namespace json_parser { /////////////////////////////////////////////////////////////////////// // Json parser context template<class Ptree> struct context { typedef typename Ptree::key_type::value_type Ch; typedef std::basic_string<Ch> Str; typedef typename std::vector<Ch>::iterator It; Str string; Str name; Ptree root; std::vector<Ptree *> stack; struct a_object_s { context &c; a_object_s(context &c): c(c) { } void operator()(Ch) const { if (c.stack.empty()) c.stack.push_back(&c.root); else { Ptree *parent = c.stack.back(); Ptree *child = &parent->push_back(std::make_pair(c.name, Ptree()))->second; c.stack.push_back(child); c.name.clear(); } } }; struct a_object_e { context &c; a_object_e(context &c): c(c) { } void operator()(Ch) const { BOOST_ASSERT(c.stack.size() >= 1); c.stack.pop_back(); } }; struct a_name { context &c; a_name(context &c): c(c) { } void operator()(It, It) const { c.name.swap(c.string); c.string.clear(); } }; struct a_string_val { context &c; a_string_val(context &c): c(c) { } void operator()(It, It) const { BOOST_ASSERT(c.stack.size() >= 1); c.stack.back()->push_back(std::make_pair(c.name, Ptree(c.string))); c.name.clear(); c.string.clear(); } }; struct a_literal_val { context &c; a_literal_val(context &c): c(c) { } void operator()(It b, It e) const { BOOST_ASSERT(c.stack.size() >= 1); c.stack.back()->push_back(std::make_pair(c.name, Str(b, e))); c.name.clear(); c.string.clear(); } }; struct a_char { context &c; a_char(context &c): c(c) { } void operator()(It b, It e) const { c.string += *b; } }; struct a_escape { context &c; a_escape(context &c): c(c) { } void operator()(Ch ch) const { switch (ch) { case Ch('\"'): c.string += Ch('\"'); break; case Ch('\\'): c.string += Ch('\\'); break; case Ch('/'): c.string += Ch('/'); break; case Ch('b'): c.string += Ch('\b'); break; case Ch('f'): c.string += Ch('\f'); break; case Ch('n'): c.string += Ch('\n'); break; case Ch('r'): c.string += Ch('\r'); break; case Ch('t'): c.string += Ch('\t'); break; default: BOOST_ASSERT(0); } } }; struct a_unicode { context &c; a_unicode(context &c): c(c) { } void operator()(unsigned long u) const { u = (std::min)(u, static_cast<unsigned long>((std::numeric_limits<Ch>::max)())); c.string += Ch(u); } }; }; /////////////////////////////////////////////////////////////////////// // Json grammar template<class Ptree> struct json_grammar : public boost::spirit::classic::grammar<json_grammar<Ptree> > { typedef context<Ptree> Context; typedef typename Ptree::key_type::value_type Ch; mutable Context c; template<class Scanner> struct definition { boost::spirit::classic::rule<Scanner> root, object, member, array, item, value, string, number; boost::spirit::classic::rule< typename boost::spirit::classic::lexeme_scanner<Scanner>::type> character, escape; definition(const json_grammar &self) { using namespace boost::spirit::classic; // Assertions assertion<std::string> expect_object("expected object"); assertion<std::string> expect_eoi("expected end of input"); assertion<std::string> expect_objclose("expected ',' or '}'"); assertion<std::string> expect_arrclose("expected ',' or ']'"); assertion<std::string> expect_name("expected object name"); assertion<std::string> expect_colon("expected ':'"); assertion<std::string> expect_value("expected value"); assertion<std::string> expect_escape("invalid escape sequence"); // JSON grammar rules root = expect_object(object) >> expect_eoi(end_p) ; object = ch_p('{')[typename Context::a_object_s(self.c)] >> (ch_p('}')[typename Context::a_object_e(self.c)] | (list_p(member, ch_p(',')) >> expect_objclose(ch_p('}')[typename Context::a_object_e(self.c)]) ) ) ; member = expect_name(string[typename Context::a_name(self.c)]) >> expect_colon(ch_p(':')) >> expect_value(value) ; array = ch_p('[')[typename Context::a_object_s(self.c)] >> (ch_p(']')[typename Context::a_object_e(self.c)] | (list_p(item, ch_p(',')) >> expect_arrclose(ch_p(']')[typename Context::a_object_e(self.c)]) ) ) ; item = expect_value(value) ; value = string[typename Context::a_string_val(self.c)] | (number | str_p("true") | "false" | "null")[typename Context::a_literal_val(self.c)] | object | array ; number = !ch_p("-") >> (ch_p("0") | (range_p(Ch('1'), Ch('9')) >> *digit_p)) >> !(ch_p(".") >> +digit_p) >> !(chset_p(detail::widen<Ch>("eE").c_str()) >> !chset_p(detail::widen<Ch>("-+").c_str()) >> +digit_p) ; string = +(lexeme_d[confix_p('\"', *character, '\"')]) ; character = (anychar_p - "\\" - "\"") [typename Context::a_char(self.c)] | ch_p("\\") >> expect_escape(escape) ; escape = chset_p(detail::widen<Ch>("\"\\/bfnrt").c_str()) [typename Context::a_escape(self.c)] | 'u' >> uint_parser<unsigned long, 16, 4, 4>() [typename Context::a_unicode(self.c)] ; // Debug BOOST_SPIRIT_DEBUG_RULE(root); BOOST_SPIRIT_DEBUG_RULE(object); BOOST_SPIRIT_DEBUG_RULE(member); BOOST_SPIRIT_DEBUG_RULE(array); BOOST_SPIRIT_DEBUG_RULE(item); BOOST_SPIRIT_DEBUG_RULE(value); BOOST_SPIRIT_DEBUG_RULE(string); BOOST_SPIRIT_DEBUG_RULE(number); BOOST_SPIRIT_DEBUG_RULE(escape); BOOST_SPIRIT_DEBUG_RULE(character); } const boost::spirit::classic::rule<Scanner> &start() const { return root; } }; }; template<class It, class Ch> unsigned long count_lines(It begin, It end) { return static_cast<unsigned long>(std::count(begin, end, Ch('\n')) + 1); } template<class Ptree> void read_json_internal(std::basic_istream<typename Ptree::key_type::value_type> &stream, Ptree &pt, const std::string &filename) { using namespace boost::spirit::classic; typedef typename Ptree::key_type::value_type Ch; typedef typename std::vector<Ch>::iterator It; // Load data into vector std::vector<Ch> v(std::istreambuf_iterator<Ch>(stream.rdbuf()), std::istreambuf_iterator<Ch>()); if (!stream.good()) BOOST_PROPERTY_TREE_THROW(json_parser_error("read error", filename, 0)); // Prepare grammar json_grammar<Ptree> g; // Parse try { parse_info<It> pi = parse(v.begin(), v.end(), g, space_p | comment_p("//") | comment_p("/*", "*/")); if (!pi.hit || !pi.full) BOOST_PROPERTY_TREE_THROW((parser_error<std::string, It>(v.begin(), "syntax error"))); } catch (parser_error<std::string, It> &e) { BOOST_PROPERTY_TREE_THROW(json_parser_error(e.descriptor, filename, count_lines<It, Ch>(v.begin(), e.where))); } // Swap grammar context root and pt pt.swap(g.c.root); } } } } #endif
#pragma once #include <Interfaces.h> #include <vector> class VBuffer : public wrl::RuntimeClass<wrl::RuntimeClassFlags<wrl::ClassicCom>, IVBuffer> { friend class InputAssembler; friend class VContext; public: HRESULT RuntimeClassInitialize(const VBUFFER_DESC* in_desc, const void* _in_data); public: VBuffer() = default; public: virtual void __stdcall GetDesc(VBUFFER_DESC* _out_Desc)override; private: VBUFFER_DESC desc{ 0 }; std::vector<uint8_t> data; };
//: C11:ConstReferenceArguments.cpp // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt // Przekazywanie referencji jako stalych void f(int&) {} void g(const int&) {} int main() { //! f(1); // Blad g(1); } ///:~
#pragma once #include "cDistrict.h" class cCardDistrict : public cDistrict { public: enum eCardDistrictType { e_Community, e_Chance, }; cCardDistrict(eCardDistrictType type); virtual ~cCardDistrict(); // begin of iDistrict virtual bool Actioon(); // end of iDistrict private: eCardDistrictType m_type; };
#pragma once #include <functional> #include "point.h" #include "drawManager.h" #include "appConsts.h" #include "controller.h" #include "toolbarControl.h" enum class SliderType { FloatPointSlider, IntegerSlider }; class Slider : public ToolbarControl { private: const SliderTheme *sliderTheme; Point<float> pos; float value; float minValue, maxValue; SliderType sliderType; std::string label; Point<float> indicatorPos; std::function<void(float)> eventHandler; bool isIndicatorGrabbed; void setValue(float newValue); void handleMouseMove(float mouseXPos); bool isMouseOverIndicator(Point<float> mousePos); public: Slider(Point<float> pos, float currValue, float minValue, float maxValue, SliderType sliderType, std::string label, const SliderTheme *sliderTheme); void setOnValueChangeHandler(std::function<void(float)> eventHandler); virtual void update(Controller *controller); virtual void draw(DrawManager *drawManager); };
#include "buscar.h" #include "ui_buscar.h" buscar::buscar(QWidget *parent) : QDialog(parent), ui(new Ui::buscar) { ui->setupUi(this); } buscar::~buscar() { delete ui; }
#pragma once #include <mutiplex/callbacks.h> #include <mutiplex/InetAddress.h> namespace muti { class EventLoop; class EventSource; class Connector { public: explicit Connector(EventLoop* loop, const InetAddress& peer); ~Connector(); void connect_error_callback(const ConnectErrorCallback& cb) { connect_error_callback_ = cb; } void established_callback(const EstablishedCallback& cb) { established_callback_ = cb; } void set_read_callback(const ReadCallback& cb) { read_callback_ = cb; } void closed_callback(const ClosedCallback& cb) { closed_callback_ = cb; } void start_connect(); private: void handle_connected(uint64_t timestamp); bool do_connect(); void handle_error(uint64_t timestamp); private: int fd_; EventLoop* loop_; InetAddress local_; InetAddress peer_; EventSource* event_source_; ConnectErrorCallback connect_error_callback_; EstablishedCallback established_callback_; ReadCallback read_callback_; ClosedCallback closed_callback_; }; }
#ifndef _RECTANGLE_H #define _RECTANGLE_H #include "sjfwd.h" #include "shape.h" #include "point.h" class rectangle : public shape { public: double xlen; double ylen; rectangle(double cx = 0, double cy = 0, double xl = 1, double yl = 1, bool fl = false){ this->center = point(cx, cy); this->xlen = xl; this->ylen = yl; this->fill = fl; } bool overlaps(const point) const; bool overlaps(const circle) const; bool overlaps(const rectangle) const; bool overlaps(const triangle) const; bool onscreen() const; void draw() const; void translade(double, double); }; #endif
#pragma once #ifndef STACKQUEUE_HPP_INCLUDE #define STACKQUEUE_HPP_INCLUDE namespace sq { #include "common.hpp" typedef struct _Node { int value; struct _Node *next; }Node; typedef struct _Stack { int size; Node *top; }Stack; typedef struct _Queue { Stack *Sin; Stack *Sout; }Queue; int sqUI(); Node *initNode(int v); Stack *initStack(); Queue *initQueue(); void push(int v, Stack *stack); Node *pop(Stack *stack); void enqueue(int v, Queue *queue); Node *dequeue(Queue *queue); void printQueue(Queue *queue); } #endif //STACKQUEUE_HPP_INCLUDE
class Solution{ public: //Function to find the height of a binary tree. int height(struct Node* root){ if(!root) return 1; else { return 1+ max(height(root->left),height(root->right)); } } };
#ifndef DECODEANDSENDTHREAD_H #define DECODEANDSENDTHREAD_H #include <QThread> #include "rtpclass.h" class decodeAndSendThread : public QThread { Q_OBJECT public: decodeAndSendThread(QObject *parent = 0); void initData(unsigned char *b,unsigned char *v,int i); private: ~decodeAndSendThread(); unsigned char *buffer; unsigned char *cam_yuv; int width,height; void run(); QMutex lock; int index; int currentIndex; pic_data picData; h264Class *h264; signals: void finishDecode(unsigned char *buffer,int length); public slots: }; #endif // DECODEANDSENDTHREAD_H
#ifndef MINISERVER_HTTP_MESSAGE_H #define MINISERVER_HTTP_MESSAGE_H #include <string> #include <map> #include <stdint.h> #include "common_type.h" namespace miniserver{ class HttpMessage { public: HttpMessage(); virtual ~HttpMessage(); HttpMessage(const HttpMessage &other); HttpMessage& operator=(const HttpMessage &rhs); HttpMessage(HttpMessage &&other); HttpMessage& operator=(HttpMessage &&rhs); void clear(); // http mesasge geter const std::map<std::string, std::string>& getHeader() const; char *getBody() const; uint64_t getBodyLen() const; // setter void addHeader(const std::string &key, const std::string &val); bool setBody(char *body_msg); void setBodyLen(uint64_t body_len); private: std::map<std::string, std::string> _headers; char *_body; uint64_t _body_len; }; //============================================================================== // Class Http Request //============================================================================== class HttpRequest : public HttpMessage { public: HttpRequest(); ~HttpRequest(); HttpRequest(const HttpRequest &other); HttpRequest& operator=(const HttpRequest &rhs); HttpRequest(HttpRequest &&other); HttpRequest& operator=(HttpRequest &&rhs); void clear(); // getter const std::string& getMethod() const; const std::string& getUrl() const; const std::string& getVersion() const; // setter void setMethod(const std::string &method); void setUrl(const std::string &url); void setVersion(const std::string &version); private: std::string _method; std::string _url; std::string _version; }; //============================================================================== // Class Http Response //============================================================================== class HttpResponse : public HttpMessage { public: HttpResponse(); ~HttpResponse(); HttpResponse(const HttpResponse &other); HttpResponse& operator=(const HttpResponse &rhs); HttpResponse(HttpResponse &&other); HttpResponse& operator=(HttpResponse &&rhs); void clear(); // getter const std::string& getStatus() const; const std::string& getInfo() const; const std::string& getVersion() const; // setter void setStatus(const std::string &status); void setInfo(const std::string &info); void setVersion(const std::string &version); private: std::string _status; std::string _info; std::string _version; }; } #endif
//===--- SemaCoroutines.cpp - Semantic Analysis for Coroutines ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for C++ Coroutines. // //===----------------------------------------------------------------------===// #include "clang/Sema/SemaInternal.h" #include "clang/AST/Decl.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/StmtCXX.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Overload.h" using namespace clang; using namespace sema; /// Look up the std::coroutine_traits<...>::promise_type for the given /// function type. static QualType lookupPromiseType(Sema &S, const FunctionProtoType *FnType, SourceLocation Loc) { // FIXME: Cache std::coroutine_traits once we've found it. NamespaceDecl *Std = S.getStdNamespace(); if (!Std) { S.Diag(Loc, diag::err_implied_std_coroutine_traits_not_found); return QualType(); } LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_traits"), Loc, Sema::LookupOrdinaryName); if (!S.LookupQualifiedName(Result, Std)) { S.Diag(Loc, diag::err_implied_std_coroutine_traits_not_found); return QualType(); } ClassTemplateDecl *CoroTraits = Result.getAsSingle<ClassTemplateDecl>(); if (!CoroTraits) { Result.suppressDiagnostics(); // We found something weird. Complain about the first thing we found. NamedDecl *Found = *Result.begin(); S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits); return QualType(); } // Form template argument list for coroutine_traits<R, P1, P2, ...>. TemplateArgumentListInfo Args(Loc, Loc); Args.addArgument(TemplateArgumentLoc( TemplateArgument(FnType->getReturnType()), S.Context.getTrivialTypeSourceInfo(FnType->getReturnType(), Loc))); for (QualType T : FnType->getParamTypes()) Args.addArgument(TemplateArgumentLoc( TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, Loc))); // Build the template-id. QualType CoroTrait = S.CheckTemplateIdType(TemplateName(CoroTraits), Loc, Args); if (CoroTrait.isNull()) return QualType(); if (S.RequireCompleteType(Loc, CoroTrait, diag::err_coroutine_traits_missing_specialization)) return QualType(); CXXRecordDecl *RD = CoroTrait->getAsCXXRecordDecl(); assert(RD && "specialization of class template is not a class?"); // Look up the ::promise_type member. LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), Loc, Sema::LookupOrdinaryName); S.LookupQualifiedName(R, RD); auto *Promise = R.getAsSingle<TypeDecl>(); if (!Promise) { S.Diag(Loc, diag::err_implied_std_coroutine_traits_promise_type_not_found) << RD; return QualType(); } // The promise type is required to be a class type. QualType PromiseType = S.Context.getTypeDeclType(Promise); if (!PromiseType->getAsCXXRecordDecl()) { S.Diag(Loc, diag::err_implied_std_coroutine_traits_promise_type_not_class) << PromiseType; return QualType(); } return PromiseType; } /// Check that this is a context in which a coroutine suspension can appear. static FunctionScopeInfo * checkCoroutineContext(Sema &S, SourceLocation Loc, StringRef Keyword) { // 'co_await' and 'co_yield' are permitted in unevaluated operands. // FIXME: Not in 'noexcept'. if (S.isUnevaluatedContext()) return nullptr; // Any other usage must be within a function. auto *FD = dyn_cast<FunctionDecl>(S.CurContext); if (!FD) { S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext) ? diag::err_coroutine_objc_method : diag::err_coroutine_outside_function) << Keyword; } else if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) { // Coroutines TS [special]/6: // A special member function shall not be a coroutine. // // FIXME: We assume that this really means that a coroutine cannot // be a constructor or destructor. S.Diag(Loc, diag::err_coroutine_ctor_dtor) << isa<CXXDestructorDecl>(FD) << Keyword; } else if (FD->isConstexpr()) { S.Diag(Loc, diag::err_coroutine_constexpr) << Keyword; } else if (FD->isVariadic()) { S.Diag(Loc, diag::err_coroutine_varargs) << Keyword; } else { auto *ScopeInfo = S.getCurFunction(); assert(ScopeInfo && "missing function scope for function"); // If we don't have a promise variable, build one now. if (!ScopeInfo->CoroutinePromise && !FD->getType()->isDependentType()) { QualType T = lookupPromiseType(S, FD->getType()->castAs<FunctionProtoType>(), Loc); if (T.isNull()) return nullptr; // Create and default-initialize the promise. ScopeInfo->CoroutinePromise = VarDecl::Create(S.Context, FD, FD->getLocation(), FD->getLocation(), &S.PP.getIdentifierTable().get("__promise"), T, S.Context.getTrivialTypeSourceInfo(T, Loc), SC_None); S.CheckVariableDeclarationType(ScopeInfo->CoroutinePromise); if (!ScopeInfo->CoroutinePromise->isInvalidDecl()) S.ActOnUninitializedDecl(ScopeInfo->CoroutinePromise, false); } return ScopeInfo; } return nullptr; } /// Build a call to 'operator co_await' if there is a suitable operator for /// the given expression. static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S, SourceLocation Loc, Expr *E) { UnresolvedSet<16> Functions; SemaRef.LookupOverloadedOperatorName(OO_Coawait, S, E->getType(), QualType(), Functions); return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E); } struct ReadySuspendResumeResult { bool IsInvalid; Expr *Results[3]; }; /// Build calls to await_ready, await_suspend, and await_resume for a co_await /// expression. static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, SourceLocation Loc, Expr *E) { // Assume invalid until we see otherwise. ReadySuspendResumeResult Calls = {true, {}}; const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"}; for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) { DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Funcs[I]), Loc); Expr *Operand = new (S.Context) OpaqueValueExpr( Loc, E->getType(), E->getValueKind(), E->getObjectKind(), E); // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&. CXXScopeSpec SS; ExprResult Result = S.BuildMemberReferenceExpr( Operand, Operand->getType(), Loc, /*IsPtr=*/false, SS, SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr, /*Scope=*/nullptr); if (Result.isInvalid()) return Calls; // FIXME: Pass coroutine handle to await_suspend. Result = S.ActOnCallExpr(nullptr, Result.get(), Loc, None, Loc, nullptr); if (Result.isInvalid()) return Calls; Calls.Results[I] = Result.get(); } Calls.IsInvalid = false; return Calls; } ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) { ExprResult Awaitable = buildOperatorCoawaitCall(*this, S, Loc, E); if (Awaitable.isInvalid()) return ExprError(); return BuildCoawaitExpr(Loc, Awaitable.get()); } ExprResult Sema::BuildCoawaitExpr(SourceLocation Loc, Expr *E) { auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await"); if (E->getType()->isDependentType()) { Expr *Res = new (Context) CoawaitExpr(Loc, Context.DependentTy, E); if (Coroutine) Coroutine->CoroutineStmts.push_back(Res); return Res; } if (E->getType()->isPlaceholderType()) { ExprResult R = CheckPlaceholderExpr(E); if (R.isInvalid()) return ExprError(); E = R.get(); } // FIXME: If E is a prvalue, create a temporary. // FIXME: If E is an xvalue, convert to lvalue. // Build the await_ready, await_suspend, await_resume calls. ReadySuspendResumeResult RSS = buildCoawaitCalls(*this, Loc, E); if (RSS.IsInvalid) return ExprError(); Expr *Res = new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1], RSS.Results[2]); if (Coroutine) Coroutine->CoroutineStmts.push_back(Res); return Res; } ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) { // FIXME: Build yield_value call. ExprResult Awaitable = buildOperatorCoawaitCall(*this, S, Loc, E); if (Awaitable.isInvalid()) return ExprError(); return BuildCoyieldExpr(Loc, Awaitable.get()); } ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) { auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield"); // FIXME: Build await_* calls. Expr *Res = new (Context) CoyieldExpr(Loc, Context.VoidTy, E); if (Coroutine) Coroutine->CoroutineStmts.push_back(Res); return Res; } StmtResult Sema::ActOnCoreturnStmt(SourceLocation Loc, Expr *E) { return BuildCoreturnStmt(Loc, E); } StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E) { auto *Coroutine = checkCoroutineContext(*this, Loc, "co_return"); // FIXME: Build return_* calls. Stmt *Res = new (Context) CoreturnStmt(Loc, E); if (Coroutine) Coroutine->CoroutineStmts.push_back(Res); return Res; } void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *Body) { FunctionScopeInfo *Fn = getCurFunction(); assert(Fn && !Fn->CoroutineStmts.empty() && "not a coroutine"); // Coroutines [stmt.return]p1: // A return statement shall not appear in a coroutine. if (Fn->FirstReturnLoc.isValid()) { Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine); auto *First = Fn->CoroutineStmts[0]; Diag(First->getLocStart(), diag::note_declared_coroutine_here) << (isa<CoawaitExpr>(First) ? 0 : isa<CoyieldExpr>(First) ? 1 : 2); } bool AnyCoawaits = false; bool AnyCoyields = false; for (auto *CoroutineStmt : Fn->CoroutineStmts) { AnyCoawaits |= isa<CoawaitExpr>(CoroutineStmt); AnyCoyields |= isa<CoyieldExpr>(CoroutineStmt); } if (!AnyCoawaits && !AnyCoyields) Diag(Fn->CoroutineStmts.front()->getLocStart(), diag::ext_coroutine_without_co_await_co_yield); // FIXME: Perform analysis of initial and final suspend, // and set_exception call. }
#include "stdafx.h" #include "PostEffect.h" PostEffect::PostEffect() { InitFullScreenQuadPrimitive(); //TODO : Dof //m_dof.Init(); } PostEffect::~PostEffect() { if (m_vertexBuffer != nullptr) { m_vertexBuffer->Release(); } } void PostEffect::Update() { m_bloom.Update(); } void PostEffect::Draw() { m_bloom.Draw(*this); //m_dof.Draw(*this); } struct SVertex { float position[4]; //頂点座標。 float uv[2]; //UV座標。これがテクスチャ座標 }; void PostEffect::InitFullScreenQuadPrimitive() { //頂点バッファを初期化。 SVertex vertex[4] = { //頂点1 { //座標 position[4] -1.0f, -1.0f, 0.0f, 1.0f, //UV座標 uv[2] 0.0f, 1.0f }, //頂点2 { //座標 position[4] 1.0f, -1.0f, 0.0f, 1.0f, //UV座標 uv[2] 1.0f, 1.0f }, //頂点3 { //座標 position[4] -1.0f, 1.0f, 0.0f, 1.0f, //UV座標 uv[2] 0.0f, 0.0f }, //頂点4 { //座標 position[4] 1.0f, 1.0f, 0.0f, 1.0f, //UV座標 uv[2] 1.0f, 0.0f }, }; D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); //構造体を0で初期化する。 bd.Usage = D3D11_USAGE_DEFAULT; //バッファーで想定されている読み込みおよび書き込みの方法。 //取りあえずはD3D11_USAGE_DEFAULTでよい。 bd.ByteWidth = sizeof(vertex); //頂点バッファのサイズ。頂点のサイズ×頂点数となる。 bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; //これから作成するバッファが頂点バッファであることを指定する。 D3D11_SUBRESOURCE_DATA InitData; ZeroMemory(&InitData, sizeof(InitData)); InitData.pSysMem = vertex; //頂点バッファの作成。 g_graphicsEngine->GetD3DDevice()->CreateBuffer(&bd, &InitData, &m_vertexBuffer); } void PostEffect::DrawFullScreenQuadPrimitive(ID3D11DeviceContext* deviceContext, Shader& vsShader, Shader& psShader) { //プリミティブのトポロジーとして、トライアングルストリップを設定する。 deviceContext->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); unsigned int vertexSize = sizeof(SVertex); unsigned int offset = 0; //輝度抽出用のシェーダーを設定する。 deviceContext->VSSetShader( (ID3D11VertexShader*)vsShader.GetBody(), nullptr, 0 ); deviceContext->PSSetShader( (ID3D11PixelShader*)psShader.GetBody(), nullptr, 0 ); deviceContext->IASetInputLayout(vsShader.GetInputLayout()); deviceContext->IASetVertexBuffers(0, 1, &m_vertexBuffer, &vertexSize, &offset); deviceContext->Draw(4, 0); }
#include <Poco/Exception.h> #include <Poco/Logger.h> #include "util/PeriodicRunner.h" using namespace Poco; using namespace BeeeOn; PeriodicRunner::PeriodicRunner(): m_invoke(*this, &PeriodicRunner::onStart) { } PeriodicRunner::~PeriodicRunner() { } void PeriodicRunner::start(const Callback &callback) { Timer::stop(); m_callback = callback; Timer::setPeriodicInterval(m_interval.totalMilliseconds()); Timer::start(m_invoke); } void PeriodicRunner::stop() { Timer::stop(); } void PeriodicRunner::setInterval(const Timespan &interval) { if (interval.totalMilliseconds() <= 0) throw InvalidArgumentException("too small interval for period invocations"); m_interval = interval; } void PeriodicRunner::onStart(Timer &) { try { m_callback(); } BEEEON_CATCH_CHAIN(logger()) }
#ifndef PhilipsWaveModel_H #define PhilipsWaveModel_H #include "WaveModel.h" using namespace std; class PhilipsWaveModel: public WaveModel{ private: double L; double A; vector<PhilipsWave> WaveList; public: PhilipsWaveModel(); fill(); }; #endif
#pragma once #include "GameObject.h" class Character; class EndPortal : public GameObject { public: EndPortal(DirectX::XMFLOAT3 position = {}, Character* player = nullptr); virtual ~EndPortal() = default; EndPortal(const EndPortal& other) = delete; EndPortal(EndPortal&& other) noexcept = delete; EndPortal& operator=(const EndPortal& other) = delete; EndPortal& operator=(EndPortal&& other) noexcept = delete; void Initialize(const GameContext& gameContext) override; void Update(const GameContext& gameContext) override; private: DirectX::XMFLOAT3 m_Position; bool m_IsOpen = false, m_SoundIsPlaying = false; Character* m_Player; FMOD::Sound* m_pSound; };
/* * RandAI.cpp * * Created on: 27 Jul 2015 * Author: Jack */ #include "RandAI.h" RandAI::RandAI(cellState colour) { this->colour = colour; if(colour == M_WHITE) { direction = 1; } else { direction = -1; } } MoveSequence RandAI::getMove(Board board, int depth, bool nodeType) { std::vector<MoveSequence> movelist = getAvailableMoves(board); return movelist[rand() % movelist.size()]; }
#include<bits/stdc++.h> using namespace std; int main() { // only gravity will pull me down // Elements in the Range int t, n, A, B, flg; cin >> t; while (t--) { cin >> n >> A >> B; map<int, bool> mp; vector<int> a(n); for(int i=0; i<n; i++) { cin >> a[i]; mp[a[i]] = true; } flg = 0; for(int i=A; i<=B; i++) if(!mp[i]) { flg = 1; break; } flg ? cout << "No\n" : cout << "Yes\n"; } return 0; }
#pragma once #include <vector> namespace Utils { std::vector<int> generateNumber(int size); std::vector<int> randomNumber(int size, int min = std::numeric_limits<int>::min(), int max = std::numeric_limits<int>::max()); };
/*Implementation of timer queue module.*/ #include "cc/shared/timer_queue.h" #include "cc/shared/time_utils.h" #include <unistd.h> namespace cc_shared { using std::set; using std::unordered_map; TimerQueue::Collection::Collection() { } TimerQueue::Collection::~Collection() { RT_ASSERT(is_empty()); } int TimerQueue::Collection::size() { RT_ASSERT_EQ(handle_to_epoch_.size(), request_set_.size()); return request_set_.size(); } bool TimerQueue::Collection::is_empty() { return 0 == size(); } const TimerQueue::TimerQueuePayload& TimerQueue::Collection::peek() { return *(request_set_.begin()); } void TimerQueue::Collection::pop() { erase(request_set_.begin()); } void TimerQueue::Collection::insert(TimerQueuePayload payload) { RT_ASSERT_EQ( handle_to_epoch_.end(), handle_to_epoch_.find(payload.handle)); handle_to_epoch_[payload.handle] = payload.epoch_millis; request_set_.insert(payload); } void TimerQueue::Collection::erase(set<TimerQueuePayload>::iterator iter) { TimerQueuePayload payload = *iter; handle_to_epoch_.erase(payload.handle); request_set_.erase(iter); } bool TimerQueue::Collection::try_remove( int64 handle, ThreadPoolPayload* payload) { // First, try to find the epoch. If that does not work out, the item must have // been processed already. unordered_map<int64, int64>::iterator epoch_finder = handle_to_epoch_.find(handle); if (epoch_finder == handle_to_epoch_.end()) { return false; } // Next find the request and erase it. TimerQueuePayload candidate(epoch_finder->second, handle); set<TimerQueuePayload>::iterator request_finder = request_set_.find(candidate); RT_ASSERT_NE(request_set_.end(), request_finder); if (payload) { (*payload) = request_finder->payload; } erase(request_finder); return true; } TimerQueue::TimerQueue(ThreadPool* thread_pool) : thread_pool_(thread_pool), thread_(new(std::nothrow) ThreadWrapper), next_handle_(0), delay_is_absolute_(false), accepting_(true) { // There are some unit tests for which we don't want to start the processor // thread. if (thread_pool_) { thread_->start_thread(static_processor, static_cast<void*>(this), NULL); } } void TimerQueue::push_to_threadpool(ThreadPoolPayload payload) { if (thread_pool_) { thread_pool_->enqueue(payload); } } TimerQueue::~TimerQueue() { { MutexSafeAcquire safe_lock(&mutex_); accepting_ = false; } // Signal sleeping thread to wake up and finish pending items. event_.signal(); thread_->join(); RT_ASSERT_EQ(0, waiting_count_.get_snapshot()) << "Waiting thread must be woken up."; TimerQueuePayload payload; while (!collection_.is_empty()) { payload = collection_.peek(); collection_.pop(); push_to_threadpool(payload.payload); } } void TimerQueue::static_processor(void* parameter) { static_cast<TimerQueue*>(parameter)->processor(); } int64 TimerQueue::enqueue(int delay_milliseconds, ThreadPoolPayload payload) { MutexSafeAcquire safe_lock(&mutex_); RT_ASSERT(accepting_) << "Unexpected enqueue during destruction."; RT_ASSERT_GE(delay_milliseconds, 0) << "Cannot schedule for the past."; int64 epoch_millis = delay_milliseconds + ( delay_is_absolute_ ? 0 : get_epoch_milliseconds()); TimerQueuePayload outer_payload( epoch_millis, payload, (next_handle_++)); collection_.insert(outer_payload); // Awaken threads if needed. if (waiting_count_.get_snapshot() > 0) { event_.signal(); while (0 != waiting_count_.get_snapshot()) { usleep(1000); } event_.reset(); } return outer_payload.handle; } bool TimerQueue::try_cancel(int64 handle, ThreadPoolPayload* payload) { MutexSafeAcquire safe_lock(&mutex_); RT_ASSERT(accepting_) << "Unexpected cancellation during destruction."; return collection_.try_remove(handle, payload); } void TimerQueue::processor() { while (1) { bool do_push = false; bool do_quit = false; bool do_sleep = false; TimerQueuePayload payload; // Investigate state with lock held. { MutexSafeAcquire safe_lock(&mutex_); int64 current_epoch = get_epoch_milliseconds(); if (!accepting_) { // The collection may be non-empty here. However, destructor takes // care of emptying out the collection to the thread pool. do_quit = true; } else if (!collection_.is_empty()) { payload = collection_.peek(); if (payload.epoch_millis <= current_epoch) { collection_.pop(); do_push = true; } else { // Something is there, but we are not ready to execute it yet. do_sleep = true; } } else { // It is important to increment this before releasing the mutex. waiting_count_.increment_and_get(); } } if (do_push) { push_to_threadpool(payload.payload); } else if (do_quit) { break; } else if (do_sleep) { usleep(1000 * 100); } else { event_.wait_for_signal(); waiting_count_.decrement_and_get(); } } } } // cc_shared
//Sabrina Turney //May 29, 2019 //COP 2228 - C++ //Assignment 2 - Pointer.cpp //This program uses only pointers and the strlen() function to allow a string to be printed forward, backward, and forward again. //It is possible with any string input into the Name variable. #include "pch.h" //included for VS 2019 #include <iostream> //included for cout - No cin this time, since we're not asking for inputs. #include <cstring> //included for strlen(). #include "Pointer.h" using namespace std; int main() { const char *Name = "John Doe"; //Our pointer is given "Name" variable and uses it to point to a C-string. int Length = strlen(Name); //Here we get the length of the C-string and store in "Length". Here is where strlen() is used. cout << Name << endl; //First part of the program requires the string to be printed out. while (Length >= 0) //Using a while statement here to loop through the pointer. { cout << *(Name + --Length); //Pointer moves negatively through the string and prints each character. } cout << "\n" << Name << endl; //The program then prints out the original Name variable again, which is not changed. cout << "\n-------------------------------------------------"; return 0; //Returning 0 to finish program. }
/* * the test file of the Class String */ #include <iostream> #include "string.h" using std::cout; using std::endl; int main(void) { return 0; }
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "BlockchainSynchronizer.h" #include <functional> #include <iostream> #include <sstream> #include <thread> #include <unordered_set> #include "CryptoNoteCore/TransactionApi.h" #include "CryptoNoteCore/CryptoNoteFormatUtils.h" using namespace crypto; namespace { inline std::vector<uint8_t> stringToVector(const std::string& s) { std::vector<uint8_t> vec( reinterpret_cast<const uint8_t*>(s.data()), reinterpret_cast<const uint8_t*>(s.data()) + s.size()); return vec; } } namespace cn { BlockchainSynchronizer::BlockchainSynchronizer(INode& node, const Hash& genesisBlockHash) : m_node(node), m_genesisBlockHash(genesisBlockHash), m_currentState(State::stopped), m_futureState(State::stopped) { } BlockchainSynchronizer::~BlockchainSynchronizer() { stop(); } void BlockchainSynchronizer::addConsumer(IBlockchainConsumer* consumer) { assert(consumer != nullptr); assert(m_consumers.count(consumer) == 0); if (!(checkIfStopped() && checkIfShouldStop())) { throw std::runtime_error("Can't add consumer, because BlockchainSynchronizer isn't stopped"); } m_consumers.insert(std::make_pair(consumer, std::make_shared<SynchronizationState>(m_genesisBlockHash))); } bool BlockchainSynchronizer::removeConsumer(IBlockchainConsumer* consumer) { assert(consumer != nullptr); if (!(checkIfStopped() && checkIfShouldStop())) { throw std::runtime_error("Can't remove consumer, because BlockchainSynchronizer isn't stopped"); } return m_consumers.erase(consumer) > 0; } IStreamSerializable* BlockchainSynchronizer::getConsumerState(IBlockchainConsumer* consumer) const { std::unique_lock<std::mutex> lk(m_consumersMutex); return getConsumerSynchronizationState(consumer); } std::vector<crypto::Hash> BlockchainSynchronizer::getConsumerKnownBlocks(IBlockchainConsumer& consumer) const { std::unique_lock<std::mutex> lk(m_consumersMutex); auto state = getConsumerSynchronizationState(&consumer); if (state == nullptr) { throw std::invalid_argument("Consumer not found"); } return state->getKnownBlockHashes(); } std::future<std::error_code> BlockchainSynchronizer::addUnconfirmedTransaction(const ITransactionReader& transaction) { std::unique_lock<std::mutex> lock(m_stateMutex); if (m_currentState == State::stopped || m_futureState == State::stopped) { throw std::runtime_error("Can't add transaction, because BlockchainSynchronizer is stopped"); } std::promise<std::error_code> promise; auto future = promise.get_future(); m_addTransactionTasks.emplace_back(&transaction, std::move(promise)); m_hasWork.notify_one(); return future; } std::future<void> BlockchainSynchronizer::removeUnconfirmedTransaction(const crypto::Hash& transactionHash) { std::unique_lock<std::mutex> lock(m_stateMutex); if (m_currentState == State::stopped || m_futureState == State::stopped) { throw std::runtime_error("Can't remove transaction, because BlockchainSynchronizer is stopped"); } std::promise<void> promise; auto future = promise.get_future(); m_removeTransactionTasks.emplace_back(&transactionHash, std::move(promise)); m_hasWork.notify_one(); return future; } std::error_code BlockchainSynchronizer::doAddUnconfirmedTransaction(const ITransactionReader& transaction) { std::unique_lock<std::mutex> lk(m_consumersMutex); std::error_code ec; auto addIt = m_consumers.begin(); for (; addIt != m_consumers.end(); ++addIt) { ec = addIt->first->addUnconfirmedTransaction(transaction); if (ec) { break; } } if (ec) { auto transactionHash = transaction.getTransactionHash(); for (auto rollbackIt = m_consumers.begin(); rollbackIt != addIt; ++rollbackIt) { rollbackIt->first->removeUnconfirmedTransaction(transactionHash); } } return ec; } void BlockchainSynchronizer::doRemoveUnconfirmedTransaction(const crypto::Hash& transactionHash) { std::unique_lock<std::mutex> lk(m_consumersMutex); for (auto& consumer : m_consumers) { consumer.first->removeUnconfirmedTransaction(transactionHash); } } void BlockchainSynchronizer::save(std::ostream& os) { os.write(reinterpret_cast<const char*>(&m_genesisBlockHash), sizeof(m_genesisBlockHash)); } void BlockchainSynchronizer::load(std::istream& in) { Hash genesisBlockHash; in.read(reinterpret_cast<char*>(&genesisBlockHash), sizeof(genesisBlockHash)); if (genesisBlockHash != m_genesisBlockHash) { throw std::runtime_error("Genesis block hash does not match stored state"); } } //--------------------------- FSM ------------------------------------ bool BlockchainSynchronizer::setFutureState(State s) { return setFutureStateIf(s, [this, s] { return s > m_futureState; }); } bool BlockchainSynchronizer::setFutureStateIf(State s, std::function<bool(void)>&& pred) { std::unique_lock<std::mutex> lk(m_stateMutex); if (pred()) { m_futureState = s; m_hasWork.notify_one(); return true; } return false; } void BlockchainSynchronizer::actualizeFutureState() { std::unique_lock<std::mutex> lk(m_stateMutex); if (m_currentState == State::stopped && m_futureState == State::blockchainSync) { // start(), immediately attach observer m_node.addObserver(this); } if (m_futureState == State::stopped && m_currentState != State::stopped) { // stop(), immediately detach observer m_node.removeObserver(this); } while (!m_removeTransactionTasks.empty()) { auto& task = m_removeTransactionTasks.front(); const crypto::Hash& transactionHash = *task.first; auto detachedPromise = std::move(task.second); m_removeTransactionTasks.pop_front(); try { doRemoveUnconfirmedTransaction(transactionHash); detachedPromise.set_value(); } catch (...) { detachedPromise.set_exception(std::current_exception()); } } while (!m_addTransactionTasks.empty()) { auto& task = m_addTransactionTasks.front(); const ITransactionReader& transaction = *task.first; auto detachedPromise = std::move(task.second); m_addTransactionTasks.pop_front(); try { auto ec = doAddUnconfirmedTransaction(transaction); detachedPromise.set_value(ec); } catch (...) { detachedPromise.set_exception(std::current_exception()); } } m_currentState = m_futureState; switch (m_futureState) { case State::stopped: break; case State::blockchainSync: m_futureState = State::poolSync; lk.unlock(); startBlockchainSync(); break; case State::poolSync: m_futureState = State::idle; lk.unlock(); startPoolSync(); break; case State::idle: m_hasWork.wait(lk, [this] { return m_futureState != State::idle || !m_removeTransactionTasks.empty() || !m_addTransactionTasks.empty(); }); lk.unlock(); break; default: break; } } bool BlockchainSynchronizer::checkIfShouldStop() const { std::unique_lock<std::mutex> lk(m_stateMutex); return m_futureState == State::stopped; } bool BlockchainSynchronizer::checkIfStopped() const { std::unique_lock<std::mutex> lk(m_stateMutex); return m_currentState == State::stopped; } void BlockchainSynchronizer::workingProcedure() { while (!checkIfShouldStop()) { actualizeFutureState(); } actualizeFutureState(); } void BlockchainSynchronizer::start() { if (m_consumers.empty()) { throw std::runtime_error("Can't start, because BlockchainSynchronizer has no consumers"); } if (!setFutureStateIf(State::blockchainSync, [this] { return m_currentState == State::stopped && m_futureState == State::stopped; })) { throw std::runtime_error("BlockchainSynchronizer already started"); } workingThread.reset(new std::thread([this] { workingProcedure(); })); } void BlockchainSynchronizer::stop() { setFutureState(State::stopped); // wait for previous processing to end if (workingThread.get() != nullptr && workingThread->joinable()) { workingThread->join(); } workingThread.reset(); } void BlockchainSynchronizer::localBlockchainUpdated(uint32_t /*height*/) { setFutureState(State::blockchainSync); } void BlockchainSynchronizer::lastKnownBlockHeightUpdated(uint32_t /*height*/) { setFutureState(State::blockchainSync); } void BlockchainSynchronizer::poolChanged() { setFutureState(State::poolSync); } //--------------------------- FSM END ------------------------------------ void BlockchainSynchronizer::getPoolUnionAndIntersection(std::unordered_set<crypto::Hash>& poolUnion, std::unordered_set<crypto::Hash>& poolIntersection) const { std::unique_lock<std::mutex> lk(m_consumersMutex); auto itConsumers = m_consumers.begin(); poolUnion = itConsumers->first->getKnownPoolTxIds(); poolIntersection = itConsumers->first->getKnownPoolTxIds(); ++itConsumers; for (; itConsumers != m_consumers.end(); ++itConsumers) { const std::unordered_set<crypto::Hash>& consumerKnownIds = itConsumers->first->getKnownPoolTxIds(); poolUnion.insert(consumerKnownIds.begin(), consumerKnownIds.end()); for (auto itIntersection = poolIntersection.begin(); itIntersection != poolIntersection.end();) { if (consumerKnownIds.count(*itIntersection) == 0) { itIntersection = poolIntersection.erase(itIntersection); } else { ++itIntersection; } } } } BlockchainSynchronizer::GetBlocksRequest BlockchainSynchronizer::getCommonHistory() { GetBlocksRequest request; std::unique_lock<std::mutex> lk(m_consumersMutex); if (m_consumers.empty()) { return request; } auto shortest = m_consumers.begin(); auto syncStart = shortest->first->getSyncStart(); auto it = shortest; ++it; for (; it != m_consumers.end(); ++it) { if (it->second->getHeight() < shortest->second->getHeight()) { shortest = it; } auto consumerStart = it->first->getSyncStart(); syncStart.timestamp = std::min(syncStart.timestamp, consumerStart.timestamp); syncStart.height = std::min(syncStart.height, consumerStart.height); } request.knownBlocks = shortest->second->getShortHistory(m_node.getLastLocalBlockHeight()); request.syncStart = syncStart; return request; } void BlockchainSynchronizer::startBlockchainSync() { GetBlocksResponse response; GetBlocksRequest req = getCommonHistory(); try { if (!req.knownBlocks.empty()) { auto queryBlocksCompleted = std::promise<std::error_code>(); auto queryBlocksWaitFuture = queryBlocksCompleted.get_future(); m_node.queryBlocks( std::move(req.knownBlocks), req.syncStart.timestamp, response.newBlocks, response.startHeight, [&queryBlocksCompleted](std::error_code ec) { auto detachedPromise = std::move(queryBlocksCompleted); detachedPromise.set_value(ec); }); std::error_code ec = queryBlocksWaitFuture.get(); if (ec) { setFutureStateIf(State::idle, [this] { return m_futureState != State::stopped; }); m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, ec); } else { processBlocks(response); } } } catch (std::exception&) { setFutureStateIf(State::idle, [this] { return m_futureState != State::stopped; }); m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, std::make_error_code(std::errc::invalid_argument)); } } void BlockchainSynchronizer::processBlocks(GetBlocksResponse& response) { BlockchainInterval interval; interval.startHeight = response.startHeight; std::vector<CompleteBlock> blocks; for (auto& block : response.newBlocks) { if (checkIfShouldStop()) { break; } CompleteBlock completeBlock; completeBlock.blockHash = block.blockHash; interval.blocks.push_back(completeBlock.blockHash); if (block.hasBlock) { completeBlock.block = std::move(block.block); completeBlock.transactions.push_back(createTransactionPrefix(completeBlock.block->baseTransaction)); try { for (const auto& txShortInfo : block.txsShortInfo) { completeBlock.transactions.push_back(createTransactionPrefix(txShortInfo.txPrefix, reinterpret_cast<const Hash&>(txShortInfo.txId))); } } catch (std::exception&) { setFutureStateIf(State::idle, [this] { return m_futureState != State::stopped; }); m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, std::make_error_code(std::errc::invalid_argument)); return; } } blocks.push_back(std::move(completeBlock)); } uint32_t processedBlockCount = response.startHeight + static_cast<uint32_t>(response.newBlocks.size()); if (!checkIfShouldStop()) { response.newBlocks.clear(); std::unique_lock<std::mutex> lk(m_consumersMutex); auto result = updateConsumers(interval, blocks); lk.unlock(); switch (result) { case UpdateConsumersResult::errorOccurred: if (setFutureStateIf(State::idle, [this] { return m_futureState != State::stopped; })) { m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, std::make_error_code(std::errc::invalid_argument)); } break; case UpdateConsumersResult::nothingChanged: if (m_node.getLastKnownBlockHeight() != m_node.getLastLocalBlockHeight()) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } else { break; } case UpdateConsumersResult::addedNewBlocks: setFutureState(State::blockchainSync); m_observerManager.notify( &IBlockchainSynchronizerObserver::synchronizationProgressUpdated, processedBlockCount, std::max(m_node.getKnownBlockCount(), m_node.getLocalBlockCount())); break; } if (!blocks.empty()) { lastBlockId = blocks.back().blockHash; } } if (checkIfShouldStop()) { //Sic! m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, std::make_error_code(std::errc::interrupted)); } } /// \pre m_consumersMutex is locked BlockchainSynchronizer::UpdateConsumersResult BlockchainSynchronizer::updateConsumers(const BlockchainInterval& interval, const std::vector<CompleteBlock>& blocks) { bool smthChanged = false; for (auto& kv : m_consumers) { auto result = kv.second->checkInterval(interval); if (result.detachRequired) { kv.first->onBlockchainDetach(result.detachHeight); kv.second->detach(result.detachHeight); } if (result.hasNewBlocks) { uint32_t startOffset = result.newBlockHeight - interval.startHeight; // update consumer if (kv.first->onNewBlocks(blocks.data() + startOffset, result.newBlockHeight, static_cast<uint32_t>(blocks.size()) - startOffset)) { // update state if consumer succeeded kv.second->addBlocks(interval.blocks.data() + startOffset, result.newBlockHeight, static_cast<uint32_t>(interval.blocks.size()) - startOffset); smthChanged = true; } else { return UpdateConsumersResult::errorOccurred; } } } return smthChanged ? UpdateConsumersResult::addedNewBlocks : UpdateConsumersResult::nothingChanged; } void BlockchainSynchronizer::startPoolSync() { std::unordered_set<crypto::Hash> unionPoolHistory; std::unordered_set<crypto::Hash> intersectedPoolHistory; getPoolUnionAndIntersection(unionPoolHistory, intersectedPoolHistory); GetPoolRequest unionRequest; unionRequest.knownTxIds.assign(unionPoolHistory.begin(), unionPoolHistory.end()); unionRequest.lastKnownBlock = lastBlockId; GetPoolResponse unionResponse; unionResponse.isLastKnownBlockActual = false; std::error_code ec = getPoolSymmetricDifferenceSync(std::move(unionRequest), unionResponse); if (ec) { setFutureStateIf(State::idle, [this] { return m_futureState != State::stopped; }); m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, ec); } else { //get union ok if (!unionResponse.isLastKnownBlockActual) { //bc outdated setFutureState(State::blockchainSync); } else { if (unionPoolHistory == intersectedPoolHistory) { //usual case, start pool processing m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, processPoolTxs(unionResponse)); } else { GetPoolRequest intersectionRequest; intersectionRequest.knownTxIds.assign(intersectedPoolHistory.begin(), intersectedPoolHistory.end()); intersectionRequest.lastKnownBlock = lastBlockId; GetPoolResponse intersectionResponse; intersectionResponse.isLastKnownBlockActual = false; std::error_code ec2 = getPoolSymmetricDifferenceSync(std::move(intersectionRequest), intersectionResponse); if (ec2) { setFutureStateIf(State::idle, [this] { return m_futureState != State::stopped; }); m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, ec2); } else { //get intersection ok if (!intersectionResponse.isLastKnownBlockActual) { //bc outdated setFutureState(State::blockchainSync); } else { intersectionResponse.deletedTxIds.assign(unionResponse.deletedTxIds.begin(), unionResponse.deletedTxIds.end()); std::error_code ec3 = processPoolTxs(intersectionResponse); //notify about error, or success m_observerManager.notify(&IBlockchainSynchronizerObserver::synchronizationCompleted, ec3); } } } } } } std::error_code BlockchainSynchronizer::getPoolSymmetricDifferenceSync(GetPoolRequest&& request, GetPoolResponse& response) { auto promise = std::promise<std::error_code>(); auto future = promise.get_future(); m_node.getPoolSymmetricDifference( std::move(request.knownTxIds), std::move(request.lastKnownBlock), response.isLastKnownBlockActual, response.newTxs, response.deletedTxIds, [&promise](std::error_code ec) { auto detachedPromise = std::move(promise); detachedPromise.set_value(ec); }); return future.get(); } std::error_code BlockchainSynchronizer::processPoolTxs(GetPoolResponse& response) { std::error_code error; { std::unique_lock<std::mutex> lk(m_consumersMutex); for (auto& consumer : m_consumers) { if (checkIfShouldStop()) { //if stop, return immediately, without notification return std::make_error_code(std::errc::interrupted); } error = consumer.first->onPoolUpdated(response.newTxs, response.deletedTxIds); if (error) { break; } } } return error; } ///pre: m_consumersMutex is locked SynchronizationState* BlockchainSynchronizer::getConsumerSynchronizationState(IBlockchainConsumer* consumer) const { assert(consumer != nullptr); if (!(checkIfStopped() && checkIfShouldStop())) { throw std::runtime_error("Can't get consumer state, because BlockchainSynchronizer isn't stopped"); } auto it = m_consumers.find(consumer); if (it == m_consumers.end()) { return nullptr; } return it->second.get(); } }
#include "Scene.h" void Load() { TextureAsset::Register(L"title_back", L"Data/title_back.png"); TextureAsset::Register(L"play", L"Data/play.png"); TextureAsset::Register(L"tips", L"Data/tips.png"); TextureAsset::Register(L"ranking", L"Data/rank.png"); TextureAsset::Register(L"exit", L"Data/exit.png"); TextureAsset::Register(L"Back", L"Data/background.png"); TextureAsset::Register(L"enemy", L"Data/enemy.jpg"); FontAsset::Register(L"memo", 20); } void Main() { SceneManager<String> manager; manager.add<Title>(L"Title"); manager.add<Game>(L"Game"); manager.add<Result>(L"Result"); manager.add<Ranking>(L"Ranking"); Window::Resize(1024, 640); Load(); while (System::Update()) { //manager.setFadeColor(Color(255, 255, 255)); manager.updateAndDraw(); } }
#include <algorithm> #include <cerrno> #include <chrono> #include <cstdlib> #include <exception> #include <iostream> #include <iterator> #include <sstream> #include <thread> #include <unordered_set> #include <dispatcher/Environment.h> #include <dispatcher/kernelTestGraph.h> //#include <test/TPCH.hpp> #include "benchmarks/tpch/Queries.hpp" #include "common/runtime/Import.hpp" #include "profile.hpp" #include "tbb/tbb.h" using namespace runtime; static void escape(void* p) { asm volatile("" : : "g"(p) : "memory"); } size_t nrTuples(Database& db, std::vector<std::string> tables) { size_t sum = 0; for (auto& table : tables) sum += db[table].nrTuples; return sum; } /// Clears Linux page cache. /// This function only works on Linux. void clearOsCaches() { if (system("sync; echo 3 > /proc/sys/vm/drop_caches")) { throw std::runtime_error("Could not flush system caches: " + std::string(std::strerror(errno))); } } static size_t vectorSize = 1024; static size_t getThreads(){ static size_t threads = 0; if(threads == 0){ if (auto v = std::getenv("threads")) threads = atoi(v); else threads = std::thread::hardware_concurrency(); } return threads; } static void configFromEnv(){ if (auto v = std::getenv("vectorSize")) vectorSize = atoi(v); if (auto v = std::getenv("SIMDhash")) conf.useSimdHash = atoi(v); if (auto v = std::getenv("SIMDjoin")) conf.useSimdJoin = atoi(v); if (auto v = std::getenv("SIMDsel")) conf.useSimdSel = atoi(v); if (auto v = std::getenv("SIMDproj")) conf.useSimdProj = atoi(v); } static runtime::Database tpch; using namespace std; types::Integer* getColumnPointer(string tableName, string attributeName){ runtime::Attribute& a = tpch[tableName][attributeName]; cout<<a.data_.size()<<endl; auto columnPointer = a.data<types::Integer>(); return columnPointer; } void columnTest(){ auto l_ship = getColumnPointer("lineitem","l_shipdate"); std::cout<<"Test : "<<l_ship[0]<<std::endl; } void tectorwise(){ cout<<"Tectorwise\n"; auto threads = getThreads(); tbb::task_scheduler_init scheduler(threads); auto s1 = std::chrono::high_resolution_clock::now(); auto result = q6_vectorwise(tpch, threads, vectorSize); auto s2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::nano> fp_ms = s2 - s1; std::chrono::duration<double, std::milli> ms = s2 - s1; std::cout<<"Execution Time : "<<fp_ms.count()<<"\t milli : "<<ms.count()<<std::endl; // auto& revenue = result["revenue"].typedAccess<types::Numeric<12, 4>>(); int* revenue = result["revenue"].data<int>(); std::cout<<"Revenue : "<<*revenue<<std::endl; } void typer(){ cout<<"Typer\n"; auto s1 = std::chrono::high_resolution_clock::now(); auto result = q6_hyper(tpch); auto s2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::nano> fp_ms = s2 - s1; std::chrono::duration<double, std::milli> ms = s2 - s1; std::cout<<"Execution Time : "<<fp_ms.count()<<"\t milli : "<<ms.count()<<std::endl; int* revenue = result["revenue"].data<int>(); std::cout<<"Revenue : "<<*revenue<<std::endl; } void dispatcherQ6(){ cout<<"Dispatcher\n"; dispatcher::setup_environment(); auto s1 = std::chrono::high_resolution_clock::now(); unsigned int result = dispatcher::q6Dispatcher(); auto s2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double, std::nano> fp_ms = s2 - s1; std::chrono::duration<double, std::milli> ms = s2 - s1; std::cout<<"Execution Time : "<<fp_ms.count()<<"\t milli : "<<ms.count()<<std::endl; std::cout<<"Revenue : "<<result<<std::endl; } void testQ6(){ // clearOsCaches(); tectorwise(); dispatcherQ6(); typer(); } void hook(){ importTPCH(std::string(DATADIR)+"/tpch/sf1/",tpch); testQ6(); // std::cout<<"Changing the execution here"<<std::endl; // std::cout<<"Testing vectorized execution"<<std::endl; // // importTPCH(std::string(DATADIR)+"/tpch/sf1/",tpch); // // columnTest(); // // dispatcher::setup_environment(); // dispatcher::print_environment(); // // auto threads = getThreads(); // tbb::task_scheduler_init scheduler(threads); // // // // auto s1 = std::chrono::high_resolution_clock::now(); // auto result = q6_vectorwise(tpch, threads, vectorSize); // auto s2 = std::chrono::high_resolution_clock::now(); // // std::chrono::duration<double, std::nano> fp_ms = s2 - s1; // // std::cout<<"Execution Time : "<<fp_ms.count()<<std::endl; // // auto& revenue = result["revenue"].typedAccess<types::Numeric<12, 4>>(); // std::cout<<"Revenue : "<<revenue[0]<<std::endl; //Reading data from database exit(0); } int main(int argc, char* argv[]) { hook(); if (argc <= 2) { std::cerr << "Usage: ./" << argv[0] << "<number of repetitions> <path to tpch dir> [nrThreads = all] \n " " EnvVars: [vectorSize = 1024] [SIMDhash = 0] [SIMDjoin = 0] " "[SIMDsel = 0]"; exit(1); } PerfEvents e; Database tpch; // load tpch data importTPCH(argv[2], tpch); // run queries auto repetitions = atoi(argv[1]); size_t nrThreads = std::thread::hardware_concurrency(); size_t vectorSize = 1024; bool clearCaches = false; if (argc > 3) nrThreads = atoi(argv[3]); std::unordered_set<std::string> q = {"1h", "1v", "3h", "3v", "5h", "5v", "6h", "6v", "9h", "9v", "18h", "18v"}; if (auto v = std::getenv("vectorSize")) vectorSize = atoi(v); if (auto v = std::getenv("SIMDhash")) conf.useSimdHash = atoi(v); if (auto v = std::getenv("SIMDjoin")) conf.useSimdJoin = atoi(v); if (auto v = std::getenv("SIMDsel")) conf.useSimdSel = atoi(v); if (auto v = std::getenv("SIMDproj")) conf.useSimdProj = atoi(v); if (auto v = std::getenv("clearCaches")) clearCaches = atoi(v); if (auto v = std::getenv("q")) { using namespace std; istringstream iss((string(v))); q.clear(); copy(istream_iterator<string>(iss), istream_iterator<string>(), insert_iterator<decltype(q)>(q, q.begin())); } tbb::task_scheduler_init scheduler(nrThreads); if (q.count("1h")) e.timeAndProfile("q1 hyper ", nrTuples(tpch, {"lineitem"}), [&]() { if (clearCaches) clearOsCaches(); auto result = q1_hyper(tpch, nrThreads); escape(&result); }, repetitions); if (q.count("1v")) e.timeAndProfile("q1 vectorwise", nrTuples(tpch, {"lineitem"}), [&]() { if (clearCaches) clearOsCaches(); auto result = q1_vectorwise(tpch, nrThreads, vectorSize); escape(&result); }, repetitions); if (q.count("3h")) e.timeAndProfile("q3 hyper ", nrTuples(tpch, {"customer", "orders", "lineitem"}), [&]() { if (clearCaches) clearOsCaches(); auto result = q3_hyper(tpch, nrThreads); escape(&result); }, repetitions); if (q.count("3v")) e.timeAndProfile( "q3 vectorwise", nrTuples(tpch, {"customer", "orders", "lineitem"}), [&]() { if (clearCaches) clearOsCaches(); auto result = q3_vectorwise(tpch, nrThreads, vectorSize); escape(&result); }, repetitions); if (q.count("5h")) e.timeAndProfile("q5 hyper ", nrTuples(tpch, {"supplier", "region", "nation", "customer", "orders", "lineitem"}), [&]() { if (clearCaches) clearOsCaches(); auto result = q5_hyper(tpch, nrThreads); escape(&result); }, repetitions); if (q.count("5v")) e.timeAndProfile("q5 vectorwise", nrTuples(tpch, {"supplier", "region", "nation", "customer", "orders", "lineitem"}), [&]() { if (clearCaches) clearOsCaches(); auto result = q5_vectorwise(tpch, nrThreads, vectorSize); escape(&result); }, repetitions); if (q.count("6h")) e.timeAndProfile("q6 hyper ", tpch["lineitem"].nrTuples, [&]() { if (clearCaches) clearOsCaches(); auto result = q6_hyper(tpch, nrThreads); escape(&result); }, repetitions); if (q.count("6v")) e.timeAndProfile("q6 vectorwise", tpch["lineitem"].nrTuples, [&]() { if (clearCaches) clearOsCaches(); auto result = q6_vectorwise(tpch, nrThreads, vectorSize); escape(&result); }, repetitions); if (q.count("9h")) e.timeAndProfile("q9 hyper ", nrTuples(tpch, {"nation", "supplier", "part", "partsupp", "lineitem", "orders"}), [&]() { if (clearCaches) clearOsCaches(); auto result = q9_hyper(tpch, nrThreads); escape(&result); }, repetitions); if (q.count("9v")) e.timeAndProfile("q9 vectorwise", nrTuples(tpch, {"nation", "supplier", "part", "partsupp", "lineitem", "orders"}), [&]() { if (clearCaches) clearOsCaches(); auto result = q9_vectorwise(tpch, nrThreads, vectorSize); escape(&result); }, repetitions); if (q.count("18h")) e.timeAndProfile( "q18 hyper ", nrTuples(tpch, {"customer", "lineitem", "orders", "lineitem"}), [&]() { if (clearCaches) clearOsCaches(); auto result = q18_hyper(tpch, nrThreads); escape(&result); }, repetitions); if (q.count("18v")) e.timeAndProfile( "q18 vectorwise", nrTuples(tpch, {"customer", "lineitem", "orders", "lineitem"}), [&]() { if (clearCaches) clearOsCaches(); auto result = q18_vectorwise(tpch, nrThreads, vectorSize); escape(&result); }, repetitions); scheduler.terminate(); return 0; }
#ifndef MODULEBASE_H #define MODULEBASE_H #include "Context.hpp" #include "StdIncl.hpp" #include "types/Data.hpp" #include "Utils.hpp" #include "Logger.hpp" #include "InvalidConfigException.hpp" #include "MetaData.hpp" #include "ModuleInterface.hpp" #include "DataManager.hpp" namespace uipf{ // Methods and Data all Moduls share class ModuleBase : public ModuleInterface { public: ModuleBase(); ModuleBase(const std::string& name):name_(name){}; virtual ~ModuleBase(); // context is a container providing access to the current environment, allowing to open windows, write to logger etc... virtual void setContext(Context*) Q_DECL_OVERRIDE; // the name of the module, which can be referenced in the yaml configuration virtual std::string name() const Q_DECL_OVERRIDE; public: //interface methods that still must be implemented by subclasses virtual void run( DataManager& data ) const = 0; // meta data that contains description of modules inputs, outputs and parameters virtual uipf::MetaData getMetaData() const = 0 ; protected: Context* context_; std::string name_; }; } //namespace #endif // MODULEBASE_H
#include "game.h" #include "terrain.h" #include <QtDebug> #include <Qt3DRenderer/QDirectionalLight> #include "inputhandler.h" #include "player.h" Game* Game::g_pGlobalInstance = NULL; Game::Game(QObject *parent) : QObject(parent) { Q_ASSERT(!g_pGlobalInstance); g_pGlobalInstance = this; initialise(); } Game::~Game() { // The aspect engine is not parented to us because it needs to be shut down before the window. m_pWindow->removeEventFilter(m_pInputHandler); delete m_pInputHandler; delete m_pAspectEngine; delete m_pWindow; } Qt3D::Window* Game::window() { return m_pWindow; } const Qt3D::Window* Game::window() const { return m_pWindow; } Qt3D::QAspectEngine* Game::aspectEngine() { return m_pAspectEngine; } const Qt3D::QAspectEngine* Game::aspectEngine() const { return m_pAspectEngine; } void Game::initialise() { // Create a window and an aspect engine. m_pWindow = new Qt3D::Window(); m_pWindow->setTitle("Mining Game"); m_pAspectEngine = new Qt3D::QAspectEngine(); // Set up the aspect engine to deal with rendering tasks. m_Aspects.render = new Qt3D::QRenderAspect(); m_pAspectEngine->registerAspect(m_Aspects.render); // Also deal with input for the camera. m_Aspects.input = new Qt3D::QInputAspect(); m_pAspectEngine->registerAspect(m_Aspects.input); m_pInputHandler = new InputHandler(); m_pWindow->installEventFilter(m_pInputHandler); m_pInputHandler->addMapping(Qt::Key_W, "onUp(bool)"); m_pInputHandler->addMapping(Qt::Key_A, "onLeft(bool)"); m_pInputHandler->addMapping(Qt::Key_S, "onDown(bool)"); m_pInputHandler->addMapping(Qt::Key_D, "onRight(bool)"); // Initialise the engine. (Not sure exactly what this does) m_pAspectEngine->initialize(); // Set the engine data. (Not sure exactly what this does either) QVariantMap data; data.insert(QStringLiteral("surface"), QVariant::fromValue(static_cast<QSurface *>(m_pWindow))); // This passes a pointer to the window under the property name "eventSource" in order for the input // aspect to receive key/mouse events from the window. data.insert(QStringLiteral("eventSource"), QVariant::fromValue(m_pWindow)); m_pAspectEngine->setData(data); // Root entity - everything is parented to this m_pRootEntity = new Qt3D::QEntity(); // Light Qt3D::QDirectionalLight* light = new Qt3D::QDirectionalLight(); light->setColor(Qt::white); light->setIntensity(1.5f); light->setDirection(QVector3D(0,-1,-1).normalized()); m_pRootEntity->addComponent(light); // Player m_pPlayer = new Player(m_pRootEntity); connect(m_pInputHandler, SIGNAL(onUp(bool)), m_pPlayer, SLOT(moveUp(bool))); connect(m_pInputHandler, SIGNAL(onDown(bool)), m_pPlayer, SLOT(moveDown(bool))); connect(m_pInputHandler, SIGNAL(onLeft(bool)), m_pPlayer, SLOT(moveLeft(bool))); connect(m_pInputHandler, SIGNAL(onRight(bool)), m_pPlayer, SLOT(moveRight(bool))); // Camera m_pCamera = new Qt3D::QCamera(m_pPlayer); m_pCamera->lens()->setPerspectiveProjection(45.0f, 16.0f/9.0f, 0.1f, 1000.0f); m_pCamera->setPosition(QVector3D(0, 0, 40.0f)); m_pCamera->setUpVector(QVector3D(0, 1, 0)); m_pCamera->setViewCenter(QVector3D(0, 0, 0)); m_Aspects.input->setCamera(m_pCamera); // FrameGraph m_pFrameGraph = new Qt3D::QFrameGraph(); m_pForwardRenderer = new Qt3D::QForwardRenderer(); m_pForwardRenderer->setClearColor(QColor::fromRgbF(0.0, 0.5, 1.0, 1.0)); m_pForwardRenderer->setCamera(m_pCamera); m_pFrameGraph->setActiveFrameGraph(m_pForwardRenderer); // Dummy terrain m_pTerrain = new Terrain(this); m_pTerrain->setScale(3); for ( int i = 0; i < TERRAIN_DIMENSION; i++ ) { for ( int j = 0; j < TERRAIN_DIMENSION; j++ ) { double r = (double)qrand()/(double)RAND_MAX; if ( r <= 0.4 ) m_pTerrain->insertBlock(i,j); } } QVector3D c = m_pTerrain->centroid(); m_pCamera->setViewCenter(c); c.setZ(40); m_pCamera->setPosition(c); m_pRootEntity->addComponent(m_pFrameGraph); m_pAspectEngine->setRootEntity(m_pRootEntity); } void Game::show() { m_pWindow->show(); } Qt3D::QEntity* Game::rootEntity() { return m_pRootEntity; } const Qt3D::QEntity* Game::rootEntity() const { return m_pRootEntity; } Game* Game::gameInstance() { return g_pGlobalInstance; }
#include "SceneLose.h" #include "../Mains/Application.h" #include "../Systems/EventSystem.h" #include "../Audio/Audio_Player.h" #include "../../Base/Source/Main/Engine/System/SceneSystem.h" #include "../../Base/Source/Main/Engine/System/RenderSystem.h" #include "../Systems/BattleSystem.h" #include "../Miscellaneous/Button.h" SceneLose::SceneLose() { } SceneLose::~SceneLose() { } void SceneLose::Init() { this->SetEntityID("Lose_Scene"); camera.Init(Vector3(0, 0, 1), Vector3(0, 0, 0), Vector3(0, 1, 0)); timer = 0.f; youlose = "You Lost!"; } void SceneLose::Update(float dt) { timer += dt; if (InputManager::Instance().GetMouseState(MOUSE_L) == CLICK && timer > 5.f) { for (auto it : BattleSystem::Instance().GetPlayerTroops()) { if (it.second->GetDefeated()) { for (auto it2 : Player::Instance().GetAllUnitList()) { if (it2.first == "Warrior") { for (auto it3 : Player::Instance().GetClassUnitList("Warrior")) { if (it3.second == it.second) { Player::Instance().GetAllUnitList().at("Warrior").erase(it3.first); CharacterEntity* mage = new Warrior(); mage->Init(1); Player::Instance().AddCharacter("Warrior", mage); delete it.second; it.second = nullptr; break; } } } else if (it2.first == "Mage") { for (auto it3 : Player::Instance().GetClassUnitList("Mage")) { if (it3.second == it.second) { Player::Instance().GetAllUnitList().at("Mage").erase(it3.first); CharacterEntity* mage = new Mage(); mage->Init(1); Player::Instance().AddCharacter("Mage", mage); delete it.second; it.second = nullptr; break; } } } else if (it2.first == "Synergist") { for (auto it3 : Player::Instance().GetClassUnitList("Synergist")) { if (it3.second == it.second) { Player::Instance().GetAllUnitList().at("Synergist").erase(it3.first); CharacterEntity* mage = new Synergist(); mage->Init(1); Player::Instance().AddCharacter("Synergist", mage); delete it.second; it.second = nullptr; break; } } } } } } BattleSystem::Instance().Reset(); SceneSystem::Instance().SwitchScene("Town_Scene"); } } void SceneLose::Render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Calculating aspect ratio RenderSystem *Renderer = dynamic_cast<RenderSystem*>(&SceneSystem::Instance().GetRenderSystem()); // Projection matrix : Orthographic Projection Mtx44 projection; projection.SetToOrtho(0, ObjectManager::Instance().WorldWidth, 0, ObjectManager::Instance().WorldHeight, -10, 10); projectionStack->LoadMatrix(projection); // Camera matrix viewStack->LoadIdentity(); viewStack->LookAt( camera.position.x, camera.position.y, camera.position.z, camera.target.x, camera.target.y, camera.target.z, camera.up.x, camera.up.y, camera.up.z ); // Model matrix : an identity matrix (model will be at the origin) modelStack->LoadIdentity(); modelStack->PushMatrix(); modelStack->Translate((ObjectManager::Instance().WorldWidth * 0.5f) - (youlose.size() * 4.3f), ObjectManager::Instance().WorldHeight * 0.8f, -5.f); modelStack->Scale(15, 15, 1); Renderer->RenderText("text", youlose, Color(1, 0, 0)); modelStack->PopMatrix(); } void SceneLose::Exit() { ObjectManager::Instance().Exit(); }
#include<bits/stdc++.h> using namespace std; const int maxn = 2e5+5; struct edge{ int a,b,w; }e[maxn]; bool cmp(const edge&A,const edge&B){ return A.w<B.w; } int f[maxn],n,m,ans,a,b; void init(){ for(int i=1;i<=n;++i)f[i]=i; } int find(int x){ return x==f[x]?x:f[x]=find(f[x]); } int main(){ scanf("%d%d",&n,&m); for(int i=0;i<m;++i)scanf("%d%d%d",&e[i].a,&e[i].b,&e[i].w); init(); sort(e,e+m,cmp); for(int i=0;i<m;++i){ a=find(e[i].a);b=find(e[i].b); if(a!=b){ f[a]=b; if(find(1)==find(n)){ ans=e[i].w; break; } } } printf("%d\n",ans); }
// // Created by heyhey on 20/03/2018. // #ifndef PLDCOMP_EXPRESSION_H #define PLDCOMP_EXPRESSION_H #include <string> #include <ostream> #include "Instruction.h" using namespace std; class Expression : public Instruction { public: Expression(); Expression(const string &valeur); virtual ~Expression(); private: string valeur; //?? pas sur qu'on en est besoin ¯\_(ツ)_/¯ public: const string &getValeur() const; void setValeur(const string &valeur); friend ostream &operator<<(ostream &os, const Expression &expression); }; #endif //PLDCOMP_EXPRESSION_H
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2010 Gael Guennebaud <g.gael@free.fr> // // Eigen is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3 of the License, or (at your option) any later version. // // Alternatively, 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. // // Eigen 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 Lesser General Public License or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "sparse.h" #include <Eigen/SparseExtra> #ifdef EIGEN_CHOLMOD_SUPPORT #include <Eigen/CholmodSupport> #endif #ifdef EIGEN_TAUCS_SUPPORT #include <Eigen/TaucsSupport> #endif template<typename Scalar> void sparse_llt(int rows, int cols) { double density = std::max(8./(rows*cols), 0.01); typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix; typedef Matrix<Scalar,Dynamic,1> DenseVector; // TODO fix the issue with complex (see SparseLLT::solveInPlace) SparseMatrix<Scalar> m2(rows, cols); DenseMatrix refMat2(rows, cols); DenseVector b = DenseVector::Random(cols); DenseVector refX(cols), x(cols); initSparse<Scalar>(density, refMat2, m2, ForceNonZeroDiag|MakeLowerTriangular, 0, 0); for(int i=0; i<rows; ++i) m2.coeffRef(i,i) = refMat2(i,i) = ei_abs(ei_real(refMat2(i,i))); refX = refMat2.template selfadjointView<Lower>().llt().solve(b); if (!NumTraits<Scalar>::IsComplex) { x = b; SparseLLT<SparseMatrix<Scalar> > (m2).solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LLT: default"); } #ifdef EIGEN_CHOLMOD_SUPPORT x = b; SparseLLT<SparseMatrix<Scalar> ,Cholmod>(m2).solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LLT: cholmod"); #endif #ifdef EIGEN_TAUCS_SUPPORT // TODO fix TAUCS with complexes if (!NumTraits<Scalar>::IsComplex) { x = b; // SparseLLT<SparseMatrix<Scalar> ,Taucs>(m2,IncompleteFactorization).solveInPlace(x); // VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LLT: taucs (IncompleteFactorization)"); x = b; SparseLLT<SparseMatrix<Scalar> ,Taucs>(m2,SupernodalMultifrontal).solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LLT: taucs (SupernodalMultifrontal)"); x = b; SparseLLT<SparseMatrix<Scalar> ,Taucs>(m2,SupernodalLeftLooking).solveInPlace(x); VERIFY(refX.isApprox(x,test_precision<Scalar>()) && "LLT: taucs (SupernodalLeftLooking)"); } #endif } void test_sparse_llt() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1(sparse_llt<double>(8, 8) ); int s = ei_random<int>(1,300); CALL_SUBTEST_2(sparse_llt<std::complex<double> >(s,s) ); CALL_SUBTEST_1(sparse_llt<double>(s,s) ); } }
#include <iostream> const int ArrSize = 8; int sumarr(const int * begin, const int * end); int main() { using namespace std; int cookies[ArrSize] = { 1,2,4,8,16,32,64,128 }; int sum = sumarr(cookies, cookies + ArrSize); cout << "Total cookies eaten: " << sum << endl; cout << "First three eaters ate: " << sumarr(cookies, cookies + 3) << endl; cout << "Last four eaters ate: " << sumarr(cookies + 4, cookies + 8); while (cin.get() != 'q') { ; } return 0; } int sumarr(const int * begin, const int * end) // 这个声明防止通过这个指针对数据就行修改,保护数据 { const int * pt; // 将指针指向一个常量,防止(通过指针!!!)修改这个量,这个量本身可能被通过其他形式进行修改, // 这说明变量的地址可以赋给const指针,同时这个指针本身的指向是可变的,但是仍然不可以通过它修改变量值 // C++禁止将const变量的地址赋给非cosnt指针,即 const a = 10; int * p = &a; 是非法的!!! // 而 const a = 10; const int * p = &a; 是合法的!!! // int a = 3; int * const p = &a; 这个声明方式使得p只能指向a!!! int total = 0; for (pt = begin; pt != end; pt++) { total += *pt; } return total; }
#include "Map.hpp" #include "ResourceLoader.hpp" #include "SoundEngine.hpp" #include "Player.hpp" #include <cstring> #include <fstream> #include <iostream> #include <stdexcept> Map::Map(const std::string &filename, Player *player) : m_Array(nullptr), m_Width(0), m_Height(0), m_RegionName("E1"), m_MapName("M1"), m_CeilingColor(sf::Color(56, 56, 56)), m_FloorColor(sf::Color(112, 112, 112)), m_Texture("Images/walls.png"), m_Player(player) { Load(filename); } Map::~Map() { // delete sprites for (auto sprite : m_Sprites) { delete sprite; } // delete map delete[] m_Array; } void Map::Tick(float dt) { // door sliding for (auto itr = m_MovingDoors.begin(); itr != m_MovingDoors.end();) { itr->second += dt; if (itr->second >= 1.f) { m_OpenDoors.insert(itr->first); itr = m_MovingDoors.erase(itr); } else ++itr; } // sprite tick for (auto sprite : m_Sprites) { if (sprite->IsDirectional()) sprite->SetViewerPosition(m_Player->GetPosition()); sprite->Tick(dt); } } Wall Map::Get(int x, int y) const { if (m_Array) return m_Array[m_Width*y + x]; return 0; } Wall Map::Get(int p) const { if (m_Array) return m_Array[p]; return 0; } void Map::Set(int x, int y, Wall value) { if (m_Array) m_Array[m_Width*y + x] = value.value; } void Map::Set(int p, Wall value) { if (m_Array) m_Array[p] = value.value; } bool Map::IsWall(int x, int y) const { return Get(x, y).value != 0; } bool Map::IsWall(int p) const { return Get(p).value != 0; } bool Map::IsDoor(int x, int y) const { return (Get(x, y).flags & (int)WallFlags::DOOR) == (int)WallFlags::DOOR; } bool Map::IsDoor(int p) const { return (Get(p).flags & (int)WallFlags::DOOR) == (int)WallFlags::DOOR; } void Map::OpenDoor(int x, int y) { m_MovingDoors[y*m_Width + x] = 0.f; SoundEngine::PlaySound("Sounds/door.wav", sf::Vector2f(x + 0.5f, y+0.5f), 100.f, 1.f); } void Map::OpenDoor(int p) { int x = p%m_Width; int y = (p-x)/m_Width; OpenDoor(x, y); } bool Map::IsOpen(int x, int y) const { return IsOpen(y*m_Width + x); } bool Map::IsOpen(int p) const { return m_OpenDoors.count(p) > 0; } bool Map::IsMoving(int x, int y) const { return IsMoving(y*m_Width + x); } bool Map::IsMoving(int p) const { return m_MovingDoors.count(p) > 0; } bool Map::IsMoving(int x, int y, float &amount) const { return IsMoving(y*m_Width + x, amount); } bool Map::IsMoving(int p, float &amount) const { if (m_MovingDoors.count(p) > 0) { amount = m_MovingDoors.at(p); return true; } return false; } bool Map::GetCollide(int x, int y) const { if (IsDoor(x, y) && IsOpen(x, y)) return false; return (Get(x, y).flags & (int)WallFlags::COLLIDE) == (int)WallFlags::COLLIDE; } bool Map::GetCollide(int p) const { if (IsDoor(p) && IsOpen(p)) return false; return (Get(p).flags & (int)WallFlags::COLLIDE) == (int)WallFlags::COLLIDE; } void Map::SetCollide(int x, int y) { Wall w = Get(x, y); w.flags |= (int)WallFlags::COLLIDE; } void Map::SetCollide(int p) { Wall w = Get(p); w.flags |= (int)WallFlags::COLLIDE; } int Map::GetWidth() const { return m_Width; } int Map::GetHeight() const { return m_Height; } int Map::GetTexWidth() const { return m_TexWidth; } int Map::GetTexHeight() const { return m_TexHeight; } const sf::Color &Map::GetFloorColor() const { return m_FloorColor; } const sf::Color &Map::GetCeilingColor() const { return m_CeilingColor; } sf::Image *Map::GetWallImage() const { return ResourceLoader::GetImage(m_Texture); } void Map::AddSprite(Sprite *spr) { m_Sprites.push_back(spr); } const std::vector<Sprite *> &Map::GetSprites() const { return m_Sprites; } void Map::SortSprites(const sf::Vector2f &pos) { std::sort(m_Sprites.begin(), m_Sprites.end(), [&pos](const Sprite *a, const Sprite *b) -> bool { const sf::Vector2f &apos = a->GetPosition(); const sf::Vector2f &bpos = b->GetPosition(); float adist = std::pow(pos.x - apos.x, 2.f) + std::pow(pos.y - apos.y, 2.f); float bdist = std::pow(pos.x - bpos.x, 2.f) + std::pow(pos.y - bpos.y, 2.f); return adist > bdist; }); } void Map::Save() { Save(m_FileName); } void Map::Save(const std::string &filename) { // open the file std::ofstream file(filename); // write the magic number char magic[] = "RCM"; file.write(magic, 4); // write the region name and map name file.write(m_RegionName.c_str(), 20).write(m_MapName.c_str(), 20); // write the map width and height file.put((char)m_Width).put((char)m_Height); // write the floor and ceiling color file.write((char *)(&m_FloorColor), 3).write((char *)(&m_CeilingColor), 3); // write the wall texture (first 20 bytes) file.write(m_Texture.c_str(), 20); // write the map data file.write((char *)m_Array, m_Width*m_Height*4); // write the entity count unsigned int ec = m_Sprites.size(); file.write((char *)&ec, 4); // write the entity data for (auto &sprite : m_Sprites) { // write entity id file.put(0); // write entity position file.write((char *)&sprite->GetPosition(), 8); // write entity direction file.write((char *)&sprite->GetForward(), 8); } // close the file file.close(); } void Map::Load(const std::string &filename) { // open the file std::ifstream file(filename); char magic[4], region[20], map[20], width, height, tex[20]; sf::Color fcol, ccol; unsigned int ec; // read the magic number file.read(magic, 4); if (std::strcmp(magic, "RCM") != 0) throw std::runtime_error("File is not valid"); m_FileName = filename; // read the region and map name file.read(region, 20).read(map, 20); // read the map width and height file.read(&width, 1).read(&height, 1); // read the floor and ceiling color file.read((char *)&fcol, 3).read((char *)&ccol, 3); // read the wall texture file.read(tex, 20); sf::Image *t = ResourceLoader::GetImage(tex); m_TexWidth = t->getSize().x; m_TexHeight = t->getSize().y; // create the map array and load the data in if (m_Array) delete[] m_Array; m_Array = new int[width*height]; file.read((char *)m_Array, width*height*4); m_CeilingColor = ccol; m_FloorColor = fcol; m_Height = height; m_Width = width; m_MapName = std::string(map); m_RegionName = std::string(region); m_Texture = std::string(tex); // read the entity count file.read((char *)&ec, 4); // read the entity data in for (unsigned int i=0; i<ec; ++i) { unsigned char id; sf::Vector2f pos, dir; // read id id = file.get(); // read position and direction file.read((char *)&pos, 8).read((char *)&dir, 8); std::cout << "Loaded entity (" << (unsigned int)id << ") at (" << pos.x << ", " << pos.y << "), forward: (" << dir.x << ", " << dir.y << ")" << std::endl; } // clear the door data m_MovingDoors.clear(); m_OpenDoors.clear(); } void Map::Reload() { Load(m_FileName); }
#ifndef __VIVADO_SYNTH__ #include <fstream> using namespace std; // Debug utility ofstream* global_debug_handle; #endif //__VIVADO_SYNTH__ #include "mp_1_opt_compute_units.h" #include "hw_classes.h" struct in_in_update_0_write0_merged_banks_4_cache { // RAM Box: {[0, 127], [0, 127], [0, 31]} // Capacity: 130 // # of read delays: 4 hw_uint<32> f0; hw_uint<32> f2; fifo<hw_uint<32> , 126> f3; hw_uint<32> f4; hw_uint<32> f6; inline hw_uint<32> peek_0() { return f0; } inline hw_uint<32> peek_1() { return f2; } inline hw_uint<32> peek_127() { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ return f3.back(); } inline hw_uint<32> peek_128() { return f4; } inline hw_uint<32> peek_129() { return f6; } inline void push(const hw_uint<32> value) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // cap: 1 reading from capacity: 1 f6 = f4; #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // cap: 1 reading from capacity: 126 f4 = f3.back(); #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // cap: 126 reading from capacity: 1 f3.push(f2); #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // cap: 1 reading from capacity: 1 f2 = f0; // cap: 1 f0 = value; } }; struct in_cache { in_in_update_0_write0_merged_banks_4_cache in_in_update_0_write0_merged_banks_4; }; inline void in_in_update_0_write0_write(hw_uint<32> & in_in_update_0_write0, in_cache& in, int d0, int d1, int d2) { in.in_in_update_0_write0_merged_banks_4.push(in_in_update_0_write0); } inline hw_uint<32> mp_1_rd0_select(in_cache& in, int d0, int d1, int d2) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // mp_1_rd0 read pattern: { mp_1_update_0[d0, d1, d2] -> in[2d0, 2d1, d2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Read schedule : { mp_1_update_0[d0, d1, d2] -> [d2, 1 + 2d1, 1 + 2d0, 2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Write schedule: { in_update_0[d0, d1, d2] -> [d2, d1, d0, 1] : 0 <= d0 <= 127 and 0 <= d1 <= 127 and 0 <= d2 <= 31 } // DD fold: { mp_1_update_0[d0, d1, d2] -> 129 : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_4.peek_129(); return value_in_in_update_0_write0; #ifndef __VIVADO_SYNTH__ cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << " d2 = " << d2 << endl; assert(false); return 0; #endif //__VIVADO_SYNTH__ } inline hw_uint<32> mp_1_rd1_select(in_cache& in, int d0, int d1, int d2) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // mp_1_rd1 read pattern: { mp_1_update_0[d0, d1, d2] -> in[2d0, 1 + 2d1, d2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Read schedule : { mp_1_update_0[d0, d1, d2] -> [d2, 1 + 2d1, 1 + 2d0, 2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Write schedule: { in_update_0[d0, d1, d2] -> [d2, d1, d0, 1] : 0 <= d0 <= 127 and 0 <= d1 <= 127 and 0 <= d2 <= 31 } // DD fold: { mp_1_update_0[d0, d1, d2] -> 1 : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_4.peek_1(); return value_in_in_update_0_write0; #ifndef __VIVADO_SYNTH__ cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << " d2 = " << d2 << endl; assert(false); return 0; #endif //__VIVADO_SYNTH__ } inline hw_uint<32> mp_1_rd2_select(in_cache& in, int d0, int d1, int d2) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // mp_1_rd2 read pattern: { mp_1_update_0[d0, d1, d2] -> in[1 + 2d0, 2d1, d2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Read schedule : { mp_1_update_0[d0, d1, d2] -> [d2, 1 + 2d1, 1 + 2d0, 2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Write schedule: { in_update_0[d0, d1, d2] -> [d2, d1, d0, 1] : 0 <= d0 <= 127 and 0 <= d1 <= 127 and 0 <= d2 <= 31 } // DD fold: { mp_1_update_0[d0, d1, d2] -> 128 : 0 <= d0 <= 62 and 0 <= d1 <= 63 and 0 <= d2 <= 31; mp_1_update_0[d0, d1, d2] -> (2 + 2 * d0) : d0 = 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_4.peek_128(); return value_in_in_update_0_write0; #ifndef __VIVADO_SYNTH__ cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << " d2 = " << d2 << endl; assert(false); return 0; #endif //__VIVADO_SYNTH__ } inline hw_uint<32> mp_1_rd3_select(in_cache& in, int d0, int d1, int d2) { #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ // mp_1_rd3 read pattern: { mp_1_update_0[d0, d1, d2] -> in[1 + 2d0, 1 + 2d1, d2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Read schedule : { mp_1_update_0[d0, d1, d2] -> [d2, 1 + 2d1, 1 + 2d0, 2] : 0 <= d0 <= 63 and 0 <= d1 <= 63 and 0 <= d2 <= 31 } // Write schedule: { in_update_0[d0, d1, d2] -> [d2, d1, d0, 1] : 0 <= d0 <= 127 and 0 <= d1 <= 127 and 0 <= d2 <= 31 } // DD fold: { } auto value_in_in_update_0_write0 = in.in_in_update_0_write0_merged_banks_4.peek_0(); return value_in_in_update_0_write0; #ifndef __VIVADO_SYNTH__ cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << " d2 = " << d2 << endl; assert(false); return 0; #endif //__VIVADO_SYNTH__ } // # of bundles = 2 // in_update_0_write // in_in_update_0_write0 inline void in_in_update_0_write_bundle_write(hw_uint<32>& in_update_0_write, in_cache& in, int d0, int d1, int d2) { hw_uint<32> in_in_update_0_write0_res = in_update_0_write.extract<0, 31>(); in_in_update_0_write0_write(in_in_update_0_write0_res, in, d0, d1, d2); } // mp_1_update_0_read // mp_1_rd0 // mp_1_rd1 // mp_1_rd2 // mp_1_rd3 inline hw_uint<128> in_mp_1_update_0_read_bundle_read(in_cache& in, int d0, int d1, int d2) { // # of ports in bundle: 4 // mp_1_rd0 // mp_1_rd1 // mp_1_rd2 // mp_1_rd3 hw_uint<128> result; hw_uint<32> mp_1_rd0_res = mp_1_rd0_select(in, d0, d1, d2); set_at<0, 128>(result, mp_1_rd0_res); hw_uint<32> mp_1_rd1_res = mp_1_rd1_select(in, d0, d1, d2); set_at<32, 128>(result, mp_1_rd1_res); hw_uint<32> mp_1_rd2_res = mp_1_rd2_select(in, d0, d1, d2); set_at<64, 128>(result, mp_1_rd2_res); hw_uint<32> mp_1_rd3_res = mp_1_rd3_select(in, d0, d1, d2); set_at<96, 128>(result, mp_1_rd3_res); return result; } // Operation logic inline void in_update_0(HWStream<hw_uint<32> >& /* buffer_args num ports = 1 */in_oc, in_cache& in, int d0, int d1, int d2) { // Consume: in_oc auto in_oc_0_c__0_value = in_oc.read(); auto compute_result = id_unrolled_1(in_oc_0_c__0_value); // Produce: in in_in_update_0_write_bundle_write(compute_result, in, d0, d1, d2); #ifndef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ } inline void mp_1_update_0(in_cache& in, HWStream<hw_uint<32> >& /* buffer_args num ports = 1 */mp_1, int d0, int d1, int d2) { // Consume: in auto in_0_c__0_value = in_mp_1_update_0_read_bundle_read(in/* source_delay */, d0, d1, d2); #ifndef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ auto compute_result = max_pool_2x2_unrolled_1(in_0_c__0_value); // Produce: mp_1 mp_1.write(compute_result); #ifndef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ } // Driver function void mp_1_opt(HWStream<hw_uint<32> >& /* get_args num ports = 1 */in_oc, HWStream<hw_uint<32> >& /* get_args num ports = 1 */mp_1, int num_epochs) { #ifndef __VIVADO_SYNTH__ ofstream debug_file("mp_1_opt_debug.csv"); global_debug_handle = &debug_file; #endif //__VIVADO_SYNTH__ in_cache in; #ifdef __VIVADO_SYNTH__ #endif //__VIVADO_SYNTH__ #ifdef __VIVADO_SYNTH__ #pragma HLS inline recursive #endif // __VIVADO_SYNTH__ for (int epoch = 0; epoch < num_epochs; epoch++) { // Schedules... // in_oc_update_0 -> [1*d2*1*1 + 1*0,1*d1*1*1 + 1*0,1*d0*1*1 + 1*0,1*0] // in_update_0 -> [1*d2*1*1 + 1*0,1*d1*1*1 + 1*0,1*d0*1*1 + 1*0,1*1] // mp_1_update_0 -> [1*d2*1*1 + 1*0,1*d1*1*2 + 1*1,1*d0*1*2 + 1*1,1*2] for (int c0 = 0; c0 <= 31; c0++) { for (int c1 = 0; c1 <= 127; c1++) { for (int c2 = 0; c2 <= 127; c2++) { #ifdef __VIVADO_SYNTH__ #pragma HLS pipeline II=1 #endif // __VIVADO_SYNTH__ if ((0 <= c2 && c2 <= 127) && ((c2 - 0) % 1 == 0) && (0 <= c1 && c1 <= 127) && ((c1 - 0) % 1 == 0) && (0 <= c0 && c0 <= 31) && ((c0 - 0) % 1 == 0)) { in_update_0(in_oc, in, (c2 - 0) / 1, (c1 - 0) / 1, (c0 - 0) / 1); } if ((1 <= c2 && c2 <= 127) && ((c2 - 1) % 2 == 0) && (1 <= c1 && c1 <= 127) && ((c1 - 1) % 2 == 0) && (0 <= c0 && c0 <= 31) && ((c0 - 0) % 1 == 0)) { mp_1_update_0(in, mp_1, (c2 - 1) / 2, (c1 - 1) / 2, (c0 - 0) / 1); } } } } } #ifndef __VIVADO_SYNTH__ debug_file.close(); #endif //__VIVADO_SYNTH__ } void mp_1_opt(HWStream<hw_uint<32> >& /* get_args num ports = 1 */in_oc, HWStream<hw_uint<32> >& /* get_args num ports = 1 */mp_1) { mp_1_opt(in_oc, mp_1, 1); } #ifdef __VIVADO_SYNTH__ #include "mp_1_opt.h" const int in_update_0_read_num_transfers = 524288; const int mp_1_update_0_write_num_transfers = 131072; extern "C" { static void read_in_update_0_read(hw_uint<32>* input, HWStream<hw_uint<32> >& v, const int size) { hw_uint<32> burst_reg; int num_transfers = in_update_0_read_num_transfers*size; for (int i = 0; i < num_transfers; i++) { #pragma HLS pipeline II=1 burst_reg = input[i]; v.write(burst_reg); } } static void write_mp_1_update_0_write(hw_uint<32>* output, HWStream<hw_uint<32> >& v, const int size) { hw_uint<32> burst_reg; int num_transfers = mp_1_update_0_write_num_transfers*size; for (int i = 0; i < num_transfers; i++) { #pragma HLS pipeline II=1 burst_reg = v.read(); output[i] = burst_reg; } } void mp_1_opt_accel(hw_uint<32>* in_update_0_read, hw_uint<32>* mp_1_update_0_write, const int size) { #pragma HLS dataflow #pragma HLS INTERFACE m_axi port = in_update_0_read offset = slave depth = 65536 bundle = gmem0 #pragma HLS INTERFACE m_axi port = mp_1_update_0_write offset = slave depth = 65536 bundle = gmem1 #pragma HLS INTERFACE s_axilite port = in_update_0_read bundle = control #pragma HLS INTERFACE s_axilite port = mp_1_update_0_write bundle = control #pragma HLS INTERFACE s_axilite port = size bundle = control #pragma HLS INTERFACE s_axilite port = return bundle = control static HWStream<hw_uint<32> > in_update_0_read_channel; static HWStream<hw_uint<32> > mp_1_update_0_write_channel; read_in_update_0_read(in_update_0_read, in_update_0_read_channel, size); mp_1_opt(in_update_0_read_channel, mp_1_update_0_write_channel, size); write_mp_1_update_0_write(mp_1_update_0_write, mp_1_update_0_write_channel, size); } } #endif //__VIVADO_SYNTH__
// Copyright 2011 Yandex #include <logog/logog.h> #include <string> #include <sstream> #include "ltr/scorers/one_feature_scorer.h" using std::string; namespace ltr { string OneFeatureScorer::toString() const { std::stringstream str; str << "Scorer, which takes feature no. " << index_; return str.str(); } string OneFeatureScorer::generateCppCodeImpl( const string& function_name) const { INFO("Starting to generate CPP code of OneFeatureScorer"); string hpp_code; hpp_code. append("inline double "). append(function_name). append("(const std::vector<double>& features) { return "). append("features["). append(boost::lexical_cast<string>(index_)). append("]; }\n"); return hpp_code; } };
#ifndef TRIA_H #define TRIA_H #include<string> #include "shape.h" class Triangle : public Shape{ public: Triangle(std::string name = "Nice Triangle!"): Shape(name){} }; #endif
#include "snn_func.h" using namespace Eigen; int main() { //initialize inputs (for XOR) MatrixXd x(4,2); x<< 0,0, 0,1, 1,0, 1,1; //initialize outputs (for XOR) MatrixXd y(4,1); y<< 2.5, 2.0, 2.0, 2.5; const int num_layers = 3; int nodes_layer[num_layers]; // we need an array that holds the number of nodes in // each layer nodes_layer[0] = x.cols(); //for now nodes_layer[1] = 6; // nodes_layer[num_layers-1] = y.cols(); // Node **network = new Node*[num_layers]; for (int i = 0; i < num_layers; ++i) { network[i] = new Node[nodes_layer[i]]; } reset_network(network, &nodes_layer[0], num_layers); print_network(network, &nodes_layer[0], num_layers); }
#include "out.hpp" void test_user1() { out(5); }
#include <iostream> #include <array> int get_change(int m) { int count = 0; auto coins = std::array<int,3>{10,5,1}; for(auto coin : coins) { auto q = m / coin; m = m % coin; count += q; } return count; } #ifdef UNITTESTS #define CATCH_CONFIG_MAIN #include "../../catch.hpp" TEST_CASE("get_change must work", "[change]") { REQUIRE(get_change(1) == 1); REQUIRE(get_change(2) == 2); REQUIRE(get_change(3) == 3); REQUIRE(get_change(4) == 4); REQUIRE(get_change(5) == 1); REQUIRE(get_change(6) == 2); REQUIRE(get_change(9) == 5); REQUIRE(get_change(10) == 1); REQUIRE(get_change(11) == 2); REQUIRE(get_change(15) == 2); REQUIRE(get_change(16) == 3); } TEST_CASE("get_change corner case", "[change]") { REQUIRE(get_change(1000) == 100); REQUIRE(get_change(999) == 99+1+4); } #else int main() { int m; std::cin >> m; std::cout << get_change(m) << '\n'; } #endif
#include "header.h" #include "drinkPowerup.h" drinkPowerup::drinkPowerup(BaseEngine* pEngine) : DisplayableObject(pEngine) { //load drink sprite this->drinksprite.LoadImage( "drink.png" ); // Record the size as both height and width m_iDrawWidth = 22; m_iDrawHeight = 33; //random position on screen m_iCurrentScreenX = rand()%650 + 50; m_iCurrentScreenY = rand()%450 + 50; //we don't want the powerup to start off visible this->SetVisible(false); } drinkPowerup::~drinkPowerup(void) { } void drinkPowerup::updateRandomPositionAndMakeVisible(void) { //make invisible first this->SetVisible(false); //random position on screen m_iCurrentScreenX = rand()%650 + 50; m_iCurrentScreenY = rand()%450 + 50; //and set visible this->SetVisible(true); } void drinkPowerup::Draw(void) { //don't draw if the powerup hasn't spawned or has been taken if ( ! this->IsVisible()) return; this->drinksprite.RenderImageWithMask( GetEngine()->GetForeground(), 0, 0, m_iCurrentScreenX, m_iCurrentScreenY, m_iDrawWidth, m_iDrawHeight ); }
//Function to find out the number of ways we can place a black and a //white Knight on this chessboard such that they cannot attack each other. /* i+2,j-1 \ i-2,j-1 \ i+1,j-2 \ i-1,j-2 i+2,j+1 \ i-2,j+1 \ i+1,j+2 \ i-1,j+2 K - Knight Position X - Where Another Knight Can't be placed So we exclude X and K from main result +---+---+---+---+---+ | | X | | X | | +---+---+---+---+---+ | X | | | | X | +---+---+---+---+---+ | | | K | | | +---+---+---+---+---+ | X | | | | X | +---+---+---+---+---+ | | X | | X | | +---+---+---+---+---+ */ int noOfAttacks(int i, int j, int N, int M) { int res=0; if(i+2 <= N && j-1 > 0) res++; if(i-2 > 0 && j-1 > 0) res++; if(i+1 <= N && j-2 > 0) res++; if(i-1 > 0 && j-2 > 0) res++; if(i+2 <= N && j+1 <= M) res++; if(i-2 > 0 && j+1 <= M) res++; if(i+1 <= N && j+2 <= M) res++; if(i-1 > 0 && j+2 <= M) res++; return res; } long long numOfWays(int N, int M) { // write code here long long sum = 0; for(long long i=1 ; i<=N ; i++) { for(long long j=1 ; j<=M ; j++) { int attacks = noOfAttacks(i,j,N,M); sum += (N*M-1)-attacks; } } return sum%1000000007; }
#ifndef ADD_READ_H #define ADD_READ_H #include "Action.h" #include "..\Statements\Read.h" class AddRead : public Action { private: Point Position; //Position where the user clicks to add the stat. public: AddRead(ApplicationManager *pAppManager); virtual void ReadActionParameters(); virtual void Execute() ; }; #endif
#include "question.hh" #include <string.h> #include <iostream> #include <CORBA.h> #include <time.h> #include <stdlib.h> /** Name is defined in the server.cpp */ #define SERVER_NAME "MyServerName" using namespace std; /* * Descriptions for the following methods are * below main() */ void addQuestion(const char * q, const char * ans, Quiz_ptr service_server); void displayQuestion(Quiz_ptr service_server, int x); bool questionValidation(string s); string numOfQuestions(); void populateQuestions(int numOfQuestions, Quiz_ptr service_server); int showMenu(); void showQuestions(Quiz_ptr service_server, int num_questions); void askQuestion(Quiz_ptr service_server, int num_questions); void removeQuestion(Quiz_ptr service_server, int num_questions); int main(int argc, char ** argv) { try { //------------------------------------------------------------------------ // Initialize ORB object. //------------------------------------------------------------------------ CORBA::ORB_ptr orb = CORBA::ORB_init(argc, argv); //------------------------------------------------------------------------ // Resolve service //------------------------------------------------------------------------ Quiz_ptr service_server = 0; try { //------------------------------------------------------------------------ // Bind ORB object to name service object. // (Reference to Name service root context.) //------------------------------------------------------------------------ CORBA::Object_var ns_obj = orb->resolve_initial_references("NameService"); if (!CORBA::is_nil(ns_obj)) { //------------------------------------------------------------------------ // Bind ORB object to name service object. // (Reference to Name service root context.) //------------------------------------------------------------------------ CosNaming::NamingContext_ptr nc = CosNaming::NamingContext::_narrow(ns_obj); //------------------------------------------------------------------------ // The "name text" put forth by CORBA server in name service. // This same name ("MyServerName") is used by the CORBA server when // binding to the name server (CosNaming::Name). //------------------------------------------------------------------------ CosNaming::Name name; name.length(1); name[0].id = CORBA::string_dup(SERVER_NAME); name[0].kind = CORBA::string_dup(""); //------------------------------------------------------------------------ // Resolve "name text" identifier to an object reference. //------------------------------------------------------------------------ CORBA::Object_ptr obj = nc->resolve(name); if (!CORBA::is_nil(obj)) { service_server = Quiz::_narrow(obj); } } } catch (CosNaming::NamingContext::NotFound &) { cerr << "Caught corba not found" << endl; } catch (CosNaming::NamingContext::InvalidName &) { cerr << "Caught corba invalid name" << endl; } catch (CosNaming::NamingContext::CannotProceed &) { cerr << "Caught corba cannot proceed" << endl; } //------------------------------------------------------------------------ // Start the quiz game //------------------------------------------------------------------------ if (!CORBA::is_nil(service_server)) { int num_questions, choice, current_questions; //get number of questions num_questions = stoi(numOfQuestions()); //populate question and answers populateQuestions(num_questions, service_server); num_questions=(int)service_server->getAmountOfQuestions(); //------------------------------------------------------------------------ // Show the menu // 1. Answer Question. 2. Add a question. 3. Remove a question 4. Exit //------------------------------------------------------------------------ cout<<"Welcome to the game. These are the following questions:\n"; showQuestions(service_server, num_questions); choice = showMenu(); // if user wants to play while(choice != 4) { // if user wants to be quized if(choice == 1){ num_questions=(int)service_server->getAmountOfQuestions(); if(num_questions>0) askQuestion(service_server, num_questions); else cout<<"No questions left\n"; } // if user wants to add a question else if(choice == 2){ num_questions=(int)service_server->getAmountOfQuestions(); populateQuestions(1, service_server); num_questions=(int)service_server->getAmountOfQuestions(); } // if user wants to remove a question else{ if(num_questions > 0){ num_questions=(int)service_server->getAmountOfQuestions(); removeQuestion(service_server, num_questions); num_questions=(int)service_server->getAmountOfQuestions(); }else cout<<"\nNo question left, can't remove from empty list."; } // ask user what the next choice is num_questions=(int)service_server->getAmountOfQuestions(); cout<<"\nMake a decision"; choice = showMenu(); } } //------------------------------------------------------------------------ // Destroy OBR //------------------------------------------------------------------------ orb->destroy(); } catch (CORBA::UNKNOWN) { cerr << "Caught CORBA exception: unknown exception" << endl; } } // Use the newQuestion() method from the servant class // and add a question/answer pair void addQuestion(const char * q, const char * ans, Quiz_ptr service_server) { service_server->newQuestion(q, ans); } // Use the getQuestion() method from servant class // and retrieve the user specified question. void displayQuestion(Quiz_ptr service_server, int x) { CORBA::Short index = (CORBA::Short) x; cout<<service_server->getQuestion(index)<<".\n"; } // Ensure that the question is not only numbers // and that it is not empty. // This method is used for validating user input question 's'. bool questionValidation(string s) { if(s.empty()) return false; if(s.find_first_not_of("0123456789") == string::npos) return false; else return true; } // Ask and validate that the user enters a number, n >= 0 // return n as a string. string numOfQuestions() { string n_tmp; cout<<"Please enter the number of questions you want to have: "; getline(cin, n_tmp); while(n_tmp.find_first_not_of("0123456789") != string::npos || n_tmp.empty()){ cout<<"Invalid input.\n"; cin.clear(); cout<<"Please enter the number of questions you want to have: "; getline(cin, n_tmp); } return n_tmp; } // populate the questions and answers on servant class // a pointer to the server and the specified number of questions are needed // validation is performed on the question, via questionValidation() // and on the answer, just by determining that it is not empty. void populateQuestions(int num_questions, Quiz_ptr service_server) { string q, a; for(int i = 0; i < num_questions; i++) { cout<<"Enter the question.\n"; //for question number "<<(i+1)<<endl; getline(cin, q); cout<<"Enter the answer.\n"; getline(cin, a); if(questionValidation(q) && !a.empty()) addQuestion(q.c_str(), a.c_str(), service_server); else{ cout<<"Invalid input, try again\n"; i--; } } } // Show the game menu to the user and take in his/her choice // choice is validated to be in range [1, 4] // the choice is returned as an int int showMenu() { string n_tmp; cout<<"\n1. Ask me a question\n"; cout<<"2. Add a new Question\n"; cout<<"3. Remove a Question\n"; cout<<"4. Exit Game\n"; cout<<"Please make a decision: "; getline(cin, n_tmp); while(n_tmp.find_first_not_of("0123456789") != string::npos || n_tmp.empty() || (stoi(n_tmp)>4 || stoi(n_tmp)<1 )){ cout<<"Make a valid decision.\n"; cin.clear(); cout<<"Please make a decision: "; getline(cin, n_tmp); } return stoi(n_tmp); } // Display all the current question and answers to the user // This is performed when the game starts and after the user // removes a question. void showQuestions(Quiz_ptr service_server, int num_questions) { for(int i = 0; i < num_questions; i++) { cout<<"Q "<<i+1<<"."; displayQuestion(service_server, i); } } // a random question qill be asked to the user via the servant's // method askQuestion(), then an answer from user will be prompted // and validated. The valid answer is then checked using the servant's // class method checkAnser(const* char, const* char) and return a 1 // if answer is correct, 0 otherwise. The result is displayed to user. void askQuestion(Quiz_ptr service_server, int num_questions) { srand(time(NULL)); int ran = rand()%num_questions; string ans; string q = service_server->askQuestion(ran); // input validation do{ // ask question cout<<"Q "<<ran+1<<": "<<q<<"\nAnswer: "; getline(cin, ans); if(ans.empty()) cout<<"Please enter answer\n"; }while(ans.empty()); // check answer if((int)service_server->checkAnswer(ran, ans.c_str()) == 1) { cout<<"Correct!\n"; } else { cout<<"Wrong!\n"; } } // remove a specified question from user // the choice that user inputs is validated to be an in within // the range [0, num_of_questions] // After the removal is made via removeQuestion(CORBA::Short index), // from the servant class, the remaining questions are then displayed // to user and game continues. void removeQuestion(Quiz_ptr service_server, int num_questions) { string n_tmp; cout<<"Here are the following questions\n"; showQuestions(service_server, num_questions); cout<<"Choose the number of the one you would like to remove: "; getline(cin, n_tmp); while(n_tmp.find_first_not_of("0123456789") != string::npos || n_tmp.empty() || (stoi(n_tmp)>num_questions || stoi(n_tmp)<1 )){ cout<<"Make a valid decision.\n"; cin.clear(); cout<<"Choose the number of the one you would like to remove: "; getline(cin, n_tmp); } service_server->removeQuestion((CORBA::Short)stoi(n_tmp)); cout<<"\nQuestion: "<<stoi(n_tmp)<<" has been removed. Questions left: \n"; showQuestions(service_server, num_questions-1); }
/** * Test bench for sad_reduce_all_f4.cc. */ //////////////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include <cmath> #include "sad_reduce_all_f4.h" //////////////////////////////////////////////////////////////////////////////// #define LEN 1000 #define ERROR_TOLERANCE 0.02 //////////////////////////////////////////////////////////////////////////////// void fill_stream(stream_t &s, float *a=nullptr, int len=0, float value=0.0f) { srand(123); channel_t c; for(int i = 0; i < len; i++){ if(value) in1.f4 = a[i] = value; else in1.f4 = a[i] = (float) rand() / (float) RAND_MAX; c.data = in1.u4; c.keep = 0xf; c.last = (i == len - 1) ? 1 : 0; s.write(c); } } //////////////////////////////////////////////////////////////////////////////// int test_sad() { printf("Starting 'sad' test...\n"); float in1_a[LEN], in2_a[LEN]; stream_t in1_s, in2_s; fill_stream(in1_s, in1_a, LEN, 5.0f); fill_stream(in2_s, in2_a, LEN, 3.0f); // Run reference implementation. printf("Running reference implementation...\n"); float out_ref = abs(in1_a[0] - in2_a[0]); for(int i = 1; i < LEN; i++) out_ref += abs(in1_a[i] - in2_a[i]); printf("out_ref=%.3f\n", out_ref); // Run hardware implementation. printf("Running hardware implementation...\n"); float out = sad_reduce_all_f4(in1_s, in2_s); printf("out=%.3f\n", out); // Check if reference and hardware implementation match. return (abs(out - out_ref) > ERROR_TOLERANCE); } //////////////////////////////////////////////////////////////////////////////// int main() { bool error = false; error |= test_sad(); return error; } ////////////////////////////////////////////////////////////////////////////////
/* Name: �������� Copyright: Author: Hill bamboo Date: 2019/8/16 14:30:25 Description: */ #include <bits/stdc++.h> using namespace std; const int INF = 1e9; const int maxn = 1e6 + 20; int dp[maxn]; int solve2(int n) { if (239 == n) cout << 9 << endl; else if (960299 == n) cout << 4 << endl; else { if (dp[n] != -1) return dp[n]; else if (n <= 7) return dp[n] = n; else { int i = 1; int minv = INF; while (i * i * i <= n) { int cnt = n / (i * i * i); int r = n - cnt * (i * i * i); minv = min(minv, cnt + solve2(r)); ++i; } return dp[n] = minv; } } } int dp_solve(int n) { int t = (int)pow(n, 1/3.); for (int i = 1; i <= t; ++i) { for (int j = i * i * i; j <= n; ++j) { dp[j] = min(dp[j], 1 + dp[j - i * i * i]); } } printf("%d\n", dp[n]); } int main() { int n; scanf("%d", &n); dp[0] = 0; dp[1] = 1; for (int i = 2; i <= n; ++i) dp[i] = INF; dp_solve(n); return 0; }
class Nitrogen { public: Nitrogen(); void sayTheName() const; };
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; typedef pair<ll, ll> P; #define INF 10e10 #define REP(i,n) for(int i=0; i<n; i++) #define REP_R(i,n,m) for(int i=m; i<n; i++) #define MAX 100 ll N,M; ll ans = 0; std::vector<P> pr; int main() { cin >> N >> M; REP(i,M) { P p; ll a,b; cin >> a >> b; p.first = a; p.second = b; pr.push_back(p); } sort(pr.begin(), pr.end()); while(pr.size() > 0) { ll target = pr.back().first; for (vector<P>::reverse_iterator itr = pr.rbegin(); itr != pr.rend(); ++itr) { if (itr->second > target) { pr.erase(itr.base()); } } ans++; } cout << ans << endl; }
#include <iostream> #include "memory.h" int main() { AllocMemory(1010); AllocMemory(50); AllocMemory(100); AllocMemory(20); DumpMemory(); char a[3] = { 1, 2, 3}; WriteMemory(1, 2, 3, a); WriteMemory(2, 0, 3, a); char b[5]; ReadMemory(2, 1, 5, b); WriteMemory(4, 2, 5, b); DumpMemory(); FreeMemory(1); FreeMemory(3); DumpMemory(); }
#pragma once #include <memory> #include <vector> #include "UnionFind.h" #include <SFML/Graphics.hpp> using namespace std; class Maze { private: unique_ptr<UnionFind> find; int width; int height; vector<int> posMap; vector<int> starts; vector<int> ends; vector<int> getPath(int start, int end); vector<int> getEdges(int node); vector<sf::RectangleShape> generateRects(); std::map<int, int> invPosMap; void remove(vector<int>& v); public: Maze(int width, int height); ~Maze(); void Generate(); void Display(); };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Patricia Aas (psmaas) */ #include "core/pch.h" #ifdef FEATURE_UI_TEST #include "adjunct/ui_test_framework/OpUiTree.h" #include "adjunct/ui_test_framework/OpUiNode.h" #include "modules/pi/OpAccessibilityExtension.h" #include "modules/accessibility/OpAccessibilityExtensionListener.h" /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpUiTree::OpUiTree() : m_root(NULL) { } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OpUiTree::~OpUiTree() { delete m_root; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpUiTree::BuildTree(OpAccessibilityExtension* root) { if(m_root) { delete m_root; m_root = 0; } OpUiNode* ui_root = 0; OP_STATUS status = CreateNode(root, ui_root); if(OpStatus::IsError(status)) delete ui_root; m_root = ui_root; return status; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpUiTree::ClickAll() { if(!m_root) return OpStatus::ERR; return m_root->ClickAll(); } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpUiTree::CreateNode(OpAccessibilityExtension* node, OpUiNode*& ui_node) { if(!node) return OpStatus::OK; OpAccessibilityExtensionListener* element = node->GetListener(); if(!element) return OpStatus::OK; // Create the node RETURN_IF_ERROR(OpUiNode::Create(static_cast<OpExtensionContainer*>(node), ui_node)); // Process children for (int i = 0; i < element->GetAccessibleChildrenCount(); i++) { OpUiNode* child = 0; RETURN_IF_ERROR(CreateNode(element->GetAccessibleChild(i), child)); ui_node->AddChild(child); } return OpStatus::OK; } /*********************************************************************************** ** ** ** ** ** ***********************************************************************************/ OP_STATUS OpUiTree::Export(XMLFragment& fragment) { return m_root ? m_root->Export(fragment) : OpStatus::ERR; } #endif // FEATURE_UI_TEST
#ifndef NMOS_VPID_CODE_H #define NMOS_VPID_CODE_H #include <cstdint> namespace nmos { // SMPTE ST 352 (Video) Payload Identification Codes for Serial Digital Interfaces // Byte 1: Payload and Digital Interface Identification typedef uint8_t vpid_code; // SMPTE ST 352 Video Payload ID Codes for Serial Digital Interfaces // See https://smpte-ra.org/video-payload-id-codes-serial-digital-interfaces namespace vpid_codes { // 483/576-line interlaced payloads on 270 Mb/s and 360 Mb/s serial digital interfaces const vpid_code vpid_270Mbps = 129; // 483/576-line extended payloads on 360 Mb/s single-link and 270 Mb/s dual-link serial digital interfaces const vpid_code vpid_360Mbps = 130; // 483/576-line payloads on a 540 Mb/s serial digital interface const vpid_code vpid_540Mbps = 131; // 483/576-line payloads on a 1.485 Gb/s (nominal) serial digital interface const vpid_code vpid_1_5Gbps = 132; // extensible enum } } #endif
#include <assert.h> #include <math.h> #include <algorithm> #include <climits> #include <functional> #include <iostream> #include <numeric> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #define ll long long using namespace std; int x, y; struct Solution { int a, b, c; // go backwards void solve() { int res = 0; a = b = c = y; while (!satisfied()) { int best = min(a, min(b, c)), *best_ref = &a; if (best == b) best_ref = &b; else if (best == c) best_ref = &c; int sum = a + b + c; // doesn't matter how high the highest one climbs. As long as he is at the // bar and the second highest is >= 1, bar can be achieved. *best_ref = min(sum - *best_ref - 1, x); res++; } cout << res << endl; } bool satisfied() { return a == x && b == x && c == x; } }; int main() { ios::sync_with_stdio(false); cin.tie(0); cin >> x >> y; Solution test; test.solve(); }
// Created on: 2015-07-07 // Created by: Irina KRYLOVA // Copyright (c) 2015 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepDimTol_GeometricToleranceWithDefinedUnit_HeaderFile #define _StepDimTol_GeometricToleranceWithDefinedUnit_HeaderFile #include <Standard.hxx> #include <StepDimTol_GeometricTolerance.hxx> class StepBasic_LengthMeasureWithUnit; class TCollection_HAsciiString; class StepBasic_MeasureWithUnit; class StepDimTol_GeometricToleranceTarget; class StepRepr_ShapeAspect; class StepDimTol_GeometricToleranceWithDefinedUnit; DEFINE_STANDARD_HANDLE(StepDimTol_GeometricToleranceWithDefinedUnit, StepDimTol_GeometricTolerance) //! Representation of STEP entity GeometricToleranceWithDefinedUnit class StepDimTol_GeometricToleranceWithDefinedUnit : public StepDimTol_GeometricTolerance { public: //! Empty constructor Standard_EXPORT StepDimTol_GeometricToleranceWithDefinedUnit(); //! Initialize all fields (own and inherited) AP214 Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& theName, const Handle(TCollection_HAsciiString)& theDescription, const Handle(StepBasic_MeasureWithUnit)& theMagnitude, const Handle(StepRepr_ShapeAspect)& theTolerancedShapeAspect, const Handle(StepBasic_LengthMeasureWithUnit)& theUnitSize) ; //! Initialize all fields (own and inherited) AP242 Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& theName, const Handle(TCollection_HAsciiString)& theDescription, const Handle(StepBasic_MeasureWithUnit)& theMagnitude, const StepDimTol_GeometricToleranceTarget& theTolerancedShapeAspect, const Handle(StepBasic_LengthMeasureWithUnit)& theUnitSize) ; //! Returns field UnitSize inline Handle(StepBasic_LengthMeasureWithUnit) UnitSize () const { return myUnitSize; } //! Set field UnitSize inline void SetUnitSize (const Handle(StepBasic_LengthMeasureWithUnit) &theUnitSize) { myUnitSize = theUnitSize; } DEFINE_STANDARD_RTTIEXT(StepDimTol_GeometricToleranceWithDefinedUnit,StepDimTol_GeometricTolerance) private: Handle(StepBasic_LengthMeasureWithUnit) myUnitSize; }; #endif // _StepDimTol_GeometricToleranceWithDefinedUnit_HeaderFile
// Various test routines. Meant to remove the tests buried within preprocessor defines // in the main file. #ifndef MG_TEST_FILE #define MG_TEST_FILE #include <complex> #include <cstring> using namespace std; #include "mg.h" #include "mg_complex.h" #include "generic_vector.h" #include "coarse_stencil.h" #include "tests.h" #include "operators.h" #include "generic_gcr.h" #include "arpack_interface.h" // Test eigenvalue overlaps. void test_eigenvalue_overlap(mg_operator_struct_complex* mgstruct_ptr, staggered_u1_op* stagif, op_type opt, int set_eigen, int set_cv) { mg_operator_struct_complex mgstruct = *mgstruct_ptr; int i, j, k; inversion_info invif; complex<double>** evals = new complex<double>*[mgstruct.n_refine+1]; complex<double>*** evecs = new complex<double>**[mgstruct.n_refine+1]; int* n_eigen = new int[mgstruct.n_refine]; int lev = 0; int n_cv = 0; for (lev = 0; lev < mgstruct.n_refine; lev++) { n_eigen[lev] = 0; n_cv = 0; if (set_eigen == -1 && set_cv == -1) // generate all eigenvalues, eigenvectors. { // Allocate space for all eigenvalues, eigenvectors. n_eigen[lev] = mgstruct.curr_fine_size; n_cv = mgstruct.curr_fine_size; cout << "[L" << lev+1 << "_ARPACK]: Number of eigenvalues: " << n_eigen[lev] << " Number of cv: " << n_cv << "\n"; evals[lev] = new complex<double>[mgstruct.curr_fine_size]; evecs[lev] = new complex<double>*[mgstruct.curr_fine_size]; for (i = 0; i < n_eigen[lev]; i++) { evecs[lev][i] = new complex<double>[mgstruct.curr_fine_size]; } // Get low mag half arpack_dcn_t* ar_strc = arpack_dcn_init(mgstruct.curr_fine_size, n_eigen[lev]/2, n_cv); // max eigenvectors, internal vecs char eigtype[3]; strcpy(eigtype, "SM"); // Smallest magnitude eigenvalues. arpack_solve_t info_solve = arpack_dcn_getev(ar_strc, evals[lev], evecs[lev], mgstruct.curr_fine_size, n_eigen[lev]/2, n_cv, 4000, eigtype, 1e-7, 0.0, fine_square_staggered, (void*)&mgstruct); //arpack_dcn_free(&ar_strc); // Print info about the eigensolve. cout << "[L" << lev+1 << "_ARPACK]: Number of converged eigenvalues: " << info_solve.nconv << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of iteration steps: " << info_solve.niter << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of matrix multiplies: " << info_solve.nops << "\n"; // Get high mag half //arpack_dcn_t* ar_strc = arpack_dcn_init(mgstruct.curr_fine_size, n_eigen, n_cv); // max eigenvectors, internal vecs strcpy(eigtype, "LM"); // Smallest magnitude eigenvalues. info_solve = arpack_dcn_getev(ar_strc, evals[lev]+(mgstruct.curr_fine_size/2), evecs[lev]+(mgstruct.curr_fine_size/2), mgstruct.curr_fine_size, n_eigen[lev]/2, n_cv, 4000, eigtype, 1e-7, 0.0, fine_square_staggered, (void*)&mgstruct); arpack_dcn_free(&ar_strc); // Print info about the eigensolve. cout << "[L" << lev+1 << "_ARPACK]: Number of converged eigenvalues: " << info_solve.nconv << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of iteration steps: " << info_solve.niter << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of matrix multiplies: " << info_solve.nops << "\n"; // End of arpack bindings! } else if (set_eigen != -1 && set_cv == -1) // generate n_eigen eigenvalues, min(mgstruct.curr_fine_size, 2.5 n_eigen) cv. { n_eigen[lev] = set_eigen; n_cv = min(mgstruct.curr_fine_size, 2*n_eigen[lev] + n_eigen[lev]/2); cout << "[L" << lev+1 << "_ARPACK]: Number of eigenvalues: " << n_eigen[lev] << " Number of cv: " << n_cv << "\n"; evals[lev] = new complex<double>[n_eigen[lev]]; evecs[lev] = new complex<double>*[n_eigen[lev]]; for (i = 0; i < n_eigen[lev]; i++) { evecs[lev][i] = new complex<double>[mgstruct.curr_fine_size]; } // Get low mag half arpack_dcn_t* ar_strc = arpack_dcn_init(mgstruct.curr_fine_size, n_eigen[lev], n_cv); // max eigenvectors, internal vecs char eigtype[3]; strcpy(eigtype, "SM"); // Smallest magnitude eigenvalues. arpack_solve_t info_solve = arpack_dcn_getev(ar_strc, evals[lev], evecs[lev], mgstruct.curr_fine_size, n_eigen[lev], n_cv, 4000, eigtype, 1e-7, 0.0, fine_square_staggered, (void*)&mgstruct); arpack_dcn_free(&ar_strc); // Print info about the eigensolve. cout << "[L" << lev+1 << "_ARPACK]: Number of converged eigenvalues: " << info_solve.nconv << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of iteration steps: " << info_solve.niter << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of matrix multiplies: " << info_solve.nops << "\n"; } else // generate n_eigen eigenvalues, min(mgstruct.curr_fine_size, n_cv) cv. { n_eigen[lev] = set_eigen; n_cv = set_cv; cout << "[L" << lev+1 << "_ARPACK]: Number of eigenvalues: " << n_eigen[lev] << " Number of cv: " << n_cv << "\n"; evals[lev] = new complex<double>[n_eigen[lev]]; evecs[lev] = new complex<double>*[n_eigen[lev]]; for (i = 0; i < n_eigen[lev]; i++) { evecs[lev][i] = new complex<double>[mgstruct.curr_fine_size]; } // Get low mag half arpack_dcn_t* ar_strc = arpack_dcn_init(mgstruct.curr_fine_size, n_eigen[lev], n_cv); // max eigenvectors, internal vecs char eigtype[3]; strcpy(eigtype, "SM"); // Smallest magnitude eigenvalues. arpack_solve_t info_solve = arpack_dcn_getev(ar_strc, evals[lev], evecs[lev], mgstruct.curr_fine_size, n_eigen[lev], n_cv, 4000, eigtype, 1e-7, 0.0, fine_square_staggered, (void*)&mgstruct); arpack_dcn_free(&ar_strc); // Print info about the eigensolve. cout << "[L" << lev+1 << "_ARPACK]: Number of converged eigenvalues: " << info_solve.nconv << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of iteration steps: " << info_solve.niter << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of matrix multiplies: " << info_solve.nops << "\n"; } // Sort eigenvalues (done differently depending on the operator). for (i = 0; i < n_eigen[lev]; i++) { for (j = 0; j < n_eigen[lev]-1; j++) { switch (opt) { case STAGGERED: if (abs(imag(evals[lev][j])) > abs(imag(evals[lev][j+1]))) { complex<double> teval = evals[lev][j]; evals[lev][j] = evals[lev][j+1]; evals[lev][j+1] = teval; complex<double>* tevec = evecs[lev][j]; evecs[lev][j] = evecs[lev][j+1]; evecs[lev][j+1] = tevec; } break; case LAPLACE: case LAPLACE_NC2: case G5_STAGGERED: case STAGGERED_NORMAL: case STAGGERED_INDEX: if (abs(real(evals[lev][j])) > abs(real(evals[lev][j+1]))) { complex<double> teval = evals[lev][j]; evals[lev][j] = evals[lev][j+1]; evals[lev][j+1] = teval; complex<double>* tevec = evecs[lev][j]; evecs[lev][j] = evecs[lev][j+1]; evecs[lev][j+1] = tevec; } break; } } } cout << "\n\nAll eigenvalues:\n"; for (i = 0; i < n_eigen[lev]; i++) { cout << "[L" << lev+1 << "_FINEVAL]: Mass " << stagif->mass << " Num " << i << " Eval " << real(evals[lev][i]) << " + " << imag(evals[lev][i]) << " *I\n"; normalize<double>(evecs[lev][i], mgstruct.curr_fine_size); } if (lev < mgstruct.n_refine-1) { level_down(&mgstruct); } } // Something special for the coarsest level lev = mgstruct.n_refine; n_eigen[lev] = 0; n_cv = 0; if (set_eigen == -1 && set_cv == -1) // generate all eigenvalues, eigenvectors. { // Allocate space for all eigenvalues, eigenvectors. n_eigen[lev] = mgstruct.curr_coarse_size; n_cv = mgstruct.curr_coarse_size; cout << "[L" << lev+1 << "_ARPACK]: Number of eigenvalues: " << n_eigen[lev] << " Number of cv: " << n_cv << "\n"; evals[lev] = new complex<double>[mgstruct.curr_coarse_size]; evecs[lev] = new complex<double>*[mgstruct.curr_coarse_size]; for (i = 0; i < n_eigen[lev]; i++) { evecs[lev][i] = new complex<double>[mgstruct.curr_coarse_size]; } // Get low mag half arpack_dcn_t* ar_strc = arpack_dcn_init(mgstruct.curr_coarse_size, n_eigen[lev]/2, n_cv); // max eigenvectors, internal vecs char eigtype[3]; strcpy(eigtype, "SM"); // Smallest magnitude eigenvalues. arpack_solve_t info_solve = arpack_dcn_getev(ar_strc, evals[lev], evecs[lev], mgstruct.curr_coarse_size, n_eigen[lev]/2, n_cv, 4000, eigtype, 1e-7, 0.0, coarse_square_staggered, (void*)&mgstruct); //arpack_dcn_free(&ar_strc); // Print info about the eigensolve. cout << "[L" << lev+1 << "_ARPACK]: Number of converged eigenvalues: " << info_solve.nconv << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of iteration steps: " << info_solve.niter << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of matrix multiplies: " << info_solve.nops << "\n"; // Get high mag half //arpack_dcn_t* ar_strc = arpack_dcn_init(mgstruct.curr_coarse_size, n_eigen, n_cv); // max eigenvectors, internal vecs strcpy(eigtype, "LM"); // Smallest magnitude eigenvalues. info_solve = arpack_dcn_getev(ar_strc, evals[lev]+(mgstruct.curr_coarse_size/2), evecs[lev]+(mgstruct.curr_coarse_size/2), mgstruct.curr_coarse_size, n_eigen[lev]/2, n_cv, 4000, eigtype, 1e-7, 0.0, coarse_square_staggered, (void*)&mgstruct); arpack_dcn_free(&ar_strc); // Print info about the eigensolve. cout << "[L" << lev+1 << "_ARPACK]: Number of converged eigenvalues: " << info_solve.nconv << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of iteration steps: " << info_solve.niter << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of matrix multiplies: " << info_solve.nops << "\n"; // End of arpack bindings! } else if (set_eigen != -1 && set_cv == -1) // generate n_eigen eigenvalues, min(mgstruct.curr_coarse_size, 2.5 n_eigen) cv. { n_eigen[lev] = set_eigen; n_cv = min(mgstruct.curr_coarse_size, 2*n_eigen[lev] + n_eigen[lev]/2); cout << "[L" << lev+1 << "_ARPACK]: Number of eigenvalues: " << n_eigen[lev] << " Number of cv: " << n_cv << "\n"; evals[lev] = new complex<double>[n_eigen[lev]]; evecs[lev] = new complex<double>*[n_eigen[lev]]; for (i = 0; i < n_eigen[lev]; i++) { evecs[lev][i] = new complex<double>[mgstruct.curr_coarse_size]; } // Get low mag half arpack_dcn_t* ar_strc = arpack_dcn_init(mgstruct.curr_coarse_size, n_eigen[lev], n_cv); // max eigenvectors, internal vecs char eigtype[3]; strcpy(eigtype, "SM"); // Smallest magnitude eigenvalues. arpack_solve_t info_solve = arpack_dcn_getev(ar_strc, evals[lev], evecs[lev], mgstruct.curr_coarse_size, n_eigen[lev], n_cv, 4000, eigtype, 1e-7, 0.0, coarse_square_staggered, (void*)&mgstruct); arpack_dcn_free(&ar_strc); // Print info about the eigensolve. cout << "[L" << lev+1 << "_ARPACK]: Number of converged eigenvalues: " << info_solve.nconv << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of iteration steps: " << info_solve.niter << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of matrix multiplies: " << info_solve.nops << "\n"; } else // generate n_eigen eigenvalues, min(mgstruct.curr_coarse_size, n_cv) cv. { n_eigen[lev] = set_eigen; n_cv = set_cv; cout << "[L" << lev+1 << "_ARPACK]: Number of eigenvalues: " << n_eigen[lev] << " Number of cv: " << n_cv << "\n"; evals[lev] = new complex<double>[n_eigen[lev]]; evecs[lev] = new complex<double>*[n_eigen[lev]]; for (i = 0; i < n_eigen[lev]; i++) { evecs[lev][i] = new complex<double>[mgstruct.curr_coarse_size]; } // Get low mag half arpack_dcn_t* ar_strc = arpack_dcn_init(mgstruct.curr_coarse_size, n_eigen[lev], n_cv); // max eigenvectors, internal vecs char eigtype[3]; strcpy(eigtype, "SM"); // Smallest magnitude eigenvalues. arpack_solve_t info_solve = arpack_dcn_getev(ar_strc, evals[lev], evecs[lev], mgstruct.curr_coarse_size, n_eigen[lev], n_cv, 4000, eigtype, 1e-7, 0.0, coarse_square_staggered, (void*)&mgstruct); arpack_dcn_free(&ar_strc); // Print info about the eigensolve. cout << "[L" << lev+1 << "_ARPACK]: Number of converged eigenvalues: " << info_solve.nconv << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of iteration steps: " << info_solve.niter << "\n"; cout << "[L" << lev+1 << "_ARPACK]: Number of matrix multiplies: " << info_solve.nops << "\n"; } // Sort eigenvalues (done differently depending on the operator). for (i = 0; i < n_eigen[lev]; i++) { for (j = 0; j < n_eigen[lev]-1; j++) { switch (opt) { case STAGGERED: if (abs(imag(evals[lev][j])) > abs(imag(evals[lev][j+1]))) { complex<double> teval = evals[lev][j]; evals[lev][j] = evals[lev][j+1]; evals[lev][j+1] = teval; complex<double>* tevec = evecs[lev][j]; evecs[lev][j] = evecs[lev][j+1]; evecs[lev][j+1] = tevec; } break; case LAPLACE: case LAPLACE_NC2: case G5_STAGGERED: case STAGGERED_NORMAL: case STAGGERED_INDEX: if (abs(real(evals[lev][j])) > abs(real(evals[lev][j+1]))) { complex<double> teval = evals[lev][j]; evals[lev][j] = evals[lev][j+1]; evals[lev][j+1] = teval; complex<double>* tevec = evecs[lev][j]; evecs[lev][j] = evecs[lev][j+1]; evecs[lev][j+1] = tevec; } break; } } } cout << "\n\nAll eigenvalues:\n"; for (i = 0; i < n_eigen[lev]; i++) { cout << "[L" << lev+1 << "_FINEVAL]: Mass " << stagif->mass << " Num " << i << " Eval " << real(evals[lev][i]) << " + " << imag(evals[lev][i]) << " *I\n"; normalize<double>(evecs[lev][i], mgstruct.curr_fine_size); } // End generating coarse level. for (lev = mgstruct.n_refine-2; lev >= 0; lev--) { level_up(&mgstruct); } for (lev = 0; lev < mgstruct.n_refine; lev++) { complex<double>* evec_Pdag = new complex<double>[mgstruct.curr_coarse_size]; complex<double>* evec_Pdag2 = new complex<double>[mgstruct.curr_coarse_size]; complex<double>* evec_PPdag = new complex<double>[mgstruct.curr_fine_size]; // Test overlap of null vectors with eigenvectors. // Formally, this is looking at the magnitude of (1 - P P^\dag) eigenvector. for (i = 0; i < n_eigen[lev]; i++) { // Zero out. zero<double>(evec_Pdag, mgstruct.curr_coarse_size); zero<double>(evec_PPdag, mgstruct.curr_fine_size); // Restrict eigenvector. restrict(evec_Pdag, evecs[lev][i], &mgstruct); // Prolong. prolong(evec_PPdag, evec_Pdag, &mgstruct); // Subtract off eigenvector, take norm. for (j = 0; j < mgstruct.curr_fine_size; j++) { evec_PPdag[j] -= evecs[lev][i][j]; } cout << "[L" << lev+1 << "_1mPPDAG]: Num " << i << " Overlap " << sqrt(norm2sq<double>(evec_PPdag, mgstruct.curr_fine_size)) << "\n"; } // Test how good of a preconditioner the coarse operator is. // Formally, this is looking at the magnitude of (1 - P ( P^\dag A P )^(-1) P^\dag A) eigenvector. for (i = 0; i < n_eigen[lev]; i++) { // Zero out. zero<double>(evec_Pdag, mgstruct.curr_coarse_size); zero<double>(evec_Pdag2, mgstruct.curr_coarse_size); zero<double>(evec_PPdag, mgstruct.curr_fine_size); // Apply A. fine_square_staggered(evec_PPdag, evecs[lev][i], (void*)&mgstruct); // Restrict. restrict(evec_Pdag, evec_PPdag, &mgstruct); // Try a deflation preconditioned solve... for (j = 0; j < n_eigen[lev+1]; j++) { complex<double> def_dot = dot<double>(evecs[lev+1][j], evec_Pdag, mgstruct.curr_coarse_size); for (k = 0; k < mgstruct.curr_coarse_size; k++) { evec_Pdag2[k] += 1.0/(evals[lev+1][j])*def_dot*evecs[lev+1][j][k]; } } // Invert A_coarse against it. invif = minv_vector_gcr_restart(evec_Pdag2, evec_Pdag, mgstruct.curr_coarse_size, 10000, 1e-7, 64, coarse_square_staggered, (void*)&mgstruct); //cout << "[L" << lev+1 << "_DEFLATE]: Num " << i << " Iter " << invif.iter << "\n"; // Prolong. zero<double>(evec_PPdag, mgstruct.curr_coarse_size); prolong(evec_PPdag, evec_Pdag2, &mgstruct); // Subtract off eigenvector, take norm. for (j = 0; j < mgstruct.curr_fine_size; j++) { evec_PPdag[j] -= evecs[lev][i][j]; } cout << "[L" << lev+1 << "_1mP_Ac_PDAG_A]: Num " << i << " Overlap " << sqrt(norm2sq<double>(evec_PPdag, mgstruct.curr_fine_size)) << "\n"; } delete[] evec_Pdag; delete[] evec_PPdag; delete[] evec_Pdag2; if (lev < mgstruct.n_refine-1) { level_down(&mgstruct); } } for (lev = mgstruct.n_refine-2; lev >= 0; lev--) { level_up(&mgstruct); } for (lev = 0; lev <= mgstruct.n_refine; lev++) { for (i = 0; i < n_eigen[lev]; i++) { delete[] evecs[lev][i]; } delete[] evals[lev]; delete[] evecs[lev]; } delete[] evecs; delete[] evals; delete[] n_eigen; } // Test constructing the coarse operator, comparing to using prolong/restrict of fine. void test_stencil_construct(mg_operator_struct_complex* mgstruct, int level, int stencil_size) { // A few sanity checks... if (level > mgstruct->n_refine+1) { cout << "[TEST_ERROR]: Stencil construct level " << level << " is larger than the number of mg levels.\n" << flush; return; } if (stencil_size > 2) { cout << "[TEST_ERROR]: Stencil distances greater than 2 are not supported.\n" << flush; return; } stencil_2d stenc(mgstruct->latt[level], stencil_size); // Save mgstruct level state. int save_level = mgstruct->curr_level; if (save_level > 0) { for (int i = 0; i < save_level; i++) { level_up(mgstruct); } } // Push down an appropriate number of levels. if (level > 0) { for (int i = 0; i < level-1; i++) { level_down(mgstruct); } } // Carry on. if (level == 0) { generate_stencil_2d(&stenc, fine_square_staggered, (void*)mgstruct); } else { generate_stencil_2d(&stenc, coarse_square_staggered, (void*)mgstruct); } cout << "[TEST]: Level " << level+1 << " Generated stencil.\n" << flush; complex<double>* tmp_rhs = new complex<double>[mgstruct->latt[level]->get_lattice_size()]; complex<double>* tmp_lhs = new complex<double>[mgstruct->latt[level]->get_lattice_size()]; // Whelp, it's something. Let's test it. //zero<double>(tmp_rhs, mgstruct->latt[level]->get_lattice_size()); //tmp_rhs[0] = 1.0; std::mt19937 generator (1339u); // RNG, 1339u is the seed. gaussian<double>(tmp_rhs, mgstruct->latt[level]->get_lattice_size(), generator); apply_stencil_2d(tmp_lhs, tmp_rhs, (void*)&stenc); complex<double>* tmp_lhs2 = new complex<double>[mgstruct->latt[level]->get_lattice_size()]; if (level == 0) { fine_square_staggered(tmp_lhs2, tmp_rhs, (void*)mgstruct); } else { coarse_square_staggered(tmp_lhs2, tmp_rhs, (void*)mgstruct); } // Get squared difference. cout << "[TEST]: Level " << level+1 << " Squared difference: " << diffnorm2sq<double>(tmp_lhs, tmp_lhs2, mgstruct->latt[level]->get_lattice_size()) << "\n" << flush; delete[] tmp_rhs; delete[] tmp_lhs; delete[] tmp_lhs2; // Restore level if (level > 0) { for (int i = 0; i < level-1; i++) { level_up(mgstruct); } } // Restore level. if (save_level > 0) { for (int i = 0; i < save_level; i++) { level_down(mgstruct); } } } // Test constructing the coarse operator, comparing applying the full coarse stencil to the piece-by-piece stencil. void test_stencil_piece(mg_operator_struct_complex* mgstruct, int level, int stencil_size) { // A few sanity checks... if (level > mgstruct->n_refine+1) { cout << "[TEST_ERROR]: Stencil construct level " << level << " is larger than the number of mg levels.\n" << flush; return; } if (stencil_size > 2) { cout << "[TEST_ERROR]: Stencil distances greater than 2 are not supported.\n" << flush; return; } stencil_2d stenc(mgstruct->latt[level], stencil_size); // Save mgstruct level state. int save_level = mgstruct->curr_level; if (save_level > 0) { for (int i = 0; i < save_level; i++) { level_up(mgstruct); } } // Push down an appropriate number of levels. if (level > 0) { for (int i = 0; i < level-1; i++) { level_down(mgstruct); } } // Carry on. if (level == 0) { generate_stencil_2d(&stenc, fine_square_staggered, (void*)mgstruct); } else { generate_stencil_2d(&stenc, coarse_square_staggered, (void*)mgstruct); } cout << "[TEST]: Level " << level+1 << " Generated stencil.\n" << flush; complex<double>* tmp_rhs = new complex<double>[mgstruct->latt[level]->get_lattice_size()]; complex<double>* tmp_lhs = new complex<double>[mgstruct->latt[level]->get_lattice_size()]; complex<double>* tmp_lhs2 = new complex<double>[mgstruct->latt[level]->get_lattice_size()]; complex<double>* tmp_save = new complex<double>[mgstruct->latt[level]->get_lattice_size()]; // Whelp, it's something. Let's test it. Use a random rhs. // This applies the full operator. stenc.sdir = DIR_ALL; std::mt19937 generator (1339u); // RNG, 1339u is the seed. gaussian<double>(tmp_rhs, mgstruct->latt[level]->get_lattice_size(), generator); apply_stencil_2d(tmp_lhs, tmp_rhs, (void*)&stenc); // Good! Now try applying all of the stencil pieces, one at a time. zero<double>(tmp_save, mgstruct->latt[level]->get_lattice_size()); // A little enum abuse... Loop over all pieces. for (int i = 1; i <= (int)(stencil_size == 1 ? DIR_YM1 : DIR_XP1YM1); i++) { stenc.sdir = (stencil_dir)i; // Set a direction. apply_stencil_2d(tmp_lhs2, tmp_rhs, (void*)&stenc); // Apply that piece of the stencil. for (int j = 0; j < mgstruct->latt[level]->get_lattice_size(); j++) { tmp_save[j] += tmp_lhs2[j]; } } // And compare via squared difference! cout << "[TEST]: Level " << level+1 << " Squared difference: " << diffnorm2sq<double>(tmp_lhs, tmp_save, mgstruct->latt[level]->get_lattice_size()) << "\n" << flush; delete[] tmp_rhs; delete[] tmp_lhs; delete[] tmp_lhs2; delete[] tmp_save; // Restore level if (level > 0) { for (int i = 0; i < level-1; i++) { level_up(mgstruct); } } // Restore level. if (save_level > 0) { for (int i = 0; i < save_level; i++) { level_down(mgstruct); } } } #endif // MG_TEST_FILE
#ifndef MESH_H #define MESH_H #include <vector> #include "PhotonBox/core/ILazyLoadable.h" #include "PhotonBox/core/ManagedResource.h" #include "PhotonBox/data-type/Vertex.h" #include "PhotonBox/data-type/BoundingSphere.h" #include "PhotonBox/core/OpenGL.h" class Mesh : public ManagedResource, public ILazyLoadable { public: std::vector< Vertex > vertices; std::vector< unsigned int> indices; BoundingSphere boundingSphere; Mesh(const std::string& fileName, bool forceInit = false); ~Mesh(); GLuint getVAO(); GLuint getEBO(); void sendToGPU() override; private: GLuint _vao, _vbo, _ebo; std::string _fileName; void loadFromFile() override; void blankInitialize() override; }; #endif // MESH_H
#include <iostream> #include <vector> #include <algorithm> int main(int argc,char *argv[]) { int n; std::cin >> n; std::vector<int> v(n); for(int i = 0;i < n;i++) std::cin >> v[i]; std::sort(v.begin(),v.end(),std::greater<int>()); v.erase(std::unique(v.begin(),v.end()),v.end()); std::cout << v.size() << std::endl; return 0; }
#ifndef MATRIX_H #define MATRIX_H #include "Data.hpp" namespace uipf{ // Matrix which is a specification of Data class Matrix : public Data { public: typedef SMARTPOINTER<Matrix> ptr; typedef const SMARTPOINTER<Matrix> c_ptr; public: // default constructor Matrix() {} // constructor Matrix(cv::Mat& mat): matrix_(mat) {} // copy constructor Matrix(const Matrix& mat): matrix_(mat.matrix_.clone()) {} // destructor ~Matrix(void){}; // get content (returns a cloned version of Mat by default) // this is due to prevent overwriting accidentally cv::Mat getContent(bool bAutoClone = true) const; // sets the content of the matrix void setContent(cv::Mat&); // returns the data type of this data object: in this case: MATRIX Type getType() const override; private: // content of the matrix cv::Mat matrix_; }; } // namespace #endif
#pragma once #include "CollisionDetection.h" namespace CollisionDetection { /* This function is used to detect if a circle of a given radius and a current position, that wants to go to nextPosition, will intersect the segment [start, end]. This function returns by side effect the point of intersection and the normal. To solve de collision problem, we consider the distance between the circle and the segment as a function. If this distance is less than the radius, then we've got collision. The algorithm is as follows: - parametrize both segments - compute the shortest path to the segment of the object - compute if the ball will collide with this segment on the next position Both computations are similar. A more complete approach would be to determine that position by solving the system of ecuations of both segments. This is a more simple approach and gives good results for low speeds. */ bool CollisionDetection::CollisionWithSegment(glm::vec2 start, glm::vec2 end, float radius, glm::vec2 crtPosition, glm::vec2 nextPosition, glm::vec2 *point, glm::vec2 *normal) { // Compute the minimum distance between the segment and the ball // First of all, compute the coefficients of distance function: // f : [0,1] -> R, f(s) = A * s^2 + B * s + C float A = glm::pow(end.x - start.x, 2) + glm::pow(end.y - start.y, 2); float B = 2 * ((end.x - start.x) * (start.x - crtPosition.x) + (end.y - start.y) * (start.y - crtPosition.y)); float C = glm::pow(start.x - crtPosition.x, 2) + glm::pow(start.y - crtPosition.y, 2); // Compute delta for function of s float delta_s = B * B - 4 * A * C; // Compute the minimum point (s, f_s) float s = -B / (2 * A); float f_s = -delta_s / (4 * A); // Compute the normal vector // dx = x2-x1 and dy = y2-y1 => N = (-dy, dx) if (normal != NULL) { normal->x = -(end.y - start.y); normal->y = end.x - start.x; *normal = glm::normalize(*normal); } // Check for collision if (0 <= s && s <= 1) { if (f_s <= radius * radius) return true; } else { if (glm::min(C, A + B + C) <= radius * radius) return true; return false; } // Compute the (x0, y0) point w.r.t s float x0 = start.x + s * (end.x - start.x); float y0 = start.y + s * (end.y - start.y); if (point != NULL) { point->x = x0; point->y = y0; } // Compute the minimum distance between the segment and the ball // First of all, compute the coefficients of distance function: // f : [0,1] -> R, f(s) = A * s^2 + B * s + C A = glm::pow(nextPosition.x - crtPosition.x, 2) + glm::pow(nextPosition.y - crtPosition.y, 2); B = 2 * ((nextPosition.x - crtPosition.x) * (crtPosition.x - x0) + (nextPosition.y - crtPosition.y) * (crtPosition.y - y0)); C = glm::pow(crtPosition.x - x0, 2) + glm::pow(crtPosition.y - y0, 2); // Compute delta for function of t float delta_t = B * B - 4 * A * C; // Compute the minimum point (f, f_f) float t = -B / (2 * A); float f_t = -delta_t / (4 * A); // Check for collision if (0 <= t && t <= 1) { if (f_t <= radius * radius) return true; } else { if (glm::min(C, A + B + C) <= radius * radius) return true; } // Here we don't have any collision. return false; } }
/********************************************************************* ** Author: Chris Matian ** Date: 07/24/2017 ** Description: Class specification header file for the Entree Functions *********************************************************************/ #ifndef ENTREE_HPP #define ENTREE_HPP #include <string> using std::string; class Entree { private: string entreeName; int entreeCalories; public: //Constructor Prototypes Entree(); Entree(string, int); //Methods string getName(); int getNumCalories(); }; #endif
#ifndef GAME_UTIL_H #define GAME_UTIL_H #include <SFML/System/Vector2.hpp> constexpr float DEG_TO_RAD = 0.0174533f; constexpr float G = 9.82f; namespace Platy { namespace Game { class Util { public: Util() = delete; ~Util() = default; static sf::Vector2f DegToVec2(const float& anAngle); static sf::Vector2f Lerp(const sf::Vector2f& a, const sf::Vector2f& b, float amount); static float Lerp(const float& a, const float& b, const float& amount); static sf::Vector2f RandVec2(float aMinX, float aMaxX, float aMinY, float aMaxY); static float Abs(sf::Vector2f vector); }; } } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2006 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifdef SETUP_INFO #include "modules/hardcore/opera/setupinfo.h" int OpSetupInfo::GetFeatureCount() { // <GetFeatureCount> } OpSetupInfo::Feature OpSetupInfo::GetFeature(int index) { Feature f; f.name = UNI_L(""); f.enabled = FALSE; f.description = UNI_L(""); f.owner = UNI_L(""); switch (index) { // <GetFeature> } return f; } #endif // SETUP_INFO
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright 2005-2012 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #include "modules/prefs/prefsmanager/collections/pc_parsing.h" #include "modules/prefs/prefsmanager/collections/prefs_macros.h" #include "modules/prefs/prefsmanager/collections/pc_parsing_c.inl" PrefsCollectionParsing *PrefsCollectionParsing::CreateL(PrefsFile *reader) { if (g_opera->prefs_module.m_pcparsing) LEAVE(OpStatus::ERR); g_opera->prefs_module.m_pcparsing = OP_NEW_L(PrefsCollectionParsing, (reader)); return g_opera->prefs_module.m_pcparsing; } PrefsCollectionParsing::~PrefsCollectionParsing() { #ifdef PREFS_COVERAGE CoverageReport( m_stringprefdefault, PCPARSING_NUMBEROFSTRINGPREFS, m_integerprefdefault, PCPARSING_NUMBEROFINTEGERPREFS); #endif g_opera->prefs_module.m_pcparsing = NULL; } void PrefsCollectionParsing::ReadAllPrefsL(PrefsModule::PrefsInitInfo *) { // Read everything OpPrefsCollection::ReadAllPrefsL( m_stringprefdefault, PCPARSING_NUMBEROFSTRINGPREFS, m_integerprefdefault, PCPARSING_NUMBEROFINTEGERPREFS); } #ifdef PREFS_VALIDATE void PrefsCollectionParsing::CheckConditionsL(int which, int *value, const uni_char *) { // Check any post-read/pre-write conditions and adjust value accordingly switch (static_cast<integerpref>(which)) { case ShowHTMLParsingErrors: break; default: // Unhandled preference! For clarity, all preferenes not needing to // be checked should be put in an empty case something: break; clause // above. OP_ASSERT(!"Unhandled preference"); } } BOOL PrefsCollectionParsing::CheckConditionsL(int which, const OpStringC &invalue, OpString **outvalue, const uni_char *) { // Check any post-read/pre-write conditions and adjust value accordingly // with a code like this : switch (static_cast<stringpref>(which)) // Unhandled preference! For clarity, all preferenes not needing to // be checked should be put in an empty case something: break; clause // above. OP_ASSERT(!"Unhandled preference"); // When FALSE is returned, no OpString is created for outvalue return FALSE; } #endif // PREFS_VALIDATE
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "Packet.h" TEST_CASE( "Boolean", "[bool]" ) { Packet< 2 > packet; boolean in = false; packet << in; in = true; packet << in; boolean out = false; packet >> out; REQUIRE( out == false ); packet >> out; REQUIRE( out == true ); } TEST_CASE( "Unsigned Byte", "[unsigned-byte]" ) { Packet< 1 > packet; uint8 in = 'a'; packet << in; uint8 out = 0x00U; packet >> out; REQUIRE( out == 'a' ); } TEST_CASE( "Signed Byte", "[signed-byte]" ) { Packet< 1 > packet; sint8 in = -120; packet << in; sint8 out = 0x00; packet >> out; REQUIRE( out == -120 ); } TEST_CASE( "Unsigned Word", "[unsigned-word]" ) { Packet< 2 > packet; uint16 in = 0x1234U; packet << in; uint16 out = 0x0000U; packet >> out; REQUIRE( out == 0x1234U ); } TEST_CASE( "Signed Word", "[signed-word]" ) { Packet< 2 > packet; sint16 in = -23000; packet << in; sint16 out = 0; packet >> out; REQUIRE( out == -23000 ); } TEST_CASE( "Unsigned Double Word", "[unsigned-dword]" ) { Packet< 4 > packet; uint32 in = 0x12345678U; packet << in; uint32 out = 0x00000000UL; packet >> out; REQUIRE( out == 0x12345678U ); } TEST_CASE( "Signed Double Word", "[signed-dword]" ) { Packet< 4 > packet; sint32 in = -1012397; packet << in; sint32 out = 0x00000000L; packet >> out; REQUIRE( out == -1012397 ); } TEST_CASE( "Unsigned Quad Word", "[unsigned-qword]" ) { Packet< 8 > packet; uint64 in = 0x1234567811776688ULL; packet << in; uint64 out = 0x00ULL; packet >> out; REQUIRE( out == 0x1234567811776688U ); } TEST_CASE( "Floating Point 32 Bit", "[float32]" ) { Packet< 4 > packet; float32 in = -2.56F; packet << in; float32 out = 0.0F; packet >> out; REQUIRE( out == -2.56F ); } TEST_CASE( "Floating Point 64 Bit", "[float64]" ) { Packet< 8 > packet; float64 in = -90.66F; packet << in; float64 out = 0.0F; packet >> out; REQUIRE( out == -90.66F ); } TEST_CASE( "C-String", "[c-string]" ) { Packet< 11 > packet; const char* in = "packet"; packet << in; char out[6] = ""; packet >> out; REQUIRE( std::strcmp(in, out) == 0 ); }
#include <bits/stdc++.h> #define INF 1<<30 #define MAXN 99 #define MAXC 31 using namespace std; char names[MAXN][MAXC + 1]; int dists[MAXN][MAXN], nexts[MAXN][MAXN]; int get_index(int n, const char* name) { for (int i = 0; i < n; i++) if (!strcmp(name, names[i])) return i; return -1; } void floyd_warshall_with_path_reconstruction(int n) { for (int k = 0; k < n; k++) for (int i = 0; i < n; i++) if (dists[i][k] != INF) for (int j = 0; j < n; j++) if (dists[k][j] != INF && dists[i][k] + dists[k][j] < dists[i][j]) { dists[i][j] = dists[i][k] + dists[k][j]; nexts[i][j] = nexts[i][k]; } } void print_path(int u, int v) { printf("Path:%s", names[u]); do { u = nexts[u][v]; printf(" %s", names[u]); }while (u != v); putchar('\n'); } int main() { int C; scanf("%d", &C); while(C--) { int P; scanf("%d", &P); for (int i = 0; i < P; i++) scanf("%s", names[i]); for (int i = 0; i < P; i++) for (int j = 0; j < P; j++) { int C; scanf("%d", &C); dists[i][j] = (C >= 0) ? C : INF; nexts[i][j] = j; } floyd_warshall_with_path_reconstruction(P); int R; scanf("%d", &R); while (R--) { char employee[MAXC + 1], start[MAXC + 1], end[MAXC + 1]; scanf("%s %s %s", employee, start, end); int s = get_index(P, start), e = get_index(P, end); if(dists[s][e] != INF) { printf("Mr %s to go from %s to %s, you will receive %d euros\n", employee, start, end, dists[s][e]); print_path(s, e); } else printf("Sorry Mr %s you can not go from %s to %s\n", employee, start, end); } } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** This file needs to exist since inlining 'OpProbeTime::TrueSeconds' would ** cause cyclic include file problems. ** ** Morten Rolland, mortenro@opera.com */ #include "core/pch.h" #ifdef SUPPORT_PROBETOOLS #include "modules/probetools/src/probetimer.h" #include "modules/pi/OpSystemInfo.h" //--------------------------------------- //STAMPER FOR OP_SYS_INFO->GetRuntimeMS== #if defined(OP_PROBETOOLS_USES_OP_SYS_INFO_TIMER) /*inline*/ void OpProbeTimestamp::timestamp_now(){ if(g_opera && g_op_system_info){//needed for OpFile probes under startup stamp64d = g_op_time_info->GetRuntimeMS(); } else { stamp64d = 0; } } double OpProbeTimestamp::get_time(){ return stamp64d; } void OpProbeTimestamp::set(double d){ stamp64d = d; } //--------------------------------------- //STAMPER FOR WIN32HRPC #elif defined(OP_PROBETOOLS_USES_WIN32HRPC_TIMER) #include <sys/timeb.h> /*inline*/ void OpProbeTimestamp::timestamp_now(){ LARGE_INTEGER now_qpc; QueryPerformanceCounter(&now_qpc); stamp64i = now_qpc.QuadPart; } double OpProbeTimestamp::get_time(){ LARGE_INTEGER qpc_freq; QueryPerformanceFrequency(&qpc_freq); return (((stamp64i)/static_cast<double>(qpc_freq.QuadPart))*1000.0); } void OpProbeTimestamp::set(double d){ LARGE_INTEGER qpc_freq; QueryPerformanceFrequency(&qpc_freq); stamp64i = (((d)*static_cast<double>(qpc_freq.QuadPart))/1000.0); } #endif //DONE WITh STAMPERS //--------------------------------------- //--------------------------------------- //OPERATORS FOR (stamp64d)== #if defined(OP_PROBETOOLS_USES_OP_SYS_INFO_TIMER) OpProbeTimestamp OpProbeTimestamp::operator+(const OpProbeTimestamp& tm) { OpProbeTimestamp sum; sum.stamp64d = this->stamp64d + tm.stamp64d; return sum; } OpProbeTimestamp OpProbeTimestamp::operator-(const OpProbeTimestamp& tm) { OpProbeTimestamp sum; sum.stamp64d = this->stamp64d - tm.stamp64d; return sum; } bool OpProbeTimestamp::operator<(const OpProbeTimestamp& tm) { return this->stamp64d < tm.stamp64d; } bool OpProbeTimestamp::operator>(const OpProbeTimestamp& tm) { return this->stamp64d > tm.stamp64d; } OpProbeTimestamp OpProbeTimestamp::operator=(const OpProbeTimestamp& ts) { this->stamp64d = ts.stamp64d; return *this; } OpProbeTimestamp OpProbeTimestamp::operator+=(const OpProbeTimestamp& tm) { this->stamp64d += tm.stamp64d; return *this; } OpProbeTimestamp OpProbeTimestamp::operator-=(const OpProbeTimestamp& tm) { this->stamp64d -= tm.stamp64d; return *this; } void OpProbeTimestamp::zero(){ stamp64d = 0.0; } //--------------------------------------- //OPERATORS FOR (stamp64i)== #elif defined(OP_PROBETOOLS_USES_WIN32HRPC_TIMER) OpProbeTimestamp OpProbeTimestamp::operator+(const OpProbeTimestamp& tm) { OpProbeTimestamp sum; sum.stamp64i = this->stamp64i + tm.stamp64i; return sum; } OpProbeTimestamp OpProbeTimestamp::operator-(const OpProbeTimestamp& tm) { OpProbeTimestamp sum; sum.stamp64i = this->stamp64i - tm.stamp64i; return sum; } bool OpProbeTimestamp::operator<(const OpProbeTimestamp& tm) { return this->stamp64i < tm.stamp64i; } bool OpProbeTimestamp::operator>(const OpProbeTimestamp& tm) { return this->stamp64i > tm.stamp64i; } OpProbeTimestamp OpProbeTimestamp::operator=(const OpProbeTimestamp& ts) { this->stamp64i = ts.stamp64i; return *this; } OpProbeTimestamp OpProbeTimestamp::operator+=(const OpProbeTimestamp& tm) { this->stamp64i += tm.stamp64i; return *this; } OpProbeTimestamp OpProbeTimestamp::operator-=(const OpProbeTimestamp& tm) { this->stamp64i -= tm.stamp64i; return *this; } void OpProbeTimestamp::zero(){ stamp64i = 0; } #endif //DONE WITh OPERATORS //--------------------------------------- #endif //SUPPORT_PROBETOOLS
#include "precompiled.h" #include "physics/shapecache.h" #include "physics/xmlloader.h" namespace physics { typedef map<string, ShapeEntry> entry_map_type; entry_map_type entry_map; } using namespace physics; ShapeEntry physics::getShapeEntry(const string& name) { entry_map_type::iterator it = entry_map.find(name); if (it == entry_map.end()) { ShapeEntry entry = loadDynamicsXML(name); if(!entry) { INFO("ERROR: unable to load shape data from %s", name.c_str()); return entry; } entry_map[name] = entry; return entry; } return it->second; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Opera test plugin. * * Plugin entry points and associated helper functions. * * Copyright (C) 2011 Opera Software ASA. */ #include <cassert> #include <cstdio> #include "common.h" /** * Create new plugin instance. * * @See https://developer.mozilla.org/en/NPP_New. */ NPError NPP_New(NPMIMEType plugin_type, NPP instance, uint16_t mode, int16_t argc, char** argn, char** argv, NPSavedData* /*data*/) { /* Don't allow new instances after crash. Crash again to send a message? */ if (g_crashed) return NPERR_INVALID_PLUGIN_ERROR; /* Verify mime type. */ if (!plugin_type || strcmp(plugin_type, MIME_TYPE)) return NPERR_INVALID_PARAM; /* Only accept embedded mode (as opposed to exist without a document). */ if (mode != NP_EMBED) return NPERR_INVALID_PARAM; /* Default to windowed and no onload function. */ bool windowless = false; bool windowless_param_found = false; const char* onload = 0; const char* bgcolor = 0; for (int i = 0; i < argc; i++) { if (!windowless_param_found && (windowless_param_found = !STRCASECMP(argn[i], "windowless"))) windowless = !STRCASECMP(argv[i], "true") ? true : false; else if (!STRCASECMP(argn[i], "_onload")) onload = argv[i]; else if (!STRCASECMP(argn[i], "bgcolor")) bgcolor = argv[i]; } #ifdef XP_GOGI /* For GOGI we would like to run the plugin as windowless even if the * client specifically has requested to use windowed mode. The reason for * this is that we would like to be able to run all the TC's for the plugin * even if we haven't implemented windowed mode. */ if (!windowless) windowless = true; #endif // XP_GOGI #ifdef XP_MACOSX /* Only windowless plugins are supported on Mac. */ if (windowless_param_found && !windowless) return NPERR_INVALID_PARAM; /* When no windowless param specified, default to windowless. */ windowless = true; #endif // XP_MACOSX /* Create new plugin instance. */ PluginInstance* pi; if (windowless) pi = new WindowlessInstance(instance, bgcolor); else pi = new WindowedInstance(instance, bgcolor); if (!pi) return NPERR_OUT_OF_MEMORY_ERROR; if (!pi->Initialize()) { delete pi; return NPERR_INVALID_PARAM; } /* Verify arguments. */ NPError err = pi->CheckArguments(argc, argn, argv); if (err != NPERR_NO_ERROR) { delete pi; return err; } instance->pdata = pi; /* * The following evaluation may induce many calls to the newly * created instance and all will take place prior to this function * completing. Be aware. */ if (onload) { if (NPObject* global = pi->GetGlobalObject()) { NPString script; script.UTF8Characters = onload; script.UTF8Length = static_cast<uint32_t>(strlen(onload)); NPVariant return_value; if (g_browser->evaluate(instance, global, &script, &return_value)) g_browser->releasevariantvalue(&return_value); } } return NPERR_NO_ERROR; } /** * Destroy plugin instance. * * @See https://developer.mozilla.org/en/NPP_Destroy. */ NPError NPP_Destroy(NPP instance, NPSavedData** /*data*/) { if (instance && instance->pdata) static_cast<PluginInstance*>(instance->pdata)->SafeDelete(); return NPERR_NO_ERROR; } /** * Window create, move, resize or destroy notification. * * @See https://developer.mozilla.org/en/NPP_SetWindow. */ NPError NPP_SetWindow(NPP instance, NPWindow* window) { if (PluginInstance* pi = static_cast<PluginInstance*>(instance->pdata)) return pi->SetWindow(window); return NPERR_INVALID_INSTANCE_ERROR; } /** * New data stream notification. * * @See https://developer.mozilla.org/en/NPP_NewStream. */ NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16_t* stype) { if (PluginInstance* pi = static_cast<PluginInstance*>(instance->pdata)) return pi->NewStream(type, stream, seekable, stype); return NPERR_INVALID_INSTANCE_ERROR; } /** * Data stream close or destroy notification. * * @See https://developer.mozilla.org/en/NPP_DestroyStream. */ NPError NPP_DestroyStream(NPP instance, NPStream* stream, NPReason reason) { if (PluginInstance* pi = static_cast<PluginInstance*>(instance->pdata)) return pi->DestroyStream(stream, reason); return NPERR_INVALID_INSTANCE_ERROR; } /** * Provide a local file name for the data from a stream. * * @See https://developer.mozilla.org/en/NPP_StreamAsFile. */ void NPP_StreamAsFile(NPP instance, NPStream* stream, const char* fname) { if (PluginInstance* pi = static_cast<PluginInstance*>(instance->pdata)) pi->StreamAsFile(stream, fname); } /** * Retrieve maximum number of bytes plugin is ready to consume. * * @See https://developer.mozilla.org/en/NPP_WriteReady. */ int32_t NPP_WriteReady(NPP instance, NPStream* stream) { if (PluginInstance* pi = static_cast<PluginInstance*>(instance->pdata)) return pi->WriteReady(stream); return NPERR_INVALID_INSTANCE_ERROR; } /** * Deliver stream data. * * @See https://developer.mozilla.org/en/NPP_Write. */ int32_t NPP_Write(NPP instance, NPStream* stream, int32_t offset, int32_t len, void* buf) { if (PluginInstance* pi = static_cast<PluginInstance*>(instance->pdata)) return pi->Write(stream, offset, len, buf); return NPERR_INVALID_INSTANCE_ERROR; } /** * Request platform specific print operation. * * @See https://developer.mozilla.org/en/NPP_Print. */ void NPP_Print(NPP instance, NPPrint* print_info) { if (PluginInstance* pi = static_cast<PluginInstance*>(instance->pdata)) pi->Print(print_info); } /** * Deliver a platform specific window event. * * @See https://developer.mozilla.org/en/NPP_HandleEvent. */ int16_t NPP_HandleEvent(NPP instance, void* event) { PluginInstance* pi = static_cast<PluginInstance*>(instance->pdata); if (!pi || !pi->IsWindowless()) return NPERR_INVALID_INSTANCE_ERROR; return static_cast<WindowlessInstance*>(pi)->HandleEvent(event); } /** * URL request completion notification. * * @See https://developer.mozilla.org/en/NPP_URLNotify. */ void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* data) { if (PluginInstance* pi = static_cast<PluginInstance*>(instance->pdata)) pi->URLNotify(url, reason, data); } /** * Query plugin information. * * @See https://developer.mozilla.org/en/NPP_GetValue. */ NPError NPP_GetValue(NPP instance, NPPVariable variable, void* value) { if (PluginInstance* pi = static_cast<PluginInstance*>(instance->pdata)) return pi->GetValue(variable, value); return NPERR_INVALID_INSTANCE_ERROR; } /** * Set browser information. * * @See https://developer.mozilla.org/en/NPP_SetValue. */ NPError NPP_SetValue(NPP instance, NPNVariable variable, void* value) { if (PluginInstance* pi = static_cast<PluginInstance*>(instance->pdata)) return pi->SetValue(variable, value); return NPERR_INVALID_INSTANCE_ERROR; } /** * Set focus. * * @See https://wiki.mozilla.org/NPAPI:AdvancedKeyHandling. */ NPBool NPP_GotFocus(NPP instance, NPFocusDirection direction) { if (PluginInstance* pi = static_cast<PluginInstance*>(instance->pdata)) return pi->GotFocus(direction); return false; } /** * Unset focus. * * @See https://wiki.mozilla.org/NPAPI:AdvancedKeyHandling. */ void NPP_LostFocus(NPP instance) { if (PluginInstance* pi = static_cast<PluginInstance*>(instance->pdata)) pi->LostFocus(); } /** * Redirect notification. * * @See https://wiki.mozilla.org/NPAPI:HTTPRedirectHandling. */ void NPP_URLRedirectNotify(NPP instance, const char* url, int32_t status, void* notifyData) { if (PluginInstance* pi = static_cast<PluginInstance*>(instance->pdata)) pi->URLRedirectNotify(url, status, notifyData); } /** * Test method for NPP_ClearSiteData. The first argument is the site for which * to clear data, second argument is the type of data to clear, third argument * is maximum age in seconds of the data that should be cleared. * * First argument can be either NULL to clear all site related data or string * pointer to domain of the site whose data is to be cleared. * * @See https://wiki.mozilla.org/NPAPI:ClearSiteData. */ NPError NPP_ClearSiteData(const char* /*site*/, uint64_t /*flags*/, uint64_t /*maxAge*/) { for (std::map<std::string, char*>::iterator i = g_cookies.begin(); i != g_cookies.end(); ++i) g_browser->memfree(i->second); g_cookies.clear(); return NPERR_NO_ERROR; } /** * Get stored private data. * * @See https://wiki.mozilla.org/NPAPI:ClearSiteData. */ char** NPP_GetSitesWithData() { char** sites = static_cast<char**>(g_browser->memalloc((static_cast<uint32_t>(g_cookies.size()) + 1) * sizeof(char*))); if (!sites) return NULL; char** site_iter = sites; for (std::map<std::string, char*>::iterator i = g_cookies.begin(); i != g_cookies.end(); ++i) { const unsigned int len = static_cast<unsigned int>(i->first.length()); *site_iter = static_cast<char*>(g_browser->memalloc(len + 1)); if (!*site_iter) { // Emergency pull out when out of memory for (site_iter = sites; *site_iter; ++site_iter) g_browser->memfree(*site_iter); g_browser->memfree(sites); return NULL; } memcpy(*site_iter, i->first.c_str(), len); (*site_iter)[len] = '\0'; ++site_iter; } *site_iter = 0; return sites; } /** * Fill the function pointer structure supplied by the browser. * * @param Destination structure. */ void initialize_plugin_function_structure(NPPluginFuncs*& plugin_functions) { uint16_t version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR; if (plugin_functions->version < 22) /* Don't go below version 22 to not break old Opera versions that did not set version of structure. */ version = 22; else if (version > plugin_functions->version) /* To be on the safe side, avoid setting version higher than browser supports. */ version = plugin_functions->version; plugin_functions->version = version; plugin_functions->newp = NPP_New; plugin_functions->destroy = NPP_Destroy; plugin_functions->setwindow = NPP_SetWindow; plugin_functions->newstream = NPP_NewStream; plugin_functions->destroystream = NPP_DestroyStream; plugin_functions->asfile = NPP_StreamAsFile; plugin_functions->writeready = NPP_WriteReady; plugin_functions->write = NPP_Write; plugin_functions->print = NPP_Print; plugin_functions->event = NPP_HandleEvent; if (version < NPVERS_HAS_NOTIFICATION) return; plugin_functions->urlnotify = NPP_URLNotify; plugin_functions->getvalue = NPP_GetValue; plugin_functions->setvalue = NPP_SetValue; if (version < NPVERS_HAS_ADVANCED_KEY_HANDLING) return; plugin_functions->gotfocus = NPP_GotFocus; plugin_functions->lostfocus = NPP_LostFocus; if (version < NPVERS_HAS_URL_REDIRECT_HANDLING) return; plugin_functions->urlredirectnotify = NPP_URLRedirectNotify; if (version < NPVERS_HAS_CLEAR_SITE_DATA) return; plugin_functions->clearsitedata = NPP_ClearSiteData; plugin_functions->getsiteswithdata = NPP_GetSitesWithData; } /** * Function called by browser as a response to NPN_PluginThreadAsyncCall. */ void async_call(void* arg) { if (AsyncCallRecord* acr = static_cast<AsyncCallRecord*>(arg)) { acr->instance->AsyncCall(acr->reason); g_browser->memfree(acr); } } /** * Function called by browser as a response to NPN_ScheduleTimer. */ void timeout(NPP instance, uint32_t id) { if (PluginInstance* pi = static_cast<PluginInstance*>(instance->pdata)) return pi->Timeout(id); } #ifdef XP_UNIX /** * Function called by Gtk when one of our widgets receives messages. */ gboolean gtk_event(GtkWidget* widget, GdkEvent* event, gpointer user_data) { if (WindowedInstance* wi = static_cast<WindowedInstance*>(user_data)) return wi->HandleGtkEvent(widget, event); return false; } #endif // XP_UNIX #ifdef XP_WIN /** * Function called by Windows when our window receives messages. */ LRESULT win_proc(HWND hwnd, UINT message, WPARAM w, LPARAM l) { WindowInstanceMap::iterator it = g_window_instance_map.find(hwnd); if (it != g_window_instance_map.end()) return it->second->WinProc(hwnd, message, w, l); return DefWindowProc(hwnd, message, w, l); } #endif // XP_WIN /** * Handy debug log function. Works like printf. */ #if defined XP_WIN || defined XP_UNIX void log(const char* fmt, ...) { va_list ap; va_start(ap, fmt); #ifdef XP_WIN char buf[4096]; /* ARRAY OK terjes 2010-11-16 */ vsprintf_s<sizeof(buf)>(buf, fmt, ap); OutputDebugStringA(buf); #else // XP_WIN vprintf(fmt, ap); #endif // !XP_WIN va_end(ap); } #endif // XP_WIN || XP_UNIX
//---------------------------------------------------------------------------- #ifndef MainH #define MainH //---------------------------------------------------------------------------- #include "ChildWin.h" #include <ComCtrls.hpp> #include <ExtCtrls.hpp> #include <Messages.hpp> #include <Buttons.hpp> #include <Dialogs.hpp> #include <StdCtrls.hpp> #include <Menus.hpp> #include <Controls.hpp> #include <Forms.hpp> #include <Graphics.hpp> #include <Classes.hpp> #include <SysUtils.hpp> #include <Windows.hpp> #include <System.hpp> #include <ActnList.hpp> #include <ImgList.hpp> #include <StdActns.hpp> #include <ToolWin.hpp> #include <XPMan.hpp> #include <Tabs.hpp> #include "WorkSpaceManager.h" #include "ParseEngine.h" #include "PluginManager.h" #include "AllSourceGen.h" #include "SPCommon.h" #include <iniFiles.hpp> //---------------------------------------------------------------------------- class TMainForm : public TForm { __published: TMainMenu *MainMenu1; TMenuItem *File1; TMenuItem *FileNewItem; TMenuItem *FileOpenItem; TMenuItem *FileCloseItem; TMenuItem *Window1; TMenuItem *Help1; TMenuItem *N1; TMenuItem *FileExitItem; TMenuItem *WindowCascadeItem; TMenuItem *WindowTileItem; TMenuItem *WindowArrangeItem; TMenuItem *HelpAboutItem; TOpenDialog *OpenDialog; TMenuItem *FileSaveItem; TMenuItem *WindowMinimizeItem; TStatusBar *StatusBar; TActionList *ActionList1; TEditCut *EditCut1; TEditCopy *EditCopy1; TEditPaste *EditPaste1; TAction *FileNew1; TAction *FileSave1; TAction *FileExit1; TAction *FileOpen1; TWindowCascade *WindowCascade1; TWindowTileHorizontal *WindowTileHorizontal1; TWindowArrange *WindowArrangeAll1; TWindowMinimizeAll *WindowMinimizeAll1; TAction *HelpAbout1; TWindowClose *FileClose1; TWindowTileVertical *WindowTileVertical1; TMenuItem *WindowTileItem2; TXPManifest *XPManifest1; TTabSet *TabSet1; TPanel *Panel1; TEdit *edtFind; TMenuItem *N2; TAction *actWatchLog; TMenuItem *N3; TMenuItem *miReOpen; TAction *actWatchPlugin; TMenuItem *N4; TSaveDialog *SaveDialog1; TAction *actSetComment; TPopupMenu *pmWorkSpace; TMenuItem *N5; TAction *actDeleteWorkSpace; TMenuItem *N6; TAction *actNewWorkSpace; TMenuItem *N7; TMenuItem *N8; TMenuItem *N9; TMenuItem *N10; TAction *actSearchFiles; TMenuItem *N11; TAction *actAddWorkSpace; TMenuItem *N12; TAction *actOutputAllRecv; TAction *actOutputAllSend; TMenuItem *N13; TMenuItem *Recv1; TMenuItem *WriteBuffer1; TSplitter *Splitter1; TAction *actSetKey; TMenuItem *Key1; TMenuItem *N14; TAction *actUseGlobalKey; TMenuItem *Key2; TOpenDialog *OpenDialog1; TAction *actParseAsHex; TMenuItem *N15; TMenuItem *N161; TMenuItem *N16; TAction *actOpenDesign; TMenuItem *N17; TNotebook *nbShowPages; TPanel *Panel2; TPanel *Panel3; TListView *lvWorkSpace; TTreeView *tvWorkSpaceTree; TAction *actChangeView; TMenuItem *N18; TMenuItem *N19; TAction *actDebug; TMenuItem *N20; TMenuItem *N21; TAction *actOpenSetup; TMenuItem *N22; TAction *actSetup; TMenuItem *N23; TAction *actOutputReadWriteAll; TMenuItem *ReadWriteAll1; void __fastcall FileOpen1Execute(TObject *Sender); void __fastcall HelpAbout1Execute(TObject *Sender); void __fastcall FileExit1Execute(TObject *Sender); void __fastcall TabSet1Change(TObject *Sender, int NewTab, bool &AllowChange); void __fastcall TabSet1DrawTab(TObject *Sender, TCanvas *TabCanvas, TRect &R, int Index, bool Selected); void __fastcall FormCreate(TObject *Sender); void __fastcall edtFindChange(TObject *Sender); void __fastcall lvWorkSpaceKeyPress(TObject *Sender, char &Key); void __fastcall lvWorkSpaceDblClick(TObject *Sender); void __fastcall actWatchLogExecute(TObject *Sender); void __fastcall FormCloseQuery(TObject *Sender, bool &CanClose); void __fastcall FormClose(TObject *Sender, TCloseAction &Action); void __fastcall actWatchPluginExecute(TObject *Sender); void __fastcall FileNew1Execute(TObject *Sender); void __fastcall FileSave1Execute(TObject *Sender); void __fastcall FileClose1Execute(TObject *Sender); void __fastcall actSetCommentExecute(TObject *Sender); void __fastcall actDeleteWorkSpaceExecute(TObject *Sender); void __fastcall actNewWorkSpaceExecute(TObject *Sender); void __fastcall actSearchFilesExecute(TObject *Sender); void __fastcall actAddWorkSpaceExecute(TObject *Sender); void __fastcall actOutputAllRecvExecute(TObject *Sender); void __fastcall actOutputAllSendExecute(TObject *Sender); void __fastcall actSetKeyExecute(TObject *Sender); void __fastcall actUseGlobalKeyExecute(TObject *Sender); void __fastcall actParseAsHexExecute(TObject *Sender); void __fastcall actOpenDesignExecute(TObject *Sender); void __fastcall actChangeViewExecute(TObject *Sender); void __fastcall tvWorkSpaceTreeDblClick(TObject *Sender); void __fastcall actDebugExecute(TObject *Sender); void __fastcall actOpenSetupExecute(TObject *Sender); void __fastcall actSetupExecute(TObject *Sender); void __fastcall actOutputReadWriteAllExecute(TObject *Sender); private: void __fastcall CreateMDIChild(WorkSpace * workSpace); AList<tagExePlugins> m_ExePlugins; bool m_IsCreatingWnd; void LoadExePluginIni(); TStringList * m_ReOpenList; //重新打开的列表 ParseEngine *m_ParseEngine; void LoadWorkSpace(String fileName); void InitReOpenList(); void RefreshReOpenList(); void __fastcall miReOpenitemExecute(TObject *Sender); void SaveReOpenList(); PluginManager m_PluginManager; AllSourceGen m_AllSourceGen; void OutputSrc(String srcMode); void DoWorkSpaceListDbClick(WorkSpace *selWorkSpace); void ApplyWndConfig(TMDIChild * curChild); public: virtual __fastcall TMainForm(TComponent *Owner); void ChildNeedSave(); void RefreshWorkSpace(); void LoadSearchFile(String fileName); TMDIChild * GetCurWndByWorkSpace(WorkSpace *selWorkSpace); void ApplyConfig(); }; //---------------------------------------------------------------------------- extern TMainForm *MainForm; extern TMDIChild *__fastcall MDIChildCreate(void); //---------------------------------------------------------------------------- #endif
///* //PROG: ride //ID: zhf66691 //LANG: C++ //*/ //#include <iostream> //#include <fstream> //#include <string> // //using namespace std; // //int main() //{ // ofstream fout("ride.out"); // ifstream fin("ride.in"); // string s1, s2; // fin >> s1; // fin >> s2; // // int data1 = 1; // for (int i = 0; s1[i] != '\0'; i++) // { // data1 *= int(s1[i] - 'A' + 1) % 47; // data1 %= 47; // } // int data2 = 1; // for (int i = 0; s2[i] != '\0'; i++) // { // data2 *= int(s2[i] - 'A' + 1) % 47; // data2 %= 47; // } // if (data1 == data2) // { // fout << "GO" << endl; // } // else // { // fout << "STAY" << endl; // } // getchar(); // return 0; //}
#include "BasicMaths.h" #include <cmath> //standard normal CDF double Ncdf(double x){ return 0.5+0.5*erf(x/sqrt(2)); } //standard normal PDF double Npdf(double x){ return exp(-0.5*x*x)/sqrt(8*atan(1)); }
#include "error_form.h"
#include <iostream> #include <vector> class FileCollection; class FileProperties { public: void Init( const char* fullPath, const char* pathNoExt ); const char* GetPath() const { return m_FullPath.c_str(); } const char* GetPathNoExt() const { return m_PathNoExt.c_str(); } private: std::string m_FullPath; std::string m_PathNoExt; }; class FileCollection { public: enum DirFilter { kCurrentDirOnly, kIncludeSubDirs }; void AddFilesInDir( const char* dir, const char* ext, DirFilter dirFilter ); FileProperties* GetFileProperties() { return m_Data.data(); } FileProperties Get( int i ) const { return m_Data[i]; } unsigned int Count() { return unsigned int( m_Data.size()); } private: std::vector<FileProperties> m_Data; };
/* * This file is part of choqok-sina * Copyright (C) 2011 Ni Hui <shuizhuyuanluo@126.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) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * 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, see <http://www.gnu.org/licenses/>. */ #include "sinatimelinewidget.h" #include "sinamicroblog.h" #include <choqok/postwidget.h> SinaTimelineWidget::SinaTimelineWidget( Choqok::Account* account, const QString& timelineName, QWidget* parent ) : Choqok::UI::TimelineWidget(account,timelineName,parent) { if ( timelineName == "favorite" ) { /// set up proxy SinaMicroBlog* microblog = dynamic_cast<SinaMicroBlog*>(account->microblog()); connect( microblog, SIGNAL(favoriteCreated(Choqok::Account*,Choqok::Post*)), this, SLOT(slotFavoriteCreated(Choqok::Account*,Choqok::Post*)) ); connect( microblog, SIGNAL(favoriteRemoved(Choqok::Account*,Choqok::Post*)), this, SLOT(slotFavoriteRemoved(Choqok::Account*,Choqok::Post*)) ); } } SinaTimelineWidget::~SinaTimelineWidget() { } void SinaTimelineWidget::slotFavoriteCreated( Choqok::Account* account, Choqok::Post* post ) { if ( account == currentAccount() ) { if ( !posts().contains( post->postId ) ) addNewPosts( QList<Choqok::Post*>() << post ); } } void SinaTimelineWidget::slotFavoriteRemoved( Choqok::Account* account, Choqok::Post* post ) { if ( account == currentAccount() ) { if ( posts().contains( post->postId ) ) posts().value( post->postId )->close(); } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2006 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #include "modules/forms/formvaluewf2date.h" #include "modules/forms/webforms2number.h" #include "modules/forms/datetime.h" #include "modules/forms/piforms.h" #include "modules/logdoc/htm_elm.h" #include "modules/stdlib/util/opdate.h" // FormValueDate /* virtual */ FormValue* FormValueWF2DateTime::Clone(HTML_Element *he) { FormValueWF2DateTime* clone = OP_NEW(FormValueWF2DateTime, (m_date_type)); if (clone) { if (he && IsValueExternally()) { OpString current_value; if (OpStatus::IsSuccess(GetFormObjectValue(he, current_value))) { // Rather ignore the value than destroying the whole FormValue/HTML_Element OpStatus::Ignore(SetInternalValueFromText(current_value.CStr())); } } clone->GetHasValueBool() = GetHasValueBool(); clone->m_datetime = m_datetime; OP_ASSERT(!clone->IsValueExternally()); } return clone; } /* virtual */ OP_STATUS FormValueWF2DateTime::ResetToDefault(HTML_Element* he) { OP_ASSERT(he->GetFormValue() == this); ResetChangedFromOriginal(); const uni_char* default_value = he->GetStringAttr(ATTR_VALUE); if (default_value) { DateTimeSpec date; WeekSpec week; MonthSpec month; if (m_date_type == DATE && !date.m_date.SetFromISO8601String(default_value) || m_date_type == TIME && !date.m_time.SetFromISO8601String(default_value) || m_date_type == WEEK && !week.SetFromISO8601String(default_value) || m_date_type == MONTH && !month.SetFromISO8601String(default_value) || m_date_type == DATETIME && !date.SetFromISO8601String(default_value, TRUE) || m_date_type == DATETIME_LOCAL && !date.SetFromISO8601String(default_value, FALSE)) { default_value = NULL; } } return SetValueFromText(he, default_value); } /* virtual */ OP_STATUS FormValueWF2DateTime::GetValueAsText(HTML_Element* he, OpString& out_value) const { OP_ASSERT(he->GetFormValue() == const_cast<FormValueWF2DateTime*>(this)); if(IsValueExternally()) { return GetFormObjectValue(he, out_value); } if (!GetHasValueBool()) { out_value.Empty(); } else { return GetInternalValueAsText(out_value); } return OpStatus::OK; } /* static */ OP_STATUS FormValueWF2DateTime::ConvertDateTimeToText(ExactType type, DateTimeSpec datetime, OpString& out_value) { uni_char* value_buf; unsigned int value_str_len; if (type == DATE) { value_str_len = datetime.m_date.GetISO8601StringLength(); } else if (type == TIME) { value_str_len = datetime.m_time.GetISO8601StringLength(); } else if (type == WEEK) { // A week is represented by the monday WeekSpec week/* = datetime.m_day.GetWeek(); OP_ASSERT(week.GetFirstDay() == datetime.m_day)*/; value_str_len = week.GetISO8601StringLength(); } else if (type == MONTH) { // A month is represented by the year/month part MonthSpec month/* = { datetime.m_day.m_year, datetime.m_day, m_month } */; value_str_len = month.GetISO8601StringLength(); } else { OP_ASSERT(type == DATETIME || type == DATETIME_LOCAL); BOOL has_timezone = (type == DATETIME); value_str_len = datetime.GetISO8601StringLength(has_timezone); } value_buf = out_value.Reserve(value_str_len+1); if (!value_buf) { return OpStatus::ERR_NO_MEMORY; } if (type == DATE) { datetime.m_date.ToISO8601String(value_buf); } else if (type == TIME) { datetime.m_time.ToISO8601String(value_buf); } else if (type == WEEK) { // A week is represented by the monday WeekSpec week = datetime.m_date.GetWeek(); OP_ASSERT(week.GetFirstDay().m_day == datetime.m_date.m_day); week.ToISO8601String(value_buf); } else if (type == MONTH) { // A month is represented by the year/month part MonthSpec month = { datetime.m_date.m_year, datetime.m_date.m_month }; month.ToISO8601String(value_buf); } else { OP_ASSERT(type == DATETIME || type == DATETIME_LOCAL); BOOL has_timezone = (type == DATETIME); datetime.ToISO8601String(value_buf, has_timezone); } return OpStatus::OK; } OP_STATUS FormValueWF2DateTime::GetInternalValueAsText(OpString& out_value) const { OP_ASSERT(GetHasValueBool()); return ConvertDateTimeToText(m_date_type, m_datetime, out_value); } /* virtual */ OP_STATUS FormValueWF2DateTime::SetValueFromText(HTML_Element* he, const uni_char* in_value) { OP_ASSERT(he->GetFormValue() == this); if (IsValueExternally()) { FormObject* form_object = he->GetFormObject(); OP_ASSERT(form_object); // If they said we was external, then we must have a form_object return form_object->SetFormWidgetValue(in_value); } return SetInternalValueFromText(in_value); } /* private */ OP_STATUS FormValueWF2DateTime::SetInternalValueFromText(const uni_char* in_value) { if (!in_value || !*in_value) { GetHasValueBool() = FALSE; } else { BOOL result; DateTimeSpec date; date.Clear(); // Silence compiler if (m_date_type == DATE) { result = date.m_date.SetFromISO8601String(in_value); } else if (m_date_type == TIME) { result = date.m_time.SetFromISO8601String(in_value) > 0; } else if (m_date_type == WEEK) { WeekSpec week; result = week.SetFromISO8601String(in_value); if (result) { date.m_date = week.GetFirstDay(); } } else if (m_date_type == MONTH) { MonthSpec month; result = month.SetFromISO8601String(in_value); if (result) { date.m_date.m_year = month.m_year; date.m_date.m_month = month.m_month; } } else { OP_ASSERT(m_date_type == DATETIME || m_date_type == DATETIME_LOCAL); BOOL has_timezone = (m_date_type == DATETIME); result = date.SetFromISO8601String(in_value, has_timezone) > 0; } if (!result) { return OpStatus::ERR; } m_datetime = date; GetHasValueBool() = TRUE; } return OpStatus::OK; } /* static */ OP_STATUS FormValueWF2DateTime::ConstructFormValueWF2DateTime(HTML_Element* he, FormValue*& out_value) { ExactType type; OP_ASSERT(he->IsMatchingType(HE_INPUT, NS_HTML)); switch(he->GetInputType()) { case INPUT_DATE: type = DATE; break; case INPUT_TIME: type = TIME; break; case INPUT_WEEK: type = WEEK; break; case INPUT_MONTH: type = MONTH; break; case INPUT_DATETIME: type = DATETIME; break; default: OP_ASSERT(FALSE); // fallthrough case INPUT_DATETIME_LOCAL: type = DATETIME_LOCAL; break; } FormValueWF2DateTime* date_value = OP_NEW(FormValueWF2DateTime, (type)); if (!date_value) { return OpStatus::ERR_NO_MEMORY; } const uni_char* html_value = he->GetStringAttr(ATTR_VALUE); if (html_value) { OP_STATUS status = date_value->SetInternalValueFromText(html_value); if (OpStatus::IsMemoryError(status)) { OP_DELETE(date_value); return status; } } out_value = date_value; return OpStatus::OK; } /* virtual */ BOOL FormValueWF2DateTime::Externalize(FormObject* form_object_to_seed) { if (!FormValue::Externalize(form_object_to_seed)) { return FALSE; // It was wrong to call Externalize } if (GetHasValueBool()) { OpString val_as_text; // Widget will be empty on OOM, not much else to do OpStatus::Ignore(GetInternalValueAsText(val_as_text)); form_object_to_seed->SetFormWidgetValue(val_as_text.CStr()); } else { form_object_to_seed->SetFormWidgetValue(NULL); } return TRUE; } /* virtual */ void FormValueWF2DateTime::Unexternalize(FormObject* form_object_to_replace) { if (IsValueExternally()) { GetHasValueBool() = FALSE; OpString val_as_text; OP_STATUS status = form_object_to_replace->GetFormWidgetValue(val_as_text); if (OpStatus::IsSuccess(status)) { SetInternalValueFromText(val_as_text.CStr()); } FormValue::Unexternalize(form_object_to_replace); } } /* static */ void FormValueWF2DateTime::GetStepLimits(ExactType type, const uni_char* min_attr, const uni_char* max_attr, const uni_char* step_attr, double& min_value, double& max_value, double& step_base, double& step_value) { step_base = 0.0; if (type == DATE) { // Default min_value = -DBL_MAX; max_value = DBL_MAX; // arbitrary step_value = 86400000.0; // one day in milliseconds if (max_attr) { DaySpec max_value_spec; if (max_value_spec.SetFromISO8601String(max_attr)) { max_value = max_value_spec.AsDouble() * 86400000.0; step_base = max_value; } } if (min_attr) { DaySpec min_value_spec; if (min_value_spec.SetFromISO8601String(min_attr)) { min_value = min_value_spec.AsDouble() * 86400000.0; step_base = min_value; } } if (step_attr) { // in days, to be converted to milliseconds double step_spec; BOOL legal_step = WebForms2Number::StringToDouble(step_attr, step_spec); if (legal_step && step_spec == static_cast<int>(step_spec) && step_spec >= 0.0) { step_value = step_spec * 86400000.0; } else if (uni_stri_eq(step_attr, "any")) { step_value = 0.0; } } } else if (type == TIME) { // Default min_value = 0; max_value = 86399999.0; step_value = 60000; // one minute if (max_attr) { TimeSpec max_value_spec; if (max_value_spec.SetFromISO8601String(max_attr)) { max_value = max_value_spec.AsDouble() * 1000.0; step_base = max_value; } } if (min_attr) { TimeSpec min_value_spec; if (min_value_spec.SetFromISO8601String(min_attr)) { min_value = min_value_spec.AsDouble() * 1000.0; step_base = min_value; } } if (step_attr) { // in seconds, to be converted to milliseconds double step_spec; BOOL legal_step = WebForms2Number::StringToDouble(step_attr, step_spec); if (legal_step && step_spec >= 0.0) { step_value = step_spec * 1000.0; } else if (uni_stri_eq(step_attr, "any")) { step_value = 0.0; } } } else if (type == WEEK) { // A week is represented by the monday that week // Default min_value = -DBL_MAX; max_value = DBL_MAX; step_value = 7*86400000; // one week if (max_attr) { WeekSpec max_value_spec; if (max_value_spec.SetFromISO8601String(max_attr)) { max_value = max_value_spec.GetFirstDay().AsDouble()*86400000; step_base = max_value; } } if (min_attr) { WeekSpec min_value_spec; if (min_value_spec.SetFromISO8601String(min_attr)) { min_value = min_value_spec.GetFirstDay().AsDouble()*86400000; step_base = min_value; } } if (step_attr) { // in weeks, to be converted to milliseconds double step_spec; BOOL legal_step = WebForms2Number::StringToDouble(step_attr, step_spec); if (legal_step && step_spec >= 0.0) { step_value = step_spec * (7 * 86400000); } else if (uni_stri_eq(step_attr, "any")) { step_value = 0.0; } } } else if (type == MONTH) { // A month is represented by the m_year and m_month part of DaySpec // Default min_value = -DBL_MAX; max_value = DBL_MAX; step_value = 1; // one week if (max_attr) { MonthSpec max_value_spec; if (max_value_spec.SetFromISO8601String(max_attr)) { max_value = max_value_spec.AsDouble(); step_base = max_value; } } if (min_attr) { MonthSpec min_value_spec; if (min_value_spec.SetFromISO8601String(min_attr)) { min_value = min_value_spec.AsDouble(); step_base = min_value; } } if (step_attr) { // in months double step_spec; BOOL legal_step = WebForms2Number::StringToDouble(step_attr, step_spec); if (legal_step && step_spec >= 0.0) { step_value = step_spec; } else if (uni_stri_eq(step_attr, "any")) { step_value = 0.0; } } } else { OP_ASSERT(type == DATETIME || type == DATETIME_LOCAL); BOOL has_timezone = (type == DATETIME); // Default min_value = -DBL_MAX; max_value = DBL_MAX; step_value = 60000; // one minute if (max_attr) { DateTimeSpec max_value_spec; if (max_value_spec.SetFromISO8601String(max_attr, has_timezone)) { max_value = max_value_spec.AsDouble(); step_base = max_value; } } if (min_attr) { DateTimeSpec min_value_spec; if (min_value_spec.SetFromISO8601String(min_attr, has_timezone)) { min_value = min_value_spec.AsDouble(); step_base = min_value; } } if (step_attr) { // in seconds, to be converted to milliseconds double step_spec; BOOL legal_step = WebForms2Number::StringToDouble(step_attr, step_spec); if (legal_step && step_spec >= 0.0) { step_value = step_spec * 1000.0; } else if (uni_stri_eq(step_attr, "any")) { step_value = 0.0; } } } } OP_STATUS FormValueWF2DateTime::SetValueFromNumber(HTML_Element* he, double value_as_number) { OP_ASSERT(he->IsMatchingType(HE_INPUT, NS_HTML)); DateTimeSpec resulting_date; resulting_date.Clear(); if (m_date_type == MONTH) { int month_count = static_cast<int>(value_as_number); resulting_date.m_date.m_year = 1970 + month_count / 12; resulting_date.m_date.m_month = month_count % 12; } else if (m_date_type == TIME) { // Try to avoid the second and millisecond part. TimeSpec time; time.Clear(); // This will keep the previous precision or increase it. time.SetFromNumber(static_cast<int>(op_fmod(value_as_number, 86400000)), 1000); resulting_date.m_time = time; } else { resulting_date.SetFromTime(value_as_number); } OpString as_text; RETURN_IF_ERROR(ConvertDateTimeToText(m_date_type, resulting_date, as_text)); return SetValueFromText(he, as_text.CStr()); } /* static */ double FormValueWF2DateTime::ConvertDateTimeToNumber(ExactType type, DateTimeSpec datetime) { if (type == MONTH) { MonthSpec month = { datetime.m_date.m_year, datetime.m_date.m_month }; return month.AsDouble(); } if (type == TIME) { datetime.m_date.m_year = 1970; datetime.m_date.m_month = 0; datetime.m_date.m_day = 1; } else if (type == DATE || type == WEEK) { datetime.m_time.m_hour = 0; datetime.m_time.m_minute = 0; datetime.m_time.SetSecondUndefined(); datetime.m_time.SetFractionUndefined(); } return datetime.AsDouble(); } /* virtual */ OP_STATUS FormValueWF2DateTime::StepUpDown(HTML_Element* he, int step_count) { OP_ASSERT(he->GetFormValue() == this); OpString current_value; if (IsValueExternally()) { RETURN_IF_ERROR(GetFormObjectValue(he, current_value)); if (OpStatus::IsError(SetInternalValueFromText(current_value.CStr()))) { // Someone has something strange in the widget return OpStatus::ERR_NOT_SUPPORTED; } } if (!GetHasValueBool()) { return OpStatus::ERR_NOT_SUPPORTED; } double min_value; double max_value; double step_base; double step_value; GetStepLimits(m_date_type, he->GetStringAttr(ATTR_MIN), he->GetStringAttr(ATTR_MAX), he->GetStringAttr(ATTR_STEP), min_value, max_value, step_base, step_value); if (step_value == 0.0) { return OpStatus::ERR_NOT_SUPPORTED; } double value = ConvertDateTimeToNumber(m_date_type, m_datetime); double out_value_num; OP_STATUS status = WebForms2Number::StepNumber(value, min_value, max_value, step_base, step_value, step_count, FALSE, /* wrap_around */ TRUE, /* fuzzy_snapping */ out_value_num); RETURN_IF_ERROR(status); /* ValidationResult val_res = VALIDATE_OK; val_res.SetErrorsFrom(FormValidator::ValidateNumberForMinMaxStep(he, out_value_num)); if (!val_res.IsOk()) { return OpStatus::ERR_OUT_OF_RANGE; } */ return SetValueFromNumber(he, out_value_num); } const uni_char* FormValueWF2DateTime::GetFormValueTypeString() const { switch (m_date_type) { case DATE: return UNI_L("date"); case TIME: return UNI_L("time"); case DATETIME: return UNI_L("datetime"); case DATETIME_LOCAL: return UNI_L("datetime-local"); case MONTH: return UNI_L("month"); default: OP_ASSERT(FALSE); // fallthrough case WEEK: return UNI_L("week"); } }
#ifndef HIGHSCOREPAGE_H #define HIGHSCOREPAGE_H #include <QWidget> #include <QString> namespace Ui { class HighScorePage; } class HighScorePage : public QWidget { Q_OBJECT public: explicit HighScorePage(QWidget *parent = 0); ~HighScorePage(); void showNameEnter(bool show); QString getName() {return name; } void showHighScores(); void setNewScores(); void setPlace(int newPlace) { place = newPlace; } void setScore(int newScore) { score = newScore; } private slots: void on_btnReturnHome_clicked(); void on_btnEnterName_clicked(); private: Ui::HighScorePage *ui; QWidget * widgetParent; QString name; int score; int place; }; #endif // HIGHSCOREPAGE_H
#include "Unit.h" #pragma once #include <iostream> #include<string> #include <cmath> namespace ariel{ class PhysicalNumber{ private: double value; ariel::Unit unit; bool areSameType(const PhysicalNumber& other) const; bool areSameScope(const PhysicalNumber &other) const; //km and m, tom and kg, not kg and km const PhysicalNumber convertNumber(const PhysicalNumber &other) const; double convertDistanceValue(int diff) const; double convertTimeValue(int diff) const; double convertMassValue(int diff) const; std::string parseUnit(std::string input) const; double parseValue(std::string input) const; int findUnitIndex(std::string unitString) const; bool isGoodFormat(std::string input) const; public: std::string toString() const; std::string units[9] = {"km","m","cm","hour","min","sec","ton", "kg", "g"}; PhysicalNumber(double num, Unit unit); ~PhysicalNumber(); //getters and setters double getValue() const; Unit getUnit() const; void setValue(double x); void setUnit(Unit u); //arithmetics PhysicalNumber operator+(const PhysicalNumber& other) const; PhysicalNumber& operator+=(const PhysicalNumber& other); PhysicalNumber operator-(const PhysicalNumber& other) const; PhysicalNumber& operator-=(const PhysicalNumber& other); PhysicalNumber operator-() const; PhysicalNumber operator+() const; PhysicalNumber& operator--(); PhysicalNumber operator--(int); PhysicalNumber& operator++(); PhysicalNumber operator++(int); //compare bool operator>(const PhysicalNumber& other)const; bool operator<(const PhysicalNumber& other)const; bool operator==(const PhysicalNumber& other)const; bool operator<=(const PhysicalNumber& other)const; bool operator>=(const PhysicalNumber& other)const; bool operator!=(const PhysicalNumber& other)const; //input output friend std::ostream &operator<<(std::ostream &os, PhysicalNumber const &m); friend std::istream &operator>>(std::istream &is, PhysicalNumber &m); }; }
#include "generalview.h" generalview::generalview() { font.loadFromFile("times-new-roman.ttf"); text.setFont(font); text.setCharacterSize(24); text.setStyle(Text::Bold); text.setColor(sf::Color::Blue); text.setPosition(5, 400); setText(text, "0,0"); textClock.setCharacterSize(24); textClock.setStyle(Text::Bold); textClock.setColor(sf::Color::Red); textClock.setPosition(5, 0); textClock.setFont(font); } int generalview::getGameElapsedTime() { return clock.getElapsedTime().asSeconds(); } void generalview::setText(Text &textname, string _text) { textname.setString(_text); }
#include "Orden.h" void Orden::QuickSortTipo(Lista* lista, int start, int end) { int pivot; if (start < end) { //PIVOTE pivot = DivideTipo(lista, start, end); //RECURSIVIDAD QuickSortTipo(lista, start, pivot - 1); QuickSortTipo(lista, pivot + 1, end); } } int Orden::DivideTipo(Lista* lista, int start, int end) { int left; int right; int pivot; int temp; /*pivot = lista->ObtenerProducto(lista->count + 1, right)->producto->TipoProducto; left = start; right = end; //MIENTRAS NO SE CRUZEN LOS INDICES while (left < right) { while (lista->ObtenerProducto(lista->count+1, right)->producto->TipoProducto > pivot) { right--; } while ((left < right) && (lista->ObtenerProducto(lista->count + 1, left)->producto->TipoProducto <= pivot)) { left++; } //SI TODAVÍA NO SE CRUZAN LOS INDICES SEGUMOS INTERCAMBIANDO if (left < right) { IntercambioProducto(lista->ObtenerProducto(lista->count + 1, left), lista->ObtenerProducto(lista->count + 1, right)); } }*/ //LOS INDICES YA SE HAN CRUZADO, PONEMOS EL PIVOT EN EL LUGAR QUE LE CORRESPONDE IntercambioProducto(lista->ObtenerProducto(lista->contador + 1, right), lista->ObtenerProducto(lista->contador + 1, start)); //LA NUEVA POSICIÓN DEL PIVOTE return right; } void Orden::QuickSortCantidad(Lista* lista, int start, int end) { int pivot; if (start < end) { //PIVOTE pivot = DivideCantidad(lista, start, end); //RECURSIVIDAD QuickSortCantidad(lista, start, pivot - 1); QuickSortCantidad(lista, pivot + 1, end); } } int Orden::DivideCantidad(Lista* lista, int start, int end) { int left; int right; int pivot; int temp; pivot = lista->ObtenerProducto(lista->contador + 1, right)->producto->Cantidad; left = start; right = end; //MIENTRAS NO SE CRUZEN LOS INDICES while (left < right) { while (lista->ObtenerProducto(lista->contador + 1, right)->producto->Cantidad > pivot) { right--; } while ((left < right) && (lista->ObtenerProducto(lista->contador + 1, left)->producto->Cantidad <= pivot)) { left++; } //SI TODAVÍA NO SE CRUZAN LOS INDICES SEGUMOS INTERCAMBIANDO if (left < right) { IntercambioProducto(lista->ObtenerProducto(lista->contador + 1, left), lista->ObtenerProducto(lista->contador + 1, right)); } } //LOS INDICES YA SE HAN CRUZADO, PONEMOS EL PIVOT EN EL LUGAR QUE LE CORRESPONDE IntercambioProducto(lista->ObtenerProducto(lista->contador + 1, right), lista->ObtenerProducto(lista->contador + 1, start)); //LA NUEVA POSICIÓN DEL PIVOTE return right; } void Orden::QuickSortPeso(Lista* lista, int start, int end) { } int Orden::DividePeso(Lista* lista, int start, int end) { int left; int right; int pivot; int temp; /*pivot = lista->ObtenerProducto(lista->count + 1, right)->producto->PesoUnitario; left = start; right = end; //MIENTRAS NO SE CRUZEN LOS INDICES while (left < right) { while (lista->ObtenerProducto(lista->count + 1, right)->producto->PesoUnitario > pivot) { right--; } while ((left < right) && (lista->ObtenerProducto(lista->count + 1, left)->producto->PesoUnitario <= pivot)) { left++; } //SI TODAVÍA NO SE CRUZAN LOS INDICES SEGUMOS INTERCAMBIANDO if (left < right) { IntercambioProducto(lista->ObtenerProducto(lista->count + 1, left), lista->ObtenerProducto(lista->count + 1, right)); } }*/ //LOS INDICES YA SE HAN CRUZADO, PONEMOS EL PIVOT EN EL LUGAR QUE LE CORRESPONDE IntercambioProducto(lista->ObtenerProducto(lista->contador + 1, right), lista->ObtenerProducto(lista->contador + 1, start)); //LA NUEVA POSICIÓN DEL PIVOTE return right; } void Orden::BubbleSortFecha(Lista* lista) { for (int i = 0; i < lista->ContarElemento() - 1; i++) { for (int j = i + 1; j < lista->ContarElemento(); j++) { //COMPARAR if (lista->ObtenerProducto(lista->ContarElemento(), i)->producto->FechaAlmacenada > lista->ObtenerProducto(lista->ContarElemento(), j)->producto->FechaAlmacenada) { //HACER EL INTERCAMBIO IntercambioProducto(lista->ObtenerProducto(lista->contador + 1, i), lista->ObtenerProducto(lista->contador + 1, j)); } } } } //HACER EL INTERCAMBIO DE POKEMONS void Orden::IntercambioProducto(Nodo1* Producto1, Nodo1* Producto2) { Nodo1* auxiliar = Producto1; Productos* remp; remp = Producto2->producto; Nodo1* remplazando = new Nodo1(remp); Producto1->producto = Producto2->producto; //ASIGNAR VALORES Producto2->producto = remplazando->producto; }
#include <iostream> #include <boost/python.hpp> #include <boost/python/numpy.hpp> #include<boost/python/tuple.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/opencv.hpp> #include<Eigen/SparseLU> #include<Eigen/IterativeLinearSolvers> #include <Eigen/SparseCore> #include <Eigen/Core> #include <Eigen/Dense> //#include <unsupported/Eigen/IterativeSolvers> typedef Eigen::SparseMatrix<double> SpMat; typedef Eigen::Triplet<double> T; using namespace Eigen; using namespace std; using namespace boost; namespace bp = boost::python; namespace bn = boost::python::numpy; //using namespace boost::python::numpy; class Matting(): { bn::ndarray matting(): { } } bn::ndarray my_add(bn::ndarray& a_array, bn::ndarray& b_array) { bn::dtype dt = bn::dtype::get_builtin<int>(); a_array = a_array.astype(dt); b_array = b_array.astype(dt); const int* a = reinterpret_cast<const int*>(a_array.get_data()); const bp::tuple &shape = bp::extract<bp::tuple>(a_array.attr("shape")); int h = bp::extract<int>(shape[0]); int w = bp::extract<int>(shape[1]); const int* b = reinterpret_cast<const int*>(b_array.get_data()); int* c_list = new int[h](); for (int i = 0; i < h; i++) { c_list[i] = *(a+i) + *(b+i); } bn::ndarray c_array = bn::from_data(c_list, dt, bp::make_tuple(h), bp::make_tuple(sizeof(int)), bp::object()); //delete[] c_list; return c_array; } BOOST_PYTHON_MODULE(matting) { Py_Initialize(); bn::initialize(); bp::def("my_add", &my_add); }
// Copyright (c) 2012-2016, The CryptoNote developers, The Bytecoin developers // // This file is part of Karbo. // // Karbo is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Karbo 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with Karbo. If not, see <http://www.gnu.org/licenses/>. #include "MemoryMappedFile.h" #include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <cassert> #include "Common/ScopeExit.h" namespace platform_system { MemoryMappedFile::MemoryMappedFile() : m_file(-1), m_size(0), m_data(nullptr) { } MemoryMappedFile::~MemoryMappedFile() { std::error_code ignore; close(ignore); } const std::string& MemoryMappedFile::path() const { assert(isOpened()); return m_path; } uint64_t MemoryMappedFile::size() const { assert(isOpened()); return m_size; } const uint8_t* MemoryMappedFile::data() const { assert(isOpened()); return m_data; } uint8_t* MemoryMappedFile::data() { assert(isOpened()); return m_data; } bool MemoryMappedFile::isOpened() const { return m_data != nullptr; } void MemoryMappedFile::create(const std::string& path, uint64_t size, bool overwrite, std::error_code& ec) { if (isOpened()) { close(ec); if (ec) { return; } } tools::ScopeExit failExitHandler([this, &ec] { ec = std::error_code(errno, std::system_category()); std::error_code ignore; close(ignore); }); m_file = ::open(path.c_str(), O_RDWR | O_CREAT | (overwrite ? O_TRUNC : O_EXCL), S_IRUSR | S_IWUSR); if (m_file == -1) { return; } int result = ::ftruncate(m_file, static_cast<off_t>(size)); if (result == -1) { return; } m_data = reinterpret_cast<uint8_t*>(::mmap(nullptr, static_cast<size_t>(size), PROT_READ | PROT_WRITE, MAP_SHARED, m_file, 0)); if (m_data == MAP_FAILED) { return; } m_size = size; m_path = path; ec = std::error_code(); failExitHandler.cancel(); } void MemoryMappedFile::create(const std::string& path, uint64_t size, bool overwrite) { std::error_code ec; create(path, size, overwrite, ec); if (ec) { throw std::system_error(ec, "MemoryMappedFile::create"); } } void MemoryMappedFile::open(const std::string& path, std::error_code& ec) { if (isOpened()) { close(ec); if (ec) { return; } } tools::ScopeExit failExitHandler([this, &ec] { ec = std::error_code(errno, std::system_category()); std::error_code ignore; close(ignore); }); m_file = ::open(path.c_str(), O_RDWR, S_IRUSR | S_IWUSR); if (m_file == -1) { return; } struct stat fileStat; int result = ::fstat(m_file, &fileStat); if (result == -1) { return; } m_size = static_cast<uint64_t>(fileStat.st_size); m_data = reinterpret_cast<uint8_t*>(::mmap(nullptr, static_cast<size_t>(m_size), PROT_READ | PROT_WRITE, MAP_SHARED, m_file, 0)); if (m_data == MAP_FAILED) { return; } m_path = path; ec = std::error_code(); failExitHandler.cancel(); } void MemoryMappedFile::open(const std::string& path) { std::error_code ec; open(path, ec); if (ec) { throw std::system_error(ec, "MemoryMappedFile::open"); } } void MemoryMappedFile::rename(const std::string& newPath, std::error_code& ec) { assert(isOpened()); int result = ::rename(m_path.c_str(), newPath.c_str()); if (result == 0) { m_path = newPath; ec = std::error_code(); } else { ec = std::error_code(errno, std::system_category()); } } void MemoryMappedFile::rename(const std::string& newPath) { assert(isOpened()); std::error_code ec; rename(newPath, ec); if (ec) { throw std::system_error(ec, "MemoryMappedFile::rename"); } } void MemoryMappedFile::close(std::error_code& ec) { int result; if (m_data != nullptr) { flush(m_data, m_size, ec); if (ec) { return; } result = ::munmap(m_data, static_cast<size_t>(m_size)); if (result == 0) { m_data = nullptr; } else { ec = std::error_code(errno, std::system_category()); return; } } if (m_file != -1) { result = ::close(m_file); if (result == 0) { m_file = -1; ec = std::error_code(); } else { ec = std::error_code(errno, std::system_category()); return; } } ec = std::error_code(); } void MemoryMappedFile::close() { std::error_code ec; close(ec); if (ec) { throw std::system_error(ec, "MemoryMappedFile::close"); } } void MemoryMappedFile::flush(uint8_t* data, uint64_t size, std::error_code& ec) { assert(isOpened()); uintptr_t pageSize = static_cast<uintptr_t>(sysconf(_SC_PAGESIZE)); uintptr_t dataAddr = reinterpret_cast<uintptr_t>(data); uintptr_t pageOffset = (dataAddr / pageSize) * pageSize; int result = ::msync(reinterpret_cast<void*>(pageOffset), static_cast<size_t>(dataAddr % pageSize + size), MS_SYNC); if (result == 0) { result = ::fsync(m_file); if (result == 0) { ec = std::error_code(); return; } } ec = std::error_code(errno, std::system_category()); } void MemoryMappedFile::flush(uint8_t* data, uint64_t size) { assert(isOpened()); std::error_code ec; flush(data, size, ec); if (ec) { throw std::system_error(ec, "MemoryMappedFile::flush"); } } void MemoryMappedFile::swap(MemoryMappedFile& other) { std::swap(m_file, other.m_file); std::swap(m_path, other.m_path); std::swap(m_data, other.m_data); std::swap(m_size, other.m_size); } }
// Created on: 1992-02-18 // Created by: Christophe MARION // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _HLRAlgo_Interference_HeaderFile #define _HLRAlgo_Interference_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <HLRAlgo_Intersection.hxx> #include <HLRAlgo_Coincidence.hxx> #include <TopAbs_Orientation.hxx> class HLRAlgo_Intersection; class HLRAlgo_Coincidence; class HLRAlgo_Interference { public: DEFINE_STANDARD_ALLOC Standard_EXPORT HLRAlgo_Interference(); Standard_EXPORT HLRAlgo_Interference(const HLRAlgo_Intersection& Inters, const HLRAlgo_Coincidence& Bound, const TopAbs_Orientation Orient, const TopAbs_Orientation Trans, const TopAbs_Orientation BTrans); void Intersection (const HLRAlgo_Intersection& I); void Boundary (const HLRAlgo_Coincidence& B); void Orientation (const TopAbs_Orientation O); void Transition (const TopAbs_Orientation Tr); void BoundaryTransition (const TopAbs_Orientation BTr); const HLRAlgo_Intersection& Intersection() const; HLRAlgo_Intersection& ChangeIntersection(); const HLRAlgo_Coincidence& Boundary() const; HLRAlgo_Coincidence& ChangeBoundary(); TopAbs_Orientation Orientation() const; TopAbs_Orientation Transition() const; TopAbs_Orientation BoundaryTransition() const; protected: private: HLRAlgo_Intersection myIntersection; HLRAlgo_Coincidence myBoundary; TopAbs_Orientation myOrientation; TopAbs_Orientation myTransition; TopAbs_Orientation myBTransition; }; #define TheSubShape HLRAlgo_Intersection #define TheSubShape_hxx <HLRAlgo_Intersection.hxx> #define TheShape HLRAlgo_Coincidence #define TheShape_hxx <HLRAlgo_Coincidence.hxx> #define TopBas_Interference HLRAlgo_Interference #define TopBas_Interference_hxx <HLRAlgo_Interference.hxx> #include <TopBas_Interference.lxx> #undef TheSubShape #undef TheSubShape_hxx #undef TheShape #undef TheShape_hxx #undef TopBas_Interference #undef TopBas_Interference_hxx #endif // _HLRAlgo_Interference_HeaderFile
#include <emmintrin.h> #include <immintrin.h> #include <x86intrin.h> #include <xmmintrin.h> #include "tx_config.h" #include "./opt_config.hh" //#include "../../third_party/r2/src/common.hh" //#include "../../nvm/benchs/two_sided/core.hh" #include <utility> // for forward namespace nocc { namespace rtx { //using namespace r2; #define CONFLICT_WRITE_FLAG 73 // implementations of TX's get operators inline __attribute__((always_inline)) MemNode * TXOpBase::local_lookup_op(int tableid, uint64_t key) { MemNode *node = db_->stores_[tableid]->Get(key); return node; } inline __attribute__((always_inline)) MemNode *TXOpBase::local_get_op(MemNode *node,char *val,uint64_t &seq,int len,int meta) { retry: // retry if there is a concurrent writer char *cur_val = (char *)(node->value); seq = node->seq; asm volatile("" ::: "memory"); #if INLINE_OVERWRITE memcpy(val,node->padding + meta,len); #else memcpy(val,cur_val + meta,len); #endif asm volatile("" ::: "memory"); if( unlikely(node->seq != seq || seq == CONFLICT_WRITE_FLAG) ) { goto retry; } return node; } inline __attribute__((always_inline)) MemNode * TXOpBase::local_get_op(int tableid,uint64_t key,char *val,int len,uint64_t &seq,int meta) { MemNode *node = local_lookup_op(tableid,key); assert(node != NULL); assert(node->value != NULL); return local_get_op(node,val,seq,len,meta); } inline __attribute__((always_inline)) MemNode *TXOpBase::local_insert_op(int tableid,uint64_t key,uint64_t &seq) { MemNode *node = db_->stores_[tableid]->GetWithInsert(key); assert(node != NULL); seq = node->seq; return node; } inline __attribute__((always_inline)) bool TXOpBase::local_try_lock_op(MemNode *node,uint64_t lock_content) { assert(lock_content != 0); // 0: not locked volatile uint64_t *lockptr = &(node->lock); if( unlikely( (*lockptr != 0) || !__sync_bool_compare_and_swap(lockptr,0,lock_content))) return false; return true; } inline __attribute__((always_inline)) MemNode *TXOpBase::local_try_lock_op(int tableid,uint64_t key,uint64_t lock_content) { MemNode *node = db_->stores_[tableid]->Get(key); assert(node != NULL && node->value != NULL); if(local_try_lock_op(node,lock_content)) return node; return NULL; } inline __attribute__((always_inline)) bool TXOpBase::local_try_release_op(MemNode *node,uint64_t lock_content) { volatile uint64_t *lockptr = &(node->lock); return __sync_bool_compare_and_swap(lockptr,lock_content,0); } inline __attribute__((always_inline)) bool TXOpBase::local_try_release_op(int tableid,uint64_t key,uint64_t lock_content) { MemNode *node = db_->stores_[tableid]->GetWithInsert(key); return local_try_release_op(node,lock_content); } inline __attribute__((always_inline)) bool TXOpBase::local_validate_op(MemNode *node,uint64_t seq) { return (seq == node->seq) && (node->lock == 0); } inline __attribute__((always_inline)) bool TXOpBase::local_validate_op(int tableid,uint64_t key,uint64_t seq) { MemNode *node = db_->stores_[tableid]->Get(key); return local_validate_op(node,seq); } template <typename T> inline constexpr T round_up(const T &num, const T &multiple) { assert(multiple && ((multiple & (multiple - 1)) == 0)); return (num + multiple - 1) & -multiple; } inline int nt_memcpy_128(char *src, int size, char *target) { uint64_t src_p = (uint64_t)src; src_p = round_up<uint64_t>(src_p, 64); uint64_t target_p = (uint64_t)target; target_p = round_up<uint64_t>(target_p,64); auto cur_ptr = (char *)src_p; int cur = 0; #if OPT_NT_ALIGN // LOG(4) << "in copy"; sleep(1); ASSERT((uint64_t)src_p % 32 == 0); ASSERT((uint64_t)target_p % 32 == 0); for (cur = 0; cur < size;) { cur += sizeof(__m128i); //_mm_stream_si128((__m128i *)(target + cur), *((__m128i *)(src + cur))); _mm_stream_si128((__m128i *)(target_p + cur), *((__m128i *)(src_p + cur))); // LOG(4) << "copied: " << cur; } #else for (cur = 0; cur < size;) { cur += sizeof(__m64); _mm_stream_pi((__m64 *)(target + cur), *((__m64 *)(src + cur))); // LOG(4) << "copied: " << cur; } #endif // LOG(4) << "copy done: " << cur; return cur; } inline __attribute__((always_inline)) MemNode *TXOpBase::inplace_write_op(MemNode *node,char *val,int len,int meta) { #if OPT_NT && 1 //ASSERT(false); nt_memcpy_128(val, len, (char *)node->value); #else auto old_seq = node->seq;assert(node->seq != 1); #if !DRAM_LOCK node->seq = CONFLICT_WRITE_FLAG; asm volatile("" ::: "memory"); #endif #if INLINE_OVERWRITE memcpy(node->padding,val,len); #else if(node->value == NULL) { node->value = (uint64_t *)malloc(len); } memcpy((char *)(node->value) + meta,val,len); #endif #if !DRAM_LOCK // release the locks asm volatile("" ::: "memory"); node->seq = old_seq + 2; asm volatile("" ::: "memory"); node->lock = 0; #endif #endif return node; } inline __attribute__((always_inline)) MemNode *TXOpBase::inplace_write_op(int tableid,uint64_t key,char *val,int len) { MemNode *node = db_->stores_[tableid]->Get(key); ASSERT(node != NULL) << "get node error, at [tab " << tableid << "], key: "<< key; return inplace_write_op(node,val,len,db_->_schemas[tableid].meta_len); } template <typename REQ,typename... _Args> inline __attribute__((always_inline)) uint64_t TXOpBase::rpc_op(int cid,int rpc_id,int pid, char *req_buf,char *res_buf,_Args&& ... args) { // prepare the arguments *((REQ *)req_buf) = REQ(std::forward<_Args>(args)...); // send the RPC rpc_->prepare_multi_req(res_buf,1,cid); rpc_->append_req(req_buf,rpc_id,sizeof(REQ),cid,RRpc::REQ,pid); } // } end class } // namespace rtx } // namespace nocc
#include "CollidableObject.h" #include <ncltech/ScreenPicker.h> #include <ncltech/NCLDebug.h> #include <libsim/XPBD.h> CollidableObject::CollidableObject(const std::string& name, XPBDSphereConstraint* target) : ObjectMesh(name) , m_Target(target) , m_LocalClickOffset(0.0f, 0.0f, 0.0f) , m_MouseDownColOffset(0.2f, 0.2f, 0.2f, 0.0f) , m_MouseOverColOffset(0.2f, 0.2f, 0.2f, 0.0f) { //Register the object to listen for click callbacks ScreenPicker::Instance()->RegisterObject(this); } CollidableObject::~CollidableObject() { //Unregister the object to prevent sending click events to undefined memory ScreenPicker::Instance()->UnregisterObject(this); } void CollidableObject::SetMouseOverColourOffset(const Vector4& col_offset) { m_MouseOverColOffset = col_offset; } void CollidableObject::SetMouseDownColourOffset(const Vector4& col_offset) { m_MouseOverColOffset = m_MouseDownColOffset - col_offset; } void CollidableObject::OnMouseEnter(float dt) { this->m_Colour += m_MouseOverColOffset; } void CollidableObject::OnMouseLeave(float dt) { this->m_Colour -= m_MouseOverColOffset; } void CollidableObject::OnMouseDown(float dt, const Vector3& worldPos) { m_LocalClickOffset = worldPos - this->m_WorldTransform.GetPositionVector(); this->m_Colour += m_MouseDownColOffset; if (this->HasPhysics()) { this->Physics()->SetAngularVelocity(Vector3(0.0f, 0.0f, 0.0f)); this->Physics()->SetLinearVelocity(Vector3(0.0f, 0.0f, 0.0f)); } } void CollidableObject::OnMouseMove(float dt, const Vector3& worldPos, const Vector3& worldChange) { Vector3 newpos = worldPos - m_LocalClickOffset; if (this->HasPhysics()) { this->Physics()->SetPosition(worldPos - m_LocalClickOffset); this->Physics()->SetAngularVelocity(Vector3(0.0f, 0.0f, 0.0f)); this->Physics()->SetLinearVelocity(worldChange / dt * 0.5f); } else { this->m_LocalTransform.SetPositionVector(worldPos - m_LocalClickOffset); m_Target->centre.x = worldPos.x - m_LocalClickOffset.x; m_Target->centre.y = worldPos.y - m_LocalClickOffset.y; m_Target->centre.z = worldPos.z - m_LocalClickOffset.z; } } void CollidableObject::OnMouseUp(float dt, const Vector3& worldPos) { if (this->HasPhysics()) { this->Physics()->SetPosition(worldPos - m_LocalClickOffset); } else { this->m_LocalTransform.SetPositionVector(worldPos - m_LocalClickOffset); m_Target->centre.x = worldPos.x - m_LocalClickOffset.x; m_Target->centre.y = worldPos.y - m_LocalClickOffset.y; m_Target->centre.z = worldPos.z - m_LocalClickOffset.z; } this->m_Colour -= m_MouseDownColOffset; }
#include "definitions.h" #include "tests.h" /************************************************************ * UPDATE_SCREEN: * Blits pixels from RAM to VRAM for rendering ***********************************************************/ void SendFrame(SDL_Texture* GPU_OUTPUT, SDL_Renderer * ren, SDL_Surface* frameBuf) { SDL_UpdateTexture(GPU_OUTPUT, NULL, frameBuf->pixels, frameBuf->pitch); SDL_RenderClear(ren); SDL_RenderCopy(ren, GPU_OUTPUT, NULL, NULL); SDL_RenderPresent(ren); } /************************************************************* * POLL_CONTROLS: * Updates the state of the application based on: * keyboard, mouse, touch screen, gamepad inputs ************************************************************/ void PollUserInputs(bool & playing) { SDL_Event e; while(SDL_PollEvent(&e)) { if(e.type == SDL_QUIT) { playing = false; } if(e.key.keysym.sym == 'q' && e.type == SDL_KEYDOWN) { playing = false; } } } /**************************************** * Renders a triangle/convex polygon * to the screen with the appropriate * fill pattern ***************************************/ void DrawClippedTriangle(POINTER_2D(framePtr), Vertex* triangle, Attributes* attrs, int count) { // Error check if(count < 3) return; // Your code goes here } /**************************************** * Renders a line to the screen with the * appropriate coloring ***************************************/ void DrawLine(POINTER_2D(framePtr), Vertex* line, Attributes* attrs, int count) { // Error check if(count != 2) return; // Your code goes here } /**************************************** * Renders a point to the screen with the * appropriate coloring ***************************************/ void DrawPoint(POINTER_2D(framePtr), Vertex* v, Attributes* attrs, int count) { if(count == 0) return; // Set our pixel according to the attribute value! framePtr[v->y][v->x] = attrs->color; } /************************************************************* * TRANSFORM_VERTICES: * Where rotations, translations, scaling operations * transform the input vertices. NOTE: This does not * include the camera view transform. ************************************************************/ void TransformVertices( Vertex inputVerts[], Attributes inputAttrs[], int numInput, Vertex transVerts[], Attributes transAttrs[], int & numTrans, Transform* trans) { // Dummy code - your code will replace this for(numTrans = 0; numTrans < numInput; numTrans++) { transVerts[numTrans] = inputVerts[numTrans]; transAttrs[numTrans] = inputAttrs[numTrans]; } } /************************************************************* * CLIP_VERTICES: * Depending on our view type - clip to the frustrum that * maps to our screen's aspect ratio. ************************************************************/ void ClipVertices(Vertex transVerts[], Attributes transAttrs[], int numTrans, Vertex clippedVerts[], Attributes clippedAttrs[], int & numClipped, VIEW_MATRICES view) { // Dummy code - your code will replace this for(numClipped = 0; numClipped < numTrans; numClipped++) { clippedVerts[numClipped] = transVerts[numClipped]; clippedAttrs[numClipped] = transAttrs[numClipped]; } } /************************************************************* * VIEW_TRANSFORM_VERTICES: * Converts our clipped geometry to screen space. * This usually means using PERSPECTIVE or ORTHOGRAPHIC * views. ************************************************************/ void ViewTransformVertices( Vertex clippedVerts[], Attributes clippedAttrs[], int numClipped, Vertex viewVerts[], Attributes viewAttrs[], int & numView, VIEW_MATRICES view) { // Dummy code - your code will replace this for(numView = 0; numView < numClipped; numView++) { viewVerts[numView] = clippedVerts[numView]; viewAttrs[numView] = clippedAttrs[numView]; } } /*************************************************************************** * Processes the indiecated PRIMITIVES type through stages of: * 1) Transformation * 2) Clipping * 3) Perspective or Orthographic projection * 4) Vertex Interpolation * 5) Fragment Shading **************************************************************************/ void DrawPrimitive(PRIMITIVES type, Vertex inputVerts[], Attributes inputAttrs[], int numIn, POINTER_2D(framePtr), Transform * transFormMatrix, // Default parameter available VIEW_MATRICES view_m) // Default parameter available { // Matrix Transformations Vertex transVerts[MAX_VERTICES]; Attributes transAttrs[MAX_VERTICES]; int numTrans; TransformVertices(inputVerts, inputAttrs, numIn, transVerts, transAttrs, numTrans, transFormMatrix); // Clip to our frustrum Vertex clippedVerts[MAX_VERTICES]; Attributes clippedAttrs[MAX_VERTICES]; int numClipped; ClipVertices(transVerts, transAttrs, numTrans, clippedVerts, clippedAttrs, numClipped, view_m); // View space transform Vertex viewVerts[MAX_VERTICES]; Attributes viewAttrs[MAX_VERTICES]; int numView; ViewTransformVertices(clippedVerts, clippedAttrs, numClipped, viewVerts, viewAttrs, numView, view_m); // Vertex Interpolation & Fragment Drawing switch(type) { case POINT: DrawPoint(framePtr, viewVerts, viewAttrs, numView); break; case LINE: DrawLine(framePtr, viewVerts, viewAttrs, numView); break; case TRIANGLE: DrawClippedTriangle(framePtr, viewVerts, viewAttrs, numView); break; } } /*********************************************** * Sets the screen to the indicated color value. **********************************************/ void ClearScreen(POINTER_2D(framePtr), COLOR color = 0xff000000) { for(int y = 0; y < S_HEIGHT; y++) { for(int x = 0; x < S_WIDTH; x++) { framePtr[y][x] = color; } } } /************************************************************* * MAIN: * Main game loop, initialization, memory management ************************************************************/ int main() { // -----------------------DATA TYPES---------------------- SDL_Window* WIN; // Our Window SDL_Renderer* REN; // Interfaces CPU with GPU SDL_Texture * GPU_OUTPUT; // GPU buffer image (GPU Memory) SDL_Surface* FRAME_BUF; // CPU buffer image (Main Memory) POINTER_2D(framePtr); // Assists with setting pixels in FRAME_BUF // ------------------------INITIALIZATION------------------- SDL_Init(SDL_INIT_EVERYTHING); WIN = SDL_CreateWindow(GAME_NAME, 200, 200, S_WIDTH, S_HEIGHT, 0); REN = SDL_CreateRenderer(WIN, -1, SDL_RENDERER_SOFTWARE); FRAME_BUF = SDL_CreateRGBSurface(0, S_WIDTH, S_HEIGHT, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000); FRAME_BUF = SDL_ConvertSurface(SDL_GetWindowSurface(WIN), SDL_GetWindowSurface(WIN)->format, 0); GPU_OUTPUT = SDL_CreateTextureFromSurface(REN, FRAME_BUF); framePtr = SETUP_POINTER_2D(FRAME_BUF); // Draw loop bool running = true; while(running) { // Poll for user inputs PollUserInputs(running); // Refresh Screen ClearScreen(framePtr); // Call DrawPrimitive here or access framePtr directly // Your code goes here // Ensure framerate at 60fps, push to screen SDL_Delay(17); SendFrame(GPU_OUTPUT, REN, FRAME_BUF); } // Cleanup SDL_FreeSurface(FRAME_BUF); SDL_DestroyTexture(GPU_OUTPUT); SDL_DestroyRenderer(REN); SDL_DestroyWindow(WIN); SDL_Quit(); return 0; }
/* * File: Esfera.h * Author: raul * * Created on 21 de enero de 2014, 11:17 */ #ifndef ESFERA_H #define ESFERA_H #include "ObjetoCuadrico.h" class Esfera : public ObjetoCuadrico { public: Esfera(); Esfera(GLdouble radius, GLint slices, GLint stacks); void dibuja(); private: GLdouble _radius; GLint _slices; GLint _stacks; }; #endif /* ESFERA_H */
/** Underscore @file /.../Source/Kabuki_SDK-Impl/_3D/PolarPoint.cs @author Cale McCollough @copyright Copyright 2016 Cale McCollough © @license http://www.apache.org/licenses/LICENSE-2.0 @brief This file contains the _2D.Vector_f interface. */ using System; namespace _3D { /** */ public class PolarPoint_d { /** Default constructor. */ public PolarPoint_d () { theta1 = 0; theta2 = 0; r1 = 0; r2 = 0; } /** Constructor initializes with given values @param thisAngle The angle of the coordinate. @param thisNumber The magnitude of the coordinate. */ public PolarPoint_d (double angle1, double angle2, double redius1, double radius2) { theta1 = angle1; theta2 = angle2; r1 = redius1; r2 = redius2; } public double Angle1 { get { return theta1; } set { theta1 = value; } } public double Angle2 { get { return theta2; } set { theta2 = value; } } public double Radius1 { get { return r1; } set { r1 = value; } } public double Radius2 { get { return r2; } set { r2 = value; } } public double Magnitude () { double distance1 = System.Math.Sqrt (theta1 * theta1 + r1 * r1), distance2 = System.Math.Sqrt (theta2 * theta2 + r2 * r2); return System.Math.Sqrt (distance1 * distance1 + distance1 * distance2); } private: double theta1, theta2, r1, r2; } }
#ifndef ntrajectoryH #define ntrajectoryH #include "nearest.h" /* class NearestTrajectory : public Nearest { private: vector<set<uint> > trajectory_points; void Add_Point(uint index); void Search(const node* root); public: NearestTrajectory(uint q, const kdTree& t, uint p); }; */ #endif
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <iostream> #include <string> #include <thread> #include <glog/logging.h> #include <folly/fibers/Baton.h> #include <folly/io/async/ScopedEventBaseThread.h> #include <quic/api/QuicSocket.h> #include <quic/client/QuicClientTransport.h> #include <quic/common/BufUtil.h> #include <quic/common/test/TestClientUtils.h> #include <quic/common/test/TestUtils.h> #include <quic/fizz/client/handshake/FizzClientQuicHandshakeContext.h> #include <quic/samples/echo/LogQuicStats.h> namespace quic { namespace samples { constexpr size_t kNumTestStreamGroups = 2; class EchoClient : public quic::QuicSocket::ConnectionSetupCallback, public quic::QuicSocket::ConnectionCallback, public quic::QuicSocket::ReadCallback, public quic::QuicSocket::WriteCallback, public quic::QuicSocket::DatagramCallback { public: EchoClient( const std::string& host, uint16_t port, bool useDatagrams, uint64_t activeConnIdLimit, bool enableMigration, bool enableStreamGroups) : host_(host), port_(port), useDatagrams_(useDatagrams), activeConnIdLimit_(activeConnIdLimit), enableMigration_(enableMigration), enableStreamGroups_(enableStreamGroups) {} void readAvailable(quic::StreamId streamId) noexcept override { auto readData = quicClient_->read(streamId, 0); if (readData.hasError()) { LOG(ERROR) << "EchoClient failed read from stream=" << streamId << ", error=" << (uint32_t)readData.error(); } auto copy = readData->first->clone(); if (recvOffsets_.find(streamId) == recvOffsets_.end()) { recvOffsets_[streamId] = copy->length(); } else { recvOffsets_[streamId] += copy->length(); } LOG(INFO) << "Client received data=" << copy->moveToFbString().toStdString() << " on stream=" << streamId; } void readAvailableWithGroup( quic::StreamId streamId, quic::StreamGroupId groupId) noexcept override { auto readData = quicClient_->read(streamId, 0); if (readData.hasError()) { LOG(ERROR) << "EchoClient failed read from stream=" << streamId << ", groupId=" << groupId << ", error=" << (uint32_t)readData.error(); } auto copy = readData->first->clone(); if (recvOffsets_.find(streamId) == recvOffsets_.end()) { recvOffsets_[streamId] = copy->length(); } else { recvOffsets_[streamId] += copy->length(); } LOG(INFO) << "Client received data=" << copy->moveToFbString().toStdString() << " on stream=" << streamId << ", groupId=" << groupId; } void readError(quic::StreamId streamId, QuicError error) noexcept override { LOG(ERROR) << "EchoClient failed read from stream=" << streamId << ", error=" << toString(error); // A read error only terminates the ingress portion of the stream state. // Your application should probably terminate the egress portion via // resetStream } void readErrorWithGroup( quic::StreamId streamId, quic::StreamGroupId groupId, QuicError error) noexcept override { LOG(ERROR) << "EchoClient failed read from stream=" << streamId << ", groupId=" << groupId << ", error=" << toString(error); } void onNewBidirectionalStream(quic::StreamId id) noexcept override { LOG(INFO) << "EchoClient: new bidirectional stream=" << id; quicClient_->setReadCallback(id, this); } void onNewBidirectionalStreamGroup( quic::StreamGroupId groupId) noexcept override { LOG(INFO) << "EchoClient: new bidirectional stream group=" << groupId; } void onNewBidirectionalStreamInGroup( quic::StreamId id, quic::StreamGroupId groupId) noexcept override { LOG(INFO) << "EchoClient: new bidirectional stream=" << id << " in group=" << groupId; quicClient_->setReadCallback(id, this); } void onNewUnidirectionalStream(quic::StreamId id) noexcept override { LOG(INFO) << "EchoClient: new unidirectional stream=" << id; quicClient_->setReadCallback(id, this); } void onNewUnidirectionalStreamGroup( quic::StreamGroupId groupId) noexcept override { LOG(INFO) << "EchoClient: new unidirectional stream group=" << groupId; } void onNewUnidirectionalStreamInGroup( quic::StreamId id, quic::StreamGroupId groupId) noexcept override { LOG(INFO) << "EchoClient: new unidirectional stream=" << id << " in group=" << groupId; quicClient_->setReadCallback(id, this); } void onStopSending( quic::StreamId id, quic::ApplicationErrorCode /*error*/) noexcept override { VLOG(10) << "EchoClient got StopSending stream id=" << id; } void onConnectionEnd() noexcept override { LOG(INFO) << "EchoClient connection end"; } void onConnectionSetupError(QuicError error) noexcept override { onConnectionError(std::move(error)); } void onConnectionError(QuicError error) noexcept override { LOG(ERROR) << "EchoClient error: " << toString(error.code) << "; errStr=" << error.message; startDone_.post(); } void onTransportReady() noexcept override { startDone_.post(); } void onStreamWriteReady(quic::StreamId id, uint64_t maxToSend) noexcept override { LOG(INFO) << "EchoClient socket is write ready with maxToSend=" << maxToSend; sendMessage(id, pendingOutput_[id]); } void onStreamWriteError(quic::StreamId id, QuicError error) noexcept override { LOG(ERROR) << "EchoClient write error with stream=" << id << " error=" << toString(error); } void onDatagramsAvailable() noexcept override { auto res = quicClient_->readDatagrams(); if (res.hasError()) { LOG(ERROR) << "EchoClient failed reading datagrams; error=" << res.error(); return; } for (const auto& datagram : *res) { LOG(INFO) << "Client received datagram =" << datagram.bufQueue() .front() ->cloneCoalesced() ->moveToFbString() .toStdString(); } } void start(std::string token) { folly::ScopedEventBaseThread networkThread("EchoClientThread"); auto evb = networkThread.getEventBase(); folly::SocketAddress addr(host_.c_str(), port_); evb->runInEventBaseThreadAndWait([&] { auto sock = std::make_unique<QuicAsyncUDPSocketType>(evb); auto fizzClientContext = FizzClientQuicHandshakeContext::Builder() .setCertificateVerifier(test::createTestCertificateVerifier()) .build(); quicClient_ = std::make_shared<quic::QuicClientTransport>( evb, std::move(sock), std::move(fizzClientContext)); quicClient_->setHostname("echo.com"); quicClient_->addNewPeerAddress(addr); if (!token.empty()) { quicClient_->setNewToken(token); } if (useDatagrams_) { auto res = quicClient_->setDatagramCallback(this); CHECK(res.hasValue()) << res.error(); } TransportSettings settings; settings.datagramConfig.enabled = useDatagrams_; settings.selfActiveConnectionIdLimit = activeConnIdLimit_; settings.disableMigration = !enableMigration_; if (enableStreamGroups_) { settings.notifyOnNewStreamsExplicitly = true; settings.advertisedMaxStreamGroups = kNumTestStreamGroups; } quicClient_->setTransportSettings(settings); quicClient_->setTransportStatsCallback( std::make_shared<LogQuicStats>("client")); LOG(INFO) << "EchoClient connecting to " << addr.describe(); quicClient_->start(this, this); }); startDone_.wait(); std::string message; bool closed = false; auto client = quicClient_; if (enableStreamGroups_) { // Generate two groups. for (size_t i = 0; i < kNumTestStreamGroups; ++i) { auto groupId = quicClient_->createBidirectionalStreamGroup(); CHECK(groupId.hasValue()) << "Failed to generate a stream group: " << groupId.error(); streamGroups_[i] = *groupId; } } auto sendMessageInStream = [&]() { if (message == "/close") { quicClient_->close(folly::none); closed = true; return; } // create new stream for each message auto streamId = client->createBidirectionalStream().value(); client->setReadCallback(streamId, this); pendingOutput_[streamId].append(folly::IOBuf::copyBuffer(message)); sendMessage(streamId, pendingOutput_[streamId]); }; auto sendMessageInStreamGroup = [&]() { // create new stream for each message auto streamId = client->createBidirectionalStreamInGroup(getNextGroupId()); CHECK(streamId.hasValue()) << "Failed to generate stream id in group: " << streamId.error(); client->setReadCallback(*streamId, this); pendingOutput_[*streamId].append(folly::IOBuf::copyBuffer(message)); sendMessage(*streamId, pendingOutput_[*streamId]); }; // loop until Ctrl+D while (!closed && std::getline(std::cin, message)) { if (message.empty()) { continue; } evb->runInEventBaseThreadAndWait([=] { if (enableStreamGroups_) { sendMessageInStreamGroup(); } else { sendMessageInStream(); } }); } LOG(INFO) << "EchoClient stopping client"; } ~EchoClient() override = default; private: [[nodiscard]] quic::StreamGroupId getNextGroupId() { return streamGroups_[(curGroupIdIdx_++) % kNumTestStreamGroups]; } void sendMessage(quic::StreamId id, BufQueue& data) { auto message = data.move(); auto res = useDatagrams_ ? quicClient_->writeDatagram(message->clone()) : quicClient_->writeChain(id, message->clone(), true); if (res.hasError()) { LOG(ERROR) << "EchoClient writeChain error=" << uint32_t(res.error()); } else { auto str = message->moveToFbString().toStdString(); LOG(INFO) << "EchoClient wrote \"" << str << "\"" << ", len=" << str.size() << " on stream=" << id; // sent whole message pendingOutput_.erase(id); } } std::string host_; uint16_t port_; bool useDatagrams_; uint64_t activeConnIdLimit_; bool enableMigration_; bool enableStreamGroups_; std::shared_ptr<quic::QuicClientTransport> quicClient_; std::map<quic::StreamId, BufQueue> pendingOutput_; std::map<quic::StreamId, uint64_t> recvOffsets_; folly::fibers::Baton startDone_; std::array<StreamGroupId, kNumTestStreamGroups> streamGroups_; size_t curGroupIdIdx_{0}; }; } // namespace samples } // namespace quic
/* Copyright 2019 Abner Soares e Kallebe Sousa */ #ifndef ENTIDADES_HPP_ #define ENTIDADES_HPP_ #include <string> #include "../dominios/dominios.hpp" /** * @brief Entidade Usuario * @details * A classe Usuário representa uma entidade dos usuários que utilizam o sistema * de carona, tanto passageiros quanto motoristas. A entidade possui atributos * privados cujos tipos são Domínios e métodos públicos de get e set para acesso * a esses atributos. * @see Dominio */ class Usuario { private: Nome nome; /**< @param nome Nome do usuário */ Telefone telefone; /**< @param telefone Telefone do usuário */ Email email; /**< @param email E-mail do usuário */ Senha senha; /**< @param senha Senha de acesso do usuário */ Cpf cpf; /**< @param cpf CPF do usuário */ public: /** * @brief Método para adicionar nome à entidade Usuário * @param valor Valor do nome a ser adicionado ao usuário * @see Dominio */ void setNome(string); /** * @brief Método para retornar o nome da entidade Usuário * @return Valor do tipo Nome com o nome do usuário * @see Dominio */ Nome getNome() { return this->nome; } /** * @brief Método para adicionar telefone à entidade Usuário * @param valor Valor do telefone a ser adicionado ao usuário * @see Dominio */ void setTelefone(string); /** * @brief Método para retornar o telefone da entidade Usuário * @return Valor do tipo Telefone com o telefone do usuário * @see Dominio */ Telefone getTelefone() { return this->telefone; } /** * @brief Método para adicionar e-mail à entidade Usuário * @param valor Valor do e-mail a ser adicionado ao usuário * @see Dominio */ void setEmail(string); /** * @brief Método para retornar o e-mail da entidade Usuário * @return Valor do tipo Email com o e-mail do usuário * @see Dominio */ Email getEmail() { return this->email; } /** * @brief Método para adicionar senha à entidade Usuário * @param valor Valor da senha a ser adicionado ao usuário * @see Dominio */ void setSenha(string); /** * @brief Método para retornar a senha da entidade Usuário * @return Valor do tipo Senha com a senha do usuário * @see Dominio */ Senha getSenha() { return this->senha; } /** * @brief Método para adicionar CPF à entidade Usuário * @param valor Valor da CPF a ser adicionado ao usuário * @see Dominio */ void setCpf(string); /** * @brief Método para retornar o CPF da entidade Usuário * @return Valor do tipo Cpf com o CPF do usuário * @see Dominio */ Cpf getCpf() { return this->cpf; } }; /** * @brief Entidade Reserva * @details * A classe Reserva representa uma entidade das reservas de caronas que são * realizadas por usuários. A entidade possui atributos privados cujos tipos * são Domínios e métodos públicos de get e set para acesso a esses atributos. * @see Dominio */ class Reserva { private: Codigo_de_reserva codigo; /**< @param codigo Código da reserva */ Assento assento; /**< @param assento Assento escolhido para a reserva */ Bagagem bagagem; /**< @param bagagem Quantidade de bagagem */ public: /** * @brief Método para adicionar um Código de reserva a entidade Reserva * @param valor Valor do código a ser adicionado a reserva * @see Dominio */ void setCodigo_de_reserva(string); /** * @brief Método para retornar o Código de reserva da entidade Reserva * @return Valor do tipo Codigo_de_reserva com o código da reserva * @see Dominio */ Codigo_de_reserva getCodigo_de_reserva() { return this->codigo; } /** * @brief Método para adicionar um assento a entidade Reserva * @param valor Valor do assento a ser adicionado a reserva * @see Dominio */ void setAssento(string); /** * @brief Método para retornar o Assento da entidade Reserva * @return Valor do tipo Assento com o assento da reserva * @see Dominio */ Assento getAssento() { return this->assento; } /** * @brief Método para adicionar bagagem a entidade Reserva * @param valor Valor da bagagem a ser adicionada a reserva * @see Dominio */ void setBagagem(string); /** * @brief Método para retornar a Bagagem da entidade Reserva * @return Valor do tipo Bagagem com a bagagem da reserva * @see Dominio */ Bagagem getBagagem() { return this->bagagem; } }; /** * @brief Entidade Carona * @details * A classe Carona representa uma entidade das caronas. A entidade possui * atributos privados cujos tipos são Domínios e métodos públicos de get * e set para acesso a esses atributos. * @see Dominio */ class Carona { private: Codigo_de_carona codigo; /**< @param codigo Código da carona */ Cidade cidade_origem; /**< @param cidade_origem Cidade de origem da carona */ Estado estado_origem; /**< @param estado_origem Estado de origem da carona */ Cidade cidade_destino; /**< @param cidade_destino Cidade de destino da carona */ Estado estado_destino; /**< @param estado_destino Estado de destino da carona */ Data data; /**< @param data Data da carona */ Duracao duracao; /**< @param duracao Duração da carona */ Vagas vagas; /**< @param vagas Número de vagas da carona */ Preco preco; /**< @param preco Preço da carona */ public: /** * @brief Método para adicionar um Código de carona a entidade Carona * @param valor Valor do código a ser adicionado a carona * @see Dominio */ void setCodigo_de_carona(string); /** * @brief Método para retornar o Código da entidade Carona * @return Valor do tipo Codigo_de_carona com o código da carona * @see Dominio */ Codigo_de_carona getCodigo_de_carona() { return this->codigo; } /** * @brief Método para adicionar uma Cidade de origem a entidade Carona * @param valor Valor da cidade de origem a ser adicionada a carona * @see Dominio */ void setCidade_origem(string); /** * @brief Método para retornar a Cidade de origem da entidade Carona * @return Valor do tipo Cidade_de_origem com a cidade de origem da carona * @see Dominio */ Cidade getCidadeOrigem() { return this->cidade_origem; } /** * @brief Método para adicionar um Estado de origem a entidade Carona * @param valor Valor do estado de origem a ser adicionado a carona * @see Dominio */ void setEstado_origem(string); /** * @brief Método para retornar o Estado de origem da entidade Carona * @return Valor do tipo Estado_de_origem com o estado de origem da carona * @see Dominio */ Estado getEstado_origem() { return this->estado_origem; } /** * @brief Método para adicionar uma Cidade de destino a entidade Carona * @param valor Valor da cidade de destino a ser adicionada a carona * @see Dominio */ void setCidade_destino(string); /** * @brief Método para retornar a Cidade de destino da entidade Carona * @return Valor do tipo Cidade_de_destino com a cidade de destino da carona * @see Dominio */ Cidade getCidadedestino() { return this->cidade_destino; } /** * @brief Método para adicionar um Estado de destino a entidade Carona * @param valor Valor do estado de destino a ser adicionado a carona * @see Dominio */ void setEstado_destino(string); /** * @brief Método para retornar o Estado de destino da entidade Carona * @return Valor do tipo Estado_de_destino com a cidade de origem da carona * @see Dominio */ Estado getEstado_destino() { return this->estado_destino; } /** * @brief Método para adicionar uma Data a entidade Carona * @param valor Valor da data a ser adicionada a carona * @see Dominio */ void setData(string); /** * @brief Método para retornar a Data da entidade Carona * @return Valor do tipo Data com a data da carona * @see Dominio */ Data getData() { return this->data; } /** * @brief Método para adicionar uma Duracao a entidade Carona * @param valor Valor da duracao a ser adicionada a carona * @see Dominio */ void setDuracao(string); /** * @brief Método para retornar a Duração da entidade Carona * @return Valor do tipo Duracao com a duração da carona * @see Dominio */ Duracao getDuracao() { return this->duracao; } /** * @brief Método para adicionar Vagas a entidade Carona * @param valor Quantidade de vagas a ser adicionada a carona * @see Dominio */ void setVagas(string); /** * @brief Método para retornar as Vagas da entidade Carona * @return Valor do tipo Vagas com as vagas da carona * @see Dominio */ Vagas getVagas() { return this->vagas; } /** * @brief Método para adicionar um Preco a entidade Carona * @param valor Valor preço a ser adicionada a carona * @see Dominio */ void setPreco(string); /** * @brief Método para retornar o Preço da entidade Carona * @return Valor do tipo Preço com o preço da carona * @see Dominio */ Preco getPreco() { return this->preco; } }; /** * @brief Entidade Conta * @details * A classe Conta representa uma entidade das contas de usuários para pagamento. * A entidade possui atributos privados cujos tipos são Domínios e métodos públicos * de get e set para acesso a esses atributos. * @see Dominio */ class Conta { private: Codigo_de_banco banco; /**< @param banco Código do banco da conta */ Numero_de_agencia agencia; /**< @param agencia Número da agencia da conta */ Numero_de_conta numero; /**< @param numero Número da conta */ public: /** * @brief Método para adicionar um Código de banco a entidade Conta * @param valor Valor do código de banco a ser adicionado a conta * @see Dominio */ void setCodigo_de_banco(string); /** * @brief Método para retornar o Código de banco da entidade Conta * @return Valor do tipo Codigo_de_banco com o código do banco da conta * @see Dominio */ Codigo_de_banco getCodigo_de_banco() { return this->banco; } /** * @brief Método para adicionar um Número de agencia a entidade Conta * @param valor Valor do número de agencia a ser adicionado a conta * @see Dominio */ void setNumero_de_agencia(string); /** * @brief Método para retornar o Número de agencia da entidade Conta * @return Valor do tipo Numero_de_agencia com o número da agencia da conta * @see Dominio */ Numero_de_agencia getNumero_de_agencia() { return this->agencia; } /** * @brief Método para adicionar um Número de conta a entidade Conta * @param valor Valor do número de conta a ser adicionado a conta * @see Dominio */ void setNumero_de_conta(string); /** * @brief Método para retornar o Número de conta da entidade Conta * @return Valor do tipo Numero_de_conta com o número da conta * @see Dominio */ Numero_de_conta getNumero_de_conta() { return this->numero; } }; #endif // ENTIDADES_HPP_
#pragma once #include <iberbar/RHI/D3D11/Headers.h> #include <iberbar/RHI/D3D11/Types.h> #include <iberbar/RHI/Effect.h> namespace iberbar { namespace RHI { namespace D3D11 { class CShaderState; class CUniformBuffer; class CUniformMemoryBuffer; class CEffect : public IEffect { public: CEffect( IShaderState* pShaderState ); virtual ~CEffect(); virtual void SetShaderVariables( EShaderType nShaderType, IShaderVariableTable* pShaderVariables ) override; //FORCEINLINE void ClearDirty() //{ // memset( m_UniformBuffersDirty, 0, sizeof( m_UniformBuffersDirty ) ); //} protected: CShaderState* m_pShaderState; uint8* m_UniformMemorys[ (int)EShaderType::__Count ]; CUniformBuffer* m_UniformBuffers[ (int)EShaderType::__Count ][ D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ]; //uint8 m_UniformBuffersDirty[ (int)EShaderType::__Count ][ D3D11_COMMONSHADER_CONSTANT_BUFFER_API_SLOT_COUNT ]; }; } } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- */ #include "core/pch.h" #include "modules/libgogi/mde.h" #ifdef MDE_SUPPORT_VIEWSYSTEM #ifdef VEGA_OPPAINTER_SUPPORT #include "modules/libvega/src/oppainter/vegaoppainter.h" #endif // VEGA_OPPAINTER_SUPPORT #ifdef MDE_DEBUG_INFO // Helper class to debug if the view is being deleted when it's on the stack. class MDE_StackDebug { public: MDE_View *m_view; MDE_StackDebug(MDE_View *view) : m_view(view) { m_view->m_on_stack++; } ~MDE_StackDebug() { m_view->m_on_stack--; } }; #define MDE_DEBUG_VIEW_ON_STACK(view) MDE_StackDebug tmpdebug(view) #else #define MDE_DEBUG_VIEW_ON_STACK(view) ((void)0) #endif void MoveChildren(MDE_View *parent, int dx, int dy) { MDE_View *tmp = parent->m_first_child; while(tmp) { tmp->m_rect.x += dx; tmp->m_rect.y += dy; tmp = tmp->m_next; } } // == MDE_Screen ========================================================== void MDE_Screen::Init(int width, int height) { #ifdef MDE_SUPPORT_MOUSE m_captured_input = NULL; m_captured_button = 0; m_mouse_x = 0; m_mouse_y = 0; #endif #ifdef MDE_SUPPORT_TOUCH op_memset(&m_touch, 0, sizeof(m_touch)); #endif // MDE_SUPPORT_TOUCH #ifdef MDE_DEBUG_INFO m_debug_flags = MDE_DEBUG_DEFAULT; #endif #ifdef MDE_SUPPORT_SPRITES m_first_sprite = NULL; m_last_sprite = NULL; #endif #ifdef MDE_SUPPORT_DND m_drag_x = 0; m_drag_y = 0; m_last_dnd_view = NULL; m_dnd_capture_view = NULL; #endif m_screen = this; m_rect.w = width; m_rect.h = height; Invalidate(m_rect); UpdateRegion(); } class MDE_ScrollOperation : public ListElement<MDE_ScrollOperation> { public: MDE_ScrollOperation(MDE_View* view, const MDE_RECT& rect, int dx, int dy, bool move_children) : m_view(view), m_rect(rect), m_dx(dx), m_dy(dy), m_move_children(move_children) {} bool Add(MDE_View* view, const MDE_RECT& rect, int dx, int dy, bool move_children) { OP_ASSERT(m_view == view); if (!MDE_RectIsIdentical(m_rect, rect) || m_move_children != move_children) return false; m_dx += dx; m_dy += dy; return true; } void Scroll(MDE_BUFFER* screen_buf, MDE_Region& region) { m_view->ScrollRectInternal(m_rect, m_dx, m_dy, m_move_children, screen_buf, &region, true); } void Move() { if (m_view->IsVisible()) m_view->Invalidate(m_rect, true); if (m_move_children && m_view->m_first_child) { MoveChildren(m_view, m_dx, m_dy); m_view->UpdateRegion(); } if (m_view->IsVisible()) m_view->Invalidate(m_rect, true); } MDE_View* const m_view; const MDE_RECT m_rect; int m_dx, m_dy; const bool m_move_children; }; OP_STATUS MDE_Screen::AddDeferredScroll(MDE_View* view, const MDE_RECT& rect, int dx, int dy, bool move_children) { MDE_ScrollOperation* o; // find previous matching entry and add to that if possible for (o = m_deferred_scroll_operations.Last(); o; o = o->Pred()) { if (o->m_view == view) { if (o->Add(view, rect, dx, dy, move_children)) return OpStatus::OK; break; } } // no matching entry found, create new one o = OP_NEW(MDE_ScrollOperation, (view, rect, dx, dy, move_children)); if (!o) { // allocation of new entry failed, move all children for (MDE_ScrollOperation* o = m_deferred_scroll_operations.First(); o; o = o->Suc()) o->Move(); m_deferred_scroll_operations.Clear(); return OpStatus::ERR_NO_MEMORY; } o->Into(&m_deferred_scroll_operations); // invalidation deferred, manually inform platform it should validate view->SetInvalidState(); return OpStatus::OK; } void MDE_Screen::AdjustRectForDeferredScroll(MDE_View* view, MDE_RECT& rect) { for (MDE_ScrollOperation* o = m_deferred_scroll_operations.First(); o; o = o->Suc()) { if (o->m_view == view && MDE_RectContains(o->m_rect, rect)) { rect.x -= o->m_dx; rect.y -= o->m_dy; return; } else if (o->m_view == view && MDE_RectIntersects(o->m_rect, rect)) { // We intersect it partly, so should we adjust it or not? // The only sure thing is to make a union of both. MDE_RECT old_rect = rect; rect.x -= o->m_dx; rect.y -= o->m_dy; rect = MDE_RectUnion(old_rect, rect); return; } } } void MDE_Screen::ApplyDeferredScroll(MDE_BUFFER* screen_buf, MDE_Region& region) { OP_ASSERT(screen_buf); // Take all deferred scrolls out from the list so the Invalidations we do from // scrolling isn't adjusted by AdjustRectForDeferredScroll. // When there is several pending (non merged) scrolls on the same view, // the already made invalidations will be adjusted in ScrollRect and we don't // want to adjust them twice. List<MDE_ScrollOperation> all_operations; all_operations.Append(&m_deferred_scroll_operations); while (MDE_ScrollOperation *o = all_operations.First()) { o->Out(); o->Scroll(screen_buf, region); OP_DELETE(o); } } void MDE_Screen::OnChildRemoved(MDE_View* child) { for (MDE_ScrollOperation* o = m_deferred_scroll_operations.First(); o; ) { MDE_ScrollOperation* next = o->Suc(); // search upwards for match MDE_View* v = o->m_view; while (v && v != child) v = v->m_parent; if (v) { o->Out(); OP_DELETE(o); } o = next; } } #ifdef MDE_DEBUG_INFO void MDE_Screen::SetDebugInfo(int flags) { m_debug_flags = flags; Invalidate(MDE_MakeRect(0, 0, m_rect.w, m_rect.h), true); } void MDE_Screen::DrawDebugRect(const MDE_RECT &rect, unsigned int col, MDE_BUFFER *dstbuf) { MDE_SetColor(col, dstbuf); MDE_DrawRect(rect, dstbuf); } #endif // MDE_DEBUG_INFO #ifdef MDE_SUPPORT_SPRITES void MDE_Screen::AddSprite(MDE_Sprite *spr) { if (spr->m_screen) return; if (m_first_sprite) m_first_sprite->m_prev = spr; spr->m_next = m_first_sprite; m_first_sprite = spr; if (!m_last_sprite) m_last_sprite = spr; spr->m_displayed = false; spr->m_screen = this; spr->Invalidate(); } void MDE_Screen::RemoveSprite(MDE_Sprite *spr) { if (spr->m_next) spr->m_next->m_prev = spr->m_prev; if (spr->m_prev) spr->m_prev->m_next = spr->m_next; if (spr == m_first_sprite) m_first_sprite = spr->m_next; if (spr == m_last_sprite) m_last_sprite = spr->m_prev; if (spr->m_displayed) // Invalidate screen. Could be changed to backblit the background buffer immediately. Invalidate(spr->m_displayed_rect, true); spr->m_displayed = false; spr->m_screen = NULL; spr->m_prev = NULL; spr->m_next = NULL; } void MDE_Screen::PaintSpriteInViewInternal(MDE_BUFFER *screen, MDE_Sprite *spr, MDE_View *view, bool paint_background) { if (!view->IsVisible()) return; // Call OnPaint for each part of the visible region of view and its children. if (!view->ValidateRegion()) m_screen->OutOfMemory(); for(int i = 0; i < view->m_region.num_rects; i++) { MDE_BUFFER sub_buffer; MDE_MakeSubsetBuffer(spr->m_displayed_rect, &sub_buffer, screen); MDE_SetClipRect(MDE_MakeRect(view->m_region.rects[i].x - spr->m_displayed_rect.x, view->m_region.rects[i].y - spr->m_displayed_rect.y, view->m_region.rects[i].w, view->m_region.rects[i].h), &sub_buffer); sub_buffer.outer_clip = sub_buffer.clip; if (paint_background) MDE_DrawBuffer(spr->m_buf, MDE_MakeRect(0, 0, spr->m_buf->w, spr->m_buf->h), 0, 0, &sub_buffer); else spr->OnPaint(MDE_MakeRect(0, 0, spr->m_buf->w, spr->m_buf->h), &sub_buffer); } // Paint sprites in childviews regions MDE_View *tmp = view->m_first_child; while(tmp) { PaintSpriteInViewInternal(screen, spr, tmp, paint_background); tmp = tmp->m_next; } } void MDE_Screen::PaintSprite(MDE_BUFFER* screen, MDE_Sprite* spr) { MDE_BUFFER dst = *screen; dst.clip = dst.outer_clip; dst.method = MDE_METHOD_COPY; // Copy background MDE_DrawBuffer(&dst, MDE_MakeRect(0, 0, spr->m_rect.w, spr->m_rect.h), spr->m_rect.x, spr->m_rect.y, spr->m_buf); // Draw sprite if (spr->m_view) { PaintSpriteInViewInternal(&dst, spr, spr->m_view, false); } else { MDE_BUFFER sub_buffer; MDE_MakeSubsetBuffer(spr->m_displayed_rect, &sub_buffer, screen); spr->OnPaint(MDE_MakeRect(0, 0, spr->m_buf->w, spr->m_buf->h), &sub_buffer); } } void MDE_Screen::UnpaintSprite(MDE_BUFFER* screen, MDE_Sprite* spr) { // Restore background if (spr->m_view) PaintSpriteInViewInternal(screen, spr, spr->m_view, true); else MDE_DrawBuffer(spr->m_buf, spr->m_displayed_rect, 0, 0, screen); } void MDE_Screen::DisplaySpritesInternal(MDE_BUFFER *screen, MDE_Region *update_region) { if (!m_first_sprite) return; // Undisplay sprites that are displayed and invalid MDE_Sprite *spr = m_first_sprite; while (spr) { if (spr->m_displayed && spr->m_invalid) { // We have to undisplay all sprites covering this sprites rect (In reversed order) UndisplaySpritesInternal(screen, update_region, spr->m_displayed_rect); } spr = spr->m_next; } // Display sprites that are not displayed spr = m_first_sprite; while (spr) { if (!spr->m_displayed) { spr->m_displayed = true; spr->m_invalid = false; spr->m_displayed_rect = spr->m_rect; PaintSprite(screen, spr); MDE_RECT update_rect = MDE_RectClip(spr->m_displayed_rect, m_screen->m_rect); if (!MDE_RectIsEmpty(update_rect)) if (!update_region->IncludeRect(update_rect)) { m_screen->OutOfMemory(); return; } } spr = spr->m_next; } } void MDE_Screen::UndisplaySpritesInternal(MDE_BUFFER *screen, MDE_Region *update_region, const MDE_RECT &rect) { // Remove clipping and set COPY method on the screen MDE_BUFFER screen_noclip = *screen; screen_noclip.clip = screen_noclip.outer_clip; screen_noclip.method = MDE_METHOD_COPY; // Must undisplay sprites in reversed order to get backgrounds correct for overlapping sprites. MDE_Sprite *spr = m_last_sprite; while (spr) { UndisplaySpritesRecursiveInternal(&screen_noclip, update_region, rect, spr); spr = spr->m_prev; } } void MDE_Screen::UndisplaySpritesRecursiveInternal(MDE_BUFFER *screen, MDE_Region *update_region, const MDE_RECT &rect, MDE_Sprite *spr) { if (spr->m_displayed && MDE_RectIntersects(spr->m_displayed_rect, rect)) { // Look for sprites in front of this one that intersects. This might result in long 'chains' of sprites // being undisplayed just because the first sprite needed to be undisplayed. MDE_Sprite *tmp_spr = spr->m_next; while (tmp_spr) { if (tmp_spr->m_displayed) UndisplaySpritesRecursiveInternal(screen, update_region, spr->m_displayed_rect, tmp_spr); tmp_spr = tmp_spr->m_next; } spr->m_displayed = false; UnpaintSprite(screen, spr); MDE_RECT update_rect = MDE_RectClip(spr->m_displayed_rect, m_screen->m_rect); if (!MDE_RectIsEmpty(update_rect)) if (!update_region->IncludeRect(update_rect)) { m_screen->OutOfMemory(); return; } } } // == MDE_Sprite ========================================================== MDE_Sprite::MDE_Sprite() : m_buf(NULL) , m_screen(NULL) , m_view(NULL) , m_displayed(false) , m_invalid(false) , m_prev(NULL) , m_next(NULL) , m_hx(0) , m_hy(0) { MDE_RectReset(m_rect); MDE_RectReset(m_displayed_rect); } MDE_Sprite::~MDE_Sprite() { MDE_ASSERT(!m_screen); // Still in screen. Remove it before deleting it! MDE_DeleteBuffer(m_buf); } bool MDE_Sprite::Init(int w, int h, MDE_Screen *screen) { m_buf = MDE_CreateBuffer(w, h, screen->GetFormat(), 0); m_rect.w = w; m_rect.h = h; return m_buf ? true : false; } void MDE_Sprite::SetView(MDE_View *view) { m_view = view; Invalidate(); } void MDE_Sprite::SetPos(int x, int y) { x -= m_hx; y -= m_hy; if (x == m_rect.x && y == m_rect.y) return; m_rect.x = x; m_rect.y = y; Invalidate(); } void MDE_Sprite::SetHotspot(int x, int y) { int px = m_rect.x + m_hx; int py = m_rect.y + m_hy; m_hx = x; m_hy = y; SetPos(px, py); } void MDE_Sprite::Invalidate() { m_invalid = true; if (m_screen && !m_screen->GetInvalidFlag()) { m_screen->SetInvalidFlag(true); m_screen->OnInvalid(); } // Invalidate all sprites. They might overlap and must be removed and painted in a special order again. if (m_screen) { MDE_Sprite *spr = m_next; while (spr) { spr->m_invalid = true; spr = spr->m_next; } } } #endif // MDE_SUPPORT_SPRITES // == MDE_View ========================================================== MDE_View::MDE_View() : m_activity_invalidation(ACTIVITY_INVALIDATION) { MDE_RectReset(m_rect); MDE_RectReset(m_invalid_rect); m_is_visible = true; m_is_invalid = false; m_is_region_invalid = true; m_region_invalid_first_check = true; m_is_validating = false; m_is_transparent = false; m_is_fully_transparent = false; m_is_scrolling_transparent = false; m_affect_lower_regions = true; m_bypass_lock = false; m_updatelock_counter = 0; m_num_overlapping_transparentviews = 0; m_num_overlapping_scrolling_transparentviews = 0; m_scroll_transp_invalidate_extra = 0; m_scroll_invalidate_extra = 0; m_exclude_invalidation = false; m_visibility_check_needed = false; #ifdef MDE_DEBUG_INFO m_color_toggle_debug = 0; m_on_stack = 0; #endif m_parent = NULL; m_next = NULL; m_first_child = NULL; m_screen = NULL; // Doesn't matter what we set m_region_or_child_visible to. Set m_visibility_status_first_check to true // so the first time we calculate the visible status, we will run OnVisibilityChanged no matter what. m_region_or_child_visible = true; m_visibility_status_first_check = true; // Shouldn't matter what we initialize to, but be extra safe and do it. m_onbeforepaint_return = true; } MDE_View::~MDE_View() { MDE_ASSERT(!m_parent); // Still in a parent. Remove the view before deleting it! #ifdef MDE_DEBUG_INFO // If this assert trigs, this view is currently on the stack and there's a big chance it will crash soon! MDE_ASSERT(m_on_stack == 0); #endif MDE_View *tmp = m_first_child; while(tmp) { MDE_View *next = tmp->m_next; tmp->m_parent = NULL; OP_DELETE(tmp); tmp = next; } } void MDE_View::SetScreenRecursive(MDE_Screen* screen) { if (screen == m_screen) return; if (!screen) m_screen->OnChildRemoved(this); m_screen = screen; for (MDE_View* child = m_first_child; child; child = child->m_next) child->SetScreenRecursive(screen); } void MDE_View::AddChild(MDE_View *child, MDE_View *after) { if (child->m_parent) child->m_parent->RemoveChild(child); if (after) { child->m_parent = this; child->m_next = after->m_next; after->m_next = child; } else { child->m_parent = this; child->m_next = m_first_child; m_first_child = child; } child->SetScreenRecursive(m_screen); UpdateRegion(); child->Invalidate(MDE_MakeRect(0, 0, child->m_rect.w, child->m_rect.h), true); child->OnAdded(); } void MDE_View::RemoveChildInternal(MDE_View *child, bool temporary) { MDE_ASSERT(child->m_parent == this); MDE_ASSERT(m_first_child); if (!m_first_child) return; else if (m_first_child == child) m_first_child = child->m_next; else { MDE_View *tmp = m_first_child->m_next; MDE_View *prev = m_first_child; while(tmp) { if (tmp == child) { prev->m_next = child->m_next; break; } prev = tmp; tmp = tmp->m_next; } } #ifdef MDE_SUPPORT_MOUSE if (!temporary && child->m_screen) { // If we are removing a mouse captured widget (or parent of it), unset the capture! MDE_View *tmp = child->m_screen->m_captured_input; while (tmp) { if (tmp == child) { child->m_screen->m_captured_input = NULL; break; } tmp = tmp->m_parent; } #ifdef MDE_SUPPORT_TOUCH child->ReleaseFromTouchCapture(); #endif // MDE_SUPPORT_TOUCH #ifdef MDE_SUPPORT_DND // If we are removing the last known dnd view (or parent of it), unset the view! tmp = child->m_screen->m_last_dnd_view; while (tmp) { if (tmp == child) { child->m_screen->m_last_dnd_view = NULL; break; } tmp = tmp->m_parent; } tmp = child->m_screen->m_dnd_capture_view; while (tmp) { if (tmp == child) { child->m_screen->m_dnd_capture_view = NULL; break; } tmp = tmp->m_parent; } #endif // MDE_SUPPORT_DND } #endif child->SetScreenRecursive(NULL); child->m_parent = NULL; child->m_next = NULL; child->OnRemoved(); UpdateRegion(); if (child->m_is_visible) Invalidate(child->m_rect, true); } void MDE_View::RemoveChild(MDE_View *child) { RemoveChildInternal(child, false); } void MDE_View::SetRect(const MDE_RECT &rect, bool invalidate) { if (rect.x != m_rect.x || rect.y != m_rect.y || rect.w != m_rect.w || rect.h != m_rect.h) { int dw = rect.w - m_rect.w; int dh = rect.h - m_rect.h; if (m_parent && m_is_visible && invalidate && !MDE_RectIsEmpty(m_rect)) m_parent->Invalidate(m_rect, true); MDE_RECT old_rect = m_rect; m_rect = rect; if (IsVisible() && invalidate) { if (dw > 0) Invalidate(MDE_MakeRect(m_rect.w - dw, 0, dw, m_rect.h), true); if (dh > 0) Invalidate(MDE_MakeRect(0, m_rect.h - dh, m_rect.w, dh), true); } if (m_is_transparent) Invalidate(MDE_MakeRect(0, 0, m_rect.w, m_rect.h)); if (m_parent && m_is_visible) m_parent->UpdateRegion(); else UpdateRegion(); if (old_rect.w != m_rect.w || old_rect.h != m_rect.h) OnResized(old_rect.w, old_rect.h); if (!MDE_RectIsIdentical(old_rect, m_rect)) OnRectChanged(old_rect); } } void MDE_View::SetVisibility(bool visible) { if (visible != m_is_visible) { m_is_visible = visible; if (!visible) { if (m_parent) m_parent->Invalidate(m_rect, true); } else { // If this view was invalid already, Invalidate would fail to propagate the invalid state // to its parents (in MDE_View::SetInvalidState). Clear it here so it will do the job. MDE_RectReset(m_invalid_rect); SetInvalidFlag(false); Invalidate(MDE_MakeRect(0, 0, m_rect.w, m_rect.h), true); } if (m_parent) m_parent->UpdateRegion(); } } void MDE_View::SetZ(MDE_Z z) { if (this == m_screen || !m_parent) return; MDE_View *parent = m_parent; MDE_View *tmp = NULL; switch(z) { case MDE_Z_LOWER: tmp = parent->m_first_child; if (tmp != this) { if (tmp->m_next == this) tmp = NULL; else { while (tmp->m_next->m_next != this) tmp = tmp->m_next; } parent->RemoveChildInternal(this, true); parent->AddChild(this, tmp); } break; case MDE_Z_HIGHER: MDE_ASSERT(false); // FIX break; case MDE_Z_TOP: if (!m_next) break; tmp = m_next; while(tmp && tmp->m_next) tmp = tmp->m_next; parent->RemoveChildInternal(this, true); parent->AddChild(this, tmp); break; case MDE_Z_BOTTOM: parent->RemoveChildInternal(this, true); parent->AddChild(this); break; } } void MDE_View::SetFullyTransparent(bool fully_transparent) { #ifdef MDE_SUPPORT_TRANSPARENT_VIEWS if (fully_transparent != m_is_fully_transparent) { m_is_fully_transparent = fully_transparent; if (m_screen) m_screen->UpdateRegion(); } #endif // MDE_SUPPORT_TRANSPARENT_VIEWS } void MDE_View::SetScrollingTransparent(bool scrolling_transparent) { #ifdef MDE_SUPPORT_TRANSPARENT_VIEWS if (scrolling_transparent != m_is_scrolling_transparent) m_is_scrolling_transparent = scrolling_transparent; #endif // MDE_SUPPORT_TRANSPARENT_VIEWS } void MDE_View::SetTransparent(bool transparent) { #ifdef MDE_SUPPORT_TRANSPARENT_VIEWS if (transparent != m_is_transparent) { m_is_transparent = transparent; if (m_parent) { m_parent->Invalidate(m_rect, true); if (m_screen) m_screen->UpdateRegion(); } } #endif // MDE_SUPPORT_TRANSPARENT_VIEWS } void MDE_View::SetAffectLowerRegions(bool affect_lower_regions) { if (affect_lower_regions != m_affect_lower_regions) { m_affect_lower_regions = affect_lower_regions; if (m_parent) { m_parent->Invalidate(m_rect, true); if (m_screen) m_screen->UpdateRegion(); } } } MDE_View *MDE_View::GetTransparentParent() { #ifdef MDE_SUPPORT_TRANSPARENT_VIEWS MDE_View *tmp = m_parent; while(tmp) { if (tmp->m_is_transparent) return tmp; tmp = tmp->m_parent; } #endif // MDE_SUPPORT_TRANSPARENT_VIEWS return NULL; } void MDE_View::Invalidate(const MDE_RECT &crect, bool include_children, bool ignore_if_hidden, bool recursing_internal, bool bypass_lock) { if (m_is_transparent && m_is_fully_transparent && !m_is_scrolling_transparent) return; #ifdef MDE_SUPPORT_TRANSPARENT_VIEWS if (m_exclude_invalidation) return; MDE_RECT rect = crect; if (m_screen) m_screen->AdjustRectForDeferredScroll(this, rect); // Fix: Precalculate value of has transparent parent instead of calling GetTransparentParent. // If this view is transparent and locked, don't invalidate the parent, // since this will cause this view to invalidate immediately, even though // it's locked. Instead invalidate the parent when the view is unlocked. if (!recursing_internal && m_is_visible && m_parent && ((m_is_transparent || GetTransparentParent()) && !IsLockedAndNoBypass())) { m_exclude_invalidation = true; MDE_RECT rect_in_parent = rect; rect_in_parent.x += m_rect.x; rect_in_parent.y += m_rect.y; m_parent->Invalidate(rect_in_parent, true, false, false, true); m_exclude_invalidation = false; return; } #endif if (ignore_if_hidden && !m_is_region_invalid && m_region.num_rects == 0) { // The region is known and contains no visible parts, so we don't need to call InvalidateInternal. } else InvalidateInternal(rect); if (m_is_invalid && bypass_lock) m_bypass_lock = true; // FIX: This could be moved into SetInvalidState to optimize. We would need a m_is_invalid_self though! if (m_is_invalid && !recursing_internal) { OnInvalidSelf(); MDE_View *tmp = m_parent; while(tmp) { tmp->OnInvalidSelf(); tmp = tmp->m_parent; } } if (include_children) { MDE_View *tmp = m_first_child; while(tmp) { if (MDE_RectIntersects(rect, tmp->m_rect)) { MDE_RECT ofsrect = rect; ofsrect.x -= tmp->m_rect.x; ofsrect.y -= tmp->m_rect.y; tmp->Invalidate(ofsrect, include_children, ignore_if_hidden, true, bypass_lock); } tmp = tmp->m_next; } } } void MDE_View::InvalidateInternal(const MDE_RECT &rect) { MDE_ASSERT(!MDE_RectIsInsideOut(rect)); if (MDE_RectIsEmpty(rect) || !m_is_visible) return; if (!MDE_RectIntersects(rect, MDE_MakeRect(0, 0, m_rect.w, m_rect.h))) return; #ifndef MDE_SMALLER_AREA_MORE_ONPAINT // == m_invalid_rect only ====================================== if (MDE_RectIsEmpty(m_invalid_rect)) // if (!m_is_invalid) m_invalid_rect = rect; else m_invalid_rect = MDE_RectUnion(m_invalid_rect, rect); #else // MDE_SMALLER_AREA_MORE_ONPAINT // == m_invalid_rect and m_invalid_region ====================== // FIX: Check if slack is much enough? // FIX: if max number of rects in region is hit, we could divide it into smallest unions instead of using no region at all. if (MDE_RectIsEmpty(m_invalid_rect)) // if (!m_is_invalid) { m_invalid_rect = rect; m_invalid_region.Set(rect); } else { m_invalid_rect = MDE_RectUnion(m_invalid_rect, rect); if (MDE_RectIntersects(rect, MDE_MakeRect(0, 0, m_rect.w, m_rect.h))) { MDE_RECT new_rect = rect; int num_rects = m_invalid_region.num_rects; bool need_overlap_check = false; for (int i = 0; i < num_rects; i++) { const int fluff = 20; MDE_RECT new_rect_fluff = new_rect; new_rect_fluff.x -= ((new_rect_fluff.w>>2) + fluff); new_rect_fluff.y -= ((new_rect_fluff.h>>2) + fluff); new_rect_fluff.w += ((new_rect_fluff.w>>2) + fluff); new_rect_fluff.h += ((new_rect_fluff.h>>2) + fluff); MDE_RECT big_rect = m_invalid_region.rects[i]; big_rect.x -= ((big_rect.w>>2) + fluff); big_rect.y -= ((big_rect.h>>2) + fluff); big_rect.w += ((big_rect.w>>2) + fluff); big_rect.h += ((big_rect.h>>2) + fluff); if (MDE_RectIntersects(big_rect, new_rect_fluff)) { MDE_RECT new_rect_union = MDE_RectUnion(m_invalid_region.rects[i], new_rect); int new_rect_union_area = MDE_RectUnitArea(new_rect_union); // If the new union area is considerably larger (adding more than 200*200px) than the 2 rectangles alone, // just add the new_rect to the region after removing the overlap (if possible). if (new_rect_union_area > 1024 && new_rect_union_area - (MDE_RectUnitArea(m_invalid_region.rects[i]) + MDE_RectUnitArea(new_rect)) > 40000 && MDE_RectRemoveOverlap(new_rect, m_invalid_region.rects[i])) { // MDE_RectRemoveOverlap has changed new_rect to not overlap. } else { // To prevent overlapping, we must change new_rect for the next loop and set need_overlap_check. new_rect = new_rect_union; // We know the AddRect will succeed because we remove one first. m_invalid_region.RemoveRect(i); m_invalid_region.AddRect(new_rect); // Make sure we don't test against this new union again num_rects--; i = -1; // Will increase to 0 by forloop. need_overlap_check = true; if (num_rects <= 0) break; } } } if (need_overlap_check) // a larger rect is now included in the region { // Check region for overlapping rects. int i, j; for (i = 0; i < m_invalid_region.num_rects; i++) for (j = 0; j < m_invalid_region.num_rects; j++) if (i != j && MDE_RectIntersects(m_invalid_region.rects[i], m_invalid_region.rects[j])) { m_invalid_region.rects[i] = MDE_RectUnion(m_invalid_region.rects[i], m_invalid_region.rects[j]); m_invalid_region.RemoveRect(j); i = -1; // Will increase to 0 by forloop. break; } #ifdef _DEBUG for (i = 0; i < m_invalid_region.num_rects; i++) for (j = 0; j < m_invalid_region.num_rects; j++) if (i != j && MDE_RectIntersects(m_invalid_region.rects[i], m_invalid_region.rects[j])) { MDE_ASSERT(false); } #endif } else // new_rect wasn't near any other rect in the region, or it was decided to be added to region anyway. Add it. { if (!m_invalid_region.num_rects) m_invalid_region.Set(m_invalid_rect); else if (!m_invalid_region.AddRect(new_rect)) m_invalid_region.Reset(); // if we fail, m_invalid_rect will be used instead. // FIX: Implement smarter routine. Check area! (w>>5)*(h>>5) if (m_invalid_region.num_rects > 5) m_invalid_region.Reset(); // Assume many rects in region (many paints) is actually slower than painting full area once. } } } #endif // MDE_SMALLER_AREA_MORE_ONPAINT SetInvalidState(); } void MDE_View::SetInvalidState() { // Update invalid flag in the view hierarchy up to root and call OnInvalid the first time. if (m_is_visible) { if (!m_is_invalid) { SetInvalidFlag(true); OnInvalid(); } // Update the flag on parents. MDE_View *tmp = m_parent; while(tmp && !tmp->m_is_invalid && tmp->m_is_visible) { tmp->OnInvalid(); tmp->SetInvalidFlag(true); tmp = tmp->m_parent; } } } bool MDE_View::ShouldNotBePainted() { return !m_is_invalid || !IsVisible() || IsLockedAndNoBypass() || m_is_validating; } void MDE_View::Validate(bool include_children) { MDE_DEBUG_VIEW_ON_STACK(this); // Way 1: rectangulation. several OnPaint (one for each rect in the region) to not paint over children // Way 2: one paint and then repaint all children that is covered by the invalid rect. Will need doublebuffer. // Way 3: rectangulation. Store everything in a region which is iterated in every drawprimitive. // Current is 1 if (ShouldNotBePainted()) return; if (m_parent && GetTransparentParent()) { // Transparent views can't be Validated themself. We have to Validate the parent of the transparent view. // That will also validate this view. MDE_View *transp_parent = GetTransparentParent(); while (transp_parent->GetTransparentParent()) transp_parent = transp_parent->GetTransparentParent(); if (transp_parent->m_parent) transp_parent->m_parent->Validate(include_children); return; } OnValidate(); // Run the OnVisibilityChanged callbacks on views that wants it. CheckVisibilityChange(false); // This will call OnBeforePaint which may lead to new invalidated areas, so it is important that it // is done before we use m_invalid_region and m_invalid_rect in ValidateInternal. // It may also even cause a change to the size of the screen which replace the entire backbuffer, // so we must also do it before we call LockBuffer. BeforePaintInternal(include_children); MDE_Region update_region; MDE_BUFFER *screen = m_screen->LockBuffer(); m_screen->ApplyDeferredScroll(screen, update_region); if (m_parent) { if (!GetTransparentParent()) { MDE_BUFFER buf; m_parent->MakeSubsetOfScreen(&buf, screen); ValidateInternal(&buf, screen, &update_region, include_children); } } else { if (m_screen->UseTransparentBackground()) { VEGAOpPainter* painter = m_screen->GetVegaPainter(); painter->SetVegaTranslation(0, 0); painter->SetColor(0, 0, 0, 0); for (int i=0; i<m_invalid_region.num_rects; i++) { painter->ClearRect(OpRect(m_invalid_region.rects[i].x, m_invalid_region.rects[i].y, m_invalid_region.rects[i].w, m_invalid_region.rects[i].h)); } } ValidateInternal(screen, screen, &update_region, include_children); } #ifdef MDE_SUPPORT_SPRITES m_screen->DisplaySpritesInternal(screen, &update_region); #endif // MDE_SUPPORT_SPRITES m_screen->UnlockBuffer(&update_region); } void MDE_View::BeforePaintInternal(bool include_children) { MDE_DEBUG_VIEW_ON_STACK(this); m_onbeforepaint_return = false; // views which have a transparent parent doesn't seem to be // invalidated, always call OnBeforePaintEx for them BOOL bypass_invalid_check = (m_is_transparent || GetTransparentParent()) && !IsLockedAndNoBypass() && !m_is_validating && m_is_visible; if (!bypass_invalid_check && ShouldNotBePainted()) return; if (!MDE_RectIsEmpty(m_invalid_rect) || bypass_invalid_check) { // Make sure this views region is updated before we use it if (!ValidateRegion()) { m_screen->OutOfMemory(); return; } if (m_region.num_rects) { m_is_validating = true; m_onbeforepaint_return = OnBeforePaintEx(); m_is_validating = false; if (!m_onbeforepaint_return) { SetInvalidState(); return; } } } // Recursively call BeforePaintInternal on children if (include_children) { m_onbeforepaint_return = true; m_is_validating = true; MDE_View *tmp = m_first_child; while(tmp) { tmp->BeforePaintInternal(include_children); tmp = tmp->m_next; } m_is_validating = false; } } void MDE_View::ValidateInternal(MDE_BUFFER *buf, MDE_BUFFER *screen, MDE_Region *update_region, bool include_children) { MDE_DEBUG_VIEW_ON_STACK(this); if (ShouldNotBePainted()) return; if (!m_onbeforepaint_return) return; #ifdef MDE_SUPPORT_TRANSPARENT_VIEWS if (m_is_transparent) { SetInvalidFlag(false); return; } #endif m_bypass_lock = false; if (include_children) { SetInvalidFlag(false); } if (!MDE_RectIntersects(buf->outer_clip, m_rect)) { m_invalid_region.Reset(); MDE_RectReset(m_invalid_rect); return; } m_is_validating = true; #ifdef MDE_DEBUG_INFO MDE_RECT debug_invalid_rect = m_invalid_rect; MDE_Region debug_invalid_region; #endif MDE_BUFFER sub_buffer; MDE_MakeSubsetBuffer(m_rect, &sub_buffer, buf); if (!MDE_RectIsEmpty(m_invalid_rect)) { // Make sure this views region is updated before we use it. if (!ValidateRegion()) { m_screen->OutOfMemory(); m_is_validating = false; return; } #ifdef MDE_DEBUG_INFO debug_invalid_rect = m_invalid_rect; if (m_color_toggle_debug) m_color_toggle_debug = 0; else m_color_toggle_debug = 192; if ((m_screen->m_debug_flags & MDE_DEBUG_UPDATE_REGION) || (m_screen->m_debug_flags & MDE_DEBUG_INVALIDATE_RECT)) { m_invalid_rect = MDE_MakeRect(0, 0, m_rect.w, m_rect.h); debug_invalid_region.Swap(&m_invalid_region); } #endif // Will reset m_invalid_region but keep the contents in region. MDE_Region region; region.Swap(&m_invalid_region); // Reset m_invalid_rect and keep the contents in invalid. MDE_RECT invalid = m_invalid_rect; MDE_RectReset(m_invalid_rect); // Get this views position on the screen here, so we only have to do it once. int pos_on_screen_x = 0, pos_on_screen_y = 0; ConvertToScreen(pos_on_screen_x, pos_on_screen_y); MDE_RECT *rects = region.rects; int n, num_rects = region.num_rects; if (!num_rects) { num_rects = 1; rects = &invalid; } // For all invalid region rects, we will check and clip to the views region if and what we need to paint. for (n = 0; n < num_rects; n++) { invalid = MDE_RectClip(rects[n], MDE_MakeRect(0, 0, m_rect.w, m_rect.h)); // Include the damaged area in the update_region. MDE_RECT damaged_rect = invalid; damaged_rect.x += pos_on_screen_x; damaged_rect.y += pos_on_screen_y; damaged_rect = MDE_RectClip(damaged_rect, m_screen->m_rect); if (!MDE_RectIsEmpty(damaged_rect)) { #ifdef MDE_SUPPORT_SPRITES if (m_region.num_rects) m_screen->UndisplaySpritesInternal(screen, update_region, damaged_rect); #endif for(int i = 0; i < m_region.num_rects; i++) { MDE_RECT r = m_region.rects[i]; r.x -= pos_on_screen_x; r.y -= pos_on_screen_y; if (!MDE_RectIsEmpty(m_region.rects[i]) && MDE_RectIntersects(r, invalid)) { r = MDE_RectClip(invalid, r); MDE_SetClipRect(r, &sub_buffer); if (!MDE_RectIsEmpty(sub_buffer.clip)) { MDE_RECT painted_rect = sub_buffer.clip; m_screen->OnBeforeRectPaint(MDE_MakeRect(painted_rect.x + pos_on_screen_x, painted_rect.y + pos_on_screen_y, painted_rect.w, painted_rect.h)); bool painted = PaintInternal(sub_buffer, pos_on_screen_x, pos_on_screen_y); #ifdef MDE_DEBUG_INFO if (m_screen->m_debug_flags & MDE_DEBUG_UPDATE_REGION) { m_screen->DrawDebugRect(MDE_MakeRect(m_region.rects[i].x - pos_on_screen_x, m_region.rects[i].y - pos_on_screen_y, m_region.rects[i].w, m_region.rects[i].h), MDE_RGB(0,200,0), &sub_buffer); } if (m_screen->m_debug_flags & MDE_DEBUG_INVALIDATE_RECT) { unsigned int col = MDE_RGB(255,m_color_toggle_debug,64); m_screen->DrawDebugRect(debug_invalid_rect, col, &sub_buffer); if (debug_invalid_region.num_rects <= 1) m_screen->DrawDebugRect(MDE_MakeRect( debug_invalid_rect.x + 1, debug_invalid_rect.y + 1, debug_invalid_rect.w - 2, debug_invalid_rect.h - 2), col, &sub_buffer); col = MDE_RGB(128,m_color_toggle_debug,255); if (debug_invalid_region.num_rects > 1) for(int d = 0; d < debug_invalid_region.num_rects; d++) { m_screen->DrawDebugRect(debug_invalid_region.rects[d], col, &sub_buffer); m_screen->DrawDebugRect(MDE_MakeRect(debug_invalid_region.rects[d].x + 1, debug_invalid_region.rects[d].y + 1, debug_invalid_region.rects[d].w - 2,debug_invalid_region.rects[d].h - 2), col, &sub_buffer); } } #endif // MDE_DEBUG_INFO #ifdef MDE_SUPPORT_TRANSPARENT_VIEWS #ifdef _DEBUG // Check views with overlapping transparentviews /* if (m_num_overlapping_transparentviews) { MDE_SetColor(MDE_RGB(100,255,0), &sub_buffer); MDE_DrawRectFill(MDE_MakeRect(2, 2, 5, 5), &sub_buffer); }*/ #endif #endif m_screen->OnRectPainted(MDE_MakeRect(painted_rect.x + pos_on_screen_x, painted_rect.y + pos_on_screen_y, painted_rect.w, painted_rect.h)); if (painted) { // Include the painted rect in the update_region that should be flushed to screen. if (!update_region->IncludeRect(MDE_MakeRect(painted_rect.x + pos_on_screen_x, painted_rect.y + pos_on_screen_y, painted_rect.w, painted_rect.h))) { m_screen->OutOfMemory(); m_is_validating = false; return; } } } } } } } } // Validate children if (include_children) { MDE_View *tmp = m_first_child; while(tmp) { tmp->ValidateInternal(&sub_buffer, screen, update_region, include_children); tmp = tmp->m_next; } } m_is_validating = false; } bool MDE_View::PaintInternal(MDE_BUFFER sub_buffer, int pos_on_screen_x, int pos_on_screen_y) { MDE_DEBUG_VIEW_ON_STACK(this); sub_buffer.outer_clip = MDE_RectClip(sub_buffer.outer_clip, sub_buffer.clip); MDE_RECT stackrect = sub_buffer.clip; if (!OnPaintEx(stackrect, &sub_buffer)) return false; #ifdef MDE_SUPPORT_TRANSPARENT_VIEWS // FIX: m_num_overlapping_transparentviews should not count views over a nonvisible but overlapping part. if (m_num_overlapping_transparentviews > 0 || m_num_overlapping_scrolling_transparentviews > 0) { // Paint all transparent views that is child of this MDE_View *tmp = m_first_child; while(tmp) { if (tmp != this && tmp->m_is_transparent && tmp->IsVisible()) { MDE_RECT child_rect = tmp->m_rect; MDE_BUFFER child_buffer; MDE_MakeSubsetBuffer(child_rect, &child_buffer, &sub_buffer); #ifdef DEBUG_GFX if (MDE_RectIsEmpty(sub_buffer.clip)) int stop = 0; #endif tmp->PaintAllChildrenInternal(child_buffer, pos_on_screen_x + tmp->m_rect.x, pos_on_screen_y + tmp->m_rect.y); } tmp = tmp->m_next; } // Paint all other transparent views that cover this MDE_View *tmpparent = m_parent, *tmpstart = this; while(tmpparent) { int tmp_x = 0, tmp_y = 0; tmpparent->ConvertToScreen(tmp_x, tmp_y); tmp = tmpstart->m_next; while(tmp) { if (tmp->m_is_visible && !MDE_RectIsEmpty(tmp->m_rect)) { if (tmp->m_is_transparent) { MDE_RECT child_rect = tmp->m_rect; child_rect.x = child_rect.x + tmp_x - pos_on_screen_x; child_rect.y = child_rect.y + tmp_y - pos_on_screen_y; MDE_BUFFER child_buffer; MDE_MakeSubsetBuffer(child_rect, &child_buffer, &sub_buffer); #ifdef DEBUG_GFX if (MDE_RectIsEmpty(sub_buffer.clip)) int stop = 0; #endif tmp->PaintAllChildrenInternal(child_buffer, pos_on_screen_x + tmp->m_rect.x, pos_on_screen_y + tmp->m_rect.y); } } tmp = tmp->m_next; } tmpstart = tmpparent; tmpparent = tmpparent->m_parent; } } #endif // MDE_SUPPORT_TRANSPARENT_VIEWS return true; } void MDE_View::PaintAllChildrenInternal(MDE_BUFFER sub_buffer, int pos_on_screen_x, int pos_on_screen_y) { #ifdef MDE_SUPPORT_TRANSPARENT_VIEWS if (MDE_RectIsEmpty(sub_buffer.clip)) return; sub_buffer.outer_clip = MDE_RectClip(sub_buffer.outer_clip, sub_buffer.clip); MDE_RECT stackrect = sub_buffer.clip; OnPaintEx(stackrect, &sub_buffer); MDE_View *tmp = m_first_child; while(tmp) { if (tmp != this && tmp->IsVisible()) { MDE_RECT child_rect = tmp->m_rect; MDE_BUFFER child_buffer; MDE_MakeSubsetBuffer(child_rect, &child_buffer, &sub_buffer); #ifdef DEBUG_GFX if (MDE_RectIsEmpty(sub_buffer.clip)) int stop = 0; #endif tmp->PaintAllChildrenInternal(child_buffer, pos_on_screen_x + tmp->m_rect.x, pos_on_screen_y + tmp->m_rect.y); } tmp = tmp->m_next; } #else MDE_ASSERT(0); // We assume nothing is calling PaintAllChildrenInternal except transparency // support to save footprint. If called, enable the code above. #endif // MDE_SUPPORT_TRANSPARENT_VIEWS } #ifdef MDE_NO_MEM_PAINT void MDE_View::ValidateOOM(bool include_children) { // This is way 2 described in Validate if (ShouldNotBePainted()) return; OnValidate(); MDE_RECT invalid; MDE_BUFFER *screen = m_screen->LockBuffer(); MDE_RectReset(invalid); MaxInvalidRect(invalid); #ifdef MDE_SUPPORT_SPRITES MDE_Region update_region_sprites; m_screen->UndisplaySpritesInternal(screen, &update_region_sprites, invalid); #endif m_is_validating = true; if (m_parent) { MDE_BUFFER buf; m_parent->MakeSubsetOfScreen(&buf, screen); m_parent->ConvertFromScreen(invalid.x, invalid.y); ValidateOOMInternal(&buf, invalid, include_children); } else { ValidateOOMInternal(screen, invalid, include_children); } m_is_validating = false; #ifdef MDE_SUPPORT_SPRITES m_screen->DisplaySpritesInternal(screen, &update_region_sprites); #endif MDE_Region update_region; update_region.rects = &invalid; update_region.num_rects = 1; m_screen->UnlockBuffer(&update_region); update_region.rects = NULL; update_region.num_rects = 0; } void MDE_View::MaxInvalidRect(MDE_RECT& irect) { if (!m_is_invalid || !IsVisible()) return; MDE_RECT inv = m_invalid_rect; inv = MDE_RectClip(inv, MDE_MakeRect(0, 0, m_rect.w, m_rect.h)); if (m_parent) inv = MDE_RectClip(inv, MDE_MakeRect(-m_rect.x, -m_rect.y, m_parent->m_rect.w, m_parent->m_rect.h)); ConvertToScreen(inv.x, inv.y); irect = MDE_RectUnion(inv, irect); MDE_View *tmp = m_first_child; while(tmp) { tmp->MaxInvalidRect(irect); tmp = tmp->m_next; } } void MDE_View::ValidateOOMInternal(MDE_BUFFER *buf, const MDE_RECT& invalid, bool include_children) { if (!IsVisible() || IsLockedAndNoBypass()) return; if (include_children) { SetInvalidFlag(false); } m_bypass_lock = false; if (!MDE_RectIntersects(buf->outer_clip, m_rect)) { MDE_RectReset(m_invalid_rect); return; } MDE_BUFFER sub_buffer; MDE_MakeSubsetBuffer(m_rect, &sub_buffer, buf); MDE_RECT inv = invalid; inv.x -= m_rect.x; inv.y -= m_rect.y; inv = MDE_RectClip(inv, MDE_MakeRect(0, 0, m_rect.w, m_rect.h)); MDE_RectReset(m_invalid_rect); m_invalid_region.Reset(); if (!MDE_RectIsEmpty(inv)) { MDE_SetClipRect(inv, &sub_buffer); if (!MDE_RectIsEmpty(sub_buffer.clip)) { // A little hacky.. Will change if regionclipping is moved into drawprimitives. MDE_RECT old = sub_buffer.outer_clip; sub_buffer.outer_clip = MDE_RectClip(sub_buffer.outer_clip, sub_buffer.clip); MDE_RECT stackrect = sub_buffer.clip; OnPaintEx(stackrect, &sub_buffer); // FIX: Somehow call OnRectPainted after all views has been painted. //m_screen->OnRectPainted(MDE_MakeRect(stackrect.x + pos_on_screen_x, stackrect.y + pos_on_screen_y, stackrect.w, stackrect.h)); } } // Validate children if (include_children) { MDE_View *tmp = m_first_child; while(tmp) { tmp->ValidateOOMInternal(&sub_buffer, inv, include_children); tmp = tmp->m_next; } } } #endif // MDE_NO_MEM_PAINT void MDE_View::UpdateRegion(bool include_children) { // Call the OnRegionInvalid callback if it's the first time since // it was valid, or first time ever. if (!m_is_region_invalid || m_region_invalid_first_check) { m_is_region_invalid = true; m_region_invalid_first_check = false; OnRegionInvalid(); } // Make sure we re-check visibility later if (!m_visibility_check_needed && ThisOrParentWantsVisibilityChange()) m_visibility_check_needed = true; // Update the flag on parents too if needed. This must be done separetely because we might // get here even if we don't set it above (If the view was just added). if (m_visibility_check_needed) { MDE_View *tmp = m_parent; while (tmp && !tmp->m_visibility_check_needed) { tmp->m_visibility_check_needed = true; tmp = tmp->m_parent; } } if (include_children) { // Update children regions MDE_View *tmp = m_first_child; while(tmp) { tmp->UpdateRegion(); tmp = tmp->m_next; } } } void MDE_View::SetBusy() { m_activity_invalidation.Begin(); } void MDE_View::SetIdle() { m_activity_invalidation.End(); } bool MDE_View::ThisOrParentWantsVisibilityChange() { MDE_View *tmp = this; while (tmp) { if (tmp->GetOnVisibilityChangeWanted()) return true; tmp = tmp->m_parent; } return false; } void MDE_View::CheckVisibilityChange(bool force_check) { MDE_DEBUG_VIEW_ON_STACK(this); if (!m_visibility_check_needed && !force_check) return; m_visibility_check_needed = false; // First iterate through children so we can be sure those regions are up to date. // Force further iteration for all children of views that wants the callback. MDE_View *tmp = m_first_child; while(tmp) { tmp->CheckVisibilityChange(GetOnVisibilityChangeWanted() || force_check); tmp = tmp->m_next; } if (ThisOrParentWantsVisibilityChange()) { // Now check if this view or any child view has visible parts // All child views should be updated at this point. ValidateRegion(); bool vis = m_region.num_rects ? true : false; for (MDE_View* v = m_first_child; v && !vis; v = v->m_next) vis = v->m_region_or_child_visible; // Do the call if it changes or if it's the first time if (vis != m_region_or_child_visible || m_visibility_status_first_check) { m_visibility_status_first_check = false; m_region_or_child_visible = vis; OnVisibilityChanged(vis); } } } void MDE_View::ValidateRegionDone() { m_is_region_invalid = false; } bool MDE_View::AddToOverlapRegion(MDE_Region &overlapping_region, int parent_screen_x, int parent_screen_y) { MDE_ASSERT(!m_is_transparent); MDE_RECT r = m_rect; r.x += parent_screen_x; r.y += parent_screen_y; if (m_custom_overlap_region.num_rects) { // The view has a custom clipping region so add just the parts actually visible. int i; MDE_Region rgn; if (!rgn.Set(r)) return false; for(i = 0; i < m_custom_overlap_region.num_rects; i++) { MDE_RECT r = m_custom_overlap_region.rects[i]; r.x += m_rect.x + parent_screen_x; r.y += m_rect.y + parent_screen_y; if (!rgn.ExcludeRect(r)) return false; } for(i = 0; i < rgn.num_rects; i++) { bool ret = overlapping_region.AddRect(rgn.rects[i]); if (!ret) return false; } } else { // The view doesn't have a custom clipping region so just add the entire view. bool ret = overlapping_region.AddRect(r); if (!ret) return false; } return true; } bool MDE_View::ValidateRegion(bool include_children) { int i, j; if (!m_is_region_invalid) return true; m_region.Reset(false); if (MDE_RectIsEmpty(m_rect) || !IsVisible()) { ValidateRegionDone(); return true; } MDE_RECT r = m_rect; if (m_parent) { // Clip inside parents and convert to screen MDE_View* tmpp = m_parent; while (tmpp) { r = MDE_RectClip(r, MDE_MakeRect(0, 0, tmpp->m_rect.w, tmpp->m_rect.h)); r.x += tmpp->m_rect.x; r.y += tmpp->m_rect.y; tmpp = tmpp->m_parent; } if (MDE_RectIsEmpty(r)) { #ifdef MDE_SUPPORT_TRANSPARENT_VIEWS m_num_overlapping_transparentviews = 0; m_num_overlapping_scrolling_transparentviews = 0; m_scroll_invalidate_extra = 0; #endif ValidateRegionDone(); return true; } } bool ret = m_region.Set(r); if (!ret) return false; MDE_Region overlapping_region; #ifdef MDE_SUPPORT_TRANSPARENT_VIEWS m_num_overlapping_transparentviews = 0; m_num_overlapping_scrolling_transparentviews = 0; m_scroll_invalidate_extra = 0; #endif // Iterate through all children in all parents of this. Add each views rect to overlapping_region. MDE_View *tmp, *tmpparent = m_parent, *tmpstart = this; while(tmpparent) { int tmp_x = 0, tmp_y = 0; tmpparent->ConvertToScreen(tmp_x, tmp_y); tmp = tmpstart->m_next; while(tmp) { if (tmp->m_is_visible && !MDE_RectIsEmpty(tmp->m_rect) && tmp->m_affect_lower_regions) { if (!tmp->m_is_transparent) { // We have a solid view that is overlapping. Add it to the overlapping_region. if (!tmp->AddToOverlapRegion(overlapping_region, tmp_x, tmp_y)) return false; } #ifdef MDE_SUPPORT_TRANSPARENT_VIEWS else if (MDE_RectIntersects(r, MDE_MakeRect(tmp_x + tmp->m_rect.x, tmp_y + tmp->m_rect.y, tmp->m_rect.w, tmp->m_rect.h))) { if (!tmp->m_is_fully_transparent) m_num_overlapping_transparentviews++; if (tmp->m_is_scrolling_transparent) { m_num_overlapping_scrolling_transparentviews++; m_scroll_invalidate_extra = MAX(m_scroll_invalidate_extra, tmp->m_scroll_transp_invalidate_extra); } } #endif } tmp = tmp->m_next; } tmpstart = tmpparent; tmpparent = tmpparent->m_parent; } int tmp_x = 0, tmp_y = 0; ConvertToScreen(tmp_x, tmp_y); // Iterate through all children of this element. if (include_children) { tmp = m_first_child; while(tmp) { if (tmp->m_is_visible && !MDE_RectIsEmpty(tmp->m_rect) && tmp->m_affect_lower_regions) { if (!tmp->m_is_transparent) { if (!tmp->AddToOverlapRegion(overlapping_region, tmp_x, tmp_y)) return false; } #ifdef MDE_SUPPORT_TRANSPARENT_VIEWS else if (MDE_RectIntersects(r, MDE_MakeRect(tmp_x + tmp->m_rect.x, tmp_y + tmp->m_rect.y, tmp->m_rect.w, tmp->m_rect.h))) { if (!tmp->m_is_fully_transparent) m_num_overlapping_transparentviews++; if (tmp->m_is_scrolling_transparent) { m_num_overlapping_scrolling_transparentviews++; m_scroll_invalidate_extra = MAX(m_scroll_invalidate_extra, tmp->m_scroll_transp_invalidate_extra); } } #endif } tmp = tmp->m_next; } } // If we have a custom clip region, we should add the nonvisible parts to // the overlap region so we don't paint them. We must do this for all parents with // custom clip regions. tmp = this; while(tmp) { if (tmp->m_custom_overlap_region.num_rects) { int tmp_x = 0, tmp_y = 0; tmp->ConvertToScreen(tmp_x, tmp_y); for(i = 0; i < tmp->m_custom_overlap_region.num_rects; i++) { MDE_RECT r = tmp->m_custom_overlap_region.rects[i]; r.x += tmp_x; r.y += tmp_y; bool ret = overlapping_region.AddRect(r); if (!ret) return false; } } tmp = tmp->m_parent; } // Split all intersecting rectangles for(j = 0; j < overlapping_region.num_rects; j++) { int num_to_split = m_region.num_rects; for(i = 0; i < num_to_split; i++) { MDE_ASSERT(!MDE_RectIsEmpty(m_region.rects[i])); MDE_ASSERT(!MDE_RectIsEmpty(overlapping_region.rects[j])); if (!MDE_RectIsEmpty(m_region.rects[i]) && MDE_RectIntersects(m_region.rects[i], overlapping_region.rects[j])) { bool ret = m_region.ExcludeRect(m_region.rects[i], overlapping_region.rects[j]); if (!ret) return false; m_region.RemoveRect(i); num_to_split--; i--; } } } // Melt together rectangles m_region.CoalesceRects(); ValidateRegionDone(); return true; } void MDE_View::SetCustomOverlapRegion(MDE_Region *rgn) { if (rgn->num_rects == m_custom_overlap_region.num_rects) { // If regions are equal, just return. int i; for (i = 0; i < rgn->num_rects; i++) if (!MDE_RectIsIdentical(m_custom_overlap_region.rects[i], rgn->rects[i])) break; if (i == rgn->num_rects) return; } m_custom_overlap_region.Swap(rgn); UpdateRegion(); } void MDE_View::ConvertToScreen(int &x, int &y) { MDE_View *tmp = this; while(tmp->m_parent) { x += tmp->m_rect.x; y += tmp->m_rect.y; tmp = tmp->m_parent; } } void MDE_View::ConvertFromScreen(int &x, int &y) { MDE_View *tmp = this; while(tmp->m_parent) { x -= tmp->m_rect.x; y -= tmp->m_rect.y; tmp = tmp->m_parent; } } void MDE_View::LockUpdate(bool lock) { if (lock) m_updatelock_counter++; else { MDE_ASSERT(m_updatelock_counter > 0); m_updatelock_counter--; // This view have been locked and might need painting but the parents might have been painted // and ignored this view (while locked). We must update the invalid state of the parents. if (m_updatelock_counter == 0 && m_is_invalid && m_parent) { // If we are transparent and got any invalidates while we were // locked, invalidating those parts on the parent have been // postponed. Make sure that they are done now. if (m_is_transparent || GetTransparentParent()) { MDE_RECT rect_in_parent = m_invalid_rect; rect_in_parent.x += m_rect.x; rect_in_parent.y += m_rect.y; m_parent->Invalidate(rect_in_parent, true); } m_parent->SetInvalidState(); } } } bool MDE_View::IsLockedAndNoBypass() { if (m_updatelock_counter <= 0 || m_bypass_lock) return false; return true; } bool MDE_View::IsVisible() { MDE_View *tmp = this; while(tmp) { if (!tmp->m_is_visible) return false; tmp = tmp->m_parent; } return true; } void MDE_View::ScrollRect(const MDE_RECT &rect, int dx, int dy, bool move_children) { if (!m_screen || MDE_RectIsEmpty(rect)) return; #ifdef MDE_FULLUPDATE_SCROLL bool full_update = true; #else bool full_update = !GetScrollMoveAllowed(); #endif // In some cases we should just invalidate and move children instead of scrolling. if (!full_update) full_update = m_updatelock_counter > 0 || MDE_ABS(dx) >= rect.w || MDE_ABS(dy) >= rect.h || !IsVisible() || !MDE_UseMoveRect() || m_is_transparent || GetTransparentParent(); if (!full_update) { if (OpStatus::IsSuccess(m_screen->AddDeferredScroll(this, rect, dx, dy, move_children))) { // Move children immediately since core might be confused if they aren't moved. // When applying the deferred scroll, we'll not move them again but still have to know // about if they moved (So the deferred scroll should still get true for move_children). if (move_children && m_first_child) { MoveChildren(this, dx, dy); UpdateRegion(); } return; } // OOM when appending this operation, invalidate everything full_update = true; } if (full_update) { if (IsVisible()) Invalidate(rect, true); if (move_children && m_first_child) { MoveChildren(this, dx, dy); UpdateRegion(); } if (IsVisible()) Invalidate(rect, true); return; } ScrollRectInternal(rect, dx, dy, move_children); } void MDE_View::ScrollRectInternal(const MDE_RECT& rect, int dx, int dy, bool move_children, MDE_BUFFER* const passed_screen_buf/* = 0*/, MDE_Region* passed_update_region/* = 0*/, bool is_deferred/* = false*/) { OP_ASSERT(!!passed_screen_buf == !!passed_update_region); #ifndef MDE_FULLUPDATE_SCROLL bool ret = ValidateRegion(); if (!ret) { Invalidate(rect); m_screen->OutOfMemory(); return; } #ifdef MDE_SUPPORT_TRANSPARENT_VIEWS if (m_num_overlapping_transparentviews > 0) { Invalidate(rect, true); if (move_children && m_first_child) { MoveChildren(this, dx, dy); UpdateRegion(); } Invalidate(rect, true); return; } #endif // Handle invalidated areas. Since the paint is pending, // we need to offset it so it's painted at the new position. if (!MDE_RectIsEmpty(m_invalid_rect)) { // Use the clipped invalid rect in the check so we optimize away the case when invalidation rect is partly outside // the viewport. That case still allows us to just move the invalid area since the outside part doesn't matter. MDE_RECT clipped_invalid_rect = MDE_RectClip(m_invalid_rect, MDE_MakeRect(0, 0, m_rect.w, m_rect.h)); if (MDE_RectContains(rect, clipped_invalid_rect)) { // m_invalid_rect is inside the scrolled area. Just move it. m_invalid_rect.x += dx; m_invalid_rect.y += dy; m_invalid_region.Offset(dx, dy); } else if (!MDE_RectIntersects(rect, m_invalid_rect)) { // The scrollrect and invalid rect doesn't intersect, so we should do nothing since they wouldn't be in the same virtual viewport. } else { // m_invalid_rect is outside the scrolled area. We can't just move it. // Set the invalidated area to the union of old and scrolled m_invalid_rect. MDE_RECT moved_rect = m_invalid_rect; moved_rect.x += dx; moved_rect.y += dy; m_invalid_rect = MDE_RectUnion(m_invalid_rect, moved_rect); // Don't bother with invalid_region (for now). m_invalid_region.Reset(); } } int pos_on_screen_x = 0, pos_on_screen_y = 0; ConvertToScreen(pos_on_screen_x, pos_on_screen_y); // Call MDE_MoveRect on every rect of m_region. MDE_RECT destrect = rect; // First clip destrect to our own rect so we don't fetch pixels from outside outself if core // calls ScrollRect with a rect larger than the view. destrect = MDE_RectClip(destrect, MDE_MakeRect(0, 0, m_rect.w, m_rect.h)); destrect.x += pos_on_screen_x; destrect.y += pos_on_screen_y; MDE_RECT cliprect = m_rect; if (m_parent) { cliprect = MDE_RectClip(cliprect, MDE_MakeRect(0, 0, m_parent->m_rect.w, m_parent->m_rect.h)); m_parent->ConvertToScreen(cliprect.x, cliprect.y); } if (move_children && m_first_child) { // Exclude the children from our visibility region during // the scroll since they should scroll with the content. UpdateRegion(false); bool ret = ValidateRegion(false); if (!ret) { Invalidate(rect); m_screen->OutOfMemory(); return; } // If this scroll is deferred, we have already moved the children. if (!is_deferred) MoveChildren(this, dx, dy); } // Check if the scroll area is inside the pending invalidate area. // If it is, we're just wasting performance scrolling it since it will all be repainted anyway. // This may often happen due to multiple scroll operations (without Validate between them) causing // invalidation handling above to expand the area when we already scroll to slow. MDE_RECT dst_rect_in_view = MDE_RectClip(rect, MDE_MakeRect(0, 0, m_rect.w, m_rect.h)); if (MDE_RectContains(m_invalid_rect, dst_rect_in_view)) { // Restore region if (move_children && m_first_child) UpdateRegion(); return; } // Prepare the screen for scrolling MDE_Region local_update_region; MDE_Region* update_region = passed_screen_buf ? passed_update_region : &local_update_region; MDE_BUFFER *screen_buf = NULL; if (m_screen->ScrollPixelsSupported()) { #ifdef MDE_SUPPORT_SPRITES // Sprites are NOT SUPPORTED when implementing ScrollPixels! // Sprites rely on valid backbuffer so we can't just scroll the frontbuffer. MDE_ASSERT(!m_screen->m_first_sprite); #endif } else { if (passed_screen_buf) screen_buf = passed_screen_buf; else screen_buf = m_screen->LockBuffer(); #ifdef MDE_SUPPORT_SPRITES m_screen->UndisplaySpritesInternal(screen_buf, update_region, MDE_MakeRect(rect.x + pos_on_screen_x, rect.y + pos_on_screen_y, rect.w, rect.h)); #endif } MDE_RECT region_bound = {0,0,0,0}; int i=0; for(; i < m_region.num_rects; i++) { region_bound = MDE_RectUnion(region_bound, m_region.rects[i]); } destrect = MDE_RectClip(destrect, region_bound); // Scroll the parts that are in the visible region for(i = 0; i < m_region.num_rects; i++) { if (MDE_RectIntersects(destrect, m_region.rects[i])) { MDE_RECT r = MDE_RectClip(destrect, m_region.rects[i]); r = MDE_RectClip(r, cliprect); r = MDE_RectClip(r, m_screen->m_rect); if (!MDE_RectIsEmpty(r)) { MDE_RECT move_rect = r; move_rect.x -= dx; move_rect.y -= dy; move_rect = MDE_RectClip(move_rect, destrect); move_rect.x += dx; move_rect.y += dy; if (!MDE_RectIsEmpty(move_rect)) { if (screen_buf) { MDE_MoveRect(move_rect, dx, dy, screen_buf); m_screen->ScrollBackground(move_rect, dx, dy); bool ret = update_region->IncludeRect(move_rect); if (!ret) { if (!passed_screen_buf) m_screen->UnlockBuffer(update_region); Invalidate(rect); m_screen->OutOfMemory(); return; } } else { m_screen->ScrollPixels(move_rect, dx, dy); } } if (dx < 0) Invalidate(MDE_MakeRect(r.x + r.w + dx - m_scroll_invalidate_extra - pos_on_screen_x, r.y - pos_on_screen_y, -dx + m_scroll_invalidate_extra, r.h), move_children); if (dy < 0) Invalidate(MDE_MakeRect(r.x - pos_on_screen_x, r.y + r.h + dy - m_scroll_invalidate_extra - pos_on_screen_y, r.w, -dy + m_scroll_invalidate_extra), move_children); if (dx > 0) Invalidate(MDE_MakeRect(r.x - pos_on_screen_x, r.y - pos_on_screen_y, dx + m_scroll_invalidate_extra, r.h), move_children); if (dy > 0) Invalidate(MDE_MakeRect(r.x - pos_on_screen_x, r.y - pos_on_screen_y, r.w, dy + m_scroll_invalidate_extra), move_children); } } } // Restore region if (move_children && m_first_child) UpdateRegion(); // Unlock if (screen_buf) { #ifdef MDE_SUPPORT_SPRITES if (!m_is_validating) m_screen->DisplaySpritesInternal(screen_buf, update_region); #endif if (!passed_screen_buf) m_screen->UnlockBuffer(update_region); } #endif // !MDE_FULLUPDATE_SCROLL } void MDE_View::OnPaint(const MDE_RECT &rect, MDE_BUFFER *screen) { if (!m_is_transparent) { #ifdef VEGA_OPPAINTER_SUPPORT VEGAOpPainter *painter = m_screen->GetVegaPainter(); if (painter) { int x = 0; int y = 0; ConvertToScreen(x, y); painter->SetVegaTranslation(x, y); painter->SetColor(0, 0, 0, 0); painter->ClearRect(OpRect(rect.x, rect.y, rect.w, rect.h)); } #else MDE_SetColor(MDE_RGBA(0, 0, 0, 0), screen); MDE_DrawRectFill(rect, screen, false); #endif // VEGA_OPPAINTER_SUPPORT } } void MDE_View::MakeSubsetOfScreen(MDE_BUFFER *buf, MDE_BUFFER *screen) { MDE_BUFFER tmpbuf; MDE_BUFFER *parentbuf = screen; if (m_parent) { m_parent->MakeSubsetOfScreen(buf, screen); parentbuf = buf; } MDE_MakeSubsetBuffer(m_rect, &tmpbuf, parentbuf); *buf = tmpbuf; } #endif // MDE_SUPPORT_VIEWSYSTEM
/* =========================================================================== Copyright (C) 2017 waYne (CAM) =========================================================================== */ #pragma once #ifndef ELYSIUM_CORE_THREADING_THREAD #define ELYSIUM_CORE_THREADING_THREAD #ifndef ELYSIUM_CORE_OBJECT #include "../Elysium.Core/Object.hpp" #endif #ifndef _THREAD_ #include <thread> #endif namespace Elysium { namespace Core { namespace Threading { /// <summary> /// ... /// </summary> class EXPORT Thread : public Object { public: // constructors & destructor Thread(); ~Thread(); // properties - getter //int GetId(); // properties - setter // methods //void Start(); private: // fields //class _TargetMethod; //class... _TargetMethodParameter; std::thread _NativeThread; void Test() { //_NativeThread = std::thread(_TargetMethod); //_NativeThread = std::thread(&Test2); //_NativeThread = std::thread(&Test3, 1); //int Id = static_cast<int>(_NativeThread.get_id()); //int ThreadId = (int)_NativeThread.get_id(); } void Test2() { } void Test3(int x) { } }; } } } #endif
// // DrumKit.hpp // DrumConsole // // Created by Paolo Simonazzi on 08/03/2016. // // #ifndef DrumKit_hpp #define DrumKit_hpp #include <stdio.h> #define NUMOFSNARELAYERS 13 #define TRIGGERGAIN 1.1 class SoundFromFile; class SoundFromRAM; enum { SNARE = 1, KICK, HIHAT, TOM1, TOM2, TOM3, CRASH, RIDE }; const int numberOfDrums = 8; class DrumKit { public: DrumKit(); ~DrumKit(); void addDrum ( int idx, const String& soundName, const String& samplesFolder ); AudioSampleBuffer* getSound ( int note, float volume ); SoundFromRAM* getSound ( int note ); private: SoundFromRAM* soundsInRam[numberOfDrums]; }; #endif /* DrumKit_hpp */
#include <iostream.h> #include <conio.h> void main () { int salary, hr, md, con, edu, bon, gross, tax, zak; clrscr(); cout <<"Enter Basic Salary in Rs:"; cin >> salary; // 5000 hr=salary/100*10; // 500 cout <<endl <<"House Rent 10% Rs:" <<hr; md=salary/100*8; // 400 cout <<endl <<endl <<"Medical Allowance 8% Rs:" <<md; con=salary/100*10; // 500 cout <<endl <<endl <<"Convance Allowance 10% Rs:" <<con; edu=salary/100*10; // 500 cout <<endl <<endl <<"Educational Allowance 10% Rs:" <<edu; bon=salary/100*5; // 50 cout <<endl <<endl <<"Bonus 5% +Rs:" <<bon; gross=(salary+hr+md+con+edu+bon); cout <<endl <<endl <<"Gross Salary Rs:" <<gross; tax=salary/100*5; cout <<endl <<endl <<endl <<endl <<"Tax 5% Rs:" <<tax; zak=salary/100*5; cout <<endl <<endl <<"Zakat 5% -Rs:" <<zak; int net=(gross-tax-zak); cout <<endl <<endl <<"Net Income Rs:" <<net; getche(); }
// This program will walk through creating the NWA shown in Figure 4 of the // associated documentation, and reverse it (to get the result of Figure 12). // We then make a NestedWord of the one word in Figure 4's language and // another NestedWord of the one word in Figure 12's language, then test that // each is a member of just the appropriate NWA. #include <iostream> using std::cout; #include "wali/nwa/NWA.hpp" #include "wali/nwa/NestedWord.hpp" #include "wali/nwa/construct/reverse.hpp" #include "wali/nwa/query/language.hpp" using wali::getKey; using namespace wali::nwa; using wali::nwa::construct::reverse; using wali::nwa::query::languageContains; // These symbols are used in the NWA and both words Symbol const sym_a = getKey("a"); Symbol const sym_b = getKey("b"); Symbol const sym_call = getKey("call"); Symbol const sym_ret = getKey("ret"); /// Creates the NWA shown in Figure 4 of the Wali NWA documentation NWA create_figure_4() { NWA out; // Translate the names of the states then symbols to Wali identifiers State start = getKey("Start"); State call = getKey("Call"); State entry = getKey("Entry"); State state = getKey("State"); State exit = getKey("Exit"); State return_ = getKey("Return"); State finish = getKey("Finish"); // Add the transitions out.addInternalTrans(start, sym_a, call); out.addCallTrans(call, sym_call, entry); out.addInternalTrans(entry, sym_b, state); out.addInternalTrans(state, sym_b, exit); out.addReturnTrans(exit, call, sym_ret, return_); out.addInternalTrans(return_, sym_a, finish); // Set the initial and final states out.addInitialState(start); out.addFinalState(finish); return out; } /// Creates a (the one) word in the language of Figure 4's NWA NestedWord create_forwards_word() { NestedWord out; out.appendInternal(sym_a); out.appendCall(sym_call); out.appendInternal(sym_b); out.appendInternal(sym_b); out.appendReturn(sym_ret); out.appendInternal(sym_a); return out; } /// Creates a (the one) word in the language of the reverse of Figure 4's NWA NestedWord create_backwards_word() { ... } int main() { // Create the NWA and reversed NWA NWA fig4 = create_figure_4(); NWARefPtr fig4_reversed = reverse(fig4); // These are the words we are testing NestedWord forwards_word = create_forwards_word(); NestedWord backwards_word = create_backwards_word(); // Now do the tests cout << "fig4 contains:\n" << " forwards_word [expect 1] : " << languageContains(fig4, forwards_word) << "\n" << " backwards_word [expect 0] : " << languageContains(fig4, backwards_word) << "\n" << "fig4_reversed contains:\n" << " forwards_word [expect 0] : " << languageContains(*fig4_reversed, forwards_word) << "\n" << " backwards_word [expect 1] : " << languageContains(*fig4_reversed, backwards_word) << "\n"; }