blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c6e0a04a659bc968bdd7ae35b968f4a17d205f14 | 96237b6e45ed56be5c629c3b4a573270e1434d7e | /processors/src/EUTelProcessorALPIDEClusterFilter.cc | 76393d4ef67277f7366fdcac60e5d73458f02344 | [] | no_license | AkosHU/eutelescope | b03542e254bc5569fd3a51e078499d428eaf5b22 | 363c89635bc3f92da59cd019a2167d8099726a8a | refs/heads/master | 2020-04-22T01:59:52.290102 | 2018-11-23T15:19:25 | 2018-11-23T15:19:25 | 170,032,685 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,766 | cc | // Author Antonio Bulgheroni, INFN <mailto:antonio.bulgheroni@gmail.com>
/*
* This source code is part of the Eutelescope package of Marlin.
* You are free to use this source files for your own development as
* long as it stays in a public research context. You are not
* allowed to use it for commercial purpose. You must put this
* header with author names in all development based on this file.
*
*/
// ROOT includes:
#include "TVector3.h"
// eutelescope includes ".h"
#include "EUTelGeometryTelescopeGeoDescription.h"
#include "EUTelProcessorALPIDEClusterFilter.h"
#include "EUTelRunHeaderImpl.h"
#include "EUTelEventImpl.h"
#include "EUTELESCOPE.h"
#include "EUTelSimpleVirtualCluster.h"
#include "EUTelGenericSparseClusterImpl.h"
#include "EUTelGeometricClusterImpl.h"
#include "EUTelFFClusterImpl.h"
#include "EUTelDFFClusterImpl.h"
#include "EUTelBrickedClusterImpl.h"
#include "EUTelSparseClusterImpl.h"
#include "EUTelExceptions.h"
#include "EUTelAlignmentConstant.h"
#include "EUTelReferenceHit.h"
#include "EUTelVirtualCluster.h"
#include "EUTelMatrixDecoder.h"
#include "EUTelTrackerDataInterfacerImpl.h"
// marlin includes ".h"
#include "marlin/Processor.h"
#include "marlin/Global.h"
#include "marlin/AIDAProcessor.h"
#include "marlin/Exceptions.h"
// aida includes <.h>
#if defined(USE_AIDA) || defined(MARLIN_USE_AIDA)
#include <marlin/AIDAProcessor.h>
#include <AIDA/IHistogramFactory.h>
#include <AIDA/IHistogram1D.h>
#include <AIDA/IHistogram2D.h>
#include <AIDA/ITree.h>
#endif
// lcio includes <.h>
#include <IMPL/LCCollectionVec.h>
#include <IMPL/TrackerPulseImpl.h>
#include <IMPL/TrackerDataImpl.h>
#include <IMPL/TrackerRawDataImpl.h>
#include <IMPL/TrackerHitImpl.h>
#include <UTIL/CellIDDecoder.h>
#include <UTIL/LCTime.h>
// system includes <>
#include <string>
#include <vector>
#include <algorithm>
#include <memory>
#include <list>
#include <stdio.h>
#include <iostream>
#include <iomanip>
#include <cstdio>
using namespace std;
using namespace marlin;
using namespace eutelescope;
using namespace lcio;
// definition of static members mainly used to name histograms
#if defined(USE_AIDA) || defined(MARLIN_USE_AIDA)
#endif
EUTelProcessorALPIDEClusterFilter::EUTelProcessorALPIDEClusterFilter () : Processor("EUTelProcessorALPIDEClusterFilter"),
_nzsDataCollectionName(""),
_zsDataCollectionName(""),
_noiseCollectionName(""),
_nDeep(2),
_nShift(10),
_Range(0.1),
_pulseCollectionName(""),
_initialPulseCollectionSize(0),
allCluster(0),
notDouvbleCluster(0),
noiseCollectionVec(NULL),
_sparseClusterCollectionName(""),
_noOfDetector(0),
_isGeometryReady(),
_totClusterMap(),
_NoEvent(),
_nOfAll(0),
_nOfGood(0),
_nOfFalse(0),
_nOfNoise(0)
{
registerInputCollection (LCIO::TRACKERDATA, "NZSDataCollectionName",
"Input calibrated data not zero suppressed collection name",
_nzsDataCollectionName, string ("data"));
registerInputCollection (LCIO::TRACKERDATA, "ZSDataCollectionName",
"Input of Zero Suppressed data",
_zsDataCollectionName, string ("zsdata") );
registerInputCollection (LCIO::TRACKERDATA, "NoiseCollectionName",
"Noise (input) collection name",
_noiseCollectionName, string("noise"));
registerOutputCollection(LCIO::TRACKERPULSE, "PulseCollectionName",
"Cluster (output) collection name",
_pulseCollectionName, string("cluster"));
registerOutputCollection(LCIO::TRACKERPULSE, "sparseClusterCollectionName",
"Cluster (output) collection name to _sparseClusterCollectionName",
_sparseClusterCollectionName, string("filtered_zsdata"));
}
void EUTelProcessorALPIDEClusterFilter::init(){
cout<<"IN INIT"<<endl;
_isGeometryReady=false;
_NoEvent=0;
}
bool EUTelProcessorALPIDEClusterFilter::SameCluster(int iEvent, int iCluster, int jEvent,int jCluster)
{
int nSame=0;
for(int iPixel=0; iPixel<PixelsOfEvents[iEvent][iCluster].size(); iPixel++)
{
for(int jPixel=0; jPixel<PixelsOfEvents[jEvent][jCluster].size(); jPixel++)
{
if(PixelsOfEvents[iEvent][iCluster][iPixel][0]==PixelsOfEvents[jEvent][jCluster][jPixel][0] &&
PixelsOfEvents[iEvent][iCluster][iPixel][1]==PixelsOfEvents[jEvent][jCluster][jPixel][1] &&
PixelsOfEvents[iEvent][iCluster][iPixel][2]==PixelsOfEvents[jEvent][jCluster][jPixel][2] &&
PixelsOfEvents[iEvent][iCluster][iPixel][3]==PixelsOfEvents[jEvent][jCluster][jPixel][3])
{
nSame++;
break;
}
}
}
if(nSame>PixelsOfEvents[iEvent][iCluster].size() * _Range || nSame>PixelsOfEvents[jEvent][jCluster].size() * _Range) return true;
return false;
}
void EUTelProcessorALPIDEClusterFilter::AddCluster(int iEvent, int iCluster, int jEvent,int jCluster)
{
for(int jPixel=0; jPixel<PixelsOfEvents[jEvent][jCluster].size(); jPixel++)
{
bool samePixel=false;
for(int iPixel=0; iPixel<PixelsOfEvents[iEvent][iCluster].size(); iPixel++)
{
if(PixelsOfEvents[iEvent][iCluster][iPixel][0]==PixelsOfEvents[jEvent][jCluster][jPixel][0] &&
PixelsOfEvents[iEvent][iCluster][iPixel][1]==PixelsOfEvents[jEvent][jCluster][jPixel][1] &&
PixelsOfEvents[iEvent][iCluster][iPixel][2]==PixelsOfEvents[jEvent][jCluster][jPixel][2] &&
PixelsOfEvents[iEvent][iCluster][iPixel][3]==PixelsOfEvents[jEvent][jCluster][jPixel][3])
{
samePixel=true;
break;
}
}
if(!samePixel) PixelsOfEvents[iEvent][iCluster].push_back(PixelsOfEvents[jEvent][jCluster][jPixel]);
}
}
void EUTelProcessorALPIDEClusterFilter::DeletCluster(int jEvent, int jCluster){
PixelsOfEvents[jEvent].erase(PixelsOfEvents[jEvent].begin()+jCluster);
}
void EUTelProcessorALPIDEClusterFilter::readCollections (LCCollectionVec * zsInputDataCollectionVec) {
vector<vector<vector<int>>>EventPixels;
//cerr<<"EVENT"<<endl;
//cerr<<"zsData size: "<<zsInputDataCollectionVec->size()<<endl;
for ( size_t actualCluster=0 ; actualCluster<zsInputDataCollectionVec->size(); actualCluster++) {
//cerr<<"actualCluster: "<<actualCluster<<endl;
CellIDDecoder<TrackerDataImpl> cellDecoder( zsInputDataCollectionVec );
TrackerDataImpl * zsData = dynamic_cast< TrackerDataImpl * > ( zsInputDataCollectionVec->getElementAt(actualCluster) );
SparsePixelType type = static_cast<SparsePixelType> ( static_cast<int> (cellDecoder( zsData )["sparsePixelType"]) );
//cout<<"Sensor id: "<<zsData->getTime()<<endl;
int clusterSize = zsData->getChargeValues().size()/4;
vector<int> X(clusterSize);
vector<int> Y(clusterSize);
Cluster cluster;
if ( type == kEUTelGenericSparsePixel )
{
vector<vector<int> > pixVector;
auto sparseData = EUTelTrackerDataInterfacerImpl<EUTelGenericSparsePixel>(zsData);
for(size_t iPixel = 0; iPixel < sparseData.size(); iPixel++ )
{
auto& pixel = sparseData.at( iPixel );
X[iPixel] = pixel.getXCoord();
Y[iPixel] = pixel.getYCoord();
vector<int> pix;
pix.push_back(X[iPixel]);
pix.push_back(Y[iPixel]);
//pix[2] will be the sensor id.
pix.push_back((int)cellDecoder(zsData)["sensorID"]);
//pix[3] will be the pixel type.
pix.push_back((int)cellDecoder( zsData )["sparsePixelType"]);
//pix[4] will be the time (it is like an id) of the cluster
pix.push_back(zsData->getTime());
//pix[5] will bw Signal
pix.push_back(pixel.getSignal());
//pix[6] will be the time (from the pixel)
pix.push_back(pixel.getTime());
pixVector.push_back(pix);
}
EventPixels.push_back(pixVector);
}
}
if(EventPixels.size()!=0) {
PixelsOfEvents.push_back(EventPixels);
}
}
void EUTelProcessorALPIDEClusterFilter::writeCollection (LCCollectionVec * sparseClusterCollectionVec, LCCollectionVec * pulseCollection) {
CellIDEncoder<TrackerDataImpl> idZSClusterEncoder( EUTELESCOPE::ZSCLUSTERDEFAULTENCODING, sparseClusterCollectionVec );
CellIDEncoder<TrackerPulseImpl> idZSPulseEncoder(EUTELESCOPE::PULSEDEFAULTENCODING, pulseCollection);
if(PixelsOfEvents.size()>_nDeep) {
for(int iCluster=0; iCluster<PixelsOfEvents[0].size();iCluster++) {
// prepare a TrackerData to store the cluster candidate
auto zsCluster = std::make_unique<TrackerDataImpl>();
// prepare a reimplementation of sparsified cluster
auto sparseCluster = std::make_unique<EUTelSparseClusterImpl<EUTelGenericSparsePixel>>(zsCluster.get());
int sensorID;
int TYPE;
int TIME;
while(PixelsOfEvents[0][iCluster].size()>0)
{
EUTelGenericSparsePixel Pixel;
Pixel.setXCoord(PixelsOfEvents[0][iCluster][0][0]);
Pixel.setYCoord(PixelsOfEvents[0][iCluster][0][1]);
Pixel.setTime(PixelsOfEvents[0][iCluster][0][6]);
Pixel.setSignal(PixelsOfEvents[0][iCluster][0][5]);
sensorID=PixelsOfEvents[0][iCluster][0][2];
TYPE=PixelsOfEvents[0][iCluster][0][3];
TIME=PixelsOfEvents[0][iCluster][0][4];
PixelsOfEvents[0][iCluster].erase(PixelsOfEvents[0][iCluster].begin());
sparseCluster->push_back( Pixel );
}
//cerr<<"CHECK POINT 4"<<endl;
if ( sparseCluster->size() > 0)
{
//cerr<<"CHECK POINT sparseCluster->size() > 0"<<endl;
// set the ID for this zsCluster
idZSClusterEncoder["sensorID"] = static_cast<int >(sensorID);
//idZSClusterEncoder["sparsePixelType"] = static_cast<int> (type); //cout<<"TIPE: "<<type<<endl;
idZSClusterEncoder["sparsePixelType"]= static_cast<int >(TYPE);
idZSClusterEncoder["quality"] = 0;
idZSClusterEncoder.setCellID( zsCluster.get() );
zsCluster->setTime(TIME);
// add it to the cluster collection
sparseClusterCollectionVec->push_back( zsCluster.get() );
// prepare a pulse for this cluster
auto zsPulse = std::make_unique<TrackerPulseImpl>();
idZSPulseEncoder["sensorID"] = static_cast<int >(sensorID);
idZSPulseEncoder["type"] = static_cast<int>(kEUTelSparseClusterImpl);
idZSPulseEncoder.setCellID( zsPulse.get() );
zsPulse->setTime(TIME);
//zsPulse->setCharge( sparseCluster->getTotalCharge() );
zsPulse->setTrackerData( zsCluster.release() );
pulseCollection->push_back( zsPulse.release() );
_totClusterMap [static_cast<int >(sensorID)] +=1;
}
}
PixelsOfEvents.erase(PixelsOfEvents.begin());
}
}
void EUTelProcessorALPIDEClusterFilter::filter () {
if(PixelsOfEvents.size()>_nDeep)
{
//cerr<<" IN NDEEP"<<endl;
for(int iCluster=0; iCluster<PixelsOfEvents[0].size();iCluster++)
{
//notDouvbleCluster++;
for(int jEvent=1; jEvent<=_nDeep; jEvent++)
{
bool wasSameCluster=false;
for(int jCluster=0; jCluster<PixelsOfEvents[jEvent].size(); jCluster++)
{
if(SameCluster(0,iCluster,jEvent,jCluster))
{
//AddCluster(0,iCluster,jEvent,jCluster);
DeletCluster(jEvent,jCluster);
wasSameCluster=true;
}
}
if(!wasSameCluster) break;
}
}
}
}
void EUTelProcessorALPIDEClusterFilter::effOfALPIDE () {
int zero=0, one=0, two=0;
for(int iEff=0; iEff<PixelsOfEvents[0].size(); iEff++)
{
if(PixelsOfEvents[0][iEff][0][2]==0) zero++;
else if(PixelsOfEvents[0][iEff][0][2]==1) one++;
else if(PixelsOfEvents[0][iEff][0][2]==2) two++;
}
if(zero==1 && two==1)
{
_nOfAll++;
if(one==0) _nOfFalse++;
else if(one==1) _nOfGood++;
else if(one>1) _nOfNoise++;
}
else
{
PixelsOfEvents.erase(PixelsOfEvents.begin());
}
}
void EUTelProcessorALPIDEClusterFilter::processEvent (LCEvent * evt) {
//cout<<_nDeep<<endl;
EUTelEventImpl * event = static_cast<EUTelEventImpl*> (evt);
if ( event->getEventType() == kEORE )
{
streamlog_out ( DEBUG4 ) << "EORE found: nothing else to do." << endl;
return;
}
else if ( event->getEventType() == kUNKNOWN )
{
streamlog_out ( WARNING2 ) << "Event number " << event->getEventNumber()
<< " is of unknown type. Continue considering it as a normal Data Event." << endl;
}
//cout<<"EVT NUMB: "<<evt->getEventNumber()<<endl;
_noOfDetector =0;
_clusterAvailable = true;
try {
zsInputDataCollectionVec = dynamic_cast< LCCollectionVec * > ( evt->getCollection( _zsDataCollectionName ) ) ;
streamlog_out ( DEBUG5 ) << "zsInputDataCollectionVec: " << _zsDataCollectionName.c_str() << " found " << endl;
//cerr<<"zsInputDataCollectionVec AVAILABLE!"<<endl;
_noOfDetector += zsInputDataCollectionVec->getNumberOfElements();
allCluster++;
CellIDDecoder<TrackerDataImpl > cellDecoder( zsInputDataCollectionVec );
for ( size_t i = 0; i < zsInputDataCollectionVec->size(); ++i )
{
TrackerDataImpl * data = dynamic_cast< TrackerDataImpl * > ( zsInputDataCollectionVec->getElementAt( i ) ) ;
_totClusterMap.insert( make_pair( cellDecoder( data )[ "sensorID" ] , 0 ));
}
} catch ( lcio::DataNotAvailableException ) {
//streamlog_out ( DEBUG5 ) << "zsInputDataCollectionVec: " << _zsDataCollectionName.c_str() << " not found " << endl;
_clusterAvailable = false;
//throw SkipEventException( this );
//cerr<<"zsInputDataCollectionVec NOT AVAILABLE!"<<endl;
}
if ( _noOfDetector == 0 && _isGeometryReady==false) {
//streamlog_out( WARNING2 ) << "Unable to initialize the geometry. Trying with the following event" << endl;
_isGeometryReady=false;
//throw SkipEventException( this );
} else {
_isGeometryReady=true;
}
bool isDummyAlreadyExisting = false;
LCCollectionVec * sparseClusterCollectionVec = NULL;
//ID = 0;
//int TYPE=0;
try
{
sparseClusterCollectionVec = dynamic_cast< LCCollectionVec* > ( evt->getCollection( _sparseClusterCollectionName ) );
isDummyAlreadyExisting = true ;
}
catch (lcio::DataNotAvailableException& e)
{
sparseClusterCollectionVec = new LCCollectionVec(LCIO::TRACKERDATA);
isDummyAlreadyExisting = false;
}
LCCollectionVec * pulseCollection;
bool pulseCollectionExists = false;
_initialPulseCollectionSize = 0;
try
{
pulseCollection = dynamic_cast< LCCollectionVec * > ( evt->getCollection( _pulseCollectionName ) );
pulseCollectionExists = true;
_initialPulseCollectionSize = pulseCollection->size();
//cerr<<"pulseCollection AVAILABLE!"<<endl;
}
catch ( lcio::DataNotAvailableException& e )
{
pulseCollection = new LCCollectionVec(LCIO::TRACKERPULSE);
//cerr<<"pulseCollection DONE!"<<endl;
}
// prepare an encoder also for the pulse collection
noiseCollectionVec = 0;
try
{
noiseCollectionVec = dynamic_cast < LCCollectionVec * > (evt->getCollection( _noiseCollectionName ));
streamlog_out ( DEBUG4 ) << "noiseCollectionName: " << _noiseCollectionName.c_str() << " found " << endl;
}
catch (lcio::DataNotAvailableException& e )
{
streamlog_out ( DEBUG4 ) << "No noise pixel DB collection found in the event" << endl;
}
if(_clusterAvailable) {
readCollections(zsInputDataCollectionVec);
filter();
//effOfALPIDE();
writeCollection(sparseClusterCollectionVec, pulseCollection);
}
if ( ! isDummyAlreadyExisting )
{
//cerr<<"CHECK POINT ! isDummyAlreadyExisting"<<endl;
if ( sparseClusterCollectionVec->size() != 0 )
{
notDouvbleCluster+=1;
//cerr<<"CHECK POINT sparseClusterCollectionVec"<<endl;
evt->addCollection( sparseClusterCollectionVec, _sparseClusterCollectionName );
}
else
{
delete sparseClusterCollectionVec;
}
}
//cerr<<"CHECK POINT 7"<<endl;
// if the pulseCollection is not empty add it to the event
if ( ! pulseCollectionExists && ( pulseCollection->size() != _initialPulseCollectionSize ))
{
//notDouvbleCluster+=1;
evt->addCollection( pulseCollection, _pulseCollectionName );
//cout<<_pulseCollectionName<<endl;
}
if ( ! pulseCollectionExists && ( pulseCollection->size() == _initialPulseCollectionSize ) )
{
delete pulseCollection;
}
_NoEvent++;
}
void EUTelProcessorALPIDEClusterFilter::end()
{
cerr<<"IN END"<<endl;
//cerr<<allCluster<<"; "<<notDouvbleCluster<<endl;
cerr<<"____________________________________________________"<<endl;
cerr<<"_nOfAll: "<<_nOfAll<<"_nOfFalse: "<<_nOfFalse<<"_nOfGood: "<<_nOfGood<<"_nOfNoise: "<<_nOfNoise<<endl;
cerr<<"____________________________________________________"<<endl;
map< int, int >::iterator iter = _totClusterMap.begin();
while ( iter != _totClusterMap.end() ) {
streamlog_out ( MESSAGE2 ) << "Found " << iter->second << " clusters on detector " << iter->first << endl;
++iter;
}
}
| [
"sudar.akos@wigner.mta.hu"
] | sudar.akos@wigner.mta.hu |
04f6067e6f8f6f226ab54704e982ea604807c2f2 | 81df397ea355b5cacba448e3c8ab7baccd7682d5 | /src/SDK/aimp_dotnet/SDK/Menu/AimpServiceMenuManager.cpp | 3fdd0551963825e9a4abe9dd5b008243f53c3f43 | [
"Apache-2.0"
] | permissive | martin211/aimp_dotnet | cd5e47bd1de8785f5e0cbb10bec89b378d6c44bd | c5ae9d2285002f44bd9d257f48190642f3f9039d | refs/heads/master | 2023-02-23T15:44:50.347411 | 2023-02-01T17:33:03 | 2023-02-01T17:33:03 | 33,116,326 | 59 | 9 | Apache-2.0 | 2020-08-17T13:57:50 | 2015-03-30T10:17:19 | C++ | UTF-8 | C++ | false | false | 6,051 | cpp | // ----------------------------------------------------
// AIMP DotNet SDK
//
// Copyright (c) 2014 - 2022 Evgeniy Bogdan
// https://github.com/martin211/aimp_dotnet
//
// Mail: mail4evgeniy@gmail.com
// ----------------------------------------------------
#include "Stdafx.h"
#include "AimpMenuItem.h"
#include "AimpServiceMenuManager.h"
/// <summary>
/// Initializes a new instance of the <see cref="ServiceMenuManager"/> class.
/// </summary>
/// <param name="core">The core.</param>
AimpServiceMenuManager::AimpServiceMenuManager(ManagedAimpCore^ core) : BaseAimpService<IAIMPServiceMenuManager>(core) {
}
ActionResult AimpServiceMenuManager::Add(IAimpMenuItem^ item) {
auto result = ActionResultType::Unexpected;
IAIMPServiceMenuManager* service = GetAimpService();
try {
if (service != nullptr) {
result = CheckResult(_core->GetAimpCore()->RegisterExtension(
IID_IAIMPServiceMenuManager,
static_cast<AimpMenuItem^>(item)->InternalAimpObject));
}
}
finally {
ReleaseObject(service);
//ReleaseObject(static_cast<AimpMenuItem^>(item)->InternalAimpObject);
}
return ACTION_RESULT(result);
}
/// <summary>
/// Adds the menu item.
/// </summary>
/// <param name="parentMenuType">Type of the parent menu.</param>
/// <param name="item">The item.</param>
ActionResult AimpServiceMenuManager::Add(ParentMenuType parentMenuType, IAimpMenuItem^ item) {
auto result = ActionResultType::Unexpected;
IAIMPServiceMenuManager* service = GetAimpService();
try {
if (service != nullptr) {
// gets the parent menu item.
IAIMPMenuItem* parentMenu;
result = CheckResult(service->GetBuiltIn(int(parentMenuType), &parentMenu));
if (result == ActionResultType::OK && parentMenu != nullptr) {
static_cast<AimpMenuItem^>(item)->InternalAimpObject->SetValueAsObject(
AIMP_MENUITEM_PROPID_PARENT, parentMenu);
result = CheckResult(_core->GetAimpCore()->RegisterExtension(
IID_IAIMPServiceMenuManager,
static_cast<AimpMenuItem^>(item)->InternalAimpObject));
ReleaseObject(parentMenu);
}
}
}
finally {
ReleaseObject(service);
//ReleaseObject(static_cast<AimpMenuItem^>(item)->InternalAimpObject);
}
return ACTION_RESULT(result);
}
/// <summary>
/// Deletes the menu item.
/// </summary>
/// <param name="item">The item.</param>
ActionResult AimpServiceMenuManager::Delete(IAimpMenuItem^ item) {
const auto result = this->Delete(item->Id);
return ACTION_RESULT(result->ResultType);
}
/// <summary>
/// Deletes the menu item.
/// </summary>
/// <param name="id">The identifier.</param>
ActionResult AimpServiceMenuManager::Delete(String^ id) {
IAIMPServiceMenuManager* service = GetAimpService();
IAIMPString* idString = nullptr;
IAIMPMenuItem* aimpMenuItem = nullptr;
auto result = ActionResultType::Fail;
try {
if (service != nullptr) {
Assert::NotNull(id, "id");
idString = AimpConverter::ToAimpString(id);
result = CheckResult(service->GetByID(idString, &aimpMenuItem));
if (result == ActionResultType::OK) {
result = CheckResult(UnregisterMenu(aimpMenuItem));
}
//if (CheckResult(ManagedAimpCore::GetAimpCore()->UnregisterExtension(aimpMenuItem)) != ActionResultType::OK)
//{
// System::Diagnostics::Debugger::Break();
//}
}
}
finally {
ReleaseObject(idString);
ReleaseObject(service);
//ReleaseObject(aimpMenuItem);
}
return ACTION_RESULT(result);
}
MenuItemResult AimpServiceMenuManager::GetById(String^ id) {
IAIMPServiceMenuManager* service = GetAimpService();
IAIMPString* menuId = nullptr;
IAIMPMenuItem* aimpMenuItem = nullptr;
auto result = ActionResultType::Unexpected;
IAimpMenuItem^ item = nullptr;
try {
if (service != nullptr) {
Assert::NotNull(id, "id");
menuId = AimpConverter::ToAimpString(id);
result = CheckResult(service->GetByID(menuId, &aimpMenuItem));
if (result == ActionResultType::OK && aimpMenuItem != nullptr) {
item = gcnew AimpMenuItem(aimpMenuItem);
}
}
}
finally {
ReleaseObject(service);
ReleaseObject(menuId);
//ReleaseObject(aimpMenuItem);
}
return gcnew AimpActionResult<IAimpMenuItem^>(result, item);
}
MenuItemResult AimpServiceMenuManager::GetBuiltIn(ParentMenuType parentMenuType) {
IAIMPServiceMenuManager* service = GetAimpService();
IAIMPMenuItem* aimpMenuItem = nullptr;
auto result = ActionResultType::Unexpected;
IAimpMenuItem^ item = nullptr;
try {
result = GetService(IID_IAIMPServiceMenuManager, &service);
if (result == ActionResultType::OK) {
result = CheckResult(service->GetBuiltIn(static_cast<int>(parentMenuType), &aimpMenuItem));
if (result == ActionResultType::OK) {
item = gcnew AimpMenuItem(aimpMenuItem);
}
}
}
finally {
ReleaseObject(service);
//ReleaseObject(aimpMenuItem);
}
return gcnew AimpActionResult<IAimpMenuItem^>(result, item);
}
/// <summary>
/// Unregisters the menu.
/// </summary>
/// <param name="menuItem">The menu item.</param>
HRESULT AimpServiceMenuManager::UnregisterMenu(IAIMPMenuItem* menuItem) {
return _core->UnregisterExtension(menuItem);
}
IAIMPServiceMenuManager* AimpServiceMenuManager::GetAimpService() {
IAIMPServiceMenuManager* service = nullptr;
GetService(IID_IAIMPServiceMenuManager, &service);
return service;
}
| [
"mail4evgeniy@gmail.com"
] | mail4evgeniy@gmail.com |
12d8446c19101fb38b418b3c1af48023a44ca9ce | d590b463f9f28dcf7818b17bffa4a51a8d363200 | /src/cDPMmdensityNeal.cpp | ac1cf6d52cb8d1053aaad6f31133e78b79d55fda | [] | no_license | chujiluo/BNPqte | bde6f581abce258bd11ad8207f9259698c419dc1 | 12cae879932e89a28fbd7e71aef1488d6863fedb | refs/heads/main | 2023-06-11T15:52:18.527576 | 2021-06-27T21:04:27 | 2021-06-27T21:04:27 | 334,840,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,710 | cpp | #include "dpmNeal.h"
// [[Rcpp::export]]
Rcpp::List cDPMmdensityNeal(
const arma::uword n,
const arma::uword d,
const arma::mat & data, // nxd matrix
const arma::colvec & y, // vector of length n
const arma::mat & x, // nx(d-1) matrix
const bool diag,
const bool pdf,
const bool cdf,
const arma::uword ngrid,
arma::colvec & grid,
const arma::uword npred,
arma::mat & xpred,
const bool updateAlpha,
const bool useHyperpriors,
double alpha,
const double a0,
const double b0,
double lambda,
const double gamma1,
const double gamma2,
const int nu0,
const int nu,
arma::uword & nclusters,
const arma::uword nskip,
const arma::uword ndpost,
const arma::uword keepevery,
const arma::rowvec & diri,
const arma::colvec & probs,
const arma::uword nprobs
) {
//------------------------------------------------------------------
// initialize hyperparameters
arma::colvec m0(d);
arma::mat S0(d, d, arma::fill::zeros);
arma::mat Psi0(d, d);
arma::mat invS0(d, d);
arma::colvec invS0m0(d);
arma::mat invPsi0(d, d);
arma::colvec m(d);
arma::mat Psi(d, d);
if(useHyperpriors) {
m0 = arma::mean(data, 0).t();
arma::rowvec tmp_vec = arma::range(data, 0);
tmp_vec = tmp_vec % tmp_vec / 16.0;
S0.diag() = tmp_vec.t();
m = m0 + 100.0 * arma::randn<arma::colvec>(d);
Psi0 = S0 / nu0;
Psi = S0;
invS0 = arma::inv_sympd(S0);
invS0m0 = invS0 * m0;
invPsi0 = arma::inv_sympd(Psi0);
} else {
m = arma::mean(data, 0).t();
arma::rowvec tmp_vec = arma::range(data, 0);
tmp_vec = tmp_vec % tmp_vec / 16.0;
Psi.diag() = tmp_vec.t();
}
//------------------------------------------------------------------
// initialize parameters
arma::mat Zeta(d, nclusters); // each column is of length d
arma::cube Omega(d, d, nclusters); // each slice is dxd
arma::cube cholOmega(d, d, nclusters); // cholOmega.slice(i) = arma::chol(Omega.slice(i))
arma::cube icholOmega(d, d, nclusters); // icholOmega.slice(i) = arma::inv(cholOmega.slice(i))
arma::colvec othersOmega(nclusters); // terms excluding data in the log pdf of Normal(Zeta.col(i), Omega.slice(i))
arma::uvec kappa(n); // support: 0 ~ nclusters-1
arma::urowvec clusterSize(n+2, arma::fill::zeros);
double yloglik;
setparamNeal(n, d, nclusters, m, Psi, Omega, cholOmega, icholOmega, othersOmega, Zeta, kappa, clusterSize);
//------------------------------------------------------------------
// return data structures
arma::mat evalyPDFs(ndpost, ngrid);
arma::mat evalyCDFs(ndpost, ngrid);
arma::mat quantiles(ndpost, nprobs);
Rcpp::NumericVector ylogliks(ndpost);
//------------------------------------------------------------------
// start mcmc
for(arma::uword i=0; i<(nskip+ndpost); i++){
if(i<nskip){
Rcpp::checkUserInterrupt();
// update (hyper)parameters
drawparamNeal(n, d, nclusters, data, updateAlpha, useHyperpriors, a0, b0, m0, S0, invS0, invS0m0, gamma1, gamma2, nu0, Psi0, invPsi0,
alpha, m, lambda, nu, Psi, Omega, cholOmega, icholOmega, othersOmega, Zeta, kappa, clusterSize, diag, yloglik);
} else {
// update (hyper)parameters
for(arma::uword j=0; j<keepevery; j++){
Rcpp::checkUserInterrupt();
drawparamNeal(n, d, nclusters, data, updateAlpha, useHyperpriors, a0, b0, m0, S0, invS0, invS0m0, gamma1, gamma2, nu0, Psi0, invPsi0,
alpha, m, lambda, nu, Psi, Omega, cholOmega, icholOmega, othersOmega, Zeta, kappa, clusterSize, diag, yloglik);
}
// prediction
if(pdf || cdf) {
arma::rowvec tmp_pdf(ngrid);
arma::rowvec tmp_cdf(ngrid);
arma::rowvec tmp_quantile(nprobs);
predict_marginal_Neal(ngrid, npred, n, d, nclusters, nprobs, grid, xpred, probs, Zeta, Omega, alpha, m, lambda, nu, Psi,
clusterSize, pdf, cdf, diri, tmp_pdf, tmp_cdf, tmp_quantile);
if(pdf) {
evalyPDFs.row(i-nskip) = tmp_pdf;
}
if(cdf) {
evalyCDFs.row(i-nskip) = tmp_cdf;
quantiles.row(i-nskip) = tmp_quantile;
}
}
if(diag)
ylogliks[i-nskip] = yloglik;
}
}
//------------------------------------------------------------------
// return
Rcpp::List res;
if(diag)
res["ylogliks"] = ylogliks;
if(pdf) {
res["predict.pdfs"] = Rcpp::wrap(evalyPDFs);
}
if(cdf) {
res["predict.cdfs"] = Rcpp::wrap(evalyCDFs);
res["predict.quantiles"] = Rcpp::wrap(quantiles);
}
return res;
}
| [
"cjluo@ufl.edu"
] | cjluo@ufl.edu |
a6f91106707cf95ed179475bc1abf962e033dca1 | 33def6088ad0990337eff92ff908934ebfa438cc | /Libraries/RC_Channel/RC_Channel.cpp | 6df18867023364e60aa306b70a1fe129f7109568 | [] | no_license | andbet39/Arduboat | 7c1003cd9ec9f8fcba5f70ad9c883c559135ca71 | c95b8de64b7eb4edd84b1f49b2f9a5ec149c55ce | refs/heads/master | 2016-09-06T02:39:04.532197 | 2014-09-05T15:56:13 | 2014-09-05T15:56:13 | 22,409,970 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,979 | cpp |
#include <RC_Channel.h>
#include <RC_HAL.h>
#define SERVO_MAX 1800
#define SERVO_MIN 1200
static RC_HAL *hal;
void RC_Channel::init(uint8_t pinOut, uint8_t chIn)
{
hal=RC_HAL::getInstance();
_pinOut=pinOut;
_chIn=chIn;
servo.attach(_pinOut);
_min=SERVO_MIN;
_max=SERVO_MAX;
_override=0;
_pwmOut=_min+((_max-_min)/2);
Serial.printf("Servo attahced Channel: %d \n",chIn );
}
void RC_Channel::setPwm(uint16_t pwm){
if (pwm>_max && pwm <2000)
{
_max=pwm;
}
if (pwm<_min && pwm >1000)
{
_min=pwm;
}
if(pwm<2000 && pwm>1000){
_pwmOut=pwm;
_last_pwm=pwm;
}
}
void RC_Channel::writeCurrent(){
if (abs(_pwmOut-_last_pwm) > _dead_zone)
{
//Serial.printf("Servo OUT :%d \n",_pwmOut);
servo.writeMicroseconds(_pwmOut);
_last_pwm=_pwmOut;
}
}
void RC_Channel::setDeadZone(uint16_t dead_zone){
_dead_zone=dead_zone;
}
uint16_t RC_Channel::center(){
int16_t center = _min+((_max-_min)/2);
_center=center;
return center;
}
uint16_t RC_Channel::getMin(){
return _min;
}
uint16_t RC_Channel::getPwmOut(){
return _pwmOut;
}
uint16_t RC_Channel::getMax(){
return _max;
}
void RC_Channel::setCenter(uint16_t center){
_center=center;
}
void RC_Channel::fixCenterPos(){
_center=pwmIn;
}
uint16_t RC_Channel::readRadio(){
pwmIn = hal->chin(_chIn);
_pwmIn=pwmIn;
return pwmIn;
}
void RC_Channel::setMinMax(uint16_t min,uint16_t max){
}
float RC_Channel::getControl(){
uint16_t range=_max-_min;
float ratio = 2.0/range;
return -1+(_pwmOut-_min)*ratio;
}
void RC_Channel::setOverrideToPwm(int16_t override){
_override=override;
_pwmOut += _override;
if (_pwmOut>_max)
{
_pwmOut=_max;
}
if (_pinOut<_min)
{
_pwmOut=_min;
}
if (_max>2000)
{
_max=2000;
}
if (_min<1000)
{
_min=1000;
}
} | [
"andrea.terzani@gmail.com"
] | andrea.terzani@gmail.com |
55ae2eaa532ea0f33c8a3433525417fcf803341d | e111a36487447b102150bba42fdf2f2cda5fe1b1 | /project4/StudentTextEditor.h | cd177e03bd0e4667c2b410fda4f58108c6dbcb36 | [] | no_license | CedricKuang/UCLA-CS32-WINTER2021 | 736ae9ce854089788ac6193f6abf1758e390848e | a1fcfecb6cda1c7a0d9c650d689a79a839886646 | refs/heads/main | 2023-04-24T02:22:53.029538 | 2021-04-23T10:20:20 | 2021-04-23T10:20:20 | 342,515,061 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 703 | h | #ifndef STUDENTTEXTEDITOR_H_
#define STUDENTTEXTEDITOR_H_
#include "TextEditor.h"
#include <list>
#include <string>
class Undo;
class StudentTextEditor : public TextEditor {
public:
StudentTextEditor(Undo* undo);
~StudentTextEditor();
bool load(std::string file);
bool save(std::string file);
void reset();
void move(Dir dir);
void del();
void backspace();
void insert(char ch);
void enter();
void getPos(int& row, int& col) const;
int getLines(int startRow, int numRows, std::vector<std::string>& lines) const;
void undo();
private:
int m_row;
int m_col;
int m_lines;
std::list<std::string*> text_lines;
std::list<std::string*>::iterator m_it;
};
#endif // STUDENTTEXTEDITOR_H_
| [
"noreply@github.com"
] | noreply@github.com |
a6867376d43afcc6665ee2f41d3904a99906186b | e41671be8665ad2756485c2dea479923d2668c27 | /firmware/examples/test.cpp | 312f29469e13850b47400b8fdf56bf140b3b8a5c | [] | no_license | leemm77/Spark-Neopixel-DMA | 92dce03478c719f738455cbe0b29ef24d036c052 | 7a14756302bf94368b8c04ed86db6e5b793d1b0a | refs/heads/master | 2021-06-01T13:23:14.214379 | 2016-08-15T17:10:09 | 2016-08-15T17:10:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 360 | cpp | #include "application.h"
#include "neopixel-dma/neopixel-dma.h"
ws2812 ws2812;
void setup()
{
int lednum = 3;
ws2812.init(lednum);
for(int i=0;i<100;i++)
{
for(int k=0;k<lednum;k++)
{
ws2812.framebuffer[k].red=i;
ws2812.framebuffer[k].blue=i;
ws2812.framebuffer[k].green=i;
}
ws2812.show();
delay(300);
}
}
void loop()
{
}
| [
"ekbduffy@gmail.com"
] | ekbduffy@gmail.com |
44c757d5ed4e7bd9a37628ff547c03e92e84c84c | e41e78cc4b8d010ebdc38bc50328e7bba2d5a3fd | /SDK/Mordhau_BP_SliderEntry_parameters.hpp | 552c75fec2ab95f7cc314308724229bb20ee8b15 | [] | no_license | Mentos-/Mordhau_SDK | a5e4119d60988dca9063e75e2563d1169a2924b8 | aacf020e6d4823a76787177eac2f8f633f558ec2 | refs/heads/master | 2020-12-13T10:36:47.589320 | 2020-01-03T18:06:38 | 2020-01-03T18:06:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,195 | hpp | #pragma once
// Mordhau (Dumped by Hinnie) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function BP_SliderEntry.BP_SliderEntry_C.GetValue
struct UBP_SliderEntry_C_GetValue_Params
{
float Value; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BP_SliderEntry.BP_SliderEntry_C.SetValue
struct UBP_SliderEntry_C_SetValue_Params
{
float Value; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_SliderEntry.BP_SliderEntry_C.GetPercent
struct UBP_SliderEntry_C_GetPercent_Params
{
float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function BP_SliderEntry.BP_SliderEntry_C.GetNumericValue
struct UBP_SliderEntry_C_GetNumericValue_Params
{
struct FText ReturnValue; // (Parm, OutParm, ReturnParm)
};
// Function BP_SliderEntry.BP_SliderEntry_C.BndEvt__TestSlider_K2Node_ComponentBoundEvent_4_OnFloatValueChangedEvent__DelegateSignature
struct UBP_SliderEntry_C_BndEvt__TestSlider_K2Node_ComponentBoundEvent_4_OnFloatValueChangedEvent__DelegateSignature_Params
{
float Value; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_SliderEntry.BP_SliderEntry_C.BndEvt__sliderEntry_K2Node_ComponentBoundEvent_10_OnButtonHoverEvent__DelegateSignature
struct UBP_SliderEntry_C_BndEvt__sliderEntry_K2Node_ComponentBoundEvent_10_OnButtonHoverEvent__DelegateSignature_Params
{
};
// Function BP_SliderEntry.BP_SliderEntry_C.BndEvt__NumericDisplay_K2Node_ComponentBoundEvent_136_OnEditableTextChangedEvent__DelegateSignature
struct UBP_SliderEntry_C_BndEvt__NumericDisplay_K2Node_ComponentBoundEvent_136_OnEditableTextChangedEvent__DelegateSignature_Params
{
struct FText Text; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm)
};
// Function BP_SliderEntry.BP_SliderEntry_C.BndEvt__NumericDisplay_K2Node_ComponentBoundEvent_150_OnEditableTextCommittedEvent__DelegateSignature
struct UBP_SliderEntry_C_BndEvt__NumericDisplay_K2Node_ComponentBoundEvent_150_OnEditableTextCommittedEvent__DelegateSignature_Params
{
struct FText Text; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm)
TEnumAsByte<ETextCommit> CommitMethod; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_SliderEntry.BP_SliderEntry_C.ExecuteUbergraph_BP_SliderEntry
struct UBP_SliderEntry_C_ExecuteUbergraph_BP_SliderEntry_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function BP_SliderEntry.BP_SliderEntry_C.OnHovered__DelegateSignature
struct UBP_SliderEntry_C_OnHovered__DelegateSignature_Params
{
};
// Function BP_SliderEntry.BP_SliderEntry_C.OnValueChanged__DelegateSignature
struct UBP_SliderEntry_C_OnValueChanged__DelegateSignature_Params
{
float Value; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"hsibma02@gmail.com"
] | hsibma02@gmail.com |
26d85229856a386aedd91945b7a14fd829bff570 | 2e16d032c5f64036a13a6ecd2c939e69dcce306f | /BOJ/loop practice/boj2742.cpp | 56c76f82095a7d245c429ca67bf3da39bd7d6ca2 | [] | no_license | hjhng125/Algorithm | 3a5431119763a417552c33e7bb1d2af675afca8b | 84feea3c3f897ff5d99af82f829eba64bc7b848f | refs/heads/master | 2021-06-04T12:27:18.796332 | 2020-09-19T09:58:38 | 2020-09-19T09:58:38 | 108,951,442 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 138 | cpp | #include<cstdio>
using namespace std;
int main()
{
int n;
scanf("%d", &n);
for (int i = n; i > 0; --i) {
printf("%d\n", i);
}
}
| [
"33080926+hjhng125@users.noreply.github.com"
] | 33080926+hjhng125@users.noreply.github.com |
8f4ea889cfffcd838aedcfa02fae5a19f56879aa | 80b10a9a27c4db09ea6659be03e9bf7b12e80255 | /leetcode/961.cpp | 5a952cbe43f1d404d8ccdabd027c37d8e144aa6b | [] | no_license | HhTtLllL/algorithm | e1d777672dc8abdac9207ed7ea4b17a4efcbe9f3 | 4e331cb6dd15d9a6b8ff6ce6b61fa3887a05f9f8 | refs/heads/master | 2021-09-06T20:50:24.157469 | 2021-08-11T11:49:41 | 2021-08-11T11:49:41 | 203,563,187 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 939 | cpp | /*
* 执行用时:56ms
* 内存小号 10.7mb
*/
class Solution {
public:
int repeatedNTimes(vector<int>& A)
{
sort(A.begin(),A.end());
for(int i = 0;i < A.size()-1;i++)
{
if(A[i] == A[i+1])
{
return A[i];
}
}
}
};
/*
*执行用时 1420ms
*内存小韩 10.5mb
*/
class Solution {
public:
int repeatedNTimes(vector<int>& A)
{
int flag = 0;
for(auto i : A)
{
int time = 0;
for(auto j : A)
{
if(i == j) time++;
if(time > 1)
{
flag = i;
break;
}
}
}
return flag;
}
};
| [
"1430249706@qq.com"
] | 1430249706@qq.com |
3cb430391690f2532ac10dea7a45f9c15e5568e7 | 9d2c6126b875e2900f1b6664923956e12fac8741 | /HashTable/HashEntry.h | 225530088fe05aebc83cfaefb22ba3f8e31c2bdd | [] | no_license | strasvoul/Data-Structures | e328bc5d730cbec4a92f24f16e66145439ef14e6 | 8766a1920d9fdccc5bcec2104734a82c0113e27d | refs/heads/master | 2022-01-12T21:43:42.160276 | 2019-07-21T23:06:03 | 2019-07-21T23:06:03 | 198,112,826 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 281 | h | #ifndef DATA_STRUCTURES_HASHENTRY_H
#define DATA_STRUCTURES_HASHENTRY_H
class HashEntry {
private:
int key;
int value;
public:
HashEntry(int key, int value);
int getKey() {return key;}
int getValue() {return value;}
};
#endif //DATA_STRUCTURES_HASHENTRY_H
| [
"voulefst@csd.auth.gr"
] | voulefst@csd.auth.gr |
9b3959490b3d57145df584c152a3810cc15df121 | 667bbfd99d40a077a6cec48208b03b8d10ce3631 | /Step3/AquaLand/Testing/CFishBetaTest.cpp | c41d682e337ebb4a2999007a5a817bf1e17c46b0 | [] | no_license | Chanduniverse/CSE-335-Projects | 6cca3cbf5791d21dd031c90484e9a7c09c2501d9 | ae3b79e1314c92e0a599b2100c7ed941593f2a61 | refs/heads/main | 2023-04-24T05:03:07.103104 | 2021-05-10T21:49:24 | 2021-05-10T21:49:24 | 366,182,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,236 | cpp | /**
* \file CFishBetaTest.cpp
*
* \author Chandan Aralikatti
*
* Handles beta fish tests
*/
#include "pch.h"
#include "CppUnitTest.h"
#include "Aquarium.h"
#include "Item.h"
#include "FishBeta.h"
#include <memory>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace std;
/// Fish filename
const std::wstring FishBetaImageName = L"images/beta.png";
namespace Testing
{
/** Mock class for testing CItem */
class CItemMock : public CItem
{
public:
/** Constructor
* \param aquarium The aquarium this is a member of */
CItemMock(CAquarium* aquarium) :
CItem(aquarium, FishBetaImageName) {}
/** Draw the item
* \param graphics The graphics context to draw on */
virtual void Draw(Gdiplus::Graphics* graphics) {}
/** Test to see if we clicked on this item
* \param x X location
* \param y Y location
* \returns true if we did click on the item */
virtual bool HitTest(int x, int y) { return false; }
};
TEST_CLASS(CFishBetaTest)
{
public:
TEST_METHOD_INITIALIZE(methodName)
{
extern wchar_t g_dir[];
::SetCurrentDirectory(g_dir);
}
TEST_METHOD(TestCFishBetaConstruct)
{
CAquarium aquarium;
CFishBeta FishBeta(&aquarium);
}
};
} | [
"chand4ara@gmail.com"
] | chand4ara@gmail.com |
f9bd5e61cd133a88d36b242ff01ca88dc9039260 | d84e999bbda0cca6566df7462255261c9c88840c | /libbuild2/adhoc-rule-buildscript.hxx | b863d77d2e05c3e0a9325f1695a08e711f80e0a1 | [
"MIT"
] | permissive | aminya/build2 | a278119b1f83db657befa66d8d74d1a407f9295e | 9298908b00c1977fcce5a3ac8e29e982cc28c97f | refs/heads/master | 2023-01-22T00:56:50.932805 | 2020-09-15T16:28:08 | 2020-09-17T12:35:13 | 296,840,160 | 0 | 0 | MIT | 2020-09-19T10:11:16 | 2020-09-19T10:11:15 | null | UTF-8 | C++ | false | false | 1,410 | hxx | // file : libbuild2/adhoc-rule-buildscript.hxx -*- C++ -*-
// license : MIT; see accompanying LICENSE file
#ifndef LIBBUILD2_ADHOC_RULE_BUILDSCRIPT_HXX
#define LIBBUILD2_ADHOC_RULE_BUILDSCRIPT_HXX
#include <libbuild2/types.hxx>
#include <libbuild2/forward.hxx>
#include <libbuild2/utility.hxx>
#include <libbuild2/rule.hxx>
#include <libbuild2/build/script/script.hxx>
namespace build2
{
// Ad hoc buildscript rule.
//
// Note: not exported and should not be used directly (i.e., registered).
//
class adhoc_buildscript_rule: public adhoc_rule
{
public:
virtual bool
match (action, target&, const string&, optional<action>) const override;
virtual recipe
apply (action, target&) const override;
target_state
perform_update_file (action, const target&) const;
target_state
default_action (action, const target&) const;
adhoc_buildscript_rule (const location& l, size_t b)
: adhoc_rule ("<ad hoc buildscript recipe>", l, b) {}
virtual bool
recipe_text (context&, const target&, string&&, attributes&) override;
virtual void
dump_attributes (ostream&) const override;
virtual void
dump_text (ostream&, string&) const override;
public:
using script_type = build::script::script;
script_type script;
string checksum; // Script text hash.
};
}
#endif // LIBBUILD2_ADHOC_RULE_BUILDSCRIPT_HXX
| [
"boris@codesynthesis.com"
] | boris@codesynthesis.com |
4624352eece0e4654f399299a56636a62e991179 | 14f55d06a88cbd4974517746dceb52296f6b8423 | /MyArray.hpp | 732210635170932bbf58277c44b6c577f73080f4 | [] | no_license | JoshDHoeg/3D-Model-Builder | d8db0c0b22628c33089b09fedea31fa0b31ea191 | e2212ebb76d6671f0a0578f04134fa87398dbbb2 | refs/heads/master | 2021-08-15T23:25:55.492514 | 2017-11-18T14:21:16 | 2017-11-18T14:21:16 | 111,211,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,553 | hpp | //
// DynamicArray.h
// Homework6
//
// Created by Ben Jones on 2/24/17.
// Copyright © 2017 Ben Jones. All rights reserved.
//
#pragma once
#include <cassert>
#include <algorithm> //for std::max
template<typename T>
class MyArray{
public:
//make at least a 20 element array
MyArray(size_t initialSize = 0) {
if (initialSize <= 20) {
capacity = 20;
}
else if (initialSize > 20) {
capacity = initialSize;
}
size = initialSize;
data = new T[capacity];
};
MyArray(const MyArray<T>& other);
MyArray& operator=(const MyArray<T>& other);
~MyArray();
T Get(size_t index) const;
void Set(T v, size_t index);
size_t Size() const { return size; }
T Back() const { assert(size > 0); return Get(size -1); }
void PushBack(T val);
void PopBack(){ --size; }
void Resize(size_t newSize);
private:
T* data;
size_t size, capacity;
};
template<typename T>
MyArray<T>::MyArray(const MyArray<T>& other){
size = other.size;
capacity = other.capacity;
data = new T[capacity];
for(int i = 0; i < size; i++){ //don't worry about stuff between size and capacity
data[i] = other.data[i]; //calls operator =, so should make deep copies
}
}
template<typename T>
MyArray<T>& MyArray<T>::operator=(const MyArray<T>& other){
if(this == &other){return *this;}
delete [] data;
size = other.size;
capacity = other.capacity;
data = new T[capacity];
for(int i = 0; i < size; i++){
data[i] = other.data[i]; //calls operator =, so should make deep copies
}
return *this;
}
template<typename T>
MyArray<T>::~MyArray(){
delete[] data;
data = nullptr;
size = 0;
capacity = 0;
}
template <typename T>
T MyArray<T>::Get(size_t index) const{
assert(index < size);
return data[index];
}
template<typename T>
void MyArray<T>::Set(T val, size_t index){
assert(index < size);
data[index] = val;
}
template<typename T>
void MyArray<T>::PushBack(T val){
if(size == capacity){
size_t oldSize = size;
Resize(2*capacity);
size = oldSize; //resize changes the size, but we don't want to do that.
}
data[size++] = val; //use the old value of size and then add 1 to it
}
template<typename T>
void MyArray<T>::Resize(size_t newSize){
T* newData = new T[newSize];
for(int i = 0; i < std::min(size, newSize); i++){
newData[i] = data[i];
}
capacity = newSize;
size = newSize;
delete[] data;
data = newData;
}
| [
"jdhoeg97@gmail.com"
] | jdhoeg97@gmail.com |
1dc42244ef80615235c80514eafc433f41e04511 | b20353e26e471ed53a391ee02ea616305a63bbb0 | /trunk/game/gac_gas/ComGacGas/TFighterCtrlInfo_inl.inl | ddb9914d0b11cc0b01fc7571f51e14e8046a384e | [] | no_license | trancx/ybtx | 61de88ef4b2f577e486aba09c9b5b014a8399732 | 608db61c1b5e110785639d560351269c1444e4c4 | refs/heads/master | 2022-12-17T05:53:50.650153 | 2020-09-19T12:10:09 | 2020-09-19T12:10:09 | 291,492,104 | 0 | 0 | null | 2020-08-30T15:00:16 | 2020-08-30T15:00:15 | null | UTF-8 | C++ | false | false | 329 | inl | #pragma once
#include "TFighterCtrlInfo.h"
template<typename CtrlType>
template<typename FighterInfoType>
bool TFighterCtrlInfo<CtrlType>::IntSetCtrlState(FighterInfoType* pInfo,EFighterCtrlState eState,bool bSet)
{
if( !CppIsAlive() )
return false;
m_pAliveState->SetState(pInfo,eState,bSet);
return true;
}
| [
"CoolManBob@a2c23ad7-41ce-4a1d-83b7-33535e6483ee"
] | CoolManBob@a2c23ad7-41ce-4a1d-83b7-33535e6483ee |
1cea6be4548378d72acf733223ad34668b6d13c4 | 612325535126eaddebc230d8c27af095c8e5cc2f | /src/net/cert/sth_distributor.cc | a323f4e0b21e9b3482b1a86dfc384f20484eb41b | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/proto-quic_1V94 | 1a3a03ac7a08a494b3d4e9857b24bb8f2c2cd673 | feee14d96ee95313f236e0f0e3ff7719246c84f7 | refs/heads/master | 2023-04-01T14:36:53.888576 | 2019-10-17T02:23:04 | 2019-10-17T02:23:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,384 | cc | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/cert/sth_distributor.h"
#include "base/metrics/histogram_macros.h"
#include "base/time/time.h"
#include "net/cert/signed_tree_head.h"
namespace {
const uint8_t kPilotLogID[] = {0xa4, 0xb9, 0x09, 0x90, 0xb4, 0x18, 0x58, 0x14,
0x87, 0xbb, 0x13, 0xa2, 0xcc, 0x67, 0x70, 0x0a,
0x3c, 0x35, 0x98, 0x04, 0xf9, 0x1b, 0xdf, 0xb8,
0xe3, 0x77, 0xcd, 0x0e, 0xc8, 0x0d, 0xdc, 0x10};
}
namespace net {
namespace ct {
STHDistributor::STHDistributor()
: observer_list_(base::ObserverList<STHObserver>::NOTIFY_EXISTING_ONLY) {}
STHDistributor::~STHDistributor() {}
void STHDistributor::NewSTHObserved(const SignedTreeHead& sth) {
auto it = std::find_if(observed_sths_.begin(), observed_sths_.end(),
[&sth](const SignedTreeHead& other) {
return sth.log_id == other.log_id;
});
if (it == observed_sths_.end())
observed_sths_.push_back(sth);
else
*it = sth;
for (auto& observer : observer_list_)
observer.NewSTHObserved(sth);
if (sth.log_id.compare(0, sth.log_id.size(),
reinterpret_cast<const char*>(kPilotLogID),
sizeof(kPilotLogID)) != 0)
return;
const base::TimeDelta sth_age = base::Time::Now() - sth.timestamp;
UMA_HISTOGRAM_CUSTOM_TIMES("Net.CertificateTransparency.PilotSTHAge", sth_age,
base::TimeDelta::FromHours(1),
base::TimeDelta::FromDays(4), 100);
}
void STHDistributor::RegisterObserver(STHObserver* observer) {
observer_list_.AddObserver(observer);
// Make a local copy, because notifying the |observer| of a
// new STH may result in this class being notified of a
// (different) new STH, thus invalidating the iterator.
std::vector<SignedTreeHead> local_sths(observed_sths_);
for (const auto& sth : local_sths)
observer->NewSTHObserved(sth);
}
void STHDistributor::UnregisterObserver(STHObserver* observer) {
observer_list_.RemoveObserver(observer);
}
} // namespace ct
} // namespace net
| [
"2100639007@qq.com"
] | 2100639007@qq.com |
9512de4252f1a44adf0acfe857129853e347fed2 | 41fead7e3b4d175d57a01952ec19a5ccb8ed8571 | /clientData.h | 977d7b3d3285c5c01b6d9bc9eb21b409d7435fcc | [] | no_license | caioguedesam/message_network_posix | 0a64ff1c3051131862aaeadd2378be0e4ecb49e9 | c9a09685b32e79c7f5e3d4d9baf92ad9b390f1e9 | refs/heads/master | 2023-02-13T22:45:16.542973 | 2021-01-10T21:02:08 | 2021-01-10T21:02:08 | 327,718,409 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 232 | h | #ifndef CLIENT_DATA_H
#define CLIENT_DATA_H
#include <sys/socket.h>
#include <string.h>
class ClientData {
public:
int socket;
sockaddr_storage storage;
ClientData(int socket, sockaddr_storage *storage);
};
#endif | [
"caioguedesam@gmail.com"
] | caioguedesam@gmail.com |
8e3f9eaa38c0212d05f5a7651d597928afcba9c4 | 2cf838b54b556987cfc49f42935f8aa7563ea1f4 | /aws-cpp-sdk-iotsitewise/include/aws/iotsitewise/model/GetAssetPropertyAggregatesResult.h | 0abdddabfaf0a31e472f7e9d8598248b6ff3c392 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | QPC-database/aws-sdk-cpp | d11e9f0ff6958c64e793c87a49f1e034813dac32 | 9f83105f7e07fe04380232981ab073c247d6fc85 | refs/heads/main | 2023-06-14T17:41:04.817304 | 2021-07-09T20:28:20 | 2021-07-09T20:28:20 | 384,714,703 | 1 | 0 | Apache-2.0 | 2021-07-10T14:16:41 | 2021-07-10T14:16:41 | null | UTF-8 | C++ | false | false | 4,020 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/iotsitewise/IoTSiteWise_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/iotsitewise/model/AggregatedValue.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace IoTSiteWise
{
namespace Model
{
class AWS_IOTSITEWISE_API GetAssetPropertyAggregatesResult
{
public:
GetAssetPropertyAggregatesResult();
GetAssetPropertyAggregatesResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
GetAssetPropertyAggregatesResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The requested aggregated values.</p>
*/
inline const Aws::Vector<AggregatedValue>& GetAggregatedValues() const{ return m_aggregatedValues; }
/**
* <p>The requested aggregated values.</p>
*/
inline void SetAggregatedValues(const Aws::Vector<AggregatedValue>& value) { m_aggregatedValues = value; }
/**
* <p>The requested aggregated values.</p>
*/
inline void SetAggregatedValues(Aws::Vector<AggregatedValue>&& value) { m_aggregatedValues = std::move(value); }
/**
* <p>The requested aggregated values.</p>
*/
inline GetAssetPropertyAggregatesResult& WithAggregatedValues(const Aws::Vector<AggregatedValue>& value) { SetAggregatedValues(value); return *this;}
/**
* <p>The requested aggregated values.</p>
*/
inline GetAssetPropertyAggregatesResult& WithAggregatedValues(Aws::Vector<AggregatedValue>&& value) { SetAggregatedValues(std::move(value)); return *this;}
/**
* <p>The requested aggregated values.</p>
*/
inline GetAssetPropertyAggregatesResult& AddAggregatedValues(const AggregatedValue& value) { m_aggregatedValues.push_back(value); return *this; }
/**
* <p>The requested aggregated values.</p>
*/
inline GetAssetPropertyAggregatesResult& AddAggregatedValues(AggregatedValue&& value) { m_aggregatedValues.push_back(std::move(value)); return *this; }
/**
* <p>The token for the next set of results, or null if there are no additional
* results.</p>
*/
inline const Aws::String& GetNextToken() const{ return m_nextToken; }
/**
* <p>The token for the next set of results, or null if there are no additional
* results.</p>
*/
inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }
/**
* <p>The token for the next set of results, or null if there are no additional
* results.</p>
*/
inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }
/**
* <p>The token for the next set of results, or null if there are no additional
* results.</p>
*/
inline void SetNextToken(const char* value) { m_nextToken.assign(value); }
/**
* <p>The token for the next set of results, or null if there are no additional
* results.</p>
*/
inline GetAssetPropertyAggregatesResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}
/**
* <p>The token for the next set of results, or null if there are no additional
* results.</p>
*/
inline GetAssetPropertyAggregatesResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}
/**
* <p>The token for the next set of results, or null if there are no additional
* results.</p>
*/
inline GetAssetPropertyAggregatesResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}
private:
Aws::Vector<AggregatedValue> m_aggregatedValues;
Aws::String m_nextToken;
};
} // namespace Model
} // namespace IoTSiteWise
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
9eb6bec8d5612be6a30db9ce397502b62197882d | 228b25458e74199b18bfcdd0d1dc400e39e4a651 | /old/11653/main.cpp | 86a4e8dfb77487000ecd88a9296f124618afe913 | [] | no_license | luxroot/baekjoon | 9146f18ea345d6998e471439117516f2ea26f22c | ed40287fd53ae1f41d2958c68e6e04d498d528b9 | refs/heads/master | 2023-06-27T05:50:41.303356 | 2021-08-06T04:18:33 | 2021-08-06T04:18:33 | 111,078,357 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 255 | cpp | #include <iostream>
using namespace std;
int main()
{
int n,i,j;
cin >> n;
for(i=2;i<=n;i++){
while(n % i == 0){
n /= i;
cout << i << '\n';
}
if(n == 1)
break;
}
return 0;
} | [
"shinmg2520@gmail.com"
] | shinmg2520@gmail.com |
01b6b613505d7b51885a87f7b2289841e66fcb19 | 20d79721a01b0304dcc8cdfa8a75997682f0ee5c | /modules/cvutil/include/cvsql.h | 64b594edb86bf550e0c14bee4e8ff9eec54e0c27 | [
"MIT"
] | permissive | liangfu/dnn | e94c27a0e354e93cf1054c68634e445b3c31e37e | 526e965992a7afe337e20e2d026b4c05697d70cd | refs/heads/master | 2020-12-29T01:31:47.279715 | 2018-04-20T03:18:17 | 2018-04-20T03:18:17 | 57,319,843 | 13 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,305 | h | /**
* @file cvsql.h
* @author Liangfu Chen <liangfu.chen@nlpr.ia.ac.cn>
* @date Tue Aug 6 11:58:37 2013
*
* @brief
*
*
*/
#ifndef __CV_SQL_H__
#define __CV_SQL_H__
#include <sqlite3.h>
static
int icvSqlCallback(void *notused, int argc, char **argv, char **col){
int i;
for(i=0; i<argc; i++){
printf("%s = %s\n", col[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
static
int icvSqlCountCb(void * retval, int argc, char **argv, char **col){
*(int*)retval=atoi(argv[0]);
return 0;
}
class CvSql
{
sqlite3 * db;
int check_error(int rc){
int failed=0;
if ((rc!=SQLITE_OK)&&(rc!=SQLITE_DONE)){
LOGE("%s",sqlite3_errmsg(db));
failed=1;sqlite3_close(db);db=NULL;
}else{failed=0;}
return failed;
}
public:
CvSql():db(NULL){}
~CvSql(){ close(); }
int connected() { return (db!=NULL); }
int connect(const char * dbname){
int rc;
rc = sqlite3_open(dbname, &db);
check_error(rc);
#ifdef ANDROID
LOGI("database %s connect success!",dbname);
#else
if (rc!=SQLITE_OK){LOGE("can't connect database at location %s",dbname);}
//else{LOGI("database connected at location %s",dbname);}
#endif //ANDROID
return (rc==SQLITE_OK)?1:-1;
}
int close() {
if (db) { int rc=sqlite3_close(db); check_error(rc); db=NULL;}
return 1;
}
int execute(const char * stmt){
int rc;char * errmsg;
rc = sqlite3_exec(db,stmt,icvSqlCallback,0,&errmsg);
check_error(rc);
return rc;
}
int count(const char * table){
if (!db){return -1;}
int rc;char * errmsg;
char stmt[0xff]; int retval=-1;
sprintf(stmt,"select count(*) from %s", table);
rc = sqlite3_exec(db,stmt,icvSqlCountCb,&retval,&errmsg);
check_error(rc);
return retval;
}
int table_exists(const char * table)
{
int rc;char * errmsg;
char stmt[0xff]; int retval=-1;
sprintf(stmt,"SELECT count(name) FROM sqlite_master "
"WHERE type='table' AND name='%s'", table);
rc = sqlite3_exec(db,stmt,icvSqlCountCb,&retval,&errmsg);
check_error(rc);
return retval;
}
int insert(const char * table, const char * name,
CvMat * data, CvMat * img=0)
{
if (!db){return -1;}
assert(CV_MAT_TYPE(data->type)==CV_32F);
int failed=0;int rc;char * errmsg;
static char sql[0xff];
if (!img)
{
sprintf(sql,"insert into %s (name,data) values ('%s',?)",table,name);
}else
{
sprintf(sql,"insert into %s (name,data,img) values ('%s',?,?)",
table,name);
}
fprintf(stderr,"stmt:%s\n",sql);
// convert floating-point array to binary string as sql statement
assert(CV_MAT_TYPE(data->type)==CV_32F);
assert(data->step/sizeof(float)==data->cols);
sqlite3_stmt *stmt;
int datsize = data->cols*data->rows*sizeof(float);
fprintf(stderr,"datsize:%d\n",datsize);
rc = sqlite3_prepare_v2(db,sql,-1,&stmt,NULL);
failed=check_error(rc);
if (!failed){
rc = sqlite3_bind_blob(stmt,1,data->data.fl,datsize,SQLITE_TRANSIENT);
failed=check_error(rc);
if (img){
assert(CV_MAT_TYPE(img->type)==CV_8U);
int imgsize = img->cols*img->rows*sizeof(uchar);
fprintf(stderr,"imgsize:%d\n",imgsize);
rc = sqlite3_bind_blob(stmt,2,img->data.ptr,imgsize,SQLITE_TRANSIENT);
failed=check_error(rc);
}
}
if (!failed){ rc=sqlite3_step(stmt); failed=check_error(rc); }
if (!failed){ rc=sqlite3_finalize(stmt); failed=check_error(rc); }
return (rc==SQLITE_OK)?1:-1;
}
int select(const char * table){
if (!db){return -1;}
char stmt[0xff];
int rc,nr,nc;char * errmsg;char ** result;
sprintf(stmt,"select * from %s", table);
rc = sqlite3_get_table(db,stmt,&result,&nr,&nc,&errmsg);
//if (rc!=SQLITE_OK){fprintf(stderr,"ERROR: %s\n",errmsg);}
check_error(rc);
int i,j;
for (i=0;i<(nr+1)*nc;i++){
if (i%nc==nc-1) {
if (i>nc){
float aa[2];memcpy(aa,result[i],sizeof(aa));
fprintf(stderr," %f,%f, ...",aa[0],aa[1]);
}else{
fprintf(stderr,"%18s ",result[i]);
}
}else{
fprintf(stderr,"%8s ",result[i]);
}
if (i%nc==nc-1) {fprintf(stderr,"\n");};
}
fprintf(stderr,"INFO: table %s query success (%dx%d)!\n", table,nr,nc);
sqlite3_free_table(result);
return rc;
}
int query_int(const char * table, int rid, const char * col)
{
if (!db){return -1;}
char sql[0xff];
int rc,nr,nc;char * errmsg;
sprintf(sql,"select %s from %s", col, table);
char ** result;
rc = sqlite3_get_table(db,sql,&result,&nr,&nc,&errmsg);
check_error(rc);
int retval=atoi(result[rid]);
sqlite3_free_table(result);
return retval;
}
int query(const char * table, const char * condition, const char * col,
void * data, int bytes)
{
if (!db){return -1;}
char sql[0xff];
int rc,nr,nc;char * errmsg;
sprintf(sql,"select %s from %s %s", col, table, condition);
sqlite3_stmt * stmt;
rc=sqlite3_prepare_v2(db,sql,strlen(sql)+1,&stmt,NULL); check_error(rc);
sqlite3_step(stmt);
memcpy(data,sqlite3_column_blob(stmt,0),bytes);
sqlite3_step(stmt);
sqlite3_finalize(stmt);
return 1;
}
};
#endif //__CV_SQL_H__
| [
"liangfu.chen@nlpr.ia.ac.cn"
] | liangfu.chen@nlpr.ia.ac.cn |
71bb4065ba82ef68d60eb816bec34031709ad1ab | e6e7b7e4d923d846a6b39480aaa2d659462a8cf5 | /src/model/ControlCenter.cpp | f270a129df4aa1d6a838dc1887c0db2fa323814c | [] | no_license | ramsondon/DeltaControl | 24828afd222c6fb47ec62e72555083faa8187517 | 6cd05a4591dff924488572254f6172722d9689ce | refs/heads/master | 2021-01-13T01:27:37.950168 | 2012-02-24T14:27:40 | 2012-02-24T14:27:40 | 3,282,871 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 7,458 | cpp | /*
* ControlCenter.cpp
*
* Created on: Feb 8, 2012
* Author: matthias
*/
#include <OgreSceneManager.h>
#include <OgreMeshManager.h>
#include <OgreResourceGroupManager.h>
#include <OgreEntity.h>
#include "ControlCenter.h"
ControlCenter::ControlCenter(Ogre::SceneManager* sceneMgr) {
mSceneMgr = sceneMgr;
setup();
}
ControlCenter::~ControlCenter() {
}
void ControlCenter::setup()
{
setupFloor();
setupRoof();
setupWalls();
}
void ControlCenter::setupFloor()
{
Ogre::Plane plane;
plane.normal = Ogre::Vector3::UNIT_Y;
// horizontal plane with normal up in y-direction
plane.d = 0; //Plane passes through the origin i.e. plane at y = 0
Ogre::MeshManager::getSingleton().createPlane("floor",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, plane,
ROOM_WIDTH, ROOM_LENGTH, 1, 1, true, 1, 12, 12,
Ogre::Vector3::UNIT_Z);
Ogre::Entity* pPlaneEnt = mSceneMgr->createEntity("plane", "floor");
pPlaneEnt->setMaterialName("floor");
pPlaneEnt->setCastShadows(false);
Ogre::SceneNode* floorNode = mSceneMgr->createSceneNode("floor1");
mSceneMgr->getRootSceneNode()->addChild(floorNode);
floorNode->attachObject(pPlaneEnt);
}
void ControlCenter::setupRoof() {
// Tap
Ogre::Plane planeTap;
planeTap.normal = Ogre::Vector3::UNIT_Y;
planeTap.d = 0; //Plane passes through the origin i.e. plane at y = 0
Ogre::MeshManager::getSingleton().createPlane("tap",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, planeTap,
ROOM_WIDTH, ROOM_LENGTH, 1, 1, true, 1, 12, 12,
Ogre::Vector3::UNIT_Z);
Ogre::Entity* tapEntity = mSceneMgr->createEntity("tap", "tap");
tapEntity->setMaterialName("roof_white");
tapEntity->setCastShadows(false);
Ogre::SceneNode* tapNode = mSceneMgr->createSceneNode("tap");
mSceneMgr->getRootSceneNode()->addChild(tapNode);
tapNode->attachObject(tapEntity);
tapNode->pitch(Ogre::Degree(180));
tapNode->setPosition(0, ROOM_HEIGHT, 0);
}
void ControlCenter::setupWalls()
{
/* *******************************************************
* WALL PLANES
* *******************************************************/
setupWindowWall();
setupWoodenWalls();
Ogre::Plane planeWall1;
planeWall1.normal = Ogre::Vector3::UNIT_Z;
// horizontal plane with normal up in y-direction
planeWall1.d = 0; //Plane passes through the origin i.e. plane at y = 0
Ogre::MeshManager::getSingleton().createPlane("wallright",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, planeWall1,
ROOM_WIDTH, ROOM_HEIGHT, 12, 12, true, 1, 12, 12, Ogre::Vector3::UNIT_Y);
mWallRight = mSceneMgr->createEntity("wallright", "wallright");
mWallRight->setMaterialName("wall_light_grey");
mWallRight->setCastShadows(false);
Ogre::SceneNode* wallNode1 = mSceneMgr->createSceneNode("wallright");
mSceneMgr->getRootSceneNode()->addChild(wallNode1);
wallNode1->attachObject(mWallRight);
wallNode1->setPosition(0,ROOM_HEIGHT/2, -ROOM_LENGTH/2);
Ogre::Plane planeWall2;
planeWall2.normal = Ogre::Vector3::UNIT_Z;
// horizontal plane with normal up in y-direction
planeWall2.d = 0; //Plane passes through the origin i.e. plane at y = 0
Ogre::MeshManager::getSingleton().createPlane("wallleft",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, planeWall2,
ROOM_WIDTH, ROOM_HEIGHT, 12, 12, true, 1, 12, 12, Ogre::Vector3::UNIT_Y);
mWallLeft = mSceneMgr->createEntity("wallleft", "wallleft");
mWallLeft->setMaterialName("wall_light_grey");
mWallLeft->setCastShadows(false);
Ogre::SceneNode* wallNode2 = mSceneMgr->createSceneNode("wallleft");
mSceneMgr->getRootSceneNode()->addChild(wallNode2);
wallNode2->attachObject(mWallLeft);
wallNode2->rotate(Ogre::Vector3(-ROOM_LENGTH/2, 0, 0), Ogre::Radian(45),
Ogre::Node::TS_WORLD);
wallNode2->setPosition(0, ROOM_HEIGHT/2, ROOM_LENGTH/2);
// wall length
Ogre::Plane planeWall4;
planeWall4.normal = Ogre::Vector3::UNIT_Z;
// horizontal plane with normal up in y-direction
planeWall4.d = 0; //Plane passes through the origin i.e. plane at y = 0
Ogre::MeshManager::getSingleton().createPlane("wallback",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, planeWall4,
ROOM_LENGTH, ROOM_HEIGHT, 12, 12, true, 1, 12, 12, Ogre::Vector3::UNIT_Y);
mWallBack = mSceneMgr->createEntity("wallback", "wallback");
mWallBack->setMaterialName("wall_light_grey");
mWallBack->setCastShadows(false);
Ogre::SceneNode* wallNode4 = mSceneMgr->createSceneNode("wallback");
mSceneMgr->getRootSceneNode()->addChild(wallNode4);
wallNode4->attachObject(mWallBack);
wallNode4->yaw(Ogre::Degree(270));
wallNode4->setPosition(ROOM_WIDTH/2, ROOM_HEIGHT/2, 0);
}
void ControlCenter::setupWindowWall()
{
// wall glass
Ogre::Plane planeWall3;
planeWall3.normal = Ogre::Vector3::UNIT_Z;
planeWall3.d = 0;
Ogre::MeshManager::getSingleton().createPlane("window",
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, planeWall3,
ROOM_LENGTH, ROOM_HEIGHT, 12, 12, true, 1, 12, 12, Ogre::Vector3::UNIT_Y);
Ogre::Entity* winEnt = mSceneMgr->createEntity("window", "window");
winEnt->setMaterialName("window");
Ogre::SceneNode* winNode = mSceneMgr->createSceneNode("window");
mSceneMgr->getRootSceneNode()->addChild(winNode);
winNode->attachObject(winEnt);
winNode->yaw(Ogre::Degree(90));
winNode->setPosition(-ROOM_WIDTH/2+1, ROOM_HEIGHT/2, 0);
mPillarRight = mSceneMgr->createEntity("pillarright", "Cube.mesh");
Ogre::SceneNode* pillarN1 = mSceneMgr->createSceneNode("pillarright");
mSceneMgr->getRootSceneNode()->addChild(pillarN1);
pillarN1->attachObject(mPillarRight);
pillarN1->scale(0.5, 8, 0.5);
pillarN1->setPosition(-ROOM_WIDTH/2+12, 0, ROOM_LENGTH/2+156);
mPillarRight->setMaterialName("pillar");
mPillarLeft = mSceneMgr->createEntity("pillarleft", "Cube.mesh");
Ogre::SceneNode* pillarN2 = mSceneMgr->createSceneNode("pillarleft");
mSceneMgr->getRootSceneNode()->addChild(pillarN2);
pillarN2->attachObject(mPillarLeft);
pillarN2->scale(0.5, 8, 0.5);
pillarN2->setPosition(-ROOM_WIDTH/2+12, 0, -(ROOM_LENGTH/2-180));
mPillarLeft->setMaterialName("pillar");
mPillarMiddle = mSceneMgr->createEntity("pillarmiddle", "Cube.mesh");
Ogre::SceneNode* pillarN3 = mSceneMgr->createSceneNode("pillarmiddle");
mSceneMgr->getRootSceneNode()->addChild(pillarN3);
pillarN3->attachObject(mPillarMiddle);
pillarN3->scale(0.5, 8, 0.5);
pillarN3->setPosition(-ROOM_WIDTH/2+12, 0, 186);
mPillarMiddle->setMaterialName("pillar");
}
void ControlCenter::setupWoodenWalls() {
mWallFront = mSceneMgr->createEntity("wallfront", "Cube.mesh");
Ogre::SceneNode* woodenN1 = mSceneMgr->createSceneNode("wallfront");
mSceneMgr->getRootSceneNode()->addChild(woodenN1);
woodenN1->attachObject(mWallFront);
woodenN1->scale(0.3, 1.8, 17);
woodenN1->setPosition(-ROOM_WIDTH/2+8, 0, ROOM_LENGTH*7+120);
mWallFront->setMaterialName("wall_window");
}
bool ControlCenter::intersects(const Ogre::AxisAlignedBox & box) {
if (mWallBack->getWorldBoundingBox().intersects(box)) {
return true;
} else if (mWallLeft->getWorldBoundingBox().intersects(box)) {
return true;
} else if (mWallRight->getWorldBoundingBox().intersects(box)) {
return true;
} else if (mWallFront->getWorldBoundingBox().intersects(box)) {
return true;
} else if (mPillarLeft->getWorldBoundingBox().intersects(box)) {
return true;
} else if (mPillarMiddle->getWorldBoundingBox().intersects(box)) {
return true;
} else if (mPillarRight->getWorldBoundingBox().intersects(box)) {
return true;
}
return false;
}
| [
"schmid_mat@gmx.at"
] | schmid_mat@gmx.at |
b5cd08ad84aaa216b02930686665c1e1a6751ea5 | a62342d6359a88b0aee911e549a4973fa38de9ea | /0.6.0.3/Internal/SDK/BTTask_SnapToStone_parameters.h | d131c4c886e0d456808f1fa15070702298b105db | [] | no_license | zanzo420/Medieval-Dynasty-SDK | d020ad634328ee8ee612ba4bd7e36b36dab740ce | d720e49ae1505e087790b2743506921afb28fc18 | refs/heads/main | 2023-06-20T03:00:17.986041 | 2021-07-15T04:51:34 | 2021-07-15T04:51:34 | 386,165,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,948 | h | #pragma once
// Name: Medieval Dynasty, Version: 0.6.0.3
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function BTTask_SnapToStone.BTTask_SnapToStone_C.ReceiveExecuteAI
struct UBTTask_SnapToStone_C_ReceiveExecuteAI_Params
{
class AAIController* OwnerController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class APawn* ControlledPawn; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
// Function BTTask_SnapToStone.BTTask_SnapToStone_C.ReceiveAbortAI
struct UBTTask_SnapToStone_C_ReceiveAbortAI_Params
{
class AAIController* OwnerController; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
class APawn* ControlledPawn; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
// Function BTTask_SnapToStone.BTTask_SnapToStone_C.ExecuteUbergraph_BTTask_SnapToStone
struct UBTTask_SnapToStone_C_ExecuteUbergraph_BTTask_SnapToStone_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
8ee05fc2ad5a50c9045f417ea0ad6867db24cb59 | 206144923f04acfa22b9127755917df1c82ff18e | /src/MyChrome/cef/CefBase/client_renderer.cpp | 145f8f41ab829be3b11ad70486fd19224e6b6665 | [] | no_license | drivestudy/MyChrome | 5a98b36353bd4c518d9c1f796ec260590a3e495c | c34f1cafa6f417b533a0cfe9439154c9b90ecc68 | refs/heads/master | 2020-07-08T18:12:31.158318 | 2019-08-05T02:14:09 | 2019-08-05T02:14:09 | 203,741,250 | 3 | 0 | null | 2019-08-22T07:44:00 | 2019-08-22T07:43:59 | null | UTF-8 | C++ | false | false | 3,000 | cpp | // Copyright (c) 2012 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
#include "client_renderer.h"
#include <sstream>
#include <string>
#include "include/cef_dom.h"
#include "include/wrapper/cef_helpers.h"
#include "include/wrapper/cef_message_router.h"
namespace renderer {
namespace {
// Must match the value in client_handler.cc.
const char kFocusedNodeChangedMessage[] = "ClientRenderer.FocusedNodeChanged";
class ClientRenderDelegate : public ClientAppRenderer::Delegate {
public:
ClientRenderDelegate()
: last_node_is_editable_(false) {
}
virtual void OnWebKitInitialized(CefRefPtr<ClientAppRenderer> app) OVERRIDE {
// Create the renderer-side router for query handling.
CefMessageRouterConfig config;
message_router_ = CefMessageRouterRendererSide::Create(config);
}
virtual void OnContextCreated(CefRefPtr<ClientAppRenderer> app,
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context) OVERRIDE {
message_router_->OnContextCreated(browser, frame, context);
}
virtual void OnContextReleased(CefRefPtr<ClientAppRenderer> app,
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context) OVERRIDE {
message_router_->OnContextReleased(browser, frame, context);
}
virtual void OnFocusedNodeChanged(CefRefPtr<ClientAppRenderer> app,
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefDOMNode> node) OVERRIDE {
bool is_editable = (node.get() && node->IsEditable());
if (is_editable != last_node_is_editable_) {
// Notify the browser of the change in focused element type.
last_node_is_editable_ = is_editable;
CefRefPtr<CefProcessMessage> message =
CefProcessMessage::Create(kFocusedNodeChangedMessage);
message->GetArgumentList()->SetBool(0, is_editable);
browser->SendProcessMessage(PID_BROWSER, message);
}
}
virtual bool OnProcessMessageReceived(
CefRefPtr<ClientAppRenderer> app,
CefRefPtr<CefBrowser> browser,
CefProcessId source_process,
CefRefPtr<CefProcessMessage> message) OVERRIDE {
return message_router_->OnProcessMessageReceived(
browser, source_process, message);
}
private:
bool last_node_is_editable_;
// Handles the renderer side of query routing.
CefRefPtr<CefMessageRouterRendererSide> message_router_;
IMPLEMENT_REFCOUNTING(ClientRenderDelegate);
};
} // namespace
void CreateDelegates(ClientAppRenderer::DelegateSet& delegates) {
delegates.insert(new ClientRenderDelegate);
}
} // namespace renderer
| [
"yaojianing@meituan.com"
] | yaojianing@meituan.com |
25453a0266ab24fa8e086db1ee121b30b690c553 | 194b55d889315cc1b6e4f621f8c37ac8f9461f8c | /wave.cpp | 61aa5550daf6f05a5bda0e9b81d22f59bbced4f9 | [] | no_license | singhalpiyush12/8x8x8-LED-Cube | d5c33b60591772df4e474d09bfaee158b03c1d2e | 54447eabdc0760b8b9d1e4cf42f3b84df7502f25 | refs/heads/master | 2023-04-07T05:36:42.850194 | 2023-03-31T10:38:35 | 2023-03-31T10:38:35 | 122,678,419 | 11 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,097 | cpp | int DS_pin =23;
int LATCH_pin = 22;
int Clock_pin = 24;
boolean registers[72];
int dir;
void setup()
{ Serial.begin(9600);
pinMode(DS_pin, OUTPUT);
pinMode(LATCH_pin, OUTPUT);
pinMode(Clock_pin, OUTPUT);
writereg();
}
void writereg()
{
digitalWrite(LATCH_pin, LOW);
for (int i = 72 ; i>=0 ; i--)
{
digitalWrite(Clock_pin, LOW);
digitalWrite(DS_pin, registers[i]);
//dela(10);
digitalWrite(Clock_pin, HIGH);
// delay(10);
}
digitalWrite(LATCH_pin, HIGH);
}
//Single Led Function
void LED(int level, int row, int column){
if(level<0)
level=0;
if(level>7)
level=7;
if(row<0)
row=0;
if(row>7)
row=7;
if(column<0)
column=0;
if(column>7)
column=7;
registers[7-level] = HIGH;
registers[((8*column)+row)+8] = HIGH;
for(int i =71 ; i>=0 ; i--)
{
if(i==(7-level)||i==(((8*column)+row)+8))
continue;
registers[i] = LOW;
//delay(100);
writereg();
}
}
void loop()
{//EveryOff();
wave();
}
void EveryOff()
{
for(int i=0;i<72;i++)
{
registers[i]=LOW;
//delay(100);
writereg();
}
}
/*void wave()
{ //EveryOff();
int a[8];bool increase,decrease;
for(int i=0;i<8;i++)
{
registers[i]=HIGH;
for(int j=0;j<8;j++)
{registers[8*(j+1)+7-i]=HIGH;}
writereg();
registers[i]=LOW;
for(int j=0;j<8;j++)
{registers[8*(j+1)+7-i]=LOW;}
writereg();
}
}
*/
void wave()
{ //
int a[8];bool increase[8];
for(int i=0;i<8;i++)
{a[i]=i;if(i>0)increase[i]=false;
else increase[i]=true;}
int i=0;
while(i<8)
{ /*for(int j=0;j<8;j++)
{if(a[j]==0){increase=true;decrease=false;}
if(a[j]==7){decrease=true;increase=false;}
if(increase)
}
*/int k=0;
while(k<3)
{registers[a[i]]=HIGH;
for(int j=0;j<8;j++)
{registers[8*(j+1)+7-i]=HIGH;}
writereg();
registers[a[i]]=LOW;
for(int j=0;j<8;j++)
{registers[8*(j+1)+7-i]=LOW;}
writereg();
k++;
}
if(a[i]==0)increase[i]=true;
if(a[i]==7)increase[i]=false;
if(increase[i])a[i]++;
else a[i]--;
i++;
if(i==8)
i=0;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
7bb294e0d4b7392dcc03cf62f72d1332c3d62dd5 | 9cb1aff601ac7621d1f73f92cf427a3527f589ca | /Typometer.cpp | dbeedd7adb72f9785350923bf1bef40f9f1cc1a0 | [] | no_license | AbrarAdnan/typometer | 0926e579465d740c991a5429e7d230ce64d8cfaf | 5523900268597f79f1fefbf988865ed9718b5041 | refs/heads/master | 2020-09-08T19:24:18.535852 | 2019-11-12T13:25:58 | 2019-11-12T13:25:58 | 221,223,266 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,734 | cpp | #include<iostream>
#include<cstdio>
#include<stdlib.h>
#include<time.h>
#include<math.h>
#include<string.h>
#include<fstream>
#include<stdlib.h>
#include<conio.h>
using namespace std;
void sorting_function(struct structure list[80], int s); int main();void main_menu();void two_player_mode();
struct structure{
char name[20];
float score;
};
fstream file;
structure toplist;
structure backup[10];
structure input;
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
int stringLength = sizeof(alphanum) - 1;
char character()
{
return alphanum[rand() % stringLength];
}
int input_score(float score)
{
input.score=score;
cin.ignore();
cout<<"\nEnter your name :";
cin.getline(input.name,10);
file.open("Highscore.txt",ios::app);
file.write((char*)&input,sizeof(input));
file.close();
}
int show_data()
{
int i=0;
file.open("Highscore.txt",ios::in);
file.read((char*)&toplist,sizeof(toplist));
while(file.eof()==0)
{
backup[i]=toplist;
file.read((char*)&toplist,sizeof(toplist));
i++;
}
file.close();
sorting_function(backup,i);
cout<<"\nPress any key to go to the main menu";
getch();
main_menu();
}
void sorting_function(structure backup[], int s)
{
int i, j;
struct structure temp;
for (i=0;i<s;i++)
{
for (j=i+1;j<s;j++)
{
if (backup[j].score>backup[i].score)
{
temp = backup[j];
backup[j] = backup[i];
backup[i] = temp;
}
}
}
cout<<"\n\nThe high score is :\n\n"<<endl;
cout<<"Rank......score.........................name"<<endl;
for(i=0;i<10;i++)
{
cout.width(2);
cout<<i+1;
cout.width(0);
cout<<" "<<backup[i].score<<" characters/second ";
cout<<backup[i].name<<endl;
file.open("Highscore.txt",ios::trunc);
file.read((char*)&toplist,sizeof(toplist));
file.close();
}
}
void checking_score(double score)
{
int i=0;
file.open("Highscore.txt",ios::in);
file.read((char*)&toplist,sizeof(toplist));
while(file.eof()==0)
{
backup[i]=toplist;
file.read((char*)&toplist,sizeof(toplist));
i++;
}
file.close();
if(backup[i].score<score)
{
cout<<"\nCongratulations !"<<endl;
cout<<"Your score was enough for a place in the high score"<<endl;
printf("Your score = %.3f characters/second \n",score);
input_score(score);
show_data();
}
else
{
cout<<"\nSorry! Your score was not enough for a place in the high score";
cout<<"Your score was "<<score<<" characters/second \n";
}
}
void about_us()
{
system("Cls");
cout<<"\n\tTYPOMETER\n\tDeveloped and created by:\n\n\tAbrar Faiaz Adnan Dept. of ICE 3rd Batch"<<endl;
cout<<"\n\tSpecial thanks to:\n\tShamim Sir, Niloy bhai, Sakib bhai and Arafat bhai";
cout<<endl<<"\n\tPress any key to return to the main menu :";
getch();
main_menu();
}
void game()
{
system("Cls");
printf("\t\tRules of the game\n");
printf("\n=>You'll be given 3 sets of 5 random alphabets and numbers.\n=>You'll have to enter them exactly as they appear.\n");
printf("=>If you make a single mistake the game will stop.\n");
printf("=>The number of characters you enter per second will be your score.\n=>The higher the score the better\n");
printf("\n\n\n\tPress any key to start the game. Good Luck!\n");
getch();
system("Cls");
int a;
for (a=0;a<=100;a++)
{
printf("\n\n\n\n\n\n\n\n\t\t\t%d percent completed",a,037);
system("cls");
}
int i,j,random,correct=1;
char question[6],answer[6];
double start_time=0,end_time=0;
double elapsed_time=0,total=0;
char decision;
start_time=clock();
srand(time(NULL));
for(i=0;i<3;i++)
{
for(j=0;j<5;j++)
{
question[j]=character();
}
cout<<"Question: "<<question;
cout<<"\nYour Answer: ";
cin>>answer;
correct=strcmp(question,answer);
if(correct!=0)
{
printf("Wrong input. You lost.\nPress Y to restart the game or any other key to return to main menu ");
cin>>decision;
if(decision=='Y'||decision=='y')
{
game();
}
else
{
main_menu();
}
}
}
end_time=clock();
total=end_time-start_time;
elapsed_time=total/CLOCKS_PER_SEC;
float score=15/elapsed_time;
checking_score(score);
cout<<"\nPress any key to go to the main menu";
getch();
main_menu();
}
void two_player_mode()
{
float typing_speed_1,typing_speed_2;
system("Cls");
printf("\t\tRules of the game\n");
printf("\n=>You'll be given 3 sets of 5 random alphabets and numbers.\n=>You'll have to enter them exactly as they appear.\n");
printf("=>If you make a single mistake the game will stop.\n");
printf("=>The number of characters you enter per second will be your score.\nThe higher the better");
string player_one,player_two;
cout<<"Player one enter your name :";
cin>>player_one;
cout<<"Player two enter your name :";
cin>>player_two;
printf("\n\n\n\tPress any key to start the game. Good Luck ");
cout<<player_one<<"!\n";
getch();
system("Cls");
int a;
for (a=0;a<=100;a++)
{
printf("\n\n\n\n\n\n\n\n\t\t\t\tLOADING\n\t\t\t\t-------");
printf("\n\t\t\t %d percent completed",a,037);
system("cls");
}
int i,j,random,correct=1;
char question[6],answer[6];
double start_time=0,end_time=0;
double elapsed_time_1=0,total=0;
char decision;
start_time=clock();
srand(time(NULL));
for(i=0;i<3;i++)
{
for(j=0;j<5;j++)
{
question[j]=character();
}
cout<<"Question: "<<question;
cout<<"\nYour Answer: ";
cin>>answer;
correct=strcmp(question,answer);
if(correct!=0)
{
printf("\nWrong input. You lost.\nPress Y to restart the two player mode\nor any other key to return to main menu ");
cin>>decision;
if(decision=='Y'||decision=='y')
{
two_player_mode();
}
else
{
main_menu();
}
}
}
end_time=clock();
total=end_time-start_time;
elapsed_time_1=total/CLOCKS_PER_SEC;
typing_speed_1=15/elapsed_time_1;
printf("\nTyping speed of player one = %.3f character/second \n",typing_speed_1);
printf("\n\n\n\tPress any key to start the game. Good Luck ");
cout<<player_two<<"!\n";
getch();
system("Cls");
for (a=0;a<=100;a++)
{
printf("\n\n\n\n\n\n\n\n\t\t\t\tLOADING\n\t\t\t\t-------");
printf("\n\t\t\t %d percent completed",a,037);
system("cls");
}
correct=1;
start_time=0,end_time=0;
double elapsed_time_2=0;
total=0;
start_time=clock();
srand(time(NULL));
for(i=0;i<3;i++)
{
for(j=0;j<5;j++)
{
question[j]=character();
}
cout<<"Question: "<<question;
cout<<"\nYour Answer: ";
cin>>answer;
correct=strcmp(question,answer);
if(correct!=0)
{
printf("\nWrong input. You lost.\nPress Y to restart the two player mode\nor any other key to return to main menu ");
cin>>decision;
if(decision=='Y'||decision=='y')
{
two_player_mode();
}
else
{
main_menu();
}
}
}
end_time=clock();
total=end_time-start_time;
elapsed_time_2=total/CLOCKS_PER_SEC;
typing_speed_2=15/elapsed_time_2;
cout<<"\nTyping speed of "<<player_one;
printf(" = %.3f character/second \n",typing_speed_1);
cout<<"\nTyping speed of "<<player_two;
printf(" = %.3f character/second \n",typing_speed_2);
if(typing_speed_1<typing_speed_2)
{
cout<<"\nCongratulations "<<player_two<<"! You've won";
}
else if(typing_speed_1>typing_speed_2)
{
cout<<"\nCongratulations "<<player_two<<" You've won";
}
else
{
cout<<"\nBoth players scored the same. This is a one in a million event!! :o";
}
cout<<"\n\nPress y to start the two player mode again or any other key for main menu ";
cin>>decision;
if(decision=='Y'||decision=='y')
{
two_player_mode();
}
else
{
main_menu();
}
}
void main_menu()
{
system("Cls");
printf("\n\n\n\n\t\t\tMain Menu\n\t\t\t~~~~~~~~~\n\n");
printf("\t\tPress '1' to play new game\n");
printf("\t\tPress '2' to enter 2 player mode\n");
printf("\t\tPress '3' to see the high score\n");
printf("\t\tPress '4' to see the info about the game \n");
printf("\t\tPress any other key to exit the game\n");
int s;
cout<<"\n\t\tEnter your choice : ";
cin>>s;
system("Cls");
switch(s)
{
case 1: game();
break;
case 3: show_data();
break;
case 4: about_us();
break;
case 2: two_player_mode();
break;
default:
break;
}
}
main()
{
system("Cls");
printf("\n\n\t\tWelcome to Typometer\n\t\t\t-Programmed by BitCoders\n\n\n\t\tPress any key to continue");
getch();
system("Cls");
main_menu();
}
| [
"noreply@github.com"
] | noreply@github.com |
44f82527ea49bcde82f69db3e72ccb43327ea6e9 | f2d5a554a6c7d0de6e051ac7206bdf4a34d8347b | /Computer_Graphics_Algos/DDA.cpp | 53af0f1db11647ce3165bc7cb86019e0739ee890 | [] | no_license | CO18347/HACKTOBERFEST-DS-ALGOS | 44237b59f937cb594b96eb2d8cbeeba4cd02c6d3 | 3229a9986dfca79e4bf98c079303fd9bb0dd640c | refs/heads/main | 2023-08-12T08:47:53.464876 | 2021-10-06T20:21:39 | 2021-10-06T20:21:39 | 301,642,012 | 1 | 22 | null | 2021-10-05T17:36:37 | 2020-10-06T07:04:51 | C++ | UTF-8 | C++ | false | false | 1,009 | cpp | // EXP 3 - C program for DDA line generation
#include<graphics.h>
#include<stdio.h>
#include<conio.h>
#include<math.h>
void DDA(int Lx1, int Lx2, int Ly1, int Ly2) {
float x,y,dx,dy,step,x_inc,y_inc;
int i;
dx=Lx2-Lx1;
dy=Ly2-Ly1;
// calculate steps required for generating pixels
step = abs(dx) > abs(dy) ? abs(dx) : abs(dy);
x_inc=dx/step;
y_inc=dy/step;
x=Lx1;
y=Ly1;
for(i=0;i<step;i++)
{
putpixel(x+300,y+300,YELLOW);
x=x+x_inc;
y=y+y_inc;
i+=1;
}
}
int main(){
int graphicdriver=DETECT,graphicmode;
char driver[1000] = "c:\\turboc3\\bgi";
int Lx1,Lx2,Ly1,Ly2;
printf("enter the end points of the line\n");
scanf("%d %d %d %d",&Lx1,&Ly1,&Lx2,&Ly2);
// initgraph initializes the graphics system by loading a graphics driver from disk.
initgraph(&graphicdriver,&graphicmode,driver);
DDA(Lx1,Lx2,Ly1,Ly2);
getch();
closegraph();
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
fd4439d544c3ab09febd206b104e342108ff8395 | 3b9b4049a8e7d38b49e07bb752780b2f1d792851 | /src/v8/src/compiler-dispatcher/compiler-dispatcher.h | 6347aa89d3305a57e8fbf66da3f57c0c415c55ac | [
"BSD-3-Clause",
"Apache-2.0",
"SunPro",
"bzip2-1.0.6"
] | permissive | webosce/chromium53 | f8e745e91363586aee9620c609aacf15b3261540 | 9171447efcf0bb393d41d1dc877c7c13c46d8e38 | refs/heads/webosce | 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 | Apache-2.0 | 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null | UTF-8 | C++ | false | false | 7,713 | h | // Copyright 2016 the V8 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.
#ifndef V8_COMPILER_DISPATCHER_COMPILER_DISPATCHER_H_
#define V8_COMPILER_DISPATCHER_COMPILER_DISPATCHER_H_
#include <map>
#include <memory>
#include <unordered_set>
#include <utility>
#include "src/base/atomic-utils.h"
#include "src/base/macros.h"
#include "src/base/platform/condition-variable.h"
#include "src/base/platform/mutex.h"
#include "src/base/platform/semaphore.h"
#include "src/globals.h"
#include "testing/gtest/include/gtest/gtest_prod.h"
namespace v8 {
class Platform;
enum class MemoryPressureLevel;
namespace internal {
class CancelableTaskManager;
class CompilerDispatcherJob;
class CompilerDispatcherTracer;
class DeferredHandles;
class FunctionLiteral;
class Isolate;
class SharedFunctionInfo;
class Zone;
template <typename T>
class Handle;
// The CompilerDispatcher uses a combination of idle tasks and background tasks
// to parse and compile lazily parsed functions.
//
// As both parsing and compilation currently requires a preparation and
// finalization step that happens on the main thread, every task has to be
// advanced during idle time first. Depending on the properties of the task, it
// can then be parsed or compiled on either background threads, or during idle
// time. Last, it has to be finalized during idle time again.
//
// CompilerDispatcher::jobs_ maintains the list of all CompilerDispatcherJobs
// the CompilerDispatcher knows about.
//
// CompilerDispatcher::pending_background_jobs_ contains the set of
// CompilerDispatcherJobs that can be processed on a background thread.
//
// CompilerDispatcher::running_background_jobs_ contains the set of
// CompilerDispatcherJobs that are currently being processed on a background
// thread.
//
// CompilerDispatcher::DoIdleWork tries to advance as many jobs out of jobs_ as
// possible during idle time. If a job can't be advanced, but is suitable for
// background processing, it fires off background threads.
//
// CompilerDispatcher::DoBackgroundWork advances one of the pending jobs, and
// then spins of another idle task to potentially do the final step on the main
// thread.
class V8_EXPORT_PRIVATE CompilerDispatcher {
public:
enum class BlockingBehavior { kBlock, kDontBlock };
CompilerDispatcher(Isolate* isolate, Platform* platform,
size_t max_stack_size);
~CompilerDispatcher();
// Returns true if the compiler dispatcher is enabled.
bool IsEnabled() const;
// Enqueue a job for parse and compile. Returns true if a job was enqueued.
bool Enqueue(Handle<SharedFunctionInfo> function);
// Like Enqueue, but also advances the job so that it can potentially
// continue running on a background thread (if at all possible). Returns
// true if the job was enqueued.
bool EnqueueAndStep(Handle<SharedFunctionInfo> function);
// Enqueue a job for compilation. Function must have already been parsed and
// analyzed and be ready for compilation. Returns true if a job was enqueued.
bool Enqueue(Handle<Script> script, Handle<SharedFunctionInfo> function,
FunctionLiteral* literal, std::shared_ptr<Zone> parse_zone,
std::shared_ptr<DeferredHandles> parse_handles,
std::shared_ptr<DeferredHandles> compile_handles);
// Like Enqueue, but also advances the job so that it can potentially
// continue running on a background thread (if at all possible). Returns
// true if the job was enqueued.
bool EnqueueAndStep(Handle<Script> script,
Handle<SharedFunctionInfo> function,
FunctionLiteral* literal,
std::shared_ptr<Zone> parse_zone,
std::shared_ptr<DeferredHandles> parse_handles,
std::shared_ptr<DeferredHandles> compile_handles);
// Returns true if there is a pending job for the given function.
bool IsEnqueued(Handle<SharedFunctionInfo> function) const;
// Blocks until the given function is compiled (and does so as fast as
// possible). Returns true if the compile job was successful.
bool FinishNow(Handle<SharedFunctionInfo> function);
// Aborts a given job. Blocks if requested.
void Abort(Handle<SharedFunctionInfo> function, BlockingBehavior blocking);
// Aborts all jobs. Blocks if requested.
void AbortAll(BlockingBehavior blocking);
// Memory pressure notifications from the embedder.
void MemoryPressureNotification(v8::MemoryPressureLevel level,
bool is_isolate_locked);
private:
FRIEND_TEST(CompilerDispatcherTest, EnqueueAndStep);
FRIEND_TEST(CompilerDispatcherTest, EnqueueAndStepTwice);
FRIEND_TEST(CompilerDispatcherTest, EnqueueParsed);
FRIEND_TEST(CompilerDispatcherTest, EnqueueAndStepParsed);
FRIEND_TEST(CompilerDispatcherTest, IdleTaskSmallIdleTime);
FRIEND_TEST(CompilerDispatcherTest, CompileOnBackgroundThread);
FRIEND_TEST(CompilerDispatcherTest, FinishNowWithBackgroundTask);
FRIEND_TEST(CompilerDispatcherTest, AsyncAbortAllPendingBackgroundTask);
FRIEND_TEST(CompilerDispatcherTest, AsyncAbortAllRunningBackgroundTask);
FRIEND_TEST(CompilerDispatcherTest, FinishNowDuringAbortAll);
typedef std::multimap<std::pair<int, int>,
std::unique_ptr<CompilerDispatcherJob>>
JobMap;
class AbortTask;
class BackgroundTask;
class IdleTask;
void WaitForJobIfRunningOnBackground(CompilerDispatcherJob* job);
void AbortInactiveJobs();
bool CanEnqueue(Handle<SharedFunctionInfo> function);
JobMap::const_iterator GetJobFor(Handle<SharedFunctionInfo> shared) const;
void ConsiderJobForBackgroundProcessing(CompilerDispatcherJob* job);
void ScheduleMoreBackgroundTasksIfNeeded();
void ScheduleIdleTaskFromAnyThread();
void ScheduleIdleTaskIfNeeded();
void ScheduleAbortTask();
void DoBackgroundWork();
void DoIdleWork(double deadline_in_seconds);
Isolate* isolate_;
Platform* platform_;
size_t max_stack_size_;
// Copy of FLAG_trace_compiler_dispatcher to allow for access from any thread.
bool trace_compiler_dispatcher_;
std::unique_ptr<CompilerDispatcherTracer> tracer_;
std::unique_ptr<CancelableTaskManager> task_manager_;
// Mapping from (script id, function literal id) to job. We use a multimap,
// as script id is not necessarily unique.
JobMap jobs_;
base::AtomicValue<v8::MemoryPressureLevel> memory_pressure_level_;
// The following members can be accessed from any thread. Methods need to hold
// the mutex |mutex_| while accessing them.
base::Mutex mutex_;
// True if the dispatcher is in the process of aborting running tasks.
bool abort_;
bool idle_task_scheduled_;
// Number of currently scheduled BackgroundTask objects.
size_t num_scheduled_background_tasks_;
// The set of CompilerDispatcherJobs that can be advanced on any thread.
std::unordered_set<CompilerDispatcherJob*> pending_background_jobs_;
// The set of CompilerDispatcherJobs currently processed on background
// threads.
std::unordered_set<CompilerDispatcherJob*> running_background_jobs_;
// If not nullptr, then the main thread waits for the task processing
// this job, and blocks on the ConditionVariable main_thread_blocking_signal_.
CompilerDispatcherJob* main_thread_blocking_on_job_;
base::ConditionVariable main_thread_blocking_signal_;
// Test support.
base::AtomicValue<bool> block_for_testing_;
base::Semaphore semaphore_for_testing_;
DISALLOW_COPY_AND_ASSIGN(CompilerDispatcher);
};
} // namespace internal
} // namespace v8
#endif // V8_COMPILER_DISPATCHER_COMPILER_DISPATCHER_H_
| [
"changhyeok.bae@lge.com"
] | changhyeok.bae@lge.com |
871af2a6c157d57b89b5e933a9be7f4b545a3744 | e6507d57199bb681ac8c3522b5c2ef0406024a17 | /vengine/Utility/Actor.h | 65ca27753ca6c0180c3e6c791c54f483c3bdcef4 | [] | no_license | sdauwidhwa/ToolHub | a5b712180c8720c93e5035ea5390773d2e14d573 | 1905a380f06061c0708318f224a5b8a9197b2032 | refs/heads/master | 2023-08-06T02:22:48.862312 | 2021-09-10T05:02:00 | 2021-09-10T05:02:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,754 | h | #pragma once
#include <VEngineConfig.h>
#include <Common/Common.h>
struct ActorPointer {
void* ptr;
void (*disposer)(void*);
void operator=(ActorPointer const& p);
~ActorPointer();
ActorPointer(){};
ActorPointer(
void* ptr,
void (*disposer)(void*)) : ptr(ptr), disposer(disposer) {}
};
class VENGINE_DLL_COMMON Actor final : public vstd::IOperatorNewBase
{
private:
HashMap<Type, ActorPointer> hash;
void* GetComponent(Type t) const;
void RemoveComponent(Type t);
void SetComponent(Type t, void* ptr, void(*disposer)(void*));
mutable spin_mutex mtx;
public:
Actor();
Actor(uint32_t initComponentCapacity);
~Actor();
template <typename T>
T* GetComponent() const
{
return reinterpret_cast<T*>(GetComponent(typeid(T)));
}
template <typename T>
void RemoveComponent()
{
RemoveComponent(typeid(T));
}
template <typename T>
void SetComponent(T* ptr)
{
SetComponent(
typeid(T),
ptr,
[](void* pp)->void
{
delete ((T*)pp);
}
);
}
KILL_COPY_CONSTRUCT(Actor)
};
class VENGINE_DLL_COMMON ActorSingleThread final : public vstd::IOperatorNewBase {
private:
HashMap<Type, ActorPointer> hash;
void* GetComponent(Type t) const;
void RemoveComponent(Type t);
void SetComponent(Type t, void* ptr, void (*disposer)(void*));
public:
ActorSingleThread();
ActorSingleThread(uint32_t initComponentCapacity);
~ActorSingleThread();
template<typename T>
T* GetComponent() const {
return reinterpret_cast<T*>(GetComponent(typeid(T)));
}
template<typename T>
void RemoveComponent() {
RemoveComponent(typeid(T));
}
template<typename T>
void SetComponent(T* ptr) {
SetComponent(
typeid(T),
ptr,
[](void* pp) -> void {
delete ((T*)pp);
});
}
KILL_COPY_CONSTRUCT(ActorSingleThread)
}; | [
"18963092533@163.com"
] | 18963092533@163.com |
6a54192cdafcd65aa273f1247f3cfd7eaee91b79 | 3f639aefc0a5ce52f28f6131e63d01a3b2a1fa58 | /Stack.cpp | 9bca20f47d54320251195c3864f2defbde4bef72 | [] | no_license | Dbauer1010/Shunting | b16a600eb0ac90a78cc79d6d3e0df96b5604c788 | 908b532c0be5e80fa07d314db93314fe45459adc | refs/heads/master | 2021-02-16T20:12:14.487154 | 2020-04-06T22:26:15 | 2020-04-06T22:26:15 | 245,041,591 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 848 | cpp | #include "Stack.hpp"
Stack::Stack()
{
this->top = 0;
this->count = 0;
}
void Stack::display()
{
Node* currNode = this->top;
while(currNode)
{
cout << currNode->getPayload();
currNode = currNode->getNextNode();
}
cout << "\n";
}
void Stack::push(string s)
{
Node* n = new Node(s);
if(this->top)
{
n->setNextNode(this->top);
}
this->top = n;
this->count++;
}
string Stack::pop()
{
if(this->top)
{
Node* temp = this->top;
this->top = this->top->getNextNode();
string payload2Return = temp->getPayload();
delete temp;
return payload2Return;
}
return 0;
}
string Stack::peek()
{
if(this->top)
{
return this->top->getPayload();
}
return 0;
}
int Stack::getCount()
{
return this->count;
}
| [
"noreply@github.com"
] | noreply@github.com |
f781a1f18cd32dc849c88fed2ef4dbc35dec786b | 8593f6bdc4d707b6c93dfbadf6ae63c64092743f | /sources/Virologist.hpp | 758e74259e24773a05cf9b2680ac9b88b919c57a | [] | no_license | MyaraB/C-Ex4B | fa10425c579f421bd2e7729bbb9629d7c11b809e | a90da2ae5a3fac2ffb47607a0afa7bbafec206de | refs/heads/main | 2023-04-11T17:18:57.611623 | 2021-05-19T09:29:44 | 2021-05-19T09:29:44 | 368,814,179 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 269 | hpp | #include "Board.hpp"
#include "Player.hpp"
#include "City.hpp"
namespace pandemic{
class Virologist: public Player {
public:
Virologist(Board& board, City geo): Player(board, geo, "Virologist") {}
Player& treat(City geo);
};
} | [
"noreply@github.com"
] | noreply@github.com |
366d38b9fbc11f95072872729cdfe68796815d6b | a6af40877b53f7c711a7f47939f710faf77149fc | /source code/main - Copy.cpp | 8c2eb635b0bafb39206bd27b6e4dbd21dc8cf78a | [] | no_license | NextGenRecruiter/GroupProject | db888d36b04101710212c0c3ee1e7d4328818edf | f24e18f7bf314ece5f6d0de8eb5ad35e66336f34 | refs/heads/master | 2022-04-24T11:15:04.972584 | 2020-05-02T04:54:58 | 2020-05-02T04:54:58 | 258,620,972 | 0 | 0 | null | 2020-04-29T16:46:05 | 2020-04-24T20:49:31 | C++ | UTF-8 | C++ | false | false | 4,181 | cpp | /*
Authors: Jacob Hopkins, Misky Abshir, and Tyler Willard
Date: 4/27/2020
Due: 5/1/2020
TODO:
- Create SequenceSet Class in the 'SequenceSet.h' file
- Create a test driver for the class above
- Create the program for using the txt files with the class
- Create the design doccument for
- The Class
- The Test Driver
- A User Manual
- DyOxygen the Code
Specifications for a program which uses the Sequence Set class:
The application program will iterate through the sequence set displaying (neatly)
the Northernmost, Southernmost, Easternmost, and Westernmost zip code for a specified state.
{You can verify the results by sorting the Excel source data file first by state, then by longitude or by latitude}
Also, the application program, using a different set of command line flags,
will display (neatly) the State and Place Name for a specified Zip Code (or set of Zip Codes).
Run the test driver program to build the full Sequence Set file (and index file);
Run the application program specifying the Sequence Set file and the State on the command line;
Use the Unix script command to show:
the building of the Sequence Set file,
the repeated running of the application program and its output for several states,
the repeated running the application program to display the State and Place Name for several Zip Codes.
In Video 4:
14:30
I don't mind phone call for audi as well, 612-707-2182 that's my cellphone
*/
//import header with the SequenceSet class
#include "SequenceSet.cpp"
#include <cstdio>
/*
Here is the main function to start the program.
*/
int main(int arg_count, char** arg_values){
/*
Here we declare and initialize the sequence set data. This will call load().
*/
SequenceSet data;
data.create(); //!
data.populate(); //!
data.display_field();
data.display_record(); //works most of the time, with the occasional exit
data.display_file(); //this works great
data.display_SS(); //this works great
data.developer_show(); //this works great
std::vector<int> loc = data.search(data.get_field_from_record(0,0,0));
std::cout << "\n" << data.get_field_from_record(0,0,0) << "\nBlock:\t" << std::to_string(loc[0]) << "\nRecord:\t" << std::to_string(loc[1]) << "\n";
loc = data.search(data.get_field_from_record(4,1,0));
std::cout << "\n" << data.get_field_from_record(4,1,0) << "\nBlock:\t" << std::to_string(loc[0]) << "\nRecord:\t" << std::to_string(loc[1]) << "\n";
loc = data.search(data.get_field_from_record(4,1,1));
std::cout << "\n" << data.get_field_from_record(4,1,1) << "\nBlock:\t" << std::to_string(loc[0]) << "\nRecord:\t" << std::to_string(loc[1]) << "\n";
loc = data.search("42.1934"); // from line 28
std::cout << "\n42.1934" << "\nBlock:\t" << std::to_string(loc[0]) << "\nRecord:\t" << std::to_string(loc[1]) << "\n";
loc = data.search("yeeeet"); // from line 28
std::cout << "\nyeeeet" << "\nBlock:\t" << std::to_string(loc[0]) << "\nRecord:\t" << std::to_string(loc[1]) << "\n";
data.insert("");
data.update(0,0,0,"12345");
data.update(0,0,1,"12345");
data.update(0,0,2,"12345");
data.update(0,0,3,"12345");
data.update(0,0,4," 12.345");
data.update(0,0,5,"-12.345");
data.display_SS();
data.validate();
//! show of arguments and example using them
//std::cout << "You have entered " << arg_count << " arguments:" << "\n";
//for (int i = 0; i < arg_count; ++i)
// std::cout << arg_values[i] << "\n";
if(*arg_values[1] == 'a'){
std::cout << "Finding the furthest zip codes in: " << arg_values[2] << "\n";
data.nsew_most(arg_values[2]);
}
if(*arg_values[1] == 'b'){
for(int i = 2; i < arg_count; i++){
std::cout << "Finding the State and Place name of zip code: " << arg_values[i] << "\n";
data.state_and_place_from_zip(arg_values[i]);
}
}
//forbiden code here
//wait for character so the screen does not disappear
std::cout << "Press enter...";
getchar();
//return that the program ran correctly
return 0;
}
| [
"smika6@users.noreply.github.com"
] | smika6@users.noreply.github.com |
890718fd3ed9429e7efcb9c80c3b6c90d20391e7 | 7371e4807462253312130cf07de05ae805529d58 | /9_strings.cpp | 02c065ab3d04338e77187306b57f725ed440544d | [] | no_license | joao-vitor-machado/aprendendo_cpp_basico | 0c3f3ba93200b06b2e4526ad6bd1a783aa50744d | 15e0cc4b0695ae1d472e61664585649aa3710c8a | refs/heads/Primeiros-passos | 2023-06-13T21:47:57.829374 | 2021-07-08T14:30:34 | 2021-07-08T14:30:34 | 384,149,300 | 6 | 0 | null | 2021-07-08T14:28:55 | 2021-07-08T14:20:39 | C++ | ISO-8859-1 | C++ | false | false | 4,199 | cpp | #include <iostream>
#include <locale.h>
using namespace std;
// Strings, basicamente, são conjuntos de caracteres que são delimitados por duas aspas duplas
// O hello world que fizemos no helloWorld.cpp utiliza o cout para imprimir a string "Hello World"
int main(){
string var = "joao"; // Para declarar uma string só precisamos seguir o mesmo esquema que foi apresentado sobre criação de variáveis
cout << var << endl;
// Concatenação é o processo de unir duas strings em uma só
//Existem duas formas de concatenarmos strings
//jeito 1
string primeiroNome = "Joao", segundoNome = "Vitor";
cout << "Primeiro nome: " << primeiroNome << endl;
cout << "Segundo nome: " << segundoNome << endl;
cout << "Nome completo: " << primeiroNome + segundoNome << endl; // Desse jeito temos o problema de juntar duas strings sem espaço
// para resolver o problema das strings grudadas só precisamos concatenar uma terceira string, que é o nosso espaço
cout << "Nome completo sem espaco: " << primeiroNome + " " + segundoNome << endl;
//jeito 2
// Podemos também utilizar o append
cout << "Nome completo sem espaco 2: " << primeiroNome.append((" " + segundoNome)) << endl;
//Nota: Preste bastante atenção se tentar somar uma string com um número. Isso pode e VAI te causar problemas. um erro ocorrerá
// Um dado que muitas vezes precisamos para fazer um for, por exemplo, é o comprimento da string. Ao contrário de C, que precisa que você se vire pra conseguir o dado, C++ já te dá uma função para isso
cout << "O comprimento da string \"joao\" eh: " << var.length() << endl; // A função length() te retorna o comprimento de uma string
cout << "O comprimento da string \"joao\" eh: " << var.size() << endl; // A função size() também te retorna o comprimento de uma string. Você que escolhe a que mais te agrada
/*
Ah, outra coisa. Lembra que em "pulando_linhas.cpp" falamos sobre o "\". Pois é. Você pode ver que
as aspas são caracteres especiais. Se não usássemos o \ para explicitar para o compilador que as nossas aspsas
eram parte da string, e não as aspas limitadoras da string, o C++ não entenderia e pensaria que "O comprimento da string" era uma string,
"joao" uma variável, e "", uma outra string
*/
// Você também pode desejar acessar um caractere específico da sua string. Há uma maneira muito simples de se fazer isso
cout << "O primeiro caractere de \"Joao\" eh: " << primeiroNome[0] << endl; // Escolha o índice da sua string que deseja acessar e coloque ele entre colchetes logo após o nome da variável
// Lembre-se que em linguagens de programação sempre começamos a acessar os índices pelo índice 0
/*
Também é possível receber uma string escrita pelo usuário. Podemos fazer isso usando o cin >>.
Porém, imagino que você já tenha entendido que lidamos com muitos problemas ao trabalhar com strings, certo? Então vou pular de uma vez
a demonstração disso e te dizer que, ao usar o cin >>, ele não considera o que vem depois de um espaçamento, por exemplo. Para lidarmos com
esse problema temos o getline(), que recebe uma linha inteira, só parando ao receber um ENTER
*/
string mensagem;
cout << "Digite sua mensagem: ";
getline(cin, mensagem); // O getline irá receber a string de uma linha, só parando ao encontrar um ENTER. Ele recebe a maneira como o dado irá chegar (cin) e a variável onde vai ser armazenada a string
cout << "Sua mensagem eh: " << mensagem << endl;
//Nota: Lembre-se que não podemos receber caracteres especiais
//Agora vem a cereja do bolo. Provavelmente o motivo de muitos entrarem aqui. A maneira de aceitar caracteres especiais na sua aplicação. Para isso:
// - inclua a lib locale através do "#include<locale>" no topo da sua aplicação. logo abaixo do include da iostream
// - Insira na sua main() o seguinte trecho de código:"
setlocale(LC_ALL, "Portuguese");//habilita a acentuação para o português
cout << "Pronto. Agora nossa aplicação recebe caracteres especiais sem problemas!!!" << endl;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
93c918fb781961340ca758ddae0f158e96a6295c | cac3181aeb2e8170752e37da5d23b66a00aa0307 | /content/public/browser/webrtc_event_logger.h | 926e61d5b22027af9ffc5aeb21f84996c4366b7c | [
"BSD-3-Clause"
] | permissive | madeeasyliteracy/chromium | d4c6172adb7c8efc87363c709d64c22d06b215d9 | 4b62356e5c9750122f05e4e15e9d9732bead6e70 | refs/heads/master | 2023-01-13T03:41:17.023737 | 2018-03-24T02:56:11 | 2018-03-24T02:56:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,209 | h | // Copyright (c) 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_PUBLIC_BROWSER_WEBRTC_EVENT_LOGGER_H_
#define CONTENT_PUBLIC_BROWSER_WEBRTC_EVENT_LOGGER_H_
#include <string>
#include "base/callback.h"
#include "base/files/file_path.h"
#include "content/common/content_export.h"
namespace content {
class BrowserContext;
// Interface for a logger of WebRTC events, which the embedding application may
// subclass and instantiate. Only one instance may ever be created, and it must
// live until the embedding application terminates.
class CONTENT_EXPORT WebRtcEventLogger {
public:
// Get the only instance of WebRtcEventLogger, if one was instantiated, or
// nullptr otherwise.
static WebRtcEventLogger* Get();
// The embedding application may leak or destroy on shutdown. Either way,
// it may only be done on shutdown. It's up to the embedding application to
// only destroy at a time during shutdown when it is guaranteed that tasks
// posted earlier with a reference to the WebRtcEventLogger object, will
// not execute.
virtual ~WebRtcEventLogger();
// TODO(eladalon): Change from using BrowserContext to using Profile.
// https://crbug.com/775415
// Enables WebRTC event logging for a given BrowserContext:
// * Pending logs from previous sessions become eligible to be uploaded.
// * New logs for active peer connections *may* be recorded. (This does *not*
// start logging; it just makes it possible.)
// This function would typically be called during a BrowserContext's
// initialization.
// This function must not be called for an off-the-records BrowserContext.
// Local-logging is not associated with BrowserContexts, and is allowed even
// if EnableForBrowserContext is not called. That is, even for incognito mode.
virtual void EnableForBrowserContext(
const BrowserContext* browser_context,
base::OnceClosure reply = base::OnceClosure()) = 0;
// Disables WebRTC event logging for a given BrowserContext. New remote-bound
// WebRTC event logs will no longer be created for this BrowserContext.
// This would typically be called when a BrowserContext is destroyed. One must
// therefore be careful note to call any of BrowserContext's virtual methods.
// TODO(eladalon): After changing to a Profile-centered interface, change this
// to not even receive a pointer. https://crbug.com/775415
virtual void DisableForBrowserContext(
const BrowserContext* browser_context,
base::OnceClosure reply = base::OnceClosure()) = 0;
// Call this to let the logger know when a PeerConnection was created.
// |peer_connection_id| should be a non-empty, relatively short (i.e.
// inexpensive to store) identifier, by which the peer connection may later
// be identified. The identifier is assumed to be unique (within the
// renderer process).
// If a reply callback is given, it will be posted back to BrowserThread::UI,
// with true if and only if the operation was successful (failure is only
// possible if a peer connection with this exact key was previously added,
// but not removed).
virtual void PeerConnectionAdded(int render_process_id,
int lid,
const std::string& peer_connection_id,
base::OnceCallback<void(bool)> reply =
base::OnceCallback<void(bool)>()) = 0;
// Call this to let the logger know when a PeerConnection was closed.
// If a reply callback is given, it will be posted back to BrowserThread::UI,
// with true if and only if the operation was successful (failure is only
// possible if a peer connection with this key was not previously added,
// or if it has since already been removed).
virtual void PeerConnectionRemoved(int render_process_id,
int lid,
base::OnceCallback<void(bool)> reply =
base::OnceCallback<void(bool)>()) = 0;
// Call this to let the logger know when a PeerConnection was stopped.
// Closing of a peer connection is an irreversible action. Its distinction
// from the removal event is that it may happen before the peer connection has
// been garbage collected.
virtual void PeerConnectionStopped(int render_process_id,
int lid,
base::OnceCallback<void(bool)> reply =
base::OnceCallback<void(bool)>()) = 0;
// Enable local logging of WebRTC events.
// Local logging is distinguished from remote logging, in that local logs are
// kept in response to explicit user input, are saved to a specific location,
// and are never removed by the application.
// If a reply callback is given, it will be posted back to BrowserThread::UI,
// with true if and only if local logging was *not* already on.
// Note #1: An illegal file path, or one where we don't have the necessary
// permissions, does not cause a |false| reply, since even when we have the
// permissions, we're not guaranteed to keep them, and some files might be
// legal while others aren't due to additional restrictions (number of files,
// length of filename, etc.).
// Note #2: If the number of currently active peer connections exceeds the
// maximum number of local log files, there is no guarantee about which PCs
// will get a local log file associated (specifically, we do *not* guarantee
// it would be either the oldest or the newest).
virtual void EnableLocalLogging(const base::FilePath& base_path,
base::OnceCallback<void(bool)> reply =
base::OnceCallback<void(bool)>()) = 0;
// Disable local logging of WebRTC events.
// Any active local logs are stopped. Peer connections added after this call
// will not get a local log associated with them (unless local logging is
// once again enabled).
virtual void DisableLocalLogging(base::OnceCallback<void(bool)> reply =
base::OnceCallback<void(bool)>()) = 0;
// Called when a new log fragment is sent from the renderer. This will
// potentially be written to a local WebRTC event log, a remote-bound log
// intended for upload, or both.
// If a reply callback is given, it will be posted back to BrowserThread::UI
// with a pair of bools, the first bool associated with local logging and the
// second bool associated with remote-bound logging. Each bool assumes the
// value true if and only if the message was written in its entirety into
// a local/remote-bound log file.
virtual void OnWebRtcEventLogWrite(
int render_process_id,
int lid,
const std::string& message,
base::OnceCallback<void(std::pair<bool, bool>)> reply =
base::OnceCallback<void(std::pair<bool, bool>)>()) = 0;
protected:
WebRtcEventLogger();
};
} // namespace content
#endif // CONTENT_PUBLIC_BROWSER_WEBRTC_EVENT_LOGGER_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
f94449e112419a8701553b5a8aa806f8190b42bb | 5a47128a1800ebadb225488be67fb8075a84e324 | /mazetest.cpp | ce5c87d3c28a347d9ac87827677d2f24d8b70300 | [] | no_license | Amberda/data-structure | 33b8b584bbd7f1e0b1b0e43c6352d0a072a7e420 | c4f62153605f7c15543ca0e3028eda587ee302cf | refs/heads/master | 2021-04-12T09:26:33.563018 | 2018-08-21T04:23:31 | 2018-08-21T04:23:31 | 126,172,490 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,053 | cpp | #define _CRT_SECURE_NO_WARNINGS 1
#include "maze.h"
void FunTest()
{
int maze1[10][10] = {
{ 0, 0, 1, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
{ 1, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 1, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 } };
int maze2[10][10] = {
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
{ 1, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 1, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 1, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0 } };
Maze maze(maze2);
maze.PrintMaze();
Pos entry = { 9, 6 };
stack<Pos> path;
//maze.GetPath(entry);
maze.GetPathR(entry, path);
maze.PrintMaze();
}
int main()
{
FunTest();
system("pause");
return 0;
} | [
"18729219705@163.com"
] | 18729219705@163.com |
123a7f10da991da129423d1a3fa9540e866186fa | 6fedc290989b4a217524f60e008f84169c83261c | /SuccessiveOverRelaxation/SuccessiveOverRelaxation/LES.cpp | e9ac8b5b13580a6743989625ee17dd8d19cf089a | [] | no_license | geranium12/Numerical-Analysis | aec53a96f2ec364731d7e466001d8c299f6ae285 | 8483ee8e12aeac17772548c4fc1ac42b9f2c81e4 | refs/heads/master | 2022-12-01T16:11:54.352730 | 2020-07-27T17:42:47 | 2020-07-27T17:42:47 | 282,971,770 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,093 | cpp | #include "LES.h"
LES::LES(ExtendedMatrix exMatrix)
: mSize_(exMatrix.size()), matrix(exMatrix) {
curSol_ = new float[mSize_];
prevSol_ = new float[mSize_];
state = "LinearEquationsSystem";
}
int LES::findSolRelaxationMethod(int kMax, double accuracy, double option) {
state = "RelaxationMethod" + std::to_string(int(10 * option));
for (int k = 0; k < kMax; ++k) {
for (int i = 0; i < mSize_; ++i) {
curSol_[i] = matrix[i][mSize_];
for (int j = 0; j < i; ++j) {
curSol_[i] -= matrix[i][j] * curSol_[j];
}
for (int j = i + 1; j < mSize_; ++j) {
curSol_[i] -= matrix[i][j] * prevSol_[j];
}
curSol_[i] = curSol_[i] * option / matrix[i][i] + (1 - option) * prevSol_[i];
}
std::swap(prevSol_, curSol_);
if (maxDiff() < accuracy) {
return k;
}
}
state += "ExceededKMax";
return -1;
}
float LES::maxDiff() {
float mDiff = 0;
for (int i = 0; i < mSize_; ++i) {
if (mDiff < std::abs(prevSol_[i] - curSol_[i])) {
mDiff = std::abs(prevSol_[i] - curSol_[i]);
}
}
return mDiff;
}
float* LES::operator[] (int i) {
return matrix[i];
} | [
"hotgeranium@gmail.com"
] | hotgeranium@gmail.com |
e0e0d00919e3353046525fc83e9700d508154cae | 740c3da6fea0ac9ac1a25c9d13cffffb7c72c0a7 | /temoto_action_assistant/src/widgets/data_instance_edit_widget.h | 4a971b1fcc283bd6bcad2c842fa9221352b4220e | [
"BSD-3-Clause"
] | permissive | UTNuclearRoboticsPublic/temoto2 | 464b4485d654003b7b9d4ddf4fe9b78e7f433c42 | 86e707edf96e57fd9db67ae09cada8c42bca6768 | refs/heads/master | 2021-03-22T01:31:00.064332 | 2019-09-24T08:08:21 | 2019-09-24T08:08:21 | 93,573,827 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,176 | h | #ifndef TEMOTO_ACTION_ASSISTANT_DATA_INSTANCE_EDIT_WIDGET
#define TEMOTO_ACTION_ASSISTANT_DATA_INSTANCE_EDIT_WIDGET
#include <QWidget>
#include <QLabel>
#include <QComboBox>
#include <QTreeWidget>
#ifndef Q_MOC_RUN
#endif
#include "interface_tree_data.h"
#include "temoto_action_assistant/semantic_frame.h"
namespace temoto_action_assistant
{
class DataInstanceEditWidget : public QWidget
{
Q_OBJECT
public:
// ******************************************************************************************
// Public Functions
// ******************************************************************************************
/// Constructor
DataInstanceEditWidget(QWidget* parent);
/// Focus given
void focusGiven(QTreeWidgetItem* tree_item_ptr);
// ******************************************************************************************
// Qt Components
// ******************************************************************************************
QLabel* title_; // specify the title from the parent widget
QComboBox* data_type_field_;
private Q_SLOTS:
// ******************************************************************************************
// Slot Event Functions
// ******************************************************************************************
/// Modify the type variable
void modifyType(const QString &text);
Q_SIGNALS:
// ******************************************************************************************
// Emitted Signals
// ******************************************************************************************
private:
// ******************************************************************************************
// Variables
// ******************************************************************************************
/// Points to the active element of the interface tree
InterfaceTreeData tree_data_;
QTreeWidgetItem* tree_item_ptr_;
// ******************************************************************************************
// Private Functions
// ******************************************************************************************
};
}
#endif
| [
"valnerrobert@gmail.com"
] | valnerrobert@gmail.com |
c94d57c19ddf7f200e5be79986685dbab9d96fbf | cc9c96a921aa667e65f259d76ee0213048cc8911 | /indra/llcommon/lltimer.h | a6b535fbc14560078a896553134eeb95c9e2f777 | [] | no_license | gurucoyote/c14 | 40a175a0efdfeac85a495b9bbb72682f9af03942 | 6d94eb26380c5fed6f2fb95bca827d6d5d1f98e2 | refs/heads/master | 2020-03-14T12:43:07.363929 | 2011-12-28T00:02:06 | 2011-12-28T00:02:06 | 131,618,023 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,338 | h | /**
* @file lltimer.h
* @brief Cross-platform objects for doing timing
*
* $LicenseInfo:firstyear=2000&license=viewergpl$
*
* Copyright (c) 2000-2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#ifndef LL_TIMER_H
#define LL_TIMER_H
#if LL_LINUX || LL_DARWIN || LL_SOLARIS
#include <sys/time.h>
#endif
#include <limits.h>
#include "stdtypes.h"
#include <string>
#include <list>
// units conversions
#ifndef USEC_PER_SEC
const U32 USEC_PER_SEC = 1000000;
#endif
const U32 SEC_PER_MIN = 60;
const U32 MIN_PER_HOUR = 60;
const U32 USEC_PER_MIN = USEC_PER_SEC * SEC_PER_MIN;
const U32 USEC_PER_HOUR = USEC_PER_MIN * MIN_PER_HOUR;
const U32 SEC_PER_HOUR = SEC_PER_MIN * MIN_PER_HOUR;
const F64 SEC_PER_USEC = 1.0 / (F64) USEC_PER_SEC;
class LL_COMMON_API LLTimer
{
public:
static LLTimer *sTimer; // global timer
protected:
U64 mLastClockCount;
U64 mExpirationTicks;
BOOL mStarted;
public:
LLTimer();
~LLTimer();
static void initClass() { if (!sTimer) sTimer = new LLTimer; }
static void cleanupClass() { delete sTimer; sTimer = NULL; }
// Return a high precision number of seconds since the start of
// this application instance.
static F64 getElapsedSeconds()
{
return sTimer->getElapsedTimeF64();
}
// Return a high precision usec since epoch
static U64 getTotalTime();
// Return a high precision seconds since epoch
static F64 getTotalSeconds();
// MANIPULATORS
void start() { reset(); mStarted = TRUE; }
void stop() { mStarted = FALSE; }
void reset(); // Resets the timer
void setLastClockCount(U64 current_count); // Sets the timer so that the next elapsed call will be relative to this time
void setTimerExpirySec(F32 expiration);
BOOL checkExpirationAndReset(F32 expiration);
BOOL hasExpired() const;
F32 getElapsedTimeAndResetF32(); // Returns elapsed time in seconds with reset
F64 getElapsedTimeAndResetF64();
F32 getRemainingTimeF32() const;
static BOOL knownBadTimer();
// ACCESSORS
F32 getElapsedTimeF32() const; // Returns elapsed time in seconds
F64 getElapsedTimeF64() const; // Returns elapsed time in seconds
BOOL getStarted() const { return mStarted; }
static U64 getCurrentClockCount(); // Returns the raw clockticks
};
//
// Various functions for initializing/accessing clock and timing stuff. Don't use these without REALLY knowing how they work.
//
LL_COMMON_API U64 get_clock_count();
LL_COMMON_API F64 calc_clock_frequency(U32 msecs);
LL_COMMON_API void update_clock_frequencies();
// Sleep for milliseconds
LL_COMMON_API void ms_sleep(U32 ms);
LL_COMMON_API U32 micro_sleep(U64 us, U32 max_yields = 0xFFFFFFFF);
// Returns the correct UTC time in seconds, like time(NULL).
// Useful on the viewer, which may have its local clock set wrong.
LL_COMMON_API time_t time_corrected();
static inline time_t time_min()
{
if (sizeof(time_t) == 4)
{
return (time_t) INT_MIN;
} else {
#ifdef LLONG_MIN
return (time_t) LLONG_MIN;
#else
return (time_t) LONG_MIN;
#endif
}
}
static inline time_t time_max()
{
if (sizeof(time_t) == 4)
{
return (time_t) INT_MAX;
} else {
#ifdef LLONG_MAX
return (time_t) LLONG_MAX;
#else
return (time_t) LONG_MAX;
#endif
}
}
// Correction factor used by time_corrected() above.
extern LL_COMMON_API S32 gUTCOffset;
// Is the current computer (in its current time zone)
// observing daylight savings time?
LL_COMMON_API BOOL is_daylight_savings();
// Converts internal "struct tm" time buffer to Pacific Standard/Daylight Time
// Usage:
// S32 utc_time;
// utc_time = time_corrected();
// struct tm* internal_time = utc_to_pacific_time(utc_time, gDaylight);
LL_COMMON_API struct tm* utc_to_pacific_time(time_t utc_time, BOOL pacific_daylight_time);
LL_COMMON_API void microsecondsToTimecodeString(U64 current_time, std::string& tcstring);
LL_COMMON_API void secondsToTimecodeString(F32 current_time, std::string& tcstring);
LL_COMMON_API void timeToFormattedString(time_t time, std::string format, std::string ×tr);
LL_COMMON_API void timeStructToFormattedString(struct tm * time, std::string format, std::string ×tr);
U64 LL_COMMON_API totalTime(); // Returns current system time in microseconds
#endif
| [
"gc@testbild.tv"
] | gc@testbild.tv |
613454558095db68547f38cc3f08a720245e6dc7 | 45ae089c7d939488e56e87a71309c56f51b01f0c | /HDServer/HDServerView.h | fb8301c41b274d2b5f4dbb0b84a2c9e9c0646212 | [] | no_license | wangscript007/HDServer | 3f22472800dcdf34f75abd4f96528cf314e37e08 | c8d1c6533a0da0bc46523b5fee0f130caee71730 | refs/heads/master | 2022-12-09T22:29:01.213842 | 2020-09-03T11:38:42 | 2020-09-03T11:38:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,036 | h |
// HDServerView.h : interface of the CHDServerView class
//
#pragma once
class CHDServerView : public CView
{
protected: // create from serialization only
CHDServerView() noexcept;
DECLARE_DYNCREATE(CHDServerView)
// Attributes
public:
CHDServerDoc* GetDocument() const;
// Operations
public:
// Overrides
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
// Implementation
public:
virtual ~CHDServerView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in HDServerView.cpp
inline CHDServerDoc* CHDServerView::GetDocument() const
{ return reinterpret_cast<CHDServerDoc*>(m_pDocument); }
#endif
| [
"pieangel@naver.com"
] | pieangel@naver.com |
4f86ccaa346c50e7475302af6fb7243ec495ac0e | 96816fec7ac7c5f3303bf425467932b86019f54e | /FactoryTest/USB/USBTest.cpp | 776e7a16c0e162de6dd6f142cd33aa972ee44826 | [] | no_license | piaoxue85/DH1551-TestApp | b4b4e0fe438165b49124f8e56bd48068c38252d5 | ba78e9a7b4af7928cc1c93a79f9ed89e989667c5 | refs/heads/master | 2022-11-27T11:00:03.945191 | 2020-07-28T04:14:52 | 2020-07-28T04:14:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,541 | cpp | /*
* PlayServiceTest.cpp
*
* Created on: 2015-8-14
* Author: timothy.liao
*/
#include "APAssert.h"
#include "USBTest.h"
#include "adi_fs.h"
#include "string.h"
#include "FactoryTestInit.h"
static void USBDviceCallBack(ADIFSEvent_E eType, int nDeviceId, const void * pvEventData, void * pvUserData);
USBTest::USBTest(USBNotify* pNotify) : m_pNotify(pNotify)
{
m_unCheckStatus = NONE_USB;
}
USBTest::~USBTest()
{
ADIFSRemoveCallback(USBDviceCallBack, this);
}
void USBTest::Init(USBConfig csUSBConfig)
{
memcpy(&m_USBConfig, &csUSBConfig, sizeof(USBConfig));
ADIFSAddCallback(USBDviceCallBack, this);
}
unsigned int USBTest::Start()
{
unsigned int unRet = 0;
int anDevCnt[8] = { 0 };
int nActualCnt = 0;
if (ADI_SUCCESS == ADIFSGetAllDeviceId(anDevCnt, 8, &nActualCnt))
{
if(nActualCnt > 0)
{
for (int ii = 0; ii < nActualCnt; ii++)
{
ADIFSDeviceInfo_S stDevInfo = { 0 };
if (ADI_SUCCESS == ADIFSGetDeviceInfo((unsigned int)anDevCnt[ii], &stDevInfo))
{
if(stDevInfo.m_eDeviceType == EM_ADIFS_DEVTYPE_VOLUME && IsCheckUSBSuccess(stDevInfo.m_nMountPort))
{
m_pNotify->USBReady((unsigned int)anDevCnt[ii], &stDevInfo);
unRet = 1;
break;
}
}
}
}
if( unRet != 1 )
{
m_pNotify->NoUSBNotify(m_unCheckStatus);
}
}
else
{
m_pNotify->NoUSBNotify(m_unCheckStatus);
}
printf("-[%s][%d]-nActualUSBCount:%d---\n", __FUNCTION__, __LINE__, nActualCnt);
return unRet;
}
unsigned int USBTest::Stop()
{
unsigned int unRet = 1;
return unRet;
}
void USBTest::USBMediaReady(unsigned int unDevice, ADIFSDeviceInfo_S* psDeviceInfo)
{
if(IsCheckUSBSuccess(psDeviceInfo->m_nMountPort))
{
m_pNotify->USBReady(unDevice, psDeviceInfo);
}
else if( m_USBConfig.m_nCount > 1 && m_unCheckStatus > 0 )
{
FactoryTestInterface *pFactoryTestInterface = GetFactoryTestInterface();
if(pFactoryTestInterface != NULL)
{
TestResult_S stTestResult = {0};
if(pFactoryTestInterface->GetTestResult(&stTestResult))
{
if(stTestResult.nUSBResult != 1)
{
Start();
}
}
}
}
}
void USBTest::USBMediaPlugOut(unsigned int unDevice)
{
m_pNotify->USBPlugOut(unDevice);
m_unCheckStatus = NONE_USB;
}
BOOL USBTest::IsCheckUSBSuccess(unsigned int unDeviceID)
{
BOOL bSuccess = FALSE;
unDeviceID = unDeviceID % 2;
m_unCheckStatus |= (unDeviceID + 1);
if( m_USBConfig.m_nCount > 1)
{
if( (m_unCheckStatus & DOUBLE_USB) == DOUBLE_USB )
{
bSuccess = TRUE;
}
}
else if( m_USBConfig.m_nCount == 1 && m_unCheckStatus != NONE_USB )
{
bSuccess = TRUE;
}
return bSuccess;
}
static void USBDviceCallBack(ADIFSEvent_E eType, int nDeviceId, const void * pvEventData, void * pvUserData)
{
APAssert(pvUserData != NULL);
USBTest *pUSBTest = (USBTest*)pvUserData;
if (pUSBTest != NULL)
{
if (eType == EM_ADIFS_EVENT_READY)
{
ADIFSDeviceInfo_S stDevInfo = { 0 };
if (ADI_SUCCESS == ADIFSGetDeviceInfo((unsigned int)nDeviceId, &stDevInfo))
{
if(stDevInfo.m_eDeviceType == EM_ADIFS_DEVTYPE_VOLUME)
{
pUSBTest->USBMediaReady((unsigned int)nDeviceId, &stDevInfo);
}
}
}
else if (eType == EM_ADIFS_EVENT_PLUGOUT)
{
pUSBTest->USBMediaPlugOut((unsigned int)nDeviceId);
}
else if(eType == EM_ADIFS_EVENT_ERROR || eType == EM_ADIFS_EVENT_DEVICE_NO_PARTITION)
{
ADIFSDeviceInfo_S stDevInfo = { 0 };
stDevInfo.m_nMountPort = 0;
pUSBTest->USBMediaReady((unsigned int)nDeviceId, &stDevInfo);
printf("--[%s][%d]--eType:%d---\n", __FUNCTION__, __LINE__, eType);
}
}
}
| [
"1344465206@qq.com"
] | 1344465206@qq.com |
6e0726231174bcb3c4244afd857c18bc0157eb8b | 883e53051c4579b32e85a0d8d35b814da0f26dfe | /Jacob/Lektion 2/OPG 3.2 - QuadraticEquation/QuadraticEquation/main.cpp | d8f7a32bb78db13eb58b0751ffad760874b60423 | [] | no_license | Andreasgdp/Cpp-2.-semester | fa8b2b5b462d558cd88f6f75c04fca0fb8afc9cb | 8180e6ea86bb933f8c0f16579c57eeeac8345eff | refs/heads/main | 2023-06-10T00:20:44.345868 | 2021-06-23T15:00:12 | 2021-06-23T15:00:12 | 335,230,193 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,037 | cpp | #include <iostream>
#include "QuadraticEquation.h"
using namespace std;
int main()
{
bool newCalc = true;
while (newCalc) {
double inA;
std::cout << "Enter a: ";
std::cin >> inA;
double inB;
std::cout << "Enter b: ";
std::cin >> inB;
unsigned int inC;
std::cout << "Enter c: ";
std::cin >> inC;
QuadraticEquation q1(inA, inB, inC);
auto [x1, x2, dIsNegative] = q1.solve();
if (dIsNegative) {
auto [Reel, Imag, dIsNegative] = q1.solve();
std::cout << "Resulat: " << Reel << "+i" << Imag << " og " << Reel << "-i" << Imag << std::endl;
} else {
std::cout << "Resulat: " << x1 << " og " << x2 << std::endl;
}
std::string inNewCalc;
std::cout << "\nEnter new calculation?(y/n): ";
std::cin >> inNewCalc;
if (inNewCalc.compare("y") == 0) {
newCalc = true;
} else {
newCalc = false;
}
}
return 0;
}
| [
"45763482+JBLarsen2107@users.noreply.github.com"
] | 45763482+JBLarsen2107@users.noreply.github.com |
69e3da0ecb988f2e58e0cc13fd50d96926a008c0 | 1913e2595ab0bfec71f28a953a46e624514b55e8 | /exercises/15-maps/hash-map/myhashmap.h | d5a52f7299b761f5cc4a6262e638286a914ff088 | [] | no_license | eugene-shcherbo/programming-abstractions | 4c43149a980a51a836e97c5ee85953eb457d0a40 | f1b7c8db3e5a33f349e638e5a9c06a21bd8420cc | refs/heads/master | 2021-02-18T07:45:08.296484 | 2020-11-25T07:46:16 | 2020-11-25T07:47:00 | 245,175,467 | 0 | 0 | null | 2020-03-10T14:36:06 | 2020-03-05T13:50:27 | C++ | UTF-8 | C++ | false | false | 4,497 | h | #ifndef MyHashMap_H
#define MyHashMap_H
template <typename TKey, typename TValue>
class MyHashMap {
public:
MyHashMap();
~MyHashMap();
size_t size() const;
bool isEmpty() const;
void put(const TKey& key, const TValue& value);
TValue get(const TKey& key) const;
void remove(const TKey& key);
bool containsKey(const TKey& key) const;
void clear();
TValue& operator[](const TKey& key);
TValue operator[](const TKey& key) const;
private:
static double constexpr LOAD_THRESHOLD = .7;
static int constexpr INITIAL_BUCKETS_NUM = 13;
struct Cell {
TKey key;
TValue value;
Cell* next;
};
Cell** _buckets;
int _bucketsNum;
int _size;
Cell* findCell(int bucket, const TKey& key) const;
void expandAndRehash();
MyHashMap& operator=(const MyHashMap& other);
MyHashMap(const MyHashMap& other);
};
template <typename TKey, typename TValue>
MyHashMap<TKey, TValue>::MyHashMap() {
_bucketsNum = INITIAL_BUCKETS_NUM;
_buckets = new Cell*[_bucketsNum]();
_size = 0;
}
template <typename TKey, typename TValue>
MyHashMap<TKey, TValue>::~MyHashMap() {
if (!isEmpty())
clear();
}
template <typename TKey, typename TValue>
void MyHashMap<TKey, TValue>::put(const TKey& key, const TValue& value) {
int bucket = hashCode(key) % _bucketsNum;
Cell* cell = findCell(bucket, key);
if (cell == nullptr) {
if (_size / _bucketsNum >= LOAD_THRESHOLD) {
expandAndRehash();
bucket = hashCode(key) % _bucketsNum;
}
cell = new Cell { key, value, _buckets[bucket] };
_buckets[bucket] = cell;
_size++;
}
cell->value = value;
}
template <typename TKey, typename TValue>
void MyHashMap<TKey, TValue>::expandAndRehash() {
int oldNumBuckets = _bucketsNum;
_bucketsNum = _bucketsNum * 2 + 1;
Cell** oldBuckets = _buckets;
_buckets = new Cell*[_bucketsNum]();
for (int i = 0; i < oldNumBuckets; i++) {
Cell* cell = _buckets[i];
while (cell != nullptr) {
Cell* oldCell = cell;
put(cell->key, cell->value);
delete oldCell;
}
}
delete oldBuckets;
}
template <typename TKey, typename TValue>
TValue MyHashMap<TKey, TValue>::get(const TKey& key) const {
int bucket = hashCode(key) % _bucketsNum;
Cell* cell = findCell(bucket, key);
return cell == nullptr ? TValue() : cell->value;
}
template <typename TKey, typename TValue>
void MyHashMap<TKey, TValue>::remove(const TKey& key) {
int bucket = hashCode(key) % _bucketsNum;
Cell* parent = nullptr;
Cell* current = _buckets[bucket];
while (current != nullptr && current->key != key) {
parent = current;
current = current->next;
}
if (current != nullptr) {
if (parent == nullptr) {
_buckets[bucket] = current->next;
} else {
parent->next = current->next;
}
_size--;
delete current;
}
}
template <typename TKey, typename TValue>
struct MyHashMap<TKey, TValue>::Cell* MyHashMap<TKey, TValue>::findCell(int bucket, const TKey& key) const {
Cell* cell = _buckets[bucket];
while (cell != nullptr && cell->key != key) {
cell = cell->next;
}
return cell;
}
template <typename TKey, typename TValue>
bool MyHashMap<TKey, TValue>::containsKey(const TKey& key) const {
int bucket = hashCode(key) % _bucketsNum;
Cell* cell = findCell(bucket, key);
return cell != nullptr;
}
template <typename TKey, typename TValue>
TValue& MyHashMap<TKey, TValue>::operator[](const TKey& key) {
put(key, TValue());
int bucket = hashCode(key) % _bucketsNum;
return findCell(bucket, key)->value;
}
template <typename TKey, typename TValue>
TValue MyHashMap<TKey, TValue>::operator[](const TKey& key) const {
return get(key);
}
template <typename TKey, typename TValue>
size_t MyHashMap<TKey, TValue>::size() const {
return _size;
}
template <typename TKey, typename TValue>
bool MyHashMap<TKey, TValue>::isEmpty() const {
return _size == 0;
}
template <typename TKey, typename TValue>
void MyHashMap<TKey, TValue>::clear() {
for (int i = 0; i < _bucketsNum; i++) {
Cell* cell = _buckets[i];
while (cell != nullptr) {
Cell* oldCell = cell;
cell = cell->next;
delete oldCell;
}
}
delete[] _buckets;
_size = 0;
}
#endif // MyHashMap_H
| [
"eugene.shcherbo@gmail.com"
] | eugene.shcherbo@gmail.com |
127790dde6f860e98dc3ac5531ab0eb7799f2d45 | cd060892280983a64d1d463fcea7b3edbf843cf8 | /former_work/ZHEngine/ZHEngine/src/ZHResource.h | d82d4670d181bc5fc92088e36629725ede0d6c41 | [] | no_license | zhvirus/zhangtina | c8741d3cab4cc0929db6776dde3ce5a4733fabe1 | 88a6f85992861862e22cd9edbe852f45b8a62775 | refs/heads/master | 2021-01-21T04:31:30.673821 | 2016-06-29T03:14:16 | 2016-06-29T03:14:16 | 14,973,156 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 398 | h | #pragma once
#include "ZHRenderDecl.h"
#include "ZHBufferManager.h"
#include "ZHTextureManager.h"
namespace ZH
{
template<class T>
class RES_UNIT
{
public:
RES_UNIT():data(NULL),count(0){}
T data;
int count;
};
class ZH_DLL Resource
{
public:
explicit Resource();
~Resource();
public:
BufferManager* _bufferManager;
TextureManager* _textureManager;
};
} | [
"zhvirus@hotmail.com"
] | zhvirus@hotmail.com |
8d74474a01b59b7931c5dcf664692ef1359b0e1a | b1f1316be90ffbdf2bf81bf9521f309763b92233 | /Doom/src/Doom/ECS/ComponentManager.h | b440ffafd88903caeb851df9ffd816d5dc0feb61 | [
"MIT"
] | permissive | anggawasita/OpenGL_Engine | f8cde189521f6b717d75db82991943eff85999af | 16393609755e171dd5430cdd7586771d859d5113 | refs/heads/master | 2023-02-27T14:34:00.550646 | 2021-01-29T13:46:19 | 2021-01-29T13:46:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,371 | h | #pragma once
#ifndef COMPONENTMANAGER_H
#define COMPONENTMANAGER_H
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "Component.h"
#include "../Render/Renderer.h"
#include "../Components/SpriteRenderer.h"
#include "../Components/Render3D.h"
#include "../Components/Transform.h"
#include "../Components/Animator.h"
#include "../Components/RectangleCollider2D.h"
#include "../Components/CubeCollider.h"
#include "../Enums/ColoredOutput.h"
#include "../Components/PointLight.h"
#include "../Components/DirectionalLight.h"
#include "../Components/SphereCollider.h"
#include "../Components/ScriptComponent.h"
#include "Core/Utils.h"
namespace Doom {
class DOOM_API ComponentManager {
private:
GameObject* m_Owner = nullptr;
const char** m_NamesOfMembers = nullptr;
std::vector <Component*> m_Components;
template<class T>
void CopyComponent(ComponentManager& rhs) {
if (rhs.GetComponent<T>() != nullptr) {
AddComponent<T>()->operator=(*rhs.GetComponent<T>());
}
}
void Copy(ComponentManager& rhs) {
CopyComponent<Transform>(rhs);
CopyComponent<PointLight>(rhs);
CopyComponent<DirectionalLight>(rhs);
CopyComponent<Renderer3D>(rhs);
CopyComponent<SpriteRenderer>(rhs);
CopyComponent<SphereCollider>(rhs);
CopyComponent<Animator>(rhs);
}
friend class Component;
friend class Editor;
public:
ComponentManager(ComponentManager& rhs) {
Copy(rhs);
}
ComponentManager(GameObject* owner) {
this->m_Owner = owner;
}
~ComponentManager() {
delete[] m_NamesOfMembers;
std::vector<ScriptComponent*> scripts = GetScripts();
for (uint32_t i = 0; i < scripts.size(); i++)
{
RemoveComponent(scripts[i]);
}
for (uint32_t i = 0; i < m_Components.size(); i)
{
RemoveComponent(m_Components[i]);
}
}
void operator=(ComponentManager& rhs) {
Copy(rhs);
}
inline int GetAmountOfComponents() { return m_Components.size(); }
const char** GetItems() {
if (m_NamesOfMembers != nullptr)
delete[] m_NamesOfMembers;
m_NamesOfMembers = new const char* [m_Components.size()];
for (unsigned int i = 0; i < m_Components.size(); i++)
{
m_NamesOfMembers[i] = m_Components[i]->GetComponentType().c_str();
}
return m_NamesOfMembers;
}
std::vector<ScriptComponent*> GetScripts() {
std::vector<ScriptComponent*> scripts;
for (Component* com : m_Components) {
if (com->m_Type == Utils::GetComponentTypeName<ScriptComponent>())
scripts.push_back(static_cast<ScriptComponent*>(com));
}
return scripts;
}
template <class T>
void RemoveComponent() {
T* com = nullptr;
com = GetComponent<T>();
if (com == nullptr)
return;
int _id = com->m_Id;
if (com->m_Id < m_Components.size())
m_Components.erase(m_Components.begin() + com->m_Id);
unsigned int _size = m_Components.size();
if (com->m_Id != _size) {
for (unsigned int i = com->m_Id; i < _size; i++)
{
m_Components[i]->m_Id = i;
}
}
delete com;
return;
}
void RemoveComponent(Component* com) {
if (com == nullptr)
return;
int _id = com->m_Id;
if (com->m_Id < m_Components.size())
m_Components.erase(m_Components.begin() + com->m_Id);
unsigned int _size = m_Components.size();
if (com->m_Id != _size) {
for (unsigned int i = com->m_Id; i < _size; i++)
{
m_Components[i]->m_Id = i;
}
}
delete com;
return;
}
template<class T>
T* GetComponent()
{
for (auto com : m_Components) {
if (com->m_Type == Utils::GetComponentTypeName<T>()) {
return static_cast<T*>(com);
}
}
return nullptr;
}
template<class T>
T* AddComponent() {
if ((GetComponent<T>() != nullptr && GetComponent<T>()->m_Type == Utils::GetComponentTypeName<ScriptComponent>()) || GetComponent<T>() == nullptr) {
Component* object = T::Create();
object->m_OwnerOfCom = (this->m_Owner);
object->SetType(Utils::GetComponentTypeName<T>());
object->m_Id = m_Components.size();
m_Components.push_back(object);
#ifdef _DEBUG
std::cout << NAMECOLOR << Utils::GetComponentTypeName<T>() << " size:" << sizeof(T) << RESET << ": has been added to GameObject <" NAMECOLOR << m_Owner->m_Name << RESET << ">" << std::endl;
#endif
return static_cast<T*>(object);
}
return GetComponent<T>();
}
};
}
#endif | [
"turlak01@mail.ru"
] | turlak01@mail.ru |
e0e9d4f0799b6707783691edb8037edd507017e8 | cc799cb41ba0f736a9611eafd4ad06a0767fd102 | /CncControlerGui/CncCurveLib.cpp | 246c248c366b434c014f989e063eda3746f9e61d | [] | no_license | HackiWimmer/cnc | 8cbfe5f5b9b39d96c9ea32da4adcb89f96ec1008 | 329278bbed7b4a10407e6ddb1c135366f3ef8537 | refs/heads/master | 2023-01-08T01:39:54.521532 | 2023-01-01T15:48:06 | 2023-01-01T15:48:06 | 85,393,224 | 3 | 2 | null | 2017-03-27T18:06:19 | 2017-03-18T10:30:06 | C++ | UTF-8 | C++ | false | false | 12,190 | cpp | #include <algorithm>
#include <cmath>
#include "CncCommon.h"
#include "CncCurveLib.h"
const float CncCurveLib::PI = 3.14159265359f;
//////////////////////////////////////////////////////////////////
void CncCurveLib::LastControlPoint::setCtrlPointAbs(const CncCurveLib::Point& p) {
//////////////////////////////////////////////////////////////////
valid = true;
point = p;
}
//////////////////////////////////////////////////////////////////
const CncCurveLib::Point& CncCurveLib::LastControlPoint::getLastCtrlPointAbs(const CncCurveLib::Point& currentPoint) const {
//////////////////////////////////////////////////////////////////
if ( hasControlPoint() )
return point;
// If there is no previous command or if the previous command was not a bezier + curve,
// assume the first control point is identically with the current point
return currentPoint;
}
//////////////////////////////////////////////////////////////////
const CncCurveLib::Point CncCurveLib::LastControlPoint::getLastCtrlPointReflectedAbs(const CncCurveLib::Point& currentPoint) const {
//////////////////////////////////////////////////////////////////
if ( hasControlPoint() ) {
// Reflect (mirroring) the last control point,
// where point is always absolute
const float dx = currentPoint.x - point.x;
const float dy = currentPoint.y - point.y;
CncCurveLib::Point p(
currentPoint.x + dx,
currentPoint.y + dy
);
return p;
}
// If there is no previous command or if the previous command was not a bezier + curve,
// assume the first control point is identically with the current point
return currentPoint;
}
//////////////////////////////////////////////////////////////////
float CncCurveLib::clamp(float val, float minVal, float maxVal) {
//////////////////////////////////////////////////////////////////
float tempMin = (std::min)(val, maxVal);
return (std::max)(minVal, tempMin);
}
//////////////////////////////////////////////////////////////////
float CncCurveLib::toRadians(float angle) {
//////////////////////////////////////////////////////////////////
return angle * (CncCurveLib::PI / 180);
}
//////////////////////////////////////////////////////////////////
float CncCurveLib::angleBetween(const CncCurveLib::Point& v0, const CncCurveLib::Point& v1) {
//////////////////////////////////////////////////////////////////
float p = v0.x * v1.x + v0.y * v1.y;
float n = sqrt((pow(v0.x, 2) + pow(v0.y, 2)) * (pow(v1.x, 2) + pow(v1.y, 2)));
float sign = v0.x * v1.y - v0.y * v1.x < 0 ? -1.0f : 1.0f;
float angle = sign * acos(p / n);
return angle;
}
//////////////////////////////////////////////////////////////////
float CncCurveLib::distance(const CncCurveLib::Point& p0, const CncCurveLib::Point& p1) {
//////////////////////////////////////////////////////////////////
return sqrt(pow(p1.x - p0.x, 2) + pow(p1.y - p0.y, 2));
}
//////////////////////////////////////////////////////////////////
void CncCurveLib::init(const CncCurveLib::Setup& s) {
//////////////////////////////////////////////////////////////////
setup = s;
}
//////////////////////////////////////////////////////////////////
const CncCurveLib::Point CncCurveLib::getPointOnLine(CncCurveLib::ParameterSet& ps, const float t) {
//////////////////////////////////////////////////////////////////
auto calculateLinearLineParameter = [](float v0, float v1, float t) {
const float result = v0 + (v1-v0)*t;
return result;
};
return CncCurveLib::Point( calculateLinearLineParameter(ps.p0.x, ps.p1.x, t),
calculateLinearLineParameter(ps.p0.y, ps.p1.y, t)
);
}
//////////////////////////////////////////////////////////////////
const CncCurveLib::Point CncCurveLib::getPointOnQuadraticBezierCurve (CncCurveLib::ParameterSet& ps, const float t) {
//////////////////////////////////////////////////////////////////
auto calculateQuadraticBezierParameter = [](float v0, float v1, float v2, float t) {
const float result = pow(1-t, 2)*v0 + 2*t*(1-t)*v1 + pow(t, 2)*v2;
return result;
};
return CncCurveLib::Point( calculateQuadraticBezierParameter(ps.p0.x, ps.p1.x, ps.p2.x, t),
calculateQuadraticBezierParameter(ps.p0.y, ps.p1.y, ps.p2.y, t)
);
}
//////////////////////////////////////////////////////////////////
const CncCurveLib::Point CncCurveLib::getPointOnCubicBezierCurve(CncCurveLib::ParameterSet& ps, const float t) {
//////////////////////////////////////////////////////////////////
auto calculateCubicBezierParameter = [](float v0, float v1, float v2, float v3, float t) {
const float result = pow(1-t, 3)*v0 + 3*t*pow(1-t, 2)*v1 + 3*(1-t)*pow(t, 2)*v2 + pow(t, 3)*v3;
return result;
};
return CncCurveLib::Point( calculateCubicBezierParameter(ps.p0.x, ps.p1.x, ps.p2.x, ps.p3.x, t),
calculateCubicBezierParameter(ps.p0.y, ps.p1.y, ps.p2.y, ps.p3.y, t)
);
}
//////////////////////////////////////////////////////////////////
const CncCurveLib::Point CncCurveLib::getPointOnEllipticalArc(CncCurveLib::ParameterSet& ps, const float t) {
//////////////////////////////////////////////////////////////////
// If the endpoints are identical, then this is equivalent to omitting the elliptical arc segment entirely.
if( ps.p0 == ps.p1 ) return ps.p0;
// If rx = 0 or ry = 0 then this arc is treated as a straight line segment joining the endpoints.
if( ps.rx == 0 || ps.ry == 0) return getPointOnLine(ps, t);
// From http://www.w3.org/TR/SVG/implnote.html#ArcParameterizationAlternatives
float angle = ps.EAPCI.startAngle + (ps.EAPCI.sweepAngle * t);
double ellipseComponentX = ps.rx * cos(angle);
double ellipseComponentY = ps.ry * sin(angle);
// Attach some extra info to use
ps.EARI.ellipticalArcCenter = CncCurveLib::Point(ps.EAPCI.center.x, ps.EAPCI.center.y);
ps.EARI.ellipticalArcStartAngle = ps.EAPCI.startAngle;
ps.EARI.ellipticalArcEndAngle = ps.EAPCI.startAngle + ps.EAPCI.sweepAngle;
ps.EARI.ellipticalArcAngle = angle;
ps.EARI.resultantRx = ps.rx;
ps.EARI.resultantRy = ps.ry;
auto point = CncCurveLib::Point(
cos(ps.EAPCI.xAxisRotationRadians)*ellipseComponentX - sin(ps.EAPCI.xAxisRotationRadians)*ellipseComponentY + ps.EAPCI.center.x,
sin(ps.EAPCI.xAxisRotationRadians)*ellipseComponentX + cos(ps.EAPCI.xAxisRotationRadians)*ellipseComponentY + ps.EAPCI.center.y
);
return point;
}
//////////////////////////////////////////////////////////////////
bool CncCurveLib::callback(const CncCurveLib::Point& p) {
//////////////////////////////////////////////////////////////////
if ( caller == NULL )
return false;
return caller->callback(p);
}
//////////////////////////////////////////////////////////////////
bool CncCurveLib::render(CncCurveLib::ParameterSet& ps) {
//////////////////////////////////////////////////////////////////
if ( ps.getType() != type ) {
std::cerr << "Incompatible parameter set: ["
<< type << " != " << ps.getType() << "]"
<< std::endl;
return false;
}
// ----------------------------------------------------------
// step 1: prepare parameters
ps.prepare();
// ----------------------------------------------------------
// step 2: approximate the curve length
ps.RI.curveLength = 0.0;
Point p0 = (this->*renderFunc)(ps, 0.0);
Point p1;
ps.RI.samples = setup.approximation.samples ? setup.approximation.samples : 50;
const float factor = (1.0f / ps.RI.samples);
for(unsigned int i = 0; i < ps.RI.samples; i++) {
float t = clamp(i * factor, 0.0f, 1.0f);
p1 = (this->*renderFunc)(ps, t);
ps.RI.curveLength += distance(p0, p1);
p0 = p1;
}
// stretch to end point
p1 = (this->*renderFunc)(ps, 1.0);
ps.RI.curveLength += distance(p0, p1);
// ----------------------------------------------------------
// step 3: determine the render increment
ps.RI.resolution = setup.resolution.size ? setup.resolution.size : 1;
ps.RI.steps = setup.resolution.size ? ps.RI.curveLength / setup.resolution.size : 1 ;
if ( ps.RI.steps > 1 ) ps.RI.increment = clamp(1.0 / ps.RI.steps, 0.0001, 0.99);
else ps.RI.increment = 1.0;
if ( false ) {
ps.trace(std::cout);
std::cout << std::endl;
std::cout << CNC_LOG_FUNCT << " ps.RI.samples : " << ps.RI.samples << std::endl;
std::cout << CNC_LOG_FUNCT << " ps.RI.resolution : " << ps.RI.resolution << std::endl;
std::cout << CNC_LOG_FUNCT << " ps.RI.curveLength: " << ps.RI.curveLength << std::endl;
std::cout << CNC_LOG_FUNCT << " ps.RI.steps : " << ps.RI.steps << std::endl;
std::cout << CNC_LOG_FUNCT << " ps.RI.increment : " << ps.RI.increment << std::endl;
}
// ----------------------------------------------------------
// step 4: render the function
Point p;
for ( float t = 0.0f; t <1.0f; t += ps.RI.increment ) {
p = (this->*renderFunc)(ps, t);
callback(p);
}
// stretch to end point
p = (this->*renderFunc)(ps, 1.0);
callback(p);
ps.RI.steps++;
return true;
}
//////////////////////////////////////////////////////////////////
void CncCurveLib::ParameterElliptical::prepare() {
//////////////////////////////////////////////////////////////////
EAPCI.preCalculated = true;
rx = fabs(rx);
ry = fabs(ry);
xAxisRotation = fmod(xAxisRotation, 360.0f);
EAPCI.xAxisRotationRadians = CncCurveLib::toRadians(xAxisRotation);
// Following "Conversion from endpoint to center parameterization"
// http://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter
// -----------------------------------------------------------
// Step #1: Compute transformedPoint
double dx = (p0.x - p1.x)/2;
double dy = (p0.y - p1.y)/2;
auto transformedPoint = CncCurveLib::Point(
+cos(EAPCI.xAxisRotationRadians) * dx + sin(EAPCI.xAxisRotationRadians) * dy,
-sin(EAPCI.xAxisRotationRadians) * dx + cos(EAPCI.xAxisRotationRadians) * dy
);
// Ensure radius are large enough
double radiiCheck = pow(transformedPoint.x, 2)/pow(rx, 2) + pow(transformedPoint.y, 2)/pow(ry, 2);
if( radiiCheck > 1 ) {
rx = sqrt(radiiCheck) * rx;
ry = sqrt(radiiCheck) * ry;
}
// -----------------------------------------------------------
// Step #2: Compute transformedCenter
double cSquareNumerator = pow(rx, 2)*pow(ry, 2) - pow(rx, 2)*pow(transformedPoint.y, 2) - pow(ry, 2)*pow(transformedPoint.x, 2);
double cSquareRootDenom = pow(rx, 2)*pow(transformedPoint.y, 2) + pow(ry, 2)*pow(transformedPoint.x, 2);
double cRadicand = cSquareNumerator/cSquareRootDenom;
// Make sure this never drops below zero because of precision
cRadicand = cRadicand < 0 ? 0 : cRadicand;
double cCoef = (largeArcFlag != sweepFlag ? 1 : -1) * sqrt(cRadicand);
auto transformedCenter = CncCurveLib::Point(
cCoef*(+(rx * transformedPoint.y) / ry),
cCoef*(-(ry * transformedPoint.x) / rx)
);
// -----------------------------------------------------------
// Step #3: Compute center
EAPCI.center = CncCurveLib::Point(
cos(EAPCI.xAxisRotationRadians) * transformedCenter.x - sin(EAPCI.xAxisRotationRadians) * transformedCenter.y + ((p0.x + p1.x)/2),
sin(EAPCI.xAxisRotationRadians) * transformedCenter.x + cos(EAPCI.xAxisRotationRadians) * transformedCenter.y + ((p0.y + p1.y)/2)
);
// -----------------------------------------------------------
// Step #4: Compute start/sweep angles
// Start angle of the elliptical arc prior to the stretch and rotate operations.
// Difference between the start and end angles
auto startVector = CncCurveLib::Point(
(transformedPoint.x-transformedCenter.x) / rx,
(transformedPoint.y-transformedCenter.y) / ry
);
EAPCI.startAngle = CncCurveLib::angleBetween(CncCurveLib::Point(1.0f, 0.0f), startVector);
auto endVector = CncCurveLib::Point(
(-transformedPoint.x - transformedCenter.x) / rx,
(-transformedPoint.y - transformedCenter.y) / ry
);
EAPCI.sweepAngle = CncCurveLib::angleBetween(startVector, endVector);
if ( !sweepFlag && EAPCI.sweepAngle > 0) EAPCI.sweepAngle -= 2 * PI;
else if( sweepFlag && EAPCI.sweepAngle < 0) EAPCI.sweepAngle += 2 * PI;
// We use % instead of `mod(..)` because we want it to be -360deg to 360deg(but actually in radians)
EAPCI.sweepAngle = fmod(EAPCI.sweepAngle, 2 * PI);
}
| [
"stefan.hoelzer@fplusp.de"
] | stefan.hoelzer@fplusp.de |
4b1a083d90ee43b1ad0b940e3c7c90c8c4ce99a3 | 8ae31e5db1f7c25b6ce1c708655ab55c15dde14e | /比赛/2019暑假中山纪念中学模拟测/2019.08.18【NOIP提高组】模拟 B 组/T1 能量获取/std.cpp | 98fe4afc87e8b88e8b32cbfe8a808c07af0449e8 | [] | no_license | LeverImmy/Codes | 99786afd826ae786b5024a3a73c8f92af09aae5d | ca28e61f55977e5b45d6731bc993c66e09f716a3 | refs/heads/master | 2020-09-03T13:00:29.025752 | 2019-12-16T12:11:23 | 2019-12-16T12:11:23 | 219,466,644 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,004 | cpp | #include <cstdio>
#include <cctype>
#include <algorithm>
#include <cstring>
#include <cmath>
#define ll long long
#define rgi register int
#define il inline
using namespace std;
const int N = 1000 + 10;
const int M = 1000 + 10;
int n, ans;
int F[N], C[N], W[N];
struct node
{
int id, w;
} Node[M << 1];
il int read()
{
rgi f = 0, x = 0, ch;
while(!isdigit(ch = getchar())) f |= ch == '-';
while(isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
return f ? -x : x;
}
bool cmp(struct node a, struct node b)
{
return a.w < b.w;
}
int main()
{
n = read();
for(rgi i = 1; i <= n; ++i)
{
F[i] = read();
Node[i].w = read();
C[i] = read();
Node[i].id = i;
}
sort(Node + 1, Node + n + 1, cmp);
for(rgi i = 1; i <= n; ++i)
{
int flag = 0;
for(rgi j = Node[i].id; j; j = F[j])
if(C[j] < Node[i].w)
{
flag = 1;
break;
}
if(flag)
continue;
for(rgi j = Node[i].id; j; j = F[j])
C[j] -= Node[i].w;
ans++;
}
printf("%d", ans);
return 0;
}
| [
"506503360@qq.com"
] | 506503360@qq.com |
02caf90c021f810fbf5e68222c58015dbe7c71c3 | cd3a0da00443d6c21bc196112f323ec8b6e8f392 | /FaceCaptureSdk/StreamDecoder/OpencvDecoder.cpp | 84f2d529bf48fda6a970177e07c27bd3412f0513 | [] | no_license | linuxmap/nazhiai | 021defdec6e07cb6765cb09e2fc972175a09141b | 6ccebcb28384423a7bf8ff89673079790f7d2d29 | refs/heads/master | 2020-03-28T16:52:55.780341 | 2018-09-14T03:30:33 | 2018-09-14T03:30:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,447 | cpp |
#include "OpencvDecoder.h"
OpencvDecoder::OpencvDecoder(const std::string& url, const DecoderParam& decoderParam, const DecodeParam& decodeParam, const std::string& id)
: BaseDecoder(url, decoderParam, decodeParam, id)
, _video()
{
}
OpencvDecoder::~OpencvDecoder()
{
}
void OpencvDecoder::Create() throw(BaseException)
{
// start video with OPENCV
char* pEnd;
long interval;
interval = strtol(_url.c_str(), &pEnd, 10);
if (ERANGE == errno)
{
throw BaseException(0, "USB port(" + _url + ") is not valid");
}
else
{
_video.open(static_cast<int>(interval));
}
// if video open failed
if (!_video.isOpened())
{
throw BaseException(0, "USB(" + _url + ") can not be opened");
}
// create decode thread
BaseDecoder::Create();
}
void OpencvDecoder::Destroy() throw(BaseException)
{
_video.release();
// destroy decode thread
BaseDecoder::Destroy();
}
bool OpencvDecoder::ReadFrame(cv::Mat& frame)
{
int readFailCount = 0;
while (!_video.read(frame)) {
if (++readFailCount >= 5) {
printf("%s failed[%d times]\n", __FUNCTION__, readFailCount);
return false;
}
}
return true;
}
bool OpencvDecoder::ReadFrame(cv::cuda::GpuMat& frame)
{
cv::Mat mat;
if (ReadFrame(mat))
{
frame.upload(mat);
return true;
}
else
{
return false;
}
}
| [
"wuzhigaoem@163.com"
] | wuzhigaoem@163.com |
6a24af29c6b9033c1981659232c3509afe0cd7a8 | 6ae13704faeb73df0160a590120cd03a5617ea75 | /src/http/HttpServer.h | 1c8daf2512721146297bc4b815a2032a83266bd0 | [] | no_license | moschulze/lighter | a8b3fb2c59abbef81eb76d43182efa51297244fd | b80202dd99ab70c93497d33422b3c4075c82059f | refs/heads/master | 2021-01-21T13:40:56.518296 | 2016-04-26T15:10:46 | 2016-04-26T15:10:46 | 49,629,184 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 456 | h | #ifndef LIGHTER_HTTPSERVER_H
#define LIGHTER_HTTPSERVER_H
#include "../scene/SceneRepository.h"
#include "../rendering/Renderer.h"
class HttpServer {
public:
HttpServer(int port, SceneRepository* sceneRepository, Renderer* renderer);
void init();
void start();
void stop();
private:
int port;
int serverSocket;
bool run = true;
SceneRepository* sceneRepository;
Renderer* renderer;
};
#endif //LIGHTER_HTTPSERVER_H
| [
"mo.schulze@gmx.net"
] | mo.schulze@gmx.net |
edd64557724755e3178139dd185105b5452d480e | 3eb2d746b586340965ea9053b090e5ee5c3a5e42 | /aero/include/aerogelStackingAction.hh | a2afb5532f9d295c33f255c0b0e640fb1649e0ab | [] | no_license | vardant/aerogel | b38bf5131c4969dbe8d36a58289b8049264dac9f | fbe0ba748705684d04a5b0783bef0d96100a3acb | refs/heads/master | 2020-05-25T03:33:33.257834 | 2019-07-24T05:27:18 | 2019-07-24T05:27:18 | 187,605,343 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 433 | hh | #ifndef aerogelStackingAction_H
#define aerogelStackingAction_H 1
#include "globals.hh"
#include "G4UserStackingAction.hh"
class aerogelStackingAction : public G4UserStackingAction
{
public:
aerogelStackingAction();
~aerogelStackingAction();
public:
G4ClassificationOfNewTrack ClassifyNewTrack(const G4Track* aTrack);
void NewStage();
void PrepareNewEvent();
private:
G4int gammaCounter;
};
#endif
| [
"tadevosn@jlab.org"
] | tadevosn@jlab.org |
29475730cc8e81ed9e2f16aa30245950373b4df3 | 0d0dccc6523525223e05e94d73428843858e1a18 | /opencensus/exporters/stats/prometheus/internal/prometheus_exporter.cc | 706b9b45fbbfdc3760e5cf87f5cae8a6b149a7ab | [
"Apache-2.0"
] | permissive | bianpengyuan/opencensus-cpp | eb7dc190efa305d7c6f8925212d35598c44f855d | 4ffcd168f165d9fc44b4581337275a071ff7a0da | refs/heads/master | 2021-07-13T02:42:59.764798 | 2019-11-27T05:47:19 | 2019-11-27T05:47:19 | 196,784,093 | 0 | 0 | Apache-2.0 | 2019-07-14T02:12:58 | 2019-07-14T02:12:58 | null | UTF-8 | C++ | false | false | 1,328 | cc | // Copyright 2018, OpenCensus 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 "opencensus/exporters/stats/prometheus/prometheus_exporter.h"
#include <utility>
#include <vector>
#include "opencensus/exporters/stats/prometheus/internal/prometheus_utils.h"
#include "opencensus/stats/stats.h"
#include "prometheus/metric_family.h"
namespace opencensus {
namespace exporters {
namespace stats {
std::vector<prometheus::MetricFamily> PrometheusExporter::Collect() {
const auto data = opencensus::stats::StatsExporter::GetViewData();
std::vector<prometheus::MetricFamily> output(data.size());
for (int i = 0; i < data.size(); ++i) {
SetMetricFamily(data[i].first, data[i].second, &output[i]);
}
return output;
}
} // namespace stats
} // namespace exporters
} // namespace opencensus
| [
"noreply@github.com"
] | noreply@github.com |
540245d197d4647acb6fceb1bf08b5b6f615f8c5 | 8dda45d2a2cdfafe300269db3b8b92c1f7795d86 | /src/15_inverse_kinematics/src/InverseKinematics.cpp | 460d376f1c11c4168d8c8d059b696718c694e848 | [] | no_license | Sarah0711/Humanoid-Robotics-assignments | f1d6711a4661d81b6d1ea114ca27e6ad11be1600 | 749c515897a28a98c1ca84ce38cde14653af78f5 | refs/heads/main | 2023-07-31T00:54:43.379234 | 2021-09-16T13:18:05 | 2021-09-16T13:18:05 | 403,677,120 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,292 | cpp | #include <inverse_kinematics/InverseKinematics.h>
#include <iostream>
#include <angles/angles.h>
namespace inverse_kinematics {
/**
* Computes the Moore-Penrose inverse (pseudo inverse) of a Jacobi matrix.
* @param a the Jacobi matrix
* @return the pseudo inverse.
*/
Eigen::MatrixXd pseudoInverse(const Jacobian &a)
{
// This method is fully implemented, nothing to do here.
// You can use this method in your code.
const double epsilon = std::numeric_limits<Jacobian::Scalar>::epsilon();
if (a.rows() < a.cols()) {
throw std::runtime_error("cannot compute pseudoinverse because the system is underdetermined");
}
const Eigen::JacobiSVD<Jacobian> svd = a.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV);
const Jacobian::Scalar tolerance = epsilon * std::max(a.cols(), a.rows()) * svd.singularValues().array().abs().maxCoeff();
return svd.matrixV() * Jacobian((svd.singularValues().array().abs() > tolerance).select(svd.singularValues().
array().inverse(), 0)).asDiagonal() * svd.matrixU().adjoint();
}
/**
* \brief return a homogeneous matrix representing a rotation in 2D.
* \param[in] angle The rotation angle.
* \return Homogeneous transformation matrix as an Eigen::Matrix3d.
*/
Cartesian2DTransform InverseKinematics::rotation(const double& angle) const {
Cartesian2DTransform result = Eigen::Matrix3d::Zero();
result << cos(angle), -sin(angle), 0,
sin(angle), cos(angle), 0,
0, 0, 1;
return result;
}
/**
* \brief return a homogeneous matrix representing a translation in 2D.
* \param[in] distance_x The translation distance in x direction.
* \param[in] distance_y The translation distance in y direction.
* \return Homogeneous transformation matrix as an Eigen::Matrix3d.
*/
Cartesian2DTransform InverseKinematics::translation(const double& distance_x, const double& distance_y) const {
Cartesian2DTransform result = Eigen::Matrix3d::Zero();
result << 1, 0, distance_x,
0, 1, distance_y,
0, 0, 1;
return result;
}
/**
* \brief Computes the endeffector pose from the current joint angles.
* \param[in] q The current joint angles (as an Eigen::VectorXd of size 2).
* \return The pose (e_x, e_y) of the hand (as an Eigen::VectorXd of size 2).
*/
EndeffectorPose InverseKinematics_2Links::forwardKinematic(const JointAngles& q) const {
EndeffectorPose e = Eigen::VectorXd::Zero(2);
// TODO: Calculate the forward kinematics.
Eigen::Vector3d grip = Eigen::Vector3d::Zero(3);
grip<<h,0,1;
Eigen::Vector3d e_homo = rotation(q(0))*translation(a0,0)*rotation(q(1))*translation(a1,0)*grip;
/* Use the class member variables a0, a1, and h for the lengths given on the exercise sheet. */
e<<e_homo(0),e_homo(1);
return e;
}
/**
* \brief Computes the Jacobian of the endeffector pose with respect to the joint angles.
* \param[in] q The current joint angles as an Eigen::VectorXd of length 2.
* \return The Jacobian as an Eigen::MatrixXd of size 2x2.
*/
Jacobian InverseKinematics_2Links::jacobian(const JointAngles& q) const {
Jacobian result = Eigen::MatrixXd::Zero(2, 2);
/* TODO: Fill in the Jacobian that you calculated by hand. */
/* Use the class member variables a0, a1, and h for the lengths given on the exercise sheet. */
result << -((h+a1)*sin(q(0) + q(1)) + a0*sin(q(0))), -(h+a1)*sin(q(0) + q(1)), (h+a1)*cos(q(0) + q(1)) + a0*cos(q(0)), (h+a1)*cos(q(0) + q(1));
return result;
}
/**
* \brief Computes a small change that moves the endeffector towards the goal.
* \param[in] e The current endeffector pose as an Eigen::VectorXd of size 2.
* \param[in] g The goal pose for the endeffector as an Eigen::VectorXd of size 2.
* \return A vector (delta_e_x, delta_e_y) as an Eigen::VectorXd of size 2.
*/
EndeffectorPose InverseKinematics::chooseStep(const EndeffectorPose& e, const EndeffectorPose& g) const {
EndeffectorPose delta_e = Eigen::VectorXd::Zero(e.size());
/* TODO: Choose the small step of the endeffector towards the goal (delta_e). */
/* The step size alpha is given as a class member variable. */
delta_e = alpha*(g - e);
return delta_e;
}
/**
* \brief Computes how the joint angles have to change in order to reach the step of the endeffector chosen in chooseStep() above.
* \param[in] delta_e The step of the endeffector choosen by the chooseStep() method as an Eigen::VectorXd.
* \param[in] jacobian The Jacobian of the endeffector pose with respect to the current joint angles as an Eigen::MatrixXd.
* \return The change of the joint angles delta_q as an Eigen::VectorXd.
*/
JointAngles InverseKinematics::computeJointChange(const EndeffectorPose& delta_e, const Jacobian& jacobian) const {
JointAngles delta_q = Eigen::VectorXd::Zero(jacobian.cols());
/* TODO: Calculate the change of joint angles delta_q that is required to achieve the given
* change of the endeffector pose delta_e.
*/
/* There are two possibilities to get the inverse of the Jacobian:
* - jacobian.inverse(): Exact solution, but sensitive to singularities
* - pseudoInverse(jacobian): Returns the Moore-Penrose pseudoinverse, approximate solution, but more robust to singularities
*/
delta_q = pseudoInverse(jacobian)*delta_e;
return delta_q;
}
/**
* \brief Applies delta_q computed by computeJointChange() to the current joint angles.
* \param[in] q The current joint angles as an Eigen::VectorXd.
* \param[in] delta_q The desired change of the joint angles as an Eigen::VectorXd of the same length.
* \return The new joint angles as an Eigen::VectorXd.
*/
JointAngles InverseKinematics::applyChangeToJoints(const JointAngles& q, const JointAngles& delta_q) const {
JointAngles q_new = Eigen::VectorXd::Zero(q.size());
// TODO: Calculate the new joint angles.
q_new = q + delta_q;
return q_new;
}
/**
* \brief Performs one iteration of the inverse kinematics algorithm (the body of the while loop).
* \param[in,out] q The current joint angles as an Eigen::VectorXd.
* \param[out] e The current endeffector pose as an Eigen::VectorXd.
* \param[in] g The goal pose of the endeffector as an Eigen::VectorXd.
*/
void InverseKinematics::oneIteration(JointAngles& q, EndeffectorPose& e, const EndeffectorPose& g) const {
/* TODO: Implement one iteration (= the body of the while loop) here
* using the methods defined above to compute the new joint angles q and
* endeffector pose e.
*/
q =applyChangeToJoints(q , computeJointChange(chooseStep(e,g), jacobian(q)));
e = forwardKinematic(q);
}
/**
* \brief The complete inverse kinematics algorithm.
* \param[in] g The goal endeffector pose.
* \param[in] maxTranslationalError The maximum acceptable distance between the endeffector pose and the desired goal pose.
* \return The joint angles for reaching the given goal pose with the endeffector.
*/
JointAngles InverseKinematics_2Links::computeIK(const EndeffectorPose& g, const double& maxTranslationalError) const {
JointAngles q = Eigen::VectorXd::Zero(2);
/* TODO: Initialize q appropriately and call the oneIteration() method
* from above in a while loop.
*/
EndeffectorPose e = forwardKinematic(q);
while( sqrt((e(0)-g(0))*(e(0)-g(0)) + (e(1)-g(1))*(e(1)-g(1))) > maxTranslationalError){
oneIteration(q,e,g);
}
return q;
}
/* ============================================================================
* | The following methods are for part d)-f) with a robot arm with 3 links |
* ============================================================================*/
/**
* \brief Computes the forward kinematics for a robot arm with three links.
* \param[in] q The current joint angles as an Eigen::VectorXd of size 3.
* \return The endeffector pose e = (e_x, e_y, e_theta) as an Eigen::VectorXd of size 3.
*/
EndeffectorPose InverseKinematics_3Links::forwardKinematic(const JointAngles& q) const {
EndeffectorPose e = Eigen::VectorXd::Zero(3);
/* TODO: Calculate the endeffector pose e = (e_x, e_y, e_theta) */
Eigen::Vector3d grip = Eigen::Vector3d::Zero(3);
grip<<h,0,1;
Eigen::Vector3d e_homo = rotation(q(0))*translation(a0,0)*rotation(q(1))*translation(a1,0)*rotation(q(2))*translation(a2,0)*grip;
e<<e_homo(0),e_homo(1),q(0)+q(1)+q(2);
return e;
}
/**
* \brief Approximates the Jacobian using the quotient of differences.
* \param[in] q The current joint angles as an Eigen::VectorXd of size 3.
* \return The approximated jacobian as an Eigen::MatrixXd of size 3 x 3.
*/
Jacobian InverseKinematics_3Links::jacobian(const JointAngles& q) const {
Jacobian result = Eigen::MatrixXd::Zero(3, 3);
const double epsilon = 1e-7;
/* TODO: Approximate the Jacobian using the quotient of differences method.
* Add the epsilon defined above to the components of q and call forwardKinematic()
* to compute the endeffector pose. Then compose the Jacobian from the differences
* as described on the exercise sheet.
*/
JointAngles q0_eps = Eigen::VectorXd::Zero(3);
q0_eps<<q(0) + epsilon,q(1),q(2);
JointAngles q1_eps = Eigen::VectorXd::Zero(3);
q1_eps<<q(0),q(1) + epsilon,q(2);
JointAngles q2_eps = Eigen::VectorXd::Zero(3);
q2_eps<<q(0),q(1),q(2) + epsilon;
result << (forwardKinematic(q0_eps) - forwardKinematic(q))/epsilon, (forwardKinematic(q1_eps) - forwardKinematic(q))/epsilon, (forwardKinematic(q2_eps) - forwardKinematic(q))/epsilon;
return result;
}
/**
* \brief The complete inverse kinematics algorithm.
* \param[in] g The goal endeffector pose.
* \param[in] maxTranslationalError The maximum acceptable distance between the endeffector pose and the desired goal pose.
* \param[in] maxAngularError The maximum acceptable angular error between the endeffector orientation and the desired goal orientation.
* \return The joint angles for reaching the given goal pose with the endeffector.
*/
JointAngles InverseKinematics_3Links::computeIK(const EndeffectorPose& g, const double& maxTranslationalError, const double& maxAngularError) const {
JointAngles q = Eigen::VectorXd::Zero(3);
/* TODO: Initialize q appropriately and call the oneIteration() method
* from above in a while loop.
*/
EndeffectorPose e = forwardKinematic(q);
while( sqrt((e(0)-g(0))*(e(0)-g(0)) + (e(1)-g(1))*(e(1)-g(1))) > maxTranslationalError || (e(2)-g(2) > maxAngularError) ){
oneIteration(q,e,g);
}
return q;
}
} // namespace inverse_kinematics
| [
"sarahjmi07@gmail.com"
] | sarahjmi07@gmail.com |
7b874cc37f57ef8a765794af3cce89515ef736d7 | 13c756aabf546fb46bb6a9dbbdb3ea5d0d8b5356 | /ACM/数据结构/二叉树中序+后序-层序.cpp | 583553fe9207c0cabe020bb42eaeae259d6bb234 | [] | no_license | JosephZ7/ACM | def2fa0030989464bbaebeab400d88815df1c410 | 63c9d696dad4d010468750e783a151e68a0395ae | refs/heads/master | 2021-01-19T18:41:53.788146 | 2018-07-23T08:12:04 | 2018-07-23T08:12:04 | 101,154,332 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,365 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <string>
#include <algorithm>
#include <vector>
#include <map>
#include <queue>
#include <iostream>
#define PI 3.141592653589793
#define LL long long
#define MAX 0x3fffffff
#define INF 0x3f3f3f3f
#define mem(a,v) memset(a,v,sizeof(a))
const int MAX_N = 1e5+10;
const double eps = 1e-8;
const LL mod = 1000000009;
const LL inf = 1e15+5;
using namespace std;
int b[200],d[200];
map<int, int>L, R;
int build(int ld,int rd,int lb,int rb)
{
if(lb > rb)
return 0;
int i;
int rt = b[rb];
for(i = ld;i <= rd;i++)
if(d[i] == rt)
break;
if(i <= rd)
{
L[rt] = build(ld,i-1,lb,rb-rd+i-1);
R[rt] = build(i+1,rd,rb-rd+i,rb-1);
}
return rt;
}
void BFS(int rt)
{
queue<int> q;
q.push(rt);
int x = 0;
while(!q.empty())
{
int t = q.front();
q.pop();
if(x == 0)
printf("%d",t);
else
printf(" %d",t);
x++;
if(L[t])
q.push(L[t]);
if(R[t])
q.push(R[t]);
}
cout<<endl;
}
int main()
{
int N;
scanf("%d",&N);
for(int i = 1;i <= N;i++)
scanf("%d",&b[i]);
for(int i = 1;i <= N;i++)
scanf("%d",&d[i]);
int rt = build(1,N,1,N);
BFS(rt);
return 0;
}
/*
*/
| [
"1072920311@qq.com"
] | 1072920311@qq.com |
97dc015e80fed5ebdc93d8fb297400d6378ca4b8 | 56dd5146f53221aa16b24e31501cc4377573a70e | /HiveEngine/src/HiveComponents/TransformComponent.h | 671bc2da53a59e57e50b0866e0243d673765f456 | [] | no_license | simonverrelst/Hive-Engine | f0da6666e11664c282b00fd8a509d328f8e8478f | 463101b5c99a6dec78adb566a9a450b4173d9761 | refs/heads/master | 2021-05-24T11:23:04.204932 | 2020-06-18T12:05:35 | 2020-06-18T12:05:35 | 249,001,746 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 785 | h | #pragma once
#include "HiveCore/Core.h"
#include "Component.h"
#include <glm/vec3.hpp>
#include <glm/vec2.hpp>
namespace Hive
{
enum TransformState
{
translating,
rotated,
simulated,
};
class TransformComponent final :
public Component
{
public:
TransformComponent() = default;
virtual ~TransformComponent();
glm::vec2 GetPosition() const { return m_Position; }
float GetRotation() const { return m_Rotation; }
glm::vec2 GetScale() const { return m_Scale; }
void SetPosition(float x, float y);
void SetPosition(const glm::vec2 & position);
void SetRotation(float angle, bool euler);
void SetScale(const glm::vec2& scale) { m_Scale = scale; };
private:
glm::vec2 m_Position{};
float m_Rotation{};
glm::vec2 m_Scale{1.f,1.f};
};
}
| [
"simon.verrelst@student.howest.be"
] | simon.verrelst@student.howest.be |
06872fa370fd7a5003f6297bceee3851f14c674b | 7fdf48345a3178fd6ec582d99b34897965b09e82 | /support/xerces/src/util/FlagJanitor.hpp | 9e01536552739d9b91e92c3cf860bb0c8104bd7a | [
"Apache-1.1",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | hhy5277/livingstone2 | e748c3cec0b5b5e94e7acb6c812c879dce399f22 | 38fa2f1d81ff6124e37aff21b5c73751ad25fec0 | refs/heads/master | 2020-04-18T01:13:42.154101 | 2018-01-12T03:09:27 | 2018-01-12T03:09:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,714 | hpp | /*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log: FlagJanitor.hpp,v $
* Revision 1.1.1.1 2000/04/08 04:38:03 kurien
* XML parser for C++
*
*
* Revision 1.3 2000/02/24 20:05:24 abagchi
* Swat for removing Log from API docs
*
* Revision 1.2 2000/02/06 07:48:01 rahulj
* Year 2K copyright swat.
*
* Revision 1.1.1.1 1999/11/09 01:04:17 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:06 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
#if !defined(FLAGJANITOR_HPP)
#define FLAGJANITOR_HPP
#include <util/XML4CDefs.hpp>
template <class T> class FlagJanitor
{
public :
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
FlagJanitor(T* const valPtr, const T newVal);
~FlagJanitor();
// -----------------------------------------------------------------------
// Value management methods
// -----------------------------------------------------------------------
void release();
private :
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
FlagJanitor();
FlagJanitor(const FlagJanitor<T>&);
void operator=(const FlagJanitor<T>&);
// -----------------------------------------------------------------------
// Private data members
//
// fOldVal
// The old value that was in the flag when we were constructed.
//
// fValPtr
// A pointer to the flag that we are to restore the value of
// -----------------------------------------------------------------------
T fOldVal;
T* fValPtr;
};
#if !defined(XML4C_TMPLSINC)
#include <util/FlagJanitor.c>
#endif
#endif
| [
"gpgreen@gmail.com"
] | gpgreen@gmail.com |
424a9783c97bc7c20dbe7519f18d3bf95145c24e | ddc76a1ef868fc5d92230c0bf6e433b0a24d6fe5 | /includes/acl/math/vector4_32.h | c5e68d73000dc09e078db13d1f681f3a6cec0b54 | [
"MIT"
] | permissive | swordlegend/acl | 33b14e26532cb93be875f2585c151a53184129b2 | 0fb33a80d758b77b3115be248d569eb4cf09877b | refs/heads/master | 2020-03-25T15:13:00.509311 | 2018-07-21T00:20:41 | 2018-07-21T00:20:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,363 | h | #pragma once
////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2017 Nicholas Frechette & Animation Compression Library contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
////////////////////////////////////////////////////////////////////////////////
#include "acl/core/error.h"
#include "acl/core/memory_utils.h"
#include "acl/math/math.h"
#include "acl/math/scalar_32.h"
namespace acl
{
//////////////////////////////////////////////////////////////////////////
// Setters, getters, and casts
inline Vector4_32 vector_set(float x, float y, float z, float w)
{
#if defined(ACL_SSE2_INTRINSICS)
return Vector4_32(_mm_set_ps(w, z, y, x));
#else
return Vector4_32{ x, y, z, w };
#endif
}
inline Vector4_32 vector_set(float x, float y, float z)
{
#if defined(ACL_SSE2_INTRINSICS)
return Vector4_32(_mm_set_ps(0.0f, z, y, x));
#else
return Vector4_32{ x, y, z, 0.0f };
#endif
}
inline Vector4_32 vector_set(float xyzw)
{
#if defined(ACL_SSE2_INTRINSICS)
return Vector4_32(_mm_set_ps1(xyzw));
#else
return Vector4_32{ xyzw, xyzw, xyzw, xyzw };
#endif
}
inline Vector4_32 vector_unaligned_load(const float* input)
{
ACL_ASSERT(is_aligned(input), "Invalid alignment");
return vector_set(input[0], input[1], input[2], input[3]);
}
inline Vector4_32 vector_unaligned_load3(const float* input)
{
ACL_ASSERT(is_aligned(input), "Invalid alignment");
return vector_set(input[0], input[1], input[2], 0.0f);
}
inline Vector4_32 vector_unaligned_load_32(const uint8_t* input)
{
Vector4_32 result;
memcpy(&result, input, sizeof(Vector4_32));
return result;
}
inline Vector4_32 vector_unaligned_load3_32(const uint8_t* input)
{
float input_f[3];
memcpy(&input_f[0], input, sizeof(float) * 3);
return vector_set(input_f[0], input_f[1], input_f[2], 0.0f);
}
inline Vector4_32 vector_zero_32()
{
return vector_set(0.0f, 0.0f, 0.0f, 0.0f);
}
inline Vector4_32 quat_to_vector(const Quat_32& input)
{
#if defined(ACL_SSE2_INTRINSICS)
return input;
#else
return Vector4_32{ input.x, input.y, input.z, input.w };
#endif
}
inline Vector4_32 vector_cast(const Vector4_64& input)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_shuffle_ps(_mm_cvtpd_ps(input.xy), _mm_cvtpd_ps(input.zw), _MM_SHUFFLE(1, 0, 1, 0));
#else
return Vector4_32{ float(input.x), float(input.y), float(input.z), float(input.w) };
#endif
}
inline float vector_get_x(const Vector4_32& input)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_cvtss_f32(input);
#else
return input.x;
#endif
}
inline float vector_get_y(const Vector4_32& input)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_cvtss_f32(_mm_shuffle_ps(input, input, _MM_SHUFFLE(1, 1, 1, 1)));
#else
return input.y;
#endif
}
inline float vector_get_z(const Vector4_32& input)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_cvtss_f32(_mm_shuffle_ps(input, input, _MM_SHUFFLE(2, 2, 2, 2)));
#else
return input.z;
#endif
}
inline float vector_get_w(const Vector4_32& input)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_cvtss_f32(_mm_shuffle_ps(input, input, _MM_SHUFFLE(3, 3, 3, 3)));
#else
return input.w;
#endif
}
template<VectorMix component_index>
inline float vector_get_component(const Vector4_32& input)
{
switch (component_index)
{
case VectorMix::A:
case VectorMix::X: return vector_get_x(input);
case VectorMix::B:
case VectorMix::Y: return vector_get_y(input);
case VectorMix::C:
case VectorMix::Z: return vector_get_z(input);
case VectorMix::D:
case VectorMix::W: return vector_get_w(input);
default:
ACL_ASSERT(false, "Invalid component index");
return 0.0f;
}
}
inline float vector_get_component(const Vector4_32& input, VectorMix component_index)
{
switch (component_index)
{
case VectorMix::A:
case VectorMix::X: return vector_get_x(input);
case VectorMix::B:
case VectorMix::Y: return vector_get_y(input);
case VectorMix::C:
case VectorMix::Z: return vector_get_z(input);
case VectorMix::D:
case VectorMix::W: return vector_get_w(input);
default:
ACL_ASSERT(false, "Invalid component index");
return 0.0f;
}
}
inline const float* vector_as_float_ptr(const Vector4_32& input)
{
return reinterpret_cast<const float*>(&input);
}
inline void vector_unaligned_write(const Vector4_32& input, float* output)
{
ACL_ASSERT(is_aligned(output), "Invalid alignment");
output[0] = vector_get_x(input);
output[1] = vector_get_y(input);
output[2] = vector_get_z(input);
output[3] = vector_get_w(input);
}
inline void vector_unaligned_write3(const Vector4_32& input, float* output)
{
ACL_ASSERT(is_aligned(output), "Invalid alignment");
output[0] = vector_get_x(input);
output[1] = vector_get_y(input);
output[2] = vector_get_z(input);
}
inline void vector_unaligned_write(const Vector4_32& input, uint8_t* output)
{
memcpy(output, &input, sizeof(Vector4_32));
}
inline void vector_unaligned_write3(const Vector4_32& input, uint8_t* output)
{
memcpy(output, &input, sizeof(float) * 3);
}
//////////////////////////////////////////////////////////////////////////
// Arithmetic
inline Vector4_32 vector_add(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_add_ps(lhs, rhs);
#else
return vector_set(lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z, lhs.w + rhs.w);
#endif
}
inline Vector4_32 vector_sub(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_sub_ps(lhs, rhs);
#else
return vector_set(lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z, lhs.w - rhs.w);
#endif
}
inline Vector4_32 vector_mul(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_mul_ps(lhs, rhs);
#else
return vector_set(lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z, lhs.w * rhs.w);
#endif
}
inline Vector4_32 vector_mul(const Vector4_32& lhs, float rhs)
{
return vector_mul(lhs, vector_set(rhs));
}
inline Vector4_32 vector_div(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_div_ps(lhs, rhs);
#else
return vector_set(lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z, lhs.w / rhs.w);
#endif
}
inline Vector4_32 vector_max(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_max_ps(lhs, rhs);
#else
return vector_set(max(lhs.x, rhs.x), max(lhs.y, rhs.y), max(lhs.z, rhs.z), max(lhs.w, rhs.w));
#endif
}
inline Vector4_32 vector_min(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_min_ps(lhs, rhs);
#else
return vector_set(min(lhs.x, rhs.x), min(lhs.y, rhs.y), min(lhs.z, rhs.z), min(lhs.w, rhs.w));
#endif
}
inline Vector4_32 vector_abs(const Vector4_32& input)
{
#if defined(ACL_SSE2_INTRINSICS)
return vector_max(vector_sub(_mm_setzero_ps(), input), input);
#else
return vector_set(abs(input.x), abs(input.y), abs(input.z), abs(input.w));
#endif
}
inline Vector4_32 vector_neg(const Vector4_32& input)
{
return vector_mul(input, -1.0f);
}
inline Vector4_32 vector_reciprocal(const Vector4_32& input)
{
#if defined(ACL_SSE2_INTRINSICS)
// Perform two passes of Newton-Raphson iteration on the hardware estimate
__m128 x0 = _mm_rcp_ps(input);
// First iteration
__m128 x1 = _mm_sub_ps(_mm_add_ps(x0, x0), _mm_mul_ps(input, _mm_mul_ps(x0, x0)));
// Second iteration
__m128 x2 = _mm_sub_ps(_mm_add_ps(x1, x1), _mm_mul_ps(input, _mm_mul_ps(x1, x1)));
return x2;
#else
return vector_div(vector_set(1.0f), input);
#endif
}
inline Vector4_32 vector_cross3(const Vector4_32& lhs, const Vector4_32& rhs)
{
return vector_set(vector_get_y(lhs) * vector_get_z(rhs) - vector_get_z(lhs) * vector_get_y(rhs),
vector_get_z(lhs) * vector_get_x(rhs) - vector_get_x(lhs) * vector_get_z(rhs),
vector_get_x(lhs) * vector_get_y(rhs) - vector_get_y(lhs) * vector_get_x(rhs));
}
inline float vector_dot(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE4_INTRINSICS) && 0
// SSE4 dot product instruction isn't precise enough
return _mm_cvtss_f32(_mm_dp_ps(lhs, rhs, 0xFF));
#elif defined(ACL_SSE2_INTRINSICS)
__m128 x2_y2_z2_w2 = _mm_mul_ps(lhs, rhs);
__m128 z2_w2_0_0 = _mm_shuffle_ps(x2_y2_z2_w2, x2_y2_z2_w2, _MM_SHUFFLE(0, 0, 3, 2));
__m128 x2z2_y2w2_0_0 = _mm_add_ps(x2_y2_z2_w2, z2_w2_0_0);
__m128 y2w2_0_0_0 = _mm_shuffle_ps(x2z2_y2w2_0_0, x2z2_y2w2_0_0, _MM_SHUFFLE(0, 0, 0, 1));
__m128 x2y2z2w2_0_0_0 = _mm_add_ps(x2z2_y2w2_0_0, y2w2_0_0_0);
return _mm_cvtss_f32(x2y2z2w2_0_0_0);
#else
return (vector_get_x(lhs) * vector_get_x(rhs)) + (vector_get_y(lhs) * vector_get_y(rhs)) + (vector_get_z(lhs) * vector_get_z(rhs)) + (vector_get_w(lhs) * vector_get_w(rhs));
#endif
}
inline float vector_dot3(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE4_INTRINSICS) && 0
// SSE4 dot product instruction isn't precise enough
return _mm_cvtss_f32(_mm_dp_ps(lhs, rhs, 0x7F));
#elif defined(ACL_SSE2_INTRINSICS)
__m128 x2_y2_z2_w2 = _mm_mul_ps(lhs, rhs);
__m128 y2_0_0_0 = _mm_shuffle_ps(x2_y2_z2_w2, x2_y2_z2_w2, _MM_SHUFFLE(0, 0, 0, 1));
__m128 x2y2_0_0_0 = _mm_add_ss(x2_y2_z2_w2, y2_0_0_0);
__m128 z2_0_0_0 = _mm_shuffle_ps(x2_y2_z2_w2, x2_y2_z2_w2, _MM_SHUFFLE(0, 0, 0, 2));
__m128 x2y2z2_0_0_0 = _mm_add_ss(x2y2_0_0_0, z2_0_0_0);
return _mm_cvtss_f32(x2y2z2_0_0_0);
#else
return (vector_get_x(lhs) * vector_get_x(rhs)) + (vector_get_y(lhs) * vector_get_y(rhs)) + (vector_get_z(lhs) * vector_get_z(rhs));
#endif
}
inline float vector_length_squared(const Vector4_32& input)
{
return vector_dot(input, input);
}
inline float vector_length_squared3(const Vector4_32& input)
{
return vector_dot3(input, input);
}
inline float vector_length(const Vector4_32& input)
{
return sqrt(vector_length_squared(input));
}
inline float vector_length3(const Vector4_32& input)
{
return sqrt(vector_length_squared3(input));
}
inline float vector_length_reciprocal(const Vector4_32& input)
{
return sqrt_reciprocal(vector_length_squared(input));
}
inline float vector_length_reciprocal3(const Vector4_32& input)
{
return sqrt_reciprocal(vector_length_squared3(input));
}
inline float vector_distance3(const Vector4_32& lhs, const Vector4_32& rhs)
{
return vector_length3(vector_sub(rhs, lhs));
}
inline Vector4_32 vector_normalize3(const Vector4_32& input, float threshold = 1.0e-8f)
{
// Reciprocal is more accurate to normalize with
const float len_sq = vector_length_squared3(input);
if (len_sq >= threshold)
return vector_mul(input, vector_set(sqrt_reciprocal(len_sq)));
else
return input;
}
inline Vector4_32 vector_lerp(const Vector4_32& start, const Vector4_32& end, float alpha)
{
return vector_add(start, vector_mul(vector_sub(end, start), vector_set(alpha)));
}
inline Vector4_32 vector_fraction(const Vector4_32& input)
{
return vector_set(fraction(vector_get_x(input)), fraction(vector_get_y(input)), fraction(vector_get_z(input)), fraction(vector_get_w(input)));
}
// output = (input * scale) + offset
inline Vector4_32 vector_mul_add(const Vector4_32& input, const Vector4_32& scale, const Vector4_32& offset)
{
return vector_add(vector_mul(input, scale), offset);
}
// output = offset - (input * scale)
inline Vector4_32 vector_neg_mul_sub(const Vector4_32& input, const Vector4_32& scale, const Vector4_32& offset)
{
return vector_sub(offset, vector_mul(input, scale));
}
//////////////////////////////////////////////////////////////////////////
// Comparisons and masking
inline Vector4_32 vector_less_than(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_cmplt_ps(lhs, rhs);
#else
return Vector4_32{ math_impl::get_mask_value(lhs.x < rhs.x), math_impl::get_mask_value(lhs.y < rhs.y), math_impl::get_mask_value(lhs.z < rhs.z), math_impl::get_mask_value(lhs.w < rhs.w) };
#endif
}
inline Vector4_32 vector_greater_equal(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_cmpge_ps(lhs, rhs);
#else
return Vector4_32{ math_impl::get_mask_value(lhs.x >= rhs.x), math_impl::get_mask_value(lhs.y >= rhs.y), math_impl::get_mask_value(lhs.z >= rhs.z), math_impl::get_mask_value(lhs.w >= rhs.w) };
#endif
}
inline bool vector_all_less_than(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_movemask_ps(_mm_cmplt_ps(lhs, rhs)) == 0xF;
#else
return lhs.x < rhs.x && lhs.y < rhs.y && lhs.z < rhs.z && lhs.w < rhs.w;
#endif
}
inline bool vector_all_less_than3(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return (_mm_movemask_ps(_mm_cmplt_ps(lhs, rhs)) & 0x7) == 0x7;
#else
return lhs.x < rhs.x && lhs.y < rhs.y && lhs.z < rhs.z;
#endif
}
inline bool vector_any_less_than(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_movemask_ps(_mm_cmplt_ps(lhs, rhs)) != 0;
#else
return lhs.x < rhs.x || lhs.y < rhs.y || lhs.z < rhs.z || lhs.w < rhs.w;
#endif
}
inline bool vector_any_less_than3(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return (_mm_movemask_ps(_mm_cmplt_ps(lhs, rhs)) & 0x7) != 0;
#else
return lhs.x < rhs.x || lhs.y < rhs.y || lhs.z < rhs.z;
#endif
}
inline bool vector_all_less_equal(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_movemask_ps(_mm_cmple_ps(lhs, rhs)) == 0xF;
#else
return lhs.x <= rhs.x && lhs.y <= rhs.y && lhs.z <= rhs.z && lhs.w <= rhs.w;
#endif
}
inline bool vector_all_less_equal3(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return (_mm_movemask_ps(_mm_cmple_ps(lhs, rhs)) & 0x7) == 0x7;
#else
return lhs.x <= rhs.x && lhs.y <= rhs.y && lhs.z <= rhs.z;
#endif
}
inline bool vector_any_less_equal(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_movemask_ps(_mm_cmple_ps(lhs, rhs)) != 0;
#else
return lhs.x <= rhs.x || lhs.y <= rhs.y || lhs.z <= rhs.z || lhs.w <= rhs.w;
#endif
}
inline bool vector_any_less_equal3(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return (_mm_movemask_ps(_mm_cmple_ps(lhs, rhs)) & 0x7) != 0;
#else
return lhs.x <= rhs.x || lhs.y <= rhs.y || lhs.z <= rhs.z;
#endif
}
inline bool vector_all_greater_equal(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_movemask_ps(_mm_cmpge_ps(lhs, rhs)) == 0xF;
#else
return lhs.x >= rhs.x && lhs.y >= rhs.y && lhs.z >= rhs.z && lhs.w >= rhs.w;
#endif
}
inline bool vector_all_greater_equal3(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return (_mm_movemask_ps(_mm_cmpge_ps(lhs, rhs)) & 0x7) == 0x7;
#else
return lhs.x >= rhs.x && lhs.y >= rhs.y && lhs.z >= rhs.z;
#endif
}
inline bool vector_any_greater_equal(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_movemask_ps(_mm_cmpge_ps(lhs, rhs)) != 0;
#else
return lhs.x >= rhs.x || lhs.y >= rhs.y || lhs.z >= rhs.z || lhs.w >= rhs.w;
#endif
}
inline bool vector_any_greater_equal3(const Vector4_32& lhs, const Vector4_32& rhs)
{
#if defined(ACL_SSE2_INTRINSICS)
return (_mm_movemask_ps(_mm_cmpge_ps(lhs, rhs)) & 0x7) != 0;
#else
return lhs.x >= rhs.x || lhs.y >= rhs.y || lhs.z >= rhs.z;
#endif
}
inline bool vector_all_near_equal(const Vector4_32& lhs, const Vector4_32& rhs, float threshold = 0.00001f)
{
return vector_all_less_equal(vector_abs(vector_sub(lhs, rhs)), vector_set(threshold));
}
inline bool vector_all_near_equal3(const Vector4_32& lhs, const Vector4_32& rhs, float threshold = 0.00001f)
{
return vector_all_less_equal3(vector_abs(vector_sub(lhs, rhs)), vector_set(threshold));
}
inline bool vector_any_near_equal(const Vector4_32& lhs, const Vector4_32& rhs, float threshold = 0.00001f)
{
return vector_any_less_equal(vector_abs(vector_sub(lhs, rhs)), vector_set(threshold));
}
inline bool vector_any_near_equal3(const Vector4_32& lhs, const Vector4_32& rhs, float threshold = 0.00001f)
{
return vector_any_less_equal3(vector_abs(vector_sub(lhs, rhs)), vector_set(threshold));
}
inline bool vector_is_finite(const Vector4_32& input)
{
return is_finite(vector_get_x(input)) && is_finite(vector_get_y(input)) && is_finite(vector_get_z(input)) && is_finite(vector_get_w(input));
}
inline bool vector_is_finite3(const Vector4_32& input)
{
return is_finite(vector_get_x(input)) && is_finite(vector_get_y(input)) && is_finite(vector_get_z(input));
}
//////////////////////////////////////////////////////////////////////////
// Swizzling, permutations, and mixing
inline Vector4_32 vector_blend(const Vector4_32& mask, const Vector4_32& if_true, const Vector4_32& if_false)
{
#if defined(ACL_SSE2_INTRINSICS)
return _mm_or_ps(_mm_andnot_ps(mask, if_false), _mm_and_ps(if_true, mask));
#else
return Vector4_32{ math_impl::select(mask.x, if_true.x, if_false.x), math_impl::select(mask.y, if_true.y, if_false.y), math_impl::select(mask.z, if_true.z, if_false.z), math_impl::select(mask.w, if_true.w, if_false.w) };
#endif
}
template<VectorMix comp0, VectorMix comp1, VectorMix comp2, VectorMix comp3>
inline Vector4_32 vector_mix(const Vector4_32& input0, const Vector4_32& input1)
{
if (math_impl::is_vector_mix_arg_xyzw(comp0) && math_impl::is_vector_mix_arg_xyzw(comp1) && math_impl::is_vector_mix_arg_xyzw(comp2) && math_impl::is_vector_mix_arg_xyzw(comp3))
{
// All four components come from input 0
#if defined(ACL_SSE2_INTRINSICS)
return _mm_shuffle_ps(input0, input0, _MM_SHUFFLE(GET_VECTOR_MIX_COMPONENT_INDEX(comp3), GET_VECTOR_MIX_COMPONENT_INDEX(comp2), GET_VECTOR_MIX_COMPONENT_INDEX(comp1), GET_VECTOR_MIX_COMPONENT_INDEX(comp0)));
#else
return vector_set(vector_get_component(input0, comp0), vector_get_component(input0, comp1), vector_get_component(input0, comp2), vector_get_component(input0, comp3));
#endif
}
if (math_impl::is_vector_mix_arg_abcd(comp0) && math_impl::is_vector_mix_arg_abcd(comp1) && math_impl::is_vector_mix_arg_abcd(comp2) && math_impl::is_vector_mix_arg_abcd(comp3))
{
// All four components come from input 1
#if defined(ACL_SSE2_INTRINSICS)
return _mm_shuffle_ps(input1, input1, _MM_SHUFFLE(GET_VECTOR_MIX_COMPONENT_INDEX(comp3), GET_VECTOR_MIX_COMPONENT_INDEX(comp2), GET_VECTOR_MIX_COMPONENT_INDEX(comp1), GET_VECTOR_MIX_COMPONENT_INDEX(comp0)));
#else
return vector_set(vector_get_component(input1, comp0), vector_get_component(input1, comp1), vector_get_component(input1, comp2), vector_get_component(input1, comp3));
#endif
}
if (static_condition<(comp0 == VectorMix::X || comp0 == VectorMix::Y) && (comp1 == VectorMix::X || comp1 == VectorMix::Y) && (comp2 == VectorMix::A || comp2 == VectorMix::B) && (comp3 == VectorMix::A && comp3 == VectorMix::B)>::test())
{
// First two components come from input 0, second two come from input 1
#if defined(ACL_SSE2_INTRINSICS)
return _mm_shuffle_ps(input0, input1, _MM_SHUFFLE(GET_VECTOR_MIX_COMPONENT_INDEX(comp3), GET_VECTOR_MIX_COMPONENT_INDEX(comp2), GET_VECTOR_MIX_COMPONENT_INDEX(comp1), GET_VECTOR_MIX_COMPONENT_INDEX(comp0)));
#else
return vector_set(vector_get_component(input0, comp0), vector_get_component(input0, comp1), vector_get_component(input1, comp2), vector_get_component(input1, comp3));
#endif
}
if (static_condition<(comp0 == VectorMix::A || comp0 == VectorMix::B) && (comp1 == VectorMix::A && comp1 == VectorMix::B) && (comp2 == VectorMix::X || comp2 == VectorMix::Y) && (comp3 == VectorMix::X || comp3 == VectorMix::Y)>::test())
{
// First two components come from input 1, second two come from input 0
#if defined(ACL_SSE2_INTRINSICS)
return _mm_shuffle_ps(input1, input0, _MM_SHUFFLE(GET_VECTOR_MIX_COMPONENT_INDEX(comp3), GET_VECTOR_MIX_COMPONENT_INDEX(comp2), GET_VECTOR_MIX_COMPONENT_INDEX(comp1), GET_VECTOR_MIX_COMPONENT_INDEX(comp0)));
#else
return vector_set(vector_get_component(input1, comp0), vector_get_component(input1, comp1), vector_get_component(input0, comp2), vector_get_component(input0, comp3));
#endif
}
if (static_condition<comp0 == VectorMix::X && comp1 == VectorMix::A && comp2 == VectorMix::Y && comp3 == VectorMix::B>::test())
{
// Low words from both inputs are interleaved
#if defined(ACL_SSE2_INTRINSICS)
return _mm_unpacklo_ps(input0, input1);
#else
return vector_set(vector_get_component(input0, comp0), vector_get_component(input1, comp1), vector_get_component(input0, comp2), vector_get_component(input1, comp3));
#endif
}
if (static_condition<comp0 == VectorMix::A && comp1 == VectorMix::X && comp2 == VectorMix::B && comp3 == VectorMix::Y>::test())
{
// Low words from both inputs are interleaved
#if defined(ACL_SSE2_INTRINSICS)
return _mm_unpacklo_ps(input1, input0);
#else
return vector_set(vector_get_component(input1, comp0), vector_get_component(input0, comp1), vector_get_component(input1, comp2), vector_get_component(input0, comp3));
#endif
}
if (static_condition<comp0 == VectorMix::Z && comp1 == VectorMix::C && comp2 == VectorMix::W && comp3 == VectorMix::D>::test())
{
// High words from both inputs are interleaved
#if defined(ACL_SSE2_INTRINSICS)
return _mm_unpackhi_ps(input0, input1);
#else
return vector_set(vector_get_component(input0, comp0), vector_get_component(input1, comp1), vector_get_component(input0, comp2), vector_get_component(input1, comp3));
#endif
}
if (static_condition<comp0 == VectorMix::C && comp1 == VectorMix::Z && comp2 == VectorMix::D && comp3 == VectorMix::W>::test())
{
// High words from both inputs are interleaved
#if defined(ACL_SSE2_INTRINSICS)
return _mm_unpackhi_ps(input1, input0);
#else
return vector_set(vector_get_component(input1, comp0), vector_get_component(input0, comp1), vector_get_component(input1, comp2), vector_get_component(input0, comp3));
#endif
}
// Slow code path, not yet optimized
//ACL_ASSERT(false, "vector_mix permutation not handled");
const float x = math_impl::is_vector_mix_arg_xyzw(comp0) ? vector_get_component<comp0>(input0) : vector_get_component<comp0>(input1);
const float y = math_impl::is_vector_mix_arg_xyzw(comp1) ? vector_get_component<comp1>(input0) : vector_get_component<comp1>(input1);
const float z = math_impl::is_vector_mix_arg_xyzw(comp2) ? vector_get_component<comp2>(input0) : vector_get_component<comp2>(input1);
const float w = math_impl::is_vector_mix_arg_xyzw(comp3) ? vector_get_component<comp3>(input0) : vector_get_component<comp3>(input1);
return vector_set(x, y, z, w);
}
inline Vector4_32 vector_mix_xxxx(const Vector4_32& input) { return vector_mix<VectorMix::X, VectorMix::X, VectorMix::X, VectorMix::X>(input, input); }
inline Vector4_32 vector_mix_yyyy(const Vector4_32& input) { return vector_mix<VectorMix::Y, VectorMix::Y, VectorMix::Y, VectorMix::Y>(input, input); }
inline Vector4_32 vector_mix_zzzz(const Vector4_32& input) { return vector_mix<VectorMix::Z, VectorMix::Z, VectorMix::Z, VectorMix::Z>(input, input); }
inline Vector4_32 vector_mix_wwww(const Vector4_32& input) { return vector_mix<VectorMix::W, VectorMix::W, VectorMix::W, VectorMix::W>(input, input); }
inline Vector4_32 vector_mix_xxyy(const Vector4_32& input) { return vector_mix<VectorMix::X, VectorMix::X, VectorMix::Y, VectorMix::Y>(input, input); }
inline Vector4_32 vector_mix_xzyw(const Vector4_32& input) { return vector_mix<VectorMix::X, VectorMix::Z, VectorMix::Y, VectorMix::W>(input, input); }
inline Vector4_32 vector_mix_yzxy(const Vector4_32& input) { return vector_mix<VectorMix::Y, VectorMix::Z, VectorMix::X, VectorMix::Y>(input, input); }
inline Vector4_32 vector_mix_ywxz(const Vector4_32& input) { return vector_mix<VectorMix::Y, VectorMix::W, VectorMix::X, VectorMix::Z>(input, input); }
inline Vector4_32 vector_mix_zxyx(const Vector4_32& input) { return vector_mix<VectorMix::Z, VectorMix::X, VectorMix::Y, VectorMix::X>(input, input); }
inline Vector4_32 vector_mix_zwyz(const Vector4_32& input) { return vector_mix<VectorMix::Z, VectorMix::W, VectorMix::Y, VectorMix::Z>(input, input); }
inline Vector4_32 vector_mix_zwzw(const Vector4_32& input) { return vector_mix<VectorMix::Z, VectorMix::W, VectorMix::Z, VectorMix::W>(input, input); }
inline Vector4_32 vector_mix_wxwx(const Vector4_32& input) { return vector_mix<VectorMix::W, VectorMix::X, VectorMix::W, VectorMix::X>(input, input); }
inline Vector4_32 vector_mix_wzwy(const Vector4_32& input) { return vector_mix<VectorMix::W, VectorMix::Z, VectorMix::W, VectorMix::Y>(input, input); }
inline Vector4_32 vector_mix_xyab(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::X, VectorMix::Y, VectorMix::A, VectorMix::B>(input0, input1); }
inline Vector4_32 vector_mix_xzac(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::X, VectorMix::Z, VectorMix::A, VectorMix::C>(input0, input1); }
inline Vector4_32 vector_mix_xbxb(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::X, VectorMix::B, VectorMix::X, VectorMix::B>(input0, input1); }
inline Vector4_32 vector_mix_xbzd(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::X, VectorMix::B, VectorMix::Z, VectorMix::D>(input0, input1); }
inline Vector4_32 vector_mix_ywbd(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::Y, VectorMix::W, VectorMix::B, VectorMix::D>(input0, input1); }
inline Vector4_32 vector_mix_zyax(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::Z, VectorMix::Y, VectorMix::A, VectorMix::X>(input0, input1); }
inline Vector4_32 vector_mix_zycx(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::Z, VectorMix::Y, VectorMix::C, VectorMix::X>(input0, input1); }
inline Vector4_32 vector_mix_zwcd(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::Z, VectorMix::W, VectorMix::C, VectorMix::D>(input0, input1); }
inline Vector4_32 vector_mix_zbaz(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::Z, VectorMix::B, VectorMix::A, VectorMix::Z>(input0, input1); }
inline Vector4_32 vector_mix_zdcz(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::Z, VectorMix::D, VectorMix::C, VectorMix::Z>(input0, input1); }
inline Vector4_32 vector_mix_wxya(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::W, VectorMix::X, VectorMix::Y, VectorMix::A>(input0, input1); }
inline Vector4_32 vector_mix_wxyc(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::W, VectorMix::X, VectorMix::Y, VectorMix::C>(input0, input1); }
inline Vector4_32 vector_mix_wbyz(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::W, VectorMix::B, VectorMix::Y, VectorMix::Z>(input0, input1); }
inline Vector4_32 vector_mix_wdyz(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::W, VectorMix::D, VectorMix::Y, VectorMix::Z>(input0, input1); }
inline Vector4_32 vector_mix_bxwa(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::B, VectorMix::X, VectorMix::W, VectorMix::A>(input0, input1); }
inline Vector4_32 vector_mix_bywx(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::B, VectorMix::Y, VectorMix::W, VectorMix::X>(input0, input1); }
inline Vector4_32 vector_mix_dxwc(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::D, VectorMix::X, VectorMix::W, VectorMix::C>(input0, input1); }
inline Vector4_32 vector_mix_dywx(const Vector4_32& input0, const Vector4_32& input1) { return vector_mix<VectorMix::D, VectorMix::Y, VectorMix::W, VectorMix::X>(input0, input1); }
//////////////////////////////////////////////////////////////////////////
// Misc
inline Vector4_32 vector_sign(const Vector4_32& input)
{
Vector4_32 mask = vector_greater_equal(input, vector_zero_32());
return vector_blend(mask, vector_set(1.0f), vector_set(-1.0f));
}
}
| [
"zeno490@gmail.com"
] | zeno490@gmail.com |
8d14a8d4310f8d5105e65f70644fb355d9415483 | 184bc19dba8443ce0de6e0168ef3cb97215202b8 | /code/subprojects/m-ulator/include/m-ulator/disassembler.h | 90ec69992bd635a663a7d3a8dd7603309b337b75 | [] | no_license | mfkiwl/arm-fault-simulator-paper-results | f2aa527e6bc17d8a6557f4d8303bcfd9b5982c72 | 17486a49552f2cb6881aca191db33440b96bb798 | refs/heads/master | 2023-06-24T18:24:43.577966 | 2021-07-24T21:16:47 | 2021-07-24T21:16:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,063 | h | #pragma once
#include "m-ulator/instruction_decoder.h"
#include <string>
namespace mulator
{
class Disassembler
{
public:
Disassembler(Architecture arch);
~Disassembler();
/*
* Getters for internals.
*/
InstructionDecoder get_decoder() const;
Architecture get_architecture() const;
/*
* Resets the disassembler by clearing the IT state.
*/
void reset();
/*
* Decode and disassemble a single instruction from a byte array.
*
* @param[in] address - current address
* @param[in] code - pointer to the first byte of the instruction
* @param[in] code_size - length of the remaining bytes in byte array
*/
ReturnCode disassemble(u32 address, const u8* code, u32 code_size);
/*
* Disassemble a single already decoded instruction.
*
* @param[in] instr - the instruction to disassemble
*/
ReturnCode disassemble(Instruction instr);
/*
* Getters for disassembled data.
*/
Instruction get_instruction() const;
std::string get_mnemonic() const;
std::string get_operands() const;
std::string get_string() const;
private:
InstructionDecoder m_decoder;
u32 m_it_state;
std::string format_name(const Instruction& instr) const;
std::string format_shift(const Instruction& instr) const;
std::string format_immediate(u32 value, bool add_flag = true, bool decimal = false, bool print_signed = false) const;
bool is_load_operation(const Mnemonic& mnemonic) const;
bool is_store_operation(const Mnemonic& mnemonic) const;
bool is_shift_operation(const Mnemonic& mnemonic) const;
Instruction m_instruction;
std::string m_mnemonic;
std::string m_operands;
bool in_IT_block() const;
bool last_in_IT_block() const;
Condition pop_IT_condition();
};
} // namespace mulator
| [
"max.hoffmann@rub.de"
] | max.hoffmann@rub.de |
63fe7d6f2dafab012e16bf9f02ccabf79f2dc3a1 | 8f021f68cd0949afa8d119582c0b419b014919d8 | /UVA/uva11512.cpp | 76134d6b437e9cc97d6e253ae6421e8472fcc377 | [] | no_license | Jonatankk/codigos | b9c8426c2f33b5142460a84337480b147169b3e6 | 233ae668bdf6cdd12dbc9ef243fb4ccdab49c933 | refs/heads/master | 2022-07-22T11:09:27.271029 | 2020-05-09T20:57:42 | 2020-05-09T20:57:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,478 | cpp | /*
* Leonardo Deliyannis Constantin
* UVa 11512 - GATTACA
*/
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define MAX 1123
typedef pair<int, int> ii;
char T[MAX], P[MAX];
int n, m;
int RA[MAX], tempRA[MAX];
int SA[MAX], tempSA[MAX];
int c[MAX];
int LCP[MAX];
int Phi[MAX], PLCP[MAX];
void countingSort(int k){
int i, sum, maxi = max(300, n);
memset(c, 0, sizeof(c));
for(i = 0; i < n; i++){
c[i + k < n ? RA[i + k] : 0]++;
}
for(i = sum = 0; i < maxi; i++){
int t = c[i]; c[i] = sum; sum += t;
}
for(i = 0; i < n; i++){
tempSA[c[SA[i]+k < n ? RA[SA[i]+k] : 0]++] = SA[i];
}
for(i = 0; i < n; i++){
SA[i] = tempSA[i];
}
}
void constructSA(){
int i, k, r;
for(i = 0; i < n; i++){
RA[i] = T[i];
SA[i] = i;
}
for(k = 1; k < n; k <<= 1){
countingSort(k);
countingSort(0);
tempRA[SA[0]] = r = 0;
for(i = 1; i < n; i++){
tempRA[SA[i]] =
(RA[SA[i]] == RA[SA[i-1]] &&
RA[SA[i]+k] == RA[SA[i-1]+k]) ? r : ++r;
}
for(i = 0; i < n; i++){
RA[i] = tempRA[i];
}
if(RA[SA[n-1]] == n-1) break;
}
}
void computeLCP(){
int i, L;
Phi[SA[0]] = -1;
for (i = 1; i < n; i++){
Phi[SA[i]] = SA[i-1];}
for (i = L = 0; i < n; i++){
if (Phi[i] == -1) { PLCP[i] = 0; continue; }
while (T[i + L] == T[Phi[i] + L]) L++;
PLCP[i] = L;
L = max(L-1, 0);
}
for (i = 0; i < n; i++){
LCP[i] = PLCP[SA[i]];
}
}
ii stringMatching(){
int lo = 0, hi = n-1, mid = lo;
while(lo < hi){
mid = lo + (hi-lo)/2; // avoid overflows
int res = strncmp(T+SA[mid], P, m);
if(res >= 0) hi = mid;
else lo = mid + 1;
}
if(strncmp(T+SA[lo], P, m) != 0) return ii(-1, -1);
ii ans; ans.first = lo;
lo = 0; hi = n-1; mid = lo;
while(lo < hi){
mid = lo + (hi-lo)/2; // avoid overflows
int res = strncmp(T+SA[mid], P, m);
if(res > 0) hi = mid;
else lo = mid + 1;
}
if(strncmp(T+SA[hi], P, m) != 0) hi--;
ans.second = hi;
return ans;
}
ii LRS(){
int i, idx = 0, maxLCP = -1;
for(i = 1; i < n; i++)
if(LCP[i] > maxLCP)
maxLCP = LCP[i], idx = i;
return ii(maxLCP, idx);
}
int main(){
int tc;
ii pos;
scanf("%d\n", &tc);
while(tc--){
n = (int)strlen(fgets(T, MAX, stdin));
T[n-1] = '$';
constructSA();
computeLCP();
ii ans = LRS();
if(ans.first <= 0)
printf("No repetitions found!\n");
else{
strncpy(P, T+SA[ans.second], m = ans.first);
P[m] = 0;
pos = stringMatching();
pos.second++;
printf("%s %d\n", P, pos.second - pos.first);
}
}
return 0;
}
| [
"constantin.leo@gmail.com"
] | constantin.leo@gmail.com |
b1db97f2405ef29cf30bf076ffd831f4b7518010 | 470a5f8fa57d4db3634b65129d676bc6dbadb39b | /Pythagorean Triplet.cpp | a526420104f70276647f2f7ee61eeece7f676092 | [] | no_license | 1ansh/GeeksforGeeks_codes | 3b288785669ee3ac27093465e2e75409b218a664 | 63d02c015963ae8c90ade457efa2282118f79b7b | refs/heads/master | 2021-01-01T15:34:44.430080 | 2017-08-22T06:49:22 | 2017-08-22T06:49:22 | 97,651,456 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 836 | cpp | #include <bits/stdc++.h>
using namespace std;
int min(int a, int b)
{
return a < b ? a : b;
}
int max(int a, int b)
{
return a > b ? a : b;
}
int main() {
int t;
cin>>t;
while(t--)
{
int n,i,j,num;
cin>>n;
vector<int> arr(n);
for(i=0;i<n;i++)
{
cin>>arr[i];
}
sort(arr.begin(),arr.end());
bool flag = false;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(ceil(sqrt(arr[i]*arr[i] + arr[j]*arr[j]))==floor(sqrt(arr[i]*arr[i] + arr[j]*arr[j])))
{
num = sqrt(arr[i]*arr[i] + arr[j]*arr[j]);
if(binary_search(arr.begin(),arr.end(),num))
{
flag=true;
}
}
}
if(flag)
{
break;
}
}
if(flag)
{
cout<<"Yes"<<endl;
}
else
{
cout<<"No"<<endl;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
549d456811b172cc0a25748102f4a849227179d8 | 5456502f97627278cbd6e16d002d50f1de3da7bb | /chrome/browser/ui/android/infobars/data_reduction_promo_infobar.cc | 2cec5cc106b5fd6e425f5374ba4ee5158e6f1673 | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/Chromium_7C66 | 72d108a413909eb3bd36c73a6c2f98de1573b6e5 | c8649ab2a0f5a747369ed50351209a42f59672ee | refs/heads/master | 2023-03-16T12:51:40.231959 | 2017-12-20T10:38:26 | 2017-12-20T10:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,651 | cc | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/android/infobars/data_reduction_promo_infobar.h"
#include <utility>
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "chrome/browser/android/resource_mapper.h"
#include "chrome/browser/net/spdyproxy/data_reduction_promo_infobar_delegate_android.h"
#include "content/public/browser/web_contents.h"
// DataReductionPromoInfoBar --------------------------------------------------
DataReductionPromoInfoBar::DataReductionPromoInfoBar(
std::unique_ptr<DataReductionPromoInfoBarDelegateAndroid> delegate)
: ConfirmInfoBar(std::move(delegate)) {}
DataReductionPromoInfoBar::~DataReductionPromoInfoBar() {
}
base::android::ScopedJavaLocalRef<jobject>
DataReductionPromoInfoBar::CreateRenderInfoBar(JNIEnv* env) {
return GetDelegate()->CreateRenderInfoBar(env);
}
DataReductionPromoInfoBarDelegateAndroid*
DataReductionPromoInfoBar::GetDelegate() {
return static_cast<DataReductionPromoInfoBarDelegateAndroid*>(delegate());
}
// DataReductionPromoInfoBarDelegate ------------------------------------------
// static
std::unique_ptr<infobars::InfoBar>
DataReductionPromoInfoBarDelegateAndroid::CreateInfoBar(
infobars::InfoBarManager* infobar_manager,
std::unique_ptr<DataReductionPromoInfoBarDelegateAndroid> delegate) {
return base::MakeUnique<DataReductionPromoInfoBar>(std::move(delegate));
}
| [
"lixiaodonglove7@aliyun.com"
] | lixiaodonglove7@aliyun.com |
a4cc08a381137f69bb13af677b08ac0f9d39c64f | a7588b12855f6ca952c165a5a598f1850428a7fc | /rap-btl/junction.hpp | cd5b0779d031f02b0bc296b09eef0d79be5aa977 | [
"AFL-3.0"
] | permissive | ASA1976/RAP-BTL | e61da65432163737f0cc875903658991bbd6da56 | 94686073f84197e850e047fcbb82e68e12de8abc | refs/heads/master | 2023-03-08T05:41:39.522751 | 2023-03-04T12:47:29 | 2023-03-04T12:47:29 | 123,491,179 | 3 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 50,963 | hpp | // © 2019 Aaron Sami Abassi
// Licensed under the Academic Free License version 3.0
#ifndef JUNCTION_MODULE
#define JUNCTION_MODULE
#include <allocation.hpp>
#include <trajection.hpp>
/**
* @brief
* Linked list management and trajection implementation.
* @details
* Linked list management and trajection implementation.
*/
namespace junction {
using ::allocation::Allocative;
using ::allocation::CopyClaimable;
using ::allocation::DefaultClaimable;
using ::allocation::DefaultDisclaimable;
using ::allocation::FastCopyNew;
using ::allocation::FastDefaultNew;
using ::comparison::Comparative;
using ::comparison::Equative;
using ::comparison::Relational;
using ::location::Conferential;
using ::location::Locational;
using ::location::Positive;
using ::location::Referential;
using ::trajection::Axial;
using ::trajection::Directional;
using ::trajection::Lineal;
using ::trajection::Scalar;
using ::trajection::Vectorial;
/**
* @brief
* Linked list node conformity.
* @details
* This type is used to represent a linked list node.
* @tparam Connective
* Type of the node linkage.
* @tparam Elemental
* Type of the elements.
*/
template <
typename Connective,
typename Elemental>
struct Nodal {
Connective
link; /**< Node link(s) substructure. */
Elemental
element; /**< Instance of the element at this node. */
};
/**
* @brief
* Single link conformity.
* @details
* This type is used to represent a singly connective list node link.
* @tparam Elemental
* Type of the elements.
*/
template <typename Elemental>
struct SinglyLinked {
Locational<Nodal<SinglyLinked<Elemental>, Elemental>>
node; /**< Single node link. */
};
/**
* @brief
* Double link conformity.
* @details
* This type is used to represent a doubly connective list node link.
* @tparam Elemental
* Type of the elements.
*/
template <typename Elemental>
struct DoublyLinked {
Locational<Nodal<DoublyLinked<Elemental>, Elemental>>
previous, /**< Link to previous node. */
next; /**< Link to next node. */
};
/**
* @brief
* Singly linked node conformity.
* @details
* This type alias is used to represent a singly linked list node.
* @tparam Elemental
* Type of the elements.
*/
template <typename Elemental>
using SinglyNodal = Nodal<SinglyLinked<Elemental>, Elemental>;
/**
* @brief
* Doubly linked node conformity.
* @details
* This type alias is used to represent a doubly linked list node.
* @tparam Elemental
* Type of the elements.
*/
template <typename Elemental>
using DoublyNodal = Nodal<DoublyLinked<Elemental>, Elemental>;
/**
* @brief
* Linked list conformity.
* @details
* This type is used to represent a linked list.
* @tparam Connective
* Type of the node linkage.
* @tparam Natural
* Type of unsigned integer.
* @tparam Elemental
* Type of the elements.
*/
template <
typename Connective,
typename Natural,
typename Elemental>
struct Junctive {
Locational<Nodal<Connective, Elemental>>
first, /**< First node in the list. */
last, /**< Last node in the list. */
unused; /**< First unused node in a sublist of unused nodes. */
Natural
count, /**< Number of nodes in the active list. */
total; /**< Total number of nodes in the active and unused sublists. */
};
/**
* @brief
* Singly linked list conformity.
* @details
* This type alias is used to represent a singly linked list.
* @tparam Natural
* Type of unsigned integer.
* @tparam Elemental
* Type of the elements.
*/
template <
typename Natural,
typename Elemental>
using SinglyJunctive = Junctive<SinglyLinked<Elemental>, Natural, Elemental>;
/**
* @brief
* Doubly linked list conformity.
* @details
* This type alias is used to represent a doubly linked list.
* @tparam Natural
* Type of unsigned integer.
* @tparam Elemental
* Type of the elements.
*/
template <
typename Natural,
typename Elemental>
using DoublyJunctive = Junctive<DoublyLinked<Elemental>, Natural, Elemental>;
/**
* @brief
* Linked list node management classifier.
* @details
* This type is used to manage linked list nodes, including enforcement
* of recycling policy.
* @tparam Connective
* Type of the node linkage.
* @tparam Natural
* Type of unsigned integer.
* @tparam Elemental
* Type of the elements.
*/
template <
typename Connective,
typename Natural,
typename Elemental>
struct Adjunctive {
Referential<Locational<Nodal<Connective, Elemental>>(Referential<Junctive<Connective, Natural, Elemental>>)>
allocate; /**< Allocates one or more uninitialized nodes.
* Implementations may simply return null if this
* operation is not supported.
*/
Referential<bool(Referential<Junctive<Connective, Natural, Elemental>>, Referential<Locational<Nodal<Connective, Elemental>>>)>
deallocate; /**< Frees the memory used by one linked list node which
* has already been removed from either the active
* node list or unused node sublist.
*/
Referential<Locational<Nodal<Connective, Elemental>>(Referential<Junctive<Connective, Natural, Elemental>>, Referential<const Elemental>)>
proclaim; /**< Proclaims an element with the specified value.
* Implementations may recycle an unused node and assign
* it the provided value or allocate and initialize a
* new node to the provided value.
*/
};
/**
* @brief
* Singly linked list node management classifier.
* @details
* This type alias is used to represent a singly linked list node
* management adjunct.
* @tparam Natural
* Type of unsigned integer.
* @tparam Elemental
* Type of the elements.
*/
template <
typename Natural,
typename Elemental>
using SinglyAdjunctive = Adjunctive<SinglyLinked<Elemental>, Natural, Elemental>;
/**
* @brief
* Doubly linked list node management classifier.
* @details
* This type alias is used to represent a doubly linked list node
* management adjunct.
* @tparam Natural
* Type of unsigned integer.
* @tparam Elemental
* Type of the elements.
*/
template <
typename Natural,
typename Elemental>
using DoublyAdjunctive = Adjunctive<DoublyLinked<Elemental>, Natural, Elemental>;
/**
* @brief
* Linked list position conformity.
* @details
* This type alias is used to represent a position in the linked list.
* @tparam Connective
* Type of the node linkage.
* @tparam Elemental
* Type of the elements.
*/
template <
typename Connective,
typename Elemental>
using Positional = Positive<Nodal<Connective, Elemental>>;
/**
* @brief
* Singly linked list position conformity.
* @details
* This type alias is used to represent a position in singly linked
* list.
* @tparam Elemental
* Type of the elements.
*/
template <typename Elemental>
using SinglyPositional = Positional<SinglyLinked<Elemental>, Elemental>;
/**
* @brief
* Doubly linked list position conformity.
* @details
* This type alias is used to represent a position in doubly linked
* list.
* @tparam Elemental
* Type of the elements.
*/
template <typename Elemental>
using DoublyPositional = Positional<DoublyLinked<Elemental>, Elemental>;
/**
* @brief
* Function abstract used to get a polar position in the list.
* @details
* This function type alias is used to declare function references which
* return either the first or last node in the linked list.
* @tparam Connective
* Type of the node linkage.
* @tparam Natural
* Type of unsigned integer.
* @tparam Elemental
* Type of the elements.
*/
template <
typename Connective,
typename Natural,
typename Elemental>
using Original = Locational<Nodal<Connective, Elemental>>(
Referential<const Junctive<Connective, Natural, Elemental>>
list);
/**
* @brief
* Function abstract used to get a node subsequent to another node.
* @details
* This function type alias is used to declare function references which
* return either the next or previous node in the linked list.
* @tparam Connective
* Type of the node linkage.
* @tparam Elemental
* Type of the elements.
*/
template <
typename Connective,
typename Elemental>
using Subsequent = Locational<Nodal<Connective, Elemental>>(
const Locational<Nodal<Connective, Elemental>>
node);
template <
typename Connective,
typename Natural,
typename Elemental>
constexpr Junctive<Connective, Natural, Elemental>
InitializedList = { 0, 0, 0, 0, 0 };
template <typename Elemental>
static inline Locational<SinglyNodal<Elemental>>
GetNext(
const Locational<SinglyNodal<Elemental>>
node)
{
return node->link.node;
}
template <typename Elemental>
static inline Locational<DoublyNodal<Elemental>>
GetNext(
const Locational<DoublyNodal<Elemental>>
node)
{
return node->link.next;
}
template <typename Elemental>
static inline Locational<DoublyNodal<Elemental>>
GetPrevious(
const Locational<DoublyNodal<Elemental>>
node)
{
return node->link.previous;
}
template <typename Elemental>
static inline void
SetNext(
const Locational<SinglyNodal<Elemental>>
node,
const Locational<SinglyNodal<Elemental>>
next)
{
node->link.node = next;
}
template <typename Elemental>
static inline void
SetNext(
const Locational<DoublyNodal<Elemental>>
node,
const Locational<DoublyNodal<Elemental>>
next)
{
node->link.next = next;
}
template <typename Elemental>
static inline void
SetPrevious(
const Locational<DoublyNodal<Elemental>>
node,
const Locational<DoublyNodal<Elemental>>
previous)
{
node->link.previous = previous;
}
template <typename Elemental>
static inline void
UnsetNext(
const Locational<SinglyNodal<Elemental>>
node)
{
node->link.node = 0;
}
template <typename Elemental>
static inline void
UnsetNext(
const Locational<DoublyNodal<Elemental>>
node)
{
node->link.next = 0;
}
template <typename Elemental>
static inline void
UnsetPrevious(
const Locational<DoublyNodal<Elemental>>
node)
{
node->link.previous = 0;
}
template <typename Elemental>
static inline void
ConnectNext(
const Locational<SinglyNodal<Elemental>>
first,
const Locational<SinglyNodal<Elemental>>
second)
{
SetNext(first, second);
}
template <typename Elemental>
static inline void
ConnectNext(
const Locational<DoublyNodal<Elemental>>
first,
const Locational<DoublyNodal<Elemental>>
second)
{
SetNext(first, second);
if (second)
SetPrevious(second, first);
}
template <typename Elemental>
static inline void
ConnectPrevious(
const Locational<DoublyNodal<Elemental>>
first,
const Locational<DoublyNodal<Elemental>>
second)
{
SetPrevious(first, second);
if (second)
SetNext(second, first);
}
template <typename Elemental>
static inline void
DisconnectNext(
const Locational<SinglyNodal<Elemental>>
node)
{
UnsetNext(node);
}
template <typename Elemental>
static inline void
DisconnectNext(
const Locational<DoublyNodal<Elemental>>
node)
{
if (GetNext(node)) {
UnsetPrevious(GetNext(node));
UnsetNext(node);
}
}
template <typename Elemental>
static inline void
DisconnectPrevious(
const Locational<DoublyNodal<Elemental>>
node)
{
if (GetPrevious(node)) {
UnsetNext(GetPrevious(node));
UnsetPrevious(node);
}
}
template <
typename Natural,
typename Elemental>
static inline Locational<SinglyNodal<Elemental>>
GetFirst(
Referential<const SinglyJunctive<Natural, Elemental>>
list)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
return list.first;
}
template <
typename Natural,
typename Elemental>
static inline Locational<DoublyNodal<Elemental>>
GetFirst(
Referential<const DoublyJunctive<Natural, Elemental>>
list)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
return list.first;
}
template <
typename Natural,
typename Elemental>
static inline Locational<SinglyNodal<Elemental>>
GetLast(
Referential<const SinglyJunctive<Natural, Elemental>>
list)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
return list.last;
}
template <
typename Natural,
typename Elemental>
static inline Locational<DoublyNodal<Elemental>>
GetLast(
Referential<const DoublyJunctive<Natural, Elemental>>
list)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
return list.last;
}
template <
typename Connective,
typename Natural,
typename Elemental>
static inline Natural
Account(
Referential<const Junctive<Connective, Natural, Elemental>>
list)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
return list.count;
}
template <
typename Connective,
typename Natural,
typename Elemental,
Referential<Subsequent<Connective, Elemental>>
GetSubsequent>
static inline Natural
Count(
Referential<const Junctive<Connective, Natural, Elemental>>
list,
Referential<const Positional<Connective, Elemental>>
position)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational current;
Natural count;
count = 0;
current = position.at;
while (GetSubsequent(current)) {
count++;
current = GetSubsequent(current);
}
return count;
}
template <
typename Connective,
typename Elemental>
static inline bool
IsEqual(
Referential<const Positional<Connective, Elemental>>
base,
Referential<const Positional<Connective, Elemental>>
relative)
{
return base.at == relative.at;
}
template <
typename Connective,
typename Elemental>
static inline bool
IsNotEqual(
Referential<const Positional<Connective, Elemental>>
base,
Referential<const Positional<Connective, Elemental>>
relative)
{
return base.at != relative.at;
}
template <
typename Connective,
typename Elemental>
static inline bool
IsGreater(
Referential<const Positional<Connective, Elemental>>
base,
Referential<const Positional<Connective, Elemental>>
relative)
{
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational current;
current = GetNext(relative.at);
while (current) {
if (current == relative.at)
return true;
current = GetNext(current);
}
return false;
}
template <
typename Connective,
typename Elemental>
static inline bool
IsLesser(
Referential<const Positional<Connective, Elemental>>
base,
Referential<const Positional<Connective, Elemental>>
relative)
{
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational current;
current = GetNext(base.at);
while (current) {
if (current == relative.at)
return true;
current = GetNext(current);
}
return false;
}
template <
typename Connective,
typename Elemental>
static inline bool
IsNotLesser(
Referential<const Positional<Connective, Elemental>>
base,
Referential<const Positional<Connective, Elemental>>
relative)
{
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational current;
current = relative.at;
while (current) {
if (current == relative.at)
return true;
current = GetNext(current);
}
return false;
}
template <
typename Connective,
typename Elemental>
static inline bool
IsNotGreater(
Referential<const Positional<Connective, Elemental>>
base,
Referential<const Positional<Connective, Elemental>>
relative)
{
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational current;
current = base.at;
while (current) {
if (current == relative.at)
return true;
current = GetNext(current);
}
return false;
}
template <
typename Connective,
typename Natural,
typename Elemental>
static inline Referential<Junctive<Connective, Natural, Elemental>>
Initialize(
Referential<Junctive<Connective, Natural, Elemental>>
list)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
return list = InitializedList<Connective, Natural, Elemental>;
}
template <
typename Connective,
typename Natural,
typename Elemental>
static inline Referential<Junctive<Connective, Natural, Elemental>>
IntegrateNodes(
Referential<Junctive<Connective, Natural, Elemental>>
list,
Locational<Nodal<Connective, Elemental>>
nodes,
Referential<const Natural>
count)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
Natural offset;
if (count < 1)
return list;
for (offset = 1; offset < count; offset++)
ConnectNext(nodes + offset - 1, nodes + offset);
ConnectNext(nodes + count - 1, list.unused);
list.unused = nodes;
list.total += count;
return list;
}
template <
typename Connective,
typename Natural,
typename Elemental,
Natural
Count>
static inline Referential<Junctive<Connective, Natural, Elemental>>
IntegrateNodes(
Referential<Junctive<Connective, Natural, Elemental>>
list,
Referential<Nodal<Connective, Elemental>[Count]>
nodes)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
return IntegrateNodes(list, nodes, Count);
}
template <
typename Connective,
typename Natural,
typename Elemental>
static inline bool
RemoveAll(
Referential<Junctive<Connective, Natural, Elemental>>
list)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
bool actioned = false;
if (list.last) {
ConnectNext(list.last, list.unused);
list.unused = list.first;
actioned = true;
}
list.first = list.last = 0;
list.count = 0;
return actioned;
}
template <
typename Connective,
typename Natural,
typename Elemental>
static inline Locational<Nodal<Connective, Elemental>>
Reclaim(
Referential<Junctive<Connective, Natural, Elemental>>
list)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational result;
result = list.unused;
if (result)
list.unused = GetNext(result);
return result;
}
// Returns false if deallocate returned false to prevent infinite loops.
// Verification of memory cleanup can be achieved by sampling the total
// node counts before and after the call to this function.
template <
typename Natural,
typename Elemental,
Referential<const SinglyAdjunctive<Natural, Elemental>> Adjunct>
static inline bool
DeleteOneNode(
Referential<SinglyJunctive<Natural, Elemental>>
list)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<SinglyNodal<Elemental>>;
NodeLocational next;
if (!list.unused)
return false;
next = GetNext(list.unused);
if (!Adjunct.deallocate(list, list.unused))
return false;
list.unused = next;
return list.unused;
}
// Returns false if deallocate returned false to prevent infinite loops.
// Verification of memory cleanup can be achieved by sampling the total
// node counts before and after the call to this function.
template <
typename Natural,
typename Elemental,
Referential<const DoublyAdjunctive<Natural, Elemental>> Adjunct>
static inline bool
DeleteOneNode(
Referential<DoublyJunctive<Natural, Elemental>>
list)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<DoublyNodal<Elemental>>;
NodeLocational next;
if (!list.unused)
return false;
next = GetNext(list.unused);
if (!Adjunct.deallocate(list, list.unused))
return false;
list.unused = next;
if (next)
UnsetPrevious(next);
return list.unused;
}
template <
typename Connective,
typename Natural,
typename Elemental>
static inline Locational<Nodal<Connective, Elemental>>
AllocateNothing(
Referential<Junctive<Connective, Natural, Elemental>>
list)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
return 0;
}
template <
typename Connective,
typename Disclaimable,
typename Natural,
typename Elemental,
Referential<const Allocative<DefaultClaimable<Nodal<Connective, Elemental>>, Disclaimable>> Allocator>
static inline Locational<Nodal<Connective, Elemental>>
AllocateDefault(
Referential<Junctive<Connective, Natural, Elemental>>
list)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational result;
Allocator.claim(result);
if (result)
list.total++;
return result;
}
template <
typename Connective,
typename Natural,
typename Elemental>
static inline bool
DeallocateNothing(
Referential<Junctive<Connective, Natural, Elemental>>
list,
Referential<Locational<Nodal<Connective, Elemental>>>
node)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
return false;
}
template <
typename Connective,
typename Claimable,
typename Natural,
typename Elemental,
Referential<const Allocative<Claimable, DefaultDisclaimable<Nodal<Connective, Elemental>>>> Allocator>
static inline bool
DeallocateDefault(
Referential<Junctive<Connective, Natural, Elemental>>
list,
Referential<Locational<Nodal<Connective, Elemental>>>
node)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
if (node) {
Allocator.disclaim(node);
list.total--;
return true;
}
return false;
}
template <
typename Connective,
typename Disclaimable,
typename Natural,
typename Elemental,
Referential<const Allocative<DefaultClaimable<Nodal<Connective, Elemental>>, Disclaimable>> Allocator>
static inline Locational<Nodal<Connective, Elemental>>
ProclaimDefault(
Referential<Junctive<Connective, Natural, Elemental>>
list,
Referential<const Elemental>
value)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational result;
result = Reclaim(list);
if (!result) {
Allocator.claim(result);
if (!result)
return 0;
list.total++;
}
result->element = value;
return result;
}
template <
typename Connective,
typename Natural,
typename Elemental>
static inline Locational<Nodal<Connective, Elemental>>
ProclaimCyclic(
Referential<Junctive<Connective, Natural, Elemental>>
list,
Referential<const Elemental>
value)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational result;
result = Reclaim(list);
if (result)
result->element = value;
return result;
}
template <
typename Disclaimable,
typename Natural,
typename Elemental,
Referential<const Allocative<CopyClaimable<SinglyNodal<Elemental>>, Disclaimable>> Allocator>
static inline Locational<SinglyNodal<Elemental>>
ProclaimCopy(
Referential<SinglyJunctive<Natural, Elemental>>
list,
Referential<const Elemental>
value)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<SinglyNodal<Elemental>>;
const SinglyNodal<Elemental> copy = { { 0 }, value };
NodeLocational result;
Allocator.claim(result, copy);
if (result)
list.total++;
return result;
}
template <
typename Disclaimable,
typename Natural,
typename Elemental,
Referential<const Allocative<CopyClaimable<DoublyNodal<Elemental>>, Disclaimable>> Allocator>
static inline Locational<DoublyNodal<Elemental>>
ProclaimCopy(
Referential<DoublyJunctive<Natural, Elemental>>
list,
Referential<const Elemental>
value)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<DoublyNodal<Elemental>>;
const DoublyNodal<Elemental> copy = { { 0, 0 }, value };
NodeLocational result;
Allocator.claim(result, copy);
if (result)
list.total++;
return result;
}
template <
typename Connective,
typename Natural,
typename Elemental,
Referential<const Adjunctive<Connective, Natural, Elemental>> Adjunct>
static inline bool
Instantiate(
Referential<Junctive<Connective, Natural, Elemental>>
list,
Referential<const Natural>
count)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational result;
while (list.total - list.count < count) {
result = Adjunct.allocate(list);
if (!result)
return false;
ConnectNext(result, list.unused);
list.unused = result;
}
return true;
}
template <
typename Connective,
typename Natural,
typename Elemental>
static inline bool
Contains(
Referential<const Junctive<Connective, Natural, Elemental>>
list,
Referential<const Positional<Connective, Elemental>>
position)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational current;
current = list.first;
while (current) {
if (current == position.at)
return true;
current = GetNext(current);
}
return false;
}
template <
typename Connective,
typename Natural,
typename Elemental>
static inline Conferential<const Elemental>
GoRead(
Referential<const Junctive<Connective, Natural, Elemental>>
list,
Referential<const Positional<Connective, Elemental>>
position)
{
using ::location::Deter;
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
static auto& DeterElement = Deter<Elemental>;
return DeterElement(position.at->element);
}
template <
typename Connective,
typename Natural,
typename Elemental>
static inline Conferential<Elemental>
GoWrite(
Referential<Junctive<Connective, Natural, Elemental>>
list,
Referential<const Positional<Connective, Elemental>>
position)
{
using ::location::Confer;
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
static auto& ConferElement = Confer<Elemental>;
return ConferElement(position.at->element);
}
template <
typename Connective,
typename Natural,
typename Elemental,
Referential<Original<Connective, Natural, Elemental>> GetOrigin,
Referential<Subsequent<Connective, Elemental>> GetSubsequent>
static inline Referential<const Positional<Connective, Elemental>>
BeginReadScale(
Referential<const Junctive<Connective, Natural, Elemental>>
list,
Referential<Positional<Connective, Elemental>>
position,
Referential<const Natural>
count)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational current;
Natural index;
current = GetOrigin(list);
for (index = 0; index < count; index++)
current = GetSubsequent(current);
position.at = current;
return position;
}
template <
typename Connective,
typename Natural,
typename Elemental,
Referential<Original<Connective, Natural, Elemental>> GetOrigin,
Referential<Subsequent<Connective, Elemental>> GetSubsequent>
static inline Referential<const Positional<Connective, Elemental>>
BeginWriteScale(
Referential<Junctive<Connective, Natural, Elemental>>
list,
Referential<Positional<Connective, Elemental>>
position,
Referential<const Natural>
count)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational current;
Natural index;
current = GetOrigin(list);
for (index = 0; index < count; index++)
current = GetSubsequent(current);
position.at = current;
return position;
}
template <
typename Connective,
typename Natural,
typename Elemental,
Referential<Original<Connective, Natural, Elemental>> GetOrigin,
Referential<Subsequent<Connective, Elemental>> GetSubsequent>
static inline bool
DirectionBegins(
Referential<const Junctive<Connective, Natural, Elemental>>
list,
Referential<const Natural>
count)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational current;
Natural index;
current = GetOrigin(list);
if (!current)
return false;
for (index = 0; index < count; index++) {
current = GetSubsequent(current);
if (!current)
return false;
}
return true;
}
template <
typename Connective,
typename Natural,
typename Elemental,
Referential<Subsequent<Connective, Elemental>> GetSubsequent>
static inline Referential<const Positional<Connective, Elemental>>
TraverseReadScale(
Referential<const Junctive<Connective, Natural, Elemental>>
list,
Referential<Positional<Connective, Elemental>>
position,
Referential<const Natural>
count)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational current;
Natural index;
current = position.at;
for (index = 0; index < count; index++)
current = GetSubsequent(current);
position.at = current;
return position;
}
template <
typename Connective,
typename Natural,
typename Elemental,
Referential<Subsequent<Connective, Elemental>> GetSubsequent>
static inline Referential<const Positional<Connective, Elemental>>
TraverseWriteScale(
Referential<Junctive<Connective, Natural, Elemental>>
list,
Referential<Positional<Connective, Elemental>>
position,
Referential<const Natural>
count)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational current;
Natural index;
current = position.at;
for (index = 0; index < count; index++)
current = GetSubsequent(current);
position.at = current;
return position;
}
template <
typename Connective,
typename Natural,
typename Elemental,
Referential<Subsequent<Connective, Elemental>> GetSubsequent>
static inline bool
DirectionTraverses(
Referential<const Junctive<Connective, Natural, Elemental>>
list,
Referential<const Positional<Connective, Elemental>>
position,
Referential<const Natural>
count)
{
#ifndef RAPBTL_NO_STD_CPLUSPLUS
using namespace ::std;
static_assert(
is_integral<Natural>::value && is_unsigned<Natural>::value,
"Natural: Unsigned integer type required");
#endif
using NodeLocational = Locational<Nodal<Connective, Elemental>>;
NodeLocational current;
Natural index;
current = position.at;
for (index = 0; index < count; index++) {
current = GetSubsequent(current);
if (!current)
return false;
}
return true;
}
template <
typename Natural,
typename Elemental>
constexpr SinglyAdjunctive<Natural, Elemental>
DefaultNewSingleAdjunct = {
AllocateDefault<SinglyLinked<Elemental>, DefaultDisclaimable<SinglyNodal<Elemental>>, Natural, Elemental, FastDefaultNew<SinglyNodal<Elemental>>>,
DeallocateDefault<SinglyLinked<Elemental>, DefaultClaimable<SinglyNodal<Elemental>>, Natural, Elemental, FastDefaultNew<SinglyNodal<Elemental>>>,
ProclaimDefault<SinglyLinked<Elemental>, DefaultDisclaimable<SinglyNodal<Elemental>>, Natural, Elemental, FastDefaultNew<SinglyNodal<Elemental>>>
};
template <
typename Natural,
typename Elemental>
constexpr DoublyAdjunctive<Natural, Elemental>
DefaultNewDoubleAdjunct = {
AllocateDefault<DoublyLinked<Elemental>, DefaultDisclaimable<DoublyNodal<Elemental>>, Natural, Elemental, FastDefaultNew<DoublyNodal<Elemental>>>,
DeallocateDefault<DoublyLinked<Elemental>, DefaultClaimable<DoublyNodal<Elemental>>, Natural, Elemental, FastDefaultNew<DoublyNodal<Elemental>>>,
ProclaimDefault<DoublyLinked<Elemental>, DefaultDisclaimable<DoublyNodal<Elemental>>, Natural, Elemental, FastDefaultNew<DoublyNodal<Elemental>>>
};
template <
typename Natural,
typename Elemental>
constexpr SinglyAdjunctive<Natural, Elemental>
DefaultStaticSingleAdjunct = {
AllocateNothing<SinglyLinked<Elemental>, Natural, Elemental>,
DeallocateNothing<SinglyLinked<Elemental>, Natural, Elemental>,
ProclaimCyclic<SinglyLinked<Elemental>, Natural, Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr DoublyAdjunctive<Natural, Elemental>
DefaultStaticDoubleAdjunct = {
AllocateNothing<DoublyLinked<Elemental>, Natural, Elemental>,
DeallocateNothing<DoublyLinked<Elemental>, Natural, Elemental>,
ProclaimCyclic<DoublyLinked<Elemental>, Natural, Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr SinglyAdjunctive<Natural, Elemental>
CopyNewSingleAdjunct = {
AllocateNothing<SinglyLinked<Elemental>, Natural, Elemental>,
DeallocateDefault<SinglyLinked<Elemental>, CopyClaimable<SinglyNodal<Elemental>>, Natural, Elemental, FastCopyNew<SinglyNodal<Elemental>>>,
ProclaimCopy<DefaultDisclaimable<SinglyNodal<Elemental>>, Natural, Elemental, FastCopyNew<SinglyNodal<Elemental>>>
};
template <
typename Natural,
typename Elemental>
constexpr DoublyAdjunctive<Natural, Elemental>
CopyNewDoubleAdjunct = {
AllocateNothing<DoublyLinked<Elemental>, Natural, Elemental>,
DeallocateDefault<DoublyLinked<Elemental>, CopyClaimable<DoublyNodal<Elemental>>, Natural, Elemental, FastCopyNew<DoublyNodal<Elemental>>>,
ProclaimCopy<DefaultDisclaimable<DoublyNodal<Elemental>>, Natural, Elemental, FastCopyNew<DoublyNodal<Elemental>>>
};
template <typename Elemental>
constexpr Equative<SinglyPositional<Elemental>>
SingleEquality = {
IsEqual<SinglyLinked<Elemental>, Elemental>,
IsNotEqual<SinglyLinked<Elemental>, Elemental>
};
template <typename Elemental>
constexpr Equative<DoublyPositional<Elemental>>
DoubleEquality = {
IsEqual<DoublyLinked<Elemental>, Elemental>,
IsNotEqual<DoublyLinked<Elemental>, Elemental>
};
template <typename Elemental>
constexpr Relational<SinglyPositional<Elemental>>
SingleRelation = {
IsLesser<SinglyLinked<Elemental>, Elemental>,
IsGreater<SinglyLinked<Elemental>, Elemental>,
IsNotGreater<SinglyLinked<Elemental>, Elemental>,
IsNotLesser<SinglyLinked<Elemental>, Elemental>
};
template <typename Elemental>
constexpr Relational<DoublyPositional<Elemental>>
DoubleRelation = {
IsLesser<DoublyLinked<Elemental>, Elemental>,
IsGreater<DoublyLinked<Elemental>, Elemental>,
IsNotGreater<DoublyLinked<Elemental>, Elemental>,
IsNotLesser<DoublyLinked<Elemental>, Elemental>
};
template <typename Elemental>
constexpr Comparative<SinglyPositional<Elemental>>
SingleComparison = {
SingleEquality<Elemental>,
SingleRelation<Elemental>
};
template <typename Elemental>
constexpr Comparative<DoublyPositional<Elemental>>
DoubleComparison = {
DoubleEquality<Elemental>,
DoubleRelation<Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr Vectorial<const SinglyJunctive<Natural, Elemental>, SinglyPositional<Elemental>, const Elemental>
ReadSingleVector = {
SingleComparison<Elemental>,
Contains<SinglyLinked<Elemental>, Natural, Elemental>,
GoRead<SinglyLinked<Elemental>, Natural, Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr Vectorial<const DoublyJunctive<Natural, Elemental>, DoublyPositional<Elemental>, const Elemental>
ReadDoubleVector = {
DoubleComparison<Elemental>,
Contains<DoublyLinked<Elemental>, Natural, Elemental>,
GoRead<DoublyLinked<Elemental>, Natural, Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr Vectorial<SinglyJunctive<Natural, Elemental>, SinglyPositional<Elemental>, Elemental>
WriteSingleVector = {
SingleComparison<Elemental>,
Contains<SinglyLinked<Elemental>, Natural, Elemental>,
GoWrite<SinglyLinked<Elemental>, Natural, Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr Vectorial<DoublyJunctive<Natural, Elemental>, DoublyPositional<Elemental>, Elemental>
WriteDoubleVector = {
DoubleComparison<Elemental>,
Contains<DoublyLinked<Elemental>, Natural, Elemental>,
GoWrite<DoublyLinked<Elemental>, Natural, Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr Scalar<const SinglyJunctive<Natural, Elemental>, SinglyPositional<Elemental>, Natural, const Elemental>
ReadIncrementSingleScale = {
SingleComparison<Elemental>,
BeginReadScale<SinglyLinked<Elemental>, Natural, Elemental, GetFirst<Natural, Elemental>, GetNext<Elemental>>,
TraverseReadScale<SinglyLinked<Elemental>, Natural, Elemental, GetNext<Elemental>>,
GoRead<SinglyLinked<Elemental>, Natural, Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr Scalar<const DoublyJunctive<Natural, Elemental>, DoublyPositional<Elemental>, Natural, const Elemental>
ReadIncrementDoubleScale = {
DoubleComparison<Elemental>,
BeginReadScale<DoublyLinked<Elemental>, Natural, Elemental, GetFirst<Natural, Elemental>, GetNext<Elemental>>,
TraverseReadScale<DoublyLinked<Elemental>, Natural, Elemental, GetNext<Elemental>>,
GoRead<DoublyLinked<Elemental>, Natural, Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr Scalar<SinglyJunctive<Natural, Elemental>, SinglyPositional<Elemental>, Natural, Elemental>
WriteIncrementSingleScale = {
SingleComparison<Elemental>,
BeginWriteScale<SinglyLinked<Elemental>, Natural, Elemental, GetFirst<Natural, Elemental>, GetNext<Elemental>>,
TraverseWriteScale<SinglyLinked<Elemental>, Natural, Elemental, GetNext<Elemental>>,
GoWrite<SinglyLinked<Elemental>, Natural, Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr Scalar<DoublyJunctive<Natural, Elemental>, DoublyPositional<Elemental>, Natural, Elemental>
WriteIncrementDoubleScale = {
DoubleComparison<Elemental>,
BeginWriteScale<DoublyLinked<Elemental>, Natural, Elemental, GetFirst<Natural, Elemental>, GetNext<Elemental>>,
TraverseWriteScale<DoublyLinked<Elemental>, Natural, Elemental, GetNext<Elemental>>,
GoWrite<DoublyLinked<Elemental>, Natural, Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr Scalar<const DoublyJunctive<Natural, Elemental>, DoublyPositional<Elemental>, Natural, const Elemental>
ReadDecrementDoubleScale = {
DoubleComparison<Elemental>,
BeginReadScale<DoublyLinked<Elemental>, Natural, Elemental, GetLast<Natural, Elemental>, GetPrevious<Elemental>>,
TraverseReadScale<DoublyLinked<Elemental>, Natural, Elemental, GetPrevious<Elemental>>,
GoRead<DoublyLinked<Elemental>, Natural, Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr Scalar<DoublyJunctive<Natural, Elemental>, DoublyPositional<Elemental>, Natural, Elemental>
WriteDecrementDoubleScale = {
DoubleComparison<Elemental>,
BeginWriteScale<DoublyLinked<Elemental>, Natural, Elemental, GetLast<Natural, Elemental>, GetPrevious<Elemental>>,
TraverseWriteScale<DoublyLinked<Elemental>, Natural, Elemental, GetPrevious<Elemental>>,
GoWrite<DoublyLinked<Elemental>, Natural, Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr Lineal<const DoublyJunctive<Natural, Elemental>, DoublyPositional<Elemental>, Natural, const Elemental>
ReadDoubleLiner = {
ReadIncrementDoubleScale<Natural, Elemental>,
ReadDecrementDoubleScale<Natural, Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr Lineal<DoublyJunctive<Natural, Elemental>, DoublyPositional<Elemental>, Natural, Elemental>
WriteDoubleLiner = {
WriteIncrementDoubleScale<Natural, Elemental>,
WriteDecrementDoubleScale<Natural, Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr Directional<const SinglyJunctive<Natural, Elemental>, SinglyPositional<Elemental>, Natural, const Elemental>
ReadIncrementSingleDirection = {
ReadIncrementSingleScale<Natural, Elemental>,
DirectionBegins<SinglyLinked<Elemental>, Natural, Elemental, GetFirst<Natural, Elemental>, GetNext<Elemental>>,
DirectionTraverses<SinglyLinked<Elemental>, Natural, Elemental, GetNext<Elemental>>,
Contains<SinglyLinked<Elemental>, Natural, Elemental>,
Account<SinglyLinked<Elemental>, Natural, Elemental>,
Count<SinglyLinked<Elemental>, Natural, Elemental, GetNext<Elemental>>
};
template <
typename Natural,
typename Elemental>
constexpr Directional<const DoublyJunctive<Natural, Elemental>, DoublyPositional<Elemental>, Natural, const Elemental>
ReadIncrementDoubleDirection = {
ReadIncrementDoubleScale<Natural, Elemental>,
DirectionBegins<DoublyLinked<Elemental>, Natural, Elemental, GetFirst<Natural, Elemental>, GetNext<Elemental>>,
DirectionTraverses<DoublyLinked<Elemental>, Natural, Elemental, GetNext<Elemental>>,
Contains<DoublyLinked<Elemental>, Natural, Elemental>,
Account<DoublyLinked<Elemental>, Natural, Elemental>,
Count<DoublyLinked<Elemental>, Natural, Elemental, GetNext<Elemental>>
};
template <
typename Natural,
typename Elemental>
constexpr Directional<SinglyJunctive<Natural, Elemental>, SinglyPositional<Elemental>, Natural, Elemental>
WriteIncrementSingleDirection = {
WriteIncrementSingleScale<Natural, Elemental>,
DirectionBegins<SinglyLinked<Elemental>, Natural, Elemental, GetFirst<Natural, Elemental>, GetNext<Elemental>>,
DirectionTraverses<SinglyLinked<Elemental>, Natural, Elemental, GetNext<Elemental>>,
Contains<SinglyLinked<Elemental>, Natural, Elemental>,
Account<SinglyLinked<Elemental>, Natural, Elemental>,
Count<SinglyLinked<Elemental>, Natural, Elemental, GetNext<Elemental>>
};
template <
typename Natural,
typename Elemental>
constexpr Directional<DoublyJunctive<Natural, Elemental>, DoublyPositional<Elemental>, Natural, Elemental>
WriteIncrementDoubleDirection = {
WriteIncrementDoubleScale<Natural, Elemental>,
DirectionBegins<DoublyLinked<Elemental>, Natural, Elemental, GetFirst<Natural, Elemental>, GetNext<Elemental>>,
DirectionTraverses<DoublyLinked<Elemental>, Natural, Elemental, GetNext<Elemental>>,
Contains<DoublyLinked<Elemental>, Natural, Elemental>,
Account<DoublyLinked<Elemental>, Natural, Elemental>,
Count<DoublyLinked<Elemental>, Natural, Elemental, GetNext<Elemental>>
};
template <
typename Natural,
typename Elemental>
constexpr Directional<const DoublyJunctive<Natural, Elemental>, DoublyPositional<Elemental>, Natural, const Elemental>
ReadDecrementDoubleDirection = {
ReadDecrementDoubleScale<Natural, Elemental>,
DirectionBegins<DoublyLinked<Elemental>, Natural, Elemental, GetLast<Natural, Elemental>, GetPrevious<Elemental>>,
DirectionTraverses<DoublyLinked<Elemental>, Natural, Elemental, GetPrevious<Elemental>>,
Contains<DoublyLinked<Elemental>, Natural, Elemental>,
Account<DoublyLinked<Elemental>, Natural, Elemental>,
Count<DoublyLinked<Elemental>, Natural, Elemental, GetPrevious<Elemental>>
};
template <
typename Natural,
typename Elemental>
constexpr Directional<DoublyJunctive<Natural, Elemental>, DoublyPositional<Elemental>, Natural, Elemental>
WriteDecrementDoubleDirection = {
WriteDecrementDoubleScale<Natural, Elemental>,
DirectionBegins<DoublyLinked<Elemental>, Natural, Elemental, GetLast<Natural, Elemental>, GetPrevious<Elemental>>,
DirectionTraverses<DoublyLinked<Elemental>, Natural, Elemental, GetPrevious<Elemental>>,
Contains<DoublyLinked<Elemental>, Natural, Elemental>,
Account<DoublyLinked<Elemental>, Natural, Elemental>,
Count<DoublyLinked<Elemental>, Natural, Elemental, GetPrevious<Elemental>>
};
template <
typename Natural,
typename Elemental>
constexpr Axial<const DoublyJunctive<Natural, Elemental>, DoublyPositional<Elemental>, Natural, const Elemental>
ReadDoubleAxis = {
ReadIncrementDoubleDirection<Natural, Elemental>,
ReadDecrementDoubleDirection<Natural, Elemental>
};
template <
typename Natural,
typename Elemental>
constexpr Axial<DoublyJunctive<Natural, Elemental>, DoublyPositional<Elemental>, Natural, Elemental>
WriteDoubleAxis = {
WriteIncrementDoubleDirection<Natural, Elemental>,
WriteDecrementDoubleDirection<Natural, Elemental>
};
}
#endif
| [
"rap.paradigm@gmail.com"
] | rap.paradigm@gmail.com |
e05f09c7f385789391fff862aa0905db51023c59 | 4a294ae9ab5c62798b74d1a2ccc75624665296b3 | /cpp/Debug/Generated Files/winrt/impl/Windows.UI.Xaml.Core.Direct.2.h | d21203a38c6d2eb11b13c51de6927731717c1f3d | [] | no_license | dtakeda/w32-winrt-test | d204a8fb28d1a4ceadf8ab8448b6cae2350a1579 | e70bf485ddc44d9389ed025a80fe65b4ec736bb6 | refs/heads/main | 2023-01-02T15:18:33.151156 | 2020-10-20T01:58:51 | 2020-10-20T01:58:51 | 305,547,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 638 | h | // WARNING: Please don't edit this file. It was generated by C++/WinRT v2.0.201008.2
#ifndef WINRT_Windows_UI_Xaml_Core_Direct_2_H
#define WINRT_Windows_UI_Xaml_Core_Direct_2_H
#include "winrt/impl/Windows.UI.Xaml.Core.Direct.1.h"
WINRT_EXPORT namespace winrt::Windows::UI::Xaml::Core::Direct
{
struct __declspec(empty_bases) XamlDirect : Windows::UI::Xaml::Core::Direct::IXamlDirect
{
XamlDirect(std::nullptr_t) noexcept {}
XamlDirect(void* ptr, take_ownership_from_abi_t) noexcept : Windows::UI::Xaml::Core::Direct::IXamlDirect(ptr, take_ownership_from_abi) {}
static auto GetDefault();
};
}
#endif
| [
"dtakeda@yamaha.com"
] | dtakeda@yamaha.com |
f5f908a5311ab6ddc892537159d56e08cee249c9 | d4406838589848249b37622da97a57453ae4b99c | /src/ExecutorStream.hpp | 2f0fc89b16bdb1d4a33f17e26efba320045058ea | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-mit-taylor-variant",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | jzgriffin/rshell | c2c569fadf4ba2a636a467bd680061a3685cf496 | c8205d85b0950ec7fa94269b65375921c988bfeb | refs/heads/master | 2022-09-04T15:27:34.902453 | 2017-03-18T20:10:17 | 2017-03-18T20:10:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,132 | hpp | // rshell
// Copyright (c) Jeremiah Griffin <jgrif007@ucr.edu>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE NEGLIGENCE OR OTHER TORTIOUS ACTION,
// ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
// SOFTWARE.
/// \file
/// \brief Contains the interface to the \ref rshell::ExecutorStream class
#ifndef hpp_rshell_ExecutorStream
#define hpp_rshell_ExecutorStream
namespace rshell {
// Forward declarations
class Executor;
/// \brief Abstract base class for individual input/output streams within
/// executors
class ExecutorStream
{
public:
/// \brief Possible input/output modes for streams
enum class Mode
{
Input, //!< Stream will replace the standard input
Output, //!< Stream will replace the standard output
};
/// \brief Destructs the \ref ExecutorStream instance
virtual ~ExecutorStream();
/// \brief Gets the input/output mode of the stream
/// \return input/output mode
Mode mode() const noexcept { return _mode; }
/// \brief Activates the stream within the given executor
/// \param executor executor to activate on
virtual void activate(Executor& executor) = 0;
/// \brief Closes the stream
virtual void close() = 0;
protected:
Mode _mode; //!< Input/output mode of the stream
/// \brief Constructs a new instance of the \ref ExecutorStream class with
/// the given mode
/// \param mode input/output mode of the stream
explicit ExecutorStream(Mode mode);
};
} // namespace rshell
#endif // hpp_rshell_ExecutorStream
| [
"jgrif007@ucr.edu"
] | jgrif007@ucr.edu |
1c5c2c826feb96f9b424567f9cb4658c7dfff50e | f549ca0577b7227aaa86b077e0f3b01721542e60 | /tvapp/Classes/setting/HelpLayer.h | 2a7fc61b7b31326cc716eafcd6285752dcf7550f | [
"MIT"
] | permissive | TopCruiser/tvOS_Card | cb713422007542271d09c01cc061a5b5ac7e4e26 | 3682302bc722e93e2c0dc509a88625ac54f4075d | refs/heads/master | 2021-01-09T20:47:11.959475 | 2016-07-27T08:55:38 | 2016-07-27T08:55:38 | 63,486,821 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,213 | h | //
// HelpLayer.h
// cardgame
//
// Created by lion on 4/10/15.
// Copyright (c) 2015 Pink. All rights reserved.
//
#ifndef __cardgame__HelpLayer__
#define __cardgame__HelpLayer__
#include "Common.h"
#include "cocos2d.h"
#include "cocos-ext.h"
USING_NS_CC_EXT;//Cocos2dx defined macros
using namespace cocos2d;
class HelpLayer : public cocos2d::Layer, public cocos2d::extension::TableViewDelegate,cocos2d::extension::TableViewDataSource
{
public:
static cocos2d::Scene* scene();
virtual bool init();
virtual void init(Layer* parent);
void updateLayoutWithPortrait();
void updateLayoutWithLandscape();
void menuCloseCallback(Ref* pSender);
void onDone(Ref* sender);
public:
//TableViewDelegate inherits from ScrollViewDelegate
virtual void scrollViewDidScroll(cocos2d::extension::ScrollView* view);
virtual void scrollViewDidZoom(cocos2d::extension::ScrollView* view);
virtual void tableCellTouched(cocos2d::extension::TableView* table, cocos2d::extension::TableViewCell* cell);
//Each cell size
//virtual cocos2d::Size cellSizeForTable(cocos2d::extension::TableView *table);
virtual Size tableCellSizeForIndex(TableView *table, unsigned int idx);
//Generate cell
virtual cocos2d::extension::TableViewCell* tableCellAtIndex(cocos2d::extension::TableView *table, unsigned int idx);
//The number of cell
virtual ssize_t numberOfCellsInTableView(cocos2d::extension::TableView *table);
//Pressed down, is highlighted, where you can set the bright state
virtual void tableCellHighlight(cocos2d::extension::TableView* table, cocos2d::extension::TableViewCell* cell);
//Release time, cancel the bright state
virtual void tableCellUnhighlight(cocos2d::extension::TableView* table, cocos2d::extension::TableViewCell* cell);
void scrollBar(cocos2d::extension::TableView* table);
private:
Layer* _parentLayer;
Sprite* _background;
Sprite* _titlebar;
TableView *tableView;
MenuItem* btnDone;
Sprite* _header;
Sprite* _footer;
Sprite* _backBackground;
bool _isEnabled;
public:
};
#endif /* defined(__cardgame__HelpLayer__) */
| [
"handsomeguy0712@yahoo.com"
] | handsomeguy0712@yahoo.com |
7d3592ac7ffb38cb3d457f4a7f78048d18ad2e4c | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/Event/xAOD/xAODMissingET/xAODMissingET/MissingETAssociationMap.h | 3d0dbcf25c5336193c32e6d8c9169ed4bd467869 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 535 | h | // -*- c++ -*-
/*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#ifndef XAODMISSINGET_MISSINGETASSOCIATIONMAP_H
#define XAODMISSINGET_MISSINGETASSOCIATIONMAP_H
#include "xAODMissingET/MissingETAssociation.h"
#include "xAODMissingET/versions/MissingETAssociationMap_v1.h"
namespace xAOD
{
/*! @brief Version control by type defintion */
typedef MissingETAssociationMap_v1 MissingETAssociationMap;
}
#include "xAODCore/CLASS_DEF.h"
CLASS_DEF( xAOD::MissingETAssociationMap, 135890658, 1 )
#endif
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
5a56476f6a68576c82087f17204348e29e1dc9c6 | 22afbddd2e6add2b51d17d5bfbfe28307b095cb9 | /Source/RTS/Plugins/RTSPlugin/Source/RTSPlugin/Private/RTSCharacterAIEventComponent.cpp | 6b9e1e0077afd35f7339c23c85b185dbbe252849 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | jashking/ue4-rts | 9a9cef1f5b65cf001ca39bbfe1bc80efe8fa6e88 | 360f684db4199cefa7bf5376c8844873c1b512e0 | refs/heads/develop | 2021-05-12T18:10:38.440215 | 2019-05-22T02:59:36 | 2019-05-22T02:59:36 | 117,061,553 | 3 | 1 | MIT | 2019-05-22T02:59:37 | 2018-01-11T06:45:39 | C++ | UTF-8 | C++ | false | false | 68 | cpp | #include "RTSPluginPCH.h"
#include "RTSCharacterAIEventComponent.h"
| [
"dev@npruehs.de"
] | dev@npruehs.de |
e971c8549d6fcd6f420fe19f691b38f02fa82deb | d47c341d59ed8ba577463ccf100a51efb669599c | /boost/asio/windows/random_access_handle.hpp | e7dbfacd1aaf5bb932f0c4f2cd679690ffc29b6c | [
"BSL-1.0"
] | permissive | cms-externals/boost | 5980d39d50b7441536eb3b10822f56495fdf3635 | 9615b17aa7196c42a741e99b4003a0c26f092f4c | refs/heads/master | 2023-08-29T09:15:33.137896 | 2020-08-04T16:50:18 | 2020-08-04T16:50:18 | 30,637,301 | 0 | 4 | BSL-1.0 | 2023-08-09T23:00:37 | 2015-02-11T08:07:04 | C++ | UTF-8 | C++ | false | false | 1,142 | hpp | //
// windows/random_access_handle.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2014 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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_ASIO_WINDOWS_RANDOM_ACCESS_HANDLE_HPP
#define BOOST_ASIO_WINDOWS_RANDOM_ACCESS_HANDLE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) \
|| defined(GENERATING_DOCUMENTATION)
#include <boost/asio/windows/basic_random_access_handle.hpp>
namespace boost {
namespace asio {
namespace windows {
/// Typedef for the typical usage of a random-access handle.
typedef basic_random_access_handle<> random_access_handle;
} // namespace windows
} // namespace asio
} // namespace boost
#endif // defined(BOOST_ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE)
// || defined(GENERATING_DOCUMENTATION)
#endif // BOOST_ASIO_WINDOWS_RANDOM_ACCESS_HANDLE_HPP
| [
"giulio.eulisse@cern.ch"
] | giulio.eulisse@cern.ch |
f3f461e456c0d26c23169e47dd2be4a47bf7b0e6 | f79e45b3c2974252b83f0f926d40445cd17ee2ef | /src/include/fileHeader/GrdFileHeader.h | 8b7356d93dc92f063353131e20724bec502856da | [] | no_license | ByAVM/VTK_uni_converter | 65c44bd2c5b4fd193f0606d54cb5a02e6033fc7a | e2fd71b485caa4ca882ba9f9547996090ca3a585 | refs/heads/master | 2022-11-21T22:46:28.456025 | 2020-07-08T04:48:32 | 2020-07-08T04:48:32 | 269,573,485 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,204 | h | #pragma once
#include "../fileHeader/FileHeader.h"
using namespace std;
namespace vtkConv
{
class GrdFileHeader : public IFileHeader {
protected:
struct GrdHeader {
char type[4];
short sizeX;
short sizeY;
double xMin;
double xMax;
double yMin;
double yMax;
double zMin;
double zMax;
} header;
public:
double getValue(const string& key) {
if (key == "sizeX") {
return header.sizeX;
} else if (key == "sizeY") {
return header.sizeY;
} else if (key == "xMin") {
return header.xMin;
} else if (key == "xMax") {
return header.xMax;
} else if (key == "yMin") {
return header.yMin;
} else if (key == "yMax") {
return header.yMax;
} else if (key == "zMin") {
return header.zMin;
} else if (key == "zMax") {
return header.xMax;
}
throw new HeaderException("Key \"" + key + "\" not found");
}
void readFile(ifstream& stream) {
stream.read(reinterpret_cast<char*>(&header), sizeof(header));
}
};
} // namespace vtkConv
| [
"miha_102035_20@mail.ru"
] | miha_102035_20@mail.ru |
cc110ab24520456d41d443735817a7dc4fda62d3 | deb9334fc2e75fd105370e7cdd857d4f7c2caffb | /acwing/每日一题/428.cpp | 3aea20cee3fd540d52fe1f4e51bd281d753bc423 | [] | no_license | liwei2088/oi | a641aa06cfeeaeff75673191c4e0bd3f5aae9de3 | 487acf4b1d4f97ab26614f9f396c9ca007c2b507 | refs/heads/master | 2021-06-12T00:00:02.767091 | 2021-03-27T06:21:09 | 2021-03-27T06:21:09 | 149,082,839 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 302 | cpp | #include <cstdio>
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int k, n;
cin >> k >> n;
// n[10,1000] 1000转换为二进制最高10位
int ans = 0;
for (int i = 0; i <= 10; i++)
if ((n >> i) & 1) ans += pow(k, i);
cout << ans;
return 0;
} | [
"liwei2088@sohu.com"
] | liwei2088@sohu.com |
87a6dec90bca55a4523437f451c0b6649265fff8 | b5a214062f140389527479802d98d414d8e41dc6 | /test/CodeGenCXX/microsoft-abi-structors-delayed-template.cpp | f9e188033ca4d26c5b984142b1edf66f7c80df7e | [
"NCSA"
] | permissive | Codeon-GmbH/mulle-clang | f050d6d8fb64689a1e4b039c4a6513823de9b430 | 2f6104867287dececb46e8d93dd9246aad47c282 | refs/heads/master | 2021-07-18T07:45:29.083064 | 2016-11-01T13:16:44 | 2016-11-01T13:16:44 | 72,544,381 | 29 | 5 | Apache-2.0 | 2020-04-30T11:36:08 | 2016-11-01T14:32:02 | C++ | UTF-8 | C++ | false | false | 400 | cpp | // RUN: %clang_cc1 -emit-llvm -fdelayed-template-parsing -std=c++11 -o - -triple=i386-pc-win32 %s > %t
// RUN: FileCheck %s < %t
// PR20671
namespace vtable_referenced_from_template {
struct ImplicitCtor {
virtual ~ImplicitCtor();
};
template <class T> void foo(T t) { new ImplicitCtor; }
void bar() { foo(0); }
// CHECK: store {{.*}} @"\01??_7ImplicitCtor@vtable_referenced_from_template@@6B@"
}
| [
"nicolasweber@gmx.de"
] | nicolasweber@gmx.de |
c227a887ae982ef53fe64aeac1b3d944fb683e9e | 87e0ee79d65145ac02b55a7d70e09bf406ba4448 | /si-purasupurasu.cpp | 144fc932859568cf08e930f1e375ff11c08e6007 | [
"MIT"
] | permissive | betaEncoder/si-purasupurasu | 2600792db065e6715ebd6a1c9d652db931b42867 | 2e581c4608a862abd9154ba6e48f512d80ce1290 | refs/heads/main | 2023-06-25T15:47:16.760168 | 2021-08-02T16:58:23 | 2021-08-02T16:58:23 | 392,021,309 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 187 | cpp | #include <iostream>
#include "si-purasupurasu.h"
イント メイン()
{
エステーデー::コンソールアウト << "ハローワールド!\n";
リターン 0;
} | [
"noreply@github.com"
] | noreply@github.com |
8d5e4c170f88bb19946653e0641c93c288c5f2d7 | 46f53e9a564192eed2f40dc927af6448f8608d13 | /cc/resources/drawing_display_item.h | b45a0392ad0756ef3a45212106dbcbb2cac8c13c | [
"BSD-3-Clause"
] | permissive | sgraham/nope | deb2d106a090d71ae882ac1e32e7c371f42eaca9 | f974e0c234388a330aab71a3e5bbf33c4dcfc33c | refs/heads/master | 2022-12-21T01:44:15.776329 | 2015-03-23T17:25:47 | 2015-03-23T17:25:47 | 32,344,868 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,320 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CC_RESOURCES_DRAWING_DISPLAY_ITEM_H_
#define CC_RESOURCES_DRAWING_DISPLAY_ITEM_H_
#include "base/memory/scoped_ptr.h"
#include "cc/base/cc_export.h"
#include "cc/resources/display_item.h"
#include "skia/ext/refptr.h"
#include "ui/gfx/geometry/point_f.h"
class SkCanvas;
class SkDrawPictureCallback;
class SkPicture;
namespace cc {
class CC_EXPORT DrawingDisplayItem : public DisplayItem {
public:
~DrawingDisplayItem() override;
static scoped_ptr<DrawingDisplayItem> Create(
skia::RefPtr<SkPicture> picture) {
return make_scoped_ptr(new DrawingDisplayItem(picture));
}
void Raster(SkCanvas* canvas, SkDrawPictureCallback* callback) const override;
void RasterForTracing(SkCanvas* canvas) const override;
bool IsSuitableForGpuRasterization() const override;
int ApproximateOpCount() const override;
size_t PictureMemoryUsage() const override;
void AsValueInto(base::trace_event::TracedValue* array) const override;
protected:
explicit DrawingDisplayItem(skia::RefPtr<SkPicture> picture);
private:
skia::RefPtr<SkPicture> picture_;
};
} // namespace cc
#endif // CC_RESOURCES_DRAWING_DISPLAY_ITEM_H_
| [
"scottmg@chromium.org"
] | scottmg@chromium.org |
73336404d34437e519eec3b126d1f5615480e3bb | b9e8d33a26e13bc5b919150574f03d47a082055a | /library/core/Geometry.cc | bdf96874140c9c5e0a01b434224a570cedacedc8 | [
"Zlib",
"BSL-1.0"
] | permissive | magestik/gf | 9215fb1e25c8a092bad4aa5875f030fd63d891ac | 60d9bbe084828fff88f1a511bd1191c774ccef4a | refs/heads/master | 2020-12-26T19:54:45.888737 | 2020-01-14T15:31:28 | 2020-01-14T15:31:28 | 237,623,167 | 0 | 0 | NOASSERTION | 2020-02-01T14:02:32 | 2020-02-01T14:02:31 | null | UTF-8 | C++ | false | false | 11,879 | cc | /*
* Gamedev Framework (gf)
* Copyright (C) 2016-2019 Julien Bernard
*
* 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.
*/
#include <gf/Geometry.h>
#include <cassert>
#include <gf/Log.h>
#include <gf/VectorOps.h>
namespace gf {
#ifndef DOXYGEN_SHOULD_SKIP_THIS
inline namespace v1 {
#endif
Bresenham::Bresenham(Vector2i p0, Vector2i p1)
: m_p0(p0)
, m_p1(p1)
, m_delta(p1 - p0)
{
m_step.x = gf::sign(m_delta.x);
m_step.y = gf::sign(m_delta.y);
m_error = std::max(m_step.x * m_delta.x, m_step.y * m_delta.y);
m_delta *= 2;
}
bool Bresenham::step(Vector2i& res) {
if (m_step.x * m_delta.x > m_step.y * m_delta.y) {
if (m_p0.x == m_p1.x) {
return true;
}
m_p0.x += m_step.x;
m_error -= m_step.y * m_delta.y;
if (m_error < 0) {
m_p0.y += m_step.y;
m_error += m_step.x * m_delta.x;
}
} else {
if (m_p0.y == m_p1.y) {
return true;
}
m_p0.y += m_step.y;
m_error -= m_step.x * m_delta.x;
if (m_error < 0) {
m_p0.x += m_step.x;
m_error += m_step.y * m_delta.y;
}
}
res = m_p0;
return false;
}
std::vector<Vector2i> generateLine(Vector2i p0, Vector2i p1) {
Bresenham bresenham(p0, p1);
std::vector<Vector2i> ret;
ret.push_back(p0);
Vector2i p;
while (!bresenham.step(p)) {
ret.push_back(p);
}
assert(ret.back() == p1);
ret.pop_back(); // to remove p1
return ret;
}
/*
* Midpoint Displacement 1D
*/
std::vector<Vector2f> midpointDisplacement1D(Vector2f p0, Vector2f p1, Random& random, unsigned iterations, Vector2f direction, float initialFactor, float reductionFactor) {
direction = initialFactor * gf::euclideanDistance(p0, p1) * gf::normalize(direction);
std::vector<Vector2f> ret;
std::size_t size = static_cast<std::size_t>(1) << iterations;
std::size_t count = size + 1;
ret.resize(count);
ret[0] = p0;
ret[count - 1] = p1;
std::size_t step = size / 2;
while (step > 0) {
for (std::size_t i = step; i < size; i += 2 * step) {
assert(i - step < count);
Vector2f prev = ret[i - step];
assert(i + step < count);
Vector2f next = ret[i + step];
Vector2f mid = (prev + next) / 2;
mid += random.computeUniformFloat(-0.5f, 0.5f) * direction;
ret[i] = mid;
}
direction *= reductionFactor;
step /= 2;
}
return ret;
}
std::vector<Vector2f> midpointDisplacement1D(Vector2f p0, Vector2f p1, Random& random, unsigned iterations, float initialFactor, float reductionFactor) {
return midpointDisplacement1D(p0, p1, random, iterations, gf::perp(p1 - p0), initialFactor, reductionFactor);
}
/*
* Midpoint Displacement 2D
*/
namespace {
int computePowerOfTwoSize(Vector2i size) {
int actualSize = 1;
while (actualSize + 1 < size.height || actualSize + 1 < size.width) {
actualSize = actualSize * 2;
}
return actualSize;
}
void initializeCorners(Heightmap& map, ArrayRef<double> initialValues, int d) {
if (initialValues.getSize() == 0) {
map.setValue({ 0, 0 }, 0.0);
map.setValue({ 0, d }, 0.0);
map.setValue({ d, d }, 0.0);
map.setValue({ d, 0 }, 0.0);
} else if (initialValues.getSize() < 4) {
map.setValue({ 0, 0 }, initialValues[0]);
map.setValue({ 0, d }, initialValues[0]);
map.setValue({ d, d }, initialValues[0]);
map.setValue({ d, 0 }, initialValues[0]);
} else {
map.setValue({ 0, 0 }, initialValues[0]);
map.setValue({ 0, d }, initialValues[1]);
map.setValue({ d, d }, initialValues[2]);
map.setValue({ d, 0 }, initialValues[3]);
}
}
} // anonymous namespace
Heightmap midpointDisplacement2D(Vector2i size, Random& random, ArrayRef<double> initialValues) {
int actualSize = computePowerOfTwoSize(size);
int d = actualSize;
actualSize = actualSize + 1;
Heightmap map({ actualSize, actualSize });
initializeCorners(map, initialValues, d);
while (d >= 2) {
int d2 = d / 2;
std::uniform_real_distribution<double> dist(-static_cast<double>(d), static_cast<double>(d));
for (int y = d2; y < actualSize; y += d) {
for (int x = d2; x < actualSize; x += d) {
double ne = map.getValue({ x - d2, y - d2 });
double nw = map.getValue({ x - d2, y + d2 });
double se = map.getValue({ x + d2, y - d2 });
double sw = map.getValue({ x + d2, y + d2 });
// center
double center = (ne + nw + se + sw) / 4;
map.setValue({ x, y }, center + dist(random.getEngine()));
// north
double north = (ne + nw) / 2;
map.setValue({ x - d2, y }, north + dist(random.getEngine()));
// south
double south = (se + sw) / 2;
map.setValue({ x + d2, y }, south + dist(random.getEngine()));
// east
double east = (ne + se) / 2;
map.setValue({ x, y - d2 }, east + dist(random.getEngine()));
// west
double west = (nw + sw) / 2;
map.setValue({ x, y + d2 }, west + dist(random.getEngine()));
}
}
d = d2;
}
Vector2i offset = (actualSize - size) / 2;
return map.subMap(RectI::fromPositionSize(offset, size));
}
/*
* Diamond-Square
*/
namespace {
void diamond(Heightmap& map, Random& random, Vector2i pos, int d) {
double value = (map.getValue({ pos.x - d, pos.y - d })
+ map.getValue({ pos.x - d, pos.y + d })
+ map.getValue({ pos.x + d, pos.y - d })
+ map.getValue({ pos.x + d, pos.y + d })) / 4;
double noise = random.computeUniformFloat(-static_cast<double>(d), static_cast<double>(d));
map.setValue(pos, value + noise);
}
void square(Heightmap& map, Random& random, Vector2i pos, int d) {
Vector2i size = map.getSize();
double value = 0.0;
int n = 0;
if (pos.x >= d) {
value += map.getValue({ pos.x - d, pos.y });
++n;
}
if (pos.x + d < size.width) {
value += map.getValue({ pos.x + d, pos.y });
++n;
}
if (pos.y >= d) {
value += map.getValue({ pos.x, pos.y - d });
++n;
}
if (pos.y + d < size.height) {
value += map.getValue({ pos.x, pos.y + d });
++n;
}
assert(n > 0);
value = value / n;
double noise = random.computeUniformFloat(-static_cast<double>(d), static_cast<double>(d));
map.setValue(pos, value + noise);
}
} // anonymous namespace
Heightmap diamondSquare2D(Vector2i size, Random& random, ArrayRef<double> initialValues) {
int actualSize = computePowerOfTwoSize(size);
int d = actualSize;
actualSize = actualSize + 1;
Heightmap map({ actualSize, actualSize });
initializeCorners(map, initialValues, d);
while (d >= 2) {
int d2 = d / 2;
for (int y = d2; y < actualSize; y += d) {
for (int x = d2; x < actualSize; x += d) {
diamond(map, random, { x, y }, d2);
}
}
for (int y = 0; y < actualSize; y += d) {
for (int x = d2; x < actualSize; x += d) {
square(map, random, { x, y }, d2);
}
}
for (int y = d2; y < actualSize; y += d) {
for (int x = 0; x < actualSize; x += d) {
square(map, random, { x, y }, d2);
}
}
d = d2;
}
Vector2i offset = (actualSize - size) / 2;
return map.subMap(RectI::fromPositionSize(offset, size));
}
/*
* Convex Hull
*/
namespace {
void findHull(const std::vector<Vector2f>& in, std::vector<Vector2f>& out, Vector2f a, Vector2f b) {
if (in.empty()) {
return;
}
Vector2f perp = gf::perp(a - b);
auto it = std::max_element(in.begin(), in.end(), [a, perp](Vector2f p1, Vector2f p2) {
Vector2f ap1 = p1 - a;
Vector2f ap2 = p2 - a;
float d1 = gf::dot(ap1, perp);
assert(d1 > 0);
float d2 = gf::dot(ap2, perp);
assert(d2 > 0);
return d1 < d2;
});
Vector2f c = *it;
std::vector<Vector2f> s1;
std::vector<Vector2f> s2;
for (auto& p : in) {
if (p == c) {
continue;
}
if (gf::cross(c - a, p - a) < 0) { // P is left of AC
s1.push_back(p);
}
if (gf::cross(b - c, p - c) < 0) { // P is left of CB
s2.push_back(p);
}
}
findHull(s1, out, a, c);
out.push_back(c);
findHull(s2, out, c, b);
}
void quickHull(ArrayRef<Vector2f> in, std::vector<Vector2f>& out) {
const Vector2f *pa;
const Vector2f *pb;
std::tie(pa, pb) = std::minmax_element(in.begin(), in.end(), [](Vector2f p1, Vector2f p2) {
return p1.x < p2.x;
});
const Vector2f a = *pa;
const Vector2f b = *pb;
std::vector<Vector2f> s1;
std::vector<Vector2f> s2;
for (auto& p : in) {
if (p == a || p == b) {
continue;
}
if (gf::cross(b - a, p - a) < 0) { // P is left of AB
s1.push_back(p);
} else { // P is left of BA
s2.push_back(p);
}
}
out.push_back(a);
findHull(s1, out, a, b);
out.push_back(b);
findHull(s2, out, b, a);
}
} // anonymous namespace
Polygon convexHull(ArrayRef<Vector2f> points) {
if (points.getSize() <= 3) {
return Polygon(points);
}
std::vector<Vector2f> out;
quickHull(points, out);
return Polygon(out);
}
namespace {
float distanceOfPointToLine(gf::Vector2f point, gf::Vector2f l1, gf::Vector2f l2) {
return std::abs(cross(l1 - l2, point - l1)) / euclideanDistance(l1, l2);
}
void simplifyPointsRecursive(ArrayRef<Vector2f> points, float distance, std::vector<Vector2f>& result) {
float maxDistance = 0.0f;
std::size_t maxIndex = 0;
std::size_t last = points.getSize() - 1;
for (std::size_t i = 1; i < last; ++i) {
float currentDistance = distanceOfPointToLine(points[i], points[0], points[last]);
if (currentDistance > maxDistance) {
maxDistance = currentDistance;
maxIndex = i;
}
}
if (maxDistance > distance) {
simplifyPointsRecursive(gf::array(points.begin(), maxIndex + 1), distance, result);
result.push_back(points[maxIndex]);
simplifyPointsRecursive(gf::array(points.begin() + maxIndex, points.getSize() - maxIndex), distance, result);
}
}
} // anonymous namespace
std::vector<Vector2f> simplifyPoints(ArrayRef<Vector2f> points, float distance) {
std::vector<Vector2f> result;
result.push_back(points[0]);
simplifyPointsRecursive(points, distance, result);
result.push_back(points[points.getSize() - 1]);
return result;
}
#ifndef DOXYGEN_SHOULD_SKIP_THIS
}
#endif
}
| [
"julien.bernard@univ-fcomte.fr"
] | julien.bernard@univ-fcomte.fr |
d18607a29d861e1ab2eb0aed6a70b83feaf27b03 | 8aca1a8e7c13b88b8cf1d288843be49eae1396a6 | /Exception.h | b226eaa9f67595663e250255f1fbe1bc831557c8 | [] | no_license | 1044686256/YuanchaoLib | 5da83b20560464ede1c0dd7ecb99314f0c470eee | f5330d5e2cea29be0d69db2e887a2871510f7b6b | refs/heads/main | 2023-02-09T17:15:07.198470 | 2020-12-30T03:21:49 | 2020-12-30T03:21:49 | 324,161,390 | 0 | 0 | null | 2020-12-30T03:43:38 | 2020-12-24T13:23:26 | C++ | UTF-8 | C++ | false | false | 3,861 | h | #ifndef EXCEPTION_H
#define EXCEPTION_H
/*
* 功能:异常类
* Exception:
* ArithmeticException //计算异常
* NullPointerException //空指针异常
* IndexOutOfBoundsException //越界异常
* NoEnoughMemoryException //内存不足异常
* InvalidParameterException //参数错误异常
* Time:20201224
* Aauthor:Yuanchao.Wu
*/
namespace YuanchaoLib{
#define THROW_EXCEPTION(e,m) (throw e(m,__FILE__,__LINE__))
class Exception
{
protected:
char* m_message;
char* m_location;
void init(const char* message,const char* file,int line);
public:
Exception(const char* message);
Exception(const char* file,int line);
Exception(const char* message,const char* file,int line);
Exception(const Exception& e);
Exception& operator = (const Exception& e);
virtual const char* message() const;
virtual const char* location() const;
virtual ~Exception()=0;
};
class ArithmeticException : public Exception
{
public:
ArithmeticException():Exception(0){}
ArithmeticException(const char* message):Exception(message){}
ArithmeticException(const char* message,int line):Exception(message,line){}
ArithmeticException(const char* message,char* file,int line):Exception(message,file,line){}
ArithmeticException(const ArithmeticException&e):Exception(e){}
ArithmeticException& operator = (const ArithmeticException& e)
{
Exception::operator=(e);
return *this;
}
};
class NullPointerException : public Exception
{
public:
NullPointerException():Exception(0){}
NullPointerException(const char* message):Exception(message){}
NullPointerException(const char* message,int line):Exception(message,line){}
NullPointerException(const char* message,char* file,int line):Exception(message,file,line){}
NullPointerException(const NullPointerException&e):Exception(e){}
NullPointerException& operator = (const NullPointerException& e)
{
Exception::operator=(e);
return *this;
}
};
class IndexOutOfBoundsException : public Exception
{
public:
IndexOutOfBoundsException():Exception(0){}
IndexOutOfBoundsException(const char* message):Exception(message){}
IndexOutOfBoundsException(const char* message,int line):Exception(message,line){}
IndexOutOfBoundsException(const char* message,char* file,int line):Exception(message,file,line){}
IndexOutOfBoundsException(const IndexOutOfBoundsException&e):Exception(e){}
IndexOutOfBoundsException& operator = (const IndexOutOfBoundsException& e)
{
Exception::operator=(e);
return *this;
}
};
class NoEnoughMemoryException : public Exception
{
public:
NoEnoughMemoryException():Exception(0){}
NoEnoughMemoryException(const char* message):Exception(message){}
NoEnoughMemoryException(const char* message,int line):Exception(message,line){}
NoEnoughMemoryException(const char* message,char* file,int line):Exception(message,file,line){}
NoEnoughMemoryException(const ArithmeticException&e):Exception(e){}
NoEnoughMemoryException& operator = (const NoEnoughMemoryException& e)
{
Exception::operator=(e);
return *this;
}
};
class InvalidParameterException : public Exception
{
public:
InvalidParameterException():Exception(0){}
InvalidParameterException(const char* message):Exception(message){}
InvalidParameterException(const char* message,int line):Exception(message,line){}
InvalidParameterException(const char* message,char* file,int line):Exception(message,file,line){}
InvalidParameterException(const InvalidParameterException&e):Exception(e){}
InvalidParameterException& operator = (const InvalidParameterException& e)
{
Exception::operator=(e);
return *this;
}
};
}
#endif // EXCEPTION_H
| [
"1044686256@qq.com"
] | 1044686256@qq.com |
d5493b38cce2dcf979580b1296125093c2e43da2 | 4433a2a1231225d23ceb14a898884c274e9c887c | /arduino_firmwares/midi_basic_io/midi_basic_io.ino | aa6c04436b5006dd073e8ff93ab4b3de9ed86e2a | [] | no_license | medialab-prado/Interactivos-16-DigitalStretch | f7c13e2bb2fa30fb402291e8027e8bb10976773d | 3eb5a676f4e10ab815be0b9d41ba5b9c42a5ab0a | refs/heads/master | 2021-01-20T20:41:55.059314 | 2016-06-09T15:39:57 | 2016-06-09T15:39:57 | 60,254,236 | 1 | 1 | null | 2016-06-09T14:09:11 | 2016-06-02T10:15:22 | Arduino | UTF-8 | C++ | false | false | 685 | ino | #define STRETCHSENSE A0
#include "MIDIUSB.h"
void setup() {
Serial.begin(115200);
}
// First parameter is the event type (0x0B = control change).
// Second parameter is the event type, combined with the channel.
// Third parameter is the control number number (0-119).
// Fourth parameter is the control value (0-127).
void controlChange(byte channel, byte control, byte value) {
midiEventPacket_t event = {0x0B, 0xB0 | channel, control, value};
MidiUSB.sendMIDI(event);
}
void loop() {
int reading;
reading = analogRead(STRETCHSENSE);
reading = map(reading, 0, 1023, 0, 127);
Serial.println(reading);
// for (int i = 0; i < 100; i++) {
controlChange(0, 65, reading);
// }
}
| [
"paclema@gmail.com"
] | paclema@gmail.com |
d4b3b19722eaacc8803ff5fe089f16eafc5ec992 | 26fd4d615946f73ee3964cd48fa06120611bf449 | /109_Convert_Sorted_List_to_Binary_Search_Tree_1.cpp | 7d7b64709ead6149945e2055b6170da78e189360 | [] | no_license | xujie-nm/Leetcode | 1aab8a73a33f954bfb3382a286626a56d2f14617 | eb8a7282083e2d2a6c94475759ba01bd4220f354 | refs/heads/master | 2020-04-12T07:25:51.621189 | 2016-12-03T09:29:36 | 2016-12-03T09:29:36 | 28,400,113 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,417 | cpp | #include <iostream>
#include <string>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
TreeNode* helper(ListNode *&head, int low, int high){
if(low > high)
return NULL;
int mid = (low + high)/2;
TreeNode* left;
left = helper(head, low, mid-1);
TreeNode* node = new TreeNode(head->val);
node->left = left;
head = head->next;
node->right = helper(head, mid+1, high);
return node;
}
TreeNode* sortedArrayToBST(ListNode* head){
if(head == NULL)
return NULL;
int size = 0;
ListNode *temp = head;
while(temp != NULL){
temp = temp->next;
size++;
}
return helper(head, 0, size-1);
}
void inOrder(TreeNode* root){
if(root == NULL)
return;
inOrder(root->left);
cout << root->val << " ";
inOrder(root->right);
}
int main(int argc, const char *argv[])
{
ListNode n1(1);
ListNode n2(2);
ListNode n3(3);
ListNode n4(4);
ListNode n5(5);
ListNode n6(6);
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
n5.next = &n6;
TreeNode* root;
root = sortedArrayToBST(&n1);
inOrder(root);
cout << endl;
return 0;
}
| [
"xujie_nm@163.com"
] | xujie_nm@163.com |
9b0197145a7a40fe113ee8897f69df131f847e8d | f54027a6c687c008fc0bba20b849276d4d1b6b1c | /IN2P3 and PHENIICS Geant4 Tutorial/session10/session10_start/session10_start/src/EDChamberSD.cc | 3d436af3daad0129d37c0365b1fa7d03ff059899 | [] | no_license | lc-leo/geant4-resource | f7969c256fb34e2604285dd31ab05d65551c2f2b | 9d5ba13634bbfbfaadd4274152eee1e635bed562 | refs/heads/master | 2023-04-13T16:35:06.489819 | 2023-04-09T07:40:49 | 2023-04-09T07:40:49 | 217,879,691 | 39 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 4,713 | cc | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// $Id$
//
/// \file EDChamberSD.cc
/// \brief Implementation of the EDChamberSD class
//
#include "EDChamberSD.hh"
#include "EDAnalysis.hh"
#include "G4HCofThisEvent.hh"
#include "G4SDManager.hh"
#include "G4VTouchable.hh"
#include "G4Step.hh"
#include "G4ios.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
EDChamberSD::EDChamberSD(const G4String& name,
const G4String& hitsCollectionName,
G4int ntupleId)
: G4VSensitiveDetector(name),
fHitsCollection(0),
fNtupleId(ntupleId)
{
collectionName.insert(hitsCollectionName);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
EDChamberSD::~EDChamberSD()
{}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void EDChamberSD::Initialize(G4HCofThisEvent* hce)
{
fHitsCollection
= new EDChamberHitsCollection(SensitiveDetectorName, collectionName[0]);
// Add this collection in hce
G4int hcID
= G4SDManager::GetSDMpointer()->GetCollectionID(collectionName[0]);
hce->AddHitsCollection(hcID, fHitsCollection);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
G4bool EDChamberSD::ProcessHits(G4Step* step,
G4TouchableHistory* /*history*/)
{
// Change the following line to get the charge of the tracked particle
G4double charge = step->GetTrack()->GetDefinition()->GetPDGCharge();
if ( charge == 0. ) return false;
// Create new hit
EDChamberHit* newHit = new EDChamberHit();
// Layer number
// = copy number of mother volume
G4StepPoint* preStepPoint = step->GetPreStepPoint();
const G4VTouchable* touchable = preStepPoint->GetTouchable();
G4VPhysicalVolume* motherPhysical = touchable->GetVolume(1); // mother
G4int copyNo = motherPhysical->GetCopyNo();
newHit->SetLayerNumber(copyNo);
// Time
G4double time = preStepPoint->GetGlobalTime();
newHit->SetTime(time);
// Position
G4ThreeVector position = preStepPoint->GetPosition();
newHit->SetPosition(position);
// Add hit in the collection
fHitsCollection->insert(newHit);
// Add hits properties in the ntuple
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
analysisManager->FillNtupleIColumn(fNtupleId, 0, copyNo);
analysisManager->FillNtupleDColumn(fNtupleId, 1, position.x());
analysisManager->FillNtupleDColumn(fNtupleId, 2, position.y());
analysisManager->FillNtupleDColumn(fNtupleId, 3, position.z());
analysisManager->AddNtupleRow(fNtupleId);
return false;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void EDChamberSD::EndOfEvent(G4HCofThisEvent* /*hce*/)
{
G4cout << "\n-------->" << fHitsCollection->GetName()
<< ": in this event: " << G4endl;
G4int nofHits = fHitsCollection->entries();
for ( G4int i=0; i<nofHits; i++ ) (*fHitsCollection)[i]->Print();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
| [
"noreply@github.com"
] | noreply@github.com |
2b8ce682f0e0354a92fe2590e74c7cd1e41a5c0b | 6b3f5fe67efcca2b9aa2c5c9a73964e3240748ab | /class16/file_read.cpp | b09ea03012965d2ed3f485968636ae1027407551 | [] | no_license | hunandy14/Cpp_Concept | 6197e2d7d508385460c39c38ff453c17c6b1e582 | 145bb8982cb41a613a8dbb5ac14f4fe2193e1ba3 | refs/heads/master | 2021-01-11T20:19:49.300528 | 2017-08-08T03:32:52 | 2017-08-08T03:32:52 | 79,092,228 | 0 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,009 | cpp | /*****************************************************************
Name :
Date : 2017/07/18
By : CharlotteHonG
Final: 2017/07/18
*****************************************************************/
#include <iostream>
#include <fstream>
#include "file_read.hpp"
using namespace std;
//================================================================
int main(int argc, char const *argv[]){
BmpFileHeader bf;
BmpInfoHeader bi;
string imgName ="in.bmp";
string imgName2 ="out.bmp";
// 讀取圖片
ifstream input;
input.open(imgName, ios::binary);
input.exceptions(ifstream::failbit|ifstream::badbit);
input >> bf >> bi;
size_t filesize = bf.bfSize;
cout << "filesize = " << filesize << endl;
// 寫入圖片
ofstream output;
output.open(imgName2, ios::binary);
output.exceptions(ifstream::failbit|ifstream::badbit);
bf.bfSize = filesize;
output << bf << bi;
return 0;
}
//================================================================
| [
"hunandy14@gmail.com"
] | hunandy14@gmail.com |
fbd2a4391994eab0f64577ed1897b8058efdfdab | 63ed2deb4616e8d3b93a4aefccd21d327ba82245 | /SizeRestrictions/form.cpp | 0c5b9248ed8a47e0f0b18d3d3c9a6f8ce9520be7 | [] | no_license | drescherjm/QtExamples | 2f49cf85b04c08c011c2c0539862bfbf613f92a5 | 129a14dabb4cda84526d2780862d32156c75ec01 | refs/heads/master | 2020-12-25T06:12:05.772601 | 2012-03-19T00:40:40 | 2012-03-19T00:40:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 263 | cpp | #include "form.h"
MyForm::MyForm(QWidget *parent)
: QWidget(parent)
{
setupUi(this);
connect( this->pushButton, SIGNAL( clicked() ), this, SLOT(pushButton_SetLabelText()) );
}
void MyForm::pushButton_SetLabelText()
{
this->label->setText("hello");
}
| [
"daviddoria@gmail.com"
] | daviddoria@gmail.com |
480c7a14e2709b9f49f4f9474d21e52760bae677 | f0bba4aa341b5e6d54ed07208568a697bb8a9041 | /Homework02/solutions/matrix.cpp | 6327558ddddd6bea9b8be88f286663c9c63c62ff | [] | no_license | destroierdam/Intro-to-Programming-IS-2019 | 3aba05d88df866e9c857596113094ff738bed86c | f91cdecb7b95f3557324bd0ab0aca8115b75ba29 | refs/heads/master | 2021-06-28T09:28:56.534631 | 2021-01-27T20:19:17 | 2021-01-27T20:19:17 | 212,347,410 | 0 | 3 | null | 2021-01-27T20:19:17 | 2019-10-02T13:21:38 | C++ | UTF-8 | C++ | false | false | 2,309 | cpp | #include<iostream>
using std::cin;
using std::cout;
using std::endl;
const int MAX_SIZE = 32;
// Exercise: Make the following two functions more generic
/// Moves first to second, second to third, third to fourth, fourth to first
void twistClockwise(int & first, int & second, int & third, int & fourth) {
int temp = fourth;
// Move third to fourth
fourth = third;
third = second;
second = first;
first = temp;
}
/// Moves second to first, third to second, fourth to third, first to fourth
void twistCounterclockwise(int & first, int & second, int & third, int & fourth) {
int temp = first;
first = second;
second = third;
third = fourth;
fourth = temp;
}
void twist(int matrix[][MAX_SIZE], int rows, int cols, int n) {
// Indices of the element in the upper left corner
int upperLeftCornerRow = 0;
int upperLeftCornerColumn = 0;
int upperRightCornerRow = 0;
int upperRightCornerColumn = cols-1;
int lowerLeftCornerRow = rows-1;
int lowerLeftCornerColumn = 0;
int lowerRightCornerRow = rows-1;
int lowerRightCornerColumn = cols-1;
for(int i = 0; i < rows/2; i++) {
for(int j = 0; j < n; j++) {
if(i % 2 == 0) {
twistClockwise(matrix[upperLeftCornerRow][upperLeftCornerColumn],
matrix[upperRightCornerRow][upperRightCornerColumn],
matrix[lowerRightCornerRow][lowerRightCornerColumn],
matrix[lowerLeftCornerRow][lowerLeftCornerColumn]);
} else {
twistCounterclockwise(matrix[upperLeftCornerRow][upperLeftCornerColumn],
matrix[upperRightCornerRow][upperRightCornerColumn],
matrix[lowerRightCornerRow][lowerRightCornerColumn],
matrix[lowerLeftCornerRow][lowerLeftCornerColumn]);
}
}
upperLeftCornerRow++;
upperLeftCornerColumn++;
upperRightCornerRow++;
upperRightCornerColumn--;
lowerRightCornerRow--;
lowerRightCornerColumn--;
lowerLeftCornerRow--;
lowerLeftCornerColumn++;
}
}
int main() {
int rows = 5, cols = 5;
int matrix[MAX_SIZE][MAX_SIZE] = { { 1, 2, 3, 4, 5 },
{ 4, 5, 6, 7, 8 },
{ 3, 4, 5, 9, 0 },
{ 5, 6, 9, 1, 2 },
{ 6, 10, 11, 0, 1} };
twist(matrix, rows, cols, 3);
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
cout << matrix[i][j] << '\t';
}
cout << endl;
}
return 0;
} | [
"dam-bb@hotmail.com"
] | dam-bb@hotmail.com |
6b945cc50767019b235fc9c2994d5572d63298da | 431a5c28b8dfcc7d6ca6f4f97bf370cd770547a7 | /src/v2i-hub/CARMAStreetsPlugin/src/JsonToJ2735SpatConverter.cpp | 999be321d53a96530f45d31e94efd31614969355 | [
"Apache-2.0"
] | permissive | usdot-fhwa-OPS/V2X-Hub | 134061cfb55d8c83e871f7fd4bbfa5d8d3092eb0 | aae33e6a16b8a30e1faee31a7ee863d191be06b8 | refs/heads/develop | 2023-08-26T10:10:59.989176 | 2023-08-24T14:58:21 | 2023-08-24T14:58:21 | 168,020,929 | 106 | 63 | null | 2023-09-11T20:24:45 | 2019-01-28T19:16:45 | C | UTF-8 | C++ | false | false | 10,538 | cpp | #include "JsonToJ2735SpatConverter.h"
namespace CARMAStreetsPlugin
{
void JsonToJ2735SpatConverter::convertJson2Spat(const Json::Value &spat_json, SPAT *spat) const
{
ASN_STRUCT_FREE_CONTENTS_ONLY(asn_DEF_SPAT, spat);
// Parse spat name field
if (spat_json.isMember("name") && spat_json["name"].asString().length() != 0)
{
std::string name = spat_json["name"].asString();
spat->name = (DescriptiveName_t *)calloc(1, sizeof(DescriptiveName_t));
spat->name->buf = (uint8_t *)calloc(1, name.length());
spat->name->size = name.length();
memcpy(spat->name->buf, name.c_str(), name.length());
}
if (spat_json.isMember("time_stamp"))
{
int32_t time_stamp = spat_json["time_stamp"].asInt();
spat->timeStamp = (MinuteOfTheYear_t *)calloc(1, sizeof(MinuteOfTheYear_t));
*spat->timeStamp = time_stamp;
}
// Parse intersections
if (spat_json["intersections"].isArray())
{
convertJson2IntersectionStateList(spat_json["intersections"], &spat->intersections);
}
}
void JsonToJ2735SpatConverter::convertJson2IntersectionStateList(const Json::Value &intersections_json, IntersectionStateList *intersections) const
{
for (const auto &int_json : intersections_json)
{
auto intersection = (IntersectionState_t *)calloc(1, sizeof(IntersectionState_t));
// intersection name
auto name = int_json["name"].asString();
auto intersection_name = (DescriptiveName_t *)calloc(1, sizeof(DescriptiveName_t));
intersection_name->size = name.length();
intersection_name->buf = (uint8_t *)calloc(1, name.length());
memcpy(intersection_name->buf, name.c_str(), name.length());
// intersection id
auto id = int_json["id"].asInt();
intersection->id.id = id;
intersection->name = intersection_name;
// revision
auto revision = int_json["revision"].asInt();
intersection->revision = revision;
// moy
auto moy_int = int_json["moy"].asInt();
intersection->moy = (MinuteOfTheYear_t *)calloc(1, sizeof(MinuteOfTheYear_t));
*intersection->moy = moy_int;
// timestamp
intersection->timeStamp = (DSecond_t *)calloc(1, sizeof(DSecond_t));
*intersection->timeStamp = int_json["time_stamp"].asInt();
// status
auto status = static_cast<int16_t>(int_json["status"].asInt());
intersection->status.buf = (uint8_t *)calloc(2, sizeof(uint8_t));
intersection->status.size = 2 * sizeof(uint8_t);
intersection->status.bits_unused = 0;
intersection->status.buf[1] = static_cast<int8_t>(status);
intersection->status.buf[0] = (status >> 8);
// enabled_lanes
const auto &enabled_lanes_json = int_json["enabled_lanes"];
if (enabled_lanes_json.isArray())
{
intersection->enabledLanes = (EnabledLaneList_t *)calloc(1, sizeof(EnabledLaneList_t));
for (const auto &laneId : enabled_lanes_json)
{
auto lane = (LaneID_t *)calloc(1, sizeof(LaneID_t));
*lane = laneId.asInt();
ASN_SEQUENCE_ADD(&intersection->enabledLanes->list, lane);
}
}
// Movements
if (int_json["states"].isArray())
{
convertJson2MovementList(int_json["states"], &intersection->states);
}
// Manuever Assist List
if (int_json["maneuver_assist_list"].isArray())
{
intersection->maneuverAssistList = (ManeuverAssistList_t *)calloc(1, sizeof(ManeuverAssistList_t));
convertJson2ManeuverAssistList(int_json["maneuver_assist_list"], intersection->maneuverAssistList);
}
ASN_SEQUENCE_ADD(&intersections->list, intersection);
}
}
void JsonToJ2735SpatConverter::convertJson2MovementList(const Json::Value &movements_json, MovementList *states) const
{
for (const auto &movement_json : movements_json)
{
auto state = (MovementState_t *)calloc(1, sizeof(MovementState_t));
if (movement_json.isMember("movement_name") && movement_json["movement_name"].asString().length() != 0)
{
auto movement_name_str = movement_json["movement_name"].asString();
state->movementName = (DescriptiveName_t *)calloc(1, sizeof(DescriptiveName_t));
state->movementName->size = movement_name_str.length();
state->movementName->buf = (uint8_t *)calloc(1, movement_name_str.length());
memcpy(state->movementName->buf, movement_name_str.c_str(), movement_name_str.length());
}
state->signalGroup = movement_json["signal_group"].asInt();
if (movement_json["state_time_speed"].isArray())
{
convertJson2MovementEventList(movement_json["state_time_speed"], &state->state_time_speed);
}
if (movement_json["maneuver_assist_list"].isArray())
{
state->maneuverAssistList = (ManeuverAssistList_t *)calloc(1, sizeof(ManeuverAssistList_t));
convertJson2ManeuverAssistList(movement_json["maneuver_assist_list"], state->maneuverAssistList);
}
ASN_SEQUENCE_ADD(&states->list, state);
}
}
void JsonToJ2735SpatConverter::convertJson2MovementEventList(const Json::Value &movement_event_list_json, MovementEventList *state_time_speed) const
{
for (const auto &m_event : movement_event_list_json)
{
auto movement_event = (MovementEvent_t *)calloc(1, sizeof(MovementEvent_t));
movement_event->eventState = m_event["event_state"].asInt();
// Timing
const auto &timing_json = m_event["timing"];
movement_event->timing = (TimeChangeDetails_t *)calloc(1, sizeof(TimeChangeDetails_t));
convertJson2TimeChangeDetail(timing_json, movement_event->timing);
// speeds
const auto &speeds_json = m_event["speeds"];
if (speeds_json.isArray())
{
movement_event->speeds = (AdvisorySpeedList_t *)calloc(1, sizeof(AdvisorySpeedList_t));
convertJson2AdvisorySpeed(speeds_json, movement_event->speeds);
}
ASN_SEQUENCE_ADD(&state_time_speed->list, movement_event);
}
}
void JsonToJ2735SpatConverter::convertJson2TimeChangeDetail(const Json::Value &time_change_detail_json, TimeChangeDetails_t *timing) const
{
timing->startTime = (DSRC_TimeMark_t *)calloc(1, sizeof(DSRC_TimeMark_t));
*timing->startTime = time_change_detail_json["start_time"].asInt();
timing->minEndTime = time_change_detail_json["min_end_time"].asInt();
timing->maxEndTime = (DSRC_TimeMark_t *)calloc(1, sizeof(DSRC_TimeMark_t));
*timing->maxEndTime = time_change_detail_json["max_end_time"].asInt();
timing->likelyTime = (DSRC_TimeMark_t *)calloc(1, sizeof(DSRC_TimeMark_t));
*timing->likelyTime = time_change_detail_json["likely_time"].asInt();
timing->nextTime = (DSRC_TimeMark_t *)calloc(1, sizeof(DSRC_TimeMark_t));
*timing->nextTime = time_change_detail_json["next_time"].asInt();
timing->confidence = (TimeIntervalConfidence_t *)calloc(1, sizeof(TimeIntervalConfidence_t));
*timing->confidence = time_change_detail_json["confidence"].asInt();
}
void JsonToJ2735SpatConverter::convertJson2AdvisorySpeed(const Json::Value &speeds_json, AdvisorySpeedList_t *speeds) const
{
for (const auto &speed_json : speeds_json)
{
auto speed = (AdvisorySpeed_t *)calloc(1, sizeof(AdvisorySpeed_t));
speed->type = speed_json["type"].asInt();
speed->speed = (SpeedAdvice_t *)calloc(1, sizeof(SpeedAdvice_t));
*speed->speed = speed_json["speed_limit"].asInt();
speed->confidence = (SpeedConfidence_t *)calloc(1, sizeof(SpeedConfidence_t));
*speed->confidence = speed_json["speed_confidence"].asInt();
speed->Class = (RestrictionClassID_t *)calloc(1, sizeof(RestrictionClassID_t));
*speed->Class = speed_json["class"].asInt();
speed->distance = (ZoneLength_t *)calloc(1, sizeof(ZoneLength_t));
*speed->distance = speed_json["distance"].asInt();
ASN_SEQUENCE_ADD(&speeds->list, speed);
}
}
void JsonToJ2735SpatConverter::convertJson2ManeuverAssistList(const Json::Value &maneuver_assist_list_json, ManeuverAssistList_t *maneuver_assist_list) const
{
for (const auto &masst : maneuver_assist_list_json)
{
auto maneuver_assist = (ConnectionManeuverAssist_t *)calloc(1, sizeof(ConnectionManeuverAssist_t));
maneuver_assist->connectionID = masst["connection_id"].asInt();
maneuver_assist->queueLength = (ZoneLength_t *)calloc(1, sizeof(ZoneLength_t));
*maneuver_assist->queueLength = masst["queue_length"].asInt();
maneuver_assist->availableStorageLength = (ZoneLength_t *)calloc(1, sizeof(ZoneLength_t));
*maneuver_assist->availableStorageLength = masst["available_storage_length"].asInt();
maneuver_assist->waitOnStop = (WaitOnStopline_t *)calloc(1, sizeof(WaitOnStopline_t));
*maneuver_assist->waitOnStop = masst["wait_on_stop"].asBool() ? 1 : 0;
maneuver_assist->pedBicycleDetect = (PedestrianBicycleDetect_t *)calloc(1, sizeof(PedestrianBicycleDetect_t));
*maneuver_assist->pedBicycleDetect = masst["ped_bicycle_detect"].asBool() ? 1 : 0;
ASN_SEQUENCE_ADD(&maneuver_assist_list->list, maneuver_assist);
}
}
void JsonToJ2735SpatConverter::encodeSpat(const std::shared_ptr<SPAT> &spat_ptr, tmx::messages::SpatEncodedMessage &encodedSpat) const
{
tmx::messages::MessageFrameMessage frame(spat_ptr);
encodedSpat.set_data(tmx::messages::TmxJ2735EncodedMessage<SPAT>::encode_j2735_message<tmx::messages::codec::uper<tmx::messages::MessageFrameMessage>>(frame));
free(frame.get_j2735_data().get());
}
} | [
"noreply@github.com"
] | noreply@github.com |
ad29e289ac458c4f6c4316fe99488608f16d16be | 0f8ef68729cb03c50a9649feed7b48bf3dda3730 | /lab1/message.cpp | ed311291377d2249059f1fe2aae9a8dd4bfb9fc0 | [] | no_license | se98100/polito-SP-labs | 89f9bfd3386fbf14c10aefdfb4a4969c2fe813a0 | 5d638c61562990d9e4529786964a4876bf79d25e | refs/heads/master | 2023-04-01T14:11:58.861492 | 2021-04-12T20:54:23 | 2021-04-12T20:54:23 | 355,485,726 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,954 | cpp | //
// Created by Sergio on 08/04/2021.
//
#include <cstring>
#include "message.h"
char* mkMessage(int n) {
string vowels = "aeiou";
string consonants = "bcdfghlmnpqrstvz";
char* m = new (nothrow) char[n+1];
if(m != nullptr){
for(int i=0; i<n; i++)
m[i] = i%2 ? vowels [rand() % vowels.size()] : consonants[rand() % consonants.size()];
m[n] = '\0';
}
return m;
}
ostream& operator<<(ostream& out, const Message& m) {
const char* data = m.getData();
string s(data == nullptr ? "NULL" : data);
out << "[id:" << m.getId() << "][size:" << m.getSize() << "][data:" << s.substr(0, 20) << "]";
return out;
}
Message& Message::operator=(const Message& source) {
if(&source == this) return *this;
delete[] _data;
_data = nullptr;
_size = source._size;
_id = source._id;
if(source._data != nullptr){
_data = new char[_size+1];
memcpy(_data, source._data, _size+1);
}
return *this;
}
Message& Message::operator=(Message&& source) {
delete[] _data;
_id = source._id;
_size = source._size;
_data = source._data;
source._data = nullptr;
source._id = -1;
source._size = -1;
return *this;
}
Message::Message() : _size(0), _id(-1) {
_data = nullptr;
}
Message::Message(int size, long id) : _size(size), _id(id) {
if(_size > -1){
_data = mkMessage(_size);
}else{
_data = nullptr;
_id = -1;
}
}
Message::~Message() {
delete[] _data;
_data = nullptr;
}
Message::Message(const Message& source){
_id = source._id;
_size = source._size;
_data = nullptr;
if(source._size > 0) {
_data = new char[_size + 1];
memcpy(_data, source._data, _size + 1);
}
}
Message::Message(Message&& source) {
_id = source._id;
_size = source._size;
_data = source._data;
source._data = nullptr;
source._id = -1;
source._size = -1;
}
| [
"se98100@gmail.com"
] | se98100@gmail.com |
f4ec7c7dbae7f270f751e51b7e489202071c4c9c | e04f3bebf39ff6ea8be005182e0d98d395b15337 | /org.xtext.alma.sdmdsl/generated/include/GainTrackingRow.h | 6759785ae923471efaca4cf7746a7df2f30c3c7c | [] | no_license | loriebi/SDMDSL | edb457caf440baa6638ba6997be3d81c613a0049 | 0a41e8d2c1b7c3f1eef1fbc39c793b347f7e9b2b | refs/heads/master | 2021-01-23T20:32:13.222533 | 2017-09-08T14:05:53 | 2017-09-08T14:05:53 | 102,865,767 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,154 | h | /*
* ALMA - Atacama Large Millimeter Array
* (c) European Southern Observatory, 2002
* (c) Associated Universities Inc., 2002
* Copyright by ESO (in the framework of the ALMA collaboration),
* Copyright by AUI (in the framework of the ALMA collaboration),
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY, without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
* Warning!
* --------------------------------------------------------------------
* | This is generated code! Do not modify this file. |
* | If you do, all changes will be lost when the file is re-generated. |
* --------------------------------------------------------------------
*
* File GainTrackingRow.h
*/
#ifndef GainTrackingRow_CLASS
#define GainTrackingRow_CLASS
#include <vector>
#include <string>
#include <set>
#ifndef WITHOUT_ACS
#include <asdmIDLC.h>
#endif
#include <ArrayTimeInterval.h>
#include <Tag.h>
#include <ComplexWrapper.h>
#include "CPolarizationType.h"
#include <ConversionException.h>
#include <NoSuchRow.h>
#include <IllegalAccessException.h>
#include <RowTransformer.h>
//#include <TableStreamReader.h>
/*\file GainTracking.h
\brief Generated from model's revision "-1", branch ""
*/
namespace asdm {
//class asdm::GainTrackingTable;
// class asdm::AntennaRow;
class AntennaRow;
// class asdm::SpectralWindowRow;
class SpectralWindowRow;
// class asdm::FeedRow;
class FeedRow;
class GainTrackingRow;
typedef void (GainTrackingRow::*GainTrackingAttributeFromBin) (EndianIStream& eis);
typedef void (GainTrackingRow::*GainTrackingAttributeFromText) (const string& s);
/**
* The GainTrackingRow class is a row of a GainTrackingTable.
*
* Generated from model's revision "-1", branch ""
*
*/
class GainTrackingRow {
friend class asdm::GainTrackingTable;
friend class asdm::RowTransformer<GainTrackingRow>;
//friend class asdm::TableStreamReader<GainTrackingTable, GainTrackingRow>;
public:
virtual ~GainTrackingRow();
/**
* Return the table to which this row belongs.
*/
GainTrackingTable &getTable() const;
/**
* Has this row been added to its table ?
* @return true if and only if it has been added.
*/
bool isAdded() const;
////////////////////////////////
// Intrinsic Table Attributes //
////////////////////////////////
// ===> Attribute timeInterval
/**
* Get timeInterval.
* @return timeInterval as ArrayTimeInterval
*/
ArrayTimeInterval getTimeInterval() const;
/**
* Set timeInterval with the specified ArrayTimeInterval.
* @param timeInterval The ArrayTimeInterval value to which timeInterval is to be set.
* @throw IllegalAccessException If an attempt is made to change this field after is has been added to the table.
*/
void setTimeInterval (ArrayTimeInterval timeInterval);
// ===> Attribute numReceptor
/**
* Get numReceptor.
* @return numReceptor as int
*/
int getNumReceptor() const;
/**
* Set numReceptor with the specified int.
* @param numReceptor The int value to which numReceptor is to be set.
*/
void setNumReceptor (int numReceptor);
// ===> Attribute attenuator
/**
* Get attenuator.
* @return attenuator as vector<float >
*/
vector<float > getAttenuator() const;
/**
* Set attenuator with the specified vector<float >.
* @param attenuator The vector<float > value to which attenuator is to be set.
*/
void setAttenuator (vector<float > attenuator);
// ===> Attribute polarizationType
/**
* Get polarizationType.
* @return polarizationType as vector<PolarizationTypeMod::PolarizationType >
*/
vector<PolarizationTypeMod::PolarizationType > getPolarizationType() const;
/**
* Set polarizationType with the specified vector<PolarizationTypeMod::PolarizationType >.
* @param polarizationType The vector<PolarizationTypeMod::PolarizationType > value to which polarizationType is to be set.
*/
void setPolarizationType (vector<PolarizationTypeMod::PolarizationType > polarizationType);
// ===> Attribute samplingLevel, which is optional
/**
* The attribute samplingLevel is optional. Return true if this attribute exists.
* @return true if and only if the samplingLevel attribute exists.
*/
bool isSamplingLevelExists() const;
/**
* Get samplingLevel, which is optional.
* @return samplingLevel as float
* @throws IllegalAccessException If samplingLevel does not exist.
*/
float getSamplingLevel() const;
/**
* Set samplingLevel with the specified float.
* @param samplingLevel The float value to which samplingLevel is to be set.
*/
void setSamplingLevel (float samplingLevel)
/**
* Mark samplingLevel, which is an optional field, as non-existent.
*/
void clearSamplingLevel ();
// ===> Attribute numAttFreq, which is optional
/**
* The attribute numAttFreq is optional. Return true if this attribute exists.
* @return true if and only if the numAttFreq attribute exists.
*/
bool isNumAttFreqExists() const;
/**
* Get numAttFreq, which is optional.
* @return numAttFreq as int
* @throws IllegalAccessException If numAttFreq does not exist.
*/
int getNumAttFreq() const;
/**
* Set numAttFreq with the specified int.
* @param numAttFreq The int value to which numAttFreq is to be set.
*/
void setNumAttFreq (int numAttFreq)
/**
* Mark numAttFreq, which is an optional field, as non-existent.
*/
void clearNumAttFreq ();
// ===> Attribute attFreq, which is optional
/**
* The attribute attFreq is optional. Return true if this attribute exists.
* @return true if and only if the attFreq attribute exists.
*/
bool isAttFreqExists() const;
/**
* Get attFreq, which is optional.
* @return attFreq as vector<double >
* @throws IllegalAccessException If attFreq does not exist.
*/
vector<double > getAttFreq() const;
/**
* Set attFreq with the specified vector<double >.
* @param attFreq The vector<double > value to which attFreq is to be set.
*/
void setAttFreq (vector<double > attFreq)
/**
* Mark attFreq, which is an optional field, as non-existent.
*/
void clearAttFreq ();
// ===> Attribute attSpectrum, which is optional
/**
* The attribute attSpectrum is optional. Return true if this attribute exists.
* @return true if and only if the attSpectrum attribute exists.
*/
bool isAttSpectrumExists() const;
/**
* Get attSpectrum, which is optional.
* @return attSpectrum as vector<Complex >
* @throws IllegalAccessException If attSpectrum does not exist.
*/
vector<Complex > getAttSpectrum() const;
/**
* Set attSpectrum with the specified vector<Complex >.
* @param attSpectrum The vector<Complex > value to which attSpectrum is to be set.
*/
void setAttSpectrum (vector<Complex > attSpectrum)
/**
* Mark attSpectrum, which is an optional field, as non-existent.
*/
void clearAttSpectrum ();
////////////////////////////////
// Extrinsic Table Attributes //
////////////////////////////////
// ===> Attribute antennaId
/**
* Get antennaId.
* @return antennaId as Tag
*/
Tag getAntennaId() const;
/**
* Set antennaId with the specified Tag.
* @param antennaId The Tag value to which antennaId is to be set.
* @throw IllegalAccessException If an attempt is made to change this field after is has been added to the table.
*/
void setAntennaId (Tag antennaId);
// ===> Attribute feedId
/**
* Get feedId.
* @return feedId as int
*/
int getFeedId() const;
/**
* Set feedId with the specified int.
* @param feedId The int value to which feedId is to be set.
* @throw IllegalAccessException If an attempt is made to change this field after is has been added to the table.
*/
void setFeedId (int feedId);
// ===> Attribute spectralWindowId
/**
* Get spectralWindowId.
* @return spectralWindowId as Tag
*/
Tag getSpectralWindowId() const;
/**
* Set spectralWindowId with the specified Tag.
* @param spectralWindowId The Tag value to which spectralWindowId is to be set.
* @throw IllegalAccessException If an attempt is made to change this field after is has been added to the table.
*/
void setSpectralWindowId (Tag spectralWindowId);
///////////
// Links //
///////////
/**
* Compare each mandatory attribute except the autoincrementable one of this GainTrackingRow with
* the corresponding parameters and return true if there is a match and false otherwise.
* @param antennaId
* @param spectralWindowId
* @param timeInterval
* @param feedId
* @param numReceptor
* @param attenuator
* @param polarizationType
*/
bool compareNoAutoInc(Tag antennaId, Tag spectralWindowId, ArrayTimeInterval timeInterval, int feedId, int numReceptor, vector<float > attenuator, vector<PolarizationTypeMod::PolarizationType > polarizationType);
/**
* Compare each mandatory value (i.e. not in the key) attribute with
* the corresponding parameters and return true if there is a match and false otherwise.
* @param numReceptor
* @param attenuator
* @param polarizationType
*/
bool compareRequiredValue(int numReceptor, vector<float > attenuator, vector<PolarizationTypeMod::PolarizationType > polarizationType);
/**
* Return true if all required attributes of the value part are equal to their homologues
* in x and false otherwise.
*
* @param x a pointer on the GainTrackingRow whose required attributes of the value part
* will be compared with those of this.
* @return a boolean.
*/
bool equalByRequiredValue(GainTrackingRow* x) ;
#ifndef WITHOUT_ACS
/**
* Return this row in the form of an IDL struct.
* @return The values of this row as a GainTrackingRowIDL struct.
*/
asdmIDL::GainTrackingRowIDL *toIDL() const;
/**
* Define the content of a GainTrackingRowIDL struct from the values
* found in this row.
*
* @param x a reference to the GainTrackingRowIDL struct to be set.
*
*/
void toIDL(asdmIDL::GainTrackingRowIDL& x) const;
#endif
#ifndef WITHOUT_ACS
/**
* Fill the values of this row from the IDL struct GainTrackingRowIDL.
* @param x The IDL struct containing the values used to fill this row.
* @throws ConversionException
*/
void setFromIDL (asdmIDL::GainTrackingRowIDL x) ;
#endif
/**
* Return this row in the form of an XML string.
* @return The values of this row as an XML string.
*/
std::string toXML() const;
/**
* Fill the values of this row from an XML string
* that was produced by the toXML() method.
* @param rowDoc the XML string being used to set the values of this row.
* @throws ConversionException
*/
void setFromXML (std::string rowDoc) ;
/// @cond DISPLAY_PRIVATE
////////////////////////////////////////////////////////////
// binary-deserialization material from an EndianIStream //
////////////////////////////////////////////////////////////
std::map<std::string, GainTrackingAttributeFromBin> fromBinMethods;
void antennaIdFromBin( EndianIStream& eis);
void spectralWindowIdFromBin( EndianIStream& eis);
void timeIntervalFromBin( EndianIStream& eis);
void feedIdFromBin( EndianIStream& eis);
void numReceptorFromBin( EndianIStream& eis);
void attenuatorFromBin( EndianIStream& eis);
void polarizationTypeFromBin( EndianIStream& eis);
void samplingLevelFromBin( EndianIStream& eis);
void numAttFreqFromBin( EndianIStream& eis);
void attFreqFromBin( EndianIStream& eis);
void attSpectrumFromBin( EndianIStream& eis);
/**
* Deserialize a stream of bytes read from an EndianIStream to build a PointingRow.
* @param eiss the EndianIStream to be read.
* @param table the GainTrackingTable to which the row built by deserialization will be parented.
* @param attributesSeq a vector containing the names of the attributes . The elements order defines the order
* in which the attributes are written in the binary serialization.
*/
static GainTrackingRow* fromBin(EndianIStream& eis, GainTrackingTable& table, const std::vector<std::string>& attributesSeq);
/**
* Parses a string t and assign the result of the parsing to the attribute of name attributeName.
*
* @param attributeName the name of the attribute whose value is going to be defined.
* @param t the string to be parsed into a value given to the attribute of name attributeName.
*/
void fromText(const std::string& attributeName, const std::string& t);
/// @endcond
private:
/**
* The table to which this row belongs.
*/
GainTrackingTable &table;
/**
* Whether this row has been added to the table or not.
*/
bool hasBeenAdded;
// This method is used by the Table class when this row is added to the table.
void isAdded(bool added);
/**
* Create a GainTrackingRow.
* <p>
* This constructor is private because only the
* table can create rows. All rows know the table
* to which they belong.
* @param table The table to which this row belongs.
*/
GainTrackingRow (GainTrackingTable &table);
/**
* Create a GainTrackingRow using a copy constructor mechanism.
* <p>
* Given a GainTrackingRow row and a GainTrackingTable table, the method creates a new
* GainTrackingRow owned by table. Each attribute of the created row is a copy (deep)
* of the corresponding attribute of row. The method does not add the created
* row to its table, its simply parents it to table, a call to the add method
* has to be done in order to get the row added (very likely after having modified
* some of its attributes).
* If row is null then the method returns a row with default values for its attributes.
*
* This constructor is private because only the
* table can create rows. All rows know the table
* to which they belong.
* @param table The table to which this row belongs.
* @param row The row which is to be copied.
*/
GainTrackingRow (GainTrackingTable &table, GainTrackingRow &row);
////////////////////////////////
// Intrinsic Table Attributes //
////////////////////////////////
// ===> Attribute timeInterval
ArrayTimeInterval timeInterval;
// ===> Attribute numReceptor
int numReceptor;
// ===> Attribute attenuator
vector<float > attenuator;
// ===> Attribute polarizationType
vector<PolarizationTypeMod::PolarizationType > polarizationType;
// ===> Attribute samplingLevel, which is optional
bool samplingLevelExists;
float samplingLevel;
// ===> Attribute numAttFreq, which is optional
bool numAttFreqExists;
int numAttFreq;
// ===> Attribute attFreq, which is optional
bool attFreqExists;
vector<double > attFreq;
// ===> Attribute attSpectrum, which is optional
bool attSpectrumExists;
vector<Complex > attSpectrum;
////////////////////////////////
// Extrinsic Table Attributes //
////////////////////////////////
// ===> Attribute antennaId
Tag antennaId;
// ===> Attribute feedId
int feedId;
// ===> Attribute spectralWindowId
Tag spectralWindowId;
///////////
// Links //
///////////
/*
////////////////////////////////////////////////////////////
// binary-deserialization material from an EndianIStream //
////////////////////////////////////////////////////////////
std::map<std::string, GainTrackingAttributeFromBin> fromBinMethods;
void antennaIdFromBin( EndianIStream& eis);
void spectralWindowIdFromBin( EndianIStream& eis);
void timeIntervalFromBin( EndianIStream& eis);
void feedIdFromBin( EndianIStream& eis);
void numReceptorFromBin( EndianIStream& eis);
void attenuatorFromBin( EndianIStream& eis);
void polarizationTypeFromBin( EndianIStream& eis);
void samplingLevelFromBin( EndianIStream& eis);
void numAttFreqFromBin( EndianIStream& eis);
void attFreqFromBin( EndianIStream& eis);
void attSpectrumFromBin( EndianIStream& eis);
*/
///////////////////////////////////
// text-deserialization material //
///////////////////////////////////
std::map<std::string, GainTrackingAttributeFromText> fromTextMethods;
void antennaIdFromText (const string & s);
void spectralWindowIdFromText (const string & s);
void timeIntervalFromText (const string & s);
void feedIdFromText (const string & s);
void numReceptorFromText (const string & s);
void attenuatorFromText (const string & s);
void polarizationTypeFromText (const string & s);
void samplingLevelFromText (const string & s);
void numAttFreqFromText (const string & s);
void attFreqFromText (const string & s);
void attSpectrumFromText (const string & s);
/**
* Serialize this into a stream of bytes written to an EndianOSStream.
* @param eoss the EndianOSStream to be written to
*/
void toBin(EndianOSStream& eoss);
/**
* Deserialize a stream of bytes read from an EndianIStream to build a PointingRow.
* @param eiss the EndianIStream to be read.
* @param table the GainTrackingTable to which the row built by deserialization will be parented.
* @param attributesSeq a vector containing the names of the attributes . The elements order defines the order
* in which the attributes are written in the binary serialization.
static GainTrackingRow* fromBin(EndianIStream& eis, GainTrackingTable& table, const std::vector<std::string>& attributesSeq);
*/
};
} // End namespace asdm
#endif /* GainTracking_CLASS */
| [
"levan.l2ria@gmail.com"
] | levan.l2ria@gmail.com |
01e173eb156257f97ff5631042e2f8c452f7d093 | b38383846d082ec4e65ac18c1582f1ce231ea0b4 | /Siv3D/src/ThirdParty/infoware/src/cpu/vendor_model_name/vendor_model_name_non_windows_non_darwin.cpp | d86b11fd1ac0b173fe44f128170bea649fae2c78 | [
"MIT"
] | permissive | Siv3D/siv6 | 9c12427f470b65772f40504b1e5e5239a60bbe95 | 090e82b2f6398640638dfa43da3f829ba977d0e2 | refs/heads/master | 2021-02-07T05:12:41.108547 | 2020-10-25T05:27:11 | 2020-10-25T05:27:11 | 243,986,884 | 3 | 5 | MIT | 2020-09-27T14:32:38 | 2020-02-29T14:50:43 | C++ | UTF-8 | C++ | false | false | 1,224 | cpp | // infoware - C++ System information Library
//
// Written in 2016-2020 by nabijaczleweli <nabijaczleweli@gmail.com> and ThePhD <phdofthehouse@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright and related
// and neighboring rights to this software to the public domain worldwide. This software is
// distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>
#ifndef _WIN32
#ifndef __APPLE__
#include "infoware/cpu.hpp"
#include <fstream>
#include <string>
static std::string cpuinfo_value(const char* key) {
std::ifstream cpuinfo("/proc/cpuinfo");
if(!cpuinfo.is_open() || !cpuinfo)
return {};
for(std::string line; std::getline(cpuinfo, line);)
if(line.find(key) == 0) {
const auto colon_id = line.find_first_of(':');
const auto nonspace_id = line.find_first_not_of(" \t", colon_id + 1);
return line.c_str() + nonspace_id;
}
return {};
}
std::string iware::cpu::vendor() {
return cpuinfo_value("vendor");
}
std::string iware::cpu::model_name() {
return cpuinfo_value("model name");
}
#endif
#endif
| [
"reputeless+github@gmail.com"
] | reputeless+github@gmail.com |
b5eb4c68ebdea9cc727e3bf48d69fc92b317cf7c | d156ecd033ffdab9c959e7924d41b944549bd549 | /dbc/dbc_table.h | 335a36fcf54969327fb76bec384aaaac06fdbf07 | [] | no_license | Refuge89/WoWCraft | 42a88d0d5f590879f6dfeb9d56a13cfabca785b2 | 78bd04cbe41a70f7fdcbb3eff08effc19651c5a8 | refs/heads/master | 2020-03-14T14:14:10.770943 | 2017-06-02T21:56:01 | 2017-06-02T21:56:01 | 131,649,521 | 1 | 1 | null | 2018-04-30T21:41:53 | 2018-04-30T21:41:53 | null | UTF-8 | C++ | false | false | 9,339 | h | #ifndef DBC_TABLE_H
#define DBC_TABLE_H
#include <vector>
#include "dbc/dbc_files.h"
#include "dbc/dbc_projection.h"
#include "dbc/dbc.h"
enum class dbc_table_state
{
BEGIN,
CONFIGURED,
LOADED
};
enum class dbc_table_error
{
NO_ERROR,
INVALID_SOURCE
};
/*
* Given is a table T with n rows of records, where each record is uniquely identified by it's key fields
*
* The table T is not mutable at all, so we can identify each row uniquely also by it's index i.
* So T[i] is said to be a row with index i. We now need a mapping k -> i where keys k are sorted for fast lookup (logn),
* Then T[k] is also allowed but implemented as T[f(k)] = T[i].
*
* But now we also want this table to be sorted by any column, so we apply a sort on all rows and and get a list of
* keys in a new order and this order will be unordered with regards to the key, but ordered with regards to the column.
* This is a lookup si -> k where si is "sorted index".
*
* The last thing we need is a lookup with k -> si
*/
template <typename K>
struct key_t
{
unsigned int index;
K key;
unsigned int sorted_index;
key_t(unsigned int idx, K k, unsigned int sorted_idx) : index(idx), key(k), sorted_index(sorted_idx) {}
};
template <typename K>
struct si_t
{
key_t<K> * key;
si_t(key_t<K> & k) : key(&k) {}
};
template <typename K, typename RECORD>
struct key_index_lookup_table
{
private:
std::vector<RECORD> data;
std::vector<key_t<K>> keys;
std::vector<si_t<K>> sorted_keys;
unsigned int lookup_key_impl(const K & k, unsigned int l, unsigned int u) const
{
if(dbc_impl::dbc_field_less_than<K>{}(k,keys[(l+u)/2].key))
{
return lookup_key_impl(k,l,((l+u)/2));
}
else if(dbc_impl::dbc_field_less_than<K>{}(keys[(l+u)/2].key,k))
{
return lookup_key_impl(k,((l+u)/2)+1,u);
}
return keys[(l+u)/2].index;
}
unsigned int lookup_key(const K & k) const
{
return lookup_key_impl(k,0,keys.size()-1);
}
public:
template <typename F>
void push_back(RECORD r, F f)
{
data.push_back(r);
keys.push_back(key_t<K>{data.size()-1,f(r),data.size()-1});
}
/* Before using any other operation than push on this class, sort_keys() must be performed. */
void sort_keys()
{
sorted_keys.clear();
std::sort(keys.begin(),keys.end(),[](const key_t<K> & ls, const key_t<K> & rs)
{
return dbc_impl::dbc_field_less_than<K>{}(ls.key,rs.key);
});
for(unsigned int i = 0; i < keys.size(); ++i)
{
sorted_keys.push_back(si_t<K>{keys[i]});
}
}
void sort_by(bool (*cmp)(const RECORD&,const RECORD&))
{
std::sort(sorted_keys.begin(),sorted_keys.end(), [=](const si_t<K> & L, const si_t<K> & R)
{
return cmp(data[(L.key)->index],data[(R.key)->index]);
});
for(unsigned int i = 0; i < sorted_keys.size(); ++i)
{
(sorted_keys[i].key)->sorted_index = i;
}
}
const RECORD & at_index(unsigned int idx) const
{
return data[lookup_key((*(sorted_keys[idx].key)).key)];
}
const RECORD & at_key(const K & key) const
{
return data[lookup_key(key)];
}
unsigned int key_index(const K & key) const
{
return lookup_key(key);
}
void clear()
{
data.clear();
keys.clear();
sorted_keys.clear();
}
unsigned int size() const { return data.size(); }
};
struct empty_string
{
const char * string_block() { return nullptr; }
void reserve(unsigned int){}
void copy(const char *, unsigned int){}
};
struct string_wrapper
{
char * m_data;
const char * string_block() { return m_data; }
void reserve(unsigned int n)
{
m_data = new char[n];
}
void copy(const char * begin, unsigned int count)
{
memcpy(m_data,begin,count);
}
string_wrapper() : m_data(nullptr) {}
~string_wrapper()
{
if(m_data)
delete [] m_data;
}
};
template <typename VIEW, typename PROJECTION>
struct dbc_table_types
{
typedef typename VIEW::record_type record_type;
using map = typename PROJECTION::map;
typedef typename record_type::template tuple_t<map> record_t;
typedef typename record_type::template projected_record<map> projected_record;
enum { has_string = dbc_record<projected_record>::has_string };
};
template <typename VIEW, typename PROJECTION>
class dbc_table :
/* If there are strings in the projection, we need a vector with all string data from view. */
public tmp::get_element_at<dbc_table_types<VIEW,PROJECTION>::has_string,empty_string,string_wrapper>
{
private:
typedef typename VIEW::record_type record_type;
using map = typename PROJECTION::map;
using map_index = typename PROJECTION::map_index;
typedef typename record_type::template tuple_t<map> record_t;
static_assert(record_type::template is_compatible<map>::value,"A projection mapping must refer to field indices in the view.");
template <map_index I>
using map_index_type = typename record_type::template field_store_type<tmp::get_element_in<static_cast<unsigned int>(I), map>::value>;
typedef map_index_type<PROJECTION::map_key> map_key_type;
unsigned int m_order_by_field;
key_index_lookup_table<map_key_type, record_t> m_lookup_table;
void sort_by(unsigned int column)
{
m_lookup_table.sort_by([=](const record_t& L, const record_t& R)
{
return VIEW::record_type::compare_by_field(column,L,R);
});
}
dbc_table_state m_state;
dbc_table_error m_error;
const VIEW * m_view;
public:
dbc_table()
{
m_state = dbc_table_state::BEGIN;
m_error = dbc_table_error::NO_ERROR;
m_order_by_field = static_cast<unsigned int>(PROJECTION::map_key);
}
~dbc_table(){}
void configure(const VIEW & view)
{
m_view = &view;
m_state = dbc_table_state::CONFIGURED;
if(!m_view->is_valid())
m_error = dbc_table_error::INVALID_SOURCE;
}
void load()
{
if(m_state == dbc_table_state::CONFIGURED && m_error != dbc_table_error::INVALID_SOURCE)
{
if(dbc_table_types<VIEW,PROJECTION>::has_string)
{
this->reserve(m_view->string_block_size());
this->copy(m_view->string_block(),m_view->string_block_size());
}
const char * string_block_begin = this->string_block();
for(unsigned int i = 0; i < m_view->count(); ++i)
{
auto key_data_f = [](const record_t & t) -> map_key_type
{
return std::get<static_cast<unsigned int>(PROJECTION::map_key)>(t);
};
m_lookup_table.push_back(dbc_impl::dbc_project_on_tuple<VIEW,record_type,map>::project(*m_view,i,string_block_begin),
key_data_f);
}
m_lookup_table.sort_keys();
m_state = dbc_table_state::LOADED;
}
}
bool is_valid() const { return (m_state == dbc_table_state::CONFIGURED) ? m_view.is_valid() : true; }
std::string error_msg() const
{
switch(m_error)
{
case dbc_table_error::NO_ERROR:
return "No error.";
case dbc_table_error::INVALID_SOURCE:
return std::string{"Invalid source ("} + m_view->error_msg() + std::string{")"};
}
return "";
}
bool correct_error() const { return m_view->correct_error(); }
float progress_value() const
{
return (m_state == dbc_table_state::CONFIGURED ? 100.0f*float(m_lookup_table.size())/float(m_view->count()) : 0.0f);
}
bool is_completed() const { return m_state == dbc_table_state::LOADED; }
/* Discard the data */
void discard()
{
if(m_state == dbc_table_state::LOADED)
{
m_state = dbc_state::CONFIGURED;
m_lookup_table.clear();
}
m_error = dbc_error::NO_ERROR;
m_order_by_field = static_cast<unsigned int>(PROJECTION::map_key);
}
struct view
{
private:
const dbc_table & m_table;
public:
typedef dbc_table::record_t record_t;
view(const dbc_table & t) : m_table(t) {}
inline const record_t& record_at(unsigned int idx) const
{
return m_table.m_lookup_table.at_index(idx);
}
inline unsigned int key_index(const map_key_type& key) const
{
return m_table.m_lookup_table.key_index(key);
}
bool is_valid() const { return m_table.is_valid(); }
std::string error_msg() const { return m_table.error_msg(); }
bool correct_error() const { return m_table.correct_error(); }
float progress_value() const { return m_table.progress_value(); }
unsigned int count() const { return m_table.m_lookup_table.size(); }
};
/* Get the view */
view operator()() const
{
return view{*this};
}
};
#endif /* DBC_TABLE_H */
| [
"hermanh@student.chalmers.se"
] | hermanh@student.chalmers.se |
fe877226aa3e64f7946572e78af9f18b4005dbcf | 7a8a90dab1a7ebb99a1d71d160ada1ce73e916d6 | /DarkTable.h | a4ae2644421a098d053b37fec28f62c85c4567b5 | [] | no_license | mtab3/xafsm2 | 95f5823f79f43105bc7ceef50746cc1f0cb3d623 | 46c6debf633d215de51eff9e150c61ff333155a1 | refs/heads/master | 2021-01-10T06:50:22.514830 | 2015-05-25T08:44:02 | 2015-05-25T08:44:02 | 46,334,410 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 496 | h | #ifndef DARKTABLE_H
#define DARKTABLE_H
#include "ui_DarkTable.h"
class DarkTable : public QFrame, private Ui::DarkTable
{
Q_OBJECT
private:
public:
DarkTable( QWidget *p = NULL );
void clearItems( void );
void setRowCol( int r, int c )
{ DTable->setRowCount( r ); DTable->setColumnCount( c ); };
void setItem( int r, int c, QTableWidgetItem *item )
{ DTable->setItem( r, c, item ); };
QTableWidgetItem* getItem( int r, int c ) { return DTable->item( r, c ); };
};
#endif
| [
"m.tabuchi@nusr.nagoya-u.ac.jp"
] | m.tabuchi@nusr.nagoya-u.ac.jp |
a9d1b7c09e1cb504d76ab4c5268701ba3d975ae9 | 80ce68cc469a17301088143ade30774d606c7623 | /Source/18120598_18120632_18120650_console/18120598_18120632_18120650/FileInteraction_QFLoat.h | 61dfbebbcb0eca712a4c2b29a96807d4f6549566 | [] | no_license | lntuan99/Computer-Architecture-and-Assembly-Language---Project-1 | 5016c24b3d35fe69259dada038084b32b6d2bf18 | f7465b1df092353a54e1ed1e7fd7cbbd212667bc | refs/heads/master | 2022-07-08T10:02:50.284550 | 2020-05-10T09:58:22 | 2020-05-10T09:58:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 554 | h | #pragma once
#include"Qfloat.h"
#include<sstream>
#include<fstream>
using namespace std;
void processDataFromFile_QFloat(string inputFile, string outputFile); // Đọc file từng dòng và lưu dữ liệu vào các biến phù hợp theo thứ tự và cách nhau bằng khoảng cách
string CalculateData_QFloat(string p1, string p2, string n); // Sử dụng các biến đưa vào, xác định yêu cầu tính qua sự hiện diện của các biến và bắt đầu tính toán
void writeDataToFile_QFloat(string n, string outputFile);
| [
"nhattuannhat99@gmail.com"
] | nhattuannhat99@gmail.com |
48311edbafb5d134e05f4ad410640a5a9bfa731d | cc946ca4fb4831693af2c6f252100b9a83cfc7d0 | /uCash.Cybos/uCash.Cybos.FutureJpBid.cpp | 4da095ea0da595b16b21252a4d62efd2da692530 | [] | no_license | primespace/ucash-cybos | 18b8b324689516e08cf6d0124d8ad19c0f316d68 | 1ccece53844fad0ef8f3abc8bbb51dadafc75ab7 | refs/heads/master | 2021-01-10T04:42:53.966915 | 2011-10-14T07:15:33 | 2011-10-14T07:15:33 | 52,243,596 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,465 | cpp | /*
* uCash.Cybos Copyright (c) 2011 Taeyoung Park (primespace@naver.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "stdafx.h"
#include "uCash.Cybos.Export.h"
#include "uCash.Cybos.CpObject.h"
#include "uCash.Cybos.CpFutureJpBid.h"
namespace uCash { namespace Cybos {
CpFutureJpBid::CpFutureJpBid(void)
{
}
CpFutureJpBid::~CpFutureJpBid(void)
{
}
}} // namespace uCash::Cybos | [
"uacefx@gmail.com"
] | uacefx@gmail.com |
7aed73eeffd1772c1c85305789a26625a70fa98e | b56b32e4ab050b362ecf1065cf36997b612079ff | /tools/aapt2/Resource_test.cpp | ad4e3ce02b32b7aa331ed6ff03ed6cf58e4fea10 | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | FrankenRom/android_frameworks_base | b9966f4c56fef231e4828b0aba6a396547b5a54f | afe38efd0f8f8853bcefe5b86381b85565459ac4 | refs/heads/oc | 2021-09-21T13:19:35.687858 | 2017-12-27T18:30:48 | 2017-12-27T18:30:48 | 124,714,862 | 2 | 13 | NOASSERTION | 2021-07-06T09:14:59 | 2018-03-11T02:01:29 | Java | UTF-8 | C++ | false | false | 3,496 | cpp | /*
* Copyright (C) 2015 The Android Open Source Project
*
* 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 "Resource.h"
#include "test/Test.h"
namespace aapt {
TEST(ResourceTypeTest, ParseResourceTypes) {
const ResourceType* type = ParseResourceType("anim");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kAnim);
type = ParseResourceType("animator");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kAnimator);
type = ParseResourceType("array");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kArray);
type = ParseResourceType("attr");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kAttr);
type = ParseResourceType("^attr-private");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kAttrPrivate);
type = ParseResourceType("bool");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kBool);
type = ParseResourceType("color");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kColor);
type = ParseResourceType("configVarying");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kConfigVarying);
type = ParseResourceType("dimen");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kDimen);
type = ParseResourceType("drawable");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kDrawable);
type = ParseResourceType("font");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kFont);
type = ParseResourceType("fraction");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kFraction);
type = ParseResourceType("id");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kId);
type = ParseResourceType("integer");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kInteger);
type = ParseResourceType("interpolator");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kInterpolator);
type = ParseResourceType("layout");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kLayout);
type = ParseResourceType("menu");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kMenu);
type = ParseResourceType("mipmap");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kMipmap);
type = ParseResourceType("plurals");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kPlurals);
type = ParseResourceType("raw");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kRaw);
type = ParseResourceType("string");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kString);
type = ParseResourceType("style");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kStyle);
type = ParseResourceType("transition");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kTransition);
type = ParseResourceType("xml");
ASSERT_NE(type, nullptr);
EXPECT_EQ(*type, ResourceType::kXml);
type = ParseResourceType("blahaha");
EXPECT_EQ(type, nullptr);
}
} // namespace aapt
| [
"adamlesinski@google.com"
] | adamlesinski@google.com |
5797788113d39ff1d86ccd375de6effe3d305d44 | af37ecb44f69f82bea034a9cdafbccb85fff1a01 | /src/spork.h | 7e8819b070a11ede13571447b4f58b61c6922058 | [
"MIT"
] | permissive | defiantcrypto/defiant | aa0651d1922c920bc0d3f03fe70f41532c7e1242 | 8bcb78800582fdc71b100dc87034e3a99ecc1dfa | refs/heads/master | 2022-12-21T08:54:32.037859 | 2020-09-03T09:24:12 | 2020-09-03T09:24:12 | 292,109,111 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,188 | h | // Copyright (c) 2015 The Defiant developers
// Copyright (c) 2009-2012 The Darkcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef SPORK_H
#define SPORK_H
#include "bignum.h"
#include "sync.h"
#include "net.h"
#include "key.h"
#include "util.h"
#include "script.h"
#include "base58.h"
#include "main.h"
using namespace std;
using namespace boost;
// Don't ever reuse these IDs for other sporks
#define SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT 10000
#define SPORK_2_MAX_VALUE 10002
#define SPORK_3_REPLAY_BLOCKS 10003
#define SPORK_4_NOTUSED 10004
#define SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT_DEFAULT 2428537599 //2015-4-8 23:59:59 GMT
#define SPORK_2_MAX_VALUE_DEFAULT 5000 //5000 Defiant
#define SPORK_3_REPLAY_BLOCKS_DEFAULT 0
#define SPORK_4_RECONVERGE_DEFAULT 1451606400 //2016-01-01 // NOT USED
class CSporkMessage;
class CSporkManager;
#include "bignum.h"
#include "net.h"
#include "key.h"
#include "util.h"
#include "protocol.h"
#include "darksend.h"
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
extern std::map<uint256, CSporkMessage> mapSporks;
extern std::map<int, CSporkMessage> mapSporksActive;
extern CSporkManager sporkManager;
void ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv);
int GetSporkValue(int nSporkID);
bool IsSporkActive(int nSporkID);
void ExecuteSpork(int nSporkID, int nValue);
//
// Spork Class
// Keeps track of all of the network spork settings
//
class CSporkMessage
{
public:
std::vector<unsigned char> vchSig;
int nSporkID;
int64_t nValue;
int64_t nTimeSigned;
uint256 GetHash(){
uint256 n = Hash(BEGIN(nSporkID), END(nTimeSigned));
return n;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
unsigned int nSerSize = 0;
READWRITE(nSporkID);
READWRITE(nValue);
READWRITE(nTimeSigned);
READWRITE(vchSig);
}
};
class CSporkManager
{
private:
std::vector<unsigned char> vchSig;
std::string strMasterPrivKey;
std::string strTestPubKey;
std::string strMainPubKey;
public:
CSporkManager() {
strMainPubKey = "04a983220ea7a38a7106385003fef77896538a382a0dcc389cc45f3c98751d9af423a097789757556259351198a8aaa628a1fd644c3232678c5845384c744ff8d7";
strTestPubKey = "04a983220ea7a38a7106385003fef77896538a382a0dcc389cc45f3c98751d9af423a097789757556259351198a8aaa628a1fd644c3232678c5845384c744ff8d7";
}
std::string GetSporkNameByID(int id);
int GetSporkIDByName(std::string strName);
bool UpdateSpork(int nSporkID, int64_t nValue);
bool SetPrivKey(std::string strPrivKey);
bool CheckSignature(CSporkMessage& spork);
bool Sign(CSporkMessage& spork);
void Relay(CSporkMessage& msg);
};
#endif
| [
"ttt@ttt.com"
] | ttt@ttt.com |
4f63f02051471e7b8bbe3e28e8a48400a310cddc | d8c149edd5b614afa1ca531eb1198aa143a5e049 | /src/ZcloudDeskAssist/BigDataImpl.h | cde6b3fff2bbd716b7fcc34553862134e4fcf95b | [] | no_license | gispda/ZcloudDesk | ecb9d08231373815107a082d2f6a517d668e8513 | c4a0c126c2261a6d087d96175a457783c2f43ebd | refs/heads/master | 2022-12-03T13:51:49.978571 | 2020-08-24T16:46:27 | 2020-08-24T16:46:27 | 283,679,013 | 1 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,261 | h | #pragma once
#include <QThread>
#include <QQueue>
#include <QWaitCondition>
#include <QtNetwork/QTcpSocket>
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QNetworkInterface>
#include <QTimer>
class BigDataImpl:public QThread
{
Q_OBJECT
public:
~BigDataImpl();
static BigDataImpl *GetInstance();
virtual void produceData(QString strMsgClsId, QString strOperationId, QString strOperandId, QString strNotes = "", bool isImmediately = false);
virtual void stopThread();
virtual void initData();
public slots:
//!行为上报timer
void onReportCollection();
protected:
void run();
private:
void destory();
void setBuffSize(int nSize = 100);
void stopImmediately();
void waitForStop();
void setReleaseThread();
//!开始线程
void startThread();
//!上报数据到大数据服务器
void reportCollectionData(QTcpSocket *cli);
QString getHostMacAddress();
explicit BigDataImpl(QObject *parent = 0);
static BigDataImpl *m_pInstance;
bool initialized;
QString tcpClientIp;
QString strIp;
int actionPort;
int m_nBufferSize;
QMutex m_mutex;
QMutex m_boolMutex;
QQueue<QString> m_BdQueue;
QQueue<QString> m_SendQueue;
bool m_bBreak;
QByteArray m_colloctBytes;
QTimer* m_pTimerClient;
};
| [
"gispda@qq.com"
] | gispda@qq.com |
89d1d6fc7e17724a4c78bf32f2164553fb45d7c8 | 301d8ccc8789667d168586286e78a2434cf40c9f | /ejercicios/mas_ejercicios/ejercicio7.cpp | 24c1efde7314b78b2c399ffde179120c8a1ecc08 | [] | no_license | SebastianRomeritho/curso_cplusplus | 1e3d3d477f904bec981972d080150fc536a0eadb | f3b7fade9b2e661cc98b4bfc7ccf0bb4239373f6 | refs/heads/master | 2022-12-28T23:36:44.831342 | 2020-10-15T14:48:25 | 2020-10-15T14:48:25 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 3,370 | cpp | //################################################################################
//Diseñar un programa que permita adivinar al ordenador un determinado número
//entero y positivo para lo cual se deben leer los límites en los que está
//comprendido dicho número.
//################################################################################
#include <iostream>
using namespace std;
int devolverNumero(int liminf,int limsup);
char LeerOpcion(int num,int &liminf,int &limsup);
int main(int argc, char *argv[]) {
int limite_inferior, limite_superior, minumero;
char opcion;
int intentos=0;
cout << "Piensa un número..." << endl;
//Se pide el primer intervalo
cout << "Necesito saber el intervalo donde se encuentra el número:" << endl;
cout << "Límite inferior:" << endl;
cin >> limite_inferior;
cout << "Límite superior:" << endl;
cin >> limite_superior;
//Se va repitiendo hasta que se acierte el número
do {
//Escribimos el número propuesto (qué sera el número intermedio del intervalo)
minumero=devolverNumero(limite_inferior,limite_superior);
cout << "¿Has pensando en el número?:" << minumero << endl;
//Incrementamos el número de intentos
intentos=intentos+1;
//Leemos la opción, si no ha acertado se modifica algunos de los límites y se vuelve a proponer un nuevo número
opcion=LeerOpcion(minumero,limite_inferior,limite_superior);
}
while(toupper(opcion!='S'));
//Se escribe los intentos que ha necesitado para acertarlo
cout << "Lo he acertado en " << intentos << " intentos.";
}
//################################################################################
//Función devolverNumero: Recibe un intervalo (límite inferior y superior) y
//devuelve el número intermedio como posible número que tiene que acertar.
//Parámetro de entrada: Límite inferior y superior del intervalo.
//Dato devuelto: Número intermedio del intervalo.
//################################################################################
int devolverNumero(int liminf,int limsup)
{
return (liminf+limsup) / 2;
}
//################################################################################
//Función LeerOpcion: Recibe un intervalo (límite inferior y superior) y el número
//que ha propuesto como solución y devuelve la opción escogida:
//'S', si es correcto.
//'A', si es más alto que el número a adivinar.
//'B', si es más bajo. Al finalizar el programa, se deberá escribir el número de
//intentos realizados para acertar el número.
//Si la opción es A, se modifica el límite inferior con el número propuesto.
//Si la opción es B, se modifica el límite superior con el número propuesto.
//Parámetro de entrada: Número propuesto
//Parámetro de entrada y salida: Límite inferior y superior del intervalo.
//Dato devuelto: Opción escogida
//################################################################################
char LeerOpcion(int num,int &liminf,int &limsup)
{
char opcion;
do
{
cout << "¿Es correcto?" << endl;
cout << "S: si es correcto." << endl;
cout << "A: si es más alto que el número a adivinar." << endl;
cout << "B: si es más bajo." << endl;
cin >> opcion;
}
while(toupper(opcion)!='S' && toupper(opcion)!='A' && toupper(opcion)!='B');
if(toupper(opcion)!='A')
liminf=num;
if(toupper(opcion)!='B')
limsup=num;
return opcion;
}
| [
"josedom24@gmail.com"
] | josedom24@gmail.com |
90f5cadeb68872c643ff3fdd707deb65d42f1f3d | 9bcb900f91b9c50a4cd23208568a5c7f8ebf9c5b | /FCFS.cpp | 470d4ee134be818a9bc4378ec955d82f9aa85b85 | [] | no_license | Aayushshrivastav/Operating-System | cb3aa4afdb054998fb996e8232811ce304d89aab | 8b8288970d19a0e8663ac5072e5d7a31dc288cf4 | refs/heads/master | 2020-04-21T16:42:41.542497 | 2019-04-18T17:15:50 | 2019-04-18T17:15:50 | 169,711,449 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 708 | cpp | #include<iostream>
using namespace std;
int main()
{ int n;
cout<<"enter no. of processes\n";
cin>>n;
int AT[n],ET[n];
cout<<"enter arrival time for processes\n";
for(int i=0;i<=n-1;i++)
{
cin>>AT[i];
}
cout<<"enter execution time for processes\n";
for(int i=0;i<=n-1;i++)
{
cin>>ET[i];
}
int CT[n],TAT[n],WT[n];
for(int i=0;i<=n-1;i++)
{
if(i==0)
CT[i]=ET[i]-AT[i];
else if(CT[i-1]>AT[i])
CT[i]=CT[i-1]+ET[i];
else
CT[i]=AT[i]+ET[i];
TAT[i]=CT[i]-AT[i];
WT[i]=TAT[i]-ET[i];
}
for(int i=0;i<=n-1;i++)
{
cout<<"CT["<<i<<"]="<<CT[i]<<"\n";
cout<<"TAT["<<i<<"]="<<TAT[i]<<"\n";
cout<<"WT["<<i<<"]="<<WT[i]<<"\n";
}
}
| [
"noreply@github.com"
] | noreply@github.com |
c94e794782a0ebe9ec7b248a7021fd051c993f27 | 9658fb19f9dca5ea3d908ae558f63638d44ad868 | /hw4/include/SetImpl.h | 213f0369a4dddaa38b80c0d7dea466ef3b007868 | [] | no_license | modalton/CSCI104-Older- | 207de704cb0a8f1c3fcc6c0338786b7e96a08737 | a19c8c9889100ce4ab1e7d94d45ade6f5464580c | refs/heads/master | 2021-01-19T10:14:57.122140 | 2014-07-26T05:54:14 | 2014-07-26T05:54:14 | 87,845,203 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,100 | h |
#include <stdexcept>
template <class T>
Set<T>::Set(){} //constructor
template <class T>
Set<T>::Set(const Set<T> & other){} //copy constructor
template <class T> //deconstructor
Set<T>::~Set(){}
template <class T>
void Set<T>::add(const T & other){
if(this->contains(other)){ throw std::invalid_argument("void Set<T>::add(const T & other)- already in set");}
internalStorage.insert(0, other);
} //throws exception if alread in set
template <class T>
void Set<T>::remove (const T & item){
if(this->contains(item)==false){ throw std::invalid_argument("void Set<T>::remove (const T & item)- set doesn't contain item");}
for(int i =0; i<internalStorage.capacity;i++)
{if(internalStorage.get(i)==item){ internalStorage.remove(i); return;}
}
}
/* Removes the item from the set.
Throws an exception if the set does not contain the item. */
template <class T>
bool Set<T>::contains (const T & item) const{
for(int i =0; i<internalStorage.capacity;i++)
{if(internalStorage.get(i)==item){ return true;}}
return false;}
/* Returns true if the set contains the item, and false otherwise. */
template <class T>
int Set<T>::size () const{return internalStorage.capacity;}
/* Returns the number of elements in the set. */
template <class T>
bool Set<T>::isEmpty () const{
if(internalStorage.capacity==0){return false;}
else{return true;}
}
/* Returns true if the set is empty, and false otherwise. */
template <class T>
Set<T> Set<T>::setIntersection (const Set<T> & other) const{
Set<T> intersect;
Set<T> new_obj;
for (int i = 0; i < internalStorage.size(); i++)
{if(other.contains(internalStorage.get(i))){ new_obj.add(internalStorage.get(i)); std::cout<<"intersect "<<internalStorage.get(i)<<"\n"; }}
return new_obj;
}
/* Returns the intersection of the current set with other.
That is, returns the set of all items that are both in this
and in other. */
template <class T>
Set<T> Set<T>::setUnion (const Set<T> & other) const{
Set<T> new_obj;
for (int i = 0; i < internalStorage.size(); i++)
{ new_obj.add(internalStorage.get(i));std::cout<< internalStorage.get(i)<< "\n";}
for (int i=0; i < other.size(); i++)
{if(new_obj.contains(other.internalStorage.get(i))){}
else{new_obj.add(other.internalStorage.get(i)); std::cout<< other.internalStorage.get(i)<< "\n";}
}
return new_obj;
}
/* Returns the union of the current set with other.
That is, returns the set of all items that are in this set
or in other (or both).
The resulting set should not contain duplicates. */
/* The next two functions together implement a suboptimal version
of what is called an "iterator".
Together, they should give you a way to loop through all elements
of the set. The function "first" starts the loop, and the function
"next" moves on to the next element.
You will want to keep the state of the loop inside a private variable.
We will learn the correct way to implement iterators soon, at
which point you will replace this.
For now, we want to keep it simple. */
template <class T>
T* Set<T>::first (){
if(internalStorage.capacity==0){return NULL;}
else{return &internalStorage.get(0);} //insert RAND
}
/* Returns the pointer to some element of the set,
which you may consider the "first" element.
Should return NULL if the set is empty. */
template <class T>
T* Set<T>::next (){
first_num = last_num%internalStorage.size();
last_num = (last_num+1)%internalStorage.size();
//std:: cout << "First num-" << first_num <<" last num-" << last_num%internalStorage.size()<< "\n";
return &internalStorage.get((last_num)%internalStorage.size());
}
/* Returns the pointer to an element of the set different from all
the ones that "first" and "next" have returned so far.
Should return NULL if there are no more element. */
template <class T>
T* Set<T>::commonsense(int pos){ return &internalStorage.get(pos);}
template<class T>
int Set<T>::fnum(){return last_num;}
| [
"modalton@usc.edu"
] | modalton@usc.edu |
ca9eaa565b70c30bbb127c10f8a29549dd94385b | 678465f0ee681c0c3e4ce1050f6b539fa2fc17fc | /program/pcf/pcf_core/point_cloud/transform_iterator.h | 4c58a80ec8a2dc9ec02b03e901483fc02767b646 | [] | no_license | timlenertz/Thesis | 528f15024bbfc92073fab303577236681ce2496f | 78a7c1f12be5f945d43ffb27f9cf070fe0360a78 | refs/heads/master | 2021-01-25T19:23:36.239621 | 2015-08-15T19:01:39 | 2015-08-15T19:01:39 | 24,094,197 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,279 | h | #ifndef PCF_POINT_TRANSFORM_ITERATOR_H_
#define PCF_POINT_TRANSFORM_ITERATOR_H_
#include <iterator>
#include <Eigen/Geometry>
#include "../point.h"
namespace pcf {
/**
Point iterator that applies affine transformation to point.
Provides read-only access to the point.
*/
template<typename Point>
class point_transform_iterator :
public std::iterator<std::random_access_iterator_tag, Point> {
private:
Eigen::Affine3f transformation_;
Point* point_;
mutable bool should_load_transformed_point_;
mutable Point transformed_point_;
void load_transformed_point_() const;
template<typename That, typename Condition_func, typename Callback_func>
static void nearest_neighbors_(That that, std::size_t k, Condition_func cond, Callback_func callback, bool parallel);
public:
point_transform_iterator(Point*, const Eigen::Affine3f& = Eigen::Affine3f());
point_transform_iterator(const point_transform_iterator&) = default;
point_transform_iterator& operator=(const point_transform_iterator& it) {
transformation_ = it.transformation_;
point_ = it.point_;
return *this;
}
bool operator==(const point_transform_iterator&) const;
bool operator!=(const point_transform_iterator&) const;
bool operator<(const point_transform_iterator&) const;
bool operator<=(const point_transform_iterator&) const;
bool operator>(const point_transform_iterator&) const;
bool operator>=(const point_transform_iterator&) const;
const Point& operator*() const;
const Point* operator->() const;
const Point& real_point() const { return *point_; }
Point& real_point() { return *point_; }
point_transform_iterator& operator++();
point_transform_iterator& operator--();
point_transform_iterator operator++(int);
point_transform_iterator operator--(int);
point_transform_iterator& operator+=(std::ptrdiff_t);
point_transform_iterator& operator-=(std::ptrdiff_t);
point_transform_iterator operator+(std::ptrdiff_t) const;
point_transform_iterator operator-(std::ptrdiff_t) const;
std::ptrdiff_t operator-(const point_transform_iterator&) const;
Point& operator[](std::ptrdiff_t) const;
};
extern template class point_transform_iterator<point_xyz>;
extern template class point_transform_iterator<point_full>;
}
#include "transform_iterator.tcc"
#endif | [
"timlenertz@gmail.com"
] | timlenertz@gmail.com |
f7ae0cdbd0fd937d5063a80f7b87bde802e37f21 | d0f03c9d8ae1d69ad7f3e6619e966ced8745e4ca | /TransferScript.h | 2d54e47536d3eb79bca82eea8fa0409045474ec5 | [] | no_license | dsanch1120/C403_Final | 97912ae48f2adca12f4b4d10e4ef3141d08a852f | 37a49f2e5568510ae865ec6847d2e8a620829695 | refs/heads/master | 2022-04-22T03:13:37.977291 | 2020-04-23T19:50:00 | 2020-04-23T19:50:00 | 257,123,877 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | h | //
// Created by Daniel Sanchez on 3/30/20.
//
#ifndef THEOFFICEDATA_TRANSFERSCRIPT_H
#define THEOFFICEDATA_TRANSFERSCRIPT_H
#include <string>
#include <vector>
class TransferScript {
public:
TransferScript();
void readData();
private:
void writeData();
void checkName();
std::vector<std::string> makeGoodName();
std::vector<std::string> makeBadName();
const std::string READ_FILE = "officeScript.csv";
const std::string WRITE_FILE = "officeData.sql";
std::vector<std::string> data;
};
#endif //THEOFFICEDATA_TRANSFERSCRIPT_H
| [
"sanchez@mymail.mines.edu"
] | sanchez@mymail.mines.edu |
86caf8d0e6107fb84d5a79467c94be51c827d117 | f108eb7eb9e261c608bda3d565a1302b7ebaaa9b | /src/include/reward_window.h | b942d757ba883c69ab5c9db7fc1221a4ddeb68f7 | [] | no_license | Florent-Bouisset/rogue_like | d5a2d7a3c810f29f9ff647270320946cbdea93f5 | 34a50fe0b0f9b93aff48c57d35a425d6eef61335 | refs/heads/master | 2022-06-20T06:54:45.727223 | 2020-05-06T20:39:08 | 2020-05-06T20:39:08 | 259,398,534 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 460 | h | #ifndef REWARD_WINDOW_H
#define REWARD_WINDOW_H
class Monster;
class Champion;
class Relic;
#include <QWidget>
#include <QPushButton>
#include <memory>
#include <QLabel>
class RewardWindow : public QWidget
{
public:
RewardWindow();
~RewardWindow();
QPushButton *nextLevel;
void setUp();
void loadMonsterRewards(std::shared_ptr<Monster> monster);
protected:
QLabel *title;
QLabel *goldReward;
QLabel *relicReward;
};
#endif | [
"florent.bouisset@gmail.com"
] | florent.bouisset@gmail.com |
1dc644fe5f11f228309a09e780712b782fde191a | 231db5b6d629d456fbf0bc8eaf35dda5336b1e71 | /tst/integration/InvocationTest.hpp | 235b643551b13bdf77822368af3d9909087370c4 | [] | no_license | HolySmoke86/blank | fc555ff0cbbb5b7ba2f77de5af79d5eef36607c6 | 28585b166ce3ad765ab613a375a97265449841e7 | refs/heads/master | 2020-12-24T16:24:00.119868 | 2018-11-17T12:10:22 | 2018-11-17T12:10:33 | 37,578,628 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 540 | hpp | #ifndef BLANK_TEST_INTEGRATION_INVOCATIONTEST_HPP_
#define BLANK_TEST_INTEGRATION_INVOCATIONTEST_HPP_
#include <cppunit/extensions/HelperMacros.h>
namespace blank {
namespace test {
class InvocationTest
: public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(InvocationTest);
CPPUNIT_TEST(testUnknownArg);
CPPUNIT_TEST(testIncompleteOption);
CPPUNIT_TEST(testMissingArgs);
CPPUNIT_TEST_SUITE_END();
public:
void setUp();
void tearDown();
void testUnknownArg();
void testIncompleteOption();
void testMissingArgs();
};
}
}
#endif
| [
"daniel.karbach@localhorst.tv"
] | daniel.karbach@localhorst.tv |
cdeae51b49896d39b95083353e56c02e7be4e627 | c774e5175433b3ae918a6ec9cef53b0ce3a94abd | /lib/Object/TapiFile.cpp | 4d9fe7d9e8ac1b313c58f1d2d5f13b7fcbe9c548 | [
"NCSA",
"LLVM-exception",
"Apache-2.0"
] | permissive | chisuhua/llvm | 5c23a69b3f2677c8d4983909d642f6d83c215aff | 3e4c29f4f7f8e78a961702c4e71ae5c9a515dd28 | refs/heads/master | 2020-05-19T05:53:24.760260 | 2020-03-08T07:46:39 | 2020-03-08T07:46:39 | 184,845,892 | 0 | 0 | Apache-2.0 | 2020-03-08T07:46:41 | 2019-05-04T03:01:42 | LLVM | UTF-8 | C++ | false | false | 3,620 | cpp | //===- TapiFile.cpp -------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the Text-based Dynamcic Library Stub format.
//
//===----------------------------------------------------------------------===//
#include "llvm/Object/TapiFile.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Object/Error.h"
#include "llvm/Support/MemoryBuffer.h"
using namespace llvm;
using namespace MachO;
using namespace object;
static constexpr StringLiteral ObjC1ClassNamePrefix = ".objc_class_name_";
static constexpr StringLiteral ObjC2ClassNamePrefix = "_OBJC_CLASS_$_";
static constexpr StringLiteral ObjC2MetaClassNamePrefix = "_OBJC_METACLASS_$_";
static constexpr StringLiteral ObjC2EHTypePrefix = "_OBJC_EHTYPE_$_";
static constexpr StringLiteral ObjC2IVarPrefix = "_OBJC_IVAR_$_";
static uint32_t getFlags(const Symbol *Sym) {
uint32_t Flags = BasicSymbolRef::SF_Global;
if (Sym->isUndefined())
Flags |= BasicSymbolRef::SF_Undefined;
else
Flags |= BasicSymbolRef::SF_Exported;
if (Sym->isWeakDefined() || Sym->isWeakReferenced())
Flags |= BasicSymbolRef::SF_Weak;
return Flags;
}
TapiFile::TapiFile(MemoryBufferRef Source, const InterfaceFile &interface,
Architecture Arch)
: SymbolicFile(ID_TapiFile, Source) {
for (const auto *Symbol : interface.symbols()) {
if (!Symbol->getArchitectures().has(Arch))
continue;
auto Platform = interface.getPlatform();
switch (Symbol->getKind()) {
case SymbolKind::GlobalSymbol:
Symbols.emplace_back(StringRef(), Symbol->getName(), getFlags(Symbol));
break;
case SymbolKind::ObjectiveCClass:
if (Platform == PlatformKind::macOS && Arch == AK_i386) {
Symbols.emplace_back(ObjC1ClassNamePrefix, Symbol->getName(),
getFlags(Symbol));
} else {
Symbols.emplace_back(ObjC2ClassNamePrefix, Symbol->getName(),
getFlags(Symbol));
Symbols.emplace_back(ObjC2MetaClassNamePrefix, Symbol->getName(),
getFlags(Symbol));
}
break;
case SymbolKind::ObjectiveCClassEHType:
Symbols.emplace_back(ObjC2EHTypePrefix, Symbol->getName(),
getFlags(Symbol));
break;
case SymbolKind::ObjectiveCInstanceVariable:
Symbols.emplace_back(ObjC2IVarPrefix, Symbol->getName(),
getFlags(Symbol));
break;
}
}
}
TapiFile::~TapiFile() = default;
void TapiFile::moveSymbolNext(DataRefImpl &DRI) const {
const auto *Sym = reinterpret_cast<const Symbol *>(DRI.p);
DRI.p = reinterpret_cast<uintptr_t>(++Sym);
}
Error TapiFile::printSymbolName(raw_ostream &OS, DataRefImpl DRI) const {
const auto *Sym = reinterpret_cast<const Symbol *>(DRI.p);
OS << Sym->Prefix << Sym->Name;
return Error::success();
}
uint32_t TapiFile::getSymbolFlags(DataRefImpl DRI) const {
const auto *Sym = reinterpret_cast<const Symbol *>(DRI.p);
return Sym->Flags;
}
basic_symbol_iterator TapiFile::symbol_begin() const {
DataRefImpl DRI;
DRI.p = reinterpret_cast<uintptr_t>(&*Symbols.begin());
return BasicSymbolRef{DRI, this};
}
basic_symbol_iterator TapiFile::symbol_end() const {
DataRefImpl DRI;
DRI.p = reinterpret_cast<uintptr_t>(&*Symbols.end());
return BasicSymbolRef{DRI, this};
}
| [
"noreply@github.com"
] | noreply@github.com |
e6576c198c8f6beb743341a17b61e5e18824b90d | 03c01f0a10c844c3432f499e59271e31898f3a3a | /Restoring Three Numbers.cpp | 829e393f0e8688abca243df9d60910623148e33d | [] | no_license | AmirFaruk75/Codeforces | ae2fba252a236be2baafe27d75008ecdb95febdb | 3a381547543a8fd557afaa68c4ed576bcb662906 | refs/heads/main | 2023-03-07T22:56:45.179559 | 2021-02-23T16:31:58 | 2021-02-23T16:31:58 | 341,608,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 608 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int a,b,c,x1,x2,x3,x4,i,j;
cin>>x1>>x2>>x3>>x4;
if(x1>x2 && x1>x3 && x1>x4)
{
c=x1-x2;
a=x3-c;
b=x4-c;
cout<<a<<" "<<b<<" "<<c;
}
else if(x2>x1 && x2>x3 && x2>x4)
{
c=x2-x1;
a=x3-c;
b=x4-c;
cout<<a<<" "<<b<<" "<<c;
}
else if(x3>x1 && x3>x2 && x3>x4)
{
c=x3-x1;
a=x2-c;
b=x4-c;
cout<<a<<" "<<b<<" "<<c;
}
else
{
c=x4-x1;
a=x2-c;
b=x3-c;
cout<<a<<" "<<b<<" "<<c;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
03d3b38f33a0e49148d3a61bc7a27621ff8576d5 | fbbe424559f64e9a94116a07eaaa555a01b0a7bb | /Tensorflow_OpenCV_Nightly/source/tensorflow/include/tensorflow/core/protobuf/device_properties.pb_text.h | d337c4bc36ec0b230d1d3806d40f204d3535e11a | [
"MIT"
] | permissive | ryfeus/lambda-packs | 6544adb4dec19b8e71d75c24d8ed789b785b0369 | cabf6e4f1970dc14302f87414f170de19944bac2 | refs/heads/master | 2022-12-07T16:18:52.475504 | 2022-11-29T13:35:35 | 2022-11-29T13:35:35 | 71,386,735 | 1,283 | 263 | MIT | 2022-11-26T05:02:14 | 2016-10-19T18:22:39 | Python | UTF-8 | C++ | false | false | 794 | h | // GENERATED FILE - DO NOT MODIFY
#ifndef tensorflow_core_protobuf_device_properties_proto_H_
#define tensorflow_core_protobuf_device_properties_proto_H_
#include "tensorflow/core/protobuf/device_properties.pb.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/types.h"
namespace tensorflow {
// Message-text conversion for tensorflow.DeviceProperties
string ProtoDebugString(
const ::tensorflow::DeviceProperties& msg);
string ProtoShortDebugString(
const ::tensorflow::DeviceProperties& msg);
bool ProtoParseFromString(
const string& s,
::tensorflow::DeviceProperties* msg)
TF_MUST_USE_RESULT;
} // namespace tensorflow
#endif // tensorflow_core_protobuf_device_properties_proto_H_
| [
"ryfeus@gmail.com"
] | ryfeus@gmail.com |
1ebba69decda35d644669411b1c31eb2c44a0c9d | 4aa16adcdc90775a27e8bc725eec401725e14646 | /Game.cpp | 50beaff02d908b1b86927da98c6db4cf77d44fa4 | [] | no_license | Tsutomu-dayoo/Game1 | d404d18b7eeb77f9b0f33dfb2ce61c84b40efe13 | 9904239411ddebf97130ab642a23462bc6d4f31e | refs/heads/master | 2020-04-21T03:10:03.396773 | 2019-03-23T13:14:37 | 2019-03-23T13:14:37 | 169,276,186 | 0 | 0 | null | 2019-03-23T13:04:32 | 2019-02-05T16:50:10 | C++ | UTF-8 | C++ | false | false | 7,606 | cpp | //
// Game.cpp
// Game1
//
// Created by 山口勉 on 2019/02/03.
// Copyright © 2019年 山口勉. All rights reserved.
//
#include "Game.h"
#include <iostream>
const int thickness = 15;
const float PaddleH = 100.0f;
const float windowW = 1024.0f;//ウィンドウの幅
const float windowH = 768.0f;//ウィンドウの高さ
Game::Game()//class内のprivateのメンバ関数の値や状態の記述
:mWindow(nullptr)
,mRenderer(nullptr)
,mTicksCount(0)
,mIsRunning(true)
,mPaddleDir(0)
,mPaddle2Dir(0)
{
}
bool Game::Initialize()
{
int sdlResult = SDL_Init(SDL_INIT_VIDEO);//SDLの初期化に成功なら0を返す。
if(sdlResult != 0)
{
printf("SDLの初期化に失敗");
SDL_Log("%s", SDL_GetError());//SDL_GetErrorでエラーメッセージをC言語のスタイルにする
return false;
}
mWindow = SDL_CreateWindow("Game Programming Sample1",//タイトル
100,//左上隅のx座標
100,//左上隅のy座標
static_cast<int>(windowW),//ウィンドウの幅
static_cast<int>(windowH),//ウィンドウの高さ
0 //フラグ
);
if(!mWindow)
{
printf("画面作成に失敗");
SDL_Log("%s",SDL_GetError());
return false;
}
mRenderer = SDL_CreateRenderer(mWindow,// mWindowに描画
-1,
SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC
);
//ゲームオブジェクトの初期位置
mPaddlePos.x = 10.0f;
mPaddlePos.y = windowH/2.0f;
mPaddle2Pos.x = windowW - 10.0f - thickness;
mPaddle2Pos.y = windowH/2.0f;
mBallPos.x = windowW/2.0f;
mBallPos.y = windowH/2.0f;
mBallVel.x = 200.0f;
mBallVel.y = -235.0f;
for(int i=0;i<2;i++)
{
//複数のボールを更新できるようにする→ランダム関数を用いて
}
return true;//上記が問題なければtrue
}
void Game::Shutdown()
{
SDL_DestroyWindow(mWindow);
SDL_DestroyRenderer(mRenderer);
SDL_Quit();
}
void Game::RunLoop()
{
while(mIsRunning){
ProcessInput();
UpdateGame();
GenerateOutput();
}
}
void Game::ProcessInput()
{
SDL_Event event;
while (SDL_PollEvent(&event))//キューにイベントがあればtrue 引数はSDL_Eventのポインタ
{
switch(event.type)
{
case SDL_QUIT:// バツボタンでウィンドウが消える
mIsRunning = false;
break;
}
}
const Uint8* state = SDL_GetKeyboardState(NULL);
if(state[SDL_SCANCODE_ESCAPE])
{
mIsRunning = false;// ESCでウィンドウが閉じる
}
mPaddleDir = 0;
if(state[SDL_SCANCODE_W])
{
mPaddleDir -= 1;
}
if(state[SDL_SCANCODE_S])
{
mPaddleDir += 1;
}
mPaddle2Dir = 0;
if(state[SDL_SCANCODE_O])
{
mPaddle2Dir -= 1;
}
if(state[SDL_SCANCODE_K])
{
mPaddle2Dir += 1;
}
}
void Game::UpdateGame()
{
//前回の更新から16ms待つようにする
while(!SDL_TICKS_PASSED(SDL_GetTicks(), mTicksCount+16));
// deltatime is the difference between last last frame and current frame
float deltatime = (SDL_GetTicks() - mTicksCount) / 1000.0f; //convert to secounds
mTicksCount = SDL_GetTicks();//update time
//デルタタイムが大きくなり過ぎないように最大値を設けて制限
if(deltatime > 0.05f)
{
deltatime = 0.05f;
}
// update game objects
if(mPaddleDir != 0)
{
mPaddlePos.y += mPaddleDir * 300.0f * deltatime;//方向*ピクセル数*デルタタイム
//パドルが画面外に行かないようにする
if(mPaddlePos.y < PaddleH/2.0f + thickness)
{
mPaddlePos.y = PaddleH/2.0f + thickness;
}
else if(mPaddlePos.y > windowH - PaddleH/2.0f - thickness)
{
mPaddlePos.y = windowH - PaddleH/2.0f - thickness;
}
}
if(mPaddle2Dir != 0)
{
mPaddle2Pos.y += mPaddle2Dir * 300.0f * deltatime;//方向*ピクセル数*デルタタイム
//パドルが画面外に行かないようにする
if(mPaddle2Pos.y < PaddleH/2.0f + thickness)
{
mPaddle2Pos.y = PaddleH/2.0f + thickness;
}
else if(mPaddle2Pos.y > windowH - PaddleH/2.0f - thickness)
{
mPaddle2Pos.y = windowH - PaddleH/2.0f - thickness;
}
}
//ボールの位置の更新
mBallPos.x += mBallVel.x * deltatime;
mBallPos.y += mBallVel.y * deltatime;
//ボールの接触判定
float diff = mPaddlePos.y - mBallPos.y;
diff = (diff<0.0f)? -diff : diff;
float diff2 = mPaddle2Pos.y - mBallPos.y;
diff2 = (diff2<0.0f)? -diff2 : diff2;
if(mBallPos.y <= thickness && mBallVel.y < 0.0f)//上の壁にボールが接触し、かつ速度が負方向の時に反転
{
mBallVel.y *= -1;
}
else if(mBallPos.y >= (windowH - thickness) && mBallVel.y > 0.0f)//下の壁にボールが接触し、かつ速度が負方向の時に反転
{
mBallVel.y *= -1;
}
/*
if(mBallPos.x >= (windowW - thickness) && mBallVel.x > 0.0f)//右の壁との接触判定
{
mBallVel.x *= -1;
}
*/
if(mBallVel.x < 0.0f && mBallPos.x >= 20.0f && mBallPos.x <= 25.0f && diff < PaddleH/2.0f)
{
mBallVel.x *= -1;
}
else if(mBallPos.x < 0.0f)
{
mIsRunning = false;
}
if(mBallVel.x > 0.0f && mBallPos.x >= mPaddle2Pos.x && mBallPos.x <= mPaddle2Pos.x + thickness && diff2 < PaddleH/2.0f)
{
mBallVel.x *= -1;
}
else if(mBallPos.x > windowW)
{
mIsRunning = false;
}
}
void Game::GenerateOutput()
{
SDL_SetRenderDrawColor(mRenderer,0,0,255,255);//R,G,B,alpha
SDL_RenderClear(mRenderer);// 現在の描画色でクリアする
SDL_SetRenderDrawColor(mRenderer, 255, 255, 255, 255);
SDL_Rect wall{//top wall
0,//x (左上隅)
0,//y (左上隅)
static_cast<int>(windowW),//幅
thickness//高さ
};
SDL_RenderFillRect(mRenderer, &wall);//Draw rectangle
wall.y = windowH-thickness;//bottom wall
SDL_RenderFillRect(mRenderer, &wall);
/*
wall.x = windowW - thickness;
wall.y = 0;
wall.w = thickness;
wall.h = windowW;
SDL_RenderFillRect(mRenderer, &wall);// Right wall
*/
SDL_Rect paddle{
static_cast<int>(mPaddlePos.x),
static_cast<int>(mPaddlePos.y - PaddleH/2.0f),
thickness,
static_cast<int>(PaddleH),
};
SDL_RenderFillRect(mRenderer, &paddle);
SDL_Rect paddle2{
static_cast<int>(mPaddle2Pos.x),
static_cast<int>(mPaddle2Pos.y - PaddleH/2.0f),
thickness,
static_cast<int>(PaddleH),
};
SDL_RenderFillRect(mRenderer, &paddle2);
SDL_Rect ball{//Draw ball
static_cast<int>(mBallPos.x - thickness/2),
static_cast<int>(mBallPos.y - thickness/2),//static_cast -> floatをintに変換する
thickness,
thickness
};
SDL_RenderFillRect(mRenderer, &ball);
SDL_RenderPresent(mRenderer);//フロントバッファとバックバッファを入れ替える 必ず描画したいものを上にmRendererに描画し終える
}
| [
"t.yamaguchi.air@outlook.jp"
] | t.yamaguchi.air@outlook.jp |
d4b628be14ca1e94682bb9993cc017f2673eacea | 8e52ec9430cb86f23982e012cb29d5e52e6c1d13 | /MFC_readFile/MFC_readFile/stdafx.cpp | 28013f5f0b1465ccb8286211afd3dc93b094d272 | [] | no_license | Gewin/MFC_File | d8666ae2dba5d60b582889a9db35f7511349662e | b2f7e3bd2240755d8bfdb3376770367adfedade8 | refs/heads/master | 2021-01-23T06:50:23.537054 | 2014-03-27T05:31:39 | 2014-03-27T05:31:39 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 166 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// MFC_readFile.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
| [
"ljwlh54@163.com"
] | ljwlh54@163.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.