blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c8dcc96aa5e7428d8e3d5974a126a99847ba1976 | b2139a7f5e04114c39faea797f0f619e69b8b4ae | /src/piSquare/src/dmpMotionGeneration/dynamicMovementPrimitive.cpp | 64be8acd65542d1511304936c1bc6e54e8c40ca1 | [] | no_license | hychyc07/contrib_bk | 6b82391a965587603813f1553084a777fb54d9d7 | 6f3df0079b7ea52d5093042112f55a921c9ed14e | refs/heads/master | 2020-05-29T14:01:20.368837 | 2015-04-02T21:00:31 | 2015-04-02T21:00:31 | 33,312,790 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 38,360 | cpp | /*********************************************************************
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
**********************************************************************/
#include <math.h>
#include <sstream>
#include <errno.h>
#include <boost/foreach.hpp>
#include <iCub/piSquare/dmpMotionGeneration/dynamicMovementPrimitive.h>
#include <iCub/piSquare/dmpMotionGeneration/constants.h>
#include <iCub/piSquare/dmpMotionGeneration/mathHelper.h>
using namespace Eigen;
using namespace yarp::os;
namespace dmp
{
static const int DMP_ID_OFFSET = 10000;
static const double NOT_ASSIGNED = -666.666;
DynamicMovementPrimitive::DynamicMovementPrimitive(ResourceFinder* rf) :
initialized_(false), rf_(rf), params_(rf)
{
}
DynamicMovementPrimitive::~DynamicMovementPrimitive()
{
}
bool DynamicMovementPrimitive::initialize(int numTransformationSystems)
{
Parameters dmpParams(rf_);
if (!dmpParams.initialize())
{
printf("ERROR: Could not initialize dmp parameters from resource finder\n");
initialized_ = false;
return initialized_;
}
lwr::Parameters lwrParams(rf_);
if (!lwrParams.initialize())
{
printf("ERROR: Could not initialize lwr parameters from resource finder\n");
initialized_ = false;
return initialized_;
}
return initialize(numTransformationSystems, dmpParams, lwrParams);
}
bool DynamicMovementPrimitive::initialize(int numTransformationSystems, Parameters dmpParams, lwr::Parameters lwrParams)
{
//assign dmp parameters
params_ = dmpParams;
//overwrite number of transformation system in dmp_params
if (numTransformationSystems <= 0)
{
printf("ERROR: Number of transformation system %i is not valid\n", numTransformationSystems);
initialized_ = false;
return initialized_;
}
params_.numTransformationSystems_ = numTransformationSystems;
//initialized transformation systems using the lwr parameters
transformationSystems_.resize(params_.numTransformationSystems_);
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
if (!transformationSystems_[i].initialize(i, lwrParams))
{
printf("ERROR: Could not initialize transformation system %i.\n", i);
initialized_ = false;
return initialized_;
}
}
// set canonical system to pre-defined state
resetCanonicalState();
// allocate some memory (usefull?)
initialize();
initialized_ = true;
return initialized_;
}
void DynamicMovementPrimitive::initialize()
{
//debugTrajectoryPoint is probably meaningless
trajectoryTargetFunctionInput_.clear();
debugTrajectoryPoint_
= VectorXd::Zero(NUM_DEBUG_CANONICAL_SYSTEM_VALUES + (params_.numTransformationSystems_ * NUM_DEBUG_TRANSFORMATION_SYSTEM_VALUES));
}
bool DynamicMovementPrimitive::reInitializeParams()
{
return params_.initialize();
}
bool DynamicMovementPrimitive::learnFromThetas(const std::vector<VectorXd>& thetas, const VectorXd &initialStart, const VectorXd &initialGoal,
const double samplingFrequency, const double initialDuration)
{
if (!initialized_)
{
printf("ERROR: DMP is not initialized.\n");
params_.isLearned_ = false;
return params_.isLearned_;
}
ResourceFinder rf;
//set y0 to start state of trajectory and set goal to end of the trajectory
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
// set initial start and initial goal
transformationSystems_[i].setInitialStart(initialStart(i));
transformationSystems_[i].setInitialGoal(initialGoal(i));
}
params_.alphaX_ = -log(params_.canSysCutoff_);
params_.teachingDuration_ = initialDuration;
params_.deltaT_ = static_cast<double> (1.0) / samplingFrequency;
params_.initialDeltaT_ = params_.deltaT_;
params_.tau_ = params_.teachingDuration_;
params_.initialTau_ = params_.tau_;
if (!setThetas(thetas))
{
printf("ERROR: Could not set theta parameters.\n");
params_.isLearned_ = false;
return params_.isLearned_;
}
params_.isLearned_ = true;
return params_.isLearned_;
}
bool DynamicMovementPrimitive::learnFromMinJerk(const yarp::sig::Vector &start, const yarp::sig::Vector &goal, const double duration, const double deltaT)
{
if (!initialized_)
{
printf("ERROR: DMP motion unit is not initialized, not learning from minimum jerk trajectory.\n");
params_.isLearned_ = false;
return params_.isLearned_;
}
double samplingFrequency = static_cast<double> (1.0) / deltaT;
//could be removed
std::vector<std::string> variableNames;
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
std::stringstream ss;
ss << i;
variableNames.push_back(std::string("dummy_") + ss.str());
}
dmp::Trajectory minJerkTrajectory(rf_);
if (!minJerkTrajectory.initialize(variableNames, samplingFrequency))
{
printf("ERROR: Could not initialize trajectory.\n");
params_.isLearned_ = false;
return params_.isLearned_;
}
if (!MathHelper::generateMinJerkTrajectory(start, goal, duration, deltaT, minJerkTrajectory))
{
printf("ERROR: Could not generate minimum jerk trajectory.\n");
params_.isLearned_ = false;
return params_.isLearned_;
}
if (!learnFromTrajectory(minJerkTrajectory))
{
printf("ERROR: Could not learn from minimum jerk trajectory.\n");
params_.isLearned_ = false;
return params_.isLearned_;
}
//just for debug
/*
std::vector<Eigen::VectorXd> thetas;
getThetas(thetas);
printf("THETAS: ");
std::vector<Eigen::VectorXd>::iterator iter = thetas.begin();
for(; iter != thetas.end(); ++iter)
{
for(int i = 0; i < iter->size(); i++)
{
Eigen::VectorXd v = *iter;
printf("%f ", v(i));
}
printf("\n\n");
}
printf("\n");
*/
return (params_.isLearned_ = true);
}
bool DynamicMovementPrimitive::learnFromCustomTrajectory(dmp::Trajectory& trajectory)
{
if (!initialized_)
{
printf("ERROR: DMP motion unit is not initialized, not learning from custom trajectory.\n");
params_.isLearned_ = false;
return params_.isLearned_;
}
if (!learnFromTrajectory(trajectory))
{
printf("ERROR: Could not learn from custom trajectory.\n");
params_.isLearned_ = false;
return params_.isLearned_;
}
return (params_.isLearned_ = true);
}
bool DynamicMovementPrimitive::learnFromTrajectory(const Trajectory &trajectory)
{
if (!initialized_)
{
printf("ERROR: DMP motion unit is not initialized, not learning from trajectory.\n");
params_.isLearned_ = false;
return params_.isLearned_;
}
int numRows = trajectory.getLength();
if (numRows < MIN_NUM_DATA_POINTS)
{
printf("ERROR: Trajectory has %i rows, but should have at least %i.\n", numRows, MIN_NUM_DATA_POINTS);
params_.isLearned_ = false;
return params_.isLearned_;
}
double samplingFrequency = trajectory.getSamplingFrequency();
if (samplingFrequency <= 0)
{
printf("ERROR: Sampling frequency %f [Hz] of the trajectory is not valid.\n",samplingFrequency);
params_.isLearned_ = false;
return params_.isLearned_;
}
//set teaching duration to the duration of the trajectory
params_.teachingDuration_ = static_cast<double> (numRows) / static_cast<double> (samplingFrequency);
params_.deltaT_ = static_cast<double> (1.0) / samplingFrequency;
params_.initialDeltaT_ = params_.deltaT_;
params_.tau_ = params_.teachingDuration_;
params_.initialTau_ = params_.tau_;
//compute alpha_x such that the canonical system drops below the cutoff when the trajectory has finished
//alpha_x is the time constant for the phase system (second order asimptotically stable system)
params_.alphaX_ = -log(params_.canSysCutoff_);
double mseTotal = 0.0;
double normalizedMseTotal = 0.0;
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
transformationSystems_[i].trajectoryTarget_.clear();
transformationSystems_[i].resetMSE();
}
trajectoryTargetFunctionInput_.clear();
//reset canonical system
resetCanonicalState();
//obtain start and goal position
VectorXd start = VectorXd::Zero(params_.numTransformationSystems_);
if (!trajectory.getStartPosition(start))
{
printf("ERROR: Could not get the start position of the trajectory\n");
params_.isLearned_ = false;
return params_.isLearned_;
}
VectorXd goal = VectorXd::Zero(params_.numTransformationSystems_);
if (!trajectory.getEndPosition(goal))
{
printf("ERROR: Could not get the goal position of the trajectory\n");
params_.isLearned_ = false;
return params_.isLearned_;
}
//set y0 to start state of trajectory and set goal to end of the trajectory
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
//check whether all this is necessary (I don't think so...)
transformationSystems_[i].reset();
//set start and goal
transformationSystems_[i].setStart(start(i));
transformationSystems_[i].setGoal(goal(i));
//set current state to start state (position and velocity)
transformationSystems_[i].setState(start(i), 0.0);
}
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
transformationSystems_[i].setInitialStart(transformationSystems_[i].y0_);
transformationSystems_[i].setInitialGoal(transformationSystems_[i].goal_);
}
//for each time step and for each dimension, perform supervised learning of the input trajectory
//Actually is not a "classical" learning problem...here the problem is how to encode the
//target trajectory in the dmp by representing it as a second order system modulated with
//a nonlinear function f.
for (int rowIndex = 0; rowIndex < numRows; rowIndex++)
{
//set transformation target:
//t_, td_ and tdd_ represent the current position, velocity and acceleration we want
//to learn throught supervised learning. f_ represents the current values of
//the nonlinear function used to modulate the dmp behaviour, while ft_ is the target
//value for such nonlinear function.
//NOTE: is f_ actually used anywhere?????
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
transformationSystems_[i].t_ = trajectory.getTrajectoryPosition(rowIndex, i);
transformationSystems_[i].td_ = trajectory.getTrajectoryVelocity(rowIndex, i);
transformationSystems_[i].tdd_ = trajectory.getTrajectoryAcceleration(rowIndex, i);
transformationSystems_[i].f_ = 0.0;
transformationSystems_[i].ft_ = 0.0;
}
//fit the target function:
//it computes the ideal value of f_ (i.e. ft_) which allows to exactly reproduce
//the trajectory with the dmp
if (!integrateAndFit())
{
printf("ERROR: Could not integrate system and fit the target function\n");
params_.isLearned_ = false;
return params_.isLearned_;
}
}
if(!writeVectorToFile(trajectoryTargetFunctionInput_, "data/trajectory_target_function_input_.txt")) return false;
if(!transformationSystems_[0].writeTrajectoryTargetToFile("data/trajectory_target_.txt")) return false;
if (!learnTransformationTarget())
{
printf("ERROR: Could not learn transformation target.\n");
params_.isLearned_ = false;
return params_.isLearned_;
}
mseTotal = 0.0;
normalizedMseTotal = 0.0;
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
double mse;
double normalizedMse;
if (transformationSystems_[i].getMSE(mse))
{
mseTotal += mse;
}
if (transformationSystems_[i].getNormalizedMSE(normalizedMse))
{
normalizedMseTotal += normalizedMse;
}
transformationSystems_[i].resetMSE();
}
printf("Successfully learned DMP from trajectory.\n");
params_.isLearned_ = true;
return params_.isLearned_;
}
bool DynamicMovementPrimitive::getInitialStart(VectorXd &initialStart)
{
if (initialStart.size() != params_.numTransformationSystems_)
{
return false;
}
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
initialStart(i) = transformationSystems_[i].initialY0_;
}
return true;
}
bool DynamicMovementPrimitive::getInitialGoal(VectorXd &initialGoal)
{
if (initialGoal.size() != params_.numTransformationSystems_)
{
return false;
}
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
initialGoal(i) = transformationSystems_[i].initialGoal_;
}
return true;
}
bool DynamicMovementPrimitive::getGoal(VectorXd &goal)
{
if (goal.size() != params_.numTransformationSystems_)
{
return false;
}
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
goal(i) = transformationSystems_[i].goal_;
}
return true;
}
bool DynamicMovementPrimitive::setup(const double samplingFrequency)
{
VectorXd start = VectorXd::Zero(params_.numTransformationSystems_);
VectorXd goal = VectorXd::Zero(params_.numTransformationSystems_);
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
start(i) = transformationSystems_[i].initialY0_;
goal(i) = transformationSystems_[i].initialGoal_;
}
return setup(start, goal, params_.initialTau_, samplingFrequency);
}
bool DynamicMovementPrimitive::setup(const VectorXd &goal, const double movementDuration, const double samplingFrequency)
{
VectorXd start = VectorXd(params_.numTransformationSystems_);
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
start(i) = transformationSystems_[i].initialY0_;
}
if (!setup(start, goal, movementDuration, samplingFrequency))
{
params_.isSetup_ = false;
return params_.isSetup_;
}
//start has not been specified, need to be set before the DMP can be propagated
params_.isStartSet_ = false;
params_.isSetup_ = true;
return params_.isSetup_;
}
bool DynamicMovementPrimitive::setup(const VectorXd &start, const VectorXd &goal, const double movementDuration, const double samplingFrequency)
{
if (!initialized_)
{
printf("ERROR: DMP unit is not initialized.\n");
params_.isSetup_ = false;
return params_.isSetup_;
}
if (!params_.isLearned_)
{
printf("ERROR: DMP unit is not learned.\n");
params_.isSetup_ = false;
return params_.isSetup_;
}
if (start.size() != params_.numTransformationSystems_)
{
printf("ERROR: Cannot set start of the DMP, the size is %i, but should be %i.\n", start.size(), params_.numTransformationSystems_);
params_.isSetup_ = false;
return params_.isSetup_;
}
if (goal.size() != params_.numTransformationSystems_)
{
printf("ERROR: Cannot set goal of the DMP, the size is %i, but should be %i.\n", goal.size(), params_.numTransformationSystems_);
params_.isSetup_ = false;
return params_.isSetup_;
}
//reset canonical system
resetCanonicalState();
if (movementDuration > 0)
{
params_.tau_ = movementDuration;
if (samplingFrequency <= 0)
{
printf("ERROR: Sampling frequency %f [Hz] of the trajectory is not valid.\n", samplingFrequency);
params_.isSetup_ = false;
return params_.isSetup_;
}
params_.deltaT_ = static_cast<double> (1.0) / static_cast<double> (samplingFrequency);
}
else
{
params_.tau_ = params_.initialTau_;
params_.deltaT_ = params_.initialDeltaT_;
}
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
//set internal variables to zero
transformationSystems_[i].reset();
// set start and goal
transformationSystems_[i].setStart(start(i));
transformationSystems_[i].setGoal(goal(i));
//set current state to start state (position and velocity)
transformationSystems_[i].setState(start(i), 0.0);
}
params_.numSamples_ = 0;
params_.isStartSet_ = true;
params_.isSetup_ = true;
return params_.isSetup_;
}
bool DynamicMovementPrimitive::getCurrentPosition(VectorXd ¤tDesiredPosition, const int startIndex, const int endIndex)
{
if ((!params_.isSetup_) || (startIndex < 0) || (endIndex > params_.numTransformationSystems_) || (endIndex <= startIndex))
{
return false;
}
if (currentDesiredPosition.size() != endIndex - startIndex)
{
printf("ERROR: Provided vector has wrong size (%i), required size is (%i). Cannot get current position.\n", currentDesiredPosition.size(), endIndex-startIndex);
return false;
}
for (int i = startIndex; i < endIndex; i++)
{
currentDesiredPosition(i) = transformationSystems_[i].y_;
}
return true;
}
bool DynamicMovementPrimitive::changeGoal(const VectorXd &goal, const int startIndex, const int endIndex)
{
if ((!params_.isSetup_) || (startIndex < 0) || (endIndex > params_.numTransformationSystems_) || (endIndex <= startIndex))
{
return false;
}
if (goal.size() != endIndex - startIndex)
{
printf("ERROR: Provided vector has wrong size (%i), required size is (%i). Cannot change goal position.\n", goal.size(), endIndex-startIndex);
return false;
}
for (int i = startIndex; i < endIndex; i++)
{
transformationSystems_[i].setGoal(goal(i - startIndex));
}
return true;
}
bool DynamicMovementPrimitive::changeGoal(const double newGoal, const int index)
{
if ((!params_.isSetup_) || (index < 0) || (index > params_.numTransformationSystems_))
{
return false;
}
transformationSystems_[index].setGoal(newGoal);
return true;
}
bool DynamicMovementPrimitive::changeStart(const VectorXd &start)
{
if (!params_.isSetup_)
{
printf("ERROR: DMP is not setup\n");
return false;
}
if (start.size() != params_.numTransformationSystems_)
{
printf("ERROR: Start vector has wrong size (%i), it should be %i.\n", start.size(), params_.numTransformationSystems_);
return false;
}
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
transformationSystems_[i].setStart(start(i));
// set current state to start state (position and velocity)
transformationSystems_[i].setState(start(i), 0.0);
}
params_.isStartSet_ = true;
return true;
}
bool DynamicMovementPrimitive::getThetas(std::vector<VectorXd>& thetas)
{
if(!initialized_) return false;
thetas.clear();
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
int numRfs;
if (!transformationSystems_[i].lwrModel_.getNumRFS(numRfs))
{
printf("ERROR: Could not get number of receptive fields.\n");
return false;
}
VectorXd thetaVector = VectorXd::Zero(numRfs);
if (!transformationSystems_[i].lwrModel_.getThetas(thetaVector))
{
printf("ERROR: Could not retrieve thetas from transformation system %i.\n",i);
return false;
}
thetas.push_back(thetaVector);
}
return true;
}
bool DynamicMovementPrimitive::setThetas(const std::vector<VectorXd>& thetas)
{
if(!initialized_) return false;
if(!static_cast<int>(thetas.size()) == params_.numTransformationSystems_) return false;
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
if (!transformationSystems_[i].lwrModel_.setThetas(thetas[i]))
{
printf("ERROR: Could not set thetas of transformation system %i.\n",i);
return false;
}
}
return true;
}
bool DynamicMovementPrimitive::getWidthsAndCenters(std::vector<Eigen::VectorXd>& widths, std::vector<Eigen::VectorXd>& centers)
{
if(!initialized_) return false;
widths.clear();
centers.clear();
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
int numRfs;
if (!transformationSystems_[i].lwrModel_.getNumRFS(numRfs))
{
printf("ERROR: Could not get number of receptive fields.\n");
return false;
}
VectorXd centersVector = VectorXd::Zero(numRfs);
VectorXd widthsVector = VectorXd::Zero(numRfs);
if (!transformationSystems_[i].lwrModel_.getWidthsAndCenters(widthsVector , centersVector))
{
printf("ERROR: Could not retrieve thetas from transformation system %i.\n",i);
return false;
}
widths.push_back(widthsVector);
centers.push_back(centersVector);
}
return true;
}
bool DynamicMovementPrimitive::getWidthsAndCenters(const int transSystemIndex, VectorXd& widths, VectorXd& centers)
{
if(!initialized_) return false;
int numRfs;
if(getNumRFS(transSystemIndex, numRfs)) return false;
if(!widths.size() == numRfs) return false;
if(!centers.size() == numRfs) return false;
if (!transformationSystems_[transSystemIndex].lwrModel_.getWidthsAndCenters(widths, centers))
{
printf("ERROR: Could not get widths and centers of transformation system %i.\n", transSystemIndex);
return false;
}
return true;
}
bool DynamicMovementPrimitive::getBasisFunctions(const int numTimeSteps, std::vector<MatrixXd>& basisFunctions)
{
if(!initialized_) return false;
basisFunctions.clear();
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
int numRfs;
if (!getNumRFS(i, numRfs))
{
return false;
}
MatrixXd basisFunctionMatrix = MatrixXd::Zero(numTimeSteps, numRfs);
VectorXd xInputVector = VectorXd::Zero(numTimeSteps);
double dx = static_cast<double> (1.0) / static_cast<double> (numTimeSteps - 1);
xInputVector(0) = 0.0;
for (int j = 1; j < numTimeSteps; j++)
{
xInputVector(j) = xInputVector(j - 1) + dx;
}
if (!transformationSystems_[i].lwrModel_.generateBasisFunctionMatrix(xInputVector, basisFunctionMatrix))
{
printf("ERROR: LWR basis function generation failed!\n");
return false;
}
basisFunctions.push_back(basisFunctionMatrix);
}
return true;
}
bool DynamicMovementPrimitive::getCanonicalSystem(const int numTimeSteps, VectorXd& canSystemVector)
{
if(!canSystemVector.size() == numTimeSteps) return false;
if(numTimeSteps <= 0) return false;
double dt = params_.tau_ / static_cast<double> (numTimeSteps - 1);
double time = 0;
canSystemVector(0) = 1;
for (int j = 1; j < numTimeSteps; j++)
{
integrateCanonicalSystem(canSystemVector(j), time);
time += dt;
}
return true;
}
bool DynamicMovementPrimitive::getNumRFS(const int transId, int& numRfs)
{
if(!initialized_) return false;
if ((transId < 0) || (transId >= params_.numTransformationSystems_))
{
printf("ERROR: Could not get number of receptive fields, the transformation system id (%i) is invalid.\n", transId);
return false;
}
return transformationSystems_[transId].lwrModel_.getNumRFS(numRfs);
}
bool DynamicMovementPrimitive::getNumRFS(std::vector<int>& numRfs)
{
numRfs.clear();
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
int tmpNumRfs;
if (!getNumRFS(i, tmpNumRfs))
{
return false;
}
numRfs.push_back(tmpNumRfs);
}
return true;
}
bool DynamicMovementPrimitive::setDuration(const double movementDuration, const int samplingFrequency)
{
if (!params_.isSetup_)
{
printf("ERROR: DMP need to be setup first.\n");
return false;
}
if (samplingFrequency <= 0)
{
printf("ERROR: Sampling frequency %i [Hz] is not valid.\n", samplingFrequency);
return false;
}
//is this condition so restrictive???
if (movementDuration <= 0.5)
{
printf("ERROR: Movement duration (%f) is too small.\n", movementDuration);
return false;
}
params_.tau_ = movementDuration;
params_.deltaT_ = static_cast<double> (1.0) / static_cast<double> (samplingFrequency);
return true;
}
bool DynamicMovementPrimitive::propagateFull(Trajectory& trajectory, const double samplingDuration, const int numSamples)
{
if ((!params_.isLearned_) || (!params_.isSetup_) || (!params_.isStartSet_))
{
if(!params_.isLearned_) printf("ERROR: DMP is not learned from demonstration.\n");
if(!params_.isSetup_) printf("ERROR: DMP with is not setup. Need to set start, goal, and duration first.\n");
return false;
}
if(trajectory.getMaxDimension() < params_.numTransformationSystems_ * POS_VEL_ACC) return false;
if(trajectory.getMaxLength() <= numSamples) return false;
double specialSamplingFrequency = static_cast<double> (numSamples) / (samplingDuration);
if (!trajectory.setSamplingFrequency(specialSamplingFrequency))
{
printf("ERROR: Could not set sampling frequency.\n");
return false;
}
VectorXd desiredCoordinates = VectorXd::Zero(params_.numTransformationSystems_ * POS_VEL_ACC);
bool movementFinished = false;
while (!movementFinished)
{
if (!propagateStep(desiredCoordinates, movementFinished, samplingDuration, numSamples))
{
printf("ERROR: Could not propagate dmp.\n");
return false;
}
if (!trajectory.add(desiredCoordinates))
{
printf("ERROR: Could not add point to trajectory.\n");
return false;
}
}
return true;
}
bool DynamicMovementPrimitive::propagateStep(VectorXd &desiredCoordinates, bool &movementFinished)
{
return propagateStep(desiredCoordinates, movementFinished, params_.tau_, static_cast<int> (params_.tau_ / params_.deltaT_));
}
bool DynamicMovementPrimitive::propagateStep(VectorXd &desiredCoordinates, bool &movementFinished, const double samplingDuration, const int numSamples)
{
if ((!params_.isLearned_) || (!params_.isSetup_) || (!params_.isStartSet_))
{
if(!params_.isLearned_) printf("DMP is not learned from demonstration.\n");
if(!params_.isSetup_) printf("DMP is not setup. Need to set start, goal, and duration first.\n");
movementFinished = true;
return false;
}
if (desiredCoordinates.size() != params_.numTransformationSystems_ * POS_VEL_ACC)
{
printf("ERROR: Number of desired coordinates (%i) is not correct, it should be %i. TODO: REMOVE ME !!\n", desiredCoordinates.size(), params_.numTransformationSystems_ * POS_VEL_ACC);
movementFinished = true;
return false;
}
if (numSamples <= 0)
{
printf("ERROR: Number of samples (%i) is not valid. TODO: REMOVE ME !!\n", numSamples);
}
double dtTotal = samplingDuration / static_cast<double> (numSamples);
double dtThreshold = static_cast<double> (1.0) / DEFAULT_SAMPLING_FREQUENCY;
int numIteration = (int)ceil(dtTotal / dtThreshold);
//integrate the system, make sure that all internal variables are set properly
if (!integrate(dtTotal, numIteration))
{
printf("ERROR: Problem while integrating the dynamical system.\n");
movementFinished = true;
return false;
}
params_.numSamples_++;
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
desiredCoordinates(i * POS_VEL_ACC + _POS_ - 1) = transformationSystems_[i].y_;
desiredCoordinates(i * POS_VEL_ACC + _VEL_ - 1) = transformationSystems_[i].yd_;
desiredCoordinates(i * POS_VEL_ACC + _ACC_ - 1) = transformationSystems_[i].ydd_;
}
//check whether movement has finished...
if (params_.numSamples_ >= numSamples)
{
params_.isSetup_ = false;
params_.isStartSet_ = false;
movementFinished = true;
return true;
}
else
{
movementFinished = false;
}
return true;
}
bool DynamicMovementPrimitive::integrateAndFit()
{
/**
* trajectoryTargetFunctionInput_ represents the input for the locally weighted regression
* (lwr) algorithm used to find the values for theta parameters. As a classical regression
* problem, given a function y(x) to fit by tuning some parameters of the model, the input
* are some values of the independent variable (x) and the targets are the values of the
* dependent variable (y) assumed in correspondence of those x values. Since for a dmp the
* role of the independent variable (time) is played by the canonical system, in particular
* by the behaviour of x, the input of the lwr algorithm in this case is the behaviour of
* the canonical system itself, i.e. an exponentially decreasing trend from 1 to 0.
* trajectoryTarget_ contained in the transformationSystem object represents the sequence
* of values of the nonlinear function.
*/
trajectoryTargetFunctionInput_.push_back(canonicalSystem_.x);
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
transformationSystems_[i].ft_ = ((transformationSystems_[i].tdd_ * pow(params_.tau_, 2) + params_.dGain_ * transformationSystems_[i].td_
* params_.tau_) / params_.kGain_) - (transformationSystems_[i].goal_ - transformationSystems_[i].t_)
+ (transformationSystems_[i].goal_ - transformationSystems_[i].y0_) * canonicalSystem_.x;
transformationSystems_[i].ft_ /= canonicalSystem_.x;
//the nonlinearity is computed by LWR (later)
transformationSystems_[i].trajectoryTarget_.push_back(transformationSystems_[i].ft_);
//transformation state derivatives (make use of target knowledge)
transformationSystems_[i].zd_ = (params_.kGain_ * (transformationSystems_[i].goal_ - transformationSystems_[i].y_) - params_.dGain_
* transformationSystems_[i].z_ - params_.kGain_ * (transformationSystems_[i].goal_ - transformationSystems_[i].y0_)
* canonicalSystem_.x + params_.kGain_ * transformationSystems_[i].ft_) * (static_cast<double> (1.0) / params_.tau_);
//integrate all systems, coupling between z and y variables
transformationSystems_[i].z_ += transformationSystems_[i].zd_ * params_.deltaT_;
transformationSystems_[i].y_ += transformationSystems_[i].yd_ * params_.deltaT_;
}
//canonical system
integrateCanonicalSystem(canonicalSystem_.x, canonicalSystem_.time);
canonicalSystem_.time += params_.deltaT_;
return true;
}
bool DynamicMovementPrimitive::learnTransformationTarget()
{
/**
* The input of the regression algorithm (lwr) is trajectory_target_function_input_
* which represents the indipendent variable behaviour (i.e. canonical system/x) and the target is
* trajectory_target_ , contained into the transformation system, which are the values of the nonlinear
* function f.
*/
Eigen::Map<VectorXd> input = VectorXd::Map(&trajectoryTargetFunctionInput_[0], trajectoryTargetFunctionInput_.size());
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
if (trajectoryTargetFunctionInput_.size() != transformationSystems_[i].trajectoryTarget_.size())
{
printf("ERROR: Traget trajectory of transformation system %i has different size than input trajectory.\n", i);
return false;
}
Eigen::Map<VectorXd> target = VectorXd::Map(&transformationSystems_[i].trajectoryTarget_[0], transformationSystems_[i].trajectoryTarget_.size());
if (!transformationSystems_[i].lwrModel_.learnWeights(input, target))
{
printf("ERROR: Could not learn weights of transformation system %i.\n", i);
return false;
}
}
//compute mean squared error
for (int i = 0; i < params_.numTransformationSystems_; ++i)
{
transformationSystems_[i].computeMSE();
}
return true;
}
inline bool DynamicMovementPrimitive::integrate(const double dtTotal, const int numIteration)
{
//what does num_iteration means?
double dt = dtTotal / static_cast<double> (numIteration);
for (int n = 0; n < numIteration; n++)
{
for (int i = 0; i < params_.numTransformationSystems_; i++)
{
//compute nonlinearity using LWR
double prediction = 0;
if (!transformationSystems_[i].lwrModel_.predict(canonicalSystem_.x, prediction))
{
printf("ERROR: Could not predict output.\n");
return false;
}
//compute all the actual values for the transformation system differential equations.
transformationSystems_[i].f_ = prediction * canonicalSystem_.x;
transformationSystems_[i].zd_ = (params_.kGain_ * (transformationSystems_[i].goal_ - transformationSystems_[i].y_) - params_.dGain_
* transformationSystems_[i].z_ - params_.kGain_ * (transformationSystems_[i].goal_ - transformationSystems_[i].y0_)
* canonicalSystem_.x + params_.kGain_ * transformationSystems_[i].f_) * (static_cast<double> (1.0) / params_.tau_);
transformationSystems_[i].yd_ = transformationSystems_[i].z_ * (static_cast<double> (1.0) / params_.tau_);
transformationSystems_[i].ydd_ = transformationSystems_[i].zd_ * (static_cast<double> (1.0) / params_.tau_);
transformationSystems_[i].z_ += transformationSystems_[i].zd_ * dt; //* params_.delta_t_;
transformationSystems_[i].y_ += transformationSystems_[i].yd_ * dt; //* params_.delta_t_;
}
//canonical system
integrateCanonicalSystem(canonicalSystem_.x, canonicalSystem_.time);
canonicalSystem_.time += dt; //+= params_.delta_t_;
}
return true;
}
inline void DynamicMovementPrimitive::integrateCanonicalSystem(double& canonicalSystemX, const double canonicalSystemTime) const
{
canonicalSystemX = exp(-(params_.alphaX_ / params_.tau_) * canonicalSystemTime);
}
bool DynamicMovementPrimitive::isIncreasing(int transformationSystemIndex, bool &isIncreasing)
{
if ((transformationSystemIndex >= 0) && (transformationSystemIndex < params_.numTransformationSystems_) && params_.isLearned_)
{
return (transformationSystems_[transformationSystemIndex].initialY0_ >= transformationSystems_[transformationSystemIndex].initialGoal_);
}
return false;
}
double DynamicMovementPrimitive::getProgress() const
{
double progress;
if (canonicalSystem_.x < 1.0e-8)
{
progress = 1.0;
}
else if (params_.alphaX_ > 1.0e-8)
{
progress = -log(canonicalSystem_.x) / params_.alphaX_;
}
else
{
progress = 0.0;
}
return progress;
}
bool DynamicMovementPrimitive::writeVectorToFile(std::vector<double> trajectory, std::string fileName)
{
FILE *fp;
int count = 0;
if ((fp = fopen(fileName.c_str(), "w")) == NULL)
{
printf("ERROR: Cannot open file: %s\n", fileName.c_str());
return false;
}
std::vector<double>::iterator iter = trajectory.begin();
for(; iter != trajectory.end(); ++iter)
{
fprintf(fp, "%f\n", *iter);
count++;
}
return true;
}
}
| [
"hychyc07@cs.utexas.edu"
] | hychyc07@cs.utexas.edu |
ba1d4d295fcf6b0c9084acf6905570b5f9b3eafe | 6bcbd9c9c9cf07846eb76927804cc0b6b48247c0 | /src/third_party/webrtc/modules/remote_bitrate_estimator/overuse_detector_unittest.cc | 8ff3bddf546acf4e894e5d94d50794095e0f2eb0 | [] | no_license | haska1025/spiritbreaker | 108730c882e7b82fd1027e2efdeca8205f93e51e | 0bc5129d373e54b17084c5dfc9be05f7cc28ce74 | refs/heads/master | 2022-12-23T07:07:29.032596 | 2020-04-05T06:05:10 | 2020-04-05T06:05:10 | 176,910,696 | 5 | 3 | null | 2022-12-10T15:01:15 | 2019-03-21T09:18:25 | C++ | UTF-8 | C++ | false | false | 28,633 | cc | /*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <cstdlib>
#include <memory>
#include "common_types.h" // NOLINT(build/include)
#include "modules/remote_bitrate_estimator/inter_arrival.h"
#include "modules/remote_bitrate_estimator/overuse_detector.h"
#include "modules/remote_bitrate_estimator/overuse_estimator.h"
#include "rtc_base/random.h"
#include "test/field_trial.h"
#include "test/gtest.h"
namespace webrtc {
namespace testing {
const double kRtpTimestampToMs = 1.0 / 90.0;
class OveruseDetectorTest : public ::testing::Test {
public:
OveruseDetectorTest()
: now_ms_(0),
receive_time_ms_(0),
rtp_timestamp_(10 * 90),
overuse_detector_(),
overuse_estimator_(new OveruseEstimator(options_)),
inter_arrival_(new InterArrival(5 * 90, kRtpTimestampToMs, true)),
random_(123456789) {}
protected:
void SetUp() override { overuse_detector_.reset(new OveruseDetector()); }
int Run100000Samples(int packets_per_frame,
size_t packet_size,
int mean_ms,
int standard_deviation_ms) {
int unique_overuse = 0;
int last_overuse = -1;
for (int i = 0; i < 100000; ++i) {
for (int j = 0; j < packets_per_frame; ++j) {
UpdateDetector(rtp_timestamp_, receive_time_ms_, packet_size);
}
rtp_timestamp_ += mean_ms * 90;
now_ms_ += mean_ms;
receive_time_ms_ = std::max<int64_t>(
receive_time_ms_,
now_ms_ + static_cast<int64_t>(
random_.Gaussian(0, standard_deviation_ms) + 0.5));
if (BandwidthUsage::kBwOverusing == overuse_detector_->State()) {
if (last_overuse + 1 != i) {
unique_overuse++;
}
last_overuse = i;
}
}
return unique_overuse;
}
int RunUntilOveruse(int packets_per_frame,
size_t packet_size,
int mean_ms,
int standard_deviation_ms,
int drift_per_frame_ms) {
// Simulate a higher send pace, that is too high.
for (int i = 0; i < 1000; ++i) {
for (int j = 0; j < packets_per_frame; ++j) {
UpdateDetector(rtp_timestamp_, receive_time_ms_, packet_size);
}
rtp_timestamp_ += mean_ms * 90;
now_ms_ += mean_ms + drift_per_frame_ms;
receive_time_ms_ = std::max<int64_t>(
receive_time_ms_,
now_ms_ + static_cast<int64_t>(
random_.Gaussian(0, standard_deviation_ms) + 0.5));
if (BandwidthUsage::kBwOverusing == overuse_detector_->State()) {
return i + 1;
}
}
return -1;
}
void UpdateDetector(uint32_t rtp_timestamp,
int64_t receive_time_ms,
size_t packet_size) {
uint32_t timestamp_delta;
int64_t time_delta;
int size_delta;
if (inter_arrival_->ComputeDeltas(
rtp_timestamp, receive_time_ms, receive_time_ms, packet_size,
×tamp_delta, &time_delta, &size_delta)) {
double timestamp_delta_ms = timestamp_delta / 90.0;
overuse_estimator_->Update(time_delta, timestamp_delta_ms, size_delta,
overuse_detector_->State(), receive_time_ms);
overuse_detector_->Detect(
overuse_estimator_->offset(), timestamp_delta_ms,
overuse_estimator_->num_of_deltas(), receive_time_ms);
}
}
int64_t now_ms_;
int64_t receive_time_ms_;
uint32_t rtp_timestamp_;
OverUseDetectorOptions options_;
std::unique_ptr<OveruseDetector> overuse_detector_;
std::unique_ptr<OveruseEstimator> overuse_estimator_;
std::unique_ptr<InterArrival> inter_arrival_;
Random random_;
};
TEST_F(OveruseDetectorTest, GaussianRandom) {
int buckets[100];
memset(buckets, 0, sizeof(buckets));
for (int i = 0; i < 100000; ++i) {
int index = random_.Gaussian(49, 10);
if (index >= 0 && index < 100)
buckets[index]++;
}
for (int n = 0; n < 100; ++n) {
printf("Bucket n:%d, %d\n", n, buckets[n]);
}
}
TEST_F(OveruseDetectorTest, SimpleNonOveruse30fps) {
size_t packet_size = 1200;
uint32_t frame_duration_ms = 33;
uint32_t rtp_timestamp = 10 * 90;
// No variance.
for (int i = 0; i < 1000; ++i) {
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
now_ms_ += frame_duration_ms;
rtp_timestamp += frame_duration_ms * 90;
EXPECT_EQ(BandwidthUsage::kBwNormal, overuse_detector_->State());
}
}
// Roughly 1 Mbit/s
TEST_F(OveruseDetectorTest, SimpleNonOveruseWithReceiveVariance) {
uint32_t frame_duration_ms = 10;
uint32_t rtp_timestamp = 10 * 90;
size_t packet_size = 1200;
for (int i = 0; i < 1000; ++i) {
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
rtp_timestamp += frame_duration_ms * 90;
if (i % 2) {
now_ms_ += frame_duration_ms - 5;
} else {
now_ms_ += frame_duration_ms + 5;
}
EXPECT_EQ(BandwidthUsage::kBwNormal, overuse_detector_->State());
}
}
TEST_F(OveruseDetectorTest, SimpleNonOveruseWithRtpTimestampVariance) {
// Roughly 1 Mbit/s.
uint32_t frame_duration_ms = 10;
uint32_t rtp_timestamp = 10 * 90;
size_t packet_size = 1200;
for (int i = 0; i < 1000; ++i) {
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
now_ms_ += frame_duration_ms;
if (i % 2) {
rtp_timestamp += (frame_duration_ms - 5) * 90;
} else {
rtp_timestamp += (frame_duration_ms + 5) * 90;
}
EXPECT_EQ(BandwidthUsage::kBwNormal, overuse_detector_->State());
}
}
TEST_F(OveruseDetectorTest, SimpleOveruse2000Kbit30fps) {
size_t packet_size = 1200;
int packets_per_frame = 6;
int frame_duration_ms = 33;
int drift_per_frame_ms = 1;
int sigma_ms = 0; // No variance.
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(7, frames_until_overuse);
}
TEST_F(OveruseDetectorTest, SimpleOveruse100kbit10fps) {
size_t packet_size = 1200;
int packets_per_frame = 1;
int frame_duration_ms = 100;
int drift_per_frame_ms = 1;
int sigma_ms = 0; // No variance.
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(7, frames_until_overuse);
}
TEST_F(OveruseDetectorTest, DISABLED_OveruseWithHighVariance100Kbit10fps) {
uint32_t frame_duration_ms = 100;
uint32_t drift_per_frame_ms = 10;
uint32_t rtp_timestamp = frame_duration_ms * 90;
size_t packet_size = 1200;
int offset = 10;
// Run 1000 samples to reach steady state.
for (int i = 0; i < 1000; ++i) {
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
rtp_timestamp += frame_duration_ms * 90;
if (i % 2) {
offset = random_.Rand(0, 49);
now_ms_ += frame_duration_ms - offset;
} else {
now_ms_ += frame_duration_ms + offset;
}
EXPECT_EQ(BandwidthUsage::kBwNormal, overuse_detector_->State());
}
// Simulate a higher send pace, that is too high.
// Above noise generate a standard deviation of approximately 28 ms.
// Total build up of 150 ms.
for (int j = 0; j < 15; ++j) {
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
now_ms_ += frame_duration_ms + drift_per_frame_ms;
rtp_timestamp += frame_duration_ms * 90;
EXPECT_EQ(BandwidthUsage::kBwNormal, overuse_detector_->State());
}
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
EXPECT_EQ(BandwidthUsage::kBwOverusing, overuse_detector_->State());
}
TEST_F(OveruseDetectorTest, DISABLED_OveruseWithLowVariance100Kbit10fps) {
uint32_t frame_duration_ms = 100;
uint32_t drift_per_frame_ms = 1;
uint32_t rtp_timestamp = frame_duration_ms * 90;
size_t packet_size = 1200;
int offset = 10;
// Run 1000 samples to reach steady state.
for (int i = 0; i < 1000; ++i) {
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
rtp_timestamp += frame_duration_ms * 90;
if (i % 2) {
offset = random_.Rand(0, 1);
now_ms_ += frame_duration_ms - offset;
} else {
now_ms_ += frame_duration_ms + offset;
}
EXPECT_EQ(BandwidthUsage::kBwNormal, overuse_detector_->State());
}
// Simulate a higher send pace, that is too high.
// Total build up of 6 ms.
for (int j = 0; j < 6; ++j) {
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
now_ms_ += frame_duration_ms + drift_per_frame_ms;
rtp_timestamp += frame_duration_ms * 90;
EXPECT_EQ(BandwidthUsage::kBwNormal, overuse_detector_->State());
}
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
EXPECT_EQ(BandwidthUsage::kBwOverusing, overuse_detector_->State());
}
TEST_F(OveruseDetectorTest, OveruseWithLowVariance2000Kbit30fps) {
uint32_t frame_duration_ms = 33;
uint32_t drift_per_frame_ms = 1;
uint32_t rtp_timestamp = frame_duration_ms * 90;
size_t packet_size = 1200;
int offset = 0;
// Run 1000 samples to reach steady state.
for (int i = 0; i < 1000; ++i) {
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
rtp_timestamp += frame_duration_ms * 90;
if (i % 2) {
offset = random_.Rand(0, 1);
now_ms_ += frame_duration_ms - offset;
} else {
now_ms_ += frame_duration_ms + offset;
}
EXPECT_EQ(BandwidthUsage::kBwNormal, overuse_detector_->State());
}
// Simulate a higher send pace, that is too high.
// Total build up of 30 ms.
for (int j = 0; j < 3; ++j) {
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
now_ms_ += frame_duration_ms + drift_per_frame_ms * 6;
rtp_timestamp += frame_duration_ms * 90;
EXPECT_EQ(BandwidthUsage::kBwNormal, overuse_detector_->State());
}
UpdateDetector(rtp_timestamp, now_ms_, packet_size);
EXPECT_EQ(BandwidthUsage::kBwOverusing, overuse_detector_->State());
}
#if defined(WEBRTC_ANDROID)
#define MAYBE_LowGaussianVariance30Kbit3fps \
DISABLED_LowGaussianVariance30Kbit3fps
#else
#define MAYBE_LowGaussianVariance30Kbit3fps LowGaussianVariance30Kbit3fps
#endif
TEST_F(OveruseDetectorTest, MAYBE_LowGaussianVariance30Kbit3fps) {
size_t packet_size = 1200;
int packets_per_frame = 1;
int frame_duration_ms = 333;
int drift_per_frame_ms = 1;
int sigma_ms = 3;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(20, frames_until_overuse);
}
TEST_F(OveruseDetectorTest, LowGaussianVarianceFastDrift30Kbit3fps) {
size_t packet_size = 1200;
int packets_per_frame = 1;
int frame_duration_ms = 333;
int drift_per_frame_ms = 100;
int sigma_ms = 3;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(4, frames_until_overuse);
}
TEST_F(OveruseDetectorTest, HighGaussianVariance30Kbit3fps) {
size_t packet_size = 1200;
int packets_per_frame = 1;
int frame_duration_ms = 333;
int drift_per_frame_ms = 1;
int sigma_ms = 10;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(44, frames_until_overuse);
}
TEST_F(OveruseDetectorTest, HighGaussianVarianceFastDrift30Kbit3fps) {
size_t packet_size = 1200;
int packets_per_frame = 1;
int frame_duration_ms = 333;
int drift_per_frame_ms = 100;
int sigma_ms = 10;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(4, frames_until_overuse);
}
#if defined(WEBRTC_ANDROID)
#define MAYBE_LowGaussianVariance100Kbit5fps \
DISABLED_LowGaussianVariance100Kbit5fps
#else
#define MAYBE_LowGaussianVariance100Kbit5fps LowGaussianVariance100Kbit5fps
#endif
TEST_F(OveruseDetectorTest, MAYBE_LowGaussianVariance100Kbit5fps) {
size_t packet_size = 1200;
int packets_per_frame = 2;
int frame_duration_ms = 200;
int drift_per_frame_ms = 1;
int sigma_ms = 3;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(20, frames_until_overuse);
}
#if defined(WEBRTC_ANDROID)
#define MAYBE_HighGaussianVariance100Kbit5fps \
DISABLED_HighGaussianVariance100Kbit5fps
#else
#define MAYBE_HighGaussianVariance100Kbit5fps HighGaussianVariance100Kbit5fps
#endif
TEST_F(OveruseDetectorTest, MAYBE_HighGaussianVariance100Kbit5fps) {
size_t packet_size = 1200;
int packets_per_frame = 2;
int frame_duration_ms = 200;
int drift_per_frame_ms = 1;
int sigma_ms = 10;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(44, frames_until_overuse);
}
#if defined(WEBRTC_ANDROID)
#define MAYBE_LowGaussianVariance100Kbit10fps \
DISABLED_LowGaussianVariance100Kbit10fps
#else
#define MAYBE_LowGaussianVariance100Kbit10fps LowGaussianVariance100Kbit10fps
#endif
TEST_F(OveruseDetectorTest, MAYBE_LowGaussianVariance100Kbit10fps) {
size_t packet_size = 1200;
int packets_per_frame = 1;
int frame_duration_ms = 100;
int drift_per_frame_ms = 1;
int sigma_ms = 3;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(20, frames_until_overuse);
}
#if defined(WEBRTC_ANDROID)
#define MAYBE_HighGaussianVariance100Kbit10fps \
DISABLED_HighGaussianVariance100Kbit10fps
#else
#define MAYBE_HighGaussianVariance100Kbit10fps HighGaussianVariance100Kbit10fps
#endif
TEST_F(OveruseDetectorTest, MAYBE_HighGaussianVariance100Kbit10fps) {
size_t packet_size = 1200;
int packets_per_frame = 1;
int frame_duration_ms = 100;
int drift_per_frame_ms = 1;
int sigma_ms = 10;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(44, frames_until_overuse);
}
#if defined(WEBRTC_ANDROID)
#define MAYBE_LowGaussianVariance300Kbit30fps \
DISABLED_LowGaussianVariance300Kbit30fps
#else
#define MAYBE_LowGaussianVariance300Kbit30fps LowGaussianVariance300Kbit30fps
#endif
TEST_F(OveruseDetectorTest, MAYBE_LowGaussianVariance300Kbit30fps) {
size_t packet_size = 1200;
int packets_per_frame = 1;
int frame_duration_ms = 33;
int drift_per_frame_ms = 1;
int sigma_ms = 3;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(19, frames_until_overuse);
}
TEST_F(OveruseDetectorTest, LowGaussianVarianceFastDrift300Kbit30fps) {
size_t packet_size = 1200;
int packets_per_frame = 1;
int frame_duration_ms = 33;
int drift_per_frame_ms = 10;
int sigma_ms = 3;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(5, frames_until_overuse);
}
TEST_F(OveruseDetectorTest, HighGaussianVariance300Kbit30fps) {
size_t packet_size = 1200;
int packets_per_frame = 1;
int frame_duration_ms = 33;
int drift_per_frame_ms = 1;
int sigma_ms = 10;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(44, frames_until_overuse);
}
TEST_F(OveruseDetectorTest, HighGaussianVarianceFastDrift300Kbit30fps) {
size_t packet_size = 1200;
int packets_per_frame = 1;
int frame_duration_ms = 33;
int drift_per_frame_ms = 10;
int sigma_ms = 10;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(10, frames_until_overuse);
}
#if defined(WEBRTC_ANDROID)
#define MAYBE_LowGaussianVariance1000Kbit30fps \
DISABLED_LowGaussianVariance1000Kbit30fps
#else
#define MAYBE_LowGaussianVariance1000Kbit30fps LowGaussianVariance1000Kbit30fps
#endif
TEST_F(OveruseDetectorTest, MAYBE_LowGaussianVariance1000Kbit30fps) {
size_t packet_size = 1200;
int packets_per_frame = 3;
int frame_duration_ms = 33;
int drift_per_frame_ms = 1;
int sigma_ms = 3;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(19, frames_until_overuse);
}
TEST_F(OveruseDetectorTest, LowGaussianVarianceFastDrift1000Kbit30fps) {
size_t packet_size = 1200;
int packets_per_frame = 3;
int frame_duration_ms = 33;
int drift_per_frame_ms = 10;
int sigma_ms = 3;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(5, frames_until_overuse);
}
TEST_F(OveruseDetectorTest, HighGaussianVariance1000Kbit30fps) {
size_t packet_size = 1200;
int packets_per_frame = 3;
int frame_duration_ms = 33;
int drift_per_frame_ms = 1;
int sigma_ms = 10;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(44, frames_until_overuse);
}
TEST_F(OveruseDetectorTest, HighGaussianVarianceFastDrift1000Kbit30fps) {
size_t packet_size = 1200;
int packets_per_frame = 3;
int frame_duration_ms = 33;
int drift_per_frame_ms = 10;
int sigma_ms = 10;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(10, frames_until_overuse);
}
#if defined(WEBRTC_ANDROID)
#define MAYBE_LowGaussianVariance2000Kbit30fps \
DISABLED_LowGaussianVariance2000Kbit30fps
#else
#define MAYBE_LowGaussianVariance2000Kbit30fps LowGaussianVariance2000Kbit30fps
#endif
TEST_F(OveruseDetectorTest, MAYBE_LowGaussianVariance2000Kbit30fps) {
size_t packet_size = 1200;
int packets_per_frame = 6;
int frame_duration_ms = 33;
int drift_per_frame_ms = 1;
int sigma_ms = 3;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(19, frames_until_overuse);
}
TEST_F(OveruseDetectorTest, LowGaussianVarianceFastDrift2000Kbit30fps) {
size_t packet_size = 1200;
int packets_per_frame = 6;
int frame_duration_ms = 33;
int drift_per_frame_ms = 10;
int sigma_ms = 3;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(5, frames_until_overuse);
}
TEST_F(OveruseDetectorTest, HighGaussianVariance2000Kbit30fps) {
size_t packet_size = 1200;
int packets_per_frame = 6;
int frame_duration_ms = 33;
int drift_per_frame_ms = 1;
int sigma_ms = 10;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(44, frames_until_overuse);
}
TEST_F(OveruseDetectorTest, HighGaussianVarianceFastDrift2000Kbit30fps) {
size_t packet_size = 1200;
int packets_per_frame = 6;
int frame_duration_ms = 33;
int drift_per_frame_ms = 10;
int sigma_ms = 10;
int unique_overuse = Run100000Samples(packets_per_frame, packet_size,
frame_duration_ms, sigma_ms);
EXPECT_EQ(0, unique_overuse);
int frames_until_overuse =
RunUntilOveruse(packets_per_frame, packet_size, frame_duration_ms,
sigma_ms, drift_per_frame_ms);
EXPECT_EQ(10, frames_until_overuse);
}
class OveruseDetectorExperimentTest : public OveruseDetectorTest {
public:
OveruseDetectorExperimentTest()
: override_field_trials_(
"WebRTC-AdaptiveBweThreshold/Enabled-0.01,0.00018/") {}
protected:
void SetUp() override { overuse_detector_.reset(new OveruseDetector()); }
test::ScopedFieldTrials override_field_trials_;
};
TEST_F(OveruseDetectorExperimentTest, ThresholdAdapts) {
const double kOffset = 0.21;
double kTsDelta = 3000.0;
int64_t now_ms = 0;
int num_deltas = 60;
const int kBatchLength = 10;
// Pass in a positive offset and verify it triggers overuse.
bool overuse_detected = false;
for (int i = 0; i < kBatchLength; ++i) {
BandwidthUsage overuse_state =
overuse_detector_->Detect(kOffset, kTsDelta, num_deltas, now_ms);
if (overuse_state == BandwidthUsage::kBwOverusing) {
overuse_detected = true;
}
++num_deltas;
now_ms += 5;
}
EXPECT_TRUE(overuse_detected);
// Force the threshold to increase by passing in a higher offset.
overuse_detected = false;
for (int i = 0; i < kBatchLength; ++i) {
BandwidthUsage overuse_state =
overuse_detector_->Detect(1.1 * kOffset, kTsDelta, num_deltas, now_ms);
if (overuse_state == BandwidthUsage::kBwOverusing) {
overuse_detected = true;
}
++num_deltas;
now_ms += 5;
}
EXPECT_TRUE(overuse_detected);
// Verify that the same offset as before no longer triggers overuse.
overuse_detected = false;
for (int i = 0; i < kBatchLength; ++i) {
BandwidthUsage overuse_state =
overuse_detector_->Detect(kOffset, kTsDelta, num_deltas, now_ms);
if (overuse_state == BandwidthUsage::kBwOverusing) {
overuse_detected = true;
}
++num_deltas;
now_ms += 5;
}
EXPECT_FALSE(overuse_detected);
// Pass in a low offset to make the threshold adapt down.
for (int i = 0; i < 15 * kBatchLength; ++i) {
BandwidthUsage overuse_state =
overuse_detector_->Detect(0.7 * kOffset, kTsDelta, num_deltas, now_ms);
if (overuse_state == BandwidthUsage::kBwOverusing) {
overuse_detected = true;
}
++num_deltas;
now_ms += 5;
}
EXPECT_FALSE(overuse_detected);
// Make sure the original offset now again triggers overuse.
for (int i = 0; i < kBatchLength; ++i) {
BandwidthUsage overuse_state =
overuse_detector_->Detect(kOffset, kTsDelta, num_deltas, now_ms);
if (overuse_state == BandwidthUsage::kBwOverusing) {
overuse_detected = true;
}
++num_deltas;
now_ms += 5;
}
EXPECT_TRUE(overuse_detected);
}
TEST_F(OveruseDetectorExperimentTest, DoesntAdaptToSpikes) {
const double kOffset = 1.0;
const double kLargeOffset = 20.0;
double kTsDelta = 3000.0;
int64_t now_ms = 0;
int num_deltas = 60;
const int kBatchLength = 10;
const int kShortBatchLength = 3;
// Pass in a positive offset and verify it triggers overuse.
bool overuse_detected = false;
for (int i = 0; i < kBatchLength; ++i) {
BandwidthUsage overuse_state =
overuse_detector_->Detect(kOffset, kTsDelta, num_deltas, now_ms);
if (overuse_state == BandwidthUsage::kBwOverusing) {
overuse_detected = true;
}
++num_deltas;
now_ms += 5;
}
// Pass in a large offset. This shouldn't have a too big impact on the
// threshold, but still trigger an overuse.
now_ms += 100;
overuse_detected = false;
for (int i = 0; i < kShortBatchLength; ++i) {
BandwidthUsage overuse_state =
overuse_detector_->Detect(kLargeOffset, kTsDelta, num_deltas, now_ms);
if (overuse_state == BandwidthUsage::kBwOverusing) {
overuse_detected = true;
}
++num_deltas;
now_ms += 5;
}
EXPECT_TRUE(overuse_detected);
// Pass in a positive normal offset and verify it still triggers.
overuse_detected = false;
for (int i = 0; i < kBatchLength; ++i) {
BandwidthUsage overuse_state =
overuse_detector_->Detect(kOffset, kTsDelta, num_deltas, now_ms);
if (overuse_state == BandwidthUsage::kBwOverusing) {
overuse_detected = true;
}
++num_deltas;
now_ms += 5;
}
EXPECT_TRUE(overuse_detected);
}
} // namespace testing
} // namespace webrtc
| [
"evilwolf125@163.com"
] | evilwolf125@163.com |
e82d1cd1c4059c0cde88cad8b71005935b0aff61 | a66ed48d62837d55df45408afa07cb3308eefe02 | /WpGenetic/src/CPairOfChromosome.cpp | 4b47b880499bf4ff7954eecb21fdbe12ff0ace3f | [] | no_license | cybiosphere/Source | 228a2cb9c7edf6bc518b39405a9b9b8dd79226db | 5da9b59521703d1c46dcf0dde6fc3582c56ae57d | refs/heads/master | 2023-08-31T03:32:42.271519 | 2023-08-26T20:33:09 | 2023-08-26T20:33:09 | 54,154,398 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,331 | cpp | /*
https://github.com/cybiosphere
copyright (c) 2005-2014 Frederic RIBERT
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
//===========================================================================
// FILE: CPairOfChromosome.cpp
//
// GENERAL DESCRIPTION:
// This CLASS represents a set of basic caracteristics of a creature
//
// (C) COPYRIGHT 2005. All Rights Reserved.
//
// 26/12/2002 : Creation
//
//===========================================================================
#include "CPairOfChromosome.h"
///////////////////////////////////////
// constructors
CPairOfChromosome::CPairOfChromosome(size_t number)
{
m_IdNumber = number;
m_pPaterChromosome = new CChromosome(number);
m_pMaterChromosome = new CChromosome(number);
}
CPairOfChromosome::CPairOfChromosome(CPairOfChromosome& model)
{
// inherite both chromosome from model (clonage)
m_IdNumber = model.m_IdNumber;
m_pMaterChromosome = new CChromosome(*model.m_pMaterChromosome);
m_pPaterChromosome = new CChromosome(*model.m_pPaterChromosome);
}
CPairOfChromosome::CPairOfChromosome(CPairOfChromosome& mother, CPairOfChromosome& father, double crossoverRate)
{
m_IdNumber = mother.m_IdNumber;
// inherite 1 chromosome from mother
if ((mother.m_pMaterChromosome->getChromosomeType() == CHROMOSOME_NEUTRAL) && testChance(crossoverRate))
{
string crossedStr;
m_pMaterChromosome = new CChromosome(m_IdNumber);
getCrossedChromosomeStr(mother, crossedStr);
m_pMaterChromosome->buildGenesFromStringData(crossedStr);
}
else if (testChance(50.0))
{
m_pMaterChromosome = new CChromosome(*mother.m_pMaterChromosome);
}
else
{
m_pMaterChromosome = new CChromosome(*mother.m_pPaterChromosome);
}
// inherite 1 chromosome from father
if ((father.m_pMaterChromosome->getChromosomeType() == CHROMOSOME_NEUTRAL) && testChance(crossoverRate))
{
string crossedStr;
m_pPaterChromosome = new CChromosome(m_IdNumber);
getCrossedChromosomeStr(father, crossedStr);
m_pPaterChromosome->buildGenesFromStringData(crossedStr);
}
else if (testChance(50.0))
{
m_pPaterChromosome = new CChromosome(*father.m_pMaterChromosome);
}
else
{
m_pPaterChromosome = new CChromosome(*father.m_pPaterChromosome);
}
}
CPairOfChromosome::~CPairOfChromosome()
{
if (m_pPaterChromosome!=NULL)
delete m_pPaterChromosome;
if (m_pMaterChromosome!=NULL)
delete m_pMaterChromosome;
}
///////////////////////////////////////
// methods
CChromosome* CPairOfChromosome::getPaterChromosome ()
{
return (m_pPaterChromosome);
}
CChromosome* CPairOfChromosome::getMaterChromosome ()
{
return (m_pMaterChromosome);
}
size_t CPairOfChromosome::getNumGenes()
{
size_t materNumGen = 0;
size_t paterNumGen = 0;
if (m_pMaterChromosome!=NULL)
materNumGen = m_pMaterChromosome->getNumGene();
if (m_pPaterChromosome!=NULL)
paterNumGen = m_pPaterChromosome->getNumGene();
if (paterNumGen>materNumGen)
return (paterNumGen);
else
return (materNumGen);
}
CGene* CPairOfChromosome::getDominantAllele(size_t index)
{
CGene* pResu = NULL;
CGene* pMaterGene = NULL;
CGene* pPaterGene = NULL;
if (m_pMaterChromosome!=NULL)
pMaterGene = m_pMaterChromosome->getGene(index);
if (m_pPaterChromosome!=NULL)
pPaterGene = m_pPaterChromosome->getGene(index);
if ((pMaterGene == NULL)&&(pPaterGene == NULL))
{
pResu = NULL;
}
else if (pMaterGene == NULL)
{
pResu = pPaterGene;
}
else if (pPaterGene == NULL)
{
pResu = pMaterGene;
}
else if (m_pPaterChromosome->getChromosomeType() == CHROMOSOME_SEX_MALE) // Rule: sexual male chromo always dominant
{
pResu = pPaterGene;
}
else
{
// Rq: No check on Gene compatibility.
// No codominance supported. Dominant allele has the smallest factor
if (pPaterGene->getRecessiveFactor() < pMaterGene->getRecessiveFactor())
pResu = pPaterGene;
else
pResu = pMaterGene;
}
return (pResu);
}
bool CPairOfChromosome::tryMutation(int rate)
{
if ((m_pPaterChromosome->tryMutation(rate))||(m_pMaterChromosome->tryMutation(rate)))
return (true);
else
return (false);
}
bool CPairOfChromosome::setAsSexualMale(void)
{
if (m_pMaterChromosome!=NULL)
m_pMaterChromosome->setChromosomeType(CHROMOSOME_SEX_FEMALE);
if (m_pPaterChromosome!=NULL)
m_pPaterChromosome->setChromosomeType(CHROMOSOME_SEX_MALE);
return (true);
}
bool CPairOfChromosome::setAsSexualFemale(void)
{
if (m_pMaterChromosome!=NULL)
m_pMaterChromosome->setChromosomeType(CHROMOSOME_SEX_FEMALE);
if (m_pPaterChromosome!=NULL)
m_pPaterChromosome->setChromosomeType(CHROMOSOME_SEX_FEMALE);
return (true);
}
bool CPairOfChromosome::setAsNeutral(void)
{
if (m_pMaterChromosome!=NULL)
m_pMaterChromosome->setChromosomeType(CHROMOSOME_NEUTRAL);
if (m_pPaterChromosome!=NULL)
m_pPaterChromosome->setChromosomeType(CHROMOSOME_NEUTRAL);
return (true);
}
ChromosomeType_e CPairOfChromosome::getSex(void)
{
return (m_pPaterChromosome->getChromosomeType());
}
size_t CPairOfChromosome::getIdNumber(void)
{
return m_IdNumber;
}
bool CPairOfChromosome::getCrossedChromosomeStr(CPairOfChromosome& pPair, string& crossedStr)
{
string motherStr;
string fatherStr;
motherStr = pPair.m_pMaterChromosome->buildStringDataFromGenes();
fatherStr = pPair.m_pPaterChromosome->buildStringDataFromGenes();
size_t cutIndex = getRandInt(motherStr.length());
crossedStr = motherStr.substr(0,cutIndex) + fatherStr.substr(cutIndex);
return (true);
} | [
"cybiosphere@yahoo.fr"
] | cybiosphere@yahoo.fr |
c6e07d3b21bcf4c8534dd8ba4636051247dd6417 | 3142d3650f95c9c34d3f1aa11cf129061a95a53f | /include/cruisecontrol.h | a4025cc266d5c3c5b4e69e6688333a63b0a4ee91 | [
"MIT"
] | permissive | GaryWu0512/Car_driving_simulator | e00359e88aa9e38bdb21ca08fd150800902a82c0 | 88c1216b345c462f786a641d37823a0e96c98045 | refs/heads/master | 2020-04-27T23:05:02.888393 | 2019-03-22T00:12:23 | 2019-03-22T00:12:23 | 174,761,203 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,083 | h | #include <iostream>
#include <chrono>
#include "elma/elma.h"
//! \file
using namespace std::chrono;
using std::vector;
using namespace elma;
namespace driving_example {
class CruiseControl : public Process {
public:
//! Wrap the base process class
//! \param name The name of the controller
CruiseControl(std::string name) : Process(name) {}
//! Watch for events that change the desired speed, car state, heading angle
void init();
//! Nothing to do to start
void start() {}
//! Get the velocity from the Velocity Channel, compute
//! a simple proportional control law, and send the result
//! to the Throttle channel and Angle channel.
void update();
//! Nothing to do to stop
void stop() {}
private:
double speed = 0;
double desired_speed = 0.0;
double desired_angle = 0.0;
double angle = 0;
int car_state;
const double KP = 314.15;
vector<double> _v;
};
} | [
"youwu12@uw.edu"
] | youwu12@uw.edu |
e9fc3bf87c602da7464bf0c768a391511f56f20f | 61deb5ec26ca4f1675f643619f1e34be515981ad | /src/base/url.h | 5366bcc29e14e844e61de0b1e6319b9665ebd23e | [
"Apache-2.0"
] | permissive | youwi/xpaf | f4ae86995fb7dbcd62332b7c42e04b3b765d8517 | fc40b837e043608faae36e4e00cf7d8ed378c2a2 | refs/heads/master | 2020-03-16T22:05:00.290592 | 2018-05-13T16:33:59 | 2018-05-13T16:33:59 | 133,026,079 | 1 | 1 | null | 2018-05-11T10:30:39 | 2018-05-11T10:30:38 | null | UTF-8 | C++ | false | false | 2,357 | h | // Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Dummy implementation of URL class for use in open source release.
// API is a tiny subset of Google's URL class API.
//
// NOTE: This implementation does not correctly resolve all relative urls.
// We may want to consider using http://code.google.com/p/google-url/.
#ifndef XPAF_BASE_URL_H_
#define XPAF_BASE_URL_H_
#include <string>
#include "base/macros.h"
#include "base/stl_decl.h"
#include "base/stringpiece.h"
#include "base/strutil.h"
namespace xpaf {
class URL {
public:
// Constructs a URL from the url string "url".
URL(const StringPiece& url)
: url_(url.data(), url.size()) {}
// Constructs a URL from "url", using "base_url" to turn relative components
// into absolute components.
// TODO(sadovsky): This implementation is simplistic and often incorrect; it
// should be replaced.
// See http://tools.ietf.org/html/rfc3986#section-5.2 for proper algorithm.
URL(const URL& base_url, const StringPiece& url) {
const size_t url_slash_idx = url.find('/');
if (url_slash_idx != StringPiece::npos && url_slash_idx != 0) {
url_ = url.as_string();
return;
}
const size_t last_slash_idx = base_url.url_.rfind('/');
if (last_slash_idx == string::npos) {
url_ = url.as_string();
return;
}
const size_t substr_len = last_slash_idx + (url_slash_idx == 0 ? 0 : 1);
url_ = StrCat(base_url.url_.substr(0, substr_len), url);
}
const char* Assemble() { return url_.c_str(); }
string AssembleString() const { return url_; }
bool is_valid() const { return true; }
private:
// For our dummy implementation, internal representation is just a string.
string url_;
DISALLOW_COPY_AND_ASSIGN(URL);
};
} // namespace xpaf
#endif // XPAF_BASE_URL_H_
| [
"asadovsky@gmail.com"
] | asadovsky@gmail.com |
95ca2d6e6bf7051d1445b1a87f76cdad5c8072e6 | e3a6740be52f2badcf00d827f9662ec651d78401 | /find_pink_corners_test.cc | 1a9c91e34ff7b1139c3ea264b580475159914ee6 | [] | no_license | atn34/labyrinth-bot | 83df173594092559d623ca23aedb89a669a0569d | a98ebb3da5b7f812bf3c958f2d0dccfa9e686ac0 | refs/heads/master | 2021-01-02T09:44:38.105422 | 2017-09-27T04:53:07 | 2017-09-27T04:53:07 | 99,284,656 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,009 | cc | #include "gtest/gtest.h"
#include "opencv2/highgui/highgui.hpp"
#include "find_pink_corners.h"
#include "connected_components.h"
using namespace cv;
TEST(FourCorners, Test) {
for (const auto &filename : {
"./testdata/2017-08-11-000135.jpg",
"./testdata/2017-08-11-124339.jpg",
"./testdata/2017-08-11-124344.jpg",
"./testdata/2017-08-11-124351.jpg",
"./testdata/2017-08-11-124402.jpg",
"./testdata/2017-08-11-124411.jpg",
"./testdata/2017-08-11-124421.jpg",
"./testdata/2017-08-11-124430.jpg",
}) {
Mat src = imread("./testdata/2017-08-11-124411.jpg", CV_LOAD_IMAGE_COLOR);
HueThresholder thresholder;
Mat threshed = thresholder.thresh(src);
ConnectedComponentsVisitor visitor(&threshed);
int num_connected_components = 0;
visitor.Visit(
[&](Vec2 /* p */, int label) { num_connected_components = label + 1; });
EXPECT_EQ(4, num_connected_components) << filename;
}
}
| [
"anoyes34@gmail.com"
] | anoyes34@gmail.com |
411e1172e101cf49084b41a96fc7d01d590a1d30 | 63bc247adf9bce867fb35583854d7ab0bb8a8714 | /Commands/motionmove_command.cpp | 39b833e2f68fb7c455a582f894077287eda59838 | [] | no_license | yanganok/SITSNEW | 2848f645e70e88aec344bf4eb6303b5a777f89e1 | 67aa4039d1afa6ac305948ec763e6a62638ca86c | refs/heads/master | 2022-12-13T21:02:58.031548 | 2020-08-31T00:43:38 | 2020-08-31T00:43:38 | 290,928,033 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 442 | cpp | #include "motionmove_command.h"
MotionMove_Command::MotionMove_Command()
{
}
MotionMove_Command::MotionMove_Command(InstrumentOperator *operate, Response *response, int msec, Motion_Axis axis, int distance)
:Command(operate, response, msec), _axis(axis), _distance(distance)
{
}
bool MotionMove_Command::package(QByteArray &arr)
{
return true;
}
bool MotionMove_Command::packageToResponse(QByteArray &arr)
{
return true;
}
| [
"yanganok@126.com"
] | yanganok@126.com |
62be633730eb02457de2b5afa95bca73941ce91c | 8fe2e38fd3f23f58dd0f35d1f351601f8a723e07 | /3party/boost/boost/math/special_functions/detail/polygamma.hpp | d5ee7452fb8d6d8762ad8f99ad40052439f4e8ef | [
"BSL-1.0",
"Apache-2.0"
] | permissive | ruilin/RLMap | cb139b7fb3020b163a6857cfa6b98f0c930f2a45 | e16b52f77d165e719b3af20b097f227959e8e374 | refs/heads/master | 2022-10-06T10:11:39.760428 | 2019-11-22T01:03:27 | 2019-11-22T01:03:27 | 97,201,756 | 2 | 1 | Apache-2.0 | 2022-10-04T23:29:25 | 2017-07-14T06:39:33 | C++ | UTF-8 | C++ | false | false | 22,072 | hpp |
///////////////////////////////////////////////////////////////////////////////
// Copyright 2013 Nikhar Agrawal
// Copyright 2013 Christopher Kormanyos
// Copyright 2014 John Maddock
// Copyright 2013 Paul Bristow
// 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_POLYGAMMA_DETAIL_2013_07_30_HPP_
#define _BOOST_POLYGAMMA_DETAIL_2013_07_30_HPP_
#include <cmath>
#include <limits>
#include <boost/cstdint.hpp>
#include <boost/math/policies/policy.hpp>
#include <boost/math/special_functions/bernoulli.hpp>
#include <boost/math/special_functions/trunc.hpp>
#include <boost/math/special_functions/zeta.hpp>
#include <boost/math/special_functions/digamma.hpp>
#include <boost/math/special_functions/sin_pi.hpp>
#include <boost/math/special_functions/cos_pi.hpp>
#include <boost/math/special_functions/pow.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/int.hpp>
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_convertible.hpp>
namespace boost { namespace math { namespace detail{
template<class T, class Policy>
T polygamma_atinfinityplus(const int n, const T& x, const Policy& pol, const char* function) // for large values of x such as for x> 400
{
// See http://functions.wolfram.com/GammaBetaErf/PolyGamma2/06/02/0001/
BOOST_MATH_STD_USING
//
// sum == current value of accumulated sum.
// term == value of current term to be added to sum.
// part_term == value of current term excluding the Bernoulli number part
//
if(n + x == x)
{
// x is crazy large, just concentrate on the first part of the expression and use logs:
if(n == 1) return 1 / x;
T nlx = n * log(x);
if((nlx < tools::log_max_value<T>()) && (n < max_factorial<T>::value))
return ((n & 1) ? 1 : -1) * boost::math::factorial<T>(n - 1) * pow(x, -n);
else
return ((n & 1) ? 1 : -1) * exp(boost::math::lgamma(T(n), pol) - n * log(x));
}
T term, sum, part_term;
T x_squared = x * x;
//
// Start by setting part_term to:
//
// (n-1)! / x^(n+1)
//
// which is common to both the first term of the series (with k = 1)
// and to the leading part.
// We can then get to the leading term by:
//
// part_term * (n + 2 * x) / 2
//
// and to the first term in the series
// (excluding the Bernoulli number) by:
//
// part_term n * (n + 1) / (2x)
//
// If either the factorial would overflow,
// or the power term underflows, this just gets set to 0 and then we
// know that we have to use logs for the initial terms:
//
part_term = ((n > boost::math::max_factorial<T>::value) && (T(n) * n > tools::log_max_value<T>()))
? T(0) : static_cast<T>(boost::math::factorial<T>(n - 1, pol) * pow(x, -n - 1));
if(part_term == 0)
{
// Either n is very large, or the power term underflows,
// set the initial values of part_term, term and sum via logs:
part_term = boost::math::lgamma(n, pol) - (n + 1) * log(x);
sum = exp(part_term + log(n + 2 * x) - boost::math::constants::ln_two<T>());
part_term += log(T(n) * (n + 1)) - boost::math::constants::ln_two<T>() - log(x);
part_term = exp(part_term);
}
else
{
sum = part_term * (n + 2 * x) / 2;
part_term *= (T(n) * (n + 1)) / 2;
part_term /= x;
}
//
// If the leading term is 0, so is the result:
//
if(sum == 0)
return sum;
for(unsigned k = 1;;)
{
term = part_term * boost::math::bernoulli_b2n<T>(k, pol);
sum += term;
//
// Normal termination condition:
//
if(fabs(term / sum) < tools::epsilon<T>())
break;
//
// Increment our counter, and move part_term on to the next value:
//
++k;
part_term *= T(n + 2 * k - 2) * (n - 1 + 2 * k);
part_term /= (2 * k - 1) * 2 * k;
part_term /= x_squared;
//
// Emergency get out termination condition:
//
if(k > policies::get_max_series_iterations<Policy>())
{
return policies::raise_evaluation_error(function, "Series did not converge, closest value was %1%", sum, pol);
}
}
if((n - 1) & 1)
sum = -sum;
return sum;
}
template<class T, class Policy>
T polygamma_attransitionplus(const int n, const T& x, const Policy& pol, const char* function)
{
// See: http://functions.wolfram.com/GammaBetaErf/PolyGamma2/16/01/01/0017/
// Use N = (0.4 * digits) + (4 * n) for target value for x:
BOOST_MATH_STD_USING
const int d4d = static_cast<int>(0.4F * policies::digits_base10<T, Policy>());
const int N = d4d + (4 * n);
const int m = n;
const int iter = N - itrunc(x);
if(iter > (int)policies::get_max_series_iterations<Policy>())
return policies::raise_evaluation_error<T>(function, ("Exceeded maximum series evaluations evaluating at n = " + boost::lexical_cast<std::string>(n) + " and x = %1%").c_str(), x, pol);
const int minus_m_minus_one = -m - 1;
T z(x);
T sum0(0);
T z_plus_k_pow_minus_m_minus_one(0);
// Forward recursion to larger x, need to check for overflow first though:
if(log(z + iter) * minus_m_minus_one > -tools::log_max_value<T>())
{
for(int k = 1; k <= iter; ++k)
{
z_plus_k_pow_minus_m_minus_one = pow(z, minus_m_minus_one);
sum0 += z_plus_k_pow_minus_m_minus_one;
z += 1;
}
sum0 *= boost::math::factorial<T>(n);
}
else
{
for(int k = 1; k <= iter; ++k)
{
T log_term = log(z) * minus_m_minus_one + boost::math::lgamma(T(n + 1), pol);
sum0 += exp(log_term);
z += 1;
}
}
if((n - 1) & 1)
sum0 = -sum0;
return sum0 + polygamma_atinfinityplus(n, z, pol, function);
}
template <class T, class Policy>
T polygamma_nearzero(int n, T x, const Policy& pol, const char* function)
{
BOOST_MATH_STD_USING
//
// If we take this expansion for polygamma: http://functions.wolfram.com/06.15.06.0003.02
// and substitute in this expression for polygamma(n, 1): http://functions.wolfram.com/06.15.03.0009.01
// we get an alternating series for polygamma when x is small in terms of zeta functions of
// integer arguments (which are easy to evaluate, at least when the integer is even).
//
// In order to avoid spurious overflow, save the n! term for later, and rescale at the end:
//
T scale = boost::math::factorial<T>(n, pol);
//
// "factorial_part" contains everything except the zeta function
// evaluations in each term:
//
T factorial_part = 1;
//
// "prefix" is what we'll be adding the accumulated sum to, it will
// be n! / z^(n+1), but since we're scaling by n! it's just
// 1 / z^(n+1) for now:
//
T prefix = pow(x, n + 1);
if(prefix == 0)
return boost::math::policies::raise_overflow_error<T>(function, 0, pol);
prefix = 1 / prefix;
//
// First term in the series is necessarily < zeta(2) < 2, so
// ignore the sum if it will have no effect on the result anyway:
//
if(prefix > 2 / policies::get_epsilon<T, Policy>())
return ((n & 1) ? 1 : -1) *
(tools::max_value<T>() / prefix < scale ? policies::raise_overflow_error<T>(function, 0, pol) : prefix * scale);
//
// As this is an alternating series we could accelerate it using
// "Convergence Acceleration of Alternating Series",
// Henri Cohen, Fernando Rodriguez Villegas, and Don Zagier, Experimental Mathematics, 1999.
// In practice however, it appears not to make any difference to the number of terms
// required except in some edge cases which are filtered out anyway before we get here.
//
T sum = prefix;
for(unsigned k = 0;;)
{
// Get the k'th term:
T term = factorial_part * boost::math::zeta(T(k + n + 1), pol);
sum += term;
// Termination condition:
if(fabs(term) < fabs(sum * boost::math::policies::get_epsilon<T, Policy>()))
break;
//
// Move on k and factorial_part:
//
++k;
factorial_part *= (-x * (n + k)) / k;
//
// Last chance exit:
//
if(k > policies::get_max_series_iterations<Policy>())
return policies::raise_evaluation_error<T>(function, "Series did not converge, best value is %1%", sum, pol);
}
//
// We need to multiply by the scale, at each stage checking for oveflow:
//
if(boost::math::tools::max_value<T>() / scale < sum)
return boost::math::policies::raise_overflow_error<T>(function, 0, pol);
sum *= scale;
return n & 1 ? sum : -sum;
}
//
// Helper function which figures out which slot our coefficient is in
// given an angle multiplier for the cosine term of power:
//
template <class Table>
typename Table::value_type::reference dereference_table(Table& table, unsigned row, unsigned power)
{
return table[row][power / 2];
}
template <class T, class Policy>
T poly_cot_pi(int n, T x, T xc, const Policy& pol, const char* function)
{
BOOST_MATH_STD_USING
// Return n'th derivative of cot(pi*x) at x, these are simply
// tabulated for up to n = 9, beyond that it is possible to
// calculate coefficients as follows:
//
// The general form of each derivative is:
//
// pi^n * SUM{k=0, n} C[k,n] * cos^k(pi * x) * csc^(n+1)(pi * x)
//
// With constant C[0,1] = -1 and all other C[k,n] = 0;
// Then for each k < n+1:
// C[k-1, n+1] -= k * C[k, n];
// C[k+1, n+1] += (k-n-1) * C[k, n];
//
// Note that there are many different ways of representing this derivative thanks to
// the many trigomonetric identies available. In particular, the sum of powers of
// cosines could be replaced by a sum of cosine multiple angles, and indeed if you
// plug the derivative into Mathematica this is the form it will give. The two
// forms are related via the Chebeshev polynomials of the first kind and
// T_n(cos(x)) = cos(n x). The polynomial form has the great advantage that
// all the cosine terms are zero at half integer arguments - right where this
// function has it's minumum - thus avoiding cancellation error in this region.
//
// And finally, since every other term in the polynomials is zero, we can save
// space by only storing the non-zero terms. This greatly complexifies
// subscripting the tables in the calculation, but halves the storage space
// (and complexity for that matter).
//
T s = fabs(x) < fabs(xc) ? boost::math::sin_pi(x, pol) : boost::math::sin_pi(xc, pol);
T c = boost::math::cos_pi(x, pol);
switch(n)
{
case 1:
return -constants::pi<T, Policy>() / (s * s);
case 2:
{
return 2 * constants::pi<T, Policy>() * constants::pi<T, Policy>() * c / boost::math::pow<3>(s, pol);
}
case 3:
{
int P[] = { -2, -4 };
return boost::math::pow<3>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<4>(s, pol);
}
case 4:
{
int P[] = { 16, 8 };
return boost::math::pow<4>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<5>(s, pol);
}
case 5:
{
int P[] = { -16, -88, -16 };
return boost::math::pow<5>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<6>(s, pol);
}
case 6:
{
int P[] = { 272, 416, 32 };
return boost::math::pow<6>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<7>(s, pol);
}
case 7:
{
int P[] = { -272, -2880, -1824, -64 };
return boost::math::pow<7>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<8>(s, pol);
}
case 8:
{
int P[] = { 7936, 24576, 7680, 128 };
return boost::math::pow<8>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<9>(s, pol);
}
case 9:
{
int P[] = { -7936, -137216, -185856, -31616, -256 };
return boost::math::pow<9>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<10>(s, pol);
}
case 10:
{
int P[] = { 353792, 1841152, 1304832, 128512, 512 };
return boost::math::pow<10>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<11>(s, pol);
}
case 11:
{
int P[] = { -353792, -9061376, -21253376, -8728576, -518656, -1024};
return boost::math::pow<11>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<12>(s, pol);
}
case 12:
{
int P[] = { 22368256, 175627264, 222398464, 56520704, 2084864, 2048 };
return boost::math::pow<12>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<13>(s, pol);
}
#ifndef BOOST_NO_LONG_LONG
case 13:
{
long long P[] = { -22368256LL, -795300864LL, -2868264960LL, -2174832640LL, -357888000LL, -8361984LL, -4096 };
return boost::math::pow<13>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<14>(s, pol);
}
case 14:
{
long long P[] = { 1903757312LL, 21016670208LL, 41731645440LL, 20261765120LL, 2230947840LL, 33497088LL, 8192 };
return boost::math::pow<14>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<15>(s, pol);
}
case 15:
{
long long P[] = { -1903757312LL, -89702612992LL, -460858269696LL, -559148810240LL, -182172651520LL, -13754155008LL, -134094848LL, -16384 };
return boost::math::pow<15>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<16>(s, pol);
}
case 16:
{
long long P[] = { 209865342976LL, 3099269660672LL, 8885192097792LL, 7048869314560LL, 1594922762240LL, 84134068224LL, 536608768LL, 32768 };
return boost::math::pow<16>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<17>(s, pol);
}
case 17:
{
long long P[] = { -209865342976LL, -12655654469632LL, -87815735738368LL, -155964390375424LL, -84842998005760LL, -13684856848384LL, -511780323328LL, -2146926592LL, -65536 };
return boost::math::pow<17>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<18>(s, pol);
}
case 18:
{
long long P[] = { 29088885112832LL, 553753414467584LL, 2165206642589696LL, 2550316668551168LL, 985278548541440LL, 115620218667008LL, 3100738912256LL, 8588754944LL, 131072 };
return boost::math::pow<18>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<19>(s, pol);
}
case 19:
{
long long P[] = { -29088885112832LL, -2184860175433728LL, -19686087844429824LL, -48165109676113920LL, -39471306959486976LL, -11124607890751488LL, -965271355195392LL, -18733264797696LL, -34357248000LL, -262144 };
return boost::math::pow<19>(constants::pi<T, Policy>(), pol) * tools::evaluate_even_polynomial(P, c) / boost::math::pow<20>(s, pol);
}
case 20:
{
long long P[] = { 4951498053124096LL, 118071834535526400LL, 603968063567560704LL, 990081991141490688LL, 584901762421358592LL, 122829335169859584LL, 7984436548730880LL, 112949304754176LL, 137433710592LL, 524288 };
return boost::math::pow<20>(constants::pi<T, Policy>(), pol) * c * tools::evaluate_even_polynomial(P, c) / boost::math::pow<21>(s, pol);
}
#endif
}
//
// We'll have to compute the coefficients up to n,
// complexity is O(n^2) which we don't worry about for now
// as the values are computed once and then cached.
// However, if the final evaluation would have too many
// terms just bail out right away:
//
if((unsigned)n / 2u > policies::get_max_series_iterations<Policy>())
return policies::raise_evaluation_error<T>(function, "The value of n is so large that we're unable to compute the result in reasonable time, best guess is %1%", 0, pol);
#ifdef BOOST_HAS_THREADS
static boost::detail::lightweight_mutex m;
boost::detail::lightweight_mutex::scoped_lock l(m);
#endif
static std::vector<std::vector<T> > table(1, std::vector<T>(1, T(-1)));
int index = n - 1;
if(index >= (int)table.size())
{
for(int i = (int)table.size() - 1; i < index; ++i)
{
int offset = i & 1; // 1 if the first cos power is 0, otherwise 0.
int sin_order = i + 2; // order of the sin term
int max_cos_order = sin_order - 1; // largest order of the polynomial of cos terms
int max_columns = (max_cos_order - offset) / 2; // How many entries there are in the current row.
int next_offset = offset ? 0 : 1;
int next_max_columns = (max_cos_order + 1 - next_offset) / 2; // How many entries there will be in the next row
table.push_back(std::vector<T>(next_max_columns + 1, T(0)));
for(int column = 0; column <= max_columns; ++column)
{
int cos_order = 2 * column + offset; // order of the cosine term in entry "column"
BOOST_ASSERT(column < (int)table[i].size());
BOOST_ASSERT((cos_order + 1) / 2 < (int)table[i + 1].size());
table[i + 1][(cos_order + 1) / 2] += ((cos_order - sin_order) * table[i][column]) / (sin_order - 1);
if(cos_order)
table[i + 1][(cos_order - 1) / 2] += (-cos_order * table[i][column]) / (sin_order - 1);
}
}
}
T sum = boost::math::tools::evaluate_even_polynomial(&table[index][0], c, table[index].size());
if(index & 1)
sum *= c; // First coeffient is order 1, and really an odd polynomial.
if(sum == 0)
return sum;
//
// The remaining terms are computed using logs since the powers and factorials
// get real large real quick:
//
T power_terms = n * log(boost::math::constants::pi<T>());
if(s == 0)
return sum * boost::math::policies::raise_overflow_error<T>(function, 0, pol);
power_terms -= log(fabs(s)) * (n + 1);
power_terms += boost::math::lgamma(T(n));
power_terms += log(fabs(sum));
if(power_terms > boost::math::tools::log_max_value<T>())
return sum * boost::math::policies::raise_overflow_error<T>(function, 0, pol);
return exp(power_terms) * ((s < 0) && ((n + 1) & 1) ? -1 : 1) * boost::math::sign(sum);
}
template <class T, class Policy>
struct polygamma_initializer
{
struct init
{
init()
{
// Forces initialization of our table of coefficients and mutex:
boost::math::polygamma(30, T(-2.5f), Policy());
}
void force_instantiate()const{}
};
static const init initializer;
static void force_instantiate()
{
initializer.force_instantiate();
}
};
template <class T, class Policy>
const typename polygamma_initializer<T, Policy>::init polygamma_initializer<T, Policy>::initializer;
template<class T, class Policy>
inline T polygamma_imp(const int n, T x, const Policy &pol)
{
BOOST_MATH_STD_USING
static const char* function = "boost::math::polygamma<%1%>(int, %1%)";
polygamma_initializer<T, Policy>::initializer.force_instantiate();
if(n < 0)
return policies::raise_domain_error<T>(function, "Order must be >= 0, but got %1%", static_cast<T>(n), pol);
if(x < 0)
{
if(floor(x) == x)
{
//
// Result is infinity if x is odd, and a pole error if x is even.
//
if(lltrunc(x) & 1)
return policies::raise_overflow_error<T>(function, 0, pol);
else
return policies::raise_pole_error<T>(function, "Evaluation at negative integer %1%", x, pol);
}
T z = 1 - x;
T result = polygamma_imp(n, z, pol) + constants::pi<T, Policy>() * poly_cot_pi(n, z, x, pol, function);
return n & 1 ? T(-result) : result;
}
//
// Limit for use of small-x-series is chosen
// so that the series doesn't go too divergent
// in the first few terms. Ordinarily this
// would mean setting the limit to ~ 1 / n,
// but we can tolerate a small amount of divergence:
//
T small_x_limit = std::min(T(T(5) / n), T(0.25f));
if(x < small_x_limit)
{
return polygamma_nearzero(n, x, pol, function);
}
else if(x > 0.4F * policies::digits_base10<T, Policy>() + 4.0f * n)
{
return polygamma_atinfinityplus(n, x, pol, function);
}
else if(x == 1)
{
return (n & 1 ? 1 : -1) * boost::math::factorial<T>(n, pol) * boost::math::zeta(T(n + 1), pol);
}
else if(x == 0.5f)
{
T result = (n & 1 ? 1 : -1) * boost::math::factorial<T>(n, pol) * boost::math::zeta(T(n + 1), pol);
if(fabs(result) >= ldexp(tools::max_value<T>(), -n - 1))
return boost::math::sign(result) * policies::raise_overflow_error<T>(function, 0, pol);
result *= ldexp(T(1), n + 1) - 1;
return result;
}
else
{
return polygamma_attransitionplus(n, x, pol, function);
}
}
} } } // namespace boost::math::detail
#endif // _BOOST_POLYGAMMA_DETAIL_2013_07_30_HPP_
| [
"zruilin@126.com"
] | zruilin@126.com |
1190a75257ef207e138675657b6a3fae70628293 | 0149ed842327e3133fc2fe7b49d6ee2e27c22021 | /opencl/source/sharings/gl/linux/gl_sharing_linux.h | 952898fcc87887ea5bea14b2bbb4acb577da7ca6 | [
"MIT"
] | permissive | intel/compute-runtime | 17f1c3dd3e1120895c6217b1e6c311d88a09902e | 869e3ec9f83a79ca4ac43a18d21847183c63e037 | refs/heads/master | 2023-09-03T07:28:16.591743 | 2023-09-02T02:04:35 | 2023-09-02T02:24:33 | 105,299,354 | 1,027 | 262 | MIT | 2023-08-25T11:06:41 | 2017-09-29T17:26:43 | C++ | UTF-8 | C++ | false | false | 10,112 | h | /*
* Copyright (C) 2023 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include "opencl/extensions/public/cl_gl_private_intel.h"
#include "opencl/source/sharings/gl/gl_sharing.h"
#include "opencl/source/sharings/gl/linux/include/gl_types.h"
#include <GL/gl.h>
#include <EGL/eglext.h>
namespace NEO {
// OpenGL API names
typedef GLboolean (*PFNOGLSetSharedOCLContextStateINTEL)(GLDisplay hdcHandle, GLContext contextHandle, GLboolean state, GLvoid *pContextInfo);
typedef GLboolean (*PFNOGLAcquireSharedBufferINTEL)(GLDisplay hdcHandle, GLContext contextHandle, GLContext backupContextHandle, GLvoid *pBufferInfo);
typedef GLboolean (*PFNOGLAcquireSharedRenderBufferINTEL)(GLDisplay hdcHandle, GLContext contextHandle, GLContext backupContextHandle, GLvoid *pResourceInfo);
typedef GLboolean (*PFNOGLReleaseSharedBufferINTEL)(GLDisplay hdcHandle, GLContext contextHandle, GLContext backupContextHandle, GLvoid *pBufferInfo);
typedef GLboolean (*PFNOGLReleaseSharedRenderBufferINTEL)(GLDisplay hdcHandle, GLContext contextHandle, GLContext backupContextHandle, GLvoid *pResourceInfo);
typedef GLboolean (*PFNOGLReleaseSharedTextureINTEL)(GLDisplay hdcHandle, GLContext contextHandle, GLContext backupContextHandle, GLvoid *pResourceInfo);
typedef GLContext (*PFNOGLGetCurrentContext)();
typedef GLDisplay (*PFNOGLGetCurrentDisplay)();
typedef GLboolean (*PFNOGLMakeCurrent)(GLDisplay hdcHandle, void *draw, void *read, GLContext contextHandle);
typedef GLboolean (*PFNOGLRetainSyncINTEL)(GLDisplay hdcHandle, GLContext contextHandle, GLContext backupContextHandle, GLvoid *pSyncInfo);
typedef GLboolean (*PFNOGLReleaseSyncINTEL)(GLDisplay hdcHandle, GLContext contextHandle, GLContext backupContextHandle, GLvoid *pSync);
typedef void (*PFNOGLGetSyncivINTEL)(GLvoid *pSync, GLenum pname, GLint *value);
typedef const GLubyte *(*PFNglGetString)(GLenum name);
typedef const GLubyte *(*PFNglGetStringi)(GLenum name, GLuint index);
typedef void (*PFNglGetIntegerv)(GLenum pname, GLint *params);
typedef void (*PFNglBindTexture)(GLenum target, GLuint texture);
typedef void (*PFNglGetTexLevelParameteriv)(GLenum target, GLint level, GLenum pname, GLint *params);
// egl
typedef unsigned char (*PFNeglMakeCurrent)(void *, void *);
typedef GLContext (*PFNeglCreateContext)(GLDisplay hdcHandle);
typedef int (*PFNeglShareLists)(GLContext contextHandle, GLContext backupContextHandle);
typedef EGLBoolean (*PFNeglDeleteContext)(EGLDisplay dpy, EGLContext ctx);
typedef bool (*PFNglArbSyncObjectSetup)(GLSharingFunctions &sharing, OSInterface &osInterface, CL_GL_SYNC_INFO &glSyncInfo);
typedef void (*PFNglArbSyncObjectCleanup)(OSInterface &osInterface, CL_GL_SYNC_INFO *glSyncInfo);
typedef void (*PFNglArbSyncObjectSignal)(OsContext &osContext, CL_GL_SYNC_INFO &glSyncInfo);
typedef void (*PFNglArbSyncObjectWaitServer)(OSInterface &osInterface, CL_GL_SYNC_INFO &glSyncInfo);
typedef EGLImage (*PFNeglCreateImage)(EGLDisplay dpy, EGLContext ctx, EGLenum target, EGLClientBuffer buffer, const EGLAttrib *attribList);
typedef EGLBoolean (*PFNeglDestroyImage)(EGLDisplay dpy, EGLImage image);
class GLSharingFunctionsLinux : public GLSharingFunctions {
public:
GLSharingFunctionsLinux() = default;
GLSharingFunctionsLinux(GLType glhdcType, GLContext glhglrcHandle, GLContext glhglrcHandleBkpCtx, GLDisplay glhdcHandle);
~GLSharingFunctionsLinux() override;
OS_HANDLE getGLDeviceHandle() const { return glDeviceHandle; }
OS_HANDLE getGLContextHandle() const { return glContextHandle; }
GLboolean initGLFunctions() override;
bool isOpenGlSharingSupported() override;
static bool isGlSharingEnabled();
// Arb sync event
template <typename EventType = GlArbSyncEvent>
auto getOrCreateGlArbSyncEvent(Event &baseEvent) -> decltype(EventType::create(baseEvent));
GlArbSyncEvent *getGlArbSyncEvent(Event &baseEvent);
void removeGlArbSyncEventMapping(Event &baseEvent);
// Gl functions
GLboolean acquireSharedBufferINTEL(GLvoid *pBufferInfo) {
return glAcquireSharedBuffer(glHDCHandle, glHGLRCHandle, glHGLRCHandleBkpCtx, pBufferInfo);
}
GLboolean releaseSharedBufferINTEL(GLvoid *pBufferInfo) {
return glReleaseSharedBuffer(glHDCHandle, glHGLRCHandle, glHGLRCHandleBkpCtx, pBufferInfo);
}
GLboolean acquireSharedRenderBuffer(GLvoid *pResourceInfo) {
return glAcquireSharedRenderBuffer(glHDCHandle, glHGLRCHandle, glHGLRCHandleBkpCtx, pResourceInfo);
}
GLboolean releaseSharedRenderBuffer(GLvoid *pResourceInfo) {
return glReleaseSharedRenderBuffer(glHDCHandle, glHGLRCHandle, glHGLRCHandleBkpCtx, pResourceInfo);
}
EGLBoolean acquireSharedTexture(CL_GL_RESOURCE_INFO *pResourceInfo) {
int fds;
int stride, offset;
int miplevel = 0;
EGLAttrib attribList[] = {EGL_GL_TEXTURE_LEVEL, miplevel, EGL_NONE};
EGLImage image = eglCreateImage(glHDCHandle, glHGLRCHandle, EGL_GL_TEXTURE_2D, reinterpret_cast<EGLClientBuffer>(static_cast<uintptr_t>(pResourceInfo->name)), &attribList[0]);
if (image == EGL_NO_IMAGE) {
return EGL_FALSE;
}
EGLBoolean ret = glAcquireSharedTexture(glHDCHandle, image, &fds, &stride, &offset);
if (ret == EGL_TRUE && fds > 0) {
pResourceInfo->globalShareHandle = fds;
} else {
eglDestroyImage(glHDCHandle, image);
ret = EGL_FALSE;
}
return ret;
}
GLboolean releaseSharedTexture(GLvoid *pResourceInfo) {
return 1;
}
GLboolean retainSync(GLvoid *pSyncInfo) {
return glRetainSync(glHDCHandle, glHGLRCHandle, glHGLRCHandleBkpCtx, pSyncInfo);
}
GLboolean releaseSync(GLvoid *pSync) {
return glReleaseSync(glHDCHandle, glHGLRCHandle, glHGLRCHandleBkpCtx, pSync);
}
void getSynciv(GLvoid *pSync, GLenum pname, GLint *value) {
return glGetSynciv(pSync, pname, value);
}
GLContext getCurrentContext() {
return glGetCurrentContext();
}
GLDisplay getCurrentDisplay() {
return glGetCurrentDisplay();
}
GLboolean makeCurrent(GLContext contextHandle, GLDisplay displayHandle = 0) {
if (displayHandle == 0) {
displayHandle = glHDCHandle;
}
return this->eglMakeCurrent(displayHandle, contextHandle);
}
GLContext getBackupContextHandle() {
return glHGLRCHandleBkpCtx;
}
GLContext getContextHandle() {
return glHGLRCHandle;
}
bool glArbSyncObjectSetup(OSInterface &osInterface, CL_GL_SYNC_INFO &glSyncInfo) {
return pfnGlArbSyncObjectSetup(*this, osInterface, glSyncInfo);
}
void glArbSyncObjectCleanup(OSInterface &osInterface, CL_GL_SYNC_INFO *glSyncInfo) {
pfnGlArbSyncObjectCleanup(osInterface, glSyncInfo);
}
void glArbSyncObjectSignal(OsContext &osContext, CL_GL_SYNC_INFO &glSyncInfo) {
pfnGlArbSyncObjectSignal(osContext, glSyncInfo);
}
void glArbSyncObjectWaitServer(OSInterface &osInterface, CL_GL_SYNC_INFO &glSyncInfo) {
pfnGlArbSyncObjectWaitServer(osInterface, glSyncInfo);
}
// Buffer reuse
std::mutex mutex;
std::vector<std::pair<unsigned int, GraphicsAllocation *>> graphicsAllocationsForGlBufferReuse;
PFNglGetTexLevelParameteriv glGetTexLevelParameteriv = nullptr;
protected:
void updateOpenGLContext() {
if (glSetSharedOCLContextState) {
setSharedOCLContextState();
}
}
GLboolean setSharedOCLContextState();
void createBackupContext();
bool isOpenGlExtensionSupported(const unsigned char *pExtentionString);
// Handles
GLType glHDCType = 0;
GLContext glHGLRCHandle = 0;
GLContext glHGLRCHandleBkpCtx = 0;
GLDisplay glHDCHandle = 0;
OS_HANDLE glDeviceHandle = 0;
OS_HANDLE glContextHandle = 0;
// GL functions
std::unique_ptr<OsLibrary> glLibrary;
std::unique_ptr<OsLibrary> eglLibrary;
PFNOGLSetSharedOCLContextStateINTEL glSetSharedOCLContextState = nullptr;
PFNOGLAcquireSharedBufferINTEL glAcquireSharedBuffer = nullptr;
PFNOGLReleaseSharedBufferINTEL glReleaseSharedBuffer = nullptr;
PFNOGLAcquireSharedRenderBufferINTEL glAcquireSharedRenderBuffer = nullptr;
PFNOGLReleaseSharedRenderBufferINTEL glReleaseSharedRenderBuffer = nullptr;
PFNEGLEXPORTDMABUFIMAGEMESAPROC glAcquireSharedTexture = nullptr;
PFNOGLReleaseSharedTextureINTEL glReleaseSharedTexture = nullptr;
PFNOGLGetCurrentContext glGetCurrentContext = nullptr;
PFNOGLGetCurrentDisplay glGetCurrentDisplay = nullptr;
PFNglGetString glGetString = nullptr;
PFNglGetStringi glGetStringi = nullptr;
PFNglGetIntegerv glGetIntegerv = nullptr;
PFNeglCreateContext pfnEglCreateContext = nullptr;
PFNeglMakeCurrent eglMakeCurrent = nullptr;
PFNeglShareLists pfnEglShareLists = nullptr;
PFNeglDeleteContext pfnEglDeleteContext = nullptr;
PFNOGLRetainSyncINTEL glRetainSync = nullptr;
PFNOGLReleaseSyncINTEL glReleaseSync = nullptr;
PFNOGLGetSyncivINTEL glGetSynciv = nullptr;
PFNglArbSyncObjectSetup pfnGlArbSyncObjectSetup = nullptr;
PFNglArbSyncObjectCleanup pfnGlArbSyncObjectCleanup = nullptr;
PFNglArbSyncObjectSignal pfnGlArbSyncObjectSignal = nullptr;
PFNglArbSyncObjectWaitServer pfnGlArbSyncObjectWaitServer = nullptr;
PFNeglCreateImage eglCreateImage = nullptr;
PFNeglDestroyImage eglDestroyImage = nullptr;
// support for GL_ARB_cl_event
std::mutex glArbEventMutex;
std::unordered_map<Event *, GlArbSyncEvent *> glArbEventMapping;
};
template <typename EventType>
inline auto GLSharingFunctionsLinux::getOrCreateGlArbSyncEvent(Event &baseEvent) -> decltype(EventType::create(baseEvent)) {
std::lock_guard<std::mutex> lock{glArbEventMutex};
auto it = glArbEventMapping.find(&baseEvent);
if (it != glArbEventMapping.end()) {
return it->second;
}
auto arbEvent = EventType::create(baseEvent);
if (nullptr == arbEvent) {
return arbEvent;
}
glArbEventMapping[&baseEvent] = arbEvent;
return arbEvent;
}
} // namespace NEO
| [
"compute-runtime@intel.com"
] | compute-runtime@intel.com |
9f5b8acca0417e562f181f89ae91a3873f814392 | 4f63cf74d091209ce336c61553b400f562c4f169 | /firmware/hw_layer/sensors/yaw_rate_sensor.cpp | 4e8af7ba0c34502d5b794b23e7c9d1e9b8740aaf | [] | no_license | abelom/firmware_ME7 | 0f274843d01c2f318f28c746005f15a47dae4c64 | fddae062cad8d4827c43e6e431226b0988f1d669 | refs/heads/master | 2022-04-27T00:22:40.564306 | 2020-04-28T22:22:09 | 2020-04-28T22:22:09 | 259,839,218 | 6 | 1 | null | 2020-04-29T06:06:25 | 2020-04-29T06:06:24 | null | UTF-8 | C++ | false | false | 638 | cpp | /*
* yaw_rate_sensor.cpp
*
* bosch Yaw Rate Sensor YRS 3
*
* https://github.com/rusefi/rusefi/files/2476705/Yaw_Rate_Sensor_YRS_3_Datasheet_51_en_2778925323.pdf
* http://www.bosch-motorsport.de/media/msd/downloads/archiv/sensoren/Yaw_Rate_Sensor_YRS_3_Datasheet_51_en_2778925323.pdf
*
* 0 265 005 693 2007-2013 INFINITI G37
* BLACK or GREY GND
* GREEN +12
* LT BLU BUS-H
* YEL BUS-L
*
*
* @date Oct 16, 2018
* @author Andrey Belomutskiy, (c) 2012-2020
*/
#include "yaw_rate_sensor.h"
#if EFI_BOSCH_YAW
EXTERN_ENGINE;
void initBoschYawRateSensor() {
}
#endif /* EFI_BOSCH_YAW */
| [
"olaruud@hotmail.com"
] | olaruud@hotmail.com |
39b246cf1aad45347d7122e319b0dbeab0cabe03 | cf6dfcb469f4188fd4fc27b58a3e9391bf043818 | /testStaticLibrary/testStaticLibrary/Person.cpp | f74452e792f3acdfe2733db68c3be77e571e3099 | [] | no_license | codeLee321/C-C-Objective-C-Interactive | c43ca9fb27fd113daeb4bb26960db9c47169a002 | e07b816f339a20c5e650081443c74daad558c355 | refs/heads/master | 2020-03-07T03:00:05.580187 | 2018-03-29T02:39:44 | 2018-03-29T02:39:44 | 127,223,201 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | cpp | //
// Person.cpp
// testStaticLibrary
//
// Created by 荣 li on 2018/3/26.
// Copyright © 2018年 rongli. All rights reserved.
//
#include "Person.hpp"
#include <sstream>
list<Hello *> Person::coutPersonList(){
list<Hello *>H;
for (int i = 0; i<3; i++) {
Hello * hel = new Hello();
ostringstream oss;
oss << "hel" << i << endl;
hel->name = oss.str();
H.push_back(hel);
}
cout<<"run hear .....\n";
return H;
}
| [
"15617211769@sina.cn"
] | 15617211769@sina.cn |
7acedb4b626e1599444a6b349f09f396e857efb6 | 4a46f9d06515e61ef89ef0a5bfa1393cf218e68f | /src/qt/transactiondescdialog.cpp | 1e31f9e42ca14de6b87abec9a358d2409bb36b52 | [
"MIT"
] | permissive | GroinGuy/GroinCoin-GXG | fe886d386fef948c818b4b34c59040791da45f3b | d71c1b200683a77ccf797d8a500e468351da5ee0 | refs/heads/master | 2020-05-21T14:04:39.761147 | 2019-02-02T13:52:52 | 2019-02-02T13:52:52 | 19,191,079 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 862 | cpp | // Copyright (c) 2011-2017 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// Copyright (c) 2014-2018 The Groincoin Core developers
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/transactiondescdialog.h>
#include <qt/forms/ui_transactiondescdialog.h>
#include <qt/transactiontablemodel.h>
#include <QModelIndex>
TransactionDescDialog::TransactionDescDialog(const QModelIndex &idx, QWidget *parent) :
QDialog(parent),
ui(new Ui::TransactionDescDialog)
{
ui->setupUi(this);
setWindowTitle(tr("Details for %1").arg(idx.data(TransactionTableModel::TxIDRole).toString()));
QString desc = idx.data(TransactionTableModel::LongDescriptionRole).toString();
ui->detailText->setHtml(desc);
}
TransactionDescDialog::~TransactionDescDialog()
{
delete ui;
}
| [
"mendozg@gmx.com"
] | mendozg@gmx.com |
a23969b73611793503d0b108ae0327f6e1634eae | 0fcdc4c5de9bc0c352a4c5f79432ea6ce7e96114 | /DobotDemoV2.0/QT/Dobot2.0Multi-controlDemoForQt/Dobot2.0Multi/build-DobotDemoForQt-Desktop_Qt_5_7_1_GCC_64bit-Debug/ui_form.h | 9f60f143d09476dd752c72637b346df0b9359818 | [
"Apache-2.0"
] | permissive | nanusefue/dobotMagician | d3614c720f128b767662cc72557699d875fe8b57 | ca265b772a627865edbb038897b73909c1d213ce | refs/heads/master | 2022-02-14T03:15:30.552282 | 2022-02-01T09:52:46 | 2022-02-01T09:52:46 | 109,893,664 | 5 | 3 | null | 2018-11-02T21:15:11 | 2017-11-07T21:35:19 | C | UTF-8 | C++ | false | false | 3,664 | h | /********************************************************************************
** Form generated from reading UI file 'form.ui'
**
** Created by: Qt User Interface Compiler version 5.7.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_FORM_H
#define UI_FORM_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QFrame>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QTabWidget>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_Form
{
public:
QVBoxLayout *verticalLayout;
QTabWidget *tabWidget;
QFrame *frame;
QHBoxLayout *horizontalLayout;
QPushButton *pushButton;
QLabel *label_2;
QLabel *lbSearchResult;
void setupUi(QWidget *Form)
{
if (Form->objectName().isEmpty())
Form->setObjectName(QStringLiteral("Form"));
Form->resize(883, 562);
verticalLayout = new QVBoxLayout(Form);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
tabWidget = new QTabWidget(Form);
tabWidget->setObjectName(QStringLiteral("tabWidget"));
verticalLayout->addWidget(tabWidget);
frame = new QFrame(Form);
frame->setObjectName(QStringLiteral("frame"));
frame->setFrameShape(QFrame::StyledPanel);
frame->setFrameShadow(QFrame::Raised);
horizontalLayout = new QHBoxLayout(frame);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
pushButton = new QPushButton(frame);
pushButton->setObjectName(QStringLiteral("pushButton"));
QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(pushButton->sizePolicy().hasHeightForWidth());
pushButton->setSizePolicy(sizePolicy);
horizontalLayout->addWidget(pushButton);
label_2 = new QLabel(frame);
label_2->setObjectName(QStringLiteral("label_2"));
QSizePolicy sizePolicy1(QSizePolicy::Fixed, QSizePolicy::Preferred);
sizePolicy1.setHorizontalStretch(0);
sizePolicy1.setVerticalStretch(0);
sizePolicy1.setHeightForWidth(label_2->sizePolicy().hasHeightForWidth());
label_2->setSizePolicy(sizePolicy1);
QFont font;
font.setBold(true);
font.setWeight(75);
label_2->setFont(font);
horizontalLayout->addWidget(label_2);
lbSearchResult = new QLabel(frame);
lbSearchResult->setObjectName(QStringLiteral("lbSearchResult"));
horizontalLayout->addWidget(lbSearchResult);
verticalLayout->addWidget(frame);
retranslateUi(Form);
tabWidget->setCurrentIndex(-1);
QMetaObject::connectSlotsByName(Form);
} // setupUi
void retranslateUi(QWidget *Form)
{
Form->setWindowTitle(QApplication::translate("Form", "Form", Q_NULLPTR));
pushButton->setText(QApplication::translate("Form", "\346\267\273\345\212\240\347\252\227\345\217\243", Q_NULLPTR));
label_2->setText(QApplication::translate("Form", "\346\220\234\347\264\242\344\270\262\345\217\243:", Q_NULLPTR));
lbSearchResult->setText(QString());
} // retranslateUi
};
namespace Ui {
class Form: public Ui_Form {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_FORM_H
| [
"nanusefue@gmail.com"
] | nanusefue@gmail.com |
02e5da282b18ffa20f9a8774e5888b991cb91cca | 0f8965ca3ef310dc0ba47f383ebdcc1bcef3616a | /ext/TslGame_MULTI_HACK-master/PUBG 2.3.3/SDK/PUBG_VehicleBase_classes.hpp | d38f73bad806ff973184d68c39f3df60b6f24b6e | [] | no_license | sbaa2014/MFCApplication1 | dc8f58200845ad6c51edb7aff72b3532ad63f532 | ca6106582c77a55d50cfa209341dc424757d3978 | refs/heads/master | 2021-01-20T17:19:52.409004 | 2017-07-14T11:47:28 | 2017-07-14T11:47:28 | 95,742,921 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 16,357 | hpp | #pragma once
// PUBG (Beta) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace Classes
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass VehicleBase.VehicleBase_C
// 0x01BC (0x0694 - 0x04D8)
class AVehicleBase_C : public ATslWheeledVehicle
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x04D8(0x0008) (CPF_ZeroConstructor, CPF_Transient, CPF_DuplicateTransient)
class UPointLightComponent* BoostLight; // 0x04E0(0x0008) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData)
class UPointLightComponent* LowFuelLight; // 0x04E8(0x0008) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData)
class UPointLightComponent* TailLamp_3; // 0x04F0(0x0008) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData)
class UPointLightComponent* TailLamp_2; // 0x04F8(0x0008) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData)
class USpotLightComponent* HeadLamp_3; // 0x0500(0x0008) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData)
class USpotLightComponent* HeadLamp_2; // 0x0508(0x0008) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData)
class UCameraComponent* ThirdPersonCameraInVehicle; // 0x0510(0x0008) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData)
class USpringArmInVehicleComponent* ThirdPersonSpringArmInVehicle; // 0x0518(0x0008) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData)
class UCameraComponent* FirstPersonCameraInVehicle; // 0x0520(0x0008) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData)
class USpringArmInVehicleComponent* FirstPersonSpringArmInVehicle; // 0x0528(0x0008) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData)
class URadialForceComponent* RadialForce; // 0x0530(0x0008) (CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData)
float ImpactModifier; // 0x0538(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float ImpactAbsorption; // 0x053C(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float ImpactModifierUpsideDown; // 0x0540(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float ImpactAbsorptionUpsideDown; // 0x0544(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float FuelConsumptionModifierBoost; // 0x0548(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float ImpactAbsorptionPassenger; // 0x054C(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float ImpactAbsorptionPassengerUpsideDown; // 0x0550(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float LaunchVelocityFactorOnHitCharacter; // 0x0554(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char IsLightsOn : 1; // 0x0558(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_Net, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char IsBrakeEngaging : 1; // 0x0559(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_Net, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char IsReverseEngaging : 1; // 0x055A(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_Net, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char IsHandBraking : 1; // 0x055B(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float BrakeLightIntensity_On; // 0x055C(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float BrakeLightIntensity_Off; // 0x0560(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float ExplosionRadius_Inner; // 0x0564(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float ExplosionRadius_Outer; // 0x0568(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char UnknownData00[0x4]; // 0x056C(0x0004) MISSED OFFSET
class UCurveFloat* DamageCurve; // 0x0570(0x0008) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float Throttle; // 0x0578(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char UnknownData01[0x4]; // 0x057C(0x0004) MISSED OFFSET
class UCurveFloat* FuelConsumptionCurve; // 0x0580(0x0008) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float FuelEfficiency; // 0x0588(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char UnknownData02[0x4]; // 0x058C(0x0004) MISSED OFFSET
class UTslWheeledVehicleMovement* TslWheeledVehicleMovementRef; // 0x0590(0x0008) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
class ATslPlayerController* DriveControllerrRef; // 0x0598(0x0008) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnTemplate, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
TArray<float> WheelsLatSlip; // 0x05A0(0x0010) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance)
TArray<float> WheelsLongSlip; // 0x05B0(0x0010) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance)
float FuelConsumptionModifierIdle; // 0x05C0(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float SpeedKPH; // 0x05C4(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_IsPlainOldData)
TArray<float> WheelsSuspensionOffset; // 0x05C8(0x0010) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance)
TArray<class UPhysicalMaterial*> WheelsContactSurface; // 0x05D8(0x0010) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance)
TArray<float> WheelsRotationSpeed; // 0x05E8(0x0010) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance)
TArray<float> WheelsSuspensionMaxDrop; // 0x05F8(0x0010) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance)
TArray<float> WheelsSuspensionMaxRaise; // 0x0608(0x0010) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance)
float RPM; // 0x0618(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char TestBoostingAKEvent : 1; // 0x061C(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char TestBoostingAKEvent_prev : 1; // 0x061D(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char TestThrottlingAKEvent : 1; // 0x061E(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char TestThrottlingAKEvent_prev : 1; // 0x061F(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char TestSteeringAKEvent : 1; // 0x0620(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char TestSteeringAKEvent_prev : 1; // 0x0621(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char UnknownData03[0x2]; // 0x0622(0x0002) MISSED OFFSET
float Brake; // 0x0624(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char TestBrakingAKEvent : 1; // 0x0628(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char UnknownData04[0x7]; // 0x0629(0x0007) MISSED OFFSET
TArray<class UPhysicalMaterial*> TestWheelsContactSurface_prev; // 0x0630(0x0010) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance)
unsigned char TestBrakingAKEvent_prev : 1; // 0x0640(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char UnknownData05[0x7]; // 0x0641(0x0007) MISSED OFFSET
TArray<float> WheelsSuspensionOffsetNorm; // 0x0648(0x0010) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance)
TArray<float> WheelsWaterDepth; // 0x0658(0x0010) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance)
float FlatTireCount; // 0x0668(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char bUseDynamicCamera : 1; // 0x066C(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char UnknownData06[0x3]; // 0x066D(0x0003) MISSED OFFSET
class Vector3D LastVelocity; // 0x0670(0x000C) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
class Vector3D Acceleration; // 0x067C(0x000C) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char bTickFuelIndicator : 1; // 0x0688(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char bTickBoostIndicator : 1; // 0x0689(0x0001) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
unsigned char UnknownData07[0x2]; // 0x068A(0x0002) MISSED OFFSET
float LowFuelLevel; // 0x068C(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
float LastFuelConsumptionTime; // 0x0690(0x0004) (CPF_Edit, CPF_BlueprintVisible, CPF_ZeroConstructor, CPF_DisableEditOnInstance, CPF_IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass VehicleBase.VehicleBase_C");
return ptr;
}
void TickIndicators();
void TickDynamicCamera();
void TickBrakeSoundTest();
void TickThrottleSoundTest();
void TickBoostSoundTest();
void TickFuelConsumption(float DeltaSeconds);
void TickBasicInfoCaching();
void TickWheelCaching();
void TickWheelSound();
void OnRep_IsBrakeEngaged();
void OnRep_isLightsOn();
void UserConstructionScript();
void InpActEvt_Handbrake_K2Node_InputActionEvent_4(const struct FKey& Key);
void InpActEvt_Handbrake_K2Node_InputActionEvent_3(const struct FKey& Key);
void ToggleLights();
void BrakeLampOn();
void BrakeLampOff();
void ReceiveTick(float* DeltaSeconds);
void InpAxisEvt_MoveForward_K2Node_InputAxisEvent_8(float AxisValue);
void ReceiveBeginPlay();
void TurnOffLight(float KillingDamage, const struct FDamageEvent& DamageEvent, class ATslPlayerState* PlayerInstigator, class AActor* DamageCauser);
void InpAxisEvt_MoveRight_K2Node_InputAxisEvent_16(float AxisValue);
void EventFuelConsumption();
void ExecuteUbergraph_VehicleBase(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sbaa2009@gmail.com"
] | sbaa2009@gmail.com |
db02430b2a6c11576e755c31a622ca892eb6f7d0 | 963ab3f508583a3ebf547c0d6acd7db57e6fed9d | /CPlayer.cpp | a23da3e1eeadf147cc262b567951650cb022a49a | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive"
] | permissive | PSP-Archive/Pollo-Pollo | 88714445e2e4c085bd8077979f1bd40383e5152c | 887087124c75be73a60afc1fd24bd0c6be50cf0e | refs/heads/main | 2023-04-03T10:25:41.729298 | 2021-04-16T21:32:10 | 2021-04-16T21:32:10 | 358,724,434 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,696 | cpp |
//include class definition
#include "CPlayer.h"
//include some objects declarations
#include "CMGELog.h"
#include "CPlayingMode.h"
#include "CGameGraphic.h"
#include "CPOLLOPOLLOGame.h"
CMGEFont* CPlayer::m_poFont=NULL;
CMGESpriteBank* CPlayer::m_poSprites=NULL;
WORD CPlayer::m_idWinner=0;
WORD CPlayer::m_idLooser=0;
void CPlayer::InitSprites(CMGESpriteBank* pSprites,CMGEFont* pFont)
{
m_poFont=pFont;
m_poSprites = pSprites;
m_idWinner = pSprites->GetId("winner");
m_idLooser = pSprites->GetId("looser");
}
//init CPlayer
bool CPlayer::Init(CPlayingMode* pParent, int nSide, TPlayerMode pmMode, int idChar, int nGameLevel)
{
//finalize
End();
//log output
CMGELog::SysLog(CMGELog::lInfo,"Init CPlayer");
CMGELog::SysIdent();
//base initialize
inherited::Init();
//are we ok?
if(IsOk())
{
m_idChar = idChar;
m_pParent = pParent;
m_pmMode = pmMode;
m_psState = bsPreReady;
m_nWaitNoInput=0;
m_nPoints=0;
m_bBlinkText = true;
m_nAcumulatedBlocks=0;
m_DisapiarBlocks=0;
m_nLoopUntilDrop=0;
m_pParent->GetControl()->m_cuControl.buttons[2] = PSP_CTRL_TRIANGLE;
m_pParent->GetControl()->m_cuControl.buttons[3] = PSP_CTRL_SQUARE;
m_pParent->GetControl()->m_cuControl.buttons[4] = PSP_CTRL_CROSS;
m_pParent->GetControl()->m_cuControl.buttons[5] = PSP_CTRL_CIRCLE;
m_pParent->GetControl()->m_cuControl.buttons[6] = PSP_CTRL_LTRIGGER;
m_pParent->GetControl()->m_cuControl.buttons[7] = PSP_CTRL_RTRIGGER;
m_nSide = nSide;
m_nGameLevel = nGameLevel;
m_nShowNextPieces=3-m_nGameLevel;
CPOLLOPOLLOGame* pGame = (CPOLLOPOLLOGame*) CMGEApp::GetApp();
CPOLLOPOLLOGame::GameLevelConfig config = pGame->GetGameLevelConfig(m_nGameLevel);
m_nSpeed = config.m_nSpeed;
m_nScrenWidth=pGame->GetRenderDevice()->GetWidth();
if(pGame->GetPlayingMode()==CPOLLOPOLLOGame::Pollomania)
{
m_nSpeed=1+m_nGameLevel;
m_bPolloManiaGame=true;
m_nCountToNext=(m_nSpeed*10);
}
else
m_bPolloManiaGame=false;
m_bOk = m_oArea.Init(this);
m_bOk &= m_oPiece.Init(0,0,m_nShowNextPieces);
m_oPiece.Move((CPlayerArea::cnBlockWidth*(m_oArea.GetNumBlocksWidth()>>1)),
-CPlayerArea::cnBlockHeight);
m_nNextCharCount=0;
m_bNextMoveDoChar=false;
m_nLocalSpeed=0;
m_nLoops=0;
if(m_pmMode==pmCpu)
{
m_oCpuLogic.Init(&m_oArea,&m_oPiece,m_nGameLevel);
m_oCpuLogic.Reset();
}
m_bOk = m_oChar.Init(m_pParent,m_idChar);
}
//log output
Log();
CMGELog::SysUnident();
//are we ok?
if (IsOk())
CMGELog::SysLog(CMGELog::lInfo,"Init CPlayer [Ok]");
else
CMGELog::SysLog(CMGELog::lInfo,"Init CPlayer [Fail]");
//return initialization status
return IsOk();
}
//finalize object
void CPlayer::End()
{
//are we ok?
if (IsOk())
{
m_oArea.End();
m_oPiece.End();
//call base finalize
inherited::End();
}
}
//log some info
void CPlayer::Log()
{
//log output
CMGELog::SysLog(CMGELog::lInfo,"Logging CPlayer class");
CMGELog::SysIdent();
CMGELog::SysUnident();
}
void CPlayer::Logic()
{
switch(m_psState)
{
case bsPreReady:
m_psState = bsReady;
m_oArea.AddGraphic(CGameGraphic::gtReadyLogo,
(((m_oArea.GetNumBlocksWidth())*CPlayerArea::cnBlockWidth)>>1)
+CPlayerArea::cBlockStartX
,350,
0,-4,0,0,
(DWORD)this,
(DWORD)m_pParent);
break;
case bsPlaying:
{
CheckControls();
/*
Speeds tables
Speed 0 -> each 4 loops move 1
Speed 1 -> each 3 loops move 1
Speed 2 -> each 2 loops move 1
Speed 3 -> each 1 loops move 1
Speed 4 -> each 1 loops move 2
Speed 5 -> each 1 loops move 3
Speed 6 -> each 1 loops move 4
Speed 7 -> each 1 loops move 5
Speed 8 -> each 1 loops move 6
*/
int m_nLoopMatch = 4 - m_nLocalSpeed;
if(m_nLoopMatch<1)
m_nLoopMatch=1;
if((m_nLoops%m_nLoopMatch)==0)
{
int nToMove = (m_nLocalSpeed-3);
if(nToMove<=0)
nToMove=1;
if(m_bNextMoveDoChar)
{
m_bNextMoveDoChar=false;
DoCharacterStep();
}
for(int nMove=0;nMove<nToMove;nMove++)
{
m_oPiece.Move(0,1);
if((m_oPiece.GetY()%CPlayerArea::cnBlockHeight)==0)
{
if ( Collide() )
{
m_nNextCharCount++;
if(m_nNextCharCount>(cCharCountToPlay-1))
{
m_nNextCharCount=0;
m_bNextMoveDoChar=true;
}
m_oPiece.End();
if((m_bPolloManiaGame)&&(m_nSpeed<cMaxPlayableSpeed))
{
m_nCountToNext--;
if(m_nCountToNext==0)
{
m_nSpeed++;
m_nCountToNext=(m_nSpeed*10);
}
}
m_oPiece.Init(0,0,m_nShowNextPieces);
m_oPiece.Move((CPlayerArea::cnBlockWidth*(m_oArea.GetNumBlocksWidth()>>1)),
-CPlayerArea::cnBlockHeight);
if(!m_oArea.IsEmpty((m_oArea.GetNumBlocksWidth()>>1),0))
{
m_psState=bsStoped;
m_pParent->SetLooser(GetSide());
break;
}
if(m_pmMode==pmCpu)
{
m_oCpuLogic.Reset();
}
if(m_oArea.GetTotalBlink()==0)
{
if(m_nAcumulatedBlocks)
DropAcumulated();
}
break;
}
}
}
}
m_oPiece.Logic();
}
break;
case bsWaitingFalling:
if (m_oArea.GetFalling()==0)
{
if(m_nAcumulatedBlocks)
DropAcumulated();
else
{
if((m_psState!=bsLoosing)&&(m_psState!=bsWinning))
{
m_psState = bsPlaying;
m_nLoops=0;
}
}
}
break;
case bsWaitingBlink:
if(m_oArea.GetTotalBlink()==0)
{
if(m_oArea.GetFalling())
{
if((m_psState!=bsLoosing)&&(m_psState!=bsWinning))
m_psState = bsWaitingFalling;
}
else
{
m_DisapiarBlocks+=m_oArea.GetTotalDisapiar();
if((m_psState!=bsLoosing)&&(m_psState!=bsWinning))
m_psState = bsWaitingDisapiar;
}
}
break;
case bsWaitingDisapiar:
if(m_oArea.GetTotalDisapiar()==0)
{
m_nAcumulatedBlocks -= (m_DisapiarBlocks>>2);
if((m_nAcumulatedBlocks<0)&&(!m_bPolloManiaGame))
{
signed int send = -m_nAcumulatedBlocks;
m_nAcumulatedBlocks-=-send;
m_oArea.AddGraphic(CGameGraphic::gtLigth,
CPlayerArea::cnCharacterX-
(GetSide()*
(
CPlayerArea::cDistanceFromPlayer
)
)
+(GetSide()*CPlayerArea::cDistanceNextPieces)
,CPlayerArea::cnCharacterY,
(GetSide()?-CPlayerArea::cnStartVX:CPlayerArea::cnStartVX),-CPlayerArea::cnStartVY,
0+(GetSide()*CPlayerArea::cBlockStartX),
CPlayerArea::cBlockStartY,
(DWORD)m_pParent,
(DWORD)GetSide(),
(DWORD)send);
//m_pParent->SendBlocksFromPlayer(GetSide(),send);
}
m_DisapiarBlocks=0;
m_nLoops=0;
if(m_nAcumulatedBlocks)
{
DropAcumulated();
}
else
{
if((m_psState!=bsLoosing)&&(m_psState!=bsWinning))
m_psState = bsPlaying;
}
}
if(m_oArea.GetFalling())
{
if((m_psState!=bsLoosing)&&(m_psState!=bsWinning))
m_psState = bsWaitingFalling;
}
break;
case bsLoosing:
case bsWinning:
if((m_nLoops%8)==0)
m_bBlinkText=!m_bBlinkText;
break;
}
if((m_psState!=bsLoosing)&&(m_psState!=bsWinning))
m_nPoints+=m_oArea.Logic();
if(m_oArea.GetTotalBlink()>0)
{
if((m_psState!=bsLoosing)&&(m_psState!=bsWinning))
m_psState=bsWaitingBlink;
}
m_nLoopUntilDrop--;
m_nLoops++;
if(m_nLoops>1000)
m_nLoops=0;
m_oChar.Logic();
}
void CPlayer::Draw()
{
if(!m_bPolloManiaGame)
m_oPiece.DrawNextPieces(CPlayerArea::cNexPiecesStar+
(CPlayerArea::cDistanceNextPieces*GetSide()),
CPlayerArea::cBlockStartY);
else
{
m_oPiece.DrawNextPieces(m_nScrenWidth-CPlayerArea::cBlockStartX -
(4*CPlayerArea::cNextPieceSeparationX),
CPlayerArea::cBlockStartY);
}
if(m_psState==bsPlaying)
m_oPiece.Draw(CPlayerArea::cBlockStartX+
(CPlayerArea::cDistanceFromPlayer*GetSide()),
CPlayerArea::cBlockStartY);
m_oArea.Draw();
/*
switch(m_psState)
{
case bsLoosing:
if(m_bBlinkText)
m_poSprites->Draw(m_idLooser,CPlayerArea::cnCenter+(CPlayerArea::cDistanceFromPlayer*GetSide()),60);
*m_poFont->Write(CPlayerArea::cBlockStartX+(CPlayerArea::cDistanceFromPlayer*GetSide()),
60,"You Loose");
break;
case bsWinning:
if(m_bBlinkText)
m_poFont->Write(CPlayerArea::cBlockStartX+(CPlayerArea::cDistanceFromPlayer*GetSide()),
60,"You Win");
break;
}
*/
if( (m_psState==bsLoosing) || (m_psState==bsWinning) )
{
int idSprite = (m_psState==bsLoosing)?m_idLooser:m_idWinner;
m_poSprites->TransDraw(idSprite,
(((m_oArea.GetNumBlocksWidth())*CPlayerArea::cnBlockWidth)>>1)
+CPlayerArea::cBlockStartX+(CPlayerArea::cDistanceFromPlayer*GetSide()),
60,
m_bBlinkText?32:16);
}
DrawAcumulated(CPlayerArea::cBlockStartX+
(CPlayerArea::cDistanceFromPlayer*GetSide()),0);
if(!m_bPolloManiaGame)
{
m_poFont->Write(64+(CPlayerArea::cDistanceFromPlayer*GetSide()),260,
"%11d",m_nPoints);
m_oChar.Draw(CPlayerArea::cnCharacterX+(CPlayerArea::cDistanceNextPieces*GetSide()),
CPlayerArea::cnCharacterY);
}
else
{
m_poFont->Write(64+CPlayerArea::cDistanceFromPlayer,260,
"%11d",m_nPoints);
m_oChar.Draw(m_nScrenWidth-CPlayerArea::cBlockStartX-(CPlayerArea::cnCharacterWidth>>1),
CPlayerArea::cnCharacterY);
m_poFont->Write(m_nScrenWidth-CPlayerArea::cBlockStartX-(CPlayerArea::cnCharacterWidth>>1)+16
,158,"%d",m_nSpeed);
m_poFont->Write(m_nScrenWidth-CPlayerArea::cBlockStartX-(CPlayerArea::cnCharacterWidth>>1)+16
,177,"%d",m_nCountToNext);
}
}
bool CPlayer::Collide(bool bOnlyTest/*=false*/)
{
bool bResult = false;
bool bCollideCenter = CollideBlock(CPiece::cCenterBlock);
bool bCollideStick = CollideBlock(CPiece::cStickBlock);
if(bCollideCenter||bCollideStick)
{
if ( (m_oPiece.GetCicle()==CPiece::tcTOP)
|| (m_oPiece.GetCicle()==CPiece::tcDOWN) )
{
bCollideCenter=true;
bCollideStick=true;
}
}
if((bCollideCenter)&&(!bOnlyTest))
SetBlock(CPiece::cCenterBlock);
if((bCollideStick)&&(!bOnlyTest))
SetBlock(CPiece::cStickBlock);
bResult = (bCollideCenter||bCollideStick);
//check if we need a falling block
if((bResult)&&(bCollideCenter!=bCollideStick)&&(!bOnlyTest))
{
//stick to center its the falling block
if(bCollideCenter)
{
AddFallinBlock(CPiece::cStickBlock);
}
//center its the falling block
else
{
AddFallinBlock(CPiece::cCenterBlock);
}
}
if((bResult)&&(!bOnlyTest))
GroundBlocks(true);
return bResult;
}
bool CPlayer::CollideBlock(BYTE block)
{
bool bResult = false;
CBlock* pBlock = m_oPiece.GetBlock(block);
int width = m_oPiece.GetX()/CPlayerArea::cnBlockWidth;
int height = m_oPiece.GetY()/CPlayerArea::cnBlockHeight;
width += pBlock->GetX()/CPlayerArea::cnBlockWidth;
height += pBlock->GetY()/CPlayerArea::cnBlockHeight;
if(height>=0)
{
if (height==(CPlayerArea::cnNumBlocksHeight-1))
{
bResult=true;
}
else
{
bResult=!m_oArea.IsEmpty(width,height+1);
}
}
return bResult;
}
void CPlayer::SetBlock(BYTE block)
{
CBlock* pBlock = m_oPiece.GetBlock(block);
int width = m_oPiece.GetX()/CPlayerArea::cnBlockWidth;
int height = m_oPiece.GetY()/CPlayerArea::cnBlockHeight;
width += pBlock->GetX()/CPlayerArea::cnBlockWidth;
height += pBlock->GetY()/CPlayerArea::cnBlockHeight;
if(height<0)
{
m_psState=bsStoped;
m_pParent->SetLooser(GetSide());
}
m_nPoints+=m_oArea.SetBlock(width,height,m_oPiece.GetBlock(block));
}
bool CPlayer::CheckControls()
{
bool bResult=false;
m_oPlayerResponse.left=false;
m_oPlayerResponse.rigth=false;
m_oPlayerResponse.up=false;
m_oPlayerResponse.down=false;
m_oPlayerResponse.buttons[0].wasPressed=false;
m_oPlayerResponse.buttons[0].bePushed=false;
switch(m_pmMode)
{
case pmSolo:
m_oPlayerResponse.left=m_pParent->GetControl()->m_cuResponse.left;
m_oPlayerResponse.rigth=m_pParent->GetControl()->m_cuResponse.rigth;
m_oPlayerResponse.up=m_pParent->GetControl()->m_cuResponse.up;
m_oPlayerResponse.down=m_pParent->GetControl()->m_cuResponse.down;
m_oPlayerResponse.buttons[0].wasPressed=m_pParent->GetControl()->m_cuResponse.buttons[4].wasPressed;
break;
case pmFirst:
#if defined (WIN_VER)
m_oPlayerResponse.up=m_pParent->GetControl()->m_cuResponse.buttons[2].bePushed;
m_oPlayerResponse.left=m_pParent->GetControl()->m_cuResponse.buttons[3].bePushed;
m_oPlayerResponse.down=m_pParent->GetControl()->m_cuResponse.buttons[4].bePushed;
m_oPlayerResponse.rigth=m_pParent->GetControl()->m_cuResponse.buttons[5].bePushed;
#else
m_oPlayerResponse.left=m_pParent->GetControl()->m_cuResponse.left;
m_oPlayerResponse.rigth=m_pParent->GetControl()->m_cuResponse.rigth;
m_oPlayerResponse.up=m_pParent->GetControl()->m_cuResponse.up;
m_oPlayerResponse.down=m_pParent->GetControl()->m_cuResponse.down;
#endif
m_oPlayerResponse.buttons[0].wasPressed=m_pParent->GetControl()->m_cuResponse.buttons[6].wasPressed;
break;
case pmSecond:
#if defined (WIN_VER)
m_oPlayerResponse.left=m_pParent->GetControl()->m_cuResponse.left;
m_oPlayerResponse.rigth=m_pParent->GetControl()->m_cuResponse.rigth;
m_oPlayerResponse.up=m_pParent->GetControl()->m_cuResponse.up;
m_oPlayerResponse.down=m_pParent->GetControl()->m_cuResponse.down;
#else
m_oPlayerResponse.up=m_pParent->GetControl()->m_cuResponse.buttons[2].bePushed;
m_oPlayerResponse.left=m_pParent->GetControl()->m_cuResponse.buttons[3].bePushed;
m_oPlayerResponse.down=m_pParent->GetControl()->m_cuResponse.buttons[4].bePushed;
m_oPlayerResponse.rigth=m_pParent->GetControl()->m_cuResponse.buttons[5].bePushed;
#endif
m_oPlayerResponse.buttons[0].wasPressed=m_pParent->GetControl()->m_cuResponse.buttons[7].wasPressed;
break;
case pmCpu:
m_oCpuLogic.Calculate();
m_oPlayerResponse.left=m_oCpuLogic.GetResponse()->left;
m_oPlayerResponse.rigth=m_oCpuLogic.GetResponse()->rigth;
m_oPlayerResponse.up=m_oCpuLogic.GetResponse()->up;
m_oPlayerResponse.down=m_oCpuLogic.GetResponse()->down;
m_oPlayerResponse.buttons[0].wasPressed=m_oCpuLogic.GetResponse()->buttons[0].wasPressed;
break;
}
if (m_oPlayerResponse.buttons[0].wasPressed)
{
if(CouldRotate())
{
m_oPiece.Rotate();
m_pParent->TurnSound();
}
}
if(m_nWaitNoInput==0)
{
if (m_oPlayerResponse.left)
{
if (CouldMoveToLeft())
{
m_oPiece.Move(-CPlayerArea::cnBlockWidth,0);
m_nWaitNoInput=cWaitNoInput;
bResult=true;
m_pParent->TraslateSound();
}
}
if (m_oPlayerResponse.rigth)
{
if (CouldMoveToRigth())
{
m_oPiece.Move(CPlayerArea::cnBlockWidth,0);
m_nWaitNoInput=cWaitNoInput;
bResult=true;
m_pParent->TraslateSound();
}
}
}
else
m_nWaitNoInput--;
if(m_oPlayerResponse.down)
{
m_nLocalSpeed=cMaxSpeed;
}
else
m_nLocalSpeed=m_nSpeed;
return bResult;
}
void CPlayer::AddFallinBlock(BYTE block)
{
CBlock* pBlock = m_oPiece.GetBlock(block);
int width = m_oPiece.GetX()/CPlayerArea::cnBlockWidth;
int height = m_oPiece.GetY()/CPlayerArea::cnBlockHeight;
width += pBlock->GetX()/CPlayerArea::cnBlockWidth;
height += pBlock->GetY()/CPlayerArea::cnBlockHeight;
m_psState=bsWaitingFalling;
m_oArea.AddFallinBlock(width,height,m_oPiece.GetBlock(block));
}
bool CPlayer::CouldMoveToLeft()
{
bool bResult=true;
int width = m_oPiece.GetX();
int height = m_oPiece.GetY();
int bwidth=0;
int bheight=0;
CBlock* pBlock = NULL;
for(int block=0;block<CPiece::cnMaxBlocks;block++)
{
pBlock = m_oPiece.GetBlock(block);
bwidth = width + pBlock->GetX();
bheight = height + pBlock->GetY();
if((bheight%CPlayerArea::cnBlockHeight)==0)
{
bwidth /= CPlayerArea::cnBlockWidth;
bheight /= CPlayerArea::cnBlockHeight;
}
else
{
bwidth /= CPlayerArea::cnBlockWidth;
bheight /= CPlayerArea::cnBlockHeight;
bheight++;
}
if(bwidth<=0)
bResult=false;
else
bResult=m_oArea.IsEmpty(bwidth-1,bheight);
if(!bResult)
break;
}
return bResult;
}
bool CPlayer::CouldMoveToRigth()
{
bool bResult=true;
int width = m_oPiece.GetX();
int height = m_oPiece.GetY();
int bwidth=0;
int bheight=0;
CBlock* pBlock = NULL;
for(int block=0;block<CPiece::cnMaxBlocks;block++)
{
pBlock = m_oPiece.GetBlock(block);
bwidth = width + pBlock->GetX();
bheight = height + pBlock->GetY();
if((bheight%CPlayerArea::cnBlockHeight)==0)
{
bwidth /= CPlayerArea::cnBlockWidth;
bheight /= CPlayerArea::cnBlockHeight;
}
else
{
bwidth /= CPlayerArea::cnBlockWidth;
bheight /= CPlayerArea::cnBlockHeight;
bheight++;
}
if(bwidth>=((m_oArea.GetNumBlocksWidth())-1))
bResult=false;
else
bResult=m_oArea.IsEmpty(bwidth+1,bheight);
if(!bResult)
break;
}
return bResult;
}
bool CPlayer::CouldRotate()
{
bool bResult=true;
int width = m_oPiece.GetX();
int height = m_oPiece.GetY();
int bwidth=0;
int bheight=0;
CBlock* pBlock = NULL;
for(int block=0;block<CPiece::cnMaxBlocks;block++)
{
pBlock = m_oPiece.GetBlock(block);
bwidth = width + pBlock->GetX();
bheight = height + pBlock->GetY();
if((bheight%CPlayerArea::cnBlockHeight)==0)
{
bwidth /= CPlayerArea::cnBlockWidth;
bheight /= CPlayerArea::cnBlockHeight;
}
else
{
bwidth /= CPlayerArea::cnBlockWidth;
bheight /= CPlayerArea::cnBlockHeight;
bheight++;
}
if(bheight>=(CPlayerArea::cnNumBlocksHeight-1))
bResult=false;
if(bwidth>=((m_oArea.GetNumBlocksWidth())-1))
{
if(m_oPiece.GetCicle()==CPiece::tcDOWN)
bResult=false;
}
if(bwidth<=0)
{
if(m_oPiece.GetCicle()==CPiece::tcTOP)
bResult=false;
}
if(!bResult)
break;
}
if(bResult)
{
m_oPiece.Rotate();
bResult=!Collide(true);
m_oPiece.Rotate();
m_oPiece.Rotate();
m_oPiece.Rotate();
}
if(!bResult)
{
if( (m_oPiece.GetCicle()==CPiece::tcTOP) )
{
if(bwidth<((m_oArea.GetNumBlocksWidth())-1))
{
if(CouldMoveToRigth())
{
m_oPiece.Move(CPlayerArea::cnBlockWidth,0);
bResult=CouldRotate();
if(!bResult)
m_oPiece.Move(-CPlayerArea::cnBlockWidth,0);
}
}
}
if( (m_oPiece.GetCicle()==CPiece::tcDOWN) )
{
if(bwidth>0)
{
if (CouldMoveToLeft())
{
m_oPiece.Move(-CPlayerArea::cnBlockWidth,0);
bResult=CouldRotate();
if(!bResult)
m_oPiece.Move(CPlayerArea::cnBlockWidth,0);
}
}
}
}
return bResult;
}
void CPlayer::AddBlocks(BYTE nBlocks)
{
if((m_psState!=bsLoosing)&&(m_psState!=bsWinning))
{
m_nAcumulatedBlocks+=nBlocks;
if(m_nLoopUntilDrop<=0)
m_nLoopUntilDrop=(CPlayerArea::cnLoopUntilDrop);
}
}
void CPlayer::DropAcumulated()
{
if(m_nLoopUntilDrop<0)
{
int m_nAcumulatedBlocksActual = m_nAcumulatedBlocks;
m_nAcumulatedBlocks-=m_nAcumulatedBlocks;
if((m_psState!=bsLoosing)&&(m_psState!=bsWinning))
m_psState = bsWaitingFalling;
CBlock m_bTempBlock;
m_bTempBlock.Init(0,0);
m_bTempBlock.SetType(6);
for(int nAcumulate=0;nAcumulate<m_nAcumulatedBlocksActual;nAcumulate++)
{
m_oArea.AddFallinBlock(rand()%(m_oArea.GetNumBlocksWidth()),
0,&m_bTempBlock);
}
}
}
void CPlayer::DrawAcumulated(int x, int y)
{
int nLocalX = 0;
int m_nAcumulatedBlocksActualSmall = m_nAcumulatedBlocks;
int m_nAcumulatedBlocksActualBig = m_nAcumulatedBlocksActualSmall>>2;
m_nAcumulatedBlocksActualSmall-=(m_nAcumulatedBlocksActualBig<<2);
int nAcumulate=0;
CBlock m_bTempBlock;
m_bTempBlock.Init(x,y);
m_bTempBlock.SetState(CBlock::bsNoEyes);
m_bTempBlock.SetType(6);
for(nAcumulate=0;nAcumulate<m_nAcumulatedBlocksActualBig;nAcumulate++)
{
m_bTempBlock.Draw(nLocalX,0);
nLocalX+=CPlayerArea::cnBlockWidth;
}
m_bTempBlock.SetType(7);
for(nAcumulate=0;nAcumulate<m_nAcumulatedBlocksActualSmall;nAcumulate++)
{
m_bTempBlock.Draw(nLocalX,0);
nLocalX+=CPlayerArea::cnBlockWidth>>1;
}
}
void CPlayer::BingoSound(){m_pParent->BingoSound();}
void CPlayer::HitgroundSound(){m_pParent->HitgroundSound();}
void CPlayer::GroundBlocks(bool bEmotion)
{
HitgroundSound();
//CMGELog::SysLog(CMGELog::lAll,"player %d : relative %d total %d",GetSide(),relativeline,total);
}
void CPlayer::DoCharacterStep()
{
if((m_psState!=bsLoosing)&&(m_psState!=bsWinning))
{
int total = m_oArea.GetTotalBlocks();
int relativeline = total / (m_oArea.GetNumBlocksWidth());
if(relativeline==3)
{
m_oChar.SetMode("normal");
}
else if((relativeline>=0)&&(relativeline<=2))
{
m_oChar.SetMode("winning");
}
else
{
m_oChar.SetMode("loosing");
}
}
}
void CPlayer::SetDemoPlay()
{
SetSate(CPlayer::bsPlaying);
m_oArea.GenerateRandom();
m_nPoints=15000+(rand()%15000);
}
| [
"pierluigiortenzi@gmail.com"
] | pierluigiortenzi@gmail.com |
891e9b310e9b2d493ece0638e050ef81703ac49b | 2650fb3f9efd082c949f304cf438d10b2b70e74a | /gms/representations/graphs/log_graph/cc.cc | 4895c54cc670e631953715daeb8de91613e50fc3 | [
"MIT"
] | permissive | jingmouren/gms | 0abc3468bc7cf7b0576628e3f7a5e107d877aa3b | bd8f384ca2f02c52909f4ab77cbb86edba89c7b6 | refs/heads/main | 2023-05-29T19:51:07.071003 | 2021-06-11T09:04:40 | 2021-06-11T09:04:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,461 | cc | // Copyright (c) 2015, The Regents of the University of California (Regents)
// See LICENSE.txt for license details
#include <algorithm>
#include <cinttypes>
#include <iostream>
#include <unordered_map>
#include <vector>
#include <gms/third_party/gapbs/benchmark.h>
#include <gms/third_party/gapbs/bitmap.h>
#include <gms/third_party/gapbs/builder.h>
#include <gms/third_party/gapbs/command_line.h>
#include <gms/third_party/gapbs/graph.h>
#include <gms/third_party/gapbs/pvector.h>
#include <gms/third_party/gapbs/timer.h>
/*
GAP Benchmark Suite
Kernel: Connected Components (CC)
Author: Scott Beamer
Will return comp array labelling each vertex with a connected component ID
This CC implementation makes use of the Shiloach-Vishkin [2] algorithm with
implementation optimizations from Bader et al. [1].
[1] David A Bader, Guojing Cong, and John Feo. "On the architectural
requirements for efficient execution of graph algorithms." International
Conference on Parallel Processing, Jul 2005.
[2] Yossi Shiloach and Uzi Vishkin. "An o(logn) parallel connectivity algorithm"
Journal of Algorithms, 3(1):57–67, 1982.
*/
using namespace std;
pvector<NodeId> ShiloachVishkin(const CSRGraph &g) {
pvector<NodeId> comp(g.num_nodes());
#pragma omp parallel for
for (NodeId n=0; n < g.num_nodes(); n++)
comp[n] = n;
bool change = true;
int num_iter = 0;
while (change) {
change = false;
num_iter++;
#pragma omp parallel for
for (NodeId u=0; u < g.num_nodes(); u++) {
NodeId comp_u = comp[u];
for (NodeId v : g.out_neigh(u)) {
NodeId comp_v = comp[v];
if ((comp_u < comp_v) && (comp_v == comp[comp_v])) {
change = true;
comp[comp_v] = comp_u;
}
}
}
#pragma omp parallel for
for (NodeId n=0; n < g.num_nodes(); n++) {
while (comp[n] != comp[comp[n]]) {
comp[n] = comp[comp[n]];
}
}
}
#if PRINT_INFO
cout << "Shiloach-Vishkin took " << num_iter << " iterations" << endl;
#endif
return comp;
}
void PrintCompStats(const CSRGraph &g, const pvector<NodeId> &comp) {
cout << endl;
unordered_map<NodeId, NodeId> count;
for (NodeId comp_i : comp)
count[comp_i] += 1;
int k = 5;
vector<pair<NodeId, NodeId>> count_vector;
count_vector.reserve(count.size());
for (auto kvp : count)
count_vector.push_back(kvp);
vector<pair<NodeId, NodeId>> top_k = TopK(count_vector, k);
k = min(k, static_cast<int>(top_k.size()));
cout << k << " biggest clusters" << endl;
for (auto kvp : top_k)
cout << kvp.second << ":" << kvp.first << endl;
cout << "There are " << count.size() << " components" << endl;
}
// Verifies CC result by performing a BFS from a vertex in each component
// - Asserts search does not reach a vertex with a different component label
// - If the graph is directed, it performs the search as if it was undirected
// - Asserts every vertex is visited (degree-0 vertex should have own label)
bool CCVerifier(const CSRGraph &g, const pvector<NodeId> &comp) {
unordered_map<NodeId, NodeId> label_to_source;
for (NodeId n : g.vertices())
label_to_source[comp[n]] = n;
Bitmap visited(g.num_nodes());
visited.reset();
vector<NodeId> frontier;
frontier.reserve(g.num_nodes());
for (auto label_source_pair : label_to_source) {
NodeId curr_label = label_source_pair.first;
NodeId source = label_source_pair.second;
frontier.clear();
frontier.push_back(source);
visited.set_bit(source);
for (auto it = frontier.begin(); it != frontier.end(); it++) {
NodeId u = *it;
for (NodeId v : g.out_neigh(u)) {
if (comp[v] != curr_label)
return false;
if (!visited.get_bit(v)) {
visited.set_bit(v);
frontier.push_back(v);
}
}
if (g.directed()) {
for (NodeId v : g.in_neigh(u)) {
if (comp[v] != curr_label)
return false;
if (!visited.get_bit(v)) {
visited.set_bit(v);
frontier.push_back(v);
}
}
}
}
}
for (NodeId n=0; n < g.num_nodes(); n++)
if (!visited.get_bit(n))
return false;
return true;
}
int main(int argc, char* argv[]) {
CLApp cli(argc, argv, "connected-components");
if (!cli.ParseArgs())
return -1;
Builder b(cli);
CSRGraph g = b.MakeGraph();
BenchmarkKernelLegacy(cli, g, ShiloachVishkin, PrintCompStats, CCVerifier);
return 0;
}
| [
"maciej@maciej-pc"
] | maciej@maciej-pc |
6dfab61543b5f1bdbc3671bd7076de2dbcb978a0 | 20049d88e2e8f0e1904efc561103c1d84d21507a | /gusarov.ilya/common/circle.cpp | ca9df56c571cdd77db1eacf4b161057abe0ee0f5 | [] | no_license | gogun/Labs-for-SPbSPU-C-course-during-2019 | 5442a69152add3e66f02a7541e8dc8dd817f38a1 | 16ade47b859517a48d0fdb2e9704464bce4cc355 | refs/heads/master | 2022-01-09T16:02:54.728830 | 2019-06-06T11:06:33 | 2019-06-06T11:06:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,133 | cpp | #include "circle.hpp"
#include <iostream>
#include <stdexcept>
#include <cmath>
gusarov::Circle::Circle(const point_t ¢er, const double radius):
center_(center),
radius_(radius)
{
if (radius <= 0)
{
throw std::invalid_argument("Invalid radius value");
}
}
double gusarov::Circle::getArea() const
{
return M_PI * pow(radius_, 2);
}
gusarov::rectangle_t gusarov::Circle::getFrameRect() const
{
return {radius_ * 2, radius_ * 2, center_};
}
void gusarov::Circle::move(const double shiftX, const double shiftY)
{
center_.x += shiftX;
center_.y += shiftY;
}
void gusarov::Circle::move(const gusarov::point_t &newPoint)
{
center_ = newPoint;
}
void gusarov::Circle::printInfo() const
{
std::cout << "Radius of circle is " << radius_ << '\n';
std::cout << "Center of circle is a point: (" << center_.x << ";" << center_.y << ")" << '\n';
}
void gusarov::Circle::scale(const double scale)
{
if (scale <= 0)
{
throw std::invalid_argument("Invalid scale value");
}
radius_ *= scale;
}
double gusarov::Circle::getRadius() const
{
return radius_;
}
void gusarov::Circle::rotate(double)
{
}
| [
"gusarov2000@gmail.com"
] | gusarov2000@gmail.com |
ea1167e164a821af1b073752a3153233e13c1eb6 | eea38cc8b2c0833038b661b11efee953156c58ce | /Sorting/Merge sort.cpp | 5d7fdb94098d1f98b7f74ecfd61593fe5b14767e | [] | no_license | parasvillis/Problem-Solving | 5b6ba1945e1add995f5ef8ffe0f2a6d4f694d250 | 5ec964abff6210525aa4e96a64c67eb217d2bb4e | refs/heads/master | 2020-06-23T06:25:13.717602 | 2019-07-24T03:08:48 | 2019-07-24T03:08:48 | 198,543,304 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 511 | cpp | #include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i = 0; i < n; i++)
{
cin>>arr[i];
}
int l[n/2], r[n-(n/2)];
for(int i = 0; i < n/2; i++)
{
l[i] = arr[i];
}
int j = n/2;
for(int i = 0; i <= n/2; i++)
{
r[i] = arr[j];
j++;
}
for(int i = 0; i < n/2; i++)
{
cout<<l[i]<<" ";
}
cout<<endl;
for(int i = 0; i <= n/2; i++)
{
cout<<r[i]<<" ";
}
}
| [
"parasvillis655@gmail.com"
] | parasvillis655@gmail.com |
64216541ceb8827b1f3459e1d9057df8cd7b9b7d | b9c92f6e2095b220b26a08d5f465babc3882a5f3 | /board.h | 90fe6863348d640dadfab811420fb73ac57ad26c | [
"LicenseRef-scancode-public-domain"
] | permissive | jrtick/15-466-f17-base1 | ec98d3ca5b8b2cb253e22de877ee7d6a7ad6e852 | 0b90f894460f99cbbc34520e02da87a74b006337 | refs/heads/master | 2021-01-23T22:19:07.011761 | 2017-09-16T07:13:07 | 2017-09-16T07:13:07 | 102,925,455 | 0 | 0 | null | 2017-09-09T04:00:07 | 2017-09-09T04:00:07 | null | UTF-8 | C++ | false | false | 2,080 | h | #include <functional>
#include <glm/glm.hpp>
#include <vector>
enum class Terrain {Grass,Castle,End,Road}; //End is castle end
#define TERR_STR(x) (x==Terrain::Grass? "Grass" : (x==Terrain::Road? "Road" : (x==Terrain::End? "End" : "Castle")))
struct int2{
int x,y;
int2(){ x=y=0;}
int2(int x,int y){
this->x=x;
this->y=y;
}
};
struct Tile{
int tileNum;
int x,y; //position on board
bool flag;
bool hasChurch;
Terrain sides[4]; // up right down left
int rotation;
Tile *up,*right,*down,*left;
Tile(int tileNum, bool flag, int x=-1, int y=-1);
Terrain getTerrain(int dir){
Terrain out = sides[(dir+(rotation%360)/90+4)%4];
return out;
}
void rotate(int angle){
rotation = (rotation+angle)%360;
}
};
class Board{
private:
std::vector<Tile*> tiles;
int tile_freqs[20] = {0,8,1,4,9,3,3,3,3,5,2,3,4,2,4,5,4,3,3,1};
/* connects tile based on position, returns false if invalidly placed */
bool connectTile(bool flag,Tile* tile,Tile* curTile);
public:
static Terrain sides[20][4];
int minx,miny,maxx,maxy;
Tile* center; //starting tile which board is built off
Board(Tile* first){
center = first;
tiles.push_back(first);
minx=std::min(first->x,0);
maxx=std::max(first->x,0);
miny=std::min(first->y,0);
maxy=std::max(first->y,0);
}
int2 mouseToXY(glm::vec2 mouse); //tile coords based on gl screen pt
Tile* find(int x, int y); //finds board loc (x,y) if it exists
void freeTiles(Tile* current, bool flag); //release data structure
Tile* getRandTile(); //returns a random tile out of the remaining tile_freqs
bool addTile(Tile* tile); //place and ret true if valid, otherwise don't place and return false
int completedCastle(Tile* tile,bool flag, int dir,int score = 0, bool firstCall=true); //check if castle completed & return score
void mapDraw(std::function<void (Tile*)> drawFn, bool flag, Tile* curTile); //draw ALL tiles stemming from curTile
void setFlag(bool flag){ //reset processed flags
for(Tile* tile : tiles) tile->flag = flag;
}
int getWidth(){ return maxx-minx+1;}
int getHeight(){ return maxy-miny+1;}
};
| [
"jrtick@andrew.cmu.edu"
] | jrtick@andrew.cmu.edu |
d674f143b31fb509a88cc144ec947df99f7d7730 | ea5b01a6ccaa93b14808c95c841e12abad6e6c20 | /common/include/ctsn_common/XBeeTxHTTPRequestHandler.h | c86292cb9345b713679f2be80998bebe81218f42 | [] | no_license | xforever1313/commutertrackingsensornet | c9cdcc98d2c74dbf491185b2e31eae38ea0ea748 | cd3f3a6de929a7329744e5425aa01f16f764172a | refs/heads/master | 2020-04-06T03:42:53.641087 | 2015-03-15T01:42:27 | 2015-03-15T01:42:27 | 30,444,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,845 | h | #ifndef XBEE_TX_HTTP_REQUEST_HANDLER_H_
#define XBEE_TX_HTTP_REQUEST_HANDLER_H_
#include <Poco/Net/HTTPServerRequest.h>
#include <Poco/Net/HTTPServerResponse.h>
#include <string>
#include "EventExecutorInterface.h"
#include "ctsn_common/BaseHTTPRequestHandler.h"
#include "ctsn_common/NodeContainerInterface.h"
#include "ctsn_common/UartInterface.h"
namespace CTSNCommon {
/**
* \class XBeeTxHTTPRequestHandler
* \brief Handles the http request when an agent wants the gateway to
* send a message out via XBee.
* \note To use, do an http post request with the data in the following form:
* node=nodeNumberToSendTo&message=message to send.
*/
class XBeeTxHTTPRequestHandler : public CTSNCommon::BaseHTTPRequestHandler {
public:
XBeeTxHTTPRequestHandler(Common::EventExecutorInterface *eventExecutor,
CTSNCommon::UartInterface *uart,
NodeContainerInterface *nodes);
~XBeeTxHTTPRequestHandler();
void handleGetRequest(Poco::Net::HTTPServerRequest &request,
Poco::Net::HTTPServerResponse &response) override;
void handlePostRequest(Poco::Net::HTTPServerRequest &request,
Poco::Net::HTTPServerResponse &response) override;
private:
static const std::string POST_MESSAGE;
static const std::string POST_MISSING_FIELD_MESSAGE;
static const std::string GET_MESSAGE;
static const std::string MESSAGE_FORM_DATA;
static const std::string NODE_FORM_DATA;
XBeeTxHTTPRequestHandler() = delete;
XBeeTxHTTPRequestHandler(const XBeeTxHTTPRequestHandler&);
Common::EventExecutorInterface *m_eventExecutor;
CTSNCommon::UartInterface *m_uart;
NodeContainerInterface *m_nodes;
};
}
#endif
| [
"xforever1313@aim.com"
] | xforever1313@aim.com |
2eee9584aab31dba9c37de996220b5b607002881 | 461c327d09480b0af414eace6f3203d67bd912db | /kia_amplifier_serial/kia_amplifier_serial.cpp | af8e47d003be591a8bedc24ab3631d323f0bf0fa | [] | no_license | michael200kg/kia_amplifier_sketch | 91a7705750564e3fa58f7ff359d2ec8b66eac067 | 18d6c5ccfa38e8a2de94abfd0e239bccc313250c | refs/heads/master | 2023-03-16T21:43:43.179946 | 2021-03-02T21:30:34 | 2021-03-02T21:30:34 | 343,869,033 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,814 | cpp | #include <SPI.h>
#include <EEPROM.h>
#include <kia_amplifier_serial.h>
void KiaAmplifierSerial::init() {
while (!Serial);
Serial.begin(BOUND_RATE);
SPI.begin();
};
CanDataKeeper KiaAmplifierSerial::readEprom() {
//reading stored settings
byte stnTmp[8];
int sumTmp;
boolean isDataValid = true;
for (int i = 0; i < 8; i++) {
stnTmp[i] = EEPROM.read(i);
sumTmp = sumTmp + EEPROM.read(i);
}
Serial.println("Summ in EEPROM = " + String(sumTmp));
if (sumTmp != 388 && sumTmp != 2048) {
Serial.println(F("loaded from eeprom"));
memccpy(sendingData, stnTmp, "", 8);
for (int i = 0; i < sizeof sendingData; i++) {
Serial.println(sendingData[i], HEX);
}
} else {
Serial.println(F("Error while loading from EEPROM"));
isDataValid = false;
}
return CanDataKeeper(isDataValid, sendingData);
};
CanDataKeeper KiaAmplifierSerial::generateNewData() {
int ret = 0;
int CheckSum = 0;
boolean isDataValid = true;
for (int i = 0; i < sizeof receive - 2; i++) {
CheckSum = (int) receive[i] + CheckSum;
}
if (((CheckSum & 255) ^ 255) == (int)receive[8]) {
ret = 1;
memccpy(sendingData, receive, "", 8);
for (int i = 0; i < sizeof sendingData - 1; i++) {
EEPROM.write(i, sendingData[i]);
}
} else {
Serial.println(F("Chsumm fail"));
isDataValid = false;
}
return CanDataKeeper(isDataValid, sendingData);
};
CanDataKeeper KiaAmplifierSerial::readNewValues(byte sData[8]) {
for(int ii=0;ii<8;ii++) {
sendingData[ii] = sData[ii];
}
Serial.setTimeout(20);
Serial.readBytesUntil(77, receive, 10);
Serial.println("Recieved bytes via serial: ");
for(int ii=0;ii<10;ii++) {
Serial.print( String(receive[ii]) + " " );
}
Serial.println("");
return generateNewData();
}; | [
"michael.vershkov@gmail.com"
] | michael.vershkov@gmail.com |
fa507425523f0e914710a7bf381011d4f614e52f | bff9ee7f0b96ac71e609a50c4b81375768541aab | /src/external/armadillo/include/armadillo_bits/cond_rel_meat.hpp | 3710dc14c8b049bffc894ac6398f2d36d0af6169 | [
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | rohitativy/turicreate | d7850f848b7ccac80e57e8042dafefc8b949b12b | 1c31ee2d008a1e9eba029bafef6036151510f1ec | refs/heads/master | 2020-03-10T02:38:23.052555 | 2018-04-11T02:20:16 | 2018-04-11T02:20:16 | 129,141,488 | 1 | 0 | BSD-3-Clause | 2018-04-11T19:06:32 | 2018-04-11T19:06:31 | null | UTF-8 | C++ | false | false | 1,982 | hpp | // Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au)
// Copyright 2008-2016 National ICT Australia (NICTA)
//
// 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.
// ------------------------------------------------------------------------
//! \addtogroup cond_rel
//! @{
template<>
template<typename eT>
arma_inline
bool
cond_rel<true>::lt(const eT A, const eT B)
{
return (A < B);
}
template<>
template<typename eT>
arma_inline
bool
cond_rel<false>::lt(const eT, const eT)
{
return false;
}
template<>
template<typename eT>
arma_inline
bool
cond_rel<true>::gt(const eT A, const eT B)
{
return (A > B);
}
template<>
template<typename eT>
arma_inline
bool
cond_rel<false>::gt(const eT, const eT)
{
return false;
}
template<>
template<typename eT>
arma_inline
bool
cond_rel<true>::leq(const eT A, const eT B)
{
return (A <= B);
}
template<>
template<typename eT>
arma_inline
bool
cond_rel<false>::leq(const eT, const eT)
{
return false;
}
template<>
template<typename eT>
arma_inline
bool
cond_rel<true>::geq(const eT A, const eT B)
{
return (A >= B);
}
template<>
template<typename eT>
arma_inline
bool
cond_rel<false>::geq(const eT, const eT)
{
return false;
}
template<>
template<typename eT>
arma_inline
eT
cond_rel<true>::make_neg(const eT val)
{
return -val;
}
template<>
template<typename eT>
arma_inline
eT
cond_rel<false>::make_neg(const eT)
{
return eT(0);
}
//! @}
| [
"znation@apple.com"
] | znation@apple.com |
46abb38c9121c44e36c28fb4f163b3c1f5302a18 | f62dd59bccadd57b05a15e22ad1e6f2e382d04d0 | /include/hscpp/cmd-shell/ICmdShellTask.h | 6eced1a6a50d07a56a000b4d6e7550d060c0f285 | [
"MIT"
] | permissive | lijiansong/hscpp | e018add1f961743b4c4903174e8611f44b248a84 | 74175b028bf5dd0aa0dc8450f5251e6dfdf0e380 | refs/heads/master | 2023-05-28T23:02:19.171518 | 2021-06-16T13:42:27 | 2021-06-16T13:42:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 519 | h | #pragma once
#include <chrono>
#include <functional>
#include "hscpp/cmd-shell/ICmdShell.h"
namespace hscpp
{
class ICmdShellTask
{
public:
enum class Result
{
Success,
Failure,
};
virtual ~ICmdShellTask() = default;
virtual void Start(ICmdShell* pCmdShell,
std::chrono::milliseconds timeout,
const std::function<void(Result)>& doneCb) = 0;
virtual void Update() = 0;
};
} | [
"jheruty@gmail.com"
] | jheruty@gmail.com |
043919e24699e8faa2eeca8ab5a358c4e0085f48 | 104061c3e4d192c22bb2b6adaa97b1d66cc6da21 | /Arrays and strings/Permutation.cpp | cab0f2ae95a0232e7a3b4aa317b7746caf0ea135 | [] | no_license | vedantv/CTCI-by-Gayle-Laakmann-McDowell | 29de390261c40c7b39d42fb91b16b68cd2dfd87e | 4052af11f86c9e00306799df0e4859b6fefac817 | refs/heads/master | 2021-09-15T03:04:32.868765 | 2018-05-24T18:00:17 | 2018-05-24T18:00:17 | 123,950,480 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 618 | cpp | #include <iostream>
#include <string>
using namespace std;
int main()
{
string s1,s2;
cout<<"enter two strings"<<endl;
getline(cin,s1);
getline(cin,s2);
int l1,l2,*a;
l1=s1.length();
l2=s2.length();
if(l1!=l2)
{
cout<<"not permutation";
return 0;
}
else
{
int max=0;
for(int i=0;i<l1;i++)
{
if(max<(s1[i]-95))
{
max = s1[i]-95;
}
}
a = new int[max];
for(int i=0;i<max;i++)
{
a[i]=0;
}
for(int i=0;i<max;i++)
{
a[s1[i]-95]++;
}
for(int i=0;i<max;i++)
{
cout<<a[i]<<endl;
}
}
return 0;
}
| [
"vedant1966@gmail.com"
] | vedant1966@gmail.com |
ba761bc6b75d7c7cb2d98f7d8d9c8d772a9dad08 | 7dcdd401ce31389f7efa96d8f6a7420d42b39c38 | /ligthoj1059.cpp | 9ad7bab6aa75284aa11c14bbd1e6f69ca006cd4e | [] | no_license | ntloi95/ACM_ICPC_Codeforces | dc4449ea21fc37ba851101418cfb238b500c9afb | c97f8b9f6dea56b5e56a54acd3cabe66b5db2e7c | refs/heads/master | 2021-01-18T16:16:36.970659 | 2017-03-30T17:48:37 | 2017-03-30T17:48:37 | 86,731,723 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,822 | cpp | #include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pi pair<int, int>
#define pii pair<double, pi>
const int INF = 1000000000;
const int N = 501;
const int M = N*(N-1);
int parent[N];
int rnk[N];
vector<pii> adj;
pi point[N];
bool cmp(pii x, pii y) { return x < y; }
int n, s;
ll x, y, c;
ll weight;
ll cost;
ll cnt;
int findp(int x)
{
int root = x;
while (parent[root] != root)
{
root = parent[root];
}
while (x != parent[x])
{
int t = parent[x];
parent[x] = root;
x = t;
}
return root;
}
void join(int x, int y)
{
int px = findp(x);
int py = findp(y);
if (px != py)
{
if (rnk[px] < rnk[py])
parent[px] = py;
else if (rnk[px] > rnk[py])
parent[py] = px;
else
{
parent[py] = px;
rnk[px]++;
}
}
}
int kruskal()
{
weight = 0;
sort(adj.begin(), adj.end(), cmp);
int px, py;
for (int i = adj.size()-1; i >= 0 && s; i++)
{
x = adj[i].second.first;
y = adj[i].second.second;
c = adj[i].first;
px = findp(x);
py = findp(y);
if (px != py)
{
join(x, y);
s--;
}
}
double res = 0;
for (int i = 0; i < adj.size(); i++)
{
x = adj[i].second.first;
y = adj[i].second.second;
c = adj[i].first;
px = findp(x);
py = findp(y);
if (px != py)
{
join(x, y);
res = c;
}
}
printf("%.2lf", res);
}
int main()
{
freopen("IN.txt", "rt", stdin);
int test;
scanf("%d", &test);
for (int t = 1; t <= test; t++)
{
scanf("%d%d", &s, &n);
adj.clear();
for (int i = 0; i < n; i++)
{
scanf("%d%d", &x, &y);
point[i] = pi(x, y);
}
for (int i = 0; i < n; i++)
for (int j = i+1; j < n; j++)
{
pi p1 = point[i];
pi p2 = point[j];
adj.push_back(pii(hypot(p1.first - p2.first, p1.second - p2.second), pi(i,j)));
}
kruskal();
}
return 0;
} | [
"ntloi95@gmail.com"
] | ntloi95@gmail.com |
ce62f1333d84af00e2b007f77fe6fafc0a696be5 | 1bef5376cb108e3caa2d2972635d0b514eef7a09 | /source/GUI2.cpp | e984e9e69465c248b88930869e113ef5be9ca08e | [] | no_license | Xirious/RisenSDK2 | 711c4cf7eb35ef21ed5ba5d1e28af5e9d9ca95da | 6fb1f08d0b71a3295a359e6f683f43420efb1f1b | refs/heads/master | 2021-01-20T05:02:26.610373 | 2017-01-19T09:28:55 | 2017-01-19T09:28:55 | 101,413,235 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 114 | cpp | #include "GUI2.h"
namespace Linker
{
namespace Warning
{
char Disable4221_GUI2;
}
}
| [
"nicode@1f35f6f1-ac98-46d3-9b0a-30c6b533b274"
] | nicode@1f35f6f1-ac98-46d3-9b0a-30c6b533b274 |
c381e2caa543f8cb9e6e667ba87782279f13face | 1ca9954b6b1d180ac5ef11dc9a086893d8f37db0 | /icedrifter/ds18b20.cpp | 46dd9d92befb19f4757ef1473d606e78114ece5e | [] | no_license | tgidave/icedrifter | 733fffecc35b91f1775ca0de1301582b4135accb | afd26066d6c3fca572b44e8989e584bb74cf6064 | refs/heads/master | 2021-08-17T02:34:00.396872 | 2020-04-15T21:14:16 | 2020-04-15T21:14:16 | 160,993,728 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 945 | cpp | #include <OneWire.h>
#include <DallasTemperature.h>
#include "icedrifter.h"
#include "ds18b20.h"
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(& oneWire);
float getRemoteTemp(icedrifterData* idData) {
// pinMode(DS18B20_POWER_PIN, OUTPUT);
digitalWrite(DS18B20_POWER_PIN, HIGH);
delay(1000);
//Start the Library.
sensors.begin();
#ifdef SERIAL_DEBUG_DS18B20
DEBUG_SERIAL.print(F("Requesting DS18B20 temperatures...\n"));
#endif
sensors.requestTemperatures(); // Send the command to get temperature readings
idData->idRemoteTemp = sensors.getTempCByIndex(0);
#ifdef SERIAL_DEBUG_DS18B20
DEBUG_SERIAL.print(F("Remote temperature is "));
DEBUG_SERIAL.print(idData->idRemoteTemp);
DEBUG_SERIAL.print(F(" C\n"));
if (idData->idRemoteTemp == -127) {
DEBUG_SERIAL.print(F("Error: Disconnected!!!\n"));
} else {
DEBUG_SERIAL.print(F("Done!\n"));
}
#endif
digitalWrite(DS18B20_POWER_PIN, LOW);
}
| [
"dave@tgi.com"
] | dave@tgi.com |
d4257c9f5c32ee901682562f11a549cff036dda5 | d4d7f63398c19eaad2b8e043a06bc1b9bfe88e94 | /dao.cpp | b6fdba8f72ae962896ec2cee78ff2e75a379df19 | [] | no_license | DinnerForBreakfast/supermacrobot | 3fa5bdf2c7562698148a034f3d094de1eb785e88 | 52d799377369f095d138e53d1c62a2ed619d91b8 | refs/heads/master | 2021-01-21T06:48:58.699585 | 2013-08-15T05:49:22 | 2013-08-15T05:49:22 | 91,586,387 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 560 | cpp | #include "dao.h"
#include "QDebug"
DAO::DAO(QString path, QString type, QObject *parent) :
QObject(parent)
{
db = QSqlDatabase::addDatabase(type);
db.setDatabaseName(path);
if (!db.open()) {
qDebug("Failed to create database ");
qDebug() << path;
}else{
QSqlQuery query("SELECT name FROM sqlite_master WHERE type='table'", db);
query.exec();
if(!query.next()){
initDatabase();
initQueries();
}
}
}
DAO::~DAO()
{
if(db.isOpen()){
db.close();
}
}
bool DAO::initDatabase(){
return true;
}
bool DAO::initQueries(){
return true;
}
| [
"josh@josh-Kubuntu.(none)"
] | josh@josh-Kubuntu.(none) |
4c01d0fb136a28cecdaa270574690a17a707a72e | 529e42ee99c3fdc59803aab8b2bcf32ae04c2ba1 | /inheritanceZoo/inheritanceZoo/main.cpp | bf65e1b7ba2c6059ca9d76a4773dcf8c1ba83edf | [] | no_license | theosfa/inheritanceZoo | 06530a368c673c25739e4c0ee1596b90e617c9e8 | 5ffcb11d90b5219b1ae789d2be4540d897243277 | refs/heads/master | 2023-01-02T12:56:28.501162 | 2020-10-27T09:16:20 | 2020-10-27T09:16:20 | 306,601,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 220 | cpp | //
// main.cpp
// inheritanceZoo
//
// Created by Fedor on 27/10/2020.
//
#include <iostream>
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
| [
"theos.fa@gmail.com"
] | theos.fa@gmail.com |
ca2388ac442f424bfbc03ea55ea15531c43b73ad | 1f6ed4c03ed117f3440f3d48c95d4a0c3a70ebbd | /YAPOG.Test/test_chat.cpp | caf884d0d7a32c173f31579531d36f64c24d2300 | [] | no_license | hackerlank/YAPOG | d2aa8b1dcc9231049bd8a5d27107c9cc32616094 | 93f5a9d00b14ae1343ff5666617ffc1b14c87ec2 | refs/heads/master | 2020-06-13T09:40:57.312506 | 2013-04-23T11:03:24 | 2013-04-23T11:03:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 458 | cpp | #include "YAPOG/Game/Chat/ChatHeader.hpp"
#include "YAPOG/Game/Chat/Chat.hpp"
#include "YAPOG/Game/Chat/ChatDisplayer.hpp"
#include "YAPOG/System/IntTypes.hpp"
int main()
{
std::string line = "";
yap::Chat mychat;
while (true)
{
while (line.compare ("") == 0)
std::getline (std::cin, line);
if (line.compare ("exit") == 0)
break;
mychat.SetBuf (line);
mychat.Parse ();
mychat.Exec ();
line = "";
}
return EXIT_SUCCESS;
} | [
"franck.ly@epita.fr"
] | franck.ly@epita.fr |
8eded28f7ba7b32f969c97c454531c1027cbcf1d | 385f8eca3787451f83dcc55fa758c98491e4cf28 | /libs/webrtc/include/common_types.h | 4a760509634c710cdeaf8b2fca21bbe362238e5a | [
"MIT"
] | permissive | jomael/AudioMixer | e5337a3bab9f8efb173217bd793a61b04856eb32 | cfdd19b0d56418f9bf37164429a248f075a0751a | refs/heads/master | 2021-11-20T16:27:57.454387 | 2021-08-08T21:29:57 | 2021-08-08T21:29:57 | 148,709,153 | 0 | 0 | MIT | 2020-04-25T23:48:18 | 2018-09-13T23:21:37 | C++ | UTF-8 | C++ | false | false | 14,816 | h | /*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef COMMON_TYPES_H_
#define COMMON_TYPES_H_
#include <stddef.h>
#include <string.h>
#include <string>
#include <vector>
#include "api/array_view.h"
#include "api/optional.h"
// TODO(sprang): Remove this include when all usage includes it directly.
#include "api/video/video_bitrate_allocation.h"
#include "rtc_base/checks.h"
#include "rtc_base/deprecation.h"
#include "typedefs.h" // NOLINT(build/include)
#if defined(_MSC_VER)
// Disable "new behavior: elements of array will be default initialized"
// warning. Affects OverUseDetectorOptions.
#pragma warning(disable : 4351)
#endif
#define RTP_PAYLOAD_NAME_SIZE 32u
#if defined(WEBRTC_WIN) || defined(WIN32)
// Compares two strings without regard to case.
#define STR_CASE_CMP(s1, s2) ::_stricmp(s1, s2)
// Compares characters of two strings without regard to case.
#define STR_NCASE_CMP(s1, s2, n) ::_strnicmp(s1, s2, n)
#else
#define STR_CASE_CMP(s1, s2) ::strcasecmp(s1, s2)
#define STR_NCASE_CMP(s1, s2, n) ::strncasecmp(s1, s2, n)
#endif
namespace webrtc {
enum FrameType {
kEmptyFrame = 0,
kAudioFrameSpeech = 1,
kAudioFrameCN = 2,
kVideoFrameKey = 3,
kVideoFrameDelta = 4,
};
// Statistics for an RTCP channel
struct RtcpStatistics {
RtcpStatistics()
: fraction_lost(0),
packets_lost(0),
extended_highest_sequence_number(0),
jitter(0) {}
uint8_t fraction_lost;
union {
int32_t packets_lost; // Defined as a 24 bit signed integer in RTCP
RTC_DEPRECATED uint32_t cumulative_lost;
};
union {
uint32_t extended_highest_sequence_number;
RTC_DEPRECATED uint32_t extended_max_sequence_number;
};
uint32_t jitter;
};
class RtcpStatisticsCallback {
public:
virtual ~RtcpStatisticsCallback() {}
virtual void StatisticsUpdated(const RtcpStatistics& statistics,
uint32_t ssrc) = 0;
virtual void CNameChanged(const char* cname, uint32_t ssrc) = 0;
};
// Statistics for RTCP packet types.
struct RtcpPacketTypeCounter {
RtcpPacketTypeCounter()
: first_packet_time_ms(-1),
nack_packets(0),
fir_packets(0),
pli_packets(0),
nack_requests(0),
unique_nack_requests(0) {}
void Add(const RtcpPacketTypeCounter& other) {
nack_packets += other.nack_packets;
fir_packets += other.fir_packets;
pli_packets += other.pli_packets;
nack_requests += other.nack_requests;
unique_nack_requests += other.unique_nack_requests;
if (other.first_packet_time_ms != -1 &&
(other.first_packet_time_ms < first_packet_time_ms ||
first_packet_time_ms == -1)) {
// Use oldest time.
first_packet_time_ms = other.first_packet_time_ms;
}
}
void Subtract(const RtcpPacketTypeCounter& other) {
nack_packets -= other.nack_packets;
fir_packets -= other.fir_packets;
pli_packets -= other.pli_packets;
nack_requests -= other.nack_requests;
unique_nack_requests -= other.unique_nack_requests;
if (other.first_packet_time_ms != -1 &&
(other.first_packet_time_ms > first_packet_time_ms ||
first_packet_time_ms == -1)) {
// Use youngest time.
first_packet_time_ms = other.first_packet_time_ms;
}
}
int64_t TimeSinceFirstPacketInMs(int64_t now_ms) const {
return (first_packet_time_ms == -1) ? -1 : (now_ms - first_packet_time_ms);
}
int UniqueNackRequestsInPercent() const {
if (nack_requests == 0) {
return 0;
}
return static_cast<int>((unique_nack_requests * 100.0f / nack_requests) +
0.5f);
}
int64_t first_packet_time_ms; // Time when first packet is sent/received.
uint32_t nack_packets; // Number of RTCP NACK packets.
uint32_t fir_packets; // Number of RTCP FIR packets.
uint32_t pli_packets; // Number of RTCP PLI packets.
uint32_t nack_requests; // Number of NACKed RTP packets.
uint32_t unique_nack_requests; // Number of unique NACKed RTP packets.
};
class RtcpPacketTypeCounterObserver {
public:
virtual ~RtcpPacketTypeCounterObserver() {}
virtual void RtcpPacketTypesCounterUpdated(
uint32_t ssrc,
const RtcpPacketTypeCounter& packet_counter) = 0;
};
// Callback, used to notify an observer whenever new rates have been estimated.
class BitrateStatisticsObserver {
public:
virtual ~BitrateStatisticsObserver() {}
virtual void Notify(uint32_t total_bitrate_bps,
uint32_t retransmit_bitrate_bps,
uint32_t ssrc) = 0;
};
struct FrameCounts {
FrameCounts() : key_frames(0), delta_frames(0) {}
int key_frames;
int delta_frames;
};
// Callback, used to notify an observer whenever frame counts have been updated.
class FrameCountObserver {
public:
virtual ~FrameCountObserver() {}
virtual void FrameCountUpdated(const FrameCounts& frame_counts,
uint32_t ssrc) = 0;
};
// Callback, used to notify an observer whenever the send-side delay is updated.
class SendSideDelayObserver {
public:
virtual ~SendSideDelayObserver() {}
virtual void SendSideDelayUpdated(int avg_delay_ms,
int max_delay_ms,
uint32_t ssrc) = 0;
};
// Callback, used to notify an observer whenever a packet is sent to the
// transport.
// TODO(asapersson): This class will remove the need for SendSideDelayObserver.
// Remove SendSideDelayObserver once possible.
class SendPacketObserver {
public:
virtual ~SendPacketObserver() {}
virtual void OnSendPacket(uint16_t packet_id,
int64_t capture_time_ms,
uint32_t ssrc) = 0;
};
// Callback, used to notify an observer when the overhead per packet
// has changed.
class OverheadObserver {
public:
virtual ~OverheadObserver() = default;
virtual void OnOverheadChanged(size_t overhead_bytes_per_packet) = 0;
};
// ==================================================================
// Voice specific types
// ==================================================================
// Each codec supported can be described by this structure.
struct CodecInst {
int pltype;
char plname[RTP_PAYLOAD_NAME_SIZE];
int plfreq;
int pacsize;
size_t channels;
int rate; // bits/sec unlike {start,min,max}Bitrate elsewhere in this file!
bool operator==(const CodecInst& other) const {
return pltype == other.pltype &&
(STR_CASE_CMP(plname, other.plname) == 0) &&
plfreq == other.plfreq && pacsize == other.pacsize &&
channels == other.channels && rate == other.rate;
}
bool operator!=(const CodecInst& other) const { return !(*this == other); }
};
// RTP
enum { kRtpCsrcSize = 15 }; // RFC 3550 page 13
// NETEQ statistics.
struct NetworkStatistics {
// current jitter buffer size in ms
uint16_t currentBufferSize;
// preferred (optimal) buffer size in ms
uint16_t preferredBufferSize;
// adding extra delay due to "peaky jitter"
bool jitterPeaksFound;
// Stats below correspond to similarly-named fields in the WebRTC stats spec.
// https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats
uint64_t totalSamplesReceived;
uint64_t concealedSamples;
uint64_t concealmentEvents;
uint64_t jitterBufferDelayMs;
// Stats below DO NOT correspond directly to anything in the WebRTC stats
// Loss rate (network + late); fraction between 0 and 1, scaled to Q14.
uint16_t currentPacketLossRate;
// Late loss rate; fraction between 0 and 1, scaled to Q14.
union {
RTC_DEPRECATED uint16_t currentDiscardRate;
};
// fraction (of original stream) of synthesized audio inserted through
// expansion (in Q14)
uint16_t currentExpandRate;
// fraction (of original stream) of synthesized speech inserted through
// expansion (in Q14)
uint16_t currentSpeechExpandRate;
// fraction of synthesized speech inserted through pre-emptive expansion
// (in Q14)
uint16_t currentPreemptiveRate;
// fraction of data removed through acceleration (in Q14)
uint16_t currentAccelerateRate;
// fraction of data coming from secondary decoding (in Q14)
uint16_t currentSecondaryDecodedRate;
// Fraction of secondary data, including FEC and RED, that is discarded (in
// Q14). Discarding of secondary data can be caused by the reception of the
// primary data, obsoleting the secondary data. It can also be caused by early
// or late arrival of secondary data.
uint16_t currentSecondaryDiscardedRate;
// clock-drift in parts-per-million (negative or positive)
int32_t clockDriftPPM;
// average packet waiting time in the jitter buffer (ms)
int meanWaitingTimeMs;
// median packet waiting time in the jitter buffer (ms)
int medianWaitingTimeMs;
// min packet waiting time in the jitter buffer (ms)
int minWaitingTimeMs;
// max packet waiting time in the jitter buffer (ms)
int maxWaitingTimeMs;
// added samples in off mode due to packet loss
size_t addedSamples;
};
// Statistics for calls to AudioCodingModule::PlayoutData10Ms().
struct AudioDecodingCallStats {
AudioDecodingCallStats()
: calls_to_silence_generator(0),
calls_to_neteq(0),
decoded_normal(0),
decoded_plc(0),
decoded_cng(0),
decoded_plc_cng(0),
decoded_muted_output(0) {}
int calls_to_silence_generator; // Number of calls where silence generated,
// and NetEq was disengaged from decoding.
int calls_to_neteq; // Number of calls to NetEq.
int decoded_normal; // Number of calls where audio RTP packet decoded.
int decoded_plc; // Number of calls resulted in PLC.
int decoded_cng; // Number of calls where comfort noise generated due to DTX.
int decoded_plc_cng; // Number of calls resulted where PLC faded to CNG.
int decoded_muted_output; // Number of calls returning a muted state output.
};
// ==================================================================
// Video specific types
// ==================================================================
// TODO(nisse): Delete, and switch to fourcc values everywhere?
// Supported video types.
enum class VideoType {
kUnknown,
kI420,
kIYUV,
kRGB24,
kABGR,
kARGB,
kARGB4444,
kRGB565,
kARGB1555,
kYUY2,
kYV12,
kUYVY,
kMJPEG,
kNV21,
kNV12,
kBGRA,
};
// TODO(magjed): Move this and other H264 related classes out to their own file.
namespace H264 {
enum Profile {
kProfileConstrainedBaseline,
kProfileBaseline,
kProfileMain,
kProfileConstrainedHigh,
kProfileHigh,
};
} // namespace H264
// Video codec types
enum VideoCodecType {
// There are various memset(..., 0, ...) calls in the code that rely on
// kVideoCodecUnknown being zero.
kVideoCodecUnknown = 0,
kVideoCodecVP8,
kVideoCodecVP9,
kVideoCodecH264,
kVideoCodecI420,
kVideoCodecGeneric,
kVideoCodecMultiplex,
// TODO(nisse): Deprecated aliases, for code expecting RtpVideoCodecTypes.
kRtpVideoNone = kVideoCodecUnknown,
kRtpVideoGeneric = kVideoCodecGeneric,
kRtpVideoVp8 = kVideoCodecVP8,
kRtpVideoVp9 = kVideoCodecVP9,
kRtpVideoH264 = kVideoCodecH264,
};
// Translates from name of codec to codec type and vice versa.
const char* CodecTypeToPayloadString(VideoCodecType type);
VideoCodecType PayloadStringToCodecType(const std::string& name);
struct SpatialLayer {
bool operator==(const SpatialLayer& other) const;
bool operator!=(const SpatialLayer& other) const { return !(*this == other); }
unsigned short width;
unsigned short height;
unsigned char numberOfTemporalLayers;
unsigned int maxBitrate; // kilobits/sec.
unsigned int targetBitrate; // kilobits/sec.
unsigned int minBitrate; // kilobits/sec.
unsigned int qpMax; // minimum quality
bool active; // encoded and sent.
};
// Simulcast is when the same stream is encoded multiple times with different
// settings such as resolution.
typedef SpatialLayer SimulcastStream;
// TODO(sprang): Remove this when downstream projects have been updated.
using BitrateAllocation = VideoBitrateAllocation;
// Bandwidth over-use detector options. These are used to drive
// experimentation with bandwidth estimation parameters.
// See modules/remote_bitrate_estimator/overuse_detector.h
// TODO(terelius): This is only used in overuse_estimator.cc, and only in the
// default constructed state. Can we move the relevant variables into that
// class and delete this? See also disabled warning at line 27
struct OverUseDetectorOptions {
OverUseDetectorOptions()
: initial_slope(8.0 / 512.0),
initial_offset(0),
initial_e(),
initial_process_noise(),
initial_avg_noise(0.0),
initial_var_noise(50) {
initial_e[0][0] = 100;
initial_e[1][1] = 1e-1;
initial_e[0][1] = initial_e[1][0] = 0;
initial_process_noise[0] = 1e-13;
initial_process_noise[1] = 1e-3;
}
double initial_slope;
double initial_offset;
double initial_e[2][2];
double initial_process_noise[2];
double initial_avg_noise;
double initial_var_noise;
};
// This structure will have the information about when packet is actually
// received by socket.
struct PacketTime {
PacketTime() : timestamp(-1), not_before(-1) {}
PacketTime(int64_t timestamp, int64_t not_before)
: timestamp(timestamp), not_before(not_before) {}
int64_t timestamp; // Receive time after socket delivers the data.
int64_t not_before; // Earliest possible time the data could have arrived,
// indicating the potential error in the |timestamp|
// value,in case the system is busy.
// For example, the time of the last select() call.
// If unknown, this value will be set to zero.
};
// Minimum and maximum playout delay values from capture to render.
// These are best effort values.
//
// A value < 0 indicates no change from previous valid value.
//
// min = max = 0 indicates that the receiver should try and render
// frame as soon as possible.
//
// min = x, max = y indicates that the receiver is free to adapt
// in the range (x, y) based on network jitter.
//
// Note: Given that this gets embedded in a union, it is up-to the owner to
// initialize these values.
struct PlayoutDelay {
int min_ms;
int max_ms;
};
} // namespace webrtc
#endif // COMMON_TYPES_H_
| [
"xz4215@gmail.com"
] | xz4215@gmail.com |
fd8d8ff3dac63a08199b31c92b7a58376827dce7 | 5902fa0857cd4f722a9663bbd61aa0895b9f8dea | /BMIG-5101-SequencesAsBioInformation/Blast/ncbi-blast-2.10.0+-src/c++/include/corelib/expr.hpp | 8221a5a140e5d779a52f310f62595e22216d8a7e | [] | no_license | thegrapesofwrath/spring-2020 | 1b38d45fa44fcdc78dcecfb3b221107b97ceff9c | f90fcde64d83c04e55f9b421d20f274427cbe1c8 | refs/heads/main | 2023-01-23T13:35:05.394076 | 2020-12-08T21:40:42 | 2020-12-08T21:40:42 | 319,763,280 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 130 | hpp | version https://git-lfs.github.com/spec/v1
oid sha256:07aadac064879e065507e724ef17441ce0261f3c1fa23377b406263c3efed8c2
size 11479
| [
"shawn-hartley@sbcglobal.net"
] | shawn-hartley@sbcglobal.net |
5512885fe85d708551e97c77f017cdd8e586abdc | 94efad5022098a59e827dac0d1cef509b8ec3913 | /src/component.cpp | 9bc47d3b00df7b54f3d319124e86b443e56444c8 | [
"MIT"
] | permissive | skrimpon/phycad | 159a65ccd1c38e7337c9bb1846ebe9c1ef9a5982 | 92430c92671603fe2dfbd18ed38d00e0ec543ade | refs/heads/master | 2021-05-11T20:33:48.975836 | 2018-05-08T13:38:09 | 2018-05-08T13:38:09 | 117,440,598 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 229 | cpp | #include "component.h"
Component::Component(const std::string& name) : _name(name)
{
_rgb[0] = (float)(rand())/RAND_MAX;
_rgb[1] = (float)(rand())/RAND_MAX;
_rgb[2] = (float)(rand())/RAND_MAX;
}
Component::~Component()
{
} | [
"panagiotis.skrimponis@Panagiotis-Skrimponis-MacBook-Pro-2295.local"
] | panagiotis.skrimponis@Panagiotis-Skrimponis-MacBook-Pro-2295.local |
aa345e021377157ad0e2127ffecc0c353d9b7bfd | 794ec36417d1f5fe9f8a8dfefee17169ba346447 | /CodeForces/831A/9610814_AC_31ms_2052kB.cpp | c56389f95bd9288dd0d8ebf357f7aa151af74efe | [] | no_license | riba2534/My_ACM_Code | 1d2f7dacb50f7e9ed719484419b3a7a41ba407cf | fa914ca98ad0794073bc1ccac8ab7dca4fe13f25 | refs/heads/master | 2020-03-24T01:19:19.889558 | 2019-03-11T03:01:09 | 2019-03-11T03:01:09 | 142,331,120 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 964 | cpp | //#include <cstdio>
//#include <cstring>
//#include <cctype>
//#include <string>
//#include <set>
//#include <iostream>
//#include <stack>
//#include <cmath>
//#include <queue>
//#include <vector>
//#include <algorithm>
//#define mem(a,b) memset(a,b,sizeof(a))
//#define inf 0x3f3f3f3f
//#define mod 1000007
//#define N 8
//#define M 12357
//#define ll long long
//using namespace std;
#include<cstdio>
#include<iostream>
using namespace std;
const int N = 105;
int a[N];
int n,maxn = 1;
bool check()
{
for(int i = 1;i <= n;i++)
{
if(a[i] == maxn)
{
for(int j = i-1;j >= 1;j--)
if(a[j] >= a[j+1])
return false;
while(a[i] == maxn && i <= n)
i++;
for(int j = i;j <= n;j++)
if(a[j-1] <= a[j] || a[j] >= maxn)
return false;
break;
}
}
return true;
}
int main()
{
cin >> n;
for(int i = 1;i <= n;i++)
cin >> a[i],maxn = max(a[i],maxn);
if(check())
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
| [
"riba2534@qq.com"
] | riba2534@qq.com |
c349e96e31b7e3d008664fd4bd044310d8788329 | 6b322e561f5d6be8281b08e7c71321bbad47ff07 | /src/alignment.cpp | 80d1622fdac53d48ca342ae54f562064266d9cab | [
"MIT"
] | permissive | isovic/spoa | ac97839dc0b4b74704d4ab60ef74649b59e9863c | d8086df3392260a0830c6a20398516f43b50bf77 | refs/heads/master | 2021-01-17T20:03:05.113424 | 2016-04-04T08:21:21 | 2016-04-04T08:21:21 | 55,397,817 | 0 | 0 | null | 2016-04-04T09:05:12 | 2016-04-04T09:05:11 | null | UTF-8 | C++ | false | false | 10,434 | cpp | /*!
* @file alignment.cpp
*
* @brief Alignment class source file
*/
#include <limits>
#include <algorithm>
#include "node.hpp"
#include "edge.hpp"
#include "graph.hpp"
#include "alignment.hpp"
AlignmentParams::AlignmentParams(int16_t m, int16_t mm, int16_t gap_opn,
int16_t gap_ext, AlignmentType t) :
match(m), mismatch(mm), insertion_open(gap_opn), insertion_extend(gap_ext),
deletion_open(gap_opn), deletion_extend(gap_ext), type(t) {
assert(type == AlignmentType::kNW || type == AlignmentType::kSW || type == AlignmentType::kOV);
}
AlignmentParams::AlignmentParams(int16_t m, int16_t mm, int16_t ins_opn,
int16_t ins_ext, int16_t del_opn, int16_t del_ext, AlignmentType t) :
match(m), mismatch(mm), insertion_open(ins_opn), insertion_extend(ins_ext),
deletion_open(del_opn), deletion_extend(del_ext), type(t) {
assert(type == AlignmentType::kNW || type == AlignmentType::kSW || type == AlignmentType::kOV);
}
AlignmentParams::~AlignmentParams() {
}
std::unique_ptr<Alignment> createAlignment(const std::string& sequence,
std::shared_ptr<Graph> graph, AlignmentParams params) {
assert(sequence.size() != 0);
return std::unique_ptr<Alignment>(new Alignment(sequence, graph,
std::move(params)));
}
Alignment::Alignment(const std::string& sequence, std::shared_ptr<Graph> graph,
AlignmentParams params) :
sequence_profile_(256), graph_(graph), params_(std::move(params)),
matrix_width_(sequence.size() + 1),
matrix_height_(graph->nodes().size() + 1),
H_(matrix_width_ * matrix_height_, 0),
F_(matrix_width_ * matrix_height_, 0),
E_(matrix_width_ * matrix_height_, 0),
is_aligned_(false),
max_i_(-1), max_j_(-1), max_score_(0),
node_id_to_graph_id_(),
is_backtracked_(false),
alignment_node_ids_(),
alignment_seq_ids_() {
for (const auto& c: graph->alphabet()) {
sequence_profile_[c].reserve(sequence.size());
for (const auto& s: sequence) {
sequence_profile_[c].push_back(c == s ? params_.match : params_.mismatch);
}
}
int32_t big_negative_value = std::numeric_limits<int32_t>::min() + 1000;
for (uint32_t j = 1; j < matrix_width_; ++j) {
F_[j] = big_negative_value;
}
for (uint32_t i = 1; i < matrix_height_; ++i) {
E_[i * matrix_width_] = big_negative_value;
}
graph_->topological_sort();
const auto& sorted_nodes_ids = graph_->sorted_nodes_ids();
node_id_to_graph_id_.resize(sorted_nodes_ids.size());
for (uint32_t i = 0; i < sorted_nodes_ids.size(); ++i) {
node_id_to_graph_id_[sorted_nodes_ids[i]] = i;
}
if (params_.type == AlignmentType::kNW) {
max_score_ = big_negative_value;
for (uint32_t j = 1; j < matrix_width_; ++j) {
H_[j] = params_.insertion_open + (j - 1) * params_.insertion_extend;
E_[j] = H_[j];
}
for (uint32_t node_id: sorted_nodes_ids) {
const auto& node = graph_->node(node_id);
uint32_t i = node_id_to_graph_id_[node_id] + 1;
if (node->in_edges().size() == 0) {
H_[i * matrix_width_] = params_.deletion_open;
} else {
int32_t max_score = big_negative_value;
for (const auto& edge: node->in_edges()) {
uint32_t pred_i = node_id_to_graph_id_[edge->begin_node_id()] + 1;
max_score = std::max(max_score, H_[pred_i * matrix_width_]);
}
H_[i * matrix_width_] = max_score + params_.deletion_extend;
}
F_[i * matrix_width_] = H_[i * matrix_width_];
}
}
// print_matrix();
}
Alignment::~Alignment() {
}
void Alignment::align_sequence_to_graph() {
if (is_aligned_ == true) {
return;
}
graph_->topological_sort();
const auto& sorted_nodes_ids = graph_->sorted_nodes_ids();
for (uint32_t node_id: sorted_nodes_ids) {
const auto& node = graph_->node(node_id);
const auto& char_profile = sequence_profile_[node->letter()];
uint32_t i = node_id_to_graph_id_[node_id] + 1;
int32_t* H_row = &H_[i * matrix_width_];
int32_t* F_row = &F_[i * matrix_width_];
uint32_t pred_i = node->in_edges().empty() ? 0 :
node_id_to_graph_id_[node->in_edges().front()->begin_node_id()] + 1;
int32_t* H_pred_row = &H_[pred_i * matrix_width_];
int32_t* F_pred_row = &F_[pred_i * matrix_width_];
for (uint32_t j = 1; j < matrix_width_; ++j) {
// update F
F_row[j] = std::max(H_pred_row[j] + params_.insertion_open, F_pred_row[j] + params_.insertion_extend);
// update H
H_row[j] = std::max(H_pred_row[j - 1] + char_profile[j - 1], F_row[j]);
}
// check other predeccessors
for (uint32_t p = 1; p < node->in_edges().size(); ++p) {
pred_i = node_id_to_graph_id_[node->in_edges()[p]->begin_node_id()] + 1;
H_pred_row = &H_[pred_i * matrix_width_];
F_pred_row = &F_[pred_i * matrix_width_];
for (uint32_t j = 1; j < matrix_width_; ++j) {
// update F
F_row[j] = std::max(F_row[j], std::max(H_pred_row[j] + params_.insertion_open, F_pred_row[j] + params_.insertion_extend));
// update H
H_row[j] = std::max(H_row[j], std::max(H_pred_row[j - 1] + char_profile[j - 1], F_row[j]));
}
}
int32_t* E_row = &E_[i * matrix_width_];
for (uint32_t j = 1; j < matrix_width_; ++j) {
// update E
E_row[j] = std::max(H_row[j - 1] + params_.deletion_open, E_row[j - 1] + params_.deletion_extend);
// update H
H_row[j] = std::max(H_row[j], E_row[j]);
if (params_.type == AlignmentType::kSW) {
H_row[j] = std::max(H_row[j], 0);
update_max_score(H_row, i, j);
} else if (params_.type == AlignmentType::kNW) {
if (j == matrix_width_ - 1 && node->out_edges().size() == 0) {
update_max_score(H_row, i, j);
}
} else if (params_.type == AlignmentType::kOV) {
if (j == matrix_width_ - 1 || node->out_edges().size() == 0) {
update_max_score(H_row, i, j);
}
}
}
}
is_aligned_ = true;
// print_matrix();
}
int32_t Alignment::score() const {
assert(is_aligned_ == true && "No alignment done!");
return max_score_;
}
void Alignment::backtrack() {
if (is_backtracked_ == true) {
return;
}
assert(is_aligned_ == true && "No alignment done!");
if (max_i_ == -1 && max_j_ == -1) { // no alignment found
is_backtracked_ = true;
return;
}
uint32_t i = max_i_;
uint32_t j = max_j_;
auto sw_condition = [&]() { return (H_[i * matrix_width_ + j] == 0) ? false : true; };
auto nw_condition = [&]() { return (i == 0 && j == 0) ? false : true; };
auto ov_condition = [&]() { return (i == 0 || j == 0) ? false : true; };
const auto& graph_id_to_node_id = graph_->sorted_nodes_ids();
uint32_t prev_i = 0, prev_j = 0;
while ((params_.type == AlignmentType::kSW && sw_condition()) ||
(params_.type == AlignmentType::kNW && nw_condition()) ||
(params_.type == AlignmentType::kOV && ov_condition())) {
// bloody backtrack
auto H_ij = H_[i * matrix_width_ + j];
bool predecessor_found = false;
if (i != 0) {
const auto& node = graph_->node(graph_id_to_node_id[i - 1]);
int32_t match_cost = j != 0 ? sequence_profile_[node->letter()][j - 1] : 0;
uint32_t pred_i = node->in_edges().empty() ? 0 :
node_id_to_graph_id_[node->in_edges().front()->begin_node_id()] + 1;
if (j != 0 && H_ij == H_[pred_i * matrix_width_ + (j - 1)] + match_cost) {
prev_i = pred_i;
prev_j = j - 1;
predecessor_found = true;
} else if ((H_ij == F_[pred_i * matrix_width_ + j] + params_.insertion_extend) ||
(H_ij == H_[pred_i * matrix_width_ + j] + params_.insertion_open)) {
prev_i = pred_i;
prev_j = j;
predecessor_found = true;
}
if (!predecessor_found) {
const auto& edges = node->in_edges();
for (uint32_t p = 1; p < edges.size(); ++p) {
uint32_t pred_i = node_id_to_graph_id_[edges[p]->begin_node_id()] + 1;
if (j != 0 && H_ij == H_[pred_i * matrix_width_ + (j - 1)] + match_cost) {
prev_i = pred_i;
prev_j = j - 1;
predecessor_found = true;
break;
}
if ((H_ij == F_[pred_i * matrix_width_ + j] + params_.insertion_extend) ||
(H_ij == H_[pred_i * matrix_width_ + j] + params_.insertion_open)){
prev_i = pred_i;
prev_j = j;
predecessor_found = true;
break;
}
}
}
}
if (!predecessor_found && H_ij == E_[i * matrix_width_ + j]) {
prev_i = i;
prev_j = j - 1;
}
alignment_node_ids_.emplace_back(i == prev_i ? -1 : graph_id_to_node_id[i - 1]);
alignment_seq_ids_.emplace_back(j == prev_j ? -1 : j - 1);
i = prev_i;
j = prev_j;
}
std::reverse(alignment_node_ids_.begin(), alignment_node_ids_.end());
std::reverse(alignment_seq_ids_.begin(), alignment_seq_ids_.end());
is_backtracked_ = true;
}
inline void Alignment::update_max_score(int32_t* H_row, uint32_t i, uint32_t j) {
if (max_score_ < H_row[j]) {
max_score_ = H_row[j];
max_i_ = i;
max_j_ = j;
}
}
void Alignment::print_matrix() {
for (uint32_t i = 0; i < matrix_height_; ++i) {
for (uint32_t j = 0; j < matrix_width_; ++j) {
printf("(%3d %3d %3d) ", H_[i * matrix_width_ + j],
E_[i * matrix_width_ + j], F_[i * matrix_width_ + j]);
}
printf("\n");
}
printf("\n");
}
| [
"robert.vaser@gmail.com"
] | robert.vaser@gmail.com |
a20fb02aea289466a62057cb6cc17b1a22b0ad77 | e1fac2cb6c5ed63970f2b6db6ed86f6c30a7eb63 | /audme21.cp | 03dfdeb96c2029d6ca0815f7d2695fbb49ab7c57 | [] | no_license | malev/Adume | dc2af4a751cc812a1b78593764fb5cde1ca681ed | 114f0ffa684b3be5b6cffec11141f922b8517f9b | refs/heads/master | 2020-06-03T20:58:28.926859 | 2009-05-16T15:36:59 | 2009-05-16T15:36:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,679 | cp | #line 1 "C:/Documents and Settings/Administrador/Escritorio/Software/030309_d/Proyectos_4013/audme21.c"
#line 9 "C:/Documents and Settings/Administrador/Escritorio/Software/030309_d/Proyectos_4013/audme21.c"
int Samples[256] absolute 0x0C00;
int Samples2[128];
int impulsos[25];
int indices[10];
short flag = 0;
unsigned Adrr = 0;
void MostrarDatos(short modo);
void Segundos(unsigned cantidad);
unsigned ReadAdc();
void CargarDatos(short f);
short EncontrarFc();
float Fract2Float(int input);
void Derivando(void);
int tipo(short ini, short fin, short T);
short Promediar(short T);
short encontrar_pico(short inicio, short T);
void CalculoIndices(short dir, short freq);
void GuardarDatos(short modo);
void Formatear (void);
void REeprom(char Adrr1, char Adrr0);
void WEeprom(char Adrr1, char Adrr0);
char LeerByte(char Adrr1, char Adrr0);
void EscribirByte(char Adrr1, char Adrr0, unsigned int dato);
short IntToShort(int valor16);
void TextToUart(unsigned char *m);
void EnviarByte(unsigned dato);
void NewLine();
void EnviarBloque(char *m);
void EnviarDatos(void);
void InitAdc();
void InitLCD();
void InitConfig();
void Generar_Senal(short modo){
unsigned i=0;
unsigned arg;
unsigned temp;
while(i<256){
arg = 360 * 0.02 * i;
temp = 1.1 * SinE3(1.5 * arg) + 0.95 * SinE3(3 * arg) + 0.2 * SinE3(4.5 * arg);
if (modo == 2) temp = 1.1 * SinE3(1.9 * arg) + 0.95 * SinE3(3 * arg) + 0.2 * SinE3(4.5 * arg);
Samples[i++] = temp;
if (modo == 0) Samples[i++] = 0;
}
}
void main(void){
short i, T, A=0, freq, opt;
char txt3[3], txt6[6];
InitConfig();
Inicio:
LCD_Custom_Out(1,1,"Iniciando");
LCD_Custom_Out(2,1,"Audme 2.1");
delay_ms(2000);
LCD_Custom_Out(1,1,"Iniciar ");
LCD_Custom_Out(2,1,"Presione Enter");
opt = 0;
while(1){
if(Button(&PORTD, 0, 100, 0)){
if(opt == 0) goto Empieza;
if(opt == 1) Formatear();
if(opt == 2) EnviarDatos();
delay_ms(100);
goto Inicio;
} else if (Button(&PORTD, 1, 100,0)){
opt++;
if(opt == 3) opt = 0;
if (opt == 0) LCD_Custom_Out(1,1,"Iniciar ");
if (opt == 1) LCD_Custom_Out(1,1,"Formatear ");
if (opt == 2) LCD_Custom_Out(1,1,"Enviar Datos ");
delay_ms(100);
}
}
Empieza:
LCD_Custom_Out(1,1,"Cargando datos");
while(1){
CargarDatos(0);
freq = EncontrarFc();
if(freq > 5 && freq < 20) break;
LCD_Custom_Cmd(LCD_CLEAR);
LCD_Custom_Out(1,1,"No se encuentra la");
LCD_Custom_Out(2,1,"senal.");
Segundos(5);
flag++;
if(flag == 5){
LCD_Custom_Cmd(LCD_CLEAR);
LCD_Custom_Out(1,1,"Error 69");
Segundos(5);
goto Inicio;
}
LCD_Custom_Cmd(LCD_CLEAR);
LCD_Custom_Out(1,1,"Buscando senal");
}
LCD_Custom_Cmd(LCD_CLEAR);
GuardarDatos(99);
CargarDatos(1);
CalculoIndices(0, freq);
delay_ms(500);
GuardarDatos(0);
delay_ms(200);
EscribirByte(Adrr,47,freq);
NewLine();
TextToUart("Datos nuevos");
NewLine();
for(i=0;i<50;i++){
IntToStr(Samples2[i], txt6);
TextToUart(txt6);
NewLine();
delay_ms(5);
}
TextToUart("-- done --");
NewLine;
LCD_Custom_Out(2,1,"3...");
Segundos(5);
LCD_Custom_Out(2,1,"2...");
Segundos(5);
LCD_Custom_Out(2,1,"1...");
Segundos(5);
LCD_Custom_Out(2,1,"Post Oclusion");
Segundos(25);
CargarDatos(2);
CalculoIndices(2, freq);
GuardarDatos(2);
Lcd_Custom_Out(2,1,"Procesando ");
Segundos(25);
CargarDatos(1);
CalculoIndices(4, freq);
GuardarDatos(4);
Segundos(25);
CargarDatos(2);
CalculoIndices(6, freq);
GuardarDatos(6);
Segundos(25);
CargarDatos(1);
CalculoIndices(8, freq);
GuardarDatos(8);
Lcd_Custom_Cmd(LCD_CLEAR);
Lcd_Custom_Out(1,1,"Finalizado");
i=0;
flag = freq;
MostrarDatos(0);
while(1){
if(Button(&PORTD, 0, 100,0)){
i++;
if(i == 6) i = 0;
MostrarDatos(i);
delay_ms(200);
} else if(Button(&PORTD, 1, 100,0)){
LCD_Custom_Cmd(LCD_CLEAR);
LCD_Custom_Out(1,1,"Salir?");
LCD_Custom_Out(2,1,"Si -> Start");
while(1){
if(Button(&PORTD, 0, 100, 0)){
Delay_ms(200);
goto Inicio;
}else if (Button(&PORTD, 1, 100,0)){
LCD_Custom_Cmd(LCD_CLEAR);
MostrarDatos(0);
break;
}
}
}
}
goto Inicio;
}
void MostrarDatos(short modo){
char txt6[6];
char txt4[4];
LCD_Custom_Cmd(LCD_CLEAR);
if(modo == 0){
IntToStr(indices[0], txt6);
LCD_Custom_Out(1,1,"RIctrl: ");
LCD_Custom_Out(1,8,txt6);
IntToStr(indices[1], txt6);
LCD_Custom_Out(2,1,"dTctrl: ");
LCD_Custom_Out(2,8,txt6);
}else if (modo == 5){
IntToStr(Adrr, txt6);
ShortToStr(flag, txt4);
LCD_Custom_Cmd(LCD_CLEAR);
Lcd_Custom_Out(1,1,"NdReg: ");
Lcd_Custom_Out(1,10,txt6);
Lcd_Custom_Out(2,1,"freq: ");
Lcd_Custom_Out(2,8,txt4);
}else if ((modo > 0) && (modo < 5)){
IntToStr(indices[modo], txt6);
ShortToStr(modo, txt4);
LCD_Custom_Out(1,1,"RI :");
LCD_Custom_Out(1,3,txt4);
LCD_Custom_Out(1,10,txt6);
IntToStr(indices[modo + 1], txt6);
ShortToStr(modo, txt4);
LCD_Custom_Out(2,1,"dT :");
LCD_Custom_Out(2,3,txt4);
LCD_Custom_Out(2,10,txt6);
}
}
void Segundos(unsigned cantidad){
unsigned short i;
for(i=0; i < cantidad; i++) delay_ms(1000);
}
unsigned ReadAdc() {
ADCON1.F1 = 1;
while (ADCON1.F0 == 0)
asm nop;
return ADCBUF0;
}
void CargarDatos(short f){
Generar_Senal(f);
#line 286 "C:/Documents and Settings/Administrador/Escritorio/Software/030309_d/Proyectos_4013/audme21.c"
}
short EncontrarFc(){
float Rer, Imr, tmpR;
char index = 0;
unsigned i, j;
FFT(7, TwiddleCoeff_128, Samples);
BitReverseComplex(7, Samples);
j = 0;
for (i=0;i<256;i++){
Rer = Fract2Float(Samples[i]);
Imr = Fract2Float(Samples[++i]);
Samples2[j++] = sqrt(Rer * Rer + Imr * Imr)*100;
}
j = Samples2[0];
for(i=1;i<128;i++){
if (Samples2[i] > j){
j = Samples2[i];
index = i;
}
}
index = index * 1.9;
return index;
}
float Fract2Float(int input) {
if (input < 0) input = - input;
return (input / 32768.);
}
void Derivando(void){
#line 331 "C:/Documents and Settings/Administrador/Escritorio/Software/030309_d/Proyectos_4013/audme21.c"
unsigned i;
unsigned j=0;
int temp1, temp2;
for(i=0;i<25;i++) impulsos[i] = 0;
temp1 = samples[1] - samples[0];
for(i=1;i<254;i++){
temp2 = Samples[i+1] - Samples[i];
if (temp1 < 0 && temp2 > 0) impulsos[j++] = i+1;
temp1 = temp2;
}
}
int tipo(short ini, short fin, short T){
#line 359 "C:/Documents and Settings/Administrador/Escritorio/Software/030309_d/Proyectos_4013/audme21.c"
float tol=0.15;
unsigned dif;
dif = fin - ini;
if (dif > 2*(T + T*tol)) return 0;
if(dif >= (T-T*tol)){
if (dif <= (T+T*tol)) return 2;
if (dif >= 2*(T-T*tol)) return 4;
return 3;
}
return 0;
}
short Promediar(short T){
#line 383 "C:/Documents and Settings/Administrador/Escritorio/Software/030309_d/Proyectos_4013/audme21.c"
short j=0, cant = 0;
short A=0, num1;
unsigned i;
for(i=0;i<128;i++) samples2[i] = 0;
while (impulsos[cant] != 0) cant++;
i = 1;
while(A <= 4 || i > cant - 3){
num1 = tipo(impulsos[i], impulsos[i+2], T);
if(num1 == 2){
if(samples[impulsos[i]] > samples[impulsos[i+1]]) i++;
for(j=0;j<T;j++) samples2[j] = samples2[j] + samples[impulsos[i] + j];
A++; i++;
} else if (num1 == 3) {
i++;
for(j=0;j<T;j++) samples2[j] = samples2[j] + samples[impulsos[i] + j];
A++; i++;
} else if (num1 == 4) {
for(j=0;j<T;j++) samples2[j] = samples2[j] + samples[impulsos[i] + j];
i++; A++;
} else {
i++;
}
}
for(i=0;i<T;i++) samples2[i] = samples2[i] /A;
return A;
}
short encontrar_pico(short inicio, short T){
#line 427 "C:/Documents and Settings/Administrador/Escritorio/Software/030309_d/Proyectos_4013/audme21.c"
int i = 0;
for (i = inicio + 1;i < T-1;i++){
if((samples2[i] > samples2[i-1]) && (samples2[i] > samples2[i+1])) return i;
}
return 0;
}
void CalculoIndices(short dir, short freq){
short k, T, A;
unsigned dir_a, dir_b=0, deltaT;
int ampli_a=0, ampli_b=0, ri;
float tempa, tempb;
for(k=0;k<128;k++) Samples2[k] = 0;
Derivando();
T = 500/freq;
A = Promediar(T);
dir_a = encontrar_pico(0,T);
dir_b = encontrar_pico(dir_a, T);
if (dir_b > 0){
Ampli_a = Samples2[dir_a] - Samples2[T-1];
Ampli_b = Samples2[dir_b] - Samples2[T-1];
tempa = Fract2Float(Ampli_a);
tempb = Fract2Float(Ampli_b);
ri = 100 * tempb / tempa;
deltaT = dir_b - dir_a;
indices[dir++] = ri;
indices[dir++] = deltaT;
} else {
Ampli_a = Samples2[dir_a] - Samples2[T-1];
indices[dir++] = Ampli_a;
indices[dir++] = 0;
}
}
void GuardarDatos(short modo){
#line 468 "C:/Documents and Settings/Administrador/Escritorio/Software/030309_d/Proyectos_4013/audme21.c"
char Adrr1 = 0, Adrr0 = 0;
char txt6[6];
unsigned i;
short stemp = 0;
if (modo == 99){
Adrr = LeerByte(0x00,0x00);
Adrr = Adrr + 1;
delay_ms(100);
EscribirByte(0x00,0x00,Adrr);
LCD_Custom_Out(1,1,"NdR: ");
IntToStr(Adrr,txt6);
LCD_Custom_Out(1,6,txt6);
return;
} else if(modo < 10){
delay_ms(500);
for(i=0;i<50;i++){
stemp = IntToShort(Samples2[i]);
samples2[i] = stemp;
}
WEeprom(Adrr, modo * 50);
delay_ms(500);
EscribirByte(Adrr,48,Indices[modo]);
EscribirByte(Adrr,49,Indices[modo + 1]);
}
return;
}
void Formatear (void){
short i;
LCD_Custom_Out(2,1,"Confirma? ");
while(1){
if(Button(&PORTD, 0, 100, 0)){
Lcd_Custom_Cmd(LCD_CLEAR);
Lcd_Custom_Out(1,1,"Formateando..");
#line 510 "C:/Documents and Settings/Administrador/Escritorio/Software/030309_d/Proyectos_4013/audme21.c"
for(i=0;i<50;i++) Samples2[i] = 0x0000;
WEeprom(0x00, 0x00);
delay_ms(2000);
Lcd_Custom_Out(2,1,"Finalizado ");
Delay_ms(2000);
break;
}else if (Button(&PORTD, 1, 100,0)){
Lcd_Custom_Out(1,1,"Cancelado ");
Delay_ms(2000);
break;
}
}
LCD_Custom_Cmd(LCD_CLEAR);
LCD_Custom_Out(1,1,"Formatear ");
LCD_Custom_Out(2,1,"Presione Enter");
}
void WEeprom(char Adrr1, char Adrr0){
char i;
I2c_Start();
I2c_Write(0xA2);
I2c_Write(Adrr1);
I2c_Write(Adrr0);
for(i=0;i<48;i++) I2c_Write(Samples2[i]);
I2c_Stop();
}
void REeprom(char Adrr1, char Adrr0){
char i;
I2c_Start();
I2c_Write(0xA2);
I2c_Write(Adrr1);
I2c_Write(Adrr0);
I2c_Restart();
I2c_Write(0xA3);
for(i=0;i<49;i++) Samples2[i] = I2c_Read(0);
Samples2[49] = I2c_Read(1);
I2c_Stop();
}
unsigned char LeerByte(char Adrr1, char Adrr0){
unsigned char temp1;
I2c_Start();
I2c_Write(0xA2);
I2c_Write(Adrr1);
I2c_Write(Adrr0);
I2c_Restart();
I2c_Write(0xA3);
temp1 = I2c_Read(1);
I2c_Stop();
return temp1;
}
void EscribirByte(char Adrr1, char Adrr0, unsigned int dato){
I2C_Start();
I2C_Write(0xA2);
I2C_Write(Adrr1);
I2C_Write(Adrr0);
I2C_Write(dato);
I2C_Stop();
}
short IntToShort(int valor16){
float fTemp;
short sTemp;
if (valor16 == 0) return 0;
if (valor16 > 0){
fTemp = valor16 * 0.0668;
sTemp = fTemp;
return fTemp;
} else if (valor16 < 0){
fTemp = valor16 * 0.06736842;
sTemp = fTemp;
return fTemp;
}
}
void TextToUart(unsigned char *m){
unsigned char i=0;
while(m[i]!=0){
EnviarByte(m[i]);
i++;
}
}
void EnviarByte(unsigned dato){
U2STA.F10 = 1;
U2TXREG = dato;
delay_ms(5);
}
void NewLine(){
EnviarByte(0x0D);
EnviarByte(0x0A);
}
void EnviarBloque(char *m){
unsigned i;
char txt3[3];
TextToUart(m);
NewLine();
TextToUart("----");
NewLine();
for(i=0;i<50;i++){
ByteToStr(Samples2[i], txt3);
TextToUart(txt3);
NewLine();
}
TextToUart("----");
NewLine();
}
void EnviarDatos(void){
unsigned Addr, i;
LCD_Custom_Out(1,1,"Enviando datos");
Addr = LeerByte(0x00, 0x00);
for(i=1;i<=Addr;i++){
REeprom(i, 0x00);
delay_ms(100);
EnviarBloque("0x00");
REeprom(i, 0x32);
delay_ms(100);
EnviarBloque("0x32");
REeprom(i, 0x64);
delay_ms(100);
EnviarBloque("0x64");
REeprom(i, 0x96);
delay_ms(100);
EnviarBloque("0x96");
REeprom(i, 0xC8);
delay_ms(100);
EnviarBloque("0xC8");
}
LCD_Custom_Out(1,1,"Done.");
delay_ms(1000);
LCD_Custom_Cmd(LCD_Clear);
}
void InitAdc() {
ADPCFG = 0xFFFE;
ADCSSL = 0;
ADCHS = 2;
ADCON2.F15 = 1;
ADCON3 = 0x1F3F;
TRISB.F2 = 1;
ADCON1 = 0x80E0;
}
void InitLCD(){
Lcd_Custom_Config(&PORTB, 5,4,3,2, &PORTD, 9, 3, 2);
Lcd_Custom_Cmd(LCD_CURSOR_OFF);
Lcd_Custom_Cmd(LCD_CLEAR);
}
void InitConfig(){
TRISB = 0x01FF;
TRISD = 0x0003;
InitAdc();
InitLCD();
Uart2_Init(9600);
I2C_Init(10000);
Twiddle_Factors_Init();
}
| [
"marcosvanetta@gmail.com"
] | marcosvanetta@gmail.com |
f11144ffbe5d421a739527671b4480474955cf7d | 5838cf8f133a62df151ed12a5f928a43c11772ed | /NT/net/sockets/winsock2/ws2_32/src/getproto.cpp | a3861d0107136c06531003bb46dd41e0bebeb3e8 | [] | no_license | proaholic/Win2K3 | e5e17b2262f8a2e9590d3fd7a201da19771eb132 | 572f0250d5825e7b80920b6610c22c5b9baaa3aa | refs/heads/master | 2023-07-09T06:15:54.474432 | 2021-08-11T09:09:14 | 2021-08-11T09:09:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,478 | cpp | /*++
Copyright (c) 1996 Microsoft Corporation
Module Name:
getproto.cpp
Abstract:
This module handles the getprotobyX() functions.
The following functions are exported by this module:
getprotobyname()
getprotobynumber()
Author:
Keith Moore (keithmo) 18-Jun-1996
Revision History:
--*/
#include "precomp.h"
#include "strsafe.h"
//
// Private contants.
//
#define DATABASE_PATH_REGISTRY_KEY \
"System\\CurrentControlSet\\Services\\Tcpip\\Parameters"
#define DATABASE_PATH_REGISTRY_VALUE "DataBasePath"
#define PROTOCOL_DATABASE_FILENAME "protocol"
//
// Private prototypes.
//
FILE *
GetProtoOpenNetworkDatabase(
VOID
);
CHAR *
GetProtoPatternMatch(
CHAR * Scan,
CHAR * Match
);
PPROTOENT
GetProtoGetNextEnt(
FILE * DbFile,
PGETPROTO_INFO ProtoInfo
);
//
// Public functions.
//
struct protoent FAR *
WSAAPI
getprotobynumber(
IN int number
)
/*++
Routine Description:
Get protocol information corresponding to a protocol number.
Arguments:
number - Supplies a protocol number, in host byte order
Returns:
If no error occurs, getprotobynumber() returns a pointer to the protoent
structure described above. Otherwise it returns a NULL pointer and a
specific error r code is stored with SetErrorCode().
--*/
{
PDTHREAD Thread;
INT ErrorCode;
PGETPROTO_INFO protoInfo;
PPROTOENT pent;
FILE * dbFile;
ErrorCode = TURBO_PROLOG_OVLP(&Thread);
if(ErrorCode != ERROR_SUCCESS)
{
SetLastError(ErrorCode);
return(NULL);
}
//
// Get the per-thread buffer.
//
protoInfo = Thread->GetProtoInfo();
if( protoInfo == NULL ) {
SetLastError( WSANO_DATA );
return NULL;
}
//
// Open the database file.
//
dbFile = GetProtoOpenNetworkDatabase();
if( dbFile == NULL ) {
SetLastError( WSANO_DATA );
return NULL;
}
//
// Scan it.
//
while( TRUE ) {
pent = GetProtoGetNextEnt(
dbFile,
protoInfo
);
if( pent == NULL ) {
break;
}
if( (int)pent->p_proto == number ) {
break;
}
}
//
// Close the database.
//
fclose( dbFile );
if( pent == NULL ) {
SetLastError( WSANO_DATA );
}
return pent;
} // getprotobynumber
struct protoent FAR *
WSAAPI
getprotobyname(
IN const char FAR * name
)
/*++
Routine Description:
Get protocol information corresponding to a protocol name.
Arguments:
name - A pointer to a null terminated protocol name.
Returns:
If no error occurs, getprotobyname() returns a pointer to the protoent
structure described above. Otherwise it returns a NULL pointer and a
specific error code is stored with SetErrorCode().
--*/
{
PDTHREAD Thread;
INT ErrorCode;
PGETPROTO_INFO protoInfo;
PPROTOENT pent;
FILE * dbFile;
ErrorCode = TURBO_PROLOG_OVLP(&Thread);
if(ErrorCode != ERROR_SUCCESS)
{
SetLastError(ErrorCode);
return(NULL);
}
if ( !name ) // Bug fix for #112420
{
SetLastError(WSAEINVAL);
return(NULL);
}
//
// Get the per-thread buffer.
//
protoInfo = Thread->GetProtoInfo();
if( protoInfo == NULL ) {
SetLastError( WSANO_DATA );
return NULL;
}
//
// Open the database file.
//
dbFile = GetProtoOpenNetworkDatabase();
if( dbFile == NULL ) {
SetLastError( WSANO_DATA );
return NULL;
}
//
// Scan it.
//
while( TRUE ) {
pent = GetProtoGetNextEnt(
dbFile,
protoInfo
);
if( pent == NULL ) {
break;
}
__try {
if( _stricmp( pent->p_name, name ) == 0 ) {
break;
}
}
__except (WS2_EXCEPTION_FILTER()) {
fclose (dbFile);
SetLastError (WSAEFAULT);
return NULL;
}
}
//
// Close the database.
//
fclose( dbFile );
if( pent == NULL ) {
SetLastError( WSANO_DATA );
}
return pent;
} // getprotobyname
//
// Private functions.
//
FILE *
GetProtoOpenNetworkDatabase(
VOID
)
/*++
Routine Description:
Opens a stream to the protocol database file.
Arguments:
None
Return Value:
FILE * - Pointer to the open stream if successful, NULL if not.
--*/
{
CHAR path[MAX_PATH];
CHAR unexpanded[MAX_PATH];
CHAR * suffix;
OSVERSIONINFO version;
LONG err;
HKEY key;
DWORD type;
DWORD length;
//
// Determine the directory for the database file.
//
// Under Win95, the database files live under the Windows directory
// (i.e. C:\WINDOWS).
//
// Under WinNT, the path to the database files is configurable in
// the registry, but the default is in the Drivers\Etc directory
// (i.e. C:\WINDOWS\SYSTEM32\DRIVERS\ETC).
//
version.dwOSVersionInfoSize = sizeof(version);
if( !GetVersionEx( &version ) ) {
return NULL;
}
suffix = "";
if( version.dwPlatformId == VER_PLATFORM_WIN32_NT ) {
//
// We're running under NT, so try to get the path from the
// registry.
//
err = RegOpenKeyEx(
HKEY_LOCAL_MACHINE,
DATABASE_PATH_REGISTRY_KEY,
0,
KEY_READ,
&key
);
if( err == NO_ERROR ) {
length = sizeof(unexpanded);
err = RegQueryValueEx(
key,
DATABASE_PATH_REGISTRY_VALUE,
NULL,
&type,
(LPBYTE)unexpanded,
&length
);
//
// Make sure it is NULL terminated (in case
// data type is not string). This lets us
// get away with not validating the type.
//
unexpanded[sizeof(unexpanded)-1] = 0;
RegCloseKey( key );
}
if( err == NO_ERROR ) {
length = ExpandEnvironmentStrings(
unexpanded,
path,
sizeof(path)
);
if (length == 0 ) {
err = WSASYSCALLFAILURE;
}
}
if( err != NO_ERROR ) {
//
// Couldn't get it from the registry, just use the default.
//
if( GetSystemDirectory(
path,
sizeof(path)
) == 0 ) {
return NULL;
}
suffix = "DRIVERS\\ETC\\";
}
} else {
//
// We're running under Win95, so just get the Windows directory.
//
if( GetWindowsDirectory(
path,
sizeof(path)
) == 0 ) {
return NULL;
}
}
//
// Ensure the path has a trailing backslash, then tack on any suffix
// needed, then tack on the filename.
//
if( path[strlen( path ) - 1] != '\\' ) {
if(StringCchCat( path, sizeof (path), "\\" ) != S_OK)
return NULL;
}
if(StringCchCat( path, sizeof (path), suffix ) != S_OK)
return NULL;
if(StringCchCat( path, sizeof (path), PROTOCOL_DATABASE_FILENAME ) != S_OK)
return NULL;
//
// Open the file, return the result.
//
return fopen( path, "rt" );
} // GetProtoOpenNetworkDatabase
CHAR *
GetProtoPatternMatch(
CHAR * Scan,
CHAR * Match
)
/*++
Routine Description:
Finds the first character in Scan that matches any character in Match.
Arguments:
Scan - The string to scan.
Match - The list of characters to match against.
Return Value:
CHAR * - Pointer to the first occurrance in Scan if successful,
NULL if not.
--*/
{
CHAR ch;
while( ( ch = *Scan ) != '\0' ) {
if( strchr( Match, ch ) != NULL ) {
return Scan;
}
Scan++;
}
return NULL;
} // GetProtoPatternMatch
PPROTOENT
GetProtoGetNextEnt(
FILE * DbFile,
PGETPROTO_INFO ProtoInfo
)
{
CHAR * ptr;
CHAR * token;
CHAR ** aliases;
PPROTOENT result = NULL;
while( TRUE ) {
//
// Get the next line, bail if EOF.
//
ptr = fgets(
ProtoInfo->TextLine,
MAX_PROTO_TEXT_LINE,
DbFile
);
if( ptr == NULL ) {
break;
}
//
// Skip comments.
//
if( *ptr == '#' ) {
continue;
}
token = GetProtoPatternMatch ( ptr, "#\n" );
if( token == NULL ) {
continue;
}
*token = '\0';
//
// Start building the entry.
//
ProtoInfo->Proto.p_name = ptr;
token = GetProtoPatternMatch( ptr, " \t" );
if( token == NULL ) {
continue;
}
*token++ = '\0';
while( *token == ' ' || *token == '\t' ) {
token++;
}
ptr = GetProtoPatternMatch( token, " \t" );
if( ptr != NULL ) {
*ptr++ = '\0';
}
ProtoInfo->Proto.p_proto = (short)atoi( token );
//
// Build the alias list.
//
ProtoInfo->Proto.p_aliases = ProtoInfo->Aliases;
aliases = ProtoInfo->Proto.p_aliases;
if( ptr != NULL ) {
token = ptr;
while( token && *token ) {
if( *token == ' ' || *token == '\t' ) {
token++;
continue;
}
if( aliases < &ProtoInfo->Proto.p_aliases[MAX_PROTO_ALIASES - 1] ) {
*aliases++ = token;
}
token = GetProtoPatternMatch( token, " \t" );
if( token != NULL ) {
*token++ = '\0';
}
}
}
*aliases = NULL;
result = &ProtoInfo->Proto;
break;
}
return result;
} // GetProtoGetNextEnt
| [
"blindtiger@foxmail.com"
] | blindtiger@foxmail.com |
136a5935bb761848039ac2d2c31ebdc0a73c744b | 4e902b8bc7a3d8aa3fff36cc417d8a1a5c2a6936 | /Palindrome Partitioning II.cpp | 617940054dcc4114bca6d17e62b4ab0eb720ebdf | [] | no_license | Itfly/leetcode | 6765f7784b1481c72dad3d20c368e461805ba717 | 3e9ee41e7981b54b7aecf86cc42244062b05ed4c | refs/heads/master | 2020-04-06T03:47:11.499770 | 2019-02-16T08:12:30 | 2019-02-16T08:12:30 | 25,846,941 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 888 | cpp | class Solution {
public:
int minCut(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n = s.length();
if (n <= 1) return 0;
vector<int> dp(n, 0);
vector<vector<bool> > isPalindrome(n, vector<bool>(n, false));
dp[0] = 0;
for (int i = 1; i < n; i++) {
dp[i] = i;
if (s[0] == s[i] && (i <= 2 || isPalindrome[1][i-1])) {
dp[i] = 0;
isPalindrome[0][i] = true;
}
for(int k = 1; k <= i; k++) {
if (s[k] == s[i] &&(i - k <=2 || isPalindrome[k+1][i-1])) {
isPalindrome[k][i] = true;
dp[i] = min(dp[i], dp[k-1]+1);
}
}
}
return dp[n-1];
}
}; | [
"pla1988@gmail.com"
] | pla1988@gmail.com |
a2882196d5dba31a22f7f03de0df03d5ffab4167 | e2092e75f34deb8867453f271d1a76cc0ca3d3b0 | /include/tao/json/external/pegtl/contrib/uri.hpp | 46a0351cf0cef3807942185867c7a4794c302c96 | [
"MIT",
"BSD-3-Clause"
] | permissive | Tecla/json | a64fb00864a135f7005ecd7bea814769754a5b2b | 648ab43448c568b6a7501d1df2a88b3387811e33 | refs/heads/master | 2021-04-29T16:01:25.629768 | 2018-02-16T18:37:23 | 2018-02-16T18:37:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,776 | hpp | // Copyright (c) 2014-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAO_JSON_PEGTL_INCLUDE_CONTRIB_URI_HPP
#define TAO_JSON_PEGTL_INCLUDE_CONTRIB_URI_HPP
#include "../ascii.hpp"
#include "../config.hpp"
#include "../rules.hpp"
#include "../utf8.hpp"
#include "abnf.hpp"
namespace tao
{
namespace TAO_JSON_PEGTL_NAMESPACE
{
namespace uri
{
// URI grammar according to RFC 3986.
// This grammar is a direct PEG translation of the original URI grammar.
// It should be considered experimental -- in case of any issues, in particular
// missing rules for attached actions, please contact the developers.
// Note that this grammar has multiple top-level rules.
using dot = one< '.' >;
using colon = one< ':' >;
// clang-format off
struct dec_octet : sor< one< '0' >,
rep_min_max< 1, 2, abnf::DIGIT >,
seq< one< '1' >, abnf::DIGIT, abnf::DIGIT >,
seq< one< '2' >, range< '0', '4' >, abnf::DIGIT >,
seq< string< '2', '5' >, range< '0', '5' > > > {};
struct IPv4address : seq< dec_octet, dot, dec_octet, dot, dec_octet, dot, dec_octet > {};
struct h16 : rep_min_max< 1, 4, abnf::HEXDIG > {};
struct ls32 : sor< seq< h16, colon, h16 >, IPv4address > {};
struct dcolon : two< ':' > {};
struct IPv6address : sor< seq< rep< 6, h16, colon >, ls32 >,
seq< dcolon, rep< 5, h16, colon >, ls32 >,
seq< opt< h16 >, dcolon, rep< 4, h16, colon >, ls32 >,
seq< opt< h16, opt< colon, h16 > >, dcolon, rep< 3, h16, colon >, ls32 >,
seq< opt< h16, rep_opt< 2, colon, h16 > >, dcolon, rep< 2, h16, colon >, ls32 >,
seq< opt< h16, rep_opt< 3, colon, h16 > >, dcolon, h16, colon, ls32 >,
seq< opt< h16, rep_opt< 4, colon, h16 > >, dcolon, ls32 >,
seq< opt< h16, rep_opt< 5, colon, h16 > >, dcolon, h16 >,
seq< opt< h16, rep_opt< 6, colon, h16 > >, dcolon > > {};
struct gen_delims : one< ':', '/', '?', '#', '[', ']', '@' > {};
struct sub_delims : one< '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=' > {};
struct unreserved : sor< abnf::ALPHA, abnf::DIGIT, one< '-', '.', '_', '~' > > {};
struct reserved : sor< gen_delims, sub_delims > {};
struct IPvFuture : if_must< one< 'v' >, plus< abnf::HEXDIG >, dot, plus< sor< unreserved, sub_delims, colon > > > {};
struct IP_literal : if_must< one< '[' >, sor< IPvFuture, IPv6address >, one< ']' > > {};
struct pct_encoded : if_must< one< '%' >, abnf::HEXDIG, abnf::HEXDIG > {};
struct pchar : sor< unreserved, pct_encoded, sub_delims, one< ':', '@' > > {};
struct query : star< sor< pchar, one< '/', '?' > > > {};
struct fragment : star< sor< pchar, one< '/', '?' > > > {};
struct segment : star< pchar > {};
struct segment_nz : plus< pchar > {};
struct segment_nz_nc : plus< sor< unreserved, pct_encoded, sub_delims, one< '@' > > > {}; // non-zero-length segment without any colon ":"
struct path_abempty : star< one< '/' >, segment > {};
struct path_absolute : seq< one< '/' >, opt< segment_nz, star< one< '/' >, segment > > > {};
struct path_noscheme : seq< segment_nz_nc, star< one< '/' >, segment > > {};
struct path_rootless : seq< segment_nz, star< one< '/' >, segment > > {};
struct path_empty : success {};
struct path : sor< path_noscheme, // begins with a non-colon segment
path_rootless, // begins with a segment
path_absolute, // begins with "/" but not "//"
path_abempty > {}; // begins with "/" or is empty
struct reg_name : star< sor< unreserved, pct_encoded, sub_delims > > {};
struct port : star< abnf::DIGIT > {};
struct host : sor< IP_literal, IPv4address, reg_name > {};
struct userinfo : star< sor< unreserved, pct_encoded, sub_delims, colon > > {};
struct opt_userinfo : opt< userinfo, one< '@' > > {};
struct authority : seq< opt_userinfo, host, opt< colon, port > > {};
struct scheme : seq< abnf::ALPHA, star< sor< abnf::ALPHA, abnf::DIGIT, one< '+', '-', '.' > > > > {};
using dslash = two< '/' >;
using opt_query = opt< if_must< one< '?' >, query > >;
using opt_fragment = opt< if_must< one< '#' >, fragment > >;
struct hier_part : sor< if_must< dslash, authority, path_abempty >, path_rootless, path_absolute, path_empty > {};
struct relative_part : sor< if_must< dslash, authority, path_abempty >, path_noscheme, path_absolute, path_empty > {};
struct relative_ref : seq< relative_part, opt_query, opt_fragment > {};
struct URI : seq< scheme, one< ':' >, hier_part, opt_query, opt_fragment > {};
struct URI_reference : sor< URI, relative_ref > {};
struct absolute_URI : seq< scheme, one< ':' >, hier_part, opt_query > {};
// clang-format on
} // namespace uri
} // namespace TAO_JSON_PEGTL_NAMESPACE
} // namespace tao
#endif
| [
"d.frey@gmx.de"
] | d.frey@gmx.de |
851d3cce9a9dc3e944476fb16c76a90efc36683f | eb5729f1abf8b9d0d8656deb2f3fe03ad3c18c97 | /circle.cpp | f1626f4c301833e0612cf7b8bc9fdbcbc57bbbc0 | [] | no_license | UVMCS120BS2019/FinalProject-Chartreuse | 0ff69f7c9085ead58ad9d9f9d67de72fdeb20765 | 23e7436cfd8eb63473e58494aa4f0315caee662a | refs/heads/master | 2020-05-15T05:49:40.725531 | 2019-05-07T01:14:29 | 2019-05-07T01:14:29 | 182,111,415 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 956 | cpp | //
// Created by Mary Woolley on 2019-04-21.
//
#include "circle.h"
#define _USE_MATH_DEFINES
using namespace std;
Circle::Circle() {
radius = 10;
}
Circle::Circle(color col, point cent, double radius) : Shape (col, cent) {
setRadius(radius);
}
double Circle::getRadius() {
return radius;
}
void Circle::setRadius(double radius) {
if (radius > 0) {
this->radius = radius;
} else {
radius = 10;
}
}
void Circle::draw() const {
glBegin(GL_TRIANGLE_FAN);
float radius = this->radius;
float xGen, yGen;
glColor4f(fill.red, fill.green, fill.blue, fill.opacity);
//for all 360 degrees, use sin and cos to determine x and y
for(int angle = 0; angle <= 360; angle++){
xGen = cent.x + float(cos(angle*(pi/180)) * radius);
yGen = cent.y + float(sin(angle*(pi/180)) * radius);
//create a vertex for the given angle
glVertex2i(xGen, yGen);
}
glEnd();
}
| [
"marymaryalma@gmail.com"
] | marymaryalma@gmail.com |
17c9c30de9946e801dc1cad613e29fc5f2b85a04 | 62408a02b44f2fd20c6d54e1f5def0184e69194c | /SPOJ/CLSLDR/16187567_AC_190ms_20480kB.cpp | f104654351737126288fef020c93eb2f33ee168c | [] | no_license | benedicka/Competitive-Programming | 24eb90b8150aead5c13287b62d9dc860c4b9232e | a94ccfc2d726e239981d598e98d1aa538691fa47 | refs/heads/main | 2023-03-22T10:14:34.889913 | 2021-03-16T05:33:43 | 2021-03-16T05:33:43 | 348,212,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 420 | cpp | #include<bits/stdc++.h>
using namespace std;
int dp[1010][1010];
int jo(int n, int k)
{
if(dp[n][k]!=0) return dp[n][k];
if (n == 1)
{
return 1;
}
else
{
return dp[n][k] = (jo(n - 1, k) + k-1) % n + 1;
}
}
int main()
{
int t,n,m,k,ans;
scanf("%d",&t);
while(t--)
{
scanf("%d %d %d",&n,&m,&k);
ans = ((jo(n, k))+m)%n;
if(ans==0) ans = n;
printf("%d\n", ans);
}
return 0;
} | [
"43498540+benedicka@users.noreply.github.com"
] | 43498540+benedicka@users.noreply.github.com |
5e4c82e3ca3056d97231b33cb347043cdfb4b966 | 6a97dcadca9c402e3cd0da57b057392bfce87568 | /chapter1_getting_started/Sales_item.h | f9f5265a507b9a50b5cd4b549bacff8c0aa95604 | [] | no_license | hlaineka/cpp_primer | 9d3416e8ec1b30f377b33dca28cc8d442d1738dc | 16d1dc8c45e54a5272ced22258deafbe533bcad1 | refs/heads/main | 2023-02-27T02:50:30.394870 | 2021-02-10T16:47:43 | 2021-02-10T16:47:43 | 333,496,524 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,732 | h | /*
* This file contains code from "C++ Primer, Fifth Edition", by Stanley B.
* Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the
* copyright and warranty notices given in that book:
*
* "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo."
*
*
* "The authors and publisher have taken care in the preparation of this book,
* but make no expressed or implied warranty of any kind and assume no
* responsibility for errors or omissions. No liability is assumed for
* incidental or consequential damages in connection with or arising out of the
* use of the information or programs contained herein."
*
* Permission is granted for this code to be used for educational purposes in
* association with the book, given proper citation if and when posted or
* reproduced.Any commercial use of this code requires the explicit written
* permission of the publisher, Addison-Wesley Professional, a division of
* Pearson Education, Inc. Send your request for permission, stating clearly
* what code you would like to use, and in what specific way, to the following
* address:
*
* Pearson Education, Inc.
* Rights and Permissions Department
* One Lake Street
* Upper Saddle River, NJ 07458
* Fax: (201) 236-3290
*/
/* This file defines the Sales_item class used in chapter 1.
* The code used in this file will be explained in
* Chapter 7 (Classes) and Chapter 14 (Overloaded Operators)
* Readers shouldn't try to understand the code in this file
* until they have read those chapters.
*/
#ifndef SALESITEM_H
// we're here only if SALESITEM_H has not yet been defined
#define SALESITEM_H
// Definition of Sales_item class and related functions goes here
#include <iostream>
#include <string>
class Sales_item {
// these declarations are explained section 7.2.1, p. 270
// and in chapter 14, pages 557, 558, 561
friend std::istream& operator>>(std::istream&, Sales_item&);
friend std::ostream& operator<<(std::ostream&, const Sales_item&);
friend bool operator<(const Sales_item&, const Sales_item&);
friend bool
operator==(const Sales_item&, const Sales_item&);
public:
// constructors are explained in section 7.1.4, pages 262 - 265
// default constructor needed to initialize members of built-in type
Sales_item() = default;
Sales_item(const std::string &book): bookNo(book) { }
Sales_item(std::istream &is) { is >> *this; }
public:
// operations on Sales_item objects
// member binary operator: left-hand operand bound to implicit this pointer
Sales_item& operator+=(const Sales_item&);
// operations on Sales_item objects
std::string isbn() const { return bookNo; }
double avg_price() const;
// private members as before
private:
std::string bookNo; // implicitly initialized to the empty string
unsigned units_sold = 0; // explicitly initialized
double revenue = 0.0;
};
// used in chapter 10
inline
bool compareIsbn(const Sales_item &lhs, const Sales_item &rhs)
{ return lhs.isbn() == rhs.isbn(); }
// nonmember binary operator: must declare a parameter for each operand
Sales_item operator+(const Sales_item&, const Sales_item&);
inline bool
operator==(const Sales_item &lhs, const Sales_item &rhs)
{
// must be made a friend of Sales_item
return lhs.units_sold == rhs.units_sold &&
lhs.revenue == rhs.revenue &&
lhs.isbn() == rhs.isbn();
}
inline bool
operator!=(const Sales_item &lhs, const Sales_item &rhs)
{
return !(lhs == rhs); // != defined in terms of operator==
}
// assumes that both objects refer to the same ISBN
Sales_item& Sales_item::operator+=(const Sales_item& rhs)
{
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
// assumes that both objects refer to the same ISBN
Sales_item
operator+(const Sales_item& lhs, const Sales_item& rhs)
{
Sales_item ret(lhs); // copy (|lhs|) into a local object that we'll return
ret += rhs; // add in the contents of (|rhs|)
return ret; // return (|ret|) by value
}
std::istream&
operator>>(std::istream& in, Sales_item& s)
{
double price;
in >> s.bookNo >> s.units_sold >> price;
// check that the inputs succeeded
if (in)
s.revenue = s.units_sold * price;
else
s = Sales_item(); // input failed: reset object to default state
return in;
}
std::ostream&
operator<<(std::ostream& out, const Sales_item& s)
{
out << s.isbn() << " " << s.units_sold << " "
<< s.revenue << " " << s.avg_price();
return out;
}
double Sales_item::avg_price() const
{
if (units_sold)
return revenue/units_sold;
else
return 0;
}
#endif | [
"helvi.lainekallio@gmail.com"
] | helvi.lainekallio@gmail.com |
0e0e9b0f2f649eaebda2f50913400cc68b2cdefd | bc245fdb1c7bc426cb9ad64220156da58de99053 | /include/grammarbuilder.h | 2bfae44c6abb75aed27bc561426f43ba1291cce3 | [] | no_license | gianmarco-todesco/Parser | c1582af5d4b9fc586109808284ed83b31b70bb19 | 32d0873f9d79c0ff8af733a7e5e3fde80cd10062 | refs/heads/master | 2021-01-20T01:19:57.538703 | 2017-09-05T17:37:42 | 2017-09-05T17:37:42 | 89,258,855 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 344 | h | #ifndef GRAMMARBUILDER_H
#define GRAMMARBUILDER_H
#include "token.h"
#include "grammar.h"
#include "parser.h"
class GrammarDefinitionParser : public Parser {
Grammar *m_theGrammar;
public:
GrammarDefinitionParser();
~GrammarDefinitionParser();
};
class GrammarBuilder {
public:
Grammar *build(BaseTokenizer *tokenizer);
};
#endif
| [
"gianmarco.todesco@gmail.com"
] | gianmarco.todesco@gmail.com |
c6daa827221fba2f223eed2ebf8ea48281dfdf02 | a553500c0e7bf730e48bc057d8923ff3a36f0c5a | /T5/src/AFE-API-MQTT.ino | 9e99ab9328d800c436ec672380e1e1c32c179832 | [
"MIT"
] | permissive | sza86/AFE-Firmware | a8eba386bc90f3e287be02cde4c829f23e344b57 | e50b5f867b52052259f9e0c77730974e269fdb74 | refs/heads/master | 2020-04-02T17:52:24.415538 | 2018-10-13T08:51:31 | 2018-10-13T08:51:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,704 | ino | /* AFE Firmware for smart home devices
LICENSE: https://github.com/tschaban/AFE-Firmware/blob/master/LICENSE
DOC: http://smart-house.adrian.czabanowski.com/afe-firmware-pl/ */
#include "AFE-API-MQTT.h"
AFEMQTT::AFEMQTT() {}
void AFEMQTT::begin() {
NetworkConfiguration = Data.getNetworkConfiguration();
sprintf(deviceName, "%s", Device.configuration.name);
Broker.setClient(esp);
if (strlen(MQTTConfiguration.host) > 0) {
Broker.setServer(MQTTConfiguration.host, MQTTConfiguration.port);
} else if (MQTTConfiguration.ip[0] > 0) {
Broker.setServer(MQTTConfiguration.ip, MQTTConfiguration.port);
} else {
isConfigured = false;
}
Broker.setCallback(MQTTMessagesListener);
sprintf(mqttTopicForSubscription, "%s#", MQTTConfiguration.topic);
Data = {};
}
void AFEMQTT::disconnect() {
if (Broker.connected()) {
Broker.disconnect();
}
}
void AFEMQTT::listener() {
if (Broker.connected()) {
Broker.loop();
} else {
connect();
}
}
void AFEMQTT::connect() {
if (isConfigured) {
if (sleepMode) {
if (millis() - sleepStartTime >=
NetworkConfiguration.waitTimeSeries * 1000) {
sleepMode = false;
}
} else {
if (ledStartTime == 0) {
ledStartTime = millis();
}
if (delayStartTime == 0) {
delayStartTime = millis();
/* LWT Topic */
char mqttLWTMessage[38];
sprintf(mqttLWTMessage, "%sstate", MQTTConfiguration.topic);
if (Broker.connect(deviceName, MQTTConfiguration.user,
MQTTConfiguration.password, mqttLWTMessage, 2, false,
"disconnected")) {
/*
Serial << endl << "INFO: Connected";
Serial << endl
<< "INFO: Subscribing to : " <<
mqttTopicForSubscription;
*/
Broker.subscribe((char *)mqttTopicForSubscription);
// Serial << endl << "INFO: Subsribed";
/* Publishing message that device has been connected */
publish(MQTTConfiguration.topic, "state", "connected");
delayStartTime = 0;
ledStartTime = 0;
Led.off();
connections = 0;
return;
}
}
if (millis() > ledStartTime + 500) {
Led.toggle();
ledStartTime = 0;
}
if (millis() >
delayStartTime + (NetworkConfiguration.waitTimeConnections * 1000)) {
connections++;
/*
Serial << endl
<< "INFO: MQTT Connection attempt: " << connections + 1
<< " from " << NetworkConfiguration.noConnectionAttempts
<< ", connection status: " << Broker.state()
<< ", connection time: " << millis() - delayStartTime <<
"ms";
*/
delayStartTime = 0;
}
if (connections >= NetworkConfiguration.noConnectionAttempts) {
sleepMode = true;
sleepStartTime = millis();
delayStartTime = 0;
ledStartTime = 0;
Led.off();
connections = 0;
/*
Serial << endl
<< "WARN: Not able to connect to MQTT.Going to sleep mode
for "
<< NetworkConfiguration.waitTimeSeries << "sec.";
*/
}
}
}
}
void AFEMQTT::setReconnectionParams(
uint8_t no_connection_attempts,
uint8_t duration_between_connection_attempts,
uint8_t duration_between_next_connection_attempts_series) {
NetworkConfiguration.noConnectionAttempts = no_connection_attempts;
NetworkConfiguration.waitTimeConnections =
duration_between_connection_attempts;
NetworkConfiguration.waitTimeSeries =
duration_between_next_connection_attempts_series;
}
void AFEMQTT::publish(const char *type, const char *message) {
char _mqttTopic[50];
sprintf(_mqttTopic, "%s%s", MQTTConfiguration.topic, type);
publishToMQTTBroker(_mqttTopic, message);
}
void AFEMQTT::publish(const char *type, float value, uint8_t width,
uint8_t precision) {
char message[10];
dtostrf(value, width, precision, message);
publish(type, message);
}
void AFEMQTT::publish(const char *topic, const char *type,
const char *message) {
char _mqttTopic[50];
sprintf(_mqttTopic, "%s%s", topic, type);
publishToMQTTBroker(_mqttTopic, message);
}
void AFEMQTT::publishToMQTTBroker(const char *topic, const char *message) {
if (Broker.state() == MQTT_CONNECTED) {
// Serial << endl << "INFO: MQTT publising: " << topic << " \\ " <<
// message;
Broker.publish(topic, message);
}
}
| [
"github@adrian.czabanowski.com"
] | github@adrian.czabanowski.com |
153112dfd8fa84087bb1e3d69f0778e1d2776f54 | d2190cbb5ea5463410eb84ec8b4c6a660e4b3d0e | /hydra2-4.9w/mdctrackG/hmetamatch2.h | 74fcdcbedde59a4978398d07709a0c1d6550ad97 | [] | no_license | wesmail/hydra | 6c681572ff6db2c60c9e36ec864a3c0e83e6aa6a | ab934d4c7eff335cc2d25f212034121f050aadf1 | refs/heads/master | 2021-07-05T17:04:53.402387 | 2020-08-12T08:54:11 | 2020-08-12T08:54:11 | 149,625,232 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,726 | h | #ifndef HMETAMATCH2_H
#define HMETAMATCH2_H
#include "hreconstructor.h"
#include "TString.h"
#include "TObject.h"
#define RICH_TAB_SIZE 3
#define META_TAB_SIZE 3
class HMetaMatch2:public TObject {
private:
Int_t trkCandInd; // index of HTrkCand object
Int_t ownIndex; // index of "this" object in categoty
Char_t sector; // sector number
UChar_t nRpcClust; // Number of matched rpc clusters
UChar_t nShrHits; // Number of matched shower hits
UChar_t nTofHits; // Number of matched tof clusters or hits
Short_t rungeKuttaInd;
Short_t rkIndShower[META_TAB_SIZE];
Short_t rkIndTofCl[META_TAB_SIZE];
Short_t rkIndTof1[META_TAB_SIZE];
Short_t rkIndTof2[META_TAB_SIZE];
Short_t rkIndRpc[META_TAB_SIZE];
Short_t kalmanFilterInd; // index of HKalTrack in catKalTrack
Short_t kfIndShower[META_TAB_SIZE];
Short_t kfIndTofCl [META_TAB_SIZE];
Short_t kfIndTof1 [META_TAB_SIZE];
Short_t kfIndTof2 [META_TAB_SIZE];
Short_t kfIndRpc [META_TAB_SIZE];
Short_t rpcClstInd[META_TAB_SIZE]; // Index of HRpcCluster object
Short_t shrHitInd[META_TAB_SIZE]; // Index of HShowerHit object
Short_t tofClstInd[META_TAB_SIZE]; // Index of HTofCluster object
Short_t tofHit1Ind[META_TAB_SIZE]; // Index of HTofHit object ???
Short_t tofHit2Ind[META_TAB_SIZE]; // Index of HTofHit object ???
// System 0:
Float_t rpcQuality[META_TAB_SIZE]; // Matching quality
Float_t rpcDX[META_TAB_SIZE]; // Deviation in X-coordinate
Float_t rpcDY[META_TAB_SIZE]; // Deviation in Y-coordinate
Float_t shrQuality[META_TAB_SIZE]; // Matching quality
Float_t shrDX[META_TAB_SIZE]; // Deviation in X-coordinate
Float_t shrDY[META_TAB_SIZE]; // Deviation in Y-coordinate
// System 1:
Float_t tofClstQuality[META_TAB_SIZE]; // Matching quality
Float_t tofClstDX[META_TAB_SIZE]; // Deviation in X-coordinate
Float_t tofClstDY[META_TAB_SIZE]; // Deviation in Y-coordinate
Float_t tofHit1Quality[META_TAB_SIZE]; // Matching quality
Float_t tofHit1DX[META_TAB_SIZE]; // Deviation in X-coordinate
Float_t tofHit1DY[META_TAB_SIZE]; // Deviation in Y-coordinate
Float_t tofHit2Quality[META_TAB_SIZE]; // Matching quality
Float_t tofHit2DX[META_TAB_SIZE]; // Deviation in X-coordinate
Float_t tofHit2DY[META_TAB_SIZE]; // Deviation in Y-coordinate
Int_t splineInd; // index of HSplineTrack object
UChar_t nRichId; // number of matched rings in richInd[]
UChar_t nRichIPUId; // number of matched rings in richIPUInd[]
Int_t richInd[RICH_TAB_SIZE]; // arr.of indexes of HRichHit objects
Int_t richIPUInd[RICH_TAB_SIZE]; // arr.of indexes of HRichHitIPU objects
// arrais are sorted by matching quality
Char_t flag; // First bit for shower(=0)/emc(=1) distinguish
Bool_t isFakeInner;
Bool_t isFakeOuter;
public:
HMetaMatch2();
~HMetaMatch2(){}
HMetaMatch2(Short_t sec, Int_t tkInd, Int_t ind);
void setTrkCandInd(Int_t tr) {trkCandInd = tr;}
void setOwnIndex(Int_t ind) {ownIndex = ind;}
void setNRpcClust(UChar_t n) {nRpcClust = n<META_TAB_SIZE ? n:META_TAB_SIZE;}
void setNShrHits(UChar_t n) {nShrHits = n<META_TAB_SIZE ? n:META_TAB_SIZE;}
void setNTofHits(UChar_t n) {nTofHits = n<META_TAB_SIZE ? n:META_TAB_SIZE;}
void setRpcClst(UChar_t el,Short_t ind,Float_t ql,Float_t dx,Float_t dy);
void setShrHit(UChar_t el,Short_t ind,Float_t ql,Float_t dx,Float_t dy);
void setTofClst(UChar_t el,Short_t ind,Float_t ql,Float_t dx,Float_t dy);
void setTofHit1(UChar_t el,Short_t ind,Float_t ql,Float_t dx,Float_t dy);
void setTofHit2(UChar_t el,Short_t ind,Float_t ql,Float_t dx,Float_t dy);
// Functions for HMetaMatchF2:
void setRpcClstMMF(UChar_t nln,Short_t ind[],Float_t ql2[][3]);
void setShrHitMMF( UChar_t nln,Short_t ind[],Float_t ql2[][3]);
void setTofClstMMF(UChar_t nln,Short_t ind[][3],Float_t ql2[][9]);
void setEmcClstMMF(UChar_t nln,Short_t ind[],Float_t ql2[][3]);
void setSplineInd(Int_t _splineInd) { splineInd = _splineInd; }
void setSector(Char_t sec) {sector = sec;}
void setNCandForRich(UChar_t nrich) {nRichId = nrich;}
void setNCandForIPU(UChar_t nrich) {nRichIPUId = nrich;}
void setRichInd(UChar_t id, Short_t ind) {if(id<RICH_TAB_SIZE) richInd[id] = ind;}
void setRichIPUInd(UChar_t id, Short_t ind) {if(id<RICH_TAB_SIZE) richIPUInd[id] = ind;}
void setRungeKuttaIndShowerHit(UChar_t n, Short_t ind) { rkIndShower[n] = ind; }
void setRungeKuttaIndEmcCluster(UChar_t n, Short_t ind) { rkIndShower[n] = ind; }
void setRungeKuttaIndTofClst(UChar_t n, Short_t ind) { rkIndTofCl[n] = ind; }
void setRungeKuttaIndTofHit1(UChar_t n, Short_t ind) { rkIndTof1[n] = ind; }
void setRungeKuttaIndTofHit2(UChar_t n, Short_t ind) { rkIndTof2[n] = ind; }
void setRungeKuttaIndRpcClst(UChar_t n, Short_t ind) { rkIndRpc[n] = ind; }
void setRungeKuttaInd(Short_t _rungeKuttaInd) { rungeKuttaInd = _rungeKuttaInd; }
void setKalmanFilterInd(Int_t _kalmanFilterInd) {kalmanFilterInd = _kalmanFilterInd; }
void setKalmanFilterIndShowerHit(UChar_t n, Short_t ind) { kfIndShower[n] = ind; }
void setKalmanFilterIndEmcCluster(UChar_t n, Short_t ind) { kfIndShower[n] = ind; }
void setKalmanFilterIndTofClst (UChar_t n, Short_t ind) { kfIndTofCl[n] = ind; }
void setKalmanFilterIndTofHit1 (UChar_t n, Short_t ind) { kfIndTof1[n] = ind; }
void setKalmanFilterIndTofHit2 (UChar_t n, Short_t ind) { kfIndTof2[n] = ind; }
void setKalmanFilterIndRpcClst (UChar_t n, Short_t ind) { kfIndRpc[n] = ind; }
void setInnerFake(Bool_t fake) { isFakeInner=fake;}
void setOuterFake(Bool_t fake) { isFakeOuter=fake;}
void setEmcClusterFlag(void) { flag |= 1;}
void setShowerHitFlag(void) { flag &= ~1;}
Char_t getSector(void) const {return sector;}
Int_t getTrkCandInd(void) const {return trkCandInd;}
Int_t getOwnIndex(void) const {return ownIndex;}
Int_t getMetaArrSize(void) const {return META_TAB_SIZE;}
Bool_t isEmcCluster(void) const {return (flag&1)==1;}
Bool_t isShowerHit(void) const {return (flag&1)==0;}
Bool_t isEmcClustValid(UChar_t n) const {return isEmcCluster() && n<nShrHits;}
Bool_t isShowerHitValid(UChar_t n) const {return isShowerHit() && n<nShrHits;}
Int_t getSystem(void) const;
UChar_t getNRpcClusters(void) const {return nRpcClust;}
UChar_t getNShrHits(void) const {return isShowerHit() ? nShrHits : 0;}
UChar_t getNEmcClusters(void) const {return isEmcCluster() ? nShrHits : 0;}
UChar_t getNTofHits(void) const {return nTofHits;}
Short_t getRpcClstInd(UChar_t n) const {return n<nRpcClust ? rpcClstInd[n] : -1;}
Short_t getShowerHitInd(UChar_t n) const {return isShowerHitValid(n) ? shrHitInd[n] : -1;}
Short_t getEmcClusterInd(UChar_t n) const {return isEmcClustValid(n) ? shrHitInd[n] : -1;}
Short_t getTofClstInd(UChar_t n) const {return n<nTofHits ? tofClstInd[n] : -1;}
Short_t getTofHit1Ind(UChar_t n) const {return n<nTofHits ? tofHit1Ind[n] : -1;}
Short_t getTofHit2Ind(UChar_t n) const {return n<nTofHits ? tofHit2Ind[n] : -1;}
Float_t getRpcClstQuality(UChar_t n) const {return n<nRpcClust ? rpcQuality[n] : -1.f;}
Float_t getShowerHitQuality(UChar_t n) const {return isShowerHitValid(n) ? shrQuality[n] : -1.f;}
Float_t getEmcClusterQuality(UChar_t n) const {return isEmcClustValid(n) ? shrQuality[n] : -1.f;}
Float_t getTofClstQuality(UChar_t n) const {return n<nTofHits ? tofClstQuality[n] : -1.f;}
Float_t getTofHit1Quality(UChar_t n) const {return n<nTofHits ? tofHit1Quality[n] : -1.f;}
Float_t getTofHit2Quality(UChar_t n) const {return n<nTofHits ? tofHit2Quality[n] : -1.f;}
Float_t getRpcClstDX(UChar_t n) const {return n<nRpcClust ? rpcDX[n] : -1000.f;}
Float_t getShowerHitDX(UChar_t n) const {return isShowerHitValid(n) ? shrDX[n] : -1000.f;}
Float_t getEmcClusterDX(UChar_t n) const {return isEmcClustValid(n) ? shrDX[n] : -1000.f;}
Float_t getTofClstDX(UChar_t n) const {return n<nTofHits ? tofClstDX[n] : -1000.f;}
Float_t getTofHit1DX(UChar_t n) const {return n<nTofHits ? tofHit1DX[n] : -1000.f;}
Float_t getTofHit2DX(UChar_t n) const {return n<nTofHits ? tofHit2DX[n] : -1000.f;}
Float_t getRpcClstDY(UChar_t n) const {return n<nRpcClust ? rpcDY[n] : -1000.f;}
Float_t getShowerHitDY(UChar_t n) const {return isShowerHitValid(n) ? shrDY[n] : -1000.f;}
Float_t getEmcClusterDY(UChar_t n) const {return isEmcClustValid(n) ? shrDY[n] : -1000.f;}
Float_t getTofClstDY(UChar_t n) const {return n<nTofHits ? tofClstDY[n] : -1000.f;}
Float_t getTofHit1DY(UChar_t n) const {return n<nTofHits ? tofHit1DY[n] : -1000.f;}
Float_t getTofHit2DY(UChar_t n) const {return n<nTofHits ? tofHit2DY[n] : -1000.f;}
Int_t getSplineInd(void) const {return splineInd;}
Short_t getRungeKuttaIndShowerHit(UChar_t n) const { return isShowerHitValid(n) ? rkIndShower[n] : -1; }
Short_t getRungeKuttaIndEmcCluster(UChar_t n) const { return isEmcClustValid(n) ? rkIndShower[n] : -1; }
Short_t getRungeKuttaIndTofClst(UChar_t n) const { return n < nTofHits ? rkIndTofCl[n] : -1; }
Short_t getRungeKuttaIndTofHit1(UChar_t n) const { return n < nTofHits ? rkIndTof1[n] : -1; }
Short_t getRungeKuttaIndTofHit2(UChar_t n) const { return n < nTofHits ? rkIndTof2[n] : -1; }
Short_t getRungeKuttaIndRpcClst(UChar_t n) const { return n < nRpcClust ? rkIndRpc[n] : -1; }
Short_t getRungeKuttaInd() const { return rungeKuttaInd; }
Short_t getKalmanFilterInd(void) const {return kalmanFilterInd;}
Short_t getKalmanFilterIndShowerHit(UChar_t n) const { return isShowerHitValid(n) ? kfIndShower[n] : -1; }
Short_t getKalmanFilterIndEmcCluster(UChar_t n) const { return isEmcClustValid(n) ? kfIndShower[n] : -1; }
Short_t getKalmanFilterIndTofClst (UChar_t n) const { return n < nTofHits ? kfIndTofCl[n] : -1; }
Short_t getKalmanFilterIndTofHit1 (UChar_t n) const { return n < nTofHits ? kfIndTof1[n] : -1; }
Short_t getKalmanFilterIndTofHit2 (UChar_t n) const { return n < nTofHits ? kfIndTof2[n] : -1; }
Short_t getKalmanFilterIndRpcClst (UChar_t n) const { return n < nRpcClust ? kfIndRpc[n] : -1; }
UChar_t getNCandForRich(void) const {return nRichId;}
UChar_t getNCandForIPU(void) const {return nRichIPUId;}
Short_t getARichInd(UChar_t id) const {return id<RICH_TAB_SIZE ? richInd[id] : -1;}
Short_t getARichIPUInd(UChar_t id) const {return id<RICH_TAB_SIZE ? richIPUInd[id] : -1;}
Bool_t isFake() { return isFakeInner|isFakeOuter;}
Bool_t isInnerFake() { return isFakeInner;}
Bool_t isOuterFake() { return isFakeOuter;}
void print(void);
private:
void setDefForRest(void);
ClassDef(HMetaMatch2,2)
};
#endif
| [
"w.esmail@fz-juelich.de"
] | w.esmail@fz-juelich.de |
365dc5fd339e3a908476e4c8ecdfe076fc7f8605 | 503536cea2777de46fc8f740eaee9448085bf379 | /38_primeCombination.cpp | 9680b79ee8a1cb0bff1794c2cb7772e87e896bb5 | [] | no_license | chenyzcs/HuaweiProblem | 55c2cb731594326d7f55f0b73d289cab757e4009 | 33776076c569f4e88c70e02cf7f28870d0820625 | refs/heads/master | 2021-01-06T20:43:41.429387 | 2017-08-21T09:17:38 | 2017-08-21T09:17:38 | 99,547,868 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,261 | cpp | #include <iostream>
#include <vector>
using namespace std;
vector<int> getPrimer(int n)
{
if (n <= 2)
return {};
vector<int> ret;
for (int i = 2; i < n; i++)
{
bool isPrimer = true;
for (int j = 2; j < i; j++)
{
if (i % j == 0)
isPrimer = false;
}
if (isPrimer)
ret.push_back(i);
}
return ret;
}
vector<int> combinePrimer(int tag)
{
if (tag < 2)
return {};
auto primer = getPrimer(tag);
if (primer.empty())
return {};
vector<int> aim(2, 0);
int step = 0xffff;
int sum;
int i = 0, j = primer.size() - 1;
while (i < j)
{
sum = primer[i] + primer[j];
if (sum > tag)
{
j--;
}
else if (sum < tag)
i++;
else
{
int tmp = j - i;
if (tmp < step)
{
step = tmp;
aim[0] = primer[i];
aim[1] = primer[j];
}
j--;
}
}
return aim;
}
int main()
{
int n;
while (cin >> n)
{
auto aim = combinePrimer(n);
cout << aim[0] << endl;
cout << aim[1] << endl;
}
return 0;
} | [
"chenyzcs@163.com"
] | chenyzcs@163.com |
9818c606f864c5e14d2dec04508f04dfcb1031bc | d1348d2c999d29e4dd33a99f77e52010e45d81d0 | /CCRadioMenu.cpp | ae8cec148e1e13cc0298d053f05c672ea1eb56fc | [] | no_license | lotussfly/flygame | c50879742bc94b3b1bca3c87aeb9d7c294b4caf0 | 2b57f74f974d1844afb0f43a6bb602b093c06b70 | refs/heads/master | 2016-08-02T22:31:21.470009 | 2015-01-18T07:39:08 | 2015-01-18T07:39:08 | 29,419,229 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,052 | cpp | //
// CCRadioMenu.cpp
// SceneHello
//
// Created by Orangef on 12-12-24.
//
//
#include "CCRadioMenu.h"
using namespace cocos2d;
CCRadioMenu* CCRadioMenu::create()
{
return static_cast<CCRadioMenu*>(CCMenu::create());
}
/*
CCRadioMenu * CCRadioMenu::create(CCMenuItem* item, ...)
{
va_list args;
va_start(args,item);
CCRadioMenu *pRet = CCRadioMenu::createWithItems(item, args);
va_end(args);
return pRet;
}
*/
/*
CCRadioMenu* CCRadioMenu::createWithItems(CCMenuItem* item, va_list args)
{
//CCArray* pArray = NULL;
cocos2d::Vector<MenuItem*> pArray;
pArray.clear();
if( item )
{
// pArray = CCArray::create(item, NULL);
pArray.pushBack(item);
CCMenuItem *i = va_arg(args, MenuItem*);
while(i)
{
pArray.pushBack(i);
i = va_arg(args, MenuItem*);
}
}
return CCRadioMenu::createWithArray(pArray);
}
*/
/*
CCRadioMenu* CCRadioMenu::createWithArray(const cocos2d::Vector<CCMenuItem*>& arrayOfItems)
{
CCRadioMenu *pRet = new CCRadioMenu();
if (pRet && pRet->initWithArray(arrayOfItems))
{
pRet->autorelease();
}
else
{
CC_SAFE_DELETE(pRet);
}
return pRet;
}
*/
void CCRadioMenu::setSelectedItem_(CCMenuItem *item){
_selectedItem = NULL;
_selectedItem = item;
}
bool CCRadioMenu::onTouchBegan(CCTouch *pTouch, CCEvent *pEvent){
if (_state != kCCMenuStateWaiting) return false;
// CCMenuItem *curSelection = this->itemForTouch(pTouch);
CCMenuItem *curSelection = this->getItemForTouch(pTouch);
if (curSelection) {
curSelection->selected();
_curHighlighted = curSelection;
if (_curHighlighted) {
if (_selectedItem && _selectedItem != curSelection) {
_selectedItem->unselected();
}
_state = kCCMenuStateTrackingTouch;
return true;
}
}
return false;
}
void CCRadioMenu::onTouchEnded(CCTouch *pTouch, CCEvent *pEvent){
CCAssert(_state == kCCMenuStateTrackingTouch, "[Menu ccTouchEnded] -- invalid state");
//CCMenuItem *curSelection = this->itemForTouch(pTouch);
CCMenuItem *curSelection = this->getItemForTouch(pTouch);
if (curSelection != _curHighlighted && curSelection != NULL) {
_selectedItem->selected();
_curHighlighted->unselected();
_curHighlighted = NULL;
_state = kCCMenuStateWaiting;
return;
}
_selectedItem = _curHighlighted;
_curHighlighted->activate();
_curHighlighted = NULL;
_state = kCCMenuStateWaiting;
}
void CCRadioMenu::onTouchCancelled(CCTouch *pTouch, CCEvent *pEvent){
CCAssert(_state == kCCMenuStateTrackingTouch, "[Menu ccTouchCancelled] -- invalid state");
_selectedItem->selected();
_curHighlighted->unselected();
_curHighlighted = NULL;
_state = kCCMenuStateWaiting;
}
void CCRadioMenu::onTouchMoved(CCTouch *pTouch, CCEvent *pEvent){
CCAssert(_state == kCCMenuStateTrackingTouch, "[Menu ccTouchMoved] -- invalid state");
//CCMenuItem *curSelection = this->itemForTouch(pTouch);
CCMenuItem *curSelection = this->getItemForTouch(pTouch);
if (curSelection != _curHighlighted && curSelection != NULL) {
_curHighlighted->unselected();
curSelection->selected();
_curHighlighted = curSelection;
return;
}
} | [
"lotussfly@gmail.com"
] | lotussfly@gmail.com |
e02557f45864a36099108306ec3dba3bb5147a66 | d32e432de919836e69855462a19f2b8daeac3cc5 | /gui.h | 789cd2e6f957d03fcda826d61f5d3c00423fde19 | [] | no_license | hi2512/OGREFighter | 3b7d6dd940985f7da9288bf5b4e33843c859bbc2 | 4878cd6397653a3be217f28aec1657ba9463f182 | refs/heads/master | 2021-10-28T08:52:10.007164 | 2019-04-23T06:38:48 | 2019-04-23T06:38:48 | 156,812,856 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 820 | h | #ifndef _GUI_H_
#define _GUI_H_
#include <Ogre.h>
#include <ImguiManager.h>
#include "state.h"
//#include "Multiplayer.h"
/*
class NetBase;
class NetClient;
class NetServer;
*/
class GameGui {
GameState* state;
public:
GameGui(GameState* gameState){
state = gameState;
}
~GameGui(void){}
void showTest();
void showScore();
bool showGameStart();
void showLoseScreen();
void showWinScreen();
bool showMultiplaySelect();
void showWaitingOnPlayers();
void showSingleSelect();
void showFrameCount(float);
void showCamPos();
void showInputBuffer();
void showComboCounter1();
void showComboCounter2();
void showHealth1();
void showHealth2();
void showMeter1();
void showMeter2();
void showTime();
bool showCharacterSelect1();
bool showCharacterSelect2();
bool showStageSelect();
};
#endif
| [
"hiken2512@gmail.com"
] | hiken2512@gmail.com |
36edea5d1f0f546945d4d1153d749486adaace39 | 64be678ca92ae1d57a7b53b8354a61d9a84c52c7 | /src/directory_storage/StorageInterface.h | eb1fbc301c6f737c3a2ea7dba6c1e7a5fcad0e4f | [] | no_license | RodionShyshkin/DirectoryAccessChecker | 6ba0d0d8f66e2c0f5bb11d1cb227f8671ebc7ea0 | 24298dc543fe1299f41c80c3506312c4ef6b366a | refs/heads/master | 2023-01-03T13:01:08.852817 | 2020-11-03T04:13:12 | 2020-11-03T04:13:12 | 309,557,467 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 622 | h | //
// Created by Rodion Shyshkin on 03.11.2020.
//
#ifndef DIRECTORYACCESSCHECKER_SRC_DIRECTORY_STORAGE_STORAGEINTERFACE_H_
#define DIRECTORYACCESSCHECKER_SRC_DIRECTORY_STORAGE_STORAGEINTERFACE_H_
#include <filesystem>
/*
* \brief Interface of storage,
* which contains all busy directories.
*
* @author Rodion Shyshkin
*/
class StorageInterface {
public:
virtual ~StorageInterface() = default;
public:
virtual bool AddDir(const std::filesystem::path& path) = 0;
virtual bool RemoveDir(const std::filesystem::path& path) = 0;
};
#endif //DIRECTORYACCESSCHECKER_SRC_DIRECTORY_STORAGE_STORAGEINTERFACE_H_
| [
"rodion.shyshkin@teamdev.com"
] | rodion.shyshkin@teamdev.com |
f9036ce5d2d1f27899bbafea399e5dce9e9b6f7b | c61d2d8f16615883627db04e95d7fc59ace95537 | /Ano4Sem1/TCC/Exemplos/projgriddemo/packmk2/source/dxmouse.h | 43624c44b9088c7be29bf071bb054d7a1f34f926 | [] | no_license | rodrigo-mendonca/Faculdade | 986469da31825ae796f0f7e7a40bb2befb7e154e | f0fb4ed8ffacd283faee3e065eef735c6a818bcd | refs/heads/master | 2021-01-25T05:16:37.161818 | 2015-09-19T18:08:48 | 2015-09-19T18:08:48 | 35,241,246 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,009 | h | #include <dinput.h>
#include <d3dx9.h>
extern unsigned char keyBuffer[256];
#define MOUSE_DOWN(button) (mouseState.rgbButtons[button] & 0x80)
/* Mouse constants */
#define MOUSE_LEFT 0
#define MOUSE_RIGHT 1
#define MOUSE_MIDDLE 2
class dxmouse{
private:
LPDIRECTINPUT8 lpdi; // Main DirectInput Object
LPDIRECTINPUTDEVICE8 lpdiKeyboard; // Keyboard's DirectInput Device
LPDIRECTINPUTDEVICE8 lpdiMouse; // Mouse's DirectInput Device (New)
HWND hWnd;
HINSTANCE hInstance;
void GetWheelMovement(void); // (New)
void GetMouseMovement(void); // (New)
public:
int x; // Mouse Positions (New)
int y; // (New)
int z; // For Wheel Movement (New)
bool Init(void); // (Edited)
void Shutdown(void); // (Edited)
void Update(void); // (Edited)
bool mousedown(int button);
dxmouse(HWND hWnd, HINSTANCE hInstance)
{
this->hWnd = hWnd;
this->hInstance = hInstance;
memset(&keyBuffer, 0, sizeof(unsigned char[256]));
}
~dxmouse()
{ }
}; | [
"rodrigo-mendonca@outlook.com.br"
] | rodrigo-mendonca@outlook.com.br |
09f1e8eb4d01fd4f4d5801778b14fac95387f6dc | caf93a6534419c1ecbb00897d58f21d46eaec81e | /Sources code/oscilloscope/miniscope/device/MiniscopeDeviceInterface.h | 0d6b0460701c32447d31b94fcc65fea6d923ab84 | [] | no_license | opus506/2_dolar_oscilloscope | 4916279f9d5be349ed5b096886a918ebed8563b6 | ff6f2fc56f72beb2d0c6728fabc4f471a26e7d34 | refs/heads/master | 2020-03-27T17:14:58.734999 | 2018-08-30T16:52:16 | 2018-08-30T16:52:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,912 | h | /** \file MiniscopeDeviceInterface.cpp
* \brief Encapsulation of "C" interface to input device dll
*/
/* Copyright (C) 2008-2009 Tomasz Ostrowski <tomasz.o.ostrowski at gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
* Miniscope is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
//---------------------------------------------------------------------------
#ifndef MiniscopeDeviceInterfaceH
#define MiniscopeDeviceInterfaceH
//---------------------------------------------------------------------------
#include "MiniscopeDevice.h"
#include "MiniscopeDeviceCapabilities.h"
#include "Data.h"
#include "Calibration.h"
#include "gnugettext.hpp"
#include <System.hpp>
#include <Forms.hpp>
#include <vector>
#include <set>
/** \brief Info about dll device library */
struct DllInfo
{
AnsiString name;
AnsiString description;
AnsiString file_version; ///< file version (as reported by OS)
struct S_DEVICE_DLL_INTERFACE ver;
};
/** \brief Info about current connection state
*/
struct ConnectionInfo
{
enum E_CONNECTION_STATE state;
AnsiString msg;
};
/** \brief Encapsulates dll plugin
*/
class DeviceInterface
{
private:
enum E_LIB_STATUS
{
E_OK = 0,
E_LOADFAILED, ///< failed to load library - library not found or other dll dependency not met
E_NOTVALID, ///< does not look like a plugin library
E_INCOMPATIBLE_VER ///< incompatible plugin interface version
};
/** \brief Verify if dll looks correctly and fill dllinfo for valid dll
\return loading status
*/
static enum E_LIB_STATUS VerifyDll(AnsiString filename, struct DllInfo* const dllinfo);
/** \brief Add dll to list
*/
static void AddDll(const struct DllInfo &dllinfo);
static std::set<class DeviceInterface*> instances;
static AnsiString asDllDir;
AnsiString filename; ///< dll name (with full path)
HINSTANCE hInstance; ///< dll instance ptr
// dll function pointers
pfGetMiniscopeInterfaceDescription dllGetMiniscopeInterfaceDescription;
pfGetMiniscopeSettings dllGetMiniscopeSettings;
pfSaveMiniscopeSettings dllSaveMiniscopeSettings;
pfSetCallbacks dllSetCallbacks;
pfShowSettings dllShowSettings;
pfGetDeviceCapabilities dllGetDeviceCapabilities;
pfEnableChannel dllEnableChannel;
pfSetSensitivity dllSetSensitivity;
pfSetSamplingPeriod dllSetSamplingPeriod;
pfRun dllRun;
pfSetTriggerMode dllSetTriggerMode;
pfSetTriggerSource dllSetTriggerSource;
pfSetTriggerLevel dllSetTriggerLevel;
pfSetTriggerPosition dllSetTriggerPosition;
pfSetCouplingType dllSetCouplingType;
pfSetBufferSize dllSetBufferSize;
pfConnect dllConnect;
pfDisconnect dllDisconnect;
pfManualTrigger dllManualTrigger;
pfStoreCalibration dllStoreCalibration;
pfGetCalibration dllGetCalibration;
struct ConnectionInfo connInfo;
// CALLBACKS DEFINITIONS
typedef void (__closure *CallbackData)(void);
typedef void (__closure *CallbackConnect)(int state, const char *szMsgText);
typedef void (__closure *CallbackTrigger)(void);
public:
/** \brief Make list of valid dlls in supplied location
*/
static void EnumerateDlls(AnsiString dir);
/** \brief Refresh list of valid dlls in previously supplied location
*/
static void ReEnumerateDlls(void);
/** \brief Constructor
\param asDllName Name of dll used by object to communicate with device
*/
DeviceInterface(AnsiString asDllName);
~DeviceInterface();
int Load(void); ///< load dll (dll name was supplied to constructor)
/** Info about found device interface libraries */
static std::vector<DllInfo> dlls;
/** Ptr to structure describing device functionality. Actual structure is allocated
* by device library
*/
struct S_SCOPE_CAPABILITIES *capabilities;
CallbackData callbackData; ///< if set called when new data is received from device
CallbackConnect callbackConnect; ///< if set called when connection state changes
CallbackTrigger callbackTrigger; ///< if set called when device is triggered
struct S_SCOPE_SETTINGS settings;
/** Calibration data for each channel, for each sensitivity (2D array)
*/
std::vector< std::vector<struct DEV_CALIBRATION> > calibration;
Data upcoming; ///< state updated immediately when GUI state changes
int rx_progress; ///< upcoming frame buffer fill level (percentage)
// dll callbacks
static void __stdcall OnLog(void *cookie, const char *szText); ///< called to generate log in parent application
static void __stdcall OnConnect(void *cookie, int state, const char *szMsgText); ///< called on connection/disconnection of device
static void __stdcall OnData(void *cookie, void *buffer, unsigned int buffersize); ///< called to pass data (samples) to parent application
static void __stdcall OnTrigger(void *cookie); ///< called when device is triggered
/** \brief Show device settings window.
*
* Show device settings window. Miniscope doesn't manage any settigs related to input devices. Device dll
* is responsible for storing/restoring data and can supply it's own window for this settings.
*/
void ShowSettings(void) {
if (dllShowSettings)
dllShowSettings(Application->Handle);
}
/** \brief Connect device
*/
int Connect(void) {
if (dllConnect)
return dllConnect();
return 0;
}
/** \brief Disconnect device
*/
int Disconnect(void) {
if (dllDisconnect)
return dllDisconnect();
return 0;
}
/** \brief Enable/disable specified channel
*/
int EnableChannel(int channel, bool state) {
if (dllEnableChannel)
{
int status = dllEnableChannel(channel, state);
if (!status)
{
upcoming.getChannel(channel).bEnabled = state;
settings.pChannelEnable[channel] = state;
}
return status;
}
return -1;
}
/** \brief Set analog gain
\param sens index of new sensitivity value inside capabilities structure
\return 0 on successs
*/
int SetSensitivity(int channel, int sens) {
upcoming.getChannel(channel).fDivY = capabilities->fSensitivityLevels[sens];
//int test = calibration.size();
//int test2 = calibration[0].size();
upcoming.getChannel(channel).calibration = calibration[channel][sens];
if (dllSetSensitivity) {
int status = dllSetSensitivity(channel, sens);
if (!status)
settings.pSensitivity[channel] = sens;
return status;
}
return 0;
}
/** \brief Set sampling frequency
\param sampl index of new sampling period inside capabilities structure
\return 0 on successs
*/
int SetSampling(int sampl) {
upcoming.fOscDivX = capabilities->fSamplingPeriod[sampl];
if (dllSetSamplingPeriod) {
int status = dllSetSamplingPeriod(sampl);
if (!status)
settings.iSamplingPeriod = sampl;
return status;
}
return 0;
}
int Run(bool state);
int SetTriggerMode(int type) {
upcoming.trigger_mode = capabilities->iTriggerModes[type];
if (dllSetTriggerMode) {
int status = dllSetTriggerMode(type);
if (!status)
{
settings.eTriggerMode = capabilities->iTriggerModes[type];
}
return status;
}
return 0;
}
/** \brief Set required trigger type
\param channel source channel
\param type trigger type according to enum E_TRIGGER_TYPE
\return 0 on successs
*/
int SetTriggerType(int channel, int type) {
upcoming.trigger_type = capabilities->iTriggerTypes[type];
upcoming.trigger_source = channel;
if (dllSetTriggerSource) {
int status = dllSetTriggerSource(channel, type);
if (!status) {
settings.iTriggerSrcChannel = channel;
settings.eTriggerType = capabilities->iTriggerTypes[type];
}
return status;
}
return 0;
}
/** \brief Set level of trigger
\param level trigger level -100%...100%
\return 0 on successs
*/
int SetTriggerLevel(int level) {
if (dllSetTriggerLevel) {
int status = dllSetTriggerLevel(level);
if (!status)
settings.iTriggerLevel = level;
return status;
}
return 0;
}
/** \brief Set position of trigger inside data frame (pre-/posttriggering)
\param position position inside frame, 0%...100%
\return 0 on successs
*/
int SetTriggerPosition(int position) {
if (dllSetTriggerPosition) {
int status = dllSetTriggerPosition(position);
if (!status)
settings.iTriggerPosition = position;
return status;
}
return 0;
}
/** \brief Immediate trigger request
\return 0 on success
*/
int ManualTrigger(void) {
if (dllManualTrigger)
return dllManualTrigger();
return -1;
}
/** \brief Set device acquision buffer size. After each triggering receiving full buffer from device is expected
\param size size of buffer [samples]
*/
int SetBufferSize(int size) {
upcoming.buffer_size = capabilities->iBufferSizes[size];
if (dllSetBufferSize) {
int status = dllSetBufferSize(size);
if (!status)
settings.iBufferSize = capabilities->iBufferSizes[size];
return status;
}
return 0;
}
/** \brief Set coupling type (AC/DC..) for analog part of device
\param type index of coupling type inside capabilities structure
\return 0 on success
*/
int SetCouplingType(int channel, int type) {
upcoming.getChannel(channel).iCouplingType = settings.eCouplingType[type];
if (dllSetCouplingType) {
int status = dllSetCouplingType(channel, type);
if (!status)
settings.eCouplingType[channel] = capabilities->iCouplingType[type];
return status;
}
return 0;
}
/** \brief Get default or saved in configuration settings for device
*/
int GetSettings(struct S_SCOPE_SETTINGS* settings)
{
if (dllGetMiniscopeSettings)
return dllGetMiniscopeSettings(settings);
return -1;
}
/** \brief Save configuration settings for device
*/
int SaveSettings(struct S_SCOPE_SETTINGS* settings)
{
if (dllSaveMiniscopeSettings)
return dllSaveMiniscopeSettings(settings);
return -1;
}
/** \brief Save calibration data for specified sensitivity range
\param range sensitivity range (index from capabilities structure)
\param offset value (int LSB) corresponding to 0 V
\param gain real_sensitivity/capabilities_sensitivity
\return 0 on success
*/
int StoreCalibration(int channel, int range, int offset, float gain)
{
if (dllStoreCalibration)
return dllStoreCalibration(channel, range, offset, gain);
return -1;
}
/** \brief Read calibration data
\param range sensitivity range (index from capabilities structure)
\param offset value (int LSB) corresponding to 0 V
\param gain real_sensitivity/capabilities_sensitivity
\return 0 on success
*/
int GetCalibration(int channel, int range, int* const offset, float* const gain)
{
if (dllGetCalibration)
return dllGetCalibration(channel, range, offset, gain);
return -1;
}
bool hasCalibration(void) {
if (dllGetCalibration && dllStoreCalibration)
return true;
return false;
}
bool hasTriggerPositionControl(void) {
if (this->dllSetTriggerPosition)
return true;
return false;
}
bool hasChannelEnable(void) {
if (this->dllEnableChannel)
return true;
return false;
}
bool hasManualTrigger(void) {
if (this->dllManualTrigger)
return true;
return false;
}
const struct ConnectionInfo& GetConnectionInfo(void) {
return connInfo;
}
static AnsiString GetTriggerTypeName(enum E_TRIGGER_TYPE type);
static AnsiString GetTriggerModeName(enum E_TRIGGER_MODE mode);
static AnsiString GetCouplingTypeName(enum E_COUPLING_TYPE type);
};
#endif
| [
"karolprzybylak1@gmail.com"
] | karolprzybylak1@gmail.com |
bce4303bd4518c6600d8d31d72618a5f37427f0a | c2d871cba94b0d683586451d11b2d9070c85eed4 | /_share/print.h | d877474eced96a1074894e438baca19250bbcad0 | [] | no_license | YGBM/demo5c | 4aa83a7d978ab4c401795be1dd046690429ddc8b | 0bb885e0e9e8d88b6e41eb2bd1f5a43acb1d8870 | refs/heads/master | 2023-05-14T02:13:53.098785 | 2021-05-22T15:23:24 | 2021-05-22T15:23:24 | 366,353,810 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,735 | h | #pragma once
/******************************************************************************************
* Data Structures in C++
* ISBN: 7-302-33064-6 & 7-302-33065-3 & 7-302-29652-2 & 7-302-26883-3
* Junhui DENG, deng@tsinghua.edu.cn
* Computer Science & Technology, Tsinghua University
* Copyright (c) 2003-2020. All rights reserved.
******************************************************************************************/
#include <stdio.h> //采用C风格精细控制输出格式
//#include "huffman/huffChar.h" //Huffman超字符
#include "binTree/BinTree.h"//二叉树
//#include "Huffman/HuffTree.h" //Huffman树
#include "BST/BST.h" //二叉搜索树
//#include "AVL/AVL.h" //AVL树
//#include "Splay/Splay.h" //伸展树
//#include "redBlack/RedBlack.h" //红黑树
#include "BTree/BTree.h" //二叉搜索树
//#include "Entry/Entry.h" //词条
//#include "Skiplist/Quadlist.h" //四叉表
//#include "Skiplist/Skiplist.h" //跳转表
//#include "Hashtable/Hashtable.h" //散列表
//#include "PQ_List/PQ_List.h" //基于列表实现的优先级队列
//#include "PQ_ComplHeap/PQ_ComplHeap.h" //基于完全堆实现的优先级队列
//#include "PQ_LeftHeap/PQ_LeftHeap.h" //基于左式堆实现的优先级队列
//#include "graph/Graph.h" //图
//#include "graphMatrix/GraphMatrix.h" //基于邻接矩阵实现的图
/******************************************************************************************
* 数据元素、数据结构通用输出接口
******************************************************************************************/
static void print ( char* x ) { printf ( " %s", x ? x : "<NULL>" ); } //字符串特别处理
static void print ( const char* x ) { printf ( " %s", x ? x : "<NULL>" ); } //字符串特别处理
class UniPrint {
public:
static void p ( int );
static void p ( float );
static void p ( double );
static void p ( char );
// static void p ( HuffChar& ); //Huffman(超)字符
// static void p ( VStatus ); //图顶点的状态
// static void p ( EType ); //图边的类型
// template <typename K, typename V> static void p ( Entry<K, V>& ); //Entry
template <typename T> static void p ( BinNode<T>& ); //BinTree节点
template <typename T> static void p ( BinTree<T>& ); //二叉树
template <typename T> static void p ( BTree<T>& ); //B-树
template <typename T> static void p ( BST<T>& ); //BST
// template <typename T> static void p ( AVL<T>& ); //AVL
// template <typename T> static void p ( RedBlack<T>& ); //RedBlack
// template <typename T> static void p ( Splay<T>& ); //Splay
// template <typename T> static void p ( Quadlist<T>& ); //Quadlist
// template <typename K, typename V> static void p ( Skiplist<K, V>& ); //Skiplist
// template <typename K, typename V> static void p ( Hashtable<K, V>& ); //Hashtable
// template <typename T> static void p ( PQ_List<T>& ); //PQ_List
// template <typename T> static void p ( PQ_ComplHeap<T>& ); //PQ_ComplHeap
// template <typename T> static void p ( PQ_LeftHeap<T>& ); //PQ_LeftHeap
// template <typename Tv, typename Te> static void p ( GraphMatrix<Tv, Te>& ); //Graph
template <typename T> static void p ( T& ); //向量、列表等支持traverse()遍历操作的线性结构
template <typename T> static void p ( T* s ) //所有指针
{ s ? p ( *s ) : print ( "<NULL>" ); } //统一转为引用
}; //UniPrint
//template <typename T> static void print ( T* x ) { x ? print ( *x ) : printf ( " <NULL>" ); }
template <typename T> static void print ( T& x ) { UniPrint::p ( x ); }
template <typename T> static void print ( const T& x ) { UniPrint::p ( x ); } //for Stack
#include "print_implementation.h" | [
"fuzusheng@gmail.com"
] | fuzusheng@gmail.com |
fd76f7be9556f7292829430fd452796a9255fdcd | bdc291a3a064c9eba540c61028f090848515a358 | /src/regexp/regexpmanager.fwd.hpp | 0c31dcd0e83f38d9a8ee7dc516bd6a66c21afb8e | [] | no_license | bjornjohansson/ircbot | 36661644a064f9549b3e7a21a05ae60ed2c02f1d | da6b726d50c0d6adff0c2cfc3aab96f695ba66b4 | refs/heads/master | 2021-01-18T23:16:15.139763 | 2016-05-02T03:42:18 | 2016-05-02T03:42:18 | 4,683,081 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21 | hpp | class RegExpManager;
| [
"bjorn@fiskbil.org"
] | bjorn@fiskbil.org |
21b532463697ea7c660e254c4df6f3be56f4017b | 2fcc9ad89cf0c85d12fa549f969973b6f4c68fdc | /SampleMathematics/IntersectInfiniteCylinders/IntersectInfiniteCylinders.h | 224ce0e0632844964f977540d8ae026babab4316 | [
"BSL-1.0"
] | permissive | nmnghjss/WildMagic | 9e111de0a23d736dc5b2eef944f143ca84e58bc0 | b1a7cc2140dde23d8d9a4ece52a07bd5ff938239 | refs/heads/master | 2022-04-22T09:01:12.909379 | 2013-05-13T21:28:18 | 2013-05-13T21:28:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,104 | h | // Geometric Tools, LLC
// Copyright (c) 1998-2012
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.7.0 (2011/08/29)
#ifndef INTERSECTINFINITECYLINDERS_H
#define INTERSECTINFINITECYLINDERS_H
#include "Wm5WindowApplication3.h"
using namespace Wm5;
class IntersectInfiniteCylinders : public WindowApplication3
{
WM5_DECLARE_INITIALIZE;
WM5_DECLARE_TERMINATE;
public:
IntersectInfiniteCylinders ();
virtual bool OnInitialize ();
virtual void OnTerminate ();
virtual void OnIdle ();
virtual bool OnKeyDown (unsigned char key, int x, int y);
protected:
void CreateScene ();
Float4 mTextColor;
NodePtr mScene;
WireStatePtr mWireState;
TriMeshPtr mCylinder0, mCylinder1;
float mRadius0, mRadius1, mHeight, mAngle;
float mC0, mW1, mW2;
PolysegmentPtr mCurve0, mCurve1;
VisibleSet mVisible;
};
WM5_REGISTER_INITIALIZE(IntersectInfiniteCylinders);
WM5_REGISTER_TERMINATE(IntersectInfiniteCylinders);
#endif
| [
"bazhenovc@bazhenovc-laptop"
] | bazhenovc@bazhenovc-laptop |
6d36dd37a61586e6dd98e9a3354059f5167081c2 | dbd4be4155fa227e1268b091147c4437a2f215be | /C++/MFTI/comand/TackC.cpp | ad99d9a668b68498aafe151f0ace70bb49b2bf97 | [] | no_license | pshpis/School_olymp | 5bdf8e885050f80e68c8407940c7289d3d413592 | 723b6121cc1a0746d0911c5a79076d9589a75839 | refs/heads/main | 2023-03-24T08:34:47.600204 | 2021-03-17T08:20:39 | 2021-03-17T08:20:39 | 348,629,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,762 | cpp |
#include <bits/stdc++.h>
using namespace std;
int n;
inline int left_(int x) {
return (x - 1 + n) % n;
}
inline int right_(int x) {
return (x + 1) % n;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int k;
cin >> n >> k;
vector<int> a(n);
vector<pair<int, int>> sorted(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
sorted[i].first = a[i];
sorted[i].second = i;
}
sort(sorted.begin(), sorted.end());
unordered_map<int, int> old, new_;
vector<int> ans(n, -1);
for (int j = 0; j < n; ++j) {
old[sorted[j].second] = 1;
for (int i = 0; i < k; ++i) {
if (n % 2 == 1 && old.size() == n) {
break;
} else if (n % 2 == 0 && old.size() == n / 2) {
if ((k - i) % 2 == 1) {
for (auto ku : old) {
new_[left_(ku.first)] = 1;
new_[right_(ku.first)] = 1;
}
old = new_;
new_.clear();
}
break;
}
for (auto ku : old) {
new_[left_(ku.first)] = 1;
new_[right_(ku.first)] = 1;
}
old = new_;
new_.clear();
}
for (auto ku : old) {
if (ans[ku.first] == -1) {
ans[ku.first] = sorted[j].first;
}
}
bool o = true;
old.clear();
for (int i = 0; i < n; ++i) {
if (ans[i] == -1) {
o = false;
}
}
if (o) {
break;
}
}
for (int i = 0; i < n; ++i) {
cout << ans[i] << " ";
}
}
| [
"51034972+pshpis@users.noreply.github.com"
] | 51034972+pshpis@users.noreply.github.com |
5d3c160b8839e08eb5a0baf5eaac311fb209218c | 639a29bf86735055a92328718fe74b04aa5fb529 | /generate_tables/memory_layout.inl | 8e4fec50649b89bc0abed4c1cbb17d661df67be7 | [
"Unlicense"
] | permissive | lshamis/FastPokerHandEval | 57dbdd5ac84e0698828ce95724ce5929c0b1d9ae | da5041f4b2cc5ebb55d733ffeef4d399c34feaf7 | refs/heads/master | 2020-03-09T09:23:40.489039 | 2019-05-15T20:22:00 | 2019-05-15T20:22:00 | 128,711,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,996 | inl | #include <queue>
#include <stack>
namespace poker_eval {
template <typename Collection, typename T>
bool has_key(const Collection& c, const T& k) {
return c.find(k) != c.end();
}
template <uint8_t hand_size>
std::vector<EncodedHand> dfs_memory_order(const FSM& fsm) {
std::unordered_map<EncodedHand, uint8_t> depth = {{-1, 0}};
std::vector<EncodedHand> order;
std::stack<std::pair<HandOrScore /* parent */, HandOrScore /* child */>> dfs;
dfs.push({-1, 0});
while (!dfs.empty()) {
auto pc = dfs.top();
auto parent = pc.first;
auto child = pc.second;
dfs.pop();
if (!has_key(fsm, child) || has_key(depth, child) || depth[parent] >= hand_size) {
continue;
}
order.push_back(child);
depth[child] = depth[parent] + 1;
for (Card card = 0; card < 52; card++) {
dfs.push({child, fsm.at(child)[card]});
}
}
return order;
}
template <uint8_t>
std::vector<EncodedHand> bfs_memory_order(const FSM& fsm) {
std::unordered_set<EncodedHand> seen_hands;
std::vector<EncodedHand> order;
std::queue<HandOrScore> bfs;
bfs.push(0);
while (!bfs.empty()) {
HandOrScore hand = bfs.front();
bfs.pop();
if (!has_key(fsm, hand) || has_key(seen_hands, hand)) {
continue;
}
order.push_back(hand);
seen_hands.insert(hand);
for (Card card = 0; card < 52; card++) {
bfs.push(fsm.at(hand)[card]);
}
}
return order;
}
namespace {
template <uint8_t hand_size>
std::pair<std::vector<EncodedHand>, std::vector<EncodedHand>> veb_memory_order_helper(
const FSM& fsm,
HandOrScore root,
std::unordered_set<EncodedHand>& seen_hands) {
if (has_key(seen_hands, root)) {
return {{}, {}};
}
auto order_next = veb_memory_order_helper<hand_size / 2>(fsm, root, seen_hands);
auto order = order_next.first;
std::vector<EncodedHand> next;
for (auto lower_root : order_next.second) {
auto lower_order_next = veb_memory_order_helper<hand_size - (hand_size / 2)>(fsm, lower_root, seen_hands);
auto& lower_order = lower_order_next.first;
auto& lower_next = lower_order_next.second;
order.insert(order.end(), lower_order.begin(), lower_order.end());
next.insert(next.end(), lower_next.begin(), lower_next.end());
}
return {order, next};
}
template <>
std::pair<std::vector<EncodedHand>, std::vector<EncodedHand>> veb_memory_order_helper<1>(
const FSM& fsm,
HandOrScore root,
std::unordered_set<EncodedHand>& seen_hands) {
if (has_key(seen_hands, root)) {
return {{}, {}};
}
seen_hands.insert(root);
std::vector<EncodedHand> next;
for (Card card = 0; card < 52; card++) {
next.push_back(fsm.at(root)[card]);
}
return {{root}, next};
}
} // namespace
template <uint8_t hand_size>
std::vector<EncodedHand> veb_memory_order(const FSM& fsm) {
std::unordered_set<EncodedHand> seen_hands;
return veb_memory_order_helper<hand_size>(fsm, 0, seen_hands).first;
}
template <uint8_t max_hand_size>
std::vector<uint32_t> flatten_fsm(const FSM& fsm,
const std::vector<EncodedHand>& order) {
assert(fsm.size() == order.size());
assert(order[0] == 0);
std::unordered_map<uint32_t, EncodedHand> idx_to_hand;
std::unordered_map<EncodedHand, uint32_t> hand_to_idx;
uint32_t next_idx = 0;
for (EncodedHand hand : order) {
idx_to_hand[next_idx] = hand;
hand_to_idx[hand] = next_idx;
next_idx += 52;
}
std::vector<uint32_t> memory(next_idx);
for (auto&& pair : hand_to_idx) {
EncodedHand hand = pair.first;
uint32_t idx = pair.second;
if (Hand::decode(hand).size + 1u == max_hand_size) {
for (Card card = 0; card < 52; card++) {
Score score = fsm.at(hand)[card];
memory[idx + card] = score;
}
} else {
for (Card card = 0; card < 52; card++) {
EncodedHand next_hand = fsm.at(hand)[card];
memory[idx + card] = hand_to_idx[next_hand];
}
}
}
return memory;
}
} // namespace poker_eval
| [
"leonid.shamis@gmail.com"
] | leonid.shamis@gmail.com |
563c6c2d44005ed7ed35794bea33cfeb9ac9c17f | 6b0d07267aa05f1bb591df68bf19c99400c92793 | /include/djah/debug/core_logger.hpp | 8db9b1459851e448c92835424d736ed0647d99c9 | [] | no_license | H-EAL/djah | 974d8a6ed902d9c47c6f2b4415b676feda259978 | bef3707708ebb4874645f41654920a5963eb0b6e | refs/heads/master | 2021-01-22T08:47:47.982363 | 2016-01-25T03:40:58 | 2016-01-25T03:40:58 | 93,427,670 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 948 | hpp | #ifndef DJAH_DEBUG_CORE_LOGGER_HPP
#define DJAH_DEBUG_CORE_LOGGER_HPP
#include <list>
#include <vector>
#include <memory>
#include "../core/singleton.hpp"
#include "record.hpp"
namespace djah { namespace debug {
class basic_sink;
class core_logger
: public utils::singleton<core_logger>
{
DJAH_MAKE_SINGLETON(core_logger);
typedef std::shared_ptr<basic_sink> sink_ptr;
public:
void addSink(const sink_ptr &pSink);
void removeSink(const sink_ptr &pSink);
basic_record& openRecord(const std::string &channels, eLogSeverity severity, int line, const char *file);
void log(const basic_record &rec);
void consume();
private:
core_logger();
~core_logger();
private:
typedef std::list<sink_ptr> sink_list_t;
sink_list_t sinks_;
typedef std::vector<basic_record> record_list_t;
record_list_t records_;
};
} /*debug*/ } /*djah*/
#endif /* DJAH_DEBUG_CORE_LOGGER_HPP */ | [
"H-EAL@users.noreply.github.com"
] | H-EAL@users.noreply.github.com |
49fab0a6e04a4d6b5889db6a18c23f286025d47b | 5fcacbc63db76625cc60ffc9d6ed58a91f134ea4 | /vxl/vxl-1.13.0/core/vil/algo/tests/test_algo_exact_distance_transform.cxx | bbd270c0f408559284b0e3387099820ac5d452a4 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | EasonZhu/rcc | c809956eb13fb732d1b2c8035db177991e3530aa | d230b542fa97da22271b200e3be7441b56786091 | refs/heads/master | 2021-01-15T20:28:26.541784 | 2013-05-14T07:18:12 | 2013-05-14T07:18:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,786 | cxx | #include <testlib/testlib_test.h>
//:
// \file
// \author Ricardo Fabbri
#include <vil/algo/vil_exact_distance_transform.h>
#include <vil/vil_print.h>
#include <vil/vil_copy.h>
#include <vcl_cstdlib.h>
void vil_exact_distance_transform_test(vil_image_view<vxl_uint_32> &im, bool print, bool three_d=false);
void vil_exact_distance_transform_test_label(vil_image_view<vxl_uint_32> &im, bool print);
void
vil_exact_distance_transform_test_3D(vil_image_view<vxl_uint_32> &im, bool print);
void
vil_exact_distance_transform_test_specific(const vil_image_view<vxl_uint_32> &im, const vil_image_view<vxl_uint_32> dt_brute, bool print, vcl_string algo);
#define DATA(I) (I).top_left_ptr()
MAIN( test_algo_exact_distance_transform )
{
START ("Exact Euclidean Distance Transform Algorithms");
{
unsigned r=3,c=5;
vil_image_view <vxl_uint_32> image(r,c,1);
image.fill(1);
image(1,1) = 0;
vcl_cout << "ORIGINAL IMAGE:\n" << vcl_endl;
vil_print_all(vcl_cout,image);
vil_exact_distance_transform_test(image,true);
vil_exact_distance_transform_test_label(image,true);
}
{
unsigned r=3,c=5;
vil_image_view <vxl_uint_32> image(r,c,1);
image.fill(1);
image(0,0) = 0;
image(1,1) = 0;
image(1,2) = 0;
vcl_cout << "ORIGINAL IMAGE:\n" << vcl_endl;
vil_print_all(vcl_cout,image);
vil_exact_distance_transform_test(image,true);
vil_exact_distance_transform_test_label(image,true);
}
{
unsigned r=5,c=7;
vil_image_view <vxl_uint_32> image(r,c,1);
image.fill(1);
image(3,2)=0;
image(2,0)=0;
image(0,0)=0;
image(4,4)=0;
DATA(image)[34]=0;
vcl_cout << "ORIGINAL IMAGE:\n" << vcl_endl;
vil_print_all(vcl_cout,image);
vil_exact_distance_transform_test(image,true);
vil_exact_distance_transform_test_label(image,true);
}
{
vil_image_view <vxl_uint_32> image(100,100,1);
image.fill(1);
image(0,0) = 0;
vil_exact_distance_transform_test(image,false);
vil_exact_distance_transform_test_label(image,false);
}
{
vil_image_view <vxl_uint_32> image(100,100,1);
image.fill(1);
image(99,99) = 0;
vil_exact_distance_transform_test(image,false);
vil_exact_distance_transform_test_label(image,false);
}
{
vil_image_view <vxl_uint_32> image(100,100,1);
image.fill(1);
image(0,99) = 0;
vil_exact_distance_transform_test(image,false);
vil_exact_distance_transform_test_label(image,false);
}
{
vil_image_view <vxl_uint_32> image(100,100,1);
image.fill(1);
image(99,0) = 0;
vil_exact_distance_transform_test(image,false);
vil_exact_distance_transform_test_label(image,false);
}
{ // 8-disconnected Voronoi region that breaks most DT algorithms that claim to be Euclidean
vil_image_view <vxl_uint_32> image(14,13,1);
image.fill(1);
image(0,2) = 0;
image(1,6) = 0;
image(6,12) = 0;
vil_exact_distance_transform_test(image,true);
vil_exact_distance_transform_test_label(image,true);
}
// ----- 3D -----
{
unsigned r=7,c=5,p=3;
vil_image_view <vxl_uint_32> image(c,r,p);
image.fill(1);
image(2,3,1)=0;
vcl_cout << "ORIGINAL IMAGE:\n" << vcl_endl;
vil_print_all(vcl_cout,image);
vil_exact_distance_transform_test(image,true,true);
}
#if 0
{ //: just runs on big image
unsigned r=200,c=300,p=400;
vil_image_view <vxl_uint_32> image(c,r,p);
image.fill(1);
image(2,3,1)=0;
image(200,150,350)=0;
vil_exact_distance_transform_saito(image);
}
#endif // 0
{
unsigned r=7,c=5,p=3;
vil_image_view <vxl_uint_32> image(c,r,p);
image.fill(1);
image(2,3,1)=0;
image(0,0,0)=0;
image(4,3,2)=0;
vil_exact_distance_transform_test(image,false,true);
}
SUMMARY();
}
//: test 2D EDT
void
vil_exact_distance_transform_test(vil_image_view<vxl_uint_32> &im, bool print, bool three_d)
{
vil_image_view <vxl_uint_32> dt_brute(vil_copy_deep(im));
if (three_d)
vil_exact_distance_transform_brute_force(dt_brute);
else
vil_exact_distance_transform_brute_force_with_list(dt_brute);
if (print) {
vcl_cout << "BRUTE DT:\n";
vil_print_all(vcl_cout,dt_brute);
}
if (three_d) {
vil_exact_distance_transform_test_specific(im, dt_brute, print, "Saito 3D");
} else {
vil_exact_distance_transform_test_specific(im, dt_brute, print, "Maurer");
vil_exact_distance_transform_test_specific(im, dt_brute, print, "Saito");
}
}
void
vil_exact_distance_transform_test_specific(
const vil_image_view<vxl_uint_32> &im,
const vil_image_view<vxl_uint_32> dt_brute,
bool print,
vcl_string algo)
{
vil_image_view <vxl_uint_32> dt_algo(vil_copy_deep(im));
if (algo == "Maurer")
vil_exact_distance_transform_maurer(dt_algo);
else if (algo == "Saito")
vil_exact_distance_transform_saito(dt_algo);
else if (algo == "Saito 3D")
vil_exact_distance_transform_saito_3D(dt_algo);
else
vcl_abort();
if (print) {
vcl_cout << algo << " DT:\n";
vil_print_all(vcl_cout,dt_algo);
}
bool algo_error=false;
for (unsigned i=0; i<im.size(); ++i) {
vxl_uint_32 dst;
dst = DATA(dt_brute)[i];
if (dst != DATA(dt_algo)[i]) {
vcl_cout << "Error! " << algo << ": " << DATA(dt_algo)[i] << " EXACT: " << dst << vcl_endl;
algo_error = true;
break;
}
}
vcl_string msg = vcl_string("Is ") + algo + vcl_string(" exact");
TEST(msg.c_str() , algo_error, false);
}
//: test closest feature pixel (label) propagation
void
vil_exact_distance_transform_test_label(vil_image_view<vxl_uint_32> &im, bool print)
{
vil_image_view <vxl_uint_32> label_brute(im.ni(), im.nj(), 1);
vil_image_view <vxl_uint_32> dt_brute(vil_copy_deep(im));
vil_exact_distance_transform_brute_force_with_list_label(dt_brute, label_brute);
vil_image_view <vxl_uint_32> label_algo(im.ni(), im.nj(), 1);
vil_image_view <vxl_uint_32> dt_algo(vil_copy_deep(im));
vil_exact_distance_transform_maurer_label(dt_algo, label_algo);
const vcl_string algo("Maurer");
if (print) {
vcl_cout << "BRUTE Closest Feature Labels:\n";
vil_print_all(vcl_cout, label_brute);
vcl_cout << algo << " Closest Feature Labels:\n";
vil_print_all(vcl_cout, label_algo);
}
bool algo_error=false;
unsigned ni = im.ni();
for (unsigned i=0; i<im.size(); ++i) {
unsigned dst;
dst = DATA(dt_algo)[i];
unsigned dst_from_label;
int r, c, rl, cl;
r = i / ni;
c = i % ni;
rl = DATA(label_algo)[i] / ni;
cl = DATA(label_algo)[i] % ni;
dst_from_label = (r-rl)*(r-rl) + (c-cl)*(c-cl);
if (dst != dst_from_label) {
vcl_cout << "Error! (labels) " << algo << ": " << DATA(label_algo)[i] << " EXACT: " << dst << vcl_endl;
algo_error = true;
break;
}
}
vcl_string msg = vcl_string("Is ") + algo + vcl_string("'s labels correct?");
TEST(msg.c_str() , algo_error, false);
}
| [
"hieuza@gmail.com"
] | hieuza@gmail.com |
c5f8994a9cce0085e2be9c488a76d76e0c33ff38 | 322b6c280a7329221d7e8ea88fc9d19590e68f92 | /test_server/test_server.cpp | 2f9ea1a0be36e868ba2d45837978a56b2c9dd8b6 | [] | no_license | wangkaichao/apkJarJniSo_end | bf08b76d20f9dce88b4dad17bcafa3dd4bad493d | acc9b737a32b596f6aad8896b2b15967598fbcbd | refs/heads/master | 2020-05-20T03:12:16.620438 | 2019-05-21T07:04:41 | 2019-05-21T07:04:41 | 185,352,697 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 625 | cpp | #include <sys/types.h>
#include <unistd.h>
#include <grp.h>
#include <binder/IPCThreadState.h>
#include <binder/ProcessState.h>
#include <binder/IServiceManager.h>
#include <utils/Log.h>
#include "TestService.h"
#include <private/android_filesystem_config.h>
#include <linux/capability.h>
#include <sys/prctl.h>
using namespace android;
int main(int argc, char** argv)
{
sp<ProcessState> proc(ProcessState::self());
printf("test in main server");
TestService::instantiate();
ProcessState::self()->startThreadPool();
IPCThreadState::self()->joinThreadPool();
return 0;
}
| [
"364596530@qq.com"
] | 364596530@qq.com |
360d50b7f6f90f00dbd2981d17080208d747a945 | 28e2bc3dfb0bfd4a722d64bea02d1f40d078640f | /Logic/ChainedOperator.h | f59d7c4a3ff5d555c5dbfa2771274b688d306fd2 | [] | no_license | WojcikDominika/HipSegmenter | 789cd51f55cd26e0c8dc88532f55b93432179fd3 | f47245c8e015a44c285084d0125d5b2defc232af | refs/heads/master | 2022-01-06T21:33:13.204168 | 2019-05-19T23:20:35 | 2019-05-19T23:20:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 221 | h | //
// Created by Dominika on 06.03.2019.
//
#ifndef HIPSEGMENTER_CHAINEDOPERATOR_H
#define HIPSEGMENTER_CHAINEDOPERATOR_H
class ChainedOperator {
public:
bool status;
};
#endif //HIPSEGMENTER_CHAINEDOPERATOR_H
| [
"dwojcik.95@gmail.com"
] | dwojcik.95@gmail.com |
742f042fee0bb33b3d62932c20f6eb1468680f9c | 724dc63de53c9911cb0ff037102bd5b964fe5768 | /Linux/cpp/object_oriented/init_order.cpp | eb3c24ab8b788afc30f891d14fea4dd05f204840 | [] | no_license | liukechao/KCodes | a1820b3df3fb053e8a5cf4e69c03b3ac69c2a780 | 8862bf03eb030b931d45b40bbdd2cbbcfc3b0482 | refs/heads/master | 2021-01-15T13:24:27.606593 | 2018-09-17T01:25:34 | 2018-09-17T01:25:34 | 68,582,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 306 | cpp | #include <iostream>
using namespace std;
class Test {
private:
int m_i;
int m_j;
public:
Test(int x): m_j(x), m_i(m_j) {}
Test(): m_j(0), m_i(m_j) {}
int get_i() { return m_i; }
int get_j() { return m_j; }
};
int main()
{
Test t(60);
cout << t.get_i() << "\t" << t.get_j() << endl;
return 0;
}
| [
"liu_kechao@163.com"
] | liu_kechao@163.com |
303f1b42e881b059b2331acb4e0469342d46c151 | 6d151144a751fefe0352d76f2793c630a6a96438 | /asm/bingen.cpp | a308618f69da37b70ed8dfab5c433e99836cee15 | [] | no_license | tokatoka/Flareon | 2a34c4a873b18de4bd6add8c5ae625844d0f82f1 | b7570490a5af8469fdd5667bbca3a18bd7640f2c | refs/heads/master | 2020-06-25T18:07:39.641480 | 2019-03-01T11:14:18 | 2019-03-01T11:14:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,609 | cpp | #include "bingen.h"
#include <stdio.h>
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <cmath>
#include <assert.h>
#include "utils.h"
// round mode (dummy)
#define RM 0b000
// simulatorのMEM_SIZE
#define MEM_SIZE 0x10000010
BinGen::BinGen(std::ofstream ofs, std::ofstream coefs, bool is_verbose, bool is_debug, bool is_ascii)
: is_verbose_(is_verbose),
is_debug_(is_debug),
is_ascii_(is_ascii),
ofs_(std::move(ofs)),
coefs_(std::move(coefs)),
regmap_(create_regmap()),
fregmap_(create_fregmap()) {}
void BinGen::ReadDataLabels(std::string input) {
std::string mnemo;
std::vector<std::string> arg;
Parse(input, mnemo, arg);
if (mnemo == ".text") {
data_mode_ = false;
return;
}
if (mnemo == ".data") {
data_mode_ = true;
return;
}
if ((!data_mode_) || mnemo == "" /* comment */)
return;
if (mnemo.back() != ':') {
assert(mnemo == ".word");
ndata_++;
return;
}
mnemo.pop_back();
// std::cerr << "[INFO] new label " << mnemo << " registered at " << ndata_ * 4 << std::endl;
data_map_[mnemo] = ndata_;
return;
}
void BinGen::ReadLabels(std::string input) {
std::string mnemo;
std::vector<std::string> arg;
Parse(input, mnemo, arg);
if (mnemo == ".text") {
data_mode_ = false;
return;
}
if (mnemo == ".data") {
data_mode_ = true;
return;
}
if (data_mode_ || mnemo == "" /* comment */)
return;
// The input wasn't a label.
if (mnemo.back() != ':') {
// Some pseudo-instructions will expand to two instrs
if (mnemo == "la" || mnemo == "ret" || mnemo == "call" || mnemo == "tail") {
nline_ += 2;
return;
}
if (mnemo == "fli") {
std::string reg, label;
ParseOffsetLabel(arg[1], ®, &label);
uint32_t imm = SolveDataLabel(label);
if (IsImmOutOfRange(imm, 12)) {
printf("fli out of range\n");
nline_ += 2;
return;
}
}
if (mnemo == "lwl" || mnemo == "swl" || mnemo == "flwl" || mnemo == "fswl") {
std::string reg, label;
ParseOffsetLabel(arg[1], ®, &label);
uint32_t imm = SolveDataLabel(label);
if (IsImmOutOfRange(imm, 12)) {
printf("lwl/swl/flwl/fswl out of range\n");
nline_ += 3;
return;
}
}
if (mnemo == "lwd" || mnemo == "swd" || mnemo == "flwd" || mnemo == "fswd") {
std::string imm, label;
ParseOffsetLabel(arg[1], &imm, &label);
uint32_t imml = SolveDataLabel(label);
if (IsImmOutOfRange(imml + stoi(imm), 12)) {
printf("lwd/swd/flwd/fswd out of range\n");
nline_ += 3;
return;
}
}
// ラベルの値
if (mnemo == "lda" && IsImmOutOfRange(SolveDataLabel(arg[1]), 12)) {
nline_ += 2;
return;
}
if (mnemo == "li" && IsImmOutOfRange(MyStoi(arg[1]), 12)) {
nline_ += 2;
return;
}
// Don't count these markers
if (mnemo == ".file" || mnemo == ".option" || mnemo == ".align" ||
mnemo == ".globl" || mnemo == ".type" || mnemo == ".size" || mnemo == ".ident") {
return;
}
nline_++;
return;
}
mnemo.pop_back();
// std::cerr << "[INFO] new label " << mnemo << " registered at " << nline_ * 4 << std::endl;
label_map_[mnemo] = nline_;
}
void BinGen::OnReadLabelsCompleted(){
nline_ = 0;
data_mode_ = false;
}
void BinGen::Main(std::string input, bool do_debug_print) {
int old_nline = nline_;
BinGen::Inst inst(Convert(input));
if (is_debug_ && do_debug_print) {
if (inst.is_inst()) {
std::printf("(%d)\t%s\n", old_nline * 4, input.c_str());
} else {
std::printf("\t%s\n", input.c_str());
}
}
if (is_verbose_ && do_debug_print) {
std::cout << "(pc " << old_nline * 4 << "):" << input << std::endl;
if (inst.is_inst()) PrintInst(inst);
std::cout << std::endl;
}
if (inst.is_empty()) return;
if (!inst.is_inst()) {
assert(inst.is_data());
WriteData(inst.data);
return;
}
WriteInst(inst.fst);
if (!inst.is_multiple_inst())
return;
WriteInst(inst.snd);
if (!inst.is_triple_inst())
return;
WriteInst(inst.third);
}
void BinGen::Finish() {
WriteInst(0);
ofs_.close();
}
// dirty...
void BinGen::Parse(std::string input, std::string &mnemo, std::vector<std::string> &arg) {
auto is_sep = [](char c){ return (c == ' ' || c == '\t' || c == '\0' || c == '#' || c == ','); };
int curr_pos = 0;
int start_pos = 0;
while (input[curr_pos] == ' ' || input[curr_pos] == '\t') curr_pos++;
if (input[curr_pos] == '\0' || input[curr_pos] == '#') return;
// mnemonic (or label)
start_pos = curr_pos;
while (!is_sep(input[curr_pos])) curr_pos++;
mnemo = input.substr(start_pos, curr_pos - start_pos);
while (input[curr_pos] == ' ' || input[curr_pos] == '\t') curr_pos++;
if (input[curr_pos] == '\0' || input[curr_pos] == '#') return;
// arg[0]
start_pos = curr_pos;
while (!is_sep(input[curr_pos])) curr_pos++;
arg.push_back(input.substr(start_pos, curr_pos - start_pos));
while (input[curr_pos] == ' ' || input[curr_pos] == '\t' || input[curr_pos] == ',') curr_pos++;
if (input[curr_pos] == '\0' || input[curr_pos] == '#') return;
// arg[1]
start_pos = curr_pos;
while (!is_sep(input[curr_pos])) curr_pos++;
arg.push_back(input.substr(start_pos, curr_pos - start_pos));
while (input[curr_pos] == ' ' || input[curr_pos] == '\t' || input[curr_pos] == ',') curr_pos++;
if (input[curr_pos] == '\0' || input[curr_pos] == '#') return;
// arg[2]
start_pos = curr_pos;
while (!is_sep(input[curr_pos])) curr_pos++;
arg.push_back(input.substr(start_pos, curr_pos - start_pos));
}
void BinGen::ParseOffset(std::string arg, std::string* reg, uint32_t* offset) {
size_t pos_lpar = arg.find("(");
size_t pos_rpar = arg.find(")");
*offset = std::stoi(arg.substr(0, pos_lpar));
*reg = arg.substr(pos_lpar + 1, (pos_rpar - pos_lpar - 1));
}
void BinGen::ParseOffsetLabel(std::string arg, std::string* reg, std::string* label) {
size_t pos_lpar = arg.find("(");
size_t pos_rpar = arg.find(")");
*label = arg.substr(0, pos_lpar);
*reg = arg.substr(pos_lpar + 1, (pos_rpar - pos_lpar - 1));
}
BinGen::Inst BinGen::Convert(std::string input) {
std::string mnemo;
std::vector<std::string> arg;
Parse(input, mnemo, arg);
Inst inst;
if (mnemo == ".text") {
data_mode_ = false;
return inst;
}
if (mnemo == ".data") {
data_mode_ = true;
return inst;
}
// Labels
if (mnemo.back() == ':')
return inst;
if (mnemo == ".file" || mnemo == ".option" || mnemo == ".align" ||
mnemo == ".globl" || mnemo == ".type" || mnemo == ".size" || mnemo == ".ident")
return inst;
// Comment
if (mnemo == "")
return inst;
// Data
if (mnemo == ".word") {
assert(data_mode_);
assert(1 == arg.size());
uint32_t imm = (data_map_.count(arg[0]) > 0) ? SolveDataLabel(arg[0]) : MyStoi(arg[0]);
inst.set_data(imm);
return inst;
}
// RV32I basic instructions ==============================================================
else if (mnemo == "lui") {
assert(2 == arg.size());
inst.set_fst(lui(arg[0], MyStoi(arg[1])));
}
else if (mnemo == "auipc") {
assert(2 == arg.size());
inst.set_fst(auipc(arg[0], MyStoi(arg[1])));
}
else if (mnemo == "jalr") {
assert(3 == arg.size());
inst.set_fst(jalr(arg[0], arg[1], MyStoi(arg[2])));
}
else if (mnemo == "beq" || mnemo == "bne" || mnemo == "blt" || mnemo == "bge") {
assert(3 == arg.size());
inst.set_fst(branch(mnemo, arg[0], arg[1], MyStoi(arg[2])));
}
else if (mnemo == "beqi" || mnemo == "bnei" || mnemo == "blti" || mnemo == "bgti") {
assert(3 == arg.size());
inst.set_fst(branch_imm(mnemo, arg[0], std::stoi(arg[1], nullptr, 10), MyStoi(arg[2])));
}
else if (mnemo == "lw") {
assert(2 == arg.size());
std::string rs1; uint32_t offset;
ParseOffset(arg[1], &rs1, &offset);
inst.set_fst(lw(arg[0], rs1, offset));
}
else if (mnemo == "sw") {
assert(2 == arg.size());
std::string rs1; uint32_t offset;
ParseOffset(arg[1], &rs1, &offset);
inst.set_fst(sw(arg[0], rs1, offset));
}
else if (mnemo == "addi" || mnemo == "xori" || mnemo == "andi") {
assert(3 == arg.size());
inst.set_fst(op_imm(mnemo, arg[0], arg[1], MyStoi(arg[2])));
}
else if (mnemo == "slli" || mnemo == "srai") {
assert(3 == arg.size());
inst.set_fst(op_imm_shift(mnemo, arg[0], arg[1], MyStoi(arg[2])));
}
else if (mnemo == "add" || mnemo == "sub" || mnemo == "xor") {
assert(3 == arg.size());
inst.set_fst(op(mnemo, arg[0], arg[1], arg[2]));
}
// I/O instructions ======================================================================
else if (mnemo == "w") {
assert(1 == arg.size());
inst.set_fst(write(arg[0]));
}
else if (mnemo == "r") {
assert(1 == arg.size());
inst.set_fst(read(arg[0]));
}
// Floating-point instructions ===========================================================
else if (mnemo == "flw") {
assert(2 == arg.size());
std::string rs; uint32_t offset;
ParseOffset(arg[1], &rs, &offset);
inst.set_fst(flw(arg[0], rs, offset));
}
else if (mnemo == "fsw") {
assert(2 == arg.size());
std::string rs; uint32_t offset;
ParseOffset(arg[1], &rs, &offset);
inst.set_fst(fsw(arg[0], rs, offset));
}
else if (mnemo == "feq" || mnemo == "flt" || mnemo == "fle") {
assert(3 == arg.size());
inst.set_fst(f_cmp(mnemo, arg[0], arg[1], arg[2]));
}
else if (mnemo == "fsqrt" || mnemo == "fabs" || mnemo == "fneg" || mnemo == "fmv" || mnemo == "finv") {
assert(2 == arg.size());
inst.set_fst(f_op2(mnemo, arg[0], arg[1]));
}
else if (mnemo == "fadd" || mnemo == "fsub" || mnemo == "fmul" || mnemo == "fdiv") {
assert(3 == arg.size());
inst.set_fst(f_op3(mnemo, arg[0], arg[1], arg[2]));
}
// Pseudo-instructions ===================================================================
else if (mnemo == "la") {
assert(2 == arg.size());
uint32_t tmp = SolveLabel(arg[1]);
inst.set_fst(auipc(arg[0], ((tmp >> 12) + ((tmp >> 11) & 0x1)) & 0xfffff));
nline_++;
inst.set_snd(op_imm("addi", arg[0], arg[0], tmp & 0xfff));
}
else if (mnemo == "lda") {
assert(2 == arg.size());
uint32_t tmp = SolveDataLabel(arg[1]);
if (tmp > (1 << 11) - 1) {
inst.set_fst(lui(arg[0], ((tmp >> 12) + ((tmp >> 11) & 0x1)) & 0xfffff));
nline_++;
inst.set_snd(op_imm("addi", arg[0], arg[0], tmp & 0xfff));
} else {
inst.set_fst(op_imm("addi", arg[0], "zero", tmp));
}
}
else if (mnemo == "li") {
assert(2 == arg.size());
uint32_t tmp = MyStoi(arg[1]);
if (IsImmOutOfRange(tmp, 12)) {
inst.set_fst(lui(arg[0], ((tmp >> 12) + ((tmp >> 11) & 0x1)) & 0xfffff));
nline_++;
inst.set_snd(op_imm("addi", arg[0], arg[0], tmp & 0xfff));
} else {
inst.set_fst(op_imm("addi", arg[0], "zero", (int)tmp));
}
}
else if (mnemo == "mv") {
assert(2 == arg.size());
inst.set_fst(op_imm("addi", arg[0], arg[1], 0));
}
else if (mnemo == "not") {
assert(2 == arg.size());
inst.set_fst(op_imm("xori", arg[0], arg[1], -1));
}
else if (mnemo == "neg") {
assert(2 == arg.size());
inst.set_fst(op("sub", arg[0], "zero", arg[1]));
}
else if (mnemo == "bgt") {
assert(3 == arg.size());
inst.set_fst(branch("blt", arg[1], arg[0], SolveLabel(arg[2])));
}
else if (mnemo == "ble") {
assert(3 == arg.size());
inst.set_fst(branch("bge", arg[1], arg[0], SolveLabel(arg[2])));
}
else if (mnemo == "b") {
assert(1 == arg.size());
inst.set_fst(branch("bge", "zero", "zero", SolveLabel(arg[0])));
}
else if (mnemo == "jr") {
assert(1 == arg.size());
inst.set_fst(jalr("zero", arg[0], 0));
}
else if (mnemo == "ret") {
assert(0 == arg.size());
inst.set_fst(jalr("x0", "x1", 0u));
}
else if (mnemo == "call") {
assert(1 == arg.size());
uint32_t imm = SolveLabel(arg[0]);
// jalrが符号拡張するため、下から12bit目が1の場合はauipcに渡す即値に1を足す
// その結果2 ^ 12を超える場合は下位20bitをわたす
inst.set_fst(auipc("x6", ((imm >> 12) + ((imm >> 11) & 1)) & 0xfffff));
nline_++;
inst.set_snd(jalr("x1", "x6", imm & 0xfff));
}
else if (mnemo == "tail") {
assert(1 == arg.size());
uint32_t imm = SolveLabel(arg[0]);
inst.set_fst(auipc("x6", ((imm >> 12) + ((imm >> 11) & 1)) & 0xfffff));
nline_++;
inst.set_snd(jalr("x0", "x6", imm & 0xfff));
}
else if (mnemo == "fli") {
// Note: t6レジスタが潰される
assert(2 == arg.size());
uint32_t imm = SolveDataLabel(arg[1]);
if (IsImmOutOfRange(imm, 12)) {
std::string tmp_reg = "t6";
inst.set_fst(lui(tmp_reg, ((imm >> 12) + ((imm >> 11) & 1)) & 0xfffff));
nline_++;
inst.set_snd(flw(arg[0], tmp_reg, (imm & 0xfff)));
} else {
inst.set_fst(flw(arg[0], "zero", (imm & 0xfff)));
}
}
else if (mnemo == "lwl" || mnemo == "swl" || mnemo == "flwl" || mnemo == "fswl") {
assert(2 == arg.size());
std::string reg, label;
ParseOffsetLabel(arg[1], ®, &label);
uint32_t imm = SolveDataLabel(label);
if (IsImmOutOfRange(imm, 12)) {
// std::cerr << "Out of range!!!" << std::endl;
inst.set_fst(lui(arg[0], ((imm >> 12) + ((imm >> 11) & 0x1)) & 0xfffff));
nline_++;
inst.set_snd(op("add", arg[0], arg[0], reg));
nline_++;
if (mnemo == "lwl") inst.set_third(lw(arg[0], reg, imm & 0xfff));
if (mnemo == "swl") inst.set_third(sw(arg[0], reg, imm & 0xfff));
if (mnemo == "flwl") inst.set_third(flw(arg[0], reg, imm & 0xfff));
if (mnemo == "fswl") inst.set_third(fsw(arg[0], reg, imm & 0xfff));
} else {
if (mnemo == "lwl") inst.set_fst(lw(arg[0], reg, imm));
if (mnemo == "swl") inst.set_fst(sw(arg[0], reg, imm));
if (mnemo == "flwl") inst.set_fst(flw(arg[0], reg, imm));
if (mnemo == "fswl") inst.set_fst(fsw(arg[0], reg, imm));
}
}
else if (mnemo == "lwd" || mnemo == "swd" || mnemo == "flwd" || mnemo == "fswd") {
assert(2 == arg.size());
std::string imms, label;
ParseOffsetLabel(arg[1], &imms, &label);
uint32_t imm = SolveDataLabel(label) + std::stoi(imms);
if (IsImmOutOfRange(imm, 12)) {
// std::cerr << "Out of range!!!" << std::endl;
inst.set_fst(lui(arg[0], ((imm >> 12) + ((imm >> 11) & 0x1)) & 0xfffff));
nline_++;
inst.set_snd(op("add", arg[0], arg[0], "zero"));
nline_++;
if (mnemo == "lwd") inst.set_third(lw(arg[0], "zero", imm & 0xfff));
if (mnemo == "swd") inst.set_third(sw(arg[0], "zero", imm & 0xfff));
if (mnemo == "flwd") inst.set_third(flw(arg[0], "zero", imm & 0xfff));
if (mnemo == "fswd") inst.set_third(fsw(arg[0], "zero", imm & 0xfff));
} else {
if (mnemo == "lwd") inst.set_fst(lw(arg[0], "zero", imm));
if (mnemo == "swd") inst.set_fst(sw(arg[0], "zero", imm));
if (mnemo == "flwd") inst.set_fst(flw(arg[0], "zero", imm));
if (mnemo == "fswd") inst.set_fst(fsw(arg[0], "zero", imm));
}
}
else {
fprintf(stderr, "No such instructions: %s\n", input.c_str());
return Inst();
}
nline_++;
return inst;
}
// 01の列にする(4桁ごとに空白)
std::string BinGen::ToString(uint32_t inst) {
std::string str;
for (int i = 0; i < 32; i++) {
str.push_back(((inst >> (31 - i)) & 0x1)? '1' : '0');
if (i % 4 == 3) str.push_back(' ');
}
assert(str.size() == 40);
return str;
}
std::string BinGen::InstToString(Inst inst) {
if (inst.is_empty())
return "";
else if (inst.snd == 0xffffffff)
return ToString(inst.fst);
else
return ToString(inst.fst) + " " + ToString(inst.snd);
}
void BinGen::PrintInt(uint32_t inst) {
std::cout << ToString(inst) << std::endl;
}
void BinGen::PrintInst(Inst inst) {
std::cout << InstToString(inst) << std::endl;
}
uint32_t BinGen::lui (std::string rd, uint32_t imm) {
CheckImmediate(imm, 20, "lui");
Fields fields{ {7, 0b0110111}, {5, regmap_.at(rd)}, {20, imm} };
return Pack(fields);
}
uint32_t BinGen::auipc (std::string rd, uint32_t imm) {
CheckImmediate(imm, 20, "auipc");
Fields fields{ {7, 0b0010111}, {5, regmap_.at(rd)}, {20, imm} };
return Pack(fields);
}
uint32_t BinGen::jalr (std::string rd, std::string rs1, uint32_t imm) {
CheckImmediate(imm, 12, "jalr");
Fields fields { {7, 0b1100111},
{5, regmap_.at(rd)},
{3, 0},
{5, regmap_.at(rs1)},
{12, imm} };
return Pack(fields);
}
// beq, bne, blt, bge
uint32_t BinGen::branch (std::string mnemo, std::string rs1, std::string rs2, uint32_t offset) {
CheckImmediate(offset, 13, "branch");
uint32_t funct3;
if (mnemo == "beq") funct3 = 0b000;
if (mnemo == "bne") funct3 = 0b001;
if (mnemo == "blt") funct3 = 0b100;
if (mnemo == "bge") funct3 = 0b101;
Fields fields { {7, 0b1100011},
{1, (offset & 0x800) >> 11},
{4, (offset & 0x1e) >> 1},
{3, funct3},
{5, regmap_.at(rs1)},
{5, regmap_.at(rs2)},
{6, (offset & 0x7e0) >> 5},
{1, (offset & 0x1000) >> 12} };
return Pack(fields);
}
// beqi, bnei, blti, bgti
uint32_t BinGen::branch_imm (std::string mnemo, std::string rs1, uint32_t imm, uint32_t offset) {
CheckImmediate(offset, 13, "branch_imm");
CheckImmediate(imm, 5, "branch_imm");
uint32_t funct3;
if (mnemo == "beqi") funct3 = 0b010;
if (mnemo == "bnei") funct3 = 0b011;
if (mnemo == "blti") funct3 = 0b110;
if (mnemo == "bgti") funct3 = 0b111;
Fields fields { {7, 0b1100011},
{1, (offset & 0x800) >> 11},
{4, (offset & 0x1e) >> 1},
{3, funct3},
{5, regmap_.at(rs1)},
{5, imm & 0x1f},
{6, (offset & 0x7e0) >> 5},
{1, (offset & 0x1000) >> 12} };
return Pack(fields);
}
uint32_t BinGen::lw (std::string rd, std::string rs1, uint32_t offset) {
CheckImmediate(offset, 12, "load");
uint32_t funct3 = 0b010;
Fields fields{ {7, 0b0000011},
{5, regmap_.at(rd)},
{3, funct3},
{5, regmap_.at(rs1)},
{12, offset} };
return Pack(fields);
}
uint32_t BinGen::sw (std::string rs2, std::string rs1, uint32_t offset) {
CheckImmediate(offset, 12, "store");
uint32_t funct3 = 0b010;
Fields fields { {7, 0b0100011},
{5, offset & 0x1f},
{3, funct3},
{5, regmap_.at(rs1)},
{5, regmap_.at(rs2)},
{7, (offset & 0xfe0) >> 5} };
return Pack(fields);
}
// addi, xori, andi
uint32_t BinGen::op_imm (std::string mnemo, std::string rd, std::string rs1, uint32_t imm) {
CheckImmediate(imm, 12, "op_imm");
uint32_t funct3;
if (mnemo == "addi") funct3 = 0b000;
if (mnemo == "xori") funct3 = 0b100;
if (mnemo == "andi") funct3 = 0b111;
Fields fields { {7, 0b0010011},
{5, regmap_.at(rd)},
{3, funct3},
{5, regmap_.at(rs1)},
{12, imm} };
return Pack(fields);
}
// slli, srai
uint32_t BinGen::op_imm_shift (std::string mnemo, std::string rd, std::string rs1, uint32_t shamt) {
CheckImmediate(shamt, 5, "op_imm_shift");
uint32_t funct3 = (mnemo == "slli") ? 0b001 : 0b101;
uint32_t funct7 = (mnemo == "srai") ? 0b0100000 : 0b0000000;
Fields fields { {7, 0b0010011},
{5, regmap_.at(rd)},
{3, funct3},
{5, regmap_.at(rs1)},
{5, shamt},
{7, funct7} };
return Pack(fields);
}
// add, sub, xor
uint32_t BinGen::op (std::string mnemo, std::string rd, std::string rs1, std::string rs2) {
uint32_t funct3;
if (mnemo == "add") funct3 = 0b000;
if (mnemo == "sub") funct3 = 0b010;
if (mnemo == "xor") funct3 = 0b100;
Fields fields { {7, 0b0110011},
{5, regmap_.at(rd)},
{3, funct3},
{5, regmap_.at(rs1)},
{5, regmap_.at(rs2)},
{7, 0b0000000} };
return Pack(fields);
}
// |31 20|19 15|14 12|11 7|6 0|
// |000000000000|00000|funct3| reg | opcode|
// |000000000000| rs | 000 |00000|1111111| w (write)
// |000000000000|00000| 001 | rd |1111111| r (read)
uint32_t BinGen::read (std::string rd) {
Fields fields { {7, 0b1111111},
{5, regmap_.at(rd)},
{3, 0b001},
{5, 0x00000},
{12, 0x00000} };
return Pack(fields);
}
uint32_t BinGen::write (std::string rs) {
Fields fields { {7, 0b1111111},
{5, 0b00000},
{3, 0b000},
{5, regmap_.at(rs)},
{12, 0x00000} };
return Pack(fields);
}
uint32_t BinGen::flw(std::string frd, std::string rs, uint32_t imm) {
CheckImmediate(imm, 12, "flw");
Fields fields { {7, 0b0000111},
{5, fregmap_.at(frd)},
{3, 0b010},
{5, regmap_.at(rs)},
{12, imm & 0xfff} };
return Pack(fields);
}
uint32_t BinGen::fsw(std::string frs2, std::string frs1, uint32_t imm) {
CheckImmediate(imm, 12, "fsw");
Fields fields { {7, 0b0100111},
{5, imm & 0x1f},
{3, 0b010},
{5, regmap_.at(frs1)},
{5, fregmap_.at(frs2)},
{7, (imm >> 5) & 0x7f} };
return Pack(fields);
}
// fsqrt, fabs, fneg, fmv, finv (2 operands)
uint32_t BinGen::f_op2(std::string mnemo, std::string frd, std::string frs) {
uint32_t funct7;
if (mnemo == "fsqrt") funct7 = 0b0101100;
if (mnemo == "fmv") funct7 = 0b0010000;
if (mnemo == "fneg") funct7 = 0b0010001;
if (mnemo == "fabs") funct7 = 0b0010010;
if (mnemo == "finv") funct7 = 0b0010011;
Fields fields { {7, 0b1010011},
{5, fregmap_.at(frd)},
{3, 0b000},
{5, fregmap_.at(frs)},
{5, 0b00000},
{7, funct7} };
return Pack(fields);
}
// fadd, fsub, fmul, fdiv (3 operands)
uint32_t BinGen::f_op3(std::string mnemo, std::string frd, std::string frs1, std::string frs2) {
uint32_t funct7;
if (mnemo == "fadd") funct7 = 0b0000000;
if (mnemo == "fsub") funct7 = 0b0000100;
if (mnemo == "fmul") funct7 = 0b0001000;
if (mnemo == "fdiv") funct7 = 0b0001100;
Fields fields { {7, 0b1010011},
{5, fregmap_.at(frd)},
{3, RM},
{5, fregmap_.at(frs1)},
{5, fregmap_.at(frs2)},
{7, funct7} };
return Pack(fields);
}
// feq.s, flt.s, fle.s
uint32_t BinGen::f_cmp(std::string mnemo, std::string rd, std::string frs1, std::string frs2) {
uint32_t funct7;
if (mnemo == "feq") funct7 = 0b1010010;
if (mnemo == "flt") funct7 = 0b1010001;
if (mnemo == "fle") funct7 = 0b1010000;
Fields fields { {7, 0b1010011},
{5, regmap_.at(rd)},
{3, 0b0},
{5, fregmap_.at(frs1)},
{5, fregmap_.at(frs2)},
{7, funct7} };
return Pack(fields);
}
uint32_t BinGen::Pack(Fields fields) {
uint32_t ret = 0;
for (auto itr = fields.rbegin(); itr != fields.rend(); ++itr) {
ret <<= itr->first;
ret += itr->second;
}
return ret;
}
bool BinGen::IsImmOutOfRange(uint32_t imm, int range) {
uint32_t mask = -1 << range;
return (mask & imm && mask & (~imm));
}
// immの上位(32 - range)bitが全部0(imm >= 0の場合)、もしくは全部1(imm < 0の場合)でなければダメ
void BinGen::CheckImmediate(uint32_t imm, int range, std::string func_name) {
uint32_t mask = -1 << range;
// mask & imm : immの上位(32 - range)bitが全部0なら0
// mask & ~imm : immの上位(32 - range)bitが全部1なら0
if (mask & imm && mask & (~imm)) {
std::cerr << "\x1b[31m[ERROR](" << func_name << "): The immediate value " << imm << " should be smaller than 2 ^ " << range << "\x1b[39m\n";
exit(1);
}
}
void BinGen::WriteInst(uint32_t inst) {
if (is_ascii_) {
std::string str;
for (int i = 0; i < 32; i++)
str.push_back(((inst >> (31 - i)) & 0x1)? '1' : '0');
assert(str.size() == 32);
ofs_ << str << std::endl;
return;
}
unsigned char d[4];
d[0] = inst >> 24;
d[1] = inst >> 16;
d[2] = inst >> 8;
d[3] = inst;
ofs_.write((char *)d, 4);
}
void BinGen::WriteData(uint32_t data) {
std::string str;
for (int i = 0; i < 32; i++)
str.push_back(((data >> (31 - i)) & 0x1)? '1' : '0');
assert(str.size() == 32);
coefs_ << str << std::endl;
}
uint32_t BinGen::MyStoi(std::string imm) {
try {
return std::stoi(imm, nullptr, 10);
}
catch (...) {
// stoi() failed. |imm| was a label.
if (label_map_.count(imm) == 0) {
std::cerr << "\x1b[31m[ERROR] Undefined symbol: " << imm << "\x1b[39m\n";
return 0;
}
return (label_map_[imm] - nline_) * 4;
}
}
uint32_t BinGen::SolveLabel(std::string label) {
if (label_map_.count(label) == 0) {
std::cerr << "\x1b[31m[ERROR] Undefined symbol: " << label << "\x1b[39m\n";
return 0;
}
return (label_map_[label] - nline_) * 4;
}
uint32_t BinGen::SolveDataLabel(std::string label) {
if (data_map_.count(label) == 0) {
std::cerr << "\x1b[31m[ERROR] Undefined symbol: " << label << "\x1b[39m\n";
return 0;
}
return data_map_[label] * 4;
}
| [
"momohatt10@gmail.com"
] | momohatt10@gmail.com |
f7b891a47bc8d7fbc1a92ec931e08cd514ce27d5 | 001616a3fd15ea58458ea12a8888f013e4a83461 | /PDI/atv5/laplgauss.cpp | 42e394d7f9e542d1fc2eb398b3d4347b70583fc4 | [] | no_license | vanessadants/vanessadants.github.io | 32e41f34e7a3c21b93699ce75cd2f61ac28517f3 | a0436d7a65121c192bfe75b2a211d6854c90b55b | refs/heads/master | 2020-04-02T08:09:32.566049 | 2018-10-23T05:23:50 | 2018-10-23T05:23:50 | 128,276,094 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,989 | cpp | #include <iostream>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
void printmask(Mat &m){
for(int i=0; i<m.size().height; i++){
for(int j=0; j<m.size().width; j++){
cout << m.at<float>(i,j) << ",";
}
cout << endl;
}
}
void menu(){
cout << "\npressione a tecla para ativar o filtro: \n"
"a - calcular modulo\n"
"m - media\n"
"g - gauss\n"
"v - vertical\n"
"h - horizontal\n"
"l - laplaciano\n"
"z - laplaciano do gaussiano\n"
"esc - sair\n";
}
int main(int argvc, char** argv){
VideoCapture video;
float media[] = {1,1,1,
1,1,1,
1,1,1};
float gauss[] = {1,2,1,
2,4,2,
1,2,1};
float horizontal[]={-1,0,1,
-2,0,2,
-1,0,1};
float vertical[]={-1,-2,-1,
0,0,0,
1,2,1};
float laplacian[]={0,-1,0,
-1,4,-1,
0,-1,0};
float laplacianGauss[]= {0,0,1,0,0,
0,1,2,1,0,
1,2,-16,2,1,
0,1,2,1,0,
0,0,1,0,0};
Mat cap, frame, frame32f, frameFiltered;
Mat mask(3,3,CV_32F), mask1;
Mat result, result1;
double width, height, min, max;
int absolut;
char key;
video.open(0);
if(!video.isOpened())
return -1;
width=video.get(CV_CAP_PROP_FRAME_WIDTH);
height=video.get(CV_CAP_PROP_FRAME_HEIGHT);
std::cout << "largura=" << width << "\n";;
std::cout << "altura =" << height<< "\n";;
namedWindow("filtroespacial",1);
mask = Mat(3, 3, CV_32F, media);
scaleAdd(mask, 1/9.0, Mat::zeros(3,3,CV_32F), mask1);
swap(mask, mask1);
absolut=1; // calcs abs of the image
menu();
while(1){
video >> cap;
cvtColor(cap, frame, CV_BGR2GRAY);
flip(frame, frame, 1);
imshow("original", frame);
frame.convertTo(frame32f, CV_32F);
filter2D(frame32f, frameFiltered, frame32f.depth(), mask, Point(1,1), 0);
if(absolut){
frameFiltered=abs(frameFiltered);
}
frameFiltered.convertTo(result, CV_8U);
imshow("filtroespacial", result);
key = (char) waitKey(10);
if( key == 27 ) break; // esc pressed!
switch(key){
case 'a':
menu();
absolut=!absolut;
break;
case 'm':
menu();
mask = Mat(3, 3, CV_32F, media);
scaleAdd(mask, 1/9.0, Mat::zeros(3,3,CV_32F), mask1);
mask = mask1;
printmask(mask);
break;
case 'g':
menu();
mask = Mat(3, 3, CV_32F, gauss);
scaleAdd(mask, 1/16.0, Mat::zeros(3,3,CV_32F), mask1);
mask = mask1;
printmask(mask);
break;
case 'h':
menu();
mask = Mat(3, 3, CV_32F, horizontal);
printmask(mask);
break;
case 'v':
menu();
mask = Mat(3, 3, CV_32F, vertical);
printmask(mask);
break;
case 'l':
menu();
mask = Mat(3, 3, CV_32F, laplacian);
printmask(mask);
break;
case 'z':
menu();
mask = Mat(5, 5, CV_32F, laplacianGauss);
printmask(mask);
break;
default:
break;
}
}
return 0;
}
| [
"vanessa.dantas796@gmail.com"
] | vanessa.dantas796@gmail.com |
89f2afeebfb8f0298b819fba812d6e3858439f2f | 8da5eb54981193d850a7e35439845a6b54326c65 | /VGP336/Engine/AssetLoader.cpp | 36d9b2c06c48200c3e197cfea196ac9dfb408fac | [] | no_license | tstaples/Cat3D | 7eb5cf590798e09a6bdb8bed68bd83fe903d43b8 | 795d3bfce0eb52b36324ffe9de99269bb40a6ec6 | refs/heads/master | 2021-01-15T20:43:48.676483 | 2015-08-14T00:53:56 | 2015-08-14T00:53:56 | 28,846,705 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,056 | cpp | #include "Precompiled.h"
#include "AssetLoader.h"
#include "AnimationClip.h"
#include "BoneAnimation.h"
#include "GraphicsSystem.h"
#include "Model.h"
#include "Mesh.h"
#include "MeshBuffer.h"
#include "MeshBuilder.h"
#include "TextureManager.h"
#include "Texture.h"
#include "IO.h"
#include "Path.h"
#include "FileBuffer.h"
#include "SerialReader.h"
#include "SerialWriter.h"
#include "Bone.h"
struct Header
{
u32 signature;
u32 version;
Header() {}
Header(u8 majver, u8 minver, const char* sig)
{
version = ((majver << 16) | ('.' << 8) | minver);
signature = ( (sig[3] << 24)
| (sig[2] << 16)
| (sig[1] << 8)
| (sig[0]));
}
inline std::pair<u8, u8> GetVersion() const
{
return GetVersion(version);
}
inline static std::pair<u8, u8> GetVersion(u32 v)
{
u8 maj = (v >> 16);
u8 min = (v >> 24);
return std::make_pair(maj, min);
}
};
AssetLoader::AssetLoader()
: mpGraphicsSystem(nullptr)
{
}
//----------------------------------------------------------------------------------------------------
void AssetLoader::Initialize(GraphicsSystem& gs)
{
mpGraphicsSystem = &gs;
mTextureManager.Initialize(gs);
}
//----------------------------------------------------------------------------------------------------
void AssetLoader::Terminate()
{
mTextureManager.Terminate();
mpGraphicsSystem = nullptr;
}
//----------------------------------------------------------------------------------------------------
bool AssetLoader::LoadModel(const wchar_t* pFilename, Model& model)
{
ASSERT(mpGraphicsSystem != nullptr, "[AssetLoader] Asset loader is unitialized");
// Get the asset type and pass to corresponding function
std::string extension = IO::GetExtension(pFilename);
if (extension.compare("catm") == 0)
{
return LoadCatmFile(pFilename, model);
}
return false;
}
//----------------------------------------------------------------------------------------------------
bool AssetLoader::LoadMesh(const wchar_t* pFilename, Mesh& mesh, MeshBuffer& meshBuffer, std::vector<Texture*>& textures)
{
ASSERT(mpGraphicsSystem != nullptr, "[AssetLoader] Asset loader is unitialized");
std::string extension = IO::GetExtension(pFilename);
if (extension.compare("catm") == 0)
{
std::string filename = IO::WCharToChar(pFilename);
IO::FileBuffer buffer(filename.c_str());
if (buffer.Initialized())
{
// Init the reader with the model data
SerialReader sin(buffer.GetBuffer(), buffer.Size());
// Read the signature and check that it matches
std::string sig = sin.ReadFormatted(4);
if (sig.compare("CATM") != 0)
{
return false;
}
const u32 version = sin.Read<u32>();
// Load the mesh data into the model
LoadSingleMesh(sin, mesh, meshBuffer);
// Load the texture paths from the file
StringVec paths;
LoadTexturesPaths(pFilename, sin, paths);
// Load the textures from the files into the model
LoadTextures(paths, textures);
return true;
}
}
return false;
}
//----------------------------------------------------------------------------------------------------
bool AssetLoader::LoadCatmFile(const wchar_t* pFilename, Model& model)
{
// Read the data into the buffer
std::string filename = IO::WCharToChar(pFilename);
IO::FileBuffer buffer(filename.c_str());
if (buffer.Initialized())
{
// Init the reader with the model data
SerialReader sin(buffer.GetBuffer(), buffer.Size());
// Read the signature and check that it matches
std::string sig = sin.ReadFormatted(4);
if (sig.compare("CATM") != 0)
{
return false;
}
const u32 version = sin.Read<u32>();
// Load the mesh data into the model
LoadMeshes(sin, model);
// Load the texture paths from the file
StringVec paths;
LoadTexturesPaths(pFilename, sin, paths);
// Load the textures from the files into the model
LoadTextures(paths, model.mTextures);
// Load bone data and weights, then link up pointers
LoadBones(sin, model);
LoadBoneWeights(sin, model);
LinkBones(model);
// TODO: fix version
//if (Header::GetVersion(version).second == 1)
//{
LoadAnimations(sin, model);
//}
}
return false;
}
//----------------------------------------------------------------------------------------------------
void AssetLoader::LoadMeshes(SerialReader& reader, Model& model)
{
u32 numMeshes = reader.Read<u32>();
for (u32 i=0; i < numMeshes; ++i)
{
// Read the verticies
u32 numVerts = reader.Read<u32>();
Mesh::Vertex* vertexBuffer = new Mesh::Vertex[numVerts];
reader.ReadArray(vertexBuffer, sizeof(Mesh::Vertex) * numVerts);
// Read in the indices
u32 numIndices = reader.Read<u32>();
u16* indexBuffer = new u16[numIndices];
reader.ReadArray(indexBuffer, sizeof(u16) * numIndices);
// Generate the push and add it to the model
Mesh* mesh = new Mesh();
MeshBuilder::GenerateMesh(*mesh, vertexBuffer, numVerts, indexBuffer, numIndices);
model.mMeshes.push_back(mesh);
// Clear the temp buffers
SafeDeleteArray(vertexBuffer);
SafeDeleteArray(indexBuffer);
// Create the mesh buffer and add it to the model
MeshBuffer* meshBuffer = new MeshBuffer();
meshBuffer->Initialize(*mpGraphicsSystem, Mesh::GetVertexFormat(), *mesh, true);
model.mMeshBuffers.push_back(meshBuffer);
}
}
//----------------------------------------------------------------------------------------------------
void AssetLoader::LoadSingleMesh(SerialReader& reader, Mesh& mesh, MeshBuffer& meshBuffer)
{
// Don't care about mesh count
reader.Seek(sizeof(u32), reader.Current);
// Read the verticies
u32 numVerts = reader.Read<u32>();
Mesh::Vertex* vertexBuffer = new Mesh::Vertex[numVerts];
reader.ReadArray(vertexBuffer, sizeof(Mesh::Vertex) * numVerts);
// Read in the indices
u32 numIndices = reader.Read<u32>();
u16* indexBuffer = new u16[numIndices];
reader.ReadArray(indexBuffer, sizeof(u16) * numIndices);
// Generate the push and add it to the model
MeshBuilder::GenerateMesh(mesh, vertexBuffer, numVerts, indexBuffer, numIndices);
// Clear the temp buffers
SafeDeleteArray(vertexBuffer);
SafeDeleteArray(indexBuffer);
// Create the mesh buffer and add it to the model
meshBuffer.Initialize(*mpGraphicsSystem, Mesh::GetVertexFormat(), mesh, true);
}
//----------------------------------------------------------------------------------------------------
void AssetLoader::LoadTextures(const StringVec& paths, std::vector<Texture*>& textures)
{
const u32 numTextures = paths.size();
for(auto path : paths)
{
wchar_t wbuffer[256];
IO::CharToWChar(path, wbuffer, 256);
Texture* texture = mTextureManager.GetResource(wbuffer);
textures.push_back(texture);
}
}
//----------------------------------------------------------------------------------------------------
void AssetLoader::LoadTexturesPaths(const wchar_t* pModelPath, SerialReader& reader, StringVec& paths)
{
// Get the directory the model is located in (assumes textures are located in same directory)
std::string modelpath = IO::WCharToChar(pModelPath); // HACK
std::string modelDir = IO::GetLocation(modelpath);
char tempPathBuffer[MAX_PATH];
u32 numTextures = reader.Read<u32>();
for (u32 i=0; i < numTextures; ++i)
{
// Read the length encode byte
u32 pathLength = reader.Read<u32>();
// Read pathLength # of bytes into the temp array
reader.ReadArray(tempPathBuffer, pathLength);
tempPathBuffer[pathLength] = '\0'; // Terminate the string
// Store the FULL path and clear the buffer
paths.push_back(modelDir + tempPathBuffer);
memset(tempPathBuffer, 0, MAX_PATH);
}
}
//----------------------------------------------------------------------------------------------------
void AssetLoader::LoadBones(SerialReader& reader, Model& model)
{
const u32 numBones = reader.Read<u32>();
model.mBones.resize(numBones);
for (u32 i=0; i < numBones; ++i)
{
Bone* bone = new Bone();
// Read the name
const u32 nameLen = reader.Read<u32>();
char nameBuffer[2048];
reader.ReadArray(nameBuffer, nameLen);
nameBuffer[nameLen] = '\0';
bone->name = nameBuffer;
// Add the bone to the index map
model.mBoneIndexMap.insert(std::make_pair(bone->name, i));
bone->parentIndex = reader.Read<u32>();
bone->index = i;
// Read in the children indices
const u32 numChildIndices = reader.Read<u32>();
reader.ReadVector(bone->childrenIndices, numChildIndices);
// Read in the transform and offset transform
bone->transform = reader.Read<Math::Matrix>();
bone->offsetTransform = reader.Read<Math::Matrix>();
// Store the bone in the model
model.mBones[i] = bone;
}
}
//----------------------------------------------------------------------------------------------------
void AssetLoader::LoadBoneWeights(SerialReader& reader, Model& model)
{
for (auto mesh : model.mMeshes)
{
const u32 numBoneWeights = reader.Read<u32>();
// Get the 2D vert weight array from each mesh and resize it
VertexWeights& vertexWeights = mesh->GetVertexWeights();
vertexWeights.resize(numBoneWeights);
for (u32 i=0; i < numBoneWeights; ++i)
{
// Get how many bone weights this vert has
const u32 numWeightsForThisVert = reader.Read<u32>();
for (u32 j=0; j < numWeightsForThisVert; ++j)
{
// Store the boneweight at the corresponding index for this vert
BoneWeight boneWeight = reader.Read<BoneWeight>();
vertexWeights[i].push_back(boneWeight);
}
}
}
}
//----------------------------------------------------------------------------------------------------
void AssetLoader::LinkBones(Model& model)
{
std::vector<Bone*>& bones = model.mBones;
for (auto bone : bones)
{
// Check the bone has a parent
const u32 parentIndex = bone->parentIndex;
if (parentIndex != NO_PARENT)
{
// Link parent pointer to element at parentIndex
bone->parent = bones[parentIndex];
}
else
{
// No parent; this bone is the root
model.mpRoot = bone;
}
// Expand children array to number of children
const u32 numChildren = bone->childrenIndices.size();
bone->children.resize(numChildren);
for (u32 i=0; i < numChildren; ++i)
{
// Store pointer to bone at childIndex's position in bone array
const u32 childIndex = bone->childrenIndices[i];
bone->children[i] = bones[childIndex];
}
}
}
//----------------------------------------------------------------------------------------------------
/*
* + Animations:
* | + Num animation clips (4)
* | + Animation Clip
* | | + Length encoded name (4 + c)
* | | + Duration (4)
* | | + TicksPerSecond (4)
* | | + KeyFrameCount (4)
* | | + Num bone animations (4)
* | | + BoneAnimation
* | | | + Bone index (4)
* | | | + Num keyframes (4)
* | | | + Keyframes
* | | | | + Translation (12)
* | | | | + Rotation (16)
* | | | | + Scale (12)
* | | | | + Time (4)
*/
void AssetLoader::LoadAnimations(SerialReader& reader, Model& model)
{
// Get the number of animation clips
const u32 numAnimClips = reader.Read<u32>();
model.mAnimations.resize(numAnimClips);
for (u32 i=0; i < numAnimClips; ++i)
{
// Read in the clip data
AnimationClip* animClip = new AnimationClip();
animClip->mName = reader.ReadLengthEncodedString();
animClip->mDuration = reader.Read<f32>();
animClip->mTicksPerSecond = reader.Read<f32>();
// Resize the bone animation array to the number of bones
const u32 numBones = model.mBones.size();
animClip->mBoneAnimations.resize(numBones);
const u32 numBoneAnimations = reader.Read<u32>();
for (u32 j=0; j < numBoneAnimations; ++j)
{
BoneAnimation* boneAnim = new BoneAnimation();
boneAnim->mBoneIndex = reader.Read<u32>();
// Get the number of keyframes and resize the array
const u32 numKeyframes = reader.Read<u32>();
boneAnim->mKeyframes.resize(numKeyframes);
for (u32 k=0; k < numKeyframes; ++k)
{
// Read in the keyframe
boneAnim->mKeyframes[k] = new Keyframe();
*boneAnim->mKeyframes[k] = reader.Read<Keyframe>();
}
// Store the animation at the corresponding bone's index
animClip->mBoneAnimations[boneAnim->mBoneIndex] = boneAnim;
}
model.mAnimations[i] = animClip;
}
} | [
"Tyler.A.Staples@gmail.com"
] | Tyler.A.Staples@gmail.com |
c3473fa459a641ca4c76c6bf21792693725a94e8 | e8a1b91fc129c2f5bd274fc3d18f45f4e5ca9769 | /qpOASES/examples/example1.cpp | 5b11640c20a5c586ddbf17443318d8c4f7c5f36f | [] | no_license | longjianquan/qpoases | 15b4aa8f7011641414effde47c4568abc0c6f396 | 4c59345f994250477ee032321d52278c3d268d75 | refs/heads/master | 2020-11-26T22:22:38.543557 | 2019-12-20T07:56:33 | 2019-12-20T07:56:33 | 229,217,118 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,519 | cpp | /*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file examples/example1.cpp
* \author Hans Joachim Ferreau
* \version 3.2
* \date 2007-2017
*
* Very simple example for testing qpOASES using the QProblem class.
*/
#include <qpOASES1.hpp>
/** Example for qpOASES main function using the QProblem class. */
int main( )
{
USING_NAMESPACE_QPOASES
/* Setup data of first QP. */
real_t H[2*2] = { 1.0, 0.0, 0.0, 0.5 };
real_t A[1*2] = { 1.0, 1.0 };
real_t g[2] = { 1.5, 1.0 };
real_t lb[2] = { 0.5, -2.0 };
real_t ub[2] = { 5.0, 2.0 };
real_t lbA[1] = { -1.0 };
real_t ubA[1] = { 2.0 };
/* Setup data of second QP. */
real_t g_new[2] = { 1.0, 1.5 };
real_t lb_new[2] = { 0.0, -1.0 };
real_t ub_new[2] = { 5.0, -0.5 };
real_t lbA_new[1] = { -2.0 };
real_t ubA_new[1] = { 1.0 };
/* Setting up QProblem object. */
QProblem example( 2,1 );
/*
Options options;
example.setOptions( options );
int_t nWSR = 10;
example.init( H,g,A,lb,ub,lbA,ubA, nWSR );
real_t xOpt[2];
real_t yOpt[2+1];
example.getPrimalSolution( xOpt );
example.getDualSolution( yOpt );
printf( "\nxOpt = [ %e, %e ]; yOpt = [ %e, %e, %e ]; objVal = %e\n\n",
xOpt[0],xOpt[1],yOpt[0],yOpt[1],yOpt[2],example.getObjVal() );
nWSR = 10;
example.hotstart( g_new,lb_new,ub_new,lbA_new,ubA_new, nWSR );
example.getPrimalSolution( xOpt );
example.getDualSolution( yOpt );
printf( "\nxOpt = [ %e, %e ]; yOpt = [ %e, %e, %e ]; objVal = %e\n\n",
xOpt[0],xOpt[1],yOpt[0],yOpt[1],yOpt[2],example.getObjVal() );
example.printOptions();
*/
return 0;
}
/*
* end of file
*/
| [
"1014896847@qq.com"
] | 1014896847@qq.com |
a428ed4089f75a2ed7aeb12d3ebee691afae82b8 | 71e4d166f8ccab62379730b7fbc671bfd7915ea8 | /чм.1лаба/Rational.cpp | f63779069f687c86a0ed3d88f27c62fd92ef1720 | [] | no_license | alekstimo/chm1 | 076b6539e5d6143398730e191cd10af303f65006 | 4d22421cf11f51db3dda21a2d08814433c9e714a | refs/heads/master | 2023-08-12T22:08:35.317539 | 2021-09-22T16:00:54 | 2021-09-22T16:00:54 | 409,267,824 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,523 | cpp | #include "Rational.h"
void Rational::reduce()
{
if (*b < 0)
{
*a *= -1;
*b *= -1;
}
for (int i = *b; i > 1; i--)
if (*a % i == 0 && *b % i == 0)
{
*a /= i;
*b /= i;
}
}
Rational::Rational(int A, int B)
{
a = new int;
*a = A;
b = new int;
*b = B;
}
Rational::Rational(int A)
{
a = new int;
*a = A;
b = new int;
*b = 1;
}
Rational::Rational(const Rational & obj)
{
a = new int;
*a = *(obj.a);
b = new int;
*b = *(obj.b);
}
void Rational::set(int A)
{
*a = A;
}
Rational::~Rational()
{
delete a;
delete b;
}
Rational Rational::operator+(Rational obj)
{
reduce(); obj.reduce();
Rational temp;
if (*a == 0) {
*temp.a = *obj.a;
*temp.b = *obj.b;
}
else if (*b == *obj.b) {
*temp.a = *a - *obj.a;
*temp.b = *b;
}
else {
*temp.a = (*a) * (*obj.b) + (*b) * (*obj.a);
*temp.b *= (*obj.b)*(*b);
}
/*if (*b == *obj.b) {
*temp.a = *a + *obj.a;
*temp.b = *b;
}
else {
*temp.b = nok(*b, *obj.b);
*temp.a = (*a)*(*temp.b/(*b))+(*obj.a)*(*temp.b / (*obj.b));
}*/
temp.reduce();
return temp;
}
Rational Rational::operator-(Rational obj)
{
reduce(); obj.reduce();
Rational temp;
if (*a == 0) {
*temp.a -= *obj.a;
*temp.b = *obj.b;
}
else if (*b == *obj.b) {
*temp.a = *a - *obj.a;
*temp.b = *b;
}
else {
*temp.a = (*a) * (*obj.b) - (*b) * (*obj.a);
*temp.b *= (*obj.b)*(*b);
}
/*if (*b == *obj.b) {
*temp.a = *a - *obj.a;
*temp.b = *b;
}
else {
*temp.b = nok(*b, *obj.b);
*temp.a = (*a)*(*temp.b / (*b)) - (*obj.a)*(*temp.b / (*obj.b));
}*/
temp.reduce();
return temp;
}
Rational Rational::operator*(Rational obj)
{
reduce(); obj.reduce();
Rational temp;
*temp.a = (*a) * (*obj.a);
*temp.b = (*b) * (*obj.b);
temp.reduce();
return temp;
}
Rational Rational::operator/(Rational obj)
{
reduce(); obj.reduce();
Rational temp;
*temp.a = (*a)*(*obj.b);
*temp.b = (*b)*(*obj.a);
if (*temp.b < 0)
{
*temp.a *= -1;
*temp.b *= -1;
}
temp.reduce();
return temp;
}
bool Rational::operator==(Rational obj)
{
reduce(); obj.reduce();
return (*a == *obj.a && *b == *obj.b);
}
bool Rational::operator!=(Rational obj)
{
reduce(); obj.reduce();
return (!(*a == *obj.a && *b == *obj.b));
}
bool Rational::operator>(Rational obj)
{
reduce(); obj.reduce(); bool f = 0;
if (*b == *obj.b) {
if (*a > *obj.a) f = 1;
}
else
if ((*a)*(nok(*b, *obj.b) / (*b)) > (*obj.a)*(nok(*b, *obj.b) / (*obj.b))) f = 1;
return f;
}
bool Rational::operator>=(Rational obj)
{
return !(operator<(obj));
}
bool Rational::operator<(Rational obj)
{
reduce(); obj.reduce(); bool f = 0;
if (*b == *obj.b) {
if (*a < *obj.a) f = 1;
}
else
if ((*a)*(nok(*b, *obj.b) / (*b)) < (*obj.a)*(nok(*b, *obj.b) / (*obj.b))) f = 1;
return f;
}
bool Rational::operator<=(Rational obj)
{
return !(operator>(obj));
}
Rational Rational::operator=(Rational obj)
{
*a = *(obj.a);
*b = *(obj.b);
return *this;
}
ostream & operator<<(ostream & out, Rational & obj)
{
if (*obj.b == 1) {
out << /*"a/b = "<<*/ *obj.a << "\t";
}
else if (*obj.a == 0) {
out << /*"a/b = "<<*/ *obj.a << "\t";
}
else {
out << /*"a/b = "<<*/ *obj.a << "/" << *obj.b<<"\t";
}
return out;
}
istream & operator>> (istream & in, Rational & obj)
{
cout << "a = ";
in >> *obj.a;
cout << "b = ";
in >> *obj.b;
cout << endl;
return in;
}
int nod(int a, int b)
{
while (a > 0 && b > 0) {
if (a > b)
a %= b;
else
b %= a;
}
return a + b;
}
int nok(int a, int b)
{
int n = nod(a, b);
if (n != 0)
n = (a*b) / n;
else n = 0;
return n;
}
| [
"alekstim01@gmail.com"
] | alekstim01@gmail.com |
f4f8c735815a65c83c19648c5d4a91fc05faf6dc | d4062fd61ad649b92557e4887c6455fac1b9e741 | /src/plugins/organisation/FileBrowserWindow/src/filebrowserwindowwidget.cpp | d4e8b470686da34d975d546b7bf16a7f336302ce | [
"Apache-2.0"
] | permissive | nickerso/opencor | 0684719a2f8f4568d8cbeb6b02f1fecb10985add | 63e164c6424dc855a4e46b835a777f6f84c617dc | refs/heads/master | 2021-01-18T00:33:34.416451 | 2015-05-12T17:34:10 | 2015-05-12T17:34:10 | 10,351,756 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,154 | cpp | /*******************************************************************************
Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
*******************************************************************************/
//==============================================================================
// File browser widget
//==============================================================================
#include "filebrowserwindowwidget.h"
//==============================================================================
#include <QApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QHeaderView>
#include <QHelpEvent>
#include <QModelIndex>
#include <QSettings>
//==============================================================================
namespace OpenCOR {
namespace FileBrowserWindow {
//==============================================================================
FileBrowserWindowWidget::FileBrowserWindowWidget(QWidget *pParent) :
TreeViewWidget(pParent),
mNeedDefColWidth(true),
mInitPathDirs(QStringList()),
mInitPathDir(QString()),
mInitPath(QString()),
mPreviousItems(QStringList()),
mNextItems(QStringList())
{
// Create an instance of the file system model that we want to view
mModel = new FileBrowserWindowModel(this);
// Set some properties for the file browser widget itself
setDragDropMode(QAbstractItemView::DragOnly);
setFrameShape(QFrame::StyledPanel);
setModel(mModel);
setSortingEnabled(true);
header()->setSectionsMovable(false);
// Some connections
connect(selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
this, SLOT(itemChanged(const QModelIndex &, const QModelIndex &)));
connect(mModel, SIGNAL(directoryLoaded(const QString &)),
this, SLOT(directoryLoaded(const QString &)));
}
//==============================================================================
static const auto SettingsColumnWidth = QStringLiteral("ColumnWidth%1");
static const auto SettingsInitialPath = QStringLiteral("InitialPath");
static const auto SettingsSortColumn = QStringLiteral("SortColumn");
static const auto SettingsSortOrder = QStringLiteral("SortOrder");
//==============================================================================
void FileBrowserWindowWidget::loadSettings(QSettings *pSettings)
{
// We are about to begin loading the settings, so we don't want to keep
// track of the change of item
disconnect(selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
this, SLOT(itemChanged(const QModelIndex &, const QModelIndex &)));
// Retrieve the width of each column
QString columnWidthKey;
for (int i = 0, iMax = header()->count(); i < iMax; ++i) {
columnWidthKey = SettingsColumnWidth.arg(i);
mNeedDefColWidth = mNeedDefColWidth
&& !pSettings->contains(columnWidthKey);
setColumnWidth(i, pSettings->value(columnWidthKey,
columnWidth(i)).toInt());
}
// Retrieve the sorting information
sortByColumn(pSettings->value(SettingsSortColumn, 0).toInt(),
Qt::SortOrder(pSettings->value(SettingsSortOrder,
Qt::AscendingOrder).toInt()));
// Retrieve the initial path
mInitPath = pSettings->value(SettingsInitialPath,
QDir::homePath()).toString();
QFileInfo initPathFileInfo = mInitPath;
if (!initPathFileInfo.exists()) {
// The initial path doesn't exist, so just revert to the home path
mInitPathDir = QDir::homePath();
mInitPath = "";
} else {
// The initial path exists, so retrieve some information about the
// folder and/or file (depending on whether the initial path refers to a
// file)
// Note: indeed, should mInitPath refer to a file, then to directly set
// the current index of the tree view widget to that of a file
// won't give us the expected behaviour (i.e. the parent folder
// being open and expanded, and the file selected), so instead
// one must set the current index to that of the parent folder
// and then select the file
if (initPathFileInfo.isDir()) {
// We are dealing with a folder
mInitPathDir = initPathFileInfo.canonicalFilePath();
mInitPath = "";
} else {
// We are dealing with a file
mInitPathDir = initPathFileInfo.canonicalPath();
mInitPath = initPathFileInfo.canonicalFilePath();
}
}
// On Windows, if mInitPathDir refers to the root of a particular drive
// (e.g. the C: drive), then it won't include a trailing separator (i.e.
// "C:" instead of "C:/") and this causes problems below (when wanting to
// retrieve the different folders), so we must make sure that that
// mInitPathDir contains a trailing separator
// Note: this is clearly not needed on Linux and OS X, but it doesn't harm
// doing it for these platforms too...
mInitPathDir = QDir(mInitPathDir+QDir::separator()).canonicalPath();
// Create a list of the different folders that need to be loaded to consider
// that the loading of the settings is finished (see just below and the
// directoryLoaded slot)
mInitPathDirs << mInitPathDir;
QDir initPathDir = mInitPathDir;
while (initPathDir.cdUp())
mInitPathDirs << initPathDir.canonicalPath();
// Set the current index to that of the folder (and file, if it exists) in
// which we are interested
// Note: this will result in the directoryLoaded signal being emitted and,
// us, to take advantage of it to scroll to the right
// directory/file...
setCurrentIndex(mModel->index(mInitPathDir));
if (!mInitPath.isEmpty())
setCurrentIndex(mModel->index(mInitPath));
// Make sure that the current path is expanded
// Note: this is important in case the current path is that of the C: drive
// or the root of the file system, in which case this won't result in
// the directoryLoaded signal being emitted
if (!isExpanded(currentIndex()))
setExpanded(currentIndex(), true);
// Let the user know of a few default things about ourselves by emitting a
// few signals
emitItemChangedRelatedSignals();
}
//==============================================================================
void FileBrowserWindowWidget::saveSettings(QSettings *pSettings) const
{
// Keep track of the width of each column
for (int i = 0, iMax = header()->count(); i < iMax; ++i)
pSettings->setValue(SettingsColumnWidth.arg(i), columnWidth(i));
// Keep track of the sorting information
pSettings->setValue(SettingsSortColumn,
header()->sortIndicatorSection());
pSettings->setValue(SettingsSortOrder, header()->sortIndicatorOrder());
// Keep track of what will be our future initial folder/file path
pSettings->setValue(SettingsInitialPath,
mModel->filePath(currentIndex()));
}
//==============================================================================
QStringList FileBrowserWindowWidget::selectedFiles() const
{
// Retrieve all the files that are currently selected
// Note: if there is a non-file among the selected items, then we return an
// empty list
QStringList res;
QModelIndexList selectedIndexes = selectionModel()->selectedIndexes();
for (int i = 0, iMax = selectedIndexes.count(); i < iMax; ++i) {
QString fileName = pathOf(selectedIndexes[i]);
QFileInfo fileInfo = fileName;
if (fileInfo.isFile()) {
if (fileInfo.isSymLink()) {
// The current item is a symbolic link, so retrieve its target
// and check that it exists, and if it does then add it to the
// list
fileName = fileInfo.symLinkTarget();
if (QFile::exists(fileName))
res << fileName;
} else {
// The current item is a file, so just add to the list
res << fileName;
}
}
}
// Remove duplicates (which might be present as a result of symbolic links)
res.removeDuplicates();
return res;
}
//==============================================================================
void FileBrowserWindowWidget::deselectFolders() const
{
// Check whether more than one item is selected with the view of dragging
// them and, if so, unselect any folder item since we don't allow them to be
// dragged
if (selectionModel()->selectedRows().count() > 1) {
QModelIndexList selectedIndexes = selectionModel()->selectedIndexes();
for (int i = 0, iMax = selectedIndexes.count(); i < iMax; ++i) {
QFileInfo fileInfo = pathOf(selectedIndexes[i]);
if (fileInfo.isDir() || !fileInfo.exists())
// Either we are dealing with a directory or an entry that
// doesn't actually exist (e.g. on Windows, it could be a drive
// for a removable device with the device not being present)
selectionModel()->select(selectedIndexes[i],
QItemSelectionModel::Deselect);
}
}
}
//==============================================================================
void FileBrowserWindowWidget::emitItemChangedRelatedSignals()
{
// Let the user know whether the path of the new item is not that of our
// home folder, as well as whether we could go to the parent item
emit notHomeFolder(currentPath() != QDir::homePath());
emit goToParentFolderEnabled(!currentPathParent().isEmpty());
// Let the user know whether we can go to the previous/next file/folder
emit goToPreviousFileOrFolderEnabled(mPreviousItems.count());
emit goToNextFileOrFolderEnabled(mNextItems.count());
}
//==============================================================================
void FileBrowserWindowWidget::updateItems(const QString &pItemPath,
QStringList &pItems) const
{
// Remove any instance of pItemPath in pItems
pItems.removeAll(pItemPath);
// Because of the above, we may have two or more consective identital items
// in the list, so we must reduce that to one
if (pItems.count() > 1) {
QStringList newItems;
QString prevItem = pItems.first();
newItems << prevItem;
for (int i = 1, iMax = pItems.count(); i < iMax; ++i) {
QString crtItem = pItems[i];
if (crtItem != prevItem) {
// The current and previous items are different, so we want to
// keep track of it and add it to our new list
newItems << crtItem;
prevItem = crtItem;
}
}
// Update the old list of items with our new one
pItems = newItems;
}
}
//==============================================================================
void FileBrowserWindowWidget::goToOtherItem(QStringList &pItems,
QStringList &pOtherItems)
{
if (pItems.isEmpty())
return;
// Go to the previous/next item and move the last item from our list of
// items to our list of other items
// First, we must stop keeping track of the change of item otherwise it's
// going to mess things up
disconnect(selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
this, SLOT(itemChanged(const QModelIndex &, const QModelIndex &)));
// Retrieve our current path and add it to our list of other items
QString crtPath = currentPath();
pOtherItems << crtPath;
// Retrieve the new path and check whether it still exists
QString newItemPath = pItems.last();
while (!pItems.isEmpty() && !QFile::exists(newItemPath)) {
// The new item doesn't exist anymore, so remove it from our list of
// items and other items
updateItems(newItemPath, pItems);
updateItems(newItemPath, pOtherItems);
// Try with the next new item
if (!pItems.isEmpty()) {
// The list is not empty, so make the last item our next new item
newItemPath = pItems.last();
// The next new item cannot, however, be the same as the current
// path
while (!pItems.isEmpty() && (newItemPath == crtPath)) {
pItems.removeLast();
if (!pItems.isEmpty())
newItemPath = pItems.last();
else
newItemPath = "";
}
} else {
newItemPath = "";
}
}
if (!newItemPath.isEmpty()) {
// We have a valid new item, so go to its path and remove it from our
// list of items
goToPath(newItemPath);
pItems.removeLast();
}
// Make sure that the last item in the lists of items and other items isn't
// that of the current path (this may happen if some items got deleted by
// the user)
crtPath = currentPath();
if (!pItems.isEmpty() && (pItems.last() == crtPath))
pItems.removeLast();
if (!pOtherItems.isEmpty() && (pOtherItems.last() == crtPath))
pOtherItems.removeLast();
// Now that we are done, we can once again keep track of the change of item
connect(selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
this, SLOT(itemChanged(const QModelIndex &, const QModelIndex &)));
// Let the user know about a few item changed related things
emitItemChangedRelatedSignals();
}
//==============================================================================
void FileBrowserWindowWidget::keyPressEvent(QKeyEvent *pEvent)
{
// Default handling of the event
TreeViewWidget::keyPressEvent(pEvent);
// Deselect folders, if required
deselectFolders();
// Let people know about a key having been pressed with the view of opening
// one or several files
QStringList crtSelectedFiles = selectedFiles();
if ( crtSelectedFiles.count()
&& ((pEvent->key() == Qt::Key_Enter) || (pEvent->key() == Qt::Key_Return)))
// There are some files that are selected and we want to open them, so
// let people know about it
emit filesOpenRequested(crtSelectedFiles);
}
//==============================================================================
void FileBrowserWindowWidget::mouseMoveEvent(QMouseEvent *pEvent)
{
// Default handling of the event
TreeViewWidget::mouseMoveEvent(pEvent);
// Deselect folders, if required
deselectFolders();
}
//==============================================================================
void FileBrowserWindowWidget::mousePressEvent(QMouseEvent *pEvent)
{
// Default handling of the event
TreeViewWidget::mousePressEvent(pEvent);
// Deselect folders, if required
deselectFolders();
}
//==============================================================================
bool FileBrowserWindowWidget::viewportEvent(QEvent *pEvent)
{
if (pEvent->type() == QEvent::ToolTip) {
// We need to show a tool tip, so make sure that it's up to date by
// setting it to the path of the current item
QHelpEvent *helpEvent = static_cast<QHelpEvent *>(pEvent);
setToolTip(QDir::toNativeSeparators(mModel->filePath(indexAt(helpEvent->pos()))));
}
// Default handling of the event
return TreeViewWidget::viewportEvent(pEvent);
}
//==============================================================================
void FileBrowserWindowWidget::itemChanged(const QModelIndex &,
const QModelIndex &pPrevItem)
{
// A new item has been selected, so we need to keep track of the old one in
// case we want to go back to it
mPreviousItems << pathOf(pPrevItem);
// Reset the list of next items since that list doesn't make sense anymore
mNextItems.clear();
// Let the user know about a few item changed related things
emitItemChangedRelatedSignals();
}
//==============================================================================
void FileBrowserWindowWidget::directoryLoaded(const QString &pPath)
{
static bool needInitializing = true;
if (needInitializing
&& ( ( mInitPath.isEmpty() && mInitPathDir.contains(pPath))
|| (!mInitPath.isEmpty() && mInitPath.contains(pPath)))) {
// mModel is still loading the initial path, so we try to expand it and
// scroll to it, but first we process any pending event (indeed, though
// Windows doesn't need this, Linux and OS X definitely do and it can't
// harm having it for all three environments)
qApp->processEvents();
QModelIndex initPathDirIndex = mModel->index(mInitPathDir);
setExpanded(initPathDirIndex, true);
scrollTo(initPathDirIndex);
setCurrentIndex(initPathDirIndex);
if (!mInitPath.isEmpty()) {
// The initial path is that of a file and it exists, so select it
QModelIndex initPathIndex = mModel->index(mInitPath);
scrollTo(initPathIndex);
setCurrentIndex(initPathIndex);
}
// Set the default width of the columns, if needed, so that it fits
// their contents
if (mNeedDefColWidth)
resizeColumnsToContents();
// Remove the loaded directory from mInitPathDirs
mInitPathDirs.removeOne(QDir(pPath+QDir::separator()).canonicalPath());
// Note #1: it is very important, on Windows, to add QDir::separator()
// to pPath. Indeed, say that mInitPathDir is on the C: drive,
// then eventually pPath will be equal to "C:" while
// mInitPathDirs will know about "C:/"...
// Note #2: this is clearly not needed on Linux and OS X, but it doesn't
// harm adding it for these platforms too...
// Check whether we are done initializing
if (mInitPathDirs.isEmpty()) {
// We are now done loading the settings for the file browser widget,
// so we can now keep track of the change of item
connect(selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)),
this, SLOT(itemChanged(const QModelIndex &, const QModelIndex &)));
needInitializing = false;
}
}
}
//==============================================================================
void FileBrowserWindowWidget::goToPath(const QString &pPath,
const bool &pExpand)
{
// Set the current index to that of the provided path
QModelIndex pathIndex = mModel->index(pPath);
if ((pathIndex.isValid()) && (pathIndex != currentIndex())) {
// The path exists, so we can go to it
if (pExpand)
setExpanded(pathIndex, true);
setCurrentIndex(pathIndex);
}
}
//==============================================================================
void FileBrowserWindowWidget::goToHomeFolder()
{
// Go to the home folder
goToPath(QDir::homePath(), true);
}
//==============================================================================
void FileBrowserWindowWidget::goToParentFolder()
{
// Go to the parent folder
goToPath(currentPathParent());
}
//==============================================================================
void FileBrowserWindowWidget::goToPreviousFileOrFolder()
{
// Go to the previous file/folder
goToOtherItem(mPreviousItems, mNextItems);
}
//==============================================================================
void FileBrowserWindowWidget::goToNextFileOrFolder()
{
// Go to the next file/folder
goToOtherItem(mNextItems, mPreviousItems);
}
//==============================================================================
QString FileBrowserWindowWidget::currentPath() const
{
// Return the current path
return mModel->filePath(currentIndex());
}
//==============================================================================
QString FileBrowserWindowWidget::currentPathParent() const
{
// Return the current path parent, if any
QModelIndex crtIndexParent = currentIndex().parent();
return crtIndexParent.isValid()?mModel->filePath(crtIndexParent):QString();
}
//==============================================================================
QString FileBrowserWindowWidget::pathOf(const QModelIndex &pIndex) const
{
// Return the file path of pIndex, if it exists
return pIndex.isValid()?mModel->filePath(pIndex):QString();
}
//==============================================================================
} // namespace FileBrowserWindow
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
| [
"agarny@hellix.com"
] | agarny@hellix.com |
debe8bc07239751df74d7b3f9a96962a19b1fba0 | 5eb01b2eff25fb0d8fbbb00b02961e565ac3f415 | /widgetkit/httpimagetoolbutton.h | 5316909fa421b0ed7b53628cf5f27703a2fb585c | [] | no_license | biglone/LT-PureCodes | 3ca6fc47731e2d566cd1c5389cce93e55768933a | 22d7ec1a1414bc99a16a050800a2cc9259546b9a | refs/heads/master | 2020-05-04T10:29:03.603664 | 2019-04-02T14:23:40 | 2019-04-02T14:23:40 | 179,088,457 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,043 | h | #ifndef HTTPIMAGETOOLBUTTON_H
#define HTTPIMAGETOOLBUTTON_H
#include <QToolButton>
#include <QPointer>
#include <QVariantMap>
#include "widgetkit_global.h"
class QNetworkAccessManager;
class QNetworkReply;
class WIDGETKIT_EXPORT HttpImageToolButton : public QToolButton
{
Q_OBJECT
public:
HttpImageToolButton(QWidget *parent);
~HttpImageToolButton();
void setNetworkAccessManager(QNetworkAccessManager *networkAccessManager);
void setCacheDir(const QString &cacheDir);
void setHttpUrl(const QString &urlString);
void setData(const QString &name, const QVariant &val);
QVariant data(const QString &name) const;
private slots:
void httpFinished(QNetworkReply *reply);
private:
QString cacheFileName(const QString &urlString);
void getImage();
private:
QPointer<QNetworkAccessManager> m_networkAccessManager;
QString m_cacheDir;
QString m_urlString;
QNetworkReply *m_networkReply;
QVariantMap m_data;
};
#endif // HTTPIMAGETOOLBUTTON_H
| [
"jjoyceu@gmail.com"
] | jjoyceu@gmail.com |
85f4499e15dfba17ac131bbb06ada02094e9a699 | 117907ec407f9cee0b1f1f4ba4f42c9d99caab37 | /src/sqleventmodel.cpp | 71ba4291fec4edb6692bea25c4e9e869c071a2d9 | [] | no_license | alesnando/calendar | ea2cb9970da3c24de33323a873e499d6141f3ea9 | 9ef77f023bf30a89f4adf7b61939a17e6350d632 | refs/heads/master | 2021-01-10T14:27:36.470506 | 2016-03-30T18:09:57 | 2016-03-30T18:09:57 | 55,085,981 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,080 | cpp | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "sqleventmodel.h"
#include <QDebug>
#include <QFileInfo>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlDriver>
#include <QTime>
SqlEventModel::SqlEventModel() :
QSqlQueryModel()
{
createConnection();
}
QList<QObject*> SqlEventModel::eventsForDate(const QDate &date)
{
const QString queryStr = QString::fromLatin1("SELECT * FROM Event WHERE '%1' >= startDate AND '%1' <= endDate order by startTime asc ").arg(date.toString("yyyy-MM-dd"));
QSqlQuery query(queryStr);
if (!query.exec())
qFatal("Query failed");
QList<QObject*> events;
while (query.next()) {
Event *event = new Event(this);
event->setName(query.value("name").toString());
QDateTime startDate;
startDate.setDate(query.value("startDate").toDate());
startDate.setTime(query.value("startTime").toTime());
event->setStartDate(startDate);
QDateTime endDate;
endDate.setDate(query.value("endDate").toDate());
endDate.setTime(query.value("endTime").toTime());
event->setEndDate(endDate);
events.append(event);
}
return events;
}
QList<QObject*> SqlEventModel::listaEventsForDate(const QDate &date)
{
const QString queryStr = QString::fromLatin1("SELECT * FROM Event WHERE '%1' >= startDate AND '%1' <= endDate order by startTime asc ").arg(date.toString("yyyy-MM-dd"));
QSqlQuery query(queryStr);
if (!query.exec())
qFatal("Query failed");
QList<QObject*> events;
while (query.next()) {
Event *event = new Event(this);
event->setName(query.value("name").toString());
QDateTime startDate;
startDate.setDate(query.value("startDate").toDate());
startDate.setTime(query.value("startTime").toTime());
event->setStartDate(startDate);
QDateTime endDate;
endDate.setDate(query.value("endDate").toDate());
endDate.setTime(query.value("endTime").toTime());
event->setEndDate(endDate);
events.append(event);
}
return events;
}
bool SqlEventModel::nuevoEvent(QString nombre, QDateTime fechaInicio, QDateTime fechaFin)
{
QTime horaInicio = fechaInicio.time();
QTime horaFin = fechaFin.time();
QSqlQuery query;
// We store the time as seconds because it's easier to query.
query.prepare("insert into Event values(:nombre, :fechaInicio, :horaInicio, :fechaFin, :horaFin)");
query.bindValue(":nombre", nombre);
query.bindValue(":fechaInicio", fechaInicio.date());
query.bindValue(":horaInicio", horaInicio);
query.bindValue(":fechaFin", fechaFin.date());
query.bindValue(":horaFin", horaFin);
bool inserto = query.exec();
if(inserto){
listaEventsForDate(fechaInicio.date());
}
return inserto;
}
QList<QObject*> SqlEventModel::eliminarEvent(const QDate &fecha)
{
const QString queryStr = QString::fromLatin1("SELECT * FROM Event WHERE '%1' >= startDate AND '%1' <= endDate order by startTime asc ").arg(fecha.toString("yyyy-MM-dd"));
QSqlQuery query(queryStr);
if (!query.exec())
qFatal("Query failed");
QList<QObject*> events;
while (query.next()) {
Event *event = new Event(this);
event->setName(query.value("name").toString());
QDateTime startDate;
startDate.setDate(query.value("startDate").toDate());
startDate.setTime(query.value("startTime").toTime());
event->setStartDate(startDate);
QDateTime endDate;
endDate.setDate(query.value("endDate").toDate());
endDate.setTime(query.value("endTime").toTime());
event->setEndDate(endDate);
events.append(event);
}
Event *primerEvento = qobject_cast<Event *> (events.first());
QSqlQuery queryD;
// We store the time as seconds because it's easier to query.
queryD.prepare("delete from Event where name = :nombre ");
queryD.bindValue(":nombre", primerEvento->name());
queryD.exec();
events.removeFirst();
return events;
}
/*
Defines a helper function to open a connection to an
in-memory SQLITE database and to create a test table.
*/
void SqlEventModel::createConnection()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
// db.setHostName("127.0.0.1");
db.setDatabaseName(":memory:");
// db.setUserName("root");
// db.setPassword("root");
if (!db.open()) {
qFatal("Cannot open database");
return;
}
QSqlQuery query;
// We store the time as seconds because it's easier to query.
query.exec("create table Event (name TEXT, startDate DATE, startTime DATETIME, endDate DATE, endTime DATETIME)");
query.exec("insert into Event values('Juan Perez', '2016-03-01', '08:00:00', '2016-03-01', '08:30:00')");
query.exec("insert into Event values('Pedro Salazar', '2016-03-01', '09:00:00', '2016-03-01', '09:30:00')");
query.exec("insert into Event values('Roberto Rojas', '2016-03-15', '08:00:00', '2016-03-15', '08:30:00')");
query.exec("insert into Event values('Ana Castro', '2016-03-24', '08:00:00', '2016-03-28', '08:30:00')");
return;
}
| [
"ing.acevedo.fer@gmail.com"
] | ing.acevedo.fer@gmail.com |
680a1017b491ce6622da5d08722dbf6b2569c7de | 1602d7429bb360edbe28016cfcf93f9f1247042f | /nec/src/nec.ino | 7fd9b41472da5bca2cca67f0f773f9ebee15f0bc | [] | no_license | DrPity/codedReality | c21dbf296fef0670f033fbe915396aa7d5815522 | ec7aca770980ff6144ae0286fd7e495a50d67a5a | refs/heads/master | 2021-01-10T17:07:56.319415 | 2016-02-05T19:49:28 | 2016-02-05T19:49:28 | 50,681,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,316 | ino | ///////REMEMBER TO SET THIS FUCKING VALUE
#define STRIP_PIN_L 2
#define STRIP_PIN_R 9
#define NUMBEROFPIXELS 8
#define NUMSTRIPS 2
#define NUMBEROFTIMERS 6
#include <Adafruit_NeoPixel.h>
#include "wrapper_class.h"
#include <Brain.h>
// Set up the brain parser, pass it the hardware serial object you want to listen on.
Brain brain(Serial);
uint8_t fadeSpeed = 1;
int attentionLevel = 0;
int attentionLevelOld = 0;
int meditationLevel = 0;
int meditationLevelOld = 0;
int signalStrength = 0;
uint32_t delta = 0;
uint32_t deltaOld = 0;
uint32_t theta = 0;
uint32_t thetaOld = 0;
bool setStrip = true;
bool aGoodSignalStreak = false;
bool colorReached = false;
bool started = false;
bool isMeditation = false;
bool isAttenttion = false;
bool isNeutral = false;
bool isTheta = false;
bool isDelta = false;
bool isNeutralDT = false;
uint8_t end = 10;
uint32_t waitTime[NUMBEROFTIMERS];
uint32_t currentTime[NUMBEROFTIMERS];
String inByte;
Wrapper_class strips[] = {
Wrapper_class(NUMBEROFPIXELS, STRIP_PIN_R),
Wrapper_class(NUMBEROFPIXELS, STRIP_PIN_L),
};
void setup() {
Serial.begin(57600);
for (int i = 0; i < NUMSTRIPS; ++i)
{
strips[i].init();
strips[i].setStripColor(0,255,0);
strips[i].show();
}
delay(2000);
setTargetColor(255,255,255);
//wait Nr 1:
wait(3000,0);
//wait Nr 2: Checks
wait(5000,1);
//wait Nr3: Checks Signal Quality
wait(500,2);
Serial.print("Setup");
}
void loop() {
if (Serial.available() > 0){
if (brain.update()) {
// Check for good connection and preCalc Data
if(checkTimers(2)){
signalStrength = brain.readSignalQuality();
aGoodSignalStreak = signalStrength == 0 ? true : false;
// Serial.print("good: ");
// Serial.println(aGoodSignalStreak);
}
// brain.printCSV();
attentionLevel = brain.readAttention();
meditationLevel = brain.readMeditation();
delta = brain.eegPower[0]%100; // * (1.8/4096) ) / 2000; //voltage conversion
theta = brain.eegPower[1]%100; // * (1.8/4096) ) / 2000;
if(aGoodSignalStreak && colorReached) {
aGoodSignalStreak = false;
if(attentionLevel != attentionLevelOld || meditationLevel != meditationLevelOld){
// Serial.println("attentionLevel: ");
// Serial.println(attentionLevel);
// Serial.println("meditationLevel: ");
// Serial.println(meditationLevel);
// Serial.println("In eSense before timer");
if(checkTimers(0)){
// Serial.println("In eSense");
checkColorEsense();
attentionLevelOld = attentionLevel;
meditationLevelOld = meditationLevel;
}
}
}else if (brain.readSignalQuality() > 0 && colorReached) {
if (delta != deltaOld && theta != thetaOld){
if(delta > 0 || theta > 0){
// if(checkTimers(0)){
// Serial.print("In raw");
// }
// Serial.print("delta: ");
// Serial.println(delta);
// Serial.print("theta: ");
// Serial.println(theta);
}
if(checkTimers(1)){
checkColorRaw();
}
}
deltaOld = delta;
thetaOld = theta;
}
}
}
if(!colorReached){
if(fadeSpeed > 0){
for (int i = 0; i < NUMSTRIPS; ++i)
{
fadeOut(i);
}
// Serial.println("In fade");
}
}
if(colorReached && !started){
started = true;
}
}
void showStrips(){
for(int i = 0; i < NUMSTRIPS; i++){
strips[i].show();
}
setStrip = true;
}
int setColor(uint8_t r, uint8_t g, uint8_t b){
for(int i = 0; i < NUMSTRIPS; i++){
strips[i].setStripColor(r,g,b);
}
}
int setTargetColor(uint8_t r, uint8_t g, uint8_t b){
for(int i = 0; i < NUMSTRIPS; i++){
strips[i].targetColorR = r;
strips[i].targetColorG = g;
strips[i].targetColorB = b;
}
}
void checkColorEsense(){
if(attentionLevel >= 60 && meditationLevel < 60 && colorReached && !isAttenttion){
setTargetColor(255,0,0);
colorReached = false;
// Serial.println("In attention");
isMeditation = false;
isAttenttion = true;
isNeutral = false;
Serial.println('6');
}
if (meditationLevel >= 60 && attentionLevel < 60 && colorReached && !isMeditation){
setTargetColor(0,255,0);
colorReached = false;
// Serial.println("In meditation");
isMeditation = true;
isAttenttion = false;
isNeutral = false;
Serial.println('5');
}
if (meditationLevel < 60 && attentionLevel < 60 && colorReached && !isNeutral){
setTargetColor(255,160,0);
colorReached = false;
// Serial.println("In neutral");
isMeditation = false;
isAttenttion = false;
isNeutral = true;
Serial.println('4');
}
}
void checkColorRaw(){
if(delta >= 70 && theta < 70 && colorReached && !isDelta){
setTargetColor(255,0,0);
colorReached = false;
// Serial.println("In attention");
isTheta = false;
isDelta = true;
isNeutralDT = false;
Serial.println('3');
}
if (theta >= 70 && delta < 70 && colorReached && !isTheta){
setTargetColor(0,255,0);
colorReached = false;
// Serial.println("In meditation");
isTheta = true;
isDelta = false;
isNeutralDT = false;
Serial.println('2');
}
if (theta < 70 && delta < 70 && colorReached && !isNeutralDT){
setTargetColor(255,160,0);
colorReached = false;
// Serial.println("In neutral");
isTheta = false;
isDelta = false;
isNeutralDT = true;
Serial.println('1');
}
}
//set up to 6 Timers:
void wait(int _waitTime, int _numberOfIndex){
waitTime[_numberOfIndex] = _waitTime;
currentTime[_numberOfIndex] = millis();
}
//check Time:
bool checkTimers(int _index){
if(millis() - currentTime[_index] >= waitTime[_index]){
// Serial.print("TimeStamp: ");
// Serial.println(currentTime[_index]);
currentTime[_index] = millis();
return true;
}else{
return false;
}
}
void fadeOut(int k){
for(int i = 0; i < strips[k].getNumPixels(); i++){
uint32_t color = strips[k].getPixelColor(i);
int
r = (uint8_t)(color >> 16),
g = (uint8_t)(color >> 8),
b = (uint8_t)color;
r = (fadeSpeed >= abs(strips[k].targetColorR - r))?strips[k].targetColorR:r<strips[k].targetColorR?r+fadeSpeed:r-fadeSpeed;
g = (fadeSpeed >= abs(strips[k].targetColorG - g))?strips[k].targetColorG:g<strips[k].targetColorG?g+fadeSpeed:g-fadeSpeed;
b = (fadeSpeed >= abs(strips[k].targetColorB - b))?strips[k].targetColorB:b<strips[k].targetColorB?b+fadeSpeed:b-fadeSpeed;
if(r == strips[k].targetColorR && g == strips[k].targetColorG && b == strips[k].targetColorB && !colorReached){
// Serial.println("Fade done");
colorReached = true;
}
strips[k].setPixelColor(i, r, g, b);
}
// delay(20);
}
| [
"schade.mich@gmail.com"
] | schade.mich@gmail.com |
90d32917da4f10b13ecaf0dfb341efd4c16c84a1 | 8ed304a28d9633488a1d17c0aec81209d736ea55 | /COP 3014 HW/Arrays.cpp | 048e4966d0ea0efa1536d06e578783d138b2116b | [] | no_license | CodyCamp/HomeworkAssignments | dde0522a9be9393580c9c51ea57197f9b0ea4388 | 8f8e5aa457ec462416ca65d9f2e1771871cbd48b | refs/heads/master | 2016-09-05T11:32:38.706370 | 2014-12-22T01:58:54 | 2014-12-22T01:58:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,559 | cpp | /* Starter file for assignment 5
* Two functions are provided. You will write the 5 specified functions,
* as well as a menu program to test the functions.
*
* Name: Cody Campbell
Date: 11/6/14
Section: 2
Assignment: 5
Due Date: 11/6/14
About this project: This project will help develop skills with arrays and functions
Assumptions: correct user input, assumes first thing user does is fill the array arraye
All work done below was performed by Cody Campbell*/
#include <iostream>
using namespace std;
/* Given Function prototypes */
void PrintArray(const int arr[], const int size);
void FillArray(int arr[], const int size);
/* My function prototypes */
void printMenu(); //defining functions
void Insert(int arr[], int size, int newValue, int newIndex);
void Reverse(int arr[], int size);
void Delete(int arr[], int size, int indexNum);
int SumEvens(int arr[], int size, int numAdd);
int HowMany(int arr[], int size, int value);
int main() //main starts here
{
const int SIZE = 15;
/* Declare your array and write the menu loop */
int arraye[SIZE] = {};
char userSelection = 'M';
do
{
switch (userSelection){
case 'I':{ // Insert function
int insertValue = 0;
int insertIndex = 0;
cout << "Enter the value to be inserted: ";
cin >> insertValue;
cout << "Enter the index number: ";
cin >> insertIndex;
Insert(arraye, SIZE, insertValue, insertIndex);
PrintArray(arraye, SIZE);
break;
}
case 'Q':{ //exits program
break;
}
case 'P':{ //prints the array "arraye"
PrintArray(arraye, SIZE);
break;
}
case 'D':{ //deletes number at given index
int deleteIndex = 0;
cout << "Enter the index to be deleted: ";
cin >> deleteIndex;
Delete(arraye, SIZE, deleteIndex);
PrintArray(arraye, SIZE);
break;
}
case 'R':{ //reverses array
Reverse(arraye, SIZE);
PrintArray(arraye, SIZE);
break;
}
case 'S':{ //sum of the number of even numbers in the range the user entered
int numToAdd = 0;
cout << "Enter how many even numbers to add: ";
cin >> numToAdd;
while (numToAdd > SIZE || numToAdd < 0)
{
cout << "Make sure your number is less than the array size and greater than zero!";
cin >> numToAdd;
}
cout << "The sum of the first " << numToAdd << " even numbers is: " << SumEvens(arraye, SIZE, numToAdd);
break;
}
case 'H':{ //tells how many times the value is in the array
int searchFor = 0;
cout << "Enter a value to search for: ";
cin >> searchFor;
cout << "The value " << searchFor << " appears in the list " << HowMany(arraye, SIZE, searchFor) << " times";
break;
}
case 'M':{ //print menu again
printMenu();
break;
}
case 'F':{ //allows user to fill array
FillArray(arraye, SIZE);
break;
}
}
cout << "\nEnter your menu selection: ";
cin >> userSelection;
} while (userSelection != 'Q');
return 0;
} // end main()
/* My functions */
void printMenu() //Prints menu
{
cout << "\t " << "** Given features **" << endl;
cout << "P\t" << "Print the array contents" << endl;
cout << "F\t" << "Fill the array (user entry)" << endl << endl;
cout << "\t " << "** Function Tests **" << endl;
cout << "I\t" << "Insert" << endl;
cout << "D\t" << "Delete" << endl;
cout << "R\t" << "Reverse" << endl;
cout << "H\t" << "HowMany" << endl;
cout << "S\t" << "SumEvents" << endl << endl;
cout << "M\t" << "Print this menu" << endl;
cout << "Q\t" << "Quit this program" << endl;
}
int SumEvens(int arr[], int size, int numAdd) // working
{
int count = 0;
int sum = 0;
for (int i = 0; i < size; i++){
if (count >= numAdd) //ends program when count hits numAdd
break;
else if (arr[i] == 0) //passes zero w/o changing count
sum += 0;
else if (arr[i] % 2 == 0){ //adds if number is even, also adds one to count
sum += arr[i];
count++;
}
}
return sum;
}
int HowMany(int arr[], int size, int value) // working
{
int count = 0;
for (int i = 0; i <= size; i++){ //loops through array and adds to count when value is present at checked index
if (arr[i] == value)
count++;
}
return count;
}
void Reverse(int arr[], int size) // working
{
int placeHolder = 0;
for (int i = 0; i < (size / 2); i++){ //loops through the first half of the array using a temperary variable to store an array index
placeHolder = arr[i]; // changes two array indexes every loop
arr[i] = arr[size - i - 1];
arr[size - i - 1] = placeHolder;
}
}
void Delete(int arr[], int size, int indexNum) // working
{
if (indexNum < size) // makes sure index is in the range
{
for (int i = indexNum; i < size; i++) // loops through changing each array value to the one after it except the last, which is set to zero
{
if (i == size - 1)
arr[i] = 0;
else
arr[i] = arr[i + 1];
}
}
}
void Insert(int arr[], int size, int newValue, int newIndex) // working
{
if (newIndex <= size)
for (int i = size; i >= newIndex; i--) //loops starting from the end of the array, changing the values to the values at the index before them
arr[i] = arr[i - 1]; // stops when i hits new index
arr[newIndex] = newValue;
}
/* DO NOT CHANGE THESE! */
void PrintArray(const int arr[], const int size)
// this function prints the contents of the array
{
cout << "\nThe array:\n { ";
for (int i = 0; i < size - 1; i++) // print all but last item
cout << arr[i] << ", ";
cout << arr[size - 1] << " }\n"; // print last item
}
void FillArray(int arr[], const int size)
// this function loads the contents of the array with user-entered values
{
cout << "Please enter " << size
<< " integers to load into the array\n> ";
for (int i = 0; i < size; i++)
cin >> arr[i]; // enter data into array slot
} | [
"codycampbell6@gmail.com"
] | codycampbell6@gmail.com |
ca0a6202c968e34fa6ac299a517b2eadc8d88c40 | c2a05b0b513dc16e5946e7ad9fc19f33b1124187 | /Lab06/main.cpp | 7029e6680f5cd1e398fd667252f935d85c0b3244 | [] | no_license | asd00012334/OS2017 | 075a73e092dc289b90ad4c6a4d4a2656c4890b11 | b7b91d1a1fbcca8b297b6a4f343a3da33f50b169 | refs/heads/master | 2021-09-04T09:06:20.281155 | 2018-01-17T14:57:16 | 2018-01-17T14:57:16 | 112,812,749 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,460 | cpp | #include<cstdio>
#include<cstdlib>
#include<string>
#include<assert.h>
#include<sys/types.h>
#include<dirent.h>
#include<sys/stat.h>
#include<unistd.h>
#define ull unsigned long long
using namespace std;
bool indValid=false;
ull ind;
bool fnameValid=false;
string fname;
bool szMinValid;
ull szMin;
bool szMaxValid;
ull szMax;
void listAll(string const& path){
DIR* dir = opendir(path.c_str());
if(!dir) return;
for(dirent* ptr=readdir(dir);ptr;ptr=readdir(dir)){
string tmp = path+"/"+ptr->d_name;
if(string(".")==ptr->d_name ||string("..")==ptr->d_name)
continue;
listAll(tmp);
if(indValid && ind!=ptr->d_ino) continue;
if(fnameValid && fname!=ptr->d_name) continue;
struct stat buf;
stat(tmp.c_str(),&buf);
if(szMinValid && buf.st_size<szMin) continue;
if(szMaxValid && buf.st_size>szMax) continue;
printf("%s %lu %lf MB\n",tmp.c_str(),ptr->d_ino,(double)buf.st_size/(1<<20));
}
}
int main(int argc, char* argv[]){
assert(argc>2 && argc%2==0);
string path = argv[1];
for(int i=2;i<argc;i+=2){
string k = argv[i], v = argv[i+1];
if(k=="-inode"){
indValid = true;
ind = atoi(v.c_str());
} else if(k=="-name"){
fnameValid = true;
fname = v;
} else if(k=="-size_min"){
szMinValid = true;
szMin = ((ull)atoi(v.c_str()))<<20;
} else if(k=="-size_max"){
szMaxValid = true;
szMax = ((ull)atoi(v.c_str()))<<20;
} else{
printf("Invalid argument list");
exit(-1);
}
}
listAll(path);
}
| [
"asd00012334@hotmail.com"
] | asd00012334@hotmail.com |
c017ea7daf2ecaa3b9f56d550b3c9a5a5693ff42 | f6c7435c2619bd233a884717e96799bfc28975d0 | /Sunfish/src/Config/configure.cpp | 2e5d6b0832fe09cd1664fcb524e39e3759f007a6 | [] | no_license | sunfish-shogi/sunfish2 | 734c875675480a4510ab23396b146c9bd4dd79d4 | aa62f30be0955dc97899c1267bb85f3e7315f8f4 | refs/heads/master | 2023-01-23T17:30:28.792055 | 2023-01-07T09:17:46 | 2023-01-07T09:17:46 | 15,472,136 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,765 | cpp | /*
* configure.cpp
*
* Created on: 2013/02/03
* Author: ryosuke
*/
#include "configure.h"
#include "../Log/logger.h"
#include "../Util/tableString.h"
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
namespace Configures {
bool Configure::read(const char* filename) {
// open a configure file.
Log::message.fileOpenMessage(filename);
std::ifstream fin(filename);
if (!fin) {
Log::error.fileOpenError(filename);
return false;
}
// set default values
init();
// input
for (int l = 0; ; l++) {
char line[LINE_BUFFER_SIZE];
fin.getline(line, sizeof(line));
if (fin.eof()) { break; }
if (fin.fail()) {
Log::error.fileIoError(filename);
return false;
}
if (!readLine(line)) {
Log::error.fileFormatError(filename, l, line);
}
}
fin.close(); // close a configure file.
return true;
}
void Configure::init() {
// 初期値を代入
ConfigItem* items = itemList();
int size = itemSize();
for (int i = 0; i < size; i++){
// 設定項目のデータ型毎に変換
if (!convert(items[i], items[i].defaultValue)) {
Log::error.unknownError();
}
}
}
bool Configure::readLine(const char* line) {
if (line[0] == '\0' || line[0] == '#') {
return true;
}
// '=' で左辺値と右辺値に分解
std::vector<std::string> tokens;
boost::algorithm::split(tokens, line, boost::is_any_of("="));
if (tokens.size() != 2) {
return false;
}
// 左辺値に一致する項目を探す。
ConfigItem* items = itemList();
int size = itemSize();
for (int i = 0; i < size; i++){
if (tokens[0] == items[i].name) {
// 設定項目のデータ型毎に変換
if (convert(items[i], tokens[1])) {
return true;
} else {
Log::error.unknownError();
return false;
}
}
}
return false;
}
bool Configure::convert(ConfigItem& item, const std::string& str) {
// 設定項目のデータ型毎に変換
if (item.type == STRING) {
*(std::string*)item.data = str;
} else if (item.type == INTEGER) {
*(int*)item.data = boost::lexical_cast<int>(str);
} else if (item.type == BOOL) {
*(bool*)item.data = boost::lexical_cast<bool>(str);
} else {
return false;
}
return true;
}
std::string Configure::toString() {
Util::TableString table(":");
ConfigItem* items = itemList();
int size = itemSize();
for (int i = 0; i < size; i++){
table.row() << items[i].name;
if (items[i].type == STRING) {
table << *(std::string*)items[i].data;
} else if (items[i].type == INTEGER) {
table << *(int*)items[i].data;
} else if (items[i].type == BOOL) {
table << *(bool*)items[i].data;
} else {
table << "error";
}
}
return table.get();
}
}
| [
"sunfish-shogi@users.noreply.github.com"
] | sunfish-shogi@users.noreply.github.com |
2a8d128d5d61a2873ddd47f60a8794924e309ece | c8a4924f8850bbe89a77f686e6ebe19b9f05c63f | /include/dragon/operators/arithmetic/dot_op.h | ce65e071d7e09f1fcd52dfd1896ff68cc88d030f | [] | no_license | afterimagex/REID_SDK | 62c7c9bf725e1305b11125165931b4a6991f1a0d | 6b80d4c360411390f57292ec68fce2f5ac74d4aa | refs/heads/master | 2021-08-30T14:08:25.365802 | 2017-12-18T08:29:28 | 2017-12-18T08:29:28 | 114,615,104 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,645 | h | // --------------------------------------------------------
// Dragon
// Copyright(c) 2017 SeetaTech
// Written by Ting Pan
// --------------------------------------------------------
#ifndef DRAGON_OPERATORS_ARITHMETIC_DOT_OP_H_
#define DRAGON_OPERATORS_ARITHMETIC_DOT_OP_H_
#include "core/operator.h"
namespace dragon {
template <class Context>
class DotOp final : public Operator<Context> {
public:
DotOp(const OperatorDef& op_def, Workspace* ws)
: Operator<Context>(op_def, ws),
transA(OperatorBase::GetSingleArg<bool>("TransA", false)),
transB(OperatorBase::GetSingleArg<bool>("TransB", false)) {}
void RunOnDevice() override;
template <typename T> void DotRunWithType();
template <typename T> void GemmRunWithType();
template <typename T> void GemvRunWithType();
protected:
bool transA, transB;
TIndex M, K1, K2, N1, N2;
};
template <class Context>
class DotGradientOp final : public Operator<Context> {
public:
DotGradientOp(const OperatorDef& op_def, Workspace* ws)
: Operator<Context>(op_def, ws),
transA(OperatorBase::GetSingleArg<bool>("TransA", false)),
transB(OperatorBase::GetSingleArg<bool>("TransB", false)) {}
void ShareGradient() override;
void RunOnDevice() override;
template <typename T> void DotRunWithType();
template <typename T> void GemmRunWithType();
template <typename T> void GemvRunWithType();
protected:
bool transA, transB;
TIndex M, K1, K2, N1, N2;
};
} // namespace dragon
#endif // DRAGON_OPERATORS_ARITHMETIC_DOT_OP_H_ | [
"563853580@qq.com"
] | 563853580@qq.com |
fbae80ab8e367691a0fe1262a5f818ab95f43f15 | b1ffebce4156867356c475d4bc0886d01790ab6e | /Codeforces/Problems/C. Sereja and Prefixes.cpp | 216d058c0f4053b38cc9fb6e9b6b5811580119c6 | [] | no_license | Nezz7/Competitive-programming | 1d6d54b2927ad0e45db852c477df71d63fab9ae5 | 681561a241b60453ef0ef0796d5025c3c0a358e4 | refs/heads/master | 2021-07-10T12:01:05.238837 | 2021-03-18T21:15:39 | 2021-03-18T21:15:39 | 237,987,026 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,187 | cpp | #include <bits/stdc++.h>
#define LL long long int
using namespace std;
LL const MAXN = 1e5+9;
vector<LL> v;
vector<pair<pair<LL,LL>,LL>>inv;
LL sum[MAXN];
LL get(LL x){
LL mx = 1e9;
LL id = (upper_bound(inv.begin(),inv.end(),make_pair(make_pair(x,mx),0LL))) - inv.begin();
id --;
if (id < 0 ) return v[x];
if (inv[id].first.first <= x && x <= inv[id].first.second){
x -= inv[id].first.first;
x %= inv[id].second;
return get(x);
}
x -= sum[id+1];
return v[x];
}
int main (){
ios_base::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
LL n;
cin >> n;
LL r = 0;
while (n--){
LL t;
cin >> t;
if (t == 1){
LL x;
cin >> x;
v.push_back(x);
r++;
}else {
LL l, c;
cin >> l >> c;
inv.push_back({{r,r+l*c -1},l});
r = r+l*c;
}
}
LL i = 1;
for (auto cur : inv){
sum[i] = sum[i-1] + cur.first.second - cur.first.first + 1;
i++;
}
LL q;
cin >> q;
while (q--){
LL x;
cin >> x;
x--;
cout << get(x) << " ";
}
}
| [
"omarkamoun97@gmail.com"
] | omarkamoun97@gmail.com |
aac5f105855e0fd8a6ed777c2298414738cc5caf | 7159f5af85ec5cd720fbbf66ac675cdf42e97d4d | /test/mysSort/22-6-树状数组-poj3067.cpp | 0e2cbf05deb66f9d58a0e81126913f3500c44145 | [] | no_license | YuyangQin/job | a004379555e30cd64fbdae35d586022b43b4479d | ad3fe114fc9b7c1bd058f492f34f2344feccc38a | refs/heads/master | 2023-04-13T23:38:18.100484 | 2021-04-27T08:00:57 | 2021-04-27T08:00:57 | 290,733,042 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,166 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <algorithm>
using namespace std;
//1、由于本题有巨大的输入数据,所以使用scanf而不是cin以避免超时
//2、由于输入的顺序,所以本题可简化为一维的树状数组,仅记录比其横坐标小的数量即可
const int maxn = 1005;
const int maxk = 1000010;
typedef long long LL;
struct Edge
{
int x, y;
}e[maxk];
bool cmp(Edge a, Edge b)
{
return a.x < b.x || (a.x == b.x&&a.y < b.y);
}
int n,m,k,cases;
int a[maxn], c[maxn];
int lowbit(int x)
{
return (-x)&x;
}
void add(int i, int z)//在位置i增加a[i]
{
for (; i <= maxn; i += lowbit(i))
{
c[i] += z;
}
}
//求1~i的和
int sum(int i)
{
int ans = 0;
for (; i > 0; i -= lowbit(i))
{
ans += c[i];
}
return ans;
}
int main()
{
int T;
scanf("%d", &T);
while (T--)
{
memset(c, 0, sizeof(c));
scanf("%d%d%d", &n,&m,&k);
for (size_t i = 0; i < k; i++)
{
scanf("%d %d", &e[i].x, &e[i].y);
}
sort(e, e + k, cmp);
LL ans = 0;
for (size_t i = 0; i < k; i++)
{
ans += i - sum(e[i].y);
add(e[i].y, 1);
}
printf("Test case %d: %lld\n", ++cases, ans);
}
return 0;
}
| [
"1170901345@qq.com"
] | 1170901345@qq.com |
73b866d81f6c5e5d43d79206418c1c87078562aa | bce4a3e1cdadd9c415f3b1c1ba542d884a74bf2b | /June Lunchtime/b2.cpp | 2fdacbd638eb6f5aa58eaa5b8211cde01562fae3 | [] | no_license | nishitanand/codechef | 5143acc6c24c2d88b81d4ed52f9688fd86d6d54c | e5564a211e4251a3f045ed02a5d59dd1c805c163 | refs/heads/master | 2022-12-03T02:08:28.660636 | 2020-08-16T13:02:14 | 2020-08-16T13:02:14 | 287,268,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,220 | cpp | #include<bits/stdc++.h>
using namespace std;
#define lli long long int
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
lli t,n;
cin>>t;
while(t--)
{
lli flag=0;
cin>>n;
lli a;
vector<lli> v;
lli i;
for(i=0;i<n;i++)
{
cin>>a;
v.push_back(a);
}
sort(v.begin(),v.end());
for (i=v.size()-1;i>0;i--)
{
//cout<<"i "<<i<<" v[i] "<<v[i]<<" ";
if (v[i-1]==v[i])
{
if (i==v.size()-1)
{
cout<<"NO\n";
flag=1;
break;
}
if (v[i-2]==v[i])
{
cout<<"NO\n";
flag=1;
break;
}
else
{
v.push_back(v[i-1]);
v.erase(v.begin()+i-1);
}
}
}
if (flag==0)
{
cout<<"YES\n";
for(auto it: v)
cout<<it<<" ";
cout<<"\n";
}
}
return 0;
}
| [
"nishitanand99@hotmail.com"
] | nishitanand99@hotmail.com |
e5aecb56ac357076cca479f5c0a131444a040930 | 8b5db3bc9f2afe52fce03a843e79454319f3c950 | /hardware/intel/common/omx-components/videocodec/OMXVideoEncoderVP8.h | afafb7f7d5cd0b86a54f169a143022737f06d8d1 | [
"Apache-2.0"
] | permissive | 10114395/android-5.0.0_r5 | 619a6ea78ebcbb6d2c44a31ed0c3f9d5b64455b2 | d023f08717af9bb61c2a273a040d3986a87422e1 | refs/heads/master | 2021-01-21T19:57:16.122808 | 2015-04-02T04:39:50 | 2015-04-02T04:39:50 | 33,306,407 | 2 | 2 | null | 2020-03-09T00:07:10 | 2015-04-02T11:58:28 | C | UTF-8 | C++ | false | false | 1,269 | h |
#ifndef OMX_VIDEO_ENCODER_VP8_H
#define OMX_VIDEO_ENCODER_VP8_H
#include <OMX_VideoExt.h>
#include "OMXVideoEncoderBase.h"
class OMXVideoEncoderVP8 : public OMXVideoEncoderBase {
public:
OMXVideoEncoderVP8();
virtual ~OMXVideoEncoderVP8();
protected:
virtual OMX_ERRORTYPE InitOutputPortFormatSpecific(OMX_PARAM_PORTDEFINITIONTYPE *paramPortDeninitionOutput);
virtual OMX_ERRORTYPE ProcessorInit(void);
virtual OMX_ERRORTYPE ProcessorDeinit(void);
virtual OMX_ERRORTYPE ProcessorProcess(OMX_BUFFERHEADERTYPE **buffers, buffer_retain_t *retains, OMX_U32 numberBuffers);
virtual OMX_ERRORTYPE BuildHandlerList(void);
virtual OMX_ERRORTYPE SetVideoEncoderParam();
DECLARE_HANDLER(OMXVideoEncoderVP8, ParamVideoVp8);
DECLARE_HANDLER(OMXVideoEncoderVP8, ConfigVideoVp8ReferenceFrame);
DECLARE_HANDLER(OMXVideoEncoderVP8, ConfigVp8MaxFrameSizeRatio);
private:
enum {
OUTPORT_MIN_BUFFER_COUNT = 1,
OUTPORT_ACTUAL_BUFFER_COUNT = 2,
OUTPORT_BUFFER_SIZE = 1382400,
};
OMX_VIDEO_PARAM_VP8TYPE mParamVp8;
OMX_VIDEO_VP8REFERENCEFRAMETYPE mConfigVideoVp8ReferenceFrame;
};
#endif /* OMX_VIDEO_ENCODER_VP8_H */
| [
"xdtianyu@gmail.com"
] | xdtianyu@gmail.com |
6c6e7332517673fcc7c6b27443c4900cab143d59 | d0b2e7e7bb3c7141be2e4d0d758a0795b824d43f | /Source/Editor/Private/Nodes/K2Node_Action.cpp | b4ad4b6049ce4da03b4b3084252c88b7b4d53d2c | [
"Apache-2.0"
] | permissive | b2220333/ActionsExtension | 682a808de6a3dfbc862bfeee5e67d809276a026f | 5923dd6b8fbd202309ef72b41e936d00d32aa03f | refs/heads/master | 2020-06-19T15:57:18.512326 | 2019-06-14T07:49:04 | 2019-06-14T07:49:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,597 | cpp | // Copyright 2015-2019 Piperift. All Rights Reserved.
#include "K2Node_Action.h"
#include "Kismet2/BlueprintEditorUtils.h"
#include "KismetCompiler.h"
#include "BlueprintNodeSpawner.h"
#include "EditorCategoryUtils.h"
#include "BlueprintNodeSpawner.h"
#include "BlueprintFunctionNodeSpawner.h"
#include "BlueprintActionDatabaseRegistrar.h"
#include "K2Node_CallFunction.h"
#include "K2Node_AssignmentStatement.h"
#include "ActionsEditor.h"
#include "ActionNodeHelpers.h"
#include "ActionLibrary.h"
#include "Action.h"
#define LOCTEXT_NAMESPACE "ActionEditor"
FName UK2Node_Action::ClassPinName(TEXT("Class"));
FName UK2Node_Action::OwnerPinName(UEdGraphSchema_K2::PN_Self);
UK2Node_Action::UK2Node_Action(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
NodeTooltip = LOCTEXT("NodeTooltip", "Creates a new action");
}
void UK2Node_Action::PostLoad()
{
Super::PostLoad();
BindBlueprintCompile();
}
///////////////////////////////////////////////////////////////////////////////
// UEdGraphNode Interface
void UK2Node_Action::AllocateDefaultPins()
{
const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>();
// Add execution pins
CreatePin(EGPD_Input, K2Schema->PC_Exec, K2Schema->PN_Execute);
CreatePin(EGPD_Output, K2Schema->PC_Exec, K2Schema->PN_Then);
// Action Owner
UEdGraphPin* SelfPin = CreatePin(EGPD_Input, K2Schema->PC_Object, UObject::StaticClass(), OwnerPinName);
SelfPin->PinFriendlyName = LOCTEXT("Owner", "Owner");
//If we are not using a predefined class
if (!UsePrestatedClass()) {
// Add blueprint pin
UEdGraphPin* ClassPin = CreatePin(EGPD_Input, K2Schema->PC_Class, GetClassPinBaseClass(), ClassPinName);
}
// Result pin
UEdGraphPin* ResultPin = CreatePin(EGPD_Output, K2Schema->PC_Object, GetClassPinBaseClass(), K2Schema->PN_ReturnValue);
//Update class pins if we are using a prestated node
if (UsePrestatedClass())
{
OnClassPinChanged();
BindBlueprintCompile();
}
Super::AllocateDefaultPins();
}
FLinearColor UK2Node_Action::GetNodeTitleColor() const
{
return FColor{ 27, 240, 247 };
}
FText UK2Node_Action::GetNodeTitle(ENodeTitleType::Type TitleType) const
{
if (!UsePrestatedClass() && (TitleType == ENodeTitleType::ListView || TitleType == ENodeTitleType::MenuTitle))
{
return GetBaseNodeTitle();
}
else if (auto ClassToSpawn = GetActionClass())
{
if (CachedNodeTitle.IsOutOfDate(this))
{
FFormatNamedArguments Args;
Args.Add(TEXT("ClassName"), ClassToSpawn->GetDisplayNameText());
// FText::Format() is slow, so we cache this to save on performance
CachedNodeTitle.SetCachedText(FText::Format(GetNodeTitleFormat(), Args), this);
}
return CachedNodeTitle;
}
return NSLOCTEXT("K2Node", "Action_Title_None", "No Action");
}
void UK2Node_Action::PinDefaultValueChanged(UEdGraphPin* ChangedPin)
{
// Class changed
if (ChangedPin && (ChangedPin->PinName == ClassPinName))
{
OnClassPinChanged();
BindBlueprintCompile();
}
}
FText UK2Node_Action::GetTooltipText() const
{
return NodeTooltip;
}
bool UK2Node_Action::HasExternalDependencies(TArray<class UStruct*>* OptionalOutput) const
{
UClass* SourceClass = GetActionClass();
const UBlueprint* SourceBlueprint = GetBlueprint();
const bool bResult = (SourceClass != nullptr) && (SourceClass->ClassGeneratedBy != SourceBlueprint);
if (bResult && OptionalOutput)
{
OptionalOutput->AddUnique(SourceClass);
}
const bool bSuperResult = Super::HasExternalDependencies(OptionalOutput);
return bSuperResult || bResult;
}
bool UK2Node_Action::IsCompatibleWithGraph(const UEdGraph* TargetGraph) const
{
UBlueprint* Blueprint = FBlueprintEditorUtils::FindBlueprintForGraph(TargetGraph);
return Super::IsCompatibleWithGraph(TargetGraph) && (!Blueprint || FBlueprintEditorUtils::FindUserConstructionScript(Blueprint) != TargetGraph);
}
void UK2Node_Action::PinConnectionListChanged(UEdGraphPin* Pin)
{
if (Pin && (Pin->PinName == ClassPinName))
{
OnClassPinChanged();
}
}
void UK2Node_Action::GetPinHoverText(const UEdGraphPin& Pin, FString& HoverTextOut) const
{
UEdGraphPin* ClassPin = GetClassPin();
if (ClassPin)
{
SetPinToolTip(*ClassPin, LOCTEXT("ClassPinDescription", "The object class you want to construct"));
}
UEdGraphPin* ResultPin = GetResultPin();
if (ResultPin)
{
SetPinToolTip(*ResultPin, LOCTEXT("ResultPinDescription", "The constructed action"));
}
if (UEdGraphPin* OwnerPin = GetOwnerPin())
{
SetPinToolTip(*OwnerPin, LOCTEXT("OwnerPinDescription", "Parent of the action"));
}
return Super::GetPinHoverText(Pin, HoverTextOut);
}
//This will expand node for our custom object, with properties
//which are set as EditAnywhere and meta=(ExposeOnSpawn), or equivalent in blueprint.
void UK2Node_Action::ExpandNode(class FKismetCompilerContext& CompilerContext, UEdGraph* SourceGraph)
{
Super::ExpandNode(CompilerContext, SourceGraph);
const UEdGraphSchema_K2* Schema = CompilerContext.GetSchema();
check(SourceGraph && Schema);
//Get static function
static FName Create_FunctionName = GET_FUNCTION_NAME_CHECKED(UActionLibrary, CreateAction);
static FName Activate_FunctionName = GET_FUNCTION_NAME_CHECKED(UAction, Activate);
//Set function parameter names
static FString ParamName_Type = FString(TEXT("Type"));
/* Retrieve Pins */
//Exec
UEdGraphPin* ExecPin = GetExecPin(); // Exec pins are those big arrows, connected with thick white lines.
UEdGraphPin* ThenPin = GetThenPin(); // Then pin is the same as exec pin, just on the other side (the out arrow).
//Inputs
UEdGraphPin* OwnerPin = GetOwnerPin();
UEdGraphPin* ClassPin = GetClassPin(); // Get class pin which is used to determine which class to spawn.
//Outputs
UEdGraphPin* ResultPin = GetResultPin(); // Result pin, which will output our spawned object.
if(!HasWorldContext())
{
CompilerContext.MessageLog.Error(*LOCTEXT("CreateActionNodeMissingClass_Error", "@@ node requires world context.").ToString(), this);
// we break exec links so this is the only error we get, don't want the CreateItemData node being considered and giving 'unexpected node' type warnings
BreakAllNodeLinks();
return;
}
UClass* SpawnClass;
if(UsePrestatedClass())
{
SpawnClass = PrestatedClass;
}
else
{
SpawnClass = ClassPin ? Cast<UClass>(ClassPin->DefaultObject) : nullptr;
//Don't proceed if ClassPin is not defined or valid
if (!ClassPin || (ClassPin->LinkedTo.Num() == 0 && nullptr == SpawnClass))
{
CompilerContext.MessageLog.Error(*LOCTEXT("CreateActionNodeMissingClass_Error", "Create Action node @@ must have a class specified.").ToString(), this);
// we break exec links so this is the only error we get, don't want the CreateItemData node being considered and giving 'unexpected node' type warnings
BreakAllNodeLinks();
return;
}
}
bool bIsErrorFree = true;
//////////////////////////////////////////////////////////////////////////
// create 'UActionFunctionLibrary::CreateAction' call node
UK2Node_CallFunction* CreateActionNode = CompilerContext.SpawnIntermediateNode<UK2Node_CallFunction>(this, SourceGraph);
//Attach function
CreateActionNode->FunctionReference.SetExternalMember(Create_FunctionName, UActionLibrary::StaticClass());
CreateActionNode->AllocateDefaultPins();
//allocate nodes for created widget.
UEdGraphPin* CreateAction_Exec = CreateActionNode->GetExecPin();
UEdGraphPin* CreateAction_Owner = CreateActionNode->FindPinChecked(TEXT("Owner"));
UEdGraphPin* CreateAction_Type = CreateActionNode->FindPinChecked(ParamName_Type);
UEdGraphPin* CreateAction_Result = CreateActionNode->GetReturnValuePin();
// Move 'exec' pin to 'UActionFunctionLibrary::CreateAction'
CompilerContext.MovePinLinksToIntermediate(*ExecPin, *CreateAction_Exec);
//TODO: Create local variable for PrestatedClass
//Move pin if connected else, copy the value
if (!UsePrestatedClass() && ClassPin->LinkedTo.Num() > 0)
{
// Copy the 'blueprint' connection from the spawn node to 'UActionLibrary::CreateAction'
CompilerContext.MovePinLinksToIntermediate(*ClassPin, *CreateAction_Type);
}
else
{
// Copy blueprint literal onto 'UActionLibrary::CreateAction' call
CreateAction_Type->DefaultObject = SpawnClass;
}
// Copy Owner pin to 'UActionFunctionLibrary::CreateAction' if necessary
if (OwnerPin)
{
CompilerContext.MovePinLinksToIntermediate(*OwnerPin, *CreateAction_Owner);
}
// Move Result pin to 'UActionFunctionLibrary::CreateAction'
CreateAction_Result->PinType = ResultPin->PinType; // Copy type so it uses the right actor subclass
CompilerContext.MovePinLinksToIntermediate(*ResultPin, *CreateAction_Result);
//////////////////////////////////////////////////////////////////////////
// create 'set var' nodes
// Set all properties of the object
UEdGraphPin* LastThenPin = FKismetCompilerUtilities::GenerateAssignmentNodes(CompilerContext, SourceGraph, CreateActionNode, this, CreateAction_Result, GetActionClass());
// For each delegate, define an event, bind it to delegate and implement a chain of assignments
for (TFieldIterator<UMulticastDelegateProperty> PropertyIt(GetActionClass(), EFieldIteratorFlags::IncludeSuper); PropertyIt && bIsErrorFree; ++PropertyIt)
{
UMulticastDelegateProperty* Property = *PropertyIt;
if (Property && Property->HasAllPropertyFlags(CPF_BlueprintAssignable))
{
const UFunction* DelegateSignatureFunction = Property->SignatureFunction;
if (DelegateSignatureFunction->NumParms < 1)
{
bIsErrorFree &= FHelper::HandleDelegateImplementation(Property, CreateAction_Result, LastThenPin, this, SourceGraph, CompilerContext);
}
else
{
bIsErrorFree &= FHelper::HandleDelegateBindImplementation(Property, CreateAction_Result, LastThenPin, this, SourceGraph, CompilerContext);
}
}
}
if (!bIsErrorFree)
{
CompilerContext.MessageLog.Error(*LOCTEXT("CreateActionNodeMissingClass_Error", "There was a compile error while binding delegates.").ToString(), this);
// we break exec links so this is the only error we get, don't want the CreateAction node being considered and giving 'unexpected node' type warnings
BreakAllNodeLinks();
return;
}
//////////////////////////////////////////////////////////////////////////
// create 'UAction::Activate' call node
UK2Node_CallFunction* ActivateActionNode = CompilerContext.SpawnIntermediateNode<UK2Node_CallFunction>(this, SourceGraph);
//Attach function
ActivateActionNode->FunctionReference.SetExternalMember(Activate_FunctionName, UAction::StaticClass());
ActivateActionNode->AllocateDefaultPins();
//allocate nodes for created widget.
UEdGraphPin* ActivateAction_Exec = ActivateActionNode->GetExecPin();
UEdGraphPin* ActivateAction_Self = ActivateActionNode->FindPinChecked(Schema->PN_Self);
UEdGraphPin* ActivateAction_Then = ActivateActionNode->GetThenPin();
bIsErrorFree &= Schema->TryCreateConnection(LastThenPin, ActivateAction_Exec);
bIsErrorFree &= Schema->TryCreateConnection(CreateAction_Result, ActivateAction_Self);
CompilerContext.MovePinLinksToIntermediate(*ThenPin, *ActivateAction_Then);
if (!bIsErrorFree)
{
CompilerContext.MessageLog.Error(*LOCTEXT("CreateActionNodeMissingClass_Error", "There was a compile error while activating the action.").ToString(), this);
// we break exec links so this is the only error we get, don't want the CreateAction node being considered and giving 'unexpected node' type warnings
BreakAllNodeLinks();
return;
}
// Break any links to the expanded node
BreakAllNodeLinks();
}
///////////////////////////////////////////////////////////////////////////////
// UK2Node Interface
void UK2Node_Action::ReallocatePinsDuringReconstruction(TArray<UEdGraphPin*>& OldPins)
{
AllocateDefaultPins();
if (UClass* UseSpawnClass = GetActionClass(&OldPins))
{
CreatePinsForClass(UseSpawnClass);
}
RestoreSplitPins(OldPins);
}
void UK2Node_Action::GetNodeAttributes(TArray<TKeyValuePair<FString, FString>>& OutNodeAttributes) const
{
UClass* ClassToSpawn = GetActionClass();
const FString ClassToSpawnStr = ClassToSpawn ? ClassToSpawn->GetName() : TEXT("InvalidClass");
OutNodeAttributes.Add(TKeyValuePair<FString, FString>(TEXT("Type"), TEXT("CreateAction")));
OutNodeAttributes.Add(TKeyValuePair<FString, FString>(TEXT("Class"), GetClass()->GetName()));
OutNodeAttributes.Add(TKeyValuePair<FString, FString>(TEXT("Name"), GetName()));
OutNodeAttributes.Add(TKeyValuePair<FString, FString>(TEXT("ObjectClass"), ClassToSpawnStr));
}
void UK2Node_Action::GetMenuActions(FBlueprintActionDatabaseRegistrar& ActionRegistrar) const
{
UClass* ActionKey = GetClass();
FActionNodeHelpers::RegisterActionClassActions(ActionRegistrar, ActionKey);
if (ActionRegistrar.IsOpenForRegistration(ActionKey))
{
UBlueprintNodeSpawner* NodeSpawner = UBlueprintNodeSpawner::Create(GetClass());
check(NodeSpawner != nullptr);
NodeSpawner->DefaultMenuSignature.Keywords = LOCTEXT("MenuKeywords", "Create Action");
ActionRegistrar.AddBlueprintAction(ActionKey, NodeSpawner);
}
}
//Set context menu category in which our node will be present.
FText UK2Node_Action::GetMenuCategory() const
{
return FText::FromString("Actions");
}
///////////////////////////////////////////////////////////////////////////////
// UK2Node_Action
void UK2Node_Action::CreatePinsForClass(UClass* InClass, TArray<UEdGraphPin*>* OutClassPins)
{
check(InClass != nullptr);
const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>();
const UObject* const ClassDefaultObject = InClass->GetDefaultObject(false);
for (TFieldIterator<UProperty> PropertyIt(InClass, EFieldIteratorFlags::IncludeSuper); PropertyIt; ++PropertyIt)
{
UProperty* Property = *PropertyIt;
const bool bIsDelegate = Property->IsA(UMulticastDelegateProperty::StaticClass());
const bool bIsExposedToSpawn = UEdGraphSchema_K2::IsPropertyExposedOnSpawn(Property);
const bool bIsSettableExternally = !Property->HasAnyPropertyFlags(CPF_DisableEditOnInstance);
if (nullptr == FindPin(Property->GetName())) {
if (bIsExposedToSpawn &&
!Property->HasAnyPropertyFlags(CPF_Parm) &&
bIsSettableExternally &&
Property->HasAllPropertyFlags(CPF_BlueprintVisible) &&
!bIsDelegate)
{
UEdGraphPin* Pin = CreatePin(EGPD_Input, FName(), Property->GetFName());
const bool bPinGood = (Pin != nullptr) && K2Schema->ConvertPropertyToPinType(Property, Pin->PinType);
if (OutClassPins && Pin)
{
OutClassPins->Add(Pin);
}
if (ClassDefaultObject && Pin != nullptr && K2Schema->PinDefaultValueIsEditable(*Pin))
{
FString DefaultValueAsString;
const bool bDefaultValueSet = FBlueprintEditorUtils::PropertyValueToString(Property, reinterpret_cast<const uint8*>(ClassDefaultObject), DefaultValueAsString);
check(bDefaultValueSet);
K2Schema->TrySetDefaultValue(*Pin, DefaultValueAsString);
}
// Copy tooltip from the property.
if (Pin != nullptr)
{
K2Schema->ConstructBasicPinTooltip(*Pin, Property->GetToolTipText(), Pin->PinToolTip);
}
}
else if (bIsDelegate && Property->HasAllPropertyFlags(CPF_BlueprintAssignable)) {
UMulticastDelegateProperty* const Delegate = Cast<UMulticastDelegateProperty>(*PropertyIt);
if (Delegate)
{
UFunction* DelegateSignatureFunction = Delegate->SignatureFunction;
if (DelegateSignatureFunction)
{
UEdGraphPin* Pin;
if (DelegateSignatureFunction->NumParms < 1)
{
Pin = CreatePin(EGPD_Output, K2Schema->PC_Exec, Delegate->GetFName());
}
else
{
UEdGraphNode::FCreatePinParams Params{};
Params.bIsConst = true;
Params.bIsReference = true;
Pin = CreatePin(EGPD_Input, K2Schema->PC_Delegate, Delegate->GetFName(), Params);
Pin->PinFriendlyName = FText::Format(NSLOCTEXT("K2Node", "PinFriendlyDelegatetName", "{0} Event"), FText::FromName(Delegate->GetFName()));
//Update PinType with the delegate's signature
FMemberReference::FillSimpleMemberReference<UFunction>(DelegateSignatureFunction, Pin->PinType.PinSubCategoryMemberReference);
}
if (OutClassPins && Pin)
{
OutClassPins->Add(Pin);
}
}
else
{
UE_LOG(LogActionsEd, Error, TEXT("Delegate '%s' may be corrumped"), *Delegate->GetName());
}
}
}
}
}
// Change class of output pin
UEdGraphPin* ResultPin = GetResultPin();
ResultPin->PinType.PinSubCategoryObject = InClass;
}
bool UK2Node_Action::IsActionVarPin(UEdGraphPin* Pin)
{
const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>();
return(Pin->PinName != K2Schema->PN_Execute &&
Pin->PinName != K2Schema->PN_Then &&
Pin->PinName != K2Schema->PN_ReturnValue &&
Pin->PinName != ClassPinName &&
Pin->PinName != OwnerPinName);
}
UEdGraphPin* UK2Node_Action::GetThenPin()const
{
const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>();
UEdGraphPin* Pin = FindPinChecked(K2Schema->PN_Then);
check(Pin->Direction == EGPD_Output);
return Pin;
}
UEdGraphPin* UK2Node_Action::GetClassPin(const TArray<UEdGraphPin*>* InPinsToSearch /*= nullptr*/) const
{
if (UsePrestatedClass())
return nullptr;
const TArray<UEdGraphPin*>* PinsToSearch = InPinsToSearch ? InPinsToSearch : &Pins;
UEdGraphPin* Pin = nullptr;
for (auto PinIt = PinsToSearch->CreateConstIterator(); PinIt; ++PinIt)
{
UEdGraphPin* TestPin = *PinIt;
if (TestPin && TestPin->PinName == ClassPinName)
{
Pin = TestPin;
break;
}
}
check(Pin == nullptr || Pin->Direction == EGPD_Input);
return Pin;
}
UEdGraphPin* UK2Node_Action::GetResultPin() const
{
const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>();
UEdGraphPin* Pin = FindPinChecked(K2Schema->PN_ReturnValue);
check(Pin->Direction == EGPD_Output);
return Pin;
}
UEdGraphPin* UK2Node_Action::GetOwnerPin() const
{
UEdGraphPin* Pin = FindPin(OwnerPinName);
ensure(nullptr == Pin || Pin->Direction == EGPD_Input);
return Pin;
}
UClass* UK2Node_Action::GetActionClass(const TArray<UEdGraphPin*>* InPinsToSearch /*=nullptr*/) const
{
UClass* UseSpawnClass = nullptr;
if (UsePrestatedClass())
{
UseSpawnClass = PrestatedClass;
}
else
{
const TArray<UEdGraphPin*>* PinsToSearch = InPinsToSearch ? InPinsToSearch : &Pins;
UEdGraphPin* ClassPin = GetClassPin(PinsToSearch);
if (ClassPin && ClassPin->DefaultObject != nullptr && ClassPin->LinkedTo.Num() == 0)
{
UseSpawnClass = CastChecked<UClass>(ClassPin->DefaultObject);
}
else if (ClassPin && ClassPin->LinkedTo.Num())
{
auto ClassSource = ClassPin->LinkedTo[0];
UseSpawnClass = ClassSource ? Cast<UClass>(ClassSource->PinType.PinSubCategoryObject.Get()) : nullptr;
}
}
return UseSpawnClass;
}
UBlueprint* UK2Node_Action::GetActionBlueprint() const
{
UClass* ClassToSpawn = GetActionClass();
if (!ClassToSpawn)
return nullptr;
FString ClassPath = ClassToSpawn->GetPathName();
ClassPath.RemoveFromEnd(TEXT("_C"), ESearchCase::CaseSensitive);
const FString BPPath = FString::Printf(TEXT("Blueprint'%s'"), *ClassPath);
return Cast<UBlueprint>(
StaticFindObject(UBlueprint::StaticClass(), nullptr, *BPPath)
);
}
bool UK2Node_Action::UseWorldContext() const
{
auto BP = GetBlueprint();
const UClass* ParentClass = BP ? BP->ParentClass : nullptr;
return ParentClass ? ParentClass->HasMetaDataHierarchical(FBlueprintMetadata::MD_ShowWorldContextPin) != nullptr : false;
}
bool UK2Node_Action::HasWorldContext() const
{
return FBlueprintEditorUtils::ImplementsGetWorld(GetBlueprint());
}
FText UK2Node_Action::GetBaseNodeTitle() const
{
return LOCTEXT("Action_BaseTitle", "Action");
}
FText UK2Node_Action::GetNodeTitleFormat() const
{
return LOCTEXT("Action_ClassTitle", "{ClassName}");
}
//which class can be used with this node to create objects. All childs of class can be used.
UClass* UK2Node_Action::GetClassPinBaseClass() const
{
return UsePrestatedClass() ? PrestatedClass : UAction::StaticClass();
}
void UK2Node_Action::SetPinToolTip(UEdGraphPin& MutatablePin, const FText& PinDescription) const
{
MutatablePin.PinToolTip = UEdGraphSchema_K2::TypeToText(MutatablePin.PinType).ToString();
UEdGraphSchema_K2 const* const K2Schema = Cast<const UEdGraphSchema_K2>(GetSchema());
if (K2Schema != nullptr)
{
MutatablePin.PinToolTip += TEXT(" ");
MutatablePin.PinToolTip += K2Schema->GetPinDisplayName(&MutatablePin).ToString();
}
MutatablePin.PinToolTip += FString(TEXT("\n")) + PinDescription.ToString();
}
void UK2Node_Action::OnClassPinChanged()
{
const UEdGraphSchema_K2* K2Schema = GetDefault<UEdGraphSchema_K2>();
// Remove all pins related to archetype variables
TArray<UEdGraphPin*> OldPins = Pins;
TArray<UEdGraphPin*> OldClassPins;
for (UEdGraphPin* OldPin : OldPins)
{
if (IsActionVarPin(OldPin))
{
Pins.Remove(OldPin);
OldClassPins.Add(OldPin);
}
}
CachedNodeTitle.MarkDirty();
TArray<UEdGraphPin*> NewClassPins;
if (UClass* UseSpawnClass = GetActionClass())
{
CreatePinsForClass(UseSpawnClass, &NewClassPins);
}
RestoreSplitPins(OldPins);
UEdGraphPin* ResultPin = GetResultPin();
// Cache all the pin connections to the ResultPin, we will attempt to recreate them
TArray<UEdGraphPin*> ResultPinConnectionList = ResultPin->LinkedTo;
// Because the archetype has changed, we break the output link as the output pin type will change
ResultPin->BreakAllPinLinks(true);
// Recreate any pin links to the Result pin that are still valid
for (UEdGraphPin* Connections : ResultPinConnectionList)
{
K2Schema->TryCreateConnection(ResultPin, Connections);
}
// Rewire the old pins to the new pins so connections are maintained if possible
RewireOldPinsToNewPins(OldClassPins, Pins, nullptr);
// Refresh the UI for the graph so the pin changes show up
GetGraph()->NotifyGraphChanged();
// Mark dirty
FBlueprintEditorUtils::MarkBlueprintAsModified(GetBlueprint());
}
void UK2Node_Action::OnBlueprintCompiled(UBlueprint* CompiledBP)
{
if (BindedActionBlueprint == CompiledBP)
{
OnClassPinChanged();
}
}
void UK2Node_Action::BindBlueprintCompile()
{
if (BindedActionBlueprint)
{
BindedActionBlueprint->OnCompiled().RemoveAll(this);
BindedActionBlueprint = nullptr;
}
if (UBlueprint* BPToSpawn = GetActionBlueprint())
{
BPToSpawn->OnCompiled().AddUObject(this, &UK2Node_Action::OnBlueprintCompiled);
BindedActionBlueprint = BPToSpawn;
}
}
bool UK2Node_Action::FHelper::ValidDataPin(const UEdGraphPin* Pin, EEdGraphPinDirection Direction, const UEdGraphSchema_K2* Schema)
{
check(Schema);
const bool bValidDataPin = Pin
&& (Pin->PinName != Schema->PN_Execute)
&& (Pin->PinName != Schema->PN_Then)
&& (Pin->PinType.PinCategory != Schema->PC_Exec);
const bool bProperDirection = Pin && (Pin->Direction == Direction);
return bValidDataPin && bProperDirection;
}
bool UK2Node_Action::FHelper::CreateDelegateForNewFunction(UEdGraphPin* DelegateInputPin, FName FunctionName, UK2Node* CurrentNode, UEdGraph* SourceGraph, FKismetCompilerContext& CompilerContext)
{
const UEdGraphSchema_K2* Schema = CompilerContext.GetSchema();
check(DelegateInputPin && Schema && CurrentNode && SourceGraph && (FunctionName != NAME_None));
bool bResult = true;
// WORKAROUND, so we can create delegate from nonexistent function by avoiding check at expanding step
// instead simply: Schema->TryCreateConnection(AddDelegateNode->GetDelegatePin(), CurrentCENode->FindPinChecked(UK2Node_CustomEvent::DelegateOutputName));
UK2Node_Self* SelfNode = CompilerContext.SpawnIntermediateNode<UK2Node_Self>(CurrentNode, SourceGraph);
SelfNode->AllocateDefaultPins();
UK2Node_CreateDelegate* CreateDelegateNode = CompilerContext.SpawnIntermediateNode<UK2Node_CreateDelegate>(CurrentNode, SourceGraph);
CreateDelegateNode->AllocateDefaultPins();
bResult &= Schema->TryCreateConnection(DelegateInputPin, CreateDelegateNode->GetDelegateOutPin());
bResult &= Schema->TryCreateConnection(SelfNode->FindPinChecked(Schema->PN_Self), CreateDelegateNode->GetObjectInPin());
CreateDelegateNode->SetFunction(FunctionName);
return bResult;
}
bool UK2Node_Action::FHelper::CopyEventSignature(UK2Node_CustomEvent* CENode, UFunction* Function, const UEdGraphSchema_K2* Schema)
{
check(CENode && Function && Schema);
bool bResult = true;
for (TFieldIterator<UProperty> PropIt(Function); PropIt && (PropIt->PropertyFlags & CPF_Parm); ++PropIt)
{
const UProperty* Param = *PropIt;
if (!Param->HasAnyPropertyFlags(CPF_OutParm) || Param->HasAnyPropertyFlags(CPF_ReferenceParm))
{
FEdGraphPinType PinType;
bResult &= Schema->ConvertPropertyToPinType(Param, /*out*/ PinType);
bResult &= (nullptr != CENode->CreateUserDefinedPin(Param->GetFName(), PinType, EGPD_Output));
}
}
return bResult;
}
bool UK2Node_Action::FHelper::HandleDelegateImplementation(
UMulticastDelegateProperty* CurrentProperty,
UEdGraphPin* ProxyObjectPin, UEdGraphPin*& InOutLastThenPin,
UK2Node* CurrentNode, UEdGraph* SourceGraph, FKismetCompilerContext& CompilerContext)
{
bool bIsErrorFree = true;
const UEdGraphSchema_K2* Schema = CompilerContext.GetSchema();
check(CurrentProperty && ProxyObjectPin && InOutLastThenPin && CurrentNode && SourceGraph && Schema);
UEdGraphPin* PinForCurrentDelegateProperty = CurrentNode->FindPin(CurrentProperty->GetName());
if (!PinForCurrentDelegateProperty || (Schema->PC_Exec != PinForCurrentDelegateProperty->PinType.PinCategory))
{
FText ErrorMessage = FText::Format(LOCTEXT("WrongDelegateProperty", "BaseAsyncConstructObject: Cannot find execution pin for delegate "), FText::FromString(CurrentProperty->GetName()));
CompilerContext.MessageLog.Error(*ErrorMessage.ToString(), CurrentNode);
return false;
}
UK2Node_CustomEvent* CurrentCENode = CompilerContext.SpawnIntermediateEventNode<UK2Node_CustomEvent>(CurrentNode, PinForCurrentDelegateProperty, SourceGraph);
{
UK2Node_AddDelegate* AddDelegateNode = CompilerContext.SpawnIntermediateNode<UK2Node_AddDelegate>(CurrentNode, SourceGraph);
UBlueprint* Blueprint = FBlueprintEditorUtils::FindBlueprintForNodeChecked(CurrentNode);
bool const bIsSelfContext = Blueprint->SkeletonGeneratedClass->IsChildOf(CurrentProperty->GetOwnerClass());
AddDelegateNode->SetFromProperty(CurrentProperty, bIsSelfContext);
AddDelegateNode->AllocateDefaultPins();
bIsErrorFree &= Schema->TryCreateConnection(AddDelegateNode->FindPinChecked(Schema->PN_Self), ProxyObjectPin);
bIsErrorFree &= Schema->TryCreateConnection(InOutLastThenPin, AddDelegateNode->FindPinChecked(Schema->PN_Execute));
InOutLastThenPin = AddDelegateNode->FindPinChecked(Schema->PN_Then);
CurrentCENode->CustomFunctionName = *FString::Printf(TEXT("%s_%s"), *CurrentProperty->GetName(), *CompilerContext.GetGuid(CurrentNode));
CurrentCENode->AllocateDefaultPins();
bIsErrorFree &= FHelper::CreateDelegateForNewFunction(AddDelegateNode->GetDelegatePin(), CurrentCENode->GetFunctionName(), CurrentNode, SourceGraph, CompilerContext);
bIsErrorFree &= FHelper::CopyEventSignature(CurrentCENode, AddDelegateNode->GetDelegateSignature(), Schema);
}
UEdGraphPin* LastActivatedNodeThen = CurrentCENode->FindPinChecked(Schema->PN_Then);
bIsErrorFree &= CompilerContext.MovePinLinksToIntermediate(*PinForCurrentDelegateProperty, *LastActivatedNodeThen).CanSafeConnect();
return bIsErrorFree;
}
bool UK2Node_Action::FHelper::HandleDelegateBindImplementation(
UMulticastDelegateProperty* CurrentProperty,
UEdGraphPin* ObjectPin, UEdGraphPin*& InOutLastThenPin,
UK2Node* CurrentNode, UEdGraph* SourceGraph, FKismetCompilerContext& CompilerContext)
{
bool bIsErrorFree = true;
const UEdGraphSchema_K2* Schema = CompilerContext.GetSchema();
check(CurrentProperty && Schema);
UEdGraphPin* DelegateRefPin = CurrentNode->FindPinChecked(CurrentProperty->GetName());
check(DelegateRefPin);
UK2Node_AddDelegate* AddDelegateNode = CompilerContext.SpawnIntermediateNode<UK2Node_AddDelegate>(CurrentNode, SourceGraph);
check(AddDelegateNode);
AddDelegateNode->SetFromProperty(CurrentProperty, false);
AddDelegateNode->AllocateDefaultPins();
bIsErrorFree &= Schema->TryCreateConnection(AddDelegateNode->FindPinChecked(Schema->PN_Self), ObjectPin);
bIsErrorFree &= Schema->TryCreateConnection(InOutLastThenPin, AddDelegateNode->FindPinChecked(Schema->PN_Execute));
InOutLastThenPin = AddDelegateNode->FindPinChecked(Schema->PN_Then);
UEdGraphPin* AddDelegate_DelegatePin = AddDelegateNode->GetDelegatePin();
bIsErrorFree &= CompilerContext.MovePinLinksToIntermediate(*DelegateRefPin, *AddDelegate_DelegatePin).CanSafeConnect();
DelegateRefPin->PinType = AddDelegate_DelegatePin->PinType;
return bIsErrorFree;
}
#undef LOCTEXT_NAMESPACE | [
"muit@piperift.com"
] | muit@piperift.com |
eff2b55f6c86cb7603192b2cb5572a832f34e8ba | df6a7072020c0cce62a2362761f01c08f1375be7 | /doc/quickbook/oglplus/quickref/object/group.cpp | 3eed3a837c4dd067c5ef3f743c81f55d6a8950bf | [
"BSL-1.0"
] | permissive | matus-chochlik/oglplus | aa03676bfd74c9877d16256dc2dcabcc034bffb0 | 76dd964e590967ff13ddff8945e9dcf355e0c952 | refs/heads/develop | 2023-03-07T07:08:31.615190 | 2021-10-26T06:11:43 | 2021-10-26T06:11:43 | 8,885,160 | 368 | 58 | BSL-1.0 | 2018-09-21T16:57:52 | 2013-03-19T17:52:30 | C++ | UTF-8 | C++ | false | false | 773 | cpp | /*
* Copyright 2014-2015 Matus Chochlik. 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)
*/
//[oglplus_object_StaticGroup_example_1
__VertexShader vxs;
vxs.Source(/* ... */).Compile();
__TessControlShader tcs;
tcs.Source(/* ... */).Compile();
__TessEvaluationShader tes;
tes.Source(/* ... */).Compile();
__GeometryShader gys;
gys.Source(/* ... */).Compile();
__FragmentShader fgs;
fgs.Source(/* ... */).Compile();
__Program prog;
prog.AttachShaders(__MakeGroup(vxs, tcs, tes, gys, fgs)); /*<
__MakeGroup creates a __StaticGroup<__Shader> which is implicitly
convertible to __Sequence<Shader> accepted by [^__Program::AttachShaders].
>*/
prog.Link();
//]
| [
"chochlik@gmail.com"
] | chochlik@gmail.com |
83c8d9ec969b3cf5714be7beec25d2e13596c855 | 764653c7d86be3c6d3d0c6e03deac62649590d8f | /euler_03.cpp | 116d8a5d3a5aa0afbe5dc8001feb3960fb246502 | [] | no_license | sunowsir/Euler | 32d67a4f8b6a3622ca6ec58eff7d9a224766fb01 | 51c12b2ed389371b3373525c6584b5e19755d629 | refs/heads/master | 2020-03-25T06:27:48.804105 | 2018-08-10T08:55:46 | 2018-08-10T08:55:46 | 143,503,230 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 970 | cpp | /*************************************************************************
> File Name: euler_03.cpp
> Author: sunowsir
> GitHub: github.com/sunowsir
> Created Time: 2018年07月31日 星期二 14时23分07秒
************************************************************************/
#include <iostream>
#include <inttypes.h>
using namespace std;
#define MAX_N 600851475143
int main () {
int64_t ans = -1;
for (int64_t i = 2; i * i < MAX_N ; i++) {
//i是否是该数的因数
if (MAX_N % i == 0) {
bool flag = true;
//判断i是否为素数
for (int64_t j = 2; j * j < i; j++) {
if (i % j == 0) {
flag = false;
break;
}
}
//如果是素数,把较大的存储在ans中
if (flag) {
ans = max(ans, i);
}
}
}
cout << ans << endl;
return 0;
}
| [
"sunowsir@qq.com"
] | sunowsir@qq.com |
82eef6fe593c9cfba9b723b344d2dd5db81a7440 | e08712b455da46ac9d8f16594daa141499bc8f6d | /DrVerServer/dataParser/ServerHandler.hpp | 2ef6202895d0239653111affbf0a4800cb17239e | [] | no_license | KingsleyYau/PushServer | ff97adedd73402cbb46009db69bf20993b787194 | 1183902d7e856e6124b4e8d5b06609215588d9b6 | refs/heads/master | 2021-01-15T14:29:48.678430 | 2014-01-18T13:29:25 | 2014-01-18T13:29:25 | 16,003,224 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,643 | hpp | /*
* File : ServerHandler.hpp
* Date : 2012-06-20
* Author : FGX
* Copyright : City Hotspot Co., Ltd.
* Description : Class for PushServer<->Server, it handles protocol and business logic
*/
#ifndef SERVERHANDLER_H
#define SERVERHANDLER_H
#include "DrVerData.hpp"
#include "LogicHandler.hpp"
class PushHandler;
class ServerHandler : public LogicHandler
{
protected:
typedef enum {
BEGIN_STEP = 0,
GET_CHANLLENGE_STEP = BEGIN_STEP,
REGISTER_SERVER_STEP,
PUSHMESSAGE_STEP,
END_STEP,
}TServerHandlerStep;
public:
ServerHandler();
virtual ~ServerHandler();
// LogicHandler interface
public:
virtual void SetPushHandler(PushHandler *pPushHandler);
virtual bool HandleProtocolData(const Json::Value &value, LPMESSAGE_DATA pMsgData);
virtual void Reset(bool bIsDeregisterTokenId = true);
virtual void SendSuccess();
private:
// handle protocol
inline bool GetChanllengeHandle(const Json::Value &value, LPMESSAGE_DATA pMsgData);
inline bool RegisterHandle(const Json::Value &value, LPMESSAGE_DATA pMsgData);
inline bool PushMessageHandle(const Json::Value &value, LPMESSAGE_DATA pMsgData);
inline void SetSendData(LPMESSAGE_DATA pMsgData, const Json::Value &value, const char *pHttpHead, const char *pHttpStatus);
public:
static bool CanHandle(const Json::Value &value, const char *pBody);
private:
PushHandler *m_pPushHandler;
TServerHandlerStep m_eHandleStep;
string m_strChanllenge;
pthread_mutex_t m_mutexReset;
};
#endif // SERVERHANDLER_H
| [
"Kingsleyyau@gmail.com"
] | Kingsleyyau@gmail.com |
f2aa325e7a76f2d822978e8be02d8f331aef2e25 | 301988ec503825eb36a4d74e2d14b7400b2781d7 | /src/spec_functions.cpp | f4fc964819e33de2baaddeede9e150d7f1b52474 | [] | no_license | lshand/rdimexp | d74d3cd574f247f9fdb8362b2fdf27b6b6b61b6b | 9c68a2bcb9d2862bd9fdc6d47bb22fb3c7168d57 | refs/heads/master | 2020-11-26T18:24:13.809341 | 2019-12-20T02:27:03 | 2019-12-20T02:27:03 | 229,171,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,163 | cpp | #include <RcppArmadillo.h>
//[[Rcpp::depends(RcppArmadillo)]]
#include <math.h>
#include <cmath>
using namespace Rcpp;
//' weighted frequency of a vector
//'
//' @param x vector of values
//' @param w vector of weights
//' @return weighted contingency table
//' @export
// [[Rcpp::export]]
arma::vec freqweight(arma::vec x,arma::vec w){
arma::vec x1 = sort(unique(x));
arma::vec count;
count.zeros(x1.n_elem);
for(int i=0; i< x1.n_elem; i++){
for(int j=0; j< x.n_elem; j++){
if(x(j)==x1(i)){
count(i)+= w(j);
}
}
}
return count;
}
//' weighted frequency of a vector
//'
//' @param rvec unique distance vector
//' @param rprof radial profile
//' @param r distance matrix
//' @return empirical spectral covariance
//' @export
// [[Rcpp::export]]
arma::mat cov_specd(arma::vec rvec,arma::vec rprof, arma::mat r){
arma::mat covmat;
covmat.zeros(size(r));
arma::vec dd;
double kmin;
double n = size(r,0);
for(int i=0; i< n; i++){
for(int j=i; j< n; j++){
dd = abs(r(i,j)-rvec);
kmin = dd.index_min();
covmat(i,j) = rprof(kmin);
covmat(j,i) = rprof(kmin);
}
}
return covmat;
}
| [
"lshand@sandia.gov"
] | lshand@sandia.gov |
437357686f98ff19dbed9087aed2ec52e431833e | 4882a18a4850e68728bc9c0a2d842c25eb29c8ff | /34.cpp | 39c7714df9abef9c81a0769dabe355e6899add19 | [] | no_license | OOCZC/coding-interviews | 761e7382cd1f49a31e522ab72cc6db21e1daa332 | 96f2b4f34d7c8ab086886cf5719d006b744dbef3 | refs/heads/master | 2021-05-10T11:05:16.772888 | 2019-07-08T15:06:51 | 2019-07-08T15:06:51 | 118,402,177 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,063 | cpp | vector<vector<int>> FindPath(TreeNode *root, int expectNumber){
vector<vector<int>> ans;
if(root == nullptr)
return ans;
int path[10000];
addPath(root, path, 0, ans, expectNumber);
return ans;
}
int addPath(TreeNode *root, int *path, int pathNum,
vector<vector<int>> &ans, int expectNumber){
if(root -> left == nullptr && root -> right == nullptr){
path[pathNum++] = root -> val;
int sum = 0;
for(int i = 0; i < pathNum; ++i){
sum += path[i];
}
if(sum == expectNumber){
vector<int> currentPath;
for(int i = 0; i < pathNum; ++i){
currentPath.push_back(path[i]);
}
ans.push_back(currentPath);
}
return 0;
}
path[pathNum++] = root -> val;
if(root -> left != nullptr){
addPath(root -> left, path, pathNum, ans, expectNumber);
}
if(root -> right != nullptr){
addPath(root -> right, path, pathNum, ans, expectNumber);
}
return 0;
}
| [
"whatisooc@gmail.com"
] | whatisooc@gmail.com |
192bbc44e635c117a71c98e0fee9d8619deaaaa1 | 9df57d037b0bf98060b172866a837f797fc935e0 | /main_archived/sensorReadings.ino | 718fe3115c776d5f51ab4943ba4fe585732a9494 | [] | no_license | NirobNabil/LFR | e03db71396e868ddb3f3f83cfdd8fa6cb18421f6 | 6847d0c90b5dae127852906f198131223f14b27f | refs/heads/master | 2022-08-19T18:19:50.776181 | 2022-07-22T05:32:55 | 2022-07-22T05:32:55 | 161,366,674 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | ino |
int ir_array[6];
char sensor_s[6];
int sensor;
void readData() {
ir_array[0] = analogRead(A0);
ir_array[1] = analogRead(A1);
ir_array[2] = analogRead(A2);
ir_array[3] = analogRead(A3);
ir_array[4] = analogRead(A4);
ir_array[5] = analogRead(A5);
sensor = 0;
for( int i=0; i<6; i++ ) {
sensor += ( ir_array[i] > IRminValueWhenOnBlack ? 1 : 0 ) * ( 1 << (i+1) );
sensor_s[i] = ( ir_array[i] > IRminValueWhenOnBlack ? '1' : '0' );
}
}
| [
"almubinnabil@gmail.com"
] | almubinnabil@gmail.com |
9cb0a33c08ede3e64079e67b09de1456a02277d0 | 400b1c7c4d4df879382387c68371b2b3fbda5d86 | /graphics/default_3d_shader.cpp | c8125037469fb090ae6e1cce8b6974fa8afcf618 | [] | no_license | grantclarke-abertay/gef | c5bbc131eee9d7577cc47862aac1c215d434f0fd | f75d686977899f115ead0062357bd8272bdfd367 | refs/heads/master | 2020-07-18T02:38:55.621559 | 2017-10-13T05:59:26 | 2017-10-13T05:59:26 | 67,597,774 | 12 | 4 | null | 2017-10-13T06:11:26 | 2016-09-07T10:42:37 | C++ | UTF-8 | C++ | false | false | 8,300 | cpp | /*
* default_3d_shader.cpp
*
* Created on: 29 Jan 2015
* Author: grant
*/
#include <graphics/default_3d_shader.h>
#include <graphics/shader_interface.h>
#include <graphics/mesh_instance.h>
#include <graphics/primitive.h>
#include <system/debug_log.h>
#include <graphics/mesh.h>
#include <graphics/material.h>
#include <graphics/colour.h>
#include <graphics/default_3d_shader_data.h>
#ifdef _WIN32
#include <platform/d3d11/graphics/shader_interface_d3d11.h>
#endif
namespace gef
{
Default3DShader::Default3DShader(const Platform& platform)
:Shader(platform)
,wvp_matrix_variable_index_(-1)
,world_matrix_variable_index_(-1)
,invworld_matrix_variable_index_(-1)
,light_position_variable_index_(-1)
,material_colour_variable_index_(-1)
,ambient_light_colour_variable_index_(-1)
,light_colour_variable_index_(-1)
,texture_sampler_index_(-1)
{
bool success = true;
// load vertex shader source in from a file
char* vs_shader_source = NULL;
Int32 vs_shader_source_length = 0;
success = LoadShader("default_3d_shader_vs", "shaders/gef", &vs_shader_source, vs_shader_source_length, platform);
char* ps_shader_source = NULL;
Int32 ps_shader_source_length = 0;
success = LoadShader("default_3d_shader_ps", "shaders/gef", &ps_shader_source, ps_shader_source_length, platform);
device_interface_->SetVertexShaderSource(vs_shader_source, vs_shader_source_length);
device_interface_->SetPixelShaderSource(ps_shader_source, ps_shader_source_length);
delete[] vs_shader_source;
vs_shader_source = NULL;
delete[] ps_shader_source;
ps_shader_source = NULL;
wvp_matrix_variable_index_ = device_interface_->AddVertexShaderVariable("wvp", ShaderInterface::kMatrix44);
world_matrix_variable_index_ = device_interface_->AddVertexShaderVariable("world", ShaderInterface::kMatrix44);
invworld_matrix_variable_index_ = device_interface_->AddVertexShaderVariable("invworld", ShaderInterface::kMatrix44);
light_position_variable_index_ = device_interface_->AddVertexShaderVariable("light_position", ShaderInterface::kVector4, 4);
// pixel shader variables
// TODO - probable need to keep these separate for D3D11
material_colour_variable_index_ = device_interface_->AddPixelShaderVariable("material_colour", ShaderInterface::kVector4);
ambient_light_colour_variable_index_ = device_interface_->AddPixelShaderVariable("ambient_light_colour", ShaderInterface::kVector4);
light_colour_variable_index_ = device_interface_->AddPixelShaderVariable("light_colour", ShaderInterface::kVector4, 4);
texture_sampler_index_ = device_interface_->AddTextureSampler("texture_sampler");
device_interface_->AddVertexParameter("position", ShaderInterface::kVector3, 0, "POSITION", 0);
device_interface_->AddVertexParameter("normal", ShaderInterface::kVector3, 12, "NORMAL", 0);
device_interface_->AddVertexParameter("uv", ShaderInterface::kVector2, 24, "TEXCOORD", 0);
device_interface_->set_vertex_size(sizeof(Mesh::Vertex));
device_interface_->CreateVertexFormat();
#ifdef _WIN32
gef::ShaderInterfaceD3D11* shader_interface_d3d11 = static_cast<gef::ShaderInterfaceD3D11*>(device_interface_);
// Create a texture sampler state description.
D3D11_SAMPLER_DESC sampler_desc;
sampler_desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sampler_desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sampler_desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sampler_desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
sampler_desc.MipLODBias = 0.0f;
sampler_desc.MaxAnisotropy = 1;
sampler_desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
sampler_desc.BorderColor[0] = 0;
sampler_desc.BorderColor[1] = 0;
sampler_desc.BorderColor[2] = 0;
sampler_desc.BorderColor[3] = 0;
sampler_desc.MinLOD = 0;
sampler_desc.MaxLOD = D3D11_FLOAT32_MAX;
shader_interface_d3d11->AddSamplerState(sampler_desc);
#endif
success = device_interface_->CreateProgram();
}
Default3DShader::Default3DShader()
: wvp_matrix_variable_index_(-1)
, world_matrix_variable_index_(-1)
, invworld_matrix_variable_index_(-1)
, light_position_variable_index_(-1)
, material_colour_variable_index_(-1)
, ambient_light_colour_variable_index_(-1)
, light_colour_variable_index_(-1)
, texture_sampler_index_(-1)
{
}
Default3DShader::~Default3DShader()
{
}
void Default3DShader::SetSceneData(const Default3DShaderData& shader_data, const Matrix44& view_matrix, const Matrix44& projection_matrix)
{
//gef::Matrix44 wvp = world_matrix * view_matrix * projection_matrix;
gef::Vector4 light_positions[MAX_NUM_POINT_LIGHTS];
gef::Vector4 light_colours[MAX_NUM_POINT_LIGHTS];
gef::Vector4 ambient_light_colour = shader_data.ambient_light_colour().GetRGBAasVector4();
for (Int32 light_num = 0; light_num < MAX_NUM_POINT_LIGHTS; ++light_num)
{
Vector4 light_position;
Colour light_colour;
if (light_num < shader_data.GetNumPointLights())
{
const PointLight& point_light = shader_data.GetPointLight(light_num);
light_position = point_light.position();
light_colour = point_light.colour();
}
else
{
// no light data
// set this light to a light with no colour
light_position = Vector4(0.0f, 0.0f, 0.0f);
light_colour = Colour(0.0f, 0.0f, 0.0f);
}
light_positions[light_num] = Vector4(light_position.x(), light_position.y(), light_position.z(), 1.f);
light_colours[light_num] = light_colour.GetRGBAasVector4();
}
view_projection_matrix_ = view_matrix * projection_matrix;
device_interface_->SetVertexShaderVariable(light_position_variable_index_, (float*)light_positions);
device_interface_->SetPixelShaderVariable(ambient_light_colour_variable_index_, (float*)&ambient_light_colour);
device_interface_->SetPixelShaderVariable(light_colour_variable_index_, (float*)light_colours);
}
void Default3DShader::SetMeshData(const gef::MeshInstance& mesh_instance)
{
// calculate world view projection matrix
gef::Matrix44 wvp = mesh_instance.transform() * view_projection_matrix_;
// calculate the transpose of inverse world matrix to transform normals in shader
Matrix44 inv_world;
inv_world.Inverse(mesh_instance.transform());
//inv_world_transpose_matrix.Transpose(inv_world);
// take transpose of matrices for the shaders
gef::Matrix44 wvpT, worldT;
wvpT.Transpose(wvp);
worldT.Transpose(mesh_instance.transform());
// taking the transpose of the inverse world transpose matrix, just give use the inverse world matrix
// no need to waste calculating that here
device_interface_->SetVertexShaderVariable(wvp_matrix_variable_index_, &wvpT);
device_interface_->SetVertexShaderVariable(world_matrix_variable_index_, &worldT);
device_interface_->SetVertexShaderVariable(invworld_matrix_variable_index_, &inv_world);
}
void Default3DShader::SetMeshData(const gef::Matrix44& transform)
{
// calculate world view projection matrix
gef::Matrix44 wvp = transform * view_projection_matrix_;
// calculate the transpose of inverse world matrix to transform normals in shader
Matrix44 inv_world;
inv_world.Inverse(transform);
//inv_world_transpose_matrix.Transpose(inv_world);
// take transpose of matrices for the shaders
gef::Matrix44 wvpT, worldT;
wvpT.Transpose(wvp);
worldT.Transpose(transform);
// taking the transpose of the inverse world transpose matrix, just give use the inverse world matrix
// no need to waste calculating that here
device_interface_->SetVertexShaderVariable(wvp_matrix_variable_index_, &wvpT);
device_interface_->SetVertexShaderVariable(world_matrix_variable_index_, &worldT);
device_interface_->SetVertexShaderVariable(invworld_matrix_variable_index_, &inv_world);
}
void Default3DShader::SetMaterialData(const gef::Material* material)
{
Colour material_colour(1.0f, 1.0f, 1.0f, 1.0f);
if (material)
{
primitive_data_.material_texture = material->texture();
material_colour.SetFromAGBR(material->colour());
}
else
primitive_data_.material_texture = NULL;
primitive_data_.material_colour = material_colour.GetRGBAasVector4();
device_interface_->SetPixelShaderVariable(material_colour_variable_index_, (float*)&primitive_data_.material_colour);
device_interface_->SetTextureSampler(texture_sampler_index_, primitive_data_.material_texture);
}
} /* namespace gef */
| [
"g.clarke@abertay.ac.uk"
] | g.clarke@abertay.ac.uk |
458701bc348071837efb669b0af864cbc823c679 | b25cb6a5214e19474c853240ac0d2b095e38cc17 | /src/masternode.cpp | cb5d58ef2d283a95dfce06b303eb13646796463e | [
"MIT"
] | permissive | danirabbani90/BeaconCoin | 6e3b74304eeb30eeba81f8d961c4f9fa4c1774d5 | e41c7a294df28e5c29d685a464d7b6c4581f2c91 | refs/heads/master | 2022-03-05T09:29:13.495160 | 2019-07-16T05:33:12 | 2019-07-16T05:33:12 | 196,143,102 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,074 | cpp | // Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "masternode.h"
#include "addrman.h"
#include "masternodeman.h"
#include "masternode-payments.h"
#include "masternode-helpers.h"
#include "sync.h"
#include "util.h"
#include "init.h"
#include "wallet.h"
#include "activemasternode.h"
#include <boost/lexical_cast.hpp>
// keep track of the scanning errors I've seen
map<uint256, int> mapSeenMasternodeScanningErrors;
// cache block hashes as we calculate them
std::map<int64_t, uint256> mapCacheBlockHashes;
//Get the last hash that matches the modulus given. Processed in reverse order
bool GetBlockHash(uint256& hash, int nBlockHeight)
{
if (chainActive.Tip() == NULL) return false;
if (nBlockHeight == 0)
nBlockHeight = chainActive.Tip()->nHeight;
if (mapCacheBlockHashes.count(nBlockHeight)) {
hash = mapCacheBlockHashes[nBlockHeight];
return true;
}
const CBlockIndex* BlockLastSolved = chainActive.Tip();
const CBlockIndex* BlockReading = chainActive.Tip();
if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || chainActive.Tip()->nHeight + 1 < nBlockHeight) return false;
int nBlocksAgo = 0;
if (nBlockHeight > 0) nBlocksAgo = (chainActive.Tip()->nHeight + 1) - nBlockHeight;
assert(nBlocksAgo >= 0);
int n = 0;
for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
if (n >= nBlocksAgo) {
hash = BlockReading->GetBlockHash();
mapCacheBlockHashes[nBlockHeight] = hash;
return true;
}
n++;
if (BlockReading->pprev == NULL) {
assert(BlockReading);
break;
}
BlockReading = BlockReading->pprev;
}
return false;
}
CMasternode::CMasternode()
{
LOCK(cs);
vin = CTxIn();
addr = CService();
pubKeyCollateralAddress = CPubKey();
pubKeyMasternode = CPubKey();
sig = std::vector<unsigned char>();
activeState = MASTERNODE_ENABLED;
sigTime = GetAdjustedTime();
lastPing = CMasternodePing();
cacheInputAge = 0;
cacheInputAgeBlock = 0;
unitTest = false;
allowFreeTx = true;
nActiveState = MASTERNODE_ENABLED,
protocolVersion = PROTOCOL_VERSION;
nLastDsq = 0;
nScanningErrorCount = 0;
nLastScanningErrorBlockHeight = 0;
lastTimeChecked = 0;
nLastDsee = 0; // temporary, do not save. Remove after migration to v12
nLastDseep = 0; // temporary, do not save. Remove after migration to v12
}
CMasternode::CMasternode(const CMasternode& other)
{
LOCK(cs);
vin = other.vin;
addr = other.addr;
pubKeyCollateralAddress = other.pubKeyCollateralAddress;
pubKeyMasternode = other.pubKeyMasternode;
sig = other.sig;
activeState = other.activeState;
sigTime = other.sigTime;
lastPing = other.lastPing;
cacheInputAge = other.cacheInputAge;
cacheInputAgeBlock = other.cacheInputAgeBlock;
unitTest = other.unitTest;
allowFreeTx = other.allowFreeTx;
nActiveState = MASTERNODE_ENABLED,
protocolVersion = other.protocolVersion;
nLastDsq = other.nLastDsq;
nScanningErrorCount = other.nScanningErrorCount;
nLastScanningErrorBlockHeight = other.nLastScanningErrorBlockHeight;
lastTimeChecked = 0;
nLastDsee = other.nLastDsee; // temporary, do not save. Remove after migration to v12
nLastDseep = other.nLastDseep; // temporary, do not save. Remove after migration to v12
}
CMasternode::CMasternode(const CMasternodeBroadcast& mnb)
{
LOCK(cs);
vin = mnb.vin;
addr = mnb.addr;
pubKeyCollateralAddress = mnb.pubKeyCollateralAddress;
pubKeyMasternode = mnb.pubKeyMasternode;
sig = mnb.sig;
activeState = MASTERNODE_ENABLED;
sigTime = mnb.sigTime;
lastPing = mnb.lastPing;
cacheInputAge = 0;
cacheInputAgeBlock = 0;
unitTest = false;
allowFreeTx = true;
nActiveState = MASTERNODE_ENABLED,
protocolVersion = mnb.protocolVersion;
nLastDsq = mnb.nLastDsq;
nScanningErrorCount = 0;
nLastScanningErrorBlockHeight = 0;
lastTimeChecked = 0;
nLastDsee = 0; // temporary, do not save. Remove after migration to v12
nLastDseep = 0; // temporary, do not save. Remove after migration to v12
}
//
// When a new masternode broadcast is sent, update our information
//
bool CMasternode::UpdateFromNewBroadcast(CMasternodeBroadcast& mnb)
{
if (mnb.sigTime > sigTime) {
pubKeyMasternode = mnb.pubKeyMasternode;
pubKeyCollateralAddress = mnb.pubKeyCollateralAddress;
sigTime = mnb.sigTime;
sig = mnb.sig;
protocolVersion = mnb.protocolVersion;
addr = mnb.addr;
lastTimeChecked = 0;
int nDoS = 0;
if (mnb.lastPing == CMasternodePing() || (mnb.lastPing != CMasternodePing() && mnb.lastPing.CheckAndUpdate(nDoS, false))) {
lastPing = mnb.lastPing;
mnodeman.mapSeenMasternodePing.insert(make_pair(lastPing.GetHash(), lastPing));
}
return true;
}
return false;
}
//
// Deterministically calculate a given "score" for a Masternode depending on how close it's hash is to
// the proof of work for that block. The further away they are the better, the furthest will win the election
// and get paid this block
//
uint256 CMasternode::CalculateScore(int mod, int64_t nBlockHeight)
{
if (chainActive.Tip() == NULL) return 0;
uint256 hash = 0;
uint256 aux = vin.prevout.hash + vin.prevout.n;
if (!GetBlockHash(hash, nBlockHeight)) {
LogPrint("masternode","CalculateScore ERROR - nHeight %d - Returned 0\n", nBlockHeight);
return 0;
}
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << hash;
uint256 hash2 = ss.GetHash();
CHashWriter ss2(SER_GETHASH, PROTOCOL_VERSION);
ss2 << hash;
ss2 << aux;
uint256 hash3 = ss2.GetHash();
uint256 r = (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3);
return r;
}
void CMasternode::Check(bool forceCheck)
{
if (ShutdownRequested()) return;
if (!forceCheck && (GetTime() - lastTimeChecked < MASTERNODE_CHECK_SECONDS)) return;
lastTimeChecked = GetTime();
//once spent, stop doing the checks
if (activeState == MASTERNODE_VIN_SPENT) return;
if (!IsPingedWithin(MASTERNODE_REMOVAL_SECONDS)) {
activeState = MASTERNODE_REMOVE;
return;
}
if (!IsPingedWithin(MASTERNODE_EXPIRATION_SECONDS)) {
activeState = MASTERNODE_EXPIRED;
return;
}
if (!unitTest) {
CValidationState state;
CMutableTransaction tx = CMutableTransaction();
CTxOut vout = CTxOut((MASTERNODE_COLLATERAL-0.01) * COIN, masternodeSigner.collateralPubKey);
tx.vin.push_back(vin);
tx.vout.push_back(vout);
{
TRY_LOCK(cs_main, lockMain);
if (!lockMain) return;
if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL)) {
activeState = MASTERNODE_VIN_SPENT;
return;
}
}
}
activeState = MASTERNODE_ENABLED; // OK
}
int64_t CMasternode::SecondsSincePayment()
{
CScript pubkeyScript;
pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID());
int64_t sec = (GetAdjustedTime() - GetLastPaid());
int64_t month = 60 * 60 * 24 * 30;
if (sec < month) return sec; //if it's less than 30 days, give seconds
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vin;
ss << sigTime;
uint256 hash = ss.GetHash();
// return some deterministic value for unknown/unpaid but force it to be more than 30 days old
return month + hash.GetCompact(false);
}
int64_t CMasternode::GetLastPaid()
{
CBlockIndex* pindexPrev = chainActive.Tip();
if (pindexPrev == NULL) return false;
CScript mnpayee;
mnpayee = GetScriptForDestination(pubKeyCollateralAddress.GetID());
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vin;
ss << sigTime;
uint256 hash = ss.GetHash();
// use a deterministic offset to break a tie -- 2.5 minutes
int64_t nOffset = hash.GetCompact(false) % 150;
if (chainActive.Tip() == NULL) return false;
const CBlockIndex* BlockReading = chainActive.Tip();
int nMnCount = mnodeman.CountEnabled() * 1.25;
int n = 0;
for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
if (n >= nMnCount) {
return 0;
}
n++;
if (masternodePayments.mapMasternodeBlocks.count(BlockReading->nHeight)) {
/*
Search for this payee, with at least 2 votes. This will aid in consensus allowing the network
to converge on the same payees quickly, then keep the same schedule.
*/
if (masternodePayments.mapMasternodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2)) {
return BlockReading->nTime + nOffset;
}
}
if (BlockReading->pprev == NULL) {
assert(BlockReading);
break;
}
BlockReading = BlockReading->pprev;
}
return 0;
}
std::string CMasternode::GetStatus()
{
switch (nActiveState) {
case CMasternode::MASTERNODE_PRE_ENABLED:
return "PRE_ENABLED";
case CMasternode::MASTERNODE_ENABLED:
return "ENABLED";
case CMasternode::MASTERNODE_EXPIRED:
return "EXPIRED";
case CMasternode::MASTERNODE_OUTPOINT_SPENT:
return "OUTPOINT_SPENT";
case CMasternode::MASTERNODE_REMOVE:
return "REMOVE";
case CMasternode::MASTERNODE_WATCHDOG_EXPIRED:
return "WATCHDOG_EXPIRED";
case CMasternode::MASTERNODE_POSE_BAN:
return "POSE_BAN";
default:
return "UNKNOWN";
}
}
bool CMasternode::IsValidNetAddr()
{
// TODO: regtest is fine with any addresses for now,
// should probably be a bit smarter if one day we start to implement tests for this
return Params().NetworkID() == CBaseChainParams::REGTEST ||
(IsReachable(addr) && addr.IsRoutable());
}
CMasternodeBroadcast::CMasternodeBroadcast()
{
vin = CTxIn();
addr = CService();
pubKeyCollateralAddress = CPubKey();
pubKeyMasternode1 = CPubKey();
sig = std::vector<unsigned char>();
activeState = MASTERNODE_ENABLED;
sigTime = GetAdjustedTime();
lastPing = CMasternodePing();
cacheInputAge = 0;
cacheInputAgeBlock = 0;
unitTest = false;
allowFreeTx = true;
protocolVersion = PROTOCOL_VERSION;
nLastDsq = 0;
nScanningErrorCount = 0;
nLastScanningErrorBlockHeight = 0;
}
CMasternodeBroadcast::CMasternodeBroadcast(CService newAddr, CTxIn newVin, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyMasternodeNew, int protocolVersionIn)
{
vin = newVin;
addr = newAddr;
pubKeyCollateralAddress = pubKeyCollateralAddressNew;
pubKeyMasternode = pubKeyMasternodeNew;
sig = std::vector<unsigned char>();
activeState = MASTERNODE_ENABLED;
sigTime = GetAdjustedTime();
lastPing = CMasternodePing();
cacheInputAge = 0;
cacheInputAgeBlock = 0;
unitTest = false;
allowFreeTx = true;
protocolVersion = protocolVersionIn;
nLastDsq = 0;
nScanningErrorCount = 0;
nLastScanningErrorBlockHeight = 0;
}
CMasternodeBroadcast::CMasternodeBroadcast(const CMasternode& mn)
{
vin = mn.vin;
addr = mn.addr;
pubKeyCollateralAddress = mn.pubKeyCollateralAddress;
pubKeyMasternode = mn.pubKeyMasternode;
sig = mn.sig;
activeState = mn.activeState;
sigTime = mn.sigTime;
lastPing = mn.lastPing;
cacheInputAge = mn.cacheInputAge;
cacheInputAgeBlock = mn.cacheInputAgeBlock;
unitTest = mn.unitTest;
allowFreeTx = mn.allowFreeTx;
protocolVersion = mn.protocolVersion;
nLastDsq = mn.nLastDsq;
nScanningErrorCount = mn.nScanningErrorCount;
nLastScanningErrorBlockHeight = mn.nLastScanningErrorBlockHeight;
}
bool CMasternodeBroadcast::Create(std::string strService, std::string strKeyMasternode, std::string strTxHash, std::string strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast& mnbRet, bool fOffline)
{
CTxIn txin;
CPubKey pubKeyCollateralAddressNew;
CKey keyCollateralAddressNew;
CPubKey pubKeyMasternodeNew;
CKey keyMasternodeNew;
//need correct blocks to send ping
if (!fOffline && !masternodeSync.IsBlockchainSynced()) {
strErrorRet = "Sync in progress. Must wait until sync is complete to start Masternode";
LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet);
return false;
}
if (!masternodeSigner.GetKeysFromSecret(strKeyMasternode, keyMasternodeNew, pubKeyMasternodeNew)) {
strErrorRet = strprintf("Invalid masternode key %s", strKeyMasternode);
LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet);
return false;
}
if (!pwalletMain->GetMasternodeVinAndKeys(txin, pubKeyCollateralAddressNew, keyCollateralAddressNew, strTxHash, strOutputIndex)) {
strErrorRet = strprintf("Could not allocate txin %s:%s for masternode %s", strTxHash, strOutputIndex, strService);
LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet);
return false;
}
// CService service = CService(strService);
// int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort();
// if (Params().NetworkID() == CBaseChainParams::MAIN) {
// if (service.GetPort() != mainnetDefaultPort) {
// strErrorRet = strprintf("Invalid port %u for masternode %s, only %d is supported on mainnet.", service.GetPort(), strService, mainnetDefaultPort);
// LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet);
// return false;
// }
// } else if (service.GetPort() == mainnetDefaultPort) {
// strErrorRet = strprintf("Invalid port %u for masternode %s, %d is the only supported on mainnet.", service.GetPort(), strService, mainnetDefaultPort);
// LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet);
// return false;
// }
return Create(txin, CService(strService), keyCollateralAddressNew, pubKeyCollateralAddressNew, keyMasternodeNew, pubKeyMasternodeNew, strErrorRet, mnbRet);
}
bool CMasternodeBroadcast::Create(CTxIn txin, CService service, CKey keyCollateralAddressNew, CPubKey pubKeyCollateralAddressNew, CKey keyMasternodeNew, CPubKey pubKeyMasternodeNew, std::string& strErrorRet, CMasternodeBroadcast& mnbRet)
{
// wait for reindex and/or import to finish
if (fImporting || fReindex) return false;
LogPrint("masternode", "CMasternodeBroadcast::Create -- pubKeyCollateralAddressNew = %s, pubKeyMasternodeNew.GetID() = %s\n",
CBitcoinAddress(pubKeyCollateralAddressNew.GetID()).ToString(),
pubKeyMasternodeNew.GetID().ToString());
CMasternodePing mnp(txin);
if (!mnp.Sign(keyMasternodeNew, pubKeyMasternodeNew)) {
strErrorRet = strprintf("Failed to sign ping, masternode=%s", txin.prevout.hash.ToString());
LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet);
mnbRet = CMasternodeBroadcast();
return false;
}
mnbRet = CMasternodeBroadcast(service, txin, pubKeyCollateralAddressNew, pubKeyMasternodeNew, PROTOCOL_VERSION);
// if (!mnbRet.IsValidNetAddr()) {
// strErrorRet = strprintf("Invalid IP address %s, masternode=%s", mnbRet.addr.ToStringIP (), txin.prevout.hash.ToString());
// LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet);
// mnbRet = CMasternodeBroadcast();
// return false;
// }
mnbRet.lastPing = mnp;
if (!mnbRet.Sign(keyCollateralAddressNew)) {
strErrorRet = strprintf("Failed to sign broadcast, masternode=%s", txin.prevout.hash.ToString());
LogPrint("masternode","CMasternodeBroadcast::Create -- %s\n", strErrorRet);
mnbRet = CMasternodeBroadcast();
return false;
}
return true;
}
bool CMasternodeBroadcast::CheckAndUpdate(int& nDos)
{
// make sure signature isn't in the future (past is OK)
if (sigTime > GetAdjustedTime() + 60 * 60) {
LogPrint("masternode","mnb - Signature rejected, too far into the future %s\n", vin.prevout.hash.ToString());
nDos = 1;
return false;
}
std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end());
std::string vchPubKey2(pubKeyMasternode.begin(), pubKeyMasternode.end());
std::string strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(protocolVersion);
if (protocolVersion < masternodePayments.GetMinMasternodePaymentsProto()) {
LogPrint("masternode","mnb - ignoring outdated Masternode %s protocol version %d\n", vin.prevout.hash.ToString(), protocolVersion);
return false;
}
CScript pubkeyScript;
pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID());
if (pubkeyScript.size() != 25) {
LogPrint("masternode","mnb - pubkey the wrong size\n");
nDos = 100;
return false;
}
CScript pubkeyScript2;
pubkeyScript2 = GetScriptForDestination(pubKeyMasternode.GetID());
if (pubkeyScript2.size() != 25) {
LogPrint("masternode","mnb - pubkey2 the wrong size\n");
nDos = 100;
return false;
}
if (!vin.scriptSig.empty()) {
LogPrint("masternode","mnb - Ignore Not Empty ScriptSig %s\n", vin.prevout.hash.ToString());
return false;
}
std::string errorMessage = "";
if (!masternodeSigner.VerifyMessage(pubKeyCollateralAddress, sig, strMessage, errorMessage)) {
LogPrint("masternode","mnb - Got bad Masternode address signature\n");
nDos = 100;
return false;
}
// if (Params().NetworkID() == CBaseChainParams::MAIN) {
// if (addr.GetPort() != 7333) return false;
// } else if (addr.GetPort() == 7333)
// return false;
//search existing Masternode list, this is where we update existing Masternodes with new mnb broadcasts
CMasternode* pmn = mnodeman.Find(vin);
// no such masternode, nothing to update
if (pmn == NULL)
return true;
else {
// this broadcast older than we have, it's bad.
if (pmn->sigTime > sigTime) {
LogPrint("masternode","mnb - Bad sigTime %d for Masternode %s (existing broadcast is at %d)\n",
sigTime, vin.prevout.hash.ToString(), pmn->sigTime);
return false;
}
// masternode is not enabled yet/already, nothing to update
if (!pmn->IsEnabled()) return true;
}
// mn.pubkey = pubkey, IsVinAssociatedWithPubkey is validated once below,
// after that they just need to match
if (pmn->pubKeyCollateralAddress == pubKeyCollateralAddress && !pmn->IsBroadcastedWithin(MASTERNODE_MIN_MNB_SECONDS)) {
//take the newest entry
LogPrint("masternode","mnb - Got updated entry for %s\n", vin.prevout.hash.ToString());
if (pmn->UpdateFromNewBroadcast((*this))) {
pmn->Check();
if (pmn->IsEnabled()) Relay();
}
masternodeSync.AddedMasternodeList(GetHash());
}
return true;
}
bool CMasternodeBroadcast::CheckInputsAndAdd(int& nDoS)
{
// we are a masternode with the same vin (i.e. already activated) and this mnb is ours (matches our Masternode privkey)
// so nothing to do here for us
if (fMasterNode && vin.prevout == activeMasternode.vin.prevout && pubKeyMasternode == activeMasternode.pubKeyMasternode)
return true;
// search existing Masternode list
CMasternode* pmn = mnodeman.Find(vin);
if (pmn != NULL) {
// nothing to do here if we already know about this masternode and it's enabled
if (pmn->IsEnabled()) return true;
// if it's not enabled, remove old MN first and continue
else
mnodeman.Remove(pmn->vin);
}
CValidationState state;
CMutableTransaction tx = CMutableTransaction();
CTxOut vout = CTxOut((MASTERNODE_COLLATERAL-0.01) * COIN, masternodeSigner.collateralPubKey);
tx.vin.push_back(vin);
tx.vout.push_back(vout);
{
TRY_LOCK(cs_main, lockMain);
if (!lockMain) {
// not mnb fault, let it to be checked again later
mnodeman.mapSeenMasternodeBroadcast.erase(GetHash());
masternodeSync.mapSeenSyncMNB.erase(GetHash());
return false;
}
if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL)) {
//set nDos
state.IsInvalid(nDoS);
return false;
}
}
LogPrint("masternode", "mnb - Accepted Masternode entry\n");
if (GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS) {
LogPrint("masternode","mnb - Input must have at least %d confirmations\n", MASTERNODE_MIN_CONFIRMATIONS);
// maybe we miss few blocks, let this mnb to be checked again later
mnodeman.mapSeenMasternodeBroadcast.erase(GetHash());
masternodeSync.mapSeenSyncMNB.erase(GetHash());
return false;
}
// verify that sig time is legit in past
// should be at least not earlier than block when 1000 BCC tx got MASTERNODE_MIN_CONFIRMATIONS
uint256 hashBlock = 0;
CTransaction tx2;
GetTransaction(vin.prevout.hash, tx2, hashBlock, true);
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pMNIndex = (*mi).second; // block for 1000 PIVX tx -> 1 confirmation
CBlockIndex* pConfIndex = chainActive[pMNIndex->nHeight + MASTERNODE_MIN_CONFIRMATIONS - 1]; // block where tx got MASTERNODE_MIN_CONFIRMATIONS
if (pConfIndex->GetBlockTime() > sigTime) {
LogPrint("masternode","mnb - Bad sigTime %d for Masternode %s (%i conf block is at %d)\n",
sigTime, vin.prevout.hash.ToString(), MASTERNODE_MIN_CONFIRMATIONS, pConfIndex->GetBlockTime());
return false;
}
}
LogPrint("masternode","mnb - Got NEW Masternode entry - %s - %lli \n", vin.prevout.hash.ToString(), sigTime);
CMasternode mn(*this);
mnodeman.Add(mn);
// if it matches our Masternode privkey, then we've been remotely activated
if (pubKeyMasternode == activeMasternode.pubKeyMasternode && protocolVersion == PROTOCOL_VERSION) {
activeMasternode.EnableHotColdMasterNode(vin, addr);
}
bool isLocal = addr.IsRFC1918() || addr.IsLocal();
if (Params().NetworkID() == CBaseChainParams::REGTEST) isLocal = false;
if (!isLocal) Relay();
return true;
}
void CMasternodeBroadcast::Relay()
{
CInv inv(MSG_MASTERNODE_ANNOUNCE, GetHash());
RelayInv(inv);
}
bool CMasternodeBroadcast::Sign(CKey& keyCollateralAddress)
{
std::string errorMessage;
std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end());
std::string vchPubKey2(pubKeyMasternode.begin(), pubKeyMasternode.end());
sigTime = GetAdjustedTime();
std::string strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(protocolVersion);
if (!masternodeSigner.SignMessage(strMessage, errorMessage, sig, keyCollateralAddress)) {
LogPrint("masternode","CMasternodeBroadcast::Sign() - Error: %s\n", errorMessage);
return false;
}
if (!masternodeSigner.VerifyMessage(pubKeyCollateralAddress, sig, strMessage, errorMessage)) {
LogPrint("masternode","CMasternodeBroadcast::Sign() - Error: %s\n", errorMessage);
return false;
}
return true;
}
CMasternodePing::CMasternodePing()
{
vin = CTxIn();
blockHash = uint256(0);
sigTime = 0;
vchSig = std::vector<unsigned char>();
}
CMasternodePing::CMasternodePing(CTxIn& newVin)
{
vin = newVin;
blockHash = chainActive[chainActive.Height() - 12]->GetBlockHash();
sigTime = GetAdjustedTime();
vchSig = std::vector<unsigned char>();
}
bool CMasternodePing::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode)
{
std::string errorMessage;
std::string strMasterNodeSignMessage;
sigTime = GetAdjustedTime();
std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime);
if (!masternodeSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) {
LogPrint("masternode","CMasternodePing::Sign() - Error: %s\n", errorMessage);
return false;
}
if (!masternodeSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) {
LogPrint("masternode","CMasternodePing::Sign() - Error: %s\n", errorMessage);
return false;
}
return true;
}
bool CMasternodePing::CheckAndUpdate(int& nDos, bool fRequireEnabled)
{
if (sigTime > GetAdjustedTime() + 60 * 60) {
LogPrint("masternode","CMasternodePing::CheckAndUpdate - Signature rejected, too far into the future %s\n", vin.prevout.hash.ToString());
nDos = 1;
return false;
}
if (sigTime <= GetAdjustedTime() - 60 * 60) {
LogPrint("masternode","CMasternodePing::CheckAndUpdate - Signature rejected, too far into the past %s - %d %d \n", vin.prevout.hash.ToString(), sigTime, GetAdjustedTime());
nDos = 1;
return false;
}
LogPrint("masternode","CMasternodePing::CheckAndUpdate - New Ping - %s - %lli\n", blockHash.ToString(), sigTime);
// see if we have this Masternode
CMasternode* pmn = mnodeman.Find(vin);
if (pmn != NULL && pmn->protocolVersion >= masternodePayments.GetMinMasternodePaymentsProto()) {
if (fRequireEnabled && !pmn->IsEnabled()) return false;
// LogPrint("masternode","mnping - Found corresponding mn for vin: %s\n", vin.ToString());
// update only if there is no known ping for this masternode or
// last ping was more then MASTERNODE_MIN_MNP_SECONDS-60 ago comparing to this one
if (!pmn->IsPingedWithin(MASTERNODE_MIN_MNP_SECONDS - 60, sigTime)) {
std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime);
std::string errorMessage = "";
if (!masternodeSigner.VerifyMessage(pmn->pubKeyMasternode, vchSig, strMessage, errorMessage)) {
LogPrint("masternode","CMasternodePing::CheckAndUpdate - Got bad Masternode address signature %s\n", vin.prevout.hash.ToString());
nDos = 33;
return false;
}
BlockMap::iterator mi = mapBlockIndex.find(blockHash);
if (mi != mapBlockIndex.end() && (*mi).second) {
if ((*mi).second->nHeight < chainActive.Height() - 24) {
LogPrint("masternode","CMasternodePing::CheckAndUpdate - Masternode %s block hash %s is too old\n", vin.prevout.hash.ToString(), blockHash.ToString());
// Do nothing here (no Masternode update, no mnping relay)
// Let this node to be visible but fail to accept mnping
return false;
}
} else {
if (fDebug) LogPrint("masternode","CMasternodePing::CheckAndUpdate - Masternode %s block hash %s is unknown\n", vin.prevout.hash.ToString(), blockHash.ToString());
// maybe we stuck so we shouldn't ban this node, just fail to accept it
// TODO: or should we also request this block?
return false;
}
pmn->lastPing = *this;
//mnodeman.mapSeenMasternodeBroadcast.lastPing is probably outdated, so we'll update it
CMasternodeBroadcast mnb(*pmn);
uint256 hash = mnb.GetHash();
if (mnodeman.mapSeenMasternodeBroadcast.count(hash)) {
mnodeman.mapSeenMasternodeBroadcast[hash].lastPing = *this;
}
pmn->Check(true);
if (!pmn->IsEnabled()) return false;
LogPrint("masternode", "CMasternodePing::CheckAndUpdate - Masternode ping accepted, vin: %s\n", vin.prevout.hash.ToString());
Relay();
return true;
}
LogPrint("masternode", "CMasternodePing::CheckAndUpdate - Masternode ping arrived too early, vin: %s\n", vin.prevout.hash.ToString());
//nDos = 1; //disable, this is happening frequently and causing banned peers
return false;
}
LogPrint("masternode", "CMasternodePing::CheckAndUpdate - Couldn't find compatible Masternode entry, vin: %s\n", vin.prevout.hash.ToString());
return false;
}
void CMasternodePing::Relay()
{
CInv inv(MSG_MASTERNODE_PING, GetHash());
RelayInv(inv);
}
| [
"yoonusansar@gmail.com"
] | yoonusansar@gmail.com |
22906d53a0b584ed70c0dcb774f9ee105d79a97e | 659c5a9a55a47773f60b7e60e6ca8d1a88a5d034 | /src/scan/ParallelScanner.h | f374aacb2af246a6b537615315c835bbe4efde75 | [] | no_license | harperjiang/simdscan | e87e64d11f5db91c40613c860318dffda6525a88 | 262004497fbbc1548bb99151e21133c270c24204 | refs/heads/master | 2021-01-20T02:23:19.700323 | 2019-05-06T02:46:21 | 2019-05-06T02:46:21 | 101,318,954 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 650 | h | //
// Created by harper on 3/21/18.
//
#ifndef SIMDSCAN_PARALLELSCANNER_H
#define SIMDSCAN_PARALLELSCANNER_H
#include <pthread.h>
#include "Scanner.h"
class ParallelScanner : public Scanner {
private:
int numThread = 0;
int entrySize = 0;
Scanner *innerScanner = NULL;
pthread_t *threadHandles = NULL;
public:
ParallelScanner(int nt, int es, Scanner *inner);
virtual ~ParallelScanner();
void scan(int *, uint64_t, int *, Predicate *);
};
typedef struct _ScannerParam {
int *input;
int *output;
uint64_t size;
Predicate *p;
Scanner *scanner;
} ScannerParam;
#endif //SIMDSCAN_PARALLELSCANNER_H
| [
"harperjiang@msn.com"
] | harperjiang@msn.com |
e1222a989da44104bd2b6edbdecb243354db3993 | 5c0f55728cca333b52dc9cd8e282faf424d18fd0 | /src/Game.hpp | acfa363df8403ce992a57ebbbcbe900a5f7897fa | [] | no_license | sagarPakhrin/SnakeGame | 114ec17ab8180603a967b0d483acd500d1a5b7c6 | 607d1732facdda5d98f754303d6066be0b2bcfc4 | refs/heads/master | 2020-06-28T11:30:53.313390 | 2019-08-08T18:32:39 | 2019-08-08T18:32:39 | 200,222,832 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 599 | hpp | #pragma once
#include <memory>
#include <string>
#include <SFML/Graphics.hpp>
#include "StateMachine.hpp"
#include "AssetManager.hpp"
#include "InputManager.hpp"
namespace Sagar
{
struct GameData
{
StateMachine machine;
sf::RenderWindow window;
AssetManager assets;
InputManager input;
};
typedef std::shared_ptr<GameData> GameDataRef;
class Game
{
public:
Game(int width, int height, std::string title);
private:
const float dt = 1.0f/60.0f;
sf::Clock _clock;
GameDataRef _data = std::make_shared<GameData>();
void Run();
};
}
| [
"sagarlama826@gmail.com"
] | sagarlama826@gmail.com |
7c4507edf86a3dc3b8dd1c627f7c6fe370d2c6eb | 2b07a9a2be66c4d36f596fabd12a0086f680b992 | /examples/SI47XX_03_OLED_I2C/SI47XX_03_ALL_IN_ONE_NEW_INTERFACE_V20/SI47XX_03_ALL_IN_ONE_NEW_INTERFACE_V20.ino | d1229c3196bf1628132cf9d98b2fb8479340a6a6 | [
"MIT"
] | permissive | theqf/SI4735 | 6bbbdb3ba2bf9581174c67c934f3535630e4312d | c2299d0f37c125f630a62a7ebe6ad6d35f0c04c9 | refs/heads/master | 2023-09-05T06:52:23.486614 | 2021-11-10T11:48:37 | 2021-11-10T11:48:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,188 | ino | /*
Please, read the user_manual.txt for more details about this project.
ATTENTION: Turn your receiver on with the encoder push button pressed at first time to RESET the eeprom content.
ARDUINO LIBRARIES:
1) This sketch uses the Rotary Encoder Class implementation from Ben Buxton (the source code is included together with this sketch). You do not need to install it;
2) Tiny4kOLED Library and TinyOLED-Fonts (on your Arduino IDE, look for this library on Tools->Manage Libraries).
3) PU2CLR SI4735 Arduino Library (on your Arduino IDE look for this library on Tools->Manage Libraries).
ABOUT THE EEPROM:
ATMEL says the lifetime of an EEPROM memory position is about 100,000 writes.
For this reason, this sketch tries to avoid save unnecessary writes into the eeprom.
So, the condition to store any status of the receiver is changing the frequency, bandwidth, volume, band or step and 10 seconds of inactivity.
For example, if you switch the band and turn the receiver off immediately, no new information will be written into the eeprom.
But you wait 10 seconds after changing anything, all new information will be written.
ABOUT SSB PATCH:
First of all, it is important to say that the SSB patch content is not part of this library. The paches used here were made available by Mr.
Vadim Afonkin on his Dropbox repository. It is important to note that the author of this library does not encourage anyone to use the SSB patches
content for commercial purposes. In other words, this library only supports SSB patches, the patches themselves are not part of this library.
In this context, a patch is a piece of software used to change the behavior of the SI4735 device.
There is little information available about patching the SI4735 or Si4732 devices. The following information is the understanding of the author of
this project and it is not necessarily correct. A patch is executed internally (run by internal MCU) of the device.
Usually, patches are used to fixes bugs or add improvements and new features of the firmware installed in the internal ROM of the device.
Patches to the SI4735 are distributed in binary form and have to be transferred to the internal RAM of the device by
the host MCU (in this case Arduino). Since the RAM is volatile memory, the patch stored into the device gets lost when you turn off the system.
Consequently, the content of the patch has to be transferred again to the device each time after turn on the system or reset the device.
Wire up on Arduino UNO, Pro mini and SI4735-D60
| Device name | Device Pin / Description | Arduino Pin |
| ---------------- | ----------------------------- | ------------ |
| Display OLED | | |
| | SDA | A4 |
| | CLK | A5 |
| (*1) SI4735 | | |
| | RESET (pin 15) | 12 |
| | SDIO (pin 18) | A4 |
| | SCLK (pin 17) | A5 |
| | SEN (pin 16) | GND |
| (*2) Buttons | | |
| | Switch MODE (AM/LSB/AM) | 4 |
| | Banddwith | 5 |
| | Volume | 6 |
| | Custom button 1 (*3) | 7 |
| | Band | 8 |
| | Custom button 2 (*3) | 9 |
| | Step | 10 |
| | AGC / Attentuation | 11 |
| | VFO/VFO Switch (Encoder) | 14 / A0 |
| Encoder (*4) | | |
| | A | 2 |
| | B | 3 |
*1 - You can use the SI4732-A10. Check on the SI4732 package the pins: RESET, SDIO, SCLK and SEN.
*2 - Please, read the file user_manual.txt for more detail.
*3 - You can remove this buttons from your circuit and sketch if you dont want to use them.
*4 - Some encoder devices have pins A and B inverted. So, if the clockwise and counterclockwise directions
are not correct for you, please, invert the settings for pins A and B.
Prototype documentation: https://pu2clr.github.io/SI4735/
PU2CLR Si47XX API documentation: https://pu2clr.github.io/SI4735/extras/apidoc/html/
By Ricardo Lima Caratti, April 2021.
*/
#include <SI4735.h>
#include <EEPROM.h>
#include <Tiny4kOLED.h>
#include <font8x16atari.h> // Please, install the TinyOLED-Fonts library
#include "Rotary.h"
#include "patch_ssb_compressed.h" // Compressed SSB patch version (saving almost 1KB)
const uint16_t size_content = sizeof ssb_patch_content; // See ssb_patch_content.h
const uint16_t cmd_0x15_size = sizeof cmd_0x15; // Array of lines where the 0x15 command occurs in the patch content.
#define FM_BAND_TYPE 0
#define MW_BAND_TYPE 1
#define SW_BAND_TYPE 2
#define LW_BAND_TYPE 3
// OLED Diaplay constants
#define RST_PIN -1 // Define proper RST_PIN if required.
#define RESET_PIN 12
// Enconder PINs - if the clockwise and counterclockwise directions are not correct for you, please, invert this settings.
#define ENCODER_PIN_A 2
#define ENCODER_PIN_B 3
// Buttons controllers
#define MODE_SWITCH 4 // Switch MODE (Am/LSB/USB)
#define BANDWIDTH_BUTTON 5 // Used to select the banddwith.
#define VOLUME_BUTTON 6 // Volume Up
#define FREE_BUTTON1 7 // **** Use thi button to implement a new function
#define BAND_BUTTON 8 // Next band
#define FREE_BUTTON2 9 // **** Use thi button to implement a new function
#define AGC_BUTTON 11 // Switch AGC ON/OF
#define STEP_BUTTON 10 // Used to select the increment or decrement frequency step (see tabStep)
#define ENCODER_BUTTON 14 // Used to select the enconder control (BFO or VFO) and SEEK function on AM and FM modes
#define MIN_ELAPSED_TIME 100
#define MIN_ELAPSED_RSSI_TIME 150
#define DEFAULT_VOLUME 45 // change it for your favorite sound volume
#define FM 0
#define LSB 1
#define USB 2
#define AM 3
#define LW 4
#define SSB 1
#define STORE_TIME 10000 // Time of inactivity to make the current receiver status writable (10s / 10000 milliseconds).
const uint8_t app_id = 41; // Useful to check the EEPROM content before processing useful data
const int eeprom_address = 0;
long storeTime = millis();
const char *bandModeDesc[] = {"FM ", "LSB", "USB", "AM "};
uint8_t currentMode = FM;
uint8_t seekDirection = 1;
bool bfoOn = false;
bool ssbLoaded = false;
bool fmStereo = true;
bool cmdVolume = false; // if true, the encoder will control the volume.
bool cmdAgcAtt = false; // if true, the encoder will control the AGC / Attenuation
bool cmdStep = false; // if true, the encoder will control the step frequency
bool cmdBw = false; // if true, the encoder will control the bandwidth
bool cmdBand = false; // if true, the encoder will control the band
long countRSSI = 0;
int currentBFO = 0;
long elapsedRSSI = millis();
long elapsedButton = millis();
// Encoder control variables
volatile int encoderCount = 0;
// Some variables to check the SI4735 status
uint16_t currentFrequency;
uint16_t previousFrequency;
// uint8_t currentStep = 1;
uint8_t currentBFOStep = 25;
// Datatype to deal with bandwidth on AM, SSB and FM in numerical order.
// Ordering by bandwidth values.
typedef struct
{
uint8_t idx; // SI473X device bandwidth index value
const char *desc; // bandwidth description
} Bandwidth;
int8_t bwIdxSSB = 4;
Bandwidth bandwidthSSB[] = {
{4, "0.5"}, // 0
{5, "1.0"}, // 1
{0, "1.2"}, // 2
{1, "2.2"}, // 3
{2, "3.0"}, // 4 - default
{3, "4.0"} // 5
}; // 3 = 4kHz
int8_t bwIdxAM = 4;
const int maxFilterAM = 6;
Bandwidth bandwidthAM[] = {
{4, "1.0"}, // 0
{5, "1.8"}, // 1
{3, "2.0"}, // 2
{6, "2.5"}, // 3
{2, "3.0"}, // 4 - default
{1, "4.0"}, // 5
{0, "6.0"} // 6
};
int8_t bwIdxFM = 0;
Bandwidth bandwidthFM[] = {
{0, "AUT"}, // Automatic - default
{1, "110"}, // Force wide (110 kHz) channel filter.
{2, " 84"},
{3, " 60"},
{4, " 40"}};
// Atenuação and AGC
int8_t agcIdx = 0;
uint8_t disableAgc = 0;
uint8_t agcNdx = 0;
int tabStep[] = {1, // 0
5, // 1
9, // 2
10, // 3
50, // 4
100}; // 5
const int lastStep = (sizeof tabStep / sizeof(int)) - 1;
int idxStep = 3;
/*
Band data structure
*/
typedef struct
{
uint8_t bandType; // Band type (FM, MW or SW)
uint16_t minimumFreq; // Minimum frequency of the band
uint16_t maximumFreq; // maximum frequency of the band
uint16_t currentFreq; // Default frequency or current frequency
uint16_t currentStepIdx; // Idex of tabStep: Defeult frequency step (See tabStep)
int8_t bandwidthIdx; // Index of the table bandwidthFM, bandwidthAM or bandwidthSSB;
} Band;
/*
Band table
To add a new band, all you have to do is insert a new line in the table below. No extra code will be needed.
Remove or comment a line if you do not want a given band
You have to RESET the eeprom after modiging this table.
Turn your receiver on with the encoder push button pressed at first time to RESET the eeprom content.
*/
Band band[] = {
{FM_BAND_TYPE, 6400, 8400, 7000, 3, 0}, // FM from 64 to 84 MHz
{FM_BAND_TYPE, 8400, 10800, 10570, 3, 0},
{LW_BAND_TYPE, 100, 510, 300, 0, 4},
{MW_BAND_TYPE, 520, 1720, 810, 3, 4},
{MW_BAND_TYPE, 531, 1701, 783, 2, 4}, // MW for Europe, Africa and Asia
{SW_BAND_TYPE, 1800, 3500, 1900, 0, 4}, // 160 meters
{SW_BAND_TYPE, 3500, 4500, 3700, 0, 5}, // 80 meters
{SW_BAND_TYPE, 4500, 5500, 4850, 1, 4},
{SW_BAND_TYPE, 5600, 6300, 6000, 1, 4},
{SW_BAND_TYPE, 6800, 7800, 7200, 1, 4}, // 40 meters
{SW_BAND_TYPE, 9200, 10000, 9600, 1, 4},
{SW_BAND_TYPE, 10000, 11000, 10100, 0, 4}, // 30 meters
{SW_BAND_TYPE, 11200, 12500, 11940, 1, 4},
{SW_BAND_TYPE, 13400, 13900, 13600, 1, 4},
{SW_BAND_TYPE, 14000, 14500, 14200, 0, 4}, // 20 meters
{SW_BAND_TYPE, 15000, 15900, 15300, 1, 4},
{SW_BAND_TYPE, 17200, 17900, 17600, 1, 4},
{SW_BAND_TYPE, 18000, 18300, 18100, 0, 4}, // 17 meters
{SW_BAND_TYPE, 21000, 21900, 21200, 0, 4}, // 15 mters
{SW_BAND_TYPE, 24890, 26200, 24940, 0, 4}, // 12 meters
{SW_BAND_TYPE, 26200, 27900, 27500, 0, 4}, // CB band (11 meters)
{SW_BAND_TYPE, 28000, 30000, 28400, 0, 4} // 10 meters
};
const int lastBand = (sizeof band / sizeof(Band)) - 1;
int bandIdx = 1;
uint8_t rssi = 0;
uint8_t stereo = 1;
uint8_t volume = DEFAULT_VOLUME;
// Devices class declarations
Rotary encoder = Rotary(ENCODER_PIN_A, ENCODER_PIN_B);
SI4735 si4735;
void setup()
{
// Encoder pins
pinMode(ENCODER_PIN_A, INPUT_PULLUP);
pinMode(ENCODER_PIN_B, INPUT_PULLUP);
pinMode(BANDWIDTH_BUTTON, INPUT_PULLUP);
pinMode(BAND_BUTTON, INPUT_PULLUP);
pinMode(FREE_BUTTON2, INPUT_PULLUP);
pinMode(VOLUME_BUTTON, INPUT_PULLUP);
pinMode(FREE_BUTTON1, INPUT_PULLUP);
pinMode(ENCODER_BUTTON, INPUT_PULLUP);
pinMode(AGC_BUTTON, INPUT_PULLUP);
pinMode(STEP_BUTTON, INPUT_PULLUP);
pinMode(MODE_SWITCH, INPUT_PULLUP);
oled.begin();
oled.clear();
oled.on();
oled.setFont(FONT6X8);
// Splash - Change it for your introduction text.
oled.setCursor(40, 0);
oled.print("SI473X");
oled.setCursor(20, 1);
oled.print("Arduino Library");
delay(500);
oled.setCursor(15, 2);
oled.print("All in One Radio");
delay(500);
oled.setCursor(10, 3);
oled.print("V3.0.7 - By PU2CLR");
delay(1000);
// end Splash
// If you want to reset the eeprom, keep the VOLUME_UP button pressed during statup
if (digitalRead(ENCODER_BUTTON) == LOW)
{
oled.clear();
EEPROM.write(eeprom_address, 0);
oled.setCursor(0, 0);
oled.print("EEPROM RESETED");
delay(2000);
oled.clear();
}
delay(2000);
// end Splash
// Encoder interrupt
attachInterrupt(digitalPinToInterrupt(ENCODER_PIN_A), rotaryEncoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(ENCODER_PIN_B), rotaryEncoder, CHANGE);
si4735.getDeviceI2CAddress(RESET_PIN); // Looks for the I2C bus address and set it. Returns 0 if error
si4735.setup(RESET_PIN, MW_BAND_TYPE); //
delay(300);
// Checking the EEPROM content
if (EEPROM.read(eeprom_address) == app_id)
{
readAllReceiverInformation();
}
// Set up the radio for the current band (see index table variable bandIdx )
useBand();
currentFrequency = previousFrequency = si4735.getFrequency();
si4735.setVolume(volume);
oled.clear();
showStatus();
}
// Use Rotary.h and Rotary.cpp implementation to process encoder via interrupt
void rotaryEncoder()
{ // rotary encoder events
uint8_t encoderStatus = encoder.process();
if (encoderStatus)
{
if (encoderStatus == DIR_CW)
{
encoderCount = 1;
}
else
{
encoderCount = -1;
}
}
}
/*
writes the conrrent receiver information into the eeprom.
The EEPROM.update avoid write the same data in the same memory position. It will save unnecessary recording.
*/
void saveAllReceiverInformation()
{
int addr_offset;
EEPROM.update(eeprom_address, app_id); // stores the app id;
EEPROM.update(eeprom_address + 1, si4735.getVolume()); // stores the current Volume
EEPROM.update(eeprom_address + 2, bandIdx); // Stores the current band
EEPROM.update(eeprom_address + 3, currentMode); // Stores the current Mode (FM / AM / SSB)
EEPROM.update(eeprom_address + 4, currentBFO >> 8);
EEPROM.update(eeprom_address + 5, currentBFO & 0XFF);
addr_offset = 6;
band[bandIdx].currentFreq = currentFrequency;
for (int i = 0; i < lastBand; i++)
{
EEPROM.update(addr_offset++, (band[i].currentFreq >> 8)); // stores the current Frequency HIGH byte for the band
EEPROM.update(addr_offset++, (band[i].currentFreq & 0xFF)); // stores the current Frequency LOW byte for the band
EEPROM.update(addr_offset++, band[i].currentStepIdx); // Stores current step of the band
EEPROM.update(addr_offset++, band[i].bandwidthIdx); // table index (direct position) of bandwidth
}
}
/**
* reads the last receiver status from eeprom.
*/
void readAllReceiverInformation()
{
int addr_offset;
int bwIdx;
volume = EEPROM.read(eeprom_address + 1); // Gets the stored volume;
bandIdx = EEPROM.read(eeprom_address + 2);
currentMode = EEPROM.read(eeprom_address + 3);
currentBFO = EEPROM.read(eeprom_address + 4) << 8;
currentBFO |= EEPROM.read(eeprom_address + 5);
addr_offset = 6;
for (int i = 0; i < lastBand; i++)
{
band[i].currentFreq = EEPROM.read(addr_offset++) << 8;
band[i].currentFreq |= EEPROM.read(addr_offset++);
band[i].currentStepIdx = EEPROM.read(addr_offset++);
band[i].bandwidthIdx = EEPROM.read(addr_offset++);
}
previousFrequency = currentFrequency = band[bandIdx].currentFreq;
idxStep = tabStep[band[bandIdx].currentStepIdx];
bwIdx = band[bandIdx].bandwidthIdx;
if (currentMode == LSB || currentMode == USB)
{
loadSSB();
bwIdxSSB = (bwIdx > 5) ? 5 : bwIdx;
si4735.setSSBAudioBandwidth(bandwidthSSB[bwIdxSSB].idx);
// If audio bandwidth selected is about 2 kHz or below, it is recommended to set Sideband Cutoff Filter to 0.
if (bandwidthSSB[bwIdxSSB].idx == 0 || bandwidthSSB[bwIdxSSB].idx == 4 || bandwidthSSB[bwIdxSSB].idx == 5)
si4735.setSBBSidebandCutoffFilter(0);
else
si4735.setSBBSidebandCutoffFilter(1);
}
else if (currentMode == AM)
{
bwIdxAM = bwIdx;
si4735.setBandwidth(bandwidthAM[bwIdxAM].idx, 1);
}
else
{
bwIdxFM = bwIdx;
si4735.setFmBandwidth(bandwidthFM[bwIdxFM].idx);
}
}
/*
* To store any change into the EEPROM, it is needed at least STORE_TIME milliseconds of inactivity.
*/
void resetEepromDelay()
{
storeTime = millis();
previousFrequency = 0;
}
/**
* Converts a number to a char string and places leading zeros.
* It is useful to mitigate memory space used by sprintf or generic similar function
*
* value - value to be converted
* strValue - the value will be receive the value converted
* len - final string size (in bytes)
* dot - the decimal or tousand separator position
* separator - symbol "." or ","
*/
void convertToChar(uint16_t value, char *strValue, uint8_t len, uint8_t dot, uint8_t separator)
{
char d;
for (int i = (len - 1); i >= 0; i--)
{
d = value % 10;
value = value / 10;
strValue[i] = d + 48;
}
strValue[len] = '\0';
if (dot > 0)
{
for (int i = len; i >= dot; i--)
{
strValue[i + 1] = strValue[i];
}
strValue[dot] = separator;
}
if (strValue[0] == '0')
{
strValue[0] = ' ';
if (strValue[1] == '0')
strValue[1] = ' ';
}
}
/**
Show current frequency
*/
void showFrequency()
{
char *unit;
char freqDisplay[10];
if (band[bandIdx].bandType == FM_BAND_TYPE)
{
convertToChar(currentFrequency, freqDisplay, 5, 3, ',');
unit = (char *)"MHz";
}
else
{
unit = (char *)"kHz";
if (band[bandIdx].bandType == MW_BAND_TYPE || band[bandIdx].bandType == LW_BAND_TYPE)
convertToChar(currentFrequency, freqDisplay, 5, 0, '.');
else
convertToChar(currentFrequency, freqDisplay, 5, 2, ',');
}
oled.invertOutput(bfoOn);
oled.setFont(FONT8X16ATARI);
oled.setCursor(34, 0);
oled.print(" ");
oled.setCursor(34, 0);
oled.print(freqDisplay);
oled.setFont(FONT6X8);
oled.invertOutput(false);
oled.setCursor(95, 0);
oled.print(unit);
}
/**
This function is called by the seek function process.
*/
void showFrequencySeek(uint16_t freq)
{
currentFrequency = freq;
showFrequency();
}
/**
Checks the stop seeking criterias.
Returns true if the user press the touch or rotates the encoder during the seek process.
*/
bool checkStopSeeking()
{
// Checks the touch and encoder
return (bool)encoderCount || (digitalRead(ENCODER_BUTTON) == LOW); // returns true if the user rotates the encoder or press the push button
}
/**
Shows some basic information on display
*/
void showStatus()
{
showFrequency();
showBandDesc();
showStep();
showBandwidth();
showAgcAtt();
showRSSI();
showVolume();
}
/**
* Shows band information
*/
void showBandDesc()
{
char *bandMode;
if (currentFrequency < 520)
bandMode = (char *)"LW ";
else
bandMode = (char *)bandModeDesc[currentMode];
oled.setCursor(0, 0);
oled.print(" ");
oled.setCursor(0, 0);
oled.invertOutput(cmdBand);
oled.print(bandMode);
oled.invertOutput(false);
}
/* *******************************
Shows RSSI status
*/
void showRSSI()
{
int bars = (rssi / 20.0) + 1;
oled.setCursor(90, 3);
oled.print(" ");
oled.setCursor(90, 3);
oled.print(".");
for (int i = 0; i < bars; i++)
oled.print('_');
oled.print('|');
if (currentMode == FM)
{
oled.setCursor(18, 0);
oled.print(" ");
oled.setCursor(18, 0);
oled.invertOutput(true);
if (si4735.getCurrentPilot())
{
oled.invertOutput(true);
oled.print("s");
}
oled.invertOutput(false);
}
}
/*
Shows the volume level on LCD
*/
void showVolume()
{
oled.setCursor(58, 3);
oled.print(" ");
oled.setCursor(58, 3);
oled.invertOutput(cmdVolume);
oled.print(' ');
oled.invertOutput(false);
oled.print(si4735.getCurrentVolume());
}
void showStep()
{
if (bfoOn)
return;
oled.setCursor(93, 1);
oled.print(" ");
oled.setCursor(93, 1);
oled.invertOutput(cmdStep);
oled.print("S:");
oled.invertOutput(false);
oled.print(tabStep[idxStep]);
}
/**
Shows bandwidth on AM,SSB and FM mode
*/
void showBandwidth()
{
char *bw;
if (currentMode == LSB || currentMode == USB)
{
bw = (char *)bandwidthSSB[bwIdxSSB].desc;
showBFO();
}
else if (currentMode == AM)
{
bw = (char *)bandwidthAM[bwIdxAM].desc;
}
else
{
bw = (char *)bandwidthFM[bwIdxFM].desc;
}
oled.setCursor(0, 3);
oled.print(" ");
oled.setCursor(0, 3);
oled.invertOutput(cmdBw);
oled.print("BW: ");
oled.invertOutput(false);
oled.print(bw);
}
/*
* Shows AGCC and Attenuation
*/
void showAgcAtt()
{
// Show AGC Information
oled.setCursor(0, 1);
oled.print(" ");
oled.setCursor(0, 1);
oled.invertOutput(cmdAgcAtt);
if (agcIdx == 0)
{
oled.print("AGC");
}
else
{
oled.print("At");
oled.print(agcNdx);
}
oled.invertOutput(false);
}
/*
Shows the BFO current status.
Must be called only on SSB mode (LSB or USB)
*/
void showBFO()
{
oled.setCursor(0, 2);
oled.print(" ");
oled.setCursor(0, 2);
oled.print("BFO: ");
oled.print(currentBFO);
oled.print("Hz ");
oled.setCursor(93, 2);
oled.print(" ");
oled.setCursor(93, 2);
oled.invertOutput(cmdStep);
oled.print("S:");
oled.invertOutput(false);
oled.print(currentBFOStep);
}
char *stationName;
char bufferStatioName[20];
long rdsElapsed = millis();
char oldBuffer[15];
/*
* Clean the content of the third line (line 2 - remember the first line is 0)
*/
void cleanBfoRdsInfo()
{
oled.setCursor(0, 2);
oled.print(" ");
}
/*
* Show the Station Name.
*/
void showRDSStation()
{
char *po, *pc;
int col = 0;
po = oldBuffer;
pc = stationName;
while (*pc)
{
if (*po != *pc)
{
oled.setCursor(col, 2);
oled.print(*pc);
}
*po = *pc;
po++;
pc++;
col += 10;
}
// strcpy(oldBuffer, stationName);
delay(100);
}
/*
* Checks the station name is available
*/
void checkRDS()
{
si4735.getRdsStatus();
if (si4735.getRdsReceived())
{
if (si4735.getRdsSync() && si4735.getRdsSyncFound() && !si4735.getRdsSyncLost() && !si4735.getGroupLost())
{
stationName = si4735.getRdsText0A();
if (stationName != NULL /* && si4735.getEndGroupB() && (millis() - rdsElapsed) > 10 */)
{
showRDSStation();
// si4735.resetEndGroupB();
rdsElapsed = millis();
}
}
}
}
/*
Goes to the next band (see Band table)
*/
void bandUp()
{
// save the current frequency for the band
band[bandIdx].currentFreq = currentFrequency;
band[bandIdx].currentStepIdx = idxStep; // currentStep;
if (bandIdx < lastBand)
{
bandIdx++;
}
else
{
bandIdx = 0;
}
useBand();
}
/*
Goes to the previous band (see Band table)
*/
void bandDown()
{
// save the current frequency for the band
band[bandIdx].currentFreq = currentFrequency;
band[bandIdx].currentStepIdx = idxStep;
if (bandIdx > 0)
{
bandIdx--;
}
else
{
bandIdx = lastBand;
}
useBand();
}
/*
This function loads the contents of the ssb_patch_content array into the CI (Si4735) and starts the radio on
SSB mode.
*/
void loadSSB()
{
oled.setCursor(0, 2);
oled.print(" Switching to SSB ");
// si4735.setI2CFastModeCustom(850000); // It is working. Faster, but I'm not sure if it is safe.
si4735.setI2CFastModeCustom(500000);
si4735.queryLibraryId(); // Is it really necessary here? I will check it.
si4735.patchPowerUp();
delay(50);
si4735.downloadCompressedPatch(ssb_patch_content, size_content, cmd_0x15, cmd_0x15_size);
si4735.setSSBConfig(bandwidthSSB[bwIdxSSB].idx, 1, 0, 1, 0, 1);
si4735.setI2CStandardMode();
ssbLoaded = true;
// oled.clear();
cleanBfoRdsInfo();
}
/*
Switch the radio to current band.
The bandIdx variable points to the current band.
This function change to the band referenced by bandIdx (see table band).
*/
void useBand()
{
cleanBfoRdsInfo();
if (band[bandIdx].bandType == FM_BAND_TYPE)
{
currentMode = FM;
si4735.setTuneFrequencyAntennaCapacitor(0);
si4735.setFM(band[bandIdx].minimumFreq, band[bandIdx].maximumFreq, band[bandIdx].currentFreq, tabStep[band[bandIdx].currentStepIdx]);
si4735.setSeekFmLimits(band[bandIdx].minimumFreq, band[bandIdx].maximumFreq);
si4735.setSeekFmSpacing(1);
bfoOn = ssbLoaded = false;
si4735.setRdsConfig(1, 2, 2, 2, 2);
si4735.setFifoCount(1);
bwIdxFM = band[bandIdx].bandwidthIdx;
si4735.setFmBandwidth(bandwidthFM[bwIdxFM].idx);
}
else
{
if (band[bandIdx].bandType == MW_BAND_TYPE || band[bandIdx].bandType == LW_BAND_TYPE)
si4735.setTuneFrequencyAntennaCapacitor(0);
else
si4735.setTuneFrequencyAntennaCapacitor(1);
if (ssbLoaded)
{
si4735.setSSB(band[bandIdx].minimumFreq, band[bandIdx].maximumFreq, band[bandIdx].currentFreq, tabStep[band[bandIdx].currentStepIdx], currentMode);
si4735.setSSBAutomaticVolumeControl(1);
si4735.setSsbSoftMuteMaxAttenuation(0); // Disable Soft Mute for SSB
bwIdxSSB = band[bandIdx].bandwidthIdx;
si4735.setSSBAudioBandwidth(bandwidthSSB[bwIdxSSB].idx);
si4735.setSSBBfo(currentBFO);
}
else
{
currentMode = AM;
si4735.setAM(band[bandIdx].minimumFreq, band[bandIdx].maximumFreq, band[bandIdx].currentFreq, tabStep[band[bandIdx].currentStepIdx]);
si4735.setAutomaticGainControl(disableAgc, agcNdx);
si4735.setAmSoftMuteMaxAttenuation(8); // // Disable Soft Mute for AM
bwIdxAM = band[bandIdx].bandwidthIdx;
si4735.setBandwidth(bandwidthAM[bwIdxAM].idx, 1);
bfoOn = false;
}
si4735.setSeekAmLimits(band[bandIdx].minimumFreq, band[bandIdx].maximumFreq); // Consider the range all defined current band
si4735.setSeekAmSpacing((tabStep[band[bandIdx].currentStepIdx] > 10) ? 10 : tabStep[band[bandIdx].currentStepIdx]); // Max 10kHz for spacing
}
delay(100);
currentFrequency = band[bandIdx].currentFreq;
idxStep = band[bandIdx].currentStepIdx;
showStatus();
resetEepromDelay();
}
/**
* Changes the step frequency value based on encoder rotation
*/
void doStep(int8_t v)
{
// This command should work only for SSB mode
if ((currentMode == LSB || currentMode == USB) && bfoOn)
{
currentBFOStep = (currentBFOStep == 25) ? 10 : 25;
showBFO();
}
else
{
idxStep = (v == 1) ? idxStep + 1 : idxStep - 1;
if (idxStep > lastStep)
idxStep = 0;
else if (idxStep < 0)
idxStep = lastStep;
si4735.setFrequencyStep(tabStep[idxStep]);
band[bandIdx].currentStepIdx = idxStep;
si4735.setSeekAmSpacing((tabStep[idxStep] > 10) ? 10 : tabStep[idxStep]); // Max 10kHz for spacing
showStep();
}
delay(MIN_ELAPSED_TIME); // waits a little more for releasing the button.
}
/**
* Changes the volume based on encoder rotation
*/
void doVolume(int8_t v)
{
if (v == 1)
si4735.volumeUp();
else
si4735.volumeDown();
showVolume();
delay(MIN_ELAPSED_TIME); // waits a little more for releasing the button.
}
/**
* Switches the AGC/Attenuation based on encoder rotation
*/
void doAgcAtt(int8_t v)
{
agcIdx = (v == 1) ? agcIdx + 1 : agcIdx - 1;
if (agcIdx < 0)
agcIdx = 37;
else if (agcIdx > 37)
agcIdx = 0;
disableAgc = (agcIdx > 0); // if true, disable AGC; esle, AGC is enable
if (agcIdx > 1)
agcNdx = agcIdx - 1;
else
agcNdx = 0;
// Sets AGC on/off and gain
si4735.setAutomaticGainControl(disableAgc, agcNdx);
showAgcAtt();
delay(MIN_ELAPSED_TIME); // waits a little more for releasing the button.
}
/**
* Switches the bandwidth based on encoder rotation
*/
void doBandwidth(uint8_t v)
{
if (currentMode == LSB || currentMode == USB)
{
bwIdxSSB = (v == 1) ? bwIdxSSB + 1 : bwIdxSSB - 1;
if (bwIdxSSB > 5)
bwIdxSSB = 0;
else if (bwIdxSSB < 0)
bwIdxSSB = 5;
band[bandIdx].bandwidthIdx = bwIdxSSB;
si4735.setSSBAudioBandwidth(bandwidthSSB[bwIdxSSB].idx);
// If audio bandwidth selected is about 2 kHz or below, it is recommended to set Sideband Cutoff Filter to 0.
if (bandwidthSSB[bwIdxSSB].idx == 0 || bandwidthSSB[bwIdxSSB].idx == 4 || bandwidthSSB[bwIdxSSB].idx == 5)
si4735.setSBBSidebandCutoffFilter(0);
else
si4735.setSBBSidebandCutoffFilter(1);
}
else if (currentMode == AM)
{
bwIdxAM = (v == 1) ? bwIdxAM + 1 : bwIdxAM - 1;
if (bwIdxAM > maxFilterAM)
bwIdxAM = 0;
else if (bwIdxAM < 0)
bwIdxAM = maxFilterAM;
band[bandIdx].bandwidthIdx = bwIdxAM;
si4735.setBandwidth(bandwidthAM[bwIdxAM].idx, 1);
}
else
{
bwIdxFM = (v == 1) ? bwIdxFM + 1 : bwIdxFM - 1;
if (bwIdxFM > 4)
bwIdxFM = 0;
else if (bwIdxFM < 0)
bwIdxFM = 4;
band[bandIdx].bandwidthIdx = bwIdxFM;
si4735.setFmBandwidth(bandwidthFM[bwIdxFM].idx);
}
showBandwidth();
delay(MIN_ELAPSED_TIME); // waits a little more for releasing the button.
}
/**
* disble command buttons and keep the current status of the last command button pressed
*/
void disableCommand(bool *b, bool value, void (*showFunction)())
{
cmdVolume = false;
cmdAgcAtt = false;
cmdStep = false;
cmdBw = false;
cmdBand = false;
showVolume();
showStep();
showAgcAtt();
showBandwidth();
showBandDesc();
if (b != NULL) // rescues the last status of the last command only the parameter is not null
*b = value;
if (showFunction != NULL) // show the desired status only if it is necessary.
showFunction();
elapsedRSSI = millis();
countRSSI = 0;
}
void loop()
{
// Check if the encoder has moved.
if (encoderCount != 0)
{
if (cmdVolume)
doVolume(encoderCount);
else if (cmdAgcAtt)
doAgcAtt(encoderCount);
else if (cmdStep)
doStep(encoderCount);
else if (cmdBw)
doBandwidth(encoderCount);
else if (cmdBand)
{
if (encoderCount == 1)
bandUp();
else
bandDown();
}
else if (bfoOn)
{
currentBFO = (encoderCount == 1) ? (currentBFO + currentBFOStep) : (currentBFO - currentBFOStep);
si4735.setSSBBfo(currentBFO);
previousFrequency = 0; // Forces eeprom update
showBFO();
}
else
{
if (encoderCount == 1)
{
si4735.frequencyUp();
seekDirection = 1;
}
else
{
si4735.frequencyDown();
seekDirection = 0;
}
// Show the current frequency only if it has changed
currentFrequency = si4735.getFrequency();
showFrequency();
}
encoderCount = 0;
resetEepromDelay(); // if you moved the encoder, something was changed
elapsedRSSI = millis();
countRSSI = 0;
}
// Check button commands
if ((millis() - elapsedButton) > MIN_ELAPSED_TIME)
{
// check if some button is pressed
if (digitalRead(BANDWIDTH_BUTTON) == LOW)
{
cmdBw = !cmdBw;
disableCommand(&cmdBw, cmdBw, showBandwidth);
delay(MIN_ELAPSED_TIME); // waits a little more for releasing the button.
}
else if (digitalRead(BAND_BUTTON) == LOW)
{
cmdBand = !cmdBand;
disableCommand(&cmdBand, cmdBand, showBandDesc);
delay(MIN_ELAPSED_TIME); // waits a little more for releasing the button.
}
else if (digitalRead(FREE_BUTTON2) == LOW)
{
// available to add other function
showStatus();
}
else if (digitalRead(VOLUME_BUTTON) == LOW)
{
cmdVolume = !cmdVolume;
disableCommand(&cmdVolume, cmdVolume, showVolume);
delay(MIN_ELAPSED_TIME); // waits a little more for releasing the button.
}
else if (digitalRead(FREE_BUTTON1) == LOW)
{
// available to add other function
showStatus();
}
else if (digitalRead(ENCODER_BUTTON) == LOW)
{
if (currentMode == LSB || currentMode == USB)
{
bfoOn = !bfoOn;
if (bfoOn)
showBFO();
showStatus();
disableCommand(NULL, false, NULL); // disable all command buttons
}
else if (currentMode == FM || currentMode == AM)
{
// Jumps up or down one space
if (seekDirection)
si4735.frequencyUp();
else
si4735.frequencyDown();
si4735.seekStationProgress(showFrequencySeek, checkStopSeeking, seekDirection);
delay(30);
if (currentMode == FM)
{
float f = round(si4735.getFrequency() / 10.0);
currentFrequency = (uint16_t)f * 10; // adjusts band space from 1 (10kHz) to 10 (100 kHz)
si4735.setFrequency(currentFrequency);
}
else
{
currentFrequency = si4735.getFrequency(); //
}
showFrequency();
}
delay(MIN_ELAPSED_TIME); // waits a little more for releasing the button.
}
else if (digitalRead(AGC_BUTTON) == LOW)
{
cmdAgcAtt = !cmdAgcAtt;
disableCommand(&cmdAgcAtt, cmdAgcAtt, showAgcAtt);
delay(MIN_ELAPSED_TIME); // waits a little more for releasing the button.
}
else if (digitalRead(STEP_BUTTON) == LOW)
{
if (currentMode != FM)
{
cmdStep = !cmdStep;
disableCommand(&cmdStep, cmdStep, showStep);
}
delay(MIN_ELAPSED_TIME); // waits a little more for releasing the button.
}
else if (digitalRead(MODE_SWITCH) == LOW)
{
if (currentMode != FM)
{
if (currentMode == AM)
{
// If you were in AM mode, it is necessary to load SSB patch (avery time)
loadSSB();
currentMode = LSB;
}
else if (currentMode == LSB)
{
currentMode = USB;
}
else if (currentMode == USB)
{
currentMode = AM;
ssbLoaded = false;
bfoOn = false;
}
// Nothing to do if you are in FM mode
band[bandIdx].currentFreq = currentFrequency;
band[bandIdx].currentStepIdx = idxStep;
useBand();
}
}
elapsedButton = millis();
}
// Show RSSI status only if this condition has changed
if ((millis() - elapsedRSSI) > MIN_ELAPSED_RSSI_TIME * 9)
{
si4735.getCurrentReceivedSignalQuality();
int aux = si4735.getCurrentRSSI();
if (rssi != aux)
{
rssi = aux;
showRSSI();
}
if (countRSSI++ > 3)
{
disableCommand(NULL, false, NULL); // disable all command buttons
countRSSI = 0;
}
elapsedRSSI = millis();
}
if (currentMode == FM)
{
if (currentFrequency != previousFrequency)
{
cleanBfoRdsInfo();
}
else
{
checkRDS();
}
}
// Show the current frequency only if it has changed
if (currentFrequency != previousFrequency)
{
if ((millis() - storeTime) > STORE_TIME)
{
saveAllReceiverInformation();
storeTime = millis();
previousFrequency = currentFrequency;
}
}
delay(10);
}
| [
"pu2clr@gmail.com"
] | pu2clr@gmail.com |
3c5b72b6b21b2e4a46305cb74e0b555f537e893b | 3f8f82eddb180b31f3793a0ef53f7cfa49b20bc4 | /mc521/placar3/Placar3_ExercicioI_RA122307.cpp | cf53bc83ff039ed627fdfc1615b71a2e4a9646bb | [] | no_license | italomg/Programming_Contests | d8391dbb3b609a4cd0f864cf21de56387a83fa05 | 207772a5c1c4036705769c01d0cda71ff9a8edc5 | refs/heads/master | 2021-01-01T03:57:29.997784 | 2016-05-16T23:32:55 | 2016-05-16T23:32:55 | 58,974,482 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,374 | cpp | #include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<string>
#include<cstring>
#include<cctype>
using namespace std;
int tamSeq,queries;
int freq[200005];
int inicPos[200005];
int seqInput[200005];
int sTree[1000000];
void montaArvore(int nodeNumber , int inic, int fim){
if(inic == fim) {
sTree[nodeNumber] = freq[seqInput[inic]];
return ;
}
int md = (inic + fim) / 2;
int n1 = (2 * nodeNumber) + 1;
int n2 = n1 + 1;
montaArvore(n1, inic , md) ;
montaArvore(n2, md + 1, fim);
if(sTree[n1] >= sTree[n2])
sTree[nodeNumber] = sTree[n1];
else
sTree[nodeNumber] = sTree[n2];
}
int makeQuery(int nodeNumber, int inic, int fim, int inic1, int fim2) {
int ret ;
if(fim < inic1 || inic > fim2)
return -1;
if(inic >= inic1 && fim <= fim2)
return sTree[nodeNumber];
int noesq = (2 * nodeNumber) + 1;
int nodir = (2 * nodeNumber) + 2;
int meio = (inic + fim) / 2;
int res1 = makeQuery(noesq, inic, meio , inic1, fim2);
int res2 = makeQuery(nodir, meio + 1, fim, inic1, fim2);
if(res1 == -1)
ret = res2;
if(res2 == -1)
ret = res1;
if(res1 >= res2)
ret = res1;
else
ret = res2;
return ret;
}
int main(){
int i;
while(scanf("%d", &tamSeq) == 1) {
if(tamSeq == 0)
break;
scanf("%d", &queries);
memset(freq, 0, sizeof(freq));
memset(inicPos, -1, sizeof(freq));
for(i = 0; i < tamSeq; i ++) {
scanf("%d", &seqInput[i]) ;
seqInput[i] += 100000;
freq[seqInput[i]] ++ ;
if(freq[seqInput[i]] == 1)
inicPos[seqInput[i]] = i;
}
montaArvore(0, 0, tamSeq - 1);
int nInp1,nInp2;
for(i = 0; i < queries; i ++) {
scanf("%d %d", &nInp1, &nInp2);
nInp1--;
nInp2--;
if(seqInput[nInp1] == seqInput[nInp2]) {
printf("%d\n", nInp2 - nInp1 + 1);
continue;
}
int resp ;
int op1 = freq[seqInput[nInp1]] - nInp1 + inicPos[seqInput [nInp1]];
int op2 = nInp2 - inicPos[seqInput[nInp2]] + 1;
if(op1 > op2)
resp = op1;
else
resp = op2;
int lim1 = inicPos[seqInput[nInp1]] + freq[seqInput[nInp1]] ;
int lim2 = inicPos[seqInput[nInp2]] - 1;
if(lim1 <= lim2) {
int var = makeQuery(0, 0, tamSeq - 1, lim1, lim2);
if(var > resp)
resp = var;
}
printf("%d\n", resp);
}
}
return 0;
}
| [
"italogmoraes@gmail.com"
] | italogmoraes@gmail.com |
cbd3d7c44773ff63bf1f319ef0287a042a91e203 | 7a3771e499a27f809434ea80c6b9710a678d7a02 | /UVa/10004Bicoloring.cpp | acd14500c512ddb71f1ee7dabdb46276ed5f80ad | [] | no_license | sunset1995/ACM_ICPC_prac | b00e9ccb36fe37fede78361267668233f0c201f2 | 22a7850dcc7a1d15e1fd6a6fe7e43251ca15db1b | refs/heads/master | 2021-01-19T02:49:27.177125 | 2016-06-18T13:12:55 | 2016-06-18T13:12:55 | 45,678,547 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 791 | cpp | #include<cstdio>
#include<list>
using namespace std;
int n,l;
list<int> node[210];
int color[210];
bool ok;
void dfs(int at,int c){
if( color[at] ){
if( color[at]!=c )
ok = false;
return;
}
color[at] = c;
list<int>::iterator it = node[at].begin();
while( it!=node[at].end() && ok ){
dfs( (*it) , -1*color[at] );
++it;
}
}
int main(){
while( scanf(" %d%d",&n,&l)!=EOF && n ){
ok = true;
for(int i=0;i<l;++i){
node[i].clear();
color[i] = 0;
}
for(int i=0;i<l;++i){
int a , b;
scanf(" %d%d",&a,&b);
node[a].push_back( b );
node[b].push_back( a );
}
dfs( 0 , 1 );
if( ok )
printf("BICOLORABLE.\n");
else
printf("NOT BICOLORABLE.\n");
}
}
| [
"s2821d3721@gmail.com"
] | s2821d3721@gmail.com |
fb0111b286d2fedefa48b2ef8d92bad809e30699 | 6ab52864add92269d2a7dbe499289f3a5522ae8d | /include/lightmetrica/accel3.h | 2e0963e4428374b050bc16822d64b4cf81f8aa24 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | jammm/lightmetrica-v2 | b778ae7fa8ffbde82614204852e37e4a7c9f5702 | 6864942ec48d37f2c35dc30a38a26d7cc4bb527e | refs/heads/master | 2022-12-08T08:34:11.733982 | 2020-09-05T04:53:16 | 2020-09-05T04:53:16 | 292,744,217 | 0 | 0 | NOASSERTION | 2020-09-04T03:57:33 | 2020-09-04T03:57:32 | null | UTF-8 | C++ | false | false | 2,425 | h | /*
Lightmetrica - A modern, research-oriented renderer
Copyright (c) 2015 Hisanari Otsu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#pragma once
#include <lightmetrica/accel.h>
LM_NAMESPACE_BEGIN
struct Primitive;
struct Ray;
struct Intersection;
/*!
\brief An interface for the acceleration structure for 3-dimensional scenes.
\ingroup accel
*/
class Accel3 : public Accel
{
public:
LM_INTERFACE_CLASS(Accel3, Accel, 1);
public:
Accel3() = default;
LM_DISABLE_COPY_AND_MOVE(Accel3);
public:
/*!
\brief Intersection query with triangles.
The function checks if `ray` hits with the scene.
This function is supposed to be accelerated by spatial acceleration structure.
When intersected, information on the hit point is stored in the intersection data.
The intersection is valid only with the range of the distance between `minT` and `maxT`.
\param scene Scene.
\param ray Ray.
\param isect Intersection data.
\param minT Minimum range of the distance.
\param minT Maximum range of the distance.
\retval true Intersected with the scene.
\retval false Not intersected with the scene.
*/
LM_INTERFACE_F(0, Intersect, bool(const Scene* scene, const Ray& ray, Intersection& isect, Float minT, Float maxT));
};
LM_NAMESPACE_END
| [
"hi2p.perim@gmail.com"
] | hi2p.perim@gmail.com |
ede4b0f18e4551c2053064b9c87d26b410db0950 | 62408a02b44f2fd20c6d54e1f5def0184e69194c | /Gym/102219H/22172839_AC_15ms_40kB.cpp | 4fe4cbf25dc3ceb2ffc32f6e71f0c3beaaea5c05 | [] | no_license | benedicka/Competitive-Programming | 24eb90b8150aead5c13287b62d9dc860c4b9232e | a94ccfc2d726e239981d598e98d1aa538691fa47 | refs/heads/main | 2023-03-22T10:14:34.889913 | 2021-03-16T05:33:43 | 2021-03-16T05:33:43 | 348,212,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,167 | cpp | #include<bits/stdc++.h>
using namespace std;
struct point
{
double x,y;
};
bool cross(point a ,point b, point c)
{
double ax,ay,bx,by;
ax = a.x-b.x;
ay = a.y-b.y;
bx = c.x-b.x;
by = c.y-b.y;
if(ax*by-ay*bx > 0) return 1;
else return 0;
}
bool cmp(point a,point b)
{
return ((a.x<b.x) || (a.x == b.x && a.y<b.y));
}
vector < point > monotone_chain(vector < point > pts)
{
int sz = pts.size();
point cek1,cek2;
vector< point > res;
sort(pts.begin(), pts.end(),cmp);
stack < point > lh,uh;
uh.push(pts[0]);
cek1 = pts[0];
uh.push(pts[1]);
cek2 = pts[1];
for(int i=2;i<sz;i++)
{
while(uh.size()>2 && cross(cek1,cek2,pts[i]))
{
uh.pop();
cek2 = uh.top();
uh.pop();
cek1 = uh.top();
uh.push(cek2);
}
if(uh.size()<=2 && cross(cek1,cek2,pts[i]))
{
uh.pop();
}
cek1 = uh.top();
uh.push(pts[i]);
cek2 = pts[i];
}
lh.push(pts[sz-1]);
cek1 = pts[sz-1];
lh.push(pts[sz-2]);
cek2 = pts[sz-2];
for(int i=sz-3;i>=0;i--)
{
while(lh.size()>2 && cross(cek1,cek2,pts[i]))
{
lh.pop();
cek2 = lh.top();
lh.pop();
cek1 = lh.top();
lh.push(cek2);
}
if(lh.size()<=2 && cross(cek1,cek2,pts[i]))
{
lh.pop();
}
cek1 = lh.top();
lh.push(pts[i]);
cek2 = pts[i];
}
while(!lh.empty())
{
res.push_back(lh.top());
lh.pop();
}
uh.pop();
while(!uh.empty())
{
res.push_back(uh.top());
uh.pop();
}
reverse(res.begin(),res.end());
return res;
}
bool onSegment(point p, point q, point r)
{
if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) && q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y)) return 1;
return 0;
}
int orientation(point p, point q, point r)
{
double val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
if (val == 0.0) return 0; // colinear
return (val > 0.0)? 1: 2; // clock or counterclock wise
}
bool doIntersect(point p1, point q1, point p2, point q2)
{
int o1 = orientation(p1, q1, p2);
int o2 = orientation(p1, q1, q2);
int o3 = orientation(p2, q2, p1);
int o4 = orientation(p2, q2, q1);
if (o1 != o2 && o3 != o4) return 1;
if (o1 == 0 && onSegment(p1, p2, q1)) return 1;
if (o2 == 0 && onSegment(p1, q2, q1)) return 1;
if (o3 == 0 && onSegment(p2, p1, q2)) return 1;
if (o4 == 0 && onSegment(p2, q1, q2)) return 1;
return 0;
}
bool isInside(vector < point > polygon, point p)
{
polygon.push_back(p);
polygon = monotone_chain(polygon);
for(int i=0;i<polygon.size();i++)
{
if(p.x==polygon[i].x && p.y==polygon[i].y) return 0;
}
return 1;
}
int main()
{
int t,n,m,cnt;
vector < point > pts;
point pt;
double x1,x2,y1,y2;
scanf("%d",&t);
for(int tc=1;tc<=t;tc++)
{
if(tc>1) printf("\n");
pts.clear();
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++)
{
scanf("%lf %lf",&pt.x,&pt.y);
pts.push_back(pt);
}
pts = monotone_chain(pts);
printf("Case %d\n",tc);
for(int i=0;i<pts.size();i++)
{
printf("%.0lf %.0lf\n",pts[i].x,pts[i].y);
}
pts.resize(pts.size()-1);
for(int i=0;i<m;i++)
{
cnt = 0;
scanf("%lf %lf",&pt.x,&pt.y);
printf("%.0lf %.0lf %s\n",pt.x,pt.y,isInside(pts,pt)?"is unsafe!":"is safe!");
}
}
return 0;
} | [
"43498540+benedicka@users.noreply.github.com"
] | 43498540+benedicka@users.noreply.github.com |
6f885a02d2c16901b12e019e727efd0bc06eed57 | d09092dbe69c66e916d8dd76d677bc20776806fe | /.libs/puno_automatic_generated/inc/types/com/sun/star/configuration/backend/XLayerHandler.hpp | a2aa6947eaa118d2131d62bba428b9aec69d8e87 | [] | no_license | GXhua/puno | 026859fcbc7a509aa34ee857a3e64e99a4568020 | e2f8e7d645efbde5132b588678a04f70f1ae2e00 | refs/heads/master | 2020-03-22T07:35:46.570037 | 2018-07-11T02:19:26 | 2018-07-11T02:19:26 | 139,710,567 | 0 | 0 | null | 2018-07-04T11:03:58 | 2018-07-04T11:03:58 | null | UTF-8 | C++ | false | false | 1,630 | hpp | #ifndef INCLUDED_COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERHANDLER_HPP
#define INCLUDED_COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERHANDLER_HPP
#include "sal/config.h"
#include "com/sun/star/configuration/backend/XLayerHandler.hdl"
#include "com/sun/star/configuration/backend/TemplateIdentifier.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/Type.hxx"
#include "cppu/unotype.hxx"
#include "rtl/ustring.hxx"
#include "sal/types.h"
namespace com { namespace sun { namespace star { namespace configuration { namespace backend {
inline ::css::uno::Type const & cppu_detail_getUnoType(SAL_UNUSED_PARAMETER ::css::configuration::backend::XLayerHandler const *) {
static typelib_TypeDescriptionReference * the_type = 0;
if ( !the_type )
{
typelib_static_mi_interface_type_init( &the_type, "com.sun.star.configuration.backend.XLayerHandler", 0, 0 );
}
return * reinterpret_cast< ::css::uno::Type * >( &the_type );
}
} } } } }
SAL_DEPRECATED("use cppu::UnoType") inline ::css::uno::Type const & SAL_CALL getCppuType(SAL_UNUSED_PARAMETER ::css::uno::Reference< ::css::configuration::backend::XLayerHandler > const *) {
return ::cppu::UnoType< ::css::uno::Reference< ::css::configuration::backend::XLayerHandler > >::get();
}
::css::uno::Type const & ::css::configuration::backend::XLayerHandler::static_type(SAL_UNUSED_PARAMETER void *) {
return ::cppu::UnoType< ::css::configuration::backend::XLayerHandler >::get();
}
#endif // INCLUDED_COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERHANDLER_HPP
| [
"guoxinhua@10.10.12.142"
] | guoxinhua@10.10.12.142 |
c15f853c8e5889eeafa833cba674e80f9fb3ea57 | fda58bc787b9ded138a2bceacba4ce82078d38e9 | /Example/Pods/gRPC-Core/src/core/ext/filters/client_channel/backend_metric.cc | ceafa2903d61340eb134da301896315fd9b4a079 | [
"MIT",
"Apache-2.0"
] | permissive | vishal-i4gs/speechAssistant | c3436e06a45c5bc2531747fcd43616f0dc43f43b | 1bc3c8d6b7a49d82a05f92c07253981e75a8258b | refs/heads/master | 2022-11-28T22:04:19.412602 | 2020-08-19T06:24:51 | 2020-08-19T06:24:51 | 288,274,352 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,308 | cc | //
// Copyright 2019 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#include <grpc/support/port_platform.h>
#include "src/core/ext/filters/client_channel/backend_metric.h"
#include "absl/strings/string_view.h"
#if COCOAPODS==1
#include "src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.h"
#else
#include "udpa/data/orca/v1/orca_load_report.upb.h"
#endif
#include "src/core/lib/gprpp/map.h"
namespace grpc_core {
namespace {
template <typename EntryType>
std::map<absl::string_view, double, StringLess> ParseMap(
udpa_data_orca_v1_OrcaLoadReport* msg,
EntryType** (*entry_func)(udpa_data_orca_v1_OrcaLoadReport*, size_t*),
upb_strview (*key_func)(const EntryType*),
double (*value_func)(const EntryType*), Arena* arena) {
std::map<absl::string_view, double, StringLess> result;
size_t size;
const auto* const* entries = entry_func(msg, &size);
for (size_t i = 0; i < size; ++i) {
upb_strview key_view = key_func(entries[i]);
char* key = static_cast<char*>(arena->Alloc(key_view.size + 1));
memcpy(key, key_view.data, key_view.size);
result[absl::string_view(key, key_view.size)] = value_func(entries[i]);
}
return result;
}
} // namespace
const LoadBalancingPolicy::BackendMetricData* ParseBackendMetricData(
const grpc_slice& serialized_load_report, Arena* arena) {
upb::Arena upb_arena;
udpa_data_orca_v1_OrcaLoadReport* msg =
udpa_data_orca_v1_OrcaLoadReport_parse(
reinterpret_cast<const char*>(
GRPC_SLICE_START_PTR(serialized_load_report)),
GRPC_SLICE_LENGTH(serialized_load_report), upb_arena.ptr());
if (msg == nullptr) return nullptr;
LoadBalancingPolicy::BackendMetricData* backend_metric_data =
arena->New<LoadBalancingPolicy::BackendMetricData>();
backend_metric_data->cpu_utilization =
udpa_data_orca_v1_OrcaLoadReport_cpu_utilization(msg);
backend_metric_data->mem_utilization =
udpa_data_orca_v1_OrcaLoadReport_mem_utilization(msg);
backend_metric_data->requests_per_second =
udpa_data_orca_v1_OrcaLoadReport_rps(msg);
backend_metric_data->request_cost =
ParseMap<udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry>(
msg, udpa_data_orca_v1_OrcaLoadReport_mutable_request_cost,
udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_key,
udpa_data_orca_v1_OrcaLoadReport_RequestCostEntry_value, arena);
backend_metric_data->utilization =
ParseMap<udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry>(
msg, udpa_data_orca_v1_OrcaLoadReport_mutable_utilization,
udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_key,
udpa_data_orca_v1_OrcaLoadReport_UtilizationEntry_value, arena);
return backend_metric_data;
}
} // namespace grpc_core
| [
"vishal.i4gs@gmail.com"
] | vishal.i4gs@gmail.com |
7781d767ab25b78d8b653b3ebb6b612101fc7d23 | d45f1bfabc227148e8542a2830c4f5a943c95b9a | /RTK_UBLOX/ublox_base_logger/menu.ino | 3dd095d8b8c0da555756c2dbbf090673d8356fbd | [] | no_license | dewsl/dewsl_loggers | 4b7726e7c2e86f0749df1e747c0e433f197d8c5e | 052a132946fc8281bab7e4c73531f7a2ba10cdd7 | refs/heads/master | 2023-06-08T19:39:02.344580 | 2023-06-06T21:40:21 | 2023-06-06T21:40:21 | 92,142,128 | 0 | 3 | null | 2020-02-21T02:05:07 | 2017-05-23T07:21:34 | C++ | UTF-8 | C++ | false | false | 39,997 | ino | #define ATCMD "AT"
#define ATECMDTRUE "ATE"
#define ATECMDFALSE "ATE0"
#define OKSTR "OK"
#define ERRORSTR "ERROR"
bool ate = false;
void getAtcommand()
{
// wakeGSM();
String serial_line, command;
int i_equals = 0;
unsigned long startHere = millis();
bool timeToExit;
do
{
timeToExit = timeOutExit(startHere, DEBUGTIMEOUT);
serial_line = Serial.readStringUntil('\r\n');
} while (serial_line == "" && timeToExit == false);
serial_line.toUpperCase();
serial_line.replace("\r", "");
if (timeToExit)
{
Serial.println("Exit from debug menu");
debug_flag_exit = true;
}
// echo command if ate is set, default true
if (ate)
Serial.println(serial_line);
// get characters before '='
i_equals = serial_line.indexOf('=');
if (i_equals == -1)
command = serial_line;
else
command = serial_line.substring(0, i_equals);
if (command == ATCMD)
Serial.println(OKSTR);
else if (command == ATECMDTRUE)
{
ate = true;
Serial.println(OKSTR);
}
else if (command == ATECMDFALSE)
{
ate = false;
Serial.println(OKSTR);
}
else if (command == "A")
{
Serial.println("[0] Sending data using GSM only"); //arQ like function only
Serial.println("[1] Version 5 datalogger LoRa with GSM (arQ + LoRa)"); //arQ + LoRa rx
Serial.println("[2] LoRa transmitter for version 5 datalogger"); //TX LoRa
Serial.println("[3] Gateway Mode with only ONE LoRa transmitter");
Serial.println("[4] Gateway Mode with TWO LoRa transmitter");
Serial.println("[5] Gateway Mode with THREE LoRa transmitter");
Serial.println("[6] LoRa transmitter for Raspberry Pi"); //TX LoRa
Serial.println("[7] Sends sensor and rain gauge data via LoRa"); //TX LoRa
Serial.println("[8] LoRa dummy transmitter"); //TX LoRa
Serial.println("[9] GSM - Surficial Tilt");
Serial.println("[10] LoRa Tx - Surficial Tilt");
Serial.println("[11] Rain gauge mode only");
Serial.println("[12] Surficial Tilt Gateway - LoRa Rx");
if (get_logger_version() == 0)
{
//default arQ like sending
turn_ON_GSM(get_gsm_power_mode());
send_rain_data(0);
disable_watchdog();
get_Due_Data(1, get_serverNum_from_flashMem());
disable_watchdog();
turn_OFF_GSM(get_gsm_power_mode());
}
else if (get_logger_version() == 1)
{
//arQ + 1 LoRa receiver
if (gsmPwrStat)
{
turn_ON_GSM(get_gsm_power_mode());
}
get_Due_Data(1, get_serverNum_from_flashMem());
disable_watchdog();
send_rain_data(0);
disable_watchdog();
if (getSensorDataFlag == true && OperationFlag == true)
{
receive_lora_data(1);
disable_watchdog();
}
if (gsmPwrStat)
{
turn_OFF_GSM(get_gsm_power_mode());
}
}
else if (get_logger_version() == 2)
{
//LoRa transmitter of version 5 datalogger
get_Due_Data(2, get_serverNum_from_flashMem());
disable_watchdog();
}
else if (get_logger_version() == 3)
{
//only one trasmitter
turn_ON_GSM(get_gsm_power_mode());
send_rain_data(0);
disable_watchdog();
receive_lora_data(3);
disable_watchdog();
turn_OFF_GSM(get_gsm_power_mode());
}
else if (get_logger_version() == 4)
{
//Two transmitter
turn_ON_GSM(get_gsm_power_mode());
send_rain_data(0);
disable_watchdog();
receive_lora_data(4);
disable_watchdog();
turn_OFF_GSM(get_gsm_power_mode());
}
else if (get_logger_version() == 5)
{
// Three transmitter
turn_ON_GSM(get_gsm_power_mode());
send_rain_data(0);
disable_watchdog();
receive_lora_data(5);
disable_watchdog();
turn_OFF_GSM(get_gsm_power_mode());
}
else if (get_logger_version() == 6)
{
//default arabica LoRa transmitter
get_Due_Data(6, get_serverNum_from_flashMem());
disable_watchdog();
}
else if (get_logger_version() == 7)
{
// Sends rain gauge data via LoRa
get_Due_Data(0, get_serverNum_from_flashMem());
disable_watchdog();
delay_millis(1000);
send_rain_data(1);
disable_watchdog();
}
else if (get_logger_version() == 8)
{
// Sends rain gauge data via LoRa
get_Due_Data(0, get_serverNum_from_flashMem());
disable_watchdog();
delay_millis(1000);
send_thru_lora(dataToSend);
send_rain_data(1);
disable_watchdog();
}
else if (get_logger_version() == 9)
{
Serial.print("Datalogger verion: ");
Serial.println(get_logger_version());
// Sends IMU sensor data to GSM
/*
on_IMU();
turn_ON_GSM(get_gsm_power_mode());
send_rain_data(0);
disable_watchdog();
delay_millis(1000);
send_thru_gsm(read_IMU_data(get_calib_param()), get_serverNum_from_flashMem());
delay_millis(1000);
turn_OFF_GSM(get_gsm_power_mode());
off_IMU();
*/
}
else if (get_logger_version() == 10)
{
Serial.print("Datalogger verion: ");
Serial.println(get_logger_version());
// Sends IMU sensor data to LoRa
// send_thru_gsm(read_IMU_data(),get_serverNum_from_flashMem());
// on_IMU();
// print_data();
// read_IMU_data(0);
// send_thru_lora(read_IMU_data(get_calib_param()));
// delay_millis(1000);
// send_rain_data(1);
}
else if (get_logger_version() == 11)
{
Serial.print("Datalogger verion: ");
Serial.println(get_logger_version());
// Sends rain gauge data ONLY
turn_ON_GSM(get_gsm_power_mode());
send_rain_data(0);
disable_watchdog();
delay_millis(1000);
turn_OFF_GSM(get_gsm_power_mode());
}
else if (get_logger_version() == 12)
{
Serial.print("Datalogger verion: ");
Serial.println(get_logger_version());
disable_watchdog();
digitalWrite(LED_BUILTIN, HIGH);
do
{
read_lora_data_only(12);
} while (millis() - timer2 < LORATIMEOUTMODE3); //20 mins
digitalWrite(LED_BUILTIN, LOW);
enable_watchdog();
// turn_OFF_GSM(get_gsm_power_mode());
}
else if (get_logger_version() == 13)
{
Serial.print("Datalogger verion: ");
Serial.println(get_logger_version());
on_UBLOX();
disable_watchdog();
//kukunin yung rtcm data ng ilang uulit
for (int i = 0; i < MAX_RETRY_BASE; i++)
{
rtcm_len = ublox_get_rtcm();
Serial.print("rtcm length: ");
Serial.println(rtcm_len);
send_rtcm_to_rover(rtcm_len);
delay(100);
}
//send final string
rf95.send(final_string, 5);
rf95.waitPacketSent();
//get final data
// read_lora_data();
// Serial.println((char *)received_ublox);
// delay_millis(1000);
off_UBLOX();
}
//rover
else if (get_logger_version() == 14)
{
Serial.print("Datalogger verion: ");
Serial.println(get_logger_version());
on_UBLOX();
disable_watchdog();
long timer_base = millis();
do
{
len_total_rover = 0;
lastTime = millis();
do
{
len_rover = read_lora_data_rover(len_total_rover);
if (len_rover <= -1)
break;
len_total_rover = len_rover + len_total_rover;
} while (millis() - lastTime < 5000); //5 secs
if (len_rover == -2)
break;
// print_buf_total(len_total);
if (len_total_rover > 2)
{
//possible daw masira yung code pag laging nagstore sa flash, kaya every 4hrs lang sana
//pero wag na to haha
//rtcm_store_to_flash(len_total);
Serial.println("Serial write");
for (int i = 0; i < len_total_rover; i++)
{
Serial1.write(buf_total[i]);
}
}
} while (millis() - timer_base < 180000); //3 mins
Serial.println("Read Data");
read_ublox_data();
delay_millis(1000);
Serial.print("Sending data: ");
Serial.println(dataToSend);
send_thru_lora_rover(dataToSend);
delay_millis(1000);
off_UBLOX();
}
else
{
Serial.print("Datalogger verion: ");
Serial.println(get_logger_version());
}
Serial.println("* * * * * * * * * * * * * * * * * * * *");
}
else if (command == "B")
{
Serial.print("RTC temperature: ");
Serial.println(readTemp());
// Serial.println(readTempRTC());
// Serial.println(BatteryVoltage(get_logger_version()));
Serial.println("* * * * * * * * * * * * * * * * * * * *");
}
else if (command == "C")
{
printMenu();
}
else if (command == "D")
{
Serial.print("Alarm stored: ");
Serial.println(alarmFromFlashMem());
print_rtcInterval();
if (isChangeParam())
setAlarmInterval();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
Serial.readStringUntil('\r\n');
}
else if (command == "E")
{
Serial.println("Exiting debug mode!");
//real time clock alarm settings
setAlarmEvery30(alarmFromFlashMem());
delay_millis(75);
rtc.clearINTStatus(); // needed to re-trigger rtc
turn_OFF_GSM(get_gsm_power_mode());
Serial.println("* * * * * * * * * * * * * * * * * * * *");
debug_flag = 0;
}
else if (command == "F")
{
Serial.print("Server Number: ");
Serial.println(get_serverNum_from_flashMem());
Serial.println("Default server numbers: GLOBE1 - 639175972526 ; SMART1 - 639088125642");
Serial.println("Default server numbers: GLOBE2 - 639175388301 ; SMART2 - 639088125642");
if (isChangeParam())
changeServerNumber();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
Serial.readStringUntil('\r\n');
}
else if (command == "G")
{
//print voltage
Serial.print("Voltage: ");
Serial.println(readBatteryVoltage(get_logger_version()));
if (get_logger_version() == 6)
{
send_thru_lora(read_batt_vol(get_logger_version()));
}
Serial.println("* * * * * * * * * * * * * * * * * * * *");
}
else if (command == "H")
{
// on_IMU();
// delay_millis(1000);
// read_IMU_data(get_calib_param()); //print IMU sensor Datalogger
// delay_millis(1000);
// off_IMU();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
// Serial.println("AT + CMGF");
// GSMSerial.write("AT+CMGF=1\r");
// delay_millis(300);
/*
Serial.println("AT + CNMI");
GSMSerial.write("AT+CNMI=1,2,0,0,0\r");
delay_millis(300);
while (GSMSerial.available() > 0)
{
// processIncomingByte(GSMSerial.read(), 0);
String gsm_reply = GSMSerial.readString();
if (gsm_reply.indexOf("SENSLOPE,") > -1)
{
Serial.println("read SENSLOPE");
if (gsm_reply.indexOf(",REGISTERNUM") > -1)
{
Serial.println("Number Registered!");
}
}
// else if (gsm_reply.indexOf(",REGISTERNUM") > -1)
// {
// Serial.println("read REGISTERNUM");
// }
else
{
Serial.println("Not valid message!");
}
}
// Serial.println("delete sms");
// gsmDeleteReadSmsInbox();
Serial.println("end . . .");
*/
}
else if (command == "I")
{
Serial.println("GSM receive test!");
flashLed(LED_BUILTIN, 3, 50);
/*
do
{
Serial.println("starting do. . .");
GSMSerial.write("AT\r"); //gsm initialization
delay_millis(50);
GSMSerial.write("AT+CSCLK=0\r");
gsmReadOK();
GSMSerial.write("AT+CMGF=1\r");
gsmReadOK();
GSMSerial.write("AT+CNMI=1,2,0,0,0\r");
delay_millis(300);
processIncomingByte(GSMSerial.read());
} while (GSMSerial.available() > 0);
*/
// turn_ON_GSM(get_gsm_power_mode());
Serial.println("AT + CNMI");
if (get_gsm_power_mode() == 1)
{
Serial.println("1st AT + CNMI");
GSMSerial.write("AT+CNMI=1,2,0,0,0\r");
delay_millis(100);
}
GSMSerial.write("AT+CNMI=1,2,0,0,0\r");
delay_millis(300);
Serial.println("after CNMI");
while (GSMSerial.available() > 0)
{
processIncomingByte(GSMSerial.read(), 0);
}
// Serial.println("delete sms");
// gsmDeleteReadSmsInbox();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
}
else if (command == "J")
{
Serial.print("Logger version: ");
Serial.println(get_logger_version());
printLoggerVersion();
if (isChangeParam())
setLoggerVersion();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
Serial.readStringUntil('\r\n');
}
else if (command == "K")
{
Serial.print("Password: ");
Serial.println(get_password_from_flashMem());
if (isChangeParam())
changePassword();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
Serial.readStringUntil('\r\n');
}
else if (command == "L")
{
manualGSMcmd();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
}
else if (command == "M")
{
disable_watchdog();
send_rain_data(1);
Serial.println("* * * * * * * * * * * * * * * * * * * *");
}
else if (command == "N")
{
if (get_logger_version() == 1)
{
Serial.print("Gateway sensor name: ");
Serial.println(get_logger_A_from_flashMem());
Serial.print("Remote sensor name: ");
Serial.println(get_logger_B_from_flashMem());
}
else if (get_logger_version() == 3)
{
Serial.print("Gateway name: ");
Serial.println(get_logger_A_from_flashMem());
Serial.print("Sensor Name A: ");
Serial.println(get_logger_B_from_flashMem());
}
else if (get_logger_version() == 4)
{
Serial.print("Gateway name: ");
Serial.println(get_logger_A_from_flashMem());
Serial.print("Sensor Name A: ");
Serial.println(get_logger_B_from_flashMem());
Serial.print("Sensor Name B: ");
Serial.println(get_logger_C_from_flashMem());
}
else if (get_logger_version() == 5)
{
Serial.print("Gateway name: ");
Serial.println(get_logger_A_from_flashMem());
Serial.print("Sensor Name A: ");
Serial.println(get_logger_B_from_flashMem());
Serial.print("Sensor Name B: ");
Serial.println(get_logger_C_from_flashMem());
Serial.print("Sensor Name C: ");
Serial.println(get_logger_D_from_flashMem());
}
else if (get_logger_version() == 12)
{
Serial.print("Gateway name: ");
Serial.println(get_logger_A_from_flashMem());
Serial.print("Sensor Name A: ");
Serial.println(get_logger_B_from_flashMem());
Serial.print("Sensor Name B: ");
Serial.println(get_logger_C_from_flashMem());
Serial.print("Sensor Name C: ");
Serial.println(get_logger_D_from_flashMem());
Serial.print("Sensor Name D: ");
Serial.println(get_logger_E_from_flashMem());
Serial.print("Sensor Name E: ");
Serial.println(get_logger_F_from_flashMem());
}
else
{ // 2; 6; 7
Serial.print("Gateway sensor name: ");
Serial.println(get_logger_A_from_flashMem());
// Serial.print("Remote sensor name: ");
// Serial.println(get_logger_B_from_flashMem());
}
if (isChangeParam())
inputLoggerNames();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
Serial.readStringUntil('\r\n');
}
else if (command == "O")
{
Serial.print("CSQ: ");
Serial.println(readCSQ());
Serial.println("* * * * * * * * * * * * * * * * * * * *");
}
else if (command == "P")
{
Serial.print("Rain tips: ");
if (get_rainCollector_type() == 0)
{
Serial.println(rainTips * 2.0);
}
else if (get_rainCollector_type() == 1)
{
Serial.println(rainTips);
}
else
{
Serial.println(rainTips);
}
delay_millis(20);
resetRainTips();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
}
else if (command == "Q")
{
Serial.print("IMU Parameter: ");
Serial.println(get_calib_param());
Serial.println("[0] Raw IMU data");
Serial.println("[1] Calibrated IMU data");
if (isChangeParam())
setIMUdataRawCalib();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
Serial.readStringUntil('\r\n');
}
else if (command == "R")
{
resetGSM();
gsm_network_connect();
init_gsm();
Serial.print("CSQ: ");
Serial.println(readCSQ());
Serial.println("* * * * * * * * * * * * * * * * * * * *");
}
else if (command == "S")
{
readTimeStamp();
Serial.print("Timestamp: ");
Serial.println(Ctimestamp);
if (isChangeParam())
setupTime();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
Serial.readStringUntil('\r\n');
}
else if (command == "T")
{
Serial.print("Rain collector type: ");
Serial.println(get_rainCollector_type());
Serial.println("[0] Pronamic Rain Collector (0.5mm/tip)");
Serial.println("[1] DAVIS Rain Collector (0.2mm/tip)");
Serial.println("[2] Generic Rain Collector (1.0/tip)");
if (isChangeParam())
setRainCollectorType();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
Serial.readStringUntil('\r\n');
/*
Serial.println("MADTB*VOLT:12.33*200214111000");
char toParse[200];
Serial.setTimeout(15000);
Serial.println("Insert data to be parsed: ");
String fromUser = Serial.readStringUntil('\n');
fromUser.toCharArray(toParse, 200);
// Serial.print("Parsed data: ");
// Serial.println(parse_voltage(toParse));
// strncpy(txVoltage, parse_voltage(toParse), sizeof(parse_voltage(toParse)));
parse_voltage(toParse).toCharArray(txVoltage, sizeof(txVoltage));
Serial.print("Volt: ");
Serial.println(txVoltage);
Serial.print("Volt: ");
Serial.println(txVoltageB);
Serial.print("Volt: ");
Serial.println(txVoltageC);
get_rssi(5);
Serial.println("* * * * * * * * * * * * * * * * * * * *");
*/
}
else if (command == "U")
{
Serial.println("sending rain gauge data . . .");
if (get_logger_version() == 6)
{
//LoRa
send_rain_data(1);
}
else
{
//GSM
send_rain_data(0);
}
disable_watchdog();
// wakeGSM();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
}
else if (command == "V")
{
// turn_OFF_GSM(get_gsm_power_mode());
turn_ON_GSM(get_gsm_power_mode());
disable_watchdog();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
}
else if (command == "W")
{
Serial.print("Current gsm power mode: ");
Serial.println(get_gsm_power_mode());
Serial.println("[0] Hardware power ON or OFF");
Serial.println("[1] Sleep and wake via AT commands");
Serial.println("[2] GSM power always ON");
if (isChangeParam())
setGsmPowerMode();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
Serial.readStringUntil('\r\n');
}
else if (command == "X")
{
Serial.print("Datalogger Version: ");
Serial.println(get_logger_version());
receive_lora_data(get_logger_version());
disable_watchdog();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
}
else if (command == "Y")
{
unsigned long startHere = millis();
char specialMsg[200];
Serial.print("Enter message to send: ");
while (!Serial.available())
{
if (timeOutExit(startHere, DEBUGTIMEOUT))
{
debug_flag_exit = true;
break;
}
}
if (Serial.available())
{
String gsmCmd = Serial.readStringUntil('\n');
Serial.println(gsmCmd);
gsmCmd.toCharArray(specialMsg, sizeof(specialMsg));
GSMSerial.write("AT\r");
delay_millis(300);
send_thru_gsm(specialMsg, get_serverNum_from_flashMem());
}
Serial.println("* * * * * * * * * * * * * * * * * * * *");
}
else if (command == "Z")
{
Serial.print("Current command: ");
sensCommand = passCommand.read();
Serial.println(sensCommand.senslopeCommand);
if (isChangeParam())
changeSensCommand();
Serial.println("* * * * * * * * * * * * * * * * * * * *");
Serial.readStringUntil('\r\n');
}
else if (command == "?")
{
Serial.println("**Printing Stored Parameters**");
readTimeStamp();
Serial.print("Real time clock: ");
Serial.println(Ctimestamp);
Serial.print("Server number: ");
Serial.println(get_serverNum_from_flashMem());
Serial.print("Gsm power mode: ");
Serial.println(get_gsm_power_mode());
Serial.print("Sending time: ");
Serial.println(alarmFromFlashMem());
Serial.print("Logger version: ");
Serial.println(get_logger_version());
Serial.print("Logger name: ");
Serial.println(get_logger_A_from_flashMem());
Serial.print("Sensor command: ");
sensCommand = passCommand.read();
Serial.println(sensCommand.senslopeCommand);
Serial.print("MCU password: ");
Serial.println(get_password_from_flashMem());
Serial.print("Rain collector type: ");
Serial.println(get_rainCollector_type());
Serial.println("* * * * * * * * * * * * * * * * * * * *");
}
else
{
Serial.println(" ");
Serial.println("Command invalid!");
Serial.println(" ");
}
}
void printMenu()
{
Serial.println(F(" "));
Serial.print(F("Firmware Version: "));
Serial.println(F(firmwareVersion));
Serial.println(F("****************************************"));
Serial.println(F("[A] Sample sensor data"));
Serial.println(F("[B] Read RTC temperature."));
Serial.println(F("[C] Print this menu"));
Serial.println(F("[D] Change sending time."));
Serial.println(F("[E] Exit Debug mode."));
Serial.println(F("[F] Change SERVER NUMBER"));
Serial.println(F("[G] Print input voltage"));
Serial.println(F("[H] Test send IMU sensor data"));
Serial.println(F("[I] GSM receive SMS test"));
Serial.println(F("[J] Change LOGGER VERSION"));
Serial.println(F("[K] Change MCU PASSWORD"));
Serial.println(F("[L] Manual GSM commands"));
Serial.println(F("[M] Special sending rain data via LoRa"));
Serial.println(F("[N] Change DATALOGGER NAMES"));
Serial.println(F("[O] Read GSM CSQ."));
Serial.println(F("[P] Read rain gauge tip."));
Serial.println(F("[Q] Change IMU data parameters"));
Serial.println(F("[R] Reset GSM"));
Serial.println(F("[S] Set date and time."));
Serial.println(F("[T] Set rain collector type."));
Serial.println(F("[U] Send rain tips."));
Serial.println(F("[V] Turn ON GSM"));
Serial.println(F("[W] Set GSM POWER MODE"));
Serial.println(F("[X] Wait for LoRa data"));
Serial.println(F("[Y] Send CUSTOM SMS"));
Serial.println(F("[Z] Change SENSLOPE command."));
Serial.println(F("[?] Print stored config parameters."));
Serial.println(F("****************************************"));
Serial.println(F(" "));
}
void print_rtcInterval()
{
// Serial.println("------------------------------------------------");
Serial.println("[0] Alarm for every 0 and 30 minutes interval");
Serial.println("[1] Alarm for every 5 and 35 minutes interval");
Serial.println("[2] Alarm for every 10 and 40 minutes interval");
Serial.println("[3] Alarm for every 15 and 45 minutes interval");
Serial.println("[4] Alarm for every 10 minutes interval");
Serial.println("[5] Alarm for every 5,15,25. . . minutes interval");
// Serial.println("------------------------------------------------");
}
void setRainCollectorType()
{
unsigned long startHere = millis();
int _rainCollector;
Serial.print("Enter rain collector type: ");
while (!Serial.available())
{
if (timeOutExit(startHere, DEBUGTIMEOUT))
{
debug_flag_exit = true;
break;
}
}
if (Serial.available())
{
_rainCollector = Serial.parseInt();
Serial.print("Rain Collector type = ");
Serial.println(_rainCollector);
delay_millis(50);
rainCollectorType.write(_rainCollector);
}
}
uint8_t get_rainCollector_type()
{
int _rainType = rainCollectorType.read();
return _rainType;
}
void setIMUdataRawCalib()
{
unsigned long startHere = millis();
int raw_calib;
Serial.print("Enter IMU data mode: ");
while (!Serial.available())
{
if (timeOutExit(startHere, DEBUGTIMEOUT))
{
debug_flag_exit = true;
break;
}
}
if (Serial.available())
{
raw_calib = Serial.parseInt();
Serial.print("IMU mode = ");
Serial.println(raw_calib);
delay_millis(50);
imuRawCalib.write(raw_calib);
}
}
uint8_t get_calib_param()
{
int param = imuRawCalib.read();
return param;
}
void setLoggerVersion()
{
int version;
unsigned long startHere = millis();
Serial.print("Enter datalogger version: ");
while (!Serial.available())
{
if (timeOutExit(startHere, DEBUGTIMEOUT))
{
debug_flag_exit = true;
break;
}
}
if (Serial.available())
{
version = Serial.parseInt();
Serial.println(version);
delay_millis(50);
loggerVersion.write(version);
}
}
void printLoggerVersion()
{
Serial.println("[0] Sending sensor data using GSM only (arQ like function)"); //arQ like function only
Serial.println("[1] Version 5 GSM with LoRa tx (arQ + LoRa RX)"); //arQ + LoRa rx
Serial.println("[2] LoRa transmitter for version 5 datalogger"); //TX LoRa
Serial.println("[3] Gateway Mode with only ONE LoRa transmitter");
Serial.println("[4] Gateway Mode with TWO LoRa transmitter");
Serial.println("[5] Gateway Mode with THREE LoRa transmitter");
Serial.println("[6] LoRa transmitter for Raspberry Pi"); //TX LoRa
Serial.println("[7] Sends sensor and rain gauge data via LoRa"); //TX LoRa
Serial.println("[8] LoRa dummy transmitter (for testing only)"); //TX LoRa
Serial.println("[9] Surficial Tilt - GSM mode");
Serial.println("[10] Surficial Tilt - LoRa TX");
Serial.println("[11] Rain gauge sensor only - GSM");
Serial.println("[12] Surficial Tilt Gateway - LoRa TX");
Serial.println("[13] UBLOX Base");
Serial.println("[14] UBLOX Rover");
}
uint8_t get_logger_version()
{
int lversion = loggerVersion.read();
return lversion;
}
void setGsmPowerMode()
{
int gsm_power;
unsigned long startHere = millis();
Serial.print("Enter GSM mode setting: ");
while (!Serial.available())
{
if (timeOutExit(startHere, DEBUGTIMEOUT))
{
debug_flag_exit = true;
break;
}
}
if (Serial.available())
{
Serial.setTimeout(8000);
gsm_power = Serial.parseInt();
Serial.println(gsm_power);
delay_millis(50);
gsmPower.write(gsm_power);
}
}
uint8_t get_gsm_power_mode()
{
int gsm_mode = gsmPower.read();
return gsm_mode;
}
void setAlarmInterval()
{
unsigned long startHere = millis();
int alarmSelect;
Serial.print("Enter alarm settings: ");
while (!Serial.available())
{
if (timeOutExit(startHere, DEBUGTIMEOUT))
{
debug_flag_exit = true;
break;
}
}
if (Serial.available())
{
alarmSelect = Serial.parseInt();
Serial.println(alarmSelect);
delay_millis(50);
alarmStorage.write(alarmSelect);
}
}
uint8_t alarmFromFlashMem()
{
int fromAlarmStorage;
fromAlarmStorage = alarmStorage.read();
return fromAlarmStorage;
}
void changeSensCommand()
{
unsigned long startHere = millis();
Serial.print("Insert DUE command: ");
while (!Serial.available())
{
if (timeOutExit(startHere, DEBUGTIMEOUT))
{
debug_flag_exit = true;
break;
}
}
if (Serial.available())
{
String dynaCommand = Serial.readStringUntil('\n');
Serial.println(dynaCommand);
dynaCommand.toCharArray(sensCommand.senslopeCommand, 50);
passCommand.write(sensCommand); //save to flash memory
}
}
void inputLoggerNames()
{
unsigned long startHere = millis();
Serial.setTimeout(20000);
if (get_logger_version() == 1)
{
Serial.print("Input name of gateway SENSOR: ");
while (!Serial.available())
{
if (timeOutExit(startHere, DEBUGTIMEOUT))
{
debug_flag_exit = true;
break;
}
}
if (Serial.available())
{
String inputLoggerA = Serial.readStringUntil('\n');
Serial.println(inputLoggerA);
Serial.print("Input name of remote SENSOR: ");
String inputLoggerB = Serial.readStringUntil('\n');
Serial.println(inputLoggerB);
inputLoggerA.toCharArray(loggerName.sensorA, 10);
inputLoggerB.toCharArray(loggerName.sensorB, 10);
flashLoggerName.write(loggerName);
}
}
else if (get_logger_version() == 3)
{
Serial.print("Input name of GATEWAY: ");
while (!Serial.available())
{
if (timeOutExit(startHere, DEBUGTIMEOUT))
{
debug_flag_exit = true;
break;
}
}
if (Serial.available())
{
String inputLoggerA = Serial.readStringUntil('\n');
Serial.println(inputLoggerA);
Serial.print("Input name of remote SENSOR: ");
String inputLoggerB = Serial.readStringUntil('\n');
Serial.println(inputLoggerB);
inputLoggerA.toCharArray(loggerName.sensorA, 10);
inputLoggerB.toCharArray(loggerName.sensorB, 10);
flashLoggerName.write(loggerName);
}
}
else if (get_logger_version() == 4)
{
Serial.print("Input name of GATEWAY: ");
while (!Serial.available())
{
if (timeOutExit(startHere, DEBUGTIMEOUT))
{
debug_flag_exit = true;
break;
}
}
if (Serial.available())
{
String inputLoggerA = Serial.readStringUntil('\n');
Serial.println(inputLoggerA);
Serial.print("Input name of remote SENSOR A: ");
String inputLoggerB = Serial.readStringUntil('\n');
Serial.println(inputLoggerB);
Serial.print("Input name of remote SENSOR B: ");
String inputLoggerC = Serial.readStringUntil('\n');
Serial.println(inputLoggerC);
inputLoggerA.toCharArray(loggerName.sensorA, 10);
inputLoggerB.toCharArray(loggerName.sensorB, 10);
inputLoggerC.toCharArray(loggerName.sensorC, 10);
flashLoggerName.write(loggerName);
}
}
else if (get_logger_version() == 5)
{
Serial.print("Input name of GATEWAY: ");
while (!Serial.available())
{
if (timeOutExit(startHere, DEBUGTIMEOUT))
{
debug_flag_exit = true;
break;
}
}
if (Serial.available())
{
String inputLoggerA = Serial.readStringUntil('\n');
Serial.println(inputLoggerA);
Serial.print("Input name of remote SENSOR A: ");
String inputLoggerB = Serial.readStringUntil('\n');
Serial.println(inputLoggerB);
Serial.print("Input name of remote SENSOR B: ");
String inputLoggerC = Serial.readStringUntil('\n');
Serial.println(inputLoggerC);
Serial.print("Input name of remote SENSOR C: ");
String inputLoggerD = Serial.readStringUntil('\n');
Serial.println(inputLoggerD);
inputLoggerA.toCharArray(loggerName.sensorA, 10);
inputLoggerB.toCharArray(loggerName.sensorB, 10);
inputLoggerC.toCharArray(loggerName.sensorC, 10);
inputLoggerD.toCharArray(loggerName.sensorD, 10);
flashLoggerName.write(loggerName);
}
}
else if (get_logger_version() == 12)
{
Serial.print("Input name of GATEWAY: ");
while (!Serial.available())
{
if (timeOutExit(startHere, DEBUGTIMEOUT))
{
debug_flag_exit = true;
break;
}
}
if (Serial.available())
{
String inputLoggerA = Serial.readStringUntil('\n');
Serial.println(inputLoggerA);
Serial.print("Input name of remote SENSOR A: ");
String inputLoggerB = Serial.readStringUntil('\n');
Serial.println(inputLoggerB);
Serial.print("Input name of remote SENSOR B: ");
String inputLoggerC = Serial.readStringUntil('\n');
Serial.println(inputLoggerC);
Serial.print("Input name of remote SENSOR C: ");
String inputLoggerD = Serial.readStringUntil('\n');
Serial.println(inputLoggerD);
Serial.print("Input name of remote SENSOR D: ");
String inputLoggerE = Serial.readStringUntil('\n');
Serial.println(inputLoggerE);
Serial.print("Input name of remote SENSOR E: ");
String inputLoggerF = Serial.readStringUntil('\n');
Serial.println(inputLoggerF);
inputLoggerA.toCharArray(loggerName.sensorA, 10);
inputLoggerB.toCharArray(loggerName.sensorB, 10);
inputLoggerC.toCharArray(loggerName.sensorC, 10);
inputLoggerD.toCharArray(loggerName.sensorD, 10);
inputLoggerE.toCharArray(loggerName.sensorE, 10);
inputLoggerF.toCharArray(loggerName.sensorF, 10);
flashLoggerName.write(loggerName);
}
}
else
{
Serial.print("Input name of SENSOR: ");
while (!Serial.available())
{
if (timeOutExit(startHere, DEBUGTIMEOUT))
{
debug_flag_exit = true;
break;
}
}
if (Serial.available())
{
String inputLoggerA = Serial.readStringUntil('\n');
Serial.println(inputLoggerA);
inputLoggerA.toCharArray(loggerName.sensorA, 10);
flashLoggerName.write(loggerName);
}
}
}
void changeServerNumber()
{
unsigned long startHere = millis();
// Serial.println("Insert server number GLOBE - 639175972526 ; SMART - 639088125642");
Serial.print("Enter new server number: ");
while (!Serial.available())
{
if (timeOutExit(startHere, DEBUGTIMEOUT))
{
debug_flag_exit = true;
break;
}
}
if (Serial.available())
{
String ser_num = Serial.readStringUntil('\n');
Serial.println(ser_num);
ser_num.toCharArray(flashServerNumber.inputNumber, 50);
newServerNum.write(flashServerNumber); //save to flash memory
}
}
void changePassword()
{
unsigned long startHere = millis();
Serial.print("Enter MCU password: ");
while (!Serial.available())
{
if (timeOutExit(startHere, DEBUGTIMEOUT))
{
debug_flag_exit = true;
break;
}
}
if (Serial.available())
{
String inPass = Serial.readStringUntil('\n');
// inPass += ",";
Serial.println(inPass);
inPass.toCharArray(flashPassword.keyword, 50);
flashPasswordIn.write(flashPassword);
}
}
bool isChangeParam()
{
String serial_line;
unsigned long serStart = millis();
unsigned long startHere = millis();
bool timeToExit;
Serial.println(" ");
Serial.println("Enter C to change:");
do
{
timeToExit = timeOutExit(startHere, DEBUGTIMEOUT);
serial_line = Serial.readStringUntil('\r\n');
} while (serial_line == "" && timeToExit == false);
// } while ((serial_line == "") && ((millis() - serStart) < DEBUGTIMEOUT));
serial_line.toUpperCase();
serial_line.replace("\r", "");
if (timeToExit)
{
Serial.println("Exiting . . .");
debug_flag_exit = true;
}
if (serial_line == "C")
{
return true;
}
else
{
// printMenu();
Serial.println(" ");
Serial.println("Change cancelled. Reselect.");
Serial.println(" ");
return false;
}
}
bool timeOutExit(unsigned long _startTimeOut, int _timeOut)
{
if ((millis() - _startTimeOut) > _timeOut)
{
_startTimeOut = millis();
Serial.println(" ");
Serial.println("*****************************");
Serial.print("Timeout reached: ");
Serial.print(_timeOut / 1000);
Serial.println(" seconds");
Serial.println("*****************************");
Serial.println(" ");
return true;
}
else
{
return false;
}
}
| [
"dmarkarnel@gmail.com"
] | dmarkarnel@gmail.com |
e42f6203d6d0ee05783ec421d9b74f631abc9ea4 | 1766911e055e84442b21c6416f8469f864908e33 | /xrScriptEngine/ScriptEngineScript.cpp | 08b13da4fc680e9360bd6965e2f69d1cc6449ba8 | [] | no_license | xhyangxianjun/X-Ray-Engine-1.6 | 3db1528d796c7c58af5eb421bcbbd035a9d62ae5 | 5fa3cdc8895ecf7fb4f549bef3c32afd5a7d4d50 | refs/heads/master | 2021-08-31T20:53:02.226551 | 2017-12-22T21:41:00 | 2017-12-22T21:41:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,971 | cpp | ////////////////////////////////////////////////////////////////////////////
// Module : script_engine_script.cpp
// Created : 25.12.2002
// Modified : 13.05.2004
// Author : Dmitriy Iassenev
// Description : ALife Simulator script engine export
////////////////////////////////////////////////////////////////////////////
#include "pch.hpp"
#include "ScriptEngineScript.hpp"
#include "script_engine.hpp"
#include "script_debugger.hpp"
#include "DebugMacros.hpp"
#include "Include/xrAPI/xrAPI.h"
#include "ScriptExporter.hpp"
void LuaLog(LPCSTR caMessage)
{
#ifndef MASTER_GOLD
GlobalEnv.ScriptEngine->script_log(LuaMessageType::Message, "%s", caMessage);
#endif
#if defined(USE_DEBUGGER) && !defined(USE_LUA_STUDIO)
if (GlobalEnv.ScriptEngine->debugger())
GlobalEnv.ScriptEngine->debugger()->Write(caMessage);
#endif
}
void ErrorLog(LPCSTR caMessage)
{
GlobalEnv.ScriptEngine->error_log("%s", caMessage);
//#ifdef DEBUG
GlobalEnv.ScriptEngine->print_stack();
//#endif
#if defined(USE_DEBUGGER) && !defined(USE_LUA_STUDIO)
if (GlobalEnv.ScriptEngine->debugger())
GlobalEnv.ScriptEngine->debugger()->Write(caMessage);
#endif
#ifdef DEBUG
bool lua_studio_connected = !!GlobalEnv.ScriptEngine->debugger();
if (!lua_studio_connected)
R_ASSERT2(0, caMessage);
#else
R_ASSERT2(0, caMessage);
#endif
}
void FlushLogs()
{
#ifdef DEBUG
FlushLog();
GlobalEnv.ScriptEngine->flush_log();
#endif
}
void verify_if_thread_is_running()
{
THROW2(GlobalEnv.ScriptEngine->current_thread(), "coroutine.yield() is called outside the LUA thread!");
}
bool is_editor()
{
#ifdef EDITOR
return true;
#else
return false;
#endif
}
int bit_and(int i, int j) { return i & j; }
int bit_or(int i, int j) { return i | j; }
int bit_xor(int i, int j) { return i ^ j; }
int bit_not(int i) { return ~i; }
const char* user_name() { return Core.UserName; }
void prefetch_module(LPCSTR file_name) { GlobalEnv.ScriptEngine->process_file(file_name); }
struct profile_timer_script
{
u64 m_start_cpu_tick_count;
u64 m_accumulator;
u64 m_count;
int m_recurse_mark;
profile_timer_script()
{
m_start_cpu_tick_count = 0;
m_accumulator = 0;
m_count = 0;
m_recurse_mark = 0;
}
profile_timer_script(const profile_timer_script& profile_timer) { *this = profile_timer; }
profile_timer_script& operator=(const profile_timer_script& profile_timer)
{
m_start_cpu_tick_count = profile_timer.m_start_cpu_tick_count;
m_accumulator = profile_timer.m_accumulator;
m_count = profile_timer.m_count;
m_recurse_mark = profile_timer.m_recurse_mark;
return *this;
}
bool operator<(const profile_timer_script& profile_timer) const
{
return m_accumulator < profile_timer.m_accumulator;
}
void start()
{
if (m_recurse_mark)
{
m_recurse_mark++;
return;
}
m_recurse_mark++;
m_count++;
m_start_cpu_tick_count = CPU::GetCLK();
}
void stop()
{
if (!m_recurse_mark)
return;
m_recurse_mark--;
if (m_recurse_mark)
return;
u64 finish = CPU::GetCLK();
if (finish > m_start_cpu_tick_count)
m_accumulator += finish - m_start_cpu_tick_count;
}
float time() const
{
FPU::m64r();
float result = float(double(m_accumulator) / double(CPU::clk_per_second)) * 1000000.f;
FPU::m24r();
return result;
}
};
IC profile_timer_script operator+(const profile_timer_script& portion0, const profile_timer_script& portion1)
{
profile_timer_script result;
result.m_accumulator = portion0.m_accumulator + portion1.m_accumulator;
result.m_count = portion0.m_count + portion1.m_count;
return result;
}
std::ostream& operator<<(std::ostream& os, const profile_timer_script& pt) { return os << pt.time(); }
SCRIPT_EXPORT(CScriptEngine, (), {
using namespace luabind;
module(luaState)[class_<profile_timer_script>("profile_timer")
.def(constructor<>())
.def(constructor<profile_timer_script&>())
.def(const_self + profile_timer_script())
.def(const_self < profile_timer_script())
.def(tostring(self))
.def("start", &profile_timer_script::start)
.def("stop", &profile_timer_script::stop)
.def("time", &profile_timer_script::time),
def("log", &LuaLog), def("error_log", &ErrorLog), def("flush", &FlushLogs), def("prefetch", &prefetch_module),
def("verify_if_thread_is_running", &verify_if_thread_is_running), def("editor", &is_editor),
def("bit_and", &bit_and), def("bit_or", &bit_or), def("bit_xor", &bit_xor), def("bit_not", &bit_not),
def("user_name", &user_name)];
});
| [
"nouverbe@gmail.com"
] | nouverbe@gmail.com |
8498e6f78796ed434c9a0a207cd863999e8740d4 | 1c9ce29adcb905b1c6990f70e458624a89ff1131 | /106. Construct Binary Tree from Inorder and Postorder Traversal/solution.cpp | ebe81f91d61ac79488241271712167337000f6fa | [
"MIT"
] | permissive | KailinLi/LeetCode-Solutions | 90853613d0de566332ad94d96af06024f2772188 | bad6aa401b290a203a572362e63e0b1085f7fc36 | refs/heads/master | 2021-01-23T05:35:05.856028 | 2018-10-14T09:40:18 | 2018-10-14T09:40:18 | 86,318,316 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 875 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
int index;
public:
TreeNode* build(vector<int>& inorder, vector<int>& postorder, int begin, int length) {
if (length == 0) return nullptr;
int i = 0;
while (inorder[i] != postorder[index]) i++;
index--;
TreeNode* get = new TreeNode(inorder[i]);
get->right = build(inorder, postorder, i + 1, length - i + begin - 1);
get->left = build(inorder, postorder, begin, i - begin);
return get;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
index = (int)postorder.size() - 1;
return build(inorder, postorder, 0, (int)inorder.size());
}
};
| [
"likailinhust@gmail.com"
] | likailinhust@gmail.com |
8819410606e886e794e12524eaf0683f5017bef5 | ebd582b7fb493ccc2af59a5c0b5f0e98b2b5e8c3 | /Chapter10/src/Sales_item.h | 4a419634039873b58952ffad7388aacf12f1d6f0 | [] | no_license | rarog2018/C-Primer_Lippman | 97957e5c7f2d969f1534dd0992dd4c0e9d072700 | 3c3f5084aa744ef971e3bfa4fdfc639c5eea34d5 | refs/heads/master | 2021-06-28T17:45:34.549300 | 2021-01-05T08:15:27 | 2021-01-05T08:15:27 | 206,675,493 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,606 | h | #ifndef SALES_ITEM_H
#define SALES_ITEM_H
class Sales_data {
// friend declarations for nonmember Sales_data operations added
friend Sales_data add(const Sales_data&, const Sales_data&);
friend std::istream &read(std::istream&, Sales_data&);
friend std::ostream &print(std::ostream&, const Sales_data&);
public:
// nondelegating constructor initializes members from corresponding arguments
Sales_data(std::string s, unsigned cnt, double price):
bookNo(s), units_sold(cnt), revenue(cnt*price) { std::cout << "I am a regular constructor\n";}
// remaining constructors all delegate to another constructor
Sales_data(): Sales_data("", 0, 0) { std::cout << "I am a default contructor\n";}
Sales_data(std::string s): Sales_data(s, 0,0) { std::cout << "I am a string constuctor\n";}
Sales_data(std::istream &is): Sales_data() { std::cout << "I am an istream constructor\n"; read(is, *this); }
// new members: operations on Sales_data objects
std::string isbn() const { return bookNo; }
Sales_data& combine(const Sales_data&);
private:
double avg_price() const
{ return units_sold ? revenue/units_sold : 0; }
// data members are unchanged from § 2.6.1 (p. 72)
std::string bookNo;
unsigned units_sold = 0;
double revenue = 0.0;
};
// nonmember Sales_data interface functions
Sales_data add(const Sales_data&, const Sales_data&);
std::ostream &print(std::ostream&, const Sales_data&);
std::istream &read(std::istream& is, Sales_data& item);
#endif // SALES_ITEM_H
| [
"rarog91@protonmail.com"
] | rarog91@protonmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.