blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
2fcad5cea04c54480c752d284686f15b233b00dc
021e8c48a44a56571c07dd9830d8bf86d68507cb
/build/vtk/vtkQtStatisticalBoxChartOptions.h
ea8d52a9564f328b3c7fe262269860112a7b2920
[ "BSD-3-Clause" ]
permissive
Electrofire/QdevelopVset
c67ae1b30b0115d5c2045e3ca82199394081b733
f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5
refs/heads/master
2021-01-18T10:44:01.451029
2011-05-01T23:52:15
2011-05-01T23:52:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,444
h
/*========================================================================= Program: Visualization Toolkit Module: vtkQtStatisticalBoxChartOptions.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm 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. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ /// \file vtkQtStatisticalBoxChartOptions.h /// \date May 15, 2008 #ifndef _vtkQtStatisticalBoxChartOptions_h #define _vtkQtStatisticalBoxChartOptions_h #include "vtkQtChartExport.h" #include <QObject> #include "vtkQtChartLayer.h" // needed for enum class vtkQtChartHelpFormatter; /// \class vtkQtStatisticalBoxChartOptions /// \brief /// The vtkQtStatisticalBoxChartOptions class stores the drawing options for a /// box chart. /// /// The default settings are as follows: /// \li axes: \c BottomLeft /// \li box width fraction: 0.8 /// \li outline style: \c Darker class VTKQTCHART_EXPORT vtkQtStatisticalBoxChartOptions : public QObject { Q_OBJECT public: enum OutlineStyle { Darker, ///< Draws the box outline in a darker color. Black ///< Draws a black box outline. }; public: /// \brief /// Creates a box chart options instance. /// \param parent The parent object. vtkQtStatisticalBoxChartOptions(QObject *parent=0); /// \brief /// Makes a copy of another box chart options instance. /// \param other The box chart options to copy. vtkQtStatisticalBoxChartOptions( const vtkQtStatisticalBoxChartOptions &other); virtual ~vtkQtStatisticalBoxChartOptions(); /// \brief /// Gets the pair of axes used by the box chart. /// \return /// The pair of axes used by the box chart. vtkQtChartLayer::AxesCorner getAxesCorner() const {return this->AxesCorner;} /// \brief /// Sets the pair of axes used by the box chart. /// \param axes The new chart axes. void setAxesCorner(vtkQtChartLayer::AxesCorner axes); /// \brief /// Gets the box width fraction. /// /// The box width fraction is used to set the spacing between the /// boxs of different series. /// /// \return /// The box width fraction. float getBoxWidthFraction() const {return this->BoxFraction;} /// \brief /// Sets the box width fraction. /// \param fraction The new box width fraction. void setBoxWidthFraction(float fraction); /// \brief /// Gets the outline style for the boxes. /// \return /// The current outline style. OutlineStyle getOutlineStyle() const {return this->OutlineType;} /// \brief /// Sets the outline style for the boxes. /// /// The default style is \c Darker. /// /// \param style The outline style to use. void setOutlineStyle(OutlineStyle style); /// \brief /// Gets the chart help text formatter. /// /// The help text formatter stores the format string. It is also /// used to generate the help text. /// /// \return /// A pointer to the chart help text formatter. vtkQtChartHelpFormatter *getHelpFormat() {return this->Help;} /// \brief /// Gets the chart help text formatter. /// \return /// A pointer to the chart help text formatter. const vtkQtChartHelpFormatter *getHelpFormat() const {return this->Help;} /// \brief /// Gets the outlier help text formatter. /// /// The help text formatter stores the format string. It is also /// used to generate the help text. /// /// \return /// A pointer to the outlier help text formatter. vtkQtChartHelpFormatter *getOutlierFormat() {return this->Outlier;} /// \brief /// Gets the outlier help text formatter. /// \return /// A pointer to the outlier help text formatter. const vtkQtChartHelpFormatter *getOutlierFormat() const {return this->Outlier;} /// \brief /// Makes a copy of another box chart options instance. /// \param other The box chart options to copy. /// \return /// A reference to the object being assigned. vtkQtStatisticalBoxChartOptions &operator=( const vtkQtStatisticalBoxChartOptions &other); signals: /// Emitted when the box chart axes change. void axesCornerChanged(); /// Emitted when the box width fraction changes. void boxFractionChanged(); /// Emitted when the outline style changes. void outlineStyleChanged(); private: vtkQtChartLayer::AxesCorner AxesCorner; ///< Stores the chart axes. OutlineStyle OutlineType; ///< Stores the outline style. vtkQtChartHelpFormatter *Help; ///< Stores the help text format. vtkQtChartHelpFormatter *Outlier; ///< Stores the outlier text format. float BoxFraction; ///< Stores the box width fraction. }; #endif
[ "ganondorf@ganondorf-VirtualBox.(none)" ]
ganondorf@ganondorf-VirtualBox.(none)
e94881026f3cd6e01265211a2634103b721dbb99
da7ccfd7debd939894fe460ca4c6c9466fe5d2a8
/components/resultPanel.cpp
28e6ee2b9a12af68e4954962b5a9a2b594a457cb
[]
no_license
bingshiue/TestProject
a0fef4bd81c80adf011530e33f4cd543e762f437
408539e309b1116d6f08a972b35fd6d0f1659dcc
refs/heads/master
2021-01-15T22:28:43.914710
2014-08-30T14:06:45
2014-08-30T14:06:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,348
cpp
/** * @file resultPanel.cpp * */ #include "../include/components/resultPanel.h" ResultPanel::ResultPanel(wxPanel* parent,wxString title) : wxPanel(parent,wxID_ANY,wxDefaultPosition,wxDefaultSize,wxBORDER_NONE) { this->m_parent = parent; this->m_sb = new wxStaticBox(this,wxID_ANY,title,wxDefaultPosition,wxDefaultSize); this->m_sz = new wxStaticBoxSizer(this->m_sb,wxVERTICAL); this->m_gridSz = new wxGridSizer(6,6,0,0); this->m_totalKeyIn = new wxStaticText(this,wxID_ANY,L"T-KeyIn Coin"); this->m_totalKeyOut = new wxStaticText(this,wxID_ANY,L"T-KeyOut Coin"); this->m_keyInOutPercent = new wxStaticText(this,wxID_ANY,L"T-KeyIn/Out %"); this->m_totalPlayScore = new wxStaticText(this,wxID_ANY,L"T-Play Scores"); this->m_totalWinScore = new wxStaticText(this,wxID_ANY,L"T-Win Scores"); this->m_PlayWinScorePercent = new wxStaticText(this,wxID_ANY,L"T-Play/Win Scores %"); this->m_totalPlayTimes = new wxStaticText(this,wxID_ANY,L"T-Play Times"); this->m_totalWinTimes = new wxStaticText(this,wxID_ANY,L"T-Win Times"); this->m_PlayWinTimesPercent = new wxStaticText(this,wxID_ANY,L"T-Play/Win Times %"); this->m_doubleTotalPlayScore = new wxStaticText(this,wxID_ANY,L"D-Play Scores"); this->m_doubleTotalWinScore = new wxStaticText(this,wxID_ANY,L"D-Win Scores"); this->m_doublePlayWinScorePercent = new wxStaticText(this,wxID_ANY,L"D-Play/Win Scores %"); this->m_doubleTotalPlayTimes = new wxStaticText(this,wxID_ANY,L"D-Play Times"); this->m_doubleTotalWinTimes = new wxStaticText(this,wxID_ANY,L"D-Win Times"); this->m_doublePlayWinTimesPercent = new wxStaticText(this,wxID_ANY,L"D-Play/Win Times %"); this->m_mainGameOverMaxWinTimes = new wxStaticText(this,wxID_ANY,L"M-OverWin Times"); this->m_doubleGameOverMaxWinTimes = new wxStaticText(this,wxID_ANY,L"D-OverWin Times"); this->m_doubleGameMaxConsecutivePassTimes = new wxStaticText(this,wxID_ANY,L"D-Max Continuous"); this->m_totalKeyIn_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_totalKeyOut_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_keyInOutPercent_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_totalPlayScore_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_totalWinScore_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_PlayWinScorePercent_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_totalPlayTimes_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_totalWinTimes_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_PlayWinTimesPercent_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_doubleTotalPlayScore_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_doubleTotalWinScore_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_doublePlayWinScorePercent_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_doubleTotalPlayTimes_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_doubleTotalWinTimes_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_doublePlayWinTimesPercent_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_mainGameOverMaxWinTimes_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_doubleGameOverMaxWinTimes_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_doubleGameMaxConsecutivePassTimes_tc = new wxTextCtrl(this,wxID_ANY,L""); this->m_totalKeyIn_tc->SetEditable(false); this->m_totalKeyOut_tc->SetEditable(false); this->m_keyInOutPercent_tc->SetEditable(false); this->m_totalPlayScore_tc->SetEditable(false); this->m_totalWinScore_tc->SetEditable(false); this->m_PlayWinScorePercent_tc->SetEditable(false); this->m_totalPlayTimes_tc->SetEditable(false); this->m_totalWinTimes_tc->SetEditable(false); this->m_PlayWinTimesPercent_tc->SetEditable(false); this->m_doubleTotalPlayScore_tc->SetEditable(false); this->m_doubleTotalWinScore_tc->SetEditable(false); this->m_doublePlayWinScorePercent_tc->SetEditable(false); this->m_doubleTotalPlayTimes_tc->SetEditable(false); this->m_doubleTotalWinTimes_tc->SetEditable(false); this->m_doublePlayWinTimesPercent_tc->SetEditable(false); this->m_mainGameOverMaxWinTimes_tc->SetEditable(false); this->m_doubleGameOverMaxWinTimes_tc->SetEditable(false); this->m_doubleGameMaxConsecutivePassTimes_tc->SetEditable(false); this->m_totalKeyIn_tc->SetValue("0"); this->m_totalKeyOut_tc->SetValue("0"); this->m_keyInOutPercent_tc->SetValue("0"); this->m_totalPlayScore_tc->SetValue("0"); this->m_totalWinScore_tc->SetValue("0"); this->m_PlayWinScorePercent_tc->SetValue("0"); this->m_totalPlayTimes_tc->SetValue("0"); this->m_totalWinTimes_tc->SetValue("0"); this->m_PlayWinTimesPercent_tc->SetValue("0"); this->m_doubleTotalPlayScore_tc->SetValue("0"); this->m_doubleTotalWinScore_tc->SetValue("0"); this->m_doublePlayWinScorePercent_tc->SetValue("0"); this->m_doubleTotalPlayTimes_tc->SetValue("0"); this->m_doubleTotalWinTimes_tc->SetValue("0"); this->m_doublePlayWinTimesPercent_tc->SetValue("0"); this->m_mainGameOverMaxWinTimes_tc->SetValue("0"); this->m_doubleGameOverMaxWinTimes_tc->SetValue("0"); this->m_doubleGameMaxConsecutivePassTimes_tc->SetValue("0"); this->m_gridSz->Add(this->m_totalKeyIn,0,wxALL, 5); this->m_gridSz->Add(this->m_totalKeyIn_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_totalKeyOut,0,wxALL, 5); this->m_gridSz->Add(this->m_totalKeyOut_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_keyInOutPercent,0,wxALL, 5); this->m_gridSz->Add(this->m_keyInOutPercent_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_totalPlayScore,0,wxALL, 5); this->m_gridSz->Add(this->m_totalPlayScore_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_totalWinScore,0,wxALL, 5); this->m_gridSz->Add(this->m_totalWinScore_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_PlayWinScorePercent,0,wxALL, 5); this->m_gridSz->Add(this->m_PlayWinScorePercent_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_totalPlayTimes,0,wxALL, 5); this->m_gridSz->Add(this->m_totalPlayTimes_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_totalWinTimes,0,wxALL, 5); this->m_gridSz->Add(this->m_totalWinTimes_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_PlayWinTimesPercent,0,wxALL, 5); this->m_gridSz->Add(this->m_PlayWinTimesPercent_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_doubleTotalPlayScore,0,wxALL, 5); this->m_gridSz->Add(this->m_doubleTotalPlayScore_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_doubleTotalWinScore,0,wxALL, 5); this->m_gridSz->Add(this->m_doubleTotalWinScore_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_doublePlayWinScorePercent,0,wxALL, 5); this->m_gridSz->Add(this->m_doublePlayWinScorePercent_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_doubleTotalPlayTimes,0,wxALL, 5); this->m_gridSz->Add(this->m_doubleTotalPlayTimes_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_doubleTotalWinTimes,0,wxALL, 5); this->m_gridSz->Add(this->m_doubleTotalWinTimes_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_doublePlayWinTimesPercent,0,wxALL, 5); this->m_gridSz->Add(this->m_doublePlayWinTimesPercent_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_mainGameOverMaxWinTimes,0,wxALL, 5); this->m_gridSz->Add(this->m_mainGameOverMaxWinTimes_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_doubleGameOverMaxWinTimes,0,wxALL, 5); this->m_gridSz->Add(this->m_doubleGameOverMaxWinTimes_tc,0,wxALL, 5); this->m_gridSz->Add(this->m_doubleGameMaxConsecutivePassTimes,0,wxALL, 5); this->m_gridSz->Add(this->m_doubleGameMaxConsecutivePassTimes_tc,0,wxALL, 5); this->m_sz->Add(this->m_gridSz,0); this->SetSizer(this->m_sz,true); }
3e343b437f8bc2b44e549ddaaf03a16f857dceba
1b608693ff8693b246287f4b7b98cfb4ad690c84
/fon9/Exception.hpp
b06a17a25306e960dffbd5d2d56522f03d6ddc7a
[ "Apache-2.0" ]
permissive
tidesq/libfon9
7a804bcb883ed2e96271277e0cd63647b275b376
7a050db7678c54c275b80d32a057d654344ea18a
refs/heads/master
2020-04-18T23:16:58.330908
2019-01-27T03:56:45
2019-01-27T03:56:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,274
hpp
/// \file fon9/Exception.hpp /// \author [email protected] #ifndef __fon9_Exception_hpp__ #define __fon9_Exception_hpp__ #include "fon9/sys/Config.hpp" #include <stdexcept> namespace fon9 { /// \ingroup Misc /// 丟出異常. /// 透過一層間接呼叫, 可讓 compiler 更容易最佳化: 會丟出異常的 function. template <class E, class... ArgsT> [[noreturn]] void Raise(ArgsT&&... args) { throw E(std::forward<ArgsT>(args)...); } /// \ingroup Misc /// 丟出異常. /// - 指定返回值型別, 雖然Raise()不會返回。 /// - 就可以使用 `cond ? Raise<ReturnT,ex>(msg) : retval;` 這樣的敘述。 /// - 這在 constexpr function 裡面很常用到。 template <class ReturnT, class E, class... ArgsT> [[noreturn]] ReturnT Raise(ArgsT&&... args) { throw E(std::forward<ArgsT>(args)...); } fon9_MSC_WARN_DISABLE(4623); // 4623: 'fon9::BufferOverflow': default constructor was implicitly defined as deleted #define fon9_DEFINE_EXCEPTION(exceptionName, baseException) \ class exceptionName : public baseException { \ using base = baseException; \ public: \ exceptionName() = default; \ using base::base; \ }; fon9_DEFINE_EXCEPTION(BufferOverflow, std::runtime_error); fon9_MSC_WARN_POP; } // namespace #endif//__fon9_Exception_hpp__
04068c90f8a17f9d8aed8fd5ffcdb7ecdf07c53a
6d1b727ce5930270571ce1c9be9744184a16d8a0
/arrayss.cpp
213b17d0f7c7530adcf7eaae5fccd4d5455d9e82
[]
no_license
shivamsatyam/cpp-course
5ca45924de51eb7a52b0553fe5fb86a21ccec367
50d87615dff196095fd7c73498aec6dd36894d12
refs/heads/master
2023-02-14T03:58:53.932189
2021-01-14T15:02:57
2021-01-14T15:02:57
329,649,476
0
0
null
null
null
null
UTF-8
C++
false
false
918
cpp
#include<iostream> #include <iomanip> using namespace std; int main() { int marks[4] = {23,45,56,89}; //we can also make array like that //1. int marks[] = {23,4,5,6,7}; cout<<marks[0]<<endl; cout<<marks[1]<<endl; cout<<marks[2]<<endl; cout<<marks[3]<<endl; /*printing array using for loop*/ for (int i = 0; i < 4; i++) { cout<<"the value of marks is "<<marks[i]<<endl; } /*using pointer for making array*/ /*pointer arthimatic---------- pointer(new) = point(current) + i*size of data type */ int *pointer = marks; cout<<"the value of marks[0] is "<<*pointer<<endl; cout<<"the value of marks[0] is "<<*(pointer+1)<<endl; cout<<"the value of marks[0] is "<<*(pointer+2)<<endl; cout<<"the value of marks[0] is "<<*(pointer+3)<<endl; return 0; }
c8a41be38ee60a8554ac7a1fd0b6d822c931c7a2
bed66ac3ac02b936c108e6a3685412dd82e8a1a3
/万圣节后的早晨.cpp
fb0bc8b57c60a1e70f13c5f197ff44e3f9a23cfc
[]
no_license
muleimulei/liurujia2-ACM
a39c4ed296060925c5dd67cb441a727083b93dad
d980d7e309e88788f1cc1797b453d7f6908861dc
refs/heads/master
2021-06-09T06:50:48.142943
2021-04-11T12:41:05
2021-04-11T12:41:05
140,162,117
3
3
null
null
null
null
WINDOWS-1252
C++
false
false
2,350
cpp
#include<cstdio> #include<cctype> #include<cstring> #include<map> #include<queue> using namespace std; const int maxn = 18; int h,w,n; char G[maxn][maxn]; int s[3], e[3]; bool mark[maxn*maxn]; // ¼Ç¼¿ÕµØ short d[maxn*maxn][maxn*maxn][maxn*maxn]; vector<short> vv[maxn*maxn], ve; int go[][2]={ 0, 0, -1, 0, 1, 0, 0, -1, 0, 1 }; bool chongtu(int n1, int n2, int x, int y){ return n1==n2 || ( n1==y && n2==x); } int bfs(){ vector<int> v1, v2; for(int i = 0; i < n; i++){ v1.push_back(s[i]); v2.push_back(e[i]); } d[v1[0]][v1[1]][v1[2]] = 0; // ³õʼ״̬ queue<vector<int> > q; q.push(v1); while(!q.empty()){ vector<int> b = q.front(); q.pop(); if(b==v2){ return d[v2[0]][v2[1]][v2[2]]; }else{ int y1 = b[0], y2 = b[1], y3 = b[2]; // ×´Ì¬Ç¨ÒÆ for(int i = 0; i < vv[y1].size(); i++){ int new1 = vv[y1][i]; for(int j = 0; j < vv[y2].size(); j++){ int new2 = vv[y2][j]; if(chongtu(new1, new2, y1, y2)) continue; for(int k = 0; k < vv[y3].size(); k++){ int new3 = vv[y3][k]; if(chongtu(new1, new3, y1, y3)) continue; if(chongtu(new2, new3, y2, y3)) continue; if(d[new1][new2][new3]!=-1) continue; d[new1][new2][new3] = d[y1][y2][y3]+1; q.push({new1, new2, new3}); } } } } } return -1; } int main(){ #ifdef LOCAL freopen("1.in", "r", stdin); #endif while(scanf("%d%d%d", &w, &h, &n)!=EOF&&n){ getchar(); memset(mark, 0, sizeof(mark)); memset(d, -1, sizeof(d)); ve.clear(); for(int i = 0; i < h; i++){ fgets(G[i], maxn, stdin); } for(int i = 0; i < h; i++){ for(int j = 0; j < w; j++ ){ int id = i * w + j; if(G[i][j]!='#'){ ve.push_back(id); if(islower(G[i][j])){ s[ G[i][j]-'a' ] = id; }else if(isupper( G[i][j] )){ e[ G[i][j]-'A' ] = id; } } } } for(int i = 0; i < ve.size(); i++){ vv[ve[i]].clear(); int x = ve[i]/ w, y = ve[i] % w; for(int k = 0; k < 5; k++){ int nx = x + go[k][0], ny = y + go[k][1]; if(G[nx][ny]!='#'){ vv[ve[i]].push_back(nx * w + ny); } } } if(n<=2){ s[n] = e[n] = 0; vv[0].clear(); vv[0].push_back(0); n++; } if(n<=1){ s[n] = e[n] = 1; vv[1].clear(); vv[1].push_back(1); n++; } printf("%d\n", bfs()); } return 0; }
e3ea1392b978065ace3e483aa57f7162dadb18b3
9f8a069f7d337a022cae89e3e5b75d161c832e2d
/Midterm_Case/Graded_Mesh/TimeAccurate/Laminar/275/p
e630247dd98c988b655c7aa306f8625cdb892f25
[]
no_license
Logan-Price/CFD
453f6df21f90fd91a834ce98bc0b3970406f148d
16e510ec882e65d5f7101e0aac91dbe8a035f65d
refs/heads/master
2023-04-06T04:17:49.899812
2021-04-19T01:22:14
2021-04-19T01:22:14
359,291,399
0
0
null
null
null
null
UTF-8
C++
false
false
19,332
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1912 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "275"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 2000 ( -0.0412587 0.0761525 0.130732 0.123843 0.108015 0.101707 0.1011 0.10245 0.102668 0.10244 0.102573 0.10225 0.101988 0.101931 0.101981 0.101932 0.101771 0.101672 0.101619 0.101578 0.101511 0.101381 0.101213 0.101046 0.100924 0.100859 0.10083 0.100791 0.100718 0.100605 0.100467 0.100335 0.10025 0.100252 0.100371 0.100661 0.101085 0.101597 0.102142 0.102638 0.102995 0.103117 0.102783 0.102017 0.100821 0.0991973 0.0969938 0.0947154 0.0923419 0.0901228 0.0883188 0.087119 0.0865811 0.0866186 0.0869937 0.0872968 0.0869939 0.0856064 0.0832109 0.081085 0.0811714 0.0851397 0.0938199 0.105736 0.119189 0.132697 0.145354 0.156745 0.166678 0.17495 0.181329 0.18551 0.187037 0.18525 0.179128 0.167527 0.148852 0.122525 0.0824137 0.0413566 0.0119854 0.0971626 0.135981 0.122786 0.105045 0.100844 0.104375 0.106806 0.104059 0.100834 0.100394 0.101686 0.102142 0.102012 0.102166 0.101969 0.101746 0.101578 0.101517 0.101493 0.101466 0.101365 0.101192 0.101022 0.100901 0.100842 0.100833 0.100839 0.100802 0.10067 0.100469 0.100243 0.100049 0.0999582 0.100042 0.100296 0.100783 0.101455 0.10224 0.103031 0.103724 0.10398 0.103933 0.103373 0.102157 0.10024 0.0976508 0.0945546 0.0911836 0.0879411 0.0853112 0.0836424 0.0829977 0.0831274 0.0833652 0.0827307 0.0803845 0.0760504 0.0706076 0.0681374 0.0722633 0.0817555 0.0937794 0.107004 0.12068 0.133819 0.145738 0.156139 0.164914 0.171959 0.177065 0.17983 0.179701 0.175986 0.167706 0.153821 0.13294 0.10486 0.0652035 0.0293581 0.0630498 0.0968483 0.11954 0.117983 0.108784 0.104607 0.10464 0.104002 0.102104 0.101446 0.103046 0.104599 0.103557 0.101046 0.100132 0.101001 0.101871 0.101979 0.101709 0.101486 0.101296 0.10111 0.101006 0.100965 0.100956 0.100991 0.101057 0.101103 0.101044 0.100884 0.100557 0.1001 0.0996106 0.0992209 0.099075 0.0992875 0.0998911 0.100915 0.102276 0.103794 0.105199 0.10643 0.10706 0.106882 0.105585 0.103021 0.0992012 0.0943651 0.0890316 0.0839925 0.0801045 0.0779538 0.0776163 0.0787401 0.0802578 0.0812301 0.0809345 0.0794532 0.0779234 0.0775029 0.0807497 0.0880601 0.0984169 0.110224 0.12226 0.133687 0.143948 0.152731 0.159888 0.165294 0.16873 0.169821 0.16804 0.162735 0.153106 0.13839 0.117607 0.0909969 0.0555759 0.0249042 0.0880344 0.0980482 0.110598 0.114677 0.111983 0.108963 0.107301 0.105571 0.103956 0.103151 0.10296 0.102836 0.102475 0.101749 0.101207 0.102128 0.103308 0.10247 0.101147 0.100523 0.100301 0.100469 0.100764 0.100992 0.101181 0.101394 0.101621 0.101806 0.101792 0.10151 0.100922 0.100041 0.0989965 0.0980111 0.0973876 0.0974394 0.0981637 0.0997088 0.102081 0.10497 0.107935 0.110451 0.111903 0.11237 0.110892 0.107257 0.101538 0.0942122 0.0862025 0.0787928 0.0732714 0.0704677 0.0702666 0.0724328 0.0759476 0.0793826 0.08176 0.0828541 0.0833355 0.0844476 0.087787 0.0941064 0.102885 0.112892 0.123063 0.1327 0.14131 0.148549 0.154195 0.158075 0.159956 0.159498 0.156244 0.149661 0.139153 0.124206 0.104169 0.0794561 0.0480317 0.0206985 0.100373 0.103973 0.111493 0.115462 0.114332 0.112001 0.110619 0.10958 0.108279 0.10683 0.105473 0.10437 0.10363 0.102766 0.101768 0.101763 0.102276 0.102416 0.102093 0.101401 0.100828 0.100588 0.100641 0.100882 0.101196 0.101575 0.101974 0.102267 0.102422 0.102191 0.101398 0.100034 0.0982898 0.0965142 0.0951834 0.094792 0.0955649 0.097818 0.101322 0.105695 0.11031 0.11441 0.11739 0.11798 0.116162 0.111529 0.104161 0.0947379 0.0845053 0.0751092 0.0682491 0.0647986 0.0649749 0.0678083 0.0722826 0.0770408 0.0810671 0.0840567 0.0864619 0.0892251 0.0933464 0.0993289 0.106901 0.115295 0.123726 0.131613 0.138539 0.144195 0.148353 0.150811 0.151334 0.149617 0.145289 0.137936 0.127117 0.112479 0.0935572 0.0708133 0.042695 0.0180296 0.108812 0.110646 0.114599 0.116768 0.115951 0.114341 0.113379 0.112702 0.11174 0.110546 0.10941 0.108405 0.10737 0.106016 0.104605 0.103861 0.103685 0.103463 0.102727 0.101622 0.100796 0.100485 0.100575 0.100832 0.101145 0.101585 0.10219 0.102809 0.103148 0.102887 0.101808 0.0999421 0.0975948 0.0952447 0.0934923 0.0928757 0.0940518 0.0968443 0.101114 0.106411 0.111991 0.116938 0.120342 0.121238 0.119116 0.113793 0.105628 0.0955721 0.0850809 0.0758875 0.0694632 0.066556 0.0670407 0.0701372 0.0747727 0.0797708 0.0842932 0.0880791 0.0914132 0.0949066 0.0991753 0.104542 0.110885 0.117743 0.124565 0.130885 0.136348 0.140671 0.143616 0.144961 0.144472 0.141879 0.136874 0.129126 0.118283 0.104079 0.0861406 0.0649299 0.0390765 0.0163969 0.115621 0.116444 0.117681 0.118017 0.117228 0.11624 0.115577 0.115034 0.114363 0.1136 0.112865 0.112128 0.111244 0.110104 0.108899 0.108002 0.107427 0.106726 0.105602 0.104317 0.103336 0.102813 0.102631 0.102617 0.102718 0.102971 0.103349 0.103681 0.103723 0.103248 0.102103 0.100304 0.0981057 0.0959601 0.0945121 0.0942749 0.0956222 0.0985428 0.102803 0.107889 0.113075 0.117523 0.120404 0.120986 0.118822 0.113813 0.10633 0.0973079 0.0881139 0.080255 0.0749244 0.0726392 0.0732011 0.0759166 0.0798927 0.0842792 0.0884825 0.0922999 0.0958827 0.0995868 0.103773 0.108628 0.114075 0.119812 0.125438 0.130582 0.134934 0.138232 0.140244 0.140748 0.139521 0.136317 0.130868 0.122891 0.112089 0.0982465 0.08104 0.0609179 0.0365751 0.0153586 0.121497 0.121442 0.120526 0.119315 0.118489 0.117969 0.117488 0.117012 0.116563 0.116117 0.115653 0.115136 0.114512 0.113737 0.112892 0.11215 0.111541 0.110815 0.109816 0.108714 0.107786 0.107151 0.106762 0.106536 0.10644 0.106473 0.106584 0.106637 0.106445 0.105829 0.104681 0.10305 0.101187 0.0995024 0.0986032 0.098781 0.100285 0.103078 0.106889 0.111249 0.115537 0.119062 0.121157 0.121279 0.119129 0.114729 0.108492 0.101221 0.0939716 0.0878165 0.0835638 0.0815607 0.0816781 0.0834566 0.0863086 0.0896793 0.0931674 0.0966064 0.100046 0.103664 0.107644 0.112068 0.116854 0.121773 0.126519 0.130782 0.134291 0.136805 0.138102 0.137968 0.136185 0.132525 0.126745 0.118596 0.10782 0.0942328 0.0775447 0.0581836 0.0348856 0.0146532 0.126901 0.12591 0.122945 0.1204 0.119641 0.119548 0.11921 0.118795 0.118523 0.118294 0.11801 0.117665 0.117249 0.116737 0.116158 0.115614 0.115131 0.114568 0.113821 0.11298 0.112227 0.111668 0.111295 0.111058 0.110925 0.110873 0.110856 0.110771 0.110481 0.109863 0.108863 0.107556 0.106163 0.105034 0.104394 0.104705 0.106047 0.108351 0.111399 0.114818 0.118125 0.120789 0.122314 0.122307 0.120565 0.117121 0.112285 0.106626 0.100888 0.095834 0.0920686 0.0899057 0.0893422 0.0901386 0.0919421 0.0943964 0.0972207 0.100263 0.103499 0.106983 0.110778 0.114886 0.11921 0.123555 0.127668 0.131287 0.134167 0.136086 0.136832 0.136198 0.133977 0.129953 0.123901 0.1156 0.104822 0.0914123 0.0750978 0.0562819 0.0337343 0.0141208 0.13213 0.129942 0.124746 0.1211 0.120633 0.120955 0.120721 0.120391 0.120297 0.120254 0.120116 0.119903 0.119633 0.119287 0.118883 0.11849 0.118131 0.117712 0.117159 0.116531 0.11596 0.115535 0.115257 0.115085 0.114987 0.114936 0.114891 0.114772 0.114483 0.113943 0.113129 0.11211 0.111054 0.110202 0.109777 0.110093 0.111217 0.113088 0.115533 0.11826 0.120885 0.122992 0.124191 0.124175 0.122777 0.120013 0.116107 0.111479 0.106678 0.102281 0.0987686 0.0964329 0.0953518 0.0954307 0.0964743 0.0982586 0.100583 0.103308 0.106362 0.109724 0.113374 0.117259 0.121263 0.125205 0.128864 0.132007 0.134411 0.135868 0.136179 0.135144 0.132565 0.128235 0.121948 0.113506 0.102711 0.0894271 0.0733919 0.0549812 0.0329701 0.0137302 0.137368 0.133517 0.125823 0.12143 0.121518 0.122205 0.122027 0.121806 0.121899 0.122024 0.122018 0.121924 0.121775 0.121554 0.121275 0.120991 0.120718 0.120395 0.119971 0.119491 0.119056 0.118736 0.118533 0.118417 0.118357 0.118325 0.118285 0.118173 0.117916 0.117458 0.116788 0.115969 0.115132 0.114465 0.114172 0.114463 0.11541 0.116963 0.118982 0.121229 0.123395 0.125139 0.12614 0.126143 0.125005 0.122728 0.119474 0.115557 0.111394 0.107436 0.104079 0.101599 0.10013 0.0996743 0.100149 0.101425 0.103363 0.105838 0.108751 0.112025 0.115583 0.119325 0.123115 0.126775 0.130101 0.132883 0.134915 0.136005 0.135962 0.134598 0.131718 0.127127 0.120635 0.112064 0.101243 0.0880579 0.0722425 0.0541468 0.0324925 0.0134937 0.142734 0.136564 0.126148 0.121486 0.122349 0.123307 0.123151 0.123067 0.123343 0.123611 0.123723 0.123742 0.123702 0.123592 0.12342 0.123226 0.123026 0.122777 0.122447 0.122071 0.121731 0.121481 0.121329 0.121249 0.121214 0.121198 0.121167 0.121067 0.120842 0.120447 0.119882 0.119198 0.118509 0.117971 0.117754 0.118015 0.118824 0.120149 0.12187 0.123793 0.125659 0.127179 0.128078 0.128133 0.127211 0.125298 0.122511 0.119088 0.115359 0.111689 0.108417 0.105809 0.104029 0.103152 0.103176 0.104048 0.105678 0.107958 0.11077 0.113993 0.117502 0.12116 0.124807 0.128266 0.131344 0.133846 0.135585 0.136378 0.136048 0.13441 0.131279 0.126468 0.119799 0.111118 0.100274 0.0871783 0.0715471 0.0537093 0.0322521 0.0134453 0.148306 0.138977 0.125755 0.12139 0.123149 0.12426 0.12412 0.1242 0.124644 0.125032 0.125247 0.125368 0.125428 0.125416 0.125339 0.125228 0.125097 0.124917 0.124666 0.124374 0.124108 0.123914 0.123801 0.123748 0.123733 0.123731 0.123709 0.123623 0.123425 0.123084 0.122596 0.122012 0.121428 0.120977 0.1208 0.121027 0.121724 0.122871 0.124372 0.126063 0.127721 0.129097 0.129946 0.130066 0.129329 0.127704 0.125273 0.122221 0.118811 0.115346 0.11212 0.109386 0.107334 0.106091 0.105726 0.106251 0.107623 0.109745 0.112485 0.115687 0.119182 0.122797 0.126353 0.129669 0.132559 0.134842 0.136345 0.136896 0.136328 0.134466 0.131129 0.126138 0.119327 0.110561 0.0997094 0.086702 0.0712341 0.0536181 0.0322219 0.0136074 0.154125 0.140639 0.124742 0.121257 0.123914 0.125067 0.124966 0.125226 0.125817 0.126303 0.12661 0.126823 0.126971 0.127045 0.127051 0.127015 0.126949 0.126833 0.126652 0.126433 0.12623 0.126086 0.126008 0.125981 0.125985 0.125997 0.125987 0.125917 0.125749 0.125453 0.125029 0.124522 0.124014 0.123618 0.123457 0.123645 0.124244 0.125246 0.126575 0.128091 0.129603 0.130888 0.131724 0.131921 0.131351 0.129969 0.127826 0.125062 0.121892 0.118567 0.115349 0.112479 0.110169 0.10859 0.107874 0.10809 0.109237 0.111231 0.113925 0.117128 0.120633 0.124233 0.127733 0.130944 0.133689 0.135797 0.137108 0.137463 0.136704 0.134662 0.131164 0.126038 0.119125 0.110306 0.0994672 0.0865535 0.0712349 0.0538189 0.0323795 0.0139661 0.160198 0.141441 0.123255 0.121178 0.124627 0.125741 0.125716 0.12616 0.126873 0.127442 0.127832 0.128126 0.128351 0.1285 0.128578 0.128609 0.128603 0.128544 0.128424 0.128268 0.128121 0.128021 0.127975 0.127973 0.127996 0.128023 0.128029 0.127978 0.127838 0.127583 0.127213 0.126766 0.126313 0.125954 0.125796 0.125941 0.126453 0.127332 0.128522 0.129905 0.131312 0.132543 0.13339 0.133671 0.133253 0.132079 0.130171 0.127637 0.124647 0.121416 0.118176 0.115161 0.112598 0.110703 0.109662 0.109599 0.110549 0.112439 0.115104 0.11832 0.121846 0.125446 0.128908 0.132041 0.134671 0.13664 0.137798 0.137997 0.137089 0.134914 0.131301 0.126085 0.119113 0.110275 0.0994689 0.0866537 0.0714726 0.0542454 0.0326907 0.0145156 0.166505 0.141308 0.121469 0.121202 0.125265 0.1263 0.126393 0.127011 0.127824 0.128464 0.128928 0.129295 0.129588 0.129802 0.129944 0.130034 0.130081 0.130073 0.130007 0.129905 0.129807 0.129746 0.129729 0.129749 0.129791 0.129834 0.129855 0.129824 0.129712 0.129495 0.12917 0.128771 0.12836 0.128023 0.127859 0.127961 0.128392 0.129166 0.130241 0.131519 0.13285 0.134051 0.134923 0.135288 0.135008 0.134009 0.132294 0.129938 0.127079 0.123899 0.120609 0.117436 0.114628 0.112439 0.111103 0.110795 0.111577 0.113381 0.116025 0.119257 0.122803 0.126407 0.129841 0.132913 0.135454 0.137315 0.138356 0.13844 0.137425 0.135159 0.131477 0.126213 0.11922 0.110393 0.0996378 0.0869228 0.0718679 0.0548243 0.0331283 0.0151874 0.172995 0.140229 0.119566 0.121339 0.125806 0.126769 0.127014 0.127786 0.128678 0.129381 0.129913 0.130344 0.130697 0.130968 0.131166 0.131309 0.131403 0.131441 0.131422 0.131367 0.13131 0.131282 0.131291 0.131331 0.131389 0.131448 0.131484 0.131471 0.131384 0.131199 0.130912 0.130551 0.13017 0.129844 0.129665 0.12972 0.130076 0.130756 0.131733 0.132925 0.134199 0.135382 0.136284 0.136725 0.136559 0.135701 0.134132 0.131902 0.129124 0.125955 0.122592 0.119263 0.116234 0.11379 0.11221 0.111701 0.112347 0.11408 0.116705 0.119945 0.123505 0.127108 0.13052 0.133545 0.13602 0.137802 0.138761 0.138767 0.137685 0.135368 0.131652 0.126377 0.119394 0.110601 0.0999062 0.0872903 0.0723501 0.0554867 0.0336463 0.0159246 0.179583 0.138226 0.117704 0.121571 0.126245 0.127171 0.127587 0.128487 0.129442 0.130202 0.130793 0.13128 0.131683 0.132004 0.13225 0.132437 0.132572 0.132649 0.13267 0.132653 0.132631 0.13263 0.132659 0.132715 0.132786 0.132856 0.132903 0.132904 0.132838 0.132676 0.132415 0.13208 0.131714 0.131387 0.131184 0.131189 0.131473 0.132069 0.132962 0.134083 0.135311 0.136482 0.137408 0.137906 0.137826 0.137066 0.135594 0.133441 0.130701 0.127517 0.124079 0.120618 0.117414 0.114779 0.113015 0.112356 0.112897 0.114573 0.117176 0.120414 0.123976 0.127574 0.130966 0.133958 0.136388 0.138119 0.139026 0.138987 0.13787 0.135531 0.131811 0.126549 0.119595 0.110849 0.100222 0.0877011 0.0728583 0.0561763 0.0342057 0.0166811 0.186177 0.135397 0.115995 0.121855 0.126585 0.127521 0.128108 0.129107 0.13011 0.130915 0.131554 0.132085 0.132528 0.132886 0.133169 0.133391 0.133557 0.133664 0.133714 0.133726 0.133729 0.133746 0.133788 0.133853 0.13393 0.134005 0.134058 0.134065 0.134012 0.133855 0.133609 0.133285 0.132921 0.132582 0.132349 0.132308 0.13253 0.133056 0.133882 0.134948 0.136141 0.137301 0.138241 0.138777 0.138749 0.13805 0.136634 0.134521 0.131794 0.12859 0.125094 0.121541 0.11822 0.115458 0.113573 0.11281 0.113275 0.114903 0.117481 0.120709 0.124264 0.127852 0.131229 0.134197 0.136599 0.138301 0.139182 0.139121 0.137992 0.135655 0.131949 0.126713 0.1198 0.111108 0.100548 0.0881173 0.0733666 0.0568493 0.0347768 0.0174225 0.192685 0.131871 0.11451 0.122143 0.12683 0.127817 0.128553 0.129618 0.13065 0.131485 0.132156 0.132714 0.133182 0.133565 0.133872 0.134115 0.134301 0.134426 0.134495 0.134524 0.134541 0.134568 0.134616 0.134683 0.134761 0.134836 0.134889 0.1349 0.134837 0.134686 0.134444 0.13412 0.133751 0.133397 0.133139 0.13306 0.133237 0.133715 0.134495 0.135524 0.136692 0.137842 0.138789 0.139344 0.139346 0.138679 0.137292 0.135199 0.132477 0.129258 0.125727 0.122122 0.118735 0.1159 0.113943 0.113115 0.113526 0.115115 0.117666 0.120876 0.124419 0.127995 0.131359 0.134313 0.1367 0.138389 0.13926 0.139196 0.138071 0.135747 0.132065 0.126865 0.119995 0.111359 0.100863 0.0885143 0.0738474 0.0574809 0.0353385 0.0181268 0.199031 0.127807 0.113288 0.122397 0.126991 0.12804 0.12888 0.12998 0.131023 0.131874 0.132561 0.133134 0.133615 0.134011 0.13433 0.134585 0.134782 0.134916 0.134994 0.135032 0.135056 0.135086 0.135135 0.135202 0.135279 0.135351 0.135402 0.135408 0.135342 0.135192 0.134948 0.134621 0.134246 0.133881 0.133606 0.133505 0.133655 0.134105 0.134859 0.135865 0.137017 0.13816 0.139108 0.139672 0.139687 0.139037 0.137665 0.135582 0.132862 0.129637 0.126091 0.122463 0.119046 0.116175 0.114179 0.113311 0.113686 0.115242 0.117767 0.120957 0.124484 0.128049 0.131402 0.134348 0.13673 0.138416 0.139288 0.139232 0.138121 0.135818 0.132164 0.127 0.120174 0.11159 0.101155 0.0888827 0.0742895 0.0580582 0.0358758 0.0187839 0.205214 0.123473 0.112355 0.122589 0.127074 0.128172 0.129073 0.130185 0.131232 0.13209 0.132785 0.133364 0.133852 0.134254 0.134578 0.134839 0.13504 0.135179 0.135261 0.135303 0.13533 0.135362 0.135412 0.135478 0.135553 0.135623 0.135671 0.135675 0.135608 0.135455 0.135209 0.134879 0.1345 0.134129 0.133846 0.133734 0.133872 0.134308 0.135048 0.136043 0.137187 0.138325 0.139272 0.139838 0.13986 0.139217 0.137852 0.135776 0.13306 0.129835 0.126285 0.12265 0.119223 0.116338 0.114322 0.113432 0.113781 0.115311 0.117813 0.120984 0.124495 0.128049 0.131395 0.134337 0.136719 0.138409 0.13929 0.139246 0.138154 0.135874 0.132249 0.127119 0.120335 0.1118 0.101421 0.0892166 0.0746899 0.0585764 0.0363797 0.0193937 0.211377 0.119385 0.111721 0.122706 0.127091 0.12822 0.129152 0.13027 0.13132 0.132181 0.132879 0.133462 0.133952 0.134357 0.134685 0.134948 0.135151 0.135292 0.135376 0.135421 0.135449 0.135482 0.135531 0.135597 0.135671 0.135741 0.135787 0.13579 0.135723 0.135568 0.135321 0.134989 0.134607 0.134235 0.133948 0.133833 0.133966 0.134398 0.135132 0.136122 0.137262 0.138396 0.139341 0.139909 0.139935 0.139295 0.137935 0.135863 0.133151 0.12993 0.126382 0.122748 0.119319 0.116429 0.114405 0.1135 0.113831 0.115342 0.117824 0.120977 0.124476 0.12802 0.131361 0.134303 0.136688 0.138385 0.139278 0.13925 0.138177 0.13592 0.132323 0.127225 0.12048 0.111989 0.101662 0.0895201 0.0750552 0.0590435 0.0368529 0.0199735 0.217474 0.116179 0.111324 0.122755 0.127071 0.128214 0.129159 0.130285 0.131337 0.132201 0.132902 0.133486 0.133978 0.134384 0.134713 0.134978 0.135182 0.135324 0.135409 0.135454 0.135483 0.135517 0.135566 0.135632 0.135706 0.135775 0.135822 0.135825 0.135756 0.135602 0.135354 0.135021 0.134639 0.134265 0.133978 0.133863 0.133996 0.134426 0.13516 0.136148 0.137285 0.138419 0.139364 0.139934 0.139959 0.139324 0.137968 0.135901 0.133193 0.129975 0.126431 0.122798 0.11937 0.116478 0.114448 0.113533 0.11385 0.115345 0.117812 0.120951 0.12444 0.127978 0.131317 0.134261 0.136651 0.138358 0.139264 0.139253 0.138201 0.135968 0.132398 0.127331 0.12062 0.112171 0.10189 0.0898048 0.075397 0.059475 0.0373003 0.0205522 0.222201 0.114237 0.111099 0.122782 0.127049 0.128189 0.129143 0.130274 0.13133 0.132196 0.132897 0.133483 0.133975 0.134382 0.134711 0.134976 0.135181 0.135323 0.135408 0.135454 0.135483 0.135517 0.135568 0.135634 0.135709 0.135778 0.135825 0.135827 0.135758 0.135603 0.135354 0.135021 0.134639 0.134266 0.133979 0.133864 0.133998 0.134428 0.135162 0.13615 0.137288 0.138422 0.139368 0.139939 0.139967 0.139335 0.137983 0.135919 0.133215 0.130001 0.126459 0.122828 0.1194 0.116506 0.11447 0.113546 0.113851 0.115331 0.117786 0.120915 0.124397 0.127932 0.131272 0.134219 0.136616 0.138334 0.139253 0.139258 0.138224 0.136012 0.132465 0.127426 0.120747 0.112334 0.102094 0.0900563 0.0756956 0.0598516 0.0376838 0.0210964 ) ; boundaryField { inlet { type zeroGradient; } outlet { type fixedValue; value uniform 0; } fixedWalls { type zeroGradient; } frontAndBack { type empty; } } // ************************************************************************* //
32e95d34c32588081d77b47e5ea56809153b98da
b2efbd38e567eb271df9ec0a11ebf1abccd22881
/main.cpp
e3d8514c6560426ade1c47181612eb25be1d72ff
[]
no_license
jcaesar/C4C
63050e425414b5fc2931c81a71b7f9badb17741f
338e535d16307045c80b6ed35b56467eca040140
refs/heads/master
2021-01-23T06:29:09.297788
2014-07-17T08:34:29
2014-07-17T08:34:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,817
cpp
#include <utility> using std::swap; using std::move; using std::forward; using std::remove_reference; #include <memory> using std::unique_ptr; #include <limits> using std::numeric_limits; #include <stdexcept> using std::runtime_error; #include <string> using std::string; using std::to_string; #include <unordered_map> using std::unordered_map; #include <list> using std::list; #include <vector> using std::vector; #include <type_traits> using std::underlying_type; #include <cassert> #include <iostream> #include <llvm/Analysis/Passes.h> #include <llvm/ExecutionEngine/ExecutionEngine.h> #include <llvm/ExecutionEngine/JIT.h> #include <llvm/IR/DataLayout.h> #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/IRBuilder.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include <llvm/IR/Module.h> #include <llvm/Analysis/Verifier.h> #include <llvm/PassManager.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Transforms/Scalar.h> using llvm::Module; using llvm::BasicBlock; using llvm::IRBuilder; using llvm::getGlobalContext; using llvm::Value; using llvm::FunctionType; using llvm::ExecutionEngine; using llvm::EngineBuilder; using llvm::FunctionPassManager; using llvm::APInt; using llvm::ConstantInt; using llvm::ConstantStruct; using llvm::AllocaInst; using llvm::StructType; using llvm::Constant; using llvm::CmpInst; using llvm::PHINode; typedef llvm::Function llvmFunction; typedef llvm::Type llvmType; template<typename Res, typename... Args> std::unique_ptr<Res> make_unique(Args && ..._args) { return std::unique_ptr<Res>(new Res(std::forward<Args>(_args)...)); } template <typename T, typename Pred> auto map_vector(const T &vec, Pred f) -> std::vector<typename std::result_of<Pred(typename T::value_type)>::type> { using ret_t = typename std::result_of<Pred(typename T::value_type)>::type; std::vector<ret_t> ret; ret.reserve(vec.size()); for(auto it = vec.begin(); it != vec.end(); ++it) ret.push_back(f(*it)); return ret; } enum class Type : uint8_t { Nil = 0, Variant = 255, Integer = 1, Bool = 2, }; underlying_type<Type>::type TypeTag(Type type) { return static_cast<std::underlying_type<Type>::type>(type); } string Typename(Type type) { switch(type) { case Type::Nil: return "Nil/Void"; case Type::Variant: return "Variant"; case Type::Integer: return "Integer"; case Type::Bool: return "Bool"; } } /* For quick C&P switch(type) { case Type::Nil: case Type::Variant: case Type::Integer: case Type::Bool: } */ template<typename T> Type Type2Script(); template<> Type Type2Script<int32_t>() { return Type::Integer; } template<> Type Type2Script<bool>() { return Type::Bool; } template<> Type Type2Script<void>() { return Type::Nil; } class CompilerError : public runtime_error { public: CompilerError(string msg) : runtime_error(msg) {} }; class UnknownIdentifier : public CompilerError { public: UnknownIdentifier(const string& identifier) : CompilerError("Unknown identifier " + identifier) {} }; class TypeConversion : public CompilerError { public: TypeConversion(Type from, Type to) : CompilerError("Cannot convert " + Typename(from) + " to " + Typename(to)) {} }; class CompilerInternal : public CompilerError { public: CompilerInternal(const string& msg) : CompilerError(msg) {} }; class Unreachable : public CompilerInternal { public: Unreachable() : CompilerInternal("Reached location presumed as unreachable.") {} }; class NamingProvider { private: string basename; static unordered_map<string, size_t> names; string make_name(string name) { auto it = names.find(name); if(it != names.end()) { return name + "." + to_string(++it->second); } else { names.emplace(name, 1); return name + ".1"; } } public: NamingProvider(const string& basename) : basename(basename) {} string tmp(string hint) { return make_name(basename + ".tmp." + hint); } string block(string hint) { return make_name(basename + ".block." + hint); } string stack(string hint) { return make_name(basename + ".stack." + hint); } string tcv(string hint) { return make_name(basename + ".typeconversion." + hint); } }; decltype(NamingProvider::names) NamingProvider::names; class Function; class Variable; class Scope { private: Scope* parent = nullptr; unordered_map<string, unique_ptr<Function>> fns; unordered_map<string, Variable*> vars; template<typename T, typename Q> T& lookup(Q map, const string& name) { const auto it = (this->*map).find(name); if(it == (this->*map).end()) { if(parent) return parent->lookup<T, Q>(map, move(name)); else throw UnknownIdentifier(name); } else return *it->second; } public: Scope() {} explicit Scope(Scope& parent) : parent(&parent) {} Function& func(string&& name) { string temp = move(name); return lookup<Function>(&Scope::fns, temp); } Function& func(const string& name) { return lookup<Function>(&Scope::fns, name); } Variable& var(const string& name) { return lookup<Variable>(&Scope::vars, name); } void addfunc(unique_ptr<Function> f); void addvar(Variable*); void forallfunctions(std::function<void(Function&)> l) { if(parent) parent->forallfunctions(l); for(auto& f: fns) l(*f.second); } }; class SuperContext { private: Module* mod; // owned by execution engine ExecutionEngine* executionengine; unique_ptr<FunctionPassManager> funcpassmgr; Scope globalscope; public: explicit SuperContext(Scope&& scope) : globalscope(scope) { llvm::InitializeNativeTarget(); mod = new Module("mm", getGlobalContext()); string err; executionengine = EngineBuilder(mod).setErrorStr(&err).create(); if(!executionengine) throw CompilerInternal("Could not create Execution Engine: " + err); executionengine->DisableSymbolSearching(); funcpassmgr = make_unique<FunctionPassManager>(mod); //mod->setDataLayout(executionengine->getDataLayout()); //funcpassmgr->add(new llvm::DataLayoutPass(mod)); funcpassmgr->add(llvm::createBasicAliasAnalysisPass()); funcpassmgr->add(llvm::createInstructionCombiningPass()); funcpassmgr->add(llvm::createReassociatePass()); funcpassmgr->add(llvm::createGVNPass()); funcpassmgr->add(llvm::createCFGSimplificationPass()); funcpassmgr->doInitialization(); executionengine->addModule(mod); } SuperContext(SuperContext&&) = default; Scope& scope() { return globalscope; } Module& module() { assert(mod); return *mod; } ExecutionEngine& ee() { assert(executionengine); return *executionengine; } FunctionPassManager& fpm() { assert(funcpassmgr); return *funcpassmgr; } }; class CompilationContext { private: SuperContext& supercontext; IRBuilder<> m_builder; NamingProvider m_names; Function& function; Scope contextscope; public: CompilationContext(SuperContext& sc, const string& name, Function& func) : supercontext(sc), m_builder(getGlobalContext()), m_names(name), function(func), contextscope(sc.scope()) { llvmFunction* f = sc.module().getFunction(name); if(!f) throw CompilerInternal("Context for nonexistent function"); BasicBlock* bb = BasicBlock::Create(getGlobalContext(), names().block("entry"), f); m_builder.SetInsertPoint(bb); } /*CompilationContext(CompilationContext& parent, const string& name) : m_module(parent.module()), m_builder(parent.builder()), m_names(parent.names().block(name)), m_scope(parent.scope()), function(parent.function) { builder().SetInsertPoint(&bb()); }*/ CompilationContext(const CompilationContext&) = delete; Module& module() { return supercontext.module(); } IRBuilder<>& builder() { return m_builder; } NamingProvider& names() { return m_names; } Scope& scope() { return contextscope; } Function& func() { return function; } }; template<typename T> T* checkCompile(T* t) { if(!t) throw CompilerInternal("Empty llvm result"); return t; } class Statement { public: virtual ~Statement() {} virtual void compile(CompilationContext&) = 0; }; size_t getVariantTypeSize() { return sizeof(Type) * CHAR_BIT; } size_t getVariantVarSize() { return sizeof(void*) * CHAR_BIT; } llvmType* getVariantTypeLLVMType() { return llvmType::getIntNTy(getGlobalContext(), getVariantTypeSize()); } llvmType* getVariantVarLLVMType() { return llvmType::getIntNTy(getGlobalContext(), getVariantVarSize()); } StructType* getVariantLLVMType() { return StructType::get(getGlobalContext(), { getVariantTypeLLVMType(), getVariantVarLLVMType() }, false); } llvmType* getLLVMType(Type type) { switch(type) { case Type::Nil: return llvmType::getVoidTy(getGlobalContext()); // I don't need space to save a Nil if I already know it's one at Compiletime case Type::Integer: return llvmType::getInt32Ty(getGlobalContext()); case Type::Bool: return llvmType::getInt1Ty(getGlobalContext()); case Type::Variant: return getVariantLLVMType(); } } Constant* TypeTagValue(Type type) { return checkCompile(ConstantInt::get(getGlobalContext(), APInt(getVariantTypeSize(), TypeTag(type), false))); } Value* defaultVariant(Type type) { return ConstantStruct::get(getVariantLLVMType(), vector<Constant*>{ TypeTagValue(type), ConstantInt::get(getGlobalContext(), APInt(getVariantVarSize(), 0, false)), }); } Value* defaultvalue(Type type) { switch(type) { case Type::Integer: return ConstantInt::get(getGlobalContext(), APInt(32, 0, true)); case Type::Bool: return ConstantInt::get(getGlobalContext(), APInt(1, 0, false)); case Type::Nil: case Type::Variant: return defaultVariant(Type::Nil); } } class RValue { private: static llvmFunction* variantconversionexternalfunc; public: static void prepare(SuperContext& sc) { variantconversionexternalfunc = checkCompile(llvmFunction::Create(FunctionType::get(getVariantVarLLVMType(), { getVariantTypeLLVMType(), getVariantTypeLLVMType(), getVariantVarLLVMType() }, false), llvmFunction::ExternalLinkage, "varianttypecoersion", &sc.module())); sc.ee().addGlobalMapping(variantconversionexternalfunc, (void*)&RValue::VariantCoersionFunction); } public: const Type type; Value * const value; RValue(Type type, Value* value) : type(type), value(checkCompile(value)) {} RValue convert(CompilationContext& cc, Type newtype); static void* VariantCoersionFunction(Type oldtype, Type newtype, void* val) { if(oldtype == Type::Integer && newtype == Type::Bool) { if(val != nullptr) return static_cast<char*>(nullptr)+1; else return nullptr; } if(oldtype == Type::Bool && newtype == Type::Integer) { if(val != nullptr) return static_cast<char*>(nullptr)+1; else return nullptr; } throw runtime_error("Cannot convert " + Typename(oldtype) + " to " + Typename(newtype) + "."); } }; decltype(RValue::variantconversionexternalfunc) RValue::variantconversionexternalfunc(nullptr); class Variable : public Statement { protected: AllocaInst* stackptr = nullptr; public: const Type type; const string name; Variable(Type type, const string&& name) : type(type), name(move(name)) { if(type == Type::Nil) throw CompilerInternal("Variable with static type Nil"); } void compile(CompilationContext& cc, Value* defaultvalue) { llvmFunction* f = cc.builder().GetInsertBlock()->getParent(); IRBuilder<> entrybuilder(&f->getEntryBlock(), f->getEntryBlock().begin()); stackptr = entrybuilder.CreateAlloca(getLLVMType(type), 0, cc.names().stack(name)); if(!defaultvalue) defaultvalue = ::defaultvalue(type); store(cc, RValue(type, defaultvalue)); cc.scope().addvar(this); } void compile(CompilationContext& cc) { compile(cc, nullptr); } RValue load(CompilationContext& cc) { if(!stackptr) throw CompilerInternal("Variable::load before Variable::compile"); return RValue(type, cc.builder().CreateLoad(stackptr, cc.names().tmp(name))); } virtual void store(CompilationContext& cc, RValue&& value) { if(!stackptr) throw CompilerInternal("Variable::store before Variable::compile"); cc.builder().CreateStore(value.convert(cc, type).value, stackptr); } }; class Body { private: vector<unique_ptr<Statement>> body; public: Body() {} Body(vector<unique_ptr<Statement>>&& stmts) : body(move(stmts)) {} void add_statement(unique_ptr<Statement> stmt) { body.push_back(move(stmt)); } void compile(CompilationContext& cc); }; class Function { protected: llvmFunction* f = nullptr; public: const string name; const Type returntype; Function(const string& fname, Type ret) : name(fname), returntype(ret) {} virtual ~Function() {}; virtual void precompile(Module& m) { if(m.getFunction(name)) throw CompilerInternal("Function has already been precompiled"); FunctionType *ft = FunctionType::get(getLLVMType(returntype), map_vector(partypes(), getLLVMType), false); f = checkCompile(llvmFunction::Create(ft, llvmFunction::ExternalLinkage, name, &m)); if (f->getName() != name) { f->eraseFromParent(); throw CompilerInternal("Uncaught naming clash"); } } virtual void compile(SuperContext& sc) = 0; llvmFunction& func() { if(!f) throw CompilerInternal("Reference to uncompiled function"); return *f; } virtual vector<Type> partypes() = 0; virtual RValue compilecall(CompilationContext& cc, vector<RValue> argvs) { return RValue(returntype, cc.builder().CreateCall(&func(), map_vector(argvs, [](const RValue& v){ return v.value; }), returntype != Type::Nil ? cc.names().tmp("call." + name) : "")); } }; class ScriptFunction : public Function { private: Body body; vector<Variable> args; public: ScriptFunction(const string& name, Type ret, const vector<Variable>&& args, Body&& body) : Function(name, ret), body(move(body)), args(move(args)) {} virtual void precompile(Module& m) { Function::precompile(m); size_t i = 0; for (llvmFunction::arg_iterator argit = f->arg_begin(); i != args.size(); ++argit, ++i) { argit->setName(args[i].name); } } void compile(SuperContext& sc) { if(!f) throw CompilerInternal("Function::compile before Function::precompile"); CompilationContext cc(sc, name, *this); llvmFunction::arg_iterator argit = f->arg_begin(); for (unsigned i = 0; i != args.size(); ++i, ++argit) { args[i].compile(cc, argit); } assert(argit == f->arg_end()); body.compile(cc); if(!cc.builder().GetInsertBlock()->getTerminator()) cc.builder().CreateRet(cc.func().returntype == Type::Nil ? nullptr : defaultvalue(cc.func().returntype)); f->dump(); llvm::verifyFunction(*f); sc.fpm().run(*f); } vector<Type> partypes() { return map_vector(args, std::function<Type(const Variable&)>([](const Variable& arg){ return arg.type; })); } }; class EngineFunction : public Function{ private: void *ef = nullptr; vector<Type> argts; public: template<typename Result, typename... Args> EngineFunction(const string& name, Result(*func)(Args...)) : Function(name, Type2Script<Result>()), ef(reinterpret_cast<void*>(func)), argts{Type2Script<Args>()...} {} void compile(SuperContext& sc) { if(!f) throw CompilerInternal("Function::compile before Function::precompile"); sc.ee().addGlobalMapping(f, ef); } vector<Type> partypes() { return argts; } }; class Program { private: vector<unique_ptr<Function>> fns; public: void addfunc(unique_ptr<Function> fp) { fns.push_back(move(fp)); } SuperContext&& compile() { Scope globalscope; for(auto& fn: fns) globalscope.addfunc(move(fn)); SuperContext sc(move(globalscope)); RValue::prepare(sc); globalscope.forallfunctions([&sc](Function& f) { f.precompile(sc.module()); }); globalscope.forallfunctions([&sc](Function& f) { f.compile(sc); }); sc.module().MaterializeAllPermanently(); return move(sc); } }; class Expression { public: virtual ~Expression() {} virtual RValue compile(CompilationContext&) = 0; }; typedef unique_ptr<Expression> Eup; class Return : public Statement { private: Eup rv; public: Return(Eup rv) : rv(move(rv)) {} void compile(CompilationContext& cc) { if(cc.func().returntype == Type::Nil) { if(!rv) checkCompile(cc.builder().CreateRet(nullptr)); else throw TypeConversion(rv->compile(cc).type, Type::Nil); } else { if(rv) checkCompile(cc.builder().CreateRet(rv->compile(cc).convert(cc, Type::Integer).value)); else throw TypeConversion(Type::Nil, cc.func().returntype); } } }; class Eval : public Statement { private: Eup ev; public: Eval(Eup ev) : ev(move(ev)) {} void compile(CompilationContext& cc) { checkCompile(ev->compile(cc).value); } }; class Var : public Expression { private: string v; public: explicit Var(const string& v) : v(v) {} RValue compile(CompilationContext& cc) { return cc.scope().var(string(v)).load(cc); } }; class ConstInt : public Expression { private: int32_t c; public: ConstInt(int32_t c) : c(c) {} RValue compile(CompilationContext& cc) { return RValue(Type::Integer, ConstantInt::get(getGlobalContext(), APInt(sizeof(c)*CHAR_BIT,c,numeric_limits<decltype(c)>::min < 0))); } }; template<Type type, Type rettype> class Binary : public Expression { // Currently integer binary protected: Eup lh, rh; private: virtual Value* compileInstr(CompilationContext& cc, Value* lhv, Value* rhv) = 0; public: Binary(Eup lh, Eup rh) : lh(move(lh)), rh(move(rh)) {} RValue compile(CompilationContext& cc) { auto lhv = lh->compile(cc).convert(cc, type); auto rhv = rh->compile(cc).convert(cc, type); return RValue(rettype, compileInstr(cc, lhv.value, rhv.value)); } }; class Plus : public Binary<Type::Integer, Type::Integer> { public: using Binary::Binary; private: Value* compileInstr(CompilationContext& cc, Value* lhv, Value* rhv) { return cc.builder().CreateAdd(lhv, rhv, cc.names().tmp("add")); } }; class Minus : public Binary<Type::Integer, Type::Integer> { public: using Binary::Binary; private: Value* compileInstr(CompilationContext& cc, Value* lhv, Value* rhv) { return cc.builder().CreateSub(lhv, rhv, cc.names().tmp("sub")); } }; template<llvm::CmpInst::Predicate pdc> class IntComparison : public Binary<Type::Integer, Type::Bool> { public: using Binary::Binary; private: Value* compileInstr(CompilationContext& cc, Value* lhv, Value* rhv) { return cc.builder().CreateICmp(pdc, lhv, rhv, cc.names().tmp(name())); } virtual string name() = 0; }; class Less : public IntComparison<CmpInst::ICMP_SLT> { public: using IntComparison::IntComparison; string name() { return "less" ; } }; class Greater : public IntComparison<CmpInst::ICMP_SGT> { public: using IntComparison::IntComparison; string name() { return "greater" ; } }; class LessEq : public IntComparison<CmpInst::ICMP_SLE> { public: using IntComparison::IntComparison; string name() { return "lesseq" ; } }; class GreaterEq : public IntComparison<CmpInst::ICMP_SGE> { public: using IntComparison::IntComparison; string name() { return "greatereq"; } }; class Assignment : public Expression { // Theoretically a binary operation, but technically too different private: string to; Eup rh; public: Assignment(const string& to, Eup rh) : to(to), rh(move(rh)) {} RValue compile(CompilationContext& cc) { Variable& var = cc.scope().var(to); RValue rhv = rh->compile(cc).convert(cc, var.type); var.store(cc, RValue(rhv)); return rhv; } }; class Call : public Expression { private: string fn; vector<Eup> args; public: Call(const string& fn, vector<Eup>&& args) : fn(fn), args(move(args)) {} RValue compile(CompilationContext& cc) { Function& callee = cc.scope().func(fn); auto partypes = callee.partypes(); if (partypes.size() != args.size()) throw CompilerError("Incorrect number of arguments passed: " + callee.name + " expects " + to_string(partypes.size()) + ", " + to_string(args.size()) + " given."); std::vector<RValue> argvs; for (unsigned i = 0, e = args.size(); i != e; ++i) { argvs.push_back(args[i]->compile(cc).convert(cc, partypes[i])); } return callee.compilecall(cc, argvs); } }; class If : public Statement { private: Eup condition; Body thenbody; Body elsebody; public: If(Eup condition, Body thenbody, Body elsebody) : condition(move(condition)), thenbody(move(thenbody)), elsebody(move(elsebody)) {} void compile(CompilationContext& cc) { RValue ifcond(condition->compile(cc).convert(cc, Type::Bool)); BasicBlock* orig = cc.builder().GetInsertBlock(); BasicBlock* thenbb = BasicBlock::Create(getGlobalContext(), cc.names().block("if.then"), &cc.func().func()); cc.builder().SetInsertPoint(thenbb); thenbody.compile(cc); BasicBlock* elsebb = BasicBlock::Create(getGlobalContext(), cc.names().block("if.else"), &cc.func().func()); cc.builder().SetInsertPoint(elsebb); elsebody.compile(cc); cc.builder().SetInsertPoint(orig); cc.builder().CreateCondBr(ifcond.value, thenbb, elsebb); BasicBlock* continuation = BasicBlock::Create(getGlobalContext(), cc.names().block("if.continuation"), &cc.func().func()); if(!thenbb->getTerminator()) { cc.builder().SetInsertPoint(thenbb); cc.builder().CreateBr(continuation); } if(!elsebb->getTerminator()) { cc.builder().SetInsertPoint(elsebb); cc.builder().CreateBr(continuation); } cc.builder().SetInsertPoint(continuation); } }; class While : public Statement { private: Eup condition; Body body; public: While(Eup condition, Body body) : condition(move(condition)), body(move(body)) {} void compile(CompilationContext& cc) { // Blocks BasicBlock* orig = cc.builder().GetInsertBlock(); BasicBlock* condbb = BasicBlock::Create(getGlobalContext(), cc.names().block("while.cond"), &cc.func().func()); BasicBlock* bodybb = BasicBlock::Create(getGlobalContext(), cc.names().block("while.body"), &cc.func().func()); BasicBlock* contbb = BasicBlock::Create(getGlobalContext(), cc.names().block("while.continuation"), &cc.func().func()); // Compile cc.builder().CreateBr(condbb); cc.builder().SetInsertPoint(condbb); RValue whilecond(condition->compile(cc).convert(cc, Type::Bool)); cc.builder().CreateCondBr(whilecond.value, bodybb, contbb); cc.builder().SetInsertPoint(bodybb); body.compile(cc); cc.builder().CreateBr(condbb); cc.builder().SetInsertPoint(contbb); } }; namespace demo { // convenience functions for demonstration purposes - ugly to write, beautiful when used template<typename T, typename... Args> unique_ptr<Expression> e(Args && ... args) { return make_unique<T>(forward<Args>(args)...); } template<typename T, typename... Args> unique_ptr<Statement> s(Args && ... args) { return make_unique<T>(forward<Args>(args)...); } template<typename T, typename... Args> unique_ptr<Function> f(Args && ... args) { return make_unique<T>(forward<Args>(args)...); } template<typename L> void L_ins(vector<unique_ptr<L>>&) {} template<typename L, typename T1, typename... TR> void L_ins(vector<unique_ptr<L>>& v, T1 t1, TR... rest) { v.emplace_back(move(t1)); L_ins(v, move(rest)...); } template<typename... T> vector<unique_ptr<Statement>> SL(T... t) { vector<unique_ptr<Statement>> sl; L_ins<Statement> (sl, move(t)...); return move(sl); } template<typename... T> vector<unique_ptr<Expression>> EL(T... t) { vector<unique_ptr<Expression>> el; L_ins<Expression>(el, move(t)...); return move(el); } int maindo(SuperContext&& sc) { //sc.module().dump(); You can either dump it or execute it, but not both. SIGSEGV otherwise auto mainf = sc.module().getFunction("Main"); if(!mainf) throw CompilerError("No Main"); auto scriptmain = reinterpret_cast<int32_t(*)()>(sc.ee().getPointerToFunction(mainf)); if(!scriptmain) throw CompilerError("Nothing compiled"); return (*scriptmain)(); } } extern "C" { void LogInt(int32_t i) { std::cout << i << std::endl; } void LogBool(bool f) { std::cout << (f?"true":"false") << std::endl; } } int main() { using namespace demo; Program p; //p.addfunc(unique_ptr<ScriptFunction>(new ScriptFunction("Simpleton", Type::Nil, {}, Body(SL(s<Return>(nullptr)))))); p.addfunc(unique_ptr<ScriptFunction>(new ScriptFunction("Foo", Type::Integer, { Variable(Type::Integer, "a"), Variable(Type::Integer, "b") }, Body(SL(s<Return>(e<Plus>(e<Plus>(e<Var>("a"), e<Var>("b")), e<ConstInt>(-1)))))))); p.addfunc(unique_ptr<ScriptFunction>(new ScriptFunction("Bar", Type::Integer, { Variable(Type::Variant, "a"), Variable(Type::Variant, "b") }, Body(SL( s<Variable>(Type::Variant, "ret"), s<Eval>(e<Assignment>("ret", e<Call>("Foo", EL(e<Var>("a"), e<Var>("b"))))), s<If>(e<Less>(e<Var>("ret"), e<ConstInt>(3)), SL(s<Eval>(e<Assignment>("ret", e<ConstInt>(3)))), SL()), s<Return>(e<Var>("ret")) ))))); p.addfunc(unique_ptr<ScriptFunction>(new ScriptFunction("Main", Type::Integer, {}, Body(SL( s<Eval>(e<Call>("LogInt", EL(e<Call>("Foo", EL(e<ConstInt>(1), e<ConstInt>(3)))))), s<Eval>(e<Call>("LogBool", EL(e<Call>("Foo", EL(e<ConstInt>(1), e<ConstInt>(2)))))), s<Eval>(e<Call>("LogBool", EL(e<ConstInt>(-2)))), s<Eval>(e<Call>("LogBool", EL(e<ConstInt>(-1)))), s<Eval>(e<Call>("LogBool", EL(e<ConstInt>( 0)))), s<Eval>(e<Call>("LogBool", EL(e<ConstInt>(+1)))), s<Eval>(e<Call>("LogBool", EL(e<ConstInt>(+2)))), s<Variable>(Type::Integer, "inttest"), s<Eval>(e<Assignment>("inttest", e<Call>("Foo", EL(e<ConstInt>(5), e<ConstInt>(2))))), s<Variable>(Type::Bool, "booltest"), s<Eval>(e<Assignment>("booltest", e<Var>("inttest"))), s<Eval>(e<Call>("LogBool", EL(e<Var>("booltest")))), s<Variable>(Type::Variant, "varianttest"), s<Eval>(e<Assignment>("varianttest", e<ConstInt>(13))), s<Eval>(e<Assignment>("varianttest", e<Var>("booltest"))), s<Eval>(e<Call>("LogBool", EL(e<Var>("varianttest")))), s<Eval>(e<Call>("VariantFuncTest", EL(e<ConstInt>(17)))), s<Eval>(e<Call>("WhileTest", EL(e<ConstInt>(7)))), s<Return>(e<ConstInt>(0)) ))))); p.addfunc(make_unique<EngineFunction>("LogInt", &LogInt)); p.addfunc(make_unique<EngineFunction>("LogBool", &LogBool)); p.addfunc(unique_ptr<ScriptFunction>(new ScriptFunction("VariantFuncTest", Type::Nil, { Variable(Type::Variant, "p") }, Body(SL( s<Eval>(e<Call>("LogInt", EL(e<Var>("p")))), s<Eval>(e<Call>("LogBool", EL(e<Var>("p")))) ))))); p.addfunc(unique_ptr<ScriptFunction>(new ScriptFunction("WhileTest", Type::Nil, { Variable(Type::Integer, "upto") }, Body(SL( s<Variable>(Type::Variant, "i"), s<Eval>(e<Assignment>("i", e<ConstInt>(0))), s<While>(e<Less>(e<Var>("i"), e<Var>("upto")), SL( s<Eval>(e<Assignment>("i", e<Plus>(e<Var>("i"), e<ConstInt>(1)))), s<Eval>(e<Call>("LogInt", EL(e<Var>("i")))) )) ))))); //p.addfunc(unique_ptr<Function>(new ScriptFunction("LogInt", Type::Nil, {Variable(Type::Integer, "discard")}, Body(SL(s<Return>(nullptr)))))); return maindo(move(p.compile())); } void Scope::addfunc(unique_ptr<Function> f) { if(parent) parent->addfunc(move(f)); else { string name = f->name; fns.emplace(name, move(f)); } } void Scope::addvar(Variable* v) { string name = v->name; vars.emplace(name, v); } RValue RValue::convert(CompilationContext& cc, Type newtype) { if(newtype == type) return *this; if(newtype == Type::Variant) { Value* newvalue = nullptr; switch(type) { case Type::Nil: newvalue = defaultVariant(type); break; case Type::Integer: case Type::Bool: newvalue = cc.builder().CreateInsertValue(defaultVariant(type), cc.builder().CreateZExt(value, getVariantVarLLVMType(), cc.names().tcv("intbooltovariantvalue")), {1}, cc.names().tcv("intbooltovariant")); break; case Type::Variant: throw Unreachable(); } return RValue(Type::Variant, newvalue); } if(type == Type::Variant) { switch(newtype) { case Type::Integer: case Type::Bool: { Value* typetag = checkCompile(cc.builder().CreateExtractValue(value, {0}, cc.names().tcv("varianttointbool.typetag"))); Value* typematch = checkCompile(cc.builder().CreateICmp(CmpInst::ICMP_EQ, TypeTagValue(newtype), typetag, cc.names().tcv("varianttointbool.typematch"))); Value* extract = checkCompile(cc.builder().CreateExtractValue(value, {1}, cc.names().tcv("varianttointbool.directextract"))); BasicBlock* orig = cc.builder().GetInsertBlock(); BasicBlock* mismatch = BasicBlock::Create(getGlobalContext(), cc.names().block("varianttointbool.typemismatch"), &cc.func().func()); BasicBlock* continuation = BasicBlock::Create(getGlobalContext(), cc.names().block("varianttointbool.continuation"), &cc.func().func()); cc.builder().CreateCondBr(typematch, continuation, mismatch); cc.builder().SetInsertPoint(mismatch); if(!variantconversionexternalfunc) throw CompilerInternal("RValue was not prepare()d"); Value* coersion = checkCompile(cc.builder().CreateCall(variantconversionexternalfunc, { typetag, TypeTagValue(newtype), extract }, cc.names().tcv("varianttoint.enginecoersion"))); cc.builder().CreateBr(continuation); cc.builder().SetInsertPoint(continuation); PHINode *pn = cc.builder().CreatePHI(getVariantVarLLVMType(), 2, cc.names().tcv("varianttointbool.merge")); pn->addIncoming(extract, orig); pn->addIncoming(coersion, mismatch); Value* trunc = checkCompile(cc.builder().CreateTrunc(pn, getLLVMType(newtype), cc.names().tcv("varianttointbool.trunc"))); return RValue(newtype, trunc); } break; case Type::Nil: case Type::Variant: throw Unreachable(); } } if(newtype == Type::Bool && type == Type::Integer) return RValue(Type::Bool, cc.builder().CreateICmp(CmpInst::ICMP_NE, value, ConstInt(0).compile(cc).value, cc.names().tcv("inttobool"))); throw TypeConversion(type, newtype); } void Body::compile(CompilationContext& cc) { for(auto& stmt: body) { stmt->compile(cc); if(cc.builder().GetInsertBlock()->getTerminator()) return; } }
35c473776703d720a97279a8f4d06f4090421832
1942a0d16bd48962e72aa21fad8d034fa9521a6c
/aws-cpp-sdk-batch/include/aws/batch/model/TerminateJobResult.h
333671097f9973c768fd6161d7195ab41020f146
[ "Apache-2.0", "JSON", "MIT" ]
permissive
yecol/aws-sdk-cpp
1aff09a21cfe618e272c2c06d358cfa0fb07cecf
0b1ea31e593d23b5db49ee39d0a11e5b98ab991e
refs/heads/master
2021-01-20T02:53:53.557861
2018-02-11T11:14:58
2018-02-11T11:14:58
83,822,910
0
1
null
2017-03-03T17:17:00
2017-03-03T17:17:00
null
UTF-8
C++
false
false
1,177
h
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/batch/Batch_EXPORTS.h> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace Batch { namespace Model { class AWS_BATCH_API TerminateJobResult { public: TerminateJobResult(); TerminateJobResult(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); TerminateJobResult& operator=(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); }; } // namespace Model } // namespace Batch } // namespace Aws
aa9c9089cab878e2854bd86d5f607ec6926958ad
c3e2efd04e5a79d66ba81ea4bbd5f6fc910170cf
/Main.cpp
2a03eb7eaf9aebc3e8fa6d522d8895fe10de58ac
[]
no_license
max1fox/skolziot11
38aa8f967b7542031ef9ce768ce477f946cf70f9
b49968757e01e9663830d1db23526ec73c2379ed
refs/heads/master
2020-09-12T12:15:40.240182
2019-11-18T11:19:51
2019-11-18T11:19:51
222,422,413
0
0
null
null
null
null
UTF-8
C++
false
false
2,345
cpp
#include "iostream" #include "conio.h" using namespace std; class Matrix { private: int mtx[5]; public: void InputElement(int a) { cin >> mtx[a]; } void sMatrix(int a) { static int ptr = 0; mtx[ptr] = a; if (ptr == 4) ptr = -1; ptr++; } int* GetMatrix() { return mtx; } friend void OutputMatrix(Matrix* A, int n); void merge(int start, int mid, int end) { int t[5]; int i = start, j = mid + 1, k = 0; while (i <= mid && j <= end) { if (this->mtx[i] <= this->mtx[j]) { t[k] = this->mtx[i]; k++; i++; } else { t[k] = this->mtx[j]; k++; j++; } } while (i <= mid) { t[k] = this->mtx[i]; k++; i++; } while (j <= end) { t[k] = this->mtx[j]; k++; j++; } for (i = start; i <= end; i++) { this->mtx[i] = t[i - start]; } } void mergeSort(int start, int end) { if (start < end) { int mid = (start + end) / 2; mergeSort(start, mid); mergeSort(mid + 1, end); merge(start, mid, end); } } }; void OutputMatrix(Matrix* mtx, int n) { for (int i = 0; i < n; ++i) { cout << mtx->mtx[i]; } cout << endl; } int main() { Matrix matrix[5]; for (int i = 0; i < 5; i++) for (int j = 0; j < 5; j++) { matrix[j].InputElement(i); } Matrix matrix1; for (int i = 0; i < 5; i++) matrix[i].mergeSort(0, 4); for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { cout << matrix[j].GetMatrix()[i] << "\t "; matrix1.sMatrix(matrix[j].GetMatrix()[i]); } cout << endl; } double sum = 0; int f1 = 0, f2 = 0, f3 = 0, f4 = 0, f5 = 0; for (int i = 0; i < 5; i++) { // f1 f1 += matrix[i].GetMatrix()[0]; } for (int i = 0; i < 5; i++) { // f2 f2 += matrix[i].GetMatrix()[1]; } for (int i = 0; i < 5; i++) { // f3 f3 += matrix[i].GetMatrix()[2]; } for (int i = 0; i < 5; i++) { // f4 f4 += matrix[i].GetMatrix()[3]; } for (int i = 0; i < 5; i++) { // f5 f5 += matrix[i].GetMatrix()[4]; } cout << "\n"; sum = pow((f1 * f2 * f3 * f4 * f5),1./5); cout << "f1(): " << f1 << "\n" << "f2(): " << f2 << "\n" << "f3(): " << f3 << "\n" << "f4(): " << f4 << "\n" << "f5():" << f5 << "\n\n"; cout << "F(f()): " << sum << "\n"; return 0; }
e8c40eca078e9ddfde0aa571d7157b2e937c94eb
19c5b34e8863539d1c89362c599e63471759bc6c
/StringMachine/src/scenes/CircleScene.h
7ca77d0e1060a25720dd66c7a1e8f0f81c670846
[]
no_license
jg33/StringMachinery
8463a4ef9a46789c15438f7141ca84bdeea373c6
3fcc22a915651556bbfa3a80c846ca670e7c1f53
refs/heads/master
2021-01-10T19:20:23.670853
2015-05-03T08:30:31
2015-05-03T08:30:31
24,396,990
1
0
null
null
null
null
UTF-8
C++
false
false
670
h
// // CircleScene.h // StringMachine // // Created by Jesse Garrison on 10/8/14. // // #ifndef __StringMachine__CircleScene__ #define __StringMachine__CircleScene__ #define NUMCIRCLES 2 #include <stdio.h> #include "ofMain.h" #include "ofxAppUtils.h" #include "Circle.h" class CircleScene : public ofxScene{ public: CircleScene():ofxScene("Circles"){setSingleSetup(false);}; void setup(); void update(); void draw(); void setSizes(vector<float>); inline void setSize(int i, float amp ){circles[i].setSize(amp);}; private: vector<Circle> circles; }; #endif /* defined(__StringMachine__CircleScene__) */
d84039b47a826a880956ece3487293af7af48b0e
e51d009c6c6a1633c2c11ea4e89f289ea294ec7e
/xr2-dsgn/sources/xray/editor/controls/sources/mode_button.cpp
d5cb9064f04acc36f168c59d503cd2d7d989733f
[]
no_license
avmal0-Cor/xr2-dsgn
a0c726a4d54a2ac8147a36549bc79620fead0090
14e9203ee26be7a3cb5ca5da7056ecb53c558c72
refs/heads/master
2023-07-03T02:05:00.566892
2021-08-06T03:10:53
2021-08-06T03:10:53
389,939,196
3
2
null
null
null
null
UTF-8
C++
false
false
2,227
cpp
//////////////////////////////////////////////////////////////////////////// // Created : 13.01.2011 // Author : Evgeniy Obertyukh // Copyright (C) GSC Game World - 2011 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include "mode_button.h" namespace xray { namespace editor { namespace controls { Int32 mode_button::current_mode::get( ) { return m_mode; } void mode_button::current_mode::set( Int32 value ) { if( value >= modes->Count ) throw gcnew ArgumentException( "such mode does not exist in modes collection" ); m_context_menu_items[m_mode]->Checked = false; m_mode = value; m_context_menu_items[m_mode]->Checked = true; ImageIndex = value; super::Text = modes[m_mode]; } List<String^>^ mode_button::modes::get( ) { return m_modes; } void mode_button::modes::set( List<String^>^ value ) { m_modes = value; create_context_menu ( ); } String^ mode_button::current_mode_name::get( ) { return modes[ current_mode ]; } void mode_button::create_context_menu ( ) { m_context_menu_items = gcnew array<MenuItem^>( modes->Count ); for( int i = 0; i < m_modes->Count ; ++i ) { m_context_menu_items[i] = gcnew MenuItem( m_modes[i], gcnew EventHandler( this, &mode_button::context_item_click ) ); m_context_menu_items[i]->Tag = i; } m_context_menu_items[ 0 ]->Checked = true; m_context_menu = gcnew System::Windows::Forms::ContextMenu( m_context_menu_items ); } void mode_button::context_item_click ( Object^ sender, EventArgs^ e ) { current_mode = (Int32)((MenuItem^)sender)->Tag; Button::OnClick ( e ); } void mode_button::OnMouseUp ( MouseEventArgs^ e) { if( e->Button == System::Windows::Forms::MouseButtons::Right ) { m_context_menu->Show( this, e->Location ); } super::OnMouseUp( e ); } void mode_button::OnMouseClick ( MouseEventArgs^ e ) { if( e->Button == System::Windows::Forms::MouseButtons::Left ) { current_mode = ( current_mode + 1 ) % modes->Count; super::OnClick ( e ); return; }else super::OnMouseClick( e ); } void mode_button::OnClick ( EventArgs^ e ) { } } // namespace controls } // namespace editor } // namespace xray
2b67e4dc6865510c7aae6ccf80a24d5049aa95ad
b50a46306a4deff1cb2c59f85c65be29fd384c94
/src/LockedElement.cpp
361df95b8b2198a7672b778970f3835422a0847d
[]
no_license
ddalex/Lemon-Web-Server
5762d07a3c89552f1dac81087cc2e41cc31aa8c2
551d9a20b3c447c91863397c89f165b71ea87539
refs/heads/master
2020-04-22T22:16:37.498456
2012-11-08T11:01:02
2012-11-08T11:01:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
133
cpp
/* * LockedElement.cpp * * Created on: Apr 18, 2012 * Author: ddalex */ #include "LockedElement.h" namespace lemon { }
3b89355aae4b1749a07f9c136a90e181b2efaf46
72fa3bc7957bea62735eca9149107024557dab27
/Codes/SI_03_20190305/SI_03_20190305.ino
3d110430646cfee37a851dfff150042e0954477c
[]
no_license
brucetsao/eWind
6ff4b8a39b796d5cf8b23e0a330fa494af3827b4
9e7b8681a5ad57d6cd1bb6f45ba2d5ef4b961fbb
refs/heads/master
2021-06-09T21:12:04.760907
2021-05-26T10:07:10
2021-05-26T10:07:10
99,143,620
0
1
null
null
null
null
UTF-8
C++
false
false
11,238
ino
#include "crc16.h" #include <SPI.h> #include <WiFi101.h> #include "arduino_secrets.h" ///////please enter your sensitive data in the Secret tab/arduino_secrets.h char ssid[] = SECRET_SSID; // your network SSID (name) char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP) int keyIndex = 0; // your network key Index number (needed only for WEP) int status = WL_IDLE_STATUS; WiFiServer server(80); uint8_t outdata1[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x84, 0x0A } ; // crc16 for data1 is 840A uint8_t incomingdata1[7] ; uint8_t outdata2[] = {0x02, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x38 } ; // crc16 for data2 is C438 uint8_t incomingdata2[9] ; uint8_t outdata3[] = {0x03, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC5, 0xE9 } ; // crc16 for data3 is C5E9 uint8_t incomingdata3[9] ; String WindWay[] = {"北風","東北風","東風","東南風","南風","西南風","西風","西北風" } ; int Winddir=0 ; String WinddirName ="" ; double Windspeed =0, Temp=0, Humid =0 ; void setup() { initall() ; // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { Serial.println("WiFi shield not present"); while (true); // don't continue } // attempt to connect to WiFi network: while ( status != WL_CONNECTED) { WiFi.config(IPAddress(192, 168, 0, 220)) ; Serial.print("Attempting to connect to Network named: "); Serial.println(ssid); // print the network name (SSID); // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(4000); } server.begin(); // start the web server on port 80 printWiFiStatus(); // you're connected now, so print out the status } void loop() { digitalWrite(RSLED,HIGH) ; GetSensorData() ; ShowSensor() ; digitalWrite(RSLED,LOW) ; WiFiClient client = server.available(); // listen for incoming clients if (client) { // if you get a client, digitalWrite(AccessLED,HIGH) ; Serial.println("new client"); // print a message out the serial port String currentLine = ""; // make a String to hold incoming data from the client while (client.connected()) { // loop while the client's connected if (client.available()) { // if there's bytes to read from the client, char c = client.read(); // read a byte, then Serial.write(c); // print it out the serial monitor if (c == '\n') { // if the byte is a newline character // if the current line is blank, you got two newline characters in a row. // that's the end of the client HTTP request, so send a response: if (currentLine.length() == 0) { // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) // and a content-type so the client knows what's coming, then a blank line: client.println("HTTP/1.1 200 OK"); client.println(); client.print("<html>"); client.print("<head>"); client.println("<meta http-equiv='refresh' content='15'>"); client.println("<meta http-equiv='Content-Type' content-type:text/html; charset=utf-8>"); client.println("<title>吳厝國小風速、風向、溫溼度播報站</title>"); // client.println(); // client.println("<style type='text/css'>body,td,th {font-size: 72px;}"); // client.println(); client.print("</head>"); // the content of the HTTP response follows the header: client.print("<body>"); // client.print("Wind Speed:"); client.print(w1); client.print(Windspeed); client.print(w5); client.print("<br>"); // client.print(" m/s <br>"); client.print(w2); // client.print("Wind Direction:"); client.print(WinddirName); client.print("<br>"); client.print(w3); // client.print("Temperature"); client.print(Temp); client.print(w6); client.print("<br>"); client.print(w4); // client.print("Humidity:"); client.print(Humid); client.print(" % <br>"); client.print("</body>"); client.print("</html>"); // The HTTP response ends with another blank line: client.println(); // break out of the while loop: break; } else { // if you got a newline, then clear currentLine: currentLine = ""; } } else if (c != '\r') { // if you got anything else but a carriage return character, currentLine += c; // add it to the end of the currentLine } } } // close the connection: client.stop(); Serial.println("client disonnected"); digitalWrite(AccessLED,LOW) ; } delay(2000); } void GetSensorData() { Windspeed = GetWindSpeed() ; ClearBuffer() ; WinddirName = GetWindDir() ; ClearBuffer() ; GetDHT() ; ClearBuffer() ; } void ShowSensor() { IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); Serial.print("\n") ; Serial.print("Wind Speed is :(") ; Serial.print(Windspeed) ; Serial.print(" m/s )\n") ; Serial.print("Wind Direction is :(") ; Serial.print(WinddirName) ; Serial.print(")\n") ; Serial.print("Temperature is :(") ; Serial.print(Temp) ; Serial.print(")\n") ; Serial.print("Humidity is :(") ; Serial.print(Humid) ; Serial.print(")\n") ; } void printWiFiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID()); // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm"); // print where to go in a browser: Serial.print("To see this page in action, open a browser to http://"); Serial.println(ip); } //---------Speed---------- double GetWindSpeed() { sendSpeedQuery() ; delay(250) ; if (receiveSpeedQuery()) { if ( CompareCRC16(ModbusCRC16(incomingdata1,5),incomingdata1[6],incomingdata1[5]) ) { return ( ( (double)incomingdata1[3]*256+(double)incomingdata1[4] )/10) ; } else { return (-1) ; } } else { return (-2) ; } } void sendSpeedQuery() { Serial1.write(outdata1,8) ; } boolean receiveSpeedQuery() { boolean ret = false ; unsigned strtime = millis() ; while(true) { if ( (millis() - strtime) > 3000) { ret = false ; return ret ; } if (Serial1.available() >= 7) { Serial1.readBytes(incomingdata1, 7) ; ret = true ; return ret ; } } } //---------Win direction---------- String GetWindDir() { sendDirQuery() ; delay(250) ; int tmp = GetWindDirCheck() ; Serial.print("GetWindDir():(") ; Serial.print(tmp) ; Serial.print(")\n") ; if (tmp >= 0) { return WindWay[tmp] ; } else { return "Undefined" ; } } int CalcWind(uint8_t Hi, uint8_t Lo) { return ( Hi * 256+ Lo ) ; } int CalcWind1(uint8_t Hi, uint8_t Lo) { if ((Hi,7) == 1) { Hi = bitWrite(Hi,7,0) ; return ( Hi * 256+ Lo ) * (-1) ; } else { return ( Hi * 256+ Lo ) ; } } int GetWindDirCheck() { if (receiveDirQuery()) { if ( CompareCRC16(ModbusCRC16(incomingdata2,7),incomingdata2[8],incomingdata2[7]) ) { return (CalcWind(incomingdata2[3],incomingdata2[4])) ; } else { return (-1) ; } } else { return (-2) ; } } void sendDirQuery() { Serial1.write(outdata2,8) ; } boolean receiveDirQuery() { boolean ret = false ; unsigned strtime = millis() ; while(true) { if ( (millis() - strtime) > 3000) { ret = false ; return ret ; } if (Serial1.available() >= 9) { Serial1.readBytes(incomingdata2, 9) ; ret = true ; return ret ; } } } //---------DHT ---------- int GetDHT() { sendDHTQuery() ; delay(250) ; int tmp = GetDHTCheck() ; if (tmp == 1) { Temp = (double)(CalcWind1(incomingdata3[5],incomingdata3[6])/10) ; Humid = (double)(CalcWind(incomingdata3[3],incomingdata3[4])/10) ; } else { Serial.print("GetDHTCheck Error Code is :(") ; Serial.print(tmp) ; Serial.print(")\n") ; } return tmp ; } int GetDHTCheck() { if (receiveDHTQuery()) { if ( CompareCRC16(ModbusCRC16(incomingdata3,7),incomingdata3[8],incomingdata3[7]) ) { return 1 ; } else { return (-1) ; } } else { return (-2) ; } } void sendDHTQuery() { Serial1.write(outdata3,8) ; } boolean receiveDHTQuery() { boolean ret = false ; unsigned strtime = millis() ; while(true) { if ( (millis() - strtime) > 3000) { ret = false ; return ret ; } if (Serial1.available() >= 9) { Serial1.readBytes(incomingdata3, 9) ; ret = true ; return ret ; } } } //----------- void ClearBuffer() { unsigned char tt; if ( Serial1.available() >0) { while ( Serial1.available() >0) { tt = Serial1.read() ; } } } void initall() { Serial.begin(9600); // initialize serial communication Serial1.begin(9600); // initialize serial communication pinMode(PowerLED,OUTPUT) ; pinMode(RSLED,OUTPUT) ; pinMode(AccessLED,OUTPUT) ; digitalWrite(PowerLED,HIGH) ; digitalWrite(RSLED,LOW) ; digitalWrite(AccessLED,LOW) ; }
cbfd30d0993e25be22b0626d30347681b8f74204
6767be84c4ffa16f0c1930c7b8c34c28f2c96dd2
/spirit/fipa_acl.cpp
fbafb94a883a5e49972183ee9ca2c4468c36127e
[]
no_license
hdd-robot/gAgent
6d47b597c24c09c6bbc88572023c2decce99173e
b8c3703965fa8a1671ae985b1de127389d11c007
refs/heads/master
2022-01-16T12:11:04.105880
2019-05-18T09:46:44
2019-05-18T09:46:44
95,297,136
2
0
null
null
null
null
UTF-8
C++
false
false
4,014
cpp
#include <boost/spirit/include/qi.hpp> #include <boost/variant.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <string> #include <vector> #include <iostream> using namespace boost::spirit; typedef boost::variant<int, bool> int_or_bool; namespace fipa { struct AgentIdentifierDef{ string }; struct Message_parameterDef { std::string param; boost::variant<AgentIdentifierDef >; }; struct MessageTypeDef{ std::string msgType; }; struct message { std::string MessageType; std::vector<Message_parameterDef> message_parameter; }; template<typename Iterator, typename Skipper> struct fipa_acl_grammar: qi::grammar<Iterator, message(), Skipper> { fipa_acl_grammar() : fipa_acl_grammar::base_type { Message } { using qi::lit; using qi::print; using qi::int_; using qi::float_; using qi::char_; using qi::digit; /** * Lex */ Word = (print - lit('#')) >> *(print); StringFipa = (StringLiteral | ByteLengthEncodedString); StringLiteral = lit('\"') >> *((print - lit('\"') ) | (print - lit("\\\""))) >> lit('\"'); ByteLengthEncodedString = lit('#') >> +(digit) >> lit("\"") >> (*char_); Number = int_ | float_; URL = *(char_); DateTimeToken = -(Sign) >> Year >> Month >> Day >> lit('T') >> Hour >> Minute >> Second >> MilliSecond >> -(TypeDesignator); Year = digit >> digit >> digit >> digit; Month = digit >> digit; Day = digit >> digit; Hour = digit >> digit; Minute = digit >> digit; Second = digit >> digit; MilliSecond = digit >> digit >> digit; TypeDesignator = *(char_); Sign = (lit('-') | lit('+')); DateTimeFipa = DateTimeToken; UserDefinedParameter = Word ; Expression = WordFipa | StringFipa | Number | DateTimeFipa | '(' >> *(Expression) >> ')'; AgentIdentifier = '(' >> "agent-identifier" >> lit(":name") >> Word >> -(lit(":addresses") >> URLSequence) >> -(lit(":resolvers") >> AgentIdentifierSequence) >> *(UserDefinedParameter >> Expression) >> ')' ; AgentIdentifierSequence = '(' >> lit("sequence") >> *(AgentIdentifier) >> ')'; AgentIdentifierSet = '(' >> lit("set") >> *(AgentIdentifier) >> ')'; URLSequence = '(' >> lit("sequence") >> *(URL) >> ')'; /** * Lex */ Message = '(' >> MessageType >> *(MessageParameter) >> ')' ; MessageParameter = lit(":sender") >> AgentIdentifier | lit(":receiver") >> AgentIdentifierSet | lit(":content") >> *(char_) | lit(":reply-with") >> Expression | lit(":reply-by") >> DateTimeFipa | lit(":in-reply-to") >> Expression | lit(":reply-to") >> AgentIdentifierSet | lit(":language") >> Expression | lit(":encoding") >> Expression | lit(":ontology") >> Expression | lit(":protocol") >> Word | lit(":conversation-id") >> Expression | UserDefinedParameter >> Expression ; MessageType = lit("accept-proposal") | lit("agree") | lit("cancel") | lit("cfp") | lit("confirm") | lit("disconfirm") | lit("failure") | lit("inform") | lit("inform-if") | lit("inform-ref") | lit("not-understood") | lit("propagate") | lit("propose") | lit("proxy") | lit("query-ref") | lit("refuse") | lit("reject-proposal") | lit("request") | lit("request-when") | lit("request-whenever") | lit("subscribe"); } qi::rule<Iterator, message(), Skipper> Message; qi::rule<Iterator, message_parameter(), Skipper> MessageParameter; qi::rule<Iterator, std::string(), ascii::space_type> MessageType; // todo .... }; }
e3a96a0ed51ede3f0b34acc83f030678c6dc191a
4a905d68030de1c8efd41fd580e99dcad360ffe1
/NU group Easy contest-1/D - Ants.cpp
87f17dbabc37948b719469b1f80a7615d8e89e96
[]
no_license
AliAkberAakash/_CONTESTS_
e687d80c7a69fdb134be08f1755e1dd93c6292c1
e9fe96eda38dd107bdd025d955d69e4fe789704b
refs/heads/master
2021-01-22T22:56:51.355883
2018-05-01T19:31:41
2018-05-01T19:31:41
85,589,590
0
0
null
null
null
null
UTF-8
C++
false
false
849
cpp
#include<bits/stdc++.h> using namespace std; int main() { int t,length,pos,mid,x; int least,most,lowest; scanf("%d", &t); for(int i=0; i<t; i++) { most=INT_MAX; least=INT_MIN; lowest=INT_MIN; scanf("%d %d", &length, &pos); mid=(length/2); for(int j=0; j<pos; j++) { scanf("%d", &x); if(x<most) most=x; else if(x>lowest) lowest=x; if(x<=mid && x>least) { least=x; } if(x>mid && (length-x)>least) { least=x; } } printf("%d ", length-least); if((length-most)>(lowest)) printf("%d\n", length-most); else printf("%d\n", lowest); } return 0; }
b6340b98a7e5f2df7d34da57722253ca9827ea5b
665443052fa3c17f94c945f08b6378016d5a1dae
/0152/src/emu/bus/adam/exp.h
42bb1f230a53f9f7d00f1024db8787568d595a28
[]
no_license
dezi/mame-libretro-odroid
a6f3e0fd87e00fe8beda936f1cd3cf2fe508fcf0
31b588c088928f967b9fb9cf903b7a3f18a91eaa
refs/heads/master
2020-04-18T07:49:09.588326
2014-02-11T14:27:40
2014-02-11T14:27:40
16,698,177
2
0
null
null
null
null
UTF-8
C++
false
false
4,692
h
// license:BSD-3-Clause // copyright-holders:Curt Coder /********************************************************************** Coleco Adam Expansion Port emulation Copyright MESS Team. Visit http://mamedev.org for licensing and usage restrictions. **********************************************************************/ #pragma once #ifndef __ADAM_EXPANSION_SLOT__ #define __ADAM_EXPANSION_SLOT__ #include "emu.h" //************************************************************************** // CONSTANTS //************************************************************************** #define ADAM_LEFT_EXPANSION_SLOT_TAG "slot1" #define ADAM_CENTER_EXPANSION_SLOT_TAG "slot2" #define ADAM_RIGHT_EXPANSION_SLOT_TAG "slot3" //************************************************************************** // INTERFACE CONFIGURATION MACROS //************************************************************************** #define ADAM_EXPANSION_SLOT_INTERFACE(_name) \ const adam_expansion_slot_interface (_name) = #define MCFG_ADAM_EXPANSION_SLOT_ADD(_tag, _clock, _config, _slot_intf, _def_slot) \ MCFG_DEVICE_ADD(_tag, ADAM_EXPANSION_SLOT, _clock) \ MCFG_DEVICE_CONFIG(_config) \ MCFG_DEVICE_SLOT_INTERFACE(_slot_intf, _def_slot, false) //************************************************************************** // TYPE DEFINITIONS //************************************************************************** // ======================> adam_expansion_slot_interface struct adam_expansion_slot_interface { devcb_write_line m_out_int_cb; }; // ======================> adam_expansion_slot_device class device_adam_expansion_slot_card_interface; class adam_expansion_slot_device : public device_t, public adam_expansion_slot_interface, public device_slot_interface, public device_image_interface { public: // construction/destruction adam_expansion_slot_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock); virtual ~adam_expansion_slot_device(); // computer interface UINT8 bd_r(address_space &space, offs_t offset, UINT8 data, int bmreq, int biorq, int aux_rom_cs, int cas1, int cas2); void bd_w(address_space &space, offs_t offset, UINT8 data, int bmreq, int biorq, int aux_rom_cs, int cas1, int cas2); // cartridge interface DECLARE_WRITE_LINE_MEMBER( int_w ); protected: // device-level overrides virtual void device_config_complete(); virtual void device_start(); virtual void device_reset(); // image-level overrides virtual bool call_load(); virtual bool call_softlist_load(char *swlist, char *swname, rom_entry *start_entry); virtual iodevice_t image_type() const { return IO_CARTSLOT; } virtual bool is_readable() const { return 1; } virtual bool is_writeable() const { return 0; } virtual bool is_creatable() const { return 0; } virtual bool must_be_loaded() const { return 0; } virtual bool is_reset_on_load() const { return 1; } virtual const char *image_interface() const { return "adam_rom"; } virtual const char *file_extensions() const { return "bin,rom"; } virtual const option_guide *create_option_guide() const { return NULL; } // slot interface overrides virtual const char * get_default_card_software(const machine_config &config, emu_options &options); devcb_resolved_write_line m_out_int_func; device_adam_expansion_slot_card_interface *m_cart; }; // ======================> device_adam_expansion_slot_card_interface class device_adam_expansion_slot_card_interface : public device_slot_card_interface { friend class adam_expansion_slot_device; public: // construction/destruction device_adam_expansion_slot_card_interface(const machine_config &mconfig, device_t &device); virtual ~device_adam_expansion_slot_card_interface(); protected: // initialization virtual UINT8* adam_rom_pointer(running_machine &machine, size_t size); virtual UINT8* adam_ram_pointer(running_machine &machine, size_t size); // runtime virtual UINT8 adam_bd_r(address_space &space, offs_t offset, UINT8 data, int bmreq, int biorq, int aux_rom_cs, int cas1, int cas2) { return data; } virtual void adam_bd_w(address_space &space, offs_t offset, UINT8 data, int bmreq, int biorq, int aux_rom_cs, int cas1, int cas2) { } adam_expansion_slot_device *m_slot; UINT8 *m_rom; UINT8 *m_ram; size_t m_rom_mask; size_t m_ram_mask; }; // device type definition extern const device_type ADAM_EXPANSION_SLOT; // slot devices #include "adamlink.h" #include "ide.h" #include "ram.h" SLOT_INTERFACE_EXTERN( adam_slot1_devices ); SLOT_INTERFACE_EXTERN( adam_slot2_devices ); SLOT_INTERFACE_EXTERN( adam_slot3_devices ); #endif
c823178580e382d8d17dd69564afabaaab61165f
58e8a2a6f4db3aed5968e65e168b4e41031a7d6d
/src/Express/HTTP/HTTPProtocol.cpp
2242cf6042e05581c84978c2f75ee895ab71ef2e
[ "MIT" ]
permissive
Loki-Astari/ThorsNisse
4471f67c55bf9678cab8360b292835d3cf1d6ddc
ec497863598f594b64b467c982dbbc1948b3879b
refs/heads/master
2023-08-17T20:46:42.486246
2023-08-08T07:33:14
2023-08-08T07:33:14
96,054,325
6
1
null
null
null
null
UTF-8
C++
false
false
2,823
cpp
#include "HTTPProtocol.h" #include "ThorsSocket/SocketStream.h" using namespace ThorsAnvil::Nisse::Protocol::HTTP; class DevNullStreamBuf: public std::streambuf { private: typedef std::streambuf::traits_type traits; typedef traits::int_type int_type; typedef traits::char_type char_type; std::size_t written; protected: virtual std::streamsize xsputn(char_type const* /*s*/,std::streamsize count) override { written += count; return count; } virtual std::streampos seekoff(std::streamoff /*off*/, std::ios_base::seekdir /*way*/, std::ios_base::openmode which = std::ios_base::in | std::ios_base::out) override { ((void)which); return written; } public: DevNullStreamBuf() : written(0) {} }; ReadRequestHandler::ReadRequestHandler(Core::Service::Server& parent, ThorsSocket::DataSocket&& socket, Binder const& binder) : HandlerSuspendable(parent, std::move(socket), EV_READ) , binder(binder) , flusher(nullptr) /*MIY TODO remove*/, running(false) {} /*MIY TODO Remove*/struct SetRunning { bool& running; SetRunning(bool& running) : running(running) { running = true; } ~SetRunning() { running = false; } }; bool ReadRequestHandler::eventActivateNonBlocking() { /*MIY TODO remove*/SetRunning setRunning(running); HttpScanner scanner; std::vector<char> buffer(bufferLen); while (!scanner.data.messageComplete) { bool more; std::size_t recved; std::tie(more, recved) = stream.getMessageData(&buffer[0], bufferLen, 0); scanner.scan(&buffer[0], recved); if (scanner.data.messageComplete || !more) { break; } suspend(EV_READ); } ThorsSocket::IOSocketStream input(stream, [&parent = *this](){parent.suspend(EV_READ);}, [](){}, std::move(buffer), scanner.data.bodyBegin, scanner.data.bodyEnd); ThorsSocket::IOSocketStream output(stream, [&parent = *this](){parent.suspend(EV_WRITE);}, [&parent = *this](){parent.flushing();}); DevNullStreamBuf devNullBuffer; if (scanner.data.method == Method::Head) { output.rdbuf(&devNullBuffer); } URI const uri(scanner.data.headers.get("Host"), std::move(scanner.data.uri)); Action const& action(binder.find(scanner.data.method, uri.host, uri.path)); Request request(scanner.data.method, URI(std::move(uri)), scanner.data.headers, input); Response response(*this, stream, output); action(request, response); return true; }
dae5babc86409cb3a4777412315842f9a64bff37
28d86647f98f050e9b0757dc6e6dc2b268e73fb7
/11403/11403.cpp
7545f895c41a8bd6c1a76e912bf427c333ec6f88
[]
no_license
Park52/BaekJoon
5b521d3996c2ce95f5445e69bf96443ce2792802
03389f021c11d77afa4587ade9acaf7ff5e31f07
refs/heads/master
2020-06-03T19:37:55.256955
2019-12-17T00:47:10
2019-12-17T00:47:10
191,703,348
0
0
null
null
null
null
UTF-8
C++
false
false
789
cpp
#include <iostream> #include <queue> #include <cstdio> #include <cstring> using namespace std; int N; int nMap[101][101]; int nAns[101][101]; int nChecked[101][101]; queue<int> q; void BFS(int y) { q.push(y); while (!q.empty()) { int cy = q.front(); q.pop(); for (int i = 1; i <= N; i++) { if (nMap[cy][i] == 1 && nChecked[cy][i] == 0) { nAns[y][i] = 1; nChecked[cy][i] = 1; q.push(i); } } } } int main(void) { cin >> N; for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { cin >> nMap[i][j]; } } for (int y = 1; y <= N; y++) { BFS(y); memset(nChecked, 0, sizeof(nChecked)); } for (int i = 1; i <= N; i++) { for (int j = 1; j <= N; j++) { cout << nAns[i][j] << " "; } cout << endl; } return 0; }
823655ab1ffc4c24529f8222c1b8878539c5bf2e
48e197b8f69f2a8b3765e0993d6c66a5823f3840
/src/qt/signverifymessagedialog.cpp
e36f03f3dfed42a075660fe993ab5c69aa1fd77f
[ "MIT" ]
permissive
SorachanCoin/SorachanCoin-qt
d82bb3a2e3ba0b2c301b2ac9aa16d1f0b8b07cfe
f7acc67c633d2f4f1dddf67424986f485a280ec2
refs/heads/master
2022-11-21T15:10:44.261662
2020-07-09T09:44:05
2020-07-09T09:44:05
278,484,779
0
0
MIT
2020-07-09T22:35:26
2020-07-09T22:35:26
null
UTF-8
C++
false
false
9,180
cpp
#include "signverifymessagedialog.h" #include "ui_signverifymessagedialog.h" #include "addressbookpage.h" #include "base58.h" #include "guiutil.h" #include "dialogwindowflags.h" #include "init.h" #include "main.h" #include "optionsmodel.h" #include "walletmodel.h" #include "wallet.h" #include <string> #include <vector> #include <QClipboard> #include <QKeyEvent> SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) : QWidget(parent, DIALOGWINDOWHINTS), ui(new Ui::SignVerifyMessageDialog), model(0) { if(! ui){ throw std::runtime_error("SignVerifyMessageDialog Failed to allocate memory."); } ui->setupUi(this); #if (QT_VERSION >= 0x040700) /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addressIn_SM->setPlaceholderText(tr("Enter a SorachanCoin address (e.g. SUEgQX5BMKamE3eZYJD7wGfV1T3EuytBak)")); ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature")); ui->addressIn_VM->setPlaceholderText(tr("Enter a SorachanCoin address (e.g. SUEgQX5BMKamE3eZYJD7wGfV1T3EuytBak)")); ui->signatureIn_VM->setPlaceholderText(tr("Enter SorachanCoin signature")); #endif GUIUtil::setupAddressWidget(ui->addressIn_SM, this); GUIUtil::setupAddressWidget(ui->addressIn_VM, this); ui->addressIn_SM->installEventFilter(this); ui->messageIn_SM->installEventFilter(this); ui->signatureOut_SM->installEventFilter(this); ui->addressIn_VM->installEventFilter(this); ui->messageIn_VM->installEventFilter(this); ui->signatureIn_VM->installEventFilter(this); ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont()); ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont()); } SignVerifyMessageDialog::~SignVerifyMessageDialog() { delete ui; } void SignVerifyMessageDialog::setModel(WalletModel *model) { this->model = model; } void SignVerifyMessageDialog::setAddress_SM(QString address) { ui->addressIn_SM->setText(address); ui->messageIn_SM->setFocus(); } void SignVerifyMessageDialog::setAddress_VM(QString address) { ui->addressIn_VM->setText(address); ui->messageIn_VM->setFocus(); } void SignVerifyMessageDialog::showTab_SM(bool fShow) { ui->tabWidget->setCurrentIndex(0); if (fShow) { this->show(); } } void SignVerifyMessageDialog::showTab_VM(bool fShow) { ui->tabWidget->setCurrentIndex(1); if (fShow) { this->show(); } } void SignVerifyMessageDialog::on_addressBookButton_SM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_SM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_pasteButton_SM_clicked() { setAddress_SM(QApplication::clipboard()->text()); } void SignVerifyMessageDialog::on_signMessageButton_SM_clicked() { /* Clear old signature to ensure users don't get confused on error with an old signature displayed */ ui->signatureOut_SM->clear(); CBitcoinAddress addr(ui->addressIn_SM->text().toStdString()); if (! addr.IsValid()) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (! addr.GetKeyID(keyID)) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if (! ctx.isValid()) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled.")); return; } CKey key; if (! entry::pwalletMain->GetKey(keyID, key)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Private key for the entered address is not available.")); return; } CDataStream ss(SER_GETHASH, 0); ss << block_info::strMessageMagic; ss << ui->messageIn_SM->document()->toPlainText().toStdString(); std::vector<unsigned char> vchSig; if (! key.SignCompact(hash_basis::Hash(ss.begin(), ss.end()), vchSig)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>")); return; } ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>")); ui->signatureOut_SM->setText(QString::fromStdString(base64::EncodeBase64(&vchSig[0], vchSig.size()))); } void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked() { QApplication::clipboard()->setText(ui->signatureOut_SM->text()); } void SignVerifyMessageDialog::on_clearButton_SM_clicked() { ui->addressIn_SM->clear(); ui->messageIn_SM->clear(); ui->signatureOut_SM->clear(); ui->statusLabel_SM->clear(); ui->addressIn_SM->setFocus(); } void SignVerifyMessageDialog::on_addressBookButton_VM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_VM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked() { CBitcoinAddress addr(ui->addressIn_VM->text().toStdString()); if (! addr.IsValid()) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (! addr.GetKeyID(keyID)) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } bool fInvalid = false; std::vector<unsigned char> vchSig = base64::DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid); if (fInvalid) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again.")); return; } CDataStream ss(SER_GETHASH, 0); ss << block_info::strMessageMagic; ss << ui->messageIn_VM->document()->toPlainText().toStdString(); CPubKey key; if (! key.SetCompactSignature(hash_basis::Hash(ss.begin(), ss.end()), vchSig)) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again.")); return; } if (!(CBitcoinAddress(key.GetID()) == addr)) { ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>")); return; } ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>")); } void SignVerifyMessageDialog::on_clearButton_VM_clicked() { ui->addressIn_VM->clear(); ui->signatureIn_VM->clear(); ui->messageIn_VM->clear(); ui->statusLabel_VM->clear(); ui->addressIn_VM->setFocus(); } bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn) { if (ui->tabWidget->currentIndex() == 0) { /* Clear status message on focus change */ ui->statusLabel_SM->clear(); /* Select generated signature */ if (object == ui->signatureOut_SM) { ui->signatureOut_SM->selectAll(); return true; } } else if (ui->tabWidget->currentIndex() == 1) { /* Clear status message on focus change */ ui->statusLabel_VM->clear(); } } return QWidget::eventFilter(object, event); } void SignVerifyMessageDialog::keyPressEvent(QKeyEvent *event) { #ifdef ANDROID if(event->key() == Qt::Key_Back) { close(); } #else if(event->key() == Qt::Key_Escape) { close(); } #endif }
64c1c318032a9df85d39ef803c16e2284adb0403
62d5a234396840e9f222a8cb160cca22686525e9
/LUA/LUA/LuaMacros.h
e780db4c08610d7f75c130ca24a97ee998c45aff
[]
no_license
marty1885/LuaWrapperCpp
76872dee66a7883cf87f53912c9ee0009e620d10
4e8aa57c14daf1ffc5514deb222518851e428023
refs/heads/master
2020-03-27T06:58:36.224483
2018-08-26T05:17:48
2018-08-26T05:17:48
146,152,619
0
0
null
2018-08-26T04:58:32
2018-08-26T04:58:32
null
UTF-8
C++
false
false
2,422
h
#ifndef LUA_MACROS_H #define LUA_MACROS_H //============================================================================================= // Compilation defines //Enable more type checking when getting pointer from Lua //However, this is a bit slower then unsafe version without checks #define SAFE_PTR_CHECKS 1 //String class used in Lua #define LUA_STRING std::string //#define LUA_STRING MyStringAnsi //inline call #ifdef _MSC_VER #define LUA_INLINE __forceinline #else #define LUA_INLINE inline __attribute__((always_inline)) #endif //FORCE_INLINE //============================================================================================= // Some helper DEFINEs //Macro for registration of overloaded methods #define CLASS_METHOD_OVERLOAD(ClassName, MethodName, ...) \ LuaCallbacks::function<decltype(ClassOverloadMethod<ClassName, ##__VA_ARGS__>::get(&ClassName::MethodName)), &ClassName::MethodName> //Macro for registration of class methods #define CLASS_METHOD(ClassName, MethodName) \ LuaCallbacks::function<decltype(&ClassName::MethodName), &ClassName::MethodName> //Macro for class attribute registration #define CLASS_ATTRIBUTE(ClassName, AttrName) \ LuaCallbacks::getSetAttr<decltype(ClassName::AttrName), ClassName, &ClassName::AttrName> //Macro for simple method registration #define METHOD(MethodName) \ LuaCallbacks::function<decltype(&MethodName), &MethodName> #define LUA_SAFE_DELETE(a) {if (a != nullptr) { delete a; a = nullptr; }}; #define LUA_SAFE_DELETE_ARRAY(a) {if (a != nullptr) { delete[] a; a = nullptr; }}; #define INTEGRAL_SIGNED(T) typename = typename std::enable_if <std::is_integral<T>::value>::type, \ typename = typename std::enable_if <std::is_signed<T>::value == true>::type #define INTEGRAL_SIGNED_IMPL(T) typename, typename #define INTEGRAL_UNSIGNED(T) typename = typename std::enable_if <std::is_integral<T>::value>::type, \ typename = typename std::enable_if <std::is_signed<T>::value == false>::type, \ typename = void #define INTEGRAL_UNSIGNED_IMPL(T) typename, typename, typename //============================================================================================= // Debug logging #ifndef LUA_LOG_ERROR #define LUA_LOG_ERROR(...) printf(__VA_ARGS__) #endif #ifndef LUA_LOG_WARNING #define LUA_LOG_WARNING(...) printf(__VA_ARGS__) #endif #ifndef LUA_LOG_INFO #define LUA_LOG_INFO(...) printf(__VA_ARGS__) #endif #endif
676e436d74be9acc96d6a1cb9a7b9d9f79156e16
7b34793f270945fb20c03d6bd3e2ced13b59f079
/14 - Draw Sort Order/src/C_Sprite.hpp
cf192bbeb088199e73c6f2d475f232dc764fea48
[ "MIT" ]
permissive
thatgamesguy/that_game_engine
3a1c8fa57d5582ec19bcef111552f12eb669be94
90c80ebb4e890b9e4684ec87841b4bf4e446a3d1
refs/heads/master
2021-12-31T07:11:15.765836
2021-12-10T10:24:26
2021-12-10T10:24:26
120,003,746
88
34
MIT
2021-04-01T16:23:40
2018-02-02T16:21:06
C++
UTF-8
C++
false
false
788
hpp
#ifndef C_Sprite_hpp #define C_Sprite_hpp #include "Component.hpp" #include "C_Transform.hpp" #include "ResourceAllocator.hpp" #include "C_Drawable.hpp" class C_Sprite : public Component, public C_Drawable { public: C_Sprite(Object* owner); void SetTextureAllocator(ResourceAllocator<sf::Texture>* allocator); void Load(int id); void Load(const std::string& filePath); void LateUpdate(float deltaTime) override; void Draw(Window& window) override; void SetTextureRect(int x, int y, int width, int height); void SetTextureRect(const sf::IntRect& rect); void SetScale(float x, float y); private: ResourceAllocator<sf::Texture>* allocator; sf::Sprite sprite; int currentTextureID; }; #endif /* C_Sprite_hpp */
99b49fefc2fba86e29302ba5e11711c5257dbe5f
879681c994f1ca9c8d2c905a4e5064997ad25a27
/root-2.3.0/run/MicroChannelFOAM/TurbulenceMicroChannel/0.318/alpha.water
164221032af4a157af048052b3458f7e9ddf796e
[]
no_license
MizuhaWatanabe/OpenFOAM-2.3.0-with-Ubuntu
3828272d989d45fb020e83f8426b849e75560c62
daeb870be81275e8a81f5cbac4ca1906a9bc69c0
refs/heads/master
2020-05-17T16:36:41.848261
2015-04-18T09:29:48
2015-04-18T09:29:48
34,159,882
1
0
null
null
null
null
UTF-8
C++
false
false
4,676
water
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.3.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.318"; object alpha.water; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; internalField nonuniform List<scalar> 545 ( 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 1 1 0.999987 0.999957 0.999938 0.999934 0.999936 0.999939 0.999941 0.999941 0.999941 0.99994 0.999939 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 1 1 0.999316 0.997077 0.994151 0.994221 0.994881 0.995376 0.995681 0.995777 0.995725 0.995599 0.995468 0.995368 0.995317 0.995306 0.995318 0.99534 0.995363 0.995376 0.995382 0.99538 0.995376 0.995368 0.995358 0.995347 0.995341 0.995335 0.995334 0.995332 0.995335 0.995336 0.995335 0.99533 0.995321 0.995307 0.9953 0.995289 0.995286 0.995283 0.995285 0.995289 0.995297 0.995301 0.995304 0.178104 0.46813 0.862502 0.47498 0.419736 0.419725 0.419763 0.703994 0.995795 0.794202 0.545673 0.534226 0.531285 0.5327 0.594338 0.970227 0.752506 0.509263 0.537546 0.52798 0.530941 0.527634 0.790358 0.985696 0.864401 0.436896 0.448716 0.522864 0.496286 0.50179 0.523935 0.85454 0.995514 0.995537 0.856971 0.375233 0.214726 0.254242 0.330441 0.290243 0.29045 0.384815 0.815662 0.976395 0.940277 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0.999316 0.997074 0.994143 0.994228 0.994884 0.995387 0.995691 0.995788 0.995732 0.995606 0.995469 0.995368 0.995313 0.9953 0.99531 0.995332 0.995351 0.995366 0.99537 0.995372 0.995367 0.995361 0.99535 0.995341 0.995332 0.995328 0.995323 0.995324 0.995323 0.995325 0.995322 0.995316 0.995303 0.99529 0.995276 0.995268 0.995258 0.995259 0.995257 0.995267 0.995275 0.995282 0.995283 1 1 0.999987 0.999957 0.999938 0.999934 0.999936 0.999939 0.999941 0.999941 0.999941 0.99994 0.999939 0.999938 0.999938 0.999937 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 0.999938 1 1 1 1 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 0.999999 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ) ; boundaryField { AirInlet { type fixedValue; value uniform 0; } WaterInlet { type fixedValue; value uniform 1; } ChannelWall { type zeroGradient; } Outlet { type inletOutlet; inletValue uniform 0; value nonuniform List<scalar> 11 ( 1 1 0.999999 0.999938 0.995304 0.940277 0.995283 0.999938 0.999999 1 1 ) ; } FrontAndBack { type empty; } } // ************************************************************************* //
ba3cce8a449e8b3cc800bd8eaa32c9c4e8512400
edabddd23276d9a40c7f8bf6d6986fb451adbc34
/Archive/Multi-University Training Contest/2017/5th/J.cpp
91e1f3cc4bb889000e88f8334f6e8607993bcb1a
[]
no_license
Akatsukis/ACM_Training
b70f49435b8c7bada6b52366e4a6a8010ff80ef9
0503f50bc033ba01c7993de346ac241b0d9d5625
refs/heads/master
2021-06-06T09:00:15.665775
2019-12-24T20:13:14
2019-12-24T20:13:14
103,283,338
2
0
null
null
null
null
UTF-8
C++
false
false
1,783
cpp
#include <iostream> #include <cstdio> #include <cctype> #include <algorithm> #include <cstring> #include <string> #include <cmath> #include <vector> #include <set> #include <stack> #include <sstream> #include <queue> #include <map> #include <functional> #include <bitset> //#include <unordered_map> //#include <unordered_set> using namespace std; #define pb push_back #define mk make_pair #define ll long long #define ull unsigned long long #define pii pair<int, int> #define fi first #define se second #define ALL(A) A.begin(),A.end() #define sc(x) scanf("%d", &x) #define pr(x) printf(#x":%d\n", x) #define fastio ios::sync_with_stdio(0), cin.tie(0) #define frein freopen("in.txt", "r", stdin) #define freout freopen("out.txt", "w", stdout) #define debug cout<<"???"<<endl const ll mod = 1e9+7; const int INF = 2e9+5; //int INF = 0x3f3f3f3f; const double eps = 1e-6; template<class T> T gcd(T a, T b){if(!b)return a;return gcd(b,a%b);} const int maxm = 1e4+10; ll b[maxm]; ll dp[maxm]; ll n, m; vector<int> ans; int main() { int T; sc(T); while(T--){ ans.clear(); memset(dp, 0, sizeof(dp)); dp[0] = 1; scanf("%lld%lld", &n, &m); for(int i = 0; i <= m; i++){ scanf("%lld", &b[i]); } for(int i = 1; i <= m; i++){ ll cur = b[i] - dp[i]; for(int j = 0; j < cur; j++)ans.pb(i); for(int j = 0; j < cur; j++){ for(int k = m-i; k >= 0; k--){ dp[k+i] += dp[k]; //printf("dp[%d+%d]+=dp[%d]=%d\n", k, i, k, dp[k+i]); } } } for(int i = 0; i < (int)ans.size(); i++){ printf("%d%c", ans[i], i == (int)ans.size() - 1 ? '\n' : ' '); } } return 0; }
c3b9a546ed719a7861885d8e7fdbd3089b92b72f
87a1b702904a711af2546db81f2fbc26ad7dd954
/2048/Crad.h
3e73c976b3b77c0fc5365b80d71c541dd7febf0d
[]
no_license
Candypz/cocos2dxTest
b98f6435adf1f0af8ec04ca85fe246b5c4a05aca
2f752cdab88c8a6ae3d6bb189fb4d775ccd83f29
refs/heads/master
2020-04-06T03:42:00.177140
2015-05-02T17:07:43
2015-05-02T17:07:43
34,954,802
0
0
null
null
null
null
GB18030
C++
false
false
492
h
#pragma once #include "cocos2d.h" USING_NS_CC; class Card :public Sprite{ public: static Card *createCardSprite(int number,int wigth,int height,float x,float y); virtual bool init(); CREATE_FUNC(Card); //获取数字 int getNumber(); //设置数字 void setNumber(int num); private: //显示数字 int m_number; void eneyInit(int number, int wigth, int height, float x, float y); //显示数字的控件 Label *labelNumber; //显示背景 LayerColor *layerColorBG; };
9fe0e4c05b36e51adeff27b99d5309d09e008324
c650db386420adbfe1822fb448ca7b0dc67d3709
/src/choicebutton.cpp
b803cc3f08e4cc7156c2561e2770cb7194483db6
[]
no_license
m-irigoyen/pages
63b1daca8bc2a5312b976ca04ecab1cf07180fe2
aa3a5392475abfa45b9a91b4af91a6026636f668
refs/heads/master
2021-07-09T17:39:58.898016
2017-10-08T21:56:57
2017-10-08T21:56:57
106,085,175
0
0
null
null
null
null
UTF-8
C++
false
false
1,310
cpp
#include "choicebutton.hpp" #include <sfmlutils/colorutils.hpp> namespace pages { ChoiceButton::ChoiceButton() : sfmltemplate::ShapeShifterPushButtonNode(Flags::SHAPE | Flags::TEXT, Shape::Rectangle) , hoverColor_(0.7f, 0.7f, 0.7f, 0.2f) , restColor_(0.8f, 0.8f, 0.8f, 0.2f) , selectedColor_(0.9f, 0.9f, 0.9f, 0.2f) , hoverOutlineColor_(0.f, 0.f, 1.f, 1.f) , restOutlineColor_(0.5f, 0.5f, 0.5f, 1.f) , selectedOutlineColor_(1.f, 0.f, 0.f, 1.f) { shape_->setFillColor(sfmlutils::toSfColor(restColor_)); shape_->setOutlineColor(sfmlutils::toSfColor(restOutlineColor_)); shape_->setOutlineThickness(1.f); text_->setCharacterSize(16); setMargin(5.f, 5.f); } void ChoiceButton::onEnableChanged() { } void ChoiceButton::onStatusChanged(Status oldStatus) { switch (status_) { case Status::Hovered: shape_->setFillColor(sfmlutils::toSfColor(hoverColor_)); shape_->setOutlineColor(sfmlutils::toSfColor(hoverOutlineColor_)); break; case Status::Rest: shape_->setFillColor(sfmlutils::toSfColor(restColor_)); shape_->setOutlineColor(sfmlutils::toSfColor(restOutlineColor_)); break; case Status::Selected: shape_->setFillColor(sfmlutils::toSfColor(selectedColor_)); shape_->setOutlineColor(sfmlutils::toSfColor(selectedOutlineColor_)); break; } } }
fa343fe685a970b1f571a72568a73b6fe4d329fa
ab7a31ccbd1303aa09b35c4b597544d573f1a510
/src/automatiny.cpp
bed02a5c8b91ce3c2c90a6b69f331d90c1deb7e0
[]
no_license
peppergeist/automatiny
b827d90fcf7af42603a24cd4cac09238eadc2b47
729cc17be19ff6797b1273ff8aad28cafaa6aabc
refs/heads/master
2020-03-17T22:29:39.881403
2018-05-19T23:57:23
2018-05-19T23:57:23
134,005,872
0
0
null
null
null
null
UTF-8
C++
false
false
162
cpp
/** * \file automatiny.cpp */ #include <stdio.h> int main(int argc, char *argv[]) { printf("Hello world!"); printf("\n"); return 0; }
c0494048e8133735673b367c5884a975339bffa3
c7d4d31e26e4ee4a13f21050fc8a96005b1a2a24
/ABC058/C.cpp
8a417d1e07842394d87a6096fd573829348d07d8
[]
no_license
motacapla/ProgrammingContest-Atcoder-etc-
c26840bf435159ed46c44b3ec37f0ad6e4a722e5
a647b9656b1656ce7da73f8e66a54d353765717b
refs/heads/master
2021-10-28T06:25:40.276550
2021-10-23T11:29:37
2021-10-23T11:29:37
141,571,371
0
0
null
null
null
null
UTF-8
C++
false
false
1,634
cpp
//#include <bits/stdc++.h> #include <iostream> #include <complex> #include <sstream> #include <string> #include <algorithm> #include <deque> #include <list> #include <map> #include <numeric> #include <queue> #include <vector> #include <set> #include <limits> #include <cstdio> #include <cctype> #include <cmath> #include <cstring> #include <cstdlib> #include <ctime> #include <climits> #define REP(i, n) for(int i = 0; i < (int)(n); i++) #define FOR(i, j, k) for(int i = (int)(j); i < (int)(k); ++i) #define ROF(i, j, k) for(int i = (int)(j); i >= (int)(k); --i) #define FORLL(i, n, m) for(long long i = n; i < (long long)(m); i++) #define SORT(v, n) sort(v, v+n) #define REVERSE(v) reverse((v).begin(), (v).end()) using namespace std; using ll = long long; const ll MOD=1000000007LL; typedef pair<int, int> P; ll ADD(ll x, ll y) { return (x+y) % MOD; } ll SUB(ll x, ll y) { return (x-y+MOD) % MOD; } ll MUL(ll x, ll y) { return x*y % MOD; } ll POW(ll x, ll e) { ll v=1; for(; e; x=MUL(x,x), e>>=1) if (e&1) v = MUL(v,x); return v; } ll DIV(ll x, ll y) { /*assert(y%MOD!=0);*/ return MUL(x, POW(y, MOD-2)); } int main(void){ int n; string s; cin >> n; int v[n][30] = {}; REP(i, n){ cin >> s; REP(j, s.size()){ int itmp = (int)s[j]-97; v[i][itmp]++; } } /* REP(i, n){ REP(j, 26) cout << "v :i,j " << v[i][j] << endl; } */ int res[30] = {}; REP(i, 30) res[i] = INT_MAX; REP(i, n) REP(j, 26) if(v[i][j] < res[j]) res[j] = v[i][j]; REP(i, 26) { while(res[i] > 0) { cout << (char)('a'+ i); res[i]--; } } cout << endl; return 0; }
6020511a056d06afa904db66c57c771b9fcac55d
59c3ca6bd5a98e792860e62d1f9961814d6c3282
/Week_01/G20200343040109/leetcode_189_0109.cpp
7121cad75a7105ca87bd9d73b4b384f2fa47c132
[]
no_license
hongxchen/algorithm007-class01
241991b7112d000da7fe9e255189b766349162fd
24b0f94d37220b434aae7e4e7df814246ececf35
refs/heads/master
2021-04-02T11:21:24.248439
2020-06-02T06:55:08
2020-06-02T06:55:08
248,269,605
0
0
null
2020-03-18T15:26:58
2020-03-18T15:26:57
null
UTF-8
C++
false
false
1,436
cpp
//leetcode_189_0109.cpp //旋转数组 #include <iostream> #include <vector> #include <algorithm> void rotate(std::vector<int>& nums, int k) { int nsize = nums.size(); //方法1:一个个移动,时间复杂度O(n),空间复杂度O(1) if(k % nsize) { int nMove = k % nsize; for(int n = 0; n < nMove; ++n) { int nEnd = nums[nsize - 1]; nums.pop_back(); nums.insert(nums.begin(), nEnd); } } //方法2:通过反转函数reverse,时间复杂度为O(n),空间复杂度为O(1) } void rotate2(std::vector<int>& nums, int k) { int nsize = nums.size(); int nMove = k % nsize; //方法2:通过反转函数reverse,时间复杂度为O(1),空间复杂度为O(1) std::reverse(&nums[0], &nums[nsize - nMove]); std::reverse(&nums[nsize - nMove], &nums[nsize]); std::reverse(&nums[0], &nums[nsize]); } int main(void) { std::vector<int> vec; vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); vec.push_back(6); vec.push_back(7); int k = 3; //rotate(vec, k); rotate2(vec, k); for(unsigned int i = 0; i < vec.size(); ++i) { std::cout<<vec.at(i)<<" "; } std::cout<<std::endl; char ar; std::cin>>ar; return 0; }
3747000f073e75409a98c4eb94b77fffe76ee0f6
baeecdbb529e81365fb3ed7fece1267394c2012e
/IndependentSet/test.cpp
a8ff0f51654be143e3213235266fcafe81d40290
[]
no_license
ikn-lab/EnumerationAlgorithms
7a119923211e1b27bf5c886a7bf8094bead2faf7
1e7ee634583a93d8e86c1c1a857952a898dbc71b
refs/heads/master
2020-12-24T19:51:25.409974
2019-04-25T13:33:37
2019-04-25T13:33:37
86,220,950
1
0
null
null
null
null
UTF-8
C++
false
false
7,859
cpp
//////////////////////////////////////// /* */ /* Enumeration of independnet set */ /* O(1) time per solution */ /* constraint: \omega(G) is constant */ /* kurita */ /* */ //////////////////////////////////////// #include<iostream> #include<vector> #include<fstream> #include<memory> #include<queue> #include<stack> #include<chrono> using namespace std; //List.hpp#include<chrono> #ifndef __LIST__ #define __LIST__ template<typename T> class List{ public: List(){}; List(std::vector<T> elem){init(elem);}; List(int size){init(size);}; ~List(){}; List(List&& x){}; void init(std::vector<T> elem); void init(int size); inline T& operator[](const int id){return list[id];}; inline int GetNext(int id){return next[id];}; inline int GetPrev(int id){return prev[id];}; void set(T elem, int id){list[id] = elem;}; int remove(int id); void undo(); inline int size(){return _size;} inline int maxSize(){return tail;} inline int end(){return tail;}; inline int begin(){return next[tail];}; inline T back(){return list[prev[end()]];}; inline bool member(int id){return not removed[id];}; private: std::unique_ptr<T[]> list; std::unique_ptr<int[]> next, prev; std::unique_ptr<bool[]> removed; int tail, _size, head = -1; }; //n-th element is sentinel template<typename T> void List<T>::init(std::vector<T> elem){ _size = tail = elem.size(); list = std::make_unique<T[]>(tail); next = std::make_unique<int[]>(tail + 1); prev = std::make_unique<int[]>(tail + 1); removed = std::make_unique<bool[]>(tail); for (int i = 0; i < tail; i++) { list[i] = elem[i]; next[i] = i + 1; prev[i] = i - 1; removed[i] = false; } next[tail] = 0; prev[tail] = tail - 1; prev[0] = tail; } //n-th element is sentinel template<typename T> void List<T>::init(int size) { _size = tail = size; list = std::make_unique<T[]>(tail); next = std::make_unique<int[]>(tail + 1); prev = std::make_unique<int[]>(tail + 1); removed = std::make_unique<bool[]>(tail); for (int i = 0; i <= tail; i++) { next[i] = i + 1; prev[i] = i - 1; removed[i] = false; } next[tail] = 0; prev[0] = tail; } template<typename T> int List<T>::remove(int id){ #ifdef DEBUG if(removed[id]){ printf("%d is already removed.\n", id); std::exit(1); } #endif if(removed[id])return prev[id]; removed[id] = true; _size--; prev[next[id]] = prev[id]; next[prev[id]] = next[id]; next[id] = head; head = id; return prev[id]; } template<typename T> void List<T>::undo(){ #ifdef DEBUG if(head == -1){ printf("stack is empty. "); std::exit(1); } #endif removed[head] = false; _size++; int id = head; head = next[id]; next[id] = next[prev[id]]; prev[next[id]] = id; next[prev[id]] = id; } #endif // __LIST__ #ifndef __BASICDATASTRUCTRUE__ #define __BASICDATASTRUCTRUE__ template<typename T> class FixedStack{ public: FixedStack(){}; FixedStack(int n):cap(n){stack = std::make_unique<T[]>(n);} inline void resize(int n){cap = n, stack = std::make_unique<T[]>(n);} inline bool push(T item); inline T top(); inline bool pop(); inline bool empty(){return s == 0;}; inline bool clear(){s = 0; return true;}; inline int size(){return s;}; private: std::unique_ptr<T[]> stack; int s = 0, cap; }; template<typename T> class FixedQueue{ public: FixedQueue(){}; FixedQueue(int n){que = std::make_unique<T[]>(n + 1), cap = n;} inline void resize(int n){que = std::make_unique<T[]>(n + 1), cap = n;} inline bool push(T item); inline T front(); inline bool pop(); inline bool empty(){return tail == head;}; inline bool clear(){tail = head = 0; return true;}; inline int size(){return (tail - head < 0)?tail + cap - head:tail - head;}; inline int end(){return tail;} inline T operator[](const int p){return que[p];} private: std::unique_ptr<T[]> que; int tail = 0, head = 0, cap; }; template<typename T> bool FixedStack<T>::push(T item){ #ifdef DEBUG if(cap == s){ std::cerr << "FixedStack size is over " << cap << std::endl; return false; } #endif stack[s++] = item; return true; } template<typename T> T FixedStack<T>::top(){ #ifdef DEBUG if(s == 0){ std::cerr << "FixedStack is empty" << std::endl; exit(1); } #endif return stack[s - 1]; }; template<typename T> bool FixedStack<T>::pop(){ #ifdef DEBUG if(cap == 0){ std::cerr << "FixedStack size is zero" << std::endl; return false; } #endif --s; return true; } template<typename T> bool FixedQueue<T>::push(T item){ #ifdef DEBUG if(cap == size()){ std::cerr << "FixedQueue size is over " << cap << std::endl; return false; } #endif que[tail++] = item; if(tail >= cap) tail = 0; return true; } template<typename T> T FixedQueue<T>::front(){ #ifdef DEBUG if(empty()){ std::cerr << "FixedQueue is empty" << std::endl; exit(1); } #endif return que[head]; }; template<typename T> bool FixedQueue<T>::pop(){ #ifdef DEBUG if(empty()){ std::cerr << "FixedQueue size is zero" << std::endl; return false; } #endif if(++head >= cap) head = 0; return true; } #endif // __BASICDATASTRUCTRUE__ using bigint = long long int; class EIS{ public: EIS(std::vector<std::vector<int> > H); ~EIS(){}; inline int size(){return G.size();} void Enumerate(); void print(); private: void RecEnum(int v = 0); std::vector<std::vector<int> > G; List<int> cand; FixedStack<int> solution; std::vector<bigint> ans; std::vector<int> degList; int n; }; // #define DEBUG using bigint = long long int; int main(){ int n, m, cnt = 0; std::cin >> n >> m; std::vector<std::vector<int> > G(n, std::vector<int>(n, 1)); for (int i = 0; i < n; i++) G[i][i] = 0; for (int i = 0; i < m; i++) { int u, v, w; std::cin >> u >> v >> w; u--, v--; G[u][v] = G[v][u] = 0; } EIS eis(G); // std::cout << "degeneracy:" << eds.GetDegeneracy() << std::endl; // std::cout << "n:" << eds.size() << std::endl; auto start = std::chrono::system_clock::now(); eis.Enumerate(); auto end = std::chrono::system_clock::now(); auto diff = end - start; std::cout << "elapsed time = " << std::chrono::duration_cast<std::chrono::milliseconds>(diff).count() << " msec." << std::endl; eis.print(); // std::cout << "time:" // << std::chrono::duration_cast<std::chrono::milliseconds>(eds.time).count() // << std::endl; return 0; } #define INF 1e9 using bigint = long long int; EIS::EIS(std::vector<std::vector<int> > H){ n = H.size(); ans.resize(n, 0); G.resize(H.size()); solution.resize(n); for (int i = 0; i < n; i++) G[i].resize(n); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) G[i][j] = H[i][j]; std::vector<int> c(n); for (int i = 0; i < n; i++) c[i] = i; cand.init(c); } void EIS::Enumerate(){ RecEnum(); } void EIS::RecEnum(int v) { if(cand.member(v)){ int stack = 0; cand.remove(v); if(cand.size() > 0) RecEnum(v + 1); else ans[solution.size()]++; for (int i = cand.begin(); i != cand.end(); i = cand.GetNext(i)) { if(G[v][i] == 1) i = cand.remove(i), stack++; } solution.push(v); if(cand.size() > 0) RecEnum(v + 1); else ans[solution.size()]++; solution.pop(); for (int i = 0; i < stack + 1; i++) cand.undo(); }else{ if(cand.size() > 0) RecEnum(v + 1); else ans[solution.size()]++; } } void EIS::print(){ int sum = 0; for (int i = 0; i < ans.size(); i++) sum += ans[i]; std::cout << "sum:" << sum << std::endl; for (int i = 0; i < n; i++) { std::cout << "[" << i << "]:" << ans[i] << std::endl; if(ans[i] == 0)break; } }
89939f5bd20e111fe2712aebc4dd2d8127988493
9cae86c820f6e2e05cb6a7ebc5218f4a9891c68e
/server/server/dreamheroes_server-master/gameserver/gate_manager.h
69ad532eaa34341bda11fbb8773b98a7d61e0662
[]
no_license
kingstop/HardwareServer
aa4c061c408c01b274440db71c22377e0f92c42c
53ace8c689f3eea734578669b1ef6b7fdb8c91ea
refs/heads/master
2021-01-17T06:33:18.342357
2016-08-04T10:54:31
2016-08-04T10:54:31
64,917,148
1
0
null
null
null
null
UTF-8
C++
false
false
813
h
#ifndef __gate_manager_h__ #define __gate_manager_h__ class GateSession ; class Session; class GateManager : public EventableObject { public: GateManager(); ~GateManager(); bool addGate(u16 nId, GateSession* pkGate); void removeGate(GateSession* pkGate); Session* getUser(tran_id_type tranid); Session* addUser(tran_id_type tranid, account_type accid, u16 gate); void removeUser(tran_id_type tranid); void sendMessage(google::protobuf::Message* msg, pb_flag_type flag, u16 nGate); void sendMsgToAll(google::protobuf::Message* msg, pb_flag_type flag); void offlineUser(tran_id_type tranid); void removeAllUsers(); void collectSessionInfo(); protected: void removeUserByGate(u16 nGateId); protected: private: GateSession* m_Gates[MAX_GATE_ID]; obj_ptr_map<tran_id_type, Session>m_Onlines; }; #endif
0061331aaf8190833ea683c1621b5299278ccf80
f9a2bb5fd471428f6c31617ab45dabb400c2ab6a
/bucketsort.cpp
dc58c0e9916ececf07834694cce0f99d076e34ed
[]
no_license
IMNG7/Concurrent_Lab1
e91bf8b0c75af98624ead1b1f29ab767eec0cf2b
6749c4212b265c44b36904ef7b18f9cad13069f7
refs/heads/master
2022-12-20T06:48:48.541107
2020-09-30T22:27:36
2020-09-30T22:27:36
298,194,585
0
0
null
null
null
null
UTF-8
C++
false
false
2,278
cpp
/* FileName: bucket.cpp Description:Contains the function definitions required to perform bucketsort operation on the given numbers. Author: Nitik Gupta References Used: For Bucket Sort Algorithm: https://www.geeksforgeeks.org/bucket-sort-2/ */ #include <iostream> #include <vector> #include <mutex> #include <pthread.h> #include "bucketsort.h" #include "quicksort.h" #include <bits/stdc++.h> using namespace std; extern vector<int> UnsortedArray; extern int thread_num; extern int offset; mutex mtx; map<int,int> bucket; /* Function Name: bucketsort_thread Description: Initial recursive function to split the vector for sorting for single thread Inputs: args - thread number Returns: Nothing. */ void* bucketsort_thread(void* args) { // Taking the thread number size_t thread_part = *((size_t*)args); int size = UnsortedArray.size(); // Calculating the value of left to send for sorting int left =thread_part * (size/thread_num); // Calculating the value of right to send for sorting int right=((thread_part+1) * (size/thread_num)) -1; // In the last thread, checking if there are number left and adding // to right if (thread_part == thread_num - 1) { right += offset; } // Inserting the value in individual bucket maps for(int i=left;i<=right;i++) { mtx.lock(); bucket.insert(pair<int,int>(UnsortedArray[i],i)); mtx.unlock(); } } /* Function Name: bucketsort Description: Sorting function to initialize and start the bucket sort with threading Inputs: threads- thread array Returns: Nothing. */ void bucketsort(pthread_t *threads) { ssize_t* argt = new ssize_t[thread_num+1]; int ret; int size = UnsortedArray.size(); for(int i=0;i<thread_num;i++) { argt[i]=i; ret = pthread_create(&threads[i],NULL,&bucketsort_thread,&argt[i]); if(ret) { cout<<"ERROR WHILE CREATION"; exit(-1); } cout<<"\n\rThreads "<<i<<" Created"; } for(int i=0;i<thread_num;i++) { ret = pthread_join(threads[i],NULL); if(ret) { printf("ERROR; pthread_join: %d\n", ret); exit(-1); } cout<<"\n\rThreads "<<i<<" Joined"; } int index = 0; // Storing the value in the array from the sorted buckets for(auto i=bucket.begin();i!=bucket.end();i++) { UnsortedArray[index++] = i->first; } delete argt; }
8644a95a515aac2b5ffe4923abd0019727f9bcc7
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5695413893988352_0/C++/YeskendirSultanov/b.cpp
9e6dd36a4f804ff313763b3327096af1b46df0cd
[]
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
2,486
cpp
#include <algorithm> #include <iostream> #include <vector> #include <cstdio> #include <string> #include <queue> #include <stack> #include <cmath> #include <set> #include <map> #define ll long long #define f first #define s second #define mp make_pair #define pb push_back using namespace std; int T, id; string a, b; void solve() { id++; cout << "Case #" << id << ": "; cin >> a >> b; int md = 10000; int C = 1000, J = 2000; int n = a.size(); if (n == 1) { if (a[0] == b[0] && a[0] == '?') { cout << "0 0" << endl; } else if (a[0] == '?') { cout << b[0] << ' ' << b[0] << endl; } else { cout << a[0] << ' ' << a[0] << endl; } return; } else if (n == 2) { for (int i = 0; i < 100; ++i) for (int j = 0; j < 100; ++j) { bool ok = true; if (a[0] != '?' && a[0] - '0' != i / 10) ok = false; if (a[1] != '?' && a[1] - '0' != i % 10) ok = false; if (b[0] != '?' && b[0] - '0' != j / 10) ok = false; if (b[1] != '?' && b[1] - '0' != j % 10) ok = false; if (ok) { if (abs(i - j) < md) { md = abs(i - j); C = i; J = j; } else if (abs(i - j) == md) { if (i < C) { C = i; J = j; } else if (i == C && j < J) { C = i; J = j; } } } } cout << C / 10 << C % 10 << ' ' << J / 10 << J % 10 << endl; return; } else { for (int i = 0; i < 1000; ++i) for (int j = 0; j < 1000; ++j) { bool ok = true; if (a[0] != '?' && a[0] - '0' != i / 100) ok = false; if (a[1] != '?' && a[1] - '0' != (i % 100) / 10) ok = false; if (a[2] != '?' && a[2] - '0' != i % 10) ok = false; if (b[0] != '?' && b[0] - '0' != j / 100) ok = false; if (b[1] != '?' && b[1] - '0' != (j % 100) / 10) ok = false; if (b[2] != '?' && b[2] - '0' != j % 10) ok = false; if (ok) { if (abs(i - j) < md) { C = i; J = j; md = abs(i - j); } else if (abs(i - j) == md && i < C) { C = i; J = j; } else if (abs(i - j) == md && (i == C && j < J)) { C = i; J = j; } } } cout << C / 100 << (C % 100) / 10 << C % 10 << ' ' << J / 100 << (J % 100) / 10 << J % 10 << endl; return; } } int main() { #ifdef LOCAL freopen("in", "r", stdin); freopen("out", "w", stdout); #endif cin >> T; while (T--) { solve(); } return 0; }
7d52d9101e2833c39c99f794749b6152d87f516c
b9eb73aecdbd71dfebad4d384fbe51a807588deb
/DataContainers/Forward_list/main.cpp
269e1c3ecfc77b5362af53d1801d9bf4ef33ed16
[]
no_license
DashiBD011/OOP_CPP
f199cff3c2d1b251e167ec87476452959321c181
afbc063176aaef575a1dc23fa69d95d5024f3523
refs/heads/master
2023-07-17T03:54:41.710698
2021-08-20T16:01:26
2021-08-20T16:01:26
348,753,577
1
0
null
null
null
null
UTF-8
C++
false
false
6,807
cpp
#include<iostream> using namespace std; #define tab "\t" #define delimeter "\n-----------------------------------------------------\n" class Element { int Data; // Значение элемента Element* pNext; // Указатель на следующий элемент static int count; public: Element(int Data, Element* pNext = nullptr) :Data(Data), pNext(pNext) { count++; #ifdef DEBUG cout << "EConstructor:\t" << this << endl; #endif // DEBUG } ~Element() { count--; #ifdef DEBUG cout << "EDestructor:\t" << this << endl; #endif // DEBUG } friend class ForwardList; friend class Iterator; }; int Element::count = 0; // инициализация статической переменной class Iterator { Element* Temp; public: Iterator(Element* Temp = nullptr) { this->Temp = Temp; #ifdef DEBUG cout << "IConstructor:\t" << this << endl; #endif // DEBUG } ~Iterator() { #ifdef DEBUG cout << "IDestructor:\t" << this << endl; #endif // DEBUG } // Operators: Iterator& operator++() { Temp = Temp->pNext; return *this; } Iterator operator++(int) { Iterator old = *this; Temp = Temp->pNext; return old; } bool operator==(const Iterator& other)const { return this->Temp == other.Temp; } bool operator!=(const Iterator& other)const { return this->Temp != other.Temp; } Element*& operator->() { return Temp; } Element* get_current_address() { return Temp; } int& operator*() { return Temp->Data; } const int& operator*()const { return Temp->Data; } }; class ForwardList { Element* Head; int size; public: Iterator getHead() { return Head; } Iterator begin() { return Head; } Iterator end() { return nullptr; } ForwardList() { Head = nullptr; //DefaultConstructor создает пустой список size = 0; cout << "LConstructor:\t" << this << endl; } ForwardList(initializer_list<int>il) :ForwardList() { //il - это контейнер, такой же, как наш ForwardList //У любого контейнера есть методы begin() и end(), //которые возвращают указатели на начало и конец контейнера cout << typeid(il.begin()).name() << endl; for (int const* it = il.begin(); it != il.end(); it++) { //it - это итератор, который проходит по il push_back(*it); } } ForwardList(const ForwardList& other) { Element* Temp = other.Head; while (Temp) { push_back(Temp->Data); Temp = Temp->pNext; } cout << "LCopyConstructor:\t" << this << endl; } ~ForwardList() { while (Head) pop_front(); cout << "LDestructor:\t" << this << endl; } // Operators: ForwardList& operator=(const ForwardList& other) { if (this == &other)return *this; while (Head)pop_front(); Element* Temp = other.Head; while (Temp) { push_back(Temp->Data); Temp = Temp->pNext; } cout << "LCopyAssignment:" << this << endl; return *this; } // Adding elements: void push_front(int Data) { /*Element* New = new Element(Data); New -> pNext = Head; Head = New;*/ Head = new Element(Data, Head); size++; } void push_back(int Data) { // push_back не умеет работать с пустым списком if (Head == nullptr) { push_front(Data); return; } //Element* New = new Element(Data); Element* Temp = Head; while (Temp->pNext != nullptr) { Temp = Temp->pNext; } Temp->pNext = new Element(Data); size++; } // Erasing elements: void pop_front() { Element* Temp = Head; Head = Temp->pNext; delete Temp; size--; } void pop_back() { Element* Temp = Head; while (Temp->pNext->pNext) { Temp = Temp->pNext; } delete Temp->pNext; Temp->pNext = nullptr; size--; } void insert(int Data, int index) { if (index == 0) { push_front(Data); return; } //Element* New = new Element(Data); Element* Temp = Head; for (int i = 0; i < index - 1; i++, Temp = Temp->pNext) if (Temp->pNext == nullptr)break; /*Temp = Temp->pNext; New->pNext = Temp->pNext; Temp->pNext = New;*/ Temp->pNext = new Element(Data, Temp->pNext); size++; } void erase(int index) { if (index > size)return; if (index == 0) { pop_front(); return; } Element* Temp = Head; for (int i = 0; i < index - 1; i++) { Temp = Temp->pNext; } Element* to_del = Temp->pNext; Temp->pNext = Temp->pNext->pNext; delete to_del; size--; } // Methods void print() { /*Element* Temp = Head; while (Temp != nullptr) { cout << Temp << "\t" << Temp->Data << "\t" << Temp->pNext << endl; Temp = Temp->pNext; }*/ for (Iterator Temp = Head; Temp != nullptr; Temp++) //cout << Temp.get_current_address() << tab << Temp->Data << tab << Temp->pNext << endl; cout << *Temp << tab; cout << endl; cout << "Количество элементов в списке: " << size << endl; cout << "Общее количество элементов: " << Element::count << endl; } }; //#define BASE_CHECK //#define ITERATOR_CHECK //#define RANGE_BASED_ARRAY void main() { setlocale(LC_ALL, ""); #ifdef BASE_CHECK int n; cout << "Введите размер списка: "; cin >> n; ForwardList list; for (int i = 0; i < n; i++) { //list.push_front(rand() % 100); list.push_back(rand() % 100); } list = list; list.print(); #endif // BASE_CHECK #ifdef ITERATOR_CHECK for (Iterator it = list.getHead(); it != nullptr; it++) { *it = rand() % 100; } list.print(); #endif // ITERATOR_CHECK #ifdef BASE_CHECK //list.pop_front(); //list.print(); //list.pop_back(); //list.print(); //list.push_back(1000); int value; int index; cout << "Введите добавляемое значение: "; cin >> value; cout << "Введите индекс добавляемого значения: "; cin >> index; list.insert(value, index); list.print(); cout << "Введите индекс удаляемого значения: "; cin >> index; list.erase(index); list.print(); //cout << "Еще один список:\n" << endl; //ForwardList list2; //list2.push_back(3); //list2.push_back(5); //list2.push_back(8); //list2.print(); #endif // BASE_CHECK //ForwardList list2(list); //list2.print(); // //ForwardList list3 = list2; //list3.print(); #ifdef RANGE_BASED_ARRAY int arr[] = { 3,5,8,13,21 }; for (int i = 0; i < size(arr); i++) { cout << arr[i] << tab; } cout << endl; for (int i : arr)// Range-based for (цикл for для контейнера) { cout << i << tab; } cout << endl; #endif // RANGE_BASED_ARRAY ForwardList list = { 3,5,8,13,21 }; list.print(); for (int i : list) { cout << i << tab; } cout << endl; }
6a7e6ed55cbbe920d39b02cedfbd2d9ecffb2180
0aec4b2dfc30829c475102a20458d43fa2a67325
/Laboratorio/02/sources/root_comparison/UT/include/root_UT_testbench.hh
196f8a098a6127c9d4b704997b84f37094b2f70a
[]
no_license
FilippoNevi/EISD
f80e78b057fbb796294daa77ee516933f583b73e
0f350ed1b73b15e5e72beeb1510bca192d855a55
refs/heads/main
2023-06-12T19:44:31.924021
2021-07-05T16:14:37
2021-07-05T16:14:37
334,434,156
0
0
null
2021-07-02T16:02:49
2021-01-30T14:37:58
VHDL
UTF-8
C++
false
false
595
hh
#ifndef _root_UT_TESTBENCH_H_ #define _root_UT_TESTBENCH_H_ #include <systemc.h> #include <tlm.h> #include "define_UT.hh" class root_UT_testbench : public sc_module , public virtual tlm::tlm_bw_transport_if<> { private: SC_HAS_PROCESS(root_UT_testbench); virtual void invalidate_direct_mem_ptr(uint64 start_range, uint64 end_range); virtual tlm::tlm_sync_enum nb_transport_bw(tlm::tlm_generic_payload & trans, tlm::tlm_phase & phase, sc_time & t); void run(); public: tlm::tlm_initiator_socket<> initiator_socket; root_UT_testbench(sc_module_name name); }; #endif
52af2962ee527773dae0a3dc0e06ec2cb796d4b6
5bcb821eb8afbc0bb20b20e2b4391f96eab69bdd
/exercise/ipd13a-4.hxx
0acb3b7d54f7abe5947479e47dcc0b90f1b7be3c
[]
no_license
nu-ipd/ipd13a
d80157bf76c3520109007e8fc58dec9473a0c676
6a397a1e5c43da7c52ca7f96aa879855eb4f26e9
refs/heads/master
2023-01-08T21:59:28.131618
2020-11-05T23:26:05
2020-11-05T23:26:05
306,994,609
0
2
null
null
null
null
UTF-8
C++
false
false
1,441
hxx
#pragma once #include <vector> namespace ipd { // A shorter name for a long-ish type name: using Int_vec = std::vector<int>; // Replaces each element of the given vector with the prefix sum up to // and including itself. // // Example: // // Int_vec v {1, 2, 3, 5, 7}; // sum_prefixes(v); // CHECK( v == Int_vec{1, 3, 6, 11, 18}); // void sum_prefixes(Int_vec& in_place); // Undoes the effect of `sum_prefixes`. // // Example: // // Int_vec v {1, 3, 6, 11, 18}; // unsum_prefixes(v); // CHECK( v == Int_vec{1, 2, 3, 5, 7}); // void unsum_prefixes(Int_vec& in_place); // Extends `dst` with the prefix sum of `src`. // // Examples: // // Int_vec v1 {2, 4, 6}; // Int_vec v2; // sum_prefixes_into(v2, v1); // unsum_prefixes(v2); // CHECK( v1 == v2 ); // // sum_prefixes_into(v2, v1); // CHECK( v1 == Int_vec{2, 4, 6} ); // CHECK( v2 == Int_vec{2, 4, 6, 2, 6, 12} ); // void sum_prefixes_into( Int_vec& dst, Int_vec const& src); // Determines whether `summed` contains the prefix sums of `unsummed`. // // Examples: // // - contains_prefix_sums(Int_vec{1, 2, 3}, Int_vec{1, 1, 1}) is true // - contains_prefix_sums(Int_vec{1, 2, 3}, Int_vec{0, 0, 5}) is false // - contains_prefix_sums(Int_vec{1, 2, 3}, Int_vec{1, 1}) is false // bool contains_prefix_sums( Int_vec const& summed, Int_vec const& unsummed); } // end namespace ipd
e20b4b7312534a207c6b9142f371a3d243e1c930
e50e5cf22c9d9a29b856798095c816b889eb7571
/simple.multifit.cc
16d99883bd7bccfb896e2ab81c13755ad77dc0fa
[]
no_license
amassiro/AdvancedMultifit
c958afc35f482dca65a525405bc1abaf814b420e
8e1fb7b59888a92f8db80d7681e34142bef1186c
refs/heads/master
2021-01-11T05:35:12.466350
2018-09-04T15:32:53
2018-09-04T15:32:53
71,792,072
0
1
null
null
null
null
UTF-8
C++
false
false
18,085
cc
// // MultiFit amplitude reconstruction // To run: // g++ -o simple.multifit.exe simple.multifit.cc PulseChiSqSNNLS.cc -std=c++11 `root-config --cflags --glibs` // #include <iostream> #include "PulseChiSqSNNLS.h" #include "Pulse.h" #include "TTree.h" #include "TF1.h" #include "TProfile.h" #include "TH2.h" #include "TFile.h" //---- transform the pulse into an histogram - type is "reco = 1" or "sim = 0" TH1F* CreateHistoShape( SampleVector& sam, int itime, int type) { TString name = Form ("h_%d_%d",type, itime); TH1F* temphist = new TH1F(name.Data(),"",sam.rows(),0,sam.rows()); for (int i=0; i<sam.rows(); i++) { temphist->SetBinContent(i+1, sam[i]); } return temphist; } //---- transform the pulse into an histogram - type is "reco = 1" or "sim = 0" TH1F* CreateHistoAmplitudes( const PulseVector& sam, int itime, int type) { TString name = Form ("hAmpl_%d_%d",type, itime); TH1F* temphist = new TH1F(name.Data(),"",sam.rows(),0,sam.rows()); for (int i=0; i<sam.rows(); i++) { temphist->SetBinContent(i+1, sam[i]); } return temphist; } void run(std::string inputFile, std::string outFile, int NSAMPLES, float NFREQ, float time_shift, float pedestal_shift) { std::cout << " run ..." << std::endl; float return_chi2 = -99; //---- // int NSAMPLES = 10; // int NFREQ = 25; // int WFLENGTH = 500; // int IDSTART = 180; // int IDSTART = 7*25; float IDSTART = 6*25 + time_shift; //---- // IDSTART = 7.2 * NFREQ; int WFLENGTH = 500*4; //---- step 1/4 ns in waveform if (( IDSTART + NSAMPLES * NFREQ ) > 500 ) { WFLENGTH = (IDSTART + NSAMPLES * NFREQ)*4 + 100; } std::cout << " WFLENGTH = " << WFLENGTH << std::endl; std::cout << " NFREQ = " << NFREQ << std::endl; Pulse pSh; pSh.SetNSAMPLES (NSAMPLES); pSh.SetNFREQ (NFREQ); pSh.SetWFLENGTH(WFLENGTH); pSh.SetIDSTART(IDSTART); pSh.Init(); std::cout << " pSh ready " << std::endl; // FullSampleVector fullpulse(FullSampleVector::Zero()); // FullSampleMatrix fullpulsecov(FullSampleMatrix::Zero()); // SampleMatrix noisecor(SampleMatrix::Zero()); // BXVector activeBX; // SampleVector amplitudes(SampleVector::Zero()); FullSampleVector fullpulse; FullSampleMatrix fullpulsecov; SampleMatrix noisecor; BXVector activeBX; SampleVector amplitudes; fullpulse.resize(2*NSAMPLES,1); fullpulse.setZero(); // (Eigen::Matrix<double,2*NSAMPLES,1>::Zero()); fullpulsecov.resize(2*NSAMPLES,2*NSAMPLES); fullpulsecov.setZero(); // (Eigen::Matrix<double,2*NSAMPLES,2*NSAMPLES>::Zero()); noisecor.resize(NSAMPLES,NSAMPLES); noisecor.setZero(); // (Eigen::Matrix<double,NSAMPLES,NSAMPLES>::Zero()); activeBX.resize(Eigen::NoChange,1); amplitudes.resize(NSAMPLES,1); amplitudes.setZero(); // (SampleVector::Zero()); std::cout << " default ready " << std::endl; // intime sample is [2] // double pulseShapeTemplate[NSAMPLES+2]; std::vector<double> pulseShapeTemplate; // for(int i=0; i<(NSAMPLES+2*int(25 /NFREQ)); i++) { // for(int i=0; i<(NSAMPLES+5*int(25 /NFREQ)); i++) { for(int i=0; i<(NSAMPLES+7*int(25 /NFREQ)); i++) { // for(int i=0; i<(2*NSAMPLES+2); i++){ // for(int i=0; i<(NSAMPLES+2); i++){ // double x = double( IDSTART + NFREQ * (i + 3) - WFLENGTH / 2 + 25); //----> + 25 or not? // double x = double( IDSTART + NFREQ * (i + 3) - WFLENGTH / 2 ); //----> + 25 or not? // double x = double( IDSTART + NFREQ * (i) + 3*25. - WFLENGTH / 2 + 25.); // double x = double( IDSTART + NFREQ * (i) + 3*25. - WFLENGTH / 2 ); // ----> best for 25 ns spacing?? // double x = double( IDSTART + NFREQ * (i) + 3*25. - WFLENGTH / 2 + 5 ); //--------------> this is the residual of the 180 ns shift ... arbitrary 180 ns!!! // double x = double( IDSTART + NFREQ * (i) + 3*25. - WFLENGTH / 2 + 5 + 25 * ( int( IDSTART / NFREQ ) - ( IDSTART / NFREQ ) ) ); double x; // if ( NFREQ == 25) x = double( IDSTART + NFREQ * (i) + 3*25. - WFLENGTH / 2 ); // if ( NFREQ == 6.25) x = double( IDSTART + NFREQ * (i) + 3*25. - WFLENGTH / 2 + 5); // if ( NFREQ == 12.5) x = double( IDSTART + NFREQ * (i) + 3*25. - WFLENGTH / 2 + 10); // x = double( IDSTART + NFREQ * i + 4*25. - 500 / 2. ); //----> 500 ns is fixed! x = double( IDSTART + NFREQ * i + 3*25. - 500 / 2. ); //----> 500 ns is fixed! // std::cout << " IDSTART + NFREQ * i + 3*25. - 500 / 2. = " << IDSTART + NFREQ * i + 3*25. - 500 / 2. << std::endl; // double x = double( IDSTART + NFREQ * (i) + 3*25. - WFLENGTH / 2 - 25.); // double x = double( NFREQ * (i) + 3*25. - WFLENGTH / 2 - 25.); // double x = double( IDSTART + NFREQ * (i) - WFLENGTH / 2 ); // pulseShapeTemplate[i] = pSh.fShape(x); // if (NFREQ == 12.5) pulseShapeTemplate.push_back( pSh.fShape(x) / (2.5)); // else if (NFREQ == 6.25) pulseShapeTemplate.push_back( pSh.fShape(x) / (10/0.3)); // else pulseShapeTemplate.push_back( pSh.fShape(x)); pulseShapeTemplate.push_back( pSh.fShape(x)); // pulseShapeTemplate.push_back( pSh.fShape(x) * NFREQ/25.); // pulseShapeTemplate.push_back( pSh.fShape(x)); std::cout << " [" << i << "::" << (NSAMPLES+2*25 /NFREQ) << "] --> pSh.fShape(" << x << ") = " << pSh.fShape(x) << " ---> " << pSh.fShape(x) * NFREQ/25. << std::endl; } // for(int i=0; i<(NSAMPLES+2); i++) pulseShapeTemplate[i] /= pulseShapeTemplate[2]; // for (int i=0; i<(NSAMPLES+2); i++) fullpulse(i+(NSAMPLES-3)) = pulseShapeTemplate[i]; // for (int i=0; i<(NSAMPLES+2); i++) fullpulse(i+7) = pulseShapeTemplate[i]; // 7 before was due to // IDSTART = 180 ns = 7.2 * 25 ns ; // now it should be, in a more general way: // 180 ns = X * NFREQ --> X = 180 / NFREQ // for (int i=0; i<(NSAMPLES + 3*int(25 /NFREQ)); i++) { for (int i=1; i<(NSAMPLES + 2*int(25 /NFREQ)); i++) { // for (int i=0; i<(NSAMPLES + 2*int(25 /NFREQ)); i++) { // fullpulse(i + NSAMPLES - 3*25 /NFREQ + int( IDSTART / NFREQ )) = pulseShapeTemplate[i]; // std::cout << " i + NSAMPLES - 3*int(25 /NFREQ) = " << i << " + " << NSAMPLES << " - 3*int(25 / " << NFREQ << " ) = " << i + NSAMPLES - 3*int(25 /NFREQ) << std::endl; // fullpulse(i + NSAMPLES - 3*int(25 /NFREQ)) = pulseShapeTemplate[i]; fullpulse(i + 7 * int(25 /NFREQ)) = pulseShapeTemplate[i]; // fullpulse(i + 7 * int(25 /NFREQ)) = pulseShapeTemplate[i-1]; // _NSAMPLES - 5 * int(25. /_NFREQ) // fullpulse(i) = pulseShapeTemplate[i]; // fullpulse(i + int( IDSTART / NFREQ )) = pulseShapeTemplate[i]; // fullpulse(i + int(180/NFREQ)) = pulseShapeTemplate[i]; // fullpulse(i + NSAMPLES/2 + int(2 * 25 /NFREQ) ) = pulseShapeTemplate[i]; // std::cout << " i + int(" << IDSTART << "/NFREQ) = " << i << " + " << int(IDSTART/NFREQ) << " = " << i + int(IDSTART/NFREQ) << " --> " << pulseShapeTemplate[i] << std::endl; // std::cout << " i = " << i << " --> pulseShapeTemplate = " << pulseShapeTemplate[i] << std::endl; } // for (int i=0; i<(NSAMPLES+5); i++) fullpulse(i+(NSAMPLES-3)) = pulseShapeTemplate[i]; // for (int i=0; i<(NSAMPLES+2); i++) fullpulse(i+(NSAMPLES-3)) = pulseShapeTemplate[i]; // for (int i=0; i<(NSAMPLES+2); i++) fullpulse(i+(NSAMPLES-3)) = pulseShapeTemplate[i]; //---- correlation for (int i=0; i<NSAMPLES; ++i) { for (int j=0; j<NSAMPLES; ++j) { int vidx = std::abs(j-i); noisecor(i,j) = pSh.corr(vidx); } } std::cout << " noise ready " << std::endl; //---- collision every 25 ns -> this is fixed number //---- number of sampls * frequence in ns / 25 ns if ( round((NSAMPLES * NFREQ) / 25.) != (NSAMPLES * NFREQ) / 25 ) { std::cout << " Attention please! How do you think multifit can fit a pulse in the middle between collisions!?!?!?!?" << std::endl; } int totalNumberOfBxActive = int(NSAMPLES * NFREQ) / 25; // int totalNumberOfBxActive = int(NSAMPLES * NFREQ) / 25 - 1; std::cout << " totalNumberOfBxActive = " << totalNumberOfBxActive << std::endl; // totalNumberOfBxActive = 4; // int activeBXs[] = { -5, -1, 0, 1 }; std::vector<int> activeBXs; for (unsigned int ibx=0; ibx<totalNumberOfBxActive; ++ibx) { // activeBXs.push_back( ibx * 25./NFREQ - 3 * 25 / NFREQ ); //----> -3 BX are active w.r.t. 0 BX // activeBXs.push_back( ibx * int(25 /NFREQ) - 5 * int(25 /NFREQ) ); //----> -5 BX are active w.r.t. 0 BX activeBXs.push_back( ibx * int(25 /NFREQ) - 4 * int(25 /NFREQ) ); //----> -5 BX are active w.r.t. 0 BX // activeBXs.push_back( ibx * 25./NFREQ - 3 * 25 / NFREQ ); // if (NSAMPLES%2) { // //---- odd // activeBXs[ibx] = ibx * 25./NFREQ - (NSAMPLES+1)/2; // } // else { // //---- even // activeBXs[ibx] = ibx * 25./NFREQ - NSAMPLES/2; // } // activeBXs[ibx] = ibx * 25./NFREQ - NSAMPLES/2; std::cout << " activeBXs[" << ibx << "] = " << activeBXs[ibx] << std::endl; } // // int activeBXs[] = { -5, -4, -3, -2, -1, 0, 1, 2, 3, 4 }; // int activeBXs[500]; // if (NSAMPLES == 10) { // for (unsigned int ibx=0; ibx<NSAMPLES; ++ibx) { // activeBXs[ibx] = ibx - NSAMPLES/2; // std::cout << " activeBXs[" << ibx << "] = " << activeBXs[ibx] << std::endl; // } // } // else { // for (unsigned int ibx=0; ibx<10; ++ibx) { // activeBXs[ibx] = 2*ibx - NSAMPLES/2; // std::cout << " activeBXs[" << ibx << "] = " << activeBXs[ibx] << std::endl; // } // } activeBX.resize(totalNumberOfBxActive); for (unsigned int ibx=0; ibx<totalNumberOfBxActive; ++ibx) { activeBX.coeffRef(ibx) = activeBXs[ibx]; } std::cout << " end init " << std::endl; // activeBX.resize(1); // activeBX.coeffRef(0) = 0; std::cout << " inputFile = " << inputFile << std::endl; TFile *file2 = new TFile(inputFile.c_str()); // TFile *file2 = new TFile("data/samples_signal_10GeV_eta_0.0_pu_140.root"); // double samples[NSAMPLES]; std::vector<double>* samples = new std::vector<double>; double amplitudeTruth; TTree *tree = (TTree*) file2->Get("Samples"); tree->SetBranchAddress("amplitudeTruth", &amplitudeTruth); tree->SetBranchAddress("samples", &samples); float sigmaNoise; // = 0.044; tree->SetBranchAddress("sigmaNoise", &sigmaNoise); int nentries = tree->GetEntries(); std::cout << " nentries = " << nentries << std::endl; std::cout << " NSAMPLES = " << NSAMPLES << std::endl; TFile *fout; TH1D *h01; std::vector<TH1F*> v_pulses; std::vector<TH1F*> v_amplitudes_reco; std::cout << " outFile = " << outFile << std::endl; fout = new TFile(outFile.c_str(),"recreate"); h01 = new TH1D("h01", "dA", 5000, -5.0, 5.0); fout->cd(); TTree* newtree = (TTree*) tree->CloneTree(0); //("RecoAndSim"); newtree->SetName("RecoAndSim"); std::vector <double> samplesReco; int ipulseintime = 0; newtree->Branch("chi2", &return_chi2, "chi2/F"); newtree->Branch("samplesReco", &samplesReco); newtree->Branch("ipulseintime", ipulseintime, "ipulseintime/I"); newtree->Branch("activeBXs", &activeBXs); newtree->Branch("pulseShapeTemplate", &pulseShapeTemplate); std::cout << " pulseShapeTemplate.size () = " << pulseShapeTemplate.size() << std::endl; for (unsigned int ibx=0; ibx<totalNumberOfBxActive; ++ibx) { samplesReco.push_back(0.); } v_amplitudes_reco.clear(); //---- create the multifit PulseChiSqSNNLS pulsefunc; pulsefunc.setNSAMPLES(NSAMPLES); pulsefunc.setNFREQ(NFREQ); pulsefunc.Init(); //---- initialization, needed fout->cd(); for(int ievt=0; ievt<nentries; ++ievt){ if (!(ievt%10)) { std::cout << " ievt = " << ievt << " :: " << nentries << std::endl; } // std::cout << " here " << std::endl; tree->GetEntry(ievt); // std::cout << " here " << std::endl; // std::cout << " samples->size() = " << samples->size() << std::endl; for(int i=0; i<NSAMPLES; i++){ amplitudes[i] = samples->at(i) - pedestal_shift; // std::cout << " samples->at(" << i << ") = " << samples->at(i) << std::endl; } // v_pulses.push_back(CreateHistoShape(amplitudes, ievt, 0)); double pedval = 0.; double pedrms = 1.0; // --- why have you disabled this!?!?!??! // pulsefunc.disableErrorCalculation(); // if (sigmaNoise == 0) pedrms = 0.1; // else pedrms = sigmaNoise / 0.044; if (sigmaNoise == 0) pedrms = 0.00044; else pedrms = sigmaNoise; // std::cout << " amplitudes = " << amplitudes << std::endl; // std::cout << " noisecor = " << noisecor << std::endl; // std::cout << " pedrms = " << pedrms << std::endl; // // std::cout << " activeBX = " << activeBX << std::endl; // std::cout << " fullpulse = " << fullpulse << std::endl; // std::cout << " fullpulsecov = " << fullpulsecov << std::endl; bool status = pulsefunc.DoFit( amplitudes, noisecor, pedrms, activeBX, fullpulse, fullpulsecov ); double chisq = pulsefunc.ChiSq(); return_chi2 = chisq; std::cout << " Example7 :: return_chi2 = " << return_chi2 << std::endl; ipulseintime = 0; for (unsigned int ipulse=0; ipulse<pulsefunc.BXs()->rows(); ++ipulse) { // std::cout << " pulsefunc.BXs()->coeff(" << ipulse << ") = " << int(pulsefunc.BXs()->coeff(ipulse)) << std::endl; // if (pulsefunc.BXs()->coeff(ipulse)==0) { if ( ((int(pulsefunc.BXs()->coeff(ipulse))) * NFREQ/25 + 5) == 0) { // std::cout << " found intime!!! --> " << ipulse << std::endl; ipulseintime = ipulse; break; } } // std::cout << " >> ipulseintime = " << ipulseintime << " >> status = " << status << std::endl; // std::cout << " >> ipulseintime = " << ipulseintime << std::endl; // std::cout << " >> status = " << status << std::endl; double aMax = status ? (*(pulsefunc.X()))[ipulseintime] : 0.; // double aErr = status ? pulsefunc.Errors()[ipulseintime] : 0.; // std::cout << " pulsefunc.BXs().rows() = " << pulsefunc.BXs()->rows() << std::endl; // std::cout << " pulsefunc.X() = " << pulsefunc.X() << std::endl; for (unsigned int ipulse=0; ipulse<pulsefunc.BXs()->rows(); ++ipulse) { if (status) { // std::cout << " ip = " << ipulse << " --> " << int(pulsefunc.BXs()->coeff(ipulse)) << " ----> " << (*(pulsefunc.X()))[ ipulse ] << std::endl; // std::cout << " ip = " << ipulse << " --> " << (int(pulsefunc.BXs()->coeff(ipulse)) + NSAMPLES / 2) * NFREQ/25 << " ----> " << (*(pulsefunc.X()))[ ipulse ] << std::endl; // std::cout << " ip = " << ipulse << " --> " << (int(pulsefunc.BXs()->coeff(ipulse)) + 3) * NFREQ/25 << " ----> " << (*(pulsefunc.X()))[ ipulse ] << std::endl; if (ievt == 0) std::cout << " ip = " << ipulse << " --> [" << (int(pulsefunc.BXs()->coeff(ipulse))) << "] --> " << (int(pulsefunc.BXs()->coeff(ipulse))) * NFREQ/25 + 5 << " == " << (*(pulsefunc.X()))[ ipulse ] << std::endl; // samplesReco[ int(pulsefunc.BXs()->coeff(ipulse)) + NSAMPLES / 2 ] = (*(pulsefunc.X()))[ ipulse ]; // samplesReco[ (int(pulsefunc.BXs()->coeff(ipulse)) + NSAMPLES / 2) * NFREQ/25 ] = (*(pulsefunc.X()))[ ipulse ]; // samplesReco[ (int(pulsefunc.BXs()->coeff(ipulse)) + 3 ) * NFREQ/25 ] = (*(pulsefunc.X()))[ ipulse ]; // samplesReco[ (int(pulsefunc.BXs()->coeff(ipulse)) + 5 ) * NFREQ/25 ] = (*(pulsefunc.X()))[ ipulse ]; //---- YES samplesReco[ (int(pulsefunc.BXs()->coeff(ipulse))) * NFREQ/25 + 5] = (*(pulsefunc.X()))[ ipulse ]; // // ibx * 25./NFREQ - NSAMPLES/2 // // samplesReco[ int(pulsefunc.BXs()->coeff(ipulse)) + 5] = (*(pulsefunc.X()))[ ipulse ]; // samplesReco[ int(pulsefunc.BXs().coeff(ipulse)) + 5] = pulsefunc.X()[ int(pulsefunc.BXs().coeff(ipulse)) + 5 ]; // samplesReco[ipulse] = pulsefunc.X()[ ipulse ]; // samplesReco[ipulse] = pulsefunc.X()[ pulsefunc.BXs().coeff(ipulse) ]; } else { samplesReco[ipulse] = -1; } } // for (unsigned int ipulse=0; ipulse<pulsefunc.BXs().rows(); ++ipulse) { // amplitudes[ipulse] = pulsefunc.X()[ipulse]; // } // v_pulses_reco.push_back(CreateHistoShape(amplitudes, ievt, 1)); // v_amplitudes_reco.push_back(CreateHistoAmplitudes(*(pulsefunc.X()), ievt, 1)); h01->Fill(aMax - amplitudeTruth); // std::cout << " aMax - amplitudeTruth = " << aMax << " - " << amplitudeTruth << std::endl; newtree->Fill(); } //---- save pulses // fout->cd(); // fout->mkdir("samples"); // fout->cd("samples"); // for (int ievt = 0; ievt < v_pulses.size(); ievt++) { // v_pulses.at(ievt)->Write(); // } // // for (int ievt = 0; ievt < v_amplitudes_reco.size(); ievt++) { // v_amplitudes_reco.at(ievt)->Write(); // } std::cout << " Mean of REC-MC = " << h01->GetMean() << " GeV" << std::endl; std::cout << " RMS of REC-MC = " << h01->GetRMS() << " GeV" << std::endl; fout->cd(); std::cout << " done (1) " << std::endl; h01->Write(); std::cout << " done (2) " << std::endl; // newtree->AutoSave(); newtree->Write(); std::cout << " done (3) " << std::endl; fout->Close(); std::cout << " done ... " << std::endl; } # ifndef __CINT__ int main(int argc, char** argv) { std::string inputFile = "data/samples_signal_10GeV_pu_0.root"; if (argc>=2) { inputFile = argv[1]; } std::string outFile = "output.root"; if (argc>=3) { outFile = argv[2]; } std::cout << " outFile = " << outFile << std::endl; //---- number of samples per impulse int NSAMPLES = 10; if (argc>=4) { NSAMPLES = atoi(argv[3]); } std::cout << " NSAMPLES = " << NSAMPLES << std::endl; //---- number of samples per impulse float NFREQ = 25; if (argc>=5) { NFREQ = atof(argv[4]); } std::cout << " NFREQ = " << NFREQ << std::endl; //---- time shift float time_shift = 0; if (argc>=6) { time_shift = atof(argv[5]); } std::cout << " time_shift = " << time_shift << std::endl; //---- pedestal shift float pedestal_shift = 0; if (argc>=7) { pedestal_shift = atof(argv[6]); } std::cout << " pedestal_shift = " << pedestal_shift << std::endl; run(inputFile, outFile, NSAMPLES, NFREQ, time_shift, pedestal_shift); std::cout << " outFile = " << outFile << std::endl; return 0; } # endif
cd82013a04684e212a1a19c8f7a27aff45c9da18
15b84964763f0e88f114812aa3ee654263a59025
/HeadFirstDesignPatterns/Iterator/DinerMerger/StaticMenuItem.cpp
fa3db7c116be6b43763f6b567b41d0ecf9e3072d
[]
no_license
RussDHill/hfdp-cpp
a0524248fcf90dba06ff4e106ac315f9080b5826
2459c3e4564531184123256049d9b5515ce451a9
refs/heads/master
2021-01-10T15:29:07.353612
2020-08-29T13:02:43
2020-08-29T13:02:43
46,441,962
2
1
null
null
null
null
UTF-8
C++
false
false
749
cpp
#include "stdafx.h" #include "MenuItem.h" int MenuItem::size = 0; MenuItem::MenuItem(string name, string description, bool vegetarian, double price) :name(name), description(description), vegetarian(vegetarian), price(price) { } MenuItem::MenuItem() { } MenuItem::~MenuItem() { } string MenuItem::getName() { return name; } string MenuItem::getDescription() { return description; } double MenuItem::getPrice() { return price; } bool MenuItem::isVegetarian() { return vegetarian; } string MenuItem::toString() { char buffer[64]; sprintf(buffer, "%.2f", price); return (name + ", $" + buffer + "\n " + description); } void MenuItem::setSize(int size) { this->size = size; } int MenuItem::getSize() { return size; }
1c3be3e76b8304088701992e6053fbd87bb05652
16288c0fb3a712150c715ddd0c9843e75f69034b
/cpp04/ex03/srcs/Character.cpp
37347315f28c0e0c9e236420bba5cbbd36d0c5a8
[]
no_license
brian-xu-vlt/42_CPP_PISCINE
3c6cb8ce224e53335b3e53cd24c97dc867c2d9f0
bda1f5834649e50012d0153c3cdd28769280fc9d
refs/heads/main
2023-02-25T23:17:43.176521
2021-02-03T07:12:22
2021-02-03T07:12:22
323,266,501
1
0
null
null
null
null
UTF-8
C++
false
false
1,956
cpp
# include "Character.hpp" /* ** ------------------------------- CONSTRUCTOR -------------------------------- */ Character::Character( std::string name ) : _name(name) { for (size_t i = 0; i < Character::_inventorySize; i++) this->_inventory[i] = NULL; } /* ** ------------------------------- COPY CTOR --------------------------------- */ Character::Character( const Character & src ) { *this = src; } /* ** -------------------------------- DESTRUCTOR -------------------------------- */ Character::~Character() { for (size_t i = 0; i < Character::_inventorySize; i++) if (this->_inventory[i] != NULL) delete this->_inventory[i]; } /* ** --------------------------------- OVERLOAD --------------------------------- */ Character & Character::operator=( Character const & rhs ) { if ( this != &rhs ) { for (size_t i = 0; i < Character::_inventorySize; i++) { if (rhs._inventory[i] != NULL) this->_inventory[i] = rhs._inventory[i]->clone(); } } return *this; } /* ** --------------------------------- METHODS ---------------------------------- */ std::string const & Character::getName() const { return (this->_name); } void Character::equip(AMateria* m) { if (m == NULL) return; for (size_t i = 0; i < Character::_inventorySize; i++) { if (this->_inventory[i] == m) break ; if (this->_inventory[i] == NULL) { this->_inventory[i] = m; break ; } } } void Character::unequip(int idx) { if (idx >= 0 && (size_t)idx < Character::_inventorySize && this->_inventory[idx] != NULL) this->_inventory[idx] = NULL; } void Character::use(int idx, ICharacter& target) { if (idx >= 0 && (size_t)idx < Character::_inventorySize && this->_inventory[idx] != NULL) this->_inventory[idx]->use(target); } /* ** --------------------------------- ACCESSOR --------------------------------- */ /* ************************************************************************** */
07511c25dc8fc02fb9ac2e11947198652f09bbb5
3fd592b8c2a8cba48d1f95500e5979ebea8146be
/QCustomModelViewLib/QComboxDelegate.cpp
bdc3764aece9179610f5bf0613534452ec5fb475
[]
no_license
wkqCatch/universalLib
a9f69e9df57acc527dca2a9987c136bc139b76f5
d53a5ca33c86e0d75b826bde15ad285fa1902a49
refs/heads/master
2020-08-09T08:57:37.049953
2020-03-06T12:58:17
2020-03-06T12:58:17
214,053,158
2
1
null
null
null
null
UTF-8
C++
false
false
1,727
cpp
#include "QComboxDelegate.h" #include <QStyledItemDelegate> QComboxDelegate::QComboxDelegate(QObject *parent) : QStyledItemDelegate(parent) { } QComboxDelegate::~QComboxDelegate() { } QWidget * QComboxDelegate::createEditor(QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index) const { QComboBox *pComboEditor = new QComboBox(parent); QStyledItemDelegate *pSerialSelectionDelegate = new QStyledItemDelegate(); pComboEditor->setItemDelegate(pSerialSelectionDelegate); pComboEditor->addItems(m_listComboxContent); return pComboEditor; } void QComboxDelegate::setEditorData(QWidget * editor, const QModelIndex & index) const { QString currentContent = index.model()->data(index, Qt::DisplayRole).toString(); QComboBox *pComboBox = dynamic_cast<QComboBox*>(editor); if(pComboBox) { pComboBox->setCurrentText(currentContent); connect(pComboBox, QOverload<const QString&>::of(&QComboBox::activated), this, &QComboxDelegate::sig_ComboBoxActived); } } void QComboxDelegate::setModelData(QWidget * editor, QAbstractItemModel * model, const QModelIndex & index) const { QComboBox *pComboBox = dynamic_cast<QComboBox*>(editor); QString strSetContent; if(pComboBox) { strSetContent = pComboBox->currentText(); } model->setData(index, strSetContent, Qt::DisplayRole); } void QComboxDelegate::updateEditorGeometry(QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index) const { editor->setGeometry(option.rect); QComboBox *pComboBox = dynamic_cast<QComboBox*>(editor); if(pComboBox) { pComboBox->showPopup(); } } void QComboxDelegate::setComboxContentList(const QStringList& listComboxContent) { m_listComboxContent = listComboxContent; }
74886d2ce0de36268f8aa9aa4bf823a96127126f
8532c19a38aab7a3a9f4a73a097613d59af31f7a
/Enchantment.cc
eaa81463b59ce5f4a10acda7cd95201734601dcf
[]
no_license
a879120315/Sorcery
9b7da4a8c19c741bf79bdb611b874339faee2741
9866211268f2792b536276c16baeab31d75fe0b6
refs/heads/master
2020-04-30T20:05:18.346700
2018-12-03T18:53:55
2018-12-03T18:53:55
175,076,108
0
0
null
null
null
null
UTF-8
C++
false
false
4,283
cc
// // Created by jason on 2018-11-20. // #include "Enchantment.h" #include "Minion.h" #include <iostream> Enchantment::Enchantment(int cost, std::string att, std::string def, std::string name, std::string description, bool hasAttDef) : Card(cost, name, description),hasAttDef{hasAttDef}, att{att}, def{def} { } void Enchantment::effect(Player &player, Player &otherPlayer) {} bool Enchantment::hasStats() { return hasAttDef; } bool Enchantment::canPlay(Player &) { return true; } std::string Enchantment::getAtt() { return att; } std::string Enchantment::getDef() { return def; } //------------------------------------Giant Strength----------------------------------------------------------------- GiantStrength::GiantStrength() : Enchantment(1, "+2" , "+2", "Giant Strength", "", true) {} void GiantStrength::effect(Player &player, Player &targetPlayer, Player &otherPlayer, Card &targetCard) { auto &minion = dynamic_cast<Minion &>(targetCard); minion.mutateAtt(2); minion.mutateDef(2); } void GiantStrength::removeEnchantment(Minion &minion) { minion.mutateAtt(-2); if(minion.getDef() - 2 > 0){ minion.mutateDef(-2); }else{ minion.mutateDef(-minion.getDef() + 1); } } //------------------------------------Enlarge----------------------------------------------------------------- Enrage::Enrage() : Enchantment(2, "*2", "*2", "Enrage", "", true) {} void Enrage::effect(Player &player, Player &targetPlayer, Player &otherPlayer, Card &targetCard) { auto &minion = dynamic_cast<Minion &>(targetCard); minion.mutateAtt(minion.getAtt()); // doubles the attack minion.mutateDef(minion.getDef()); // doubles the defense } void Enrage::removeEnchantment(Minion &minion) { minion.mutateAtt(-minion.getAtt() / 2); if(minion.getDef() / 2 > 0){ minion.mutateDef(-minion.getDef() / 2); }else{ minion.mutateDef(-minion.getDef() + 1); } } //------------------------------------Haste----------------------------------------------------------------- Haste::Haste() : Enchantment(1, "", "", "Haste", "Enchanted minion gains +1 action each turn", false) {} void Haste::effect(Player &player, Player &targetPlayer, Player &otherPlayer, Card &card) { auto &m = dynamic_cast<Minion &>(card); m.setActionValue(m.getActionValue() + 1); m.setRecordActionValue(m.getActionValue() + 1); } void Haste::removeEnchantment(Minion &minion) { minion.setRecordActionValue(minion.getRecordActionValue() - 1); minion.setActionValue(minion.getActionValue() - 1); } //------------------------------------Magic Fatigue----------------------------------------------------------------- MagicFatigue::MagicFatigue() : Enchantment(0, "", "", "Magic Fatigue", "Enchanted minion's activated ability costs 2 more", false) {} void MagicFatigue::effect(Player &player, Player &targetPlayer, Player &otherPlayer, Card &card) { auto &m = dynamic_cast<Minion &>(card); if(m.hasAbility()){ m.setMagic(m.getMagic() + 2); }else{ std::cout << m.getName() << " does not have ability, Magic Fatigue will only remain as an Enchantment" << std::endl; } } void MagicFatigue::removeEnchantment(Minion &minion) { minion.setMagic(minion.getMagic() - 2); } //------------------------------------Silence----------------------------------------------------------------- Silence::Silence() : Enchantment(1, "", "", "Silence", "Enchanted minion cannot use abilities", false) {} void Silence::effect(Player &player, Player &targetPlayer, Player &otherPlayer, Card &card) { auto &m = dynamic_cast<Minion &>(card); m.setSilence(m.getSilence() + 1); } void Silence::removeEnchantment(Minion &minion) { minion.setSilence(minion.getSilence() - 1); } //------------------------------------HunterMark----------------------------------------------------------------- HunterMark::HunterMark(): Enchantment(2,"","","Hunter's Mark","Change a minion's health to 1",false) {} void HunterMark::effect(Player &player, Player &targetPlayer, Player &otherPlayer, Card &card) { auto &m = dynamic_cast<Minion &>(card); this->recordDef = m.getDef(); m.mutateDef(-m.getDef()+1); } void HunterMark::removeEnchantment(Minion &minion) { minion.mutateDef(this->recordDef - 1); }
433b31d0d6728392402443cc4b8c2310363c47a9
2d743169a19328de3a1e2209d338ee00a97e1eb8
/src/cropeditor/drawing/arrowitem.hpp
c43be3f10445a3f6b260814bbe0942dbad12fecd
[ "MIT" ]
permissive
Gurkengewuerz/KShare
c3a5a76e9cecdbef3760c50b488ebb3c01eb1509
befc5e5446fde1c2c4c0e3cbed4c89254a5fc0d2
refs/heads/master
2021-07-25T19:47:52.548625
2020-06-05T13:51:58
2020-06-05T13:51:58
185,391,751
17
3
MIT
2020-06-05T13:52:00
2019-05-07T11:54:48
C++
UTF-8
C++
false
false
478
hpp
#ifndef ARROWITEM_HPP #define ARROWITEM_HPP #include "drawitem.hpp" class ArrowItem : public DrawItem { public: ArrowItem() { } QString name() override { return "Arrow"; } void mouseDragEvent(QGraphicsSceneMouseEvent *, CropScene *scene) override; void mouseDragEndEvent(QGraphicsSceneMouseEvent *, CropScene *) override { } private: QGraphicsLineItem *line; QGraphicsPathItem *head; QPointF init; }; #endif // ARROWITEM_HPP
4933341d26f1f907a01a5e4eea4b601a8469e08c
d34960c2d9a84ad0639005b86d79b3a0553292ab
/boost/boost/type_traits/is_float.hpp
3ef460987917b5686b373aae592b61fcc51965b6
[ "BSL-1.0", "Apache-2.0" ]
permissive
tonystone/geofeatures
413c13ebd47ee6676196399d47f5e23ba5345287
25aca530a9140b3f259e9ee0833c93522e83a697
refs/heads/master
2020-04-09T12:44:36.472701
2019-03-17T01:37:55
2019-03-17T01:37:55
41,232,751
28
9
NOASSERTION
2019-03-17T01:37:56
2015-08-23T02:35:40
C++
UTF-8
C++
false
false
1,089
hpp
// (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000. // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). // // See http://www.boost.org/libs/type_traits for most recent version including documentation. #ifndef BOOST_TYPE_TRAITS_IS_FLOAT_HPP_INCLUDED #define BOOST_TYPE_TRAITS_IS_FLOAT_HPP_INCLUDED // should be the last #include #include <boost/type_traits/detail/bool_trait_def.hpp> namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { //* is a type T a floating-point type described in the standard (3.9.1p8) BOOST_TT_AUX_BOOL_TRAIT_DEF1(is_float,T,false) BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_float,float,true) BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_float,double,true) BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_float,long double,true) } // namespace geofeatures_boost #include <boost/type_traits/detail/bool_trait_undef.hpp> #endif // BOOST_TYPE_TRAITS_IS_FLOAT_HPP_INCLUDED
655155e4f9cee05c14e975bccd543adcd1f4246a
bb285e1849703530e40bfa39109d440b80b9cc88
/0023_Merge_K_Sorted_Lists/Solution.cpp
4b80f44373f4443c9760c52121d5fb61363a9aa1
[]
no_license
kkoala0864/LeetCode
43fe84a63af1605a3034b072f4cd26683af1fd85
386f8f17a5507f3940ad1621fd36d2ae98950727
refs/heads/master
2023-07-14T12:49:04.735378
2021-08-15T08:17:04
2021-08-15T08:17:04
33,233,776
0
0
null
null
null
null
UTF-8
C++
false
false
1,332
cpp
#include <Solution.h> #include <iostream> #include <queue> using namespace std; void print(ListNode* input) { while (input) { cout << input->val << " "; input = input->next; } cout << endl; } ListNode* Solution::mergeKLists(vector<ListNode*>& lists) { if (lists.empty()) return nullptr; queue<ListNode*> que; for (const auto& val : lists) { if (val) que.emplace(val); } queue<ListNode*> nextLV; while (!que.empty()) { if (que.size() == 1) { if (nextLV.empty()) { return que.front(); } else { nextLV.emplace(que.front()); que = move(nextLV); continue; } } ListNode* list1 = que.front(); que.pop(); ListNode* list2 = que.front(); que.pop(); ListNode* retHead = nullptr; ListNode* appendIter = retHead; while (list1 && list2) { if (retHead) { if (list1->val < list2->val) { appendIter->next = list1; list1 = list1->next; } else { appendIter->next = list2; list2 = list2->next; } appendIter = appendIter->next; } else { retHead = list1->val < list2->val ? list1 : list2; retHead == list1 ? list1 = list1->next : list2 = list2->next; appendIter = retHead; } } appendIter->next = list1 ? list1 : list2; nextLV.emplace(retHead); if (que.empty()) { que = move(nextLV); } } return nullptr; }
d062bb75a1464ec1ed11f002e3b9a1877d4f201f
de74af41eaec84c9e86d97034e626ef00a6b2c9e
/rocket-shooter-android/jni/src/Ship.cpp
a7dd91eb460a6faef2bacca5e6c389e23d04f529
[ "MIT" ]
permissive
Azure-poobalan/Space-Game
70a8fd0f29c98b7557c41b29aef198e456147d82
de064b374ca910a97abcfba3433c8b41ae0be3dd
refs/heads/master
2021-12-06T05:54:56.062907
2015-10-09T10:42:33
2015-10-09T10:42:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
21
cpp
../../../src/Ship.cpp
d1764211e0a828189993cd846614ef29bfe04306
ea7f5968513fea3331cb4c7c87e5e397d610541b
/thePerv/Round95/q5.cpp
756f0cb8973fd122d9c7378d3e8e7c902b880415
[]
no_license
uWaterloo-IEEE-StudentBranch/CodeForces
7210c2cf6eed3f5b8e4257d8f490d35f213338b7
8e8594938daa4ef94b4705e993dc5ef69992df94
refs/heads/master
2021-01-01T06:38:17.575923
2012-05-28T13:14:19
2012-05-28T13:14:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,332
cpp
#include <iostream> #include <vector> #include <algorithm> #include <cstdio> #include <cstdlib> #include <string> #include <fstream> #include <cmath> #include <iomanip> #include <set> #include <map> #include <queue> using namespace std; int main(int argc, char const* argv[]){ int dx[] = {0,1,1,1,0,-1,-1,-1}; int dy[] = {1,1,0,-1,-1,-1,0,1}; int n, m; cin >> n >> m; int board[n][n]; //bool threaten[m][m]; //if threaten[i][j], then threaten[j][i]. threaten[i][i] = false always int queen[m][3]; int ans[9] = {0}; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) board[i][j] = -1; //for(int i = 0; i < m; i++) // for(int j = 0; j < m; j++) // threaten[i][j] = false; for(unsigned int i = 0; i < m; i += 1){ int r, c; cin >> r >> c; r--; c--; board[r][c] = i; queen[i][0] = r; queen[i][1] = c; queen[i][2] = 0; } //cout << "loaded" << endl; //cout << "n : " << n << " m: " << m << endl; //detect threatened queens for(int z = 0; z < m; z++){ //cout << "queen: " << z << endl; for(int a = 0; a < 8; a++){ //cout << "accessing queen" << endl; int r = queen[z][0]; int c = queen[z][1]; while(r < n && c < n && r >= 0 && c >= 0){ r += dx[a]; c += dy[a]; if(!(r < n && c < n && r >= 0 && c >= 0)) break; //cout << "at: " << r << ", " << c << endl; if(board[r][c] != -1){ queen[z][2]++; //threaten break; } } } } /* for(int z = 0; z < n; z++){ for(int w = 0; w < n; w++){ cout << board[z][w] << " "; } cout << endl; } for(int z = 0; z < m; z++){ for(int w = 0; w < m; w++){ cout << threaten[z][w] << " "; } cout << endl; } */ for(int z = 0; z < m; z++){ ans[queen[z][2]]++; } for(int i = 0; i < 9; i++) cout << ans[i] << " "; cout << endl; return 0; }
4348e5b7625e52f2efdd98c067b14173f4781ce0
cfee8d64efaf907df32e56e41801d851b656764c
/modules/gpu/perf_cpu/perf_imgproc.cpp
9a1adde81090fb1e2e80624c98c2951058873629
[]
no_license
jkammerl/opencv
edf96c61bc88ed228ecd2e5925a4434c7906da78
27c2aa3a4ed54b4dfc391f441e0e071a9253e62d
refs/heads/master
2020-11-30T16:22:08.806574
2012-08-02T12:25:30
2012-08-02T12:25:30
5,273,790
1
0
null
null
null
null
UTF-8
C++
false
false
22,175
cpp
#include "perf_cpu_precomp.hpp" #ifdef HAVE_CUDA ////////////////////////////////////////////////////////////////////// // Remap GPU_PERF_TEST(Remap, cv::gpu::DeviceInfo, cv::Size, MatType, Interpolation, BorderMode) { cv::Size size = GET_PARAM(1); int type = GET_PARAM(2); int interpolation = GET_PARAM(3); int borderMode = GET_PARAM(4); cv::Mat src(size, type); fill(src, 0, 255); cv::Mat xmap(size, CV_32FC1); fill(xmap, 0, size.width); cv::Mat ymap(size, CV_32FC1); fill(ymap, 0, size.height); cv::Mat dst; cv::remap(src, dst, xmap, ymap, interpolation, borderMode); declare.time(20.0); TEST_CYCLE() { cv::remap(src, dst, xmap, ymap, interpolation, borderMode); } } INSTANTIATE_TEST_CASE_P(ImgProc, Remap, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES, testing::Values(MatType(CV_8UC1), MatType(CV_8UC3), MatType(CV_8UC4), MatType(CV_16UC1), MatType(CV_16UC3), MatType(CV_16UC4), MatType(CV_32FC1), MatType(CV_32FC3), MatType(CV_32FC4)), testing::Values(Interpolation(cv::INTER_NEAREST), Interpolation(cv::INTER_LINEAR), Interpolation(cv::INTER_CUBIC)), testing::Values(BorderMode(cv::BORDER_REFLECT101), BorderMode(cv::BORDER_REPLICATE), BorderMode(cv::BORDER_CONSTANT), BorderMode(cv::BORDER_REFLECT), BorderMode(cv::BORDER_WRAP)))); ////////////////////////////////////////////////////////////////////// // Resize IMPLEMENT_PARAM_CLASS(Scale, double) GPU_PERF_TEST(Resize, cv::gpu::DeviceInfo, cv::Size, MatType, Interpolation, Scale) { cv::Size size = GET_PARAM(1); int type = GET_PARAM(2); int interpolation = GET_PARAM(3); double f = GET_PARAM(4); cv::Mat src(size, type); fill(src, 0, 255); cv::Mat dst; cv::resize(src, dst, cv::Size(), f, f, interpolation); declare.time(20.0); TEST_CYCLE() { cv::resize(src, dst, cv::Size(), f, f, interpolation); } } INSTANTIATE_TEST_CASE_P(ImgProc, Resize, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES, testing::Values(MatType(CV_8UC1), MatType(CV_8UC3), MatType(CV_8UC4), MatType(CV_16UC1), MatType(CV_16UC3), MatType(CV_16UC4), MatType(CV_32FC1), MatType(CV_32FC3), MatType(CV_32FC4)), testing::Values(Interpolation(cv::INTER_NEAREST), Interpolation(cv::INTER_LINEAR), Interpolation(cv::INTER_CUBIC), Interpolation(cv::INTER_AREA)), testing::Values(Scale(0.5), Scale(0.3), Scale(2.0)))); GPU_PERF_TEST(ResizeArea, cv::gpu::DeviceInfo, cv::Size, MatType, Scale) { cv::Size size = GET_PARAM(1); int type = GET_PARAM(2); int interpolation = cv::INTER_AREA; double f = GET_PARAM(3); cv::Mat src_host(size, type); fill(src_host, 0, 255); cv::Mat src(src_host); cv::Mat dst; cv::resize(src, dst, cv::Size(), f, f, interpolation); declare.time(1.0); TEST_CYCLE() { cv::resize(src, dst, cv::Size(), f, f, interpolation); } } INSTANTIATE_TEST_CASE_P(ImgProc, ResizeArea, testing::Combine( ALL_DEVICES, testing::Values(perf::sz1080p, cv::Size(4096, 2048)), testing::Values(MatType(CV_8UC1)/*, MatType(CV_8UC3), MatType(CV_8UC4), MatType(CV_16UC1), MatType(CV_16UC3), MatType(CV_16UC4), MatType(CV_32FC1), MatType(CV_32FC3), MatType(CV_32FC4)*/), testing::Values(Scale(0.2),Scale(0.1),Scale(0.05)))); ////////////////////////////////////////////////////////////////////// // WarpAffine GPU_PERF_TEST(WarpAffine, cv::gpu::DeviceInfo, cv::Size, MatType, Interpolation, BorderMode) { cv::Size size = GET_PARAM(1); int type = GET_PARAM(2); int interpolation = GET_PARAM(3); int borderMode = GET_PARAM(4); cv::Mat src(size, type); fill(src, 0, 255); cv::Mat dst; const double aplha = CV_PI / 4; double mat[2][3] = { {std::cos(aplha), -std::sin(aplha), src.cols / 2}, {std::sin(aplha), std::cos(aplha), 0}}; cv::Mat M(2, 3, CV_64F, (void*) mat); cv::warpAffine(src, dst, M, size, interpolation, borderMode); declare.time(20.0); TEST_CYCLE() { cv::warpAffine(src, dst, M, size, interpolation, borderMode); } } INSTANTIATE_TEST_CASE_P(ImgProc, WarpAffine, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES, testing::Values(MatType(CV_8UC1), MatType(CV_8UC3), MatType(CV_8UC4), MatType(CV_16UC1), MatType(CV_16UC3), MatType(CV_16UC4), MatType(CV_32FC1), MatType(CV_32FC3), MatType(CV_32FC4)), testing::Values(Interpolation(cv::INTER_NEAREST), Interpolation(cv::INTER_LINEAR), Interpolation(cv::INTER_CUBIC)), testing::Values(BorderMode(cv::BORDER_REFLECT101), BorderMode(cv::BORDER_REPLICATE), BorderMode(cv::BORDER_CONSTANT), BorderMode(cv::BORDER_REFLECT), BorderMode(cv::BORDER_WRAP)))); ////////////////////////////////////////////////////////////////////// // WarpPerspective GPU_PERF_TEST(WarpPerspective, cv::gpu::DeviceInfo, cv::Size, MatType, Interpolation, BorderMode) { cv::Size size = GET_PARAM(1); int type = GET_PARAM(2); int interpolation = GET_PARAM(3); int borderMode = GET_PARAM(4); cv::Mat src(size, type); fill(src, 0, 255); cv::Mat dst; const double aplha = CV_PI / 4; double mat[3][3] = { {std::cos(aplha), -std::sin(aplha), src.cols / 2}, {std::sin(aplha), std::cos(aplha), 0}, {0.0, 0.0, 1.0}}; cv::Mat M(3, 3, CV_64F, (void*) mat); cv::warpPerspective(src, dst, M, size, interpolation, borderMode); declare.time(20.0); TEST_CYCLE() { cv::warpPerspective(src, dst, M, size, interpolation, borderMode); } } INSTANTIATE_TEST_CASE_P(ImgProc, WarpPerspective, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES, testing::Values(MatType(CV_8UC1), MatType(CV_8UC3), MatType(CV_8UC4), MatType(CV_16UC1), MatType(CV_16UC3), MatType(CV_16UC4), MatType(CV_32FC1), MatType(CV_32FC3), MatType(CV_32FC4)), testing::Values(Interpolation(cv::INTER_NEAREST), Interpolation(cv::INTER_LINEAR), Interpolation(cv::INTER_CUBIC)), testing::Values(BorderMode(cv::BORDER_REFLECT101), BorderMode(cv::BORDER_REPLICATE), BorderMode(cv::BORDER_CONSTANT), BorderMode(cv::BORDER_REFLECT), BorderMode(cv::BORDER_WRAP)))); ////////////////////////////////////////////////////////////////////// // CopyMakeBorder GPU_PERF_TEST(CopyMakeBorder, cv::gpu::DeviceInfo, cv::Size, MatType, BorderMode) { cv::Size size = GET_PARAM(1); int type = GET_PARAM(2); int borderType = GET_PARAM(3); cv::Mat src(size, type); fill(src, 0, 255); cv::Mat dst; cv::copyMakeBorder(src, dst, 5, 5, 5, 5, borderType); TEST_CYCLE() { cv::copyMakeBorder(src, dst, 5, 5, 5, 5, borderType); } } INSTANTIATE_TEST_CASE_P(ImgProc, CopyMakeBorder, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES, testing::Values(MatType(CV_8UC1), MatType(CV_8UC3), MatType(CV_8UC4), MatType(CV_16UC1), MatType(CV_16UC3), MatType(CV_16UC4), MatType(CV_32FC1), MatType(CV_32FC3), MatType(CV_32FC4)), testing::Values(BorderMode(cv::BORDER_REFLECT101), BorderMode(cv::BORDER_REPLICATE), BorderMode(cv::BORDER_CONSTANT), BorderMode(cv::BORDER_REFLECT), BorderMode(cv::BORDER_WRAP)))); ////////////////////////////////////////////////////////////////////// // Threshold CV_ENUM(ThreshOp, cv::THRESH_BINARY, cv::THRESH_BINARY_INV, cv::THRESH_TRUNC, cv::THRESH_TOZERO, cv::THRESH_TOZERO_INV) #define ALL_THRESH_OPS testing::Values(ThreshOp(cv::THRESH_BINARY), ThreshOp(cv::THRESH_BINARY_INV), ThreshOp(cv::THRESH_TRUNC), ThreshOp(cv::THRESH_TOZERO), ThreshOp(cv::THRESH_TOZERO_INV)) GPU_PERF_TEST(Threshold, cv::gpu::DeviceInfo, cv::Size, MatDepth, ThreshOp) { cv::Size size = GET_PARAM(1); int depth = GET_PARAM(2); int threshOp = GET_PARAM(3); cv::Mat src(size, depth); fill(src, 0, 255); cv::Mat dst; cv::threshold(src, dst, 100.0, 255.0, threshOp); TEST_CYCLE() { cv::threshold(src, dst, 100.0, 255.0, threshOp); } } INSTANTIATE_TEST_CASE_P(ImgProc, Threshold, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES, testing::Values(MatDepth(CV_8U), MatDepth(CV_16U), MatDepth(CV_32F), MatDepth(CV_64F)), ALL_THRESH_OPS)); ////////////////////////////////////////////////////////////////////// // Integral GPU_PERF_TEST(Integral, cv::gpu::DeviceInfo, cv::Size) { cv::Size size = GET_PARAM(1); cv::Mat src(size, CV_8UC1); fill(src, 0, 255); cv::Mat dst; cv::integral(src, dst); TEST_CYCLE() { cv::integral(src, dst); } } INSTANTIATE_TEST_CASE_P(ImgProc, Integral, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES)); ////////////////////////////////////////////////////////////////////// // HistEven_OneChannel GPU_PERF_TEST(HistEven_OneChannel, cv::gpu::DeviceInfo, cv::Size, MatDepth) { cv::Size size = GET_PARAM(1); int depth = GET_PARAM(2); cv::Mat src(size, depth); fill(src, 0, 255); int hbins = 30; float hranges[] = {0.0f, 180.0f}; cv::Mat hist; int histSize[] = {hbins}; const float* ranges[] = {hranges}; int channels[] = {0}; cv::calcHist(&src, 1, channels, cv::Mat(), hist, 1, histSize, ranges); TEST_CYCLE() { cv::calcHist(&src, 1, channels, cv::Mat(), hist, 1, histSize, ranges); } } INSTANTIATE_TEST_CASE_P(ImgProc, HistEven_OneChannel, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES, testing::Values(MatDepth(CV_8U), MatDepth(CV_16U), MatDepth(CV_16S)))); ////////////////////////////////////////////////////////////////////// // EqualizeHist GPU_PERF_TEST(EqualizeHist, cv::gpu::DeviceInfo, cv::Size) { cv::Size size = GET_PARAM(1); cv::Mat src(size, CV_8UC1); fill(src, 0, 255); cv::Mat dst; cv::equalizeHist(src, dst); TEST_CYCLE() { cv::equalizeHist(src, dst); } } INSTANTIATE_TEST_CASE_P(ImgProc, EqualizeHist, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES)); ////////////////////////////////////////////////////////////////////// // Canny IMPLEMENT_PARAM_CLASS(AppertureSize, int) IMPLEMENT_PARAM_CLASS(L2gradient, bool) GPU_PERF_TEST(Canny, cv::gpu::DeviceInfo, AppertureSize, L2gradient) { int apperture_size = GET_PARAM(1); bool useL2gradient = GET_PARAM(2); cv::Mat image = readImage("perf/1280x1024.jpg", cv::IMREAD_GRAYSCALE); ASSERT_FALSE(image.empty()); cv::Mat dst; cv::Canny(image, dst, 50.0, 100.0, apperture_size, useL2gradient); TEST_CYCLE() { cv::Canny(image, dst, 50.0, 100.0, apperture_size, useL2gradient); } } INSTANTIATE_TEST_CASE_P(ImgProc, Canny, testing::Combine( ALL_DEVICES, testing::Values(AppertureSize(3), AppertureSize(5)), testing::Values(L2gradient(false), L2gradient(true)))); ////////////////////////////////////////////////////////////////////// // MeanShiftFiltering GPU_PERF_TEST_1(MeanShiftFiltering, cv::gpu::DeviceInfo) { cv::Mat img = readImage("gpu/meanshift/cones.png"); ASSERT_FALSE(img.empty()); cv::Mat dst; cv::pyrMeanShiftFiltering(img, dst, 50, 50); declare.time(15.0); TEST_CYCLE() { cv::pyrMeanShiftFiltering(img, dst, 50, 50); } } INSTANTIATE_TEST_CASE_P(ImgProc, MeanShiftFiltering, ALL_DEVICES); ////////////////////////////////////////////////////////////////////// // Convolve IMPLEMENT_PARAM_CLASS(KSize, int) IMPLEMENT_PARAM_CLASS(Ccorr, bool) GPU_PERF_TEST(Convolve, cv::gpu::DeviceInfo, cv::Size, KSize, Ccorr) { cv::Size size = GET_PARAM(1); int templ_size = GET_PARAM(2); bool ccorr = GET_PARAM(3); ASSERT_FALSE(ccorr); cv::Mat image(size, CV_32FC1); image.setTo(1.0); cv::Mat templ(templ_size, templ_size, CV_32FC1); templ.setTo(1.0); cv::Mat dst; cv::filter2D(image, dst, image.depth(), templ); declare.time(10.0); TEST_CYCLE() { cv::filter2D(image, dst, image.depth(), templ); } } INSTANTIATE_TEST_CASE_P(ImgProc, Convolve, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES, testing::Values(KSize(3), KSize(9), KSize(17), KSize(27), KSize(32), KSize(64)), testing::Values(Ccorr(false), Ccorr(true)))); //////////////////////////////////////////////////////////////////////////////// // MatchTemplate_8U CV_ENUM(TemplateMethod, cv::TM_SQDIFF, cv::TM_SQDIFF_NORMED, cv::TM_CCORR, cv::TM_CCORR_NORMED, cv::TM_CCOEFF, cv::TM_CCOEFF_NORMED) #define ALL_TEMPLATE_METHODS testing::Values(TemplateMethod(cv::TM_SQDIFF), TemplateMethod(cv::TM_SQDIFF_NORMED), TemplateMethod(cv::TM_CCORR), TemplateMethod(cv::TM_CCORR_NORMED), TemplateMethod(cv::TM_CCOEFF), TemplateMethod(cv::TM_CCOEFF_NORMED)) IMPLEMENT_PARAM_CLASS(TemplateSize, cv::Size) GPU_PERF_TEST(MatchTemplate_8U, cv::gpu::DeviceInfo, cv::Size, TemplateSize, Channels, TemplateMethod) { cv::Size size = GET_PARAM(1); cv::Size templ_size = GET_PARAM(2); int cn = GET_PARAM(3); int method = GET_PARAM(4); cv::Mat image(size, CV_MAKE_TYPE(CV_8U, cn)); fill(image, 0, 255); cv::Mat templ(templ_size, CV_MAKE_TYPE(CV_8U, cn)); fill(templ, 0, 255); cv::Mat dst; cv::matchTemplate(image, templ, dst, method); TEST_CYCLE() { cv::matchTemplate(image, templ, dst, method); } }; INSTANTIATE_TEST_CASE_P(ImgProc, MatchTemplate_8U, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES, testing::Values(TemplateSize(cv::Size(5, 5)), TemplateSize(cv::Size(16, 16)), TemplateSize(cv::Size(30, 30))), testing::Values(Channels(1), Channels(3), Channels(4)), ALL_TEMPLATE_METHODS)); //////////////////////////////////////////////////////////////////////////////// // MatchTemplate_32F GPU_PERF_TEST(MatchTemplate_32F, cv::gpu::DeviceInfo, cv::Size, TemplateSize, Channels, TemplateMethod) { cv::Size size = GET_PARAM(1); cv::Size templ_size = GET_PARAM(2); int cn = GET_PARAM(3); int method = GET_PARAM(4); cv::Mat image(size, CV_MAKE_TYPE(CV_32F, cn)); fill(image, 0, 255); cv::Mat templ(templ_size, CV_MAKE_TYPE(CV_32F, cn)); fill(templ, 0, 255); cv::Mat dst; cv::matchTemplate(image, templ, dst, method); TEST_CYCLE() { cv::matchTemplate(image, templ, dst, method); } }; INSTANTIATE_TEST_CASE_P(ImgProc, MatchTemplate_32F, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES, testing::Values(TemplateSize(cv::Size(5, 5)), TemplateSize(cv::Size(16, 16)), TemplateSize(cv::Size(30, 30))), testing::Values(Channels(1), Channels(3), Channels(4)), testing::Values(TemplateMethod(cv::TM_SQDIFF), TemplateMethod(cv::TM_CCORR)))); ////////////////////////////////////////////////////////////////////// // MulSpectrums CV_FLAGS(DftFlags, 0, cv::DFT_INVERSE, cv::DFT_SCALE, cv::DFT_ROWS, cv::DFT_COMPLEX_OUTPUT, cv::DFT_REAL_OUTPUT) GPU_PERF_TEST(MulSpectrums, cv::gpu::DeviceInfo, cv::Size, DftFlags) { cv::Size size = GET_PARAM(1); int flag = GET_PARAM(2); cv::Mat a(size, CV_32FC2); fill(a, 0, 100); cv::Mat b(size, CV_32FC2); fill(b, 0, 100); cv::Mat dst; cv::mulSpectrums(a, b, dst, flag); TEST_CYCLE() { cv::mulSpectrums(a, b, dst, flag); } } INSTANTIATE_TEST_CASE_P(ImgProc, MulSpectrums, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES, testing::Values(DftFlags(0), DftFlags(cv::DFT_ROWS)))); ////////////////////////////////////////////////////////////////////// // Dft GPU_PERF_TEST(Dft, cv::gpu::DeviceInfo, cv::Size, DftFlags) { cv::Size size = GET_PARAM(1); int flag = GET_PARAM(2); cv::Mat src(size, CV_32FC2); fill(src, 0, 100); cv::Mat dst; cv::dft(src, dst, flag); declare.time(10.0); TEST_CYCLE() { cv::dft(src, dst, flag); } } INSTANTIATE_TEST_CASE_P(ImgProc, Dft, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES, testing::Values(DftFlags(0), DftFlags(cv::DFT_ROWS), DftFlags(cv::DFT_INVERSE)))); ////////////////////////////////////////////////////////////////////// // CornerHarris IMPLEMENT_PARAM_CLASS(BlockSize, int) IMPLEMENT_PARAM_CLASS(ApertureSize, int) GPU_PERF_TEST(CornerHarris, cv::gpu::DeviceInfo, MatType, BorderMode, BlockSize, ApertureSize) { int type = GET_PARAM(1); int borderType = GET_PARAM(2); int blockSize = GET_PARAM(3); int apertureSize = GET_PARAM(4); cv::Mat img = readImage("gpu/stereobm/aloe-L.png", cv::IMREAD_GRAYSCALE); ASSERT_FALSE(img.empty()); img.convertTo(img, type, type == CV_32F ? 1.0 / 255.0 : 1.0); cv::Mat dst; double k = 0.5; cv::cornerHarris(img, dst, blockSize, apertureSize, k, borderType); TEST_CYCLE() { cv::cornerHarris(img, dst, blockSize, apertureSize, k, borderType); } } INSTANTIATE_TEST_CASE_P(ImgProc, CornerHarris, testing::Combine( ALL_DEVICES, testing::Values(MatType(CV_8UC1), MatType(CV_32FC1)), testing::Values(BorderMode(cv::BORDER_REFLECT101), BorderMode(cv::BORDER_REPLICATE), BorderMode(cv::BORDER_REFLECT)), testing::Values(BlockSize(3), BlockSize(5), BlockSize(7)), testing::Values(ApertureSize(0), ApertureSize(3), ApertureSize(5), ApertureSize(7)))); ////////////////////////////////////////////////////////////////////// // CornerMinEigenVal GPU_PERF_TEST(CornerMinEigenVal, cv::gpu::DeviceInfo, MatType, BorderMode, BlockSize, ApertureSize) { int type = GET_PARAM(1); int borderType = GET_PARAM(2); int blockSize = GET_PARAM(3); int apertureSize = GET_PARAM(4); cv::Mat img = readImage("gpu/stereobm/aloe-L.png", cv::IMREAD_GRAYSCALE); ASSERT_FALSE(img.empty()); img.convertTo(img, type, type == CV_32F ? 1.0 / 255.0 : 1.0); cv::Mat dst; cv::cornerMinEigenVal(img, dst, blockSize, apertureSize, borderType); TEST_CYCLE() { cv::cornerMinEigenVal(img, dst, blockSize, apertureSize, borderType); } } INSTANTIATE_TEST_CASE_P(ImgProc, CornerMinEigenVal, testing::Combine( ALL_DEVICES, testing::Values(MatType(CV_8UC1), MatType(CV_32FC1)), testing::Values(BorderMode(cv::BORDER_REFLECT101), BorderMode(cv::BORDER_REPLICATE), BorderMode(cv::BORDER_REFLECT)), testing::Values(BlockSize(3), BlockSize(5), BlockSize(7)), testing::Values(ApertureSize(0), ApertureSize(3), ApertureSize(5), ApertureSize(7)))); ////////////////////////////////////////////////////////////////////// // PyrDown GPU_PERF_TEST(PyrDown, cv::gpu::DeviceInfo, cv::Size, MatType) { cv::Size size = GET_PARAM(1); int type = GET_PARAM(2); cv::Mat src(size, type); fill(src, 0, 255); cv::Mat dst; cv::pyrDown(src, dst); TEST_CYCLE() { cv::pyrDown(src, dst); } } INSTANTIATE_TEST_CASE_P(ImgProc, PyrDown, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES, testing::Values(MatType(CV_8UC1), MatType(CV_8UC3), MatType(CV_8UC4), MatType(CV_16UC1), MatType(CV_16UC3), MatType(CV_16UC4), MatType(CV_32FC1), MatType(CV_32FC3), MatType(CV_32FC4)))); ////////////////////////////////////////////////////////////////////// // PyrUp GPU_PERF_TEST(PyrUp, cv::gpu::DeviceInfo, cv::Size, MatType) { cv::Size size = GET_PARAM(1); int type = GET_PARAM(2); cv::Mat src(size, type); fill(src, 0, 255); cv::Mat dst; cv::pyrUp(src, dst); TEST_CYCLE() { cv::pyrUp(src, dst); } } INSTANTIATE_TEST_CASE_P(ImgProc, PyrUp, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES, testing::Values(MatType(CV_8UC1), MatType(CV_8UC3), MatType(CV_8UC4), MatType(CV_16UC1), MatType(CV_16UC3), MatType(CV_16UC4), MatType(CV_32FC1), MatType(CV_32FC3), MatType(CV_32FC4)))); ////////////////////////////////////////////////////////////////////// // CvtColor GPU_PERF_TEST(CvtColor, cv::gpu::DeviceInfo, cv::Size, MatDepth, CvtColorInfo) { cv::Size size = GET_PARAM(1); int depth = GET_PARAM(2); CvtColorInfo info = GET_PARAM(3); cv::Mat src(size, CV_MAKETYPE(depth, info.scn)); fill(src, 0, 255); cv::Mat dst; cv::cvtColor(src, dst, info.code, info.dcn); TEST_CYCLE() { cv::cvtColor(src, dst, info.code, info.dcn); } } INSTANTIATE_TEST_CASE_P(ImgProc, CvtColor, testing::Combine( ALL_DEVICES, GPU_TYPICAL_MAT_SIZES, testing::Values(MatDepth(CV_8U), MatDepth(CV_16U), MatDepth(CV_32F)), testing::Values(CvtColorInfo(4, 4, cv::COLOR_RGBA2BGRA), CvtColorInfo(4, 1, cv::COLOR_BGRA2GRAY), CvtColorInfo(1, 4, cv::COLOR_GRAY2BGRA), CvtColorInfo(3, 3, cv::COLOR_BGR2XYZ), CvtColorInfo(3, 3, cv::COLOR_XYZ2BGR), CvtColorInfo(3, 3, cv::COLOR_BGR2YCrCb), CvtColorInfo(3, 3, cv::COLOR_YCrCb2BGR), CvtColorInfo(3, 3, cv::COLOR_BGR2YUV), CvtColorInfo(3, 3, cv::COLOR_YUV2BGR), CvtColorInfo(3, 3, cv::COLOR_BGR2HSV), CvtColorInfo(3, 3, cv::COLOR_HSV2BGR), CvtColorInfo(3, 3, cv::COLOR_BGR2HLS), CvtColorInfo(3, 3, cv::COLOR_HLS2BGR)))); #endif
[ "no@email" ]
no@email
6b8f2cde586c343d823ebae2ff3bf3ad68c3697c
1be0c003cd2908e3d0151385b2d1991c0419a2da
/include/kernel/pic.h
b8b09d6a757811f5f2b5f39a9806900fe0d0295e
[]
no_license
Insecurity-plan15/bombela-microkernel
6df19ff9010b4e582908dc2cdfbd82fa71c411af
b5f412dcf70a670b2a5f450749db203cfaad2481
refs/heads/master
2021-01-12T19:59:54.417881
2011-02-19T13:00:51
2011-02-19T13:00:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,895
h
/* * pic.h * Copyright © 2010, Alexandre Gau <[email protected]> * Copyright © 2011, François-Xavier 'Bombela' Bourlet <[email protected]> * */ #pragma once #ifndef PIC_H #define PIC_H #include <kernel/types.h> #include <kernel/ioports.h> #include KERNEL_PIC_DEBUG #include KERNEL_PIC_CHECK namespace kernel { namespace pic { class Manager { public: Manager(); ~Manager(); static inline uint8_t int2irq(uint8_t intIdx) { return intIdx - BASE_INT; } static inline uint8_t irq2int(uint8_t irqIdx) { return irqIdx + BASE_INT; } void enable(uint8_t irqIdx) { assert(irqIdx <= 15); assert(irqIdx != 2); // don't touch the master/slave link IRQ2 if (irqIdx < 8) { /* irq on master pic */ _masterMask &= ~(1 << irqIdx); kernel::io::out::byte(_masterMask, PORT2_M); } else { /* irq on slave pic */ _slaveMask &= ~(1 << (irqIdx - 8)); kernel::io::out::byte(_slaveMask, PORT2_S); } dbg("IRQ #%c enabled", irqIdx); } void disable(uint8_t irqIdx) { assert(irqIdx <= 15); assert(irqIdx != 2); // don't touch the master/slave link IRQ2 if (irqIdx < 8) { /* irq on master pic */ _masterMask |= (1 << irqIdx); kernel::io::out::byte(_masterMask, PORT2_M); } else { /* irq on slave pic */ _slaveMask |= (1 << (irqIdx - 8)); kernel::io::out::byte(_slaveMask, PORT2_S); } dbg("IRQ #%c disabled", irqIdx); } void eoi(uint8_t irqIdx) const { assert(irqIdx <= 15); assert(irqIdx != 2); // don't touch the master/slave link IRQ2 dbg("IRQ EOI #%c", irqIdx); if (irqIdx < 8) { /* irq on master pic */ kernel::io::out::byte(EOI, PORT1_M); } else { /* irq on slave pic */ kernel::io::out::byte(EOI, PORT1_S); kernel::io::out::byte(EOI, PORT1_M); } } private: uint8_t _masterMask; uint8_t _slaveMask; static const uint8_t BASE_INT = 32; static const uint16_t PORT1_M = 0x20; static const uint16_t PORT2_M = 0x21; static const uint16_t PORT1_S = 0xA0; static const uint16_t PORT2_S = 0xA1; static const uint8_t ICW1_M = 0x11; // cascaded mode static const uint8_t ICW2_M = Manager::BASE_INT; // Base #INT static const uint8_t ICW3_M = 4; // master, IRQ 2 = PIC slave. static const uint8_t ICW4_M = 1; // intel mode, EOI manuel. static const uint8_t OCW1_M = 0xFB; // full mask but slave static const uint8_t ICW1_S = 0x11; // cascaded mode static const uint8_t ICW2_S = Manager::BASE_INT + 8; // Base #INT static const uint8_t ICW3_S = 2; // slave, connected on master IRQ 2 static const uint8_t ICW4_S = 1; // intel mode, EOI manuel. static const uint8_t OCW1_S = 0xFF; // full mask static const uint8_t EOI = 0x20; // full mask }; } // namespace pic extern pic::Manager picManager; } // namespace kernel #include <check_off.h> #include <debug_off.h> #endif /* PIC_H */
87dd0b69951fe61488efda28f8219b3753ec7719
4ccf45302ca0976de024006536b23899cd136835
/C++/Class1_A.hpp
ea370fe831828b7a550e69dc0e70040d2f4db844
[]
no_license
goeb/reference
ac593e40769bb9dc48a666308fce129243d42c64
fbdf0b961d4209652b1d6e0c7cbf022dbacc9ee0
refs/heads/master
2023-06-26T13:22:12.852398
2023-06-13T19:46:57
2023-06-13T19:46:57
13,687,825
0
2
null
null
null
null
UTF-8
C++
false
false
21
hpp
typdef int intFred;
[ "fred@fred1" ]
fred@fred1
a1d8b3bc451f48d769edca9bea37cbc5704f91fd
0c705398ad8c1ad67de3185aae926f187ba3ae77
/PROJECT/test/gameobject.h
a8bc039e4797d4987c66f51abae27ac8cb20c28d
[]
no_license
qldrnjs2001/cs2018
ba22dd1f2876a66813b4d4347de1e69cb9dc643b
5484789d3c9589e2a93f2d0d4fd0fe362673a94a
refs/heads/master
2021-09-25T22:41:05.623500
2018-07-20T07:12:48
2018-07-20T07:12:48
138,545,533
0
0
null
null
null
null
UTF-8
C++
false
false
1,934
h
#pragma once namespace cs2018prj { struct S_GAMEOBJECT { double m_dbSpeed; irr::core::vector2df m_vPos; double m_dbAngle; double m_dbWorkTick; void *m_pWeapon; tge_sprite::S_SPRITE_OBJECT *m_pSprite; irr::core::vector2df m_translation; int m_nFSM; int m_rnd; bool m_bActive; void *m_pTarget; void(*m_fpApply)(S_GAMEOBJECT *, double); void(*m_fpRender)(S_GAMEOBJECT *, CHAR_INFO *); void(*m_fpClone)(S_GAMEOBJECT *pObj); }; namespace playerObject { struct S_SUBOBJECT { }; void Init(S_GAMEOBJECT *pObj, irr::core::vector2df _pos, double _dbspeed, tge_sprite::S_SPRITE_OBJECT *pSpr); void Apply(S_GAMEOBJECT *pObj, double _deltaTick); void Render(S_GAMEOBJECT *pObj, CHAR_INFO *pTargetBuf); void Activate(S_GAMEOBJECT *pObj); } namespace enemyObject { struct S_SUBOBJECT { }; void Init(S_GAMEOBJECT *pObj, irr::core::vector2df _pos, double _dbspeed, tge_sprite::S_SPRITE_OBJECT *pSpr); void Apply(S_GAMEOBJECT *pObj, double _deltaTick); void Activate(S_GAMEOBJECT *pObj); void createRandomInt(S_GAMEOBJECT *pObj); } namespace attackObject { namespace beam { struct S_SUBOBJECT { }; void Init(S_GAMEOBJECT *pObj, irr::core::vector2df _pos, double _dbspeed, tge_sprite::S_SPRITE_OBJECT *pSpr); void Apply(S_GAMEOBJECT *pObj, double _deltaTick); void Activate(S_GAMEOBJECT *pObj); } namespace fire { void Init(S_GAMEOBJECT *pObj, irr::core::vector2df _pos, double _dbspeed, tge_sprite::S_SPRITE_OBJECT *pSpr); void Apply(S_GAMEOBJECT *pObj, double _deltaTick); void Activate(S_GAMEOBJECT *pObj); } } namespace objMng { struct S_OBJECT_MNG { S_GAMEOBJECT *m_pListObject[1024]; int m_nIndex; }; void add(S_OBJECT_MNG *pObj, S_GAMEOBJECT *pGameObj); void applyAll(S_OBJECT_MNG *pObj, double _deltaTick); void renderAll(S_OBJECT_MNG *pObj, CHAR_INFO *pBuf); void clearAll(S_OBJECT_MNG *pObj); } }
18acedd2998347ef28c65d6f4300b076594214b2
89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04
/media/renderers/skcanvas_video_renderer.h
ff2a9195db5d7dc22fe4b44526642c27f735d119
[ "BSD-3-Clause" ]
permissive
bino7/chromium
8d26f84a1b6e38a73d1b97fea6057c634eff68cb
4666a6bb6fdcb1114afecf77bdaa239d9787b752
refs/heads/master
2022-12-22T14:31:53.913081
2016-09-06T10:05:11
2016-09-06T10:05:11
67,410,510
1
3
BSD-3-Clause
2022-12-17T03:08:52
2016-09-05T10:11:59
null
UTF-8
C++
false
false
4,628
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_RENDERERS_SKCANVAS_VIDEO_RENDERER_H_ #define MEDIA_RENDERERS_SKCANVAS_VIDEO_RENDERER_H_ #include <stddef.h> #include <stdint.h> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/threading/thread_checker.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "media/base/media_export.h" #include "media/base/timestamp_constants.h" #include "media/base/video_frame.h" #include "media/base/video_rotation.h" #include "media/filters/context_3d.h" #include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkRefCnt.h" #include "third_party/skia/include/core/SkXfermode.h" class SkCanvas; class SkImage; namespace gfx { class RectF; } namespace media { class VideoImageGenerator; // Handles rendering of VideoFrames to SkCanvases. class MEDIA_EXPORT SkCanvasVideoRenderer { public: SkCanvasVideoRenderer(); ~SkCanvasVideoRenderer(); // Paints |video_frame| on |canvas|, scaling and rotating the result to fit // dimensions specified by |dest_rect|. // If the format of |video_frame| is PIXEL_FORMAT_NATIVE_TEXTURE, |context_3d| // must be provided. // // Black will be painted on |canvas| if |video_frame| is null. void Paint(const scoped_refptr<VideoFrame>& video_frame, SkCanvas* canvas, const gfx::RectF& dest_rect, uint8_t alpha, SkXfermode::Mode mode, VideoRotation video_rotation, const Context3D& context_3d); // Copy |video_frame| on |canvas|. // If the format of |video_frame| is PIXEL_FORMAT_NATIVE_TEXTURE, |context_3d| // must be provided. void Copy(const scoped_refptr<VideoFrame>& video_frame, SkCanvas* canvas, const Context3D& context_3d); // Convert the contents of |video_frame| to raw RGB pixels. |rgb_pixels| // should point into a buffer large enough to hold as many 32 bit RGBA pixels // as are in the visible_rect() area of the frame. static void ConvertVideoFrameToRGBPixels(const media::VideoFrame* video_frame, void* rgb_pixels, size_t row_bytes); // Copy the contents of texture of |video_frame| to texture |texture|. // |level|, |internal_format|, |type| specify target texture |texture|. // The format of |video_frame| must be VideoFrame::NATIVE_TEXTURE. static void CopyVideoFrameSingleTextureToGLTexture( gpu::gles2::GLES2Interface* gl, VideoFrame* video_frame, unsigned int texture, unsigned int internal_format, unsigned int type, bool premultiply_alpha, bool flip_y); // Copy the contents of texture of |video_frame| to texture |texture| in // context |destination_gl|. // |level|, |internal_format|, |type| specify target texture |texture|. // The format of |video_frame| must be VideoFrame::NATIVE_TEXTURE. // |context_3d| has a GrContext that may be used during the copy. // Returns true on success. bool CopyVideoFrameTexturesToGLTexture( const Context3D& context_3d, gpu::gles2::GLES2Interface* destination_gl, const scoped_refptr<VideoFrame>& video_frame, unsigned int texture, unsigned int internal_format, unsigned int type, bool premultiply_alpha, bool flip_y); // In general, We hold the most recently painted frame to increase the // performance for the case that the same frame needs to be painted // repeatedly. Call this function if you are sure the most recent frame will // never be painted again, so we can release the resource. void ResetCache(); private: // Update the cache holding the most-recently-painted frame. Returns false // if the image couldn't be updated. bool UpdateLastImage(const scoped_refptr<VideoFrame>& video_frame, const Context3D& context_3d); // Last image used to draw to the canvas. sk_sp<SkImage> last_image_; // Timestamp of the videoframe used to generate |last_image_|. base::TimeDelta last_timestamp_ = media::kNoTimestamp; // If |last_image_| is not used for a while, it's deleted to save memory. base::DelayTimer last_image_deleting_timer_; // Used for DCHECKs to ensure method calls executed in the correct thread. base::ThreadChecker thread_checker_; DISALLOW_COPY_AND_ASSIGN(SkCanvasVideoRenderer); }; } // namespace media #endif // MEDIA_RENDERERS_SKCANVAS_VIDEO_RENDERER_H_
bd96faad68585fa078758fc56f3093b1ba881aef
9a369ace9dd8fc47c132b32aec4e50d4a606aaf4
/Pytorch/torchscript.cpp
0b25783725099b27b96f0fc8d706a6cc9b1a0958
[]
no_license
LokeshBonta/Academic-Projects
602cc59029fb3e243fda789df897a271096483d3
eb6af97b7e225f4e0d6d8b81b142af58a44bdbc9
refs/heads/master
2022-10-03T21:05:13.797498
2022-09-17T17:00:11
2022-09-17T17:00:11
227,907,465
0
0
null
2020-07-28T15:02:23
2019-12-13T19:21:41
Jupyter Notebook
UTF-8
C++
false
false
872
cpp
#include <torch/script.h> // One-stop header. #include <iostream> #include <memory> int main(int argc, const char* argv[]) { if (argc != 2) { std::cerr << "usage: example-app <path-to-exported-script-module>\n"; return -1; } torch::jit::script::Module module; try { // Deserialize the ScriptModule from a file using torch::jit::load(). module = torch::jit::load(argv[1]); } catch (const c10::Error& e) { std::cerr << "error loading the model\n"; return -1; } std::cout << "ok\n"; // Create a vector of inputs. std::vector<torch::jit::IValue> inputs; //std::cout << module.graph() << std::endl; inputs.push_back(torch::ones({1, 3, 224, 224})); // Execute the model and turn its output into a tensor. at::Tensor output = module.forward(inputs).toTensor(); std::cout << output.slice(/*dim=*/1, /*start=*/0, /*end=*/5) << '\n'; }
531913273e42994bc7019d7968e8564e747dfe3a
4d14eacf69f9f43b106ac6acc4968cf86c1447ed
/C++ Ess/Chapter2/Lab 2.3/lab 2.3.9.cpp
ecabf49f71eb8ced7813626b2a484fb351f5c2bb
[]
no_license
lizakrishen/Practice-2017-2018
9baf77ffee4dd3b6880fdb41ce3c21cfe1d4087c
4e25ea817f800f4c72f867e35398e7326676b549
refs/heads/master
2021-08-31T00:22:03.162679
2017-12-20T00:17:33
2017-12-20T00:17:33
111,195,992
0
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
#include <iostream> using namespace std; int main() { long value = 1; int number = -1; do { cout << "Please enter the odd value > 1"; cin >> number; cout << "\n"; } while (number < 1 || number % 2 == 0); cout << number * number - 2 * number + 2; return 0; }
cec7c84de8cd86e4f568797d3035b26662cac5bb
3b576d1928bccef56ddf0be455f99800db244e92
/template.cpp
0bee3d7b7fe9cbca87a94d97ba1b7c18a54e42ed
[]
no_license
cRYP70n-13/Data_structures-and-Algorithms
3c843698f5cb1cf2555ac24d1f4b7eaec713db4e
d7a20ef68b319c82a127aa23da39fdf36ef06d9d
refs/heads/master
2022-04-20T15:55:48.390984
2020-04-16T20:23:33
2020-04-16T20:23:33
253,341,533
1
0
null
null
null
null
UTF-8
C++
false
false
2,003
cpp
#include <iostream> #include <iomanip> #include <algorithm> #include <queue> #include <stack> #include <string> #include <vector> #include <cmath> #include <map> #include <set> #include <string.h> #include <stdlib.h> using namespace std; // vector push_back push front top empty pop make_pair long long insert begin end typedef long long ll; typedef vector<int> vi; typedef vector<pair <int,int> > vpi; typedef vector<long long> vll; typedef pair<int,int> pi; #define F first #define S second #define PB push_back #define MP make_pair #define B begin() #define RB rbegin() #define E end() #define RE rend() #define Z size() #define REP(i,a,b) for (int i = a; i < b; i++) #define L length() #define show(a) cerr << " *** " << a << endl; #define show1(a) cerr << " /// " << a << endl; #define valid(a,b,c) (a >= b && a < c ? 1 : 0) int dx[4] = {0,0,1,-1}; int dy[4] = {1,-1,0,0}; const int mod = (int)1e9 + 7; void smxl(ll &a, ll b){if (a < b)a=b;} void smnl(ll &a, ll b){if (a > b)a=b;} void adsl(ll &a, ll b){a += b;if (a >= mod)a -= mod;} void misl(ll &a, ll b){a -= b;if (a >= mod)a -= mod; if (a < 0)a += mod;} void smx(ll &a, ll b){if (a < b)a=b;} void smn(ll &a, ll b){if (a > b)a=b;} void ads(ll &a, ll b){a += b;if (a >= mod)a -= mod;} void mis(ll &a, ll b){a -= b;if (a >= mod)a -= mod; if (a < 0)a += mod;} ll gcd(ll a, ll b) {return (b==0? a:gcd(b,a%b));} ll egcd(ll a, ll b, ll & x, ll & y) {if (a == 0){x = 0;y = 1;return b;}ll x1, y1;ll d = egcd(b % a, a, x1, y1);x = y1 - (b / a) * x1;y = x1;return d;} ll mbinp(ll a, ll b){a %= mod;if (b == 0)return 1;ll ans = mbinp(a, b/2);ll tmp = (ans * ans) % mod;if (b % 2)return ((tmp * a) % mod);return ((tmp) % mod);} ll binp(ll a, ll b){if (b == 0)return 1;ll ans = binp(a, b/2);ll tmp = (ans * ans);if (b % 2)return ((tmp * a));return ((tmp));} bool cmp(pair <ll , pair <ll, ll > > &a, pair <ll ,pair <ll, ll > > &b) { return (a.F < b.F); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); return (0); }
af1a83baa27a618fd5faaf1d79dd226faca0cbe6
6e6d8644e3cfa48a90cc6108a193e4f808ef81cc
/binarySearch.cpp
59f097ab1bd10da1506bc322c96fcb258fda4d4b
[]
no_license
shubh13/Cpp
ee77f31f1f721de50f2051b38f44f1cc7234465b
69408a734fe95a6661b8d0c6a2b1d33f00a5c472
refs/heads/master
2023-03-09T02:54:15.088115
2021-03-04T04:21:08
2021-03-04T04:21:08
343,279,713
0
0
null
null
null
null
UTF-8
C++
false
false
138
cpp
#include<iostream> using namespace std; int main(int argc, char const *argv[]) { /* code for binary search in C++*/ return 0; }
f5bc88207fbe345df684826fda4ced164a3b3e7e
8c20db410f711a6518984bf18a7e4ff5f672eb50
/NeuralNetwork/tutorial1/src/Neuron.cpp
35426951ebad900864ca4adcab29f6707fe0271b
[]
no_license
Proothean/VSCode
f2ee5950e4b7c4a0bec34cc18bb410e6fa41538d
6b8c02e891ff9ee0c64e546d1916f3597e9fc415
refs/heads/master
2020-07-26T05:19:19.868969
2019-09-18T09:12:32
2019-09-18T09:12:32
208,547,067
0
0
null
null
null
null
UTF-8
C++
false
false
184
cpp
#include <iostream> //#include "../inc/Neuron.hpp" #include "Neuron.hpp" #include <cmath> using namespace std; /* Separate compilation could make trouble, so neglect this file */
767aa2a861bdfa120cf57a8cdb5b0d478b14264f
a4991e5031ebd0f0a2c1212f6480983512234aa9
/examples/UBLOX_example/UBLOX_example.ino
f5717b8f7162eac387efec5320bc2356efc8f27e
[ "MIT" ]
permissive
Salmon-Built-Designs/ublox-arduino
189922544fbe7852602ffcc79fc2c892bfb9ff1d
1a62c097c80bb1df523982b7c10e752c23567e24
refs/heads/main
2023-03-03T14:16:23.295474
2021-02-15T21:18:42
2021-02-15T21:18:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,788
ino
/* * Brian R Taylor * [email protected] * * Copyright (c) 2021 Bolder Flight Systems Inc * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the “Software”), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "ublox.h" /* Ublox object on hardware serial port 1 */ Ublox gps(&Serial1); /* Rad to Deg conversion */ static constexpr double rad2deg = 180.0 / 3.14159265358979323846; void setup() { /* Serial to display data */ Serial.begin(115200); while (!Serial) {} /* Starting communication with the GPS receiver, 115200 baud */ if (!gps.Begin(115200)) { Serial.println("Cannot communicate with GPS receiver"); while (1) {} } } void loop() { /* Check for new packet and display some data */ if (gps.Read()) { Serial.print(gps.year()); ///< [year], Year (UTC) Serial.print("\t"); Serial.print(gps.month()); ///< [month], Month, range 1..12 (UTC) Serial.print("\t"); Serial.print(gps.day()); ///< [day], Day of month, range 1..31 (UTC) Serial.print("\t"); Serial.print(gps.hour()); ///< [hour], Hour of day, range 0..23 (UTC) Serial.print("\t"); Serial.print(gps.minute()); ///< [min], Minute of hour, range 0..59 (UTC) Serial.print("\t"); Serial.print(gps.sec()); ///< [s], Seconds of minute, range 0..60 (UTC) Serial.print("\t"); Serial.print(gps.num_satellites()); ///< [ND], Number of satellites used in Nav Solution Serial.print("\t"); Serial.print(gps.lat_rad() * rad2deg, 10); ///< [deg], Latitude Serial.print("\t"); Serial.print(gps.lon_rad() * rad2deg,10); ///< [deg], Longitude Serial.print("\t"); Serial.println(gps.alt_msl_m()); ///< [m], Height above mean sea level } }
8af7b58a44677edf13c6ac19bb0a973c57fd974c
5afb4286dba1bc9a43894e046c6367dbaee82cd6
/MemoryTest/MemoryTest/MemoryTest.cpp
94fbf33026ad3c91ebf04b59558f539200df04c1
[]
no_license
philipchang/Cplusplus
524cdcc6ee819ac7f526f674e964fab2ae539f44
5160de5e4b2c7ded1d1282f21bb063b8ec90fe25
refs/heads/master
2020-12-11T19:54:30.275575
2016-08-26T08:08:40
2016-08-26T08:08:40
53,122,641
0
0
null
null
null
null
GB18030
C++
false
false
5,760
cpp
// MemoryTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "GeoImage.h" #include <stdexcept> #include <stdio.h> #include <cstdlib> #include "CObj.h" #include "CLog.h" #include "CRect.h" //引用头文件 #include "debug_new.h" #include <string> void test1() { int* p = debug_new int(); //delete p; } void test() { int* p = debug_new int(); delete p; COrg* pObj = debug_new COrg(); delete pObj; } using namespace std; typedef enum{ INIT_STATE = 1, WORD_STATE, SPACE_STATE, }; int count_word_number(const char* pStr) { int count = 0; int state = INIT_STATE; char value ; if(NULL == pStr) return 0; while(value = *pStr++){ if('\0' == *pStr) break; switch (state) { case INIT_STATE: if(' ' != value) count ++, state = WORD_STATE; else state = SPACE_STATE; break; case WORD_STATE: if(' ' == value) state = SPACE_STATE; break; case SPACE_STATE: if(' ' != value) count ++, state = WORD_STATE; break; default: break; } } return count; } #include <cassert> void testCount() { assert(0 == count_word_number(NULL)); assert(0 == count_word_number("")); assert(1 == count_word_number("hello")); assert(3 == count_word_number("china baby hello")); } /////Check函数功能:检验第n行的皇后是否和之前的皇后有冲突,没有的话返回1 int Check(int a[],int n) { for(int i=1;i<n;i++) { if(abs(a[i]-a[n])==abs(i-n) || a[i]==a[n])//////////////见下面注释 return 0; } return 1; } void for_queue() { CTimerCls timer; int a[9]; int i,t=1; for(a[1]=1;a[1]<9;a[1]++) for(a[2]=1;a[2]<9;a[2]++) { if(!Check(a,2)) continue; for(a[3]=1;a[3]<9;a[3]++) { if(!Check(a,3)) continue; for(a[4]=1;a[4]<9;a[4]++) { if(!Check(a,4)) continue; for(a[5]=1;a[5]<9;a[5]++) { if(!Check(a,5)) continue; for(a[6]=1;a[6]<9;a[6]++) { if(!Check(a,6)) continue; for(a[7]=1;a[7]<9;a[7]++) { if(!Check(a,7)) continue; for(a[8]=1;a[8]<9;a[8]++) { if(!Check(a,8)) continue; else { /*printf("第%d种解法:\n",t++); for(i=1;i<9;i++) printf("第%d个皇后:%d\n",i,a[i]); printf("\n\n");*/ } } } } } } } } } int main1() { for_queue(); //atexit(test1); testCount(); MN_LOG("main", "COrg size %d\n", sizeof(COrg)); for(size_t i = 0; i < 100000; ++i) test(); test1(); try { char* p = debug_new char[64]; memcpy(p, "this is test!", 16); MN_LOG("main", "%s\n",p); delete[] p; } catch (const std::runtime_error& e) { MN_LOG("main", "Exception: %s\\n", e.what()); } return 0; } int a[20],n,i,j,t=1;////////////////////////////////////////全局变量 int m_nTotalFunNum = 0; void Try(int i) { int j,k; for(j=1;j<=n;j++) { a[i]=j; if(Check(a,i))///////如果第j列不会与之前的皇后冲突 { if(i<n)/////如果i<n,即还没有找到八个皇后,继续递归 Try(i+1); else ////如果找到了一组解就输出 { //printf("第%d种解法:\n",t++); if(++m_nTotalFunNum == 192){ for(k=1;k<=n;k++) printf("第%d个皇后:%d\n",k,a[k]); printf("\n\n"); } } } } } void RecursionQueen() { CTimerCls timer; //printf("几皇后?n="); //scanf("%d",&n); n = 8; Try(1); } #define ulong long long ulong gcd2(ulong a, ulong b) { if(b == 0) return a; return gcd2(b, a % b); } ulong gcd3(ulong a, ulong b) { if(a == 0) return b; if(b == 0) return a; if(a % 2 == 0 && b % 2 == 0) return 2 * gcd3(a>>1, b>>1); else if(a % 2 == 0) return gcd3(a>>1, b); else if(b % 2 == 0) return gcd3(a, b>>1); else return gcd3(abs(a-b), min(a,b)); } void gcd2main(ulong a, ulong b) { CTimerCls timer; for(size_t i = 0; i < 10000; ++i) gcd2( a, b); //cout<<"gcd2main "<<gcd2( a, b)<<endl; } void gcd3main(ulong a, ulong b) { CTimerCls timer; for(size_t i = 0; i < 10000; ++i) gcd3( a, b); //cout<<"gcd3main "<<gcd3( a, b)<<endl; } class CNum1 { public: ~CNum1() { int i = 0; +i; } private: int a; }; void testRect(vector<CWRect2Di>& vtRects, int i ) { int x = 10, y = 30, w = 20, h = 20; CWRect2Di temprect = CWRect2Di((int)x, (int)(y + h), (int)(x + w), (int)y); vtRects[i] = temprect; } int main3 () { vector<CWRect2Di> vtRects; CWRect2Di tmep; for(int i = 0; i < 3; ++i){ vtRects.push_back(tmep); testRect(vtRects,i); } for(int i = 0; i < vtRects.size(); ++i) { cout<<endl<<endl<<i<<" "<<vtRects[i].left<<"--"<<vtRects[i].bottom<<"--"<<vtRects[i].right<<"--"<<vtRects[i].top<<endl<<endl; } gcd2main(131211111112, 1455555555582); gcd3main(131211111112, 1455555555582); void whileQueen(); cout<<"whileQueen() \n"; whileQueen(); cout<<"for_queue() \n"; for_queue(); cout<<"RecursionQueen() \n"; RecursionQueen(); CQueen queen(8); cout<<"CQueen() \n"; queen.Queen(); return 0; } void whileQueen() { CTimerCls timer; int a[256]={0}; int totalNum = 0; int i=1,j,n,t=1;///i表示当前正在搜索第i行的皇后位置 n = 8; while(i>0) { for(++a[i]; a[i]<=n; ++a[i]) { if(Check(a,i))//如果第i行的皇后与之前的皇后位置上没有冲突,则break跳出循环 break; } if(a[i]<=n)//如果a[i]<=n,即上面的for循环是由“break;”跳出来的,即第i行皇后的位置符合条件 { if(i==n)////找到一组解,输出 { /*printf("第%d种解法:\n",t++); for(j=1;j<=n;j++) printf("第%d个皇后:%d\n",j,a[j]); printf("\n\n");*/ ++totalNum; } else///未找完 { i++; a[i]=0; } } else i--;////////////回溯 } printf("while queen %d\n", totalNum); }
c8250994bb8541ba4b0a65f7149cb3f490dfda3c
d0d4b45211dc67d06e4a0aa5aaf300f413e65d6b
/src/ino/util.h
29c5ead9bdab17fc3c6920616783e5aaf88f26f0
[]
no_license
inotai/ino-node-ui
de007eb93b2fc4527d219235aa0e4bce889cfaa7
7c88f19750f1e107ab1eabe5c310f8aa32ea3b7e
refs/heads/master
2021-01-10T10:21:32.264573
2013-02-28T13:43:19
2013-02-28T13:43:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
467
h
#ifndef __INO_UTIL_H__ #define __INO_UTIL_H__ namespace ino { struct util { static std::wstring format(const wchar_t* fmt, ...) { int size = 80; std::wstring ret; ret.resize(size); va_list vl; va_start(vl, fmt); int size_n = _vsnwprintf(&ret[0], size, fmt, vl); if (size <= size_n) { ret.resize(size_n + 1); size_n = _vsnwprintf(&ret[0], size_n, fmt, vl); } va_end(vl); return ret; } }; } #endif // __INO_UTIL_H__
b08d48da6078e59529be075aa7ae2d69bdbbc7e5
56f534694525d8dc665c1c182496719f5ff3cc51
/standalone/multicamera/addons/ofxTSPS/src/ofxTSPSPeopleTracker.cpp
b49e136fe652a322eb8df2c59478662539442aed
[]
no_license
sgilroy/openTSPS
631fd0ca33e779d4f529def1188c06f54fa63de8
05d1406dad2e68033a23de497f0bc9ad88ff77bd
refs/heads/master
2021-01-18T10:57:18.173676
2012-03-31T21:09:49
2012-03-31T21:09:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
41,820
cpp
#include "ofxTSPSPeopleTracker.h" #include "CPUImageFilter.h" //scales down tracking images for improved performance #define TRACKING_SCALE_FACTOR .5 //Fix for FMAX not in Visual Studio C++ #if defined _MSC_VER #define fmax max #define fmin min #pragma warning (disable:4996) #define snprintf sprintf_s #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma mark Setup ofxTSPSPeopleTracker::ofxTSPSPeopleTracker(){ p_Settings = NULL; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setup(int w, int h, string settingsfile) { ofAddListener(ofEvents.mousePressed, this, &ofxTSPSPeopleTracker::mousePressed); width = w; height = h; grayImage.allocate(width, height); colorImage.allocate(width,height); grayImageWarped.allocate(width, height); colorImageWarped.allocate(width,height); grayBg.allocate(width, height); grayDiff.allocate(width, height); floatBgImg.allocate(width, height); graySmallImage.allocate( width*TRACKING_SCALE_FACTOR, height*TRACKING_SCALE_FACTOR ); grayLastImage.allocate( width*TRACKING_SCALE_FACTOR, height*TRACKING_SCALE_FACTOR ); grayBabyImage.allocate( width*TRACKING_SCALE_FACTOR, height*TRACKING_SCALE_FACTOR ); //set up optical flow opticalFlow.allocate( width*TRACKING_SCALE_FACTOR, height*TRACKING_SCALE_FACTOR ); opticalFlow.setCalcStep(5,5); grayLastImage = graySmallImage; //set tracker bOscEnabled = bTuioEnabled = bTcpEnabled = bWebSocketsEnabled = false; p_Settings = gui.getSettings(); //gui.loadFromXML(); //gui.setDraw(true); //setup gui quad in manager gui.setup(); gui.setupQuadGui( width, height ); gui.loadSettings( settingsfile ); activeHeight = ofGetHeight(); activeWidth = ofGetWidth(); activeViewIndex = 4; //setup view rectangles cameraView.setup(width, height); adjustedView.setup(width, height); bgView.setup(width, height); processedView.setup(width, height); dataView.setup(width, height); updateViewRectangles(); cameraView.setImage(colorImage); cameraView.setTitle("Camera Source View", "Camera"); cameraView.setColor(218,173,90); adjustedView.setImage(grayImageWarped); adjustedView.setTitle("Adjusted Camera View", "Adjusted"); adjustedView.setColor(174,139,138); bgView.setImage(grayBg); bgView.setTitle("Background Reference View", "Background"); bgView.setColor(213,105,68); processedView.setImage(grayDiff); processedView.setTitle("Differenced View", "Differencing"); processedView.setColor(113,171,154); dataView.setTitle("Data View", "Data"); dataView.setColor(191,120,0); setActiveView(PROCESSED_VIEW); persistentTracker.setListener( this ); //updateSettings(); lastHaarFile = ""; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setHaarXMLFile(string haarFile) { haarFile = "haar/" + haarFile; //check if haar file has changed if(lastHaarFile != haarFile){ ofLog(OF_LOG_VERBOSE, "changing haar file to " + haarFile); haarFinder.setup(haarFile); haarTracker.setup(&haarFinder); lastHaarFile = haarFile; } } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma mark Setup Communication //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setupTuio(string ip, int port) { ofLog(OF_LOG_VERBOSE, "SEND TUIO"); bTuioEnabled = true; if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->oscPort = port; p_Settings->oscHost = ip; tuioClient.setup(ip, port); } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setupOsc(string ip, int port) { ofLog(OF_LOG_VERBOSE, "SEND OSC"); bOscEnabled = true; if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->oscPort = port; p_Settings->oscHost = ip; oscClient.setupSender(ip, port); } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setupTcp(int port) { bTcpEnabled = true; ofLog(OF_LOG_VERBOSE, "SEND TCP TO PORT "+port); if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->tcpPort = port; tcpClient.setup(port); } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setupWebSocket( int port) { ofLog(OF_LOG_VERBOSE, "SEND VIA WEBSOCKETS AT PORT "+port); if (p_Settings == NULL) p_Settings = gui.getSettings(); bWebSocketsEnabled = true; p_Settings->webSocketPort = port; bWebSocketsEnabled = webSocketServer.setup(port); p_Settings->bSendWebSockets = bWebSocketsEnabled; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setListener(ofxPersonListener* listener) { eventListener = listener; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma mark Track People //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::update(ofxCvColorImage image) { grayImage = image; colorImage = image; updateSettings(); trackPeople(); } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::update(ofxCvGrayscaleImage image) { grayImage = image; updateSettings(); trackPeople(); } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::updateSettings() { if (p_Settings == NULL) p_Settings = gui.getSettings(); setHaarXMLFile(p_Settings->haarFile); //check to enable OSC if (p_Settings->bSendOsc && !bOscEnabled) setupOsc(p_Settings->oscHost, p_Settings->oscPort); else if (!p_Settings->bSendOsc) bOscEnabled = false; //check to enable TUIO if (p_Settings->bSendTuio && !bTuioEnabled) setupTuio(p_Settings->tuioHost, p_Settings->tuioPort); else if (!p_Settings->bSendTuio) bTuioEnabled = false; //check to enable TCP if (p_Settings->bSendTcp && !bTcpEnabled) setupTcp(p_Settings->tcpPort); else if (!p_Settings->bSendTcp) bTcpEnabled = false; //check to enable websockets if (p_Settings->bSendWebSockets && !bWebSocketsEnabled){ setupWebSocket(p_Settings->webSocketPort); } else if (!p_Settings->bSendWebSockets){ bWebSocketsEnabled = false; webSocketServer.close(); } //switch camera view if new panel is selected if (p_Settings->currentPanel != p_Settings->lastCurrentPanel) setActiveView(p_Settings->currentPanel + 1); // Set the current view within the gui so the image can only be warped when in Camera View if (cameraView.isActive()) { gui.changeGuiCameraView(true); } else { gui.changeGuiCameraView(false); } } /** * Core Method * Run every frame to update * the system to the current location * of people */ //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::trackPeople() { if (p_Settings == NULL) p_Settings = gui.getSettings(); //------------------- //QUAD WARPING //------------------- //warp background //grayImageWarped = grayImage; colorImage = grayImage; colorImageWarped = colorImage; //getQuadSubImage(&colorImage, &colorImageWarped, &p_Settings->quadWarpScaled, 3); getQuadSubImage(&grayImage, &grayImageWarped, &p_Settings->quadWarpScaled, 1); //grayImageWarped.warpIntoMe(grayImage, p_Settings->quadWarpScaled, p_Settings->quadWarpOriginal); //colorImageWarped.warpIntoMe(colorImage, p_Settings->quadWarpScaled, p_Settings->quadWarpOriginal); graySmallImage.scaleIntoMe(grayImageWarped); grayBabyImage.scaleIntoMe(grayImageWarped); grayDiff = grayImageWarped; //amplify (see cpuimagefilter class) if(p_Settings->bAmplify){ grayDiff.amplify(grayDiff, p_Settings->highpassAmp/15.0f); } grayImageWarped = grayDiff; //------------------- //BACKGROUND //------------------- //force learn background if there are > 5 blobs (off by default) //JG Disabling this feature for now, //I think it's a great idea but it needs to be better described and "5" needs to be customizable // if (p_Settings->bSmartLearnBackground == true && contourFinder.nBlobs > 5){ // p_Settings->bLearnBackground = true; // } //learn background (either in reset or additive) if (p_Settings->bLearnBackground){ cout << "Learning Background" << endl; grayBg = grayImageWarped; } //progressive relearn background if (p_Settings->bLearnBackgroundProgressive){ if (p_Settings->bLearnBackground) floatBgImg = grayBg; floatBgImg.addWeighted( grayImageWarped, p_Settings->fLearnRate * .00001); grayBg = floatBgImg; //cvConvertScale( floatBgImg.getCvImage(), grayBg.getCvImage(), 255.0f/65535.0f, 0 ); //grayBg.flagImageChanged(); } //printf("track type %d from (%d,%d,%d)\n", p_Settings->trackType, TRACK_ABSOLUTE, TRACK_DARK, TRACK_LIGHT); if(p_Settings->trackType == TRACK_ABSOLUTE){ grayDiff.absDiff(grayBg, grayImageWarped); } else{ grayDiff = grayImageWarped; if(p_Settings->trackType == TRACK_LIGHT){ //grayDiff = grayBg - grayImageWarped; cvSub(grayBg.getCvImage(), grayDiff.getCvImage(), grayDiff.getCvImage()); } else if(p_Settings->trackType == TRACK_DARK){ cvSub(grayDiff.getCvImage(), grayBg.getCvImage(), grayDiff.getCvImage()); //grayDiff = grayImageWarped - grayBg; } grayDiff.flagImageChanged(); } //----------------------- // IMAGE TREATMENT //----------------------- if(p_Settings->bSmooth){ grayDiff.blur((p_Settings->smooth * 2) + 1); //needs to be an odd number } //highpass filter (see cpuimagefilter class) if(p_Settings->bHighpass){ grayDiff.highpass(p_Settings->highpassBlur, p_Settings->highpassNoise); } //threshold grayDiff.threshold(p_Settings->threshold); //----------------------- // TRACKING //----------------------- //find the optical flow if (p_Settings->bTrackOpticalFlow){ opticalFlow.calc(grayLastImage, graySmallImage, 11); } //accumulate and store all found haar features. vector<ofRectangle> haarRects; if(p_Settings->bDetectHaar){ haarTracker.findHaarObjects( grayBabyImage ); float x, y, w, h; while(haarTracker.hasNextHaarItem()){ haarTracker.getHaarItemPropertiesEased( &x, &y, &w, &h ); haarRects.push_back( ofRectangle(x,y,w,h) ); } } char pringString[1024]; sprintf(pringString, "found %i haar items this frame", haarRects.size()); ofLog(OF_LOG_VERBOSE, pringString); contourFinder.findContours(grayDiff, p_Settings->minBlob*width*height, p_Settings->maxBlob*width*height, 50, p_Settings->bFindHoles); persistentTracker.trackBlobs(contourFinder.blobs); // By setting maxVector and minVector outside the following for-loop, blobs do NOT have to be detected first // before optical flow can begin working. if(p_Settings->bTrackOpticalFlow) { scene.averageMotion = opticalFlow.flowInRegion(0,0,width,height); scene.percentCovered = 0; opticalFlow.maxVector = p_Settings->maxOpticalFlow; opticalFlow.minVector = p_Settings->minOpticalFlow; } for(int i = 0; i < persistentTracker.blobs.size(); i++){ ofxCvTrackedBlob blob = persistentTracker.blobs[i]; ofxTSPSPerson* p = getTrackedPerson(blob.id); //somehow we are not tracking this person, safeguard (shouldn't happen) if(NULL == p){ ofLog(OF_LOG_WARNING, "ofxPerson::warning. encountered persistent blob without a person behind them\n"); continue; } scene.percentCovered += blob.area; //update this person with new blob info p->update(blob, p_Settings->bCentroidDampen); //normalize simple contour for (int i=0; i<p->simpleContour.size(); i++){ p->simpleContour[i].x /= width; p->simpleContour[i].y /= height; } ofRectangle roi; roi.x = fmax( (p->boundingRect.x - p_Settings->haarAreaPadding) * TRACKING_SCALE_FACTOR, 0.0f ); roi.y = fmax( (p->boundingRect.y - p_Settings->haarAreaPadding) * TRACKING_SCALE_FACTOR, 0.0f ); roi.width = fmin( (p->boundingRect.width + p_Settings->haarAreaPadding*2) * TRACKING_SCALE_FACTOR, grayBabyImage.width - roi.x ); roi.height = fmin( (p->boundingRect.height + p_Settings->haarAreaPadding*2) * TRACKING_SCALE_FACTOR, grayBabyImage.width - roi.y ); //sum optical flow for the person if(p_Settings->bTrackOpticalFlow){ p->opticalFlowVectorAccumulation = opticalFlow.flowInRegion(roi); } //detect haar patterns (faces, eyes, etc) if (p_Settings->bDetectHaar){ bool bHaarItemSet = false; //find the region of interest, expanded by haarArea. //bound by the frame edge //cout << "ROI is " << roi.x << " " << roi.y << " " << roi.width << " " << roi.height << endl; bool haarThisFrame = false; for(int i = 0; i < haarRects.size(); i++){ ofRectangle hr = haarRects[i]; //check to see if the haar is contained within the bounding rectangle if(hr.x > roi.x && hr.y > roi.y && hr.x+hr.width < roi.x+roi.width && hr.y+hr.height < roi.y+roi.height){ hr.x /= TRACKING_SCALE_FACTOR; hr.y /= TRACKING_SCALE_FACTOR; hr.width /= TRACKING_SCALE_FACTOR; hr.height /= TRACKING_SCALE_FACTOR; p->setHaarRect(hr); haarThisFrame = true; break; } } if(!haarThisFrame){ p->noHaarThisFrame(); } /* //JG 1/28/2010 //This is the prper way to do the Haar, checking one person at a time. //however this discards the robustness of the haarFinder and //makes the whole operation really spotty. // The solution is to put more energy into finding out how // the haar tracker works to get robust/persistent haar items over time. //for now we just check the whole screen and see if the haar is contained grayBabyImage.setROI(roi.x, roi.y, roi.width, roi.height); int numFound = haarFinder.findHaarObjects(grayBabyImage, roi); //cout << "found " << numFound << " for this object" << endl; if(numFound > 0) { ofRectangle haarRect = haarFinder.blobs[0].boundingRect; haarRect.x /= TRACKING_SCALE_FACTOR; haarRect.y /= TRACKING_SCALE_FACTOR; haarRect.width /= TRACKING_SCALE_FACTOR; haarRect.height /= TRACKING_SCALE_FACTOR; p->setHaarRect(haarRect); } else { p->noHaarThisFrame(); } */ } if(eventListener != NULL){ if( p->velocity.x != 0 || p->velocity.y != 0){ eventListener->personMoved(p, &scene); } eventListener->personUpdated(p, &scene); } } //normalize it scene.percentCovered /= width*height; //----------------------- // VIEWS //----------------------- //store the old image grayLastImage = graySmallImage; //update views cameraView.update(colorImage); if (p_Settings->bAdjustedViewInColor) adjustedView.update(colorImageWarped); else adjustedView.update(grayImageWarped); bgView.update(grayBg); processedView.update(grayDiff); //----------------------- // COMMUNICATION //----------------------- for (int i = 0; i < trackedPeople.size(); i++){ ofxTSPSPerson* p = trackedPeople[i]; ofPoint centroid = p->getCentroidNormalized(width, height); // if(p_Settings->bUseHaarAsCenter && p->hasHaarRect()){ if (bTuioEnabled){ ofPoint tuioCursor = p->getCentroidNormalized(width, height); tuioClient.cursorDragged( tuioCursor.x, tuioCursor.y, p->oid); } if (bOscEnabled){ if( p->velocity.x != 0 || p->velocity.y != 0){ //DEPRECATED: oscClient.personMoved(p, centroid, width, height, p_Settings->bSendOscContours); } oscClient.personUpdated(p, centroid, width, height, p_Settings->bSendOscContours); } if (bTcpEnabled){ tcpClient.personMoved(p, centroid, width, height, p_Settings->bSendOscContours); } if (bWebSocketsEnabled){ webSocketServer.personMoved(p, centroid, width, height, p_Settings->bSendOscContours); } } if(bTuioEnabled){ tuioClient.update(); } if (bOscEnabled){ oscClient.ip = p_Settings->oscHost; oscClient.port = p_Settings->oscPort; oscClient.useLegacy = p_Settings->bUseLegacyOsc; oscClient.update(); }; if (bTcpEnabled){ tcpClient.port = p_Settings->oscPort; tcpClient.update(); tcpClient.send(); } if (bWebSocketsEnabled){ if (p_Settings->webSocketPort != webSocketServer.getPort()){ webSocketServer.close(); cout<<"OR HERE?"<<endl; webSocketServer.setup( p_Settings->webSocketPort ); } //sent automagically webSocketServer.send(); } } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma mark Person Management //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::blobOn( int x, int y, int id, int order ) { if (p_Settings == NULL) p_Settings = gui.getSettings(); ofxCvTrackedBlob blob = persistentTracker.getById( id ); ofxTSPSPerson* newPerson = new ofxTSPSPerson(id, order, blob); trackedPeople.push_back( newPerson ); if(eventListener != NULL){ eventListener->personEntered(newPerson, &scene); } ofPoint centroid = newPerson->getCentroidNormalized(width, height); if(bTuioEnabled){ tuioClient.cursorPressed(1.0*x/width, 1.0*y/height, order); } if(bOscEnabled){ oscClient.personEntered(newPerson, centroid, width, height, p_Settings->bSendOscContours); } if(bTcpEnabled){ tcpClient.personEntered(newPerson, centroid, width, height, p_Settings->bSendOscContours); } if(bWebSocketsEnabled){ webSocketServer.personEntered(newPerson, centroid, width, height, p_Settings->bSendOscContours); } } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::blobMoved( int x, int y, int id, int order ){/*not used*/} //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::blobOff( int x, int y, int id, int order ) { ofxTSPSPerson* p = getTrackedPerson(id); //ensure we are tracking if(NULL == p){ ofLog(OF_LOG_WARNING, "ofxPerson::warning. encountered persistent blob without a person behind them\n"); return; } //alert the delegate if(eventListener != NULL){ eventListener->personWillLeave(p, &scene); } ofPoint centroid = p->getCentroidNormalized(width, height); if (bTuioEnabled) { tuioClient.cursorReleased(centroid.x, centroid.y, order); } //send osc kill message if enabled if (bOscEnabled){ oscClient.personWillLeave(p, centroid, width, height, p_Settings->bSendOscContours); }; //send tcp kill message if enabled if(bTcpEnabled){ tcpClient.personWillLeave(p, centroid, width, height, p_Settings->bSendOscContours); } if(bWebSocketsEnabled){ webSocketServer.personWillLeave(p, centroid, width, height, p_Settings->bSendOscContours); } //delete the object and remove it from the vector std::vector<ofxTSPSPerson*>::iterator it; for(it = trackedPeople.begin(); it != trackedPeople.end(); it++){ if((*it)->pid == p->pid){ trackedPeople.erase(it); delete p; break; } } } //--------------------------------------------------------------------------- ofxTSPSPerson* ofxTSPSPeopleTracker::getTrackedPerson( int pid ) { for( int i = 0; i < trackedPeople.size(); i++ ) { if( trackedPeople[i]->pid == pid ) { return trackedPeople[i]; } } return NULL; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma mark Draw //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::draw() { draw(0,0); } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::draw(int x, int y) { draw(x,y,drawMode); } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::draw(int x, int y, int mode) { if (p_Settings == NULL) p_Settings = gui.getSettings(); // run lean + mean if we're minimized if (p_Settings->bMinimized) return; ofPushMatrix(); ofTranslate(x, y, 0); // draw the incoming, the grayscale, the bg and the thresholded difference ofSetHexColor(0xffffff); // draw gui gui.draw(); //draw large image if (activeViewIndex == CAMERA_SOURCE_VIEW){ cameraView.drawLarge(activeView.x, activeView.y, activeView.width, activeView.height); gui.drawQuadGui( activeView.x, activeView.y, activeView.width, activeView.height ); } else if ( activeViewIndex == ADJUSTED_CAMERA_VIEW){ adjustedView.drawLarge(activeView.x, activeView.y, activeView.width, activeView.height); } else if ( activeViewIndex == REFERENCE_BACKGROUND_VIEW){ bgView.drawLarge(activeView.x, activeView.y, activeView.width, activeView.height); } else if ( activeViewIndex == PROCESSED_VIEW){ processedView.drawLarge(activeView.x, activeView.y, activeView.width, activeView.height); } else if ( activeViewIndex == DATA_VIEW ){ ofPushMatrix(); ofTranslate(activeView.x, activeView.y); drawBlobs(activeView.width, activeView.height); ofPopMatrix(); dataView.drawLarge(activeView.x, activeView.y, activeView.width, activeView.height); } //draw all images small cameraView.draw(); adjustedView.draw(); bgView.draw(); processedView.draw(); dataView.draw(); ofPushMatrix(); ofTranslate(dataView.x, dataView.y); drawBlobs(dataView.width, dataView.height); ofPopMatrix(); ofPopMatrix(); //draw framerate in a box char frmrate[1024]; sprintf(frmrate, "Frame rate: %f", ofGetFrameRate() ); ofPushStyle(); ofFill(); ofSetColor(196,182,142); ofRect(cameraView.x, cameraView.y + cameraView.height + spacing*3 + 8, cameraView.width*2 + spacing, spacing*4); ofPopStyle(); if (!bFontLoaded) ofDrawBitmapString(frmrate, cameraView.x + 10, cameraView.y + 10 + cameraView.height + spacing*5); else font.drawString(frmrate, (int)cameraView.x + 10, (int) (cameraView.y + 10 + cameraView.height + spacing*5)); } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::drawBlobs( float drawWidth, float drawHeight){ if (p_Settings == NULL) p_Settings = gui.getSettings(); float scaleVar = (float) drawWidth/width; ofFill(); ofSetHexColor(0x333333); ofRect(0,0,drawWidth,drawHeight); ofSetHexColor(0xffffff); ofNoFill(); if (p_Settings->bTrackOpticalFlow){ ofSetColor(34,151,210); opticalFlow.draw(drawWidth,drawHeight); } ofPushMatrix(); ofScale(scaleVar, scaleVar); // simpler way to draw contours: contourFinder.draw(); for (int i=0; i < trackedPeople.size(); i++){ //draw blobs //if haarfinder is looking at these blobs, draw the area it's looking at ofxTSPSPerson* p = trackedPeople[i]; //draw contours ofPushStyle(); ofNoFill(); if (p_Settings->bSendOscContours){ ofSetHexColor(0x3abb93); } else { ofSetHexColor(0xc4b68e); } ofBeginShape(); for( int j=0; j<p->contour.size(); j++ ) { ofVertex( p->contour[j].x, p->contour[j].y ); } ofEndShape(); ofPopStyle(); if(p_Settings->bTrackOpticalFlow){ //purple optical flow arrow ofSetHexColor(0xff00ff); //JG Doesn't really provide any helpful information since its so scattered // ofLine(p->centroid.x, // p->centroid.y, // p->centroid.x + p->opticalFlowVectorAccumulation.x, // p->centroid.y + p->opticalFlowVectorAccumulation.y); } ofSetHexColor(0xffffff); if(p_Settings->bDetectHaar){ ofSetHexColor(0xee3523); //draw haar search area expanded //limit to within data box so it's not confusing /*ofRect(p->boundingRect.x - p_Settings->haarAreaPadding, p->boundingRect.y - p_Settings->haarAreaPadding, p->boundingRect.width + p_Settings->haarAreaPadding*2, p->boundingRect.height + p_Settings->haarAreaPadding*2);*/ ofRectangle haarRect = ofRectangle(p->boundingRect.x - p_Settings->haarAreaPadding, p->boundingRect.y - p_Settings->haarAreaPadding, p->boundingRect.width + p_Settings->haarAreaPadding*2, p->boundingRect.height + p_Settings->haarAreaPadding*2); if (haarRect.x < 0){ haarRect.width += haarRect.x; haarRect.x = 0; } if (haarRect.y < 0){ haarRect.height += haarRect.y; haarRect.y = 0; } if (haarRect.x + haarRect.width > width) haarRect.width = width-haarRect.x; if (haarRect.y + haarRect.height > height) haarRect.height = height-haarRect.y; ofRect(haarRect.x, haarRect.y, haarRect.width, haarRect.height); } if(p->hasHaarRect()){ //draw the haar rect ofSetHexColor(0xee3523); ofRect(p->getHaarRect().x, p->getHaarRect().y, p->getHaarRect().width, p->getHaarRect().height); //haar-detected people get a red square ofSetHexColor(0xfd5f4f); } else { //no haar gets a yellow square ofSetHexColor(0xeeda00); } //draw person ofRect(p->boundingRect.x, p->boundingRect.y, p->boundingRect.width, p->boundingRect.height); //draw centroid ofSetHexColor(0xff0000); ofCircle(p->centroid.x, p->centroid.y, 3); //draw id ofSetHexColor(0xffffff); char idstr[1024]; sprintf(idstr, "pid: %d\noid: %d\nage: %d", p->pid, p->oid, p->age ); ofDrawBitmapString(idstr, p->centroid.x+8, p->centroid.y); } ofPopMatrix(); ofSetHexColor(0xffffff); //ofDrawBitmapString("blobs and optical flow", 5, height - 5 ); } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma mark mouse //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::mousePressed( ofMouseEventArgs &e ) { if (isInsideRect(e.x, e.y, cameraView)){ activeViewIndex = CAMERA_SOURCE_VIEW; cameraView.setActive(); adjustedView.setActive(false); bgView.setActive(false); processedView.setActive(false); dataView.setActive(false); } else if (isInsideRect(e.x, e.y, adjustedView)){ activeViewIndex = ADJUSTED_CAMERA_VIEW; adjustedView.setActive(); cameraView.setActive(false); bgView.setActive(false); processedView.setActive(false); dataView.setActive(false); } else if (isInsideRect(e.x, e.y, bgView)){ activeViewIndex = REFERENCE_BACKGROUND_VIEW; bgView.setActive(); cameraView.setActive(false); adjustedView.setActive(false); processedView.setActive(false); dataView.setActive(false); } else if (isInsideRect(e.x, e.y, processedView)){ activeViewIndex = PROCESSED_VIEW; processedView.setActive(); cameraView.setActive(false); adjustedView.setActive(false); bgView.setActive(false); dataView.setActive(false); } else if (isInsideRect(e.x, e.y, dataView)){ activeViewIndex = DATA_VIEW; dataView.setActive(); cameraView.setActive(false); adjustedView.setActive(false); bgView.setActive(false); processedView.setActive(false); } } //--------------------------------------------------------------------------- bool ofxTSPSPeopleTracker::isInsideRect(float x, float y, ofRectangle rect){ return ( x >= rect.x && x <= rect.x + rect.width && y >= rect.y && y <= rect.y + rect.height ); } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma mark gui extension //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::enableGuiEvents(){ gui.enableEvents(); }; //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::disableGuiEvents(){ gui.disableEvents(); }; //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::addSlider(string name, int* value, int min, int max) { //forward to the gui manager gui.addSlider(name, value, min, max); } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::addSlider(string name, float* value, float min, float max) { gui.addSlider(name, value, min, max); } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::addToggle(string name, bool* value) { gui.addToggle(name, value); } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma mark accessors /** * simple public getter for external classes */ //--------------------------------------------------------------------------- ofxTSPSPerson* ofxTSPSPeopleTracker::personAtIndex(int i) { return trackedPeople[i]; } //--------------------------------------------------------------------------- int ofxTSPSPeopleTracker::totalPeople() { return trackedPeople.size(); } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::enableHaarFeatures(bool doHaar) { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->bDetectHaar = doHaar; } void ofxTSPSPeopleTracker::enableOpticalFlow(bool doOpticalFlow) { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->bTrackOpticalFlow = doOpticalFlow; } //--------------------------------------------------------------------------- // for accessing the OSC sender whose parameters are adjusted in the GUI ofxTSPSOscSender* ofxTSPSPeopleTracker::getOSCsender() { return &oscClient; } //--------------------------------------------------------------------------- ofxTSPSWebSocketSender * ofxTSPSPeopleTracker::getWebSocketServer(){ return &webSocketServer; }; //--------------------------------------------------------------------------- bool ofxTSPSPeopleTracker::useKinect(){ if (p_Settings == NULL) p_Settings = gui.getSettings(); return p_Settings->bUseKinect; }; //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma mark background management //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::relearnBackground() { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->bLearnBackground = true; } //JG Disabled this feature //void ofxTSPSPeopleTracker::enableBackgroundRelearnSmart(bool doSmartLearn)//auto-relearns if there are too many blobs in the scene //{ // p_Settings->bSmartLearnBackground = doSmartLearn; //} //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::enableBackgroundReleaernProgressive(bool doProgressive) //relearns over time using progessive frame averagering { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->bLearnBackgroundProgressive = doProgressive; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setRelearnRate(float relearnRate) { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->fLearnRate = relearnRate; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma mark image control //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setThreshold(float thresholdAmount) { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->threshold = thresholdAmount; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setMinBlobSize(float minBlobSize) { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->minBlob = minBlobSize; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setMaxBlobSize(float maxBlobSize) { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->maxBlob = maxBlobSize; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::enableSmooth(bool doSmooth) { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->bSmooth = doSmooth; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setSmoothAmount(int smoothAmount) { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->smooth = smoothAmount; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::enableHighpass(bool doHighpass) { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->bHighpass = doHighpass; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setHighpassBlurAmount(int highpassBlurAmount) { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->highpassBlur = highpassBlurAmount; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setHighpassNoiseAmount(int highpassNoiseAmount) { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->highpassNoise = highpassNoiseAmount; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::enableAmplify(bool doAmp) { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->bAmplify = doAmp; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setAmplifyAmount(int amplifyAmount) { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->highpassAmp = amplifyAmount; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma mark filter controls //haar //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setHaarExpandArea(float haarExpandAmount) //makes the haar rect +area bigger { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->haarAreaPadding = haarExpandAmount; } //JG 1/21/10 disabled this feature to simplify the interface //void ofxTSPSPeopleTracker::setMinHaarArea(float minArea) //{ // p_Settings->minHaarArea = minArea; //} //void ofxTSPSPeopleTracker::setMaxHaarArea(float maxArea) //{ // p_Settings->maxHaarArea = maxArea; //} //void ofxTSPSPeopleTracker::useHaarAsCentroid(bool useHaarCenter) //{ // p_Settings->bUseHaarAsCenter = useHaarCenter; //} //blobs //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::enableFindHoles(bool findHoles) { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->bFindHoles = findHoles; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::trackDarkBlobs() { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->trackType = TRACK_DARK; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::trackLightBlobs() { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->trackType = TRACK_LIGHT; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setDrawMode(int mode) { drawMode = mode; } //--------------------------------------------------------------------------- int ofxTSPSPeopleTracker::getDrawMode() { return drawMode; } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma mark gui customization //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setActiveView( int viewIndex ){ int oldActiveView = activeViewIndex; activeViewIndex = viewIndex; if (activeViewIndex == CAMERA_SOURCE_VIEW){ cameraView.setActive(); adjustedView.setActive(false); bgView.setActive(false); processedView.setActive(false); dataView.setActive(false); } else if (activeViewIndex == ADJUSTED_CAMERA_VIEW){ adjustedView.setActive(); cameraView.setActive(false); bgView.setActive(false); processedView.setActive(false); dataView.setActive(false); } else if (activeViewIndex == REFERENCE_BACKGROUND_VIEW){ bgView.setActive(); cameraView.setActive(false); adjustedView.setActive(false); processedView.setActive(false); dataView.setActive(false); } else if (activeViewIndex == PROCESSED_VIEW){ processedView.setActive(); cameraView.setActive(false); adjustedView.setActive(false); bgView.setActive(false); dataView.setActive(false); } else if (activeViewIndex == DATA_VIEW){ dataView.setActive(); cameraView.setActive(false); adjustedView.setActive(false); bgView.setActive(false); processedView.setActive(false); } else { activeViewIndex = oldActiveView; } } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setActiveDimensions ( int actWidth, int actHeight){ activeWidth = actWidth; activeHeight = actHeight; updateViewRectangles(); } //--------------------------------------------------------------------------- bool ofxTSPSPeopleTracker::loadFont( string fontName, int fontSize){ bFontLoaded = font.loadFont(fontName, fontSize); if (bFontLoaded){ cameraView.setFont(&font); adjustedView.setFont(&font); bgView.setFont(&font); processedView.setFont(&font); dataView.setFont(&font); } return bFontLoaded; } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::setVideoGrabber(ofBaseVideo* grabber, tspsInputType inputType) { if (p_Settings == NULL) p_Settings = gui.getSettings(); p_Settings->setVideoGrabber( grabber, inputType ); if (inputType == TSPS_INPUT_VIDEO){ gui.enableElement( "open video settings" ); gui.disableElement( "use kinect" ); } else if (inputType == TSPS_INPUT_KINECT){ gui.disableElement( "open video settings" ); gui.enableElement( "use kinect" ); } } //--------------------------------------------------------------------------- void ofxTSPSPeopleTracker::updateViewRectangles(){ //build all rectangles for drawing views ofPoint smallView; smallView.x = (activeWidth - GUI_WIDTH - spacing*6)/5.f; smallView.y = (height*TRACKING_SCALE_FACTOR) * (smallView.x/(width*TRACKING_SCALE_FACTOR)); activeView.x = GUI_WIDTH + spacing; activeView.y = spacing; activeView.width = (activeWidth - GUI_WIDTH - spacing*2); activeView.height = (height*TRACKING_SCALE_FACTOR)*activeView.width/(width*TRACKING_SCALE_FACTOR); cameraView.x = GUI_WIDTH + spacing; cameraView.y = activeView.y + activeView.height + spacing; cameraView.width = smallView.x; cameraView.height = smallView.y; adjustedView.x = cameraView.x + cameraView.width + spacing; adjustedView.y = cameraView.y; adjustedView.width = smallView.x; adjustedView.height = smallView.y; bgView.x = adjustedView.x + adjustedView.width + spacing; bgView.y = cameraView.y; bgView.width = smallView.x; bgView.height = smallView.y; processedView.x = bgView.x + bgView.width + spacing; processedView.y = cameraView.y; processedView.width = smallView.x; processedView.height = smallView.y; dataView.x = processedView.x + processedView.width + spacing; dataView.y = cameraView.y; dataView.width = smallView.x; dataView.height = smallView.y; gui.drawQuadGui( activeView.x, activeView.y, activeView.width, activeView.height ); } //--------------------------------------------------------------------------- // for accessing Optical Flow within a specific region ofPoint ofxTSPSPeopleTracker::getOpticalFlowInRegion(float x, float y, float w, float h) { return opticalFlow.flowInRegion(x,y,w,h); } //--------------------------------------------------------------------------- // for accessing which view is the current view bool ofxTSPSPeopleTracker::inCameraView() { return cameraView.isActive(); } //--------------------------------------------------------------------------- bool ofxTSPSPeopleTracker::inBackgroundView() { return bgView.isActive(); } //--------------------------------------------------------------------------- bool ofxTSPSPeopleTracker::inDifferencingView() { return processedView.isActive(); } //--------------------------------------------------------------------------- bool ofxTSPSPeopleTracker::inDataView() { return dataView.isActive(); } //--------------------------------------------------------------------------- bool ofxTSPSPeopleTracker::inAdjustedView() { return adjustedView.isActive(); } // for getting a color version of the adjusted view image // NOTE: only works if the adjusted view is currently in color // (this parameter can be set in the GUI under the 'views' tab) ofxCvColorImage ofxTSPSPeopleTracker::getAdjustedImageInColor() { if (p_Settings == NULL) p_Settings = gui.getSettings(); if (p_Settings->bAdjustedViewInColor) return adjustedView.getColorImage(); }
144708aeb9777c38e60be1090b6f8eca1ed21ab2
bb70e109b3441e60f3bb969e2951338659a5fa39
/0/intersection_of_two_arrays.cpp
b8c042c122caeeb7aac895e17ff49d2ae9e22519
[]
no_license
moyuanhuang/leetcode
d06d389725d6d7fd1e3bd3786a1325a48b0933a3
ef052efcbcceb38e44fdd7cbcb6a7e6bd7ff8aa2
refs/heads/master
2020-09-19T20:38:29.891287
2019-02-13T04:55:06
2019-02-13T04:55:06
66,139,783
2
2
null
null
null
null
UTF-8
C++
false
false
329
cpp
class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { unordered_set<int> uset(nums1.begin(), nums1.end()); vector<int> ret; for(int n : nums2){ if(uset.count(n)){ ret.push_back(n); uset.erase(n); } } return ret; } };
41651144ce333af86ea026dbad1621c96b2d7036
5456502f97627278cbd6e16d002d50f1de3da7bb
/storage/browser/fileapi/sandbox_quota_observer.cc
a2a26bb32fb6f183ad327b8de788e26d6a75b8b6
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,834
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "storage/browser/fileapi/sandbox_quota_observer.h" #include <stdint.h> #include "base/sequenced_task_runner.h" #include "storage/browser/fileapi/file_system_usage_cache.h" #include "storage/browser/fileapi/sandbox_file_system_backend_delegate.h" #include "storage/browser/fileapi/timed_task_helper.h" #include "storage/browser/quota/quota_client.h" #include "storage/browser/quota/quota_manager_proxy.h" #include "storage/common/fileapi/file_system_util.h" namespace storage { SandboxQuotaObserver::SandboxQuotaObserver( storage::QuotaManagerProxy* quota_manager_proxy, base::SequencedTaskRunner* update_notify_runner, ObfuscatedFileUtil* sandbox_file_util, FileSystemUsageCache* file_system_usage_cache) : quota_manager_proxy_(quota_manager_proxy), update_notify_runner_(update_notify_runner), sandbox_file_util_(sandbox_file_util), file_system_usage_cache_(file_system_usage_cache) { } SandboxQuotaObserver::~SandboxQuotaObserver() {} void SandboxQuotaObserver::OnStartUpdate(const FileSystemURL& url) { DCHECK(update_notify_runner_->RunsTasksOnCurrentThread()); base::FilePath usage_file_path = GetUsageCachePath(url); if (usage_file_path.empty()) return; file_system_usage_cache_->IncrementDirty(usage_file_path); } void SandboxQuotaObserver::OnUpdate(const FileSystemURL& url, int64_t delta) { DCHECK(update_notify_runner_->RunsTasksOnCurrentThread()); if (quota_manager_proxy_.get()) { quota_manager_proxy_->NotifyStorageModified( storage::QuotaClient::kFileSystem, url.origin(), FileSystemTypeToQuotaStorageType(url.type()), delta); } base::FilePath usage_file_path = GetUsageCachePath(url); if (usage_file_path.empty()) return; pending_update_notification_[usage_file_path] += delta; if (!delayed_cache_update_helper_) { delayed_cache_update_helper_.reset( new TimedTaskHelper(update_notify_runner_.get())); delayed_cache_update_helper_->Start( FROM_HERE, base::TimeDelta(), // No delay. base::Bind(&SandboxQuotaObserver::ApplyPendingUsageUpdate, base::Unretained(this))); } } void SandboxQuotaObserver::OnEndUpdate(const FileSystemURL& url) { DCHECK(update_notify_runner_->RunsTasksOnCurrentThread()); base::FilePath usage_file_path = GetUsageCachePath(url); if (usage_file_path.empty()) return; PendingUpdateNotificationMap::iterator found = pending_update_notification_.find(usage_file_path); if (found != pending_update_notification_.end()) { UpdateUsageCacheFile(found->first, found->second); pending_update_notification_.erase(found); } file_system_usage_cache_->DecrementDirty(usage_file_path); } void SandboxQuotaObserver::OnAccess(const FileSystemURL& url) { if (quota_manager_proxy_.get()) { quota_manager_proxy_->NotifyStorageAccessed( storage::QuotaClient::kFileSystem, url.origin(), FileSystemTypeToQuotaStorageType(url.type())); } } void SandboxQuotaObserver::SetUsageCacheEnabled( const GURL& origin, FileSystemType type, bool enabled) { if (quota_manager_proxy_.get()) { quota_manager_proxy_->SetUsageCacheEnabled( storage::QuotaClient::kFileSystem, origin, FileSystemTypeToQuotaStorageType(type), enabled); } } base::FilePath SandboxQuotaObserver::GetUsageCachePath( const FileSystemURL& url) { DCHECK(sandbox_file_util_); base::File::Error error = base::File::FILE_OK; base::FilePath path = SandboxFileSystemBackendDelegate::GetUsageCachePathForOriginAndType( sandbox_file_util_, url.origin(), url.type(), &error); if (error != base::File::FILE_OK) { LOG(WARNING) << "Could not get usage cache path for: " << url.DebugString(); return base::FilePath(); } return path; } void SandboxQuotaObserver::ApplyPendingUsageUpdate() { delayed_cache_update_helper_.reset(); for (PendingUpdateNotificationMap::iterator itr = pending_update_notification_.begin(); itr != pending_update_notification_.end(); ++itr) { UpdateUsageCacheFile(itr->first, itr->second); } pending_update_notification_.clear(); } void SandboxQuotaObserver::UpdateUsageCacheFile( const base::FilePath& usage_file_path, int64_t delta) { DCHECK(!usage_file_path.empty()); if (!usage_file_path.empty() && delta != 0) file_system_usage_cache_->AtomicUpdateUsageByDelta(usage_file_path, delta); } } // namespace storage
f09e4543e3ca856723701413c11b5567f9a94182
a9481c2069749fd88f0772289e53804a212f617c
/QuadGS/Modules/dbgModule/src/dbgModule.cpp
2f085a255b97f5f58e90647c2c585f88990cefd3
[]
no_license
mlundh/QuadSys
a7e0527943505262733382093024e43aa553372e
630a7ba17434d27cbc1b2e460035e0006651d1a0
refs/heads/master
2023-01-23T15:42:48.159595
2023-01-18T13:50:46
2023-01-18T13:50:46
164,338,347
0
0
null
null
null
null
UTF-8
C++
false
false
9,007
cpp
/* * dbgModule.cpp * * Copyright (C) 2018 Martin Lundh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include "dbgModule.h" #include "msg_enums.h" #include "msgAddr.h" #include "Msg_RegUiCommand.h" #include "Msg_UiCommandResult.h" #include "Msg_Display.h" #include "Msg_BindRc.h" #include "Msg_FlightModeReq.h" #include "Msg_TestMem.h" #include "Msg_TestMemReg.h" #include "Msg_InitExternal.h" #include <sstream> #include <array> namespace QuadGS { dbgModule::dbgModule(msgAddr_t name, msgAddr_t dbgAddr):QGS_MessageHandlerBase(name),mDbgAddr(dbgAddr) { mCommands.push_back(UiCommand("dbgModuleSend","Send a message from the dbg module to any other module.",std::bind(&dbgModule::sendUiMsg, this, std::placeholders::_1))); mCommands.push_back(UiCommand("dbgGetRuntimeStats","Get runtime stats from the FC.",std::bind(&dbgModule::getRuntimeStats, this, std::placeholders::_1))); mCommands.push_back(UiCommand("rcBind","Bind the spectrum receiver.",std::bind(&dbgModule::BindRc, this, std::placeholders::_1))); mCommands.push_back(UiCommand("stateChange","Request a state change from the FC.",std::bind(&dbgModule::StateChangeReq, this, std::placeholders::_1))); mCommands.push_back(UiCommand("memTest","Test the memory on the FC.",std::bind(&dbgModule::MemTest, this, std::placeholders::_1))); mCommands.push_back(UiCommand("memReadReg","Read Status and/or device id registers.",std::bind(&dbgModule::MemReadReg, this, std::placeholders::_1))); mCommands.push_back(UiCommand("InitExternal","Initialize the external units.",std::bind(&dbgModule::InitExternal, this, std::placeholders::_1))); } dbgModule::~dbgModule() { } std::string dbgModule::sendUiMsg(std::string msg) { size_t posEndType = msg.find(" "); if(posEndType == std::string::npos) { return "Provide both message type and address."; } std::string command = msg.substr(0, posEndType); messageTypes_t type = messageTypes_t::Msg_NoType_e; for(int i = Msg_NoType_e; i < Msg_LastType_e; i++) { if(command.compare(messageTypesStr[i]) == 0) { type = static_cast<messageTypes_t>(i); break; } } if(type == messageTypes_t::Msg_NoType_e || type == messageTypes_t::Msg_LastType_e) { std::stringstream ss; ss << "No such type. " << std::endl << "Available types are: " << std::endl; for(int i = Msg_NoType_e; i < Msg_LastType_e; i++) { ss << " " << messageTypesStr[i] << std::endl; } return ss.str(); } size_t posEndAddress = msg.find(" ", posEndType+1); std::string address = msg.substr(posEndType+1, posEndAddress); msgAddr_t addr = msgAddr_t::Unassigned_e; for(const auto i : msgAddrStr) { if(address.compare(i.second) == 0) { addr = static_cast<msgAddr_t>(i.first); break; } } if(addr == msgAddr_t::Unassigned_e) { std::stringstream ss; ss << "No such address. " << std::endl << "Available addresses are: " << std::endl; for(unsigned int i = Unassigned_e; i < msgAddrStr.size(); i++) { ss << " " << msgAddrStr.at(i) << std::endl; } return ss.str(); } std::string strResponce; switch (type) { case Msg_NoType_e: { strResponce = "dbgModule: Warning: Message with no type requested."; break; } case Msg_Test_e: { Msg_Test::ptr ptr = std::make_unique<Msg_Test>(addr); sendMsg(std::move(ptr)); strResponce = "Message sent."; break; } default: { strResponce = "dbgModule: Warning: Message with unsupported type requested."; break; } } return strResponce; } std::string dbgModule::getRuntimeStats(std::string) { Msg_Debug::ptr ptr = std::make_unique<Msg_Debug>(mDbgAddr, DbgCtrl_t::QSP_DebugGetRuntimeStats, ""); sendMsg(std::move(ptr)); return ""; } std::string dbgModule::BindRc(std::string param) { uint8_t quitBind = 0; if(!param.empty()) { try { quitBind = std::stoi(param); } catch(const std::invalid_argument& e) { return "Argument not valid."; } if(quitBind != 0 && quitBind != 1) { return "Argument not valid."; } } Msg_BindRc::ptr ptr = std::make_unique<Msg_BindRc>(FC_Broadcast_e, quitBind); sendMsg(std::move(ptr)); return ""; } std::string dbgModule::InitExternal(std::string param) { Msg_InitExternal::ptr ptr = std::make_unique<Msg_InitExternal>(FC_Broadcast_e, ""); sendMsg(std::move(ptr)); return ""; } std::string dbgModule::printStateStrings() { std::stringstream ss; ss << "No such state. " << std::endl << "Available states are: " << std::endl; for (const auto& kv : mapStringToFlightMode) { ss << " " << kv.first << std::endl; } return ss.str(); } std::string dbgModule::StateChangeReq(std::string param) { if(!param.empty()) { FlightMode_t flightMode; try { flightMode = mapStringToFlightMode.at(param); } catch(const std::out_of_range & e) { return printStateStrings(); } switch (flightMode) { case FlightMode_t::fmode_init: break; case FlightMode_t::fmode_config: break; case FlightMode_t::fmode_arming: break; case FlightMode_t::fmode_disarming: break; default: return printStateStrings(); } Msg_FlightModeReq::ptr ptr = std::make_unique<Msg_FlightModeReq>(FC_Broadcast_e, flightMode); sendMsg(std::move(ptr)); } else { return printStateStrings(); } return "Request sent"; } std::string dbgModule::MemTest(std::string param) { std::array<std::string, 4> tokens; for(int i = 0; i < 4; i++) { size_t pos = 0; pos = param.find(" "); tokens[i] = param.substr(0, pos); param.erase(0, pos + 1); if(pos == std::string::npos && i != 3) { return "Please provide all arguments separated with space: Write [1/0] startAddress[0-255] startNumber[0-255] size[0-255]"; } } std::array<uint8_t, 4> args; for(int i = 0; i < 4; i++) { try { args[i] = static_cast<uint8_t>(std::stoi(tokens[i])); } catch(const std::invalid_argument& e) { std::cerr << e.what() << '\n'; return "Only numbers are valid as arguments."; } } Msg_TestMem::ptr ptr = std::make_unique<Msg_TestMem>(FC_Broadcast_e, args[0], args[1], args[2], args[3]); sendMsg(std::move(ptr)); return "Test started."; } std::string dbgModule::MemReadReg(std::string param) { std::array<std::string, 2> tokens; for(int i = 0; i < 2; i++) { size_t pos = 0; pos = param.find(" "); tokens[i] = param.substr(0, pos); param.erase(0, pos + 1); if(pos == std::string::npos && i != 1) { return "Please provide all arguments separated with space."; } } std::array<uint8_t, 2> args; for(int i = 0; i < 2; i++) { try { args[i] = static_cast<uint8_t>(std::stoi(tokens[i])); } catch(const std::invalid_argument& e) { std::cerr << e.what() << '\n'; return "Only numbers are valid as arguments."; } if(args[i] != 1 && args[i] != 0) { return "Only 1 or 0 are valid as arguments."; } } Msg_TestMemReg::ptr ptr = std::make_unique<Msg_TestMemReg>(FC_Broadcast_e, args[0], args[1]); sendMsg(std::move(ptr)); return "Test started."; } void dbgModule::process(Msg_GetUiCommands* message) { for(UiCommand command : mCommands) { Msg_RegUiCommand::ptr ptr = std::make_unique<Msg_RegUiCommand>(message->getSource(), command.command, command.doc); sendMsg(std::move(ptr)); } } void dbgModule::process(Msg_FireUiCommand* message) { for(UiCommand command : mCommands) { if(command.command.compare(message->getCommand()) == 0) { std::string result = command.function(message->getArgs()); Msg_UiCommandResult::ptr ptr = std::make_unique<Msg_UiCommandResult>(message->getSource(), result); sendMsg(std::move(ptr)); return; } } std::cout << "no such command."; Msg_UiCommandResult::ptr ptr = std::make_unique<Msg_UiCommandResult>(message->getSource(), "No such command."); sendMsg(std::move(ptr)); return; } void dbgModule::process(Msg_Debug* message) { Msg_Display::ptr ptr = std::make_unique<Msg_Display>(msgAddr_t::GS_GUI_e, message->getPayload()); sendMsg(std::move(ptr)); } } /* namespace QuadGS */
2f3ed7752c5605039e41ee153f53d625667a27c1
db4d9954a6c095397d7f1de33cc32519dff6ef6c
/src/sais.hpp
ee24a53bdd7eef01688ecfb641bc97a28503a1fd
[ "BSD-3-Clause" ]
permissive
SebWouters/aiss4
3f890d1ac5cbb0710769c364ae79a50b39cce30a
f46ea04e573b77abec74459f018d32bd0bdc8865
refs/heads/main
2023-02-04T14:54:43.893368
2020-12-21T16:44:27
2020-12-21T16:44:27
323,388,885
0
0
null
null
null
null
UTF-8
C++
false
false
19,075
hpp
/* aiss4: suffix array via induced sorting Copyright (c) 2020, Sebastian Wouters All rights reserved. This file is part of aiss4, licensed under the BSD 3-Clause License. A copy of the License can be found in the file LICENSE in the root folder of this project. */ #pragma once #include <stdint.h> #include <stdlib.h> #include <memory.h> namespace aiss4 { template <class index_t, class data_t, class idx_t> void sais_recursion(index_t * suffix, const index_t str_size, const index_t num_lms, const index_t name, const index_t bound); template <class token_t, class index_t> void sais_implementation(const token_t * orig, const index_t abc_size, index_t * suffix, const index_t str_size, index_t * work1, index_t * work2) { if (str_size < 2 || abc_size < 2 || orig == NULL || suffix == NULL) { if (str_size == 1) suffix[0] = 0; return; } index_t * head = work1 ? work1 : new index_t[abc_size]; index_t * locs = work2 ? work2 : new index_t[abc_size]; const size_t memcpy_head_size = sizeof(index_t) * static_cast<size_t>(abc_size); const size_t memcpy_tail_size = sizeof(index_t) * static_cast<size_t>(abc_size - 1); // Step 0: Compute bucket heads for (index_t chr = 0; chr < abc_size; ++chr){ head[chr] = 0; } for (index_t odx = 0; odx < str_size; ++odx){ ++head[orig[odx]]; } { index_t total = 0; index_t tmp; for (index_t chr = 0; chr < abc_size; ++chr) { tmp = head[chr]; head[chr] = total; total += tmp; } } // Step 1: Place the L prefix indices of LMS substrings (i.e. index of preceding L-type character) at bucket tail // Bucket: [ 0 0 0 0 (L-string) | 0 0 0 0 (S-string) ] --> [ 0 0 0 0 (L-string) | 0 0 a b (S-string) ] // orig[a], orig[b] are L-type prefixes of LMS substrings memcpy(locs, head + 1, memcpy_tail_size); locs[abc_size - 1] = str_size; index_t num_lms = 0; { for (index_t sdx = 0; sdx < str_size; ++sdx) { suffix[sdx] = 0; } index_t odx = str_size - 1; // orig index token_t cur; // current character token_t prv = orig[odx--]; // previous character: orig[str_size - 1] is L-type while (odx > 0) // orig[0] cannot be LMS { while (odx >= 0 && (cur = orig[odx]) >= prv){ --odx; prv = cur; } // First S-type is cur = orig[odx]; prv L-type while (odx >= 0 && (cur = orig[odx]) <= prv){ --odx; prv = cur; } // First L-type is cur = orig[odx]; prv S-type if (odx >= 0) { suffix[--locs[prv]] = odx; // Index of preceding L-type character ++num_lms; } } } // Step 2: Place the prefix indices of L-type characters at bucket head, retain S-type only // Bucket: [ 0 0 0 0 (L-string) | 0 0 a b (S-string) ] --> [ 0 c 0 d (L-string) | 0 0 0 0 (S-string) ] // orig[a], orig[b] are L-type prefixes of LMS substrings. // All inductions from an LMS substring will be at larger indices, // because insertion occurs at head, and L-type implies later bucket. // If the L-prefix has an L-prefix: handled & reset later in the for-loop. // If the L-prefix has an S-prefix: bit-flipped later in the for-loop. // orig[c], orig[d] are S-type prefixes of L-type strings. memcpy(locs, head, memcpy_head_size); { index_t odx = str_size - 1; // orig index token_t act = orig[odx--]; // active character: orig[str_size - 1] is L-type before '$' token_t chk; // check character index_t * loc = suffix + locs[act]; // bucket location: speed-up w.r.t. suffix[--locs[act]] *loc++ = orig[odx] < act ? ~odx : odx; for (index_t sdx = 0; sdx < str_size; ++sdx) // suffix index if ((odx = suffix[sdx]) > 0) // L-type { if ((chk = orig[odx--]) != act) { locs[act] = loc - suffix; loc = suffix + locs[act = chk]; } *loc++ = orig[odx] < act ? ~odx : odx; // Index preceding L-type character suffix[sdx] = 0; // Reset } else if (odx < 0) // S-type becomes positive { suffix[sdx] = ~odx; } } // Step 3: Place the prefix indices of S-type characters at bucket tail, retain LMS only // Bucket: [ 0 c 0 d (L-string) | 0 0 0 0 (S-string) ] --> [ 0 0 0 0 (S-string) | 0 e f 0 (S-string) ] // orig[c], orig[d] are S-type prefixes of L-type strings // All inductions from L-type strings will be at smaller indices, // because insertion occurs at tail, and S-type implies earlier bucket. // If the S-prefix has an S-prefix: handled & reset later in the for-loop. // If the S-prefix has an L-prefix: set to LMS index (negative). // orig[e], orig[f] are initial characters of LMS substrings. memcpy(locs, head + 1, memcpy_tail_size); locs[abc_size - 1] = str_size; { index_t odx; // orig index token_t act = 0; // active character token_t chk; // check character index_t * loc = suffix + locs[act]; // bucket location: speed-up w.r.t. suffix[--locs[act]] for (index_t sdx = str_size - 1; sdx >= 0; --sdx) // suffix index if ((odx = suffix[sdx]) > 0) // Check for S-type { if ((chk = orig[odx--]) != act) { locs[act] = loc - suffix; loc = suffix + locs[act = chk]; } *--loc = orig[odx] > act ? ~(odx + 1) : odx; // LMS negative with start index; S-type positive suffix[sdx] = 0; // Reset } } // All non-size one LMS prefixes and sentinel are sorted in SA: compute names for reduced problem // Step 4: Move LMS odx to front { index_t lms = 0; // lms index index_t odx; // orig index // 2 * num_lms <= str_size, so while stops before lms == str_size while ((odx = suffix[lms]) < 0) { suffix[lms++] = ~odx; } if (lms < num_lms) for (index_t sdx = lms + 1; sdx < str_size; ++sdx) // suffix index if ((odx = suffix[sdx]) < 0) { suffix[lms++] = ~odx; suffix[sdx] = 0; } } // Step 5: Store the length of LMS substring orig[odx] at suffix[num_lms + (odx >> 1)] // Character preceding or following LMS character cannot be LMS; 2 * num_lms <= str_size { index_t odx = str_size - 1; // orig index index_t pdx = odx; // previous index token_t cur; // current character token_t prv = orig[odx--]; // previous character: orig[str_size - 1] is L-type while (odx > 0) // orig[0] cannot be LMS { while (odx >= 0 && (cur = orig[odx]) >= prv){ --odx; prv = cur; } // First S-type is cur = orig[odx]; prv L-type while (odx >= 0 && (cur = orig[odx]) <= prv){ --odx; prv = cur; } // First L-type is cur = orig[odx]; prv S-type if (odx >= 0) { suffix[num_lms + ((odx + 1) >> 1)] = pdx - odx; pdx = odx; } } } // Step 6: Compute names // - odx = suffix[sdx < num_lms] are ordered LMS substrings // (only substrings - not entire suffixes - are ordered) // - len = suffix[num_lms + (odx + 1) >> 1] contains length index_t name = 0; { index_t prv_pos = str_size; index_t prv_len = 0; index_t cur_pos; index_t cur_len; index_t odx; bool diff; for (index_t lms = 0; lms < num_lms; ++lms) { cur_pos = suffix[lms]; cur_len = suffix[num_lms + (cur_pos >> 1)]; diff = true; if (cur_len == prv_len) // Any LMS (except for '$' with length 0) has length at least two { for (odx = 0; odx < prv_len && orig[cur_pos + odx] == orig[prv_pos + odx]; ++odx) { } if (odx == prv_len) { diff = false; } } /* The above is faster than: bool same = cur_len == prv_len; for (index_t odx = 0; same && odx < prv_len; ++odx) same = orig[cur_pos + odx] == orig[prv_pos + odx]; if (!same) { ... } */ if (diff) { ++name; prv_pos = cur_pos; prv_len = cur_len; } suffix[num_lms + (cur_pos >> 1)] = name; } } // Step 7: Solve recursion problem // 2 * (name - 1) < 2 * num_lms <= str_size (index_t) // --> data_bytes <= index_bytes <= sizeof(index_t) const index_t bound = str_size & static_cast<index_t>(1) ? (str_size >> 1) + 1 : (str_size >> 1); uint8_t index_bytes = 255; if (name == num_lms) { index_bytes = sizeof(index_t); index_t * source = suffix + num_lms; index_t lms = 0; for (index_t sdx = 0; sdx < bound; ++sdx) if (source[sdx] > 0) suffix[source[sdx] - 1] = lms++; } else { const uint8_t data_bytes = static_cast<size_t>(name - 1) <= static_cast<size_t>( UINT8_MAX) ? 1 : (static_cast<size_t>(name - 1) <= static_cast<size_t>(UINT16_MAX) ? 2 : (static_cast<size_t>(name - 1) <= static_cast<size_t>(UINT32_MAX) ? 4 : 8)); index_bytes = static_cast<size_t>(num_lms) <= static_cast<size_t>( INT8_MAX) ? 1 : (static_cast<size_t>(num_lms) <= static_cast<size_t>(INT16_MAX) ? 2 : (static_cast<size_t>(num_lms) <= static_cast<size_t>(INT32_MAX) ? 4 : 8)); if (data_bytes == 8) { // str_size > num_lms > name - 1 > UINT32_MAX > INT32_MAX: recursion index_t (for num_lms) can only be int64_t sais_recursion<index_t, uint64_t, int64_t>(suffix, str_size, num_lms, name, bound); } else if (data_bytes == 4) { // str_size > num_lms > name - 1 > UINT16_MAX > INT16_MAX: recursion index_t (for num_lms) can only be int32_t or int64_t if (index_bytes == 8) sais_recursion<index_t, uint32_t, int64_t>(suffix, str_size, num_lms, name, bound); else // index_bytes == 4 sais_recursion<index_t, uint32_t, int32_t>(suffix, str_size, num_lms, name, bound); } else if (data_bytes == 2) { // str_size > num_lms > name - 1 > UINT8_MAX > INT8_MAX: recursion index_t (for num_lms) can only be int16_t, int32_t or int64_t if (index_bytes == 8) sais_recursion<index_t, uint16_t, int64_t>(suffix, str_size, num_lms, name, bound); else if (index_bytes == 4) sais_recursion<index_t, uint16_t, int32_t>(suffix, str_size, num_lms, name, bound); else // index_bytes == 2 sais_recursion<index_t, uint16_t, int16_t>(suffix, str_size, num_lms, name, bound); } else // if (data_bytes == 1) { if (index_bytes == 8) sais_recursion<index_t, uint8_t, int64_t>(suffix, str_size, num_lms, name, bound); else if (index_bytes == 4) sais_recursion<index_t, uint8_t, int32_t>(suffix, str_size, num_lms, name, bound); else if (index_bytes == 2) sais_recursion<index_t, uint8_t, int16_t>(suffix, str_size, num_lms, name, bound); else // index_bytes == 1 sais_recursion<index_t, uint8_t, int8_t>(suffix, str_size, num_lms, name, bound); } } // Step 8: Build suffix[lms] = P1[SA1[lms]] { index_t * P1 = suffix + num_lms; index_t odx = str_size - 1; index_t lms = num_lms; token_t cur; token_t prv = orig[odx--]; // orig[str_size - 1] is L-type while (odx > 0) // orig[0] cannot be LMS { while (odx >= 0 && (cur = orig[odx]) >= prv){ --odx; prv = cur; } // First S-type is cur = orig[odx]; prv L-type while (odx >= 0 && (cur = orig[odx]) <= prv){ --odx; prv = cur; } // First L-type is cur = orig[odx]; prv S-type if (odx >= 0) P1[--lms] = odx + 1; } if (index_bytes == 8) { int64_t * SA1 = reinterpret_cast<int64_t *>(suffix); for (index_t lms = num_lms - 1; lms >= 0; --lms) suffix[lms] = P1[SA1[lms]]; } else if (index_bytes == 4) { int32_t * SA1 = reinterpret_cast<int32_t *>(suffix); for (index_t lms = num_lms - 1; lms >= 0; --lms) suffix[lms] = P1[SA1[lms]]; } else if (index_bytes == 2) { int16_t * SA1 = reinterpret_cast<int16_t *>(suffix); for (index_t lms = num_lms - 1; lms >= 0; --lms) suffix[lms] = P1[SA1[lms]]; } else // index_bytes == 1 { int8_t * SA1 = reinterpret_cast<int8_t *>(suffix); for (index_t lms = num_lms - 1; lms >= 0; --lms) suffix[lms] = P1[SA1[lms]]; } } // Step 9: Place the LMS characters at their bucket tails // Assumes the LMS indices are in correct order stored in suffix[0:num_lms]; // they can hence only be moved to the right memcpy(locs, head + 1, memcpy_tail_size); locs[abc_size - 1] = str_size; { index_t lms = num_lms - 1; // lms index index_t odx = suffix[lms]; // orig index index_t sdx = str_size; // suffix index token_t act; // active character token_t chk = orig[odx]; // check character index_t end; while (lms >= 0) { end = locs[act = chk]; while (sdx > end) { suffix[--sdx] = 0; } do { suffix[--sdx] = odx; if (--lms < 0){ break; } odx = suffix[lms]; } while ((chk = orig[odx]) == act); } while (sdx > 0) { suffix[--sdx] = 0; } } // Step 10: Place the indices of L-type characters at bucket head // Bucket: [ 0 0 0 0 (L-string) | 0 0 a b (S-string) ] --> [ c d e f (L-string) | 0 0 a b (S-string) ] // Before: a, b are LMS substring starts. // a, b > 0 because they induce L-type. // Inductions will be at later indices, because insertion at head, and L-type implies later. // After: orig[c:], orig[d:], orig[e:], orig[f:] are induced L-type strings. // a, b, c, d, e, f < 0 if they induce L-type; a, b, c, d, e, f > 0 if they induce S-type. memcpy(locs, head, memcpy_head_size); { index_t odx = str_size - 1; // orig index token_t act = orig[odx]; // active character: orig[str_size - 1] is L-type before '$' token_t chk; // check character index_t * loc = suffix + locs[act]; // bucket location: speed-up w.r.t. suffix[--locs[act]] *loc++ = odx > 0 && orig[odx - 1] < act ? ~odx : odx; // < 0 resp. > 0 means it induces S-type resp. L-type for (index_t sdx = 0; sdx < str_size; ++sdx) // suffix index { odx = suffix[sdx]; suffix[sdx] = ~odx; // L-type becomes negative, S-type positive if (odx > 0) // L-type { if ((chk = orig[--odx]) != act) { locs[act] = loc - suffix; loc = suffix + locs[act = chk]; } *loc++ = odx > 0 && orig[odx - 1] < act ? ~odx : odx; // L-type positive, but after later handling negative } } } // Step 11: Place the indices of S-type characters at bucket tail // Bucket: [ c d e f (L-string) | 0 0 a b (S-string) ] --> [ c d e f (L-string) | g h i j (S-string) ] // Before: a, b, c, d, e, f < 0 if they induce L-type; a, b, c, d, e, f > 0 if they induce S-type // Inductions will be at earlier indices, because insertions at tail, and S-type implies earlier. // After: all indices >= 0. memcpy(locs, head + 1, memcpy_tail_size); locs[abc_size - 1] = str_size; { index_t odx; // orig index token_t act = 0; // active character token_t chk; // check character index_t * loc = suffix + locs[act]; // bucket location: speed-up w.r.t. suffix[--locs[act]] for (index_t sdx = str_size - 1; sdx >= 0; --sdx) // suffix index if ((odx = suffix[sdx]) > 0) // S-type { if ((chk = orig[--odx]) != act) { locs[act] = loc - suffix; loc = suffix + locs[act = chk]; } *--loc = odx == 0 || orig[odx - 1] > act ? ~odx : odx; // L-type negative, S-type positive } else { suffix[sdx] = ~odx; // Make L-type positive } } if (!work1) { delete [] head; } if (!work2) { delete [] locs; } } template <class index_t, class data_t, class idx_t> void sais_recursion(index_t * suffix, const index_t str_size, const index_t num_lms, const index_t name, const index_t bound) { int8_t * buffer = reinterpret_cast<int8_t *>(suffix); size_t space_bfr = sizeof(index_t) * static_cast<size_t>(str_size); size_t space_sa1 = sizeof( idx_t) * static_cast<size_t>(num_lms); size_t space_s1 = sizeof( data_t) * static_cast<size_t>(num_lms); size_t space_w12 = sizeof( idx_t) * static_cast<size_t>(name); index_t * src = suffix + num_lms; data_t * S1 = reinterpret_cast<data_t *>(buffer + space_sa1); idx_t * SA1 = reinterpret_cast< idx_t *>(buffer); idx_t * work1 = space_sa1 + space_s1 + space_w12 <= space_bfr ? reinterpret_cast<idx_t *>(buffer + space_sa1 + space_s1) : NULL; idx_t * work2 = space_sa1 + space_s1 + 2 * space_w12 <= space_bfr ? work1 + name : NULL; index_t lms = 0; for (index_t sdx = 0; sdx < bound; ++sdx) if (src[sdx] > 0) S1[lms++] = static_cast<data_t>(src[sdx] - 1); sais_implementation<data_t, idx_t>(S1, static_cast<idx_t>(name), SA1, static_cast<idx_t>(num_lms), work1, work2); } void sais(const uint8_t * orig, int64_t * suffix, const int64_t size) { sais_implementation<uint8_t, int64_t>(orig, 256, suffix, size, NULL, NULL); } void sais(const uint8_t * orig, int32_t * suffix, const int32_t size) { sais_implementation<uint8_t, int32_t>(orig, 256, suffix, size, NULL, NULL); } } // End of namespace aiss4
ffedde0ddd6372d83c00eb3a10de028385aca107
f6e28e7a1b2485b18d712fb092fea5fdeaa1d85c
/src/camera.cpp
2f6e26b2521fcba55b420184f2ff5aaca44d8c82
[]
no_license
eypidan/deformation_opengl
dba4676c076f83e9b3a7ac14614bebb9d055a6e9
043f605a508287f249d235a17ba09cc14870f5f1
refs/heads/master
2022-11-10T22:49:35.874839
2020-06-30T15:05:00
2020-06-30T15:05:00
262,209,820
0
0
null
null
null
null
UTF-8
C++
false
false
460
cpp
#include "pch.h" double mouseX, mouseY; glm::vec3 Camera::createRay() { glm::mat4 view = this->GetViewMatrix(); glm::mat4 proj = this->GetPerspectiveMatrix(); glm::mat4 invVP = glm::inverse(proj * view); double trueMouseY = SCR_HEIGHT / 1.0f - mouseY; glm::vec4 screenPos = glm::vec4(mouseX, trueMouseY, 1.0f, 1.0f); glm::vec4 worldPos = invVP * screenPos; glm::vec3 dir = glm::normalize(glm::vec3(worldPos)); return dir; }
a30a29fcb585b36c5e91d62f9c2e96ae3d6429a8
a7914b450aeae015a24ba90e5ce60d41d5c592a9
/SummerTraining/7.27 线性与区间dp/问题B Common Subsequence.cpp
ec9513f41077878c33c17cc802ca86b644a8bcf8
[]
no_license
packbacker-s/CCode
07eb157e0be7eade9d72807a508f4a9dee6eed90
4a2ac77352989f38c372671ac4e562aea7a25d96
refs/heads/master
2023-08-11T07:20:49.297388
2021-10-01T08:51:53
2021-10-01T08:51:53
412,320,148
0
0
null
null
null
null
UTF-8
C++
false
false
574
cpp
#include<iostream> #include<cstring> using namespace std; string n,m,temp; int main (){ while(cin >> n >> m){ if(n.size() < m.size()){ temp = n; n = m; m = temp; } int dp[n.size()+10][n.size()+10]; memset(dp ,0 ,sizeof dp); int maxn = 0; for(int i = 0; i < m.size();i++){ int k = i +1; for(int j = 0; j < n.size();j++){ int l = j +1; if(n[j] == m[i]){ dp[k][l] = dp[k-1][l-1 ]+ 1; } else dp[k][l]= max(dp[k-1][l],dp[k][l-1]); maxn = max(maxn ,dp[k][l]); } } cout << dp[m.size()][n.size()] << endl; } return 0; }
9903869b3943fb2b52b873e6635e6866f21561e3
b0dd7779c225971e71ae12c1093dc75ed9889921
/boost/fusion/include/make_tuple.hpp
49b653edd0d6300ed7813f877599eaa2d935e528
[ "BSL-1.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
blackberry/Boost
6e653cd91a7806855a162347a5aeebd2a8c055a2
fc90c3fde129c62565c023f091eddc4a7ed9902b
refs/heads/1_48_0-gnu
2021-01-15T14:31:33.706351
2013-06-25T16:02:41
2013-06-25T16:02:41
2,599,411
244
154
BSL-1.0
2018-10-13T18:35:09
2011-10-18T14:25:18
C++
UTF-8
C++
false
false
500
hpp
/*============================================================================= Copyright (c) 2001-2007 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(FUSION_INCLUDE_MAKE_TUPLE) #define FUSION_INCLUDE_MAKE_TUPLE #include <boost/fusion/tuple/make_tuple.hpp> #endif
9cb57d6271a4d39346f2a1c0e0ed093271908c19
524591f2c4f760bc01c12fea3061833847a4ff9a
/arm/usr/include/Poco/Net/TCPServer.h
49411d9c400560bceb079f1efebed899fc80e248
[ "BSD-3-Clause" ]
permissive
Roboy/roboy_plexus
6f78d45c52055d97159fd4d0ca8e0f32f1fbd07e
1f3039edd24c059459563cb81d194326fe824905
refs/heads/roboy3
2023-03-10T15:01:34.703853
2021-08-16T13:42:54
2021-08-16T13:42:54
101,666,005
2
4
BSD-3-Clause
2022-10-22T13:43:45
2017-08-28T16:53:52
C++
UTF-8
C++
false
false
7,131
h
// // TCPServer.h // // $Id: //poco/1.3/Net/include/Poco/Net/TCPServer.h#4 $ // // Library: Net // Package: TCPServer // Module: TCPServer // // Definition of the TCPServer class. // // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #ifndef Net_TCPServer_INCLUDED #define Net_TCPServer_INCLUDED #include "Poco/Net/Net.h" #include "Poco/Net/ServerSocket.h" #include "Poco/Net/TCPServerConnectionFactory.h" #include "Poco/Net/TCPServerParams.h" #include "Poco/Runnable.h" #include "Poco/Thread.h" #include "Poco/ThreadPool.h" namespace Poco { namespace Net { class TCPServerDispatcher; class Net_API TCPServer: public Poco::Runnable /// This class implements a multithreaded TCP server. /// /// The server uses a ServerSocket to listen for incoming /// connections. The ServerSocket must have been bound to /// an address before it is passed to the TCPServer constructor. /// Additionally, the ServerSocket must be put into listening /// state before the TCPServer is started by calling the start() /// method. /// /// The server uses a thread pool to assign threads to incoming /// connections. Before incoming connections are assigned to /// a connection thread, they are put into a queue. /// Connection threads fetch new connections from the queue as soon /// as they become free. Thus, a connection thread may serve more /// than one connection. /// /// As soon as a connection thread fetches the next connection from /// the queue, it creates a TCPServerConnection object for it /// (using the TCPServerConnectionFactory passed to the constructor) /// and calls the TCPServerConnection's start() method. When the /// start() method returns, the connection object is deleted. /// /// The number of connection threads is adjusted dynamically, depending /// on the number of connections waiting to be served. /// /// It is possible to specify a maximum number of queued connections. /// This prevents the connection queue from overflowing in the /// case of an extreme server load. In such a case, connections that /// cannot be queued are silently and immediately closed. /// /// TCPServer uses a separate thread to accept incoming connections. /// Thus, the call to start() returns immediately, and the server /// continues to run in the background. /// /// To stop the server from accepting new connections, call stop(). /// /// After calling stop(), no new connections will be accepted and /// all queued connections will be discarded. /// Already served connections, however, will continue being served. { public: TCPServer(TCPServerConnectionFactory::Ptr pFactory, const ServerSocket& socket, TCPServerParams::Ptr pParams = 0); /// Creates the TCPServer, using the given ServerSocket. /// /// The server takes ownership of the TCPServerConnectionFactory /// and deletes it when it's no longer needed. /// /// The server also takes ownership of the TCPServerParams object. /// If no TCPServerParams object is given, the server's TCPServerDispatcher /// creates its own one. /// /// News threads are taken from the default thread pool. TCPServer(TCPServerConnectionFactory::Ptr pFactory, Poco::ThreadPool& threadPool, const ServerSocket& socket, TCPServerParams::Ptr pParams = 0); /// Creates the TCPServer, using the given ServerSocket. /// /// The server takes ownership of the TCPServerConnectionFactory /// and deletes it when it's no longer needed. /// /// The server also takes ownership of the TCPServerParams object. /// If no TCPServerParams object is given, the server's TCPServerDispatcher /// creates its own one. /// /// News threads are taken from the given thread pool. virtual ~TCPServer(); /// Destroys the TCPServer and its TCPServerConnectionFactory. const TCPServerParams& params() const; /// Returns a const reference to the TCPServerParam object /// used by the server's TCPServerDispatcher. void start(); /// Starts the server. A new thread will be /// created that waits for and accepts incoming /// connections. /// /// Before start() is called, the ServerSocket passed to /// TCPServer must have been bound and put into listening state. void stop(); /// Stops the server. /// /// No new connections will be accepted. /// Already handled connections will continue to be served. /// /// Once the server is stopped, it cannot be restarted. int currentThreads() const; /// Returns the number of currently used connection threads. int totalConnections() const; /// Returns the total number of handled connections. int currentConnections() const; /// Returns the number of currently handled connections. int maxConcurrentConnections() const; /// Returns the maximum number of concurrently handled connections. int queuedConnections() const; /// Returns the number of queued connections. int refusedConnections() const; /// Returns the number of refused connections. Poco::UInt16 port() const; /// Returns the port the server socket listens to protected: void run(); /// Runs the server. The server will run until /// the stop() method is called, or the server /// object is destroyed, which implicitly calls /// the stop() method. static std::string threadName(const ServerSocket& socket); /// Returns a thread name for the server thread. private: TCPServer(); TCPServer(const TCPServer&); TCPServer& operator = (const TCPServer&); ServerSocket _socket; TCPServerDispatcher* _pDispatcher; Poco::Thread _thread; bool _stopped; }; inline Poco::UInt16 TCPServer::port() const { return _socket.address().port(); } } } // namespace Poco::Net #endif // Net_TCPServer_INCLUDED
d1a8c18efbaef36943e85ec82d03acb74845893a
69de20a373be583f71b0ca6a15b01f4bf46353c3
/Source/NS/NSProjectile.h
fdb6ad92901c2098227884c801ade005de37a563
[]
no_license
AlvaroVV/ShooterUnreal
32279108ad34d5091fc80c1f89e1c57b1c4e5c92
ac244bc546e8f032bf62a0161368a2f560bea8c7
refs/heads/master
2021-05-06T02:39:22.445220
2021-03-19T17:13:29
2021-03-19T17:13:29
114,656,039
0
0
null
null
null
null
UTF-8
C++
false
false
1,069
h
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #pragma once #include "GameFramework/Actor.h" #include "NSProjectile.generated.h" UCLASS(config=Game) class ANSProjectile : public AActor { GENERATED_BODY() /** Sphere collision component */ UPROPERTY(VisibleDefaultsOnly, Category=Projectile) class USphereComponent* CollisionComp; /** Projectile movement component */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Movement, meta = (AllowPrivateAccess = "true")) class UProjectileMovementComponent* ProjectileMovement; public: ANSProjectile(); /** called when projectile hits something */ UFUNCTION() void OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit); /** Returns CollisionComp subobject **/ FORCEINLINE class USphereComponent* GetCollisionComp() const { return CollisionComp; } /** Returns ProjectileMovement subobject **/ FORCEINLINE class UProjectileMovementComponent* GetProjectileMovement() const { return ProjectileMovement; } };
2fa4cd8a934d157a6ccffc4823791b8bbb92f5de
b212c52146f58909fca295ea6fb8a0b619a7fd00
/queueexample3/queue.h
48323256903acebb7cfe9b5690d5789937a4c195
[]
no_license
Darkmind14/cs253
0df50d29fabd00ff3d36cd959326cda524416110
f2c74fd14facdfba2f09b19c2ab277227cae1679
refs/heads/master
2016-08-13T01:06:20.460450
2015-12-15T23:26:29
2015-12-15T23:26:29
45,935,859
0
0
null
null
null
null
UTF-8
C++
false
false
722
h
#ifndef queue_h #define queue_h #include <vector> using namespace std; class EmptyQueueException { public: EmptyStringException(string); string getMessage(); private: string msg; }; class Node { public: Node(int, Node*); ~Node(); Node* getNext(); int getData(); void setNext(Node*); void setData(int); private: int val; Node* next; }; class Queue { public: Queue(); ~Queue(); // not queue, deconstructor // the enqueue method enqueues an item on the queue. void enqueue(int item); int dequeue(); bool isEmpty(); private: Node* head; Node* tail; }; Queue& operator<<(Queue&, int); Queue& operator>>(Queue&, int&); #endif
5002d0bbd5475ef59a6265f64f20492899d8e6fb
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/third_party/WebKit/Source/platform/text/UnicodeUtilities.h
c97cbe82afb7936c4a71139b59297f72928bbe73
[ "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
2,730
h
/* * Copyright (C) 2004, 2006, 2009 Apple 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 UnicodeUtilities_h #define UnicodeUtilities_h #include "platform/PlatformExport.h" #include "platform/wtf/Vector.h" #include "platform/wtf/text/Unicode.h" #include "platform/wtf/text/WTFString.h" namespace blink { PLATFORM_EXPORT bool IsSeparator(UChar32); PLATFORM_EXPORT bool IsKanaLetter(UChar character); PLATFORM_EXPORT bool ContainsKanaLetters(const String&); PLATFORM_EXPORT void NormalizeCharactersIntoNFCForm(const UChar* characters, unsigned length, Vector<UChar>& buffer); PLATFORM_EXPORT void FoldQuoteMarksAndSoftHyphens(UChar* data, size_t length); PLATFORM_EXPORT void FoldQuoteMarksAndSoftHyphens(String&); PLATFORM_EXPORT bool CheckOnlyKanaLettersInStrings(const UChar* first_data, unsigned first_length, const UChar* second_data, unsigned second_length); PLATFORM_EXPORT bool CheckKanaStringsEqual(const UChar* first_data, unsigned first_length, const UChar* second_data, unsigned second_length); } // namespace blink #endif // UnicodeUtilities_h
48b3e1195e4cdff8a4716fa394de544933cabaa2
ab0130f06d681dd6171c91b5851c8db383225ea3
/cpp/MyClothingManagement/MyStack.cpp
550d888fbdb05aa5d0f1cc4bb37e5676b3258a6c
[]
no_license
mborko/code-examples
6750f316a26791863e08ac08dba8ae3ec00234d1
3ea2be6179f0ed3094c66da0259d021067eb00c2
refs/heads/master
2022-10-25T19:36:00.745573
2022-10-01T13:57:19
2022-10-01T13:57:19
43,496,571
0
13
null
2020-10-13T06:47:43
2015-10-01T13:00:24
C
UTF-8
C++
false
false
716
cpp
#include "MyStack.h" using namespace std; MyStack::MyStack(void) { } MyStack::~MyStack(void) { for(;lastindex>0;lastindex--) minus(); } int MyStack::lastindex=-1; void MyStack::plus(string c) { if (c=="shirt"){ Clothing* temp = new Shirt(); elements.push_back(temp); } if (c=="jeans") elements.push_back(new Jeans()); if (c=="dress") elements.push_back(new Dress()); lastindex++; cout << elements.at(lastindex)->id << endl; } void MyStack::minus() { if(elements.size() > 0){ cout << "first" << endl; if( lastindex > -1 ) { cout << elements.at(lastindex)->id << endl; delete elements.back(); elements.pop_back(); lastindex--; } }else cout << "Liste ist leer." << endl; }
288aa2379ab5bd3397b925e7e83722abbd921944
df6bfd60ac6812d09d2a51be654ac215f45fe887
/hit.h
1495f772ed1a2473a8ec29b34b067936485d5197
[]
no_license
seoyh0812/TeamLaunge
b4db82fa31364268713ec0c98d1ef68137a81228
c8d5f9116e7eb4131703e4b720c5f40499ca0cd5
refs/heads/master
2023-03-29T07:04:45.689621
2021-03-18T13:37:14
2021-03-18T13:37:14
325,739,522
0
0
null
null
null
null
UTF-8
C++
false
false
177
h
#pragma once #include "STATE.h" class player; class hit : public STATE { private: int count; public: void EnterState(); void updateState(); void ExitState(); };
81a88c043f10f25aee472f40e0fac541d40b778a
9f5242ec43c65ba0d032044cf655723a77ddc689
/src/rpcprotocol.cpp
2681dd4d653d557e78d39ef799179df1dc67bdf2
[ "MIT" ]
permissive
TScoin/Transend
22bb1691dc9b86ca7b9ceb4d9dd1be23eae29e7f
6f8f75dbba962dfe9fc9d85b79cebf20625f871d
refs/heads/master
2021-01-25T13:28:20.681340
2018-10-04T22:45:40
2018-10-04T22:45:40
123,572,575
14
8
MIT
2018-03-14T19:50:15
2018-03-02T11:43:38
C++
UTF-8
C++
false
false
9,172
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017-2018 The Transend developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcprotocol.h" #include "clientversion.h" #include "tinyformat.h" #include "util.h" #include "utilstrencodings.h" #include "utiltime.h" #include "version.h" #include <stdint.h> #include "json/json_spirit_writer_template.h" #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/shared_ptr.hpp> using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; //! Number of bytes to allocate and read at most at once in post data const size_t POST_READ_SIZE = 256 * 1024; /** * HTTP protocol * * This ain't Apache. We're just using HTTP header for the length field * and to be compatible with other JSON-RPC implementations. */ string HTTPPost(const string& strMsg, const map<string, string>& mapRequestHeaders) { ostringstream s; s << "POST / HTTP/1.1\r\n" << "User-Agent: transend-json-rpc/" << FormatFullVersion() << "\r\n" << "Host: 127.0.0.1\r\n" << "Content-Type: application/json\r\n" << "Content-Length: " << strMsg.size() << "\r\n" << "Connection: close\r\n" << "Accept: application/json\r\n"; BOOST_FOREACH (const PAIRTYPE(string, string) & item, mapRequestHeaders) s << item.first << ": " << item.second << "\r\n"; s << "\r\n" << strMsg; return s.str(); } static string rfc1123Time() { return DateTimeStrFormat("%a, %d %b %Y %H:%M:%S +0000", GetTime()); } static const char* httpStatusDescription(int nStatus) { switch (nStatus) { case HTTP_OK: return "OK"; case HTTP_BAD_REQUEST: return "Bad Request"; case HTTP_FORBIDDEN: return "Forbidden"; case HTTP_NOT_FOUND: return "Not Found"; case HTTP_INTERNAL_SERVER_ERROR: return "Internal Server Error"; default: return ""; } } string HTTPError(int nStatus, bool keepalive, bool headersOnly) { if (nStatus == HTTP_UNAUTHORIZED) return strprintf("HTTP/1.0 401 Authorization Required\r\n" "Date: %s\r\n" "Server: transend-json-rpc/%s\r\n" "WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n" "Content-Type: text/html\r\n" "Content-Length: 296\r\n" "\r\n" "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n" "\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n" "<HTML>\r\n" "<HEAD>\r\n" "<TITLE>Error</TITLE>\r\n" "<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n" "</HEAD>\r\n" "<BODY><H1>401 Unauthorized.</H1></BODY>\r\n" "</HTML>\r\n", rfc1123Time(), FormatFullVersion()); return HTTPReply(nStatus, httpStatusDescription(nStatus), keepalive, headersOnly, "text/plain"); } string HTTPReplyHeader(int nStatus, bool keepalive, size_t contentLength, const char* contentType) { return strprintf( "HTTP/1.1 %d %s\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: %u\r\n" "Content-Type: %s\r\n" "Server: transend-json-rpc/%s\r\n" "\r\n", nStatus, httpStatusDescription(nStatus), rfc1123Time(), keepalive ? "keep-alive" : "close", contentLength, contentType, FormatFullVersion()); } string HTTPReply(int nStatus, const string& strMsg, bool keepalive, bool headersOnly, const char* contentType) { if (headersOnly) { return HTTPReplyHeader(nStatus, keepalive, 0, contentType); } else { return HTTPReplyHeader(nStatus, keepalive, strMsg.size(), contentType) + strMsg; } } bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int& proto, string& http_method, string& http_uri) { string str; getline(stream, str); // HTTP request line is space-delimited vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return false; // HTTP methods permitted: GET, POST http_method = vWords[0]; if (http_method != "GET" && http_method != "POST") return false; // HTTP URI must be an absolute path, relative to current host http_uri = vWords[1]; if (http_uri.size() == 0 || http_uri[0] != '/') return false; // parse proto, if present string strProto = ""; if (vWords.size() > 2) strProto = vWords[2]; proto = 0; const char* ver = strstr(strProto.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver + 7); return true; } int ReadHTTPStatus(std::basic_istream<char>& stream, int& proto) { string str; getline(stream, str); //LogPrintf("ReadHTTPStatus - getline string: %s\n",str.c_str()); vector<string> vWords; boost::split(vWords, str, boost::is_any_of(" ")); if (vWords.size() < 2) return HTTP_INTERNAL_SERVER_ERROR; proto = 0; const char* ver = strstr(str.c_str(), "HTTP/1."); if (ver != NULL) proto = atoi(ver + 7); return atoi(vWords[1].c_str()); } int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet) { int nLen = 0; while (true) { string str; std::getline(stream, str); if (str.empty() || str == "\r") break; string::size_type nColon = str.find(":"); if (nColon != string::npos) { string strHeader = str.substr(0, nColon); boost::trim(strHeader); boost::to_lower(strHeader); string strValue = str.substr(nColon + 1); boost::trim(strValue); mapHeadersRet[strHeader] = strValue; if (strHeader == "content-length") nLen = atoi(strValue.c_str()); } } return nLen; } int ReadHTTPMessage(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet, int nProto, size_t max_size) { mapHeadersRet.clear(); strMessageRet = ""; // Read header int nLen = ReadHTTPHeaders(stream, mapHeadersRet); if (nLen < 0 || (size_t)nLen > max_size) return HTTP_INTERNAL_SERVER_ERROR; // Read message if (nLen > 0) { vector<char> vch; size_t ptr = 0; while (ptr < (size_t)nLen) { size_t bytes_to_read = std::min((size_t)nLen - ptr, POST_READ_SIZE); vch.resize(ptr + bytes_to_read); stream.read(&vch[ptr], bytes_to_read); if (!stream) // Connection lost while reading return HTTP_INTERNAL_SERVER_ERROR; ptr += bytes_to_read; } strMessageRet = string(vch.begin(), vch.end()); } string sConHdr = mapHeadersRet["connection"]; if ((sConHdr != "close") && (sConHdr != "keep-alive")) { if (nProto >= 1) mapHeadersRet["connection"] = "keep-alive"; else mapHeadersRet["connection"] = "close"; } return HTTP_OK; } /** * JSON-RPC protocol. Transend speaks version 1.0 for maximum compatibility, * but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were * unspecified (HTTP errors and contents of 'error'). * * 1.0 spec: http://json-rpc.org/wiki/specification * 1.2 spec: http://jsonrpc.org/historical/json-rpc-over-http.html * http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx */ string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id) { Object request; request.push_back(Pair("method", strMethod)); request.push_back(Pair("params", params)); request.push_back(Pair("id", id)); return write_string(Value(request), false) + "\n"; } Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id) { Object reply; if (error.type() != null_type) reply.push_back(Pair("result", Value::null)); else reply.push_back(Pair("result", result)); reply.push_back(Pair("error", error)); reply.push_back(Pair("id", id)); return reply; } string JSONRPCReply(const Value& result, const Value& error, const Value& id) { Object reply = JSONRPCReplyObj(result, error, id); return write_string(Value(reply), false) + "\n"; } Object JSONRPCError(int code, const string& message) { Object error; error.push_back(Pair("code", code)); error.push_back(Pair("message", message)); return error; }
887428b911b1e55aee9de646986d579cbc1918b3
04621baa46a8b2851936f5c32d3e0c372d850ee6
/lab14/lab14/lab14/Hash.cpp
29c9b43a09d3a71d9e5b72b876b7d4e376b6d11f
[]
no_license
Arcuman/Basics-of-Algorithmization
08e0cd865dee435bb90093bfb51a2203fbc60cc4
262ae62eb96ad575b591da0519cc4858b39e5295
refs/heads/master
2021-01-15T01:33:07.608082
2020-02-24T20:38:56
2020-02-24T20:38:56
242,828,564
1
0
null
null
null
null
WINDOWS-1251
C++
false
false
3,462
cpp
#include "pch.h" #include "Hash.h" #include <iostream> int HashFunction(int key, int size, int p) //Хеш-функция (модульная 3 вариант) { double A; A = (sqrt(5.0f) - 1.0f) / 2.0f; int k; k = key * A ; return k % size; } //------------------------------- int Next_hash(int hash, int size, int p) //Следующий индекс массива (1 вариант квадратичный шаг) { return (hash + 5 * p + 3 * p * p) % size; ; } //------------------------------- Object create(int size, int(*getkey)(void*)) //Созание хэш таблицы { return *(new Object(size, getkey)); } //------------------------------- Object::Object(int size, int(*getkey)(void*))//конструктор хэш таблицы { N = 0; this->size = size; //макимальный размер this->getKey = getkey; // функция взятия ключа this->data = new void*[size]; //массив структур for (int i = 0; i < size; ++i) data[i] = NULL; } //------------------------------- bool Object::insert(void* d) //вставка элементов в таблицу { bool b = false; if (N != size) for (int i = 0, t = getKey(d), j = HashFunction(t, size, 0); // хеширование ключа i != size && !b; j = Next_hash(j, size, ++i)) // пока i > максимального размера; j следующий индекс в соответствии с хешом if (data[j] == NULL || data[j] == DEL) { data[j] = d; N++; b = true; } return b; } //------------------------------- int Object::searchInd(int key) //Поиск по ключу { int t = -1; bool b = false; if (N != 0) for (int i = 0, j = HashFunction(key, size, 0); data[j] != NULL && i != size && !b; j = HashFunction(key, size, ++i)) // хеширование ключа if (data[j] != DEL) if (getKey(data[j]) == key) { t = j; b = true; } return t; //возврат индекса массива в котором совпал ключ } //------------------------------- void* Object::search(int key) // Поиск по ключу { int t = searchInd(key); return(t >= 0) ? (data[t]) : (NULL); //если элемент удален вернем null } //------------------------------- void* Object::deleteByKey(int key) // формальное Удаление элемента по ключу { int i = searchInd(key); void* t = data[i]; if (t != NULL) { data[i] = DEL; // DEL = -1 знак "удаления" N--; } return t; } //------------------------------- bool Object::deleteByValue(void* d) // Удаление по значению { return(deleteByKey(getKey(d)) != NULL); } //------------------------------- void Object::scan(void(*f)(void*)) // Вывод таблицы { for (int i = 0; i < this->size; i++) { std::cout << " Элемент" << i; if ((this->data)[i] == NULL) // Не заполнен std::cout << " пусто" << std::endl; else if ((this->data)[i] == DEL) // Удален std::cout << " удален" << std::endl; else f((this->data)[i]); //Вызов функции вывода ААА } } int HashFunctionU(int key, int size, int p) // метод универсального хеширования (14 вариант) { int h, a = 31415, b = 27183; for (h = 0; key != 0; key--, a = a * b % (size - 1)) h = (a*h + key) % size; return (h < 0) ? (h + size) : h; }
cded961e8ad96c6b7b5a9a1d3d746f0caa7a5983
12352408efa20481131f8e2f4e3fea8ecc041d6c
/ModuleCollision.h
bff7f4a499508a34f7d53d3e55e6b3291f2c289a
[ "Zlib" ]
permissive
Arnau77/Flappy_Bird
ebe92dbc911fdc0e11b34c6f9a1f25f77a971f33
a74cb3c9a846647ca2908fa8cba6b887d961e02a
refs/heads/master
2020-07-12T09:20:35.303347
2019-09-15T22:56:52
2019-09-15T22:56:52
204,777,628
0
0
null
null
null
null
UTF-8
C++
false
false
1,020
h
#ifndef __ModuleCollision_H__ #define __ModuleCollision_H__ #define MAX_COLLIDERS 50 #include "Module.h" #include "SDL/include/SDL_rect.h" enum COLLIDER_TYPE { COLLIDER_NONE = -1, COLLIDER_WALL, COLLIDER_POINT, COLLIDER_PLAYER, COLLIDER_MAX }; struct Collider { SDL_Rect rect; bool to_delete = false; COLLIDER_TYPE type; Module* callback = nullptr; Collider(SDL_Rect rectangle, COLLIDER_TYPE type, Module* callback = nullptr) : rect(rectangle), type(type), callback(callback) {} void SetPos(int, int); bool CheckCollision(const SDL_Rect& r) const; }; class ModuleCollision : public Module { public: ModuleCollision(); ~ModuleCollision(); update_status PreUpdate() override; update_status Update() override; bool CleanUp() override; Collider* AddCollider(SDL_Rect rect, COLLIDER_TYPE type, Module* callback = nullptr); void DebugDraw(); private: Collider* colliders[MAX_COLLIDERS]; bool matrix[COLLIDER_MAX][COLLIDER_MAX]; bool debug = false; }; #endif // __ModuleCollision_H__
cf918233025c6ab1e1889c94e3186aad2945c7c0
2af3e04d25617fbb3597f9b28fe39121c5c9288d
/My Game Engine v1.0/OpenGL/TextMaker.h
9b70dccf8fc9580bc299f8a4bab25cd448a338e3
[]
no_license
Kmann180/MyGameEngineV1
6cd620a0de752526f5b464795b6f5f0e57c84ea7
52815bbcca76500c1476e2282b4954b529566853
refs/heads/master
2021-01-23T14:57:19.316978
2014-03-24T22:04:48
2014-03-24T22:04:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,492
h
#pragma once #ifndef _TEXTMAKER_H_ #define _TEXTMAKER_H_ #include "Utilities.h" #include <tinyxml2.h> #include "Sprite.h" struct Char // makes a struct called Char that contains two structs, //one dealing with Vectors and the other dealing with floats { union { struct { std::string sName; Vector2 v2Size; Vector4 v4Location; float yOffset; }; struct { std::string Name; float width; float height; float x0; float x1; float y0; float y1; float Offset; }; }; }; struct Font // struct that stores the size, sheet and the kerning of the font { Vector2 v2Size; std::string sSheet; float fKerning; }; class TextMaker { public: static TextMaker& Instance(); //Static member function that dynamically instances each character's sprite. void LoadFont(const char * a_pFontSheet); // self explanitory. void DrawString(std::string str, Vector2 pos, float scale); // draws the string you put into it. protected: static void CleanUp(); // self explanitory TextMaker(void); ~TextMaker(void); void LoadString(std::string str); Sprite iSprite; Font FontAtlas; std::map<char, Char> charMap; // maps where each thing is on the XML sheet std::vector<Char> DrawList; // list of hings to draw. int CharCount; // how many characters are in the string static TextMaker* MInstance; // stores the instance GLuint PositionBuffer; // buffers! GLuint ColorBuffer; GLuint UVBuffer; GLuint MatrixBuffer; }; #endif // _FONT_MANAGER_H_
43c623304643d04f78452b665ec8ae9234ddc08b
e545d22639e64e277201664619f06ebacd4b4bd0
/src/base58.h
7514d005cfbf9bdfa8cc87637868d49b0662f6bc
[ "MIT", "BSD-3-Clause" ]
permissive
shriishrii/csap
2c6b057d917728a6d9fe0476247427e7ce0b32ae
b5cd263c56ce49b17b7d8ebd3c3bafa0430cd2af
refs/heads/master
2020-12-24T21:01:35.773594
2016-05-27T09:01:57
2016-05-27T09:01:57
59,740,292
0
0
null
null
null
null
UTF-8
C++
false
false
13,011
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // Modified by CSAP developers - 2016 // // Why base-58 instead of standard base-64 encoding? // - Don't want 0OIl characters that look the same in some fonts and // could be used to create visually identical looking account numbers. // - A string with non-alphanumeric characters is not as easily accepted as an account number. // - E-mail usually won't line-break if there's no punctuation to break at. // - Double-clicking selects the whole number as one word if it's all alphanumeric. // #ifndef BITCOIN_BASE58_H #define BITCOIN_BASE58_H #include <string> #include <vector> #include "bignum.h" #include "key.h" #include "script.h" #include "allocators.h" static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; // Encode a byte sequence as a base58-encoded string inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) { CAutoBN_CTX pctx; CBigNum bn58 = 58; CBigNum bn0 = 0; // Convert big endian data to little endian // Extra zero at the end make sure bignum will interpret as a positive number std::vector<unsigned char> vchTmp(pend-pbegin+1, 0); reverse_copy(pbegin, pend, vchTmp.begin()); // Convert little endian data to bignum CBigNum bn; bn.setvch(vchTmp); // Convert bignum to std::string std::string str; // Expected size increase from base58 conversion is approximately 137% // use 138% to be safe str.reserve((pend - pbegin) * 138 / 100 + 1); CBigNum dv; CBigNum rem; while (bn > bn0) { if (!BN_div(&dv, &rem, &bn, &bn58, pctx)) throw bignum_error("EncodeBase58 : BN_div failed"); bn = dv; unsigned int c = rem.getulong(); str += pszBase58[c]; } // Leading zeroes encoded as base58 zeros for (const unsigned char* p = pbegin; p < pend && *p == 0; p++) str += pszBase58[0]; // Convert little endian std::string to big endian reverse(str.begin(), str.end()); return str; } // Encode a byte vector as a base58-encoded string inline std::string EncodeBase58(const std::vector<unsigned char>& vch) { return EncodeBase58(&vch[0], &vch[0] + vch.size()); } // Decode a base58-encoded string psz into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet) { CAutoBN_CTX pctx; vchRet.clear(); CBigNum bn58 = 58; CBigNum bn = 0; CBigNum bnChar; while (isspace(*psz)) psz++; // Convert big endian string to bignum for (const char* p = psz; *p; p++) { const char* p1 = strchr(pszBase58, *p); if (p1 == NULL) { while (isspace(*p)) p++; if (*p != '\0') return false; break; } bnChar.setulong(p1 - pszBase58); if (!BN_mul(&bn, &bn, &bn58, pctx)) throw bignum_error("DecodeBase58 : BN_mul failed"); bn += bnChar; } // Get bignum as little endian data std::vector<unsigned char> vchTmp = bn.getvch(); // Trim off sign byte if present if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80) vchTmp.erase(vchTmp.end()-1); // Restore leading zeros int nLeadingZeros = 0; for (const char* p = psz; *p == pszBase58[0]; p++) nLeadingZeros++; vchRet.assign(nLeadingZeros + vchTmp.size(), 0); // Convert little endian data to big endian reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size()); return true; } // Decode a base58-encoded string str into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58(str.c_str(), vchRet); } // Encode a byte vector to a base58-encoded string, including checksum inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn) { // add 4-byte hash check to the end std::vector<unsigned char> vch(vchIn); uint256 hash = Hash(vch.begin(), vch.end()); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); return EncodeBase58(vch); } // Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet) { if (!DecodeBase58(psz, vchRet)) return false; if (vchRet.size() < 4) { vchRet.clear(); return false; } uint256 hash = Hash(vchRet.begin(), vchRet.end()-4); if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) { vchRet.clear(); return false; } vchRet.resize(vchRet.size()-4); return true; } // Decode a base58-encoded string str that includes a checksum, into byte vector vchRet // returns true if decoding is successful inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58Check(str.c_str(), vchRet); } /** Base class for all base58-encoded data */ class CBase58Data { protected: // the version byte unsigned char nVersion; // the actually encoded data typedef std::vector<unsigned char, zero_after_free_allocator<unsigned char> > vector_uchar; vector_uchar vchData; CBase58Data() { nVersion = 0; vchData.clear(); } void SetData(int nVersionIn, const void* pdata, size_t nSize) { nVersion = nVersionIn; vchData.resize(nSize); if (!vchData.empty()) memcpy(&vchData[0], pdata, nSize); } void SetData(int nVersionIn, const unsigned char *pbegin, const unsigned char *pend) { SetData(nVersionIn, (void*)pbegin, pend - pbegin); } public: bool SetString(const char* psz) { std::vector<unsigned char> vchTemp; DecodeBase58Check(psz, vchTemp); if (vchTemp.empty()) { vchData.clear(); nVersion = 0; return false; } nVersion = vchTemp[0]; vchData.resize(vchTemp.size() - 1); if (!vchData.empty()) memcpy(&vchData[0], &vchTemp[1], vchData.size()); OPENSSL_cleanse(&vchTemp[0], vchData.size()); return true; } bool SetString(const std::string& str) { return SetString(str.c_str()); } std::string ToString() const { std::vector<unsigned char> vch(1, nVersion); vch.insert(vch.end(), vchData.begin(), vchData.end()); return EncodeBase58Check(vch); } int CompareTo(const CBase58Data& b58) const { if (nVersion < b58.nVersion) return -1; if (nVersion > b58.nVersion) return 1; if (vchData < b58.vchData) return -1; if (vchData > b58.vchData) return 1; return 0; } bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; } bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; } bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; } bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; } bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; } }; /** base58-encoded CSAP addresses. * Public-key-hash-addresses have version 0 (or 111 testnet). * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key. * Script-hash-addresses have version 5 (or 196 testnet). * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script. */ class CBitcoinAddress; class CBitcoinAddressVisitor : public boost::static_visitor<bool> { private: CBitcoinAddress *addr; public: CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { } bool operator()(const CKeyID &id) const; bool operator()(const CScriptID &id) const; bool operator()(const CNoDestination &no) const; }; class CBitcoinAddress : public CBase58Data { public: enum { PUBKEY_ADDRESS = 16, // "0" is for leading "1"; and "16" is for "7"; site: en.bitcoin.it/wiki/List_of_address_prefixes SCRIPT_ADDRESS = 5, PUBKEY_ADDRESS_TEST = 111, SCRIPT_ADDRESS_TEST = 196, }; bool Set(const CKeyID &id) { SetData(fTestNet ? PUBKEY_ADDRESS_TEST : PUBKEY_ADDRESS, &id, 20); return true; } bool Set(const CScriptID &id) { SetData(fTestNet ? SCRIPT_ADDRESS_TEST : SCRIPT_ADDRESS, &id, 20); return true; } bool Set(const CTxDestination &dest) { return boost::apply_visitor(CBitcoinAddressVisitor(this), dest); } bool IsValid() const { unsigned int nExpectedSize = 20; bool fExpectTestNet = false; switch(nVersion) { case PUBKEY_ADDRESS: nExpectedSize = 20; // Hash of public key fExpectTestNet = false; break; case SCRIPT_ADDRESS: nExpectedSize = 20; // Hash of CScript fExpectTestNet = false; break; case PUBKEY_ADDRESS_TEST: nExpectedSize = 20; fExpectTestNet = true; break; case SCRIPT_ADDRESS_TEST: nExpectedSize = 20; fExpectTestNet = true; break; default: return false; } return fExpectTestNet == fTestNet && vchData.size() == nExpectedSize; } CBitcoinAddress() { } CBitcoinAddress(const CTxDestination &dest) { Set(dest); } CBitcoinAddress(const std::string& strAddress) { SetString(strAddress); } CBitcoinAddress(const char* pszAddress) { SetString(pszAddress); } CTxDestination Get() const { if (!IsValid()) return CNoDestination(); switch (nVersion) { case PUBKEY_ADDRESS: case PUBKEY_ADDRESS_TEST: { uint160 id; memcpy(&id, &vchData[0], 20); return CKeyID(id); } case SCRIPT_ADDRESS: case SCRIPT_ADDRESS_TEST: { uint160 id; memcpy(&id, &vchData[0], 20); return CScriptID(id); } } return CNoDestination(); } bool GetKeyID(CKeyID &keyID) const { if (!IsValid()) return false; switch (nVersion) { case PUBKEY_ADDRESS: case PUBKEY_ADDRESS_TEST: { uint160 id; memcpy(&id, &vchData[0], 20); keyID = CKeyID(id); return true; } default: return false; } } bool IsScript() const { if (!IsValid()) return false; switch (nVersion) { case SCRIPT_ADDRESS: case SCRIPT_ADDRESS_TEST: { return true; } default: return false; } } }; bool inline CBitcoinAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); } bool inline CBitcoinAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); } bool inline CBitcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; } /** A base58-encoded secret key */ class CBitcoinSecret : public CBase58Data { public: void SetSecret(const CSecret& vchSecret, bool fCompressed) { assert(vchSecret.size() == 32); SetData(fTestNet ? 239 : 128, &vchSecret[0], vchSecret.size()); if (fCompressed) vchData.push_back(1); } CSecret GetSecret(bool &fCompressedOut) { CSecret vchSecret; vchSecret.resize(32); memcpy(&vchSecret[0], &vchData[0], 32); fCompressedOut = vchData.size() == 33; return vchSecret; } bool IsValid() const { bool fExpectTestNet = false; switch(nVersion) { case 128: break; case 239: fExpectTestNet = true; break; default: return false; } return fExpectTestNet == fTestNet && (vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1)); } bool SetString(const char* pszSecret) { return CBase58Data::SetString(pszSecret) && IsValid(); } bool SetString(const std::string& strSecret) { return SetString(strSecret.c_str()); } CBitcoinSecret(const CSecret& vchSecret, bool fCompressed) { SetSecret(vchSecret, fCompressed); } CBitcoinSecret() { } }; #endif // BITCOIN_BASE58_H
77db1c58ab9614f152faeef373a93d09a670a66f
cb0b3c7d6b3b03a1b12360c621d495368aedd0c8
/src/testApp.cpp
9b2ba53de53f6fc11c868857b92bb6800ffc313c
[ "Apache-2.0" ]
permissive
wdyang/oscVideoSensor
9b8b3e37ba1ed5b59e8e2d0b3a023e59f3faa960
351983da8654af15a179c595b83581c3f1ae19bb
refs/heads/master
2016-09-05T23:49:34.941659
2014-05-26T22:25:10
2014-05-26T22:25:10
17,278,633
1
0
null
null
null
null
UTF-8
C++
false
false
13,851
cpp
// // Created by Weidong Yang on 12/1/13. // // #include "testApp.h" using namespace ofxCv; using namespace cv; void testApp::setup() { // if(bUsePs3Eye){ int numPs3Eye = ps3eye.listDevices().size(); cout<<"Number of Ps3 Eye connected: "<< numPs3Eye<< endl; if(numPs3Eye>0){ bUsePs3Eye=true; ps3eye.setDesiredFrameRate(60); ps3eye.initGrabber(camW, camH); ps3eye.setAutoGainAndShutter(false); ps3eye.setGain(camGain); //longer shutter results in more stable images. less affected by flicker on both utility and monitor. Should set it to 1 as much as possible ps3eye.setShutter(camShutter); ps3eye.setGamma(0.4); ps3eye.setBrightness(0.6); ps3eye.setHue(camHue); ps3eye.setFlicker(2);/* 0 - no flicker, 1 - 50hz, 2 - 60hz */ ps3eye.setWhiteBalance(2); /* 1 - linear, 2 - indoor, 3 - outdoor, 4 - auto */ }else{ bUsePs3Eye = false; ofSetVerticalSync(true); ofSetFrameRate(120); int numCam=cam.listDevices().size(); cam.setDeviceID(numCam-1); cam.initGrabber(camW, camH); } mesh.setMode(OF_PRIMITIVE_TRIANGLES); ySteps = camH / stepSize; xSteps = camW / stepSize; for(int y = 0; y < ySteps; y++) { for(int x = 0; x < xSteps; x++) { mesh.addVertex(ofVec2f(x * stepSize, y * stepSize)); mesh.addTexCoord(ofVec2f(x * stepSize, y * stepSize)); } } for(int y = 0; y + 1 < ySteps; y++) { for(int x = 0; x + 1 < xSteps; x++) { int nw = y * xSteps + x; int ne = nw + 1; int sw = nw + xSteps; int se = sw + 1; mesh.addIndex(nw); mesh.addIndex(ne); mesh.addIndex(se); mesh.addIndex(nw); mesh.addIndex(se); mesh.addIndex(sw); } } faceFbo.allocate(camW*2, camH*2, GL_RGBA); faceFbo.begin(); ofClear(255,255,255,0); faceFbo.end(); if(bUseGarrett){ setUpGarrettGrid(); }else{ setUpNormalGrid(); } // SoundBlock::zDown = 0.05; // Audio stuff numPlayers = nCol*nRow; colSteps = xSteps / nCol; rowSteps = ySteps / nRow; midiIn.listPorts(); midiIn.openPort(0); midiIn.ignoreTypes(false, false, false); midiIn.addListener(this); midiIn.setVerbose(true); //osc sender sender.setup(HOST, PORT); } void testApp::setUpNormalGrid(){ float deltaX = camW/nCol, deltaY = camH/nRow; int i=0; for(int iCol=nCol-1; iCol>=0; iCol--){ for(int iRow=0; iRow<nRow; iRow++){ float x = deltaX * (iCol+0.5); float y = deltaY * (iRow+0.5); soundBlocks.push_back(SoundBlock(x, y, targetW, targetH, camW, camH, i, bLoop)); i++; } } } void testApp::setUpGarrettGrid(){ float deltaX = camW/nCol, deltaY = camH/nRow; int i=0; float offset = 0; int numCol = 0; for(int iRow=0; iRow<nRow; iRow++){ if(iRow%2 == 0){ offset = deltaX/2.0; numCol = nCol - 1; }else{ offset = 0; numCol = nCol; } for(int iCol=numCol-1; iCol>=0; iCol--){ float x = deltaX * (iCol+0.5) + offset; float y = deltaY * (iRow+0.5); soundBlocks.push_back(SoundBlock(x, y, targetW, targetH, camW, camH, i, bLoop)); i++; } } } void testApp::update() { // vector<float> maxSpeeds; // for(int i=0; i<numPlayers; i++){ // maxSpeeds.push_back(0); // } bool bNewFrame=false; if(bUsePs3Eye){ ps3eye.update(); bNewFrame=ps3eye.isFrameNew(); }else{ cam.update(); bNewFrame=cam.isFrameNew(); } if(bNewFrame) { flow.setWindowSize(8); if(bUsePs3Eye){ flow.calcOpticalFlow(ps3eye); }else{ flow.calcOpticalFlow(cam); } int i = 0; float sumX=0, sumIntX=0, numActive=0; float sumY=0, sumIntY=0, sumSpeed=0; float maxSpeed = 0; int xAtMaxSpeed = -1; int yAtMaxSpeed = -1; // float distortionStrength = 4; for(int y = 1; y + 1 < ySteps; y++) { for(int x = 1; x + 1 < xSteps; x++) { int i = y * xSteps + x; ofVec2f position(x * stepSize, y * stepSize); ofRectangle area(position - ofVec2f(stepSize, stepSize) / 2, stepSize, stepSize); ofVec2f offset = flow.getAverageFlowInRegion(area); // mesh.setVertex(i, position + distortionStrength * offset); ofVec2f current_offset = mesh.getVertex(i) - position; ofVec2f new_offset = current_offset * (1-zFactor) + distortionStrength * offset*zFactor; mesh.setVertex(i, position + new_offset); i++; // audio stuff int iCol = floor(x / colSteps*1.0); int iRow = floor(y / rowSteps*1.0); int idx = iRow*nCol + iCol; // calculate the center of the movement float speed = offset.length(); if(speed>10.0){ //for near field, may use 15.0 int _x=x*stepSize + stepSize/2; int _y=y*stepSize + stepSize/2; sumX+=_x; sumY+=_y; sumIntX+=speed * _x; sumIntY+=speed * _y; numActive++; sumSpeed+=speed; if(speed > maxSpeed){ maxSpeed = speed; xAtMaxSpeed = _x; yAtMaxSpeed = _y; } } // if(speed > maxSpeeds[idx]) { // maxSpeeds[idx] = speed; // } // cout<<iCol<<" "<<iRow<<endl; } } if(sumSpeed>0){ bReportXY = true; if(bReportMax){ reportX = xAtMaxSpeed; reportY = yAtMaxSpeed; }else{ reportX = sumIntX/sumSpeed; reportY = sumIntY/sumSpeed; } if(bMirror){ reportX=camW-reportX; } cout<<"numActive: "<<numActive<<" aveX: "<<reportX<<" aveY: "<<reportY<<" sumSpeed: "<<sumSpeed<<endl; oscSendAverageLocation(reportX, reportY); // oscSendVideoPosition(sumIntX/sumSpeed); }else{ bReportXY=false; } } if(false){ //turn off extra broadcasting for(int i=0; i<soundBlocks.size(); i++){ float volume = soundBlocks[i].update(mesh, stepSize, xSteps, ySteps); SoundBlockState currentState = soundBlocks[i].currentState; if(currentState == TriggerPlay){ oscLiveTriggerPlay(i, 0); oscLiveSetVolume(i, volume); oscRenoiseNoteOn(i, i, 60, 127); }else if(currentState == On){ oscLiveSetVolume(i, volume); }else if(currentState == TriggerStop){ oscLiveTriggerStop(i, 0); oscRenoiseNoteOff(i, i, 60, 0); } } } } void testApp::oscLiveTriggerPlay(int track, int clip){ ofxOscMessage m; stringstream ss; // ss<<"/sound/"<<i; ss<<"/live/play/clip"; m.setAddress(ss.str()); m.addIntArg(track); //track m.addIntArg(clip); //clip, only loading one clip for now // m.addFloatArg(volume); sender.sendMessage(m); } void testApp::oscLiveTriggerStop(int track, int clip){ ofxOscMessage m; stringstream ss; // ss<<"/sound/"<<i; ss<<"/live/stop/clip"; m.setAddress(ss.str()); m.addIntArg(track); //track m.addIntArg(clip); //clip, only loading one clip for now // m.addFloatArg(volume); sender.sendMessage(m); } void testApp::oscLiveSetVolume(int track, float volume){ ofxOscMessage m; stringstream ss; // ss<<"/sound/"<<i; ss<<"/live/volume"; m.setAddress(ss.str()); m.addIntArg(track); //track m.addFloatArg(volume); sender.sendMessage(m); // cout<<ss<<" "<<track<<" "<<volume<<endl; } void testApp::oscRenoiseNoteOn(int t, int i, int n, int v){ ofxOscMessage m; stringstream ss; // ss<<"/sound/"<<i; ss<<"/renoise/trigger/note_on"; m.setAddress(ss.str()); m.addIntArg(i); //track m.addIntArg(i); //instrument m.addIntArg(n); m.addIntArg(v); sender.sendMessage(m); } void testApp::oscRenoiseNoteOff(int t, int i, int n, int v){ ofxOscMessage m; stringstream ss; // ss<<"/sound/"<<i; ss<<"/renoise/trigger/note_off"; m.setAddress(ss.str()); m.addIntArg(i); //track m.addIntArg(i); //instrument m.addIntArg(n); m.addIntArg(v); sender.sendMessage(m); } void testApp::oscSendAverageLocation(int x, int y){ ofxOscMessage m; stringstream ss; // ss<<"/sound/"<<i; ss<<"/location"; m.setAddress(ss.str()); m.addIntArg(x); m.addIntArg(y); sender.sendMessage(m); } void testApp::oscSendVideoPosition(int x){ ofxOscMessage m; stringstream ss; // ss<<"/sound/"<<i; cout<<"/video/"<<x<<endl; ss<<"/video"; m.setAddress(ss.str()); m.addFloatArg(x/200.0); sender.sendMessage(m); } void testApp::draw() { faceFbo.begin(); ofBackground(0); ofScale(2, 2); if(bUsePs3Eye){ ps3eye.getTextureReference().bind(); mesh.draw(); ps3eye.getTextureReference().unbind(); }else{ cam.getTextureReference().bind(); mesh.draw(); cam.getTextureReference().unbind(); } if(ofGetMousePressed()) { mesh.drawWireframe(); } faceFbo.end(); ofBackground(0); // ofScale(2, 2); // cam.getTextureReference().bind(); // // mesh.draw(); // cam.getTextureReference().unbind(); // if(ofGetMousePressed()) { // mesh.drawWireframe(); // } // faceFbo.getTextureReference() if(bMirror) faceFbo.draw(drawW, 0, -drawW, drawH); else faceFbo.draw(0, 0, drawW, drawH); ofEnableAlphaBlending(); ofSetColor(255, 255, 255, 255); stringstream reportStream; reportStream<<"distortion strength: "<< distortionStrength<<" +/- increase/decrease"<<endl; reportStream<<"zFactor: "<<zFactor<<" a/z increase/decrease"<<endl; reportStream<<"0: fast enhance"<<endl; reportStream<<"1: smooth enhance"<<endl; reportStream<<"2: extreme smooth enhance\n"; reportStream<<"3: reverse smooth enhance\n"; reportStream<<"4: fast, large enhance\n"; reportStream<<"m: switch mirror image\n\n"; reportStream<<"bLoop (cycle) is: "<<(bLoop ? "true" : "false")<<endl<<endl; reportStream<<"Sets (< >):\n"; reportStream<<"zDown "<<SoundBlock::zDown<<endl; reportStream<<"gain (<Q, q>):"<<camGain<<endl; reportStream<<"shutter (<W, w>):"<<camShutter<<endl; if(bReportMax){ reportStream<<"Reporting max speed loaction, 'x' to toggle\n"; }else{ reportStream<<"Reporting average motion location, 'x' to toggle\n"; } if(bReportXY) reportStream<<"Reporting X:"<<reportX<<" Y: "<<reportY<<endl; ofDrawBitmapString(reportStream.str(), 810, 20); ofDisableAlphaBlending(); for(int i=0; i<soundBlocks.size(); i++){ soundBlocks[i].draw(bMirror, drawCamRatio); } } void testApp::keyPressed(int key){ switch (key) { case '=': if(SoundBlock::zDown<0.99) SoundBlock::zDown+=0.01; break; case '-': if(SoundBlock::zDown>0.01) SoundBlock::zDown-=0.01; break; case 'a': if(zFactor<0.99)zFactor+=0.01; break; case 'z': if(zFactor>0.01)zFactor-=0.01; break; case 'm': bMirror= !bMirror; break; case 'x': bReportMax = !bReportMax; break; case '0': distortionStrength = 4.0; zFactor = 0.99; break; case '1': distortionStrength = 12.0; zFactor = 0.2; break; case '2': distortionStrength=100.0; zFactor= 0.01; break; case '3': distortionStrength=-100.0; zFactor= 0.01; break; case '4': distortionStrength=10.0; zFactor= 0.5; break; case 'q': if(camGain<1.0) camGain+=0.1; ps3eye.setGain(camGain); cout<<"gain is "<<camGain<<endl; break; case 'Q': if(camGain>0.0) camGain-=0.1; ps3eye.setGain(camGain); cout<<"camGain is "<<camGain<<endl; break; case 'w': if(camShutter<1.0) camShutter+=0.1; ps3eye.setShutter(camShutter); cout<<"camShutter is "<<camShutter<<endl; break; case 'W': if(camShutter>0.0) camShutter-=0.1; ps3eye.setShutter(camShutter); cout<<"camShutter is "<<camShutter<<endl; break; case 'e': if(camHue<1.0) camHue+=0.1; ps3eye.setHue(camHue); cout<<"camHue is "<<camHue<<endl; break; case 'E': if(camHue>0.0) camHue-=0.1; ps3eye.setHue(camHue); cout<<"camHue is "<<camHue<<endl; break; default: break; } } void testApp::newMidiMessage(ofxMidiMessage &msg){ // midiMessage = msg; cout<<"channel: "<<msg.channel<<" control: "<<msg.control<<" value: "<<msg.value<<endl; int control = msg.control; int value = msg.value; }
c515804a1aa0b07fd62d69a32a13c9eb608c1c04
28b01cdc5a4d8eff2dd822a166d950784d21e380
/serverload.cpp
eacbc1320dd883465b73b4c4e6b2e82ea06daf57
[]
no_license
strimbob/ofxNetworkArdunio
bbc326142bf2ec1e8e1939a2b249b8b0304d9cca
38712b8f10901d02591eeeac89a57dac3b84af69
refs/heads/master
2020-04-01T06:58:58.824279
2013-08-09T11:52:39
2013-08-09T11:52:39
11,999,824
1
0
null
null
null
null
UTF-8
C++
false
false
1,909
cpp
#include "serverload.h" static ofEvent < vector <bool> > buttonChange; ofEvent < vector <bool> > serverload::buttonChange = ofEvent < vector <bool> >(); static ofEvent < vector <bool> > hillsPress; ofEvent < vector <bool> > serverload::hillsPress = ofEvent < vector <bool> >(); serverload::serverload() { udpConnection.Create(); udpConnection.Bind(9000); udpConnection.SetNonBlocking(true); udpConnectionTwo.Create(); udpConnectionTwo.Bind(8000); udpConnectionTwo.SetNonBlocking(true); preMes = "start"; } //-------------------------- //-------------------------- void serverload::update() { string message; char udpMessage[50]; udpConnection.Receive(udpMessage,50); message=udpMessage; if(message!=""){ if(message != preMes){ vector<string> dataFromArdunio = ofSplitString(message,","); vector<bool> send; for(int x = 0;x < dataFromArdunio.size()-1;x++){ send.push_back(ofToBool(dataFromArdunio[x])); } ofNotifyEvent(buttonChange, send); } preMes = message; } } void serverload::updateTwo(){ string message; char udpMessage[50]; udpConnectionTwo.Receive(udpMessage,50); message=udpMessage; if(message!=""){ if(message != preMesTwo){ vector<string> dataFromArdunio = ofSplitString(message,","); vector<bool> send; for(int x = 0;x < dataFromArdunio.size()-1;x++){ send.push_back(ofToBool(dataFromArdunio[x])); } ofNotifyEvent(hillsPress, send); } preMesTwo = message; } } //-------------------------- serverload::~serverload() { udpConnection.Close(); udpConnection.~ofxUDPManager(); udpConnectionTwo.Close(); udpConnectionTwo.~ofxUDPManager(); preMes.empty(); preMesTwo.empty(); }
42abc784e97c9e9c69d91224b5fce39a4d6dedb9
6e66eff65c9905d5e802865f5101b6044e3a0d20
/src/include/carve/triangle_intersection.hpp
751eb7d7a385d3afd87c94aeb88d8a56df3d1434
[ "MIT" ]
permissive
paulobala/ofxCarveCSG
787084b9912e1df040466ffe01137bed6edb66ec
03ed31758cd866f78252ecbd734b8ed1adffe6f9
refs/heads/master
2016-08-07T13:57:08.609075
2012-08-07T22:04:08
2012-08-07T22:04:08
5,329,362
3
1
null
null
null
null
UTF-8
C++
false
false
1,900
hpp
// Begin License: // Copyright (C) 2006-2011 Tobias Sargeant ([email protected]). // All rights reserved. // // This file is part of the Carve CSG Library (http://carve-csg.com/) // // This file may be used under the terms of the GNU General Public // License version 2.0 as published by the Free Software Foundation // and appearing in the file LICENSE.GPL2 included in the packaging of // this file. // // This file is provided "AS IS" with NO WARRANTY OF ANY KIND, // INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE. // End: #pragma once #include <carve.hpp> #include <geom.hpp> namespace carve { namespace geom { enum TriangleIntType { TR_TYPE_NONE = 0, TR_TYPE_TOUCH = 1, TR_TYPE_INT = 2 }; enum TriangleInt { TR_INT_NONE = 0, // no intersection. TR_INT_INT = 1, // intersection. TR_INT_VERT = 2, // intersection due to shared vertex. TR_INT_EDGE = 3, // intersection due to shared edge. TR_INT_TRI = 4 // intersection due to identical triangle. }; TriangleInt triangle_intersection(const vector<2> tri_a[3], const vector<2> tri_b[3]); TriangleInt triangle_intersection(const vector<3> tri_a[3], const vector<3> tri_b[3]); bool triangle_intersection_simple(const vector<2> tri_a[3], const vector<2> tri_b[3]); bool triangle_intersection_simple(const vector<3> tri_a[3], const vector<3> tri_b[3]); TriangleIntType triangle_intersection_exact(const vector<2> tri_a[3], const vector<2> tri_b[3]); TriangleIntType triangle_intersection_exact(const vector<3> tri_a[3], const vector<3> tri_b[3]); TriangleIntType triangle_linesegment_intersection_exact(const vector<2> tri_a[3], const vector<2> line_b[2]); TriangleIntType triangle_point_intersection_exact(const vector<2> tri_a[3], const vector<2> &pt_b); } }
9ae3e5605890a24396453b098487ea8be01a47b1
e9b1184954095d2736b63ed29fdf13f02f355009
/Assignment/GameObject.h
e85dbd97773ac82b397182214ae93ac662417b32
[ "Apache-2.0" ]
permissive
ivanchotom/Assignment
b6bcc5596c7b87068fe5ed45aa96e56ffe484176
f87a957985af99a758eb037cd9fbbcda825d3670
refs/heads/main
2023-01-27T21:21:41.755098
2020-12-17T15:11:59
2020-12-17T15:11:59
320,154,105
0
0
null
null
null
null
UTF-8
C++
false
false
1,244
h
#pragma once #include "Object.h" class GameObject : public ObjectClass { public: //Basic objects with position with/without colors GameObject(const char* _ObjectFile, std::shared_ptr<Shader> _objectShader, std::shared_ptr<CameraObject> _camera, int _ScreenWidth, int _ScreenHeight); //Basic objects with textures GameObject(const char* _ObjectFile, const char* _TexturePath[], int _TextureCount, std::shared_ptr <Shader> _objectShader, std::shared_ptr <CameraObject> _camera, int _ScreenWidth, int _ScreenHeight); //Object That use and .obj file GameObject(std::shared_ptr<Shader> _objectShader, std::shared_ptr<CameraObject> _camera, const char * _ObjectFile, int _ScreenWidth, int _ScreenHeight); ~GameObject(); //Set Rotation void setRotation(float _degree, glm::vec3 _rotation); //Set Position void setPosition(glm::vec3); //Set Scale void setScale(glm::vec3 _scale); //Set Directional Light Position void setDirLightPos(std::shared_ptr<GameObject> _lightSrc); //Set Point Light Positions and Amount void setPointLightPos(std::vector<std::shared_ptr<GameObject>> _lightPositions, int _AmountOfLights); //Get Position glm::vec3 getPosition(); //Get Model Matrix glm::mat4 getModelMatrix(); private: };
501ebfa8b6aa29a2f22721c963e5f861ef36842b
18e5714c0f21305121e5537dfc50609674e102ff
/cpp/prime-factors/prime_factors_test.cpp
1ce18c5d93d8407569f6ec0539f7dc546797d393
[]
no_license
viktorzetterstrom/exercism
d3118820684f7bb10856ddb2249f0698722b9f70
8a2722d98c2f16e02ea2eb3cd4426875c05fdf50
refs/heads/master
2021-12-22T17:23:42.675638
2021-11-30T08:24:24
2021-11-30T08:24:24
159,395,561
0
0
null
2019-10-07T13:39:07
2018-11-27T20:32:41
JavaScript
UTF-8
C++
false
false
2,636
cpp
#include "prime_factors.h" #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <iostream> BOOST_AUTO_TEST_CASE(_1_yields_empty) { const std::vector<int> expected{}; const std::vector<int> actual{prime_factors::of(1)}; BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end()); } BOOST_AUTO_TEST_CASE(_2_yields_2) { const std::vector<int> expected{2}; const std::vector<int> actual{prime_factors::of(2)}; BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end()); } BOOST_AUTO_TEST_CASE(_3_yields_3) { const std::vector<int> expected{3}; const std::vector<int> actual{prime_factors::of(3)}; BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end()); } BOOST_AUTO_TEST_CASE(_4_yields_2_2) { const std::vector<int> expected{2, 2}; const std::vector<int> actual{prime_factors::of(4)}; BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end()); } BOOST_AUTO_TEST_CASE(_6_yields_2_3) { const std::vector<int> expected{2, 3}; const std::vector<int> actual{prime_factors::of(6)}; BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end()); } BOOST_AUTO_TEST_CASE(_8_yields_2_2_2) { const std::vector<int> expected{2, 2, 2}; const std::vector<int> actual{prime_factors::of(8)}; BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end()); } BOOST_AUTO_TEST_CASE(_9_yields_3_3) { const std::vector<int> expected{3, 3}; const std::vector<int> actual{prime_factors::of(9)}; BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end()); } BOOST_AUTO_TEST_CASE(_27_yields_3_3_3) { const std::vector<int> expected{3, 3, 3}; const std::vector<int> actual{prime_factors::of(27)}; BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end()); } BOOST_AUTO_TEST_CASE(_625_yields_5_5_5_5) { const std::vector<int> expected{5, 5, 5, 5}; const std::vector<int> actual{prime_factors::of(625)}; BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end()); } BOOST_AUTO_TEST_CASE(_901255_yields_5_17_23_461) { const std::vector<int> expected{5, 17, 23, 461}; const std::vector<int> actual{prime_factors::of(901255)}; BOOST_REQUIRE_EQUAL_COLLECTIONS(expected.begin(), expected.end(), actual.begin(), actual.end()); } #if defined(EXERCISM_RUN_ALL_TESTS) #endif
6727bb4d83196e61765f247a6038e63af0d4894a
5a51c40dca774374d563324b3a698d8f0080683b
/Common/C2DSprite.h
beaa321d6979e7e13a390b2d07996eabf56b00d4
[]
no_license
CherylHuang/LightingHW
1aab4481a0c83f66def3713dfdc5fe913787880d
992df8e801960b96bb0e9c1775ffcf6e9fbf12d5
refs/heads/master
2020-03-20T21:48:33.953067
2019-07-25T14:50:30
2019-07-25T14:50:30
137,761,608
0
0
null
null
null
null
BIG5
C++
false
false
763
h
#ifndef C2DSPRITE_H #define C2DSPRITE_H #include "../header/Angel.h" #include "C2DShape.h" typedef Angel::vec4 color4; typedef Angel::vec4 point4; #define QUAD_NUM 6 // 2 faces, 2 triangles/face class C2DSprite : public C2DShape { public: C2DSprite(); ~C2DSprite(); vec4 m_OriginalLL, m_OriginalTR; // sprite 在 local 座標的左下與右上兩個頂點座標 vec4 m_LL, m_TR; // sprite 在世界座標的左上與右下兩個頂點座標 vec4 m_DefaultColor; bool m_bPushed; void SetTRSMatrix(mat4 &mat); void SetDefaultColor(vec4 vColor); bool getButtonStatus(){ return m_bPushed; } bool OnTouches(const vec2 &tp); void Update(float dt); GLuint GetShaderHandle() { return m_uiProgram; } void Draw(); void DrawW(); }; #endif
d6ba1f108b4cd86f3b6d4a15a678d7149899bb34
ef160c3cd5677b53f3bd305166bf010d00055929
/objarsenal.h
cfa2432ff51feef91ee096eccc656f4f2d684c37
[]
no_license
GPif/WootManager
4b5953e9c8051345b96787db679072281decb6b7
283f3e9231084625cbf3639673d0227f7f0e74c8
refs/heads/master
2016-09-10T10:05:56.988732
2012-05-28T14:40:12
2012-05-28T14:40:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
434
h
#ifndef OBJARSENAL_H #define OBJARSENAL_H #include <QString> class ObjArsenal { public: ObjArsenal(); ObjArsenal(int id, QString name, int enc, int value); int getId(); void setId(int); QString getName(); void setName(QString); int getEnc(); void setEnc(int); int getValue(); void setValue(int); private: int id; QString name; int enc; int value; }; #endif // OBJARSENAL_H
28a14bac8e41dfc509c65f515b72952bef5d0bb3
5188bda3380687121d57206c5f616a6612bbbf05
/src/api_elements.cpp
2f9f1d0b719acab912df9e296765eddb52148bf2
[]
no_license
PollyLabs/library-metamorphic-testing
6fce5a7f352ee5afe6c8f108cc75bcf8015936fe
b5f661851b0c9435e460f76032758092c7ef7728
refs/heads/master
2021-06-09T16:21:02.349135
2021-06-01T09:51:52
2021-06-01T09:51:52
144,584,456
5
2
null
2019-04-10T11:06:42
2018-08-13T13:35:38
C++
UTF-8
C++
false
false
27,291
cpp
#include "api_elements.hpp" std::map<std::string, PrimitiveTypeEnum> primitives_map = { { "char", CHAR }, { "string", STRING }, { "std::string", STRING }, { "nqstring", NQSTRING }, { "unsigned int", UINT }, { "int", INT }, { "int32_t", INT }, { "uint32_t", UINT }, { "size_t", UINT }, { "int64_t", LONG }, { "long", LONG }, { "double", DOUBLE }, { "float", FLOAT }, { "bool", BOOL }, }; std::map<std::string, std::string> api_ops_map = { { "ApiOp_Add", "+" }, { "ApiOp_Sub", "-" }, { "ApiOp_Div", "/" }, { "ApiOp_Mul", "*" }, { "ApiOp_Equals", "==" }, { "ApiOp_LessThan", "<" }, { "ApiOp_LessThanEquals", "<=" }, { "ApiOp_GreaterThan", ">" }, { "ApiOp_GreaterThanEquals", ">=" }, }; /******************************************************************************* * Helper functions ******************************************************************************/ void logDebug(std::string message) { if (DEBUG) { std::cerr << "DEBUG: " << message << std::endl; } } void CHECK_CONDITION(bool condition, std::string message) { if (!condition) { std::cout << "CHECK FAILED: " << message << std::endl; if (DEBUG) { assert(false); } exit(1); } } std::string getStringWithDelims(std::vector<std::string> string_list, char delim) { if (string_list.begin() == string_list.end()) { return ""; } std::string string_with_delim = ""; std::vector<std::string>::iterator it = string_list.begin(); for (int i = 1; i < string_list.size(); i++) { string_with_delim += *it + delim + " "; it++; } string_with_delim += *it; return string_with_delim; } template<typename T> std::string makeArgString(std::vector<T> func_args) { std::vector<std::string> args_to_string; for (T& obj : func_args) { CHECK_CONDITION(obj != nullptr, fmt::format("Got null pointer argument when making argument string")); args_to_string.push_back(obj->toStr()); } return getStringWithDelims(args_to_string, ','); } /******************************************************************************* * ApiType functions ******************************************************************************/ bool ApiType::isType(const ApiType* other) const { if (other->isExplicit()) { other = dynamic_cast<const ExplicitType*>(other)->getUnderlyingType(); } return !this->toStr().compare(other->toStr()); } std::ostream& operator<<(std::ostream& os, ApiType* type) { os << type->toStr(); return os; } /******************************************************************************* * ExplicitType functions ******************************************************************************/ ExplicitType::ExplicitType(std::string _definition, const ApiType* _underlying_type) : ApiType(_definition), underlying_type(_underlying_type), definition(_definition) { size_t mid_one = _definition.find(delim_mid); size_t mid_two = _definition.find(delim_mid, mid_one + 1); CHECK_CONDITION(mid_two != std::string::npos, fmt::format("Expected second middle delimiter in comprehension `{}`.", _definition)); size_t end = _definition.rfind(delim_back); this->gen_type = _definition.substr(1, mid_one - 1); this->gen_method = _definition.substr(mid_one + 1, mid_two - mid_one - 1); this->descriptor = _definition.substr(mid_two + 1, end - mid_two - 1); } //const ApiObject* //ExplicitType::retrieveObj() const //{ //assert(this->definition.front() == delim_front && //this->definition.back() == delim_back); //logDebug("Definition to retrieve: " + this->getDefinition()); //if (this->definition.find(fmt::format("string{}", delim_mid)) //!= std::string::npos) //{ //assert(this->getUnderlyingType()->isPrimitive()); //assert(((PrimitiveType *) this->getUnderlyingType())->getTypeEnum() //== STRING); //std::string data = this->definition.substr(this->definition.find(delim_mid) + 1, //this->definition.find(delim_back) - this->definition.find(delim_mid) - 1); //return new PrimitiveObject<std::string>( //(PrimitiveType*) this->getUnderlyingType(), data); //} //else if (this->definition.find(fmt::format("uint{}", delim_mid)) //!= std::string::npos) //{ //assert(this->getUnderlyingType()->isPrimitive()); //assert(((PrimitiveType *) this->getUnderlyingType())->getTypeEnum() //== UINT); //std::string data = this->definition.substr(this->definition.find(delim_mid) + 1, //this->definition.find(delim_back) - this->definition.find(delim_mid) - 1); //return new PrimitiveObject<unsigned int>( //(PrimitiveType*) this->getUnderlyingType(), std::stoi(data)); //} //else if (this->definition.find(fmt::format("input{}", delim_mid)) //!= std::string::npos) //{ //// TODO //assert(false); //} //assert(false); //} std::string ExplicitType::extractExplicitTypeDecl(std::string type_str) { assert(type_str.front() == delim_front && type_str.back() == delim_back); assert(type_str.find(delim_mid) != std::string::npos); unsigned int substr_start = type_str.find(delim_mid) + 1; unsigned int substr_length = type_str.find(delim_back) - type_str.find(delim_mid) - 1; return type_str.substr(substr_start, substr_length); } /******************************************************************************* * TemplateType functions ******************************************************************************/ TemplateType::TemplateType(std::string _name, size_t _template_count) : ApiType(_name), template_count(_template_count) { //std::string template_str = std::accumulate(std::begin(_template_list), //std::end(_template_list), //std::string(), [](std::string acc, const ApiType* template_type) //{ //return acc + ',' + template_type->toStr(); //}); //this->name = fmt::format("{}<{}>", _base_type->toStr(), template_str); } /******************************************************************************* * ApiObject functions ******************************************************************************/ ApiObject::ApiObject(std::string _name, size_t _id, const ApiType* _type, bool _initialize) : id(_id), name(_name), type(_type), initialize(_initialize), declared(false) { if (_type && _type->isEnum()) { CHECK_CONDITION(dynamic_cast<const EnumType*>(_type)->checkValue(_name), fmt::format("Invalid enum value {} for type {}.", _name, _type->toStr())); } } FuncObject::FuncObject(const ApiFunc* _func, const ApiObject* _target, std::vector<const ApiObject*> _params) : ApiObject(_func->getName(), -1, _func->getReturnType()), func(_func), target(_target), params(_params) {}; FuncObject* FuncObject::concretizeVars(const ApiObject* curr_meta_variant, const std::vector<const ApiObject*>& meta_variant_vars, const std::vector<const ApiObject*>& input_vars) const { // TODO add a makeConcrete function to ApiObject std::vector<const ApiObject*> concrete_params; std::transform(this->params.begin(), this->params.end(), std::back_inserter(concrete_params), [&](const ApiObject* param) { if (dynamic_cast<const MetaVarObject*>(param)) { return dynamic_cast<const ApiObject*>( dynamic_cast<const MetaVarObject*>(param)-> getConcreteVar(curr_meta_variant, meta_variant_vars, input_vars)); } if (dynamic_cast<const FuncObject*>(param)) { return dynamic_cast<const ApiObject*>( dynamic_cast<const FuncObject*>(param)-> concretizeVars(curr_meta_variant, meta_variant_vars, input_vars)); } return param; }); const ApiObject* concrete_target = nullptr; if (target) { if (dynamic_cast<const MetaVarObject*>(target)) { concrete_target = dynamic_cast<const MetaVarObject*>(target)-> getConcreteVar(curr_meta_variant, meta_variant_vars, input_vars); } else if (dynamic_cast<const FuncObject*>(target)) { concrete_target = dynamic_cast<const FuncObject*>(target)-> concretizeVars(curr_meta_variant, meta_variant_vars, input_vars); } else { concrete_target = target; } } return new FuncObject(this->func, concrete_target, concrete_params); } /** * @brief Returns all ApiObject references from current FuncObject * * Iterates over all object fields of current FuncObject and gathers valid * ApiObject pointers; if any such field points to another FuncObject, * recursively calls `getAllObjs` over the respective pointers. * * @return A vector containing all ApiObject pointers of this and any children * FuncObjects */ std::vector<const ApiObject*> FuncObject::getAllObjs(void) const { std::vector<const ApiObject*> all_objs; if (this->target) { std::vector<const ApiObject*> target_objs = target->getAllObjs(); all_objs.insert(all_objs.end(), target_objs.begin(), target_objs.end()); } std::for_each(this->params.begin(), this->params.end(), [&all_objs](const ApiObject* param) { std::vector<const ApiObject*> param_objs = param->getAllObjs(); all_objs.insert(all_objs.end(), param_objs.begin(), param_objs.end()); }); return all_objs; } std::string FuncObject::toStr() const { std::vector<std::string> param_names; //for (const ApiObject* param : this->params) //{ //param_names.push_back(param->toStr()); //} std::transform(this->params.begin(), this->params.end(), std::back_inserter(param_names), [](const ApiObject* param) { return param->toStr(); }); if (target) { return fmt::format("{}.{}({})", this->target->toStr(), this->name, getStringWithDelims(param_names, ',')); } return fmt::format("{}({})", this->name, getStringWithDelims(param_names, ',')); } /******************************************************************************* * TemplateObject functions ******************************************************************************/ TemplateObject::TemplateObject(std::string _name, size_t _id, const TemplateInstance _ti): ApiObject(_name, _id, _ti.getBaseType()), template_instance(_ti) {}; //std::string //templateObject::toStr() const //{ //std::string type_name = fmt::format("{}<{}>", this->getType()->toStr(), //std::accumulate(std::begin(this->template_types), //std::end(this->template_list), std::string(), //[](std::string acc, const ApiType* template_type) //{ //return acc + ',' + template_type->toStr(); //})); //return fmt::format("{} {}", type_name, this->name); //} /******************************************************************************* * MetaVarObject functions ******************************************************************************/ bool MetaVarObject::isInput(void) const { size_t pos; std::stoul(this->getIdentifier(), &pos); return pos == this->getIdentifier().size(); } const ApiObject* MetaVarObject::getConcreteVar(const ApiObject* curr_meta_variant, const std::vector<const ApiObject*>& meta_variants, const std::vector<const ApiObject*>& input_vars) const { if (this->meta_relations.empty()) { if (!this->getIdentifier().compare("<m_curr>")) { return curr_meta_variant; } else if (this->getIdentifier().front() == 'm') { assert(std::isdigit(this->getIdentifier()[1])); size_t meta_variant_id = stoi(this->getIdentifier().substr(1)); for (const ApiObject* mv : meta_variants) { if (mv->getID() == meta_variant_id) { return mv; } } assert(false); } else if (std::isdigit(this->getIdentifier().front())) { size_t input_id = stoi(this->getIdentifier()) - 1; assert (input_id < input_vars.size()); return input_vars.at(input_id); } assert(false); } return this->meta_relations.at( this->rng->getRandInt(0, this->meta_relations.size())) ->getBaseFunc()->concretizeVars(curr_meta_variant, meta_variants, input_vars); } const MetaRelation* MetaRelation::concretizeVars(const ApiObject* curr_meta_variant, const std::vector<const ApiObject*>& meta_variant_vars, const std::vector<const ApiObject*>& input_vars ) const { const MetaVarObject* meta_store_var = dynamic_cast<const MetaVarObject*>(this->store_var); const ApiObject* concrete_store_var = nullptr; if (meta_store_var) { concrete_store_var = meta_store_var->getConcreteVar(curr_meta_variant, meta_variant_vars, input_vars); } const FuncObject* concrete_func_obj = this->getBaseFunc()->concretizeVars(curr_meta_variant, meta_variant_vars, input_vars); return new MetaRelation(this->getAbstractRelation(), concrete_func_obj, concrete_store_var); } const ApiInstruction* MetaRelation::toApiInstruction() const { const ApiFunc* func = this->getBaseFunc()->getFunc(); const std::vector<const ApiObject*> params = this->getBaseFunc()->getParams(); const ApiObject* target_obj = this->getBaseFunc()->getTarget(); const ApiObject* result_obj = this->getStoreVar(); return new ApiInstruction(func, result_obj, target_obj, params); } std::string MetaRelation::toStr() const { std::stringstream mr_ss; if (store_var) { mr_ss << store_var->toStr() << " = "; } mr_ss << base_func->toStr() << ";"; return mr_ss.str(); } /******************************************************************************* * ApiFunc functions ******************************************************************************/ const ApiType* ApiFunc::getParamType(const unsigned int index) const { assert(index < this->getParamCount()); return this->param_types.at(index); } bool ApiFunc::hasParamTypes(std::vector<const ApiType*> param_types_check) const { if (param_types_check.size() != this->getParamCount()) { return false; } for (int i = 0; i < param_types_check.size(); i++) { if (param_types_check.at(i)->isExplicit()) { if (dynamic_cast<const ExplicitType*>(param_types_check.at(i))-> getUnderlyingType()->isType(this->getParamType(i))) { return false; } } else if (!param_types_check.at(i)->isType(this->getParamType(i))) { return false; } } return true; } /** * @brief Checks whether the given arguments are compatible with the declared * function signature * * Ensures that the given arguments match with those in the function declaration, * both in terms of number of provided arguments and in terms of individual types * for each argument. Checks that given arguments are not null pointers, which * might happend due to issues further above the generation chain. * * @param args_check A vector containing ApiObjects to be checked against the * provided function signature * * @return `True` is all arguments given are compatible; `False` otherwise */ bool ApiFunc::checkArgs(std::vector<const ApiObject*> args_check) const { if (args_check.size() != this->getParamCount()) { return false; } for (int i = 0; i < args_check.size(); i++) { CHECK_CONDITION(args_check.at(i) != nullptr, fmt::format("Given argument {} to check for function `{}` is null.", i, this->name)); CHECK_CONDITION(args_check.at(i)->getType() != nullptr, fmt::format("Given argument named `{}` to check for function `{}` " "has null type.", args_check.at(i)->toStr(), this->name)); if (!args_check.at(i)->getType()->isType(this->getParamType(i))) { return false; } } return true; } /** * @brief Returns the value for the given flag string * * Looks inside the `flags` map and returns the appropriate bool value for the * corresponding `flag` key. The given parameter can be transformed by the * following operators: * * '!' - negates the returned value of the flag * * @param flag A string representing a flag value to be returned * * @return The corresponding value from the `flags` map */ bool ApiFunc::checkFlag(std::string flag) const { bool negative = flag.front() == '!'; if (negative) { flag.erase(flag.begin()); } assert(flags.count(flag) != 0); //CHECK_CONDITION(flags.count(flag) != 0, //fmt::format("Could not find flag {} for ApiFunc {}.", //flag, this->name)); return negative ^ this->flags.find(flag)->second; } /** * @brief Checks whether a function is callable given existing ApiObjects * * In order for a function to be callable, there must exist objects of required * types to pass as parameters or as a required object instance. If such objects * do exist in the provided `obj_list`, then this function yields `true`. * * @param obj_list List of available objects to use by a potential function call * * @return Whether there are sufficient objects to construct a function call */ bool ApiFunc::isCallable(std::pair<ApiObject_c, ApiFunc_c> gen_data) const { logDebug(fmt::format("Checking if {} is callable.", this->name)); ApiObject_c obj_list = gen_data.first; ApiFunc_c func_list = gen_data.second; if (obj_list.empty() && func_list.empty()) { return false; } if (this->enclosing_class) { ApiObject_c::iterator obj_it = std::find_if(obj_list.begin(), obj_list.end(), [this](const ApiObject* obj) { return obj->hasType(this->getClassType()); }); ApiFunc_c::iterator func_it = std::find_if(func_list.begin(), func_list.end(), [this](const ApiFunc* func) { return func->checkFlag("ctor") && func->hasReturnType(this->getClassType()); }); if ((obj_list.empty() || obj_it == obj_list.end()) && (func_list.empty() || func_it == func_list.end())) { logDebug(fmt::format("Could not find existing object or constructor " "of type {} for instance of func {}.", this->enclosing_class->toStr(), this->name)); return false; } } for (const ApiType* param_type : this->param_types) { ApiObject_c::iterator obj_it = std::find_if(obj_list.begin(), obj_list.end(), [param_type](const ApiObject* obj) { return obj->hasType(param_type); }); ApiFunc_c::iterator func_it = std::find_if(func_list.begin(), func_list.end(), [param_type](const ApiFunc* func) { return func->checkFlag("ctor") && func->hasReturnType(param_type); }); if ((obj_list.empty() || obj_it == obj_list.end()) && (func_list.empty() || func_it == func_list.end())) { logDebug(fmt::format("Could not find existing object or " " constructor of type {} for param of func {}.", param_type->toStr(), this->name)); return false; } } logDebug(fmt::format("{} found callable.", this->name)); return true; } //bool //ApiFunc::isConstructorCallable( //std::set<const ApiFunc*, decltype(&ApiFunc::pointerCmp)> func_list) const //{ //logDebug(fmt::format("Checking if {} is constructor callable.", this->name)); //if (func_list.empty()) //{ //return false; //} //if (this->enclosing_class) //{ //std::set<const ApiFunc*, decltype(&ApiType::pointerCmp)>::iterator it = //std::find_if(func_list.begin(), func_list.end(), //[this](const ApiFunc* af) //{ //return af->checkFlag("ctor") && //af->hasReturnType(this->getClassType()); //}); //if (it == func_list.end()) //{ //logDebug(fmt::format("Could not find existing ctor func of type {} " //"for instance of func {}.", this->enclosing_class->toStr(), //this->name)); //return false; //} //} //for (const ApiType* param_type : this->param_types) //{ //std::set<const ApiFunc*, decltype(&ApiType::pointerCmp)>::iterator it = //std::find_if(func_list.begin(), func_list.end(), //[&param_type](const ApiFunc* af) //{ //return af->checkFlag("ctor") && af->hasReturnType(param_type); //}); //if (it == func_list.end()) //{ //logDebug(fmt::format("Could not find existing ctor func of type {} " //"for param of func {}.", param_type->toStr(), this->name)); //return false; //} //} //logDebug(fmt::format("{} found callable.", this->name)); //return true; //} std::string ApiFunc::printSignature() const { std::stringstream print_ss; //if (this->getClassType()->toStr() != "") if (this->getClassType()) { print_ss << this->getClassType()->toStr() << "."; } print_ss << this->getName() << "("; print_ss << makeArgString(this->getParamTypes()) << ")"; return print_ss.str(); } /******************************************************************************* * ApiExpr functions ******************************************************************************/ std::string BinaryExpr::toStr() const { return fmt::format("{} {} {}", this->lhs->toStr(), api_ops_map[this->op_name], this->rhs->toStr()); } std::string UnaryExpr::toStr() const { return this->obj->toStr(); } /******************************************************************************* * ApiInstruction functions ******************************************************************************/ ApiInstruction::ApiInstruction(const ApiFunc* _func, const ApiObject* _result, const ApiObject* _target, std::vector<const ApiObject*> _params, bool _decl_instr) : func(_func), func_elems{_result, _target, _params} { if (func_elems.result) { decl_instr = !func_elems.result->isDeclared(); func_elems.result->setDeclared(); } } /** * @brief Returns the string representation of an ApiInstruction * * Appropriately transforms each member of an ApiInstruction via `toStr()` calls * to each object, and collates them together in a C++ syntax. In essence, the * `target` and `result` fields are directly translated into strings, while an * invocation of `func` is constructed by applying it to `func_params`. * * @return A string representation of all internal constructs. */ std::string ApiInstruction::toStr() const { std::stringstream instr_ss; if (!this->getFunc()->checkArgs(this->getFuncParams())) { const ApiFunc* func = this->getFunc(); std::cout << "Invalid arguments given for func " << func->getName(); std::cout << std::endl << "\tExpected types: " << makeArgString( func->getParamTypes()); std::vector<std::string> arg_strings; for (const ApiObject* func_param : this->getFuncParams()) { //arg_strings.push_back(func_param->toStrWithType()); arg_strings.push_back(func_param->toStr()); } std::cout << std::endl << "\tGiven types: "; std::cout << getStringWithDelims(arg_strings, ',') << std::endl; assert(false); } if (this->getResultObj() != nullptr) { if (this->isDeclInstr()) { instr_ss << this->getResultObj()->toStrWithType(); } else { instr_ss << this->getResultObj()->toStr(); } instr_ss << " = "; } else { assert(!this->getFunc()->checkFlag("ctor")); } if (!this->getFunc()->getConditions().empty()) { assert(false); //instr_ss << this->emitFuncCond(this->getFunc, this->getTargetObj, //this->getFuncParams()); } if (!this->getFunc()->checkFlag("statik") && this->getTargetObj() != nullptr) { // TODO consider pointer objects std::string invocation_string = this->getTargetObj()->getType()->checkFlag("pointer") ? "->" : "."; instr_ss << this->getTargetObj()->toStr() << invocation_string; } else if (this->getFunc()->checkFlag("statik")) { CHECK_CONDITION(this->getTargetObj() == nullptr, fmt::format("Called static function `{}` on enclosing class instance.", this->getFunc()->getName())); instr_ss << this->getFunc()->getClassType()->toStr() << "::"; } instr_ss << this->printFuncInvocation(this->getFunc(), this->getFuncParams()); instr_ss << ";"; return instr_ss.str(); } /** * @brief Helper function to print the invocation of a ApiFunc * * Fully prints an ApiFunc invocation for the given parameters, in the form * `name(params...). Appropriate checks are performed by the * ApiInstruction::toStr() caller. * * @param func A pointer to the ApiFunc to be invoked * @param params A vector containing the parameter to pass to the function * invocation * * @return A string representing the invocation in plain text. */ std::string ApiInstruction::printFuncInvocation(const ApiFunc* func, std::vector<const ApiObject*> params) const { std::stringstream print_inv_ss; print_inv_ss << func->getName() << "("; print_inv_ss << makeArgString(params) << ")"; return print_inv_ss.str(); } std::string ObjectDeclInstruction::toStr() const { return this->getObject()->toStrWithType() + ";"; } std::string ObjectConstructionInstruction::toStr() const { // TODO move this check somewhere else CHECK_CONDITION(this->ctor->checkArgs(this->params), fmt::format("Invalid arguments given to constructor `{}` for object `{}`.", this->ctor->getName(), this->getObject()->toStr())); std::stringstream obj_ctor_instr_ss; obj_ctor_instr_ss << this->getObject()->toStrWithType(); obj_ctor_instr_ss << this->ctor->getName() << "("; obj_ctor_instr_ss << makeArgString(this->params) << ");"; return obj_ctor_instr_ss.str(); }
426c2dff8dbfaf45f59dc2c1effa11525c9329ef
45097a13834f73d96cd40d8f301b085d3c054516
/features/jvp1Test/jvp1Test.h
5b896c38f9dd954566078012d327c2baa83b71a7
[ "Apache-2.0" ]
permissive
trikset/trik-teststand
be53d7b810aa838383deebcaed42f46dc728368f
4ccf89203efd80c03f8d8ff1a32241c1547b5baf
refs/heads/master
2021-08-22T06:03:45.883512
2017-11-29T12:46:41
2017-11-29T12:46:41
112,473,290
0
0
null
2017-11-29T12:34:19
2017-11-29T12:34:19
null
UTF-8
C++
false
false
990
h
/* Copyright 2014 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "testInterface.h" class jvp1Test : public QObject , public TestInterface { Q_OBJECT Q_INTERFACES(TestInterface) Q_PLUGIN_METADATA(IID "com.trikset.teststand.vp1") public: TestInterface::Result run(trikControl::BrickInterface &brick, QStringList &log); private: TestInterface::Result captureVideo(); QStringList *mLog; TestInterface::Result mResult; };
5735a1d63601977ac2cdbc19cdcc2e6974f603d5
eab0452a2fa4075eb7351294279603bab7940000
/src/windows/utf.hpp
edc4b2f4bc4f71d8978edb81c553a4141217a0b7
[]
no_license
cooky451/passchain
c0b16315aa7e4a5d67aec96bad9810416a063ba6
b40445433077dd803c4249c87849dab1063cbd8e
refs/heads/master
2020-05-21T18:03:07.656630
2016-10-23T16:56:24
2016-10-23T16:56:24
63,672,911
1
0
null
null
null
null
UTF-8
C++
false
false
1,361
hpp
#pragma once #include <string> #include "base.hpp" std::string toUtf8(const wchar_t* sourceString, std::size_t sourceStringSize) { auto destStringSize = WideCharToMultiByte(CP_UTF8, 0, sourceString, static_cast<int>(sourceStringSize), nullptr, 0, nullptr, nullptr); std::string destString(destStringSize, char()); WideCharToMultiByte(CP_UTF8, 0, sourceString, static_cast<int>(sourceStringSize), &destString[0], destStringSize, nullptr, nullptr); return destString; } std::string toUtf8(const wchar_t* sourceString) { return toUtf8(sourceString, lstrlenW(sourceString)); } std::string toUtf8(const std::wstring& sourceString) { return toUtf8(sourceString.c_str(), sourceString.size()); } std::wstring toWideString(const char* sourceString, std::size_t sourceStringSize) { auto destStringSize = MultiByteToWideChar(CP_UTF8, 0, sourceString, static_cast<int>(sourceStringSize), nullptr, 0); std::wstring destString(destStringSize, destStringSize); MultiByteToWideChar(CP_UTF8, 0, sourceString, static_cast<int>(sourceStringSize), &destString[0], destStringSize); return destString; } std::wstring toWideString(const char* sourceString) { return toWideString(sourceString, lstrlenA(sourceString)); } std::wstring toWideString(const std::string& sourceString) { return toWideString(sourceString.c_str(), sourceString.size()); }
dc71d853c2b7683affea5763076eea8dbcc9e5cc
a2334c8385e29e414428c3c38cc0925f1c205be1
/qt_gl/model/Tensor.cpp
8a9b2358799673d41f649f09fe0a9e6c1bfcfa86
[]
no_license
dem42/exp_tran
6c3fddbe67d09d89fde5758792499695ee36c38f
3bd31225db1ad5fabe8a8b0a3b50c23983e8848f
refs/heads/master
2020-09-12T23:08:11.260813
2014-08-05T00:24:24
2014-08-05T00:24:24
674,170
2
0
null
null
null
null
UTF-8
C++
false
false
21
cpp
#include "Tensor.h"
3d9305feb22a3c5c1146cbc964690171712ab97a
956b91611aa6901913d24025a45d33dfcb0abadb
/lab6/Circle.cpp
c5a8b9d3de24c5f00fbbcdbcc72c350c8a556209
[]
no_license
dhruvchawla1996/ece244_labs
b72f0bb7ca6a4128edb3b2b6cf051d33e68247ae
7568041ebeb263c2bf5d2da671ae65ef42d8a4d7
refs/heads/master
2016-08-11T11:24:35.245511
2015-12-31T14:11:50
2015-12-31T14:11:50
48,846,809
0
2
null
null
null
null
UTF-8
C++
false
false
939
cpp
#include <iostream> #include <cmath> #include "Circle.h" using namespace std; Circle::Circle (string _name, string _colour, float _xcen, float _ycen, float _radius) : Shape (_name, _colour, _xcen, _ycen) { radius = _radius; } Circle::~Circle() { // nothing to delete } void Circle::print () const { Shape::print(); cout << "circle radius: " << radius << endl; } void Circle::scale (float scaleFac) { radius *= scaleFac; } float Circle::computeArea () const { return PI * radius * radius; } float Circle::computePerimeter () const { return 2 * PI * radius; } void Circle::draw (easygl* window) const { // set colour window->gl_setcolor(getColour()); // draw window->gl_fillarc(getXcen(), getYcen(), radius, 0, 360); } bool Circle::pointInside (float x, float y) const { // true if (x-Xcen)^2 + (y-Ycen)^2 < r^2 return ( pow(x - getXcen(),2) + pow(y - getYcen(),2) < pow(radius,2) ); }
df7f980562cbdbef5b45814d688562a82e9182cc
38f055a979a0e4acecf5d2a5ad0d0344d1f52db2
/src/mess/machine/isa_hdc.h
61399e9fa7108fe53c08a4be1904eb6ffdff7e5c
[]
no_license
poliva/mame-rr
0cc05bed2a80addbb906e97b8f25633496eecab6
124dbb66844bc6d8747b19b8483cefa28fb6b7fb
refs/heads/master
2021-01-22T05:16:42.247183
2015-04-24T08:59:22
2015-04-24T08:59:22
34,506,421
3
0
null
null
null
null
UTF-8
C++
false
false
2,888
h
/********************************************************************** ISA 8 bit XT Hard Disk Controller **********************************************************************/ #pragma once #ifndef ISA_HDC_H #define ISA_HDC_H #include "emu.h" #include "machine/isa.h" #include "imagedev/harddriv.h" //************************************************************************** // TYPE DEFINITIONS //************************************************************************** // ======================> isa8_hdc_device class isa8_hdc_device : public device_t, public device_isa8_card_interface { public: // construction/destruction isa8_hdc_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock); // optional information overrides virtual machine_config_constructor device_mconfig_additions() const; virtual const rom_entry *device_rom_region() const; protected: // device-level overrides virtual void device_start(); virtual void device_reset(); private: int drv; /* 0 master, 1 slave drive */ int cylinders[2]; /* number of cylinders */ int rwc[2]; /* reduced write current from cyl */ int wp[2]; /* write precompensation from cyl */ int heads[2]; /* heads */ int ecc[2]; /* ECC bytes */ /* indexes */ int cylinder[2]; /* current cylinder */ int head[2]; /* current head */ int sector[2]; /* current sector */ int sector_cnt[2]; /* sector count */ int control[2]; /* control */ int csb; /* command status byte */ int status; /* drive status */ int error; /* error code */ int dip; /* dip switches */ emu_timer *timer; int data_cnt; /* data count */ UINT8 *buffer; /* data buffer */ UINT8 *buffer_ptr; /* data pointer */ UINT8 hdc_control; UINT8 hdcdma_data[512]; UINT8 *hdcdma_src; UINT8 *hdcdma_dst; int hdcdma_read; int hdcdma_write; int hdcdma_size; // internal state public: virtual UINT8 dack_r(int line); virtual void dack_w(int line,UINT8 data); virtual bool have_dack(int line); protected: hard_disk_file *pc_hdc_file(int id); void pc_hdc_result(int set_error_info); int no_dma(void); int get_lbasector(); int pc_hdc_dack_r(); void pc_hdc_dack_w(int data); void execute_read(); void execute_write(); void get_drive(); void get_chsn(); int test_ready(); static TIMER_CALLBACK(pc_hdc_command); public: void hdc_command(); void pc_hdc_data_w(int data); void pc_hdc_reset_w(int data); void pc_hdc_select_w(int data); void pc_hdc_control_w(int data); UINT8 pc_hdc_data_r(); UINT8 pc_hdc_status_r(); UINT8 pc_hdc_dipswitch_r(); }; // device type definition extern const device_type ISA8_HDC; #endif /* ISA_HDC_H */
1572d13220a486733c966be887134f716e622840
2476e036866ebf861e834eb0ddb2a8cd49104285
/pat/pat_A_1067/pat_A_1067/main.cpp
ceb694d2f8771ab4d329474ca5d1da59621390ed
[]
no_license
xchmwang/algorithm
7deaedecb58e3925cc23239020553ffed8cc3f04
55345160b6d8ef02bc89e01247b4dbd1bc094d5e
refs/heads/master
2021-09-17T23:54:40.785962
2018-07-07T06:40:27
2018-07-07T06:40:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
255
cpp
#include <iostream> using namespace std; const int maxn = 1e5 + 10; int num[maxn]; void solve() { int N; cin >> N; for (int i = 0; i < N; ++i) scanf("%d", &num[i]); for (int i = 0; i < N; ++i) { } return; } int main() { solve(); return 0; }
3140e5d968021dfe0e78df95b8e818ad4a12049b
67ed89e1bbd21cb771240943bce3f299591a844e
/board.cpp
b90f2fe76c4997b0b875eb361836a5553517cf35
[]
no_license
damon-murdoch/nqueens-cpp
555ee10e3a9a050fdf14a6b8643e5fc3c4d3f7c8
4c42521a73d92653cfaa4b1efc407c500766abb1
refs/heads/master
2023-05-28T07:46:47.831895
2021-06-16T05:29:39
2021-06-16T05:29:39
375,603,086
0
0
null
null
null
null
UTF-8
C++
false
false
3,491
cpp
#ifndef __BOARD__CPP #define __BOARD__CPP #include "board.hpp" using namespace std; bool compare(Point * a, Point * b) { return (a -> x == b -> x) && (a -> y == b -> y); } Point::Point() { this->x = 0; this->y = 0; } Point::Point(int x, int y) { this->x = x; this->y = y; } bool compare_h(Board a, Board b) { // Compare function, return if 'a' is less costly than 'b'. return a.getHeuristic() < b.getHeuristic(); } Board::Board(int size) { // Vector of array points this->queens = vector::vector<Point>(); // Keep going until the array is full while(this->queens.size() < size) { // Create a new random queen Point p = Point::Point(rand() % size, rand() % size); // If the queen is not a duplicate if (!this->at(&p)) { // Add a random queen to the list this->queens.push_back(p); } } } Board::Board(Board * other) { // Create a clone of the existing boards array this->queens = vector::vector<Point>(other->queens); } Board::Board() { // Create an empty queens array this->queens = vector::vector<Point>(); } int Board::getSize() { // Return the size of the queens list return this->queens.size(); } int Board::getHeuristic() { // Check every queen against every other queen // Number of Collisions int h = 0; for(int i = 0; i<this->queens.size() - 1; i++) { for(int j = i + 1; j<this->queens.size(); j++) { // If the queens 'x' location is the same if (this->queens.at(i).x == this->queens.at(j).x) { // Increment the 'h' value h++; } // If the queens 'y' location is the same else if (this->queens.at(i).y == this->queens.at(j).y) { // Increment the 'h' value h++; } // If the queens are diagonal to each other // If the 'difference between the 'x' and 'y' is the same else if (abs(this->queens.at(i).y - this->queens.at(j).y) == abs(this->queens.at(i).x - this->queens.at(j).x)) { // Increment the 'h' value h++; } } } return h; } bool Board::at(Point * p) { // Create an iterator for the moves list std::vector<Point>::iterator it = this->queens.begin(); // Loop over the iterator of the list for(; it < this->queens.end(); it++) { // Compare the current index to the provided points // If the value is true, return true if (compare(p, &(*it)) == true) return true; } // No comparison was correct, return false return false; } bool Board::at(int x, int y) { // Create a temporary variable for the given point Point p = Point::Point(x, y); // Return the result of the comparison return this->at(&p); } void Board::print() { // Output map object, same length as queen count vector<vector<bool>> map(this->queens.size(),vector::vector<bool>(this->queens.size(), false)); // Loop over the queens in the list for(int i=0; i<this->queens.size(); i++) { // Set the point on the map to true map.at(this->queens.at(i).y).at(this->queens.at(i).x) = true; } // Loop over the y axis for(int i=0; i<this->queens.size(); i++) { // Loop over the x axis for(int j=0; j<this->queens.size(); j++) { // Print a hashtag if this is a queen, blank space if it is not if (map.at(i).at(j) == true) { cout << "#"; } else { cout << " "; } } // Print the newline cout << endl; } } #endif //__BOARD__CPP
369fe7fe61f486745c500edc543fc157f1052d83
ed1dd1e84ca75127a12e1592c2fbc3b6365a749f
/generatedNeedham/CryptoLib/test/cryptorTestFile.cpp
28f4dfac64a8c175b43517c1a42198556ac508a1
[]
no_license
SpencerL-Y/testGenerated
c25dc1a0b18df73f6e3cd84dc3eee9c80222b75b
6492f82aea88c3215e70f7deda283c849ca96d86
refs/heads/main
2023-01-02T14:23:30.479836
2020-10-22T09:32:29
2020-10-22T09:32:29
306,269,780
0
0
null
null
null
null
UTF-8
C++
false
false
3,516
cpp
#include "../include/Cryptor.hpp" #include <stdlib.h> #include <iostream> #include <string> int main(){ Cryptor cryptor; Cryptor cryptor1; std::string key = "thisiskey"; std::string key2 = "thisiskey"; std::string wrongKey = "thisis"; char* out = (char*)malloc(100*sizeof(char)); std::string origin = "serialization::archi���C�"; cryptor.aes_encrypt((char*)origin.c_str(), (char*)key.c_str(), out); std::cout << out << std::endl; char* outout = (char*)malloc(100*sizeof(char)); cryptor1.aes_decrypt(out, (char*)key2.c_str(), outout); std::cout << outout << std::endl; free(out); free(outout); std::string pri, pub; cryptor.createRSAKeyPair(pub, pri); std::cout << "pri:\n" << pri << std::endl; std::cout << "pub:\n" << pub << std::endl; //pri = "false"; //std::string pubkey = "MIIBCAKCAQEAvT1ytMNiQo+6GREbw4NzhzbXMPI+tZ49S/tvQpNzy2BXqBWnNVvvKsqh4OCGE9mA9US3Ei3SCzhJFhsQGWL5ut71wmPOCyFjSa70985LnuRLlcBbOvO5p3Hhf3ZguwUZRy3HgMBfSy9l86IurSBW3kupzP6ITBy8KCpoJ0h6kEcp4ZpnXFucF8NYuTE5bge88bC/5CrHIPO87L45rTsF2TCx5XHfH7PHPmH2u+ppND56tlCwazKRWpPgHRxn6oQf4OdmvnVA6y6SpotwWDzQhWZucn3JRWV9El6D8G1mn+WNiEcbSkQE2H8omGoo97HFz9CbAWULyLB6OG7B1UajjQIBAw=="; out = (char*)malloc(sizeof(char)*1000); outout = (char*)malloc(sizeof(char)*1000); origin = "this is me"; std::cout << origin << std::endl; std::string cypher = cryptor.rsa_pubkey_encrypt(origin, pub); std::cout << "out: " << cypher << std::endl; //std::string prikey = "IIEowIBAAKCAQEAvT1ytMNiQo+6GREbw4NzhzbXMPI+tZ49S/tvQpNzy2BXqBWnNVvvKsqh4OCGE9mA9US3Ei3SCzhJFhsQGWL5ut71wmPOCyFjSa70985LnuRLlcBbOvO5p3Hhf3ZguwUZRy3HgMBfSy9l86IurSBW3kupzP6ITBy8KCpoJ0h6kEcp4ZpnXFucF8NYuTE5bge88bC/5CrHIPO87L45rTsF2TCx5XHfH7PHPmH2u+ppND56tlCwazKRWpPgHRxn6oQf4OdmvnVA6y6SpotwWDzQhWZucn3JRWV9El6D8G1mn+WNiEcbSkQE2H8omGoo97HFz9CbAWULyLB6OG7B1UajjQIBAwKCAQB+KPcjLOwsX9FmC2fXrPeveeTLTCnOaX4yp5+Bt6KHlY/FY8TOPUochxaV6wQNO6tOLc9hc+Fc0DC5Z2AQ7KZ8lKPW7TQHa5eGdKNP3t0UmDJj1ZInTSZvoUD/pEB8rhDaHoUAgD+HdO6ibB8eFY8+3Rvd/wWIEygaxvAaMFG1g6EbaUo/N3SQ16GcMwS3C3P5r2SBK1eilzUZKUNy5FgZuHNh/jSmuaa9XfdlxfbqfjkW0TQcHVn0JOaFdsaNApzuhLLlcIcpyoBUpoPFUu5RpBbWPflFyVo59C4BgIUW1IEDn5hVJCH8UYyWJL1hbct6cwNf3htKXkNsG1sE4ZgrAoGBAN3fez7kf5WdwT/iWCe3yyQefnTPsQHRuadjmVtcgv9lnht8bNhlR16dvfP3DB+oJN4c0NNj5OBuPZxwGBjtVtv3X+WQTeeVAHeJEyI8pIePir2/Gh9+6OXjg3L8hfuYxZT0ZPVcwln3Us2ziuU0CzclQ5xRgEbHGHQHgDBcdftxAoGBANpZATkZCNegvqZsjIqjq2rcqzRSuMHbV0XjZvkkYYJM/elWB7fAVe6Elw+sNVcsXEb3Rg7dIan+Hunk0iUpqViDwHTV/o6Xflqefohzm+N7ZY5yBrPdzo/X7MvxpqNk4TcOcsFty3fmsggDqCexgd1y4HmgF5wSCqEOxYjxfkPdAoGBAJPqUintqmO+gNVBkBp6h21pqaM1IKvhJm+Xu5I9rKpDvrz9neWY2j8T0/f6CBUawz694IztQ0BJfmhKurtI5JKk6pkK3ppjVaUGDMF9wwUKXH5/Zr+p8JlCV6H9rqe7LmNNmKOTLDv6NzPNB0N4B3oY172LqtnaEE1aVXWS+VJLAoGBAJGQq3tmBeUV1G7zCFxtHPHociLh0IE85NlCRKYYQQGIqUY5WnqAOUmtugpyzjodktn6LrSTa8apafFDNsNxG5BX1aM5VF8PqZG+/wWiZ+z87l72ryKT3wqP8zKhGcJDQM9e9yueh6VEdrACcBp2VpOh6vvAD71hXGtfLltLqYKTAoGBALpe2ruWH2nQkjg6eyuaVsO2oOpHXK6y7CnD/H60NsdwLStQg0UazLgMdPxiy6C9K3tX2KtP2szZaabOI954qvB+gxUZlnCSxE8LQXXpgU67qrt8flfSj0F9ak5xivFCHj209GqZWQLjMi51Snc4Bg6JmJVYf9R9wNwquGmFnvvz"; std::string clear = cryptor.rsa_prikey_decrypt(cypher, pri); std::cout << "outout: " << clear << std::endl; free(out); free(outout); std::string cipher = cryptor.sha1_encrypt(origin, pri); std::cout << "cipher: " << cipher << std::endl; std::string outoutStr = cryptor.sha1_decrypt(cipher, pub); std::cout << "outoutStr: " << outoutStr << std::endl; return 0; }
b895d90206f65780dbda0849eecac3b3c3bd21d8
0ec9df3bb8b86216e18fe4cb66b6612297245aea
/Sources/CXXBoost/include/boost/iterator/iterator_facade.hpp
7860bc747256d04a035245bbf59ae7acb8f44dbb
[]
no_license
jprescott/BoostTestWithLib
78ae59d1ee801201883cf07ab76b8267fadf7daa
8650523cab467c41be60f3a1c144f556e9a7f25c
refs/heads/master
2022-11-18T14:49:00.664753
2020-07-18T21:45:17
2020-07-18T21:45:17
280,749,418
0
1
null
null
null
null
UTF-8
C++
false
false
33,331
hpp
// (C) Copyright David Abrahams 2002. // (C) Copyright Jeremy Siek 2002. // (C) Copyright Thomas Witt 2002. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_ITERATOR_FACADE_23022003THW_HPP #define BOOST_ITERATOR_FACADE_23022003THW_HPP #include <boost/config.hpp> #include <boost/iterator/interoperable.hpp> #include <boost/iterator/iterator_traits.hpp> #include <boost/iterator/iterator_categories.hpp> #include <boost/iterator/detail/facade_iterator_category.hpp> #include <boost/iterator/detail/enable_if.hpp> #include <boost/static_assert.hpp> #include <boost/core/addressof.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/type_traits/add_const.hpp> #include <boost/type_traits/add_pointer.hpp> #include <boost/type_traits/add_lvalue_reference.hpp> #include <boost/type_traits/remove_const.hpp> #include <boost/type_traits/remove_reference.hpp> #include <boost/type_traits/is_convertible.hpp> #include <boost/type_traits/is_pod.hpp> #include <boost/mpl/eval_if.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/or.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/not.hpp> #include <boost/mpl/always.hpp> #include <boost/mpl/apply.hpp> #include <boost/mpl/identity.hpp> #include <cstddef> #include <boost/iterator/detail/config_def.hpp> // this goes last namespace boost { namespace iterators { // This forward declaration is required for the friend declaration // in iterator_core_access template <class I, class V, class TC, class R, class D> class iterator_facade; namespace detail { // A binary metafunction class that always returns bool. VC6 // ICEs on mpl::always<bool>, probably because of the default // parameters. struct always_bool2 { template <class T, class U> struct apply { typedef bool type; }; }; // The type trait checks if the category or traversal is at least as advanced as the specified required traversal template< typename CategoryOrTraversal, typename Required > struct is_traversal_at_least : public boost::is_convertible< typename iterator_category_to_traversal< CategoryOrTraversal >::type, Required > {}; // // enable if for use in operator implementation. // template < class Facade1 , class Facade2 , class Return > struct enable_if_interoperable : public boost::iterators::enable_if< is_interoperable< Facade1, Facade2 > , Return > {}; // // enable if for use in implementation of operators specific for random access traversal. // template < class Facade1 , class Facade2 , class Return > struct enable_if_interoperable_and_random_access_traversal : public boost::iterators::enable_if< mpl::and_< is_interoperable< Facade1, Facade2 > , is_traversal_at_least< typename iterator_category< Facade1 >::type, random_access_traversal_tag > , is_traversal_at_least< typename iterator_category< Facade2 >::type, random_access_traversal_tag > > , Return > {}; // // Generates associated types for an iterator_facade with the // given parameters. // template < class ValueParam , class CategoryOrTraversal , class Reference , class Difference > struct iterator_facade_types { typedef typename facade_iterator_category< CategoryOrTraversal, ValueParam, Reference >::type iterator_category; typedef typename remove_const<ValueParam>::type value_type; // Not the real associated pointer type typedef typename mpl::eval_if< boost::iterators::detail::iterator_writability_disabled<ValueParam,Reference> , add_pointer<const value_type> , add_pointer<value_type> >::type pointer; # if defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) \ && (BOOST_WORKAROUND(_STLPORT_VERSION, BOOST_TESTED_AT(0x452)) \ || BOOST_WORKAROUND(BOOST_DINKUMWARE_STDLIB, BOOST_TESTED_AT(310))) \ || BOOST_WORKAROUND(BOOST_RWSTD_VER, BOOST_TESTED_AT(0x20101)) \ || BOOST_WORKAROUND(BOOST_DINKUMWARE_STDLIB, <= 310) // To interoperate with some broken library/compiler // combinations, user-defined iterators must be derived from // std::iterator. It is possible to implement a standard // library for broken compilers without this limitation. # define BOOST_ITERATOR_FACADE_NEEDS_ITERATOR_BASE 1 typedef iterator<iterator_category, value_type, Difference, pointer, Reference> base; # endif }; // iterators whose dereference operators reference the same value // for all iterators into the same sequence (like many input // iterators) need help with their postfix ++: the referenced // value must be read and stored away before the increment occurs // so that *a++ yields the originally referenced element and not // the next one. template <class Iterator> class postfix_increment_proxy { typedef typename iterator_value<Iterator>::type value_type; public: explicit postfix_increment_proxy(Iterator const& x) : stored_value(*x) {} // Returning a mutable reference allows nonsense like // (*r++).mutate(), but it imposes fewer assumptions about the // behavior of the value_type. In particular, recall that // (*r).mutate() is legal if operator* returns by value. value_type& operator*() const { return this->stored_value; } private: mutable value_type stored_value; }; // // In general, we can't determine that such an iterator isn't // writable -- we also need to store a copy of the old iterator so // that it can be written into. template <class Iterator> class writable_postfix_increment_proxy { typedef typename iterator_value<Iterator>::type value_type; public: explicit writable_postfix_increment_proxy(Iterator const& x) : stored_value(*x) , stored_iterator(x) {} // Dereferencing must return a proxy so that both *r++ = o and // value_type(*r++) can work. In this case, *r is the same as // *r++, and the conversion operator below is used to ensure // readability. writable_postfix_increment_proxy const& operator*() const { return *this; } // Provides readability of *r++ operator value_type&() const { return stored_value; } // Provides writability of *r++ template <class T> T const& operator=(T const& x) const { *this->stored_iterator = x; return x; } // This overload just in case only non-const objects are writable template <class T> T& operator=(T& x) const { *this->stored_iterator = x; return x; } // Provides X(r++) operator Iterator const&() const { return stored_iterator; } private: mutable value_type stored_value; Iterator stored_iterator; }; # ifdef BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION template <class Reference, class Value> struct is_non_proxy_reference_impl { static Reference r; template <class R> static typename mpl::if_< is_convertible< R const volatile * , Value const volatile * > , char[1] , char[2] >::type& helper(R const&); BOOST_STATIC_CONSTANT(bool, value = sizeof(helper(r)) == 1); }; template <class Reference, class Value> struct is_non_proxy_reference : mpl::bool_< is_non_proxy_reference_impl<Reference, Value>::value > {}; # else template <class Reference, class Value> struct is_non_proxy_reference : is_convertible< typename remove_reference<Reference>::type const volatile * , Value const volatile * > {}; # endif // A metafunction to choose the result type of postfix ++ // // Because the C++98 input iterator requirements say that *r++ has // type T (value_type), implementations of some standard // algorithms like lexicographical_compare may use constructions // like: // // *r++ < *s++ // // If *r++ returns a proxy (as required if r is writable but not // multipass), this sort of expression will fail unless the proxy // supports the operator<. Since there are any number of such // operations, we're not going to try to support them. Therefore, // even if r++ returns a proxy, *r++ will only return a proxy if // *r also returns a proxy. template <class Iterator, class Value, class Reference, class CategoryOrTraversal> struct postfix_increment_result : mpl::eval_if< mpl::and_< // A proxy is only needed for readable iterators is_convertible< Reference // Use add_lvalue_reference to form `reference to Value` due to // some (strict) C++03 compilers (e.g. `gcc -std=c++03`) reject // 'reference-to-reference' in the template which described in CWG // DR106. // http://www.open-std.org/Jtc1/sc22/wg21/docs/cwg_defects.html#106 , typename add_lvalue_reference<Value const>::type > // No multipass iterator can have values that disappear // before positions can be re-visited , mpl::not_< is_convertible< typename iterator_category_to_traversal<CategoryOrTraversal>::type , forward_traversal_tag > > > , mpl::if_< is_non_proxy_reference<Reference,Value> , postfix_increment_proxy<Iterator> , writable_postfix_increment_proxy<Iterator> > , mpl::identity<Iterator> > {}; // operator->() needs special support for input iterators to strictly meet the // standard's requirements. If *i is not a reference type, we must still // produce an lvalue to which a pointer can be formed. We do that by // returning a proxy object containing an instance of the reference object. template <class Reference, class Pointer> struct operator_arrow_dispatch { // proxy references struct proxy { explicit proxy(Reference const & x) : m_ref(x) {} Reference * operator->() { return boost::addressof(m_ref); } // This function is needed for MWCW and BCC, which won't call // operator-> again automatically per 13.3.1.2 para 8 operator Reference * () { return boost::addressof(m_ref); } Reference m_ref; }; typedef proxy result_type; static result_type apply(Reference const & x) { return result_type(x); } }; template <class T, class Pointer> struct operator_arrow_dispatch<T&, Pointer> { // "real" references typedef Pointer result_type; static result_type apply(T& x) { return boost::addressof(x); } }; // A proxy return type for operator[], needed to deal with // iterators that may invalidate referents upon destruction. // Consider the temporary iterator in *(a + n) template <class Iterator> class operator_brackets_proxy { // Iterator is actually an iterator_facade, so we do not have to // go through iterator_traits to access the traits. typedef typename Iterator::reference reference; typedef typename Iterator::value_type value_type; public: operator_brackets_proxy(Iterator const& iter) : m_iter(iter) {} operator reference() const { return *m_iter; } operator_brackets_proxy& operator=(value_type const& val) { *m_iter = val; return *this; } private: Iterator m_iter; }; // A metafunction that determines whether operator[] must return a // proxy, or whether it can simply return a copy of the value_type. template <class ValueType, class Reference> struct use_operator_brackets_proxy : mpl::not_< mpl::and_< // Really we want an is_copy_constructible trait here, // but is_POD will have to suffice in the meantime. boost::is_POD<ValueType> , iterator_writability_disabled<ValueType,Reference> > > {}; template <class Iterator, class Value, class Reference> struct operator_brackets_result { typedef typename mpl::if_< use_operator_brackets_proxy<Value,Reference> , operator_brackets_proxy<Iterator> , Value >::type type; }; template <class Iterator> operator_brackets_proxy<Iterator> make_operator_brackets_result(Iterator const& iter, mpl::true_) { return operator_brackets_proxy<Iterator>(iter); } template <class Iterator> typename Iterator::value_type make_operator_brackets_result(Iterator const& iter, mpl::false_) { return *iter; } struct choose_difference_type { template <class I1, class I2> struct apply : # ifdef BOOST_NO_ONE_WAY_ITERATOR_INTEROP iterator_difference<I1> # else mpl::eval_if< is_convertible<I2,I1> , iterator_difference<I1> , iterator_difference<I2> > # endif {}; }; template < class Derived , class Value , class CategoryOrTraversal , class Reference , class Difference , bool IsBidirectionalTraversal , bool IsRandomAccessTraversal > class iterator_facade_base; } // namespace detail // Macros which describe the declarations of binary operators # ifdef BOOST_NO_STRICT_ITERATOR_INTEROPERABILITY # define BOOST_ITERATOR_FACADE_INTEROP_HEAD_IMPL(prefix, op, result_type, enabler) \ template < \ class Derived1, class V1, class TC1, class Reference1, class Difference1 \ , class Derived2, class V2, class TC2, class Reference2, class Difference2 \ > \ prefix typename mpl::apply2<result_type,Derived1,Derived2>::type \ operator op( \ iterator_facade<Derived1, V1, TC1, Reference1, Difference1> const& lhs \ , iterator_facade<Derived2, V2, TC2, Reference2, Difference2> const& rhs) # else # define BOOST_ITERATOR_FACADE_INTEROP_HEAD_IMPL(prefix, op, result_type, enabler) \ template < \ class Derived1, class V1, class TC1, class Reference1, class Difference1 \ , class Derived2, class V2, class TC2, class Reference2, class Difference2 \ > \ prefix typename enabler< \ Derived1, Derived2 \ , typename mpl::apply2<result_type,Derived1,Derived2>::type \ >::type \ operator op( \ iterator_facade<Derived1, V1, TC1, Reference1, Difference1> const& lhs \ , iterator_facade<Derived2, V2, TC2, Reference2, Difference2> const& rhs) # endif # define BOOST_ITERATOR_FACADE_INTEROP_HEAD(prefix, op, result_type) \ BOOST_ITERATOR_FACADE_INTEROP_HEAD_IMPL(prefix, op, result_type, boost::iterators::detail::enable_if_interoperable) # define BOOST_ITERATOR_FACADE_INTEROP_RANDOM_ACCESS_HEAD(prefix, op, result_type) \ BOOST_ITERATOR_FACADE_INTEROP_HEAD_IMPL(prefix, op, result_type, boost::iterators::detail::enable_if_interoperable_and_random_access_traversal) # define BOOST_ITERATOR_FACADE_PLUS_HEAD(prefix,args) \ template <class Derived, class V, class TC, class R, class D> \ prefix typename boost::iterators::enable_if< \ boost::iterators::detail::is_traversal_at_least< TC, boost::iterators::random_access_traversal_tag >, \ Derived \ >::type operator+ args // // Helper class for granting access to the iterator core interface. // // The simple core interface is used by iterator_facade. The core // interface of a user/library defined iterator type should not be made public // so that it does not clutter the public interface. Instead iterator_core_access // should be made friend so that iterator_facade can access the core // interface through iterator_core_access. // class iterator_core_access { # if defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS) // Tasteless as this may seem, making all members public allows member templates // to work in the absence of member template friends. public: # else template <class I, class V, class TC, class R, class D> friend class iterator_facade; template <class I, class V, class TC, class R, class D, bool IsBidirectionalTraversal, bool IsRandomAccessTraversal> friend class detail::iterator_facade_base; # define BOOST_ITERATOR_FACADE_RELATION(op) \ BOOST_ITERATOR_FACADE_INTEROP_HEAD(friend,op, boost::iterators::detail::always_bool2); BOOST_ITERATOR_FACADE_RELATION(==) BOOST_ITERATOR_FACADE_RELATION(!=) # undef BOOST_ITERATOR_FACADE_RELATION # define BOOST_ITERATOR_FACADE_RANDOM_ACCESS_RELATION(op) \ BOOST_ITERATOR_FACADE_INTEROP_RANDOM_ACCESS_HEAD(friend,op, boost::iterators::detail::always_bool2); BOOST_ITERATOR_FACADE_RANDOM_ACCESS_RELATION(<) BOOST_ITERATOR_FACADE_RANDOM_ACCESS_RELATION(>) BOOST_ITERATOR_FACADE_RANDOM_ACCESS_RELATION(<=) BOOST_ITERATOR_FACADE_RANDOM_ACCESS_RELATION(>=) # undef BOOST_ITERATOR_FACADE_RANDOM_ACCESS_RELATION BOOST_ITERATOR_FACADE_INTEROP_RANDOM_ACCESS_HEAD( friend, -, boost::iterators::detail::choose_difference_type) ; BOOST_ITERATOR_FACADE_PLUS_HEAD( friend inline , (iterator_facade<Derived, V, TC, R, D> const& , typename Derived::difference_type) ) ; BOOST_ITERATOR_FACADE_PLUS_HEAD( friend inline , (typename Derived::difference_type , iterator_facade<Derived, V, TC, R, D> const&) ) ; # endif template <class Facade> static typename Facade::reference dereference(Facade const& f) { return f.dereference(); } template <class Facade> static void increment(Facade& f) { f.increment(); } template <class Facade> static void decrement(Facade& f) { f.decrement(); } template <class Facade1, class Facade2> static bool equal(Facade1 const& f1, Facade2 const& f2, mpl::true_) { return f1.equal(f2); } template <class Facade1, class Facade2> static bool equal(Facade1 const& f1, Facade2 const& f2, mpl::false_) { return f2.equal(f1); } template <class Facade> static void advance(Facade& f, typename Facade::difference_type n) { f.advance(n); } template <class Facade1, class Facade2> static typename Facade1::difference_type distance_from( Facade1 const& f1, Facade2 const& f2, mpl::true_) { return -f1.distance_to(f2); } template <class Facade1, class Facade2> static typename Facade2::difference_type distance_from( Facade1 const& f1, Facade2 const& f2, mpl::false_) { return f2.distance_to(f1); } // // Curiously Recurring Template interface. // template <class I, class V, class TC, class R, class D> static I& derived(iterator_facade<I,V,TC,R,D>& facade) { return *static_cast<I *>(&facade); } template <class I, class V, class TC, class R, class D> static I const& derived(iterator_facade<I,V,TC,R,D> const& facade) { return *static_cast<I const *>(&facade); } // objects of this class are useless BOOST_DELETED_FUNCTION(iterator_core_access()) }; namespace detail { // Implementation for forward traversal iterators template < class Derived , class Value , class CategoryOrTraversal , class Reference , class Difference > class iterator_facade_base< Derived, Value, CategoryOrTraversal, Reference, Difference, false, false > # ifdef BOOST_ITERATOR_FACADE_NEEDS_ITERATOR_BASE : public boost::iterators::detail::iterator_facade_types< Value, CategoryOrTraversal, Reference, Difference >::base # undef BOOST_ITERATOR_FACADE_NEEDS_ITERATOR_BASE # endif { private: typedef boost::iterators::detail::iterator_facade_types< Value, CategoryOrTraversal, Reference, Difference > associated_types; typedef boost::iterators::detail::operator_arrow_dispatch< Reference , typename associated_types::pointer > operator_arrow_dispatch_; public: typedef typename associated_types::value_type value_type; typedef Reference reference; typedef Difference difference_type; typedef typename operator_arrow_dispatch_::result_type pointer; typedef typename associated_types::iterator_category iterator_category; public: reference operator*() const { return iterator_core_access::dereference(this->derived()); } pointer operator->() const { return operator_arrow_dispatch_::apply(*this->derived()); } Derived& operator++() { iterator_core_access::increment(this->derived()); return this->derived(); } protected: // // Curiously Recurring Template interface. // Derived& derived() { return *static_cast<Derived *>(this); } Derived const& derived() const { return *static_cast<Derived const *>(this); } }; // Implementation for bidirectional traversal iterators template < class Derived , class Value , class CategoryOrTraversal , class Reference , class Difference > class iterator_facade_base< Derived, Value, CategoryOrTraversal, Reference, Difference, true, false > : public iterator_facade_base< Derived, Value, CategoryOrTraversal, Reference, Difference, false, false > { public: Derived& operator--() { iterator_core_access::decrement(this->derived()); return this->derived(); } Derived operator--(int) { Derived tmp(this->derived()); --*this; return tmp; } }; // Implementation for random access traversal iterators template < class Derived , class Value , class CategoryOrTraversal , class Reference , class Difference > class iterator_facade_base< Derived, Value, CategoryOrTraversal, Reference, Difference, true, true > : public iterator_facade_base< Derived, Value, CategoryOrTraversal, Reference, Difference, true, false > { private: typedef iterator_facade_base< Derived, Value, CategoryOrTraversal, Reference, Difference, true, false > base_type; public: typedef typename base_type::reference reference; typedef typename base_type::difference_type difference_type; public: typename boost::iterators::detail::operator_brackets_result<Derived, Value, reference>::type operator[](difference_type n) const { typedef boost::iterators::detail::use_operator_brackets_proxy<Value, Reference> use_proxy; return boost::iterators::detail::make_operator_brackets_result<Derived>( this->derived() + n , use_proxy() ); } Derived& operator+=(difference_type n) { iterator_core_access::advance(this->derived(), n); return this->derived(); } Derived& operator-=(difference_type n) { iterator_core_access::advance(this->derived(), -n); return this->derived(); } Derived operator-(difference_type x) const { Derived result(this->derived()); return result -= x; } }; } // namespace detail // // iterator_facade - use as a public base class for defining new // standard-conforming iterators. // template < class Derived // The derived iterator type being constructed , class Value , class CategoryOrTraversal , class Reference = Value& , class Difference = std::ptrdiff_t > class iterator_facade : public detail::iterator_facade_base< Derived, Value, CategoryOrTraversal, Reference, Difference, detail::is_traversal_at_least< CategoryOrTraversal, bidirectional_traversal_tag >::value, detail::is_traversal_at_least< CategoryOrTraversal, random_access_traversal_tag >::value > { protected: // For use by derived classes typedef iterator_facade<Derived,Value,CategoryOrTraversal,Reference,Difference> iterator_facade_; }; template <class I, class V, class TC, class R, class D> inline typename boost::iterators::detail::postfix_increment_result<I,V,R,TC>::type operator++( iterator_facade<I,V,TC,R,D>& i , int ) { typename boost::iterators::detail::postfix_increment_result<I,V,R,TC>::type tmp(*static_cast<I *>(&i)); ++i; return tmp; } // // Comparison operator implementation. The library supplied operators // enables the user to provide fully interoperable constant/mutable // iterator types. I.e. the library provides all operators // for all mutable/constant iterator combinations. // // Note though that this kind of interoperability for constant/mutable // iterators is not required by the standard for container iterators. // All the standard asks for is a conversion mutable -> constant. // Most standard library implementations nowadays provide fully interoperable // iterator implementations, but there are still heavily used implementations // that do not provide them. (Actually it's even worse, they do not provide // them for only a few iterators.) // // ?? Maybe a BOOST_ITERATOR_NO_FULL_INTEROPERABILITY macro should // enable the user to turn off mixed type operators // // The library takes care to provide only the right operator overloads. // I.e. // // bool operator==(Iterator, Iterator); // bool operator==(ConstIterator, Iterator); // bool operator==(Iterator, ConstIterator); // bool operator==(ConstIterator, ConstIterator); // // ... // // In order to do so it uses c++ idioms that are not yet widely supported // by current compiler releases. The library is designed to degrade gracefully // in the face of compiler deficiencies. In general compiler // deficiencies result in less strict error checking and more obscure // error messages, functionality is not affected. // // For full operation compiler support for "Substitution Failure Is Not An Error" // (aka. enable_if) and boost::is_convertible is required. // // The following problems occur if support is lacking. // // Pseudo code // // --------------- // AdaptorA<Iterator1> a1; // AdaptorA<Iterator2> a2; // // // This will result in a no such overload error in full operation // // If enable_if or is_convertible is not supported // // The instantiation will fail with an error hopefully indicating that // // there is no operator== for Iterator1, Iterator2 // // The same will happen if no enable_if is used to remove // // false overloads from the templated conversion constructor // // of AdaptorA. // // a1 == a2; // ---------------- // // AdaptorA<Iterator> a; // AdaptorB<Iterator> b; // // // This will result in a no such overload error in full operation // // If enable_if is not supported the static assert used // // in the operator implementation will fail. // // This will accidently work if is_convertible is not supported. // // a == b; // ---------------- // # ifdef BOOST_NO_ONE_WAY_ITERATOR_INTEROP # define BOOST_ITERATOR_CONVERTIBLE(a,b) mpl::true_() # else # define BOOST_ITERATOR_CONVERTIBLE(a,b) is_convertible<a,b>() # endif # define BOOST_ITERATOR_FACADE_INTEROP(op, result_type, return_prefix, base_op) \ BOOST_ITERATOR_FACADE_INTEROP_HEAD(inline, op, result_type) \ { \ /* For those compilers that do not support enable_if */ \ BOOST_STATIC_ASSERT(( \ is_interoperable< Derived1, Derived2 >::value \ )); \ return_prefix iterator_core_access::base_op( \ *static_cast<Derived1 const*>(&lhs) \ , *static_cast<Derived2 const*>(&rhs) \ , BOOST_ITERATOR_CONVERTIBLE(Derived2,Derived1) \ ); \ } # define BOOST_ITERATOR_FACADE_RELATION(op, return_prefix, base_op) \ BOOST_ITERATOR_FACADE_INTEROP( \ op \ , boost::iterators::detail::always_bool2 \ , return_prefix \ , base_op \ ) BOOST_ITERATOR_FACADE_RELATION(==, return, equal) BOOST_ITERATOR_FACADE_RELATION(!=, return !, equal) # undef BOOST_ITERATOR_FACADE_RELATION # define BOOST_ITERATOR_FACADE_INTEROP_RANDOM_ACCESS(op, result_type, return_prefix, base_op) \ BOOST_ITERATOR_FACADE_INTEROP_RANDOM_ACCESS_HEAD(inline, op, result_type) \ { \ /* For those compilers that do not support enable_if */ \ BOOST_STATIC_ASSERT(( \ is_interoperable< Derived1, Derived2 >::value && \ boost::iterators::detail::is_traversal_at_least< typename iterator_category< Derived1 >::type, random_access_traversal_tag >::value && \ boost::iterators::detail::is_traversal_at_least< typename iterator_category< Derived2 >::type, random_access_traversal_tag >::value \ )); \ return_prefix iterator_core_access::base_op( \ *static_cast<Derived1 const*>(&lhs) \ , *static_cast<Derived2 const*>(&rhs) \ , BOOST_ITERATOR_CONVERTIBLE(Derived2,Derived1) \ ); \ } # define BOOST_ITERATOR_FACADE_RANDOM_ACCESS_RELATION(op, return_prefix, base_op) \ BOOST_ITERATOR_FACADE_INTEROP_RANDOM_ACCESS( \ op \ , boost::iterators::detail::always_bool2 \ , return_prefix \ , base_op \ ) BOOST_ITERATOR_FACADE_RANDOM_ACCESS_RELATION(<, return 0 >, distance_from) BOOST_ITERATOR_FACADE_RANDOM_ACCESS_RELATION(>, return 0 <, distance_from) BOOST_ITERATOR_FACADE_RANDOM_ACCESS_RELATION(<=, return 0 >=, distance_from) BOOST_ITERATOR_FACADE_RANDOM_ACCESS_RELATION(>=, return 0 <=, distance_from) # undef BOOST_ITERATOR_FACADE_RANDOM_ACCESS_RELATION // operator- requires an additional part in the static assertion BOOST_ITERATOR_FACADE_INTEROP_RANDOM_ACCESS( - , boost::iterators::detail::choose_difference_type , return , distance_from ) # undef BOOST_ITERATOR_FACADE_INTEROP # undef BOOST_ITERATOR_FACADE_INTEROP_RANDOM_ACCESS # define BOOST_ITERATOR_FACADE_PLUS(args) \ BOOST_ITERATOR_FACADE_PLUS_HEAD(inline, args) \ { \ Derived tmp(static_cast<Derived const&>(i)); \ return tmp += n; \ } BOOST_ITERATOR_FACADE_PLUS(( iterator_facade<Derived, V, TC, R, D> const& i , typename Derived::difference_type n )) BOOST_ITERATOR_FACADE_PLUS(( typename Derived::difference_type n , iterator_facade<Derived, V, TC, R, D> const& i )) # undef BOOST_ITERATOR_FACADE_PLUS # undef BOOST_ITERATOR_FACADE_PLUS_HEAD # undef BOOST_ITERATOR_FACADE_INTEROP_HEAD # undef BOOST_ITERATOR_FACADE_INTEROP_RANDOM_ACCESS_HEAD # undef BOOST_ITERATOR_FACADE_INTEROP_HEAD_IMPL } // namespace iterators using iterators::iterator_core_access; using iterators::iterator_facade; } // namespace boost #include <boost/iterator/detail/config_undef.hpp> #endif // BOOST_ITERATOR_FACADE_23022003THW_HPP
b17b273f78dd17badd4e566e40821dd89a09aa28
2672b41f905c0561c816cbb969d1c57752863420
/UVA/UVA 10653.cpp
4de3f00b2bc59ca419efad1bed29091185c35d66
[]
no_license
MohamedFathi45/Competitive-programming
a9a6b8b3e8be5924ef4774b90b81a5149cfc0332
3ed5bdd0c698c5c4273455828f6d74ff13374902
refs/heads/master
2021-01-25T14:46:57.008806
2020-12-22T03:35:54
2020-12-22T03:35:54
123,729,376
0
0
null
null
null
null
UTF-8
C++
false
false
2,466
cpp
#include<iostream> #include<algorithm> #include<string.h> #include<string> #include<vector> #include<math.h> #include<set> #include<map> #include<iomanip> #include<queue> #include<deque> #include<bitset> #include<stack> #include<stdlib.h> #include<list> #include<fstream> #define Flash ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); typedef long long ll; using namespace std; double EPS = 1e-7; long long gcd( long long a , long long b ){ if( b == 0 ) return a; return gcd(b,a%b); } int lcm(int a , int b){ if( b > a ) swap(a, b); return (a*b)/gcd(a , b); } int power( int b , int p ){ if( p == 0 ) return 1; int sq = power(b, p/2); sq = sq*sq; if( p%2 == 1) sq*=b; return sq; } const int MAX = 2e5; int xDir[]={-1, 0,1,0}; int yDir[]={0,-1,0 ,1}; int dcomp( double a , double b ){ if( fabs(a - b ) <= EPS ) return 0; return ((a > b) ? 1 : -1); } int n,m; vector<vector<int> >adj; vector<vector<bool> >vis; void BFS( pair<int,int>s , pair<int,int>e ){ queue<pair<int , int> > q; vector<vector<int> >dist(n , vector<int>(m) ); vis[s.first][s.second] = 1; dist[s.first][s.second] = 0; q.push(s); int sz=1,dep=1; bool ok=true; for( ;ok && !q.empty() ; sz=q.size(),dep++ ){ while( ok && sz--){ pair<int,int>cur = q.front(); q.pop(); for( int i=0; i<4 ; i++ ){ int tox=cur.first+xDir[i]; int toy=cur.second+yDir[i]; if( (tox>=0 && tox<n && toy>=0 && toy<m ) && (!vis[tox][toy]) && adj[tox][toy] != 1 ) { q.push({tox,toy}) , dist[tox][toy]=dep , vis[tox][toy]=1; if(e.first == cur.first && e.second == cur.second){ ok=false; break; } } } } } cout<<dist[e.first][e.second]<<'\n'; } int main(){ Flash while(cin>>n>>m&&n&&m){ adj = vector<vector<int> >(n , vector<int>(m)); vis = vector<vector<bool> >(n , vector<bool>(m)); int p; cin>>p; while(p--){ int row; cin>>row; int q; cin>>q; for( int i = 0 ; i < q ; i ++ ){ int col; cin>>col; adj[row][col] = 1; } } pair<int , int> s,e; cin>>s.first>>s.second>>e.first>>e.second; BFS(s,e); } return 0; }
702ec1b85386407777c0031b2ec8c517be131152
eb8e2283f21c318a0440f90445ea09d09d922ff8
/EventLoop.h
ef22031641fab6f59d37621355f518f7f716f5ba
[]
no_license
donghe0313/mymuduo
4690ed348a6d826838cfa6f56d35dd4465ee3c20
82eed7af0ccde98315d818b943544ce7e673f050
refs/heads/main
2023-03-11T15:58:32.062106
2021-02-22T12:20:45
2021-02-22T12:20:45
339,649,332
0
0
null
null
null
null
UTF-8
C++
false
false
2,098
h
#pragma once #include <functional> #include <vector> #include <atomic> #include <memory> #include <mutex> #include "noncopyable.h" #include "Timestamp.h" #include "CurrentThread.h" class Channel; class Poller; // 时间循环类 主要包含了两个大模块 Channel Poller(epoll的抽象) class EventLoop : noncopyable { public: using Functor = std::function<void()>; EventLoop(); ~EventLoop(); // 开启事件循环 void loop(); // 退出事件循环 void quit(); Timestamp pollReturnTime() const { return pollReturnTime_; } // 在当前loop中执行cb void runInLoop(Functor cb); // 把cb放入队列中,唤醒loop所在的线程,执行cb void queueInLoop(Functor cb); // 用来唤醒loop所在的线程的 void wakeup(); // EventLoop的方法 =》 Poller的方法 void updateChannel(Channel *channel); void removeChannel(Channel *channel); bool hasChannel(Channel *channel); // 判断EventLoop对象是否在自己的线程里面 bool isInLoopThread() const { return threadId_ == CurrentThread::tid(); } private: void handleRead(); // wake up void doPendingFunctors(); // 执行回调 using ChannelList = std::vector<Channel*>; std::atomic_bool looping_; // 原子操作,通过CAS实现的 std::atomic_bool quit_; // 标识退出loop循环 const pid_t threadId_; // 记录当前loop所在线程的id Timestamp pollReturnTime_; // poller返回发生事件的channels的时间点 std::unique_ptr<Poller> poller_; int wakeupFd_; // 主要作用,当mainLoop获取一个新用户的channel,通过轮询算法选择一个subloop,通过该成员唤醒subloop处理channel std::unique_ptr<Channel> wakeupChannel_; ChannelList activeChannels_; std::atomic_bool callingPendingFunctors_; // 标识当前loop是否有需要执行的回调操作 std::vector<Functor> pendingFunctors_; // 存储loop需要执行的所有的回调操作 std::mutex mutex_; // 互斥锁,用来保护上面vector容器的线程安全操作 };
6b12a9cedaf6acb60c05ffc5447a8aeb86ac13a3
2e2de88745dd6c7cf58b6dfd68ae8d8200ed387f
/Mewtle/src/Mewtle/UI/Label.cpp
c02f8d53c23f8cf16c7a3da7b594d678bc9dee54
[ "Apache-2.0" ]
permissive
TinSlam/Mewtle
2b233a519fc216b06fe47106d2029a63c103bfaf
3d178c4523a6a70fd362f781b7a92847f6bac559
refs/heads/master
2020-06-18T03:36:46.238609
2019-08-10T10:46:38
2019-08-10T10:46:38
196,152,023
0
0
null
null
null
null
UTF-8
C++
false
false
935
cpp
#include <PrecompiledHeaders.h> #include "Label.h" #include "Mewtle/Core/MyGLRenderer.h" #include "Mewtle/ResourceManager/Model/ModelPremade.h" namespace Mewtle{ Label::Label(int id, Texture* texture, float x, float y, float width, float height, float rot) : Entity(id, Model3D::getModel(ModelPremade::MODEL_SQUARE), texture, x, y, 0, 0, 0, rot, width, height, 0){ } void Label::render() { render(1); } void Label::render(float alpha) { MyGLRenderer::drawLabel(this, alpha); } bool Label::mouseOver(double x, double y){ x -= this->x + this->width / 2; y -= this->y + this->height / 2; double tempX = x * cos(rotZ) - y * sin(rotZ); double tempY = x * sin(rotZ) + y * cos(rotZ); tempX += this->x + this->width / 2; tempY += this->y + this->height / 2; if(tempX >= this->x && tempX <= this->x + this->width && tempY >= this->y && tempY <= this->y + this->height) return true; return false; } }
ce7013aed57a3ed4314e2b7338a5310106e9bf12
7f0fecfcdadd67036443a90034d34a0b0318a857
/sparta/sparta/statistics/dispatch/archives/ReportStatisticsArchive.hpp
5ce13efa4433fcc496a6a61fa6b60d7a1a6b3382
[ "MIT" ]
permissive
timsnyder/map
e01b855288fc204d12e32198b2c8bd0f13c4cdf7
aa4b0d7a1260a8051228707fd047431e1e52e01e
refs/heads/master
2020-12-21T19:34:48.716857
2020-02-17T17:29:29
2020-02-17T17:29:29
236,536,756
0
0
MIT
2020-01-27T16:31:24
2020-01-27T16:31:23
null
UTF-8
C++
false
false
6,500
hpp
// <ReportStatisticsArchive> -*- C++ -*- #ifndef __SPARTA_REPORT_STATISTICS_ARCHIVE_H__ #define __SPARTA_REPORT_STATISTICS_ARCHIVE_H__ #include "sparta/statistics/dispatch/archives/ReportStatisticsAggregator.hpp" #include "sparta/statistics/dispatch/archives/ArchiveDispatcher.hpp" #include "sparta/statistics/dispatch/archives/ArchiveController.hpp" #include "sparta/statistics/dispatch/archives/BinaryIArchive.hpp" #include "sparta/statistics/dispatch/archives/BinaryOArchive.hpp" namespace sparta { namespace statistics { class RootArchiveNode; /*! * \brief This class coordinates live SPARTA simulations (source) * with binary output archives (sink). */ class ReportStatisticsArchive { public: ReportStatisticsArchive(const std::string & db_directory, const std::string & db_subdirectory, const Report & report) { dispatcher_.reset(new ReportStatisticsDispatcher( db_directory, db_subdirectory, report)); } //Metadata will be forwarded along to the underlying RootArchiveNode. //You can get this root node object by calling getRoot() void setArchiveMetadata(const app::NamedExtensions & metadata) { dispatcher_->setArchiveMetadata(metadata); } //One-time initialization of the output binary archive void initialize() { dispatcher_->configureBinaryArchive(this); } //Access the underlying root node for our archive tree std::shared_ptr<RootArchiveNode> getRoot() const { return dispatcher_->getRoot(); } //Send out all of the report's StatisticInstance current //values to the binary sink void dispatchAll() { dispatcher_->dispatch(); dirty_ = true; } //Synchronize the data source with the binary sink. Returns //true if the flush was made, and false if the archive was //already in sync. Returning false is NOT a sign of an error. bool flushAll() { if (!dirty_) { return false; } dispatcher_->flush(); dirty_ = false; return true; } //Make a deep copy of the archive, sending it to the //given directory. This does not invalidate the current //ongoing/live archive. This call can safely be made during //simulation. void saveTo(const std::string & db_directory) { dispatcher_->flush(); const auto & sinks = dispatcher_->getSinks(); for (const auto & sink : sinks) { copyArchiveToDirectory_(*sink, db_directory); } } private: /*! * \brief Specialized dispatcher which sends data to a binary * output file. */ class ReportStatisticsDispatcher : public ArchiveDispatcher { public: ReportStatisticsDispatcher(const std::string & db_directory, const std::string & db_subdirectory, const Report & report) : db_directory_(db_directory), db_subdirectory_(db_subdirectory) { std::unique_ptr<ReportStatisticsAggregator> source( new ReportStatisticsAggregator(report)); source->initialize(); root_ = source->getRoot(); setStatisticsSource(std::move(source)); } void setArchiveMetadata(const app::NamedExtensions & metadata) { root_->setMetadata(metadata); //All archives should have a "triggers" property, even //if there were no triggers used to generate the report. //This is to support Python, so we can give a user friendly //message like this: // // >>> foo.bar.triggers.showInfo() // "No triggers have been set" if (!root_->tryGetMetadataValue<app::TriggerKeyValues>("trigger")) { app::TriggerKeyValues no_triggers; root_->setMetadataValue("trigger", no_triggers); } } void configureBinaryArchive(ReportStatisticsArchive * source) { //Give the root archive node a controller it can use to //save the archive to another directory, synchronize the //data source / data sink, etc. std::shared_ptr<ArchiveController> controller( new LiveSimulationArchiveController(source)); root_->setArchiveController(controller); root_->initialize(); //Append a time stamp to the database directory we were given. //This is a static string which will be the same for all archive //sinks in the tempdir for this simulation. const std::string & time_stamp = ArchiveDispatcher::getSimulationTimeStamp_(); std::unique_ptr<BinaryOArchive> sink(new BinaryOArchive); sink->setPath(db_directory_ + "/" + time_stamp); sink->setSubpath(db_subdirectory_); sink->setRoot(root_); sink->initialize(); addStatisticsSink(std::move(sink)); } std::shared_ptr<RootArchiveNode> getRoot() { return root_; } private: const std::string db_directory_; const std::string db_subdirectory_; std::shared_ptr<RootArchiveNode> root_; }; //Copy all archive files that belong to an ongoing data sink, //and put the copies in the given directory. This does not //invalidate the ongoing sink, or change any internal state //in any way. void copyArchiveToDirectory_(const ArchiveSink & original_sink, const std::string & destination_dir) const { BinaryIArchive binary_source; binary_source.setPath(original_sink.getPath()); binary_source.setSubpath(original_sink.getSubpath()); binary_source.initialize(); BinaryOArchive copied_sink; copied_sink.setPath(destination_dir); copied_sink.setSubpath(original_sink.getSubpath()); copied_sink.initialize(); while (true) { const std::vector<double> & binary_data = binary_source.readFromSource(); if (binary_data.empty()) { break; } copied_sink.sendToSink(binary_data); } copied_sink.copyMetadataFrom(&original_sink); } std::unique_ptr<ReportStatisticsDispatcher> dispatcher_; bool dirty_ = true; }; } // namespace statistics } // namespace sparta #endif
f81ca9b34557e432d085601edee24e7b2ebcdcae
30ad231c47db74e4cce9d11024d0c187d1a91175
/day12/main.cpp
47a655364c825745a47827f7d2d42336327cf292
[ "Unlicense" ]
permissive
wuggy-ianw/AoC2017
afa36502238232956299b4baa6b5bd149667591f
138c66bdd407e76f6ad71c9d68df50e0afa2251a
refs/heads/master
2021-09-01T18:06:13.445410
2017-12-28T06:15:40
2017-12-28T06:15:40
112,793,144
0
0
null
null
null
null
UTF-8
C++
false
false
370
cpp
// // Created by wuggy on 21/12/2017. // #include "day12.h" #include <iostream> #include <fstream> #include <vector> int main(void) { std::ifstream ifs("input.txt"); std::map<int, Day12::program> programs = Day12::parse_input(ifs); std::cout << Day12::solve_part1(programs) << std::endl; std::cout << Day12::solve_part2(programs) << std::endl; return 0; }
635b03d522e7451a01b3458280494e15ffd23d9d
2ed5c000b9de09bdfa54936ab523229501ba64bc
/src/reference/leader_reference.cpp
11451e600a168be33b3c277518e2a306d4e42a1d
[]
no_license
mbyase/swarm_robot_formation
6f088d27dc912fcc9b79802e71509e35f1403ed6
0dc35278ee7b5bf0336eefbdd763c15c72fce97b
refs/heads/master
2020-04-27T21:45:00.552272
2018-01-02T09:31:39
2018-01-02T09:31:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,316
cpp
#include "formation/reference/leader_reference.h" #include <stdexcept> #include <math.h> #include <sstream> using namespace formation; LeaderRerence::LeaderRerence(tf::TransformListener* tf, Formation pF, double pDS) { tfListener_ = tf; f = pF; desiredSpaceing = pDS; mNameSpace_ = nh_.getNamespace(); } bool LeaderRerence::getRobotPose(tf::Stamped<tf::Pose>& global_pose, int leader_id) const { std::string global_frame = "/map"; std::string leader_base_frame; std::stringstream leader_id_stream; leader_id_stream<<leader_id; leader_base_frame = "/robot" + leader_id_stream.str() + "_base_footprint"; global_pose.setIdentity(); tf::Stamped < tf::Pose > robot_pose; robot_pose.setIdentity(); robot_pose.frame_id_ = leader_base_frame; robot_pose.stamp_ = ros::Time(); ros::Time current_time = ros::Time::now(); // save time for checking tf delay later // get the global pose of the robot try { // ROS_INFO(" getting robot pose"); tfListener_->transformPose(global_frame, robot_pose, global_pose); } catch (tf::LookupException& ex) { ROS_ERROR_THROTTLE(1.0, "No Transform available Error looking up robot pose: %s\n", ex.what()); return false; } catch (tf::ConnectivityException& ex) { ROS_ERROR_THROTTLE(1.0, "Connectivity Error looking up robot pose: %s\n", ex.what()); return false; } catch (tf::ExtrapolationException& ex) { ROS_ERROR_THROTTLE(1.0, "Extrapolation Error looking up robot pose: %s\n", ex.what()); return false; } catch (tf2::InvalidArgumentException& ex) { ROS_ERROR_THROTTLE(1.0, "InvalidArgumentException: %s\n", ex.what()); return false; } double transform_tolerance = 0.1; // check global_pose timeout if (current_time.toSec() - global_pose.stamp_.toSec() > transform_tolerance) { ROS_WARN_THROTTLE(1.0, "Costmap2DROS transform timeout. Current time: %.4f, global_pose stamp: %.4f, tolerance: %.4f", current_time.toSec(), global_pose.stamp_.toSec(), transform_tolerance); return false; } // ROS_INFO("global_pose.frame_id_: %s", global_pose.frame_id_.c_str()); return true; } bool LeaderRerence::tramformToOdom(tf::Stamped<tf::Pose>& orign_pose, geometry_msgs::PoseStamped& output_pose) const { std::string output_frame = mNameSpace_.substr(1, mNameSpace_.length() - 1) + "_odom"; tf::Stamped<tf::Pose> output_pose_odom; output_pose_odom.setIdentity(); ros::Time current_time = ros::Time::now(); // save time for checking tf delay later // get the global pose of the robot try { // ROS_INFO(" getting robot pose"); tfListener_->transformPose(output_frame, orign_pose, output_pose_odom); } catch (tf::LookupException& ex) { ROS_ERROR_THROTTLE(1.0, "No Transform available Error looking up robot pose: %s\n", ex.what()); return false; } catch (tf::ConnectivityException& ex) { ROS_ERROR_THROTTLE(1.0, "Connectivity Error looking up robot pose: %s\n", ex.what()); return false; } catch (tf::ExtrapolationException& ex) { ROS_ERROR_THROTTLE(1.0, "Extrapolation Error looking up robot pose: %s\n", ex.what()); return false; } catch (tf2::InvalidArgumentException& ex) { ROS_ERROR_THROTTLE(1.0, "InvalidArgumentException: %s\n", ex.what()); return false; } double transform_tolerance = 0.1; // check global_pose timeout if (current_time.toSec() - output_pose_odom.stamp_.toSec() > transform_tolerance) { ROS_WARN_THROTTLE(1.0, "Costmap2DROS transform timeout. Current time: %.4f, global_pose stamp: %.4f, tolerance: %.4f", current_time.toSec(), output_pose_odom.stamp_.toSec(), transform_tolerance); return false; } tf::poseStampedTFToMsg(output_pose_odom, output_pose); return true; } bool LeaderRerence::transformToMap(geometry_msgs::PoseStamped& globalPlanPose, tf::Stamped<tf::Pose>& output_pose_map) { tf::Stamped<tf::Pose> orign_pose; tf::poseStampedMsgToTF(globalPlanPose, orign_pose); std::string output_frame = "/map"; output_pose_map.setIdentity(); // Identity is very importance for using to transform the orientation.Without it, we can not transform correctly. Remenber this!!! // orign_pose.setIdentity(); // Here, But we can't set orign_pose.setIdentity again! output_pose_map.stamp_ = ros::Time(); //Reset the time, so it can transform even this stamp is outtime. orign_pose.stamp_ = ros::Time(); output_pose_map.frame_id_ = output_frame; try { tfListener_->transformPose(output_frame, orign_pose, output_pose_map); } catch (tf::LookupException& ex) { ROS_ERROR_THROTTLE(1.0, "No Transform available Error looking up robot pose: %s\n", ex.what()); return false; } catch (tf::ConnectivityException& ex) { ROS_ERROR_THROTTLE(1.0, "Connectivity Error looking up robot pose: %s\n", ex.what()); return false; } catch (tf::ExtrapolationException& ex) { ROS_ERROR_THROTTLE(1.0, "Extrapolation Error looking up robot pose: %s\n", ex.what()); return false; } catch (tf2::InvalidArgumentException& ex) { ROS_ERROR_THROTTLE(1.0, "InvalidArgumentException: %s\n", ex.what()); return false; } // ROS_INFO("output_pose_map x:%f y:%f z:%f, x:%f y:%f z:%f w:%f", output_pose_map.getOrigin().getX(), output_pose_map.getOrigin().getY(), // output_pose_map.getOrigin().getZ(), output_pose_map.getRotation().getX(), output_pose_map.getRotation().getY(), output_pose_map.getRotation().getZ(), // output_pose_map.getRotation().getW()); return true; } bool LeaderRerence::getDesiredPosition(geometry_msgs::PoseStamped& outputPosition, int position, int leader_id, geometry_msgs::PoseStamped globalPlanPose) { // std::string mNameSpace = mNameSpace_.substr(2, mNameSpace_.length() - 2); tf::Stamped<tf::Pose> leaderPos; tf::Stamped<tf::Pose> poseToMap; transformToMap(globalPlanPose, poseToMap); double yawOfPath = tf::getYaw(poseToMap.getRotation()); ROS_INFO("yawOfPath_map: %f", yawOfPath); // can't get the pose os leader if(!getRobotPose(leaderPos, leader_id)) { ROS_WARN("Can not get DesiredPosition!"); return false; } ROS_INFO("leaderPos x:%f y:%f z:%f, x:%f y:%f z:%f w:%f", leaderPos.getOrigin().getX(), leaderPos.getOrigin().getY(), leaderPos.getOrigin().getZ(), leaderPos.getRotation().getX(), leaderPos.getRotation().getY(), leaderPos.getRotation().getZ(), leaderPos.getRotation().getW()); tf::Stamped<tf::Pose> desiredPosition(leaderPos); desiredPosition.setRotation(poseToMap.getRotation()); desiredPosition.getOrigin().setY(leaderPos.getOrigin().getY() + position * desiredSpaceing * sin(yawOfPath - M_PI_2)); desiredPosition.getOrigin().setX(leaderPos.getOrigin().getX() + position * desiredSpaceing * cos(yawOfPath - M_PI_2)); ROS_INFO("desiredPosition x:%f y:%f z:%f, x:%f y:%f z:%f w:%f", desiredPosition.getOrigin().getX(), desiredPosition.getOrigin().getY(), desiredPosition.getOrigin().getZ(), desiredPosition.getRotation().getX(), desiredPosition.getRotation().getY(), desiredPosition.getRotation().getZ(), desiredPosition.getRotation().getW()); tramformToOdom(desiredPosition, outputPosition); return true; }