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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
53789223973e729d8fc411479b255d059f7af966 | 0b86bd8883aa139ce220483f014cd3a11f102e62 | /source/GRID.cpp | 1d2173cc543471e03e0196e159108b22d8386707 | [] | no_license | iammalekI/mpm_lab_2d | 8d21fb48d5fb8d232dcc02a9f8076dd4835fc863 | 6670b03c55edc2602fcff7fcafae7034a7273ca6 | refs/heads/master | 2020-06-10T20:56:04.198184 | 2018-02-22T20:46:29 | 2018-02-22T20:46:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 52,702 | cpp | GRID.cpp | //
// Created by Martin Rodriguez Cruz on 3/7/17.
//
#include <vector>
#include "../Eigen/Dense"
#include "../include/GRID.h"
#include "../include/INTERPOLATION.h"
#include "../include/ELASTOPLASTIC.h"
#include <iostream>
#include <math.h>
using namespace std;
using namespace Eigen;
/***********************************************************************************************************************
*
* THIS IS ALL THE GRID PARAMETERS AND STUFF
*
**********************************************************************************************************************/
void GRID::SetDefaultGrid() {
m_nx = 64;
m_ny = m_nx;
m_xmin = (double) 0;
m_xmax = (double) 1;
m_ymin = m_xmin;
m_ymax = m_xmax;
m_h = (m_xmax - m_xmin)/(m_nx - 1);
mass.reserve(m_nx*m_ny);
position.reserve(m_nx*m_ny);
velocity.reserve(m_nx*m_ny);
newVelocity.reserve(m_nx*m_ny);
force.reserve(m_nx*m_ny);
InitializeGrid();
}
int GRID::Index2D(const int i, const int j) {
return i*m_ny + j;
}
double GRID::GetGridSpacing() {
return m_h;
}
double GRID::Getxmin() {
return m_xmin;
}
double GRID::Getymin() {
return m_ymin;
}
double GRID::Getxmax() {
return m_xmax;
}
int GRID::GetN() {
return m_nx;
}
void GRID::InitializeMassGrid() {
for (int i = 0; i < m_nx*m_ny; i++){
mass.push_back((double) 0);
}
}
void GRID::InitializePositionGrid() {
for (int i = 0; i < m_nx; i++){
for (int j = 0; j < m_ny; j++){
position.push_back( Vector2d( i*m_h, j*m_h) );
}
}
}
void GRID::InitializeVelocityGrid() {
for (int i = 0; i < m_nx*m_ny; i++){
velocity.push_back( Vector2d (0, 0) );
newVelocity.push_back( Vector2d (0, 0) );
}
}
void GRID::InitializeForceGrid() {
for (int i = 0; i < m_nx*m_ny; i++){
force.push_back( Vector2d (0, 0) );
}
}
void GRID::InitializeGrid() {
InitializePositionGrid();
InitializeVelocityGrid();
InitializeMassGrid();
InitializeForceGrid();
}
/***********************************************************************************************************************
*
* THIS IS ALL THE GRID COMPUTATION FUNCTIONS
*
**********************************************************************************************************************/
void GRID::ComputeGridNodeWeights( vector<Vector2d>& positionParticle, INTERPOLATION& Interpolation ){
VectorXd wip;
wip = VectorXd::Zero(positionParticle.size(),1);
for (int i = 0; i < GetN(); i++){
for (int j = 0; j < GetN(); j++){
for (int p = 0; p < positionParticle.size(); p ++){
wip[p] = Interpolation.Weight(m_h, positionParticle[p], i, j);
}
if (wip.norm() != 0){
nodeWeights.push_back(wip);
nodeWeightsList.push_back( Vector2i(i,j) );
}
wip = VectorXd::Zero(positionParticle.size(),1);
}
}
/*for (int p = 0; p < positionParticle.size(); p++){
for (int i = 0; i < GetN(); i++){
for (int j = 0; j < GetN(); j++){
wip[p] = Interpolation.Weight(m_h, positionParticle[p], i, j);
}
}
}*/
}
void GRID::ComputeNeighborhood(Vector2d& positionParticle, Vector2i& gridIndexCenter, Vector2i& minGridIndex, Vector2i& maxGridIndex){
Vector2i radius(3,3);
gridIndexCenter.x() = floor( ( positionParticle.x() - Getxmin() ) / m_h ) ;
gridIndexCenter.y() = floor( ( positionParticle.y() - Getymin() ) / m_h );
minGridIndex.x() = gridIndexCenter.x() - radius.x();
minGridIndex.y() = gridIndexCenter.y() - radius.y();
maxGridIndex.x() = gridIndexCenter.x() + radius.x();
maxGridIndex.y() = gridIndexCenter.y() + radius.y();
if ( minGridIndex.x() < 0 ){
minGridIndex.x() = 0;
}
if (minGridIndex.y() < 0) {
minGridIndex.y() = 0;
}
if ( maxGridIndex.x() > GetN() ){
maxGridIndex.x() = GetN();
}
if( maxGridIndex.y() > GetN() ){
maxGridIndex.y() = GetN();
}
}
void GRID::ParticleToGrid( vector<double>& massParticle, vector<Vector2d>& positionParticle, vector<Vector2d>& velocityParticle, INTERPOLATION& Interpolation) {
clock_t begin_P2G = clock();
// double massWeighted = 0;
// Vector2d momentumWeighted = Vector2d (0, 0);
//
//
// for (int i = 0; i < nodeWeightsList.size(); i++){
//
// // Setting the node indices to something easier to type
// int iw = nodeWeightsList[i].x();
// int jw = nodeWeightsList[i].y();
//
// for (int p = 0; p < massParticle.size(); p++){
//
// massWeighted += massParticle[p]*nodeWeights[i][p];
// momentumWeighted.x() += velocityParticle[p].x()*massParticle[p]*nodeWeights[i][p];
// momentumWeighted.y() += velocityParticle[p].y()*massParticle[p]*nodeWeights[i][p];
// }
//
//
// // cout << "Weighted Mass = " << massWeighted << endl;
//
// mass[ Index2D(iw, jw) ] = massWeighted;
// if (mass[ Index2D(iw, jw)] != 0 ){
// velocity[Index2D(iw, jw)].x() = momentumWeighted.x()/mass[Index2D(iw, jw)];
// velocity[Index2D(iw, jw)].y() = momentumWeighted.y()/mass[Index2D(iw, jw)];
// }
//
// massWeighted = 0;
// momentumWeighted = Vector2d (0, 0);
//
//
//
// }
for (int p = 0; p < massParticle.size(); p++){
Vector2i minGridIndex, maxGridIndex, centerIndex;
ComputeNeighborhood(positionParticle[p], centerIndex, minGridIndex, maxGridIndex);
int imin = minGridIndex.x();
int jmin = minGridIndex.y();
int imax = maxGridIndex.x();
int jmax = maxGridIndex.y();
int ig = centerIndex.x();
int jg = centerIndex.y();
// if (p == 0){
// cout << "Center Index P2G = "<< centerIndex.transpose() << endl;
// }
double totalWip = 0;
for (int i = imin; i < imax; i++){
for (int j = jmin; j < jmax; j++){
double wip = Interpolation.Weight(m_h, positionParticle[p], i, j);
// if (wip < 0){
// wip = 0;
// }
// cout << "wip at node (" << i << ", " << j << ") = " << wip << endl;
totalWip += wip;
mass[ Index2D(ig,jg) ] += massParticle[p] * wip;
velocity[ Index2D(ig,jg) ] += velocityParticle[p]*massParticle[p] * wip;
}
}
if( fabs(totalWip - 1) > 1e-6){
cout << "Particle p = " << p << endl;
cout << "Particle Position = " << positionParticle[p].transpose() << endl;
cout << "Total wip = " << totalWip << endl;
cout << "Center Index = " << centerIndex.transpose() << endl;
cout << "Max Grid Index = " << maxGridIndex.transpose() << endl;
cout << "Min Grid Index = " << minGridIndex.transpose() << endl;
cin.get();
}
}
clock_t end_P2G = clock();
double totalTime = double(end_P2G - begin_P2G)/CLOCKS_PER_SEC;
// cout << "Time for P2G = " << totalTime << " seconds." << endl;
/* double wip = 0;
double massWeighted = 0;
Vector3d momentumWeighted = Vector3d (0, 0, 0);
for (int i = 0; i < GetN(); i++){
for (int j = 0; j < GetN(); j++){
for (int k = 0; k < GetN(); k++){
for (int p = 0; p < massParticle.size(); p++){
wip = Interpolation.Weight(m_h, positionParticle[p], i, j, k);
massWeighted += massParticle[p]*wip;
momentumWeighted.x() += velocityParticle[p].x()*massParticle[p]*wip;
momentumWeighted.y() += velocityParticle[p].y()*massParticle[p]*wip;
momentumWeighted.z() += velocityParticle[p].z()*massParticle[p]*wip;
}
mass[Index3D(i,j,k)] = massWeighted;
if (mass[Index3D(i,j,k)] != 0 ){
velocity[Index3D(i,j,k)].x() = momentumWeighted.x()/mass[Index3D(i,j,k)];
velocity[Index3D(i,j,k)].y() = momentumWeighted.y()/mass[Index3D(i,j,k)];
velocity[Index3D(i,j,k)].z() = momentumWeighted.z()/mass[Index3D(i,j,k)];
}
wip = 0;
massWeighted = 0;
momentumWeighted = Vector3d (0, 0, 0);
}
}
}*/
}
void GRID::NodesWithMass() {
/*for (int i = 0; i < GetN(); i++){
for (int j = 0; j < GetN(); j++){
for (int k = 0; k < GetN(); k++){
if (mass[Index3D(i,j,k)] != 0 ){
massList.push_back(Vector3i(i,j,k));
}
}
}
}*/
for (int i = 0; i < GetN(); i++){
for (int j = 0; j < GetN(); j++){
if (mass[Index2D(i,j)] != 0){
velocity[Index2D(i,j)] = velocity[Index2D(i,j)]/mass[Index2D(i,j)];
massList.push_back(Vector2i(i,j));
}
}
}
//massList = nodeWeightsList;
// cout << "Length of massList = " << massList.size() << endl;
}
void GRID::ComputeGridForces(bool usePlasticity, double mu0, double lambda0, double hardeningCoeff, vector<double>& JElastic, vector<double>& JPlastic,
vector<double>& volumeParticle, vector<Vector2d>& positionParticle, vector<Matrix2d>& cauchyStress,
vector<Matrix2d>& elasticDeformationGradient, vector<Matrix2d>& RE, vector<Matrix2d>& SE, ELASTOPLASTIC& ConstitutiveModel, INTERPOLATION& Interpolation) {
clock_t begin_P2G = clock();
ConstitutiveModel.CauchyStress(usePlasticity, mu0, lambda0, hardeningCoeff, cauchyStress, JElastic, JPlastic, elasticDeformationGradient, RE, SE);
// for (int p = 0; p < cauchyStress.size(); p++ ){
//
// cout << "-------------------------------------" << endl;
// cout << cauchyStress[p] << endl;
// cout << "......................" << endl;
// cout << "Norm of sigma = " << cauchyStress[p].norm() << endl;
//
// }
// cin.get();
// commented out
// cout << SIGMA[1] << endl;
//for (int i = 0; i < massList.size(); i++){
// int ig, jg;
// ig = massList[i].x();
// jg = massList[i].y();
//
//
// Vector2d FORCE;
// FORCE = Vector2d::Zero();
for (int p = 0; p < JElastic.size(); p++){
Vector2i minGridIndex, maxGridIndex, centerIndex;
ComputeNeighborhood(positionParticle[p], centerIndex, minGridIndex, maxGridIndex);
int imin = minGridIndex.x();
int jmin = minGridIndex.y();
int imax = maxGridIndex.x();
int jmax = maxGridIndex.y();
int ig = centerIndex.x();
int jg = centerIndex.y();
// if (p == 0){
// cout << "Center Index ForceUpdate = "<< centerIndex.transpose() << endl;
// }
Vector2d totalDWIP = Vector2d(0,0);
for (int i = imin; i < imax; i++){
for (int j = jmin; j < jmax; j++){
Vector2d d_wip = Interpolation.GradientWeight(m_h, positionParticle[p], i, j);
force[ Index2D(ig,jg) ] += -JElastic[p]*JPlastic[p]*volumeParticle[p]*cauchyStress[p]*d_wip;
totalDWIP += d_wip;
}
}
// cout << "Total Dwip = " << totalDWIP.transpose() << endl;
// FORCE += -JElastic[p]*JPlastic[p]*volumeParticle[p]*cauchyStress[p]*Interpolation.GradientWeight(m_h, positionParticle[p], ig, jg);
}
// cin.get();
clock_t end_P2G = clock();
double totalTime = double(end_P2G - begin_P2G)/CLOCKS_PER_SEC;
// cout << "Time for Force Update = " << totalTime << " seconds." << endl;
//force.push_back(FORCE);
//} // END MASS LIST FOR LOOP
}
void GRID::AddGravityForce(Vector2d& gravity) {
for (int i = 0; i < massList.size(); i++){
int ig, jg;
ig = massList[i].x();
jg = massList[i].y();
force[Index2D(ig, jg)].x() += mass[ Index2D(ig, jg) ]*gravity.x();
force[Index2D(ig, jg)].y() += mass[ Index2D(ig, jg) ]*gravity.y();
}
}
void GRID::UpdateVelocityGrid(double timeStep) {
for (int i = 0; i < massList.size(); i++){
int ig, jg;
ig = massList[i].x();
jg = massList[i].y();
// newVelocity[ Index2D(ig, jg) ].x() = velocity[ Index2D(ig, jg) ].x() + timeStep*force[ Index2D(ig, jg) ].x()/mass[ Index2D(ig, jg) ];
// newVelocity[ Index2D(ig, jg) ].y() = velocity[ Index2D(ig, jg) ].y() + timeStep*force[ Index2D(ig, jg) ].y()/mass[ Index2D(ig, jg) ];
newVelocity[ Index2D(ig,jg) ] = velocity[Index2D(ig,jg)] + timeStep*force[Index2D(ig,jg)]/mass[Index2D(ig,jg)];
}
}
void GRID::UpdateGravityVelocityGrid(const double timeStep, const Vector2d& gravity) {
for (int i = 0; i < massList.size(); i++){
int ig, jg;
ig = massList[i].x();
jg = massList[i].y();
newVelocity[ Index2D(ig, jg) ] += timeStep*gravity;
}
}
///////////////////////////////////////////////////////////////////
void GRID::UpdateDeformationGradient(bool usePlasticity, double timeStep, double criticalStretch, double criticalCompression, vector<double>& JElastic,
vector<double>& JPlastic, vector<Vector2d>& positionParticle, vector<Matrix2d>& elasticDeformationGradient,
vector<Matrix2d>& plasticDeformationGradient, vector<Matrix2d>& deformationGradient,
INTERPOLATION& Interpolation) {
double dt = timeStep;
for (int p = 0; p < positionParticle.size(); p++){
Vector2i minGridIndex, maxGridIndex, centerIndex;
ComputeNeighborhood(positionParticle[p], centerIndex, minGridIndex, maxGridIndex);
int imin = minGridIndex.x();
int jmin = minGridIndex.y();
int imax = maxGridIndex.x();
int jmax = maxGridIndex.y();
int ig = centerIndex.x();
int jg = centerIndex.y();
// if (p == 0){
// cout << "Center Index UpdateDeformationGradient = "<< centerIndex.transpose() << endl;
// }
Matrix2d velocity_Gradient;
velocity_Gradient = Matrix2d::Zero();
for (int i = imin; i < imax; i++){
for (int j = jmin; j < jmax; j++){
Vector2d d_wip = Interpolation.GradientWeight(m_h, positionParticle[p], i, j);
velocity_Gradient += newVelocity[ Index2D(ig, jg) ]*d_wip.transpose();
}
}
// for ( int i = 0; i < massList.size(); i++ ) {
// int ig, jg;
// Matrix2d velocity_Gradient, A;
// ig = massList[i].x();
// jg = massList[i].y();
// gradientWeight = Interpolation.GradientWeight(m_h, positionParticle[p], ig, jg);
// A = newVelocity[ Index2D(ig, jg) ]*gradientWeight.transpose();
//
//
// // cout << "Iteration = " << i << endl;
// // cout << " Velocity Vector: " << endl;
// // cout << velocityGrid[ GridNodes.Index3D(ig, jg, kg) ] << endl;
// //
// // cout << "Gradient Weight: " << endl;
// // cout << gradientWeight.transpose() << endl;
//
// velocity_Gradient += A ;
//
// // cout << "Check :\n " << velocityGrid[ GridNodes.Index3D(ig, jg, kg) ]*gradientWeight.transpose() << endl;
// // cout << "Gradient Velocity : " << endl;
// // cout << velocity_Gradient << endl;
// // cout << " " << endl;
// } // END WEIGHT INTERPOLATION TRANSFER
Matrix2d FE_hat, FP_hat, F_hat;
FE_hat = Matrix2d::Zero();
FP_hat = Matrix2d::Zero();
F_hat = Matrix2d::Zero();
FE_hat = elasticDeformationGradient[p] + dt*velocity_Gradient*elasticDeformationGradient[p];
FP_hat = plasticDeformationGradient[p];
F_hat = FE_hat*FP_hat;
JacobiSVD<Matrix2d> svd(FE_hat, ComputeFullU | ComputeFullV);
Matrix2d sigmaMatrix;
sigmaMatrix = svd.singularValues().asDiagonal();
if ( usePlasticity == true ){
sigmaMatrix = Clamp( sigmaMatrix, criticalStretch, criticalCompression );
elasticDeformationGradient[p] = svd.matrixU()*sigmaMatrix*svd.matrixV().transpose();
plasticDeformationGradient[p] = svd.matrixV()*sigmaMatrix.inverse()*svd.matrixU().transpose()*F_hat;
}
else{
elasticDeformationGradient[p] = svd.matrixU()*sigmaMatrix*svd.matrixV().transpose();
plasticDeformationGradient[p] = Matrix2d::Identity(); // svd.matrixV()*sigmaMatrix.inverse()*svd.matrixU().transpose()*F_hat;
}
/*cout << "Elastic Deformaiton Gradient = \n" << elasticDeformationGradient[p] << endl;
cout << "Platic Deformation Gradient = \n" << plasticDeformationGradient[p] << endl;
cout << "Deformation Gradient = \n" << elasticDeformationGradient[p]*plasticDeformationGradient[p] << endl;*/
deformationGradient[p] = elasticDeformationGradient[p]*plasticDeformationGradient[p];
JElastic[p] = elasticDeformationGradient[p].determinant();
JPlastic[p] = plasticDeformationGradient[p].determinant();
} // END PARTICLE LOOP
}
//
// void GRID::UpdateDeformationGradient(bool usePlasticity, double timeStep, double criticalStretch, double criticalCompression, vector<double>& JElastic,
// vector<double>& JPlastic, vector<Vector2d>& positionParticle, vector<Matrix2d>& elasticDeformationGradient,
// vector<Matrix2d>& plasticDeformationGradient, vector<Matrix2d>& deformationGradient,
// INTERPOLATION& Interpolation) {
//
//
// double dt = timeStep;
//
// for (int p = 0; p < positionParticle.size(); p++){
//
// Vector2d gradientWeight;
// Matrix2d velocity_Gradient, A;
// velocity_Gradient = Matrix2d::Zero();
// A = Matrix2d::Zero();
//
//
//
// for ( int i = 0; i < massList.size(); i++ ) {
// int ig, jg;
// ig = massList[i].x();
// jg = massList[i].y();
// gradientWeight = Interpolation.GradientWeight(m_h, positionParticle[p], ig, jg);
// A = newVelocity[ Index2D(ig, jg) ]*gradientWeight.transpose();
//
//
// // cout << "Iteration = " << i << endl;
// // cout << " Velocity Vector: " << endl;
// // cout << velocityGrid[ GridNodes.Index3D(ig, jg, kg) ] << endl;
// //
// // cout << "Gradient Weight: " << endl;
// // cout << gradientWeight.transpose() << endl;
//
// velocity_Gradient += A ;
//
// // cout << "Check :\n " << velocityGrid[ GridNodes.Index3D(ig, jg, kg) ]*gradientWeight.transpose() << endl;
// // cout << "Gradient Velocity : " << endl;
// // cout << velocity_Gradient << endl;
// // cout << " " << endl;
// } // END WEIGHT INTERPOLATION TRANSFER
//
// Matrix2d FE_hat, FP_hat, F_hat;
// FE_hat = Matrix2d::Zero();
// FP_hat = Matrix2d::Zero();
// F_hat = Matrix2d::Zero();
//
// FE_hat = elasticDeformationGradient[p] + dt*velocity_Gradient*elasticDeformationGradient[p];
// FP_hat = plasticDeformationGradient[p];
//
// F_hat = FE_hat*FP_hat;
//
// JacobiSVD<Matrix2d> svd(FE_hat, ComputeFullU | ComputeFullV);
// Matrix2d sigmaMatrix;
//
//
// sigmaMatrix = svd.singularValues().asDiagonal();
// if ( usePlasticity == true ){
// sigmaMatrix = Clamp( sigmaMatrix, criticalStretch, criticalCompression );
// elasticDeformationGradient[p] = svd.matrixU()*sigmaMatrix*svd.matrixV().transpose();
// plasticDeformationGradient[p] = svd.matrixV()*sigmaMatrix.inverse()*svd.matrixU().transpose()*F_hat;
// }
// else{
// elasticDeformationGradient[p] = svd.matrixU()*sigmaMatrix*svd.matrixV().transpose();
// plasticDeformationGradient[p] = Matrix2d::Identity(); // svd.matrixV()*sigmaMatrix.inverse()*svd.matrixU().transpose()*F_hat;
// }
//
//
// /*cout << "Elastic Deformaiton Gradient = \n" << elasticDeformationGradient[p] << endl;
// cout << "Platic Deformation Gradient = \n" << plasticDeformationGradient[p] << endl;
// cout << "Deformation Gradient = \n" << elasticDeformationGradient[p]*plasticDeformationGradient[p] << endl;*/
//
// deformationGradient[p] = elasticDeformationGradient[p]*plasticDeformationGradient[p];
// JElastic[p] = elasticDeformationGradient[p].determinant();
// JPlastic[p] = plasticDeformationGradient[p].determinant();
//
//
// } // END PARTICLE LOOP
//
//
//
//
// }
//
void GRID::ClearEulerianFields() {
massList.erase( massList.begin(), massList.end() );
// force.erase( force.begin(), force.end() );
nodeWeights.erase(nodeWeights.begin(), nodeWeights.end() );
nodeWeightsList.erase(nodeWeightsList.begin(),nodeWeightsList.end() );
for (int i = 0; i < velocity.size(); i ++ ){
mass[i] = (double) 0;
velocity[i] = Vector2d (0, 0 );
newVelocity[i] = Vector2d (0, 0);
force[i] = Vector2d(0,0);
}
}
Matrix2d GRID::Clamp(Matrix2d &principalValues, double criticalStretch, double criticalCompression) {
for (int i = 0; i < 2; i++){
if ( principalValues(i,i) < 1-criticalCompression ){
principalValues(i,i) = 1-criticalCompression;
}
else if ( principalValues(i,i) > 1+criticalStretch ){
principalValues(i,i) = 1+criticalStretch;
}
}
Matrix2d A;
A = principalValues;
return A;
}
/////////////////////////////////////////////////////////////////////////////////////
// IMPLICIT TIME INTEGRATION MODULE
// SOLVES SYSTEM OF EQUATION DESCRIBED BY EQUATION (9) IN STOMAKHIN ET AL. 2013.
// ALSO DESCRIBED IN THESIS - SEMI IMPLICIT INTEGRATION SYSTEM
//
// SUBMODULES:
// 1. COMPUTE deltaF
// 2. COMPUTE delta_JF_iT
// 3. COMPUTE delta_R
// 4. COMPUTE Ap
//
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
// PERFORM THIS AFTER COMPUTING THE EXPLICIT UPDATE
// EXPLICIT UPDATE SHOULD BE YOUR INITIAL GUESS
//////////////////////////////////////////////////////////
void GRID::ImplicitUpdateVelocityGrid(const bool usePlasticity, const double beta, const double dt, const double mu0, const double lambda0, const double hardeningCoeff, vector<double>& JE, vector<double>& JP, const vector<double>& particleVolume, const vector<Vector2d>& positionParticle, const vector<Matrix2d>& FE, const vector<Matrix2d>& R, const vector<Matrix2d>& S, INTERPOLATION& Interpolation, ELASTOPLASTIC& Elastoplastic){
// Setting the velocity grid nodes to temporary vector u, then we can compute the
// hessian for an arbitrary vector u rather than specify for velocity and an
// arbitrary vector.
vector<Vector2d> u;
for (int i = 0; i < massList.size(); i++){
int ig = massList[i].x();
int jg = massList[i].y();
u.push_back(newVelocity[ Index2D(ig,jg) ]);
}
// vector<Vector2d> V1;
// Vector2d v(0,1);
// V1.push_back(v);
// V1.push_back(v);
//
// cout << V1[0].transpose() << endl;
// cout << V1[1].transpose() << endl;
// cout << "Inner Product^2 of V1 = " << InnerProduct(V1,V1) << endl;
// cin.get();
// void ConjugateResidual(const bool usePlasticity, const double beta, const double dt, const double mu0, const double lambda0, const double hardeningCoeff, vector<double>& JE, vector<double>& JP, const vector<double>& particleVolume, vector<Vector2d>& u, const vector<Vector2d>& positionParticle, const vector<Matrix2d>& FE, const vector<Matrix2d>& R, const vector<Matrix2d>& S, INTERPOLATION& Interpolation, ELASTOPLASTIC& Elastoplastic);
ConjugateResidual(usePlasticity, beta, dt, mu0, lambda0, hardeningCoeff, JE, JP, particleVolume, u, positionParticle, FE, R, S, Interpolation, Elastoplastic);
for (int i = 0; i < massList.size(); i++){
int ig = massList[i].x();
int jg = massList[i].y();
newVelocity[Index2D(ig,jg)] = u[i];
}
}
void GRID::ConjugateResidual(const bool usePlasticity, const double beta, const double dt, const double mu0, const double lambda0, const double hardeningCoeff, vector<double>& JE, vector<double>& JP, const vector<double>& particleVolume, vector<Vector2d>& u, const vector<Vector2d>& positionParticle, const vector<Matrix2d>& FE, const vector<Matrix2d>& R, const vector<Matrix2d>& S, INTERPOLATION& Interpolation, ELASTOPLASTIC& Elastoplastic){
// Max Iterations
int iter = 0;
int maxIters = 30;
double alpha, y, test;
// compute r -> residual
vector<Vector2d> r, s, p, q;
// letting Eu = r temporarily to save some space...
r = ComputeHessianAction(usePlasticity, beta, dt, mu0, lambda0, hardeningCoeff, JE, JP, particleVolume, u, positionParticle, FE, R, S, Interpolation, Elastoplastic);
// r = VectorSubtraction(u, r);
for (int i = 0; i < u.size(); i++){
r[i] = u[i] - r[i];
}
// for (int i = 0; i < u.size(); i++){
// cout << u[i].transpose() << endl;
// }
// cin.get();
// s = Ar
s = ComputeHessianAction(usePlasticity, beta, dt, mu0, lambda0, hardeningCoeff, JE, JP, particleVolume, r, positionParticle, FE, R, S, Interpolation, Elastoplastic);
p = r;
q = s;
y = InnerProduct(r, s);
alpha = y/ InnerProduct(q,q);
test = sqrt( InnerProduct(r,r) );
while ( test > sqrt(InnerProduct(u,u))*1e-5 && iter <= maxIters ){
cout << "Iteration " << iter << " | " << "Norm = " << test << endl;
double alpha_num = InnerProduct(r,s);
double alpha_den = InnerProduct(q,q);
alpha = alpha_num/alpha_den;
double BETA_den = alpha_num; // Save for steps below;
// UPDATE SOLUTION AND RESIDUAL
for (int i = 0; i < u.size(); i++){
u[i] += alpha*p[i];
r[i] -= alpha*q[i];
}
s = ComputeHessianAction(usePlasticity, beta, dt, mu0, lambda0, hardeningCoeff, JE, JP, particleVolume, r, positionParticle, FE, R, S, Interpolation, Elastoplastic);
double BETA_num = InnerProduct(r,s);
double BETA = BETA_num/BETA_den;
// UPDATE p AND q
for (int i = 0; i < p.size(); i++){
p[i] = r[i] + BETA*p[i];
q[i] = s[i] + BETA*q[i];
}
test = sqrt( InnerProduct(r,r) );
iter += 1;
// vector<Vector2d> V = scalarVectorProduct(alpha,p);
//
// u = VectorAddition(u, V);
// V.clear();
//
// V = scalarVectorProduct(alpha,q);
// r = VectorSubtraction(r, V);
// V.clear();
// // Updating s = Ar with
// // r_j+1 which was updated in the line above.
// s = ComputeHessianAction(usePlasticity, beta, dt, mu0, lambda0, hardeningCoeff, JE, JP, particleVolume, r, positionParticle, FE, R, S, Interpolation, Elastoplastic);
//
// double B = InnerProduct(r, s)/y;
// y = B*y;
// V = scalarVectorProduct(B,p);
// p = VectorAddition( r, V );
// V.clear();
//
// V = scalarVectorProduct(B,q);
// q = VectorAddition( s, V);
// V.clear();
//
// test = fabs( alpha * InnerProduct(r,r) );
// iter += 1;
}
}
// NOT REALLY BEING USED....
vector<Vector2d> GRID::scalarVectorProduct(double a, vector<Vector2d>& p){
vector<Vector2d> temp;
for (int i = 0; i < p.size(); i++){
temp.push_back( a*p[i] );
}
return temp;
}
vector<Vector2d> GRID::VectorSubtraction(vector<Vector2d>& p, vector<Vector2d>& q){
vector<Vector2d> temp;
for (int i = 0; i < p.size(); i++){
temp.push_back( p[i]-q[i] );
}
return temp;
}
vector<Vector2d> GRID::VectorAddition(vector<Vector2d>& p, vector<Vector2d>& q){
vector<Vector2d> temp;
for (int i = 0; i < p.size(); i++){
temp.push_back( p[i]+q[i] );
}
return temp;
}
double GRID::InnerProduct(vector<Vector2d>& a, vector<Vector2d>& b){
double sum = 0;
for (int i = 0; i < a.size(); i++){
sum += a[i].x()*b[i].x() + a[i].y()*b[i].y(); // A[i]*B[i] + A[2*i+1]*B[2*i+1];
}
return sum;
}
vector<Vector2d> GRID::ComputeHessianAction(const bool usePlasticity, const double beta, const double dt, const double mu0, const double lambda0, const double hardeningCoeff, vector<double>& JE, vector<double>& JP, const vector<double>& particleVolume, vector<Vector2d>& u, const vector<Vector2d>& positionParticle, const vector<Matrix2d>& FE, const vector<Matrix2d>& R, const vector<Matrix2d>& S, INTERPOLATION& Interpolation, ELASTOPLASTIC& Elastoplastic){
vector<Vector2d> Au, deltaForce;
vector<Matrix2d> Ap;
// ComputeAp(const double timeStep, const bool usePlasticity, const double mu0, const double lambda0, const double hardeningCoeff, vector<double>& JE, vector<double>& JP, const vector<Vector2d>& positionParticle, const vector<Vector2d>& velocityGrid, const vector<Vector2d>& u, const vector<Matrix2d>& F, const vector<Matrix2d>& R, const vector<Matrix2d>& S, INTERPOLATION& Interpolation, ELASTOPLASTIC& Elastoplastic)
//
Ap = ComputeAp(dt, usePlasticity, mu0, lambda0, hardeningCoeff, JE, JP, positionParticle, u, FE, R, S, Interpolation, Elastoplastic);
deltaForce = ComputeDeltaForce(particleVolume, positionParticle, FE, Ap, Interpolation );
for (int i = 0; i < deltaForce.size(); i++){
double ig = massList[i].x();
double jg = massList[i].y();
double one_over_mass = 1.0/mass[ Index2D(ig,jg) ];
Au.push_back( u[i] - beta*dt*deltaForce[i]*one_over_mass );
}
return Au;
}
vector<Vector2d> GRID::ComputeDeltaForce(const vector<double>& particleVolume, const vector<Vector2d>& positionParticle, const vector<Matrix2d>& F, const vector<Matrix2d>& Ap, INTERPOLATION& Interpolation ){
vector<Vector2d> delta_force;
Vector2d DELTA_FORCE;
for (int i = 0; i < massList.size(); i++){
DELTA_FORCE = Vector2d::Zero();
int ig, jg;
ig = massList[i].x();
jg = massList[i].y();
for (int p = 0; p < F.size(); p++){
Vector2d gradientWeight;
gradientWeight = Vector2d::Zero();
gradientWeight = Interpolation.GradientWeight(m_h, positionParticle[p], ig, jg);
DELTA_FORCE += particleVolume[p]*Ap[p]*F[p].transpose()*gradientWeight;
}
delta_force.push_back(DELTA_FORCE);
}
return delta_force;
}
////////////////////////////////////////////////////////////////////////////////////////
// *************************************************************************************
// vector<Matrix3d> GRID::ComputeDeltaF(const double timeStep, const vector<Vector2d>& positionParticle, const vector<Matrix2d>& elasticDeformationGradient, INTERPOLATION& Interpolation)
// Input: timeStep ===> time step size, dt.
// positionParticle ==> particle position vector<Vector2d>
// elasticDeformationGradient ==> deformation gradient FE
// INTERPOLATION ==> Interpolation class
// output: deltaF ==> vector<Matrix2d>
//
// Details: This ComputeDeltaF is used to compute hessian action Ev where v is the velocity
//
// Author: Martin Rodriguez Cruz
// Date: February 16, 2017
// ************************************************************************************
///////////////////////////////////////////////////////////////////////////////////////
// vector<Matrix2d> GRID::ComputeDeltaF(const double timeStep, const vector<Vector2d>& positionParticle, const vector<Matrix2d>& elasticDeformationGradient, INTERPOLATION& Interpolation){
// vector<Matrix2d> deltaF;
//
//
// for (int p = 0; p < elasticDeformationGradient.size(); p++){
// Vector2d gradientWeight;
// Matrix2d deltaFp;
//
// for (int i = 0; i < massList.size(); i++){
// int ig, jg;
// ig = massList[i].x();
// jg = massList[i].y();
//
// gradientWeight = Interpolation.GradientWeight(m_h, positionParticle[p], ig, jg);
// deltaFp += timeStep*velocity[ Index2D(ig, jg) ]*gradientWeight.transpose()*elasticDeformationGradient[p];
//
// }
//
// deltaF.push_back(deltaFp);
//
// }
//
// return deltaF;
//
// }
////////////////////////////////////////////////////////////////////////////////////////
// *************************************************************************************
// vector<Matrix3d> GRID::ComputeDeltaF(const double timeStep, const vector<Vector2d>& u, const vector<Vector2d>& positionParticle, const vector<Matrix2d>& elasticDeformationGradient, INTERPOLATION& Interpolation)
// Input: timeStep ===> time step size, dt.
// u ==> arbitrary vector u of size = massList.size()
// positionParticle ==> particle position vector<Vector2d>
// elasticDeformationGradient ==> deformation gradient FE
// INTERPOLATION ==> Interpolation class
// output: deltaF ==> vector<Matrix2d>
//
// Details: This ComputeDeltaF is used to compute arbitrary hessian action Eu.
//
// Author: Martin Rodriguez Cruz
// Date: February 16, 2017
// ************************************************************************************
///////////////////////////////////////////////////////////////////////////////////////
vector<Matrix2d> GRID::ComputeDeltaF(const double timeStep, vector<Vector2d>& u, const vector<Vector2d>& positionParticle, vector<double>& JE_hat, const vector<Matrix2d>& elasticDeformationGradient, vector<Matrix2d>& F_hat, vector<Matrix2d>& R_hat, vector<Matrix2d>& S_hat , INTERPOLATION& Interpolation){
vector<Matrix2d> deltaF;
// For computing Fhat
Matrix2d velocity_Gradient, A;
velocity_Gradient = Matrix2d::Zero();
A = Matrix2d::Zero();
for (int p = 0; p < elasticDeformationGradient.size(); p++){
Matrix2d deltaFp;
for (int i = 0; i < u.size(); i++){
int ig, jg;
ig = massList[i].x();
jg = massList[i].y();
Vector2d gradientWeight = Interpolation.GradientWeight(m_h, positionParticle[p], ig, jg);
deltaFp += timeStep*u[i]*gradientWeight.transpose()*elasticDeformationGradient[p];
A = newVelocity[ Index2D(ig, jg) ]*gradientWeight.transpose();
velocity_Gradient += A ;
}
deltaF.push_back(deltaFp);
// const double dt, const Matrix2d& velocityGradient, vector<double>& JE_hat, const vector<Vector2d>& particlePosition, const Matrix2d& F, vector<Matrix2d>& F_hat, vector<Matrix2d>& R_hat, vector<Matrix2d>& S_hat, INTERPOLATION& Interpolation
ComputeFHat(timeStep, velocity_Gradient, JE_hat, positionParticle, elasticDeformationGradient[p], F_hat, R_hat, S_hat, Interpolation);
}
return deltaF;
}
vector<Matrix2d> GRID::ComputeAp(const double timeStep, const bool usePlasticity, const double mu0, const double lambda0, const double hardeningCoeff, vector<double>& JE, vector<double>& JP, const vector<Vector2d>& positionParticle, vector<Vector2d>& u, const vector<Matrix2d>& F, const vector<Matrix2d>& R, const vector<Matrix2d>& S, INTERPOLATION& Interpolation, ELASTOPLASTIC& Elastoplastic){
vector<Matrix2d> Ap, deltaF, deltaR, deltaJFiT, F_hat, R_hat, S_hat;
vector<double> mu, lambda, JE_hat;
// const double timeStep, vector<Vector2d>& u, const vector<Vector2d>& positionParticle, vector<double>& JE_hat, const vector<Matrix2d>& elasticDeformationGradient, vector<Matrix2d>& F_hat, vector<Matrix2d>& R_hat, vector<Matrix2d>& S_hat , INTERPOLATION& Interpolation
deltaF = ComputeDeltaF(timeStep, u, positionParticle, JE_hat, F, F_hat, R_hat, S_hat, Interpolation);
Elastoplastic.ComputePolarDecomposition(F_hat, R_hat, S_hat);
deltaR = ComputeDeltaR(deltaF, S_hat, R_hat);
deltaJFiT = ComputeDeltaJFiT(F_hat, deltaF);
mu = Elastoplastic.ComputeMu(usePlasticity, mu0, hardeningCoeff, JP);
lambda = Elastoplastic.ComputeLambda(usePlasticity, lambda0, hardeningCoeff, JP);
for (int p = 0; p < F.size(); p ++){
Matrix2d B = JE_hat[p]*F[p].transpose().inverse();
double JFiT_dd_deltaF = DoubleDotProduct( B, deltaF[p]);
Matrix2d TEMP = 2*mu[p]*deltaF[p] - 2*mu[p]*deltaR[p] + lambda[p]*JE_hat[p]*F_hat[p].transpose().inverse()*JFiT_dd_deltaF + lambda[p]*(JE_hat[p]-1)*deltaJFiT[p];
Ap.push_back(TEMP);
}
return Ap;
}
void GRID::ComputeFHat(const double dt, const Matrix2d& velocityGradient, vector<double>& JE_hat, const vector<Vector2d>& particlePosition, const Matrix2d& F, vector<Matrix2d>& F_hat, vector<Matrix2d>& R_hat, vector<Matrix2d>& S_hat, INTERPOLATION& Interpolation){
Matrix2d F_hat_temp = F + dt*velocityGradient*F;
double JE_hat_temp = F_hat_temp.determinant();
F_hat.push_back(F_hat_temp);
JE_hat.push_back( JE_hat_temp );
R_hat.push_back(Matrix2d::Zero());
S_hat.push_back(Matrix2d::Zero());
}
//
// // OLD VERSION
// void GRID::ComputeFHat(double dt, vector<double>& JE_hat, const vector<Vector2d>& particlePosition, const vector<Matrix2d>& F, vector<Matrix2d>& F_hat, vector<Matrix2d>& R_hat, vector<Matrix2d>& S_hat, INTERPOLATION& Interpolation, ELASTOPLASTIC& Elastoplastic){
//
// for (int p = 0; p < particlePosition.size(); p++){
// Vector2d gradientWeight;
// Matrix2d velocity_Gradient, A;
// velocity_Gradient = Matrix2d::Zero();
// A = Matrix2d::Zero();
//
// for ( int i = 0; i < massList.size(); i++ ) {
// int ig, jg;
// ig = massList[i].x();
// jg = massList[i].y();
// gradientWeight = Interpolation.GradientWeight(m_h, particlePosition[p], ig, jg);
// A = newVelocity[ Index2D(ig, jg) ]*gradientWeight.transpose();
//
// velocity_Gradient += A ;
// } // END WEIGHT INTERPOLATION TRANSFER
// F_hat.push_back(F[p] + dt*velocity_Gradient*F[p]);
// JE_hat.push_back( F_hat[p].determinant() );
// R_hat.push_back(Matrix2d::Zero());
// S_hat.push_back(Matrix2d::Zero());
//
// }
//
// Elastoplastic.ComputePolarDecomposition(F_hat, R_hat, S_hat);
//
// }
//
////////////////////////////////////////////////////////////////////////////////////////
// *************************************************************************************
// vector<Matrix3d> GRID::ComputeDeltaR(vector<Matrix3d> &deltaF, vector<Matrix3d> &S, vector<Matrix3d> &R)
// Input: deltaF ===> differential of deformation gradient, 3x3 matrix for all particles
// S ==> polar decomposition, 3x3 matrix for all particles
// R ==> polar decomposition matrix, 3x3 matrix for all particles
// output: deltaR ==> vector<Matrix3d>
//
// Details: Check thesis Implicit time integration section
//
// Author: Martin Rodriguez Cruz
// Date: February 16, 2017
// ************************************************************************************
///////////////////////////////////////////////////////////////////////////////////////
vector<Matrix2d> GRID::ComputeDeltaR(const vector<Matrix2d> &deltaF, const vector<Matrix2d> &S, const vector<Matrix2d> &R) {
vector<Matrix2d> deltaR;
for (int p = 0; p < S.size(); p++){
Matrix2d B = R[p].transpose()*deltaF[p] - deltaF[p].transpose()*R[p];
// b << B(0,1), B(0,2), B(1,2);
// A << S[p](0,0)+S[p](1,1), S[p](2,1), -S[p](0,2), S[p](1,2), S[p](0,0)+S[p](2,2), S[p](0,1), -S[p](0,2), S[p](1,0), S[p](1,1)+S[p](2,2);
// x = A.inverse()*b; // A.colPivHouseholderQr().solve(b);
double a = B(0,1)/(S[p](0,0) + S[p](1,1));
Matrix2d RTdR;
RTdR << 0 , a, -a, 0;
deltaR.push_back( R[p]*RTdR );
RTdR = Matrix2d::Zero();
}
return deltaR;
}
////////////////////////////////////////////////////////////////////////////////////////
// *************************************************************************************
// vector<Matrix2d> GRID::ComputeDeltaJFiT(vector<Matrix2d> &deltaF, vector<Matrix2d> &S, vector<Matrix2d> &R)
// Input: deltaF ===> differential of deformation gradient, 3x3 matrix for all particles
// S ==> polar decomposition, 2x2 matrix for all particles
// R ==> polar decomposition matrix, 2x2 matrix for all particles
// output: deltaR ==> vector<Matrix3d>
//
// Details: Check thesis Implicit time integration section
//
// Author: Martin Rodriguez Cruz
// Date: February 16, 2017
// ************************************************************************************
///////////////////////////////////////////////////////////////////////////////////////
vector<Matrix2d> GRID::ComputeDeltaJFiT(const vector<Matrix2d>& F, const vector<Matrix2d>& deltaF){
vector<Matrix2d> deltaJFiT;
vector<Matrix2d> A; // 4x1 vector of 2x2 matrices
for (int p = 0; p < F.size(); p++){
A = Compute_dJFiT( F[p] );
deltaJFiT.push_back(DoubleDotProduct(A,deltaF[p]));
for (int i = 0; i < 4; i++) {
A[i] = Matrix2d::Zero();
}
}
return deltaJFiT;
}
////////////////////////////////////////////////////////////////////////////////////////
// *************************************************************************************
// Compute_dJFiT(Matrix2d& Fe) -> derivative of J*inv(F)^T with respect components of F
// Input: Fe ===> Elastic deformation gradient
// output: Fourth order tensor (Vector of 4x1 2x2 matrices / Total of 16 components)
//
// Author: Martin Rodriguez Cruz
// Date: February 16, 2017
// ************************************************************************************
///////////////////////////////////////////////////////////////////////////////////////
vector<Matrix2d> GRID::Compute_dJFiT(const Matrix2d& F){
vector<Matrix2d> dJFiT;
Matrix2d temp;
// dJFiT(0)
temp << 0, 0, 0, 1;
dJFiT.push_back( temp );
// dJFiT(1)
temp << 0, 0, -1, 0;
dJFiT.push_back( temp );
temp << 0, -1, 0, 0;
dJFiT.push_back( temp );
temp << 1, 0, 0, 0;
dJFiT.push_back( temp );
return dJFiT;
}
////////////////////////////////////////////////////////////////////////////////////////
// *************************************************************************************
// DoubleDotProduct(vector<Matrix3d>& C, Matrix3d& B)
// Input: C ===> Fourth Order Tensor in 4x1 of 2x2 matrices format.
// B ===> second order tensor 2x2 matrix.
// output: A ===> second order tensor 2x2 matrix.
//
// Author: Martin Rodriguez Cruz
// Date: February 16, 2017
// ************************************************************************************
///////////////////////////////////////////////////////////////////////////////////////
Matrix2d GRID::DoubleDotProduct(const vector<Matrix2d>& C, const Matrix2d& B){
Matrix2d matrixProduct;
Matrix2d A;
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
matrixProduct = C[2*i + j]*B;
A(i,j) = matrixProduct.sum();
}
}
return A;
}
////////////////////////////////////////////////////////////////////////////////////////
// *************************************************************************************
// DoubleDotProduct(Matrix2d& C, Matrix2d& B)
// Input: C ===> second Order Tensor 2x2 matrix.
// B ===> second order tensor 2x2 matrix.
// output: A ===> a double number in reals.
//
// Author: Martin Rodriguez Cruz
// Date: February 16, 2017
// ************************************************************************************
///////////////////////////////////////////////////////////////////////////////////////
double GRID::DoubleDotProduct(const Matrix2d& C, const Matrix2d& B){
Matrix2d matrixProduct;
double A;
matrixProduct = C*B;
A = matrixProduct.sum();
return A;
}
////////////////////////////////////////////////////////////////////////////////////////////
//=======================================================================================//
// GRID_NO_OBSTACLE
//=======================================================================================//
///////////////////////////////////////////////////////////////////////////////////////////
void GRID_NO_OBSTACLE::GridCollision( double frictionCoeff ) {
Vector2d collisionNormal;
Vector2d velocityCollision = Vector2d ( 0, 0);
for (int i = 0; i < massList.size(); i++){
bool hasItCollided = false;
bool stickyCollision = true;
int ig, jg;
ig = massList[i].x();
jg = massList[i].y();
// GROUND COLLISION
if ( position[Index2D(ig,jg)].y() <= (double) 0.05 ){
hasItCollided = true;
collisionNormal = Vector2d( 0, 1);
}
else if(position[Index2D(ig,jg)].x() <= (double) 0.05){
hasItCollided = true;
collisionNormal = Vector2d(1, 0);
stickyCollision = true;
}
else if( position[Index2D(ig,jg)].y() >= (double) 0.95){
hasItCollided = true;
collisionNormal = Vector2d(0, -1.0);
stickyCollision = true;
}
else if( position [Index2D(ig,jg)].x() >= (double) 0.95 ){
hasItCollided = true;
collisionNormal = Vector2d(-1.0, 0);
stickyCollision = true;
}
if ( hasItCollided ){
Vector2d velocityRel = newVelocity[Index2D(ig,jg)] - velocityCollision;
double normalVelocity = velocityRel.dot(collisionNormal);
if (normalVelocity < 0){
Vector2d tangentVelocity = velocityRel - collisionNormal*normalVelocity;
Vector2d velocityRelPrime;
if (tangentVelocity.norm() <= -frictionCoeff*normalVelocity || stickyCollision ){
velocityRelPrime = Vector2d (0, 0);
}
else{
velocityRelPrime.x() = tangentVelocity.x() + frictionCoeff*normalVelocity*tangentVelocity.x()/tangentVelocity.norm();
velocityRelPrime.y() = tangentVelocity.y() + frictionCoeff*normalVelocity*tangentVelocity.y()/tangentVelocity.norm();
}
newVelocity[ Index2D(ig,jg) ] = velocityRelPrime + velocityCollision;
} // if normalVelocity < 0
} // if hasItCollided
// cout << "Grid Node ( " << ig << " , " << jg << " , " << kg << " ) = " << hasItCollided << endl;
} // for massList
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
//====================================================================================================//
// GRID_CYLINDER_OBSTACLE
//====================================================================================================//
/////////////////////////////////////////////////////////////////////////////////////////////////////////
/// CYLINDER
double GRID_CYLINDER_OBSTACLE::LevelSet(const double x, const double y){
return (x-0.5)*(x-0.5) + (y-0.3)*(y-0.3) - 0.1*0.1;
}
Vector2d GRID_CYLINDER_OBSTACLE::GradientLevelSet(const double x, const double y){
Vector2d v = Vector2d( 2*(x-0.5), 2*(y-0.3) );
return v/v.norm();
}
void GRID_CYLINDER_OBSTACLE::GridCollision( double frictionCoeff ) {
Vector2d collisionNormal;
Vector2d velocityCollision = Vector2d ( 0, 0);
for (int i = 0; i < massList.size(); i++){
bool hasItCollided = false;
int ig, jg;
ig = massList[i].x();
jg = massList[i].y();
//////////////////////////////////////////
// COLLISION WITH CYLINDER
//////////////////////////////////////////
double phi = LevelSet( position[Index2D(ig,jg)].x(), position[Index2D(ig,jg)].y() );
if ( phi <= 0 ){
// cout << "Collision with Cylinder GRID" << endl;
hasItCollided = true;
collisionNormal = GradientLevelSet(position[Index2D(ig,jg)].x(), position[Index2D(ig,jg)].y());
}
// GROUND COLLISION
if ( position[Index2D(ig,jg)].y() <= (double) 0.05 ){
hasItCollided = true;
collisionNormal = Vector2d( 0, 1);
}
else if(position[Index2D(ig,jg)].x() <= (double) 0.05){
hasItCollided = true;
collisionNormal = Vector2d(1, 0);
}
else if( position[Index2D(ig,jg)].y() >= (double) 0.95){
hasItCollided = true;
collisionNormal = Vector2d(0, -1.0);
}
else if( position [Index2D(ig,jg)].x() >= (double) 0.95 ){
hasItCollided = true;
collisionNormal = Vector2d(-1.0, 0);
}
if ( hasItCollided ){
Vector2d velocityRel = newVelocity[Index2D(ig,jg)] - velocityCollision;
double normalVelocity = velocityRel.dot(collisionNormal);
if (normalVelocity < 0){
Vector2d tangentVelocity = velocityRel - collisionNormal*normalVelocity;
Vector2d velocityRelPrime;
if (tangentVelocity.norm() <= -frictionCoeff*normalVelocity ){
velocityRelPrime = Vector2d (0, 0);
}
else{
velocityRelPrime.x() = tangentVelocity.x() + frictionCoeff*normalVelocity*tangentVelocity.x()/tangentVelocity.norm();
velocityRelPrime.y() = tangentVelocity.y() + frictionCoeff*normalVelocity*tangentVelocity.y()/tangentVelocity.norm();
}
newVelocity[ Index2D(ig,jg) ] = velocityRelPrime + velocityCollision;
} // if normalVelocity < 0
} // if hasItCollided
// cout << "Grid Node ( " << ig << " , " << jg << " , " << kg << " ) = " << hasItCollided << endl;
} // for massList
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
//====================================================================================================//
// GRID_HAT_OBSTACLE
//====================================================================================================//
/////////////////////////////////////////////////////////////////////////////////////////////////////////
double GRID_HAT_OBSTACLE::LevelSet(const double x, const double y){
if (x >= 0.4 && x <= 0.6 && y >= 0.5 && y <= 0.6){
return -( 0.6 - fabs(x-0.5) - y );
}
else{
return (double) 1;
}
}
Vector2d GRID_HAT_OBSTACLE::GradientLevelSet(const double x, const double y){
Vector2d v;
if ( x >= 0.4 && x <= 0.5 && y >= 0.5 && y <= 0.6 ){
v = Vector2d( -1, 1 );
}
else if (x > 0.5 && x <= 0.6 && y >= 0.5 && y <= 0.6 ){
v = Vector2d( 1, 1 );
}
return v/v.norm();
}
void GRID_HAT_OBSTACLE::GridCollision( double frictionCoeff ) {
Vector2d collisionNormal;
Vector2d velocityCollision = Vector2d ( 0, 0);
for (int i = 0; i < massList.size(); i++){
bool hasItCollided = false;
int ig, jg;
ig = massList[i].x();
jg = massList[i].y();
//////////////////////////////////////////
// COLLISION WITH CYLINDER
//////////////////////////////////////////
double phi = LevelSet( position[Index2D(ig,jg)].x(), position[Index2D(ig,jg)].y() );
if ( phi <= 0 ){
// cout << "Collision with Cylinder GRID" << endl;
hasItCollided = true;
collisionNormal = GradientLevelSet(position[Index2D(ig,jg)].x(), position[Index2D(ig,jg)].y());
}
// GROUND COLLISION
if ( position[Index2D(ig,jg)].y() <= (double) 0.05 ){
hasItCollided = true;
collisionNormal = Vector2d( 0, 1);
}
else if(position[Index2D(ig,jg)].x() <= (double) 0.05){
hasItCollided = true;
collisionNormal = Vector2d(1, 0);
}
else if( position[Index2D(ig,jg)].y() >= (double) 0.95){
hasItCollided = true;
collisionNormal = Vector2d(0, -1.0);
}
else if( position [Index2D(ig,jg)].x() >= (double) 0.95 ){
hasItCollided = true;
collisionNormal = Vector2d(-1.0, 0);
}
if ( hasItCollided ){
Vector2d velocityRel = newVelocity[Index2D(ig,jg)] - velocityCollision;
double normalVelocity = velocityRel.dot(collisionNormal);
if (normalVelocity < 0){
Vector2d tangentVelocity = velocityRel - collisionNormal*normalVelocity;
Vector2d velocityRelPrime;
if (tangentVelocity.norm() <= -frictionCoeff*normalVelocity ){
velocityRelPrime = Vector2d (0, 0);
}
else{
velocityRelPrime.x() = tangentVelocity.x() + frictionCoeff*normalVelocity*tangentVelocity.x()/tangentVelocity.norm();
velocityRelPrime.y() = tangentVelocity.y() + frictionCoeff*normalVelocity*tangentVelocity.y()/tangentVelocity.norm();
}
newVelocity[ Index2D(ig,jg) ] = velocityRelPrime + velocityCollision;
} // if normalVelocity < 0
} // if hasItCollided
// cout << "Grid Node ( " << ig << " , " << jg << " , " << kg << " ) = " << hasItCollided << endl;
} // for massList
}
|
6105d7f269e08ba011164bf88372356c928f5412 | c68f791005359cfec81af712aae0276c70b512b0 | /0-unclassified/polyline.cpp | 3c8fdbc1ca0a9959766295dd125e634c2015ef1e | [] | no_license | luqmanarifin/cp | 83b3435ba2fdd7e4a9db33ab47c409adb088eb90 | 08c2d6b6dd8c4eb80278ec34dc64fd4db5878f9f | refs/heads/master | 2022-10-16T14:30:09.683632 | 2022-10-08T20:35:42 | 2022-10-08T20:35:42 | 51,346,488 | 106 | 46 | null | 2017-04-16T11:06:18 | 2016-02-09T04:26:58 | C++ | UTF-8 | C++ | false | false | 1,079 | cpp | polyline.cpp | #include <bits/stdc++.h>
using namespace std;
const double inf = 1e18;
const double eps = 1e-11;
bool equal(double a, double b) {
return abs(a - b) < eps;
}
int main() {
double a, b;
scanf("%lf %lf", &a, &b);
if(equal(a, b)) {
printf("%.15f\n", a);
return 0;
}
bool ada = 0;
double ans = inf;
if(a - b > -eps) {
int l = 1, r = 1e9;
while(l < r) {
int k = (l + r + 1) >> 1;
double x = (a - b) / (2 * k);
if(b - eps < x) {
l = k;
} else {
r = k - 1;
}
}
double x = (a - b) / (2 * l);
if(b - eps < x) {
ada = 1;
ans = min(ans, x);
}
}
int l = 0, r = 1e9;
while(l < r) {
int k = (l + r + 1) >> 1;
double x = (a + b) / (2 * k + 2);
double c = x - b;
if(b - eps < x && c - eps < x) {
l = k;
} else {
r = k - 1;
}
}
double x = (a + b) / (2 * l + 2);
double c = x - b;
if(b - eps < x && c - eps < x) {
ada = 1;
ans = min(ans, x);
}
if(!ada) {
puts("-1");
} else {
printf("%.15f\n", ans);
}
return 0;
} |
08d446fb5bfc1eabe8d920d65630dbdd164b2ee5 | ec57a6e218dd98f51384428041e62f476905f149 | /test/testPnPOptim.cc | b8d848de4e9a3dce9d0e6b1f50a061050ae14514 | [] | no_license | huhumeng/ceresBA | 45453958d14a0f54ec6915076f08e3f9ffc7f90c | bcccbf644376f99fc30ad8e9cd8fa1a1b0c2378f | refs/heads/master | 2021-06-28T19:09:28.729580 | 2019-03-25T09:38:42 | 2019-03-25T09:38:42 | 140,649,951 | 8 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,360 | cc | testPnPOptim.cc | #include <iostream>
#include <ceres/ceres.h>
#include "GenData.h"
#include "PnPproblem.h"
#include <opencv2/core/core.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#define OPTIMIZE_ONLY_POSE 1
using namespace std;
int main(){
double r[3] = {1.0, 2.0, 3.0};
double t[3] = {3.0, 2.0, 1.0};
GenPointWithPoseKnown gener(r, t, 480);
double initR[3] = {10.1, 21.0, 11.0};
double initT[3] = {100.0, 20.1, 31.1};
// Eigen::Quaterniond q(1.0, 0, 0, 0);
// cout << q.coeffs() << endl;
#if OPTIMIZE_ONLY_POSE
PnPproblem problem(gener.p3ds, gener.p2ds, initR, initT);
#else
// cv::Mat K = cv::Mat_<double>(3, 3) << (520.9, 0.0, 521.0, 0, 325.1, 249.7, 0, 0, 1);
// cv::solvePnP();
PnPPointproblem problem(gener.p2ds, gener.p3dnoise, initR, initT);
#endif
ceres::Solver::Options option;
option.linear_solver_type = ceres::DENSE_SCHUR;
option.trust_region_strategy_type = ceres::DOGLEG;
option.minimizer_progress_to_stdout = true;
option.max_num_iterations = 100;
ceres::Solver::Summary summary;
problem.solve(option, &summary);
cout << summary.BriefReport() << endl;
cout << "Result is: " << endl;
cout << initR[0] << ", " << initR[1] << ", " << initR[2] << endl;
cout << initT[0] << ", " << initT[1] << ", " << initT[2] << endl;
return 0;
} |
3c11ad746ebdd7504742ef0cca880699c30b4ec4 | 142b071b3873bea1f7d716fca6df95f1eaa3527a | /kellerkompanie_zeus.Altis/functions/logistics/internal/logisticDialog.hpp | 1d56558e965e9b6da0715f182330c7b6b6c76998 | [] | no_license | kellerkompanie/kellerkompanie-template | b9987cacddcc7d693877dd326465975d66ba117e | d2bda2953bbb52a7950817f75f6fe863ea621dff | refs/heads/master | 2021-09-13T20:00:28.235477 | 2018-02-25T20:48:23 | 2018-02-25T20:48:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,568 | hpp | logisticDialog.hpp | ////////////////////////////////////////////////////////
// GUI EDITOR OUTPUT START
////////////////////////////////////////////////////////
#include "parentDialog.hpp"
// MACROS
#define IDC_keko_logistic_LOADOUT_RSCTEXT_1000 6877
#define IDC_keko_logistic_LOADOUT_RSCTEXT_1001 6878
#define IDC_keko_logistic_LOADOUT_RSCLISTBOX_1500 7377
#define IDC_keko_logistic_LOADOUT_RSCBUTTON_1600 7477
#define IDC_keko_logistic_LOADOUT_RSCBUTTON_1601 7478
#define IDC_keko_logistic_LOADOUT_RSCFRAME_1800 7677
#define IDC_keko_logistic_LOADOUT_RSCCOMBO_2100 7977
#define IDC_keko_logistic_LOADOUT_IGUIBACK_2200 8077
class keko_logistic_mainDialog {
idd = 11;
movingEnable = true;
enableSimulation = true; // does not freeze the game
// lade init-Skript
//onload = "(_this) execVM 'functions\logistic\fn_dialogLogInit.sqf';";
onload = "(_this) spawn keko_fnc_dialogLogInit;";
controls[] = {
IGUIBack_2200,
RscFrame_1800,
RscListbox_1500,
RscText_1000,
//RscCombo_2100,
//RscText_1001,
RscButton_1600,
RscButton_1601
};
class IGUIBack_2200: keko_logistic_IGUIBack
{
idc = IDC_keko_logistic_LOADOUT_IGUIBACK_2200;
x = 0.06 * GUI_GRID_W + GUI_GRID_X;
y = 0.99 * GUI_GRID_H + GUI_GRID_Y;
w = 40 * GUI_GRID_W;
h = 24 * GUI_GRID_H;
moving = 1;
};
class RscFrame_1800: keko_logistic_RscFrame
{
idc = IDC_keko_logistic_LOADOUT_RSCFRAME_1800;
text = "Logistik-Auswahlmenü"; //--- ToDo: Localize;
x = 0 * GUI_GRID_W + GUI_GRID_X;
y = 0.5 * GUI_GRID_H + GUI_GRID_Y;
w = 40 * GUI_GRID_W;
h = 24.5 * GUI_GRID_H;
sizeEx = 1 * GUI_GRID_H;
};
class RscListbox_1500: keko_logistic_RscListbox
{
idc = IDC_keko_logistic_LOADOUT_RSCLISTBOX_1500;
text = "Kisten"; //--- ToDo: Localize;
x = 1 * GUI_GRID_W + GUI_GRID_X;
y = 3 * GUI_GRID_H + GUI_GRID_Y;
w = 16 * GUI_GRID_W;
h = 21 * GUI_GRID_H;
colorSelectBackground[] =
{
0.03,
0.42,
0.53,
1
};
};
class RscText_1000: keko_logistic_RscText
{
idc = IDC_keko_logistic_LOADOUT_RSCTEXT_1000;
text = "Kisten"; //--- ToDo: Localize;
x = 1 * GUI_GRID_W + GUI_GRID_X;
y = 1.5 * GUI_GRID_H + GUI_GRID_Y;
w = 15.5 * GUI_GRID_W;
h = 2 * GUI_GRID_H;
};
/*
class RscCombo_2100: keko_logistic_RscCombo
{
idc = IDC_keko_logistic_LOADOUT_RSCCOMBO_2100;
x = 18 * GUI_GRID_W + GUI_GRID_X;
y = 4.5 * GUI_GRID_H + GUI_GRID_Y;
w = 19.5 * GUI_GRID_W;
h = 1.5 * GUI_GRID_H;
};
/*
class RscText_1001: keko_logistic_RscText
{
idc = IDC_keko_logistic_LOADOUT_RSCTEXT_1001;
text = "Optik"; //--- ToDo: Localize;
x = 18 * GUI_GRID_W + GUI_GRID_X;
y = 3 * GUI_GRID_H + GUI_GRID_Y;
w = 19 * GUI_GRID_W;
h = 2 * GUI_GRID_H;
};
*/
class RscButton_1600: keko_logistic_RscButton
{
idc = IDC_keko_logistic_LOADOUT_RSCBUTTON_1600;
text = "OK"; //--- ToDo: Localize;
x = 18 * GUI_GRID_W + GUI_GRID_X;
y = 8.5 * GUI_GRID_H + GUI_GRID_Y;
w = 9 * GUI_GRID_W;
h = 1.5 * GUI_GRID_H;
//action = "[lbData [7377, lbCurSel 7377], lbData[7977, lbCurSel 7977]] call keko_fnc_dialogLogistic;";
action = "[lbData [7377, lbCurSel 7377]] call keko_fnc_dialogLogistic;";
};
class RscButton_1601: keko_logistic_RscButton
{
idc = IDC_keko_logistic_LOADOUT_RSCBUTTON_1601;
text = "Abbrechen"; //--- ToDo: Localize;
x = 28.5 * GUI_GRID_W + GUI_GRID_X;
y = 8.5 * GUI_GRID_H + GUI_GRID_Y;
w = 9 * GUI_GRID_W;
h = 1.5 * GUI_GRID_H;
action = "closeDialog 2"; // CANCEL BUTTON
};
};
////////////////////////////////////////////////////////
// GUI EDITOR OUTPUT END
//////////////////////////////////////////////////////// |
b8479bbe55bdd0675f8684fbbf6ac73bc71e4ea5 | cc0f2e8aea290459b0ef9d62f097fb94c9929bda | /data_saver.cpp | 15ce9025d09b8a8677ac4d48abfca9c29d6c4215 | [] | no_license | demon1999/finder | 30f0d479a3151b0608e48d7d3ff1d1f72099cb0b | a0a5e42000f7071fbee45ea7f56064c71a80256f | refs/heads/master | 2020-04-17T03:09:45.176684 | 2019-01-29T07:16:06 | 2019-01-29T07:16:06 | 166,169,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,714 | cpp | data_saver.cpp | #include "data_saver.h"
#include "finder.h"
#include "scanner.h"
#include <iostream>
#include <QString>
#include <QVector>
#include <QThread>
data_saver::data_saver()
{
int k = QThread::idealThreadCount() - 1;
if (k <= 0) k = 2;
numberOfThreads = k;
}
void data_saver::set_flag() {
aborted_flag = true;
for (auto v : finders) {
v->set_flag();
}
for (auto v : scan)
v->set_flag();
}
void data_saver::add_path(const QString &path) {
if (added.find(path) == added.end()) {
added.insert(path);
watcher->addPath(path);
}
}
void data_saver::get_files(const QString &dir, QMap<QString, bool> &was, QSet<QString> &fileList, bool isSearch) {
if (aborted_flag) return;
QDir d(dir);
if (was[d.canonicalPath()]) return;
was[d.canonicalPath()] = true;
//std::cout << d.canonicalPath().toStdString() << "\n";
QFileInfoList list = d.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
if (!isSearch)
add_path(dir);
for (const auto& file_info : list)
{
if (aborted_flag) return;
if (file_info.isSymLink()) {
//ignore
} else if (file_info.isReadable()) {
if (file_info.isDir()) {
get_files(file_info.absoluteFilePath(), was, fileList, isSearch);
} else {
QString path = file_info.canonicalFilePath();
fileList.insert(path);
if (!isSearch) {
add_path(path);
}
}
}
}
}
void data_saver::scan_directory(QString dir) {
finishedThreads = 0;
QVector<QString> fileList;
QMap<QString, bool> was;
if (currentDir == dir) {
for (auto v : fileList) {
auto it = data.find(v);
if (it != data.end())
data.erase(it);
//std::cout << "I got it! " << v.toStdString() << "\n";
}
} else {
added.clear();
currentDir = dir;
watcher = new QFileSystemWatcher;
get_files(dir, was, changed, false);
}
for (auto v : changed) {
fileList.append(v);
}
if (aborted_flag) return;
connect(watcher, SIGNAL(directoryChanged(const QString &)), this, SLOT(directory_changed(const QString &)));
connect(watcher, SIGNAL(fileChanged(const QString &)), this, SLOT(directory_changed(const QString &)));
for (auto v : threadsForScanning)
v->quit();
threadsForScanning.resize(0);
for (int i = 0; i < numberOfThreads; i++)
threadsForScanning.push_back(new QThread);
cnt = fileList.size();
currentCnt = 0;
scan.resize(0);
QSet<QPair<long long, long long> > sizes;
for (int i = 0; i < threadsForScanning.size(); i++) {
scan.push_back(new scanner());
sizes.insert({0, i});
}
for (auto path : fileList) {
QPair<long long, long long> now = *sizes.begin();
sizes.erase(sizes.begin());
now.first += QFile(path).size();
sizes.insert(now);
scan[now.second]->add_file(path);
}
for (int i = 0; i < threadsForScanning.size(); i++) {
scan[i]->moveToThread(threadsForScanning[i]);
connect(scan[i], SIGNAL(percentage()), this, SLOT(show_percentage()));
connect(threadsForScanning[i], SIGNAL(started()), scan[i], SLOT(run()));
connect(scan[i], SIGNAL(finished()), threadsForScanning[i], SLOT(quit()));
qRegisterMetaType<QSet<qint32> >("QSet<qint32>");
connect(scan[i], SIGNAL(done(const QString&, const QSet<qint32> &)), this, SLOT(add_info(const QString&, const QSet<qint32> &)));
connect(scan[i], SIGNAL(indexing_finished()), this, SLOT(indexing_finished()));
threadsForScanning[i]->start();
}
}
void data_saver::directory_changed(const QString &path) {
//std::cout << path.toStdString() << "\n";
if (QFileInfo(path).isDir()) {
QMap<QString, bool> was;
get_files(path, was, changed, false);
}
if (QFileInfo(path).isFile()) {
changed.insert(path);
add_path(path);
}
}
void data_saver::indexing_finished() {
finishedThreads++;
if (aborted_flag) return;
if (finishedThreads == numberOfThreads)
emit s_indexing_finished();
}
void data_saver::reset_flag() {
aborted_flag = false;
}
void data_saver::add_info(const QString& path, const QSet<qint32> &_data) {
data[path] = _data;
auto it = changed.find(path);
if (it != changed.end())
changed.erase(it);
//std::cout << path.toStdString() << " update indexes " << _data.size() << "\n";
}
void data_saver::search(QString textToFind) {
if (aborted_flag) return;
QMap<QString, bool> was;
QSet<QString> f;
get_files(currentDir, was, f, true);
QVector<QString> fileList;
for (auto v : f) fileList.push_back(v);
cnt = fileList.size();
currentCnt = 0;
finishedThreads = 0;
for (auto v : threadsForSearch)
v->quit();
threadsForSearch.resize(0);
for (int i = 0; i < numberOfThreads; i++)
threadsForSearch.push_back(new QThread);
finders.resize(0);
fileNames.resize(0);
for (int i = 0; i < threadsForSearch.size(); i++) {
finders.push_back(new finder(textToFind));
for (int j = i; j < fileList.size(); j += threadsForSearch.size()) {
finders[i]->add_file(fileList[j], data[fileList[j]]);
}
}
if (aborted_flag) return;
//std::cout << threadsForSearch.size() << "\n";
for (int i = 0; i < threadsForSearch.size(); i++) {
finders[i]->moveToThread(threadsForSearch[i]);
connect(finders[i], SIGNAL(percentage()), this, SLOT(show_percentage()));
connect(threadsForSearch[i], SIGNAL(started()), finders[i], SLOT(run()));
connect(finders[i], SIGNAL(finished()), threadsForSearch[i], SLOT(quit()));
qRegisterMetaType<QVector<QString>>("QVector<QString>");
connect(finders[i], SIGNAL(done(const QVector<QString> &)), this, SLOT(add_info(const QVector<QString> &)));
threadsForSearch[i]->start();
}
}
void data_saver::show_percentage() {
currentCnt++;
if (cnt == 0) {
emit percentage(100);
} else {
// std::cout << currentCnt << " " << cnt;
// if (currentCnt > cnt) std::cout << " ya debil!\n";
// else
// std::cout << "\n";
emit percentage(currentCnt * 100 / cnt);
}
}
void data_saver::add_info(const QVector<QString> &paths) {
fileNames.append(paths);
finishedThreads++;
if (aborted_flag) return;
//std::cout << "kukarek\n";
if (finishedThreads == threadsForSearch.size()) {
emit done(fileNames);
}
}
|
960157c2fe0db08d44f235061afe3b48be7419f7 | 710f2cf5524cb1101ea11b5941b1b139e7469ec6 | /IceCreamParlor.cpp | cdfa5fe088a0ef0dec5744fd9e4339b774a6a22b | [] | no_license | themennice/programming-challenges | 2bbf49f9848e84c5062f9c3718232f3095d45e4f | c62d2a84ec43076f4c8db101e7d88b2a27eb37a8 | refs/heads/master | 2023-04-06T16:22:23.298137 | 2021-04-06T03:00:42 | 2021-04-06T03:00:42 | 230,023,937 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 480 | cpp | IceCreamParlor.cpp | /*
https://www.hackerrank.com/challenges/icecream-parlor/problem
*/
vector<int> icecreamParlor(int m, vector<int> arr) {
vector<int> cost{};
for(int i = 0; i < arr.size() - 1; i++)
{
for(int j = i + 1; j < arr.size(); j++)
{
if(arr[i] + arr[j] == m)
{
cost.push_back(i+1);
cost.push_back(j+1);
}
}
}
sort(cost.begin(), cost.end());
return cost;
} |
4bcbd78cb4dd3bfdc99cd22e3fdbc7ca413c90fa | a210d39bea987392e9032c1952454630fd0696a6 | /data structure & algorithms/ClassroomExercise/Exercise_1/bai_1.cpp | 8249caea8e1a5c30dc727f84aaa5e599abaab162 | [] | no_license | duytoxic/learn-cpp | 327ac74d1a66e923f8f44c1bade1790a423f3090 | 64243d1e96ac6a5725de28e247b8b519240a6956 | refs/heads/master | 2023-05-13T06:55:18.226143 | 2021-05-23T01:03:05 | 2021-05-23T01:03:05 | 293,559,762 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 759 | cpp | bai_1.cpp | #include <iostream>
using namespace std;
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
void lowest(int &den3, int &num3)
{
int common_factor = gcd(num3,den3);
den3 = den3/common_factor;
num3 = num3/common_factor;
}
void addFraction(int num1, int den1, int num2,
int den2, int &num3, int &den3)
{
den3 = gcd(den1,den2);
// LCM * GCD = a * b
den3 = (den1*den2) / den3;
num3 = (num1)*(den3/den1) + (num2)*(den3/den2);
lowest(den3,num3);
}
// Driver program
int main()
{
int num1=1, den1=500, num2=2, den2=1500, den3, num3;
addFraction(num1, den1, num2, den2, num3, den3);
printf("%d/%d + %d/%d = %d/%d\n", num1, den1, num2, den2, num3, den3);
return 0;
}
|
716c432fd6cb50937694ccbf2304b5f050d97c3b | 7c974a6805b96838f23061d94500b16cb73df320 | /facefrnd/main.cpp | 8cd4d57572c244b391cb0eede50ad4fb15f11998 | [] | no_license | vectar31/Spoj-solutions-and-other-c-codes | b14ea488baf8c34d078dc0f18b5d3220b08d144f | db3fbf884c3ba00b4bb1495da60fee692cad3cf8 | refs/heads/master | 2021-01-10T02:10:45.340417 | 2015-12-14T11:47:10 | 2015-12-14T11:47:10 | 47,930,233 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 494 | cpp | main.cpp | #include <iostream>
using namespace std;
bool fr[10000]={false};
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
int m;
cin>>m;
for(int i=0;i<m;i++)
{
int f;
cin>>f;
fr[f]=1;
}
}
for(int i=0;i<n;i++)
fr[a[i]]=0;
int ans=0;
for(int i=0;i<=9999;i++)
{
if(fr[i]==true)
ans++;
}
cout<<ans<<endl;
return 0;
}
|
86dc280bed7c4c58fa4acafe2b58462376797669 | 25d0798e3d131c73d054d8808645ab2f7ada1dce | /CrossPlatform/MeshRenderer.h | 134a0e1b5bb8b8e7be020891f04c6eb7cac786ff | [] | no_license | michaelrcason/Platform | 4f4eccabee6e9a1727a11186756b284fdc4330d8 | e9b3f953c81302bc12c05ca1f59a81d700c1081e | refs/heads/master | 2023-05-05T11:12:43.617451 | 2021-05-26T13:24:05 | 2021-05-26T13:24:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,354 | h | MeshRenderer.h | #pragma once
#include "RenderPlatform.h"
#include "Platform/Shaders/SL/camera_constants.sl"
#include "Platform/Shaders/SL/solid_constants.sl"
#include "Platform/CrossPlatform/Mesh.h"
#include "Export.h"
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4251)
#endif
namespace simul
{
namespace crossplatform
{
class SIMUL_CROSSPLATFORM_EXPORT MeshRenderer
{
public:
MeshRenderer();
~MeshRenderer();
//! To be called when a rendering device has been initialized.
void RestoreDeviceObjects(RenderPlatform *r);
void RecompileShaders();
//! To be called when the rendering device is no longer valid.
void InvalidateDeviceObjects();
//! Render the mesh.
void Render(GraphicsDeviceContext &deviceContext, Mesh *mesh,mat4 model
,Texture *diffuseCubemap,Texture *specularCubemap,Texture *screenspaceShadow);
void ApplyMaterial(DeviceContext &deviceContext, Material *material);
protected:
void DrawSubMesh(GraphicsDeviceContext& deviceContext, Mesh* mesh, int);
void DrawSubNode(GraphicsDeviceContext& deviceContext, Mesh* mesh, const Mesh::SubNode& subNode);
ConstantBuffer<CameraConstants> cameraConstants;
RenderPlatform *renderPlatform;
Effect *effect;
crossplatform::ConstantBuffer<SolidConstants> solidConstants;
};
}
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif |
0fbf549449b9c2172f92a87083471fad3ea7407b | a5b43123d91d23581ae1f1cc725d7b004a4caa25 | /cpp/Tree/Balanced Brackets.cpp | 28574e4446967f0179d338b975a543c709ff2540 | [] | no_license | ivan570/code | 376001416a01f0a870a0d73796f1a61dd3bfe958 | e5a8e9bf7c9ea27b070ca3f351bb54cb16ce0317 | refs/heads/main | 2023-05-23T04:48:30.477060 | 2021-06-11T15:50:30 | 2021-06-11T15:50:30 | 330,686,610 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 951 | cpp | Balanced Brackets.cpp | #include <bits/stdc++.h>
using namespace std;
bool ans(string str) {
stack<int> st;
for (char i : str) {
if (i == '(' || i == '[' || i == '{')
st.push(i);
if (i == ')') {
if (st.empty() || st.top() != '(')
return false;
cout << i << endl;
st.pop();
}
if (i == '}') {
if (st.empty() || st.top() != '{')
return false;
cout << i << endl;
st.pop();
}
if (i == ']') {
if (st.empty() || st.top() != '[')
return false;
cout << i << endl;
st.pop();
}
}
return true;
}
void test_case() {
string str;
cin >> str;
if (ans(str))
cout << "YES" << endl;
else
cout << "NO" << endl;
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; ++i)
test_case();
return 0;
} |
193edadeca27f11f77b0e8996fc70ee92296865a | c3bbdbbbc5f47577e332a280f81bd905617423c9 | /Source/AllProjects/CIDLib/CIDLib_Facility.cpp | 2b2cd2eb101e6f56daf1cdfcf76b074cb3f6d022 | [
"MIT"
] | permissive | DeanRoddey/CIDLib | 65850f56cb60b16a63bbe7d6d67e4fddd3ecce57 | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | refs/heads/develop | 2023-03-11T03:08:59.207530 | 2021-11-06T16:40:44 | 2021-11-06T16:40:44 | 174,652,391 | 227 | 33 | MIT | 2020-09-16T11:33:26 | 2019-03-09T05:26:26 | C++ | UTF-8 | C++ | false | false | 16,100 | cpp | CIDLib_Facility.cpp | //
// FILE NAME: CIDLib_Facility.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 11/25/1996
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// TFacility is the basic facility class. All other Facility Classes are derived
// from this guy. It makes sure that all Facilities provide a basic public API,
// and it does a lot of the grunt work.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Facility specific includes
// ---------------------------------------------------------------------------
#include "CIDLib_.hpp"
// ---------------------------------------------------------------------------
// Do our RTTI macros
// ---------------------------------------------------------------------------
RTTIDecls(TFacility,TObject)
namespace
{
namespace CIDLib_Facility
{
// -----------------------------------------------------------------------
// Local types
//
// We have to maintain a local list of all constructed facilities. This
// allows lookup of facility objects by name. Facility objects are all
// singletons, so this is a reasonably safe thing to do. Because of the very
// fundamental nature of facilities, we do a custom data structure. Since
// facilities never die, we really only have to add. But, we do implement
// the code to remove upon destruction just in case.
// -----------------------------------------------------------------------
struct TFacListItem
{
tCIDLib::THashVal hshName;
TFacility* pfacThis;
TFacListItem* pfliNext;
};
// -----------------------------------------------------------------------
// Local const data
//
// hshModulus
// THe hash modulus used for hashing facility names.
//
// pszVersionFormat
// This is the format string for the version member. The provided maj,
// min, and revision values are formatted into it during construction.
// -----------------------------------------------------------------------
constexpr tCIDLib::THashVal hshModulus = 29;
constexpr const tCIDLib::TCh* const pszVersionFmt = L"%(1).%(2).%(3)";
// -----------------------------------------------------------------------
// Local data
//
// pfliHead
// The head of the facility list.
// -----------------------------------------------------------------------
TFacListItem* pfliHead = nullptr;
// -----------------------------------------------------------------------
// We need some light locking here. Because of the fundamental nature of
// modules and facilities, we use a lazy fault in scheme here.
// -----------------------------------------------------------------------
TCriticalSection* pcrsList()
{
static TCriticalSection crsList;
return &crsList;
}
}
}
// ---------------------------------------------------------------------------
// Local methods
// ---------------------------------------------------------------------------
static tCIDLib::TVoid AddToList(TFacility* const pfacNew)
{
CIDLib_Facility::TFacListItem* pfliNew = new CIDLib_Facility::TFacListItem;
pfliNew->hshName = pfacNew->strName().hshCalcHash(CIDLib_Facility::hshModulus);
pfliNew->pfacThis = pfacNew;
// Lock the list and add the new facility
TCritSecLocker lockList(CIDLib_Facility::pcrsList());
pfliNew->pfliNext = CIDLib_Facility::pfliHead;
CIDLib_Facility::pfliHead = pfliNew;
}
static tCIDLib::TVoid RemoveFromList(const TFacility* const pfacToRemove)
{
// Lock the list while we search
TCritSecLocker lockList(CIDLib_Facility::pcrsList());
CIDLib_Facility::TFacListItem* pfliCur = CIDLib_Facility::pfliHead;
CIDLib_Facility::TFacListItem* pfliPrev = nullptr;
while (pfliCur)
{
if (pfliCur->pfacThis == pfacToRemove)
{
//
// If the previous is zero, then this is the head node, so we
// do the simpler scenario. Else, we patch around.
//
if (pfliPrev)
pfliPrev->pfliNext = pfliCur->pfliNext;
else
CIDLib_Facility::pfliHead = pfliCur->pfliNext;
// And free this node and break out
delete pfliCur;
break;
}
pfliPrev = pfliCur;
pfliCur = pfliPrev->pfliNext;
}
}
// ---------------------------------------------------------------------------
// CLASS: TFacility
// PREFIX: fac
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TFacility: Public, static methods
// ---------------------------------------------------------------------------
// Get/set the global log mode
tCIDLib::ESeverities
TFacility::eGlobalLogMode(const tCIDLib::ESeverities eSevToSet)
{
s_eGlobalLogMode = eSevToSet;
return s_eGlobalLogMode;
}
tCIDLib::ESeverities TFacility::eGlobalLogMode()
{
return s_eGlobalLogMode;
}
// Look up a facility by name
TFacility* TFacility::pfacFromName(const TString& strFacName)
{
// Get the hash of the passed name for use in the search
const tCIDLib::THashVal hshName = strFacName.hshCalcHash(CIDLib_Facility::hshModulus);
// Lock the list while we search
TCritSecLocker lockList(CIDLib_Facility::pcrsList());
// Try to find the passed name in the local hash table
CIDLib_Facility::TFacListItem* pfliCur = CIDLib_Facility::pfliHead;
while (pfliCur)
{
if (pfliCur->hshName == hshName)
{
if (strFacName == pfliCur->pfacThis->strName())
return pfliCur->pfacThis;
}
pfliCur = pfliCur->pfliNext;
}
return nullptr;
}
TFacility& TFacility::facFromName(const TString& strFacName)
{
TFacility* pfacRet = pfacFromName(strFacName);
if (!pfacRet)
{
facCIDLib().ThrowErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcMod_CantFindFac
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::NotFound
, strFacName
);
}
return *pfacRet;
}
// ---------------------------------------------------------------------------
// TFacility: Constructors and Destructor
// ---------------------------------------------------------------------------
TFacility::TFacility( const TString& strFacName
, const tCIDLib::EModTypes eModType
, const tCIDLib::TCard4 c4MajVer
, const tCIDLib::TCard4 c4MinVer
, const tCIDLib::TCard4 c4Revision
, const tCIDLib::EModFlags eFlags
, const tCIDLib::TBoolean bLoad) :
TModule(strFacName, eModType, c4MajVer, c4MinVer, eFlags, bLoad)
, m_c4MajVer(c4MajVer)
, m_c4MinVer(c4MinVer)
, m_c4Revision(c4Revision)
{
// Make sure it's just a facility name, not a path
if (strFacName.bContainsChar(kCIDLib::chPathSep))
{
facCIDLib().ThrowErr
(
CID_FILE
, CID_LINE
, kCIDErrs::errcMod_OnlyBaseName
, strFacName
, tCIDLib::ESeverities::Failed
, tCIDLib::EErrClasses::AppError
);
}
// Call a common init method
CommonInit(strFacName, c4MajVer, c4MinVer, c4Revision);
// Add this facilty to the facility list
AddToList(this);
}
// This one is always a load, not a query, since it's from a path
TFacility::TFacility( const TString& strFacName
, const TString& strFromPath
, const tCIDLib::EModTypes eModType
, const tCIDLib::TCard4 c4MajVer
, const tCIDLib::TCard4 c4MinVer
, const tCIDLib::TCard4 c4Revision
, const tCIDLib::EModFlags eFlags) :
TModule(strFacName, strFromPath, eModType, c4MajVer, c4MinVer, eFlags)
, m_c4MajVer(c4MajVer)
, m_c4MinVer(c4MinVer)
, m_c4Revision(c4Revision)
{
// Call a common init method
CommonInit(strFacName, c4MajVer, c4MinVer, c4Revision);
// Add this facilty to the facility list
AddToList(this);
}
TFacility::~TFacility()
{
RemoveFromList(this);
}
// ---------------------------------------------------------------------------
// TFacility: Public, non-virtual methods
// ---------------------------------------------------------------------------
//
// Similar to eLogMode below, but a more convenient syntax for code to use
// to check whether something they want to log at a given level should be
// logged or not, i.e. whehter the passed severity is above the level for
// this facility (or the global mode.)
//
tCIDLib::TBoolean
TFacility::bShouldLogAt(const tCIDLib::ESeverities eToCheck) const
{
// Grab the verbosity for this facility from the stats cache
tCIDLib::ESeverities eSev = tCIDLib::ESeverities
(
TStatsCache::c8CheckValue(m_sciLogThreshold)
);
// Sanity check it and adjust if needed
if (eSev >= tCIDLib::ESeverities::Count)
eSev = tCIDLib::ESeverities::Max;
return ((eToCheck >= eSev) || (eToCheck >= s_eGlobalLogMode));
}
//
// When exceptions are caught, the code often wants to see if should log
// the exception. This will do that check for them.
//
tCIDLib::TBoolean TFacility::bShouldLog(const TLogEvent& logeToCheck) const
{
// If already logged, say no
if (logeToCheck.bLogged())
return kCIDLib::False;
// Else just check its severity
return bShouldLogAt(logeToCheck.eSeverity());
}
// Return the verion and revision values of this facility
tCIDLib::TCard4 TFacility::c4MajVersion() const
{
return m_c4MajVer;
}
tCIDLib::TCard4 TFacility::c4MinVersion() const
{
return m_c4MinVer;
}
tCIDLib::TCard4 TFacility::c4Revision() const
{
return m_c4MinVer;
}
//
// Return the logging verbosity from the stats cache for this facility,
// or the global mode, whichever is lower.
//
tCIDLib::ESeverities TFacility::eLogThreshold() const
{
// Grab the verbosity for this facility from the stats cache
tCIDLib::ESeverities eSev = tCIDLib::ESeverities
(
TStatsCache::c8CheckValue(m_sciLogThreshold)
);
// Sanity check it and adjust if needed
if (eSev >= tCIDLib::ESeverities::Count)
eSev = tCIDLib::ESeverities::Max;
// If the facility level mode is larger than the global, return the global
if (eSev > s_eGlobalLogMode)
return s_eGlobalLogMode;
// Otherwise, return the facility specific mode
return eSev;
}
// Provide access to our version formatted out in standard test form
const TString& TFacility::strVersion() const
{
return m_strVersion;
}
//
// Set our logging flags. They caller provides the bits to change and a mask of those
// they want to be affected.
//
tCIDLib::TVoid
TFacility::SetLoggingFlags( const tCIDLib::TCard8 c8ToSet
, const tCIDLib::TCard8 c8Mask)
{
// Get the current value as the full Card8
tCIDLib::TCard8 c8Val = TStatsCache::c8CheckValue(m_sciLogFlags);
// Turn off any mask bits, then set the ones that need setting
c8Val &= ~c8Mask;
c8Val |= (c8Mask & c8ToSet);
// ANd now set it back
TStatsCache::SetValue(m_sciLogFlags, c8Val);
}
// Set our logging threshold
tCIDLib::TVoid TFacility::SetLogThreshold(const tCIDLib::ESeverities eToSet)
{
TStatsCache::SetValue(m_sciLogThreshold, tCIDLib::c4EnumOrd(eToSet));
}
//
// Set our log tracing flag. If set, we log all thrown exceptions, or or parent
// TModule class does.
//
tCIDLib::TVoid TFacility::SetLogTrace(const tCIDLib::TBoolean bToSet)
{
TStatsCache::bSetFlag(m_sciLogTrace, bToSet);
}
// ---------------------------------------------------------------------------
// TFacility: Protected, inherited methods
// ---------------------------------------------------------------------------
//
// Let our parent class see our error tracking setting. If it's set, he will log
// all thrown exceptions.
//
tCIDLib::TBoolean TFacility::bTraceErrs() const
{
return TStatsCache::bCheckFlag(m_sciLogTrace);
}
// ---------------------------------------------------------------------------
// TFacility: Protected, non-virtual methods
// ---------------------------------------------------------------------------
//
// We cannot provide these directly, because each facility has it's own logging
// flag enum and we want each to have its own, typesafe, method. But they can just
// turn around and call us here after converting the enum to a number and we can
// do the work.
//
// We call our bShouldLog type methods above to check the overall severity. If it
// returns true, then we also check the indicated flag bit.
//
tCIDLib::TBoolean
TFacility::bCheckLogFlags( const tCIDLib::ESeverities eToCheck
, const tCIDLib::TCard4 c4FlagBit) const
{
if (!bShouldLogAt(eToCheck))
return kCIDLib::False;
return TStatsCache::bCheckBitFlag(m_sciLogFlags, c4FlagBit);
}
tCIDLib::TBoolean
TFacility::bCheckLogFlags( const TLogEvent& logeToCheck
, const tCIDLib::TCard4 c4FlagBit) const
{
if (!bShouldLog(logeToCheck))
return kCIDLib::False;
return TStatsCache::bCheckBitFlag(m_sciLogFlags, c4FlagBit);
}
// ---------------------------------------------------------------------------
// TFacility: Private, non-virtual methods
// ---------------------------------------------------------------------------
// Theres a bit of setup and we have more than one ctor so this is broken out
tCIDLib::TVoid
TFacility::CommonInit( const TString& strFacName
, const tCIDLib::TCard4 c4MajVer
, const tCIDLib::TCard4 c4MinVer
, const tCIDLib::TCard4 c4Revision)
{
//
// Set the log level initial to any value that might have been set on
// the command line or in the environment for this facility. This
// wil register the item and default to the correct type because of
// the method we call.
//
TString strKey(kCIDLib::pszStat_Scope_LogThresh);
strKey.Append(strFacName);
TStatsCache::SetValue
(
strKey.pszBuffer()
, m_sciLogThreshold
, tCIDLib::c4EnumOrd(TSysInfo::eDefModuleLog(strFacName))
);
// For this one, the default value is fine, so just register it
strKey = kCIDLib::pszStat_Scope_LogFlags;
strKey.Append(strFacName);
TStatsCache::RegisterItem(strKey.pszBuffer(), tCIDLib::EStatItemTypes::BitFlags, m_sciLogFlags);
// For this one, the default value is fine, so just register it
strKey = kCIDLib::pszStat_Scope_LogTrace;
strKey.Append(strFacName);
TStatsCache::RegisterItem(strKey.pszBuffer(), tCIDLib::EStatItemTypes::Flag, m_sciLogTrace);
// Format the version
m_strVersion = CIDLib_Facility::pszVersionFmt;
m_strVersion.eReplaceToken(c4MajVer, L'1');
m_strVersion.eReplaceToken(c4MinVer, L'2');
m_strVersion.eReplaceToken(c4Revision, L'3');
}
// ---------------------------------------------------------------------------
// TFacility: Private, static data members
// ---------------------------------------------------------------------------
tCIDLib::ESeverities TFacility::s_eGlobalLogMode(tCIDLib::ESeverities::Failed);
|
3e86d2904517349884bd92aa2c76df497567e066 | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/openscreen/src/cast/standalone_sender/streaming_encoder_util.h | d4d00b4282c49ef4524d7f581321fa2d7b789e51 | [
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 607 | h | streaming_encoder_util.h | // Copyright 2021 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 CAST_STANDALONE_SENDER_STREAMING_ENCODER_UTIL_H_
#define CAST_STANDALONE_SENDER_STREAMING_ENCODER_UTIL_H_
#include <stdint.h>
namespace openscreen {
namespace cast {
void CopyPlane(const uint8_t* src,
int src_stride,
int num_rows,
uint8_t* dst,
int dst_stride);
} // namespace cast
} // namespace openscreen
#endif // CAST_STANDALONE_SENDER_STREAMING_ENCODER_UTIL_H_
|
97c3fbef7ba12c479b8365eb2936cc6a896ce93c | 06034ec6c90d8cd8fc7e4a8c70c62b838f186ab1 | /fluorender/FluoRender/Glyph.cpp | c380ff4aeb8e78ffcade4bb5609947dc01ade763 | [
"BSD-3-Clause",
"MIT"
] | permissive | JaneliaSciComp/VVDViewer | 5b2dd4ca3dc0c8a3b4f4de231f1a4b04d6c48d5c | dd4b9a78867f1425e5cb6ddebb6e788a5186f088 | refs/heads/master | 2023-07-19T18:16:15.196545 | 2023-07-18T13:47:26 | 2023-07-18T13:47:26 | 369,368,663 | 10 | 2 | NOASSERTION | 2023-04-13T17:12:04 | 2021-05-21T00:12:31 | C++ | UTF-8 | C++ | false | false | 2,185 | cpp | Glyph.cpp | //
// Created by snorri on 10.10.2018.
//
#include <stdexcept>
#include "Glyph.h"
#include "TextureAtlas.h"
Glyph::Glyph(FT_Face face, FT_UInt ix, std::shared_ptr<TextureAtlas> ta) : m_face(face), m_glyphIndex(ix) {
auto error = FT_Load_Glyph(m_face, m_glyphIndex, FT_LOAD_DEFAULT);
if(error) {
throw std::runtime_error("failed to load glyph");
}
FT_GlyphSlot glyphSlot = m_face->glyph;
error = FT_Render_Glyph(glyphSlot, FT_RENDER_MODE_NORMAL);
if(error) {
throw std::runtime_error("failed to render glyph");
}
m_left = glyphSlot->bitmap_left;
m_top = glyphSlot->bitmap_top;
m_width = static_cast<int>(glyphSlot->metrics.width / 64);
m_height = static_cast<int>(glyphSlot->metrics.height / 64);
m_advance = static_cast<int>(glyphSlot->advance.x / 64);
CreateTextureFromBitmap(ta);
}
void Glyph::CreateTextureFromBitmap(std::shared_ptr<TextureAtlas> &ta) {
FT_GlyphSlot glyphSlot = m_face->glyph;
if(glyphSlot->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY || glyphSlot->bitmap.num_grays != 256) {
throw std::runtime_error("unsupported pixel mode");
}
auto width = glyphSlot->bitmap.width;
auto height = glyphSlot->bitmap.rows;
auto bufferSize = width*height*4;
if(bufferSize == 0) {
return;
}
std::vector<uint8_t> buffer(bufferSize);
uint8_t* src = glyphSlot->bitmap.buffer;
uint8_t* startOfLine = src;
int dst = 0;
for(int y = 0; y < height; ++y) {
src = startOfLine;
for(int x = 0; x < width; ++x) {
auto value = *src;
src++;
buffer[dst++] = value;
buffer[dst++] = value;
buffer[dst++] = value;
buffer[dst++] = value;
}
startOfLine += glyphSlot->bitmap.pitch;
}
m_texture = ta->Add(width, height, buffer.data());
}
int Glyph::GetLeft() {
return m_left;
}
int Glyph::GetTop() {
return m_top;
}
std::shared_ptr<AtlasTexture> Glyph::GetTexture() {
return m_texture;
}
int Glyph::GetWidth() {
return m_width;
}
int Glyph::GetHeight() {
return m_height;
}
int Glyph::GetAdvance() {
return m_advance;
}
|
9f1ca407a8872fe561b26fcfce42d486a6da46be | 14e329dc48069ce714014488e285018907b36f17 | /core/vision/LineDetector.cpp | e39e17070e38d05fc43e8d6133ef0f7b892768bc | [] | no_license | aliunwala/backuprobocup | 685a80a90953adb064b4bb39a59564f097a9cae4 | 2227baba1e19b1b097b484a8ee187e82bbc7e140 | refs/heads/master | 2020-12-30T10:23:14.892137 | 2013-10-31T00:05:46 | 2013-10-31T00:05:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,388 | cpp | LineDetector.cpp | #include <vision/LineDetector.h>
LineDetector::LineDetector(DETECTOR_DECLARE_ARGS, Classifier*& classifier, BlobDetector*& blob_detector) :
DETECTOR_INITIALIZE, classifier_(classifier), blob_detector_(blob_detector) {
FieldLinesCounter = 0;
fieldLines = new FieldLine * [MAX_FIELDLINES];
for (int i = 0; i < MAX_FIELDLINES; i++) {
fieldLines[i] = new FieldLine();
fieldLines[i]->id = i;
fieldLines[i]->TranPointsArray = new LinePoint * [MAX_POINTS_PER_LINE];
fieldLines[i]->PointsArray = new LinePoint * [MAX_POINTS_PER_LINE];
for (int j = 0; j < MAX_POINTS_PER_LINE; j++)
fieldLines[i]->TranPointsArray[j] = new LinePoint();
for (int j = 0; j < MAX_POINTS_PER_LINE; j++)
fieldLines[i]->PointsArray[j] = new LinePoint();
}
}
void LineDetector::detectLine(bool topCamera) {
/*if(topCamera){ return; }
int imageX, imageY;
bool foundLine = false;
findLine(imageX, imageY, foundLine); // function defined elsewhere that fills in imageX, imageY by reference
WorldObject* line = &vblocks_.world_object->objects_[WO_OPP_GOAL_LINE];
if(foundLine)
{
line->imageCenterX = imageX;
line->imageCenterY = imageY;
Position p = cmatrix_.getWorldPosition(imageX, imageY);
line->visionBearing = cmatrix_.bearing(p);
line->visionElevation = cmatrix_.elevation(p);
line->visionDistance = cmatrix_.groundDistance(p);
}
line->fromTopCamera = topCamera;
line->seen = foundLine;*/
}
void LineDetector::findLine(int& imageX, int& imageY , bool& found) {
/*int lowestWhite = 0;
imageX = 0;
imageY = 0;
int allowedBlank = 5;
int seenBlank = 0;
int totalMiddleToUse = 15;
int totalBlankMiddle = 0;
int runningMiddleAverage = 0;
int begRange = (iparams_.width/2.0)-7;
int endRange = (iparams_.width/2.0)+7;
int whiteColumns = 0;
int leftEmptyPixels = 0;
for(int x = 0; x < iparams_.width; x++) {
bool seenGreen = false;
for(int y=iparams_.height-1; y >= -1; y--)
{
if(y==-1)
{
if(x>=begRange && x<=endRange)
{
totalBlankMiddle++;
}
// seenBlank++;
// if(seenBlank > allowedBlank)
// {
// found = false;
// printf("NO WHITE LINE\n");
// return;
// }
}
else if(getSegPixelValueAt(x, y) == c_FIELD_GREEN)
{
seenGreen = true;
}
else if((getSegPixelValueAt(x, y) == c_WHITE) && seenGreen)
{
whiteColumns++;
if(lowestWhite < y)
{
lowestWhite = y;
}
if(x>=begRange && x<=endRange)
{
runningMiddleAverage += y;
}
seenBlank = 0;
y = -2;
}
}
}
int middleAverage = 0;
if((whiteColumns+0.0)/(iparams_.width+0.0) < 0.5)
{
// printf("PERCENTAGE: %f \n", (whiteColumns+0.0)/(iparams_.width+0.0));
found = false;
return;
}
if((totalMiddleToUse-totalBlankMiddle)!=0)
{
middleAverage = (runningMiddleAverage)/(totalMiddleToUse-totalBlankMiddle);
}
//printf("AVG: %d > %f\n and totalBlankMiddle = %d \n", middleAverage, iparams_.height*.8, totalBlankMiddle);
found = (middleAverage+0.0) > iparams_.height*.8;
// printf("%d > %f\n", lowestWhite, iparams_.height*.8);*/
}
|
b7eb9d5eb1f657937246a81330176b74396f8956 | ef6ef195ecff4a349d7cb2611bd67ba2ab92f34b | /hdu.cpp/杭电1800.cpp | b0446324376048210c49804aacbe3142cf0b023b | [] | no_license | GDDXH/First-year-of-University | 2f721ca182c02c8dde3fe957dc69bd825969ac43 | 67ec100de6bc03cb538f8db5babcd32c1ab3e992 | refs/heads/master | 2020-12-10T09:09:43.968893 | 2020-01-13T09:32:47 | 2020-01-13T09:32:47 | 233,552,368 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 567 | cpp | 杭电1800.cpp | #include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<string>
#include<cstring>
#include<cstdlib>
#include<cctype>
using namespace std;
int main()
{
int N,i,max,k,soldier_level[3001];
while(scanf("%d",&N)!=EOF)
{
for(i=0;i<N;i++)
scanf("%d",&soldier_level[i]);
sort(soldier_level,soldier_level+N);
for(i=1,max=0,k=1;i<N;i++)
{
if (soldier_level[i-1]==soldier_level[i])
k++;
else
{
if(k>max)
max=k;
k=1;
}
}
if(k>max)
max=k;
printf("%d\n",max) ;
}
return 0;
}
|
d2a9b2eeb7c1bbddc49f27d920791fc590ca30ce | c3a79a4708a9e99fe22964a6291990b861313b7d | /OR_thodox_Distinction.cpp | ebde17b5d284218f36e4dc14024da3609b78f7b1 | [] | no_license | parthkris13/CC-Solutions | d04ef8f15e5c9e019d2cf8d84ca1649d84b4f51d | d190294bfb44449b803799819ee1f06f5f6c5a17 | refs/heads/main | 2023-04-11T11:04:11.042172 | 2021-04-29T14:15:33 | 2021-04-29T14:15:33 | 323,133,672 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,135 | cpp | OR_thodox_Distinction.cpp | #include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
#define int long long int
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int32_t main(){
IOS;
int t;
cin >> t;
while(t--){
int n;
cin >> n;
int arr[n];
for(int i = 0; i<n; i++) cin >> arr[i];
int r = (n*(n+1))/2;
int k = 0;
int flag =0;
int par[r]={0};
for(int i=0; i<r; i++){
cout << par[i] << " ";
}
cout << endl;
for(int i = 0; i<n; i++){
// int x = arr[i];
for(int j = i; j<n; j++){
for(int l = i; l <= j; l++){
par[k] = par[k] | arr[l];
}
k++;
}
}
sort(par, par+r);
for(int i=0; i<r; i++){
cout << par[i] << " ";
}
cout << endl;
for(int i =0; i<r; i++){
if(par[i] == par[i-1]){
flag = 1;
break;
}
}
if(flag) cout << "NO" << endl;
else cout << "YES" << endl;
}
return 0;
}
|
ffe0c70eb17f614ae591ab2208f855e845476783 | 4b55cc0ff3190d76ce208c9da4d70c550e9b85f2 | /dbconnect.cpp | 4fccb43f318895f2400f08a10d7d26711825caec | [] | no_license | ostRa19/Simple-Qt-application | fd03df5016421e0624fce965d02566a947ba9aea | 5fba12371fbdd9d5a27789a3607315130f3aaf43 | refs/heads/master | 2021-05-18T14:53:04.984808 | 2020-03-30T11:51:47 | 2020-03-30T11:51:47 | 251,288,686 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,828 | cpp | dbconnect.cpp | #include "dbconnect.h"
DbAdapter::DbAdapter()
{
db = QSqlDatabase::addDatabase("QODBC3");//QMYSQL
}
DbAdapter::~DbAdapter()
{
}
DbAdapter::DbAdapter(QString adapterType)
{
db = QSqlDatabase::addDatabase(adapterType);
}
DbAdapter::DbAdapter(DbAdapter* adapter)
{
this->db = adapter->db;
}
bool DbAdapter::createConnection()
{
if (db.isOpen()) return true;
else if(db.open()) return true;
db.setDatabaseName("DRIVER={SQL Server};SERVER=LAPTOP-LNO34RK6;Trusted_Connection=Yes; DATABASE=TSS;");
if (!db.open())
{
qDebug() << "Cannot open database:" << db.lastError();
return false;
}
else
{
QSqlQuery* query = new QSqlQuery(db);
query->exec("SELECT name FROM master.dbo.sysdatabases");
qDebug() << "Connected to server" << db.hostName() << " with databases:";
while(query->next())
qDebug() << query->value(0).toString();
query->clear();
delete query;
return true;
}
}
bool DbAdapter::executeQuery(QString sqlCode)
{
if (db.isOpen())
{
QSqlQuery* query = new QSqlQuery(db);
if(query->exec(sqlCode))
{
return true;
}
else
qDebug() << "Query error:" << db.lastError();
}
else
{
db.open();
return executeQuery(sqlCode);
}
return false;
}
bool DbAdapter::fillTable(QTableView* table, QString selectQuery)
{
if (db.isOpen())
{
model.setQuery(selectQuery);
if(model.lastError().isValid())
{
qDebug() << "Model error: " << model.lastError();
return false;
}
table->setModel(&model);
//db.close();
return true;
}
else
{
db.open();
return fillTable(table, selectQuery);
}
}
|
cf70234564197db7540d08ca99582b2484c7b128 | 201aeac0e0dd9c1fc3e4a9f0ad51344e6235a032 | /CO302_Compiler_Design/CD_Lab/L3_token_count.cpp | 74f8e03dd115ccd69cebd572583937c51cf971ee | [] | no_license | IsCoelacanth/6thSem_At_DTU | b1d298766d7fc3bb3a21f43b1ac0946605c3f514 | ab1a32755b297376f75fa5c69b4e8c74863742f5 | refs/heads/master | 2021-03-27T13:05:09.987230 | 2021-02-23T06:54:33 | 2021-02-23T06:54:33 | 116,067,762 | 8 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,180 | cpp | L3_token_count.cpp | #include<bits/stdc++.h>
using namespace std;
map<string, pair<string, int> > Table;
string t[] = { "auto","break","case","char","const","continue","default","do","double","else","enum","extern","float","for","goto","if","int","long","register","return","short","signed","sizeof","static","struct","switch","typedef","union","unsigned","void","volatile","while"
};
set<string> keyw(t, t+13);
string o[] = { "+", "-", "*", "*", "<<", ">>", ".", "==", "<", ">", "!=", "!", "=" };
set<string> opr(o, o + 13);
int main()
{
ifstream fin("Text.cpp");
string line, temp;
while (!fin.eof())
{
getline(fin, line);
// cout << "Line : " << line << endl;
if (line[0] == '#' || (line[0] == '/' && line[1] == '/'))
continue;
int i = 0;
while( i < line.length())
{
temp.clear();
if (line[i] == ' ' || line[i] == '\t')
{
while(line[i] == ' ' || line[i] == '\t')
i++;
// getchar();
// i--;
}
else if (isalpha(line[i]))
{
while ((line[i] != ' ' ) && i < line.length() && isalnum(line[i]))
temp += line[i++];
// cout << "temp : " << temp << endl;
if (keyw.find(temp) != keyw.end())
{
Table[temp].second++;
Table[temp].first = "Keyword";
}
else
{
Table[temp].second++;
Table[temp].first = "Identifier";
}
temp.clear();
// i--;
}
else if (isdigit(line[i]))
{
while(isdigit(line[i]))
temp += line[i++];
// cout << "temp : " << temp << endl;
Table[temp].second++;
Table[temp].first = "Constant/Literal";
temp.clear();
}
else
{
while (line[i] != ' ' && i < line.length() && !(isalnum(line[i])))
temp += line[i++];
// cout << "temp : " << temp << endl;
if (opr.find(temp) != opr.end())
{
Table[temp].second++;
Table[temp].first = "Operator";
}
temp.clear();
}
}
}
fin.close();
map<string, pair<string, int> >::iterator it;
for (it = Table.begin(); it != Table.end(); it++)
{
cout << "Name : " << it->first << " Type : " << it->second.first << " Count : " << it->second.second << endl;
}
return 0;
} |
f34ca3015ff6acb6dfcfc210664de1785dd247cc | 55f157f70614c954a1c163c898fbf1916bff694e | /CoffeemakerPS/lib/AWS_IOT/examples/DHT11_Logger/DHT11_Logger.ino | e024651d31d98ed4dd0fd71260cccb8dfa6e5fc7 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] | permissive | thankthemaker/sharespresso | f458204ad26b62e45b6f6735573ae55061148bc9 | f0295f04dd3be8a6d2edae751551df050e90afcd | refs/heads/master | 2021-06-07T14:36:07.378712 | 2019-12-16T10:25:10 | 2019-12-16T10:25:10 | 111,951,978 | 8 | 4 | MIT | 2018-10-06T15:31:15 | 2017-11-24T20:03:08 | C++ | UTF-8 | C++ | false | false | 2,572 | ino | DHT11_Logger.ino |
#include <AWS_IOT.h>
#include <WiFi.h>
#include "DHT.h"
#define DHTPIN 4 // what digital pin we're connected to
// Uncomment whatever type you're using!
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
DHT dht(DHTPIN, DHTTYPE);
AWS_IOT hornbill; // AWS_IOT instance
char WIFI_SSID[]="your Wifi SSID";
char WIFI_PASSWORD[]="Wifi Password";
char HOST_ADDRESS[]="AWS host address";
char CLIENT_ID[]= "client id";
char TOPIC_NAME[]= "your thing/topic name";
int status = WL_IDLE_STATUS;
int tick=0,msgCount=0,msgReceived = 0;
char payload[512];
char rcvdPayload[512];
void setup() {
Serial.begin(115200);
delay(2000);
while (status != WL_CONNECTED)
{
Serial.print("Attempting to connect to SSID: ");
Serial.println(WIFI_SSID);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
// wait 5 seconds for connection:
delay(5000);
}
Serial.println("Connected to wifi");
if(hornbill.connect(HOST_ADDRESS,CLIENT_ID)== 0) // Connect to AWS using Host Address and Cliend ID
{
Serial.println("Connected to AWS");
delay(1000);
}
else
{
Serial.println("AWS connection failed, Check the HOST Address");
while(1);
}
delay(2000);
dht.begin(); //Initialize the DHT11 sensor
}
void loop() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Failed to read from DHT sensor!");
}
else
{
sprintf(payload,"Humidity:%f Temperature:%f'C",h,t); // Create the payload for publishing
if(hornbill.publish(TOPIC_NAME,payload) == 0) // Publish the message(Temp and humidity)
{
Serial.print("Publish Message:");
Serial.println(payload);
}
else
{
Serial.println("Publish failed");
}
// publish the temp and humidity every 5 seconds.
vTaskDelay(5000 / portTICK_RATE_MS);
}
}
|
271feaa1411acedc709c23164937815db2dcca9e | f0cb80bcba4fcdff0969ffe6d4b343ff61655965 | /MemoForm/CStatusButton.cpp | 27cb5b84d0ac5b4adad533b53018a0debf7f8796 | [] | no_license | rlagudtn/Memo | 4975c5cede72542ef1dbcf965989ca0403deff99 | ff15a9780b84d10a93cf66e9bf8771268fbe112d | refs/heads/master | 2023-06-06T07:59:18.326987 | 2021-06-24T05:50:32 | 2021-06-24T05:50:32 | 113,292,651 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 859 | cpp | CStatusButton.cpp | //CStatusButton.cpp
#include "CStatusButton.h"
CStatusButton::CStatusButton(){}
CStatusButton::~CStatusButton(){}
void CStatusButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) {
CDC dc;
dc.Attach(lpDrawItemStruct->hDC);
CRect rt;
rt = lpDrawItemStruct->rcItem;
//상태바와 같은색으로 색칠
//dc.FillSolidRect(rt, RGB(204, 204, 204));
//버튼상태 가져오기
UINT nstate = lpDrawItemStruct->itemState;
//눌릴때
if (nstate&ODS_SELECTED) {
dc.DrawEdge(rt, EDGE_SUNKEN, BF_SOFT);
dc.FillSolidRect(rt, RGB(255, 255, 255));
dc.SetTextColor(RGB(0, 0, 255));
//dc.SetBkMode(OPAQUE);
EnableWindow(FALSE);
}
else {
dc.DrawEdge(rt, EDGE_RAISED, BF_LEFT | BF_RIGHT);
}
//버튼에 있는 글자 받아온다.
CString str;
GetWindowText(str);
dc.DrawText(str, rt, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
dc.Detach();
} |
bb2ad748d437f572fd5be4f4463680d66407f743 | a3a3a5f07abf9dc91921fb7291f454e16a64f135 | /opengl_mycar/Track.cpp | 66329fec5a33970ab4cbe5db2317e86c9b81be1a | [] | no_license | sjnam450/OpenGL_mycar | 508742b8165ceb0abac098c0eb8a89949f6743bc | 56ce848ccf4897e4093381c092aa290d1df2796a | refs/heads/master | 2020-07-17T09:18:45.508478 | 2016-12-16T00:58:45 | 2016-12-16T00:58:45 | 73,932,738 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,065 | cpp | Track.cpp | //
// Track.cpp
// opengl_mycar
//
// Created by sjnam on 12/2/16.
// Copyright © 2016 sjnam. All rights reserved.
//
#include "Track.hpp"
Track::Track() {
}
void Track::draw_track(float R1,float R2) {
float X,Y,Z;
int y;
Y = 0;
glPushMatrix();
//
// GLfloat specular[] = {1.0f, 1.0f, 1.0f, 1.0f};
//
// glEnable(GL_COLOR_MATERIAL);
// glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
// glColor4f(0.75f, 0.75f, 0.75f, 1.0f);
// glMaterialfv(GL_FRONT, GL_SPECULAR, specular);
// glMateriali(GL_FRONT, GL_SHININESS, 10);
glColor3f(0.3,0.3,0.3);
glPushMatrix();
glTranslatef(-1200, 0, 0);
glBegin(GL_QUAD_STRIP);
for (y=0; y<=2401; y++) {
X = y;
Z = -50;
glVertex3f(X,Y,Z);
glNormal3f(0, 1, 0);
Z = 50;
glVertex3f(X,Y,Z);
glNormal3f(0, 1, 0);
}
glEnd();
glPopMatrix();
//glLoadIdentity();
glPushMatrix();
glTranslatef(1200, 0, 50 + R2);
//glTranslatef(10, 0, 10);
glBegin(GL_QUAD_STRIP);
for( y=-90;y<=91;y+=1) {
X=R1*cos(c*y);
Z=R1*sin(c*y);
glVertex3f(X,Y,Z);
glNormal3f(0, 1, 0);
X=R2*cos(c*y);
Z=R2*sin(c*y);
glVertex3f(X,Y,Z);
glNormal3f(0, 1, 0);
}
glEnd();
glPopMatrix();
glPushMatrix();
glTranslatef(-1200, 0, 1300);
glBegin(GL_QUAD_STRIP);
for (y=0; y<=2400; y++) {
X = y;
Z = -50;
glVertex3f(X,Y,Z);
glNormal3f(0, 1, 0);
Z = 50;
glVertex3f(X,Y,Z);
glNormal3f(0, 1, 0);
}
glEnd();
glPopMatrix();
glPushMatrix();
glTranslatef(-1200, 0, 650);
glBegin(GL_QUAD_STRIP);
for( y=90;y<=271;y+=1) {
X=R1*cos(c*y);
Z=R1*sin(c*y);
glVertex3f(X,Y,Z);
glNormal3f(0, 1, 0);
X=R2*cos(c*y);
Z=R2*sin(c*y);
glVertex3f(X,Y,Z);
glNormal3f(0, 1, 0);
}
glEnd();
glPopMatrix();
}
|
6686a3dc8ac325ed5f94aaf6e6e36c6ddb55f119 | d1cee40adee73afdbce5b3582bbe4761b595c4e1 | /back/RtmpLivePushSDK/boost/boost/units/make_scaled_unit.hpp | 26a9efdd917a6a5aa89591733a25d92bc262aec1 | [
"BSL-1.0"
] | permissive | RickyJun/live_plugin | de6fb4fa8ef9f76fffd51e2e51262fb63cea44cb | e4472570eac0d9f388ccac6ee513935488d9577e | refs/heads/master | 2023-05-08T01:49:52.951207 | 2021-05-30T14:09:38 | 2021-05-30T14:09:38 | 345,919,594 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,781 | hpp | make_scaled_unit.hpp | // Boost.Units - A C++ library for zero-overhead dimensional analysis and
// unit/quantity manipulation and conversion
//
// Copyright (C) 2003-2008 Matthias Christian Schabel
// Copyright (C) 2007-2008 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_UNITS_MAKE_SCALED_UNIT_HPP_INCLUDED
#define BOOST_UNITS_MAKE_SCALED_UNIT_HPP_INCLUDED
#include "units_fwd.hpp"
#include "heterogeneous_system.hpp"
#include "unit.hpp"
namespace boost {
namespace units {
template<class Unit, class Scale>
struct make_scaled_unit {
typedef typename make_scaled_unit<typename reduce_unit<Unit>::type, Scale>::type type;
};
template<class Dimension, class UnitList, class OldScale, class Scale>
struct make_scaled_unit<unit<Dimension, heterogeneous_system<heterogeneous_system_impl<UnitList, Dimension, OldScale> > >, Scale> {
typedef unit<
Dimension,
heterogeneous_system<
heterogeneous_system_impl<
UnitList,
Dimension,
typename mpl::times<
OldScale,
list<scale_list_dim<Scale>, dimensionless_type>
>::type
>
>
> type;
};
template<class Dimension, class UnitList, class OldScale, long Base>
struct make_scaled_unit<unit<Dimension, heterogeneous_system<heterogeneous_system_impl<UnitList, Dimension, OldScale> > >, scale<Base, static_rational<0> > > {
typedef unit<
Dimension,
heterogeneous_system<
heterogeneous_system_impl<
UnitList,
Dimension,
OldScale
>
>
> type;
};
}
}
#endif
|
aac61e7ccad4c9db65b69e4ed9d836fe443d2a78 | cd1bad03ef80e9112aaa97c950a1fc4d74da7fc7 | /Practice(Beginner)/C++/HOW MANY DIGITS DO I HAVE.cpp | 2ab952e2d201d8917de670edd51775645f71fb10 | [] | no_license | UtsabSen/Codechef | 85a875443f0afbbc1b7b6d25e8731968ba385ae5 | 92ff47f6ae58824115bac15190c4c9f1b5a28e67 | refs/heads/master | 2021-04-02T22:47:28.711698 | 2020-05-16T08:56:54 | 2020-05-16T08:56:54 | 248,332,274 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 281 | cpp | HOW MANY DIGITS DO I HAVE.cpp | // Source: https://www.codechef.com/problems/HOWMANY
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int cnt = 0;
while(n){
cnt++;
n /= 10;
}
cnt < 4 ? cout << cnt : cout << "More than 3 digits";
} |
dbd66286fa5cfd8af74e1b8749b8453e90a994d9 | 597167bcff2f68d5dfbbca6b621604baab029af3 | /G_OnInit.cpp | c08f110244546240050dad4e656a6d9f39375759 | [] | no_license | rperruccio/Arcade | cea09c0437965880cbbb72f5c06addc64040bcd4 | 1208466e18529c4b936490dda8c58f712f7d202c | refs/heads/master | 2016-09-05T09:13:23.092816 | 2012-08-07T04:50:56 | 2012-08-07T04:50:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 355 | cpp | G_OnInit.cpp | #include "Game.h"
bool Game::OnInit()
{
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
return false;
if ((pantalla = SDL_SetVideoMode(WWIDTH, WHEIGHT, 32, SDL_HWSURFACE | SDL_DOUBLEBUF)) == NULL)
return false;
SDL_EnableKeyRepeat(1, SDL_DEFAULT_REPEAT_DELAY / 3);
StateManager::SetActiveState(STATE_INTRO);
return true;
}
|
800a447e2d22a033b7d040ce0b790b1a00aceb03 | 0ec697b71eb942c83a707f3231fd9e76e1cd6d70 | /permute.cpp | 19920b3c8291f6c258c832cd24611b7d404c1757 | [] | no_license | mahesh001/cn | 85e07cc6581dd748284e4b140960e909ff0f4b21 | 1b87755a131dac7007cc40ff0d93a20b2e3c7cda | refs/heads/master | 2020-02-26T16:07:53.942552 | 2016-10-16T11:47:47 | 2016-10-16T11:47:47 | 71,045,370 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 441 | cpp | permute.cpp | #include <iostream>
using namespace std;
void swap(char *str,int i,int j)
{
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
void permute(char *str,int l,int h)
{
if(l == h)
{
cout<<str<<endl;
}
else
{
for(int i=l;i<=h;i++)
{
swap(str,l,i);
permute(str,l+1,h);
swap(str,i,l);
}
}
}
int main()
{
char str[] = "abc";
int n = sizeof(str)/sizeof(str[0]);
cout<<"n is : "<<n<<endl;
permute(str,0,n-2);
}
|
fcd13a7ee347395f583edd9ee59492ce3ed55dac | da7ac77dca2cedd56325e0b8b518d3b499aaa0ed | /Contests/Codeforces Round #702 (Div. 3)/E. Accidental Victory.cpp | 8a9ed61f07c701add0066235ce916d0128c72ed3 | [] | no_license | KartikDholakia/CP-KartikDholakia | fdd89f7486be4f62ddb1968fbc0215942a456176 | 4748b2817f2229d97232e2711e2118a3bd6cc53c | refs/heads/master | 2023-07-18T21:25:36.497833 | 2021-09-06T05:23:45 | 2021-09-06T05:23:45 | 289,425,222 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,697 | cpp | E. Accidental Victory.cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef short int st;
#define MOD 1000000007
#define MAX 1000001 //1e6 + 1
#define INF 9223372036854775807
#define all(x) x.begin(), x.end()
#define pb(x) push_back(x)
#define mp make_pair
//E. Accidental Victory
//Codeforces Round #702 (Div. 3)
bool cmp(pair<int, int> a, pair<int, int> b) {
if (a.first < b.first)
return 1;
else if (a.first == b.first)
return a.second < b.second;
else
return 0;
}
void solve() {
int n, i, inp;
cin >> n;
vector<pair<int, int>> v; //first->value, 2nd->index
for (i = 0; i < n; i++) {
cin >> inp;
v.pb(make_pair(inp, i+1));
}
sort(all(v), cmp);
// for (i = 0; i < n; i++) {
// cout << v[i].first << " " << v[i].second << "\n";
// }
vector<int> prefix(n);
prefix[0] = v[0].first;
for (i = 1; i < n; i++) {
prefix[i] = prefix[i-1] + v[i].first;
}
vector<int> ans;
for (i = n-1; i >= 0; i--) {
if (i == n-1) {
ans.pb(v[i].second);
continue;
}
if (prefix[i] >= v[i+1].first)
ans.pb(v[i].second);
else
break;
}
cout << ans.size() << "\n";
for (i = ans.size()-1; i >= 0; i--)
cout << ans[i] << " ";
cout << "\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
#ifndef ONLINE_JUDGE
//remove this piece of code when this has to be submitted in kickstart
freopen("input.txt", "r", stdin);
freopen("error.txt", "w", stderr);
freopen("output.txt", "w", stdout);
//freopen is used to associate a file with stdin or stdout stream in C++
#endif
int t = 1;
cin >> t;
for (int i = 1; i <= t; i++) {
solve();
}
cerr << "time: "<<(double)clock()/CLOCKS_PER_SEC<<" secs"<<endl;
return 0;
} |
a0aa8196eecc54140dac65d7659865aeaa616e82 | 22365309a864cc9f7dfddef90c4bb7a005d29f37 | /Venda.h | 2f5d0eacf05783243db14c2a766b7051d31b2d13 | [
"MIT"
] | permissive | MurielPinho/FEUP-AEDA-GestaoMetro | c73ef77413d90f3805179062f84cc9ebec0084fe | 281f3cb46b059919786529b115b9690d2d55fb93 | refs/heads/master | 2021-08-02T03:50:40.416164 | 2021-07-26T19:22:09 | 2021-07-26T19:22:09 | 153,625,805 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,090 | h | Venda.h | #ifndef VENDA_H_
#define VENDA_H_
#include <fstream>
#include <limits>
#include "Utentes.h"
#include "Bilhete.h"
using namespace std;
// ! Classe Venda.
/*!
Contem funcoes responsaveis por controlar a gestao dos bilhetes.
*/
class Venda {
public:
//! Membro normal.
/*!
Chama a cadeia de funcoes para a compra do Bilhete.
*/
void comprarBilhete();
//! Membro normal.
/*!
Continuacao da funcao comprarBilhete() para compra em Maquina, adiciona o Bilhete ao vetor seu respectivo vetor.
*/
void comprarMaquina();
//! Membro normal.
/*!
Continuacao da funcao comprarBilhete() para compra em Loja, adiciona o Bilhete ao vetor seu respectivo vetor.
*/
void comprarLoja();
//! Membro normal.
/*!
Continuacao da funcao comprarBilhete() para bilhetes ocasionais.
\return Retorna um ponteiro de Bilhete do tipo ocasional.
*/
Bilhete* criarOcasional();
//! Membro normal.
/*!
Continuacao da funcao comprarBilhete() para bilhetes assinaturas.
\return Retorna um ponteiro de Bilhete do tipo assinatura.
*/
Bilhete* criarAssinatura();
//! Membro normal.
/*!
Efetua a confirmacao do pagamento, apos o output de preco.
\param preco float contendo o preco do bilhete.
\return Retorna o booleano relativo a realizacao do pagamento.
*/
bool Pagamento(float preco);
//! Membro normal.
/*!
Renova o bilhete do tipo Assinatura.
*/
void renovarAss();
//! Membro normal.
/*!
Valida um bilhete
*/
void validar();
//! Membro normal.
/*!
Imprime na tela a informacao resumida de cada bilhete atual.
*/
void Bilhetes();
//! Membro normal.
/*!
Imprime na tela a informacao resumida das assinaturas inativas.
*/
void AssinaturasInativas();
//! Membro normal.
/*!
Imprime na tela todos os dados do bilhete escolhido pelo usuario.
*/
void dadosBilhete();
//! Membro normal.
/*!
Faz a leitura do ficheiro, bilhetes.txt, com os dados da execucao anterior e do ficheiro, locais.txt, com os dados dos pontos de venda e os adiciona nos vetores apropriados.
*/
void readData();
//! Membro normal.
/*!
Escreve os bilhetes presentes nos vetores no ficheiro bilhetes.txt .
*/
void writeData();
//! Membro normal.
/*!
Altera o localAtual de acordo com o numero do local escolhido.
*/
void alterarLocal();
//! Membro normal.
/*!
\return Uma string com o nome do local atual.
*/
string localAtual();
//! Membro normal.
/*!
Imprime na tela a informacao de todos os pontos de venda.
*/
void Locais();
//! Membro normal.
/*!
Remove o bilhete escolhido pelo usuario, caso esse exista.
*/
void removeBilhete();
//! Membro normal.
/*!
\param Z inteiro contendo o numero de zonas.
\param D inteiro contendo a identificacao do desconto.
\return Um float do preco de bilhete de acordo com o numero de zonas e seu desconto.
*/
float precos(int Z, int D);
//! Membro normal.
/*!
\param b1 Bilhete para ser convertido.
\return Uma assinatura com os dados fornecidos em b1.
*/
Assinatura* BilAss(const Bilhete &b1) const;
};
#endif /*VENDA_H_*/
|
6e04487d212c39013d9b1c41bb515f4128a01404 | 75925ce20ff073c806b8f07ba65b65b78c7ec17f | /commands/impl/OCommand.cpp | 40528e6bbf7e5be34001e08bd7ffd24cf4c77a3c | [
"MIT"
] | permissive | markvolkov/BookStore | 6dfdbfd0305a3dde4e4640002b038f6f40eba14c | f27d1abca08959cbe725f9fa56fc43dc95d0b94d | refs/heads/master | 2021-08-30T22:25:03.832550 | 2017-12-19T16:31:32 | 2017-12-19T16:31:32 | 110,712,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 756 | cpp | OCommand.cpp | //
// Created by brien pacholec on 12/5/17.
//
#include "OCommand.h"
//Create a bulk purchase order for additional books based on a comparison of the have and want values in the inventory.
OCommand::OCommand(std::string identifier, BookManager* bookManager) {
this->identifier=identifier;
this->bookManager = bookManager;
}
std::string OCommand::toString() {
std::string oString = "O - Command: Order Books";
std::cout<<"IMPORTANT! Make sure there is a space between the command and entry."<<std::endl;
return oString;
}
void OCommand::execute(std::vector<std::string> args) {
this->bookManager->placeOrder(args[0]);
}
std::string OCommand::getName() {
return identifier;
}
int OCommand::argumentCount() {
return 1;
}
|
4ab2d44679d0b4fc195b96eebedfb56234b7c400 | 768371d8c4db95ad629da1bf2023b89f05f53953 | /applayerprotocols/httptransportfw/Test/T_FilterConfigIter/FilterConfigurationIteratorTransitions.inl | 28acaa49d3a2bc07364e1318a7475fd541f6ea5c | [] | no_license | SymbianSource/oss.FCL.sf.mw.netprotocols | 5eae982437f5b25dcf3d7a21aae917f5c7c0a5bd | cc43765893d358f20903b5635a2a125134a2ede8 | refs/heads/master | 2021-01-13T08:23:16.214294 | 2010-10-03T21:53:08 | 2010-10-03T21:53:08 | 71,899,655 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,497 | inl | FilterConfigurationIteratorTransitions.inl | // Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
// The implementation of the transition classes upon the TFilterConfigurationIterator class methods.
//
//
/**
@file FilterConfigurationIteratorTransitions.inl
*/
// ______________________________________________________________________________
//
_LIT(KFilterConfigurationIteratorNewLTransition,"CFilterConfigurationIterator_NewL_Transition");
inline CFilterConfigurationIterator_NewL_Transition::CFilterConfigurationIterator_NewL_Transition(CUnitTestContext& aUTContext,
TTransitionValidator& aValidator)
: CTransitionType(KFilterConfigurationIteratorNewLTransition, aUTContext, aValidator)
{
// Do nothing here.
}
inline void CFilterConfigurationIterator_NewL_Transition::TransitMethodL()
{
_LIT(KFilterConfigurationIteratorNewLTransitMethod, "CFilterConfigurationIterator::NewL transition");
Context().DataLogger().LogInformation(KFilterConfigurationIteratorNewLTransitMethod);
Context().CreateFilterIterL();
}
inline CFilterConfigurationIterator_UnitTestContext& CFilterConfigurationIterator_NewL_Transition::Context() const
{
return REINTERPRET_CAST(CFilterConfigurationIterator_UnitTestContext&,iUTContext);
}
// ______________________________________________________________________________
//
_LIT(KFilterConfigurationIteratorDtorTransition,"CFilterConfigurationIterator_Dtor_Transition");
// WARNING : It is not recommended that CLeakTestTransitions
// are used on Dtor methods, so if CTransitionType is defined as CLeakTestTransition
// it is suggested that this Dtor transition's base is changed explicitly to CTransition
inline CFilterConfigurationIterator_Dtor_Transition::CFilterConfigurationIterator_Dtor_Transition(CUnitTestContext& aUTContext,
TTransitionValidator& aValidator)
: CTransitionType(KFilterConfigurationIteratorDtorTransition, aUTContext, aValidator)
{
// Do nothing here.
}
inline void CFilterConfigurationIterator_Dtor_Transition::TransitMethodL()
{
_LIT(KFilterConfigurationIteratorDtorTransitMethod, "CFilterConfigurationIterator::Dtor transition");
Context().DataLogger().LogInformation(KFilterConfigurationIteratorDtorTransitMethod);
Context().DeleteFilterIter();
}
inline CFilterConfigurationIterator_UnitTestContext& CFilterConfigurationIterator_Dtor_Transition::Context() const
{
return REINTERPRET_CAST(CFilterConfigurationIterator_UnitTestContext&,iUTContext);
}
// ______________________________________________________________________________
//
_LIT(KFilterConfigurationIteratorFirstTransition,"CFilterConfigurationIterator_First_Transition");
inline CFilterConfigurationIterator_First_Transition::CFilterConfigurationIterator_First_Transition(CUnitTestContext& aUTContext,
TTransitionValidator& aValidator)
: CTransitionType(KFilterConfigurationIteratorFirstTransition, aUTContext, aValidator)
{
// Do nothing here.
}
inline void CFilterConfigurationIterator_First_Transition::TransitMethodL()
{
_LIT(KFilterConfigurationIteratorFirstTransitMethod, "CFilterConfigurationIterator::First transition");
Context().DataLogger().LogInformation(KFilterConfigurationIteratorFirstTransitMethod);
Context().iFirstReturn = Context().iFilterConfigurationIterator->First();
}
inline CFilterConfigurationIterator_UnitTestContext& CFilterConfigurationIterator_First_Transition::Context() const
{
return REINTERPRET_CAST(CFilterConfigurationIterator_UnitTestContext&,iUTContext);
}
// ______________________________________________________________________________
//
_LIT(KFilterConfigurationIteratorAtStartTransition,"CFilterConfigurationIterator_AtStart_Transition");
inline CFilterConfigurationIterator_AtStart_Transition::CFilterConfigurationIterator_AtStart_Transition(CUnitTestContext& aUTContext,
TTransitionValidator& aValidator)
: CTransitionType(KFilterConfigurationIteratorAtStartTransition, aUTContext, aValidator)
{
// Do nothing here.
}
inline void CFilterConfigurationIterator_AtStart_Transition::TransitMethodL()
{
_LIT(KFilterConfigurationIteratorAtStartTransitMethod, "CFilterConfigurationIterator::AtStart transition");
Context().DataLogger().LogInformation(KFilterConfigurationIteratorAtStartTransitMethod);
Context().iAtStartReturn = Context().iFilterConfigurationIterator->AtStart();
}
inline CFilterConfigurationIterator_UnitTestContext& CFilterConfigurationIterator_AtStart_Transition::Context() const
{
return REINTERPRET_CAST(CFilterConfigurationIterator_UnitTestContext&,iUTContext);
}
// ______________________________________________________________________________
//
_LIT(KFilterConfigurationIteratorNextTransition,"CFilterConfigurationIterator_Next_Transition");
inline CFilterConfigurationIterator_Next_Transition::CFilterConfigurationIterator_Next_Transition(CUnitTestContext& aUTContext,
TTransitionValidator& aValidator)
: CTransitionType(KFilterConfigurationIteratorNextTransition, aUTContext, aValidator)
{
// Do nothing here.
}
inline void CFilterConfigurationIterator_Next_Transition::TransitMethodL()
{
_LIT(KFilterConfigurationIteratorNextTransitMethod, "CFilterConfigurationIterator::Next transition");
Context().DataLogger().LogInformation(KFilterConfigurationIteratorNextTransitMethod);
Context().iNextReturn = Context().iFilterConfigurationIterator->Next();
}
inline CFilterConfigurationIterator_UnitTestContext& CFilterConfigurationIterator_Next_Transition::Context() const
{
return REINTERPRET_CAST(CFilterConfigurationIterator_UnitTestContext&,iUTContext);
}
// ______________________________________________________________________________
//
_LIT(KFilterConfigurationIteratorCurrentFilterInformationTransition,"CFilterConfigurationIterator_CurrentFilterInformation_Transition");
inline CFilterConfigurationIterator_CurrentFilterInformation_Transition::CFilterConfigurationIterator_CurrentFilterInformation_Transition(CUnitTestContext& aUTContext,
TTransitionValidator& aValidator)
: CTransitionType(KFilterConfigurationIteratorCurrentFilterInformationTransition, aUTContext, aValidator)
{
// Do nothing here.
}
inline void CFilterConfigurationIterator_CurrentFilterInformation_Transition::TransitMethodL()
{
_LIT(KFilterConfigurationIteratorCurrentFilterInformationTransitMethod, "CFilterConfigurationIterator::CurrentFilterInformation transition");
Context().DataLogger().LogInformation(KFilterConfigurationIteratorCurrentFilterInformationTransitMethod);
TFilterInformation filterInfo = Context().iFilterConfigurationIterator->CurrentFilterInformation();
Context().iFilterInfo = new(ELeave) TFilterInformation(filterInfo);
}
inline CFilterConfigurationIterator_UnitTestContext& CFilterConfigurationIterator_CurrentFilterInformation_Transition::Context() const
{
return REINTERPRET_CAST(CFilterConfigurationIterator_UnitTestContext&,iUTContext);
}
// ______________________________________________________________________________
//
_LIT(KFilterConfigurationIteratorFindByDataTypeTransition,"CFilterConfigurationIterator_FindByDataType_Transition");
inline CFilterConfigurationIterator_FindByDataType_Transition::CFilterConfigurationIterator_FindByDataType_Transition(CUnitTestContext& aUTContext,
TTransitionValidator& aValidator)
: CTransitionType(KFilterConfigurationIteratorFindByDataTypeTransition, aUTContext, aValidator)
{
// Do nothing here.
}
inline void CFilterConfigurationIterator_FindByDataType_Transition::TransitMethodL()
{
_LIT(KFilterConfigurationIteratorFindByDataTypeTransitMethod, "CFilterConfigurationIterator::FindByDataType transition");
Context().DataLogger().LogInformation(KFilterConfigurationIteratorFindByDataTypeTransitMethod);
Context().iFindByDataTypeReturn = Context().iFilterConfigurationIterator->
FindByDataType(Context().GetTestFilterName(CFilterConfigurationIterator_UnitTestContext::ENotExist));
}
inline CFilterConfigurationIterator_UnitTestContext& CFilterConfigurationIterator_FindByDataType_Transition::Context() const
{
return REINTERPRET_CAST(CFilterConfigurationIterator_UnitTestContext&,iUTContext);
}
// ______________________________________________________________________________
//
_LIT(KFilterConfigurationIteratorListProtocolsTransition,"CFilterConfigurationIterator_ListProtocols_Transition");
inline CFilterConfigurationIterator_ListProtocols_Transition::CFilterConfigurationIterator_ListProtocols_Transition(CUnitTestContext& aUTContext,
TTransitionValidator& aValidator)
: CTransition(KFilterConfigurationIteratorListProtocolsTransition, aUTContext, aValidator)
{
// Do nothing here.
}
inline void CFilterConfigurationIterator_ListProtocols_Transition::TransitMethodL()
{
// This transition is a defect fix test for a memory leak in ListAvailableProtocolsL() on RHTTPSession
TInt ii = 0;
// OOM Loop
FOREVER
{
__UHEAP_MARK;
__UHEAP_FAILNEXT(ii);
// Logging
_LIT(KSessionListAvailableProtocolsTransitMethod, "RHTTPSession::ListAvailableProtocols transition");
Context().DataLogger().LogInformation(KSessionListAvailableProtocolsTransitMethod);
// Call method under test
TRAPD(err,Context().iTFSession.ListAvailableProtocolsL(Context().iProtocolArray));
Context().iProtocolCount = Context().iProtocolArray.Count();
// If the method runs successfully items will have been appended to array so cleanup
if(err==KErrNone)
Context().iProtocolArray.ResetAndDestroy();
__UHEAP_MARKEND;
User::Heap().Check();
__UHEAP_RESET;
// Break out if the test passes successfully; allow only memory failure or test failure codes to proceed.
if (err == KErrNone)
break;
else if (err != KErrNoMemory)
User::Leave(err);
// Next iteration
++ii;
}
_LIT(KTransitionRunSuccess, "CLeakTestTransition::TransitMethodL() successful completion on iteration %d.");
Context().DataLogger().LogInformationWithParameters(KTransitionRunSuccess, ii);
}
inline CFilterConfigurationIterator_UnitTestContext& CFilterConfigurationIterator_ListProtocols_Transition::Context() const
{
return REINTERPRET_CAST(CFilterConfigurationIterator_UnitTestContext&,iUTContext);
}
|
965e22b3e2017ae6048c74429fb9b0d935290a66 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/squid/gumtree/squid_new_log_1074.cpp | 55196fc47de26f454788311664a706ce222cc226 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 60 | cpp | squid_new_log_1074.cpp | storeAppendPrintf(&e, "Maximum entries: %9d\n", entryLimit); |
cabb05de0f11ece21e61c8a0b6a857c4e8dcae84 | b00756d0a1510be3ed42c1bc169175a877f17327 | /SpaceInvaders++/CFigure/CShip.h | 10508253e1a7dc6539c06a0a347fd73a329ad701 | [] | no_license | engooref/C- | 9c0098440aa68182e48e4ba7f416c3114ed9300b | 07237e64c65d1deb147f3f46f4691e921daa22c7 | refs/heads/master | 2022-11-12T15:26:43.943504 | 2020-07-06T13:38:58 | 2020-07-06T13:38:58 | 275,896,869 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,317 | h | CShip.h | /*
* CShip.h
*
* Created on: 29 juin 2020
* Author: armand
*/
#ifndef CSHIP_H_
#define CSHIP_H_
#include <CFigure.h>
#include <iostream>
using namespace std;
class CShip : public CFigure {
private:
static SDL_Texture * C_pTexture;
public:
CShip();
CShip(
int iLocX,
int iLocY,
int iWidth,
int iHeigth,
int iHotRatioX,
int iHotRatioY,
int iSpeedX,
int iSpeedY );
~CShip();
void Draw() const;
void Move(int iLocX, int iLocY);
SDL_Point* GetHotPoint();
public:
static void InitGraphic(SDL_Renderer*pRenderer, const char*pImageFileName){
SDL_Surface * image = IMG_Load(pImageFileName);
if (image == nullptr) return;
C_pTexture = SDL_CreateTextureFromSurface(pRenderer, image);
SDL_FreeSurface(image);
};
static void ReleaseGraphic(){
if (C_pTexture) {
SDL_DestroyTexture(C_pTexture);
C_pTexture = nullptr;
}
}
static CShip*DrawFunc(CShip*pShip, void*pParam){
pShip->Draw();
return pShip;
}
static void* DeleteFunc(CShip*pShip){
delete pShip;
return nullptr;
}
static void* MoveFunc(CShip*pShip, int iLocX, int iLocY){
pShip->Move(iLocX, iLocY);
return nullptr;
}
static SDL_Point*GetHotPointFunc(CShip*pShip){
return pShip->GetHotPoint();
}
static void*ShipRelife(void*pParam){
return nullptr;
}
};
#endif /* CSHIP_H_ */
|
351f563c08bd58b28a0f3576bffc1adbdb03fe96 | ba149a0a424cd19201a081c6a46110c685a00055 | /AVlib_c/source/lib_gen2/xSys.h | 3359f4505388fc6177fd4c64ba4f8f1201d89335 | [] | no_license | haku90/JPEG | 1b820db6eebdd31c10e7a8a459e70ae9b1f7f183 | 57822ed68bdd8a26234e4a8a6297ec18a8dd474d | refs/heads/master | 2021-01-19T13:55:33.098763 | 2014-05-28T16:58:09 | 2014-05-28T16:58:09 | 19,584,487 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,633 | h | xSys.h | #pragma once
#ifndef _xSysH_
#define _xSysH_
#include "xLicense.h"
#include "xType.h"
#include "xLanguage.h"
#include "xDefines.h"
#include <windows.h>
#include <stdio.h>
//================================================================================================
//Clasic main():
//main( int argc, char *argv[ ], char *envp[ ] )
//
//UNICODE main():
//wmain( int argc, wchar_t *argv[ ], wchar_t *envp[ ] )
//================================================================================================
//================================================================================================
// SYS
//================================================================================================
#define X_SEEK_CUR 1
#define X_SEEK_END 2
#define X_SEEK_BEGIN 0
#define X_SEEK_SET X_SEEK_BEGIN
FILE_HANDLE x_fopen (xchar* name, xchar* attr);
uint32 x_fwrite (FILE_HANDLE hfile, void* buff, uint32 len);
uint32 x_fread (FILE_HANDLE hfile, void* buff, uint32 len);
uint32 x_fwrite (FILE_HANDLE file_handle, void* buf, uint32 len);
uint32 x_fseek (FILE_HANDLE file_handle, int64 pos, uint32 origin);
uint64 x_fsize (FILE_HANDLE file_handle);
uint32 x_eof (FILE_HANDLE file_handle);
uint64 x_ftell (FILE_HANDLE hfile);
uint32 x_fskip (FILE_HANDLE hfile, int64 pos);
FILE_HANDLE x_fclose (FILE_HANDLE hfile);
int32 argi (int argc, xchar *argv[], xchar* header, int deft);
float argf (int argc, xchar *argv[], xchar* header, float deft);
xchar* args (int argc, xchar *argv[], xchar* header, xchar* deft);
int32 argt (int argc, xchar *argv[], xchar* header);
int argl (int argc, xchar *argv[], xchar* header, xchar* label);
#define _ARGI(h,d) argi(argc,argv,(h),(d))
#define _ARGF(h,d) argf(argc,argv,(h),(d))
#define _ARGS(h,d) args(argc,argv,(h),(d))
#define _ARGT(h) argt(argc,argv,(h))
#define _ARGL(h,d) argl(argc,argv,(h),(d))
void x_fprinterror();
void x_sys_print_compiler();
//================================================================================================
// CPU
//================================================================================================
class xCpuInfo
{
protected:
char m_VendorID[13];
uint8 m_FPU; //Floating Point Unit (integrated since 80486)
uint8 m_MMX;
uint8 m_SSE1;
uint8 m_SSE2;
uint8 m_SSE3;
uint8 m_SSSE3; //SupplementalSSE3
uint8 m_SSE4_1;
uint8 m_SSE4_2;
uint8 m_AVX1;
uint8 m_AVX2;
uint8 m_AVX512CD;
uint8 m_AVX512ER;
uint8 m_AVX512PF;
uint8 m_FMA; //Fused multiple-add
uint8 m_BMI1; //Bit Manipulation Instructions 1
uint8 m_BMI2; //Bit Manipulation Instructions 2
uint8 m_CMOV; //Conditional move
uint8 m_POPCNT; //Population count instruction
uint8 m_LZCNT; //Leading zero count instruction
uint8 m_AES; //EAS encryption accelerator
uint8 m_SHA;
uint8 m_FP16C; //Half float convertion
uint8 m_RDRAND; //SP 800-90A - Cryptographically secure pseudorandom number generator
uint8 m_RDSEED; //SP 800-90B & C - Non-deterministic random bit generator
uint8 m_TSX; //TSX=RTM+HLE
uint8 m_MOVBE; //Load and Store of Big Endian forms
uint8 m_INVPCID; //Invalidate processor context ID
uint8 m_ADX; //ADOX, ADCX, MULX arbitrary-precision integer operations
uint8 m_HT; //Hyperthreading;
public:
void checkCPIUD();
void printCpuInfo();
int32 checkCompatibility();
};
#endif //_xSysH_ |
764f565da3c589a8afcb90bf586f6bd45f277b5b | 2223fdf5ab025c1465e139f39490129591a58808 | /day04/ex01/PlasmaRifle.cpp | e4f84369c6ce7d8c297406c4c267247d9525d60d | [] | no_license | base1905/CPP_piscine | 5907bcb91ab24c6f8496431811477992279bfd65 | 3c6b2a7a08cc773dd141ce5920cd7cd119e110e3 | refs/heads/main | 2023-04-18T19:56:27.226952 | 2021-05-04T18:52:08 | 2021-05-04T18:52:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 495 | cpp | PlasmaRifle.cpp | #include "PlasmaRifle.hpp"
PlasmaRifle::PlasmaRifle()
{
this->_name = "Plasma Rifle";
this->_apcost = 5;
this->_damage = 21;
}
PlasmaRifle::PlasmaRifle(PlasmaRifle const & src)
{ *this = src; }
PlasmaRifle & PlasmaRifle::operator=(PlasmaRifle const & src)
{
this->_name = src._name;
this->_apcost = src._apcost;
this->_damage = src._damage;
return *this;
}
PlasmaRifle::~PlasmaRifle() { }
void PlasmaRifle::attack() const
{ std::cout << "* piouuu piouuu piouuu *" << std::endl; }
|
3e733a865d1f9723057c0f1b433ab65d1135f60f | edb1b07246393d72ec43be283abe71f37d16b72e | /Parser0205/Parser0205/Rule.cpp | 58a1afce7b2c569c3cacbcee0225ae7cc6a4a071 | [] | no_license | JaredEzz/Parser | 1be8c11d79684800d0c59bf102fa85a0a4744f0a | 0c749eb95c6a6f426469384d45dd93312a475442 | refs/heads/master | 2020-04-21T04:21:35.269578 | 2019-02-05T20:56:44 | 2019-02-05T20:56:44 | 169,311,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 147 | cpp | Rule.cpp | #include "Rule.h"
using namespace std;
Rule::Rule(Predicate p)
{
myPred = p;
}
void Rule::addPredicate(Predicate p)
{
predList.push_back(p);
} |
afa9046b096fc923d7c3cc61512c8045f7c32d78 | 50ddd40e2bd71a605cd9354814dc7dfa464bf7fa | /task2/problemA/main.cpp | 7694b1af00db27e77e669a068b36079d41769d3f | [] | no_license | ilyaderkatch/3sem-Algorithms | 5635a18d5c6f3085f54f5372146ce18de06fb60d | 956fa87d7ef86f476ae3d85282cdf124564d085a | refs/heads/master | 2022-04-16T03:57:19.433291 | 2020-04-11T22:38:56 | 2020-04-11T22:38:56 | 254,963,642 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,690 | cpp | main.cpp | #include <algorithm>
#include <iostream>
#include <vector>
const size_t alphabet_length = 256;
using std::cin;
using std::cout;
using std::endl;
using std::max;
using std::min;
using std::string;
using std::vector;
class SufArray {
private:
vector<size_t> suff_arr_;
void FirstStepOfBuilding(const string &input_string, vector<size_t> &classes);
void OthersStepsOfBuilding(const string &input_string,
vector<size_t> &classes);
public:
size_t operator[](const size_t index) const { return suff_arr_[index]; }
size_t Size() const { return suff_arr_.size(); }
SufArray(const string &input_string);
};
void CalculatePosFromCount(vector<size_t> &count_in_classes) {
for (size_t i = count_in_classes.size() - 1; i > 0; --i) {
count_in_classes[i] = count_in_classes[i - 1];
}
count_in_classes[0] = 0;
for (size_t i = 1; i < count_in_classes.size(); ++i) {
count_in_classes[i] += count_in_classes[i - 1];
}
}
void SufArray::FirstStepOfBuilding(const string &input_string,
vector<size_t> &classes) {
vector<size_t> count_in_classes(max(input_string.size(), alphabet_length), 0);
for (char i : input_string) {
count_in_classes[static_cast<size_t>(i)] += 1;
}
CalculatePosFromCount(count_in_classes);
for (size_t i = 0; i < input_string.size(); ++i) {
suff_arr_[count_in_classes[static_cast<size_t>(input_string[i])]++] = i;
}
classes[suff_arr_[0]] = 0;
size_t num_of_class = 0;
for (size_t i = 1; i < suff_arr_.size(); ++i) {
if (input_string[suff_arr_[i]] != input_string[suff_arr_[i - 1]]) {
++num_of_class;
}
classes[suff_arr_[i]] = num_of_class;
}
}
void SufArray::OthersStepsOfBuilding(const string &input_string,
vector<size_t> &classes) {
vector<size_t> count_in_classes(max(input_string.size(), alphabet_length), 0);
size_t num_of_class = 0;
size_t curr_len = 1;
while (curr_len < input_string.size()) {
count_in_classes.clear();
count_in_classes.assign(max(input_string.size(), alphabet_length), 0);
vector<size_t> sorted_by_old_classes(input_string.size(), 0);
for (size_t i = 0; i < sorted_by_old_classes.size(); ++i) {
sorted_by_old_classes[i] =
(suff_arr_[i] - curr_len + input_string.size()) % input_string.size();
}
for (size_t sorted_by_old_classe : sorted_by_old_classes) {
++count_in_classes[classes[sorted_by_old_classe]];
}
CalculatePosFromCount(count_in_classes);
for (size_t i = 0; i < suff_arr_.size(); ++i) {
suff_arr_[count_in_classes[classes[sorted_by_old_classes[i]]]] =
sorted_by_old_classes[i];
++count_in_classes[classes[sorted_by_old_classes[i]]];
}
vector<size_t> new_classes(input_string.size());
new_classes[suff_arr_[0]] = 0;
num_of_class = 0;
for (size_t i = 1; i < new_classes.size(); ++i) {
if (classes[suff_arr_[i]] != classes[suff_arr_[i - 1]] ||
classes[(suff_arr_[i] + curr_len) % input_string.size()] !=
classes[(suff_arr_[i - 1] + curr_len) % input_string.size()]) {
++num_of_class;
}
new_classes[suff_arr_[i]] = num_of_class;
}
classes = new_classes;
curr_len <<= 1;
}
}
SufArray::SufArray(const string &input_string) {
vector<size_t> classes(input_string.size());
suff_arr_.resize(input_string.size());
FirstStepOfBuilding(input_string, classes);
OthersStepsOfBuilding(input_string, classes);
}
vector<size_t> CountMaxLengthOfCommonPrefixes(const SufArray &suff_arr,
const string &str) {
vector<size_t> ans(str.size());
size_t pos = 0;
vector<size_t> anti_suff_arr(suff_arr.Size());
for (size_t i = 0; i < suff_arr.Size(); ++i) {
anti_suff_arr[suff_arr[i]] = i;
}
for (size_t i = 0; i < str.size(); ++i) {
if (pos > 0) {
--pos;
}
if (anti_suff_arr[i] != str.size() - 1) {
while ((pos + i < str.size()) &&
(pos + suff_arr[anti_suff_arr[i] + 1] < str.size()) &&
(str[i + pos] == str[suff_arr[anti_suff_arr[i] + 1] + pos])) {
++pos;
}
ans[anti_suff_arr[i]] = pos;
}
}
return ans;
}
int FindCountOfDifferentSubstrings(const string &input_str) {
string s = input_str + '$';
SufArray suff_arr(s);
vector<size_t> lcp = CountMaxLengthOfCommonPrefixes(suff_arr, s);
int ans = 0;
for (size_t i = 1; i < lcp.size(); ++i) {
ans +=
static_cast<int>(s.size()) - static_cast<int>(suff_arr[i] + lcp[i]) - 1;
}
return ans;
}
int main() {
string s;
cin >> s;
cout << FindCountOfDifferentSubstrings(s) << endl;
return 0;
}
|
8c01a01bf29ad550f21b82faa09654d8e2abc8ad | 3f8f2e97e4ffd5f98bd428875f8b5deec37cf208 | /src/CBateau.h | 50ea7ed3d523da1b3e88592eb32b314124b9f09e | [] | no_license | sullivanlb/NavalBattle | a4988fd9018f670671c7ab8a2af338b87b3a9bdd | 733317ac4118303cd0e550704508ee7b93232bec | refs/heads/main | 2023-03-16T07:10:31.539903 | 2021-03-09T08:37:56 | 2021-03-09T08:37:56 | 338,581,918 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 716 | h | CBateau.h | #ifndef CBATEAU_H
#define CBATEAU_H
#include "BiblioStd.h"
class CBateau {
private:
int m_taille;
string m_nom;
pair<int, int> m_position;
bool* m_pDegats;
public:
CBateau();
CBateau(string n, pair<int, int> p, int t);
CBateau(const CBateau& theBToCopy);
~CBateau();
bool getDegats(int i);
string getNom();
int getTaille();
pair<int, int> getPosition();
void setPosition(int i, int j);
bool estCoule();
bool tirAdverse(pair<int, int> p);
void operator=(const CBateau& theBtoCopy);
friend ostream& operator<<(ostream& os, CBateau& theB);
};
#endif |
00f56b497d956ec1353471a796affdb724420e01 | 8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a | /3rdParty/boost/1.78.0/boost/hana/zip_shortest_with.hpp | 4371e4dc3152e77098ed18b30f95a3ec8deddd56 | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode-public-domain",
"JSON",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"BSD-4-Clause",
"Python-2.0",
"LGPL-2.1-or-later"
] | permissive | arangodb/arangodb | 0980625e76c56a2449d90dcb8d8f2c485e28a83b | 43c40535cee37fc7349a21793dc33b1833735af5 | refs/heads/devel | 2023-08-31T09:34:47.451950 | 2023-08-31T07:25:02 | 2023-08-31T07:25:02 | 2,649,214 | 13,385 | 982 | Apache-2.0 | 2023-09-14T17:02:16 | 2011-10-26T06:42:00 | C++ | UTF-8 | C++ | false | false | 2,131 | hpp | zip_shortest_with.hpp | /*!
@file
Defines `boost::hana::zip_shortest_with`.
@copyright Louis Dionne 2013-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_ZIP_SHORTEST_WITH_HPP
#define BOOST_HANA_ZIP_SHORTEST_WITH_HPP
#include <boost/hana/fwd/zip_shortest_with.hpp>
#include <boost/hana/concept/sequence.hpp>
#include <boost/hana/core/dispatch.hpp>
#include <boost/hana/config.hpp>
#include <boost/hana/detail/algorithm.hpp>
#include <boost/hana/detail/fast_and.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/length.hpp>
#include <boost/hana/take_front.hpp>
#include <boost/hana/zip_with.hpp>
#include <cstddef>
namespace boost { namespace hana {
//! @cond
template <typename F, typename Xs, typename ...Ys>
constexpr auto
zip_shortest_with_t::operator()(F&& f, Xs&& xs, Ys&& ...ys) const {
#ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
static_assert(detail::fast_and<
hana::Sequence<Xs>::value, hana::Sequence<Ys>::value...
>::value,
"hana::zip_shortest_with(f, xs, ys...) requires 'xs' and 'ys...' to be Sequences");
#endif
return zip_shortest_with_impl<typename hana::tag_of<Xs>::type>::apply(
static_cast<F&&>(f),
static_cast<Xs&&>(xs),
static_cast<Ys&&>(ys)...
);
}
//! @endcond
template <typename S, bool condition>
struct zip_shortest_with_impl<S, when<condition>> : default_ {
template <typename F, typename ...Xs>
static constexpr decltype(auto) apply(F&& f, Xs&& ...xs) {
constexpr std::size_t lengths[] = {
decltype(hana::length(xs))::value...
};
constexpr std::size_t min_len =
*detail::min_element(lengths, lengths + sizeof...(xs));
return hana::zip_with(static_cast<F&&>(f),
hana::take_front(static_cast<Xs&&>(xs), hana::size_c<min_len>)...
);
}
};
}} // end namespace boost::hana
#endif // !BOOST_HANA_ZIP_SHORTEST_WITH_HPP
|
ca1935c2703f72774c65ea31c93d262c6404e0d5 | 278c977951eba2a49abeed3365a919db21f2b87d | /src/rectify/src/libRectification/rectify.h | c4e9904ffa9be7816efd945647248eaafe4e531b | [] | no_license | BB88/tesi_watermarking | cb5a2fc6f0642f7c5886648b33205b71214aaccd | 9a8cbbd338536a48d60788a3bbef2982727941f6 | refs/heads/master | 2021-01-21T21:54:56.400325 | 2016-03-21T20:49:08 | 2016-03-21T20:49:08 | 33,986,082 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 344 | h | rectify.h | #ifndef RECTIFY_H
#define RECTIFY_H
#include "../libNumerics/homography.h"
#include "../libMatch/imgmatch.h"
#include <vector>
std::pair<float,float> compRectif(int w, int h, const std::vector<imgMatch>& m,
libNumerics::Homography& Hl,
libNumerics::Homography& Hr);
#endif
|
105c8adb7b3f66861e2d45603339d15a930dfda9 | 2b2e4666da79d4b7727ec20adf846530beed9f9c | /libeventtest/WorkServer.cpp | cf14e68efd13ecf1b93eeb63cc90e94ec0ba3d87 | [] | no_license | chengf2018/SimpleServer | fd942d26d8b6d3a46721ddb1494952da22a34ad5 | d5c25fab6e22102f73b016ef010c944404d9025d | refs/heads/master | 2020-03-28T00:47:34.852566 | 2018-09-05T03:06:35 | 2018-09-05T03:06:35 | 147,449,946 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,133 | cpp | WorkServer.cpp | #include "stdafx.h"
#include "WorkServer.h"
void CWorkServer::OnProcessMessage(bufferevent *bev, char *message, unsigned short len)
{
//printf("收到数据:%s\n", message);
bufferevent_lock(bev);//加锁,以方便处理逻辑业务
CMemoryStream packet(message, len);
unsigned char nCmdId = 0;
packet >> nCmdId;
printf("CmdId:%d\n", nCmdId);
if (nCmdId == cmd_LoginSystem)//登录系统单独处理
{
m_userMgr.LoginSystemHandle(bev, packet);
bufferevent_unlock(bev);//return前必须解锁
return;
}
evutil_socket_t sockid = bufferevent_getfd(bev);
if (sockid == -1)
{
bufferevent_unlock(bev);
return;
}
CUser *user = m_userMgr.GetUser(sockid);
if (user == nullptr)
{
bufferevent_unlock(bev);
return;
}
user->ProcessNetMessage(nCmdId, packet);
bufferevent_unlock(bev);
}
void CWorkServer::OnConnect(bufferevent *bev, char *ip)
{
}
void CWorkServer::OnClose(bufferevent *bev)
{
evutil_socket_t sockid = bufferevent_getfd(bev);
if (sockid == -1) return;
CUser *user = m_userMgr.GetUser(sockid);
if (user == nullptr) return;
user->OnLoginOut();
m_userMgr.DeleteUser(sockid);
}
|
d5c54f1c6637d71914a84c429110405ebff9e3bd | c45702cf0889ef2bb40e053967d654b307fcb988 | /src/Http.cpp | c76650f5fa15b4289efe71f5a53bfcfb8688f4ac | [
"Apache-2.0"
] | permissive | sihai90/liblifthttp | 04515ef6e3819129e9edd6b3e14070f47763a4dd | 38819330a751514595a737348dc465b9cf29f813 | refs/heads/master | 2022-04-18T04:06:33.123130 | 2020-04-15T22:54:05 | 2020-04-15T22:54:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,727 | cpp | Http.cpp | #include "lift/Http.hpp"
namespace lift::http {
using namespace std::string_literals;
static const std::string METHOD_GET = "GET"s;
static const std::string METHOD_HEAD = "HEAD"s;
static const std::string METHOD_POST = "POST"s;
static const std::string METHOD_PUT = "PUT"s;
static const std::string METHOD_DELETE = "DELETE"s;
static const std::string METHOD_CONNECT = "CONNECT"s;
static const std::string METHOD_OPTIONS = "OPTIONS"s;
static const std::string METHOD_PATCH = "PATCH"s;
auto to_string(
Method method) -> const std::string&
{
switch (method) {
case Method::GET:
return METHOD_GET;
case Method::HEAD:
return METHOD_HEAD;
case Method::POST:
return METHOD_POST;
case Method::PUT:
return METHOD_PUT;
case Method::DELETE:
return METHOD_DELETE;
case Method::CONNECT:
return METHOD_CONNECT;
case Method::OPTIONS:
return METHOD_OPTIONS;
case Method::PATCH:
return METHOD_PATCH;
default:
return METHOD_GET;
}
}
static const std::string STATUS_CODE_HTTP_UNKNOWN = "UNKNOWN"s;
static const std::string STATUS_CODE_HTTP_100_CONTINUE = "100 Continue"s;
static const std::string STATUS_CODE_HTTP_101_SWITCHING_PROTOCOLS = "101 Switching Protocols"s;
static const std::string STATUS_CODE_HTTP_102_PROCESSING = "102 Processing"s;
static const std::string STATUS_CODE_HTTP_103_EARLY_HINTS = "103 Early Hints"s;
static const std::string STATUS_CODE_HTTP_200_OK = "200 OK"s;
static const std::string STATUS_CODE_HTTP_201_CREATED = "201 Created"s;
static const std::string STATUS_CODE_HTTP_202_ACCEPTED = "202 Accepted"s;
static const std::string STATUS_CODE_HTTP_203_NON_AUTHORITATIVE_INFORMATION = "203 Non-Authoritative Information"s;
static const std::string STATUS_CODE_HTTP_204_NO_CONTENT = "204 No Content"s;
static const std::string STATUS_CODE_HTTP_205_RESET_CONTENT = "205 Reset Content"s;
static const std::string STATUS_CODE_HTTP_206_PARTIAL_CONTENT = "206 Partial Content"s;
static const std::string STATUS_CODE_HTTP_207_MULTI_STATUS = "207 Multi-Status"s;
static const std::string STATUS_CODE_HTTP_208_ALREADY_REPORTED = "208 Already Reported"s;
static const std::string STATUS_CODE_HTTP_226_IM_USED = "226 IM Used"s;
static const std::string STATUS_CODE_HTTP_300_MULTIPLE_CHOICES = "300 Multiple Choices"s;
static const std::string STATUS_CODE_HTTP_301_MOVED_PERMANENTLY = "301 Moved Permanently"s;
static const std::string STATUS_CODE_HTTP_302_FOUND = "302 Found"s;
static const std::string STATUS_CODE_HTTP_303_SEE_OTHER = "303 See Other"s;
static const std::string STATUS_CODE_HTTP_304_NOT_MODIFIED = "304 Not Modified"s;
static const std::string STATUS_CODE_HTTP_305_USE_PROXY = "305 Use Proxy"s;
static const std::string STATUS_CODE_HTTP_306_SWITCH_PROXY = "306 Switch Proxy"s;
static const std::string STATUS_CODE_HTTP_307_TEMPORARY_REDIRECT = "307 Temporary Redirect"s;
static const std::string STATUS_CODE_HTTP_308_PERMANENT_REDIRECT = "308 Permanent Redirect"s;
static const std::string STATUS_CODE_HTTP_400_BAD_REQUEST = "400 Bad Request"s;
static const std::string STATUS_CODE_HTTP_401_UNAUTHORIZED = "401 Unauthorized"s;
static const std::string STATUS_CODE_HTTP_402_PAYMENT_REQUIRED = "402 Payment Required"s;
static const std::string STATUS_CODE_HTTP_403_FORBIDDEN = "403 Forbidden"s;
static const std::string STATUS_CODE_HTTP_404_NOT_FOUND = "404 Not Found"s;
static const std::string STATUS_CODE_HTTP_405_METHOD_NOT_ALLOWED = "405 Method Not Allowed"s;
static const std::string STATUS_CODE_HTTP_406_NOT_ACCEPTABLE = "406 Not Acceptable"s;
static const std::string STATUS_CODE_HTTP_407_PROXY_AUTHENTICATION_REQUIRED = "407 Proxy Authentication Required"s;
static const std::string STATUS_CODE_HTTP_408_REQUEST_TIMEOUT = "408 Request Timeout"s;
static const std::string STATUS_CODE_HTTP_409_CONFLICT = "409 Conflict"s;
static const std::string STATUS_CODE_HTTP_410_GONE = "410 Gone"s;
static const std::string STATUS_CODE_HTTP_411_LENGTH_REQUIRED = "411 Length Required"s;
static const std::string STATUS_CODE_HTTP_412_PRECONDITION_FAILED = "412 Precondition Failed"s;
static const std::string STATUS_CODE_HTTP_413_PAYLOAD_TOO_LARGE = "413 Payload Too Large"s;
static const std::string STATUS_CODE_HTTP_414_URI_TOO_LONG = "414 URI Too Long"s;
static const std::string STATUS_CODE_HTTP_415_UNSUPPORTED_MEDIA_TYPE = "415 Unsupported Media Type"s;
static const std::string STATUS_CODE_HTTP_416_RANGE_NOT_SATISFIABLE = "416 Range Not Satisfiable"s;
static const std::string STATUS_CODE_HTTP_417_EXPECTATION_FAILED = "417 Expectation Failed"s;
static const std::string STATUS_CODE_HTTP_418_IM_A_TEAPOT_ = "418 I'm a teapot"s;
static const std::string STATUS_CODE_HTTP_421_MISDIRECTED_REQUEST = "421 Misdirected Request"s;
static const std::string STATUS_CODE_HTTP_422_UNPROCESSABLE_ENTITY = "422 Unprocessable Entity"s;
static const std::string STATUS_CODE_HTTP_423_LOCKED = "423 Locked"s;
static const std::string STATUS_CODE_HTTP_424_FAILED_DEPENDENCY = "424 Failed Dependency"s;
static const std::string STATUS_CODE_HTTP_425_TOO_EARLY = "425 Too Early"s;
static const std::string STATUS_CODE_HTTP_426_UPGRADE_REQUIRED = "426 Upgrade Required"s;
static const std::string STATUS_CODE_HTTP_428_PRECONDITION_REQUIRED = "428 Precondition Required"s;
static const std::string STATUS_CODE_HTTP_429_TOO_MANY_REQUESTS = "429 Too Many Requests"s;
static const std::string STATUS_CODE_HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE = "431 Request Header Fields Too Large"s;
static const std::string STATUS_CODE_HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS = "451 Unavailable For Legal Reasons"s;
static const std::string STATUS_CODE_HTTP_500_INTERNAL_SERVER_ERROR = "500 Internal Server Error"s;
static const std::string STATUS_CODE_HTTP_501_NOT_IMPLEMENTED = "501 Not Implemented"s;
static const std::string STATUS_CODE_HTTP_502_BAD_GATEWAY = "502 Bad Gateway"s;
static const std::string STATUS_CODE_HTTP_503_SERVICE_UNAVAILABLE = "503 Service Unavailable"s;
static const std::string STATUS_CODE_HTTP_504_GATEWAY_TIMEOUT = "504 Gateway Timeout"s;
static const std::string STATUS_CODE_HTTP_505_HTTP_VERSION_NOT_SUPPORTED = "505 HTTP Version Not Supported"s;
static const std::string STATUS_CODE_HTTP_506_VARIANT_ALSO_NEGOTIATES = "506 Variant Also Negotiates"s;
static const std::string STATUS_CODE_HTTP_507_INSUFFICIENT_STORAGE = "507 Insufficient Storage"s;
static const std::string STATUS_CODE_HTTP_508_LOOP_DETECTED = "508 Loop Detected"s;
static const std::string STATUS_CODE_HTTP_510_NOT_EXTENDED = "510 Not Extended"s;
static const std::string STATUS_CODE_HTTP_511_NETWORK_AUTHENTICATION_REQUIRED = "511 Network Authentication Required"s;
auto to_string(
StatusCode code) -> const std::string&
{
switch (code) {
case StatusCode::HTTP_UNKNOWN:
return STATUS_CODE_HTTP_UNKNOWN;
case StatusCode::HTTP_100_CONTINUE:
return STATUS_CODE_HTTP_100_CONTINUE;
case StatusCode::HTTP_101_SWITCHING_PROTOCOLS:
return STATUS_CODE_HTTP_101_SWITCHING_PROTOCOLS;
case StatusCode::HTTP_102_PROCESSING:
return STATUS_CODE_HTTP_102_PROCESSING;
case StatusCode::HTTP_103_EARLY_HINTS:
return STATUS_CODE_HTTP_103_EARLY_HINTS;
case StatusCode::HTTP_200_OK:
return STATUS_CODE_HTTP_200_OK;
case StatusCode::HTTP_201_CREATED:
return STATUS_CODE_HTTP_201_CREATED;
case StatusCode::HTTP_202_ACCEPTED:
return STATUS_CODE_HTTP_202_ACCEPTED;
case StatusCode::HTTP_203_NON_AUTHORITATIVE_INFORMATION:
return STATUS_CODE_HTTP_203_NON_AUTHORITATIVE_INFORMATION;
case StatusCode::HTTP_204_NO_CONTENT:
return STATUS_CODE_HTTP_204_NO_CONTENT;
case StatusCode::HTTP_205_RESET_CONTENT:
return STATUS_CODE_HTTP_205_RESET_CONTENT;
case StatusCode::HTTP_206_PARTIAL_CONTENT:
return STATUS_CODE_HTTP_206_PARTIAL_CONTENT;
case StatusCode::HTTP_207_MULTI_STATUS:
return STATUS_CODE_HTTP_207_MULTI_STATUS;
case StatusCode::HTTP_208_ALREADY_REPORTED:
return STATUS_CODE_HTTP_208_ALREADY_REPORTED;
case StatusCode::HTTP_226_IM_USED:
return STATUS_CODE_HTTP_226_IM_USED;
case StatusCode::HTTP_300_MULTIPLE_CHOICES:
return STATUS_CODE_HTTP_300_MULTIPLE_CHOICES;
case StatusCode::HTTP_301_MOVED_PERMANENTLY:
return STATUS_CODE_HTTP_301_MOVED_PERMANENTLY;
case StatusCode::HTTP_302_FOUND:
return STATUS_CODE_HTTP_302_FOUND;
case StatusCode::HTTP_303_SEE_OTHER:
return STATUS_CODE_HTTP_303_SEE_OTHER;
case StatusCode::HTTP_304_NOT_MODIFIED:
return STATUS_CODE_HTTP_304_NOT_MODIFIED;
case StatusCode::HTTP_305_USE_PROXY:
return STATUS_CODE_HTTP_305_USE_PROXY;
case StatusCode::HTTP_306_SWITCH_PROXY:
return STATUS_CODE_HTTP_306_SWITCH_PROXY;
case StatusCode::HTTP_307_TEMPORARY_REDIRECT:
return STATUS_CODE_HTTP_307_TEMPORARY_REDIRECT;
case StatusCode::HTTP_308_PERMANENT_REDIRECT:
return STATUS_CODE_HTTP_308_PERMANENT_REDIRECT;
case StatusCode::HTTP_400_BAD_REQUEST:
return STATUS_CODE_HTTP_400_BAD_REQUEST;
case StatusCode::HTTP_401_UNAUTHORIZED:
return STATUS_CODE_HTTP_401_UNAUTHORIZED;
case StatusCode::HTTP_402_PAYMENT_REQUIRED:
return STATUS_CODE_HTTP_402_PAYMENT_REQUIRED;
case StatusCode::HTTP_403_FORBIDDEN:
return STATUS_CODE_HTTP_403_FORBIDDEN;
case StatusCode::HTTP_404_NOT_FOUND:
return STATUS_CODE_HTTP_404_NOT_FOUND;
case StatusCode::HTTP_405_METHOD_NOT_ALLOWED:
return STATUS_CODE_HTTP_405_METHOD_NOT_ALLOWED;
case StatusCode::HTTP_406_NOT_ACCEPTABLE:
return STATUS_CODE_HTTP_406_NOT_ACCEPTABLE;
case StatusCode::HTTP_407_PROXY_AUTHENTICATION_REQUIRED:
return STATUS_CODE_HTTP_407_PROXY_AUTHENTICATION_REQUIRED;
case StatusCode::HTTP_408_REQUEST_TIMEOUT:
return STATUS_CODE_HTTP_408_REQUEST_TIMEOUT;
case StatusCode::HTTP_409_CONFLICT:
return STATUS_CODE_HTTP_409_CONFLICT;
case StatusCode::HTTP_410_GONE:
return STATUS_CODE_HTTP_410_GONE;
case StatusCode::HTTP_411_LENGTH_REQUIRED:
return STATUS_CODE_HTTP_411_LENGTH_REQUIRED;
case StatusCode::HTTP_412_PRECONDITION_FAILED:
return STATUS_CODE_HTTP_412_PRECONDITION_FAILED;
case StatusCode::HTTP_413_PAYLOAD_TOO_LARGE:
return STATUS_CODE_HTTP_413_PAYLOAD_TOO_LARGE;
case StatusCode::HTTP_414_URI_TOO_LONG:
return STATUS_CODE_HTTP_414_URI_TOO_LONG;
case StatusCode::HTTP_415_UNSUPPORTED_MEDIA_TYPE:
return STATUS_CODE_HTTP_415_UNSUPPORTED_MEDIA_TYPE;
case StatusCode::HTTP_416_RANGE_NOT_SATISFIABLE:
return STATUS_CODE_HTTP_416_RANGE_NOT_SATISFIABLE;
case StatusCode::HTTP_417_EXPECTATION_FAILED:
return STATUS_CODE_HTTP_417_EXPECTATION_FAILED;
case StatusCode::HTTP_418_IM_A_TEAPOT_:
return STATUS_CODE_HTTP_418_IM_A_TEAPOT_;
case StatusCode::HTTP_421_MISDIRECTED_REQUEST:
return STATUS_CODE_HTTP_421_MISDIRECTED_REQUEST;
case StatusCode::HTTP_422_UNPROCESSABLE_ENTITY:
return STATUS_CODE_HTTP_422_UNPROCESSABLE_ENTITY;
case StatusCode::HTTP_423_LOCKED:
return STATUS_CODE_HTTP_423_LOCKED;
case StatusCode::HTTP_424_FAILED_DEPENDENCY:
return STATUS_CODE_HTTP_424_FAILED_DEPENDENCY;
case StatusCode::HTTP_425_TOO_EARLY:
return STATUS_CODE_HTTP_425_TOO_EARLY;
case StatusCode::HTTP_426_UPGRADE_REQUIRED:
return STATUS_CODE_HTTP_426_UPGRADE_REQUIRED;
case StatusCode::HTTP_428_PRECONDITION_REQUIRED:
return STATUS_CODE_HTTP_428_PRECONDITION_REQUIRED;
case StatusCode::HTTP_429_TOO_MANY_REQUESTS:
return STATUS_CODE_HTTP_429_TOO_MANY_REQUESTS;
case StatusCode::HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE:
return STATUS_CODE_HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE;
case StatusCode::HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS:
return STATUS_CODE_HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS;
case StatusCode::HTTP_500_INTERNAL_SERVER_ERROR:
return STATUS_CODE_HTTP_500_INTERNAL_SERVER_ERROR;
case StatusCode::HTTP_501_NOT_IMPLEMENTED:
return STATUS_CODE_HTTP_501_NOT_IMPLEMENTED;
case StatusCode::HTTP_502_BAD_GATEWAY:
return STATUS_CODE_HTTP_502_BAD_GATEWAY;
case StatusCode::HTTP_503_SERVICE_UNAVAILABLE:
return STATUS_CODE_HTTP_503_SERVICE_UNAVAILABLE;
case StatusCode::HTTP_504_GATEWAY_TIMEOUT:
return STATUS_CODE_HTTP_504_GATEWAY_TIMEOUT;
case StatusCode::HTTP_505_HTTP_VERSION_NOT_SUPPORTED:
return STATUS_CODE_HTTP_505_HTTP_VERSION_NOT_SUPPORTED;
case StatusCode::HTTP_506_VARIANT_ALSO_NEGOTIATES:
return STATUS_CODE_HTTP_506_VARIANT_ALSO_NEGOTIATES;
case StatusCode::HTTP_507_INSUFFICIENT_STORAGE:
return STATUS_CODE_HTTP_507_INSUFFICIENT_STORAGE;
case StatusCode::HTTP_508_LOOP_DETECTED:
return STATUS_CODE_HTTP_508_LOOP_DETECTED;
case StatusCode::HTTP_510_NOT_EXTENDED:
return STATUS_CODE_HTTP_510_NOT_EXTENDED;
case StatusCode::HTTP_511_NETWORK_AUTHENTICATION_REQUIRED:
return STATUS_CODE_HTTP_511_NETWORK_AUTHENTICATION_REQUIRED;
default:
return STATUS_CODE_HTTP_UNKNOWN;
}
}
auto to_enum(
int32_t code) -> StatusCode
{
switch (code) {
case 100:
return StatusCode::HTTP_100_CONTINUE;
case 101:
return StatusCode::HTTP_101_SWITCHING_PROTOCOLS;
case 102:
return StatusCode::HTTP_102_PROCESSING;
case 103:
return StatusCode::HTTP_103_EARLY_HINTS;
case 200:
return StatusCode::HTTP_200_OK;
case 201:
return StatusCode::HTTP_201_CREATED;
case 202:
return StatusCode::HTTP_202_ACCEPTED;
case 203:
return StatusCode::HTTP_203_NON_AUTHORITATIVE_INFORMATION;
case 204:
return StatusCode::HTTP_204_NO_CONTENT;
case 205:
return StatusCode::HTTP_205_RESET_CONTENT;
case 206:
return StatusCode::HTTP_206_PARTIAL_CONTENT;
case 207:
return StatusCode::HTTP_207_MULTI_STATUS;
case 208:
return StatusCode::HTTP_208_ALREADY_REPORTED;
case 226:
return StatusCode::HTTP_226_IM_USED;
case 300:
return StatusCode::HTTP_300_MULTIPLE_CHOICES;
case 301:
return StatusCode::HTTP_301_MOVED_PERMANENTLY;
case 302:
return StatusCode::HTTP_302_FOUND;
case 303:
return StatusCode::HTTP_303_SEE_OTHER;
case 304:
return StatusCode::HTTP_304_NOT_MODIFIED;
case 305:
return StatusCode::HTTP_305_USE_PROXY;
case 306:
return StatusCode::HTTP_306_SWITCH_PROXY;
case 307:
return StatusCode::HTTP_307_TEMPORARY_REDIRECT;
case 308:
return StatusCode::HTTP_308_PERMANENT_REDIRECT;
case 400:
return StatusCode::HTTP_400_BAD_REQUEST;
case 401:
return StatusCode::HTTP_401_UNAUTHORIZED;
case 402:
return StatusCode::HTTP_402_PAYMENT_REQUIRED;
case 403:
return StatusCode::HTTP_403_FORBIDDEN;
case 404:
return StatusCode::HTTP_404_NOT_FOUND;
case 405:
return StatusCode::HTTP_405_METHOD_NOT_ALLOWED;
case 406:
return StatusCode::HTTP_406_NOT_ACCEPTABLE;
case 407:
return StatusCode::HTTP_407_PROXY_AUTHENTICATION_REQUIRED;
case 408:
return StatusCode::HTTP_408_REQUEST_TIMEOUT;
case 409:
return StatusCode::HTTP_409_CONFLICT;
case 410:
return StatusCode::HTTP_410_GONE;
case 411:
return StatusCode::HTTP_411_LENGTH_REQUIRED;
case 412:
return StatusCode::HTTP_412_PRECONDITION_FAILED;
case 413:
return StatusCode::HTTP_413_PAYLOAD_TOO_LARGE;
case 414:
return StatusCode::HTTP_414_URI_TOO_LONG;
case 415:
return StatusCode::HTTP_415_UNSUPPORTED_MEDIA_TYPE;
case 416:
return StatusCode::HTTP_416_RANGE_NOT_SATISFIABLE;
case 417:
return StatusCode::HTTP_417_EXPECTATION_FAILED;
case 418:
return StatusCode::HTTP_418_IM_A_TEAPOT_;
case 421:
return StatusCode::HTTP_421_MISDIRECTED_REQUEST;
case 422:
return StatusCode::HTTP_422_UNPROCESSABLE_ENTITY;
case 423:
return StatusCode::HTTP_423_LOCKED;
case 424:
return StatusCode::HTTP_424_FAILED_DEPENDENCY;
case 425:
return StatusCode::HTTP_425_TOO_EARLY;
case 426:
return StatusCode::HTTP_426_UPGRADE_REQUIRED;
case 428:
return StatusCode::HTTP_428_PRECONDITION_REQUIRED;
case 429:
return StatusCode::HTTP_429_TOO_MANY_REQUESTS;
case 431:
return StatusCode::HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE;
case 451:
return StatusCode::HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS;
case 500:
return StatusCode::HTTP_500_INTERNAL_SERVER_ERROR;
case 501:
return StatusCode::HTTP_501_NOT_IMPLEMENTED;
case 502:
return StatusCode::HTTP_502_BAD_GATEWAY;
case 503:
return StatusCode::HTTP_503_SERVICE_UNAVAILABLE;
case 504:
return StatusCode::HTTP_504_GATEWAY_TIMEOUT;
case 505:
return StatusCode::HTTP_505_HTTP_VERSION_NOT_SUPPORTED;
case 506:
return StatusCode::HTTP_506_VARIANT_ALSO_NEGOTIATES;
case 507:
return StatusCode::HTTP_507_INSUFFICIENT_STORAGE;
case 508:
return StatusCode::HTTP_508_LOOP_DETECTED;
case 510:
return StatusCode::HTTP_510_NOT_EXTENDED;
case 511:
return StatusCode::HTTP_511_NETWORK_AUTHENTICATION_REQUIRED;
case 0:
default:
return StatusCode::HTTP_UNKNOWN;
}
}
const static std::string NO_CONTENT = ""s;
const static std::string TEXT_CSS = "text/css"s;
const static std::string TEXT_CSV = "text/csv"s;
const static std::string TEXT_HTML = "text/html"s;
const static std::string TEXT_PLAIN = "text/plain"s;
const static std::string TEXT_XML = "text/xml"s;
const static std::string IMAGE_GIF = "image/gif"s;
const static std::string IMAGE_JPEG = "image/jpeg"s;
const static std::string IMAGE_PNG = "image/png"s;
const static std::string IMAGE_TIFF = "image/tiff"s;
const static std::string IMAGE_X_ICON = "image/x-icon"s;
const static std::string IMAGE_SVG_XML = "image/svg+xml"s;
const static std::string VIDEO_MPEG = "video/mpeg"s;
const static std::string VIDEO_MP4 = "video/mp4"s;
const static std::string VIDEO_X_FLV = "video/x-flv"s;
const static std::string VIDEO_WEBM = "video/webm"s;
const static std::string MULTIPART_MIXED = "multipart/mixed"s;
const static std::string MULTIPART_ALTERNATIVE = "multipart/alternative"s;
const static std::string MULTIPART_RELATED = "multipart/related"s;
const static std::string MULTIPART_FORM_DATA = "multipart/form-data"s;
const static std::string AUDIO_MPEG = "audio/mpeg"s;
const static std::string AUDIO_X_MS_WMA = "audio/x-ms-wma"s;
const static std::string AUDIO_X_WAV = "audio/x-wav"s;
const static std::string APPLICATION_JAVASCRIPT = "application/javascript"s;
const static std::string APPLICATION_OCTET_STREAM = "application/octet-stream"s;
const static std::string APPLICATION_OGG = "application/ogg"s;
const static std::string APPLICATION_PDF = "application/pdf"s;
const static std::string APPLICATION_XHTML_XML = "application/xhtml+xml"s;
const static std::string APPLICATION_X_SHOCKWAVE_FLASH = "application/x-shockwave-flash"s;
const static std::string APPLICATION_JSON = "application/json"s;
const static std::string APPLICATION_LD_JSON = "application/ld+json"s;
const static std::string APPLICATION_XML = "application/xml"s;
const static std::string APPLICATION_ZIP = "application/zip"s;
const static std::string APPLICATION_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded"s;
auto to_string(
ContentType content_type) -> const std::string&
{
switch (content_type) {
case ContentType::NO_CONTENT:
return NO_CONTENT;
case ContentType::TEXT_CSS:
return TEXT_CSS;
case ContentType::TEXT_CSV:
return TEXT_CSV;
case ContentType::TEXT_HTML:
return TEXT_HTML;
case ContentType::TEXT_PLAIN:
return TEXT_PLAIN;
case ContentType::TEXT_XML:
return TEXT_XML;
case ContentType::IMAGE_GIF:
return IMAGE_GIF;
case ContentType::IMAGE_JPEG:
return IMAGE_JPEG;
case ContentType::IMAGE_PNG:
return IMAGE_PNG;
case ContentType::IMAGE_TIFF:
return IMAGE_TIFF;
case ContentType::IMAGE_X_ICON:
return IMAGE_X_ICON;
case ContentType::IMAGE_SVG_XML:
return IMAGE_SVG_XML;
case ContentType::VIDEO_MPEG:
return VIDEO_MPEG;
case ContentType::VIDEO_MP4:
return VIDEO_MP4;
case ContentType::VIDEO_X_FLV:
return VIDEO_X_FLV;
case ContentType::VIDEO_WEBM:
return VIDEO_WEBM;
case ContentType::MULTIPART_MIXED:
return MULTIPART_MIXED;
case ContentType::MULTIPART_ALTERNATIVE:
return MULTIPART_ALTERNATIVE;
case ContentType::MULTIPART_RELATED:
return MULTIPART_RELATED;
case ContentType::MULTIPART_FORM_DATA:
return MULTIPART_FORM_DATA;
case ContentType::AUDIO_MPEG:
return AUDIO_MPEG;
case ContentType::AUDIO_X_MS_WMA:
return AUDIO_X_MS_WMA;
case ContentType::AUDIO_X_WAV:
return AUDIO_X_WAV;
case ContentType::APPLICATION_JAVASCRIPT:
return APPLICATION_JAVASCRIPT;
case ContentType::APPLICATION_OCTET_STREAM:
return APPLICATION_OCTET_STREAM;
case ContentType::APPLICATION_OGG:
return APPLICATION_OGG;
case ContentType::APPLICATION_PDF:
return APPLICATION_PDF;
case ContentType::APPLICATION_XHTML_XML:
return APPLICATION_XHTML_XML;
case ContentType::APPLICATION_X_SHOCKWAVE_FLASH:
return APPLICATION_X_SHOCKWAVE_FLASH;
case ContentType::APPLICATION_JSON:
return APPLICATION_JSON;
case ContentType::APPLICATION_LD_JSON:
return APPLICATION_LD_JSON;
case ContentType::APPLICATION_XML:
return APPLICATION_XML;
case ContentType::APPLICATION_ZIP:
return APPLICATION_ZIP;
case ContentType::APPLICATION_X_WWW_FORM_URLENCODED:
return APPLICATION_X_WWW_FORM_URLENCODED;
default:
return NO_CONTENT;
}
}
const static std::string CT_CLOSE = "close"s;
const static std::string CT_KEEP_ALIVE = "keep-alive"s;
const static std::string CT_UPGRADE = "upgrade"s;
auto to_string(
ConnectionType connection_type) -> const std::string&
{
switch (connection_type) {
case ConnectionType::CLOSE:
return CT_CLOSE;
case ConnectionType::KEEP_ALIVE:
return CT_KEEP_ALIVE;
case ConnectionType::UPGRADE:
return CT_UPGRADE;
default:
return CT_KEEP_ALIVE;
}
}
} // namespace lift::http
|
0ae801cef02cdb2b0d77a11e79b843e2b4dea174 | e57d206aac19fbd73482b2ebc5f62afa6186c53e | /src/gv.h | 5489e85c023546b4c8123fef003b60161998ed84 | [] | no_license | adrien1018/CompilerDesign2019 | d41ba71e56cead7cc730357b08d0563cb320395d | ad7b791264b3dabe7e25fb45af3c693489ea1065 | refs/heads/master | 2021-07-05T17:50:58.869633 | 2020-12-28T11:35:28 | 2020-12-28T11:35:28 | 215,280,145 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 135 | h | gv.h | #ifndef GV_H_
#define GV_H_
#include <string>
#include "ast.h"
void PrintGV(AstNode *root, std::string filename);
#endif // GV_H_
|
26622ea57572a549c34826b58cbcaad73a48eedf | 5594030a866fb87befba95b8f3f274a7c2041b54 | /sudoku.cpp | 9348dd9979cae1a0eee1a445bcaaa076cf89ffe7 | [] | no_license | songxiaopeng/sudoku | 1df987e7d1eae9f7ae67aad0dad8edf3afb17ce0 | e09fe7e13da74a0a89993808c932ec27f56265ac | refs/heads/master | 2021-06-18T11:57:12.184121 | 2017-03-14T17:28:39 | 2017-03-14T17:28:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,068 | cpp | sudoku.cpp | #include <iostream>
#include <string>
using namespace std;
#define NUM9 9
class Sudoku
{
public:
Sudoku(int sudokuArray[81])
{
for (int i = 0; i < 81; i++) {
int col = i % 9;
int row = i / 9;
mSudokuMat[row][col] = sudokuArray[i];
}
initMatSets();
};
~Sudoku()
{
};
void initMatSets()
{
memset(mMatSets, 0, sizeof(mMatSets));
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
if (mSudokuMat[i][j] == 0)
{
mMatSets[i][j] = (1 << 10) - 2;
}
else
{
mMatSets[i][j] = 0;
}
}
}
//memset(changeElement, false, sizeof(changeElement));
};
int& getCandidateSet(int row, int col)
{
return mMatSets[row][col];
};
//根据输入 求解这个数独
/*
求解算法:
一遍又一遍的遍历整个9x9格子,
1. 根据横纵行,以及3x3格子块的情况,确定当前格子可选数字 如1~9等
如果当前格子可以确定,那就用当前格子的数字,去剔除掉能影响到的格子
如果不可以确定,那么就把候选的数字集合保留起来
2. 遍历一遍后,再接着遍历,返回1
*/
//初始化 让所有为0的格子的候选集合都为1~9
//std::cout << "what the fuck" << getCandidateSet(3, 1)[0] << std::endl;
void swapMat9x9(bool isBackup, int backup[9][9], int origin[9][9])
{
for (int i = 0; i < 81; i++)
{
int row = i / 9, col = i % 9;
if (isBackup) {
backup[row][col] = origin[row][col];
}
else {
origin[row][col] = backup[row][col];
}
}
}
void backupSudokuMat(int dep)
{
if (changeElement[dep])return;
swapMat9x9(true, mBackupSudokuSets[dep], mSudokuMat );
}
void restoreSudokuMat(int dep)
{
swapMat9x9(false, mBackupSudokuSets[dep], mSudokuMat);
}
void backupAllCandidate(int dep)
{
if (changeElement[dep])return;
swapMat9x9(true, mBackupMatSets[dep], mMatSets);
}
void restoreAllCandidate(int dep)
{
swapMat9x9(false, mBackupMatSets[dep], mMatSets);
}
bool changeElement[82] = {};
bool solve(int dep)
{
for (int x = 0; x < 100; x++)
{
bool changed = false;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
int& val = mSudokuMat[i][j];
//此时val的值是不确定的 那就根据横纵行 还有小方块,来更新当前块的候选数字
//如果更新成功 那么就把val改好
if (val == 0)
{
int& candidateSet = getCandidateSet(i, j);
if (candidateSet == 0)
{
printf("candidateSet==0这里出错了 row:%d col:%d!!!!!\n", i, j);
printSelf();
return false;
}
int res = updateCandidateSet(i, j);
if (res != -1)
{
changed = true;
val = res;
candidateSet = 0;
printf("val值更新成功! %d row:%d col:%d\n", val, i, j);
printSelf();
}
else if (candidateSet == 0)
{
return false;
}
}
}
}
printf("扫描第%d次!!!\n", x);
printPosibilities();
printSelf();
if (isSolved())
{
return true;
}
if (!changed)
{
// printPosibilities();
//尝试优化
for (int i = 0; i < 9; i++)
{
int srow = i / 3 * 3;
int scol = i % 3 * 3;
int oneCnt = 0;
int filter[10] = {};
int filterAttach[10] = {};
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 3; k++)
{
int erow = srow + j;
int ecol = scol + k;
int& cset = getCandidateSet(erow, ecol);
for (int p = 1; p <= 9; p++)
{
if ((cset >> p) & 1)
{
filter[p]++;
filterAttach[p] = erow * 9 + ecol;
}
}
}
}
for (int q = 1; q <= 9; q++)
{
if (filter[q] == 1)
{
int erow = filterAttach[q] / 9;
int ecol = filterAttach[q] % 9;
mMatSets[erow][ecol] = 0;
mSudokuMat[erow][ecol] = q;
changed = true;
}
}
}
}
/*如果集合没有变化,那么就从canSet里面的元素,进行枚举,直到能推出整个*/
if (!changed)
{
int minIndex = -1;
int minCanCnt = 1000;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
int& canSet = getCandidateSet(i, j);
if (canSet != 0)
{
int setCnt = getSetCnt(canSet);
if (setCnt < minCanCnt)
{
minCanCnt = setCnt;
minIndex = i * 9 + j;
}
}
}
}
if (minIndex != -1)
{
int& minCanset = getCandidateSet(minIndex / 9, minIndex % 9);
for (int k = 1; k <= 9; k++) {
if ((minCanset >> k) & 1)
{
backupAllCandidate(dep);
backupSudokuMat(dep);
changeElement[dep] = true;
mSudokuMat[minIndex/9][minIndex%9] = k;
minCanset = 0;
//minCanset &= ~(1 << k);
if (solve(dep+1))
{
printf("更换元素 搜索成功\n");
return true;
}
else
{
printf("dep:%d 更换元素 搜索失败!!!!!\n",dep);
printSelf();
restoreAllCandidate(dep);
restoreSudokuMat(dep);
changeElement[dep] = false;
//printPosibilities();
mSudokuMat[minIndex / 9][minIndex % 9] = 0;
minCanset &= ~(1 << k);
}
}
}
return false;
}
}
}
return false;
}
void printPosibilities()
{
int cnt = 0;
long long posibilities = 1;
int undeterminedElements = 0;
for (int i = 0; i < 9; i++)
{
int srow = i / 3 * 3;
int scol = i % 3 * 3;
printf("i:%d\n", i + 1);
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 3; k++)
{
int erow = srow + j;
int ecol = scol + k;
int& set = getCandidateSet(erow, ecol);
int cnt = getSetCnt(set);
if (cnt != 0)
{
undeterminedElements++;
posibilities *= cnt;
printf("(%d,%d,n=%d):", erow + 1, ecol + 1, cnt);
printSet(set);
printf("\t");
}
}
printf("\n");
}
}
printf("剩余可能的组合数:%lld 未确定元素数:%d\n", posibilities, undeterminedElements);
}
void printSet(int set)
{
int count = 0;
for (int i = 1; i <= 9; i++)
{
if ((set >> i) & 1)
{
if (count == 0)
{
printf("{%d", i);
count++;
}
else
{
printf(",%d", i);
}
}
}
printf("}");
}
int getSetCnt(int set)
{
int cnt = 0;
for (int i = 1; i <= 9; i++)
{
if ((set >> i) & 1)
{
cnt++;
}
}
// printf("Cnt:%d\n",cnt);
return cnt;
}
int updateCandidateSet(int row, int col)
{
//求出横竖行还有小方格的并集 然后用val的候选集减去这个并集 便能成功更新这个候选集
int& candidateSet = getCandidateSet(row, col);
for (int i = 0; i < 9; i++)
{
if (mSudokuMat[row][i] != 0)
{
candidateSet &= ~(1 << mSudokuMat[row][i]);
}
if (mSudokuMat[i][col] != 0)
{
candidateSet &= ~(1 << mSudokuMat[i][col]);
}
}
int smallSetStartRow = row / 3 * 3;
int smallSetStartCol = col / 3 * 3;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
int& innerVal = mSudokuMat[smallSetStartRow + i][smallSetStartCol + j];
if (innerVal != 0)
{
candidateSet &= ~(1 << innerVal);
}
}
}
if (candidateSet != 0)
{
int cnt = 0;
int candidateNum = -1;
for (int i = 1; i <= 9; i++)
{
if ((candidateSet >> i) & 1)
{
cnt++;
candidateNum = i;
}
}
if (cnt == 1)
{
return candidateNum;
}
}
return -1;
}
/*
判断一个数独是否正确
*/
bool isSolved()
{
/*
判断每一行 是否OK
*/
for (int row = 0; row < 9; row++)
{
if (!isSetOk(mSudokuMat[row])) {
return false;
}
}
/*
判断每一列 是否OK
*/
for (int col = 0; col < 9; col++)
{
int colSet[9];
for (int i = 0; i < 9; i++)
{
colSet[i] = mSudokuMat[i][col];
}
if (!isSetOk(colSet)) {
return false;
}
}
/*
判断每一个小集合是否OK
*/
for (int iset = 0; iset< 9; iset++)
{
int innerSet[9], outRow, outCol;
outRow = iset / 3 * 3;
outCol = iset % 3 * 3;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
innerSet[i * 3 + j] = mSudokuMat[outRow + i][outCol + j];
}
}
//printf("输出InnerSet i:%d\n", iset);
//print(3, innerSet);
if (!isSetOk(innerSet)) {
return false;
}
}
printf("数独已完成\n");
return true;
}
bool isSetOk(int(&set)[9])
{
int emptySet[10] ={};
for (int i = 0; i < 9; i++) {
if (set[i] == 0)return false;
emptySet[set[i]]++;
if (emptySet[set[i]] > 1) {
printSelf();
printf("数独仍待解决\n");
return false;
}
}
return true;
}
void print(int dimension, int* mat)
{
for (int i = 0; i < dimension; i++) {
for (int j = 0; j < dimension; j++) {
printf("%d ", mat[i*dimension + j]);
if ((j + 1) % 3 == 0)printf(" ");
}
if ((i + 1) % 3 == 0)printf("\n");
printf("\n");
}
}
void printSelf()
{
printf("输出mSudokuMat:\n");
print(9, &(mSudokuMat[0][0]));
}
private:
int mSudokuMat[9][9];
int mMatSets[9][9];
int mBackupSudokuSets[100][9][9] = {};
int mBackupMatSets[100][9][9] = {};
};
int InputSudoku[] = {
//0,0,0, 0,0,0, 0,0,0,
8,0,0, 0,0,0, 0,0,0,
0,0,3, 6,0,0, 0,0,0,
0,7,0, 0,9,0, 2,0,0,
0,5,0, 0,0,7, 0,0,0,
0,0,0, 0,4,5, 7,0,0,
0,0,0, 1,0,0, 0,3,0,
0,0,1, 0,0,0, 0,6,8,
0,0,8, 5,0,0, 0,1,0,
0,9,0, 0,0,0, 4,0,0,
/*0,5,0, 0,0,1, 0,0,0,
0,0,0, 0,0,0, 0,0,0,
0,0,4, 0,7,0, 0,0,9,
0,0,0, 0,0,2, 1,5,0,
7,0,9, 0,8,0, 0,0,0,
0,0,0, 0,0,0, 0,3,0,
0,0,7, 9,0,0, 0,0,0,
0,0,0, 0,0,0, 0,1,0,
0,0,8, 0,6,0, 0,0,0*/
/*0,0,0, 0,0,0, 0,0,0,
0,9,7, 0,8,0, 0,0,0,
0,0,0, 3,0,0, 0,0,1,
0,0,0, 0,0,0, 9,7,0,
3,0,0, 1,0,0, 0,2,0,
0,0,0, 0,6,0, 8,0,0,
6,0,0, 0,0,0, 0,0,0,
1,0,0, 0,0,5, 0,0,4,
0,0,0, 0,9,0, 0,0,0,*/
/*3,0,2, 0,0,4, 0,0,8,
7,0,0, 0,1,0, 0,0,9,
0,0,0, 0,2,0, 7,0,6,
0,7,0, 1,3,0, 0,0,4,
0,3,0, 0,9,8, 0,0,0,
1,0,0, 0,0,0, 0,0,0,
0,0,0, 3,4,9, 0,8,0,
0,0,3, 0,0,0, 6,0,0,
0,0,0, 0,7,6, 0,9,0,*/
/*0,0,0, 8,6,5, 9,0,0,
7,0,0, 0,0,0, 6,0,1,
0,2,6, 0,0,0, 0,0,0,
9,0,0, 0,7,0, 0,0,5,
0,6,0, 3,0,0, 2,0,0,
0,0,0, 0,0,4, 0,0,0,
6,0,0, 9,1,3, 0,0,0,
0,0,0, 0,0,0, 0,1,6,
3,8,0, 0,0,0, 4,0,0,*/
/*0,9,0, 0,2,8, 7,0,0,
7,0,0, 0,0,0, 0,0,3,
0,0,2, 0,3,0, 0,0,0,
7,4,0, 0,0,0, 0,6,0,
0,0,0, 0,9,0, 8,0,0,
0,0,3, 4,0,0, 0,0,0,
1,0,0, 0,0,0, 0,9,5,
0,6,0, 0,1,9, 3,8,0,
9,0,0, 3,7,0, 0,0,0,
*/
// 0,0,0,0,5,4,9,0,0,
// 1,6,0,0,0,0,0,0,0,
// 2,0,0,0,0,0,0,0,0,
// 0,0,8,0,0,0,7,0,0,
// 0,0,0,0,0,0,0,0,0,
// 0,0,0,6,0,1,0,0,2,
// 0,0,7,0,9,0,8,0,0,
// 0,0,0,0,7,0,0,0,0,
// 3,0,0,0,0,0,0,7,1
// 8,7,3,2,5,4,9,1,6,
// 1,6,9,8,3,0,5,4,7,
// 2,5,4,9,1,6,3,8,0,
// 9,4,8,5,2,3,7,6,0,
// 6,2,0,0,4,7,1,0,8,
// 7,3,5,6,8,1,4,9,2,
// 0,1,7,3,9,2,8,5,4,
// 4,8,2,1,7,5,6,3,9,
// 3,9,0,4,6,8,2,7,1
/* 3,0,2, 0,0,8 ,0,0,7,
0,0,0, 0,0,0 ,0,0,0,
4,0,0, 5,9,0 ,0,6,0,
0,0,4, 0,0,9 ,0,0,3,
6,0,8, 0,4,0 ,0,2,0,
2,0,1, 6,7,5 ,0,9,0,
0,0,0, 0,0,0 ,0,0,0,
5,7,0, 1,0,3 ,0,0,4,
0,0,0, 8,2,7 ,0,0,0*/
/* 0,8,7, 0,0,5, 0,3,0,
0,0,0, 7,0,0, 0,2,0,
0,0,0, 0,4,0, 5,9,0,
0,0,0, 0,0,3, 0,4,0,
6,0,0, 0,9,0, 0,0,0,
0,3,0, 0,5,0, 0,0,0,
0,5,1, 9,0,0, 0,0,0,
4,0,0, 0,0,1, 8,0,0,
0,0,6, 0,3,0, 1,0,0,*/
/* 0,0,0 ,0,2,4 ,0,6,9,
9,0,0 ,1,0,0 ,7,8,0,
8,5,0 ,0,9,0 ,0,3,0,
0,1,0 ,0,0,3 ,0,9,6,
5,2,0 ,0,8,0 ,0,0,0,
0,0,7 ,9,0,2 ,0,0,4,
0,8,1 ,0,4,0 ,0,0,5,
3,6,4 ,0,0,1 ,0,0,8,
0,0,5 ,7,0,8 ,1,0,0*/
// 3,9,6,5,8,4,1,7,2,
//2,7,5,1,3,9,6,8,4,
//1,8,4,7,2,6,5,3,9,
//6,0,8,9,4,5,0,1,7,
//9,0,1,0,6,7,8,0,5,
//5,0,7,8,1,0,9,0,6,
//7,1,0,6,9,8,4,0,3,
//4,5,9,0,7,1,0,6,8,
//8,6,0,4,5,0,7,9,1
/*0,7,2,9,0,0,0,1,0,
0,0,0,0,3,0,0,9,8,
8,0,5,4,7,0,0,0,0,
6,1,4,0,0,0,0,2,3,
0,0,0,0,2,3,4,0,1,
7,0,0,1,9,0,0,6,0,
0,3,7,0,0,2,0,0,0,
4,0,8,0,0,0,2,5,0,
0,5,0,0,8,6,3,0,9*/
};
int OkSudoku[] = {
3,9,6,5,8,4,1,7,2,
2,7,5,1,3,9,6,8,4,
1,8,4,7,2,6,5,3,9,
6,2,8,9,4,5,3,1,7,
9,3,1,2,6,7,8,4,5,
5,4,7,8,1,3,9,2,6,
7,1,2,6,9,8,4,5,3,
4,5,9,3,7,1,2,6,8,
8,6,3,4,5,2,7,9,1
};
int main()
{
Sudoku mSudo(InputSudoku);
mSudo.printSelf();
mSudo.solve(0);
//mSudo.isSolved();
while (true);
return 0;
}
// 0,0,0,0,0,0,0,0,0,
// 0,0,0,0,0,0,0,0,0,
// 0,0,0,0,0,0,0,0,0,
// 0,0,0,0,0,0,0,0,0,
// 0,0,0,0,0,0,0,0,0,
// 0,0,0,0,0,0,0,0,0
|
032956073b946c38d64d2dbb54c542626786feb9 | 17445d64663a7a7127a23dfe31faa2d502479e7b | /sources/Researcher.hpp | d15d2ec7e2e281acab00a06dfc2a36a803975a82 | [] | no_license | michaeleliyahu/Pamdomic_game | 64f83bdb0119d29feba318f6e9428650482b5bc6 | 7d7ecd3375fab26e5b47a0d9fa4480d9b08ab7bb | refs/heads/master | 2023-04-28T08:24:05.211623 | 2021-05-18T20:00:07 | 2021-05-18T20:00:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 305 | hpp | Researcher.hpp | #include "Player.hpp"
namespace pandemic
{
class Researcher : public Player
{
public:
Researcher(Board &board, City city) : Player(board, city) {}
Researcher &discover_cure(Color color);
std::string role()
{
return "Researcher";
}
};
} |
4b93006219b265e0c506c847f59f0982f402d7e6 | b850714723a49408b16fc71940ec05dc7fed7f36 | /header.h | 345bc5a1e06ba29d9f603b69e5d49f51445a21c2 | [] | no_license | BarunPrakash/CPLUSlearningProjects2016 | 977f95809769f2ded4a81190d8b4a8fe4089a34e | f7900c92f14abe6ca912ad102ee3d0f4056b0249 | refs/heads/master | 2022-01-20T02:28:19.515235 | 2019-07-27T03:26:14 | 2019-07-27T03:26:14 | 98,091,159 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,405 | h | header.h | /*
* header.h
*
* Created on: 21-Mar-2016
* Author: epl-lab
*/
#ifndef HEADER_H_
#define HEADER_H_
/**********************************************************/
#include<string>
#include<iostream>
#include<fstream>
#include<iomanip>
#include<stdint.h>
#include<string.h>
using namespace std;
/************************************************************/
#define maxNumbOfSalsePerson 5
#define noOfQuater 4
#define offMode 0
#define onMode 1
#define arrayIndex 1
#define quarterFirst 3
#define quarterSecond 6
#define quarterThird 9
#define quarterFourth 12
#define numofFucCall 2
#define getInit 0
#define readFromFile 1
#define DEBUG
/*************************************************************/
typedef struct salesPersonRec
{
string ID;
double salseByquater[noOfQuater];
double totalSales;
}salesPersonRec;
/*********************************************************************/
#if onMode
class empDataAnalysis
{
private:
uint8_t index;
uint8_t iQuarter;
public:
class salesPersonRec
{
public:
string ID;
double salseByquater[noOfQuater];
double totalSales;
}salesPersonArr[maxNumbOfSalsePerson];
public:
void initialize(ifstream &);
void getData(ifstream &);
void salesByQuarter(double totalSalesByQuarter[]);
void salesByYearlyForEachEmploye(void);
void printEmployeReport(ofstream & outputData,double totalSalesByQuarter[]);
void maxSalesByPerson(ofstream & );
void maxSalesByQuarter(ofstream & outputFile ,double maxSalesByQt[]);
void sumOfAllStack(void);
};
#endif
//memset(salesPersonRec,'\0',sizeof(salesPersonRec));
/*******************************************************************/
class empDataAnalysisB
{
public:
class salesPersonRec
{
public:
string ID;
double salseByquater[noOfQuater];
double totalSales;
}salesPersonArr[maxNumbOfSalsePerson];
};
class empDataAnalysisClass :public empDataAnalysisB
{
private:
uint8_t index;
uint8_t iQuarter;
public:
void initialize(ifstream &);
void getData(ifstream &);
void salesByQuarter(double totalSalesByQuarter[]);
void salesByYearlyForEachEmploye(void);
void printEmployeReport(ofstream & outputData,double totalSalesByQuarter[]);
void maxSalesByPerson(ofstream & );
void maxSalesByQuarter(ofstream & outputFile ,double maxSalesByQt[]);
void sumOfAllStack(void);
};
/**********************************************************************/
void initialize(ifstream & indata,salesPersonRec salesPersonList[]);
void getData(ifstream &indata,salesPersonRec salesPersonList[]);
/********************************************************************/
#if offMode
typedef void (*funcForInit)(ifstream &,salesPersonRec *);
funcForInit readAndIntilize[numofFucCall]={initialize ,getData };
#endif
/******************************************************************/
extern void salesByQuarter(salesPersonRec list[],double totalSalesByQuarter[]);
extern void salesByYearlyForEachEmploye(salesPersonRec list[]);
extern void printEmployeReport(ofstream & outputData,salesPersonRec list[],double totalSalesByQuarter[]);
extern void maxSalesByPerson(ofstream & outputFile ,salesPersonRec list[]);
extern void maxSalesByQuarter(ofstream & outputFile ,double maxSalesByQt[]);
extern void sumOfAllStack(void);
/**********************************************************/
#endif /* HEADER_H_ */
|
a5ee5dd0350e27273372ad4ca1e66115353a5641 | ecb4887e4cc5ed91ede47dfd8c0b65869f8d3535 | /easyClient.cpp | f757008f52e50c0e6ea0133fcfe7475a81d14f24 | [] | no_license | TGDdream/network-learn | 8054eafc7fbcd3b1d6eae038afcce2e549fcd072 | ead7f7ad33ba5d6331ff7366439e734a012bb767 | refs/heads/master | 2022-08-19T20:20:33.662228 | 2020-05-27T04:49:46 | 2020-05-27T04:49:46 | 267,221,269 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,703 | cpp | easyClient.cpp | #include "easyClient.h"
easyClient::easyClient()
{
_sock = INVALID_SOCKET;
_lastPos = 0;
}
easyClient::~easyClient()
{
Close();
}
/* 初始化Socket */
void easyClient::InitSocket()
{
if (_sock != INVALID_SOCKET)
{
cout << "repeat Socket ..close _socket" << "<" << _sock << ">" << endl;
Close();
}
#ifdef _WINDOWS
WORD ver = MAKEWORD(2, 2);
WSADATA dat;
WSAStartup(ver, &dat);
#endif
_sock = socket(AF_INET, SOCK_STREAM, 0);
if (INVALID_SOCKET == _sock)
{
cout << "creat socket error..." << endl;
}
}
/* 连接到指定IP和端口的服务器 */
int easyClient::Connect(char* ip, unsigned short port)
{
ServerIp = ip;
if (_sock == INVALID_SOCKET)
{
InitSocket();
}
sockaddr_in _sin = {};
_sin.sin_family = AF_INET;
_sin.sin_port = htons(port);
#ifdef _WINDOWS
_sin.sin_addr.S_un.S_addr = inet_addr(ServerIp);
#else
_sin.sin_addr.s_addr = inet_addr(ServerIp);
#endif
int ret = connect(_sock, (sockaddr*)&_sin, sizeof(sockaddr_in));
if (SOCKET_ERROR == ret)
{
cout << "connect Socket <" << _sock << "> error..." << endl;
Close();
}
else
{
//cout << "connect Socket <" << _sock << "> success..." << "--connect Server IP: " << ServerIp << endl;
}
return ret;
}
/*关闭当前的网络连接*/
void easyClient::Close()
{
if (_sock != INVALID_SOCKET)
{
#ifdef _WINDOWS
closesocket(_sock);
WSACleanup();
#else
close(_sock);
#endif
_sock = INVALID_SOCKET;
}
}
SOCKET easyClient::getSocket()
{
return _sock;
}
/* 运行网络服务 */
bool easyClient::onRun()
{
if (isRun())
{
fd_set fdRead;
FD_ZERO(&fdRead);
FD_SET(_sock, &fdRead);
timeval select_time = { 0,0 };
#ifdef _WINDOWS
auto ret = select(0, &fdRead, 0, 0, &select_time);
#else
auto ret = select(_sock + 1, &fdRead, 0, 0, &select_time);
#endif
if (ret < 0)
{
cout << "select end..." << endl;
}
if (FD_ISSET(_sock, &fdRead))
{
FD_CLR(_sock, &fdRead);
if (-1 == recvData())
{
cout << "select end..." << endl;
Close();
return false;
}
}
return true;
}
else return false;
}
bool easyClient::isRun()
{
return _sock != INVALID_SOCKET;
}
/* 消息处理 */
/* 处理粘包,拆包 */
int easyClient::recvData()
{
int nlen = recv(_sock, _ftMsgBuf, MSG_BUF_SIZE, 0);
if (nlen <= 0)
{
cout << "Server connect false..." << endl;
return -1;
}
else
{
//一级缓冲数据拷贝到二级缓冲区
memcpy(_sdMsgBuf + _lastPos, _ftMsgBuf, nlen);
_lastPos += nlen;
//二级缓冲区满
if (_lastPos >= MSG_BUF_SIZE * 10 || nlen >= MSG_BUF_SIZE)
{
cout << "Client Overflow MSG_BUF_SIZE" << endl;
return -1;
}
dataHeader* datahead = (dataHeader*)_sdMsgBuf;
//缓冲的数据长度大于head的长度时,判断接收数据类型
while (_lastPos >= sizeof(dataHeader))
{
//判断接收长度大于消息的总长度,处理消息
if (_lastPos >= datahead->dataLen)
{
int nSize = _lastPos - datahead->dataLen;
onNetMsg(datahead);
//将未处理的数据前移
memcpy(_sdMsgBuf, _sdMsgBuf + datahead->dataLen, nSize);
//消息处理后更新二级缓冲区中lastPos位置
_lastPos = nSize;
}
else
{
break;
}
}
}
return 0;
}
/* 响应网络消息 */
int easyClient::onNetMsg(dataHeader* datahead)
{
switch (datahead->dataCmd)
{
case(CMD_LOGIN_RESULT): {
logInResult* login_r = (logInResult*)datahead;
if (login_r->i_logInReslut != 0)
{
cout << "login success" << endl;
}
else
{
cout << "Check the password" << endl;
}
break;
}
case(CMD_NEW_CLIENT_ADD): {
newClientAdd* newClient = (newClientAdd*)datahead;
cout << "new Client Add..." << "SOCKET:" << newClient->newClientSocket << endl;
break;
}
case(CMD_LOGOUT_RESULT): {
logOutResult* logout_r = (logOutResult*)datahead;
if (logout_r->i_logOutReslut != 0)
{
cout << "logout success" << endl;
}
else
{
cout << "can't Logout..." << endl;
}
break;
}case(CMD_ERR): {
errer* err = (errer*)datahead;
cout << "CMD_ERR ; " << err->_err << endl;
break;
}case(CMD_DATATX): {
//dataer* dat = (dataer*)datahead;
//cout << "test::reciv CMD_DATATX" << "::" << dat->dataStr << endl;
/*if (0 != strcmp(dat->dataStr, "ssssssssssssssssssssssssssq"))
{
cout << "error data" << endl;
}*/
break;
}
default: {
cout << "no define Head Command!" << endl;
}
}
return 0;
}
/* 发送数据包 */
int easyClient::sendData(dataHeader* data)
{
if (isRun() && data)
return send(_sock, (char *)data, data->dataLen, 0);
else return SOCKET_ERROR;
}
/* 一次发送多个数据包 */
int easyClient::sendDataN(dataHeader* data,int n)
{
if (isRun() && data)
return send(_sock, (char *)data, (data->dataLen)*n, 0);
else return SOCKET_ERROR;
} |
8b50f0be30c6da232e7ee6e759f30dab321d2204 | d75849d7f1ec1ac452d4a71724d822ae33e8655a | /src/ui/winmain.h | 5e3669bc4c12176698925ac29e196100f2715097 | [] | no_license | xavierliancw/CS1C-Class-Project | eab8950b4537370d6ef25370cd5587f421a75753 | 85a4a51a3a6848795c1118dd76e7cbb176584f6a | refs/heads/master | 2020-05-04T13:09:09.335860 | 2019-05-28T21:45:50 | 2019-05-28T21:45:50 | 179,149,378 | 1 | 0 | null | 2019-05-06T08:46:04 | 2019-04-02T19:59:17 | C++ | UTF-8 | C++ | false | false | 3,153 | h | winmain.h | #ifndef WINMAIN_H
#define WINMAIN_H
#include "dlgshapereport.h"
#include "dlgcontactform.h"
#include "dlgeditorrectframe.h"
#include "dlgtestimonialcreate.h"
#include "dlgloginscreen.h"
#include "models/shapeellipse.h"
#include "models/ishape.h"
#include "models/shapecircle.h"
#include "viewmodels/vmcanvas.h"
#include "ui/dlgeditorvertices.h"
#include "ui/lcshapelayer.h"
#include "ui/dlgeditortext.h"
#include "models/jsontestimonial.h"
#include <util/goldenconevector.h>
#include <chrono>
#include <QDialog>
#include <QMainWindow>
#include <QPainter>
#include <QDebug>
#include <QTimer>
#include <QListWidgetItem>
#include <QDropEvent>
#include <QColorDialog>
#include <QMovie>
#include <QStackedLayout>
#include <QDesktopWidget>
namespace Ui {
class WINMain;
}
/**
* @brief The main window for the entire application.
*
*/
class WINMain : public QMainWindow
{
Q_OBJECT
public:
/**
* @brief The different screens WINMain can switch between.
*/
enum ScreensInWINMain {welcome, guest, canvas};
/**
* @brief Constructor.
*
* @param parent: Parent QWidget pointer.
*/
explicit WINMain(QWidget *parent = nullptr);
/**
* @brief Destructor.
*
*/
~WINMain() override;
protected:
/**
* @brief Lifecycle event that renders graphics on the window.
*
* @param QPaintEvent pointer (unused).
*/
virtual void paintEvent(QPaintEvent*) override;
/**
* @brief Lifecycle event that fires when the window is closed.
*
* @param QCloseEvent pointer (unused).
*/
void closeEvent(QCloseEvent*) override;
/**
* @brief Look for Qt events
* @param object : GUI element that's generating a Qt event
* @param event : Qt event that's happening
* @return Returns false always
*
* Drag and drop functionality within the itinerary is implemented
* in this method.
*/
bool eventFilter(QObject *object, QEvent *event) override;
private:
//General UI
Ui::WINMain *ui;
void switchScreenToShow(ScreensInWINMain);
//Welcome screen UI
QMovie* movie;
QVector<QString> testimonials;
void refreshTestimonials();
//Pop up UI
DLGContactForm *contactFormWin;
DLGEditorRectFrame *dlgRectEditor;
DLGLoginScreen *dlgLogin;
//Canvas UI
QTimer* refreshTimer;
VMCanvas vm;
QVector<LCShapeLayer*> layerVwCells;
int rowNumberFromPickUpEvent;
VMCanvas initCanvasVM();
void initCanvasBackBt();
void refreshLayersVw();
void initLayerSelectionBehavior();
void redrawWhateverCurrentCanvasIsShowing();
void summonDlgThatEdits(IShape*);
void updatePropertyInspectorFor(const IShape*);
void initPropertyInspector();
void initVertexEditor();
void initRectEditor();
void initTxtEditor();
void updatePropInspectorVisibility();
void initReportGenBt();
//Welcome screen UI
void initStartBt();
void initTestimonialCreateBt();
void initContactUsBt();
VMCanvas initVM();
void initGuestAuthenticateBt();
void initGuestBackBt();
};
#endif // WINMAIN_H
|
1184accfb68c377d440ac4b73695356f1f83a9c5 | 9721df80bca8d6cd8aa4914b47f6b5c68981a9c0 | /MetalTrainer/src/interval/PlatformSpecific.cpp | a5548f7afc704493307ddbf9f42a0e617f23d579 | [
"BSD-3-Clause"
] | permissive | eperiod-software/metal-trainer | 3ce0467c46ec8af6c3b68c328fe24c9cbf232dea | 9a9307d15eda4c071357a0259069d2ddd6358d89 | refs/heads/master | 2016-09-05T13:16:17.320730 | 2015-09-13T08:04:43 | 2015-09-13T08:04:43 | 40,936,061 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 565 | cpp | PlatformSpecific.cpp | #include <QThread>
#include <QMutex>
#include <unistd.h>
#include "PlatformSpecific.h"
class Sleeper : public QThread {
public:
static void sleepMs(TimeMs amount) {
QThread::msleep(amount);
}
};
void TimeManager::sleep(TimeMs amount) {
Sleeper::sleepMs(amount);
}
Mutex::Mutex() {
QMutex *mutex = new QMutex();
data = (void *)mutex;
}
Mutex::~Mutex() {
QMutex *mutex = (QMutex *)data;
delete mutex;
}
void Mutex::lock() {
QMutex *mutex = (QMutex *)data;
mutex->lock();
}
void Mutex::unlock() {
QMutex *mutex = (QMutex *)data;
mutex->unlock();
}
|
ba71925de4ad6f745a90e641d6ffbdab9470da13 | fb33129d7281363ce0b1e0cbc82e721980952706 | /w13/evolution/algorithm.cpp | 0cbdf6f8184a9bededc9ab4ece40df204eac3813 | [] | no_license | bunjj/Algorithms-Lab | 4f83a8bfb1ba569dab352c8fe165d51a3cf6a8cc | eb38dd3ecc2e4fd971813d7c22471206e096e1ec | refs/heads/main | 2023-08-18T02:39:51.189215 | 2021-10-03T19:31:56 | 2021-10-03T19:31:56 | 413,116,275 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,960 | cpp | algorithm.cpp | #include <limits>
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <set>
#include <stack>
struct specie{
std::string name;
int age;
std::vector<std::string> children;
};
struct query{
std::string name;
int age;
int ind;
};
void testcase() {
int n, q;
std::cin >> n >> q;
std::unordered_map<std::string, specie> species;
std::set<std::pair<int, std::string>> result;
std::unordered_map<std::string, std::vector<query>> queries;
std::string luca;
int oldest = 0;
for(int i = 0; i < n; i++){
std::string s; int a;
std::cin >> s >> a;
species[s] = {s, a, std::vector<std::string> ()};
if(a > oldest){
oldest = a;
luca = s;
}
}
for(int i = 1; i < n; i++){
std::string s, p;
std::cin >> s >> p;
species[p].children.push_back(s);
}
for(int i = 0; i < q; i++){
std::string s; int b;
std::cin >> s >> b;
queries[s].push_back({s, b, i});
}
std::unordered_map<std::string, bool> vis;
std::stack<std::string> stack;
std::vector<std::string> path;
stack.push(luca);
while(!stack.empty()){
std::string current = stack.top();
if(vis[current]){
path.pop_back();
stack.pop();
continue;
}
vis[current] = true;
for(auto it = species[current].children.begin(); it != species[current].children.end(); it++){
stack.push(*it);
}
path.push_back(current);
for(auto it = queries[current].begin(); it != queries[current].end(); it++){
int age = it->age;
int max = path.size();
int min = 0;
while(min < max){
int p = min + (max-min)/2;
if(species[path[p]].age > age){
min = p + 1;
}else{
max = p;
}
}
result.insert({it->ind, path[max]});
}
}
for(auto out : result){
std::cout << out.second << " ";
}
std::cout << std::endl;
}
int main() {
std::ios_base::sync_with_stdio(false);
int t;
std::cin >> t;
for (int i = 0; i < t; ++i)
testcase();
}
|
7948d62279a2b712220abde56f633f9757d1ddb0 | 2d42a50f7f3b4a864ee19a42ea88a79be4320069 | /source/graphics/primitives/index_array.h | 37ef4d30b94aab024df736a10a3eb18fbb8990a3 | [] | no_license | Mikalai/punk_project_a | 8a4f55e49e2ad478fdeefa68293012af4b64f5d4 | 8829eb077f84d4fd7b476fd951c93377a3073e48 | refs/heads/master | 2016-09-06T05:58:53.039941 | 2015-01-24T11:56:49 | 2015-01-24T11:56:49 | 14,536,431 | 1 | 0 | null | 2014-06-26T06:40:50 | 2013-11-19T20:03:46 | C | UTF-8 | C++ | false | false | 1,825 | h | index_array.h | #ifndef INDEX_ARRAY_H
#define INDEX_ARRAY_H
#include <vector>
#include <config.h>
#include "iindex_array.h"
PUNK_ENGINE_BEGIN
namespace Graphics {
template<typename IndexType> class IndexArray : public IIndexArray {
public:
IndexArray(const std::vector<IndexType>& array)
: m_array(array) {}
IndexArray(IndexType* buffer, std::uint64_t size) {
m_array.resize(size);
for (auto i = 0; i < size; ++i) {
m_array.push_back(*((IndexType*)buffer+i));
}
}
virtual ~IndexArray() {}
// IObject
void QueryInterface(const Core::Guid& type, void** object) {
Core::QueryInterface(this, type, object, { Core::IID_IObject, IID_IIndexArray });
}
std::uint32_t AddRef() override {
return m_ref_count.fetch_add(1);
}
std::uint32_t Release() override {
auto v = m_ref_count.fetch_sub(1) - 1;
if (!v)
delete this;
return v;
}
// IIndexArray
std::uint64_t GetIndexSize() const override {
return sizeof(IndexType);
}
std::uint64_t GetIndexCount() const override {
return m_array.size();
}
std::uint64_t GetMemoryUsage() const override {
return GetIndexCount()*GetIndexSize();
}
IndexType* GetIndexBuffer() {
return &m_array[0];
}
const IndexType* GetIndexBuffer() const {
return &m_array[0];
}
private:
void* GetBuffer() override {
return (void*)&m_array[0];
}
const void* GetBuffer() const override {
return (const void*)&m_array[0];
}
std::atomic<std::uint32_t> m_ref_count{ 0 };
std::vector<IndexType> m_array;
};
template<> class IndexArray < std::nullptr_t > {};
}
PUNK_ENGINE_END
#endif // INDEX_ARRAY_H
|
6b829f76c5fa718b9614af58b603b0b041d5c710 | e5dad8e72f6c89011ae030f8076ac25c365f0b5f | /caret_gui/GuiBorderProjectionDialog.cxx | abe391cc05588452d2d36b0f31021c0cd51e9a2d | [] | no_license | djsperka/caret | f9a99dc5b88c4ab25edf8b1aa557fe51588c2652 | 153f8e334e0cbe37d14f78c52c935c074b796370 | refs/heads/master | 2023-07-15T19:34:16.565767 | 2020-03-07T00:29:29 | 2020-03-07T00:29:29 | 122,994,146 | 0 | 1 | null | 2018-02-26T16:06:03 | 2018-02-26T16:06:03 | null | UTF-8 | C++ | false | false | 3,988 | cxx | GuiBorderProjectionDialog.cxx | /*LICENSE_START*/
/*
* Copyright 1995-2002 Washington University School of Medicine
*
* http://brainmap.wustl.edu
*
* This file is part of CARET.
*
* CARET 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.
*
* CARET 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 CARET; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*LICENSE_END*/
#include <QApplication>
#include <QButtonGroup>
#include <QGroupBox>
#include <QLayout>
#include <QPushButton>
#include <QRadioButton>
#include "BorderFileProjector.h"
#include "BorderProjectionFile.h"
#include "BrainModelBorderSet.h"
#include "BrainSet.h"
#include "GuiBrainModelOpenGL.h"
#include "GuiBorderProjectionDialog.h"
#include "GuiFilesModified.h"
#include "GuiMainWindow.h"
#include "QtUtilities.h"
#include "global_variables.h"
/**
* Constructor
*/
GuiBorderProjectionDialog::GuiBorderProjectionDialog(QWidget* parent)
: WuQDialog(parent)
{
setModal(true);
setWindowTitle("Border Projection");
QVBoxLayout* dialogLayout = new QVBoxLayout(this);
dialogLayout->setMargin(5);
dialogLayout->setSpacing(5);
//
// Projection method buttons
//
QGroupBox* projGroupBox = new QGroupBox("Projection Method");
dialogLayout->addWidget(projGroupBox);
nearestNodeButton = new QRadioButton("Nearest Node");
nearestTileButton = new QRadioButton("Nearest Tile");
QVBoxLayout* projGroupLayout = new QVBoxLayout(projGroupBox);
projGroupLayout->addWidget(nearestNodeButton);
projGroupLayout->addWidget(nearestTileButton);
QButtonGroup* buttGroup = new QButtonGroup(this);
buttGroup->addButton(nearestNodeButton);
buttGroup->addButton(nearestTileButton);
nearestTileButton->setChecked(true);
//
// Buttons
//
QHBoxLayout* buttonsLayout = new QHBoxLayout;
dialogLayout->addLayout(buttonsLayout);
buttonsLayout->setSpacing(5);
QPushButton* ok = new QPushButton("OK");
QObject::connect(ok, SIGNAL(clicked()),
this, SLOT(accept()));
buttonsLayout->addWidget(ok);
QPushButton* close = new QPushButton("Cancel");
QObject::connect(close, SIGNAL(clicked()),
this, SLOT(reject()));
buttonsLayout->addWidget(close);
QtUtilities::makeButtonsSameSize(ok, close);
}
/**
* Destructor
*/
GuiBorderProjectionDialog::~GuiBorderProjectionDialog()
{
}
/**
* called by QDialog when accept/reject signal is emitted.
*/
void
GuiBorderProjectionDialog::done(int r)
{
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
if (r == QDialog::Accepted) {
GuiBrainModelOpenGL* openGL = theMainWindow->getBrainModelOpenGL();
BrainModelSurface* bms = openGL->getDisplayedBrainModelSurface();
if (bms != NULL) {
//
// Project borders used by this surface
//
BrainModelBorderSet* bmbs = theMainWindow->getBrainSet()->getBorderSet();
bmbs->projectBorders(bms, nearestTileButton->isChecked());
//
// Notify that borders have been changed.
//
GuiFilesModified fm;
fm.setBorderModified();
theMainWindow->fileModificationUpdate(fm);
//
// Update all displayed surfaces
//
GuiBrainModelOpenGL::updateAllGL(NULL);
}
}
//
// Call parent' method to close dialog.
//
QDialog::done(r);
QApplication::restoreOverrideCursor();
}
|
967ea9ed4852de4c29ca50d613c227bfe8d7f65e | 493ac26ce835200f4844e78d8319156eae5b21f4 | /flow_simulation/ideal_flow/processor3/0.05/nut | 2a4dfa8a893d77548410d9c16a50d73fc6fa8b5a | [] | no_license | mohan-padmanabha/worm_project | 46f65090b06a2659a49b77cbde3844410c978954 | 7a39f9384034e381d5f71191122457a740de3ff0 | refs/heads/master | 2022-12-14T14:41:21.237400 | 2020-08-21T13:33:10 | 2020-08-21T13:33:10 | 289,277,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,088 | nut | /*--------------------------------*- 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.05";
object nut;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -1 0 0 0 0];
internalField nonuniform List<scalar>
1431
(
0.00128523
0.00111672
0.000742272
0.000765825
0.000940049
0.000974595
0.000756736
0.00254321
0.000901981
0.000623496
0.00185377
0.00172226
0.000975543
0.00114649
0.000814373
0.000759376
0.000766187
0.000794677
0.000781385
0.000859755
0.00227427
0.00109388
0.00102291
0.0012414
0.000908252
0.00111883
0.0016969
0.000861086
0.000353463
0.000521694
0.000902351
0.00085585
0.000953963
0.000999846
0.000913977
0.000876436
0.000878396
0.000782904
0.00062203
0.000770068
0.00085074
0.000868864
0.00105373
0.000855913
0.000756269
0.000784628
0.000844136
0.00156987
0.000845998
0.000869029
0.00116936
0.000826705
0.00110413
0.00211975
0.000978286
0.00105375
0.000684162
0.00200926
0.000829749
0.000572563
0.00073307
0.000721751
0.000609635
0.000677849
0.000483861
0.000489043
0.000603025
0.000627435
0.000577531
0.000577118
0.00176514
0.000836366
0.000641261
0.00076908
0.000818547
0.000520582
0.000549679
0.000601515
0.000722514
0.000616954
0.000730353
0.000562029
0.00111538
0.000953193
0.000862112
0.000835628
0.000606116
0.00116943
0.0011649
0.00122523
0.000802896
0.000905083
0.000836168
0.000839845
0.00091556
0.000422165
0.00229087
0.00131431
0.000842145
0.000659125
0.00131791
0.00080189
0.000836991
0.000819625
0.000687966
0.00104187
0.000857303
0.00149933
0.00102958
0.000863694
0.000747039
0.0009243
0.00102516
0.000882652
0.00103104
0.000731004
0.000883301
0.000717754
0.000627984
0.000543061
0.000545222
0.000704179
0.00121912
0.000629268
0.00114711
0.000614372
0.000646588
0.00101335
0.000868382
0.000753574
0.000574039
0.000509248
0.000852643
0.000666195
0.000827864
0.000935738
0.000866743
0.000916736
0.00128208
0.000536975
0.000632732
0.00104123
0.000647499
0.0004671
0.00125216
0.000930174
0.000600125
0.00118588
0.00077724
0.000606773
0.000812142
0.000673024
0.000842294
0.000669396
0.00103814
0.000884999
0.00107407
0.00122502
0.00119789
0.00085889
0.00152717
0.000904958
0.000626549
0.000748811
0.00129753
0.00101882
0.000859924
0.000959941
0.000854229
0.00121342
0.001413
0.000990719
0.000781516
0.0012182
0.00119978
0.00106832
0.00083033
0.000927541
0.00109981
0.000909117
0.000505803
0.000751937
0.00125354
0.00143479
0.000939226
0.000531433
0.000787299
0.00124599
0.00103584
0.00102534
0.00119451
0.00101338
0.00097515
0.00172141
0.00062422
0.00119448
0.00134277
0.000929123
0.000697147
0.00115647
0.00122989
0.000669935
0.00171905
0.00066443
0.000981891
0.00113467
0.0011177
0.000694374
0.00121423
0.00121334
0.00103736
0.000547396
0.000925088
0.00108136
0.00111633
0.000958795
0.000994782
0.000953037
0.00093754
0.00168991
0.000926348
0.00129906
0.00117584
0.000714842
0.00106114
0.0012791
0.00171551
0.00126007
0.000823985
0.00140704
0.00175858
0.00093158
0.00122009
0.000919657
0.000868447
0.00140929
0.000996133
0.00124811
0.00117226
0.0010773
0.000873434
0.000971503
0.00123466
0.001225
0.00105391
0.000903874
0.00130762
0.00165314
0.000923511
0.000872361
0.00110346
0.00135414
0.000857011
0.000858423
0.0011686
0.000896117
0.000855788
0.00133759
0.00143937
0.00101179
0.00107416
0.00123253
0.00102097
0.000807281
0.00110143
0.00187947
0.000887675
0.00215605
0.00152562
0.00046764
0.00120471
0.000995384
0.00103213
0.000954886
0.00153025
0.000753483
0.00150022
0.00172039
0.000498476
0.000627435
0.00093057
0.000886615
0.000930999
0.00113767
0.000904391
0.00129022
0.000882781
0.00137427
0.00084533
0.00123702
0.000451664
0.000883846
0.00132327
0.000966337
0.00130202
0.000725301
0.00089044
0.000595098
0.00128143
0.000538104
0.0010742
0.000517669
0.000978641
0.00113145
0.00163625
0.000854768
0.00125509
0.0010173
0.000873693
0.00116393
0.00121869
0.000556836
0.000596607
0.000735092
0.000897316
0.00130743
0.000916524
0.000938098
0.0008941
0.00241543
0.00118214
0.00126104
0.000653676
0.00100271
0.000914695
0.000589447
0.000498491
0.000886722
0.00188966
0.000835412
0.000655601
0.00086507
0.000878627
0.000999342
0.000866499
0.00109226
0.000932193
0.00138484
0.000923476
0.000695781
0.000523379
0.00106641
0.00124077
0.000912275
0.00094341
0.0014766
0.00112123
0.00142828
0.0011367
0.00105411
0.00103771
0.000874669
0.0011534
0.0010144
0.000875584
0.000781963
0.00141366
0.000972623
0.00123957
0.000869081
0.00110107
0.000518554
0.000599818
0.000935803
0.000875843
0.00122223
0.00087581
0.00151039
0.0006617
0.00113445
0.00171702
0.000955431
0.00120861
0.00100775
0.000952298
0.00162542
0.00111394
0.000675587
0.00109674
0.0017081
0.000902546
0.000941022
0.000881213
0.000847849
0.00200916
0.000954689
0.000978348
0.00102575
0.000936492
0.000985146
0.000883494
0.000926453
0.000920481
0.000853288
0.00148298
0.00107561
0.000895523
0.000891231
0.000865027
0.000941189
0.00102394
0.000973245
0.00138986
0.000907056
0.000932809
0.000907459
0.000984455
0.000488039
0.000876756
0.000914084
0.00109154
0.000907317
0.000920277
0.000932991
0.00102991
0.000854535
0.000967473
0.000447164
0.000943848
0.000924684
0.000912897
0.00092484
0.00113587
0.000974972
0.000926164
0.000909784
0.000942219
0.000944646
0.000966804
0.00119211
0.000909338
0.000896757
0.000890573
0.000891609
0.000890263
0.000900136
0.000904864
0.000900931
0.000909362
0.000902818
0.000882363
0.00137622
0.00087776
0.000877912
0.000876849
0.000884171
0.000946691
0.000928971
0.00121662
0.00104283
0.00100499
0.000882367
0.000917688
0.000918045
0.000934403
0.000880416
0.00108182
0.00143562
0.000960488
0.000875904
0.00107904
0.000876906
0.00144313
0.000896969
0.000889137
0.000891592
0.000876078
0.00146325
0.000897961
0.00149474
0.000870461
0.000868531
0.000873493
0.000974447
0.00131958
0.00133292
0.000923629
0.000877914
0.000899534
0.000863551
0.000956154
0.000948361
0.00135551
0.000886853
0.000917873
0.000931533
0.000875703
0.000875518
0.000880433
0.000894813
0.00141699
0.000874707
0.000890232
0.000929943
0.000903093
0.000883584
0.000917541
0.00146259
0.000869716
0.000871105
0.000826189
0.00103116
0.0009723
0.000467603
0.00146813
0.00138501
0.000874883
0.000911241
0.00087105
0.000959596
0.000951941
0.000941942
0.000947203
0.000924577
0.00045967
0.000906437
0.000912408
0.000981526
0.000951518
0.00141506
0.00082079
0.000933633
0.00100976
0.000850133
0.00110072
0.000876677
0.00150244
0.000753524
0.000882705
0.000436209
0.0012714
0.00115755
0.00111513
0.00103146
0.000896529
0.00106771
0.00114268
0.000690323
0.00112161
0.00088771
0.000926223
0.000596639
0.00105319
0.00103035
0.000878697
0.0010279
0.00109415
0.000663075
0.000907368
0.000893935
0.000990934
0.000455514
0.000977785
0.000917186
0.000826878
0.00104667
0.000874798
0.000844199
0.000673804
0.00245679
0.000894796
0.00152224
0.00129101
0.00094153
0.0027198
0.000718452
0.000858314
0.000731362
0.000952836
0.000914929
0.000948009
0.00144456
0.000913677
0.000988652
0.000445894
0.000973552
0.000883908
0.000662666
0.000931815
0.000905876
0.000951481
0.0013283
0.000806548
0.000972434
0.00099134
0.001017
0.0011454
0.0010994
0.000491629
0.00113242
0.000958657
0.000594792
0.00118298
0.00103845
0.000939077
0.000890846
0.000928451
0.000960087
0.00129358
0.00121075
0.000702834
0.00114287
0.000912345
0.00108778
0.00108138
0.000911646
0.00111857
0.0010724
0.000786298
0.000883577
0.000879713
0.00083248
0.000919658
0.000931797
0.000953277
0.000914771
0.0008221
0.000861875
0.00112133
0.000909128
0.0010978
0.00125039
0.000469443
0.000911111
0.00108909
0.00109366
0.000892714
0.00108275
0.00116397
0.0010439
0.00113195
0.00120187
0.000502873
0.000917015
0.000945103
0.000984885
0.00194005
0.000901973
0.000839203
0.00120402
0.000874554
0.00135073
0.000880405
0.000913986
0.00061212
0.0012368
0.00102165
0.00091218
0.00147377
0.00104833
0.000994777
0.000885484
0.000624714
0.00102246
0.000866344
0.000913359
0.000976209
0.00117045
0.00109259
0.00132878
0.00151595
0.000889602
0.00105068
0.00099235
0.000889471
0.00104289
0.00105673
0.00113486
0.00116562
0.000854282
0.000926722
0.00101093
0.000689189
0.000903855
0.00106476
0.000807628
0.000693345
0.00102611
0.0008454
0.000996458
0.00105839
0.00092765
0.000977386
0.000682485
0.000780034
0.000785986
0.000948077
0.000901139
0.000885945
0.000400723
0.00118426
0.00100148
0.00102414
0.000394776
0.000367719
0.00088794
0.000448349
0.000889294
0.000347208
0.00135938
0.00041532
0.000957807
0.000949004
0.000384763
0.000636125
0.000706622
0.000599875
0.00042947
0.00110459
0.000913289
0.00100978
0.000613649
0.00163079
0.000804931
0.000786422
0.000986975
0.000938595
0.000833554
0.000888306
0.000839949
0.0011253
0.00112279
0.00133033
0.00100802
0.00070362
0.000871869
0.00142147
0.000950124
0.00147328
0.00196363
0.000874323
0.00117058
0.00100469
0.000889349
0.00114371
0.00112946
0.000995435
0.000473295
0.000670087
0.000873816
0.000421416
0.00104841
0.000920573
0.000871589
0.000932285
0.000996914
0.00101357
0.000871041
0.000948425
0.000897847
0.00110629
0.00119427
0.000875008
0.000882638
0.00124111
0.000944157
0.000952861
0.00107463
0.00100174
0.000440299
0.00136435
0.00128686
0.00127111
0.00094478
0.000998995
0.000879801
0.000839943
0.000827456
0.000909544
0.00102057
0.00094732
0.00110275
0.000919163
0.000962337
0.000934527
0.00111883
0.00036362
0.00112477
0.000885206
0.00111076
0.00097005
0.000782398
0.000990568
0.000910293
0.00040724
0.00155444
0.000915082
0.00105919
0.000803287
0.00101262
0.00101083
0.00103608
0.00105169
0.000887794
0.00109821
0.000339367
0.000873233
0.0015773
0.000874223
0.00101194
0.000821438
0.00104984
0.0010273
0.000918609
0.00093143
0.00258869
0.0011447
0.000954357
0.000879311
0.000895784
0.00207673
0.000670995
0.00127988
0.00109276
0.000892718
0.00146676
0.000972565
0.00089416
0.000882443
0.000860782
0.00084014
0.00188653
0.000950425
0.000895747
0.000410413
0.000424164
0.000913127
0.00105951
0.000914413
0.000827426
0.000895208
0.000498773
0.000634839
0.000814748
0.0010163
0.00207537
0.00119514
0.000881987
0.000939194
0.00107922
0.0010087
0.000912086
0.000885476
0.00126709
0.000917431
0.00141911
0.000841899
0.00197626
0.00139878
0.00148539
0.000686965
0.00110035
0.00117723
0.00138738
0.00068912
0.000692392
0.000799124
0.00133487
0.000851187
0.000845881
0.00113905
0.0009622
0.00108163
0.00100141
0.00091226
0.000898252
0.00093215
0.000797053
0.00139101
0.000906639
0.00090548
0.00245396
0.000889004
0.000532876
0.00105914
0.000869112
0.000791721
0.000718296
0.000908112
0.000819218
0.0015526
0.000845751
0.000849465
0.00175514
0.0020335
0.00180688
0.00210707
0.000566196
0.000381334
0.000355291
0.000301798
0.000323392
0.000640048
0.000388607
0.000333349
0.000392236
0.000353727
0.000359745
0.000499788
0.000694096
0.000408899
0.00047712
0.000477175
0.000438527
0.000378051
0.000367895
0.000446234
0.000360727
0.00037017
0.00044032
0.000388651
0.000941643
0.00148946
0.000876629
0.00120513
0.00094178
0.00104443
0.000872944
0.0015401
0.000645275
0.00114004
0.00113406
0.00101043
0.000953877
0.00193019
0.000915205
0.000893645
0.00150376
0.000966784
0.000931126
0.000974445
0.000633953
0.00153051
0.00101138
0.000401155
0.000913182
0.000974638
0.000476895
0.000875493
0.00115776
0.00118455
0.0010761
0.000923194
0.000968429
0.000912045
0.0011166
0.00156379
0.00091754
0.000769001
0.000878828
0.000866022
0.000971668
0.000388165
0.000513465
0.00115574
0.00108746
0.00100097
0.00115568
0.000924782
0.000938495
0.000436927
0.00107868
0.000912635
0.0010177
0.000762469
0.000871494
0.000972967
0.000876166
0.000378077
0.000950575
0.00039629
0.0010158
0.0015872
0.000561029
0.000907665
0.000864541
0.000869315
0.000983488
0.000923121
0.00234179
0.000904816
0.00127917
0.000747586
0.00251368
0.000893828
0.00134602
0.000869206
0.000819926
0.000873615
0.00101647
0.000878902
0.000929598
0.00139751
0.00225113
0.00115686
0.000391298
0.000898679
0.000868907
0.00151558
0.00093161
0.00080928
0.00155928
0.00106757
0.000936885
0.00173915
0.000931028
0.00075762
0.000877184
0.000874203
0.00087984
0.000931978
0.00139706
0.00117103
0.000794983
0.000909933
0.00112499
0.00102312
0.000776428
0.000921029
0.000992381
0.000922041
0.0023739
0.000671218
0.000319378
0.000505916
0.00076638
0.000888818
0.0020198
0.000499924
0.00101953
0.000950012
0.00153738
0.00126816
0.000878592
0.000861091
0.000853435
0.000907562
0.000520254
0.000990359
0.00088984
0.000980728
0.000385693
0.00102175
0.000373499
0.000901693
0.00123514
0.000768831
0.000877818
0.00188447
0.00156502
0.000889494
0.00109016
0.000909241
0.000785785
0.000895915
0.000528378
0.000874214
0.000696477
0.000912916
0.000882535
0.000949267
0.000985654
0.000889949
0.00157276
0.000816726
0.000824926
0.000919392
0.000647992
0.00090291
0.000723047
0.000880814
0.000894997
0.00061899
0.000397197
0.000539168
0.000524226
0.000520169
0.000740935
0.000680368
0.000672389
0.000564329
0.000702186
0.000403367
0.000340251
0.000306568
0.000367902
0.000278092
0.000316079
0.000999867
0.000844845
0.000894502
0.00111602
0.000910931
0.000480234
0.000843384
0.000946643
0.000861091
0.000912662
0.000941326
0.00085698
0.00098685
0.000795342
0.00040542
0.00111774
0.000999188
0.000963462
0.000917173
0.000797987
0.000914101
0.00162091
0.000856965
0.000970531
0.00213136
0.00100718
0.00103454
0.00126964
0.00106715
0.000902291
0.00102623
0.000886465
0.000880611
0.000884591
0.000634201
0.000978912
0.000872942
0.000410624
0.00113873
0.000891553
0.000703864
0.000888519
0.000876955
0.00086868
0.00111901
0.000879539
0.000860574
0.00093605
0.00117495
0.00168636
0.000831713
0.00085331
0.00102708
0.000837256
0.00107196
0.00109904
0.000866173
0.00129423
0.00137974
0.00055383
0.000911957
0.000962811
0.00129775
0.000891074
0.000439399
0.00141575
0.00106306
0.000861568
0.000894619
0.00113588
0.000948903
0.00130057
0.000868109
0.000982392
0.00122891
0.000999329
0.00126473
0.000815008
0.000701242
0.00108685
0.000876133
0.000841203
0.000851241
0.00146042
0.000952978
0.000823477
0.00128112
0.00101868
0.00109465
0.000892969
0.000765472
0.00115732
0.00200691
0.00148936
0.000912206
0.000875864
0.000874665
0.00115681
0.000837792
0.000888643
0.000537178
0.000691585
0.000892086
0.000885716
0.00181445
0.0011647
0.00116516
0.000898202
0.00088211
0.000908045
0.00194425
0.00105999
0.00109738
0.000919685
0.000826962
0.00086784
0.000895885
0.000892602
0.00101471
0.00147938
0.00118578
0.00120126
0.000899406
0.00116156
0.000955054
0.000889255
0.00110271
0.000399398
0.00106329
0.000770537
0.000894835
0.00104921
0.000910783
0.000950143
0.000998273
0.00072251
0.000857308
0.000755459
0.000839236
0.000914895
0.000538978
0.000944155
0.00177679
0.00113742
0.000730432
0.000973383
0.00154996
0.000944662
0.000933706
0.000901134
0.00117129
0.000773277
0.000659199
0.000942575
0.000960977
0.00123224
0.000935968
0.0012223
0.000931287
0.000879246
0.000910009
0.00150881
0.00090534
0.00152836
0.000950815
0.00121221
0.000907511
0.000910411
0.00117494
0.000977634
0.000790477
0.00101951
0.000886727
0.000975675
0.00277493
0.000914481
0.000921113
0.000859913
0.000860285
0.00149838
0.000937638
0.0013129
0.000544672
0.000895327
0.000884348
0.001194
0.00101467
0.00092117
0.000908515
0.000963806
0.00142835
0.00105773
0.000297281
0.000480651
0.0013623
0.00114872
0.000829054
0.00113081
0.00102254
0.00196749
0.000964894
0.000873572
0.000946841
0.000896477
0.00164553
0.00146183
0.00157489
0.000897337
0.00205418
0.00108668
0.000872485
0.000874
0.00172991
0.000942794
0.000891785
0.000905354
0.000903006
0.000781111
0.000762274
0.00202955
0.000739993
0.00085431
0.000668445
0.00209011
0.000360369
0.00236028
0.00121903
0.000931777
0.00113869
0.00160634
0.00200093
0.000879896
0.000729251
0.000700729
0.00100133
0.000833255
0.000957637
0.00102498
0.00147803
0.000578389
0.000919276
0.000426379
0.00197664
0.00039054
0.000450726
0.000381122
0.00100306
0.000877349
0.00114631
0.000896313
0.00193518
0.000899263
0.000643158
0.000962913
0.00101239
0.000839048
0.00118634
0.00107515
0.000898999
0.000870492
0.001139
0.00201312
0.000861927
0.000930864
0.00105847
0.000926748
0.00126944
0.000830417
0.00119162
0.000901034
0.000904634
0.000727779
0.000850096
0.000834726
0.00121492
0.000821839
0.00047004
0.000711145
0.00130288
0.000896404
0.00087557
0.000893701
0.000974004
0.000828206
0.00103349
0.000971365
0.000998403
0.000504324
0.000397187
0.00115815
0.00115097
0.000683326
0.000906187
0.000836797
0.000875373
0.000875045
0.000787266
0.000849225
0.00083791
0.000844979
0.000822408
0.000965762
0.000899523
0.00137828
0.000647655
0.00113769
0.000931092
0.000772608
0.00121801
0.000907382
0.000897002
0.00112831
0.000665008
0.000423437
0.00217659
0.000609872
0.000870154
0.000512525
0.000500288
0.000481104
0.000649983
0.000527189
0.000623082
0.000425553
0.00102395
0.00125478
0.000771314
0.000845592
0.00058303
0.000607981
0.0004414
0.000627834
0.000674927
0.000447982
0.000431477
0.00076955
0.00065056
0.00047529
0.000489913
0.000716771
0.000789157
0.000456812
0.000513217
)
;
boundaryField
{
frontAndBack
{
type empty;
}
wallOuter
{
type nutkWallFunction;
Cmu 0.09;
kappa 0.41;
E 9.8;
value nonuniform List<scalar>
96
(
4.40692e-05
6.41906e-05
5.36537e-05
8.07414e-05
8.11359e-05
8.00302e-05
5.08474e-05
5.0139e-05
4.66591e-05
5.5918e-05
4.39634e-05
5.22863e-05
4.88719e-05
8.2588e-05
5.38309e-05
5.86723e-05
7.87191e-05
5.21617e-05
4.61691e-05
5.15904e-05
4.29343e-05
5.18609e-05
5.24385e-05
6.15017e-05
7.47937e-05
6.76547e-05
4.84452e-05
4.49584e-05
3.76545e-05
4.06387e-05
7.6266e-05
4.93943e-05
4.13335e-05
4.85991e-05
4.38224e-05
4.49932e-05
6.00714e-05
8.26733e-05
5.1656e-05
5.79394e-05
5.77015e-05
5.56694e-05
4.79763e-05
4.65659e-05
5.67563e-05
4.5502e-05
4.65589e-05
5.60224e-05
4.87445e-05
5.01496e-05
4.84089e-05
6.36137e-05
4.68172e-05
5.03419e-05
6.64511e-05
4.86847e-05
9.03709e-05
3.97519e-05
6.20632e-05
6.24116e-05
6.3822e-05
4.88524e-05
4.69989e-05
8.95184e-05
7.81577e-05
8.64565e-05
7.47698e-05
4.90855e-05
6.58262e-05
6.40182e-05
6.34396e-05
8.85302e-05
8.15103e-05
8.05549e-05
6.84288e-05
8.39658e-05
5.07613e-05
4.24417e-05
3.79497e-05
4.61377e-05
3.4196e-05
3.92405e-05
6.03167e-05
5.16075e-05
5.20793e-05
5.54765e-05
6.45384e-05
5.08592e-05
6.58741e-05
6.64899e-05
3.69359e-05
5.87391e-05
4.51643e-05
8.50796e-05
5.07229e-05
4.81269e-05
)
;
}
inlet
{
type calculated;
value nonuniform 0();
}
outlet
{
type calculated;
value nonuniform List<scalar> 9(0.00151039 0.00200916 0.00111857 0.00124111 0.00258869 0.0023739 0.000768831 0.00168636 0.00102708);
}
wallInner
{
type nutkWallFunction;
Cmu 0.09;
kappa 0.41;
E 9.8;
value nonuniform List<scalar>
126
(
9.54892e-05
7.37386e-05
9.25386e-05
9.07424e-05
7.73905e-05
8.64973e-05
6.15555e-05
6.15897e-05
7.65434e-05
7.91108e-05
7.42388e-05
7.3533e-05
0.000182347
0.000101351
8.07492e-05
9.77547e-05
0.000100377
6.73358e-05
7.07645e-05
7.69527e-05
9.14614e-05
7.9325e-05
8.98754e-05
7.23128e-05
8.43646e-05
9.27746e-05
0.000105009
9.02447e-05
7.94376e-05
6.96747e-05
6.9767e-05
8.51202e-05
0.000129461
7.93626e-05
0.000130233
7.84122e-05
8.28301e-05
7.2554e-05
6.58425e-05
6.87653e-05
8.04559e-05
7.77163e-05
6.0363e-05
7.66e-05
7.76594e-05
8.59976e-05
8.44914e-05
0.000139191
6.40156e-05
6.54611e-05
9.54784e-05
7.88566e-05
0.000119818
5.85456e-05
6.16191e-05
7.8477e-05
5.8027e-05
0.000108958
7.28354e-05
6.43233e-05
6.6531e-05
7.12114e-05
7.55945e-05
9.30472e-05
7.56304e-05
6.43833e-05
7.89389e-05
8.47383e-05
6.71664e-05
0.000113697
6.43762e-05
7.22936e-05
6.00446e-05
5.56575e-05
5.85372e-05
5.72723e-05
5.66059e-05
8.63836e-05
7.29484e-05
8.1627e-05
5.74638e-05
8.35478e-05
5.56338e-05
8.05653e-05
6.24957e-05
7.18174e-05
8.5871e-05
5.82535e-05
6.38778e-05
7.39891e-05
7.57402e-05
7.72124e-05
7.26506e-05
5.63466e-05
6.46472e-05
8.73083e-05
5.51283e-05
0.000108117
5.05035e-05
5.73206e-05
7.6422e-05
5.14916e-05
7.79689e-05
6.53546e-05
6.39822e-05
6.13395e-05
6.75702e-05
5.3773e-05
0.000122168
0.000135308
9.79787e-05
0.000100178
7.29803e-05
5.66208e-05
7.76135e-05
8.23073e-05
5.70355e-05
5.55146e-05
9.34011e-05
7.83808e-05
6.11032e-05
6.26702e-05
8.15568e-05
8.91239e-05
5.86255e-05
6.34773e-05
)
;
}
procBoundary3to1
{
type processor;
value nonuniform List<scalar>
48
(
0.000880225
0.000817401
0.000842284
0.000882584
0.000886941
0.000812246
0.000817401
0.00108185
0.000895585
0.000955759
0.000955759
0.00088758
0.00088758
0.00087815
0.000893134
0.000872325
0.000875987
0.000873867
0.000875987
0.000878668
0.000878914
0.000894648
0.000878668
0.000886293
0.000985481
0.00095463
0.00094388
0.000894648
0.00100558
0.000959937
0.000959937
0.0010861
0.0010861
0.000895585
0.000894518
0.000934761
0.00101737
0.000985481
0.000882603
0.000724481
0.00087815
0.000960438
0.00093097
0.000878668
0.000911821
0.000412121
0.000818178
0.000878516
)
;
}
procBoundary3to2
{
type processor;
value nonuniform List<scalar>
29
(
0.000955113
0.000955113
0.00054681
0.000568732
0.000506286
0.000551867
0.000574461
0.000951559
0.000905396
0.000746567
0.000834332
0.000793948
0.000907709
0.000904742
0.000869743
0.000850116
0.000948692
0.000942573
0.000929997
0.000927039
0.000917576
0.000948692
0.000415841
0.000942573
0.000744823
0.000946739
0.000942573
0.000926366
0.000926366
)
;
}
}
// ************************************************************************* //
| |
2f5b6850ad251c9cfff27791175e266d6ffce01a | 9832855ae4486a3b776930f7ce73e128bdc02aca | /Po que mão/Po que mão.cpp | 29b22bb6d7ea5a36a4878eb7229b915522a081de | [] | no_license | glaucoacassio/NEPS | df2eee784bed6859e9db2ca99f6bc15d6e7f489d | 94b962df8420c022f2815d83ff2b7cb3df036255 | refs/heads/master | 2022-12-14T18:52:27.331802 | 2020-09-16T23:55:27 | 2020-09-16T23:55:27 | 288,892,166 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 504 | cpp | Po que mão.cpp | /**
* Author: @glaucoacassioc
* Created on 13.09.2020, 21:23:25
**/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;
#define INF 1000000000
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n;
vi v(3);
cin>>n;
for(int i=0; i<3; i++)
cin>>v[i];
sort(v.begin(), v.end());
int i = 0;
while(i < 3 && n >= v[i])
{
n -= v[i];
i++;
}
cout << i << endl;
return 0;
}
|
de593b9721e01dc6d4e15412e70c74787a946748 | 92747972b6bd8ad76c9951c9a4f44f4f61619071 | /src/scene/OrthoCamera.cpp | 7025eebcc137dac27b783e6b258b4fe66518edd7 | [] | no_license | cha63506/kocmoc-core | 729327bc14bfbb21684c97489e7d0ac7f67cc9e6 | 543f4f4b4975dfecf2e493760c32dcf76a2f08e7 | refs/heads/master | 2017-11-13T15:42:15.202802 | 2013-12-13T10:43:44 | 2013-12-13T10:43:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 984 | cpp | OrthoCamera.cpp | #include <kocmoc-core/scene/OrthoCamera.hpp>
#include <glm/gtc/matrix_transform.hpp>
using namespace kocmoc::core::scene;
using glm::vec3;
using glm::vec4;
using glm::mat4;
OrthoCamera::OrthoCamera(vec3 _focus, vec3 _direction, vec3 _upVector)
: focus(_focus)
, direction(_direction)
, upVector(glm::normalize(_upVector))
, width(1)
, height(1)
, depth(1)
{}
OrthoCamera::~OrthoCamera(void)
{
}
void OrthoCamera::updateMatrices()
{
vec3 s = glm::normalize(glm::cross(direction, upVector));
vec3 u = glm::normalize(glm::cross(s, direction));
mat4 untranslatedViewMatrix = mat4(vec4(s, 0), vec4(u, 0), vec4(direction, 0), vec4(0, 0, 0, 1.0f));
untranslatedViewMatrix = glm::transpose(untranslatedViewMatrix);
viewMatrix = glm::translate(untranslatedViewMatrix, -focus);
projectionMatrix = mat4(1/width, 0, 0, 0,
0, 1/height, 0, 0,
0, 0, 1/depth, 0,
0, 0, 0, 1);
}
void OrthoCamera::setFocus(vec3 _focus)
{
focus = _focus;
}
|
06be5a0d16fce62381ad43888024ea3be8a9f945 | 39cdb6ff35231538ef25c565181981ccf237cc30 | /SWEA/8993.cpp | e644df9019fbe8515e71d166f0ed44977905c86a | [] | no_license | dittoo8/algorithm_cpp | 51b35321f6cf16c8c1c259af746a9f35d5ba8b76 | d9cdda322d3658ffc07744e4080c71faeee6370c | refs/heads/master | 2023-08-03T14:49:08.808253 | 2021-02-16T04:13:53 | 2021-02-16T04:13:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 542 | cpp | 8993.cpp | #include <cstdio>
#include <queue>
using namespace std;
bool solve (long long n){
queue<long long> arr;
while(n>1){
if (n%2==0){
n/=2;
}else {
arr.push(n);
if (n == arr.front()) return false;
n = 3*n+3;
}
}
return true;
}
int main(){
int tc;
scanf("%d",&tc);
long long n;
for(int t=1;t<=tc;t++){
scanf("%lld",&n);
if (solve(n)){
printf("#%d YES\n",t);
} else printf("#%d NO\n",t);
}
return 0;
} |
2a1fe75f496db2533cd290ff2cd5913848c29822 | c0459046ed85fb919cdb4114cfc49f4db005e3b2 | /arduino_control/HelloWorld/subscribe_Hello_World/subscribe_Hello_World.ino | 58ffb05ab892cda4a1acb04d11a2859aefa1d562 | [] | no_license | fschalling/JuRP_HK | 4d3b2d2deb6c4c6e95118727bc393135a27a751a | 4e9d643addbfeb3359f6a7a10413c66d980f257a | refs/heads/master | 2020-03-30T19:37:03.878203 | 2018-12-10T16:16:44 | 2018-12-10T16:16:44 | 151,550,611 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 500 | ino | subscribe_Hello_World.ino | #include <ros.h>
#include <std_msgs/String.h>
#include <std_msgs/Empty.h>
ros::NodeHandle nh;
void messageCb( const std_msgs::Empty& toggle_msg){
}
std_msgs::String str_msg;
ros::Subscriber<std_msgs::Empty> sub("chatter", &messageCb);
ros::Publisher chatter_2("chatter_2", &str_msg);
char hello[13] = "hello world!";
void setup()
{
nh.initNode();
nh.advertise(chatter_2);
}
void loop()
{
str_msg.data = hello;
chatter_2.publish( &str_msg );
nh.spinOnce();
delay(1000);
}
|
e464270ccdc297242c47ab7160b4c95aa0c24abd | 2fe11f0bdb260d3cfeca15c73b3131db7e58db63 | /Codeforces Round #693/693_c.cpp | 097472326045fa9be15100968c02b96ea0861eba | [] | no_license | Saumya-Agarwal29/codeforces | 68a3ccd6a11b4b2e83ea6c2ec5f0cbc407573d66 | 20a379bfb3ed35647c5a314c50e770030b49345c | refs/heads/main | 2023-08-13T09:32:54.502303 | 2021-10-04T23:02:32 | 2021-10-04T23:02:32 | 413,606,296 | 0 | 0 | null | 2021-10-04T22:55:25 | 2021-10-04T22:55:25 | null | UTF-8 | C++ | false | false | 662 | cpp | 693_c.cpp | /*------------------Honey, you should see me in a crown--------------------*/
#include<bits/stdc++.h>
#define FAST cin.tie(0);cout.tie(0);ios_base::sync_with_stdio(0)
#define lli(n) long long n; cin>>n;
#define li(n) long n; cin>>n;
#define inti(n) int n;cin>>n;
#define CC int test;\
cin>>test;\
while(test--)
using namespace std;
/*------------Every fairy tale needs a good old-fashioned villain----------------*/
int main()
{
FAST;
CC
{
inti(n);
long a[n+1],m=0;
for(int i=1;i<=n;i++)
cin>>a[i];
for(int i=n;i>0;i--)
{
if(a[i]+i<=n)
a[i]+=a[a[i]+i];
m=max(m,a[i]);
}cout<<m<<'\n';
}
return 0;
}
|
619fa3374694210040e87fe025acc4b7fc78b8a6 | 73bd731e6e755378264edc7a7b5d16132d023b6a | /CodeForces/CodeForces - 1061B.cpp | 867d105fee44b1fbad5eedbfba1d7866e051b0ad | [] | no_license | IHR57/Competitive-Programming | 375e8112f7959ebeb2a1ed6a0613beec32ce84a5 | 5bc80359da3c0e5ada614a901abecbb6c8ce21a4 | refs/heads/master | 2023-01-24T01:33:02.672131 | 2023-01-22T14:34:31 | 2023-01-22T14:34:31 | 163,381,483 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 718 | cpp | CodeForces - 1061B.cpp | //Problem ID: CodeForces - 1061B (Views Matter)
//Programmer: IQBAL HOSSAIN Description: Greedy
//Date: 11/02/19
#include <bits/stdc++.h>
#define MAX 100005
using namespace std;
typedef long long ll;
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n, m, arr[MAX], Max = -1;
ll tot = 0;
cin>>n>>m;
for(int i = 0; i < n; i++){
cin>>arr[i];
tot += (ll) arr[i];
}
if(n == 1){
cout<<0<<endl;
return 0;
}
sort(arr, arr + n);
int last = 0;
ll sum = n;
for(int i = 0; i < n; i++){
if(arr[i] > last)
last++;
}
sum += (ll) (arr[n-1] - last);
cout<<(tot - sum)<<endl;
return 0;
}
|
0fd72e6b076a8563fc058c65737f88aef8adb3e2 | fafce52a38479e8391173f58d76896afcba07847 | /uppdev/sic.oold/Sic.h | a2d3e774443437a57a5d957899fd9d7efdea83e1 | [] | no_license | Sly14/upp-mirror | 253acac2ec86ad3a3f825679a871391810631e61 | ed9bc6028a6eed422b7daa21139a5e7cbb5f1fb7 | refs/heads/master | 2020-05-17T08:25:56.142366 | 2015-08-24T18:08:09 | 2015-08-24T18:08:09 | 41,750,819 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,063 | h | Sic.h | #include <Core/Core.h>
enum { SV_VOID, SV_NUMBER, SV_STRING, SV_MAP, SV_LAMBDA };
struct SValMap;
struct SLambda;
class SVal : Moveable<SVal> {
struct SValMap;
int type;
String string;
double number;
int ipos;
struct SLambdaRef;
union {
SValMap *map;
SLambdaRef *lambda;
};
void Free();
void Assign(const SVal& s);
public:
int GetType() const { return type; }
bool IsVoid() const { return type == SV_VOID; }
bool IsNumber() const { return type == SV_NUMBER; }
bool IsString() const { return type == SV_STRING; }
bool IsMap() const { return type == SV_MAP; }
bool IsLambda() const { return type == SV_LAMBDA; }
double GetNumber() const { ASSERT(IsNumber()); return number; }
const String& GetString() const { ASSERT(IsString()); return string; }
String& GetString() { ASSERT(IsString()); return string; }
const SLambda& GetLambda() const;
const ArrayMap<SVal, SVal>& GetMap() const;
unsigned GetHashValue() const;
bool operator==(const SVal& a) const;
bool operator!=(const SVal& a) const { return !(*this == a); }
void operator=(const Nuller&);
void operator=(double d);
void operator=(const String& s);
SLambda& CreateLambda();
void SetMap();
SVal& Set(SVal key);
SVal& Add();
void operator=(const SVal& s);
String Dump() const;
SVal();
SVal(const SVal& src);
SVal(const Nuller& s);
SVal(const String& s);
SVal(double n);
~SVal();
};
inline unsigned GetHashValue(const SVal& v)
{
return v.GetHashValue();
}
bool IsTrue(const SVal& a);
struct Sic : public CParser {
struct SRVal : Moveable<SRVal> {
SVal *lvalue;
SVal rvalue;
operator const SVal&() { return lvalue ? *lvalue : rvalue; }
const SVal *operator->() const { return lvalue ? lvalue : &rvalue; }
const SVal& operator~() const { return lvalue ? *lvalue : rvalue; }
SRVal() { lvalue = NULL; }
SRVal(const SVal& a) { rvalue = a; lvalue = NULL; }
SRVal(double d) { rvalue = d; lvalue = NULL; }
SRVal(const String& s) { rvalue = s; lvalue = NULL; }
};
struct Var : Moveable<Var> {
SVal *ref;
SVal var;
Var() { ref = NULL; }
};
ArrayMap<String, SVal>& global;
SVal *self;
ArrayMap<String, Var> var;
int loop;
bool no_break, no_return;
SVal return_value;
int stack_level;
int DoCompare(const SVal& a);
SVal ReadLambda();
String ReadName();
SVal ExecuteLambda(const String& id, SVal lambda, SVal *self, Vector<SRVal>& arg);
SRVal Operator(Sic::SRVal a, Sic::SRVal b, const char *oper, const char *op,
bool sym = false);
SRVal Term();
SRVal Unary();
SRVal Mul();
SRVal Add();
SRVal Shift();
SRVal Compare();
SRVal Equal();
SRVal BinAnd();
SRVal BinXor();
SRVal BinOr();
SRVal And();
SRVal Or();
SRVal Cond();
SRVal Assign();
SRVal Exp();
void SkipTerm();
void SkipStatement();
void SkipExp();
bool PCond();
void FinishSwitch();
void DoStatement();
void Run();
Sic(ArrayMap<String, SVal>& global, const char *s) : global(global), CParser(s)
{ stack_level = 0; self = NULL; }
};
struct SLambda {
Vector<String> arg;
Vector<bool> ref;
String code;
SVal (*escape)(Sic& sic, Vector<Sic::SRVal>& var);
SLambda() { escape = NULL; }
};
void Escape(ArrayMap<String, SVal>& global,
const char *function,
SVal (*fn)(Sic& sic, Vector<Sic::SRVal>& arg));
void Scan(ArrayMap<String, SVal>& global, const char *file);
void StdLib(ArrayMap<String, SVal>& global);
SVal Execute(ArrayMap<String, SVal>& global, const char *fnname, const Vector<SVal>& arg);
SVal Execute(ArrayMap<String, SVal>& global, const char *fnname);
|
928703702a62b904bf50a806a093dece85f8ab8d | 436623ee85c9d9444d700b56f2729b12b9f2c659 | /src/tools/ecode/plugins/lsp/lspclientserver.hpp | 431bf555462f5a0f7098ff7d456683e9b77ca78b | [
"MIT"
] | permissive | SpartanJ/eepp | 0bd271b33058ef119f5c34460ed94e44df882a25 | 9f64a2149f3a0842ced34b8b981ffe3a8efc6d13 | refs/heads/develop | 2023-09-01T01:17:30.155540 | 2023-08-27T20:58:19 | 2023-08-27T20:58:19 | 125,767,856 | 341 | 27 | MIT | 2023-04-01T20:10:26 | 2018-03-18T21:11:21 | C++ | UTF-8 | C++ | false | false | 10,391 | hpp | lspclientserver.hpp | #ifndef ECODE_LSPCLIENTSERVER_HPP
#define ECODE_LSPCLIENTSERVER_HPP
#include "../pluginmanager.hpp"
#include "lspdefinition.hpp"
#include "lspdocumentclient.hpp"
#include "lspprotocol.hpp"
#include <atomic>
#include <eepp/network/tcpsocket.hpp>
#include <eepp/system/process.hpp>
#include <eepp/ui/doc/textdocument.hpp>
#include <eepp/ui/doc/undostack.hpp>
#include <eepp/ui/uicodeeditor.hpp>
#include <eepp/ui/uipopupmenu.hpp>
#include <memory>
#include <nlohmann/json.hpp>
#include <queue>
using json = nlohmann::json;
using namespace EE;
using namespace EE::System;
using namespace EE::UI;
using namespace EE::UI::Doc;
namespace ecode {
class LSPClientServerManager;
class LSPClientServer {
public:
static PluginIDType getID( const json& json );
using IdType = PluginIDType;
template <typename T> using ReplyHandler = std::function<void( const IdType& id, const T& )>;
template <typename T> using WReplyHandler = std::function<void( const IdType& id, T&& )>;
using JsonReplyHandler = ReplyHandler<json>;
using CodeActionHandler = ReplyHandler<std::vector<LSPCodeAction>>;
using CodeLensHandler = ReplyHandler<std::vector<LSPCodeLens>>;
using HoverHandler = ReplyHandler<LSPHover>;
using CompletionHandler = ReplyHandler<LSPCompletionList>;
using SymbolInformationHandler = WReplyHandler<LSPSymbolInformationList>;
using SelectionRangeHandler = ReplyHandler<std::vector<std::shared_ptr<LSPSelectionRange>>>;
using SignatureHelpHandler = ReplyHandler<LSPSignatureHelp>;
using LocationHandler = ReplyHandler<std::vector<LSPLocation>>;
using TextEditArrayHandler = ReplyHandler<std::vector<LSPTextEdit>>;
using WorkspaceEditHandler = ReplyHandler<LSPWorkspaceEdit>;
using SemanticTokensDeltaHandler = ReplyHandler<LSPSemanticTokensDelta>;
class LSPRequestHandle : public PluginRequestHandle {
public:
void cancel() {
if ( server && mId.isValid() )
server->cancel( mId );
}
private:
friend class LSPClientServer;
LSPClientServer* server;
};
LSPClientServer( LSPClientServerManager* manager, const String::HashType& id,
const LSPDefinition& lsp, const std::string& rootPath,
const std::vector<std::string>& languagesSupported );
~LSPClientServer();
bool start();
bool registerDoc( const std::shared_ptr<TextDocument>& doc );
bool isRunning();
const LSPServerCapabilities& getCapabilities() const;
LSPClientServerManager* getManager() const;
const std::shared_ptr<ThreadPool>& getThreadPool() const;
LSPRequestHandle cancel( const PluginIDType& id );
LSPRequestHandle send( const json& msg, const JsonReplyHandler& h = nullptr,
const JsonReplyHandler& eh = nullptr );
void sendAsync( const json& msg, const JsonReplyHandler& h = nullptr,
const JsonReplyHandler& eh = nullptr );
const LSPDefinition& getDefinition() const { return mLSP; }
LSPRequestHandle documentSymbols( const URI& document, const JsonReplyHandler& h,
const JsonReplyHandler& eh );
LSPRequestHandle documentSymbols( const URI& document,
const WReplyHandler<LSPSymbolInformationList>& h,
const ReplyHandler<LSPResponseError>& eh = {} );
LSPRequestHandle documentSymbolsBroadcast( const URI& document );
LSPRequestHandle didOpen( const URI& document, const std::string& text, int version );
LSPRequestHandle didOpen( TextDocument* doc, int version );
LSPRequestHandle didSave( const URI& document, const std::string& text );
LSPRequestHandle didSave( TextDocument* doc );
LSPRequestHandle didClose( const URI& document );
LSPRequestHandle didChange( const URI& document, int version, const std::string& text,
const std::vector<DocumentContentChange>& change = {} );
LSPRequestHandle didChange( TextDocument* doc,
const std::vector<DocumentContentChange>& change = {} );
void queueDidChange( const URI& document, int version, const std::string& text,
const std::vector<DocumentContentChange>& change = {} );
void processDidChangeQueue();
void documentDefinition( const URI& document, const TextPosition& pos );
void documentDeclaration( const URI& document, const TextPosition& pos );
void documentTypeDefinition( const URI& document, const TextPosition& pos );
void documentImplementation( const URI& document, const TextPosition& pos );
bool hasDocument( TextDocument* doc ) const;
bool hasDocument( const URI& uri ) const;
bool hasDocuments() const;
LSPRequestHandle didChangeWorkspaceFolders( const std::vector<LSPWorkspaceFolder>& added,
const std::vector<LSPWorkspaceFolder>& removed,
bool async );
void publishDiagnostics( const json& msg );
void workDoneProgress( const LSPWorkDoneProgressParams& workDoneParams );
void getAndGoToLocation( const URI& document, const TextPosition& pos,
const std::string& search, const LocationHandler& h );
void getAndGoToLocation( const URI& document, const TextPosition& pos,
const std::string& search );
void switchSourceHeader( const URI& document );
void documentCodeAction( const URI& document, const TextRange& range,
const std::vector<std::string>& kinds,
const nlohmann::json& diagnostics, const JsonReplyHandler& h );
void documentCodeAction( const URI& document, const TextRange& range,
const std::vector<std::string>& kinds,
const nlohmann::json& diagnostics, const CodeActionHandler& h );
void documentCodeLens( const URI& document, const JsonReplyHandler& h );
void documentCodeLens( const URI& document, const CodeLensHandler& h );
void documentHover( const URI& document, const TextPosition& pos, const JsonReplyHandler& h );
void documentHover( const URI& document, const TextPosition& pos, const HoverHandler& h );
void documentReferences( const URI& document, const TextPosition& pos, bool decl,
const JsonReplyHandler& h );
void documentReferences( const URI& document, const TextPosition& pos, bool decl,
const LocationHandler& h );
LSPRequestHandle documentCompletion( const URI& document, const TextPosition& pos,
const JsonReplyHandler& h );
LSPRequestHandle documentCompletion( const URI& document, const TextPosition& pos,
const CompletionHandler& h );
void workspaceSymbol( const std::string& querySymbol, const JsonReplyHandler& h,
const size_t& limit = 100 );
void workspaceSymbol( const std::string& querySymbol, const SymbolInformationHandler& h,
const size_t& limit = 100 );
LSPRequestHandle selectionRange( const URI& document,
const std::vector<TextPosition>& positions,
const JsonReplyHandler& h );
LSPRequestHandle selectionRange( const URI& document,
const std::vector<TextPosition>& positions,
const SelectionRangeHandler& h );
void documentSemanticTokensFull( const URI& document, bool delta, const std::string& requestId,
const TextRange& range, const JsonReplyHandler& h );
void documentSemanticTokensFull( const URI& document, bool delta, const std::string& requestId,
const TextRange& range, const SemanticTokensDeltaHandler& h );
LSPRequestHandle signatureHelp( const URI& document, const TextPosition& pos,
const JsonReplyHandler& h );
LSPRequestHandle signatureHelp( const URI& document, const TextPosition& pos,
const SignatureHelpHandler& h );
LSPRequestHandle documentFormatting( const URI& document, const json& options,
const JsonReplyHandler& h );
LSPRequestHandle documentFormatting( const URI& document, const json& options,
const TextEditArrayHandler& h );
LSPRequestHandle documentRangeFormatting( const URI& document, const TextRange& range,
const json& options, const JsonReplyHandler& h );
LSPRequestHandle documentRangeFormatting( const URI& document, const TextRange& range,
const json& options, const TextEditArrayHandler& h );
void documentRename( const URI& document, const TextPosition& pos, const std::string& newName,
const JsonReplyHandler& h );
void documentRename( const URI& document, const TextPosition& pos, const std::string& newName,
const WorkspaceEditHandler& h );
void memoryUsage( const JsonReplyHandler& h );
void memoryUsage();
void executeCommand( const std::string& cmd, const json& params );
void registerCapabilities( const json& jcap );
void removeDoc( TextDocument* doc );
void shutdown();
bool supportsLanguage( const std::string& lang ) const;
LSPDocumentClient* getLSPDocumentClient( TextDocument* doc );
protected:
LSPClientServerManager* mManager{ nullptr };
String::HashType mId;
LSPDefinition mLSP;
std::string mRootPath;
Process mProcess;
TcpSocket* mSocket{ nullptr };
std::vector<TextDocument*> mDocs;
std::unordered_map<TextDocument*, std::unique_ptr<LSPDocumentClient>> mClients;
using HandlersMap = std::map<PluginIDType, std::pair<JsonReplyHandler, JsonReplyHandler>>;
HandlersMap mHandlers;
Mutex mClientsMutex;
Mutex mHandlersMutex;
bool mReady{ false };
bool mUsingProcess{ false };
bool mUsingSocket{ false };
struct QueueMessage {
json msg;
JsonReplyHandler h;
JsonReplyHandler eh;
};
std::vector<QueueMessage> mQueuedMessages;
std::string mReceive;
std::string mReceiveErr;
LSPServerCapabilities mCapabilities;
URI mWorkspaceFolder;
std::vector<std::string> mLanguagesSupported;
struct DidChangeQueue {
URI uri;
IdType version;
std::vector<DocumentContentChange> change;
};
std::queue<DidChangeQueue> mDidChangeQueue;
Mutex mDidChangeMutex;
std::atomic<int> mLastMsgId{ 0 };
void readStdOut( const char* bytes, size_t n );
void readStdErr( const char* bytes, size_t n );
LSPRequestHandle write( const json& msg, const JsonReplyHandler& h = nullptr,
const JsonReplyHandler& eh = nullptr, const int id = 0 );
void initialize();
void sendQueuedMessages();
void processNotification( const json& msg );
void processRequest( const json& msg );
void goToLocation( const json& res );
void notifyServerInitialized();
bool needsAsync();
bool socketConnect();
void socketInitialize();
LSPClientServer::LSPRequestHandle sendSync( const json& msg,
const JsonReplyHandler& h = nullptr,
const JsonReplyHandler& eh = nullptr );
void refreshSmenaticHighlighting();
void refreshCodeLens();
};
} // namespace ecode
#endif // ECODE_LSPCLIENTSERVER_HPP
|
ac921ef37160c1efec40db2e5973374f22d8486c | 304dcc859ff1bad63ae881a096e687f7dc3de04b | /Test_PC_Poker/UPGCommon/src/GameURL.cpp | aa68ee795d068cc8e903806ae647ca8b5040e4d9 | [] | no_license | idh37/testrepo | 03e416b115563cf62a4436f7a278eda2cd05d115 | b07cdd22bd42356522a599963f031a6294e14065 | refs/heads/master | 2020-07-11T00:57:34.526556 | 2019-09-10T07:22:35 | 2019-09-10T07:22:35 | 204,413,346 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 22,776 | cpp | GameURL.cpp | // GameURL.cpp
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "GameURL.h"
CString getGameURL(IDX_GAMEURL nGameURL, LPARAM lParam /* = NULL */)
{
CString strGameCode = GM().GetCurrentGameString();
int nGameCode = GM().GetCurrentGameCode();
int nGameIndex = GM().GetCurrentGameType();
CString strRet = "";
switch(nGameURL)
{
case IDX_GAMEURL_CHANCEAVATAR:
{
int nGroupCode = (int)lParam;
strRet.Format("http://game1.netmarble.net/gameshop/client/chanceavatar/chanceavatar.asp?game=%s&groupcode=%d&client=Y", strGameCode.GetString(), nGroupCode);
}
break;
case IDX_GAMEURL_ROULETTE:
strRet.Format("http://game1.netmarble.net/sub/Roulette/?game=%s",strGameCode.GetString());
break;
case IDX_GAMEURL_KISA:
strRet.Format("http://game1.netmarble.net/family/client/option/index.asp?gamecode=%d", nGameCode);
break;
case IDX_GAMEURL_FAMILYAVATARLIST:
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
strRet.Format( "http://poker.toctocgame.com/gameShop/client/gameavatar/familyavatarlist.asp?game=%s&client=Y", strGameCode.GetString());
else
strRet.Format( "http://game1.netmarble.net/gameshop/client/gameavatar/familyavatarlist.asp?game=%s&client=Y", strGameCode.GetString());
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format( "http://game1.netmarble.net/gameshop/client/gameavatar/familyavatarlist.asp?game=%s&client=Y", strGameCode.GetString());
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_GAMEAVATARLIST:
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
strRet.Format( "http://poker.toctocgame.com/gameshop/client/gameavatar/gameavatarlist.asp?game=%s&client=Y", strGameCode.GetString());
else
strRet.Format( "http://game1.netmarble.net/gameshop/client/gameavatar/gameavatarlist.asp?game=%s&client=Y", strGameCode.GetString());
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format( "http://game1.netmarble.net/gameshop/client/gameavatar/gameavatarlist.asp?game=%s&client=Y", strGameCode.GetString());
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_LOTTOAVATARLIST:
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
strRet.Format( "http://poker.toctocgame.com/gameshop/client/gameitem/lottoavatarlist.asp?game=%s&client=Y", strGameCode.GetString());
else
strRet.Format( "http://game1.netmarble.net/gameshop/client/gameitem/lottoavatarlist.asp?game=%s&client=Y", strGameCode.GetString());
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format( "http://game1.netmarble.net/gameshop/client/gameitem/lottoavatarlist.asp?game=%s&client=Y", strGameCode.GetString());
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_GAMEITEMLIST:
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
strRet.Format( "http://poker.toctocgame.com/gameshop/client/gameitem/gameitemlist.asp?game=%s&client=Y", strGameCode.GetString());
else
strRet.Format( "http://game1.netmarble.net/gameshop/client/gameitem/gameitemlist.asp?game=%s&client=Y", strGameCode.GetString());
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format( "http://game1.netmarble.net/gameshop/client/gameitem/gameitemlist.asp?game=%s&client=Y", strGameCode.GetString());
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_MYITEMLIST:
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
strRet.Format( "http://poker.toctocgame.com/gameshop/client/myinfo/myitemlist.asp?game=%s&client=Y", strGameCode.GetString());
else
strRet.Format( "http://game1.netmarble.net/gameshop/client/myinfo/myitemlist.asp?game=%s&client=Y", strGameCode.GetString());
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format( "http://game1.netmarble.net/gameshop/client/myinfo/myitemlist.asp?game=%s&client=Y", strGameCode.GetString());
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_REFILL:
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
{
strRet.Format( "http://www.toctocgame.com/M_Shop/Cash_Charge_PopUp.asp");
}
else
{
//strRet.Format( "https://nbill.netmarble.net/refill/cashFrameWin.asp?calltype=web&OPEN_CODE=poker");
strRet.Format( "https://nbill.netmarble.net/Cash/Payment/Main.aspx?calltype=web&OPEN_CODE=poker");
}
#else //UPGRADE_20120308_TOCTOC_CHANNELING
//strRet.Format( "https://nbill.netmarble.net/refill/cashFrameWin.asp?calltype=web&OPEN_CODE=poker");
strRet.Format( "https://nbill.netmarble.net/Cash/Payment/Main.aspx?calltype=web&OPEN_CODE=poker");
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_JACKPOT_RANK:
strRet.Format( "http://game1.netmarble.net/sub/jackpot/Rank/maxRank.asp?gamecode=%s&chk=game", strGameCode.GetString());
break;
case IDX_GAMEURL_MYFAMILY:
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
strRet.Format( "http://poker.toctocgame.com/family/client/myfamily/index.asp?gamecode=%d", nGameCode);
else
strRet.Format( "http://game1.netmarble.net/family/client/myfamily/index.asp?gamecode=%d", nGameCode);
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format( "http://game1.netmarble.net/family/client/myfamily/index.asp?gamecode=%d", nGameCode);
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_FREECHARGEINSURANCE:
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
strRet.Format( "http://poker.toctocgame.com/Service/Charge/FreeChargeInsurance.asp?game=%s&client=Y", strGameCode.GetString());
else
strRet.Format( "http://game1.netmarble.net/service/freechargeinsurance.asp?game=%s&client=Y", strGameCode.GetString());
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format( "http://game1.netmarble.net/service/freechargeinsurance.asp?game=%s&client=Y", strGameCode.GetString());
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_INSURANCE:
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
strRet.Format( "http://poker.toctocgame.com/Service/Insurance/InsurancePopup.asp?game=%s&client=Y", strGameCode.GetString());
else
strRet.Format( "http://game1.netmarble.net/Service/Insurance/InsurancePopup.asp?game=%s&client=Y", strGameCode.GetString());
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format( "http://game1.netmarble.net/Service/Insurance/InsurancePopup.asp?game=%s&client=Y", strGameCode.GetString());
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_INSURANCE_GOLD:
{
// 기본 보험금 안내 팝업
// 보험을 못받는 상태에서 지급받기 버튼을 클릭시 노출 (보유골드가 보험금 보다 많은 경우)
// 현재 보유 골드 및 보험 내용을 안내
strRet.Format("http://game1.netmarble.net/Service/GoldInsurance/index.asp");
}
break;
case IDX_GAMEURL_INSURANCE_GOLD2:
{
// 보험금 가입/지급 팝업
strRet.Format("http://game1.netmarble.net/Service/GoldInsurance/index.asp?gold=%I64d", GM().GetGoldInsuChangeChip());
}
break;
case IDX_GAMEURL_INSURANCE_RESULT: //보험가입결과 URL
{
int nInsuKind = (int)lParam;
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
strRet.Format( "http://poker.toctocgame.com/Service/Insurance/InsuranceEndPopup.asp?game=%s&client=Y&process=REGIST&insurancekind=%d", strGameCode.GetString(), nInsuKind);
else
strRet.Format( "http://game1.netmarble.net/Service/Insurance/InsuranceEndPopup.asp?game=%s&client=Y&process=REGIST&insurancekind=%d", strGameCode.GetString(), nInsuKind);
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format( "http://game1.netmarble.net/Service/Insurance/InsuranceEndPopup.asp?game=%s&client=Y&process=REGIST&insurancekind=%d", strGameCode.GetString(), nInsuKind);
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
}
break;
case IDX_GAMEURL_FREECHARGE:
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
strRet.Format( "http://poker.toctocgame.com/Service/Charge/FreeChargePopup.asp?game=%s&client=Y", strGameCode.GetString());
else
strRet.Format( "http://game1.netmarble.net/Service/Charge/FreeChargePopup.asp?game=%s&client=Y", strGameCode.GetString());
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format( "http://game1.netmarble.net/Service/Charge/FreeChargePopup.asp?game=%s&client=Y", strGameCode.GetString());
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_COLLECTOVERMONEY:
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
strRet.Format( "http://poker.toctocgame.com/family/LimitMoney/popCollectOverMoney.asp?game=%s", strGameCode.GetString());
else
strRet.Format( "http://game1.netmarble.net/family/LimitMoney/popCollectOverMoney.asp?game=%s", strGameCode.GetString());
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format( "http://game1.netmarble.net/family/LimitMoney/popCollectOverMoney.asp?game=%s", strGameCode.GetString());
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_ACHIEVELIMITMONEY:
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
strRet.Format( "http://poker.toctocgame.com/family/LimitMoney/popAchieveLimitMoney.asp?game=%s", strGameCode.GetString());
else
strRet.Format( "http://game1.netmarble.net/family/LimitMoney/popWebAchieveLimitMoney.asp?game=%s", strGameCode.GetString());
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format( "http://game1.netmarble.net/family/LimitMoney/popWebAchieveLimitMoney.asp?game=%s", strGameCode.GetString());
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_COLLECTREVISIONMONEY:
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
strRet.Format( "http://poker.toctocgame.com/family/LimitMoney/popCollectRevisionMoney.asp?game=%s", strGameCode.GetString());
else
strRet.Format( "http://game1.netmarble.net/family/LimitMoney/popCollectRevisionMoney.asp?game=%s", strGameCode.GetString());
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format( "http://game1.netmarble.net/family/LimitMoney/popCollectRevisionMoney.asp?game=%s", strGameCode.GetString());
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_COLLECTBOTHMONEY:
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
strRet.Format( "http://poker.toctocgame.com/family/LimitMoney/popCollectBothMoney.asp?game=%s", strGameCode.GetString());
else
strRet.Format( "http://game1.netmarble.net/family/LimitMoney/popCollectBothMoney.asp?game=%s", strGameCode.GetString());
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format( "http://game1.netmarble.net/family/LimitMoney/popCollectRevisionMoney.asp?game=%s", strGameCode.GetString());
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_COLLECTOVERGOLDBANK:
strRet.Format("http://game1.netmarble.net/family/limitgold/popCollectOverGold.asp");
break;
case IDX_GAMEURL_LOBBYITEMSHOP:
strRet.Format( "http://game1.netmarble.net/agame/gameshop/shop/?gamecode=%s", strGameCode.GetString());
break;
case IDX_GAMEURL_SEATKEEPER: //자리지킴이 구매페이지
//strRet.Format("http://game1.netmarble.net/gameshop/client/buy/GamePlaceDefend.asp?game=%s", strGameCode.GetString());
strRet.Format("http://game1.netmarble.net/gameshop/client/buy/GamePlaceDefend_Totalclient.asp?game=%s", strGameCode.GetString());
break;
case IDX_GAMEURL_GOLDENCHIP_CHANGE:
strRet.Format("http://game1.netmarble.net/GoldenChip/Client/GoldenChip_Change.asp?game=%s", strGameCode.GetString());
break;
case IDX_GAMEURL_GOLDENCHIP_LIST:
strRet.Format("http://game1.netmarble.net/GoldenChip/Client/GoldenChip_List.asp");
break;
case IDX_GAMEURL_ENDING_BANNER:
strRet.Format("http://service.netmarble.net/banner/ending/focus.asp?game=pokergroup");
break;
case IDX_GAMEURL_ENDING_BANNER_NATE:
strRet.Format("http://service.netmarble.net/banner/ending/focus.asp?game=nate");
break;
case IDX_GAMEURL_GAMEMANUAL: //게임방법창
{
//strRet.Format("http://c2.img.netmarble.kr/web/2007/html/gopo/po_guide/%s/main.html", strGameCode.GetString());
//strRet.Format("http://game1.netmarble.net/Poker/info/?game=%s", strGameCode.GetString());
strRet.Format("http://game1.netmarble.net/Poker/info/?game=%s", strGameCode.GetString());
//
// if (strGameCode == "spoker2")
// strRet="http://nrd.netmarble.net/201012010057.RD";
// else if (strGameCode == "low")
// strRet="http://nrd.netmarble.net/201012010058.RD";
// else if (strGameCode == "newpoker")
// strRet="http://nrd.netmarble.net/201012010056.RD";
// else if (strGameCode == "sutda")
// strRet="http://nrd.netmarble.net/201012010062.RD";
// else if (strGameCode == "hoola")
// strRet="http://nrd.netmarble.net/201012010063.RD";
// else if (strGameCode == "7cardhighlow")
// strRet="http://nrd.netmarble.net/201012010061.RD";
}
break;
case IDX_GAMEURL_LOBBYEVENTDIALOG: //로비이벤트 버튼 클릭하며 나오는 다이얼로그
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
{
strRet.Format("http://poker.toctocgame.com/gameshop/client/event/index.asp");
}
else
{
strRet.Format("http://game1.netmarble.net/pokerclient/index.asp");
}
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format("http://game1.netmarble.net/pokerclient/index.asp");
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_LOBBY_EVENT: //우측하단 이벤트
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
{
strRet.Format("http://poker.toctocgame.com/gameshop/client/event/eventbanner.asp");//http://game1.netmarble.net/event/2010/_12/20101207_pokerbeta/");
}
else
{
strRet.Format("http://game1.netmarble.net/pokerclient/eventbanner.asp");//http://game1.netmarble.net/event/2010/_12/20101207_pokerbeta/");
}
break;
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format("http://game1.netmarble.net/pokerclient/eventbanner.asp");//http://game1.netmarble.net/event/2010/_12/20101207_pokerbeta/");
break;
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
case IDX_GAMEURL_LOBBY_SHOP: //우측하단 추천상품
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
{
strRet.Format("http://poker.toctocgame.com/gameshop/client/waitroom/index.asp?gamecode=%s", strGameCode.GetString());
}
else
{
strRet.Format("http://game1.netmarble.net/gameshop/client/waitroom/?gamecode=%s", strGameCode.GetString());
}
break;
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format("http://game1.netmarble.net/gameshop/client/waitroom/?gamecode=%s", strGameCode.GetString());
break;
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
case IDX_GAMEURL_BADUSER: //불량유저 신고하기 페이지
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
strRet.Format("http://www.toctocgame.com/M_Customer/Customer_Main.asp");
else
strRet.Format("http://helpdesk.netmarble.net/HelpMyPage.asp?tab=4");
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format("http://helpdesk.netmarble.net/HelpMyPage.asp?tab=4");
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_PCROOM_ADVANTAGE:
{
if (strGameCode == "spoker2")
//strRet="http://pcbang.netmarble.net/PcBangPop/Benefit/main.asp?gtype=PG&gCode=5.02";
strRet="http://pcbang.netmarble.net/Popup/?gtype=PG&gCode=spoker2";
else if (strGameCode == "low")
//strRet="http://pcbang.netmarble.net/PcBangPop/Benefit/main.asp?gtype=PG&gCode=5.04";
strRet="http://pcbang.netmarble.net/Popup/?gtype=PG&gCode=low";
else if (strGameCode == "newpoker")
//strRet="http://pcbang.netmarble.net/PcBangPop/Benefit/main.asp?gtype=PG&gCode=5.01";
strRet="http://pcbang.netmarble.net/Popup/?gtype=PG&gCode=newpoker";
else if (strGameCode == "sutda")
//strRet="http://pcbang.netmarble.net/PcBangPop/Benefit/main.asp?gtype=PG&gCode=5.08";
strRet="http://pcbang.netmarble.net/Popup/?gtype=PG&gCode=sutda";
else if (strGameCode == "hoola")
//strRet="http://pcbang.netmarble.net/PcBangPop/Benefit/main.asp?gtype=PG&gCode=5.06";
strRet="http://pcbang.netmarble.net/Popup/?gtype=PG&gCode=hoola";
else if (strGameCode == "7cardhighlow")
//strRet="http://pcbang.netmarble.net/PcBangPop/Benefit/main.asp?gtype=PG&gCode=5.03";
strRet="http://pcbang.netmarble.net/Popup/?gtype=PG&gCode=7cardhighlow";
}break;
case IDX_GAMEURL_GAMEMAINPAGE: // 바로가기 주소
{
IDX_GAME idxGame = (IDX_GAME) lParam;
CGame *pGame = GM().GetGame(idxGame);
if (pGame)
{
strRet.Format("http://game1.netmarble.net/%s", pGame->GetGameString());
}
else
{
strRet.Format("http://www.netmarble.net");
}
}break;
case IDX_GAMEURL_GAMEMAINPAGE_NATE: //네이트 바로가기 주소
{
IDX_GAME idxGame = (IDX_GAME) lParam;
CGame *pGame = GM().GetGame(idxGame);
if (pGame)
{
strRet.Format("http://game.nate.com/NateFilter.asp?targetURL=http://game1.netmarble.net/%s/", pGame->GetGameString());
}
else
{
strRet.Format("http://game.nate.com/");
}
}break;
case IDX_GAMEURL_GAMEMAINPAGE_TOCTOC: // 톡톡 바로가기 주소
{
IDX_GAME idxGame = (IDX_GAME) lParam;
CGame *pGame = GM().GetGame(idxGame);
if (pGame)
{
strRet.Format("http://poker.toctocgame.com/?game=%s", pGame->GetGameString());
}
else
{
strRet.Format("http://poker.toctocgame.com/");
}
}break;
case IDX_GAMEURL_ENDPOPUP: //종료팝업
#ifdef UPGRADE_20120308_TOCTOC_CHANNELING
if (NMBASE::UTIL::GetCurSiteNo() == NMBASE::UTIL::SNO_TOCTOC)
{
strRet.Format("http://poker.toctocgame.com/gameshop/client/event/EndingPop.asp?game=%s", strGameCode.GetString());
}
else
strRet.Format("http://game1.netmarble.net/gameshop/client/shop/EndingEventPop.asp?game=%s", strGameCode.GetString());
#else //UPGRADE_20120308_TOCTOC_CHANNELING
strRet.Format("http://game1.netmarble.net/gameshop/client/shop/EndingEventPop.asp?game=%s", strGameCode.GetString());
#endif //UPGRADE_20120308_TOCTOC_CHANNELING
break;
case IDX_GAMEURL_EVENT_PCPROMOTION_LOBBY_TOP:
{
strRet.Format("http://game1.netmarble.net/event/2011/_03/20110315_PCRoomPromotion/ClientPrizewinnerLstSlidebarType1.asp");
} break;
case IDX_GAMEURL_EVENTPAGE:
{
/*if (GM().GetMyInfo()->UI.SiteCode == NMBASE::UTIL::SNO_NATE)
strRet.Format("http://game1.netmarble.net/event/2014/poker/06/?siteinfo=nate");
else
strRet.Format("http://game1.netmarble.net/event/2014/poker/06/");*/
//if (GM().GetMyInfo()->UI.SiteCode == NMBASE::UTIL::SNO_NATE)
//strRet.Format("http://nrd.netmarble.net/201406170103.TR");
//else
//strRet.Format("http://nrd.netmarble.net/201406170102.TR");
/*strRet.Format("http://game1.netmarble.net/event/2014/poker/09/");*/
//strRet.Format("http://game1.netmarble.net/event/2014/poker/12/index.asp");
//if(true==GM().IsOverDay(2015, 2, 27)){
// strRet.Format("http://promotion.netmarble.net/m/event/mpoker/26");
//}
//else{
// if (GM().GetMyInfo()->UI.SiteCode == NMBASE::UTIL::SNO_NATE){
// strRet.Format("http://game1.netmarble.net/event/2015/poker/01/index.asp?siteinfo=nate");
// }
// else{
// strRet.Format("http://game1.netmarble.net/event/2015/poker/01/index.asp");
// }
//}
strRet.Format("http://promotion.netmarble.net/m/event/mpoker/26");
} break;
case IDX_GAMEURL_TIMELIMITAVATAR:
{
strRet.Format( "http://game1.netmarble.net/Item/LimitedGoods/?game=%s&client=Y", strGameCode.GetString());
} break;
case IDX_GAMEURL_POSTBOX:
{
#if defined(_DEBUG)
strRet.Format( "http://10.103.92.128:12002/pcgostop/message/repo/1/view" );
#else
if(g_strConnectecMasterServerName == "183.110.61.192:12000")
{
strRet.Format( "http://10.103.92.128:12002/pcgostop/message/repo/1/view" );
}
else
{
strRet.Format( "https://matgo-message.netmarble.net:12002/pcgostop/message/repo/1/view" );
}
#endif
} break;
case IDX_GAMEURL_POSTBOX_SEND_MESSAGE:
{
#if defined(_DEBUG)
strRet.Format( "http://10.103.92.128:12002/pcgostop/message/send/view" );
#else
if(g_strConnectecMasterServerName == "183.110.61.192:12000")
{
strRet.Format( "http://10.103.92.128:12002/pcgostop/message/send/view" );
}
else
{
strRet.Format( "https://matgo-message.netmarble.net:12002/pcgostop/message/send/view" );
}
#endif
} break;
case IDX_GAMEURL_POSTBOX_URL:
{
#if defined(_DEBUG)
strRet.Format( "10.103.92.128" );
#else
if(g_strConnectecMasterServerName == "183.110.61.192:12000")
{
strRet.Format( "10.103.92.128" );
}
else
{
strRet.Format( "matgo-message.netmarble.net" );
}
#endif
} break;
case IDX_GAMEURL_CHICKEN_URL:
{
strRet.Format( "http://game1.netmarble.net/event/2018/nychk/p_list.asp?gc=%d", nGameCode);
} break;
case IDX_GAMEURL_CHICKEN_REWARD:
{
strRet.Format( "http://game1.netmarble.net/event/2018/nychk/p_info.asp?gc=%d", nGameCode);
} break;
case IDX_GAMEURL_GOLD_BIGWHEEL:
{
//strRet.Format( "http://game1.netmarble.net/game/bigwheel/");
char buffer[MAX_PATH];
GetModuleFileName( NULL, buffer, MAX_PATH );
CString path = buffer;
path.Replace("\\", "/");
int pathLength = path.ReverseFind('/');
path.Delete(pathLength, path.GetLength());
strRet.Format( "file:///%s/Lobby/data/bigwheel/index.html", path.GetString());
} break;
case IDX_GAMEURL_CAPTCHA:
{
strRet.Format("http://game1.netmarble.net/poker/captcha/main.asp");
}
break;
case IDX_GAMEURL_CAFE:
{
strRet.Format("http://game1.netmarble.net/poker/reward/_html/cafeComm/cafe.asp");
}
break;
case IDX_GAMEURL_FREECHARGE_SHOP:
{
strRet.Format("http://game1.netmarble.net/poker/shop/freecharge.asp");
}
break;
}
return strRet;
}
|
b59877ac12a9261f6e051022b36c8084d95a575c | adc3102407dd9f5d912092d63a21dad367c5b842 | /pepcoding/OOPS/friendfn2.cpp | dae34e6d1e3fed0a66d10f3efabf4c3bafa69616 | [] | no_license | cashinqmar/DSALGO | e96b41d0f78e80175764026347acb2fd81264acd | 828d320b8f6df928a992760837ef65782538dc6d | refs/heads/master | 2020-12-05T21:32:06.717509 | 2020-11-17T10:17:15 | 2020-11-17T10:17:15 | 232,251,908 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 688 | cpp | friendfn2.cpp | #include<bits/stdc++.h>
using namespace std;
class class_2;
class class_1{
int data;
public:
void fill(int data){
this->data=data;
}
void display(){
cout<<data<<"\n";
}
friend void exchange(class_1 &,class_2 &);
};
class class_2{
int data;
public:
void fill(int data){
this->data=data;
}
void display(){
cout<<data<<"\n";
}
friend void exchange(class_1 &,class_2 &);
};
void exchange(class_1 &a,class_2 &b){
int temp=a.data;
a.data=b.data;
b.data=temp;
}
int main(){
class_1 a;
class_2 b;
a.fill(5);
b.fill(7);
a.display();
b.display();
exchange(a,b);
a.display();
b.display();
} |
0232149bde55d1c7e55a1cade47aedeeb89b8512 | be31580024b7fb89884cfc9f7e8b8c4f5af67cfa | /CTDL1/New folder/VC/VCWizards/AppWiz/MFC/Application/templates/1040/CalendarBar.h | 78dce878f53695df62d7262e2916b183a2ceab4f | [] | no_license | Dat0309/CTDL-GT1 | eebb73a24bd4fecf0ddb8428805017e88e4ad9da | 8b5a7ed4f98e5d553bf3c284cd165ae2bd7c5dcc | refs/heads/main | 2023-06-09T23:04:49.994095 | 2021-06-23T03:34:47 | 2021-06-23T03:34:47 | 379,462,390 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,497 | h | CalendarBar.h | [!if RIBBON_TOOLBAR]
// Questo codice sorgente degli esempi di MFC illustra l'utilizzo dell'interfaccia utente Microsoft Office Fluent di MFC
// e viene fornito esclusivamente come riferimento in supplemento
// al materiale di riferimento e alla documentazione in formato elettronico MFC
// forniti con il software della libreria MFC C++.
// Le condizioni di licenza per la copia, l'utilizzo o la distribuzione dell'interfaccia utente Microsoft Office Fluent sono disponibili separatamente.
// Per ulteriori informazioni sul programma di licenza dell'interfaccia utente Microsoft Office Fluent, visitare il sito
// http://go.microsoft.com/fwlink/?LinkId=238214.
//
// Copyright (C) Microsoft Corporation
// Tutti i diritti riservati.
[!endif]
#pragma once
/////////////////////////////////////////////////////////////////////////////
// Finestra CCalendarBar
class CCalendarBar : public CWnd
{
// Costruzione
public:
CCalendarBar();
// Attributi
protected:
CMonthCalCtrl m_wndCalendar;
int m_nMyCalendarsY;
CImageList m_Images;
// Sostituzioni
public:
virtual BOOL Create(const RECT& rect, CWnd* pParentWnd, UINT nID = (UINT)-1);
virtual BOOL PreTranslateMessage(MSG *pMsg);
// Implementazione
public:
virtual ~CCalendarBar();
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnPaint();
afx_msg void OnSetFocus(CWnd *pOldWnd);
DECLARE_MESSAGE_MAP()
};
|
a71f1788b3fc76bbdbeccfa8f1f1b0f51cdabcc0 | d09945668f19bb4bc17087c0cb8ccbab2b2dd688 | /srm/501-520/505/SetMultiples.cpp | 9df221abea484692a3a2b6b5c882a891e689cefc | [] | no_license | kmjp/procon | 27270f605f3ae5d80fbdb28708318a6557273a57 | 8083028ece4be1460150aa3f0e69bdb57e510b53 | refs/heads/master | 2023-09-04T11:01:09.452170 | 2023-09-03T15:25:21 | 2023-09-03T15:25:21 | 30,825,508 | 23 | 2 | null | 2023-08-18T14:02:07 | 2015-02-15T11:25:23 | C++ | UTF-8 | C++ | false | false | 3,631 | cpp | SetMultiples.cpp | #include <cstdlib>
#include <cstring>
#include <memory>
#include <cstdio>
#include <fstream>
#include <iostream>
#include <cmath>
#include <string>
#include <sstream>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <numeric>
using namespace std;
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef signed long long ll;
typedef unsigned long long ull;
#undef _P
#define _P(...) printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<to;x++)
#define FOR2(x,from,to) for(x=from;x<to;x++)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(x) x.begin(),x.end()
#define ZERO(a) memset(a,0,sizeof(a))
void _fill_int(int* p,int val,int rep) {int i; FOR(i,rep) p[i]=val;}
#define FILL_INT(a,val) _fill_int((int*)a,val,sizeof(a)/4)
#define MINUS(a) _fill_int((int*)a,-1,sizeof(a)/4)
#define EPS (1e-11)
template <class T> T sqr(T val){ return val*val;}
//-------------------------------------------------------
class SetMultiples {
public:
long long smallestSubset(long long A, long long B, long long C, long long D) {
A=max(A,B/2+1);
C=max(C,D/2+1);
ll ret=D-C+1;
while(A<=B) {
if(D/A<2) {
ret += B-A+1;
break;
}
ll m=(C+(A-1))/A;
if(m*A>D) {
// out
ll y=min(B+1,(C+(m-2))/(m-1));
ret+=y-A;
A=y;
}
else {
A=min(B+1,D/m+1);
}
}
return ret;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const long long &Expected, const long long &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { long long Arg0 = 1LL; long long Arg1 = 1LL; long long Arg2 = 2LL; long long Arg3 = 2LL; long long Arg4 = 1LL; verify_case(0, Arg4, smallestSubset(Arg0, Arg1, Arg2, Arg3)); }
void test_case_1() { long long Arg0 = 1LL; long long Arg1 = 2LL; long long Arg2 = 3LL; long long Arg3 = 4LL; long long Arg4 = 2LL; verify_case(1, Arg4, smallestSubset(Arg0, Arg1, Arg2, Arg3)); }
void test_case_2() { long long Arg0 = 2LL; long long Arg1 = 3LL; long long Arg2 = 5LL; long long Arg3 = 7LL; long long Arg4 = 3LL; verify_case(2, Arg4, smallestSubset(Arg0, Arg1, Arg2, Arg3)); }
void test_case_3() { long long Arg0 = 1LL; long long Arg1 = 10LL; long long Arg2 = 100LL; long long Arg3 = 1000LL; long long Arg4 = 500LL; verify_case(3, Arg4, smallestSubset(Arg0, Arg1, Arg2, Arg3)); }
void test_case_4() { long long Arg0 = 1000000000LL; long long Arg1 = 2000000000LL; long long Arg2 = 9000000000LL; long long Arg3 = 10000000000LL; long long Arg4 = 1254365078LL; verify_case(4, Arg4, smallestSubset(Arg0, Arg1, Arg2, Arg3)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main(int argc,char** argv) {
SetMultiples ___test;
if(argc==1) {
___test.run_test(-1);
}
else {
int i = atoi(argv[1]);
___test.run_test(i);
}
}
|
750a707f4170be159e6f59e351edf3d28b2a8075 | 6d135f8c8a16fdc1d555b4cf63bc21ce57fe17b9 | /test/gtest/geometry/TestRect.cpp | 4c32293e8920fb1c7f9e111f421796a0d66aadf7 | [
"Apache-2.0"
] | permissive | jefftastemakers/CrossLayout | 408a741a7d343fffe3d9f21aa35b3471cafbf34e | 4e0d6a54bbe83d184542c046cbb0044125512472 | refs/heads/master | 2022-01-02T09:07:42.280776 | 2018-01-22T09:44:00 | 2018-01-22T09:44:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,133 | cpp | TestRect.cpp | //
// Created by Dawid Drozd aka Gelldur on 14/01/17.
//
#include <gtest/gtest.h>
#include <crosslayout/geometry/Rect.h>
#include <crosslayout/geometry/GeometryToString.h>
using namespace CrossLayout;
TEST(TestRect, mergeSticky)
{
Rect<int> rectA{0, 0, 10, 10};
Rect<int> rectB{10, 10, 10, 10};
EXPECT_EQ((Rect<int>{0, 0, 20, 20}), rectA.merge(rectB));
}
TEST(TestRect, mergeSpace)
{
Rect<int> rectA{5, 5, 10, 10};
Rect<int> rectB{20, 20, 10, 10};
EXPECT_EQ((Rect<int>{5, 5, 25, 25}), rectA.merge(rectB));
EXPECT_EQ((Rect<int>{5, 5, 25, 25}), rectB.merge(rectA));
}
TEST(TestRect, mergeIntersect)
{
Rect<int> rectA{15, 15, 10, 10};
Rect<int> rectB{20, 20, 10, 10};
EXPECT_EQ((Rect<int>{15, 15, 15, 15}), rectA.merge(rectB));
EXPECT_EQ((Rect<int>{15, 15, 15, 15}), rectB.merge(rectA));
}
TEST(TestRect, mergeUnion)
{
Rect<int> rectA{20, 20, 10, 10};
Rect<int> rectB{20, 20, 10, 10};
EXPECT_EQ((Rect<int>{20, 20, 10, 10}), rectA.merge(rectB));
EXPECT_EQ((Rect<int>{20, 20, 10, 10}), rectB.merge(rectA));
}
TEST(TestRect, mergeWithSelf)
{
Rect<int> rectA{20, 20, 10, 10};
EXPECT_EQ(rectA, rectA.merge(rectA));
}
|
f4feb986bb92fb59189be834224498487324ca6a | 64ab366f1ffc3b69bbf4c9d67e4d51be43fb72bd | /LanQiaoExercise/08 深搜/190320王子救公主.cpp | 2d0d6f884cd157742fe4ee731be99f23c340cbd8 | [] | no_license | cnbeiyu/Algorithm | 94dfec758f2f64e3dfd7a084398538b76675d364 | d99a939bf42da54c5eb831a26b264c76dd95960f | refs/heads/master | 2022-03-04T06:15:53.381234 | 2022-02-15T04:37:52 | 2022-02-15T04:37:52 | 176,132,307 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 965 | cpp | 190320王子救公主.cpp | #include <iostream>
using namespace std;
char map[100][100];
bool vis[100][100][5];
int n, m, ans;
bool in(int x, int y)
{
return 0 <= x && x < n && 0 <= y && y < m;
}
void dfs(int x, int y, int d)
{
if (!in(x, y) || !vis[x][y])
{
return;
}
vis[x][y][2 - d] = true;
dfs(x, y + 2 - d, d);
dfs(x, y - (2 - d), d);
dfs(x + 2 - d, y, d);
dfs(x - (2 - d), y, d);
}
int main(int argc, char const *argv[])
{
cin >> n >> m;
for (int i = 0; i < n; ++i)
{
for (int j = 0; i < m; ++j)
{
cin >> map[n][m];
}
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
if (map[n][m] == 'w')
{
dfs(n, m, 0);
break;
}
}
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
if (map[n][m] == 'g')
{
dfs(n, m, 1);
break;
}
}
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
if (vis[n][m][1] && vis[n][m][2])
{
cout << "yes";
return 0;
}
}
}
return 0;
} |
eba7f49ef8e3bcacc80c7caa2341d28c5572c540 | b93f861463f42d90ed18b19abc5037b42412d7cf | /source/adios2/engine/dataman/DataManReader.cpp | 2b02281d781ccaf9319e1885804004aa709e5526 | [
"Apache-2.0"
] | permissive | kiizawa/ADIOS2 | acbdb76f927bfbe3addafb9e7186b18851a9b243 | 44d7d586016daaae58d00c85f2ca7c0eed01cfd4 | refs/heads/master | 2021-05-05T15:26:10.989500 | 2018-01-12T18:56:52 | 2018-01-12T18:56:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,901 | cpp | DataManReader.cpp | /*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* DataManReader.cpp
*
* Created on: Feb 21, 2017
* Author: Jason Wang
* William F Godoy
*/
#include "DataManReader.h"
#include "DataManReader.tcc"
#include "adios2/helper/adiosFunctions.h" //CSVToVector
namespace adios2
{
DataManReader::DataManReader(IO &io, const std::string &name, const Mode mode,
MPI_Comm mpiComm)
: Engine("DataManReader", io, name, mode, mpiComm),
m_BP3Deserializer(mpiComm, m_DebugMode), m_Man(mpiComm, m_DebugMode)
{
m_EndMessage = " in call to IO Open DataManReader " + m_Name + "\n";
Init();
}
StepStatus DataManReader::BeginStep(StepMode stepMode,
const float timeoutSeconds)
{
std::vector<char> buffer;
buffer.reserve(m_BufferSize);
size_t size = 0;
m_Man.ReadWAN(buffer.data(), size);
StepStatus status;
if (size > 0)
{
status = StepStatus::OK;
m_BP3Deserializer.m_Data.Resize(size, "in DataMan Streaming Listener");
std::memcpy(m_BP3Deserializer.m_Data.m_Buffer.data(), buffer.data(),
size);
m_BP3Deserializer.ParseMetadata(m_BP3Deserializer.m_Data, m_IO);
}
else
{
status = StepStatus::EndOfStream;
}
return status;
}
void DataManReader::PerformGets() {}
void DataManReader::EndStep() {}
void DataManReader::Close(const int transportIndex) {}
// PRIVATE
bool DataManReader::GetBoolParameter(Params ¶ms, std::string key,
bool &value)
{
auto itKey = params.find(key);
if (itKey != params.end())
{
if (itKey->second == "yes" || itKey->second == "YES" ||
itKey->second == "Yes" || itKey->second == "true" ||
itKey->second == "TRUE" || itKey->second == "True")
{
value = true;
return true;
}
if (itKey->second == "no" || itKey->second == "NO" ||
itKey->second == "No" || itKey->second == "false" ||
itKey->second == "FALSE" || itKey->second == "False")
{
value = false;
return true;
}
}
return false;
}
bool DataManReader::GetStringParameter(Params ¶ms, std::string key,
std::string &value)
{
auto it = params.find(key);
if (it != params.end())
{
value = it->second;
return true;
}
return false;
}
bool DataManReader::GetUIntParameter(Params ¶ms, std::string key,
unsigned int &value)
{
auto it = params.find(key);
if (it != params.end())
{
value = std::stoi(it->second);
return true;
}
return false;
}
void DataManReader::InitParameters()
{
GetUIntParameter(m_IO.m_Parameters, "NChannels", m_NChannels);
GetStringParameter(m_IO.m_Parameters, "Format", m_UseFormat);
}
void DataManReader::InitTransports()
{
size_t channels = m_IO.m_TransportsParameters.size();
std::vector<std::string> names;
for (size_t i = 0; i < channels; ++i)
{
names.push_back(m_Name + std::to_string(i));
}
m_Man.OpenWANTransports(names, Mode::Read, m_IO.m_TransportsParameters,
true);
}
void DataManReader::Init()
{
for (auto &j : m_IO.m_Operators)
{
if (j.ADIOSOperator.m_Type == "Signature2")
{
m_Man.SetCallback(j.ADIOSOperator);
break;
}
}
InitParameters();
if (m_UseFormat == "BP" || m_UseFormat == "bp")
{
m_BP3Deserializer.InitParameters(m_IO.m_Parameters);
}
m_Man.SetBP3Deserializer(m_BP3Deserializer);
m_Man.SetIO(m_IO);
InitTransports();
}
#define declare_type(T) \
void DataManReader::DoGetSync(Variable<T> &variable, T *data) \
{ \
GetSyncCommon(variable, data); \
} \
void DataManReader::DoGetDeferred(Variable<T> &variable, T *data) \
{ \
GetDeferredCommon(variable, data); \
} \
void DataManReader::DoGetDeferred(Variable<T> &variable, T &data) \
{ \
GetDeferredCommon(variable, &data); \
}
ADIOS2_FOREACH_TYPE_1ARG(declare_type)
#undef declare_type
} // end namespace adios2
|
72634e0f70c17d51877c98e5bee0ffbe7b4ecf53 | c3ffa07567d3d29a7439e33a6885a5544e896644 | /UVa/10557.cpp | 959270702f49ca7e55d0059e3424f2227f18527f | [] | no_license | a00012025/Online_Judge_Code | 398c90c046f402218bd14867a06ae301c0c67687 | 7084865a7050fc09ffb0e734f77996172a93d3ce | refs/heads/master | 2018-01-08T11:33:26.352408 | 2015-10-10T23:20:35 | 2015-10-10T23:20:35 | 44,031,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,370 | cpp | 10557.cpp | #include<stdio.h>
#include<vector>
#include<queue>
#include<string.h>
#define INF 100000000
using namespace std;
vector<int> v[101] ;
queue<int> q ;
int d[101],w[101],cnt[101],n ;
bool inq[101],done[101] ;
bool bellmanford(int s)
{
memset(inq,0,sizeof(inq)) ;
memset(cnt,0,sizeof(cnt)) ;
memset(done,0,sizeof(done)) ;
while(!q.empty()) q.pop();
for(int i=1;i<=n;i++) d[i]=-INF ;
d[s]=100 ; q.push(s) ; inq[s]=1 ;
while(!q.empty())
{
int u=q.front() ; q.pop() ; inq[u]=0 ;
if(u==n) return 1 ;
if(done[u]) continue ;
if(d[u]==INF) done[u]=1 ;
for(int i=0;i<v[u].size();i++)
if(d[u]+w[v[u][i]]>0 && d[u]+w[v[u][i]]>d[v[u][i]])
{
d[v[u][i]]=d[u]+w[v[u][i]] ;
if(++cnt[v[u][i]] > n+1) d[v[u][i]]=INF ;
if(!inq[v[u][i]]) q.push(v[u][i]) ;
inq[v[u][i]]=1 ;
}
}
return 0 ;
}
main()
{
while(scanf("%d",&n)==1 && n!=-1)
{
for(int i=0;i<=n;i++) v[i].clear() ;
for(int i=1;i<=n;i++)
{
int num,a ;
scanf("%d%d",&w[i],&num) ;
while(num--) {scanf("%d",&a) ; v[i].push_back(a) ;}
}
if(bellmanford(1)) printf("winnable\n") ;
else printf("hopeless\n") ;
}
}
|
699a25f8e138d3b94f6e7989369dad0e1c8f8daf | a1d634c8c9808d9eae81bc2514ee5817af677b18 | /Configuration/src/ArtusConfig.cc | f7811aa1de8991ac51928bc1f78797afc31f593f | [] | no_license | artus-analysis/Artus | eaeeec4e36b167e72275176076edc7167d304607 | 9170dd2f0e7664f43231243aee79f3e0a0657a0a | refs/heads/master | 2022-08-11T12:12:23.166211 | 2019-12-17T18:18:51 | 2020-01-22T12:49:14 | 23,577,702 | 7 | 25 | null | 2020-01-21T12:45:19 | 2014-09-02T12:27:01 | C++ | UTF-8 | C++ | false | false | 6,624 | cc | ArtusConfig.cc |
#include <iostream>
#include <cstdlib>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/trim.hpp>
#include "TObjString.h"
#include "Artus/Configuration/interface/ArtusConfig.h"
#include "Artus/Configuration/interface/PropertyTreeSupport.h"
#include "Artus/Utility/interface/Utility.h"
ArtusConfig::ArtusConfig(int argc, char** argv) :
m_jsonConfigFileName(""),
m_minimumLogLevelString("")
{
boost::program_options::options_description programOptions("Options");
programOptions.add_options()
("help,h", "Print help message")
("log-level", boost::program_options::value<std::string>(&m_minimumLogLevelString),
"Detail level of logging (debug, info, warning, error, critical). [Default: taken from JSON config or info]")
("json-config", boost::program_options::value<std::string>(&m_jsonConfigFileName),
"JSON config file");
boost::program_options::positional_options_description positionalProgramOptions;
positionalProgramOptions.add("json-config", 1);
boost::program_options::variables_map optionsVariablesMap;
boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(programOptions).positional(positionalProgramOptions).run(),
optionsVariablesMap);
boost::program_options::notify(optionsVariablesMap);
// print help message, either if requested or if no parameters
// have been supplied
if (optionsVariablesMap.count("help") || (optionsVariablesMap.size() == 0))
{
std::cout << "Usage: " << argv[0] << " [options] JSON-CONFIG" << std::endl;
std::cout << programOptions << std::endl;
exit(0);
}
InitConfig();
// logging can be uses from here on
}
std::pair<bool, el::Level> ArtusConfig::parseLogLevel(
std::string const& minimumLogLevelString) const
{
if (minimumLogLevelString == "debug")
{
return std::make_pair(true, el::Level::Debug);
}
else if (minimumLogLevelString == "info")
{
return std::make_pair(true, el::Level::Info);
}
else if (minimumLogLevelString == "warning")
{
return std::make_pair(true, el::Level::Warning);
}
else if (minimumLogLevelString == "error")
{
return std::make_pair(true, el::Level::Error);
}
else if (minimumLogLevelString == "critical")
{
return std::make_pair(true, el::Level::Fatal);
}
return std::make_pair(false, el::Level::Fatal);
}
ArtusConfig::ArtusConfig(std::stringstream& sStream)
{
boost::property_tree::json_parser::read_json(sStream, m_propTreeRoot);
InitConfig(true);
}
void ArtusConfig::InitConfig(bool configPreLoaded)
{
// has the config been preloaded via the constructor already ?
if (! configPreLoaded)
{
if(m_jsonConfigFileName.empty())
{
LOG(FATAL) << "NO JSON config specified!";
}
std::cout << "Loading Config file from \"" << m_jsonConfigFileName << "\"." << std::endl;
boost::property_tree::json_parser::read_json(m_jsonConfigFileName, m_propTreeRoot);
}
// init logging
if(m_minimumLogLevelString.empty())
{
m_minimumLogLevelString = m_propTreeRoot.get<std::string>("LogLevel", "info");
}
std::pair<bool, el::Level> minimumLogLevel = parseLogLevel(m_minimumLogLevelString);
el::Configurations defaultLoggingConfig;
defaultLoggingConfig.setToDefault();
defaultLoggingConfig.set(el::Level::Global, el::ConfigurationType::ToFile, "false");
defaultLoggingConfig.set(el::Level::Debug, el::ConfigurationType::Enabled, "true");
defaultLoggingConfig.set(el::Level::Info, el::ConfigurationType::Enabled, "true");
defaultLoggingConfig.set(el::Level::Warning, el::ConfigurationType::Enabled, "true");
defaultLoggingConfig.set(el::Level::Error, el::ConfigurationType::Enabled, "true");
defaultLoggingConfig.set(el::Level::Fatal, el::ConfigurationType::Enabled, "true");
gErrorIgnoreLevel = kInfo;
if (minimumLogLevel.second >= el::Level::Info)
{
defaultLoggingConfig.set(el::Level::Debug, el::ConfigurationType::Enabled, "false");
RooMsgService::instance().setGlobalKillBelow(RooFit::INFO) ;
gErrorIgnoreLevel = kInfo;
}
if (minimumLogLevel.second >= el::Level::Warning)
{
defaultLoggingConfig.set(el::Level::Info, el::ConfigurationType::Enabled, "false");
RooMsgService::instance().setGlobalKillBelow(RooFit::WARNING) ;
gErrorIgnoreLevel = kWarning;
}
if (minimumLogLevel.second >= el::Level::Error)
{
defaultLoggingConfig.set(el::Level::Warning, el::ConfigurationType::Enabled, "false");
RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR) ;
gErrorIgnoreLevel = kError;
}
if (minimumLogLevel.second >= el::Level::Fatal)
{
defaultLoggingConfig.set(el::Level::Error, el::ConfigurationType::Enabled, "false");
gErrorIgnoreLevel = kFatal;
}
defaultLoggingConfig.set(el::Level::Debug, el::ConfigurationType::Format, "%msg");
defaultLoggingConfig.set(el::Level::Info, el::ConfigurationType::Format, "%msg");
defaultLoggingConfig.set(el::Level::Warning, el::ConfigurationType::Format, "\033[0;30;43m%level:\033[0m %msg");
defaultLoggingConfig.set(el::Level::Error, el::ConfigurationType::Format, "\033[0;37;41m%level:\033[0m %msg");
defaultLoggingConfig.set(el::Level::Fatal, el::ConfigurationType::Format, "\033[0;37;41m%level:\033[0;31m %msg\033[0m");
el::Loggers::reconfigureLogger("default", defaultLoggingConfig);
m_outputPath = m_propTreeRoot.get<std::string>("OutputPath", "output.root");
m_fileNames = PropertyTreeSupport::GetAsStringList(&m_propTreeRoot, "InputFiles");
LOG(INFO) << "Loading " << m_fileNames.size() << " input files.";
if (m_fileNames.size() == 0)
{
LOG(FATAL) << "No input files specified!";
}
}
void ArtusConfig::SaveConfig(TFile* outputFile) const
{
TObjString jsonConfigContent(
Utility::ReadStringFromFile(m_jsonConfigFileName).c_str());
outputFile->cd();
jsonConfigContent.Write("config");
}
std::vector<std::string> const& ArtusConfig::GetInputFiles() const
{
return m_fileNames;
}
ArtusConfig::NodeTypePair ArtusConfig::ParseProcessNode(std::string const& sInp)
{
std::vector<std::string> splitted;
boost::algorithm::split(splitted, sInp, boost::algorithm::is_any_of(":"));
transform(splitted.begin(), splitted.end(), splitted.begin(),
[](std::string s) { return boost::algorithm::trim_copy(s); });
if (splitted.size() != 2)
{
LOG(FATAL) << "Process node description " << sInp << " cannot be parsed!";
}
ProcessNodeType ntype;
if (splitted[0] == "filter")
{
ntype = ProcessNodeType::Filter;
}
else if (splitted[0] == "producer")
{
ntype = ProcessNodeType::Producer;
}
else
{
LOG(FATAL) << "process node type " << splitted[0] << " is unknown!";
}
return std::make_pair(ntype, splitted[1]);
}
|
8dcd40f53b8590789575e66d96505ff728a6293b | ab5a682d2b38429694b4a8c0dfdfd058c4832c30 | /source/Board/AttackHandler.cpp | dacdb519803d27342be2cc495c13b1faf0c9da4e | [] | no_license | GLorenz/DauntlessDebate | ea24ffc595c21c479ad2ddcdd3b49bb3447a5782 | 91490a9efa3ef2e41ad22408690a4a6317a5d2ca | refs/heads/master | 2023-03-31T05:40:00.968370 | 2021-03-31T14:15:54 | 2021-03-31T14:15:54 | 353,374,123 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,406 | cpp | AttackHandler.cpp | // Authors: Lorenz Gonsa & Sabrina Loder, MMP2a FHS-MMT
#include "pch.h"
#include "Board/AttackHandler.h"
#include "Foundation/ConfigHandler.h"
#include "GameManager.h"
BoardComponent::Squares AttackHandler::getAttackOptions(std::shared_ptr<Meeple> attacker, AttackDir attackDir)
{
auto board = GameManager::getInstance().getBoard();
auto coord = attacker->getCurrentSquare()->getBoardCoordinates();
// Find affectedSquares of Attack Range
BoardComponent::Squares squares;
std::vector<std::vector<int>> pattern;
if (attacker->getAttack() == Meeple::Attack::Melee) pattern = ConfigHandler::getInstance().getMeleePattern();
else if (attacker->getAttack() == Meeple::Attack::Ranged) pattern = ConfigHandler::getInstance().getRangedPattern();
else pattern = ConfigHandler::getInstance().getRandomPattern(attacker->getRandomIdx());
switch (attackDir)
{
case AttackDir::Right:
pattern = transpose(reverseRows(pattern));
break;
case AttackDir::Left:
pattern = transpose(reverseCols(pattern));
break;
case AttackDir::Down:
pattern = reverseRows(reverseCols(pattern));
break;
};
int cols = pattern.size();
int rows = pattern[0].size();
int attackerCol = 0;
int attackerRow = 0;
for (int row = 0; row < rows; row++)
{
for(int col = 0; col < cols; col++)
{
if (pattern[col][row] == 2) {
attackerCol = col;
attackerRow = row;
}
}
}
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
if (pattern[col][row] == 1)
{
sf::Vector2i distance = sf::Vector2i(col - attackerCol, row - attackerRow);
// x is always col, y is always row
auto targetSquare = board->getSquareAt(coord.x + distance.x, coord.y + distance.y);
if(targetSquare != nullptr)
squares.push_back(targetSquare);
}
}
}
return squares;
}
void AttackHandler::attack(std::shared_ptr<Meeple> attacker, BoardComponent::Squares affectedSquares)
{
// Calculate effectiveness and damage enemy
for (auto square : affectedSquares)
{
auto meeple = GameManager::getInstance().getBoard()->getMeepleOnSquare(square);
if (!meeple) continue;
if (meeple->isPlayerOne() == attacker->isPlayerOne()) continue;
Meeple::Type enemyType = meeple->getType();
Meeple::Type attackerType = attacker->getType();
if (enemyType == attackerType) meeple->receiveDamage(standardDamage);
else
{
if (attackerType == Meeple::Type::A)
{
if(enemyType == Meeple::Type::B) meeple->receiveDamage(standardDamage * 2);
else if (enemyType == Meeple::Type::C) meeple->receiveDamage(standardDamage / 2);
}
else if (attackerType == Meeple::Type::B)
{
if (enemyType == Meeple::Type::C) meeple->receiveDamage(standardDamage * 2);
else if (enemyType == Meeple::Type::A) meeple->receiveDamage(standardDamage / 2);
}
else if (attackerType == Meeple::Type::C)
{
if (enemyType == Meeple::Type::A) meeple->receiveDamage(standardDamage * 2);
else if (enemyType == Meeple::Type::B) meeple->receiveDamage(standardDamage / 2);
}
}
}
}
std::vector<std::vector<int>> AttackHandler::transpose(std::vector<std::vector<int>> matrix)
{
// column major means size of matrix is cols
int cols = matrix.size();
int rows = matrix[0].size();
auto output = createEmpty(cols, rows);
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
output[row][col] = matrix[col][row];
}
}
return output;
}
std::vector<std::vector<int>> AttackHandler::reverseCols(std::vector<std::vector<int>> matrix)
{
int cols = matrix.size();
int rows = matrix[0].size();
auto output = createEmpty(rows, cols);
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < cols; col++)
{
output[col][row] = matrix[cols - col - 1][row];
}
}
return output;
}
std::vector<std::vector<int>> AttackHandler::reverseRows(std::vector<std::vector<int>> matrix)
{
int cols = matrix.size();
int rows = matrix[0].size();
auto output = createEmpty(rows, cols);
for (int col = 0; col < cols; col++)
{
for (int row = 0; row < rows; row++)
{
output[col][row] = matrix[col][rows - row - 1];
}
}
return output;
}
std::vector<std::vector<int>> AttackHandler::createEmpty(int rows, int cols)
{
// 2d vector is column major
std::vector<std::vector<int>> result(cols);
for (size_t i = 0; i < result.size(); i++) {
result[i] = std::vector<int>(rows);
}
return result;
} |
6cb3f71359cc3bf88e81c328545b8c8c19e845b9 | f2c110a519d874afc045f9a3a912546789e344e1 | /LiveEntityImplementation/Rabbit.cpp | a3d417d77a2d33cf05f943a0d75f1dfcf58a9517 | [] | no_license | Barbariansyah/OOP-Tubes-1-Harvest-Moon | 2c82e13c4cdb6c70d98ccb4787a3e977ec84d31f | 30bb24d6bb62b348e100bda240cacf81e555a0be | refs/heads/master | 2021-10-25T16:33:45.100805 | 2019-04-05T12:11:21 | 2019-04-05T12:11:21 | 174,787,460 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,015 | cpp | Rabbit.cpp | #include <iostream>
using namespace std;
#include "../Rabbit.h"
#include "../Game.h"
//! Konstruktor dari kelas Rabbit
/*!
*/
Rabbit :: Rabbit(int _pos_x , int _pos_y)
{
pos_x = _pos_x;
pos_y = _pos_y;
hunger_countdown = 5;
allowed_tiles = "Barn";
}
//! Implementasi dari fungsi Render()
/*!
Digunakan untuk menampilkan rabbit pada Map
@return karakter serta kode warna yang sesuai dengan Player.
*/
string Rabbit :: Render()
{
if(GetHungerCountdown() <= 0 && GetHungerCountdown() > -5){
return "r";
}
else if (GetHungerCountdown() > 0){
return "R";
}
}
//! Implementasi dari fungsi Sounds()
/*!
Digunakan untuk mengeluarkan suara rabbit
TBD!
*/
void Rabbit :: Sounds()
{
cout << "Chill :3" << endl;
}
void Rabbit :: GetKilledProduct()
{
Game::getPlayer().GetInventory().add(new RabbitMeat());
}
void Rabbit :: GetProduct()
{
throw "Can't be interracted";
} |
60dc95143784f1a2bd443d3b5f236588b96dab48 | 70597d3eb5e5c2ffc2955f3d6f7a6a124bd26b95 | /Networking/Server/dataline.cpp | ce23d14abbe40c20b2ae9eaad57567a054c59325 | [] | no_license | ppate67/NetworkBoardGames | c52f47a6720bf66745b129be45be56b3c83feae7 | faf98f594cc54b76974d4dba08e44e04a000bbcc | refs/heads/master | 2021-01-01T15:25:25.845889 | 2017-05-15T15:34:02 | 2017-05-15T15:34:02 | 97,612,302 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 134 | cpp | dataline.cpp | #include "dataline.h"
dataLine::dataLine(int key, string username, int gameID, int gameType, int moveNumber, GameMsg msg)
{
}
|
012006d9b5332d315b7eb7d3f80226861832e18e | 2a02d8873c8825eb3fef2b352fcda238961831c9 | /kattis/gridmst.cpp | 90a46c1196669e05c8dc6108f7a8d171f418873a | [] | no_license | Stypox/olympiad-exercises | eb42b93a10ae566318317dfa3daaa65b7939621b | 70c6e83a6774918ade532855e818b4822d5b367b | refs/heads/master | 2023-04-13T22:30:55.122026 | 2023-04-10T15:09:17 | 2023-04-10T15:09:17 | 168,403,900 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,578 | cpp | gridmst.cpp | #include <bits/stdc++.h>
using namespace std;
struct Point{
int16_t x,y;
int par=-1;
};
struct Con{
int i,j,d;
bool operator<(const Con& o){
return d<o.d;
}
};
int main(){
int N;
cin>>N;
vector<vector<int>> grid(1000, vector<int>(1000,-1));
vector<Point> points;
queue<pair<int,int>> q;
for(int n=0;n<N;++n){
int16_t x,y;
cin>>x>>y;
points.push_back({x,y});
q.push({x,y});
grid[x][y]=n;
}
if(points.size()==0){
cout<<0<<"\n";
return 0;
}
while(!q.empty()) {
auto [x,y]=q.front();
q.pop();
int i=grid[x][y];
for (auto [dx,dy] : initializer_list{pair{1,0}, {-1,0}, {0,1}, {0,-1}}){
int nx=x+dx,ny=y+dy;
if(nx<0||nx>=1000||ny<0||ny>=1000) continue;
if(grid[nx][ny] == -1){
grid[nx][ny]=i;
q.push({nx,ny});
}
}
}
set<pair<int,int>> consSet;
for(int a=0;a<1000;++a){
for(int b=0;b<1000-1;++b){
if(grid[a][b]!=grid[a][b+1]){
consSet.insert({grid[a][b], grid[a][b+1]});
}
if(grid[b][a]!=grid[b+1][a]){
consSet.insert({grid[b][a], grid[b+1][a]});
}
}
}
vector<Con> cons;
for(auto [i,j] : consSet){
cons.push_back({i,j,abs(points[i].x-points[j].x)+abs(points[i].y-points[j].y)});
}
sort(cons.begin(), cons.end());
function<int(int)> par = [&](int i){
if(points[i].par==-1)return i;
assert(points[i].par!=i);
return par(points[i].par);
};
function<bool(int,int)> merge = [&](int i, int j){
i=par(i);
j=par(j);
if (i==j){
return false;
}
points[j].par=i;
return true;
};
int res=0;
for(auto [i,j,d] : cons){
if(merge(i,j)) res+=d;
}
cout<<res<<"\n";
} |
e864c09377507718f08da3dc2540a0fd265bf858 | 2b3b5203233ebb11ccbf3c9830de9e26cc2785ee | /XRay/xr_3da/xrGame/smart_cast.h | d66496f65f32ad283a3ddf3d59e9297421dc074c | [
"Apache-2.0"
] | permissive | OLR-xray/XRay-NEW | b308aeefada0f0361706e8e57f23ebafc7fe3bc5 | f6988c98b45a9ff4eefec9538c6dffadef170ed7 | refs/heads/master | 2021-01-24T19:12:44.173491 | 2016-02-17T21:42:31 | 2016-02-17T21:42:31 | 50,777,026 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,500 | h | smart_cast.h | ////////////////////////////////////////////////////////////////////////////
// Module : smart_cast.h
// Created : 17.09.2004
// Modified : 17.09.2004
// Author : Dmitriy Iassenev
// Description : Smart dynamic cast
////////////////////////////////////////////////////////////////////////////
#ifndef SMART_CAST_H
#define SMART_CAST_H
#define TL_FAST_COMPILATION
#undef STATIC_CHECK
#include <typelist.h>
//#define PURE_DYNAMIC_CAST
#define PURE_DYNAMIC_CAST_COMPATIBILITY_CHECK
#ifdef PURE_DYNAMIC_CAST
# define smart_cast dynamic_cast
#else
# ifdef DEBUG
//# define SMART_CAST_STATS_ALL
# endif
# ifndef DECLARE_SPECIALIZATION
# include "smart_cast_impl0.h"
# else
# include "smart_cast_impl2.h"
# define DO_NOT_DECLARE_TYPE_LIST
# endif
# ifdef XRGAME_EXPORTS
DECLARE_SPECIALIZATION (CKinematics, IRender_Visual, dcast_PKinematics);
# undef cast_type_list
# define cast_type_list save_cast_list (CKinematics, IRender_Visual)
DECLARE_SPECIALIZATION (CKinematicsAnimated, IRender_Visual, dcast_PKinematicsAnimated);
# undef cast_type_list
# define cast_type_list save_cast_list (CKinematicsAnimated, IRender_Visual)
DECLARE_SPECIALIZATION (IParticleCustom, IRender_Visual, dcast_ParticleCustom);
# undef cast_type_list
# define cast_type_list save_cast_list (IParticleCustom, IRender_Visual)
# ifndef DO_NOT_DECLARE_TYPE_LIST
class ENGINE_API ISpatial;
namespace Feel { class ENGINE_API Sound; }
typedef Feel::Sound Feel__Sound;
template <> extern\
Feel::Sound* SmartDynamicCast::smart_cast<Feel::Sound,ISpatial>(ISpatial *p);\
add_to_cast_list(Feel__Sound,ISpatial);
# undef cast_type_list
# define cast_type_list save_cast_list (Feel__Sound, ISpatial)
# endif
DECLARE_SPECIALIZATION (IRenderable, ISpatial, dcast_Renderable);
# undef cast_type_list
# define cast_type_list save_cast_list (IRenderable, ISpatial)
DECLARE_SPECIALIZATION (IRender_Light, ISpatial, dcast_Light);
# undef cast_type_list
# define cast_type_list save_cast_list (IRender_Light, ISpatial)
DECLARE_SPECIALIZATION (CObject, ISpatial, dcast_CObject);
# undef cast_type_list
# define cast_type_list save_cast_list (CObject, ISpatial)
# ifndef DO_NOT_DECLARE_TYPE_LIST
class CObject;
class CGameObject;
add_to_cast_list (CGameObject, CObject);
# undef cast_type_list
# define cast_type_list save_cast_list (CGameObject, CObject)
# endif
DECLARE_SPECIALIZATION (CEntity, CGameObject, cast_entity);
# undef cast_type_list
# define cast_type_list save_cast_list (CEntity, CGameObject)
DECLARE_SPECIALIZATION (CEntityAlive, CGameObject, cast_entity_alive);
# undef cast_type_list
# define cast_type_list save_cast_list (CEntityAlive, CGameObject)
DECLARE_SPECIALIZATION (CInventoryItem, CGameObject, cast_inventory_item);
# undef cast_type_list
# define cast_type_list save_cast_list (CInventoryItem, CGameObject)
DECLARE_SPECIALIZATION (CInventoryOwner, CGameObject, cast_inventory_owner);
# undef cast_type_list
# define cast_type_list save_cast_list (CInventoryOwner, CGameObject)
DECLARE_SPECIALIZATION (CActor, CGameObject, cast_actor);
# undef cast_type_list
# define cast_type_list save_cast_list (CActor, CGameObject)
DECLARE_SPECIALIZATION (CGameObject, CInventoryOwner, cast_game_object);
# undef cast_type_list
# define cast_type_list save_cast_list (CGameObject, CInventoryOwner)
DECLARE_SPECIALIZATION (CWeapon, CInventoryItem, cast_weapon);
# undef cast_type_list
# define cast_type_list save_cast_list (CWeapon, CInventoryItem)
DECLARE_SPECIALIZATION (CWeapon, CGameObject, cast_weapon);
# undef cast_type_list
# define cast_type_list save_cast_list (CWeapon, CGameObject)
DECLARE_SPECIALIZATION (CFoodItem, CInventoryItem, cast_food_item);
# undef cast_type_list
# define cast_type_list save_cast_list (CFoodItem, CInventoryItem)
DECLARE_SPECIALIZATION (CMissile, CInventoryItem, cast_missile);
# undef cast_type_list
# define cast_type_list save_cast_list (CMissile, CInventoryItem)
DECLARE_SPECIALIZATION (CCustomZone, CGameObject, cast_custom_zone);
# undef cast_type_list
# define cast_type_list save_cast_list (CCustomZone, CGameObject)
DECLARE_SPECIALIZATION (CWeaponMagazined, CWeapon, cast_weapon_magazined);
# undef cast_type_list
# define cast_type_list save_cast_list (CWeaponMagazined, CWeapon)
DECLARE_SPECIALIZATION (CHudItem, CInventoryItem, cast_hud_item);
# undef cast_type_list
# define cast_type_list save_cast_list (CHudItem, CInventoryItem)
DECLARE_SPECIALIZATION (CPhysicsShellHolder,CGameObject, cast_physics_shell_holder);
# undef cast_type_list
# define cast_type_list save_cast_list (CPhysicsShellHolder,CGameObject)
DECLARE_SPECIALIZATION (IInputReceiver, CGameObject, cast_input_receiver);
# undef cast_type_list
# define cast_type_list save_cast_list (IInputReceiver, CGameObject)
DECLARE_SPECIALIZATION (CWeaponAmmo, CInventoryItem, cast_weapon_ammo);
# undef cast_type_list
# define cast_type_list save_cast_list (CWeaponAmmo, CInventoryItem)
/*
DECLARE_SPECIALIZATION (CCameraShotEffector, CCameraEffector, cast_effector_shot);
# undef cast_type_list
# define cast_type_list save_cast_list (CCameraShotEffector, CCameraEffector)
DECLARE_SPECIALIZATION (CEffectorZoomInertion, CCameraEffector, cast_effector_zoom_inertion);
# undef cast_type_list
# define cast_type_list save_cast_list (CEffectorZoomInertion, CCameraEffector)
*/
DECLARE_SPECIALIZATION (CParticlesPlayer, CGameObject, cast_particles_player);
# undef cast_type_list
# define cast_type_list save_cast_list (CParticlesPlayer, CGameObject)
DECLARE_SPECIALIZATION (CArtefact, CGameObject, cast_artefact);
# undef cast_type_list
# define cast_type_list save_cast_list (CArtefact, CGameObject)
DECLARE_SPECIALIZATION (CCustomMonster, CGameObject, cast_custom_monster);
# undef cast_type_list
# define cast_type_list save_cast_list (CCustomMonster, CGameObject)
DECLARE_SPECIALIZATION (CAI_Stalker, CGameObject, cast_stalker);
# undef cast_type_list
# define cast_type_list save_cast_list (CAI_Stalker, CGameObject)
DECLARE_SPECIALIZATION (CScriptEntity, CGameObject, cast_script_entity);
# undef cast_type_list
# define cast_type_list save_cast_list (CScriptEntity, CGameObject)
DECLARE_SPECIALIZATION (CSpaceRestrictor, CGameObject, cast_restrictor);
# undef cast_type_list
# define cast_type_list save_cast_list (CSpaceRestrictor, CGameObject)
DECLARE_SPECIALIZATION (CExplosive, CGameObject, cast_explosive);
# undef cast_type_list
# define cast_type_list save_cast_list (CExplosive, CGameObject)
DECLARE_SPECIALIZATION (CGameObject, CAttachmentOwner, cast_game_object);
# undef cast_type_list
# define cast_type_list save_cast_list (CGameObject, CAttachmentOwner)
DECLARE_SPECIALIZATION (CGameObject, CInventoryItem, cast_game_object);
# undef cast_type_list
# define cast_type_list save_cast_list (CGameObject, CInventoryItem)
DECLARE_SPECIALIZATION (CAttachableItem, CGameObject, cast_attachable_item);
# undef cast_type_list
# define cast_type_list save_cast_list (CAttachableItem, CGameObject)
DECLARE_SPECIALIZATION (CHolderCustom, CGameObject, cast_holder_custom);
# undef cast_type_list
# define cast_type_list save_cast_list (CHolderCustom, CGameObject)
DECLARE_SPECIALIZATION (CAttachmentOwner, CGameObject, cast_attachment_owner);
# undef cast_type_list
# define cast_type_list save_cast_list (CAttachmentOwner, CGameObject)
DECLARE_SPECIALIZATION (CEatableItem, CInventoryItem, cast_eatable_item);
# undef cast_type_list
# define cast_type_list save_cast_list (CEatableItem, CInventoryItem)
DECLARE_SPECIALIZATION (CBaseMonster, CGameObject, cast_base_monster);
# undef cast_type_list
# define cast_type_list save_cast_list (CBaseMonster, CGameObject)
# endif
DECLARE_SPECIALIZATION (CSE_Abstract, CSE_ALifeInventoryItem, cast_abstract);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_Abstract, CSE_ALifeInventoryItem)
DECLARE_SPECIALIZATION (CSE_Abstract, CSE_ALifeTraderAbstract, cast_abstract);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_Abstract, CSE_ALifeTraderAbstract)
DECLARE_SPECIALIZATION (CSE_Abstract, CSE_ALifeGroupAbstract, cast_abstract);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_Abstract, CSE_ALifeGroupAbstract)
DECLARE_SPECIALIZATION (CSE_Abstract, CSE_ALifeSchedulable, cast_abstract);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_Abstract, CSE_ALifeSchedulable)
DECLARE_SPECIALIZATION (CSE_ALifeGroupAbstract, CSE_Abstract, cast_group_abstract);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeGroupAbstract, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_ALifeSchedulable, CSE_Abstract, cast_schedulable);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeSchedulable, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_ALifeInventoryItem, CSE_Abstract, cast_inventory_item);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeInventoryItem, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_ALifeTraderAbstract, CSE_Abstract, cast_trader_abstract);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeTraderAbstract, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_Visual, CSE_Abstract, visual);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_Visual, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_Motion, CSE_Abstract, motion);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_Motion, CSE_Abstract)
DECLARE_SPECIALIZATION (ISE_Shape, CSE_Abstract, shape);
# undef cast_type_list
# define cast_type_list save_cast_list (ISE_Shape, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_Abstract, CSE_PHSkeleton, cast_abstract);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_Abstract, CSE_PHSkeleton)
DECLARE_SPECIALIZATION (CSE_ALifeObject, CSE_Abstract, cast_alife_object);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeObject, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_ALifeDynamicObject, CSE_Abstract, cast_alife_dynamic_object);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeDynamicObject, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_ALifeItemAmmo, CSE_Abstract, cast_item_ammo);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeItemAmmo, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_ALifeItemWeapon, CSE_Abstract, cast_item_weapon);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeItemWeapon, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_ALifeItemDetector, CSE_Abstract, cast_item_detector);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeItemDetector, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_ALifeMonsterAbstract, CSE_Abstract, cast_monster_abstract);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeMonsterAbstract, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_ALifeHumanAbstract, CSE_Abstract, cast_human_abstract);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeHumanAbstract, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_ALifeAnomalousZone, CSE_Abstract, cast_anomalous_zone);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeAnomalousZone, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_ALifeTrader, CSE_Abstract, cast_trader);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeTrader, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_ALifeCreatureAbstract, CSE_Abstract, cast_creature_abstract);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeCreatureAbstract, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_ALifeSmartZone, CSE_Abstract, cast_smart_zone);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeSmartZone, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_ALifeOnlineOfflineGroup, CSE_Abstract, cast_online_offline_group);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeOnlineOfflineGroup, CSE_Abstract)
DECLARE_SPECIALIZATION (CSE_ALifeItemPDA, CSE_Abstract, cast_item_pda);
# undef cast_type_list
# define cast_type_list save_cast_list (CSE_ALifeItemPDA, CSE_Abstract)
# ifndef DO_NOT_DECLARE_TYPE_LIST
# include "smart_cast_impl1.h"
# endif
#endif
#endif //SMART_CAST_H |
060419abc9a107a8933cc6df580cd14cd58cc35d | d40da1602ab21febe8ac4367ce36a47954f343a6 | /recipemanager.cpp | 29d802c10af18b187aeedf19103a413d905987cf | [
"Apache-2.0"
] | permissive | Hepibear/ksiazkakucharskacpp | d331262bdf0546c57b83cac6bb154cf407f7cf4d | 8a6c949e95ca996cc3d04157bf4aa6e05c39d025 | refs/heads/master | 2020-03-18T17:32:53.102330 | 2018-05-27T10:08:14 | 2018-05-27T10:08:14 | 135,034,812 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,732 | cpp | recipemanager.cpp | #include "recipemanager.h"
QVector<Recipe> RecipeManager::getRecipes() const
{
return m_recipes;
}
RecipeManager::RecipeManager()
{
this->loadRecipesFromDatabase();
}
void RecipeManager::loadRecipesFromDatabase()
{
QResource common(":/database/database.txt");
QFile commonFile(common.absoluteFilePath());
if (!commonFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Unable to open file: " << commonFile.fileName() << " because of error " << commonFile.errorString() << '\n';
return;
}
QTextStream in(&commonFile);
QString content = in.readAll();
QRegExp rx("(\\;)");
QVector<QString> queries = content.split(rx).toVector();
QVector<QVector<QString>> raw_recipes;
QVector<QString> temp_query;
for(auto query : queries)
{
temp_query.push_back(query);
if((query == "sniadanie") ||
(query == "obiad") ||
(query == "kolacja") )
{
raw_recipes.push_back(temp_query);
temp_query.clear();
}
}
for(auto rec : raw_recipes)
{
Recipe temp_recipe;
temp_recipe.setId(rec[0].toInt());
temp_recipe.setTitle(rec[1]);
int i=2;
QVector<QString> temp_ingredients;
QVector<QString> temp_quantity;
while(rec[i] != "koniec skladnikow")
{
temp_ingredients.push_back(rec[i]);
i++;
temp_quantity.push_back(rec[i]);
i++;
}
i++;//pomijamy "koniec skladnikow"
temp_recipe.setIngredients(temp_ingredients);
temp_recipe.setQuantity(temp_quantity);
QVector<QString> temp_steps;
while(rec[i] != "koniec krokow")
{
temp_steps.push_back(rec[i]);
i++;
}
i++;//pomijamy "koniec krokow"
temp_recipe.setSteps(temp_steps);
temp_recipe.setTime(rec[i]);
i++;
if(rec[i] == "sniadanie")
temp_recipe.setType(Recipe::Type::Sniadanie);
else if(rec[i] == "obiad")
temp_recipe.setType(Recipe::Type::Obiad);
else if(rec[i] == "kolacja")
temp_recipe.setType(Recipe::Type::Kolacja);
m_recipes.push_back(temp_recipe);
}
}
QVector<QString> RecipeManager::getAllIngredients()
{
QVector<QString> temp_ingredients;
for(auto rec : m_recipes)
{
for(auto ing : rec.ingredients())
{
if(!temp_ingredients.contains(ing))
temp_ingredients.push_back(ing);
}
}
return temp_ingredients;
}
|
dd9c0a1f8ff4718c79ddccc77e9844e58bb021db | c547c4da323f293150978d399b41ed097344f850 | /Games/PocketTris/PocketTris/Logic/Pieces/PieceCollisionSystem.cpp | 72a1e183998861b3fc0070edb4abe23ce7027515 | [] | no_license | Guanzhe/PocketEngine | 48686a77714cf8e0c52c68896fc4db31e828efab | 7728f6d8e520f54be5cd39023801286c78cce446 | refs/heads/master | 2021-09-18T06:32:28.031072 | 2017-12-29T20:50:22 | 2017-12-29T20:50:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,483 | cpp | PieceCollisionSystem.cpp | //
// PieceCollisionSystem.cpp
// Tetris
//
// Created by Jeppe Nielsen on 4/5/14.
// Copyright (c) 2014 Jeppe Nielsen. All rights reserved.
//
#include "PieceCollisionSystem.hpp"
#include <vector>
void PieceCollisionSystem::Initialize() {
AddComponent<PointTransform>();
AddComponent<Piece>();
AddComponent<PieceCollider>();
}
void PieceCollisionSystem::ObjectAdded(GameObject* object) {
PieceCollider* collider = object->GetComponent<PieceCollider>();
collider->Changed += event_handler(this, &PieceCollisionSystem::ColliderChanged, object);
}
void PieceCollisionSystem::ObjectRemoved(GameObject* object) {
PieceCollider* collider = object->GetComponent<PieceCollider>();
collider->Changed -= event_handler(this, &PieceCollisionSystem::ColliderChanged, object);
ChangedColliders::iterator it = changedColliders.find(object);
if (it!=changedColliders.end()) {
changedColliders.erase(it);
}
}
void PieceCollisionSystem::ColliderChanged(PieceCollider *collider, GameObject* object) {
changedColliders.insert(object);
}
void PieceCollisionSystem::Update(float dt) {
if (changedColliders.empty()) return;
for (ChangedColliders::iterator it = changedColliders.begin(); it!=changedColliders.end(); ++it) {
HandleCollision(*it);
}
changedColliders.clear();
}
void PieceCollisionSystem::HandleCollision(GameObject* object) {
PointTransform* pointTransform = object->GetComponent<PointTransform>();
Piece* piece = object->GetComponent<Piece>();
PieceCollider* collider = object->GetComponent<PieceCollider>();
CollisionPoints worldPoints;
for (int i=0; i<collider->movements.size(); i++) {
PieceCollider::Movement& m = collider->movements[i];
Point prevPosition = pointTransform->position;
int prevRotation = pointTransform->rotation;
pointTransform->position += m.deltaPosition;
pointTransform->rotation += m.deltaRotation;
if (!m.force) {
worldPoints.clear();
for (int x=0; x<4; x++) {
for (int y=0; y<4; y++) {
if (piece->grid[x][y]) {
worldPoints.push_back(pointTransform->LocalToWorld(Point(x-piece->pivotX,y-piece->pivotY)));
}
}
}
if (HitAny(worldPoints, object)) {
pointTransform->position = prevPosition;
pointTransform->rotation = prevRotation;
}
}
}
collider->movements.clear();
}
bool PieceCollisionSystem::HitAny(CollisionPoints &collisionPoints, GameObject* excludeObject) {
for (ObjectCollection::const_iterator it = Objects().begin(); it!=Objects().end(); ++it) {
GameObject* object = (*it);
if (object == excludeObject) continue;
PointTransform* pointTransform = object->GetComponent<PointTransform>();
Piece* piece = object->GetComponent<Piece>();
for (int x=0; x<4; x++) {
for (int y=0; y<4; y++) {
if (piece->grid[x][y]) {
Point worldPoint = pointTransform->LocalToWorld(Point(x-piece->pivotX,y-piece->pivotY));
for (int i=0; i<collisionPoints.size(); i++) {
if (collisionPoints[i] == worldPoint) return true;
}
}
}
}
}
return false;
}
|
447cfd009185918c16307f2370b0a159e0613ea0 | 2de9fc07794686798ab7c11fddab2bb1ed852f92 | /graphicPatternClass.cpp | 60582b6c0cd7bdbc2f30f8786b2f0fbc01a7c8c6 | [] | no_license | Takagi-Waluigi/Sound-Graphics | 1e999a3bdd457df7e13d2153d2652eadcb39f4f5 | 83a74a705377b6e9ca355b21ef5fa46c0e7279cd | refs/heads/master | 2022-12-19T08:31:25.773311 | 2020-09-28T02:10:43 | 2020-09-28T02:10:43 | 299,159,318 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,349 | cpp | graphicPatternClass.cpp | // Created by 高木健太 on 2020/08/17.
//
#include "graphicPatternClass.hpp"
//--------------------------------------------------------------
void GraphicsPattern::init_shapeGrid(int beginPos){
B_posZ = beginPos;
}
void GraphicsPattern::draw_shapeGrid(int n, float speed, float size){
float radius = ofMap(B_posZ, 0, 1000, 0, 50) * size;
float alpha = ofMap(B_posZ, 0, 2000, 0, 255);
ofSetColor(200, 0, 0, alpha);
for(int x = -ofGetWidth()/2; x < ofGetWidth()/2; x += 40){
for(int y = -ofGetHeight()/2; y < ofGetHeight()/2; y += 40){
shapeMaker(n, ofVec3f(x, y, B_posZ), radius);
}
}
B_posZ += speed;
if (B_posZ > 1000) {
B_posZ = 0;
}
}
//--------------------------------------------------------------
void GraphicsPattern::bordreLine(float speed, float input_max){
ofSetRectMode(OF_RECTMODE_CENTER);
lineAlpha = ofMap(line_w, 0, 500, 255, 0);
ofSetColor(lineAlpha);
if(isLineDisplay){
ofDrawRectangle(line_beginPos, 0, line_w, ofGetHeight());
line_w += speed;
}
if(line_w > 500){
line_w = 0;
isLineDisplay = false;
}
if(isLineDisplay == false){
line_beginPos = ofRandom(-ofGetWidth()/2, ofGetWidth()/2);
isLineDisplay = true;
}
}
//--------------------------------------------------------------
void GraphicsPattern::init_Rings(){
rings_time = 0;
}
void GraphicsPattern::update_Rings(){
rings_time ++;
}
void GraphicsPattern::draw_Rings(int num, float radius, float speed, float maxR, float ampInput){
ofPushMatrix();
float offset = ofNormalize(radius, 0, maxR);
ofRotateYDeg(rings_time * speed * offset);
ofRotateXDeg(rings_time * speed * (1 -offset));
ofRotateZDeg(rings_time * speed * offset * 0.5);
shapeMaker(num, ofVec3f(0, 0, 0), radius * ampInput);
ofPopMatrix();
}
//--------------------------------------------------------------
void GraphicsPattern::init_imageDistortion(){
for(int i=0; i<25; i++){
fileName[i]= "images/city/city" + ofToString(i + 1) + ".jpg";
imgs[i].load(fileName[i]);
imgs[i].resize(ofGetWidth(), ofGetHeight());
}
img_amp = ofVec3f(100.0, 100.0, 300.0);
imageNum = (int)ofRandom(1, 25);
img_time = 0;
}
void GraphicsPattern::update_imageDistortion(){
for(int i = 0; i < 25; i ++){
imgs[i].resize(ofGetWidth(), ofGetHeight());
}
imageNum = ((ofGetFrameNum() + imageNum) / 60) % 25;
img_time ++;
if((img_time / 60) % 25 == 0){
img_amp += 1.5;
}
}
void GraphicsPattern::draw_imageDistortion(float amp, float inputAmp, float threshold, float spread, float freq){
ofPushMatrix();
ofMesh particle;
img_amp = ofVec3f(amp, amp, amp);
ofDisableBlendMode();
particle.setMode(OF_PRIMITIVE_POINTS);
glPointSize(1);
for(int x = 0; x < imgs[imageNum].getWidth(); x += 4){
for(int y = 0; y < imgs[imageNum].getHeight(); y += 4){
ofColor col = imgs[imageNum].getColor(x, y);
float noise = ofNoise(x, y);
drop = ofMap(col.getBrightness(), 0, 255, 1, 30);
slip.x = ofMap(col.getBrightness(), 0, 255, -PI, PI);
slip.y = ofMap(col.getBrightness(), 0, 255, -PI, PI);
slip.z = ofMap(col.getBrightness(), 0, 255, 0, 8 * PI);
wave.x = img_amp.x * (cos(TWO_PI * 8 * sin(img_time * freq - slip.x)) + sin( TWO_PI * 8 * sin(img_time * 0.0005 - slip.x)));
wave.y = img_amp.y * (sin(TWO_PI * 8 * sin(img_time * freq - slip.y)) - cos(TWO_PI * 8 * sin(img_time * 0.0005 - slip.y)));
wave.z = img_amp.z * cos(TWO_PI * cos(img_time * freq - slip.z));
float d = ofDist(imgs[imageNum].getWidth()/2, imgs[imageNum].getHeight()/2, x, y);
float distOffset = ofNormalize(d, 0, ofDist(0, 0, imgs[imageNum].getWidth()/2, imgs[imageNum].getHeight()/2)) + 1.0;
pos.x = -(x - ofGetWidth()/2) * spread * distOffset;
pos.y = -((ofGetHeight() - y) - ofGetHeight()/2) * spread * distOffset;
pos.z = ofMap(col.getBrightness(), 0, 255, 0, 0) - 500;
float dropY = pos.y;
dropY -= drop;
//音の大きさによって彩度を変化させる
float saturation = ofMap(inputAmp, 0.0, 1.0, 120, 255);
col.setSaturation(saturation);
particle.addColor(col);
particle.addVertex(pos + wave);
}
}
ofEnableBlendMode(OF_BLENDMODE_SCREEN);
particle.draw();
ofPopMatrix();
}
void GraphicsPattern::draw_imageDistortionB(float threshold, float amp){
for (int x = 0; x < imgs[imageNum].getWidth(); x += 5) {
for(int y = 0; y < imgs[imageNum].getHeight(); y += 5){
int brightness = imgs[imageNum].getColor(x, y).getBrightness() / 2;
ofColor col = ofColor(brightness, brightness, brightness);
if (amp > threshold) {
col = ofColor(brightness, brightness, brightness);
}else{
col.setBrightness(0);
}
ofSetColor(col);
float difference = ofMap(x, 0, imgs[imageNum].getWidth(), 0, TWO_PI * 4);
ofDrawRectangle(x - ofGetWidth()/2, (-y + ofGetHeight()/2) + (img_time * 0.005) * sin(ofGetFrameNum() * 0.005 - difference), 10, 10);
}
}
}
//--------------------------------------------------------------
void GraphicsPattern::draw_redCross(float inputAmp, float speed){
int lineH = 240;
//ofEnableBlendMode(OF_BLENDMODE_SCREEN);
for (int i = 0; i < lineH; i ++) {
float amp = ofMap(abs(i - lineH), 0, lineH / 2, 50, 5);
float freq = ofMap(abs(i - lineH), 0, lineH / 2, 10, 6);
float bri = ofMap(abs(i - lineH / 2), 0, lineH / 2, 255, 0);
float slip = ofMap(i, 0, lineH, 0.0, TWO_PI);
draw_simpleWave(amp * inputAmp, ofGetFrameNum() * speed, PI * freq, slip, (i - lineH / 2) );
ofPushMatrix();
ofRotateZRad(HALF_PI);
draw_simpleWave(amp * inputAmp, ofGetFrameNum() * speed, PI * freq, slip, (i - lineH / 2) );
ofPopMatrix();
}
ofDisableBlendMode();
}
//--------------------------------------------------------------
void GraphicsPattern::init_fallingDown(){
fall_pos.x = ofRandom(-ofGetWidth()/2, ofGetWidth()/2);
fall_pos.y = ofRandom(-ofGetHeight()/2, ofGetHeight()/2);
fall_pos.z = ofRandom(0, -300);
isDisplay = true;
}
void GraphicsPattern::update_fallingDown(){
if (isDisplay == false) {
fall_pos.x = ofRandom(-ofGetWidth()/2, ofGetWidth()/2);
fall_pos.y = ofGetHeight() / 2 - 50;
fall_pos.z = ofRandom(0, -300);
isDisplay = true;
}
}
void GraphicsPattern::draw_fallingDown(float fall_speed){
ofMesh point;
point.setMode(OF_PRIMITIVE_LINES);
point.addVertex(fall_pos);
point.addVertex(ofVec3f(fall_pos.x, fall_pos.y + 50, fall_pos.z));
if (isDisplay == true) {
fall_pos.y -= fall_speed;
point.draw();
}
if (fall_pos.y < -ofGetHeight() / 2 - 100) {
isDisplay = false;
}
}
//--------------------------------------------------------------
void GraphicsPattern::init_breaking(float initX, float initY, float size){
debrisPos.x = initX;
debrisPos.y = initY;
debrisPos.z = 0;
debrisSize = size;
beginAngle = ofRandom(TWO_PI);
isDebrisDisplay = true;
}
void GraphicsPattern::update_breaking(){
float dist = ofDist(0, 0, debrisPos.x, debrisPos.y);
float theta = atan2(debrisPos.y, debrisPos.x);
float offset = ofMap(pow(dist, 2), 0, pow(ofDist(0, 0, ofGetWidth()/2, ofGetHeight()/2), 2), 10.0, 4.0);
if(debrisPos.x < 0){
debrisSp.x = -offset;
}else{
debrisSp.x = offset;
}
debrisSp.y = tan(theta) * debrisSp.x;
debrisSp.y -= 5.0;
debrisPos += debrisSp;
}
void GraphicsPattern::draw_breaking(){
ofSetColor(208, 234, 237, 128);
ofPushMatrix();
ofTranslate(debrisPos);
if (debrisPos.x > 0 && debrisPos.y > 0) {
ofRotateXRad(ofGetFrameNum() * 0.07 - beginAngle);
ofRotateYRad(ofGetFrameNum() * 0.07 - beginAngle);
}else if (debrisPos.x > 0 && debrisPos.y < 0){
ofRotateXRad(ofGetFrameNum() * 0.07 - beginAngle);
ofRotateYRad(ofGetFrameNum() * (-0.07) - beginAngle);
}else if (debrisPos.x < 0 && debrisPos.y > 0){
ofRotateXRad(ofGetFrameNum() * (-0.07) - beginAngle);
ofRotateYRad(ofGetFrameNum() * 0.07 - beginAngle);
}else{
ofRotateXRad(ofGetFrameNum() * (-0.07) - beginAngle);
ofRotateYRad(ofGetFrameNum() * (-0.07) - beginAngle);
}
ofSetRectMode(OF_RECTMODE_CENTER);
if (debrisPos.x < ofGetWidth()/2 && debrisPos.x > -ofGetWidth()/2
&& debrisPos.y < ofGetHeight()/2 && debrisPos.y > -ofGetHeight()/2) {
ofDrawRectangle(0, 0, debrisSize, debrisSize);
}else{
isDebrisDisplay = false;
}
ofPopMatrix();
ofSetRectMode(OF_RECTMODE_CORNER);
}
//--------------------------------------------------------------
void GraphicsPattern::init_activeMap(float initZ, float initNum, int initInterval){
mapImg.load("images/map01.png");
mapImg.resize(ofGetWidth(), ofGetHeight());
for (int i = 0; i < 27; i ++) {
string fileName = "images/map/map" + ofToString(i + 1) + ".png";
mapImgs[i].load(fileName);
mapImgs[i].resize(ofGetWidth(), ofGetHeight());
}
mapImgNum = initNum;
globMapPos.z = initZ;
mapImgInterval = initInterval;
}
void GraphicsPattern::update_activeMap(){
if (globMapPos.z > (ofGetHeight()/2 + ofGetHeight())){
mapImgNum += mapImgInterval;
globMapPos.z = - (ofGetHeight()/2 + ofGetHeight() * mapImgInterval/2);
}
globMapPos.z += mapSpeed;
}
void GraphicsPattern::draw_activeMap(float amp, ofVec3f pos, float angle){
ofPushMatrix();
ofRotateXDeg(angle);
globMapPos.x = pos.x;
globMapPos.y = pos.y;
ofTranslate(globMapPos);
for (int x = 0; x < mapImg.getWidth(); x += 8) {
for (int y = 0; y < mapImg.getHeight(); y += 8) {
float noise = ofNoise(x, y);
float differeence = ofMap(noise, 0.0, 1.0, -TWO_PI, TWO_PI);
ofColor col = mapImgs[mapImgNum % 27].getColor(x, y);
mapPos = ofVec3f(x - ofGetWidth()/2, 0, y - mapImg.getHeight()/2);
int red = col.r;
int green = col.g;
int blue = col.b;
float ampCalcY = ofMap(amp, 0.0, 0.5, 0.0, 180.0) * noise;
if (col.r < 240 && col.g < 240 && col.b < 240) {
//ofSetColor(200, 200, 200);
//shapeMaker(8, mapPos, amp * 20);
ofSetColor(col);
ofEnableBlendMode(OF_BLENDMODE_SCREEN);
ofEnableDepthTest();
ofPushMatrix();
ofTranslate(mapPos);
ofRotateXRad(ofGetFrameNum() * 0.05 - differeence);
ofRotateYRad(ofGetFrameNum() * 0.05 - differeence);
ofDrawBox(0, 0, 0, 3, ampCalcY, 3);
ofPopMatrix();
}
}
}
ofPopMatrix();
}
//--------------------------------------------------------------
void GraphicsPattern::init_face(){
faceImg.load("images/b.JPG");
faceImg.resize(ofGetWidth(), ofGetHeight() * 0.7);
}
void GraphicsPattern::draw_face(){
for (int x = 0; x < faceImg.getWidth(); x += 18) {
for (int y = 0; y < faceImg.getHeight(); y += 18) {
ofColor col = faceImg.getColor(x, y);
float difference = ofMap(x * y, 0, faceImg.getWidth() * faceImg.getHeight(),-PI, PI);
float radius = ofMap(col.getBrightness(), 0, 255, 3, 8)/2 * cos(ofGetFrameNum() * 0.01 - PI) + ofMap(col.getBrightness(), 0, 255, 3, 8) * 1.5;
col.setBrightness(100);
ofSetColor(col);
ofDrawEllipse(x - faceImg.getWidth()/2, -(y - faceImg.getHeight()/2), radius, radius);
col.setBrightness(150);
ofSetColor(col);
shapeMaker(6, ofVec3f(x - faceImg.getWidth()/2, -(y - faceImg.getHeight()/2), 0), radius);
}
}
}
//--------------------------------------------------------------
void GraphicsPattern::draw_simpleWave(float amp, float speed, float width, float slip, float y_offset){
ofMesh particleWave;
particleWave.setMode(OF_PRIMITIVE_POINTS);
for (int x = -ofGetWidth()/2; x < ofGetWidth()/2; x += 10) {
float theta = ofMap(x, -ofGetWidth()/2, ofGetWidth()/2, -width/2, width);
ofVec3f posA;
posA.x = x;
posA.y = amp * sin(theta - ofGetFrameNum() * 0.005 * speed - slip) + y_offset;
posA.z = amp * cos(theta - ofGetFrameNum() * 0.005 * speed);
ofVec3f posB;
posB.x = x;
posB.y = amp * cos(theta + ofGetFrameNum() * 0.005 * speed - slip) + y_offset;
posB.z = amp * cos(theta - ofGetFrameNum() * (0.005 * speed) - PI);
ofDrawLine(posA, posB);
}
}
//--------------------------------------------------------------
void GraphicsPattern::shapeMaker(int n, ofVec3f pos, float radius){
ofMesh vert;
vert.setMode(OF_PRIMITIVE_LINE_STRIP);
for(float angle = 0; angle < TWO_PI; angle += TWO_PI/n){
float x = radius * cos(angle) + pos.x;
float y = radius * sin(angle) + pos.y;
vert.addVertex(ofVec3f(x, y, pos.z));
}
vert.draw();
}
//--------------------------------------------------------------
void GraphicsPattern::drawWavingPlane(){
ofMesh points;
for (int x = 0; x < 40; x ++) {
for (int y = 0; y < 30; y ++) {
wavePoint[y + x * 30].x = (x - 20) * 100;
wavePoint[y + x * 30].z = (y - 15) * 100;
float thetaX = ofMap(wavePoint[y + x * 30].x, -2000, 2000, -TWO_PI, TWO_PI);
float thetaY = ofMap(wavePoint[y + x * 30].z, -1500, 1500, -TWO_PI, TWO_PI);
wavePoint[y + x * 30].y = 100 * (sin(thetaX - ofGetFrameNum() * 0.005) + cos(thetaY - ofGetFrameNum() * 0.005));
points.addVertex(wavePoint[y + x * 30]);
}
}
points.draw();
for (int i = 0; i < 1200; i ++) {
for(int j = 0; j < 1200; j ++){
if (i != j) {
float dist = ofDist(wavePoint[i].x, wavePoint[i].y, wavePoint[i].z, wavePoint[j].x, wavePoint[j].y, wavePoint[j].z);
if (dist < 200) {
ofDrawLine(wavePoint[i], wavePoint[j]);
}
}
}
}
}
//--------------------------------------------------------------
void GraphicsPattern::draw_flash(float threShold, float amp){
if (threShold < amp) {
ofSetColor(255, 255, 255, 128);
ofDrawRectangle(-ofGetWidth()/2, -ofGetHeight()/2, ofGetWidth(), ofGetHeight());
}
}
//--------------------------------------------------------------
void GraphicsPattern::draw_rects(float n, ofColor col){
ofPushMatrix();
ofNoFill();
ofSetColor(col);
ofSetRectMode(OF_RECTMODE_CENTER);
ofRotateZDeg(45);
for (int i = 0; i < n; i ++) {
ofDrawRectangle(0, 0, 750 + i * 30, 750 + i * 30);
}
ofPopMatrix();
ofFill();
ofSetRectMode(OF_RECTMODE_CORNER);
}
void GraphicsPattern::flashLight(float radius, float npow){
for (int x = -ofGetWidth()/2; x < ofGetWidth()/2; x +=2) {
for (int y = -ofGetHeight()/2; y < ofGetHeight()/2; y += 2) {
float d = ofDist(0, 0, x, y);
float alpha = ofMap(pow(d, npow), 0, pow(radius, npow), 255, 0);
ofSetColor(alpha);
ofDrawRectangle(x, y, 2, 2);
}
}
}
|
69f0688431e2efc5a45f64ccb63d0050e65d13b8 | 5d6f3330bc5699134eacaf46267feab9708ddb19 | /webrtc-jni/src/main/cpp/include/media/video/VideoDeviceManager.h | 95d92adbf347256cdc2d6fe61023cfc8cc5b7a61 | [
"BSD-3-Clause",
"DOC",
"LicenseRef-scancode-html5",
"Apache-2.0"
] | permissive | devopvoid/webrtc-java | ca0549864591e000a63ed95055646ed54264426c | 682a40187f653613eefb0a51ac4337781ce15ff6 | refs/heads/master | 2023-05-02T11:06:46.538322 | 2023-01-16T17:04:54 | 2023-01-16T17:04:54 | 224,890,850 | 203 | 56 | Apache-2.0 | 2023-01-01T20:41:51 | 2019-11-29T16:41:25 | C++ | UTF-8 | C++ | false | false | 1,656 | h | VideoDeviceManager.h | /*
* Copyright 2019 Alex Andres
*
* 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.
*/
#ifndef JNI_WEBRTC_MEDIA_VIDEO_DEVICE_MANAGER_H_
#define JNI_WEBRTC_MEDIA_VIDEO_DEVICE_MANAGER_H_
#include "media/DeviceManager.h"
#include "media/DeviceList.h"
#include "media/video/VideoDevice.h"
#include "media/video/VideoCaptureCapability.h"
#include "modules/video_capture/video_capture_defines.h"
#include <mutex>
#include <set>
namespace jni
{
namespace avdev
{
using VideoDevicePtr = std::shared_ptr<VideoDevice>;
class VideoDeviceManager : public DeviceManager
{
public:
VideoDeviceManager();
virtual ~VideoDeviceManager() {};
VideoDevicePtr getDefaultVideoCaptureDevice();
virtual std::set<VideoDevicePtr> getVideoCaptureDevices() = 0;
virtual std::set<VideoCaptureCapability> getVideoCaptureCapabilities(const VideoDevice & device) = 0;
protected:
void setDefaultCaptureDevice(VideoDevicePtr device);
VideoDevicePtr getDefaultCaptureDevice();
protected:
DeviceList<VideoDevicePtr> captureDevices;
private:
VideoDevicePtr defaultCaptureDevice;
std::mutex mutex;
};
}
}
#endif |
35db8ec55bb0e763e9c6c56d21a5db873444c3d9 | 0c0a9f99c6431206e5fcbf6f9fd44b7abfad296c | /tools-dl-cv/useful_examples/code/ssd_call.cpp | 57235fd8990d6da4c0c0b14c35854e241a71c155 | [
"MIT"
] | permissive | magic428/work_note | 05c61f7912c43da1ddba42f36961ab23da46b476 | d1ca27e86eaf35ab1812e1b607bc127268ded49e | refs/heads/master | 2020-09-03T09:16:38.413938 | 2020-03-31T02:50:22 | 2020-03-31T02:50:22 | 98,979,753 | 6 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 9,330 | cpp | ssd_call.cpp | #include <fstream>
#include <iostream>
#include <cv.h>
#include <highgui.h>
#include <classification.h>
using namespace cv;
using namespace std;
#define HAS_VIDEO
struct DetectObjectInfo{
float xmin, ymin, xmax, ymax;
float score;
int label;
const Rect rect() const{
return Rect(xmin, ymin, xmax - xmin, ymax - ymin);
}
};
float IoU(const Rect& a, const Rect& b){
float xmax = max(a.x, b.x);
float ymax = max(a.y, b.y);
float xmin = min(a.x + a.width, b.x + b.width);
float ymin = min(a.y + a.height, b.y + b.height);
float uw = (xmin - xmax + 1 > 0) ? (xmin - xmax + 1) : 0;
float uh = (ymin - ymax + 1 > 0) ? (ymin - ymax + 1) : 0;
float iou = uw * uh;
return iou / min(a.area(), b.area());
}
vector<string> loadLabels(const char* labelsFile){
ifstream fin(labelsFile);
vector<string> out;
string s;
while (fin >> s)
out.push_back(s);
return out;
}
vector<DetectObjectInfo> toDetInfo(BlobData* fr, int imWidth, int imHeight){
const float Scorethreshold = 0.2;
vector<DetectObjectInfo> out;
float* data = fr->list;
for (int i = 0; i < fr->count; i += 7, data += 7){
DetectObjectInfo obj;
//if invalid det
if (data[0] == -1 || data[2] < Scorethreshold)
continue;
obj.label = data[1];
obj.score = data[2];
obj.xmin = data[3] * imWidth;
obj.ymin = data[4] * imHeight;
obj.xmax = data[5] * imWidth;
obj.ymax = data[6] * imHeight;
out.push_back(obj);
}
return out;
}
Scalar getColor(int label){
static vector<Scalar> colors;
if (colors.size() == 0){
#if 0
for (float r = 127.5; r <= 256 + 127.5; r += 127.5){
for (float g = 256; g >= 0; g -= 127.5){
for (float b = 0; b <= 256; b += 127.5)
colors.push_back(Scalar(b, g, r > 256 ? r - 256 : r));
}
}
#endif
colors.push_back(Scalar(0, 255, 0));
colors.push_back(Scalar(0, 0, 255));
colors.push_back(Scalar(255, 0, 0));
colors.push_back(Scalar(0, 255, 255));
colors.push_back(Scalar(255, 0, 255));
colors.push_back(Scalar(128, 0, 255));
colors.push_back(Scalar(128, 255, 255));
colors.push_back(Scalar(255, 128, 255));
colors.push_back(Scalar(128, 255, 128));
}
return colors[label % colors.size()];
}
bool fileExists(const char* file){
FILE* f = fopen(file, "rb");
if (f == 0) return false;
fclose(f);
return true;
}
float cosdis(const float* a, const float* b, int len){
float x = 0;
float y = 0;
float z = 0;
for (int i = 0; i < len; ++i){
x += a[i] * a[i];
y += b[i] * b[i];
z += a[i] * b[i];
}
float t = (sqrt(x) * sqrt(y));
if (t == 0) return 0;
return z / t;
}
float cosdis(const uchar* a, const uchar* b, int len){
long x = 0;
long y = 0;
long z = 0;
for (int i = 0; i < len; ++i){
x += a[i] * a[i];
y += b[i] * b[i];
z += a[i] * b[i];
}
float t = 0.0;
if (x > 0 && y > 0)
t = (sqrt(x) * sqrt(y));
if (t == 0 || z <= 0 || z >= t ) return 0;
return z / t;
}
float average(vector<float> &sm)
{
float sum = 0;
int valid = 0;
if (!sm.empty())
{
for (int i = 0; i < sm.size(); i++){
if (sm[i] - 0.7 > 0){
valid++;
sum += sm[i];
}
}
}
if (valid == 0) return 0;
return sum / valid;
}
int main(int argc, char * argv)
{
char caffeModel[256] = "E:/vs_workspace/generalTemplate/VGG_VOC0712_SSD_300x300_iter_80000.caffemodel";
char deployPrototxt[256] = "E:/vs_workspace/generalTemplate/deploy.prototxt";
char labels[256] = "E:/vs_workspace/generalTemplate/labels.txt";
vector<string> labelMap = loadLabels(labels);
float means[] = { 104.0f, 117.0f, 123.0f };
Classifier classifier(deployPrototxt, caffeModel, 1, 0, 3, means, 0);
//float means[] = { 123, 117, 104 };
Classifier cls("deploy_resnet101-v2.prototxt", "resnet-101_iter_5000.caffemodel", 1, 0, 3, means, 0);
vector<Mat> imgSet;
Mat img;
string preName = "00010";
char name[256];
for (int i = 2; i < 39; i++){
sprintf(name, "templet/%s%02d.jpg", preName.c_str(), i);
img = imread(name);
if (img.data)
imgSet.push_back(img);
if (imgSet.size() <= 0)
return -1;
}
#if 1
#ifdef HAS_VIDEO
VideoCapture cap("jiHuo.avi");
#else
//HK_Camera hkCamera;
//hkCamera.open();
//frame = hkCamera.getImg();
VideoCapture cap(0);
#endif
WPtr<BlobData> feature;
vector<DetectObjectInfo> objs;
// 处理视频流数据
cv::Mat frame;
cv::Mat detectROI;
cap >> frame;
vector<float> sm;
while (1)
{
if (frame.empty()){
continue;
}
cap >> frame;
feature = classifier.extfeature(frame, "detection_out");
objs = toDetInfo(feature, frame.cols, frame.rows);
// First frame, give the groundtruth to the tracker
for (size_t i = 0; i < objs.size(); i++)
{
auto obj = objs[i];
//cout << obj.label << endl; // 因为第一个label是背景,第二个label是饮料;
rectangle(frame, obj.rect(), getColor(obj.label), 2);
auto box = obj.rect();
box = box & Rect(0, 0, frame.cols, frame.rows);
if (box.width > 0 && box.height > 0){
// 在冰柜的检测区域内
if (box.x > 200 && box.x < 400){
frame(box).copyTo(detectROI);
int len = 0;
for (int i = 0; i < imgSet.size(); i++){
resize(detectROI, detectROI, imgSet[i].size(), 0);
len = imgSet[i].cols*imgSet[i].rows * imgSet[i].channels();
if (imgSet[i].size() == detectROI.size())
sm.push_back(cosdis(detectROI.data, imgSet[i].data, len));
}
cout << "cosdis=" << average(sm) << endl;
imshow("roi", detectROI);
}
}
//Mat im1 = imread("492846.jpg");
//WPtr<BlobData> feature1 = cls.extfeature(im1, "pool5");
//WPtr<BlobData> feature2 = cls.extfeature(im2, "pool5");
//WPtr<SoftmaxResult> feature1 = cls.predictSoftmax(dectectROI, 1);
//float sm = cosdis(dectectROI.data, imgSet[2].data, imgSet[2].data);
//paDrawString(frame, labelMap[obj.label].c_str(), Point(obj.xmin, obj.ymin - 20), getColor(obj.label), 20, true);
}
line(frame, Point(200, 0), Point(200, frame.rows), Scalar(255, 0, 255), 2);
line(frame, Point(400, 0), Point(400, frame.rows), Scalar(255, 0, 255), 2);
imshow("Image", frame);
waitKey(1);
}
#endif
return 0;
}
int main(int argc, char * argv)
{
char caffeModel[256] = "E:/vs_workspace/generalTemplate/VGG_VOC0712_SSD_300x300_iter_80000.caffemodel";
char deployPrototxt[256] = "E:/vs_workspace/generalTemplate/deploy.prototxt";
char labels[256] = "E:/vs_workspace/generalTemplate/labels.txt";
vector<string> labelMap = loadLabels(labels);
float means[] = { 104.0f, 117.0f, 123.0f };
Classifier classifier(deployPrototxt, caffeModel, 1, 0, 3, means, 0);
//float means[] = { 123, 117, 104 };
Classifier cls("deploy_resnet101-v2.prototxt", "resnet-101_iter_5000.caffemodel", 1, 0, 3, means, 0);
vector<Mat> imgSet;
Mat img;
string preName = "00010";
char name[256];
for (int i = 2; i < 39; i++){
sprintf(name, "templet/%s%02d.jpg", preName.c_str(), i);
img = imread(name);
if (img.data)
imgSet.push_back(img);
if (imgSet.size() <= 0)
return -1;
}
#if 1
#ifdef HAS_VIDEO
VideoCapture cap("jiHuo.avi");
#else
//HK_Camera hkCamera;
//hkCamera.open();
//frame = hkCamera.getImg();
VideoCapture cap(0);
#endif
WPtr<BlobData> feature;
vector<DetectObjectInfo> objs;
// 处理视频流数据
cv::Mat frame;
cv::Mat detectROI;
cap >> frame;
vector<float> sm;
while (1)
{
if (frame.empty()){
continue;
}
cap >> frame;
feature = classifier.extfeature(frame, "detection_out");
objs = toDetInfo(feature, frame.cols, frame.rows);
// First frame, give the groundtruth to the tracker
for (size_t i = 0; i < objs.size(); i++)
{
auto obj = objs[i];
//cout << obj.label << endl; // 因为第一个label是背景,第二个label是饮料;
rectangle(frame, obj.rect(), getColor(obj.label), 2);
auto box = obj.rect();
box = box & Rect(0, 0, frame.cols, frame.rows);
if (box.width > 0 && box.height > 0){
// 在冰柜的检测区域内
if (box.x > 200 && box.x < 400){
frame(box).copyTo(detectROI);
int len = 0;
for (int i = 0; i < imgSet.size(); i++){
resize(detectROI, detectROI, imgSet[i].size(), 0);
len = imgSet[i].cols*imgSet[i].rows * imgSet[i].channels();
if (imgSet[i].size() == detectROI.size())
sm.push_back(cosdis(detectROI.data, imgSet[i].data, len));
}
cout << "cosdis=" << average(sm) << endl;
imshow("roi", detectROI);
}
}
//Mat im1 = imread("492846.jpg");
//WPtr<BlobData> feature1 = cls.extfeature(im1, "pool5");
//WPtr<BlobData> feature2 = cls.extfeature(im2, "pool5");
//WPtr<SoftmaxResult> feature1 = cls.predictSoftmax(dectectROI, 1);
//float sm = cosdis(dectectROI.data, imgSet[2].data, imgSet[2].data);
//paDrawString(frame, labelMap[obj.label].c_str(), Point(obj.xmin, obj.ymin - 20), getColor(obj.label), 20, true);
}
line(frame, Point(200, 0), Point(200, frame.rows), Scalar(255, 0, 255), 2);
line(frame, Point(400, 0), Point(400, frame.rows), Scalar(255, 0, 255), 2);
imshow("Image", frame);
waitKey(1);
}
#endif
return 0;
}
|
5b0c5d837c74bf7fbb131616f91e6becb9f33802 | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir7941/dir29315/dir34534/file34597.cpp | cfa91abd44d6af1d2f0f1182702e7733c326402e | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | file34597.cpp | #ifndef file34597
#error "macro file34597 must be defined"
#endif
static const char* file34597String = "file34597"; |
22784e7e1eddc6efd8cdacc2a45d86cc13a36520 | 1b5881e83c213d1e61e9b424714993c8b7cbb18f | /Arrays/q3.cpp | cf2df1e6a4d20e902e05600048e7c2054c885432 | [] | no_license | srajan-code-heaven/coding_interview_preparation | 228c8e0029938835e529ad73ee774fa1ae1a80f0 | afffc3757026c09651801da05ea17f3c0b41a673 | refs/heads/master | 2021-07-20T17:52:45.947272 | 2021-06-20T06:41:36 | 2021-06-20T06:41:36 | 240,834,614 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 476 | cpp | q3.cpp | //Find the Number Occurring Odd Number of Times
#include <bits/stdc++.h>
using namespace std;
void getOddOccurrence(int A[],int arr_size)
{
unordered_map<int,int> m;
int maj;
for(int i=0;i<arr_size;i++)
{
m[A[i]]++;
}
for(auto i:m)
{
if(i.second%2!=0)
{
cout<<i.first<<" ";
}
}
}
int main()
{
int A[]={ 2, 3, 5, 4, 5, 2, 4,3, 5, 2, 4, 4, 2 };
int arr_size=sizeof(A)/sizeof(int);
getOddOccurrence(A,arr_size);
}
|
1d76498236f3263bb337d6b17b72be3d2a7ddf4c | 2962f164cecb440ecd905ab9f3cc569c03a01ad5 | /RtspPlayer/assemblies/sunell/include/FisheyeVideoLayout.h | 835b906340c30c8af2d3da15269afa063afeccd5 | [] | no_license | paxan222/hello-world | 5ef9bd04a5c4337c1403a04973e2c0c11665bb26 | c55c60e0f72a04e1e2560dc19c2a6bbd7e8b430f | refs/heads/master | 2020-12-11T21:09:30.200433 | 2017-05-04T08:39:53 | 2017-05-04T08:39:53 | 55,044,669 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 2,443 | h | FisheyeVideoLayout.h | #ifndef _FISHEYE_VIDEO_LAYOUT_H_
#define _FISHEYE_VIDEO_LAYOUT_H_
#include "SNPlatOS.h"
#include "VideoRect.h"
#include <vector>
using namespace std;
/**********************************************************************/
//此处用于控制文件编译字节对齐,拷贝时两行注释间内容需一起拷贝,
//结束处的“#ifdef PRAGMA_PACK”部分也要一起拷贝,否则pragma pack入栈出栈不匹配
#if(PRAGMA_PACK_DEFINE != 10000)
# error Not included "SNPlatOS.h".
#endif
#ifdef PRAGMA_PACK
#ifdef WIN32
#pragma pack(push, PRAGMA_PACK_CHAR)
#endif
#ifndef WIN32
#ifndef _PACKED_1_
#define _PACKED_1_ __attribute__((packed, aligned(PRAGMA_PACK_CHAR))) // for gcc
#endif
#else
#ifndef _PACKED_1_
#define _PACKED_1_
#endif
#endif
#else
#ifndef _PACKED_1_
#define _PACKED_1_
#endif
#endif
/**********************************************************************/
class SN_DLL_API FisheyeVideoLayout
{
public:
FisheyeVideoLayout();
~FisheyeVideoLayout();
public:
//安装模式
void setCameraId(const int p_nCameraId);
const int getCameraId()const;
//安装模式
void setVideoRectList(const std::vector<VideoRect> &p_objVideoRectList);
void getVideoRectList(std::vector<VideoRect> &p_objVideoRectList)const;
/************************************************************************
**概述:两个对象判等操作
*
**输入:
* p_objRhs:判等操作右操作符
**输出:
* 无
**返回值:
* 相等返回true, 不等返回false
*************************************************************************/
bool operator == (const FisheyeVideoLayout& p_objRhs);
/************************************************************************
**概述:赋值操作
*
**输入:
* p_objRhs:赋值操作右操作符
**输出:
* 无
**返回值:
* 返回FisheyeVideoLayout对象的引用
*************************************************************************/
FisheyeVideoLayout& operator =(const FisheyeVideoLayout& objRhs);
private:
int m_nCameraId; //通道号
std::vector<VideoRect> m_nVideoRectList; //鱼眼、全景或PTZ显示区域
}_PACKED_1_;
/**********************************************************************/
#ifdef PRAGMA_PACK
#ifdef WIN32
#pragma pack(pop)
#endif
#endif
/**********************************************************************/
#endif //_FISHEYE_VIDEO_LAYOUT_H_ |
c06976bc438960ba4eb30ce3f1b4462dc4030217 | f041d395412a30685217e7a5687d1bbbb02ff7bc | /include/GameEntity.h | 605d9a49640f394008b1d647a92feb260e99bb78 | [] | no_license | AndrzejTM/atm_core_gry_armaty4 | 9e956eb576cf29c456644cb237287ff1201c19f6 | a29d9897b2840051e6dc4384bca6b8b348396693 | refs/heads/master | 2020-04-01T06:16:15.462224 | 2018-10-14T04:56:11 | 2018-10-14T04:56:11 | 152,940,332 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 552 | h | GameEntity.h | #ifndef OBIEKTGRY_H
#define OBIEKTGRY_H
#include <SFML/Graphics.hpp>
class GameEntity : public sf::Drawable
{
public:
GameEntity();
GameEntity(float x, float y);
virtual ~GameEntity();
sf::RectangleShape shape;
sf::RectangleShape pocisk;
sf::Vertex line[2];
double kat;
int moc;
void ruchArmata(double& kat, sf::Vertex&, sf::Vertex&);
protected:
private:
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
};
#endif // OBIEKTGRY_H
|
910584b5d9859b6da27383fba98e1b3206472bd7 | 3588147092dbbc182cfcdea1b0b86875489e39b6 | /cpp_base/derived/Cover.cpp | 68330278efb87634e6283d6ad87a49c7d6ceba6e | [] | no_license | hisan/cpp_study | 74ca7632ff604fd8b171bad644998b1f76c45a9a | 4cc1af6b0c42d46e9223ddf714c5b6b4defc65a6 | refs/heads/master | 2023-04-06T09:54:45.835682 | 2021-04-19T16:06:43 | 2021-04-19T16:06:43 | 356,827,591 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 643 | cpp | Cover.cpp | #include <iostream>
using namespace std;
class Base
{
public:
void func();
void func(int);
};
void Base::func(){cout<<"Base::func()"<<endl;}
void Base::func(int a){cout<<"Base::func(int)"<<endl;}
class Derived:public Base
{
public:
void func();
void func(bool);
};
void Derived::func(){cout<<"Derived::func()"<<endl;}
void Derived::func(bool flag){cout<<"Derived::func(bool)"<<endl;}
int main()
{
Derived d;
d.func();
d.func("c.biancheng.net");
d.func(true);
//d.func(); //compile error
//d.func(10); //compile error
d.Base::func();
d.Base::func(100);
return 0;
} |
2cc78e4ab00a471c0d9bbd3b3ecffe45d4ee3e21 | d327e106285776f28ef1d6c8a7f561b7f05763a6 | /SDL_EngineProject/以前的代码/PvZ1.0/Classses/BackgroundLayer.cpp | 8b86888cafc6d87d00075b270fd32715199bad46 | [] | no_license | sky94520/old-code | a4bb7b6826906ffa02f57151af2dc21471cf2106 | 6b37cc7a9338d283a330b4afae2c7fbd8aa63683 | refs/heads/master | 2020-05-03T12:37:48.443045 | 2019-07-23T00:38:16 | 2019-07-23T00:38:16 | 178,631,201 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,690 | cpp | BackgroundLayer.cpp | #include "BackgroundLayer.h"
#include "Lawn.h"
#include "MainLua.h"
BackgroundLayer::BackgroundLayer()
:m_pBG(nullptr),m_startPos(256,80),m_size(80,100)
,m_bDay(true),m_skillCD(0.f),m_elapsed(0.f)
,m_zombiePath("")
{
//初始化
for(int i=0;i<5;i++)
for(int j=0;j<9;j++)
m_pCarriers[i][j] = nullptr;
}
BackgroundLayer::~BackgroundLayer()
{
}
bool BackgroundLayer::init()
{
//todo
//创建载体
for(int i=0;i<5;i++)
{
for(int j=0;j<9;j++)
{
auto carrier = Lawn::create();
carrier->setPosition(m_startPos + Point(j*m_size.width,i*m_size.height));
this->addChild(carrier);
m_pCarriers[i][j] = carrier;
}
}
return true;
}
void BackgroundLayer::update(float dt)
{
}
void BackgroundLayer::loadLevel(const std::string&level)
{
MainLua::getInstance()->dofile(level.c_str());
std::string bg = MainLua::getInstance()->getStringFromTable("level","background");
m_bDay = MainLua::getInstance()->getBoolFromTable("level","bDay");
m_zombiePath = MainLua::getInstance()->getStringFromTable("level","filepath");
if(m_pBG)
m_pBG->removeFromParent();
m_pBG = Sprite::create(bg);
this->addChild(m_pBG);
this->setContentSize(m_pBG->getContentSize());
initSkillCD();
}
void BackgroundLayer::initSkillCD()
{
m_skillCD = MainLua::getInstance()->getDoubleFromTable("level","skillCD");
}
Carrier* BackgroundLayer::getCarrierByPos(const Point&pos)
{
//获取指定载体
int x = (pos.y - m_startPos.y)/m_size.height;
int y = (pos.x - m_startPos.x)/m_size.width;
//if()
return m_pCarriers[x][y];
}
Rect BackgroundLayer::getLegalRect()const
{
return Rect(m_startPos,Size(9*m_size.width,5*m_size.height));
}
bool BackgroundLayer::isDay()const
{
return m_bDay;
}
|
deebb7508c6a5b0883c576f1e60099d5dc01f5bf | 6d088ec295b33db11e378212d42d40d5a190c54c | /core/vgl/vgl_polygon_test.h | f96403e50455603cf21f7d5dfa448ab15a8da224 | [] | no_license | vxl/vxl | 29dffd5011f21a67e14c1bcbd5388fdbbc101b29 | 594ebed3d5fb6d0930d5758630113e044fee00bc | refs/heads/master | 2023-08-31T03:56:24.286486 | 2023-08-29T17:53:12 | 2023-08-29T17:53:12 | 9,819,799 | 224 | 126 | null | 2023-09-14T15:52:32 | 2013-05-02T18:32:27 | C++ | UTF-8 | C++ | false | false | 556 | h | vgl_polygon_test.h | // This is core/vgl/vgl_polygon_test.h
#ifndef vgl_polygon_test_h_
#define vgl_polygon_test_h_
//:
// \file
// \author fsm
// \verbatim
// Modifications
// Nov.2003 - Peter Vanroose - made function templated
// \endverbatim
//: return true iff (x, y) is inside (or on boundary of) the given n-gon.
// \relatesalso vgl_polygon
template <class T>
bool vgl_polygon_test_inside(T const *xs, T const *ys, unsigned n, T x, T y);
#define VGL_POLYGON_TEST_INSTANTIATE(T) extern "please include vgl/vgl_polygon_test.hxx instead"
#endif // vgl_polygon_test_h_
|
209a1621a88992bf3f420d10db464a7e8e06118c | 8d953b8783bc94e835b092c72370ff7f4ead90dc | /Source/Gunslinger/Public/Abilities/Shared/GA_RangedAttack.h | 9eb0106bfac75834da1809354b8f7c20438c0671 | [] | no_license | mvoitkevics/Gunslinger | c9c906f56f4be15e94d05aac87b75baea4a899a2 | e7ed0a8458416df0fdf87cd6a3af5b0b6decebe6 | refs/heads/master | 2023-06-01T03:18:42.895253 | 2021-06-28T10:43:52 | 2021-06-28T10:43:52 | 237,199,313 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,284 | h | GA_RangedAttack.h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Abilities/GunslingerGameplayAbility.h"
#include "GA_RangedAttack.generated.h"
class AGunslingerProjectile;
/**
*
*/
UCLASS()
class GUNSLINGER_API UGA_RangedAttack : public UGunslingerGameplayAbility
{
GENERATED_BODY()
public:
UGA_RangedAttack();
UPROPERTY(BlueprintReadOnly, EditAnywhere)
UAnimMontage* FireMontage;
UPROPERTY(BlueprintReadOnly, EditAnywhere)
TSubclassOf<AGunslingerProjectile> ProjectileClass;
UPROPERTY(BlueprintReadOnly, EditAnywhere)
TSubclassOf<UGameplayEffect> DamageGameplayEffect;
/** Actually activate ability, do not call this directly. We'll call it from APAHeroCharacter::ActivateAbilitiesWithTags(). */
virtual void ActivateAbility(const FGameplayAbilitySpecHandle Handle, const FGameplayAbilityActorInfo* ActorInfo, const FGameplayAbilityActivationInfo ActivationInfo, const FGameplayEventData* TriggerEventData) override;
protected:
UFUNCTION()
void OnCancelled(FGameplayTag EventTag, FGameplayEventData EventData);
UFUNCTION()
void OnCompleted(FGameplayTag EventTag, FGameplayEventData EventData);
UFUNCTION()
void EventReceived(FGameplayTag EventTag, FGameplayEventData EventData);
};
|
224ec44e756ac1c6d83f7544e6494a3d8c37ccb9 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_2645486_1/C++/chinoxyz/p2.cc | b089e2fb5561fdf13fad513ea22fb0b68c97aa9e | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,407 | cc | p2.cc | #include <cstdio>
#include <vector>
#include <cstring>
#include <map>
#include <cmath>
#include <iostream>
#include <queue>
#include <stack>
#include <set>
#include <algorithm>
using namespace std;
class par{
public:
int i;
int val;
bool operator<(const par &s) const {
return (val < s.val);
}
};
int T;
int E, R, N, val;
par p;
vector<int> v;
vector<par> v2;
vector<long long> r;
long long res;
int main(){
scanf("%d", &T);
for(int t = 0; t < T; t++){
scanf("%d %d %d", &E, &R, &N);
v.clear();
v2.clear();
r.clear();
r.push_back(E);
for(int i = 0; i < N; i++){
scanf("%d", &val);
v.push_back(val);
p.i = i;
p.val = val;
v2.push_back(p);
r.push_back(R);
}
sort(v2.begin(), v2.end());
reverse(v2.begin(), v2.end());
res = 0;
for(int i = 0; i < N; i++){
long long sum = E;
int j = v2[i].i;
while(sum > 0 && j >= 0){
int minimo = min(r[j], sum);
sum = sum - minimo;
r[j] = r[j] - minimo;
j--;
}
res += (E - sum)*v2[i].val ;
//printf("%lld %d %d\n", res,v2[i].val, (E - sum));
}
/*long long res = 0;
int e = E;
for(int i = 0; i < N; i++){
res += e*v[i];
e = min(R, E);
//printf("%d %d %lld)\n", e, v[i], res);
}*/
printf("Case #%d: %lld\n", t+1, res);
//break;
}
}
|
a06792f315bec9b77b4d475229dd42dd76546e3c | 7f3c42a1ce46c7794fa2ac0a0e817f209b85e6a1 | /source/SnakeFood.cpp | 5b89831b370b4c83c57e03a8205b1a51741efa69 | [] | no_license | Natador/2playerSocketSnake | 884fc908626fb0dcdacc5ff4f17a0bf0dfe0fd12 | 586f4002a25ec3badafb33280b91a912791646ee | refs/heads/master | 2020-07-22T00:55:30.342653 | 2019-09-07T20:38:23 | 2019-09-07T20:38:23 | 207,022,880 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 663 | cpp | SnakeFood.cpp | /*
* Implementation file for the SnakeFood class, which encodes the position
* of the food for the snakes.
*/
#include "include/SnakeFood.h"
// Default constructor
SnakeFood::SnakeFood() {
randPos();
}
// Destructor
SnakeFood::~SnakeFood() {
}
// Parameterized constructor with X/Y position
SnakeFood::SnakeFood(int xpos, int ypos) : x_pos(xpos), y_pos(ypos) {
}
// Return X position
int SnakeFood::getXPos(void) {
return x_pos;
}
// Return Y position
int SnakeFood::getYPos(void) {
return y_pos;
}
// Assigns a random value to the x and y position
void SnakeFood::randPos() {
x_pos = rand() % (X_SIZE-2) + 1;
y_pos = rand() % (Y_SIZE-2) + 1;
}
|
f4a71fa82728976d00fc8f87a55bcdc57bec1cde | 7debf6adedcfc1d828321ccd62861ce5d679d70d | /include/tracker/Tracker.cpp | 5d2012ab1737288e20b420a88388fd1baa173596 | [] | no_license | GSO-soslab/online_photometric_calib | 85a8f620dd6c0059097da97fdb16d09e45ef1638 | d00da3a9140b1c8190424bc6448d50e5b9e6c673 | refs/heads/main | 2023-06-28T15:48:45.028119 | 2021-07-30T18:50:41 | 2021-07-30T18:50:41 | 391,116,351 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,841 | cpp | Tracker.cpp | //
// Tracker.cpp
// OnlinePhotometricCalibration
//
// Created by Paul on 16.11.17.
// Copyright (c) 2017-2018 Paul Bergmann and co-authors. All rights reserved.
//
// See LICENSE.txt
//
#include "Tracker.h"
Tracker::Tracker(int patch_size,int nr_active_features,int nr_pyramid_levels,Database* database) :
feature_id_(0)
{
// Simply store all passed arguments to object
m_patch_size = patch_size;
m_max_nr_active_features = nr_active_features;
m_nr_pyramid_levels = nr_pyramid_levels;
m_database = database;
}
void Tracker::trackNewFrame(cv::Mat input_image,double gt_exp_time)
{
// Compute gradient (necessary for weighting factors)
// Todo: move to class member
cv::Mat gradient_image;
computeGradientImage(input_image, gradient_image);
// Correct the input image based on the current response and vignette estimate (exposure time not known yet)
// Todo: move to class member
cv::Mat corrected_frame = input_image.clone();
photometricallyCorrectImage(corrected_frame);
// Empty database -> First frame - extract features and push them back
if(m_database->m_tracked_frames.size() == 0)
{
initialFeatureExtraction(input_image,gradient_image,gt_exp_time);
prev_ids_ = visualized_feature_ids_;
return;
}
// Database not empty
// Fetch the old active feature locations together with their image
std::vector<cv::Point2f> feature_locations = m_database->fetchActiveFeatureLocations();
cv::Mat last_frame = m_database->fetchActiveImage();
// Track the feature locations forward using gain robust KLT
std::vector<cv::Point2f> tracked_points_new_frame;
std::vector<unsigned char> tracked_point_status;
std::vector<float> tracking_error_values;
GainRobustTracker gain_robust_klt_tracker(C_KLT_PATCH_SIZE,C_NR_PYRAMID_LEVELS);
std::vector<int> tracked_point_status_int;
gain_robust_klt_tracker.trackImagePyramids(last_frame,
input_image,
feature_locations,
tracked_points_new_frame,
tracked_point_status_int);
for(int i = 0;i < tracked_point_status_int.size();i++)
{
if(tracked_point_status_int.at(i) == 0)
{
tracked_point_status.push_back(0);
}
else
{
tracked_point_status.push_back(1);
}
}
// Bidirectional tracking filter: Track points backwards and make sure its consistent
std::vector<cv::Point2f> tracked_points_backtracking;
std::vector<unsigned char> tracked_point_status_backtracking;
std::vector<float> tracking_error_values_backtracking;
GainRobustTracker gain_robust_klt_tracker_2(C_KLT_PATCH_SIZE,C_NR_PYRAMID_LEVELS);
std::vector<int> tracked_point_status_int2;
gain_robust_klt_tracker_2.trackImagePyramids(input_image,
last_frame,
tracked_points_new_frame,
tracked_points_backtracking,
tracked_point_status_int2);
for(int i = 0;i < tracked_point_status_int2.size();i++)
{
if(tracked_point_status_int2.at(i) == 0)
{
tracked_point_status_backtracking.push_back(0);
}
else
{
tracked_point_status_backtracking.push_back(1);
}
}
// Tracked points from backtracking and old frame should be the same -> check and filter by distance
for(int p = 0;p < feature_locations.size();p++)
{
if(tracked_point_status.at(p) == 0) // Point already set invalid by forward tracking -> ignore
continue;
if(tracked_point_status_backtracking.at(p) == 0) // Invalid in backtracking -> set generally invalid
tracked_point_status.at(p) = 0;
// Valid in front + backtracked images -> calculate displacement error
cv::Point2d d_p = feature_locations.at(p) - tracked_points_backtracking.at(p);
double distance = sqrt(d_p.x*d_p.x + d_p.y*d_p.y);
if(distance > C_FWD_BWD_TRACKING_THRESH)
{
tracked_point_status.at(p) = 0;
}
}
Frame frame;
frame.m_image = input_image;
frame.m_image_corrected = corrected_frame;
frame.m_gradient_image = gradient_image;
frame.m_exp_time = 1.0;
frame.m_gt_exp_time = gt_exp_time;
// Reject features that have been tracked to the side of the image
// Todo: validity_vector can be combined with tracked_point_status to one vector?
std::vector<int> validity_vector = checkLocationValidity(tracked_points_new_frame);
int nr_pushed_features = 0;
visualized_feature_ids_.clear();
visualized_features_.clear();
// feature_locations is previous frame features
// prev ids vector is same as this one
for(int i = 0;i < feature_locations.size();i++)
{
// If the feature became invalid don't do anything, otherwise if its still valid, push it to the database and set the feature pointers
// tracked_point_status:
// 1) filter by forward Robust KLT
// 2) filter by backward Robust KLT
// 3) filter by distance filter from forward-backward tracking
if(tracked_point_status.at(i) == 0 || validity_vector.at(i) == 0)
continue;
// Feature is valid, set its data and push it back
Feature* f = new Feature();
// Todo: remove os, is, gs
std::vector<double> os = bilinearInterpolateImagePatch(input_image,tracked_points_new_frame.at(i).x,tracked_points_new_frame.at(i).y);
f->m_output_values = os;
std::vector<double> is = bilinearInterpolateImagePatch(corrected_frame,tracked_points_new_frame.at(i).x,tracked_points_new_frame.at(i).y);
f->m_radiance_estimates = is;
std::vector<double> gs = bilinearInterpolateImagePatch(gradient_image, tracked_points_new_frame.at(i).x, tracked_points_new_frame.at(i).y);
f->m_gradient_values = gs;
f->m_xy_location = tracked_points_new_frame.at(i);
// feature visualization
// modify the id_
visualized_feature_ids_.push_back(prev_ids_[i]);
visualized_features_.push_back(f->m_xy_location);
f->m_next_feature = NULL;
f->m_prev_feature = m_database->m_tracked_frames.at(m_database->m_tracked_frames.size()-1).m_features.at(i);
m_database->m_tracked_frames.at(m_database->m_tracked_frames.size()-1).m_features.at(i)->m_next_feature = f;
frame.m_features.push_back(f);
nr_pushed_features++;
}
m_database->m_tracked_frames.push_back(frame);
// Extract new features
std::vector<cv::Point2f> new_feature_locations = extractFeatures(input_image,m_database->fetchActiveFeatureLocations());
std::vector<int> new_validity_vector = checkLocationValidity(new_feature_locations);
for(int p = 0;p < new_feature_locations.size();p++)
{
// Skip invalid points (too close to the side of image)
if(new_validity_vector.at(p) == 0)
continue;
// Push back new feature information
Feature* f = new Feature();
f->m_xy_location = new_feature_locations.at(p);
// feature visualizaton
feature_id_ ++;
visualized_feature_ids_.push_back(feature_id_);
visualized_features_.push_back(f->m_xy_location);
f->m_next_feature = NULL;
f->m_prev_feature = NULL;
// Todo: remove os, is, gs
std::vector<double> os = bilinearInterpolateImagePatch(input_image,new_feature_locations.at(p).x,new_feature_locations.at(p).y);
f->m_output_values = os;
std::vector<double> is = bilinearInterpolateImagePatch(corrected_frame,new_feature_locations.at(p).x,new_feature_locations.at(p).y);
f->m_radiance_estimates = is;
std::vector<double> gs = bilinearInterpolateImagePatch(gradient_image, new_feature_locations.at(p).x, new_feature_locations.at(p).y);
f->m_gradient_values = gs;
m_database->m_tracked_frames.at(m_database->m_tracked_frames.size()-1).m_features.push_back(f);
}
visualizer_.add_current_features(visualized_features_, visualized_feature_ids_);
prev_ids_ = visualized_feature_ids_;
}
// Todo: change both types to reference
std::vector<cv::Point2f> Tracker::extractFeatures(cv::Mat frame,std::vector<cv::Point2f> old_features)
{
std::vector<cv::Point2f> new_features;
// No new features have to be extracted
if(old_features.size() >= m_max_nr_active_features)
{
return new_features;
}
int nr_features_to_extract = static_cast<int>(m_max_nr_active_features-old_features.size());
// Build spatial distribution map to check where to extract features
int cells_r = 10;
int cells_c = 10;
double im_width = m_database->m_image_width;
double im_height = m_database->m_image_height;
int cell_height = floor(im_height / cells_r);
int cell_width = floor(im_width / cells_c);
// Todo: change to class member
int pointDistributionMap[cells_r][cells_c];
for(int r = 0;r < cells_r;r++)
{
for(int c = 0;c < cells_c;c++)
{
pointDistributionMap[r][c] = 0;
}
}
// Build the point distribution map to check where features need to be extracted mostly
// Lin:
for(int p = 0;p < old_features.size();p++)
{
double x_value = old_features.at(p).x;
double y_value = old_features.at(p).y;
int c_bin = x_value / cell_width;
if(c_bin >= cells_c)
c_bin = cells_c - 1;
int r_bin = y_value / cell_height;
if(r_bin >= cells_r)
r_bin = cells_r - 1;
pointDistributionMap[r_bin][c_bin]++;
}
// Identify empty cells
std::vector<int> empty_row_indices;
std::vector<int> empty_col_indices;
for(int r = 0;r < cells_r;r++)
{
for(int c = 0;c < cells_c;c++)
{
if(pointDistributionMap[r][c] == 0)
{
empty_row_indices.push_back(r);
empty_col_indices.push_back(c);
}
}
}
// Todo: empty_col_indices might be 0!!!
// Todo: Another bad case is: only one cell is empty and all other cells have only 1 feature inside,
// Todo: then all the features to extract will be extracted from the single empty cell.
int points_per_cell = ceil(nr_features_to_extract / (empty_col_indices.size()*1.0));
// Extract "points per cell" features from each empty cell
for(int i = 0;i < empty_col_indices.size();i++)
{
// Select random cell from where to extract features
int random_index = rand() % empty_row_indices.size();
// Select row and col
int selected_row = empty_row_indices.at(random_index);
int selected_col = empty_col_indices.at(random_index);
// Define the region of interest where to detect a feature
cv::Rect ROI(selected_col * cell_width,selected_row * cell_height,cell_width,cell_height);
// Extract features from this frame
cv::Mat frame_roi = frame(ROI);
// Extract features
std::vector<cv::Point2f> good_corners;
cv::goodFeaturesToTrack(frame_roi,
good_corners,
points_per_cell,
0.01,
7,
cv::Mat(),
7,
false,
0.04);
// Add the strongest "points per cell" features from this extraction
for(int k = 0;k < good_corners.size();k++)
{
if(k == points_per_cell)
break;
// Add the offset to the point location
cv::Point2f point_location = good_corners.at(k);
point_location.x += selected_col*cell_width;
point_location.y += selected_row*cell_height;
new_features.push_back(point_location);
}
}
return new_features;
}
/**
* Note: For this function, it is assumed that x,y lies within the image!
*/
double Tracker::bilinearInterpolateImage(cv::Mat image,double x,double y)
{
double floor_x = std::floor(x);
double ceil_x = std::ceil(x);
double floor_y = std::floor(y);
double ceil_y = std::ceil(y);
// Normalize x,y to be in [0,1)
double x_normalized = x - floor_x;
double y_normalized = y - floor_y;
// Get bilinear interpolation weights
double w1 = (1-x_normalized)*(1-y_normalized);
double w2 = x_normalized*(1-y_normalized);
double w3 = (1-x_normalized)*y_normalized;
double w4 = x_normalized*y_normalized;
// Evaluate image locations
double i1 = static_cast<double>(image.at<uchar>(floor_y,floor_x));
double i2 = static_cast<double>(image.at<uchar>(floor_y,ceil_x));
double i3 = static_cast<double>(image.at<uchar>(ceil_y,floor_x));
double i4 = static_cast<double>(image.at<uchar>(ceil_y,ceil_x));
// Interpolate the result
return w1*i1 + w2*i2 + w3*i3 + w4*i4;
}
/**
* Note: For this function, it is assumed that x,y lies within the image!
*/
std::vector<double> Tracker::bilinearInterpolateImagePatch(cv::Mat image,double x,double y)
{
std::vector<double> result;
for(int x_offset = -m_patch_size;x_offset <= m_patch_size;x_offset++)
{
for(int y_offset = -m_patch_size;y_offset <= m_patch_size;y_offset++)
{
double o_value = bilinearInterpolateImage(image,x+x_offset,y+y_offset);
result.push_back(o_value);
}
}
return result;
}
// Todo: change return to parameter passed by ref
std::vector<int> Tracker::checkLocationValidity(std::vector<cv::Point2f> points)
{
// Check for each passed point location if the patch centered around it falls completely within the input images
// Return 0 for a point if not, 1 if yes
int min_x = m_patch_size+1; //Todo: should be m_patch_size?
int min_y = m_patch_size+1;
int max_x = m_database->m_image_width-m_patch_size-1;
int max_y = m_database->m_image_height-m_patch_size-1;
std::vector<int> is_valid;
for(int i = 0;i < points.size();i++)
{
if(points.at(i).x < min_x || points.at(i).x > max_x || points.at(i).y < min_y || points.at(i).y > max_y)
{
is_valid.push_back(0);
}
else
{
is_valid.push_back(1);
}
}
return is_valid;
}
// Todo: change parameter type to reference (or const reference)
void Tracker::initialFeatureExtraction(cv::Mat input_image,cv::Mat gradient_image,double gt_exp_time)
{
std::vector<cv::Point2f> old_f;
std::vector<cv::Point2f> feature_locations = extractFeatures(input_image,old_f);
std::vector<int> validity_vector = checkLocationValidity(feature_locations);
// Initialize new tracking Frame
Frame frame;
frame.m_image = input_image;
frame.m_image_corrected = input_image.clone();
frame.m_exp_time = 1.0;
frame.m_gt_exp_time = gt_exp_time;
// Push back tracked feature points to the tracking Frame
visualized_feature_ids_.clear();
visualized_features_.clear();
for(int p = 0;p < feature_locations.size();p++)
{
// Skip invalid points (too close to the side of image)
if(validity_vector.at(p) == 0)
continue;
// Create new feature object and associate with it output intensities, gradient values, etc.
Feature* f = new Feature();
f->m_xy_location = feature_locations.at(p);
/** feature visualize **/
feature_id_ ++;
visualized_feature_ids_.push_back(feature_id_);
visualized_features_.push_back(f->m_xy_location);
f->m_next_feature = NULL;
f->m_prev_feature = NULL;
std::vector<double> os = bilinearInterpolateImagePatch(input_image,feature_locations.at(p).x,feature_locations.at(p).y);
std::vector<double> gs = bilinearInterpolateImagePatch(gradient_image,feature_locations.at(p).x,feature_locations.at(p).y);
f->m_output_values = os;
f->m_gradient_values = gs;
f->m_radiance_estimates = os;
frame.m_features.push_back(f);
}
visualizer_.add_new_features(visualized_features_, visualized_feature_ids_);
m_database->m_tracked_frames.push_back(frame);
}
void Tracker::computeGradientImage(cv::Mat input_image,cv::Mat &gradient_image)
{
// Blur the input image a little and apply discrete 3x3 sobel filter in x,y directions to obtain a gradient estimate
// Todo: change to class member
cv::Mat blurred_image;
cv::GaussianBlur( input_image, blurred_image, cv::Size(3,3), 0, 0, cv::BORDER_DEFAULT );
// Todo: change to class member
cv::Mat grad_x,grad_y;
cv::Sobel( blurred_image, grad_x, CV_16S, 1, 0, 3, 1.0, 0, cv::BORDER_DEFAULT );
cv::Sobel( blurred_image, grad_y, CV_16S, 0, 1, 3, 1.0, 0, cv::BORDER_DEFAULT );
cv::convertScaleAbs( grad_x, grad_x );
cv::convertScaleAbs( grad_y, grad_y );
cv::addWeighted( grad_x, 0.5, grad_y, 0.5, 0, gradient_image );
}
void Tracker::photometricallyCorrectImage(cv::Mat &corrected_frame)
{
for(int r = 0;r < corrected_frame.rows;r++)
{
for(int c = 0;c < corrected_frame.cols;c++)
{
int o_value = corrected_frame.at<uchar>(r,c);
double radiance = m_database->m_response_estimate.removeResponse(o_value);
double vig = m_database->m_vignette_estimate.getVignetteFactor(cv::Point2f(c,r));
radiance /= vig;
if(radiance > 255)radiance = 255;
if(radiance < 0)radiance = 0;
corrected_frame.at<uchar>(r,c) = (uchar)radiance;
}
}
/*
* For debugging: visualize the corrected frame
*
* cv::imshow("radiance image", corrected_frame);
* cv::waitKey(0);
*
*/
}
cv::Mat Tracker::get_visualized_img()
{
cv::Mat last_frame = m_database->fetchActiveImage();
return visualizer_.draw_tracks(last_frame);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// from https://github.com/daniilidis-group/msckf_mono/blob/master/include/msckf_mono/corner_detector.h#L85
TrackVisualizer::TrackVisualizer()
{
feature_tracks_.clear();
}
void TrackVisualizer::add_predicted(Point2fVector& features, IdVector& feature_ids)
{
assert(features.size()==feature_ids.size());
predicted_pts_.clear();
auto fit=features.begin();
auto idit=feature_ids.begin();
for(;fit!=features.end() && idit!=feature_ids.end();++fit, ++idit){
predicted_pts_.emplace(*idit, *fit);
}
}
// maintained tracked features with ID, only keep tracked, delete lost features
void TrackVisualizer::add_current_features(Point2fVector& features, IdVector& feature_ids)
{
assert(features.size()==feature_ids.size());
std::set<size_t> current_ids;
auto fit=features.begin();
auto idit=feature_ids.begin();
for(;fit!=features.end() && idit!=feature_ids.end();++fit, ++idit){
size_t id = *idit;
current_ids.insert(id);
if(feature_tracks_.find(id)==feature_tracks_.end()){
feature_tracks_.emplace(*idit, Point2fVector());
}
feature_tracks_[id].push_back(*fit);
}
// remove one id: when one of tracked id not found in current detected
std::vector<int> to_remove;
for(auto& track : feature_tracks_)
if(current_ids.count(track.first)==0)
to_remove.push_back(track.first);
for(auto id : to_remove)
feature_tracks_.erase(id);
}
void TrackVisualizer::add_new_features(Point2fVector& features, IdVector& feature_ids)
{
assert(features.size()==feature_ids.size());
auto fit=features.begin();
auto idit=feature_ids.begin();
// add new features into feature visualization management
for(;fit!=features.end();++fit, ++idit){
size_t id = *idit;
if(feature_tracks_.find(id)==feature_tracks_.end()){
feature_tracks_.insert(std::make_pair(id, Point2fVector()));
}
feature_tracks_[id].push_back(*fit);
}
}
cv::Mat TrackVisualizer::draw_tracks(cv::Mat image)
{
cv::Mat outImage;
if( image.type() == CV_8UC3 ){
image.copyTo( outImage );
}else if( image.type() == CV_8UC1 ){
if (image.empty()) {
std::cout<<"image is empty. not draw\n";
return outImage;
}
cvtColor( image, outImage, cv::COLOR_GRAY2BGR );
}else{
CV_Error( cv::Error::StsBadArg, "Incorrect type of input image.\n" );
return outImage;
}
bool first;
Point2fVector::reverse_iterator prev;
cv::Scalar color;
for(auto& track : feature_tracks_)
{
first = true;
size_t id = track.first;
// create consistent color for each track
color = cv::Scalar(((id/64)%8)*255/8, ((id/8)%8)*255/8, (id%8)*255/8);
auto search = predicted_pts_.find(id);
if(search!=predicted_pts_.end()){
cv::circle(outImage, search->second, 6, color, 2);
}
for(auto it = track.second.rbegin(); it != track.second.rend(); ++it)
{
if(first){
first = false;
cv::circle(outImage, *it, 4, color, 2);
}else{
cv::line(outImage, *it, *prev, color, 1);
}
prev = it;
}
}
return outImage;
}
|
c9aff538ee3b006ba998bfdaa8464c83ab29c445 | 1860676a456a34a491b4583f938dcbcb36bc3cc1 | /포폴발표/1주차/포폴프로젝트/Dx3D/cSkinnedMesh.h | 14ecc60be22443caeaa9908249437aecafb5480c | [] | no_license | alstn191919/Ariya | e39b4d1c4a0a564fcb07a4042e2a0f5e347a7f18 | 173dfe65e97e2db0f327d3aa0ef071cb4595f620 | refs/heads/master | 2020-03-19T17:05:07.306850 | 2017-01-05T02:30:58 | 2017-01-05T02:31:05 | 75,247,759 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,265 | h | cSkinnedMesh.h | #pragma once
struct ST_BONE;
class cSkinnedMesh
{
friend class cSkinnedMeshManager;
private:
//하나만 생성
ST_BONE* m_pRootFrame;
DWORD m_dwWorkingPaletteSize;
D3DXMATRIX* m_pmWorkingPalette;
LPD3DXEFFECT m_pEffect;
ST_SPHERE m_stBoundingSphere;
// 객체마다 생성
LPD3DXANIMATIONCONTROLLER m_pAnimController;
D3DXVECTOR3 m_vPosition;
float m_fBlendTime;
float m_fPassedAnimTime;
bool m_isBlending;
SYNTHESIZE(D3DXVECTOR3, m_Min, Min);
SYNTHESIZE(D3DXVECTOR3, m_Max, Max);
public:
cSkinnedMesh(char* szFolder, char* szFilename);
~cSkinnedMesh(void);
void UpdateAndRender(D3DXMATRIXA16* pmat = NULL);
void SetAnimationIndex(int nIndex);
void SetRandomTrackPosition(); // 테스트용
void SetPosition(D3DXVECTOR3 v)
{
m_vPosition = v;
m_stBoundingSphere.vCenter += v;
}
D3DXVECTOR3 GetPosition()
{
return m_vPosition;
}
ST_SPHERE* GetBoundingSphere()
{
return &m_stBoundingSphere;
}
private:
cSkinnedMesh();
void Load(char* szFolder, char* szFilename);
LPD3DXEFFECT LoadEffect(char* szFilename);
void Update(ST_BONE* pCurrent, D3DXMATRIXA16* pmatParent);
void Render(ST_BONE* pBone = NULL);
void SetupBoneMatrixPtrs(ST_BONE* pBone);
void Destroy();
};
|
80365ae8e7c5de25b046eaec415f670512dc0c3b | 2b93656c33dac0e3f531ca40d6e2afd12dbca291 | /src/key.hpp | 65c14d8500b57569abb4164d828b22cf968aecd7 | [
"MIT"
] | permissive | andmatand/kitty-town | 33c8778e135591957b27968dd27997010f168965 | 0eb03c7d1421aa1bd33a48bf59f5e6eae8501e67 | refs/heads/master | 2020-05-27T06:26:41.668561 | 2013-10-08T05:30:29 | 2013-10-08T05:30:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 136 | hpp | key.hpp | #ifndef KEY_HPP
#define KEY_HPP
enum KEY {
KEY_UP = 0,
KEY_RIGHT = 1,
KEY_DOWN = 2,
KEY_LEFT = 3
};
#endif // KEY_HPP
|
786c60508abc26afadefba151513db2f5d6245af | 1bf6e620ec39d17a0faeeb04280448b8ec5b18ec | /Array/array and pointer/1.cpp | 57e1f9d85e1a6264691906946708ee7e276881d5 | [] | no_license | irfaniskandar-23/Programming-Technique | 5dee21558211037934bbd32d04aafffcd960c386 | 3de3b207b29ea53867462f31deb5ad56ea108417 | refs/heads/main | 2023-03-07T18:19:03.219006 | 2021-02-25T18:47:12 | 2021-02-25T18:47:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 214 | cpp | 1.cpp | #include<iostream>
using namespace std;
main()
{
int array[5]={10,20,30,40,50};
int *ptr;
ptr=&array[0];
for(int i=0;i<5;i++)
{
cout<<"the adress of "<<*(ptr+i)<<" is "<<(ptr+i)<<endl;
}
}
|
d17add66cf2b3d1be3a413d8d42d78e6a6d376e6 | b995409896ccacc465e6000f0dc60e2b42f3ecef | /test/parser_test.cpp | ec86340bd33a4b9478c29b23548b31ebe1838eb0 | [
"MIT"
] | permissive | rvaser/bioparser | 6a7201451f048966a6a6c34611100508678f187e | 4fa7126293d2a0eb90125b58fb704f0eed33ffe0 | refs/heads/master | 2023-05-26T01:04:07.651476 | 2023-05-12T15:05:47 | 2023-05-18T10:03:19 | 61,360,327 | 11 | 8 | MIT | 2023-05-18T10:09:39 | 2016-06-17T08:59:17 | C++ | UTF-8 | C++ | false | false | 528 | cpp | parser_test.cpp | // Copyright (c) 2020 Robert Vaser
#include "bioparser/parser.hpp"
#include "biosoup/sequence.hpp"
#include "gtest/gtest.h"
#include "bioparser/fasta_parser.hpp"
namespace bioparser {
namespace test {
TEST(BioparserParserTest, Create) {
try {
auto p = Parser<biosoup::Sequence>::Create<FastaParser>("");
} catch (std::invalid_argument& exception) {
EXPECT_STREQ(
exception.what(),
"[bioparser::Parser::Create] error: unable to open file ");
}
}
} // namespace test
} // namespace bioparser
|
3081e091881878415792eedba72c73608e2b3693 | 994f96151fb4b38330990f4284bb217262dbb18e | /Chess_45603/Piece.h | 921fabe66af418209762091fbe610659f55b1c50 | [] | no_license | Todor-Shishmanov/Chess | b3653fa680e778fcee6bbd13a835fae42d62250a | 12d6e1b95a37937968f389bab3207ca663ce2bfc | refs/heads/master | 2021-03-24T01:34:19.798500 | 2020-03-15T16:21:38 | 2020-03-15T16:21:38 | 247,502,194 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,034 | h | Piece.h | #include "PieceBasic.h"
class Pawn: public PieceBasic{
private:
bool first_turn = 1;
public:
Pawn(char new_letter, int new_number, int Board[8][8]) {
set_place(new_letter, new_number);
Board[8 - (new_number)][new_letter - 'a'] = 1;
}
int symbol();
void set_first_turn();
bool get_first_turn();
void move(char letter, int number, int Board[8][8]);
};
class Knight : public PieceBasic {
public:
Knight(char new_letter, int new_number, int Board[8][8]) {
set_place(new_letter, new_number);
Board[8 - (new_number)][new_letter - 'a'] = 2;
}
int symbol();
void move(char letter, int number, int Board[8][8]);
};
class Bishop :public PieceBasic {
public:
Bishop(char new_letter, int new_number, int Board[8][8]) {
set_place(new_letter, new_number);
Board[8 - (new_number)][new_letter - 'a'] = 3;
}
int symbol();
void move(char letter, int number, int Board[8][8]);
};
class Rook :public PieceBasic {
private:
bool first_turn = 1;
public:
Rook(char new_letter, int new_number, int Board[8][8]) {
set_place(new_letter, new_number);
Board[8 - (new_number)][new_letter - 'a'] = 4;
}
int symbol();
void move(char letter, int number, int Board[8][8]);
void set_first_turn();
bool get_first_turn();
};
class Queen:public PieceBasic {
public:
Queen(char new_letter, int new_number, int Board[8][8]) {
set_place(new_letter, new_number);
Board[8 - (new_number)][new_letter - 'a'] = 5;
}
int symbol();
void move(char letter, int number, int Board[8][8]);
};
class King :public PieceBasic {
private:
bool check = 0;
bool first_turn = 1;
bool flag1 = 0;
bool flag2 = 0;
public:
King(char new_letter, int new_number, int Board[8][8]) {
set_place(new_letter, new_number);
Board[8 - (new_number)][new_letter - 'a'] = 6;
}
int symbol();
void set_flag1();
bool get_flag1();
void set_flag2();
bool get_flag2();
void set_first_turn();
void set_false_first_turn();
bool get_first_turn();
void set_check();
bool get_check();
void move(char letter, int number, int Board[8][8]);
};
|
20fdf467db47d219a91296346bcb7d0effff0edd | ec00df8410c9c8894f5127a4019be28c3c732542 | /LightChaserAnim/katana_source_code/plugin_apis/include/FnDefaultAttributeProducer/plugin/FnDefaultAttributeProducerUtil.h | 7aeb3fcfa4b133026015051535a8c6afdca4e377 | [] | no_license | tws0002/aWorkingSource | 580964ef39a7e5106d75136cfcd23814deecf0fd | 188c081d261c11faa11766be41def34b7e01ee5e | refs/heads/master | 2021-05-11T18:23:19.427869 | 2018-01-03T03:17:57 | 2018-01-03T03:17:57 | 117,823,716 | 1 | 0 | null | 2018-01-17T10:51:59 | 2018-01-17T10:51:59 | null | UTF-8 | C++ | false | false | 2,803 | h | FnDefaultAttributeProducerUtil.h | #ifndef INCLUDED_FNDEFAULTATTRIBUTEPRODUCERUTIL_H
#define INCLUDED_FNDEFAULTATTRIBUTEPRODUCERUTIL_H
#include <FnAttribute/FnAttribute.h>
#include <FnAttribute/FnGroupBuilder.h>
#include "ns.h"
FNDEFAULTATTRIBUTEPRODUCER_NAMESPACE_ENTER
{
namespace DapUtil
{
void SetAttrHints(
FnAttribute::GroupBuilder & gb,
const std::string & attrPath,
const FnAttribute::GroupAttribute & hintsGroup);
void SetHintsForAllChildren(
FnAttribute::GroupBuilder & gb,
const std::string & attrPath,
const FnAttribute::GroupAttribute & hintsGroup);
void CopyAttrHints(
FnAttribute::GroupBuilder & gb,
const FnAttribute::GroupAttribute & srcGrp,
const std::string & srcAttrPath,
const std::string & dstAttrPath,
bool recursive);
void PromoteAttrHints(
FnAttribute::GroupBuilder & gb,
const FnAttribute::GroupAttribute & attrWithHints,
const std::string & attrPath);
FnAttribute::GroupAttribute StripAttrHints(
const FnAttribute::GroupAttribute & attr);
void SetContainerHints(
FnAttribute::GroupBuilder & gb,
const std::string & attrPath,
const std::string & containerPath,
const FnAttribute::GroupAttribute & hintsGroup);
/// For the given Defaults Group, returns for the attribute at
/// |attributePath|, the container hints for the container specified by
/// |containerPath|.
///
/// @param defaultsGroup: The defaults group being cooked by a DAP.
/// @param attributePath: The attribute whose container hints are to be
/// returned.
/// @param containerPath: The container whose hints are to be returned.
FnAttribute::GroupAttribute GetContainerHints(
const FnAttribute::GroupAttribute& defaultsGroup,
const std::string& attributePath, const std::string& containerPath);
/// For the given Defaults Group, returns the parameter-level hints for the
/// attribute at |attributePath|.
///
/// @param defaultsGroup: The Defaults Group being cooked by a DAP.
/// @param attributePath: The attribute whose hints are to be returned.
FnAttribute::GroupAttribute GetAttributeHints(
const FnAttribute::GroupAttribute& defaultsGroup,
const std::string& attributePath);
void ParseAttributeHints(
const std::string & argsRoot,
FnAttribute::GroupBuilder & mainGb,
FnAttribute::GroupBuilder & argsGb,
FnAttribute::GroupAttribute & groupAttr,
const std::string & attrPath);
} // namespace DapUtil
}
FNDEFAULTATTRIBUTEPRODUCER_NAMESPACE_EXIT
#endif // INCLUDED_FNDEFAULTATTRIBUTEPRODUCERUTIL_H
|
0aea3822a841441a23ec0fab531e160228b02e36 | c3ce361d66cca3c61047ed368e8c98cdec44e228 | /Group_of_Figures/Figure.cpp | 42a2f1093f09c3e83c911a2a7cdd10d220c1a51e | [] | no_license | kamil-s-kaczor/Group_of_Figures | 8e56e00f10d34ba8b9456d88699e5f3f567b097d | 9b84dc631944c1684191efee32b5685efd95af5f | refs/heads/master | 2022-12-03T03:54:03.731295 | 2020-08-25T08:18:22 | 2020-08-25T08:18:22 | 290,150,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 733 | cpp | Figure.cpp | #include "pch.h"
#include "Figure.h"
class Circle;
class Rectangle;
class Triangle;
Point::Point(float const& x, float const& y)
{
this->x = x;
this->y = y;
}
Point Point::set_values(float x, float y)
{
this->x = x;
this->y = y;
return Point();
}
Point Point::operator=(Point const& a)
{
this->x = a.x;
this->y = a.y;
return *this;
}
bool Point::operator==(Point const& a) const& noexcept
{
if (a.x == this->x)
{
if (a.y == this->y)
{
return true;
}
}
return false;
}
void Figure::set_Figure_type(int const& x)
{
this->figure_type = x;
}
bool Figure::operator==(Figure const& a) const
{
if (this->figure_type == a.figure_type)
{
}
return false;
}
|
bed9d69a742d798ac7929ecff34db4ce11d69e99 | b80b980eb7730cbfa7ebfe0220cb86a69cac51e6 | /apps/my_app.h | 695a1660fa40b1fef6c8a1d8b3640603a9fdb78f | [
"MIT"
] | permissive | CS126SP20/final-project-meghasg2 | eee7a1f74377e1967e47cdbb20e1d7ba047185c9 | aad841877542c0fc6e51a1deeed55b8b96881844 | refs/heads/master | 2022-07-19T15:44:42.583036 | 2020-05-07T04:28:46 | 2020-05-07T04:28:46 | 256,848,973 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,696 | h | my_app.h | // Copyright (c) 2020 CS126SP20. All rights reserved.
#ifndef FINALPROJECT_APPS_MYAPP_H_
#define FINALPROJECT_APPS_MYAPP_H_
#include <Box2D/Box2D.h>
#include <cinder/audio/Voice.h>
#include "Conversions.h"
#include "ParticleController.h"
#include "cinder/app/App.h"
#include "cinder/gl/gl.h"
namespace myapp {
class MyApp : public cinder::app::App {
public:
MyApp();
~MyApp();
void setup() override;
void update() override;
void draw() override;
void keyDown(cinder::app::KeyEvent) override;
void mouseMove(cinder::app::MouseEvent event) override;
void mouseDown(cinder::app::MouseEvent event) override;
void mouseUp(cinder::app::MouseEvent event) override;
void mouseDrag(cinder::app::MouseEvent event) override;
void PrintText(const std::string& text, const cinder::Color& color,
const cinder::ivec2& size, const cinder::vec2& loc);
cinder::audio::VoiceRef mVoice;
private:
bool mouse_pressed_;
cinder::vec2 mouse_pos_;
const std::string text_ = "Welcome to Etch a Sketch!"
"\n Press the spacebar to clear the screen and change the"
" color of the particles"
"\n Press the 's' key to increase the size of the particles"
"\n Press the 'd' key to decrease the size of the particles"
"\n Press the 'a' key to watch the particles fall";
b2Vec2 gravity_;
b2World* world_;
particles::ParticleController particle_controller_;
const float32 kTimeStep = 1.0f / 60.0f;
const int32 kVelocityIterations = 6;
const int32 kPositionIterations = 2;
cinder::gl::TextureRef texture_;
};
} // namespace myapp
#endif // FINALPROJECT_APPS_MYAPP_H_
|
7fb405130530f22959d074bb191b2766b8509a8e | 7d5ab12afa98390e714faa9cfd8c6bfe0ab505f8 | /src/CppUtil/Engine/Filter/FilterSinc.cpp | 6658f81d4f3380e2d26662163cdbedfa6eaad509 | [
"MIT"
] | permissive | huangx916/RenderLab | 6199b0a4bc44cbae5b28291f999484eedec7de87 | a0059705d5694146bbe51442e0cabdcbcd750fe7 | refs/heads/master | 2020-07-21T21:46:31.215327 | 2019-09-07T09:47:02 | 2019-09-07T09:47:02 | 206,981,200 | 1 | 0 | MIT | 2019-09-07T14:40:54 | 2019-09-07T14:40:54 | null | UTF-8 | C++ | false | false | 330 | cpp | FilterSinc.cpp | #include <CppUtil/Engine/FilterSinc.h>
using namespace CppUtil;
using namespace CppUtil::Basic;
using namespace CppUtil::Engine;
float FilterSinc::WindowSinc(float x, float radius) const {
x = std::abs(x);
if (x > radius)
return 0;
const auto lanczos = Basic::Math::Sinc(x / tau);
return Basic::Math::Sinc(x) * lanczos;
}
|
0e408ee7d7557b978a9e318d37d5d17f80d05460 | 60fdc45761aac91af97028e2861e709d9dbbe2cd | /kscope-binary-only-works-on-lucid/include/dnssd/domainbrowser.h | 825422d8e80fbbe4e78fa73de174b05be857116a | [] | no_license | fredollinger/kscope | f3636cd4809f6be8e22cb8b20fc68d14740d9292 | 8bd0f6d1f5ec49e130ee86292b1e6b6cfe3b0f4d | refs/heads/master | 2021-01-01T19:56:55.106226 | 2010-09-29T20:17:22 | 2010-09-29T20:17:22 | 948,786 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,737 | h | domainbrowser.h | /* This file is part of the KDE project
*
* Copyright (C) 2004 Jakub Stachowski <qbast@go2.pl>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef DNSSDDOMAINBROWSER_H
#define DNSSDDOMAINBROWSER_H
#include <qobject.h>
#include <qdict.h>
#include <dnssd/remoteservice.h>
// KIPC message ID used by kcm module to signal change in browsing domains list
#define KIPCDomainsChanged 2014
class QStringList;
namespace DNSSD
{
class DomainBrowserPrivate;
/**
@short Class used to provide current list of domains for browsing.
@author Jakub Stachowski
*/
class KDNSSD_EXPORT DomainBrowser : public QObject
{
Q_OBJECT
public:
/**
Standard constructor. It takes all parameters from global configuration.
All changes in configuration are applied immediately.
@param parent Parent object.
*/
DomainBrowser(QObject *parent=0);
/**
Constructor that creates browser for domain list. This does not use global
configuration at all.
@param domains List of domains
@param recursive TRUE - additionally local network will be browsed for more domains
@param parent Parent object.
This process is recursive.
*/
DomainBrowser(const QStringList& domains, bool recursive=false, QObject *parent=0);
~DomainBrowser();
/**
Current list of domains to browse.
*/
const QStringList& domains() const;
/**
Starts browsing. To stop destroy this object.
*/
void startBrowse() ;
/**
Returns true when browse has already started
*/
bool isRunning() const;
signals:
/**
Emitted when domain has been removed from browsing list
*/
void domainRemoved(const QString&);
/**
New domain has been discovered. Also emitted for domain specified in constructor
and in global configuration
*/
void domainAdded(const QString&);
protected:
virtual void virtual_hook(int,void*);
private:
friend class DomainBrowserPrivate;
DomainBrowserPrivate *d;
void gotNewDomain(const QString&);
void gotRemoveDomain(const QString&);
private slots:
void domainListChanged(int,int);
};
}
#endif
|
289e8e34d8ee87edaacbe746519da9def4b17b60 | 05f9d65f9e2063ab4250e5671e6a9a7466601d5b | /Sudoku_Solver.cpp | e941890d882c725ab24a6dc1a9dfd902deb75805 | [] | no_license | kalrapradeep/Competitive-Programming | a23b1703dc43c4d65ab6326f7bddb4c115fc6693 | d4f59370f5163e56463f8de299a1cc522791446f | refs/heads/master | 2023-02-22T00:37:12.179820 | 2021-01-20T18:35:26 | 2021-01-20T18:35:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,908 | cpp | Sudoku_Solver.cpp | class Solution {
public:
unordered_map<int,unordered_map<char,int>> mp1;
unordered_map<int,unordered_map<char,int>> mp2;
unordered_map<int,unordered_map<char,int>> mp3;
vector<vector<char>> res;
int indexBoard(int r,int c)
{
if(r/3==0)
{
return c/3;
}
else if(r/3==1)
{
return 3+c/3;
}
else
{
return 6+c/3;
}
}
bool isFilled(vector<vector<char>> board)
{
for(int i=0;i<board.size();i++)
{
for(int j=0;j<board[i].size();j++)
{
if(board[i][j]=='.')
return false;
}
}
return true;
}
void traverse(vector<vector<char>>& board,int r,int c)
{
//cout<<r<<" ";
if(r==8&&c==9)
{
for(int i=0;i<board.size();i++)
{
for(int j=0;j<board[i].size();j++)
{
res[i][j]=board[i][j];
}
}
return;
}
if(c==9)
{
r++;
c=0;
}
int i=r,j=c;
if(board[i][j]=='.')
{
for(int k=0;k<9;k++)
{
if(mp1[i].find(k+'1')==mp1[i].end()&&mp2[j].find(k+'1')==mp2[j].end()&&mp3[indexBoard(i,j)].find(k+'1')==mp3[indexBoard(i,j)].end())
{
board[i][j]=k+'1';
mp3[indexBoard(i,j)][board[i][j]]=1;
mp1[i][board[i][j]]=1;
mp2[j][board[i][j]]=1;
traverse(board,i,j+1);
mp3[indexBoard(i,j)].erase(board[i][j]);
mp1[i].erase(board[i][j]);
mp2[j].erase(board[i][j]);
board[i][j]='.';
}
}
}
else
{
traverse(board,i,j+1);
}
}
void solveSudoku(vector<vector<char>>& board) {
for(int i=0;i<board.size();i++)
{
res.push_back(board[i]);
for(int j=0;j<board[i].size();j++)
{
if(board[i][j]!='.')
{
mp1[i][board[i][j]]=1;
mp2[j][board[i][j]]=1;
mp3[indexBoard(i,j)][board[i][j]]=1;
}
}
}
traverse(board,0,0);
for(int i=0;i<res.size();i++)
{
for(int j=0;j<res[i].size();j++)
{
board[i][j]=res[i][j];
}
}
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.