blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
148299db2d4de6f64ec8440e6270b9623f7f362b
|
70f3bff2cbceb478dc09c8260482472e6f2b7170
|
/include/Material.h
|
ecff806a104f06185786b0482aa9bc99d536aaac
|
[] |
no_license
|
irpainel-zz/assignment3
|
2b0d3d1e0249c55599b7f653ccba97e11edf4f58
|
5dce885faebc4c7760ccac029dbd54a24a7c1c2f
|
refs/heads/master
| 2021-09-08T20:32:41.559459
| 2014-10-01T05:16:48
| 2014-10-01T05:16:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 395
|
h
|
Material.h
|
/*
* Material.h
*
* Created on: Sep 15, 2014
* Author: Iury Roger Painelli
*/
#ifndef MATERIAL_H_
#define MATERIAL_H_
#include "glm/vec4.hpp"
class Material {
public:
Material();
virtual ~Material();
glm::vec4 emission; // Ecm
glm::vec4 ambient; // Acm
glm::vec4 diffuse; // Dcm
glm::vec4 specular; // Scm
float shininess; // Srm
};
#endif /* MATERIAL_H_ */
|
94443525fd24c2253c3dea74404d3e9b61f9b910
|
d8e7a11322f6d1b514c85b0c713bacca8f743ff5
|
/7.6.00.37/V76_00_37/MaxDB_ORG/sys/src/SAPDB/Interfaces/Runtime/IFR_SQLWarning.cpp
|
6bc589ad8b34aab62e19c103772757550fd58c07
|
[] |
no_license
|
zhaonaiy/MaxDB_GPL_Releases
|
a224f86c0edf76e935d8951d1dd32f5376c04153
|
15821507c20bd1cd251cf4e7c60610ac9cabc06d
|
refs/heads/master
| 2022-11-08T21:14:22.774394
| 2020-07-07T00:52:44
| 2020-07-07T00:52:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,695
|
cpp
|
IFR_SQLWarning.cpp
|
/*!
@file IFR_SQLWarning.cpp
@author D039759
@ingroup IFR_Common
@brief SQL Warnings
@see
\if EMIT_LICENCE
========== licence begin GPL
Copyright (c) 2001-2005 SAP AG
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
========== licence end
\endif
*/
#include "Interfaces/Runtime/IFR_SQLWarning.h"
IFR_BEGIN_NAMESPACE
//----------------------------------------------------------------------
IFR_SQLWarning::IFR_SQLWarning(IFR_SQLWarningCode warningcode)
:m_warningcode(warningcode),
m_nextwarning(0)
{}
//----------------------------------------------------------------------
IFR_SQLWarning::~IFR_SQLWarning()
{
}
//----------------------------------------------------------------------
void
IFR_SQLWarning::addWarning(IFR_SQLWarning* warning)
{
IFR_SQLWarning *p=this;
while(p->m_nextwarning) {
if(p==warning) {
return;
}
p=p->m_nextwarning;
}
p->m_nextwarning=warning;
}
IFR_END_NAMESPACE
|
7fa6dd2f1226fdab92831f1365d1c1922dd0803e
|
76c5e0e751e41873a871c31ad590d3e93d193982
|
/docaocuacay.cpp
|
053354237af1556c26f6c9d73dcde13d313120c2
|
[] |
no_license
|
quynhtrangn/CTDL-GT
|
f25a892523b294c0e419df2e7553436f6be3b6f1
|
af28b0c45063c45b9d6a401a1127414e00301929
|
refs/heads/master
| 2023-07-30T10:56:14.660274
| 2021-09-13T11:54:55
| 2021-09-13T11:54:55
| 405,948,437
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 750
|
cpp
|
docaocuacay.cpp
|
//#include<bits/stdc++.h>
//#include<queue>
//#include<vector>
//using namespace std;
//int main(){
// long long k,i,j,n,m,x,d,t;
// cin>>t;
// while(t--){
// cin>>n;
// d=0;
// long long s[n+1];
// s[1]=0;
// d=0;
// for (i=0;i<n-1;i++) {
// cin>>m>>k;
// s[k]=s[m]+1;
// if (s[k]>d) d=s[k];
// }
// cout<<d<<endl;
// }
// return 0;
//}
#include<bits/stdc++.h>
using namespace std;
long long n;
void run(){
cin>>n;
long long a[n+5];
long long dem=0;
a[1]=0;
for (int i=0;i<n-1;i++) {
long long u,v;
cin>>u>>v;
a[v]=a[u]+1;
if (a[v]>dem) dem=a[v];
}
cout<<dem;
}
int main(){
int T;
cin>>T;
while(T--){
run();
cout<<endl;
}
return 0;
}
|
d339a2f9b913bdc3dd89cdc1dca69d01313326ba
|
435959be994ec86ac1c09c972a52b8c2b0f9a5b8
|
/src/model_importer/FileUtils.h
|
a48134fafda5c00350365a9e859414116e0b8f0b
|
[] |
no_license
|
JRB-90/SoftwareRenderer
|
77c87cfac4afad925b52b0e3be2c98af17cf2063
|
c938f4b9a6a22b84ce4d5ff587732a85092d696c
|
refs/heads/main
| 2023-03-03T12:21:01.051349
| 2021-02-05T10:26:37
| 2021-02-05T10:26:37
| 316,537,644
| 0
| 0
| null | 2021-01-15T15:44:37
| 2020-11-27T15:30:30
|
C++
|
UTF-8
|
C++
| false
| false
| 216
|
h
|
FileUtils.h
|
#pragma once
#include <vector>
#include <string>
namespace softengine
{
class FileUtils
{
public:
FileUtils() = delete;
static std::vector<std::string> explode(
const std::string& s,
char c
);
};
}
|
9ecb02841426e0256488469abf8742b7ccd0a7af
|
3095cc4d7c149c67d56767abf52aa02d354aa0e6
|
/src/ds/Triple.h
|
5ba5ab0e9966be92e4908fb5fce844ecb5e9380f
|
[] |
no_license
|
t-s-moon/infltrait
|
b8e617698de206b8ccbc0362048bc51719f7b3c5
|
641423157b46f4d28025764eba680a2dd868201b
|
refs/heads/master
| 2021-01-01T16:55:14.555124
| 2012-04-01T16:15:22
| 2012-04-01T16:15:22
| 33,077,107
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,135
|
h
|
Triple.h
|
/**
* @file Triple.h
* @author Taesun Moon <tsmoon@w-central-232-178.public.utexas.edu>
* @date Sun Apr 12 18:11:51 2009
*
* @brief
*
*
*/
#ifndef __TRIPLE_H__
#define __TRIPLE_H__
#include <map>
#include <string>
#include <vector>
namespace infl {
template <typename Container = std::vector<double>,
typename StringT = std::string, typename T = size_t>
struct Triple {
Container* const vp;
StringT label;
T cluster_idx;
Triple(Container* _vp, StringT& _l, T _cl) :
vp(_vp), label(_l), cluster_idx(_cl) {}
typename Container::iterator begin() const {return vp->begin();}
typename Container::iterator end() const {return vp->end();}
typename Container::size_type size() const {return vp->size();}
bool operator<(const Triple& tr) const {
return vp < tr.vp;
}
};
typedef Triple<std::vector<double> > TRIPLEVD;
typedef Triple<std::vector<float> > TRIPLEVF;
typedef std::vector<TRIPLEVD> VTRIPLEVD;
typedef std::vector<TRIPLEVF> VTRIPLEVF;
typedef std::map<TRIPLEVD, size_t> MTRIPLEVD;
typedef std::map<TRIPLEVF, size_t> MTRIPLEVF;
}
#endif
|
2ce51908d6412eaf548ab7beb30aca0e475cc190
|
2298cf6c691925733b254368de09e1428c754fcf
|
/UserTools/MCParticleProperties/MCParticleProperties.cpp
|
ccbb4d9d5a593dac225963b546f6695b8ffb230c
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
ANNIEsoft/ToolAnalysis
|
a7d6ea18e22ba0770aa3dbb96654e871027cd945
|
0ba4a6ad1c1f7051579b1dea638f7e6fe8a58a30
|
refs/heads/Application
| 2023-08-16T18:18:13.419107
| 2023-07-25T21:12:45
| 2023-07-25T21:51:38
| 113,612,944
| 7
| 42
|
NOASSERTION
| 2023-09-13T07:01:16
| 2017-12-08T20:07:35
|
C++
|
UTF-8
|
C++
| false
| false
| 57,594
|
cpp
|
MCParticleProperties.cpp
|
/* vim:set noexpandtab tabstop=4 wrap */
#include "MCParticleProperties.h"
#include "MRDSubEventClass.hh" // a class for defining subevents
#include "MRDTrackClass.hh" // a class for defining MRD tracks - needed for cMRDTrack EnergyLoss TF1
#include "Position.h"
#include "TF1.h"
MCParticleProperties::MCParticleProperties():Tool(){}
bool MCParticleProperties::Initialise(std::string configfile, DataModel &data){
/////////////////// Usefull header ///////////////////////
if(configfile!="") m_variables.Initialise(configfile); //loading config file
//m_variables.Print();
m_data= &data; //assigning transient data pointer
/////////////////////////////////////////////////////////////////
m_variables.Get("verbosity",verbosity);
// Get the anniegeom
get_ok = m_data->Stores.at("ANNIEEvent")->Header->Get("AnnieGeometry",anniegeom);
if(not get_ok){
Log("MCParticleProperties Tool: Could not get the AnnieGeometry from ANNIEEvent!",v_error,verbosity);
return false;
}
fidcutradius = anniegeom->GetFiducialCutRadius()*100.; // convert to cm
fidcutz = anniegeom->GetFiducialCutZ()*100.;
fidcuty = anniegeom->GetFiducialCutY()*100.;
tank_radius = anniegeom->GetTankRadius()*100.;
tank_start = (anniegeom->GetTankCentre().Z()-tank_radius)*100.;
tank_yoffset = (anniegeom->GetTankCentre().Y())*100.;
tank_halfheight = (anniegeom->GetTankHalfheight())*100.;
// XXX override as anniegeom versions are wrong
tank_radius = MRDSpecs::tank_radius;
tank_start = MRDSpecs::tank_start;
tank_yoffset = MRDSpecs::tank_yoffset;
tank_halfheight = MRDSpecs::tank_halfheight;
// generate pdg code to name / mass maps & save them to the CStore for further use by downstream tools
this->GeneratePdgMap();
this->GeneratePdgMassMap();
m_data->CStore.Set("PdgNameMap",pdgcodetoname);
m_data->CStore.Set("PdgMassMap",pdgcodetomass);
return true;
}
bool MCParticleProperties::Execute(){
Log("Tool MCParticleProperties Executing",v_message,verbosity);
// first check if this is a delayed MCTrigger; if it is, we've already run
// on this set of particles and we don't need to do it again
uint16_t MCTriggernum;
get_ok = m_data->Stores["ANNIEEvent"]->Get("MCTriggernum",MCTriggernum);
Log("MCParticleProperties tool: MCTriggernum: "+std::to_string(MCTriggernum),v_message,verbosity);
if(not get_ok){
Log("MCParticleProperties Tool: No MCTriggernum in ANNIEEvent!",v_error,verbosity);
return false;
}
bool splitSubtriggers = false;
m_data->CStore.Get("SplitSubTriggers",splitSubtriggers);
if(splitSubtriggers && (MCTriggernum>0)){
return true; // nothing to do
}
// retrieve the tracks from the BoostStore
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
get_ok = m_data->Stores["ANNIEEvent"]->Get("MCParticles",MCParticles);
if(not get_ok){
Log("MCParticleProperties Tool: No MCParticles in ANNIEEvent!",v_error,verbosity);
return false;
}
// Loop over reconstructed tracks and calculate additional properties
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Log("MCParticleProperties Tool: Looping over MCParticles",v_debug,verbosity);
for(int tracki=0; tracki<(int)MCParticles->size(); tracki++){
Log("MCParticleProperties Tool: Processing MCParticle "+to_string(tracki),v_debug,verbosity);
// Get the track details
MCParticle* nextparticle = &MCParticles->at(tracki);
Log("MCParticleProperties Tool: Printing existing particle stats",v_debug,verbosity);
if(verbosity>v_debug){
cout<<"<<<<<<<<<<<<<<<<"<<endl;
nextparticle->Print();
cout<<"<<<<<<<<<<<<<<<<"<<endl;
}
Position startvertex = nextparticle->GetStartVertex();
startvertex.UnitToCentimeter();
Position stopvertex = nextparticle->GetStopVertex();
stopvertex.UnitToCentimeter();
Position differencevector = (stopvertex-startvertex);
double atracklengthtotal = differencevector.Mag();
// XXX DEBUG THIS, why isn't this returning the correct answer?
//double atrackangle = differencevector.Angle(Position(0,0,1));
// check if it starts in the fiducial volume
bool isinfiducialvol=false;
if( (sqrt(pow(startvertex.X(), 2)
+ pow(startvertex.Z()-tank_start-tank_radius,2)) < fidcutradius) &&
(abs(startvertex.Y()-tank_yoffset) < fidcuty) &&
((startvertex.Z()-tank_start-tank_radius) < fidcutz) ){
isinfiducialvol=true;
}
nextparticle->SetStartsInFiducialVolume(isinfiducialvol);
//====================================================================================================
// Estimate MRD penetration TODO add mrd entry/exit points to WCSim Tracks?
//====================================================================================================
// The mrd is as wide as the tank. We can ensure a track enters the mrd by projecting
// the track forward from the start vertex at the angle between start and stop vertices,
// and requiring:
// 1) at z=MRD_start, x is between +/-(MRD_width/2);
// 2) z endpoint is > MRD_start
// For at least 2 layers of penetration, as above but with requirement on x @ z=MRD_layer2
// For range-out, as above with requirement on x @ z=MRD_start+MRD_depth &&
// z endpoint is > MRD_start+MRD_depth
float oppx = stopvertex.X() - startvertex.X();
float adj = stopvertex.Z() - startvertex.Z();
double avgtrackgradx = (adj!=0) ? (oppx/adj) : 1000000;
float avgtrackanglex = atan(avgtrackgradx);
float oppy = stopvertex.Y() - startvertex.Y();
double avgtrackgrady = (adj!=0) ? (oppy/adj) : 1000000;
float avgtrackangley = atan(avgtrackgrady);
// XXX debug override until we fix version above
double atrackangle = sqrt(pow(avgtrackanglex,2.)+pow(avgtrackangley,2.));
float xatmrd = startvertex.X() + (MRDSpecs::MRD_start-startvertex.Z())*avgtrackgradx;
float yatmrd = startvertex.Y() + (MRDSpecs::MRD_start-startvertex.Z())*avgtrackgrady;
if(verbosity>3){
cout<<"primary start vertex: "; startvertex.Print();
cout<<"primary stop vertex: "; stopvertex.Print();
cout<<"oppx = "<<oppx<<endl;
cout<<"adj = "<<adj<<endl;
cout<<"anglex = "<<avgtrackanglex<<endl;
cout<<"tan(anglex) = "<<avgtrackgradx<<endl;
cout<<"projected x at z="<<MRDSpecs::MRD_start<<" is "<<xatmrd<<endl;
cout<<"xatmrd="<<xatmrd<<", MRD_width="<<MRDSpecs::MRD_width<<endl;
cout<<"yatmrd="<<yatmrd<<", MRD_height="<<MRDSpecs::MRD_height<<endl;
}
// variables to be saved to EventDistributions
Position MRDentrypoint(0,0,0), MRDexitpoint(0,0,0), MuTrackInMRD(0,0,0);
double atracklengthinmrd, mrdpenetrationcm;
int mrdpenetrationlayers;
bool atrackprojectedhitmrd;
bool atrackentersmrd, atrackstopsinmrd, atrackpenetratesmrd;
// check for intercept and record entry point
bool checkboxlinerror=false;
//======================================================================================================
// Calculate whether the extended (projected) particle trajectory would hit the MRD (first layer)
//======================================================================================================
atrackprojectedhitmrd = CheckProjectedMRDHit(startvertex, stopvertex, MRDSpecs::MRD_width, MRDSpecs::MRD_height,MRDSpecs::MRD_start);
//new version based on external function calls
///////////////////////////////////////////////
// bool CheckLineBox( Position L1, Position L2, Position B1, Position B2,
// Position &Hit, Position &Hit2, bool &error)
// returns true if line (L1, L2) intersects with the box (B1, B2)
// returns intersection with smaller Z in Hit
// if 2 interceptions are found, returns interception with larger Z,
// if 1 interception is found, returns L2 (stopping point).
// error returns true if >2 intercepts are found, or other error.
atrackentersmrd = CheckLineBox(startvertex, stopvertex,
Position(-MRDSpecs::MRD_width,-MRDSpecs::MRD_height,MRDSpecs::MRD_start),
Position(MRDSpecs::MRD_width,MRDSpecs::MRD_height,MRDSpecs::MRD_end),
MRDentrypoint, MRDexitpoint, checkboxlinerror);
// sanity check: DISABLE TO ALLOW TRACKS STARTING IN THE MRD
//assert(MRDentrypoint!=startvertex&&"track starts in MRD!?");
// check if MRD stops in the MRD
atrackstopsinmrd = ( abs(stopvertex.X())<MRDSpecs::MRD_width&&
abs(stopvertex.Y())<MRDSpecs::MRD_height&&
stopvertex.Z()>MRDSpecs::MRD_start&&
stopvertex.Z()<MRDSpecs::MRD_end );
if(atrackentersmrd){
atrackpenetratesmrd = ( (MRDentrypoint.Z()==MRDSpecs::MRD_start)&&
(MRDexitpoint.Z()==MRDSpecs::MRD_end) );
MuTrackInMRD = (MRDexitpoint-MRDentrypoint);
atracklengthinmrd = MuTrackInMRD.Mag();
mrdpenetrationcm = MuTrackInMRD.Z();
mrdpenetrationlayers=0;
for(auto layerzval : MRDSpecs::mrdscintlayers){
if(MRDexitpoint.Z()<layerzval) break;
mrdpenetrationlayers++;
}
} else {
atrackpenetratesmrd=false;
mrdpenetrationcm=0.;
mrdpenetrationlayers=0;
atracklengthinmrd=0.;
}
double muxtracklength=MuTrackInMRD.X();
double muytracklength=MuTrackInMRD.Y();
double muztracklength=MuTrackInMRD.Z();
if(verbosity>3){
cout<<"particle travels "<<atracklengthinmrd<<"cm before exiting MRD bounds"<<endl
<<"particle travels "<<muxtracklength<<"cm before leaving X bounds"<<endl
<<"particle travles "<<muytracklength<<"cm before leaving Y bounds"<<endl;
}
double maxtracklengthinMRD = sqrt(
pow(MRDSpecs::MRD_width*2.,2.) +
pow(MRDSpecs::MRD_height*2.,2.) +
pow(MRDSpecs::MRD_depth,2.) );
if((atracklengthinmrd>maxtracklengthinMRD)||
(muxtracklength>((MRDSpecs::MRD_width*2)*1.01)) || (muytracklength>((MRDSpecs::MRD_height*2)*1.01))||
(mrdpenetrationcm>(MRDSpecs::MRD_depth*1.01)) || checkboxlinerror ){ // float inaccuracies...
cerr<<"MRD track length is bad!"<<endl
<<"Max track length is "<<maxtracklengthinMRD<<"cm"
<<", this track is "<<atracklengthinmrd<<"cm, "
<<"distances are ("<<muxtracklength<<", "
<<muytracklength<<", "<<mrdpenetrationcm<<")"<<endl
<<"compare to maximum extents ("<<(2*MRDSpecs::MRD_width)
<<", "<<(2*MRDSpecs::MRD_height)<<", "<<MRDSpecs::MRD_depth<<")"<<endl
<<"MRD Track goes = ("<<MRDentrypoint.X()<<", "<<MRDentrypoint.Y()<<", "
<<MRDentrypoint.Z()<<") -> ("<<MRDexitpoint.X()<<", "<<MRDexitpoint.Y()<<", "
<<MRDexitpoint.Z()<<") and ";
if(atrackstopsinmrd) cerr<<"stops in the MRD"<<endl;
else if(atrackpenetratesmrd) cerr<<"penetrates the MRD"<<endl;
else cerr<<"exits the side of the MRD"<<endl;
cerr<<"MRD width is "<<MRDSpecs::MRD_width<<", MRD height is "<<MRDSpecs::MRD_height
<<", MRD start is "<<MRDSpecs::MRD_start<<", MRD end is "<<(MRDSpecs::MRD_end)<<endl
<<"total path is from ("<<startvertex.X()<<", "<<startvertex.Y()
<<", "<<startvertex.Z()<<") -> ("<<stopvertex.X()<<", "
<<stopvertex.Y()<<", "<<stopvertex.Z()<<")"<<endl
<<"avgtrackangley="<<avgtrackangley<<", avgtrackanglex="<<avgtrackanglex<<endl
<<"CheckLineBox error is "<<checkboxlinerror<<endl;
//return false;
}
// transfer to ANNIEEvent
// ~~~~~~~~~~~~~~~~~~~~~~
nextparticle->SetTrackAngleX(avgtrackanglex);
nextparticle->SetTrackAngleY(avgtrackangley);
nextparticle->SetTrackAngleFromBeam(atrackangle);
nextparticle->SetProjectedHitMrd(atrackprojectedhitmrd);
nextparticle->SetEntersMrd(atrackentersmrd);
MRDentrypoint.UnitToMeter();
nextparticle->SetMrdEntryPoint(MRDentrypoint);
MRDexitpoint.UnitToMeter();
nextparticle->SetExitsMrd(!atrackstopsinmrd);
nextparticle->SetMrdExitPoint(MRDexitpoint);
nextparticle->SetPenetratesMrd(atrackpenetratesmrd);
nextparticle->SetMrdPenetration(mrdpenetrationcm/100.);
nextparticle->SetNumMrdLayersPenetrated(mrdpenetrationlayers);
nextparticle->SetTrackLengthInMrd(atracklengthinmrd/100.);
double dEdx = cMRDTrack::AngleToEnergyLoss(atrackangle);
double energylossinmrd = (atracklengthinmrd) ? (atracklengthinmrd*dEdx) : 0;
nextparticle->SetMrdEnergyLoss(energylossinmrd);
if(verbosity>3){
cout<<"atrackangle: "<<atrackangle<<endl
<<"atrackprojectedhitmrd: "<<atrackprojectedhitmrd<<endl
<<"atrackentersmrd: "<<atrackentersmrd<<endl
<<"atrackstopsinmrd: "<<atrackstopsinmrd<<endl
<<"mrdpenetrationcm: "<<mrdpenetrationcm<<endl
<<"mrdpenetrationlayers: "<<mrdpenetrationlayers<<endl
<<"atracklengthinmrd: "<<atracklengthinmrd<<endl
<<"energylossinmrd: "<<(energylossinmrd)<<endl
<<"MRD track goes = ("<<MRDentrypoint.X()<<", "<<MRDentrypoint.Y()<<", "
<<MRDentrypoint.Z()<<") -> ("<<MRDexitpoint.X()<<", "<<MRDexitpoint.Y()<<", "
<<MRDexitpoint.Z()<<")"<<endl;
}
//====================================================================================================
// calculate the track length in water
//====================================================================================================
// to calculate track length _in water_ find distance from start vertex to the point
// where it intercepts the tank. if this length > total track length, use total track length
// otherwise use this length.
// first check if the start and endpoints are in the tank - if so, there is no tank exit point
// and track length in tank is total length.
Log("MCParticleProperties Tool: Estimating track length in tank",v_debug,verbosity);
double atracklengthintank=0;
bool interceptstank=true;
bool hastrueexitvtx=false;
Position tankentryvtx, tankexitvtx, truetankexitvtx;
bool trackstartsintank = ( sqrt(pow(startvertex.X(),2.) +
pow(startvertex.Z()-tank_start-tank_radius,2.))
< tank_radius ) &&
( abs(startvertex.Y()-tank_yoffset)
< tank_halfheight );
bool trackstopsintank = ( sqrt(pow(stopvertex.X(),2.) +
pow(stopvertex.Z()-tank_start-tank_radius,2.))
< tank_radius ) &&
( abs(stopvertex.Y()-tank_yoffset)
< tank_halfheight );
// // if TankExitPoint is not close to either the tank caps or tank walls,
// // we probably don't have one. So project it instead.
// double tankexitradius = sqrt(pow(nextparticle->GetTankExitPoint().X(),2.) +
// pow(nextparticle->GetTankExitPoint().Z(),2.));
// double tankexitheight = abs(nextparticle->GetTankExitPoint().Y());
// if((tankexitradius<(tank_radius*0.8))&&(tankexitheight<(tank_height*0.8))){
//
if(nextparticle->GetTankExitPoint().Mag()>0.2){ // cover rounding errors
// Later versions of WCSim record the tank exit point explicitly
truetankexitvtx = nextparticle->GetTankExitPoint();
truetankexitvtx.UnitToCentimeter();
hastrueexitvtx=true;
}
if(trackstartsintank&&(trackstopsintank||hastrueexitvtx)){
// If we have know true start and endpoints in tank, we can calculate track length directly
logmessage="MCParticleProperties Tool: Track endpoints in tank are both known";
Log(logmessage,v_debug,verbosity);
tankentryvtx = startvertex;
tankexitvtx = stopvertex;
} else {
logmessage="MCParticleProperties Tool: Estimating tank track length";
Log(logmessage,v_debug,verbosity);
// Three potential cases here:
// 1. Start is outside the tank (entry unknown), exit point is known (either inside tank or recorded)
// - we need to estimate entry point
// 2. Start is inside tank, but endpoint is outside the tank and exit was not recorded by WCSim
// - we need to estimate the exit point
// 3. Both start and endpoints are outside the tank and unknown
// - we need to check the track intercepts the tank, and estimate both entry & exit points
// If we have a recorded truth exit point we can use it as the endpoint for CheckTankIntercepts
// to get a more accurate estimate
Position theendvertex = (hastrueexitvtx) ? truetankexitvtx : stopvertex;
interceptstank = CheckTankIntercepts(startvertex, theendvertex, trackstartsintank, trackstopsintank, tankexitvtx, tankentryvtx);
if(verbosity>3){
cout<<"checktankintercepts returned "<<interceptstank<<endl;
cout<<"and set tankexitvtx to: ("<<tankexitvtx.X()
<<", "<<tankexitvtx.Y()<<", "<<tankexitvtx.Z()<<")"<<endl;
cout<<"and set tankentryvtx to ("<<tankentryvtx.X()<<", "<<tankentryvtx.Y()
<<", "<<tankentryvtx.Z()<<")"<<endl;
}
if(trackstartsintank) tankentryvtx=startvertex;
if(trackstopsintank) tankexitvtx=stopvertex;
}
if(hastrueexitvtx) tankexitvtx = truetankexitvtx;
// we're now able to determine particle track length in the tank:
atracklengthintank = (interceptstank) ? (tankexitvtx-tankentryvtx).Mag() : 0;
// Sanity checks
double maxtanktracklength =
sqrt(pow(tank_radius*2.,2.)+pow(tank_halfheight*2.,2.));
if(verbosity>3){
cout<<"TRACK SUMMARY"<<endl;
cout<<"track start point : ("<<startvertex.X()<<", "<<startvertex.Y()
<<", "<<startvertex.Z()<<")"<<endl
<<"track stop point : ("<<stopvertex.X()<<", "<<stopvertex.Y()
<<", "<<stopvertex.Z()<<")"<<endl;
cout<<"track starts "<<((trackstartsintank) ? "inside" : "outside")<<" tank, and ends "
<<((trackstopsintank) ? "inside" : "outside")<<" the tank"<<endl;
cout<<"tank entry point : ("<<tankentryvtx.X()<<", "<<tankentryvtx.Y()
<<", "<<tankentryvtx.Z()<<")"<<endl;
cout<<"tank exit point: ("<<tankexitvtx.X()<<", "<<tankexitvtx.Y()<<", "<<tankexitvtx.Z()<<") "
<<endl;
cout<<"tank "<<((hastrueexitvtx) ? "had" : "didn't have")<<" a truth recorded exit point"<<endl;
cout<<"tank track length: ("<<(tankexitvtx.X()-tankentryvtx.X())
<<", "<<(tankexitvtx.Y()-tankentryvtx.Y())<<", "
<<(tankexitvtx.Z()-tankentryvtx.Z())<<") = "<<atracklengthintank<<"cm total"<<endl;
cout<<"c.f. max possible tank track length is "<<maxtanktracklength<<endl;
}
if(atracklengthintank > maxtanktracklength){
Log("MCParticleProperties Tool: Track length is impossibly long!",v_error,verbosity);
//return false;
}
if(atracklengthintank > differencevector.Mag()){
Log("MCParticleProperties Tool: Track length in tank is greater than total track length.",v_warning,verbosity); //This seems to happen all the time for gammas/protons with short tracks--> reduce verbosity to warning
//return false;
}
if(TMath::IsNaN(atracklengthintank)){
Log("MCParticleProperties Tool: NaN RESULT FROM MU TRACK LENGTH IN TANK?!",v_error,verbosity);
//return false;
}
// We can also use a slightly modified version of the CheckTankIntercepts to find
// the projected tank exit point for particles that started in the tank, regardless
// of whether they left it. This is useful for e.g. showing pion decay gamma vertices,
// even if the light is not produced by the gammas themselves
Log("MCParticleProperties Tool: Calculating projected tank exit",v_debug,verbosity);
Position projectedexitvertex;
if(hastrueexitvtx||(interceptstank&&(!trackstopsintank))){
Log("MCParticleProperties Tool: Using true/estimated tank exit",v_debug,verbosity);
} else {
// exit projection only makes sense for tracks starting in tank
if(trackstartsintank && trackstopsintank){
bool projectok = ProjectTankIntercepts(startvertex, stopvertex, projectedexitvertex);
if(not projectok){
cerr<<"MCParticleProperties Tool: ProjectTankIntercepts returned false?!"<<std::endl;
} else {
Log("MCParticleProperties Tool: Projected track exit OK",v_debug,verbosity);
}
} else {
// TODO we could relax the requirement that it started in the tank;
// provided it either started in the tank *or* had a tankentryvtx
// we can project an exit. Leave that for now though. FIXME
Log("MCParticleProperties Tool: Track did not start in tank; no projected exit",v_debug,verbosity);
}
}
// transfer to ANNIEEvent
// ~~~~~~~~~~~~~~~~~~~~~~
nextparticle->SetEntersTank(interceptstank);
tankentryvtx.UnitToMeter();
nextparticle->SetTankEntryPoint(tankentryvtx);
nextparticle->SetExitsTank(interceptstank&&!trackstopsintank);
// TankExitPoint is either a projected or true exit point
if(hastrueexitvtx){
// do nothing: the tankexitvtx is already populated by LoadWCSim
}
else if(interceptstank&&(!trackstopsintank)){
tankexitvtx.UnitToMeter();
nextparticle->SetTankExitPoint(tankexitvtx);
} else {
projectedexitvertex.UnitToMeter();
nextparticle->SetTankExitPoint(projectedexitvertex);
}
nextparticle->SetTrackLengthInTank(atracklengthintank/100.);
if(verbosity>3){
cout<<"tankentryvtx: ("<<tankentryvtx.X()<<", "<<tankentryvtx.Y()<<", "<<tankentryvtx.Z()<<")"
<<", tankexitvtx: ("<<tankexitvtx.X()<<", "<<tankexitvtx.Y()<<", "<<tankexitvtx.Z()<<")"
<<", atracklengthintank: "<<atracklengthintank<<endl;
}
} // end of loop over MCParticles
return true;
}
bool MCParticleProperties::Finalise(){
return true;
}
//============================================================================
// a test to see if a projected point in a plane is within a box in that plane
int MCParticleProperties::InBox( Position Hit, Position B1, Position B2, const int Axis) {
if ( Axis==1 && Hit.Z() > B1.Z() && Hit.Z() < B2.Z() && Hit.Y() > B1.Y() && Hit.Y() < B2.Y()) return 1;
if ( Axis==2 && Hit.Z() > B1.Z() && Hit.Z() < B2.Z() && Hit.X() > B1.X() && Hit.X() < B2.X()) return 1;
if ( Axis==3 && Hit.X() > B1.X() && Hit.X() < B2.X() && Hit.Y() > B1.Y() && Hit.Y() < B2.Y()) return 1;
return 0;
}
// projects the hitpoint by adding a scaled vector to the start point
int MCParticleProperties::GetIntersection( float fDst1, float fDst2, Position P1, Position P2, Position &Hit) {
if ( (fDst1 * fDst2) >= 0.0f) return 0;
if ( fDst1 == fDst2) return 0;
Hit = P1 + (P2-P1) * ( -fDst1/(fDst2-fDst1) );
return 1;
}
// returns true if line (L1, L2) intersects with the box (B1, B2)
// returns intersection point in Hit
bool MCParticleProperties::CheckLineBox( Position L1, Position L2, Position B1, Position B2, Position &Hit, Position &Hit2, bool &error, int verbose){
error=false;
if(verbose){
cout<<"CheckLineBox called with start:"; L1.Print(); cout<<" and stop "; L2.Print();
cout<<", c.f. box corners are "; B1.Print(); cout<<" and "; B2.Print(); cout<<endl;
}
// check if it misses the box entirely by being on one side of a plane over entire track
if (L2.X() <= B1.X() && L1.X() <= B1.X()) return false;
if (L2.X() >= B2.X() && L1.X() >= B2.X()) return false;
if (L2.Y() <= B1.Y() && L1.Y() <= B1.Y()) return false;
if (L2.Y() >= B2.Y() && L1.Y() >= B2.Y()) return false;
if (L2.Z() <= B1.Z() && L1.Z() <= B1.Z()) return false;
if (L2.Z() >= B2.Z() && L1.Z() >= B2.Z()) return false;
if(verbose){
cout<<"passes initial tests as not missing box"<<endl;
}
// check if it's inside the box to begin with (classed as an interception at start vtx)
if (L1.X() > B1.X() && L1.X() < B2.X() &&
L1.Y() > B1.Y() && L1.Y() < B2.Y() &&
L1.Z() > B1.Z() && L1.Z() < B2.Z()){
if(verbose){
cout<<"starts in the box"<<endl;
}
Hit = L1;
}
// check if it's inside the box at endpoint (classed as an interception at end vtx)
if (L2.X() > B1.X() && L2.X() < B2.X() &&
L2.Y() > B1.Y() && L2.Y() < B2.Y() &&
L2.Z() > B1.Z() && L2.Z() < B2.Z()){
Hit2 = L2;
if(verbose){
cout<<"ends in the box"<<endl;
}
}
if(Hit==L1&&Hit2==L2) return true;
// check for an interception in X, Y then Z.
//if ( (GetIntersection( L1.X()-B1.X(), L2.X()-B1.X(), L1, L2, Hit) && InBox( Hit, B1, B2, 1 ))
// || (GetIntersection( L1.Y()-B1.Y(), L2.Y()-B1.Y(), L1, L2, Hit) && InBox( Hit, B1, B2, 2 ))
// || (GetIntersection( L1.Z()-B1.Z(), L2.Z()-B1.Z(), L1, L2, Hit) && InBox( Hit, B1, B2, 3 ))
// || (GetIntersection( L1.X()-B2.X(), L2.X()-B2.X(), L1, L2, Hit) && InBox( Hit, B1, B2, 1 ))
// || (GetIntersection( L1.Y()-B2.Y(), L2.Y()-B2.Y(), L1, L2, Hit) && InBox( Hit, B1, B2, 2 ))
// || (GetIntersection( L1.Z()-B2.Z(), L2.Z()-B2.Z(), L1, L2, Hit) && InBox( Hit, B1, B2, 3 )))
// return true;
// Above seems to assume there will only be one interception!!
// e.g. if X has an interception, there are no checks for Z interception - if it enters
// the front face and exits the side, only the side exit will be returned.
// Instead, note all interception points and return the first (and second if it exists)
std::vector<Position> interceptions;
bool anyinterception=false;
bool thisinterception;
if(verbose){
cout<<"finding interceptions"<<endl;
}
Position temphit;
thisinterception=
GetIntersection( L1.X()-B1.X(), L2.X()-B1.X(), L1, L2, temphit) && InBox(temphit, B1, B2, 1);
if(thisinterception){ interceptions.push_back(temphit); anyinterception=true; }
thisinterception=
GetIntersection( L1.Y()-B1.Y(), L2.Y()-B1.Y(), L1, L2, temphit) && InBox( temphit, B1, B2, 2 );
if(thisinterception){ interceptions.push_back(temphit); anyinterception=true; }
thisinterception=
GetIntersection( L1.Z()-B1.Z(), L2.Z()-B1.Z(), L1, L2, temphit) && InBox( temphit, B1, B2, 3 );
if(thisinterception){ interceptions.push_back(temphit); anyinterception=true; }
thisinterception=
GetIntersection( L1.X()-B2.X(), L2.X()-B2.X(), L1, L2, temphit) && InBox( temphit, B1, B2, 1 );
if(thisinterception){ interceptions.push_back(temphit); anyinterception=true; }
thisinterception=
GetIntersection( L1.Y()-B2.Y(), L2.Y()-B2.Y(), L1, L2, temphit) && InBox( temphit, B1, B2, 2 );
if(thisinterception){ interceptions.push_back(temphit); anyinterception=true; }
thisinterception=
GetIntersection( L1.Z()-B2.Z(), L2.Z()-B2.Z(), L1, L2, temphit) && InBox( temphit, B1, B2, 3 );
if(thisinterception){ interceptions.push_back(temphit); anyinterception=true; }
if(verbose){
cout<<"found "<<interceptions.size()<<" interceptions";
if(interceptions.size()>0) { cout<<" at "; interceptions.at(0).Print(); }
if(interceptions.size()>1) { cout<<" and "; interceptions.at(1).Print(); }
cout<<endl;
}
if(interceptions.size()>2){
cerr<<"CheckLineBox found more than two intercepts?! They are at:"<<endl;
for(auto&& avec : interceptions)
cerr<<"("<<avec.X()<<", "<<avec.Y()<<", "<<avec.Z()<<")"<<endl;
error=true;
return false;
} else if(interceptions.size()==2){
auto vec1 = interceptions.at(0);
auto vec2 = interceptions.at(1);
if(vec1.Z()<vec2.Z()){
Hit=vec1;
Hit2=vec2;
} else {
Hit=vec2;
Hit2=vec1;
}
return true;
} else if(interceptions.size()==1){
if(Hit==L1){ // track starts in mrd - found intercept is exit point
Hit2=interceptions.at(0);
return true;
} else { // track starts outside mrd - found intercept is entry point
Hit=interceptions.at(0);
return true;
}
} else {
return false;
}
}
bool MCParticleProperties::CheckProjectedMRDHit(Position startvertex, Position stopvertex, double mrdwidth, double mrdheight, double mrdstart){
bool projected_mrdhit = true;
Position diffvertex = stopvertex - startvertex;
//calculate projected x and y positions of the extended particle track from the track to the MRD
double ProjMRDHit = (mrdstart - startvertex.Z())/(diffvertex.Z());
double ProjXMRD = startvertex.X() + ProjMRDHit*diffvertex.X();
double ProjYMRD = startvertex.Y() + ProjMRDHit*diffvertex.Y();
//check if the projected x and y positions at the z-position of the first MRD layer are contained within the first MRD layers
if (fabs(ProjXMRD) > mrdwidth) projected_mrdhit = false;
if (fabs(ProjYMRD) > mrdheight) projected_mrdhit = false;
if (ProjMRDHit < 0.) projected_mrdhit = false; //particle going in wrong direction
return projected_mrdhit;
}
//=========================================================================================
// A test to see whether a projected line within a plane intersects a circle within the plane
bool MCParticleProperties::CheckTankIntercepts( Position startvertex, Position stopvertex, bool trackstartsintank, bool trackstopsintank, Position &Hit, Position &Hit2, int verbose){
if(verbose){
cout<<"CheckTankIntercepts with startvertex=("<<startvertex.X()<<", "<<startvertex.Y()
<<", "<<startvertex.Z()<<"), stopvertex=("<<stopvertex.X()<<", "
<<stopvertex.Y()<<", "<<stopvertex.Z()<<")"<<endl;
}
// simple checks to save time
if(
( (startvertex.X() > tank_radius) && (stopvertex.X() > tank_radius) ) ||
( (startvertex.X() < -tank_radius) && (stopvertex.X() < -tank_radius) ) ||
( ((startvertex.Y()-tank_yoffset) > tank_halfheight) && ((stopvertex.Y()-tank_yoffset) > tank_halfheight) ) ||
( ((startvertex.Y()-tank_yoffset) < -tank_halfheight) && ((stopvertex.Y()-tank_yoffset) < -tank_halfheight) ) ||
( (startvertex.Z() < tank_start) && (stopvertex.Z() < tank_start) ) ||
( (startvertex.Z() > (tank_start+2.*tank_radius)) && (stopvertex.Z() > (tank_start+2.*tank_radius)) )
){
logmessage = "MCParticleProperties Tool::CheckTankIntercepts breaking early as start and endpoints"
" are both on the same side outside of the tank bounds";
Log(logmessage,v_debug,verbosity);
if(verbose){
if( (startvertex.X() > tank_radius) && (stopvertex.X() > tank_radius) )
cout<<"track entirely on right of tank"<<endl;
if( (startvertex.X() < -tank_radius) && (stopvertex.X() < -tank_radius) )
cout<<"track entirely on left of tank"<<endl;
if( ((startvertex.Y()-tank_yoffset) > tank_halfheight) && ((stopvertex.Y()-tank_yoffset) > tank_halfheight) )
cout<<"track entirely above tank"<<endl;
if( ((startvertex.Y()-tank_yoffset) < -tank_halfheight) && ((stopvertex.Y()-tank_yoffset) < -tank_halfheight) )
cout<<"track entirely below tank"<<endl;
if( (startvertex.Z() < tank_start) && (stopvertex.Z() < tank_start) )
cout<<"track entirely before tank"<<endl;
if( (startvertex.Z() > (tank_start+2.*tank_radius)) && (stopvertex.Z() > (tank_start+2.*tank_radius)) )
cout<<"track entirely after tank"<<endl;
}
return false;
}
// calculate average gradients
double oppx = stopvertex.X() - startvertex.X();
double adj = stopvertex.Z() - startvertex.Z();
double avgtrackgradx = (adj!=0) ? (oppx/adj) : 1000000;
double oppy = stopvertex.Y() - startvertex.Y();
double avgtrackgrady = (adj!=0) ? (oppy/adj) : 1000000;
// make it unit so we don't get issues with very short tracks
Position differencevector = (stopvertex-startvertex).Unit();
// first check for the track being in the z plane, as this will produce infinite gradients
//if(abs(differencevector.Z())<0.1){ //0.1 seems to be too high of a threshold, happens for a lot of tracks (normalized unit vector)
if(abs(differencevector.Z())<0.001){
// we have a simpler case: the tank is simply a box of height tankheight
// and width = length of a chord at the given z
if(verbose){
cout<<"track is in z plane, using alt method"<<endl;
}
double base = abs(startvertex.Z()-tank_start-tank_radius);
double chordlen = sqrt(pow(tank_radius,2.)-pow(base,2.)); // half the chord length, strictly.
if(verbose){
cout<<"half width of tank in plane z="<<startvertex.Z()<<" is "<<chordlen<<endl;
}
// simple checks to save time
if(base>tank_radius) return false; // track misses tank in z plane
if( ((startvertex.Y()-tank_yoffset)<-tank_halfheight) &&
((stopvertex.Y() -tank_yoffset)<-tank_halfheight) ){
return false; // track is entirely below tank
} else
if( ((startvertex.Y()-tank_yoffset)>tank_halfheight) &&
((stopvertex.Y() -tank_yoffset)>tank_halfheight) ){
return false; // track is entirely above tank
} else
if( (startvertex.X()<-chordlen) &&
(stopvertex.Z( )<-chordlen) ){
return false; // track is entirely to left of tank
} else
if( (startvertex.X()>chordlen) &&
(stopvertex.X() >chordlen) ){
return false; // track is entirely to right of tank
}
if(verbose){
cout<<"track intercepted tank somewhere"<<endl;
}
// second possibility: track is parallel to x-axis: then d*/dz=inf AND dx/dy=inf
if(abs(differencevector.Y())<0.1){
if(verbose){
cout<<"track ran parallel to x axis"<<endl;
}
// even simpler: entry and exit points are just the tank walls in that z plane
bool isrightgoing = (stopvertex.X()>startvertex.X());
if(!trackstartsintank){
(isrightgoing) ? Hit2.SetX(-chordlen) : Hit2.SetX(chordlen);
Hit2.SetY(startvertex.Y()); Hit2.SetZ(startvertex.Z());
}
if(!trackstopsintank){
(isrightgoing) ? Hit.SetX(chordlen) : Hit.SetX(-chordlen);
Hit.SetY(startvertex.Y()); Hit.SetZ(startvertex.Z());
}
} else {
// track intercepted the tank at least once. find where
double trackdxdy = (stopvertex.X()-startvertex.X())/(stopvertex.Y()-startvertex.Y());
if(verbose){
cout<<"trackdxdy="<<trackdxdy<<endl;
}
// there are 4 possible intersection points (2x, 2y), of which only 1 or 2 may be relevant
double xentry=-1., xexit=-1., yentry=-1., yexit=-1.;
bool entryfound=false, exitfound=false;
// entry point
if(!trackstartsintank){ // if startvol is not in tank we must have had an entry point
if(verbose){
cout<<"track started outside tank, finding entry point"<<endl;
}
// find y entry - track must start outside tank y bounds to have a cap entry
if(abs(startvertex.Y()-tank_yoffset)>tank_halfheight){
bool isupgoing = (stopvertex.Y()>startvertex.Y());
(isupgoing) ? yentry=-tank_halfheight : yentry=tank_halfheight;
double distancetoyentry = yentry - startvertex.Y(); // signed
double xatyentry = startvertex.X()+(trackdxdy*distancetoyentry);
if(abs(xatyentry)<chordlen){
Hit2.SetX(xatyentry);
Hit2.SetY(yentry+tank_yoffset);
entryfound=true;
}
// else track entered via a wall
if(verbose){
cout<<"track started outside caps ";
if(entryfound){
cout<<"and entered at ("<<Hit2.X()<<", "<<(Hit2.Y()-tank_yoffset)<<")"<<endl;
} else {
cout<<"but entered via the wall, as xatyentry="<<xatyentry<<endl;
}
}
} // else track did not start outside tank y bounds: no cap entry
// find wall entry - track must start outside tank x bounds to have a wall entry
if((!entryfound) && abs(startvertex.X())>chordlen){
bool isrightgoing = (stopvertex.X()>startvertex.X());
(isrightgoing) ? xentry=-chordlen : xentry=chordlen;
double distancetoxentry = xentry - (startvertex.X()); // signed
double yatxentry = startvertex.Y()+(distancetoxentry/trackdxdy);
if(abs(yatxentry)<tank_halfheight){ Hit2.SetX(xentry); Hit2.SetY(yatxentry); entryfound=true; }
// else track entered via a cap
if(verbose){
cout<<"track started outside walls ";
if(entryfound){
cout<<"and entered at ("<<Hit2.X()<<", "<<(Hit2.Y()-tank_yoffset)<<")"<<endl;
} else {
cout<<"but yatxentry="<<yatxentry<<endl;
}
}
} // else track did not start outside tank x bounds: no wall entry
if(!entryfound) Log("MCParticleProperties tool: Could not find track entry point!? ("+std::to_string(startvertex.X())+","+std::to_string(startvertex.Y())+","+std::to_string(startvertex.Z())+") --> ("+std::to_string(stopvertex.X())+","+std::to_string(stopvertex.Y())+","+std::to_string(stopvertex.Z())+")",v_error,verbosity);
else Hit2.SetZ(startvertex.Z());
if(verbose){
if(entryfound) cout<<"setting entry Z to "<<(Hit2.Z()-tank_start-tank_radius)<<endl;
}
}
// repeat for exit point
if(!trackstopsintank){
if(verbose){
cout<<"track ended outside tank, finding exit point"<<endl;
}
// find y exit - track must stop outside tank y bounds to have a cap exit
if(abs(stopvertex.Y()-tank_yoffset)>tank_halfheight){
bool isupgoing = (stopvertex.Y()>startvertex.Y());
(isupgoing) ? yexit=tank_halfheight : yexit=-tank_halfheight;
double distancetoyexit = yexit - startvertex.Y(); // signed
double xatyexit = startvertex.X()+(trackdxdy*distancetoyexit);
if(abs(xatyexit)<chordlen){ Hit.SetX(xatyexit); Hit.SetY(yexit+tank_yoffset); exitfound=true; }
// else track entered via a wall
if(verbose){
cout<<"track stopped outside caps ";
if(exitfound) cout<<"and exited at ("<<Hit.X()<<", "<<(Hit.Y()-tank_yoffset)<<")"<<endl;
else cout<<"but exited via the wall, as xatyexit="<<xatyexit<<endl;
}
} // else track did not start outside tank y bounds: no cap exit
// find wall exit - track must start outside tank x bounds to have a wall exit
if((!exitfound) && abs(stopvertex.X())>chordlen){
bool isrightgoing = (stopvertex.X()>startvertex.X());
(isrightgoing) ? xexit=chordlen : xexit=-chordlen;
double distancetoxexit = xexit - (startvertex.X()); // signed
double yatxexit = startvertex.Y()+(distancetoxexit/trackdxdy);
if(abs(yatxexit)<tank_halfheight){ Hit.SetX(xexit); Hit.SetY(yatxexit); exitfound=true; }
// else track entered via a cap
if(verbose){
cout<<"track stopped outside walls ";
if(entryfound) cout<<"and exited at ("<<Hit.X()<<", "<<(Hit.Y()-tank_yoffset)<<")"<<endl;
else cout<<"but yatxexit="<<yatxexit<<endl;
}
} // else track did not start outside tank y bounds: no wall exit
if(!exitfound) Log("MCParticleProperties tool: Could not find track exit point!? ("+std::to_string(startvertex.X())+","+std::to_string(startvertex.Y())+","+std::to_string(startvertex.Z())+") --> ("+std::to_string(stopvertex.X())+","+std::to_string(stopvertex.Y())+","+std::to_string(stopvertex.Z())+")",v_error,verbosity);
else Hit.SetZ(startvertex.Z());
if(verbose){
if(exitfound) cout<<"setting exit Z to "<<(Hit.Z()-tank_start-tank_radius)<<endl;
}
}
if( ((!trackstopsintank)&&(!exitfound)) || ((!trackstartsintank)&&(!entryfound)) ) return false;
}
} else { // track was not in z plane: use old method, based on dx/dz, dy/dz
// parameterize the track by it's z position, and find the
// z value where the track would leave the radius of the tank
double xattankcentre = startvertex.X() - (startvertex.Z()-tank_start-tank_radius)*avgtrackgradx;
double firstterm = -avgtrackgradx*xattankcentre;
double thirdterm = 1+pow(avgtrackgradx,2.);
double secondterm = (pow(tank_radius,2.)*thirdterm) - pow(xattankcentre,2.);
if(secondterm<=0){
if(verbose){ cout<<"Tank miss!"<<endl; }
return false; // Doens't hit the tank.
}
double solution1 = (firstterm + sqrt(secondterm))/thirdterm;
double solution2 = (firstterm - sqrt(secondterm))/thirdterm;
double tankstartpointz, tankendpointz;
if(stopvertex.Z() > startvertex.Z()){
tankendpointz = solution1; //forward going track
tankstartpointz = solution2; // more upstream intercept is entry point
} else {
tankendpointz = solution2; // backward going track
tankstartpointz = solution1; // more upstream intercept is exit point
}
// correct for tank z offset
tankendpointz += tank_start+tank_radius;
tankstartpointz += tank_start+tank_radius;
if(verbose){
// for sanity check:
cout<<"z'1 = "<<solution1<<", z1 = "<<(solution1+startvertex.Z())
<<", x1 = "<<(xattankcentre+(avgtrackgradx*solution1))
<<", r1 = "<<sqrt(pow(solution1,2.)+pow(xattankcentre+(avgtrackgradx*solution1),2.))<<endl;
cout<<"z'2 = "<<solution2<<", z2 = "<<(solution2+startvertex.Z())
<<", x2 = "<<(xattankcentre+(avgtrackgradx*solution2))
<<", r2 = "<<sqrt(pow(solution2,2.)+pow(xattankcentre+(avgtrackgradx*solution2),2.))<<endl;
}
// calculate x by projecting track along parameterization
double tankendpointx = startvertex.X() + (tankendpointz-startvertex.Z())*avgtrackgradx;
double tankstartpointx = startvertex.X() + (tankstartpointz-startvertex.Z())*avgtrackgradx;
// and same for y
double tankendpointy = startvertex.Y() + (tankendpointz-startvertex.Z())*avgtrackgrady;
double tankstartpointy = startvertex.Y() + (tankstartpointz-startvertex.Z())*avgtrackgrady;
if(verbose){
cout<<"tank start: "<<tank_start<<endl;
cout<<"tank end: "<<(tank_start+2*tank_radius)<<endl;
cout<<"tank radius: "<<tank_radius<<endl;
Position trackdir = (stopvertex - startvertex).Unit();
cout<<"start dir =("<<trackdir.X()<<", "<<trackdir.Y()
<<", "<<trackdir.Z()<<")"<<endl;
cout<<"avgtrackgradx="<<avgtrackgradx<<endl;
cout<<"avgtrackgrady="<<avgtrackgrady<<endl;
cout<<"xattankcentre="<<xattankcentre<<endl;
cout<<"firstterm="<<firstterm<<endl;
cout<<"thirdterm="<<thirdterm<<endl;
cout<<"secondterm="<<secondterm<<endl;
cout<<"tank intercept z solution1="<<solution1<<endl;
cout<<"tank intercept z solution2="<<solution2<<endl<<endl;
cout<<"values before cap exit check"<<endl;
cout<<"tankstartpointz="<<tankstartpointz<<endl;
cout<<"tankstartpointx="<<tankstartpointx<<endl;
cout<<"tankstartpointy="<<tankstartpointy<<endl;
cout<<"tankendpointz="<<tankendpointz<<endl;
cout<<"tankendpointx="<<tankendpointx<<endl;
cout<<"tankendpointy="<<tankendpointy<<endl;
cout<<"TMath::Abs(startvertex.Y()-tank_yoffset)="
<<TMath::Abs(startvertex.Y()-tank_yoffset)
<<"(tank_halfheight)="<<(tank_halfheight)<<endl;
}
// now check if the particle would have exited through one of the caps before reaching this point
// if projected y value at the radial exit is outside the tank, and the track started inside the tank,
// then the tank must have left prior to this point via one of the caps
if( TMath::Abs(tankendpointy-tank_yoffset)>(tank_halfheight) &&
TMath::Abs(startvertex.Y()-tank_yoffset)<(tank_halfheight)){
// ^ second condition due to slight (mm) differences in tank y height in WCSim.
// this trajectory exits through the cap. Need to recalculate x, z exiting points...!
if(stopvertex.Y()>startvertex.Y()){
tankendpointy = tank_halfheight+tank_yoffset; // by definition of leaving through cap
} else {
tankendpointy = -tank_halfheight+tank_yoffset;
}
tankendpointz =
startvertex.Z() + (tankendpointy-startvertex.Y())/avgtrackgrady;
tankendpointx =
startvertex.X() + (tankendpointz-startvertex.Z())*avgtrackgradx;
} // else this trajectory exited the tank by a side point; existing value is valid
// repeat for the tankstartpoint
if( TMath::Abs(tankstartpointy-tank_yoffset)>(tank_halfheight) &&
TMath::Abs(startvertex.Y()-tank_yoffset)<(tank_halfheight)){
// ^ second condition due to slight (mm) differences in tank y height in WCSim.
// this trajectory exits through the cap. Need to recalculate x, z exiting points...!
if(stopvertex.Y()>startvertex.Y()){
tankstartpointy = tank_halfheight+tank_yoffset; // by definition of leaving through cap
} else {
tankstartpointy = -tank_halfheight+tank_yoffset;
}
tankstartpointz =
startvertex.Z() + (tankstartpointy-startvertex.Y())/avgtrackgrady;
tankstartpointx =
startvertex.X() + (tankstartpointz-startvertex.Z())*avgtrackgradx;
} // else this trajectory entered the tank by a side point; existing value is valid
if(verbose){
cout<<"values after cap exit check"<<endl;
cout<<"tankstartpointz="<<tankstartpointz<<endl;
cout<<"tankstartpointx="<<tankstartpointx<<endl;
cout<<"tankstartpointy="<<tankstartpointy<<endl;
cout<<"tankendpointz="<<tankendpointz<<endl;
cout<<"tankendpointx="<<tankendpointx<<endl;
cout<<"tankendpointy="<<tankendpointy<<endl;
}
// return only the appropriate vertices
if(!trackstopsintank) Hit=Position(tankendpointx,tankendpointy,tankendpointz);
if(!trackstartsintank) Hit2=Position(tankstartpointx,tankstartpointy,tankstartpointz);
}
return true;
}
//=========================================================================================
//=========================================================================================
// Find the particle would have left the tank, had it done so
// XXX remove me, hacked these to static so we can make the following function static and usable by other tools
double MCParticleProperties::tank_radius=MRDSpecs::tank_radius;
double MCParticleProperties::tank_start=MRDSpecs::tank_start;
double MCParticleProperties::tank_yoffset=MRDSpecs::tank_yoffset;
double MCParticleProperties::tank_halfheight=MRDSpecs::tank_halfheight;
bool MCParticleProperties::ProjectTankIntercepts(Position startvertex, Position stopvertex, Position &Hit, int verbose){
// this is based on CheckTankIntercepts which estimates the tank entry and exit points,
// but only if the track did indeed enter or exit the tank
// ProjectTankIntercepts cuts out all the checks, and
// 1. assumes the particle started in the tank
// 2. projects an exit point regardless of whether it is beyond the track end
if(verbose){
cout<<"ProjectTankIntercepts with startvertex=("<<startvertex.X()<<", "<<startvertex.Y()
<<", "<<startvertex.Z()<<"), stopvertex=("<<stopvertex.X()<<", "
<<stopvertex.Y()<<", "<<stopvertex.Z()<<")"<<endl;
}
// calculate average gradients
double oppx = stopvertex.X() - startvertex.X();
double adj = stopvertex.Z() - startvertex.Z();
double avgtrackgradx = (adj!=0) ? (oppx/adj) : 1000000;
double oppy = stopvertex.Y() - startvertex.Y();
double avgtrackgrady = (adj!=0) ? (oppy/adj) : 1000000;
// make it unit so we don't get rounding issues with very short tracks
Position differencevector = (stopvertex-startvertex).Unit();
// first check for the track being in the z plane, as this will produce infinite gradients
if(abs(differencevector.Z())<0.1){
// we have a simpler case: the tank is simply a box of height tankheight
// and width = length of a chord at the given z
if(verbose){
cout<<"track is in z plane, using alt method"<<endl;
}
double base = abs(startvertex.Z()-tank_start-tank_radius);
double chordlen = sqrt(pow(tank_radius,2.)-pow(base,2.)); // half the chord length, strictly.
if(verbose){
cout<<"half width of tank in plane z="<<startvertex.Z()<<" is "<<chordlen<<endl;
}
// second possibility: track is parallel to x-axis: then d*/dz=inf AND dx/dy=inf
if(abs(differencevector.Y())<0.1){
if(verbose){
cout<<"track ran parallel to x axis"<<endl;
}
// even simpler: entry and exit points are just the tank walls in that z plane
bool isrightgoing = (stopvertex.X()>startvertex.X());
(isrightgoing) ? Hit.SetX(chordlen) : Hit.SetX(-chordlen); // exit point is tank extent in that plane
Hit.SetY(startvertex.Y()); Hit.SetZ(startvertex.Z()); // parallel to y and z axes: no change
} else {
// track is in z-plane, but not along the X axis: line through a box scenario
double trackdxdy = (stopvertex.X()-startvertex.X())/(stopvertex.Y()-startvertex.Y());
if(verbose){
cout<<"trackdxdy="<<trackdxdy<<endl;
}
// there are 4 possible intersection points (2x, 2y), of which only 1 or 2 may be relevant
double xentry=-1., xexit=-1., yentry=-1., yexit=-1.;
bool entryfound=true, exitfound=false;
// find exit point
if(verbose){
cout<<"finding projected exit point"<<endl;
}
// find y exit - calculate points for both barrel and cap exit
bool isupgoing = (stopvertex.Y()>startvertex.Y());
(isupgoing) ? yexit=tank_halfheight : yexit=-tank_halfheight;
double distancetoyexit = yexit - startvertex.Y(); // signed
double xatyexit = startvertex.X()+(trackdxdy*distancetoyexit);
if(abs(xatyexit)<chordlen){ Hit.SetX(xatyexit); Hit.SetY(yexit+tank_yoffset); exitfound=true; }
// else track entered via a wall
if(verbose){
if(exitfound) cout<<"track exited via cap at ("<<Hit.X()<<", "<<(Hit.Y()-tank_yoffset)<<")"<<endl;
else cout<<"track exited via the wall, as xatyexit="<<xatyexit<<endl;
}
// find wall exit
if(!exitfound){
bool isrightgoing = (stopvertex.X()>startvertex.X());
(isrightgoing) ? xexit=chordlen : xexit=-chordlen;
double distancetoxexit = xexit - (startvertex.X()); // signed
double yatxexit = startvertex.Y()+(distancetoxexit/trackdxdy);
if(abs(yatxexit)<tank_halfheight){ Hit.SetX(xexit); Hit.SetY(yatxexit); exitfound=true; }
// else track entered via a cap
if(verbose){
if(entryfound) cout<<"track exited through the barrel at ("<<Hit.X()<<", "<<(Hit.Y()-tank_yoffset)<<")"<<endl;
else cerr<<"but yatxexit="<<yatxexit
<<">tank_halfheight suggests we should have already found a cap exit!"<<endl;
}
} // else we already found a cap exit
if(!exitfound) cerr<<"MCParticleProperties::ProjectTankExit could not find track exit point!?"<<endl;
else Hit.SetZ(startvertex.Z());
if(verbose){
if(exitfound) cout<<"setting exit Z to "<<(Hit.Z()-tank_start-tank_radius)<<endl;
}
} // end else track did not run along x-axis
} else { // track was not in z plane: use old method, based on dx/dz, dy/dz
// parameterize the track by it's z position, and find the
// z value where the track would leave the radius of the tank
double xattankcentre = startvertex.X() - (startvertex.Z()-tank_start-tank_radius)*avgtrackgradx;
double firstterm = -avgtrackgradx*xattankcentre;
double thirdterm = 1+pow(avgtrackgradx,2.);
double secondterm = (pow(tank_radius,2.)*thirdterm) - pow(xattankcentre,2.);
if(secondterm<=0){
if(verbose){ cout<<"MCParticleProperties::ProjectTankExit says Tank miss?!"<<endl; }
return false; // Doens't hit the tank.
}
double solution1 = (firstterm + sqrt(secondterm))/thirdterm;
double solution2 = (firstterm - sqrt(secondterm))/thirdterm;
double tankendpointz;
if(stopvertex.Z() > startvertex.Z()){
tankendpointz = solution1; //forward going track
} else {
tankendpointz = solution2; // backward going track
}
// correct for tank z offset
tankendpointz += tank_start+tank_radius;
if(verbose){
// for sanity check:
cout<<"z'1 = "<<solution1<<", z1 = "<<(solution1+startvertex.Z())
<<", x1 = "<<(xattankcentre+(avgtrackgradx*solution1))
<<", r1 = "<<sqrt(pow(solution1,2.)+pow(xattankcentre+(avgtrackgradx*solution1),2.))<<endl;
cout<<"z'2 = "<<solution2<<", z2 = "<<(solution2+startvertex.Z())
<<", x2 = "<<(xattankcentre+(avgtrackgradx*solution2))
<<", r2 = "<<sqrt(pow(solution2,2.)+pow(xattankcentre+(avgtrackgradx*solution2),2.))<<endl;
}
// calculate x by projecting track along parameterization
double tankendpointx = startvertex.X() + (tankendpointz-startvertex.Z())*avgtrackgradx;
// and same for y
double tankendpointy = startvertex.Y() + (tankendpointz-startvertex.Z())*avgtrackgrady;
if(verbose){
cout<<"tank start: "<<tank_start<<endl;
cout<<"tank end: "<<(tank_start+2*tank_radius)<<endl;
cout<<"tank radius: "<<tank_radius<<endl;
Position trackdir = (stopvertex - startvertex).Unit();
cout<<"start dir =("<<trackdir.X()<<", "<<trackdir.Y()
<<", "<<trackdir.Z()<<")"<<endl;
cout<<"avgtrackgradx="<<avgtrackgradx<<endl;
cout<<"avgtrackgrady="<<avgtrackgrady<<endl;
cout<<"xattankcentre="<<xattankcentre<<endl;
cout<<"firstterm="<<firstterm<<endl;
cout<<"thirdterm="<<thirdterm<<endl;
cout<<"secondterm="<<secondterm<<endl;
cout<<"tank intercept z solution1="<<solution1<<endl;
cout<<"tank intercept z solution2="<<solution2<<endl<<endl;
cout<<"tankendpointz="<<tankendpointz<<endl;
cout<<"tankendpointx="<<tankendpointx<<endl;
cout<<"tankendpointy="<<tankendpointy<<endl;
cout<<"TMath::Abs(startvertex.Y()-tank_yoffset)="
<<TMath::Abs(startvertex.Y()-tank_yoffset)
<<"(tank_halfheight)="<<(tank_halfheight)<<endl;
}
// now check if the particle would have exited through one of the caps before reaching this point
// if projected y value at the radial exit is outside the tank, and the track started inside the tank,
// then the tank must have left prior to this point via one of the caps
if( TMath::Abs(tankendpointy-tank_yoffset)>(tank_halfheight) &&
TMath::Abs(startvertex.Y()-tank_yoffset)<(tank_halfheight)){
// ^ second condition due to slight (mm) differences in tank y height in WCSim.
// this trajectory exits through the cap. Need to recalculate x, z exiting points...!
if(stopvertex.Y()>startvertex.Y()){
tankendpointy = tank_halfheight+tank_yoffset; // by definition of leaving through cap
} else {
tankendpointy = -tank_halfheight+tank_yoffset;
}
tankendpointz =
startvertex.Z() + (tankendpointy-startvertex.Y())/avgtrackgrady;
tankendpointx =
startvertex.X() + (tankendpointz-startvertex.Z())*avgtrackgradx;
} // else this trajectory exited the tank by a side point; existing value is valid
if(verbose){
cout<<"values after cap exit check"<<endl;
cout<<"tankendpointz="<<tankendpointz<<endl;
cout<<"tankendpointx="<<tankendpointx<<endl;
cout<<"tankendpointy="<<tankendpointy<<endl;
}
Hit.SetX(tankendpointx);
Hit.SetY(tankendpointy);
Hit.SetZ(tankendpointz);
}
return true;
}
//=========================================================================================
std::string MCParticleProperties::PdgToString(int code){
if(pdgcodetoname.size()==0) GeneratePdgMap();
if(pdgcodetoname.count(code)!=0){
return pdgcodetoname.at(code);
} else {
cerr<<"unknown pdg code "<<code<<endl;
return std::to_string(code);
}
}
std::map<int,std::string>* MCParticleProperties::GeneratePdgMap(){
if(pdgcodetoname.size()!=0) return &pdgcodetoname;
pdgcodetoname.emplace(2212,"Proton");
pdgcodetoname.emplace(-2212,"Anti Proton");
pdgcodetoname.emplace(11,"Electron");
pdgcodetoname.emplace(-11,"Positron");
pdgcodetoname.emplace(12,"Electron Neutrino");
pdgcodetoname.emplace(-12,"Anti Electron Neutrino");
pdgcodetoname.emplace(22,"Gamma");
pdgcodetoname.emplace(2112,"Neutron");
pdgcodetoname.emplace(-2112,"Anti Neutron");
pdgcodetoname.emplace(-13,"Muon+");
pdgcodetoname.emplace(13,"Muon-");
pdgcodetoname.emplace(130,"Kaonlong");
pdgcodetoname.emplace(211,"Pion+");
pdgcodetoname.emplace(-211,"Pion-");
pdgcodetoname.emplace(321,"Kaon+");
pdgcodetoname.emplace(-321,"Kaon-");
pdgcodetoname.emplace(3122,"Lambda");
pdgcodetoname.emplace(-3122,"Antilambda");
pdgcodetoname.emplace(310,"Kaonshort");
pdgcodetoname.emplace(3112,"Sigma-");
pdgcodetoname.emplace(3222,"Sigma+");
pdgcodetoname.emplace(3212,"Sigma0");
pdgcodetoname.emplace(111,"Pion0");
pdgcodetoname.emplace(311,"Kaon0");
pdgcodetoname.emplace(-311,"Antikaon0");
pdgcodetoname.emplace(14,"Muon Neutrino");
pdgcodetoname.emplace(-14,"Anti Muon Neutrino");
pdgcodetoname.emplace(-3222,"Anti Sigma-");
pdgcodetoname.emplace(-3212,"Anti Sigma0");
pdgcodetoname.emplace(-3112,"Anti Sigma+");
pdgcodetoname.emplace(3322,"Xsi0");
pdgcodetoname.emplace(-3322,"Anti Xsi0");
pdgcodetoname.emplace(3312,"Xsi-");
pdgcodetoname.emplace(-3312,"Xsi+");
pdgcodetoname.emplace(3334,"Omega-");
pdgcodetoname.emplace(-3334,"Omega+");
pdgcodetoname.emplace(-15,"Tau+");
pdgcodetoname.emplace(15,"Tau-");
pdgcodetoname.emplace(100,"OpticalPhoton");
pdgcodetoname.emplace(3328,"Alpha");
pdgcodetoname.emplace(3329,"Deuteron");
pdgcodetoname.emplace(3330,"Triton");
pdgcodetoname.emplace(3351,"Li7");
pdgcodetoname.emplace(3331,"C10");
pdgcodetoname.emplace(3345,"B11");
pdgcodetoname.emplace(3332,"C12");
pdgcodetoname.emplace(3350,"C13");
pdgcodetoname.emplace(3349,"N13");
pdgcodetoname.emplace(3340,"N14");
pdgcodetoname.emplace(3333,"N15");
pdgcodetoname.emplace(3334,"N16");
pdgcodetoname.emplace(3335,"O16");
pdgcodetoname.emplace(3346,"Al27");
pdgcodetoname.emplace(3341,"Fe54");
pdgcodetoname.emplace(3348,"Mn54");
pdgcodetoname.emplace(3342,"Mn55");
pdgcodetoname.emplace(3352,"Mn56");
pdgcodetoname.emplace(3343,"Fe56");
pdgcodetoname.emplace(3344,"Fe57");
pdgcodetoname.emplace(3347,"Fe58");
pdgcodetoname.emplace(3353,"Eu154");
pdgcodetoname.emplace(3336,"Gd158");
pdgcodetoname.emplace(3337,"Gd156");
pdgcodetoname.emplace(3338,"Gd157");
pdgcodetoname.emplace(3339,"Gd155");
return &pdgcodetoname;
}
double MCParticleProperties::PdgToMass(int code){
if(pdgcodetomass.size()==0) GeneratePdgMassMap();
if(pdgcodetomass.count(code)!=0){
return pdgcodetomass.at(code);
} else {
cerr<<"unknown pdg code "<<code<<endl;
return double(code);
}
}
std::map<int,double>* MCParticleProperties::GeneratePdgMassMap(){
//all masses in MeV
if(pdgcodetomass.size()!=0) return &pdgcodetomass;
pdgcodetomass.emplace(2212,938.272);
pdgcodetomass.emplace(-2212,938.272);
pdgcodetomass.emplace(11,0.511);
pdgcodetomass.emplace(-11,0.511);
pdgcodetomass.emplace(12,0.000);
pdgcodetomass.emplace(-12,0.000);
pdgcodetomass.emplace(22,0.000);
pdgcodetomass.emplace(2112,939.565);
pdgcodetomass.emplace(-2112,939.485);
pdgcodetomass.emplace(-13,105.658);
pdgcodetomass.emplace(13,105.658);
pdgcodetomass.emplace(211,139.571);
pdgcodetomass.emplace(-211,139.571);
pdgcodetomass.emplace(321,493.666);
pdgcodetomass.emplace(-321,493.666);
pdgcodetomass.emplace(3122,1115.683);
pdgcodetomass.emplace(-3122,1115.683);
pdgcodetomass.emplace(3112,1197.449);
pdgcodetomass.emplace(3222,1189.37);
pdgcodetomass.emplace(3212,1192.642);
pdgcodetomass.emplace(111,134.977);
pdgcodetomass.emplace(311,497.611);
pdgcodetomass.emplace(-311,497.611);
pdgcodetomass.emplace(14,0.000);
pdgcodetomass.emplace(-14,0.000);
pdgcodetomass.emplace(-3222,1189.37);
pdgcodetomass.emplace(-3212,1192.642);
pdgcodetomass.emplace(-3112,1197.449);
pdgcodetomass.emplace(3322,1314.86);
pdgcodetomass.emplace(-3322,1314.86);
pdgcodetomass.emplace(3312,1321.71);
pdgcodetomass.emplace(-3312,1321.71);
pdgcodetomass.emplace(3334,1672.45);
pdgcodetomass.emplace(-3334,1672.45);
pdgcodetomass.emplace(-15,1776.86);
pdgcodetomass.emplace(15,1776.86);
pdgcodetomass.emplace(100,0.000);
//masses of nuclei not specified since they won't be able to generate Cherenkov light
return &pdgcodetomass;
}
|
939e534176fd14d74421b48e098cd90be0ad1606
|
158456d78a4ae26c260f7d6a10fa289f0c396427
|
/cpu_load.cpp
|
690e0db1a02397e65cbd4a33c1bb44e6db2c0c62
|
[] |
no_license
|
Teste899/SC18
|
e8324ff8594d7d5f37f979e7492aed97e2bca084
|
263852c3661610dd89542e3370757c6622e0860e
|
refs/heads/master
| 2020-03-07T04:37:49.048518
| 2018-05-31T04:32:37
| 2018-05-31T04:32:37
| 127,271,757
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 911
|
cpp
|
cpu_load.cpp
|
#include <pthread.h>
#include <pthread.h>
#include <cstdlib>
#include <iostream>
#include <sys/time.h>
#include <unistd.h>
#include <math.h>
using namespace std;
bool shut= false;
void *idle(void *arg)
{
long n= (long)arg;
cout << "Thread " << n << endl;
double res= 0, i=0;
while(!shut)
{
res+=sqrt(i)*sqrt(i);
i++;
}
}
int main(int argc, char** argv)
{
int n= 1;
float tempo_total= 0;
if(argc == 3){
n= atoi(argv[1]);
tempo_total= atof(argv[2]);
}
pthread_t th[n];
cout << "In main: creating thread" << endl;
for(int i=0; i<n; i++)
pthread_create(&th[i], NULL, &idle, (void*)(long)i);
double diff_t;
timeval t1, t2;
gettimeofday(&t1, NULL);
while(diff_t<tempo_total)
{
gettimeofday(&t2, NULL);
diff_t = (t2.tv_sec - t1.tv_sec)+(t2.tv_usec - t1.tv_usec)/1000000.0;
}
shut= true;
for(int i=0; i<n; i++)
pthread_join(th[i], NULL);
return 0;
}
|
969ede88d8c836ba8fd0ab2343da2a4e9ae14371
|
c35d0440a42c0694ac02f7148c33d611a7406689
|
/save_pcd.cpp
|
0274b77f439701987b4bde1683ab42f1fa245b09
|
[] |
no_license
|
Yuki-fuku/ssii2016_tutorial
|
c4c1eaa2258a56715004285408d53901a47b5854
|
a5dc94a9b637d276da55d7320044e5b29098c65d
|
refs/heads/master
| 2021-12-09T05:17:33.040679
| 2016-04-28T09:49:24
| 2016-04-28T09:49:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,871
|
cpp
|
save_pcd.cpp
|
#include <ros/ros.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/highgui/highgui.hpp>
#include <pcl_ros/io/pcd_io.h>
#include <sensor_msgs/image_encodings.h>
class SavePCD {
private:
ros::NodeHandle _nh;
ros::Subscriber _sub1, _sub2;
pcl::PointCloud<pcl::PointXYZRGB> input_cloud;
int save_count;
public:
SavePCD() : save_count(0) {
//* subscribe ROS topics
_sub1 = _nh.subscribe ("/camera/rgb/image_color", 1, &SavePCD::image_cb, this);
ROS_INFO ("Listening for incoming data on topic /camera/rgb/image_color ..." );
_sub2 = _nh.subscribe ("/camera/depth_registered/points", 1, &SavePCD::points_cb, this);
ROS_INFO ("Listening for incoming data on topic /camera/depth_registered/points ..." );
}
~SavePCD() {}
//* get points
void points_cb( const sensor_msgs::PointCloud2ConstPtr& cloud ){
if ((cloud->width * cloud->height) == 0)
return;
pcl::fromROSMsg (*cloud, input_cloud);
}
//* show color img and save color img + point cloud
void image_cb( const sensor_msgs::ImageConstPtr& msg ){
cv_bridge::CvImagePtr cv_ptr = cv_bridge::toCvCopy(msg);
//* show color img
cv::Mat color_img = cv_ptr->image;
cv::imshow( "color image", color_img );
cv::waitKey(10);
if ((input_cloud.width * input_cloud.height) == 0)
return;
//* save
std::stringstream filename1;
filename1 << save_count << ".png";
cv::imwrite( filename1.str(), color_img );
std::cout << filename1.str() << " saved." << std::endl;
std::stringstream filename2;
filename2 << save_count << ".pcd";
pcl::io::savePCDFileBinary( filename2.str(), input_cloud );
std::cout << filename2.str() << " saved." << std::endl;
save_count++;
usleep( 300000 );
}
};
int main( int argc, char** argv ){
ros::init(argc,argv,"save_pcd");
SavePCD spcd;
ros::spin();
return 1;
}
|
ca697be0950ddb5b729fef988681a61248d1986a
|
59c26579e0e993f485878aab72b0b6a735c657b5
|
/ThrowBack/GrandPrize.cpp
|
de82b1734f3a854457c7d507f3d4ece75613dee2
|
[
"MIT"
] |
permissive
|
Rufian55/Cplusplus
|
0bf999638640ff4fee02d2ca12244a2a9de5654a
|
baaf5d3b0a36c95d1e796b85aafc407d3f2c5a4b
|
refs/heads/master
| 2021-04-26T05:36:54.030791
| 2016-10-10T20:17:09
| 2016-10-10T20:17:09
| 66,270,120
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,859
|
cpp
|
GrandPrize.cpp
|
/****************************************************************************************
** Program Filename: GrandPrize.cpp
** Author: Chris Kearns
** Date: 3/17/2016
** Description: Contains the grandPrize() function.
** Input: array "collector"
** Output: Used by Main.cpp to generate Jan Kok's Galaxy oscillator animation.
*****************************************************************************************/
#include "GrandPrize.hpp"
#include <iomanip>
using std::setw;
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <string>
/***************************************************************************************
** Function: grandPrize()
** Description:Description: animation function that generates Jan Kok's Galaxy images.
** Parameters: none.
** Pre-Conditions: Runs on Linux console.
** Post-Conditions: None.
****************************************************************************************/
void GrandPrize::grandPrize() {
int univRows, winRows, univCols, winCols;
univRows = 60; // Row bounds of our Universe.
winRows = 40; // Row bounds of our Window.
univCols = 40; // Column bounds of our Universe.
winCols = 20; // Column bounds of our Window.
int time = 50000 * 2; // Time between iterations.
int iterations = 19; // Iterations desired by user.
int aliveCount = 0; // Counter to determine cell state.
int xOffset = 20; // x axis offset for initial image.
int yOffset = 20; // y-axis offset for inital image.
std::string matrix_0[univRows][univCols]; // Our initial Universe array matrix_0 - all cells dead.
// Fill matrix_0 with " "
for (int i = 0; i < univRows; i++) {
for (int j = 0; j < univCols; j++) {
matrix_0[i][j] = " ";
}
}
// "Inject" initial Galaxy image.
int i, j;
i = j = 0;
matrix_0[i - 4 + yOffset][j - 2 + xOffset] = "*";
matrix_0[i - 4 + yOffset][j + 1 + xOffset] = "*";
matrix_0[i - 4 + yOffset][j + 3 + xOffset] = "*";
matrix_0[i - 3 + yOffset][j - 4 + xOffset] = "*";
matrix_0[i - 3 + yOffset][j - 3 + xOffset] = "*";
matrix_0[i - 3 + yOffset][j - 1 + xOffset] = "*";
matrix_0[i - 3 + yOffset][j + 1 + xOffset] = "*";
matrix_0[i - 3 + yOffset][j + 2 + xOffset] = "*";
matrix_0[i - 3 + yOffset][j + 3 + xOffset] = "*";
matrix_0[i - 2 + yOffset][j - 3 + xOffset] = "*";
matrix_0[i - 2 + yOffset][j + 4 + xOffset] = "*";
matrix_0[i - 1 + yOffset][j - 4 + xOffset] = "*";
matrix_0[i - 1 + yOffset][j - 3 + xOffset] = "*";
matrix_0[i - 1 + yOffset][j + 3 + xOffset] = "*";
matrix_0[i + 1 + yOffset][j - 3 + xOffset] = "*";
matrix_0[i + 1 + yOffset][j + 3 + xOffset] = "*";
matrix_0[i + 1 + yOffset][j + 4 + xOffset] = "*";
matrix_0[i + 2 + yOffset][j - 4 + xOffset] = "*";
matrix_0[i + 2 + yOffset][j + 3 + xOffset] = "*";
matrix_0[i + 3 + yOffset][j - 3 + xOffset] = "*";
matrix_0[i + 3 + yOffset][j - 2 + xOffset] = "*";
matrix_0[i + 3 + yOffset][j - 1 + xOffset] = "*";
matrix_0[i + 3 + yOffset][j + 1 + xOffset] = "*";
matrix_0[i + 3 + yOffset][j + 3 + xOffset] = "*";
matrix_0[i + 3 + yOffset][j + 4 + xOffset] = "*";
matrix_0[i + 4 + yOffset][j - 3 + xOffset] = "*";
matrix_0[i + 4 + yOffset][j - 1 + xOffset] = "*";
matrix_0[i + 4 + yOffset][j + 2 + xOffset] = "*";
// Our initial Universe array matrix_1 - all cells dead.
std::string matrix_1[univRows][univCols];
// Fill matrix_1 with " "
for (int i = 0; i < univRows; i++) {
for (int j = 0; j < univCols; j++) {
matrix_1[i][j] = " ";
}
}
//Animation loop.
for (int i = 0; i < iterations; i++) {
// Output/display matrix_0.
cout << palette(24) << "";
for (int i = 10; i < winRows + 10; i++) {
for (int j = 10; j < winCols + 10; j++) {
cout << setw(4) << matrix_0[i][j];
}
cout << endl;
}
cout << palette(1) << "";
usleep(time);
// Move cursor up above matrix_1 rendering.
cout << "\033[41A" << palette(24) << "\tYou are the winner!! For Two Full Weeks, YOU"
<< " are Ruler of the Galaxy!" << palette(1) << "\n";
//Build matrix_1 *********************************************************
// Determine change in state events.
for (int i = 1; i < 59; i++) {
for (int j = 1; j < 39; j++) {
aliveCount = 0; // Count occupied cells.
if (matrix_0[i - 1][j - 1] == "*") // Top left.
aliveCount++;
if (matrix_0[i - 1][j] == "*") // Top center.
aliveCount++;
if (matrix_0[i - 1][j + 1] == "*") // Top right.
aliveCount++;
if (matrix_0[i][j + 1] == "*") // Center right.
aliveCount++;
if (matrix_0[i][j - 1] == "*") // Bottom right.
aliveCount++;
if (matrix_0[i + 1][j + 1] == "*") // Bottom center.
aliveCount++;
if (matrix_0[i + 1][j] == "*") // Bottom left.
aliveCount++;
if (matrix_0[i + 1][j - 1] == "*") // Center left.
aliveCount++;
// Rule #1: If occupied cell has 0, 1, or > 3 neighbors it dies!
if ((matrix_0[i][j] == "*") && ((aliveCount < 2) || (aliveCount > 3))) {
matrix_1[i][j] = " ";
}
else {//Rule #2: If occupied cell has 2 or 3 neighbors it lives!
if ((matrix_0[i][j] == "*") && ((aliveCount > 1) && (aliveCount < 4))) {
matrix_1[i][j] = "*";
}
}
// Rule #3: If unoccupied cell has 3 neighbors, an '*' is "born"!
if ((matrix_0[i][j] == " ") && (aliveCount == 3)) {
matrix_1[i][j] = "*";
}
else {
if ((matrix_1[i][j] == " ") && (aliveCount != 3)) {
matrix_1[i][j] = " ";
}
}
}
}
// End matrix_1 build****************************************************
// Reset Matrix_0
for (int i = 0; i < univRows; i++) {
for (int j = 0; j < univCols; j++) {
matrix_0[i][j] = " ";
}
}
// Output/display matrix_1
cout << palette(19) << "";
for (int i = 10; i < winRows + 10; i++) {
for (int j = 10; j < winCols + 10; j++) {
cout << setw(4) << matrix_1[i][j];
}
cout << endl;
}
cout << palette(1) << "";
// Build matrix_0 *********************************************************
// Determine change in state events.
for (int i = 1; i < 59; i++) {
for (int j = 1; j < 39; j++) {
aliveCount = 0; // Count occupied cells.
if (matrix_1[i - 1][j - 1] == "*") // Top left.
aliveCount++;
if (matrix_1[i - 1][j] == "*") // Top center.
aliveCount++;
if (matrix_1[i - 1][j + 1] == "*") // Top right.
aliveCount++;
if (matrix_1[i][j + 1] == "*") // Center right.
aliveCount++;
if (matrix_1[i][j - 1] == "*") // Bottom right.
aliveCount++;
if (matrix_1[i + 1][j + 1] == "*") // Bottom center.
aliveCount++;
if (matrix_1[i + 1][j] == "*") // Bottom left.
aliveCount++;
if (matrix_1[i + 1][j - 1] == "*") // Center left.
aliveCount++;
// Rule #1: Occupied cell has 0, 1, or > 3 neighbors it dies!
if ((matrix_1[i][j] == "*") && ((aliveCount < 2) || (aliveCount > 3))) {
matrix_0[i][j] = " ";
}
else {//Rule #2: Occupied cell has 2 or 3 neighbors it lives!
if ((matrix_1[i][j] == "*") && ((aliveCount > 1) && (aliveCount < 4))) {
matrix_0[i][j] = "*";
}
}
// Rule #3: Unoccupied cell has 3 neighbors, an '*' is "born"!
if ((matrix_1[i][j] == " ") && (aliveCount == 3)) {
matrix_0[i][j] = "*";
}
else {
if ((matrix_1[i][j] == " ") && (aliveCount != 3)) {
matrix_0[i][j] = " ";
}
}
}
}
// End matrix_0 build****************************************************
// Reset matrix_1
for (int i = 0; i < univRows; i++) {
for (int j = 0; j < univCols; j++) {
matrix_1[i][j] = " ";
}
}
usleep(time);
// Move cursor up above matrix_1 rendering, clear console, user message!
cout << "\033[41A" << palette(19) << "\tYou are the winner!! For Two Full Weeks, YOU"
<< " are Ruler of the Galaxy!" << palette(1) << "\n";
} // End animation loop.
cout << palette(1) << "\033[60B";
}
|
8b89bdba9fe8f693f2ba14f5160f8a90dc6904df
|
5c23b302684f260fbbad2edfe19dd7cf16fd822c
|
/ch06/exercise_6_33.cpp
|
5bf21169bdc173eac7d7f9e2757765298b5a66cc
|
[] |
no_license
|
platoTao/CPP_Primer_Answer
|
123c99b0283ba15d51037cf16f2a6886b570d394
|
b1837239c9d58e54587f7a5ae44ee220238f5c95
|
refs/heads/master
| 2021-04-03T06:43:04.089574
| 2018-06-10T06:25:57
| 2018-06-10T06:25:57
| 124,714,759
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 343
|
cpp
|
exercise_6_33.cpp
|
#include<iostream>
#include<vector>
using namespace std;
void print(vector<int>::iterator beg,vector<int>::iterator ends){
if(beg == ends)
return;
else{
cout << *beg << " ";
return print(++beg,ends);
}
}
int main(){
vector<int> v1 = {1,2,3,4,5,6,7,8};
print(v1.begin(),v1.end());
return 0;
}
|
d32852fd8ab35f824af446a4b66acd014bedd654
|
fb5b25b4fbe66c532672c14dacc520b96ff90a04
|
/export/release/macos/obj/include/EtternaFunctions.h
|
d65808e36ea35ff81045b149285a5ebad4cafa96
|
[
"Apache-2.0"
] |
permissive
|
Tyrcnex/tai-mod
|
c3849f817fe871004ed171245d63c5e447c4a9c3
|
b83152693bb3139ee2ae73002623934f07d35baf
|
refs/heads/main
| 2023-08-15T07:15:43.884068
| 2021-09-29T23:39:23
| 2021-09-29T23:39:23
| 383,313,424
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| true
| 2,271
|
h
|
EtternaFunctions.h
|
// Generated by Haxe 4.1.5
#ifndef INCLUDED_EtternaFunctions
#define INCLUDED_EtternaFunctions
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS0(EtternaFunctions)
class HXCPP_CLASS_ATTRIBUTES EtternaFunctions_obj : public ::hx::Object
{
public:
typedef ::hx::Object super;
typedef EtternaFunctions_obj OBJ_;
EtternaFunctions_obj();
public:
enum { _hx_ClassId = 0x79c641ea };
void __construct();
inline void *operator new(size_t inSize, bool inContainer=false,const char *inName="EtternaFunctions")
{ return ::hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return ::hx::Object::operator new(inSize+extra,false,"EtternaFunctions"); }
inline static ::hx::ObjectPtr< EtternaFunctions_obj > __new() {
::hx::ObjectPtr< EtternaFunctions_obj > __this = new EtternaFunctions_obj();
__this->__construct();
return __this;
}
inline static ::hx::ObjectPtr< EtternaFunctions_obj > __alloc(::hx::Ctx *_hx_ctx) {
EtternaFunctions_obj *__this = (EtternaFunctions_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(EtternaFunctions_obj), false, "EtternaFunctions"));
*(void **)__this = EtternaFunctions_obj::_hx_vtable;
return __this;
}
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(::hx::DynamicArray inArgs);
//~EtternaFunctions_obj();
HX_DO_RTTI_ALL;
static bool __GetStatic(const ::String &inString, Dynamic &outValue, ::hx::PropertyAccess inCallProp);
static bool __SetStatic(const ::String &inString, Dynamic &ioValue, ::hx::PropertyAccess inCallProp);
static void __register();
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_("EtternaFunctions",36,00,59,c6); }
static void __boot();
static Float a1;
static Float a2;
static Float a3;
static Float a4;
static Float a5;
static Float p;
static Float erf(Float x);
static ::Dynamic erf_dyn();
static int getNotes();
static ::Dynamic getNotes_dyn();
static int getHolds();
static ::Dynamic getHolds_dyn();
static int getMapMaxScore();
static ::Dynamic getMapMaxScore_dyn();
static Float wife3(Float maxms,Float ts);
static ::Dynamic wife3_dyn();
};
#endif /* INCLUDED_EtternaFunctions */
|
b86dddbb07432228fedf10b9ced0437f92357bd8
|
d2211a60418e59cdc59528168b961600c0d06da0
|
/Engine/Igneel.D3D9/EnumConverter.cpp
|
8c467eaaa407874b0b8e8512255dce0e05b2cd22
|
[
"Apache-2.0"
] |
permissive
|
ansel86castro/Igneel
|
2bdee251d9b66760284bb65b238904a00f1217b4
|
7a1e6c81e18326aff78be97cc4321f3a610481ff
|
refs/heads/master
| 2020-01-23T21:57:10.375352
| 2018-09-07T20:18:49
| 2018-09-07T20:18:49
| 74,725,914
| 8
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,829
|
cpp
|
EnumConverter.cpp
|
#include "stdafx.h"
#include "EnumConverter.h"
#include < stdio.h >
#include < stdlib.h >
#include < vcclr.h >
D3DFORMAT GetD3DFORMAT(Format f)
{
switch (f)
{
case Igneel::Graphics::Format::UNKNOWN: return D3DFMT_UNKNOWN;
case Igneel::Graphics::Format::R16G16B16A16_FLOAT: return D3DFMT_A16B16G16R16F;
case Igneel::Graphics::Format::R16G16B16A16_TYPELESS:
case Igneel::Graphics::Format::R16G16B16A16_UINT:
case Igneel::Graphics::Format::R16G16B16A16_SINT: return D3DFMT_A16B16G16R16;
case Igneel::Graphics::Format::R8G8B8A8_TYPELESS:
case Igneel::Graphics::Format::R8G8B8A8_UNORM:
case Igneel::Graphics::Format::R8G8B8A8_UNORM_SRGB:
case Igneel::Graphics::Format::R8G8B8A8_UINT:
case Igneel::Graphics::Format::R8G8B8A8_SNORM:
case Igneel::Graphics::Format::R8G8B8A8_SINT: return D3DFMT_A8B8G8R8;
case Igneel::Graphics::Format::D32_FLOAT: return D3DFMT_D32;
case Igneel::Graphics::Format::R32_FLOAT: return D3DFMT_R32F;
case Igneel::Graphics::Format::D24_UNORM_S8_UINT: return D3DFMT_D24S8;
case Igneel::Graphics::Format::R24_UNORM_X8_TYPELESS: return D3DFMT_D24X8;
case Igneel::Graphics::Format::X24_TYPELESS_G8_UINT:return D3DFMT_A8;
break;
case Igneel::Graphics::Format::R8G8_TYPELESS:
break;
case Igneel::Graphics::Format::R8G8_UNORM:
break;
case Igneel::Graphics::Format::R8G8_UINT:
break;
case Igneel::Graphics::Format::R8G8_SNORM:
break;
case Igneel::Graphics::Format::R8G8_SINT:
break;
case Igneel::Graphics::Format::R16_TYPELESS:
break;
case Igneel::Graphics::Format::R16_FLOAT:return D3DFMT_R16F;
case Igneel::Graphics::Format::D16_UNORM: return D3DFMT_D16;
case Igneel::Graphics::Format::R8_TYPELESS: return D3DFMT_A8;
case Igneel::Graphics::Format::R8_UNORM:
case Igneel::Graphics::Format::R8_UINT:
case Igneel::Graphics::Format::R8_SNORM:
case Igneel::Graphics::Format::R8_SINT:
case Igneel::Graphics::Format::A8_UNORM: return D3DFMT_A8;
case Igneel::Graphics::Format::R1_UNORM: return D3DFMT_A1;
case Igneel::Graphics::Format::R8G8_B8G8_UNORM:
case Igneel::Graphics::Format::G8R8_G8B8_UNORM: return D3DFMT_G8R8_G8B8;
case Igneel::Graphics::Format::BC1_TYPELESS:
case Igneel::Graphics::Format::BC1_UNORM:
case Igneel::Graphics::Format::BC1_UNORM_SRGB: return D3DFMT_DXT1;
case Igneel::Graphics::Format::BC2_TYPELESS:
case Igneel::Graphics::Format::BC2_UNORM:
case Igneel::Graphics::Format::BC2_UNORM_SRGB: return D3DFMT_DXT2;
case Igneel::Graphics::Format::BC3_TYPELESS:
case Igneel::Graphics::Format::BC3_UNORM:
case Igneel::Graphics::Format::BC3_UNORM_SRGB:return D3DFMT_DXT3;
case Igneel::Graphics::Format::BC4_TYPELESS:
case Igneel::Graphics::Format::BC4_UNORM:
case Igneel::Graphics::Format::BC4_SNORM:return D3DFMT_DXT4;
case Igneel::Graphics::Format::BC5_TYPELESS:
case Igneel::Graphics::Format::BC5_UNORM:
case Igneel::Graphics::Format::BC5_SNORM: return D3DFMT_DXT5;
case Igneel::Graphics::Format::B5G6R5_UNORM: return D3DFMT_R5G6B5;
case Igneel::Graphics::Format::B5G5R5A1_UNORM: return D3DFMT_A1R5G5B5;
case Igneel::Graphics::Format::B8G8R8A8_TYPELESS:
case Igneel::Graphics::Format::B8G8R8A8_UNORM_SRGB:
case Igneel::Graphics::Format::B8G8R8A8_UNORM: return D3DFMT_A8R8G8B8;
case Igneel::Graphics::Format::B8G8R8X8_TYPELESS:
case Igneel::Graphics::Format::B8G8R8X8_UNORM_SRGB:
case Igneel::Graphics::Format::B8G8R8X8_UNORM: return D3DFMT_X8R8G8B8;
case Igneel::Graphics::Format::BC6H_TYPELESS:
break;
case Igneel::Graphics::Format::BC6H_UF16:
break;
case Igneel::Graphics::Format::BC6H_SF16:
break;
case Igneel::Graphics::Format::BC7_TYPELESS:
break;
case Igneel::Graphics::Format::BC7_UNORM:
break;
case Igneel::Graphics::Format::BC7_UNORM_SRGB:
break;
default:
throw gcnew FormatNotSupportedException(f);
break;
}
throw gcnew FormatNotSupportedException(f);
}
Format GetFORMAT(D3DFORMAT f)
{
switch (f)
{
case D3DFMT_UNKNOWN: return Format::UNKNOWN;
case D3DFMT_A16B16G16R16F: return Format::R16G16B16A16_FLOAT;
case D3DFMT_A16B16G16R16: return Format::R16G16B16A16_TYPELESS;
case D3DFMT_D32: return Format::D32_FLOAT;
case D3DFMT_R32F: return Format::R32_FLOAT;
case D3DFMT_R16F: return Format::R16_FLOAT;
case D3DFMT_D16: return Format::D16_UNORM;
case D3DFMT_D24S8: return Format::D24_UNORM_S8_UINT;
case D3DFMT_A8: return Format::R8_TYPELESS;
case D3DFMT_A1: return Format::R1_UNORM;
case D3DFMT_G8R8_G8B8: return Format::R8G8_B8G8_UNORM;
case D3DFMT_DXT1: return Format::BC1_TYPELESS;
case D3DFMT_DXT2: return Format::BC2_TYPELESS;
case D3DFMT_DXT3: return Format::BC3_TYPELESS;
case D3DFMT_DXT4: return Format::BC4_TYPELESS;
case D3DFMT_DXT5: return Format::BC5_TYPELESS;
case D3DFMT_R5G6B5: return Format::B5G6R5_UNORM;
case D3DFMT_A1R5G5B5: return Format::B5G5R5A1_UNORM;
case D3DFMT_A8R8G8B8: return Format::B8G8R8A8_UNORM;
case D3DFMT_X8R8G8B8: return Format::B8G8R8X8_UNORM;
default:
throw gcnew InvalidOperationException(L"Not D3DFORMAT Supported");
break;
}
throw gcnew InvalidOperationException(L"Not D3DFORMAT Supported");
}
void GetTextureUsage(ResourceUsage usage, BindFlags binding , CpuAccessFlags cpuAcces, OUT DWORD * d3dUsage , OUT D3DPOOL * d3dPool)
{
if((binding & BindFlags::RenderTarget) == BindFlags::RenderTarget)
{
*d3dPool = D3DPOOL_DEFAULT;
*d3dUsage = D3DUSAGE_RENDERTARGET;
}
else if((binding & BindFlags::DepthStencil) == BindFlags::DepthStencil)
{
*d3dPool = D3DPOOL_DEFAULT;
*d3dUsage = D3DUSAGE_DEPTHSTENCIL;
}
else if((binding & BindFlags::ShaderResource) == BindFlags::ShaderResource)
{
if(usage == ResourceUsage::Default)
{
*d3dPool = D3DPOOL_MANAGED;
*d3dUsage = cpuAcces == CpuAccessFlags::Write ? D3DUSAGE_WRITEONLY: 0;
}
else if(usage== ResourceUsage::Dynamic)
{
*d3dPool = D3DPOOL_DEFAULT;
*d3dUsage = D3DUSAGE_DYNAMIC;
}
else if(usage == ResourceUsage::Immutable)
{
*d3dPool = D3DPOOL_DEFAULT;
*d3dUsage = 0;
}
}
else if(usage == ResourceUsage::Staging)
{
switch (cpuAcces)
{
case Igneel::Graphics::CpuAccessFlags::None:
*d3dPool = D3DPOOL_MANAGED;
*d3dUsage = 0;
break;
case Igneel::Graphics::CpuAccessFlags::Read:
*d3dPool = D3DPOOL_SYSTEMMEM;
*d3dUsage = 0;
break;
case Igneel::Graphics::CpuAccessFlags::Write:
*d3dPool = D3DPOOL_SYSTEMMEM;
*d3dUsage = 0;
break;
default:
break;
}
}
}
DWORD GetD3DLOCK(MapType mapType , bool doNotWait)
{
DWORD flags = 0;
switch (mapType)
{
case Igneel::Graphics::MapType::Read:
flags = D3DLOCK_READONLY;
break;
case Igneel::Graphics::MapType::Write:
flags = 0;
break;
case Igneel::Graphics::MapType::ReadWrite:
flags = 0;
break;
case Igneel::Graphics::MapType::Write_Discard:
flags = D3DLOCK_DISCARD;
break;
case Igneel::Graphics::MapType::Write_No_OverWrite:
flags = D3DLOCK_NOOVERWRITE;
break;
default:
flags = 0;
break;
}
if(doNotWait)
flags |= D3DLOCK_DONOTWAIT;
return flags;
}
D3DDEVTYPE GetD3DDEVTYPE(GraphicDeviceType devType)
{
D3DDEVTYPE type;
switch (devType)
{
case GraphicDeviceType::Hardware: type = D3DDEVTYPE_HAL;break;
case GraphicDeviceType::NullReference:type = D3DDEVTYPE_NULLREF;break;
case GraphicDeviceType::Reference:type = D3DDEVTYPE_REF;break;
case GraphicDeviceType::Software:type = D3DDEVTYPE_SW;break;
}
return type;
}
D3DRESOURCETYPE GetD3DD3DRESOURCETYPE(ResourceType rsType)
{
D3DRESOURCETYPE d3dType;
switch (rsType)
{
case Igneel::Graphics::ResourceType::Unknown:
throw gcnew InvalidOperationException();
break;
case Igneel::Graphics::ResourceType::Buffer:
d3dType = D3DRESOURCETYPE::D3DRTYPE_INDEXBUFFER;
break;
case Igneel::Graphics::ResourceType::Texture1D:
d3dType = D3DRESOURCETYPE::D3DRTYPE_TEXTURE;
break;
case Igneel::Graphics::ResourceType::Texture2D:
d3dType = D3DRESOURCETYPE::D3DRTYPE_TEXTURE;
break;
case Igneel::Graphics::ResourceType::Texture3D:
d3dType = D3DRESOURCETYPE::D3DRTYPE_VOLUME;
break;
case Igneel::Graphics::ResourceType::TextureCube:
d3dType = D3DRESOURCETYPE::D3DRTYPE_CUBETEXTURE;
break;
default:
break;
}
return d3dType;
}
DWORD GetD3DUSAGE(BindFlags binding)
{
DWORD usage = 0;
switch (binding)
{
case Igneel::Graphics::BindFlags::DepthStencil: usage = D3DUSAGE_DEPTHSTENCIL;break;
case Igneel::Graphics::BindFlags::RenderTarget: usage = D3DUSAGE_RENDERTARGET;break;
}
return usage;
}
void GetBufferUsage(MapType cpuAcces , DWORD* d3dusage, D3DPOOL* pool)
{
switch (cpuAcces)
{
case Igneel::Graphics::MapType::Read:
*pool = D3DPOOL_MANAGED;
break;
case Igneel::Graphics::MapType::Write:
*pool = D3DPOOL_DEFAULT;
*d3dusage = D3DUSAGE_WRITEONLY;
break;
case Igneel::Graphics::MapType::ReadWrite:
*pool = D3DPOOL_MANAGED;
*d3dusage = 0;
break;
case Igneel::Graphics::MapType::Write_Discard:
* pool = D3DPOOL_DEFAULT;
*d3dusage = D3DUSAGE_DYNAMIC;
break;
case Igneel::Graphics::MapType::Write_No_OverWrite:
*pool = D3DPOOL_DEFAULT;
*d3dusage = D3DUSAGE_DYNAMIC;
break;
default:
break;
}
}
String^ GetErr(HRESULT x)
{
switch (x)
{
case D3DERR_DEVICELOST:return L"DEVICELOST";
case D3DERR_DEVICENOTRESET:return L"DEVICENOTRESET";
case D3DERR_DEVICEHUNG:return L"DEVICEHUNG";
case D3DERR_CONFLICTINGRENDERSTATE:return L"CONFLICTINGRENDERSTATE";
case D3DERR_CANNOTPROTECTCONTENT:return L"CANNOTPROTECTCONTENT";
case D3DERR_CONFLICTINGTEXTUREFILTER:return L"CONFLICTINGTEXTUREFILTER";
case D3DERR_CONFLICTINGTEXTUREPALETTE:return L"CONFLICTINGTEXTUREPALETTE";
case D3DERR_DEVICEREMOVED:return L"DEVICEREMOVED";
case D3DERR_DRIVERINTERNALERROR:return L"DRIVERINTERNALERROR";
case D3DERR_INVALIDCALL:return L"INVALIDCALL";
case D3DERR_DRIVERINVALIDCALL:return L"DRIVERINVALIDCALL";
case D3DERR_INVALIDDEVICE:return L"INVALIDDEVICE";
case D3DERR_OUTOFVIDEOMEMORY:return L"OUTOFVIDEOMEMORY";
case D3DERR_NOTAVAILABLE:return L"NOTAVAILABLE";
default: return L"Invalid Call";
}
}
//LPSTR ConvertToChar(String^ str)
//{
// // Pin memory so GC can't move it while native function is called
// pin_ptr<const wchar_t> wch = PtrToStringChars(str);
//
// // Conversion to char* :
// // Can just convert wchar_t* to char* using one of the
// // conversion functions such as:
// // WideCharToMultiByte()
// // wcstombs_s()
// // ... etc
// size_t convertedChars = 0;
// size_t sizeInBytes = ((str->Length + 1) * 2);
// errno_t err = 0;
// char *ch = new char[sizeInBytes];
//
// err = wcstombs_s(&convertedChars,
// ch, sizeInBytes,
// wch, sizeInBytes);
// if (err != 0)
// {
// delete ch;
// }
// return ch;
//}
|
f99a0d83d090c53dc16c32b5e1104d5e38659999
|
91a882547e393d4c4946a6c2c99186b5f72122dd
|
/Source/XPSP1/NT/inetsrv/msmq/src/admin/mqsnap/certgen.h
|
5c0cf8d09002c76e1cdaddf73c13ec08b2f18a20
|
[] |
no_license
|
IAmAnubhavSaini/cryptoAlgorithm-nt5src
|
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
|
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
|
refs/heads/master
| 2023-09-02T10:14:14.795579
| 2021-11-20T13:47:06
| 2021-11-20T13:47:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,466
|
h
|
certgen.h
|
#if !defined(AFX_CERTGEN_H__3FE71264_DA70_11D1_9C86_006008764D0E__INCLUDED_)
#define AFX_CERTGEN_H__3FE71264_DA70_11D1_9C86_006008764D0E__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// CertGen.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CCertGen dialog
class CCertGen : public CMqPropertyPage
{
DECLARE_DYNCREATE(CCertGen)
// Construction
public:
CCertGen();
~CCertGen();
void
Initialize(
CMQSigCertificate** pCertList,
DWORD NumOfCertificate
);
// Dialog Data
//{{AFX_DATA(CCertGen)
enum { IDD = IDD_USER_CERTIFICATE };
CString m_Label;
//}}AFX_DATA
// Overrides
// ClassWizard generate virtual function overrides
//{{AFX_VIRTUAL(CCertGen)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CCertGen)
virtual BOOL OnInitDialog();
afx_msg void OnCertView();
afx_msg void OnCertRemove();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
void
FillCertsList(
void
);
CListBox* m_pCertListBox;
CMQSigCertificate** m_pCertList;
DWORD m_NumOfCertificate;
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_CERTGEN_H__3FE71264_DA70_11D1_9C86_006008764D0E__INCLUDED_)
|
8098d1e757e358aff977311a7c5f48dedee07af0
|
b66eaf76662219e560eadf6e2d62b8b1a19de4f1
|
/Introduction/LinearDS/STLlist/11988.cpp
|
0e18821ca86c8fefac36a7f9eace864d6a220b5c
|
[] |
no_license
|
jPHU/CP3
|
a6d6256ea53fcbecef0af99a26ef4b3633009ea9
|
d1b8b37ef0a3896829fa5704a69b8b808056f686
|
refs/heads/master
| 2021-05-05T12:00:37.896507
| 2018-02-18T19:56:11
| 2018-02-18T19:56:11
| 118,205,699
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 727
|
cpp
|
11988.cpp
|
#include <list>
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
string input;
while(getline(cin, input) && input != "")
{
list<char> beiju;
list<char>::iterator it = beiju.begin();
for(char c : input)
{
if(c == '[')
{
it = beiju.begin();
}
else if (c == ']')
{
it = beiju.end();
}
else
{
beiju.insert(it,c);
}
}
for(char c : beiju)
{
cout << c ;
}
cout << endl;
}
return 0;
}
|
774810091b8acded36a0a6fdce133212e27c545e
|
9d364070c646239b2efad7abbab58f4ad602ef7b
|
/platform/external/chromium_org/chrome/browser/ui/libgtk2ui/g_object_destructor_filo.h
|
02c6ae9263090f0e68b963b1a40612c9c2fd277f
|
[
"BSD-3-Clause"
] |
permissive
|
denix123/a32_ul
|
4ffe304b13c1266b6c7409d790979eb8e3b0379c
|
b2fd25640704f37d5248da9cc147ed267d4771c2
|
refs/heads/master
| 2021-01-17T20:21:17.196296
| 2016-08-16T04:30:53
| 2016-08-16T04:30:53
| 65,786,970
| 0
| 2
| null | 2020-03-06T22:00:52
| 2016-08-16T04:15:54
| null |
UTF-8
|
C++
| false
| false
| 1,685
|
h
|
g_object_destructor_filo.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 CHROME_BROWSER_UI_LIBGTK2UI_G_OBJECT_DESTRUCTOR_FILO_H_
#define CHROME_BROWSER_UI_LIBGTK2UI_G_OBJECT_DESTRUCTOR_FILO_H_
#include <glib.h>
#include <list>
#include <map>
#include "base/basictypes.h"
template <typename T> struct DefaultSingletonTraits;
typedef struct _GObject GObject;
namespace libgtk2ui {
class GObjectDestructorFILO {
public:
typedef void (*DestructorHook)(void* context, GObject* where_the_object_was);
static GObjectDestructorFILO* GetInstance();
void Connect(GObject* object, DestructorHook callback, void* context);
void Disconnect(GObject* object, DestructorHook callback, void* context);
private:
struct Hook {
Hook(GObject* o, DestructorHook cb, void* ctx)
: object(o), callback(cb), context(ctx) {
}
bool equal(GObject* o, DestructorHook cb, void* ctx) const {
return object == o && callback == cb && context == ctx;
}
GObject* object;
DestructorHook callback;
void* context;
};
typedef std::list<Hook> HandlerList;
typedef std::map<GObject*, HandlerList> HandlerMap;
GObjectDestructorFILO();
~GObjectDestructorFILO();
friend struct DefaultSingletonTraits<GObjectDestructorFILO>;
void WeakNotify(GObject* where_the_object_was);
static void WeakNotifyThunk(gpointer data, GObject* where_the_object_was) {
reinterpret_cast<GObjectDestructorFILO*>(data)->WeakNotify(
where_the_object_was);
}
HandlerMap handler_map_;
DISALLOW_COPY_AND_ASSIGN(GObjectDestructorFILO);
};
}
#endif
|
6a829dda3c55e28b88579ba8cdcd5ef30fabe7e5
|
39e1131c46c2c934b758638e0b13b59b01a28df6
|
/semana1/main.cpp
|
85815697a70fb1234fb4f75ce89c3a3504446223
|
[] |
no_license
|
ator89/clasesP3
|
ab88bae53670066306e0990c0a9e05be2afeb1b1
|
5e3f70dd79d0ffb70043e4854a5230f47796a8b1
|
refs/heads/master
| 2020-04-01T10:47:04.253359
| 2019-01-30T19:25:47
| 2019-01-30T19:25:47
| 153,131,551
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 542
|
cpp
|
main.cpp
|
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
int main(){
int numero;
char opcion;
do{
cout << "Ingrese un numero: "<< endl;
cin >> numero;
if(numero < 0){
cout << "Ingrese solo positivos."<<endl;
}else{
for(int i=1; i<=numero; i++){
cout << " " << i;
}
cout <<endl;
}
cout << "Desea continuar? (s/n)"<<endl;
cin >> opcion;
}while (opcion != 'n');
cout << "Programa terminado con éxito\n";
return 0;
}
|
56242da78516452c139963d29353b88957369c9f
|
7556139eba33cbbbf0e0262c69e9c8b56e08a399
|
/include/RED4ext/Scripting/Natives/Generated/input/InputSystemWin32Base.hpp
|
290fb6cba4d2be26d70c27d444948c9c68db87bf
|
[
"MIT"
] |
permissive
|
vandermerwewaj/RED4ext.SDK
|
3ef7563a1855e6206097fdf6c5b44ae1c1c2c20d
|
9dd544a221a39f27c8d38aa23a607b31aba1715a
|
refs/heads/master
| 2023-09-05T06:32:39.278419
| 2021-11-22T15:01:18
| 2021-11-22T15:01:18
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 540
|
hpp
|
InputSystemWin32Base.hpp
|
#pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/Scripting/Natives/Generated/input/IInputSystem.hpp>
namespace RED4ext
{
namespace input {
struct InputSystemWin32Base : input::IInputSystem
{
static constexpr const char* NAME = "inputInputSystemWin32Base";
static constexpr const char* ALIAS = NAME;
uint8_t unk140[0x178 - 0x140]; // 140
};
RED4EXT_ASSERT_SIZE(InputSystemWin32Base, 0x178);
} // namespace input
} // namespace RED4ext
|
1889b447ea9a77e3af7cd9745532e7c0a8d09194
|
9d96add1aa91b24d47b671bb6dabbc0f7335c0a9
|
/base/string16.h
|
0cf5804b2cc6cd08bc37b284d284bb05c91fae2c
|
[] |
no_license
|
shangsh/chromium_ui
|
eff0fdde5da038b98485ec78cb9a5314e99c71b8
|
c9dd9643247b2ce824ca8d6164604ee3dfdbc1bb
|
refs/heads/master
| 2022-11-18T00:18:03.039532
| 2020-07-18T09:30:09
| 2020-07-18T09:30:09
| 280,623,231
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 171
|
h
|
string16.h
|
#ifndef __string16_h__
#define __string16_h__
#pragma once
#include <string>
typedef wchar_t char16;
typedef std::wstring string16;
#endif //__string16_h__
|
b2aa5159195e52fefbb243beaf3317147331f0a0
|
b3cef08db0c047ddf3e608048b6a2422b1aeecd0
|
/dependencies/include/Utilities/EdeficeCommon/BasicTString.h
|
fac87a4d5a3f3e7187603f9a1205274b836e9378
|
[] |
no_license
|
benagain/CredProv
|
5668eadbb07ad8784179e4ae7026e02fe9646dfa
|
e9ff80af69ef2b46cba9ab33f1091a2135b277b0
|
refs/heads/master
| 2021-09-10T21:55:55.821741
| 2018-04-02T20:41:40
| 2018-04-02T20:41:40
| 127,474,144
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 351
|
h
|
BasicTString.h
|
#pragma once
#include <string>
#include <tchar.h>
namespace EdeficeCommon {
#ifdef _UNICODE
typedef std::wstring tstring;
typedef std::wstringstream tstringstream;
#else
typedef std::string tstring;
typedef std::stringstream tstringstream;
#endif
}
namespace eUtil {
using EdeficeCommon::tstring;
using EdeficeCommon::tstringstream;
}
|
2bfe24203e47a8881485f1ea081ce6d91f05d23e
|
4bea57e631734f8cb1c230f521fd523a63c1ff23
|
/projects/openfoam/rarefied-flows/hyperCavity/test_case/0.00034/linearKE
|
b71831a5fca8abceae2cbb8f446b7d0fb29245a6
|
[] |
no_license
|
andytorrestb/cfal
|
76217f77dd43474f6b0a7eb430887e8775b78d7f
|
730fb66a3070ccb3e0c52c03417e3b09140f3605
|
refs/heads/master
| 2023-07-04T01:22:01.990628
| 2021-08-01T15:36:17
| 2021-08-01T15:36:17
| 294,183,829
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 16,408
|
linearKE
|
/*--------------------------------*- 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 "0.00034";
object linearKE;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [1 -1 -2 0 0 0 0];
internalField nonuniform List<scalar>
1300
(
0
6013.260128
4960.955313
111824.104
62703.64078
6996.125846
40354.68654
51798.39538
31189.00114
18547.62439
3374.046684
1747.082488
39976.88148
107936.6742
129389.1076
18935.9802
46543.94212
58111.35266
39171.94829
14971.07925
176.6340348
4583.870151
25967.7827
177408.3155
89643.91464
39491.13564
46157.02894
88928.72043
48816.49546
54517.72367
0
2647.796711
9273.246802
165172.4563
25943.86444
50318.91911
134281.6734
143334.4018
107153.354
43661.73815
0
2418.3448
35513.29642
166471.3728
107399.1352
14361.15928
82315.83988
93055.65511
55884.55025
29543.52722
0
0
38258.18624
193106.2647
102760.7914
13745.58808
61565.51362
130588.7957
119152.1797
115636.5447
1538.85
2217.458294
31537.06962
178261.6765
64860.57696
29770.59174
77369.57192
61586.12865
56407.46035
90106.64963
0
0
19165.06544
186007.9438
112827.4598
10081.8048
96598.17534
124296.7112
105356.1576
66324.78102
0
0
7494.681589
225554.5841
84636.73268
38239.67051
81106.89642
110394.38
27269.40474
47966.8827
0
0
15362.04142
165529.5614
65627.96347
23448.85058
95132.27011
165030.1931
40623.36526
73967.47262
0
0
38157.05194
166686.9634
70407.16395
20726.3239
68977.2749
116814.5914
116360.9544
44908.39556
0
0
34463.31441
179751.6109
136354.3756
23947.6782
75893.27691
102720.6276
61647.43976
37616.02362
0
2838.704236
24738.08186
171495.2696
103877.3699
32513.70695
75042.70536
149798.4551
33411.99665
97334.1343
0
0
25632.57648
173678.0193
79417.31189
16429.21936
39952.43657
129458.0693
23671.52083
51418.31406
0
0
24241.21915
200796.8016
94235.86935
38686.23443
71221.36959
123024.4415
83758.38016
84199.13648
0
0
41248.10506
147225.727
86973.25612
4825.124184
22791.06375
119575.9667
90757.42983
57446.73433
0
0
17824.79234
159778.9093
75911.09701
24556.17607
111809.3947
103504.7614
79853.1878
126823.4148
0
0
54245.69505
160946.8388
137418.0936
28102.99404
43418.77731
112731.4454
101753.9582
38940.71887
0
0
38663.84607
160552.2181
99029.25431
23410.64894
89694.52857
127450.0893
122460.6604
75209.28292
0
0
29610.33078
140007.0924
103225.5982
13053.36394
75280.16029
109991.101
61914.92419
97150.24493
14691.16028
14629.60675
20157.98418
15321.16485
14552.06379
13475.34303
3371.843131
16559.93883
18130.17535
6188.633808
8321.426529
15970.66039
3257.854568
5955.07023
6995.480511
16213.01241
14818.2777
12048.24113
28384.51548
2752.115731
12659.21464
10801.13624
10111.01556
12733.62458
10332.22195
10318.79739
13370.10375
7667.060465
14680.64107
5793.677384
8840.590932
27649.22932
13928.03744
25977.4632
29495.16173
30072.71134
8405.367203
16812.01208
14360.63409
17833.75293
32631.49052
20299.61014
8227.986165
11407.67385
22893.65931
18707.89331
14341.56061
18780.52031
23483.54484
9981.262321
10847.90006
6010.91459
11384.80045
17867.06417
16983.88355
38699.70277
19284.38424
16332.92813
10630.5784
21079.74013
47427.56204
131351.817
27598.5696
16095.45648
27171.44266
52943.52133
35458.40315
15668.21456
29411.57423
31518.16869
27592.71997
31846.55796
16294.00053
21098.58083
12358.51426
18132.52377
29642.82408
19816.20778
24242.34653
11067.21406
26571.54698
9590.194432
9820.515286
9321.339891
2500.718532
25315.92
9423.090034
7627.446443
9174.077159
12332.38747
60052.27783
43673.28862
35328.24784
43016.90705
48517.96862
15589.49581
47629.88556
21500.69033
56154.24677
46478.58048
32819.39457
47958.83252
25801.94326
17801.45246
24650.18506
21446.89074
18479.68024
14540.15616
23745.75421
29674.9969
31431.41299
17048.98707
13254.75725
38888.78389
26900.29087
17448.57739
13635.61903
17648.62463
16945.37874
8046.296478
91319.80253
103393.1497
96004.14942
70716.93354
118911.0967
40016.17938
55319.09044
60989.00056
39894.1873
48708.55482
40951.45789
28527.54145
34441.46945
33445.37496
58272.1491
22953.28347
38337.34092
48780.48739
14049.44372
52602.67726
42992.46513
11502.14162
29701.8112
28304.29656
29606.95065
21410.90294
25154.42852
19098.93195
22047.28382
15718.84039
88925.25179
100923.0937
82913.89517
111076.4801
65028.81973
50404.81232
66451.87037
84717.35144
44252.24723
37329.76011
59087.1642
23212.77668
39175.24695
55015.25757
30851.73999
27609.06869
45232.71703
36346.701
44740.90355
34318.95095
24608.57356
24341.99647
28747.30715
39842.95387
17663.04038
36958.8647
20844.31437
25453.19948
34635.82373
25833.39564
88525.7723
117088.6537
66461.89741
83100.3653
84268.92334
63200.37778
74684.00533
75904.50533
146715.0611
44993.71027
59932.94192
63444.59436
102819.0799
37231.65413
72409.84747
53104.89532
36685.37829
63865.38985
32843.88593
25486.41534
49350.90178
11924.00817
46225.60639
39240.83846
24357.07944
42334.94419
37495.02062
52125.93198
31137.9456
24146.29945
127519.7038
69865.45599
99046.61172
92425.0948
156115.604
50044.83051
75452.79451
67492.94699
76874.87631
67173.00587
68202.42425
98568.27313
61101.68924
79171.2765
53730.29937
72458.50961
63845.22864
102801.8373
80358.60698
37246.55607
33297.62184
25712.6943
57105.99014
32306.51009
64234.78735
47934.83567
45337.96357
58400.38191
39702.05708
41895.20974
83576.71956
124290.0235
102034.0686
113992.7363
128199.53
69149.6746
117145.0093
82356.267
101960.7325
101148.2035
80020.59155
83677.1003
76661.92073
63814.23166
56215.95791
62364.80474
80965.43868
90258.06641
98489.40985
105796.1085
52819.80482
77269.23667
26807.73747
59923.74507
72931.48616
98132.42416
38637.00239
57178.12006
29701.55615
45397.55236
42702.7553
78775.75659
43680.69807
62712.80848
61232.75123
35064.08984
54645.60836
54496.79227
51889.80515
100936.8206
79150.18656
137508.5077
122352.8272
63796.18491
53092.40719
110591.6995
61469.28167
41164.16801
93128.4541
45202.06874
68160.00137
49767.35091
122463.9739
52333.38218
69105.74723
33451.28793
48605.33555
28617.42794
21892.78547
45061.06964
93577.31133
70023.95587
93498.66998
67984.47834
84158.76841
85602.31704
77727.79536
88821.6633
108172.4899
74063.77104
68271.63613
83282.06968
74617.94182
50176.24918
70176.85677
51658.2492
138820.4822
118329.9819
69847.60155
91988.38964
52367.22763
117070.8441
112215.8636
54398.1029
61220.19138
89684.11359
41802.00535
60620.18289
63374.02395
47968.68139
52979.35142
95721.55803
43367.36238
67012.87008
55228.73884
121958.6467
75265.50213
116756.5071
67835.23333
42541.52373
74281.30491
145796.5197
136698.6552
81648.08176
53151.11093
105296.3507
127120.7942
77359.47332
86445.84086
83492.81206
127080.555
74947.61984
88146.93788
52514.58744
72163.18423
71694.52744
69811.52674
62425.70862
60917.21836
32182.00826
89899.29884
103709.5576
106177.2407
73856.9677
109526.6183
111096.1633
133863.431
59946.59561
60713.58374
65703.21222
99524.99781
75132.05015
83944.09858
50581.10437
165147.8141
117394.7192
155628.8955
114752.8571
109460.2483
79048.45999
116981.67
113679.9081
75926.89435
102276.9978
75323.67328
86971.53985
56773.55205
22708.78333
26157.57208
131993.8913
69432.67624
57429.67393
110427.8432
102587.8205
76140.02519
126942.882
97553.33989
96263.45352
88760.69371
73369.22504
53785.46421
125605.7337
62857.69382
112916.9143
83200.41098
121177.5427
145338.5679
75699.81056
81279.49942
111616.6418
81223.49335
95372.30402
68314.15603
79530.00986
95912.30708
71849.75544
71556.40182
81222.53451
103950.8823
55698.30907
70520.45649
133607.0217
116801.0494
86073.43897
127943.0935
46343.00727
84757.36994
57853.27807
104306.3021
97866.82127
123106.4977
90807.77642
74349.04021
66884.08644
54030.78318
142428.2409
48942.0936
104990.7291
145337.9695
63905.72234
92815.52431
95992.4066
97099.98559
84827.73147
146069.4226
75190.44267
83643.36344
74786.3637
73760.88789
48752.79619
66584.08054
73205.64863
60048.95577
67148.41079
72509.35253
44981.07093
68740.85051
62387.20609
21393.26112
89885.59763
106016.1899
93606.47017
90864.6233
88901.95144
75648.57905
119463.7709
99583.90724
91471.74902
83398.92501
86062.01137
65989.56292
78264.90456
141994.8904
96204.93123
113823.837
73526.41785
144969.1768
74853.03526
127266.7113
100883.8303
62050.89785
77301.44375
78759.49097
86184.43441
56230.87202
109437.5138
30487.61284
118945.1772
86253.86829
40129.02317
95415.85791
87203.6131
88832.47957
94276.40684
54162.44825
80048.7191
85587.36016
102925.7415
62026.37271
159985.6192
55818.92732
112025.1341
108500.0396
107001.2676
121468.3852
126057.3148
95996.77152
106129.1853
113703.5382
91983.61547
82564.12718
102563.4346
121182.0387
82044.72085
115781.2473
91904.81067
68309.22926
73473.04034
83781.33318
63652.57032
74627.84266
100270.2476
92094.89161
86225.31577
67044.6193
81767.36766
60811.80982
98420.59537
84947.72623
62489.16741
65520.27719
102096.0559
106004.8604
102430.4514
61337.91085
54629.63578
152530.1275
90869.39592
153383.9082
144554.6159
99050.70112
114500.4806
56268.17436
38225.00749
88693.39925
77588.56739
87616.34382
128406.0799
88860.28123
58901.98227
91031.7453
25519.90361
71383.98727
81426.27061
94515.22211
67581.50758
133868.593
70415.1226
82605.25141
85618.18104
49594.90326
86119.94133
67214.57741
94054.15962
85504.36283
83641.44351
107870.8459
73520.31465
111210.2988
99083.90306
52488.31304
91890.87844
87076.46859
82418.18775
40957.0808
49232.07614
89734.93416
48039.49696
91663.66285
93271.96488
95855.20284
64370.12008
96589.05456
97658.461
108844.2623
83550.1376
106987.7286
69601.54957
128113.6342
61203.07832
65312.43861
84617.26893
94850.77318
139753.763
59244.6116
102327.8072
56395.61774
69548.21747
144525.4079
56823.38796
9727.616219
5541.979762
10047.60498
10850.89746
10931.27148
6569.382445
6327.889263
2358.116032
3961.692051
7954.176001
18480.83037
18745.30598
20211.9518
13012.61112
5526.979155
8046.625491
14293.43764
13412.96563
19167.95432
5287.672019
18500.66609
20517.65087
21095.45514
11595.74681
16569.69077
6956.829958
14317.27606
11679.39255
11511.00392
7852.853272
13593.42708
3772.039199
16495.50122
23536.15891
15115.68361
8533.825039
5919.407339
8455.372322
12191.24315
25040.68996
30364.42399
28561.30252
2756.682937
20260.70971
6581.735586
10853.41211
24352.94845
7086.030301
8929.353036
15294.19597
23970.80434
19600.28982
20871.27599
9360.32762
12028.2573
10567.39047
16870.37133
15097.69185
23092.18416
13840.6773
27232.41206
28445.63241
18297.97036
21640.77009
32051.07502
14842.89859
7569.228171
28165.29576
32566.6385
17888.83501
26786.56657
27149.66933
21586.32744
16290.40293
25084.63261
12620.26365
17520.04448
25125.09556
22600.64825
11649.27834
55841.63629
27285.73555
21865.09663
43229.49124
48965.50395
9369.232807
12048.95793
15764.63045
21454.88828
16517.59488
57357.21301
52537.46641
39980.399
33805.59786
39120.35957
23500.76863
28826.57913
31052.6409
66616.95107
30177.9291
48183.36881
68725.06207
37097.05095
31740.24585
33429.62481
60195.15699
38437.91845
47933.09407
32203.45111
33777.83806
72853.21887
30905.50718
52460.14243
68502.78616
33472.88653
75366.64639
32851.92696
39296.5795
50731.42093
20835.97703
42066.69095
80449.1783
59106.33857
61040.10966
88499.1791
90294.59997
30397.82408
18198.44577
60636.65656
21681.35001
157287.3875
37575.99918
38191.2079
86478.25475
50272.68635
75182.43939
54599.7088
61489.72392
62155.79503
81890.715
140771.9479
62273.58707
95447.89202
86348.12554
60364.7772
100645.0044
61254.77894
39139.94458
47921.57079
84210.67606
46559.04771
76161.17327
46499.71334
88760.297
138036.3848
121795.5389
24052.56362
101355.0221
71565.71126
47931.4936
80784.42554
73290.28909
55119.98788
120693.6812
99174.44863
161210.7055
124312.7745
117310.5072
117198.8617
89944.05261
99150.03229
73748.05611
104116.3253
103381.9924
81455.24906
115640.0476
104183.4561
117361.1849
137467.9468
117246.5788
113461.0587
141913.0442
93602.05649
101853.765
164542.7352
148287.7506
119015.8171
122550.5376
109663.2243
119754.1731
134120.8894
81541.3916
120679.4611
132155.5318
138988.7905
124248.1455
104752.9224
91527.48357
141563.4845
123826.5867
1385.995974
7714.472457
9160.416413
2090.899198
15020.78441
9078.499138
9049.680776
2837.090237
12399.4438
4534.874098
6968.90324
9246.39212
4258.72572
17805.34388
9572.690118
6645.060739
10304.8504
10879.51459
11872.23993
9665.157508
7014.064977
3094.517559
4775.908954
5138.354472
16050.82365
14062.39994
6680.212955
11272.23913
6457.72307
10321.28721
15864.80492
11378.0357
6678.697526
11362.39883
15520.72575
1974.731357
14174.77265
14395.86154
6286.503287
11834.75297
9781.002833
12003.46204
10760.91227
11274.00056
8035.949275
7933.600759
9870.229932
7183.302429
11405.5164
8763.966111
11591.86605
10878.76821
9901.096348
12357.70697
18676.95954
9246.777195
23866.71708
4996.412111
20897.89962
6829.056367
8571.430742
13146.94718
6327.191224
9924.059403
11955.82026
7348.931985
7639.936841
3414.796653
15845.21129
7162.435677
7427.821217
16178.61726
1918.688527
10662.84281
8940.476026
13030.88112
11792.9188
10363.52424
5655.271171
7345.514975
10377.00401
1468.42133
8698.047743
20488.49309
6400.797685
19709.23341
6587.105559
16390.70699
5310.29673
8595.160111
11478.50563
6313.18802
11490.85802
16127.22645
8326.03324
16249.99418
6445.469074
5166.486012
6453.867936
9848.100935
12995.10664
3011.281997
14184.94027
10023.24379
7763.144736
8115.171813
6186.892404
10712.47155
3486.021218
4024.953341
3786.575367
14281.89402
14060.52784
24011.26924
14665.78018
26614.11769
17269.25822
14267.87636
18527.45127
13368.03083
6738.565401
6518.679793
12405.81046
9944.892306
6080.440963
12255.97426
7236.09641
4411.55952
11325.12555
5825.456633
6547.468542
7087.604999
6826.085328
17635.26313
13636.89374
9328.158525
10508.39753
23106.06541
8994.735074
20771.89952
13178.92952
2762.079372
12237.37875
17506.9314
9993.798139
2634.717422
6061.900552
11619.98865
9519.987328
12415.53781
4429.012163
5913.251143
13077.65923
4364.344284
5458.74838
5831.217552
5265.733345
6231.642226
8041.847659
4540.879974
10877.68996
15029.55875
6954.822694
2080.39074
9712.489431
12253.91066
10803.2114
8368.629793
21645.07657
6462.326694
5292.774714
9593.438912
7825.168826
13559.69305
8194.419923
16194.7967
9934.709091
13679.26211
20608.14055
11290.2187
1939.024675
13177.86721
15527.88798
7270.974945
14140.45287
8880.51996
11489.84552
8405.599717
3842.714208
12714.04741
13030.10812
12712.44665
12122.0091
11136.96487
12255.53455
12191.10086
9103.795892
21490.61784
7099.525431
24122.48266
4346.99162
14273.37915
14933.52287
5002.936149
8939.312614
17495.11765
21994.83881
11279.99836
14926.99482
8152.094428
2974.424655
6535.517458
2803.125297
6255.879753
15830.60302
12722.00374
11831.69601
17718.20445
7270.196606
8625.460634
10402.21967
7725.294329
14726.78339
5767.162564
12252.97722
8848.392367
19053.45438
22382.87077
14148.94584
3305.16138
11944.0017
5472.529946
13023.17152
20200.0861
15456.51445
3705.037618
19696.83841
7121.85543
6599.619207
3492.487041
5719.615927
9267.838787
5195.017189
8789.695604
12620.42588
6104.719573
8808.442875
17994.27687
11259.1644
6772.619158
10884.84275
11899.75945
13951.82032
20157.54954
14706.29583
11505.35339
1265.079859
12522.57368
11324.12187
6561.952344
11994.36132
14065.49682
16534.22364
18317.87021
16764.51336
10679.54866
19649.14703
20353.15701
5138.297462
5485.669838
13000.41904
8642.7789
8789.708935
8289.345971
11271.11867
15668.98878
6356.894534
6770.606264
9718.139638
12746.55127
9866.221596
6875.278083
15321.0815
6214.473388
21660.63179
14928.4217
8502.27639
10751.49517
16040.84186
6360.09554
6693.696264
14185.19601
4814.709609
10160.32033
7329.270072
4164.921531
18148.73947
11177.2501
19428.94414
12267.99195
)
;
boundaryField
{
inlet
{
type zeroGradient;
}
outlet
{
type zeroGradient;
}
wall
{
type calculated;
value uniform 0;
}
frontAndBack
{
type empty;
}
}
// ************************************************************************* //
|
|
96c14ced1e63da7d2b1aa1c74ea7bd35ddc9293e
|
e8e25b6152e01e4f6de80524e44f874392825b71
|
/Engine/Renderer/FrameTimer.cpp
|
108c422a5d15fffca958ef63867c316de8e1cb72
|
[] |
no_license
|
BenPowellDev/RelicHuntersSEG
|
0bf43252cae6179e60edd3943d557268601a31b2
|
9a7c91222d3b851ac69b47b1a5bd241eb6903842
|
refs/heads/main
| 2023-04-30T17:37:13.709324
| 2021-05-12T10:19:11
| 2021-05-12T10:19:11
| 366,674,370
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 717
|
cpp
|
FrameTimer.cpp
|
#include "FrameTimer.h"
#include <iostream>
const double TARGET_FRAMETIME = 1.0 / 60.0;
FrameTimer::FrameTimer()
{
}
FrameTimer::~FrameTimer()
{
}
void FrameTimer::Initialise()
{
m_ElapsedTime = 0.0;
QueryPerformanceFrequency(&frequency);
//start the timer
QueryPerformanceCounter(&lastTime);
}
void FrameTimer::StartFrame()
{
QueryPerformanceCounter(¤tTime);
}
void FrameTimer::EndFrame()
{
do
{
QueryPerformanceCounter(¤tTime);
m_ElapsedTime = ((currentTime.QuadPart - lastTime.QuadPart) * 1.0) / frequency.QuadPart;
} while (m_ElapsedTime < TARGET_FRAMETIME);
m_CurrentFPS = (float)(1.0 / m_ElapsedTime);
lastTime = currentTime;
}
|
4c25e483ffec7fa4bb65b47cc5125fb1053beef7
|
d7085a2924fb839285146f88518c69c567e77968
|
/KS/SRC/ks/files_frontend.cpp
|
e3423c97118f004c288c54918338ece59e74537f
|
[] |
no_license
|
historicalsource/kelly-slaters-pro-surfer
|
540f8f39c07e881e9ecebc764954c3579903ad85
|
7c3ade041cc03409a3114ce3ba4a70053c6e4e3b
|
refs/heads/main
| 2023-07-04T09:34:09.267099
| 2021-07-29T19:35:13
| 2021-07-29T19:35:13
| 390,831,183
| 40
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,169
|
cpp
|
files_frontend.cpp
|
// front end files
// With precompiled headers enabled, all text up to and including
// the following line are ignored by the compiler (dc 01/18/02)
#include "global.h"
#include "globaltextenum.cpp"
#include "boarddata.cpp"
#include "FEPanel.cpp"
#include "FEAnim.cpp"
#include "FEMenu.cpp"
#include "tutorialmanager.cpp"
#include "igolearn_new_trickmanager.cpp"
#include "igoiconmanager.cpp"
#include "igohintmanager.cpp"
#include "igo_widget.cpp"
#include "igo_widget_simple.cpp"
#include "igo_widget_meterchallenge.cpp"
#include "igo_widget_analogclock.cpp"
#include "igo_widget_skillchallenge.cpp"
#include "igo_widget_specialmeter.cpp"
//#include "igo_widget_breakindicator.cpp"
#include "igo_widget_waveindicator.cpp"
#include "igo_widget_balance.cpp"
#include "igo_widget_splitter.cpp"
#include "igo_widget_fanmeter.cpp"
#include "igo_widget_camera.cpp"
#include "igo_widget_objectalert.cpp"
#include "igo_widget_photo.cpp"
#include "igo_widget_replay.cpp"
#include "igo_widget_splitmeter.cpp"
#include "igo_widget_splitscore.cpp"
#include "igo_widget_splitclock.cpp"
#include "igo_widget_timeattack.cpp"
#include "igo_widget_iconcount.cpp"
#include "igo_widget_iconradar.cpp"
#include "igo_widget_grid.cpp"
#include "IGOFrontEnd.cpp"
#include "MainFrontEnd.cpp"
#include "SurferFrontEnd.cpp"
#include "Map.cpp"
#include "BeachFrontEnd.cpp"
#include "TrickBookFrontEnd.cpp"
#include "FrontEndManager.cpp"
/*#ifdef TARGET_XBOX
#include "HWOSXB\xb_SaveLoadFrontEnd.cpp"
#else*/
#include "SaveLoadFrontEnd.cpp"
//#endif
#include "GameData.cpp"
#ifdef TARGET_GC
#include "GCMCDetectFrontEnd.cpp"
#endif
#include "MCDetectFrontEnd.cpp"
#include "FrontEndMenus.cpp"
#include "BoardFrontEnd.cpp"
#include "StatsFrontEnd.cpp"
#include "ExtrasFrontEnd.cpp"
#include "MultiFrontEnd.cpp"
#include "GraphicalMenuSystem.cpp"
#include "FEEntityManager.cpp"
#include "PlaylistMenu.cpp"
#include "HighScoreFrontEnd.cpp"
#include "PhotoFrontEnd.cpp"
#include "TutorialFrontEnd.cpp"
#include "CheatFrontEnd.cpp"
#include "AccompFrontEnd.cpp"
#include "PAL60FrontEnd.cpp"
#include "LogbookFrontEnd.cpp"
|
ab8217c8b8262313b942b7c3feb2526e1955242e
|
eef061820925a2c30599aa244f3a4716f4e469f9
|
/RangoShooter/3dHelperClasses.cpp
|
e88558622e0719298b065f0c88df334e0751dc90
|
[] |
no_license
|
licnep/RangoShooter
|
56b9c5b040abea804d20fa7ba1dbd55920345594
|
b69d1c79ada63c5e2aac7f6c589d70d5ed13e5d8
|
refs/heads/master
| 2016-09-06T18:26:58.980005
| 2013-07-21T15:28:16
| 2013-07-21T15:28:16
| 11,183,122
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,629
|
cpp
|
3dHelperClasses.cpp
|
#include "loader.h"
#include "3dHelperClasses.h"
float linearInterpolation(float start,float end, float percent)
{
return start+percent*(end-start);
}
void translateRotate(locRot r) {
glTranslatef(r.x,r.y,r.z);
glRotatef(r.x_rot,1.0,0.0,0.0);
glRotatef(r.y_rot,0.0,1.0,0.0);
glRotatef(r.z_rot,0.0,0.0,1.0);
}
void animation::setup(locRot end_locRot, int duration_milliseconds, std::chrono::time_point<std::chrono::system_clock> start_time = std::chrono::system_clock::now()) {
this->end_locRot = end_locRot;
this->start_time = start_time;
//end_time = std::chrono::system_clock::now();
this->end_time = start_time + std::chrono::milliseconds(duration_milliseconds);
this->duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count();
finished = false;
}
locRot animation::getLocRot() {
double tempo_trascorso = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start_time).count();
if (tempo_trascorso<0) return locRot(); //ritorna 0,0,0... se l'animazione non e' ancora iniziata
double percentage = tempo_trascorso/duration;
if (percentage>=1)
{
finished = true;
return end_locRot;
}
//std::cout << "percent: " << percentage << std::endl;
locRot lr;
lr.x = linearInterpolation(0,end_locRot.x,percentage);
lr.y = linearInterpolation(0,end_locRot.y,percentage);
lr.z = linearInterpolation(0,end_locRot.z,percentage);
lr.x_rot = linearInterpolation(0,end_locRot.x_rot,percentage);
lr.y_rot = linearInterpolation(0,end_locRot.y_rot,percentage);
lr.z_rot = linearInterpolation(0,end_locRot.z_rot,percentage);
return lr;
}
|
2491e64ff46177abf98578fe0f1d838f5d81c9c8
|
c6bddd88916e6c8697a9e02485bd22c58d76bcec
|
/GeneratedPlaceholders/Engine/MaterialExpressionStaticBool.h
|
7364f810d2bee44934dcff1b7a2c8c89b222513b
|
[] |
no_license
|
GIRU-GIRU/Mordhau-Unofficial-SDK
|
18d13d62d746a838820e387907d13b0a37aed654
|
f831d7355cf553b81fb6e82468b3abf68f7955aa
|
refs/heads/master
| 2020-07-06T03:36:48.908227
| 2020-04-22T13:54:00
| 2020-04-22T13:54:00
| 202,872,898
| 7
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 281
|
h
|
MaterialExpressionStaticBool.h
|
#pragma once
#include "CoreMinimal.h"
#include "MaterialExpressionStaticBool.generated.h"
UCLASS()
class UMaterialExpressionStaticBool : public UMaterialExpression
{
GENERATED_BODY()
public:
UPROPERTY(Replicated, EditAnywhere, BlueprintReadWrite)
unsigned char Value : 1;
};
|
ce42656f295cf01fb388e94eac81502da093536d
|
d58c240d46a77f04f7dbda6a4ccbf77777fb08f3
|
/createll.hpp
|
8fc55cdca7f67ffc8a32fb0169e27570e0b170ca
|
[] |
no_license
|
joshianshul2/Linked-List
|
968e7126fa231f08ed6a42c385286cfa3342f1e5
|
7a7156ccf794d026a962f41e69903cca3e1368a3
|
refs/heads/master
| 2022-04-18T20:53:40.999946
| 2020-04-18T18:21:15
| 2020-04-18T18:21:15
| 256,822,968
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 221
|
hpp
|
createll.hpp
|
//
// createll.hpp
// LL
//
// Created by Anshul joshi on 18/04/20.
// Copyright © 2020 Anshul joshi. All rights reserved.
//
#ifndef createll_hpp
#define createll_hpp
#include <stdio.h>
#endif /* createll_hpp */
|
9a6972b9ffa1f273fd9c92db7db405d7de2ea021
|
a58b889171c57b8509c72b9b122b31faf975ffae
|
/完全数.cpp
|
159616f0191cde3a22a3d788f7ef1c6d30d60fdf
|
[] |
no_license
|
Lstaras/C-practices
|
8e8aa0764bd0d63d1f43ffc000ceb2ef57af260d
|
af27d53584f6e7f22ee3e76a45bf714a18cfe8d9
|
refs/heads/master
| 2020-04-26T09:13:25.607738
| 2019-03-28T14:09:06
| 2019-03-28T14:09:06
| 173,448,259
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 547
|
cpp
|
完全数.cpp
|
//完全数:如果一个数恰好等于它的因子之和,则称该数为"完全数"
//它所有的真因子(即除了自身以外的约数)的和(即因子函数),恰好等于它本身。
#include<stdio.h>
int isPerfect(int n){
int i;
int sum = 0;
if (n<=0){
return 0;//
}else{
sum = 0;
for (i = 1; i < n; ++i){
if (n%i==0)
{
sum+=i;
}
}
}
if (sum==n)
{
return 1;
}else{
return 0;
}
}
int main(int argc, char const *argv[])
{
int n;
scanf("%d",&n);
printf("%d\n",isPerfect(n));
return 0;
}
|
97fe1f444f916f01bf8df53c2b2f9c9830660076
|
60a02af9855fd34fbe668628bca31e1bd0e37ea2
|
/projects/eclipse_workspace_kang/test2/src/aa.cpp
|
c6edf8d9bee554f2862930b9815f6b9c4d3707e6
|
[] |
no_license
|
dwkang0/auto-car
|
ac43dcd178789c906886042931f6634a85b79d4f
|
230e5a558790634bd420010c049d386561b089ca
|
refs/heads/master
| 2020-06-01T15:27:00.951042
| 2019-09-21T01:13:25
| 2019-09-21T01:13:25
| 190,833,289
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 152
|
cpp
|
aa.cpp
|
/*
* aa.cpp
*
* Created on: 2019. 7. 28.
* Author: dwkang
*/
#include "abc.h"
#include <stdio.h>
void abc::print2(){
printf("print2");
}
|
2ffd9dd96e5f93036837bee838e0d4d0d91444f9
|
3adbe404c5a38e92a48f8cc45753b888cb71450d
|
/minnum.cpp
|
c6c8cfeed22ec308170b9616cdadb4ca3aad3fa7
|
[] |
no_license
|
pravinkumarkg/codekata7
|
08254a6ef6acd684462bbbb4018a174e7a9ef016
|
18fc0a60a7dcda1ec196f7805e6e5f7887c5012f
|
refs/heads/master
| 2020-06-30T13:38:30.777915
| 2019-08-06T14:03:01
| 2019-08-06T14:03:01
| 200,843,257
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 229
|
cpp
|
minnum.cpp
|
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int min=arr[0];
for(int j=0;j<n;j++)
{
if(min>arr[j])
min=arr[j];
}
cout<<min;
return 0;
}
|
87a9421d09eea2500f114bd6d6bd704e48a93e3b
|
79e1d6c2a95d9833b0d645191fbd518c673cf27f
|
/_7.0.95/MainMCU/THardware.h
|
754aeb3aba968f931d8a9be166fa7478938db826
|
[] |
no_license
|
yaroslau1/Firmware_LastRelease
|
1a1ff064a6097e53429a9aa32784270ba0a1e0df
|
57ba1e60ff9562601a9a98d5851ced2559ed3dc8
|
refs/heads/master
| 2021-09-25T03:42:07.583348
| 2018-10-09T14:01:09
| 2018-10-09T14:01:09
| 152,089,652
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,748
|
h
|
THardware.h
|
/*----------------------------------------------------------------------------------*/
#ifndef HARDWARE_H
#define HARDWARE_H
/*----------------------------------------------------------------------------------*/
#include "main.h"
/*----------------------------------------------------------------------------------*/
// SDCard pinout
#define SD_GPIO_RCC_ENABLE RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB | RCC_AHB1Periph_GPIOC, ENABLE)
#define SD_SPI_RCC_ENABLE RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE)
#define SD_SPI_RCC_DISABLE RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, DISABLE)
#define SD_EN_PORT GPIOB
#define SD_EN_PIN GPIO_Pin_8
#define SD_CS_PORT GPIOC
#define SD_CS_PIN GPIO_Pin_11
#define SD_SCK_PORT GPIOB
#define SD_SCK_PIN GPIO_Pin_3
#define SD_SCK_PINSOURCE GPIO_PinSource3
#define SD_MISO_PORT GPIOB
#define SD_MISO_PIN GPIO_Pin_4
#define SD_MISO_PINSOURCE GPIO_PinSource4
#define SD_MOSI_PORT GPIOB
#define SD_MOSI_PIN GPIO_Pin_5
#define SD_MOSI_PINSOURCE GPIO_PinSource5
#define SD_SPI SPI1
#define SD_SPI_AF GPIO_AF_SPI1
// Bluetooth pinout
#define LMX_USART_RCC_ENABLE RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE)
#define LMX_USART_RCC_DISABLE RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, DISABLE)
#define LMX_GPIO_RCC_ENABLE RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB | RCC_AHB1Periph_GPIOC, ENABLE)
#define LMX_TXD_GPIO_PORT GPIOB
#define LMX_TXD_GPIO_PIN GPIO_Pin_6
#define LMX_TXD_GPIO_PINSOURCE GPIO_PinSource6
#define LMX_RXD_GPIO_PORT GPIOB
#define LMX_RXD_GPIO_PIN GPIO_Pin_7
#define LMX_RXD_GPIO_PINSOURCE GPIO_PinSource7
#define LMX_EN_GPIO_PORT GPIOC
#define LMX_EN_GPIO_PIN GPIO_Pin_13
#define LMX_RST_GPIO_PORT GPIOC
#define LMX_RST_GPIO_PIN GPIO_Pin_14
#define LMX_LSTAT_GPIO_PORT GPIOB
#define LMX_LSTAT_GPIO_PIN GPIO_Pin_9
#define LMX_LSTAT_EXTI_PORT EXTI_PortSourceGPIOB
#define LMX_LSTAT_EXTI_PIN EXTI_PinSource9
#define LMX_LSTAT_EXTI_LINE EXTI_Line9
#define LMX_LSTAT_IRQChannel EXTI9_5_IRQn
#define LMX_USART_IRQChannel USART1_IRQn
#define LMX_USART USART1
#define LMX_USART_AF GPIO_AF_USART1
// ADS pinout
#define ADS1298_GPIO_RCC_ENABLE RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE)
#define ADS1298_SPI_RCC_ENABLE RCC_APB1PeriphClockCmd( RCC_APB1Periph_SPI2, ENABLE )
#define ADS1298_CS_PORT GPIOB
#define ADS1298_CS_PIN GPIO_Pin_12
#define ADS1298_SPI_PORT GPIOB
#define ADS1298_SCK_PIN GPIO_Pin_13
#define ADS1298_SCK_PINSOURCE GPIO_PinSource13
#define ADS1298_MISO_PIN GPIO_Pin_14
#define ADS1298_MISO_PINSOURCE GPIO_PinSource14
#define ADS1298_MOSI_PIN GPIO_Pin_15
#define ADS1298_MOSI_PINSOURCE GPIO_PinSource15
#define ADS1298_SPI SPI2
#define ADS1298_SPI_AF GPIO_AF_SPI2
#define ADS1298_DRDY_PORT GPIOB
#define ADS1298_DRDY_PIN GPIO_Pin_2
#define ADS_DRDY_EXTI_PORT EXTI_PortSourceGPIOB
#define ADS_DRDY_EXTI_PIN GPIO_PinSource2
#define ADS_DRDY_EXTI_LINE EXTI_Line2
#define ADS_DRDY_IRQChannel EXTI2_IRQn
// Keys pinout
#define UB1_BUTTON_CLK RCC_AHB1Periph_GPIOC
#define UB1_BUTTON_PORT GPIOC
#define UB1_BUTTON_PIN GPIO_Pin_1
#define UB1_EXTI_PORT EXTI_PortSourceGPIOC
#define UB1_EXTI_PIN EXTI_PinSource1
#define UB1_EXTI_LINE EXTI_Line1
#define UB1_IRQChannel EXTI1_IRQn
#define UB2_BUTTON_CLK RCC_AHB1Periph_GPIOC
#define UB2_BUTTON_PORT GPIOC
#define UB2_BUTTON_PIN GPIO_Pin_0
#define UB2_EXTI_PORT EXTI_PortSourceGPIOC
#define UB2_EXTI_PIN EXTI_PinSource0
#define UB2_EXTI_LINE EXTI_Line0
#define UB2_IRQChannel EXTI0_IRQn
// NiBat pinout
#define NiBat_GPIO_CLK RCC_APB2Periph_GPIOB
#define NiBat_GPIO_PORT GPIOB
#define NiBat_GPIO_PIN GPIO_Pin_0
#define NiBat_ADC_Channel ADC_Channel_8
// Audio pinout
#define AudioIn_GPIO_CLK RCC_AHB1Periph_GPIOC
#define AudioIn_GPIO_PORT GPIOC
#define AudioIn_GPIO_PIN GPIO_Pin_2
#define AudioIn_ADC_Channel ADC_Channel_12
#define AudioPwr_GPIO_CLK RCC_AHB1Periph_GPIOC
#define AudioPwr_GPIO_PORT GPIOC
#define AudioPwr_GPIO_PIN GPIO_Pin_3
// LEDs, Test pin, etc pinout
#define TEST_GPIO_CLK RCC_AHB1Periph_GPIOC
#define TEST_PIN GPIO_Pin_5
#define TEST_PORT GPIOC
// #define WAKEUP_GPIO_PORT GPIOE
// #define WAKEUP_GPIO_PIN GPIO_Pin_2
#define BUZZER_P_GPIO_CLK RCC_AHB1Periph_GPIOC
#define BUZZER_P_GPIO_PORT GPIOC
#define BUZZER_P_GPIO_PIN GPIO_Pin_7
#define BUZZER_P_GPIO_PINSOURCE GPIO_PinSource7
#define BUZZER_N_GPIO_CLK RCC_AHB1Periph_GPIOB
#define BUZZER_N_GPIO_PORT GPIOB
#define BUZZER_N_GPIO_PIN GPIO_Pin_0
#define BUZZER_N_GPIO_PINSOURCE GPIO_PinSource0
#define BUZZER_TIM TIM8
#define BUZZER_TIM_AF GPIO_AF_TIM8
#define BUZZER_TIM_CLK RCC_APB2Periph_TIM8
#define _SET_PIN( x, y ) GPIO_SetBits( x ## _PORT, y ## _PIN )
#define _CLR_PIN( x, y ) GPIO_ResetBits( x ## _PORT, y ## _PIN )
#define SET_PIN( z ) _SET_PIN( z ##, z ## )
#define CLR_PIN( z ) _CLR_PIN( z ##, z ## )
/*----------------------------------------------------------------------------------*/
typedef struct
{
void( *Enable )( void );
void( *Disable )( void );
bool Status;
struct {
void( *On )( void );
void( *Off )( void );
}Led1;
struct {
void( *On )( void );
void( *Off )( void );
}Led2;
struct {
void( *On )( void );
void( *Off )( void );
}Led3;
struct {
void( *On )( void );
void( *Off )( void );
}Led4;
struct {
void( *On )( void );
void( *Off )( void );
}Led;
}DebugTools_TypeDef;
enum KeyDefs {
ChangeButton = 0,
SelectButton
};
/*----------------------------------------------------------------------------------*/
class THardware
{
public:
static void KeysInit( void );
static void KeysDeinit( void );
static void TestPinInit( void );
static void TestPinDeinit( void );
static void LedOn( void );
static void LedOff( void );
static void LedInvert( void );
static DebugTools_TypeDef DebugTools;
static bool BlockKeys;
static volatile uint16_t ADC3_ScanResult[4];
#ifdef EV_BOARD
static void Led0_On( void );
static void Led0_Off( void );
static void Led1_On( void );
static void Led1_Off( void );
static void Led2_On( void );
static void Led2_Off( void );
static void Led3_On8( void );
static void Led3_Off( void );
#endif
static void BT_ResetControl( bool state );
static int CheckKey( int _Key );
static void LedsPHYInit( void );
static void RS232PHYInit( void );
static void VoltmeterInit( void );
static void VoltmeterDeinit( void );
#ifndef EV_BOARD
static void TestPinControl( bool state );
#endif
};
/*----------------------------------------------------------------------------------*/
#endif
|
c19bef80d1158d0766dec28021d1596764cd6f45
|
2f7fba7427ae2a7f95664080c1a48c4502f2b78c
|
/Codeforces/beautiful_year.cpp
|
8a4e2823c2e900808af3f2fd3a3b32c5d3b1fb7f
|
[] |
no_license
|
max-muoto/competitve-programming
|
b66c6079a3a7b41a02a15133f5bd9215b36948fb
|
4ca66c4c24286eebcf0cf69362e76a2d0c6d4d5b
|
refs/heads/master
| 2023-01-30T23:19:15.880343
| 2020-12-19T23:32:48
| 2020-12-19T23:32:48
| 322,956,126
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 630
|
cpp
|
beautiful_year.cpp
|
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <map>
using namespace std;
int main() {
int y;
cin >> y;
for (int i = y; i++;) {
string z = to_string(i);1
int counter = 0;
std::map<char, int> occurences = {};
for (int x = 0; x < z.size(); x++) {
if (occurences[z[x]] > 1) {
counter++;
} else {
occurences[z[x]]++;
}
if (counter == 0 && x == z.size() - 1) {
cout << z << endl;
return 0;
}
}
}
return 0;
}
|
18223aef0cf380aa6b8e76396a3490c5a80ad46d
|
e87944a8f72367e62cf35f11e0ae741ba2ade27c
|
/src/lasers/button.cpp
|
3c12c8d2ec81b1b1abddc823726c9bd291d829cd
|
[] |
no_license
|
Think-Engineer/laser-harp
|
2c09bc69b0f23afe79a0e8689eab4b8279e9ac51
|
8cd87345ac7f7e5eb2701339cae535260a632190
|
refs/heads/master
| 2020-03-27T13:46:30.126520
| 2018-08-29T17:16:50
| 2018-08-29T17:16:50
| 146,627,408
| 4
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,692
|
cpp
|
button.cpp
|
#include "button.h"
/* Store Button Pins and Values */
int nextButton = A14; //TODO: update after buttons installed
int nextButtonValue;
int prevButton = A15;
int prevButtonValue;
/* Store voices */
int voices[VOICE_COUNT] = { 46, 102, 12, 18, 101, 91, 89, 80, 95, 45 };
int currentVoice = 0;
void saveVoice() {
updateVoice(voices[currentVoice]);
/* Plays chord */
noteOn(0, 36, 127);
noteOn(0, 48, 127);
noteOn(0, 52, 127);
noteOn(0, 55, 127);
delay(250);
noteOff(0, 36, 127);
noteOff(0, 48, 127);
noteOff(0, 52, 127);
noteOff(0, 55, 127);
}
int nextVoice() {
currentVoice = (currentVoice + 1) % VOICE_COUNT;
saveVoice();
return currentVoice;
}
int prevVoice() {
currentVoice = (currentVoice - 1);
if (currentVoice < 0) {
currentVoice += VOICE_COUNT;
}
saveVoice();
return currentVoice;
}
void buttonInit() {
pinMode(nextButton, INPUT_PULLUP);
pinMode(prevButton, INPUT_PULLUP);
nextButtonValue = digitalRead(nextButton);
prevButtonValue = digitalRead(prevButton);
}
/**
* Returns value if voice updated. Returns -1 if not.
*/
int buttonUpdate() {
int newNextButtonValue = digitalRead(nextButton);
int newPrevButtonValue = digitalRead(prevButton);
int newVoice = -1;
/* Next Button clicked down */
if (newNextButtonValue == LOW && nextButtonValue == HIGH) {
newVoice = nextVoice();
}
/* Prev Button clicked down */
if (newPrevButtonValue == LOW && prevButtonValue == HIGH) {
newVoice = prevVoice();
}
prevButtonValue = newPrevButtonValue;
nextButtonValue = newNextButtonValue;
return newVoice;
}
|
1dfe57b914ae396870975a76a75b426df6514fd8
|
ba7a96bd68d6ccbe571cb7a2f0f3f007ecbeafe9
|
/UVA.11461.SquareNumbers/squareNumbers.cpp
|
0ead327dfcf91903c7b1fe0462e992200f095ab8
|
[] |
no_license
|
simon0191/ProgrammingExercises
|
6d45cf8d60a494218d188e9bbf776940a7928779
|
3e49e539a844e2a3069f0e008fee61de6eb7ccd9
|
refs/heads/master
| 2021-01-23T03:05:28.105220
| 2012-09-21T05:51:16
| 2012-09-21T05:51:16
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 852
|
cpp
|
squareNumbers.cpp
|
#include <algorithm>
#include <bitset>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <iostream>
#include <iterator>
#include <limits>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#define UL unsigned long long
#define LL long long
#define LD long double
#define EPS 1e-9
const int AZ_SIZE = 'Z'-'A'+1;
using namespace std;
#define NN 100010
int main(){
bitset<NN> isSquare;
for(int i = 0;i<317;++i){
isSquare[i*i] = true;
}
int acum[NN];
memset(acum,0,sizeof(acum));
acum[0] = 1;
for(int i = 1;i<NN;++i){
acum[i] = acum[i-1];
if(isSquare[i])++acum[i];
}
int a,b;
while(scanf("%d%d",&a,&b) && (a+b)){
//if(b<a)swap(b,a);
printf("%d\n",acum[b]-acum[a-1]);
}
return 0;
}
|
287294b5ce591e77ff193c599bdc0dbf9c104442
|
eb3d5577434b795317b6c9f768f80c7b18bd243f
|
/ecf50/fh.cpp
|
77c121ee90cf2e4dfb0d7cc22d3ecba3d4931ef8
|
[] |
no_license
|
JacobianDet/CompeteUp
|
e00f9f468eb074dfe6e21eeadc17193e5b118f28
|
f4048b093e0dc0dad054cc4024eac09e2567630e
|
refs/heads/master
| 2021-06-08T16:18:26.320750
| 2021-04-03T13:29:42
| 2021-04-03T13:29:42
| 143,545,505
| 2
| 1
| null | 2021-04-03T13:29:42
| 2018-08-04T16:37:05
|
C++
|
UTF-8
|
C++
| false
| false
| 174
|
cpp
|
fh.cpp
|
#include <bits/stdc++.h>
typedef long long ll;
int main(void)
{
ll n,k;
std::cin>>n>>k;
if(k % n)
std::cout<<(k/n) + 1<<"\n";
else std::cout<<(k/n)<<"\n";
return 0;
}
|
5b96e51fcf95fa5b7d2644cf438b434d57a0762b
|
0ef4f71c8ff2f233945ee4effdba893fed3b8fad
|
/misc_microsoft_gamedev_source_code/misc_microsoft_gamedev_source_code/extlib/Scaleform/GFx SDK 2.1.57/Src/GKernel/GRefCount.cpp
|
e10ae5d6a8b3d026977dc9ab6977f2887ee39cf8
|
[] |
no_license
|
sgzwiz/misc_microsoft_gamedev_source_code
|
1f482b2259f413241392832effcbc64c4c3d79ca
|
39c200a1642102b484736b51892033cc575b341a
|
refs/heads/master
| 2022-12-22T11:03:53.930024
| 2020-09-28T20:39:56
| 2020-09-28T20:39:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,386
|
cpp
|
GRefCount.cpp
|
/**********************************************************************
Filename : GRefCount.cpp
Content : Reference counting implementation
Created : January 14, 1999
Authors : Michael Antonov
Notes :
History :
Copyright : (c) 1999-2006 Scaleform Corp. All Rights Reserved.
Licensees may use this file in accordance with the valid Scaleform
Commercial License Agreement provided with the software.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR ANY PURPOSE.
**********************************************************************/
#include "GRefCount.h"
#include "GTLTypes.h"
#ifndef GFC_NO_THREADSUPPORT
#include "GAtomic.h"
#endif
// ***** Reference Count Base implementation
// ** Ref-Counting delegated functions
// Functions for nothing
void GFASTCALL AddRef_Null(GRefCountBaseImpl *pbase)
{
GUNUSED(pbase);
}
void GFASTCALL Release_Null(GRefCountBaseImpl *pbase, UInt flags)
{
GUNUSED(pbase);
GUNUSED(flags);
}
static GRefCountImpl RefCountImpl_Null =
{
&AddRef_Null,
&Release_Null
};
//Functions for reference counting
void GFASTCALL AddRef_Normal(GRefCountBaseImpl *pbase)
{
pbase->RefCount++;
}
void GFASTCALL Release_Normal(GRefCountBaseImpl *pbase, UInt flags)
{
GUNUSED(flags);
pbase->RefCount--;
if (pbase->RefCount==0)
delete pbase;
}
static GRefCountImpl RefCountImpl_Normal =
{
&AddRef_Normal,
&Release_Normal
};
#ifndef GFC_NO_THREADSUPPORT
// Functions for thread-safe reference counting
void GFASTCALL AddRef_ThreadSafe(GRefCountBaseImpl *pbase)
{
GAtomicOps<SInt>::ExchangeAdd_NoSync(&pbase->RefCount, 1);
}
void GFASTCALL Release_ThreadSafe(GRefCountBaseImpl *pbase, UInt flags)
{
GUNUSED(flags);
if ((GAtomicOps<SInt>::ExchangeAdd_NoSync(&pbase->RefCount, -1) - 1) == 0)
delete pbase;
}
static GRefCountImpl RefCountImpl_ThreadSafe =
{
&AddRef_ThreadSafe,
&Release_ThreadSafe
};
#endif
// Constructor
// Does some custom processing to initialize the base
GRefCountBaseImpl::GRefCountBaseImpl()
{
pWeakProxy = 0;
// Reference counts one, no info by default
if ( (RefCount==GFC_REFCOUNT_KEY1) && (UPInt(pRefCountImpl)==GFC_REFCOUNT_KEY2) )
{
RefCount = 1;
pRefCountImpl = &RefCountImpl_Normal;
}
else
{
RefCount = 0;
pRefCountImpl = &RefCountImpl_Null;
}
}
GRefCountBaseImpl::GRefCountBaseImpl(GRefCountImpl *pNormalImpl, GRefCountImpl *pNullImpl)
{
pWeakProxy = 0;
// Reference counts one, no info by default
if ( (RefCount==GFC_REFCOUNT_KEY1) && (UPInt(pRefCountImpl)==GFC_REFCOUNT_KEY2) )
{
RefCount = 1;
pRefCountImpl = pNormalImpl;
}
else
{
RefCount = 0;
pRefCountImpl = pNullImpl ? pNullImpl : &RefCountImpl_Null;
}
}
GRefCountBaseImpl::~GRefCountBaseImpl()
{
// This may assert if 'delete' was called on a Ref-Couted object. This is
// forbidden because Release must be called instead.
// First generate a warning so that non-source customers have a message.
GFC_DEBUG_ERROR(RefCount > 0,
"Object destroyed with non-zero reference count. Did you call delete?");
GASSERT(RefCount <= 0);
if (pWeakProxy)
{
pWeakProxy->NotifyObjectDied();
pWeakProxy->Release();
}
}
bool GRefCountBaseImpl::SetRefCountMode(UInt mode)
{
// If in null-ref counting mode fail.
if (pRefCountImpl == &RefCountImpl_Null)
return 0;
switch(mode)
{
case GFC_REFCOUNT_NORMAL:
pRefCountImpl = &RefCountImpl_Normal;
return 1;
case GFC_REFCOUNT_THREADSAFE:
#ifndef GFC_NO_THREADSUPPORT
pRefCountImpl = &RefCountImpl_ThreadSafe;
return 1;
#else
return 0;
#endif
}
return 0;
}
// Create/return create proxy, users must release proxy when no longer needed
GWeakPtrProxy* GRefCountBaseImpl::CreateWeakProxy() const
{
if (!pWeakProxy)
if ((pWeakProxy = new GWeakPtrProxy)==0)
return 0;
pWeakProxy->AddRef();
return pWeakProxy;
}
|
295eeccaeb86367e33f72d5d22b4f6637ca66eab
|
53f5ffa858d936b3dcdd2c62d972f5dcfcc8d48f
|
/src/systems/differential/attractor/Lorenz83Attractor.h
|
b27e64c9008590f8de66d499a99eca3196208286
|
[
"Unlicense"
] |
permissive
|
pigatron-industries/xen_octasource
|
7c8ffc20374f3bdaec66892b42e664b1657662ae
|
6430c1af2382233d5608d654688bc4a24131440f
|
refs/heads/master
| 2023-07-22T21:36:29.744523
| 2023-07-19T22:27:05
| 2023-07-19T22:27:05
| 234,933,202
| 7
| 1
|
Unlicense
| 2021-11-06T11:06:07
| 2020-01-19T16:54:05
|
C++
|
UTF-8
|
C++
| false
| false
| 956
|
h
|
Lorenz83Attractor.h
|
#ifndef Lorenz83Attractor_h
#define Lorenz83Attractor_h
#include "../ContinuousSystem.h"
class Lorenz83Attractor : public ContinuousSystemN<3> {
public:
void init(float sampleRate) {
ContinuousSystemN::init(sampleRate);
pos[X] = 0.1;
pos[Y] = 0.1;
pos[Z] = 0.1;
mult[X] = 1.8;
mult[Y] = 1.5;
mult[Z] = 1.5;
offset[X] = -0.75;
offset[Y] = -0.25;
offset[Z] = -0.25;
speedMult = 1;
}
const char* getName() { return "LORENZ83"; }
void system() {
delta[X] = - a*pos[X] - pos[Y]*pos[Y] - pos[Z]*pos[Z] + a*f;
delta[Y] = - pos[Y] + pos[X]*pos[Y] - b*pos[X]*pos[Z] + g;
delta[Z] = - pos[Z] + b*pos[X]*pos[Y] + pos[X]*pos[Z];
}
private:
float a = 0.95;
float b = 7.91;
float f = 4.83;
float g = 4.66;
};
#endif
|
7542dbbaa9e18282cda17d701e4c739491ee7bc3
|
cc426fede0b4ecc7af978f23227e01b6e962df44
|
/src/game/player_controller.hpp
|
791c3a2f8bafd995acc428f8004ee4fa99c157ea
|
[
"MIT"
] |
permissive
|
RiscadoA/voxel-platformer
|
0618cef1b524eb9983e779c93fc8faa4c3d3adb0
|
4e7aadad978c333a59f452a8ee9f4612ee128614
|
refs/heads/master
| 2023-03-14T20:42:32.566603
| 2021-03-05T20:35:05
| 2021-03-05T20:35:05
| 342,795,753
| 5
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,601
|
hpp
|
player_controller.hpp
|
#pragma once
#include <vpg/ecs/behaviour.hpp>
#include <vpg/data/text.hpp>
#include <vpg/input/mouse.hpp>
#include <vpg/input/keyboard.hpp>
#include <vpg/physics/collider.hpp>
using namespace vpg;
struct PlayerController : public ecs::IBehaviour {
static constexpr char TypeName[] = "PlayerController";
struct Info : public IBehaviour::Info {
ecs::Entity torso;
ecs::Entity lfoot, rfoot;
ecs::Entity lhand, rhand;
ecs::Entity feet_collider;
virtual bool serialize(memory::Stream& stream) const override;
virtual bool deserialize(memory::Stream& stream) override;
};
PlayerController(ecs::Entity entity, const Info& info);
~PlayerController();
virtual void update(float dt) override;
void on_feet_collision(const physics::Manifold& manifold);
void on_body_collision(const physics::Manifold& manifold);
void mouse_move_callback(glm::vec2 mouse);
void mouse_scroll_callback(input::Mouse::Wheel wheel, float delta);
void respawn(glm::vec3 position);
vpg::Listener mouse_move_listener;
vpg::Listener mouse_scroll_listener;
ecs::Entity entity;
ecs::Entity camera;
ecs::Entity torso;
ecs::Entity lfoot, rfoot;
ecs::Entity lhand, rhand;
ecs::Entity feet_collider;
float camera_distance, camera_x, camera_y;
bool on_floor, respawned;
float time;
glm::vec3 torso_pos;
glm::vec3 lfoot_pos, rfoot_pos;
glm::vec3 lhand_pos, rhand_pos;
glm::vec3 velocity;
glm::vec3 floor_velocity, last_dir;
glm::vec2 last_mouse;
float sensitivity;
};
|
7a2bcdc3418f62d14677686f7e1e74f4df171a0e
|
39f0781900fe2eb6a9be10fd1f014ffebbff188d
|
/src/keysubscriber.cpp
|
880ab0cdaddb0b761c7000131d6e88e93fb43d22
|
[] |
no_license
|
f5gkw/visionS
|
0b34fb015a07dcf16b2379de708257853648cad5
|
b1d943893dfdc3964f1adc63f2f07dc0d043382a
|
refs/heads/master
| 2021-08-27T17:16:39.655574
| 2017-05-05T20:07:26
| 2017-05-05T20:07:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 139
|
cpp
|
keysubscriber.cpp
|
#include "keysubscriber.h"
void KeySubscriber::parse() {
// std::string str = data_buffer->front();
// data_buffer->popFront();
}
|
b069e5b788e233a5d85c8a42b5e589b1cd0abc3a
|
c7c6e341decb69347dfba3eb8ef9dab0e628104a
|
/include/bak/TEA16.h
|
9ceab359d3c049ded295dd8a3e64c2d22949809b
|
[] |
no_license
|
sarrows/EasyCoding
|
1307ef39d1befbbf8493c864a53746ab4ec77707
|
319802595367f15ae915c8a9f5b6fa60961a419f
|
refs/heads/master
| 2021-01-10T19:45:18.326058
| 2014-11-04T15:25:23
| 2014-11-04T15:25:23
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,234
|
h
|
TEA16.h
|
/*TEA 16*/
#ifndef _QCRYPTER_H_
#define _QCRYPTER_H_
#include "MD5Cryptor.h"
class CQCryptor
{
public:
CQCryptor();
~CQCryptor();
static int encrypt(unsigned char * in, // 输入串
int in_len, // 输入串长度
unsigned char * key, // 密钥
unsigned char * out, // 输出缓冲区
int * out_len); // 输出缓冲区最大长度
static int decrypt(unsigned char * in, // 输入串
int in_len, // 输入串长度
unsigned char * key, // 密钥
unsigned char * out, // 输出缓冲区
int * out_len); // 输出缓冲区最大长度
private:
static void tea_encipher(unsigned long * const v,
const unsigned long * const k,
unsigned long * const w);
static void tea_decipher(unsigned long * const v,
const unsigned long * const k,
unsigned long * const w);
};
#endif
|
f052a1657c7eff2e3c624914a6df7db6c9fe1203
|
733de464662408d2ed3fa637b0c7ecdc7c281c0a
|
/device/component/keys/ascii_key.h
|
6ee4fcc872ac876f7554e6872038fb2fd6e704bf
|
[
"MIT"
] |
permissive
|
aconstlink/snakeoil
|
f15740eb93d3e36b656621bb57a0f7eb2592f252
|
3c6e02655e1134f8422f01073090efdde80fc109
|
refs/heads/master
| 2021-01-01T17:39:53.820180
| 2020-02-23T20:56:36
| 2020-02-23T20:56:36
| 98,117,868
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,055
|
h
|
ascii_key.h
|
//------------------------------------------------------------
// snakeoil (c) Alexis Constantin Link
// Distributed under the MIT license
//------------------------------------------------------------
#pragma once
#include "../../typedefs.h"
#include <snakeoil/log/global.h>
namespace so_device
{
enum class ascii_key
{
invalid,
escape,
f1,
f2,
f3,
f4,
f5,
f6,
f7,
f8,
f9,
f10,
f11,
f12,
f13,
f14,
print,
pause,
a,
b,
c,
d,
e,
f,
g,
h,
i,
j,
k,
l,
m,
n,
o,
p,
q,
r,
s,
t,
u,
v,
w,
x,
y,
z,
k_0,
k_1,
k_2,
k_3,
k_4,
k_5,
k_6,
k_7,
k_8,
k_9,
num_0,
num_1,
num_2,
num_3,
num_4,
num_5,
num_6,
num_7,
num_8,
num_9,
num_komma,
num_sub,
num_add,
num_mult,
num_div,
num_caps,
num_return,
shift_left,
shift_right,
ctrl_left,
ctrl_right,
alt_left,
alt_right,
k_return,
back_space,
space,
tab,
tab_lock,
sharp,
plus,
minus,
komma,
point,
insert,
k_delete,
pos1,
sk_end,
one_up,
one_down,
arrow_left,
arrow_right,
arrow_up,
arrow_down,
lower_than,
// os specific?
context,
// windows spec
win_win_left,
win_win_right,
// mac spec
mac_control,
// last key
num_keys
};
static bool_t convert_key_to_ascii_char( so_device::ascii_key const k, char_ref_t c )
{
if( k >= so_device::ascii_key::a && k <= so_device::ascii_key::z )
{
c = 'a' + char_t( k ) - char_t( so_device::ascii_key::a ) ;
return true ;
}
return false ; ;
}
static bool_t convert_key_to_ascii_number( so_device::ascii_key const k, char_ref_t c )
{
if( k >= so_device::ascii_key::k_0 && k <= so_device::ascii_key::k_9 )
{
c = '0' + char_t( k ) - char_t( so_device::ascii_key::k_0 ) ;
return true ;
}
return false ;
}
static so_device::ascii_key convert_ascii_number_keys( size_t const delta )
{
bool_t const cond = delta <= ( size_t( ascii_key::k_9 ) - size_t( ascii_key::k_0 ) ) ;
so_log::global::error_and_exit( so_core::is_not( cond ),
"[so_device::convert_ascii_number_keys]" ) ;
return ascii_key( size_t( ascii_key::k_0 ) + delta ) ;
}
static ascii_key convert_ascii_letter_keys( size_t const delta )
{
bool_t const cond = delta <= ( size_t( ascii_key::z ) - size_t( ascii_key::a ) ) ;
so_log::global::error_and_exit( so_core::is_not( cond ),
"[so_device::convert_ascii_letter_keys]" ) ;
return ascii_key( size_t( ascii_key::a ) + delta ) ;
}
static ascii_key convert_ascii_function_keys( size_t const delta )
{
bool_t const cond = delta <= ( size_t( ascii_key::f14 ) - size_t( ascii_key::f1 ) ) ;
so_log::global::error_and_exit( so_core::is_not( cond ),
"[so_device::convert_ascii_function_keys]" ) ;
return ascii_key( size_t( ascii_key::f1 ) + delta ) ;
}
static ascii_key convert_ascii_numpad_number_keys( size_t const delta )
{
bool_t const cond = delta <= ( size_t( ascii_key::num_9 ) - size_t( ascii_key::num_0 ) ) ;
so_log::global::error_and_exit( so_core::is_not( cond ),
"[so_device::convert_ascii_numpad_number_keys]" ) ;
return ascii_key( size_t( ascii_key::num_0 ) + delta ) ;
}
}
|
2ce7776b2f6cd3e462787a41df369d247293d3d1
|
e452ae6edba31ad013d9fcb058ff91f217b66d45
|
/Zaprzyjaznij_sie_z_algorytmami/trt.cpp
|
639e74942f833719f990469ad19796f88124e739
|
[] |
no_license
|
bati22/Algorithmics---solved-problems
|
fa725cea43e697ebca5c049e6c7785affccd87f2
|
8aa3317380833c27fc60c5b92ef45d1f54640818
|
refs/heads/main
| 2023-04-03T13:55:32.382866
| 2021-04-15T18:17:30
| 2021-04-15T18:17:30
| 358,334,966
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,451
|
cpp
|
trt.cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N_MAX = 2000009;
ll f_begin, f_end;
ll a, b, n, k;
ll x[N_MAX];
ll y[N_MAX];
ll part_x[N_MAX];
ll part_y[N_MAX];
ll v;
ll part_number;
ll last_result;
ll check(ll v)
{
ll result = 0;
ll j = n;
for (ll i = 0; i <= n; i++)
{
while(j >= 0 && part_x[i]*part_y[j] >= v)
j--;
result += n-j;
}
return result;
}
int main()
{
ios_base::sync_with_stdio(0);
cin >> a >> b >> n >> k;
x[n+1] = a;
y[n+1] = b;
part_number = n+1;
for (int i = 1; i <= n; i++)
cin >> x[i];
for (int i = 1; i <= n; i++)
cin >> y[i];
f_begin = 1;
f_end = a*b;
for (int i = 0; i <= n; i++)
{
part_x[i] = x[i+1]-x[i];
part_y[i] = y[i+1]-y[i];
}
sort(part_y, part_y+n+1);
sort(part_x, part_x+n+1);
/*cout << "Boki x: " << endl;
for (int i = 0; i <= n+1; i++)
cout << x[i] << " ";
cout << endl;
cout << endl;
cout << "Boki y: " << endl;
for (int i = 0; i <= n+1; i++)
cout << y[i] << " ";
cout << endl;
cout << endl;
cout << "Kawałki x: " << endl;
for (int i = 0; i <= n; i++)
cout << part_x[i] << " ";
cout << endl;
cout << endl;
cout << "Kawałki y: " << endl;
for (int i = 0; i <= n; i++)
cout << part_y[i] << " ";
cout << endl;
cout << endl;*/
while (f_begin <= f_end)
{
v = (f_begin+f_end)/2;
if (check(v) >= k)
{
f_begin = v+1;
last_result = v;
}
else
f_end = v-1;
}
cout << last_result << endl;
return 0;
}
|
72ee3bf8d41bc2c2fbf88d5c7d4410dd6bd9daaf
|
32809f6f425bf5665fc19de2bc929bacc3eeb469
|
/src/1259-Handshakes-That-Don't-Cross/1259.cpp
|
37f95888dc620f4bb602c219ca071ddea440dbad
|
[] |
no_license
|
luliyucoordinate/Leetcode
|
9f6bf01f79aa680e2dff11e73e4d10993467f113
|
bcc04d49969654cb44f79218a7ef2fd5c1e5449a
|
refs/heads/master
| 2023-05-25T04:58:45.046772
| 2023-05-24T11:57:20
| 2023-05-24T11:57:20
| 132,753,892
| 1,575
| 569
| null | 2023-05-24T11:57:22
| 2018-05-09T12:30:59
|
C++
|
UTF-8
|
C++
| false
| false
| 482
|
cpp
|
1259.cpp
|
class Solution
{
public:
int numberOfWays(int n)
{
vector<long long> inv(n / 2 + 2, 0);
inv[1] = 1;
long long mod = 1e9 + 7, res = 1;
for (int i = 2; i < n / 2 + 2; i++)
{
inv[i] = mod - mod / i * inv[mod%i]%mod;
}
for (int i = 1; i < n/ 2 + 1; i++)
{
res = res * (i + n / 2) % mod;
res = res * inv[i] % mod;
}
return res * inv[n / 2 + 1] % mod;
}
};
|
4ed43d621d77bb65045cbafa9c0990607d60e045
|
6e8c86ecd1b21a94d119142f3d9681fc68cde014
|
/2.2. lab in cpp/6th lab.cpp
|
4bc83ee1094297c04c68345cc44c95d0d7f8dda1
|
[] |
no_license
|
NaziaAnjumSharupa/c-and-cpp
|
6bca220fe792fe7e3cca23215c5396ed7c44a8cf
|
c39798158c4590a0c7646050e137d37bcf3006e2
|
refs/heads/master
| 2021-05-03T14:26:38.967870
| 2018-02-06T12:40:06
| 2018-02-06T12:40:06
| 120,456,073
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,022
|
cpp
|
6th lab.cpp
|
#include<iostream>
#include<conio.h>
#define INF 999999999
using namespace std;
int a,b,u,v,n,i,j,k,ne=1;
int mini,mincost=0,cost[9][9],parent[9];
long int m[20][20];
int s[20][20],p[20];
int find1(int);
int uni(int,int);
void print_optimal(int,int);
void matmultiply(void);
Kruskals()
{
cout<<"Enter the number of vertices: ";
cin>>n;
cout<<"Enter the adjacency matrix :"<<endl;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cin>>cost[i][j];
if(cost[i][j]==0)
cost[i][j]=999;
}
}
cout<<"The edges of minimum cost spanning tree are: "<<endl;
while(ne<n)
{
for(i=1,mini=999;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(cost[i][j]<mini)
{
mini=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find1(u);
v=find1(v);
if(uni(u,v))
{
cout<<ne++<<" edge ("<<a<<","<<b<<")="<<mini<<endl;
mincost+=mini;
}
cost[a][b]=cost[b][a]=999;
}
cout<<"MInimum cost = "<<mincost<<endl;
}
int find1(int i)
{
while(parent[i])
i=parent[i];
return i;
}
int uni(int i,int j)
{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}
void print_optimal(int i,int j)
{
if(i==j)
cout<<"A "<<i;
}
void matmultiply(void)
{
long int q;
int k;
for(i=n;i>0;i--)
{
for(j=i;j<=n;j++)
{
if(i==j)
m[i][j]=0;
else
{
for(k=i;k<j;k++)
{
q=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j];
if(q<m[i][j])
{
m[i][j]=q;
s[i][j]=k;
}
}
}
}
}
}
MatChainMult()
{
int k;
cout<<"Enter the number of elements: ";
cin>>n;
for(i=1;i<=n;i++)
for(j=i+1;j<=n;j++)
{
m[i][i]=0;
m[i][j]=INF;
s[i][j]=0;
}
cout<<"Enter the dimensions: "<<endl;
for(k=0;k<=n;k++)
{
cout<<"P"<<k<<": ";
cin>>p[k];
}
matmultiply();
cout<<"Cost Matrix M: "<<endl;
for(i=1;i<=n;i++)
for(j=i;j<=n;j++)
cout<<"m["<<i<<"]["<<j<<"]: "<<m[i][j]<<endl;
cout<<endl<<"Matrix S for K values: "<<endl;
for(i=1;i<=n;i++)
for(j=i;j<n;j++)
cout<<"m["<<i<<"]["<<j<<"]: "<<s[i][j]<<endl;
i=1,j=n;
print_optimal(i,j);
}
int main()
{
int choice;
cout<<"Enter your choice: "<<endl<<"1. Kruskal's Algorithm"<<endl<<"2. Matrix-Chain Multiplication"<<endl;
cin>>choice;
switch(choice)
{
case 1:
Kruskals();
break;
case 2:
MatChainMult();
break;
default:
cout<<"Invalid choice!"<<endl;
}
return 0;
}
|
315abc36a45b398ff8527cf4f2d342f4421bd7ab
|
40116762cdaf8af03d9b77d412abbc2bd2a0f822
|
/native/cocos/core/geometry/Frustum.cpp
|
1c9c08411a6649bc6d9b4a16e01f4eca6745361b
|
[
"MIT"
] |
permissive
|
shrinktofit/engine
|
10facc571f22584691661399f280cccc6b0cfeb5
|
7bad7a25ec9fa9c540e2231c25ec4a52fe00d8cb
|
refs/heads/develop
| 2023-08-21T19:55:32.188131
| 2023-07-21T06:01:33
| 2023-07-21T06:05:54
| 147,444,425
| 1
| 1
|
NOASSERTION
| 2023-08-14T03:15:15
| 2018-09-05T01:53:20
|
C++
|
UTF-8
|
C++
| false
| false
| 7,869
|
cpp
|
Frustum.cpp
|
/****************************************************************************
Copyright (c) 2021-2023 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
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 "core/geometry/Frustum.h"
#include <cmath>
#include "core/geometry/Enums.h"
#include "scene/Define.h"
namespace cc {
namespace geometry {
namespace {
const ccstd::vector<cc::Vec3> VEC_VALS{
{1, 1, 1},
{-1, 1, 1},
{-1, -1, 1},
{1, -1, 1},
{1, 1, -1},
{-1, 1, -1},
{-1, -1, -1},
{1, -1, -1}};
} // namespace
void Frustum::createOrtho(Frustum *out, float width,
float height,
float near,
float far,
const Mat4 &transform) {
createOrthographic(out, width, height, near, far, transform);
}
void Frustum::createOrthographic(Frustum *out, float width,
float height,
float near,
float far,
const Mat4 &transform) {
auto halfWidth = width / 2.0F;
auto halfHeight = height / 2.0F;
Vec3::transformMat4({halfWidth, halfHeight, -near}, transform, &out->vertices[0]);
Vec3::transformMat4({-halfWidth, halfHeight, -near}, transform, &out->vertices[1]);
Vec3::transformMat4({-halfWidth, -halfHeight, -near}, transform, &out->vertices[2]);
Vec3::transformMat4({halfWidth, -halfHeight, -near}, transform, &out->vertices[3]);
Vec3::transformMat4({halfWidth, halfHeight, -far}, transform, &out->vertices[4]);
Vec3::transformMat4({-halfWidth, halfHeight, -far}, transform, &out->vertices[5]);
Vec3::transformMat4({-halfWidth, -halfHeight, -far}, transform, &out->vertices[6]);
Vec3::transformMat4({halfWidth, -halfHeight, -far}, transform, &out->vertices[7]);
out->updatePlanes();
}
Frustum *Frustum::createFromAABB(Frustum *out, const AABB &aabb) {
Vec3 minPos;
Vec3 maxPos;
aabb.getBoundary(&minPos, &maxPos);
out->vertices[0].set(maxPos.x, maxPos.y, -minPos.z);
out->vertices[1].set(minPos.x, maxPos.y, -minPos.z);
out->vertices[2].set(minPos.x, minPos.y, -minPos.z);
out->vertices[3].set(maxPos.x, minPos.y, -minPos.z);
out->vertices[4].set(maxPos.x, maxPos.y, -maxPos.z);
out->vertices[5].set(minPos.x, maxPos.y, -maxPos.z);
out->vertices[6].set(minPos.x, minPos.y, -maxPos.z);
out->vertices[7].set(maxPos.x, minPos.y, -maxPos.z);
out->updatePlanes();
return out;
}
void Frustum::createPerspective(Frustum *out, float fov,
float aspect,
float near,
float far,
const Mat4 &transform) {
const float h = tanf(fov * 0.5F);
const float w = h * aspect;
const Vec3 nearTemp(near * w, near * h, near);
const Vec3 farTemp(far * w, far * h, far);
out->vertices[0].transformMat4(Vec3(nearTemp.x, nearTemp.y, -nearTemp.z), transform);
out->vertices[1].transformMat4(Vec3(-nearTemp.x, nearTemp.y, -nearTemp.z), transform);
out->vertices[2].transformMat4(Vec3(-nearTemp.x, -nearTemp.y, -nearTemp.z), transform);
out->vertices[3].transformMat4(Vec3(nearTemp.x, -nearTemp.y, -nearTemp.z), transform);
out->vertices[4].transformMat4(Vec3(farTemp.x, farTemp.y, -farTemp.z), transform);
out->vertices[5].transformMat4(Vec3(-farTemp.x, farTemp.y, -farTemp.z), transform);
out->vertices[6].transformMat4(Vec3(-farTemp.x, -farTemp.y, -farTemp.z), transform);
out->vertices[7].transformMat4(Vec3(farTemp.x, -farTemp.y, -farTemp.z), transform);
out->updatePlanes();
}
void Frustum::update(const Mat4 &m, const Mat4 &inv) {
// left plane
planes[0]->n.set(m.m[3] + m.m[0], m.m[7] + m.m[4], m.m[11] + m.m[8]);
planes[0]->d = -(m.m[15] + m.m[12]);
// right plane
planes[1]->n.set(m.m[3] - m.m[0], m.m[7] - m.m[4], m.m[11] - m.m[8]);
planes[1]->d = -(m.m[15] - m.m[12]);
// bottom plane
planes[2]->n.set(m.m[3] + m.m[1], m.m[7] + m.m[5], m.m[11] + m.m[9]);
planes[2]->d = -(m.m[15] + m.m[13]);
// top plane
planes[3]->n.set(m.m[3] - m.m[1], m.m[7] - m.m[5], m.m[11] - m.m[9]);
planes[3]->d = -(m.m[15] - m.m[13]);
// near plane
planes[4]->n.set(m.m[3] + m.m[2], m.m[7] + m.m[6], m.m[11] + m.m[10]);
planes[4]->d = -(m.m[15] + m.m[14]);
// far plane
planes[5]->n.set(m.m[3] - m.m[2], m.m[7] - m.m[6], m.m[11] - m.m[10]);
planes[5]->d = -(m.m[15] - m.m[14]);
for (Plane *plane : planes) {
float invDist = 1 / plane->n.length();
plane->n *= invDist;
plane->d *= invDist;
}
uint32_t i = 0;
for (const Vec3 &vec : VEC_VALS) {
vertices[i].transformMat4(vec, inv);
i++;
}
}
void Frustum::transform(const Mat4 &mat) {
for (auto i = 0; i < 8; i++) {
vertices[i].transformMat4(vertices[i], mat);
}
updatePlanes();
}
void Frustum::createOrthographic(float width, float height, float near, float far, const Mat4 &transform) {
createOrthographic(this, width, height, near, far, transform);
}
void Frustum::createOrtho(const float width, const float height, const float near, const float far, const Mat4 &transform) {
createOrthographic(width, height, near, far, transform);
}
void Frustum::split(float near, float far, float aspect, float fov, const Mat4 &transform) {
createPerspective(this, fov, aspect, near, far, transform);
}
void Frustum::updatePlanes() {
// left plane
planes[0]->define(vertices[1], vertices[6], vertices[5]);
// right plane
planes[1]->define(vertices[3], vertices[4], vertices[7]);
// bottom plane
planes[2]->define(vertices[6], vertices[3], vertices[7]);
// top plane
planes[3]->define(vertices[0], vertices[5], vertices[4]);
// near plane
planes[4]->define(vertices[2], vertices[0], vertices[3]);
// far plane
planes[5]->define(vertices[7], vertices[5], vertices[6]);
}
Frustum::Frustum() : ShapeBase(ShapeEnum::SHAPE_FRUSTUM) {
init();
}
Frustum::Frustum(const Frustum &rhs) : ShapeBase(rhs) {
init();
*this = rhs;
}
Frustum::~Frustum() {
for (auto *plane : planes) {
plane->release();
}
}
Frustum &Frustum::operator=(const Frustum &rhs) {
if (this == &rhs) {
return *this;
}
vertices = rhs.vertices;
for (size_t i = 0; i < planes.size(); ++i) { // NOLINT(modernize-loop-convert)
Plane::copy(planes[i], *rhs.planes[i]);
}
return *this;
}
void Frustum::init() {
for (size_t i = 0; i < planes.size(); ++i) { // NOLINT(modernize-loop-convert)
planes[i] = ccnew Plane();
planes[i]->addRef();
}
}
} // namespace geometry
} // namespace cc
|
65844e6c782be8fd9e9f8823fd7798231df22ff2
|
c3f18073dac4767129e28dece885dc95525c1f53
|
/LeetCode/Tag/Depth-first-Search/cpp/1306.jump-game-iii.cpp
|
b1b5e0fa04b11fbcb37dadb469ac21b41c5f4263
|
[
"MIT"
] |
permissive
|
sunnysetia93/competitive-coding-problems
|
670ffe1ec90bfee0302f0b023c09e80bf5547e96
|
e8fad1a27a9e4df8b4138486a52bef044586c066
|
refs/heads/master
| 2023-08-09T04:31:24.027037
| 2023-07-24T12:39:46
| 2023-07-24T12:39:46
| 89,518,943
| 20
| 22
|
MIT
| 2023-07-24T12:39:48
| 2017-04-26T19:29:18
|
JavaScript
|
UTF-8
|
C++
| false
| false
| 364
|
cpp
|
1306.jump-game-iii.cpp
|
class Solution {
public:
bool canReach(vector<int>& arr, int start) {
if (start < 0 || start >= arr.size() || arr[start] < 0)
return false;
int jump = arr[start];
arr[start] = -arr[start]; // a way of marking the index as visited
return jump == 0 || canReach(arr, start-jump) || canReach(arr, start+jump);
}
};
|
487f6353a9e28108df96ed7145a62c385e5d4072
|
350d19972a11b83d212489ec2b9fa7f5bcd83ebc
|
/WagonsRecognition/_old_code.cpp
|
84a958a87ff892119fe84d2b5ceaac0da4f8fb79
|
[] |
no_license
|
igororlov/WagonsRecognition
|
30f2d998075ff7bae2fdb5cc483f818fc822b0da
|
883679d3e20917f1d83665fddd9fd0fc5f9f7b3e
|
refs/heads/master
| 2021-05-28T08:27:00.028648
| 2014-02-23T14:04:01
| 2014-02-23T14:04:01
| 6,472,063
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 72,431
|
cpp
|
_old_code.cpp
|
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// OPENCV includes BEGIN
#include <opencv2\core\core.hpp>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\features2d\features2d.hpp>
#include <opencv2\objdetect\objdetect.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <opencv2\legacy\legacy.hpp>
#include <opencv2\video\tracking.hpp>
#include <opencv2\stitching\stitcher.hpp>
// OPENCV includes END
#include <math.h>
#include <iostream>
using namespace cv;
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Глобальные переменные (использующиеся несколько раз в разных кусках, чтобы не было проблем с их хранением и передачей)
int NUMBER_HEIGHT = 30;
int SE_WIDTH = 40;
int thresh = NUMBER_HEIGHT*4*255; // порог для отбрасывания секторов средняя ширина номера = высота / 2, номер состоит из 4-х символов
int NUM_SECTORS = 0;
int* histogram;
int* minPositions; // локальные минимумы гистограммы
int NUM_MINS;
int CORNERS_THRESH = 15; // порог при поиске уголков, должен меняться в зависимости от размера номера
float COMPR_RATE = 2.; // коэффициент сжатия для поиска уголков (типа пирамиды)
int RADIUS_X = 25; // отдельно по осям Х
int RADIUS_Y = 10; // и Y в эллипсе
int VIDEO_TRACKBAR_MAX_VALUE = 100;
int VIDEO_TRACKBAR_VALUE = 0;
int RADIUS_TRACKBAR_MAX_VALUE = 50;
int RADIUS_X_TRACKBAR_VALUE = RADIUS_X;
int RADIUS_Y_TRACKBAR_VALUE = RADIUS_Y;
int COMPR_RATE_TRACKBAR_VALUE = (int)COMPR_RATE;
int COMPR_RATE_TRACKBAR_MAX_VALUE = 5;
int FASTTHRESH_TRACKBAR_VALUE = CORNERS_THRESH;
int FASTTHRESH_TRACKBAR_MAX_VALUE = 50;
int UP_BORDER = 0;
int DOWN_BORDER = 800;
int borders_setting = 0; // 0 - не включено, 1 - ждем первую границу, 2 - ждем вторую.
int HEIGHT_THRESH = 5; // пороги для трекинга - оставлять точки,
int WIDTH_THRESH = 25; // которые на новом кадре передвинулись не более чем данные пороги.
float ANGLE_THRESH = 10.0; // оставлять только BBox с углами наклона из промежутка (-ANGLE_THRESH,ANGLE_THRESH)
float h_alpha_up = 1.9; // насколько ВВЕРХ допустимы отклонения по высоте для minBBox'а (если 1.0 = NUMBER_HEIGHT)
float h_alpha_down = 0.85; // и ВНИЗ
int MIN_BBOX_AREA = NUMBER_HEIGHT * NUMBER_HEIGHT;
VideoCapture capture;
int num_frame = 0;
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// Объявления классов и функций.
class Region;
// Простые функции
char* getVideoTrack();
cv::Mat binarize(cv::Mat image);
float whiteRatio(cv::Mat image);
int* medFiltHist(int* arr,int n);
int* calcHist(cv::Mat image,int flag=0); // flag = 0 - hor, = 1 - vert
int* min(int* arr,int n);
int* max(int* arr,int n);
void printArray(int* arr,int n);
void prewittFilter(const cv::Mat &inp_image,cv::Mat &out_image,int type=1);
cv::Mat makeBlack(cv::Mat image);
int mean(int* arr,int n);
int* cleanHist(int* inp_arr,int n, int thresh);
bool belongs(int value, int* arr,int n);
int* mysort(int* arr,int n);
bool belongsToTriangle(cv::Point2f point,std::vector<cv::Point2f> vertices);
bool belongsToArea(cv::Point2f point,std::vector<cv::Point2f> vertices);
cv::Mat invertImage(cv::Mat image);
// Listener-ы для изменения настроек
void on_trackbar_listener( int, void* );
void on_trackbar2_listener( int, void* );
void on_trackbar3_listener( int, void* );
void onMouse( int event, int x, int y, int /*flags*/, void* /*param*/ );
// Вспомогательные функции
int* copyPartOfArray(int* inp_arr,int start,int finish);
int* localMins(int* arr,int n,int win_width = 20);
cv::Mat drawHist(cv::Mat image);
void imrotate(cv::Mat image,cv::Mat &out_image,double angle);
void drawBorders(cv::Mat &image);
void tmpShow(cv::Mat image);
float calcMatMorphoDensity(cv::Mat img);
bool checkRectOverlap(cv::Rect rect1,cv::Rect rect2);
Region joinRegions(Region region1,Region region2,cv::Mat frame);
Rect widenRect(Rect rect,int pixels = 2);
cv::Mat concatImages(cv::Mat img1,cv::Mat img2);
int getBinImgHeight(Mat charImage);
int getBinImgWidth(Mat charImage);
void printIntVector(std::vector<int> vect);
void drawLocalMins(Mat &image,std::vector<int> local_mins,cv::Scalar color = cv::Scalar(128,128,128));
int* getVertHist(Mat binImage);
void widenFrame(Mat &frame,int pixels);
cv::Mat cutCharWhite(cv::Mat charImage,cv::Mat binImage);
// Временно неиспользуемые
std::vector<cv::RotatedRect> makeTracking(std::vector<cv::KeyPoint> curr_keypts,std::vector<cv::KeyPoint> prev_keypts,cv::Mat &curr_image,cv::Mat prev_image,std::vector<cv::RotatedRect> prev_boxes);
std::vector<cv::DMatch> getBriskMatches(cv::Mat curr_frame, cv::Mat prev_frame, std::vector<cv::KeyPoint> curr_keypts,std::vector<cv::KeyPoint> prev_keypts);
cv::Mat drawBriskMatches(cv::Mat curr_frame, cv::Mat prev_frame, std::vector<cv::KeyPoint> curr_keypts,std::vector<cv::KeyPoint> prev_keypts,std::vector<cv::DMatch> matches);
std::vector<cv::DMatch> cleanMatches(std::vector<cv::DMatch> matches,std::vector<cv::KeyPoint> curr_keypts,std::vector<cv::KeyPoint> prev_keypts,int thresh);
cv::Mat drawLinesHoughDetection(cv::Mat image);
cv::Mat getContours(cv::Mat image);
// Важные функции
std::vector<cv::KeyPoint> detectCorners(cv::Mat image, float ratio ,int fast_thresh=25) ;
std::vector<std::vector<cv::KeyPoint>> getKeypointGroups(std::vector<cv::KeyPoint> keypoints,int RADIUS_X,int RADIUS_Y);
void getTrueBoxWidthHeight(RotatedRect bBox,float &width,float &height);
cv::RotatedRect getMinBBox(cv::Mat image,std::vector<cv::Point> points);
cv::Mat drawMinBBox(cv::Mat image, cv::RotatedRect box,cv::Scalar color);
bool checkedMinBBox(cv::RotatedRect box);
void clearKeypointsByAreaHeight(std::vector<cv::KeyPoint> keypoints,std::vector<cv::KeyPoint> &out_keypoints);
cv::Mat getBBoxImage(cv::Mat image,cv::RotatedRect box);
std::vector<Region> getJoinedRegions(std::vector<Region> regions,cv::Mat frame);
std::vector<cv::Mat> getUnitedImages(std::vector<Region> regions,cv::Mat frame);
std::vector<cv::KeyPoint> cleanStaticKeypts(std::vector<cv::KeyPoint> curr_keypts,std::vector<cv::KeyPoint> prev_keypts, Mat curr_frame, Mat prev_frame);
std::vector<int> clearLocalMins(int* minPositions, int* values, int n);
std::vector<Region> cutRegionsUpDown(std::vector<Region> regions,cv::Mat frame);
void splitIntoImages(Mat image,Mat binImage,std::vector<int> new_local_mins,std::vector<cv::Mat> &charImages,std::vector<cv::Mat> &charBinImages);
// Функции алгоритма
std::vector<Region> processFrameRegions(cv::Mat frame,std::vector<Region> regions,std::vector<cv::Mat> &united_images);
cv::Mat searchForNumber(cv::Mat image,cv::Mat prev_frame,std::vector<cv::KeyPoint> curr_keypts,
std::vector<cv::KeyPoint> prev_keypts);
void myMATLABLocalization(char* filename);
//////////////////////////////////////////// MAIN //////////////////////////////////////////// MAIN
//////////////////////////////////////////// MAIN //////////////////////////////////////////// MAIN
int _main()
{
// getVideoTrack()
// "C:\\Main\\WORK\\video\\new\\new25.avi"
myMATLABLocalization(getVideoTrack());
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
class Region
{
public:
std::vector<cv::KeyPoint> keypts;
cv::RotatedRect box;
cv::Mat box_image;
cv::Rect rect;
bool isGood;
Region(std::vector<cv::KeyPoint> keypoints,cv::Mat frame)
{
keypts = keypoints;
std::vector<cv::Point> points;
for (int j = 0; j < keypoints.size(); j++)
{
points.push_back((cv::Point)keypoints.at(j).pt);
}
box = getMinBBox(frame,points);
box_image = getBBoxImage(frame,box);
rect = boundingRect(Mat(points));
isGood = true;
}
Region(cv::Rect inp_rect)
{ // новый конструктор
rect = inp_rect; // ???????????????????????????????????????????????????????? be careful !!!
}
void drawRect(cv::Mat &image,cv::Scalar color = cv::Scalar(0,255,0),int thickness = 2)
{
if (rect.area() > 0)
{
rectangle(image,rect,color,thickness);
//char msg[50];
//std::sprintf(msg,"x=%d,y=%d,w=%d,h=%d;",rect.x,rect.y,rect.width,rect.height);
//cv::putText(image,msg,Point(rect.x,rect.y+rect.height/2),FONT_HERSHEY_PLAIN, .8, cv::Scalar(255,0,0));
}
}
cv::Mat getRectImage(cv::Mat image)
{
cv::Mat imROI = image(rect);
return imROI;
}
cv::Mat getKeypointsMap()
{
cv::Mat map(cv::Size(rect.width,rect.height),CV_8U,cv::Scalar(0));
for (int i = 0; i < keypts.size(); i++)
{
cv::Point pt = keypts.at(i).pt;
pt.x -= rect.x; pt.y -= rect.y;
cv::circle(map,pt,2,cv::Scalar(255),2);
}
return map;
}
float getKeyptsDensity()
{ // плотность кейпойнтов в прямоуг-ке.
return ( rect.area() / keypts.size() );
}
float getMorphoDensity(cv::Mat frame)
{
cv::Mat tmp = frame(rect);
cv::Mat tmp2;
tmp.copyTo(tmp2);
return calcMatMorphoDensity(tmp2);
}
float getBiggerMorphoDensity(cv::Mat frame)
{
// Померять плотность морф.градиента в увеличенном во все стороны на 25% прямоугольнике.
Point p1(rect.x,rect.y),
p2(rect.x+rect.width,rect.y+rect.height);
if (p1.x > rect.width*0.25) p1.x-=rect.width*0.25; else p1.x = 0;
if (p1.y > rect.height*0.25) p1.y-=rect.height*0.25; else p1.y = 0;
if (p2.x < frame.cols - rect.width*0.25) p2.x+=rect.width*0.25; else p2.x = frame.cols-1;
if (p1.x < frame.rows - rect.height*0.25) p2.y-=rect.height*0.25; else p2.y = frame.rows-1;
Rect big_rect(p1,p2);
cv::Mat tmp = frame(big_rect);
cv::Mat tmp2;
tmp.copyTo(tmp2);
return calcMatMorphoDensity(tmp2);
}
float getDiffUpDownMorphoDensity(cv::Mat frame)
{
// модуль разницы между плотностями морф. град-та
// в верхней и нижней половинах изображения
cv::Mat tmp2;
frame.copyTo(tmp2);
printf("\nframe.rows=%d, cols=%d",frame.rows,frame.cols);
Rect up_rect(Point(rect.x,rect.y),Point(rect.x+rect.width,rect.y+rect.height/2));
Rect down_rect(Point(rect.x,rect.y+rect.height/2),Point(rect.x+rect.width,rect.y+rect.height));
printf("\nup.x=%d,up.y=%d,up.width=%d,up.height=%d",up_rect.x,up_rect.y,up_rect.width,up_rect.height);
printf("\ndown.x=%d,down.y=%d,down.width=%d,down.height=%d",down_rect.x,down_rect.y,down_rect.width,down_rect.height);
float dens1 = calcMatMorphoDensity(tmp2(up_rect));
float dens2 = calcMatMorphoDensity(tmp2(down_rect));
return abs(dens1 - dens2);
//return 0.;
}
};
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
// CURRENT DEVELOPMENT // CURRENT DEVELOPMENT // CURRENT DEVELOPMENT // CURRENT DEVELOPMENT
// CURRENT DEVELOPMENT // CURRENT DEVELOPMENT // CURRENT DEVELOPMENT // CURRENT DEVELOPMENT
bool checkIfText(Region region,cv::Mat frame)
{ // TO DO - написать что-то поадекватнее!
Mat img = frame(region.rect);
Mat copy;
img.copyTo(copy);
prewittFilter(copy,copy);
if (whiteRatio(copy) <= 20.0)
return false;
return true;
}
//std::vector<Mat> joinImages(std::vector<Mat> charImages,std::vector<bool> joinMap)
//{ // будет объединять charBinImage's в порядке, указанном картой.
// std::vector<Mat> new_charImages;
//
// for (int i = 0; i < charImages.size()-1; i++)
// { // есть ли объединение i-го и следующего
// if (joinMap.at(i))
// {
// new_charImages.push_back(concatImages(charImages.at(i),charImages.at(i+1)));
// i++;
// }
// else
// {
// new_charImages.push_back(charImages.at(i));
// }
// }
//
// if ( !joinMap.at(joinMap.size()-1) )
// {
// new_charImages.push_back(charImages.at(charImages.size()-1));
// }
//
// return new_charImages;
//}
Mat drawNumberSeparated(std::vector<cv::Mat> charImages,std::vector<cv::Mat> unitedImages,std::vector<int> unitedBegins,int curr_number_height)
{
std::vector<int> imgs_y,united_y; // координаты столбца, в который нужно вставить картинку (левый отступ от края)
int curr_otst1 = 5,curr_otst2 = 5; // будут хранить требуемую ширину для умещения всех charImages и unitedImages на одной картинке соответственно
for(int i = 0; i < charImages.size(); i++)
{
imgs_y.push_back(curr_otst1);
curr_otst1 += charImages.at(i).cols + 25;
}
for (int i = 0; i < unitedImages.size(); i++)
{
united_y.push_back(imgs_y.at(unitedBegins.at(i))); // такое же начало, как и левого из родителей
}
if (unitedImages.size()>0){
curr_otst2 = united_y.at(united_y.size()-1) // начало последнего
+unitedImages.at(unitedImages.size()-1).cols+25; // ширина последнего + 25
}
// Создаем общее изображение для charImages в 1-й строчке и unitedImages - во второй
int rows = 2 * curr_number_height + 50;
int cols = curr_otst1 > curr_otst2 ? curr_otst1 : curr_otst2;
cv::Mat bigImg(rows,cols,charImages.at(0).type());
// Отрисовываем все charImages и unitedImages
for(int i = 0; i < charImages.size(); i++)
{
Mat ROI = bigImg(cv::Rect(imgs_y.at(i),10,charImages.at(i).cols,charImages.at(i).rows));
(charImages.at(i)).copyTo(ROI);
}
for (int i = 0; i < unitedImages.size(); i++)
{
Mat ROI = bigImg(cv::Rect(united_y.at(i),20+curr_number_height+10,unitedImages.at(i).cols,unitedImages.at(i).rows));
(unitedImages.at(i)).copyTo(ROI);
}
return bigImg;
}
bool canBeJoined(Mat bin1, Mat bin2)
{
if (whiteRatio(bin1) * whiteRatio(bin2) == 0)
return false;
Mat joined = concatImages(bin1,bin2);
if (getBinImgHeight(joined) < 1.3 * getBinImgWidth(joined)) return false;
return true;
}
void processCharImages(std::vector<cv::Mat> &charImages, // вернутся новые - инвертированные и обрезанные
std::vector<cv::Mat> charBinImages,
std::vector<int> values,
Mat binImg,
std::vector<int> local_mins,
std::vector<cv::Mat> &unitedImages, // Объединяет те charImages, объед. которых удовл. ф-и canBeJoined,
std::vector<int> &unitedBegins // хранит порядк.номер левого из charImage'й, из которых он сделан
)
{ // решаем, что делать с кусками номера между лок.миним.
std::vector<int> cbj; // cbj = canBeJoined, можно ли объединить i-й и (i+1)-й
for (int i = 0; i < charBinImages.size()-1; i++)
{
if (canBeJoined(charBinImages.at(i),charBinImages.at(i+1)))
cbj.push_back(1);
else
cbj.push_back(0);
}
std::vector<cv::Mat> unitedBinImages;
int curr_number_height = charImages.at(0).rows;
for (int i = 0; i < local_mins.size(); i++)
{
if (cbj.at(i)==1)
{
Mat united = concatImages(charImages.at(i),charImages.at(i+1));
Mat unitedBin = concatImages(charBinImages.at(i),charBinImages.at(i+1));
unitedImages.push_back(united);
unitedBegins.push_back(i);
unitedBinImages.push_back(unitedBin);
}
}
// Обрезка charImages и unitedImages по черному с трех сторон
std::vector<cv::Mat> cut_charImages;
std::vector<cv::Mat> cut_unitedImages;
for (int i = 0; i < charImages.size(); i++)
{
cut_charImages.push_back(cutCharWhite(charImages.at(i),charBinImages.at(i)));
}
for (int i = 0; i < unitedImages.size(); i++)
{
cut_unitedImages.push_back(cutCharWhite(unitedImages.at(i),unitedBinImages.at(i)));
}
charImages.swap(cut_charImages);
unitedImages.swap(cut_unitedImages);
// Инвертирование
for (int i = 0; i < charImages.size(); i++)
{
charImages.at(i) = invertImage(charImages.at(i));
}
for (int i = 0; i < unitedImages.size(); i++)
{
unitedImages.at(i) = invertImage(unitedImages.at(i));
}
Mat tmp = drawNumberSeparated(charImages,unitedImages,unitedBegins,curr_number_height);
tmpShow(tmp);
}
std::vector<int> recognize(cv::Mat number_image)
{
Mat image;
number_image.copyTo(image);
Mat binImage;
image = binarize(image);
image.copyTo(binImage);
number_image.copyTo(image);
int* histArr = getVertHist(binImage); // вычислить вертикальную гистограмму
minPositions = localMins(histArr,binImage.cols); // вычислить локальные минимумы на ней
int* values = new int[NUM_MINS];
for (int i = 0; i < NUM_MINS; i++)
{
values[i] = histArr[minPositions[i]];
}
std::vector<int> new_local_mins = clearLocalMins(minPositions, values, NUM_MINS);
std::vector<int> new_values;
// создать вектор хранящий значения в новых.лок.мин-х
for (int i = 0; i < new_local_mins.size(); i++)
{
new_values.push_back(histArr[new_local_mins.at(i)]);
}
std::vector<cv::Mat> charImages; // куски изображения между двумя минимумами, предположительно - символ
std::vector<cv::Mat> charBinImages; // то же ЧБ
// разбить изображение номера и бин.номера на отдельные картинки
splitIntoImages(image,binImage,new_local_mins,charImages,charBinImages);
// Проверка на то, есть ли хоть один локальный минимум == 0. Если да, распознаем, нет - адьос.
int mult = 1;
for (int i = 0; i < new_values.size(); i++)
mult *= new_values.at(i);
std::vector<Mat> unitedImages;
std::vector<int> unitedBegins;
if (mult == 0)
processCharImages(charImages,
charBinImages,
new_values,
binImage,
new_local_mins,
unitedImages,
unitedBegins);
// TO DO - подготовка к распознаванию, распознавание, обработка результатов!
//drawLocalMins(binImage,new_local_mins);
//tmpShow(binImage);
//tmpShow(image);
std::vector<int> recognized_number;
return recognized_number;
}
// CURRENT DEVELOPMENT END // CURRENT DEVELOPMENT END // CURRENT DEVELOPMENT END // CURRENT DEVELOPMENT END
// CURRENT DEVELOPMENT END // CURRENT DEVELOPMENT END // CURRENT DEVELOPMENT END // CURRENT DEVELOPMENT END
// Функции алгоритма
void myMATLABLocalization(char* filename)
{
// BEGIN Prepare for playing video
capture.open(filename); // from file
int num_frames = capture.get(CV_CAP_PROP_FRAME_COUNT);
if (num_frames > 0)
VIDEO_TRACKBAR_MAX_VALUE=num_frames;
else
VIDEO_TRACKBAR_MAX_VALUE = 1000;
double rate = capture.get(CV_CAP_PROP_FPS); // frames per second
bool stop(false);
cv::Mat frame,prev_frame,background_frame;
std::vector<cv::KeyPoint> curr_keypts,prev_keypts,
background_keypts; // кейпойнты фона (нужно будет делать снимок фона перед проездом поезда и вычислять кейпойнты)
// Declaring windows
cv::namedWindow("Extracted Frame 1");
cv::namedWindow("Settings");
int frameNumber = 0;
int delay = 1000/rate; // 1000 microseconds = 1 sec => delay is real time needed for one frame in current avi.
// END
capture.read(frame);
widenFrame(frame,15);
//// Setup output video
//cv::VideoWriter output_cap("C:\\Main\\WORK\\!test\\current_wagons.avi",
// capture.get(CV_CAP_PROP_FOURCC),
// capture.get(CV_CAP_PROP_FPS),
// cv::Size(frame.cols,frame.rows));
//// int codec = static_cast<int>(capture.get(CV_CAP_PROP_FOURCC));
//if (!output_cap.isOpened())
//{
// std::cout << "!!! Output video could not be opened" << std::endl;
// return;
//}
// Параметры, зависящие от конкретного видео
DOWN_BORDER = frame.rows;
MIN_BBOX_AREA = NUMBER_HEIGHT * NUMBER_HEIGHT;
cv::moveWindow("Extracted Frame 1",200,50);
cv::moveWindow("Extracted Frame 2",200,130+frame.rows);
cv::moveWindow("Histogram",200+frame.cols+20,130+frame.rows);
cv::moveWindow("Settings",200+frame.cols+20,50);
// Adding trackbars...
createTrackbar("Frame No", "Settings", &VIDEO_TRACKBAR_VALUE, VIDEO_TRACKBAR_MAX_VALUE, on_trackbar_listener);
createTrackbar("FAST_THRES", "Settings", &FASTTHRESH_TRACKBAR_VALUE, FASTTHRESH_TRACKBAR_MAX_VALUE, on_trackbar2_listener);
createTrackbar("RADIUS_X", "Settings", &RADIUS_X_TRACKBAR_VALUE, RADIUS_TRACKBAR_MAX_VALUE, on_trackbar3_listener);
createTrackbar("RADIUS_Y", "Settings", &RADIUS_Y_TRACKBAR_VALUE, RADIUS_TRACKBAR_MAX_VALUE, on_trackbar3_listener);
createTrackbar("COMPR_RATE", "Settings", &COMPR_RATE_TRACKBAR_VALUE, COMPR_RATE_TRACKBAR_MAX_VALUE, on_trackbar3_listener);
setMouseCallback( "Extracted Frame 1", onMouse, 0 );
printf("NUMBER_HEIGHT=%d;\n",NUMBER_HEIGHT);
num_frame = 0;
while (!stop)
{
frame.copyTo(prev_frame);
std::swap(curr_keypts, prev_keypts);
num_frame++;
cv::setTrackbarPos("Frame No","Settings",1+getTrackbarPos("Frame No","Settings"));
if (!capture.read(frame))
break;
widenFrame(frame,15);
cv::Mat image1(frame.rows,frame.cols,CV_8UC3,cv::Scalar(0));
cv::Mat image2(frame.rows,frame.cols,CV_8UC3,cv::Scalar(0));
frame.copyTo(image1);
frame.copyTo(image2);
curr_keypts = detectCorners(frame,COMPR_RATE,CORNERS_THRESH);
if (num_frame == 1) // считаем, что на первом кадре ФОН, тогда навсегда сохраним изображение фона и его кейпойнты
{
frame.copyTo(background_frame);
background_keypts=detectCorners(frame,COMPR_RATE,5);
}
if (num_frame > 2 )//&& prev_keypts.size() > 0)
{
curr_keypts = cleanStaticKeypts(curr_keypts,background_keypts,frame,background_frame); // почистить от кейпойнтов фона
if ( prev_keypts.size() > 0 )
{
//curr_keypts = cleanStaticKeypts(curr_keypts,prev_keypts,frame,prev_frame); // почистить от кейпойнтов предыдущего кадра
}
}
image2 = searchForNumber(image2,prev_frame,curr_keypts,prev_keypts);
int key = cv::waitKey(delay/5);
if (key == 27) // ESC pressed - close window
{
stop = true;
}
else if (key == 32) // SPACE pressed - pause until any key pressed
{
cv::waitKey(0);
}
else if (key == 9)
{
cv::putText(image2,"SETTING UP BORDERS",Point(10,image1.rows/2), FONT_HERSHEY_SIMPLEX, .9, CV_RGB(0,0,0));
cv::imshow("Extracted Frame 1",image2);
borders_setting = 1;
cv::waitKey(0);
}
drawBorders(image2);
//cv::imshow("Extracted Frame 1",image1);
cv::imshow("Extracted Frame 1",image2);
//output_cap.write(image2);
}
capture.release();
//output_cap.release();
}
cv::Mat searchForNumber(cv::Mat image,cv::Mat prev_frame,std::vector<cv::KeyPoint> curr_keypts,
std::vector<cv::KeyPoint> prev_keypts)
{
printf("\n\nFrame No:%d",num_frame);
double t; // time
std::vector<Region> regions; // хранит все области-кандидаты данного кадра
cv::Mat cleanImage;
image.copyTo(cleanImage);
std::vector<cv::KeyPoint> keypoints;
clearKeypointsByAreaHeight(curr_keypts,keypoints); // отсеять keypoint'ы по огранич. высоте
// Отрисовка keypoints
t = (double)getTickCount();
cv::drawKeypoints(image,keypoints,image,cv::Scalar(0,255,0),cv::DrawMatchesFlags::DRAW_OVER_OUTIMG);
t = ((double)getTickCount() - t) / getTickFrequency();
printf("\nKeypoints drawing time: %0.5f",t);
// Объединение keypoints в группы по связности
t = (double)getTickCount();
std::vector<std::vector<cv::KeyPoint>> kp_groups;
if (keypoints.size() > 0)
{
kp_groups = getKeypointGroups(keypoints,RADIUS_X,RADIUS_Y);
}
t = ((double)getTickCount() - t) / getTickFrequency();
printf("\nKeypoints processing time: %0.5f",t);
t = (double)getTickCount();
// Создание регионов по кейпойнтам (с ограничениями (*))
for (int i = 0; i < kp_groups.size(); i++)
{
if (kp_groups.at(i).size() >= 4) // (*) а) минимальное кол-во точек для создания региона = 4
{
Region tmp_region(kp_groups.at(i),cleanImage);
if( tmp_region.box.size.area() > MIN_BBOX_AREA) // (*) учитываем только регионы с площадью box'a не менее чем заданная
{
regions.push_back(tmp_region);
}
}
}
// Обработка регионов, отбрасывание лишних
std::vector<cv::Mat> united_images; // изображения, полученные объединением двух соседних по горизонтали регионов
regions = processFrameRegions(cleanImage,regions,united_images);
for (int i = 0; i < regions.size(); i++)
{
Region tmp_region = regions.at(i);
if ( tmp_region.rect.height > NUMBER_HEIGHT * h_alpha_down &&
tmp_region.rect.height < NUMBER_HEIGHT * h_alpha_up &&
tmp_region.rect.width > NUMBER_HEIGHT * 3.5
&& checkIfText(tmp_region,cleanImage)) // удовлетворяет ли этот прямоугольник ограничениям
{
tmp_region.drawRect(image);
recognize(cleanImage(tmp_region.rect));
// + инвертированное
Mat inv = invertImage(cleanImage(tmp_region.rect));
recognize(inv);
char filename[50];
std::sprintf(filename,"C:\\Main\\WORK\\!test\\%d-%d.bmp",num_frame,i);
//cv::imwrite(filename,concatImages(recogn_im,inv_recogn_im));
}
else
{
tmp_region.drawRect(image,cv::Scalar(0,0,255),2);
}
//cv::Mat bin = binarize(cleanImage(tmp_region.rect));
//bin.copyTo(image(tmp_region.rect));
/*char filename[50];
std::sprintf(filename,"C:\\Main\\WORK\\!test\\%d-%d.bmp",num_frame,i);
cv::imwrite(filename,cleanImage(tmp_region.rect));*/
}
for (int i = 0; i < united_images.size(); i++)
{
if ( united_images.at(i).rows > NUMBER_HEIGHT * h_alpha_down &&
united_images.at(i).rows < NUMBER_HEIGHT * h_alpha_up &&
united_images.at(i).cols > NUMBER_HEIGHT * 3.5) // удовлетворяет ли этот прямоугольник ограничениям
{
if (true) // CHECK IF TEXT!!!
{
recognize(united_images.at(i));
// + инвертированное
Mat inv = invertImage(united_images.at(i));
recognize(inv);
}
}
}
t = ((double)getTickCount() - t) / getTickFrequency();
printf("\nAreas processing (incl. drawing) time: %0.5f",t);
return image;
}
std::vector<Region> processFrameRegions(cv::Mat frame,std::vector<Region> regions,std::vector<cv::Mat> &united_images)
{
std::vector<Region> new_regions;
// а) Проверка на ПЕРЕСЕЧЕНИЕ регионов
// если пересекаются - объединить в один
new_regions = getJoinedRegions(regions,frame);
// б) Обрезает лишнее сверху и снизу
new_regions = cutRegionsUpDown(new_regions,frame);
for (int i = 0; i < new_regions.size(); i++)
{
new_regions.at(i).rect = widenRect(new_regions.at(i).rect,3);
}
// в) Разрезать на слова
// cutIntoWords !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// г) Проверка на наличие двух соседних регионов
// позволяет соединять части номера в одно изображение
united_images = getUnitedImages(new_regions,frame);
/*for (int i = 0; i < united_images.size(); i++)
{
char filename[50];
std::sprintf(filename,"C:\\Main\\WORK\\!test\\united_%d-%d.bmp",num_frame,i);
cv::imwrite(filename,united_images.at(i));
}*/
return new_regions;
}
// Важные функции
std::vector<cv::KeyPoint> detectCorners(cv::Mat image/* входящее изображение*/, float ratio /* коэфф сжатия высоты и ширины*/,int fast_thresh /*порог для детекции уголков*/)
{
// vector of keypoints
std::vector<cv::KeyPoint> keypoints;
// corners detector
cv::FastFeatureDetector fast(
fast_thresh); // threshold for detection
cv::Mat small_image;
cv::resize(image,small_image,cv::Size(image.cols/ratio,image.rows/ratio));
fast.detect(small_image,keypoints);
// drawing keypoints on the image
cv::Mat blackIm(image.rows,image.cols,CV_8UC3,cv::Scalar(0));
for (int j = 0; j < (int)keypoints.size(); j++)
{
// change keypoints coords * ratio
keypoints.at(j).pt.x *= ratio;
keypoints.at(j).pt.y *= ratio;
}
return keypoints;
}
std::vector<std::vector<cv::KeyPoint>> getKeypointGroups(std::vector<cv::KeyPoint> keypoints,int RADIUS_X,int RADIUS_Y)
{
std::vector<std::vector<cv::KeyPoint>> kp_groups;
const int N = (int)keypoints.size();
int i;
int* id = new int[N]; // будет хранить "связные" области (как в алгоритме из книги)
for (i = 0; i < N; i++) id[i] = i;
// Перебор вершин
for (int j = 0; j < N-1; j++)
for (int k = j+1; k < N; k++)
{
float X = keypoints.at(j).pt.x-keypoints.at(k).pt.x;
float Y = keypoints.at(j).pt.y-keypoints.at(k).pt.y;
//if ( (int)pow(X,2) + (int)pow(Y,2) < (int)pow((float)RADIUS,2)) // СТАРАЯ ВЕРСИЯ - ПОИСК В КРУГЕ.
if ( (int)(pow(X,2) / pow((float)RADIUS_X,2)) + (int)(pow(Y,2) / pow((float)RADIUS_Y,2)) < 1 ) // эллипс
{
//printf("This keypoints are connected - %d and %d\n",j,k);
//printf("j=%d; k=%d; X=%f; Y=%f; sumsquared=%d; RADIUS^2=%d\n",j,k,X,Y,(int)pow(X,2) + (int)pow(Y,2),(int)pow((float)RADIUS,2));
int t = id[j];
if (t == id[k]) continue;
for (i = 0; i < N; i++)
if (id[i] == t) id[i] = id[k];
}
}
std::vector<int> groups; // будет хранить уникальные номера групп (Пр. 1 25 - то в id есть только все элементы равны или 1, или 25, т.е. образуют две связные области)
for (i = 0; i < N; i++)
{
bool unique = true;
for (int j = 0; j < groups.size(); j++)
{
if (id[i] == groups.at(j))
unique = false;
}
if (unique)
groups.push_back(id[i]);
}
//// для каждой группы создать вектор keypoint-ов, состоящий только их keypoint-ов этой группы
for (int j = 0; j < groups.size(); j++)
{
std::vector<cv::KeyPoint> tmp;
// Проход по точкам
for (i = 0; i < N; i++)
{
if (id[i] == groups.at(j))
tmp.push_back(keypoints.at(i));
}
kp_groups.push_back(tmp);
}
return kp_groups;
}
void getTrueBoxWidthHeight(RotatedRect bBox,float &width,float &height)
{
// вовзращает настоящие высоту и ширину box-а
double angle = bBox.angle; // угол поворота
if (angle <= -45.)
angle += 90.;
if (angle < 0)
{
width = bBox.size.width;
height = bBox.size.height;
}
else if (angle > 0)
{
width = bBox.size.height;
height = bBox.size.width;
}
else
{
cv::Point2f vertices[4];
bBox.points(vertices);
if (vertices[0].x == vertices[1].x)
{
height = abs(vertices[0].y - vertices[1].y);
width = abs(vertices[0].x - vertices[2].x);
}
else
{
height = abs(vertices[0].y - vertices[2].y);
width = abs(vertices[0].x - vertices[1].x);
}
}
//printf("\nangle=%.2f,height=%.2f,width=%.2f",bBox.angle,height,width);
}
cv::RotatedRect getMinBBox(cv::Mat image,std::vector<cv::Point> points)
{
// найти минимальный описанный прямоугольник вокруг точек
cv::RotatedRect box = cv::minAreaRect(cv::Mat(points));
return box;
}
cv::Mat drawMinBBox(cv::Mat image, cv::RotatedRect box,cv::Scalar color)
{
double angle = box.angle; // угол поворота
if (angle <= -45.)
angle += 90.;
cv::Point2f vertices[4];
box.points(vertices);
for(int i = 0; i < 4; ++i)
{
cv::line(image, vertices[i], vertices[(i + 1) % 4], color, 1, CV_AA);
}
float height,width;
getTrueBoxWidthHeight(box,width,height);
char msg[30];
std::sprintf(msg, "(%.1f,%.1f,%.1f)", angle,height,width);
putText(image, msg, (cv::Point)box.center, FONT_HERSHEY_SIMPLEX, .4, CV_RGB(255,0,0));
return image;
}
bool checkedMinBBox(cv::RotatedRect box)
{
// ПРОВЕРКА BOX-a:
// 1) угол наклона
// 2) высота
// 3) положение в кадре (от UP_BORDER до DOWN_BORDER)
float height,width;
getTrueBoxWidthHeight(box,width,height);
double angle = box.angle; // угол поворота
if (angle <= -45.)
angle += 90.;
if (angle > ANGLE_THRESH || angle < - ANGLE_THRESH) // отсеять по углу наклона
return false;
if (height > NUMBER_HEIGHT*h_alpha_up || height < NUMBER_HEIGHT * h_alpha_down)
return false;
if (box.center.y < UP_BORDER || box.center.y > DOWN_BORDER)
return false;
return true;
}
void clearKeypointsByAreaHeight(std::vector<cv::KeyPoint> keypoints,std::vector<cv::KeyPoint> &out_keypoints)
{
out_keypoints.clear();
for (int i = 0; i < keypoints.size(); i++)
{
if (keypoints.at(i).pt.y > UP_BORDER && keypoints.at(i).pt.y < DOWN_BORDER)
out_keypoints.push_back(keypoints.at(i));
}
}
cv::Mat getBBoxImage(cv::Mat image,cv::RotatedRect box)
{// ПОЛУЧЕНИЕ РЕАЛЬНОЙ КАРТИНКИ ИЗ ИЗОБРАЖЕНИЯ ПО bbox-у
// АЛГОРИТМ - 1) ПОЛУЧИТЬ ПОВЕРНУТОЕ ИЗОБРАЖЕНИЕ,
// 2) ПОЛУЧИТЬ КООРДИНАТЫ ПРЯМОУГОЛЬНИКА НА ПОВЕРНУТОМ,
// 3) ВЫДЕЛИТЬ НА НЕМ ROI и вернуть
cv::Mat imgROI;
image.copyTo(imgROI);
double angle = box.angle; // угол поворота
if (angle <= -45.)
angle += 90.;
imrotate(imgROI,imgROI,angle);
cv::Mat rot_mat = getRotationMatrix2D(Point(imgROI.cols/2,imgROI.rows/2),angle,1);
cv::Point2f vertices[4],new_vertices[4];
box.points(vertices);
for (int i = 0; i < 4; i++)
{
new_vertices[i].x = abs(rot_mat.at<double>(0,0) * vertices[i].x + rot_mat.at<double>(0,1) * vertices[i].y + rot_mat.at<double>(0,2));
new_vertices[i].y = abs(rot_mat.at<double>(1,0) * vertices[i].x + rot_mat.at<double>(1,1) * vertices[i].y + rot_mat.at<double>(1,2));
}
cv::Rect rect(new_vertices[0],new_vertices[2]);
if (rect.x < 0 || rect.x+rect.width >= imgROI.cols-1 || rect.y < 0 || rect.y+rect.height >= imgROI.rows)
{
// если область вылазит за пределы изображения, вернуть один пиксел
cv::Mat errIm(1,1,CV_8U);
return errIm;
}
else
{ // если удовлетворяет - выделяем ее на изображени
imgROI = imgROI(rect);
}
//cv::Mat box_image = image(box);
return imgROI;
}
std::vector<Region> getJoinedRegions(std::vector<Region> regions,cv::Mat frame)
{
const int N = regions.size();
int* id = new int[N]; // будет хранить "связные" области (как в алгоритме из книги)
for (int i = 0; i < N; i++) id[i] = i;
for (int j = 0; j < N-1; j++)
for (int k = j+1; k < N; k++)
{
if ( checkRectOverlap(regions.at(k).rect,regions.at(j).rect) )
{
int t = id[j];
if (t == id[k]) continue;
for (int i = 0; i < N; i++)
if (id[i] == t) id[i] = id[k];
}
}
std::vector<Region> new_regions;
for (int j = 0; j < regions.size(); j++)
{
int group_no = id[j];
if (!regions.at(j).isGood) continue; // если еще не участвовал в объединении
std::vector<cv::KeyPoint> tmp_keypts = regions.at(j).keypts; // хранит все кейпойнты объедин-го региона
for (int k = j+1; k < regions.size(); k++)
{
if (id[k] == group_no && regions.at(k).isGood)
{
tmp_keypts.insert(tmp_keypts.end(),regions.at(k).keypts.begin(),regions.at(k).keypts.end());
regions.at(k).isGood = false; // уже участвовал в объединении, больше не нужен
}
}
if (tmp_keypts.size() == regions.at(j).keypts.size())
{
new_regions.push_back(regions.at(j));
}
else
{
Region reg(tmp_keypts,frame);
new_regions.push_back(reg);
}
}
return new_regions;
}
std::vector<cv::Mat> getUnitedImages(std::vector<Region> regions,cv::Mat frame)
{
std::vector<cv::Mat> united_images;
// ПРОВЕРКА, НЕТ ЛИ РЯДОМ СПРАВА ИЛИ СЛЕВА РЕГИОНА С СОПОСТАВИМОЙ ВЫСОТОЙ, ЕСЛИ ЕСТЬ СОЗДАТЬ ОБЪЕДИНЕННОЕ ИЗОБРАЖЕНИЕ
for (int i = 0; i < regions.size(); i++)
{
for (int j = i+1; j < regions.size(); j++)
{
Rect rect1 = regions.at(j).rect;
Rect rect2 = regions.at(i).rect;
// Условия на объединяемые прямоугольники
if (
(rect1.y + rect1.height/2 > rect2.y && rect1.y + rect1.height/2 < rect2.y + rect2.height) && //середина одного не выходит за верт. границы другого (чтобы друг напротив друга)
(abs(rect1.x+rect1.width - rect2.x) < NUMBER_HEIGHT*2 || // небольшое расстояние по горизонтали
abs(rect2.x+rect2.width - rect1.x) < NUMBER_HEIGHT*2) &&
(rect1.width < NUMBER_HEIGHT * 3 || rect2.width < NUMBER_HEIGHT * 3) && // один из них более узкий, чем три высоты номера
!checkRectOverlap(rect1,rect2) && // не пересекаются
(rect1.height > 0.8*NUMBER_HEIGHT && rect2.height > 0.8 * NUMBER_HEIGHT) && // высота не ниже чем
(rect1.height < 2 * NUMBER_HEIGHT && rect2.height < 2 * NUMBER_HEIGHT) && // и не выше чем
( rect1.width > 2 * NUMBER_HEIGHT || rect2.width > 2 * NUMBER_HEIGHT ) && // один из них шире, чем две высоты номера
rect1.width < frame.cols * 0.66 && rect2.width < frame.cols * 0.66 // каждая область не шире чем 2/3 ширины кадра
)
{
cv::Mat im1;
cv::Mat im2;
if (rect1.x < rect2.x)
{
im1 = frame(rect1);
im2 = frame(rect2);
}
else
{
im1 = frame(rect2);
im2 = frame(rect1);
}
cv::Mat tmp1,tmp2;
im1.copyTo(tmp1);
im2.copyTo(tmp2);
cv::Mat res = concatImages(tmp1,tmp2);
united_images.push_back(res);
}
}
}
return united_images;
}
std::vector<cv::KeyPoint> cleanStaticKeypts(std::vector<cv::KeyPoint> curr_keypts,std::vector<cv::KeyPoint> prev_keypts, Mat curr_frame, Mat prev_frame)
{
cv::Mat prev_desc, curr_desc;
std::vector<cv::DMatch> matches;
cv::BruteForceMatcher<cv::Hamming> matcher;
cv::BriefDescriptorExtractor extractor;
extractor.compute(curr_frame, curr_keypts, curr_desc);
extractor.compute(prev_frame, prev_keypts, prev_desc);
std::vector<cv::KeyPoint> pois;
if (prev_keypts.size() == 0)
return curr_keypts;
try // matcher throws an error because there aren't sometimes any matches.
{
matcher.match( curr_desc, prev_desc, matches);
}
catch (...)
{
printf("error");
}
// Пороги - смещение не менее чем и не более чем
int DIST_THOLD = 100;
float V_THOLD = 0.1f;
for (int i = 0; i < matches.size(); i++)
{
if (matches[i].distance < DIST_THOLD)
{
float x_d = curr_keypts[matches[i].queryIdx].pt.x -
prev_keypts[matches[i].trainIdx].pt.x;
float y_d = curr_keypts[matches[i].queryIdx].pt.y -
prev_keypts[matches[i].trainIdx].pt.y;
if (sqrt(x_d * x_d + y_d * y_d) > V_THOLD)
{
pois.push_back(curr_keypts[matches[i].queryIdx]);
}
}
}
return pois;
}
std::vector<int> clearLocalMins(int* minPositions, int* values, int n)
{ // если два лок.минимума в гистограмме номера ближе, чем MIN_DIST пикс.,
//то оставить тот из них, значение в котором меньше.
int MIN_DIST = 5;
std::vector<int> new_local_mins;
int i = 0;
while (i < n)
{
if (i == n - 1) // последнее записываем по умолч.
{
new_local_mins.push_back(minPositions[i]);
break;
}
if (minPositions[i+1] - minPositions[i] < MIN_DIST) // расст между текущим и след миним-ми меньше MIN_DIST
{ // проверить значение в каком из них меньше
if (values[i] <= values[i+1])
{ // добавить i-й
new_local_mins.push_back(minPositions[i]);
i++; // чтобы пропустить в будущем i+1-й элемент
}
else
{ // добавить i+1-й
new_local_mins.push_back(minPositions[i+1]);
i++;
}
}
else
{ // добавить этот минимум в текущие
new_local_mins.push_back(minPositions[i]);
}
i++;
}
return new_local_mins;
}
std::vector<Region> cutRegionsUpDown(std::vector<Region> regions,cv::Mat frame)
{// Вернет новые регионы, разрезанные на вертикальные слова (или удалит, если неудачно)
std::vector<Region> new_regions;
std::vector<cv::Rect> new_rects;
for (int nReg = 0; nReg < regions.size(); nReg++) // для каждого старого региона
{
cv::Mat processedImage;
frame(regions.at(nReg).rect).copyTo(processedImage);
processedImage = binarize(processedImage);
cv::morphologyEx(processedImage,processedImage,MORPH_GRADIENT,cv::Mat(1,5,CV_8U));
cv::morphologyEx(processedImage,processedImage,MORPH_CLOSE,cv::Mat(1,processedImage.cols/3,CV_8U));
int n = processedImage.rows;
int* inp_arr = calcHist(processedImage);
inp_arr = medFiltHist(inp_arr,n);
minPositions = localMins(inp_arr,n,10);
int mean = 0;
for (int i = 0; i < n; i++)
{
mean += inp_arr[i];
}
mean = mean/n;
for (int i = 0; i < n; i++)
{
if (inp_arr[i] < 255*processedImage.cols / 5 )
//|| ( belongs(i,minPositions,NUM_MINS) && inp_arr[i] < mean / 2)) // по локальным минимумам
inp_arr[i] = 0;
}
// разбиение на горизонтальные области
std::vector<std::vector<int>> row_arrays;
std::vector<int> tmp_arr;
if (inp_arr[0] != 0) // если область началась сразу
tmp_arr.push_back(0);
for (int i = 1; i < n; i++)
{
if ((inp_arr[i] == 0 && inp_arr[i-1] != 0) // начались нули
|| (i==n-1 && inp_arr[i] != 0))
{
tmp_arr.push_back(i);
row_arrays.push_back(tmp_arr);
tmp_arr.clear();
}
else if ((inp_arr[i] != 0 && inp_arr[i-1] == 0)) // началась область
{
tmp_arr.push_back(i);
}
}
for (int i = 0; i < row_arrays.size(); i++)
{
if (row_arrays.at(i).size() == 2)
{
cv::Rect rect(regions.at(nReg).rect.x,
regions.at(nReg).rect.y+row_arrays.at(i).at(0),
regions.at(nReg).rect.width,
row_arrays.at(i).at(1) - row_arrays.at(i).at(0));
Region tmp_reg(rect);
new_rects.push_back(rect);
new_regions.push_back(tmp_reg);
}
}//END разбиение на горизонтальные области
/*// Отрисовка обрезания
// Draw histogram image
cv::Mat histImg(n,2*n,CV_8U,cv::Scalar(0));
int maxValue = 255*processedImage.cols;
int intensity = 0;
for (int i = 0; i < n; i++)
{
intensity = (int)(2*n * inp_arr[i]/maxValue);
cv::line(histImg,cv::Point(0,i),
cv::Point(intensity,i),
cv::Scalar::all(255));
//printf("\nrow[%d]=%d;",i,intensity);
}
cv::Mat clearRegion;
frame(regions.at(nReg).rect).copyTo(clearRegion);
cv::cvtColor(clearRegion,clearRegion,CV_RGB2GRAY);
cv::Mat tmp = concatImages(concatImages(clearRegion,processedImage),histImg);
for (int i = 0; i < n; i++)
{
//printf("\ninp_arr[%d]=%d",i,inp_arr[i]);
if (inp_arr[i] == 0)
cv::line(tmp,cv::Point(0,i),
cv::Point(tmp.cols-1,i),
cv::Scalar::all(0));
}
// Нарисовать локальные минимумы на гистограмме.
//for (int i = 0; i < NUM_MINS; i++) //while (minPositions[i] > 0 && minPositions[i] < n)
//{
// //if (inp_arr[minPositions[i]] < )
// printf("\n%d",inp_arr[minPositions[i]]);
// cv::line(tmp,cv::Point(0,minPositions[i]),
// cv::Point(tmp.cols-1,minPositions[i]),
// cv::Scalar::all(128));
//}
tmpShow(tmp);
cv::imwrite(filename,tmp);*/
}
return new_regions;
}
void splitIntoImages(Mat image,Mat binImage,std::vector<int> new_local_mins,std::vector<cv::Mat> &charImages,std::vector<cv::Mat> &charBinImages)
{// Сохранить по отдельности в картинки
charImages.clear(); charBinImages.clear();
Mat charImg,charBinImg;
image(Range(0,image.rows-1),Range(0,new_local_mins.at(0))).copyTo(charImg);
charImages.push_back(charImg);
binImage(Range(0,image.rows-1),Range(0,new_local_mins.at(0))).copyTo(charBinImg);
charBinImages.push_back(charBinImg);
charImg.release();
charBinImg.release();
for (int i = 0; i < new_local_mins.size()-1; i++)
{
Mat charImg,charBinImg;
image(Range(0,image.rows-1),Range(new_local_mins.at(i),new_local_mins.at(i+1))).copyTo(charImg);
charImages.push_back(charImg);
binImage(Range(0,image.rows-1),Range(new_local_mins.at(i),new_local_mins.at(i+1))).copyTo(charBinImg);
charBinImages.push_back(charBinImg);
}
image(Range(0,image.rows-1),
Range( new_local_mins.at(new_local_mins.size()-1) , image.cols-1)).copyTo(charImg);
charImages.push_back(charImg);
binImage(Range(0,image.rows-1),
Range( new_local_mins.at(new_local_mins.size()-1) , image.cols-1)).copyTo(charBinImg);
charBinImages.push_back(charBinImg);
}
// Временно неиспользуемые
std::vector<cv::RotatedRect> makeTracking(std::vector<cv::KeyPoint> curr_keypts,std::vector<cv::KeyPoint> prev_keypts,cv::Mat &curr_image,cv::Mat prev_image,
std::vector<cv::RotatedRect> prev_boxes)
{
std::vector<std::vector<cv::KeyPoint>> prev_box_groups,curr_box_groups; // будут хранить группы кейпойнтов для каждого minBBox'a
// Оставить из старых кейп-в только принадлежащие прямоугольникам, разбить их на группы
for (int ctr_box = 0; ctr_box < prev_boxes.size(); ctr_box++)
{
std::vector<cv::KeyPoint> tmp_group;
cv::Point2f vert[4];
prev_boxes.at(ctr_box).points(vert);
std::vector<cv::Point2f> vertices;
for (int i = 0; i < 4; i++) vertices.push_back(vert[i]);
for (int ctr_keypt = 0; ctr_keypt < prev_keypts.size(); ctr_keypt++)
{
if (belongsToArea(prev_keypts.at(ctr_keypt).pt,vertices))
{
tmp_group.push_back(prev_keypts.at(ctr_keypt));
}
}
prev_box_groups.push_back(tmp_group);
}
std::vector<cv::DMatch> matches = getBriskMatches(curr_image,prev_image,curr_keypts,prev_keypts);
// нарисовать на старом старые прямоугольники - со временем удалить
for (int i = 0; i < prev_boxes.size(); i++)
{
RotatedRect tmp_box = prev_boxes.at(i);
prev_image = drawMinBBox(prev_image,tmp_box,cv::Scalar(0,0,255));
}
cv::Mat img_matches;
curr_image.copyTo(img_matches);
img_matches = drawBriskMatches(curr_image,prev_image,curr_keypts,prev_keypts,matches);
// Поиск соответствий точкам из prev_box_groups в curr_keypts и запись в curr_box_groups.
for (int ctr_gr = 0; ctr_gr < prev_box_groups.size(); ctr_gr++)
{
std::vector<cv::KeyPoint> tmp = prev_box_groups.at(ctr_gr);
std::vector<cv::KeyPoint> tmp2;
// Проход по каждой группе, поиск соответствий
for (int ctr = 0; ctr < tmp.size(); ctr++)
{
for (int i = 0; i < matches.size(); i++)
{
if (prev_keypts.at(matches.at(i).trainIdx).pt.x == tmp.at(ctr).pt.x &&
prev_keypts.at(matches.at(i).trainIdx).pt.y == tmp.at(ctr).pt.y
&& abs(tmp.at(ctr).pt.y - curr_keypts.at(i).pt.y) < HEIGHT_THRESH
&& abs(tmp.at(ctr).pt.x - curr_keypts.at(i).pt.x) < WIDTH_THRESH)
{
tmp2.push_back(curr_keypts.at(i));
}
}
}
curr_box_groups.push_back(tmp2);
}
printf("new boxes = %d; old boxes = %d; \n",curr_box_groups.size(), prev_box_groups.size());
std::vector<cv::RotatedRect> curr_boxes;
// вокруг каждой из новых групп сделать minBBox, нарисовать
for (int i = 0; i < curr_box_groups.size(); i++)
{
// Перевести в вектор точек points
std::vector<cv::Point> points;
for (int j = 0; j < curr_box_groups.at(i).size(); j++)
{
points.push_back(curr_box_groups.at(i).at(j).pt);
}
// нарисовать
printf("Points in group[%d]=%d\n",i,points.size());
if (points.size()>2)
{
cv::RotatedRect box = getMinBBox(img_matches,points);
img_matches = drawMinBBox(img_matches,box,cv::Scalar(255,255,0));
curr_boxes.push_back(box);
}
}
cv::namedWindow("win");
cv::imshow("win",img_matches);
return curr_boxes; // должно возвращать curr_boxes, но их пока нет.
}
std::vector<cv::DMatch> getBriskMatches(cv::Mat curr_frame, cv::Mat prev_frame, std::vector<cv::KeyPoint> curr_keypts,std::vector<cv::KeyPoint> prev_keypts)
{
cv::Mat prev_desc, curr_desc;
std::vector<cv::DMatch> matches;
cv::BruteForceMatcher<cv::Hamming> matcher;
cv::BriefDescriptorExtractor extractor;
extractor.compute(curr_frame, curr_keypts, curr_desc);
extractor.compute(prev_frame, prev_keypts, prev_desc);
try // matcher throws an error because there aren't sometimes any matches.
{
matcher.match( curr_desc, prev_desc, matches);
// инфо по текущему и предыдущему кадрам, ключесвым точкам и дескрипторам
//printf("\ncurr_desc.rows=%d,prev_desc.rows=%d,matches.size()=%d; curr_keyp.size()=%d; prev_keyp.size()=%d\n",curr_desc.rows,prev_desc.rows,matches.size(),curr_keypts.size(),prev_keypts.size());
//for (int i = 0; i < matches.size(); i++)
//{
// printf("Matches[%d].trainIdx=%d\n",i,matches.at(i).trainIdx); // какая точка какой соответствует
//}
}
catch (...)
{
printf("error");
}
return matches;
}
cv::Mat drawBriskMatches(cv::Mat curr_frame, cv::Mat prev_frame, std::vector<cv::KeyPoint> curr_keypts,std::vector<cv::KeyPoint> prev_keypts,std::vector<cv::DMatch> matches)
{
cv::Mat img_match;
cv::drawMatches(curr_frame, curr_keypts, prev_frame, prev_keypts, matches, img_match);
// Пронумеровать точки текущего кадра
for (int i = 0; i < curr_keypts.size(); i++)
{
char msg[30];
std::sprintf(msg, "%d", i);
putText(img_match, msg, curr_keypts.at(i).pt, FONT_HERSHEY_SIMPLEX, .4, CV_RGB(255,0,0));
}
// Пронумеровать точки предыдущего кадра
for (int i = 0; i < prev_keypts.size(); i++)
{
cv::Point2f pt = prev_keypts.at(i).pt;
pt.x += curr_frame.cols;
char msg[30];
std::sprintf(msg, "%d", i);
putText(img_match, msg, pt, FONT_HERSHEY_SIMPLEX, .4, CV_RGB(255,0,255));
}
return img_match;
}
std::vector<cv::DMatch> cleanMatches(std::vector<cv::DMatch> matches,std::vector<cv::KeyPoint> curr_keypts,std::vector<cv::KeyPoint> prev_keypts,int thresh)
{
std::vector<cv::DMatch> tmp_matches;
for (int i = 0; i < matches.size(); i++)
{
if (abs(curr_keypts.at(i).pt.y - prev_keypts.at(matches.at(i).trainIdx).pt.y) < thresh ) // отклонение по вертикали не более чем на thresh.
{
tmp_matches.push_back(matches.at(i));
}
}
return tmp_matches;
}
cv::Mat drawLinesHoughDetection(cv::Mat image)
{
//cv::Mat image = cv::imread("C:\\Main\\WORK\\Laganiere Images\\road.jpg");
cv::Mat contours;
cv::Canny(image,contours,125,350);
// Hough transform for line detection
std::vector<cv::Vec2f> lines;
//cv::cvtColor(image,image,CV_RGB2GRAY);
cv::HoughLines(contours,lines,
1,3.14/180, // step size
80); // minimum number of votes
std::vector<cv::Vec2f>::const_iterator it = lines.begin();
while (it != lines.end())
{
float rho = (*it)[0]; // first element is distanse rho
float theta = (*it)[1]; // second element is angle theta
if (theta<3.14/4. || theta > 3. * 3.14 / 4.) { // vertical line
// point of intersection of the line with first row
cv::Point pt1(rho/cos(theta),0);
// point of intersection of the line with last row
cv::Point pt2((rho - image.rows * sin(theta))/cos(theta),image.rows);
//draw a white line
cv::line(image,pt1,pt2,cv::Scalar(255),1);
}
else // horisontal line
{
// point of intersection of the
// line with the first column
cv::Point pt1(0,rho/sin(theta));
// point of intersection of the line with last column
cv::Point pt2(image.cols,(rho-image.cols*cos(theta))/sin(theta));
cv::line(image,pt1,pt2,cv::Scalar(255),1);
}
++it;
}
/*cv::namedWindow("win");
cv::imshow("win",image);
cv::waitKey(0);*/
return image;
}
cv::Mat getContours(cv::Mat image)
{
image = binarize(image);
std::vector<std::vector<cv::Point>> contours;
cv::findContours(image,
contours, // a vector of contours
CV_RETR_EXTERNAL, // retrieve the external contours
CV_CHAIN_APPROX_NONE); // all pixels of each contours
// Draw black contours on a white image
cv::Mat result(image.size(),CV_8U,cv::Scalar(255));
cv::drawContours(result,contours,
-1, // ALL CONTOURS
cv::Scalar(0), // in black
2); // thickness
return result;
}
// Вспомогательные функции
int* copyPartOfArray(int* inp_arr,int start,int finish)
{
// Вернет новый массив, содержащий в себе элементы массива inp_arr
// с элемента start (включительно) по элемент finish (невключительно).
const int win_size = finish-start;
int* out_arr = (int *)malloc(win_size * sizeof(int));
for (int i = start; i < finish; i++)
{
out_arr[i-start] = inp_arr[i];
}
return out_arr;
}
int* localMins(int* arr,int n,int win_width)
{
int* localmins = (int *)malloc(n * sizeof(int));
NUM_MINS = 0; // количество минимумов на текущий момент
int* current_window; // текущий подмассив, в котором ищется локальный минимум.
for (int i = 0; i < n - win_width; i++)
{
current_window = copyPartOfArray(arr,i,i+win_width);
int* mins = min(current_window,win_width);
if (mins[1] != 0 && mins[1] != win_width-1 && localmins[NUM_MINS-1] != mins[1] + i && !belongs(mins[1] + i,localmins,NUM_MINS-1)) // локальный минимум в окне
{
if (!(arr[mins[1] + i] == 0 && arr[mins[1] + i - 1] == 0 && arr[mins[1] + i + 1] == 0))
{
localmins[NUM_MINS] = mins[1] + i;
NUM_MINS += 1;
}
}
}
for (int i = 1; i < n - 1; i++)
{
if (((arr[i] == 0 && arr[i-1] > 0)||(arr[i] == 0 && arr[i+1] > 0))&&(!belongs(i,localmins,NUM_MINS-1))) // также к локальные минимумы добавляются "подножия" ([... 0 0 0 20 25 40 ...] и в другую сторону)
{
localmins[NUM_MINS] = i;
NUM_MINS += 1;
}
}
localmins = mysort(localmins,NUM_MINS);
return copyPartOfArray(localmins,0,NUM_MINS);
}
cv::Mat drawHist(cv::Mat image)
{
int n = image.rows;
int* inp_arr = calcHist(image);
inp_arr = medFiltHist(inp_arr,n);
inp_arr = medFiltHist(inp_arr,n);
inp_arr = cleanHist(inp_arr,n,120); // все, что меньше 20-ти в гистограмме сделать 0 (из-за сглаживания завтыки)
minPositions = localMins(inp_arr,n,NUMBER_HEIGHT);
// Draw histogram image
cv::Mat histImg(n,n,CV_8U,cv::Scalar(255));
int maxValue = -1;
/*for (int i = 0; i < n; i++)
{
if (inp_arr[i] > maxValue)
maxValue = inp_arr[i];
}*/ // если хотим, чтобы масштабировалось по максимальному элементу гистограммы
maxValue = 255*image.cols; // без масштабирования - максимум = 255 (белый пиксель) * количество пикселей в колонке
int intensity = 0;
for (int i = 0; i < n; i++)
{
intensity = (int)(n * inp_arr[i]/maxValue);
cv::line(histImg,cv::Point(0,i),
cv::Point(intensity,i),
cv::Scalar::all(0));
}
// Нарисовать локальные минимумы на гистограмме.
for (int i = 0; i < NUM_MINS; i++) //while (minPositions[i] > 0 && minPositions[i] < n)
{
cv::line(histImg,cv::Point(0,minPositions[i]),
cv::Point(n,minPositions[i]),
cv::Scalar::all(128));
//i++;
}
// ПОРОГ!!!
/*thresh = (int)(1.15 * mean(inp_arr,n));
printf("\nthresh=%d;\n",thresh);*/
// Нарисовать линию предела 1.15 на гистограмме
cv::line(histImg,cv::Point((int)(thresh*n/maxValue),0),cv::Point((int)(thresh*n/maxValue),image.rows),cv::Scalar::all(128));
histogram = inp_arr;
return histImg;
}
void imrotate(cv::Mat image,cv::Mat &out_image,double angle)
{
// Вокруг какой точки вращать
Point center = Point( image.cols/2, image.rows/2 );
double scale = 1; // уменьшения/увеличение
// Матрица поворота
cv::Mat rot_mat = getRotationMatrix2D( center, angle, scale );
/// Повернуть
warpAffine( image, out_image, rot_mat, image.size() );
}
void drawBorders(cv::Mat &image)
{ // Отрисовывает веритикальные границы области поиска, если они были заданы.
if (UP_BORDER > 0 || DOWN_BORDER < image.rows)
{
line(image,Point(0,UP_BORDER),Point(image.cols-1,UP_BORDER),Scalar(255,0,255),2);
line(image,Point(0,DOWN_BORDER),Point(image.cols-1,DOWN_BORDER),Scalar(255,0,255),2);
}
}
void tmpShow(cv::Mat image)
{
// Отображение во временном окне входящего изображения
cv::namedWindow("tmp");
cv::imshow("tmp",image);
cv::waitKey(0);
cv::destroyWindow("tmp");
}
float calcMatMorphoDensity(cv::Mat img)
{
cv::cvtColor(img,img,CV_RGB2GRAY);
equalizeHist(img,img); // аналог imadjust
cv::morphologyEx(img,img,MORPH_GRADIENT,cv::Mat(5,5,CV_8U));
int sumBrigth = 0;
for (int j = 0; j < img.cols; j++)
for (int i = 0; i < img.rows; i++)
{
sumBrigth = sumBrigth + (int)(img.at<uchar>(i,j));
}
return (float)sumBrigth / (img.rows * img.cols);
}
bool checkRectOverlap(cv::Rect rect1,cv::Rect rect2)
{
if (rect1.x > rect2.x + rect2.width ||
rect1.x + rect1.width < rect2.x ||
rect1.y > rect2.y + rect2.height ||
rect1.y + rect1.height < rect2.y
)
return false;
return true;
}
Region joinRegions(Region region1,Region region2,cv::Mat frame)
{
std::vector<cv::KeyPoint> united_keypts;
united_keypts.insert(united_keypts.end(), region1.keypts.begin(), region1.keypts.end());
united_keypts.insert(united_keypts.end(), region2.keypts.begin(), region2.keypts.end());
Region united_region(united_keypts,frame);
return united_region;
}
Rect widenRect(Rect rect,int pixels)
{// расширить Rect на Pixel пикселов во все стороны
Rect new_rect(rect.x-pixels,rect.y-pixels,rect.width+pixels*2,rect.height+pixels*2);
return new_rect;
}
cv::Mat concatImages(cv::Mat img1,cv::Mat img2)
{ // Соединить два изображения в одно!
if (img1.rows > img2.rows) // выравнять высоту (растянуть меньшее до нужной высоты)
{
cv::resize(img2,img2,cv::Size(img2.cols,img1.rows));
}
else if (img1.rows < img2.rows)
{
cv::resize(img1,img1,cv::Size(img1.cols,img2.rows));
}
cv::Mat new_image(img1.rows,img1.cols+img2.cols,img1.type());
if (img1.channels() != img2.channels())
{
if (img1.channels() == 3)
cv::cvtColor(img1,img1,CV_RGB2GRAY);
if (img2.channels() == 3)
cv::cvtColor(img2,img2,CV_RGB2GRAY);
}
img1.copyTo(new_image.colRange(0,img1.cols));
img2.copyTo(new_image.colRange(img1.cols,img1.cols+img2.cols));
return new_image;
}
int getBinImgHeight(Mat charImage)
{ // вычисляет высоту белой области в ч.б. картинке, "обрезая" снизу и сверху
int row_sum, // сумма яркостей в строке
up_otst = -1,down_otst = -1; // высота черной области сверху и снизу
// вычисление вернего отступа
for (int i = 0; i < charImage.rows; i++)
{
row_sum = 0;
for (int j = 0; j < charImage.cols * charImage.channels(); j++)
{
row_sum += charImage.at<uchar>(i,j);
}
if (row_sum != 0)
{
up_otst = i;
break;
}
}
if (up_otst == -1) // если до конца так и не появилось НЕчерной строчки...
return 0;
// вычисление нижнего отступа
for (int i = 0; i < charImage.rows; i++)
{
row_sum = 0;
for (int j = 0; j < charImage.cols * charImage.channels(); j++)
{
row_sum += charImage.at<uchar>(charImage.rows-i-1,j);
}
if (row_sum != 0)
{
down_otst = charImage.rows - i - 1;
break;
}
}
return down_otst - up_otst + 1;
}
int getBinImgWidth(Mat charImage)
{
int col_sum, // сумма яркостей в столбце
left_otst = -1,right_otst = -1; // высота черной области слева и справа
for (int i = 0; i < charImage.cols * charImage.channels(); i++)
{
col_sum = 0;
for (int j = 0; j < charImage.rows; j++)
{
col_sum += charImage.at<uchar>(j,i);
}
if (col_sum != 0)
{
left_otst = i;
break;
}
}
if (left_otst == -1)
return 0;
for (int i = 0; i < charImage.cols * charImage.channels() ; i++)
{
col_sum = 0;
for (int j = 0; j < charImage.rows; j++)
{
col_sum += charImage.at<uchar>(j,charImage.cols*charImage.channels()-i-1);
}
if (col_sum != 0)
{
right_otst = charImage.cols * charImage.channels() - i - 1;
break;
}
}
return (right_otst - left_otst + 1)/3;
}
void printIntVector(std::vector<int> vect)
{
printf("\n");
for (int i = 0; i < vect.size(); i++)
{
printf("%d ",vect.at(i));
}
printf("\n");
}
void drawLocalMins(Mat &image,std::vector<int> local_mins,cv::Scalar color)
{
// Нарисовать локальные минимумы на изображении номера
for (int i = 0; i < local_mins.size(); i++)
{
cv::line(image,cv::Point(local_mins.at(i),0),
cv::Point(local_mins.at(i),image.cols),
color);
}
}
int* getVertHist(Mat binImage)
{
int* histArr = new int[binImage.cols];
for (int j = 0; j < binImage.cols; j++)
{
histArr[j] = 0;
for (int i = 0; i < binImage.rows; i++)
{
histArr[j] += binImage.at<uchar>(i,j*3) / 255;
}
}
return histArr;
}
void widenFrame(Mat &frame,int pixels)
{
Mat expanded_frame(frame.rows+pixels*2,frame.cols+pixels*2,frame.type());
Mat imageROI = expanded_frame(Rect(pixels,pixels,frame.cols,frame.rows));
frame.copyTo(imageROI);
expanded_frame.copyTo(frame);
}
cv::Mat cutCharWhite(cv::Mat charImage,cv::Mat binImage)
{
if (whiteRatio(binImage)<0.001)
{
return charImage;
}
int line_sum, up_otst = -1,down_otst = -1,left_otst = -1;
//// вычисление вернего отступа
for (int i = 0; i < binImage.rows; i++)
{
line_sum = 0;
for (int j = 0; j < binImage.cols * binImage.channels(); j++)
{
line_sum += binImage.at<uchar>(i,j);
}
if (line_sum != 0)
{
up_otst = i;
break;
}
}
if (up_otst == -1) // если до конца так и не появилось НЕчерной строчки...
return charImage;
//// вычисление нижнего отступа
for (int i = 0; i < binImage.rows; i++)
{
line_sum = 0;
for (int j = 0; j < binImage.cols * binImage.channels(); j++)
{
line_sum += binImage.at<uchar>(binImage.rows-i-1,j);
}
if (line_sum != 0)
{
down_otst = binImage.rows - i - 1;
break;
}
}
for (int i = 0; i < binImage.cols; i++)
{
line_sum = 0;
for (int j = 0; j < binImage.rows; j++)
{
line_sum += binImage.at<uchar>(j,i);
}
if (line_sum != 0)
{
left_otst = i;
break;
}
}
if (left_otst <= 0)
left_otst = 0;
left_otst = left_otst / 3;
//cv::Mat cut_image=charImage(Rect(0,up_otst,charImage.cols,down_otst - up_otst + 1));
cv::Mat cut_image=charImage(Rect(left_otst,up_otst,charImage.cols-left_otst,down_otst - up_otst + 1));
return cut_image;
//return charImage;
}
// Listener-ы для изменения настроек
void on_trackbar_listener( int, void* )
{
capture.set(CV_CAP_PROP_POS_FRAMES,VIDEO_TRACKBAR_VALUE);
num_frame = VIDEO_TRACKBAR_VALUE;
}
void on_trackbar2_listener( int, void* )
{
CORNERS_THRESH = FASTTHRESH_TRACKBAR_VALUE;
}
void on_trackbar3_listener( int, void* )
{
RADIUS_X = RADIUS_X_TRACKBAR_VALUE;
RADIUS_Y = RADIUS_Y_TRACKBAR_VALUE;
if (COMPR_RATE_TRACKBAR_VALUE == 0)
{
COMPR_RATE = 0.5;
}
else
{
COMPR_RATE = (float)COMPR_RATE_TRACKBAR_VALUE;
}
}
void onMouse( int event, int x, int y, int /*flags*/, void* /*param*/ )
{
if( event == CV_EVENT_LBUTTONDOWN )
{
if (borders_setting == 1)
{
if (y > DOWN_BORDER)
{
UP_BORDER = DOWN_BORDER;
DOWN_BORDER = y;
}
else
{UP_BORDER = y;}
borders_setting = 2;
printf("UP_BORDER SET: %d\n",y);
}
else if (borders_setting == 2)
{
if (y < UP_BORDER)
{
DOWN_BORDER = UP_BORDER;
UP_BORDER = y;
}
else
{ DOWN_BORDER = y; }
borders_setting = 0;
printf("DOWN_BORDER SET: %d\n",y);
}
}
}
// Простейшие функции.
char* getVideoTrack()
{
int i;
printf("SELECT VIDEO TRACK:\n");
printf("PRESS '0' FOR _3.avi\n");
printf("PRESS '1' FOR _4.avi\n");
printf("PRESS '2' FOR 4 mins.avi\n");
printf("PRESS '3' FOR all.avi\n");
printf("PRESS '4' FOR cisterns.avi\n");
printf("PRESS '5' FOR cisterns2.avi\n");
printf("PRESS '6' FOR cisterns3.avi\n");
printf("PRESS '7' FOR hoppers.avi\n");
printf("PRESS '8' FOR wagons.avi\n");
printf("PRESS '9' FOR wagons2.avi\n");
printf("PRESS '10' FOR 0.avi\n");
printf("PRESS '11' FOR 1.avi\n");
printf("PRESS '12' FOR 3.avi\n");
printf("PRESS '13' FOR 4.avi\n");
printf("PRESS '14' FOR 5.avi\n");
printf("MY CHOICE: ");
scanf("%d",&i);
switch (i)
{
case 0:
NUMBER_HEIGHT = 23;
return "C:\\Main\\WORK\\video\\_3.avi";
break;
case 1:
NUMBER_HEIGHT = 20;
return "C:\\Main\\WORK\\video\\_4.avi";
break;
case 2:
NUMBER_HEIGHT = 25; // ???
return "C:\\Main\\WORK\\video\\4 mins.avi";
break;
case 3:
NUMBER_HEIGHT = 30;
return "C:\\Main\\WORK\\video\\all.avi";
break;
case 4:
NUMBER_HEIGHT = 38;
return "C:\\Main\\WORK\\video\\cisterns.avi";
break;
case 5:
NUMBER_HEIGHT = 34;
return "C:\\Main\\WORK\\video\\cisterns2.avi";
break;
case 6:
NUMBER_HEIGHT = 30;
CORNERS_THRESH = 25;
FASTTHRESH_TRACKBAR_VALUE = CORNERS_THRESH;
return "C:\\Main\\WORK\\video\\cisterns3.avi";
break;
case 7:
NUMBER_HEIGHT = 43;
return "C:\\Main\\WORK\\video\\hoppers.avi";
break;
case 8:
NUMBER_HEIGHT = 41;
return "C:\\Main\\WORK\\video\\wagons.avi";
break;
case 9:
NUMBER_HEIGHT = 30;
return "C:\\Main\\WORK\\video\\wagons2.avi";
break;
case 10:
NUMBER_HEIGHT = 30;
return "C:\\Main\\WORK\\video\\0.avi";
break;
case 11:
NUMBER_HEIGHT = 25;
return "C:\\Main\\WORK\\video\\1.avi";
break;
case 12:
NUMBER_HEIGHT = 30;
return "C:\\Main\\WORK\\video\\3.avi";
break;
case 13:
NUMBER_HEIGHT = 30;
return "C:\\Main\\WORK\\video\\4.avi";
break;
case 14:
NUMBER_HEIGHT = 30;
return "C:\\Main\\WORK\\video\\5.avi";
break;
default:
return "C:\\Main\\WORK\\video\\cisterns.avi";
}
}
cv::Mat binarize(cv::Mat image)
{
cv::Mat grey;
if (image.channels() == 3)
{
cv::cvtColor(image,grey,CV_RGB2GRAY);
}
else image.copyTo(grey);
cv::Mat binary;
cv::threshold(grey,binary,128,255,CV_THRESH_OTSU); // or CV_THRESH_BINARY
if (image.channels() == 3)
{
for (int i = 0; i < image.rows; i++)
for (int j = 0; j < image.cols; j++)
{
image.at<Vec3b>(i,j)[0] = binary.at<uchar>(i,j);
image.at<Vec3b>(i,j)[1] = binary.at<uchar>(i,j);
image.at<Vec3b>(i,j)[2] = binary.at<uchar>(i,j);
}
return image;
}
return binary;
}
float whiteRatio(cv::Mat image)
{
if (image.cols*image.rows == 0) return 0;
int sum = 0;
image = binarize(image);
for (int i = 0; i < image.cols*image.channels(); i++)
for (int j = 0; j < image.rows; j++)
{
sum += image.at<uchar>(j,i);
}
return sum / (image.cols * image.channels() * image.rows);
}
int* medFiltHist(int* arr,int n)
{
// Усредняет значения (сглаживает), проходясь окном шириной = 5.
for (int i = 2; i < n - 2; i++)
{
arr[i] = ( arr[i-2] + arr[i-1] + arr[i] + arr[i+1] + arr[i+2] ) / 5;
}
return arr;
}
int* calcHist(cv::Mat image,int flag) // flag = 0 - hor, = 1 - vert
{
// Compute histogram
int* histArr;
//printf("rows=%d; cols=%d;\n",image.rows,image.cols);
if (flag == 0) // горизонтальная гистограмма
{
histArr = new int[image.rows];
for (int j = 0; j < image.rows; j++)
{
histArr[j] = 0;
for (int i = 0; i < image.cols; i++)
{
histArr[j] += image.at<uchar>(j,i);
}
//printf("histArr[%d]=%d;\n",j,histArr[j]);
}
}
else if (flag == 1)
{
histArr = new int[image.cols];
for (int j = 0; j < image.cols; j++)
{
histArr[j] = 0;
for (int i = 0; i < image.rows; i++)
{
histArr[j] += image.at<uchar>(i,j);
}
}
}
return histArr;
}
int* min(int* arr,int n)
{ // Возвращает минимальное значение массива и его порядковый номер в массиве.
int* p = new int[2];
int minVal = 500000;
int minPos = -1;
for (int i = 0; i < n; i++)
{
if (arr[i] <= minVal)
{
minVal = arr[i];
minPos = i;
}
}
p[0] = minVal;
p[1] = minPos;
return p;
}
int* max(int* arr,int n)
{ // Возвращает максимальное значение массива и его порядковый номер в массиве.
int* p = new int[2];
int maxVal = -500000;
int maxPos = -1;
for (int i = 0; i < n; i++)
{
if (arr[i] > maxVal)
{
maxVal = arr[i];
maxPos = i;
}
}
p[0] = maxVal;
p[1] = maxPos;
return p;
}
void printArray(int* arr,int n)
{
for (int i = 0; i < n; i++)
{
printf("arr[%d]=%d;\n",i,arr[i]);
}
}
void prewittFilter(const cv::Mat &inp_image,cv::Mat &out_image,int type)
{
// Construct kernel (initialize all entries with 0)
cv::Mat kernel(3,3,CV_32F,cv::Scalar(0));
// assign kernel values
switch (type){
case 0:
kernel.at<float>(0,0) = 1.0; //horisontal Prewitt filter http://en.wikipedia.org/wiki/Prewitt_operator
kernel.at<float>(0,1) = 1.0;
kernel.at<float>(0,2) = 1.0;
kernel.at<float>(2,0) = -1.0;
kernel.at<float>(2,1) = -1.0;
kernel.at<float>(2,2) = -1.0;
break;
case 1:
kernel.at<float>(0,0) = 1.0; // vertical Prewitt filter
kernel.at<float>(1,0) = 1.0;
kernel.at<float>(2,0) = 1.0;
kernel.at<float>(0,2) = -1.0;
kernel.at<float>(1,2) = -1.0;
kernel.at<float>(2,2) = -1.0;
break;
}
//sharpening image
/*kernel.at<float>(1,1) = 5.0;
kernel.at<float>(1,0) = -1.0;
kernel.at<float>(1,2) = -1.0;
kernel.at<float>(2,1) = -1.0;
kernel.at<float>(0,1) = -1.0;*/
cv::filter2D(inp_image,out_image,inp_image.depth(),kernel);
}
cv::Mat makeBlack(cv::Mat image)
{
for (int i = 0; i < image.rows; i++)
{
for (int j = 0; j < image.cols*image.channels(); j++)
{
image.at<uchar>(i,j) = 0;
}
}
return image;
}
int mean(int* arr,int n)
{
int sum = 0;
for (int i = 0; i < n; i++)
{
sum+=arr[i];
}
return (int)(sum/n);
}
int* cleanHist(int* inp_arr,int n, int thresh)
{
for (int i = 0; i < n; i++)
{
if (inp_arr[i] <= thresh)
inp_arr[i] = 0;
}
return inp_arr;
}
bool belongs(int value, int* arr,int n)
{
for (int i = 0; i < n; i++)
{
if (arr[i] == value)
return true;
}
return false;
}
int* mysort(int* arr,int n)
{
int tmp;
for (int i = 0; i < n; i++)
{
int minval = arr[i];
int minpos = i;
for (int j = i; j < n; j++)
{
if (arr[j] < minval)
{
minval = arr[j];
minpos = j;
}
}
tmp = arr[i];
arr[i] = minval;
arr[minpos] = tmp;
}
return arr;
}
bool belongsToTriangle(cv::Point2f point,std::vector<cv::Point2f> vertices)
{ //принадлежность точки треугольнику
if (vertices.size() == 3)
{
double t1 = (vertices.at(0).x - point.x)*(vertices.at(1).y - vertices.at(0).y) - (vertices.at(1).x - vertices.at(0).x)*(vertices.at(0).y - point.y);
double t2 = (vertices.at(1).x - point.x)*(vertices.at(2).y - vertices.at(1).y) - (vertices.at(2).x - vertices.at(1).x)*(vertices.at(1).y - point.y);
double t3 = (vertices.at(2).x - point.x)*(vertices.at(0).y - vertices.at(2).y) - (vertices.at(0).x - vertices.at(2).x)*(vertices.at(2).y - point.y);
if ((t1 > 0 && t2 > 0 && t3 > 0)||(t1 < 0 && t2 < 0 && t3 < 0))
return true;
}
return false;
}
bool belongsToArea(cv::Point2f point,std::vector<cv::Point2f> vertices)
{// Проверить, принадлежит ли точка области с вершинами (пока только треугольник или четырехугольник)
if (vertices.size() >= 3 && vertices.size() <= 4)
{
if (vertices.size() == 3)
{
return belongsToTriangle(point,vertices);
}
else
{
// Разобьем четырехугольник на два треугольника
std::vector<cv::Point2f> vertices1,vertices2;
vertices1.push_back(vertices.at(0));
vertices1.push_back(vertices.at(1));
vertices1.push_back(vertices.at(2));
vertices2.push_back(vertices.at(0));
vertices2.push_back(vertices.at(2));
vertices2.push_back(vertices.at(3));
return (belongsToTriangle(point,vertices1) || belongsToTriangle(point,vertices2));
}
}
return false;
}
cv::Mat invertImage(cv::Mat image)
{
cv::Mat invImage;
image.copyTo(invImage);
for(int i = 0; i < image.rows; i++)
for(int j = 0; j < image.cols*image.channels(); j++)
invImage.at<uchar>(i,j) = 255-image.at<uchar>(i,j);
return invImage;
}
// WRITE TO FILE
/*char filename[30];
std::sprintf(filename,"C:\\Main\\WORK\\!test\\%d.bmp",num_frame);
cv::imwrite(filename,image1);*/
|
48b0ee7fe3ebe8ea001f8ee29db02d304eff89e0
|
811ff0c8389ad4aa5496872227324e6185c5bba1
|
/UIs/Studio/DesignScriptStudio.Renderer/Camera.h
|
c4de2225d27d7e3880e857e91e3cbeb352838ddc
|
[
"Apache-2.0"
] |
permissive
|
DynamoDS/designscript-archive
|
2c2bb2182f6214a262a56d685168dc8a345616e0
|
2cfafd1299af0ffddacf77c41f51150556e88b80
|
refs/heads/master
| 2020-04-10T20:12:10.737867
| 2014-02-17T12:24:45
| 2014-02-17T12:24:45
| 11,632,510
| 4
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 802
|
h
|
Camera.h
|
#pragma once
#include "Primitives.h"
namespace DesignScriptStudio { namespace Renderer {
class Camera
{
public:
Camera(int pixelWidth, int pixelHeight);
~Camera(void);
void SetOrthographicMode(bool orthographic);
void SetProjectionMatrix(void) const;
void SetModelViewMatrices(void) const;
void FitToBoundingBox(const float* pCorners);
float NearClipPlane(void) const;
float FarClipPlane(void) const;
Vector EyePosition(void) const;
Vector ViewDirection(void) const;
private:
bool mOrthographicMode;
float mContentDiameter;
float mFieldOfView, mViewAspect;
float mNearClip, mFarClip;
Vector mEye, mTarget, mUpVector;
};
} }
|
76ce7eb15788e470eba44a8a39d9fb57ea016ef5
|
835aa348b329b740bbdc2e26cb07d122248890ce
|
/src/node.cpp
|
9b22f175d34db67a50de451cd30ef33d74acfc99
|
[
"NCSA"
] |
permissive
|
jayp/Rappel
|
a81ec6d69fa5242420d6cac253f8e55efe0948c2
|
3ad355fbd3ed82b42e2b108e4eadfc22dd47e425
|
refs/heads/master
| 2021-01-19T22:02:09.916132
| 2011-10-04T20:24:33
| 2011-10-04T20:24:33
| 2,514,562
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,242
|
cpp
|
node.cpp
|
#include "rappel_common.h"
#include "timer.h"
#include "transport.h"
#include "node.h"
#include "vivaldi.h"
#include "rappel.h"
#include "debug.h"
// global variables
static sqlite3_stmt* g_stats_insert_coordinates_stmt;
// constructor
Node::Node(const node_id_t& node_id) {
_timer = Timer::get_instance();
assert(_timer != NULL);
_transport = Transport::get_instance();
assert(_transport != NULL);
_rng = RNG::get_instance();
assert(_rng != NULL);
// initialize class variables
_node_id = node_id;
_rappel_online_since = 0;
_is_rappel_online = false;
_bootstrap_phase_complete = false;
// initialize coordinates (to randomness)
_nc.init();
_vivaldi = NULL;
_rappel = NULL;
}
Node::~Node() {
_vivaldi->take_offline(); // vivaldi taken offline only when node destroyed
delete _vivaldi;
_vivaldi = NULL;
if (_rappel) {
if ( _is_rappel_online) {
rappel_take_offline(true);
}
delete _rappel;
_rappel = NULL;
}
}
/**
* Redirect event to VIVALDI or RAPPEL
*/
int Node::event_callback(Event& event) {
assert(event.layer == LYR_APPLICATION);
if (event.flag >= EVT_VIVALDI_START && event.flag <= EVT_VIVALDI_END) {
assert(_vivaldi != NULL);
return _vivaldi->event_callback(event);
} else if (event.flag >= EVT_RAPPEL_START && event.flag <= EVT_RAPPEL_END) {
// don't deliver any events if rappel is not online
if (!_is_rappel_online) {
std::cerr << "warn: @time=" << _timer->get_time_str() << " node="
<< _node_id.str() << " missed event=" << event_flag_str(event.flag)
<< " [node offline]" << std::endl;
delete(event.data);
assert(false);
return 0;
}
assert(_rappel != NULL);
return _rappel->event_callback(event);
}
assert(false);
return 0;
}
/**
* Redirect msg to VIVALDI or RAPPEL
*/
int Node::msg_callback(Message& msg) {
assert(msg.layer == LYR_APPLICATION);
if (msg.flag >= MSG_VIVALDI_START && msg.flag <= MSG_VIVALDI_END) {
assert(_vivaldi != NULL);
return _vivaldi->msg_callback(msg);
} else if (msg.flag >= MSG_RAPPEL_START && msg.flag <= MSG_RAPPEL_END) {
// don't deliver any messages if rappel is not online
if (!_is_rappel_online) {
delete(msg.data);
return 0;
}
assert(_rappel != NULL);
return _rappel->msg_callback(msg);
}
delete(msg.data);
std::cerr << "warn: unknown LYR_APPLICATION message" << std::endl;
return 0;
}
void Node::debug(unsigned int seq_num) {
if (_rappel != NULL) {
((Rappel*) _rappel)->debug(seq_num);
} else if (_vivaldi != NULL) { // only debug vivaldi, if it is not a rappel node
((Vivaldi*) _vivaldi)->debug(seq_num);
}
}
std::vector<std::pair<node_id_t, Clock> > Node::get_all_landmarks() const {
Clock curr_time = _timer->get_time();
std::vector<std::pair<node_id_t, Clock> > all_landmarks;
for (std::map<node_id_t, Clock>::const_iterator it = _landmarks.begin();
it != _landmarks.end(); it++) {
node_id_t landmark = it->first;
Clock last_heard_at = it->second;
all_landmarks.push_back(make_pair(landmark, curr_time - last_heard_at));
}
return all_landmarks;
}
std::vector<std::pair<node_id_t, Clock> >
Node::get_sample_landmarks(unsigned int num_landmarks) const {
std::vector<std::pair<node_id_t, Clock> > all_landmarks = get_all_landmarks();
unsigned total_landmarks = all_landmarks.size();
unsigned min_landmarks = min(total_landmarks, num_landmarks);
random_shuffle(all_landmarks.begin(), all_landmarks.end());
std::vector<std::pair<node_id_t, Clock> > sample_landmarks(
all_landmarks.begin(), all_landmarks.begin() + min_landmarks);
// remove any old landmark
for (std::vector<std::pair<node_id_t, Clock> >::iterator
it = sample_landmarks.begin(); it != sample_landmarks.end(); /* it++ */) {
node_id_t landmark = it->first;
Clock last_heard_ago = it->second;
// TODO: variablize
if (last_heard_ago > 10 * MINUTES) {
sample_landmarks.erase(it);
} else {
it++;
}
}
return sample_landmarks;
}
Coordinate Node::get_landmark_coordinate(const node_id_t& landmark) const {
std::map<node_id_t, std::pair<Coordinate, std::vector<double> > >::const_iterator
it = _landmark_samples.find(landmark);
assert(it != _landmark_samples.end());
Coordinate coord = it->second.first;
return coord;
}
double Node::get_filtered_landmark_measurement(const node_id_t& landmark,
bool just_probing) const {
std::map<node_id_t, std::pair<Coordinate, std::vector<double> > >::const_iterator
it = _landmark_samples.find(landmark);
assert(it != _landmark_samples.end());
vector<double> samples = it->second.second;
if (samples.size() == 0) {
if (just_probing) {
return -1;
}
assert(false);
}
sort(samples.begin(), samples.end());
double min_sample = samples[0];
return min_sample;
}
////////// mutators /////////////////////////////////////
node_id_t Node::get_random_landmark() {
Clock curr_time = _timer->get_time();
for (std::map<node_id_t, Clock>::iterator it = _landmarks.begin();
it != _landmarks.end(); /* it++ */) {
node_id_t landmark = it->first;
Clock last_heard_ago = curr_time - it->second;
std::map<node_id_t, Clock>::iterator it_now = it;
it++;
// forget inactive landmarks -- except the sync node
// TODO: variablize
if (landmark != globops.first_landmark && last_heard_ago > 20 * MINUTES) {
_landmarks.erase(it_now); // it_now is not invalid
assert(_landmarks.find(landmark) == _landmarks.end());
}
}
if (_landmarks.size() == 0) {
return NO_SUCH_NODE;
}
unsigned int r = _rng->rand_uint(0, _landmarks.size() - 1);
unsigned int counter = 0;
for (std::map<node_id_t, Clock>::const_iterator it = _landmarks.begin();
it != _landmarks.end(); it++) {
if (counter++ == r) {
return it->first;
}
}
// shouldn't happen
std::cerr << "landmarks size=" << _landmarks.size() << "; r=" << r << std::endl;
assert(false);
return NO_SUCH_NODE;
}
void Node::add_landmark(const node_id_t& node) {
std::vector<std::pair<node_id_t, Clock> > landmark;
landmark.push_back(make_pair(node, 0 * SECONDS));
add_landmarks(landmark);
}
void Node::add_landmarks(const std::vector<std::pair<node_id_t, Clock> >& nodes) {
Clock curr_time = _timer->get_time();
for (std::vector<std::pair<node_id_t, Clock> >::const_iterator it = nodes.begin();
it != nodes.end(); it++) {
node_id_t landmark = it->first;
Clock last_heard_ago = it->second;
// do not add the node itself to the landmark list
if (landmark == _node_id) {
continue;
}
std::map<node_id_t, Clock>::const_iterator it = _landmarks.find(landmark);
if (it != _landmarks.end()) {
_landmarks[landmark] = max(_landmarks[landmark], curr_time - last_heard_ago);
} else {
//std::cout << "adding new landmark: " << landmark.str() << std::endl;
_landmarks[landmark] = curr_time - last_heard_ago;
}
std::map<node_id_t, std::pair<Coordinate, std::vector<double> > >::const_iterator
it2 = _landmark_samples.find(landmark);
if (it2 == _landmark_samples.end()) {
_landmark_samples[landmark] = make_pair(Coordinate(), vector<double>());
}
}
}
void Node::add_landmark_measurement(const node_id_t& landmark,
double ow_latency_in_msecs, const Coordinate& coord) {
std::map<node_id_t, std::pair<Coordinate, std::vector<double> > >::const_iterator
it = _landmark_samples.find(landmark);
assert(it != _landmark_samples.end());
vector<double> samples = it->second.second;
if (samples.size() == globops.vivaldi_num_samples) {
samples.erase(samples.begin());
}
// save the current sample
samples.push_back(ow_latency_in_msecs);
// update the info in landmark_samples
_landmark_samples[landmark] = make_pair(coord, samples);
}
/**
* update the nc of the node depending on rtt and sender coordinate
*/
void Node::update_local_nc(const Coordinate& sender_coord,
double ow_latency_in_msecs) {
assert(!_is_rappel_online);
#ifdef DEBUG
printf(" old coordinate (app) => %s\n", _nc.to_string().c_str());
printf(" old coordinate (sys) => %s\n", _nc.to_string(false).c_str());
printf(" sender coordinate (app) => %s\n", sender_coord.to_string().c_str());
printf(" sender latency => %0.3f\n", ow_latency_in_msecs);
#endif // DEBUG
bool coord_changed = _nc.update(sender_coord, ow_latency_in_msecs, false);
#ifdef DEBUG
if (coord_changed) {
printf(" new coordinate (synced) => %s\n", _nc.to_string().c_str());
} else {
printf(" no change in coordinate\n");
}
#endif // DEBUG
if (coord_changed) {
if (_rappel != NULL) { // if a rappel node
flush_coords_to_db();
}
}
}
void Node::flush_coords_to_db() {
if (g_stats_insert_coordinates_stmt == NULL) {
string sql_insert_coordinates(
"INSERT INTO coordinates(node_id, sync_time, "
"version, app_coords_1, app_coords_2, app_coords_3, app_coords_4, app_coords_5"
#if COMPILE_FOR == SIMULATOR
") VALUES(?, ?, ?, ?, ?, ?, ?, ?)");
#elif COMPILE_FOR == NETWORK
", sync_time) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)");
#endif // COMPILE_FOR
assert(sqlite3_prepare(stats_db, sql_insert_coordinates.c_str(),
-1, &g_stats_insert_coordinates_stmt, NULL) == SQLITE_OK);
}
Clock curr_time = _timer->get_time();
// get app coords
std::vector<double> app_coords = _nc.get_app_coords();
#if COMPILE_FOR == SIMULATOR
assert(sqlite3_bind_int(g_stats_insert_coordinates_stmt, 1,
_node_id.get_address()) == SQLITE_OK);
#elif COMPILE_FOR == NETWORK
assert(sqlite3_bind_text(g_stats_insert_coordinates_stmt, 1,
_node_id.str().c_str(), -1, SQLITE_TRANSIENT) == SQLITE_OK);
#endif
assert(sqlite3_bind_int64(g_stats_insert_coordinates_stmt, 2,
_timer->get_sync_time(curr_time)) == SQLITE_OK);
assert(sqlite3_bind_int(g_stats_insert_coordinates_stmt, 3,
_nc.get_version()) == SQLITE_OK);
assert(sqlite3_bind_double(g_stats_insert_coordinates_stmt, 4,
app_coords[0]) == SQLITE_OK);
assert(sqlite3_bind_double(g_stats_insert_coordinates_stmt, 5,
app_coords[1]) == SQLITE_OK);
assert(sqlite3_bind_double(g_stats_insert_coordinates_stmt, 6,
app_coords[2]) == SQLITE_OK);
assert(sqlite3_bind_double(g_stats_insert_coordinates_stmt, 7,
app_coords[3]) == SQLITE_OK);
assert(sqlite3_bind_double(g_stats_insert_coordinates_stmt, 8,
app_coords[4]) == SQLITE_OK);
#if COMPILE_FOR == NETWORK
assert(sqlite3_bind_int64(g_stats_insert_coordinates_stmt, 2,
curr_time) == SQLITE_OK);
#endif // COMPILE_FOR == NETWORK
assert(sqlite3_step(g_stats_insert_coordinates_stmt) == SQLITE_DONE);
sqlite3_reset(g_stats_insert_coordinates_stmt);
}
void Node::signal_vivaldi_bootstrap_complete() { // from vivaldi
assert(_rappel != NULL);
assert(!_bootstrap_phase_complete);
// indicate that we are bootstrapped
_bootstrap_phase_complete = true;
// force a sync -- at bootstrap complete time
// NOTE: this is req'd for nodes who never move out of the origin
// as their movement resides within the origin +/- stability range
_nc.sync();
flush_coords_to_db();
#if COMPILE_FOR == NETWORK
// send message to ctrl server
Message msg;
CommandMessageData* data = new CommandMessageData;
data->self_name = globops.self_name;
// swap src and dst as we send this message out directly via udp_send()
msg.src = _node_id;
msg.dst = node_id_t(_node_id.get_address(), globops.ctrl_port);
msg.layer = LYR_CONTROL;
msg.flag = MSG_CMD_SIGNAL_BOOTSTRAPPED;
msg.data = data;
_transport->send(msg);
#endif // COMPILE_FOR == NETWORK
}
////////////// Vivaldi specific
void Node::vivaldi_init() {
assert(_vivaldi == NULL);
assert(_rappel == NULL);
// initialize vivaldi
_vivaldi = new Vivaldi(this);
assert(_vivaldi != NULL);
_vivaldi->bring_online();
}
////////////// RAPPEL specific
bool Node::rappel_is_publisher() const {
Rappel* rappel = dynamic_cast<Rappel*>(_rappel);
return (_rappel != NULL && rappel->is_publisher());
}
bool Node::rappel_is_subscribed_to(const feed_id_t& feed_id) const {
Rappel* rappel = dynamic_cast<Rappel*>(_rappel);
return (_rappel != NULL && rappel->is_subscribed_to(feed_id));
}
void Node::rappel_init(bool is_publisher) {
assert(_vivaldi == NULL);
assert(_rappel == NULL);
assert(_is_rappel_online == false);
// initialize vivaldi
_vivaldi = new Vivaldi(this);
assert(_vivaldi != NULL);
_rappel = new Rappel(this, is_publisher);
assert(_rappel != NULL);
// a rappel node also runs vivaldi. once vivaldi bootstraps the node's
// NC, a rappel node may be brought online
_vivaldi->bring_online(); // NOTE: must be called after new Rappel
}
void Node::rappel_bring_online() {
assert(_is_rappel_online == false);
assert(_rappel != NULL);
assert(_bootstrap_phase_complete);
// in the beginning
_is_rappel_online = true;
_rappel_online_since = _timer->get_time();
((Vivaldi*) _vivaldi)->deactivate();
_rappel->bring_online();
}
void Node::rappel_take_offline(bool final) {
assert(_rappel != NULL);
assert(_is_rappel_online == true);
_rappel->take_offline();
_is_rappel_online = false;
if (!final) {
((Vivaldi*) _vivaldi)->reactivate();
}
}
void Node::rappel_add_feed(const feed_id_t& feed_id) {
assert(_rappel != NULL);
Rappel* rappel = dynamic_cast<Rappel*>(_rappel);
assert(rappel != NULL);
rappel->add_feed(feed_id);
}
void Node::rappel_remove_feed(const feed_id_t& feed_id) {
assert(_rappel != NULL);
Rappel* rappel = dynamic_cast<Rappel*>(_rappel);
assert(rappel != NULL);
rappel->add_feed(feed_id);
}
void Node::rappel_publish_update(size_t num_bytes) {
assert(_rappel != NULL);
Rappel* rappel = dynamic_cast<Rappel*>(_rappel);
assert(rappel != NULL);
assert(rappel->is_publisher());
rappel->publish_update(num_bytes);
}
#if COMPILE_FOR == NETWORK
void Node::rappel_add_feed_rtt_sample(const feed_id_t& feed_id, const Clock& rtt) {
Rappel* rappel = dynamic_cast<Rappel*>(_rappel);
assert(_rappel != NULL);
return rappel->add_feed_rtt_sample(feed_id, rtt);
}
#endif // COMPILE_FOR == NETWORK
|
a11e16226a61ae37eaf188b925fa137c4f01871c
|
4db67c8c69dac02bbccb41a370a58ad21e17aabd
|
/src/commands.h
|
1649f387567e0e28c5c23f94ad2b0c5358ef11a9
|
[
"MIT"
] |
permissive
|
charlesfleche/lpd8editor
|
3fc66476364d81811614595f988aa52d80d5a7aa
|
ae9072e58d23d5926ca8d0228400eead9248a494
|
refs/heads/master
| 2022-05-03T00:33:11.631662
| 2022-04-09T21:27:26
| 2022-04-09T21:27:26
| 90,320,665
| 41
| 6
|
MIT
| 2022-04-09T21:27:27
| 2017-05-05T00:14:26
|
C++
|
UTF-8
|
C++
| false
| false
| 1,853
|
h
|
commands.h
|
#ifndef COMMANDS_H
#define COMMANDS_H
#include <QUndoCommand>
#include <QVariant>
class ProgramsModel;
class QAbstractItemModel;
class QItemSelectionModel;
class QModelIndex;
class QUndoStack;
QUndoStack* undoStack();
int selectedProgramId(QItemSelectionModel* model);
class CreateProgramCommand : public QUndoCommand {
public:
CreateProgramCommand(ProgramsModel* model, const QString&, const QByteArray&, QUndoCommand* parent = nullptr);
void undo() override;
void redo() override;
private:
ProgramsModel *m_model;
const QString m_name;
const QByteArray m_sysex;
int m_program_id;
};
class DeleteProgramCommand : public QUndoCommand {
public:
DeleteProgramCommand(ProgramsModel* model, int programId, QUndoCommand* parent = nullptr);
void undo() override;
void redo() override;
private:
ProgramsModel *m_model;
int m_program_id;
QString m_name;
QByteArray m_sysex;
};
class UpdateParameterCommand : public QUndoCommand {
public:
UpdateParameterCommand(
QAbstractItemModel* model,
int row,
int column,
const QVariant& value,
int role,
QUndoCommand *parent = nullptr
);
void undo() override;
void redo() override;
private:
void setDataAndKeepPrevious();
QAbstractItemModel* m_model;
const int m_row;
const int m_column;
QVariant m_value;
const int m_role;
};
class UpdateProgramFromSysexCommand : public QUndoCommand {
public:
UpdateProgramFromSysexCommand(
ProgramsModel* model,
int programId,
const QByteArray& sysex,
QUndoCommand *parent = nullptr);
void undo() override;
void redo() override;
private:
bool setSysexAndKeepPrevious();
ProgramsModel *m_model;
const int m_program_id;
QByteArray m_sysex;
};
#endif // COMMANDS_H
|
c459ced7c8d7b058244e80ba62aa7791e8f9ffb4
|
777a75e6ed0934c193aece9de4421f8d8db01aac
|
/src/Providers/UNIXProviders/DatabaseResourceStatistics/UNIX_DatabaseResourceStatistics_STUB.hxx
|
b45a5b058ac34cb7a1088519026430fc1aa9ae57
|
[
"MIT"
] |
permissive
|
brunolauze/openpegasus-providers-old
|
20fc13958016e35dc4d87f93d1999db0eae9010a
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
refs/heads/master
| 2021-01-01T20:05:44.559362
| 2014-04-30T17:50:06
| 2014-04-30T17:50:06
| 19,132,738
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 147
|
hxx
|
UNIX_DatabaseResourceStatistics_STUB.hxx
|
#ifdef PEGASUS_OS_STUB
#ifndef __UNIX_DATABASERESOURCESTATISTICS_PRIVATE_H
#define __UNIX_DATABASERESOURCESTATISTICS_PRIVATE_H
#endif
#endif
|
c4969eafd01c8b5bffd5fa3e27e0b4643ba311a6
|
4861067392a62a94eb6754e002c4348cfc378e43
|
/src/network/ssl/qdtls.h
|
dd24aa219ade5ed864fa2113a88f9f2b06d20636
|
[] |
no_license
|
qt/qtbase
|
10c7d55cfa1e34e4d23c00e96c6199a1657095e1
|
0e5f60a6cae61c5086f25c039a953a5ade5fa471
|
refs/heads/dev
| 2023-09-01T20:11:09.742148
| 2023-08-31T15:56:57
| 2023-09-01T16:06:27
| 9,880,335
| 2,175
| 1,249
| null | 2023-07-17T10:11:10
| 2013-05-06T06:01:22
|
C++
|
UTF-8
|
C++
| false
| false
| 4,092
|
h
|
qdtls.h
|
// Copyright (C) 2018 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
#ifndef QDTLS_H
#define QDTLS_H
#include <QtNetwork/qtnetworkglobal.h>
#include <QtNetwork/qsslsocket.h>
#include <QtNetwork/qssl.h>
#include <QtCore/qcryptographichash.h>
#include <QtCore/qobject.h>
#include <QtCore/qcontainerfwd.h>
Q_MOC_INCLUDE(<QtNetwork/QSslPreSharedKeyAuthenticator>)
#ifndef Q_QDOC
QT_REQUIRE_CONFIG(dtls);
#endif
QT_BEGIN_NAMESPACE
enum class QDtlsError : unsigned char
{
NoError,
InvalidInputParameters,
InvalidOperation,
UnderlyingSocketError,
RemoteClosedConnectionError,
PeerVerificationError,
TlsInitializationError,
TlsFatalError,
TlsNonFatalError
};
class QHostAddress;
class QUdpSocket;
class QByteArray;
class QString;
class QDtlsClientVerifierPrivate;
class Q_NETWORK_EXPORT QDtlsClientVerifier : public QObject
{
Q_OBJECT
public:
explicit QDtlsClientVerifier(QObject *parent = nullptr);
~QDtlsClientVerifier();
struct Q_NETWORK_EXPORT GeneratorParameters
{
GeneratorParameters();
GeneratorParameters(QCryptographicHash::Algorithm a, const QByteArray &s);
QCryptographicHash::Algorithm hash = QCryptographicHash::Sha1;
QByteArray secret;
};
bool setCookieGeneratorParameters(const GeneratorParameters ¶ms);
GeneratorParameters cookieGeneratorParameters() const;
bool verifyClient(QUdpSocket *socket, const QByteArray &dgram,
const QHostAddress &address, quint16 port);
QByteArray verifiedHello() const;
QDtlsError dtlsError() const;
QString dtlsErrorString() const;
private:
Q_DECLARE_PRIVATE(QDtlsClientVerifier)
Q_DISABLE_COPY(QDtlsClientVerifier)
};
class QSslPreSharedKeyAuthenticator;
class QSslConfiguration;
class QSslCipher;
class QSslError;
class QDtlsPrivate;
class Q_NETWORK_EXPORT QDtls : public QObject
{
Q_OBJECT
public:
enum HandshakeState
{
HandshakeNotStarted,
HandshakeInProgress,
PeerVerificationFailed,
HandshakeComplete
};
explicit QDtls(QSslSocket::SslMode mode, QObject *parent = nullptr);
~QDtls();
bool setPeer(const QHostAddress &address, quint16 port,
const QString &verificationName = {});
bool setPeerVerificationName(const QString &name);
QHostAddress peerAddress() const;
quint16 peerPort() const;
QString peerVerificationName() const;
QSslSocket::SslMode sslMode() const;
void setMtuHint(quint16 mtuHint);
quint16 mtuHint() const;
using GeneratorParameters = QDtlsClientVerifier::GeneratorParameters;
bool setCookieGeneratorParameters(const GeneratorParameters ¶ms);
GeneratorParameters cookieGeneratorParameters() const;
bool setDtlsConfiguration(const QSslConfiguration &configuration);
QSslConfiguration dtlsConfiguration() const;
HandshakeState handshakeState() const;
bool doHandshake(QUdpSocket *socket, const QByteArray &dgram = {});
bool handleTimeout(QUdpSocket *socket);
bool resumeHandshake(QUdpSocket *socket);
bool abortHandshake(QUdpSocket *socket);
bool shutdown(QUdpSocket *socket);
bool isConnectionEncrypted() const;
QSslCipher sessionCipher() const;
QSsl::SslProtocol sessionProtocol() const;
qint64 writeDatagramEncrypted(QUdpSocket *socket, const QByteArray &dgram);
QByteArray decryptDatagram(QUdpSocket *socket, const QByteArray &dgram);
QDtlsError dtlsError() const;
QString dtlsErrorString() const;
QList<QSslError> peerVerificationErrors() const;
void ignoreVerificationErrors(const QList<QSslError> &errorsToIgnore);
Q_SIGNALS:
void pskRequired(QSslPreSharedKeyAuthenticator *authenticator);
void handshakeTimeout();
private:
bool startHandshake(QUdpSocket *socket, const QByteArray &dgram);
bool continueHandshake(QUdpSocket *socket, const QByteArray &dgram);
Q_DECLARE_PRIVATE(QDtls)
Q_DISABLE_COPY_MOVE(QDtls)
};
QT_END_NAMESPACE
#endif // QDTLS_H
|
c0f01aece36b44f01724671fcf7be90ed0206bc5
|
08b6b4544776ae685a7113a82953cd7d5b02952f
|
/SNOTRA/Game.cpp
|
4fb014afffec8e14e6b180f6be8624f09b51829e
|
[] |
no_license
|
SNOTRAProject/snotra
|
964cdc11c34dc56375af71e2e29fb1db2c703f8c
|
e7321ecf49ea064563bbcb45cc000cd9a3110f62
|
refs/heads/master
| 2020-06-01T16:41:12.982628
| 2013-04-18T17:07:44
| 2013-04-18T17:07:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,334
|
cpp
|
Game.cpp
|
/*
* File: Game.cpp
* Author: antoine
*
* Created on 12 février 2013, 22:17
*/
#include "Game.h"
#include "BackupManager.h"
#include "WireShark.h"
/**
* the window Game and connect the toolbox and the area of the game
*/
Game::Game() {
gameWindow.setupUi(this);
QMdiSubWindow * toolBoxMdi = new QMdiSubWindow;
QMdiSubWindow * networkGameAreaMdi = new QMdiSubWindow;
gameWindow.mdiArea->addSubWindow(toolBoxMdi);
gameWindow.mdiArea->addSubWindow(networkGameAreaMdi);
toolBox = new ToolBox();
networkGameArea = new NetworkGameArea();
toolBoxMdi->setWidget(toolBox);
networkGameAreaMdi->setWidget(networkGameArea);
networkGameAreaMdi->setGeometry(300, 0, 1200, 800);
connect(gameWindow.actionTool_Box, SIGNAL(activated()), toolBox,
SLOT(show()));
connect(toolBox->widget.pushButtonFil, SIGNAL(clicked()), networkGameArea,
SLOT(pushButtonPressed()));
// connect(gameWindow.actionCharger, SIGNAL(activated()), networkGameArea,
// SLOT(slotLoadLabelList()));
// connect(gameWindow.actionSauvegarder, SIGNAL(activated()), networkGameArea,
// SLOT(slotSaveLabelList()));
connect(gameWindow.actionNouvelle, SIGNAL(activated()), networkGameArea,
SLOT(slotResetGame()));
}
Game::~Game() {
}
|
484125a27139015864659b97b376b4cefe711c37
|
02377b31ea07978717e8cb5c702fd135cc16f04e
|
/Lógica de Programação/URI n div 10000.cpp
|
a4f44cbab99a2242e55df76e14be8aad0ef76022
|
[
"MIT"
] |
permissive
|
biielsantos/SENAI
|
3d28daf2989f5fd5598da84628414addf384cf23
|
dad5ef5519cb6ece833d9862eff280a98ff9e6f6
|
refs/heads/main
| 2023-03-24T23:49:16.809328
| 2021-03-23T23:32:00
| 2021-03-23T23:32:00
| 350,887,266
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 142
|
cpp
|
URI n div 10000.cpp
|
#include <stdio.h>
int main(){
int n, i;
scanf("%d", &n);
for(i = 1; i <=10000; i++){
if (i%n == 2){
printf("%d\n", i);
}
}
}
|
a688f65e05798c317442b0a1547e70f43a2bf9eb
|
806a0e71fa40501e2f0edfe62269e8801f187e5c
|
/C++/BaiTap/NganHang/De1/nguoi.h
|
1a8025f544a489037bcc26299c7500b13d2a25f4
|
[] |
no_license
|
ducthangbui/Learning
|
1c991a84a27cf6f112f9d2d643eacfdfb0a1de49
|
5a7acdf0c05e00e4ba736113a075423bf0b967db
|
refs/heads/master
| 2020-03-31T13:46:30.180506
| 2018-10-14T15:18:06
| 2018-10-14T15:18:06
| 152,268,559
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 267
|
h
|
nguoi.h
|
#ifndef NGUOI_H
#define NGUOI_H
#include <iostream>
using namespace std;
/*
* No description
*/
class Nguoi
{
// private section
public:
// class constructor
Nguoi();
void Nhap();
void Xuat();
protected:
string hoten,diachi,sdt;
};
#endif // NGUOI_H
|
9b845882f8d502a2e5603402b0ae4bcd3f750b1d
|
01b1f86aa05da3543a2399ffc34a8ba91183e896
|
/modules/type/complex/polynom/unit/scalar/ratfracder.cpp
|
821c96d72f2724cd8300b263eb339148a5206fbf
|
[
"BSL-1.0"
] |
permissive
|
jtlap/nt2
|
8070b7b3c4b2f47c73fdc7006b0b0eb8bfc8306a
|
1b97350249a4e50804c2f33e4422d401d930eccc
|
refs/heads/master
| 2020-12-25T00:49:56.954908
| 2015-05-04T12:09:18
| 2015-05-04T12:09:18
| 1,045,122
| 35
| 7
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,646
|
cpp
|
ratfracder.cpp
|
//==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#include <nt2/table.hpp>
#include <nt2/include/functions/ratfracder.hpp>
#include <nt2/include/functions/tie.hpp>
#include <nt2/include/functions/of_size.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/unit/tests/relation.hpp>
#include <complex>
#include <nt2/include/functions/complexify.hpp>
NT2_TEST_CASE_TPL ( ratfracder_real__1_0, NT2_REAL_TYPES)
{
typedef std::complex<T> cT;
using nt2::ratfracder;
using nt2::tag::ratfracder_;
nt2::table<cT> a = nt2::_(T(1), T(4));
nt2::table<cT> b = nt2::_(T(1), T(3));
nt2::table<cT> c(nt2::of_size(1, 0));
nt2::table<cT> n, d;
T rn[] = { 1, 4, 10, 4, 1 };
T rd [] = { 1, 4, 10, 12, 9 };
T dab[] = { 1, 4, 10, 4, 1 };
T da [] = { 3, 4, 3 };
nt2::table<cT> rdab(nt2::of_size(1, 5), &dab[0], &dab[5]);
nt2::table<cT> rda (nt2::of_size(1, 3), &da[0], &da[3]);
nt2::table<cT> rnn (nt2::of_size(1, 5), &rn[0], &rn[5]);
nt2::table<cT> rdd (nt2::of_size(1, 5), &rd[0], &rd[5]);
NT2_TEST_EQUAL(rda, ratfracder(a));
NT2_TEST_EQUAL(rdab, ratfracder(a, b));
nt2::tie(n, d) = ratfracder(a, b);
NT2_TEST_EQUAL(rnn, n);
NT2_TEST_EQUAL(rdd, d);
}
|
ce25a846e43189e3221d01793bb7b45c01c91150
|
2c7bad0defab1f275b8e65e614932b3833e73f9f
|
/src/common/config.cpp
|
67a4f5734882cd7c10115f8af52b42d016c4fc79
|
[
"MIT"
] |
permissive
|
Fadis/shader-samples-2020
|
84557a108466a20618738e902b902e9f04469d3c
|
916554161f63f62b33c85ffc8731ad003ef6cccb
|
refs/heads/master
| 2021-01-13T23:27:22.881671
| 2020-02-23T14:15:10
| 2020-02-23T14:17:36
| 242,527,752
| 4
| 0
| null | null | null | null |
EUC-JP
|
C++
| false
| false
| 3,122
|
cpp
|
config.cpp
|
#include <iostream>
#include <boost/filesystem/path.hpp>
#include <boost/program_options.hpp>
#include <boost/spirit/include/qi.hpp>
#include <cstdlib>
#include "common/config.h"
namespace common {
configs_t parse_configs( int argc, const char *argv[] ) {
namespace po = boost::program_options;
po::options_description desc( "Options" );
unsigned int device_index = 0u;
bool default_camera;
std::string window_size;
std::string shader_dir;
std::string mesh_file;
std::string vertex_shader;
std::string fragment_shader;
float zoom;
bool rotate;
desc.add_options()
( "help,h", "show this message" )
( "list,l", "show all available devices" )
( "device,d", po::value< unsigned int >(&device_index)->default_value( 0u ), "use specific device" )
( "validation,v", "use VK_LAYER_LUNARG_standard_validation" )
( "window,w", po::value< std::string >(&window_size)->default_value( "640x480" ), "window size" )
( "fullscreen,f", "fullscreen" )
( "debug,g", "debug mode" )
( "shader,s", po::value< std::string >(&shader_dir)->default_value( "../shaders/" ), "shader directory" )
( "vertex_shader,v", po::value< std::string >(&vertex_shader)->default_value( "simple.vert.spv" ), "shader directory" )
( "fragment_shader,p", po::value< std::string >(&fragment_shader)->default_value( "simple.frag.spv" ), "shader directory" )
( "mesh,m", po::value< std::string >(&mesh_file)->default_value( "../mesh/sponza.dae" ), "mesh file" )
( "default_camera,c", po::value< bool >(&default_camera)->default_value( false ), "default camera" )
( "zoom,z", po::value< float >(&zoom)->default_value( 1.0 ), "zoom" )
( "rotate,r", po::value< bool >(&rotate)->default_value( false ), "rotate" );
po::variables_map vm;
po::store( po::parse_command_line( argc, argv, desc ), vm );
po::notify( vm );
if( vm.count( "help" ) ) {
std::cout << desc << std::endl;
exit( 0 );
}
namespace qi = boost::spirit::qi;
auto iter = window_size.begin();
const auto end = window_size.end();
boost::fusion::vector< unsigned int, unsigned int > parsed_window_size;
if( !qi::parse( iter, end, qi::uint_ >> 'x' >> qi::uint_, parsed_window_size ) ) {
std::cerr << "不正なウィンドウサイズ: " << window_size << std::endl;
exit( 1 );
}
return configs_t()
.set_prog_name( boost::filesystem::path( argv[ 0 ] ).filename().native() )
.set_device_index( device_index )
.set_list( vm.count( "list" ) )
.set_validation( vm.count( "validation" ) )
.set_width( boost::fusion::at_c< 0 >( parsed_window_size ) )
.set_height( boost::fusion::at_c< 1 >( parsed_window_size ) )
.set_fullscreen( vm.count( "fullscreen" ) )
.set_debug_mode( vm.count( "debug" ) )
.set_shader_dir( shader_dir )
.set_mesh_file( mesh_file )
.set_vertex_shader( vertex_shader )
.set_fragment_shader( fragment_shader )
.set_default_camera( default_camera )
.set_zoom( zoom )
.set_rotate( rotate );
}
}
|
ba34f701fb78357e4826e912602ea9bd359be4af
|
e243c8817e2196b3fbff88ee3d568f644472f1ad
|
/CPP Tutorial/cpp4.cpp
|
0881d9180f9eef0554bb199ca615fda18b72a13b
|
[] |
no_license
|
keerthu230/Programming
|
7a0417e46f8a9c6b25516d47989d2f0b33d6635a
|
1695b804a673237de406e18a1a475e72f20f7118
|
refs/heads/main
| 2023-06-10T06:05:41.919723
| 2021-06-30T18:08:24
| 2021-06-30T18:08:24
| 381,247,600
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,765
|
cpp
|
cpp4.cpp
|
// cpp tutorial 4
// Data types -> int , float , double , char , bool , signed and unsigned of char , int , short int , long int
// naming variables with -> camel casing format -> alphabetNumber , begins with small letter then new word begins with capital one
#include<iostream>
using namespace std;
int main()
{
int DOB = 1999;
char Gender = 'f';
bool Is_older_than_18 = true;
float Average_IQ = 7.5;
double bank_balance = 500000000;
// space allocatation of each data type
// sizeof() -> find the memory used by each operator
cout<<"Size of int -> "<<sizeof(int)<<" bytes"<<endl;
cout<<"Int min value(64 bits) is -> "<<INT64_MIN<<endl;
cout<<"Int min value(32 bits ) is -> "<<INT32_MIN<<endl;
cout<<"Int min value(16 bits ) is -> "<<INT16_MIN<<endl;
cout<<"Int min value(8 bits ) is -> "<<INT8_MIN<<endl;
cout<<"Int max value(64 bits) is -> "<<INT64_MAX<<endl;
cout<<"Int max value(32 bits ) is -> "<<INT32_MAX<<endl;
cout<<"Int max value(16 bits ) is -> "<<INT16_MAX<<endl;
cout<<"Int max value(8 bits ) is -> "<<INT8_MAX<<endl;
// INT_MIN and INT_MAX Values may vary from complier to complier ,
// deponding on the complier to stores the integer values using 64 bits or 32 bits or 16 bits or 8 bits .
//want to use positive inetgers only -> (unsigned int) datatype 32 bits
cout<<"size of unsigned int -> "<<sizeof(unsigned int)<<" bytes"<<endl;
cout<<"unsigned int max value -> "<<UINT32_MAX<<endl;
// size of data types
cout<<"size of char -> "<<sizeof(char)<<" bytes"<<endl;
cout<<"size of unsigned char -> "<<sizeof(unsigned char)<<" bytes"<<endl;
cout<<"size of signed char -> "<<sizeof(signed char)<<" bytes"<<endl;
cout<<"size of int -> "<<sizeof(int)<<" bytes"<<endl;
cout<<"size of unsigned int -> "<<sizeof(unsigned int)<<" bytes"<<endl;
cout<<"size of signed int -> "<<sizeof(signed int)<<" bytes"<<endl;
cout<<"size of short int -> "<<sizeof(short int)<<" bytes"<<endl;
cout<<"size of unsigned short int -> "<<sizeof(unsigned short int)<<" bytes"<<endl;
cout<<"size of signed short int -> "<<sizeof(signed short int)<<" bytes"<<endl;
cout<<"size of long int -> "<<sizeof(long int)<<" bytes"<<endl;
cout<<"size of unsigned long int -> "<<sizeof(unsigned long int)<<" bytes"<<endl;
cout<<"size of signed long int -> "<<sizeof(signed long int)<<" bytes"<<endl;
cout<<"size of float -> "<<sizeof(float)<<" bytes"<<endl;
cout<<"size of double -> "<<sizeof(double)<<" bytes"<<endl;
cout<<"size of bool -> "<<sizeof(bool)<<" bytes"<<endl;
// 1 byte = 8 bit
}
|
a6acc689b313a5d18a4a97eebe8df0d240ff1c6c
|
4a8c93591269fba8e7f87ffacf2d1e18f049a682
|
/Example/linked list (insert + sort).cpp
|
14fcdd51efd87b27cbe41645be96264091cc5f4d
|
[] |
no_license
|
Pooh1223/Online-Judge
|
fd3c237b21bd07396e841b4d077a997c51383d8a
|
afb208ccc5ecc6f3fa42693d190dc64e19195ff6
|
refs/heads/master
| 2020-07-25T19:28:30.163074
| 2020-06-29T15:15:32
| 2020-06-29T15:15:32
| 208,401,769
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,098
|
cpp
|
linked list (insert + sort).cpp
|
#include <cstdio>
#include <cstdlib>
typedef struct node {
int val;
struct node *next;
}node;
node *head = NULL;
// insert value "val" into link list
void insert_value(int val)
{
node *prev, *rush;
// create node for that insertor
node *data = (node*) malloc(sizeof(node));
// put the value in that node
data->val = val;
prev = rush = head;
// find out the correct position for val
while (rush != NULL && val > rush->val) {
prev = rush;
rush = rush->next;
}
// link it next to the bigger value
data->next = rush;
// if there is no element in link list
// or val is the smallest
if (rush == head)
head = data;
else
prev->next = data;
}
// show link list elements
void show_list(void)
{
node *rush = head;
printf("\nThe result is:\n");
while (rush != NULL) {
printf("%d ", rush->val);
rush = rush->next;
}
puts("");
}
int main()
{
int n;
printf("Enter values:\n");
while(scanf("%d", &n) != EOF) {
printf("%d ", n);
insert_value(n);
}
show_list();
return 0;
}
|
ccaaa0c337c52b5e551299b7fa8f6c80e6550c6f
|
4edbb86de29e65b1a1f9068431a4eec57ff29d5a
|
/Server_ChattingSystem/Command.h
|
3be8929b90e34ea8e481525d79482c8a47dac464
|
[] |
no_license
|
nntp0/ChattingMFC
|
ecf36584ecd4da4381fbca98f91073b6ffc51210
|
8027eaa2934bbfc5ec27e040aa69bc85e8fe3e8d
|
refs/heads/master
| 2023-06-18T21:46:14.063051
| 2021-07-19T13:45:59
| 2021-07-19T13:45:59
| 357,121,748
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 679
|
h
|
Command.h
|
#pragma once
#include "iServer.h"
#include "iCommand.h"
// CreateRoomDlg 대화 상자
class CommandDlg : public CDialogEx, public iCommand
{
DECLARE_DYNAMIC(CommandDlg)
public:
CommandDlg(CWnd* pParent = nullptr); // 표준 생성자입니다.
virtual ~CommandDlg();
// 대화 상자 데이터입니다.
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_DIALOG1 };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
virtual BOOL OnInitDialog();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedOk();
private:
CString commandLine;
CMutex mtxCommandResultList;
public:
void MessageResponse(CString commandResult);
};
|
c2d3fdd4f15348dc1be1b839b2877873e317610d
|
202b96b76fc7e3270b7a4eec77d6e1fd7d080b12
|
/platforms/unix/product/x11quick/popupmenu.h
|
dc9e8e370b04c3af6b9d7a7d66076a1d8980126b
|
[] |
no_license
|
prestocore/browser
|
4a28dc7521137475a1be72a6fbb19bbe15ca9763
|
8c5977d18f4ed8aea10547829127d52bc612a725
|
refs/heads/master
| 2016-08-09T12:55:21.058966
| 1995-06-22T00:00:00
| 1995-06-22T00:00:00
| 51,481,663
| 98
| 66
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,932
|
h
|
popupmenu.h
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* Espen Sand
*/
#ifndef POPUPMENU_H
#define POPUPMENU_H
#include "menuelement.h"
#include "modules/hardcore/timer/optimer.h"
#include "modules/pi/OpView.h"
#include "modules/skin/OpWidgetImage.h"
#include "modules/util/simset.h"
#include "platforms/unix/base/x11/x11_widget.h"
#include "adjunct/desktop_scope/src/generated/g_scope_desktop_window_manager_interface.h"
class OpFont;
class OpInputAction;
class OpWidget;
class OpWindow;
class PopupMenuItem;
class PopupMenuComponent;
class PopupMenu
:public MenuElement
,public OpPaintListener
,public OpMouseListener
,public X11Widget::InputEventListener
,public OpTimerListener
{
public:
enum ContextType
{
UnknownContext, KeyboardContext, MouseContext
};
class PopupMenuListener
{
public:
virtual void OnPopupOpened() = 0;
virtual void OnPopupClosed() = 0;
};
enum AnchorType { BELOW_OR_ABOVE, RIGHT_OR_LEFT_OF };
private:
struct SubMenuData
{
SubMenuData() { value = 0; start = 0;}
OpString8 name;
INTPTR value;
INT32 start;
};
public:
PopupMenu();
~PopupMenu();
OP_STATUS Init() { return OpStatus::OK; } // For OpMouseListener. What's the point?
OP_STATUS Init(OpView *parent);
/**
* Appends an item or a sub menu entry to the menu
*/
OP_STATUS AddItem(const uni_char* name, const uni_char* shortcut, OpInputAction* action, UINT32 state, OpWidgetImage* image, PopupMenu* submenu=0);
/**
* Appends a separator to the menu. If last item already is a separator no
* new separator is created.
*/
OP_STATUS AddSeparator();
/**
* Sets the selected item. Inf index is less than 0
* the selected item will be cleared
*/
void SetSelectedItem(INT32 index);
/**
* Sets that menu element that acts as the parent of this menu
*/
void SetParent(MenuElement *parent) {m_parent_menu = parent;}
/**
* Sets the context to be used when executing an action
*/
void SetExecContext( ContextType context_type ) { m_context_type = context_type; }
/**
* Returns the context to be used when executing an action
*/
ContextType GetExecContext() const { return m_context_type; }
/**
* Sets data used for opening a submenu
*
* @return OpStatus::OK on success
*/
OP_STATUS SetSubMenuData(const char* sub_menu_name, INTPTR sub_menu_value, INT32 sub_menu_start);
/**
* Sets this menu as the hotclick menu or removes all
* references to a hotclick menu
*
* @param is_hotclick Set if TRUE, otherwise reset
*/
void SetIsHotClickMenu(BOOL is_hotclick) { m_hotclick_menu = is_hotclick ? this : 0; }
/**
* Cancels (hide and do not execute any action) the menu
*/
void Cancel();
/**
* Repaints the entire window
*/
void Invalidate();
/**
* Returns currently selected action.
*
* @return Returns 0 if not slected item or menu was cancelled
*/
OpInputAction* TakeInputAction();
/**
* Returns TRUE if menu has any content, otherwise FALSE
*/
BOOL HasContent() const { return !!m_menu_items.First(); }
/**
* Returns TRUE if the height of the menu will extend the
* screen height if adding a new normal item
*/
BOOL SoonTooTall();
/**
* Returns width of menu should it be shown right now
*/
UINT32 GetWidth() const;
/**
* Returns height of menu should it be shown right now
*/
UINT32 GetHeight() const;
/**
* Returns item height.
*/
UINT32 GetItemHeight() const;
/**
* Computes item position relative to menu window
*
* @return true if item (and thus x and y) is valid
*/
bool GetItemPosition(PopupMenuComponent* item, INT32& x, INT32& y);
/**
* Returns separator height
*/
UINT32 GetSeparatorHeight() const;
/**
* Returns internal view
*/
OpView *GetOpView() const { return m_opview; }
/**
* @return Font to use for bold menu items
*/
OpFont* GetBoldFont();
/**
* @return Font to use for normal menu items (non-bold)
*/
OpFont* GetNormalFont();
/**
* Returns TRUE if a menu can be closed. This is just an advisory.
* Automatically opened sub menus can return FALSE if not enough time
* has elapsed since they were opened
*
* @return See above
*/
BOOL CanHideNow() const;
/**
* Returns a pointer to the menu (itself, a sub menu, sub sub menu etc)
* that is visible and contains the global coordinate. 0 is returned on
* no match
*
* @param gx Global X coordinate
* @param gy Global Y coordinate
* @param include_submenu Include sub menu(s) in test if TRUE
*
* @return See above
*/
PopupMenu* Contains(int gx, int gy, BOOL include_submenu);
void OnItemHover(PopupMenuComponent* item);
void ClearStatusBar();
/**
* Grabs mouse and keyboard
*/
void Grab();
/**
* Moves this menu to a new position.
*
* @param anchor_type how to compute the position from @a anchor_rect
* @param anchor_rect calculate the position as adjacent to this rect.
* Screen coordinates are assumed.
*/
void MoveTo(AnchorType anchor_type, const OpRect& anchor_rect);
/*
* Implementation of MenuElement
*/
bool IsMenuBar() const { return false; }
void Stop(bool cancel=false);
void CancelSubMenu();
void ShowNext(MenuElement* current, bool next);
bool HandleMouseEvent(int gx, int gy, MouseEvent event, bool confine_to_area);
bool ShowSubmenu(int gx, int gy);
MenuElement* Hide(int gx, int gy);
PopupMenuComponent* ItemAt(int gx, int gy);
/*
* Implementation of OpPaintListener
*/
void OnPaint(const OpRect &rect, OpView *view);
/*
* Implementation of OpMouseListener
*/
void OnMouseMove(const OpPoint &point, ShiftKeyState shift_state, OpView *view);
void OnMouseDown(MouseButton button, UINT8 nclicks, ShiftKeyState shift_state, OpView *view);
void OnMouseUp(MouseButton button, ShiftKeyState shift_state, OpView *view);
void OnMouseLeave();
BOOL OnMouseWheel(INT32 delta, BOOL vertical, ShiftKeyState shift_state ) { return TRUE; }
void OnSetCursor();
void OnMouseCaptureRelease();
/**
* Implementation of X11Widget::InputEventListener
*/
BOOL OnInputEvent(XEvent* e);
/**
* Implementation of OpTimerListener
*/
void OnTimeOut(OpTimer* timer);
void PostPendingMenu();
/**
* Specify Opera menu
*
* @param is_o_menu The menu is an O-menu if true
*/
void SetIsOMenu(bool is_o_menu) { m_is_o_menu = is_o_menu; }
/**
* Set popup listener. There can only be one listener
*/
void SetPopupMenuListener(PopupMenuListener* listener) {m_listener = listener;}
/**
* For Scope Automated UI testing.
*
* @param menu_name The name of the menu
* @param info Scope Info structure that is to be be filled with information about the menu
*/
OP_STATUS SetQuickMenuInfo(class OpScopeDesktopWindowManager_SI::QuickMenuInfo& info);
/**
* For Scope Automated testing
*
* @param menu The menu that is about to be shown/closed
* @param show TRUE or FALSE
*/
void SendOnMenuShown(PopupMenu* menu, BOOL show);
/**
* Sets this menu as the topmost popup menu
* (used so scope can retrieve the open menus)
*
*/
void SetIsTopPopupMenu() { m_topmost_popup_menu = this; }
/**
* Sets this menu as the bookmark context menu
* (used so Scope can retrieve all open menus)
*/
void SetIsBookmarkContextMenu() { m_bookmark_context_menu = this; }
/**
* Set the name to be used to identify this menu to Scope
* (this name is normally the one found in standard_menu.ini)
*/
void SetScopeName(const char* name) { m_scope_name.Set(name); }
/**
* Get ScopeName that can be used to identify the menu to Scope
*/
const OpStringC& GetScopeName() { return m_scope_name;}
/**
* Opens a menu and invokes the action if user chooses to do so.
*
* @param menu the menu to show
* @param anchor_type how to compute the position from @a anchor_rect
* @param anchor_rect calculate the position as adjacent to this rect.
* Screen coordinates are assumed.
* @param delete_menu delete menu before action is invoked if @c true. The
* menu is not deleted at all if @c false.
* @param invoke_action invoke the selected action before the function
* returns
*
* @return the selected action type or OpInputAction::ACTION_UNKNOWN if the
* menu is canceled
*/
static OpInputAction::Action Exec(PopupMenu* menu, AnchorType anchor_type, const OpRect& anchor_rect, bool delete_menu, bool invoke_action);
static OpInputAction::Action Exec(PopupMenu* menu, const OpPoint& anchor_point, bool delete_menu, bool invoke_action)
{ return Exec(menu, BELOW_OR_ABOVE, OpRect(anchor_point.x, anchor_point.y, 0, 0), delete_menu, invoke_action); }
/**
* Returns the active hotclick menu, if any
*/
static PopupMenu* GetHotClickMenu();
/**
* Returns the topmost (not a submenu) popupmenu open, if any
*/
static PopupMenu* GetTopPopupMenu();
/**
* Returns the bookmark context menu (from rightclicking a bookmark menu item)
* if it is Open, otherwise NULL
*/
static PopupMenu* GetBookmarkContextMenu();
/**
* Returns the submenu of this menu that is currently open, if any
*/
PopupMenu* GetOpenSubMenu() { return m_open_submenu; }
/**
* Returns TRUE if event shall be blocked from further processing
*
* @param e X11 event to test
*
* @return TRUE if event should be filtered, otherwise FALSE
*/
static BOOL FilterEvent(XEvent* e);
static bool SupportMouseHover();
private:
void AboutToShow();
void Show(AnchorType anchor_type, const OpRect& anchor_rect);
void Hide();
void Exec(AnchorType anchor_type, const OpRect& anchor_rect);
bool ShowSubmenu(bool activate);
bool IsSubmenu() const { return m_parent_menu != NULL; }
/**
* Select and repaint all items in the parent menu chain
* if pupup menu contains a selected item
*/
void SelectParents();
/**
* Converts the position into a global coordinate
*
* @param point Local position in window
*
* @return The global position
*/
OpPoint ConvertToScreen(const OpPoint& point);
/**
* @param anchor_type how to compute the position from @a anchor_rect
* @param anchor_rect calculate the position as adjacent to this rect.
* Screen coordinates are assumed.
* @return menu position in screen coordinates
*/
OpPoint CalculateMenuPosition(AnchorType anchor_type, const OpRect& anchor_rect) const;
/**
* Returns the menu item located a the coordinate or 0
* if outside menu area.
*
* @param x X position (local to the window)
* @param y Y position (local to the window)
*
* @return The item or 0
*/
PopupMenuComponent* GetItem(INT32 x, INT32 y);
/**
* Returns the menu item located a the y coordinate.
*
* @param x X position (local to the window)
*
* @return The item or 0
*/
PopupMenuComponent* GetItem(INT32 y) { return GetItem(0,y); }
void PaintMenuFrame(OpPainter* painter, const OpRect& view_rect, const OpRect& rect);
private:
Head m_menu_items;
X11OpWindow* m_opwindow;
OpView* m_opview;
OpWidget* m_paint_widget;
OpFont* m_normalfont;
OpFont* m_boldfont;
MenuElement* m_parent_menu;
PopupMenu* m_open_submenu;
PopupMenuComponent* m_selected_item;
PopupMenuComponent* m_mouse_selected_item;
PopupMenuListener* m_listener;
ContextType m_context_type;
UINT32 m_image_width;
UINT32 m_image_height;
UINT32 m_max_text_width;
UINT32 m_max_shortcut_width;
double m_auto_shown_time;
bool m_has_submenus;
bool m_cancelled;
bool m_mouse_has_moved;
bool m_is_o_menu;
SubMenuData m_submenu;
OpTimer m_timer;
OpString m_scope_name;
private:
static PopupMenu* m_hotclick_menu;
static bool m_block_mouse_up;
static bool m_block_after_close;
static OpInputAction* m_exec_action;
static ContextType m_exec_context;
static PopupMenu* m_topmost_popup_menu;
static PopupMenu* m_bookmark_context_menu;
};
#endif // POPUPMENU_H
|
3fea5fc943a13ae87cb92af0dc457c3a869f3668
|
32da723b5c759c98845249bb51332109014b4f62
|
/C++OOP.cpp/03 ReadingAndPrintingOnTextFile/InputOutputTextFilesSecond.cpp
|
98109e1011d07f20befb137dd017b70bc0e20467
|
[] |
no_license
|
IliyanKafedzhiev/FacultyOfMathematicAndInformatic
|
b8a810ca1100cc0f39c1460f60eb014e4c0b5ffc
|
a2b05a9aa7e677609447c0311ee79552464434ce
|
refs/heads/master
| 2020-07-06T04:19:30.531000
| 2015-03-02T21:54:42
| 2015-03-02T21:54:42
| 18,809,355
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 339
|
cpp
|
InputOutputTextFilesSecond.cpp
|
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string line;
ifstream text;
text.open("ntbtlog.txt");
if (text.is_open())
{
while (text.good())
{
getline (text,line);
cout<<line<<endl;
}
}
text.close();
return 0;
}
|
d5baa15c72e8ce844f0b984ff7f3b80fa5efb5ef
|
c0d7220b4e4c572ebd0394aebe5e8b63ea0593b0
|
/Bomberman/GameEngine.cpp
|
eb1b496ce760ad07e3dac5a45a7302b8747e0958
|
[] |
no_license
|
CyrilPivec/teck3
|
602f7bbd703da0376662673052438cbd953a22a1
|
df5041d487d4efad0b43a2f60c9422b31f2d77db
|
refs/heads/master
| 2021-01-10T17:38:25.864288
| 2017-04-19T00:09:39
| 2017-04-19T00:09:39
| 51,869,830
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,395
|
cpp
|
GameEngine.cpp
|
#include "GameEngine.hpp"
#include <iostream>
GameEngine::GameEngine()
{
}
GameEngine::~GameEngine()
{
for (size_t i = 0; i < _objects.size(); ++i)
delete _objects[i];
delete _ground;
delete _mapLoader;
}
bool GameEngine::initialize()
{
if (!_context.start(1000, 800, "My bomberman!"))
return false;
glEnable(GL_DEPTH_TEST);
if (!_shader.load("./shaders/basic.fp", GL_FRAGMENT_SHADER)
|| !_shader.load("./shaders/basic.vp", GL_VERTEX_SHADER)
|| !_shader.build())
return false;
_mapLoader = new Map("./maps/map2");
if (!_mapLoader->load())
return false;
_map = _mapLoader->getMap();
_ground = new Ground(glm::vec3(_mapLoader->getMaxX(), 0, _mapLoader->getMaxZ()));
if (!_ground->initialize())
return false;
glm::mat4 projection;
glm::mat4 transformation;
AObject* p = new Player(0, _map, &_bombs);
if (p->initialize() == false)
return false;
_objects.push_back(p);
AObject* p2 = new Player(1, _map, &_bombs);
if (p2->initialize() == false)
return false;
_objects.push_back(p2);
projection = glm::perspective(60.0f, 1000.0f / 800.0f, 0.1f, 100.0f);
transformation = glm::lookAt(glm::vec3(7.0f, 10.0f, 15.0f),
glm::vec3(7.0f, 0.0f, 5.0f),
glm::vec3(0.0f, 1.0f, 0.0f));
_shader.bind();
_shader.setUniform("view", transformation);
_shader.setUniform("projection", projection);
return true;
}
bool GameEngine::update()
{
if (_input.getKey(SDLK_ESCAPE) || _input.getInput(SDL_QUIT))
return false;
_context.updateClock(_clock);
_context.updateInputs(_input);
for (size_t i = 0; i < _objects.size(); ++i)
_objects[i]->update(_clock, _input);
for (std::vector<Bomb*>::iterator it = _bombs.begin();
it != _bombs.end();)
{
if ((*it)->getExploded())
{
this->explosion(*it);
delete *it;
it = _bombs.erase(it);
}
else
{
(*it)->update(_clock, _input);
++it;
}
}
for (std::vector<Fire*>::iterator it = _fires.begin();
it != _fires.end();)
{
if ((*it)->getStatus())
{
delete *it;
it = _fires.erase(it);
}
else
{
(*it)->update(_clock, _input);
++it;
}
}
return true;
}
void GameEngine::draw()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
_shader.bind();
_ground->draw(_shader, _clock);
for (size_t i = 0; i < _map->size(); ++i)
{
for (size_t j = 0; j < (*_map)[i].size(); ++j)
if ((*_map)[i][j])
(*_map)[i][j]->draw(_shader, _clock);
}
for (size_t i = 0; i < _objects.size(); ++i)
_objects[i]->draw(_shader, _clock);
for (size_t i = 0; i < _bombs.size(); ++i)
_bombs[i]->draw(_shader, _clock);
for (size_t i = 0; i < _fires.size(); ++i)
_fires[i]->draw(_shader, _clock);
_context.flush();
}
void GameEngine::explosion(Bomb* b)
{
float x = b->getPosX();
float z = b->getPosZ();
Fire* f;
f = new Fire(x, z, _map, &_objects);
if (!f->initialize())
return;
_fires.push_back(f);
f = new Fire(x - 1.0, z, _map, &_objects);
if (!f->initialize())
return;
_fires.push_back(f);
f = new Fire(x + 1.0, z, _map, &_objects);
if (!f->initialize())
return;
_fires.push_back(f);
f = new Fire(x, z - 1.0, _map, &_objects);
if (!f->initialize())
return;
_fires.push_back(f);
f = new Fire(x, z + 1.0, _map, &_objects);
if (!f->initialize())
return;
_fires.push_back(f);
}
|
8aa4e5948b282fda3f486c5803c370d3ca799c05
|
8689857310cdb7ac9dd9dde14195e50742d1f471
|
/geeksforgeeks/graphs/add-maximum-edges.cpp
|
fae827c32020e3446ff4d3515f78f47ae73ce12f
|
[] |
no_license
|
aayush2k11/competitive-programming
|
78a50826b92e2f3381d802bdee19ed58f10dd8c4
|
1eb3d770be9e6d4ff85dfabee83c5ef3184eca08
|
refs/heads/master
| 2021-01-10T14:49:30.800522
| 2016-12-03T13:03:35
| 2016-12-03T13:03:35
| 55,831,180
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,621
|
cpp
|
add-maximum-edges.cpp
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <set>
#include <queue>
using namespace std;
vector<int> topologicalSort(vector<int> graph[], vector<int> indegree, int v){
vector<int> topolgical;
queue<int> q;
for (int i=0;i<v;i++){
if (indegree[i] == 0){
q.push(i);
}
}
while(!q.empty()){
int t = q.front();
q.pop();
topolgical.push_back(t);
for (int i=0;i<graph[t].size();i++){
cout << graph[t][i] << " ";
indegree[graph[t][i]]--;
if (indegree[graph[t][i]] == 0){
q.push(graph[t][i]);
}
}
}
return topolgical;
}
void maximumEdgeAddtion(vector<int> graph[], vector<int> indegree, int v){
bool visited[v];
for (int i=0;i<v;i++)
visited[i] = false;
vector<int> topo = topologicalSort(graph, indegree, v);
for (int i=0;i<topo.size();i++){
int t = topo[i];
for (int j=0;j<graph[t].size();j++){
visited[j] = true;
}
for (int j=i+1;j<topo.size();j++){
if (visited[topo[j]] == false){
cout << t << "-" << topo[j] << " ";
}
visited[topo[j]] = false;
}
cout << endl;
}
}
int main(){
int vertices, edge;
vector <int> graph[10005];
cout << "Enter number of vertices: " << endl;
cin >> vertices;
cout << "Enter number of edges: " << endl;
cin >> edge;
int x, y;
vector<int> indegree;
for (int i=0;i<vertices;i++){
indegree.push_back(0);
}
cout << "Enter edges: " << endl;
for (int i=0;i<edge;i++){
cin >> x >> y;
graph[x].push_back(y);
indegree[y]++;
}
maximumEdgeAddtion(graph, indegree, vertices);
return 0;
}
|
74b0e1dff31bae2791d87c5382a1564862d1aa99
|
5b83b4f72c9836cf9ee44b9aef7b2f045498ac22
|
/pot_game.cpp
|
4137262ad203bc2e1d77ba46a86b0bc6bacb69d5
|
[] |
no_license
|
liehendi11/cpsource
|
1d623ff7ead79f6de9442ec6c65e49d5dff0549f
|
154985a24ea64433733910bfde33325070fbcfe3
|
refs/heads/master
| 2016-09-11T11:12:25.142341
| 2015-01-27T14:34:15
| 2015-01-27T14:34:15
| 29,897,045
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 793
|
cpp
|
pot_game.cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <cstring>
using namespace std;
vector<int> dpSum;
vector<int> num;
int dp[100][100];
int n;
void createDpSum()
{
int sum = 0;
for (int i=0; i<num.size(); i++)
{
sum += num[i];
dpSum.push_back(sum);
}
}
int findSum(int a, int b)
{
int left = 0;
if (a > 0) left = dpSum[a-1];
return dpSum[b]-left;
}
int compute(int x, int y)
{
if (x==y) return num[x];
if (dp[x][y] == -1)
{
dp[x][y] = max(num[x] + findSum(x+1, y) - compute(x+1,y), num[y] + findSum(x, y-1) - compute(x, y-1));
}
return dp[x][y];
}
int main()
{
scanf("%d", &n);
int x;
for (int i=0; i<n; i++)
{
scanf("%d", &x);
num.push_back(x);
}
createDpSum();
memset(dp, -1, sizeof(dp));
printf("%d\n", compute(0, n-1));
return 0;
}
|
3e379c81becb3dbedac1e89a22347023cb8a197b
|
c84dbf974bfa9e1d07105f9ced9270ecffb2e5c5
|
/80-QThread-FileWrite/main.cpp
|
c1562a47a242d498f281d1fe3379d7f63169475b
|
[] |
no_license
|
yogach/QT-Experiment
|
859bf19804445f84f140c68b94d96a21c165cf99
|
70a8373c443b5e71c6925fb7e412eda912228d1f
|
refs/heads/main
| 2023-08-13T11:36:22.753072
| 2021-10-09T02:21:58
| 2021-10-09T02:21:58
| 350,174,937
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 491
|
cpp
|
main.cpp
|
#include <QtCore/QCoreApplication>
#include "FileWrite.h"
#include <QThread>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug() << "main() tid = " << QThread::currentThreadId();
FileWrite writer("/home/delphi/2.txt");
if( writer.open() )
{
writer.write("D.T.Software\r\n");
writer.write("中文测试\r\n");
writer.write("狄泰软件\r\n");
writer.close();
}
return a.exec();
}
|
807230735ae55db66ec2e7b6a5c903858db2082b
|
e83fd6a92810c746415a0648306ba2549d2df6ce
|
/include/Menu-UI/Image.h
|
336146f1890fa493de52898473ffb31987f220c8
|
[] |
no_license
|
Craigspaz/Axle
|
e59906af68a9d9b7e3fc7902cb4b70d630b09811
|
9a37162e393dba9f1a5b5769a6d88cd59a3e4a37
|
refs/heads/master
| 2023-06-05T15:08:47.044512
| 2021-06-23T01:38:12
| 2021-06-23T01:38:12
| 114,414,532
| 0
| 0
| null | 2020-10-12T18:05:57
| 2017-12-15T21:59:07
|
C
|
UTF-8
|
C++
| false
| false
| 419
|
h
|
Image.h
|
#ifndef __IMAGE__
#define __IMAGE__
#include "UIElement.h"
#include <iostream>
class Image : public UIElement
{
public:
Image(glm::vec3 position, glm::vec3 rotation, glm::vec3 scale, bool visible = true, bool disabled = false);
~Image();
void render();
UIElement toParentObject() const;
bool operator==(const Image &image);
bool operator!=(const Image &image);
private:
protected:
};
#endif
|
812b609549b30cda866d6695c05ca36080ed48f8
|
fb71a2ef9e4c2f33a33d74912bd28342c6200404
|
/tests/boost-http/request_parser_test.cc
|
c1689ca10191b3f128f66cbf020aa54aca392496
|
[] |
no_license
|
nzimmerman3/server
|
7aa2da4bc61b87a7365d5ed43a30f8790593e830
|
49d60d25425facda256597df22db97e8881ebe14
|
refs/heads/master
| 2022-11-12T04:42:28.019163
| 2020-06-24T19:31:09
| 2020-06-24T19:31:09
| 274,745,598
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,566
|
cc
|
request_parser_test.cc
|
#include "gtest/gtest.h"
#include "../../libraries/boost-http/include/request_parser.hpp"
#include "../../libraries/boost-http/include/request.hpp"
#include "../../libraries/boost-http/include/header.hpp"
class RequestParserTests : public ::testing::Test {
protected:
http::server::request_parser reqParser;
};
TEST_F(RequestParserTests, ParseValidRequest) {
std::string rawRequest = "GET / HTTP/1.1\r\nConnection: keep-alive\r\n\r\n";
http::server::request goldenRequest;
goldenRequest.method = "GET";
goldenRequest.uri = "/";
goldenRequest.http_version_major = 1;
goldenRequest.http_version_minor = 1;
http::server::header header;
header.name = "Connection";
header.value = "keep-alive";
goldenRequest.headers.push_back(header);
http::server::request request;
http::server::request_parser::result_type rc = std::get<0>(reqParser.parse(request, rawRequest.begin(), rawRequest.end()));
EXPECT_EQ(rc, http::server::request_parser::good);
// TODO: Overload = operator to make comparison of request easier
EXPECT_EQ(request.method, goldenRequest.method);
EXPECT_EQ(request.uri, goldenRequest.uri);
EXPECT_EQ(request.http_version_major, goldenRequest.http_version_major);
EXPECT_EQ(request.http_version_minor, goldenRequest.http_version_minor);
// EXPECT_EQ(request.headers, goldenRequest.headers);
}
TEST_F(RequestParserTests, MissingMethodRequest) {
std::string rawRequest = "/ HTTP/1.1\r\nConnection: keep-alive\r\n\r\n";
http::server::request request;
http::server::request_parser::result_type rc = std::get<0>(reqParser.parse(request, rawRequest.begin(), rawRequest.end()));
EXPECT_EQ(rc, http::server::request_parser::bad);
}
TEST_F(RequestParserTests, MissingURIRequest) {
std::string rawRequest = "GET HTTP/1.1\r\nConnection: keep-alive\r\n\r\n";
http::server::request request;
http::server::request_parser::result_type rc = std::get<0>(reqParser.parse(request, rawRequest.begin(), rawRequest.end()));
EXPECT_EQ(rc, http::server::request_parser::bad);
}
TEST_F(RequestParserTests, MissingVersionRequest) {
std::string rawRequest = "GET /\r\nConnection: keep-alive\r\n\r\n";
http::server::request request;
http::server::request_parser::result_type rc = std::get<0>(reqParser.parse(request, rawRequest.begin(), rawRequest.end()));
EXPECT_EQ(rc, http::server::request_parser::bad);
}
TEST_F(RequestParserTests, VersionMissingSlashRequest) {
std::string rawRequest = "GET / HTTP1.1\r\nConnection: keep-alive\r\n\r\n";
http::server::request request;
http::server::request_parser::result_type rc = std::get<0>(reqParser.parse(request, rawRequest.begin(), rawRequest.end()));
EXPECT_EQ(rc, http::server::request_parser::bad);
}
TEST_F(RequestParserTests, VersionMissingDotRequest) {
std::string rawRequest = "GET / HTTP/11\r\nConnection: keep-alive\r\n\r\n";
http::server::request request;
http::server::request_parser::result_type rc = std::get<0>(reqParser.parse(request, rawRequest.begin(), rawRequest.end()));
EXPECT_EQ(rc, http::server::request_parser::bad);
}
TEST_F(RequestParserTests, VersionMissingMajorRequest) {
std::string rawRequest = "GET / HTTP/.1\r\nConnection: keep-alive\r\n\r\n";
http::server::request request;
http::server::request_parser::result_type rc = std::get<0>(reqParser.parse(request, rawRequest.begin(), rawRequest.end()));
EXPECT_EQ(rc, http::server::request_parser::bad);
}
TEST_F(RequestParserTests, VersionMissingMinorRequest) {
std::string rawRequest = "GET / HTTP/1\r\nConnection: keep-alive\r\n\r\n";
http::server::request request;
http::server::request_parser::result_type rc = std::get<0>(reqParser.parse(request, rawRequest.begin(), rawRequest.end()));
EXPECT_EQ(rc, http::server::request_parser::bad);
}
TEST_F(RequestParserTests, MissingHeaderValueRequest) {
std::string rawRequest = "GET / HTTP/1.1\r\nConnection:\r\n\r\n";
http::server::request request;
http::server::request_parser::result_type rc = std::get<0>(reqParser.parse(request, rawRequest.begin(), rawRequest.end()));
EXPECT_EQ(rc, http::server::request_parser::bad);
}
TEST_F(RequestParserTests, ParseIncompleteRequest) {
std::string rawRequest = "GET / HTTP/1.1\r\nConnection: keep-alive\r\n";
http::server::request request;
http::server::request_parser::result_type rc = std::get<0>(reqParser.parse(request, rawRequest.begin(), rawRequest.end()));
EXPECT_EQ(rc, http::server::request_parser::indeterminate);
}
|
4f4df472ff87f84a6f3deb8636a94e5fb51be027
|
3b9eed9a464c512f6a8b97491515e2707b71aa6a
|
/FOFReaderLib/FOFFiles/FOFMultiCube.h
|
1b7b54c12dfd1a0256a0ee4a84f7d1c95a6c4dec
|
[
"CECILL-B",
"LicenseRef-scancode-cecill-b-en"
] |
permissive
|
pasdeloup/FOFReaderLib
|
d2f5da474568b93e0513c1d5532d826e941430c9
|
33ba45cd60fa4f702b918512ec5e40fd048ef1f0
|
refs/heads/master
| 2020-12-24T16:24:07.712142
| 2016-03-16T09:34:18
| 2016-03-16T09:34:18
| 13,593,825
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,297
|
h
|
FOFMultiCube.h
|
/* ************************** FOFReaderLib ********************************** */
/*////////////////////////////////////////////////////////////////////////////*/
// PROJECT : FOFReaderLib
// TITLE : FOFMultiCube
// DESCRIPTION : FOF MultiCube file management
// AUTHOR(S) : Jean Pasdeloup (jean.pasdeloup@obspm.fr)
// CONTRIBUTIONS : [Jean Pasdeloup (2013)]
// LICENSE : CECILL-B License
/*////////////////////////////////////////////////////////////////////////////*/
/// \file FOFMultiCube.h
/// \brief FOF MultiCube file management
/// \author Jean Pasdeloup (jean.pasdeloup@obspm.fr)
/// \date 2013
/// \copyright CECILL-B License
/*////////////////////////////////////////////////////////////////////////////*/
#ifndef FOFMULTICUBE_H
#define FOFMULTICUBE_H
#include <vector>
#include "FOFCube.h"
#include "FOFFile.h"
class FOFMultiCube : protected FOFCube
{
public:
FOFMultiCube();
FOFMultiCube(std::string, int readParticles = READ_POS | READ_VEL);
FOFMultiCube(const FOFMultiCube& orig);
virtual ~FOFMultiCube();
// Getter
std::vector<FOFCube*> cubes() {return _cubes; }
// Enhanced getters
FOFCube *cubes(int i) {return _cubes[i]; }
int nCubes() {return _cubes.size(); }
// Overload of Cube to read multicube like a giant cube
long npart();
float boundaries(int i);
float minX(void) {return boundaries(0);}
float maxX(void) {return boundaries(1);}
float minY(void) {return boundaries(2);}
float maxY(void) {return boundaries(3);}
float minZ(void) {return boundaries(4);}
float maxZ(void) {return boundaries(5);}
void readMultiCubeFile(int readParticles = READ_POS | READ_VEL); // Check if dir and add
void addMultiCubeFile(std::string filename, int readParticles = READ_POS | READ_VEL); // Open file and add cube (not multi)
void divideNpart(int divider = 8); // Divide all cube npart
void npart(int npart); // Force npart globally (reduce proportionnaly for each cube)
protected:
std::vector<FOFCube*> _cubes;
float minBoundaries();
float maxBoundaries();
};
#endif /* FOFMULTICUBE_H */
|
be65bd8b1660d5c6bbdba7fce4c666fcce8f0e8b
|
f7979bcaa25a5b32f0916cc201cc72ea5595237c
|
/GameScreen.h
|
18110f0a789cbe7fd949edebb3ae880c44f89c8f
|
[] |
no_license
|
adrian-1066/Mario
|
6088cd5ea627a222394f09e5b6fd699cff826089
|
6d9ffa06a9fc500f00cdebad10a18a358fe0aeb7
|
refs/heads/main
| 2023-04-16T12:04:07.857523
| 2021-04-21T15:55:19
| 2021-04-21T15:55:19
| 360,217,836
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 334
|
h
|
GameScreen.h
|
#pragma once
#ifndef _GameScreen_H
#define _GameScreen_H
#include<SDL.h>
class GameScreen
{
protected:
SDL_Renderer* m_renderer;
private:
public:
GameScreen(SDL_Renderer* renderer);
~GameScreen();
virtual void Render();
virtual void Update(float deltaTime, SDL_Event e);
};
#endif // !_GameScreen_H
|
b92222fee6152ba5206d651c1cd7f7c508144bc5
|
da1bb93db9b11763011ec2eff0879c75940acb3c
|
/src/source.cpp
|
79afdee8fbcb725d08554bfcc44e783ae9e56b88
|
[] |
no_license
|
FeverDream12/SpellChecker
|
0883aacfdb8a5e6ab489918ff6c0c63bf36f48ab
|
52e12a533ed7a87dff1fe9ad91c1c02249c107d8
|
refs/heads/master
| 2021-04-10T10:53:15.953868
| 2021-01-04T10:25:16
| 2021-01-04T10:25:16
| 248,930,807
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,054
|
cpp
|
source.cpp
|
#include "textWork.h"
#include <fstream>
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
unordered_set<string> introduceDictionary(string filename)
{
unordered_set<string> Dictionary;
ifstream dictFile;
dictFile.open(filename);
if (dictFile.is_open()) {
string word;
while (dictFile >> word) {
lowerCase(word);
Dictionary.insert(word);
}
} else {
cout << "Can't open file: " << filename << endl;
}
return Dictionary;
}
string excessLetter(
string word, unordered_set<string> dict, string& text, int findHelper)
{
int wordSize = word.size();
string result;
for (int i = 0; i < wordSize; i++) {
string newWord = word;
newWord = newWord.erase(i, 1);
if (dict.find(newWord) != dict.end()) {
result = newWord;
int wordPosition = text.find(word, findHelper);
text.replace(
text.begin() + wordPosition,
text.begin() + wordPosition + word.size(),
result);
break;
}
}
return result;
}
string missingLetter(
string word, unordered_set<string> dict, string& text, int findHelper)
{
bool wordFinded = false;
string alphabet = "abcdefghijklmnopqrstuvwxyz";
string result;
string newWord = "_" + word;
int wordSize = newWord.size();
int alphabetSize = alphabet.size();
for (int i = 0; i < wordSize; i++) {
for (int j = 0; j < alphabetSize; j++) {
newWord[i] = alphabet[j];
if (dict.find(newWord) != dict.end()) {
result = newWord;
int wordPosition = text.find(word, findHelper);
text.replace(
text.begin() + wordPosition,
text.begin() + wordPosition + word.size(),
result);
wordFinded = true;
break;
}
}
if (wordFinded) {
break;
} else {
swap(newWord[i], newWord[i + 1]);
}
}
return result;
}
string swapLetters(
string word, unordered_set<string> dict, string& text, int findHelper)
{
int wordSize = word.size();
string result;
for (int i = 0; i < wordSize; i++) {
string newWord = word;
swap(newWord[i], newWord[i + 1]);
if (dict.find(newWord) != dict.end()) {
result = newWord;
int wordPosition = text.find(word, findHelper);
text.replace(
text.begin() + wordPosition,
text.begin() + wordPosition + word.size(),
result);
}
}
return result;
}
string wrongLetter(
string word, unordered_set<string> dict, string& text, int findHelper)
{
bool wordFinded = false;
string alphabet = "abcdefghijklmnopqrstuvwxyz";
string result;
string newWord = word;
int wordSize = newWord.size();
int alphabetSize = alphabet.size();
for (int i = 0; i < wordSize; i++) {
newWord = word;
for (int j = 0; j < alphabetSize; j++) {
newWord[i] = alphabet[j];
if (dict.find(newWord) != dict.end()) {
result = newWord;
int wordPosition = text.find(word, findHelper);
text.replace(
text.begin() + wordPosition,
text.begin() + wordPosition + word.size(),
result);
wordFinded = true;
break;
}
}
if (wordFinded) {
break;
}
}
return result;
}
string checkText(string filename, unordered_set<string> dict, string& text)
{
int pos = 0;
ifstream read;
string wordContainer;
read.open(filename);
if (read.is_open()) {
string word;
while (read >> word) {
lowerCase(word);
cout << word;
if (dict.find(word) != dict.end()) {
cout << "\033[1;32m -> correct word \033[0m\n";
} else {
wordContainer = swapLetters(word, dict, text, pos);
if (wordContainer.empty()) {
wordContainer = excessLetter(word, dict, text, pos);
if (wordContainer.empty()) {
wordContainer = missingLetter(word, dict, text, pos);
if (wordContainer.empty()) {
wordContainer = wrongLetter(word, dict, text, pos);
if (wordContainer.empty()) {
cout << "\033[1;31m -> unknown or\033[0m"
<< "\033[1;31m nonexisted word \033[0m\n";
} else {
cout << "\033[1;33m -> uncorrect word, \033[0m"
<< "\033[1;33mmaybe you mean -->> \033[0m"
<< wordContainer << endl;
}
} else {
cout << "\033[1;33m -> uncorrect word, \033[0m"
<< "\033[1;33mmaybe you mean -->> \033[0m"
<< wordContainer << endl;
}
} else {
pos--;
cout << "\033[1;33m -> uncorrect word, \033[0m"
<< "\033[1;33mmaybe you mean -->> \033[0m"
<< wordContainer << endl;
}
} else {
cout << "\033[1;33m -> uncorrect word, \033[0m"
<< "\033[1;33mmaybe you mean -->> \033[0m"
<< wordContainer << endl;
}
}
pos += word.size() + 1;
}
} else {
cout << "Could not open file : " << filename << endl;
}
return text;
}
|
a70f88d4de62c46c76cf777671287e279f406a6d
|
d815a285ede3ffd3ca1a431ec14410a613cadcdc
|
/CauTrucDuLieu&GiaiThuat/BTLon/BTLon_ThamKhao/Nhóm 13/Source/Dictionary/Header.h
|
3399bbb0e57e2e15e0a6c67825bf9aabe5f210cb
|
[] |
no_license
|
PTson2207/HK1_Year-2
|
dbb893ca844957ac001a20683a097f98afb8ea92
|
d39a18c4ec7f530be1b85c327e0e29dd64bda0eb
|
refs/heads/master
| 2023-02-16T11:24:47.449700
| 2021-01-19T15:37:08
| 2021-01-19T15:37:08
| 301,892,152
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,491
|
h
|
Header.h
|
#pragma once
#include <conio.h>
#include <string>
#include <iostream>
#include <conio.h>
#include <fcntl.h>
#include <io.h>
#include <locale>
#include <codecvt>
#include <fstream>
#include <Windows.h>
#include <sstream>
#include <stdio.h>
#include <thread>
#include<stdlib.h>
const HANDLE StdHandel = GetStdHandle(STD_OUTPUT_HANDLE);
struct COLOR
{
int Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Yellow = 6,
White = 7;
};
static int Light = 8;
COLOR Color;
const int Default_FontColor = 15, Default_BackgroundFontColor = 0;
void DefaultColor()
{
SetConsoleTextAttribute(StdHandel, (Default_BackgroundFontColor << 4)| Default_FontColor);
}
int GetID()
{
static int ID = 1;
return ++ID;
}
int ID_Huy = 0;
/*void Set_FontSize(int FontSize)
{
CONSOLE_FONT_INFOEX info = { 0 };
info.cbSize = sizeof(info);
info.dwFontSize.Y = FontSize;
info.FontWeight = FW_NORMAL;
wcscpy(info.FaceName, L"Consolas");
SetCurrentConsoleFontEx(StdHandel, NULL, &info);
}*/
using namespace std; // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
const char firstString = 120, lastString = 121, firstFile = 122, lastFile = 123, newString = 124;
locale loc(locale(), new codecvt_utf8<wchar_t>);
int CodeTable_length = 231;
wchar_t* CodeTable = new wchar_t[CodeTable_length];
wchar_t Decode_value(char value)
{
return CodeTable[value + 126];
}
char Encode_value(wchar_t value)
{
for (int i = 0; i < CodeTable_length; i++)
{
if (value == CodeTable[i])
{
i = i - 126;
return i;
}
}
return -126;
}
void Load_CodeTable()
{
wifstream CodeTableFile(L"P:/Project Tu de AV/data/CodeTable.dictionary");
if (!CodeTableFile)
{
wcout << L"Loi khong the doc file";
}
else
{
wstring StringCodeTable;
CodeTableFile.imbue(loc);
while (!CodeTableFile.eof())
{
getline(CodeTableFile, StringCodeTable);
}
CodeTableFile.close();
if (StringCodeTable.length() == 229)
{
CodeTable[0] = NULL;
CodeTable[1] = 13;
for (int i = 2; i < 231; i++)
{
CodeTable[i] = StringCodeTable[i - 2];
}
}
}
}
//---------------------------------
struct PATHS_
{
/*path_av_dictionary = L"data/root/av.dictionary";
path_help_dictionary = L"data/root/help.dictionary";
*path_va_dictionary = L"data/root/va.dictionary";
*path_user_av_dictionary = L"data/user/av.dictionary";
*path_user_Set = L"data/user/set.setting";*/
wstring
//av = L"P:/Project/Dictionary/data/root/av.dictionary",
av = L"data/root/av.dictionary",
help = L"",
//user_av = L"P:/Project/Dictionary/data/user/av.dictionary",
user_av = L"data/user/av.dictionary",
user_set = L"P:/Project/Dictionary/data/user/set";
}; typedef struct PATHS_* Paths_;
//const Path_ Path;
const PATHS_ paths;
wstring
*path_av_dictionary,
*path_help_dictionary,
*path_va_dictionary,
*path_user_av_dictionary,
*path_user_Set;
//------title-----------------------
//----------------------------------
void LoadFileHelp()
{
wifstream fin(paths.help);
wstring str;
if (!fin)
{
MessageBoxW(NULL, ( LPCWSTR )L"Dữ liệu phần mềm bị hỏng !\nThoát !",
( LPCWSTR )L"Dictionary thông báo",
MB_OK | MB_ICONERROR);
quick_exit(0);
}
else
{
system("cls&color 2");
while (!fin.eof())
{
getline(fin, str);
wcout << str;
}
fin.close();
while (true)
{
if (_getch() == 27) quick_exit(0);
else
MessageBoxW(NULL, ( LPCWSTR )L"Nhấn phím ESC hoặc click vào [x] để thoát !",
( LPCWSTR )L"Dictionary thông báo",
MB_OK | MB_ICONINFORMATION);
}
}
}
COORD *Toa_Do_Select;
CONSOLE_CURSOR_INFO* StdCursorInfo;
RECT Rect_Desktop;
int width_console = 1000,
height_console = 500;
void EvenSlect(COORD* ToaDoSelect_)
{
CONSOLE_SELECTION_INFO ToaDoSelect;
HWND consoleWD = GetConsoleWindow();
RECT RectConsoleWD;
while (true)
{
GetConsoleSelectionInfo(&ToaDoSelect);
if (ToaDoSelect.dwSelectionAnchor.X != 0 || ToaDoSelect.dwSelectionAnchor.Y != 0)
{
ToaDoSelect_->X = ToaDoSelect.dwSelectionAnchor.X;
ToaDoSelect_->Y = ToaDoSelect.dwSelectionAnchor.Y;
Sleep(50);
keybd_event(0, NULL, NULL, NULL);
keybd_event(13, NULL, NULL, NULL);
}
GetWindowRect(consoleWD, &RectConsoleWD);
if (RectConsoleWD.right != width_console || RectConsoleWD.bottom != height_console)
{
consoleWD = GetConsoleWindow();
MoveWindow(consoleWD, RectConsoleWD.left, RectConsoleWD.top, width_console, height_console, true);
}
Sleep(50);
}
}
|
05ad4c843dedb6c39d646ff27ae7baa79d6daf0f
|
d997a68f0193e7992779b076ee1d1b212b2b6738
|
/Algorithms and data structure/SIS/sis.cpp
|
80660589e7654596ae6d70579cbafb995f0fe089
|
[] |
no_license
|
alikhan880/ADS
|
f76508be3f9715da53cb14c45884bf6e8c3583ad
|
c28a844ff5e5cfcc5247730dc086bec413a299b3
|
refs/heads/master
| 2021-01-13T07:57:42.402934
| 2017-05-31T06:43:11
| 2017-05-31T06:43:11
| 71,996,809
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,307
|
cpp
|
sis.cpp
|
#include <iostream>
#include <vector>
using namespace std;
bool found = false, added = false;
struct Node{
public:
string name;
Node *parent;
vector<Node*> children;
Node(string name){
this->name = name;
parent = NULL;
}
};
struct GenTree{
public:
Node *root;
vector<Node*> roots;
GenTree(){
root = NULL;
}
void add(string father, string son){
if(roots.empty()){
Node *f = new Node(father);
Node *s = new Node(son);
s->parent = f;
f->children.push_back(s);
root = f;
roots.push_back(root);
}
else{
for(int i=0; i<roots.size(); i++){
Node *temp = roots[i];
addEx(temp, father, son);
}
if(!added){
Node *fnode = new Node(father);
Node *snode = new Node(son);
snode->parent = fnode;
fnode->children.push_back(snode);
roots.push_back(fnode);
}
}
}
void addEx(Node* node, string father, string son){
added = false;
if(node->name == father){
found = false;
for(int i=0; i<roots.size(); i++){
if(roots[i]->name == son){
node->children.push_back(roots[i]);
roots[i]->parent = node;
roots.erase(roots.begin() + i);
found = true;
added = true;
break;
}
}
if(!found){
Node *snode = new Node(son);
snode->parent = node;
node->children.push_back(snode);
added = true;
}
}
else{
for(int i=0; i<node->children.size(); i++){
addEx(node->children[i], father, son);
}
}
}
Node* find(string name){
for(int i=0; i<roots.size(); i++){
if(roots[i]->name == name){
return roots[i];
}
}
return NULL;
}
void showSons(Node *p){
for(int i=0; i<p->children.size(); i++){
cout<<p->children[i]->name<<" ";
}
cout<<endl;
}
void showGrandSons(Node *p){
for(int i=0; i<p->children.size(); i++){
for(int j=0; j<p->children[i]->children.size(); j++){
cout<<p->children[i]->children[j]->name<<" ";
}
cout<<endl;
}
}
bool checkEquality(string name1, string name2){
Node *node1 = find(name1);
Node *node2 = find(name2);
if(node1->parent != NULL){
while(node1->parent != NULL){
node1 = node1->parent;
}
}
if(node2->parent != NULL){
while(node2->parent != NULL){
node2 = node2->parent;
}
}
if(node1 == node2){
return true;
}
return false;
}
// Node* findAncestor(string name){
// Node *temp = find(name);
// while(temp->parent != NULL){
// temp = temp->parent;
// }
// return temp;
// }
};
int main(){
freopen("sis.in", "r", stdin);
// freopen(".out", "w", stdout);
GenTree *tree = new GenTree();
int n;
string father, son, space;
cin>>n;
for(int i=0; i<n; i++){
cin>>father>>space>>son;
tree->add(father, son);
cout<<tree->roots.size()<<endl;
}
cout<<"1-Find all childrens"<<endl;
cout<<"2-Find all grandsons"<<endl;
cout<<"3-Find similarity"<<endl;
int choice;
cin>>choice;
if(choice == 1){
string name;
cin>>name;
tree->showSons(tree->find(name));
}
else if(choice == 2){
string name;
cin>>name;
tree->showGrandSons(tree->find(name));
}
else if(choice == 3){
string name1, name2;
cin>>name1>>name2;
if(tree->checkEquality(name1, name2)){
// cout<<"They have common ancestor "<<tree->findAncestor(name1)->name<<endl;
}
}
fclose(stdin);
// fclose(stdout);
return 0;
}
|
c4f802ba0f3596cff80597e216577f4e393bc059
|
8be023f90d9a18f4917af4bba8fb31230df3df2a
|
/SigLog_Lib/snmp_auth.cpp
|
7c3fc6e532392ee01a84602fe9e497214bc6ebea
|
[] |
no_license
|
duniansampa/SigLog
|
d6dba1c0e851e1c8d3aef3af4bb85b4d038ab9c9
|
3dae0e42a36ebc5dca46fb044d3b1d40152ec786
|
refs/heads/master
| 2021-01-10T12:25:17.511236
| 2016-03-12T18:38:19
| 2016-03-12T18:38:19
| 44,571,851
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,125
|
cpp
|
snmp_auth.cpp
|
/*
* snmp_auth.c
*
* Community name parse/build routines.
*/
/**********************************************************************
Copyright 1988, 1989, 1991, 1992 by Carnegie Mellon University
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of CMU not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
CMU DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
CMU BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
******************************************************************/
#include <siglog/net-snmp-config.h>
#ifdef KINETICS
#include "gw.h"
#include "fp4/cmdmacro.h"
#endif
#include <stdio.h>
#if HAVE_STDLIB_H
#include <stdlib.h>
#endif
#if HAVE_STRING_H
#include <string.h>
#else
#include <strings.h>
#endif
#include <sys/types.h>
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#if HAVE_SYS_SELECT_H
#include <sys/select.h>
#endif
#if HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#if HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if HAVE_DMALLOC_H
#include <dmalloc.h>
#endif
#ifdef vms
#include <in.h>
#endif
#include <siglog/types.h>
#include <siglog/output_api.h>
#include <siglog/utilities.h>
#include <siglog/library/asn1.h>
#include <siglog/library/snmp_api.h>
#include <siglog/library/mib.h>
#include <siglog/library/md5.h>
#include <siglog/library/scapi.h>
/*
* Globals.
*/
#if !defined(NETSNMP_DISABLE_SNMPV1) || !defined(NETSNMP_DISABLE_SNMPV2C)
/*******************************************************************-o-******
* snmp_comstr_parse
*
* Parameters:
* *data (I) Message.
* *length (I/O) Bytes left in message.
* *psid (O) Community string.
* *slen (O) Length of community string.
* *version (O) Message version.
*
* Returns:
* Pointer to the remainder of data.
*
*
* Parse the header of a community string-based message such as that found
* in SNMPv1 and SNMPv2c.
*/
u_char *
snmp_comstr_parse(u_char * data,
size_t * length,
u_char * psid, size_t * slen, long *version)
{
u_char type;
long ver;
size_t origlen = *slen;
/*
* Message is an ASN.1 SEQUENCE.
*/
data = asn_parse_sequence(data, length, &type,
(ASN_SEQUENCE | ASN_CONSTRUCTOR),
"auth message");
if (data == NULL) {
return NULL;
}
/*
* First field is the version.
*/
DEBUGDUMPHEADER("recv", "SNMP version");
data = asn_parse_int(data, length, &type, &ver, sizeof(ver));
DEBUGINDENTLESS();
*version = ver;
if (data == NULL) {
ERROR_MSG("bad parse of version");
return NULL;
}
/*
* second field is the community string for SNMPv1 & SNMPv2c
*/
DEBUGDUMPHEADER("recv", "community string");
data = asn_parse_string(data, length, &type, psid, slen);
DEBUGINDENTLESS();
if (data == NULL) {
ERROR_MSG("bad parse of community");
return NULL;
}
psid[SNMP_MIN(*slen, origlen - 1)] = '\0';
return (u_char *) data;
} /* end snmp_comstr_parse() */
/*******************************************************************-o-******
* snmp_comstr_build
*
* Parameters:
* *data
* *length
* *psid
* *slen
* *version
* messagelen
*
* Returns:
* Pointer into 'data' after built section.
*
*
* Build the header of a community string-based message such as that found
* in SNMPv1 and SNMPv2c.
*
* NOTE: The length of the message will have to be inserted later,
* if not known.
*
* NOTE: Version is an 'int'. (CMU had it as a long, but was passing
* in a *int. Grrr.) Assign version to verfix and pass in
* that to asn_build_int instead which expects a long. -- WH
*/
u_char *
snmp_comstr_build(u_char * data,
size_t * length,
u_char * psid,
size_t * slen, long *version, size_t messagelen)
{
long verfix = *version;
u_char *h1 = data;
u_char *h1e;
size_t hlength = *length;
/*
* Build the the message wrapper (note length will be inserted later).
*/
data =
asn_build_sequence(data, length,
(u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), 0);
if (data == NULL) {
return NULL;
}
h1e = data;
/*
* Store the version field.
*/
data = asn_build_int(data, length,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_INTEGER), &verfix, sizeof(verfix));
if (data == NULL) {
return NULL;
}
/*
* Store the community string.
*/
data = asn_build_string(data, length,
(u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE |
ASN_OCTET_STR), psid,
*(u_char *) slen);
if (data == NULL) {
return NULL;
}
/*
* Insert length.
*/
asn_build_sequence(h1, &hlength,
(u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR),
data - h1e + messagelen);
return data;
} /* end snmp_comstr_build() */
#endif /* support for community based SNMP */
|
93ee77a03f2efd255c6879e45b633f275458b7bb
|
da677987cf0319f09f6c192d5f22caf4eaf5f73c
|
/L10/t3.cpp
|
7035a78ef8e4fa264c909d351f9b4f36a6e43e16
|
[] |
no_license
|
DRJ31/COMP1013-SP
|
bc6f0a1da19fc658f7023734ada27d7f1e7a03e0
|
e703dd81acba80beedd5401217f90b27a3c39a49
|
refs/heads/master
| 2021-03-22T01:04:23.247467
| 2017-12-19T03:57:02
| 2017-12-19T03:57:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 425
|
cpp
|
t3.cpp
|
#include <stdio.h>
char* stringCopy(char *dest, char *res);
int main() {
char str1[20], str2[20];
scanf("%s", str1);
stringCopy(str2, str1);
puts(str2);
return 0;
}
char* stringCopy(char *dest, char *res) {
//Another way to solve this Problem
// while ((*dest++ = *res++) != '\0');
while (true){
*dest = *res;
if (*res == '\0')
break;
*dest++;
*res++;
}
return dest;
}
|
960fd7494accde619312a8d48c88ef740c2447d1
|
e4c7e4941c4d403f70026ebdf5172a62eabba3da
|
/filehandler.h
|
fc1b5fd6aad67663cacd9e1f6f8de649fe9eb4c7
|
[] |
no_license
|
BenSliwa/AgentVisualization
|
34633f631afec9b51adb162e3a74b5bee6e513c5
|
2a1040462218999d67312de6c81304c6a6e3aaaf
|
refs/heads/master
| 2020-04-15T05:01:34.189599
| 2016-08-18T05:36:24
| 2016-08-18T05:36:24
| 61,936,318
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 335
|
h
|
filehandler.h
|
#ifndef FILEHANDLER_H
#define FILEHANDLER_H
#include <QObject>
#include <QDebug>
#include <QStringList>
#include "Mobility/csvmobilitydataaccess.h"
class FileHandler : public QObject
{
Q_OBJECT
public:
FileHandler(QObject *_parent = 0);
static QStringList readLines(const QString &_path);
};
#endif // FILEHANDLER_H
|
4c69445d5fe9dd501e0d2c4e4a9a884368e4b3ce
|
63bc247adf9bce867fb35583854d7ab0bb8a8714
|
/Responses/camerasnapfree_command_response.h
|
969edbf46d8884e39325f9e6da320b986b08c418
|
[] |
no_license
|
yanganok/SITSNEW
|
2848f645e70e88aec344bf4eb6303b5a777f89e1
|
67aa4039d1afa6ac305948ec763e6a62638ca86c
|
refs/heads/master
| 2022-12-13T21:02:58.031548
| 2020-08-31T00:43:38
| 2020-08-31T00:43:38
| 290,928,033
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 311
|
h
|
camerasnapfree_command_response.h
|
#ifndef CAMERASNAPFREE_COMMAND_RESPONSE_H
#define CAMERASNAPFREE_COMMAND_RESPONSE_H
#include "response.h"
class CameraSnapFree_Command_Response : public Response
{
public:
CameraSnapFree_Command_Response();
};
Q_DECLARE_METATYPE(CameraSnapFree_Command_Response)
#endif // CAMERASNAPFREE_COMMAND_RESPONSE_H
|
e1166126c103ad94842bddf45ebee9d4e83ade11
|
0e7b9be29357c36dbb3a61094d567e179d7fb9a6
|
/Arduino-Code/Tests/mega_pin_test/mega_pin_test.ino
|
ef62540e62d0135c514b46a779803a93466d392a
|
[] |
no_license
|
SulaimanKsj/Capstone-DogDrone
|
78a20cd15d957c03666985c58d0867d1f57b9d60
|
5d4f07cd5ab2ee51de0354e20b35a00cb726ce0a
|
refs/heads/master
| 2021-04-05T13:19:23.601384
| 2020-03-16T17:53:26
| 2020-03-16T17:53:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,940
|
ino
|
mega_pin_test.ino
|
//External libraries
#include "arduino.h"
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_FXAS21002C.h>
#include <Adafruit_FXOS8700.h>
//PIN MAP
//Battery voltage
#define batteryMotorPin A1
#define batteryCompPin A3
//Xbee breakout
//Serial3
#define rssiInPin A0
#define xbeeRX 15
#define xbeeTX 14
//IMU
#define imuSCL 21
#define imuSDA 20
//Ultrasonic
#define sonarEchoPin 7
#define sonarTrig 6
//Rpi serial2
#define piRX 17
#define piTX 16
//Motor Driver
#define motorOp1 12
#define motorOp2 13
#define motorFrontA_PWM 9
#define motorFrontB_PWM 8
#define motorRearA_PWM 11
#define motorRearB_PWM 10
//Motor Encoders
#define motorFrontA_Encoder 3
#define motorFrontB_Encoder 2
#define motorRearA_Encoder 19
#define motorRearB_Encoder 18
//Servo pins
//VARIABLES
//global variables for main
byte blinkState = 0;
byte echoFlag = 0;
float batCV = 0;
float batMV = 0;
//IMU objects
Adafruit_FXAS21002C gyro;
Adafruit_FXOS8700 accelmag;
sensors_event_t gyro_event;
sensors_event_t accel_event;
sensors_event_t mag_event;
void setup() {
//Pin setup
pinMode(motorFrontA_PWM, OUTPUT);
pinMode(motorFrontB_PWM, OUTPUT);
pinMode(motorRearA_PWM, OUTPUT);
pinMode(motorRearB_PWM, OUTPUT);
// put your setup code here, to run once:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
while ((Serial.available() <= 0)) {
Serial.print('A'); // send a capital A
delay(500);
}
Serial.println(' ');
Serial2.begin(9600);
Serial3.begin(9600);
digitalWrite(motorOp1, HIGH);
digitalWrite(motorOp2, LOW);
analogWrite(motorFrontA_PWM, 155);
analogWrite(motorFrontB_PWM, 155);
analogWrite(motorRearA_PWM, 155);
analogWrite(motorRearB_PWM, 155);
digitalWrite(sonarTrig, LOW);
}
void loop() {
// put your main code here, to run repeatedly:
if(!gyro.begin()){
/* There was a problem detecting the gyro ... check your connections */
Serial.println(F("Ooops, no gyro detected ... Check your wiring!"));
}
if(!accelmag.begin(ACCEL_RANGE_4G)){
Serial.println(F("Ooops, no FXOS8700 detected ... Check your wiring!"));
}
Serial.println("Computer battery voltage: " + String(5.0*analogRead(batteryCompPin)/1024.0));
delay(10);
Serial.println("Motor battery voltage: " + String(5.0*analogRead(batteryMotorPin)/1024.0));
delay(10);
Serial.println("RSSI voltage: " + String(5.0*analogRead(rssiInPin)/1024.0));
//Sonar
Serial.println("sonar echo: " + String(digitalRead(sonarEchoPin)));
digitalWrite(sonarTrig, HIGH);
delay(100);
digitalWrite(sonarTrig, LOW);
Serial.println("sonar echo: " + String(digitalRead(sonarEchoPin)));
Serial.println("Echo duration: " + String(pulseIn(sonarEchoPin, HIGH)));
delay(1000);
}
|
615f4163dde4097b5d28bb872d84251649abebfe
|
05975df9f354e16e4dacdf07a231c72b6066e825
|
/Castlevania/HUD.cpp
|
226aca7b813a9118a8fce03c2aad7c41d8c48adc
|
[] |
no_license
|
PhanVinhLong/GameDevIntro
|
d55ea4ecb17913f4f270c8a43386e015b86e53b8
|
16138b495467730e33937dcfbc741657c563f0c0
|
refs/heads/master
| 2020-03-29T03:55:49.210954
| 2019-01-05T12:08:20
| 2019-01-05T12:08:20
| 149,507,531
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,886
|
cpp
|
HUD.cpp
|
#define _CRT_SECURE_NO_WARNINGS
#include "HUD.h"
CHUD* CHUD::__instance;
CHUD::CHUD()
{
player = CSimon::GetInstance();
this->texBackground = CTextures::GetInstance()->Get(ID_TEX_HUD_BG);
this->texHealth = CTextures::GetInstance()->Get(ID_TEX_HEALTH);
text = CText::GetInstance();
for (int i = 0; i < 3; i++)
listHealth.insert(pair<int, RECT>(i, { 5 * i, 0, 5 * (i + 1), 8 }));
enemyHealth = 16;
}
void CHUD::DrawHealth(int id, D3DXVECTOR2 position)
{
RECT sourceRect = listHealth[id];
CGame::GetInstance()->Draw(position.x, position.y, texHealth, sourceRect.left, sourceRect.top, sourceRect.right, sourceRect.bottom);
}
CHUD::~CHUD()
{
}
char* IntToChar(int value, int len = 10)
{
char* c = new char[len + 1];
c[len] = '\0';
for (int i = len - 1; i >= 0; i--)
{
c[i] = value % 10 + 48;
value = value / 10;
}
return c;
}
void CHUD::Draw(D3DXVECTOR2 position)
{
CGame::GetInstance()->Draw(0, 0, texBackground, 0, 0, 256, 40);
// scores
text->DrawString("SCORE-", { 1,3 });
text->DrawString(IntToChar(player->GetScore(), 6), { 49, 3 });
// time
text->DrawString("TIME", { 105,3 });
text->DrawString(IntToChar(player->GetTime(), 3), { 141, 3 });
// state
text->DrawString("STAGE", { 181,3 });
text->DrawString("01", { 225, 3 });
// player's heart
text->DrawString(IntToChar(player->GetHeart(), 2), { 205, 16 });
// player's health
text->DrawString("PLAYER", { 1,3 + 10 });
for (int i = 0; i < SIMON_MAX_HEALTH; i++)
{
int tmpId = i < player->GetHealth() ? 0 : 1;
DrawHealth(tmpId, { float(55 + i * 5), 13 });
}
// enemy's health
text->DrawString("ENEMY", { 1,3 + 20 });
for (int i = 0; i < 16; i++)
{
int tmpId = i < enemyHealth ? 2 : 1;
DrawHealth(tmpId, { float(55 + i * 5), 24 });
}
// item
GetItemSprite()->Draw(165, 31);
// multi shoot
GetMultiShootSprite()->Draw(230, 32);
// player's life
text->DrawString(IntToChar(player->GetLife(), 2), { 205, 25 });
}
CHUD * CHUD::GetInstance()
{
if (__instance == NULL) __instance = new CHUD();
return __instance;
}
LPSPRITE CHUD::GetItemSprite()
{
int spriteId;
int itemId = player->GetSubWeaponID();
switch (itemId)
{
case ID_SUBWEAPON_DAGGER:
spriteId = 12003;
break;
case ID_SUBWEAPON_AXE:
spriteId = 12011;
break;
case ID_SUBWEAPON_HOLY_WATER:
spriteId = 12020;
break;
case ID_SUBWEAPON_BOOMERANG:
spriteId = 12039;
break;
case ID_SUBWEAPON_STOPWATCH:
spriteId = 12007;
break;
default:
spriteId = 0;
break;
}
return CSprites::GetInstance()->Get(spriteId);
}
LPSPRITE CHUD::GetMultiShootSprite()
{
int spriteId;
int multiShootLevel = player->GetMultiShootLevel();
switch (multiShootLevel)
{
case 2:
spriteId = 12050;
break;
case 3:
spriteId = 12051;
break;
default:
spriteId = 0;
break;
}
return CSprites::GetInstance()->Get(spriteId);
}
void CHUD::SetEnemyHealth(int health)
{
enemyHealth = health;
}
|
4f507ca1342700d8d9f8bc5f3e0e630bff7f9951
|
b7f7756ee79768bcdff05ac96575f25ca975cd79
|
/Rotate List/Rotate List.cpp
|
f53654fb5b6660f3e3f49b6ff3535d973f5851c3
|
[] |
no_license
|
suwei111333/BaseInterviewCode
|
e8a3c3b4e283676d0b438a5d3276c73ac9877343
|
205089eda593add518be518176e15d8f5aae37f8
|
refs/heads/master
| 2021-01-10T19:04:41.076863
| 2013-11-05T08:41:04
| 2013-11-05T08:41:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 777
|
cpp
|
Rotate List.cpp
|
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(!head || k == 0) return head;
int Listlen = 1;
ListNode* LastNode = head;
while(LastNode->next)
{
Listlen ++;
LastNode = LastNode->next;
}
if(Listlen == 1 || k % Listlen == 0) return head;
k = k% Listlen;
k = Listlen - k;
while(k --)
{
ListNode* CurNode = head;
head = head->next;
LastNode->next = CurNode;
LastNode = CurNode;
CurNode->next = NULL;
}
return head;
}
};
int main()
{
return 0;
}
|
22ddda43da58b2aac678164b979d899bb5a428d6
|
3310dca4d36ff34f1aede0088fe15053b18c688b
|
/clickhouse/columns/factory.cpp
|
aeacdabcea7bb40520cc305ab803075d67ad7b86
|
[
"Apache-2.0"
] |
permissive
|
ClickHouse/clickhouse-cpp
|
6448fabd21db31960b47c18e3c5afd0a41b804d7
|
a133b50db0160f4e2b1e0288a99f123ae76793b7
|
refs/heads/master
| 2023-09-03T18:08:01.833017
| 2023-08-02T11:10:40
| 2023-08-02T11:10:40
| 208,047,461
| 258
| 163
|
Apache-2.0
| 2023-09-14T18:43:33
| 2019-09-12T12:35:34
|
C++
|
UTF-8
|
C++
| false
| false
| 9,171
|
cpp
|
factory.cpp
|
#include "factory.h"
#include "array.h"
#include "date.h"
#include "decimal.h"
#include "enum.h"
#include "geo.h"
#include "ip4.h"
#include "ip6.h"
#include "lowcardinality.h"
#include "lowcardinalityadaptor.h"
#include "map.h"
#include "nothing.h"
#include "nullable.h"
#include "numeric.h"
#include "string.h"
#include "tuple.h"
#include "uuid.h"
#include "../types/type_parser.h"
#include "../exceptions.h"
#include <stdexcept>
#include <string>
namespace clickhouse {
namespace {
// Like Python's list's []:
// * 0 - first element
// * 1 - second element
// * -1 - last element
// * -2 - one before last, etc.
const auto& GetASTChildElement(const TypeAst & ast, int position) {
if (static_cast<size_t>(abs(position)) >= ast.elements.size())
throw ValidationError("AST child element index out of bounds: " + std::to_string(position));
if (position < 0)
position = static_cast<int>(ast.elements.size() + position);
return ast.elements[static_cast<size_t>(position)];
}
static ColumnRef CreateTerminalColumn(const TypeAst& ast) {
switch (ast.code) {
case Type::Void:
return std::make_shared<ColumnNothing>();
case Type::UInt8:
return std::make_shared<ColumnUInt8>();
case Type::UInt16:
return std::make_shared<ColumnUInt16>();
case Type::UInt32:
return std::make_shared<ColumnUInt32>();
case Type::UInt64:
return std::make_shared<ColumnUInt64>();
case Type::Int8:
return std::make_shared<ColumnInt8>();
case Type::Int16:
return std::make_shared<ColumnInt16>();
case Type::Int32:
return std::make_shared<ColumnInt32>();
case Type::Int64:
return std::make_shared<ColumnInt64>();
case Type::Int128:
return std::make_shared<ColumnInt128>();
case Type::Float32:
return std::make_shared<ColumnFloat32>();
case Type::Float64:
return std::make_shared<ColumnFloat64>();
case Type::Decimal:
return std::make_shared<ColumnDecimal>(GetASTChildElement(ast, 0).value, GetASTChildElement(ast, -1).value);
case Type::Decimal32:
return std::make_shared<ColumnDecimal>(9, GetASTChildElement(ast, 0).value);
case Type::Decimal64:
return std::make_shared<ColumnDecimal>(18, GetASTChildElement(ast, 0).value);
case Type::Decimal128:
return std::make_shared<ColumnDecimal>(38, GetASTChildElement(ast, 0).value);
case Type::String:
return std::make_shared<ColumnString>();
case Type::FixedString:
return std::make_shared<ColumnFixedString>(GetASTChildElement(ast, 0).value);
case Type::DateTime:
if (ast.elements.empty()) {
return std::make_shared<ColumnDateTime>();
} else {
return std::make_shared<ColumnDateTime>(GetASTChildElement(ast, 0).value_string);
}
case Type::DateTime64:
if (ast.elements.empty()) {
return nullptr;
}
if (ast.elements.size() == 1) {
return std::make_shared<ColumnDateTime64>(ast.elements[0].value);
} else {
return std::make_shared<ColumnDateTime64>(ast.elements[0].value, ast.elements[1].value_string);
}
case Type::Date:
return std::make_shared<ColumnDate>();
case Type::Date32:
return std::make_shared<ColumnDate32>();
case Type::IPv4:
return std::make_shared<ColumnIPv4>();
case Type::IPv6:
return std::make_shared<ColumnIPv6>();
case Type::UUID:
return std::make_shared<ColumnUUID>();
case Type::Point:
return std::make_shared<ColumnPoint>();
case Type::Ring:
return std::make_shared<ColumnRing>();
case Type::Polygon:
return std::make_shared<ColumnPolygon>();
case Type::MultiPolygon:
return std::make_shared<ColumnMultiPolygon>();
default:
return nullptr;
}
}
static ColumnRef CreateColumnFromAst(const TypeAst& ast, CreateColumnByTypeSettings settings) {
switch (ast.meta) {
case TypeAst::Array: {
return std::make_shared<ColumnArray>(
CreateColumnFromAst(GetASTChildElement(ast, 0), settings)
);
}
case TypeAst::Nullable: {
return std::make_shared<ColumnNullable>(
CreateColumnFromAst(GetASTChildElement(ast, 0), settings),
std::make_shared<ColumnUInt8>()
);
}
case TypeAst::Terminal: {
return CreateTerminalColumn(ast);
}
case TypeAst::Tuple: {
std::vector<ColumnRef> columns;
columns.reserve(ast.elements.size());
for (const auto& elem : ast.elements) {
if (auto col = CreateColumnFromAst(elem, settings)) {
columns.push_back(col);
} else {
return nullptr;
}
}
return std::make_shared<ColumnTuple>(columns);
}
case TypeAst::Enum: {
std::vector<Type::EnumItem> enum_items;
//ast.elements.size() minimum is 1.
if ((ast.elements.size() % 2) != 0) {
throw ValidationError(ast.name + " content is not correct");
}
enum_items.reserve(ast.elements.size() / 2);
for (size_t i = 0; i < ast.elements.size(); i += 2) {
enum_items.push_back(Type::EnumItem{
ast.elements[i].value_string,
static_cast<int16_t>(ast.elements[i + 1].value)
});
}
if (ast.code == Type::Enum8) {
return std::make_shared<ColumnEnum8>(
Type::CreateEnum8(enum_items)
);
} else if (ast.code == Type::Enum16) {
return std::make_shared<ColumnEnum16>(
Type::CreateEnum16(enum_items)
);
}
break;
}
case TypeAst::LowCardinality: {
const auto nested = GetASTChildElement(ast, 0);
if (settings.low_cardinality_as_wrapped_column) {
switch (nested.code) {
// TODO (nemkov): update this to maximize code reuse.
case Type::String:
return std::make_shared<LowCardinalitySerializationAdaptor<ColumnString>>();
case Type::FixedString:
return std::make_shared<LowCardinalitySerializationAdaptor<ColumnFixedString>>(GetASTChildElement(nested, 0).value);
case Type::Nullable:
throw UnimplementedError("LowCardinality(" + nested.name + ") is not supported with LowCardinalityAsWrappedColumn on");
default:
throw UnimplementedError("LowCardinality(" + nested.name + ") is not supported");
}
}
else {
switch (nested.code) {
// TODO (nemkov): update this to maximize code reuse.
case Type::String:
return std::make_shared<ColumnLowCardinalityT<ColumnString>>();
case Type::FixedString:
return std::make_shared<ColumnLowCardinalityT<ColumnFixedString>>(GetASTChildElement(nested, 0).value);
case Type::Nullable:
return std::make_shared<ColumnLowCardinality>(
std::make_shared<ColumnNullable>(
CreateColumnFromAst(GetASTChildElement(nested, 0), settings),
std::make_shared<ColumnUInt8>()
)
);
default:
throw UnimplementedError("LowCardinality(" + nested.name + ") is not supported");
}
}
}
case TypeAst::SimpleAggregateFunction: {
return CreateTerminalColumn(GetASTChildElement(ast, -1));
}
case TypeAst::Map: {
if (ast.elements.size() != 2) {
throw ValidationError(ast.name + " content is not correct");
}
std::vector<ColumnRef> columns;
columns.reserve(ast.elements.size());
for (const auto& elem : ast.elements) {
if (auto col = CreateColumnFromAst(elem, settings)) {
columns.push_back(col);
} else {
return nullptr;
}
}
return std::make_shared<ColumnMap>(
std::make_shared<ColumnArray>(
std::make_shared<ColumnTuple>(columns)));
}
case TypeAst::Assign:
case TypeAst::Null:
case TypeAst::Number:
case TypeAst::String:
break;
}
return nullptr;
}
} // namespace
ColumnRef CreateColumnByType(const std::string& type_name, CreateColumnByTypeSettings settings) {
auto ast = ParseTypeName(type_name);
if (ast != nullptr) {
return CreateColumnFromAst(*ast, settings);
}
return nullptr;
}
}
|
209fc2a0872c7609935fcd610663d3b6351cc50d
|
5fa0e0ba6cd719a856c6e479e90602dfb6bed4ff
|
/DigDug/DigDugStateDead.cpp
|
9d68ae9647bc0affd7b0aeece9538d173d882d56
|
[] |
no_license
|
Cem-Alagozlu/MyEngine
|
a853a2ff23e2dbd02c53e14f2e96605e74718666
|
b81ff77ca87266bcdfeccef577c72e54e04d4030
|
refs/heads/master
| 2022-01-10T18:39:49.902708
| 2019-05-26T21:13:15
| 2019-05-26T21:13:15
| 183,600,565
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,441
|
cpp
|
DigDugStateDead.cpp
|
#include "DigDugPCH.h"
#include "DigDugStateDead.h"
#include "GameObject.h"
#include "DigDugBlackboard.h"
#include "Player.h"
#include "PlayerData.h"
namespace cem
{
DigDugStateDead::DigDugStateDead()
{
}
DigDugStateDead::~DigDugStateDead()
{
}
void DigDugStateDead::Enter()
{
std::shared_ptr<GameObject> player = GetBlackboard<DigDugBlackboard>()->m_pPlayer.lock();
if (player)
{
std::dynamic_pointer_cast<Player>(player)->SetSpritesInvisible();
std::dynamic_pointer_cast<Player>(player)->GetPlayerSprites(Player::PlayerSprites::dead)->SetVisibility(true);
}
}
void DigDugStateDead::Exit()
{
PlayerData::GetInstance().AddLives(-1);
std::shared_ptr<GameObject> player = GetBlackboard<DigDugBlackboard>()->m_pPlayer.lock();
if (player)
{
std::dynamic_pointer_cast<Player>(player)->SetSpritesInvisible();
}
}
void DigDugStateDead::Update()
{
std::shared_ptr<GameObject> player = GetBlackboard<DigDugBlackboard>()->m_pPlayer.lock();
if (player)
{
auto sprite = player->GetComponent<SpriteComponent>();
GetBlackboard<DigDugBlackboard>()->m_Velocity = Vector2f{ 0.0f,0.0f };
if (sprite->HasEnded())
{
GetBlackboard<DigDugBlackboard>()->m_HasDied = false;
}
}
std::cout << "is dying bruh\n";
}
bool DigDugStateDead::CanTransition()
{
bool& isDead = GetBlackboard<DigDugBlackboard>()->m_HasDied;
if (isDead)
{
return true;
}
return false;
}
}
|
1b4938502c924e5c063865030d574675c35267fd
|
0a48f16abff32fe331a956c91278eb58de2e8a74
|
/include/estudiante.h
|
05b11a3df9e79e6d4b0d1db78c87a8f475a86f64
|
[] |
no_license
|
sserna1231/POSGSOFT
|
b0ee601392dffdfc18441b9184f02b26694f2134
|
1e595e25add96336abec0dfb75e5607cb7490d05
|
refs/heads/master
| 2023-03-24T19:16:40.415878
| 2021-03-24T06:19:51
| 2021-03-24T06:19:51
| 348,100,817
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 660
|
h
|
estudiante.h
|
#ifndef ESTUDIANTE_H
#define ESTUDIANTE_H
#ifndef EMPTY_ID
#define EMPTY_ID
static constexpr int empty_id = -1;
#endif
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
using std::string;
class Estudiante{
private:
string nombre;
int id;
string celular;
string email;
public:
Estudiante();
Estudiante( int );
Estudiante( string, int, string, string );
void llenarEstudiante();
void mostrarEstudiante();
int getId();
string getNombre();
void modificarEstudiante();
int mostrarOpciones();
void setId( int );
};
#endif
|
1631cd0240271f2b5ada0b67f838e3d235d77152
|
ef7e5f9f2528126b0ca5ae4ddc5dad63e9aa91b8
|
/LedStrips.h
|
ddd73e439c69e1340838ea6a71d27177935156be
|
[] |
no_license
|
michelkeijzers/SynthLedStrips
|
16b97ea18c42841568aef852019ed84639b581fb
|
3ca3d4bd15ef5b75d6eecb25efbfd13f3893584b
|
refs/heads/master
| 2023-05-14T01:43:39.935509
| 2021-06-09T21:23:56
| 2021-06-09T21:23:56
| 342,181,497
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 724
|
h
|
LedStrips.h
|
#pragma once
#include <stdlib.h>
#include "LedStrip.h"
#include "SynthLedStrips.h"
constexpr auto NR_OF_LED_STRIPS = 4;
constexpr auto NR_OF_KEYBOARD_1_FRONT_LEDS = 98;
constexpr auto NR_OF_KEYBOARD_1_BACK_LEDS = 125; //TODO
constexpr auto NR_OF_KEYBOARD_2_FRONT_LEDS = 178;
constexpr auto NR_OF_KEYBOARD_2_BACK_LEDS = 188; //TODO
class LedStrips
{
public:
enum ELocation
{
Keyboard1Front = 0,
Keyboard1Back = 1,
Keyboard2Front = 2,
Keyboard2Back = 3
};
LedStrips();
void Initialize();
void Process();
void On();
void Off();
bool IsOn();
LedStrip& GetLedStrip(uint8_t index);
private:
static const uint16_t MAX_CURRENT_IN_MILLI_AMP;
LedStrip _ledStrips[NR_OF_LED_STRIPS];
bool _on;
};
|
35f42c8aa4902dd82df2d7abd2cd1b51ad0d3215
|
ab8d5c1344ece514a61ae0f4646575d4028df548
|
/week12_Hash/hash.h
|
a35fa333ac162d81af4829734fb2e76808b38207
|
[] |
no_license
|
YuraVasiuk/Custom-Made-Data-Structures
|
e20262b3e3e43d1e4d61e441ffc237b3d88aa88b
|
032ea861280cf26f33ce76a2279e17eead5f0a49
|
refs/heads/master
| 2021-09-04T11:09:16.722965
| 2018-01-18T05:00:44
| 2018-01-18T05:00:44
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,295
|
h
|
hash.h
|
#include <list>
#include <string>
#include <assert.h>
using namespace std;
/****************************************
* HASH
* The parent template hash class
****************************************/
template <typename T>
class Hash
{
public:
// the constructors
Hash() : numBuckets(0), numElements(0), buckets(NULL) {}
Hash(int numBuckets) throw (const char *) ;
Hash(const Hash & rhs) throw (const char *) ;
// destructor
~Hash()
{
//if (numBuckets != 0)
//delete[] buckets;
}
// is the hash empty?
bool empty() const
{
if (numElements == 0)
return true;
else
return false;
}
// return the array's capacity
int capacity() const { return numBuckets; }
// how many elements does the hash have?
int size() const { return numElements; }
// clear the content of the hash
void clear();
// is the item in the hash?
bool find(T item) const;
// insert the item into the hash
void insert(T item);
// pure vitual hash function
virtual int hash(T & value) const = 0;
private:
int numBuckets;
int numElements;
list<T> * buckets;
};
/****************************************
* HASH : NON-DEFAULT CONSTRUCTOR
* Allocate the array of the passed number of list, assign the variables
****************************************/
template <typename T>
Hash<T>::Hash(int numBuckets) throw (const char *)
{
this->numBuckets = numBuckets;
numElements = 0;
try
{
buckets = new list<T> [this->numBuckets];
}
catch (bad_alloc)
{
cout << "ERROR: Unable to allocate memory for the hash.";
}
}
/****************************************
* HASH : COPY CONSTRUCTOR
* Make a new hash, the same with the passed one
****************************************/
template <typename T>
Hash<T>::Hash(const Hash & rhs) throw (const char *)
{
// copy the empty hash with no capacity
if ((rhs.empty() == true) && (rhs.capacity() == 0))
{
this->numBuckets = 0;
this->numElements = 0;
buckets = NULL;
}
// copy the empty hash with some capacity
else if (rhs.empty() == true)
{
this->numBuckets = rhs.numBuckets;
this->numElements = 0;
try
{
buckets = new list<T>[numBuckets];
}
catch (bad_alloc)
{
cout << "ERROR: Unable to allocate memory for the hash.";
}
}
// copy the hash with some elements
else
{
this->numBuckets = rhs.numBuckets;
this->numElements = rhs.numElements;
try
{
buckets = new list<T>[numBuckets];
}
catch (bad_alloc)
{
cout << "ERROR: Unable to allocate memory for the hash.";
}
for (int i = 0; i < rhs.numBuckets; i++)
{
if (!rhs.buckets[i].empty())
{
this->buckets = rhs.buckets;
}
}
}
}
/****************************************
* HASH : CLEAR
* Clear the content of the hash
****************************************/
template <typename T>
void Hash<T>::clear()
{
if (!empty())
{
for (int i = 0; i < numBuckets; i++)
{
if (!buckets[i].empty())
{
buckets[i].clear();
}
}
}
}
/****************************************
* HASH : FIND
* Is the element in the hash?
****************************************/
template <typename T>
bool Hash<T>::find(T element) const
{
if (!empty())
{
int index = hash(element);
for (list<T>::iterator it = buckets[index].begin(); it != buckets[index].end(); it++)
{
if (*it == element)
return true;
}
}
return false;
}
/****************************************
* HASH : INSERT
* Insert the element into the hash?
****************************************/
template <typename T>
void Hash<T>::insert(T element)
{
int index = hash(element);
buckets[index].push_back(element);
numElements++;
}
/****************************************
* SHASH
* A hash of strings : It inherits from HASH class
****************************************/
class SHash : public Hash <string>
{
public:
SHash(int numBuckets) throw (const char *) : Hash <string>(numBuckets) {}
SHash(const SHash & rhs) throw (const char *) : Hash <string>(rhs) {}
// hash function for integers is simply to take the modulous
int hash(string & word) const
{
int index = 0;
int sumLetters = 0;
for (string::iterator it = word.begin(); it != word.end(); it++)
{
sumLetters += static_cast<int>(*it);
}
index = sumLetters % capacity();
assert(index >= 0 && index < 232);
return index;
}
};
|
c1d39174e6d2ee65188fc4012ad0b4e4eaf88650
|
bc7d3cb16a9d479c0891dd251203b3e39716a97b
|
/binary-search/vjudge-binary-search/a.cpp
|
08d851c1f1c88901a3f825c162037793a1c7b8f4
|
[] |
no_license
|
dorenyerbolov/algorithms-and-ds
|
87e9e68fc4d10df500e615f3d39cc6df9d47305a
|
a5a25b49a57707a8d35982f79087c3fed81866dd
|
refs/heads/master
| 2020-03-28T18:00:44.204592
| 2018-10-14T04:55:39
| 2018-10-14T04:55:39
| 148,844,451
| 0
| 1
| null | 2018-10-27T20:55:52
| 2018-09-14T21:40:04
|
C++
|
UTF-8
|
C++
| false
| false
| 529
|
cpp
|
a.cpp
|
#include <iostream>
using namespace std;
string binarySearch(int *a, int el, int size){
int l = 0;
int r = size - 1;
while(l<r){
int m = (l+r)/2;
if(a[m] < el) l = m + 1;
else r = m;
}
if(a[l] == el) return "YES";
else return "NO";
}
int main(){
int n, m, el;
freopen("collect.in", "r", stdin);
freopen("collect.out", "w", stdout);
cin >> n;
int a[n];
for(int i = 0; i < n; i++){
cin >> a[i];
}
cin >> m;
for(int i = 0; i < m; i++){
cin >> el;
cout << binarySearch(a, el, n) << endl;
}
return 0;
}
|
15085590857857d3ccf52f2d0101f12eacf685de
|
61cbb1d05c2119381ebbdc721ecd49ff24949e56
|
/xcode/luminous/luminous/main.cpp
|
f1b8bd686f184fcb7b9e479f3e63065699dba957
|
[
"Apache-2.0"
] |
permissive
|
GordonMcGregor/luminous
|
328db10db73d203e9cdfe021f6e04479fe5bf577
|
b4f8d7134059072a5f524e2133af9609fc76c1e2
|
refs/heads/master
| 2021-01-01T15:35:20.580652
| 2014-02-28T15:32:56
| 2014-02-28T15:32:56
| 17,150,292
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,964
|
cpp
|
main.cpp
|
//
// main.cpp
// Main file
// ----------------------------------
// Developed with embedXcode
// http://embedXcode.weebly.com
//
// Project luminous
//
// Created by Gordon McGregor, 2/25/14 4:47 PM
// Gordon McGregor
//
// Copyright © Gordon McGregor, 2014
// License <#license#>
//
// See luminous.ino and ReadMe.txt for references
//
// ----------------------------------
// DO NOT EDIT THIS FILE.
// THE SKETCH IS IN luminous.ino
// ----------------------------------
//
// Last update: May 06, 2013 release 48
// IDE selection
#if defined(EMBEDXCODE)
// Sketch
#include "luminous.ino"
// Core library and main()
#if defined(MPIDE)
// ============================================================================= chipKIT specific
//************************************************************************
//* main.c
//*
//* Arduino core files for PIC32
//* Copyright (c) 2010, 2011 by Mark Sproul
//*
//*
//************************************************************************
//* this code is based on code Copyright (c) 2005-2006 David A. Mellis
//*
//* This library is free software; you can redistribute it and/or
//* modify it under the terms of the GNU Lesser General Public
//* License as published by the Free Software Foundation; either
//* version 2.1 of the License, or (at your option) any later version.
//*
//* This library is distributed in the hope that it will be useful,
//* but WITHOUT ANY WARRANTY; without even the implied warranty of
//* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.//* See the GNU
//* Lesser General Public License for more details.
//*
//* You should have received a copy of the GNU Lesser General
//* Public License along with this library; if not, write to the
//* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
//* Boston, MA 02111-1307 USA
//*
//*
//************************************************************************
//* Edit History
//************************************************************************
//* Oct 12, 2010 Got MPLAB X working on MacOSX 1.6 for the first time
//* Dec 12, 2011 <GeneApperson> added call to _scheduleTask() before call
//* to loop().
//************************************************************************
#define OPT_SYSTEM_INTERNAL
#include <System_Defs.h>
#if (ARDUINO >= 100)
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
extern "C" {
extern void __use_isr_install(void);
__attribute__((section(".comment"))) void (*__use_force_isr_install)(void) = &__use_isr_install;
}
//************************************************************************
int main(void)
{
init();
setup();
while (1)
{
_scheduleTask();
loop();
}
return 0;
}
#elif defined(DIGISPARK)
// ============================================================================= Digispark specific
#include "WProgram.h"
int main(void)
{
init();
setup();
for (;;)
loop();
return 0;
}
#elif defined(MICRODUINO)
// ============================================================================= Microduino specific
#include "Arduino.h"
int main(void)
{
init();
#if defined(USBCON)
USBDevice.attach();
#endif
setup();
for (;;) {
loop();
if (serialEventRun) serialEventRun();
}
return 0;
}
#elif defined(ENERGIA)
// ============================================================================= LaunchPad MSP430, Stellaris and Tiva, Experimeter Board FR5739 specific
#if defined(__LM4F120H5QR__) or defined(__TM4C1230C3PM__)
// ----------------------------------------------------------------------------- LaunchPad Stellaris and Tiva specific
#include "Energia.h"
#include "inc/lm4f120h5qr.h"
#include "inc/hw_gpio.h"
#include "driverlib/rom.h"
#include "driverlib/sysctl.h"
#include "driverlib/eeprom.h"
int main(void)
{
timerInit();
ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOC);
ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOE);
ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_EEPROM0);
if(ROM_EEPROMInit() == EEPROM_INIT_ERROR) {
if(ROM_EEPROMInit() != EEPROM_INIT_ERROR)
ROM_EEPROMMassErase();
}
//Unlock and commit NMI pins PD7 and PF0
HWREG(GPIO_PORTF_BASE + GPIO_O_LOCK) = 0x4C4F434B;
HWREG(GPIO_PORTF_BASE + GPIO_O_CR) |= 0x1;
HWREG(GPIO_PORTD_BASE + GPIO_O_LOCK) = 0x4C4F434B;
HWREG(GPIO_PORTD_BASE + GPIO_O_CR) |= 0x80;
setup();
for (;;) {
loop();
if (serialEventRun) serialEventRun();
}
}
#else
// ----------------------------------------------------------------------------- LaunchPad MSP430 and Experimeter Board FR5739 specific
#include "Energia.h"
int main(void)
{
init();
setup();
for (;;) {
loop();
if (serialEventRun) serialEventRun();
}
return 0;
}
#endif // Energia
#elif defined(MAPLE_IDE)
// ============================================================================= Maple specific
// *****************************************************************************
// The MIT License
//
// Copyright (c) 2010 LeafLabs LLC.
//
// 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.
// ****************************************************************************
__attribute__(( constructor )) void premain() {
init();
}
int main(void) {
setup();
for (;;)
loop();
return 0;
}
#elif defined(TEENSYDUINO) || defined(CORE_TEENSY)
// ============================================================================= Teensy specific
#if defined(__MK20DX128__) || defined(__MK20DX256__)
// ----------------------------------------------------------------------------- Teensy 3 specific
#include "WProgram.h"
extern "C" int main(void)
{
// Arduino's main() function just calls setup() and loop()....
setup();
while (1) {
loop();
yield();
}
}
#else
// ----------------------------------------------------------------------------- Teensy 2 specific
#include "WProgram.h"
//int main(void) __attribute__((noreturn));
int main(void)
{
_init_Teensyduino_internal_();
setup();
for (;;)
loop();
}
#endif // Teensy
#elif defined(WIRING)
// ============================================================================= Wiring specific
// Replace #include "WProgram.h" by #include "Wiring.h"
// Comment boardInit();
#include "Wiring.h"
int main(void)
{
// Hardware specific initializations.
// boardInit();
init();
// User defined setup routine
setup();
// User defined loop routine
for(;;)
loop();
}
#elif defined(ARDUINO)
// ============================================================================= Arduino specific
#if (ARDUINO < 100)
// ----------------------------------------------------------------------------- Arduino 0023 specific
#include "WProgram.h"
int main(void)
{
init();
setup();
for (;;)
loop();
return 0;
}
#elif (ARDUINO < 150)
// ----------------------------------------------------------------------------- Arduino 1.0x specific
#include "Arduino.h"
int main(void)
{
init();
#if defined(USBCON)
USBDevice.attach();
#endif
setup();
for (;;) {
loop();
if (serialEventRun) serialEventRun();
}
return 0;
}
#else
// ----------------------------------------------------------------------------- Arduino 1.5x specific
#if defined(__SAM3X8E__)
// ............................................................................. Arduino 1.5x SAM architecture specific
/*
Copyright (c) 2011 Arduino. All rights reserved.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#define ARDUINO_MAIN
#include "Arduino.h"
/*
* Cortex-M3 Systick IT handler
*/
/*
extern void SysTick_Handler( void )
{
// Increment tick count each ms
TimeTick_Increment() ;
}
*/
/*
* \brief Main entry point of Arduino application
*/
int main( void )
{
init();
delay(1);
#if defined(USBCON)
USBDevice.attach();
#endif
setup();
for (;;)
{
loop();
if (serialEventRun) serialEventRun();
}
return 0;
}
#else
// ............................................................................. Arduino 1.5x AVR architecture specific
#include "Arduino.h"
int main(void)
{
init();
#if defined(USBCON)
USBDevice.attach();
#endif
setup();
for (;;) {
loop();
if (serialEventRun) serialEventRun();
}
return 0;
}
#endif // architecture
#endif // Arduino
#else // error
#error Platform not defined
#endif // end IDE
#endif // end embedXcode
|
5a1662cedb2f653af4b1fe603d3d9ed2fa4f3d6a
|
658d9a724201b391f7f5bdfac82dbf0c4911e7f6
|
/problems/cracking-the-coding-interview/cci_2-3.cpp
|
8eaae0fff12f9473a30e00d91f53cec4c8e07872
|
[] |
no_license
|
currant77/interview-preparation
|
26e58a887c3b9b920d3999662a476c16b1c129a0
|
91cecef2097cb9fe0220e8b7e893487831eaf25e
|
refs/heads/master
| 2022-12-23T11:51:16.344963
| 2020-09-23T06:21:47
| 2020-09-23T06:21:47
| 270,768,199
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,623
|
cpp
|
cci_2-3.cpp
|
/**
* @file cci_2-3.cpp
* @author Taylor Curran
* @brief Solution to problem 2.3 from Cracking the Coding Interview
* @version 0.1
* @date 2020-07-02
*
* @note McDowell, Gayle Lakkmann. Cracking the Coding Interview.
* 6th ed. Palo Alto, CA: CareerCup, 2016.
*
* @copyright Copyright (c) 2020
*
*/
/* Problem 2.3: "Delete Middle Node: Implement an algorithm to delete
a node in the middle (i.e. any node but the first and last node, not
necessarily the exact middle) of a sinly linked list, given only
access to that node."*/
/* Approach: Copy the next node's data to that node, update points */
#include <cassert> // assert
#include <iostream> // std::cout, std::endl;
#include "../../data-structures/Node.h" // SinglyLinkedListNode<T>, compare_list<T>()
template<class T>
using Node = SinglyLinkedListNode<T>;
template<class T>
void remove_middle_node(Node<T>* node)
{
Node<T>* ptr = node->next;
node->data = node->next->data;
node->next = node->next->next;
delete ptr;
}
int main()
{
std::cout << std::endl << "Beginning tests..." << std::endl;
Node<int>* head = new Node<int>(1, new Node<int>(2, new Node<int>(3)));
remove_middle_node(head->next); // [1,2,3] -> [1,3]
assert(compare_list<int>(head, {1,3}));
head->next->next = new Node<int>(5, new Node<int>(7));
remove_middle_node(head->next->next); // [1,3,5,7] -> [1,3,7]
assert(compare_list<int>(head, {1,3,7}));
std::cout << "All tests passed!" << std::endl;
exit(0);
}
|
91c8607f3640892f7c2d0e706affd6964f7db7e0
|
e5b8a4d038300c8d98361ebee439ab04ca8f0668
|
/third_party/streamDM/streamDM/streams/LibSVMReader.cpp
|
c427479b46fef030676a03fc531fcf4189223719
|
[
"BSD-3-Clause"
] |
permissive
|
scikit-ika/scikit-ika
|
5c48985893159f082ac0ec45cbb1c1aa139aa9c8
|
ae70e053e4f89b524415971bfb9180c98b1aadd9
|
refs/heads/master
| 2022-05-10T02:05:46.572973
| 2022-04-27T03:30:50
| 2022-04-27T03:30:50
| 211,992,306
| 15
| 3
|
BSD-3-Clause
| 2022-04-20T08:39:39
| 2019-10-01T01:41:49
|
Python
|
UTF-8
|
C++
| false
| false
| 3,652
|
cpp
|
LibSVMReader.cpp
|
//================================================================================//
// Copyright 2009 Google Inc. //
// //
// 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. //
//================================================================================//
//
// LibSVMReader.cpp
//
// Author: D. Sculley, December 2008
// dsculley@google.com or dsculley@cs.tufts.edu
//
// Implementation of LibSVMReader.h
#include <assert.h>
#include "LibSVMReader.h"
REGISTER_CLASS(LibSVMReader)
REGISTER_COMMAND_LINE_PARAMETER(
LibSVMReader,
"{\"type\":\"Reader\","
"\"name\":\"LibSVMReader\","
"\"parameter\":{"
"\"-b\":\"UseBiasTerm\","
"\"-s\":\"BufferSize\""
"}}"
"");
//----------------------------------------------------------------//
//------------------ SfDataSet Public Methods --------------------//
//----------------------------------------------------------------//
//LibSVMReader::LibSVMReader(bool use_bias_term)
//:m_use_bias_term(use_bias_term), m_buffersize_mb(40), m_file_buffer(NULL), m_pFileStream(NULL)
//{
//}
//
//LibSVMReader::LibSVMReader(int buffer_mb, bool use_bias_term)
//:m_use_bias_term(use_bias_term), m_buffersize_mb(buffer_mb), m_file_buffer(NULL), m_pFileStream(NULL)
//{
//}
LibSVMReader::LibSVMReader()
{
m_use_bias_term = false;
m_buffersize_mb = 40;
m_file_buffer = NULL;
m_pFileStream = NULL;
}
LibSVMReader::~LibSVMReader()
{
if (NULL != m_file_buffer)
{
delete[] m_file_buffer;
}
if (NULL != m_pFileStream)
{
if (m_pFileStream->is_open())
{
m_pFileStream->close();
}
delete m_pFileStream;
}
}
void LibSVMReader::doSetParams() {
m_use_bias_term = getParam("UseBiasTerm", false);
m_buffersize_mb = getParam("BufferSize", 40);
}
int LibSVMReader::input(string& line_string)
{
this->mHasNextInstance = false;
this->mNextInstance = NULL;
if (getline(*m_pFileStream, line_string))
{
this->mNextInstance = new SparseInstance(line_string.c_str(), m_use_bias_term);
this->mHasNextInstance = true;
}
return 0;
}
bool LibSVMReader::setFile(const string& file_name)
{
long int buffer_size = m_buffersize_mb * 1024 * 1024;
m_file_buffer = new char[buffer_size];
m_pFileStream = new std::ifstream(file_name.c_str(), std::ifstream::in);
m_pFileStream->rdbuf()->pubsetbuf(m_file_buffer, buffer_size);
if (!m_pFileStream->is_open())
{
return false;
}
return true;
}
bool LibSVMReader::hasNextInstance()
{
string line_string = "";
input(line_string);
return this->mHasNextInstance;
}
|
e7a555e2d3ceadf0766382c99573b23e576dd3fe
|
c8ff2d4fc99f4e37e16e42440aa3a22156d0adc2
|
/test/test.cpp
|
a4efcec6e79cbf111b07f9dd787c245824580ac5
|
[
"BSL-1.0"
] |
permissive
|
BoostGSoC17/data_frame
|
3ef0ffb99a3c227ee625e07380500cf4affea870
|
c6ed820df8154491021dd22b34322d60f23ac086
|
refs/heads/master
| 2018-10-31T11:55:36.162939
| 2018-08-24T05:29:32
| 2018-08-24T05:29:32
| 92,756,543
| 8
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,763
|
cpp
|
test.cpp
|
// Copyright(C) Rishabh Arora 2017.
// 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)
// To compile, use boost with the flag -lboost_unit_test_framework.
// To run use ./a.out --log_level=all to see the entire error report.
#define BOOST_DYN_LINK
#define BOOST_TEST_MODULE DATA_FRAME
#include <boost/test/unit_test.hpp>
#include "../include/boost/numeric/ublas/FINAL_VERSIONS/df.hpp"
using namespace boost::numeric::ublas;
BOOST_AUTO_TEST_CASE (df_column_constructors) {
// default constructor
df_column c1;
BOOST_CHECK(c1.size() == 0);
// copy constructor with params: vector<T>
vector <int> I(100);
for(size_t i = 0; i < 100; i++) I(i) = i+2;
df_column II(I);
BOOST_CHECK(II.size() == 100);
for(size_t i = 0; i < 100; i++) {
BOOST_CHECK(I(i) == II.get<int>()(i));
}
// copy constructor with params: df_column
df_column III(II);
BOOST_CHECK(II.size() == III.size());
for(size_t i = 0; i < 100; ++i) {
BOOST_CHECK(II.get<int>()(i) == III.get<int>()(i));
}
df_column IV(II + III);
BOOST_CHECK(IV.size() == II.size());
for(size_t i = 0; i < 100; ++i) {
BOOST_CHECK(II.get<int>()(i) + III.get<int>()(i) == IV.get<int>()(i));
}
}
BOOST_AUTO_TEST_CASE (df_column_assignment) {
vector < std::string > x(2);
x(0) = "rishabh";
x(1) = "arora";
df_column X = x;
BOOST_CHECK(X.size() == x.size());
for(size_t i = 0; i < X.size(); ++i) {
BOOST_CHECK(X.get<std::string>()(i) == x(i));
}
df_column Y = X;
BOOST_CHECK(X.size() == Y.size());
for(size_t i = 0; i < X.size(); ++i) {
BOOST_CHECK(X.get<std::string>()(i) == Y.get<std::string>()(i));
}
}
BOOST_AUTO_TEST_CASE (df_column_Equality_Check_Operators) {
vector < double > a(3);
a(0) = 1.1;
a(1) = 1.2;
a(2) = 1.32;
vector < char > b(2);
b(0) = 'a';
b(1) = 'b';
// should fail
df_column A(a), B(b);
//BOOST_CHECK(A == B);
// should pass
BOOST_CHECK(A != B);
df_column C(A);
// should pass
BOOST_CHECK(A == C);
// should fail
//BOOST_CHECK(A != C);
vector < char > d(2);
d(0) = 'c';
d(1) = 'd';
df_column D(d);
// should fail
//BOOST_CHECK(B == D);
// should pass
BOOST_CHECK(B != D);
}
BOOST_AUTO_TEST_CASE (df_column_Unary_Operator) {
// unary - operator
vector < int > z(3);
z(0) = 15;
z(1) = 12;
z(2) = 13;
df_column Z(z);
// move assignment :)
df_column T = -Z;
BOOST_CHECK(T.size() == Z.size());
for(size_t i = 0; i < T.size(); ++i) {
BOOST_CHECK(T.get<int>()(i) == -Z.get<int>()(i));
}
}
BOOST_AUTO_TEST_CASE (df_column_Binary_Operators) {
vector < int > z(3);
z(0) = 15;
z(1) = 12;
z(2) = 13;
df_column Z(z);
df_column Y(2*Z);
BOOST_CHECK(Z.size() == Y.size());
for(size_t i = 0; i < Y.size(); ++i) {
BOOST_CHECK(2 * Z.get<int>()(i) == Y.get<int>()(i));
}
Z *= 2;
for(size_t i = 0; i < Y.size(); ++i) {
BOOST_CHECK(Z.get<int>()(i) == Y.get<int>()(i));
}
df_column X = Z + 3;
BOOST_CHECK(X.size() == Z.size());
for(size_t i = 0; i < Z.size(); ++i) {
BOOST_CHECK(X.get <int>()(i) == Z.get<int>()(i) + 3);
}
X += 3;
for(size_t i = 0; i < Z.size(); ++i) {
BOOST_CHECK(X.get <int>()(i) == Z.get<int>()(i) + 6);
}
X -= 3;
for(size_t i = 0; i < Z.size(); ++i) {
BOOST_CHECK(X.get <int>()(i) == Z.get<int>()(i) + 3);
}
df_column A = X + Z;
BOOST_CHECK(A.size() == X.size() && A.size() == Z.size());
for(size_t i = 0; i < Z.size(); ++i) {
BOOST_CHECK(A.get<int>()(i) == X.get <int>()(i) + Z.get<int>()(i));
}
A -= X;
for(size_t i = 0; i < Z.size(); ++i) {
BOOST_CHECK(A.get<int>()(i) == Z.get<int>()(i));
}
}
// No static_assert checking. Manual looking shows that results are perfect. :-)
BOOST_AUTO_TEST_CASE (df_column_Printing) {
vector < int > z(3);
z(0) = 15;
z(1) = 12;
z(2) = 13;
df_column Z(z);
df_column Y(2*Z);
Z.print();
Y.summary < int, double> ();
}
BOOST_AUTO_TEST_CASE (df_column_Statistical_Summaries) {
// Mean
vector<double> v(6);
v(0) = 10, v(1) = 20, v(2) = 30, v(3) = 40, v(4) = 50, v(5) = 60.123777;
df_column V(v);
double mean = V.Mean<double, double>();
double var = (10.0 + 20.0 + 30.0 + 40.0 + 50.0 + 60.123777) / 6.0;
//std::cout << mean << ' ' << var << '\n';
BOOST_CHECK(fabs(mean - var) < 1e-9);
// Median
double Median = V.Median<double, double>();
BOOST_CHECK( fabs(Median - 35) < 1e-9);
v.resize(7);
v(6) = 70;
V = v;
Median = V.Median<double, double>();
BOOST_CHECK( fabs(Median - 40) < 1e-9);
// Max, Min
vector < long long > r(10);
for(int i = 0; i < 10; ++i) r(i) = 1e16 + rand() % 1000;
long long mx = -1, mn = 1e18;
for(int i = 0; i < 10; ++i) {
if (r(i) > mx) mx = r(i);
if (r(i) < mn) mn = r(i);
}
df_column R(r);
long long MAX = R.Max<long long, long long>();
long long MIN = R.Min<long long, long long>();
BOOST_CHECK(mx == MAX);
BOOST_CHECK(mn == MIN);
}
BOOST_AUTO_TEST_CASE (data_frame_Constructors) {
// default constructor
data_frame df1;
BOOST_CHECK(df1.nrow() == 0 && df1.ncol() == 0);
vector < std::string > names(2);
names(0) = "col1";
names(1) = "col2";
vector < int > x(2), y(2);
x(0) = 1;
y(1) = 1;
vector < df_column > cols(2);
cols (0) = x;
cols (1) = y;
data_frame df2(names, cols);
BOOST_CHECK(df2.ncol() == 2 && df2.nrow() == 2);
for(size_t i = 0; i < df2.ncol(); ++i) {
BOOST_CHECK(names(i) == df2.headers()(i));
}
for(size_t j = 0; j < df2.nrow(); ++j) {
BOOST_CHECK(x(j) == df2["col1"].get<int>()(j));
}
for(size_t j = 0; j < df2.nrow(); ++j) {
BOOST_CHECK(y(j) == df2["col2"].get<int>()(j));
}
}
BOOST_AUTO_TEST_CASE (data_frame_Column_Accessors_Manipulators) {
// Column Retrieval
vector < std::string > names(3);
names(0) = "x";
names(1) = "y";
names(2) = "z";
vector < char > x(2);
vector < bool > y(2);
vector < std::string > z(2);
x(0) = 'p';
x(1) = 'q';
y(0) = true;
y(1) = false;
z(0) = "Oh!";
z(1) = "Yeah..";
vector < df_column > cols(3);
cols (0) = x;
cols (1) = y;
cols (2) = z;
data_frame df(names, cols);
BOOST_CHECK(df.ncol() == 3 && df.nrow() == 2);
for(size_t i = 0; i < df.nrow(); ++i) {
BOOST_CHECK(x(i) == df["x"].get<char>()(i));
BOOST_CHECK(x(i) == df[0].get<char>()(i));
BOOST_CHECK(x(i) == df.column<char>("x")(i));
BOOST_CHECK(x(i) == df.column<char>(0)(i));
}
for(size_t i = 0; i < df.nrow(); ++i) {
BOOST_CHECK(y(i) == df["y"].get<bool>()(i));
BOOST_CHECK(y(i) == df[1].get<bool>()(i));
BOOST_CHECK(y(i) == df.column<bool>("y")(i));
BOOST_CHECK(y(i) == df.column<bool>(1)(i));
}
for(size_t i = 0; i < df.nrow(); ++i) {
BOOST_CHECK(z(i) == df["z"].get<std::string>()(i));
BOOST_CHECK(z(i) == df[2].get<std::string>()(i));
BOOST_CHECK(z(i) == df.column<std::string>("z")(i));
BOOST_CHECK(z(i) == df.column<std::string>(2)(i));
}
/// Column Accessors + Updating
// via string
df["x"] = y;
BOOST_CHECK(df["x"].size() == df.nrow());
for(size_t i = 0; i < df.nrow(); ++i) {
BOOST_CHECK(y(i) == df["x"].get<bool>()(i));
BOOST_CHECK(y(i) == df[0].get<bool>()(i));
BOOST_CHECK(y(i) == df.column<bool>("x")(i));
BOOST_CHECK(y(i) == df.column<bool>(0)(i));
}
// via index
df[0] = x; // df is back to original
BOOST_CHECK(df["x"].size() == df.nrow());
for(size_t i = 0; i < df.nrow(); ++i) {
BOOST_CHECK(x(i) == df["x"].get<char>()(i));
BOOST_CHECK(x(i) == df[0].get<char>()(i));
BOOST_CHECK(x(i) == df.column<char>("x")(i));
BOOST_CHECK(x(i) == df.column<char>(0)(i));
}
/// erasing columns
// via index
size_t ncol_earlier = df.ncol();
df.erase_column(0);
BOOST_CHECK(df.ncol() == ncol_earlier-1);
// test for correct restructuring of data_frame after the erase
for(size_t i = 0; i < df.nrow(); ++i) {
BOOST_CHECK(y(i) == df["y"].get<bool>()(i));
BOOST_CHECK(y(i) == df[0].get<bool>()(i));
BOOST_CHECK(y(i) == df.column<bool>("y")(i));
BOOST_CHECK(y(i) == df.column<bool>(0)(i));
}
for(size_t i = 0; i < df.nrow(); ++i) {
BOOST_CHECK(z(i) == df["z"].get<std::string>()(i));
BOOST_CHECK(z(i) == df[1].get<std::string>()(i));
BOOST_CHECK(z(i) == df.column<std::string>("z")(i));
BOOST_CHECK(z(i) == df.column<std::string>(1)(i));
}
// via string
ncol_earlier = df.ncol();
df.erase_column("y");
BOOST_CHECK(df.ncol() == ncol_earlier-1);
for(size_t i = 0; i < df.nrow(); ++i) {
BOOST_CHECK(z(i) == df["z"].get<std::string>()(i));
BOOST_CHECK(z(i) == df[0].get<std::string>()(i));
BOOST_CHECK(z(i) == df.column<std::string>("z")(i));
BOOST_CHECK(z(i) == df.column<std::string>(0)(i));
}
/// Add columns via accessor
// via string
df.print();
ncol_earlier = df.ncol();
df["y"] = y;
BOOST_CHECK(df.ncol() == ncol_earlier + 1);
df.print();
}
BOOST_AUTO_TEST_CASE (data_frame_Equality_Check_Operators) {
// Column Retrieval
vector < std::string > names(3);
names(0) = "x";
names(1) = "y";
names(2) = "z";
vector < char > x(2);
vector < bool > y(2);
vector < std::string > z(2);
x(0) = 'p';
x(1) = 'q';
y(0) = true;
y(1) = false;
z(0) = "Oh!";
z(1) = "Yeah..";
vector < df_column > cols(3);
cols (0) = x;
cols (1) = y;
cols (2) = z;
data_frame df(names, cols);
data_frame df2(df);
// should pass
BOOST_CHECK(df == df2);
data_frame empty;
// should pass
BOOST_CHECK(df != empty);
// should fail
//BOOST_CHECK(df == empty);
}
BOOST_AUTO_TEST_CASE (data_frame_Unary_Operators) {
vector < std::string > names(4);
names(0) = "a", names(1) = "b", names(2) = "c", names(3) = "d";
vector < int > x(2), y(2);
x(0) = 1;
y(1) = 1;
vector < df_column > cols(4);
cols (0) = x;
cols (1) = y;
cols (2) = x;
cols (3) = y;
data_frame df(names, cols);
// move constructor :)
data_frame negate_df(-df);
BOOST_CHECK (negate_df.nrow() == df.nrow() && negate_df.ncol() == df.ncol());
for(size_t i = 0; i < negate_df.ncol(); ++i) negate_df.colname(i) == names(i);
for(size_t i = 0; i < df.nrow(); ++i) {
BOOST_CHECK(x(i) == -negate_df[0].get<int>()(i));
BOOST_CHECK(x(i) == -negate_df[2].get<int>()(i));
}
for(size_t i = 0; i < df.nrow(); ++i) {
BOOST_CHECK(y(i) == -negate_df[1].get<int>()(i));
BOOST_CHECK(y(i) == -negate_df[3].get<int>()(i));
}
}
BOOST_AUTO_TEST_CASE (data_frame_Statistical_Summaries) {
vector < int > x(2);
vector < std::string > y(2);
vector < double > z(2);
x(0) = 10, x(1) = 11;
y(0) = "rishabh", y(1) = "arora";
z(0) = 1.2, z(1) = 2.0;
vector < std::string > headers(3);
headers(0) = "x", headers(1) = "y", headers(2) = "z";
vector < df_column > A(3);
A(0) = x, A(1) = y, A(2) = z;
data_frame df(headers, A);
// Already checked above that df_column_summaries work fine. and data_Frame summaries are extension of df_column_summaries for each column of the data_Frame.
df.summary();
}
BOOST_AUTO_TEST_CASE (data_frame_Binary_Operators) {
vector < std::string > headers(2);
headers(0) = "a";
headers(1) = "b";
vector < double > a(2), b(2);
a(0) = 1.1, a(1) = 2.1;
b(0) = 1.2, b(1) = 2.3;
vector < df_column > col(2);
col(0) = a;
col(1) = b;
data_frame df1(headers, col);
vector < df_column > col2(2);
a = 2 * a;
b = 2 * b;
col2(0) = a;
col2(1) = b;
data_frame df2(headers, col2);
data_frame df3 = df1 + df2;
BOOST_CHECK(df3.nrow() == df1.nrow() && df3.nrow() == df2.nrow());
BOOST_CHECK(df3.ncol() == df1.ncol() && df3.ncol() == df2.ncol());
for(size_t i = 0; i < df3.nrow(); ++i) {
BOOST_CHECK(df3[0].get<double>()(i) == df1[0].get<double>()(i) + df2[0].get<double>()(i));
}
for(size_t i = 0; i < df3.nrow(); ++i) {
BOOST_CHECK(df3[1].get<double>()(i) == df1[1].get<double>()(i) + df2[1].get<double>()(i));
}
data_frame df4 = df3 - df2;
BOOST_CHECK(df4.nrow() == df3.nrow() && df4.nrow() == df2.nrow());
BOOST_CHECK(df4.ncol() == df3.ncol() && df4.ncol() == df2.ncol());
for(size_t i = 0; i < df4.nrow(); ++i) {
BOOST_CHECK(fabs(df4[0].get<double>()(i) - df1[0].get<double>()(i)) < 1e-9);
}
for(size_t i = 0; i < df3.nrow(); ++i) {
BOOST_CHECK(fabs(df4[1].get<double>()(i) - df1[1].get<double>()(i)) < 1e-9);
}
data_frame df5 = df1 + 5;
BOOST_CHECK(df5.nrow() == df1.nrow());
BOOST_CHECK(df5.ncol() == df1.ncol());
for(size_t i = 0; i < df5.nrow(); ++i) {
BOOST_CHECK(fabs(df5[0].get<double>()(i) - df1[0].get<double>()(i) - 5) < 1e-9);
}
for(size_t i = 0; i < df5.nrow(); ++i) {
BOOST_CHECK(fabs(df5[1].get<double>()(i) - df1[1].get<double>()(i)- 5) < 1e-9);
}
data_frame df6 = df1 - 10;
BOOST_CHECK(df6.nrow() == df1.nrow());
BOOST_CHECK(df6.ncol() == df1.ncol());
for(size_t i = 0; i < df6.nrow(); ++i) {
BOOST_CHECK(fabs(df6[0].get<double>()(i) - df1[0].get<double>()(i) + 10) < 1e-9);
}
for(size_t i = 0; i < df6.nrow(); ++i) {
BOOST_CHECK(fabs(df6[1].get<double>()(i) - df1[1].get<double>()(i) + 10) < 1e-9);
}
data_frame df7 = 2 * df1;
BOOST_CHECK(df7.nrow() == df1.nrow());
BOOST_CHECK(df7.ncol() == df1.ncol());
for(size_t i = 0; i < df7.nrow(); ++i) {
BOOST_CHECK(fabs(df7[0].get<double>()(i) - 2 * df1[0].get<double>()(i)) < 1e-9);
}
for(size_t i = 0; i < df7.nrow(); ++i) {
BOOST_CHECK(fabs(df7[1].get<double>()(i) - 2 * df1[1].get<double>()(i)) < 1e-9);
}
df7 += df1;
for(size_t i = 0; i < df7.nrow(); ++i) {
BOOST_CHECK(fabs(df7[0].get<double>()(i) - 3 * df1[0].get<double>()(i)) < 1e-9);
}
for(size_t i = 0; i < df7.nrow(); ++i) {
BOOST_CHECK(fabs(df7[1].get<double>()(i) - 3 * df1[1].get<double>()(i)) < 1e-9);
}
df7 -= df1;
for(size_t i = 0; i < df7.nrow(); ++i) {
BOOST_CHECK(fabs(df7[0].get<double>()(i) - 2 * df1[0].get<double>()(i)) < 1e-9);
}
for(size_t i = 0; i < df7.nrow(); ++i) {
BOOST_CHECK(fabs(df7[1].get<double>()(i) - 2 * df1[1].get<double>()(i)) < 1e-9);
}
df7 += 5;
for(size_t i = 0; i < df7.nrow(); ++i) {
BOOST_CHECK(fabs(df7[0].get<double>()(i) - 2 * df1[0].get<double>()(i) - 5) < 1e-9);
}
for(size_t i = 0; i < df6.nrow(); ++i) {
BOOST_CHECK(fabs(df7[1].get<double>()(i) - 2 * df1[1].get<double>()(i) - 5) < 1e-9);
}
df7 -= 10;
for(size_t i = 0; i < df7.nrow(); ++i) {
BOOST_CHECK(fabs(df7[0].get<double>()(i) - 2 * df1[0].get<double>()(i) + 5) < 1e-9);
}
for(size_t i = 0; i < df6.nrow(); ++i) {
BOOST_CHECK(fabs(df7[1].get<double>()(i) - 2 * df1[1].get<double>()(i) + 5) < 1e-9);
}
df7 += 5;
df7 *= 3;
for(size_t i = 0; i < df7.nrow(); ++i) {
BOOST_CHECK(fabs(df7[0].get<double>()(i) - 6 * df1[0].get<double>()(i)) < 1e-9);
}
for(size_t i = 0; i < df7.nrow(); ++i) {
BOOST_CHECK(fabs(df7[1].get<double>()(i) - 6 * df1[1].get<double>()(i)) < 1e-9);
}
}
BOOST_AUTO_TEST_CASE (data_frame_row_accessor) {
vector < int > a(3);
vector < std::string > b(3);
vector < bool > c(3);
vector < long long > d(3);
vector < char > e(3);
vector < std::string > headers(5);
headers(0) = "a", headers(1) = "b", headers(2) = "c", headers(3) = "d", headers(4) = "e";
a(0) = 1, a(1) = 2, a(2) = 3;
b(0) = "R", b(1) = "RArora", b(2) = "Arora";
c(0) = 0, c(1) = 1, c(2) = 0;
d(0) = (long long)1e10, d(1) = (long long)1e10 + 100, d(2) = (long long)1e10 - 100;
e(0) = 'a', e(1) = 'b', e(2) = 'c';
vector < df_column > col(5);
col(0) = a, col(1) = b, col(2) = c, col(3) = d, col(4) = e;
data_frame df(headers, col);
vector < boost::variant < COLUMN_DATA_TYPES > > row = df(0);
BOOST_CHECK(row.size() == df.ncol());
BOOST_CHECK(boost::get<int>(row(0)) == a(0));
BOOST_CHECK(boost::get<std::string>(row(1)) == b(0));
BOOST_CHECK(boost::get<bool>(row(2)) == c(0));
BOOST_CHECK(boost::get<long long>(row(3)) == d(0));
BOOST_CHECK(boost::get<char>(row(4)) == e(0));
}
BOOST_AUTO_TEST_CASE (data_frame_proxies) {
vector < int > a(3);
vector < std::string > b(3);
vector < bool > c(3);
vector < long long > d(3);
vector < char > e(3);
vector < std::string > headers(5);
headers(0) = "a", headers(1) = "b", headers(2) = "c", headers(3) = "d", headers(4) = "e";
a(0) = 1, a(1) = 2, a(2) = 3;
b(0) = "R", b(1) = "RArora", b(2) = "Arora";
c(0) = 0, c(1) = 1, c(2) = 0;
d(0) = (long long)1e10, d(1) = (long long)1e10 + 100, d(2) = (long long)1e10 - 100;
e(0) = 'a', e(1) = 'b', e(2) = 'c';
vector < df_column > col(5);
col(0) = a, col(1) = b, col(2) = c, col(3) = d, col(4) = e;
data_frame df(headers, col);
data_frame_range dfr1(&df, range(0, 3));
BOOST_CHECK(dfr1.size() == 3);
//dfr1.print();
for (int i = 0; i < 3; ++i) {
BOOST_CHECK(dfr1[0].get<int>()(i) == a(i));
}
for (int i = 0; i < 3; ++i) {
BOOST_CHECK(dfr1[1].get<std::string>()(i) == b(i));
}
for (int i = 0; i < 3; ++i) {
BOOST_CHECK(dfr1[2].get<bool>()(i) == c(i));
}
data_frame_slice dfs1(&df, slice(0, 2, 3));
BOOST_CHECK(dfs1.size() == 3);
//dfs1.print();
for (int i = 0; i < 3; ++i) {
BOOST_CHECK(dfs1[0].get<int>()(i) == a(i));
}
for (int i = 0; i < 3; ++i) {
BOOST_CHECK(dfs1[1].get<bool>()(i) == c(i));
}
for (int i = 0; i < 3; ++i) {
BOOST_CHECK(dfs1[2].get<char>()(i) == e(i));
}
indirect_array<> ia(3);
ia[0] = 0, ia[1] = 1, ia[2] = 4;
data_frame_indirect dfi1(&df, ia);
// dfi1.print();
BOOST_CHECK(dfs1.size() == 3);
for (int i = 0; i < 3; ++i) {
BOOST_CHECK(dfi1[0].get<int>()(i) == a(i));
}
for (int i = 0; i < 3; ++i) {
BOOST_CHECK(dfi1[1].get<std::string>()(i) == b(i));
}
for (int i = 0; i < 3; ++i) {
BOOST_CHECK(dfi1[2].get<char>()(i) == e(i));
}
data_frame_range dfr(&df, range(3, 4));
dfr += 3;
dfr.print();
// now only column 3 is updated, rest of the data_frame remains the same.
for(size_t i = 0; i < 3; ++i) {
BOOST_CHECK(dfr[0].get<long long>()(i) == d(i) + 3);
}
dfr -= 3;
for(size_t i = 0; i < 3; ++i) {
BOOST_CHECK(dfr[0].get<long long>()(i) == d(i));
}
dfr *= 5;
for(size_t i = 0; i < 3; ++i) {
BOOST_CHECK(dfr[0].get<long long>()(i) == 5 * d(i));
}
data_frame_slice dfs(&df, slice(0, 3, 2));
dfs += 3;
for(size_t i = 0; i < 3; ++i) {
BOOST_CHECK(dfs[0].get<int>()(i) == a(i) + 3);
BOOST_CHECK(dfs[1].get<long long>()(i) == 5 * d(i) + 3);
}
dfs -= 3;
for(size_t i = 0; i < 3; ++i) {
BOOST_CHECK(dfs[0].get<int>()(i) == a(i));
BOOST_CHECK(dfs[1].get<long long>()(i) == 5 * d(i));
}
dfs *= 2;
for(size_t i = 0; i < 3; ++i) {
BOOST_CHECK(dfs[0].get<int>()(i) == 2 * a(i));
BOOST_CHECK(dfs[1].get<long long>()(i) == 10 * d(i) );
}
indirect_array <> ia1(2);
ia1[0] = 0, ia1[1] = 3;
data_frame_indirect dfi(&df, ia1);
dfi += 1;
for(size_t i = 0; i < 3; ++i) {
BOOST_CHECK(dfi[0].get<int>()(i) == 2 * a(i) + 1);
BOOST_CHECK(dfi[1].get<long long>()(i) == 10 * d(i) + 1);
}
dfi -= 1;
for(size_t i = 0; i < 3; ++i) {
BOOST_CHECK(dfi[0].get<int>()(i) == 2 * a(i));
BOOST_CHECK(dfi[1].get<long long>()(i) == 10 * d(i));
}
dfi *= 100;
for(size_t i = 0; i < 3; ++i) {
BOOST_CHECK(dfi[0].get<int>()(i) == 200 * a(i));
BOOST_CHECK(dfi[1].get<long long>()(i) == 1000 * d(i));
}
}
|
d1d4dff8fde6df1d7eb0a0c23c234e9089916469
|
6f7574c8adc99e09f44029d8dc9f7e1f4b055365
|
/LED_Patterns/shimmer4SaberWhite/shimmer4SaberWhite.ino
|
b02cb13f44a1592d1478e53b87a4eff893af9f56
|
[] |
no_license
|
jacobjoaquin/D18
|
7242238af33592f3a99051cf80cc948e13f14739
|
5a796b8b94c7850de63c5ab67255d24ec4a59df1
|
refs/heads/master
| 2021-08-16T10:51:50.197910
| 2018-09-06T19:25:01
| 2018-09-06T19:25:01
| 142,781,012
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,665
|
ino
|
shimmer4SaberWhite.ino
|
#include <Adafruit_NeoPixel.h>
// Combine rbg values to color
#define rgb(R, G, B) ((((uint32_t)(R)) << 16) | (((uint32_t)(G)) << 8) | ((uint32_t)(B)))
// Constansts
const int PIN = 13;
const int nLeds = 60;
const int frameDelay = 1000 / 12;
const int nSparklesPerFrame = 1;
// Neopixel setup
Adafruit_NeoPixel leds(nLeds, PIN, NEO_GRB + NEO_KHZ800);;
// User defined variables
uint32_t orange = rgb(255, 64, 0);
uint32_t magenta = rgb(255, 0, 92);
uint32_t black = rgb(0, 0, 0);
uint32_t white = rgb(255, 255, 255);
uint32_t pink = rgb(128, 0, 64);
// LED Buffer
uint32_t buffer[nLeds] = {0};
// Timing
uint32_t showTime = millis() + frameDelay;
// Sparkle
struct Sparkle {
int position;
int length;
int direction;
uint32_t color;
int framesLeft;
};
const int nSparkles = 100;
Sparkle sparkleList[nSparkles];
int sparkleLength = 5;
int sparkleFrames = 40;
int sparkleIndex = 0;
void initSparkleList() {
struct Sparkle * zPtr = sparkleList;
for (int i = 0; i < nSparkles; i++) {
zPtr->position = 0;
zPtr->length = sparkleLength;
zPtr->direction = 0;
zPtr->color = white;
zPtr->framesLeft = 0;
zPtr++;
}
}
void newSparkle() {
Sparkle * zPtr = &sparkleList[sparkleIndex];
zPtr->position = random(nLeds);
zPtr->direction = random(2) ? 1 : -1;
zPtr->framesLeft = sparkleFrames;
zPtr->length = random(1, 5);
zPtr->color = white;
// Update index
sparkleIndex = (sparkleIndex + 1) % nSparkles;
}
void updateSparkles() {
struct Sparkle * zPtr = sparkleList;
for (int i = 0; i < nSparkles; i++) {
if (zPtr->framesLeft > 0) {
zPtr->framesLeft--;
zPtr->position += zPtr->direction;
uint32_t c = lerpColor(zPtr->color, 0, float(zPtr->framesLeft) / (float) sparkleFrames);
int length = zPtr->length;
int position = zPtr->position;
for (int j = 0; j < length; j++) {
int index = position + j;
index += nLeds * (index < 0);
index -= nLeds * (index >= nLeds);
buffer[index] = c;
}
}
zPtr++;
}
}
void bufferToLEDs() {
uint32_t * bufferPtr = buffer;
// Add additional sparkle
for (int i = 0; i < nLeds; i++) {
uint32_t c = *bufferPtr;
int amt = random(256);
c = lerpColor(0, c, amt);
leds.setPixelColor(i, c);
bufferPtr++;
}
}
void setup() {
initSparkleList();
leds.begin();
}
void loop() {
memset(&buffer[0], 0, sizeof(buffer));
leds.clear();
for (int i = 0; i < nSparklesPerFrame; ++i) {
newSparkle();
}
updateSparkles();
bufferToLEDs();
displayLEDs();
}
void displayLEDs() {
while (millis() < showTime) {}
leds.show();
showTime = millis() + frameDelay;
}
|
243a63183e7d68365d6e5fcdcef946ed77b2f329
|
c88eca76f98aeaed16bfbd6051eea6c9594f5595
|
/framework/core/src/db/schema/grammars/rename_column.cc
|
977d6d9039cd97f10c2510a3e53b9106607313d1
|
[
"MIT"
] |
permissive
|
xubingyue/plain
|
9154acfb95e47f72221773d14eea78fdbfc6076e
|
28f9411de4507735da340a341211570992407a01
|
refs/heads/master
| 2020-05-19T18:23:11.562043
| 2019-03-26T12:29:33
| 2019-03-26T12:29:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 306
|
cc
|
rename_column.cc
|
#include "pf/db/schema/grammars/rename_column.h"
using namespace pf_db::schema::grammars;
//Compile a change column command into a series of SQL statements.
std::vector<std::string> RenameColumn::compile(
Grammar *,
Blueprint *,
fluent_t &,
ConnectionInterface *) {
return {"", };
}
|
30ef5025fed61e3ea671a0c33562acb2af08acc7
|
9f90a51dcec4068ea316da1a7e1716ec8f718dca
|
/proxy_dll/myIDirect3DSwapChain9.h
|
8765633a4cac9420a37ebf7729678c50276af7cd
|
[
"MIT"
] |
permissive
|
Poyeyo/deltabest
|
622ca6c8df0c6d6471b58be59bfdfb671db39eb1
|
6b4d17591c75073515f1e2c2615919486c49ecbf
|
refs/heads/master
| 2022-12-09T14:32:40.983963
| 2020-09-21T22:02:03
| 2020-09-21T22:02:03
| 297,467,070
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,174
|
h
|
myIDirect3DSwapChain9.h
|
#pragma once
class myIDirect3DSwapChain9 : public IDirect3DSwapChain9
{
public:
myIDirect3DSwapChain9(IDirect3DSwapChain9* pOriginal, IDirect3DDevice9* pDevice);
virtual ~myIDirect3DSwapChain9(void);
// START: The original DX9 function definitions
HRESULT __stdcall QueryInterface (REFIID riid, void** ppvObj);
ULONG __stdcall AddRef(void);
ULONG __stdcall Release(void);
HRESULT __stdcall Present(CONST RECT* pSourceRect,CONST RECT* pDestRect,HWND hDestWindowOverride,CONST RGNDATA* pDirtyRegion,DWORD dwFlags);
HRESULT __stdcall GetFrontBufferData(IDirect3DSurface9* pDestSurface);
HRESULT __stdcall GetBackBuffer(UINT iBackBuffer,D3DBACKBUFFER_TYPE Type,IDirect3DSurface9** ppBackBuffer);
HRESULT __stdcall GetRasterStatus(D3DRASTER_STATUS* pRasterStatus);
HRESULT __stdcall GetDisplayMode(D3DDISPLAYMODE* pMode);
HRESULT __stdcall GetDevice(IDirect3DDevice9** ppDevice);
HRESULT __stdcall GetPresentParameters(D3DPRESENT_PARAMETERS* pPresentationParameters);
// END: The original DX9 function definitions
private:
IDirect3DSwapChain9 *m_pIDirect3DSwapChain9;
IDirect3DDevice9 *m_pIDirect3DDevice9;
};
|
de3976b67e8aece115b6b098b2398176bb2d11ab
|
98cd78aad82b56adfe9e9658ffe299e9e8598b5b
|
/src/entities/Box.hpp
|
eebc65e485a4ef9badee3bb30e11986a4cac2f29
|
[] |
no_license
|
paul-maxime/bombercraft
|
6e6ac6bcd31f4f05db1593aa9a7a5b297e24194f
|
fb7bf2aaf57423a251607556e52a9d0ec7355a8c
|
refs/heads/master
| 2020-09-28T02:11:21.790785
| 2016-10-27T09:28:40
| 2016-10-27T09:28:40
| 67,894,054
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,287
|
hpp
|
Box.hpp
|
/**
* \file Box.hpp
* Defines the box entity.
*/
#ifndef BOX_HPP_
#define BOX_HPP_
#include "AEntity.hpp"
/**
* \class Box
* A destructible block containing a bonus
* Inherits from AEntity
*/
class Box : public AEntity
{
public:
/**
* The box constructor
* \param map The map where the entity is contained
* \param posX The initial x coordinate
* \param posY The initial y coordinate
*/
Box(Map *map, int posX, int posY);
/**
* The virtual destructor of the bomb
*/
virtual ~Box();
/**
* Overload of the AEntity kill function
*/
virtual void kill();
/**
* Update the entity
* \param clock The game's clock
*/
virtual void update(gdl::Clock const &clock);
/**
* Draw the entity on the screen
* \param shader The shader used to draw
* \param clock The game's clock
*/
virtual void draw(gdl::AShader &shader, gdl::Clock const &clock);
/**
* Serialize the entity
* \param out The stream to output the result
*/
virtual void serialize(std::ostream& out) const;
/**
* Unserialize the entity
* \param in The stream to read
*/
virtual void unserialize(std::istream& in);
private:
Box(const Box&);
Box& operator=(const Box&);
private:
unsigned int _percentDropBonus;
};
#endif
|
3f862371235bf6ab34f5ed3b5eb16a7b98bffe4b
|
9c69f7f7ae42c4df28201cf208beaea112398dc0
|
/gstmultimedialib/Multimedia/Multimedia/Filter/Sink/Video/XVideoImageSink.h
|
b231b82c4d606b5aaba1f072986d5961133d9ced
|
[
"BSD-4-Clause"
] |
permissive
|
alekstheod/gstmultimedialib
|
1cc2545b6f228f7b50658a2c217c6b949529fa72
|
ce9699e402d6870bf2724e09e89c03fe8a52fd16
|
refs/heads/master
| 2016-09-05T11:08:30.401766
| 2015-03-22T11:49:41
| 2015-03-22T11:49:41
| 32,673,295
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 572
|
h
|
XVideoImageSink.h
|
/*
* XVideoImageSink.h
*
* Created on: Feb 23, 2011
* Author: m1cRo
*/
#ifndef XVIDEOIMAGESINK_H_
#define XVIDEOIMAGESINK_H_
#include <Multimedia/Filter/BaseFilter/BaseSinkFilter.h>
namespace multimedia {
class XVideoImageSink: public multimedia::BaseSinkFilter {
public:
static const std::string CONST_PLUGIN_NAME;
public:
XVideoImageSink(const std::string& description) throw (GstException);
XVideoImageSink(const std::string& description, gulong xWindowId)
throw (GstException);
virtual ~XVideoImageSink();
};
}
#endif /* XVIDEOIMAGESINK_H_ */
|
ebd6dc82f1a0a8beff15153f5fd8ad2f1f76c43e
|
75b9e915c0614a48d5f7a5d14998ce05dc9921f2
|
/kernel/ide.h
|
50739a15ccbc4c2f64f52e6a6932ac981f134838
|
[] |
no_license
|
pato/patOS
|
bd2c6ea21cacd89a1c9f18db82ae6f8cf69573c1
|
e59c2b501a2125394e85dfaba45d1d6f9d9c4f9e
|
refs/heads/master
| 2020-06-06T11:28:09.987574
| 2014-12-13T08:09:14
| 2014-12-13T08:09:14
| 27,852,811
| 7
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 329
|
h
|
ide.h
|
#ifndef _IDE_H_
#define _IDE_H_
#include "block.h"
#include "semaphore.h"
class IDE : public BlockDevice {
int drive;
Mutex mutex;
public:
static constexpr uint32_t SECTOR_SIZE = 512;
IDE(int drive) : BlockDevice(SECTOR_SIZE), drive(drive) {}
void readBlock(uint32_t blockNumber, void* buffer);
};
#endif
|
8a131458dac24d3e7089c850ca87c72b2c288225
|
e4acfc74af19f692dd3e12220e6fab951a199b64
|
/components/uxvcos_navigation/src/models/FIX_POS_MEAS_MODEL_EULER_BFL.h
|
a2e874d12ccd23a47319c2379c971c1e143e00e0
|
[] |
no_license
|
tu-darmstadt-ros-pkg/uxvcos
|
222b1d4c84966a04cb9862e7055a612f151c6109
|
ac57278f57dc8060950b86a1ab188ff35acdb3cd
|
refs/heads/master
| 2021-01-23T08:39:30.890385
| 2013-08-01T17:37:37
| 2013-08-01T17:37:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,948
|
h
|
FIX_POS_MEAS_MODEL_EULER_BFL.h
|
//=================================================================================================
// Copyright (c) 2013, Johannes Meyer and contributors, Technische Universitat Darmstadt
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Flight Systems and Automatic Control group,
// TU Darmstadt, nor the names of its contributors may be used to
// endorse or promote products derived from this software without
// specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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.
//=================================================================================================
/*
* FIX_POS_MODEL_EULER_BFL.h
*/
#ifndef _FIX_POS_MODEL_EULER_BFL_
#define _FIX_POS_MODEL_EULER_BFL_
/**
* @brief First implementation of fix position measurement model with Orocos-BFL
*
* @author Martin Nowara
*
* @version 1.0
*
* @date 11/11/2010
*
*/
#include <bfl/wrappers/matrix/matrix_wrapper.h>
#include <bfl/pdf/analyticconditionalgaussian_additivenoise.h>
#include "INS_NED_EULER_BFL.h"
namespace uxvcos {
namespace Navigation
{
//--> Number of arguments arg0 = MeasurementVector [y]
#define NUM_COND_ARGUMENTS_MEASUREMENT_FIX_POS 1
#ifndef NUMBER_OF_MEASUREMENTS_FIX_POS
#define NUMBER_OF_MEASUREMENTS_FIX_POS 2
#endif
class FIX_POS_MEAS_MODEL_EULER_BFL : public BFL::AnalyticConditionalGaussianAdditiveNoise
{
public:
FIX_POS_MEAS_MODEL_EULER_BFL();
virtual ~FIX_POS_MEAS_MODEL_EULER_BFL();
//--> Measurement equation y = h(x)
virtual MatrixWrapper::ColumnVector ExpectedValueGet() const;
//--> Jacobian matrix H
virtual MatrixWrapper::Matrix dfGet(unsigned int i) const;
};
}
#endif
} // namespace uxvocs
|
504624f2886c6caec4570b1a844ed12db018fda6
|
d76e86c698452a5b00e1a06ed5caaaae237429c2
|
/portable/ipc/BsdSocket.h
|
7b30adc8cbdb569017ef0e9947e9c69ac41de31e
|
[
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"MIT"
] |
permissive
|
asokolsky/libunistd
|
90e38718f451a3482a6fe880da3b87b79a7cf7d8
|
8002a231e913e56726369d4901486dc7318391f6
|
refs/heads/master
| 2020-05-16T19:59:20.055857
| 2019-04-24T01:02:39
| 2019-04-24T01:02:39
| 183,275,391
| 1
| 0
|
MIT
| 2019-04-24T17:22:41
| 2019-04-24T17:22:41
| null |
UTF-8
|
C++
| false
| false
| 3,381
|
h
|
BsdSocket.h
|
// portable/BsdSocket.h
// Created by Robin Rowe on 11/27/2015
// Copyright (c) 2015 Robin.Rowe@CinePaint.org
// License open source MIT
#ifndef BsdSocket_h
#define BsdSocket_h
#include <thread>
#include <memory.h>
#include <string>
#include <memory>
#include <vector>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "../MsgBuffer.h"
#include "../AtomicCounter.h"
#include "../VerboseCounter.h"
#include "../SystemLog.h"
#include "../time/Timestamp.h"
#pragma warning(disable:4265)
namespace portable
{
class BsdSocket
{protected:
SOCKET socketfd;
int bytesRead;
bool isVerbose;
bool isTrace;
bool isAutoClose;
sockaddr_in server_sockaddr;
virtual int OpenSocket()
{ TRACE("OpenSocket not implemented");
return 0;
}
virtual void OnSocketError(const char* filename,int lineno,const char* msg)
{ if(!isVerbose)
{ return;
}
portable::SystemLog(filename,lineno,msg);
}
void Trace(const char* msg)
{ if(!isTrace)
{ return;
}
portable::Timestamp now;
const char* t = now.toString();
printf("TRACE SOCKET(%s): %s\n",t,msg);
}
void Trace(const char* function,const char* msg,int length)
{ if(!isTrace)
{ return;
}
portable::Timestamp now;
const char* t = now.toString();
printf("TRACE SOCKET %s(%s): %.*s[%i]\n", function,t,length,msg,length);
}
void TraceOpen(const char* serverName,int port)
{ if(!isTrace)
{ return;
}
portable::Timestamp now;
const char* t = now.toString();
printf("TRACE SOCKET OPEN %s:%i @ %s\n",serverName,port,t);
}
public:
BsdSocket(BsdSocket const&) = delete;
BsdSocket& operator=(BsdSocket const&) = delete;
virtual ~BsdSocket()
{ if(isAutoClose) // ok, not a temp copy
{ Close();
} }
BsdSocket()
: socketfd(0)
, bytesRead(0)
, isTrace(false)
, isVerbose(false)
, isAutoClose(true)
{}
BsdSocket(SOCKET socketfd)
: socketfd(socketfd)
, isTrace(false)
, isVerbose(false)
, isAutoClose(false)
{}
void SetVerbose(bool isVerbose = true)
{ this->isVerbose = isVerbose;
}
bool IsVerbose() const
{ return isVerbose;
}
void SetTrace(bool isTrace = true)
{ this->isTrace = isTrace;
}
bool IsTrace() const
{ return isTrace;
}
bool IsOpen() const
{ return socketfd > 0;
}
bool Send(const char* s)
{ if(!s)
{ return false;
}
const unsigned len = (unsigned) strlen(s);
return SendTo(s,len);
}
void SocketReset(const char* msg = nullptr)
{ socketfd=0;
if(isVerbose)
{ puts("Socket Reset");
}
if(msg)
{ puts(msg);
} }
void GetPeerName(std::string& s) const
{ return GetPeerName(socketfd,s);
}
static bool SetReuse(SOCKET socketfd,int isReuse=1)
{ const char* p = (const char*) &isReuse;
const int size = sizeof(int);
const int status = setsockopt(socketfd,SOL_SOCKET,SO_REUSEADDR,p,size);
return status > 0;
}
bool SendEmptyPacket()
{ if(isTrace)
{ Trace("Send Empty Packet");
}
return SendTo("", 0);
}
int BytesRead() const
{ return bytesRead;
}
static bool GetIp(const char* hostname,std::string& ip);
static void GetPeerName(SOCKET sock, std::string& s);
bool SetAsyncMode(bool isAsync = true);
bool Open(const char* serverName, int serverPort);
bool Connect();
bool Bind();
// bool SetTimeout(unsigned secondsTimeout);// Call before Bind()
virtual void Close();
bool SendTo(const char* msg,unsigned len);
int RecvFrom(char* buffer,unsigned bufsize,unsigned offset=0);
};
}
#endif
|
3fa41bd1ad7b8a09c25e33a86c0fad88c32e53df
|
8d1561db8546b3a62eaacc1a85e01331667665e5
|
/final_project/Arduino/libraries/ColorSensor/ColorSensor.cpp
|
9519e3556fbadc990bc41bad3b7791c363f16099
|
[] |
no_license
|
ayou7995/Embedded-Experiment
|
50434bbca125b1ceb55539081fc31b205c359932
|
93923535e210fc5d7310178628a55772844624b2
|
refs/heads/master
| 2021-01-19T00:24:33.750161
| 2017-06-16T11:45:48
| 2017-06-16T11:45:48
| 86,575,222
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,886
|
cpp
|
ColorSensor.cpp
|
/*
ColorSensor.cpp - Library for White Balence and Detecting Color.
Created by ayou7995, June 11, 2017.
Released into the public domain.
*/
#include <TimerOne.h>
#include "Arduino.h"
#include "ColorSensor.h"
//#define HIGH 1
//#define LOW 0
int count = 0; // 頻率計算
int rgb[3]; // 儲存 RGB 值
int flag = 0; // RGB 過濾順序
float SF[3]; // 儲存白平衡計算後之 RGB 補償係數
int _S0 = 0;
int _S1 = 0;
int _S2 = 0;
int _S3 = 0;
int _OUT = 0;
void TSC_Init(int S0, int S1, int S2, int S3, int OUT){
pinMode(S0, OUTPUT);
pinMode(S1, OUTPUT);
pinMode(S2, OUTPUT);
pinMode(S3, OUTPUT);
pinMode(OUT, INPUT);
_S0 = S0;
_S1 = S1;
_S2 = S2;
_S3 = S3;
_OUT = OUT;
}
void TSC_setup(){
Serial.println("TCS setting up...");
digitalWrite(_S0, LOW); // OUTPUT FREQUENCY SCALING 2%
digitalWrite(_S1, HIGH);
count = 0;
flag = 0;
Timer1.initialize(); // defaulte is 1s
Timer1.attachInterrupt(TSC_Callback);
attachInterrupt(0, TSC_Count, RISING);
delay(4000);
for(int i=0; i<3; i++) {
Serial.println(String(rgb[i])+" -> 255");
}
SF[0] = 255.0 / rgb[0]; // R 補償係數
SF[1] = 255.0 / rgb[1] ; // G 補償係數
SF[2] = 255.0 / rgb[2] ; // B 補償係數
Serial.println("Compensate coefficient : ");
Serial.println("R: "+String(SF[0]));
Serial.println("G: "+String(SF[1]));
Serial.println("B: "+String(SF[2]));
//for (int i=0; i<3; i++) {
//Serial.println(int(rgb[i]*SF[i]));
//}
}
void TSC_Count(){
count ++ ;
}
void TSC_Callback(){
switch(flag)
{
case 0:
Serial.println("->WB Start");
TSC_WB(LOW, LOW); // Red
break;
case 1:
Serial.print("->Frequency R=");
Serial.println(count);
rgb[0] = count;
TSC_WB(HIGH, HIGH); // Green
break;
case 2:
Serial.print("->Frequency G=");
Serial.println(count);
rgb[1] = count;
TSC_WB(LOW, HIGH); // Blue
break;
case 3:
Serial.print("->Frequency B=");
Serial.println(count);
Serial.println("->WB End");
rgb[2] = count;
TSC_WB(HIGH, LOW); // Clear(no filter)
break;
default:
count = 0;
break;
}
}
void TSC_WB(int Level0, int Level1){
count = 0;
flag ++;
TSC_FilterColor(Level0, Level1);
Timer1.setPeriod(1000000); // us; 每秒觸發
}
void TSC_FilterColor(int Level01, int Level02){
if(Level01 != 0){
Level01 = HIGH;
}
if(Level02 != 0){
Level02 = HIGH;
}
digitalWrite(_S2, Level01);
digitalWrite(_S3, Level02);
}
String TSC_DetectColor(){
Serial.println("Inside TSC_DetectColor");
int detect[3] = {0, 0, 0};
int real_rgb[3] = {-1, -1, -1};
for(int i=0; i<4; i++){
flag = 0;
count = 0;
for(int j=0; j<3; j++){
//TSC_WB()
real_rgb[j] = rgb[j] * SF[j];
// Serial.println(int(rgb[j] * SF[j]));
}
Serial.println("");
Serial.print("detecting... ");
for (int j=0; j<3; j++) {
Serial.print(real_rgb[j]);
Serial.print(" ");
}
if (i>0) {
if (real_rgb[0]>real_rgb[1] && real_rgb[0]>real_rgb[2]) {
detect[0] ++;
}
else if (real_rgb[1]>real_rgb[0] && real_rgb[1]>real_rgb[2]) {
detect[1] ++;
}
else if (real_rgb[2]>real_rgb[0] && real_rgb[2]>real_rgb[1]) {
detect[2] ++;
}
}
delay(4000);
}
//Serial.println("detect color array");
//for (int i=0; i<3; i++) {
//Serial.print(detect[i]);
//Serial.print(" ");
//}
Serial.println();
Serial.print("The color detected is ");
if (detect[0]>=2) { Serial.println("red"); return "r";}
else if (detect[1]>=2) { Serial.println("green"); return "g";}
else if (detect[2]>=2) { Serial.println("blue"); return "b";}
else { Serial.println("nothing"); return "f";}
}
|
4297c85c456e6f309d5b68d0471fce4a6c19a53f
|
ee1c6b8f192c77e3c04476dc7733d910b67787b4
|
/week_8_cgal/1_antenna/antenna/main.cpp
|
11585a1c1efe05717639f49a05958139f7ebe466
|
[] |
no_license
|
akuendig/algolab
|
f6b8f2e971d73464a8bad21508aa6b1cac903134
|
fa0c61a64c7670fc57410f03b9d4f4b6e0b59a19
|
refs/heads/master
| 2016-09-06T07:39:02.180696
| 2013-01-23T17:44:55
| 2013-01-23T17:44:55
| 24,091,596
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,564
|
cpp
|
main.cpp
|
#include <CGAL/Exact_predicates_exact_constructions_kernel_with_sqrt.h>
#include <CGAL/Min_circle_2.h>
#include <CGAL/Min_circle_2_traits_2.h>
#include <iostream>
#include <vector>
#include <cmath>
typedef CGAL::Exact_predicates_exact_constructions_kernel_with_sqrt K;
typedef CGAL::Min_circle_2_traits_2<K> Min_Circle_Traits;
typedef CGAL::Min_circle_2<Min_Circle_Traits> Min_Circle;
using namespace std;
double floor_to_double(const K::FT& x)
{
double a = std::floor(CGAL::to_double(x));
while (a > x) a -= 1;
while (a+1 <= x) a += 1;
return a;
}
double ceil_to_double(const K::FT& x)
{
double a = std::ceil(CGAL::to_double(x));
while (a < x) a += 1;
while (a-1 >= x) a -= 1;
return a;
}
void testcases() {
vector<K::Point_2> points;
cout << fixed << setprecision(0);
while(true) {
int n;
cin >> n;
if (n <= 0)
break;
points.reserve(n);
for (int i=0; i <n; i++) {
// K::Point_2 p;
// cin >> p;
double x, y;
cin >>x >> y;
// p(x,y);
K::Point_2 p(x, y);
points.push_back(p);
}
Min_Circle mc(points.begin(), points.begin()+n, true);
Min_Circle_Traits::Circle c = mc.circle();
K::FT r = sqrt(c.squared_radius()); // you need Exact_predicates_exact_constructions_kernel_with_sqrt
cout << ceil_to_double(r) << endl;
points.clear();
}
}
int main()
{
cin.sync_with_stdio(false);
cout.sync_with_stdio(false);
testcases();
return 0;
}
|
1398b7ec00ca86bc6f91f7d88e2b5db6c3201f96
|
d58ea4adff736467d66a7634d42733fe07726df8
|
/trunk/WebKitTools/DumpRenderTree/bal/EditingDelegate.cpp
|
bca62878c7168ac7698f9fcea2be6b5be120c37f
|
[] |
no_license
|
explorer-ading/axSurface
|
3fc6334cf58d280e763d975faffff09bf47b4569
|
5cc1dd264c40925ec186efb2548cc541b8511bcc
|
refs/heads/master
| 2020-04-17T08:42:05.900900
| 2019-01-31T15:29:20
| 2019-01-31T15:29:20
| 166,422,212
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,253
|
cpp
|
EditingDelegate.cpp
|
/*
* Copyright (C) 2009 Pleyo. 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.
* 3. Neither the name of Pleyo nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY PLEYO AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL PLEYO OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "EditingDelegate.h"
#include "DumpRenderTree.h"
#include "LayoutTestController.h"
#include <string.h>
#include <string>
using std::string;
TransferSharedPtr<EditingDelegate> EditingDelegate::createInstance()
{
return new EditingDelegate();
}
EditingDelegate::EditingDelegate()
: m_acceptsEditing(true)
{
}
EditingDelegate::~EditingDelegate()
{
}
static const char* dump(DOMRange* range)
{
if (!range)
return 0;
int startOffset = range->startOffset();
int endOffset = range->endOffset();
DOMNode* startContainer = range->startContainer();
DOMNode* endContainer = range->endContainer();
if (startContainer && endContainer) {
char buffer[1024];
sprintf(buffer, "range from %d of %s to %d of %s", startOffset, dumpPath(startContainer).c_str(), endOffset, dumpPath(endContainer).c_str());
string buf = buffer;
return strdup(buf.c_str());
}
return 0;
}
bool EditingDelegate::shouldBeginEditingInDOMRange(WebView* webView, DOMRange* range)
{
if (::gLayoutTestController->dumpEditingCallbacks() && !done)
printf("EDITING DELEGATE: shouldBeginEditingInDOMRange:%s\n", dump(range));
return m_acceptsEditing;
}
bool EditingDelegate::shouldEndEditingInDOMRange(WebView* webView, DOMRange* range)
{
if (::gLayoutTestController->dumpEditingCallbacks() && !done)
printf("EDITING DELEGATE: shouldEndEditingInDOMRange:%s\n", dump(range));
return m_acceptsEditing;
}
bool EditingDelegate::shouldInsertNode(WebView* webView, DOMNode* node, DOMRange* range, WebViewInsertAction action)
{
static const char* insertactionstring[] = {
"WebViewInsertActionTyped",
"WebViewInsertActionPasted",
"WebViewInsertActionDropped",
};
if (::gLayoutTestController->dumpEditingCallbacks() && !done)
printf("EDITING DELEGATE: shouldInsertNode:%s replacingDOMRange:%s givenAction:%s\n", dumpPath(node).c_str(), dump(range), insertactionstring[action]);
return m_acceptsEditing;
}
bool EditingDelegate::shouldInsertText(WebView* webView, const char* text, DOMRange* range, WebViewInsertAction action)
{
static const char* insertactionstring[] = {
"WebViewInsertActionTyped",
"WebViewInsertActionPasted",
"WebViewInsertActionDropped",
};
if (::gLayoutTestController->dumpEditingCallbacks() && !done)
printf("EDITING DELEGATE: shouldInsertText:%s replacingDOMRange:%s givenAction:%s\n", text ? text : "", dump(range), insertactionstring[action]);
return m_acceptsEditing;
}
bool EditingDelegate::shouldDeleteDOMRange(WebView* webView, DOMRange* range)
{
if (::gLayoutTestController->dumpEditingCallbacks() && !done)
printf("EDITING DELEGATE: shouldDeleteDOMRange:%s\n", dump(range));
return m_acceptsEditing;
}
bool EditingDelegate::shouldChangeSelectedDOMRange(WebView* webView, DOMRange* currentRange, DOMRange* proposedRange, WebSelectionAffinity selectionAffinity, bool stillSelecting)
{
static const char* affinitystring[] = {
"NSSelectionAffinityUpstream",
"NSSelectionAffinityDownstream"
};
static const char* boolstring[] = {
"FALSE",
"TRUE"
};
if (::gLayoutTestController->dumpEditingCallbacks() && !done)
printf("EDITING DELEGATE: shouldChangeSelectedDOMRange:%s toDOMRange:%s affinity:%s stillSelecting:%s\n", dump(currentRange), dump(proposedRange), affinitystring[selectionAffinity], boolstring[stillSelecting]);
return m_acceptsEditing;
}
bool EditingDelegate::shouldApplyStyle(WebView* webView, DOMCSSStyleDeclaration* style, DOMRange* range)
{
if (::gLayoutTestController->dumpEditingCallbacks() && !done)
printf("EDITING DELEGATE: shouldApplyStyle:%s toElementsInDOMRange:%s\n", "'style description'", dump(range));
return m_acceptsEditing;
}
bool EditingDelegate::shouldChangeTypingStyle(WebView* webView, DOMCSSStyleDeclaration* currentStyle, DOMCSSStyleDeclaration* proposedStyle)
{
if (::gLayoutTestController->dumpEditingCallbacks() && !done)
printf("EDITING DELEGATE: shouldChangeTypingStyle:%s toStyle:%s\n", "'currentStyle description'", "'proposedStyle description'");
return m_acceptsEditing;
}
bool EditingDelegate::doPlatformCommand(WebView *webView, const char* command)
{
if (::gLayoutTestController->dumpEditingCallbacks() && !done)
printf("EDITING DELEGATE: doPlatformCommand:%s\n", command ? command : "");
return m_acceptsEditing;
}
void EditingDelegate::webViewDidBeginEditing()
{
if (::gLayoutTestController->dumpEditingCallbacks() && !done)
printf("EDITING DELEGATE: webViewDidBeginEditing:WebViewDidBeginEditingNotification\n");
}
void EditingDelegate::webViewDidChange()
{
if (::gLayoutTestController->dumpEditingCallbacks() && !done)
printf("EDITING DELEGATE: webViewDidChange:WebViewDidChangeNotification\n");
}
void EditingDelegate::webViewDidEndEditing()
{
if (::gLayoutTestController->dumpEditingCallbacks() && !done)
printf("EDITING DELEGATE: webViewDidEndEditing:WebViewDidEndEditingNotification\n");
}
void EditingDelegate::webViewDidChangeTypingStyle()
{
if (::gLayoutTestController->dumpEditingCallbacks() && !done)
printf("EDITING DELEGATE: webViewDidChangeTypingStyle:WebViewDidChangeTypingStyleNotification\n");
}
void EditingDelegate::webViewDidChangeSelection()
{
if (::gLayoutTestController->dumpEditingCallbacks() && !done)
printf("EDITING DELEGATE: webViewDidChangeSelection:WebViewDidChangeSelectionNotification\n");
}
bool EditingDelegate::shouldShowDeleteInterface(DOMHTMLElement* element)
{
return !strcmp(element->className(), "needsDeletionUI");
}
|
6c9ca518af5e47c84532870d49e35ac52be8d9f1
|
9ef582feefa39f7226dbc72a8f548c636b735b1f
|
/topovis/ttk/generated/ivw_ttkjacobiset.cpp
|
d1eaab1eeade242fca62501ec74fce5fe85490d1
|
[
"BSD-2-Clause"
] |
permissive
|
inviwo/modules
|
56f2dbb7c037da3a90dad438380efb352bc9dd35
|
c2f0f5d721d9aeed46184c76f65367ead45288c0
|
refs/heads/master
| 2023-08-27T09:47:56.993778
| 2023-08-15T18:06:00
| 2023-08-15T18:06:00
| 148,468,026
| 9
| 9
|
BSD-2-Clause
| 2023-09-11T08:20:19
| 2018-09-12T11:14:52
|
C++
|
UTF-8
|
C++
| false
| false
| 5,141
|
cpp
|
ivw_ttkjacobiset.cpp
|
#include "ivw_ttkjacobiset.h"
#include <inviwo/core/common/inviwomodule.h>
#include <inviwo/ttk/processors/ttkgenericprocessor.h>
#include <inviwo/core/properties/ordinalproperty.h>
#include <inviwo/core/properties/optionproperty.h>
#include <inviwo/core/properties/boolproperty.h>
#include <inviwo/core/properties/stringproperty.h>
#include <inviwo/core/properties/fileproperty.h>
#include <tuple>
#include <array>
#include <string_view>
#include <warn/push>
#include <warn/ignore/all>
#include "ttkJacobiSet.h"
#include <warn/pop>
namespace inviwo {
namespace ttkwrapper {
namespace {
#include <warn/push>
#include <warn/ignore/conversion>
struct Wrapper0 : FieldSelection {
bool set(ttkJacobiSet& filter) {
if (property.size() == 0) return false;
filter.SetInputArrayToProcess(0, 0, 0, 0, property.get().c_str());
return true;
}
OptionPropertyString property{"UComponent", "U Component", {}, 0};
static constexpr std::string_view inport = "Input";
};
struct Wrapper1 : FieldSelection {
bool set(ttkJacobiSet& filter) {
if (property.size() == 0) return false;
filter.SetInputArrayToProcess(1, 0, 0, 0, property.get().c_str());
return true;
}
OptionPropertyString property{"VComponent", "V Component", {}, 0};
static constexpr std::string_view inport = "Input";
};
struct Wrapper2 {
bool set(ttkJacobiSet& filter) {
filter.SetForceInputOffsetScalarField(property.get());
return true;
}
BoolProperty property{"Withpredefinedoffset", "Force Input Offset Field", false};
};
struct Wrapper3 : FieldSelection {
bool set(ttkJacobiSet& filter) {
if (property.size() == 0) return false;
filter.SetInputArrayToProcess(2, 0, 0, 0, property.get().c_str());
return true;
}
OptionPropertyString property{"UOffsetField", "U Offset Field", {}, 0};
static constexpr std::string_view inport = "Input";
};
struct Wrapper4 : FieldSelection {
bool set(ttkJacobiSet& filter) {
if (property.size() == 0) return false;
filter.SetInputArrayToProcess(3, 0, 0, 0, property.get().c_str());
return true;
}
OptionPropertyString property{"VOffsetField", "V Offset Field", {}, 0};
static constexpr std::string_view inport = "Input";
};
struct Wrapper5 {
bool set(ttkJacobiSet& filter) {
filter.SetEdgeIds(property.get());
return true;
}
BoolProperty property{"Withedgeidentifiers", "With edge identifiers", false};
};
struct Wrapper6 {
bool set(ttkJacobiSet& filter) {
filter.SetVertexScalars(property.get());
return true;
}
BoolProperty property{"Withvertexscalars", "With vertex scalars", false};
};
struct Wrapper7 {
bool set(ttkJacobiSet& filter) {
filter.SetUseAllCores(property.get());
return true;
}
BoolProperty property{"Debug_UseAllCores", "Use All Cores", true};
};
struct Wrapper8 {
bool set(ttkJacobiSet& filter) {
filter.SetThreadNumber(property.get());
return true;
}
IntProperty property{"Debug_ThreadNumber", "Thread Number", 1,
std::pair{1, ConstraintBehavior::Ignore},
std::pair{256, ConstraintBehavior::Ignore}};
};
struct Wrapper9 {
bool set(ttkJacobiSet& filter) {
filter.SetDebugLevel(property.get());
return true;
}
IntProperty property{"Debug_DebugLevel", "Debug Level", 3,
std::pair{0, ConstraintBehavior::Ignore},
std::pair{5, ConstraintBehavior::Ignore}};
};
struct Wrapper10 {
bool set(ttkJacobiSet& filter) {
filter.SetCompactTriangulationCacheSize(property.get());
return true;
}
DoubleProperty property{"CompactTriangulationCacheSize", "Cache", 0.2,
std::pair{0.0, ConstraintBehavior::Ignore},
std::pair{1.0, ConstraintBehavior::Ignore}};
};
#include <warn/pop>
} // namespace
template <>
struct TTKTraits<ttkJacobiSet> {
static constexpr std::string_view identifier = "ttkJacobiSet";
static constexpr std::string_view displayName = "TTK JacobiSet";
inline static std::array<InputData, 1> inports = {InputData{"Input", "vtkDataSet", 1}};
inline static std::array<OutputData, 0> outports = {};
inline static std::array<Group, 3> groups = {
Group{"Testing",
{"Debug_UseAllCores", "Debug_ThreadNumber", "Debug_DebugLevel",
"CompactTriangulationCacheSize", "Debug_Execute"}},
Group{"Input options",
{"U Component", "V Component", "With predefined offset", "U Offset Field",
"V Offset Field"}},
Group{"Output options", {"With edge identifiers", "With vertex scalars"}}};
std::tuple<Wrapper0, Wrapper1, Wrapper2, Wrapper3, Wrapper4, Wrapper5, Wrapper6, Wrapper7,
Wrapper8, Wrapper9, Wrapper10>
properties;
};
void registerttkJacobiSet(InviwoModule* module) {
module->registerProcessor<TTKGenericProcessor<ttkJacobiSet>>();
}
} // namespace ttkwrapper
} // namespace inviwo
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.