text
stringlengths
8
6.88M
// Created on: 2022-05-11 // Copyright (c) 2022 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 _XCAFDoc_AssemblyGraph_HeaderFile #define _XCAFDoc_AssemblyGraph_HeaderFile #include <NCollection_DataMap.hxx> #include <NCollection_IndexedMap.hxx> #include <Standard.hxx> #include <Standard_Type.hxx> #include <TCollection_AsciiString.hxx> #include <TColStd_PackedMapOfInteger.hxx> #include <TDF_LabelIndexedMap.hxx> class TDF_Label; class TDocStd_Document; class XCAFDoc_ShapeTool; class XCAFDoc_AssemblyGraph; DEFINE_STANDARD_HANDLE(XCAFDoc_AssemblyGraph, Standard_Transient) // Assembly graph. class XCAFDoc_AssemblyGraph : public Standard_Transient { public: //! \brief Type of the graph node. enum NodeType { NodeType_UNDEFINED = 0, //!< Undefined node type. NodeType_AssemblyRoot, //!< Root node. NodeType_Subassembly, //!< Intermediate node. NodeType_Occurrence, //!< Assembly/part occurrence node. NodeType_Part, //!< Leaf node to represent parts. NodeType_Subshape //!< Subshape node. }; //! \brief Type definition for graph adjacency matrix. //! This is how parent-component links are realized in the assembly graph. typedef NCollection_DataMap<Standard_Integer, TColStd_PackedMapOfInteger> AdjacencyMap; public: //! \brief Graph iterator. class Iterator { public: //! \brief Accepting the assembly graph and starting node to iterate. //! Iteration starts from the specified node. //! \param [in] theGraph - assembly graph to iterate. //! \param [in] theNode - graph node ID. Standard_EXPORT Iterator(const Handle(XCAFDoc_AssemblyGraph)& theGraph, const Standard_Integer theNode = 1); //! Checks if there are more graph nodes to iterate. //! \return true/false. Standard_Boolean More() const { return myCurrentIndex <= myGraph->NbNodes(); } //! \return 1-based ID of the current node. Standard_Integer Current() const { return myCurrentIndex; } //! Moves iterator to the next position. void Next() { ++myCurrentIndex; } private: Handle(XCAFDoc_AssemblyGraph) myGraph; //!< Assembly graph to iterate. Standard_Integer myCurrentIndex; //!< Current 1-based node ID. }; public: //! \brief Constructs graph from XCAF document. //! Construction of a formal graph will be done immediately. //! \param [in] theDoc - document to iterate. Standard_EXPORT XCAFDoc_AssemblyGraph(const Handle(TDocStd_Document)& theDoc); //! \brief Constructs graph from XCAF label. //! Construction of a formal graph will be done immediately. The specified //! label is used as a starting position. //! \param [in] theDoc - document to iterate. //! \param [in] theLabel - starting position. Standard_EXPORT XCAFDoc_AssemblyGraph(const TDF_Label& theLabel); //! \return Document shape tool. const Handle(XCAFDoc_ShapeTool)& GetShapeTool() const { return myShapeTool; } //! \brief Returns IDs of the root nodes. //! \return IDs of the root nodes. const TColStd_PackedMapOfInteger& GetRoots() const { return myRoots; } //! \brief Checks whether the assembly graph contains (n1, n2) directed link. //! \param [in] theNode1 - one-based ID of the first node. //! \param [in] theNode2 - one-based ID of the second node. //! \return true/false. Standard_EXPORT Standard_Boolean IsDirectLink(const Standard_Integer theNode1, const Standard_Integer theNode2) const; //! \brief Checks whether direct children exist for the given node. //! \param [in] theNode - one-based node ID. //! \return true/false. Standard_Boolean HasChildren(const Standard_Integer theNode) const { return myAdjacencyMap.IsBound(theNode); } //! \brief Returns IDs of child nodes for the given node. //! \param [in] theNode - one-based node ID. //! \return set of child IDs. const TColStd_PackedMapOfInteger& GetChildren(const Standard_Integer theNode) const { return myAdjacencyMap(theNode); } //! \brief Returns the node type from \ref NodeType enum. //! \param [in] theNode - one-based node ID. //! \return node type. //! \sa NodeType Standard_EXPORT NodeType GetNodeType(const Standard_Integer theNode) const; //! \brief returns object ID by node ID. //! \param [in] theNode - one-based node ID. //! \return persistent ID. const TDF_Label& GetNode(const Standard_Integer theNode) const { return myNodes(theNode); } //! \brief Returns the unordered set of graph nodes. //! \return graph nodes. const TDF_LabelIndexedMap& GetNodes() const { return myNodes; } //! \brief Returns the number of graph nodes. //! \return number of graph nodes. Standard_Integer NbNodes() const { return myNodes.Extent(); } //! \brief Returns the collection of graph links in the form of adjacency matrix. //! \return graph links. const AdjacencyMap& GetLinks() const { return myAdjacencyMap; } //! \brief Returns the number of graph links. //! \return number of graph links. Standard_EXPORT Standard_Integer NbLinks() const; //! Returns quantity of part usage occurrences. //! \param [in] theNode - one-based part ID. //! \return usage occurrence quantity. Standard_EXPORT Standard_Integer NbOccurrences(const Standard_Integer theNode) const; private: //! Builds graph out of OCAF XDE structure. //! \param [in] theLabel - optional starting position. Standard_EXPORT void buildGraph(const TDF_Label& theLabel); //! Adds components for the given parent to the graph structure. //! \param [in] theParent - OCAF label of the parent object. //! \param [in] theParentId - ID of the already registered node representing //! the parent object in the assembly graph //! being populated. Standard_EXPORT void addComponents(const TDF_Label& theParent, const Standard_Integer theParentId); //! Adds node into the graph. //! \param [in] theLabel - label at insertion level. //! \param [in] theParentId - parent one-based node IDS. //! \return one-based internal ID of the node. Standard_EXPORT Standard_Integer addNode(const TDF_Label& theLabel, const Standard_Integer theParentId); private: Handle(XCAFDoc_ShapeTool) myShapeTool; //!< Document shape tool. TColStd_PackedMapOfInteger myRoots; //!< IDs of the root nodes. TDF_LabelIndexedMap myNodes; //!< Maps assembly/part entries to graph node IDs. AdjacencyMap myAdjacencyMap; //!< "Part-of" relations. NCollection_DataMap<Standard_Integer, NodeType> myNodeTypes; //!< Node types. NCollection_DataMap<Standard_Integer, Standard_Integer> myUsages; //!< Occurrences usage. }; #endif // _XCAFDoc_AssemblyGraph_HeaderFile
// // Created by Omer on 18/01/2018. // #include "Group.h" #include "exceptions.h" #include <cmath> namespace mtm{ Group::Group(const std::string &name, const std::string &clan, int children, int adults, int tools, int food, int morale) { if (name.empty()) throw GroupInvalidArgs(); if (adults == 0 && children == 0) throw GroupInvalidArgs(); if (adults < 0 || children < 0 || tools < 0 || food < 0) { throw GroupInvalidArgs(); } if (morale < 0 || morale > 100) throw GroupInvalidArgs(); this->name = name; this->clan = clan; this->children = children; this->adults = adults; this->tools = tools; this->food = food; this->morale = morale; } Group::Group(const std::string &name, int children, int adults) { if (name.empty()) throw GroupInvalidArgs(); if (adults == 0 && children == 0) throw GroupInvalidArgs(); if (adults < 0 || children < 0) throw GroupInvalidArgs(); this->name = name; this->clan = ""; this->children = children; this->adults = adults; this->tools = 4 * adults; this->food = 3 * adults + 2 * children; this->morale = 70; } Group::Group(const Group &other) = default; Group::~Group() = default; const std::string &Group::getName() const { return name; } int Group::getSize() const { return adults + children; } const std::string &Group::getClan() const { return clan; } void Group::changeClan(const std::string &new_clan) { if (clan == new_clan) return; double temp; if (clan.empty()) { if (new_clan.empty()) return; clan = new_clan; temp = morale + morale * 0.1; } else { clan = new_clan; temp = morale - morale * 0.1; } if (temp > 100) temp = 100.0; morale = (int) temp; } int Group::calcPower(const Group &rhs) const { return int(floor(((10 * rhs.adults + 3 * rhs.children) * (10 * rhs.tools + rhs.food) * (rhs.morale)) / 100)); } bool Group::operator<(const Group &rhs) const { int rhs_power, this_power; rhs_power = calcPower(rhs); this_power = calcPower(*this); if (this_power < rhs_power) { return true; } else if (this_power > rhs_power) { return false; } else { if (name < rhs.name) { return true; } else { return false; } } } bool Group::operator==(const Group &rhs) const { int rhs_power, this_power; rhs_power = calcPower(rhs); this_power = calcPower(*this); if ((rhs_power == this_power) && (rhs.name == name)) { return true; } else { return false; } } bool Group::operator!=(const Group &rhs) const { if (!(*this == rhs)) { return true; } else { return false; } } bool Group::operator>(const Group &rhs) const { if (!(*this < rhs) && (*this != rhs)) { return true; } else { return false; } } bool Group::operator>=(const Group &rhs) const { if ((*this > rhs) || (*this == rhs)) { return true; } else { return false; } } bool Group::operator<=(const Group &rhs) const { if ((*this < rhs) || (*this == rhs)) { return true; } else { return false; } } void Group::uniteClan(Group &destination, const std::string& new_name){ int total_adults = adults + destination.adults; int total_children = children + destination.children; int total_food = food + destination.food; int total_tools = tools + destination.tools; int morale = int( floor((((this->morale * (children + adults)) + (destination.morale * (destination.children + destination.adults))) / ((double) total_adults + (double) total_children)))); morale = morale >= 100 ? 100 : morale; tools = total_tools; children = total_children; food = total_food; adults = total_adults; this->name = new_name; this->morale = morale; destination.adults = 0; destination.children = 0; destination.food = 0; destination.tools = 0; destination.morale = 0; destination.name=""; destination.clan=""; } bool Group::unite(Group &other, int max_amount) { int total_people = children + adults + other.children + other.adults; if (this != &other && this->clan == other.clan && total_people <= max_amount && other.morale >= 70 && morale >= 70) { if (*this >= other) { uniteClan(other,(*this).name); } else { uniteClan(other, other.name); } return true; } else { return false; } } Group Group::divide(const std::string &name) { if (name.empty() == true) throw GroupInvalidArgs(); if (this->adults <= 1 && this->children <= 1) throw GroupCantDivide(); int new_children = int(floor(children / 2.0)); int new_adults = int(floor(adults / 2.0)); int new_tools = int(floor(tools / 2.0)); int new_food = int(floor(food / 2.0)); Group new_group(name, clan, new_children, new_adults, new_tools, new_food, morale); this->children = children - new_children; this->adults = adults - new_adults; this->food = food - new_food; this->tools = tools - new_tools; return new_group; } void Group::postFightUpdate(Group &lost, Group &won) { int lost_food = int(ceil((1.0 / 2.0) * (lost.food))); lost.adults -= int(ceil((1.0 / 3.0) * (lost.adults))); lost.children -= int(ceil((1.0 / 3.0) * (lost.children))); lost.food -= lost_food; lost.tools -= int(ceil((1.0 / 2.0) * (lost.tools))); lost.morale -= int(ceil((0.2) * (lost.morale))); if(lost.adults == 0 && lost.children==0){ lost.name = ""; lost.food=0; lost.tools=0; lost.morale=0; lost.clan=""; } won.adults -= int(floor((1.0 / 4.0) * (won.adults))); won.food += int(floor((1.0 / 2.0) * lost_food)); won.tools -= int(floor((1.0 / 4.0) * (won.tools))); won.morale += int(ceil((0.2) * (won.morale))); if (won.morale > 100) { won.morale = 100; } } FIGHT_RESULT Group::fight(Group &opponent) { if (opponent.name == name && opponent.clan == clan) { throw GroupCantFightWithItself(); } if ((adults == 0 && children == 0) || (opponent.children == 0 && opponent.adults == 0)) { throw GroupCantFightEmptyGroup(); } if (*this > opponent) { postFightUpdate(opponent, *this); return WON; } else if (*this == opponent) { return DRAW; } else { postFightUpdate(*this, opponent); return LOST; } } int Group::max(int a, int b) { return a > b ? a : b; } int Group::min(int a, int b) { return a < b ? a : b; } void Group::makeTrade(Group &group1, Group &group2, int average_trade) { int new_average; if (max(group1.food, group1.tools) < average_trade || max(group2.food, group2.tools) < average_trade) { new_average = min(max(group2.food, group2.tools), max(group1.food, group1.tools)); } else { new_average = average_trade; } if (group1.food > group1.tools) { group1.food -= new_average; group1.tools += new_average; group2.food += new_average; group2.tools -= new_average; } else { group1.tools -= new_average; group1.food += new_average; group2.tools += new_average; group2.food -= new_average; } } bool Group::trade(Group &other) { if (this == &other) { throw GroupCantTradeWithItself(); } if ((food == tools || other.tools == other.food) || (tools > food && other.tools > other.food) || (food > tools && other.food > other.tools)) { return false; } else { int group1_trade, group2_trade, average_trade; group1_trade = int(ceil(abs(tools - food) / 2.0)); group2_trade = int(ceil(abs(other.tools - other.food) / 2.0)); average_trade = int(ceil(abs(group1_trade + group2_trade) / 2.0)); makeTrade(*this, other, average_trade); } return true; } std::ostream &operator<<(std::ostream &os, const Group &group) { os << "Group's name: " << group.name << "\n" << "Group's clan: " << group.clan << "\n" << "Group's children: " << group.children << "\n" << "Group's adults: " << group.adults << "\n" << "Group's tools: " << group.tools << "\n"<< "Group's food: " << group.food <<"\n"<< "Group's morale: " << group.morale <<"\n"; return os; } }
// // Created by 钟奇龙 on 2019-05-06. // #include <iostream> #include <vector> #include <string> using namespace std; int minEditCost(string s1,string s2,int insertCost,int deleteCost,int replaceCost){ if(s1.size() == 0 || s2.size() == 0) return 0; vector<vector<int> > dp(s1.size()+1,vector<int> (s2.size()+1,0)); for(int i=1; i<=s1.size(); ++i){ dp[i][0] = deleteCost*i; } for(int j=1; j<=s2.size(); ++j){ dp[0][j] = insertCost*j; } for(int i=1; i<=s1.size(); ++i){ for (int j = 1; j <= s2.size(); ++j) { if(s1[i-1] == s2[j-1]){ dp[i][j] = dp[i-1][j-1]; }else{ dp[i][j] = dp[i-1][j-1] + replaceCost; } dp[i][j] = min(dp[i][j],dp[i-1][j] + deleteCost); dp[i][j] = min(dp[i][j],dp[i][j-1] + insertCost); } } return dp[s1.size()][s2.size()]; } int main(){ string s1 = "ab12cd3"; string s2 = "abcdf"; int insertCost = 5; int deleteCost = 3; int replaceCost = 2; cout<<minEditCost(s1,s2,insertCost,deleteCost,replaceCost)<<endl; return 0; }
#ifndef __SEVERTEXBUFFER_H__ #define __SEVERTEXBUFFER_H__ #include "SEVertex.h" #include <vector> template <class T> class SEVertexBuffer { public: const uint32_t &refCount; SEVertexBuffer() : v_(), r_(1), refCount(r_) {} ~SEVertexBuffer() {} SEVertex<T> &operator[](std::size_t i) { return v_[i]; } SEVertex<T> operator[](std::size_t i) const { return v_[i]; } void addRef() { ++r_; } void subRef() { --r_; } void append(SEVertex<T> v) { v_.push_back(v); } private: std::vector<SEVertex<T> > v_; uint32_t r_; }; #endif // __SEVERTEXBUFFER_H__
#pragma once #include <string> #include <sstream> namespace fusion { template <class CharType, class Traits = std::char_traits<CharType>, class Allocator = std::allocator<CharType>> class basic_stringbuilder { public: typedef std::basic_string<CharType, Traits, Allocator> string_type; template <typename T> basic_stringbuilder& operator<<(const T& t) { m_ss << t; return *this; } basic_stringbuilder& operator<<(const string_type& str) { m_ss << str; return *this; } string_type str() const { return m_ss.str(); } const CharType* c_str() const { return m_ss.str().c_str(); } operator string_type() const { return m_ss.str(); } private: std::basic_ostringstream<CharType, Traits, Allocator> m_ss; }; typedef basic_stringbuilder<char> stringbuilder; typedef basic_stringbuilder<wchar_t> wstringbuilder; } // namespace fusion
#include "vocab.h" vcb::vocab::vocab() { this->operator[](csys) = "Control System"; this->operator[](mnemoSchema) = "MnemoSchema"; this->operator[](log) = "Log"; this->operator[](plot) = "Plot"; this->operator[](main) = "Main"; this->operator[](lockers) = "Lockers"; this->operator[](recipe) = "Recipe"; this->operator[](systema) = "System"; this->operator[](sources) = "Sources"; this->operator[](gases) = "Gases"; this->operator[](valves) = "Valves"; this->operator[](pumps) = "Pumps"; this->operator[](opend) = "Open"; this->operator[](closed) = "Closed"; this->operator[](control) = "Control"; this->operator[](error) = "Error"; this->operator[](open_cmd) = "Open"; this->operator[](close_cmd) = "Close"; this->operator[](init_cmd) = "Init"; this->operator[](shutter) = "Shutter"; this->operator[](ETMOP) = "Open: exceeded timeout"; this->operator[](ETMCL) = "Close: exceeded timeout"; this->operator[](EBNOP) = "Open contact bouncing"; this->operator[](EBNCL) = "Closed contact bouncing"; this->operator[](ECMD) = "Invalid command"; this->operator[](ETMNC) = "Flow is out of range"; this->operator[](air) = "Air"; this->operator[](argon) = "Argon"; this->operator[](oxygen) = "Oxygen"; this->operator[](lnk) = "Link"; this->operator[](TMERR) = "Exceeded timeout"; this->operator[](CSERR) = "Checksum failure"; this->operator[](PRERR) = "Parser error"; this->operator[](freqHz) = "Freq Hz"; this->operator[](thickA) = "Thick A"; this->operator[](rateAs) = "Rate A/s"; this->operator[](tempC) = "Temp C"; this->operator[](tool) = "Tooling"; this->operator[](mat) = "Material"; this->operator[](out) = "Out"; this->operator[](in) = "In"; this->operator[](presMb) = "Pres mb"; this->operator[](ctrl1) = "Control1"; this->operator[](ctrl2) = "Control2"; this->operator[](middle) = "Middle"; this->operator[](ETMMD) = "Middle: exceeded timeout"; this->operator[](EBNMD) = "Middle contact bouncing"; this->operator[](SPERR) = "Setpoint doens't match"; this->operator[](RGERR) = "Value out of range"; this->operator[](NOLNK) = "No link"; this->operator[](WRERR) = "Write error"; this->operator[](full_speed) = "Full speed"; this->operator[] (start_cmd) = "Start"; this->operator[] (stop_cmd) = "Stop"; this->operator[] (ETMON) = "Enabling: exceeded timeout"; this->operator[] (ETMOF) = "Disabling: exceeded timeout"; this->operator[] (INERR) = "Device error"; this->operator[](set) = "Set"; this->operator[](reset) = "Reset"; this->operator[](DEVERR) = "Device error"; }; vcb::vocab& vcb::vocab::get() { /* static initialization order fiasco workaround */ static vocab* ans = new vocab(); return *ans; }
#pragma GCC optimize("Ofast") #include <algorithm> #include <bitset> #include <deque> #include <iostream> #include <iterator> #include <string> #include <map> #include <queue> #include <set> #include <stack> #include <vector> #include <unordered_map> #include <unordered_set> using namespace std; void abhisheknaiidu() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } // complexity ==> log(n) // int countSets(int n) { // int count = 0; // while(n) { // n = n & (n-1); // count++; // } // return count; // } int main(int argc, char* argv[]) { abhisheknaiidu(); // int n = 4; // int ans = 0; // for(int i=1; i<=n; i++) { // T.C => O(nlog(n)) // ans += countSets(i); // } // cout << ans << endl; // Better Approach 🔥 T C => O(log(N)) int n = 30; n++; int ans = n/2; int power2 = 2; while(power2 <= n) { // pair's consisting of 0 and 1. int totalPairs = n / power2; // counting 1's. ans += (totalPairs/2) * power2; // cout << (totalPairs/2) * power2 << endl; ans += (totalPairs & 1) ? (n % power2) : 0; power2 <<= 1; } cout << ans << endl; // or // Base case: Number of set bits in 0 and 1 are 0 and 1 respectively. // Now for every element i from the range [2, N], if i is even then it will have the same number of set bits as i / 2 // because to get the number i we just shift the number i / 2 by one. While shifting, the number of set bits does not change. // Similarly, if i is odd then it will have 1 additional set bit at 0th position than i – 1 which was even. // int cnt = 0; // To store the count of set // bits in every integer // vector<int> setBits(n + 1); // 0 has no set bit // setBits[0] = 0; // 1 has a single set bit // setBits[1] = 1; // For the rest of the elements // for (int i = 2; i <= n; i++) { // If current element i is even then // it has set bits equal to the count // of the set bits in i / 2 // if (i % 2 == 0) { // setBits[i] = setBits[i / 2]; // } // Else it has set bits equal to one // more than the previous element // else { // setBits[i] = setBits[i - 1] + 1; // } // } // Sum all the set bits // for (int i = 0; i <= n; i++) { // cnt = cnt + setBits[i]; // } return 0; }
#include"interact.h" vector <BREAKPOINTINFO> BreakList;//容器,存放CC断点的动态数组 vector <MEMORYPOINTINFO> MemoryList;//容器,存放内存断点的动态数组 BOOL First = TRUE; /*用来设置软件断点*/ BOOL SetSoftBreakPoint(DWORD PID, LPVOID Address, BOOL once) { BOOL ret = TRUE; HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, PID); BREAKPOINTINFO bpInfo = { Address }; bpInfo.once = once; ReadProcessMemory(hProcess, Address, &bpInfo.code, 1, NULL); WriteProcessMemory(hProcess, Address, "\xCC", 1, NULL); BreakList.push_back(bpInfo); CloseHandle(hProcess); return ret; } /*修改TF标志位为单步模式*/ BOOL SetTFFlag(HANDLE hThread) { BOOL ret = TRUE; // 获取线程环境块 CONTEXT ct = { 0 }; ct.ContextFlags = CONTEXT_CONTROL; GetThreadContext(hThread, &ct); // 将TF标志位设置为1,单步执行,TF位是EFLAGS寄存器中的第8位(从0开始) ct.EFlags |= 0x100; SetThreadContext(hThread, &ct); return ret; } /*单步步过*/ BOOL SetStepFlag(DEBUGPROCESSINFO ProcessInfo) { BOOL ret = TRUE; // 获取线程环境块 CONTEXT ct = { 0 }; ct.ContextFlags = CONTEXT_CONTROL; GetThreadContext(ProcessInfo.hThread, &ct); DWORD Address = ct.Eip; cs_insn* ins = nullptr; PCHAR buf[16] = { 0 }; ReadProcessMemory(ProcessInfo.hProcess, (LPVOID)Address, buf, 16, NULL);//必须先ReadProcessMemory到调试器中 cs_disasm(ProcessInfo.cs_handle, (uint8_t*)buf, (size_t)16, (uint64_t)Address, 0, &ins); if (!memcmp(ins->mnemonic, "call", 4) || !memcmp(ins->mnemonic, "rep", 3)) { SetSoftBreakPoint(ProcessInfo.PID, (LPVOID)(Address + ins->size), TRUE);//一次性软断 } else { SetTFFlag(ProcessInfo.hThread); } return ret; } /*移除CC断点*/ VOID RemoveSoftBreakPoint(DEBUGPROCESSINFO ProcessInfo,BOOL only,PVOID address) { if (only == TRUE)//修复单个断点 { for (int i = 0; i < BreakList.size(); i++) { if (BreakList[i].addr == address) { CONTEXT ct = { CONTEXT_CONTROL }; GetThreadContext(ProcessInfo.hThread,&ct); ct.Eip -= 1; SetThreadContext(ProcessInfo.hThread, &ct); WriteProcessMemory(ProcessInfo.hProcess, BreakList[i].addr,&(BreakList[i].code), 1, NULL); } } } else//修复所有断点 { for (int i = 0; i < BreakList.size(); i++) { WriteProcessMemory(ProcessInfo.hProcess, BreakList[i].addr, &(BreakList[i].code), 1, NULL); } } } /*恢复CC断点*/ VOID RecoverSoftBreakPoint(DEBUGPROCESSINFO ProcessInfo,BOOL only, PVOID address) { if (only == TRUE) { for (int i = 0; i < BreakList.size(); i++) { if (BreakList[i].addr == address) { CONTEXT ct = { CONTEXT_CONTROL }; GetThreadContext(ProcessInfo.hThread, &ct); ct.Eip -= 1; SetThreadContext(ProcessInfo.hThread, &ct); WriteProcessMemory(ProcessInfo.hProcess, BreakList[i].addr, "\xCC", 1, NULL); } } } else { for (int i = 0; i < BreakList.size(); i++) { CONTEXT cont = { 0 }; cont.ContextFlags = CONTEXT_CONTROL; GetThreadContext(ProcessInfo.hThread, &cont); if (cont.Eip == (DWORD)(BreakList[i].addr)) { break;//当断点是EIP时不需要恢复 } WriteProcessMemory(ProcessInfo.hProcess, BreakList[i].addr, "\xCC", 1, NULL); } } } /*清除断点*/ VOID clearBreakPoint(DEBUGPROCESSINFO ProcessInfo, PVOID address) { for (int i = 0; i < BreakList.size(); i++) { if (BreakList[i].addr == address) { WriteProcessMemory(ProcessInfo.hProcess, BreakList[i].addr, &(BreakList[i].code), 1, NULL);//修复后删除 BreakList.erase(BreakList.begin() + i); } } } /*删除一次性CC断点*/ BOOL DeleteSoftBreakPoint(DEBUGPROCESSINFO ProcessInfo) { BOOL ret = FALSE; for (int i = 0; i < BreakList.size(); i++) { if ((ProcessInfo.ExceptionAddress == BreakList[i].addr) && (BreakList[i].once == TRUE)) { RemoveSoftBreakPoint(ProcessInfo, TRUE, ProcessInfo.ExceptionAddress);//恢复OPCODE BreakList.erase(BreakList.begin() + i); ret = TRUE; } } return ret; } /*反汇编*/ BOOL Disassembly(DEBUGPROCESSINFO ProcessInfo, LPVOID Address, DWORD num) { BOOL ret = TRUE; cs_insn* ins = nullptr;//读取指令位置内存指针 PCHAR buff = new CHAR[num * 16](); RemoveSoftBreakPoint(ProcessInfo,FALSE,NULL);//清除CC DWORD dwWrite = 0; ReadProcessMemory(ProcessInfo.hProcess, (LPVOID)Address, buff, num * 16, &dwWrite);//不使用ReadProcessMemory函数可能造成反汇编失败 int nCount = cs_disasm(ProcessInfo.cs_handle, (uint8_t*)buff, num * 16, (uint64_t)Address, 0, &ins);//接收反汇编指令 for (DWORD i = 0; i < num; i++) { printf_s("%08X ---> ", (UINT)ins[i].address); int tmp = 0; while (ins[i].size) { printf_s("%02X", ins[i].bytes[tmp]);//循环打印机器码 tmp++; ins[i].size -= 1; } printf_s("\t%s %s\t", ins[i].mnemonic, ins[i].op_str); printf_s("\n"); } printf_s("\n"); cs_free(ins, nCount); free(buff); //恢复CC RecoverSoftBreakPoint(ProcessInfo, FALSE, NULL); return ret; } /*获取寄存器*/ BOOL GetRegister(HANDLE hThread) { BOOL ret = TRUE; CONTEXT ct = { 0 }; ct.ContextFlags = CONTEXT_ALL; GetThreadContext(hThread, &ct); printf_s("EAX = %08X\t", ct.Eax); printf_s("EBX = %08X\t", ct.Ebx); printf_s("ECX = %08X\t", ct.Ecx); printf_s("EDX = %08X\n", ct.Edx); printf_s("ESI = %08X\t", ct.Esi); printf_s("EDI = %08X\t", ct.Edi); printf_s("ESP = %08X\t", ct.Esp); printf_s("EBP = %08X\n", ct.Ebp); printf_s("\tEIP = %08X\t\t\t", ct.Eip); printf_s("EFLAGS = %08X\n", ct.EFlags); printf_s("CS = %04X ", ct.SegCs); printf_s("SS = %04X ", ct.SegSs); printf_s("DS = %04X ", ct.SegDs); printf_s("ES = %04X ", ct.SegEs); printf_s("FS = %04X ", ct.SegFs); printf_s("GS = %04X \n", ct.SegGs); return ret; } /*获取栈信息*/ BOOL GetStack(HANDLE hProcess, HANDLE hThread) { BOOL ret = TRUE; DWORD dwRead = 0; CONTEXT ct = { 0 }; ct.ContextFlags = CONTEXT_ALL; GetThreadContext(hThread, &ct); PDWORD buf[20] = { 0 }; ReadProcessMemory(hProcess, (LPVOID)ct.Esp, buf, 4 * 20, &dwRead); int tmp = 0; while (tmp < 20) { printf_s("[%08X]\t%08X\n", ct.Esp + tmp * 4, buf[tmp]); tmp++; } return ret; } /*获取内存数据*/ BOOL GetMemory(HANDLE hProcess, DWORD Address) { BOOL ret = TRUE; PDWORD buf[0x100] = { 0 }; DWORD dwWrite = 0; ReadProcessMemory(hProcess, (LPVOID)Address, buf, 0x100, &dwWrite); for (int tmp = 0; (tmp*4) < dwWrite; tmp++) { if ( (tmp * 4) % 0x10 == 0) { printf_s("\n[%08X]\t", Address + tmp*4);//0x10为首地址 } printf_s("%08X ", buf[tmp]);//单字节打印 } printf_s("\n"); return ret; } /*查看模块*/ VOID GetModules(DWORD PID) { HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, PID); if (hSnap == INVALID_HANDLE_VALUE) return ; MODULEENTRY32 me = { sizeof(MODULEENTRY32) }; if (!Module32First(hSnap, &me)) { CloseHandle(hSnap); return ; } BOOL ret = TRUE; while (ret) { printf_s("[%08X]\t",me.modBaseAddr); printf_s("[%s]\n", (PWCHAR)me.szExePath); ret = Module32Next(hSnap, &me); } } /*查看断点*/ VOID ViewBreakPoint(DEBUGPROCESSINFO ProcessInfo) { printf_s("CC断点列表:\n"); for (int i = 0; i < BreakList.size(); i++) { printf_s("[%d]\t%08X\n", i + 1 ,BreakList[i].addr); } CONTEXT ct = { 0 }; ct.ContextFlags = CONTEXT_ALL; GetThreadContext(ProcessInfo.hThread, &ct); printf_s("DR断点列表:\n"); //e0、r1、w3 printf_s("[*]\tDR0 = %08X\t", ct.Dr0);//16-17 DWORD flag = ct.Dr7 & 0x30000; if(ct.Dr0) { if (flag == 0x30000) { printf_s("W"); } else if (flag == 0) { printf_s("E"); } else { printf_s("R"); } } printf_s("\n[*]\tDR1 = %08X\t", ct.Dr1);//20-21 flag = ct.Dr7 & 0x300000; if (ct.Dr1) { if (flag == 0x300000) { printf_s("W"); } else if (flag == 0) { printf_s("E"); } else { printf_s("R"); } } printf_s("\n[*]\tDR2 = %08X\t", ct.Dr2);//24-25 flag = ct.Dr7 & 0x3000000; if (ct.Dr2) { if (flag == 0x3000000) { printf_s("W"); } else if (flag == 0) { printf_s("E"); } else { printf_s("R"); } } printf_s("\n[*]\tDR3 = %08X\t", ct.Dr3);//28-29 flag = ct.Dr7 & 0x30000000; if (ct.Dr3) { if (flag == 0x30000000) { printf_s("W"); } else if (flag == 0) { printf_s("E"); } else { printf_s("R"); } } printf_s("\n内存断点列表:\n"); for (int y = 0; y < MemoryList.size(); y++) { printf_s("[%d]\t%08X\t", y + 1, MemoryList[y].addr); if (MemoryList[y].dwNewProtect == PAGE_EXECUTE_WRITECOPY) { printf_s("R\n"); } else if (MemoryList[y].dwNewProtect == PAGE_EXECUTE_READ) { printf_s("W\n"); } else { printf_s("E\n"); } } } /*硬件断点*/ VOID SetHBreakPoint(HANDLE hThread, char* flag, DWORD len,DWORD Address) { DWORD type = 0,les = 0; if (flag)//类型 { if (!strcmp(flag, "r")) { type = 1;//01 } else if (!strcmp(flag, "w")) { type = 3;//11 } else if (!strcmp(flag, "e")) { type = 0;//00 } } if (len)//长度 { if (len == 1) { les = 0;//01 } else if (len == 2) { les = 1;//11 } else if (len == 4) { les = 3;//00 } } CONTEXT ct = {CONTEXT_DEBUG_REGISTERS}; if (type == 1 || type == 3)//读写断点需要内存对齐 { if (les == 1)//对齐粒度 { Address = (Address % 2) ? (Address - (Address % 2)) : Address; } if (les == 3) { Address = (Address % 4) ? (Address - (Address % 4)) : Address; } } GetThreadContext(hThread,&ct); if (Address) { //00:执行 01:写入 11:读写 //00:1字节 01:2字节 11:4字节 if ((ct.Dr7 & 0x1) == 0)//0、2、4、6 { //DR0空闲 ct.Dr0 = Address; ct.Dr7 |= 0x1; ct.Dr7 |= (les *0x40000);//18-19 ct.Dr7 |= (type * 0x10000);//16-17 } else if ((ct.Dr7 & 0x4) == 0) { //DR1空闲 ct.Dr1 = Address; ct.Dr7 |= 0x4; ct.Dr7 |= (les * 0x400000); ct.Dr7 |= (type * 0x100000); } else if ((ct.Dr7 & 0x10) == 0) { //DR2空闲 ct.Dr2 = Address; ct.Dr7 |= 0x10; ct.Dr7 |= (les * 0x4000000); ct.Dr7 |= (type * 0x1000000); } else if ((ct.Dr7 & 0x40) == 0) { //DR3空闲 ct.Dr3 = Address; ct.Dr7 |= 0x40; ct.Dr7 |= (les * 0x4000000); ct.Dr7 |= (type * 0x10000000); } else { printf_s("硬件断点已用完"); } } SetThreadContext(hThread, &ct); } /*命中后清除硬件断点*/ BOOL ClearHBreakPoint(DEBUGPROCESSINFO ProcessInfo) { //由于不是专业开发人员,这里不想实现过于复杂的清除与恢复,直接将硬件断点默认为一次性断点。命中即清除 BOOL ret = FALSE; CONTEXT ct = { CONTEXT_DEBUG_REGISTERS }; GetThreadContext(ProcessInfo.hThread, &ct); if ((DWORD)ProcessInfo.ExceptionAddress == ct.Dr0) { ct.Dr7 = ct.Dr7 & 0xFFFFFFFE;//11111111111111111111111111111110 ct.Dr0 = 0; ct.Dr6 = ct.Dr6 & 0xFFFFFFFE; ret = TRUE; } if ((DWORD)ProcessInfo.ExceptionAddress == ct.Dr1) { ct.Dr7 = ct.Dr7 & 0xFFFFFFFD;//11111111111111111111111111111101 ct.Dr1 = 0; ct.Dr6 = ct.Dr6 & 0xFFFFFFFD; ret = TRUE; } if ((DWORD)ProcessInfo.ExceptionAddress == ct.Dr2) { ct.Dr7 = ct.Dr7 & 0xFFFFFFEF;//11111111111111111111111111110111 ct.Dr2 = 0; ct.Dr6 = ct.Dr6 & 0xFFFFFFEF; ret = TRUE; } if ((DWORD)ProcessInfo.ExceptionAddress == ct.Dr3) { ct.Dr7 = ct.Dr7 & 0xFFFFFFDF;// 11111111111111111111111111011111 ct.Dr3 = 0; ct.Dr6 = ct.Dr6 & 0xFFFFFFDF; ret = TRUE; } SetThreadContext(ProcessInfo.hThread, &ct); return ret; } /*内存断点*/ VOID SetMemBreakPoint(HANDLE hProcess, char* flag, DWORD Address) { MEMORYPOINTINFO mbp = { 0 }; mbp.addr = Address & 0xFFFFF000; for (int i = 0; i < MemoryList.size(); i++) { if (mbp.addr == MemoryList[i].addr) { printf_s("目标内存页已存在内存断点\n"); return;//防止一页内存多个内存断点 } } if(!strcmp(flag, "r")) { mbp.dwNewProtect = PAGE_NOACCESS; //暂时用内存访问断点代替 } else if (!strcmp(flag, "w")) { mbp.dwNewProtect = PAGE_EXECUTE_READ; } else if (!strcmp(flag, "e")) { mbp.dwNewProtect = PAGE_READWRITE; } else { printf("不存在页面属性"); return; } if ( !VirtualProtectEx(hProcess, (LPVOID)mbp.addr, 0x1000, mbp.dwNewProtect, &mbp.dwOldProtect)) { printf_s("内存断点下达失败\n"); return; } MemoryList.push_back(mbp); } /*dump*/ VOID Dump() {} /*改变寄存器值*/ VOID ChengeRegValue(DEBUGPROCESSINFO ProcessInfo, char * flag, DWORD Value) { CONTEXT context = { CONTEXT_INTEGER }; GetThreadContext(ProcessInfo.hThread, &context); if (!strcmp(flag, "eax")) //eax { context.Eax = Value; } else if (!strcmp(flag, "ebx"))//ebx { context.Ebx = Value; } else if (!strcmp(flag, "ecx"))//ecx { context.Ecx = Value; } else if (!strcmp(flag, "edx"))//edx { context.Edx = Value; } else if (!strcmp(flag, "edi"))//edi { context.Edi = Value; } else if (!strcmp(flag, "esi"))//esi { context.Esi = Value; } SetThreadContext(ProcessInfo.hThread, &context); } /*改变内存值*/ VOID ChengeMemValue(DEBUGPROCESSINFO ProcessInfo, DWORD Address, DWORD Value) { SIZE_T writen = 0; WriteProcessMemory(ProcessInfo.hProcess, (LPVOID)Address, &Value, sizeof(DWORD), &writen); return; } /*用来交互输入*/ BOOL GetCommend(DEBUGPROCESSINFO ProcessInfo) { BOOL ret = TRUE; char input[MAX_PATH] = { 0 }; while (TRUE) { printf_s("\n>>"); scanf_s("%s", input, MAX_PATH); if (!strcmp(input, "g") || !strcmp(input, "go")) { //让程序跑起来 break;//break之后进行异常处理 } else if (!strcmp(input, "u")) { //反汇编 DWORD Address = 0, lines = 0; scanf_s("%x %d", &Address, &lines); Disassembly(ProcessInfo, (LPVOID)Address, lines); } else if (!strcmp(input, "r") || !strcmp(input, "reg")) { //查看寄存器 GetRegister(ProcessInfo.hThread); } else if (!strcmp(input, "k")) { //栈信息 GetStack(ProcessInfo.hProcess, ProcessInfo.hThread); } else if (!strcmp(input, "d") || !strcmp(input, "dd")) { DWORD Address = 0; scanf_s("%x", &Address); //查看内存 GetMemory(ProcessInfo.hProcess, Address); } else if (!strcmp(input, "lm")) { //查看模块 GetModules(ProcessInfo.PID); } else if (!strcmp(input, "bl")) { //查看断点 ViewBreakPoint(ProcessInfo); } else if (!strcmp(input, "bp")) { //下CC断点 DWORD Address = 0; scanf_s("%x", &Address, sizeof(DWORD)); SetSoftBreakPoint(ProcessInfo.PID, (LPVOID)Address, TRUE); } else if (!strcmp(input, "ba")) { //下硬件断点 DWORD Address = 0,len = 0; CHAR flag[MAX_PATH] = { 0 }; scanf_s("%s", flag, MAX_PATH); scanf_s("%d %x",&len,&Address); SetHBreakPoint(ProcessInfo.hThread, flag, len, Address); } else if (!strcmp(input, "bm")) { //下内存断点 DWORD Address = 0, len = 0; CHAR flag[MAX_PATH] = { 0 }; scanf_s("%s", flag, MAX_PATH); scanf_s("%x", &Address); SetMemBreakPoint(ProcessInfo.hProcess, flag,Address); } else if (!strcmp(input, "bc")) { //清除断点 DWORD Address = 0; scanf_s("%x", &Address); clearBreakPoint(ProcessInfo, (PVOID)Address); } else if (!strcmp(input, "t")) { //单步步入 SetTFFlag(ProcessInfo.hThread); break; } else if (!strcmp(input, "p")) { //单步步过 SetStepFlag(ProcessInfo); break; } else if (!strcmp(input, "er")) { //修改内存值.寄存器值 DWORD value = 0; CHAR flag[MAX_PATH] = { 0 }; scanf_s("%s", flag, MAX_PATH); scanf_s("%x",&value); ChengeRegValue(ProcessInfo, flag,value); } else if (!strcmp(input, "em")) { //修改内存值.寄存器值 DWORD address = 0,value = 0; scanf_s("%x %x", &address ,&value); ChengeMemValue(ProcessInfo, address, value); } else if (!strcmp(input, "asm")) { //修改汇编 /*通过 汇编引擎语句实现即可,如keystone引擎*/ break; } else if (!strcmp(input, "dump")) { //dump内存 //dump未决定是将展开后的PE重写回文件还是直接按内存粒度dump,暂未实现 Dump(); } else if (!strcmp(input, "h") || !strcmp(input, "help")) { //帮助 GetHelp(); } else { printf_s("!!!指令错误,重新输入\n"); } } return ret; } /*获取帮助*/ VOID GetHelp() { printf_s("[*]\tu\t反汇编代码\t格式:u address lines\n"); printf_s("[*]\tr [reg]\t查看寄存器\n"); printf_s("[*]\tk\t查看栈信息\n"); printf_s("[*]\td [dd]\t查看内存数据\t格式:d address\n"); printf_s("[*]\tlm\t查看已加载模块\n"); printf_s("[*]\tbl\t查看断点列表\n"); printf_s("[*]\tbp\t下CC断点\t格式:bp address\n"); printf_s("[*]\tba\t下硬件断点\t格式:ba authority size address\n"); printf_s("[*]\tbm\t下内存断点\t格式:bm address authority\n"); printf_s("[*]\tbc\t清除CC断点\t格式:bc address \n"); printf_s("[*]\tt\t单步步入\n"); printf_s("[*]\tp\t单步步过\n"); printf_s("[*]\ter\t修改寄存器的值\t格式:e eax value\n"); printf_s("[*]\tem\t修改内存的值\t格式:e address value\n"); printf_s("[*]\tasm\t修改反汇编\t格式:asm address command\n"); printf_s("[*]\tdump\tdump内存\t格式:dump address size\n"); } /*用来处理异常调试事件*/ BOOL ExceptionEvent(DEBUG_EVENT DebugEvent, csh cshandle) { BOOL ret = TRUE; //保存必要的调试进程信息,便于传参 DEBUGPROCESSINFO ProcessInfo = { cshandle }; ProcessInfo.PID = DebugEvent.dwProcessId; ProcessInfo.TID = DebugEvent.dwThreadId; ProcessInfo.hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, DebugEvent.dwProcessId); ProcessInfo.hThread = OpenThread(PROCESS_ALL_ACCESS, FALSE, DebugEvent.dwThreadId); ProcessInfo.ExceptionCode = DebugEvent.u.Exception.ExceptionRecord.ExceptionCode; ProcessInfo.ExceptionAddress = DebugEvent.u.Exception.ExceptionRecord.ExceptionAddress; //第一次CC断点由系统生成,用户直接跳过 if (First && ProcessInfo.ExceptionCode == EXCEPTION_BREAKPOINT) { ProcessInfo.ExceptionAddress = (char*)ProcessInfo.ExceptionAddress + 1; First = FALSE; return ret; } /***********************************/ /*异常分发流程,存在异常时系统会将异常信息发送给调试器,如果*/ /*不存在调试器,或者调试器未处理该异常,将异常交给SEH,VEH顶级异常*/ /*处理,在调用异常处理过程中未处理该异常,那么异常处理过程会返回进行第*/ /*二次异常分发,如果第二次还没有处理,分发给异常端口处理,csrss.exe监听*/ /***********************************/ switch (ProcessInfo.ExceptionCode) { //访问异常,内存断点相关VirtualProtect case EXCEPTION_ACCESS_VIOLATION: { DWORD64 MemAddress = (DWORD)(ProcessInfo.ExceptionAddress) & 0xFFFFF000;//内存页 DWORD64 MemAddress2 = DebugEvent.u.Exception.ExceptionRecord.ExceptionInformation[1] & 0xFFFFF000;//第二个数组元素指定不可访问数据的虚拟地址 for (int i = 0; i < MemoryList.size(); i++) { if (MemAddress == MemoryList[i].addr) { printf_s("内存断点--> %p\n", MemAddress); VirtualProtectEx(ProcessInfo.hProcess, (LPVOID)MemAddress, 0x1000, MemoryList[i].dwOldProtect, &MemoryList[i].dwNewProtect);//恢复访问 //暂时将内存断点和硬件断点均写为一次性断点 MemoryList.erase( MemoryList.begin() + i); } else if (MemAddress2 == MemoryList[i].addr) { printf_s("内存断点--> %p\n", MemAddress2); VirtualProtectEx(ProcessInfo.hProcess, (LPVOID)MemAddress2, 0x1000, MemoryList[i].dwOldProtect, &MemoryList[i].dwNewProtect);//恢复访问 //暂时将内存断点和硬件断点均写为一次性断点 MemoryList.erase(MemoryList.begin() + i); } } break; } //int3断点 case EXCEPTION_BREAKPOINT: { //一次性断点在命中后修复即删除 if (DeleteSoftBreakPoint(ProcessInfo)) { break; } //正常的INT 3断点 else { printf_s("命中硬件中断断点: %p\n", ProcessInfo.ExceptionAddress); RemoveSoftBreakPoint(ProcessInfo, TRUE, ProcessInfo.ExceptionAddress);//在反汇编函数里会统一进行修复 break; } } //单步,调试寄存器断点 case EXCEPTION_SINGLE_STEP: { if (ClearHBreakPoint(ProcessInfo))//拔出硬件断点 {//硬件断点 printf_s("命中硬件断点: %p\n", ProcessInfo.ExceptionAddress); } //单步无需处理 //步过会将CC当成一次性断点,也无需处理 break; } default: { printf_s("未处理异常类型(%08X): %p\n", ProcessInfo.ExceptionCode, ProcessInfo.ExceptionAddress); ret = FALSE; break; } } //反汇编 Disassembly(ProcessInfo, ProcessInfo.ExceptionAddress, 10);//反汇编当前异常地址 //交互输入 GetCommend(ProcessInfo); CloseHandle(ProcessInfo.hProcess); CloseHandle(ProcessInfo.hThread); return ret; }
#include <iostream> using namespace std; int main(){ int arr[10] = {3,1,4,2,4,9,2,6,5,3}; for (int &n : arr){ // 예를 들어서 6번째 n 이라면, int &n = arr[6] cout << n << ' '; n++; } cout << endl; for (int n : arr){ cout << n << ' '; } cout << endl; }
#pragma once #include "../../SDK/SDK.h" namespace Hooks { namespace WndProc { inline HWND hwWindow; inline WNDPROC Original; LONG __stdcall Func(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); void Init(); } }
#include "window.h" #include <iostream> // Static member delcarations Window* Window::self_ = nullptr; // Constructor Window::Window() : win_(nullptr), gl_context_(nullptr), width_(1920), height_(1080) { } // Destructor Window::~Window() { // Destory objects SDL_DestroyWindow( win_ ); // Cleanup pointers win_ = nullptr; gl_context_ = nullptr; self_ = nullptr; // Quit libraries SDL_Quit(); } Window* Window::get() { // Check if the window exists yet if( self_ == nullptr ) { // If the window does not yet exist, create it self_ = new Window(); bool success = self_->init(); // Check everything went OK if( success == false ) { delete self_; } } return self_; } bool Window::init() { bool success = true; /* INIT SDL */ if( SDL_Init( SDL_INIT_EVERYTHING ) < 0 ) { std::cout << "ERROR: Could not init SDL!" << std::endl; success = false; } win_ = SDL_CreateWindow( "Thomas Hope - Honours", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width_, height_, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN ); if( !win_ ) { std::cout << "ERROR: could not create window!" << std::endl; success = false; } /* INIT GL */ SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 4 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1 ); SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLEBUFFERS, 0 ); SDL_GL_SetAttribute( SDL_GL_MULTISAMPLESAMPLES, 0 ); gl_context_ = SDL_GL_CreateContext( win_ ); if( !gl_context_ ) { std::cout << "ERROR: could not create GL context!" << std::endl; success = false; } // Disable VSync SDL_GL_SetSwapInterval( 0 ); int vsync = SDL_GL_GetSwapInterval(); if( vsync != 0 ) { std::cout << "WARNING: vsync is enabled, the will likely throttle the Vive framerate!" << std::endl; } /* INIT GLEW */ glewExperimental = GL_TRUE; if( glewInit() != GLEW_OK ) { success = false; } /* INIT WINDOW SHADER */ window_shader_.loadVertexSourceFile("window_shader_vs.glsl"); window_shader_.loadFragmentSourceFile("window_shader_fs.glsl"); bool result = window_shader_.init(); if( !result ) { std::cout << "ERROR: failed to init window shader!" << std::endl; } /* CREATE WINDOW MESHS */ { GLfloat verts[] = { // Left side -1.0, -1.0f, 0, 0.0, 0.0, 0.0, -1.0, 0, 1.0, 0.0, -1.0, 1.0, 0, 0.0, 1.0, 0.0, 1.0, 0, 1.0, 1.0, // Right side 0.0, -1.0, 0, 0.0, 0.0, 1.0, -1.0, 0, 1.0, 0.0, 0.0, 1.0, 0, 0.0, 1.0, 1.0, 1.0, 0, 1.0, 1.0 }; GLushort indices[] = { 0, 1, 3, 0, 3, 2, 4, 5, 7, 4, 7, 6 }; glGenVertexArrays( 1, &vao_ ); glBindVertexArray( vao_ ); GLuint vbo; glGenBuffers( 1, &vbo ); glBindBuffer( GL_ARRAY_BUFFER, vao_ ); glBufferData( GL_ARRAY_BUFFER, sizeof( verts ), verts, GL_STATIC_DRAW ); GLuint ebo; glGenBuffers( 1, &ebo ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, ebo ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof( indices ), indices, GL_STATIC_DRAW ); GLint posAttrib = window_shader_.getAttribLocation( "vPosition" ); glEnableVertexAttribArray( posAttrib ); glVertexAttribPointer( posAttrib, 3, GL_FLOAT, GL_FALSE, 5 * sizeof( GLfloat ), 0 ); GLint uvAttrib = window_shader_.getAttribLocation( "vUV" ); glEnableVertexAttribArray( uvAttrib ); glVertexAttribPointer( uvAttrib, 2, GL_FLOAT, GL_FALSE, 5 * sizeof( GLfloat ), (void*)(3 * sizeof( GLfloat )) ); } return success; } void Window::render( GLuint left_eye_texture, GLuint right_eye_texture ) { glDisable( GL_DEPTH_TEST ); glBindFramebuffer( GL_FRAMEBUFFER, 0 ); glViewport( 0, 0, width_, height_ ); glClearColor( 0.0f, 0.5f, 0.0f, 1.0f ); glClear( GL_COLOR_BUFFER_BIT ); window_shader_.bind(); glBindVertexArray( vao_ ); glBindTexture( GL_TEXTURE_2D, left_eye_texture ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0 ); glBindTexture( GL_TEXTURE_2D, right_eye_texture ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glDrawElements( GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (const void *)(12) ); }
#include "StaticModelCollider.h" #include "MeshRenderer.h" #include "Object.h" #include "Mesh.h" #include <cmath> int triBoxOverlap(float boxcenter[3], float boxhalfsize[3], float triverts[3][3]); bool ColliderColumn::IsColliding(glm::vec3 _position, glm::vec3 _size) { for (std::vector<rend::CollitionFace>::iterator i = faces.begin(); i != faces.end(); i++) { float f[3][3] = { 0 }; f[0][0] = i->pa.x; f[0][1] = i->pa.y; f[0][2] = i->pa.z; f[1][0] = i->pb.x; f[1][1] = i->pb.y; f[1][2] = i->pb.z; f[2][0] = i->pc.x; f[2][1] = i->pc.y; f[2][2] = i->pc.z; float bc[3] = { 0 }; bc[0] = _position.x; bc[1] = _position.y; bc[2] = _position.z; float bhs[3] = { 0 }; bhs[0] = _size.x / 2.0f; bhs[1] = _size.y / 2.0f; bhs[2] = _size.z / 2.0f; if (triBoxOverlap(bc, bhs, f)) { return true; } } return false; } void ColliderColumn::GetColliding(glm::vec3 _position, glm::vec3 _size, std::vector<rend::CollitionFace>& _collisions) { for (std::vector<rend::CollitionFace>::iterator i = faces.begin(); i != faces.end(); i++) { float f[3][3] = { 0 }; f[0][0] = i->pa.x; f[0][1] = i->pa.y; f[0][2] = i->pa.z; f[1][0] = i->pb.x; f[1][1] = i->pb.y; f[1][2] = i->pb.z; f[2][0] = i->pc.x; f[2][1] = i->pc.y; f[2][2] = i->pc.z; float bc[3] = { 0 }; bc[0] = _position.x; bc[1] = _position.y; bc[2] = _position.z; float bhs[3] = { 0 }; bhs[0] = _size.x / 2.0f; bhs[1] = _size.y / 2.0f; bhs[2] = _size.z / 2.0f; if (triBoxOverlap(bc, bhs, f)) { _collisions.push_back(*i); } } } void StaticModelCollider::OnInit() { resolution = 5; tryStep = 0.01f; maxStep = 1.0f; tryInc = 0.01f; maxInc = 0.5f; std::sr1::shared_ptr<Mesh> model = GetObject()->GetComponent<MeshRenderer>()->GetMesh(); extentMin = model->GetExtent().min; extentMax = model->GetExtent().max; // Create collision columns glm::vec3 size = (extentMax - extentMin); glm::vec3 colSize = size / resolution; colSize.y = size.y; for (size_t y = 0; y < resolution; y++) { glm::vec3 pos = extentMin + colSize / 2.0f; pos.z += (float)y * colSize.z; for (size_t x = 0; x < resolution; x++) { std::sr1::shared_ptr<ColliderColumn> cc = std::sr1::make_shared<ColliderColumn>(); cc->size = colSize; // Overlap columns for sub column collision //cc->size.x += 1.0f; //cc->size.z += 1.0f; // Conflicts with x / y index generation when matching column to collide with. // Done when adding face instead. cc->position = pos; columns.push_back(cc); pos.x += colSize.x; } } for (size_t f = 0; f < model->GetFaces().size(); f++) { rend::CollitionFace face = model->GetFaces().at(f); AddFace(face); } } void StaticModelCollider::RegisterTriggerCallback(const std::function<void()>& _callback) { triggerCallbacks.push_back(_callback); } void StaticModelCollider::RegisterCollisionCallback(const std::function<void()>& _callback) { collisionCallbacks.push_back(_callback); } bool StaticModelCollider::IsColliding(rend::CollitionFace& _face, glm::vec3 _position, glm::vec3 _size) { float f[3][3] = { 0 }; f[0][0] = _face.pa.x; f[0][1] = _face.pa.y; f[0][2] = _face.pa.z; f[1][0] = _face.pb.x; f[1][1] = _face.pb.y; f[1][2] = _face.pb.z; f[2][0] = _face.pc.x; f[2][1] = _face.pc.y; f[2][2] = _face.pc.z; float bc[3] = { 0 }; bc[0] = _position.x; bc[1] = _position.y; bc[2] = _position.z; float bhs[3] = { 0 }; bhs[0] = _size.x / 2.0f; bhs[1] = _size.y / 2.0f; bhs[2] = _size.z / 2.0f; if (triBoxOverlap(bc, bhs, f)) { return true; } return false; } bool StaticModelCollider::IsColliding(glm::vec3 _position, glm::vec3 _size) { for (std::vector<rend::CollitionFace>::iterator i = collisions.begin(); i != collisions.end(); i++) { float f[3][3] = { 0 }; f[0][0] = i->pa.x; f[0][1] = i->pa.y; f[0][2] = i->pa.z; f[1][0] = i->pb.x; f[1][1] = i->pb.y; f[1][2] = i->pb.z; f[2][0] = i->pc.x; f[2][1] = i->pc.y; f[2][2] = i->pc.z; float bc[3] = { 0 }; bc[0] = _position.x; bc[1] = _position.y; bc[2] = _position.z; float bhs[3] = { 0 }; bhs[0] = _size.x / 2.0f; bhs[1] = _size.y / 2.0f; bhs[2] = _size.z / 2.0f; if (triBoxOverlap(bc, bhs, f)) { return true; } } return false; } void StaticModelCollider::GetColliding(glm::vec3 _position, glm::vec3 _size) { glm::vec3 pos = _position - extentMin; size_t x = (size_t)(pos.x / columns.at(0)->size.x); size_t y = (size_t)(pos.z / columns.at(0)->size.z); size_t idx = y * resolution + x; if (idx >= columns.size()) return; columns.at(idx)->GetColliding(_position, _size, collisions); } glm::vec3 StaticModelCollider::FaceNormal(rend::CollitionFace& face) { glm::vec3 N = glm::cross ( glm::vec3(face.pb) - glm::vec3(face.pc), glm::vec3(face.pa) - glm::vec3(face.pc) ); return glm::normalize(N); } bool StaticModelCollider::CheckForCollision(glm::vec3 _position, glm::vec3 _size) { glm::vec3 solve = _position; collisions.clear(); GetColliding(solve, _size); return IsColliding(solve, _size); } glm::vec3 StaticModelCollider::GetCollisionResponse(glm::vec3 _position, glm::vec3 _size, bool& _solved) { glm::vec3 solve = _position; _solved = false; if (trigger) { for (const auto &cb : triggerCallbacks) { cb(); } } for (const auto &cb : collisionCallbacks) { cb(); } // Favour Y faces first. for (std::vector<rend::CollitionFace>::iterator it = collisions.begin(); it != collisions.end(); it++) { if (!IsColliding(*it, solve, _size)) { continue; } glm::vec3 n = FaceNormal(*it); //std::cout << n.x << " " << n.y << " " << n.z << std::endl; if (n.y < fabs(n.x) + fabs(n.z)) continue; float amount = tryStep; while (true) { solve = solve + n * amount; if (!IsColliding(*it, solve, _size)) { break; } solve = solve - n * amount; amount += tryStep; if (amount > maxStep) { break; } } } if (!IsColliding(solve, _size)) { _solved = true; return solve; } float amount = tryInc; while (true) { glm::vec3 total; // Try to uncollide using face normals for (std::vector<rend::CollitionFace>::iterator it = collisions.begin(); it != collisions.end(); it++) { glm::vec3 n = FaceNormal(*it); total = total + n; solve = solve + n * amount; if (!IsColliding(solve, _size)) { _solved = true; return solve; } solve = solve - n * amount; } // Try to uncollide using averaged face normals total = glm::normalize(total); solve = solve + total * amount; if (!IsColliding(solve, _size)) { _solved = true; return solve; } solve = solve - total * amount; amount += tryInc; if (amount > maxInc) { break; } } _solved = false; return _position; } void StaticModelCollider::AddFace(rend::CollitionFace _face) { float f[3][3] = { 0 }; f[0][0] = _face.pa.x; f[0][1] = _face.pa.y; f[0][2] = _face.pa.z; f[1][0] = _face.pb.x; f[1][1] = _face.pb.y; f[1][2] = _face.pb.z; f[2][0] = _face.pc.x; f[2][1] = _face.pc.y; f[2][2] = _face.pc.z; bool found = false; for (size_t i = 0; i < columns.size(); i++) { float bc[3] = { 0 }; bc[0] = columns.at(i)->position.x; bc[1] = columns.at(i)->position.y; bc[2] = columns.at(i)->position.z; // Overlap columns for sub column collision glm::vec3 s = columns.at(i)->size; s.x += 1; s.z += 1; float bhs[3] = { 0 }; bhs[0] = s.x / 2.0f; bhs[1] = s.y / 2.0f; bhs[2] = s.z / 2.0f; if (triBoxOverlap(bc, bhs, f)) { columns.at(i)->faces.push_back(_face); //std::cout << "Pushing face into " << i << std::endl; found = true; } } if (!found) { /*std::cout << "Assertion failed: Face not in spacial partition" << std::endl; std::cout << f[0][0] << ", " << f[0][1] << ", " << f[0][2] << std::endl; std::cout << f[1][0] << ", " << f[1][1] << ", " << f[1][2] << std::endl; std::cout << f[2][0] << ", " << f[2][1] << ", " << f[2][2] << std::endl; std::cout << "Expect collision errors" << std::endl;*/ //throw Exception("Face not assigned spatial partition"); } }
/*============================================================================== Program: 3D Slicer Copyright (c) Kitware Inc. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This file was originally developed by Julien Finet, Kitware Inc. and was partially funded by Allen Institute ==============================================================================*/ // Splines Logic includes #include "vtkSlicerSplinesLogic.h" // MRML includes #include <vtkMRMLScene.h> #include <vtkMRMLSelectionNode.h> // VTK includes #include <vtkIntArray.h> #include <vtkNew.h> #include <vtkObjectFactory.h> // Splines includes #include "vtkMRMLMarkupsSplinesNode.h" // STD includes #include <cassert> //---------------------------------------------------------------------------- vtkStandardNewMacro(vtkSlicerSplinesLogic); //---------------------------------------------------------------------------- vtkSlicerSplinesLogic::vtkSlicerSplinesLogic() { } //---------------------------------------------------------------------------- vtkSlicerSplinesLogic::~vtkSlicerSplinesLogic() { } //---------------------------------------------------------------------------- void vtkSlicerSplinesLogic::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } //--------------------------------------------------------------------------- vtkMRMLSelectionNode* vtkSlicerSplinesLogic::GetSelectionNode() const { if (!this->GetMRMLScene()) { return NULL; } // try the application logic first vtkMRMLApplicationLogic *mrmlAppLogic = this->GetMRMLApplicationLogic(); return mrmlAppLogic ? (mrmlAppLogic->GetSelectionNode() ? mrmlAppLogic->GetSelectionNode() : NULL) : NULL; } //--------------------------------------------------------------------------- bool vtkSlicerSplinesLogic ::GetCentroid(vtkMRMLMarkupsSplinesNode* splinesNode, int n, double centroid[3]) { if (!splinesNode || !splinesNode->MarkupExists(n)) { return false; } int numberOfPoints = splinesNode->GetNumberOfPointsInNthMarkup(n); if (numberOfPoints <= 0) { return false; } centroid[0] = 0.0; centroid[1] = 0.0; centroid[2] = 0.0; for (int i = 0; i < numberOfPoints; ++i) { double point[4]; splinesNode->GetMarkupPointWorld(n, i, point); vtkMath::Add(point, centroid, centroid); } vtkMath::MultiplyScalar(centroid, 1.0/numberOfPoints); return true; } //--------------------------------------------------------------------------- void vtkSlicerSplinesLogic::ObserveMRMLScene() { if (!this->GetMRMLScene()) { return; } // add known markup types to the selection node vtkMRMLSelectionNode *selectionNode = vtkMRMLSelectionNode::SafeDownCast(this->GetSelectionNode()); if (selectionNode) { // got into batch process mode so that an update on the mouse mode tool // bar is triggered when leave it this->GetMRMLScene()->StartState(vtkMRMLScene::BatchProcessState); selectionNode->AddNewPlaceNodeClassNameToList( "vtkMRMLMarkupsSplinesNode", ":/Icons/SplinesMouseModePlace.png", "Splines"); // trigger an upate on the mouse mode toolbar this->GetMRMLScene()->EndState(vtkMRMLScene::BatchProcessState); } this->Superclass::ObserveMRMLScene(); } //----------------------------------------------------------------------------- void vtkSlicerSplinesLogic::RegisterNodes() { vtkMRMLScene* scene = this->GetMRMLScene(); assert(scene != 0); scene->RegisterNodeClass(vtkSmartPointer<vtkMRMLMarkupsSplinesNode>::New()); }
#include <iostream> #include <tuple> #include <sstream> #include <map> #include <functional> #include <cstdio> #include <string> #include <vector> #include <fstream> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include <boost/bimap.hpp> #include <boost/flyweight.hpp> #include <boost/signals2.hpp> using namespace std; using namespace boost; using namespace boost::signals2; struct Query { std::string creature_name; enum Argument { attack, defense } argument; int result; Query(std::string const& creature_name, Argument argument, int result) : creature_name(creature_name), argument(argument), result(result) {} }; struct Game { signal<void(Query&)> queries; }; struct Creature { Game &game; int attack, defense; std::string name; Creature(Game &game, int attack, int defense, std::string const& name) : game(game), attack(attack), defense(defense), name(name) {} int get_attack() const { Query q{name, Query::attack, attack}; game.queries(q); return q.result; } }; struct CreatureModifier { Game &game; Creature &creature; CreatureModifier(Game &game, Creature &creature) : game(game), creature(creature) {} virtual ~CreatureModifier() = default; }; struct DoubleAttackModifier : CreatureModifier { connection conn; DoubleAttackModifier(Game &game, Creature &creature) : CreatureModifier(game, creature) { conn = game.queries.connect([&](Query&q) { if (q.creature_name == creature.name and q.argument==Query::attack) q.result *= 2; }); } ~DoubleAttackModifier() { conn.disconnect(); } }; int main() { Game game; Creature goblin{game, 2,2, "strong goblin"}; cout << goblin.get_attack() << " " << goblin.defense << std::endl; { DoubleAttackModifier dam{game, goblin}; cout << goblin.get_attack() << " " << goblin.defense << std::endl; } cout << goblin.get_attack() << " " << goblin.defense << std::endl; return 0; }
#include "Camera.h" Camera::Camera() { posX = 0; posY = 0; } Camera::Camera(float posx, float posy) { posX = posx; posY = posy; } void Camera::adjust(float width, float height) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-width/2, width/2, height/2, -height/2, -2, 2); glGetFloatv(GL_PROJECTION_MATRIX, matrix); glMatrixMode(GL_MODELVIEW); } void Camera::use() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); glLoadMatrixf(matrix); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void Camera::apply() { glTranslated(-posX, posY, 0); }
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/ListMyCoupon.g.uno. // WARNING: Changes might be lost if you edit this file directly. #include <_root.app18_accessor_ListMyCoupon_Items.h> #include <_root.app18_accessor_ListMyCoupon_Selected.h> #include <_root.app18_accessor_ListMyCoupon_Title.h> #include <_root.app18_FuseControlsTextControl_Value_Property.h> #include <_root.app18_FuseReactiveEach_Items_Property.h> #include <_root.app18_FuseReactiveWhileCount_Items_Property.h> #include <_root.app18_FuseTriggersWhileString_Value_Property.h> #include <_root.H3.h> #include <_root.ListMyCoupon.h> #include <_root.ListMyCoupon.Template.h> #include <_root.ListMyCoupon.Template1.h> #include <Fuse.Controls.Rectangle.h> #include <Fuse.Controls.Shape.h> #include <Fuse.Controls.StackPanel.h> #include <Fuse.Controls.TextControl.h> #include <Fuse.Elements.Alignment.h> #include <Fuse.Elements.Element.h> #include <Fuse.Layer.h> #include <Fuse.NodeGroupBase.h> #include <Fuse.Reactive.BindingMode.h> #include <Fuse.Reactive.Constant.h> #include <Fuse.Reactive.ConstantExpression.h> #include <Fuse.Reactive.DataBinding.h> #include <Fuse.Reactive.Each.h> #include <Fuse.Reactive.IExpression.h> #include <Fuse.Reactive.Instantiator.h> #include <Fuse.Reactive.Property.h> #include <Fuse.Reactive.WhileCount.h> #include <Fuse.Reactive.WhileNotEmpty.h> #include <Fuse.Triggers.WhileString.h> #include <Fuse.Triggers.WhileStringTest.h> #include <Uno.Bool.h> #include <Uno.Float.h> #include <Uno.Float4.h> #include <Uno.Object.h> #include <Uno.String.h> #include <Uno.UX.Property.h> #include <Uno.UX.Property-1.h> #include <Uno.UX.PropertyAccessor.h> #include <Uno.UX.PropertyObject.h> #include <Uno.UX.Selector.h> #include <Uno.UX.Template.h> namespace g{ // public partial sealed class ListMyCoupon :2 // { // static ListMyCoupon() :172 static void ListMyCoupon__cctor_5_fn(uType* __type) { ::g::Uno::UX::Selector_typeof()->Init(); ListMyCoupon::__selector01_ = ::g::Uno::UX::Selector__op_Implicit(uString::Const("Items")); ListMyCoupon::__selector1_ = ::g::Uno::UX::Selector__op_Implicit(uString::Const("Value")); } static void ListMyCoupon_build(uType* type) { type->SetDependencies( ::g::app18_accessor_ListMyCoupon_Items_typeof(), ::g::app18_accessor_ListMyCoupon_Selected_typeof(), ::g::app18_accessor_ListMyCoupon_Title_typeof(), ::g::Uno::UX::Selector_typeof()); type->SetInterfaces( ::g::Uno::Collections::IList_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface0), ::g::Fuse::Scripting::IScriptObject_typeof(), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface1), ::g::Fuse::IProperties_typeof(), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface2), ::g::Fuse::INotifyUnrooted_typeof(), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface3), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface4), ::g::Uno::Collections::IEnumerable_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface5), ::g::Uno::Collections::IList_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface6), ::g::Uno::UX::IPropertyListener_typeof(), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface7), ::g::Fuse::ITemplateSource_typeof(), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface8), ::g::Uno::Collections::IEnumerable_typeof()->MakeType(::g::Fuse::Visual_typeof(), NULL), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface9), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface10), ::g::Uno::Collections::IEnumerable_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface11), ::g::Fuse::Triggers::Actions::IShow_typeof(), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface12), ::g::Fuse::Triggers::Actions::IHide_typeof(), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface13), ::g::Fuse::Triggers::Actions::ICollapse_typeof(), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface14), ::g::Fuse::IActualPlacement_typeof(), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface15), ::g::Fuse::Animations::IResize_typeof(), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface16), ::g::Fuse::Controls::Native::IScrollViewHost_typeof(), offsetof(::g::Fuse::Controls::ScrollViewBase_type, interface17)); type->SetFields(126, uObject_typeof(), offsetof(ListMyCoupon, _field_Items), 0, uObject_typeof(), offsetof(ListMyCoupon, _field_Selected), 0, ::g::Uno::String_typeof(), offsetof(ListMyCoupon, _field_Title), 0, ::g::Uno::UX::Property1_typeof()->MakeType(uObject_typeof(), NULL), offsetof(ListMyCoupon, temp_Items_inst), 0, ::g::Uno::UX::Property1_typeof()->MakeType(uObject_typeof(), NULL), offsetof(ListMyCoupon, temp1_Items_inst), 0, ::g::Uno::UX::Property1_typeof()->MakeType(::g::Uno::String_typeof(), NULL), offsetof(ListMyCoupon, temp2_Value_inst), 0, ::g::Uno::UX::Property1_typeof()->MakeType(::g::Uno::String_typeof(), NULL), offsetof(ListMyCoupon, temp3_Value_inst), 0, ::g::Uno::UX::Property1_typeof()->MakeType(uObject_typeof(), NULL), offsetof(ListMyCoupon, temp4_Items_inst), 0, ::g::Uno::UX::Selector_typeof(), (uintptr_t)&ListMyCoupon::__selector01_, uFieldFlagsStatic, ::g::Uno::UX::Selector_typeof(), (uintptr_t)&ListMyCoupon::__selector1_, uFieldFlagsStatic); } ::g::Fuse::Controls::ScrollViewBase_type* ListMyCoupon_typeof() { static uSStrong< ::g::Fuse::Controls::ScrollViewBase_type*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Fuse::Controls::ScrollView_typeof(); options.FieldCount = 136; options.InterfaceCount = 18; options.DependencyCount = 4; options.ObjectSize = sizeof(ListMyCoupon); options.TypeSize = sizeof(::g::Fuse::Controls::ScrollViewBase_type); type = (::g::Fuse::Controls::ScrollViewBase_type*)uClassType::New("ListMyCoupon", options); type->fp_build_ = ListMyCoupon_build; type->fp_ctor_ = (void*)ListMyCoupon__New5_fn; type->fp_cctor_ = ListMyCoupon__cctor_5_fn; type->interface17.fp_OnScrollPositionChanged = (void(*)(uObject*, ::g::Uno::Float2*))::g::Fuse::Controls::ScrollViewBase__FuseControlsNativeIScrollViewHostOnScrollPositionChanged_fn; type->interface12.fp_Show = (void(*)(uObject*))::g::Fuse::Elements::Element__FuseTriggersActionsIShowShow_fn; type->interface14.fp_Collapse = (void(*)(uObject*))::g::Fuse::Elements::Element__FuseTriggersActionsICollapseCollapse_fn; type->interface13.fp_Hide = (void(*)(uObject*))::g::Fuse::Elements::Element__FuseTriggersActionsIHideHide_fn; type->interface16.fp_SetSize = (void(*)(uObject*, ::g::Uno::Float2*))::g::Fuse::Elements::Element__FuseAnimationsIResizeSetSize_fn; type->interface15.fp_get_ActualSize = (void(*)(uObject*, ::g::Uno::Float3*))::g::Fuse::Elements::Element__FuseIActualPlacementget_ActualSize_fn; type->interface15.fp_add_Placed = (void(*)(uObject*, uDelegate*))::g::Fuse::Elements::Element__add_Placed_fn; type->interface15.fp_remove_Placed = (void(*)(uObject*, uDelegate*))::g::Fuse::Elements::Element__remove_Placed_fn; type->interface9.fp_GetEnumerator = (void(*)(uObject*, uObject**))::g::Fuse::Visual__UnoCollectionsIEnumerableFuseVisualGetEnumerator_fn; type->interface10.fp_Clear = (void(*)(uObject*))::g::Fuse::Visual__UnoCollectionsICollectionFuseNodeClear_fn; type->interface10.fp_Contains = (void(*)(uObject*, void*, bool*))::g::Fuse::Visual__UnoCollectionsICollectionFuseNodeContains_fn; type->interface6.fp_RemoveAt = (void(*)(uObject*, int*))::g::Fuse::Visual__UnoCollectionsIListFuseNodeRemoveAt_fn; type->interface11.fp_GetEnumerator = (void(*)(uObject*, uObject**))::g::Fuse::Visual__UnoCollectionsIEnumerableFuseNodeGetEnumerator_fn; type->interface10.fp_get_Count = (void(*)(uObject*, int*))::g::Fuse::Visual__UnoCollectionsICollectionFuseNodeget_Count_fn; type->interface6.fp_get_Item = (void(*)(uObject*, int*, uTRef))::g::Fuse::Visual__UnoCollectionsIListFuseNodeget_Item_fn; type->interface6.fp_Insert = (void(*)(uObject*, int*, void*))::g::Fuse::Visual__Insert1_fn; type->interface7.fp_OnPropertyChanged = (void(*)(uObject*, ::g::Uno::UX::PropertyObject*, ::g::Uno::UX::Selector*))::g::Fuse::Controls::Control__OnPropertyChanged2_fn; type->interface8.fp_FindTemplate = (void(*)(uObject*, uString*, ::g::Uno::UX::Template**))::g::Fuse::Visual__FindTemplate_fn; type->interface10.fp_Add = (void(*)(uObject*, void*))::g::Fuse::Visual__Add1_fn; type->interface10.fp_Remove = (void(*)(uObject*, void*, bool*))::g::Fuse::Visual__Remove1_fn; type->interface4.fp_Clear = (void(*)(uObject*))::g::Fuse::Node__UnoCollectionsICollectionFuseBindingClear_fn; type->interface4.fp_Contains = (void(*)(uObject*, void*, bool*))::g::Fuse::Node__UnoCollectionsICollectionFuseBindingContains_fn; type->interface0.fp_RemoveAt = (void(*)(uObject*, int*))::g::Fuse::Node__UnoCollectionsIListFuseBindingRemoveAt_fn; type->interface5.fp_GetEnumerator = (void(*)(uObject*, uObject**))::g::Fuse::Node__UnoCollectionsIEnumerableFuseBindingGetEnumerator_fn; type->interface1.fp_SetScriptObject = (void(*)(uObject*, uObject*, ::g::Fuse::Scripting::Context*))::g::Fuse::Node__FuseScriptingIScriptObjectSetScriptObject_fn; type->interface4.fp_get_Count = (void(*)(uObject*, int*))::g::Fuse::Node__UnoCollectionsICollectionFuseBindingget_Count_fn; type->interface0.fp_get_Item = (void(*)(uObject*, int*, uTRef))::g::Fuse::Node__UnoCollectionsIListFuseBindingget_Item_fn; type->interface1.fp_get_ScriptObject = (void(*)(uObject*, uObject**))::g::Fuse::Node__FuseScriptingIScriptObjectget_ScriptObject_fn; type->interface1.fp_get_ScriptContext = (void(*)(uObject*, ::g::Fuse::Scripting::Context**))::g::Fuse::Node__FuseScriptingIScriptObjectget_ScriptContext_fn; type->interface3.fp_add_Unrooted = (void(*)(uObject*, uDelegate*))::g::Fuse::Node__FuseINotifyUnrootedadd_Unrooted_fn; type->interface3.fp_remove_Unrooted = (void(*)(uObject*, uDelegate*))::g::Fuse::Node__FuseINotifyUnrootedremove_Unrooted_fn; type->interface0.fp_Insert = (void(*)(uObject*, int*, void*))::g::Fuse::Node__Insert_fn; type->interface2.fp_get_Properties = (void(*)(uObject*, ::g::Fuse::Properties**))::g::Fuse::Node__get_Properties_fn; type->interface4.fp_Add = (void(*)(uObject*, void*))::g::Fuse::Node__Add_fn; type->interface4.fp_Remove = (void(*)(uObject*, void*, bool*))::g::Fuse::Node__Remove_fn; return type; } // public ListMyCoupon() :176 void ListMyCoupon__ctor_8_fn(ListMyCoupon* __this) { __this->ctor_8(); } // private void InitializeUX() :180 void ListMyCoupon__InitializeUX1_fn(ListMyCoupon* __this) { __this->InitializeUX1(); } // public object get_Items() :8 void ListMyCoupon__get_Items_fn(ListMyCoupon* __this, uObject** __retval) { *__retval = __this->Items(); } // public void set_Items(object value) :9 void ListMyCoupon__set_Items_fn(ListMyCoupon* __this, uObject* value) { __this->Items(value); } // public ListMyCoupon New() :176 void ListMyCoupon__New5_fn(ListMyCoupon** __retval) { *__retval = ListMyCoupon::New5(); } // public object get_Selected() :23 void ListMyCoupon__get_Selected_fn(ListMyCoupon* __this, uObject** __retval) { *__retval = __this->Selected(); } // public void set_Selected(object value) :24 void ListMyCoupon__set_Selected_fn(ListMyCoupon* __this, uObject* value) { __this->Selected(value); } // public void SetItems(object value, Uno.UX.IPropertyListener origin) :11 void ListMyCoupon__SetItems_fn(ListMyCoupon* __this, uObject* value, uObject* origin) { __this->SetItems(value, origin); } // public void SetSelected(object value, Uno.UX.IPropertyListener origin) :26 void ListMyCoupon__SetSelected_fn(ListMyCoupon* __this, uObject* value, uObject* origin) { __this->SetSelected(value, origin); } // public void SetTitle(string value, Uno.UX.IPropertyListener origin) :41 void ListMyCoupon__SetTitle_fn(ListMyCoupon* __this, uString* value, uObject* origin) { __this->SetTitle(value, origin); } // public string get_Title() :38 void ListMyCoupon__get_Title_fn(ListMyCoupon* __this, uString** __retval) { *__retval = __this->Title(); } // public void set_Title(string value) :39 void ListMyCoupon__set_Title_fn(ListMyCoupon* __this, uString* value) { __this->Title(value); } ::g::Uno::UX::Selector ListMyCoupon::__selector01_; ::g::Uno::UX::Selector ListMyCoupon::__selector1_; // public ListMyCoupon() [instance] :176 void ListMyCoupon::ctor_8() { ctor_7(); InitializeUX1(); } // private void InitializeUX() [instance] :180 void ListMyCoupon::InitializeUX1() { ::g::Fuse::Reactive::Constant* temp5 = ::g::Fuse::Reactive::Constant::New1(this); ::g::Fuse::Reactive::Each* temp = ::g::Fuse::Reactive::Each::New4(); temp_Items_inst = ::g::app18_FuseReactiveEach_Items_Property::New1(temp, ListMyCoupon::__selector01_); ::g::Fuse::Reactive::Property* temp6 = ::g::Fuse::Reactive::Property::New1(temp5, ::g::app18_accessor_ListMyCoupon_Selected::Singleton_); ::g::Fuse::Reactive::Constant* temp7 = ::g::Fuse::Reactive::Constant::New1(this); ::g::Fuse::Reactive::WhileNotEmpty* temp1 = ::g::Fuse::Reactive::WhileNotEmpty::New3(); temp1_Items_inst = ::g::app18_FuseReactiveWhileCount_Items_Property::New1(temp1, ListMyCoupon::__selector01_); ::g::Fuse::Reactive::Property* temp8 = ::g::Fuse::Reactive::Property::New1(temp7, ::g::app18_accessor_ListMyCoupon_Selected::Singleton_); ::g::Fuse::Reactive::Constant* temp9 = ::g::Fuse::Reactive::Constant::New1(this); ::g::H3* temp2 = ::g::H3::New4(); temp2_Value_inst = ::g::app18_FuseControlsTextControl_Value_Property::New1(temp2, ListMyCoupon::__selector1_); ::g::Fuse::Reactive::Property* temp10 = ::g::Fuse::Reactive::Property::New1(temp9, ::g::app18_accessor_ListMyCoupon_Title::Singleton_); ::g::Fuse::Reactive::Constant* temp11 = ::g::Fuse::Reactive::Constant::New1(this); ::g::Fuse::Triggers::WhileString* temp3 = ::g::Fuse::Triggers::WhileString::New2(); temp3_Value_inst = ::g::app18_FuseTriggersWhileString_Value_Property::New1(temp3, ListMyCoupon::__selector1_); ::g::Fuse::Reactive::Property* temp12 = ::g::Fuse::Reactive::Property::New1(temp11, ::g::app18_accessor_ListMyCoupon_Title::Singleton_); ::g::Fuse::Reactive::Constant* temp13 = ::g::Fuse::Reactive::Constant::New1(this); ::g::Fuse::Reactive::Each* temp4 = ::g::Fuse::Reactive::Each::New4(); temp4_Items_inst = ::g::app18_FuseReactiveEach_Items_Property::New1(temp4, ListMyCoupon::__selector01_); ::g::Fuse::Reactive::Property* temp14 = ::g::Fuse::Reactive::Property::New1(temp13, ::g::app18_accessor_ListMyCoupon_Items::Singleton_); ::g::Fuse::Controls::StackPanel* temp15 = ::g::Fuse::Controls::StackPanel::New4(); ::g::Fuse::Controls::Rectangle* temp16 = ::g::Fuse::Controls::Rectangle::New3(); ListMyCoupon__Template* temp17 = ListMyCoupon__Template::New2(this, this); ::g::Fuse::Reactive::DataBinding* temp18 = ::g::Fuse::Reactive::DataBinding::New1(temp_Items_inst, (uObject*)temp6, 1); ::g::Fuse::Reactive::DataBinding* temp19 = ::g::Fuse::Reactive::DataBinding::New1(temp1_Items_inst, (uObject*)temp8, 1); ::g::Fuse::Reactive::DataBinding* temp20 = ::g::Fuse::Reactive::DataBinding::New1(temp2_Value_inst, (uObject*)temp10, 1); ::g::Fuse::Reactive::DataBinding* temp21 = ::g::Fuse::Reactive::DataBinding::New1(temp3_Value_inst, (uObject*)temp12, 1); ListMyCoupon__Template1* temp22 = ListMyCoupon__Template1::New2(this, this); ::g::Fuse::Reactive::DataBinding* temp23 = ::g::Fuse::Reactive::DataBinding::New1(temp4_Items_inst, (uObject*)temp14, 1); temp15->Margin(::g::Uno::Float4__New2(23.0f, 0.0f, 23.0f, 0.0f)); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp15->Children()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL)), temp1); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp15->Children()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL)), temp3); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp15->Children()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL)), temp4); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp1->Nodes()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL)), temp16); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp1->Nodes()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL)), temp); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp1->Bindings()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL)), temp19); temp16->CornerRadius(::g::Uno::Float4__New2(8.0f, 8.0f, 8.0f, 8.0f)); temp16->Color(::g::Uno::Float4__New2(0.9921569f, 0.9921569f, 0.9921569f, 1.0f)); temp16->Layer(1); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp->Templates()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Uno::UX::Template_typeof(), NULL)), temp17); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp->Bindings()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL)), temp18); temp3->Test(2); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp3->Nodes()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL)), temp2); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp3->Bindings()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL)), temp21); temp2->Alignment(1); temp2->Margin(::g::Uno::Float4__New2(0.0f, 25.0f, 0.0f, 0.0f)); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp2->Bindings()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL)), temp20); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp4->Templates()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Uno::UX::Template_typeof(), NULL)), temp22); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp4->Bindings()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Binding_typeof(), NULL)), temp23); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(Children()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::g::Fuse::Node_typeof(), NULL)), temp15); } // public object get_Items() [instance] :8 uObject* ListMyCoupon::Items() { return _field_Items; } // public void set_Items(object value) [instance] :9 void ListMyCoupon::Items(uObject* value) { SetItems(value, NULL); } // public object get_Selected() [instance] :23 uObject* ListMyCoupon::Selected() { return _field_Selected; } // public void set_Selected(object value) [instance] :24 void ListMyCoupon::Selected(uObject* value) { SetSelected(value, NULL); } // public void SetItems(object value, Uno.UX.IPropertyListener origin) [instance] :11 void ListMyCoupon::SetItems(uObject* value, uObject* origin) { if (value != _field_Items) { _field_Items = value; OnPropertyChanged1(::g::Uno::UX::Selector__op_Implicit(uString::Const("Items")), origin); } } // public void SetSelected(object value, Uno.UX.IPropertyListener origin) [instance] :26 void ListMyCoupon::SetSelected(uObject* value, uObject* origin) { if (value != _field_Selected) { _field_Selected = value; OnPropertyChanged1(::g::Uno::UX::Selector__op_Implicit(uString::Const("Selected")), origin); } } // public void SetTitle(string value, Uno.UX.IPropertyListener origin) [instance] :41 void ListMyCoupon::SetTitle(uString* value, uObject* origin) { if (::g::Uno::String::op_Inequality(value, _field_Title)) { _field_Title = value; OnPropertyChanged1(::g::Uno::UX::Selector__op_Implicit(uString::Const("Title")), origin); } } // public string get_Title() [instance] :38 uString* ListMyCoupon::Title() { return _field_Title; } // public void set_Title(string value) [instance] :39 void ListMyCoupon::Title(uString* value) { SetTitle(value, NULL); } // public ListMyCoupon New() [static] :176 ListMyCoupon* ListMyCoupon::New5() { ListMyCoupon* obj1 = (ListMyCoupon*)uNew(ListMyCoupon_typeof()); obj1->ctor_8(); return obj1; } // } } // ::g
//#include <string> #include <iostream> #include <fstream> #include <direct.h> #include <math.h> #include "VirtualMachine.h" using namespace std; struct mssv{ string test_dir; string lang_def; int population; int iterations; int generations; double threshold; double mutation; double combination; }; double stddev(double * nums,double mean,int count); double mean(double * nums,int count); void fill_file(string file); void next_generation(int gen, string * gen_path, string * prev_gen, double * performance,mssv vars); int main(int argc, char ** argv){ if(argc < 2){ cout <<"Usage: ./mss <config file>\n"; return -1; } //file checking ifstream cfg_stream(argv[1]); if(! cfg_stream.good()){ cout <<"could not open config file: " << argv[1] <<"\n"; return -2; } //---------load configuration--------- string lang_def, test_dir, game_diff, s_generations, s_iterations, s_population, s_threshold, s_mutation, s_combination; int generations, iterations, population; double threshold, mutation, combination; //lang_def cfg_stream >> lang_def; cfg_stream >> lang_def; //test_dir cfg_stream >> test_dir; cfg_stream >> test_dir; //game_diff cfg_stream >> game_diff; cfg_stream >> game_diff; //generations cfg_stream >> s_generations; cfg_stream >> s_generations; generations = atoi(s_generations.c_str()); //interations cfg_stream >> s_iterations; cfg_stream >> s_iterations; iterations = atoi(s_iterations.c_str()); //population cfg_stream >> s_population; cfg_stream >> s_population; population = atoi(s_population.c_str()); //threshold cfg_stream >> s_threshold; cfg_stream >> s_threshold; threshold=atof(s_threshold.c_str()); //mutation cfg_stream >> s_mutation; cfg_stream >> s_mutation; mutation = atof(s_mutation.c_str()); //combination cfg_stream >> s_combination; cfg_stream >> s_combination; combination = atof(s_combination.c_str()); mssv vars; vars.test_dir = test_dir; vars.lang_def = lang_def; vars.population = population; vars.iterations = iterations; vars.generations = generations; vars.threshold = threshold; vars.mutation = mutation; vars.combination = combination; cout <<"config file loaded\n"; cfg_stream.close(); //build test directory structure if(_mkdir(test_dir.c_str()) < 0){ cout <<"could not create test directory: " << test_dir <<"\n"; return -3; } cout <<"test dir: "<< test_dir << " created\n"; string cur_dir; string * dirs = new string[generations];//array to hold the directories char buf[32];//buffer for _itoa_s //create generation folders for(int i=0;i<generations;i++){ cur_dir = test_dir; cur_dir.append("\\"); cur_dir.append(test_dir); cur_dir.append("_gen_"); _itoa_s(i,buf,10); cur_dir.append(buf); if(_mkdir(cur_dir.c_str())<0){ cout <<"error filling test directory: "<<cur_dir<<"\n"; _rmdir(test_dir.c_str()); return -4; } dirs[i] = cur_dir; } cout <<"test dir filled\n"; //build sample population string target_file; string * population_files = new string[population];//array of program names for virtual machine for(int i = 0;i<population;i++){ target_file = dirs[0]; target_file.append("\\population_"); _itoa_s(i,buf,10); target_file.append(buf); target_file.append(".mss"); population_files[i] = target_file; //fill target file fill_file(target_file); } cout << "generation: " << 0 << " poplulated\n"; double * performance = new double[population]; //test sample populations for(int i=0;i<generations;i++){ VirtualMachine vm(lang_def,population_files,population,iterations,performance); /* for(int j =0;j<population;j++){ cout <<"average for prog: "<< j << " : " << performance[j] << " after " << iterations << " iterations\n"; } */ cout <<"Generation " << i << "completed\n"; next_generation(i,dirs,population_files,performance,vars); } } void fill_file(string file){ ofstream out(file.c_str()); if(! out.good()){ cout <<"error creating pop member: "<<file<<"\n"; exit(-6); } //------------random file creation-------------- //---------------------------------------------- out <<"#pick squares sequentially starting at 0,0\n"; out <<"int xpos=0\n"; out <<"int ypos=0\n"; out <<"while xpos<9\n"; out <<"while ypos<9\n"; out <<"picsq xpos,ypos\n"; out <<"update ypos=ypos+1\n"; out <<"ewhile\n"; out <<"update ypos=0\n"; out <<"update xpos=xpos+1\n"; out <<"ewhile\n"; //------------------------------------------------- //------------------------------------------------- out.close(); } double mean(double * nums, int count){ double sum=0; for(int i = 0;i<count;i++){ sum+=nums[i]; } return sum / count; } double stddev(double * nums,double mean,int count){ //standard deviation double sum=0; double mean_dev; //mean deviations sum = 0; for(int i = 0;i<count;i++){ mean_dev = nums[i] - mean; //mean squared deviations mean_dev = mean_dev * mean_dev; sum += mean_dev; } sum = sum / count; double std_dev = sqrt(sum); return std_dev; } void next_generation(int gen, string * gen_path,string * prev_gen, double * performance, mssv vars){ //------------statistics calculation------------------ //---------------------------------------------------- string stats_path = gen_path[gen]; stats_path.append("\\stats.txt"); ofstream stats_file(stats_path.c_str()); if(! stats_file.good()){ cout <<"error opening stats file\n"; exit(-7); } double mn = mean(performance,vars.population); double std_dev = stddev(performance,mn,vars.population ); stats_file << "Mean: " << mn << "\n"; stats_file << "Standard deviation: " << std_dev << "\n\n"; stats_file << "Population performance ( ** denotes selection)\n"; //loop through programs and select any that preformed above mean + (threshold * std_dev) for the next generation for(int i = 0 ;i<vars.population;i++){ stats_file << prev_gen[i] << ": " << performance[i] << " %"; if(performance[i] >= mn + (vars.threshold * std_dev)){ //select this program for further use //cout << prev_gen[i] << " better than " << vars.threshold << " std. dev. from the mean\n"; stats_file << " **"; } stats_file << "\n"; } }
class Solution { public: vector<int> inorderTraversal(TreeNode* root) { stack<TreeNode*> st; vector<int> tr; while(root != NULL || !st.empty()){ if(root != NULL){ st.push(root); root = root -> left; }else{ root = st.top(); tr.push_back(root -> val); st.pop(); root = root -> right; } } return tr; } };
#pragma once #include "light.h" class directional_light final : public light { public: directional_light(vector3 direction, ::color color, double intensity); auto direction_from(const vector3& hit_point) -> vector3 override; auto distance(const vector3& hit_point) -> double override; auto intensity(const vector3& hit_point) -> double override; private: vector3 _direction; };
#pragma once #include <string> #include "Node.h" #include "fontcpp/IconsFontAwesome5Pro.h" #include "fontcpp/IconsMaterialDesign.h" namespace studio { //icon check: http://www.wapadd.cn/icons/awesome/index.htm static std::string makeIconText(const char *icon, const char *join, const char *text) { char buf[80] = { 0 }; sprintf(buf, "%s%s%s", icon, join, text); return buf; } #ifdef _WIN32 #define NB_NEWLINE "\r\n" #else #define NB_NEWLINE "\n" #endif #define NB_ICON_TEXT(icon, text) makeIconText(icon, "\t", text).data() #define NB_ALIGN_TEXT(text) makeIconText("\t", "\t", text).data() #define NB_ICON(icon) makeIconText(icon, "", "").data() struct Datas { static bool ShowMainMenu; //属性主菜单 static bool ShowHierarchyWindow;//层级窗口 static bool ShowProjectWindow; //工程窗口 static bool ShowPreviewWindow; //预览窗口 static bool ShowPropertyWindow; //属性窗口 static bool ShowConsoleWindow; //控制台窗口 static bool ShowToolWindow; //新工程弹窗 static bool ShowNewProjectPop; //新工程弹窗 static NodePtr visualTreeData; }; }
#include "TestFramework.h" #include "treecore/RefCountObject.h" #include "treecore/RefCountHolder.h" using namespace treecore; class TestType: public RefCountObject { public: TestType(bool* marker): live_marker(marker) { *live_marker = true; } virtual ~TestType() { *live_marker = false; } bool* live_marker; }; typedef RefCountHolder<TestType> TestHolder; void TestFramework::content() { bool marker1 = false; TestType* obj1 = new TestType(&marker1); OK(obj1); OK(marker1); IS(obj1->get_ref_count(), obj1->ms_count); IS(obj1->ms_count, 0); obj1->ref(); IS(obj1->get_ref_count(), 1); { TestHolder holder1(obj1); IS(obj1->get_ref_count(), 2); TestHolder holder2(holder1); IS(obj1->get_ref_count(), 3); TestHolder holder3(obj1); IS(obj1->get_ref_count(), 4); } IS(obj1->get_ref_count(), 1); OK(marker1); obj1->unref(); OK(!marker1); }
#include <cstdio> int gcd(int numa, int numb); int lcm(int numa, int numb); int main() { int numa(0), numb(0), gcdNum =(1), lcmNum(1); printf("input two positive numbers: "); scanf("%d %d", &numa, &numb); if(numa <= 0 || numb <= 0){ printf("The numbers input is negative"); } gcdNum = gcd(numa, numb); lcmNum = lcm(numa, numb); printf("The gcm between %d and %d is: %d\n",numa, numb, gcdNum); printf("The lcm between %d and %d is: %d\n",numa, numb, lcmNum); } int gcd(int numa, int numb) { int tmp(0), q(0); if(numa < numb){ tmp = numa; numa = numb; numb = tmp; } while(numb != 0){ q = numa % numb; numa = numb; numb = q; } return numa; } int lcm(int numa, int numb) { return numa * numb / gcd(numa, numb); }
#include <stdio.h> #include <iostream> #include <random> using namespace std; bool TrialDivision(uint64_t n) { if (n<2) return false; if (n<4) return true; if ((n & 1) == 0) return false; for (uint64_t i = 3; i <= (uint64_t) sqrt(n); i+=2) if (n % i == 0) return false; return true; } uint64_t genPrime(unsigned int n, bool isPrime(uint64_t), unsigned int c) { uint64_t min = 1ULL<<(n-3); uint64_t max = (min << 2) + 2; uint64_t r; mt19937_64 gen(clock()); uniform_int_distribution<uint64_t> rnd(min,max); for (int i=0; i<c; i++) { do { r = rnd(gen); cout<<i+1<<") число:"<<r<<endl; } while (isPrime(r)); } return r; } int main(int argc, char **argv) { genPrime(1,TrialDivision,3); return 0; }
// Created on: 1992-09-28 // Created by: Remi GILET // 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 _GC_MakeTrimmedCone_HeaderFile #define _GC_MakeTrimmedCone_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <GC_Root.hxx> #include <Geom_RectangularTrimmedSurface.hxx> class gp_Pnt; //! Implements construction algorithms for a trimmed //! cone limited by two planes orthogonal to its axis. The //! result is a Geom_RectangularTrimmedSurface surface. //! A MakeTrimmedCone provides a framework for: //! - defining the construction of the trimmed cone, //! - implementing the construction algorithm, and //! - consulting the results. In particular, the Value //! function returns the constructed trimmed cone. class GC_MakeTrimmedCone : public GC_Root { public: DEFINE_STANDARD_ALLOC //! Make a RectangularTrimmedSurface <TheCone> from Geom //! It is trimmed by P3 and P4. //! Its axis is <P1P2> and the radius of its base is //! the distance between <P3> and <P1P2>. //! The distance between <P4> and <P1P2> is the radius of //! the section passing through <P4>. //! An error iss raised if <P1>,<P2>,<P3>,<P4> are //! colinear or if <P3P4> is perpendicular to <P1P2> or //! <P3P4> is colinear to <P1P2>. Standard_EXPORT GC_MakeTrimmedCone(const gp_Pnt& P1, const gp_Pnt& P2, const gp_Pnt& P3, const gp_Pnt& P4); //! Make a RectangularTrimmedSurface from Geom <TheCone> //! from a cone and trimmed by two points P1 and P2 and //! the two radius <R1> and <R2> of the sections passing //! through <P1> an <P2>. //! Warning //! If an error occurs (that is, when IsDone returns //! false), the Status function returns: //! - gce_ConfusedPoints if points P1 and P2, or P3 and P4, are coincident; //! - gce_NullAngle if: //! - the lines joining P1 to P2 and P3 to P4 are parallel, or //! - R1 and R2 are equal (i.e. their difference is less than gp::Resolution()); //! - gce_NullRadius if: //! - the line joining P1 to P2 is perpendicular to the line joining P3 to P4, or //! - the points P1, P2, P3 and P4 are collinear; //! - gce_NegativeRadius if R1 or R2 is negative; or //! - gce_NullAxis if points P1 and P2 are coincident (2nd syntax only). Standard_EXPORT GC_MakeTrimmedCone(const gp_Pnt& P1, const gp_Pnt& P2, const Standard_Real R1, const Standard_Real R2); //! Returns the constructed trimmed cone. //! StdFail_NotDone if no trimmed cone is constructed. Standard_EXPORT const Handle(Geom_RectangularTrimmedSurface)& Value() const; operator const Handle(Geom_RectangularTrimmedSurface)& () const { return Value(); } private: Handle(Geom_RectangularTrimmedSurface) TheCone; }; #endif // _GC_MakeTrimmedCone_HeaderFile
#pragma once #include "Geometry.h" class CollisionDetector { public: CollisionDetector(); ~CollisionDetector(); const static bool IsCollided(const Rect& rcA, const Rect& rcB); };
#include <iostream> #include <stack> #include <cstdio> #include<string> using namespace std; string choice; int turn; int main() { ios_base::sync_with_stdio(false); int t; string url; stack <string> f; stack <string> b; cin >> t; for (int cs = 1; cs <= t; cs++) { cin >> choice; while (!b.empty()) { b.pop(); } while (!f.empty()) { f.pop(); } url = "http://www.lightoj.com/"; cout << "Case " << cs << ":\n"; while (choice != "QUIT") { if (choice == "VISIT") turn = 0; else if (choice == "FORWARD") turn = 1; else if (choice == "BACK") turn = 2; switch (turn) { //vis for back case 0: b.push(url); cin >> url; cout << url << "\n"; while (!f.empty()) { f.pop(); } break; case 1: if (f.empty()) { cout << "Ignored\n"; } else { b.push(url); url = f.top(); f.pop(); cout << url << "\n"; } break; case 2: if (b.empty()) { cout << "Ignored\n"; } else { f.push(url); url = b.top(); b.pop(); cout << url << "\n"; } break; } cin >> choice; } } }
#include <iostream> using namespace std; void drawV(char * * & ary, char & symbol, int n, int m) { // fill ary = new char * [n]; for (int i = 0; i < n; ++i) { ary[i] = new char[n]; } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if ((i == j) || (j == m - i - 1)) { ary[i][j] = symbol; } else { ary[i][j] = ' '; } } } cout << "The dimensions of the array are " << n << "x" << m << "\n"; } void print(char * * & ary, int n, int m) { for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { std::cout << ary[i][j]; } cout << "\n"; } } void replace(char * * & ary, char symbol, char symbol2, int n, int m) { cout << "Input the other symbol: "; cin >> symbol2; cout << "The array with replaced symbols: \n"; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (ary[i][j] == symbol) { ary[i][j] = symbol2; } } } } void count(char * * & ary, int n, int m) { int counter = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (ary[i][j] != ' ') { counter++; } } } cout << "Number of symbols is: " << counter << "\n"; } int main() { char symbol = 0; char symbol2 = 0; int n = 0; cout << "Input the number rows please (no smaller than 3): "; cin >> n; if (n < 3) { cout << "Sorry,wrong input! "; } else { int m = 2 * n - 1; cout << "Input the symbol please: "; cin >> symbol; char * * ary; drawV(ary, symbol, n, m); print(ary, n, m); count(ary, n, m); replace(ary, symbol, symbol2, n, m); print(ary, n, m); for (int i = 0; i < n; ++i) { delete ary[i]; } delete[] ary; } return 0; }
#pragma once #include "renderer.h" #include "..\\renderer\color.h" #include "..\\resource\resource.h" #include "..\\core\name.h" class Font : public Resource { public: Font(Renderer* renderer) : renderer_(renderer) {} ~Font(); bool Create(const Name& font_name); void Destroy(); friend class Texture; protected: Renderer* renderer_; TTF_Font* font_ = nullptr; };
/* -*- 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. */ #ifndef MODULES_UTIL_OPFILE_OPSLOTFILE_H #define MODULES_UTIL_OPFILE_OPSLOTFILE_H #ifdef UTIL_HAVE_OP_SLOTFILE #include "modules/util/opfile/opfile.h" #include "modules/util/adt/opvector.h" #define SLOTFILE_USES_CRC /** Partitioned file access * * An instance of this class writes data into slots in a file, accessing only * those slots and thus reducing disk access. * * Manages two files: one info file containing header information * about slots, and one data file containing actual slots. * * Before slot file is used first time, you need to Init() it, which * clears the data and creates the info and data files. * * Slots are identified by an id string. They are kept in order, * specified by an index (0 <= idx < max_nr_slots). * * You add data into new slots by specifying a new id-string, and you * update data in existing slots by using the same id-string. Data * removal is also performed using id. * * You can extract data in order by iterating over indexes from 0 to * (GetSlotsCount() - GetNumFreeSlots() - 1), retrieving the id for * the given index and then using ReadSlotData for that id. */ class OpSlotFile { public: OpSlotFile(); virtual ~OpSlotFile(); /** * Always call Construct first, like on OpFile * * @param data_path path to data file * @param info_path path to index file * @param max_data_size maximum size of data file, can never be larger than * this. If -1, then no checking * @param folder a named folder or a special folder type * (OPFILE_ABSOLUTE_FOLDER or OPFILE_SERIALIZED_FOLDER). * @return See OpStatus. */ OP_STATUS Construct(const uni_char* data_path, const uni_char* info_path, INT32 max_data_size, OpFileFolder folder=OPFILE_ABSOLUTE_FOLDER); /** * Initialize the slot file and creates the file on disk, filling it with * zeros to ensure that there always is enough space for the file. * * Will overwrite existing files. * * @param slotsize The size of each slot * @param nrslots Number of slots in slotfile * @param idsize Size of each id-string. If -1, then any size is allowed. * @return See OpStatus. */ OP_STATUS Init(UINT32 slotsize, UINT32 nrslots, int idsize = -1); /** Open the file. * * Need to do this before any other methods that read/write data (except for init). * * @param read_only if set, file will be opened in read-only mode. * @return See OpStatus. */ OP_STATUS Open(BOOL read_only = FALSE); /** Close file and write changes to index. * * @note Do not set write_header to FALSE unless you are absolutely sure * that no changes were made to slotfile! * * @param write_header Defaults to TRUE, to write the header, unless the * file was only open read-only; if set to FALSE, then the header is not * written. * @return See OpStatus; OK if header was written successfully and file was * closed without errors */ OP_STATUS Close(BOOL write_header = TRUE); /** * Write changes to header file. */ OP_STATUS Flush(); /** * Delete index and data files. * * If you want to use the slotfile again after calling this, you need to call Init(). */ void Delete(); /** * Checks if a file exists. * * @return TRUE if any of the files exists */ BOOL Exists(); /** * Check that file and data in file is valid. * * Will use CRC if SLOTFILE_USES_CRC is defined * * @param nrslots the number of slots that the file is supposed to have * @param slotsize the size that each slot is supposed to have * @param idsize the size that each id-string is expected to have. If -1, * then no checking is done. * @return OpStatus::OK if file was found valid */ OP_STATUS CheckValidity(UINT32 nrslots, UINT32 slotsize, int idsize = -1); /** * Reads data for a slot * * @param id indentifier string of slot * @param buffer pointer to a buffer where to store data * @param buffer_size size of buffer * * @return OpStatus::OK if data was read successfully */ OP_STATUS ReadSlotData(const char* id, char* buffer, UINT32 buffer_size); /** * Writes data into a slot. * * If ID doesn't exist, a new slot will be allocated. If ID * exists, data will be written into existing slot, and the end of * the list. * * @param id identifier string of slot. * @param buffer pointer to buffer where data is stored * @param buffer_size size of data * * @return OpStatus::OK if data was written successfully */ OP_STATUS WriteSlotData(const char* id, char* buffer, UINT32 buffer_size); /** * Removes a slot and marks it as free. * * The slot order list will be "compacted" and otherwise keep its order * * \param id identifier string of slot. * \return OpStatus::OK if slot existed and was removed successfully */ OP_STATUS RemoveSlot(const char* id); /** * Remove data of slots that are corrupt. * * The slot order list will be "compacted" and otherwise keep its order * * @return See OpStatus; OK if there were no corrupt slots, or if all * corrupt slots were successfully removed. */ OP_STATUS RemoveCorruptSlots(); /** Move an entry to a place after another entry in the list * * @param id1 Identifier string for the entry to move. * @param id2 Identifier string for the entry to move id1 after; or NULL to * move id1 to first place in list. * * @return See OpStatus; OK if entry was successfully moved. */ OP_STATUS MoveEntryAfter(const char* id1, const char* id2); /** * Removes all slots that are not specified in the argument list * * @param id Vector of ids of slots still in use; these shall NOT be removed. * @return OpStatus::OK if slot existed and was removed successfully. */ OP_STATUS RemoveUnusedSlots(OpVector<OpString8>& id); /** The number of free slots in the file. */ int GetNumFreeSlots(); /** Size of slots in use by this file. */ UINT32 GetSlotSize() { return m_slotsize; } /** Total number of slots for this file (used + unused). */ int GetSlotsCount() { return m_max_nr_slots; } /** * Get id string for a given index * * @param index * @param buf buffer to copy id into * @param buf_size size of buf * * @return number of bytes copied into buf, 0 if no ID was found/copied */ int GetSlotId(int index, char * buf, int buf_size); private: /* Specifies the maximum number of slots that can be handled (used as a * sanity check when reading nr of slots from file and allocating buffers * from this) */ static const unsigned int MAX_NR_SLOTS = 10000; struct SlotOrder { OpString id; UINT32 slot_nr; UINT32 crc; UINT32 crcsize; }; enum SlotUsage { SLOT_USED = 0, SLOT_FREE }; const char* GetHeaderString() { return "OpSlotFile"; } static int GetVersion() { return 1; } BOOL IsSupportedVersion(int version) { return version == 1; } /** * Write header to index file */ OP_STATUS WriteHeader(UINT32 slotsize, int idsize); /** * Write dummy data to data file */ OP_STATUS WriteDummySlots(OpFile& data_file, UINT32 nr_slots, UINT32 slotsize); /** * Read header from index file */ OP_STATUS ReadHeader(); /** * Helper function for reading slot data. */ OP_STATUS ReadSlotData(UINT32 slot_no, char* buffer, UINT32 buffer_size); /** * Helper function for writing slot data. */ OP_STATUS WriteSlotData(UINT32 slot_no, char* buffer, UINT32 buffer_size); /** * Removes slot data for a slot by index * * @param index of slot to remove * * @return OpStatus::OK if slot existed and was removed successfully */ OP_STATUS RemoveSlot(int idx); /** * Helper function that move an entry according to indexes. * * @param idx_2 if -1, then move first */ OP_STATUS MoveEntryAfter(int idx_1, int idx_2); /** Returns index for a free slot, -1 if no free slot */ int GetFreeSlot(); /** * Find the index of a given id string * * @return index or -1 if not found */ int FindIndex(const char* id); /** * Clears the index table */ void EraseIndex(); /** * Deletes old index tables and creates new ones and sets max_nr_slots */ OP_STATUS RecreateIndex(int max_nr_slots); /** Check each slot against its CRC. * * Assumes that slotfile is open and header has been read. * * @param remove_corrupt Remove data of any corrupt slots found */ OP_STATUS CheckSlotsValidity(BOOL remove_corrupt); /** * Calculate CRC for data in buffer */ UINT32 CalculateCRC(char* buffer, int size); OpFile m_data_file; OpFile m_info_file; BOOL m_readonly; UINT32 m_version; UINT32 m_slotsize; int m_max_nr_slots; int m_idsize; INT32 m_max_data_size; OpFileLength m_slots_start; SlotUsage* m_slots_usage; SlotOrder** m_slot_order_table; BOOL m_header_loaded; }; #endif // UTIL_HAVE_OP_SLOTFILE #endif // MODULES_UTIL_OPFILE_OPSLOTFILE_H
/** @file ***************************************************************************** Declaration of arithmetic in the finite field F[((p^2)^3)^2]. ***************************************************************************** * @author This file is part of libsnark, developed by SCIPR Lab * and contributors (see AUTHORS). * @copyright MIT license (see LICENSE file) *****************************************************************************/ #ifndef FP48_2OVER2OVER2OVER3OVER2_HPP_ #define FP48_2OVER2OVER2OVER3OVER2_HPP_ #include "algebra/fields/fp.hpp" #include "algebra/fields/fp2.hpp" #include "algebra/fields/fp4.hpp" #include "algebra/fields/fp8.hpp" #include "algebra/fields/fp24_2over2over2over3.hpp" #include <vector> namespace libsnark { template<mp_size_t n, const bigint<n>& modulus> class Fp48_2over2over2over3over2_model; template<mp_size_t n, const bigint<n>& modulus> std::ostream& operator<<(std::ostream &, const Fp48_2over2over2over3over2_model<n, modulus> &); template<mp_size_t n, const bigint<n>& modulus> std::istream& operator>>(std::istream &, Fp48_2over2over2over3over2_model<n, modulus> &); /** * Arithmetic in the finite field F[((((p^2)^2)^2)^3)^2]. * * Let p := modulus. This interface provides arithmetic for the extension field * Fp48 = Fp24[S]/(S^2+Z) * * ASSUMPTION: p = 1 (mod 6) */ template<mp_size_t n, const bigint<n>& modulus> class Fp48_2over2over2over3over2_model { public: typedef Fp_model<n, modulus> my_Fp; typedef Fp2_model<n, modulus> my_Fp2; typedef Fp4_model<n, modulus> my_Fp4; typedef Fp8_model<n, modulus> my_Fp8; typedef Fp24_2over2over2over3_model<n, modulus> my_Fp24_2over2over2over3; static Fp24_2over2over2over3_model<n, modulus> non_residue; static Fp24_2over2over2over3_model<n, modulus> Frobenius_coeffs_c1[48]; // non_residue^((modulus^i-1)/48) for i=0,...,47 my_Fp24_2over2over2over3 c0, c1; Fp48_2over2over2over3over2_model() {}; Fp48_2over2over2over3over2_model(const my_Fp24_2over2over2over3& c0, const my_Fp24_2over2over2over3& c1) : c0(c0), c1(c1) {}; void clear() { c0.clear(); c1.clear(); } void print() const { printf("c0/c1:\n"); c0.print(); c1.print(); } static Fp48_2over2over2over3over2_model<n, modulus> zero(); static Fp48_2over2over2over3over2_model<n, modulus> one(); static Fp48_2over2over2over3over2_model<n, modulus> random_element(); bool is_zero() const { return c0.is_zero() && c1.is_zero(); } bool operator==(const Fp48_2over2over2over3over2_model &other) const; bool operator!=(const Fp48_2over2over2over3over2_model &other) const; Fp48_2over2over2over3over2_model operator+(const Fp48_2over2over2over3over2_model &other) const; Fp48_2over2over2over3over2_model operator-(const Fp48_2over2over2over3over2_model &other) const; Fp48_2over2over2over3over2_model operator*(const Fp48_2over2over2over3over2_model &other) const; Fp48_2over2over2over3over2_model operator-() const; Fp48_2over2over2over3over2_model squared() const; // default is squared_complex Fp48_2over2over2over3over2_model squared_karatsuba() const; Fp48_2over2over2over3over2_model squared_complex() const; Fp48_2over2over2over3over2_model inverse() const; Fp48_2over2over2over3over2_model Frobenius_map(unsigned long power) const; Fp48_2over2over2over3over2_model unitary_inverse() const; //Fp48_2over2over2over3over2_model cyclotomic_squared() const; static my_Fp24_2over2over2over3 mul_by_non_residue(const my_Fp24_2over2over2over3 &elt); //template<mp_size_t m> //Fp48_2over2over2over3over2_model cyclotomic_exp(const bigint<m> &exponent) const; static bigint<n> base_field_char() { return modulus; } static size_t extension_degree() { return 48; } friend std::ostream& operator<< <n, modulus>(std::ostream &out, const Fp48_2over2over2over3over2_model<n, modulus> &el); friend std::istream& operator>> <n, modulus>(std::istream &in, Fp48_2over2over2over3over2_model<n, modulus> &el); }; template<mp_size_t n, const bigint<n>& modulus> std::ostream& operator<<(std::ostream& out, const std::vector<Fp48_2over2over2over3over2_model<n, modulus> > &v); template<mp_size_t n, const bigint<n>& modulus> std::istream& operator>>(std::istream& in, std::vector<Fp48_2over2over2over3over2_model<n, modulus> > &v); template<mp_size_t n, const bigint<n>& modulus> Fp48_2over2over2over3over2_model<n, modulus> operator*(const Fp_model<n, modulus> &lhs, const Fp48_2over2over2over3over2_model<n, modulus> &rhs); template<mp_size_t n, const bigint<n>& modulus> Fp48_2over2over2over3over2_model<n, modulus> operator*(const Fp2_model<n, modulus> &lhs, const Fp48_2over2over2over3over2_model<n, modulus> &rhs); template<mp_size_t n, const bigint<n>& modulus> Fp48_2over2over2over3over2_model<n, modulus> operator*(const Fp4_model<n, modulus> &lhs, const Fp48_2over2over2over3over2_model<n, modulus> &rhs); template<mp_size_t n, const bigint<n>& modulus> Fp48_2over2over2over3over2_model<n, modulus> operator*(const Fp8_model<n, modulus> &lhs, const Fp48_2over2over2over3over2_model<n, modulus> &rhs); template<mp_size_t n, const bigint<n>& modulus> Fp48_2over2over2over3over2_model<n, modulus> operator*(const Fp24_2over2over2over3_model<n, modulus> &lhs, const Fp48_2over2over2over3over2_model<n, modulus> &rhs); template<mp_size_t n, const bigint<n>& modulus, mp_size_t m> Fp48_2over2over2over3over2_model<n, modulus> operator^(const Fp48_2over2over2over3over2_model<n, modulus> &self, const bigint<m> &exponent); template<mp_size_t n, const bigint<n>& modulus, mp_size_t m, const bigint<m>& exp_modulus> Fp48_2over2over2over3over2_model<n, modulus> operator^(const Fp48_2over2over2over3over2_model<n, modulus> &self, const Fp_model<m, exp_modulus> &exponent); template<mp_size_t n, const bigint<n>& modulus> Fp24_2over2over2over3_model<n, modulus> Fp48_2over2over2over3over2_model<n, modulus>::non_residue; template<mp_size_t n, const bigint<n>& modulus> Fp24_2over2over2over3_model<n, modulus> Fp48_2over2over2over3over2_model<n, modulus>::Frobenius_coeffs_c1[48]; } // libsnark #include "algebra/fields/fp48_2over2over2over3over2.tcc" #endif // FP48_2OVER2OVER2OVER3OVER2_HPP_
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef SKINANIMHANDLER_H #define SKINANIMHANDLER_H #ifdef ANIMATED_SKIN_SUPPORT #include "modules/hardcore/timer/optimer.h" #include "modules/util/simset.h" #include "modules/skin/OpSkinElement.h" /** Handles animation of skin images */ class OpSkinAnimationHandler : public Link, public MessageObject { private: OpSkinAnimationHandler(); public: ~OpSkinAnimationHandler(); static OpSkinAnimationHandler* GetImageAnimationHandler(OpSkinElement::StateElement* element, VisualDevice *vd, SkinPart image_id); OP_STATUS AddListener(OpSkinElement::StateElementRef* elmref); void IncRef(); void DecRef(OpSkinElement::StateElement* elm, VisualDevice *vd, SkinPart image_id); void OnPortionDecoded(OpSkinElement::StateElement* elm); void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2); INT32 GetRefCount() { return m_ref_count; } private: void AnimateToNext(); OpSkinElement::StateElement* m_element; SkinPart m_image_id; VisualDevice *m_vd; Head m_elm_list; BOOL m_posted_message; BOOL m_init_called; BOOL m_waiting_for_next_frame; INT32 m_ref_count; }; #endif // ANIMATED_SKIN_SUPPORT #endif // SKINANIMHANDLER_H
#include <iostream> using namespace std; int main() { int x; int y; int summa; int starpiba; int reizinajums; int mod; double dalijums; int z; x = 1; y = 2; z = 3; summa = 2x + 3y + z; starpiba = x - y; reizinajums = x * y; mod = x % y; dalijums = x / (double) y; cout << "Skaitla " << x << " un " << y << " summa ir " << summa << endl; cout << "Skaitla " << x << " un " << y << " starpiba ir " << starpiba << endl; cout << "Skaitla " << x << " un " << y << " reizinajums ir " << reizinajums << endl; cout << "Skaitla " << x << " un " << y << " dalijums ir " << dalijums << endl; cout << "Skaitla " << x << " un " << y << " mod ir " << mod << endl; cout << "Skaitla " << x << " un " << y << " un " << z << " summa ir " << summa << endl; cout << "Alise Riekstina" << endl; return 0; }
#include <iostream> using namespace std; void sorting(){ cout<<"helo"; } int main(int argc, char const *argv[]) { char arr[]={'a','s'}; std::cout << int(arr[1]-97) << '\n'; for (int i= 0; i < sizeof(arr); i++) { cout<<arr[i]; } return 0; }
#pragma once #include "rna/primitives.h" namespace rna { // inline Scalar distance(Vec3 a, Vec3 b) { return glm::distance(a, b); } } // namespace rna
#include "detailedrecordtable.h" #include "ui_detailedrecordtable.h" using namespace cv; using namespace std; DetailedRecordTable::DetailedRecordTable(QWidget *parent) : QDialog(parent), ui(new Ui::DetailedRecordTable) { ui->setupUi(this); camera_ = NULL; // por ahroa deshabilito los dibujos de alertas ui->show_alerts->setEnabled(false); } DetailedRecordTable::~DetailedRecordTable(){ delete ui; } void paintRectByIndex(int index,Scalar color, Mat& img){ // pintar una rectangulo de 6*10 en la imagen int col = index%60; int row = index/60; int x = col*6; int y = (row*12)+1; rectangle(img,Rect(x,y,6,10),color,-1); } void DetailedRecordTable::addVideos(Camera* camera, QDate date, std::vector<RecordVideo> videos,bool dark){ camera_ = camera; date_ = date; videos_ = videos; ui->camera_label->setText("Cámara: " + camera->name_); ui->date_label->setText("Fecha: "+date.toString("dd:MM:yy")); // crear una matriz de tama;o 360*288 y pintarla de gris Mat img(288,360,CV_8UC3); Scalar background_color = Scalar(200,200,200); if(dark){ background_color = Scalar(80,80,80); img = Scalar(50,50,50); }else{ img = Scalar(235,235,235); } for(int i=0;i<60*24;i++) paintRectByIndex(i,background_color,img); // pintarle los intervalos de los videos for(uint i = 0 ;i< videos_.size();i++){ Scalar color; if(i%2==0) color = Scalar(255,115,115); else color = Scalar(80,170,105); RecordVideo rvideo = videos_[i]; QDate cur_init_date = QDateTime::fromMSecsSinceEpoch(rvideo.init_time).date(); QDate cur_end_date = QDateTime::fromMSecsSinceEpoch(rvideo.end_time).date(); if(cur_init_date != date) // cambiar el intervalo para que comience en 00:00:00 rvideo.init_time = QDateTime(date,QTime(0,0,0)).toMSecsSinceEpoch(); if(cur_end_date != date) // cambiar el intervalo para que termine en 23:59:59 rvideo.end_time = QDateTime(date,QTime(23,59,59)).toMSecsSinceEpoch(); // obtener los indices inicial y final, usando los minutos totales QTime init_time = QDateTime::fromMSecsSinceEpoch(rvideo.init_time).time(); QTime end_time = QDateTime::fromMSecsSinceEpoch(rvideo.end_time).time(); int init_index = init_time.hour()*60+init_time.minute(); int end_index = end_time.hour()*60+end_time.minute(); for(int j=init_index;j<=end_index;j++) paintRectByIndex(j,color,img); } // asignar la imagen a ui->videos_image const uchar *qImageBuffer = (const uchar*)img.data; QImage* qimg = new QImage(qImageBuffer, img.cols, img.rows, img.step, QImage::Format_RGB888); ui->videos_image->setPixmap(QPixmap::fromImage(*qimg)); } bool DetailedRecordTable::timeIsIntoVideo(qint64 etime,RecordVideo video){ return (etime>=video.init_time && etime <= video.end_time); } bool DetailedRecordTable::getVideoClicked(QPoint p,RecordVideo& rv){ // primero veo si hice click en la imagen .. if(p.x() > ui->videos_image->x() && p.x() < ui->videos_image->x()+ui->videos_image->width() && p.y() > ui->videos_image->y() && p.y() < ui->videos_image->y()+ui->videos_image->height()){ // calculo el instante de tiempo en que se hizo click .. int mins = (p.x() - ui->videos_image->x())/6; int hour = (p.y() - ui->videos_image->y())/12; QDateTime time_clicked(date_,QTime(hour,mins,0)); qint64 e_time_clicked = time_clicked.toMSecsSinceEpoch(); // busco si hay un video grabado en ese tiempo; si lo hay lo devuelvo for(uint i=0;i<videos_.size();i++){ // el instante esta contenido en el intervalo? if(e_time_clicked >= videos_[i].init_time && e_time_clicked <= videos_[i].end_time ){ rv = videos_[i]; return true; } } } return false; } void DetailedRecordTable::mousePressEvent(QMouseEvent *event){ // buscar si hay un video en ese instante RecordVideo video_clicked; bool is_video = getVideoClicked(event->pos(),video_clicked); if(is_video){ // Crear menu y agregar las opciones QMenu* mymenu = new QMenu(this); mymenu->addAction("Abrir video"); QAction* selectedItem = mymenu->exec(mapToGlobal( event->pos())); if (selectedItem){ if(selectedItem->text() == "Abrir video"){ QString filename = save_folder+"/"+ QString::fromStdString(camera_->unique_id_)+"/"+ QString::fromStdString(camera_->unique_id_)+"_"+ // id QString::number(video_clicked.init_time)+ "_"+ // init QString::number(video_clicked.end_time)+".mp4"; // end QDesktopServices::openUrl(QUrl(filename)); } } } }
#include "QE.h" class UnitTest { public: int id; Data data; UnitTest(double a, double b, double c, int i) { data = Data(a, b, c); id = i; } void twoRoots(double check1, double check2) { calculateX(&data); assert (data.result == 2); assert (data.x1 == check1); assert (data.x2 == check2); print(data); cout << "|Test " << id << " passed. 2 roots.|" << endl; cout << "**************************" << endl; } void oneRoot(double check1) { calculateX(&data); assert (data.result == 1); assert (data.x1 == check1); print(data); cout << "|Test " << id << " passed. 1 root.|" << endl; cout << "**************************" << endl; } void noRoots() { calculateX(&data); assert (data.result == 0); print(data); cout << "|Test " << id << " passed. No roots.|" << endl; cout << "**************************" << endl; } void aZero(double a, double b, double c) { calculateX(&data); print(data); } }; int main() { UnitTest test1(5,-7,2,1); UnitTest test2(1,6,9, 2); UnitTest test3(2,1,5, 3); UnitTest test4(0,0,0, 4); UnitTest test5(5,0,0, 5); UnitTest test6(0,5,0, 6); UnitTest test7(0,0,5, 7); UnitTest test8(4,8,0, 8); UnitTest test9(0,4,8, 9); test1.twoRoots(1, 0.4); test2.oneRoot(-3); test3.noRoots(); test4.noRoots(); test5.oneRoot(0); test6.oneRoot(0); test7.noRoots(); test8.twoRoots(0,-2); test9.oneRoot(-2); while (true) { } return 0; }
#include "NpcInfoSystem.h" static NpcInfoSystem* _npcInfoSystem = NULL; NpcInfo::NpcInfo(const rapidjson::Value &json) :m_nID(json["ID"].GetUint()) ,m_nSID(json["SID"].GetUint()) ,m_nQID(json["QID"].GetUint()) ,m_nRID(json["RID"].GetUint()) ,m_sSentence(json["Sentence"].GetString()) ,m_sName(json["Name"].GetString()) { log("%s,%s",getNpcName().c_str(), json["Sentence"].GetString()); } NpcInfo::~NpcInfo() { } NpcInfoSystem* NpcInfoSystem::shareNpcInfoSystem() { if (_npcInfoSystem == NULL) { _npcInfoSystem = new NpcInfoSystem(); } return _npcInfoSystem; } NpcInfoSystem::NpcInfoSystem() { //CSJson::Reader reader; // CSJson::Value json; rapidjson::Document json; string file = FileUtils::getInstance()->fullPathForFilename("game_data/npc_info.json"); CCString* filePath = CCString::createWithContentsOfFile(file.c_str()); CCAssert(filePath, "file is open fail!"); json.Parse<0>(filePath->getCString()); //if (!reader.parse(filePath->getCString(), json, false)) //{ //CCAssert(false, "Json::Reader Parse error!"); //} if (json.HasParseError()) { log("NpcInfoSystem NpcInfoSystem %s\n",json.GetParseError()); } int nArrayCount = json.Size(); for (int i=0; i<nArrayCount; i++) { const rapidjson::Value &ArrayJson = json[i];//DICTOOL->getSubDictionary_json(json,"ID",i); this->addNpcInfo(ArrayJson); } } NpcInfoSystem::~NpcInfoSystem() { map<unsigned int, NpcInfo*>::iterator itr; for (itr=m_npcInfoMap.begin(); itr!=m_npcInfoMap.end(); itr++) { delete itr->second; m_npcInfoMap.erase(itr); } _npcInfoSystem = NULL; } void NpcInfoSystem::addNpcInfo(const rapidjson::Value &json) { NpcInfo* _npcInfo = new NpcInfo(json); unsigned int key = _npcInfo->getID(); m_npcInfoMap[key] = _npcInfo; } NpcInfo* NpcInfoSystem::getNpcInfo(const unsigned int npcID) { if (_npcInfoSystem == NULL) { NpcInfoSystem::shareNpcInfoSystem(); } map<unsigned int, NpcInfo*>::iterator itr; itr = _npcInfoSystem->m_npcInfoMap.find(npcID); if (itr != _npcInfoSystem->m_npcInfoMap.end()) { return (*itr).second; } return NULL; }
#include "Sensor.h" #ifndef __Sensor_H #error [E030] Не определен заголовочный файл Sensor.h #endif void Sensor::handle() { } uint16_t Sensor::getValue() { return value; } Boolean Sensor::getTurnOn() { return turnOn; }
#include <iostream> #include <algorithm> #include <cstdlib> struct Range_error :std::out_of_range { int index; Range_error(int i) :std::out_of_range("Range error"), index{ i }{} }; /* template<typename T> class allocator { T* allocate(int n); void deallocate(T* p, int n); void construct(T* p, const T& v); void destroy(T* p); }; template<typename T> T* allocator<T>::allocate(int n) { // c // return static_cast<T*>(malloc(sizeof (T) * n)) // c++ return reinterpret_cast<T*>(new char[sizeof(T) * n]); } template<typename T> void allocator<T>::deallocate(T* p, int n) { //c++ delete[] reinterpret_cast<char*> (p); // c //free(p); } template<typename T> void allocator<T>::construct(T* p, const T& v) { //c++ new(p) T(v); } template<typename T> void allocator<T>::destroy(T* p) { // c++ p->~T(); } */ template<typename T, typename A> struct vector_base { A alloc; T* elem; int sz; int space; vector_base() : elem(alloc.allocate(0)), sz(0), space(0) {} vector_base(int n) : elem{ alloc.allocate(n) }, sz{ 0 }, space{ n } {} vector_base(const A& a, int n) : alloc{ a }, elem{ alloc.allocate(n) }, sz{ 0 }, space{ n } {} vector_base(const vector_base&); vector_base(std::initializer_list<T>); ~vector_base() { alloc.deallocate(elem, space); } }; template<typename T, typename A> vector_base<T, A>::vector_base(const vector_base& a) { T* p = alloc.allocate(a.sz); for (int i = 0; i < a.sz; ++i) alloc.construct(&p[i], a.elem[i]); elem = p; sz = a.sz; space = a.space; } template<typename T, typename A> vector_base<T, A>::vector_base(std::initializer_list<T> lst) : sz{ int(lst.size()) }, elem{ new T[sz] }, space{ sz } { std::copy(lst.begin(), lst.end(), elem); } template <typename T, typename A = std::allocator<T>> class vector : private vector_base<T, A> { public: A alloc; int sz; // Number of elements T* elem; // Pointer to first element int space; // sz + Extra slots vector() : sz{ 0 }, elem{ nullptr }, space{ 0 } {}; explicit vector(int s) // initialisation : sz{ 0 }, elem{ nullptr }, space{ 0 } { resize(s); } vector(const std::initializer_list<T>& lst); vector(const vector&); // Constructor copy vector& operator= (const vector&); // Copy assignment vector(const vector&& a); // Constructor move vector& operator= (const vector&&); // Move assignment ~vector() { delete[] elem; } //Destructor T& at(int n); const T& at(int n) const; T& operator[] (int n); // v[] const T& operator[] (int n) const; // const v[] int size() const { return sz; } // size() void reserve(int newalloc); // vector::reserve() int capacity() const { return space; } // capacity() void resize(int newsize); // resize() void push_back(const T& val); // push_back() }; template<typename T, typename A> vector<T, A>::vector(const std::initializer_list<T>& lst) : sz{ int(lst.size()) }, elem{ new T[sz] } { std::copy(lst.begin(), lst.end(), elem); } template<typename T, typename A> vector<T, A>::vector(const vector& arg) : sz{ arg.sz }, elem{ new T[arg.sz] } { std::copy(arg.elem, arg.elem + sz, elem); } template<typename T, typename A> vector<T, A>& vector<T, A>::operator= (const vector& arg) { if (&arg == this) return *this; if (arg.sz <= space) { for (int i = 0; i < arg.sz; ++i) elem[i] = arg.elem[i]; sz = arg.sz; return *this; } T* buffer = new T[arg.sz]; for (int i = 0; i < arg.sz; ++i) buffer[i] = arg.elem[i]; delete[] elem; space = sz = arg.sz; elem = buffer; return *this; } template<typename T, typename A> vector<T, A>::vector(const vector&& a) : sz{ a.sz }, elem{ a.elem } { a.sz = 0; a.elem = nullptr; } template<typename T, typename A> vector<T, A>& vector<T, A>::operator= (const vector&& a) { delete[] elem; elem = a.elem; sz = a.sz; a.elem = nullptr; a.sz = 0; return *this; } template<typename T, typename A> void vector<T, A>::reserve(int newalloc) { if (newalloc <= this->space) return; vector_base<T, A> b(this->alloc, newalloc); std::uninitialized_copy(elem, elem + sz, b.elem); b.sz = sz; for (int i = 0; i < this->sz; ++i) this->alloc.destroy(&this->elem[i]); this->alloc.deallocate(this->elem, this->space); //std::swap<vector_base<T, A>&>(static_cast<vector_base<T, A>&>(*this), b); this->elem = b.elem; this->sz = b.sz; this->space = b.space; b.elem = nullptr; b.sz = b.space = 0; } template<typename T, typename A> void vector<T, A>::resize(int newsize) { reserve(newsize); if (newsize < sz) { for (T* it = elem + newsize; it < elem + sz; ++it) alloc.destroy(it); sz = newsize; } else { T* i = elem + sz; try { for (int i = sz; i < elem + newsize; ++i) alloc.construct(i, T()); sz = newsize; } catch (...) { for (T* it = elem + sz; it < i; ++it) alloc.destroy(it); throw; } } } template<typename T, typename A> void vector<T, A>::push_back(const T& val) { if (space == 0) reserve(8); else if (sz == space) reserve(2 * space); alloc.construct(elem + sz, val); ++sz; } template<typename T, typename A> T& vector<T, A>:: operator[](int n) { return at(n); } template<typename T, typename A> const T& vector<T, A>:: operator[](int n) const { if (n < 0 || sz <= n) throw Range_error(n); return elem[n]; } template<typename T, typename A> T& vector<T, A>::at(int n) { if (n < 0 || sz <= n) throw Range_error(n); return elem[n]; } int main() { vector<int> vi; vi.push_back(55); vi.push_back(44); for (int i = 0; i < vi.size(); ++i) std::cout << vi[i] << ' '; std::cout << std::endl; vector<int> v = { 1, 2, 3, 4, 5, 6 }; vector<int> v1 = { 10, 11, 12 }; std::cout << "vector v1 : "; for (int i = 0; i < v1.size(); ++i) std::cout << v1[i] << ' '; std::cout << std::endl; std::cout << "vector v : "; for (int i = 0; i < v.size(); ++i) std::cout << v[i] << ' '; std::cout << std::endl; std::cout << "size v1: " << v1.size() << std::endl; std::cout << "size v: " << v.size() << std::endl; v = v1; std::cout << "vector v after v = v1: "; for (int i = 0; i < v.size(); ++i) std::cout << v[i] << ' '; std::cout << std::endl; v.push_back(5); std::cout << "vector v after v.push_back(5): "; for (int i = 0; i < v.size(); ++i) std::cout << v[i] << ' '; std::cout << std::endl; vector<std::string> vstr = { "I", "have", "done", "vector" }; for (int i = 0; i < vstr.size(); ++i) std::cout << vstr[i] << ' '; std::cout << std::endl; std::cout << "space v: " << v.capacity() << std::endl; std::cout << "space v1: " << v1.capacity() << std::endl; return 0; }
/* ........eWorld ReSearch 2004 ........Alessandro Polo ........http://www.ewgate.net ........===================== ........This software is freeware. Project is Open Source. ........Keep Author's Credits if you use any part of this software. ........===================== ........Project State: Completed ........Project Date: 09/3/2004 */ //--------------------------------------------------------------------------- #include <vcl.h> #include <DateUtils.hpp> #include <Clipbrd.hpp> #include "ShellAPI.h" #pragma hdrstop #include "main.h" #include "options.h" #include "calendar.h" #include "image.h" #include "imageed.h" #include "about.h" #include "twaini.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TmainFrm *mainFrm; //--------------------------------------------------------------------------- __fastcall TmainFrm::TmainFrm(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Opzioni1Click(TObject *Sender) { OptionsFrm->ShowModal(); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::exit1Click(TObject *Sender) { FormClose(Sender, caFree); Application->Terminate(); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::SalvaconNome1Click(TObject *Sender) { SaveDialog->Title = "Salva Database con nome.."; SaveDialog->DefaultExt = "DBF"; SaveDialog->Filter = "DBase (*.dbf)|*.DBF"; SaveDialog->Options.Clear(); SaveDialog->Options << ofPathMustExist; if (SaveDialog->Execute()) { expTable->Close(); expTable->Exclusive = true; expTable->DatabaseName = ""; expTable->TableName = SaveDialog->FileName; expTable->TableType = ttDBase; expTable->FieldDefs->Clear(); expTable->FieldDefs->Add("name", ftString, 32, true); expTable->FieldDefs->Add("expdate", ftDate); expTable->FieldDefs->Add("subdate", ftDate); expTable->FieldDefs->Add("birthdate", ftDate); expTable->FieldDefs->Add("notes", ftString, 128); expTable->FieldDefs->Add("phone", ftString, 32); expTable->FieldDefs->Add("address", ftString, 64); expTable->FieldDefs->Add("image", ftGraphic); expTable->FieldDefs->Add("cert", ftBoolean); expTable->IndexDefs->Clear(); expTable->IndexDefs->Add("","name", TIndexOptions() <<ixPrimary << ixUnique); expTable->IndexDefs->Add("expdate","expdate", TIndexOptions()); expTable->IndexDefs->Add("subdate","subdate", TIndexOptions()); expTable->IndexDefs->Add("birthdate","birthdate", TIndexOptions()); expTable->CreateTable(); expTable->Open(); expTable->BatchMove(Table, batAppend); expTable->Close(); if (FileExists(SaveDialog->FileName)) { AnsiString tmpmsg, basefile; basefile = SaveDialog->FileName.SubString(1, SaveDialog->FileName.LowerCase().AnsiPos(".dbf")-1); tmpmsg = "Il database è stato esportato. Mantenere la copia per sicurezza. \n\n"; tmpmsg += "Nota: I file dati sono i seguenti: \n"; tmpmsg += "\t - " + basefile + ".DBF"; tmpmsg += "\n\t - " + basefile + ".DBT"; tmpmsg += "\n\t - " + basefile + ".MDX"; tmpmsg += "\n\nNon rinominare i file e non separarli."; ShowMessage(tmpmsg); } else ShowMessage("ERRORE: Il database non è stato salvato."); }; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::GyMan1Click(TObject *Sender) { AboutBox->ShowModal(); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Button1Click(TObject *Sender) { ImageEditorFrm->Image->AutoSize = true; ImageEditorFrm->Image->Stretch = false; ImageEditorFrm->Image->Picture->Assign(DBImage1->Picture); ImageEditorFrm->HSizeEdit->Text = ImageEditorFrm->Image->Picture->Height; ImageEditorFrm->WSizeEdit->Text = ImageEditorFrm->Image->Picture->Width; ImageEditorFrm->Image->AutoSize = false; ImageEditorFrm->Button4Click(Sender); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::SvuotaDatabaseClick(TObject *Sender) { if (Table->Active) if (Application->MessageBoxA("Tutti i dati dei Clienti vengono persi irrimediabilmente.", "Svuotare il Database?", MB_YESNO) == IDYES) Table->EmptyTable(); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Modifica2Click(TObject *Sender) { if (Table->Active) { if (!PageControl->ActivePage->TabIndex) PageControl->ActivePageIndex = 2; Table->Edit(); if (PageControl->ActivePage->TabIndex == 2) DBEdit4->SetFocus(); }; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Elimina1Click(TObject *Sender) { if (Table->Exists) if (Application->MessageBoxA("Eliminare il Cliente selezionato?", "Conferma rimozione..", MB_YESNO) == IDOK) Table->Delete(); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Aggiungi1Click(TObject *Sender) { if (Table->Active) { if (!PageControl->ActivePage->TabIndex) PageControl->ActivePageIndex = 2; Table->Last(); Table->Append(); if (PageControl->ActivePage->TabIndex == 2) DBEdit1->SetFocus(); }; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Nome1Click(TObject *Sender) { Nome1->Checked = true; Scadenza1->Checked = false; Iscrizione1->Checked = false; Datadinascita1->Checked = false; Table->DisableControls(); Table->Active = false; Table->Exclusive = true; Table->IndexFieldNames = "name"; Table->IndexDefs->Update(); Table->Exclusive = false; Table->Active = true; Table->EnableControls(); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Scadenza1Click(TObject *Sender) { Nome1->Checked = false; Scadenza1->Checked = true; Iscrizione1->Checked = false; Datadinascita1->Checked = false; Table->DisableControls(); Table->Active = false; Table->Exclusive = true; Table->IndexFieldNames = "expdate"; Table->IndexDefs->Update(); Table->Exclusive = false; Table->Active = true; Table->EnableControls(); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Iscrizione1Click(TObject *Sender) { Nome1->Checked = false; Scadenza1->Checked = false; Iscrizione1->Checked = true; Datadinascita1->Checked = false; Table->DisableControls(); Table->Active = false; Table->Exclusive = true; Table->IndexFieldNames = "subdate"; Table->IndexDefs->Update(); Table->Exclusive = false; Table->Active = true; Table->EnableControls(); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Datadinascita1Click(TObject *Sender) { Nome1->Checked = false; Scadenza1->Checked = false; Iscrizione1->Checked = false; Datadinascita1->Checked = true; Table->DisableControls(); Table->Active = false; Table->Exclusive = true; Table->IndexFieldNames = "birthdate"; Table->IndexDefs->Update(); Table->Exclusive = false; Table->Active = true; Table->EnableControls(); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::FormShow(TObject *Sender) { // set default values ImageH = 240; ImageW = 200; ColDimTable[0] = 200; ColDimTable[1] = 100; ColDimTable[2] = 100; ColDimTable[3] = 100; ColDimTable[4] = 100; ColDimTable[5] = 70; ColDimTable[6] = 70; ColDimTable[7] = 50; ColDimTable[8] = 50; defStatusMsg = "Database non caricato. Aprire un file dal Menu."; defdatafile = OptionsFrm->Edit1->Text; OptionsFrm->Button1Click(Sender); //load options bool erstate = true; if ((OptionsFrm->CheckBox1->Checked)&&(FileExists(defdatafile))) { Table->Close(); Table->DatabaseName = ""; Table->Exclusive = true; Table->IndexFieldNames = ""; Table->IndexDefs->Clear(); Table->TableName = defdatafile; Table->TableType = ttDefault; try { Table->Exclusive; Table->Open(); erstate = false; } catch (EDBEngineError* dbError) { ShowMessage(dbError[0].Message); }; }; if (!erstate) { if ((Table->Fields->Count > 8) && (Table->FieldList->Strings[0] == "name") && (Table->FieldList->Strings[1] == "expdate") && (Table->FieldList->Strings[2] == "subdate") && (Table->FieldList->Strings[3] == "birthdate") && (Table->FieldList->Strings[4] == "notes") && (Table->FieldList->Strings[5] == "phone") && (Table->FieldList->Strings[6] == "address") && (Table->FieldList->Strings[7] == "image") && (Table->FieldList->Strings[8] == "cert")) { DBEdit1->DataField = Table->FieldList->Strings[0]; DBEdit2->DataField = Table->FieldList->Strings[1]; DBEdit3->DataField = Table->FieldList->Strings[2]; DBEdit4->DataField = Table->FieldList->Strings[3]; DBMemo1->DataField = Table->FieldList->Strings[4]; DBEdit5->DataField = Table->FieldList->Strings[5]; DBEdit6->DataField = Table->FieldList->Strings[6]; DBImage1->DataField = Table->FieldList->Strings[7]; DBCheckBox1->DataField = Table->FieldList->Strings[8]; Aggiorna1Click(Sender); Scadenza1Click(Sender); //ordinamento predefinito DBGrid->Columns->Items[0]->Title->Caption = "Nome Cliente"; DBGrid->Columns->Items[1]->Title->Caption = "Data Scadenza"; DBGrid->Columns->Items[2]->Title->Caption = "Data Iscrizione"; DBGrid->Columns->Items[3]->Title->Caption = "Data di Nascita"; DBGrid->Columns->Items[4]->Title->Caption = "Note"; DBGrid->Columns->Items[5]->Title->Caption = "Telefono"; DBGrid->Columns->Items[6]->Title->Caption = "Indirizzo"; DBGrid->Columns->Items[7]->Title->Caption = "Immagine"; DBGrid->Columns->Items[8]->Title->Caption = "Certificato"; if (OptionsFrm->CheckBox5->Checked) for (int i = 0; i < 9; i++) if (ColDimTable[i]) DBGrid->Columns->Items[i]->Width = ColDimTable[i]; } else if (Application->MessageBoxA("Il file Database non sembra corretto! Creare un Nuovo database?", "Impossibile caricare il database", MB_YESNO) == IDYES) Nuovodatabase1Click(Sender); PageControl->ActivePageIndex = 0; } else if (Application->MessageBoxA("Il database predefinito non esiste. Creare un Nuovo database?", "Impossibile caricare il database", MB_YESNO) == IDYES) Nuovodatabase1Click(Sender); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::CaricaFile1Click(TObject *Sender) { OpenDialog->Title = "Carica Database Clienti.."; OpenDialog->DefaultExt = "DBF"; OpenDialog->Filter = "DBase (*.dbf)|*.DBF"; OpenDialog->Options.Clear(); OpenDialog->Options << ofFileMustExist << ofPathMustExist; if (OpenDialog->Execute()) { bool erstate = false; Table->Close(); Table->DatabaseName = ""; Table->Exclusive = true; Table->IndexFieldNames = ""; Table->IndexDefs->Clear(); Table->TableName = OpenDialog->FileName; Table->TableType = ttDefault; try { Table->Exclusive; Table->Open(); } catch (EDBEngineError* dbError) { ShowMessage(dbError[0].Message); erstate = true; } if (!erstate) { if ((Table->Fields->Count > 8) && (Table->FieldList->Strings[0] == "name") && (Table->FieldList->Strings[1] == "expdate") && (Table->FieldList->Strings[2] == "subdate") && (Table->FieldList->Strings[3] == "birthdate") && (Table->FieldList->Strings[4] == "notes") && (Table->FieldList->Strings[5] == "phone") && (Table->FieldList->Strings[6] == "address") && (Table->FieldList->Strings[7] == "image") && (Table->FieldList->Strings[8] == "cert")) { DBEdit1->DataField = Table->FieldList->Strings[0]; DBEdit2->DataField = Table->FieldList->Strings[1]; DBEdit3->DataField = Table->FieldList->Strings[2]; DBEdit4->DataField = Table->FieldList->Strings[3]; DBMemo1->DataField = Table->FieldList->Strings[4]; DBEdit5->DataField = Table->FieldList->Strings[5]; DBEdit6->DataField = Table->FieldList->Strings[6]; DBImage1->DataField = Table->FieldList->Strings[7]; DBCheckBox1->DataField = Table->FieldList->Strings[8]; Aggiorna1Click(Sender); Scadenza1Click(Sender); //ordinamento predefinito DBGrid->Columns->Items[0]->Title->Caption = "Nome Cliente"; DBGrid->Columns->Items[1]->Title->Caption = "Data Scadenza"; DBGrid->Columns->Items[2]->Title->Caption = "Data Iscrizione"; DBGrid->Columns->Items[3]->Title->Caption = "Data di Nascita"; DBGrid->Columns->Items[4]->Title->Caption = "Note"; DBGrid->Columns->Items[5]->Title->Caption = "Telefono"; DBGrid->Columns->Items[6]->Title->Caption = "Indirizzo"; DBGrid->Columns->Items[7]->Title->Caption = "Immagine"; DBGrid->Columns->Items[8]->Title->Caption = "Certificato"; if (OptionsFrm->CheckBox5->Checked) for (int i = 0; i < 9; i++) if (ColDimTable[i]) DBGrid->Columns->Items[i]->Width = ColDimTable[i]; } else { ShowMessage("ERRORE: Il File dati non sembra corretto."); Table->Close(); Aggiorna1Click(Sender); }; PageControl->ActivePageIndex = 1; } else { ShowMessage("Impossibile caricare il file."); Aggiorna1Click(Sender); } }; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::DBEditKeyPress(TObject *Sender, char &Key) { StatusBar->Panels->Items[1]->Text = "Database Modificato. Salvare premendo Invio o cliccando il Visto."; if (Key == VK_RETURN) if ((Table->Active) && (Table->Exists)) if (DBEdit1->Text.IsEmpty()) ShowMessage("Inserire un nome valido!"); else Table->Post(); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Aggiorna1Click(TObject *Sender) { StatusBar->Panels->Items[0]->Text = "Oggi " + DateToStr(Date()); ExpiredList->Strings->Clear(); ExpiringList->Strings->Clear(); CalendarFrm->MonthCalendar->Date = Date();; ImageS->Picture->Assign(NULL); if (!Table->Exists) { defStatusMsg = "Database non caricato. Aprire o creare un nuovo database dal Menu File."; StatusBar->Panels->Items[1]->Text = defStatusMsg; return; }; Table->DisableControls(); Table->First(); TDate tmpdate; while (!Table->Eof) { if (!TryStrToDate(Table->FieldByName("expdate")->AsString, tmpdate)) ExpiredList->InsertRow(Table->FieldByName("name")->AsString, "Scadenza non impostata!", 1); else if (CompareDate(Date(), tmpdate) >= 0) { if (IsSameDay(tmpdate, Date())) ExpiredList->InsertRow(Table->FieldByName("name")->AsString, AnsiString(DateToStr(tmpdate) + " (oggi)"), 1); else if (DaysBetween(tmpdate, Date()) == 1) ExpiredList->InsertRow(Table->FieldByName("name")->AsString, AnsiString(DateToStr(tmpdate) + " (ieri)"), 1); else if (DaysBetween(tmpdate, Date()) <= cmb_dayscad->Text.ToIntDef(5)) ExpiredList->InsertRow(Table->FieldByName("name")->AsString, AnsiString(DateToStr(tmpdate) + " (" + AnsiString(DaysBetween(tmpdate, Date())) + " giorni fa)"), 1); }; Table->Next(); } Table->First(); while (!Table->Eof) { if (TryStrToDate(Table->FieldByName("expdate")->AsString, tmpdate)) if (CompareDate(tmpdate, Date()) > 0) { if (DaysBetween(tmpdate, Date()) == 1) ExpiringList->InsertRow(Table->FieldByName("name")->AsString, AnsiString(DateToStr(tmpdate) + " (domani)"), 1); else if (DaysBetween(tmpdate, Date()) <= cmb_dayspan->Text.ToIntDef(5)) ExpiringList->InsertRow(Table->FieldByName("name")->AsString, AnsiString(DateToStr(tmpdate) + " (tra " + AnsiString(DaysBetween(tmpdate, Date())) + " giorni)"), 1); }; Table->Next(); }; Table->EnableControls(); defStatusMsg = "Database operativo. " + AnsiString(Table->RecordCount) + " clienti."; if ((ExpiredList->RowCount==2)&&(!ExpiredList->Keys[1].IsEmpty())) defStatusMsg += " Una tessera scaduta."; else if (ExpiredList->RowCount == 2) defStatusMsg += " Nessuna tessera scaduta."; else if (ExpiredList->RowCount>2) defStatusMsg += " " + AnsiString(ExpiredList->RowCount-1) + " tessere scadute."; if ((ExpiringList->RowCount==2)&&(!ExpiringList->Keys[1].IsEmpty())) defStatusMsg += " Una tessera in scadenza."; else if (ExpiringList->RowCount == 2) defStatusMsg += " Nessuna tessera in scadenza."; else if (ExpiringList->RowCount>2) defStatusMsg += " " + AnsiString(ExpiringList->RowCount-1) + " tessere in scadenza."; defStatusMsg += " [file: " + ExtractFileName(Table->TableName) + "]"; StatusBar->Panels->Items[1]->Text = defStatusMsg; ExpiringListClick(Sender); ExpiredListClick(Sender); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Button3Click(TObject *Sender) { if (Table->Exists) { Table->DisableControls(); Table->Edit(); Table->Fields->FieldByName("subdate")->AsString = Date(); Table->Post(); Table->EnableControls(); }; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Button4Click(TObject *Sender) { if (Table->Exists) { Table->DisableControls(); Table->Edit(); Table->Fields->FieldByName("expdate")->Value = IncMonth(Date()); Table->Post(); Table->EnableControls(); }; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Button5Click(TObject *Sender) { if (Table->Exists) { Table->DisableControls(); ExpiringListClick(Sender); if (Table->FieldByName("name")->AsString == ExpiringList->Keys[ExpiringList->Row]) { Table->Edit(); Table->FieldByName("expdate")->Value = IncMonth(Date()); Table->Post(); }; Table->EnableControls(); PageControl->ActivePageIndex = 2; DBEdit2->SetFocus(); } else ShowMessage("E' necessario aprire o creare un nuovo database."); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Calendario1Click(TObject *Sender) { CalendarFrm->Visible = !CalendarFrm->Visible; Calendario1->Checked = !Calendario1->Checked; CalendarFrm->MonthCalendar->Date = MonthCalendar->Date; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::FotoTessera1Click(TObject *Sender) { ImageFrm->Visible = !ImageFrm->Visible; FotoTessera1->Checked = !FotoTessera1->Checked; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::cmb_dayspanKeyPress(TObject *Sender, char &Key) { if (Key == VK_RETURN) { cmb_dayspan->Text = cmb_dayspan->Text.ToIntDef(5); Aggiorna1Click(Sender); } } //--------------------------------------------------------------------------- void __fastcall TmainFrm::TableAfterPost(TDataSet *DataSet) { defStatusMsg = "Database Operativo. Tutti i dati sono stati salvati. [" + AnsiString(Table->RecordCount) + " clienti]"; StatusBar->Panels->Items[1]->Text = defStatusMsg; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Button8Click(TObject *Sender) { if (Table->Exists) { Table->DisableControls(); ExpiredListClick(Sender); if (Table->FieldByName("name")->AsString == ExpiredList->Keys[ExpiredList->Row]) { Table->Edit(); Table->FieldByName("expdate")->Value = IncMonth(Date()); Table->Post(); } Table->EnableControls(); PageControl->ActivePageIndex = 2; DBEdit2->SetFocus(); } else ShowMessage("E' necessario aprire o creare un nuovo database."); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Button7Click(TObject *Sender) { if (Table->Exists) { ExpiredListClick(Sender); PageControl->ActivePageIndex = 2; Table->Edit(); DBEdit2->SetFocus(); } else ShowMessage("E' necessario aprire o creare un nuovo database."); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Button6Click(TObject *Sender) { if (Table->Exists) { ExpiringListClick(Sender); PageControl->ActivePageIndex = 2; Table->Edit(); DBEdit2->SetFocus(); } else ShowMessage("E' necessario aprire o creare un nuovo database."); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::ExpiringListClick(TObject *Sender) { if ((ExpiringList->Row < ExpiringList->RowCount)&&(Table->Exists)) { TDate tmpdate = Date(); Table->First(); while (!Table->Eof) { if (Table->FieldByName("name")->AsString == ExpiringList->Keys[ExpiringList->Row]) { TryStrToDate(Table->FieldByName("expdate")->AsString, tmpdate); MonthCalendar->Date = tmpdate; CalendarFrm->MonthCalendar->Date = tmpdate; ImageS->Picture->Assign(DBImage1->Picture); ImageFrm->Image->Picture->Assign(DBImage1->Picture); break; }; Table->Next(); } Table->EnableControls(); } else { CalendarFrm->MonthCalendar->Date = Date();; ImageS->Picture->Assign(NULL); }; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::ExpiredListClick(TObject *Sender) { if ((ExpiredList->Row < ExpiredList->RowCount)&&(Table->Exists)) { TDate tmpdate = Date(); Table->DisableControls(); Table->First(); while (!Table->Eof) { if (Table->FieldByName("name")->AsString == ExpiredList->Keys[ExpiredList->Row]) { TryStrToDate(Table->FieldByName("expdate")->AsString, tmpdate); MonthCalendar->Date = tmpdate; CalendarFrm->MonthCalendar->Date = tmpdate; ImageS->Picture->Assign(DBImage1->Picture); ImageS->Hint = Table->FieldByName("notes")->AsString; ImageFrm->Image->Picture->Assign(DBImage1->Picture); break; }; Table->Next(); } Table->EnableControls(); } else { CalendarFrm->MonthCalendar->Date = Date();; ImageS->Picture->Assign(NULL); }; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::DBEditDateClick(TObject *Sender) { if (Table->Exists) { TDBEdit* TheSender = (TDBEdit*)Sender; TDate tmpdate = CalendarFrm->MonthCalendar->Date; TryStrToDate(TheSender->EditText, tmpdate); CalendarFrm->MonthCalendar->Date = tmpdate; }; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::eWorldReSearch1Click(TObject *Sender) { ShellExecute(Handle, "open", "http://www.ewgate.net/research/", NULL,NULL,SW_SHOWDEFAULT); } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- void __fastcall TmainFrm::Button11Click(TObject *Sender) { if (Table->Exists) { ImageEditorFrm->Button3Click(Sender); Table->Edit(); mainFrm->DBImage1->Picture->Graphic->Assign(ImageEditorFrm->Image->Picture->Graphic); Table->Post(); if ((ImageEditorFrm->Image->Picture->Height > ImageH) || (ImageEditorFrm->Image->Picture->Width > ImageW)) if (Application->MessageBoxA("L'immagine è più grande del necessario. Modificarla?", "Aprire Editor Immagini?", MB_YESNO) == IDYES) ImageEditorFrm->ShowModal(); } else ShowMessage("E' necessario aprire o creare un nuovo database."); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Aquisisci1Click(TObject *Sender) { if (TwainExists()) { HANDLE dib = TwainGetImage( Handle ); if ( dib == 0 ) return; LPBITMAPINFO bmi = (LPBITMAPINFO)::GlobalLock(dib); ImageEditorFrm->Image->AutoSize = true; ImageEditorFrm->Image->Stretch = false; ImageEditorFrm->Image->Picture->Bitmap->Height = bmi->bmiHeader.biHeight; ImageEditorFrm->Image->Picture->Bitmap->Width = bmi->bmiHeader.biWidth; SetDIBits( ImageEditorFrm->Image->Picture->Bitmap->Canvas->Handle, ImageEditorFrm->Image->Picture->Bitmap->Handle, 0, (UINT) bmi->bmiHeader.biHeight, (Byte*)((Byte*)bmi + sizeof(BITMAPINFOHEADER)), bmi, DIB_RGB_COLORS ); ::GlobalUnlock( dib ); ::GlobalFree( dib ); ImageEditorFrm->HSizeEdit->Text = ImageEditorFrm->Image->Picture->Height; ImageEditorFrm->WSizeEdit->Text = ImageEditorFrm->Image->Picture->Width; ImageEditorFrm->Image->Height = ImageEditorFrm->Image->Picture->Height; ImageEditorFrm->Image->Width = ImageEditorFrm->Image->Picture->Width; ImageEditorFrm->Image->AutoSize = false; }; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::FormClose(TObject *Sender, TCloseAction &Action) { if ((OptionsFrm->CheckBox3->Checked)&&(Table->Exists)) OptionsFrm->Edit1->Text = Table->TableName; if (OptionsFrm->CheckBox2->Checked) OptionsFrm->Button2Click(Sender); if (Table->Exists) Table->Close(); FreeLibrary( TwainInst ); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::EsportaListaNomi1Click(TObject *Sender) { if ((Table->Exists)&&(Table->RecordCount)) { SaveDialog->Title = "Esporta Lista Nomi Clienti.."; SaveDialog->DefaultExt = "txt"; SaveDialog->Filter = "Text files (*.txt)|*.TXT|All files (*.*)|*.*"; SaveDialog->Options.Clear(); SaveDialog->Options << ofPathMustExist; if (SaveDialog->Execute()) { TStringList *expfile; expfile = new TStringList; expfile->Clear(); expfile->Add("# GyManager 1.01"); expfile->Add("# ================================"); expfile->Add("# Lista Nomi Clienti\t" + AnsiString(Date())); expfile->Add(""); expfile->Add(""); expfile->Add("Nome Cliente\t\tTelefono\tIndirizzo"); Table->DisableControls(); Table->First(); while (!Table->Eof) { expfile->Add(Table->FieldByName("name")->AsString + "\t\t" + Table->FieldByName("phone")->AsString + "\t" + Table->FieldByName("address")->AsString); Table->Next(); } Table->EnableControls(); expfile->SaveToFile(SaveDialog->FileName); delete expfile; ShellExecute(NULL, "open", "notepad.exe", SaveDialog->FileName.c_str(), "", SW_SHOWDEFAULT); }; }; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::EsportaListaCompleta1Click(TObject *Sender) { if ((Table->Exists)&&(Table->RecordCount)) { SaveDialog->Title = "Esporta Lista Nomi Clienti.."; SaveDialog->DefaultExt = "txt"; SaveDialog->Filter = "Text files (*.txt)|*.TXT|All files (*.*)|*.*"; SaveDialog->Options.Clear(); SaveDialog->Options << ofPathMustExist; if (SaveDialog->Execute()) { TStringList *expfile; expfile = new TStringList; expfile->Clear(); expfile->Add("# GyManager 1.01"); expfile->Add("# ================================"); expfile->Add("# Lista Clienti \t" + AnsiString(Date())); expfile->Add(""); expfile->Add(""); expfile->Add("# Nome Cliente\t\tScadenza\tIscrizione"); expfile->Add(""); Table->DisableControls(); Table->First(); while (!Table->Eof) { expfile->Add(Table->FieldByName("name")->AsString + "\t\t" + Table->FieldByName("expdate")->AsString + "\t" + Table->FieldByName("subdate")->AsString); Table->Next(); } Table->EnableControls(); expfile->SaveToFile(SaveDialog->FileName); delete expfile; ShellExecute(NULL, "open", "notepad.exe", SaveDialog->FileName.c_str(), "", SW_SHOWDEFAULT); }; }; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Nuovodatabase1Click(TObject *Sender) { SaveDialog->Title = "Nuovo Database Clienti.."; SaveDialog->DefaultExt = "DBF"; SaveDialog->Filter = "DBase (*.dbf)|*.DBF"; SaveDialog->Options.Clear(); SaveDialog->Options << ofPathMustExist; if (SaveDialog->Execute()) { Table->Close(); Table->Exclusive = true; Table->DatabaseName = ""; Table->TableName = SaveDialog->FileName; Table->TableType = ttDBase; Table->FieldDefs->Clear(); Table->FieldDefs->Add("name", ftString, 32, true); Table->FieldDefs->Add("expdate", ftDate); Table->FieldDefs->Add("subdate", ftDate); Table->FieldDefs->Add("birthdate", ftDate); Table->FieldDefs->Add("notes", ftString, 128); Table->FieldDefs->Add("phone", ftString, 32); Table->FieldDefs->Add("address", ftString, 64); Table->FieldDefs->Add("image", ftGraphic); Table->FieldDefs->Add("cert", ftBoolean); Table->IndexDefs->Clear(); Table->IndexDefs->Add("","name", TIndexOptions() <<ixPrimary << ixUnique); Table->IndexDefs->Add("expdate","expdate", TIndexOptions()); Table->IndexDefs->Add("subdate","subdate", TIndexOptions()); Table->IndexDefs->Add("birthdate","birthdate", TIndexOptions()); Table->CreateTable(); Table->Open(); DBEdit1->DataField = Table->FieldList->Strings[0]; DBEdit2->DataField = Table->FieldList->Strings[1]; DBEdit3->DataField = Table->FieldList->Strings[2]; DBEdit4->DataField = Table->FieldList->Strings[3]; DBMemo1->DataField = Table->FieldList->Strings[4]; DBEdit5->DataField = Table->FieldList->Strings[5]; DBEdit6->DataField = Table->FieldList->Strings[6]; DBImage1->DataField = Table->FieldList->Strings[7]; DBCheckBox1->DataField = Table->FieldList->Strings[8]; ColDimTable[0] = 200; ColDimTable[1] = 100; ColDimTable[2] = 100; ColDimTable[3] = 100; ColDimTable[4] = 100; ColDimTable[5] = 70; ColDimTable[6] = 70; ColDimTable[7] = 50; ColDimTable[8] = 20; Aggiorna1Click(Sender); Scadenza1Click(Sender); //ordinamento predefinito DBGrid->Columns->Items[0]->Title->Caption = "Nome Cliente"; DBGrid->Columns->Items[1]->Title->Caption = "Data Scadenza"; DBGrid->Columns->Items[2]->Title->Caption = "Data Iscrizione"; DBGrid->Columns->Items[3]->Title->Caption = "Data di Nascita"; DBGrid->Columns->Items[4]->Title->Caption = "Note"; DBGrid->Columns->Items[5]->Title->Caption = "Telefono"; DBGrid->Columns->Items[6]->Title->Caption = "Indirizzo"; DBGrid->Columns->Items[7]->Title->Caption = "Immagine"; DBGrid->Columns->Items[8]->Title->Caption = "Certificato"; for (int i = 0; i < 9; i++) DBGrid->Columns->Items[i]->Width = ColDimTable[i]; PageControl->ActivePageIndex = 1; }; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::EditorImmagini1Click(TObject *Sender) { ImageEditorFrm->Image->AutoSize = true; ImageEditorFrm->Image->Stretch = false; ImageEditorFrm->Image->Picture->Assign(DBImage1->Picture); ImageEditorFrm->HSizeEdit->Text = ImageEditorFrm->Image->Picture->Height; ImageEditorFrm->WSizeEdit->Text = ImageEditorFrm->Image->Picture->Width; ImageEditorFrm->Image->AutoSize = false; ImageEditorFrm->ShowModal(); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::ImageSClick(TObject *Sender) { if (!ImageS->Picture->Graphic->Empty) { ImageFrm->Image->Picture->Assign(ImageS->Picture); ImageFrm->Width = ImageFrm->Image->Picture->Width; ImageFrm->Height = ImageFrm->Image->Picture->Height; FotoTessera1Click(Sender); }; } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Button2Click(TObject *Sender) { Aquisisci1Click(Sender); ImageEditorFrm->Button2Click(Sender); if ((ImageEditorFrm->Image->Picture->Height > ImageH) || (ImageEditorFrm->Image->Picture->Width > ImageW)) if (Application->MessageBoxA("L'immagine è più grande del necessario. Modificarla?", "Aprire Editor Immagini?", MB_YESNO) == IDYES) ImageEditorFrm->ShowModal(); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Button10Click(TObject *Sender) { if (Table->Exists) { Table->Edit(); Table->Append(); PageControl->ActivePageIndex = 2; DBEdit1->SetFocus(); } else ShowMessage("E' necessario aprire o creare un nuovo database."); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::Button12Click(TObject *Sender) { if (Table->Exists) { Scadenza1Click(Sender); PageControl->ActivePageIndex = 1; } else ShowMessage("E' necessario aprire o creare un nuovo database."); } //--------------------------------------------------------------------------- void __fastcall TmainFrm::ClientisenzaCertificato1Click(TObject *Sender) { if (Table->Exists) { AnsiString list; Table->First(); while (!Table->Eof) { if (!DBCheckBox1->Checked) { list += "\t - " + Table->FieldByName("name")->AsString + "\n"; }; Table->Next(); } ShowMessage("I Seguenti Clienti non hanno ancora consegnato il certificato medico. \n\n" + list); } } //--------------------------------------------------------------------------- void __fastcall TmainFrm::cmb_dayscadKeyPress(TObject *Sender, char &Key) { if (Key == VK_RETURN) { cmb_dayscad->Text = cmb_dayscad->Text.ToIntDef(10); Aggiorna1Click(Sender); } } //---------------------------------------------------------------------------
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; #define N 1111111 pair<int, int> p[N]; int b1[N], b2[N], b3[N], b4[N], *id = b3, *nid = b4, *suf = b1, *nsuf = b2, modl[N+N+N], cnt[N], lcp[N]; char s[N]; int l; int main() { freopen("decimal.in", "r", stdin); freopen("decimal.out", "w", stdout); char c1 = getchar(); char c2 = getchar(); gets(s); l = strlen(s); s[l++] = '0' - 1; time_t st = clock(); for (int i = 0; i < l + l + l; ++i) modl[i] = i % l; for (int i = 0; i < l; ++i) { s[i] -= '0' - 1; ++cnt[s[i]]; } for (int i = 1; i <= 10; ++i) cnt[i] += cnt[i - 1]; for (int i = l - 1; i >= 0; --i) { int p = --cnt[s[i]]; suf[ p ] = i; id[i] = s[i]; } int maxid = 10; for (int h = 0; (1 << h) < l; ++h) { int hh = (1 << h); /* for (int i = 0; i < l; ++i) { for (int j = suf[i]; j <l; ++j) putchar(s[j] + '0' - 1); puts(""); } puts(""); */ memset(cnt, 0, (maxid + 1) * sizeof(int)); for (int i = 0; i < l; ++i) ++cnt[id[i]]; for (int i = 1; i <= maxid; ++i) cnt[i] += cnt[i - 1]; for (int i = l - 1, j; i >= 0; --i) { j = modl[suf[i] - hh + l]; nsuf[ --cnt[ id[j] ] ] = j; } int cid = 0; for (int i = 0; i < l; ++i) { if (i > 0 && (id[nsuf[i]] != id[nsuf[i - 1]] || id[modl[nsuf[i] + hh]] != id[modl[nsuf[i - 1] + hh]]) ) ++cid; nid[ nsuf[i] ] = cid; } maxid = cid; swap(nsuf, suf); swap(nid, id); } cerr << clock() - st << endl; int ansi = 0; int ansj = l - 1; int last = 0; for (int i = 0; i + 1 < l; ++i) { int x = i; int y = suf[id[i] - 1]; if (last > 0) --last; while (x + last < l && y + last < l && s[x + last] == s[y + last]) ++last; lcp[id[x]] = last; } for (int i = 1; i < l; ++i) { int j = suf[i]; if (lcp[i] >= l - j - 1 && ansj > j) { ansj = j; ansi = suf[i - 1]; } if (i + 1 < l && lcp[i + 1] >= l - j - 1 && ansj > j) { ansj = j; ansi = suf[i + 1]; } } for (int i = 0; i < l; ++i) s[i] += '0' - 1; char ch = 0; swap(s[ansi], ch); printf("%c%c%s(", c1, c2, s); swap(s[ansi], ch); swap(s[ansj], ch); printf("%s)\n", s + ansi); return 0; }
#include <iostream> #include "./exercise-01/main.cpp" #include "./exercise-02/main.cpp" #include "./exercise-03/main.cpp" #include "./exercise-04/main.cpp" #include "./exercise-05/main.cpp" #include "./exercise-07/main.cpp" #include "./exercise-09/main.cpp" int main() { int b; do { std::cout << "===========================================" << std::endl; std::cout << "Choose exercise number (int) - (0 to leave)" << std::endl; std::cin >> b; switch (b) { case 0: { break; } case 1: { exercise01(); break; } case 2: { exercise02(); break; } case 3: { exercise03(); break; } case 4: { exercise04(); break; } case 5: { exercise05(); break; } case 7: { exercise07(); break; } case 9: { exercise09(); break; } default: std::cout << "Unknown exercise" << std::endl; break; } } while (b != 0); return 0; }
/* ** EPITECH PROJECT, 2018 ** cpp_indie_studio ** File description: ** Egg.hpp */ #ifndef Egg_HPP #define Egg_HPP #include "Point.hpp" class Egg { public: Egg(Point pos, int idxPlayerFrom); virtual ~Egg() = default; Egg(Egg const & rhs) = default; Egg(Egg && rhs) = default; Egg & operator=(Egg const & rhs) = default; Egg & operator=(Egg && rhs) = default; Point getPos(void) const; int getIdxPlayerFrom(void) const; void setPos(Point const & pos); void setIdxPlayerFrom(int idxPlayerFrom); private: Point _pos; int _idxPlayerFrom; }; #endif // !Egg_HPP
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #include "GraphicFile.h" #include "util/Exceptions.h" #include <cstdio> #include <common/dataSource/DataSource.h> #include "Platform.h" namespace View { void load (const char *path, void **data, int *width, int *height, int *visibleWidthOut, int *visibleHeightOut, ColorSpace *colorSpace, int *bitDepth, bool expandDimensions2) { Common::DataSource *ds = newDataSource (); ds->open (path, Common::DataSource::MODE_UNKNOWN); try { #ifdef WITH_PNG if (checkIfPng (ds)) { ds->rewind (); pngLoad (ds, data, width, height, visibleWidthOut, visibleHeightOut, colorSpace, bitDepth, expandDimensions2); deleteDataSource (ds); return; } ds->rewind (); #endif #ifdef WITH_JPEG if (checkIfJpeg (ds)) { ds->rewind (); jpegLoad (ds, data, width, height, visibleWidthOut, visibleHeightOut, colorSpace, bitDepth, expandDimensions2); deleteDataSource (ds); return; } #endif } catch (std::exception const &) { deleteDataSource (ds); throw; } deleteDataSource (ds); throw Util::OperationNotSupportedException (std::string ("load : unsupported file format. File : ") + path); } } /* namespace View */
#ifndef _SMART_BAG_H_ #define _SMART_BAG_H_ #include <iostream> #include <initializer_list> #include <stdexcept> #include <memory> template <typename Item> class SmartBag { private: int sz; int capacity; std::unique_ptr<Item[]> items; public: SmartBag() : sz(0), capacity(4), items(std::make_unique<Item[]>(4)) {} SmartBag(int c) : sz(0), capacity(c), items(std::make_unique<Item[]>(c)) {} SmartBag(const SmartBag<Item> &b) : sz(b.sz), capacity(b.capacity), items(std::make_unique<Item[]>(b.capacity)) { for (int i = 0; i < sz; i++) { items[i] = b.items[i]; } } SmartBag<Item> &operator=(const SmartBag<Item> &b) { sz = b.sz; capacity = b.capacity; auto newItems = std::make_unique<Item[]>(capacity); items = std::move(newItems); for (int i = 0; i < sz; i++) { items[i] = b.items[i]; } return *this; } SmartBag(std::initializer_list<Item> lst) : sz(0), capacity(lst.size()), items(std::make_unique<Item[]>(lst.size())) { for (Item i : lst) { items[sz++] = i; } } SmartBag<Item> &add(Item i) { if (sz == capacity) { auto newItems = std::make_unique<Item[]>(2 * capacity); for (int j = 0; j < sz; j++) { newItems[j] = items[j]; } capacity = 2 * capacity; items = std::move(newItems); } items[sz++] = i; return *this; } SmartBag<Item> &removeLast() { sz--; return *this; } Item *begin() { return items; } Item *end() { return items + sz; } Item operator[](int i) const { if (i < 0 || i >= sz) { throw std::runtime_error("Out of bounds"); } return items[i]; } Item &operator[](int i) { if (i < 0 || i >= sz) { throw std::runtime_error("Out of bounds"); } return items[i]; } int getSize() const { return sz; } int getCapacity() const { } friend std::ostream &operator<<(std::ostream &out, SmartBag<Item> &bag) { for (int i = 0; i < bag.sz; i++) { out << bag.items[i] << " "; } return out; } ~SmartBag() {} }; #endif
#include "my_light_entity.h" MyLightEntity::MyLightEntity(CVector3 pos, int cId, double maxY, Real lightDist, CColor color) : Light(pos, cId), color(color) { this->lightDist = lightDist; calculateAxis(maxY); lightArea = ColoredArea(); lightArea.color = CColor::GRAY80; lightArea.xRange = { pos.GetX() - lightDist, pos.GetX() + lightDist}; lightArea.yRange = { pos.GetY() - lightDist, pos.GetY() + lightDist}; coloredAreas.push_back(&lightArea); calculateColoredAreas(); } CRange<Real> MyLightEntity::getXRange() const { auto noOfColoredAreas = static_cast<int>(coloredAreas.size()); Real allMins[noOfColoredAreas], allMaxs[noOfColoredAreas]; for (int i = 0; i < noOfColoredAreas; i++) { allMins[i] = coloredAreas[i]->xRange.GetMin(); allMaxs[i] = coloredAreas[i]->xRange.GetMax(); } return { *min_element(allMins, allMins + noOfColoredAreas), *max_element(allMaxs, allMaxs + noOfColoredAreas)}; } CRange<Real> MyLightEntity::getYRange() const { auto noOfColoredAreas = static_cast<int>(coloredAreas.size()); Real allMins[noOfColoredAreas], allMaxs[noOfColoredAreas]; for (int i = 0; i < noOfColoredAreas; i++) { allMins[i] = coloredAreas[i]->yRange.GetMin(); allMaxs[i] = coloredAreas[i]->yRange.GetMax(); } return {*min_element(allMins, allMins + noOfColoredAreas), *max_element(allMaxs, allMaxs + noOfColoredAreas)}; } bool MyLightEntity::overlapsWith(MyLightEntity* otherLight) { bool xOverlap = otherLight->getXRange().WithinMinBoundIncludedMaxBoundIncluded(getXRange().GetMax()) || getXRange().WithinMinBoundIncludedMaxBoundIncluded(otherLight->getXRange().GetMax()); bool yOverlap = otherLight->getYRange().WithinMinBoundIncludedMaxBoundIncluded(getYRange().GetMax()) || getYRange().WithinMinBoundIncludedMaxBoundIncluded(otherLight->getYRange().GetMax()); return xOverlap && yOverlap; } bool MyLightEntity::overlapsWith(const vector<MyLightEntity*>& otherLights) { for (auto &otherLight: otherLights) { if (overlapsWith(otherLight)) { return true; } } return false; } void MyLightEntity::calculateAxis(double maxY) { bool onX = Abs(position.GetY()) >= (maxY - lightDist); if (onX) { axis = position.GetY() < 0 ? Axis::DOWN : Axis::UP; } else { axis = position.GetX() < 0 ? Axis::LEFT : Axis::RIGHT; } } void MyLightEntity::calculateColoredAreas() { auto red = new ColoredArea(); auto blue = new ColoredArea(); auto green = new ColoredArea(); auto yellow = new ColoredArea(); vector<ColoredArea*> newAreas; CColor redColor = CColor::BLACK; CColor blueColor = CColor::GRAY20; CColor greenColor = CColor::GRAY40; CColor yellowColor = CColor::GRAY60; double length = 7.5; double width = 5.0; double centerWidth = 1.0 - width; double lowerWidth = centerWidth - width; int lowerDiff = 2; switch (axis) { case Axis::UP : newAreas = {blue, green, yellow}; configureArea(blue, blueColor, 0, length, centerWidth, lowerDiff); configureArea(green, greenColor, -lowerDiff, length, lowerWidth, centerWidth); configureArea(yellow, yellowColor, -length, -lowerDiff, lowerWidth, centerWidth); break; case Axis::RIGHT : newAreas = {red, green, yellow}; configureArea(green, greenColor, centerWidth, lowerDiff, -length, 0); configureArea(yellow, yellowColor, lowerWidth, centerWidth, -length, lowerDiff); configureArea(red, redColor, lowerWidth, centerWidth, lowerDiff, length); break; case DOWN: newAreas = {red, blue, yellow}; configureArea(yellow, yellowColor, -length, 0, -lowerDiff, -centerWidth); configureArea(red, redColor, -length, lowerDiff, -centerWidth, -lowerWidth); configureArea(blue, blueColor, lowerDiff, length, -centerWidth, -lowerWidth); break; case LEFT: newAreas = {red, blue, green}; configureArea(red, redColor, -lowerDiff, -centerWidth, 0, length); configureArea(blue, blueColor, -centerWidth, -lowerWidth, -lowerDiff, length); configureArea(green, greenColor, -centerWidth, -lowerWidth, -length, -lowerDiff); break; } coloredAreas.insert(coloredAreas.end(), newAreas.begin(), newAreas.end()); } void MyLightEntity::configureArea(MyLightEntity::ColoredArea *area, CColor c, double xMinFactor, double xMaxFactor, double yMinFactor, double yMaxFactor) const { area->color = c; area->xRange = {position.GetX() + (xMinFactor * lightDist), position.GetX() + (xMaxFactor * lightDist) }; area->yRange = {position.GetY() + (yMinFactor * lightDist), position.GetY() + (yMaxFactor*lightDist) }; } CLightEntity *MyLightEntity::createEntity() { return new CLightEntity( "ld" + to_string(id), position, color, 7.0); } bool MyLightEntity::isBotNearby(Bot *bot) { return find(assignedBots.begin(), assignedBots.end(), bot->entity->GetId()) != assignedBots.end(); } CColor *MyLightEntity::getColorForPosition(CVector2 pos) { // for (auto *area : coloredAreas) { // if (lightArea.xRange.WithinMinBoundIncludedMaxBoundExcluded(pos.GetX()) && lightArea.yRange.WithinMinBoundIncludedMaxBoundExcluded(pos.GetY())){ // return &lightArea.color; // } // } for (auto *area : coloredAreas) { if (isPosInRange(pos, area->xRange, area->yRange)){ return &area->color; } } return nullptr; } bool MyLightEntity::isPosInRange(CVector2 pos, CRange<Real> xRange, CRange<Real> yRange) { return xRange.WithinMinBoundIncludedMaxBoundExcluded(pos.GetX()) && yRange.WithinMinBoundIncludedMaxBoundExcluded(pos.GetY()); } MyLightEntity::ColoredArea *MyLightEntity::getEntryArea() { return entryArea; }
#include "livingFigure.h" LivingFigure::LivingFigure(std::string name, Point offset) : Figure( name, offset, true, true,0){ /* for(int i = 0; i < triangles.size(); i++){ triangles[i].points[0].x-=this->offset.x;triangles[i].points[0].y-=this->offset.y; triangles[i].points[1].x-=this->offset.x;triangles[i].points[1].y-=this->offset.y; triangles[i].points[2].x-=this->offset.x;triangles[i].points[2].y-=this->offset.y; } */ /* for(int i = 0; i < collision.size(); i++){ this->collision[i].p1.x-=this->offset.x; this->collision[i].p2.x-=this->offset.x; this->collision[i].p1.y-=this->offset.y; this->collision[i].p2.y-=this->offset.y; } */ } LivingFigure::~LivingFigure(){ } Point LivingFigure::simulateMove(Point direction){ Point p; p.x = this->offset.x + direction.x; p.y = this->offset.y + direction.y; return p; } void LivingFigure::draw(){ //std::cout << "triangles size: "<< triangles.size() << std::endl; glColor3f(100,0,0); glBegin(GL_TRIANGLES); for(int i = 0; i < triangles.size();i++){ glVertex3f((triangles[i].points[0].x+this->offset.x),(triangles[i].points[0].y+this->offset.y),0); glVertex3f((triangles[i].points[1].x+this->offset.x),(triangles[i].points[1].y+this->offset.y),0); glVertex3f((triangles[i].points[2].x+this->offset.x),(triangles[i].points[2].y+this->offset.y),0); } glEnd(); } void LivingFigure::setPosition(Point p){ this->offset.x = p.x; this->offset.y = p.y; }
#include"pch.h" #include "MazeTraversal.h" #include<iostream> #include<string> #include<fstream> using namespace std; MazeTraversal::MazeTraversal(int size ):size(size){ maze = new char* [size]; for (int i = 0; i < size; i++) { maze[i] = new char[size]; } for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { maze[i][j] = NULL; } } LoadMaze(); curr_col = 0; start_col = 0; for (int i = 0; i < size; i++) { if (maze[i][curr_col] == '.') { curr_row = i; start_row = i; } } end_col = size - 1; for (int i = 0; i < size; i++) { if (maze[i][end_col] == '.') { end_row = i; break; } else { end_row = -1; } } Dir = 'R'; cellHeightPx = 50; cellWidthPx = 50; } void MazeTraversal::LoadMaze(){ // call in constructor ifstream input; char c; int i = 0,j = 0; input.open("maze.txt"); if (input.fail()) { cout << "UNABLE TO OPEN FILE" << endl; } if (input.is_open()) { while (input >> c) { maze[i][j] = c; j++; if (j % 12 == 0) { i++; j = 0; } } } input.close(); } void MazeTraversal::moveUp() { if (maze[curr_row - 1][curr_col] == '.') { Beep(100, 50); Dir = 'U'; curr_row = curr_row - 1; } //noend /*if (curr_col == end_col - 1 && end_row == -1 && curr_row == this->size - 2) { end_row = start_row; end_col = start_col; }*/ } void MazeTraversal::moveLeft() { if (maze[curr_row][curr_col - 1] == '.') { Beep(100, 50); Dir = 'L'; curr_col = curr_col - 1; } //noend /*if (curr_col == end_col - 1 && end_row == -1 && curr_row == this->size - 2) { end_row = start_row; end_col = start_col; }*/ } void MazeTraversal::moveDown() { if (maze[curr_row + 1][curr_col] == '.') { Beep(100, 50); Dir = 'D'; curr_row = curr_row + 1; } //noend /*if (curr_col == end_col - 1 && end_row == -1 && curr_row == this->size - 2) { end_row = start_row; end_col = start_col; }*/ } void MazeTraversal::moveRight() { if (maze[curr_row][curr_col + 1] == '.') { Beep(100, 50); Dir = 'R'; curr_col = curr_col + 1; } //noend /*if (curr_col == end_col - 1 && end_row == -1 && curr_row == this->size - 2) { end_row = start_row; end_col = start_col; }*/ } bool MazeTraversal::DestinationReached(){ if (this->curr_col == this->end_col && this->curr_row == this->end_row) { return true; } return false; } void MazeTraversal::display() { for (int i = 0; i < this->size; i++) { for (int j = 0; j < this->size; j++) { cout << this->maze[i][j]; } cout << endl; } } void MazeTraversal::moveToNextCell() { // it will be needed for automation //ifnoend /*if (curr_col == end_col - 1 && end_row == -1 && curr_row == this->size-2) { end_row = start_row; end_col = start_col; }*/ //current if (curr_row == start_row && curr_col == start_col) { moveRight(); } //1 left and bottom wall else if (maze[curr_row][curr_col - 1] == '#' && maze[curr_row + 1][curr_col] == '#' && maze[curr_row - 1][curr_col] == '.' && maze[curr_row][curr_col + 1] == '.') { if (Dir == 'L') { //Dir = 'U'; moveUp(); } else if (Dir == 'D') { //Dir = 'R'; moveRight(); } } //2 up and down wall else if (maze[curr_row - 1][curr_col] == '#' && maze[curr_row + 1][curr_col] == '#' && maze[curr_row][curr_col + 1] == '.' && maze[curr_row][curr_col - 1] == '.') { if (Dir == 'R') { moveRight(); } else if (Dir == 'L') { moveLeft(); } else if (Dir == 'D') { moveDown(); } else if (Dir == 'U') { moveUp(); } } //3 right and botton wall else if (maze[curr_row][curr_col+1] == '#' && maze[curr_row+1][curr_col] == '#' && maze[curr_row][curr_col-1] == '.' && maze[curr_row-1][curr_col] == '.') { if (Dir == 'R') { //Dir = 'U'; moveUp(); } else if (Dir == 'D') { //Dir = 'L'; moveLeft(); } } //4 left and up wall else if (maze[curr_row][curr_col-1] == '#' && maze[curr_row-1][curr_col] == '#' && maze[curr_row][curr_col+1] == '.' && maze[curr_row+1][curr_col] == '.') { if (Dir == 'U') { //Dir = 'R'; moveRight(); } else if (Dir == 'L') { //Dir = 'D'; moveDown(); } } //5 right and up wall else if (maze[curr_row][curr_col+1] == '#' && maze[curr_row-1][curr_col] == '#' && maze[curr_row][curr_col-1] == '.' && maze[curr_row+1][curr_col] == '.') { if (Dir == 'R') { //Dir = 'D'; moveDown(); } else if (Dir == 'U') { //Dir = 'L'; moveLeft(); } } //6 wall on bottom only else if (maze[curr_row+1][curr_col] == '#' && maze[curr_row][curr_col-1] == '.' && maze[curr_row][curr_col+1] == '.' && maze[curr_row-1][curr_col] == '.') { if (Dir == 'D') { //Dir = 'L'; moveLeft(); } else if (Dir == 'R') { //Dir = 'R'; moveRight(); } else if (Dir == 'L') { //Dir = 'U'; moveUp(); } } //7 wall on top, bottom, left else if (maze[curr_row-1][curr_col] == '#' && maze[curr_row+1][curr_col] == '#' && maze[curr_row][curr_col-1] == '#' && maze[curr_row][curr_col+1] == '.') { if (Dir == 'L') { //Dir = 'R'; moveRight(); } } //8 no wall on top,bottom,right and left else if (maze[curr_row+1][curr_col] == '.' && maze[curr_row-1][curr_col] == '.' && maze[curr_row][curr_col+1] == '.' && maze[curr_row][curr_col-1] == '.') { if (Dir == 'R') { //Dir = 'D'; moveDown(); } else if (Dir == 'U') { //Dir = 'R'; moveRight(); } else if (Dir == 'L') { //Dir = 'U'; moveUp(); } else if (Dir == 'D') { //Dir = 'L'; moveLeft(); } } //9 wall to left only else if (maze[curr_row][curr_col-1] == '#' && maze[curr_row-1][curr_col] == '.' && maze[curr_row+1][curr_col] == '.' && maze[curr_row][curr_col+1] == '.') { if (Dir == 'D') { //Dir = 'D'; moveDown(); } else if (Dir == 'U') { //Dir = 'R'; moveRight(); } else if (Dir == 'L') { //Dir = 'U'; moveUp(); } } //10 wall on top only else if (maze[curr_row-1][curr_col] == '#' && maze[curr_row+1][curr_col] == '.' && maze[curr_row][curr_col-1] == '.' && maze[curr_row][curr_col+1] == '.') { if (Dir == 'R') { //Dir = 'D'; moveDown(); } else if (Dir == 'L') { //Dir = 'L'; moveLeft(); } else if (Dir == 'U') { //Dir = 'R'; moveRight(); } } //11 wall on right only else if (maze[curr_row][curr_col+1] == '#' && maze[curr_row][curr_col-1] == '.' && maze[curr_row+1][curr_col] == '.' && maze[curr_row-1][curr_col] == '.') { if (Dir == 'D') { //Dir = 'L'; moveLeft(); } else if (Dir == 'U') { //Dir = 'U'; moveUp(); } else if (Dir == 'R') { // Dir = 'D'; moveDown(); } } //12 wall on top,right,left else if (maze[curr_row-1][curr_col] == '#' && maze[curr_row][curr_col+1] == '#' && maze[curr_row][curr_col-1] == '#' && maze[curr_row+1][curr_col] == '.') { if (Dir == 'U') { //Dir = 'D'; moveDown(); } } //13 wall on right,up and down else if (maze[curr_row-1][curr_col] == '#' && maze[curr_row][curr_col+1] == '#' && maze[curr_row+1][curr_col] == '#' && maze[curr_row][curr_col-1] == '.') { if (Dir == 'R') { //Dir = 'L'; moveLeft(); } } //14 wall on bottom,left,right else if (maze[curr_row+1][curr_col] == '#' && maze[curr_row][curr_col+1] == '#' && maze[curr_row][curr_col-1] == '#' && maze[curr_row-1][curr_col] == '.') { if (Dir == 'D') { //Dir = 'U'; moveUp(); } } //15 right and left wall else if (maze[curr_row ][curr_col-1] == '#' && maze[curr_row ][curr_col+1] == '#'&& maze[curr_row - 1][curr_col] == '.' && maze[curr_row + 1][curr_col] == '.') { if (Dir == 'R') { moveRight(); } else if (Dir == 'L') { moveLeft(); } else if (Dir == 'D') { moveDown(); } else if (Dir == 'U') { moveUp(); } } //ifnoend //handeled in move functions } MazeTraversal::~MazeTraversal() { for (int i = 0; i < this->size; i++) { delete[]maze[i]; } delete[]maze; } //getter functions int MazeTraversal::getCellWidthPx() { return this->cellWidthPx; } int MazeTraversal::getCellHeightPx() { return this->cellHeightPx; } int MazeTraversal::getSize() { return this->size; } int MazeTraversal::getStartRow() { return this->start_row; } int MazeTraversal::getStartCol() { return this->start_col; } int MazeTraversal::getCurrRow() { return this->curr_row; } int MazeTraversal::getCurrCol() { return this->curr_col; } char MazeTraversal::getDir() { return this->Dir; } char MazeTraversal::getCellValueAt(int i, int j) { if (i >= 0 && i < this->size) { if (j >= 0 && j < this->size) { return this->maze[i][j]; } } } bool MazeTraversal::noend() { int endrow; for (int i = this->size - 2; i >=1; i--) { if (this->maze[i][this->size - 2] == '.') { endrow = i; break; } } if (curr_col == end_col - 1 && end_row == -1 && curr_row == endrow) { end_row = start_row; end_col = start_col; return true; } return false; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2007 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef MEMORY_OPALLOCINFO_H #define MEMORY_OPALLOCINFO_H /** \file * * \brief Include file for OpAllocInfo object * * This file declares the OpAllocInfo object, which is created and * populated at the various functions used to debug memory allocations. * * Example: The \c OpMemDebug_OpMalloc() function is called for memory * debugging builds when \c op_malloc() is used. The * \c OpMemDebug_OpMalloc() function will create an OpAllocInfo object * on the stack, populate it with sensible data, and pass it along * to the memory debugging database for safekeeping (copying). * * The OpAllocInfo class primarily contains the call site info, the * stack trace and type and details of the allocation. * * This class is typically instantiated on the heap by use of the * \c OPALLOCINFO(info,type) macro (this makes it possible to * recover stack-info where the stack-frame is non-existent or * special through assembly or inlined methods). * * \author Morten Rolland, mortenro@opera.com */ #ifdef ENABLE_MEMORY_DEBUGGING #ifdef MEMORY_CALLSTACK_DATABASE # include "modules/memtools/memtools_callstack.h" #endif struct OpMemGuardInfo; // // Calculate MEMORY_ALLOCINFO_STACK_DEPTH as the maximum of: // MEMORY_KEEP_ALLOCSTACK, MEMORY_KEEP_REALLOCSTACK and MEMORY_KEEP_FREESTACK // using preprocessor only (so we can trust the macro for array declarations). // #if MEMORY_KEEP_ALLOCSTACK > 0 # define MEMORY_ALLOCINFO_STACK_DEPTH MEMORY_KEEP_ALLOCSTACK #else # define MEMORY_ALLOCINFO_STACK_DEPTH 0 #endif #if MEMORY_KEEP_REALLOCSTACK > MEMORY_ALLOCINFO_STACK_DEPTH # undef MEMORY_ALLOCINFO_STACK_DEPTH # define MEMORY_ALLOCINFO_STACK_DEPTH MEMORY_KEEP_REALLOCSTACK #endif #if MEMORY_KEEP_FREESTACK > MEMORY_ALLOCINFO_STACK_DEPTH # undef MEMORY_ALLOCINFO_STACK_DEPTH # define MEMORY_ALLOCINFO_STACK_DEPTH MEMORY_KEEP_FREESTACK #endif #if MEMORY_ALLOCINFO_STACK_DEPTH <= 0 // Create an OpAllocInfo object for allocation information #define OPALLOCINFO(info,file,line,obj,type) \ OpAllocInfo info(file,line,obj,type) #else // Create an OpAllocInfo object that includes call-stack info #define OPALLOCINFO(info,file,line,obj,type) \ OPGETCALLSTACK(MEMORY_ALLOCINFO_STACK_DEPTH); \ OpAllocInfo info(file,line,obj,type); \ OPCOPYCALLSTACK(info.SetStack(), MEMORY_ALLOCINFO_STACK_DEPTH) #endif /** * \brief Container Object to hold various information about an allocation * * An object of this type is created when an allocation (or deallocation) * happens, and its pointer is passed around to easilly propagate various * information regarding the (de-)allocation. * * Information passed around is: source file and line number of allocation * (through __FILE__ and __LINE__ and an OpSrcSite object), the * stack-trace of the allocation, the name of the object, what kind of * allocation, number of objects in an array allocation, etc. * * All this information may not be available on all platforms, or stored * for later use. * * This object will typically be allocated on the stack by the * \c OPALLOCINFO() macro, which will possibly recover the stack-frame * or return-addresses as well as allocating the \c OpAllocInfo object. */ class OpAllocInfo { public: /** * \brief Initialize a created object * * The \c file and \c line arguments are typically initialized * from \c __FILE__ and \c __LINE__ macros, the object name from the * \c \#obj construct of the preprocessor (make something into a string), * and the type is one of the \c MEMORY_FLAG_* defines. * * \param file The filename of the source code file of the allocation * \param line The line number in the soruce code file of the allocation * \param obj The name of the allocated object, or NULL when not available * \param type One of the MEMORY_FLAG_* define values */ OpAllocInfo(const char* file, int line, const char* obj, UINT32 type); /** * \brief Initialize from an existing allocation * * This is used under certain circumstances, e.g. when reporting * an allocation after it has actually taken place. This happens e.g * during startup, when the log is written slightly later than the * first few allocations. * * \param mgi The memory guard info from which to reconstruct */ OpAllocInfo(OpMemGuardInfo* mgi); /** * \brief Set the number of array elements of the allocation * * When allocating an array (through operator new[] etc.) the size of * the array can be provided from the \c OP_NEWA() macro so it is * available to the memory debugger. * * \param num The number of objects/elements created by new[] */ void SetArrayElementCount(size_t num) { array_count = num; } /** * \brief Set the size of a single element/object * * When allocating an array (through operator new[] etc.) it is * possible to provide 'sizeof(obj)' in the \c OP_NEW() macro so * the size of each element will be available to the memory debugger. * * Note: dividing the size of the allocation (in bytes) by the * number of elements may not yield correct results when extra * memory is set aside during the allocation for book-keeping. * * \param size The size in bytes of a single element/object allocated */ void SetArrayElementSize(size_t size) { array_elm_size = size; } /** * \brief Retriev the flags of the object */ UINT32 GetFlags(void) { return flags; } /** * \brief Set the flags of the object * * Setting the flags of the object it needed sometimes when e.g. * a realloc operation in practice turned out to be an allocation. */ void SetFlags(UINT32 f) { flags = f; } /** * \brief Retrieve the OpSrcSite ID of the allocation site */ UINT32 GetSiteId(void) const { return allocsite_id; } #if MEMORY_ALLOCINFO_STACK_DEPTH > 0 /** * \brief Retrieve the call stack of the allocation site * * The macro \c MEMORY_ALLOCINFO_STACK_DEPTH holds the size of * the \c UINTPTR array that contains the stack. The stack[0] * element is the most leaf-function on the stack, while * stack[MEMORY_ALLOCINFO_STACK_DEPTH-1] is the oldest entry. * There may be 0 values in the array towards the end if the * return address could not be computed (or there is none). * * \returns A pointer to an array of UINTPTR return addresses */ const UINTPTR* GetStack(void) const { return stack; } UINTPTR* SetStack(void) { return stack; } #endif #if MEMORY_ALLOCINFO_STACK_DEPTH <= 0 const UINTPTR* GetStack(void) const { return &zero_addr; } #endif #ifdef MEMORY_CALLSTACK_DATABASE OpCallStack* GetOpCallStack(int size); #endif const char* GetObject(void) const { return object; } private: size_t array_count; size_t array_elm_size; UINT32 flags; UINT32 allocsite_id; const char* object; #if MEMORY_ALLOCINFO_STACK_DEPTH > 0 # ifdef MEMORY_CALLSTACK_DATABASE OpCallStack* callstack; # endif UINTPTR stack[MEMORY_ALLOCINFO_STACK_DEPTH]; #else UINTPTR zero_addr; #endif }; #endif // ENABLE_MEMORY_DEBUGGING #endif // MEMORY_OPALLOCINFO_H
/******************************************************************************* Copyright (c) 2010, Steve Lesser Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2)Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3) The name of contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL STEVE LESSER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ /** @file XMLParser.h */ #pragma once #include "tinyxml/tinyxml.h" /** * simple parser for reading in XML files and nodes */ class XMLParser { public: /** * default constructor, does not load any files */ XMLParser() {} /** * basic constructor, starts at the root node of the file */ XMLParser(const char* fileName); /** * destructor */ ~XMLParser(); /** * sets the root node to the root of the document * @return true if successful, false otherwise */ bool resetRoot(); /** * sets the root node which is the parent point for future searches * @param rootName name of the new root node. Must be a child of the current root * @return true if successful, false otherwise */ bool setNewRoot(const char* rootName); /** * sets the result int value to the value found in the attribute name node * @param attributeName name of the node to find the int. Node must be a child of the current root node * @param result pointer to the location to store the attribute's value * @return true if successful, false otherwise */ bool getInt(const char* attributeName, int* result); /** * sets the result unsigned int value to the value found in the attribute name node * @param attributeName name of the node to find the unsigned int. Node must be a child of the current root node * @param result pointer to the location to store the attribute's value * @return true if successful, false otherwise */ bool getUnsignedInt(const char* attributeName, unsigned int* result); /** * sets the result float value to the value found in the attribute name node * @param attributeName name of the node to find the float. Node must be a child of the current root node * @param result pointer to the location to store the attribute's value * @return true if successful, false otherwise */ bool getFloat(const char* attributeName, float* result); /** * sets the result 2 float values to the values found in the node's x and y children nodes. * @param attributeName name of the node to find the floats. Node must be a child of the current root node * @param result array specifying the location to store the attribute's value * @return true if successful, false otherwise * @note Given the xml data: * \code * <xLowerBound> * <x>-1</x> * <y>-1</y> * </xLowerBound> \endcode * with code: * \code * float floatArray[2]; * getFloat2("xLowerBound",floatArray) * \endcode * floatArray will become populated as {-1,-1} */ bool getFloat2(const char* attributeName, float result[2]); /** * sets the result 3 float values to the values found in the node's x y and z children nodes. * @param attributeName name of the node to find the floats. Node must be a child of the current root node * @param result array specifying the location to store the attribute's value * @return true if successful, false otherwise * @note Given the xml data: * \code * <lowerLeftCorner> * <x>-1</x> * <y>-1</y> * <z>-1</z> * </lowerLeftCorner> \endcode * with code: * \code * float floatArray[3]; * getFloat3("lowerLeftCorner",floatArray) * \endcode * floatArray will become populated as {-1,-1,-1} */ bool getFloat3(const char* attributeName, float result[3]); private: bool m_error; char m_fileName[128]; TiXmlDocument m_document; TiXmlNode* m_root; };
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "interactive_state.hpp" #include <chrono> #include <iostream> #include "logger.hpp" #include "schedule_state.hpp" #include "sql_parser.hpp" #include "sql_query_creator.hpp" #include "orkhestra_exception.hpp" using orkhestrafs::dbmstodspi::GraphProcessingFSMInterface; using orkhestrafs::dbmstodspi::InteractiveState; using orkhestrafs::dbmstodspi::ScheduleState; using orkhestrafs::dbmstodspi::StateInterface; using orkhestrafs::dbmstodspi::logging::Log; using orkhestrafs::dbmstodspi::logging::LogLevel; using orkhestrafs::sql_parsing::SQLParser; using orkhestrafs::sql_parsing::SQLQueryCreator; using orkhestrafs::dbmstodspi::OrkhestraException; auto InteractiveState::Execute(GraphProcessingFSMInterface* fsm) -> std::unique_ptr<StateInterface> { Log(LogLevel::kTrace, "In interactive state"); switch (GetOption(fsm)) { case 1: fsm->PrintHWState(); break; case 2: if (fsm->GetFPGASpeed() == 100) { fsm->SetClockSpeed(300); } else { fsm->SetClockSpeed(100); } fsm->LoadStaticBitstream(); break; case 3: std::cout << "Enter new time limit in seconds: " << std::endl; fsm->ChangeSchedulingTimeLimit(GetDouble()); break; case 4: std::cout << "Enter new time limit in seconds: " << std::endl; fsm->ChangeExecutionTimeLimit(GetInteger()); break; case 5: { auto query = GetQueryFromInput(); try { auto begin = std::chrono::steady_clock::now(); fsm->AddNewNodes(GetExecutionPlanFile(std::move(query))); auto end = std::chrono::steady_clock::now(); long planning = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin) .count(); std::cout << "PLANNING: " << planning << " ms" << std::endl; fsm->SetStartTimer(); return std::make_unique<ScheduleState>(); } catch (OrkhestraException exception) { if (fsm->IsSWBackupEnabled()) { SQLParser::PrintResults(std::move(query.second), std::move(query.first)); } else { throw std::runtime_error("Python call unsuccessful!"); } } break; } case 6: fsm->SetFinishedFlag(); break; case 7: fsm->LoadStaticBitstream(); break; case 8: { auto new_bitstream = GetBitstreamToLoad(fsm->GetCurrentHW()); if (new_bitstream.operation_type != QueryOperationType::kPassThrough) { fsm->LoadBitstream(new_bitstream); } break; } case 9: if (fsm->IsHWPrintEnabled()){ fsm->SetHWPrint(false); } else { fsm->SetHWPrint(true); } break; default: std::cout << "Incorrect option" << std::endl; } return std::make_unique<InteractiveState>(); } void InteractiveState::PrintOutGivenOptions( const std::vector<std::string> list_of_options) { std::cout << "0: Go back" << std::endl; for (int option_i = 0; option_i < list_of_options.size(); option_i++) { std::cout << option_i + 1 << ": " << list_of_options.at(option_i) << std::endl; } } auto InteractiveState::GetBitstreamToLoad( const std::map<QueryOperationType, OperationPRModules> bitstream_map) -> ScheduledModule { bool bitstream_choice_complete = false; ScheduledModule chosen_bitstream = { "", QueryOperationType::kPassThrough, "", {0, 0}, false}; bool operation_chosen = false; QueryOperationType current_operation = QueryOperationType::kAddition; std::vector<QueryOperationType> list_of_operations; std::vector<std::string> list_of_operation_strings; std::vector<std::string> list_of_bitstreams; for (const auto& [op_type, data] : bitstream_map) { list_of_operation_strings.push_back(operation_names_.at(op_type)); list_of_operations.push_back(op_type); } while (!bitstream_choice_complete) { if (operation_chosen) { std::cout << "Choose bitstream: " << std::endl; PrintOutGivenOptions(list_of_bitstreams); auto answer = GetInteger(); if (answer == 0) { operation_chosen = false; list_of_bitstreams.clear(); } else { bitstream_choice_complete = true; std::string chosen_bitstream_name = list_of_bitstreams.at(answer - 1); chosen_bitstream = {"", current_operation, chosen_bitstream_name, {bitstream_map.at(current_operation) .bitstream_map.at(chosen_bitstream_name) .fitting_locations.front(), bitstream_map.at(current_operation) .bitstream_map.at(chosen_bitstream_name) .fitting_locations.front() + bitstream_map.at(current_operation) .bitstream_map.at(chosen_bitstream_name) .length - 1}}; } } else { std::cout << "Choose operation: " << std::endl; PrintOutGivenOptions(list_of_operation_strings); auto answer = GetInteger(); if (answer == 0) { bitstream_choice_complete = true; } else { current_operation = list_of_operations.at(answer - 1); operation_chosen = true; for (const auto& [bitstream, data] : bitstream_map.at(current_operation).bitstream_map) { list_of_bitstreams.push_back(bitstream); } } } } return chosen_bitstream; } auto InteractiveState::GetQueryFromInput() -> std::pair<std::string, std::string> { std::cout << "Enter DB name:" << std::endl; auto database = GetStdInput(); database.pop_back(); std::cout << "Enter filename with query:" << std::endl; auto query_filename = GetStdInput(); query_filename.pop_back(); return {std::move(database), std::move(query_filename)}; } auto InteractiveState::GetExecutionPlanFile(const std::pair<std::string, std::string>& input) -> std::string { SQLQueryCreator sql_creator; SQLParser::CreatePlan(sql_creator, std::move(input.second), std::move(input.first)); return sql_creator.ExportInputDef(); } void InteractiveState::PrintOptions(GraphProcessingFSMInterface* fsm) { std::cout << std::endl; std::cout << "===========MENU==========" << std::endl; std::cout << "Which operation would you like to do?" << std::endl; std::cout << "1: Print HW state" << std::endl; if (fsm->GetFPGASpeed() == 300) { std::cout << "2: Change FPGA speed (currently MAX - 300 MHz)" << std::endl; } else if (fsm->GetFPGASpeed() == 100) { std::cout << "2: Change FPGA speed (currently 100 MHz)" << std::endl; } else { throw std::runtime_error("Unsupported clock speed!"); } std::cout << "3: Change scheduling time limit" << std::endl; std::cout << "4: Change execution time limit" << std::endl; std::cout << "5: Run SQL" << std::endl; std::cout << "6: EXIT" << std::endl; std::cout << "7: Reset" << std::endl; std::cout << "8: Load module" << std::endl; if (fsm->IsHWPrintEnabled()) { std::cout << "9: Disable HW print" << std::endl; } else { std::cout << "9: Enable HW print" << std::endl; } std::cout << "Choose one of the supported options by typing a valid number " "and a ';'" << std::endl; } auto InteractiveState::GetOption(GraphProcessingFSMInterface* fsm) -> int { PrintOptions(fsm); return GetInteger(); } auto InteractiveState::GetInteger() -> int { std::string answer = ""; bool is_number = false; while (!is_number) { answer = GetStdInput(); answer.pop_back(); is_number = std::all_of(answer.begin(), answer.end(), [](auto digit) { return isdigit(digit); }); if (!is_number) { std::cout << "Invalid input" << std::endl; } } return std::stoi(answer); } auto InteractiveState::GetDouble() -> double { std::string answer = ""; bool is_number = false; while (!is_number) { answer = GetStdInput(); answer.pop_back(); is_number = std::all_of(answer.begin(), answer.end(), [](auto digit) { return isdigit(digit) || digit == '.'; }); if (!is_number) { std::cout << "Invalid input" << std::endl; } } return std::stod(answer); } auto InteractiveState::GetStdInput() -> std::string { std::string current_input = ""; std::cout << "> "; std::cin >> current_input; while (current_input.back() != ';') { std::string more_current_input = ""; std::cout << "> "; std::cin >> more_current_input; current_input += more_current_input; } std::cout << std::endl; return current_input; } // Lazily put option functions into this class rather than the FSM or even // better a separate class
#include "StdAfx.h" #include <GameLib.h> // エントリ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { // ゲームを実行 GameLib *game = new GameLib(); game->DoMainLoop(); delete game; return 0; }
#include "VertexDescription.h" #include "GraphicsInterface.h" using namespace Graphics; const VertexInputDescription& PosVertexDescription::GetDescription() { static VertexInputDescription::VertexInputElement k_Elements[] = { {"POSITION", 0, Format::RGB_32_Float, 0} }; static const VertexInputDescription k_Desc = { _countof(k_Elements), k_Elements }; return k_Desc; } const VertexInputDescription& PosColorVertexDescription::GetDescription() { static VertexInputDescription::VertexInputElement k_Elements[] = { {"POSITION", 0, Format::RGB_32_Float, 0}, {"COLOR", 0, Format::RGB_32_Float, 12} }; static const VertexInputDescription k_Desc = { _countof(k_Elements), k_Elements }; return k_Desc; } const VertexInputDescription& Graphics::Pos2TexCoordColorDescription::GetDescription() { static VertexInputDescription::VertexInputElement k_Elements[] = { {"POSITION", 0, Format::RG_32_Float, 0}, {"TEXCOORD", 0, Format::RG_32_Float, 8}, {"COLOR", 0, Format::RGBA_8_Unorm, 16} }; static const VertexInputDescription k_Desc = { _countof(k_Elements), k_Elements }; return k_Desc; } const VertexInputDescription& PosNormalTangentTexCoordDescription::GetDescription() { static VertexInputDescription::VertexInputElement k_Elements[] = { {"POSITION", 0, Format::RGB_32_Float, 0}, {"NORMAL", 0, Format::RGB_32_Float, 12}, {"TANGENT", 0, Format::RGB_32_Float, 24}, {"TEXCOORD", 0, Format::RG_32_Float, 36}, }; static const VertexInputDescription k_Desc = { _countof(k_Elements), k_Elements }; return k_Desc; }
#ifndef LOCK_HEADER #define LOCK_HEADER #include <stdint.h> #include <unistd.h> class LockService { private: uint16_t WriteID; uint16_t ReadID; uint64_t MetaDataBaseAddress; public: LockService(uint64_t MetaDataBaseAddress); ~LockService(); uint64_t WriteLock(uint16_t NodeID, uint64_t Address); bool WriteUnlock(uint64_t key, uint16_t NodeID, uint64_t Address); uint64_t ReadLock(uint16_t NodeID, uint64_t Address); bool ReadUnlock(uint64_t key, uint16_t NodeID, uint64_t Address); }; #endif
#include "runtime_file_paths.h" namespace Constants { boost::filesystem::path RuntimeFilePaths::ui(boost::filesystem::current_path() / "ui"); boost::filesystem::path RuntimeFilePaths::ui_cache(ui / "cache"); boost::filesystem::path RuntimeFilePaths::ui_index(ui / "index.html"); std::string RuntimeFilePaths::ui_localhost_path("http://localhost:3000"); }
#include <stdio.h> #include <fstream> using namespace std; int checkExist(char* array,int size, char c){ /* * Zero is doesnt exist, returns location + 1 if exist. */ for (int i = 0; i< size; i++){ if(array[i] == c){ return i + 1; } } return 0; } int main(int argc, char **argv) { ifstream input; input.open("prepare.in", ios::in); int n; input>>n; int* practical, *theory, *diff; char* answer; practical = new int[n]; theory = new int[n]; answer = new char[n]; diff = new int[n]; for(int i = 0; i <n; i++){ input>>practical[i]; } for(int i = 0; i <n; i++){ input>>theory[i]; diff[i] = practical[i] - theory[i]; // Negative when Theory has higher value. Zero when equals. if (diff[i] > 0){ answer[i] = 'P'; } else if (diff[i] < 0){ answer[i] = 'T'; } else{ answer[i] = 'X'; } } input.close(); //Check for Practical if (!checkExist(answer, n, 'P')){ int loc, FLAG = 0; loc = checkExist(answer, n, 'X'); if(loc){ answer[loc - 1] = 'P'; FLAG = 1; } if(FLAG == 0){ int replace, maxNeg = -9999; for(int i = 0; i < n; i++){ if(maxNeg < diff[i]){ maxNeg = diff[i]; replace = i; } } answer[replace] = 'P'; } } //Check for Theory if (!checkExist(answer, n, 'T')){ int loc, FLAG = 0; loc = checkExist(answer, n, 'X'); if(loc){ answer[loc - 1] = 'T'; FLAG = 1; } if(FLAG == 0){ int replace, minPos = 9999; for(int i = 0; i < n; i++){ if(minPos > diff[i]){ minPos = diff[i]; replace = i; } } answer[replace] = 'T'; } } //Replace all X and calculate O/P int output = 0; for (int i = 0; i < n; i++){ if (answer[i] == 'X'){ answer[i] = 'P'; } if (answer[i] == 'P'){ output += practical[i]; } else{ output += theory[i]; } } ofstream op; op.open("prepare.out", ios::out); op<<output; op.close(); return 0; }
/* ============================================================================ Author : Zhirong Yang Copyright : Copyright by Zhirong Yang. All rights are reserved. Description : Stochastic Optimization for t-SNE ============================================================================ */ // Modified by John Lees #include <iterator> #include "wtsne.hpp" std::vector<double> wtsne(const std::vector<int> &I, const std::vector<int> &J, std::vector<double> &dists, const int nsamples, const double perplexity, const int maxIter, const int nRepuSamp, const double eta0, const bool bInit, const int n_threads, const unsigned int seed) { // Check input std::vector<double> Y, P; std::vector<double> weights(nsamples, 1.0); std::tie(Y, P) = wtsne_init<double>(I, J, dists, weights, perplexity, n_threads, seed); long long nn = weights.size(); long long ne = P.size(); // Set up random number generation std::random_device rd; std::mt19937 gen(rd()); std::discrete_distribution<> dist_de(P.begin(), P.end()); std::discrete_distribution<> dist_dn(weights.begin(), weights.end()); // SNE algorithm const double nsq = nn * (nn - 1); double Eq = 1.0; for (long long iter = 0; iter < maxIter; iter++) { double eta = eta0 * (1 - (double)iter / maxIter); eta = MAX(eta, eta0 * 1e-4); double c = 1.0 / (Eq * nsq); double qsum = 0; long long qcount = 0; double attrCoef = (bInit && iter < maxIter / 10) ? 8 : 2; double repuCoef = 2 * c / nRepuSamp * nsq; #pragma omp parallel for reduction(+ : qsum, qcount) num_threads(n_threads) for (int worker = 0; worker < n_threads; worker++) { std::vector<double> dY(DIM); std::vector<double> Yk_read(DIM); std::vector<double> Yl_read(DIM); // long long e = gsl_ran_discrete(gsl_r_ne, gsl_de) % ne; long long e = dist_de(gen) % ne; // fprintf(stderr, "e: %d", e); long long i = I[e]; long long j = J[e]; for (long long r = 0; r < nRepuSamp + 1; r++) { // fprintf(stderr, "r: %d", r); // fflush(stderr); long long k, l, k2; if (r == 0) { k = i; l = j; } else { k = dist_dn(gen) % nn; l = dist_dn(gen) % nn; } if (k == l) continue; long long lk = k * DIM; long long ll = l * DIM; double dist2 = 0.0; for (long long d = 0; d < DIM; d++) { #pragma omp atomic read Yk_read[d] = Y[d + lk]; #pragma omp atomic read Yl_read[d] = Y[d + ll]; dY[d] = Yk_read[d] - Yl_read[d]; dist2 += dY[d] * dY[d]; } double q = 1.0 / (1 + dist2); double g; if (r == 0) g = -attrCoef * q; else g = repuCoef * q * q; bool overwrite = false; for (long long d = 0; d < DIM; d++) { double gain = eta * g * dY[d]; double Yk_read_end, Yl_read_end; #pragma omp atomic capture Yk_read_end = Y[d + lk] += gain; #pragma omp atomic capture Yl_read_end = Y[d + ll] -= gain; if (Yk_read_end != Yk_read[d] + gain || Yl_read_end != Yl_read[d] - gain) { overwrite = true; break; } } if (!overwrite) { qsum += q; qcount++; } else { // Find another neighbour for (int d = 0; d < DIM; d++) { #pragma atomic write Y[d + lk] = Yk_read[d]; #pragma atomic write Y[d + ll] = Yl_read[d]; } r--; } } } Eq = (Eq * nsq + qsum) / (nsq + qcount); update_progress(iter, maxIter, eta, Eq); } std::cerr << std::endl << "Optimizing done" << std::endl; return Y; }
// Copyright (c) 2007-2017 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // 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) #pragma once #include <pika/config.hpp> #if defined(PIKA_HAVE_CXX20_COROUTINES) # include <pika/futures/detail/future_data.hpp> # include <pika/futures/traits/future_access.hpp> # include <pika/memory/intrusive_ptr.hpp> # include <pika/modules/allocator_support.hpp> # include <coroutine> # include <cstddef> # include <exception> # include <memory> # include <type_traits> # include <utility> /////////////////////////////////////////////////////////////////////////////// namespace pika::lcos::detail { template <typename Promise = void> using coroutine_handle = std::coroutine_handle<Promise>; using suspend_never = std::suspend_never; /////////////////////////////////////////////////////////////////////////// // this was removed from the TS, so we define our own struct suspend_if { bool is_ready_; constexpr explicit suspend_if(bool cond) noexcept : is_ready_(!cond) { } [[nodiscard]] constexpr bool await_ready() const noexcept { return is_ready_; } constexpr void await_suspend(coroutine_handle<>) const noexcept {} constexpr void await_resume() const noexcept {} }; /////////////////////////////////////////////////////////////////////////// // Allow using co_await with an expression which evaluates to // pika::future<T>. template <typename T> PIKA_FORCEINLINE bool await_ready(pika::future<T> const& f) noexcept { return f.is_ready(); } template <typename T, typename Promise> PIKA_FORCEINLINE void await_suspend(pika::future<T>& f, coroutine_handle<Promise> rh) { // f.then([=](future<T> result) {}); auto st = traits::detail::get_shared_state(f); st->set_on_completed([st, rh]() mutable { if (st->has_exception()) { rh.promise().set_exception(st->get_exception_ptr()); } rh(); }); } template <typename T> PIKA_FORCEINLINE T await_resume(pika::future<T>& f) { return f.get(); } // Allow wrapped futures to be unwrapped, if possible. template <typename T> PIKA_FORCEINLINE T await_resume(pika::future<pika::future<T>>& f) { return f.get().get(); } template <typename T> PIKA_FORCEINLINE T await_resume(pika::future<pika::shared_future<T>>& f) { return f.get().get(); } // Allow using co_await with an expression which evaluates to // pika::shared_future<T>. template <typename T> PIKA_FORCEINLINE bool await_ready(pika::shared_future<T> const& f) noexcept { return f.is_ready(); } template <typename T, typename Promise> PIKA_FORCEINLINE void await_suspend(pika::shared_future<T>& f, coroutine_handle<Promise> rh) { // f.then([=](shared_future<T> result) {}) auto st = traits::detail::get_shared_state(f); st->set_on_completed([st, rh]() mutable { if (st->has_exception()) { rh.promise().set_exception(st->get_exception_ptr()); } rh(); }); } template <typename T> PIKA_FORCEINLINE T await_resume(pika::shared_future<T>& f) { return f.get(); } /////////////////////////////////////////////////////////////////////////// // derive from future shared state as this will be combined with the // necessary stack frame for the resumable function template <typename T, typename Derived> struct coroutine_promise_base : pika::lcos::detail::future_data<T> { using base_type = pika::lcos::detail::future_data<T>; using init_no_addref = typename base_type::init_no_addref; using allocator_type = pika::detail::internal_allocator<char>; // the shared state is held alive by the coroutine coroutine_promise_base() : base_type(init_no_addref{}) { } pika::future<T> get_return_object() { pika::intrusive_ptr<Derived> shared_state(static_cast<Derived*>(this)); return pika::traits::future_access<pika::future<T>>::create(PIKA_MOVE(shared_state)); } constexpr suspend_never initial_suspend() const noexcept { return suspend_never{}; } suspend_if final_suspend() noexcept { // This gives up the coroutine's reference count on the shared // state. If this was the last reference count, the coroutine // should not suspend before exiting. return suspend_if{!this->base_type::requires_delete()}; } void destroy() noexcept override { coroutine_handle<Derived>::from_promise(*static_cast<Derived*>(this)).destroy(); } // allocator support for shared coroutine state [[nodiscard]] static void* allocate(std::size_t size) { using char_allocator = typename std::allocator_traits<allocator_type>::template rebind_alloc<char>; using traits = std::allocator_traits<char_allocator>; using unique_ptr = std::unique_ptr<char, pika::detail::allocator_deleter<char_allocator>>; char_allocator alloc{}; unique_ptr p(traits::allocate(alloc, size), pika::detail::allocator_deleter<char_allocator>{alloc}); return p.release(); } static void deallocate(void* p, std::size_t size) noexcept { using char_allocator = typename std::allocator_traits<allocator_type>::template rebind_alloc<char>; using traits = std::allocator_traits<char_allocator>; char_allocator alloc{}; traits::deallocate(alloc, static_cast<char*>(p), size); } }; } // namespace pika::lcos::detail /////////////////////////////////////////////////////////////////////////////// namespace std { // Allow for functions which use co_await to return a pika::future<T> template <typename T, typename... Ts> struct coroutine_traits<pika::future<T>, Ts...> { using allocator_type = pika::detail::internal_allocator<coroutine_traits>; struct promise_type : pika::lcos::detail::coroutine_promise_base<T, promise_type> { using base_type = pika::lcos::detail::coroutine_promise_base<T, promise_type>; promise_type() = default; template <typename U> void return_value(U&& value) { this->base_type::set_value(PIKA_FORWARD(U, value)); } void unhandled_exception() noexcept { this->base_type::set_exception(std::current_exception()); } [[nodiscard]] PIKA_FORCEINLINE static void* operator new(std::size_t size) { return base_type::allocate(size); } PIKA_FORCEINLINE static void operator delete(void* p, std::size_t size) noexcept { base_type::deallocate(p, size); } }; }; template <typename... Ts> struct coroutine_traits<pika::future<void>, Ts...> { using allocator_type = pika::detail::internal_allocator<coroutine_traits>; struct promise_type : pika::lcos::detail::coroutine_promise_base<void, promise_type> { using base_type = pika::lcos::detail::coroutine_promise_base<void, promise_type>; promise_type() = default; void return_void() { this->base_type::set_value(); } void unhandled_exception() noexcept { this->base_type::set_exception(std::current_exception()); } [[nodiscard]] PIKA_FORCEINLINE static void* operator new(std::size_t size) { return base_type::allocate(size); } PIKA_FORCEINLINE static void operator delete(void* p, std::size_t size) noexcept { base_type::deallocate(p, size); } }; }; // Allow for functions which use co_await to return an // pika::shared_future<T> template <typename T, typename... Ts> struct coroutine_traits<pika::shared_future<T>, Ts...> { using allocator_type = pika::detail::internal_allocator<coroutine_traits>; struct promise_type : pika::lcos::detail::coroutine_promise_base<T, promise_type> { using base_type = pika::lcos::detail::coroutine_promise_base<T, promise_type>; promise_type() = default; template <typename U> void return_value(U&& value) { this->base_type::set_value(PIKA_FORWARD(U, value)); } void unhandled_exception() noexcept { this->base_type::set_exception(std::current_exception()); } [[nodiscard]] PIKA_FORCEINLINE static void* operator new(std::size_t size) { return base_type::allocate(size); } PIKA_FORCEINLINE static void operator delete(void* p, std::size_t size) noexcept { base_type::deallocate(p, size); } }; }; template <typename... Ts> struct coroutine_traits<pika::shared_future<void>, Ts...> { using allocator_type = pika::detail::internal_allocator<coroutine_traits>; struct promise_type : pika::lcos::detail::coroutine_promise_base<void, promise_type> { using base_type = pika::lcos::detail::coroutine_promise_base<void, promise_type>; promise_type() = default; void return_void() { this->base_type::set_value(); } void unhandled_exception() noexcept { this->base_type::set_exception(std::current_exception()); } [[nodiscard]] PIKA_FORCEINLINE static void* operator new(std::size_t size) { return base_type::allocate(size); } PIKA_FORCEINLINE static void operator delete(void* p, std::size_t size) noexcept { base_type::deallocate(p, size); } }; }; } // namespace std #endif // PIKA_HAVE_CXX20_COROUTINES
// Created on: 1991-02-20 // Created by: Jacques GOUSSARD // Copyright (c) 1991-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 _IntAna2d_IntPoint_HeaderFile #define _IntAna2d_IntPoint_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <gp_Pnt2d.hxx> #include <Standard_Boolean.hxx> //! Geometrical intersection between two 2d elements. class IntAna2d_IntPoint { public: DEFINE_STANDARD_ALLOC //! Create an intersection point between 2 parametric 2d lines. //! X,Y are the coordinate of the point. U1 is the parameter //! on the first element, U2 the parameter on the second one. Standard_EXPORT IntAna2d_IntPoint(const Standard_Real X, const Standard_Real Y, const Standard_Real U1, const Standard_Real U2); //! Create an intersection point between a parametric 2d line, //! and a line given by an implicit equation (ImplicitCurve). //! X,Y are the coordinate of the point. U1 is the parameter //! on the parametric element. //! Empty constructor. It's necessary to use one of //! the SetValue method after this one. Standard_EXPORT IntAna2d_IntPoint(const Standard_Real X, const Standard_Real Y, const Standard_Real U1); Standard_EXPORT IntAna2d_IntPoint(); //! Set the values for a "non-implicit" point. Standard_EXPORT virtual void SetValue (const Standard_Real X, const Standard_Real Y, const Standard_Real U1, const Standard_Real U2); //! Set the values for an "implicit" point. Standard_EXPORT virtual void SetValue (const Standard_Real X, const Standard_Real Y, const Standard_Real U1); //! Returns the geometric point. const gp_Pnt2d& Value() const; //! Returns True if the second curve is implicit. Standard_Boolean SecondIsImplicit() const; //! Returns the parameter on the first element. Standard_Real ParamOnFirst() const; //! Returns the parameter on the second element. //! If the second element is an implicit curve, an exception //! is raised. Standard_Real ParamOnSecond() const; protected: private: Standard_Real myu1; Standard_Real myu2; gp_Pnt2d myp; Standard_Boolean myimplicit; }; #include <IntAna2d_IntPoint.lxx> #endif // _IntAna2d_IntPoint_HeaderFile
#include "common.h" #include <iostream> void read_imgList(const std::string& filename, std::vector<cv::Mat>* images) { std::ifstream file(filename.c_str(), std::ifstream::in); std::string line; while (std::getline(file, line)) { images->push_back(cv::imread(line, 0)); } } void read_imgList2(const std::string& filename, std::vector<cv::Mat>* images, std::vector<cv::Mat>* groundTruth){ std::ifstream file(filename.c_str(), std::ifstream::in); std::string line, img_dir_name, gT_dir_name; std::getline(file, img_dir_name); std::getline(file, gT_dir_name); std::cout << img_dir_name << std::endl << gT_dir_name << std::endl << std::endl; while (std::getline(file, line)) { for(int i = 1; i < 2; i++){ images->push_back(cv::imread(img_dir_name + line + ".jpg")); printf("%s %d %d\n", (img_dir_name+line+".jpg").c_str(), cv::imread(img_dir_name + line + ".jpg").rows, cv::imread(img_dir_name + line + ".jpg").cols ); cv::cvtColor(images->at(images->size() - 1), images->at(images->size() - 1), CV_BGR2Luv); char name[512]; sprintf(name, "%s%s.mat_%d.png", gT_dir_name.c_str(), line.c_str(), i); groundTruth->push_back(cv::imread(name, 0)); //groundTruth->push_back(cv::imread(gT_dir_name + line + ".mat_1.png", 0)); } } } void cutPatchesFromImage3(cv::Mat img, cv::Mat gtruth, std::vector<cv::Mat>* img_patches, std::vector<cv::Mat> *gt_patches, int n_samples, int p_samples){ int gt_w = 16; int img_w = 32; //srand(time(NULL)); const int stride = 4; for (int i = 0; i < 2; i++){ for (int j = 0; j < ((i == 0)?n_samples:p_samples); ){ /*for (int i = 50; i < 200; i+=4){ for (int j = 50; j < 200; j+=4){*/ int rI = (rand() % img.rows) ; int rJ = (rand() % img.cols) ; //printf("i %d j %d r %d c %d\n", rI, rJ, img.rows, img.cols); cv::Mat tileCopy = img( cv::Range(rI, std::min(rI + img_w, img.rows)), cv::Range(rJ, std::min(rJ + img_w, img.cols)));//.clone(); if (tileCopy.rows == img_w && tileCopy.cols == img_w){ //continue; int cI = rI + img_w/2; int cJ = rJ + img_w/2; //if(neg_size < 400 || std[0] != 0.0 //printf("i %d j %d r %d c %d\n", cI, cJ, img.rows, img.cols); cv::Mat gt_tile = gtruth( cv::Range(cI - gt_w/2, cI + gt_w/2), cv::Range(cJ - gt_w/2, cJ + gt_w/2));//.clone(); if(gt_tile.rows == gt_w && gt_tile.cols == gt_w){ cv::Scalar mean, std; cv::meanStdDev(gt_tile, mean, std); //printf("%f\n", std[0]); if(std[0] != 0.0 && i == 0) { continue; } if(std[0] == 0.0 && i == 1) { continue; } img_patches->push_back(tileCopy); //cv::Canny(gt_tile, gt_tile, 0, 1); gt_patches->push_back(gt_tile); j++; } else{ } } } } } void cutPatchesFromImage2(cv::Mat img, cv::Mat gtruth, std::vector<cv::Mat>* img_patches, std::vector<cv::Mat> *gt_patches){ int gt_w = 16; int img_w = 32; //srand(NULL); const int stride = 4; for (int i = 0; i < img.rows; i+=stride){ for (int j = 0; j < img.cols; j+=stride){ /*for (int i = 50; i < 200; i+=4){ for (int j = 50; j < 200; j+=4){*/ //int rI = (rand() % img.rows) ; //int rJ = (rand() % img.cols) ; //printf("i %d j %d r %d c %d\n", rI, rJ, img.rows, img.cols); cv::Mat tileCopy = img( cv::Range(i, std::min(i + img_w, img.rows)), cv::Range(j, std::min(j + img_w, img.cols)));//.clone(); if (tileCopy.rows == img_w && tileCopy.cols == img_w){ //continue; //int cI = rI + img_w/2; //int cJ = rJ + img_w/2; int cI = i + img_w/2; int cJ = j + img_w/2; //int cI = (rand() % img.rows) + img_w/2; //int cJ = (rand() % img.cols) + img_w/2; //printf("continue %d %d\n", i, j); //printf("c %d %d\n", cI, cJ); //printf("c %d %d %d %d\n", cI - gt_w/2, cJ - gt_w/2, cI + gt_w/2, cJ + gt_w/2); cv::Mat gt_tile = gtruth( cv::Range(cI - gt_w/2, cI + gt_w/2), cv::Range(cJ - gt_w/2, cJ + gt_w/2));//.clone(); if(gt_tile.rows == gt_w && gt_tile.cols == gt_w){ img_patches->push_back(tileCopy); //cv::Canny(gt_tile, gt_tile, 0, 1); gt_patches->push_back(gt_tile); } } } } } void cutPatchesFromImage(cv::Mat img, std::vector<cv::Mat>* patches){ int w = 16; for (int i = 0; i < img.rows; i+=5){ for (int j = 0; j < img.cols; j+=5){ cv::Mat tileCopy = img(cv::Range(i, std::min(i + w, img.rows)), cv::Range(j, std::min(j + w, img.cols))).clone(); if (tileCopy.rows != w || tileCopy.cols != w) continue; patches->push_back(tileCopy); } } }
#include "ApplicationManager.h" #include "Actions\AddANDgate2.h" #include "Actions\AddANDgate3.h" #include "Actions\AddORgate2.h" #include "Actions\ADD_XOR_GATE_3.h" #include "Actions\AddBuff.h" #include "Actions\AddNORgate3.h" #include "Actions\AddConnection.h" #include "Actions\DSGMode.h" #include "Actions\AddGate.h" #include "Actions\Addswitch.h" #include "Actions\AddXNOR2.h" #include "Actions\AddXOR2.h" #include "Actions\change_switch.h" #include "Actions/select_c.h" #include "Actions/Close.h" #include "Actions/SIMMODE.h" #include "Actions/AddINVgate.h" #include "Actions/AddNANDgate2.h" #include "Actions/AddNORgate2.h" #include "Actions/AddLEDgate.h" #include "Actions/MOVE.h" #include "Actions/Save.h" #include "Actions/Deletecomp.h" #include "Actions/load.h" #include<iostream> using namespace std; ApplicationManager::ApplicationManager() { CompCount = 0; counter = 0; for(int i=0; i<MaxCompCount; i++) CompList[i] = NULL; //Creates the Input / Output Objects & Initialize the GUI OutputInterface = new Output(); InputInterface = OutputInterface->CreateInput(); } //////////////////////////////////////////////////////////////////// void ApplicationManager::AddComponent(Component* pComp) { CompList[CompCount++] = pComp; counter++; } //////////////////////////////////////////////////////////////////// ActionType ApplicationManager::GetUserAction() { //Call input to get what action is reuired from the user return InputInterface->GetUserAction(); } //////////////////////////////////////////////////////////////////// void ApplicationManager::ExecuteAction(ActionType ActType) { Action* pAct = NULL; switch (ActType) { case ADD_AND_GATE_2: pAct= new AddANDgate2(this); break; case ADD_AND_GATE_3: pAct = new AddANDgate3(this); break; case ADD_OR_GATE_2: pAct = new AddORgate2(this); break; case ADD_Buff: pAct = new AddBuff(this); break; case ADD_NOR_GATE_3: pAct = new AddNORgate3(this); break; case ADD_CONNECTION: pAct = new AddConnection(this); break; case DSN_MODE: pAct = new DSGMode(this); break; case DEL: pAct = new Deletecomp(this); break; case LOAD: pAct = new load(this); break; case ADD_XOR_GATE_3: pAct = new ADDXORGATE3(this); break; case ADD_XNOR_GATE_2: pAct = new AddXNOR2(this); break; case ADD_XOR_GATE_2: pAct = new AddXOR2(this); break; case ADD_Switch: pAct = new Addswitch(this); break; case Change_Switch: pAct = new change_switch(this); break; case SELECT: pAct = new select_c(this); break; case ADD_Gate: pAct = new AddGate(this); break; case close: pAct = new Close(this); break; case ADD_NAND_GATE_2: pAct = new AddNANDgate2(this); break; case ADD_NOR_GATE_2: pAct = new AddNORgate2(this); break; case ADD_INV: pAct = new AddINVgate(this); break; case SIM_MODE: pAct = new SIMMODE(this); break; case ADD_LED: pAct = new AddLEDgate(this); break; case MOVE: pAct = new Move(this); break; case SAVE: pAct = new Save(this); break; case EXIT: ///TODO: create ExitAction here break; } if(pAct) { pAct->Execute(); delete pAct; pAct = NULL; } } //////////////////////////////////////////////////////////////////// void ApplicationManager::UpdateInterface() { for(int i=0; i<CompCount; i++) CompList[i]->Draw(OutputInterface); } int ApplicationManager::get_compcount() { return CompCount; } Component**& ApplicationManager::get_CompList() { Component** x = this->CompList; return x; } //////////////////////////////////////////////////////////////////// Component* ApplicationManager::ComponentRegion(int x,int y) { // this function loop on complist for (int i = 0; i < CompCount; i++) { // and return component that point (x,y) Component* p = CompList[i]->ComponentRegion(x, y); // included in its region or return NULL if (p != NULL){ return p; } Component* com = CompList[i]; // included in its region or return NULL Connection* conn = dynamic_cast<Connection*>(com); if (conn != NULL) { GraphicsInfo g_conn = conn->get_GraphicsInfo(); if ((x > g_conn.x1 && x < ((g_conn.x1 + g_conn.x2) / 2)) && ((y < g_conn.y1 + 2) && (y > g_conn.y1 - 2))) { return conn; } else if ((x < g_conn.x2 && x >((g_conn.x1 + g_conn.x2) / 2)) && ((y < g_conn.y2 + 2) && (y > g_conn.y2 - 2))) { return conn; } if (g_conn.y1 > g_conn.y2) { if (((x < ((g_conn.x1 + g_conn.x2) / 2) + 2) && (x > ((g_conn.x1 + g_conn.x2) / 2) - 2)) && (y < g_conn.y1 && y > g_conn.y2)) { return conn; } } else if (g_conn.y1 < g_conn.y2) { if (((x < ((g_conn.x1 + g_conn.x2) / 2) + 2) && (x > ((g_conn.x1 + g_conn.x2) / 2) - 2)) && (y > g_conn.y1 && y < g_conn.y2)) { return conn; } } else if (g_conn.y1 == g_conn.y2) { if ((x < g_conn.x2 && x > g_conn.x1) && ((y < g_conn.y2 + 2) && (y > g_conn.y2 - 2))) { return conn; } } } } return NULL; } //////////////////////////////////////////////////////////////////// Component* ApplicationManager::componentreturin(int i) { return CompList[i]; } ///////////////////////// Input* ApplicationManager::GetInput() { return InputInterface; } //////////////////////////////////////////////////////////////////// Output* ApplicationManager::GetOutput() { return OutputInterface; } //////////////////////////////////////////////////////////////////// ApplicationManager::~ApplicationManager() { for(int i=0; i<CompCount; i++) delete CompList[i]; delete OutputInterface; delete InputInterface; } void ApplicationManager::save(ofstream& outputfile) // function Save in application manager { // Loop on complist and calls function save in each component int count = 0; for (int i = 0; i < CompCount; i++) { Gate* gate = dynamic_cast<Gate*>(CompList[i]); switch_key* Switch = dynamic_cast<switch_key*>(CompList[i]); LED* led = dynamic_cast<LED*>(CompList[i]); // 1st loop to determine no. of components Except connections if (led != NULL|| gate!=NULL|| Switch!=NULL) { count++; } } outputfile << count << endl; for (int i = 0; i < CompCount; i++) // 2nd loop to save gates ,leds and switchs first { Gate* gate = dynamic_cast<Gate*>(CompList[i]); if (gate != NULL) { CompList[i]->save(outputfile); } switch_key* Switch = dynamic_cast<switch_key*>(CompList[i]); if (Switch != NULL) { CompList[i]->save(outputfile); } LED* led = dynamic_cast<LED*>(CompList[i]); if (led != NULL) { CompList[i]->save(outputfile); } } outputfile << connection << endl; for (int i = 0; i < CompCount; i++) // 3rd loop to save connections { Connection* connection1 = dynamic_cast<Connection*>(CompList[i]); if (connection1 != NULL) { CompList[i]->save(outputfile); } } outputfile << -1<<endl; } ///////////////////////////// ///////////////////////////// //Delete Component* ApplicationManager::Check(int i) { if (CompList[i]->get_selected() == true) { return CompList[i]; } else { return NULL; } } void ApplicationManager::Delete(int i) { Component* comp = CompList[i]; CompList[i] = CompList[CompCount - 1]; CompList[CompCount - 1] = comp; CompList[CompCount - 1] = NULL; delete comp; CompCount--; OutputInterface->ClearDrawingArea(); UpdateInterface(); } Connection* ApplicationManager::Check_conn(int i) { Connection* conn = dynamic_cast<Connection*>(CompList[i]); if (conn != NULL) { return conn; } else { return NULL; } } //////////////////////////////// //load connection Component* ApplicationManager::load_connection(int id1) { Component* p; for (int i = 0; i < CompCount; i++) { p = CompList[i]; if (p->get_ID() == id1) { return p; } } return NULL; } Connection* ApplicationManager::get_connections(int id1,int &n) { for (int i = n; i < CompCount; i++) { Connection* connections = dynamic_cast<Connection*>(CompList[i]); if (connections != NULL) { if (connections->get_ID1() == id1 || connections->get_ID2() == id1) { n = i+1; return connections; } } } return NULL; }
// kumaran_14 // #include <boost/multiprecision/cpp_int.hpp> // using boost::multiprecision::cpp_int; #include <bits/stdc++.h> using namespace std; // ¯\_(ツ)_/¯ #define f first #define s second #define p push #define mp make_pair #define pb push_back #define eb emplace_back #define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define foi(i, a, n) for (i = (a); i < (n); ++i) #define foii(i, a, n) for (i = (a); i <= (n); ++i) #define fod(i, a, n) for (i = (a); i > (n); --i) #define fodd(i, a, n) for (i = (a); i >= (n); --i) #define debug(x) cout << '>' << #x << ':' << x << endl; #define all(v) v.begin(), v.end() #define sz(x) ((int)(x).size()) #define endl " \n" #define MAXN 100005 #define MOD 1000000007LL #define EPS 1e-13 #define INFI 1000000000 // 10^9 #define INFLL 1000000000000000000ll //10^18 // ¯\_(ツ)_/¯ #define l long int #define d double #define ll long long int #define ld long double #define vi vector<int> #define vll vector<long long> #define vvi vector<vector<int>> #define vvll vector<vll> //vector<vector<int>> v(10, vector<int>(20,500)); 2d vector initialization. of 10 rows and 20 columns, with value 500. #define mii map<int, int> #define mll map<long long, long long> #define pii pair<int, int> #define pll pair<long long, long long> #define fast_io() \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); ll tc, m, k; // ll ans = 0, c = 0; // ll i, j; // ll a, b; // ll x, y; // (n*logn*logn) approach string str = "banana"; ll n = sz(str); vll suffixArr(n); vector<pair<ll, pll>> suffixes(n); vll indices(n); bool customcompare(pair<ll, pll>& p1, pair<ll, pll>& p2) { if(p1.s.f == p2.s.f) { return p1.s.s < p2.s.s; } else { return p1.s.f < p2.s.f; } // sort based on lowest first and lowest second in a pair. } void buildSuffixArr() { ll i; foi(i, 0, n) { suffixes[i].f = i; suffixes[i].s.f = str[i]-'a'; suffixes[i].s.s = ((i+1 < n) ? str[i+1]-'a' : -1); } // sort according to first two characters sort(all(suffixes), customcompare); // sort according to first 4, 8, 16, .. characters for(k = 4; k < 2*n; k = k*2) { // first suffix value; ll rank = 0; ll prev_rank = suffixes[0].s.f; suffixes[0].s.f = rank; indices[suffixes[0].f] = 0; foi(i, 1, n) { if(suffixes[i].s.f == prev_rank && suffixes[i].s.s == suffixes[i-1].s.s) { prev_rank = suffixes[i].s.f; suffixes[i].s.f = rank; } else { prev_rank = suffixes[i].s.f; suffixes[i].s.f = ++rank; } indices[suffixes[i].f] = i; } foi(i, 0, n) { ll nexti = suffixes[i].f + k/2; suffixes[i].s.s = (nexti < n) ? suffixes[indices[nexti]].s.f : -1; } sort(all(suffixes), customcompare); } // populate final ans as suffixArr i = 0; for(auto x:suffixes) suffixArr[i++] = x.f; } int main() { fast_io(); freopen("./input.txt", "r", stdin); freopen("./output.txt", "w", stdout); // (n*logn*logn) approach buildSuffixArr(); for(auto x:suffixArr) { cout<<x<<" "; } return 0; }
#include "fir.h" #include "fir_base.h" extern void delay8(CReg addin, CReg addout); extern void delay1(CReg addin, CReg addout); extern void delay9(CReg addin, CReg addout); ////////////////////////////////////////////////////////// //// 名称: //// FIR_PATH3_HPInit_HP1 //// 功能: //// 设置fir滤波器系数 //// 参数: //// 无 //// 返回值: //// 无 ////////////////////////////////////////////////////////// //Sub_AutoField FIR_PATH3_HPInit_HP1 //{ // RSP -= 20 * MMU_BASE; // RA0 = RSP; // // // fir系数 // #define a0 0x862a // #define a1 0x03de // #define a2 0x0d2a // #define a3 0x80be // #define a4 0x9942 // #define a5 0x8c12 // #define a6 0x393e // #define a7 0x7fff // #define a8 0x7fff // #define a9 0x393e // #define a10 0x8c12 // #define a11 0x9942 // #define a12 0x80be // #define a13 0x0d2a // #define a14 0x03de // #define a15 0x862a // #define c0 0x0000 //占位 // // // //以下填入滤波器系数 // RD0 = a0; // M[RA0++] = RD0; // RD0 = a1; // M[RA0++] = RD0; // RD0 = a2; // M[RA0++] = RD0; // RD0 = a3; // M[RA0++] = RD0; // RD0 = a4; // M[RA0++] = RD0; // RD0 = a5; // M[RA0++] = RD0; // RD0 = a6; // M[RA0++] = RD0; // RD0 = a7; // M[RA0++] = RD0; // RD0 = a8; // M[RA0++] = RD0; // RD0 = a9; // M[RA0++] = RD0; // RD0 = a10; // M[RA0++] = RD0; // RD0 = a11; // M[RA0++] = RD0; // RD0 = a12; // M[RA0++] = RD0; // RD0 = a13; // M[RA0++] = RD0; // RD0 = a14; // M[RA0++] = RD0; // RD0 = a15; // M[RA0++] = RD0; // RD0 = c0; // M[RA0++] = RD0; // M[RA0++] = RD0; // M[RA0++] = RD0; // M[RA0++] = RD0; // // RA0 = RSP; // RD0 = 0; // call_AutoField FIR1_SetPara; // // // // RSP += 20 * MMU_BASE; // Return_AutoField(0 * MMU_BASE); //} //////////////////////////////////////////////////////// // 名称: // FIR_PATH3_HPInit_HP1 // 功能: // 设置fir滤波器系数 // 参数: // 无 // 返回值: // 无 //////////////////////////////////////////////////////// Sub_AutoField FIR_PATH3_HPInit_HP1 { RSP -= 20 * MMU_BASE; RA0 = RSP; // fir系数 #define a0 102 #define a1 32945 #define a2 396 #define a3 33568 #define a4 1438 #define a5 35186 #define a6 4011 #define a7 40075 #define a8 22993 #define a9 18268 #define a10 38132 #define a11 2471 #define a12 33961 #define a13 541 #define a14 32997 #define a15 0 #define c0 0x0000 //占位 //以下填入滤波器系数 RD0 = a0; M[RA0++] = RD0; RD0 = a1; M[RA0++] = RD0; RD0 = a2; M[RA0++] = RD0; RD0 = a3; M[RA0++] = RD0; RD0 = a4; M[RA0++] = RD0; RD0 = a5; M[RA0++] = RD0; RD0 = a6; M[RA0++] = RD0; RD0 = a7; M[RA0++] = RD0; RD0 = a8; M[RA0++] = RD0; RD0 = a9; M[RA0++] = RD0; RD0 = a10; M[RA0++] = RD0; RD0 = a11; M[RA0++] = RD0; RD0 = a12; M[RA0++] = RD0; RD0 = a13; M[RA0++] = RD0; RD0 = a14; M[RA0++] = RD0; RD0 = a15; M[RA0++] = RD0; RD0 = c0; M[RA0++] = RD0; M[RA0++] = RD0; M[RA0++] = RD0; M[RA0++] = RD0; RA0 = RSP; RD0 = 0; call_AutoField FIR1_SetPara; RA0 = RSP; RD0 = 1; call_AutoField FIR1_SetPara; RSP += 20 * MMU_BASE; Return_AutoField(0 * MMU_BASE); } //////////////////////////////////////////////////////// // 函数名称: // FIR1_SetPara // 函数功能: // FIR1配置系数,模拟设置fir系数操作 // 形参: // 1.RA0:系数序列 // 2.RD0:配置第几个bank,取值范围0~3 // 返回值: // 无 //////////////////////////////////////////////////////// Sub_AutoField FIR1_SetPara { int bank_id = RD0.m_data; short para[20]; for (int i = 0; i < 20; i++) { RD0 = M[RA0++]; para[i] = RD0.m_data; } fir1.setPara(bank_id, para); Return_AutoField(0 * MMU_BASE); } //////////////////////////////////////////////////////// // 名称: // _FIR1 // 功能: // 使用FIR执行滤波 // 参数: // 1.RA0:输入序列指针,16bit紧凑格式序列 // 2.RA1:输出序列指针,16bit紧凑格式序列 // 3.RD0:序列DWORD个数 // 返回值: // 无 //////////////////////////////////////////////////////// Sub_AutoField FIR1 { RD1 = RD0; RD0 = 0; // bank_id,取值范围[0,3] call_AutoField FIR1_Filter; Return_AutoField(0 * MMU_BASE); } //////////////////////////////////////////////////////// // 名称: // FIR2 // 功能: // 使用FIR执行滤波 // 参数: // 1.RA0:输入序列指针,16bit紧凑格式序列 // 2.RA1:输出序列指针,16bit紧凑格式序列 // 3.RD0:序列DWORD个数 // 返回值: // 无 //////////////////////////////////////////////////////// Sub_AutoField FIR2 { RD1 = RD0; RD0 = 1; // bank_id,取值范围[0,3] call_AutoField FIR1_Filter; Return_AutoField(0 * MMU_BASE); } //////////////////////////////////////////////////////// // 函数名称: // FIR1_Filter // 函数功能: // FIR滤波核心 // 形参: // 1.RA0:输入数据序列,16bit紧凑格式序列 // 2.RA1:输出数据序列,16bit紧凑格式序列 // 3.RD1:DWORD个数 // 4.RD0:配置第几个bank,取值范围0~3 // 返回值: // 无 //////////////////////////////////////////////////////// Sub_AutoField FIR1_Filter { int bank_id = RD0.m_data; int len = RD1.m_data; int* data_in = new int[len * 2]; for (int i = 0; i < len; i ++) { RD0 = M[RA0++]; RD1 = *(short*)(&RD0); RD1 = RD1 << 8; data_in[i * 2] = RD1.m_data; RD1 = RD0 >> 16; RD1 = RD1 << 8; data_in[i * 2 + 1] = RD1.m_data; } fir1.FirFilterFrame(bank_id, data_in, len * 2); for (int i = 0; i < len; i++) { RD0 = data_in[i * 2]; RD0 = RD0 >> 8; RD1 = data_in[i * 2 + 1]; RD1 = RD1 << 8; RD1 &= 0XFFFF0000; M[RA1++] = RD1 + RD0; } delete[] data_in; Return_AutoField(0 * MMU_BASE); } //////////////////////////////////////////////////////// // 函数名称: // doublemic // 函数功能: // 双麦算法 // 形参: // 1.RN_GRAM_IN:输入数据序列0,16bit紧凑格式序列 // 2.RN_GRAM_IN2:输入数据序列1,16bit紧凑格式序列 // 3.RN_GRAM_OUT:输出序列 // 返回值: // 无 //////////////////////////////////////////////////////// Sub_AutoField doublemic { //第一路 delay8(RN_GRAM_IN, RN_GRAM1);//序列0delay8 delay1(RN_GRAM_IN2, RN_GRAM2);//序列1delay1 RD0 = RN_GRAM2; RA0 = RD0; RA1 = RD0; RD0 = 16; call_AutoField FIR_MAC; RD0 = RN_GRAM1; RA0 = RD0; RD0 = RN_GRAM2; RA1 = RD0; RD0 = 16; call_AutoField Sub_LMT;//序列减,值在RA0 //第二路 //RD0 = RN_GRAM_IN; //RA0 = RD0; //RA1 = RD0; //RD0 = 16; //call_AutoField FIR2; //delay9(RN_GRAM_IN2, RN_GRAM_IN2);//序列1delay9 //RD0 = RN_GRAM_IN2; //RA0 = RD0; //RD0 = RN_GRAM_IN; //RA1 = RD0; //RD0 = 16; //call_AutoField Sub_LMT;//序列减,值在RA0 //RD0 = RN_GRAM_IN; //RA0 = RD0; //RA1 = RD0; //RD1 = 0;//该值可变,默认为0 //RD0 = 16; //call_AutoField MultiConstH16L16;//序列乘常量,结果在RA1 ////两路相减 //RD0 = RN_GRAM1; //RA0 = RD0; //RD0 = RN_GRAM_IN; //RA1 = RD0; //RD0 = 16; //call_AutoField Sub_LMT;//序列减,值在RA0 RA0 = RN_GRAM1; RA1 = RN_GRAM_OUT; for (int i = 0; i < 16; i++) { RD0 = M[RA0++]; M[RA1++] = RD0; } //////x*1.9,与下面方法二选一 //RD0 = RN_GRAM1; //send_para(RD0); //RD0 = 0x00f300f3; //send_para(RD0); //RD0 = RN_GRAM_OUT; //send_para(RD0); //RD0 = 16; //send_para(RD0); //call_AutoField MAC_MultiConst16_Q2207; ////x*0.9+x //RD0 = RN_GRAM1; //RA0 = RD0; //RD0 = RN_GRAM_IN; //RA1 = RD0; //RD1 = 0x73327332;//该值可变,默认为0 //RD0 = 16; //call_AutoField MultiConstH16L16;//序列乘常量,结果在RA1 ////两路相加 //RD0 = RN_GRAM1; //RA0 = RD0; //RD0 = RN_GRAM_IN; //RA1 = RD0; //RD0 = 16; //RD1 = RN_GRAM_IN; //call_AutoField Add_LMT;//序列加,值在RA0 Return_AutoField(0 * MMU_BASE); } //时延8个点 void delay8(CReg addin, CReg addout) { #define DelayCache0 (RN_GRAM_IN2+32*MMU_BASE) #define DelayCache1 (DelayCache0+4*MMU_BASE) RA0 = addin + 12 * MMU_BASE; RA1 = DelayCache1; for (int i = 0; i < 4; i++) { RD0 = M[RA0++]; M[RA1++] = RD0; } RA0 = addin; RA1 = addout; for (int i = 0; i < 12; i++) { RD0 = M[RA0 + (11 - i) * MMU_BASE]; M[RA1 + (15 - i) * MMU_BASE] = RD0; } RA0 = DelayCache0; RA1 = addout; for (int i = 0; i < 4; i++) { RD0 = M[RA0++]; M[RA1++] = RD0; } RA0 = DelayCache1; RA1 = DelayCache0; for (int i = 0; i < 4; i++) { RD0 = M[RA0++]; M[RA1++] = RD0; } } //时延1个点 void delay1(CReg addin, CReg addout) { #define DelayCache0 (RN_GRAM_IN2+50*MMU_BASE) #define DelayCache1 (DelayCache0+MMU_BASE) RA0 = DelayCache1; RD0 = M[addin + 15 * MMU_BASE]; RD0 = RD0 >> 16; M[RA0] = RD0 & 0xffff; RA0 = addin; for (int i = 0; i < 15; i++) { RD0 = M[RA0 + (14 - i) * MMU_BASE]; RD0 = RD0 >> 16; RD0 &= 0xffff; RD1 = M[RA0 + (15 - i) * MMU_BASE]; RD1 = RD1 << 16; RD0 += RD1; M[addout + (15 - i) * MMU_BASE] = RD0; } RD0 = M[RA0]; RD1 = M[DelayCache0]; RD1 += RD0 << 16; M[addout] = RD1; RA0 = DelayCache1; RA1 = DelayCache0; RD0 = M[RA0++]; M[RA1++] = RD0; } //时延9个点 void delay9(CReg addin, CReg addout) { #define DelayCache0 (RN_GRAM_IN2+60*MMU_BASE) #define DelayCache1 (DelayCache0+MMU_BASE) RA0 = DelayCache1; RD0 = M[addin + 15 * MMU_BASE]; RD0 = RD0 >> 16; M[RA0] = RD0 & 0xffff; RA0 = addin; for (int i = 0; i < 15; i++) { RD0 = M[RA0 + (14 - i) * MMU_BASE]; RD0 = RD0 >> 16; RD0 &= 0xffff; RD1 = M[RA0 + (15 - i) * MMU_BASE]; RD1 = RD1 << 16; RD0 += RD1; M[addout + (15 - i) * MMU_BASE] = RD0; } RD0 = M[RA0]; RD1 = M[DelayCache0]; RD1 += RD0 << 16; M[addout] = RD1; RA0 = DelayCache1; RA1 = DelayCache0; RD0 = M[RA0++]; M[RA1++] = RD0; #define DelayCache2 (RN_GRAM_IN2+70*MMU_BASE) #define DelayCache3 (DelayCache2+4*MMU_BASE) RA0 = addout + 12 * MMU_BASE; RA1 = DelayCache3; for (int i = 0; i < 4; i++) { RD0 = M[RA0++]; M[RA1++] = RD0; } RA0 = addout; RA1 = addout; for (int i = 0; i < 12; i++) { RD0 = M[RA0 + (11 - i) * MMU_BASE]; M[RA1 + (15 - i) * MMU_BASE] = RD0; } RA0 = DelayCache2; RA1 = addout; for (int i = 0; i < 4; i++) { RD0 = M[RA0++]; M[RA1++] = RD0; } RA0 = DelayCache3; RA1 = DelayCache2; for (int i = 0; i < 4; i++) { RD0 = M[RA0++]; M[RA1++] = RD0; } }
// // Created by dwb on 2019-07-22. // #ifndef SAMPLE_ANIMAL_H #define SAMPLE_ANIMAL_H #include <iostream> #include "AnimalFactory.h" using namespace std; class AnimalFactory; class Animal { public: Animal():m_name("Tiger"),m_weight(70),m_height(180){ cout << "Animal()" << endl; } Animal(const string& t_name,int t_weight,int t_height) :m_name(t_name),m_weight(t_weight),m_height(t_height){ cout << "Animal(...)" << endl; } ~Animal(){ cout << "~Animal()" << endl; } void print(){ cout << "m_name:" << m_name << " m_weight:" << m_weight << " m_height:" << m_height << endl; } void innerClass(); friend void getAnimalInfo(Animal &animal); friend class AnimalFactory; // friend void AnimalFactory::addAnimal(Animal& animal); class Bird{ public: Bird(){ cout << "Bird()" << endl; m_name= "Bird"; m_color="white"; } Bird(const string& t_name,const string& t_color):m_name(t_name),m_color(t_color){ cout << "Bird(...)" << endl; } ~Bird(){ cout << "~Bird()" << endl; } void print(); private: string m_name; string m_color; }; private: string m_name; int m_weight; int m_height; }; #endif //SAMPLE_ANIMAL_H
#ifndef GENERIC_BUS_H #define GENERIC_BUS_H // RsaToolbox // // Qt #include <QObject> #include <QMetaType> #include <QString> #include <QByteArray> #include <QScopedArrayPointer> namespace RsaToolbox { enum /*class*/ ConnectionType { VisaTcpConnection, VisaTcpSocketConnection, VisaHiSlipConnection, VisaGpibConnection, VisaUsbConnection, TcpSocketConnection, UsbConnection, NoConnection }; QString toString(ConnectionType connectionType); class GenericBus : public QObject { Q_OBJECT public: explicit GenericBus(QObject *parent = 0); GenericBus(ConnectionType connectionType, QString address, uint bufferSize_B = 500, uint timeout_ms = 1000, QObject *parent = 0); virtual bool isOpen() const = 0; virtual bool isClosed() const; ConnectionType connectionType() const; QString address() const; uint bufferSize_B() const; void setBufferSize(uint size_B); // Todo: Make pure virtual, // force subclass to handle so // actual timeout is read and // not assumed. // Could return int where -1 is // bus does not support timeout, // and 0 (or DBL_INF?) means forever. uint timeout_ms() const; virtual void setTimeout(uint time_ms); virtual bool read(char *buffer, uint bufferSize_B) = 0; QString read(); virtual bool write(QString scpi) = 0; QString query(QString scpi); virtual bool binaryRead(char *buffer, uint bufferSize_B, uint &bytesRead) = 0; QByteArray binaryRead(); virtual bool binaryWrite(QByteArray scpi) = 0; QByteArray binaryQuery(QByteArray scpi); // Todo: define error class/type with // - Action: {Read, Write, Lock, Unlock, Local, Remote} // - buffer (QString) // - message (QString) // bool isError() const; // QStringList errors() const; // void clearErrors() const; virtual QString status() const = 0; public slots: virtual bool lock () = 0; virtual bool unlock() = 0; virtual bool local () = 0; virtual bool remote() = 0; signals: void error(QString text = QString()) const; void print(QString text ) const; protected: static const int MAX_PRINT = 100; void printRead (char *buffer, uint bytesRead) const; void printWrite(QString scpi) const; void setConnectionType(ConnectionType type); void setAddress(const QString &address); static void nullTerminate(char *buffer, uint bufferSize_B, uint bytesUsed); private: ConnectionType _connectionType; QString _address; uint _timeout_ms; uint _bufferSize_B; QScopedArrayPointer<char> _buffer; }; } Q_DECLARE_METATYPE(RsaToolbox::ConnectionType) #endif
/* * <one line to give the library's name and an idea of what it does.> * Copyright 2014 Milian Wolff <mail@milianw.de> * * 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/>. * */ #ifndef VALAPARSINGENVIRONMENTFILE_H #define VALAPARSINGENVIRONMENTFILE_H #include "valaparsingenvironment.h" #include <language/duchain/duchainregister.h> #include <duchain/clangduchainexport.h> class ValaParsingEnvironmentFileData; class KDEVVALADUCHAIN_EXPORT ValaParsingEnvironmentFile : public KDevelop::ParsingEnvironmentFile { public: using Ptr = QExplicitlySharedDataPointer<ValaParsingEnvironmentFile>; ValaParsingEnvironmentFile(const KDevelop::IndexedString& url, const ValaParsingEnvironment& environment); ValaParsingEnvironmentFile(ValaParsingEnvironmentFileData& data); ~ValaParsingEnvironmentFile(); virtual bool needsUpdate(const KDevelop::ParsingEnvironment* environment = 0) const override; virtual int type() const override; virtual bool matchEnvironment(const KDevelop::ParsingEnvironment* environment) const override; void setEnvironment(const ValaParsingEnvironment& environment); ValaParsingEnvironment::Quality environmentQuality() const; uint environmentHash() const; enum { Identity = 142 }; private: DUCHAIN_DECLARE_DATA(ValaParsingEnvironmentFile) }; DUCHAIN_DECLARE_TYPE(ValaParsingEnvironmentFile) #endif // VALAPARSINGENVIRONMENTFILE_H
// kumaran_14 #include <bits/stdc++.h> using namespace std; #define f first #define s second #define p push #define mp make_pair #define pb push_back #define foi(i, a, n) for (i = (a); i < (n); ++i) #define foii(i, a, n) for (i = (a); i <= (n); ++i) #define fod(i, a, n) for (i = (a); i > (n); --i) #define fodd(i, a, n) for (i = (a); i >= (n); --i) #define gcd __gcd #define mem(a, b) memset(a, b, sizeof a) #define all(v) v.begin(), v.end() #define sz(x) ((int)(x).size()) #define endl "\n" #define println(a) cout << (a) << endl #define PI 3.141592653589793238L #define MOD 1000000007LL #define EPS 1e-13 #define INFI 1000000000 // 10^9 #define INFLL 1000000000000000000ll //10^18 #define l long int #define d double #define ll long long int #define ld long double #define vi vector<int> #define vs vector<string> #define vc vector<char> #define vll vector<long long> #define vvi vector<vector<int>> #define vvll vector<vll> //vector<vector<int>> v(10, vector<int>(20,500)); 2d vector initialization. of 10 rows and 20 columns. // Initialization value is 500. #define si set<int> #define mii map<int, int> #define mll map<long long, long long> #define pii pair<int, int> #define pll pair<long long, long long> #define pcc pair<char, char> #define pdd pair<double, double> #define fast_io() \ ios_base::sync_with_stdio(false); \ cin.tie(NULL); \ cout.tie(NULL); ll tc, n, m, k; // ll ans = 0, c = 0; ll i, j; // ll a, b; // ll x, y; struct Edge { // a , b are vectices. 1 <= a, b <= n ll a, b, cost; }; // edgelist indexed from 0. vector<Edge> edgelist; vll dist(100005, INFLL); vll parent(100005, -1); ll cycle_end; void printarr(vll arr) { for (auto x : arr) cout << x << " "; cout << endl; } void findnegativecycle(ll x) { foi(i, 0, n) { x = parent[x]; } vll cyclearr; for (ll v = x;; v = parent[v]) { cyclearr.pb(v); if (v == x && sz(cyclearr) > 1) break; } reverse(all(cyclearr)); cout << "Negative cycle: "; printarr(cyclearr); } //single source shortest path void bellmanford(ll source) { // a negative cycle reachable from source, then other vertex dist at starting is INFLL dist.assign(n + 1, INFLL); // a negative cycle not reachable from source, or general case, find any negative cycle, then other vertex dist at starting is 0. // dist.assign(n + 1, 0); parent.assign(n + 1, -1); dist[source] = 0; // nth time is the time we check for negative cycle. foi(i, 0, n) { cycle_end = -1; for (auto edge : edgelist) { auto curr = edge.a; auto next = edge.b; auto cost = edge.cost; if (dist[next] > dist[curr] + cost) { // for integer overflow dist[next] = max(-INFLL, dist[curr] + cost); parent[next] = curr; cycle_end = next; } } } if (cycle_end == -1) { cout << "No negative cycle" << endl; } else { findnegativecycle(cycle_end); } } int main() { fast_io(); freopen("./input.txt", "r", stdin); freopen("./output.txt", "w", stdout); //vertices n = 1000; //edges; m = 100; cin >> n >> m; foi(i, 0, m) { ll u, v, cost; cin >> u >> v >> cost; struct Edge edge = {u, v, cost}; edgelist.pb(edge); // struct Edge edge2 = {v, u, cost}; // edgelist.pb(edge2); } // a negative cycle reachable from source, then other vertices dist at starting is INFLL // a negative cycle not reachable from source, or general case, find any negative cycle, then other vertices dist at starting is 0. // choose accordingly in the function. bellmanford(5); return 0; }
#include <iterator> #include <vector> #pragma once // Patching functions all rely on the Asar DLL #ifndef WORLDLIB_IGNORE_DLL_FUNCTIONS namespace worldlib { ////////////////////////////////////////////////////////////////////////////// /// \file Patch.hpp /// \brief Contains various functions for patching and assembling files /// /// \addtogroup Patch /// @{ ////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// /// \brief Contains error data reported from Asar //////////////////////////////////////////////////////////// template <typename stringType> struct PatchErrorData { //////////////////////////////////////////////////////////// /// \brief Default constructor //////////////////////////////////////////////////////////// PatchErrorData(); //////////////////////////////////////////////////////////// /// \brief Constructor taking in various information. In retrospect I could've just taken in one of Asar's structs, couldn't've I? //////////////////////////////////////////////////////////// PatchErrorData(const char *fed, const char *red, const char *b, const char *fn, int l, const char *cfn, int cl) : fullErrorData((std::string)fed), rawErrorData((std::string)red), block((std::string)b), fileName((std::string)fn), line(l), callerLine(cl) { if (cfn != nullptr) callerFilename = std::string(cfn); }; //////////////////////////////////////////////////////////// /// \brief Contains the full error data as reported by Asar //////////////////////////////////////////////////////////// stringType fullErrorData; //////////////////////////////////////////////////////////// /// \brief Contains just the "simple" error data as reported by Asar //////////////////////////////////////////////////////////// stringType rawErrorData; //////////////////////////////////////////////////////////// /// \brief Contains the "descriptive" error data as reported by Asar //////////////////////////////////////////////////////////// stringType block; //////////////////////////////////////////////////////////// /// \brief The file name of the offending file //////////////////////////////////////////////////////////// stringType fileName; //////////////////////////////////////////////////////////// /// \brief The line the error occurred at //////////////////////////////////////////////////////////// int line; //////////////////////////////////////////////////////////// /// \brief The calling file //////////////////////////////////////////////////////////// stringType callerFilename; //////////////////////////////////////////////////////////// /// \brief The line the file was called at in the calling file //////////////////////////////////////////////////////////// int callerLine; }; //////////////////////////////////////////////////////////// /// \brief Contains warning data reported from Asar //////////////////////////////////////////////////////////// template <typename stringType> using PatchWarningData = PatchErrorData<stringType>; //////////////////////////////////////////////////////////// /// \brief Contains label data reported from Asar //////////////////////////////////////////////////////////// template <typename stringType> struct PatchLabelData { //////////////////////////////////////////////////////////// /// \brief Default constructor //////////////////////////////////////////////////////////// PatchLabelData(); //////////////////////////////////////////////////////////// /// \brief Constructor taking in various information. And what kind of a word is "couldn't've" anyway. //////////////////////////////////////////////////////////// PatchLabelData(const char *n, int l) : name((std::string)n), location(l) {}; //////////////////////////////////////////////////////////// /// \brief The name of the label //////////////////////////////////////////////////////////// stringType name; //////////////////////////////////////////////////////////// /// \brief The location of the label //////////////////////////////////////////////////////////// int location; }; //////////////////////////////////////////////////////////// /// \brief Contains define data reported from Asar //////////////////////////////////////////////////////////// template <typename stringType> struct PatchDefineData { //////////////////////////////////////////////////////////// /// \brief Default constructor //////////////////////////////////////////////////////////// PatchDefineData(); //////////////////////////////////////////////////////////// /// \brief Constructor taking in various information. //////////////////////////////////////////////////////////// PatchDefineData(const char *n, const char *c) : name((std::string)n), contents(c) {}; //////////////////////////////////////////////////////////// /// \brief The name of the define //////////////////////////////////////////////////////////// stringType name; //////////////////////////////////////////////////////////// /// \brief The literal string value of the define //////////////////////////////////////////////////////////// stringType contents; }; ///////////////////////////////////////////////////////////////////////////// /// \brief Compiles the given ASM file to a binary. /// \details The file must exist on disk. If errorDataOutput has been added to once the function returns, there was an error. Use the PatchErrorData et al structs for the parameters. /// /// \param patchFilepath The filename of the patch /// \param out Where to send the resulting data /// \param errorDataOutput Where to send the error data /// \param warningDataOutput Where to send the warning data /// \param labelDataOutput Where to send the label data /// \param defineDataOutput Where to send the define data /// /// \return Returns an iterator to the end of your compiled data. /// ///////////////////////////////////////////////////////////////////////////// template <typename stringType, typename outputIteratorType, typename errorDataOutputIteratorType, typename warningDataOutputIteratorType, typename labelDataOutputIteratorType, typename defineDataOutputIteratorType> outputIteratorType compileToBinary(const char *patchFilepath, outputIteratorType out, errorDataOutputIteratorType &errorDataOutput, warningDataOutputIteratorType &warningDataOutput, labelDataOutputIteratorType &labelDataOutput, defineDataOutputIteratorType &defineDataOutput); ///////////////////////////////////////////////////////////////////////////// /// \brief Compiles the given ASM file to a binary. /// /// \details The file must exist on disk. If errorDataOutput has been added to once the function returns, there was an error. Use the PatchErrorData et al structs for the parameters. /// /// \param patchFilepath The filename of the patch /// \param out Where to send the resulting data /// \param errorDataOutput Where to send the error data /// /// \return Returns an iterator to the end of your compiled data. /// ///////////////////////////////////////////////////////////////////////////// template <typename stringType, typename outputIteratorType, typename errorDataOutputIteratorType> outputIteratorType compileToBinary(const char *patchFilepath, outputIteratorType out, errorDataOutputIteratorType &errorDataOutput); ///////////////////////////////////////////////////////////////////////////// /// \brief Compiles the given ASM file to a binary. The file must exist on disk. If errorDataOutput has been added to once the function returns, there was an error. Use the PatchErrorData et al structs for the parameters. /// /// \param patchFilepath The filename of the patch /// \param out Where to send the resulting data /// /// \return Returns true on success and false on failure /// ///////////////////////////////////////////////////////////////////////////// template <typename stringType, typename outputIteratorType> bool compileToBinary(const char *patchFilepath, outputIteratorType &out); ///////////////////////////////////////////////////////////////////////////// /// \brief "Quick compile". Just gives you a vector from a string, basically. /// /// \param patchFilepath The filename of the patch /// \param errorDataOutput Where to send the error data. Be nice if this weren't necessary, but we need this for error reporting, obviously. /// /// \return Returns a vector containing the compiled data /// ///////////////////////////////////////////////////////////////////////////// template <typename dataType> std::vector<dataType> compileToBinary(const char *patchFilepath, std::vector<PatchErrorData<std::string>> &errorDataOutput); ///////////////////////////////////////////////////////////////////////////// /// \brief Compiles an ASM file onto a ROM. The ROM must exist in memory as a pointer to chars or unsigned chars. Or I guess you could use other integer types if you're feeling adventerous... /// /// If errorDataOutput has been added to once the function returns, there was an error. Use the PatchErrorData et al structs for the parameters. /// /// \param patchFilepath The filename of the patch /// \param romData The ROM data to modify /// \param romSize The size of the ROM to modify /// \param errorDataOutput Where to send the error data /// \param warningDataOutput Where to send the warning data /// \param labelDataOutput Where to send the label data /// \param defineDataOutput Where to send the define data /// /// \return Returns true on success and false if there was an error /// ///////////////////////////////////////////////////////////////////////////// template <typename stringType, typename romDataType, typename errorDataOutputIteratorType, typename warningDataOutputIteratorType, typename labelDataOutputIteratorType, typename defineDataOutputIteratorType> bool patchToROM(const char *patchFilepath, const romDataType *romData, int romSize, errorDataOutputIteratorType &errorDataOutput, warningDataOutputIteratorType &warningDataOutput, labelDataOutputIteratorType &labelDataOutput, defineDataOutputIteratorType &defineDataOutput); ///////////////////////////////////////////////////////////////////////////// /// \brief Compiles an ASM file onto a ROM. The ROM must exist in memory as a pointer to chars or unsigned chars. Or I guess you could use other integer types if you're feeling adventerous... /// /// If errorDataOutput has been added to once the function returns, there was an error. Use the PatchErrorData et al structs for the parameters. /// /// \param patchFilepath The filename of the patch /// \param romData The ROM data to modify /// \param romSize The size of the ROM to modify /// \param errorDataOutput Where to send the error data /// /// \return Returns true on success and false if there was an error /// ///////////////////////////////////////////////////////////////////////////// template <typename stringType, typename romDataType, typename errorDataOutputIteratorType> bool patchToROM(const char *patchFilepath, const romDataType *romData, int romSize, errorDataOutputIteratorType &errorDataOutput); ///////////////////////////////////////////////////////////////////////////// /// \brief Compiles an ASM file onto a ROM. The ROM must exist in memory as a pointer to chars or unsigned chars. Or I guess you could use other integer types if you're feeling adventerous... /// /// If errorDataOutput has been added to once the function returns, there was an error. Use the PatchErrorData et al structs for the parameters. /// /// \param patchFilepath The filename of the patch /// \param romData The ROM data to modify /// \param romSize The size of the ROM to modify /// /// \return Returns true on success and false if there was an error /// ///////////////////////////////////////////////////////////////////////////// template <typename stringType, typename romDataType> bool patchToROM(const char *patchFilepath, const romDataType *romData, int romSize); ///////////////////////////////////////////////////////////////////////////// /// \brief Given a string to a patch, finds a definition (e.g. "!true = $00") and replaces it with a new string. /// \details It's highly recommended to look at the version that just takes normal strings instead of iterators so that this function doesn't take up like 5 lines of back_insert_iterator boilerplate. /// /// \param patchStart An iterator pointing to the patch's start /// \param patchEnd An iterator pointing to the patch's end /// \param definitionStart An iterator pointing to a string containing the name of the definition you want to replace, not including the "!" /// \param definitionEnd An iterator pointing to the definition's end /// \param valueToChangeToStart An iterator pointing to a string containing the name of the value you want to replace the original definition's value with /// \param valueToChangeToEnd An iterator pointing to the value's end /// /// \throws std::runtime_error Thrown if: /// 1. The definition cannot be found /// 2. The definition is malformed /// 3. The definition's value's length (in characters) is not equal of the length of the string you want to replace it with. E.G. trying to replace "!value = $0000" with "$50" instead of "$0050" /// ///////////////////////////////////////////////////////////////////////////// template <typename patchStringIteratorType, typename definitionStringIteratorType, typename replacementStringIteratorType> void replacePatchDefinition(patchStringIteratorType patchStart, patchStringIteratorType patchEnd, definitionStringIteratorType definitionStart, definitionStringIteratorType definitionEnd, replacementStringIteratorType valueToChangeToStart, replacementStringIteratorType valueToChangeToEnd); ///////////////////////////////////////////////////////////////////////////// /// \brief Given a string to a patch, finds a definition (e.g. "!true = $00") and replaces it with a number, printed as a hex value (with a $ preceding it). /// \details It's highly recommended to look at the version that just takes normal strings instead of iterators so that this function doesn't take up like 5 lines of back_insert_iterator boilerplate. /// /// \param patchStart An iterator pointing to the patch's start /// \param patchEnd An iterator pointing to the patch's end /// \param definitionStart An iterator pointing to a string containing the name of the definition you want to replace, not including the "!" /// \param definitionEnd An iterator pointing to the definition's end /// \param valueToChangeTo The numeric value to use (will be converted to a hex value with a '$' preceding it) /// \param digits How mny digits long the value should be (for example, use 4 to convert "$50" to "$0050") /// /// \throws std::runtime_error Thrown if: /// 1. The definition cannot be found /// 2. The definition is malformed /// 3. The definition's value's length (in characters) is not equal of the length of the string you want to replace it with. E.G. trying to replace "!value = $0000" with "$50" instead of "$0050" /// ///////////////////////////////////////////////////////////////////////////// template <typename patchStringIteratorType, typename definitionStringIteratorType> void replacePatchDefinition(patchStringIteratorType patchStart, patchStringIteratorType patchEnd, definitionStringIteratorType definitionStart, definitionStringIteratorType definitionEnd, int valueToChangeTo, int digits); ///////////////////////////////////////////////////////////////////////////// /// \brief Given a string to a patch, finds a definition (e.g. "!true = $00") and replaces it with a new string. /// \details The length of the new definition's value must be equal to the length of the old definition's value /// /// \param patch The patch that should have its definition changed /// \param definitionToChange A string containing the name of the definition you want to replace, not including the "!" /// \param valueToChangeTo A string containing the name of the value you want to replace the original definition's value with /// /// \throws std::runtime_error Thrown if: /// 1. The definition cannot be found /// 2. The definition is malformed /// 3. The definition's value's length (in characters) is not equal of the length of the string you want to replace it with. E.G. trying to replace "!value = $0000" with "$50" instead of "$0050" /// ///////////////////////////////////////////////////////////////////////////// template <typename patchStringType, typename definitionStringType, typename replacementStringType> void replacePatchDefinition(patchStringType &patch, const definitionStringType &definitionToChange, const replacementStringType &valueToChangeTo); ///////////////////////////////////////////////////////////////////////////// /// \brief Given a string to a patch, finds a definition (e.g. "!true = $00") and replaces it with a number /// \details The number is printed as a hex value (with a $ preceding it). It's highly recommended to look at the version that just takes normal strings instead of iterators so that this function doesn't take up like 5 lines of back_insert_iterator boilerplate. /// /// \param patch The patch that should have its definition changed /// \param definitionToChange A string containing the name of the definition you want to replace, not including the "!" /// \param valueToChangeTo The numeric value to use (will be converted to a hex value with a '$' preceding it) /// \param digits How mny digits long the value should be (for example, use 4 to convert "$50" to "$0050") /// /// \throws std::runtime_error Thrown if: /// 1. The definition cannot be found /// 2. The definition is malformed /// 3. The definition's value's length (in characters) is not equal of the length of the string you want to replace it with. E.G. trying to replace "!value = $0000" with "$50" instead of "$0050" /// ///////////////////////////////////////////////////////////////////////////// template <typename patchStringType, typename definitionStringType> void replacePatchDefinition(patchStringType &patch, const definitionStringType &definitionToChange, int valueToChangeTo, int digits); ////////////////////////////////////////////////////////////////////////////// /// @} ////////////////////////////////////////////////////////////////////////////// } #include "Patch.inl" #endif
#include <QCoreApplication> #include <QDebug> class Person { public: Person(const QString &name, int age) : mName(name), mAge(age) { } friend inline QDebug operator<<(QDebug qd, const Person &p); private: QString mName; int mAge; }; inline QDebug operator<<(QDebug qd, const Person &p) { return qd << p.mName << " " << p.mAge; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Person aaa("AAA", 29); qDebug() << aaa; a.exit(0); // return a.exec(); }
#include <fstream> #include "blur_xy_16_unrolled_16_opt.h" int main() { ofstream in_pix("input_pixels_regression_result_blur_xy_16_unrolled_16_opt.txt"); ofstream fout("regression_result_blur_xy_16_unrolled_16_opt.txt"); HWStream<hw_uint<256> > input_update_0_read; HWStream<hw_uint<256> > blur_xy_16_unrolled_16_update_0_write; // Loading input data // cmap : { input_update_0[root = 0, input_0, input_1] -> input_arg[0, 0] : 0 <= input_0 <= 120 and 0 <= input_1 <= 1081 } // read map: { input_arg[0, 0] -> input_update_0[root = 0, input_0, input_1] : 0 <= input_0 <= 120 and 0 <= input_1 <= 1081 } // rng : { input_update_0[root = 0, input_0, input_1] : 0 <= input_0 <= 120 and 0 <= input_1 <= 1081 } for (int i = 0; i < 130922; i++) { hw_uint<256> in_val; set_at<0*16, 256, 16>(in_val, 16*i + 0); in_pix << in_val << endl; set_at<1*16, 256, 16>(in_val, 16*i + 1); in_pix << in_val << endl; set_at<2*16, 256, 16>(in_val, 16*i + 2); in_pix << in_val << endl; set_at<3*16, 256, 16>(in_val, 16*i + 3); in_pix << in_val << endl; set_at<4*16, 256, 16>(in_val, 16*i + 4); in_pix << in_val << endl; set_at<5*16, 256, 16>(in_val, 16*i + 5); in_pix << in_val << endl; set_at<6*16, 256, 16>(in_val, 16*i + 6); in_pix << in_val << endl; set_at<7*16, 256, 16>(in_val, 16*i + 7); in_pix << in_val << endl; set_at<8*16, 256, 16>(in_val, 16*i + 8); in_pix << in_val << endl; set_at<9*16, 256, 16>(in_val, 16*i + 9); in_pix << in_val << endl; set_at<10*16, 256, 16>(in_val, 16*i + 10); in_pix << in_val << endl; set_at<11*16, 256, 16>(in_val, 16*i + 11); in_pix << in_val << endl; set_at<12*16, 256, 16>(in_val, 16*i + 12); in_pix << in_val << endl; set_at<13*16, 256, 16>(in_val, 16*i + 13); in_pix << in_val << endl; set_at<14*16, 256, 16>(in_val, 16*i + 14); in_pix << in_val << endl; set_at<15*16, 256, 16>(in_val, 16*i + 15); in_pix << in_val << endl; input_update_0_read.write(in_val); } blur_xy_16_unrolled_16_opt(input_update_0_read, blur_xy_16_unrolled_16_update_0_write); for (int i = 0; i < 129600; i++) { hw_uint<256> actual = blur_xy_16_unrolled_16_update_0_write.read(); auto actual_lane_0 = actual.extract<0*16, 15>(); fout << actual_lane_0 << endl; auto actual_lane_1 = actual.extract<1*16, 31>(); fout << actual_lane_1 << endl; auto actual_lane_2 = actual.extract<2*16, 47>(); fout << actual_lane_2 << endl; auto actual_lane_3 = actual.extract<3*16, 63>(); fout << actual_lane_3 << endl; auto actual_lane_4 = actual.extract<4*16, 79>(); fout << actual_lane_4 << endl; auto actual_lane_5 = actual.extract<5*16, 95>(); fout << actual_lane_5 << endl; auto actual_lane_6 = actual.extract<6*16, 111>(); fout << actual_lane_6 << endl; auto actual_lane_7 = actual.extract<7*16, 127>(); fout << actual_lane_7 << endl; auto actual_lane_8 = actual.extract<8*16, 143>(); fout << actual_lane_8 << endl; auto actual_lane_9 = actual.extract<9*16, 159>(); fout << actual_lane_9 << endl; auto actual_lane_10 = actual.extract<10*16, 175>(); fout << actual_lane_10 << endl; auto actual_lane_11 = actual.extract<11*16, 191>(); fout << actual_lane_11 << endl; auto actual_lane_12 = actual.extract<12*16, 207>(); fout << actual_lane_12 << endl; auto actual_lane_13 = actual.extract<13*16, 223>(); fout << actual_lane_13 << endl; auto actual_lane_14 = actual.extract<14*16, 239>(); fout << actual_lane_14 << endl; auto actual_lane_15 = actual.extract<15*16, 255>(); fout << actual_lane_15 << endl; } in_pix.close(); fout.close(); return 0; }
// ShortForcast.cpp : 实现文件 // #include "stdafx.h" #include "MessAtoB.h" #include "ShortForcast.h" #include "string-trans.h" #include <fstream> #include <iostream> // ShortForcast 对话框 IMPLEMENT_DYNAMIC(ShortForcast, CDialog) ShortForcast::ShortForcast(CWnd* pParent /*=NULL*/) : CDialog(ShortForcast::IDD, pParent) { CTime ct1=CTime::GetCurrentTime();//当前日期 int cth = ct1.GetHour(); CString sth,sth2; if(cth<10) { sth = "08"; sth2 = "14"; } else if(cth<16) { sth = "14"; sth2 = "20"; } else { sth = "20"; sth2 = "08"; } forcast_content = " "+sth+"-"+sth2+"时短时天气预报\r\n\r\n" "预计"+sth+"-"+sth2+"时:全区\r\n\r\n" " "+ct1.Format("%Y年%#m月%#d日"); file_path = "//172.18.172.63/data_/xjdata/FORECAST/dsyb/"+ct1.Format("%Y/%Y%m%d")+sth+".txt"; } ShortForcast::~ShortForcast() { } void ShortForcast::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(ShortForcast, CDialog) ON_BN_CLICKED(IDOK, &ShortForcast::OnBnClickedOk) END_MESSAGE_MAP() // ShortForcast 消息处理程序 BOOL ShortForcast::OnInitDialog() { CDialog::OnInitDialog(); // TODO: 在此添加额外的初始化 CEdit *pEdit = (CEdit *)GetDlgItem(IDC_EDIT_FContent); pEdit ->SetWindowTextA(forcast_content); return TRUE; // return TRUE unless you set the focus to a control // 异常: OCX 属性页应返回 FALSE } bool ShortForcast::PutShortForcast() { CEdit *pEdit = (CEdit *)GetDlgItem(IDC_EDIT_FContent); pEdit ->GetWindowText(forcast_content); forcast_content.Replace("\r\n","\n"); if(strtofile(file_path.GetBuffer(),forcast_content.GetBuffer() )) //数据保存为文件 { MessageBox("文件成功上传至"+file_path,"成功",MB_ICONINFORMATION); } else { MessageBox("文件上传失败,请重试!", "警告", MB_ICONERROR); return false; } return true; } void ShortForcast::OnBnClickedOk() { // TODO: 在此添加控件通知处理程序代码 if(PutShortForcast()) OnOK(); }
#include<bits/stdc++.h> using namespace std; int ma[10000], mi[10000]; main() { int d, sumtime; while(cin>>d>>sumtime) { int i, maxi=0, mini =0, sum=0, ta=1, ti=1, a; for(i=1; i<=d; i++) { cin>>mi[i]>>ma[i]; mini = mini + mi[i]; maxi = maxi + ma[i]; } if(sumtime<mini || sumtime>maxi)printf("NO\n"); else { printf("YES\n"); sumtime = sumtime - mini; while(sumtime) { for(i=1; i<=d; i++) { if(mi[i]<ma[i]) { mi[i]++; sumtime--; if(sumtime==0)break; } } } for(i=1; i<=d; i++)printf("%d ", mi[i]); printf("\n"); } } return 0; }
// // debug.hpp // utilities // // Created by Six on 2/23/2018. // Copyright 2/23/2018 Six. All rights reserved. // #ifndef _DEBUG_HPP #define _DEBUG_HPP #include <stddef.h> /// /// @brief Debug log with time, file, line, and function helper /// @param[in] file The file name, will have directory delimiters removed /// @param[in] line The line number /// @param[in] func The function name /// @param[in] fmt The format string a-la printf /// @param[in] ... variable args for the format string /// void formatted_print(const char *file, int line, const char *func, const char *fmt, ...); /// /// @brief Debug print an io operation /// @param[in] file The file name, will have directory delimiters removed /// @param[in] line The line number /// @param[in] func The function name /// @param[in] in @li true for input @li false for output /// @param[in] msg Pointer to the message to print /// @param[in] len Length of msg, bytes /// void debug_print_io(const char *file, int line, const char *func, bool in, const void *msg, size_t len); /// /// Use dpr and iodpr (debug print and io debug print) and #define DEBUG to /// control printing. These macros are called exactly like printf and prints to /// stderr. /// #ifdef DEBUG #define dpr(fmt,...) formatted_print(__FILE__,__LINE__,__FUNCTION__,fmt,##__VA_ARGS__) #define iodpr(in, msg, len) debug_print_io(__FILE__,__LINE__,__FUNCTION__, in, msg, len) #else inline void dpr(const char * fmt, ...) { (void)fmt; return; } inline void iodpr(bool in, const void *msg, size_t len) { (void)msg; (void)len; return; } #endif /// @brief Always print #define HARDPR(fmt,...) formatted_print(__FILE__,__LINE__,__FUNCTION__,fmt,##__VA_ARGS__) /// @brief Always print #define HARDIODPR(in, msg, len) debug_print_io(__FILE__,__LINE__,__FUNCTION__, in, msg, len) #endif // _DEBUG_HPP
#define GLEW_STATIC #include <GL/glew.h> #include <windows.h> #include <math.h> #include "EventHandler.h" using namespace std; void init (); void display (void); void centerOnScreen (); void drawObject (); int window_x; int window_y; char *window_title = "Projeto Final"; GLuint main_window; int full_screen = 0; // pointer to the GLUI window GLUI * glui_window; // Declare live variables (related to GLUI) int wireframe = 1; // Related to Wireframe Check Box int draw = 1; // Related to Draw Check Box int listbox_item_id = 12; // Id of the selected item in the list box int radiogroup_item_id = 0; // Id of the selcted radio button float rotation_matrix[16] // Rotation Matrix Live Variable Array = { 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 }; float translate_xy[2] // Translation XY Live Variable = {0, 0}; float translate_z = 0; // Translation Z Live Variable float scale = 1; // Spinner Scale Live Variable // an array of RGB components float color[] = { 1.0, 1.0, 1.0 }; // Set up the GLUI window and its components void setupGLUI (); // Idle callack function void idle (); // Declare callbacks related to GLUI void glui_callback (int arg); // Declare the IDs of controls generating callbacks enum { COLOR_LISTBOX = 0, OBJECTYPE_RADIOGROUP, TRANSLATION_XY, TRANSLATION_Z, ROTATION, SCALE_SPINNER, QUIT_BUTTON }; // The different GLUT shapes enum GLUT_SHAPES { GLUT_WIRE_CUBE = 0, GLUT_SOLID_CUBE, GLUT_WIRE_SPHERE, GLUT_SOLID_SPHERE, GLUT_WIRE_CONE, GLUT_SOLID_CONE, GLUT_WIRE_TORUS, GLUT_SOLID_TORUS, GLUT_WIRE_DODECAHEDRON, GLUT_SOLID_DODECAHEDRON, GLUT_WIRE_OCTAHEDRON, GLUT_SOLID_OCTAHEDRON, GLUT_WIRE_TETRAHEDRON, GLUT_SOLID_TETRAHEDRON, GLUT_WIRE_ICOSAHEDRON, GLUT_SOLID_ICOSAHEDRON, GLUT_WIRE_TEAPOT, GLUT_SOLID_TEAPOT }; void printMatrixf (float *matrix) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { printf ("%f%\t", matrix[i*4 + j]); } printf ("\n"); } } void init () { glClearColor (0.0, 0.0, 0.0, 0.0); } void display (void) { glClear (GL_COLOR_BUFFER_BIT); drawObject (); glutSwapBuffers (); } void drawObject () { printf ("Displaying object...\n"); glutWireIcosahedron (); } void centerOnScreen () { window_x = (glutGet (GLUT_SCREEN_WIDTH) - window_width)/2; window_y = (glutGet (GLUT_SCREEN_HEIGHT) - window_height)/2; } int main (int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize (window_width, window_height); glutInitWindowPosition (window_x, window_y); glutInitDisplayMode (GLUT_RGBA | GLUT_DOUBLE); glutCreateWindow (window_title); if (glewInit()!= GLEW_OK) { cout << "Erro ao iniciar GLEW"; return 0; } centerOnScreen (); if (full_screen) glutFullScreen (); init(); // Seta os callbacks glutDisplayFunc (display); glutReshapeFunc (reshape); glutMouseFunc (mouse); glutMotionFunc (motion); glutPassiveMotionFunc (pmotion); glutKeyboardFunc (keyboard); glutSpecialFunc (special); // inicia o loop da GLUT glutMainLoop(); }
#include<iostream> using namespace std; int a[20]; int main() {int n=9,ans=0; for (int i = 1;i <= 9;i++ ) cin >> a[i]; for (int i = 1;i < n;i++ ) for (int j = (i+1);j <= n; j++) if (a[i]>a[j]) ans++; cout << ans << endl; return 0; }
#include "StdAfx.h" #include "GcTextureAnimationPropEntity.h" #include "GcPropertyGridFloatSpinProperty.h" #include "GcPropertyGridProperty.h" #include "Gc2DTexturePropEntity.h" GcTextureAnimationPropEntity::GcTextureAnimationPropEntity(void) { Init(); } GcTextureAnimationPropEntity::~GcTextureAnimationPropEntity(void) { } bool GcTextureAnimationPropEntity::Init() { mUpdateEventSlot.Initialize( this, &GcTextureAnimationPropEntity::UpdateEvent ); CMFCPropertyGridProperty* pGroup = new CMFCPropertyGridProperty(_T("텍스쳐 애니메이션 정보")); mpProperty = pGroup; GcPropertyGridProperty* pProp = NULL; pProp = new GcPropertyGridProperty(_T("에니 인덱스"), 0L, _T("애니메이션 인덱스를 정합니다.")); pProp->SetData( MSG_ANIINDEX ); pProp->AllowEdit( false ); pGroup->AddSubItem(pProp); //pProp = new GcPropertyGridProperty(_T("파일 이름"), _T(""), // _T("애니메이션 인덱스를 정합니다.")); //pProp->SetData( MSG_FILENAME ); //pGroup->AddSubItem(pProp); // GcPropertyGridProperty* spinProp = NULL; spinProp = new GcPropertyGridProperty(_T("시작 타임"), (_variant_t) 0.0f, _T("애니메이션 인덱스를 정합니다.")); spinProp->SetData( MSG_STARTTIME ); spinProp->EnableFloatSpinControl(TRUE, 0, INT_MAX); spinProp->SubscribeToUpdateEvent( &mUpdateEventSlot ); pGroup->AddSubItem(spinProp); spinProp = new GcPropertyGridProperty(_T("종료 타임"), (_variant_t) 1.0f, _T("애니메이션 인덱스를 정합니다.")); spinProp->SetData( MSG_ENDTIME ); spinProp->EnableFloatSpinControl(TRUE, 0, INT_MAX); spinProp->SubscribeToUpdateEvent( &mUpdateEventSlot ); pGroup->AddSubItem(spinProp); return true; } float GcTextureAnimationPropEntity::GetStartTime() { CMFCPropertyGridProperty* aniTime = GetStartTimeProperty(); return aniTime->GetValue().fltVal; } float GcTextureAnimationPropEntity::GetEndTime() { CMFCPropertyGridProperty* aniTime = GetEndTimeProperty(); return aniTime->GetValue().fltVal; } bool GcTextureAnimationPropEntity::ParseToEntity(EntityData* pObject) { EntityDataTextureAni* thisEntityData = (EntityDataTextureAni*)pObject; mpActor = (Gt2DActor*)(GtObject*)thisEntityData->mpObject; mpAni = thisEntityData->mpAni; for( gtuint i = 0 ; i < mpAni->GetAniInfoCount() ; i++ ) { Gc2DTexturePropEntity* textureProp = GtObjectNew<Gc2DTexturePropEntity>::Create(); AddChild( textureProp ); Gn2DTextureAni::TextureAniInfo* aniInfo = (Gn2DTextureAni::TextureAniInfo*)mpAni->GetAniInfo( i ); Gc2DTexturePropEntity::ThisEntity textureEntity; textureEntity.mpObject = mpActor; textureEntity.mAniInfoIndex = i; textureEntity.mTextureAniIndex = thisEntityData->mIndex; textureEntity.mpAniInfo = aniInfo; textureProp->ParseToEntity( &textureEntity ); if( i == 0 ) { GetAniIndexProperty()->SetValue( thisEntityData->mIndex ); GetStartTimeProperty()->SetValue( aniInfo->GetStartTime() ); GetEndTimeProperty()->SetValue( aniInfo->GetEndTime() ); } } return true; } bool GcTextureAnimationPropEntity::ParseToObject(EntityData* pObject) { // GnAssert( pObject->IsActor() ); // GtConvertString name = GetAniName(); // GtConvertString fileName = GetFileName(); // Gt2DActor* actor = (Gt2DActor*)pObject; // GtSequenceInfo* info = actor->GetSequenceInfo( name.GetAciiString() ); //// if( info == NULL ) //// info = actor->AddNewSequence( name.GetAciiString(), fileName.GetAciiString() ); // GnSequence* sequence = info->GetSequence(); // GnAssert( sequence ); // // int textureCount = mChildren.GetSize(); // GnSMTextureAniCtrl* ani = GnObjectNew<GnSMTextureAniCtrl>::Create( textureCount ); // for( int i = 0 ; i < textureCount ; i++ ) // { // GcPropertyEntity* entity = mChildren.GetAt( i ); // Gc2DTexturePropEntity* child = (Gc2DTexturePropEntity*)entity; // } // //// actor->SetModifyingSequence( info ); return true; } void GcTextureAnimationPropEntity::ApplyObjectData(CMFCPropertyGridProperty* pChangeProp , EntityData* pCurrentObject) { //for( int i = 0 ; i < mpProperty->GetSubItemsCount() ; i++ ) //{ // CMFCPropertyGridProperty* prop = mpProperty->GetSubItem( i ); // if( prop == pChangeProp ) // { // Gt2DActor* actor = (Gt2DActor*)pCurrentObject; // GnAssert( actor->GetType() == Gt2DActor::OBJECT_TYPE ); // for( gtuint j = 0 ; j < mChildren.GetSize() ; j++ ) // { // Gc2DTexturePropEntity* textureEntity = (Gc2DTexturePropEntity*)((GcPropertyEntity*)mChildren.GetAt( j )); // textureEntity->SetStartTime( GetStartTime() ); // textureEntity->SetEndTime( GetEndTime() ); // } // Gn2DActor* gnActor = actor->GetActor(); // if( gnActor ) // { // gnActor->StopAnimation(); // gnActor->SetTargetAnimation(actor->GetCurrentSequenceInfo()->GetSequenceID()); // } // return; // } //} //for( gtuint i = 0 ; i < mChildren.GetSize() ; i++ ) //{ // mChildren.GetAt( i )->ApplyObjectData( pChangeProp, pCurrentObject ); //} } void GcTextureAnimationPropEntity::UpdateEvent(GcPropertyGridProperty* pChangedGridProperty) { if( mpAni == NULL || mpActor == NULL || mpActor->GetModifySequence() == NULL ) return; switch( pChangedGridProperty->GetData() ) { case MSG_STARTTIME: { } break; case MSG_ENDTIME: { GnAssert( mpActor->GetType() == Gt2DActor::OBJECT_TYPE); for( gtuint i = 0 ; i < mChildren.GetSize() ; i++ ) { Gc2DTexturePropEntity* textureEntity = (Gc2DTexturePropEntity*)((GcPropertyEntity*)mChildren.GetAt( i )); textureEntity->SetStartTime( GetStartTime() ); textureEntity->SetEndTime( GetEndTime() ); } float sequenceEndTime = 0.0f; for( gtuint i = 0 ; i < mpAni->GetAniInfoCount() ; i++ ) { Gn2DTextureAni::TextureAniInfo* aniInfo = (Gn2DTextureAni::TextureAniInfo*)mpAni->GetAniInfo( i ); aniInfo->SetEndTime( GetEndTime() ); sequenceEndTime += GetEndTime(); } mpAni->SetAniSpeed( GetEndTime() ); mpActor->GetModifySequence()->GetSequence()->SetEndTime( sequenceEndTime ); SendMediateMessage( GTMG_CHAGESEQUENCEANITIME, NULL ); } break; default: return; } mpActor->GetModifySequence()->SetModifed( true ); }
#include "Complex.h" #include <iostream> using namespace std; Complex::Complex(double xx, double yy) :x(xx), y(yy) {} void Complex::dis() { cout << '(' << x << ',' << y << ')' << endl; } Complex& Complex::operator+=(const Complex& another) { this->x += another.x; this->y += another.y; return *this; } Complex& Complex::operator++() { x++; y++; return *this; } const Complex& Complex::operator++(int) { Complex t(this->x, this->y); (this->x)++; (this->y)++; return t; } ostream& operator<<(ostream &os, const Complex& c) { return os << '(' << c.x << ',' << c.y << ')'; } istream& operator>>(istream& is,Complex& c) { return is >> c.x >> c.y; }
//-------------------------------------------------------- // musket/include/musket/caret.hpp // // Copyright (C) 2018 LNSEAB // // released under the MIT License. // https://opensource.org/licenses/MIT //-------------------------------------------------------- #ifndef MUSKET_CARET_HPP_ #define MUSKET_CARET_HPP_ #include "widget.hpp" #include "color.hpp" namespace musket { class caret { spirea::area_t< float > sz_; rgba_color_t color_; spirea::d2d1::solid_color_brush color_brush_; bool visibility_ = false; public: caret() = default; caret(spirea::area_t< float > const& sz, rgba_color_t const& color = { 1.0f, 1.0f, 1.0f, 1.0f }) : sz_{ sz }, color_{ color } { } void show() { visibility_ = true; } void hide() { visibility_ = false; } void draw(spirea::d2d1::render_target const& rt, spirea::point_t< float > const& pos) { if( !visibility_ ) { return; } auto rc = spirea::rect_traits< spirea::d2d1::rect_f >::construct( spirea::rect_t< float >{ pos, sz_ } ); rt->FillRectangle( rc, color_brush_.get() ); } void recreated_target(spirea::d2d1::render_target const& rt) { color_brush_.reset(); rt->CreateSolidColorBrush( color_, color_brush_.pp() ); } }; } // namespace musket #endif // MUSKET_CARET_HPP_
#include<iostream> #include <stdlib.h> using namespace std; struct queue { int size; int f; int r; int* arr; }; int isFull(struct queue *q){ if(q->r==q->size-1){ return 1; } return 0; } void enqueue(struct queue *q, int val){ if(isFull(q)){ printf("This Queue is full\n"); } else{ q->r++; q->arr[q->r] = val; printf("Enqued element: %d\n", val); } } int isEmpty(struct queue *q){ if(q->r==q->f){ return 1; } return 0; } int dequeue(struct queue *q){ if(isEmpty(q)){ cout<<"the queue is empty"; return 0; } else{ q->f++; return q->arr[q->f]; } } int main(){ struct queue q; q.size=10; q.r=q.f=-1; q.arr=(int*)malloc(q.size*sizeof(int)); enqueue(&q, 12); // cout<<q.arr[0]; cout<<"The element dequeued is "<<dequeue(&q)<<endl; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 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 "adjunct/quick/application/BrowserApplicationCacheListener.h" #include "adjunct/quick/windows/DocumentDesktopWindow.h" #include "adjunct/quick/Application.h" #include "adjunct/quick/models/DesktopWindowCollection.h" #include "adjunct/quick/widgets/OpLocalStorageBar.h" #include "adjunct/quick/dialogs/WebStorageQuotaDialog.h" #include "modules/prefs/prefsmanager/collections/pc_ui.h" #include "modules/url/url_man.h" #define APPLICATION_CACHE_QUOTA_STEP 20*1024*1024 void BrowserApplicationCacheListener::OnDownloadAppCache(OpWindowCommander* commander, UINTPTR id, InstallAppCacheCallback* callback) { ApplicationCacheStrategy strategy = GetStrategy(commander); DocumentDesktopWindow* win = g_application->GetDesktopWindowCollection().GetDocumentWindowFromCommander(commander); if (!win) { if (IsDragonFlyWindow(commander) || strategy == Accept) { callback->OnDownloadAppCacheReply(TRUE); } else { OP_ASSERT(FALSE); callback->OnDownloadAppCacheReply(FALSE); } return; } if (strategy == Ask) { OpLocalStorageBar* bar = win->GetLocalStorageBar(); if (bar->GetRequestID() != id) bar->Show(callback, Download, id, commander->GetCurrentURL(FALSE)); } else if (strategy == Accept) { callback->OnDownloadAppCacheReply(TRUE); } else { callback->OnDownloadAppCacheReply(FALSE); } } void BrowserApplicationCacheListener::CancelDownloadAppCache(OpWindowCommander* commander, UINTPTR id) { CancelToolbar(commander, id); } void BrowserApplicationCacheListener::OnCheckForNewAppCacheVersion(OpWindowCommander* commander, UINTPTR id, InstallAppCacheCallback* callback) { ApplicationCacheStrategy strategy = GetStrategy(commander); DocumentDesktopWindow* win = g_application->GetDesktopWindowCollection().GetDocumentWindowFromCommander(commander); if (!win) { if (IsDragonFlyWindow(commander) || strategy == Accept) { callback->OnCheckForNewAppCacheVersionReply(TRUE); } else { OP_ASSERT(FALSE); callback->OnCheckForNewAppCacheVersionReply(FALSE); } return; } if (strategy == Ask) { OpLocalStorageBar* bar = win->GetLocalStorageBar(); if (bar->GetRequestID() != id) bar->Show(callback, CheckForUpdate, id, commander->GetCurrentURL(FALSE)); } else if (strategy == Accept) { callback->OnCheckForNewAppCacheVersionReply(TRUE); } else { callback->OnCheckForNewAppCacheVersionReply(FALSE); } } void BrowserApplicationCacheListener::CancelCheckForNewAppCacheVersion(OpWindowCommander* commander, UINTPTR id) { CancelToolbar(commander, id); } void BrowserApplicationCacheListener::OnDownloadNewAppCacheVersion(OpWindowCommander* commander, UINTPTR id, InstallAppCacheCallback* callback) { ApplicationCacheStrategy strategy = GetStrategy(commander); DocumentDesktopWindow* win = g_application->GetDesktopWindowCollection().GetDocumentWindowFromCommander(commander); if (!win) { if (IsDragonFlyWindow(commander) || strategy == Accept) { callback->OnDownloadNewAppCacheVersionReply(TRUE); } else { OP_ASSERT(FALSE); callback->OnDownloadNewAppCacheVersionReply(FALSE); } return; } if (strategy == Ask) { OpLocalStorageBar* bar = win->GetLocalStorageBar(); if (bar->GetRequestID() != id) bar->Show(callback, UpdateCache, id, commander->GetCurrentURL(FALSE)); } else if (strategy == Accept) { callback->OnDownloadNewAppCacheVersionReply(TRUE); } else { callback->OnDownloadNewAppCacheVersionReply(FALSE); } } void BrowserApplicationCacheListener::CancelDownloadNewAppCacheVersion(OpWindowCommander* commander, UINTPTR id) { CancelToolbar(commander, id); } void BrowserApplicationCacheListener::OnIncreaseAppCacheQuota(OpWindowCommander* commander, UINTPTR id, const uni_char* cache_domain, OpFileLength current_quota_size, QuotaCallback *callback) { DocumentDesktopWindow* win = g_application->GetDesktopWindowCollection().GetDocumentWindowFromCommander(commander); if (!win) { if (IsDragonFlyWindow(commander)) { callback->OnQuotaReply(TRUE, current_quota_size + APPLICATION_CACHE_QUOTA_STEP); } else { OP_ASSERT(FALSE); callback->OnQuotaReply(FALSE, current_quota_size); } return; } // Always ask even if the strategy is accept ApplicationCacheStrategy strategy = GetStrategy(commander); if (strategy == Reject) { OP_ASSERT(FALSE); callback->OnQuotaReply(FALSE, current_quota_size); return; } //else if (strategy == Accept) //{ // // silently increase the quota // callback->OnQuotaReply(TRUE, current_quota_size + APPLICATION_CACHE_QUOTA_STEP); //} else { // Ask WebStorageQuotaDialog* dialog = OP_NEW(WebStorageQuotaDialog,(commander->GetCurrentURL(FALSE), current_quota_size, current_quota_size + APPLICATION_CACHE_QUOTA_STEP, id)); if (!dialog) { callback->OnQuotaReply(FALSE, current_quota_size); return; } dialog->SetApplicationCacheCallback(callback); dialog->Init(win); } } void BrowserApplicationCacheListener::CancelIncreaseAppCacheQuota(OpWindowCommander* commander, UINTPTR id) { OpVector<DesktopWindow> windows; g_application->GetDesktopWindowCollection().GetDesktopWindows(windows); for(UINT32 i=0; i<windows.GetCount(); i++) { DesktopWindow* win = windows.Get(i); for (INT32 j=0; j<win->GetDialogCount(); j++) { Dialog* dialog = win->GetDialog(j); if (dialog->GetType() == OpTypedObject::DIALOG_TYPE_WEBSTORAGE_QUOTA_DIALOG) { if (((WebStorageQuotaDialog*)dialog)->GetApplicationCacheCallbackID() == id) dialog->CloseDialog(FALSE); // Don't call cancel, the callback the dialog hold is already invalid } } } } void BrowserApplicationCacheListener::CancelToolbar(OpWindowCommander* commander, UINTPTR id) { DocumentDesktopWindow* win = g_application->GetDesktopWindowCollection().GetDocumentWindowFromCommander(commander); if (win) { OpLocalStorageBar* bar = win->GetLocalStorageBar(); if (bar->GetRequestID() == id) bar->Cancel(); } } ApplicationCacheStrategy BrowserApplicationCacheListener::GetStrategy(OpWindowCommander* commander) { const uni_char* url = commander->GetCurrentURL(FALSE); URL tmp = urlManager->GetURL(url); if (tmp.GetServerName()) { int strategy = g_pcui->GetIntegerPref(PrefsCollectionUI::StrategyOnApplicationCache, tmp.GetServerName()->UniName()); switch (strategy) { case 0: return Ask; case 1: return Accept; case 2: default: break; } } return Reject; } BOOL BrowserApplicationCacheListener::IsDragonFlyWindow(OpWindowCommander* commander) { DesktopWindow* win = g_application->GetDesktopWindowCollection().GetDesktopWindowFromOpWindow(commander->GetOpWindow()); return win && win->GetType() == OpTypedObject::WINDOW_TYPE_DEVTOOLS; }
#pragma once #include "MyDocument.h" class CTestDoc : public CMyDocument { MY_DECLARE_DYNCREATE(CTestDoc) public: CTestDoc(); virtual ~CTestDoc(); };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #ifndef SSL_CERTINST_BASE_H #define SSL_CERTINST_BASE_H #if defined _NATIVE_SSL_SUPPORT_ && defined USE_SSL_CERTINSTALLER #include "modules/libssl/options/optenums.h" /** This structure contain the installation flags to be used: the certificate store and (if relevant) the validation flags */ struct SSL_Certificate_Installer_flags { SSL_CertificateStore store; BOOL warn_before_use; BOOL forbid_use; SSL_Certificate_Installer_flags(): store(SSL_Unknown_Store), warn_before_use(TRUE), forbid_use(TRUE){} SSL_Certificate_Installer_flags(SSL_CertificateStore str, BOOL warn, BOOL deny): store(str), warn_before_use(warn), forbid_use(deny){} }; /** This class is the public class for the Ceritficate installation API * * Objects that inherits this class must act as multistep procedures that return to the caller between each step. * Each step must terminate within a reasonable time and MUST NOT use blocking UI requests. * * Implementations controls the sequence, the formats supported and how to indicate when the operation is finished. */ class SSL_Certificate_Installer_Base { public: /** Constructor */ SSL_Certificate_Installer_Base(){}; /** Destructor */ virtual ~SSL_Certificate_Installer_Base(){}; /** Starts the installation. * Returns: * InstallerStatus::INSTALL_FINISHED when finished * InstallerStatus::ERR_INSTALL_FAILED when it fails * InstallerStatus::ERR_PASSWORD_NEEDED when a password is needed before installation can continue (password is managed internally) */ virtual OP_STATUS StartInstallation()=0; /** Return TRUE if the installation procedure is finished */ virtual BOOL Finished()=0; /** Return TRUE if the installation was finsihed with success. The return is only valid if Finished() returns TRUE */ virtual BOOL InstallSuccess()=0; /** Return the first remaining item of the warnings and errors encountered during the installation * Str::S_NOT_A_STRING is returned if there are no more warnings. * The return is only valid if Finished() returns TRUE */ virtual Str::LocaleString ErrorStrings(OpString &info)=0; /** Sets an optional password to use for certificate installation, only needed for non-interactive use. * * @param pass the password to use for import operations. * @return an appropriate return code from the OP_STATUS enumeration. */ virtual OP_STATUS SetImportPassword(const char* pass)=0; }; #endif // USE_SSL_CERTINSTALLER #endif // SSL_CERTINST_BASE_H
#pragma once #ifndef H_TEASER_UTILITY_H #define H_TEASER_UTILITY_H #include <chrono> #include <iostream> #include <random> #include <Eigen/Core> // #include <teaser/ply_io.h> #include <teaser/teaser_registration.h> #include <teaser/teaser_matcher.h> #include <string> #include <io.h> #include <pcl/point_types.h> #include <pcl/io/io.h> #include <pcl/io/pcd_io.h> #include <pcl/io/ply_io.h> #include <pcl/common/transforms.h> using namespace std; //// Macro constants for generating noise and outliers //const double NOISE_BOUND = 0.005; // 0.05 //const int N_OUTLIERS = 1700; //const double OUTLIER_TRANSLATION_LB = -5.0; // 0.5; //const double OUTLIER_TRANSLATION_UB = +5.0; // 0.5; //inline double getAngularError(Eigen::Matrix3d R_exp, Eigen::Matrix3d R_est) { // return std::abs(std::acos(fmin(fmax(((R_exp.transpose() * R_est).trace() - 1) / 2, -1.0), 1.0))); //} // //inline double rand_fun(const double& a, const double& b) { // if ( a > b ) { // printf_s("error in rand_fun()! lb should less than ub!\n"); // exit(-1); // } // //// dVal lies in [0, 1] // double dVal = rand() / (1.0 + RAND_MAX); // double dOut = ( b - a ) * dVal + a; // return dOut; //} // //inline void addNoiseAndOutliers(Eigen::Matrix<double, 3, Eigen::Dynamic>& tgt) { // // Add uniform noise // Eigen::Matrix<double, 3, Eigen::Dynamic> noise = // Eigen::Matrix<double, 3, Eigen::Dynamic>::Random(3, tgt.cols()) * NOISE_BOUND; // NOISE_BOUND / 2; // tgt = tgt + noise; // // // Add outliers // std::random_device rd; // std::mt19937 gen(rd()); // std::uniform_int_distribution<> dis2(0, tgt.cols() - 1); // pos of outliers // // std::uniform_int_distribution<> dis3(OUTLIER_TRANSLATION_LB, OUTLIER_TRANSLATION_UB); // random translation // std::vector<bool> expected_outlier_mask(tgt.cols(), false); // //for (int i = 0; i < 100; i++) { // // double dVal = rand_fun(OUTLIER_TRANSLATION_LB, OUTLIER_TRANSLATION_UB); // // printf_s("rand_num = %f\n", dVal); // //} // for (int i = 0; i < N_OUTLIERS; ++i) { // int c_outlier_idx = dis2(gen); // assert(c_outlier_idx < expected_outlier_mask.size()); // expected_outlier_mask[c_outlier_idx] = true; // tgt(0, c_outlier_idx) += rand_fun(OUTLIER_TRANSLATION_LB, OUTLIER_TRANSLATION_UB); // tgt(1, c_outlier_idx) += rand_fun(OUTLIER_TRANSLATION_LB, OUTLIER_TRANSLATION_UB); // tgt(2, c_outlier_idx) += rand_fun(OUTLIER_TRANSLATION_LB, OUTLIER_TRANSLATION_UB); // // tgt.col(c_outlier_idx).array() += dis3(gen); // random translation // } //} //template<typename T> //inline void cvt2Teaser_cloud( // const boost::shared_ptr<pcl::PointCloud<T>>& cloud_pcl, // teaser::PointCloud& cloud_teaser ) { // cloud_teaser.clear(); // for (int i = 0; i < cloud_pcl->points.size(); i++) { // T pt = cloud_pcl->points[i]; // cloud_teaser.push_back( {pt.x, pt.y, pt.z} ); // } //} template<typename T> inline void cvt2pcl_cloud(const teaser::PointCloud& cloud_in, boost::shared_ptr<pcl::PointCloud<T>>& cloud_out) { cloud_out.reset(new pcl::PointCloud<T>()); for (int i = 0; i < cloud_in.size(); i++) { T pt; memset(&pt, 0, sizeof(pt)); pt.x = cloud_in.at(i).x; pt.y = cloud_in.at(i).y; pt.z = cloud_in.at(i).z; cloud_out->points.push_back(pt); } cloud_out->is_dense = true; cloud_out->width = 1; cloud_out->height = cloud_out->points.size(); } //inline void test_bunny() { // //// Load the .ply file // //teaser::PLYReader reader; // //teaser::PointCloud src_cloud; // //string sFile = "example_data\\bun_zipper_res3.ply"; // //if (-1 == access(sFile.c_str(), 0)) { // // printf_s("%s does not exist!\n", sFile.c_str()); // //} // //auto status = reader.read(sFile.c_str(), src_cloud); // //int N = src_cloud.size(); // // //// Convert the point cloud to Eigen // //Eigen::Matrix<double, 3, Eigen::Dynamic> src(3, N); // //for (size_t i = 0; i < N; ++i) { // // src.col(i) << src_cloud[i].x, src_cloud[i].y, src_cloud[i].z; // //} // // //// Homogeneous coordinates // //Eigen::Matrix<double, 4, Eigen::Dynamic> src_h; // //src_h.resize(4, src.cols()); // //src_h.topRows(3) = src; // //src_h.bottomRows(1) = Eigen::Matrix<double, 1, Eigen::Dynamic>::Ones(N); // // //// Apply an arbitrary SE(3) transformation // //Eigen::Matrix4d T; // //// clang-format off // //T << 9.96926560e-01, 6.68735757e-02, -4.06664421e-02, -1.15576939e-01, // // -6.61289946e-02, 9.97617877e-01, 1.94008687e-02, -3.87705398e-02, // // 4.18675510e-02, -1.66517807e-02, 9.98977765e-01, 1.14874890e-01, // // 0, 0, 0, 1; // //// clang-format on // // //// Apply transformation // //Eigen::Matrix<double, 4, Eigen::Dynamic> tgt_h = T * src_h; // //Eigen::Matrix<double, 3, Eigen::Dynamic> tgt = tgt_h.topRows(3); // // //// Add some noise & outliers // //addNoiseAndOutliers(tgt); // // //// Convert to teaser point cloud // //teaser::PointCloud tgt_cloud; // //for (size_t i = 0; i < tgt.cols(); ++i) { // // tgt_cloud.push_back({ static_cast<float>(tgt(0, i)), static_cast<float>(tgt(1, i)), // // static_cast<float>(tgt(2, i)) }); // //} // ////// save the point cloud. // //pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_tmp(new pcl::PointCloud<pcl::PointXYZ>()); // //cvt2pcl_cloud(src_cloud, cloud_tmp); // //pcl::PCDWriter pcdWriter; // //string sSaveFile = "cloud_src.pcd"; // //pcdWriter.writeBinary(sSaveFile, *cloud_tmp); // //cvt2pcl_cloud(tgt_cloud, cloud_tmp); // //sSaveFile = "cloud_tgt.pcd"; // //pcdWriter.writeBinary(sSaveFile, *cloud_tmp); // //// Compute FPFH // //std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); // //teaser::FPFHEstimation fpfh; // //auto obj_descriptors = fpfh.computeFPFHFeatures(src_cloud, 0.02, 0.04); // //auto scene_descriptors = fpfh.computeFPFHFeatures(tgt_cloud, 0.02, 0.04); // //std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); // // //int nTime_FPFH = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() / 1000.0; // //begin = std::chrono::steady_clock::now(); // //teaser::Matcher matcher; // // //bool use_absolute_scale = true, // // use_crosscheck = false, // // use_tuple_test = true; // //float tuple_scale = 0.5; // // //auto correspondences = matcher.calculateCorrespondences(src_cloud, tgt_cloud, // // *obj_descriptors, *scene_descriptors, // // use_absolute_scale, use_crosscheck, use_tuple_test, tuple_scale); // //end = std::chrono::steady_clock::now(); // //int nTime_corres = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() / 1000.0; // // //// Run TEASER++ registration // //// Prepare solver parameters // //teaser::RobustRegistrationSolver::Params params; // //params.noise_bound = NOISE_BOUND; // //params.cbar2 = 1; // //params.estimate_scaling = false; // //params.rotation_max_iterations = 100; // //params.rotation_gnc_factor = 1.4; // //params.rotation_estimation_algorithm = // // teaser::RobustRegistrationSolver::ROTATION_ESTIMATION_ALGORITHM::GNC_TLS; // //params.rotation_cost_threshold = 0.005; // // //// Solve with TEASER++ // //teaser::RobustRegistrationSolver solver(params); // //begin = std::chrono::steady_clock::now(); // //solver.solve(src_cloud, tgt_cloud, correspondences); // //end = std::chrono::steady_clock::now(); // // //auto solution = solver.getSolution(); // // //// Compare results // //std::cout << "=====================================" << std::endl; // //std::cout << " TEASER++ Results " << std::endl; // //std::cout << "=====================================" << std::endl; // //std::cout << "Expected rotation: " << std::endl; // //std::cout << T.topLeftCorner(3, 3) << std::endl; // //std::cout << "Estimated rotation: " << std::endl; // //std::cout << solution.rotation << std::endl; // //std::cout << "Error (deg): " << getAngularError(T.topLeftCorner(3, 3), solution.rotation) // // << std::endl; // //std::cout << std::endl; // //std::cout << "Expected translation: " << std::endl; // //std::cout << T.topRightCorner(3, 1) << std::endl; // //std::cout << "Estimated translation: " << std::endl; // //std::cout << solution.translation << std::endl; // //std::cout << "Error (m): " << (T.topRightCorner(3, 1) - solution.translation).norm() << std::endl; // //std::cout << std::endl; // //std::cout << "Number of correspondences: " << N << std::endl; // //std::cout << "Number of outliers: " << N_OUTLIERS << std::endl; // //int nTime_reg = std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() / 1000.0; // //printf_s("time_fpfh = %04dms, time_matcher = %04dms, time_reg = %04dms\n", // // nTime_FPFH, nTime_corres, nTime_reg); //} #endif // !H_UTILITY_H
#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; #define INF 1000000000 #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 #define MOD 1000000007 /* add vars here */ ll N,M; int a[1000], b[1000], c[1000], dist[1000][1000]; /* add your algorithm here */ void wf() { rep(i,N) { rep(j,N) { rep(k,N) { dist[j][k] = min(dist[j][k], dist[j][i] + dist[i][k]); } } } } int main() { cin >> N >> M; rep(i,N) { rep(j,N) { if (i == j) dist[i][j] = 0; else dist[i][j] = INF; } } rep(i,M) { cin >> a[i] >> b[i] >> c[i]; a[i]--,b[i]--; dist[a[i]][b[i]] = c[i]; dist[b[i]][a[i]] = c[i]; } ll ans = M; wf(); rep(i,M) { bool shortest = false; for (int j = 0; j < N; ++j) if (dist[j][a[i]] + c[i] == dist[j][b[i]]) shortest = true; if (shortest) ans--; } cout << ans << endl; }
#include<bits/stdc++.h> using namespace std; #define NO 3 int main(){ int point[][2]={80,80, 100,98, 60,80}; int sum=0,p_sum[NO]={0}; double ave; for (int i=0;i<NO;++i) { sum+=point[i][0]; } ave=(double)sum/NO; printf("english_ave is %5.1lf!\n",ave); sum=0; for (int i=0;i<NO;++i) { sum+=point[i][1]; } ave=(double)sum/NO; printf("math_ave is %5.1lf!\n",ave); for(int i=0;i<NO;++i) { for(int j=0;j<2;++j) { p_sum[i]+=point[i][j]; } printf("No.%d total is %d!!!\n",i+1,p_sum[i]); } }
//============================================================================ // Name : SpewFilterTesting.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ // SpewFilterTesting.cpp : Defines the entry point for the console application. // #define BOOST_TEST_ALTERNATIVE_INIT_API //#include "stdafx.h" #define BOOST_TEST_MODULE SpewFilter_UI //#define BOOST_AUTO_TEST_MAIN #define BOOST_TEST_NO_MAIN #include <boost/test/included/unit_test.hpp> #include "SpewFiltering.hpp" #define BOOST_NO_CXX11_SCOPED_ENUMS #include <boost/filesystem.hpp> #undef BOOST_NO_CXX11_SCOPED_ENUMS //#include <boost/filesystem.hpp> #include <fstream> static std::string UnicodeSource = "UnicodeTestSource_01.txt"; static std::string AnsiSource = "AnsiTestSource_01.txt"; #ifdef GCC #include <errno.h> static std::string sTestOutputFileName = "ATestforSeparateOutputFiles"; static std::string RelFolder = "..//Folder_Sandbox//"; static std::string SourceFolderPath = "//home//tomh//SpewFilterTesting//Test_File_Source//"; static std::string SandboxFolderPath = "//home//tomh//SpewFilterTesting//Folder_Sandbox//"; static std::string SandboxOutputFolderPath = "//home//tomh//SpewFilterTesting//Output_Files_Go_Here//"; static std::string RelOutputFolder = "..\\Output_Files_Go_Here\\"; #else #include <direct.h> #define chdir _chdir static std::string sTestOutputFileName = "A Test for Separate Output Files"; static std::string RelFolder = "..\\Folder SandBox\\"; static std::string SourceFolderPath = "C:\\Spew Filter Test\\Test File Source\\"; static std::string SandboxFolderPath = "C:\\Spew Filter Test\\Folder SandBox\\"; static std::string SandboxOutputFolderPath = "C:\\Spew Filter Test\\Output Files Can Go Here\\"; static std::string RelOutputFolder = "..\\Output Files Can Go Here\\"; #endif static std::string sInputFileOption = "-i "; static std::string sOutputFileOption = "-o "; static std::string sFilterAbvOption = "-t "; static std::string sFilterFullOption = "--TypeOfFilter="; static std::string sWhiteSpace_Leading = " \t\t \t\t \t\t\t \t \t \t\t\t "; static std::string sWhiteSpace_Trailing = "\t\t\t \t \t \t \t \t "; using namespace boost::unit_test; struct LogToFile { LogToFile() { std::string logFileName(boost::unit_test::framework::master_test_suite().p_name); logFileName.append(".xml"); logFile.open(logFileName.c_str()); boost::unit_test::unit_test_log.set_stream(logFile); } ~LogToFile() { boost::unit_test::unit_test_log.test_finish(); logFile.close(); boost::unit_test::unit_test_log.set_stream(std::cout); } std::ofstream logFile; }; BOOST_GLOBAL_FIXTURE(LogToFile); /*struct MyConfig { MyConfig() : test_log("example.log") { boost::unit_test::unit_test_log.set_stream(test_log); } ~MyConfig() { boost::unit_test::unit_test_log.set_stream(std::cout); } std::ofstream test_log; }; //____________________________________________________________________________// BOOST_GLOBAL_FIXTURE(MyConfig); */ int main(int argc, char ** argv ) { char * argv0 = argv[0]; return boost::unit_test::unit_test_main(&init_unit_test, argc, argv); } using namespace SpewFilteringSpace; const char * progName = "SpewFilter"; struct SpewFilter_fixture { SpewFiltering sfFiltering; std::string sInputFileParent; std::string sInputFileName; std::string sInputOptionID; int iArgumentNumberOfInputFile; std::string sOutputFileParent; std::string sOutputFileName; std::string sOutputOptionID; int iArgumentNumberOfOutputFile; std::string sFilterOptionID; std::string sFilterType; int iArgumentNumberOfFilterOption; int iNumberOfArgs; char * ArguementList[50]; std::string sInputFileArg; std::string sOutputFileArg; std::string sFilterOptionArg; std::string sInputFileLeadingWhiteSpace; std::string sInputFileTrailingWhiteSpace; std::string sOutputFileLeadingWhiteSpace; std::string sOutputFileTrailingWhiteSpace; std::string sOptionLeadingWhiteSpace; std::string sOptionTrailingWhiteSpace; void ConfigureArgCArgV() { iNumberOfArgs = 2; std::string sFilePath; ArguementList[0] = const_cast<char *>(progName); // Input File Name configuration; sInputFileArg = sInputOptionID + sInputFileLeadingWhiteSpace + sInputFileParent + sInputFileName + sInputFileTrailingWhiteSpace; ArguementList[iArgumentNumberOfInputFile] = const_cast<char *>(sInputFileArg.c_str()); if (!sOutputFileName.empty()) { iNumberOfArgs++; sOutputFileArg = sOutputOptionID + sOutputFileLeadingWhiteSpace + sOutputFileParent + sOutputFileName + sOutputFileTrailingWhiteSpace; ArguementList[iArgumentNumberOfOutputFile] = const_cast<char *>(sOutputFileArg.c_str()); } if (!sFilterType.empty()) { iNumberOfArgs++; sFilterOptionArg = sFilterOptionID + sOptionLeadingWhiteSpace + sFilterType + sOptionTrailingWhiteSpace; ArguementList[iArgumentNumberOfFilterOption] = const_cast<char *>(sFilterOptionArg.c_str()); } } void ClearArgvArgC() { sInputFileParent = ""; sInputFileName = ""; sInputOptionID = ""; sInputFileLeadingWhiteSpace = ""; sInputFileTrailingWhiteSpace = ""; iArgumentNumberOfInputFile = 1; sOutputFileParent = ""; sOutputFileName = ""; sOutputOptionID = ""; sOutputFileLeadingWhiteSpace = ""; sOutputFileTrailingWhiteSpace = ""; iArgumentNumberOfOutputFile = 2; sFilterOptionID = ""; sFilterType = ""; sOptionLeadingWhiteSpace = ""; sOptionTrailingWhiteSpace = ""; iArgumentNumberOfFilterOption = 3; iNumberOfArgs = 0; for (int i = 0; i < 50; i++) ArguementList[i] = nullptr; int iNameLen = strlen(SandboxFolderPath.c_str()); // Clear the Sandbox for previous test result files auto iDirChanged = chdir(SandboxFolderPath.c_str()); if (iDirChanged >= 0) { boost::filesystem::path full_path(boost::filesystem::current_path()); boost::filesystem::directory_iterator it(full_path), end; //directory_iterator end ; for (boost::filesystem::path const &p : it) { if (is_regular_file(p)) { boost::filesystem::remove_all(p); } } } // Put the test files in the Sandbox iDirChanged = chdir(SourceFolderPath.c_str()); if (iDirChanged >= 0) { boost::filesystem::path full_path(boost::filesystem::current_path()); boost::filesystem::directory_iterator it(full_path), end; //directory_iterator end ; //for( it ; it != end ; ++it ) for (boost::filesystem::path const &sourcePath : it) { //boost::filesystem::path sourcePath = *it; if (is_regular_file(sourcePath)) { std::string dest = SandboxFolderPath;// +sourcePath.filename.string(); boost::filesystem::path sourceName = sourcePath.filename(); dest += sourceName.string(); boost::filesystem::path destPath(dest); boost::filesystem::copy_file(sourcePath, destPath); } } } } }; typedef struct SpewFilter_fixture SpewFilterTestFixture; BOOST_AUTO_TEST_SUITE(test_SpewFilter); #define SPEW_FILTER_TEST_CASE(name_) \ BOOST_FIXTURE_TEST_CASE(SpewFilter_##name_, SpewFilter_fixture) BOOST_AUTO_TEST_SUITE(test_SpewFilter_InputFileSel); // Testing valid input file selections SPEW_FILTER_TEST_CASE(InptFile_RelPath_NoKey_No_Whitespace) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_No_Whitespace) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_NoKey_Whitespace) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputFileLeadingWhiteSpace = sWhiteSpace_Leading; sInputFileTrailingWhiteSpace = sWhiteSpace_Trailing; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_Whitespace) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; sInputFileLeadingWhiteSpace = sWhiteSpace_Leading; sInputFileTrailingWhiteSpace = sWhiteSpace_Trailing; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_AbsltPath_NoKey_No_Whitespace) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = SandboxFolderPath; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_AbsltPath_Key_No_Whitespace) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = SandboxFolderPath; sInputOptionID = sInputFileOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_AbsltPath_NoKey_Whitespace) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = SandboxFolderPath; // mix them up once in a while :) sInputFileLeadingWhiteSpace = sWhiteSpace_Trailing; sInputFileTrailingWhiteSpace = sWhiteSpace_Leading; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_AbsltPath_Key_Whitespace) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = SandboxFolderPath; sInputOptionID = sInputFileOption; sInputFileLeadingWhiteSpace = sWhiteSpace_Leading; sInputFileTrailingWhiteSpace = sWhiteSpace_Trailing; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } // Testing valid filter option selections SPEW_FILTER_TEST_CASE(InptFile_RelPath_NoKey_NoW_FFiltAll) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "a"; sFilterOptionID = sFilterFullOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_NoW_FFiltEvery) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "e"; sFilterOptionID = sFilterFullOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_NoW_FFiltHFP) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "h"; sFilterOptionID = sFilterFullOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_NoW_FFiltAS) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "s"; sFilterOptionID = sFilterFullOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_NoW_FFiltBT) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "p"; sFilterOptionID = sFilterFullOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_NoW_FFiltMap) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "m"; sFilterOptionID = sFilterFullOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_NoW_FFiltUSB) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "u"; sFilterOptionID = sFilterFullOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_NoW_AFiltAll) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "a"; sFilterOptionID = sFilterAbvOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_NoW_AFiltEvery) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "e"; sFilterOptionID = sFilterAbvOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_NoW_AFiltHFP) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "h"; sFilterOptionID = sFilterAbvOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_NoW_AFiltAS) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "s"; sFilterOptionID = sFilterAbvOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_NoW_AFiltBT) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "p"; sFilterOptionID = sFilterAbvOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_NoW_AFiltMap) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "m"; sFilterOptionID = sFilterAbvOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_NoW_AFiltUSB) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "u"; sFilterOptionID = sFilterAbvOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_W_FFiltAll) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "a"; sFilterOptionID = sFilterFullOption; sOptionLeadingWhiteSpace = sWhiteSpace_Leading; sOptionTrailingWhiteSpace = sWhiteSpace_Trailing; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_W_FFiltEvery) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "e"; sFilterOptionID = sFilterFullOption; sOptionLeadingWhiteSpace = sWhiteSpace_Leading; sOptionTrailingWhiteSpace = sWhiteSpace_Trailing; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_W_FFiltHFP) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "h"; sFilterOptionID = sFilterFullOption; // mixing it up sOptionLeadingWhiteSpace = sWhiteSpace_Trailing; sOptionTrailingWhiteSpace = sWhiteSpace_Leading; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_W_FFiltAcnScrpt) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "s"; sOptionLeadingWhiteSpace = sWhiteSpace_Leading; sOptionTrailingWhiteSpace = sWhiteSpace_Trailing; sFilterOptionID = sFilterFullOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_W_FFiltBT) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "p"; sOptionLeadingWhiteSpace = sWhiteSpace_Leading; sOptionTrailingWhiteSpace = sWhiteSpace_Trailing; sFilterOptionID = sFilterFullOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_W_FFiltMap) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "m"; sOptionLeadingWhiteSpace = sWhiteSpace_Leading; sOptionTrailingWhiteSpace = sWhiteSpace_Trailing; sFilterOptionID = sFilterFullOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_W_FFiltUSB) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "u"; sFilterOptionID = sFilterFullOption; sOptionLeadingWhiteSpace = sWhiteSpace_Leading; sOptionTrailingWhiteSpace = sWhiteSpace_Trailing; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_W_AFiltAll) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "a"; sFilterOptionID = sFilterAbvOption; sOptionLeadingWhiteSpace = sWhiteSpace_Leading; sOptionTrailingWhiteSpace = sWhiteSpace_Trailing; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_W_AFiltEvery) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "e"; sFilterOptionID = sFilterAbvOption; sOptionLeadingWhiteSpace = sWhiteSpace_Leading; sOptionTrailingWhiteSpace = sWhiteSpace_Trailing; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_W_AFiltHFP) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "h"; sFilterOptionID = sFilterAbvOption; sOptionLeadingWhiteSpace = sWhiteSpace_Leading; sOptionTrailingWhiteSpace = sWhiteSpace_Trailing; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_W_AFiltActnScrpt) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "s"; sFilterOptionID = sFilterAbvOption; sOptionLeadingWhiteSpace = sWhiteSpace_Leading; sOptionTrailingWhiteSpace = sWhiteSpace_Trailing; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_W_AFiltBT) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "p"; sFilterOptionID = sFilterAbvOption; sOptionLeadingWhiteSpace = sWhiteSpace_Leading; sOptionTrailingWhiteSpace = sWhiteSpace_Trailing; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_W_AFiltMap) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "m"; sFilterOptionID = sFilterAbvOption; sOptionLeadingWhiteSpace = sWhiteSpace_Leading; sOptionTrailingWhiteSpace = sWhiteSpace_Trailing; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_Key_W_AFiltUSB) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sInputOptionID = sInputFileOption; iArgumentNumberOfFilterOption = iArgumentNumberOfInputFile + 1; sFilterType = "u"; sFilterOptionID = sFilterAbvOption; sOptionLeadingWhiteSpace = sWhiteSpace_Leading; sOptionTrailingWhiteSpace = sWhiteSpace_Trailing; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } // Testing valid output file selections SPEW_FILTER_TEST_CASE(InptFile_RelPath_NoKey_NoW_Oabs) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; iArgumentNumberOfOutputFile = iArgumentNumberOfInputFile + 1; sOutputFileName = sTestOutputFileName; sOutputOptionID = sOutputFileOption; sOutputFileParent = SandboxOutputFolderPath; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_NoKey_NoW_Orel) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; iArgumentNumberOfOutputFile = iArgumentNumberOfInputFile + 1; sOutputFileName = sTestOutputFileName; sOutputOptionID = sOutputFileOption; sOutputFileParent = RelOutputFolder; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_NoKey_W_Oabs) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; iArgumentNumberOfOutputFile = iArgumentNumberOfInputFile + 1; sOutputFileName = sTestOutputFileName; sOutputOptionID = sOutputFileOption; sOutputFileParent = SandboxOutputFolderPath; sOutputFileLeadingWhiteSpace = sWhiteSpace_Leading; sOutputFileTrailingWhiteSpace = sWhiteSpace_Trailing; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(InptFile_RelPath_NoKey_W_Orel) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; iArgumentNumberOfOutputFile = iArgumentNumberOfInputFile + 1; sOutputFileName = sTestOutputFileName; sOutputOptionID = sOutputFileOption; sOutputFileParent = RelOutputFolder; sOutputFileLeadingWhiteSpace = sWhiteSpace_Leading; sOutputFileTrailingWhiteSpace = sWhiteSpace_Trailing; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == SUCCESS); } SPEW_FILTER_TEST_CASE(NotExistInptFile_RelPath_NoKey_No_Whitespace) { ClearArgvArgC(); sInputFileName = "..//Debug//Garbage.txt"; sInputFileParent = ""; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == ERROR_FILE_WAS_NOT_FOUND); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE(test_SpewFilter_OutputFileSel); SPEW_FILTER_TEST_CASE(NotExistOutptFile_RelPath_NoKey_No_Whitespace) { ClearArgvArgC(); sInputFileName = UnicodeSource; sInputFileParent = RelFolder; sOutputFileName = "..//Debug//Garbage.txt"; sOutputFileParent = ""; sOutputOptionID = sOutputFileOption; ConfigureArgCArgV(); SpewFiltering::SpewFilteringParams FilterParams; char ** pc = &ArguementList[0]; std::size_t Configured = sfFiltering.ConfigureFilteringParams(iNumberOfArgs, pc, FilterParams); BOOST_CHECK(Configured == ERROR_OUTPUT_FILE_PATH_NOT_FOUND); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
#include "CHttpReqDispatch.h" #include <stdlib.h> #include <string.h> #include "json/json.h" #include "Logger.h" #include "CalUsingTime.h" #include "url_code.h" #include "base64.h" //#if __DDCRYPTO__ //#include "DDCrypt.h" #include "XyRsa.h" #include "XyCryptoEx.h" //#endif #include "RedisLogic.h" #include "Helper.h" #include "Util.h" #include "http_handle/CTest.h" #include "http_handle/CGuestLogin.h" #include "http_handle/CAccountLogin.h" #include "http_handle/CRegUserName.h" #include "http_handle/CRegUserNameBinding.h" #include "http_handle/CRegGetLdCode.h" #include "http_handle/CRegBindingAliPay.h" #include "http_handle/CBankCreate.h" #include "http_handle/CBankSaveMoney.h" #include "http_handle/CBankGetMoney.h" #include "http_handle/CBankResetPasswd.h" #include "http_handle/CBankFindPasswd.h" #include "http_handle/CUpdateUser.h" #include "http_handle/CUpdateIcon.h" #include "http_handle/CGetPayInfo.h" #include "http_handle/CGetGameInfo.h" #include "http_handle/CGetRank.h" #include "http_handle/CGetRankAwardRules.h" #include "http_handle/CGuestBinding.h" #include "http_handle/CGetGameSwitch.h" #include "http_handle/CGetRoomConfig.h" #include "http_handle/CGetProductRoomConfig.h" #include "http_handle/CGetGameVersion.h" #include "http_handle/CGetGameOnline.h" #include "http_handle/CSetDefaultIcon.h" #include "http_handle/CGetGameResource.h" #include "http_handle/CGetCheating.h" #include "http_handle/CGetFeedBackSet.h" #include "http_handle/CGetFeedBackHistory.h" #include "http_handle/CGetTaskInfo.h" #include "http_handle/CGetTaskAward.h" #include "http_handle/CRegResetPassword.h" #include "http_handle/CRegGetPassword.h" #include "http_handle/CIssuedAccount.h" #include "http_handle/CCheckIdCode.h" #include "http_handle/CGetNotice.h" #include "http_handle/CCheckMnick.h" #include "http_handle/CCheckUserName.h" #include "http_handle/CReceiveBenefits.h" #include "http_handle/CReloadConfig.hpp" #include "http_handle/CGetWinGoldRank.h" #include "http_handle/CGetDrawGold.h" const std::string TEST = "test"; // 0. 测试接口 const std::string GUEST_LOGIN = "login.guest"; // 1. 快速登录 const std::string ACCOUNT_LOGIN = "login.account"; // 2. 账号登录 const std::string REGISTER_USER_NAME = "register.username"; // 3. 账号注册 const std::string REGISTER_USER_NAME_BINDING = "register.usernamebinding"; // 4. 绑定手机号 const std::string REGISTER_GET_LD_CODE = "register.getidcode"; // 5. 获取验证码 const std::string REGISTER_BINDING_ALI_PAY = "register.bindingalipay"; // 6. 绑定支付宝 const std::string BANK_CREATE = "bank.create"; // 7. 创建保险箱 const std::string BANK_SAVE_MONEY = "bank.savemoney"; // 8. 保险箱存钱 const std::string BANK_GET_MONEY = "bank.getmoney"; // 9. 保险箱取钱 const std::string BANK_RESET_PASSWORD = "bank.resetpassword"; // 10. 保险箱重置密码 const std::string BANK_FIND_PASSWORD = "bank.findpassword"; // 11. 通过手机验证码重置保险箱密码 const std::string CLIENT_BASE_UPDATE_USER = "clientbase.updateuser"; // 12. 更新用户信息 const std::string CLIENT_BASE_UPDATE_ICON = "clientbase.uploadicon"; // 13. 更新用户头像 // 14. 更新用户头像 const std::string CLIENT_BASE_GET_PAY_INFO = "clientbase.getpayinfo"; // 15. 客户短获取订单信息弹框 Clientbase 是正确的吗? const std::string CLIENT_BASE_GET_GAME_INFO = "clientbase.getgameinfo"; // 16. 客户端获取游戏金币信息 const std::string CLIENT_BASE_GET_RANK = "clientbase.getrank"; // 17. 获取排行榜 const std::string CLIENT_BASE_GET_RANK_AWARD_RULES = "clientbase.getrankawardrules"; // 18. 获取排行榜规则 const std::string CLIENT_BASE_GUEST_BING_DING = "clientbase.guestbingding"; // 19. 游客帐号升级 const std::string CLIENT_BASE_GET_GAME_SWITCH = "clientbase.getgameswitch"; // 20. 获取支付方式等开关 const std::string CLIENT_BASE_GET_ROOM_CONFIG = "clientbase.getroomconfig"; // 21. 获取游戏房间配置,老接口 const std::string CLIENT_BASE_GET_PRODUCT_ROOM_CONFIG = "clientbase.getproductroomconfig"; // 22. 获取游戏房间配置,新接口 const std::string CLIENT_BASE_GET_GAME_VERSION = "clientbase.getgameversion"; // 23. 获取游戏最新版本,用于更新 const std::string CLIENT_BASE_GET_GAME_ONLINE = "clientbase.getgameonline"; // 24. 获取游戏在线人数 const std::string CLIENT_BASE_SET_DEFAULT_ICON = "clientbase.setdefaulticon"; // 25. 设置默认头像 const std::string CLIENT_BASE_GET_GAME_RESOURCE = "clientbase.getgameresource"; // 26. 获取资源,用于热更 const std::string CLIENT_BASE_GET_CHEATING = "clientbase.getcheating"; // 27. 斗地主举报 const std::string FEEDBACK_SET = "feedback.set"; // 28. 用户提交反馈 const std::string FEEDBACK_GETHISTORY = "feedback.gethistory"; // 29. 用户获取反馈历史列表 const std::string GET_TASK_INFO = "task.gettaskinfo"; // 30. 获取任务列表 const std::string GET_TASK_AWARD = "task.gettaskaward"; // 31. 领取任务奖励 const std::string GET_NOTICE = "clientbase.getnotice"; //32. 获取公告 const std::string CHECK_MNICK = "clientbase.checkmnick"; //33. 检查昵称 const std::string RECEIVE_BENEFITS = "clientbase.setmoney"; //34. 领取救济金 const std::string CHECK_USERNAME = "register.checkusername"; //35.检测用户名 const std::string REGISTER_RESEET_PASSWORD = "register.resetpassword"; // 36. 重置账号密码 const std::string REGISTER_GET_PASSWORD = "register.getpassword"; // 通过短信获取密码 const std::string CHECK_ID_CODE = "register.checkidcode"; // 37. 检查短信验证码是否正确 const std::string REGISTER_ISSUED_ACCOUNT = "register.issuedaccount"; // 38. 生成随机账号 const std::string ADMIN_RELOAD_CONFIG = "admin.reloadconfig"; // 39 管理操作,重新加载配置文件 const std::string CLIENT_BASE_WINGOLD_RANK = "clientbase.getwingoldrank"; // 40 赢金币获得排行榜 const std::string CLIENT_BASE_DRAW_GOLD = "clientbase.getdrawgold"; // 41 抽金币(老虎机) #if __DDCRYPTO__ const std::string g_strDefAuthKeyOptionArr[] = {TEST, GUEST_LOGIN, ACCOUNT_LOGIN, REGISTER_USER_NAME, REGISTER_ISSUED_ACCOUNT, REGISTER_GET_PASSWORD, CLIENT_BASE_GET_GAME_SWITCH, CLIENT_BASE_GET_GAME_VERSION, CLIENT_BASE_GET_PRODUCT_ROOM_CONFIG, CLIENT_BASE_GET_GAME_RESOURCE, CLIENT_BASE_GET_GAME_INFO, CLIENT_BASE_GET_PAY_INFO, GET_NOTICE, ""}; bool DefAuthKeyOption(const std::string& strMethod) { int i = 0; while (!g_strDefAuthKeyOptionArr[i].empty()) { if (g_strDefAuthKeyOptionArr[i] == strMethod) return true; i++; } return false; } unsigned char privateKey [] = "-----BEGIN RSA PRIVATE KEY-----\n"\ "MIICWgIBAAKBgFPZr4m25ssVIY/YSKdaG/I/NfXkmzPI51mSJyrnwbzFl/zyQxH2\n"\ "yvRxeyVYjvBA0hQnJ7LpyxgR/sxyjsHSAg93hyNEAw4MBhKZ0dDRAqKmyrUs6Thw\n"\ "jLQpw0OmNw3Ca+yorggqvX5oReEiSyk46u7ciay3iyERBy60tbWihhNtAgMBAAEC\n"\ "gYAQf+Vq0/LWQ3I3O/gP9ktJf+a+XB2uMvpTRc8vQit9WeRugb1w639EWpBA6Qw3\n"\ "eoncLVhCfH7aXbAlyuUMfqao6tM9f1rAIBFKfDknjGRX8N9+r+zo82fspV1TLMAz\n"\ "cth+asjPRk0Oyky23rOSCg3xNFAu6CjYsqMGRQ2ZN8jEAQJBAJKbtBPNKdbm0baH\n"\ "s75h/qqa41CHaQB1bu9Zvoy1hszZVe73sF5Hp10gTjRR7AUJxXZibVXObFcgpbXV\n"\ "ke8i8ZUCQQCSalD2jtWzMDICWAONoI33RmEeN2QTpY/sFIvjIFUIZIJVM5oyzlq1\n"\ "eqwcxhaAG7KQr8JkcRiMP5vkb7yviVR5AkA1Wvs3daQzdL9/yXVN5UYUetgdl5pM\n"\ "M3DTJPsnJG1RogsXNAd42GT9jGNJwUK/NqYphnq6Dqz5LIWCXp6ExFfdAkAWkisv\n"\ "By/scraS4+yQTbr07rWUCef0m2ZHd5dlCRvyskPhTJYt1N/o8CNOQD9BuoNZiK7H\n"\ "+yNUo42ttof464vJAkAerD4kH38LX4JnhUa9wnZRbmeisTGEKZEtuKwcxzotQi3L\n"\ "Isd0bMA63NtXE6PzFY25C+aaK4WUDE/pXo791l5g\n"\ "-----END RSA PRIVATE KEY-----"; #endif CHttpReqDispatch::~CHttpReqDispatch() { std::map<std::string, CHttpRequestHandler*>::iterator itTmp = m_handlers.begin(); for (;itTmp != m_handlers.end();itTmp++) { if (itTmp->second) delete itTmp->second; // m_handlers.erase(itTmp); } m_handlers.clear(); } void CHttpReqDispatch::register_handler() { m_handlers[TEST] = new CTest(); m_handlers[GUEST_LOGIN] = new CGuestLogin(); m_handlers[ACCOUNT_LOGIN] = new CAccountLogin(); m_handlers[REGISTER_USER_NAME] = new CRegUserName(); m_handlers[REGISTER_USER_NAME_BINDING] = new CRegUserNameBinding(); m_handlers[REGISTER_GET_LD_CODE] = new CRegGetLdCode(); m_handlers[REGISTER_BINDING_ALI_PAY] = new CRegBindingAliPay(); m_handlers[BANK_CREATE] = new CBankCreate(); m_handlers[BANK_SAVE_MONEY] = new CBankSaveMoney(); m_handlers[BANK_GET_MONEY] = new CBankGetMoney(); m_handlers[BANK_RESET_PASSWORD] = new CBankResetPasswd(); m_handlers[BANK_FIND_PASSWORD] = new CBankFindPasswd(); m_handlers[CLIENT_BASE_UPDATE_USER] = new CUpdateUser(); m_handlers[CLIENT_BASE_UPDATE_ICON] = new CUpdateIcon(); m_handlers[CLIENT_BASE_GET_PAY_INFO] = new CGetPayInfo(); m_handlers[CLIENT_BASE_GET_GAME_INFO] = new CGetGameInfo(); m_handlers[CLIENT_BASE_GET_RANK] = new CGetRank(); m_handlers[CLIENT_BASE_GET_RANK_AWARD_RULES] = new CGetRankAwardRules(); m_handlers[CLIENT_BASE_GUEST_BING_DING] = new CGuestBinding(); m_handlers[CLIENT_BASE_GET_GAME_SWITCH] = new CGetGameSwitch(); m_handlers[CLIENT_BASE_GET_ROOM_CONFIG] = new CGetRoomConfig(); m_handlers[CLIENT_BASE_GET_PRODUCT_ROOM_CONFIG] = new CGetProductRoomConfig(); m_handlers[CLIENT_BASE_GET_GAME_VERSION] = new CGetGameVersion(); m_handlers[CLIENT_BASE_GET_GAME_ONLINE] = new CGetGameOnline(); m_handlers[CLIENT_BASE_SET_DEFAULT_ICON] = new CSetDefaultIcon(); m_handlers[CLIENT_BASE_GET_GAME_RESOURCE] = new CGetGameResource(); m_handlers[CLIENT_BASE_GET_CHEATING] = new CGetCheating(); m_handlers[FEEDBACK_SET] = new CGetFeedBackSet(); m_handlers[FEEDBACK_GETHISTORY] = new CGetFeedBackHistory(); m_handlers[GET_TASK_INFO] = new CGetTaskInfo(); m_handlers[GET_TASK_AWARD] = new CGetTaskAward(); m_handlers[REGISTER_RESEET_PASSWORD] = new CRegResetPassword(); m_handlers[REGISTER_GET_PASSWORD] = new CRegGetPassword(); m_handlers[REGISTER_ISSUED_ACCOUNT] = new CIssuedAccount(); m_handlers[CHECK_ID_CODE] = new CCheckIdCode(); m_handlers[GET_NOTICE] = new CGetNotice(); m_handlers[CHECK_MNICK] = new CCheckMnick(); m_handlers[CHECK_USERNAME] = new CCheckUserName(); m_handlers[RECEIVE_BENEFITS] = new CReceiveBenefits(); m_handlers[ADMIN_RELOAD_CONFIG] = new CReloadConfig(); m_handlers[CLIENT_BASE_WINGOLD_RANK] = new CGetWinGoldRank(); m_handlers[CLIENT_BASE_DRAW_GOLD] = new CGetDrawGold(); } CHttpRequestHandler* CHttpReqDispatch::getHttpRequestHandler(const std::string& method) { std::map<std::string, CHttpRequestHandler*>::iterator it = m_handlers.find(method); if (it == m_handlers.end()) { return NULL; } return it->second; } int CHttpReqDispatch::DispatchReq(const char* recvbuf, unsigned int rcvlen, const char* uri, const char *client_ip, std::string& strResult) { if (uri) { _LOG_DEBUG_("Http req dispatch: %s", uri); } if (!recvbuf || rcvlen == 0 || !uri || !client_ip ) { _LOG_WARN_("Http req dispatch: rcvlen[%u]\n", rcvlen); return -1; } //解密 #if __DDCRYPTO__ string strMsg = XyDeCrypt((unsigned char *)recvbuf,rcvlen); if (strMsg.empty() || strMsg.length() < 10) { _LOG_WARN_("Http req dispatch: rcvlen[%u] is error\n", rcvlen); return -1; } std::string strApi(strMsg.c_str(),4); #else if (rcvlen < 10) { _LOG_WARN_("Http req dispatch: rcvlen[%u] is too short\n", rcvlen); return -1; } std::string strApi(recvbuf,4); #endif //end 解密 //_LOG_INFO_("[HttpSvr:handleReq] recv buffer is[%s]\n", recvbuf); //LOGGER(E_LOG_INFO) << "recv buffer is " << recvbuf; // strApi.assign(recvbuf, 4); ToLower(strApi); if (strApi != "api=") { _LOG_WARN_("Http req dispatch: error key for post[%s]\n", strApi.c_str()); return -1; } try { Json::Reader jReader(Json::Features::strictMode()); Json::Value jvRoot; std::string strJson; #if __DDCRYPTO__ strJson.assign(strMsg.begin() + 4, strMsg.end()); #else strJson.assign(recvbuf + 4, rcvlen - 4); #endif strJson = urldecode(strJson); LOGGER(E_LOG_DEBUG) << "Recv Msg From: " << client_ip << "; Json is :" << strJson; if (!jReader.parse(strJson, jvRoot)) { _LOG_WARN_("[HttpSvr:handleReq] recv error json[%s]\n", strJson.c_str()); return -1; } std::string method = jvRoot["param"].get("method", "").asString(); //LOGGER(E_LOG_INFO) << "method is :" << method; ToLower(method); CHttpRequestHandler* handler = getHttpRequestHandler(method); int ret = status_method_error; HttpResult out; if (handler) { CCalUsingTime calUsingTime(method); ret = handler->do_request(jvRoot, (char *)client_ip, out); handler->makeRet(ret, out); } else { _LOG_INFO_("method %s miss match the request handler !!!!!!", method.c_str()); out["result"] = status_method_error; out["msg"] = "方法错误"; } Json::FastWriter jWriter; //加密 #if __DDCRYPTO__ std::string strSrcJson = jWriter.write(out); strResult = XyEnCrypt((unsigned char *)strSrcJson.c_str(),strSrcJson.length()); if(strResult.empty()) { _LOG_INFO_("method %s [Private Encrypt failed] !!!!!!", method.c_str()); return -1; } /*unsigned char RetEncrypted[40960] = {0}; encrypted_length = private_encrypt((unsigned char *)strSrcJson.c_str(), strSrcJson.size(), privateKey, RetEncrypted); if (encrypted_length == -1) { _LOG_INFO_("method %s [Private Encrypt failed] !!!!!!", method.c_str()); return -1; } char* RetB64Encrypted = NULL; encrypted_length = base64::base64Encode(RetEncrypted,encrypted_length,&RetB64Encrypted); if (RetB64Encrypted) { strResult = RetB64Encrypted; free(RetB64Encrypted); RetB64Encrypted = NULL; } else { _LOG_INFO_("method %s [Private Encrypt failed2] !!!!!!", method.c_str()); return -1; }*/ #else strResult = jWriter.write(out); #endif return strResult.size(); } catch (std::exception &ex) { _LOG_ERROR_("exception occured !!!%s", ex.what()); } return 0; }
#include "GOSIM.h" void GOSIM::GridUpdate(Grid *ti, Grid *real, Grid *errmap) { //test int bin_num = 20; //calculate histogram each time Grid *hist_ti = HistCalc(ti, bin_num, minvalue_ti, maxvalue_ti); Grid *hist_real = HistCalc(real, bin_num, minvalue_real, maxvalue_real); Grid out(real->length, real->width, real->height, VarNum+1); //Define a random path Grid randompath(real->length, real->width, real->height, 3); //Initialize the random path for (int z = 0; z < real->height; ++z) { for (int y = 0; y < real->width; ++y) { for (int x = 0; x < real->length; ++x) { randompath(x, y, z, 0) = x; randompath(x, y, z, 1) = y; randompath(x, y, z, 2) = z; } } } //assign the random path for (int z = 0; z < real->height; ++z) { for (int y = 0; y < real->width; ++y) { for (int x = 0; x < real->length; ++x) { int rz = randomInt(0, real->height-1); int ry = randomInt(0, real->width-1); int rx = randomInt(0, real->length-1); int tempx = randompath(x, y, z, 0); int tempy = randompath(x, y, z, 1); int tempz = randompath(x, y, z, 2); randompath(x, y, z, 0) = randompath(rx, ry, rz, 0); randompath(x, y, z, 1) = randompath(rx, ry, rz, 1); randompath(x, y, z, 2) = randompath(rx, ry, rz, 2); randompath(rx, ry, rz, 0) = tempx; randompath(rx, ry, rz, 1) = tempy; randompath(rx, ry, rz, 2) = tempz; } } } if (HistMatch == true) { for (int h = 0; h < real->height; ++h) { for (int w = 0; w < real->width; ++w) { for (int l = 0; l < real->length; ++l) { int x = randompath(l, w, h, 0); int y = randompath(l, w, h, 1); int z = randompath(l, w, h, 2); float binwidth_real = bin_num / (maxvalue_real - minvalue_real); float binwidth_ti = bin_num / (maxvalue_ti - minvalue_ti); for (int dz = -halfPatSizez; dz <= halfPatSizez; ++dz) { if (z+dz < 0) continue; if (z+dz >= out.height) break; for (int dy = -halfPatSizey; dy <= halfPatSizey; ++dy) { if (y+dy < 0) continue; if (y+dy >= out.width) break; for (int dx = -halfPatSizex; dx <= halfPatSizex; ++dx) { if (x+dx < 0) continue; if (x+dx >= out.length) break; int offsetx = (int)(*errmap)(x+dx, y+dy, z+dz, 0); int offsety = (int)(*errmap)(x+dx, y+dy, z+dz, 1); int offsetz = (int)(*errmap)(x+dx, y+dy, z+dz, 2); float weight = 1.0/((*errmap)(x+dx, y+dy, z+dz, 3) + 1.0); //float weight = 1.0; //reweighting for histogram float something = 0.0; for (int v = 0; v < VarNum; ++v) { float value = (*ti)(offsetx-dx, offsety-dy, offsetz-dz, v); int bin_real = (int)((value - minvalue_real) * binwidth_real); if (bin_real >= bin_num) { bin_real = bin_num-1; } if (bin_real < 0) { bin_real = 0; } int bin_ti = (int)((value - minvalue_ti) * binwidth_ti); if (bin_ti >= bin_num) { bin_ti = bin_num-1; } if (bin_ti < 0) { bin_ti = 0; } something += max(0.0f, (*hist_real)(bin_real, 0, 0, v) - (*hist_ti)(bin_ti, 0, 0, v)); } weight = weight / (1.0 + something); for (int v = 0; v < VarNum; v++) { out(x, y, z, v) += weight*(*ti)(offsetx-dx, offsety-dy, offsetz-dz, v); } out(x, y, z, VarNum) += weight; } } //calculate the old bin int bin_real_old = (int)(((*real)(x, y, z, 0) - minvalue_real) * binwidth_real); if (bin_real_old >= bin_num) { bin_real_old = bin_num-1; } if (bin_real_old < 0) { bin_real_old = 0; } //update the voxel(assuming only 1 variable) (*real)(x, y, z, 0) = out(x, y, z, 0) / out(x, y, z, 1); float value = (*real)(x, y, z, 0); minvalue_real = min(value, minvalue_real); maxvalue_real = max(value, maxvalue_real); binwidth_real = bin_num / (maxvalue_real - minvalue_real); //calculate the new bin int bin_real_new = (int)((value - minvalue_real) * binwidth_real); if (bin_real_new >= bin_num) { bin_real_new = bin_num-1; } if (bin_real_new < 0) { bin_real_new = 0; } //if the same bin, do nothing if (bin_real_old == bin_real_new) continue; else { //update the histogram double scale = 1.0 / (real->length * real->width * real->height); (*hist_real)(bin_real_old, 0, 0, 0) = ((*hist_real)(bin_real_old, 1, 0, 0) - 1) * scale; (*hist_real)(bin_real_new, 0, 0, 0) = ((*hist_real)(bin_real_new, 1, 0, 0) + 1) * scale; } } } } } } else { for (int z = 0; z < real->height; ++z) { for (int y = 0; y < real->width; ++y) { for (int x = 0; x < real->length; ++x) { for (int dz = -halfPatSizez; dz <= halfPatSizez; ++dz) { if (z+dz < 0) continue; if (z+dz >= out.height) break; for (int dy = -halfPatSizey; dy <= halfPatSizey; ++dy) { if (y+dy < 0) continue; if (y+dy >= out.width) break; for (int dx = -halfPatSizex; dx <= halfPatSizex; ++dx) { if (x+dx < 0) continue; if (x+dx >= out.length) break; int offsetx = (int)(*errmap)(x+dx, y+dy, z+dz, 0); int offsety = (int)(*errmap)(x+dx, y+dy, z+dz, 1); int offsetz = (int)(*errmap)(x+dx, y+dy, z+dz, 2); float weight = 1.0/((*errmap)(x+dx, y+dy, z+dz, 3) + 1.0); //float weight = 1.0; for (int v = 0; v < VarNum; v++) { out(x, y, z, v) += weight*(*ti)(offsetx-dx, offsety-dy, offsetz-dz, v); } out(x, y, z, VarNum) += weight; } } } (*real)(x, y, z, 0) = out(x, y, z, 0) / out(x, y, z, 1); } } } } }
/* * Copyright (C) 1999-2001 Brian Paul All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* * This is a port of the infamous "glxgears" demo to straight EGL * Port by Dane Rushton 10 July 2005 * * No command line options. * Program runs for 5 seconds then exits, outputing framerate to console */ #include <math.h> #include <stdlib.h> #include <GL/gl.h> #include <EGL/egl.h> #include "eglut.h" #include <iostream> #include <iomanip> #include <cstring> #include <fstream> extern "C" { int test_init(); } static GLfloat view_rotx = 20.0, view_roty = 30.0, view_rotz = 0.0; static GLint gear1, gear2, gear3; static GLfloat angle = 0.0; static int win; static int width = 1920, height = 1080; /* * * Draw a gear wheel. You'll probably want to call this function when * building a display list since we do a lot of trig here. * * Input: inner_radius - radius of hole at center * outer_radius - radius at center of teeth * width - width of gear * teeth - number of teeth * tooth_depth - depth of tooth */ static void gear(GLfloat inner_radius, GLfloat outer_radius, GLfloat width, GLint teeth, GLfloat tooth_depth) { GLint i; GLfloat r0, r1, r2; GLfloat angle, da; GLfloat u, v, len; r0 = inner_radius; r1 = outer_radius - tooth_depth / 2.0; r2 = outer_radius + tooth_depth / 2.0; da = 2.0 * M_PI / teeth / 4.0; glShadeModel(GL_FLAT); glNormal3f(0.0, 0.0, 1.0); /* draw front face */ glBegin(GL_QUAD_STRIP); for (i = 0; i <= teeth; i++) { angle = i * 2.0 * M_PI / teeth; glVertex3f(r0 * cos(angle), r0 * sin(angle), width * 0.5); glVertex3f(r1 * cos(angle), r1 * sin(angle), width * 0.5); if (i < teeth) { glVertex3f(r0 * cos(angle), r0 * sin(angle), width * 0.5); glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5); } } glEnd(); /* draw front sides of teeth */ glBegin(GL_QUADS); da = 2.0 * M_PI / teeth / 4.0; for (i = 0; i < teeth; i++) { angle = i * 2.0 * M_PI / teeth; glVertex3f(r1 * cos(angle), r1 * sin(angle), width * 0.5); glVertex3f(r2 * cos(angle + da), r2 * sin(angle + da), width * 0.5); glVertex3f(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), width * 0.5); glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5); } glEnd(); glNormal3f(0.0, 0.0, -1.0); /* draw back face */ glBegin(GL_QUAD_STRIP); for (i = 0; i <= teeth; i++) { angle = i * 2.0 * M_PI / teeth; glVertex3f(r1 * cos(angle), r1 * sin(angle), -width * 0.5); glVertex3f(r0 * cos(angle), r0 * sin(angle), -width * 0.5); if (i < teeth) { glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5); glVertex3f(r0 * cos(angle), r0 * sin(angle), -width * 0.5); } } glEnd(); /* draw back sides of teeth */ glBegin(GL_QUADS); da = 2.0 * M_PI / teeth / 4.0; for (i = 0; i < teeth; i++) { angle = i * 2.0 * M_PI / teeth; glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5); glVertex3f(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), -width * 0.5); glVertex3f(r2 * cos(angle + da), r2 * sin(angle + da), -width * 0.5); glVertex3f(r1 * cos(angle), r1 * sin(angle), -width * 0.5); } glEnd(); /* draw outward faces of teeth */ glBegin(GL_QUAD_STRIP); for (i = 0; i < teeth; i++) { angle = i * 2.0 * M_PI / teeth; glVertex3f(r1 * cos(angle), r1 * sin(angle), width * 0.5); glVertex3f(r1 * cos(angle), r1 * sin(angle), -width * 0.5); u = r2 * cos(angle + da) - r1 * cos(angle); v = r2 * sin(angle + da) - r1 * sin(angle); len = sqrt(u * u + v * v); u /= len; v /= len; glNormal3f(v, -u, 0.0); glVertex3f(r2 * cos(angle + da), r2 * sin(angle + da), width * 0.5); glVertex3f(r2 * cos(angle + da), r2 * sin(angle + da), -width * 0.5); glNormal3f(cos(angle), sin(angle), 0.0); glVertex3f(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), width * 0.5); glVertex3f(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), -width * 0.5); u = r1 * cos(angle + 3 * da) - r2 * cos(angle + 2 * da); v = r1 * sin(angle + 3 * da) - r2 * sin(angle + 2 * da); glNormal3f(v, -u, 0.0); glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5); glVertex3f(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5); glNormal3f(cos(angle), sin(angle), 0.0); } glVertex3f(r1 * cos(0), r1 * sin(0), width * 0.5); glVertex3f(r1 * cos(0), r1 * sin(0), -width * 0.5); glEnd(); glShadeModel(GL_SMOOTH); /* draw inside radius cylinder */ glBegin(GL_QUAD_STRIP); for (i = 0; i <= teeth; i++) { angle = i * 2.0 * M_PI / teeth; glNormal3f(-cos(angle), -sin(angle), 0.0); glVertex3f(r0 * cos(angle), r0 * sin(angle), -width * 0.5); glVertex3f(r0 * cos(angle), r0 * sin(angle), width * 0.5); } glEnd(); } static void draw(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); glRotatef(view_rotx, 1.0, 0.0, 0.0); glRotatef(view_roty, 0.0, 1.0, 0.0); glRotatef(view_rotz, 0.0, 0.0, 1.0); glPushMatrix(); glTranslatef(-3.0, -2.0, 0.0); glRotatef(angle, 0.0, 0.0, 1.0); glCallList(gear1); glPopMatrix(); glPushMatrix(); glTranslatef(3.1, -2.0, 0.0); glRotatef(-2.0 * angle - 9.0, 0.0, 0.0, 1.0); glCallList(gear2); glPopMatrix(); glPushMatrix(); glTranslatef(-3.1, 4.2, 0.0); glRotatef(-2.0 * angle - 25.0, 0.0, 0.0, 1.0); glCallList(gear3); glPopMatrix(); glPopMatrix(); } static void idle(void) { static double t0 = -1.; double dt, t = eglutGet(EGLUT_ELAPSED_TIME) / 1000.0; if (t0 < 0.0) t0 = t; dt = t - t0; t0 = t; angle += 70.0 * dt; /* 70 degrees per second */ angle = fmod(angle, 360.0); /* prevents eventual overflow */ eglutPostRedisplay(); } /* new window size or exposure */ static void reshape(int width, int height) { GLfloat h = (GLfloat) height / (GLfloat) width; glViewport(0, 0, (GLint) width, (GLint) height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(-1.0, 1.0, -h, h, 5.0, 60.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0, 0.0, -40.0); } static void init(void) { static GLfloat pos[4] = { 5.0, 5.0, 10.0, 0.0 }; static GLfloat red[4] = { 0.8, 0.1, 0.0, 1.0 }; static GLfloat green[4] = { 0.0, 0.8, 0.2, 1.0 }; static GLfloat blue[4] = { 0.2, 0.2, 1.0, 1.0 }; glLightfv(GL_LIGHT0, GL_POSITION, pos); glEnable(GL_CULL_FACE); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); /* make the gears */ gear1 = glGenLists(1); glNewList(gear1, GL_COMPILE); glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, red); gear(1.0, 4.0, 1.0, 20, 0.7); glEndList(); gear2 = glGenLists(1); glNewList(gear2, GL_COMPILE); glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, green); gear(0.5, 2.0, 2.0, 10, 0.7); glEndList(); gear3 = glGenLists(1); glNewList(gear3, GL_COMPILE); glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, blue); gear(1.3, 2.0, 0.5, 10, 0.7); glEndList(); glEnable(GL_NORMALIZE); glClearColor(0.5,0.5,1.0,1.0); } void dumpFrameBuffer (int width, int height) { size_t numBytes = width * height * 3; unsigned char* rgb = new unsigned char[numBytes]; glReadBuffer (GL_BACK); glReadPixels (0,0, width, height, GL_RGB, GL_UNSIGNED_BYTE, rgb); std::ofstream outFile; outFile.open("eglgears.ppm", std::ios::binary); outFile << "P6" << "\n" << width << " " << height << "\n" << "255\n"; outFile.write((char*) rgb, numBytes); delete [] rgb; } static void keyboard (unsigned char key) { if (key == 27) { dumpFrameBuffer (width, height); eglutDestroyWindow(win); exit(0); } } int main(int argc, char *argv[]) { eglutInitWindowSize(width, height); eglutInitAPIMask(EGLUT_OPENGL_BIT); eglutInit(argc, argv); win = eglutCreateWindow("eglgears"); eglutIdleFunc(idle); eglutReshapeFunc(reshape); eglutDisplayFunc(draw); eglutKeyboardFunc(keyboard); init(); glDrawBuffer(GL_BACK); eglutMainLoop(); return 0; }
/* Copyright 2021 University of Manchester Licensed under the Apache License, Version 2.0(the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http: // www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <vector> #include "accelerated_query_node.hpp" #include "operation_types.hpp" #include "stream_data_parameters.hpp" using orkhestrafs::core_interfaces::operation_types::QueryOperationType; namespace orkhestrafs::dbmstodspi { /** * @brief Struct to hold all of the important information about a query node to * accelerate it with an FPGA. */ struct AcceleratedQueryNode { std::vector<StreamDataParameters> input_streams; std::vector<StreamDataParameters> output_streams; QueryOperationType operation_type; int operation_module_location; std::vector<int> composed_module_locations; std::vector<std::vector<int>> operation_parameters; auto operator==(const AcceleratedQueryNode& rhs) const -> bool { return input_streams == rhs.input_streams && output_streams == rhs.output_streams && operation_type == rhs.operation_type && operation_module_location == rhs.operation_module_location && composed_module_locations == rhs.composed_module_locations && operation_parameters == rhs.operation_parameters; } }; } // namespace orkhestrafs::dbmstodspi
#include "brickstest.hpp" #include <bricks/io/filestream.h> #include <bricks/io/memorystream.h> #include <bricks/io/cachestream.h> #include <bricks/io/substream.h> using namespace Bricks; using namespace Bricks::IO; TEST(BricksIoStreamTest, NonExistentFile) { EXPECT_THROW(FileStream("lolnonexistent", FileOpenMode::Open, FileMode::ReadOnly), ErrnoException) << "FileStream did not throw on non-existent file"; } TEST(BricksIoStreamTest, EmptyFile) { FileStream stream(TestPath.Combine("data/empty.bin"), FileOpenMode::Open, FileMode::ReadOnly); u8 buffer[1]; EXPECT_EQ(0, stream.Read(buffer, 1)) << "Stream read data from empty file"; } static void WriteTest(Stream* stream) { int value = 0xF88C; EXPECT_EQ(sizeof(value), stream->Write(&value, sizeof(value))) << "Stream write failed"; value = 0x1888; EXPECT_EQ(sizeof(value), stream->Write(&value, sizeof(value))) << "Stream write failed"; } static void ReadTest(Stream* stream) { int value = 0; EXPECT_EQ(sizeof(value), stream->Read(&value, sizeof(value))) << "Stream read failed"; EXPECT_EQ(0xF88C, value) << "Wrong stream data"; EXPECT_EQ(sizeof(value), stream->Read(&value, sizeof(value))) << "Stream read failed"; EXPECT_EQ(0x1888, value) << "Wrong stream data"; EXPECT_EQ(sizeof(value) * 2, stream->GetPosition()); EXPECT_EQ(stream->GetLength(), stream->GetPosition()); } TEST(BricksIoStreamTest, WriteReadTest) { String path = "/tmp/libbricks-test.bin"; { FileStream stream(path, FileOpenMode::Create, FileMode::ReadWrite, FilePermissions::OwnerReadWrite); WriteTest(tempnew stream); stream.SetPosition(0); ReadTest(tempnew stream); } { FileStream stream(path, FileOpenMode::Open, FileMode::ReadOnly, FilePermissions::OwnerReadWrite); ReadTest(tempnew stream); } Filesystem::GetDefault()->DeleteFile(path); } TEST(BricksIoStreamTest, WriteReadSubstreamTest) { String path = "/tmp/libbricks-test.bin"; { FileStream stream(path, FileOpenMode::Create, FileMode::WriteOnly, FilePermissions::OwnerReadWrite); WriteTest(tempnew stream); WriteTest(tempnew stream); } { FileStream stream(path, FileOpenMode::Open, FileMode::ReadOnly, FilePermissions::OwnerReadWrite); Substream substream(tempnew stream, 0, stream.GetLength() / 2); ReadTest(tempnew substream); } Filesystem::GetDefault()->DeleteFile(path); } TEST(BricksIoStreamTest, WriteReadCacheStreamTest) { String path = "/tmp/libbricks-test.bin"; { FileStream stream(path, FileOpenMode::Create, FileMode::WriteOnly, FilePermissions::OwnerReadWrite); WriteTest(tempnew stream); } { FileStream stream(path, FileOpenMode::Open, FileMode::ReadOnly, FilePermissions::OwnerReadWrite); CacheStream cachestream(tempnew stream); ReadTest(tempnew cachestream); } Filesystem::GetDefault()->DeleteFile(path); } TEST(BricksIoStreamTest, WriteReadMemoryStreamTest) { { MemoryStream stream; WriteTest(tempnew stream); stream.SetPosition(0); ReadTest(tempnew stream); } } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
/*** * @file FalconCLIBase.cpp * @brief Utility class for common operations (device opening, firmware loading, etc...) needed in command line interface examples * @author Kyle Machulis (kyle@nonpolynomial.com) * @version $Id$ * @copyright (c) 2007-2008 Nonpolynomial Labs/Kyle Machulis * @license BSD License * * $HeadURL$ * * Project info at http://libnifalcon.sourceforge.net/ * */ #include "falcon/util/FalconCLIBase.h" #ifdef LIBFTD2XX #include "falcon/comm/FalconCommFTD2XX.h" #endif #ifdef LIBFTDI #include "falcon/comm/FalconCommLibFTDI.h" #endif #ifdef LIBUSB #include "falcon/comm/FalconCommLibUSB.h" #endif #include "falcon/firmware/FalconFirmwareNovintSDK.h" #include "falcon/util/FalconFirmwareBinaryTest.h" #include "falcon/util/FalconFirmwareBinaryNvent.h" #include <iostream> namespace libnifalcon { namespace po = boost::program_options; FalconCLIBase::FalconCLIBase() { po::options_description program("Program Options"); program.add_options() ("help", "show this help message"); m_progOptions.add(program); } void FalconCLIBase::addOptions(int value) { if(value & COMM_OPTIONS) { po::options_description comm("Communication Options"); comm.add_options() #if defined(LIBUSB) ("libusb", "use libusb-1.0 based driver") #endif #if defined(LIBFTDI) ("libftdi", "use libftdi based driver") #elif defined(LIBFTD2XX) ("ftd2xx", "use ftd2xx based driver") #endif ; m_progOptions.add(comm); } if(value & DEVICE_OPTIONS) { po::options_description device("Device options"); device.add_options() ("device_count", "Print the number of devices currently connected and return") ("device_index", po::value<int>(), "Opens device of given index (starts at 0)") ; m_progOptions.add(device); } if(value & FIRMWARE_OPTIONS) { po::options_description firmware("Firmware Options"); firmware.add_options() ("nvent_firmware", "Use 'nVent' firmware (Recommended)") ("test_firmware", "Use test firmware") ("firmware_file", po::value<std::string>(), "Specify external firmware file (instead of nvent or test)") ("force_firmware", "Force firmware download, even if already loaded") ("skip_checksum", "Ignore checksum errors when loading firmware (useful for FTD2XX on non-windows platforms)") ; m_progOptions.add(firmware); } } bool FalconCLIBase::parseOptions(FalconDevice& device, int argc, char** argv) { po::store(po::parse_command_line(argc, argv, m_progOptions), m_varMap); po::notify(m_varMap); if (m_varMap.count("help")) { std::cout << "Usage: falcon_test_cli [args]" << std::endl; std::cout << m_progOptions << std::endl; return false; } device.setFalconFirmware<FalconFirmwareNovintSDK>(); //First off, see if we have a communication method if(m_varMap.count("libftdi") && m_varMap.count("ftd2xx")) { std::cout << "Error: can only use one comm method. Choose either libftdi or ftd2xx, depending on which is available." << std::endl; } //This is an either/or choice, since we can't link against both. Prefer libftdi. Thanks for the static linking against old libusb binaries, FTDI! #if defined(LIBUSB) else if (m_varMap.count("libusb")) { std::cout << "Setting up libusb device" << std::endl; device.setFalconComm<FalconCommLibUSB>(); } #endif #if defined(LIBFTDI) else if (m_varMap.count("libftdi")) { std::cout << "Setting up libftdi device" << std::endl; device.setFalconComm<FalconCommLibFTDI>(); } #elif defined(LIBFTD2XX) else if (m_varMap.count("ftd2xx")) { std::cout << "Setting up ftd2xx device" << std::endl; device.setFalconComm<FalconCommFTD2XX>(); } #endif else { std::cout << "No communication method selected." << std::endl; return false; } //Device count check if(m_varMap.count("device_count")) { int8_t count; device.getDeviceCount(count); std::cout << "Connected Device Count: " << (int)count << std::endl; return false; } else if(m_varMap.count("device_index")) { if(!device.open(m_varMap["device_index"].as<int>())) { std::cout << "Cannot open falcon device index " << m_varMap["device_index"].as<int>() << " - Lib Error Code: " << device.getErrorCode() << " Device Error Code: " << device.getFalconComm()->getDeviceErrorCode() << std::endl; return false; } } else { std::cout << "No device index specified to open, cannot continue (--help for options)" << std::endl; return false; } //There's only one kind of firmware right now, so automatically set that. device.setFalconFirmware<FalconFirmwareNovintSDK>(); //See if we have firmware bool firmware_loaded; if(m_varMap.count("firmware") || m_varMap.count("test_firmware") || m_varMap.count("nvent_firmware") && (m_varMap.count("force_firmware") || !device.isFirmwareLoaded())) { if(m_varMap.count("nvent_firmware")) { for(int i = 0; i < 10; ++i) { if(!device.getFalconFirmware()->loadFirmware(true, NOVINT_FALCON_NVENT_FIRMWARE_SIZE, const_cast<uint8_t*>(NOVINT_FALCON_NVENT_FIRMWARE))) { std::cout << "Could not load firmware" << std::endl; } else { std::cout <<"Firmware loaded" << std::endl; break; } } } else if(m_varMap.count("test_firmware")) { for(int i = 0; i < 10; ++i) { if(!device.getFalconFirmware()->loadFirmware(true, NOVINT_FALCON_TEST_FIRMWARE_SIZE, const_cast<uint8_t*>(NOVINT_FALCON_TEST_FIRMWARE))) { std::cout << "Could not load firmware" << std::endl; } else { std::cout <<"Firmware loaded" << std::endl; break; } } } else if(m_varMap.count("firmware")) { //Check for existence of firmware file std::string firmware_file = m_varMap["firmware"].as<std::string>(); if(!device.setFirmwareFile(firmware_file)) { std::cout << "Cannot find firmware file - " << firmware_file << std::endl; return false; } if(!device.loadFirmware(10, m_varMap.count("skip_checksum") > 0)) { std::cout << "Cannot load firmware to device" << std::endl; std::cout << "Error Code: " << device.getErrorCode() << std::endl; if(device.getErrorCode() == 2000) { std::cout << "Device Error Code: " << device.getFalconComm()->getDeviceErrorCode() << std::endl; } return false; } } } if(!device.isFirmwareLoaded()) { std::cout << "No firmware loaded to device, cannot continue" << std::endl; return false; } return true; } }
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef TIMEREVENT_H_ #define TIMEREVENT_H_ #include "IEvent.h" #include <string> namespace Event { /** * Event zegarowy. * \ingroup Events */ class TimerEvent : public IEvent { public: TimerEvent () : ticks (0) {} virtual ~TimerEvent () {} unsigned int getTicks () const { return ticks; } void setTicks (unsigned int ticks) { this->ticks = ticks; } Type getType () const { return TIMER_EVENT; } virtual bool runCallback (Model::IModel *m, View::IView *v, Controller::IController *c, void *d) { return c->onTimer (static_cast <TimerEvent *> (this), m, v); } virtual std::string toString () const; private: unsigned int ticks; }; } # endif /* TIMEREVENT_H_ */
#include "parser_main.h" #ifndef __PARSER_TEMPLATE__ #define __PARSER_TEMPLATE__ /** * A class of functions for manipulating templates within * wikimarkup. Extends the base parser class. */ class template_parser : public parser{ private: /** * A string representing the identifying characters * for a template call. Used in combination with * parser::regex_def to construct boost * regular expressions around said characters. */ static const std::string template_delimiters; public: /** * A function for extracting templates from a piece of * wikitext. Called by the (exported) extract_templates * function in mwutils.cpp * * @param text a piece of wikitext * * @return a vector of strings, each one consisting * of one template call from within the input text. */ std::vector < std::string > extract_templates(std::string text); /** * A function for /removing/ template calls from a * piece of wikitext. Can be used for sanitisation * purposes, or just for fun. * * @param text a piece of wikitext * * @return a string consisting of the same * piece of wikitext as the input, but without * any included template calls. */ std::string remove_templates(std::string text); /** * A function for extracting the names from * template calls retrieved with extract_templates. * Called by the exported extract_template_names * function in wmutils.cpp * * @param template_def a template definition. * * @return the name of the template contained * in template_def. */ std::string template_names(std::string template_def); /** * A function for extracting the value of a * particular field within a template call, * as extracted with extract_templates. * Called by extract_template_value, which * is exported and found in wmutils.cpp. * * @param template_def a template definition. * * @param parameter the name of a parameter to * search template_def for. * * @return a string consisting of the value of * parameter within template_def - or an empty * string if the parameter is not found. */ std::string template_field(std::string template_def, std::string parameter); }; #endif
#include "Magellan.h" Magellan magel; char auth[]="2abd44e0-694f-11e8-9f32-77202ac2dc97"; String payload; void setup() { Serial.begin(9600); magel.begin(auth); } void loop() { String Temperature=String(random(0,100)); String Humidity=String(random(0,100)); payload="{\"Temperature\":"+Temperature+",\"Humidity\":"+Humidity+"}"; magel.post(payload); }
#ifndef _GetPlayInfo_H_ #define _GetPlayInfo_H_ #include "BaseProcess.h" class BaseClientHandler; class GetPlayInfo : public BaseProcess { public: GetPlayInfo(); ~GetPlayInfo(); virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt); virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt); }; #endif
#ifndef MAINWINDOW_H #include "bigint.h" #define MAINWINDOW_H #include <QMainWindow> #include <QString> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_actionAbout_triggered(); void on_actionQuit_triggered(); void on_subraction_clicked(); void on_addition_clicked(); void on_memory_store_clicked(); void on_memory_recall_clicked(); void on_left_operand_textChanged(const QString &arg1); void on_right_operand_textChanged(const QString &arg1); void on_multiplication_clicked(); private: Ui::MainWindow *ui; QString _left_operand, _right_operand, _memory_value; //invariants: // _left_operand, _right_operand, _memory_value are the left right operands and memory values as Qstrings //pre:none //post: takes the entered _left_operand, _right_operand, and _memory_value strings and display them in their corresponding screens void display(); }; #endif // MAINWINDOW_H
#ifndef __RESOURCE_LOADER_H__ #define __RESOURCE_LOADER_H__ #include <cocos2d.h> #define SIZE_NUM 1024 using namespace cocos2d; using namespace std; typedef struct resourceStruct { char name[255]; int width; int height; Point start; Point end; }Resource; class ResourceLoader { public: //单例模式 static ResourceLoader* getInstance(); //销毁 static void destroyInstance(); //根据文件名称加载资源 void loadResource(string filename); //根据文件名称和纹理加载资源 void loadResource(string filename,Texture2D *textture); //通过资源的名称获取资源 SpriteFrame* getSpriteFrameByName(string name); protected: ResourceLoader(); //初始化 virtual bool init(); void loadingCallBack(Texture2D *texture); //资源加载器 static ResourceLoader* sharedResourceLoader; //资源容器 Map<std::string, SpriteFrame*> spriteFrames; }; #endif
/** * @file serialretriever.h * * @brief The serial message retriever. This will accept messages over serial. * @version 0.1 * @date 2021-07-22 * * @copyright Copyright (c) 2021 * */ #include "messageretriever.h" #ifndef SERIALRETRIEVER_H #define SERIALRETRIEVER_H /** * @brief The class that represents the Serial retriever. * * @note Derived from class declared in "messageretriever.h" * */ class SerialRetriever : public MessageRetrieverBase { public: SerialRetriever(); ~SerialRetriever(); virtual void setupRetriever() override; virtual void updateRetriever() override; private: }; #endif
#include "Application.h" #include<string> Application::Application(const std::string &title, uint32_t width, uint32_t height, CameraType cameraType) { WindowEventsListener windowEventsListener = [this](WindowEvents event) { onWindowEvent(event); }; ScrollEventsListener scrollEventsListener = [this](ScrollEvents event) { onScrollEvent(event); }; m_window = Window::create(title, width, height, windowEventsListener, scrollEventsListener); m_input = std::make_unique<Input>(m_window->getNativeWindow()); m_cameraController = CameraController::create(cameraType, *m_input, float (width) / (float) height); } bool Application::isRunning() const { return !glfwWindowShouldClose(m_window->getNativeWindow()) && !m_shouldClose; } void Application::clear() const { glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void Application::update() const { m_window->update(); m_cameraController->update(); } void Application::draw( const VertexArray &vertexArray, const IndexBuffer &indexBuffer ) const { vertexArray.bind(); indexBuffer.bind(); glDrawElements(GL_TRIANGLES, indexBuffer.getCount(), GL_UNSIGNED_INT, nullptr); } void Application::shutdown() const { glfwTerminate(); } void Application::onWindowEvent(WindowEvents event) { switch (event) { case WindowEvents::OnResize: { uint32_t width = m_window->getWidth(); uint32_t height = m_window->getHeight(); m_cameraController->resize(width, height); } break; case WindowEvents::OnClose: // TODO: Implement break; } } void Application::onScrollEvent(ScrollEvents event) { switch (event) { case ScrollEvents::OnScrollUp: m_cameraController->zoomBy(-0.1f); break; case ScrollEvents::OnScrollDown: m_cameraController->zoomBy(0.1f); break; } }