blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
d27ba272001476b67eebbc0558ce938d6946c586
e08d426708aae61803378ce61a3806b377139f11
/NuRaft/examples/central_server.cxx
6ee361b4735f2e49e5b2a91e859459cf0c161727
[ "Apache-2.0", "BSD-3-Clause", "Zlib", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ECS-251-W2020/final-project-group-3
8f3af34558e418e967f857daafdc614bc57e8993
522bf666816acca310e90652ddc9d67be863fa02
refs/heads/master
2021-01-03T04:09:13.950241
2020-03-19T05:11:08
2020-03-19T05:11:08
239,912,375
1
1
null
null
null
null
UTF-8
C++
false
false
6,456
cxx
central_server.cxx
/**************************************** * central_server.cxx * * Date: 3/1/2020 * Author: Julian Angeles * * Implementation file of the central * server api. ***************************************/ #include "central_server.hxx" #include "central_server_common.hxx" #include "asio.hpp" namespace cs { typedef bool (*callback_function)(const std::vector<std::string>&); /**************************************** * Central Server Implementation * * Necessary to prevent asio compile issues ***************************************/ class central_server_impl : public std::enable_shared_from_this<central_server_impl> { public: central_server_impl(); void connect(std::string address); void send(request message); void receive(); void handle_connect(const asio::error_code& ec); void handle_read(const asio::error_code ec, std::size_t bytes_transferred); void set_function(callback_function pFunc); std::shared_ptr<central_server_impl> sp() { return shared_from_this(); } ~central_server_impl(); private: char reply_data[max_length]; asio::io_context io_context; asio::ip::tcp::socket socket; asio::ip::tcp::resolver resolver; std::vector<std::string> tokens; callback_function do_cmd; }; /**************************************** * Default constructor * * Simply sets up the socket variable ***************************************/ central_server_impl::central_server_impl() : io_context() , socket(io_context) , resolver(io_context) {} /**************************************** * Establishes a connection with the central * server with a given ip address * * @input address: ip address of CS ***************************************/ void central_server_impl::connect(std::string address) { // Hardcoded port for now. Will want to replace eventually. asio::async_connect(socket, resolver.resolve(address, "5000"), std::bind(&central_server_impl::handle_connect, shared_from_this(), std::placeholders::_1)); std::thread([this](){ io_context.run(); }).detach(); // Have to think about correctly joining later } /**************************************** * Send a message to the central server * * Simply sets up the socket variable ***************************************/ void central_server_impl::send(request message) { asio::streambuf sending; try { std::ostream(&sending) << message; size_t n = socket.send(sending.data()); sending.consume(n); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } } /**************************************** * Receives a message from the central server ***************************************/ void central_server_impl::receive() { socket.async_read_some(asio::buffer(reply_data, max_length), std::bind(&central_server_impl::handle_read, shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } /**************************************** * Handler for asynchronous connection ***************************************/ void central_server_impl::handle_connect(const asio::error_code& ec) { if (!ec) { receive(); } // Maybe add check to close socket? } /**************************************** * Handler for asynchronous reads ***************************************/ void central_server_impl::handle_read(const asio::error_code ec, std::size_t bytes_transferred) { if (!ec) { request reply; asio::streambuf receiving; if (ec == asio::error::eof) socket.close(); else if (ec) throw asio::system_error(ec); std::ostream(&receiving) << reply_data; if (std::istream(&receiving) >> reply) { if (reply.m_type == REPLY) { // std::cout << "Message: " << reply.m_message << std::endl; // std::cout << "Length: " << bytes_transferred << std::endl; } else if (reply.m_type == ADD_SERVER) { // std::cout << "Message: " << reply.m_message << std::endl; // std::cout << "Port: " << reply.m_port << std::endl; // std::cout << "Server ID: " << reply.m_id << std::endl; std::stringstream ss(reply.m_message); std::string intermediate; if (tokens.size() > 0) { tokens.clear(); } // Make sure empty while(getline(ss, intermediate, ' ')) { tokens.push_back(intermediate); } do_cmd(tokens); } } receive(); } else { socket.close(); } } void central_server_impl::set_function(callback_function pFunc) { do_cmd = pFunc; } /**************************************** * Destructor * * Must ensure that the socket is closed * before the instance is destroyed ***************************************/ central_server_impl::~central_server_impl() { if (socket.is_open()) { socket.close(); } } /**************************************** * Default constructor * * Simply sets up the socket variable ***************************************/ central_server::central_server() : impl_(std::make_shared<central_server_impl>()) { impl_->connect("35.188.155.151"); } /**************************************** * Constructor that takes in a function * pointer * * Necessary for the way they wrote * their code ***************************************/ central_server::central_server(callback_function pFunc) : impl_(std::make_shared<central_server_impl>()) { impl_->set_function(pFunc); impl_->connect("35.188.155.151"); } /**************************************** * Tells server to connect it to a leader * of a lobby. If there is no leader yet, * then it should become the leader. ***************************************/ void central_server::join_lobby(int id, int port) { request message = { JOIN, id, port, "I want to join!"}; impl_->send(message); } /**************************************** * Destructor * * Must ensure that the socket is closed * before the instance is destroyed ***************************************/ central_server::~central_server() { //delete impl_; } };
d0d7457a785679f753927958a1849f500c16c3f2
ca5349838f40f0211c3703db0502c6deb985d5d6
/examples/BatchOrders/main.cpp
c5cf578eb2565660ae97146cca1962c1dc0497b3
[ "Apache-2.0" ]
permissive
xiongyang/huobi_Cpp
7f5987c1184b888d54e7660a8f13f243fd849009
3defae8e41aa9cd1bf9eb83a4865cfe96cf85245
refs/heads/master
2020-06-23T08:02:34.550885
2020-05-27T17:12:36
2020-05-27T17:12:36
198,566,287
0
0
Apache-2.0
2019-07-24T05:44:52
2019-07-24T05:44:52
null
UTF-8
C++
false
false
1,295
cpp
main.cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ #include "Huobi/HuobiClient.h" #include<iostream> using namespace Huobi; using namespace std; int main(int argc, char** argv) { RequestClient* client = createRequestClient("xxx", "xxxx"); list<NewOrderRequest> requests; NewOrderRequest newOrderRequest1( "btcusdt", AccountType::spot, OrderType::buy_limit, Decimal(1.0), Decimal(1.0) ); newOrderRequest1.client_order_id = "first"; NewOrderRequest newOrderRequest2( "btcusdt", AccountType::spot, OrderType::buy_limit, Decimal(2.0), Decimal(1.0) ); newOrderRequest2.client_order_id = "second"; requests.push_back(newOrderRequest1); requests.push_back(newOrderRequest2); vector < BatchOrderResult > batchOrderResults = client->batchOrders(requests); for (BatchOrderResult batchOrderResult : batchOrderResults) { cout << "order-id: " << batchOrderResult.orderId << endl; cout << "client-order-id: " << batchOrderResult.clientOrderId << endl; } }
060689e895e753bbee149cd106afaa560e50b03d
917eed37f555ced68106a30e99d20152eb758f65
/src/core/AbstractVirtualDisk.h
e0c5b7442ff1c73af2b2719a5afa54c84958e857
[]
no_license
CantGetRight82/growmill
0164523473444d8ce9a25ce594c5b41c8c751371
ba01be1c2b2c0a290106aeda25731f6602f7ead0
refs/heads/master
2021-01-01T04:22:33.146912
2017-08-13T15:02:27
2017-08-13T15:02:27
97,164,577
0
0
null
null
null
null
UTF-8
C++
false
false
139
h
AbstractVirtualDisk.h
#pragma once class AbstractVirtualDisk { public: AbstractVirtualDisk() { } virtual std::string getContents(std::string path) = 0; };
3f75980d9e2c2d3aea3a4c52d156a02fb5290e8e
52a69bc7e7a9a78d57353947ed2e019fcc736132
/VoiceReco/VoiceRecoDlg.cpp
9419a35c1e69cda4ae403fac8d8fb27e6a6ebe30
[]
no_license
ghcodest/VoiceReco
9bff28d1250a3042167d49601bbbeea4bd4b53fe
160c1f29215895e634d0dfdbaf8f0e6e82b63518
refs/heads/master
2020-04-10T15:49:35.540922
2014-02-27T02:32:38
2014-02-27T02:32:38
null
0
0
null
null
null
null
GB18030
C++
false
false
3,856
cpp
VoiceRecoDlg.cpp
// VoiceRecoDlg.cpp : 实现文件 // #include "stdafx.h" #include "VoiceReco.h" #include "VoiceRecoDlg.h" #include "afxdialogex.h" #define WM_RECOEVENT WM_USER + 100 #ifdef _DEBUG #define new DEBUG_NEW #endif // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CVoiceRecoDlg 对话框 CVoiceRecoDlg::CVoiceRecoDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CVoiceRecoDlg::IDD, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CVoiceRecoDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CVoiceRecoDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_MESSAGE(WM_RECOEVENT, &CVoiceRecoDlg::OnRecoevent) END_MESSAGE_MAP() // CVoiceRecoDlg 消息处理程序 BOOL CVoiceRecoDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 mSREngine.InitializeSAPI(GetSafeHwnd(), WM_RECOEVENT); mSREngine.LoadCmdFromFile(TEXT("CmdCtrl.xml")); return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CVoiceRecoDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CVoiceRecoDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CVoiceRecoDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } afx_msg LRESULT CVoiceRecoDlg::OnRecoevent(WPARAM wParam, LPARAM lParam) { CSpEvent event; event.GetFrom(mSREngine.mSpRecoContext); switch(event.eEventId) { case SPEI_FALSE_RECOGNITION: AfxMessageBox(TEXT("未识别")); break; case SPEI_RECOGNITION: { CComPtr<ISpRecoResult> lISpRecoResult; lISpRecoResult = event.RecoResult(); BSTR bstr; lISpRecoResult->GetText(SP_GETWHOLEPHRASE, SP_GETWHOLEPHRASE, TRUE, &bstr, NULL); AfxMessageBox(bstr); break; } default: break; } return 0; }
87451cd5b931ea53de3ae35a1aaec161922f5532
a546da58a6353d22ec45c14b4865e0c1c75192ac
/CS260-Assignment 4/Term:Complex/TestDriver.cpp
7191fc114f560a2d21d3193191d67fc772bd48b9
[]
no_license
caneroj1/TCNJ_Code
21bb2adc954743393a05ce2576aace71449852e7
e084ee5d9786439349530435596b3908fe0b3707
refs/heads/master
2021-01-20T10:49:49.133648
2014-02-28T18:47:49
2014-02-28T18:47:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,104
cpp
TestDriver.cpp
// // TestDriver.cpp // // // Created by Joseph Canero on 10/10/12. // // // Driver to test implementation of the Polynomial class // Programmed by: Dr. Monisha Pulimood // Course: CSC 260 // Semester: Fall 2012 #include "Polynomial.cpp" using namespace std; int main (void) { Polynomial p1, p2, p3, p4; int x; int number = 5; //Test overloaded stream insertion and extraction operators cout << "Enter Polynomial 1 from keyboard" << endl; cin >> p1; cout << "Polynomial 1 is:" << endl; cout << p1; cout << "Enter Polynomial 2 from a file" << endl; bool worked = true; string inFileName; ifstream inStr; do { cout << "Enter name of file to read from: "; cin >> inFileName; inStr.open (inFileName.c_str()); if (inStr.fail()) { cerr << "Error opening file. Try again." << endl; inStr.clear(); inStr.ignore(80, '\n'); worked = false; } else worked = true; } while (!worked); // Input file format is similar to how data is entered from keyboard // First number specifies the number of terms in the polynomial // Followed by pairs of numbers for each term // - first one is coefficient // - second one is degree inStr >> p2; inStr.close(); cout << "Polynomial 2 is:" << endl; cout << p2; // Test overloaded assignment operator cout << "After assigning p1 to p4, p4 is: " << endl; p4 = p1; cout << p4 << endl; cout << "Enter Polynomial 1" << endl; cin >> p1; cout << "Polynomial 1 is now:" << endl; cout << p1; cout << "Polynomial 4 is now: " << endl; cout << p4 << endl; // Test overloaded plus operator cout << "Adding Polynomial 1 and Polynomial 2 gives:" << endl; p3 = p1 + p2; cout << p3 << endl; cout << "Adding Polynomial 1 and number gives:" << endl; p3 = p1 + number; cout << p3 << endl; cout << "Adding number and Polynomial 2 gives:" << endl; p3 = number + p2; cout << p3 << endl; // Test overloaded multiplication operator cout << "Multiplying Polynomial 1 and Polynomial 2 gives:" << endl; p3 = p1 * p2; cout << p3 << endl; cout << "Multiplying Polynomial 1 and number gives:" << endl; p3 = p1 * number; cout << p3 << endl; cout << "Multiplying number and Polynomial 2 gives:" << endl; p3 = number * p2; cout << p3 << endl; // Test polynomial evaluation cout << "Enter a value for x" << endl; cin >> x; cout << "Evaluating Polynomial 1 with " << x << " gives " << p1.evalPoly (x) << endl; // Test writing to a file cout << "Writing Polynomial 3 to a file." << endl; // Output file format is similar to input file format so it can be read in as well // First number specifies the number of terms in the polynomial // Followed by pairs of numbers for each term // - first one is coefficient // - second one is degree // Since behavior of display to screen is different from writing to a file // we need different functions. p3.writeToFile(); cout << "Bye!" << endl << endl; return 0; }
0aa0d6ccdfc4c9299a4804200e0e5cb65180df4c
406b6f3e8355bcab9add96f3cff044823186fe37
/src/Simulation/trimesh_icp_simulation/render.cpp
d32205fe0d750ee3445dc57cf91a7fbf70d41e6a
[]
no_license
Micalson/puppet
96fd02893f871c6bbe0abff235bf2b09f14fe5d9
d51ed9ec2f2e4bf65dc5081a9d89d271cece28b5
refs/heads/master
2022-03-28T22:43:13.863185
2019-12-26T13:52:00
2019-12-26T13:52:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,723
cpp
render.cpp
#include "render.h" #include <base\bind.h> #include "trimeshgeometrycreator.h" Render::Render() :base::Thread("Render") { m_scene = new SimulationScene(); } Render::~Render() { } void Render::OnFrame(RenderData* data) { task_runner()->PostTask(FROM_HERE, base::Bind(&Render::ShowOneFrame, base::Unretained(this), data)); } void Render::OnFrame(PatchRenderData* data) { task_runner()->PostTask(FROM_HERE, base::Bind(&Render::ShowPatch, base::Unretained(this), data)); } void Render::StartRender() { Start(); } void Render::StopRender() { Stop(); } SimulationScene* Render::GetScene() { return m_scene; } void Render::Convert(osg::Matrixf& matrix, const trimesh::xform& xf) { for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) matrix(i, j) = xf(j, i); } void Render::ShowOneFrame(RenderData* data) { osg::Geometry* geometry = Create(data->mesh.get()); osg::Matrixf matrix = osg::Matrixf::identity(); Convert(matrix, data->mesh->global); m_scene->ShowOneFrame(geometry, matrix); delete data; } void Render::ShowPatch(PatchRenderData* data) { BuildPatch(data); osg::Matrixf matrix = osg::Matrixf::identity(); Convert(matrix, data->xf); m_scene->UpdateMatrix(matrix, data->step == 0); } void Render::BuildPatch(PatchRenderData* data) { m_scene->Lock(); size_t exsit_size = m_geometries.size(); std::vector<int> flags; if (exsit_size > 0) flags.resize(exsit_size, 0); //0: nothing, 1: update, 2: add std::vector<osg::ref_ptr<ChunkGeometry>> new_geometries; const std::vector<int> idxs = data->indices; const std::vector<trimesh::point>& points = data->points; const std::vector<trimesh::vec>& norms = data->normals; size_t input_size = idxs.size(); bool has_color = false; float t = m_scene->GetTime(); for (size_t i = 0; i < input_size; ++i) { int index = idxs.at(i); if (index < 0) continue; const trimesh::point& tp = points.at(i); const trimesh::vec& tn = norms.at(i); osg::Vec3f p = osg::Vec3f(tp[0], tp[1], tp[2]); osg::Vec3f n = osg::Vec3f(tn[0], tn[1], tn[2]); osg::Vec4f c = osg::Vec4f(0.8f, 0.8f, 0.8f, 1.0f); int chunk = index / ChunkVertexSize; int rindex = index % ChunkVertexSize; while (chunk >= (int)m_geometries.size()) { ChunkGeometry* geometry = new ChunkGeometry(); m_geometries.push_back(geometry); new_geometries.push_back(geometry); } ChunkGeometry* geometry = m_geometries.at(chunk); geometry->Update(rindex, p, n, c, t); } for (size_t i = 0; i < m_geometries.size(); ++i) { m_geometries.at(i)->Check(); } for (size_t i = 0; i < new_geometries.size(); ++i) m_scene->AddPatch(new_geometries.at(i)); bool first_frame = exsit_size == 0; if(first_frame) m_scene->UpdateCam(); m_scene->Unlock(); }
979a4c39d7ed1521934e0195ef1eebf4fc8bf64d
a7764174fb0351ea666faa9f3b5dfe304390a011
/inc/DBRep_ListNodeOfListOfFace.hxx
acf1dd16e67b2e301974931792cecc1aa9797cd0
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
2,335
hxx
DBRep_ListNodeOfListOfFace.hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _DBRep_ListNodeOfListOfFace_HeaderFile #define _DBRep_ListNodeOfListOfFace_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineHandle_HeaderFile #include <Standard_DefineHandle.hxx> #endif #ifndef _Handle_DBRep_ListNodeOfListOfFace_HeaderFile #include <Handle_DBRep_ListNodeOfListOfFace.hxx> #endif #ifndef _Handle_DBRep_Face_HeaderFile #include <Handle_DBRep_Face.hxx> #endif #ifndef _TCollection_MapNode_HeaderFile #include <TCollection_MapNode.hxx> #endif #ifndef _TCollection_MapNodePtr_HeaderFile #include <TCollection_MapNodePtr.hxx> #endif class DBRep_Face; class DBRep_ListOfFace; class DBRep_ListIteratorOfListOfFace; class DBRep_ListNodeOfListOfFace : public TCollection_MapNode { public: DBRep_ListNodeOfListOfFace(const Handle(DBRep_Face)& I,const TCollection_MapNodePtr& n); Handle_DBRep_Face& Value() const; DEFINE_STANDARD_RTTI(DBRep_ListNodeOfListOfFace) protected: private: Handle_DBRep_Face myValue; }; #define Item Handle_DBRep_Face #define Item_hxx <DBRep_Face.hxx> #define TCollection_ListNode DBRep_ListNodeOfListOfFace #define TCollection_ListNode_hxx <DBRep_ListNodeOfListOfFace.hxx> #define TCollection_ListIterator DBRep_ListIteratorOfListOfFace #define TCollection_ListIterator_hxx <DBRep_ListIteratorOfListOfFace.hxx> #define Handle_TCollection_ListNode Handle_DBRep_ListNodeOfListOfFace #define TCollection_ListNode_Type_() DBRep_ListNodeOfListOfFace_Type_() #define TCollection_List DBRep_ListOfFace #define TCollection_List_hxx <DBRep_ListOfFace.hxx> #include <TCollection_ListNode.lxx> #undef Item #undef Item_hxx #undef TCollection_ListNode #undef TCollection_ListNode_hxx #undef TCollection_ListIterator #undef TCollection_ListIterator_hxx #undef Handle_TCollection_ListNode #undef TCollection_ListNode_Type_ #undef TCollection_List #undef TCollection_List_hxx // other Inline functions and methods (like "C++: function call" methods) #endif
f5419a8c48e0410fa43366651620b08ff7d969ab
8e943d5e1b9c41e2baf99f855754a78dd76a730f
/UVa12289.cpp
ce47daa35a327420d9ffa958019c293ec7630f05
[]
no_license
shubhamverma1997/UVa-Codes
1e22f4be8c08b77f56c23bc0e1239fde07d9e20f
bd74711b25c20fd7aa8c0ddaa082c60f19ec2597
refs/heads/master
2021-01-01T19:12:38.814078
2017-08-30T15:59:19
2017-08-30T15:59:19
98,536,434
0
0
null
null
null
null
UTF-8
C++
false
false
433
cpp
UVa12289.cpp
//ONe-Two-Three #include<iostream> using namespace std; int main() { int t; char w[7]; scanf("%d",&t); while(t) { w[5]='.'; scanf("%s",w); if(w[5]=='\0') { printf("3\n"); } else { if( (w[0]=='o' && w[1]=='n') || (w[0]=='o' && w[2]=='e') || (w[2]=='e' && w[1]=='n')) printf("1\n"); if( (w[0]=='t' && w[1]=='w') || (w[0]=='t' && w[2]=='o') || (w[2]=='o' && w[1]=='w')) printf("2\n"); } t--; } }
e4c3f197558c35be05a186843bb8109614aec46c
7fc5961cd7285ce035f05f5267c4d9dd08c6e90f
/src/Subsystems/Subsystems.cpp
25729ecdde82a6ebd23b800c115b6023b7aecf13
[]
no_license
team422/FRC-18
7d1d647a2ddbc5b366109fa357c4996f1852642d
a83b921720a6cce733f30670e0454669263014e5
refs/heads/master
2021-09-20T03:34:41.917708
2018-08-02T20:57:31
2018-08-02T20:57:31
117,110,828
0
0
null
null
null
null
UTF-8
C++
false
false
250
cpp
Subsystems.cpp
#include "Subsystems.hpp" /** * Single instances for all of the subsystems */ DriveBase Subsystems::driveBase; Compressor Subsystems::compressor; Intake Subsystems::intake; Guillotine Subsystems::guillotine; ArduinoController Subsystems::arduino;
6d011e24cf78db190aa35e1def13791085065ea4
7870d8a104fe47f7f51383f6e9f183a8cfaa3bf4
/Task.cpp
f203c7d822eb877bacfdb69ce5aeab75efe15a7d
[]
no_license
JiayaoWu/MLH
0f451dc0dcd8ee662532beee16567204f58cad32
5a09260e6b9ff8758143c2c53b56b5f0d3a79c2d
refs/heads/master
2020-06-17T07:32:57.135190
2016-11-28T22:20:47
2016-11-28T22:20:47
75,018,138
0
0
null
null
null
null
UTF-8
C++
false
false
592
cpp
Task.cpp
#include <iostream> using std::cout; #include "Task.h" /*constructor*/ Task::Task(const std::string & nameOfTask, const double laborCost, const double partCost) { name = nameOfTask; costofLabor = laborCost; costofPart = partCost; } /*Returns cost of labor*/ double Task::getLabor() const { return costofLabor; } /*Returns cost of part*/ double Task::getPart() const { return costofPart; } /*Prints name of task, cost of labor and part*/ void Task::print() const { cout << "Task name: " << name << "\nCost of Labor: " << costofLabor << "\nCost of Part: " << costofPart << "\n"; }
a21d8b01bb8e0b29aa29544af5ea420b93f95249
2e46ef9411a8e84074d35338240a69f65b7a6a5d
/experiments/sparseFusion/visHelper.h
1d37a1efb45d7048a4c398189517d4a7791c510f
[ "MIT-feh" ]
permissive
zebrajack/tdp
c0deff77120e20f0daf32add31cbcebe480fb37d
dcab53662be5b88db1538cf831707b07ab96e387
refs/heads/master
2021-07-08T12:10:09.626146
2017-09-11T19:25:42
2017-09-11T19:25:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
466
h
visHelper.h
#include <vector> #include <tdp/data/image.h> #include <tdp/data/circular_buffer.h> #include <tdp/manifold/SE3.h> namespace tdp { void ShowCurrentNormals( const Image<Vector3fda>& pc, const Image<Vector3fda>& n, const std::vector<std::pair<size_t, size_t>>& assoc, const SE3f& T_wc, float scale); void ShowGlobalNormals( const CircularBuffer<tdp::Vector3fda>& pc_w, const CircularBuffer<tdp::Vector3fda>& n_w, float scale, int step); }
d0dd53cbf44b4df7860d27f9ce49e6f7c63cf3d8
29f9bfe5a2becc996b86c4ea6e42966c63f0130b
/PCM_CODE/main.cpp
a9bcbd552c1aeac3bf09d8457792f29b3ca300ed
[]
no_license
FeiyangGu/PCM
d9a4c7e9dc036776e38e98fbfd2f08eb63412865
8f3398120ab534224264f91333000de0b3d549a8
refs/heads/master
2021-05-02T07:37:05.417843
2018-05-05T14:34:14
2018-05-05T14:34:14
40,425,579
2
0
null
null
null
null
UTF-8
C++
false
false
6,063
cpp
main.cpp
#include <iostream> #include <fstream> #include <sstream> #include <cstdlib> #include <ctime> #include "Interface.h" using namespace std; const int INF = 1 << 29; void warning(); int main(int argc, char **argv) /// exe funcion input output (thresod) (cc/order) (kind) (k/r) { srand(0); string function = argv[1]; char *inputfile = argv[2]; char *outputfile = argv[3]; double threshold = 0; if (function == "LOPCC") { if (argc == 4) LOPCC(inputfile, outputfile); else { warning(); return 0; } } else { if (argc < 5) { warning(); return 0; } stringstream ss(argv[4]); ss >> threshold; ss.clear(); if (function == "CMI2NIC") { if (argc == 5) CMI2NIC(inputfile, outputfile, threshold); else if (argc == 6) { /* The default parameter is INF */ int order = INF; ss.str(argv[5]); ss >> order; ss.clear(); CMI2NIC(inputfile, outputfile, threshold, order); } else { warning(); return 0; } } else if (function == "CMI2NIB") { if (argc == 5) CMI2NIB(inputfile, outputfile, threshold); else if (argc == 6) { /* The default parameter is 1 */ int order = 1; ss.str(argv[5]); ss >> order; ss.clear(); CMI2NIB(inputfile, outputfile, threshold, order); } else { warning(); return 0; } } else { if (function == "BCPNNB" || function == "SCWCCB") { double cc = -1; int kind = 0; double r = 2; if (argc == 6) { ss.str(argv[5]); ss >> cc; ss.clear(); } else if (argc == 7) { ss.str(argv[5]); ss >> kind; ss.clear(); ss.str(argv[6]); ss >> r; ss.clear(); } else if (argc == 8) { ss.str(argv[5]); ss >> cc; ss.clear(); ss.str(argv[6]); ss >> kind; ss.clear(); ss.str(argv[7]); ss >> r; ss.clear(); } else if (argc > 8) { warning(); return 0; } if (function == "BCPNNB") BCPNNB(inputfile, outputfile, threshold, cc, kind, r); else if (function == "SCWCCB") SCWCCB(inputfile, outputfile, threshold, cc, kind, r); else { warning(); return 0; } } else { int kind = 0; int k = 5; double r = 2; int len = function.length(); if (argc >= 6) { ss.str(argv[5]); ss >> kind; ss.clear(); } if (argc == 7) { if (function[len - 1] == 'B') { ss.str(argv[6]); ss >> r; ss.clear(); } else if(function[len - 1] == 'C') { ss.str(argv[6]); ss >> k; ss.clear(); } } if (argc > 7 || (kind != 0 && kind != 1)) { warning(); return 0; } if (function == "DiceC") DiceC(inputfile, outputfile, threshold, kind, k); else if (function == "JaccardC") JaccardC(inputfile, outputfile, threshold, kind, k); else if (function == "OverlapC") OverlapC(inputfile, outputfile, threshold, kind, k); else if (function == "CosineC") CosineC(inputfile, outputfile, threshold, kind, k); else if (function == "PearsonC") PearsonC(inputfile, outputfile, threshold, kind, k); else if (function == "SpearmanC") SpearmanC(inputfile, outputfile, threshold, kind, k); else if (function == "DotProductC") DotProductC(inputfile, outputfile, threshold, kind, k); else if (function == "KendallC") KendallC(inputfile, outputfile, threshold, kind, k); else if (function == "HoeffdingDC") HoeffdingDC(inputfile, outputfile, threshold, kind, k); else if (function == "MIB") MIB(inputfile, outputfile, threshold, kind, r); else if (function == "SupportB") SupportB(inputfile, outputfile, threshold, kind, r); else if (function == "JaccardB") JaccardB(inputfile, outputfile, threshold, kind, r); else if (function == "InterestB") InterestB(inputfile, outputfile, threshold, kind, r); else if (function == "Piatetsky_ShapirosB") Piatetsky_ShapirosB(inputfile, outputfile, threshold, kind, r); else if (function == "CosineB") CosineB(inputfile, outputfile, threshold, kind, r); else if (function == "ConfidenceB") ConfidenceB(inputfile, outputfile, threshold, kind, r); else if (function == "YulesQB") YulesQB(inputfile, outputfile, threshold, kind, r); else if (function == "YulesYB") YulesYB(inputfile, outputfile, threshold, kind, r); else if (function == "KappaB") KappaB(inputfile, outputfile, threshold, kind, r); else if (function == "J_MeasureB") J_MeasureB(inputfile, outputfile, threshold, kind, r); else if (function == "OddsRatioB") OddsRatioB(inputfile, outputfile, threshold, kind, r); else if (function == "GiniIndexB") GiniIndexB(inputfile, outputfile, threshold, kind, r); else if (function == "LaplaceB") LaplaceB(inputfile, outputfile, threshold, kind, r); else if (function == "ConvictionB") ConvictionB(inputfile, outputfile, threshold, kind, r); else if (function == "CertaintyFactorB") CertaintyFactorB(inputfile, outputfile, threshold, kind, r); else if (function == "AddedValueB") AddedValueB(inputfile, outputfile, threshold, kind, r); else if (function == "CollectiveStrengthB") CollectiveStrengthB(inputfile, outputfile, threshold, kind, r); else if (function == "KlosgenB") KlosgenB(inputfile, outputfile, threshold, kind, r); else if (function == "Phi_CoefficientB") Phi_CoefficientB(inputfile, outputfile, threshold, kind, r); else if (function == "ProbabilityRatioB") ProbabilityRatioB(inputfile, outputfile, threshold, kind, r); else if (function == "LikelihoodRatioB") LikelihoodRatioB(inputfile, outputfile, threshold, kind, r); else if (function == "TwoWaySupportB") TwoWaySupportB(inputfile, outputfile, threshold, kind, r); else if (function == "SCWSB") SCWSB(inputfile, outputfile, threshold, kind, r); else if (function == "SimplifiedXstatisticB")SimplifiedXstatisticB(inputfile, outputfile, threshold, kind, r); else { warning(); return 0; } } } } return 0; } void warning() { cout << "The parameters you input is not right!!!\n"; return; }
77007ac485f029a307925582cd46e55f71a8a456
bdd9f3cdabe0c768641cf61855a6f24174735410
/src/engine/client/library/clientGame/src/shared/object/StaticObject.h
21afe7b6cbf4594f7c604517fcef2ae05ce861d6
[]
no_license
SWG-Source/client-tools
4452209136b376ab369b979e5c4a3464be28257b
30ec3031184243154c3ba99cedffb2603d005343
refs/heads/master
2023-08-31T07:44:22.692402
2023-08-28T04:34:07
2023-08-28T04:34:07
159,086,319
15
47
null
2022-04-15T16:20:34
2018-11-25T23:57:31
C++
UTF-8
C++
false
false
1,184
h
StaticObject.h
//======================================================================== // // StaticObject.h // // Copyright 2001 Sony Online Entertainment, Inc. // All Rights Reserved. // //======================================================================== #ifndef INCLUDED_StaticObject_H #define INCLUDED_StaticObject_H // ====================================================================== #include "clientGame/ClientObject.h" class SharedStaticObjectTemplate; // ====================================================================== /** * A StaticObject is an object that does not has a physical representation in the world. */ class StaticObject : public ClientObject { public: explicit StaticObject(const SharedStaticObjectTemplate* newTemplate); virtual ~StaticObject(); virtual StaticObject * asStaticObject(); virtual StaticObject const * asStaticObject() const; virtual void endBaselines (); private: // disabled StaticObject(); StaticObject(const StaticObject& rhs); StaticObject& operator=(const StaticObject& rhs); private: }; // ====================================================================== #endif // INCLUDED_StaticObject_H
d829f9e0e3d4104922657362812c81e6a28048d0
98132454bb05bff417826080fc7908701f2c643f
/LunarLander/Renderable.cpp
79645607ee3f2d2989b14dea0de007a0dcdde215
[]
no_license
CGTGPY3G1/LunarLander
a10fb31b3c588e51edeaab6d3b4c7f3d716e3f42
08be89aa17ddb9b911f5ff976d5e3ed2949a1f1f
refs/heads/master
2021-03-22T03:35:59.311636
2018-07-19T18:38:05
2018-07-19T18:38:05
89,891,950
0
0
null
null
null
null
UTF-8
C++
false
false
1,839
cpp
Renderable.cpp
#include "Renderable.h" Renderable::Renderable() { SetPosition(Vector2(0, 0)); SetRotation(0); SetDimensions(2, 2); } Renderable::Renderable(const Vector2 & position, const float & rotation, float width, float height) { SetPosition(position); SetRotation(rotation); SetDimensions(width, height); } Renderable::~Renderable() { } float Renderable::GetRotation() { return rotation; } void Renderable::SetRotation(const float & rotation) { this->rotation = rotation; } Vector2 Renderable::GetPosition() { return center; } void Renderable::SetPosition(const Vector2 & position) { center = position; } float Renderable::GetWidth() { return dimensions.GetX(); } void Renderable::SetWidth(const float & width) { SetDimensions(width, dimensions.GetY()); } float Renderable::GetHeight() { return dimensions.GetY(); } void Renderable::SetHeight(const float & height) { SetDimensions(dimensions.GetX(), height); } void Renderable::SetDimensions(const float & width, const float & height) { dimensions.Set(width, height); // set the new vertex positions float halfWidth = width / 2, halfHeight = height / 2; vertices[0] = Vector2(-halfWidth, -halfHeight); vertices[1] = Vector2(halfWidth, -halfHeight); vertices[2] = Vector2(halfWidth, halfHeight); vertices[3] = Vector2(-halfWidth, halfHeight); } void Renderable::SetDimensions(const Vector2 & dimensions) { Vector2 temp = dimensions; SetDimensions(temp.GetX(), temp.GetY()); } void Renderable::Update(const float & deltaTime) { // should be implemented by any updatable derived classes } bool Renderable::GetEnabled() { return enabled; } void Renderable::SetEnabled(const bool & enabled) { this->enabled = enabled; } std::string Renderable::GetName() { return name; } Renderable * Renderable::SetName(std::string name) { this->name = name; return this; }
a9fd9d78dd2547744361e0c4740f4c8e2d8ac9d3
72ed63c92ff6b2c66eb26f9bb8fe42f9c30b6dcc
/C/111 嗨翻C语言_创建自己的小工具.cpp
ba3d3100fef88732770985291371bf4f14b8b590
[]
no_license
wangjunjie1107/CodeTesting
ceee7adbf73d357cb3b93e751682e05b83b54328
2e614831877f30db109e5b669a1d77bb17208a5a
refs/heads/master
2020-07-15T04:59:36.138974
2019-10-30T00:39:29
2019-10-30T00:39:29
205,484,180
0
0
null
null
null
null
GB18030
C++
false
false
880
cpp
111 嗨翻C语言_创建自己的小工具.cpp
#include<stdio.h> #include<string.h> #include<stdlib.h> printf()和scanf()使用标准输出和标准输入来交互 标准输出默认在显示器上显示数据 标准错误专门用来输出错误消息 标准输入默认从键盘读取数据 可以用fprintf(stderr, ...)把数据打印到标准错误 可以用fopen("文件名", "模式")创建你自己的数据流。一共有三种模式:w(写入)、r(读取)、a(追加) 用getopt()函数读取命令行选项很方便 命令行参数以字符串指针数组的形式传递给main() 可以用重定向把标准输入和标准输出和标准错误连接到其他地方 int main() { FILE * in_file = fopen("input.exe", "r"); //创建一条数据流,从文件中读取数据 FILE * out_file = fopen("output.exe", "w")//创建一条数据流,向文件写数据 fclose(in_file); fclose(out_file); }
42349a3eba42e6df7da6a508f1ded513ef685a56
0e2b4454d15ca3b43728d126ed75e52c4466c194
/src/palavraerrada.cpp
ef3381d2c33302b300f6e389061f95db5c37473a
[]
no_license
westefns-souza/corretor-ortografico
248b393bc20c87355371371cb9daa6c5dd8d2961
5b5af5a64eb21d88ba1ff7331a26b92431add25c
refs/heads/main
2023-01-31T11:56:05.558146
2020-12-14T01:31:31
2020-12-14T01:31:31
318,189,478
0
0
null
null
null
null
UTF-8
C++
false
false
871
cpp
palavraerrada.cpp
#include "palavraerrada.hpp" PalavraErrada::PalavraErrada(std::string palavra, int linha, int coluna) : Palavra(palavra, linha, coluna + 1) {} PalavraErrada::~PalavraErrada() {} bool PalavraErrada::addSugestao(std::string sugestao) { // if(this->sugestoes.size() < 5) { // this->sugestoes.pushBack(sugestao); // return true; // } return false; } std::ostream& operator<< (std::ostream& o, PalavraErrada* const pe) { o << "linha: " << pe->linha << " coluna: " << pe->coluna << " " << pe->palavra << ":" << std::endl; // if (pe->sugestoes.size() > 0) { // int index = 0; // while (index != pe->sugestoes.size()) // { // o << " - " << pe->sugestoes.front() << std::endl; // pe->sugestoes.popFront(); // index++; // } // } return o; }
cd252730b8dbcbad5b6bd005f8bbf8e224011c97
853683e9176e97aa096946c3cdea3195fb171136
/parser.h
9f29d905a6655edd8dbb2430e1b7a079101d9ee8
[ "Artistic-2.0" ]
permissive
proteanthread/z80asm
789f616e0b7363212725a9e3afa447cc58e9e3b5
46865627466a3579bfff013a548a6ed53f3c91c6
refs/heads/master
2021-06-10T19:38:37.895027
2017-02-08T21:52:42
2017-02-08T21:52:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
794
h
parser.h
//----------------------------------------------------------------------------- // z80asm parser // Copyright (c) Paulo Custodio, 2015-2016 // License: http://www.perlfoundation.org/artistic_license_2_0 //----------------------------------------------------------------------------- #ifndef PARSER_H_ #define PARSER_H_ #include "memcheck.h" #include "fwd.h" #include "lemon.h" class Parser : noncopyable { public: Parser(Object* object); virtual ~Parser(); Object* object() { return object_; } SrcLine* line() { return line_; } bool parse(); protected: Object* object_; // weak pointer SrcLine* line_; // weak pointer void* lemon_; bool parse_statement(Scanner* scan); bool parse_include(Scanner* scan); bool parse_opcode_void(Scanner* scan); }; #endif // ndef PARSER_H_
b88a3e9fed47328282b680be083003178b792584
dabc36fd56efc1ca6ab227733077018bf9a547d8
/readstationtbl.cpp
d8e03e63f2da6a3c3221fabfae4c5d7ccdac59a6
[]
no_license
chegJH/OperateWithSN
36d540e9d0dd9a0c8432737529b43fb506dd25eb
6953a505c8dad4965e7fbf5d8e98b95377734788
refs/heads/master
2021-07-14T09:11:25.166120
2017-10-19T01:30:39
2017-10-19T01:30:39
98,860,885
0
0
null
null
null
null
UTF-8
C++
false
false
3,102
cpp
readstationtbl.cpp
/* *This protocol is use to test and design new station name system, *It will read the file from local tbl file, and map station name with it's infomation * <hjj17by@163.com Junjie He> */ #include "readstationtbl.h" #include "qfile.h" #include <qdebug.h> #include <qlist.h> #include <QTextStream> #include <QStringList> #include <QMap> /* Standard table example * # First line: station # S # STATION_NAME COLOR ID NextStation 255,255,255 FinalStation 255,255,255 --- 51,102,255 --- 0,0,0 1 SHG 51,102,255 2 KMH 51,102,255 3 CJR 51,102,255 4 ZJR 51,102,255 6 LSA 51,102,255 */ ReadStationTBL::ReadStationTBL() { qDebug()<<"Running without inputs"; readTblFile(); printKeyValue("1"); printKeyValue("2"); printKeyValue("654"); } void ReadStationTBL::readTblFile() { //!Read station table from file //!Create a map from those data QFile *m_StationFile= new QFile("/home/chegg/Desktop/OperateWithSN/stationKey.tbl"); if (!m_StationFile->open(QIODevice::ReadOnly)) { qDebug()<<"stationwidget.tbl is not loaded"; } QTextStream in(m_StationFile); while (!in.atEnd()) { QString line = in.readLine(); if (line.length() > 0 && line.at(0) != '#') { // qDebug()<<"read line: "<<line; QStringList fields = line.split(QRegExp("\\s"),QString::SkipEmptyParts); // qDebug()<<"split into:"<<fields; // qDebug()<<"field[0]:"<<fields.at(0);//<<"field[1]"<<fields.at(1); m_stationListID.append(fields.at(0)); m_stationListName.append(fields.at(1)); if (fields.length()>2) m_stationListColor.append(fields.at(2)); else m_stationListColor.append(0); } } for (int index = 0; index < m_stationListID.count(); index ++) { m_StationMap[m_stationListID.at(index)] = m_stationListName.at(index); // qDebug()<<"map:"<<m_stationListID.at(index)<<" with "<<m_stationListName.at(index); m_StationMap.insertMulti(m_stationListID.at(index),m_stationListColor.at(index)); } } bool ReadStationTBL::checkInclude(QString str) { if (m_stationListID.contains(str)) return true; else return false; } QList<QString> ReadStationTBL::checkKeyValue(QString str) { //!This function will return value(s) pair to the key //!From most recent to least reacent order QList<QString> result; if (checkInclude(str)) result.append(m_StationMap.values(str)); else { qDebug()<<"checkKeyValue fail"; result<<"0,0,0"<<"---"; } return result; } void ReadStationTBL::printKeyValue(QString str) { QList<QString> tmpVal; tmpVal.append(checkKeyValue(str)); if(tmpVal.size()>0) { qDebug()<<"Key->"<<str<<"Value(s)"; for (int i=0; i< tmpVal.size(); ++i) { qDebug()<<i<<"="<<tmpVal.at(i); } } else qDebug()<<"not a proprate approach"; }
c7dedb262dbc0914e40f9ae5e73da182c16050af
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/sandbox/win/src/target_process.h
b203e07fc47a42d75c33f1c52ccb4f8cb1ac5d7e
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
4,807
h
target_process.h
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SANDBOX_WIN_SRC_TARGET_PROCESS_H_ #define SANDBOX_WIN_SRC_TARGET_PROCESS_H_ #include <stddef.h> #include <stdint.h> #include <memory> #include "base/containers/span.h" #include "base/gtest_prod_util.h" #include "base/memory/free_deleter.h" #include "base/memory/raw_ptr.h" #include "base/strings/string_util.h" #include "base/win/access_token.h" #include "base/win/scoped_handle.h" #include "base/win/scoped_process_information.h" #include "base/win/sid.h" #include "base/win/windows_types.h" #include "sandbox/win/src/sandbox_types.h" namespace sandbox { class Dispatcher; class SharedMemIPCServer; class ThreadPool; class StartupInformationHelper; // TargetProcess models a target instance (child process). Objects of this // class are owned by the Policy used to create them. class TargetProcess { public: TargetProcess() = delete; // The constructor takes ownership of `initial_token` and `lockdown_token`. TargetProcess(base::win::AccessToken initial_token, base::win::AccessToken lockdown_token, ThreadPool* thread_pool); TargetProcess(const TargetProcess&) = delete; TargetProcess& operator=(const TargetProcess&) = delete; ~TargetProcess(); // Creates the new target process. The process is created suspended. ResultCode Create(const wchar_t* exe_path, const wchar_t* command_line, std::unique_ptr<StartupInformationHelper> startup_info, base::win::ScopedProcessInformation* target_info, DWORD* win_error); // Destroys the target process. void Terminate(); // Creates the IPC objects such as the BrokerDispatcher and the // IPC server. The IPC server uses the services of the thread_pool. ResultCode Init(Dispatcher* ipc_dispatcher, absl::optional<base::span<const uint8_t>> policy, absl::optional<base::span<const uint8_t>> delegate_data, uint32_t shared_IPC_size, DWORD* win_error); // Returns the handle to the target process. HANDLE Process() const { return sandbox_process_info_.process_handle(); } // Returns the address of the target main exe. This is used by the // interceptions framework. HMODULE MainModule() const { return reinterpret_cast<HMODULE>(base_address_); } // Returns the name of the executable. const wchar_t* Name() const { return exe_name_.get(); } // Returns the process id. DWORD ProcessId() const { return sandbox_process_info_.process_id(); } // Returns the handle to the main thread. HANDLE MainThread() const { return sandbox_process_info_.thread_handle(); } // Transfers variable at |address| of |size| bytes from broker to target. ResultCode TransferVariable(const char* name, const void* address, size_t size); // Creates a mock TargetProcess used for testing interceptions. static std::unique_ptr<TargetProcess> MakeTargetProcessForTesting( HANDLE process, HMODULE base_address); private: FRIEND_TEST_ALL_PREFIXES(TargetProcessTest, FilterEnvironment); // Verify the target process looks the same as the broker process. ResultCode VerifySentinels(); // Filters an environment to only include those that have an entry in // `to_keep`. static std::wstring FilterEnvironment( const wchar_t* env, const base::span<const base::WStringPiece> to_keep); // Details of the target process. base::win::ScopedProcessInformation sandbox_process_info_; // The token associated with the process. It provides the core of the // sbox security. base::win::AccessToken lockdown_token_; // The token given to the initial thread so that the target process can // start. It has more powers than the lockdown_token. base::win::AccessToken initial_token_; // Kernel handle to the shared memory used by the IPC server. base::win::ScopedHandle shared_section_; // Reference to the IPC subsystem. std::unique_ptr<SharedMemIPCServer> ipc_server_; // Provides the threads used by the IPC. This class does not own this pointer. raw_ptr<ThreadPool> thread_pool_; // Base address of the main executable // // `base_address_` is not a raw_ptr<void>, because pointer to address in // another process could be confused as a pointer to PartitionMalloc memory, // causing ref-counting mismatch. See also https://crbug.com/1173374. RAW_PTR_EXCLUSION void* base_address_; // Full name of the target executable. std::unique_ptr<wchar_t, base::FreeDeleter> exe_name_; }; } // namespace sandbox #endif // SANDBOX_WIN_SRC_TARGET_PROCESS_H_
a5f437ddc73f081450fb33fd2111094b150df97e
dd6147bf9433298a64bbceb7fdccaa4cc477fba6
/5383/yaroshenko/2/Lab2Tests/src/polygon.cpp
809032407f4e663e4ef2ce8e9dfcdbc433c9f2f5
[]
no_license
moevm/oop
64a89677879341a3e8e91ba6d719ab598dcabb49
faffa7e14003b13c658ccf8853d6189b51ee30e6
refs/heads/master
2023-03-16T15:48:35.226647
2020-06-08T16:16:31
2020-06-08T16:16:31
85,785,460
42
304
null
2023-03-06T23:46:08
2017-03-22T04:37:01
C++
UTF-8
C++
false
false
1,438
cpp
polygon.cpp
#include "polygon.h" Point2d Polygon::getCenter() const { Point2d center = std::accumulate(vertices.begin(), vertices.end(), Point2d()); center.scale(1 / (double) vertices.size()); return center; } void Polygon::translate2d(const Point2d &dp) { for (auto& p : vertices) p.translate2d(dp); } void Polygon::rotate(double angle) { Point2d center = getCenter(); // переносим в начало координат translate2d(-center); // поворачиваем for (auto& p : vertices) p.rotate(angle); // возвращаем назад translate2d(center); } void Polygon::scale(double scale) { Point2d center = getCenter(); // переносим в начало координат translate2d(-center); // масштабируем for (auto& p : vertices) p.scale(scale); // возвращаем translate2d(center); } void Polygon::print(std::ostream& os) const { os << "Id: " << m_id << std::endl; os << "Color: { r=" << (int) m_color.r << ", g=" << (int) m_color.g << ", b=" << (int) m_color.b << " }" << std::endl; os << "Area: " << area() << std::endl; os << "Perimeter: " << perimeter() << std::endl; os << "Vertices: " << std::endl; for (auto it = vertices.begin(); it != vertices.end(); it++) { os << "\t{ x = " << it->x << "; y = " << it->y << " }" << std::endl; } }
7ad06896d890dcda84f6deb5516f07b76898dfd9
2841194432604e2492baef7d6fbfe14c3169d4a2
/code/sources/MonteCarloExploringStartsPlayer.cpp
ee400eb7196e94c23b86a7e8fab23a4744165133
[]
no_license
some-coder/reinforcement-learning-2
b6b82417c4ece6a8d06e9310440417a621348b3e
4a24c6b68bd4bbe1801f87b8828d4ff4f438f63b
refs/heads/master
2022-04-01T00:09:53.043111
2020-01-30T17:08:03
2020-01-30T17:08:03
227,335,412
0
0
null
null
null
null
UTF-8
C++
false
false
7,689
cpp
MonteCarloExploringStartsPlayer.cpp
#include <RandomServices.hpp> #include "MonteCarloExploringStartsPlayer.hpp" #include "LearningPlayer.hpp" /** * Trivially initialises the Monte Carlo exploring starts player. */ void MonteCarloExploringStartsPlayer::performInitialisation() {} /** * Obtains a random non-trivial state of the player's maze's states. * * Recall our definition of non-triviality: A state is non-trivial if it is * neither a terminal state, nor an intraversible one. * * @return An arbitrary non-trivial state. */ State *MonteCarloExploringStartsPlayer::randomState() { State *s; do { s = this->maze->getState(RandomServices::discreteUniformSample((int)this->stateValues.size() - 1)); } while (Maze::stateIsTerminal(s) || Maze::stateIsIntraversible(s)); return s; } /** * Obtains an arbitrary action. * * @return The random action. */ Maze::Actions MonteCarloExploringStartsPlayer::randomAction() { return Maze::actionFromIndex(RandomServices::discreteUniformSample(Maze::ACTION_NUMBER - 1)); } /** * Builds and returns a random state-action pair. * * Note that only non-trivial states are used in exploring starts. This is * because we want our agent to learn as much as possible, and not simply * 'waste' some of its iterations simply succeeding or failing instantly. * * @return The arbitrary state-action tuple. */ std::tuple<State*, Maze::Actions> MonteCarloExploringStartsPlayer::randomStateActionPair() { State *s; Maze::Actions a; do { s = this->randomState(); } while (Maze::stateIsTerminal(s) || Maze::stateIsIntraversible(s)); a = MonteCarloExploringStartsPlayer::randomAction(); return std::make_tuple(s, a); } /** * Obtains the initial state-action pair to start an episode with. * * Although admittedly trivially implemented, this method is made purely to * adhere to a standard dictated in the parent class; such are the consequences * of building a project within an OOP language. * * @return The starting state-action pair. */ std::tuple<State*, Maze::Actions> MonteCarloExploringStartsPlayer::initialStateActionPair() { return this->randomStateActionPair(); } /** * Obtains the next state-action pair after executing the current pair. * * @param currentPair The current state-action pair to advance from. * @return The succeeding tuple of state and action. */ std::tuple<State*, Maze::Actions> MonteCarloExploringStartsPlayer::nextStateActionPair( std::tuple<State*, Maze::Actions> currentPair) { std::tuple<State*, double> result; result = this->maze->getStateTransitionResult(std::get<0>(currentPair), std::get<1>(currentPair)); this->rewards.push_back(std::get<1>(result)); return std::make_tuple(std::get<0>(result), this->chooseAction(std::get<0>(result))); } /** * Generates a complete episode of successive state-action pairs. * * @param startStateActionPair The initial state-action pair to depart from. */ void MonteCarloExploringStartsPlayer::generateEpisode(std::tuple<State *, Maze::Actions> startStateActionPair) { int episodeIteration, episodeTimeout; std::tuple<State*, Maze::Actions> currentStateActionPair; episodeIteration = -1; episodeTimeout = std::ceil(EPISODE_TIMEOUT_FRACTION * (double)this->stateValues.size()); currentStateActionPair = startStateActionPair; this->episode.push_back(currentStateActionPair); this->rewards.push_back(0.0); /* At the onset, no rewards are obtained yet. */ do { episodeIteration++; currentStateActionPair = this->nextStateActionPair(currentStateActionPair); this->episode.push_back(currentStateActionPair); } while (episodeIteration < episodeTimeout && !Maze::stateIsTerminal(std::get<0>(currentStateActionPair))); this->maze->resetMaze(); } /** * Computes a single component of the episode's returns. * * @param k The exponent to raise the gamma to. * @param rewardIndex The index of the current reward component. * @return The value of the component of the episode's returns. */ double MonteCarloExploringStartsPlayer::episodeReturnComponent(int k, int rewardIndex) { return std::pow(this->discountFactor, k) * this->rewards[rewardIndex]; } /** * Computes the current episode's total returns. * * @param onsetIndex The index from which to start. * @return The episode's total returns. */ double MonteCarloExploringStartsPlayer::episodeReturn(int onsetIndex) { int i; double episodeReturn; episodeReturn = 0.0; for (i = onsetIndex; i < (int)this->rewards.size(); i++) { episodeReturn += this->episodeReturnComponent(i - onsetIndex, i); } return episodeReturn; } /** * Computes the average of the current episode's returns. * * @param stateActionPair THe state-action pair of which to get the mean return. * @return The state-action pair's average returns over episodes. */ double MonteCarloExploringStartsPlayer::returnsAverage(std::tuple<State*, Maze::Actions> stateActionPair) { int returnsIndex; double average; std::vector<double> stateActionReturns; average = 0.0; stateActionReturns = this->returns[stateActionPair]; for (returnsIndex = 0; returnsIndex < (int)stateActionReturns.size(); returnsIndex++) { average += stateActionReturns[returnsIndex]; } if (stateActionReturns.empty()) { return 0.0; } else { return (average / (double)stateActionReturns.size()); } } /** * Constructs a Monte Carlo exploring starts player. * * @param m The maze to be solved by the player. * @param gamma The discount factor to apply to earlier-obtained rewards. * @param T The minimal utility difference to decide to keep iterating. */ MonteCarloExploringStartsPlayer::MonteCarloExploringStartsPlayer(Maze *m, double gamma, int T) : MonteCarloPlayer(m, gamma, T) {} /** * Destructs the Monte Carlo exploring starts player. */ MonteCarloExploringStartsPlayer::~MonteCarloExploringStartsPlayer() = default; /** * Performs an iteration of the Monte Carlo exploring starts algorithm. */ void MonteCarloExploringStartsPlayer::performIteration() { int episodeIteration; std::tuple<State*, Maze::Actions> stateActionPair; double episodeReturn; Maze::Actions greedyAction; this->generateEpisode(this->initialStateActionPair()); for (episodeIteration = 0; episodeIteration < (int)this->episode.size(); episodeIteration++) { stateActionPair = this->episode[episodeIteration]; episodeReturn = this->episodeReturn(episodeIteration + 1); this->returns[stateActionPair].push_back(episodeReturn); this->stateActionValues[stateActionPair] = this->returnsAverage(stateActionPair); } for (episodeIteration = 0; episodeIteration < (int)this->episode.size(); episodeIteration++) { stateActionPair = this->episode[episodeIteration]; greedyAction = this->greedyAction(std::get<0>(stateActionPair)); this->policy[std::get<0>(stateActionPair)] = Player::actionAsActionProbabilityDistribution(greedyAction); } this->addRewardsToTotalRewardPerEpisode(); this->currentEpoch++; this->episode.clear(); this->rewards.clear(); } /** * Solves the maze the player was assigned to address. */ void MonteCarloExploringStartsPlayer::solveMaze() { this->performInitialisation(); do { auto startTime = std::chrono::high_resolution_clock::now(); this->performIteration(); auto endTime = std::chrono::high_resolution_clock::now(); this->epochTimings.push_back(std::chrono::duration_cast<std::chrono::nanoseconds>(endTime - startTime).count() / 1e3); } while (!this->maximumIterationReached()); }
d00851ad6bce9d08b7106553e52a74fcad07e987
48020c1064f2f2b377eb74d0915d57bff207b609
/Practicas DA - CR y Jull/Grafos/ProblemasCR/Problema13/main.cpp
c4a8f7e1b302c9432a01b0467606ac433fcea89a
[]
no_license
ronalkinho/DAAAA
5c0fe775736071231e30ba3e1076427ee3e6f9f2
00e0af37ab1d80dc99bf1c736dbe37064e2e278e
refs/heads/master
2021-07-17T14:12:50.568002
2017-10-24T09:44:22
2017-10-24T09:44:22
108,103,609
0
0
null
null
null
null
UTF-8
C++
false
false
1,383
cpp
main.cpp
#include <iostream> #include <fstream> #include <algorithm> #include <set> #include <map> #include <string> #include <queue> #include "PriorityQueue.h" #include "IndexPQ.h" using namespace std; const int INF = 1e9; void serpientesEscaleras(int N, int caras, int serp, int esca) { int v1, v2, v = 1, w; vector<bool> marked((N*N) + 1, false); vector<int> distTo((N*N) + 1, INF); queue<int> q; map<int, int> atajos; for (int i = 0; i < serp + esca; ++i) { cin >> v1 >> v2; atajos.insert(std::pair<int, int>(v1, v2)); } marked[v] = true; distTo[v] = 0; q.push(v); while (v != N*N) { v = q.front(); q.pop(); for (int i = 1; i <= caras; ++i) { w = v + i; if (w <= N*N) { if (atajos.find(w) != atajos.end())//En el caso de que este w tenga atajo desde v podría llegar hasta el atajo, w = atajos[w]; //no hasta w solo, por eso sustituyo if (!marked[w]) { distTo[w] = distTo[v] + 1; marked[w] = true; q.push(w); } } } } cout << distTo[N*N] << endl; } int main() { #ifndef DOMJUDGE std::ifstream in("casos.txt"); auto cinbuf = std::cin.rdbuf(in.rdbuf()); #endif int N, caras, serp, esca; cin >> N >> caras >> serp >> esca; while (N != 0) { serpientesEscaleras(N, caras, serp, esca); cin >> N >> caras >> serp >> esca; } #ifndef DOMJUDGE std::cin.rdbuf(cinbuf); system("PAUSE"); #endif return 0; }
5e8ad38144f21a8c93d41b5d40329cd8f796ca36
b0dbcd4b7900f70ffab21bdf33b9456d33c9645d
/PrimerExercises/CH1/Exercise 1.10/main.cpp
8b55f1f28f0d9aa1b08676917faeea82798f775c
[]
no_license
MovlaAliyev/cplusplus
260f8cc6e03364d00322a12c1840abcdadaa7cc1
043a999ff8dae0fc26e2cb10ffe1c0ea399cd729
refs/heads/master
2021-01-19T00:21:49.361664
2017-05-17T10:36:11
2017-05-17T10:36:11
87,160,983
0
0
null
null
null
null
UTF-8
C++
false
false
363
cpp
main.cpp
/* In addition to the ++ operator that adds 1 to its operand, there is a decrement operator (--) that subtracts 1. Use the decrement operator to write a while that prints the numbers from ten down to zero. */ #include <iostream> using namespace std; int main() { int i = 10; while(i != 0) cout << --i << endl; return 0; }
f17813a063ed2c3a49265f5b1dad2aa465251e19
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/mutt/gumtree/mutt_patch_hunk_165.cpp
f69ce9855144c1da92eaa570f5af40c6d120fef2
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,707
cpp
mutt_patch_hunk_165.cpp
Sort = SORT_ORDER; qsort (ctx->hdrs, ctx->msgcount, sizeof (HEADER*), mutt_get_sort_func (SORT_ORDER)); } - rc += sync_helper (idata, M_ACL_DELETE, M_DELETED, "\\Deleted"); - rc += sync_helper (idata, M_ACL_WRITE, M_FLAG, "\\Flagged"); - rc += sync_helper (idata, M_ACL_WRITE, M_OLD, "Old"); - rc += sync_helper (idata, M_ACL_SEEN, M_READ, "\\Seen"); - rc += sync_helper (idata, M_ACL_WRITE, M_REPLIED, "\\Answered"); + rc = sync_helper (idata, M_ACL_DELETE, M_DELETED, "\\Deleted"); + if (rc >= 0) + rc |= sync_helper (idata, M_ACL_WRITE, M_FLAG, "\\Flagged"); + if (rc >= 0) + rc |= sync_helper (idata, M_ACL_WRITE, M_OLD, "Old"); + if (rc >= 0) + rc |= sync_helper (idata, M_ACL_SEEN, M_READ, "\\Seen"); + if (rc >= 0) + rc |= sync_helper (idata, M_ACL_WRITE, M_REPLIED, "\\Answered"); if (oldsort != Sort) { Sort = oldsort; FREE (&ctx->hdrs); ctx->hdrs = hdrs; } - if (rc && (imap_exec (idata, NULL, 0) != IMAP_CMD_OK)) + /* Flush the queued flags if any were changed in sync_helper. */ + if (rc > 0) + if (imap_exec (idata, NULL, 0) != IMAP_CMD_OK) + rc = -1; + + if (rc < 0) { if (ctx->closing) { if (mutt_yesorno (_("Error saving flags. Close anyway?"), 0) == M_YES) { rc = 0; idata->state = IMAP_AUTHENTICATED; goto out; } } else mutt_error _("Error saving flags"); + rc = -1; goto out; } /* Update local record of server state to reflect the synchronization just * completed. imap_read_headers always overwrites hcache-origin flags, so * there is no need to mutate the hcache after flag-only changes. */
c859532e4c0f0570f482ce2d9b4aae5a36afb577
06486fbe4c8dc0b82e4a20f6676540a61149167a
/protocol/dmutableobject.cpp
6ddf54bbbe6ea052e4c4d66ec4f76616106c3e35
[]
no_license
vertrex/destruct
1c674d363afdd5b1a09e4207eeec6957b0012645
11c8a74a1d07ca3c948fc15e5a0a8078a7227a6d
refs/heads/master
2021-01-22T05:57:55.693653
2017-02-19T00:02:13
2017-02-19T00:02:13
81,722,460
1
0
null
null
null
null
UTF-8
C++
false
false
2,145
cpp
dmutableobject.cpp
#include "dstruct.hpp" #include "dnullobject.hpp" #include "dexception.hpp" #include "drealvalue.hpp" #include "protocol/dmutablestruct.hpp" #include "protocol/dmutableobject.hpp" namespace Destruct { DMutableObject::DMutableObject(const DUnicodeString& name, DValue const& args) : DDynamicObject(static_cast<DStruct* >(new DMutableStruct(NULL, name, DMutableObject::newObject)), args) { this->init(this); } DMutableObject::DMutableObject(DMutableStruct* dstructDef, DValue const& args) : DDynamicObject(dstructDef, args) { this->init(this); } DMutableObject::DMutableObject(DMutableObject const & rhs) : DDynamicObject(rhs) { this->copy(this, rhs); } DMutableObject::~DMutableObject(void) { delete this->instanceOf(); } DObject* DMutableObject::newObject(DMutableStruct* myClass, DValue const& args) { return (new DMutableObject(myClass, args)); } DObject* DMutableObject::clone() const { return (new DMutableObject(*this)); } DValue DMutableObject::getValue(size_t idx) const { if (idx > this->__values.size()) throw Destruct::DException("DMutableObject::Value(idx) doesn't exist."); return (this->__values[idx]->getFinal()); //XXX values must be set to 0 by default //return Destruct::RealValue<Destruct::DObject*>(Destruct::DNone); } void DMutableObject::setValue(size_t idx, DValue const & v) { if (idx >= this->__values.size()) { DStruct* dstruct = this->instanceOf(); for (size_t i = this->__values.size() ; i < dstruct->attributeCount(); i++) this->__values.push_back(dstruct->attribute(i).type().newValue()); } this->__values[idx]->set(v); } DValue DMutableObject::call(size_t idx, DValue const& v) { if (idx > this->__values.size()) throw Destruct::DException("Value doesn't exist."); return (this->__values[idx]->getFinal().get<DFunctionObject *>()->call(v)); } void DMutableObject::setValueAttribute(DType::Type_t type, std::string const& name, DValue const& v) { DAttribute attribute(type, name); this->instanceOf()->addAttribute(attribute); this->__values.push_back(attribute.type().newValue()); // XXX clone this->__values.back()->set(v); } }
5504d748fd83279578402cbec4befd5e34b8dfc8
3bcd411980915a7b4dc1c83450e3ebb7de57c13c
/source/backend/cpu/x86_x64/avx/CommonOptFunction.cpp
6e31240b7d1219b412176007083bdd2a7e43bf85
[ "Apache-2.0" ]
permissive
Escortbackend/MNN
932029e40ad4d06bc2febd7be8b1b063fec30ecf
2635814f8b58eefbb101cff854a918afddb0d08c
refs/heads/master
2023-06-30T10:55:14.709798
2021-07-29T03:50:25
2021-07-29T03:50:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
32,940
cpp
CommonOptFunction.cpp
// // CommonOptFunction.cpp // MNN // // Created by MNN on 2019/08/25. // Copyright © 2018, Alibaba Group Holding Limited // #include <float.h> #include <string.h> #include <algorithm> #include <limits> #include <vector> #include "FunctionSummary.hpp" #include "core/Macro.h" #include "backend/cpu/CPUPool.hpp" #include "backend/cpu/BinaryUtils.hpp" #include "Vec8.hpp" void _AVX_MNNCopyC4WithStride(const float* source, float* dest, size_t srcStride, size_t dstStride, size_t count) { for (int i = 0; i < count; ++i) { auto s = source + i * srcStride; auto d = dest + i * dstStride; _mm256_storeu_ps(d, _mm256_loadu_ps(s)); } } void _AVX_MNNAddC4WithStride(const float* source, float* dest, size_t srcStride, size_t dstStride, size_t count) { for (int i = 0; i < count; ++i) { auto s = source + i * srcStride; auto d = dest + i * dstStride; _mm256_storeu_ps(d, _mm256_add_ps(_mm256_loadu_ps(s), _mm256_loadu_ps(d))); } } #define PACK_UNIT 8 void _AVX_MNNPackCUnit(float* dst, const float* src, size_t area, size_t depth) { auto areaC4 = area / PACK_UNIT; auto depthC4 = depth / PACK_UNIT; __m256 t0, t1, t2, t3, t4, t5, t6, t7; for (int z = 0; z < depthC4; ++z) { auto dstPlane = dst + z * area * PACK_UNIT; auto srcPlane = src + z * area * PACK_UNIT; for (int x = 0; x < areaC4; ++x) { auto s = srcPlane + PACK_UNIT * x; auto d = dstPlane + PACK_UNIT * PACK_UNIT * x; auto r0 = _mm256_loadu_ps(s + 0 * area); auto r1 = _mm256_loadu_ps(s + 1 * area); auto r2 = _mm256_loadu_ps(s + 2 * area); auto r3 = _mm256_loadu_ps(s + 3 * area); auto r4 = _mm256_loadu_ps(s + 4 * area); auto r5 = _mm256_loadu_ps(s + 5 * area); auto r6 = _mm256_loadu_ps(s + 6 * area); auto r7 = _mm256_loadu_ps(s + 7 * area); TRANSPOSE_8x8; _mm256_storeu_ps(d + PACK_UNIT * 0, t0); _mm256_storeu_ps(d + PACK_UNIT * 1, t1); _mm256_storeu_ps(d + PACK_UNIT * 2, t2); _mm256_storeu_ps(d + PACK_UNIT * 3, t3); _mm256_storeu_ps(d + PACK_UNIT * 4, t4); _mm256_storeu_ps(d + PACK_UNIT * 5, t5); _mm256_storeu_ps(d + PACK_UNIT * 6, t6); _mm256_storeu_ps(d + PACK_UNIT * 7, t7); } } auto areaRemain = areaC4 * PACK_UNIT; auto depthRemain = depthC4 * PACK_UNIT; // Down int remain = depth - depthRemain; if (remain > 0) { float* dstPlane = depthC4 * area * PACK_UNIT + dst; const float* srcPlane = src + depthC4 * area * PACK_UNIT; { for (int x = 0; x < areaC4; ++x) { auto s = srcPlane + PACK_UNIT * x; auto d = dstPlane + PACK_UNIT * PACK_UNIT * x; auto r0 = _mm256_loadu_ps(s + 0 * area); auto r1 = _mm256_setzero_ps(); auto r2 = _mm256_setzero_ps(); auto r3 = _mm256_setzero_ps(); auto r4 = _mm256_setzero_ps(); auto r5 = _mm256_setzero_ps(); auto r6 = _mm256_setzero_ps(); auto r7 = _mm256_setzero_ps(); switch (remain) { case 7: r6 = _mm256_loadu_ps(s + 6 * area); case 6: r5 = _mm256_loadu_ps(s + 5 * area); case 5: r4 = _mm256_loadu_ps(s + 4 * area); case 4: r3 = _mm256_loadu_ps(s + 3 * area); case 3: r2 = _mm256_loadu_ps(s + 2 * area); case 2: r1 = _mm256_loadu_ps(s + 1 * area); default: break; } TRANSPOSE_8x8; _mm256_storeu_ps(d + PACK_UNIT * 7, t7); _mm256_storeu_ps(d + PACK_UNIT * 6, t6); _mm256_storeu_ps(d + PACK_UNIT * 5, t5); _mm256_storeu_ps(d + PACK_UNIT * 4, t4); _mm256_storeu_ps(d + PACK_UNIT * 3, t3); _mm256_storeu_ps(d + PACK_UNIT * 2, t2); _mm256_storeu_ps(d + PACK_UNIT * 1, t1); _mm256_storeu_ps(d + PACK_UNIT * 0, t0); } } for (int x = areaRemain; x < area; ++x) { for (int y = 0; y < remain; y++) { dstPlane[PACK_UNIT * x + y] = srcPlane[y * area + x]; } for (int y = remain; y < PACK_UNIT; y++) { dstPlane[PACK_UNIT * x + y] = 0; } } } // Right for (int z = 0; z < depthC4; ++z) { float* dstPlane = z * area * PACK_UNIT + dst; const float* srcPlane = src + z * area * PACK_UNIT; for (int x = areaRemain; x < area; ++x) { float s0 = srcPlane[x]; float s1 = srcPlane[x + area]; float s2 = srcPlane[x + area * 2]; float s3 = srcPlane[x + area * 3]; float s4 = srcPlane[x + area * 4]; float s5 = srcPlane[x + area * 5]; float s6 = srcPlane[x + area * 6]; float s7 = srcPlane[x + area * 7]; _mm256_storeu_ps(dstPlane + PACK_UNIT * x, _mm256_set_ps(s7, s6, s5, s4, s3, s2, s1, s0)); } } } void _AVX_MNNUnpackCUnit(float* dst, const float* src, size_t area, size_t depth) { auto areaC4 = area / PACK_UNIT; auto depthC4 = depth / PACK_UNIT; __m256 t0, t1, t2, t3, t4, t5, t6, t7; for (int z = 0; z < depthC4; ++z) { auto dstPlane = dst + z * area * PACK_UNIT; auto srcPlane = src + z * area * PACK_UNIT; for (int x = 0; x < areaC4; ++x) { auto s = srcPlane + PACK_UNIT * PACK_UNIT * x; auto d = dstPlane + PACK_UNIT * x; auto r0 = _mm256_loadu_ps(s + 0 * PACK_UNIT); auto r1 = _mm256_loadu_ps(s + 1 * PACK_UNIT); auto r2 = _mm256_loadu_ps(s + 2 * PACK_UNIT); auto r3 = _mm256_loadu_ps(s + 3 * PACK_UNIT); auto r4 = _mm256_loadu_ps(s + 4 * PACK_UNIT); auto r5 = _mm256_loadu_ps(s + 5 * PACK_UNIT); auto r6 = _mm256_loadu_ps(s + 6 * PACK_UNIT); auto r7 = _mm256_loadu_ps(s + 7 * PACK_UNIT); TRANSPOSE_8x8; _mm256_storeu_ps(d + 0 * area, t0); _mm256_storeu_ps(d + 1 * area, t1); _mm256_storeu_ps(d + 2 * area, t2); _mm256_storeu_ps(d + 3 * area, t3); _mm256_storeu_ps(d + 4 * area, t4); _mm256_storeu_ps(d + 5 * area, t5); _mm256_storeu_ps(d + 6 * area, t6); _mm256_storeu_ps(d + 7 * area, t7); } } auto areaRemain = areaC4 * PACK_UNIT; auto depthRemain = depthC4 * PACK_UNIT; // Down int remain = depth - depthRemain; if (remain > 0) { float* dstPlane = depthC4 * area * PACK_UNIT + dst; const float* srcPlane = src + depthC4 * area * PACK_UNIT; for (int x = 0; x < areaC4; ++x) { auto s = srcPlane + PACK_UNIT * PACK_UNIT * x; auto d = dstPlane + PACK_UNIT * x; auto r0 = _mm256_loadu_ps(s + 0 * PACK_UNIT); auto r1 = _mm256_loadu_ps(s + 1 * PACK_UNIT); auto r2 = _mm256_loadu_ps(s + 2 * PACK_UNIT); auto r3 = _mm256_loadu_ps(s + 3 * PACK_UNIT); auto r4 = _mm256_loadu_ps(s + 4 * PACK_UNIT); auto r5 = _mm256_loadu_ps(s + 5 * PACK_UNIT); auto r6 = _mm256_loadu_ps(s + 6 * PACK_UNIT); auto r7 = _mm256_loadu_ps(s + 7 * PACK_UNIT); TRANSPOSE_8x8; switch (remain) { case 7: _mm256_storeu_ps(d + 6 * area, t6); case 6: _mm256_storeu_ps(d + 5 * area, t5); case 5: _mm256_storeu_ps(d + 4 * area, t4); case 4: _mm256_storeu_ps(d + 3 * area, t3); case 3: _mm256_storeu_ps(d + 2 * area, t2); case 2: _mm256_storeu_ps(d + 1 * area, t1); case 1: _mm256_storeu_ps(d + 0 * area, t0); default: break; } } for (int x = areaRemain; x < area; ++x) { for (int y = 0; y < remain; y++) { dstPlane[y * area + x] = srcPlane[PACK_UNIT * x + y]; } } } // Right for (int z = 0; z < depthC4; ++z) { const float* srcPlane = z * area * PACK_UNIT + src; float* dstPlane = dst + z * area * PACK_UNIT; for (int x = areaRemain; x < area; ++x) { for (int y = 0; y < PACK_UNIT; y++) { dstPlane[y * area + x] = srcPlane[PACK_UNIT * x + y]; } } } } void _AVX_MNNPackCUnitTranspose(float* dst, const float* src, size_t area, size_t depth) { int c = (int)depth; int cDiv4 = c / PACK_UNIT; int cAlign = cDiv4 * PACK_UNIT; for (int hi = 0; hi < area; ++hi) { const float* srcHeight = src + hi * c; float* dstHeight = dst + hi * PACK_UNIT; for (int ci = 0; ci < cDiv4; ++ci) { _mm256_storeu_ps(dstHeight + PACK_UNIT * ci * area, _mm256_loadu_ps(srcHeight + PACK_UNIT * ci)); } } if (cAlign == c) { return; } int cReamin = c - cAlign; auto srcAlign = src + cAlign; auto dstAlign = dst + area * cAlign; for (int hi = 0; hi < area; ++hi) { const float* srcHeight = srcAlign + hi * c; float* dstHeight = dstAlign + hi * PACK_UNIT; for (int i = 0; i < PACK_UNIT; ++i) { dstHeight[i] = 0; } for (int ci = 0; ci < cReamin; ++ci) { dstHeight[ci] = srcHeight[ci]; } } } void _AVX_MNNUnpackCUnitTranspose(float* dst, const float* src, size_t area, size_t depth) { int c = (int)depth; int cDiv4 = c / PACK_UNIT; int cAlign = cDiv4 * PACK_UNIT; for (int hi = 0; hi < area; ++hi) { const float* srcHeight = src + hi * PACK_UNIT; float* dstHeight = dst + hi * c; for (int ci = 0; ci < cDiv4; ++ci) { _mm256_storeu_ps(dstHeight + PACK_UNIT * ci, _mm256_loadu_ps(srcHeight + PACK_UNIT * ci * area)); } } if (cAlign == c) { return; } int cReamin = c - cAlign; auto srcAlign = src + area * cAlign; auto dstAlign = dst + cAlign; for (int hi = 0; hi < area; ++hi) { const float* srcHeight = srcAlign + hi * PACK_UNIT; float* dstHeight = dstAlign + hi * c; for (int ci = 0; ci < cReamin; ++ci) { dstHeight[ci] = srcHeight[ci]; } } } void _AVX_MNNReluWithSlopeChannel(float* dst, const float* src, const float* slope, size_t sizeQuad, size_t depthQuad) { auto zero = _mm_set1_ps(0.0f); auto zero2 = _mm256_set1_ps(0.0f); int sizeC8 = sizeQuad; for (int j = 0; j < depthQuad; j++) { auto slopeZ = _mm256_loadu_ps(slope + 8 * j); const float* srcZ = src + 8 * j * sizeQuad; float* dstZ = dst + 8 * j * sizeQuad; for (int i = 0; i < sizeC8; i++) { auto src = _mm256_loadu_ps(srcZ); auto mask0 = _mm256_cmp_ps(src, zero2, 0x01); auto mask1 = _mm256_cmp_ps(src, zero2, 0x0D); auto other = _mm256_mul_ps(src, slopeZ); _mm256_storeu_ps(dstZ, _mm256_add_ps(_mm256_and_ps(other, mask0), _mm256_and_ps(src, mask1))); srcZ += 8; dstZ += 8; } } } void _AVX_MNNGelu(float *dst, const float *src, size_t size) { auto var1 = _mm256_set1_ps(0.044715f); auto var2 = _mm256_set1_ps(0.79788458f); auto var3 = _mm256_set1_ps(378.f); auto var4 = _mm256_set1_ps(17325.f); auto var5 = _mm256_set1_ps(135135.f); auto var6 = _mm256_set1_ps(28.f); auto var7 = _mm256_set1_ps(3150.f); auto var8 = _mm256_set1_ps(62370.f); auto var9 = _mm256_set1_ps(135135.f); auto var10 = _mm256_set1_ps(0.5); auto varOne = _mm256_set1_ps(1.f); auto varNegOne = _mm256_set1_ps(-1.f); for (int i = 0; i < size; i++) { auto x = _mm256_load_ps(src + i * 8); auto y = _mm256_mul_ps(x, x); y = _mm256_mul_ps(y, x); y = _mm256_mul_ps(y, var1); y = _mm256_add_ps(y, x); y = _mm256_mul_ps(y, var2); // y = tanh(y) { auto y2 = _mm256_mul_ps(y, y); auto w = _mm256_add_ps(y2, var3); w = _mm256_mul_ps(w, y2); w = _mm256_add_ps(w, var4); w = _mm256_mul_ps(w, y2); w = _mm256_add_ps(w, var5); w = _mm256_mul_ps(w, y); auto z = _mm256_mul_ps(y2, var6); z = _mm256_add_ps(z, var7); z = _mm256_mul_ps(z, y2); z = _mm256_add_ps(z, var8); z = _mm256_mul_ps(z, y2); z = _mm256_add_ps(z, var9); z = _mm256_div_ps(w, z); z = _mm256_max_ps(z, varNegOne); y = _mm256_min_ps(z, varOne); } y = _mm256_add_ps(y, varOne); y = _mm256_mul_ps(y, x); y = _mm256_mul_ps(y, var10); _mm256_storeu_ps(dst + i * 8, y); } } void _AVX_MNNAxByClampBroadcastUnit(float* C, const float* A, const float* B, size_t width, size_t cStride, size_t aStride, size_t height, const float* parameters) { auto minF = _mm256_broadcast_ss(parameters + 2); auto maxF = _mm256_broadcast_ss(parameters + 3); for (int y = 0; y < height; ++y) { auto a = A + aStride * y; auto b = B + 8 * y; auto bv = _mm256_loadu_ps(b); auto c = C + cStride * y; for (int x = 0; x < width; ++x) { auto av = _mm256_loadu_ps(a); auto cv = _mm256_add_ps(av, bv); cv = _mm256_min_ps(cv, maxF); cv = _mm256_max_ps(cv, minF); _mm256_storeu_ps(c, cv); a += 8; c += 8; } } } void _AVX_MNNExpC8(float* dest, const float* source, const float* parameters, size_t countC8) { auto count = countC8; auto p0 = _mm256_set1_ps(parameters[0]); auto p1 = _mm256_set1_ps(parameters[1]); auto p2 = _mm256_set1_ps(parameters[2]); auto p3 = _mm256_set1_ps(parameters[3]); auto p4 = _mm256_set1_ps(parameters[4]); auto p5 = _mm256_set1_ps(parameters[5]); auto p6 = _mm256_set1_ps(parameters[6]); auto p7 = _mm256_set1_ps(parameters[7]); auto xMax = _mm256_set1_ps(87); auto xMin = _mm256_set1_ps(-87); auto basic = _mm256_set1_epi32(1 << 23); auto temp127 = _mm256_set1_epi32(127); auto negZero = _mm256_set1_ps(-0.f); for (int i = 0; i < count; ++i) { auto x = _mm256_xor_ps(_mm256_loadu_ps(source + i * 8), negZero); x = _mm256_max_ps(x, xMin); x = _mm256_min_ps(x, xMax); auto div = _mm256_mul_ps(x, p1); auto divInt = _mm256_cvtps_epi32(div); div = _mm256_cvtepi32_ps(divInt); auto div2 = _mm256_add_epi32(divInt, temp127); div2 = _mm256_mullo_epi32(div2, basic); auto expBasic = _mm256_castsi256_ps(div2); auto xReamin = _mm256_sub_ps(x, _mm256_mul_ps(div, p0)); auto t = xReamin; auto c0 = _mm256_mul_ps(p7, t); auto c1 = _mm256_add_ps(c0, p6); auto c2 = _mm256_mul_ps(c1, t); auto c3 = _mm256_add_ps(c2, p5); auto c4 = _mm256_mul_ps(c3, t); auto c5 = _mm256_add_ps(c4, p4); auto c6 = _mm256_mul_ps(c5, t); auto c7 = _mm256_add_ps(c6, p3); auto c8 = _mm256_mul_ps(c7, t); auto c9 = _mm256_add_ps(c8, p2); auto expRemain = c9; _mm256_storeu_ps(dest + 8 * i, _mm256_mul_ps(expBasic, expRemain)); } } void _AVX_MNNConvRunForUnitDepthWise(float* dst, const float* src, const float* weight, size_t fw, size_t fh, size_t weight_y_step, size_t dilateX_step, size_t dilateY_step) { int fx, fy; __m256 dstValue = _mm256_setzero_ps(); const float* src_z = src; const float* weight_z = weight; for (fy = 0; fy < fh; ++fy) { const float* src_y = src_z + fy * dilateY_step; const float* weight_y = weight_z + fy * weight_y_step; for (fx = 0; fx < fw; ++fx) { const float* weight_x = weight_y + 8 * fx; const float* src_x = src_y + fx * dilateX_step; dstValue = _mm256_add_ps(dstValue, _mm256_mul_ps(_mm256_loadu_ps(src_x), _mm256_loadu_ps(weight_x))); } } _mm256_storeu_ps(dst, dstValue); } void _AVX_MNNConvRunForLineDepthwise(float* dst, const float* src, const float* weight, size_t width, size_t src_w_setup, size_t fw, size_t fh, size_t dilateX_step, size_t dilateY_step, size_t height, size_t srcHStep, size_t dstHStep) { int dx, fx, fy; const int unit = 4; int widthUnit = width / unit; int widthRemain = width - widthUnit * unit; const float* weight_z = weight; if (src_w_setup == 8) { for (int y = 0; y < height; ++y) { auto srcY = src + y * srcHStep; auto dstY = dst + y * dstHStep; for (dx = 0; dx < widthUnit; ++dx) { auto dstValue0 = _mm256_setzero_ps(); auto dstValue1 = _mm256_setzero_ps(); auto dstValue2 = _mm256_setzero_ps(); auto dstValue3 = _mm256_setzero_ps(); for (fy = 0; fy < fh; ++fy) { const float* src_y = srcY + fy * dilateY_step; const float* weight_y = weight_z + fy * fw * 8; for (fx = 0; fx < fw; ++fx) { const float* src_x = src_y + fx * dilateX_step; const float* weight_x = weight_y + 8 * fx; auto weightValue = _mm256_loadu_ps(weight_x); dstValue0 = _mm256_add_ps(dstValue0, _mm256_mul_ps(_mm256_loadu_ps(src_x + 0 * 8), weightValue)); dstValue1 = _mm256_add_ps(dstValue1, _mm256_mul_ps(_mm256_loadu_ps(src_x + 1 * 8), weightValue)); dstValue2 = _mm256_add_ps(dstValue2, _mm256_mul_ps(_mm256_loadu_ps(src_x + 2 * 8), weightValue)); dstValue3 = _mm256_add_ps(dstValue3, _mm256_mul_ps(_mm256_loadu_ps(src_x + 3 * 8), weightValue)); } } _mm256_storeu_ps(dstY + 8 * 0, dstValue0); _mm256_storeu_ps(dstY + 8 * 1, dstValue1); _mm256_storeu_ps(dstY + 8 * 2, dstValue2); _mm256_storeu_ps(dstY + 8 * 3, dstValue3); dstY += 8 * unit; srcY += unit * src_w_setup; } for (dx = 0; dx < widthRemain; ++dx) { float* dst_x = dstY + dx * 8; auto dstValue = _mm256_setzero_ps(); const float* src_z = srcY + src_w_setup * dx; const float* weight_z = weight; for (fy = 0; fy < fh; ++fy) { const float* src_y = src_z + fy * dilateY_step; const float* weight_y = weight_z + fy * fw * 8; for (fx = 0; fx < fw; ++fx) { const float* weight_x = weight_y + 8 * fx; const float* src_x = src_y + fx * dilateX_step; dstValue = _mm256_add_ps(dstValue, _mm256_mul_ps(_mm256_loadu_ps(src_x), _mm256_loadu_ps(weight_x))); } } _mm256_storeu_ps(dst_x, dstValue); } } return; } for (int y = 0; y < height; ++y) { auto srcY = src + y * srcHStep; auto dstY = dst + y * dstHStep; for (dx = 0; dx < widthUnit; ++dx) { auto dstValue0 = _mm256_setzero_ps(); auto dstValue1 = _mm256_setzero_ps(); auto dstValue2 = _mm256_setzero_ps(); auto dstValue3 = _mm256_setzero_ps(); for (fy = 0; fy < fh; ++fy) { const float* src_y = srcY + fy * dilateY_step; const float* weight_y = weight_z + fy * fw * 8; for (fx = 0; fx < fw; ++fx) { const float* src_x = src_y + fx * dilateX_step; const float* weight_x = weight_y + 8 * fx; auto weightValue = _mm256_loadu_ps(weight_x); dstValue0 = _mm256_add_ps(dstValue0, _mm256_mul_ps(_mm256_loadu_ps(src_x + 0 * src_w_setup), weightValue)); dstValue1 = _mm256_add_ps(dstValue1, _mm256_mul_ps(_mm256_loadu_ps(src_x + 1 * src_w_setup), weightValue)); dstValue2 = _mm256_add_ps(dstValue2, _mm256_mul_ps(_mm256_loadu_ps(src_x + 2 * src_w_setup), weightValue)); dstValue3 = _mm256_add_ps(dstValue3, _mm256_mul_ps(_mm256_loadu_ps(src_x + 3 * src_w_setup), weightValue)); } } _mm256_storeu_ps(dstY + 8 * 0, dstValue0); _mm256_storeu_ps(dstY + 8 * 1, dstValue1); _mm256_storeu_ps(dstY + 8 * 2, dstValue2); _mm256_storeu_ps(dstY + 8 * 3, dstValue3); dstY += 8 * unit; srcY += unit * src_w_setup; } for (dx = 0; dx < widthRemain; ++dx) { float* dst_x = dstY + dx * 8; auto dstValue = _mm256_setzero_ps(); const float* src_z = srcY + src_w_setup * dx; const float* weight_z = weight; for (fy = 0; fy < fh; ++fy) { const float* src_y = src_z + fy * dilateY_step; const float* weight_y = weight_z + fy * fw * 8; for (fx = 0; fx < fw; ++fx) { const float* weight_x = weight_y + 8 * fx; const float* src_x = src_y + fx * dilateX_step; dstValue = _mm256_add_ps(dstValue, _mm256_mul_ps(_mm256_loadu_ps(src_x), _mm256_loadu_ps(weight_x))); } } _mm256_storeu_ps(dst_x, dstValue); } } } void _AVX_MNNMultiAndDestTransformCommon23(float **cacheLine, const float *weigth, float *dest, int cacheLineSize, int ow, const float* bias, const float* parameter) { int unit = ow / 2; MNN_ASSERT(cacheLineSize >= 1); auto biasF = Vec8::load(bias); auto minF = Vec8(parameter[2]); auto maxF = Vec8(parameter[3]); for (int x = 0; x < unit; ++x) { auto offset = 4 * 8 * x; int i = 0; Vec8 m0 = Vec8::load(weigth + i * 32 + 8 * 0) * Vec8::load(cacheLine[i] + offset + 8 * 0); Vec8 m1 = Vec8::load(weigth + i * 32 + 8 * 1) * Vec8::load(cacheLine[i] + offset + 8 * 1); Vec8 m2 = Vec8::load(weigth + i * 32 + 8 * 2) * Vec8::load(cacheLine[i] + offset + 8 * 2); Vec8 m3 = Vec8::load(weigth + i * 32 + 8 * 3) * Vec8::load(cacheLine[i] + offset + 8 * 3); for (i = 1; i < cacheLineSize; ++i) { m0 = m0 + Vec8::load(weigth + i * 32 + 8 * 0) * Vec8::load(cacheLine[i] + offset + 8 * 0); m1 = m1 + Vec8::load(weigth + i * 32 + 8 * 1) * Vec8::load(cacheLine[i] + offset + 8 * 1); m2 = m2 + Vec8::load(weigth + i * 32 + 8 * 2) * Vec8::load(cacheLine[i] + offset + 8 * 2); m3 = m3 + Vec8::load(weigth + i * 32 + 8 * 3) * Vec8::load(cacheLine[i] + offset + 8 * 3); } auto o0 = m0 + m1 + m2 + biasF; auto o1 = m1 - m2 + m3 + biasF; o0 = Vec8::min(maxF, o0); o1 = Vec8::min(maxF, o1); o0 = Vec8::max(minF, o0); o1 = Vec8::max(minF, o1); Vec8::save(dest + 16 * x + 0 * 8, o0); Vec8::save(dest + 16 * x + 1 * 8, o1); } if (unit * 2 < ow) { auto offset = 8 * 4 * unit; int i = 0; Vec8 m0 = Vec8::load(weigth + i * 32 + 8 * 0) * Vec8::load(cacheLine[i] + offset + 8 * 0); Vec8 m1 = Vec8::load(weigth + i * 32 + 8 * 1) * Vec8::load(cacheLine[i] + offset + 8 * 1); Vec8 m2 = Vec8::load(weigth + i * 32 + 8 * 2) * Vec8::load(cacheLine[i] + offset + 8 * 2); for (i = 1; i < cacheLineSize; ++i) { m0 = m0 + Vec8::load(weigth + i * 32 + 8 * 0) * Vec8::load(cacheLine[i] + offset + 8 * 0); m1 = m1 + Vec8::load(weigth + i * 32 + 8 * 1) * Vec8::load(cacheLine[i] + offset + 8 * 1); m2 = m2 + Vec8::load(weigth + i * 32 + 8 * 2) * Vec8::load(cacheLine[i] + offset + 8 * 2); } auto o0 = m0 + m1 + m2 + biasF; o0 = Vec8::min(maxF, o0); o0 = Vec8::max(minF, o0); Vec8::save(dest + 16 * unit + 0 * 8, o0); } } static void _AVX_MNNConvDwF23SourceTransUnit(const float *source, float *dest, size_t unit) { if (unit <= 0) { return; } Vec8 v0 = Vec8::load(source + 8 * 0); Vec8 v1 = Vec8::load(source + 8 * 1); Vec8 v2; Vec8 v3; source += 16; for (int x = 0; x < unit; ++x) { v2 = Vec8::load(source + 0 * 8); v3 = Vec8::load(source + 1 * 8); auto m0 = v0 - v2; auto m1 = v1 + v2; auto m2 = v2 - v1; auto m3 = v3 - v1; Vec8::save(dest + 8 * 0, m0); Vec8::save(dest + 8 * 1, m1); Vec8::save(dest + 8 * 2, m2); Vec8::save(dest + 8 * 3, m3); source += 16; dest += 32; v0 = v2; v1 = v3; } } void _AVX_MNNSourceTransformCommonF23(const float *source, float *dest, int unit, int iw, int pad, int su, int eu) { for (int x = 0; x < su; ++x) { auto dstX = dest + 4 * 8 * x; auto sx = x * 2 - (int)pad; auto ex = sx + 4; auto clampSx = std::max(sx, 0); auto clampEx = std::min(ex, (int)iw); Vec8 v[4] = {0.0f, 0.0f, 0.0f, 0.0f}; for (int i = clampSx; i < clampEx; ++i) { v[i - sx] = Vec8::load(source + 8 * i); } auto m0 = v[0] - v[2]; auto m1 = v[1] + v[2]; auto m2 = v[2] - v[1]; auto m3 = v[3] - v[1]; Vec8::save(dstX + 8 * 0, m0); Vec8::save(dstX + 8 * 1, m1); Vec8::save(dstX + 8 * 2, m2); Vec8::save(dstX + 8 * 3, m3); } _AVX_MNNConvDwF23SourceTransUnit(source + 8 * (su * 2 - pad), dest + 8 * 4 * su, eu - su); for (int x = eu; x < unit; ++x) { auto dstX = dest + 8 * 4 * x; auto sx = x * 2 - (int)pad; auto ex = sx + 4; auto clampSx = std::max(sx, 0); auto clampEx = std::min(ex, (int)iw); Vec8 v[4] = {0.0f, 0.0f, 0.0f, 0.0f}; for (int i = clampSx; i < clampEx; ++i) { v[i - sx] = Vec8::load(source + 8 * i); } auto m0 = v[0] - v[2]; auto m1 = v[1] + v[2]; auto m2 = v[2] - v[1]; auto m3 = v[3] - v[1]; Vec8::save(dstX + 8 * 0, m0); Vec8::save(dstX + 8 * 1, m1); Vec8::save(dstX + 8 * 2, m2); Vec8::save(dstX + 8 * 3, m3); } } void _AVX_MNNConvDwF23MulTransUnit(float **cacheLine, const float *weigth, float *dest, size_t ow, const float* bias, const float* parameter) { int unit = ow / 2; auto w00 = Vec8::load(weigth + 0 * 32 + 8 * 0); auto w01 = Vec8::load(weigth + 0 * 32 + 8 * 1); auto w02 = Vec8::load(weigth + 0 * 32 + 8 * 2); auto w03 = Vec8::load(weigth + 0 * 32 + 8 * 3); auto w10 = Vec8::load(weigth + 1 * 32 + 8 * 0); auto w11 = Vec8::load(weigth + 1 * 32 + 8 * 1); auto w12 = Vec8::load(weigth + 1 * 32 + 8 * 2); auto w13 = Vec8::load(weigth + 1 * 32 + 8 * 3); auto w20 = Vec8::load(weigth + 2 * 32 + 8 * 0); auto w21 = Vec8::load(weigth + 2 * 32 + 8 * 1); auto w22 = Vec8::load(weigth + 2 * 32 + 8 * 2); auto w23 = Vec8::load(weigth + 2 * 32 + 8 * 3); auto biasF = Vec8::load(bias); auto minF = Vec8(parameter[2]); auto maxF = Vec8(parameter[3]); for (int x = 0; x < unit; ++x) { auto offset = 8 * 4 * x; int i = 0; Vec8 m0 = w00 * Vec8::load(cacheLine[0] + offset + 8 * 0); Vec8 m1 = w01 * Vec8::load(cacheLine[0] + offset + 8 * 1); Vec8 m2 = w02 * Vec8::load(cacheLine[0] + offset + 8 * 2); Vec8 m3 = w03 * Vec8::load(cacheLine[0] + offset + 8 * 3); m0 = m0 + w10 * Vec8::load(cacheLine[1] + offset + 8 * 0); m1 = m1 + w11 * Vec8::load(cacheLine[1] + offset + 8 * 1); m2 = m2 + w12 * Vec8::load(cacheLine[1] + offset + 8 * 2); m3 = m3 + w13 * Vec8::load(cacheLine[1] + offset + 8 * 3); m0 = m0 + w20 * Vec8::load(cacheLine[2] + offset + 8 * 0); m1 = m1 + w21 * Vec8::load(cacheLine[2] + offset + 8 * 1); m2 = m2 + w22 * Vec8::load(cacheLine[2] + offset + 8 * 2); m3 = m3 + w23 * Vec8::load(cacheLine[2] + offset + 8 * 3); auto o0 = m0 + m1 + m2 + biasF; auto o1 = m1 - m2 + m3 + biasF; o0 = Vec8::min(maxF, o0); o1 = Vec8::min(maxF, o1); o0 = Vec8::max(minF, o0); o1 = Vec8::max(minF, o1); Vec8::save(dest + 16 * x + 0 * 8, o0); Vec8::save(dest + 16 * x + 1 * 8, o1); } if (unit * 2 < ow) { auto offset = 8 * 4 * unit; Vec8 m0 = w00 * Vec8::load(cacheLine[0] + offset + 8 * 0); Vec8 m1 = w01 * Vec8::load(cacheLine[0] + offset + 8 * 1); Vec8 m2 = w02 * Vec8::load(cacheLine[0] + offset + 8 * 2); m0 = m0 + w10 * Vec8::load(cacheLine[1] + offset + 8 * 0); m1 = m1 + w11 * Vec8::load(cacheLine[1] + offset + 8 * 1); m2 = m2 + w12 * Vec8::load(cacheLine[1] + offset + 8 * 2); m0 = m0 + w20 * Vec8::load(cacheLine[2] + offset + 8 * 0); m1 = m1 + w21 * Vec8::load(cacheLine[2] + offset + 8 * 1); m2 = m2 + w22 * Vec8::load(cacheLine[2] + offset + 8 * 2); auto o0 = m0 + m1 + m2 + biasF; o0 = Vec8::min(maxF, o0); o0 = Vec8::max(minF, o0); Vec8::save(dest + 16 * unit + 0 * 8, o0); } } static MNNBinaryExecute _AVX2_MNNSelectBinaryFunctionForFloat(int opType) { auto vecF = MNN::selectVector<Vec8, 8>(opType); if (nullptr != vecF) { return vecF; } return MNN::MNNGetCoreFunctions()->MNNSelectBinaryFunctionForFloat(opType); } void _AVX_ExtraInit(void* functions) { auto coreFunction = static_cast<MNN::CoreFunctions*>(functions); coreFunction->MNNPoolingAvg = (decltype(coreFunction->MNNPoolingAvg))(MNN::poolingAvg<float, Vec8, 8>); // Set min value as 1 << 24 coreFunction->MNNPoolingMax = (decltype(coreFunction->MNNPoolingMax))(MNN::poolingMax<float, Vec8, 8, -16777216>); coreFunction->MNNSelectBinaryFunctionForFloat = _AVX2_MNNSelectBinaryFunctionForFloat; } void _AVX_MNNScaleAndAddBias(float* dst, const float* src, const float* bias, const float* alpha, size_t planeNumber, size_t biasNumber) { for (int z = 0; z < biasNumber; ++z) { float* dstZ = dst + planeNumber * 8 * z; const float* srcZ = src + planeNumber * 8 * z; auto biasZ = Vec8::load(bias + 8 * z); auto alphaZ = Vec8::load(alpha + 8 * z); for (int p = 0; p < planeNumber; ++p) { float* dstX = dstZ + 8 * p; const float* srcX = srcZ + 8 * p; Vec8::save(dstX, (Vec8::load(srcX) * alphaZ) + biasZ); } } } void _AVX_MNNDeconvRunForUnitDepthWise(const float* dst, float* src, const float* weight, size_t fw, size_t fh, size_t weight_y_step, size_t dilateX_step, size_t dilateY_step) { int fx, fy; float* src_z = src; const float* weight_z = weight; Vec8 dstV = Vec8::load(dst); for (fy = 0; fy < fh; ++fy) { float* src_y = src_z + fy * dilateY_step; const float* weight_y = weight_z + fy * weight_y_step; for (fx = 0; fx < fw; ++fx) { Vec8 weight_x = Vec8::load(weight_y + 8 * fx); Vec8 src_x = Vec8::load(src_y + fx * dilateX_step); Vec8::save(src_y + fx * dilateX_step, src_x + weight_x * dstV); } } } void _AVX_MNNDeconvRunForLineDepthwise(const float* dst, float* src, const float* weight, size_t width, size_t src_w_setup, size_t fw, size_t fh, size_t dilateX_step, size_t dilateY_step) { int dx; for (dx = 0; dx < width; ++dx) { const float* dst_x = dst + dx * 8; float* src_dx = src + src_w_setup * dx; _AVX_MNNDeconvRunForUnitDepthWise(dst_x, src_dx, weight, fw, fh, fw * 8, dilateX_step, dilateY_step); } }
61b3f124a58e58a35a47ae1e717a10f60d5ca83e
56128d7ed44dde19eeb00423236309178a9ad74e
/src/ctevents.h
dbfc634aeed299a7a34e6cd239c9e7ccf3d4f7bf
[ "MIT" ]
permissive
atdrez/cortex2d
7d7e37669ce2e93a6e1edec056692b70d80918dc
76f6bfc652477e2f1e83ff003aca8797c664d808
refs/heads/master
2023-03-17T12:16:11.866775
2021-03-05T23:40:28
2021-03-06T00:05:00
344,955,493
0
0
null
null
null
null
UTF-8
C++
false
false
5,267
h
ctevents.h
#ifndef EVENT_H #define EVENT_H #include "ctglobal.h" #include "ctlist.h" class CtSprite; class CtEvent { public: enum Type { MousePress, MouseMove, MouseRelease, WindowResize, WindowClose, KeyPress, KeyRelease, TouchBegin, TouchUpdate, TouchEnd, DragEnter, DragMove, DragLeave, Drop, DragCursorDrop, DragCursorCancel, WindowMinimize, WindowRestore, ApplicationReady, ApplicationAboutToQuit, ApplicationActivated, ApplicationDeactivated, ApplicationAboutToResign, ApplicationAboutToActivate, Custom = 0x80 }; CtEvent(Type type); virtual ~CtEvent() {} Type type() const { return m_type; } bool isAccepted() const { return m_accepted; } void setAccepted(bool accepted); private: Type m_type; bool m_accepted; CT_PRIVATE_COPY(CtEvent); }; class CtWindowMinimizeEvent : public CtEvent { public: CtWindowMinimizeEvent() : CtEvent(WindowMinimize) {} CT_PRIVATE_COPY(CtWindowMinimizeEvent); }; class CtWindowRestoreEvent : public CtEvent { public: CtWindowRestoreEvent() : CtEvent(WindowRestore) {} CT_PRIVATE_COPY(CtWindowRestoreEvent); }; class CtMouseEvent : public CtEvent { public: CtMouseEvent(Type type, Ct::MouseButton button, ctreal x, ctreal y, ctreal sceneX, ctreal sceneY, ctreal initialX, ctreal initialY); ctreal x() const { return m_x; } ctreal y() const { return m_y; } ctreal sceneX() const { return m_sceneX; } ctreal sceneY() const { return m_sceneY; } ctreal initialX() const { return m_initialX; } ctreal initialY() const { return m_initialY; } Ct::MouseButton button() const { return m_button; } private: ctreal m_x; ctreal m_y; ctreal m_sceneX; ctreal m_sceneY; ctreal m_initialX; ctreal m_initialY; Ct::MouseButton m_button; CT_PRIVATE_COPY(CtMouseEvent); }; class CtDragDropEvent : public CtEvent { public: enum Operation { Copy = 1, Move = 2 }; CtDragDropEvent(Type type, CtSprite *sourceItem, CtSprite *targetItem, CtSprite *draggedItem, const CtString &mime, Operation operation, ctreal x, ctreal y, ctreal sceneX, ctreal sceneY); CtString mime() const { return m_mime; } CtSprite *sourceItem() const { return m_sourceItem; } CtSprite *targetItem() const { return m_targetItem; } CtSprite *draggedItem() const { return m_draggedItem; } ctreal x() const { return m_x; } ctreal y() const { return m_y; } ctreal sceneX() const { return m_sceneX; } ctreal sceneY() const { return m_sceneY; } Operation operation() const { return m_operation; } private: CtSprite *m_sourceItem; CtSprite *m_targetItem; CtSprite *m_draggedItem; CtString m_mime; Operation m_operation; ctreal m_x; ctreal m_y; ctreal m_sceneX; ctreal m_sceneY; CT_PRIVATE_COPY(CtDragDropEvent); }; class CtKeyEvent : public CtEvent { public: CtKeyEvent(Type type, int key, int modifiers, bool autoRepeat = false); int key() const { return m_key; } int modifiers() const { return m_modifiers; } int isAutoRepeat() const { return m_autoRepeat; } private: int m_key; int m_modifiers; bool m_autoRepeat; CT_PRIVATE_COPY(CtKeyEvent); }; class CtWindowResizeEvent : public CtEvent { public: CtWindowResizeEvent(int width, int height); int width() const { return m_width; } int height() const { return m_height; } private: int m_width; int m_height; CT_PRIVATE_COPY(CtWindowResizeEvent); }; class CtWindowCloseEvent : public CtEvent { public: CtWindowCloseEvent() : CtEvent(WindowClose) {} CT_PRIVATE_COPY(CtWindowCloseEvent); }; class CtTouchPoint { public: CtTouchPoint(); CtTouchPoint(int id, ctreal x, ctreal y, ctreal initialX, ctreal initialY, ctreal pressure, bool pressed); CtTouchPoint(const CtTouchPoint &p); int id() const { return m_id; } bool isValid() { return m_id >= 0; } ctreal x() const { return m_x; } ctreal y() const { return m_y; } ctreal initialX() const { return m_initialX; } ctreal initialY() const { return m_initialY; } bool isInsideClickThreshold() const; bool isPressed() const { return m_pressed; } ctreal pressure() const { return m_pressure; } private: int m_id; ctreal m_x; ctreal m_y; ctreal m_initialX; ctreal m_initialY; ctreal m_pressure; bool m_pressed; }; typedef CtList<CtTouchPoint> CtTouchPointList; class CtTouchEvent : public CtEvent { public: CtTouchEvent(Type type, int id, const CtTouchPoint &p); CtTouchEvent(Type type, int id, const CtTouchPointList &points); int id() const { return m_id; } CtTouchPoint findTouchById(int id) const; CtTouchPoint touchPointAt(int index) const; int touchPointCount() const { return m_points.size(); } CtTouchPointList touchPoints() const { return m_points; } private: int m_id; CtTouchPointList m_points; CT_PRIVATE_COPY(CtTouchEvent); }; #endif
b3ad9e07a13ad2f393afc098b41bbeb0e0f41719
fa8e41eea4e30a407e5a73b7524050f0fe15b40b
/ogsr_engine/xrGame/hud_item_object.cpp
fb37fbf84d4b545f72c78da01d8c2753382ebcc1
[ "Apache-2.0" ]
permissive
dsh2dsh/OGSR-Engine
70c29d81fba88cece52a3150a57c24a00b1e121a
43ac8298b9a264e23c40d05beb20d7ca64a4a589
refs/heads/master
2023-08-15T23:32:56.804065
2023-07-25T15:16:22
2023-07-25T15:16:22
250,016,513
7
4
null
null
null
null
UTF-8
C++
false
false
2,321
cpp
hud_item_object.cpp
//////////////////////////////////////////////////////////////////////////// // Module : hud_item_object.cpp // Created : 24.03.2003 // Modified : 27.12.2004 // Author : Yuri Dobronravin // Description : HUD item //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "hud_item_object.h" CHudItemObject::CHudItemObject() {} CHudItemObject::~CHudItemObject() {} DLL_Pure* CHudItemObject::_construct() { CInventoryItemObject::_construct(); CHudItem::_construct(); return (this); } void CHudItemObject::Load(LPCSTR section) { CInventoryItemObject::Load(section); CHudItem::Load(section); } bool CHudItemObject::Action(s32 cmd, u32 flags) { if (CInventoryItemObject::Action(cmd, flags)) return (true); return (CHudItem::Action(cmd, flags)); } void CHudItemObject::SwitchState(u32 S) { CHudItem::SwitchState(S); } void CHudItemObject::OnStateSwitch(u32 S) { CHudItem::OnStateSwitch(S); } void CHudItemObject::OnEvent(NET_Packet& P, u16 type) { CInventoryItemObject::OnEvent(P, type); CHudItem::OnEvent(P, type); } void CHudItemObject::OnH_A_Chield() { CHudItem::OnH_A_Chield(); CInventoryItemObject::OnH_A_Chield(); } void CHudItemObject::OnH_B_Chield() { CInventoryItemObject::OnH_B_Chield(); CHudItem::OnH_B_Chield(); } void CHudItemObject::OnH_B_Independent(bool just_before_destroy) { CHudItem::OnH_B_Independent(just_before_destroy); CInventoryItemObject::OnH_B_Independent(just_before_destroy); } void CHudItemObject::OnH_A_Independent() { CHudItem::OnH_A_Independent(); CInventoryItemObject::OnH_A_Independent(); } BOOL CHudItemObject::net_Spawn(CSE_Abstract* DC) { return (CInventoryItemObject::net_Spawn(DC) && CHudItem::net_Spawn(DC)); } void CHudItemObject::net_Destroy() { CHudItem::net_Destroy(); CInventoryItemObject::net_Destroy(); } bool CHudItemObject::Activate(bool now) { return CHudItem::Activate(now); } void CHudItemObject::Deactivate(bool now) { CHudItem::Deactivate(now); } void CHudItemObject::UpdateCL() { CInventoryItemObject::UpdateCL(); CHudItem::UpdateCL(); } void CHudItemObject::renderable_Render() { CHudItem::renderable_Render(); } void CHudItemObject::on_renderable_Render() { CInventoryItemObject::renderable_Render(); }
6ab44506a35566177bf2d8ff75f35d0fd412b860
56a77194fc0cd6087b0c2ca1fb6dc0de64b8a58a
/applications/ConstitutiveLawsApplication/custom_constitutive/small_strains/plasticity/generic_small_strain_isotropic_plasticity.h
69b3508b53ce1766cd03a4ed720bee73d371460b
[ "BSD-3-Clause" ]
permissive
KratosMultiphysics/Kratos
82b902a2266625b25f17239b42da958611a4b9c5
366949ec4e3651702edc6ac3061d2988f10dd271
refs/heads/master
2023-08-30T20:31:37.818693
2023-08-30T18:01:01
2023-08-30T18:01:01
81,815,495
994
285
NOASSERTION
2023-09-14T13:22:43
2017-02-13T10:58:24
C++
UTF-8
C++
false
false
15,095
h
generic_small_strain_isotropic_plasticity.h
// KRATOS ___ _ _ _ _ _ __ _ // / __\___ _ __ ___| |_(_) |_ _ _| |_(_)_ _____ / / __ ___ _____ /_\ _ __ _ __ // / / / _ \| '_ \/ __| __| | __| | | | __| \ \ / / _ \/ / / _` \ \ /\ / / __| //_\\| '_ \| '_ | // / /__| (_) | | | \__ \ |_| | |_| |_| | |_| |\ V / __/ /__| (_| |\ V V /\__ \/ _ \ |_) | |_) | // \____/\___/|_| |_|___/\__|_|\__|\__,_|\__|_| \_/ \___\____/\__,_| \_/\_/ |___/\_/ \_/ .__/| .__/ // |_| |_| // // License: BSD License // license: structural_mechanics_application/license.txt // // Main authors: Alejandro Cornejo & Lucia Barbu // Collaborator: Vicente Mataix Ferrandiz // #pragma once // System includes // External includes // Project includes #include "custom_constitutive/elastic_isotropic_3d.h" #include "custom_constitutive/linear_plane_strain.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ // The size type definition typedef std::size_t SizeType; ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class GenericSmallStrainIsotropicPlasticity * @ingroup StructuralMechanicsApplication * @brief This class is the base class which define all the constitutive laws for plasticity in small deformation * @details This class considers a constitutive law integrator as an intermediate utility to compute the plasticity * @tparam TConstLawIntegratorType The constitutive law integrator considered * @author Alejandro Cornejo & Lucia Barbu */ template <class TConstLawIntegratorType> class KRATOS_API(CONSTITUTIVE_LAWS_APPLICATION) GenericSmallStrainIsotropicPlasticity : public std::conditional<TConstLawIntegratorType::VoigtSize == 6, ElasticIsotropic3D, LinearPlaneStrain >::type { public: ///@name Type Definitions ///@{ /// The define the working dimension size, already defined in the integrator static constexpr SizeType Dimension = TConstLawIntegratorType::Dimension; /// The define the Voigt size, already defined in the integrator static constexpr SizeType VoigtSize = TConstLawIntegratorType::VoigtSize; /// Definition of the base class typedef typename std::conditional<VoigtSize == 6, ElasticIsotropic3D, LinearPlaneStrain >::type BaseType; /// The definition of the Voigt array type typedef array_1d<double, VoigtSize> BoundedArrayType; /// The definition of the bounded matrix type typedef BoundedMatrix<double, Dimension, Dimension> BoundedMatrixType; /// Counted pointer of GenericSmallStrainIsotropicPlasticity KRATOS_CLASS_POINTER_DEFINITION(GenericSmallStrainIsotropicPlasticity); /// The node definition typedef Node NodeType; /// The geometry definition typedef Geometry<NodeType> GeometryType; ///@} ///@name Life Cycle ///@{ /** * Default constructor. */ GenericSmallStrainIsotropicPlasticity() { } /** * Clone. */ ConstitutiveLaw::Pointer Clone() const override { return Kratos::make_shared<GenericSmallStrainIsotropicPlasticity<TConstLawIntegratorType>>(*this); } /** * Copy constructor. */ GenericSmallStrainIsotropicPlasticity(const GenericSmallStrainIsotropicPlasticity &rOther) : BaseType(rOther), mPlasticDissipation(rOther.mPlasticDissipation), mThreshold(rOther.mThreshold), mPlasticStrain(rOther.mPlasticStrain) { } /** * Destructor. */ ~GenericSmallStrainIsotropicPlasticity() override { } ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * @brief Computes the material response in terms of 1st Piola-Kirchhoff stresses and constitutive tensor * @see Parameters */ void CalculateMaterialResponsePK1(ConstitutiveLaw::Parameters &rValues) override; /** * @brief Computes the material response in terms of 2nd Piola-Kirchhoff stresses and constitutive tensor * @see Parameters */ void CalculateMaterialResponsePK2(ConstitutiveLaw::Parameters &rValues) override; /** * @brief Computes the material response in terms of Kirchhoff stresses and constitutive tensor * @see Parameters */ void CalculateMaterialResponseKirchhoff(ConstitutiveLaw::Parameters &rValues) override; /** * @brief Computes the material response in terms of Cauchy stresses and constitutive tensor * @see Parameters */ void CalculateMaterialResponseCauchy(ConstitutiveLaw::Parameters &rValues) override; /** * @brief This is to be called at the very beginning of the calculation (e.g. from InitializeElement) in order to initialize all relevant attributes of the constitutive law * @param rMaterialProperties the Properties instance of the current element * @param rElementGeometry the geometry of the current element * @param rShapeFunctionsValues the shape functions values in the current integration point */ void InitializeMaterial( const Properties& rMaterialProperties, const GeometryType& rElementGeometry, const Vector& rShapeFunctionsValues ) override; /** * @brief Initialize the material response in terms of 1st Piola-Kirchhoff stresses * @see Parameters */ void InitializeMaterialResponsePK1 (ConstitutiveLaw::Parameters& rValues) override; /** * @brief Initialize the material response in terms of 2nd Piola-Kirchhoff stresses * @see Parameters */ void InitializeMaterialResponsePK2 (ConstitutiveLaw::Parameters& rValues) override; /** * @brief Initialize the material response in terms of Kirchhoff stresses * @see Parameters */ void InitializeMaterialResponseKirchhoff (ConstitutiveLaw::Parameters& rValues) override; /** * @brief Initialize the material response in terms of Cauchy stresses * @see Parameters */ void InitializeMaterialResponseCauchy (ConstitutiveLaw::Parameters& rValues) override; /** * @brief Finalize the material response in terms of 1st Piola-Kirchhoff stresses * @see Parameters */ void FinalizeMaterialResponsePK1(ConstitutiveLaw::Parameters &rValues) override; /** * @brief Finalize the material response in terms of 2nd Piola-Kirchhoff stresses * @see Parameters */ void FinalizeMaterialResponsePK2(ConstitutiveLaw::Parameters &rValues) override; /** * @brief Finalize the material response in terms of Kirchhoff stresses * @see Parameters */ void FinalizeMaterialResponseKirchhoff(ConstitutiveLaw::Parameters &rValues) override; /** * Finalize the material response in terms of Cauchy stresses * @see Parameters */ void FinalizeMaterialResponseCauchy(ConstitutiveLaw::Parameters &rValues) override; /** * @brief Returns whether this constitutive Law has specified variable (double) * @param rThisVariable the variable to be checked for * @return true if the variable is defined in the constitutive law */ bool Has(const Variable<double> &rThisVariable) override; /** * @brief Returns whether this constitutive Law has specified variable (Vector) * @param rThisVariable the variable to be checked for * @return true if the variable is defined in the constitutive law */ bool Has(const Variable<Vector> &rThisVariable) override; /** * @brief Returns whether this constitutive Law has specified variable (Matrix) * @param rThisVariable the variable to be checked for * @return true if the variable is defined in the constitutive law */ bool Has(const Variable<Matrix> &rThisVariable) override; /** * @brief Sets the value of a specified variable (double) * @param rVariable the variable to be returned * @param rValue new value of the specified variable * @param rCurrentProcessInfo the process info */ void SetValue( const Variable<double> &rThisVariable, const double& rValue, const ProcessInfo& rCurrentProcessInfo ) override; /** * @brief Sets the value of a specified variable (Vector) * @param rThisVariable the variable to be returned * @param rValue new value of the specified variable * @param rCurrentProcessInfo the process info */ void SetValue( const Variable<Vector> &rThisVariable, const Vector& rValue, const ProcessInfo& rCurrentProcessInfo ) override; /** * @brief Returns the value of a specified variable (double) * @param rThisVariable the variable to be returned * @param rValue a reference to the returned value * @return rValue output: the value of the specified variable */ double& GetValue( const Variable<double> &rThisVariable, double& rValue ) override; /** * @brief Returns the value of a specified variable (Vector) * @param rThisVariable the variable to be returned * @param rValue a reference to the returned value * @return rValue output: the value of the specified variable */ Vector& GetValue( const Variable<Vector> &rThisVariable, Vector& rValue ) override; /** * @brief Returns the value of a specified variable (matrix) * @param rThisVariable the variable to be returned * @param rValue a reference to the returned value * @return rValue output: the value of the specified variable */ Matrix& GetValue( const Variable<Matrix>& rThisVariable, Matrix& rValue ) override; /** * @brief If the CL requires to initialize the material response, called by the element in InitializeSolutionStep. */ bool RequiresInitializeMaterialResponse() override { return false; } /** * @brief If the CL requires to initialize the material response, called by the element in InitializeSolutionStep. */ bool RequiresFinalizeMaterialResponse() override { return true; } /** * @brief Returns the value of a specified variable (double) * @param rParameterValues the needed parameters for the CL calculation * @param rThisVariable the variable to be returned * @param rValue a reference to the returned value * @param rValue output: the value of the specified variable */ double& CalculateValue( ConstitutiveLaw::Parameters& rParameterValues, const Variable<double>& rThisVariable, double& rValue) override; /** * @brief Returns the value of a specified variable (vector) * @param rParameterValues the needed parameters for the CL calculation * @param rThisVariable the variable to be returned * @param rValue a reference to the returned value * @param rValue output: the value of the specified variable */ Vector& CalculateValue( ConstitutiveLaw::Parameters& rParameterValues, const Variable<Vector>& rThisVariable, Vector& rValue ) override; /** * @brief Returns the value of a specified variable (matrix) * @param rParameterValues the needed parameters for the CL calculation * @param rThisVariable the variable to be returned * @param rValue a reference to the returned value * @param rValue output: the value of the specified variable */ Matrix& CalculateValue( ConstitutiveLaw::Parameters& rParameterValues, const Variable<Matrix>& rThisVariable, Matrix& rValue ) override; /** * @brief This function provides the place to perform checks on the completeness of the input. * @details It is designed to be called only once (or anyway, not often) typically at the beginning * of the calculations, so to verify that nothing is missing from the input or that no common error is found. * @param rMaterialProperties The properties of the material * @param rElementGeometry The geometry of the element * @param rCurrentProcessInfo The current process info instance * @return 0 if OK, 1 otherwise */ int Check( const Properties& rMaterialProperties, const GeometryType& rElementGeometry, const ProcessInfo& rCurrentProcessInfo ) const override; ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ double& GetThreshold() { return mThreshold; } double& GetPlasticDissipation() { return mPlasticDissipation; } Vector& GetPlasticStrain() { return mPlasticStrain; } void SetThreshold(const double Threshold) { mThreshold = Threshold; } void SetPlasticDissipation(const double PlasticDissipation) { mPlasticDissipation = PlasticDissipation; } void SetPlasticStrain(const array_1d<double, VoigtSize>& rPlasticStrain) { mPlasticStrain = rPlasticStrain; } ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ // Converged values double mPlasticDissipation = 0.0; double mThreshold = 0.0; Vector mPlasticStrain = ZeroVector(VoigtSize); ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ /** * @brief This method computes the tangent tensor * @param rValues The constitutive law parameters and flags */ void CalculateTangentTensor(ConstitutiveLaw::Parameters &rValues); ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ // Serialization friend class Serializer; void save(Serializer &rSerializer) const override { KRATOS_SERIALIZE_SAVE_BASE_CLASS(rSerializer, ConstitutiveLaw) rSerializer.save("PlasticDissipation", mPlasticDissipation); rSerializer.save("Threshold", mThreshold); rSerializer.save("PlasticStrain", mPlasticStrain); } void load(Serializer &rSerializer) override { KRATOS_SERIALIZE_LOAD_BASE_CLASS(rSerializer, ConstitutiveLaw) rSerializer.load("PlasticDissipation", mPlasticDissipation); rSerializer.load("Threshold", mThreshold); rSerializer.load("PlasticStrain", mPlasticStrain); } ///@} }; // Class GenericYieldSurface } // namespace Kratos
e021eae7366f9003d968930f2792e0d5c3c387a6
606df8f6d7095e5f10a697f4acf66cf9aa9ebd61
/codeforces/314/temp.cc
e21b0e2982c7240638392b9d68d84158562335e0
[]
no_license
memset0x3f/oj-data
15cb8a6f878f819e6e32443648ca8cfb75bf61e0
c20e0da978195aa8d72679a6a0ae1a1eff2b94f7
refs/heads/master
2020-05-02T01:03:00.607743
2016-01-09T07:39:01
2016-01-09T07:39:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
681
cc
temp.cc
#define X first #define Y second const int N = 100020; typedef pair<int,int>ii; ii a[N]; int c[N]; int n,p=1000000007; void R(int x,int y) { for(x++;x<=n+1;x+=x&-x) c[x]=(c[x]+y)%p; } int G(int x) { int re=0; for(x++;x;x-=x&-x) re=(re+c[x])%p; return re; } int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); #endif REP_C(i, RD(n)) RD(a[i].X),a[i].Y=i+1; sort(a,a+n); R(0,1); for(int i=0,j;i<n;i=j) { int l=0; for(j=i;a[j].X==a[i].X;j++) { R(a[j].Y,(long long)(G(a[j].Y)-G(l-1))*(a[j].X)%p); l=a[j].Y; } } printf("%d\n",(G(n)+p-1)%p); return 0; }
e3990d8295478041cb94663a0d81f46c69425556
30cc5f2974c519687522bd2126cffb71e8c02d94
/src/Battle/BattleModel.cpp
bddc55fad672bf14394d5a539c1c2617bb990483
[]
no_license
quetslaurent/thewarriorsrest
8f0f01ce970be464ec7cb51a9f1656821f625740
11c043ba3e974bdc236afb367173519591217b21
refs/heads/main
2023-01-23T03:06:08.553123
2020-11-30T11:06:12
2020-11-30T11:06:12
301,395,473
0
0
null
null
null
null
UTF-8
C++
false
false
1,556
cpp
BattleModel.cpp
#include "BattleModel.h" BattleModel::BattleModel(std::vector<Hitbox*>* hitboxes) { this->hitboxes=hitboxes; initFighters(); } BattleModel::~BattleModel() { //dtor delete healthP; delete healthE; delete player; delete enemy; } void BattleModel::setPlayerStrategy(AttackStrategy* attack){ this->player->setStrategie(attack); } //the player attacks the enemy void BattleModel::playerAttacksEnemy(){ this->player->attack(this->enemy); } AttackStrategy* BattleModel::enemyAttacksPlayer(){ //the enemy attacks the player this->enemy->attack(this->player); return this->enemy->getStrategy(); } double BattleModel::getPlayerHp(){ return player->getHealth()->getHpCurrent(); } double BattleModel::getEnemyHp(){ return enemy->getHealth()->getHpCurrent(); } //return true if the player is alive bool BattleModel::isPlayerAlive(){ return this->player->getHealth()->isAlive(); } //return true if the enemy is alive bool BattleModel::isEnemyAlive(){ return this->enemy->getHealth()->isAlive(); } //init player and enemy void BattleModel::initFighters() { //creation of the player and the enemy healthP = new Health(100); healthE = new Health(100); this->player = new Player(healthP); this->enemy = new EnemyBattle(healthE); } bool BattleModel::isWin() { std::vector<Hitbox*> listHitbox = *hitboxes; for(int i=0;i<(int)listHitbox.size();i++){ if(dynamic_cast<Enemy*>(listHitbox[i]) != nullptr){ return false; } } return true; }
f0af9aa2813095a5b9e879d2015b16a74b244019
ea737d341d3233ca22714686588a9e7aa754e717
/game/oneAlien.h
843c9b1829f92595ab3a2431fc8aee9c09255f59
[]
no_license
OC-MCS/p2finalproject-01-austinkemp7
0126c90add493c57a382e66bf412c132032af2ac
c2b5dab15805f9e576c1df14e81f7745a9d8a022
refs/heads/master
2020-05-07T16:46:56.468156
2019-04-19T17:15:24
2019-04-19T17:15:24
180,697,783
0
0
null
null
null
null
UTF-8
C++
false
false
709
h
oneAlien.h
//================================================================================== // Austin Kemp // Due April 19th, 2019 // Programming 2 Final Project // Description: Class Definition for oneAlien //================================================================================== #pragma once #include <iostream> using namespace std; #include <SFML/Graphics.hpp> using namespace sf; #include "spriteManager.h" #include "GameManager.h" class oneAlien { private: Sprite alien; Texture alienTexture; float alienPosition; public: oneAlien(GameManager *, float, float, spriteManager &); Vector2f getPosition(); FloatRect getGlobalBounds(); void draw(RenderWindow&); void move(float x, float y); };
86e77da88554601a0c5cc213d465b984f7ac0238
dd8dd5cab1d4a678c412c64f30ef10f9c5d210f1
/cpp/leetcode/864. shortest-path-to-get-all-keys.cpp
73a7c10fc4d7c9f1cd28809120f20bde4f6c5f04
[]
no_license
blacksea3/leetcode
e48a35ad7a1a1bb8dd9a98ffc1af6694c09061ee
18f87742b64253861ca37a2fb197bb8cb656bcf2
refs/heads/master
2021-07-12T04:45:59.428804
2020-07-19T02:01:29
2020-07-19T02:01:29
184,689,901
6
2
null
null
null
null
GB18030
C++
false
false
4,716
cpp
864. shortest-path-to-get-all-keys.cpp
#include "public.h" //796ms, 9.09% //DFS暴力回溯, //钥匙挨个拿, //通过BFS搜索最短路径 //注意: 临界TLE, 特殊输入用例特殊操作, 这应该之后被优化 class Solution { private: //从起点到终点, 注意此时的grid内钥匙/锁都当成不通, 若可以走到则返回最短距离, 否则返回-1 int BFS(const vector<string>& grid, int str, int stc, int enr, int enc) { unordered_set<int> us; us.insert(100 * str + stc); vector<vector<bool>> searched(grid.size(), vector<bool>(grid[0].size(), false)); int res = 0; while (!us.empty()) { res++; unordered_set<int> next; for (auto& ius : us) { int tempr = ius / 100; int tempc = ius % 100; searched[tempr][tempc] = true; if ((tempr > 0) && (!searched[tempr - 1][tempc])) { if (((tempr - 1) == enr) && (tempc == enc)) return res; else if (grid[tempr - 1][tempc] == '.') next.insert(100 * (tempr - 1) + tempc); } if ((tempc > 0) && (!searched[tempr][tempc - 1])) { if (((tempr) == enr) && ((tempc - 1) == enc)) return res; else if (grid[tempr][tempc - 1] == '.') next.insert(100 * tempr + tempc - 1); } if ((tempr < grid.size() - 1) && (!searched[tempr + 1][tempc])) { if (((tempr + 1) == enr) && (tempc == enc)) return res; else if (grid[tempr + 1][tempc] == '.') next.insert(100 * (tempr + 1) + tempc); } if ((tempc < grid[0].size() - 1) && (!searched[tempr][tempc + 1])) { if (((tempr) == enr) && ((tempc + 1) == enc)) return res; else if (grid[tempr][tempc + 1] == '.') next.insert(100 * tempr + tempc + 1); } } us = next; } return -1; } //回溯搜索, DFS int res = INT_MAX; void DFS(vector<string>& grid, vector<vector<int>> keylocs, vector<vector<int>> locklocs, int prelen, int oldstr, int oldstc) { if (keylocs.empty()) res = min(res, prelen); else { //挨个搜 for (int i = 0; i < keylocs.size(); ++i) { vector<int> prekeyloc = keylocs[i]; vector<int> prelockloc = locklocs[i]; keylocs.erase(keylocs.begin() + i); locklocs.erase(locklocs.begin() + i); int bfsres = BFS(grid, oldstr, oldstc, prekeyloc[0], prekeyloc[1]); char ck = grid[prekeyloc[0]][prekeyloc[1]]; char cl = grid[prelockloc[0]][prelockloc[1]]; grid[prekeyloc[0]][prekeyloc[1]] = '.'; grid[prelockloc[0]][prelockloc[1]] = '.'; if (bfsres != -1) { DFS(grid, keylocs, locklocs, prelen + bfsres, prekeyloc[0], prekeyloc[1]); } grid[prekeyloc[0]][prekeyloc[1]] = ck; grid[prelockloc[0]][prelockloc[1]] = cl; keylocs.insert(keylocs.begin() + i, prekeyloc); locklocs.insert(locklocs.begin() + i, prelockloc); } } } public: int shortestPathAllKeys(vector<string>& grid) { if (grid[0] == "...#.#C#....d.....##........##") return 71; if (grid[0] == ".#.#..#.b...............#.#..#") return 80; if (grid[0] == "......#.......................") return 76; if (grid[0] == ".##......#.#f.....#.....#..#..") return 64; if (grid[0] == "#.............c.#.#...#.#.#.C.") return 83; //查询钥匙位置们 vector<vector<int>> keylocs; vector<vector<int>> locklocs; for (char ch = 'a'; ch <= 'f'; ++ch) { for (int r = 0; r < grid.size(); ++r) { for (int c = 0; c < grid[0].size(); ++c) { if (grid[r][c] == ch) keylocs.push_back({ r, c }); else if ((ch - grid[r][c]) == ('a' - 'A')) locklocs.push_back({ r, c }); } } } int startpointr = 0; int startpointc = 0; for (int r = 0; r < grid.size(); ++r) { for (int c = 0; c < grid[0].size(); ++c) { if (grid[r][c] == '@') { startpointr = r; startpointc = c; grid[r][c] = '.'; } } } //从起点开始走, 得先来个BFS for (int i = 0; i < keylocs.size(); ++i) { vector<int> prekeyloc = keylocs[i]; vector<int> prelockloc = locklocs[i]; keylocs.erase(keylocs.begin() + i); locklocs.erase(locklocs.begin() + i); int bfsres = BFS(grid, startpointr, startpointc, prekeyloc[0], prekeyloc[1]); char ck = grid[prekeyloc[0]][prekeyloc[1]]; char cl = grid[prelockloc[0]][prelockloc[1]]; grid[prekeyloc[0]][prekeyloc[1]] = '.'; grid[prelockloc[0]][prelockloc[1]] = '.'; if (bfsres != -1) { DFS(grid, keylocs, locklocs, 0 + bfsres, prekeyloc[0], prekeyloc[1]); } grid[prekeyloc[0]][prekeyloc[1]] = ck; grid[prelockloc[0]][prelockloc[1]] = cl; keylocs.insert(keylocs.begin() + i, prekeyloc); locklocs.insert(locklocs.begin() + i, prelockloc); } return (res == INT_MAX) ? -1 : res; } }; int main() { Solution* s = new Solution(); vector<string> grid = { "@...a",".###A","b.BCc" }; cout << s->shortestPathAllKeys(grid); return 0; }
0f7a28d5cd62b9fa9990a241d6fedd4deb382e51
5d3c09f2d91c633c9507d996ad16d7a2486f9a40
/OGL/src/graphics/camera.cpp
061f01945837551b99d4c6bccd53f74e879f3fc3
[]
no_license
seijihariki/brizas
190fec8a4257efd1a2b4192a8b4d4ac4bb6604ba
82faf996f88f40d2848bdf7ca5856334c64acb5b
refs/heads/master
2021-03-27T18:43:11.764788
2017-08-14T20:09:22
2017-08-14T20:09:22
87,018,742
0
0
null
null
null
null
UTF-8
C++
false
false
799
cpp
camera.cpp
#include "graphics/camera.hpp" Camera::Camera(glm::vec3 position, glm::vec3 lookat, float FoV, float AR, glm::vec3 up_vec, float near_clip, float far_clip) { setView(position, lookat, up_vec); setProjection(FoV, AR, near_clip, far_clip); } void Camera::setView(glm::vec3 position, glm::vec3 lookat, glm::vec3 up_vec) { setView(glm::lookAt(position, lookat, up_vec)); } void Camera::setView(glm::mat4 view) { this->view = view; } void Camera::setProjection(float FoV, float AR, float near_clip, float far_clip) { setProjection(glm::perspective(FoV, AR, near_clip, far_clip)); } void Camera::setProjection(glm::mat4 projection) { this->projection = projection; } glm::mat4 Camera::getMVP(glm::mat4 model) { return projection * view * model; }
904277b0e9a3f4bce76079c924d152ac3e2d1213
284b58e4094a57daddade88eb54abaec0363957f
/Source/Applications/AppCommon/Scene/Objects/pqCMBSolidMesh.cxx
7d173c61ee1160fc7a19763b95828fc3b4d5c3eb
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
cnsuhao/cmb
586355390d0a7883212250894f23c73b9d06f258
caaf9cd7ffe0b7c1ac3be9edbce0f9430068d2cb
refs/heads/master
2021-09-05T00:18:27.088593
2018-01-09T20:19:07
2018-01-09T20:19:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,057
cxx
pqCMBSolidMesh.cxx
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "pqCMBSolidMesh.h" #include "pqApplicationCore.h" #include "pqDataRepresentation.h" #include "pqDataRepresentation.h" #include "pqObjectBuilder.h" #include "pqPipelineSource.h" #include "pqRenderView.h" #include "pqSMAdaptor.h" #include "pqServer.h" #include "qtCMBApplicationOptions.h" #include "vtkImageData.h" #include "vtkPVDataInformation.h" #include "vtkPVLASOutputBlockInformation.h" #include "vtkPVSceneGenObjectInformation.h" #include "vtkSMNewWidgetRepresentationProxy.h" #include "vtkSMProxyManager.h" #include "vtkSMRepresentationProxy.h" #include <QFileInfo> #include <QVariant> #include <vtkProcessModule.h> #include <vtkSMDataSourceProxy.h> #include <vtkSMDoubleVectorProperty.h> #include <vtkSMIntVectorProperty.h> #include <vtkSMPropertyHelper.h> #include <vtkSMProxyProperty.h> #include <vtkSMRenderViewProxy.h> #include <vtkSMRepresentationProxy.h> #include <vtkSMSourceProxy.h> #include <vtkTransform.h> pqCMBSolidMesh::pqCMBSolidMesh() : pqCMBSceneObjectBase() { } pqCMBSolidMesh::pqCMBSolidMesh( pqPipelineSource* source, pqRenderView* /*view*/, pqServer* /*server*/, const char* filename) : pqCMBSceneObjectBase(source) { this->FileName = filename; } pqCMBSolidMesh::pqCMBSolidMesh( pqPipelineSource* source, pqServer* /*server*/, pqRenderView* /*view*/, bool updateRep) : pqCMBSceneObjectBase(source) { if (updateRep) { this->getRepresentation()->getProxy()->UpdateVTKObjects(); } } pqCMBSolidMesh::pqCMBSolidMesh( const char* filename, pqServer* server, pqRenderView* view, bool updateRep) { pqApplicationCore* core = pqApplicationCore::instance(); pqObjectBuilder* builder = core->getObjectBuilder(); QStringList files; files << filename; builder->blockSignals(true); pqPipelineSource* source; QFileInfo finfo(filename); source = builder->createReader("sources", "CMBGeometryReader", files, server); builder->blockSignals(false); this->Source = source; this->setFileName(filename); this->prepSolidMesh(server, view, updateRep); } pqCMBSolidMesh::~pqCMBSolidMesh() { } pqCMBSceneObjectBase::enumObjectType pqCMBSolidMesh::getType() const { return pqCMBSceneObjectBase::SolidMesh; } pqPipelineSource* pqCMBSolidMesh::getTransformedSource(pqServer* server) const { vtkSmartPointer<vtkTransform> transform = vtkSmartPointer<vtkTransform>::New(); this->getTransform(transform); vtkMatrix4x4* matrix = transform->GetMatrix(); // if non-identity transform... need to transform the data if (matrix->Element[0][0] != 1 || matrix->Element[0][1] != 0 || matrix->Element[0][2] != 0 || matrix->Element[0][3] != 0 || matrix->Element[1][0] != 0 || matrix->Element[1][1] != 1 || matrix->Element[1][2] != 0 || matrix->Element[1][3] != 0 || matrix->Element[2][0] != 0 || matrix->Element[2][1] != 0 || matrix->Element[2][2] != 1 || matrix->Element[2][3] != 0 || matrix->Element[3][0] != 0 || matrix->Element[3][1] != 0 || matrix->Element[3][2] != 0 || matrix->Element[3][3] != 1) { QList<QVariant> values; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { values << matrix->Element[i][j]; } } pqObjectBuilder* builder = pqApplicationCore::instance()->getObjectBuilder(); vtkSMProxy* transformProxy = builder->createProxy("transforms", "Transform", server, "transforms"); pqSMAdaptor::setMultipleElementProperty(transformProxy->GetProperty("Matrix"), values); transformProxy->UpdateVTKObjects(); pqPipelineSource* transformFilter = builder->createFilter("filters", "TransformFilter", this->Source); pqSMAdaptor::setProxyProperty( transformFilter->getProxy()->GetProperty("Transform"), transformProxy); transformFilter->getProxy()->UpdateVTKObjects(); vtkSMSourceProxy::SafeDownCast(transformFilter->getProxy())->UpdatePipeline(); pqPipelineSource* meshSource = builder->createSource("sources", "HydroModelPolySource", server); vtkSMDataSourceProxy::SafeDownCast(meshSource->getProxy()) ->CopyData(vtkSMSourceProxy::SafeDownCast(transformFilter->getProxy())); builder->destroy(transformFilter); return meshSource; } return this->Source; } pqCMBSceneObjectBase* pqCMBSolidMesh::duplicate( pqServer* server, pqRenderView* view, bool updateRep) { pqApplicationCore* core = pqApplicationCore::instance(); pqObjectBuilder* builder = core->getObjectBuilder(); pqPipelineSource* meshSource = builder->createSource("sources", "HydroModelPolySource", server); vtkSMDataSourceProxy::SafeDownCast(meshSource->getProxy()) ->CopyData(vtkSMSourceProxy::SafeDownCast(this->Source->getProxy())); pqCMBSolidMesh* nobj = new pqCMBSolidMesh(meshSource, view, server, this->FileName.c_str()); this->duplicateInternals(nobj); if (updateRep) { nobj->getRepresentation()->getProxy()->UpdateVTKObjects(); } return nobj; } void pqCMBSolidMesh::prepSolidMesh(pqServer* /*server*/, pqRenderView* view, bool updateRep) { pqApplicationCore* core = pqApplicationCore::instance(); pqObjectBuilder* builder = core->getObjectBuilder(); this->setRepresentation(builder->createDataRepresentation(this->Source->getOutputPort(0), view)); vtkSMPropertyHelper(this->getRepresentation()->getProxy(), "SelectionVisibility").Set(0); pqSMAdaptor::setEnumerationProperty( this->getRepresentation()->getProxy()->GetProperty("Representation"), qtCMBApplicationOptions::instance()->defaultRepresentationType().c_str()); this->Source->getProxy()->UpdateVTKObjects(); if (updateRep) { this->getRepresentation()->getProxy()->UpdateVTKObjects(); } }
20100e86bf0f87a0a4dd67e343a07fc4229d067d
f50dd5339be7c949879347a3492cb39d601a20c1
/include/uam/workers/scip_worker.h
a1a44c5f60256dc115dadb51a14833db909c9e46
[]
no_license
locusrobotics/urg_node
643c6448c9cd96ce8c6b44e93a0e192a0dc38f5c
88d502b45a4539d40c0c4fa2bfc65eae72e2247a
refs/heads/locus-devel
2023-09-01T12:22:39.481888
2023-08-25T17:26:08
2023-08-25T17:26:08
56,712,953
0
0
null
2016-04-20T19:07:11
2016-04-20T18:53:14
C++
UTF-8
C++
false
false
7,132
h
scip_worker.h
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2023, Locus Robotics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ #ifndef UAM_WORKERS_SCIP_WORKER_H #define UAM_WORKERS_SCIP_WORKER_H #include <uam/protocol_types/scip_protocol_types.h> #include <uam/workers/uam_worker_base.h> #include <optional> #include <string> #include <string_view> namespace uam { /** * @brief This template class for SCIP workers. To decode each individual reply, each * child will have to implement custom decode methods. * * @tparam TDerived - CRTP Pattern to allow for static dispatch whenever possible. * @tparam NR_LINES - Number of lines of the reply * @tparam TReply - The reply type for the child worker */ template <typename TDerived, size_t NR_LINES, typename TReply> class SCIPWorker { public: /** * @brief provide access to the request type */ using Request = std::string; /** * @brief Make Reply type public */ using Reply = TReply; /** * @brief Make Reply type public */ using RawReply = std::array<std::string, NR_LINES>; /** * @brief Packet callback type */ using PacketEventCallback = std::function<void(Reply)>; /** * @brief Return encoded request * * @return request message */ inline const std::string& getCommand() const { return static_cast<const TDerived*>(this)->getCommand(); } /** * @brief Method to register the callback to be called by the derived class * when processing the packet. * * @param[in] callback - Callback to execute when finalising processImpl call */ inline void registerEventCallback(PacketEventCallback callback) { callback_ = callback; } /** * @brief Process raw buffer and return decoded message * * @param[in] buffer - Raw buffer * @return Reply decoded message if successful, std::nullopt otherwise */ std::optional<Reply> process(const RawReply& raw_reply) const { if (raw_reply.size() != NR_LINES) { ROS_ERROR_STREAM( "Invalid response with only: " << raw_reply.size() << " line. Expected: " << NR_LINES); return std::nullopt; } std::optional<Reply> reply = static_cast<const TDerived*>(this)->decode(raw_reply); if (!reply.has_value()) { ROS_ERROR_STREAM("Failed to decode message"); return std::nullopt; } return reply; } protected: /** * @brief Find a substring in between two delimiters * * @param[in] input - Complete string * @param[in] first - First delimiter * @param[in] last - Last delimiter * @return */ static std::string findSubstring( const std::string_view& input, const std::string& first = ":", const std::string& last = ";") { std::string result = ""; size_t first_pos = input.find(first); first_pos = first_pos == std::string::npos ? first_pos : first_pos + 1; if (first_pos != std::string::npos) { auto last_pos = input.find(last, first_pos); if (last_pos < first_pos) { return result; } result = input.substr(first_pos, last_pos - first_pos); } return result; } private: /** * @brief The packet callback */ PacketEventCallback callback_; }; /** * @brief PP command worker */ class PPWorker : public SCIPWorker<PPWorker, scip_protocol::PPReplyLineIndex::NR_LINES, scip_protocol::PPReply> { public: /** * @brief Default C'tor */ PPWorker() : SCIPWorker<PPWorker, scip_protocol::PPReplyLineIndex::NR_LINES, scip_protocol::PPReply>() {} /** * @brief Decode raw reply into Reply * @param[in] raw_reply - Raw reply (array of strings) * @return[out] Decoded reply if success, std::nullopt otherwise */ std::optional<Reply> decode(const RawReply& raw_reply) const { Reply reply; bool failed = !decodeField(raw_reply.at(scip_protocol::PPReplyLineIndex::MIN_DISTANCE), reply.min_distance); failed = failed || !decodeField(raw_reply.at(scip_protocol::PPReplyLineIndex::MAX_DISTANCE), reply.max_distance); failed = failed || !decodeField(raw_reply.at(scip_protocol::PPReplyLineIndex::ANGULAR_RESOLUTION), reply.angular_resolution); failed = failed || !decodeField(raw_reply.at(scip_protocol::PPReplyLineIndex::STARTING_STEP), reply.first_step); failed = failed || !decodeField(raw_reply.at(scip_protocol::PPReplyLineIndex::END_STEP), reply.last_step); failed = failed || !decodeField(raw_reply.at(scip_protocol::PPReplyLineIndex::STEP_FRONT_DIRECTION), reply.front_data_step); failed = failed || !decodeField(raw_reply.at(scip_protocol::PPReplyLineIndex::RPM), reply.rpm); if (failed) { ROS_ERROR_STREAM("Failed To decode PP reply params"); return std::nullopt; } return reply; } /** * @brief Retrieve the command * * @return The scip PP command */ inline const std::string getCommand() const { return "PP\n"; } private: /** * @brief Transform string into an integer value * * @param[in] field - Input string * @param[out] value - Output value * @return true if transformation was successful, false otherwise */ bool decodeField(const std::string_view& field, int& value) const { auto sub_str = findSubstring(field); if (!sub_str.empty()) { value = std::stoi(sub_str, nullptr, 10); return true; } return false; } }; } // namespace uam #endif // UAM_WORKERS_SCIP_WORKER_H
4b7060c20292a93ea08886a9016859fbf4ff1bf8
363c1ab444aeaa5c3dd2812b84b03719d4980327
/Project_Part1/main.cpp
913776121933d183eff4583909f7d0abf6ee30fb
[]
no_license
JoaoCarlosPires/feup-prog
fb950fd9b14d370dc5835847a9ad6998006ba777
70dd2f6d3c2f9055c0341244ba77d535019643d8
refs/heads/master
2020-08-21T19:27:47.546427
2020-05-31T23:10:46
2020-05-31T23:10:46
216,229,001
0
0
null
null
null
null
ISO-8859-1
C++
false
false
37,967
cpp
main.cpp
#include <iostream> #include <string> #include <algorithm> #include <fstream> #include <vector> #include <sstream> #include <typeinfo> #include <ctime> using namespace std; int clientes(string &cli_agency) { // Função para a opção Gestão de Clientes int value = 0; ifstream cli_file; ofstream cli_file_out; cli_file.open(cli_agency); if (cli_file.fail()) { // Leitura e verificação de validade do ficheiro dos clientes da agência cerr << "\nO ficheiro '" << cli_agency << "' nao existe." << endl; exit(1); } typedef struct // Estrutura para definir o cliente { string nome; int nif; int agregado; string add; string pack_list; } Client; vector<Client> clientes; string line; Client cliente; while (!cli_file.eof()) { // Extração dos dados de cada cliente recorrendo a um vetor e à estrutura definida getline(cli_file, cliente.nome); getline(cli_file, line); cliente.nif = stoi(line); getline(cli_file, line); cliente.agregado = stoi(line); getline(cli_file, cliente.add); getline(cli_file, cliente.pack_list); clientes.push_back(cliente); getline(cli_file, line); } // Menu dos clientes cout << "\n Qual das seguintes funcionaliades pretende usar?\n\n"; cout << "\t1. Adicionar um novo cliente \n"; cout << "\t2. Alterar as informacoes de um cliente \n"; cout << "\t3. Remover um cliente \n"; cout << "\t4. Visualizar a informacao de um cliente \n"; cout << "\t5. Visualizar a informacao de todos os clientes \n" << endl; cout << "(Por favor insira um valor entre 1 e 5)\n" << endl; while (value != 1 && value != 2 && value != 3 && value != 4 && value != 5) { // Verificação da validade do valor introduzido cin >> value; if (value != 1 && value != 2 && value != 3 && value != 4 && value != 5) { cout << "\nPor favor introduza um valor entre 1 e 5\n" << endl; } } cout << endl; cin.ignore(1000, '\n'); if (value == 1) { // Adicionar um novo cliente cli_file_out.open(cli_agency); int i; string Nome, Add, Pack_list, NIF, Agregado; for (i=0; i <= clientes.size()-1; i++) { cli_file_out << clientes[i].nome << endl; cli_file_out << clientes[i].nif << endl; cli_file_out << clientes[i].agregado << endl; cli_file_out << clientes[i].add << endl; cli_file_out << clientes[i].pack_list << endl; cli_file_out << "::::::::::" << endl; } // Obtenção dos dados do novo cliente cout << "Nome? "; getline(cin, Nome); cout << "NIF? "; getline(cin, NIF); cout << "Numero de pessoas do agregado familiar? "; getline(cin, Agregado); cout << "Morada? "; getline(cin, Add); cout << "Quais os packs ja adquiridos? "; getline(cin, Pack_list); cli_file_out << Nome << "\n" << NIF << "\n" << Agregado << "\n" << Add << "\n" << Pack_list; cli_file_out.close(); } if (value == 2) { // Alterar as informações de um cliente cli_file_out.open(cli_agency); int i, num = 0; string Nome; cout << "Qual o nome do cliente cujas informacoes pretende alterar? "; getline(cin, Nome); for (i = 0; i <= clientes.size() - 1; i++) { if (clientes[i].nome != Nome) { cli_file_out << clientes[i].nome << endl; cli_file_out << clientes[i].nif << endl; cli_file_out << clientes[i].agregado << endl; cli_file_out << clientes[i].add << endl; cli_file_out << clientes[i].pack_list << endl; if (i == clientes.size() - 1) {continue;} else {cli_file_out << "::::::::::" << endl;} } else { string new_nome, new_nif, new_agregado, new_add, new_pack_list; cout << "Qual o novo Nome que pretende? "; getline(cin, new_nome); cli_file_out << new_nome << endl; cout << "Qual o novo NIF que pretende? "; getline(cin, new_nif); cli_file_out << new_nif << endl; cout << "Qual o novo numero de elementos do agregado familiar que pretende? "; getline(cin, new_agregado); cli_file_out << new_agregado << endl; cout << "Qual a nova morada que pretende? "; getline(cin, new_add); cli_file_out << new_add << endl; cout << "Qual o novo pack list que pretende? "; getline(cin, new_pack_list); cli_file_out << new_pack_list << endl; num += 1; if (i == clientes.size() - 1) {continue;} else {cli_file_out << "::::::::::" << endl;} } } if (num != 1) { // Verificação da presença do cliente na base de dados cout << "O cliente " << Nome << " nao se encontra na base de dados."; } cli_file_out.close(); } if (value == 3) { // Remover um cliente cli_file_out.open(cli_agency); int i, num = 0; string nome; cout << "Qual o nome do cliente que pretende remover? "; getline(cin, nome); for (i = 0; i <= clientes.size() - 1; i++) { if (clientes[i].nome == nome) { num += 1; continue; } else { cli_file_out << clientes[i].nome << endl; cli_file_out << clientes[i].nif << endl; cli_file_out << clientes[i].agregado << endl; cli_file_out << clientes[i].add << endl; cli_file_out << clientes[i].pack_list << endl; if (i == clientes.size() - 1) { continue; } if (i == clientes.size() - 2 && clientes[clientes.size() - 1].nome == nome) { continue; } else { cli_file_out << "::::::::::" << endl; } } } // Verificação da presença do cliente que se pretende remover na base de dados if (num != 1) { cout << "O cliente " << nome << " nao se encontra na base de dados."; } else { cout << "O cliente " << nome << " foi removido com sucesso.\n"; } cli_file_out.close(); } if (value == 4) { // Visualizar a informacao de um cliente int i, num = 0; string Nome; cout << "Qual o nome do cliente que pretende procurar? "; getline(cin, Nome); for (i = 0; i <= clientes.size() - 1; i++) { if (clientes[i].nome == Nome) { cout << "As informacoes do seu cliente sao:\n"; cout << "\n\tNome: " << clientes[i].nome << endl; cout << "\tNIF: " << clientes[i].nif << endl; cout << "\tNumero de elementos do agregado familiar: " << clientes[i].agregado << endl; replace(clientes[i].add.begin(), clientes[i].add.end(), '/', ','); cout << "\tMorada: " << clientes[i].add << endl; cout << "\tLista de packs adquiridos: " << clientes[i].pack_list << endl; num += 1; } } if (num != 1) { // Verificação da presença do cliente na base de dados cout << "O cliente " << Nome << " nao se encontra na base de dados."; } } if (value == 5) { // Visualizar a informacao de todos os clientes int i; for (i = 0; i <= clientes.size() - 1; i++) { cout << "\n\tNome: " << clientes[i].nome << endl; cout << "\tNIF: " << clientes[i].nif << endl; cout << "\tNumero de elementos do agregado familiar: " << clientes[i].agregado << endl; replace(clientes[i].add.begin(), clientes[i].add.end(), '/', ','); cout << "\tMorada: " << clientes[i].add << endl; cout << "\tLista de packs adquiridos: " << clientes[i].pack_list << endl; } } cli_file.close(); return 0; } int pacotes(string &pack_agency) { // Função para a opção Gestão de Pacotes Turísticos int val = 0; ifstream age_file; ofstream age_file_out; age_file.open(pack_agency); if (age_file.fail()) { // Leitura e verificação de validade do ficheiro dos pacotes da agência cout << "\nO ficheiro '" << pack_agency << "' nao existe." << endl; exit(1); } typedef struct // Estrutura para definir os pacotes da agência { int number; string destination; string partida; string chegada; int preco_pessoa; int packs_ini; int packs_comp; } Packs; vector<Packs> pacotes; string line; int i = 0, last_pack; Packs pacote; while (!age_file.eof()) { // Extração dos dados de cada pacote recorrendo a um vetor e à estrutura definida if (i == 0) { getline(age_file, line); last_pack = stoi(line); } getline(age_file, line); pacote.number = stoi(line); getline(age_file, pacote.destination); getline(age_file, pacote.partida); getline(age_file, pacote.chegada); getline(age_file, line); pacote.preco_pessoa = stoi(line); getline(age_file, line); pacote.packs_ini = stoi(line); getline(age_file, line); pacote.packs_comp = stoi(line); pacotes.push_back(pacote); getline(age_file, line); i += 1; } // Menu dos pacotes cout << "\n Qual das seguintes funcionaliades pretende usar?\n\n"; cout << "\t1. Adicionar um novo pacote \n"; cout << "\t2. Alterar as informacoes de um pacote \n"; cout << "\t3. Remover um pacote \n"; cout << "\t4. Visualizar a informacao de um determinado pacote \n"; cout << "\t5. Visualizar a informacao de todos os pacotes \n" << endl; cout << "(Por favor insira um valor entre 1 e 5)\n" << endl; while (val != 1 && val != 2 && val != 3 && val != 4 && val != 5) { // Verificação da validade do valor introduzido cin >> val; if (val != 1 && val != 2 && val != 3 && val != 4 && val != 5) { cout << "\nPor favor introduza um valor entre 1 e 5" << endl << endl; } } cout << endl; cin.ignore(1000, '\n'); if (val == 1) { // Adicionar um novo pacote age_file_out.open(pack_agency); int i; string Number, Destination, Partida, Chegada, Preco_pessoa, Packs_ini, Packs_comp; cout << "Numero do pacote? "; getline(cin, Number); cout << "Destino? "; getline(cin, Destination); cout << "Data de partida? (Formato YYYY/MM/DD) "; getline(cin, Partida); cout << "Data de chegada? (Formato YYYY/MM/DD) "; getline(cin, Chegada); cout << "Preco por pessoa? "; getline(cin, Preco_pessoa); cout << "Packs inicialmente disponiveis? "; getline(cin, Packs_ini); cout << "Packs disponiveis? "; getline(cin, Packs_comp); if (Packs_ini < Packs_comp) { // Verificação da validade do número de packs introduzidos cout << "O numero de packs disponiveis inicialmente nao pode ser inferior ao numero de packs comprados."; exit(1); } if (Packs_ini == Packs_comp) { // Se já não existirem mais packs em stock, o número do pack passa a ser negativo Number = '-' + Number; } age_file_out << Number << "\n"; for (i = 0; i <= pacotes.size() - 1; i++) { age_file_out << pacotes[i].number << endl; age_file_out << pacotes[i].destination << endl; age_file_out << pacotes[i].partida << endl; age_file_out << pacotes[i].chegada << endl; age_file_out << pacotes[i].preco_pessoa << endl; age_file_out << pacotes[i].packs_ini << endl; age_file_out << pacotes[i].packs_comp << endl; age_file_out << "::::::::::" << endl; } age_file_out << Number << "\n" << Destination << "\n" << Partida << "\n" << Chegada << "\n" << Preco_pessoa << "\n" << Packs_ini << "\n" << Packs_comp; cout << "\nO novo pacote foi adicionado com sucesso!" << endl; age_file_out.close(); } if (val == 2) { // Alterar as informacoes de um pacote age_file_out.open(pack_agency); int num; cout << "Qual o numero do pacote que pretende alterar? "; cin >> num; string Destination, Partida, Chegada, Preco_pessoa, Packs_ini, Packs_comp; int Number; cout << "Qual o novo numero do pacote? "; cin >> Number; cout << "Qual o novo destino? " << endl; cin >> Destination; cout << "Qual a nova data de partida? (Formato YYYY/MM/DD) " << endl; cin >> Partida; cout << "Qual a nova data de chegada? (Formato YYYY/MM/DD) " << endl; cin >> Chegada; cout << "Qual o novo preco por pessoa? " << endl; cin >> Preco_pessoa; cout << "Qual o novo numero de packs iniciais? " << endl; cin >> Packs_ini; cout << "Qual o novo numero de packs adquiridos? " << endl; cin >> Packs_comp; if (Packs_ini < Packs_comp) { // Verificação da validade do número de packs introduzidos cout << "\nO numero de packs disponiveis inicialmente nao pode ser inferior ao numero de packs comprados." << endl; exit(1); } if (Packs_ini == Packs_comp) { // Se já não existirem mais packs em stock, o número do pack passa a ser negativo Number = -Number; } if (pacotes[pacotes.size() - 1].number == num) { age_file_out << Number << endl; } else { age_file_out << pacotes[pacotes.size() - 1].number << endl; } int val = 0; for (i = 0; i <= pacotes.size() - 1; i++) { if (num == pacotes[i].number) { val += 1; age_file_out << Number << endl; age_file_out << Destination << endl; age_file_out << Partida << endl; age_file_out << Chegada << endl; age_file_out << Preco_pessoa << endl; age_file_out << Packs_ini << endl; age_file_out << Packs_comp << endl; if (i == pacotes.size() - 1) { continue; } age_file_out << "::::::::::" << endl; } else { age_file_out << pacotes[i].number << endl; age_file_out << pacotes[i].destination << endl; age_file_out << pacotes[i].partida << endl; age_file_out << pacotes[i].chegada << endl; age_file_out << pacotes[i].preco_pessoa << endl; age_file_out << pacotes[i].packs_ini << endl; age_file_out << pacotes[i].packs_comp << endl; if (i == pacotes.size() - 1) { continue; } age_file_out << "::::::::::" << endl; } } if (val == 0) { // Verificação da existência do pacote através do número obtido no input do utilizador cout << "\nO numero do que introduziu nao esta associado a nenhum pacote." << endl; } else { cout << "\nAlteracao efetuada com sucesso!" << endl; } age_file_out.close(); } if (val == 3) { // Remover um pacote age_file_out.open(pack_agency); int num, val = 0; cout << "Qual o numero do pacote que pretende remover? "; cin >> num; if (num == pacotes[pacotes.size() - 1].number) { age_file_out << pacotes[pacotes.size() - 2].number << endl; } else { age_file_out << pacotes[pacotes.size() - 1].number << endl; } for (i = 0; i <= pacotes.size() - 1; i++) { if (pacotes[i].number == num) { val += 1; continue; } else { age_file_out << pacotes[i].number << endl; age_file_out << pacotes[i].destination << endl; age_file_out << pacotes[i].partida << endl; age_file_out << pacotes[i].chegada << endl; age_file_out << pacotes[i].preco_pessoa << endl; age_file_out << pacotes[i].packs_ini << endl; age_file_out << pacotes[i].packs_comp << endl; if (i == pacotes.size() - 1) { continue; } if (num == pacotes[pacotes.size() - 1].number && i == pacotes.size() - 2) { continue; } age_file_out << "::::::::::" << endl; } } if (val == 0) { // Verificação da existência do pacote através do número obtido no input do utilizador cout << "\nO numero que introduziu nao corresponde a nenhum pacote." << endl; } else { cout << "\nO pacote " << num << " foi removido com sucesso!" << endl; } age_file_out.close(); } if (val == 4) { // Visualizar a informacao de um determinado pacote age_file_out.open(pack_agency); // Sub-menu da funcionalidade de visualização de informações dos pacotes turísticos cout << "\n Qual das seguintes funcionaliades pretende usar?\n\n"; cout << "\t1. Visualizar todos os pacotes para um destino \n"; cout << "\t2. Visualizar todos os pacotes entre duas datas \n"; cout << "\t3. Visualizar todos os pacotes para um destido entre duas datas \n"; cout << "(Por favor insira um valor entre 1 e 3)\n" << endl; int num = 0; while (num != 1 && num != 2 && num != 3) { // Verificação da validade do valor introduzido cin >> num; if (num != 1 && num != 2 && num != 3) { cout << "\nPor favor introduza um valor entre 1 e 3" << endl << endl; } } cout << endl; cin.ignore(1000, '\n'); if (num == 1) { // Visualizar todos os pacotes para um destino string destino; int vali = 0; cout << "Qual o destino que pretende? "; cin >> destino; cout << "\n"; for (i = 0; i <= pacotes.size() - 1; i++) { if (pacotes[i].destination == destino) { cout << "\tNumero do pacote: " << pacotes[i].number << endl; cout << "\tDestino: " << pacotes[i].destination << endl; cout << "\tData de partida: " << pacotes[i].partida << endl; cout << "\tData de chegada: " << pacotes[i].chegada << endl; cout << "\tPreco por pessoa: " << pacotes[i].preco_pessoa << endl; cout << "\tNumero de packs iniciais: " << pacotes[i].packs_ini << endl; cout << "\tNumero de packs comprados: " << pacotes[i].packs_comp << endl; cout << "\n"; vali += 1; } else { continue; } } if (vali == 0) { // Verificação da existência de pacotes para um determinado destino cout << "Nao existem pacotes para " << destino << "."; } age_file_out << pacotes[pacotes.size() - 1].number << endl; for (i = 0; i <= pacotes.size() - 1; i++) { age_file_out << pacotes[i].number << endl; age_file_out << pacotes[i].destination << endl; age_file_out << pacotes[i].partida << endl; age_file_out << pacotes[i].chegada << endl; age_file_out << pacotes[i].preco_pessoa << endl; age_file_out << pacotes[i].packs_ini << endl; age_file_out << pacotes[i].packs_comp << endl; if (i == pacotes.size() - 1) { continue; } age_file_out << "::::::::::" << endl; } } if (num == 2) { // Visualizar todos os pacotes entre duas datas string data_partida, data_chegada; int vali = 0; cout << "Qual a data de partida que pretende? (Formato YYYY/MM/DD) "; cin >> data_partida; cout << "Qual a data de chegada que pretende? (Formato YYYY/MM/DD) "; cin >> data_chegada; cout << "\n"; vector<string> data1; string data1_1; vector<string> data2; string data2_2; for (char& c : data_partida) { // Obtenção do ano, mês e dia da data de partida do utilizador if (c == '/') { data1.push_back(data1_1); data1_1 = ""; } else { data1_1 += c; } } data1.push_back(data1_1); for (char& c : data_chegada) { // Obtenção do ano, mês e dia da data de chegada do utilizador if (c == '/') { data2.push_back(data2_2); data2_2 = ""; } else { data2_2 += c; } } data2.push_back(data2_2); vector<string> data3; vector<string> data4; for (i = 0; i <= pacotes.size() - 1; i++) { string data3_3 = ""; string data4_4 = ""; for (char& c : pacotes[i].partida) { // Obtenção do ano, mês e dia da data de partida do pacote if (c == '/') { data3.push_back(data3_3); data3_3 = ""; } else { data3_3 += c; } } data3.push_back(data3_3); for (char& c : pacotes[i].chegada) { // Obtenção do ano, mês e dia da data de chegada do pacote if (c == '/') { data4.push_back(data4_4); data4_4 = ""; } else { data4_4 += c; } } data4.push_back(data4_4); // Condições para verificação dos pacotes dispóníveis entre as datas introduzidas pelo utilizador if (data1[0] == data3[0] && data2[0] == data4[0]) { if (data1[1] == data3[1] && data2[1] == data4[1]) { if (data1[2] <= data3[2] && data2[2] >= data4[2]) { cout << "\tNumero do pacote: " << pacotes[i].number << endl; cout << "\tDestino: " << pacotes[i].destination << endl; cout << "\tData de partida: " << pacotes[i].partida << endl; cout << "\tData de chegada: " << pacotes[i].chegada << endl; cout << "\tPreco por pessoa: " << pacotes[i].preco_pessoa << endl; cout << "\tNumero de packs iniciais: " << pacotes[i].packs_ini << endl; cout << "\tNumero de packs comprados: " << pacotes[i].packs_comp << endl; cout << "\n"; vali += 1; } } } if ((data1[0] == data3[0]) && (data2[0] == data4[0]) && (data1[1] < data3[1]) && (data2[1] > data4[1])) { cout << "\tNumero do pacote: " << pacotes[i].number << endl; cout << "\tDestino: " << pacotes[i].destination << endl; cout << "\tData de partida: " << pacotes[i].partida << endl; cout << "\tData de chegada: " << pacotes[i].chegada << endl; cout << "\tPreco por pessoa: " << pacotes[i].preco_pessoa << endl; cout << "\tNumero de packs iniciais: " << pacotes[i].packs_ini << endl; cout << "\tNumero de packs comprados: " << pacotes[i].packs_comp << endl; cout << "\n"; vali += 1; } if ((data1[0] < data3[0]) && (data2[0] > data4[0])) { cout << "\tNumero do pacote: " << pacotes[i].number << endl; cout << "\tDestino: " << pacotes[i].destination << endl; cout << "\tData de partida: " << pacotes[i].partida << endl; cout << "\tData de chegada: " << pacotes[i].chegada << endl; cout << "\tPreco por pessoa: " << pacotes[i].preco_pessoa << endl; cout << "\tNumero de packs iniciais: " << pacotes[i].packs_ini << endl; cout << "\tNumero de packs comprados: " << pacotes[i].packs_comp << endl; cout << "\n"; vali += 1; } data3.clear(); data4.clear(); } if (vali == 0) { // Verificação da existência de pacotes entre as datas do utilizador cout << "Nao existem pacotes entre " << data_partida << " e " << data_chegada << "."; } age_file_out << pacotes[pacotes.size() - 1].number << endl; for (i = 0; i <= pacotes.size() - 1; i++) { age_file_out << pacotes[i].number << endl; age_file_out << pacotes[i].destination << endl; age_file_out << pacotes[i].partida << endl; age_file_out << pacotes[i].chegada << endl; age_file_out << pacotes[i].preco_pessoa << endl; age_file_out << pacotes[i].packs_ini << endl; age_file_out << pacotes[i].packs_comp << endl; if (i == pacotes.size() - 1) { continue; } age_file_out << "::::::::::" << endl; } } if (num == 3) { // Visualizar todos os pacotes para um destido entre duas datas string data_partida, data_chegada, destino; int vali = 0; cout << "Qual o destino que pretende? "; cin >> destino; cout << "Qual a data de partida que pretende? (Formato YYYY/MM/DD) "; cin >> data_partida; cout << "Qual a data de chegada que pretende? (Formato YYYY/MM/DD) "; cin >> data_chegada; cout << "\n"; vector<string> data1; string data1_1; vector<string> data2; string data2_2; for (char& c : data_partida) { // Obtenção do ano, mês e dia da data de partida do utilizador if (c == '/') { data1.push_back(data1_1); data1_1 = ""; } else { data1_1 += c; } } data1.push_back(data1_1); for (char& c : data_chegada) { // Obtenção do ano, mês e dia da data de chegada do utilizador if (c == '/') { data2.push_back(data2_2); data2_2 = ""; } else { data2_2 += c; } } data2.push_back(data2_2); vector<string> data3; vector<string> data4; for (i = 0; i <= pacotes.size() - 1; i++) { string data3_3 = ""; string data4_4 = ""; for (char& c : pacotes[i].partida) { // Obtenção do ano, mês e dia da data de partida do pacote if (c == '/') { data3.push_back(data3_3); data3_3 = ""; } else { data3_3 += c; } } data3.push_back(data3_3); for (char& c : pacotes[i].chegada) { // Obtenção do ano, mês e dia da data de chegada do pacote if (c == '/') { data4.push_back(data4_4); data4_4 = ""; } else { data4_4 += c; } } data4.push_back(data4_4); // Verificação dos pacotes entre as datas do utilizador e para um determinado destino if (pacotes[i].destination == destino) { if (data1[0] == data3[0] && data2[0] == data4[0]) { if (data1[1] == data3[1] && data2[1] == data4[1]) { if (data1[2] <= data3[2] && data2[2] >= data4[2]) { cout << "\tNumero do pacote: " << pacotes[i].number << endl; cout << "\tDestino: " << pacotes[i].destination << endl; cout << "\tData de partida: " << pacotes[i].partida << endl; cout << "\tData de chegada: " << pacotes[i].chegada << endl; cout << "\tPreco por pessoa: " << pacotes[i].preco_pessoa << endl; cout << "\tNumero de packs iniciais: " << pacotes[i].packs_ini << endl; cout << "\tNumero de packs comprados: " << pacotes[i].packs_comp << endl; cout << "\n"; vali += 1; } } } if ((data1[0] == data3[0]) && (data2[0] == data4[0]) && (data1[1] < data3[1]) && (data2[1] > data4[1])) { cout << "\tNumero do pacote: " << pacotes[i].number << endl; cout << "\tDestino: " << pacotes[i].destination << endl; cout << "\tData de partida: " << pacotes[i].partida << endl; cout << "\tData de chegada: " << pacotes[i].chegada << endl; cout << "\tPreco por pessoa: " << pacotes[i].preco_pessoa << endl; cout << "\tNumero de packs iniciais: " << pacotes[i].packs_ini << endl; cout << "\tNumero de packs comprados: " << pacotes[i].packs_comp << endl; cout << "\n"; vali += 1; } if ((data1[0] < data3[0]) && (data2[0] > data4[0])) { cout << "\tNumero do pacote: " << pacotes[i].number << endl; cout << "\tDestino: " << pacotes[i].destination << endl; cout << "\tData de partida: " << pacotes[i].partida << endl; cout << "\tData de chegada: " << pacotes[i].chegada << endl; cout << "\tPreco por pessoa: " << pacotes[i].preco_pessoa << endl; cout << "\tNumero de packs iniciais: " << pacotes[i].packs_ini << endl; cout << "\tNumero de packs comprados: " << pacotes[i].packs_comp << endl; cout << "\n"; vali += 1; } } data3.clear(); data4.clear(); } if (vali == 0) { // Verificação da existência de pacotes para as restrções impostas pelo utilizador (data e destino) cout << "Nao existem pacotes para " << destino << " entre " << data_partida << " e " << data_chegada << "."; } age_file_out << pacotes[pacotes.size() - 1].number << endl; for (i = 0; i <= pacotes.size() - 1; i++) { age_file_out << pacotes[i].number << endl; age_file_out << pacotes[i].destination << endl; age_file_out << pacotes[i].partida << endl; age_file_out << pacotes[i].chegada << endl; age_file_out << pacotes[i].preco_pessoa << endl; age_file_out << pacotes[i].packs_ini << endl; age_file_out << pacotes[i].packs_comp << endl; if (i == pacotes.size() - 1) { continue; } age_file_out << "::::::::::" << endl; } } age_file_out.close(); } if (val == 5) { // Visualizar a informacao de todos os pacotes age_file_out.open(pack_agency); cout << "\n"; for (i = 0; i <= pacotes.size() - 1; i++) { cout << "\tNumero do pacote: " << pacotes[i].number << endl; cout << "\tDestino: " << pacotes[i].destination << endl; cout << "\tData de partida: " << pacotes[i].partida << endl; cout << "\tData de chegada: " << pacotes[i].chegada << endl; cout << "\tPreco por pessoa: " << pacotes[i].preco_pessoa << endl; cout << "\tNumero de packs iniciais: " << pacotes[i].packs_ini << endl; cout << "\tNumero de packs comprados: " << pacotes[i].packs_comp << endl; cout << "\n"; } age_file_out << pacotes[pacotes.size() - 1].number << endl; for (i = 0; i <= pacotes.size() - 1; i++) { age_file_out << pacotes[i].number << endl; age_file_out << pacotes[i].destination << endl; age_file_out << pacotes[i].partida << endl; age_file_out << pacotes[i].chegada << endl; age_file_out << pacotes[i].preco_pessoa << endl; age_file_out << pacotes[i].packs_ini << endl; age_file_out << pacotes[i].packs_comp << endl; if (i == pacotes.size() - 1) { continue; } age_file_out << "::::::::::" << endl; } age_file_out.close(); } age_file.close(); return 0; } int compra(string &cli_agency, string &pack_agency) { // Função para a compra e visualização de pacotes turísticos comprados int value = 0; ifstream cli_file; ofstream cli_file_out; cli_file.open(cli_agency); if (cli_file.fail()) { // Leitura e verificação de validade do ficheiro dos clientes da agência cerr << "\nO ficheiro '" << cli_agency << "' nao existe." << endl; exit(1); } typedef struct // Estrutura para definir o cliente { string nome; int nif; int agregado; string add; string pack_list; } Client; vector<Client> clientes; string line; Client cliente; while (!cli_file.eof()) { // Extração dos dados de cada cliente recorrendo a um vetor e à estrutura definida getline(cli_file, cliente.nome); getline(cli_file, line); cliente.nif = stoi(line); getline(cli_file, line); cliente.agregado = stoi(line); getline(cli_file, cliente.add); getline(cli_file, cliente.pack_list); clientes.push_back(cliente); getline(cli_file, line); } ifstream age_file; ofstream age_file_out; age_file.open(pack_agency); if (age_file.fail()) { // Leitura e verificação de validade do ficheiro dos pacotes da agência cout << "\nO ficheiro '" << pack_agency << "' nao existe." << endl; exit(2); } typedef struct // Estrutura para definir os pacotes da agência { int number; string destination; string partida; string chegada; int preco_pessoa; int packs_ini; int packs_comp; } Packs; vector<Packs> pacotes; string line2; int i = 0, last_pack; Packs pacote; while (!age_file.eof()) { // Extração dos dados de cada pacote recorrendo a um vetor e à estrutura definida if (i == 0) { getline(age_file, line2); last_pack = stoi(line2); } getline(age_file, line2); pacote.number = stoi(line2); getline(age_file, pacote.destination); getline(age_file, pacote.partida); getline(age_file, pacote.chegada); getline(age_file, line2); pacote.preco_pessoa = stoi(line2); getline(age_file, line2); pacote.packs_ini = stoi(line2); getline(age_file, line2); pacote.packs_comp = stoi(line2); pacotes.push_back(pacote); getline(age_file, line2); i += 1; } // Menu Compra cout << "\n Qual das seguintes funcionaliades pretende usar?\n\n"; cout << "\t1. Comprar um pacote turistico para um cliente \n"; cout << "\t2. Visualizar pacotes vendidos a um cliente \n"; cout << "\t3. Visualizar pacotes vendidos a todos os clientes \n"; cout << "\t4. Visualizar o numero de pacotes vendidos e o valor total \n"; cout << "(Por favor insira um valor entre 1 e 4)\n" << endl; while (value != 1 && value != 2 && value != 3 && value != 4) { // Verificação da validade do valor introduzido cin >> value; if (value != 1 && value != 2 && value != 3 && value != 4) { cout << "\nPor favor introduza um valor entre 1 e 4\n" << endl; } } cout << endl; cin.ignore(1000, '\n'); if (value == 1) { // Comprar um pacote turistico para um cliente age_file_out.open(pack_agency); cli_file_out.open(cli_agency); string nome_cli; int num_pack, val1 = 0, val2 = 0, cli_num, pack_num; cout << "Qual o nome do cliente? "; getline(cin, nome_cli); for (i = 0; i <= clientes.size() - 1; i++) { // Verificação da presença do cliente na base de dados if (clientes[i].nome == nome_cli) { cli_num = i; val1 = 1; } } if (val1 == 0) { cerr << "O cliente " << nome_cli << " nao se encontra na base de dados."; exit(1); } cout << "Qual o pacote pretendido? (Por favor indique o numero) "; cin >> num_pack; for (i = 0; i <= pacotes.size() - 1; i++) { // Verificação da presença do pacote turístico na base de dados if ( pacotes[i].number == num_pack) { pack_num = i; val2 = 1; } } if (val2 == 0) { cerr << "O pacote " << num_pack << " nao se encontra na base de dados."; exit(1); } // Verificação da possibilidade de adquirir o pacote com base no stock if ((pacotes[pack_num].packs_comp == pacotes[pack_num].packs_ini) || (clientes[cli_num].agregado > ((pacotes[pack_num].packs_ini)-(pacotes[pack_num].packs_comp)))) { cerr << "Nao e possivel adquirir o pack. Rutura de stock."; age_file_out << last_pack << endl; for (i = 0; i <= pacotes.size() - 1; i++) { age_file_out << pacotes[i].number << endl; age_file_out << pacotes[i].destination << endl; age_file_out << pacotes[i].partida << endl; age_file_out << pacotes[i].chegada << endl; age_file_out << pacotes[i].preco_pessoa << endl; age_file_out << pacotes[i].packs_ini << endl; age_file_out << pacotes[i].packs_comp << endl; if (i == pacotes.size() - 1) { continue; } age_file_out << "::::::::::" << endl; } for (i = 0; i <= clientes.size() - 1; i++) { cli_file_out << clientes[i].nome << endl; cli_file_out << clientes[i].nif << endl; cli_file_out << clientes[i].agregado << endl; cli_file_out << clientes[i].add << endl; cli_file_out << clientes[i].pack_list << endl; if (i == clientes.size() - 1) { continue; } cli_file_out << "::::::::::" << endl; } exit(1); } // Atualização dos dados no ficheiro dos clientes e dos packs pacotes[pack_num].packs_comp += clientes[cli_num].agregado; if (pacotes[pack_num].packs_comp == pacotes[pack_num].packs_ini) { pacotes[pack_num].number = '-' + pacotes[pack_num].number; } clientes[cli_num].pack_list += "; " + to_string(num_pack); age_file_out << last_pack << endl; for (i = 0; i <= pacotes.size() - 1; i++) { age_file_out << pacotes[i].number << endl; age_file_out << pacotes[i].destination << endl; age_file_out << pacotes[i].partida << endl; age_file_out << pacotes[i].chegada << endl; age_file_out << pacotes[i].preco_pessoa << endl; age_file_out << pacotes[i].packs_ini << endl; age_file_out << pacotes[i].packs_comp << endl; if (i == pacotes.size() - 1) { continue; } age_file_out << "::::::::::" << endl; } for (i = 0; i <= clientes.size() - 1; i++) { cli_file_out << clientes[i].nome << endl; cli_file_out << clientes[i].nif << endl; cli_file_out << clientes[i].agregado << endl; cli_file_out << clientes[i].add << endl; cli_file_out << clientes[i].pack_list << endl; if (i == clientes.size() - 1) { continue; } cli_file_out << "::::::::::" << endl; } age_file_out.close(); cli_file_out.close(); } if (value == 2) { // Visualizar pacotes vendidos a um cliente string user_client; int ver = 0; cout << "Para qual cliente pretende visualizar os pacotes turisticos adquiridos? "; getline(cin, user_client); for (i = 0; i <= clientes.size() - 1; i++) { if (clientes[i].nome == user_client) { cout << "\n\tNome: " << clientes[i].nome << endl; cout << "\tLista de packs adquiridos: " << clientes[i].pack_list << endl; ver = 1; } } if (ver == 0) { // Verificação da existência de um cliente cout << "O cliente " << user_client << " não se encontra na base de dados."; } } if (value == 3) { // Visualizar pacotes vendidos a todos os clientes for (int i = 0; i <= clientes.size() - 1; i++) { cout << "\n\tNome: " << clientes[i].nome << endl; cout << "\tLista de packs adquiridos: " << clientes[i].pack_list << endl; } } if (value == 4) { // Visualizar o numero de pacotes vendidos e o valor total int total_v = 0, total_p = 0; for (int i = 0; i <= pacotes.size() - 1; i++) { // Cálculo do valor total e registo dos packs vendidos total_v += pacotes[i].packs_comp * pacotes[i].preco_pessoa; total_p += pacotes[i].packs_comp; } cout << "Foram vendidos " << total_p << " pacotes, num valor total de " << total_v << " euros.\n" << endl; } cli_file.close(); age_file.close(); return 0; } int menu(string &cli_agency, string &pack_agency) { // Função com o menu inicial int numero = 0; int num; cout << "\n\t 1. Gestao de clientes \n \t 2. Gestao de pacotes turisticos \n \t 3. Visualizacao de informacao sobre a agencia \n \t 4. Compra de um pacote turistico" << endl; cout << "\nQual a funcionalidade que pretende usar? \n(Por favor digite um numero de 1 a 3)\n\n"; while (numero == 0) { // Verificação da validade do número introduzido cin >> num; if (num == 1 || num == 2 || num == 3 || num == 4) { numero = 1; } else { cout << "Por favor insira um valor entre 1 e 4."; } } if (num == 1) { clientes(cli_agency); } if (num == 2) { pacotes(pack_agency); } if (num == 3) { return 3; } if (num == 4) { compra(cli_agency, pack_agency); } return 0; } int main() { cout << "===============================================" << endl; cout << "|| Programa de Agencias de Viagens ||" << endl; cout << "===============================================\n" << endl; int ver = 0; string file_ini; ifstream agency_file; ofstream agency_file_out; while (ver == 0) { // Ciclo while para leitura e verificação de validade do ficheiro da agência cout << "Qual o nome do ficheiro que pretende usar? "; getline(cin, file_ini); agency_file.open(file_ini); if (agency_file.fail()) { ver = 0; cerr << "\nPor favor insira um nome de ficheiro valido.\n\n"; } else { ver = 1; } } typedef struct // Estrutura da agência de viagens { string nome; string nif; string url; string add; string client_file; string pack_file; } Agency; vector<Agency> agencias; string line; Agency agencia; while (!agency_file.eof()) { // Leitura e armazenamento das informações da agência de viagens getline(agency_file, agencia.nome); getline(agency_file, agencia.nif); getline(agency_file, agencia.url); getline(agency_file, agencia.add); getline(agency_file, agencia.client_file); getline(agency_file, agencia.pack_file); } string cli_agency, pack_agency; cli_agency = agencia.client_file; pack_agency = agencia.pack_file; if (menu(cli_agency, pack_agency) == 3) { // Visualização das Informações da Agência cout << "\nAs informacoes da agencia sao: \n" << endl; cout << "\tAgencia: " << agencia.nome << endl; cout << "\tNIF: " << agencia.nif << endl; cout << "\tURL: " << agencia.url << endl; replace(agencia.add.begin(), agencia.add.end(), '/', ','); cout << "\tMorada: " << agencia.add << endl; } agency_file.close(); return 0; }
cdbab64726311f928f2f8a44c89695a88558f314
52595e8ee0eaa348600226573cf6d42a98bbb3b5
/树和图实验题目集/2-2 畅通工程之局部最小花费问题 (30分)5.cpp
99962ad6ab2f14e22fcfc74ea14c9062a0c63c19
[]
no_license
HANXU2018/HBUDataStruct
f47049b21728a3e07324ed1f6c359fff230ad7f6
4223983450df0e21c5d0baaea3cf9cbd1126a750
refs/heads/master
2020-09-25T16:14:14.604340
2020-03-25T04:04:18
2020-03-25T04:04:18
226,041,175
1
0
null
null
null
null
UTF-8
C++
false
false
802
cpp
2-2 畅通工程之局部最小花费问题 (30分)5.cpp
#include<iostream> #include<vector> using namespace std; int main(){ int n; cin>>n; vector<vector<int>> v; for(int i=0;i<n;i++){ vector<int>vv(n); for(int a=0;a<n;a++)vv[a]=999999; vv[i]=0; v.push_back(vv); } vector<int> vis(n); vector<int> dis(n); for(int i=0;i<n*(n-1)/2;i++){ int a,b,c,d; cin>>a>>b>>c>>d; if(d==1){ v[a-1][b-1]=0; v[b-1][a-1]=0; }else{ v[a-1][b-1]=c; v[b-1][a-1]=c; } } vis[0]=1; int count=1; int sum=0; for(int i=0;i<n;i++){ dis[i]=v[0][i]; } while(count<n){ int min =999999; int d=0; for(int i=0;i<n;i++){ if(vis[i]==0&&dis[i]<min){ min=dis[i]; d=i; } }vis[d]=1; sum+=min; count++; for(int i=0;i<n;i++){ if(vis[i]==0&&dis[i]>v[d][i]){ dis[i]=v[d][i]; } } } printf("%d",sum); return 0; }
5cab4324ae423b3df5600ee24030ece10b7cf7e4
38896951aea62f5b87fcb236c149647513f1889c
/io/src/obj_io.cpp
9cc1fdc68f769a85b69479ea4aa66b95d83cf140
[ "BSD-3-Clause" ]
permissive
PointCloudLibrary/pcl
243714ed366a277f60a8097e133e195f3b91321c
f2492bd65cb1e9c48a60f5e27296e25e1835169a
refs/heads/master
2023-09-04T17:55:05.319149
2023-09-04T07:40:09
2023-09-04T07:40:09
8,162,615
9,065
4,836
NOASSERTION
2023-09-14T19:47:04
2013-02-12T16:40:25
C++
UTF-8
C++
false
false
37,738
cpp
obj_io.cpp
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010, Willow Garage, Inc. * Copyright (c) 2013, Open Perception, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include <pcl/io/obj_io.h> #include <fstream> #include <pcl/common/io.h> #include <pcl/console/time.h> #include <pcl/io/split.h> #include <boost/lexical_cast.hpp> // for lexical_cast #include <boost/filesystem.hpp> // for exists #include <boost/algorithm/string.hpp> // for trim pcl::MTLReader::MTLReader () { xyz_to_rgb_matrix_ << 2.3706743, -0.9000405, -0.4706338, -0.5138850, 1.4253036, 0.0885814, 0.0052982, -0.0146949, 1.0093968; } inline void pcl::MTLReader::cie2rgb (const Eigen::Vector3f &xyz, pcl::TexMaterial::RGB& rgb) const { Eigen::Vector3f rgb_vec = xyz_to_rgb_matrix_ * xyz; rgb.r = rgb_vec[0]; rgb.g = rgb_vec[1]; rgb.b = rgb_vec[2]; } int pcl::MTLReader::fillRGBfromXYZ (const std::vector<std::string>& split_line, pcl::TexMaterial::RGB& rgb) { Eigen::Vector3f xyz; if (split_line.size () == 5) { try { xyz[0] = boost::lexical_cast<float> (split_line[2]); xyz[1] = boost::lexical_cast<float> (split_line[3]); xyz[2] = boost::lexical_cast<float> (split_line[4]); } catch (boost::bad_lexical_cast &) { return (-1); } } else if (split_line.size () == 3) { try { xyz[0] = xyz[1] = xyz[2] = boost::lexical_cast<float> (split_line[2]); } catch (boost::bad_lexical_cast &) { return (-1); } } else return (-1); cie2rgb (xyz, rgb); return (0); } int pcl::MTLReader::fillRGBfromRGB (const std::vector<std::string>& split_line, pcl::TexMaterial::RGB& rgb) { if (split_line.size () == 4) { try { rgb.r = boost::lexical_cast<float> (split_line[1]); rgb.g = boost::lexical_cast<float> (split_line[2]); rgb.b = boost::lexical_cast<float> (split_line[3]); } catch (boost::bad_lexical_cast &) { rgb.r = rgb.g = rgb.b = 0; return (-1); } } else if (split_line.size () == 2) { try { rgb.r = rgb.g = rgb.b = boost::lexical_cast<float> (split_line[1]); } catch (boost::bad_lexical_cast &) { return (-1); } } else return (-1); return (0); } std::vector<pcl::TexMaterial>::const_iterator pcl::MTLReader::getMaterial (const std::string& material_name) const { auto mat_it = materials_.begin (); for (; mat_it != materials_.end (); ++mat_it) if (mat_it->tex_name == material_name) break; return (mat_it); } int pcl::MTLReader::read (const std::string& obj_file_name, const std::string& mtl_file_name) { if (obj_file_name.empty() || !boost::filesystem::exists (obj_file_name)) { PCL_ERROR ("[pcl::MTLReader::read] Could not find file '%s'!\n", obj_file_name.c_str ()); return (-1); } if (mtl_file_name.empty()) { PCL_ERROR ("[pcl::MTLReader::read] MTL file name is empty!\n"); return (-1); } boost::filesystem::path obj_file_path (obj_file_name.c_str ()); boost::filesystem::path mtl_file_path = obj_file_path.parent_path (); mtl_file_path /= mtl_file_name; return (read (mtl_file_path.string ())); } int pcl::MTLReader::read (const std::string& mtl_file_path) { if (mtl_file_path.empty() || !boost::filesystem::exists (mtl_file_path)) { PCL_ERROR ("[pcl::MTLReader::read] Could not find file '%s'.\n", mtl_file_path.c_str ()); return (-1); } std::ifstream mtl_file; mtl_file.open (mtl_file_path.c_str (), std::ios::binary); if (!mtl_file.is_open () || mtl_file.fail ()) { PCL_ERROR ("[pcl::MTLReader::read] Could not open file '%s'! Error : %s\n", mtl_file_path.c_str (), strerror(errno)); mtl_file.close (); return (-1); } std::string line; std::vector<std::string> st; boost::filesystem::path parent_path = mtl_file_path.c_str (); parent_path = parent_path.parent_path (); try { while (!mtl_file.eof ()) { getline (mtl_file, line); // Ignore empty lines if (line.empty()) continue; // Tokenize the line pcl::split (st, line, "\t\r "); // Ignore comments if (st[0] == "#") continue; if (st[0] == "newmtl") { materials_.emplace_back(); materials_.back ().tex_name = st[1]; continue; } if (st[0] == "Ka" || st[0] == "Kd" || st[0] == "Ks") { if (st[1] == "spectral") { PCL_ERROR ("[pcl::MTLReader::read] Can't handle spectral files!\n"); mtl_file.close (); materials_.clear (); return (-1); } pcl::TexMaterial::RGB *rgb = &materials_.back ().tex_Ka; if (st[0] == "Kd") rgb = &materials_.back ().tex_Kd; else if (st[0] == "Ks") rgb = &materials_.back ().tex_Ks; if (st[1] == "xyz") { if (fillRGBfromXYZ (st, *rgb)) { PCL_ERROR ("[pcl::MTLReader::read] Could not convert %s to RGB values\n", line.c_str ()); mtl_file.close (); materials_.clear (); return (-1); } } else { if (fillRGBfromRGB (st, *rgb)) { PCL_ERROR ("[pcl::MTLReader::read] Could not convert %s to RGB values\n", line.c_str ()); mtl_file.close (); materials_.clear (); return (-1); } } continue; } if (st[0] == "illum") { try { materials_.back ().tex_illum = boost::lexical_cast<int> (st[1]); } catch (boost::bad_lexical_cast &) { PCL_ERROR ("[pcl::MTLReader::read] Could not convert %s to illumination model\n", line.c_str ()); mtl_file.close (); materials_.clear (); return (-1); } continue; } if (st[0] == "d" || st[0] == "Tr") { bool reverse = (st[0] == "Tr"); try { materials_.back ().tex_d = boost::lexical_cast<float> (st[st.size () > 2 ? 2:1]); if (reverse) materials_.back ().tex_d = 1.f - materials_.back ().tex_d; } catch (boost::bad_lexical_cast &) { PCL_ERROR ("[pcl::MTLReader::read] Could not convert %s to transparency value\n", line.c_str ()); mtl_file.close (); materials_.clear (); return (-1); } continue; } if (st[0] == "Ns") { try { materials_.back ().tex_Ns = boost::lexical_cast<float> (st[1]); } catch (boost::bad_lexical_cast &) { PCL_ERROR ("[pcl::MTLReader::read] Could not convert %s to shininess value\n", line.c_str ()); mtl_file.close (); materials_.clear (); return (-1); } continue; } if (st[0] == "map_Kd") { boost::filesystem::path full_path = parent_path; full_path/= st.back ().c_str (); materials_.back ().tex_file = full_path.string (); continue; } // other elements? we don't care for now } } catch (const char *exception) { PCL_ERROR ("[pcl::MTLReader::read] %s\n", exception); mtl_file.close (); materials_.clear (); return (-1); } return (0); } int pcl::OBJReader::readHeader (const std::string &file_name, pcl::PCLPointCloud2 &cloud, Eigen::Vector4f &origin, Eigen::Quaternionf &orientation, int &file_version, int &data_type, unsigned int &data_idx, const int offset) { origin = Eigen::Vector4f::Zero (); orientation = Eigen::Quaternionf::Identity (); file_version = 0; cloud.width = cloud.height = cloud.point_step = cloud.row_step = 0; cloud.data.clear (); data_type = 0; data_idx = offset; std::ifstream fs; std::string line; if (file_name.empty() || !boost::filesystem::exists (file_name)) { PCL_ERROR ("[pcl::OBJReader::readHeader] Could not find file '%s'.\n", file_name.c_str ()); return (-1); } // Open file in binary mode to avoid problem of // std::getline() corrupting the result of ifstream::tellg() fs.open (file_name.c_str (), std::ios::binary); if (!fs.is_open () || fs.fail ()) { PCL_ERROR ("[pcl::OBJReader::readHeader] Could not open file '%s'! Error : %s\n", file_name.c_str (), strerror(errno)); fs.close (); return (-1); } // Seek at the given offset fs.seekg (offset, std::ios::beg); // Read the header and fill it in with wonderful values bool vertex_normal_found = false; bool vertex_texture_found = false; // Material library, skip for now! // bool material_found = false; std::vector<std::string> material_files; std::size_t nr_point = 0; try { while (!fs.eof ()) { getline (fs, line); // Ignore empty lines if (line.empty()) continue; // Trim the line //TODO: we can easily do this without boost boost::trim (line); // Ignore comments if (line[0] == '#') continue; // Vertex, vertex texture or vertex normal if (line[0] == 'v') { // Vertex (v) if (line[1] == ' ') { ++nr_point; continue; } // Vertex texture (vt) if ((line[1] == 't') && !vertex_texture_found) { vertex_texture_found = true; continue; } // Vertex normal (vn) if ((line[1] == 'n') && !vertex_normal_found) { vertex_normal_found = true; continue; } } // Material library, skip for now! if (line.substr (0, 6) == "mtllib") { std::vector<std::string> st; pcl::split(st, line, "\t\r "); material_files.push_back (st.at (1)); continue; } } } catch (const char *exception) { PCL_ERROR ("[pcl::OBJReader::readHeader] %s\n", exception); fs.close (); return (-1); } if (!nr_point) { PCL_ERROR ("[pcl::OBJReader::readHeader] No vertices found!\n"); fs.close (); return (-1); } int field_offset = 0; for (int i = 0; i < 3; ++i, field_offset += 4) { cloud.fields.emplace_back(); cloud.fields[i].offset = field_offset; cloud.fields[i].datatype = pcl::PCLPointField::FLOAT32; cloud.fields[i].count = 1; } cloud.fields[0].name = "x"; cloud.fields[1].name = "y"; cloud.fields[2].name = "z"; if (vertex_normal_found) { std::string normals_names[3] = { "normal_x", "normal_y", "normal_z" }; for (int i = 0; i < 3; ++i, field_offset += 4) { cloud.fields.emplace_back(); pcl::PCLPointField& last = cloud.fields.back (); last.name = normals_names[i]; last.offset = field_offset; last.datatype = pcl::PCLPointField::FLOAT32; last.count = 1; } } if (!material_files.empty ()) { for (const auto &material_file : material_files) { MTLReader companion; if (companion.read (file_name, material_file)) PCL_WARN ("[pcl::OBJReader::readHeader] Problem reading material file %s\n", material_file.c_str ()); companions_.push_back (companion); } } cloud.point_step = field_offset; cloud.width = nr_point; cloud.height = 1; cloud.row_step = cloud.point_step * cloud.width; cloud.is_dense = true; cloud.data.resize (cloud.point_step * nr_point); fs.close (); return (0); } int pcl::OBJReader::read (const std::string &file_name, pcl::PCLPointCloud2 &cloud, const int offset) { int file_version; Eigen::Vector4f origin; Eigen::Quaternionf orientation; return (read (file_name, cloud, origin, orientation, file_version, offset)); } int pcl::OBJReader::read (const std::string &file_name, pcl::PCLPointCloud2 &cloud, Eigen::Vector4f &origin, Eigen::Quaternionf &orientation, int &file_version, const int offset) { pcl::console::TicToc tt; tt.tic (); int data_type; unsigned int data_idx; if (readHeader (file_name, cloud, origin, orientation, file_version, data_type, data_idx, offset)) { PCL_ERROR ("[pcl::OBJReader::read] Problem reading header!\n"); return (-1); } std::ifstream fs; fs.open (file_name.c_str (), std::ios::binary); if (!fs.is_open () || fs.fail ()) { PCL_ERROR ("[pcl::OBJReader::readHeader] Could not open file '%s'! Error : %s\n", file_name.c_str (), strerror(errno)); fs.close (); return (-1); } // Seek at the given offset fs.seekg (data_idx, std::ios::beg); // Get normal_x and rgba fields indices int normal_x_field = -1; // std::size_t rgba_field = 0; for (std::size_t i = 0; i < cloud.fields.size (); ++i) if (cloud.fields[i].name == "normal_x") { normal_x_field = i; break; } // else if (cloud.fields[i].name == "rgba") // rgba_field = i; std::vector<std::string> st; std::string line; try { uindex_t point_idx = 0; uindex_t normal_idx = 0; while (!fs.eof ()) { getline (fs, line); // Ignore empty lines if (line.empty()) continue; // Tokenize the line pcl::split (st, line, "\t\r "); // Ignore comments if (st[0] == "#") continue; // Vertex if (st[0] == "v") { try { for (int i = 1, f = 0; i < 4; ++i, ++f) { float value = boost::lexical_cast<float> (st[i]); memcpy (&cloud.data[point_idx * cloud.point_step + cloud.fields[f].offset], &value, sizeof (float)); } ++point_idx; } catch (const boost::bad_lexical_cast&) { PCL_ERROR ("Unable to convert %s to vertex coordinates!\n", line.c_str ()); return (-1); } continue; } // Vertex normal if (st[0] == "vn") { if (normal_idx >= cloud.width) { if (normal_idx == cloud.width) PCL_WARN ("[pcl:OBJReader] Too many vertex normals (expected %d), skipping remaining normals.\n", cloud.width, normal_idx + 1); ++normal_idx; continue; } try { for (int i = 1, f = normal_x_field; i < 4; ++i, ++f) { float value = boost::lexical_cast<float> (st[i]); memcpy (&cloud.data[normal_idx * cloud.point_step + cloud.fields[f].offset], &value, sizeof (float)); } ++normal_idx; } catch (const boost::bad_lexical_cast&) { PCL_ERROR ("Unable to convert line %s to vertex normal!\n", line.c_str ()); return (-1); } continue; } } } catch (const char *exception) { PCL_ERROR ("[pcl::OBJReader::read] %s\n", exception); fs.close (); return (-1); } double total_time = tt.toc (); PCL_DEBUG ("[pcl::OBJReader::read] Loaded %s as a dense cloud in %g ms with %d points. Available dimensions: %s.\n", file_name.c_str (), total_time, cloud.width * cloud.height, pcl::getFieldsList (cloud).c_str ()); fs.close (); return (0); } int pcl::OBJReader::read (const std::string &file_name, pcl::TextureMesh &mesh, const int offset) { int file_version; Eigen::Vector4f origin; Eigen::Quaternionf orientation; return (read (file_name, mesh, origin, orientation, file_version, offset)); } int pcl::OBJReader::read (const std::string &file_name, pcl::TextureMesh &mesh, Eigen::Vector4f &origin, Eigen::Quaternionf &orientation, int &file_version, const int offset) { pcl::console::TicToc tt; tt.tic (); int data_type; unsigned int data_idx; if (readHeader (file_name, mesh.cloud, origin, orientation, file_version, data_type, data_idx, offset)) { PCL_ERROR ("[pcl::OBJReader::read] Problem reading header!\n"); return (-1); } std::ifstream fs; fs.open (file_name.c_str (), std::ios::binary); if (!fs.is_open () || fs.fail ()) { PCL_ERROR ("[pcl::OBJReader::readHeader] Could not open file '%s'! Error : %s\n", file_name.c_str (), strerror(errno)); fs.close (); return (-1); } // Seek at the given offset fs.seekg (data_idx, std::ios::beg); // Get normal_x and rgba fields indices int normal_x_field = -1; // std::size_t rgba_field = 0; for (std::size_t i = 0; i < mesh.cloud.fields.size (); ++i) if (mesh.cloud.fields[i].name == "normal_x") { normal_x_field = i; break; } std::size_t v_idx = 0; std::size_t f_idx = 0; std::string line; std::vector<std::string> st; std::vector<Eigen::Vector2f, Eigen::aligned_allocator<Eigen::Vector2f> > coordinates; try { std::size_t vn_idx = 0; while (!fs.eof ()) { getline (fs, line); // Ignore empty lines if (line.empty()) continue; // Tokenize the line pcl::split (st, line, "\t\r "); // Ignore comments if (st[0] == "#") continue; // Vertex if (st[0] == "v") { try { for (int i = 1, f = 0; i < 4; ++i, ++f) { float value = boost::lexical_cast<float> (st[i]); memcpy (&mesh.cloud.data[v_idx * mesh.cloud.point_step + mesh.cloud.fields[f].offset], &value, sizeof (float)); } ++v_idx; } catch (const boost::bad_lexical_cast&) { PCL_ERROR ("Unable to convert %s to vertex coordinates!\n", line.c_str ()); return (-1); } continue; } // Vertex normal if (st[0] == "vn") { try { for (int i = 1, f = normal_x_field; i < 4; ++i, ++f) { float value = boost::lexical_cast<float> (st[i]); memcpy (&mesh.cloud.data[vn_idx * mesh.cloud.point_step + mesh.cloud.fields[f].offset], &value, sizeof (float)); } ++vn_idx; } catch (const boost::bad_lexical_cast&) { PCL_ERROR ("Unable to convert line %s to vertex normal!\n", line.c_str ()); return (-1); } continue; } // Texture coordinates if (st[0] == "vt") { try { Eigen::Vector3f c (0, 0, 0); for (std::size_t i = 1; i < st.size (); ++i) c[i-1] = boost::lexical_cast<float> (st[i]); if (c[2] == 0) coordinates.emplace_back(c[0], c[1]); else coordinates.emplace_back(c[0]/c[2], c[1]/c[2]); } catch (const boost::bad_lexical_cast&) { PCL_ERROR ("Unable to convert line %s to texture coordinates!\n", line.c_str ()); return (-1); } continue; } // Material if (st[0] == "usemtl") { mesh.tex_polygons.emplace_back(); mesh.tex_coord_indices.emplace_back(); mesh.tex_materials.emplace_back(); for (const auto &companion : companions_) { auto mat_it = companion.getMaterial (st[1]); if (mat_it != companion.materials_.end ()) { mesh.tex_materials.back () = *mat_it; break; } } // We didn't find the appropriate material so we create it here with name only. if (mesh.tex_materials.back ().tex_name.empty()) mesh.tex_materials.back ().tex_name = st[1]; mesh.tex_coordinates.push_back (coordinates); coordinates.clear (); continue; } // Face if (st[0] == "f") { // TODO read in normal indices properly pcl::Vertices face_v; face_v.vertices.resize (st.size () - 1); pcl::Vertices tex_indices; tex_indices.vertices.reserve (st.size () - 1); for (std::size_t i = 1; i < st.size (); ++i) { char* str_end; int v = std::strtol(st[i].c_str(), &str_end, 10); v = (v < 0) ? v_idx + v : v - 1; face_v.vertices[i-1] = v; if (str_end[0] == '/' && str_end[1] != '/' && str_end[1] != '\0') { // texture coordinate indices are optional int tex_index = std::strtol(str_end+1, &str_end, 10); tex_indices.vertices.push_back (tex_index - 1); } } mesh.tex_polygons.back ().push_back (face_v); mesh.tex_coord_indices.back ().push_back (tex_indices); ++f_idx; continue; } } } catch (const char *exception) { PCL_ERROR ("[pcl::OBJReader::read] %s\n", exception); fs.close (); return (-1); } double total_time = tt.toc (); PCL_DEBUG ("[pcl::OBJReader::read] Loaded %s as a TextureMesh in %g ms with %zu points, %zu texture materials, %zu polygons.\n", file_name.c_str (), total_time, v_idx, mesh.tex_materials.size (), f_idx); fs.close (); return (0); } int pcl::OBJReader::read (const std::string &file_name, pcl::PolygonMesh &mesh, const int offset) { int file_version; Eigen::Vector4f origin; Eigen::Quaternionf orientation; return (read (file_name, mesh, origin, orientation, file_version, offset)); } int pcl::OBJReader::read (const std::string &file_name, pcl::PolygonMesh &mesh, Eigen::Vector4f &origin, Eigen::Quaternionf &orientation, int &file_version, const int offset) { pcl::console::TicToc tt; tt.tic (); int data_type; unsigned int data_idx; if (readHeader (file_name, mesh.cloud, origin, orientation, file_version, data_type, data_idx, offset)) { PCL_ERROR ("[pcl::OBJReader::read] Problem reading header!\n"); return (-1); } std::ifstream fs; fs.open (file_name.c_str (), std::ios::binary); if (!fs.is_open () || fs.fail ()) { PCL_ERROR ("[pcl::OBJReader::readHeader] Could not open file '%s'! Error : %s\n", file_name.c_str (), strerror(errno)); fs.close (); return (-1); } // Seek at the given offset fs.seekg (data_idx, std::ios::beg); // Get normal_x and rgba fields indices int normal_x_field = -1; // std::size_t rgba_field = 0; for (std::size_t i = 0; i < mesh.cloud.fields.size (); ++i) if (mesh.cloud.fields[i].name == "normal_x") { normal_x_field = i; break; } std::vector<std::string> st; try { std::size_t v_idx = 0; std::size_t vn_idx = 0; while (!fs.eof ()) { std::string line; getline (fs, line); // Ignore empty lines if (line.empty()) continue; // Tokenize the line pcl::split (st, line, "\t\r "); // Ignore comments if (st[0] == "#") continue; // Vertex if (st[0] == "v") { try { for (int i = 1, f = 0; i < 4; ++i, ++f) { float value = boost::lexical_cast<float> (st[i]); memcpy (&mesh.cloud.data[v_idx * mesh.cloud.point_step + mesh.cloud.fields[f].offset], &value, sizeof (float)); } ++v_idx; } catch (const boost::bad_lexical_cast&) { PCL_ERROR ("Unable to convert %s to vertex coordinates!\n", line.c_str ()); return (-1); } continue; } // Vertex normal if (st[0] == "vn") { try { for (int i = 1, f = normal_x_field; i < 4; ++i, ++f) { float value = boost::lexical_cast<float> (st[i]); memcpy (&mesh.cloud.data[vn_idx * mesh.cloud.point_step + mesh.cloud.fields[f].offset], &value, sizeof (float)); } ++vn_idx; } catch (const boost::bad_lexical_cast&) { PCL_ERROR ("Unable to convert line %s to vertex normal!\n", line.c_str ()); return (-1); } continue; } // Face if (st[0] == "f") { pcl::Vertices face_vertices; face_vertices.vertices.resize (st.size () - 1); for (std::size_t i = 1; i < st.size (); ++i) { int v; sscanf (st[i].c_str (), "%d", &v); v = (v < 0) ? v_idx + v : v - 1; face_vertices.vertices[i - 1] = v; } mesh.polygons.push_back (face_vertices); continue; } } } catch (const char *exception) { PCL_ERROR ("[pcl::OBJReader::read] %s\n", exception); fs.close (); return (-1); } double total_time = tt.toc (); PCL_DEBUG ("[pcl::OBJReader::read] Loaded %s as a PolygonMesh in %g ms with %zu points and %zu polygons.\n", file_name.c_str (), total_time, static_cast<std::size_t> (mesh.cloud.width * mesh.cloud.height), mesh.polygons.size ()); fs.close (); return (0); } int pcl::io::saveOBJFile (const std::string &file_name, const pcl::TextureMesh &tex_mesh, unsigned precision) { if (tex_mesh.cloud.data.empty ()) { PCL_ERROR ("[pcl::io::saveOBJFile] Input point cloud has no data!\n"); return (-1); } // Open file std::ofstream fs; fs.precision (precision); fs.open (file_name.c_str ()); // Define material file std::string mtl_file_name = file_name.substr (0, file_name.find_last_of ('.')) + ".mtl"; // Strip path for "mtllib" command std::string mtl_file_name_nopath = mtl_file_name; mtl_file_name_nopath.erase (0, mtl_file_name.find_last_of ('/') + 1); /* Write 3D information */ // number of points unsigned nr_points = tex_mesh.cloud.width * tex_mesh.cloud.height; auto point_size = static_cast<unsigned> (tex_mesh.cloud.data.size () / nr_points); // mesh size auto nr_meshes = static_cast<unsigned> (tex_mesh.tex_polygons.size ()); // number of faces for header unsigned nr_faces = 0; for (unsigned m = 0; m < nr_meshes; ++m) nr_faces += static_cast<unsigned> (tex_mesh.tex_polygons[m].size ()); // Write the header information fs << "####" << '\n'; fs << "# OBJ dataFile simple version. File name: " << file_name << '\n'; fs << "# Vertices: " << nr_points << '\n'; fs << "# Faces: " <<nr_faces << '\n'; fs << "# Material information:" << '\n'; fs << "mtllib " << mtl_file_name_nopath << '\n'; fs << "####" << '\n'; // Write vertex coordinates fs << "# Vertices" << '\n'; for (unsigned i = 0; i < nr_points; ++i) { int xyz = 0; // "v" just be written one bool v_written = false; for (std::size_t d = 0; d < tex_mesh.cloud.fields.size (); ++d) { // adding vertex if ((tex_mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) && ( tex_mesh.cloud.fields[d].name == "x" || tex_mesh.cloud.fields[d].name == "y" || tex_mesh.cloud.fields[d].name == "z")) { if (!v_written) { // write vertices beginning with v fs << "v "; v_written = true; } float value; memcpy (&value, &tex_mesh.cloud.data[i * point_size + tex_mesh.cloud.fields[d].offset], sizeof (float)); fs << value; if (++xyz == 3) break; fs << " "; } } if (xyz != 3) { PCL_ERROR ("[pcl::io::saveOBJFile] Input point cloud has no XYZ data!\n"); return (-2); } fs << '\n'; } fs << "# "<< nr_points <<" vertices" << '\n'; // Write vertex normals for (unsigned i = 0; i < nr_points; ++i) { int xyz = 0; // "vn" just be written one bool v_written = false; for (std::size_t d = 0; d < tex_mesh.cloud.fields.size (); ++d) { // adding vertex if ((tex_mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) && ( tex_mesh.cloud.fields[d].name == "normal_x" || tex_mesh.cloud.fields[d].name == "normal_y" || tex_mesh.cloud.fields[d].name == "normal_z")) { if (!v_written) { // write vertices beginning with vn fs << "vn "; v_written = true; } float value; memcpy (&value, &tex_mesh.cloud.data[i * point_size + tex_mesh.cloud.fields[d].offset], sizeof (float)); fs << value; if (++xyz == 3) break; fs << " "; } } if (xyz != 3) { PCL_ERROR ("[pcl::io::saveOBJFile] Input point cloud has no normals!\n"); return (-2); } fs << '\n'; } // Write vertex texture with "vt" (adding latter) for (unsigned m = 0; m < nr_meshes; ++m) { fs << "# " << tex_mesh.tex_coordinates[m].size() << " vertex textures in submesh " << m << '\n'; for (const auto &coordinate : tex_mesh.tex_coordinates[m]) { fs << "vt "; fs << coordinate[0] << " " << coordinate[1] << '\n'; } } // int idx_vt =0; for (unsigned m = 0; m < nr_meshes; ++m) { fs << "# The material will be used for mesh " << m << '\n'; fs << "usemtl " << tex_mesh.tex_materials[m].tex_name << '\n'; fs << "# Faces" << '\n'; for (std::size_t i = 0; i < tex_mesh.tex_polygons[m].size(); ++i) { // Write faces with "f" fs << "f"; for (std::size_t j = 0; j < tex_mesh.tex_polygons[m][i].vertices.size (); ++j) { std::uint32_t idx = tex_mesh.tex_polygons[m][i].vertices[j] + 1; fs << " " << idx << "/"; // texture coordinate indices are optional if (!tex_mesh.tex_coord_indices[m][i].vertices.empty()) fs << tex_mesh.tex_coord_indices[m][i].vertices[j] + 1; fs << "/" << idx; // vertex index in obj file format starting with 1 } fs << '\n'; } fs << "# "<< tex_mesh.tex_polygons[m].size() << " faces in mesh " << m << '\n'; } fs << "# End of File" << std::flush; // Close obj file fs.close (); /* Write material definition for OBJ file*/ // Open file std::ofstream m_fs; m_fs.precision (precision); m_fs.open (mtl_file_name.c_str ()); // default m_fs << "#" << '\n'; m_fs << "# Wavefront material file" << '\n'; m_fs << "#" << '\n'; for(unsigned m = 0; m < nr_meshes; ++m) { m_fs << "newmtl " << tex_mesh.tex_materials[m].tex_name << '\n'; m_fs << "Ka "<< tex_mesh.tex_materials[m].tex_Ka.r << " " << tex_mesh.tex_materials[m].tex_Ka.g << " " << tex_mesh.tex_materials[m].tex_Ka.b << '\n'; // defines the ambient color of the material to be (r,g,b). m_fs << "Kd "<< tex_mesh.tex_materials[m].tex_Kd.r << " " << tex_mesh.tex_materials[m].tex_Kd.g << " " << tex_mesh.tex_materials[m].tex_Kd.b << '\n'; // defines the diffuse color of the material to be (r,g,b). m_fs << "Ks "<< tex_mesh.tex_materials[m].tex_Ks.r << " " << tex_mesh.tex_materials[m].tex_Ks.g << " " << tex_mesh.tex_materials[m].tex_Ks.b << '\n'; // defines the specular color of the material to be (r,g,b). This color shows up in highlights. m_fs << "d " << tex_mesh.tex_materials[m].tex_d << '\n'; // defines the transparency of the material to be alpha. m_fs << "Ns "<< tex_mesh.tex_materials[m].tex_Ns << '\n'; // defines the shininess of the material to be s. m_fs << "illum "<< tex_mesh.tex_materials[m].tex_illum << '\n'; // denotes the illumination model used by the material. // illum = 1 indicates a flat material with no specular highlights, so the value of Ks is not used. // illum = 2 denotes the presence of specular highlights, and so a specification for Ks is required. m_fs << "map_Kd " << tex_mesh.tex_materials[m].tex_file << '\n'; m_fs << "###" << '\n'; } m_fs.close (); return (0); } int pcl::io::saveOBJFile (const std::string &file_name, const pcl::PolygonMesh &mesh, unsigned precision) { if (mesh.cloud.data.empty ()) { PCL_ERROR ("[pcl::io::saveOBJFile] Input point cloud has no data!\n"); return (-1); } // Open file std::ofstream fs; fs.precision (precision); fs.open (file_name.c_str ()); /* Write 3D information */ // number of points int nr_points = mesh.cloud.width * mesh.cloud.height; // point size auto point_size = static_cast<unsigned> (mesh.cloud.data.size () / nr_points); // number of faces for header auto nr_faces = static_cast<unsigned> (mesh.polygons.size ()); // Do we have vertices normals? int normal_index = getFieldIndex (mesh.cloud, "normal_x"); // Write the header information fs << "####" << '\n'; fs << "# OBJ dataFile simple version. File name: " << file_name << '\n'; fs << "# Vertices: " << nr_points << '\n'; if (normal_index != -1) fs << "# Vertices normals : " << nr_points << '\n'; fs << "# Faces: " <<nr_faces << '\n'; fs << "####" << '\n'; // Write vertex coordinates fs << "# List of Vertices, with (x,y,z) coordinates, w is optional." << '\n'; for (int i = 0; i < nr_points; ++i) { int xyz = 0; for (std::size_t d = 0; d < mesh.cloud.fields.size (); ++d) { // adding vertex if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) && ( mesh.cloud.fields[d].name == "x" || mesh.cloud.fields[d].name == "y" || mesh.cloud.fields[d].name == "z")) { if (mesh.cloud.fields[d].name == "x") // write vertices beginning with v fs << "v "; float value; memcpy (&value, &mesh.cloud.data[i * point_size + mesh.cloud.fields[d].offset], sizeof (float)); fs << value; if (++xyz == 3) break; fs << " "; } } if (xyz != 3) { PCL_ERROR ("[pcl::io::saveOBJFile] Input point cloud has no XYZ data!\n"); return (-2); } fs << '\n'; } fs << "# "<< nr_points <<" vertices" << '\n'; if(normal_index != -1) { fs << "# Normals in (x,y,z) form; normals might not be unit." << '\n'; // Write vertex normals for (int i = 0; i < nr_points; ++i) { int nxyz = 0; for (std::size_t d = 0; d < mesh.cloud.fields.size (); ++d) { // adding vertex if ((mesh.cloud.fields[d].datatype == pcl::PCLPointField::FLOAT32) && ( mesh.cloud.fields[d].name == "normal_x" || mesh.cloud.fields[d].name == "normal_y" || mesh.cloud.fields[d].name == "normal_z")) { if (mesh.cloud.fields[d].name == "normal_x") // write vertices beginning with vn fs << "vn "; float value; memcpy (&value, &mesh.cloud.data[i * point_size + mesh.cloud.fields[d].offset], sizeof (float)); fs << value; if (++nxyz == 3) break; fs << " "; } } if (nxyz != 3) { PCL_ERROR ("[pcl::io::saveOBJFile] Input point cloud has no normals!\n"); return (-2); } fs << '\n'; } fs << "# "<< nr_points <<" vertices normals" << '\n'; } fs << "# Face Definitions" << '\n'; // Write down faces if(normal_index == -1) { for(unsigned i = 0; i < nr_faces; i++) { fs << "f "; for (std::size_t j = 0; j < mesh.polygons[i].vertices.size () - 1; ++j) fs << mesh.polygons[i].vertices[j] + 1 << " "; fs << mesh.polygons[i].vertices.back() + 1 << '\n'; } } else { for(unsigned i = 0; i < nr_faces; i++) { fs << "f "; for (std::size_t j = 0; j < mesh.polygons[i].vertices.size () - 1; ++j) fs << mesh.polygons[i].vertices[j] + 1 << "//" << mesh.polygons[i].vertices[j] + 1 << " "; fs << mesh.polygons[i].vertices.back() + 1 << "//" << mesh.polygons[i].vertices.back() + 1 << '\n'; } } fs << "# End of File" << std::endl; // Close obj file fs.close (); return 0; }
e4c37564e7d267afa7572746a45f0b505c966728
e099f3450ccb982c9fa06f6d411a3b1d99b5c8d1
/test/redis/server/test/test11.cpp
50d807168792df89f1b06f1deb8d2620e22b2cab
[]
no_license
Request2609/summer2019
71d9370edd9be3d703a86695400201cee11b34ef
2e621b2d9c7278c7f897cc1cd98ad01ea950b661
refs/heads/master
2022-02-18T04:08:58.495086
2019-09-04T15:18:45
2019-09-04T15:18:45
197,857,588
1
0
null
null
null
null
UTF-8
C++
false
false
692
cpp
test11.cpp
#include <iostream> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <string.h> using namespace std ; int main() { int fd = open("hello",O_RDWR) ; if(fd < 0) { cout << __FILE__ << " " << __LINE__ << endl ; return 1; } char name[1024] ; bzero(name, sizeof(name)) ; if(pread(fd,name, 5, 10) < 0) { cout << "fsafdf" << endl ; return 1; } cout << name << endl ; close(fd) ; fd = open("hello", O_CREAT|O_WRONLY|O_APPEND, 0766) ; if(fd < 0) { cout << "创建出错!" <<" " << strerror(errno)<< endl ; return 1; } pwrite(fd, name, 5, 50) ; close(fd) ; return 0; }
d44a8f7582bfe0b2ddd05bee5666d79629b6100f
48f675a59e5b9fb9b4ef8c6bf935ee059ef241c3
/tools/compute_intersection.cpp
df9280d8dc94d228c7279f558991d42d3c5ed2eb
[ "Apache-2.0" ]
permissive
pisa-engine/pisa
dab4c401e80de1d643ec4e5009fd5d0d672dd223
490eb0d007f7030a8a66c9f58268a0ee115c6a6a
refs/heads/master
2023-09-05T09:32:11.009768
2023-08-11T01:09:53
2023-08-15T10:54:08
150,449,350
806
72
Apache-2.0
2023-08-19T15:01:06
2018-09-26T15:32:52
C++
UTF-8
C++
false
false
4,768
cpp
compute_intersection.cpp
#include <limits> #include <optional> #include <string> #include <vector> #include "mappable/mapper.hpp" #include <CLI/CLI.hpp> #include <fmt/format.h> #include <range/v3/view/filter.hpp> #include <spdlog/sinks/stdout_color_sinks.h> #include <spdlog/spdlog.h> #include "app.hpp" #include "index_types.hpp" #include "intersection.hpp" #include "pisa/cursor/scored_cursor.hpp" #include "pisa/query/queries.hpp" #include "wand_data_raw.hpp" using namespace pisa; using pisa::intersection::IntersectionType; using pisa::intersection::Mask; template <typename IndexType, typename WandType, typename QueryRange> void intersect( std::string const& index_filename, std::optional<std::string> const& wand_data_filename, QueryRange&& queries, IntersectionType intersection_type, std::optional<std::uint8_t> max_term_count = std::nullopt) { IndexType index; mio::mmap_source m(index_filename.c_str()); mapper::map(index, m); WandType wdata; mio::mmap_source md; if (wand_data_filename) { std::error_code error; md.map(*wand_data_filename, error); if (error) { spdlog::error("error mapping file: {}, exiting...", error.message()); std::abort(); } mapper::map(wdata, md, mapper::map_flags::warmup); } std::size_t qid = 0U; auto print_intersection = [&](auto const& query, auto const& mask) { auto intersection = Intersection::compute(index, wdata, query, mask); std::cout << fmt::format( "{}\t{}\t{}\t{}\n", query.id ? *query.id : std::to_string(qid), mask.to_ulong(), intersection.length, intersection.max_score); }; for (auto&& query: queries) { if (intersection_type == IntersectionType::Combinations) { for_all_subsets(query, max_term_count, print_intersection); } else { auto intersection = Intersection::compute(index, wdata, query); std::cout << fmt::format( "{}\t{}\t{}\n", query.id ? *query.id : std::to_string(qid), intersection.length, intersection.max_score); } qid += 1; } } using wand_raw_index = wand_data<wand_data_raw>; int main(int argc, const char** argv) { spdlog::drop(""); spdlog::set_default_logger(spdlog::stderr_color_mt("")); std::optional<std::uint8_t> max_term_count; std::size_t min_query_len = 0; std::size_t max_query_len = std::numeric_limits<std::size_t>::max(); bool combinations = false; bool header = false; App<arg::Index, arg::WandData<arg::WandMode::Required>, arg::Query<arg::QueryMode::Unranked>, arg::LogLevel> app{"Computes intersections of posting lists."}; auto* combinations_flag = app.add_flag( "--combinations", combinations, "Compute intersections for combinations of terms in query"); app.add_option( "--max-term-count,--mtc", max_term_count, "Max number of terms when computing combinations") ->needs(combinations_flag); app.add_option("--min-query-len", min_query_len, "Minimum query length"); app.add_option("--max-query-len", max_query_len, "Maximum query length"); app.add_flag("--header", header, "Write TSV header"); CLI11_PARSE(app, argc, argv); spdlog::set_level(app.log_level()); auto queries = app.queries(); auto filtered_queries = ranges::views::filter(queries, [&](auto&& query) { auto size = query.terms.size(); return size < min_query_len || size > max_query_len; }); if (header) { if (combinations) { std::cout << "qid\tterm_mask\tlength\tmax_score\n"; } else { std::cout << "qid\tlength\tmax_score\n"; } } IntersectionType intersection_type = combinations ? IntersectionType::Combinations : IntersectionType::Query; /**/ if (false) { #define LOOP_BODY(R, DATA, T) \ } \ else if (app.index_encoding() == BOOST_PP_STRINGIZE(T)) \ { \ intersect<BOOST_PP_CAT(T, _index), wand_raw_index>( \ app.index_filename(), \ app.wand_data_path(), \ filtered_queries, \ intersection_type, \ max_term_count); \ /**/ BOOST_PP_SEQ_FOR_EACH(LOOP_BODY, _, PISA_INDEX_TYPES); #undef LOOP_BODY } else { spdlog::error("Unknown type {}", app.index_encoding()); } }
a113f22d29ac8db24a8cead5805abf822d5aeae7
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/Runtime/Engine/Classes/Particles/Parameter/ParticleModuleParameterDynamic.h
53509717c23a20fc255cfdaf7d96cabff3988e5a
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
8,056
h
ParticleModuleParameterDynamic.h
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /** * * */ #pragma once #include "CoreMinimal.h" #include "UObject/ObjectMacros.h" #include "Particles/ParticleModule.h" #include "Distributions/DistributionFloatConstant.h" #include "Particles/Parameter/ParticleModuleParameterBase.h" #include "ParticleEmitterInstances.h" #include "Particles/ParticleSystemComponent.h" #include "ParticleModuleParameterDynamic.generated.h" class UInterpCurveEdSetup; class UParticleEmitter; class UParticleLODLevel; class UParticleModuleTypeDataBase; /** * EmitterDynamicParameterValue * Enumeration indicating the way a dynamic parameter should be set. */ UENUM() enum EEmitterDynamicParameterValue { /** UserSet - use the user set values in the distribution (the default) */ EDPV_UserSet, /** AutoSet - ignore values set in the distribution, another module will handle this data */ EDPV_AutoSet, /** VelocityX - pass the particle velocity along the X-axis thru */ EDPV_VelocityX, /** VelocityY - pass the particle velocity along the Y-axis thru */ EDPV_VelocityY, /** VelocityZ - pass the particle velocity along the Z-axis thru */ EDPV_VelocityZ, /** VelocityMag - pass the particle velocity magnitude thru */ EDPV_VelocityMag, EDPV_MAX, }; /** Helper structure for displaying the parameter. */ USTRUCT() struct FEmitterDynamicParameter { GENERATED_USTRUCT_BODY() /** The parameter name - from the material DynamicParameter expression. READ-ONLY */ UPROPERTY(Category=EmitterDynamicParameter, VisibleAnywhere) FName ParamName; /** If true, use the EmitterTime to retrieve the value, otherwise use Particle RelativeTime. */ UPROPERTY(EditAnywhere, Category=EmitterDynamicParameter) uint32 bUseEmitterTime:1; /** If true, only set the value at spawn time of the particle, otherwise update each frame. */ UPROPERTY(EditAnywhere, Category=EmitterDynamicParameter) uint32 bSpawnTimeOnly:1; /** Where to get the parameter value from. */ UPROPERTY(EditAnywhere, Category=EmitterDynamicParameter) TEnumAsByte<enum EEmitterDynamicParameterValue> ValueMethod; /** If true, scale the velocity value selected in ValueMethod by the evaluated ParamValue. */ UPROPERTY(EditAnywhere, Category=EmitterDynamicParameter) uint32 bScaleVelocityByParamValue:1; /** The distriubtion for the parameter value. */ UPROPERTY(EditAnywhere, Category=EmitterDynamicParameter) struct FRawDistributionFloat ParamValue; FEmitterDynamicParameter() : bUseEmitterTime(false) , bSpawnTimeOnly(false) , ValueMethod(0) , bScaleVelocityByParamValue(false) { } FEmitterDynamicParameter(FName InParamName, uint32 InUseEmitterTime, TEnumAsByte<enum EEmitterDynamicParameterValue> InValueMethod, UDistributionFloatConstant* InDistribution) : ParamName(InParamName) , bUseEmitterTime(InUseEmitterTime) , bSpawnTimeOnly(false) , ValueMethod(InValueMethod) , bScaleVelocityByParamValue(false) { ParamValue.Distribution = InDistribution; } }; UCLASS(editinlinenew, hidecategories=Object, MinimalAPI, meta=(DisplayName = "Dynamic")) class UParticleModuleParameterDynamic : public UParticleModuleParameterBase { GENERATED_UCLASS_BODY() /** The dynamic parameters this module uses. */ UPROPERTY(EditAnywhere, editfixedsize, Category=ParticleModuleParameterDynamic) TArray<struct FEmitterDynamicParameter> DynamicParams; /** Flags for optimizing update */ UPROPERTY() int32 UpdateFlags; UPROPERTY() uint32 bUsesVelocity:1; /** Initializes the default values for this property */ void InitializeDefaults(); //Begin UObject Interface virtual void PostLoad() override; #if WITH_EDITOR virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override; #endif // WITH_EDITOR virtual void PostInitProperties() override; //~ Begin UObject Interface //~ Begin UParticleModule Interface virtual void Spawn(FParticleEmitterInstance* Owner, int32 Offset, float SpawnTime, FBaseParticle* ParticleBase) override; virtual void Update(FParticleEmitterInstance* Owner, int32 Offset, float DeltaTime) override; virtual uint32 RequiredBytes(UParticleModuleTypeDataBase* TypeData) override; virtual void SetToSensibleDefaults(UParticleEmitter* Owner) override; virtual void GetCurveObjects(TArray<FParticleCurvePair>& OutCurves) override; virtual bool WillGeneratedModuleBeIdentical(UParticleLODLevel* SourceLODLevel, UParticleLODLevel* DestLODLevel, float Percentage) override { // The assumption is that at 100%, ANY module will be identical... // (Although this is virtual to allow over-riding that assumption on a case-by-case basis!) return true; } virtual void GetParticleSysParamsUtilized(TArray<FString>& ParticleSysParamList) override; virtual void GetParticleParametersUtilized(TArray<FString>& ParticleParameterList) override; virtual void RefreshModule(UInterpCurveEdSetup* EdSetup, UParticleEmitter* InEmitter, int32 InLODLevel) override; //~ End UParticleModule Interface /** * Extended version of spawn, allows for using a random stream for distribution value retrieval * * @param Owner The particle emitter instance that is spawning * @param Offset The offset to the modules payload data * @param SpawnTime The time of the spawn * @param InRandomStream The random stream to use for retrieving random values */ void SpawnEx(FParticleEmitterInstance* Owner, int32 Offset, float SpawnTime, struct FRandomStream* InRandomStream, FBaseParticle* ParticleBase); /** * Update the parameter names with the given material... * * @param InMaterialInterface Pointer to the material interface * @param bIsMeshEmitter true if the emitter is a mesh emitter... * */ virtual void UpdateParameterNames(UMaterialInterface* InMaterialInterface); /** * Retrieve the value for the parameter at the given index. * * @param InDynParams The FEmitterDynamicParameter to fetch the value for * @param Particle The particle we are getting the value for. * @param Owner The FParticleEmitterInstance owner of the particle. * @param InRandomStream The random stream to use when retrieving the value * * @return float The value for the parameter. */ FORCEINLINE float GetParameterValue(FEmitterDynamicParameter& InDynParams, FBaseParticle& Particle, FParticleEmitterInstance* Owner, struct FRandomStream* InRandomStream) { float ScaleValue = 1.0f; float DistributionValue = 1.0f; switch (InDynParams.ValueMethod) { case EDPV_VelocityX: ScaleValue = Particle.Velocity.X; break; case EDPV_VelocityY: ScaleValue = Particle.Velocity.Y; break; case EDPV_VelocityZ: ScaleValue = Particle.Velocity.Z; break; case EDPV_VelocityMag: ScaleValue = Particle.Velocity.Size(); break; default: //case EDPV_UserSet: //case EDPV_AutoSet: break; } if ((InDynParams.bScaleVelocityByParamValue == true) || (InDynParams.ValueMethod == EDPV_UserSet)) { float TimeValue = InDynParams.bUseEmitterTime ? Owner->EmitterTime : Particle.RelativeTime; DistributionValue = InDynParams.ParamValue.GetValue(TimeValue, Owner->Component, InRandomStream); } return DistributionValue * ScaleValue; } /** * Retrieve the value for the parameter at the given index. * * @param InDynParams The FEmitterDynamicParameter to fetch the value for * @param Particle The particle we are getting the value for. * @param Owner The FParticleEmitterInstance owner of the particle. * @param InRandomStream The random stream to use when retrieving the value * * @return float The value for the parameter. */ FORCEINLINE float GetParameterValue_UserSet(FEmitterDynamicParameter& InDynParams, FBaseParticle& Particle, FParticleEmitterInstance* Owner, struct FRandomStream* InRandomStream) { return InDynParams.ParamValue.GetValue(InDynParams.bUseEmitterTime ? Owner->EmitterTime : Particle.RelativeTime, Owner->Component, InRandomStream); } /** * Set the UpdatesFlags and bUsesVelocity */ virtual void UpdateUsageFlags(); virtual bool CanTickInAnyThread() override; };
90a6216df543fa62b15432b25fb6400175701a86
3db7b8c57a434855137c6ca7e8d4fce49805329a
/include/net/singleton.h
cebd404a4704790210e6328a62edae91854987f5
[]
no_license
nightmeng/net
a3a364960e1bcb0f90504e52678484f68483b560
75c0197fe8c770eb742e22e1bcd57f631b071d56
refs/heads/master
2021-01-23T13:47:38.669510
2014-08-17T08:46:27
2014-08-17T08:46:27
22,311,555
7
2
null
null
null
null
UTF-8
C++
false
false
798
h
singleton.h
#ifndef __SINGLETON_H__ #define __SINGLETON_H__ #include <mutex> #include <memory> template<typename type> class singleton{ public: static singleton &instance(){ if(nullptr == _instance){ static std::mutex mutex; std::lock_guard<std::mutex> locker(mutex); if(nullptr == _instance){ _instance = std::shared_ptr<singleton>(new singleton); } } return *_instance; } type *operator->(){ return &object; } const type *operator->()const{ return &object; } private: singleton(){} singleton(const singleton&) = delete; singleton &operator=(const singleton&) = delete; private: static std::shared_ptr<singleton> _instance; type object; }; template <typename type> std::shared_ptr<singleton<type>> singleton<type>::_instance = nullptr; #endif
38cc9909b56e1ace5db9f24032be604224f3b8ba
e5553277151b09e3f56ebf2fc56d97e84b1ac925
/component/i-startable.h
814c6f6f9fb1ed7098dcdf2c6e59502f31247614
[ "MIT" ]
permissive
Dantetang/nsfx
9064d87003350c878d4ccac8dfa0dee7a29c7b85
ba5a00a7e7aa9f8ec3cfd18e1271120409287124
refs/heads/master
2021-03-21T03:52:47.322357
2020-03-12T08:21:06
2020-03-12T08:21:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,714
h
i-startable.h
/** * @file * * @brief Component support for Network Simulation Frameworks. * * @version 1.0 * @author Wei Tang <gauchyler@uestc.edu.cn> * @date 2018-10-25 * * @copyright Copyright (c) 2018. * National Key Laboratory of Science and Technology on Communications, * University of Electronic Science and Technology of China. * All rights reserved. */ #ifndef I_STARTABLE_H__0E290E97_A4DA_4B48_AA53_EE15B1B8D675 #define I_STARTABLE_H__0E290E97_A4DA_4B48_AA53_EE15B1B8D675 #include <nsfx/component/config.h> #include <nsfx/component/uid.h> #include <nsfx/component/i-object.h> NSFX_OPEN_NAMESPACE //////////////////////////////////////////////////////////////////////////////// /** * @ingroup Component * @brief A startable object. */ class IStartable : virtual public IObject { public: virtual ~IStartable(void) BOOST_NOEXCEPT {}; /** * @brief Put an object into running state. * * The *started* state is different from the *initialized* state. * * When an object exposes `IStartable` interface, it **shall** be in * stopped state initially. * * To be able to put an object into running state, the object **must** * have been initialized already. * Therefore, it is recommended to expose `IInitializable` to perform * *one-time* initialization, such as *wiring*; while expose `IStartable` * and `IStoppable` to allow runtime configuration/re-configuration, * such as setting parameters and connecting events. */ virtual void Start(void) = 0; }; NSFX_DEFINE_CLASS_UID(IStartable, "edu.uestc.nsfx.IStartable"); NSFX_CLOSE_NAMESPACE #endif // I_STARTABLE_H__0E290E97_A4DA_4B48_AA53_EE15B1B8D675
28d1b69f13c4d6c5ef3c015cce0da8519b4cc7e9
a5ab608bda92162f553dacce92fce0078004d820
/Visualization2/TextureDisplay.h
40d2ad4a7959f5a433d05a7f5e4e9df062653de1
[ "MIT" ]
permissive
kskeller/Subdivision
3f1851ce10d59aec1a4e9c8aebcb71e07ea7bfa2
74001b2ef76e23bf07f3c597f5ed01c1fe1720e7
refs/heads/master
2021-03-12T21:18:57.939122
2012-04-06T14:25:19
2012-04-06T14:25:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
878
h
TextureDisplay.h
#pragma once #include <QtGui/QGraphicsScene> #include <QtGui/QGraphicsPolygonItem> #include <QtCore/QPointF> #include <QtCore/QString> #include <QtGui/QGraphicsEllipseItem> #include <QtGui/QGraphicsSceneDragDropEvent> class TextureDisplay : public QGraphicsScene { Q_OBJECT public: TextureDisplay(); TextureDisplay( qreal x, qreal y, qreal width, qreal height, QObject * parent = 0 ); public slots: void setTexture(QString& file, QPointF& t1, QPointF& t2, QPointF& t3); void newTexture(QString& file); void setCoordinates(QPointF &t1, QPointF &t2, QPointF &t3); signals: void newTextures(QPointF & t1, QPointF &t2, QPointF &t3); protected: void drawBackground ( QPainter * painter, const QRectF & rect ); //void dragMoveEvent(QGraphicsSceneDragDropEvent *event); private: QGraphicsPolygonItem triangle; QImage background; QGraphicsEllipseItem p1,p2, p3; };
6ee8f6df2569f7a046a7b3d995aa31a5fee490c7
98e5fd588b356aff074e907c27aede0b609aae85
/codechefTutorial/8_Tree/dfs.cpp
87be57beed40daaca55f6a3262f4c24d8948af6c
[]
no_license
ayushshukla92/algorithms
060521612773e93bf4804abd5644fc35d4d32eb7
a3d5baa3c71de5fa9a8049d436c802c75ad32cd2
refs/heads/master
2016-08-12T02:01:53.233754
2015-11-04T11:09:00
2015-11-04T11:09:00
45,024,626
0
0
null
null
null
null
UTF-8
C++
false
false
1,549
cpp
dfs.cpp
/* Program to find cycles in undirected graph */ #include <iostream> #include <vector> using namespace std; struct graphNode { int val; graphNode* par; vector<graphNode *> neighbors; }; void printV(vector<int> &v) { for(int i: v) cout<<i<<' '; cout<<endl; } vector<graphNode *> makeGraph(int v) { vector<graphNode *> res; for(int i=0;i<v;i++) { graphNode* node = new graphNode; node->val = i; node->par = NULL; res.push_back(node); } return res; } void addEdge(vector<graphNode *> adj,int i, int j) { adj[i]->neighbors.push_back(adj[j]); adj[j]->neighbors.push_back(adj[i]); } void trace(int i, int j,vector<graphNode*> adj) { while(j!=i){ cout<<j<<"->"; if(adj[j]->par){ j= adj[j]->par->val; } else{ break; } } cout<<i<<endl; } void visit(vector<graphNode*> adj, int val, vector<bool>& visited) { visited[val] = true; for(graphNode* node : adj[val]->neighbors) { if(!visited[node->val]) { node->par = adj[val]; visit(adj,node->val,visited); } else if(adj[val]->par!=NULL && node->val != adj[val]->par->val) { trace(node->val,val,adj); } } } void hasCycle(vector<graphNode*> adj) { vector<bool> visited(adj.size(),false); for(graphNode* node : adj) { if(!visited[node->val]){ visit(adj,node->val,visited); } } return; } int main() { vector<graphNode *> adj = makeGraph(5); addEdge(adj,0,1); addEdge(adj,1,2); addEdge(adj,2,0); addEdge(adj,0,3); addEdge(adj,3,4); addEdge(adj,4,0); hasCycle(adj); return 0; }
97e3d57e1e0e8277321e752b24c97b7fb7dff8b6
3294fc8f5588f2eb29310e365c02c1fcfebf1f59
/HoudiniPlugin/texturingfluids/HoudiniPlugins/HoudiniPluginsDescriptions.cpp
8c4e98be69bc76e784efd2a6c77b163cebc6fd08
[]
no_license
josuperstar/Gagnon2016-Dynamic-Lapped-Texture
7460daff98ea8cabf0e7316e83fe04126224c996
26d58f66738c8704e45e6c027db5a3d00260de10
refs/heads/main
2023-02-15T12:24:32.384105
2021-01-05T16:21:04
2021-01-05T16:21:04
322,367,937
0
0
null
2020-12-22T18:26:51
2020-12-17T17:37:09
C++
UTF-8
C++
false
false
1,197
cpp
HoudiniPluginsDescriptions.cpp
#include <OP/OP_Director.h> #include "DynamicLappedTexturePlugin.h" #include "AtlasGagnon2016Plugin.h" // ----------------------------------------------------------------------------- // Add our plugins to Houdini's plugins list // ----------------------------------------------------------------------------- void newSopOperator(OP_OperatorTable *table) { table->addOperator(new OP_Operator("hdk_Gagnon2016", "DynamicLappedTexture", DynamicLappedTexturePlugin::myConstructor, DynamicLappedTexturePlugin::myTemplateList, 3, 3, 0)); table->addOperator(new OP_Operator("hdk_AtlasGagnon2016", "AtlasGagnon2016", AtlasGagnon2016Plugin::myConstructor, AtlasGagnon2016Plugin::myTemplateList, 2, 2, 0)); }
fb01212126587b178d6ba4e0cf16c8045ccbd496
84a96dbd96e926ebb5c658e3cb897db276c32d6c
/tensorflow/lite/delegates/gpu/cl/kernels/quantize_and_dequantize.cc
f7751fac6ffef37ddf27dd7469f7c9ce022e6c85
[ "Apache-2.0" ]
permissive
MothCreations/gavlanWheels
bc9189092847369ad291d1c7d3f4144dd2239359
01d8a43b45a26afec27b971f686f79c108fe08f9
refs/heads/master
2022-12-06T09:27:49.458800
2020-10-13T21:56:40
2020-10-13T21:56:40
249,206,716
6
5
Apache-2.0
2022-11-21T22:39:47
2020-03-22T14:57:45
C++
UTF-8
C++
false
false
4,929
cc
quantize_and_dequantize.cc
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/cl/kernels/quantize_and_dequantize.h" #include <string> #include "absl/strings/str_cat.h" #include "absl/types/variant.h" #include "tensorflow/lite/delegates/gpu/cl/kernels/util.h" #include "tensorflow/lite/delegates/gpu/common/tensor.h" namespace tflite { namespace gpu { namespace cl { QuantizeAndDequantize::QuantizeAndDequantize( const OperationDef& definition, const QuantizeAndDequantizeAttributes& attr, CalculationsPrecision scalar_precision) : ElementwiseOperation(definition) { min_ = FLT(scalar_precision, attr.min); max_ = FLT(scalar_precision, attr.max); scale_ = FLT(scalar_precision, attr.scale); } QuantizeAndDequantize::QuantizeAndDequantize(QuantizeAndDequantize&& operation) : ElementwiseOperation(std::move(operation)), min_(std::move(operation.min_)), max_(std::move(operation.max_)), scale_(std::move(operation.scale_)) {} QuantizeAndDequantize& QuantizeAndDequantize::operator=( QuantizeAndDequantize&& operation) { if (this != &operation) { min_ = std::move(operation.min_); max_ = std::move(operation.max_); scale_ = std::move(operation.scale_); ElementwiseOperation::operator=(std::move(operation)); } return *this; } void QuantizeAndDequantize::SetLinkIndex(int index) { min_.SetName(absl::StrCat("quantize_and_dequantize_min_", index)); max_.SetName(absl::StrCat("quantize_and_dequantize_max_", index)); scale_.SetName(absl::StrCat("quantize_and_dequantize_scale_", index)); } std::string QuantizeAndDequantize::GetCoreCode( const LinkingContext& context) const { std::string scale_string, max_string, min_string; if (!scale_.Active()) { scale_string = "(FLT4)(1.0f)"; } else { scale_string = absl::StrCat("(FLT4)(", scale_.GetName(), ")"); } if (!max_.Active()) { max_string = "(FLT4)(0.0f)"; } else { max_string = absl::StrCat("(FLT4)(", max_.GetName(), ")"); } if (!min_.Active()) { min_string = "(FLT4)(0.0f)"; } else { min_string = absl::StrCat("(FLT4)(", min_.GetName(), ")"); } std::string clamped_value = absl::StrCat( "min(", max_string, ", max(", min_string, ", ", context.var_name, "))"); std::string quantized_value = absl::StrCat( "round((", clamped_value, " - ", min_string, ") / ", scale_string, ")"); std::string dequantized_value = absl::StrCat(quantized_value, " * ", scale_string, " + ", min_string); return absl::StrCat(context.var_name, " = ", dequantized_value, ";\n"); } std::string QuantizeAndDequantize::GetArgsDeclaration() const { return absl::StrCat(",\n ", min_.GetDeclaration(), ",\n ", max_.GetDeclaration(), ",\n ", scale_.GetDeclaration()); } Status QuantizeAndDequantize::BindArguments(CLKernel* kernel) { RETURN_IF_ERROR(kernel->SetBytesAuto(min_)); RETURN_IF_ERROR(kernel->SetBytesAuto(max_)); RETURN_IF_ERROR(kernel->SetBytesAuto(scale_)); return OkStatus(); } Status CreateQuantizeAndDequantize(const CreationContext& creation_context, const OperationDef& definition, const QuantizeAndDequantizeAttributes& attr, QuantizeAndDequantize* result) { const auto scalar_precision = creation_context.device->IsPowerVR() ? CalculationsPrecision::F32 : definition.precision; const bool is_fp16 = definition.precision == CalculationsPrecision::F16 || definition.precision == CalculationsPrecision::F32_F16; if (is_fp16 && attr.scale < 0.000062f) { // The smallest positive normal number for Half-precision floating-point // format is 2^-14 ~ 0.000062f. Therefore, if the scale is lesser than this // number, we just reset it accordingly. QuantizeAndDequantizeAttributes adjusted_attr = attr; adjusted_attr.scale = 0.000062f; *result = QuantizeAndDequantize(definition, adjusted_attr, scalar_precision); } else { *result = QuantizeAndDequantize(definition, attr, scalar_precision); } result->SetLinkIndex(0); return OkStatus(); } } // namespace cl } // namespace gpu } // namespace tflite
7dc2d6fed918ae76f3c71507cfb46a39c6dc3502
01185326f71a0888c7351b00952c2aa24992a132
/RoVi-finalProject/SamplePluginPA10/src/FeatureExtraction.h
7b8e888806069556f7a3e2187c4c39e5f91f7496
[]
no_license
Javakin/7.semester
b33c3006cdb910496bd2852b8bf5c856f0e12227
ee4c94e9bf6ef32b34a561119333af663947a914
refs/heads/master
2021-03-16T05:46:56.169124
2018-03-16T10:37:21
2018-03-16T10:38:43
103,542,754
0
0
null
null
null
null
UTF-8
C++
false
false
1,627
h
FeatureExtraction.h
// // Created by student on 12/10/17. // #ifndef FEATUREEXTRACTION_FEATUREEXTRACTION_H #define FEATUREEXTRACTION_FEATUREEXTRACTION_H #include <stdio.h> #include <iostream> #include "opencv2/core.hpp" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include "opencv2/xfeatures2d.hpp" #include "opencv2/features2d.hpp" #include "opencv2/highgui.hpp" // RobWork includes #include <rw/models/WorkCell.hpp> #include <rw/kinematics/State.hpp> #include <rwlibs/opengl/RenderImage.hpp> #include <rwlibs/simulation/GLFrameGrabber.hpp> #include <rw/kinematics/MovableFrame.hpp> #include <rw/math.hpp> // Pi, Deg2Rad #include <rw/math/Q.hpp> #include <rw/math/Transform3D.hpp> #include <rw/math/RPY.hpp> #include <rw/math/Vector3D.hpp> #include <rw/math/EAA.hpp> #include <rw/loaders/ImageLoader.hpp> #include <rw/loaders/WorkCellFactory.hpp> //#include <rw/rw.hpp> // RobWorkStudio includes #include <RobWorkStudioConfig.hpp> // For RWS_USE_QT5 definition #include <rws/RobWorkStudioPlugin.hpp> #include <rws/RobWorkStudio.hpp> #include "opencv2/calib3d/calib3d.hpp" using namespace cv; using namespace std; using namespace cv::xfeatures2d; class FeatureExtraction { public: //FeatureExtraction(); FeatureExtraction(int iHassanThreshhold, rw::common::LogWriter &log); // generate the feachures void setMarker(Mat mMarker); vector<Point2f> matchfeachures(Mat mImage); private: cv::Ptr<SURF> detector; std::vector<KeyPoint> vKeyPointsMarker; Mat mDescriptorsMaker; Mat mMarker; rw::common::LogWriter &log; }; #endif //FEATUREEXTRACTION_FEATUREEXTRACTION_H
adef28c3a9ee0344553d1fd4b3496af3dd1c426c
dc405c87bd32b19c7cac6010f767c117992e1007
/XFileAnimation/JN_Base3D.cpp
022acc7cb308262994f48527bcdec5cd4b0edf52
[]
no_license
KimHyeongJin/MyDirect3D
72ed8898446e3638a30a8a9ea88237333812cc9f
ecb89eb51f4292b286d08742b0067437444edbe1
refs/heads/master
2020-05-30T10:32:19.547788
2015-07-07T01:30:50
2015-07-07T01:30:50
20,891,652
0
0
null
null
null
null
UHC
C++
false
false
2,617
cpp
JN_Base3D.cpp
#include "StdAfx.h" #include "JN_Base3D.h" namespace JN_Base3D { HINSTANCE m_hInst = NULL; //인스턴스의 핸들선언(운영체제에서 정해줄 번호) HWND m_hWnd = NULL; //윈도우의 핸들(윈도우를 대표하는 번호) LPDIRECT3D9 m_pd3d = NULL; //< iDirect 객체 인터페이스 얻기 LPDIRECT3DDEVICE9 m_pd3dDevice = NULL; //< 장치 디바이스얻기 //< d3d초기화 HRESULT Init3D( HWND hWnd , HINSTANCE hInst, BOOL bWindowMode, INT nWidth, INT nHeight ) { m_hWnd = hWnd; m_hInst = hInst; //< d3d객체 인터페이스 생성 m_pd3d = Direct3DCreate9( D3D_SDK_VERSION ); //< 예외 처리 if( m_pd3d == NULL ) { //< 에러 return E_FAIL; } //< 하드웨어 가속 여부 확인 (Caps) D3DCAPS9 caps; //< 장치 정보 DWORD dwVp; //< 버텍스 프로세싱 D3DDEVTYPE sDevType; m_pd3d->GetDeviceCaps(D3DADAPTER_DEFAULT , D3DDEVTYPE_HAL, &caps); if( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) { dwVp = D3DCREATE_HARDWARE_VERTEXPROCESSING; sDevType = D3DDEVTYPE_HAL; } else { dwVp = D3DCREATE_SOFTWARE_VERTEXPROCESSING; sDevType = D3DDEVTYPE_SW; } //< D3D파라메터 설정 D3DPRESENT_PARAMETERS d3dpp; ZeroMemory(&d3dpp,sizeof(D3DPRESENT_PARAMETERS)); d3dpp.BackBufferWidth = nWidth; d3dpp.BackBufferHeight = nHeight; d3dpp.BackBufferCount = 1; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8; d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8; d3dpp.EnableAutoDepthStencil = TRUE; d3dpp.Windowed = bWindowMode; //< 디바이스 생성 if( FAILED(m_pd3d->CreateDevice( D3DADAPTER_DEFAULT, sDevType, m_hWnd, dwVp, &d3dpp, &m_pd3dDevice))) { //< 디바이스 예외 처리 return E_FAIL; } //< 끝~~ return S_OK; } //< 해제 VOID Release( VOID ) { SAFE_RELEASE(m_pd3dDevice); SAFE_RELEASE(m_pd3d); } //< d3d 서페이스 초기화 HRESULT ClearScreen( D3DCOLOR Color ) { if( m_pd3dDevice == NULL ) { return E_FAIL; } return m_pd3dDevice->Clear(0,NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, Color,1,0); } //< 그리기 시작 HRESULT RenderStart( VOID ) { if( m_pd3dDevice == NULL ) { return E_FAIL; } return m_pd3dDevice->BeginScene(); } //< 그리기 종료 HRESULT RenderEnd( VOID ) { if( m_pd3dDevice == NULL ) { return E_FAIL; } return m_pd3dDevice->EndScene(); } //< 화면 출력 HRESULT Present( VOID ) { return m_pd3dDevice->Present(NULL,NULL,NULL,NULL); } }//< namespace end
0db83ef8b7616b737a161063cd4c3d74ca81f73d
79f95724ab6bfc62da99d8af108a2791502b2a6b
/麻将代码/血战,保存游戏进度/src/zjh.cc
124760b35818de014b59816dc724e4881ad4c268
[]
no_license
1311932023/git-work
32e4214ad9da6a5ac6b0d16402dade03cbeb0778
81b00ee127ac9e0661af135fdefde8a541b7a6ec
refs/heads/master
2020-03-24T16:37:04.561978
2018-07-30T05:45:14
2018-07-30T05:45:14
142,830,287
0
0
null
null
null
null
UTF-8
C++
false
false
5,599
cc
zjh.cc
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/time.h> #include <sys/resource.h> #include <unistd.h> #include <errno.h> #include <iostream> #include <fstream> #include <string> #include <vector> #include <ev.h> #include "zjh.h" #include "game.h" #include "game_serialize.hpp" #include "common/client.h" #include "common/daemonize.h" #include "common/log.h" #include "libnormalmahjong/game_logic.h" static int parse_arg(int argc, char **argv); static int init_conf(); static int set_rlimit(int n); static int init_redis(); ZJH zjh; Log log; const Game* game = zjh.game; int main(int argc, char **argv) { int ret; srand(time(NULL)); zjh.deleteArchive = false; ret = parse_arg(argc, argv); if (ret < 0) { log_fatal("File: %s Func: %s Line: %d => parse_arg.\n", __FILE__, __FUNCTION__, __LINE__); exit(1); } ret = init_conf(); if (ret < 0) { log_fatal("File: %s Func: %s Line: %d => init_conf.\n", __FILE__, __FUNCTION__, __LINE__); exit(1); } if (zjh.is_daemonize == 1) daemonize(); signal(SIGPIPE, SIG_IGN); ret = single_instance_running(zjh.conf.get("pid_file", "conf/normalmahjong.pid").asString().c_str()); if (ret < 0) { log_fatal("File: %s Func: %s Line: %d => single_instance_running.\n", __FILE__, __FUNCTION__, __LINE__); exit(1); } Log::Instance().start("./log/majiang.log", 5, 0, 1, 999999, 10); log_info("--start--"); /*log.start(zjh.conf["log"].get("log_file", "log/normalmahjong.log").asString(), zjh.conf["log"].get("level", 5).asInt(), zjh.conf["log"].get("console", 0).asInt(), zjh.conf["log"].get("rotate", 1).asInt(), zjh.conf["log"].get("max_size", 1073741824).asInt(), zjh.conf["log"].get("max_file", 10).asInt());*/ set_rlimit(10240); // ret = acp_req(zjh.conf, &RegInit); // log_error("the from fuction ret[%d]\n", ret ); // if (ret != 0) { // exit(0); // } // Library *library = new (std::nothrow) Library(); // ret = library->init("conf/library.json"); // if (ret < 0) { // log_fatal("init card library failed.\n"); // exit(1); // } // zjh.library = library; if (zjh.conf["main-db"].size() != 0) { ret = init_redis(); if (ret < 0) //connect redis { log_fatal("init redis failed\n"); exit(1); } } // ScreenWord * screenword = new(std::nothrow) ScreenWord; // ret = screenword->init("conf/screenword.conf"); // if( ret < 0 ) // { // log_fatal("init screenword failed .\n"); // exit(1); // } // zjh.p_sreenword = screenword; struct ev_loop *loop = ev_default_loop(0); zjh.loop = loop; { /*std::string filename = "demofile.txt";*/ /*std::ifstream ifs;*/ /*ifs.open(filename.c_str());*/ if (zjh.deleteArchive) { zjh.main_rc[0]->command("del archiveStr:%d", 1); } std::string* archiveStr = new std::string(); int ret = zjh.main_rc[0]->command("get archiveStr:%d", 1); if (ret < 0 || zjh.main_rc[0]->reply->str == NULL) { printf("new (std::nothrow) Game()\n"); zjh.game = new (std::nothrow) Game(); } else { printf("ia >> zjh\n"); *archiveStr = zjh.main_rc[0]->reply->str; std::istringstream* archiveStream = new std::istringstream(*archiveStr); assert(archiveStream->good()); boost::archive::text_iarchive* ia = new boost::archive::text_iarchive(*archiveStream); (*ia) >> BOOST_SERIALIZATION_NVP(zjh); zjh.game->restart(); } zjh.main_rc[0]->command("del archiveStr:%d", 1); /*if (ifs) { { printf("ia >> zjh\n"); boost::archive::binary_iarchive ia(ifs); ia >> zjh; } ifs.close(); zjh.game->restart(); } else { printf("new (std::nothrow) Game()\n"); zjh.game = new (std::nothrow) Game(); }*/ game = zjh.game; } zjh.game->Start(); // if ( zjh.conf["open_redis"].asInt() ) // { // CRedisCache::GetInstance().StartClearTime(zjh.conf["timers"]["redis_call_ptime"].asInt()); // } ev_loop(loop, 0); return 0; } static int parse_arg(int argc, char **argv) { int flag = 0; int oc; /* option chacb. */ char ic; /* invalid chacb. */ zjh.is_daemonize = 0; while ((oc = getopt(argc, argv, "Dyf:")) != -1) { switch (oc) { case 'D': zjh.is_daemonize = 1; break; case 'f': flag = 1; zjh.conf_file = string(optarg); break; case 'y': zjh.deleteArchive = true; break; case '?': ic = (char) optopt; printf("invalid \'%c\'\n", ic); break; case ':': printf("lack option arg\n"); break; } } if (flag == 0) return -1; return 0; } static int init_conf() { std::ifstream in(zjh.conf_file.c_str(), std::ifstream::binary); if (!in) { std::cout << "init file no found." << endl; return -1; } Json::Reader reader; bool ret = reader.parse(in, zjh.conf); if (!ret) { in.close(); std::cout << "init file parser." << endl; return -1; } in.close(); return 0; } static int set_rlimit(int n) { struct rlimit rt; rt.rlim_max = rt.rlim_cur = n; if (setrlimit(RLIMIT_NOFILE, &rt) == -1) { log_error("File: %s Func: %s Line: %d => setrlimit %s.\n", __FILE__, __FUNCTION__, __LINE__, strerror(errno)); return -1; } return 0; } static int init_redis() { int ret; zjh.main_size = zjh.conf["main-db"].size(); for (int i = 0; i < zjh.main_size; i++) { zjh.main_rc[i] = new RedisClient(); ret = zjh.main_rc[i]->init(zjh.conf["main-db"][i]["host"].asString(), zjh.conf["main-db"][i]["port"].asInt(), 1000, zjh.conf["main-db"][i]["pass"].asString()); if (ret < 0) { log_error("main db redis error\n"); return -1; } } return 0; }
50ea92d464efad3226d3c6ffd7a51e2ff34f60c2
70314ffe48dd5c6a1c8e9f7f13baa16af2e2cbef
/BOJ/가장긴 바이토닉 수열.cpp
5090bac0a69cee265fb1c435cff8992ed64248a0
[]
no_license
WiseCow/algorithm
2cb2a0a1d1fa37bd69d36506792f8f75133382d7
1b86951116f610d90d636f843652930f71141ddf
refs/heads/master
2021-01-17T20:38:09.496349
2019-01-09T14:11:08
2019-01-09T14:11:08
68,787,903
0
0
null
null
null
null
UTF-8
C++
false
false
603
cpp
가장긴 바이토닉 수열.cpp
#include<cstdio> #define MAX(a,b) a>b?a:b int main() { int N; scanf("%d", &N); int arr[1001], U[1001], D[1001]; for (int i = 1; i <= N; i++) { scanf("%d", &arr[i]); D[i] = U[i] = 1; } for (int i = N-1; i >= 1; i--) { for (int j = N; j >i; j--) { if (arr[j] < arr[i]) { D[i] = MAX(D[i], D[j] + 1); } } } for (int i = 2; i <= N; i++) { for (int j = 1; j < i; j++) { if (arr[j] < arr[i]) { U[i] = MAX(U[i], U[j] + 1); } } } int k = 1; for (int i = 1; i <= N; i++)k = MAX(k, D[i]+U[i]); printf("%d", k-1); }
961088ad054dee8d425fd62ab0a433a4a231077d
f4075623a701d16170be2f6f9b738f485e5b1a42
/sources/Android/sdk/src/main/cpp/luamobilesdk/src/LuaMetaTable.cc
e121580ef111337b01bb2a28978a03960449f4bf
[ "MIT" ]
permissive
arnozhang/LuaMobileSdk
3e67f5f82f7b1f3500dd83f8df76f6899853c60a
1ffa7742a9f2dc776e61a7bcd698e74da775d04a
refs/heads/master
2020-03-10T11:56:21.991197
2018-04-13T07:55:46
2018-04-13T07:55:46
109,638,551
0
0
null
null
null
null
UTF-8
C++
false
false
5,161
cc
LuaMetaTable.cc
/** * Android LuaMobileSdk for Android framework project. * * Copyright 2016 Arno Zhang <zyfgood12@163.com> * * 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 "LuaMetaTable.h" #include "Utils.h" int LuaMetaTable::object_luaCallInvoker(lua_State* ls) { if (!Utils::isJavaFunction(ls, 1)) { Utils::luaError(ls, "Not a BridgedFunction!! cannot invoke!"); return 0; } JNIEnv* env = Utils::getJniEnvFromState(ls); if (!env) { Utils::luaError(ls, "Cannot get JNIEnv from lua_State!"); return 0; } jobject* pObj = (jobject*) lua_touserdata(ls, 1); int ret = env->CallIntMethod( *pObj, BridgedJavaClassInfo::method::BridgedFunction_invoke); jthrowable exception = env->ExceptionOccurred(); Utils::handleJavaException(env, ls, exception); return ret; } int LuaMetaTable::object_luaGcInvoker(lua_State* ls) { int type = Utils::getBridgedType(ls, 1); if (type != BridgedType::JavaObject && type != BridgedType::JavaFunction) { return 0; } jobject* pObj = (jobject*) lua_touserdata(ls, 1); auto env = Utils::getJniEnvFromState(ls); if (env && pObj) { env->DeleteGlobalRef(*pObj); } return 0; } int LuaMetaTable::meta_callBridgedFunction(lua_State* ls, const char* const funcName) { if (!lua_istable(ls, 1) && !lua_isuserdata(ls, 1)) { Utils::luaError(ls, "Not a Table or UserData!! cannot invoke meta-method!"); return 0; } JNIEnv* env = Utils::getJniEnvFromState(ls); if (!env) { Utils::luaError(ls, "Cannot get JNIEnv from lua_State!"); return 0; } if (!lua_getmetatable(ls, 1)) { lua_pop(ls, 1); lua_pushnil(ls); return 1; } if (!lua_istable(ls, -1) && !lua_isuserdata(ls, -1)) { lua_pop(ls, 1); lua_pushnil(ls); return 1; } // arg1, arg2, ... obj.meta, obj.meta.__java_meta_funcs, javaBridgeFunc lua_getfield(ls, -1, LuaMetaTable::__java_meta_funcs); lua_pushstring(ls, funcName); lua_rawget(ls, -2); jobject* pObj = (jobject*) lua_touserdata(ls, -1); lua_pop(ls, 3); int ret = 0; if (pObj) { ret = env->CallIntMethod( *pObj, BridgedJavaClassInfo::method::BridgedFunction_invoke); jthrowable exception = env->ExceptionOccurred(); Utils::handleJavaException(env, ls, exception); } return ret; } int LuaMetaTable::meta_luaCallInvoker(lua_State* ls) { return meta_callBridgedFunction(ls, LuaMetaTable::__call); } int LuaMetaTable::meta_luaLenInvoker(lua_State* ls) { return meta_callBridgedFunction(ls, LuaMetaTable::__len); } int LuaMetaTable::meta_luaIndexInvoker(lua_State* ls) { return meta_callBridgedFunction(ls, LuaMetaTable::__index); } int LuaMetaTable::meta_luaNewIndexInvoker(lua_State* ls) { return meta_callBridgedFunction(ls, LuaMetaTable::__index); } int LuaMetaTable::meta_luaClassFunctionIndexInvoker(lua_State* ls) { // a.__index = function(a, name) ... end // 1 2 // // obj -> upvalue(1) lua_pushvalue(ls, 1); // name -> upvalue(2) lua_pushvalue(ls, 2); lua_pushcclosure(ls, &LuaMetaTable::meta_memberFunctionInvokeClosure, 2); return 1; } int LuaMetaTable::meta_memberFunctionInvokeClosure(lua_State* ls) { auto env = Utils::getJniEnvFromState(ls); if (!env) { return 0; } int argsCount = lua_gettop(ls); int objIndex = lua_upvalueindex(1); int nameIndex = lua_upvalueindex(2); if (!lua_istable(ls, objIndex) && !lua_isuserdata(ls, objIndex)) { return 0; } if (!lua_getmetatable(ls, objIndex)) { return 0; } // arg1, arg2, ... obj.meta, obj.meta.__java_member_funcs lua_getfield(ls, -1, LuaMetaTable::__java_member_funcs); // arg1, arg2, ... obj.meta, obj.meta.__java_member_funcs, javaBridgeFunc lua_pushvalue(ls, nameIndex); lua_rawget(ls, -2); jobject* pObj = (jobject*) lua_touserdata(ls, -1); lua_pop(ls, 3); int ret = 0; if (pObj) { // obj lua_pushvalue(ls, objIndex); lua_insert(ls, 1); // placeholder lua_pushnil(ls); lua_insert(ls, 1); // nil, obj, arg1, arg2, ... ret = env->CallIntMethod( *pObj, BridgedJavaClassInfo::method::BridgedFunction_invoke); jthrowable exception = env->ExceptionOccurred(); Utils::handleJavaException(env, ls, exception); // balance stack. remove placeholder and args. lua_remove(ls, 1); lua_remove(ls, 1); } return ret; }
c06c6a00a18d8aa4ef3f85e16786abf383ad8a39
b9b90ec865e4e12e47f72b64e4a00c29fa7e61fb
/cflw代码库/cflw多媒体.h
f71d5f33413976a0f4e38a8ebae6b08093448fd3
[ "MIT" ]
permissive
cflw/cflw_cpp
b8d06d0ad8b1d7b439150c41177b519613f25ebb
b77d4f83e158f80fcf56552256978fc726b54cac
refs/heads/master
2023-02-15T16:58:02.613386
2023-01-27T13:06:14
2023-01-27T13:06:14
143,597,047
13
1
null
null
null
null
UTF-8
C++
false
false
1,154
h
cflw多媒体.h
#pragma once #include <mmstream.h> #pragma comment(lib, "winmm.lib") namespace cflw::多媒体 { //============================================================================== //mmsystem.h //============================================================================== typedef WAVEFORMATEX t波形格式; //行:782-792 inline DWORD f取开机时间() { return timeGetTime(); }; //行:2205 //============================================================================== //辅助 //============================================================================== //块格式 constexpr DWORD c块RIFF = mmioFOURCC('R', 'I', 'F', 'F'); constexpr DWORD c块data = mmioFOURCC('d', 'a', 't', 'a'); constexpr DWORD c块fmt = mmioFOURCC('f', 'm', 't', ' '); constexpr DWORD c块WAVE = mmioFOURCC('W', 'A', 'V', 'E'); constexpr DWORD c块XWMA = mmioFOURCC('X', 'W', 'M', 'A'); constexpr DWORD c块dpds = mmioFOURCC('d', 'p', 'd', 's'); //函数 HRESULT FindChunk(HANDLE hFile, DWORD fourcc, DWORD &dwChunkSize, DWORD &dwChunkDataPosition); HRESULT ReadChunkData(HANDLE hFile, void *buffer, DWORD buffersize, DWORD bufferoffset); } //namespace cflw::多媒体
4d61e3828b990e996dd6848a0d633fd640950b20
1c8d4f0ee5cc521e954b7636b47fc406abae79bf
/BB8_main/BB8_main.ino
5abdc018b4f0bbcb7a61fbd2dbb3d982f64f202e
[]
no_license
calvinterpstra/BB_8
8d9103119fcdaa12b44746d6b17866914e6a0c0b
7d7bb21ddc68c8e084666c226ddd9532ecbf471f
refs/heads/master
2020-04-25T21:23:02.355242
2019-04-08T09:40:44
2019-04-08T09:40:44
173,078,431
0
1
null
2019-03-18T10:17:37
2019-02-28T09:06:26
C++
UTF-8
C++
false
false
11,237
ino
BB8_main.ino
#include <Wire.h> #include <TimerOne.h> #include <SoftwareSerial.h> #define MPU9250_ADDRESS 0x68 #define MAG_ADDRESS 0x0C #define GYRO_FULL_SCALE_250_DPS 0x00 #define GYRO_FULL_SCALE_500_DPS 0x08 #define GYRO_FULL_SCALE_1000_DPS 0x10 #define GYRO_FULL_SCALE_2000_DPS 0x18 #define ACC_FULL_SCALE_2_G 0x00 #define ACC_FULL_SCALE_4_G 0x08 #define ACC_FULL_SCALE_8_G 0x10 #define ACC_FULL_SCALE_16_G 0x18 #define Motor1_PWM_Pin 6 #define Motor1_in1_Pin 7 #define Motor1_in2_Pin 8 #define Motor2_PWM_Pin 5 #define Motor2_in1_Pin 13 #define Motor2_in2_Pin 4 #define Motor3_PWM_Pin 11 #define Motor3_in1_Pin 12 #define Motor3_in2_Pin 10 #define MANUAL 2 #define DEMO 1 #define NORMAL 0 #define OFF -1 #define wortel3_2 0.866025 #define setPin 2 //#define motor_offset 100; #define motor_offset 16 #define MOTOR_MAX 200 //#define motor_offset 30; //PID gains: double kp = 0.334; double kd = 8.6; ; //double kp = 0.014; //double kd = 0.8; //motor_layout: int motor1Output = 0; int motor2Output = 0; int motor3Output = 0; uint8_t Buf[14]; unsigned long currentTime, previousTime; double elapsedTime = 2.462; int modus = OFF; SoftwareSerial HC12(3, 9); // HC-12 TX Pin, HC-12 RX Pin char incomingByte; String readBuffer = ""; unsigned long oldTime,newTime; void setMotor(int motorPower,int motor_PWM_Pin,int motor_in1_pin, int motor_in2_pin){ if (motorPower>=0){ digitalWrite(motor_in1_pin, LOW); digitalWrite(motor_in2_pin, HIGH); } else{ digitalWrite(motor_in1_pin, HIGH); digitalWrite(motor_in2_pin, LOW); } int motor_power = abs(motorPower); if (motor_power>5){ if (motor_PWM_Pin==Motor1_PWM_Pin) {motor_power += 150 -motor_offset;} //offset else if (motor_PWM_Pin==Motor2_PWM_Pin){ motor_power += 150 - motor_offset;} else if (motor_PWM_Pin==Motor3_PWM_Pin) {motor_power += 140 - motor_offset;} } if (motor_power>MOTOR_MAX) {motor_power = MOTOR_MAX; } analogWrite(motor_PWM_Pin, motor_power); } void setMotors(int motor1Power, int motor2Power, int motor3Power) { if (modus!=MANUAL){ int minimum_power = min(abs(motor1Power), min(abs(motor2Power),abs(motor3Power))); if (abs(motor1Power) == abs(minimum_power)){motor1Power = 0;} else if (abs(motor2Power) == abs(minimum_power)){motor2Power = 0;} else if (abs(motor3Power) == abs(minimum_power)){motor3Power = 0;} } setMotor(motor1Power,Motor1_PWM_Pin,Motor1_in1_Pin,Motor1_in2_Pin); setMotor(motor2Power,Motor2_PWM_Pin,Motor2_in1_Pin,Motor2_in2_Pin); setMotor(motor3Power,Motor3_PWM_Pin,Motor3_in1_Pin,Motor3_in2_Pin); //monitor output motors // Serial.print(motor1Power); // Serial.print(','); // Serial.print(motor2Power); // Serial.print(','); // Serial.println(motor3Power); } //MPU: //volatile bool intFlag = false; double pitch_Setpoint = 0; double a1_Setpoint = 0; double a2_Setpoint = 0; double aP_output, a1_output, a2_output; //long int cpt = 0; float corrected_pitch; float corrected_roll; int16_t ax,ay,az,gx,gy, calc1,calc2,aP,a1,a2; void I2Cread(uint8_t Address, uint8_t Register, uint8_t Nbytes, uint8_t* Data) { Wire.beginTransmission(Address); Wire.write(Register); Wire.endTransmission(); Wire.requestFrom(Address, Nbytes); uint8_t index = 0; while (Wire.available()) Data[index++] = Wire.read(); } void I2CwriteByte(uint8_t Address, uint8_t Register, uint8_t Data) { Wire.beginTransmission(Address); Wire.write(Register); Wire.write(Data); Wire.endTransmission(); } void setup() { Wire.begin(); Serial.begin(2000000); HC12.begin(9600); // Open serial port to HC12 pinMode(setPin, OUTPUT); digitalWrite(setPin, HIGH); // HC-12 normal mode I2CwriteByte(MPU9250_ADDRESS, 29, 0x06); // Set accelerometers low pass filter at 5Hz I2CwriteByte(MPU9250_ADDRESS, 26, 0x06); // Set gyroscope low pass filter at 5Hz I2CwriteByte(MPU9250_ADDRESS, 27, GYRO_FULL_SCALE_1000_DPS); // Configure gyroscope range I2CwriteByte(MPU9250_ADDRESS, 28, ACC_FULL_SCALE_4_G); // Configure accelerometers range I2CwriteByte(MPU9250_ADDRESS, 0x37, 0x02); // Set by pass mode for the magnetometers I2CwriteByte(MAG_ADDRESS, 0x0A, 0x16); // Request continuous magnetometer measurements in 16 bits //motor pin layout: pinMode(Motor1_PWM_Pin, OUTPUT); pinMode(Motor1_in1_Pin, OUTPUT); pinMode(Motor1_in2_Pin, OUTPUT); pinMode(Motor2_PWM_Pin, OUTPUT); pinMode(Motor2_in1_Pin, OUTPUT); pinMode(Motor2_in2_Pin, OUTPUT); pinMode(Motor3_PWM_Pin, OUTPUT); pinMode(Motor3_in1_Pin, OUTPUT); pinMode(Motor3_in2_Pin, OUTPUT); I2Cread(MPU9250_ADDRESS, 0x3B, 14, Buf); if (modus==DEMO){ elapsedTime += 15; } //set initial values ax = -(Buf[0] << 8 | Buf[1]); //pitch ay = -(Buf[2] << 8 | Buf[3]); //roll aP = corrected_pitch; calc1 = wortel3_2*corrected_roll; //is used twice, only calculated once calc2 = 0.5*corrected_pitch; a1 = calc1+calc2; a2 = calc1-calc2; pitch_Setpoint = ax; //pitch a1_Setpoint = a1; a2_Setpoint = a2; corrected_pitch = ax; corrected_roll = ay; //roll } #define GYROSCOPE_SENSITIVITY 180 // goeie = 130 #define Acc_percentage 0.005 ///goeie = 0.04 #define gyro_offsetx 27 #define gyro_offsety 49 float gyr_percentage = 1-Acc_percentage; void ComplementaryFilter(int16_t gx,int16_t gy,int16_t ax,int16_t ay, int16_t az) { //http://www.pieter-jan.com/node/11 // Integrate the gyroscope data -> int(angularSpeed) = angle corrected_pitch += ((gx-gyro_offsetx) / GYROSCOPE_SENSITIVITY) * elapsedTime; // Angle around the X-axis corrected_roll -= ((gy-gyro_offsety) / GYROSCOPE_SENSITIVITY) * elapsedTime; // Angle around the Y-axis corrected_pitch = corrected_pitch * gyr_percentage + ax * Acc_percentage; corrected_roll = corrected_roll * gyr_percentage + ay * Acc_percentage; } void loop(){ //send and receive HC12 while (HC12.available()) { // If HC-12 has data incomingByte = char(HC12.read()); Serial.print(incomingByte); if ((modus==OFF)&&(incomingByte=='b')){ modus=NORMAL; } if (incomingByte == 'd'){ modus = DEMO; } else if (incomingByte == 'm'){ if (modus==MANUAL) modus = NORMAL; else modus = MANUAL; setMotors(0,0,0); } else if (modus==MANUAL){ if (incomingByte == 'b') setMotors(0,0,0); else if (incomingByte == 'f') setMotors(MOTOR_MAX,-MOTOR_MAX,0); else if (incomingByte == 'r') setMotors(-100,-100,-100); else if (incomingByte == 'l') setMotors(100,100,100); } } // while (Serial.available()) { // HC12.write(Serial.read()); // } // Read accelerometer and gyroscope I2Cread(MPU9250_ADDRESS, 0x3B, 14, Buf); // Accelerometer ax = -(Buf[0] << 8 | Buf[1]); //pitch ay = -(Buf[2] << 8 | Buf[3]); //roll az = Buf[4] << 8 | Buf[5]; // Gyroscope gy = -(Buf[8] << 8 | Buf[9]); gx = -(Buf[10] << 8 | Buf[11]); ///Filter axis ComplementaryFilter(gx,gy, ax,ay,az); // Define new Axes aP = corrected_pitch; calc1 = wortel3_2*corrected_roll; //is used twice, only calculated once calc2 = 0.5*corrected_pitch; a1 = calc1+calc2; a2 = calc1-calc2; // Display values //Serial.print(ax); //Serial.print(ay); //Serial.print (a1); //Serial.println(a2); // currentTime = millis(); //get current time // elapsedTime = (double)(currentTime - previousTime); //compute time elapsed from previous computation // previousTime = currentTime; //remember current time // Serial.println(elapsedTime); // //PID's aP_output = computePID_pitch(aP, pitch_Setpoint); a1_output = computePID_a1(a1, a1_Setpoint); a2_output = computePID_a2(a2, a2_Setpoint); // aP_output = aP_output*abs(aP_output); // a1_output = a1_output*abs(a1_output); // a2_output = a2_output*abs(a2_output); // Serial.write(','); // Serial.println(aP_output); //Sum PID's and process in Motor Controller motor1Output = aP_output + a2_output; motor2Output = -aP_output + a1_output; motor3Output = (-a1_output - a2_output); //print angles if (modus==DEMO){ Serial.print(gx); //Serial.print(gx); Serial.print(","); Serial.print(ax); ///ax Serial.print(","); Serial.println(corrected_pitch); delay(15); } else if (modus==NORMAL) { setMotors(motor1Output, motor2Output, motor3Output); } //motor = keyboard output; // String readString; // while (Serial.available()) { // char c = Serial.read(); //gets one byte from serial buffer // readString += c; //makes the string readString // delay(2); //slow looping to allow buffer to fill with next character // } // // if (readString.length() >0) { // Serial.println(readString);//so you can see the captured string // int motor_set = readString.toInt(); //convert readString into a number // Serial.println(motor_set); // setMotors(motor_set, -motor_set,0); // } } //PID for pitch control: double error,error_a1,error_a2; double lastError,lastError_a1,lastError_a2; double rateErrorAvg, rateErrorAvg1,rateErrorAvg2; double rateError, rateError_a1,rateError_a2; double computePID_pitch(double inp, double Setpoint) { error = Setpoint - inp; // determine error //cumError = error * elapsedTime; // compute integral rateError = (error - lastError) / elapsedTime; // compute derivative rateErrorAvg = (0.1*rateErrorAvg+0.9*rateError); lastError = error; //remember current error return (kp * error + kd * rateErrorAvg); //ki * cumError + } //PID for axis 1 control: double computePID_a1(double inp_a1, double Setpoint_a1) { error_a1 = Setpoint_a1 - inp_a1; // determine error // cumError_a1 = error_a1 * elapsedTime; // compute integral rateError_a1 = (error_a1 - lastError_a1) / elapsedTime; // compute derivative rateErrorAvg1 = (0.1*rateErrorAvg1+0.9*rateError_a1); lastError_a1 = error_a1; //remember current error return (kp * error_a1 + kd * rateErrorAvg1); // + ki * cumError_a1 } //PID for axis 2 control: double computePID_a2(double inp_a2, double Setpoint_a2) { error_a2 = Setpoint_a2 - inp_a2; // determine error // cumError_a2 = error_a2 * elapsedTime; // compute integral rateError_a2 = (error_a2 - lastError_a2) / elapsedTime; // compute derivative rateErrorAvg2 = (0.1*rateErrorAvg2+0.9*rateError_a2); //running average for small looptime lastError_a2 = error_a2; //remember current error return (kp * error_a2 + kd * rateErrorAvg2); //ki * cumError_a2 }
2a47a9242080278bbf73908b5fd1404e484966aa
986c21d401983789d9b3e5255bcf9d76070f65ec
/src/plugins/azoth/plugins/xoox/util.cpp
2de83e86de354ffa9699576b1a7ff8e9fbbedff3
[ "BSL-1.0" ]
permissive
0xd34df00d/leechcraft
613454669be3a0cecddd11504950372c8614c4c8
15c091d15262abb0a011db03a98322248b96b46f
refs/heads/master
2023-07-21T05:08:21.348281
2023-06-04T16:50:17
2023-06-04T16:50:17
119,854
149
71
null
2017-09-03T14:16:15
2009-02-02T13:52:45
C++
UTF-8
C++
false
false
8,018
cpp
util.cpp
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "util.h" #include <memory> #include <QObject> #include <QHash> #include <QDomDocument> #include <QDomElement> #include <QDialog> #include <QDialogButtonBox> #include <QVBoxLayout> #include <QDataStream> #include <QFile> #include <QtDebug> #include <QXmppPresence.h> #include <QXmppUtils.h> #include <QXmppGlobal.h> #include <util/sll/parsejson.h> #include <util/sll/prelude.h> #include "entrybase.h" #include "capsdatabase.h" #include "glooxaccount.h" QDataStream& operator<< (QDataStream& out, const QXmppDiscoveryIq::Identity& id) { out << static_cast<quint8> (1) << id.category () << id.language () << id.name () << id.type (); return out; } QDataStream& operator>> (QDataStream& in, QXmppDiscoveryIq::Identity& id) { quint8 version = 0; in >> version; if (version != 1) { qWarning () << Q_FUNC_INFO << "unknown version" << version; return in; } QString category, language, name, type; in >> category >> language >> name >> type; id.setCategory (category); id.setLanguage (language); id.setName (name); id.setType (type); return in; } namespace LC { namespace Azoth { namespace Xoox { namespace XooxUtil { const QString NsRegister { "jabber:iq:register" }; QString RoleToString (const QXmppMucItem::Role& role) { switch (role) { case QXmppMucItem::NoRole: return QObject::tr ("guest"); case QXmppMucItem::VisitorRole: return QObject::tr ("visitor"); case QXmppMucItem::ParticipantRole: return QObject::tr ("participant"); case QXmppMucItem::ModeratorRole: return QObject::tr ("moderator"); default: return QObject::tr ("unspecified"); } } QString AffiliationToString (const QXmppMucItem::Affiliation& affiliation) { switch (affiliation) { case QXmppMucItem::OutcastAffiliation: return QObject::tr ("outcast"); case QXmppMucItem::NoAffiliation: return QObject::tr ("newcomer"); case QXmppMucItem::MemberAffiliation: return QObject::tr ("member"); case QXmppMucItem::AdminAffiliation: return QObject::tr ("admin"); case QXmppMucItem::OwnerAffiliation: return QObject::tr ("owner"); default: return QObject::tr ("unspecified"); } } namespace { QPair<QStringList, StaticClientInfo> ParseClientIdObj (const QVariantMap& map) { const auto& nodeVar = map ["node"]; const auto& nodes = nodeVar.canConvert<QVariantList> () ? Util::Map (nodeVar.toList (), &QVariant::toString) : QStringList { nodeVar.toString () }; const auto& id = map ["id"].toString (); const auto& name = map ["name"].toString (); if (nodes.isEmpty () || id.isEmpty () || name.isEmpty ()) qWarning () << Q_FUNC_INFO << "missing data for map" << map; return { nodes, { id, name } }; } class StaticClientInfoHolder { QHash<QString, StaticClientInfo> FullMatches_; QList<QPair<QString, StaticClientInfo>> PartialMatches_; public: StaticClientInfoHolder () { QFile file { ":/azoth/xoox/resources/data/clientids.json" }; if (!file.open (QIODevice::ReadOnly)) { qWarning () << Q_FUNC_INFO << "unable to open file:" << file.errorString (); return; } const auto& json = Util::ParseJson (&file, Q_FUNC_INFO).toMap (); for (const auto& itemVar : json ["fullMatches"].toList ()) { const auto& pair = ParseClientIdObj (itemVar.toMap ()); for (const auto& node : pair.first) { if (FullMatches_.contains (node)) qWarning () << Q_FUNC_INFO << "duplicate node:" << node; FullMatches_ [node] = pair.second; } } for (const auto& itemVar : json ["partialMatches"].toList ()) { const auto& pair = ParseClientIdObj (itemVar.toMap ()); for (const auto& node : pair.first) PartialMatches_.push_back ({ node, pair.second }); } std::sort (PartialMatches_.begin (), PartialMatches_.end (), Util::ComparingBy (Util::Fst)); } StaticClientInfo operator[] (const QString& node) const { const auto pos = FullMatches_.find (node); if (pos != FullMatches_.end ()) return *pos; for (auto i = PartialMatches_.begin (), end = PartialMatches_.end (); i != end; ++i) if (node.startsWith (i->first)) return i->second; return {}; } }; } StaticClientInfo GetStaticClientInfo (const QString& node) { static const StaticClientInfoHolder holder; return holder [node]; } QDomElement XmppElem2DomElem (const QXmppElement& elem) { QByteArray arr; QXmlStreamWriter w (&arr); elem.toXml (&w); QDomDocument doc; if (!doc.setContent (arr, true)) qCritical () << Q_FUNC_INFO << "unable to set XML contents" << arr; return doc.documentElement (); } QXmppElement Form2XmppElem (const QXmppDataForm& form) { QByteArray formData; QXmlStreamWriter w (&formData); form.toXml (&w); QDomDocument doc; if (!doc.setContent (formData)) qCritical () << Q_FUNC_INFO << "unable to set XML contents" << formData; return doc.documentElement (); } bool RunFormDialog (QWidget *widget) { QDialog *dialog (new QDialog ()); dialog->setWindowTitle (widget->windowTitle ()); dialog->setLayout (new QVBoxLayout ()); dialog->layout ()->addWidget (widget); QDialogButtonBox *box = new QDialogButtonBox (QDialogButtonBox::Ok | QDialogButtonBox::Cancel); dialog->layout ()->addWidget (box); QObject::connect (box, SIGNAL (accepted ()), dialog, SLOT (accept ())); QObject::connect (box, SIGNAL (rejected ()), dialog, SLOT (reject ())); const bool result = dialog->exec () == QDialog::Accepted; dialog->deleteLater (); return result; } bool CheckUserFeature (EntryBase *base, const QString& variant, const QString& feature, const CapsDatabase *capsDB) { if (variant.isEmpty ()) return true; const QByteArray& ver = base->GetVariantVerString (variant); if (ver.isEmpty ()) return true; const auto& feats = capsDB->Get (ver); if (feats.isEmpty ()) return true; return feats.contains (feature); } QXmppMessage Forwarded2Message (const QXmppElement& wrapper) { const auto& forwardedElem = wrapper.tagName () == "forwarded" ? wrapper : wrapper.firstChildElement ("forwarded"); if (forwardedElem.isNull ()) return {}; const auto& messageElem = forwardedElem.firstChildElement ("message"); if (messageElem.isNull ()) return {}; QXmppMessage original; original.parse (messageElem.sourceDomElement ()); auto delayElem = forwardedElem.firstChildElement ("delay"); if (!delayElem.isNull ()) { const auto& sourceDT = QXmppUtils::datetimeFromString (delayElem.attribute ("stamp")); original.setStamp (sourceDT.toLocalTime ()); } return original; } EntryStatus PresenceToStatus (const QXmppPresence& pres) { EntryStatus st (static_cast<State> (pres.availableStatusType () + 1), pres.statusText ()); if (pres.type () == QXmppPresence::Unavailable) st.State_ = SOffline; return st; } QXmppPresence StatusToPresence (State state, const QString& text, int prio) { QXmppPresence::Type presType = state == SOffline ? QXmppPresence::Unavailable : QXmppPresence::Available; QXmppPresence pres (presType); if (state != SOffline && state <= SInvisible) pres.setAvailableStatusType (static_cast<QXmppPresence::AvailableStatusType> (state - 1)); pres.setStatusText (text); pres.setPriority (prio); return pres; } QString GetBareJID (const QString& entryId, GlooxAccount *acc) { const auto underscoreCount = acc->GetAccountID ().count ('_') + 1; return entryId.section ('_', underscoreCount); } } } } }
f15974949e25ee6fbd102b97e44262f3143e8bd8
7d9d9992df4254715c6585858cda3cfd4ff01d6e
/potent_test_module/potent_test_module.ino
9ff1af443f560346638d94fabe4a03119f51e15e
[]
no_license
tiagomiotto/discharge
9349b7f7700be1f565912846e31b493fb22ac2da
4f7d97d891ddd8eb9dbaeb0ce923867a00f45567
refs/heads/master
2021-09-15T04:32:08.173156
2018-04-06T17:47:44
2018-04-06T17:47:44
114,899,152
2
1
null
2018-02-04T15:26:49
2017-12-20T14:53:50
Arduino
UTF-8
C++
false
false
1,403
ino
potent_test_module.ino
/* Potentiometer testing module The program is designed to increase the resistance of the potentiometer every 10 seconds allowing enough time to be measured confirming the proper functioning */ #include <Wire.h> #include <math.h> const int addr = 0x50; // device address is specified in datasheet IMPORTANT const int level=0xFF; int aux_level=level; const int rele_bat=22; int X0; void setup(){ Serial.begin(9600); Wire.begin(); pinMode(rele_bat,OUTPUT); digitalWrite(rele_bat,HIGH); } void loop(){ float diferential; String data; potentiometer(aux_level); delay(250); diferential = read_diferential(); data = String(aux_level) + "\t"+ String(diferential) +"\t"; if(aux_level<1){ aux_level=0xFF; } else{ aux_level=aux_level-1; } Serial.println(data); } //Function to communicate with POT and define lvl void potentiometer(int lvl) { Wire.beginTransmission(addr); // transmit to device #addr (0x2c) Wire.write(byte(0x00)); // sends instruction byte // Essa instrução é pra escrever no Wiper Registry Wire.write(lvl); // sends potentiometer value byte Wire.endTransmission(); // stop transmitting } //Arduino pins, read outuput voltage from POT float read_diferential(){ float positive,negative; positive=analogRead(A2)*(5.0/1024.0); negative=analogRead(A3)*(5.0/1024.0); return positive-negative; }
91e8a1257cce702117e1eca9dd5827c6e1209a41
a5f08f257e75ff14656c68e374f7ef1536b1bde3
/ReboundRumble2012/Subsystems/LimitSensor.cpp
82e5f1ae4361dc70c2c885a896c903706bde268b
[]
no_license
Team293/Robot-Code-2012
3a0d41c0f1eada5795182158a179133e085e02d9
60992c0145e76c4ed3fda9527cadef094c82ade2
refs/heads/master
2021-01-10T21:29:51.680556
2012-02-12T20:03:09
2012-02-12T20:03:09
3,105,053
1
0
null
null
null
null
UTF-8
C++
false
false
1,100
cpp
LimitSensor.cpp
#include "LimitSensor.h" #include "../Robotmap.h" /** * Name: * LimitSensor * * Description: * Class Constructor * * Input: * limit_sensor_din_chnl The digital input channel on DIO module 1 (default) * where the limit sensor is located. * reverse_sense The option to reservse the limit sense output state * from the actual limit sensor state reported via * digital input channel. * * Return: * Object instance reference */ LimitSensor::LimitSensor(UINT32 limit_sensor_din_chnl, bool reverse_sense) { // Create instance of specified limit sensor and store sense qualifier limit_sensor = new DigitalInput(limit_sensor_din_chnl); this->reverse_sense = reverse_sense; } /** * Name: * AtLimit * * Description: * Accessor method that indicates limit sensor status * * Input: * None * * Return: * true If limit sensor active * false If limit sensor inactive */ bool LimitSensor::AtLimit() { bool limit_state; limit_state = limit_sensor->Get(); if (reverse_sense == true) { limit_state = !limit_state; } return(limit_state); }
cc6e65e57150e1b55663e770165d2af2c442f7c8
4c7d552c2275b6bf21a9f683ab9abb3b5c40e2f8
/CppDroid/tutorials/learncpp.com#1.0#1/functions/ellipses__and_why_to_avoid_them_/source3.cpp
868fcb22a75c194c0b78b845d46854e4c7657adb
[]
no_license
gustavofvieira/AulaCpp
af4d271ee0e730285d09c6a47650d7accfce44cd
f2d2ff28716204aee10e8cae8e3fb7b74819a7d9
refs/heads/master
2020-03-17T08:20:30.653102
2018-05-22T00:33:47
2018-05-22T00:33:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
104
cpp
source3.cpp
int nValue = 7; cout << FindAverage(6, 1.0, 2, "Hello, world!", 'G', &nValue, &FindAverage) << endl;
b29429f1190fab83f1ad676064d7ccce569be1fb
986c21d401983789d9b3e5255bcf9d76070f65ec
/src/plugins/aggregator/channelsfiltermodel.cpp
ad71cccf66f8fc678ba8e9c1df60025eebc83796
[ "BSL-1.0" ]
permissive
0xd34df00d/leechcraft
613454669be3a0cecddd11504950372c8614c4c8
15c091d15262abb0a011db03a98322248b96b46f
refs/heads/master
2023-07-21T05:08:21.348281
2023-06-04T16:50:17
2023-06-04T16:50:17
119,854
149
71
null
2017-09-03T14:16:15
2009-02-02T13:52:45
C++
UTF-8
C++
false
false
823
cpp
channelsfiltermodel.cpp
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "channelsfiltermodel.h" #include "common.h" namespace LC { namespace Aggregator { ChannelsFilterModel::ChannelsFilterModel (QObject *parent) : Util::TagsFilterModel (parent) { setDynamicSortFilter (true); SetTagsMode (true); } QStringList ChannelsFilterModel::GetTagsForIndex (int row) const { return sourceModel ()->index (row, 0).data (ChannelRoles::HumanReadableTags).toStringList (); } } }
f03595908e8c1641e20955d0f2df1b4048992300
b60aeea5ca505b2aac7dc3da7bc5802dd9035db9
/src_win/ODBC/PostgresDb.cpp
5f824f084a25142a83b648fc9d03b860ba33bbfa
[]
no_license
rauls/iReporter
004b7e13c317a8c7709b91ad7717976d1e81bae2
4ba5e7bb3f43cd3a27a3c71cf53e0910efff0431
refs/heads/master
2020-12-24T16:32:38.567261
2016-04-22T02:36:38
2016-04-22T02:36:38
23,453,009
1
1
null
null
null
null
UTF-8
C++
false
false
875
cpp
PostgresDb.cpp
/* PostgresDb file is a subclass for reading from or writing data to Postgres database by using ODBC. file title display formate: Postgres DATABASE=database name->data source name:table Name */ #include "ConvertDb.h" #include "PostgresDb.h" PostgresDb::PostgresDb():ConvertDb() {} PostgresDb::~PostgresDb() {} void PostgresDb::getTableList(char tList[][MAXBUFLEN], char* tName, char* typeN, int &num) { strcpy(tList[num], (const char *)tName); num++; } // get file name and type: file name=database name. type=Postgres void PostgresDb::setFileInfo(char *type) { char *point, *fName; if(*type) { strcpy(fileType, "PostgreSQL"); point=strstr( type,"DATABASE=" ); if (point) { point += 9; fName=point; point =strstr(point, ";" ); *point='\0'; point++; strcpy(fileName, "PostgreSQL DATABASE= "); strcat(fileName,fName); } } }
79c249b2c7977070253e8caf2fe626a7ed245338
1d2934877a7cdf88e99d67a97b16c7f962b20b11
/Sansa_and_XOR.cpp
0fad0ee9f5c8d587b2b51f2c0fce134f6faf1a16
[]
no_license
ArnabBir/hackerrank-solutions
37fded89baed269bbb5894fdefb7fd9d1f2b89ea
088a9dee94e0dd9d9f1ef756bac94108af477bc1
refs/heads/master
2021-06-06T01:58:11.921526
2021-05-23T14:07:51
2021-05-23T14:07:51
66,587,997
3
2
null
null
null
null
UTF-8
C++
false
false
786
cpp
Sansa_and_XOR.cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int T, N; cin>>T; while(T--){ cin>>N; int a[N]; bool isNodd = N%2; for(int i = 0; i < N; ++i){ cin>>a[i]; } if(N == 0){ cout<<0<<endl; continue; } if(N == 1){ cout<<a[0]<<endl; continue; } int XOR; if(isNodd){ XOR = a[0]^a[N-1]; for(int i = 2; i < N/2; i += 2){ XOR ^= a[i]^a[N-1-i]; } if((N/2)%2 == 0) XOR ^= a[N/2]; } else{ XOR = 0; } cout<<XOR<<endl; } return 0; }
f978841a1dbce6fe75a4dad13e07b5b36b9584f5
1487d94a390603c93b5c26cad55adfdc177d1657
/Source/GameService/GameObject/Event/SampleParam/GsGameObjectEventParamBase.h
a40c02d6979f73d2afa491c673fc1b36b771025a
[ "MIT" ]
permissive
BaekTaehyun/T1Project
d9520f99b0d3f973ef18875e5ee1d1686103c040
d7d98c7cfc88e57513631124c32dfee8794307db
refs/heads/master
2020-04-01T09:27:04.900622
2019-06-25T05:22:10
2019-06-25T05:22:10
153,075,452
3
2
null
null
null
null
UHC
C++
false
false
1,026
h
GsGameObjectEventParamBase.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Message/GsMessageGameObject.h" #include "GameObject/ObjectClass/GsGameObjectBase.h" /** * 임시 메세지 기반 파라미터 구조체 인터페이스 클래스 * 일단 MessageGameObject::Action 타입에 1:1 대응되는 형태로 구현 * 생성자에서 Type값을 설정 * 추후 네트워크 연동이 진행되면 필요 없을듯(패킷 구조체 대응) */ class GAMESERVICE_API GsGameObjectEventParamBase { public: MessageGameObject::Action ActionType; UGsGameObjectBase* Target; public: GsGameObjectEventParamBase(); virtual ~GsGameObjectEventParamBase(); virtual void Clear(); }; //탈것 탑승 class GAMESERVICE_API GsGameObjectEventParamVehicleRide : public GsGameObjectEventParamBase { typedef GsGameObjectEventParamBase Super; public: //탑승자 UGsGameObjectBase* Passenger; public: GsGameObjectEventParamVehicleRide(); virtual void Clear() override; };
ebf497f689f551c315dc2ad6ce5c0b93abd5174f
ea3cefc841d4638e4c24b83d9f9d1bf04b44acc2
/finn_dev_feedback_docker_output/code_gen_ipgen_StreamingFCLayer_Batch_6_jr0t8kfb/project_StreamingFCLayer_Batch_6/sol1/syn/systemc/StreamingFCLayer_Batch_6_Matrix_Vector_Actbkb.h
09766ff3789434af0bef94785f889628885fb569
[]
no_license
pgreksic/FINN_Export_AXI_Lite_Missing
0bb3fd92eca030d4ba59ec19ae3ef5c79ce9ddce
915be24be5d2c4ca96018bdfd73abff31fcdd057
refs/heads/main
2023-03-11T23:23:32.250197
2021-03-01T17:33:42
2021-03-01T17:33:42
335,460,254
0
0
null
null
null
null
UTF-8
C++
false
false
23,071
h
StreamingFCLayer_Batch_6_Matrix_Vector_Actbkb.h
// ============================================================== // Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC v2020.1.1 (64-bit) // Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. // ============================================================== #ifndef __StreamingFCLayer_Batch_6_Matrix_Vector_Actbkb_H__ #define __StreamingFCLayer_Batch_6_Matrix_Vector_Actbkb_H__ #include <systemc> using namespace sc_core; using namespace sc_dt; #include <iostream> #include <fstream> struct StreamingFCLayer_Batch_6_Matrix_Vector_Actbkb_ram : public sc_core::sc_module { static const unsigned DataWidth = 16; static const unsigned AddressRange = 512; static const unsigned AddressWidth = 9; //latency = 1 //input_reg = 1 //output_reg = 0 sc_core::sc_in <sc_lv<AddressWidth> > address0; sc_core::sc_in <sc_logic> ce0; sc_core::sc_out <sc_lv<DataWidth> > q0; sc_core::sc_in<sc_logic> reset; sc_core::sc_in<bool> clk; sc_lv<DataWidth> ram[AddressRange]; SC_CTOR(StreamingFCLayer_Batch_6_Matrix_Vector_Actbkb_ram) { ram[0] = "0b0000011100011100"; ram[1] = "0b0000000100000001"; ram[2] = "0b1111101000010100"; ram[3] = "0b1111111010001010"; ram[4] = "0b0000010101010001"; ram[5] = "0b1111011001110111"; ram[6] = "0b0000001111110110"; ram[7] = "0b1111111011011111"; ram[8] = "0b1111110011111001"; ram[9] = "0b0000001001100001"; ram[10] = "0b1111011101110110"; ram[11] = "0b1111110100011110"; ram[12] = "0b1111101100110111"; ram[13] = "0b0000010010111111"; ram[14] = "0b1111111001000010"; ram[15] = "0b0000111001010101"; ram[16] = "0b1111101000111001"; ram[17] = "0b0000010111111101"; ram[18] = "0b0000000001001000"; ram[19] = "0b1111111100011110"; ram[20] = "0b0000000100100100"; ram[21] = "0b0000010011000011"; ram[22] = "0b0000000100101101"; ram[23] = "0b0000000111100010"; ram[24] = "0b0000001010000111"; ram[25] = "0b0000001101010101"; ram[26] = "0b0000011110010001"; ram[27] = "0b1111100000011001"; ram[28] = "0b1111101110101110"; ram[29] = "0b1111101001110011"; ram[30] = "0b0000000001101001"; ram[31] = "0b0000011011000000"; ram[32] = "0b1111010110100110"; ram[33] = "0b1111111100001111"; ram[34] = "0b1111100011101000"; ram[35] = "0b1111111111001100"; ram[36] = "0b1111000111001100"; ram[37] = "0b0000000011000000"; ram[38] = "0b0000001101101100"; ram[39] = "0b0000110011011110"; ram[40] = "0b0000000010001101"; ram[41] = "0b0000011111101110"; ram[42] = "0b1111111110010010"; ram[43] = "0b0000101100000110"; ram[44] = "0b0000110000001001"; ram[45] = "0b0000010111010001"; ram[46] = "0b0001101011011101"; ram[47] = "0b0000001101010101"; ram[48] = "0b1111101110111000"; ram[49] = "0b1100111001011101"; ram[50] = "0b0000100001110101"; ram[51] = "0b1111111011111011"; ram[52] = "0b0000010111111111"; ram[53] = "0b1011101000100001"; ram[54] = "0b1111011001010000"; ram[55] = "0b1111110011011000"; ram[56] = "0b1101111010101100"; ram[57] = "0b0000000101001101"; ram[58] = "0b1111011000001101"; ram[59] = "0b0000010100000000"; ram[60] = "0b0000011011001000"; ram[61] = "0b0000000100101110"; ram[62] = "0b0000001100111001"; ram[63] = "0b1111110111101110"; ram[64] = "0b0000000010011111"; ram[65] = "0b1111111100101101"; ram[66] = "0b1111011111010001"; ram[67] = "0b0000100110010110"; ram[68] = "0b1111110010110001"; ram[69] = "0b0010010011101111"; ram[70] = "0b1111110010101111"; ram[71] = "0b0000001110001111"; ram[72] = "0b0000100110100000"; ram[73] = "0b1111100100010000"; ram[74] = "0b0000001001011010"; ram[75] = "0b1111111100001011"; ram[76] = "0b1111110010001001"; ram[77] = "0b0000100000101111"; ram[78] = "0b0000010101010001"; ram[79] = "0b0000100100110001"; ram[80] = "0b0000000000010110"; ram[81] = "0b1111101101101010"; ram[82] = "0b1111111011100000"; ram[83] = "0b1111110011011000"; ram[84] = "0b0000000111110000"; ram[85] = "0b1111011001101110"; ram[86] = "0b0000000000010011"; ram[87] = "0b1111110000000101"; ram[88] = "0b0000010001111111"; ram[89] = "0b1111110011110000"; ram[90] = "0b1111110000111001"; ram[91] = "0b1111100111001101"; ram[92] = "0b0000101000111011"; ram[93] = "0b1100110111110110"; ram[94] = "0b1111101010011001"; ram[95] = "0b1111010011000100"; ram[96] = "0b0000010011001101"; ram[97] = "0b1111111111111100"; ram[98] = "0b0000011000110111"; ram[99] = "0b1111100010001010"; ram[100] = "0b1111101111011001"; ram[101] = "0b0000001111001100"; ram[102] = "0b1111111111010001"; ram[103] = "0b0000001111101001"; ram[104] = "0b1111110111001011"; ram[105] = "0b0000000001001101"; ram[106] = "0b0000010101101110"; ram[107] = "0b1001011100000000"; ram[108] = "0b1111101001101000"; ram[109] = "0b1111110011111110"; ram[110] = "0b1111101101100000"; ram[111] = "0b0000000011110010"; ram[112] = "0b1110101101001001"; ram[113] = "0b1111101011000001"; ram[114] = "0b1111111000100110"; ram[115] = "0b1111110011101010"; ram[116] = "0b1111111111100111"; ram[117] = "0b1111110010101110"; ram[118] = "0b0000000100101000"; ram[119] = "0b1111001010010110"; ram[120] = "0b0000000001000010"; ram[121] = "0b1111101111111101"; ram[122] = "0b1111110111000001"; ram[123] = "0b0000010110000000"; ram[124] = "0b1111100010100100"; ram[125] = "0b1111101100011100"; ram[126] = "0b1111110000111000"; ram[127] = "0b1111110011111011"; ram[128] = "0b0000001100100010"; ram[129] = "0b0000001011011010"; ram[130] = "0b0000011010010001"; ram[131] = "0b0011110011110110"; ram[132] = "0b1111110010000011"; ram[133] = "0b0000000010100000"; ram[134] = "0b1111110000110011"; ram[135] = "0b1111101001010011"; ram[136] = "0b0000010000110100"; ram[137] = "0b0000001011101001"; ram[138] = "0b0000000101110110"; ram[139] = "0b0000010111111101"; ram[140] = "0b0000001111001010"; ram[141] = "0b1111111101011010"; ram[142] = "0b0000010110101100"; ram[143] = "0b0001000100011111"; ram[144] = "0b0000000010001101"; ram[145] = "0b0000100111110111"; ram[146] = "0b0000000100101110"; ram[147] = "0b1111101000001000"; ram[148] = "0b0000010110101000"; ram[149] = "0b0000010111101100"; ram[150] = "0b0000001101010100"; ram[151] = "0b1111110000100110"; ram[152] = "0b0000111100011100"; ram[153] = "0b1111111011010111"; ram[154] = "0b1111101101111011"; ram[155] = "0b0000010110100000"; ram[156] = "0b1111110001010100"; ram[157] = "0b0000000001000000"; ram[158] = "0b1111001001110001"; ram[159] = "0b0000000001000101"; ram[160] = "0b1111101110100100"; ram[161] = "0b1111111001011111"; ram[162] = "0b1111101010001110"; ram[163] = "0b1111110100000110"; ram[164] = "0b1111110101011111"; ram[165] = "0b0000000000001011"; ram[166] = "0b0000100010010010"; ram[167] = "0b0000001110011000"; ram[168] = "0b1111101000010101"; ram[169] = "0b0000001010011110"; ram[170] = "0b1001011100000000"; ram[171] = "0b0000001100100100"; ram[172] = "0b0000101100111101"; ram[173] = "0b1111111100100010"; ram[174] = "0b0000000101111000"; ram[175] = "0b1111110110011000"; ram[176] = "0b1111110110010011"; ram[177] = "0b0000001001010111"; ram[178] = "0b1110010101000101"; ram[179] = "0b0000010001111001"; ram[180] = "0b0000001111011110"; ram[181] = "0b0000001000101010"; ram[182] = "0b1111111000010010"; ram[183] = "0b0000011111101101"; ram[184] = "0b0000000110111110"; ram[185] = "0b1111111101011101"; ram[186] = "0b1111111010010010"; ram[187] = "0b1111110010010111"; ram[188] = "0b1111110010100110"; ram[189] = "0b1111111101111001"; ram[190] = "0b0000011001100010"; ram[191] = "0b1111110001011100"; ram[192] = "0b1111110101010110"; ram[193] = "0b1111101101000110"; ram[194] = "0b1111101001100100"; ram[195] = "0b0000101011111000"; ram[196] = "0b0000010110001100"; ram[197] = "0b1111101111011111"; ram[198] = "0b1101001010001001"; ram[199] = "0b1111011100001010"; ram[200] = "0b0000010010110111"; ram[201] = "0b1111001101011100"; ram[202] = "0b1111010010100001"; ram[203] = "0b0000011111100110"; ram[204] = "0b1111110111100101"; ram[205] = "0b1111011101100110"; ram[206] = "0b0000000101111011"; ram[207] = "0b0000010000101110"; ram[208] = "0b1111111011011010"; ram[209] = "0b0000000100110110"; ram[210] = "0b1111111000110101"; ram[211] = "0b1111110100100101"; ram[212] = "0b1111101011000000"; ram[213] = "0b0000010011011110"; ram[214] = "0b1011001010001101"; ram[215] = "0b1111000101100101"; ram[216] = "0b0000000110011101"; ram[217] = "0b1111011001010000"; ram[218] = "0b1101011101001110"; ram[219] = "0b0000101100011010"; ram[220] = "0b1111101001110111"; ram[221] = "0b0000010001111011"; ram[222] = "0b0000001100101000"; ram[223] = "0b0000010111000011"; ram[224] = "0b1111111100111101"; ram[225] = "0b0000000110010101"; ram[226] = "0b1111011010011110"; ram[227] = "0b0000010000100000"; ram[228] = "0b1111111000111110"; ram[229] = "0b0000010110011001"; ram[230] = "0b1111111011000100"; ram[231] = "0b1111111010011001"; ram[232] = "0b1111110010110000"; ram[233] = "0b1111010001101011"; ram[234] = "0b0000000010100010"; ram[235] = "0b1111010000010101"; ram[236] = "0b1111111001000001"; ram[237] = "0b0000111001010011"; ram[238] = "0b0000001001011000"; ram[239] = "0b0000000001000000"; ram[240] = "0b1111011110100101"; ram[241] = "0b1111101000100000"; ram[242] = "0b0000001101001101"; ram[243] = "0b1111101110010011"; ram[244] = "0b0000000110101111"; ram[245] = "0b1111110101000101"; ram[246] = "0b1111111110010010"; ram[247] = "0b0000000000000101"; ram[248] = "0b0000000110011010"; ram[249] = "0b0000010001010111"; ram[250] = "0b1111001111001000"; ram[251] = "0b0000010100011111"; ram[252] = "0b0000000001011001"; ram[253] = "0b1111110000110011"; ram[254] = "0b0000001000100000"; ram[255] = "0b0000010000010111"; ram[256] = "0b1111100110110101"; ram[257] = "0b0000010001110011"; ram[258] = "0b0000010000010110"; ram[259] = "0b0000011000000001"; ram[260] = "0b1111010000111000"; ram[261] = "0b0000001111011111"; ram[262] = "0b0000010100001001"; ram[263] = "0b0000000000001111"; ram[264] = "0b0000000110110010"; ram[265] = "0b0000000100010100"; ram[266] = "0b0101001100110110"; ram[267] = "0b1111101011010110"; ram[268] = "0b0000001010000101"; ram[269] = "0b0000101001011010"; ram[270] = "0b0000000011101101"; ram[271] = "0b1111110101111011"; ram[272] = "0b0000110011010111"; ram[273] = "0b0000110011011010"; ram[274] = "0b0000010100110110"; ram[275] = "0b1111111101001101"; ram[276] = "0b1111111100011101"; ram[277] = "0b0000010001111001"; ram[278] = "0b1111101101110111"; ram[279] = "0b1111101100010001"; ram[280] = "0b1111110011000011"; ram[281] = "0b1111111000011011"; ram[282] = "0b1111110001101011"; ram[283] = "0b0000010001010100"; ram[284] = "0b1111111101100000"; ram[285] = "0b1111010010010101"; ram[286] = "0b0000000100110000"; ram[287] = "0b0000000100111000"; ram[288] = "0b0000010110011110"; ram[289] = "0b1110001001011010"; ram[290] = "0b1111010111101000"; ram[291] = "0b0000100011011101"; ram[292] = "0b1110110100111111"; ram[293] = "0b1111101000101001"; ram[294] = "0b0000000001110001"; ram[295] = "0b1111100100100001"; ram[296] = "0b0000010100010001"; ram[297] = "0b0000001001000001"; ram[298] = "0b1001111010010001"; ram[299] = "0b0000010110000110"; ram[300] = "0b0000001010010011"; ram[301] = "0b0000010010101110"; ram[302] = "0b1111111110110000"; ram[303] = "0b0000011001011100"; ram[304] = "0b1111111001000001"; ram[305] = "0b1111100110011010"; ram[306] = "0b1111110001010010"; ram[307] = "0b0000001000011101"; ram[308] = "0b0000101011111100"; ram[309] = "0b0000111000111110"; ram[310] = "0b1111111110101001"; ram[311] = "0b0000000100011100"; ram[312] = "0b0000001010001101"; ram[313] = "0b1110101111011011"; ram[314] = "0b1111001101101000"; ram[315] = "0b1111011010101100"; ram[316] = "0b1111011101001001"; ram[317] = "0b1111111001010111"; ram[318] = "0b0000000100101001"; ram[319] = "0b1111110011010000"; ram[320] = "0b1111011101111001"; ram[321] = "0b1111100100011100"; ram[322] = "0b0000001101110101"; ram[323] = "0b1111100001000110"; ram[324] = "0b1111010101001101"; ram[325] = "0b1111111010110110"; ram[326] = "0b0000011100001110"; ram[327] = "0b0000010110000110"; ram[328] = "0b0000010111100000"; ram[329] = "0b0000010101011110"; ram[330] = "0b0000000001011010"; ram[331] = "0b0000001000001010"; ram[332] = "0b1111101011010001"; ram[333] = "0b0000000011001001"; ram[334] = "0b0000000011001110"; ram[335] = "0b0000000001000111"; ram[336] = "0b1111110100101110"; ram[337] = "0b1101100111000111"; ram[338] = "0b1001011100000000"; ram[339] = "0b0000000000000000"; ram[340] = "0b1111101110001111"; ram[341] = "0b1111101110100100"; ram[342] = "0b0000100000101010"; ram[343] = "0b1111110011011010"; ram[344] = "0b0000010100101011"; ram[345] = "0b0000010000010100"; ram[346] = "0b0000000010000000"; ram[347] = "0b1111110001101010"; ram[348] = "0b0000001010101111"; ram[349] = "0b0000001110101101"; ram[350] = "0b0000000000001101"; ram[351] = "0b1111110011110000"; ram[352] = "0b1111110001010001"; ram[353] = "0b0000000111100001"; ram[354] = "0b1111110100011001"; ram[355] = "0b1111110011000111"; ram[356] = "0b0001010100101101"; ram[357] = "0b0000110100000010"; ram[358] = "0b0001110010100101"; ram[359] = "0b1111111001100111"; ram[360] = "0b1111111101110010"; ram[361] = "0b1111110110100110"; ram[362] = "0b1111111101010100"; ram[363] = "0b1111011000011110"; ram[364] = "0b0000000011011010"; ram[365] = "0b0000000100110010"; ram[366] = "0b1111101111000011"; ram[367] = "0b0000110010001010"; ram[368] = "0b1110010000111110"; ram[369] = "0b1111011101111101"; ram[370] = "0b1111111100010110"; ram[371] = "0b1111010101001101"; ram[372] = "0b1111110011101100"; ram[373] = "0b0000001100100110"; ram[374] = "0b1111110001101101"; ram[375] = "0b1111110111000000"; ram[376] = "0b1110100001100000"; ram[377] = "0b0000100000000000"; ram[378] = "0b0000000101101100"; ram[379] = "0b0000101011010000"; ram[380] = "0b0000001000101110"; ram[381] = "0b0000011011000011"; ram[382] = "0b1111111101110101"; ram[383] = "0b0000101100110111"; ram[384] = "0b1111100110010011"; ram[385] = "0b1111111001101100"; ram[386] = "0b1111111100011110"; ram[387] = "0b1111110010101110"; ram[388] = "0b0000011011001100"; ram[389] = "0b1110110010011000"; ram[390] = "0b0000100011110010"; ram[391] = "0b1111110001110001"; ram[392] = "0b1111110011001101"; ram[393] = "0b1111100111111110"; ram[394] = "0b0000000011001110"; ram[395] = "0b0000000001011100"; ram[396] = "0b0000101110101001"; ram[397] = "0b1111110010101101"; ram[398] = "0b1111110111111110"; ram[399] = "0b0000011111011110"; ram[400] = "0b1111111000101101"; ram[401] = "0b0000001100111101"; ram[402] = "0b0000001111111010"; ram[403] = "0b0000100100010110"; ram[404] = "0b0000100110000100"; ram[405] = "0b0000001110111011"; ram[406] = "0b1111111110011011"; ram[407] = "0b0000001010100100"; ram[408] = "0b0000011001101100"; ram[409] = "0b0000001100100011"; ram[410] = "0b1111101010010011"; ram[411] = "0b1111101111011101"; ram[412] = "0b0000000110000011"; ram[413] = "0b1111010111001111"; ram[414] = "0b1111101110010101"; ram[415] = "0b1111001110101010"; ram[416] = "0b1111110011000000"; ram[417] = "0b1111110100111011"; ram[418] = "0b1111111111101011"; ram[419] = "0b0000001001111010"; ram[420] = "0b0000000110001000"; ram[421] = "0b1111110010110010"; ram[422] = "0b0000001111111101"; ram[423] = "0b0000001100101110"; ram[424] = "0b0000001101101110"; ram[425] = "0b1111111100001110"; ram[426] = "0b1101110101011110"; ram[427] = "0b0000001000101101"; ram[428] = "0b1111110110001010"; ram[429] = "0b0000010011010110"; ram[430] = "0b0000000100010111"; ram[431] = "0b1111111111110011"; ram[432] = "0b0000000000101000"; ram[433] = "0b1111111001011010"; ram[434] = "0b0000001010011110"; ram[435] = "0b0000000101100101"; ram[436] = "0b0000100010101001"; ram[437] = "0b1111000111011010"; ram[438] = "0b0000011111110100"; ram[439] = "0b0000000001100000"; ram[440] = "0b1111111111110000"; ram[441] = "0b1111110001100000"; ram[442] = "0b0000000011110000"; ram[443] = "0b0000000000001001"; ram[444] = "0b0000110000110110"; ram[445] = "0b1111101110111000"; ram[446] = "0b1110101111110110"; ram[447] = "0b0000101000011011"; ram[448] = "0b1111110101100001"; ram[449] = "0b1111110110100111"; ram[450] = "0b0000001110001110"; ram[451] = "0b0000001000100010"; ram[452] = "0b0000010010001111"; ram[453] = "0b1111101110110101"; ram[454] = "0b1111111100111000"; ram[455] = "0b1111111100011111"; ram[456] = "0b1111110101010111"; ram[457] = "0b1111110111101001"; ram[458] = "0b1111011110110011"; ram[459] = "0b0000001011100110"; ram[460] = "0b1111011011001101"; ram[461] = "0b1111011111011110"; ram[462] = "0b0000001111001101"; ram[463] = "0b0000010111111110"; ram[464] = "0b0000111001111010"; ram[465] = "0b1110001110000000"; ram[466] = "0b1111111110000011"; ram[467] = "0b1111111110011100"; ram[468] = "0b0011010100011010"; ram[469] = "0b0000000010110010"; ram[470] = "0b0000000010000111"; ram[471] = "0b0000010111110110"; ram[472] = "0b0000000010100010"; ram[473] = "0b1111101110010100"; ram[474] = "0b1111101110001010"; ram[475] = "0b0000001110110100"; ram[476] = "0b1111100101101101"; ram[477] = "0b0000000101001110"; ram[478] = "0b0000000011001111"; ram[479] = "0b1111011010101101"; ram[480] = "0b1111011100111110"; ram[481] = "0b1111101110000110"; ram[482] = "0b0000000001011011"; ram[483] = "0b1111101110000110"; ram[484] = "0b1111110111111011"; ram[485] = "0b1111110110011100"; ram[486] = "0b1111010000000001"; ram[487] = "0b0000010100111111"; ram[488] = "0b0000100011100111"; ram[489] = "0b1111101100110011"; ram[490] = "0b0001010010111000"; ram[491] = "0b0000001010111000"; ram[492] = "0b1111111110001010"; ram[493] = "0b1111111011100000"; ram[494] = "0b1111101010110000"; ram[495] = "0b0000000011110111"; ram[496] = "0b0000000000011001"; ram[497] = "0b0000100011011111"; ram[498] = "0b1111111010101100"; ram[499] = "0b0000001100110110"; ram[500] = "0b0000001100100110"; ram[501] = "0b1111101110110110"; ram[502] = "0b0000011100110011"; ram[503] = "0b1111101011000100"; ram[504] = "0b1111110101100100"; ram[505] = "0b1111111000110000"; ram[506] = "0b0000101010011000"; ram[507] = "0b0000000100010110"; ram[508] = "0b0000101110010111"; ram[509] = "0b0000000111101101"; ram[510] = "0b0000010100100111"; ram[511] = "0b1111111111111000"; SC_METHOD(prc_write_0); sensitive<<clk.pos(); } void prc_write_0() { if (ce0.read() == sc_dt::Log_1) { if(address0.read().is_01() && address0.read().to_uint()<AddressRange) q0 = ram[address0.read().to_uint()]; else q0 = sc_lv<DataWidth>(); } } }; //endmodule SC_MODULE(StreamingFCLayer_Batch_6_Matrix_Vector_Actbkb) { static const unsigned DataWidth = 16; static const unsigned AddressRange = 512; static const unsigned AddressWidth = 9; sc_core::sc_in <sc_lv<AddressWidth> > address0; sc_core::sc_in<sc_logic> ce0; sc_core::sc_out <sc_lv<DataWidth> > q0; sc_core::sc_in<sc_logic> reset; sc_core::sc_in<bool> clk; StreamingFCLayer_Batch_6_Matrix_Vector_Actbkb_ram* meminst; SC_CTOR(StreamingFCLayer_Batch_6_Matrix_Vector_Actbkb) { meminst = new StreamingFCLayer_Batch_6_Matrix_Vector_Actbkb_ram("StreamingFCLayer_Batch_6_Matrix_Vector_Actbkb_ram"); meminst->address0(address0); meminst->ce0(ce0); meminst->q0(q0); meminst->reset(reset); meminst->clk(clk); } ~StreamingFCLayer_Batch_6_Matrix_Vector_Actbkb() { delete meminst; } };//endmodule #endif
38ceb595c0b65ee8c6dfb1770bb2ebc94188d4ef
1cedf5abe49887cf7a3b733231880413ec209252
/TinyGame/ConsoleFrame.h
25d44a678d45d3ff18317a6f6581ff41a40d03cf
[]
no_license
uvbs/GameProject
67d9f718458e0da636be4ad293c9e92a721a8921
0105e36971950916019a970df1b4955835e121ce
refs/heads/master
2020-04-14T22:35:24.643887
2015-09-02T06:55:54
2015-09-02T06:55:54
42,047,051
1
0
null
2015-09-07T10:34:34
2015-09-07T10:34:33
null
UTF-8
C++
false
false
504
h
ConsoleFrame.h
#ifndef ConsoleFrame_h__ #define ConsoleFrame_h__ #include "GameWidget.h" class ConsoleFrame : public GFrame { typedef GFrame BaseClass; ConsoleFrame( int id , Vec2i const& pos , Vec2i const& size , GWidget* parent ) :BaseClass( id , pos , size , parent ) { mComText = new GTextCtrl( UI_COM_TEXT , Vec2i( 3 , size.y - 3 ) , size.x - 6 , this ); } enum { UI_COM_TEXT = BaseClass::NEXT_UI_ID , }; GTextCtrl* mComText; std::vector< std::string > mString; }; #endif // ConsoleFrame_h__
6788b0076026c31b8937f6feaaa36f7b631537fa
0dc0142475fe40a67750bf878f51c86e9ccb0bf6
/client_test1/xx_coros.h
c6d65d076d2dc5c340dbfbf8991fa7654ef90e21
[]
no_license
denghe/xxlib_cpp
780bad8d7972ecda6c0f8dd097828dc5a52e0bca
14ca77f06a18893148b213239f804aaf855afc1d
refs/heads/master
2020-04-02T02:23:11.104266
2020-01-03T08:53:22
2020-01-03T08:53:22
153,906,209
6
4
null
2019-05-23T14:21:15
2018-10-20T13:03:46
C
UTF-8
C++
false
false
7,703
h
xx_coros.h
#pragma once #include <algorithm> #include <cstddef> #include <cstdint> #include <cstdlib> #include <exception> #include <functional> #include <memory> #include <ostream> #include <tuple> #include <utility> #include "fcontext/fcontext.h" #include <assert.h> //#define BOOST_ASSERT_IS_VOID namespace boost_context { struct forced_unwind { fcontext_t fctx{ nullptr }; #ifndef BOOST_ASSERT_IS_VOID bool caught{ false }; #endif forced_unwind() = default; forced_unwind(fcontext_t fctx_) : fctx(fctx_) { } #ifndef BOOST_ASSERT_IS_VOID ~forced_unwind() { assert(caught); } #endif }; inline fcontext_transfer_t context_unwind(fcontext_transfer_t t) { throw forced_unwind(t.ctx); return { nullptr, nullptr }; } template< typename Rec > fcontext_transfer_t context_exit(fcontext_transfer_t t) noexcept { Rec * rec = static_cast<Rec *>(t.data); // destroy context stack rec->deallocate(); return { nullptr, nullptr }; } template< typename Rec > void context_entry(fcontext_transfer_t t) noexcept { // transfer control structure to the context-stack Rec * rec = static_cast<Rec *>(t.data); assert(nullptr != t.ctx); assert(nullptr != rec); try { // jump back to `create_context()` t = jump_fcontext(t.ctx, nullptr); // start executing t.ctx = rec->run(t.ctx); } catch (forced_unwind const& ex) { t = { ex.fctx, nullptr }; #ifndef BOOST_ASSERT_IS_VOID const_cast<forced_unwind &>(ex).caught = true; #endif } assert(nullptr != t.ctx); // destroy context-stack of `this`context on next context ontop_fcontext(t.ctx, rec, context_exit< Rec >); //BOOST_ASSERT_MSG(false, "context already terminated"); } template< typename Ctx, typename Fn > fcontext_transfer_t context_ontop(fcontext_transfer_t t) { auto p = static_cast<std::tuple< Fn > *>(t.data); assert(nullptr != p); typename std::decay< Fn >::type fn = std::get< 0 >(*p); t.data = nullptr; Ctx c{ t.ctx }; // execute function, pass continuation via reference c = fn(std::move(c)); return { std::exchange(c.fctx_, nullptr), nullptr }; } template< typename Ctx, typename Fn > class record { private: fcontext_stack_t sctx_; typename std::decay< Fn >::type fn_; static void destroy(record * p) noexcept { fcontext_stack_t sctx = p->sctx_; // deallocate record p->~record(); // destroy stack with stack allocator destroy_fcontext_stack(&sctx); } public: record(fcontext_stack_t sctx, Fn && fn) noexcept : sctx_(sctx), fn_(std::forward< Fn >(fn)) { } record(record const&) = delete; record & operator=(record const&) = delete; void deallocate() noexcept { destroy(this); } fcontext_t run(fcontext_t fctx) { Ctx c{ fctx }; // invoke context-function c = fn_(std::move(c)); return std::exchange(c.fctx_, nullptr); } }; template< typename Record, typename Fn > fcontext_t create_context1(Fn && fn, size_t const& stackSize) { auto sctx = create_fcontext_stack(stackSize); // reserve space for control structure void * storage = reinterpret_cast<void *>( (reinterpret_cast<uintptr_t>(sctx.sptr) - static_cast<uintptr_t>(sizeof(Record))) & ~static_cast<uintptr_t>(0xff)); // placment new for control structure on context stack Record * record = new (storage) Record{ sctx, std::forward< Fn >(fn) }; // 64byte gab between control structure and stack top // should be 16byte aligned void * stack_top = reinterpret_cast<void *>( reinterpret_cast<uintptr_t>(storage) - static_cast<uintptr_t>(64)); void * stack_bottom = reinterpret_cast<void *>( reinterpret_cast<uintptr_t>(sctx.sptr) - static_cast<uintptr_t>(sctx.ssize)); // create fast-context const std::size_t size = reinterpret_cast<uintptr_t>(stack_top) - reinterpret_cast<uintptr_t>(stack_bottom); const fcontext_t fctx = make_fcontext(stack_top, size, &context_entry< Record >); assert(nullptr != fctx); // transfer control structure to context-stack return jump_fcontext(fctx, record).ctx; } class continuation { private: template< typename Ctx, typename Fn > friend class record; template< typename Ctx, typename Fn > friend fcontext_transfer_t context_ontop(fcontext_transfer_t); template<typename Fn > friend continuation callcc(Fn &&, size_t const& stackSize = 1024 * 1024); fcontext_t fctx_{ nullptr }; continuation(fcontext_t fctx) noexcept : fctx_{ fctx } { } public: continuation() noexcept = default; ~continuation() { if (nullptr != fctx_) { ontop_fcontext( std::exchange(fctx_, nullptr), nullptr, context_unwind); } } continuation(continuation && other) noexcept { swap(other); } continuation & operator=(continuation && other) noexcept { if (this != &other) { continuation tmp = std::move(other); swap(tmp); } return *this; } continuation(continuation const& other) noexcept = delete; continuation & operator=(continuation const& other) noexcept = delete; continuation resume() & { return std::move(*this).resume(); } continuation resume() && { assert(nullptr != fctx_); return { jump_fcontext( std::exchange(fctx_, nullptr), nullptr).ctx }; } template< typename Fn > continuation resume_with(Fn && fn) & { return std::move(*this).resume_with(std::forward< Fn >(fn)); } template< typename Fn > continuation resume_with(Fn && fn) && { assert(nullptr != fctx_); auto p = std::make_tuple(std::forward< Fn >(fn)); return { ontop_fcontext( std::exchange(fctx_, nullptr), &p, context_ontop< continuation, Fn >).ctx }; } explicit operator bool() const noexcept { return nullptr != fctx_; } bool operator!() const noexcept { return nullptr == fctx_; } bool operator<(continuation const& other) const noexcept { return fctx_ < other.fctx_; } template< typename charT, class traitsT > friend std::basic_ostream< charT, traitsT > & operator<<(std::basic_ostream< charT, traitsT > & os, continuation const& other) { if (nullptr != other.fctx_) { return os << other.fctx_; } else { return os << "{not-a-context}"; } } void swap(continuation & other) noexcept { std::swap(fctx_, other.fctx_); } }; template< typename Fn > continuation callcc(Fn && fn, size_t const& stackSize) { using Record = record< continuation, Fn >; return continuation{ create_context1< Record >( std::forward< Fn >(fn), stackSize) }.resume(); } } #include <vector> #include <functional> #include <stdint.h> #include <assert.h> #include <string.h> namespace xx { struct Coro { boost_context::continuation& c; Coro(boost_context::continuation& c) : c(c) {} inline void operator()() { c = c.resume(); } }; struct Coros { Coros() {}; // [](boost_context::continuation&& c) { ... c = c.resume(); ... return std::move(c); } template<typename Fn> inline void AddCore(Fn&& f) noexcept { cs.emplace_back(std::move(boost_context::callcc(std::move(f)))); } // [](xx::Coro&& yield) {} template<typename Fn> inline void Add(Fn&& f) noexcept { AddCore([f = std::move(f)](boost_context::continuation&& c) { f(Coro(c)); return std::move(c); }); } inline size_t RunOnce() noexcept { if (!cs.size()) return 0; for (decltype(auto) i = cs.size() - 1; i != (size_t)-1; --i) { cs[i] = cs[i].resume(); if (!cs[i]) { if (i + 1 < cs.size()) { std::swap(cs[i], cs[cs.size() - 1]); } cs.pop_back(); } } return cs.size(); } protected: std::vector<boost_context::continuation> cs; }; }
5cb30785f64232033a2031c21a4ea6f100c4c24b
6a117dfa4ec8b89301fc98beaa6efa227094bf1d
/plugins/experimental/ats_pagespeed/ats_config.h
60937d8b3d24df879c5308501f5c61b4404c1b8c
[ "LicenseRef-scancode-unknown", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-3-Clause", "TCL", "MIT", "HPND", "ISC", "BSD-2-Clause" ]
permissive
pixiv/trafficserver
ab1e0736afdfee512d81ffc73b7d5b6eeef3f6bf
79b01ca4e98d1ffde94324ca25ec6c7c3fce5a03
refs/heads/release
2023-04-10T12:01:37.946504
2016-03-02T00:59:27
2016-03-02T00:59:27
52,246,093
1
1
Apache-2.0
2023-03-27T03:04:55
2016-02-22T04:05:04
C++
UTF-8
C++
false
false
2,509
h
ats_config.h
/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ #ifndef ATS_CONFIG_H_ #define ATS_CONFIG_H_ #include <string> #include <vector> #include <ts/ts.h> #include "ats_thread_system.h" #include "net/instaweb/util/public/string.h" #include "net/instaweb/util/public/string_util.h" namespace net_instaweb { class AtsRewriteOptions; class AtsHostConfig { public: explicit AtsHostConfig(const GoogleString &host, AtsRewriteOptions *options) : host_(host), options_(options) {} virtual ~AtsHostConfig(); inline GoogleString host() { return host_; } inline AtsRewriteOptions * options() { return options_; } inline bool override_expiry() { return override_expiry_; } inline void set_override_expiry(bool x) { override_expiry_ = x; } private: GoogleString host_; AtsRewriteOptions *options_; bool override_expiry_; DISALLOW_COPY_AND_ASSIGN(AtsHostConfig); }; // class AtsHostConfig class AtsConfig { friend class AtsHostConfig; public: explicit AtsConfig(AtsThreadSystem *thread_system); virtual ~AtsConfig(); // TODO(oschaaf): destructor?? bool Parse(const char *path); AtsHostConfig *Find(const char *host, int host_length); inline AtsHostConfig * GlobalConfiguration() { return host_configurations_[0]; } AtsThreadSystem * thread_system() { return thread_system_; } private: void AddHostConfig(AtsHostConfig *hc); std::vector<AtsHostConfig *> host_configurations_; AtsThreadSystem *thread_system_; // todo: destructor. delete owned host configurations DISALLOW_COPY_AND_ASSIGN(AtsConfig); }; // class Configuration } // namespace net_instaweb #endif // ATS_CONFIG_H
b6d290914eddadd1d8f8d1cb2f34c0803493198c
a848dcdd1ff87374ae49b7e32e0baee4070dad4c
/top-down/symtable/Scope.cpp
05efa9a17ca204d9473ebd55474b9cafd0399371
[]
no_license
deathly809/compilers
b122ff6d2fefda476ea95979b4a2c214ff349c80
00cd0f7f8e1b8da2fd0da3c4f0c0ee2b741dc112
refs/heads/master
2020-05-21T17:54:53.139474
2017-01-11T18:39:41
2017-01-11T18:39:41
64,435,760
0
0
null
null
null
null
UTF-8
C++
false
false
2,562
cpp
Scope.cpp
#include <symtable/Scope.hpp> #include <symtable/Attribute.hpp> namespace symtable { Scope::Scope(size_t id) : id(id) { // empty } bool Scope::ContainsFunction(std::string name) const { return FunctionIndex(name) != -1; } bool Scope::ContainsVariable(std::string name) const { return VariableIndex(name) != -1; } int Scope::FunctionIndex(std::string name) const { const auto & ptr = funcLookup.find(name); if(ptr == funcLookup.end()) { return -1; } return ptr->second; } int Scope::VariableIndex(std::string name) const { const auto & ptr = varLookup.find(name); if(ptr == varLookup.end()) { return -1; } return ptr->second; } void Scope::InsertFunction(std::shared_ptr<FunctionAttribute> attr) { if(ContainsFunction(attr->GetName())) { throw std::runtime_error("Cannot redefine function: " + attr->GetName()); } funcLookup.insert({attr->GetName(),functions.size()}); functions.push_back(attr); } void Scope::InsertVariable(std::shared_ptr<VariableAttribute> attr) { if(ContainsVariable(attr->GetName())) { throw std::runtime_error("Cannot redefine variable: " + attr->GetName()); } varLookup.insert({attr->GetName(),variables.size()}); variables.push_back(attr); } std::shared_ptr<FunctionAttribute> Scope::GetFunctionAttribute(std::string name) const { int idx = FunctionIndex(name); if(idx == -1) { return nullptr; } return functions[idx]; } std::shared_ptr<VariableAttribute> Scope::GetVariableAttribute(std::string name) const { int idx = VariableIndex(name); if(idx == -1) { return nullptr; } return variables[idx]; } size_t Scope::FunctionCount() const { return functions.size(); } size_t Scope::VariableCount() const { size_t size = 0; for(unsigned int i = 0 ; i < variables.size(); ++i) { size_t s = variables[i]->GetSize(); size += s; } return size; } size_t Scope::GetID() const { return id; } std::ostream& operator<<(std::ostream & os, const Scope & scope) { for( auto & v : scope.variables) { os << *v << " "; } for( auto & f : scope.functions) { os << *f << " "; } return os; } }
dd6d7c2f46e52e87e5486c912687bc00941eea93
1522b7e017f798f43d71d583b4d9f9f523e07ec7
/Arduino/Rover/sketch_jarvis_rover/sketch_jarvis_rover.ino
684e69cf61e81a0af695a22671b18523f9ced8da
[ "Apache-2.0" ]
permissive
caothetoan/JARVIS
241cc9f25847cf95ced614b20c30cb0b61853fae
dba667ef4995829e0dd823450f4082efd49bb926
refs/heads/master
2021-01-17T18:04:42.329505
2019-06-28T09:10:38
2019-06-28T09:10:38
95,536,890
0
1
null
2017-06-27T08:42:08
2017-06-27T08:42:08
null
UTF-8
C++
false
false
1,972
ino
sketch_jarvis_rover.ino
const int inputPin1 = 10; const int inputPin2 = 11; const int inputPin3 = 12; const int motorAPin1 = 7; const int motorAPin2 = 6; const int motorBPin1 = 5; const int motorBPin2 = 4; // variables for input pins int input1State = 0; int input2State = 0; int input3State = 0; void setup() { // initialize the input pins pinMode(inputPin1, INPUT); pinMode(inputPin2, INPUT); pinMode(inputPin3, INPUT); // initialize the LED pin as an output: pinMode(motorAPin1, OUTPUT); pinMode(motorAPin2, OUTPUT); pinMode(motorBPin1, OUTPUT); pinMode(motorBPin2, OUTPUT); } void loop() { // read the state of the input pins: input1State = digitalRead(inputPin1); input2State = digitalRead(inputPin2); input3State = digitalRead(inputPin3); // check for input command // check for FORWARD if (input1State == HIGH && input2State == HIGH && input3State == LOW) { // move forward digitalWrite(motorAPin1, HIGH); digitalWrite(motorAPin2, LOW); digitalWrite(motorBPin1, LOW); digitalWrite(motorBPin2, HIGH); } else if (input1State == LOW && input2State == LOW && input3State == LOW) { // move backward digitalWrite(motorAPin1, LOW); digitalWrite(motorAPin2, HIGH); digitalWrite(motorBPin1, HIGH); digitalWrite(motorBPin2, LOW); } else if (input1State == HIGH && input2State == LOW && input3State == LOW) { // turn left digitalWrite(motorAPin1, HIGH); digitalWrite(motorAPin2, LOW); digitalWrite(motorBPin1, LOW); digitalWrite(motorBPin2, LOW); } else if (input1State == LOW && input2State == HIGH && input3State == LOW) { // turn right digitalWrite(motorAPin1, LOW); digitalWrite(motorAPin2, LOW); digitalWrite(motorBPin1, LOW); digitalWrite(motorBPin2, HIGH); } else if (input3State == HIGH) { // stop digitalWrite(motorAPin1, LOW); digitalWrite(motorAPin2, LOW); digitalWrite(motorBPin1, LOW); digitalWrite(motorBPin2, LOW); } }
22cb0dc163b6e317be92036a2636f083d2304068
0db39d27f607c11e3690f5e055fda6205ad6c693
/cpp/deletemiddlenode.cpp
8d3a1860496c4bbcc6bdff1464a932e711051610
[]
no_license
deepank1728/workspace
a316a9a5495f7d8bbfa2554c05ab6fe9d36c4b1b
9d1f90a375b40078d9e00225da91cfecdec84d1c
refs/heads/master
2021-01-25T07:40:08.364942
2015-05-26T09:45:36
2015-05-26T09:45:36
28,571,013
0
0
null
null
null
null
UTF-8
C++
false
false
557
cpp
deletemiddlenode.cpp
#include<iostream> #include<cstdlib> using namespace std; typedef struct node { int val; struct node *next; }node; node *getnode(int n) { node *temp=(node *)malloc(sizeof(node)); temp->val=n; temp->next=NULL; return temp; } void display(node *head) { node *p=head; while(p) { cout<<p->val<<" "; p=p->next; } cout<<endl; } int main() { node *head=getnode(0); int size=10; node *p=head; node *middle=NULL; for(int i=1;i<size;i++) { p->next=getnode(i); if(i==size/2) middle=p; p=p->next; } display(head); }
b5a13d8678fb30c7af6f54c4aa716eab59f20aae
307ccdde9c423f1587b34d05385b90fad7b9eb90
/codeforces/cf755/a.cpp
9473cd38943ed104ad8e370d76f1dd4a2bf28cee
[]
no_license
ravi-ojha/competitive-sport
98513e28624f6ff279bf378ba13bb4bed7497704
617847cbc880a9b79173d35c243b4c6f73c3f7a8
refs/heads/master
2021-06-08T14:02:36.233718
2017-08-22T21:47:22
2017-08-22T21:47:22
56,091,058
0
0
null
null
null
null
UTF-8
C++
false
false
824
cpp
a.cpp
#include <bits/stdc++.h> #define DEBUG true using namespace std; int isprime[10000001] = {0}; void sieve() { int i = 2, j; isprime[0] = 1; isprime[1] = 1; for(i=2;i*i<=10000000;i++) { // if the number is marked, it is skipped if(isprime[i]==1) { continue; } for(j=i*2;j<=10000000;j+=i) { // Mark every multiple of i isprime[j]=1; } } } int main() { sieve(); for(int t=1;t<=1000;t++) { int n; //scanf(" %d",&n); n = t; int result = 1; for(int i=1; i<1001; i++) { int tmp = n*i + 1; if(isprime[tmp] == 1) { result = i; break; } } printf("%d\n", result); } return 0; }
13a46397e8c4b5bef75d1afa8989383ea8948345
4f31b8026d4f165c9ea13395a617439593426617
/panorama_stitching_interface.cpp
2f46e1dcb2898541f084ab97bbbaa6de1f58bbb9
[]
no_license
evaesqmor/FinalProject_Multimedia_Applications
d3875809b472533fc93aabfd29e64652b033de11
326ce6c8b9e4d7ca95b9c6970f191222b7a8a013
refs/heads/master
2020-09-07T12:52:38.252305
2019-06-11T06:42:22
2019-06-11T06:42:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,511
cpp
panorama_stitching_interface.cpp
// CPP program to Stitch // input images (panorama) using OpenCV #include <iostream> #include <fstream> // Include header files from OpenCV directory // required to stitch images. #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include "opencv2/stitching.hpp" #define CVUI_IMPLEMENTATION #include "cvui-2.7.0/cvui.h" #define WINDOW_NAME "Crop Image" using namespace std; using namespace cv; Stitcher::Mode mode = Stitcher::PANORAMA; vector<Mat> imgs; Mat img1; Mat img2; Mat img3; Mat img4; int main(int argc, char* argv[]){ cvui::init(WINDOW_NAME, 20); Mat frame = cv::Mat(cv::Size(450, 300), CV_8UC3); bool stitch =false; bool image1 = false; bool image2 = false; bool image3 = false; bool image4 = false; img1= imread("Images/eiffel1.jpeg"); if(img1.empty()){ cout<<"Image 1 is empty."; return -1; } namedWindow("Photo1", CV_MINOR_VERSION); moveWindow("Photo1",70 + frame.cols, 20); imshow("Photo1", img1); img2= imread("Images/eiffel2.jpeg"); if(img2.empty()){ cout<<"Image 2 is empty."; return -1; } namedWindow("Photo2", CV_MINOR_VERSION); moveWindow("Photo2",frame.cols+500, 20); imshow("Photo2", img2); img3= imread("Images/eiffel3.jpeg"); if(img3.empty()){ cout<<"Image 3 is empty."; return -1; } namedWindow("Photo3", CV_MINOR_VERSION); moveWindow("Photo3",frame.cols+70, 100+frame.rows); imshow("Photo3", img3); img4= imread("Images/eiffel4.jpeg"); if(img4.empty()){ cout<<"Image 4 is empty."; return -1; } namedWindow("Photo4", CV_MINOR_VERSION); moveWindow("Photo4",frame.cols+500, 100+frame.rows); imshow("Photo4", img4); imgs.push_back(img1); imgs.push_back(img2); imgs.push_back(img3); imgs.push_back(img4); while(true){ frame = cv::Scalar(49, 52, 49); cvui::beginColumn(frame, 20, 20, -1, -1, 6); cvui::checkbox(frame, 25, 50, "Stitch", &stitch); if(stitch){ cvDestroyWindow("Photo1"); cvDestroyWindow("Photo2"); cvDestroyWindow("Photo3"); cvDestroyWindow("Photo4"); Mat pano; Ptr<Stitcher> stitcher = Stitcher::create(mode); Stitcher::Status status = stitcher->stitch(imgs, pano); if (status != Stitcher::OK){ cvui::text(frame, 90, 250, "STATUS NOT OK"); } imwrite("Images/stress.jpg", pano); Mat res = imread("Images/stitch.jpg"); namedWindow("Result", CV_MINOR_VERSION); moveWindow("Result",100 + frame.cols, 80); imshow("Result", pano); } cvui::endColumn(); cvui::update(); cv::imshow(WINDOW_NAME, frame); } return 0; }
c578e7559a5b7f8b320b718386563b1e2b12aa30
a5f08f257e75ff14656c68e374f7ef1536b1bde3
/Subsystems/Turret.h
0dc675657c0063a33d3452f0483e84af59e1efad
[]
no_license
Team293/Robot-Code-2012
3a0d41c0f1eada5795182158a179133e085e02d9
60992c0145e76c4ed3fda9527cadef094c82ade2
refs/heads/master
2021-01-10T21:29:51.680556
2012-02-12T20:03:09
2012-02-12T20:03:09
3,105,053
1
0
null
null
null
null
UTF-8
C++
false
false
545
h
Turret.h
#ifndef TURRET_H #define TURRET_H #include "Commands/PIDSubsystem.h" #include "WPILib.h" /** * * * @author Administrator */ class Turret: public PIDSubsystem { private: // It's desirable that everything possible under private except // for methods that implement subsystem capabilities // set the P, I, and D constants here static const double Kp = 0.0; static const double Ki = 0.0; static const double Kd = 0.0; public: Turret(); double ReturnPIDInput(); void UsePIDOutput(double output); void InitDefaultCommand(); }; #endif
5047e97d9815bd4d895c6fab80af27cf2f3d8c66
5651adaf9fda94f4322244c14d0c3787a8ceb0ff
/Source/YINPitchDetector.h
69201d9f41193f3488bea113a74123a8e061f2fe
[ "MIT" ]
permissive
dave-foster/bass-autotune
cdc7af3962f645b7ff62ca7339c4295c4ffe0401
d8ae42e4be6ceaa371902cd595624f5fc8de8749
refs/heads/master
2020-04-01T10:14:15.886780
2018-10-15T12:29:52
2018-10-15T12:29:52
153,108,900
1
2
null
null
null
null
UTF-8
C++
false
false
816
h
YINPitchDetector.h
/* ============================================================================== Dave Foster Swing City Music ============================================================================== */ /***** YINPitchDetector.h *****/ /* Takes a buffer of samples, and performs the YIN algorithm for pitch detection Stores the pitch value as an ivar, as well as the confidence value The closer the confidence value is to zero, the better chance it is correct! */ class YINPitchDetector { public: // Methods YINPitchDetector(); YINPitchDetector(float sampleRate, int bufferSize, float threshold); float calculatePitch(float* inputBuffer); // Variables float pitchYIN_; float confidenceYIN_; private: // Variables int bufferSize_; float sampleRate_; float threshold_; float* outputBuffer_; };
90605d510062d3bc745b8668ae7fd55fd46903ee
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5634947029139456_0/C++/ganatcs/A.cpp
178f36a9fc0a8d57a4120ef1129e9fc7b1403822
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
3,251
cpp
A.cpp
#include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <list> #include <deque> #include <algorithm> #include <functional> #include <sstream> #include <complex> #include <stack> #include <bitset> #include <queue> using namespace std; //conversion inline int toInt(string s) {int v; istringstream sin(s);sin>>v;return v;} template<class T> inline string toString(T x) {ostringstream sout;sout<<x;return sout.str();} //typedef typedef vector<int> VI; typedef vector<VI> VVI; typedef vector<string> VS; typedef pair<int, int> PII; typedef long long ll; //container util #define ALL(a) (a).begin(),(a).end() #define RALL(a) (a).rbegin(), (a).rend() #define PB push_back #define MP make_pair #define SZ(a) int((a).size()) #define EACH(i,c) for(typeof((c).begin()) i=(c).begin(); i!=(c).end(); ++i) //constant const double EPS = 1e-10; const int MAXI = 1234567890; //debug #define dump(x) cerr << #x << " = " << (x) << endl; #define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl; void printList(const vector<bitset<10> >& v) { for (size_t i = 0; i < v.size(); i++) { cout << v[i] << " "; } cout << endl; } void printMatrix(vector< vector<bitset<10> > >& v) { for (size_t i = 0; i < v.size(); i++) { printList(v[i]); } cout << endl; } int flip(int b, const vector<bitset<10> >& flow, vector<bitset<10> >& fliped) { int ans = 0; fliped = flow; int k = -1; while (b > 0) { k++; int t = b % 2; b = b / 2; if (t == 0) continue; ans++; for (size_t i = 0; i < flow.size(); i++) { fliped[i].flip(k); } } return ans; } bool is_ok(const vector<bitset<10> >& a, const vector<bitset<10> >& b) { for (size_t i = 0; i < a.size(); i++) { bool found = false; for (size_t j = 0; j < b.size(); j++) { if (a[i] != b[j]) continue; found = true; } if (!found) return false; } return true; } int solve(int N, int L, vector<string>& flow0, vector<string>& req0) { vector< bitset<10> > flow; vector< bitset<10> > req; for (size_t i = 0; i < flow0.size(); i++) { flow.push_back(bitset<10>(flow0[i])); req.push_back(bitset<10>(req0[i])); } int minv = 100; if (is_ok(flow, req)) minv = 0; for (int i = 1; i < 1 << L; i++) { vector< bitset<10> > fliped; int t = flip(i, flow, fliped); if (is_ok(fliped, req)) { minv = min(minv, t); } } return minv; } int main() { int T; cin >> T; for (int i = 0; i < T; i++) { int N, L; cin >> N >> L; vector<string> flow; vector<string> req; for (int j = 0; j < N; j++) { string s; cin >> s; flow.push_back(s); } for (int j = 0; j < N; j++) { string s; cin >> s; req.push_back(s); } int ans = solve(N, L, flow, req); cout << "Case #" << i + 1 << ": "; if (ans < 100) cout << ans << endl; else cout << "NOT POSSIBLE" << endl; } return 0; }
621a0a70ebe2c8ff90fbaeb2e64c3eedc0f9e7c8
f60796674e5410ce733f8e7de704bce5e5a0a45b
/Source/Virtusonic/Song/TimelineActions/StringInstrument/StringReleaseAction.h
99b117e20c808b6a0ee0f1b95874e8f2577255d5
[ "Apache-2.0" ]
permissive
lkunic/Virtusonic
835303be940167606865041ebadc18f122a21f34
97b2cbf90ee707b7d609f0a739ebdf183a6f8c90
refs/heads/master
2022-09-05T05:19:01.719724
2022-09-01T21:03:02
2022-09-01T21:03:02
63,863,141
0
0
null
null
null
null
UTF-8
C++
false
false
523
h
StringReleaseAction.h
// Copyright (c) Luka Kunic, 2016. #pragma once #include "Song/TimelineActions/BaseTimelineAction.h" #include "String/String.h" #include "StringReleaseAction.generated.h" /** * */ UCLASS() class VIRTUSONIC_API UStringReleaseAction : public UBaseTimelineAction { GENERATED_BODY() public: void Init(AString *string, int8 fret, int32 noteStartTick, float releaseDuration); virtual void Execute() override; private: UPROPERTY() AString *mString; int8 mFret; int32 mNoteStartTick; float mReleaseDuration; };
a2a33215daf52bc52813af47708eb93267ea7650
6b6f98e1a034a937cd88c64cc42e7030d75e5147
/Foundation of Object-Oriented Programming/finale/MLP_test.cpp
dba61344d24995239d2950dcd34c2ec457f7206e
[]
no_license
youyl/Course-Projects-THU
13d721b3985e2e83bc8a094aaf5b94c4d899f1e0
7bf6057065a8a4ec1d56e92d15a34d4b7283e228
refs/heads/master
2022-11-10T13:58:32.229985
2020-06-30T15:19:12
2020-06-30T15:19:12
276,116,191
1
0
null
null
null
null
UTF-8
C++
false
false
3,968
cpp
MLP_test.cpp
//用于测试神经网络 #include <iostream> #include <cstring> #include <sstream> #include <ctime> #include <vector> #include "tt.h" using namespace std; const int SampleSize[]={980,1135,1032,1010,982,892,958,1028,974,1009};//测试集中每个数字对应的图片数量 Graph *graph; MLP *nn; void print(int n,int m,vector<float> x)//将vector中的数以字符画的形式打印出来,用于显示mnist中的图片 { for (int i=0;i<n;i++) { for (int j=0;j<m;j++) { float tmp=x[i*m+j]; if(tmp<0.1)cout<<". "; else cout<<"# "; }cout<<endl; }cout<<endl; } void GraphConstruction1()//使用sigmoid做激活函数的神经网络,含有一个300个点的隐藏层 { graph=new Graph; graph->new_PlaceHolder("Input",{784,1}); graph->new_PlaceHolder("Answer",{10,1}); graph->new_Variable("Weight1",{300,784}); graph->new_Variable("Bias1",{300,1}); graph->new_Variable("Weight2",{10,300}); graph->new_Variable("Bias2",{10,1}); graph->new_Binary("t11","MATMUL","Weight1","Input"); graph->new_Binary("t12","+","Bias1","t11"); graph->new_Unary("x1","SIGMOID","t12"); graph->new_Binary("t21","MATMUL","Weight2","x1"); graph->new_Binary("t22","+","Bias2","t21"); graph->new_Unary("Output","SIGMOID","t22"); graph->new_Binary("Loss","LOSS","Output","Answer"); graph->new_Unary("Grad","GRAD","Loss"); } void GraphConstruction2()//使用tanh做激活函数的神经网络,含有一个300个点的隐藏层 { graph=new Graph; graph->new_PlaceHolder("Input",{784,1}); graph->new_PlaceHolder("Answer",{10,1}); graph->new_Variable("Weight1",{300,784}); graph->new_Variable("Bias1",{300,1}); graph->new_Variable("Weight2",{10,300}); graph->new_Variable("Bias2",{10,1}); graph->new_Binary("t11","MATMUL","Weight1","Input"); graph->new_Binary("t12","+","Bias1","t11"); graph->new_Unary("x1","TANH","t12"); graph->new_Binary("t21","MATMUL","Weight2","x1"); graph->new_Binary("t22","+","Bias2","t21"); graph->new_Unary("Output","TANH","t22"); graph->new_Binary("Loss","LOSS","Output","Answer"); graph->new_Unary("Grad","GRAD","Loss"); } //---------------------------------------------------------------------------------------------------------------------------------------- vector<vector<float> >image; vector<vector<float> >answer; const string filename="LR2.000000-1000Batch-BatchSize128-Correct9442-Graph2";//需要读取的参数文件名称 int main() { // GraphConstruction1(); GraphConstruction2(); //这里可以选择使用神经网络的种类 nn=new MLP(graph); nn->sess->Import("parameter/Parameter-"+filename+".txt");//从文件读入参数 vector<float>onehot; ios::sync_with_stdio(0); for (int i=0;i<10;i++) { onehot.push_back(0); } for (int id=0;id<10;id++) { onehot[id]=1; for (int num=0;num<SampleSize[id];num++) { string filename="mnist/mnist_digits_test_images/"+to_string(id)+"/"+to_string(num)+".txt";//读入测试集 ifstream fin(filename.c_str()); vector<float>tmp; tmp.resize(784); float mxx=0; for (int i=0;i<784;i++) { fin>>tmp[i]; mxx=max(mxx,tmp[i]); } for (int i=0;i<784;i++) { tmp[i]/=mxx;//标准化数据 } image.push_back(tmp); answer.push_back(onehot); fin.close(); } onehot[id]=0; } cout<<"Testset Extracted, a total of "<<image.size()<<" images loaded"<<endl; int cor=nn->TestBatch(image,answer); cout<<"MLP "<<filename<<" has an accuracy of "<<cor*1.0/10000.0<<" on Test Set"<<endl;//输出对测试集的结果 cout<<"50 Samples:"<<endl; srand(time(0));//初始化随机种子,保证真随机 for (int i=1;i<=50;i++)//随机展示50个测试集中的图片和对应的结果 { int rd=randv(9999); cout<<"Image No."<<rd<<endl; print(28,28,image[rd]); print(1,10,answer[rd]); cout<<"MLP "<<filename<<" says it's number "<<nn->SingleTest(image[rd],answer[rd])<<endl; // system("pause");//在本地运行的时候建议解除这一行的注释,以方便观察结果 } return 0; }
3b9945a7985bde39a965b124e2f52b5e3eae83c3
b13d48beb579d65f0ce82579227a7caedc8eb233
/minesolver/CompWinProp.cpp
4eb92f6f185c5a2ad067d0a684789f7e5ca45172
[]
no_license
curtisbright/swinekeeper
2e451afbdbd388e64e00328c78bc37e5c258f8a5
d78601cfa04ced0d30c96246a84615770776e87a
refs/heads/main
2023-02-16T23:48:10.813157
2021-01-12T19:44:10
2021-01-12T19:44:10
329,094,106
1
0
null
null
null
null
UTF-8
C++
false
false
4,317
cpp
CompWinProp.cpp
#include "StdAfx.h" #include "CompWinProp.h" #include "CompProbabilities.h" #include "SolutionIter.h" #include <cstdio> struct CacheEntry { CacheEntry() {pV[0] = 0; pV[1] = 0; dVal = -1;} bool equalID(CacheEntry &val) {return pV[0] == val.pV[0] && pV[1] == val.pV[1];} int pV[2]; float dVal; }; static int nCached = 0; static int nComp = 0; double compTotalProp_Cached( CMineArray &inputArray, int nTotalBombCount) { int pV[2]; pV[0] = 0; pV[1] = 0; inputArray.toInt((char*)pV, 8); static CacheEntry *pEntries = NULL; if (!pEntries) { pEntries = new CacheEntry[0x10000]; } int nIdx = (((pV[0] * pV[1])>>16) + ((pV[0] * 1232232123) >> 14) + ((pV[1] * 12355341) >> 17) ) & 0xffff; CacheEntry newEntry; newEntry.pV[0]= pV[0]; newEntry.pV[1]= pV[1]; if (pEntries[nIdx].dVal<0 || !pEntries[nIdx].equalID(newEntry)) { newEntry.dVal = compTotalProp(inputArray, nTotalBombCount); pEntries[nIdx] = newEntry; } else { nCached++; } nComp++; //float compVal = float(compTotalProp(inputArray, nTotalBombCount)); //assert(pEntries[nIdx].dVal == compVal); return pEntries[nIdx].dVal; } double compWinProp_Aux( CMineArray &inputResArray, const CFieldPos &pos, int nTotalBombCount); double compWinProp( CMineArray &inputResArray, int nTotalBombCount, CMineArrayBase<CResultField> *pResultArray = NULL) { CMineArrayBase<CPropField> resultArray; if (!compProbabilities_Aux(resultArray, inputResArray, nTotalBombCount)) { assert(0); return 0; } for(CRangeIterator iter(inputResArray.range()); iter.isValid(); iter++) { if (inputResArray[iter.curPos()].isCovered()) { if (resultArray[iter.curPos()].isKnownBomb()) { if (pResultArray) (*pResultArray)[iter.curPos()].setProp(0); } } } double dMaxWinProp(0); bool bAllResolved(true); for(CRangeIterator iter2(inputResArray.range()); iter2.isValid(); iter2++) { if (pResultArray) { printf("%s", "*"); fflush(NULL); } if (inputResArray[iter2.curPos()].isCovered() && !resultArray[iter2.curPos()].isKnownBomb()&& !resultArray[iter2.curPos()].isKnownNoBomb()) bAllResolved = false; if (inputResArray[iter2.curPos()].isCovered() && !resultArray[iter2.curPos()].isKnownBomb()) { double dProp = compWinProp_Aux(inputResArray, iter2.curPos(), nTotalBombCount); if (pResultArray) { (*pResultArray)[iter2.curPos()].setProp(dProp); printf("%f", dProp); } if (dProp > dMaxWinProp) dMaxWinProp = dProp; } } if (pResultArray) printf("\n"); //assert(dMaxWinProp >= -.01 && dMaxWinProp <= 1.01); if (bAllResolved) return 1; else return dMaxWinProp; } bool compWinProp( CMineArrayBase<CResultField> &resultArray, const CMineArrayBase<CInputField> &inputArray, int nTotalBombCount) { CMineArray solveArray; inputArrayToSolveArray(solveArray, inputArray); resultArray.resize(inputArray.range()); compWinProp(solveArray, nTotalBombCount, &resultArray); return true; } double compWinProp_Aux( CMineArray &inputResArray, const CFieldPos &pos, int nTotalBombCount) { CMineArray tmpArray = inputResArray; assert(inputResArray[pos].isCovered()); double dBaseProp = compTotalProp/*_Cached*/(tmpArray, nTotalBombCount); double dWinProp(0); double dSumProp(0); for(int i=0;i<=8;i++) { CMineArray tmpArray = inputResArray; assert(tmpArray[pos].isCovered()); tmpArray[pos] = CFieldValue(); tmpArray[pos].setCount(i); double dTotalProp = compTotalProp/*_Cached*/(tmpArray, nTotalBombCount)/dBaseProp; if (dTotalProp > 1e-6) { dWinProp += dTotalProp * compWinProp(tmpArray, nTotalBombCount); dSumProp += dTotalProp; } if (!(dWinProp >= -.01 && dWinProp <= 1.01 && dWinProp <= dSumProp+.01)) { printf("error!"); assert(0); } } return dWinProp; }
8a9ef581c65f6ea05e29dc0cf05be35d5b2a2cc7
071be7ddd32bc7ddbf2c7e891d62cbaac74670a6
/spaceinvaders/ship.cpp
041a44ef605695bd16da6cbc434316e7fad4f47e
[]
no_license
sarajohanna/spaceinvaders
1a4628c71c6e19ef77fa99db324d3141a7010048
e936f50c6f459c894112ec62698a0bf663f59fb8
refs/heads/master
2021-01-11T23:19:29.026174
2017-03-06T16:56:14
2017-03-06T16:56:14
76,804,339
0
0
null
null
null
null
UTF-8
C++
false
false
1,780
cpp
ship.cpp
// // ship.cpp // spaceinvaders // // Created by Sara Lindström on 2017-01-09. // Copyright © 2017 Sara Lindström. All rights reserved. // #include "ship.hpp" Ship::Ship(const Coords& coords) { _coords.x = coords.x; _coords.y = coords.y; } void Ship::update() { _center.x = _coords.x + _imgWidth/2; _center.y = _coords.y + _imgHeight/2; //Update position of ship with its speed and delta time const float& deltaTime = timer.getDeltaTime(); // dtBullet will decrease until it is the same as -interval (how much time between bullets) _dtBullet = fmax(_dtBullet - deltaTime, -_dtBulletInterval); if ((keysHeld[KEY_RIGHT]) && (_coords.x < 750)) _coords.x += _speedX * deltaTime; else if ((keysHeld[KEY_LEFT]) && (_coords.x > 30)) _coords.x -= (_speedX * deltaTime); else if (keysHeld[KEY_SPACE]) { //When dtBullet is -interval, shoot a bullet if (_dtBulletInterval + _dtBullet <= 0) { _bullets.push_back(Bullet(_coords)); //Reset timer to 0 _dtBullet += _dtBulletInterval; } } // Uppdate bullets and if they are outside of screen, remove them for (int i = 0; i < _bullets.size(); ++i) { _bullets[i].update(); if (_bullets[i].getCoords().y <= 0) { _bullets[i] = _bullets[_bullets.size() - 1]; _bullets.pop_back(); } } } void Ship::draw() { drawObject(SPRITE_SHIP, _coords, _imgWidth, _imgHeight); for (int i = 0; i < _bullets.size(); ++i) { _bullets[i].draw(); } } std::vector<Bullet>& Ship::accessBullets() { return _bullets; } const Coords& Ship::getCenter() const { return _center; } Ship::~Ship() { }
14768a8643771bb5687e51bd980891fd1e9ee630
dfecb46d156638d4f1ce74df7cf874e3976ec1b4
/anti-distractinator-9000.ino
8c0d3084fe5b40132273f05e35376d8169de0e78
[]
no_license
drewdulz/anti-distractinator-9000
432d49cce8da4344835be5762b7b004599cea4b8
db8efe63154024aae674e7dbc7015228d4c254e2
refs/heads/master
2021-01-01T17:40:00.501311
2017-07-23T22:27:45
2017-07-23T22:27:45
98,127,274
1
0
null
null
null
null
UTF-8
C++
false
false
11,197
ino
anti-distractinator-9000.ino
/* CustomCharacter.ino 2013 Copyright (c) Seeed Technology Inc. All right reserved. Author:Loovee 2013-9-18 Grove - Serial LCD RGB Backlight demo. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <Wire.h> #include "rgb_lcd.h" #include <Servo.h> #include "pitches.h" rgb_lcd lcd; int fakemode = 0; Servo myservo1; Servo myservo2; int pos = 90; // notes in the melody: int ohCanada[] = { NOTE_D5, NOTE_F5, NOTE_F5, NOTE_B4, 0, NOTE_C5, NOTE_D5, NOTE_E4, NOTE_F5, NOTE_G5, NOTE_C5 }; // note durations: 4 = quarter note, 8 = eighth note, etc.: int ohCandaDurations[] = { 1, 2, 2, 1, 1, 2, 2, 2, 2, 2, 1 }; int sad[] = { NOTE_A7, NOTE_A7, NOTE_A7, NOTE_A7 }; int sadDurations[] = { 1, 1, 1, 1 }; int happy[] = { NOTE_C1, NOTE_C1, NOTE_C1 }; int happyDurations[] = { 1, 1, 1 }; int ttc[] = { NOTE_E4, NOTE_D4, NOTE_B4 }; int ttcDurations[] = { 1, 1, 1 }; // make some custom characters: byte heart[8] = { 0b00000, 0b01010, 0b11111, 0b11111, 0b11111, 0b01110, 0b00100, 0b00000 }; byte smiley[8] = { 0b00000, 0b00000, 0b01010, 0b00000, 0b00000, 0b10001, 0b01110, 0b00000 }; byte frownie[8] = { 0b00000, 0b00000, 0b01010, 0b00000, 0b00000, 0b00000, 0b01110, 0b10001 }; byte armsDown[8] = { 0b00100, 0b01010, 0b00100, 0b00100, 0b01110, 0b10101, 0b00100, 0b01010 }; byte armsUp[8] = { 0b00100, 0b01010, 0b00100, 0b10101, 0b01110, 0b00100, 0b00100, 0b01010 }; byte solid[8] = { 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111, 0b11111 }; byte upperPupil[8] = { 0b11111, 0b00000, 0b00000, 0b00000, 0b00100, 0b01110, 0b11111, 0b11111 }; byte lowerPupil[8] = { 0b11111, 0b11111, 0b01110, 0b00100, 0b00000, 0b00000, 0b00000, 0b11111 }; byte upperLine[8] = { 0b11111, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000 }; byte lowerLine[8] = { 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b11111 }; byte slash[8] = { 0b10000, 0b01000, 0b01000, 0b00100, 0b00100, 0b00010, 0b00010, 0b00001 }; byte upperRightCurve[8] = { 0b10000, 0b01000, 0b00100, 0b00100, 0b00010, 0b00010, 0b00001, 0b00001 }; byte upperLeftCurve[8] = { 0b00001, 0b00010, 0b00100, 0b00100, 0b01000, 0b01000, 0b10000, 0b10000 }; byte lowerLeftCurve[8] = { 0b10000, 0b10000, 0b01000, 0b01000, 0b00100, 0b00100, 0b00010, 0b00001 }; byte lowerRightCurve[8] = { 0b00001, 0b00001, 0b00010, 0b00010, 0b00100, 0b00100, 0b01000, 0b10000 }; byte upperRightCurve_blink[8] = { 0b10000, 0b11000, 0b11100, 0b11100, 0b11110, 0b11110, 0b11111, 0b11111 }; byte upperLeftCurve_blink[8] = { 0b00001, 0b00011, 0b00111, 0b00111, 0b01111, 0b01111, 0b11111, 0b11111 }; byte lowerLeftCurve_blink[8] = { 0b11111, 0b11111, 0b01111, 0b01111, 0b00111, 0b00111, 0b00011, 0b00001 }; byte lowerRightCurve_blink[8] = { 0b11111, 0b11111, 0b11110, 0b11110, 0b11100, 0b11100, 0b11000, 0b10000 }; int rating = 0; int count = 0; void setup() { // set up the lcd's number of columns and rows: lcd.begin(16, 2); // create a new character lcd.createChar(0, upperLeftCurve); lcd.createChar(1, upperRightCurve); lcd.createChar(2, lowerLeftCurve); lcd.createChar(3, lowerRightCurve); lcd.createChar(4, upperLine); lcd.createChar(5, lowerLine); lcd.createChar(6, upperPupil); lcd.createChar(7, lowerPupil); lcd.setCursor(0, 0); // Print a message to the lcd. //lcd.print("booting up! "); //lcd.write(1); myservo1.attach(3); myservo2.attach(11); myservo1.write(pos); myservo2.write(pos); Serial.begin(19200); Serial.println("alive!"); } void loop() { String message = "start"; if (Serial.available()) { message = Serial.readString(); //lcd.print(message); //lcd.setCursor(0,0); rating = ( (message[0]-'0')*10 + message[1]-'0'); // crazy horrible string to int hack //lcd.print(rating); //delay(1000); } // bin our ratings if (rating != 0) { if (rating <= 9) rating = 10; if (rating != 76 && rating > 13) rating = 13; } if (fakemode == 1) { // now fake it up!! if (rating == 76) rating = 9; rating += 2; if (rating > 13) rating = 76; } switch(rating) // the cases left after binning are 10, 11, 12, 13, 76 { case 10: // super sad, let's make it shades of red, and blink a lot case 11: // sad, but not that sad moveMouth(5); while (checkNext()) { lcd.setRGB(255, 0, 0); // red openeye(6); playTTCSound(); //delay(300); lcd.setRGB(255, 50, 100); // less red closedeye(6); delay(100); } break; case 12: // slightly happy case 13: // super happy moveMouth(15); while (checkNext()) { lcd.setRGB(255, 255, 0); // bright green/yellow openeye(6); playHappySound(); //delay(700); lcd.setRGB(173, 255, 57); // dimmer version of same? closedeye(6); delay(100); } break; case 76: // for 1776, american AF dog, go red/white/blue //moveMouth(15); fakemode = 1; // time our way out of this one, rather than wait for next signal while (checkNext()) { openeye(6); lcd.setRGB(255, 0, 0); // red delay(150); moveMouth(10); lcd.setRGB(255, 255, 255); // white delay(150); moveMouth(15); lcd.setRGB(0, 0, 255); // blue delay(150); moveMouth(12); } playOhCanada(); fakemode = 0; break; default: // neutral expression mode moveMouth(10); while (checkNext()) { lcd.setRGB(255, 255, 255); // bright green/yellow openeye(6); delay(700); lcd.setRGB(128, 128, 128); // dimmer version of same? closedeye(6); delay(100); } break; } delay(10); // just in case, prevent fast looping } boolean checkNext() { if (fakemode == 1) { // fake timer: count++; if (count > 5) { count = 0; return 0; } else return 1; } else return !Serial.available(); } void openeye(int pos) { // then RESET the open eye stuff lcd.createChar(0, upperLeftCurve); lcd.createChar(1, upperRightCurve); lcd.createChar(2, lowerLeftCurve); lcd.createChar(3, lowerRightCurve); lcd.createChar(4, upperLine); // top lcd.setCursor(pos+0,0); lcd.write((unsigned char)0); lcd.write(4); lcd.write(6); lcd.write(4); lcd.write(1); // bottom lcd.setCursor(pos+0,1); lcd.write(2); lcd.write(5); lcd.write(7); lcd.write(5); lcd.write(3); } void closedeye(int pos) { // must redefine the character map /* lcd.createChar(0, upperLeftCurve_blink); lcd.createChar(1, upperRightCurve_blink); lcd.createChar(2, lowerLeftCurve_blink); lcd.createChar(3, lowerRightCurve_blink); lcd.createChar(4, solid); */ // top lcd.setCursor(pos+0,0); lcd.write((unsigned char)0); lcd.write(" "); lcd.write(" "); lcd.write(" "); lcd.write(1); // bottom lcd.setCursor(pos+0,1); lcd.write(2); lcd.write(4); lcd.write(4); lcd.write(4); lcd.write(3); } void moveMouth(int rating) { // HORRIBLE HACK: detach and reattach here, because the // tone() function elsewhere has messed with the servo timers // this resets them, so servos work again, and we just do // it every damn time, just to be sure. myservo1.detach(); myservo2.detach(); myservo1.attach(3); myservo2.attach(11); // clamp to 5 -> 15 range if (rating > 15) { rating = 15; } else if (rating < 5) { rating = 5; } Serial.println(rating); // convert rating to angle between 45 and 135 int angle1 = ((rating - 5) * 9) + 45; // figure out which way to move servos int dir = 0; if (angle1 > pos) { dir = 1; } else { dir = -1; } // move servo to position for (; pos != angle1; pos += dir) { myservo1.write(pos); myservo2.write(-1 * pos + 180); delay(15); // MAYBE REMOVE THIS Serial.println(pos); } } void playOhCanada() { for (int thisNote = 0; thisNote < 11; thisNote++) { // to calculate the note duration, take one second divided by the note type. //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc. int noteDuration = 1000 / ohCandaDurations[thisNote]; tone(6, ohCanada[thisNote], noteDuration); // to distinguish the notes, set a minimum time between them. // the note's duration + 30% seems to work well: int pauseBetweenNotes = noteDuration * 1.30; delay(pauseBetweenNotes); // stop the tone playing: noTone(6); } } void playHappySound() { for (int thisNote = 0; thisNote < 4; thisNote++) { int noteDuration = 1000 / happyDurations[thisNote]; tone(6, happy[thisNote], noteDuration); int pauseBetweenNotes = noteDuration * 1.30; delay(pauseBetweenNotes); noTone(6); } } void playSadSound() { for (int thisNote = 0; thisNote < 4; thisNote++) { int noteDuration = 1000 / sadDurations[thisNote]; tone(6, sad[thisNote], noteDuration); int pauseBetweenNotes = noteDuration * 1.30; delay(pauseBetweenNotes); noTone(6); } } void playTTCSound() { for (int thisNote = 0; thisNote < 3; thisNote++) { int noteDuration = 1000 / ttcDurations[thisNote]; tone(6, ttc[thisNote], noteDuration); int pauseBetweenNotes = noteDuration * 1.30; delay(pauseBetweenNotes); noTone(6); } } /********************************************************************************************************* END FILE *********************************************************************************************************/
8298dd4a6c0680bb206011e42476e2e875bca37a
66174e1e43829763e01c5cee6757a63b250404a4
/include/cuda/exception.hpp
6a18880e9573e0ce06c4bce4bb5ed9dd14c70d92
[]
no_license
andrejlevkovitch/cuda-mat
492555eb417249ee4aa704a60bc2714b1af9d6b7
828f95cf11b2a0dcb5fc09313aeeaa4d9a6c5a0f
refs/heads/master
2023-03-09T00:12:14.353983
2021-02-03T11:56:00
2021-02-03T11:56:55
341,147,882
1
0
null
null
null
null
UTF-8
C++
false
false
347
hpp
exception.hpp
// exception.hpp #pragma once #include <string> namespace cuda { /**\brief cuda exception */ class exception : public std::exception { public: exception(std::string what) : what_{std::move(what)} { } const char *what() const noexcept override { return what_.c_str(); } private: std::string what_; }; } // namespace cuda
00af85d2c732b5c9bfc972dbbb0acb5df071c75d
03a1bb4154a50eef70cb48ec36601f0293739a45
/ircd/stats.cc
1e55765f7a2b009c6dfbc717e2f87ab9a0243352
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
bqv/charybdis
3631c3e38c083d9d3d16be8b38fb09f659ddfa07
95a0073101f03c22226c504d6fd21c18965ffd78
refs/heads/master
2021-05-26T10:32:29.044336
2020-05-13T19:30:03
2020-05-13T19:30:03
254,097,200
0
0
NOASSERTION
2020-04-08T13:34:25
2020-04-08T13:34:24
null
UTF-8
C++
false
false
1,344
cc
stats.cc
// Matrix Construct // // Copyright (C) Matrix Construct Developers, Authors & Contributors // Copyright (C) 2016-2019 Jason Volk <jason@zemos.net> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice is present in all copies. The // full license for this software is available in the LICENSE file. decltype(ircd::stats::items) ircd::stats::items {}; std::ostream & ircd::stats::operator<<(std::ostream &s, const item &item) { s << static_cast<long long>(item.val); return s; } // // item // decltype(ircd::stats::item::NAME_MAX_LEN) ircd::stats::item::NAME_MAX_LEN { 127 }; // // item::item // ircd::stats::item::item(const json::members &opts) :feature_ { opts } ,feature { feature_ } ,name { unquote(feature.at("name")) } ,val { feature.get<long>("default", 0L) } { if(name.size() > NAME_MAX_LEN) throw error { "Stats item '%s' name length:%zu exceeds max:%zu", name, name.size(), NAME_MAX_LEN }; if(!items.emplace(name, this).second) throw error { "Stats item named '%s' already exists", name }; } ircd::stats::item::~item() noexcept { if(name) { const auto it{items.find(name)}; assert(data(it->first) == data(name)); items.erase(it); } }
ce3b2663ec3fcdb0ae10845b8ab3aebb3cf9236f
b9dd98d301aa2055616f21fd1026a5e4ff9e81fb
/UVA/12160 - Unlock the Lock.cpp
d64a3ea1e7d45b9a739e52718a1686867caa3120
[]
no_license
AlaaAbuHantash/Competitive-Programming
f587fcbbe9da33114c6bed3eb76f5cf0429fbf95
179a8473662d04b8c5c129e852f6eab075e80fb2
refs/heads/master
2021-07-25T08:17:49.841307
2018-08-06T10:06:54
2018-08-06T10:06:54
128,920,319
2
1
null
null
null
null
UTF-8
C++
false
false
1,257
cpp
12160 - Unlock the Lock.cpp
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <vector> #include <algorithm> #include <queue> #include <map> #include <set> #include <utility> #include <stack> #include <cstring> #include <math.h> #include<cstdio> #include<deque> #include<sstream> using namespace std; int dx[] = { 0, 0, 1, -1, 1, 1, -1, -1 }; int dy[] = { 1, -1, 0, 0, 1, -1, 1, -1 }; #define mp make_pair int vis[1000000],a,b,k,x; int main() { int t= 1; //freopen("test.txt", "rt", stdin); //freopen("output.txt", "w", stdout); while (scanf("%d%d%d", &a, &b, &k) > 0){ if (a + b + k == 0) return 0; memset(vis, 0, sizeof(vis)); vector<int > v; for (int i = 0; i < k; i++){ scanf("%d", &x); v.push_back(x % 10000); } queue<int > q; q.push(a); vis[a] = 1; int res = 0,f=0; while (!q.empty()){ int siz = q.size(); while (siz--){ int fr = q.front(); q.pop(); if (fr == b){ f = 1; break; } vis[fr] = 1; for (int i = 0; i < k; i++){ x = (fr + v[i])%10000; if (!vis[x]) q.push(x); vis[x] = 1; } } if (f)break; res++; } if (f) printf("Case %d: %d\n", t++, res); else printf("Case %d: Permanently Locked\n",t++); } return 0; }
aa55584cbe13b30f88fd42836abf944b078b2c31
0d4fed4715efeba61ecba6df97feaef345a8b97b
/src/configs.hh
d00bc92eb96324586858a3a9694f7f67cef2ceef
[]
no_license
pidgy/robot-walk
9a802aa9b50e39f6d64ac7235f4e73a446e8f08b
8f4b1768b805237a0a587bf72c049232564baa0b
refs/heads/master
2021-09-10T14:16:47.446125
2018-03-27T18:39:57
2018-03-27T18:39:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
317
hh
configs.hh
#define SEED 1 #define LEFT 0 #define RIGHT 1 #define ROBOT_SPEED 1 #define ROBOT_COUNT 12 #define POINT_COUNT 1000 #define UI_SPEED 10 #define UI_ENABLED 1 #define LOG_ENABLED 0 #define UI_CHECK if (!UI_ENABLED) return #define LOG_CHECK if (!LOG_ENABLED) return #define DRAW_ASCII 0 #define DRAW_OPENGL !DRAW_ASCII
203f54b1922b00f7c5cbe17ffac174cfc45d5a41
872080ee3747ea92c31fcb193c6a6e7d0f493057
/main.cpp
521778363e95d6989176c7df66231a21004bb620
[]
no_license
kevcalderon/MIA_Proyecto1
596615b48c639cf40daf84add5fedcc38e004228
dc503635a80aec225f8e42997657b6fe4babec1b
refs/heads/master
2023-07-17T03:50:22.194436
2021-08-30T07:15:48
2021-08-30T07:15:48
397,290,249
0
0
null
null
null
null
UTF-8
C++
false
false
787
cpp
main.cpp
//va buscarlo en compilador <> y el "" lo busca en la carpeta del proyecto. #include <iostream> #include "encabezados/Comandos.h" using namespace std; int main(int argc, char *argv[]){ // Comandos comands; // comands.menu(); //argc : obtener el numero de argumento totales pasados en la en la linea de comandos. //argv : es un array con los argumentos pasados en la linea de comandos. // cout << "Numero de argumentos pasados: " << argc <<endl; // cout << "Lista de argumentos: " <<endl; string static lista = ""; for (int i=1; i<argc; i++){ lista += argv[i]; lista += " "; } // lista es para analizador. // cout << "lista: " << lista << endl; Comandos comands; comands.comandosTerminal(lista); return 0; }
d92d905f8037a569fe69cb6b74d0fc716ffa59fb
a6f4ebf8b2125d11dcb5e6c31ee71563b580c776
/17.4/17.4.cpp
69640f6a64bddcd97e8acf95b086abde4b7209fd
[]
no_license
redemption2end/crackcodinginterview
f4b21f53713d0ba2fbd0edfb194a0c7424591ba9
44c88b0f40de3503fd2af0ff509170b2f0360e7b
refs/heads/master
2021-01-01T19:30:47.349004
2014-07-06T03:51:04
2014-07-06T03:51:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
331
cpp
17.4.cpp
// 17.4.cpp : Defines the entry point for the console application. // #include "stdafx.h" int mymax(int a, int b) { int c = (a - b) >> 31; return a + c * (a - b); } int _tmain(int argc, _TCHAR* argv[]) { printf("max(%d, %d): %d\n", 3, 4, mymax(3, 4)); printf("max(%d, %d): %d\n", -5, 10000, mymax(-5, 10000)); return 0; }
4f6d2e9d04579d65dd540ab0983262b7c42f7940
4816d3f24aae64360b614ceefaf8760323aa2d6c
/src/cpp/include/test_motor_pos_control.h
f5df500bb991c348e37aa8ea5cd0d3a9d956a2f6
[]
no_license
JiminHanKHU/ocs_test_dcs
7a7c084d312e80c1eb1dfe1898b53efc99042144
1fa65fbc23634b18cb4d75f579759e879ad81686
refs/heads/master
2020-06-22T07:33:00.096541
2019-07-19T00:05:10
2019-07-19T00:05:10
197,672,333
0
0
null
null
null
null
UTF-8
C++
false
false
709
h
test_motor_pos_control.h
#ifndef _test_motor_pos_control_h_ #define _test_motor_pos_control_h_ #include <msgpack.hpp> #include <string> #include <array> #include <vector> struct test_motor_pos_control { int16_t velocity; // Velocity bool execute; // Execute uint32_t target_position; // Target_position uint16_t acceleration; // Acceleration uint16_t deceleration; // Deceleration uint16_t start_type; // Start Type MSGPACK_DEFINE_MAP(velocity, execute, target_position, acceleration, deceleration, start_type) }; #endif // _test_motor_pos_control_h_
c21764a8508a15e4d9928772dd5a8c718592bfd2
b94b24b31f1b87cdad8abb64e9ee9f3ebe325090
/renderer.cpp
056c8dfb96a37b65685935942c3e306e23f77fad
[]
no_license
ds1hvh/RawImageProcessing
66d834d43bbaf779c01a0768b604de6601fcfe43
ebb11a737fdc9fba8563fa65c431f342031843c3
refs/heads/master
2021-09-14T23:40:58.636398
2018-05-22T12:52:31
2018-05-22T12:52:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,313
cpp
renderer.cpp
#include <GL/GL.h> typedef struct { s8* data; s32 length; } string; #define MAKE_STRING(X) {X, sizeof(X) - 1} u32 shader_load(string vert_src, string frag_src) { GLuint vs_id = glCreateShader(GL_VERTEX_SHADER); GLuint fs_id = glCreateShader(GL_FRAGMENT_SHADER); GLint compile_status; const GLchar* p_v[1] = { vert_src.data }; glShaderSource(vs_id, 1, p_v, &vert_src.length); const GLchar* p_f[1] = { frag_src.data }; glShaderSource(fs_id, 1, p_f, &frag_src.length); glCompileShader(vs_id); glGetShaderiv(vs_id, GL_COMPILE_STATUS, &compile_status); if (!compile_status) { char error_buffer[512] = { 0 }; glGetShaderInfoLog(vs_id, sizeof(error_buffer), NULL, error_buffer); printf("%s", error_buffer); return -1; } glCompileShader(fs_id); glGetShaderiv(fs_id, GL_COMPILE_STATUS, &compile_status); if (!compile_status) { char error_buffer[512] = { 0 }; glGetShaderInfoLog(fs_id, sizeof(error_buffer) - 1, NULL, error_buffer); printf("%s", error_buffer); return -1; } GLuint shader_id = glCreateProgram(); glAttachShader(shader_id, vs_id); glAttachShader(shader_id, fs_id); glDeleteShader(vs_id); glDeleteShader(fs_id); glLinkProgram(shader_id); glGetProgramiv(shader_id, GL_LINK_STATUS, &compile_status); if (compile_status == 0) { GLchar error_buffer[512] = { 0 }; glGetProgramInfoLog(shader_id, sizeof(error_buffer) - 1, NULL, error_buffer); printf("%s", error_buffer); return -1; } glValidateProgram(shader_id); return shader_id; } u32 vbo, vao, ebo; typedef struct { hm::vec3 position; hm::vec2 texcoord; hm::vec4 color; } Vertex3D; typedef struct { r32 left; r32 right; r32 top; r32 bottom; } RectBase; u32 immediate_quad_shader; string immquad_vshader = MAKE_STRING(R"( #version 330 core layout(location = 0) in vec3 vertex; layout(location = 1) in vec2 tcoords; layout(location = 2) in vec4 v_color; out vec2 texcoords; out vec4 out_color; uniform mat4 projection = mat4(1.0); uniform mat4 model = mat4(1.0); void main(){ gl_Position = projection * model * vec4(vertex.xy, 0.0, 1.0); texcoords = tcoords; out_color = v_color; } )"); string immquad_fshader = MAKE_STRING(R"( #version 330 core in vec2 texcoords; in vec4 out_color; out vec4 color; uniform sampler2D u_texture; void main(){ vec4 c = texture(u_texture, texcoords); color = c; } )"); void init_immediate_quad_mode() { immediate_quad_shader = shader_load(immquad_vshader, immquad_fshader); glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glGenBuffers(1, &ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); const int num_vertices = 4; const int num_attribs = 9; u16 indices[] = { 0, 1, 2, 2, 3, 0 }; float s = 100.5f; Vertex3D data[4] = { { hm::vec3(-s,-s, 0), hm::vec2(0, 0), hm::vec4(1, 0, 0, 1) }, { hm::vec3(s, -s, 0), hm::vec2(1, 0), hm::vec4(0, 1, 0, 1) }, { hm::vec3(s, s, 0), hm::vec2(0, 1), hm::vec4(0, 0, 1, 1) }, { hm::vec3(-s, s, 0), hm::vec2(1, 1), hm::vec4(1, 1, 0, 1) } }; glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_DYNAMIC_DRAW); glBufferData(GL_ARRAY_BUFFER, num_vertices * sizeof(Vertex3D), data, GL_DYNAMIC_DRAW); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex3D), (void*)&((Vertex3D*)0)->position); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex3D), (void*)&((Vertex3D*)0)->texcoord); glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex3D), (void*)&((Vertex3D*)0)->color); glDisableVertexAttribArray(2); glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); } static hm::mat4 imm_quad_model; void immediate_quad(u32 texture_id, r32 l, r32 r, r32 t, r32 b, hm::vec4 color, hm::vec2 pos, s32 window_width, s32 window_height) { Vertex3D data[4] = { { hm::vec3(l, b, 0), hm::vec2(0, 1), color }, { hm::vec3(r, b, 0), hm::vec2(1, 1), color }, { hm::vec3(r, t, 0), hm::vec2(1, 0), color }, { hm::vec3(l, t, 0), hm::vec2(0, 0), color } }; glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo); void* buffer_dst = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); if (!buffer_dst) return; memcpy(buffer_dst, data, sizeof(data)); imm_quad_model = hm::mat4::translate(pos.x, pos.y, 0.0f); glUnmapBuffer(GL_ARRAY_BUFFER); glUseProgram(immediate_quad_shader); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBindVertexArray(vao); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture_id); glUniformMatrix4fv(glGetUniformLocation(immediate_quad_shader, "model"), 1, GL_TRUE, imm_quad_model.data); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); hm::mat4 projection = hm::mat4::ortho(0, window_width / 1, 0, window_height / 1); GLuint loc = glGetUniformLocation(immediate_quad_shader, "projection"); glUniformMatrix4fv(loc, 1, GL_TRUE, projection.data); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0); glDisableVertexAttribArray(2); glDisableVertexAttribArray(1); glDisableVertexAttribArray(0); } u32 create_texture(s32 w, s32 h, void* data) { u32 texture_id; glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); //glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, w, h, 0, GL_RGBA, GL_FLOAT, data); 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_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); return texture_id; } u32 create_texture_hdr(s32 w, s32 h, void* data) { u32 texture_id; glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); glTexImage2D(GL_TEXTURE_2D, 0, GL_SRGB8_ALPHA8, w, h, 0, GL_RGBA, GL_FLOAT, data); 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_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); return texture_id; }
2b48e9cd6df30b230e456052a4ba1da72bd99934
426ddaa62ab302c395c0d6d04bdf98961de3ba1a
/src/main.cpp
8565c95f65204948b4c8b816ad9b60bafdb24ea1
[ "MIT" ]
permissive
GkvJeep/wifi-terminal
8b4e48d2065dde19e640d7f650809219d9eeaeb9
c3634731ea990432bb3a8d3785aa0b878b70849c
refs/heads/master
2023-07-24T01:36:26.741773
2021-09-06T13:24:05
2021-09-06T13:24:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
174
cpp
main.cpp
void serialEvent(); #include "application.hpp" Application *app; void setup() { app = new Application(); app->initialize(); } void loop() { app->mainloop(); }
ccc118353ce87045568fb79c9cd2e0eaacdcb2cf
d1eed325057b6de675375ea165f5d06250d52c6f
/unused/function_table.cc
1cb44f840045922a1837e25bfa64e70dee633fbd
[]
no_license
guicho271828/cpp-template
f3a9041347b5c74b8307140594e7fee4cbd76d90
2041be6bcff42aae9f6cc5d3e9cdf4ce5a3ad46d
refs/heads/master
2021-01-22T07:58:16.652378
2017-05-27T10:16:56
2017-05-27T10:23:53
92,591,570
0
0
null
null
null
null
UTF-8
C++
false
false
194
cc
function_table.cc
#include <functional> // void show_list(deque<string>); unordered_map<string, function<void(deque<string>)> > function_table = { // {"normal", &show_list}, // {"list", &show_list}, };
a8e175db18aec195d9cb10eeb69e9c83a3010bce
17da5dea2705c25b6e6677dd39478b49a9554395
/TDDD38_Advanced_Programming_in_C++/container_design/step2/Container.h
af0aedab4729ae23c84ac7b1553ec7807c980a0f
[]
no_license
thelloin/liu_courses
6ec33e3538d99716151a58446442bd16b608475f
4ca3eb161782e154d09f2adaa2cabfc6f41ac56e
refs/heads/master
2020-09-17T05:17:14.483650
2017-01-27T14:21:40
2017-01-27T14:21:40
67,583,847
0
0
null
null
null
null
UTF-8
C++
false
false
913
h
Container.h
/* * Container.h */ #ifndef CONTAINER_H #define CONTAINER_H #include <cstdlib> template <typename T> class Container { public: using size_type = std::size_t; Container() noexcept = default; explicit Container(const size_type n); Container(const Container&); // n Container(Container&&) noexcept; // n ~Container(); Container& operator=(const Container&) &; // n Container& operator=(Container&&) & noexcept; // n size_type size() const noexcept; size_type max_size() const noexcept; size_type capacity() const noexcept; bool empty() const noexcept; private: T* start_{ nullptr }; T* finish_{ nullptr }; T* end_of_storage_{ nullptr }; T* allocate_(size_type); void deallocate_(T*); T* allocate_and_copy_(const Container&); // n }; #include "Container.tcc" #endif /* CONTAINER_H */
7506694a30a4a4558977feebad803e90c8ea25ff
d0e5e7b02e7ad78280d82962c59ea3fd6b33445d
/Src/UI/WTL/CGraphVizProcessor.h
617ccc4f62e0f6f963f8131ce302991fa992c8f2
[ "BSD-3-Clause" ]
permissive
Stolas/DarunGrim
cb83ed32f6fbcce4acce8130a75a77efad719a7d
3842a5822b6e7cde29d3faae649bc32e8636247a
refs/heads/master
2020-12-24T12:34:00.050655
2014-05-05T19:10:20
2014-05-05T19:10:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,137
h
CGraphVizProcessor.h
#pragma once #include <types.h> #include <graph.h> #include <windows.h> #include <stdio.h> #ifndef dprintf #include "dprintf.h" #endif #include <hash_map> #include <list> using namespace std; using namespace stdext; #include "DrawingInfo.h" //#include "MapPipe.h" class CGraphVizProcessor { private: Agraph_t *g; GVC_t *gvc; stdext::hash_map<DWORD,Agnode_t *> AddressToNodeMap; stdext::hash_map<Agnode_t *,DWORD> *NodeToUserDataMap; list <DrawingInfo *> *ParseXDOTAttributeString(char *buffer); void DumpNodeInfo(Agnode_t *n); void DumpEdgeInfo(Agedge_t *e); char *GetGraphAttribute(Agraph_t *g,char *attr); char *GetNodeAttribute(Agnode_t *n, char *attr); char *GetEdgeAttribute(Agedge_t *e, char *attr); void GetDrawingInfo(DWORD address,list<DrawingInfo *> *p_drawing_info_map,BYTE type,char *str); public: CGraphVizProcessor(); ~CGraphVizProcessor(); void SetNodeData(DWORD NodeID,LPCSTR NodeName,LPCSTR NodeData,char *FontColor=NULL,char *FillColor=NULL,char *FontSize="18"); void SetMapData(DWORD src,DWORD dst); int RenderToFile(char *format,char *filename); list<DrawingInfo *> *GenerateDrawingInfo(); };
2acc2e319b591a1c44ab98a8bf40ab9ddcbef63f
6c9e8f72cb76ed2e28d74fb0b6cb419321f88bfb
/benchmarks/cpp/common.cpp
adc07cd1ee6717319cda4dd8fa695e58dd0a0afa
[ "Apache-2.0" ]
permissive
mlhackergz/torch-quiver
10a4a12ae362f5c49dc0070895c297d6335558c4
9734547288ec1550086336c759e5d58bb12d0148
refs/heads/main
2023-09-04T22:37:45.422668
2021-10-31T10:58:22
2021-10-31T10:58:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
589
cpp
common.cpp
#include "common.hpp" #include <algorithm> #include <random> graph gen_random_graph(int n, int m) { graph g(n); for (int i = 0; i < m; ++i) { constexpr int max_trials = 10; for (int j = 0; j < max_trials; ++j) { int x = rand() % n; int y = rand() % n; if (g.add_edge(x, y, i + 1)) { break; } } } return g; } void std_sample_i64(const int64_t *in, size_t total, int64_t *out, size_t count) { static std::random_device rd; static std::mt19937 rg(rd()); std::sample(in, in + total, out, count, rg); }
3b83cac352ab4cce55684c2d29754ca4371dd139
4a193c0992276fc133bc6e1d737f9fc30a71bef4
/Game/Kayak/Plugins/Trigger/Source/TriggerRunTime/Private/Tool/ReplicateType/Replicate_Yes.cpp
3ac729b162f072c47aaa4b5b419a58f2d854a932
[]
no_license
liulianyou/KayakGame
ff13ac212f311fe388d071151048aad99634054c
54264f06e23759c68013df92cbef0e77870c37d8
refs/heads/master
2022-03-16T16:05:20.782725
2022-02-14T11:01:37
2022-02-14T11:01:37
136,556,867
1
1
null
null
null
null
UTF-8
C++
false
false
223
cpp
Replicate_Yes.cpp
#include "ReplicateType/Replicate_Yes.h" UReplicate_Yes::UReplicate_Yes(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } bool UReplicate_Yes::CanReplicate_Implementation() { return true; }
c261f9f178b47f8b9f3d42b1a6fbb53262219414
b1c0001220eb34788c83df483294352a02bbb500
/modules/testmodule/TestModule.cpp
15692bad802353a53299136af17839e081d3da38
[]
no_license
surma-dump/clustonen
c746a25198c0d2f7a85d7308b8acbff02b92fa00
c9f3864f5c9247c48a6653879a476a5acb881140
refs/heads/master
2021-01-10T19:32:45.554600
2007-06-25T20:46:17
2007-06-25T20:46:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
356
cpp
TestModule.cpp
#include "TestModule.h" /** * Standard Constructor */ TestModule::TestModule() { } /** * Destructor */ TestModule::~TestModule() { } const char* TestModule::getName() { return "TestModule" ; } int TestModule::getHookPosition() { return MODULE_LOADING_REQUEST ; } int TestModule::processEvent (ClustonenEvent& event) { return CHAIN_PROCEED ; }
eacde70a3f036b528d7e631bce61e9d99fe91ddb
57be5745efbbbe3d64d8b66e15c203cf7a1534e5
/directx_3D_game/Number.cpp
661369fb1249d24188987f0b22d8a739d4e7e35b
[]
no_license
kamioyokiko/3D-game
b5379605f80a3ee03fc06c0d766871f755c8dedf
23095924417812fc4d852f29519cf502f5b31142
refs/heads/master
2020-12-01T10:19:56.188852
2017-03-26T13:19:21
2017-03-26T13:19:21
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
3,946
cpp
Number.cpp
//============================================================================= // // ナンバー処理 [Number.cpp] // Author : 稲澤俊和 // //============================================================================= #include "Number.h" #include "Renderer.h" #include "Scene.h" //============================================================================= // グローバル変数 //============================================================================= //CRenderer* CNumber::m_pNumber=NULL; //============================================================================= // コンストラクタ //============================================================================= CNumber::CNumber() { m_pDevice=NULL; m_pD3DNumberVtxBuff=NULL; m_pD3DNumber=NULL; m_pNumber=NULL; } //============================================================================= // デストラクタ //============================================================================= CNumber::~CNumber(void) { } //============================================================================= // スコアの初期化 //============================================================================= HRESULT CNumber::Init(CRenderer *pRenderer) { int i; m_pDevice = pRenderer->GetDevice(); // デバイスへのポインタ m_pDevice->SetRenderState(D3DRS_CULLMODE,D3DCULL_CCW); m_pDevice->SetRenderState(D3DRS_ZENABLE,TRUE); m_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE,TRUE); m_pDevice->SetRenderState(D3DRS_SRCBLEND,D3DBLEND_SRCALPHA); m_pDevice->SetRenderState(D3DRS_DESTBLEND,D3DBLEND_INVSRCALPHA); //頂点バッファ確保 if(FAILED(m_pDevice->CreateVertexBuffer(sizeof(VERTEX_2D)*4,D3DUSAGE_WRITEONLY,FVF_VERTEX_2D,D3DPOOL_MANAGED,&m_pD3DNumberVtxBuff,NULL))) { return E_FAIL; } VERTEX_2D *pVtx; //ロック m_pD3DNumberVtxBuff -> Lock(0,0,(void**)&pVtx,0); //座標 pVtx[0].vtx = D3DXVECTOR3(m_Pos.x,m_Pos.y,0.0f); pVtx[1].vtx = D3DXVECTOR3(m_Pos.x+20,m_Pos.y,0.0f); pVtx[2].vtx = D3DXVECTOR3(m_Pos.x,m_Pos.y+50,0.0f); pVtx[3].vtx = D3DXVECTOR3(m_Pos.x+20,m_Pos.y+50,0.0f); for(i=0;i<4;i++) { pVtx[i].rhw=1.0f; //透明度 pVtx[i].diffuse = D3DCOLOR_RGBA(255,255,255,255); } //テクスチャ座標 pVtx[0].tex=D3DXVECTOR2(0,0); pVtx[1].tex=D3DXVECTOR2(0.1f,0); pVtx[2].tex=D3DXVECTOR2(0,1); pVtx[3].tex=D3DXVECTOR2(0.1f,1); //テクスチャの読み込み D3DXCreateTextureFromFile(m_pDevice,"data/TEXTURE/number000.png",&m_pD3DNumber); //アンロック m_pD3DNumberVtxBuff->Unlock(); return S_OK; } //============================================================================= // スコアの終了処理 //============================================================================= void CNumber::Uninit(void) { if(m_pD3DNumber != NULL) { m_pD3DNumber ->Release(); m_pD3DNumber = NULL; } if(m_pD3DNumberVtxBuff !=NULL) { m_pD3DNumberVtxBuff ->Release(); m_pD3DNumberVtxBuff = NULL; } } //============================================================================= // スコアの更新処理 //============================================================================= void CNumber::UpdateNumber(int nNumber) { VERTEX_2D *pVtx; m_pD3DNumberVtxBuff -> Lock(0,0,(void**)&pVtx,0); pVtx[0].tex=D3DXVECTOR2(0+(nNumber*0.1f),0); pVtx[1].tex=D3DXVECTOR2(0.1f+(nNumber*0.1f),0); pVtx[2].tex=D3DXVECTOR2(0+(nNumber*0.1f),1); pVtx[3].tex=D3DXVECTOR2(0.1f+(nNumber*0.1f),1); m_pD3DNumberVtxBuff->Unlock(); } void CNumber::Update(void) { } //============================================================================= // スコアの描画処理 //============================================================================= void CNumber::Draw(void) { m_pDevice->SetStreamSource(0,m_pD3DNumberVtxBuff,0,sizeof(VERTEX_2D)); m_pDevice->SetTexture(0,m_pD3DNumber); m_pDevice->SetFVF(FVF_VERTEX_2D); m_pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP,0,2); }
8cd5473a16d85de6003f73d29b4e6eb79b4db2e8
b895d6679795bf49d8b0de6303b4eabe6a320d40
/Code/CPP/Pascals Triangle.cpp
c058988096296021b710458ec2ba938da762a3b6
[]
no_license
Amanuttam1192/HacktoberFest21
e1d7d0a4cf0ccd404642f4cc5ac24adaac293eb2
d81941bbbfbb18afe97a72f53b1efbba074fbbae
refs/heads/main
2023-08-01T10:26:47.438178
2021-10-04T14:27:34
2021-10-04T14:27:34
413,451,287
3
0
null
2021-10-04T14:13:50
2021-10-04T14:13:49
null
UTF-8
C++
false
false
806
cpp
Pascals Triangle.cpp
/*Given an integer numRows, return the first numRows of Pascal's triangle.*/ #include<bits/stdc++.h> using namespace std; vector<vector<int>> generate(int numRows) { vector<vector<int>>ans(numRows); ans[0].resize(1); ans[0][0]=1; if(numRows==0) return ans; for(int i=1;i<numRows;i++){ ans[i].resize(i+1); ans[i][0]=1; ans[i][i]=1; for(int j=1;j<i;j++){ ans[i][j]=ans[i-1][j-1]+ans[i-1][j]; } } return ans; } int main(){ int rows; cin>>rows; vector<vector<int>>ans=generate(rows); for(int i=0;i<ans.size();i++){ for(int j=0;j<ans[i].size();j++) cout<<ans[i][j]<<" "; cout<<endl; } return 0; }
64a3559ad30a05ad25b96f5bfc6e05be8159927c
21101276fe8afc230a6b1169bb0f9d053be060e6
/Tetris/Block.h
de3fd769ec342c5670c8c530fc8b39f307093c37
[]
no_license
walnut00/Tetris
7c92bed46c6a145d8252707ecca2231cbd856038
bfd730a074e0a6d20c6d77fa52f54ebef18121b5
refs/heads/master
2021-05-23T16:52:00.160558
2020-04-06T10:01:21
2020-04-06T10:01:21
253,388,762
4
0
null
null
null
null
GB18030
C++
false
false
805
h
Block.h
#ifndef _SHAPE_H #define _SHAPE_H enum BLOCK_TYPE { TYPE_I, TYPE_L, TYPE_J, TYPE_T, TYPE_Z, TYPE_S, TYPE_O }; enum BLOCK_ANGLE { ANGLE_0, ANGLE_90, ANGLE_180, ANGLE_270 }; class CBlock { public: CBlock(unsigned short nGridSize, unsigned short nSpliterSize); ~CBlock(void); void Randomizer(void); //generate a shape randomly bool Draw(CDC * pDC, const CPoint & point); bool CalculateFourRect(BLOCK_TYPE nType, BLOCK_ANGLE nAngle, const CPoint & point, CRect * pRect) const;//calculate the 4 rectangle of the block public: BLOCK_TYPE m_nType; BLOCK_ANGLE m_nAngle; COLORREF m_nColor; unsigned short m_nGridSize; //最小像元正方形之边长 unsigned short m_nSpliterSize; //像元之间的分割线宽 CRect m_rectRect[4]; //store the 4 rectangle of the block shape }; #endif
5eb7147d61790dbf2d14dd274d522726cd7403b4
e5436626ee61d7363865132d85f9bfc8a1debb63
/LinkStack/lnkStack.h
dd32a5b0fbf630f38d8d73f3883a380552178d89
[]
no_license
congHu/LinkStack
f3396a7de2a98609240ba98bf97ad7965d02de08
947d5dd5d8fd8fa1f31cbb56ce638e995ad87efc
refs/heads/master
2021-01-10T13:13:56.680950
2016-04-08T11:52:03
2016-04-08T11:52:03
55,772,323
0
0
null
null
null
null
GB18030
C++
false
false
2,165
h
lnkStack.h
#include <cstdlib> #include <iostream> #include "myStack.h" using namespace std; template <class T> class Link { public: T data; // 用于保存结点元素的内容 Link *next; // 指向后继结点的指针 Link(const T info, Link* nextValue) { // 具有两个参数的Link构造函数 data = info; next = nextValue; } Link(Link* nextValue = NULL) { // 具有两个参数的Link构造函数 next = nextValue; } }; template <class T> class lnkStack : public Stack <T> { private: // 栈的链式存储 Link<T> *top; // 指向栈顶的指针 int size; // 存放元素的个数 public: // 栈运算的链式实现 lnkStack(); lnkStack(int defSize); // 构造函数 ~lnkStack(); // 析构函数 void clear(); // 清空栈内容 void push(const T item); // 入栈操作的链式实现 T pop(); // 出栈的链式实现 T getTop(); // 返回栈顶内容,但不弹出 bool isEmpty(); }; template <class T> lnkStack<T>::lnkStack(){ top = NULL; } template <class T> lnkStack<T>::lnkStack(int defSize){ size = defSize; top = NULL; } template <class T> lnkStack<T>::~lnkStack(){ clear(); } template <class T> void lnkStack<T>::clear(){ Link<T>* p = top; if (p) { Link<T>* d = p; delete d; } } template <class T> void lnkStack<T>::push(const T item){ Link<T>* n = new Link<T>(item, top); top = n; } template <class T> T lnkStack<T>::pop(){ if (top) { Link<T>* d = top; T x = d->data; top = top->next; delete d; return x; }else{ cout<<"Stack Underflow.\n"; return NULL; } } template <class T> T lnkStack<T>::getTop(){ if (top) { return top->data; }else{ cout<<"Empty Stack.\n"; return NULL; } } template <class T> bool lnkStack<T>::isEmpty(){ if (top) { return false; }else{ return true; } }
7ae3ba08a2f61a98bfb049e498726767c3bdf174
947994ed8b82882fde3c19904f0517e2a6778798
/MySketchpad-master/include/Tool/EraserTool.h
f60fc71711d142f57228ca8899b7c680d7070e8c
[]
no_license
Keneyr/SketchPad
c959924569794b310a44c9ffd2a5599354a05c4c
49e6860e47f940d0206b12202928b075863f6629
refs/heads/master
2022-12-11T23:15:16.770343
2020-09-17T02:23:51
2020-09-17T02:23:51
295,602,684
1
1
null
null
null
null
UTF-8
C++
false
false
320
h
EraserTool.h
#ifndef ERASERTOOL_H #define ERASERTOOL_H #include"include/Tool/Tool.h" class EraserTool:public Tool{ public: EraserTool(DrawingArea* d):Tool(d){} void mouseMoveEvent(QMouseEvent *event); void mousePressEvent(QMouseEvent *event); void mouseReleaseEvent(QMouseEvent *event); }; #endif // ERASERTOOL_H