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
afe1c9ad7dc54b17ad6ec0344f4577789c8950cc
f77f105963cd6447d0f392b9ee7d923315a82ac6
/Box2DandOgre/source/HoltStateInAir.cpp
19ac8236965d16cface25aab4032e4e583b70fde
[]
no_license
GKimGames/parkerandholt
8bb2b481aff14cf70a7a769974bc2bb683d74783
544f7afa462c5a25c044445ca9ead49244c95d3c
refs/heads/master
2016-08-07T21:03:32.167272
2010-08-26T03:01:35
2010-08-26T03:01:35
32,834,451
0
0
null
null
null
null
UTF-8
C++
false
false
5,707
cpp
/*============================================================================= HoltStateInAir.cpp State for Holt on the ground. =============================================================================*/ #include "HoltStateInAir.h" #include "HoltStateOnGround.h" #include "Holt.h" #include "Message.h" #include "TinyXMLHelper.h" #include "XMLQuickVars.h" //============================================================================= // Constructor // HoltStateInAir::HoltStateInAir( CharacterHolt* holt, FSMStateMachine<CharacterHolt>* stateMachine): HoltState(holt,stateMachine) { direction_ = Ogre::Vector3(0,0,1); } //============================================================================= // Enter // void HoltStateInAir::Enter() { if(driver_->onGroundState_->isJumping_) { jumpTimer_ = 0.0; } if(driver_->onGroundState_->isJumping_) { driver_->animationBlender_->Blend("jump_idle", AnimationBlender::BlendThenAnimate, 1.0, true); } else { driver_->animationBlender_->Blend("jump_idle", AnimationBlender::BlendWhileAnimating, 0.3, true); } wallJumpedLeft_ = false; justWallJumped_ = false; wallJumpTimer_ = -1.0; wallJumpBetweenTimer_ = -1.0; mySwitch = true; } //============================================================================= // Update // bool HoltStateInAir::Update() { double timeSinceLastFrame = GAMEFRAMEWORK->GetTimeSinceLastFrame(); if(driver_->moveLeft_) { MoveLeft(); } if(driver_->moveRight_) { MoveRight(); } if(driver_->jump_) { Jump(); } if(jumpTimer_ != -1.0) { jumpTimer_ += timeSinceLastFrame; } if(driver_->feetSensorHit_ == true) { stateMachine_->ChangeState(driver_->onGroundState_); } else { UpdateAnimation(); if(driver_->debugDrawOn_) { driver_->UpdateDebugDraw(); } } // We've successfully updated. return true; } //============================================================================= // HandleMessage // bool HoltStateInAir::HandleMessage(const KGBMessage message) { if(driver_->active_) { switch(message.messageType) { case CHARACTER_MOVE_LEFT_PLUS: { driver_->moveLeft_ = true; return true; } case CHARACTER_MOVE_RIGHT_PLUS: { driver_->moveRight_ = true; return true; } case CHARACTER_JUMP_PLUS: { driver_->jump_ = true; return true; } case CHARACTER_MOVE_LEFT_MINUS: { driver_->moveLeft_ = false; return true; } case CHARACTER_MOVE_RIGHT_MINUS: { driver_->moveRight_ = false; return true; } case CHARACTER_JUMP_MINUS: { driver_->jump_ = false; return true; } } } return false; } //============================================================================= // Exit // void HoltStateInAir::Exit() { } //============================================================================= // BeginContact // /// Called when two fixtures begin to touch. void HoltStateInAir::BeginContact(ContactPoint* contact, b2Fixture* contactFixture, b2Fixture* collidedFixture) { if(!collidedFixture->IsSensor()) { if(contactFixture == driver_->feetSensor_) { stateMachine_->ChangeState(driver_->onGroundState_); driver_->BeginContact(contact,contactFixture,collidedFixture); } } } //============================================================================= // EndContact // /// Called when two fixtures cease to touch. void HoltStateInAir::EndContact(ContactPoint* contact, b2Fixture* contactFixture, b2Fixture* collidedFixture) { } //============================================================================= // MoveLeft // /// void HoltStateInAir::MoveLeft() { double timeSinceLastFrame = GameFramework::getSingletonPtr()->GetTimeSinceLastFrame(); if(driver_->body_->GetLinearVelocity().x > -driver_->maximumAirVelocity_) { driver_->body_->ApplyForce(b2Vec2(-driver_->airForce_ * timeSinceLastFrame,0), driver_->body_->GetPosition()); } } //============================================================================= // MoveRight // /// void HoltStateInAir::MoveRight() { double timeSinceLastFrame = GameFramework::getSingletonPtr()->GetTimeSinceLastFrame(); if(driver_->body_->GetLinearVelocity().x < driver_->maximumAirVelocity_) { driver_->body_->ApplyForce(b2Vec2(driver_->airForce_ * timeSinceLastFrame,0), driver_->body_->GetPosition()); } } //============================================================================= // Jump /// /// Calling jump while the character is in the air will add slightly more /// height to the jump. void HoltStateInAir::Jump() { if(jumpTimer_ > 0.5) { jumpTimer_ = -1.0; } else if(jumpTimer_ != -1.0) { b2Vec2 force(b2Vec2(0, (driver_->jumpingAfterForce_ * ((0.5*2) - jumpTimer_)) * GAMEFRAMEWORK->GetTimeSinceLastFrame())); driver_->body_->ApplyImpulse(force, driver_->body_->GetPosition()); } double timeLeft = (driver_->animationState_->getLength() - driver_->animationState_->getTimePosition()) / driver_->animationState_->getLength(); //driver_->body_->ApplyForce(b2Vec2(0,driver_->jumpingAfterForce_ * timeLeft), driver_->body_->GetPosition()); } //============================================================================= // UpdateAnimation void HoltStateInAir::UpdateAnimation() { double timeSinceLastFrame = GAMEFRAMEWORK->GetTimeSinceLastFrame(); driver_->animationBlender_->AddTime(timeSinceLastFrame); }
[ "Kaziks@34afb35a-be5b-11de-bb5c-85734917f5ce" ]
Kaziks@34afb35a-be5b-11de-bb5c-85734917f5ce
e1fe29d79ea1036127962c195abe3d8c3d6e80d9
280e2ca15259066633a39ed20b04d0f70e21a96e
/external/pysoundtouch14/libsoundtouch/RateTransposer.cpp
26fa50c70bea54481b05d48af9c9e4f44585e50b
[]
no_license
psobot/remix
fb0525519975a2d0f9e36a6ff6278fbbbcc66042
2de483fd08c2760323b5abd82f695467d4f4d8a0
refs/heads/master
2021-01-18T02:59:12.247861
2013-01-15T06:58:00
2013-01-15T06:58:00
2,263,107
2
1
null
null
null
null
UTF-8
C++
false
false
18,059
cpp
//////////////////////////////////////////////////////////////////////////////// /// /// Sample rate transposer. Changes sample rate by using linear interpolation /// together with anti-alias filtering (first order interpolation with anti- /// alias filtering should be quite adequate for this application) /// /// Author : Copyright (c) Olli Parviainen /// Author e-mail : oparviai 'at' iki.fi /// SoundTouch WWW: http://www.surina.net/soundtouch /// //////////////////////////////////////////////////////////////////////////////// // // Last changed : $Date: 2009-01-11 13:34:24 +0200 (Sun, 11 Jan 2009) $ // File revision : $Revision: 4 $ // // $Id: RateTransposer.cpp 45 2009-01-11 11:34:24Z oparviai $ // //////////////////////////////////////////////////////////////////////////////// // // License : // // SoundTouch audio processing library // Copyright (c) Olli Parviainen // // 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 // //////////////////////////////////////////////////////////////////////////////// #include <memory.h> #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <stdexcept> #include "RateTransposer.h" #include "AAFilter.h" using namespace std; using namespace soundtouch; /// A linear samplerate transposer class that uses integer arithmetics. /// for the transposing. class RateTransposerInteger : public RateTransposer { protected: int iSlopeCount; int iRate; SAMPLETYPE sPrevSampleL, sPrevSampleR; virtual void resetRegisters(); virtual uint transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint numSamples); virtual uint transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint numSamples); public: RateTransposerInteger(); virtual ~RateTransposerInteger(); /// Sets new target rate. Normal rate = 1.0, smaller values represent slower /// rate, larger faster rates. virtual void setRate(float newRate); }; /// A linear samplerate transposer class that uses floating point arithmetics /// for the transposing. class RateTransposerFloat : public RateTransposer { protected: float fSlopeCount; SAMPLETYPE sPrevSampleL, sPrevSampleR; virtual void resetRegisters(); virtual uint transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint numSamples); virtual uint transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint numSamples); public: RateTransposerFloat(); virtual ~RateTransposerFloat(); }; // Operator 'new' is overloaded so that it automatically creates a suitable instance // depending on if we've a MMX/SSE/etc-capable CPU available or not. void * RateTransposer::operator new(size_t s) { throw runtime_error("Error in RateTransoser::new: don't use \"new TDStretch\" directly, use \"newInstance\" to create a new instance instead!"); return NULL; } RateTransposer *RateTransposer::newInstance() { #ifdef INTEGER_SAMPLES return ::new RateTransposerInteger; #else return ::new RateTransposerFloat; #endif } // Constructor RateTransposer::RateTransposer() : FIFOProcessor(&outputBuffer) { numChannels = 2; bUseAAFilter = TRUE; fRate = 0; // Instantiates the anti-alias filter with default tap length // of 32 pAAFilter = new AAFilter(32); } RateTransposer::~RateTransposer() { delete pAAFilter; } /// Enables/disables the anti-alias filter. Zero to disable, nonzero to enable void RateTransposer::enableAAFilter(BOOL newMode) { bUseAAFilter = newMode; } /// Returns nonzero if anti-alias filter is enabled. BOOL RateTransposer::isAAFilterEnabled() const { return bUseAAFilter; } AAFilter *RateTransposer::getAAFilter() const { return pAAFilter; } // Sets new target iRate. Normal iRate = 1.0, smaller values represent slower // iRate, larger faster iRates. void RateTransposer::setRate(float newRate) { double fCutoff; fRate = newRate; // design a new anti-alias filter if (newRate > 1.0f) { fCutoff = 0.5f / newRate; } else { fCutoff = 0.5f * newRate; } pAAFilter->setCutoffFreq(fCutoff); } // Outputs as many samples of the 'outputBuffer' as possible, and if there's // any room left, outputs also as many of the incoming samples as possible. // The goal is to drive the outputBuffer empty. // // It's allowed for 'output' and 'input' parameters to point to the same // memory position. /* void RateTransposer::flushStoreBuffer() { if (storeBuffer.isEmpty()) return; outputBuffer.moveSamples(storeBuffer); } */ // Adds 'nSamples' pcs of samples from the 'samples' memory position into // the input of the object. void RateTransposer::putSamples(const SAMPLETYPE *samples, uint nSamples) { processSamples(samples, nSamples); } // Transposes up the sample rate, causing the observed playback 'rate' of the // sound to decrease void RateTransposer::upsample(const SAMPLETYPE *src, uint nSamples) { uint count, sizeTemp, num; // If the parameter 'uRate' value is smaller than 'SCALE', first transpose // the samples and then apply the anti-alias filter to remove aliasing. // First check that there's enough room in 'storeBuffer' // (+16 is to reserve some slack in the destination buffer) sizeTemp = (uint)((float)nSamples / fRate + 16.0f); // Transpose the samples, store the result into the end of "storeBuffer" count = transpose(storeBuffer.ptrEnd(sizeTemp), src, nSamples); storeBuffer.putSamples(count); // Apply the anti-alias filter to samples in "store output", output the // result to "dest" num = storeBuffer.numSamples(); count = pAAFilter->evaluate(outputBuffer.ptrEnd(num), storeBuffer.ptrBegin(), num, (uint)numChannels); outputBuffer.putSamples(count); // Remove the processed samples from "storeBuffer" storeBuffer.receiveSamples(count); } // Transposes down the sample rate, causing the observed playback 'rate' of the // sound to increase void RateTransposer::downsample(const SAMPLETYPE *src, uint nSamples) { uint count, sizeTemp; // If the parameter 'uRate' value is larger than 'SCALE', first apply the // anti-alias filter to remove high frequencies (prevent them from folding // over the lover frequencies), then transpose. */ // Add the new samples to the end of the storeBuffer */ storeBuffer.putSamples(src, nSamples); // Anti-alias filter the samples to prevent folding and output the filtered // data to tempBuffer. Note : because of the FIR filter length, the // filtering routine takes in 'filter_length' more samples than it outputs. assert(tempBuffer.isEmpty()); sizeTemp = storeBuffer.numSamples(); count = pAAFilter->evaluate(tempBuffer.ptrEnd(sizeTemp), storeBuffer.ptrBegin(), sizeTemp, (uint)numChannels); // Remove the filtered samples from 'storeBuffer' storeBuffer.receiveSamples(count); // Transpose the samples (+16 is to reserve some slack in the destination buffer) sizeTemp = (uint)((float)nSamples / fRate + 16.0f); count = transpose(outputBuffer.ptrEnd(sizeTemp), tempBuffer.ptrBegin(), count); outputBuffer.putSamples(count); } // Transposes sample rate by applying anti-alias filter to prevent folding. // Returns amount of samples returned in the "dest" buffer. // The maximum amount of samples that can be returned at a time is set by // the 'set_returnBuffer_size' function. void RateTransposer::processSamples(const SAMPLETYPE *src, uint nSamples) { uint count; uint sizeReq; if (nSamples == 0) return; assert(pAAFilter); // If anti-alias filter is turned off, simply transpose without applying // the filter if (bUseAAFilter == FALSE) { sizeReq = (uint)((float)nSamples / fRate + 1.0f); count = transpose(outputBuffer.ptrEnd(sizeReq), src, nSamples); outputBuffer.putSamples(count); return; } // Transpose with anti-alias filter if (fRate < 1.0f) { upsample(src, nSamples); } else { downsample(src, nSamples); } } // Transposes the sample rate of the given samples using linear interpolation. // Returns the number of samples returned in the "dest" buffer inline uint RateTransposer::transpose(SAMPLETYPE *dest, const SAMPLETYPE *src, uint nSamples) { if (numChannels == 2) { return transposeStereo(dest, src, nSamples); } else { return transposeMono(dest, src, nSamples); } } // Sets the number of channels, 1 = mono, 2 = stereo void RateTransposer::setChannels(int nChannels) { assert(nChannels > 0); if (numChannels == nChannels) return; assert(nChannels == 1 || nChannels == 2); numChannels = nChannels; storeBuffer.setChannels(numChannels); tempBuffer.setChannels(numChannels); outputBuffer.setChannels(numChannels); // Inits the linear interpolation registers resetRegisters(); } // Clears all the samples in the object void RateTransposer::clear() { outputBuffer.clear(); storeBuffer.clear(); } // Returns nonzero if there aren't any samples available for outputting. int RateTransposer::isEmpty() const { int res; res = FIFOProcessor::isEmpty(); if (res == 0) return 0; return storeBuffer.isEmpty(); } ////////////////////////////////////////////////////////////////////////////// // // RateTransposerInteger - integer arithmetic implementation // /// fixed-point interpolation routine precision #define SCALE 65536 // Constructor RateTransposerInteger::RateTransposerInteger() : RateTransposer() { // Notice: use local function calling syntax for sake of clarity, // to indicate the fact that C++ constructor can't call virtual functions. RateTransposerInteger::resetRegisters(); RateTransposerInteger::setRate(1.0f); } RateTransposerInteger::~RateTransposerInteger() { } void RateTransposerInteger::resetRegisters() { iSlopeCount = 0; sPrevSampleL = sPrevSampleR = 0; } // Transposes the sample rate of the given samples using linear interpolation. // 'Mono' version of the routine. Returns the number of samples returned in // the "dest" buffer uint RateTransposerInteger::transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint nSamples) { unsigned int i, used; LONG_SAMPLETYPE temp, vol1; used = 0; i = 0; // Process the last sample saved from the previous call first... while (iSlopeCount <= SCALE) { vol1 = (LONG_SAMPLETYPE)(SCALE - iSlopeCount); temp = vol1 * sPrevSampleL + iSlopeCount * src[0]; dest[i] = (SAMPLETYPE)(temp / SCALE); i++; iSlopeCount += iRate; } // now always (iSlopeCount > SCALE) iSlopeCount -= SCALE; while (1) { while (iSlopeCount > SCALE) { iSlopeCount -= SCALE; used ++; if (used >= nSamples - 1) goto end; } vol1 = (LONG_SAMPLETYPE)(SCALE - iSlopeCount); temp = src[used] * vol1 + iSlopeCount * src[used + 1]; dest[i] = (SAMPLETYPE)(temp / SCALE); i++; iSlopeCount += iRate; } end: // Store the last sample for the next round sPrevSampleL = src[nSamples - 1]; return i; } // Transposes the sample rate of the given samples using linear interpolation. // 'Stereo' version of the routine. Returns the number of samples returned in // the "dest" buffer uint RateTransposerInteger::transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint nSamples) { unsigned int srcPos, i, used; LONG_SAMPLETYPE temp, vol1; if (nSamples == 0) return 0; // no samples, no work used = 0; i = 0; // Process the last sample saved from the sPrevSampleLious call first... while (iSlopeCount <= SCALE) { vol1 = (LONG_SAMPLETYPE)(SCALE - iSlopeCount); temp = vol1 * sPrevSampleL + iSlopeCount * src[0]; dest[2 * i] = (SAMPLETYPE)(temp / SCALE); temp = vol1 * sPrevSampleR + iSlopeCount * src[1]; dest[2 * i + 1] = (SAMPLETYPE)(temp / SCALE); i++; iSlopeCount += iRate; } // now always (iSlopeCount > SCALE) iSlopeCount -= SCALE; while (1) { while (iSlopeCount > SCALE) { iSlopeCount -= SCALE; used ++; if (used >= nSamples - 1) goto end; } srcPos = 2 * used; vol1 = (LONG_SAMPLETYPE)(SCALE - iSlopeCount); temp = src[srcPos] * vol1 + iSlopeCount * src[srcPos + 2]; dest[2 * i] = (SAMPLETYPE)(temp / SCALE); temp = src[srcPos + 1] * vol1 + iSlopeCount * src[srcPos + 3]; dest[2 * i + 1] = (SAMPLETYPE)(temp / SCALE); i++; iSlopeCount += iRate; } end: // Store the last sample for the next round sPrevSampleL = src[2 * nSamples - 2]; sPrevSampleR = src[2 * nSamples - 1]; return i; } // Sets new target iRate. Normal iRate = 1.0, smaller values represent slower // iRate, larger faster iRates. void RateTransposerInteger::setRate(float newRate) { iRate = (int)(newRate * SCALE + 0.5f); RateTransposer::setRate(newRate); } ////////////////////////////////////////////////////////////////////////////// // // RateTransposerFloat - floating point arithmetic implementation // ////////////////////////////////////////////////////////////////////////////// // Constructor RateTransposerFloat::RateTransposerFloat() : RateTransposer() { // Notice: use local function calling syntax for sake of clarity, // to indicate the fact that C++ constructor can't call virtual functions. RateTransposerFloat::resetRegisters(); RateTransposerFloat::setRate(1.0f); } RateTransposerFloat::~RateTransposerFloat() { } void RateTransposerFloat::resetRegisters() { fSlopeCount = 0; sPrevSampleL = sPrevSampleR = 0; } // Transposes the sample rate of the given samples using linear interpolation. // 'Mono' version of the routine. Returns the number of samples returned in // the "dest" buffer uint RateTransposerFloat::transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint nSamples) { unsigned int i, used; used = 0; i = 0; // Process the last sample saved from the previous call first... while (fSlopeCount <= 1.0f ) { dest[i] = (SAMPLETYPE)((1.0f - fSlopeCount) * sPrevSampleL + fSlopeCount * src[0]); i++; fSlopeCount += fRate; } fSlopeCount -= 1.0f; if (nSamples == 1) goto end; while (1) { while (fSlopeCount > 1.0f) { fSlopeCount -= 1.0f; used ++; if (used >= nSamples - 1) goto end; } //if(i>= nSamples -1) goto end; dest[i] = (SAMPLETYPE)((1.0f - fSlopeCount) * src[used] + fSlopeCount * src[used + 1]); i++; fSlopeCount += fRate; } end: // Store the last sample for the next round sPrevSampleL = src[nSamples - 1]; return i; } // Transposes the sample rate of the given samples using linear interpolation. // 'Mono' version of the routine. Returns the number of samples returned in // the "dest" buffer uint RateTransposerFloat::transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint nSamples) { unsigned int srcPos, i, used; if (nSamples == 0) return 0; // no samples, no work used = 0; i = 0; // Process the last sample saved from the sPrevSampleLious call first... while (fSlopeCount <= 1.0f) { dest[2 * i] = (SAMPLETYPE)((1.0f - fSlopeCount) * sPrevSampleL + fSlopeCount * src[0]); dest[2 * i + 1] = (SAMPLETYPE)((1.0f - fSlopeCount) * sPrevSampleR + fSlopeCount * src[1]); i++; fSlopeCount += fRate; } // now always (iSlopeCount > 1.0f) fSlopeCount -= 1.0f; if (nSamples == 1) goto end; while (1) { while (fSlopeCount > 1.0f) { fSlopeCount -= 1.0f; used ++; if (used >= nSamples - 1) goto end; } srcPos = 2 * used; dest[2 * i] = (SAMPLETYPE)((1.0f - fSlopeCount) * src[srcPos] + fSlopeCount * src[srcPos + 2]); dest[2 * i + 1] = (SAMPLETYPE)((1.0f - fSlopeCount) * src[srcPos + 1] + fSlopeCount * src[srcPos + 3]); i++; fSlopeCount += fRate; } end: // Store the last sample for the next round sPrevSampleL = src[2 * nSamples - 2]; sPrevSampleR = src[2 * nSamples - 1]; return i; }
7bc7a3d423f950632cc0ac7cd33948c6960235dc
0460cb3ce6febc094baa7a4cafb81e8b4eb2c27a
/dependencies/czPlatform/source/czPlatform/czSharedFlag.h
b3f20d37a4f9376676c466c7637d4bd0eb7f0ee5
[]
no_license
funZX/nutcracker
1cf029ac907c7fc20fc7fa11a1740f075ec92ce0
d8e4c4e6556ef0634b3fd98b6a714005f0ff53b6
refs/heads/master
2020-05-30T15:52:27.087863
2019-06-02T16:36:24
2019-06-02T16:36:24
189,830,679
2
0
null
2019-06-02T10:02:37
2019-06-02T10:02:36
null
UTF-8
C++
false
false
1,362
h
/******************************************************************** CrazyGaze (http://www.crazygaze.com) Author : Rui Figueira Email : [email protected] purpose: *********************************************************************/ #pragma once #include <memory> namespace cz { class SharedFlag { public: bool isValid() const; protected: friend class SharedFlagOwner; std::shared_ptr<bool> m_flag; }; class SharedFlagOwner { public: SharedFlagOwner(); ~SharedFlagOwner(); /*! * Copy constructor and assignment operator don't really copy anything from "other". * They create their own flag. This is so that objects that have an instance of SharedFlagOwner * can be copied around, creating their own independent SharedFlagOwner instance */ SharedFlagOwner(const SharedFlagOwner& other); SharedFlagOwner& operator=(const SharedFlagOwner& other); /** * This should only be used internally */ SharedFlag _getFlag(); /** * Normally, the flag is set to false automatically in the destructor, but in * some situations, an explicit set my be desirable, instead of waiting for the object to go out * of scope. This method allows for that explicit operatio. */ void explicitSet(); private: SharedFlag m_flag; }; } // namespace cz
e7f9e6676556f9b837c79c57e7bf74da79cf200c
0ed6208e908df7259f058b1944ea439675cb876e
/staffGovSystem/source/manager.cpp
e03f378c84956b0673ce6b0226efdbf98345c124
[]
no_license
kuntung/cppStudy
01d884399500831cbde09c26d7ee0a1977f93e42
e84de98cea85fc8235de681c64479fa8bc936ff5
refs/heads/main
2023-02-18T17:22:25.868879
2021-01-22T12:23:06
2021-01-22T12:23:06
297,596,228
1
0
null
2020-10-05T09:33:05
2020-09-22T09:14:28
Jupyter Notebook
GB18030
C++
false
false
622
cpp
// // Created by tangkun on 2020/12/26. // #include "header/manager.h" void Manager::show_info() { cout<<"职工编号为:"<<this->m_id <<"\t职工姓名:"<<this->m_name <<"\t岗位:"<<this->get_deptName() <<"\t岗位职责:"<<this->get_workType()<<endl; } Manager::Manager(int id, string name, int dId) { this->m_id = id; this->m_name = name; this->m_DeptId = dId; } string Manager::get_deptName() { return string("经理"); //返回部门岗位名称 } string Manager::get_workType() { return string("完成老板下发的任务,派发任务给普通员工"); }
f124ad71b16a67a3523f8a1eca12b2414d58479e
9cefd684e459400b4bae450d7502443f68c48338
/character.h
be19dc8931b0bdf5b9b53df52982cc06ea4ffe7a
[]
no_license
ashmit-khadka/Game-Engine-Arrow-Shooter-Cpp-OpenGL-
38fc8edcbeb2a287b09eb2f90881cc9907428520
63b4d17e4f82232e8418ff1f5ae24b9cd3772aea
refs/heads/master
2023-01-03T20:33:10.771026
2020-11-04T22:36:29
2020-11-04T22:36:29
310,125,087
0
0
null
null
null
null
UTF-8
C++
false
false
505
h
#pragma once #include "texture.h" class Character { public: enum Sprite { left, right, jump, fall }; GLfloat posX; GLfloat posY; int size; int health; int movementSpeed; GLfloat velocity; bool dead, gravityActive = false; int deathAnimation; GLfloat getPosX() { return posX; } GLfloat getPosY() { return posY; } int getSize() { return size; } bool isDead() { return dead; } void setPosition(GLfloat posX, GLfloat posY) { this->posX = posX; this->posY = posY; } };
0f5e4022cb02f98795d17a17e52bbfe268748e60
908b105f8ed1c55e7e55c75eaeac58e7fc012122
/显示左键按下和抬起/显示左键按下和抬起/显示左键按下和抬起Doc.cpp
a5de876bc66bffe10c66e50c0e4e2e5c430ad0fa
[]
no_license
GXNU-luofeng/MFC
26dcd4fa034e5f14d78d9cb594aa08a0ed667dec
8e0cdfe5be45717b9d8be66794419ff53fecd8eb
refs/heads/master
2021-05-16T21:13:15.628336
2020-06-12T10:56:08
2020-06-12T10:56:08
250,469,113
0
0
null
null
null
null
GB18030
C++
false
false
2,991
cpp
// 显示左键按下和抬起Doc.cpp : C显示左键按下和抬起Doc 类的实现 // #include "stdafx.h" // SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的 // ATL 项目中进行定义,并允许与该项目共享文档代码。 #ifndef SHARED_HANDLERS #include "显示左键按下和抬起.h" #endif #include "显示左键按下和抬起Doc.h" #include <propkey.h> #ifdef _DEBUG #define new DEBUG_NEW #endif // C显示左键按下和抬起Doc IMPLEMENT_DYNCREATE(C显示左键按下和抬起Doc, CDocument) BEGIN_MESSAGE_MAP(C显示左键按下和抬起Doc, CDocument) END_MESSAGE_MAP() // C显示左键按下和抬起Doc 构造/析构 C显示左键按下和抬起Doc::C显示左键按下和抬起Doc() { // TODO: 在此添加一次性构造代码 } C显示左键按下和抬起Doc::~C显示左键按下和抬起Doc() { } BOOL C显示左键按下和抬起Doc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: 在此添加重新初始化代码 // (SDI 文档将重用该文档) return TRUE; } // C显示左键按下和抬起Doc 序列化 void C显示左键按下和抬起Doc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: 在此添加存储代码 } else { // TODO: 在此添加加载代码 } } #ifdef SHARED_HANDLERS // 缩略图的支持 void C显示左键按下和抬起Doc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds) { // 修改此代码以绘制文档数据 dc.FillSolidRect(lprcBounds, RGB(255, 255, 255)); CString strText = _T("TODO: implement thumbnail drawing here"); LOGFONT lf; CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT)); pDefaultGUIFont->GetLogFont(&lf); lf.lfHeight = 36; CFont fontDraw; fontDraw.CreateFontIndirect(&lf); CFont* pOldFont = dc.SelectObject(&fontDraw); dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK); dc.SelectObject(pOldFont); } // 搜索处理程序的支持 void C显示左键按下和抬起Doc::InitializeSearchContent() { CString strSearchContent; // 从文档数据设置搜索内容。 // 内容部分应由“;”分隔 // 例如: strSearchContent = _T("point;rectangle;circle;ole object;"); SetSearchContent(strSearchContent); } void C显示左键按下和抬起Doc::SetSearchContent(const CString& value) { if (value.IsEmpty()) { RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid); } else { CMFCFilterChunkValueImpl *pChunk = NULL; ATLTRY(pChunk = new CMFCFilterChunkValueImpl); if (pChunk != NULL) { pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT); SetChunkValue(pChunk); } } } #endif // SHARED_HANDLERS // C显示左键按下和抬起Doc 诊断 #ifdef _DEBUG void C显示左键按下和抬起Doc::AssertValid() const { CDocument::AssertValid(); } void C显示左键按下和抬起Doc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // C显示左键按下和抬起Doc 命令
a98b6db648e27250edcd124d9548371ac76559f8
3651c7cf09fb909ee5801dd86db89e6cc46843e9
/mbed-os/features/cellular/framework/AT/AT_CellularStack.cpp
a1410fd02779f7ef9f308fd0907865d37f6b8f34
[ "Apache-2.0", "BSD-3-Clause", "MIT", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
bigw00d/mbed-ps2-controller-host
cef63076a1d5339e18f8a850c1ff1d5ddc9ada11
6d67bdf25603cb3e59047fb600ffe1fc44f56a17
refs/heads/master
2021-08-26T05:59:34.401405
2020-04-07T13:04:51
2020-04-07T13:04:51
253,772,376
0
0
Apache-2.0
2021-08-09T20:52:44
2020-04-07T11:24:26
C
UTF-8
C++
false
false
11,507
cpp
/* * Copyright (c) 2017, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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 "AT_CellularStack.h" #include "CellularUtil.h" #include "CellularLog.h" #include "ThisThread.h" using namespace mbed_cellular_util; using namespace mbed; AT_CellularStack::AT_CellularStack(ATHandler &at, int cid, nsapi_ip_stack_t stack_type) : AT_CellularBase(at), _socket(NULL), _socket_count(0), _cid(cid), _stack_type(stack_type), _ip_ver_sendto(NSAPI_UNSPEC) { memset(_ip, 0, PDP_IPV6_SIZE); } AT_CellularStack::~AT_CellularStack() { for (int i = 0; i < _socket_count; i++) { if (_socket[i]) { delete _socket[i]; _socket[i] = NULL; } } _socket_count = 0; delete [] _socket; _socket = NULL; } int AT_CellularStack::find_socket_index(nsapi_socket_t handle) { int max_socket_count = get_max_socket_count(); for (int i = 0; i < max_socket_count; i++) { if (_socket[i] == handle) { return i; } } return -1; } /** NetworkStack */ const char *AT_CellularStack::get_ip_address() { _at.lock(); bool ipv4 = false, ipv6 = false; _at.cmd_start_stop("+CGPADDR", "=", "%d", _cid); _at.resp_start("+CGPADDR:"); if (_at.info_resp()) { _at.skip_param(); if (_at.read_string(_ip, PDP_IPV6_SIZE) != -1) { convert_ipv6(_ip); SocketAddress address; address.set_ip_address(_ip); ipv4 = (address.get_ip_version() == NSAPI_IPv4); ipv6 = (address.get_ip_version() == NSAPI_IPv6); // Try to look for second address ONLY if modem has support for dual stack(can handle both IPv4 and IPv6 simultaneously). // Otherwise assumption is that second address is not reliable, even if network provides one. if ((get_property(PROPERTY_IPV4V6_PDP_TYPE) && (_at.read_string(_ip, PDP_IPV6_SIZE) != -1))) { convert_ipv6(_ip); address.set_ip_address(_ip); ipv6 = (address.get_ip_version() == NSAPI_IPv6); } } } _at.resp_stop(); _at.unlock(); if (ipv4 && ipv6) { _stack_type = IPV4V6_STACK; } else if (ipv4) { _stack_type = IPV4_STACK; } else if (ipv6) { _stack_type = IPV6_STACK; } return (ipv4 || ipv6) ? _ip : NULL; } void AT_CellularStack::set_cid(int cid) { _cid = cid; } nsapi_error_t AT_CellularStack::socket_stack_init() { return NSAPI_ERROR_OK; } nsapi_error_t AT_CellularStack::socket_open(nsapi_socket_t *handle, nsapi_protocol_t proto) { if (!is_protocol_supported(proto) || !handle) { return NSAPI_ERROR_UNSUPPORTED; } int max_socket_count = get_max_socket_count(); _socket_mutex.lock(); if (!_socket) { if (socket_stack_init() != NSAPI_ERROR_OK) { _socket_mutex.unlock(); return NSAPI_ERROR_NO_SOCKET; } _socket = new CellularSocket*[max_socket_count]; _socket_count = max_socket_count; for (int i = 0; i < max_socket_count; i++) { _socket[i] = 0; } } int index = find_socket_index(0); if (index == -1) { tr_error("No free sockets!"); _socket_mutex.unlock(); return NSAPI_ERROR_NO_SOCKET; } tr_info("Socket %d open", index); // create local socket structure, socket on modem is created when app calls sendto/recvfrom // Do not assign a socket ID yet. Socket is not created at the Modem yet. // create_socket_impl(handle) will assign the correct socket ID. _socket[index] = new CellularSocket; CellularSocket *psock = _socket[index]; SocketAddress addr(0, get_dynamic_ip_port()); psock->localAddress = addr; psock->proto = proto; *handle = psock; _socket_mutex.unlock(); return NSAPI_ERROR_OK; } nsapi_error_t AT_CellularStack::socket_close(nsapi_socket_t handle) { int err = NSAPI_ERROR_DEVICE_ERROR; struct CellularSocket *socket = (struct CellularSocket *)handle; if (!socket) { return err; } int sock_id = socket->id; int index = find_socket_index(handle); if (index == -1) { tr_error("No socket found to be closed"); return err; } err = NSAPI_ERROR_OK; // Close the socket on the modem if it was created _at.lock(); if (sock_id > -1) { err = socket_close_impl(sock_id); } if (!err) { tr_info("Socket %d closed", index); } else { tr_info("Socket %d close (id %d, started %d, error %d)", index, sock_id, socket->started, err); } _socket[index] = NULL; delete socket; _at.unlock(); return err; } nsapi_error_t AT_CellularStack::socket_bind(nsapi_socket_t handle, const SocketAddress &addr) { struct CellularSocket *socket = (CellularSocket *)handle; if (!socket) { return NSAPI_ERROR_DEVICE_ERROR; } if (addr) { return NSAPI_ERROR_UNSUPPORTED; } _at.lock(); uint16_t port = addr.get_port(); if (port != socket->localAddress.get_port()) { if (port && (get_socket_index_by_port(port) == -1)) { socket->localAddress.set_port(port); } else { _at.unlock(); return NSAPI_ERROR_PARAMETER; } } if (socket->id == -1) { create_socket_impl(socket); } return _at.unlock_return_error(); } nsapi_error_t AT_CellularStack::socket_listen(nsapi_socket_t handle, int backlog) { return NSAPI_ERROR_UNSUPPORTED;; } nsapi_error_t AT_CellularStack::socket_connect(nsapi_socket_t handle, const SocketAddress &addr) { CellularSocket *socket = (CellularSocket *)handle; if (!socket) { return NSAPI_ERROR_DEVICE_ERROR; } socket->remoteAddress = addr; socket->connected = true; return NSAPI_ERROR_OK; } nsapi_error_t AT_CellularStack::socket_accept(void *server, void **socket, SocketAddress *addr) { return NSAPI_ERROR_UNSUPPORTED;; } nsapi_size_or_error_t AT_CellularStack::socket_send(nsapi_socket_t handle, const void *data, unsigned size) { CellularSocket *socket = (CellularSocket *)handle; if (!socket || !socket->connected) { return NSAPI_ERROR_DEVICE_ERROR; } return socket_sendto(handle, socket->remoteAddress, data, size); } nsapi_size_or_error_t AT_CellularStack::socket_sendto(nsapi_socket_t handle, const SocketAddress &addr, const void *data, unsigned size) { CellularSocket *socket = (CellularSocket *)handle; if (!socket) { return NSAPI_ERROR_DEVICE_ERROR; } if (socket->closed && !socket->rx_avail) { tr_info("sendto socket %d closed", socket->id); return NSAPI_ERROR_NO_CONNECTION; } if (size == 0) { if (socket->proto == NSAPI_UDP) { return NSAPI_ERROR_UNSUPPORTED; } else if (socket->proto == NSAPI_TCP) { return 0; } } nsapi_size_or_error_t ret_val = NSAPI_ERROR_OK; if (socket->id == -1) { /* Check that stack type supports sendto address type*/ if (!is_addr_stack_compatible(addr)) { return NSAPI_ERROR_PARAMETER; } _ip_ver_sendto = addr.get_ip_version(); _at.lock(); ret_val = create_socket_impl(socket); _at.unlock(); if (ret_val != NSAPI_ERROR_OK) { tr_error("Socket %d create %s error %d", find_socket_index(socket), addr.get_ip_address(), ret_val); return ret_val; } } /* Check parameters - sendto address is valid and stack type supports sending to that address type*/ if (!is_addr_stack_compatible(addr)) { return NSAPI_ERROR_PARAMETER; } _at.lock(); ret_val = socket_sendto_impl(socket, addr, data, size); _at.unlock(); if (ret_val >= 0) { tr_info("Socket %d sent %d bytes to %s port %d", find_socket_index(socket), ret_val, addr.get_ip_address(), addr.get_port()); } else if (ret_val != NSAPI_ERROR_WOULD_BLOCK) { tr_error("Socket %d sendto %s error %d", find_socket_index(socket), addr.get_ip_address(), ret_val); } return ret_val; } nsapi_size_or_error_t AT_CellularStack::socket_recv(nsapi_socket_t handle, void *data, unsigned size) { return socket_recvfrom(handle, NULL, data, size); } nsapi_size_or_error_t AT_CellularStack::socket_recvfrom(nsapi_socket_t handle, SocketAddress *addr, void *buffer, unsigned size) { CellularSocket *socket = (CellularSocket *)handle; if (!socket) { return NSAPI_ERROR_DEVICE_ERROR; } if (socket->closed) { tr_info("recvfrom socket %d closed", socket->id); return 0; } nsapi_size_or_error_t ret_val = NSAPI_ERROR_OK; if (socket->id == -1) { _at.lock(); ret_val = create_socket_impl(socket); _at.unlock(); if (ret_val != NSAPI_ERROR_OK) { tr_error("Socket %d create error %d", find_socket_index(socket), ret_val); return ret_val; } } _at.lock(); ret_val = socket_recvfrom_impl(socket, addr, buffer, size); _at.unlock(); if (socket->closed) { tr_info("recvfrom socket %d closed", socket->id); return 0; } if (ret_val >= 0) { if (addr) { tr_info("Socket %d recv %d bytes from %s port %d", find_socket_index(socket), ret_val, addr->get_ip_address(), addr->get_port()); } else { tr_info("Socket %d recv %d bytes", find_socket_index(socket), ret_val); } } else if (ret_val != NSAPI_ERROR_WOULD_BLOCK) { tr_error("Socket %d recv error %d", find_socket_index(socket), ret_val); } return ret_val; } void AT_CellularStack::socket_attach(nsapi_socket_t handle, void (*callback)(void *), void *data) { CellularSocket *socket = (CellularSocket *)handle; if (!socket) { return; } socket->_cb = callback; socket->_data = data; } int AT_CellularStack::get_socket_index_by_port(uint16_t port) { int max_socket_count = get_max_socket_count(); for (int i = 0; i < max_socket_count; i++) { if (_socket[i]->localAddress.get_port() == port) { return i; } } return -1; } AT_CellularStack::CellularSocket *AT_CellularStack::find_socket(int sock_id) { CellularSocket *sock = NULL; for (int i = 0; i < _socket_count; i++) { if (_socket[i] && _socket[i]->id == sock_id) { sock = _socket[i]; break; } } if (!sock) { tr_error("Socket not found %d", sock_id); } return sock; } bool AT_CellularStack::is_addr_stack_compatible(const SocketAddress &addr) { if ((addr.get_ip_version() == NSAPI_UNSPEC) || (addr.get_ip_version() == NSAPI_IPv4 && _stack_type == IPV6_STACK) || (addr.get_ip_version() == NSAPI_IPv6 && _stack_type == IPV4_STACK)) { return false; } return true; }
65cef77918435881880c6f44a276ee1d02d9e69e
18e721e79b002c99ef684c39d977cce06fe523dc
/src/ConEmuCD/Actions.cpp
34d8ad1389b225a4daff13779e924948427695ba
[ "BSD-3-Clause" ]
permissive
lkisac/ConEmu
71ae64b7c539021e07a540a49f6f13ea06788af3
694d71c27f83628e65d2fbbb54c4f2c94547933f
refs/heads/master
2021-01-19T20:45:36.106700
2017-04-03T10:16:50
2017-04-03T10:16:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,649
cpp
 /* Copyright (c) 2016-2017 Maximus5 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 name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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. */ #define HIDE_USE_EXCEPTION_INFO #define SHOWDEBUGSTR #include "../common/Common.h" #include "../common/CmdLine.h" #include "../common/ConEmuCheck.h" #include "../common/CEStr.h" #include "../common/MProcess.h" #include "../common/MStrDup.h" #include "../common/ProcessData.h" #include "../common/WCodePage.h" #include "../common/WFiles.h" #include "../common/WUser.h" #include "../ConEmuHk/Injects.h" #include "../ConEmu/version.h" #include "ConEmuC.h" #include "Actions.h" #include "GuiMacro.h" #include "MapDump.h" #include "UnicodeTest.h" // ConEmuC -OsVerInfo int OsVerInfo() { OSVERSIONINFOEX osv = {sizeof(osv)}; GetOsVersionInformational((OSVERSIONINFO*)&osv); UINT DBCS = IsDbcs(); UINT HWFS = IsHwFullScreenAvailable(); UINT W5fam = IsWin5family(); UINT WXPSP1 = IsWinXPSP1(); UINT W6 = IsWin6(); UINT W7 = IsWin7(); UINT W10 = IsWin10(); UINT Wx64 = IsWindows64(); UINT WINE = IsWine(); UINT WPE = IsWinPE(); UINT TELNET = isTerminalMode(); wchar_t szInfo[200]; _wsprintf(szInfo, SKIPCOUNT(szInfo) L"OS version information\n" L"%u.%u build %u SP%u.%u suite=x%04X type=%u\n" L"W5fam=%u WXPSP1=%u W6=%u W7=%u W10=%u Wx64=%u\n" L"HWFS=%u DBCS=%u WINE=%u WPE=%u TELNET=%u\n", osv.dwMajorVersion, osv.dwMinorVersion, osv.dwBuildNumber, osv.wServicePackMajor, osv.wServicePackMinor, osv.wSuiteMask, osv.wProductType, W5fam, WXPSP1, W6, W7, W10, Wx64, HWFS, DBCS, WINE, WPE, TELNET); _wprintf(szInfo); return MAKEWORD(osv.dwMinorVersion, osv.dwMajorVersion); } void RegisterConsoleFontHKLM(LPCWSTR pszFontFace) { if (!pszFontFace || !*pszFontFace) return; HKEY hk; DWORD nRights = KEY_ALL_ACCESS|WIN3264TEST((IsWindows64() ? KEY_WOW64_64KEY : 0),0); if (!RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Console\\TrueTypeFont", 0, nRights, &hk)) { wchar_t szId[32] = {0}, szFont[255]; DWORD dwLen, dwType; for (DWORD i = 0; i <20; i++) { szId[i] = L'0'; szId[i+1] = 0; wmemset(szFont, 0, 255); if (RegQueryValueExW(hk, szId, NULL, &dwType, (LPBYTE)szFont, &(dwLen = 255*2))) { RegSetValueExW(hk, szId, 0, REG_SZ, (LPBYTE)pszFontFace, (lstrlen(pszFontFace)+1)*2); break; } if (lstrcmpi(szFont, pszFontFace) == 0) { break; // он уже добавлен } } RegCloseKey(hk); } } bool DoStateCheck(ConEmuStateCheck eStateCheck) { LogFunction(L"DoStateCheck"); bool bOn = false; switch (eStateCheck) { case ec_IsConEmu: case ec_IsAnsi: if (ghConWnd) { CESERVER_CONSOLE_MAPPING_HDR* pInfo = (CESERVER_CONSOLE_MAPPING_HDR*)malloc(sizeof(*pInfo)); if (pInfo && LoadSrvMapping(ghConWnd, *pInfo)) { _ASSERTE(pInfo->ComSpec.ConEmuExeDir[0] && pInfo->ComSpec.ConEmuBaseDir[0]); HWND hWnd = pInfo->hConEmuWndDc; if (hWnd && IsWindow(hWnd)) { switch (eStateCheck) { case ec_IsConEmu: bOn = true; break; case ec_IsAnsi: bOn = ((pInfo->Flags & CECF_ProcessAnsi) != 0); break; default: ; } } } SafeFree(pInfo); } break; case ec_IsAdmin: bOn = IsUserAdmin(); break; case ec_IsRedirect: bOn = IsOutputRedirected(); break; case ec_IsTerm: bOn = isTerminalMode(); break; default: _ASSERTE(FALSE && "Unsupported StateCheck code"); } return bOn; } int DoInjectHooks(LPWSTR asCmdArg) { gbInShutdown = TRUE; // чтобы не возникло вопросов при выходе gnRunMode = RM_SETHOOK64; LPWSTR pszNext = asCmdArg; LPWSTR pszEnd = NULL; BOOL lbForceGui = FALSE; PROCESS_INFORMATION pi = {NULL}; pi.hProcess = (HANDLE)wcstoul(pszNext, &pszEnd, 16); if (pi.hProcess && pszEnd && *pszEnd) { pszNext = pszEnd+1; pi.dwProcessId = wcstoul(pszNext, &pszEnd, 10); } if (pi.dwProcessId && pszEnd && *pszEnd) { pszNext = pszEnd+1; pi.hThread = (HANDLE)wcstoul(pszNext, &pszEnd, 16); } if (pi.hThread && pszEnd && *pszEnd) { pszNext = pszEnd+1; pi.dwThreadId = wcstoul(pszNext, &pszEnd, 10); } if (pi.dwThreadId && pszEnd && *pszEnd) { pszNext = pszEnd+1; lbForceGui = wcstoul(pszNext, &pszEnd, 10); } #ifdef SHOW_INJECT_MSGBOX wchar_t szDbgMsg[512], szTitle[128]; PROCESSENTRY32 pinf; GetProcessInfo(pi.dwProcessId, &pinf); _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuCD PID=%u", GetCurrentProcessId()); _wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"InjectsTo PID=%s {%s}\nConEmuCD PID=%u", asCmdArg ? asCmdArg : L"", pinf.szExeFile, GetCurrentProcessId()); MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL); #endif if (pi.hProcess && pi.hThread && pi.dwProcessId && pi.dwThreadId) { // Аргумент abForceGui не использовался CINJECTHK_EXIT_CODES iHookRc = InjectHooks(pi, /*lbForceGui,*/ gbLogProcess); if (iHookRc == CIH_OK/*0*/) { return CERR_HOOKS_WAS_SET; } // Ошибку (пока во всяком случае) лучше показать, для отлова возможных проблем DWORD nErrCode = GetLastError(); //_ASSERTE(iHookRc == 0); -- ассерт не нужен, есть MsgBox wchar_t szDbgMsg[255], szTitle[128]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuC[%u], PID=%u", WIN3264TEST(32,64), GetCurrentProcessId()); _wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"ConEmuC.X, PID=%u\nInjecting hooks into PID=%u\nFAILED, code=%i:0x%08X", GetCurrentProcessId(), pi.dwProcessId, iHookRc, nErrCode); MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL); } else { //_ASSERTE(pi.hProcess && pi.hThread && pi.dwProcessId && pi.dwThreadId); wchar_t szDbgMsg[512], szTitle[128]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuC, PID=%u", GetCurrentProcessId()); _wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"ConEmuC.X, PID=%u\nCmdLine parsing FAILED (%u,%u,%u,%u,%u)!\n%s", GetCurrentProcessId(), LODWORD(pi.hProcess), LODWORD(pi.hThread), pi.dwProcessId, pi.dwThreadId, lbForceGui, //-V205 asCmdArg); MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL); } return CERR_HOOKS_FAILED; } int DoInjectRemote(LPWSTR asCmdArg, bool abDefTermOnly) { gbInShutdown = TRUE; // чтобы не возникло вопросов при выходе gnRunMode = RM_SETHOOK64; LPWSTR pszNext = asCmdArg; LPWSTR pszEnd = NULL; DWORD nRemotePID = wcstoul(pszNext, &pszEnd, 10); wchar_t szStr[16]; wchar_t szTitle[128]; wchar_t szInfo[120]; wchar_t szParentPID[32]; #ifdef _DEBUG extern int ShowInjectRemoteMsg(int nRemotePID, LPCWSTR asCmdArg); if (ShowInjectRemoteMsg(nRemotePID, asCmdArg) != IDOK) { return CERR_HOOKS_FAILED; } #endif if (nRemotePID) { #if defined(SHOW_ATTACH_MSGBOX) if (!IsDebuggerPresent()) { wchar_t szTitle[100]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"%s PID=%u /INJECT", gsModuleName, gnSelfPID); const wchar_t* pszCmdLine = GetCommandLineW(); MessageBox(NULL,pszCmdLine,szTitle,MB_SYSTEMMODAL); } #endif CEStr lsName, lsPath; { CProcessData processes; processes.GetProcessName(nRemotePID, lsName.GetBuffer(MAX_PATH), MAX_PATH, lsPath.GetBuffer(MAX_PATH*2), MAX_PATH*2, NULL); CEStr lsLog(L"Remote: PID=", _ultow(nRemotePID, szStr, 10), L" Name=`", lsName, L"` Path=`", lsPath, L"`"); LogString(lsLog); } // Go to hook // InjectRemote waits for thread termination DWORD nErrCode = 0; CINFILTRATE_EXIT_CODES iHookRc = InjectRemote(nRemotePID, abDefTermOnly, &nErrCode); _wsprintf(szInfo, SKIPCOUNT(szInfo) L"InjectRemote result: %i (%s)", iHookRc, (iHookRc == CIR_OK) ? L"CIR_OK" : (iHookRc == CIR_AlreadyInjected) ? L"CIR_AlreadyInjected" : L"?"); LogString(szInfo); if (iHookRc == CIR_OK/*0*/ || iHookRc == CIR_AlreadyInjected/*1*/) { return iHookRc ? CERR_HOOKS_WAS_ALREADY_SET : CERR_HOOKS_WAS_SET; } else if ((iHookRc == CIR_ProcessWasTerminated) || (iHookRc == CIR_OpenProcess)) { // Don't show error message to user. These codes are logged to file only. return CERR_HOOKS_FAILED; } DWORD nSelfPID = GetCurrentProcessId(); PROCESSENTRY32 self = {sizeof(self)}, parent = {sizeof(parent)}; // Not optimal, needs refactoring if (GetProcessInfo(nSelfPID, &self)) GetProcessInfo(self.th32ParentProcessID, &parent); // Ошибку (пока во всяком случае) лучше показать, для отлова возможных проблем //_ASSERTE(iHookRc == 0); -- ассерт не нужен, есть MsgBox _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"%s %s, PID=%u", gsModuleName, gsVersion, nSelfPID); _wsprintf(szInfo, SKIPCOUNT(szInfo) L"Injecting remote FAILED, code=%i:0x%08X\n" L"%s %s, PID=%u\n" L"RemotePID=%u ", iHookRc, nErrCode, gsModuleName, gsVersion, nSelfPID, nRemotePID); _wsprintf(szParentPID, SKIPCOUNT(szParentPID) L"\n" L"ParentPID=%u ", self.th32ParentProcessID); CEStr lsError(lstrmerge( szInfo, lsPath.IsEmpty() ? lsName.IsEmpty() ? L"<Unknown>" : lsName.ms_Val : lsPath.ms_Val, szParentPID, parent.szExeFile)); LogString(lsError); MessageBoxW(NULL, lsError, szTitle, MB_SYSTEMMODAL); } else { //_ASSERTE(pi.hProcess && pi.hThread && pi.dwProcessId && pi.dwThreadId); wchar_t szDbgMsg[512], szTitle[128]; _wsprintf(szTitle, SKIPLEN(countof(szTitle)) L"ConEmuC, PID=%u", GetCurrentProcessId()); _wsprintf(szDbgMsg, SKIPLEN(countof(szDbgMsg)) L"ConEmuC.X, PID=%u\nCmdLine parsing FAILED (%u)!\n%s", GetCurrentProcessId(), nRemotePID, asCmdArg); LogString(szDbgMsg); MessageBoxW(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL); } return CERR_HOOKS_FAILED; } // GCC error: template argument for 'template<class _Ty> class MArray' uses local type struct ProcInfo { DWORD nPID, nParentPID; DWORD_PTR Flags; WCHAR szExeFile[64]; }; int DoExportEnv(LPCWSTR asCmdArg, ConEmuExecAction eExecAction, bool bSilent /*= false*/) { int iRc = CERR_CARGUMENT; //ProcInfo* pList = NULL; MArray<ProcInfo> List; LPWSTR pszAllVars = NULL, pszSrc; int iVarCount = 0; CESERVER_REQ *pIn = NULL; const DWORD nSelfPID = GetCurrentProcessId(); DWORD nTestPID, nParentPID; DWORD nSrvPID = 0; CESERVER_CONSOLE_MAPPING_HDR test = {}; BOOL lbMapExist = false; HANDLE h; size_t cchMaxEnvLen = 0; wchar_t* pszBuffer; CEStr szTmpPart; LPCWSTR pszTmpPartStart; LPCWSTR pszCmdArg; wchar_t szInfo[200]; //_ASSERTE(FALSE && "Continue with exporting environment"); #define ExpFailedPref WIN3264TEST("ConEmuC","ConEmuC64") ": can't export environment" if (!ghConWnd) { _ASSERTE(ghConWnd); if (!bSilent) _printf(ExpFailedPref ", ghConWnd was not set\n"); goto wrap; } // Query current environment pszAllVars = GetEnvironmentStringsW(); if (!pszAllVars || !*pszAllVars) { if (!bSilent) _printf(ExpFailedPref ", GetEnvironmentStringsW failed, code=%u\n", GetLastError()); goto wrap; } // Parse variables block, determining MAX length pszSrc = pszAllVars; while (*pszSrc) { LPWSTR pszName = pszSrc; LPWSTR pszVal = pszName + lstrlen(pszName) + 1; pszSrc = pszVal; } cchMaxEnvLen = pszSrc - pszAllVars + 1; // Preparing buffer pIn = ExecuteNewCmd(CECMD_EXPORTVARS, sizeof(CESERVER_REQ_HDR)+cchMaxEnvLen*sizeof(wchar_t)); if (!pIn) { if (!bSilent) _printf(ExpFailedPref ", pIn allocation failed\n"); goto wrap; } pszBuffer = (wchar_t*)pIn->wData; pszCmdArg = SkipNonPrintable(asCmdArg); //_ASSERTE(FALSE && "Continue to export"); LogString(L"DoExportEnv: Loading variables to export"); // Copy variables to buffer if (!pszCmdArg || !*pszCmdArg || (lstrcmp(pszCmdArg, L"*")==0) || (lstrcmp(pszCmdArg, L"\"*\"")==0) || (wcsncmp(pszCmdArg, L"* ", 2)==0) || (wcsncmp(pszCmdArg, L"\"*\" ", 4)==0)) { // transfer ALL variables, except of ConEmu's internals pszSrc = pszAllVars; while (*pszSrc) { // may be "=C:=C:\Program Files\..." LPWSTR pszEq = wcschr(pszSrc+1, L'='); if (!pszEq) { pszSrc = pszSrc + lstrlen(pszSrc) + 1; continue; } *pszEq = 0; LPWSTR pszName = pszSrc; LPWSTR pszVal = pszName + lstrlen(pszName) + 1; LPWSTR pszNext = pszVal + lstrlen(pszVal) + 1; if (IsExportEnvVarAllowed(pszName)) { // Non ConEmu's internals, transfer it size_t cchAdd = pszNext - pszName; wmemmove(pszBuffer, pszName, cchAdd); pszBuffer += cchAdd; _ASSERTE(*pszBuffer == 0); iVarCount++; if (gpLogSize) { *pszEq = L'='; LogString(pszName); } } *pszEq = L'='; pszSrc = pszNext; } } else while (0==NextArg(&pszCmdArg, szTmpPart, &pszTmpPartStart)) { if ((pszTmpPartStart > asCmdArg) && (*(pszTmpPartStart-1) != L'"')) { // Unless the argument name was surrounded by double-quotes // replace commas with spaces, this allows more intuitive // way to run something like this: // ConEmuC -export=ALL SSH_AGENT_PID,SSH_AUTH_SOCK wchar_t* pszComma = szTmpPart.ms_Val; while ((pszComma = (wchar_t*)wcspbrk(pszComma, L",;")) != NULL) { *pszComma = L' '; } } LPCWSTR pszPart = szTmpPart; CEStr szTest; while (0==NextArg(&pszPart, szTest)) { if (!*szTest || *szTest == L'*') { if (!bSilent) _printf(ExpFailedPref ", name masks can't be quoted\n"); goto wrap; } bool bFound = false; size_t cchLeft = cchMaxEnvLen - 1; // Loop through variable names pszSrc = pszAllVars; while (*pszSrc) { // may be "=C:=C:\Program Files\..." LPWSTR pszEq = wcschr(pszSrc+1, L'='); if (!pszEq) { pszSrc = pszSrc + lstrlen(pszSrc) + 1; continue; } *pszEq = 0; LPWSTR pszName = pszSrc; LPWSTR pszVal = pszName + lstrlen(pszName) + 1; LPWSTR pszNext = pszVal + lstrlen(pszVal) + 1; if (IsExportEnvVarAllowed(pszName) && CompareFileMask(pszName, szTest)) // limited { // Non ConEmu's internals, transfer it size_t cchAdd = pszNext - pszName; if (cchAdd >= cchLeft) { *pszEq = L'='; if (!bSilent) _printf(ExpFailedPref ", too many variables\n"); goto wrap; } wmemmove(pszBuffer, pszName, cchAdd); iVarCount++; pszBuffer += cchAdd; _ASSERTE(*pszBuffer == 0); cchLeft -= cchAdd; bFound = true; if (gpLogSize) { *pszEq = L'='; LogString(pszName); } } *pszEq = L'='; pszSrc = pszNext; // continue scan, only if it is a mask if (bFound && !wcschr(szTest, L'*')) break; } // end of 'while (*pszSrc)' if (!bFound && !wcschr(szTest, L'*')) { // To avoid "nothing to export" size_t cchAdd = lstrlen(szTest) + 1; if (cchAdd < cchLeft) { // Copy "Name\0\0" wmemmove(pszBuffer, szTest, cchAdd); iVarCount++; cchAdd++; // We need second zero after a Name pszBuffer += cchAdd; cchLeft -= cchAdd; _ASSERTE(*pszBuffer == 0); if (gpLogSize) { CEStr lsLog(L"Variable `", szTest, L"` was not found"); LogString(lsLog); } } } } } if (pszBuffer == (wchar_t*)pIn->wData) { if (!bSilent) _printf(ExpFailedPref ", nothing to export\n"); goto wrap; } _ASSERTE(*pszBuffer==0 && *(pszBuffer-1)==0); // Must be ASCIIZZ _ASSERTE((INT_PTR)cchMaxEnvLen >= (pszBuffer - (wchar_t*)pIn->wData + 1)); // Precise buffer size cchMaxEnvLen = pszBuffer - (wchar_t*)pIn->wData + 1; _ASSERTE(!(cchMaxEnvLen>>20)); pIn->hdr.cbSize = sizeof(CESERVER_REQ_HDR)+(DWORD)cchMaxEnvLen*sizeof(wchar_t); // Find current server (even if no server or no GUI - apply environment to parent tree) lbMapExist = LoadSrvMapping(ghConWnd, test); if (lbMapExist) { _ASSERTE(test.ComSpec.ConEmuExeDir[0] && test.ComSpec.ConEmuBaseDir[0]); nSrvPID = test.nServerPID; } // Allocate memory for process tree //pList = (ProcInfo*)malloc(cchMax*sizeof(*pList)); //if (!pList) if (!List.alloc(4096)) { if (!bSilent) _printf(ExpFailedPref ", List allocation failed\n"); goto wrap; } // Go, build tree (first step - query all running PIDs in the system) nParentPID = nSelfPID; // Don't do snapshot if only GUI was requested h = (eExecAction != ea_ExportGui) ? CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) : NULL; // Snapshot opened? if (h && (h != INVALID_HANDLE_VALUE)) { PROCESSENTRY32 PI = {sizeof(PI)}; if (Process32First(h, &PI)) { do { if (PI.th32ProcessID == nSelfPID) { // On the first step we'll get our parent process nParentPID = PI.th32ParentProcessID; } LPCWSTR pszName = PointToName(PI.szExeFile); ProcInfo pi = { PI.th32ProcessID, PI.th32ParentProcessID, IsConsoleServer(pszName) ? 1UL : 0UL }; lstrcpyn(pi.szExeFile, pszName, countof(pi.szExeFile)); List.push_back(pi); } while (Process32Next(h, &PI)); } CloseHandle(h); } // Send to parents tree if (!List.empty() && (nParentPID != nSelfPID)) { DWORD nOurParentPID = nParentPID; // Loop while parent is found bool bParentFound = true; while (nParentPID != nSrvPID) { wchar_t szName[64] = L"???"; nTestPID = nParentPID; bParentFound = false; // find next parent INT_PTR i = 0; INT_PTR nCount = List.size(); while (i < nCount) { const ProcInfo& pi = List[i]; if (pi.nPID == nTestPID) { nParentPID = pi.nParentPID; if (pi.Flags & 1) { // ConEmuC - пропустить i = 0; nTestPID = nParentPID; continue; } lstrcpyn(szName, pi.szExeFile, countof(szName)); // nTestPID is already pi.nPID bParentFound = true; break; } i++; } if (nTestPID == nSrvPID) break; // Fin, this is root server if (!bParentFound) break; // Fin, no more parents if (nTestPID == nOurParentPID) continue; // Useless, we just inherited ALL those variables from our parent _wsprintf(szInfo, SKIPCOUNT(szInfo) L"DoExportEnv: PID=%u `%s`", nTestPID, szName); LogString(szInfo); // Apply environment CESERVER_REQ *pOut = ExecuteHkCmd(nTestPID, pIn, ghConWnd, FALSE, TRUE); if (!pOut && !bSilent) { _wsprintf(szInfo, SKIPCOUNT(szInfo) WIN3264TEST(L"ConEmuC",L"ConEmuC64") L": process %s PID=%u was skipped: noninteractive or lack of ConEmuHk\n", szName, nTestPID); _wprintf(szInfo); } ExecuteFreeResult(pOut); } } // We are trying to apply environment to parent tree even if NO server or GUI was found if (nSrvPID) { _wsprintf(szInfo, SKIPCOUNT(szInfo) L"DoExportEnv: PID=%u (server)", nSrvPID); LogString(szInfo); // Server found? Try to apply environment CESERVER_REQ *pOut = ExecuteSrvCmd(nSrvPID, pIn, ghConWnd); if (!pOut) { if (!bSilent) _printf(ExpFailedPref " to PID=%u, root server was terminated?\n", nSrvPID); } else { ExecuteFreeResult(pOut); } } // Если просили во все табы - тогда досылаем и в GUI if ((eExecAction != ea_ExportCon) && lbMapExist && test.hConEmuRoot && IsWindow((HWND)test.hConEmuRoot)) { if (eExecAction == ea_ExportAll) { pIn->hdr.nCmd = CECMD_EXPORTVARSALL; } else { _ASSERTE(pIn->hdr.nCmd == CECMD_EXPORTVARS); } LogString(L"DoExportEnv: ConEmu GUI"); // ea_ExportTab, ea_ExportGui, ea_ExportAll -> export to ConEmu window ExecuteGuiCmd(ghConWnd, pIn, ghConWnd, TRUE); } _wsprintf(szInfo, SKIPCOUNT(szInfo) WIN3264TEST(L"ConEmuC",L"ConEmuC64") L": %i %s processed", iVarCount, (iVarCount == 1) ? L"variable was" : L"variables were"); LogString(szInfo); if (!bSilent) { wcscat_c(szInfo, L"\n"); _wprintf(szInfo); } iRc = 0; wrap: // Fin if (pszAllVars) FreeEnvironmentStringsW((LPWCH)pszAllVars); if (pIn) ExecuteFreeResult(pIn); return iRc; } // The function exists in both "ConEmuC/ConEmuC.cpp" and "ConEmuCD/Actions.cpp" // Version in "ConEmuC/ConEmuC.cpp" shows arguments from main(int argc, char** argv) // Version in "ConEmuCD/Actions.cpp" perhaps would not be ever called int DoParseArgs(LPCWSTR asCmdLine) { _printf("Parsing command\n `"); _wprintf(asCmdLine); _printf("`\n"); int iShellCount = 0; LPWSTR* ppszShl = CommandLineToArgvW(asCmdLine, &iShellCount); int i = 0; CEStr szArg; _printf("ConEmu `NextArg` splitter\n"); while (NextArg(&asCmdLine, szArg) == 0) { if (szArg.mb_Quoted) DemangleArg(szArg, true); _printf(" %u: `", ++i); _wprintf(szArg); _printf("`\n"); } _printf(" Total arguments parsed: %u\n", i); _printf("Standard shell splitter\n"); for (int j = 0; j < iShellCount; j++) { _printf(" %u: `", j); _wprintf(ppszShl[j]); _printf("`\n"); } _printf(" Total arguments parsed: %u\n", iShellCount); LocalFree(ppszShl); return i; } HMODULE LoadConEmuHk() { HMODULE hHooks = NULL; LPCWSTR pszHooksName = WIN3264TEST(L"ConEmuHk.dll",L"ConEmuHk64.dll"); if ((hHooks = GetModuleHandle(pszHooksName)) == NULL) { wchar_t szSelf[MAX_PATH]; if (GetModuleFileName(ghOurModule, szSelf, countof(szSelf))) { wchar_t* pszName = (wchar_t*)PointToName(szSelf); int nSelfName = lstrlen(pszName); _ASSERTE(nSelfName == lstrlen(pszHooksName)); lstrcpyn(pszName, pszHooksName, nSelfName+1); // ConEmuHk.dll / ConEmuHk64.dll hHooks = LoadLibrary(szSelf); } } return hHooks; } int DoOutput(ConEmuExecAction eExecAction, LPCWSTR asCmdArg) { int iRc = 0; CEStr szTemp; LPCWSTR pszText = NULL; DWORD cchLen = 0, dwWritten = 0; bool bAddNewLine = true; bool bProcessed = true; bool bToBottom = false; bool bAsciiPrint = false; bool bExpandEnvVar = false; bool bStreamBy1 = false; CEStr szArg; HANDLE hFile = NULL; DWORD DefaultCP = 0; _ASSERTE(asCmdArg && (*asCmdArg != L' ')); asCmdArg = SkipNonPrintable(asCmdArg); while ((*asCmdArg == L'-' || *asCmdArg == L'/') && (NextArg(&asCmdArg, szArg) == 0)) { // Make uniform if (szArg.ms_Val[0] == L'/') szArg.ms_Val[0] = L'-'; // Do not CRLF after printing if (lstrcmpi(szArg, L"-n") == 0) bAddNewLine = false; // ‘RAW’: Do not process ANSI and specials (^e^[^r^n^t^b...) else if (lstrcmpi(szArg, L"-r") == 0) bProcessed = false; // Expand environment variables before echo else if (lstrcmpi(szArg, L"-x") == 0) bExpandEnvVar = true; // Scroll to bottom of screen buffer (ConEmu TrueColor buffer compatible) else if (lstrcmpi(szArg, L"-b") == 0) bToBottom = true; // Use Ascii functions to print text (RAW data, don't convert to unicode) else if (lstrcmpi(szArg, L"-a") == 0) { if (eExecAction == ea_OutType) bAsciiPrint = true; } // For testing purposes, stream characters one-by-one else if (lstrcmpi(szArg, L"-s") == 0) { if (eExecAction == ea_OutType) bStreamBy1 = true; } // Forced codepage of typed text file else // `-65001`, `-utf8`, `-oemcp`, etc. { UINT nCP = GetCpFromString(szArg.ms_Val+1); if (nCP) DefaultCP = nCP; } } _ASSERTE(asCmdArg && (*asCmdArg != L' ')); asCmdArg = SkipNonPrintable(asCmdArg); if (eExecAction == ea_OutType) { if (NextArg(&asCmdArg, szArg) == 0) { _ASSERTE(!bAsciiPrint || !DefaultCP); DWORD nSize = 0, nErrCode = 0; int iRead = ReadTextFile(szArg, (1<<24), szTemp.ms_Val, cchLen, nErrCode, bAsciiPrint ? (DWORD)-1 : DefaultCP); if (iRead < 0) { wchar_t szInfo[100]; _wsprintf(szInfo, SKIPLEN(countof(szInfo)) L"\r\nCode=%i, Error=%u\r\n", iRead, nErrCode); szTemp = lstrmerge(L"Reading source file failed!\r\n", szArg, szInfo); cchLen = szTemp.GetLen(); bAsciiPrint = false; iRc = 4; } pszText = szTemp.ms_Val; } } else if (eExecAction == ea_OutEcho) { _ASSERTE(szTemp.ms_Val == NULL); while (NextArg(&asCmdArg, szArg) == 0) { LPCWSTR pszAdd = szArg.ms_Val; _ASSERTE(pszAdd!=NULL); CEStr lsExpand, lsDemangle; // Expand environment variables // TODO: Expand !Variables! too if (bExpandEnvVar && wcschr(pszAdd, L'%')) { lsExpand = ExpandEnvStr(pszAdd); if (!lsExpand.IsEmpty()) pszAdd = lsExpand.ms_Val; } // Replace two double-quotes with one double-quotes if (szArg.mb_Quoted // Process special symbols: ^e^[^r^n^t^b || (bProcessed && wcschr(pszAdd, L'^')) ) { lsDemangle.Set(pszAdd); if (DemangleArg(lsDemangle, szArg.mb_Quoted, bProcessed)) pszAdd = lsDemangle.ms_Val; } // Concatenate result text lstrmerge(&szTemp.ms_Val, szTemp.IsEmpty() ? NULL : L" ", pszAdd); } if (bAddNewLine) lstrmerge(&szTemp.ms_Val, L"\r\n"); pszText = szTemp.ms_Val; cchLen = pszText ? lstrlen(pszText) : 0; } #ifdef _DEBUG if (bAsciiPrint) { _ASSERTE(eExecAction == ea_OutType); } #endif iRc = WriteOutput(pszText, cchLen, dwWritten, bProcessed, bAsciiPrint, bStreamBy1, bToBottom); return iRc; } int WriteOutput(LPCWSTR pszText, DWORD cchLen, DWORD& dwWritten, bool bProcessed, bool bAsciiPrint, bool bStreamBy1, bool bToBottom) { int iRc = 0; BOOL bRc = FALSE; HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); if (bToBottom) { CONSOLE_SCREEN_BUFFER_INFO csbi = {}; if (GetConsoleScreenBufferInfo(hOut, &csbi)) { COORD crBottom = {0, csbi.dwSize.Y-1}; SetConsoleCursorPosition(hOut, crBottom); SHORT Y1 = crBottom.Y - (csbi.srWindow.Bottom-csbi.srWindow.Top); SMALL_RECT srWindow = {0, Y1, csbi.srWindow.Right-csbi.srWindow.Left, crBottom.Y}; SetConsoleWindowInfo(hOut, TRUE, &srWindow); } } if (!pszText || !cchLen) { iRc = 1; goto wrap; } if (!IsOutputRedirected()) { typedef BOOL (WINAPI* WriteProcessed_t)(LPCWSTR lpBuffer, DWORD nNumberOfCharsToWrite, LPDWORD lpNumberOfCharsWritten); typedef BOOL (WINAPI* WriteProcessedA_t)(LPCSTR lpBuffer, DWORD nNumberOfCharsToWrite, LPDWORD lpNumberOfCharsWritten, UINT Stream); WriteProcessed_t WriteProcessed = NULL; WriteProcessedA_t WriteProcessedA = NULL; HMODULE hHooks = NULL; if (bProcessed) { // ConEmuHk.dll / ConEmuHk64.dll if ((hHooks = LoadConEmuHk()) != NULL) { WriteProcessed = (WriteProcessed_t)GetProcAddress(hHooks, "WriteProcessed"); WriteProcessedA = (WriteProcessedA_t)GetProcAddress(hHooks, "WriteProcessedA"); } } // If possible - use processed (with ANSI support) output via WriteProcessed[A] function if (bAsciiPrint) { if (!bStreamBy1) { if (WriteProcessedA) bRc = WriteProcessedA((char*)pszText, cchLen, &dwWritten, 1); else bRc = WriteConsoleA(hOut, (char*)pszText, cchLen, &dwWritten, 0); } else { if (WriteProcessedA) { for (DWORD i = 0; i < cchLen; i++) bRc = WriteProcessedA(((char*)pszText)+i, 1, &dwWritten, 1); } else { for (DWORD i = 0; i < cchLen; i++) bRc = WriteConsoleA(hOut, ((char*)pszText)+i, 1, &dwWritten, 0); } } } else { if (WriteProcessed) bRc = WriteProcessed(pszText, cchLen, &dwWritten); else bRc = WriteConsoleW(hOut, pszText, cchLen, &dwWritten, 0); } } else if (bAsciiPrint) { bRc = WriteFile(hOut, pszText, cchLen, &dwWritten, 0); } else { // Current process output was redirected to file! char* pszOem = NULL; UINT cp = GetConsoleOutputCP(); int nDstLen = WideCharToMultiByte(cp, 0, pszText, cchLen, NULL, 0, NULL, NULL); if (nDstLen < 1) { iRc = 2; goto wrap; } pszOem = (char*)malloc(nDstLen); if (pszOem) { int nWrite = WideCharToMultiByte(cp, 0, pszText, cchLen, pszOem, nDstLen, NULL, NULL); if (nWrite > 1) { bRc = WriteFile(hOut, pszOem, nWrite, &dwWritten, 0); } free(pszOem); } } if (!bRc && !iRc) iRc = 3; wrap: return iRc; } int DoStoreCWD(LPCWSTR asCmdArg) { int iRc = 1; CEStr szDir; if ((NextArg(&asCmdArg, szDir) != 0) || szDir.IsEmpty()) { if (GetDirectory(szDir) == NULL) goto wrap; } // Sends CECMD_STORECURDIR into RConServer SendCurrentDirectory(ghConWnd, szDir); iRc = 0; wrap: return iRc; } int DoExecAction(ConEmuExecAction eExecAction, LPCWSTR asCmdArg /* rest of cmdline */, MacroInstance& Inst) { int iRc = CERR_CARGUMENT; switch (eExecAction) { case ea_RegConFont: { LogString(L"DoExecAction: ea_RegConFont"); RegisterConsoleFontHKLM(asCmdArg); iRc = CERR_EMPTY_COMSPEC_CMDLINE; break; } case ea_InjectHooks: { LogString(L"DoExecAction: DoInjectHooks"); iRc = DoInjectHooks((LPWSTR)asCmdArg); break; } case ea_InjectRemote: case ea_InjectDefTrm: { LogString(L"DoExecAction: DoInjectRemote"); iRc = DoInjectRemote((LPWSTR)asCmdArg, (eExecAction == ea_InjectDefTrm)); break; } case ea_GuiMacro: { LogString(L"DoExecAction: DoGuiMacro"); GuiMacroFlags Flags = gmf_SetEnvVar // If current RealConsole was already started in ConEmu, try to export variable | ((gbMacroExportResult && (gnRunMode != RM_GUIMACRO) && (ghConEmuWnd != NULL)) ? gmf_ExportEnvVar : gmf_None) // Interactive mode, print output to console | ((!gbPreferSilentMode && (gnRunMode != RM_GUIMACRO)) ? gmf_PrintResult : gmf_None); iRc = DoGuiMacro(asCmdArg, Inst, Flags); break; } case ea_CheckUnicodeFont: { LogString(L"DoExecAction: ea_CheckUnicodeFont"); iRc = CheckUnicodeFont(); break; } case ea_PrintConsoleInfo: { LogString(L"DoExecAction: ea_PrintConsoleInfo"); PrintConsoleInfo(); iRc = 0; break; } case ea_TestUnicodeCvt: { LogString(L"DoExecAction: ea_TestUnicodeCvt"); iRc = TestUnicodeCvt(); break; } case ea_OsVerInfo: { LogString(L"DoExecAction: ea_OsVerInfo"); iRc = OsVerInfo(); break; } case ea_ExportCon: case ea_ExportTab: case ea_ExportGui: case ea_ExportAll: { LogString(L"DoExecAction: DoExportEnv"); iRc = DoExportEnv(asCmdArg, eExecAction, gbPreferSilentMode); break; } case ea_ParseArgs: { LogString(L"DoExecAction: DoParseArgs"); iRc = DoParseArgs(asCmdArg); break; } case ea_ErrorLevel: { LogString(L"DoExecAction: ea_ErrorLevel"); wchar_t* pszEnd = NULL; iRc = wcstol(asCmdArg, &pszEnd, 10); break; } case ea_OutEcho: case ea_OutType: { LogString(L"DoExecAction: DoOutput"); iRc = DoOutput(eExecAction, asCmdArg); break; } case ea_StoreCWD: { LogString(L"DoExecAction: DoStoreCWD"); iRc = DoStoreCWD(asCmdArg); break; } case ea_DumpStruct: { LogString(L"DoExecAction: DoDumpStruct"); iRc = DoDumpStruct(asCmdArg); break; } default: _ASSERTE(FALSE && "Unsupported ExecAction code"); } return iRc; }
b522fe665ffffd5cf55df36948cd46e0383fc237
61d2c90145d6c4acf4d3ea64f266a6e77d6a35bf
/example/src/ofApp.h
14213ea1a11f72cb42fd307a3dd16c76da4ca85f
[]
no_license
themancalledjakob/ofxSpriteSheetRenderer
5b35d9a6b5f512be8c21c3e9c2845c48fa14ebeb
622a295d744deccde5c5a230bdd19ed0ca6a61c9
refs/heads/master
2020-06-28T16:27:45.514193
2019-08-02T18:54:39
2019-08-02T18:54:39
200,282,365
0
0
null
2019-08-02T18:42:40
2019-08-02T18:42:40
null
UTF-8
C++
false
false
2,489
h
#ifndef _OF_APP #define _OF_APP #include "ofMain.h" #include "ofxSpriteSheetRenderer.h" //create a new animation. This could be done optinally in your code andnot as a static, just by saying animation_t walkAnimation; walkAnimation.index =0, walkAnimation.frame=0 etc. I find this method the easiest though static animation_t walkAnimation = { 0, /* .index (int) - this is the index of the first animation frame. indicies start at 0 and go left to right, top to bottom by tileWidth on the spriteSheet */ 0, /* .frame (int) - this is the current frame. It's an internal variable and should always be set to 0 at init */ 4, /* .totalframes (int) - the animation length in frames */ 1, /* .width (int) - the width of each animation frame in tiles */ 1, /* .height (int) - the height of each animation frame in tiles */ 75, /* .frameduration (unsigned int) - how many milliseconds each frame should be on screen. Less = faster */ 0, /* .nexttick (unsigned int) - the next time the frame should change. based on frame duration. This is an internal variable and should always be set to 0 at init */ -1, /* .loops (int) - the number of loops to run. -1 equals infinite. This can be adjusted at runtime to pause animations, etc. */ -1, /* .finalindex (int) - the index of the final tile to draw when the animation finishes. -1 is the default so total_frames-1 will be the last frame. */ 1 /* .frameskip (int) - the incrementation of each frame. 1 should be set by default. If you wanted the animation to play backwards you could set this to -1, etc. */ }; //a quick and dirty sprite implementation struct basicSprite { animation_t animation; // a variable to store the animation this sprite uses ofPoint pos; // the position on the screen this sprite will be drawn at float speed; // the speed at which this sprite moves down the screen }; class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed (int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); ofxSpriteSheetRenderer * spriteRenderer; // our spriteRenderer vector<basicSprite *> sprites; // our vector of sprites }; #endif
944c00112f2c1c5d5bb95c13f957fb510edcfbd9
ed5669151a0ebe6bcc8c4b08fc6cde6481803d15
/test/magma-1.6.0/sparse-iter/control/magma_smlumerge.cpp
81445bced493c33604d2037476ae3c9e0c335eea
[]
no_license
JieyangChen7/DVFS-MAGMA
1c36344bff29eeb0ce32736cadc921ff030225d4
e7b83fe3a51ddf2cad0bed1d88a63f683b006f54
refs/heads/master
2021-09-26T09:11:28.772048
2018-05-27T01:45:43
2018-05-27T01:45:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,694
cpp
/* -- MAGMA (version 1.6.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date November 2014 @generated from magma_zmlumerge.cpp normal z -> s, Sat Nov 15 19:54:23 2014 @author Hartwig Anzt */ #include "magma_lapack.h" #include "common_magma.h" #include "../include/magmasparse.h" #include <assert.h> // includes CUDA #include <cuda_runtime_api.h> #include <cublas.h> #include <cusparse_v2.h> #include <cuda_profiler_api.h> #define RTOLERANCE lapackf77_slamch( "E" ) #define ATOLERANCE lapackf77_slamch( "E" ) /** Purpose ------- Takes an strictly lower triangular matrix L and an upper triangular matrix U and merges them into a matrix A containing the upper and lower triangular parts. Arguments --------- @param[in] L magma_s_sparse_matrix input strictly lower triangular matrix L @param[in] U magma_s_sparse_matrix input upper triangular matrix U @param[out] A magma_s_sparse_matrix* output matrix @param[in] queue magma_queue_t Queue to execute in. @ingroup magmasparse_saux ********************************************************************/ extern "C" magma_int_t magma_smlumerge( magma_s_sparse_matrix L, magma_s_sparse_matrix U, magma_s_sparse_matrix *A, magma_queue_t queue ){ if( L.storage_type == Magma_CSR && U.storage_type == Magma_CSR ){ if( L.memory_location == Magma_CPU && U.memory_location == Magma_CPU ){ magma_s_mtransfer( L, A, Magma_CPU, Magma_CPU, queue ); magma_free_cpu( A->col ); magma_free_cpu( A->val ); // make sure it is strictly lower triangular magma_int_t z = 0; for(magma_int_t i=0; i<A->num_rows; i++){ for(magma_int_t j=L.row[i]; j<L.row[i+1]; j++){ if( L.col[j] < i ){// make sure it is strictly lower triangular z++; } } for(magma_int_t j=U.row[i]; j<U.row[i+1]; j++){ z++; } } A->nnz = z; // fill A with the new structure; magma_int_t stat_cpu = 0; stat_cpu += magma_index_malloc_cpu( &A->col, A->nnz ); stat_cpu += magma_smalloc_cpu( &A->val, A->nnz ); if( stat_cpu != 0 ){ magma_s_mfree( A, queue ); printf("error: memory allocation.\n"); return MAGMA_ERR_HOST_ALLOC; } z = 0; for(magma_int_t i=0; i<A->num_rows; i++){ A->row[i] = z; for(magma_int_t j=L.row[i]; j<L.row[i+1]; j++){ if( L.col[j] < i ){// make sure it is strictly lower triangular A->col[z] = L.col[j]; A->val[z] = L.val[j]; z++; } } for(magma_int_t j=U.row[i]; j<U.row[i+1]; j++){ A->col[z] = U.col[j]; A->val[z] = U.val[j]; z++; } } A->row[A->num_rows] = z; A->nnz = z; return MAGMA_SUCCESS; } else{ printf("error: matrix not on CPU.\n"); return MAGMA_SUCCESS; } } else{ printf("error: matrix not on CPU.\n"); return MAGMA_SUCCESS; } }
dc86054e3c053b6ec4def3a031806427ae2042f9
9b72464c8df2a328ccf457c701625967603061e3
/21. Scope/scope.cpp
bd3af950c8117bdc1759d29c923933d67f06c5d5
[]
no_license
Hanivan/Program-cpp-dasar
a076784de7a695a30a47e3e90512b56a892b24d5
1a7a015c0d6dace06abefac2938f1c3a2ed98af5
refs/heads/master
2022-11-15T23:44:21.445421
2020-06-14T06:27:51
2020-06-14T06:27:51
272,142,624
0
0
null
null
null
null
UTF-8
C++
false
false
1,035
cpp
#include <iostream> using namespace std; // global scope int x = 10; // variabel global int ambilGLobal(){ return x; // mengambil variabel global } int xLocal(){ int x = 5; // variabel local scope xLocal return x; } int main(){ cout << "1. Variabel Global: " << x << endl; // local int x = 8; // varibel local untuk main cout << "2. Variabel Local Main: " << x << endl; cout << "3. Variabel Ambil Global: " << ambilGLobal() << endl; cout << "4. Variabel Local Main: " << x << endl; cout << "5. Variabel xLocal: " << xLocal() << endl; cout << "6. Variabel Local Main: " << x << endl; cout << "7. Variabel Local Main: " << x << endl; { cout << "8. Variabel Local Main: " << x << endl; // blok scope int x = 1; cout << "9. Variabel Global: " << ambilGLobal() << endl; cout << "10. Variabel Local Blok: " << ::x << endl; } // ::x adalah cara untuk mengambil variabel global cout << "11. Variabel Local Main: " << x << endl; cin.get(); return 0; }
cab0ea0894404bff6d1ad521eae4cbcc2a5f787e
64a1533f4541b76181cd6d3cec3b28876c969250
/LADS/LabsForms/frmSessionList.cpp
1bd7f6bffd4c1f1da5cf289799945eda1df91979
[]
no_license
drkvogel/retrasst
df1db3330115f6e2eea7afdb869e070a28c1cae8
ee952fe39cf1a00998b00a09ca361fc7c83fa336
refs/heads/master
2020-05-16T22:53:26.565996
2014-08-01T16:52:16
2014-08-01T16:52:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,527
cpp
/*--------------------------------------------------------------------------- * * 16 April 09, NG: Guess session end for single audit trail entry * 26 May 2009, NG: Move into shared library; provide callback * *--------------------------------------------------------------------------*/ #include <vcl.h> #pragma hdrstop #include "frmSessionList.h" #include "LCDbProject.h" #include "LCDbOperator.h" #include "LCDbAnalyser.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TfrmSessionHistory *frmSessionHistory; TForm * TfrmSessionHistory::details; //--------------------------------------------------------------------------- __fastcall TfrmSessionHistory::TfrmSessionHistory(TComponent* Owner) : TForm(Owner) { mcStartDate -> MaxDate = Now(); mcStartDate -> Date = TDate::CurrentDate() - 1; mcEndDate -> MaxDate = TDate::CurrentDate() + 1; mcEndDate -> Date = Now(); grid -> ColCount = NUM_COLS; grid -> Cells[ PROCESS ][ 0 ] = "Session"; grid -> Cells[ OPERATOR ][ 0 ] = "Operator"; grid -> Cells[ MACHINE ][ 0 ] = "Machine"; grid -> Cells[ START ][ 0 ] = "Start"; grid -> Cells[ FINISH ][ 0 ] = "Finish"; } //--------------------------------------------------------------------------- void __fastcall TfrmSessionHistory::FormActivate(TObject *Sender) { listSessions(); details -> Hide(); } //--------------------------------------------------------------------------- void __fastcall TfrmSessionHistory::mcStartDateEnter(TObject *Sender) { mcStartDate -> MaxDate = mcEndDate -> Date; } //--------------------------------------------------------------------------- void __fastcall TfrmSessionHistory::mcEndDateEnter(TObject *Sender) { mcEndDate -> MinDate = mcStartDate -> Date; } //--------------------------------------------------------------------------- void __fastcall TfrmSessionHistory::mcDateClick(TObject *Sender) { listSessions(); } //--------------------------------------------------------------------------- void __fastcall TfrmSessionHistory::FormResize(TObject *Sender) { grid -> ColWidths[ PROCESS ] = 58; grid -> ColWidths[ START ] = 88; grid -> ColWidths[ FINISH ] = 45; int remainder = grid -> Width - 216; grid -> ColWidths[ OPERATOR ] = remainder * 0.4; grid -> ColWidths[ MACHINE ] = remainder * 0.6; } //--------------------------------------------------------------------------- void __fastcall TfrmSessionHistory::gridClick(TObject *Sender) { details -> Show(); } //--------------------------------------------------------------------------- void __fastcall TfrmSessionHistory::FormHide(TObject *Sender) { details -> Hide(); } //--------------------------------------------------------------------------- std::pair< TDateTime, TDateTime > TfrmSessionHistory::getSelected() { std::pair< TDateTime, TDateTime > range( Now(), 0 ); TGridRect selected = grid -> Selection; for( int row = selected.Top; row <= selected.Bottom; ++ row ) { if( row > 0 && row <= sessions.size() ) { const LCDbAuditTrail::Process & proc = sessions[ row - 1 ]; if( range.first > proc.start ) range.first = proc.start; if( range.second < proc.finish ) range.second = proc.finish; } } return range; } //--------------------------------------------------------------------------- void TfrmSessionHistory::listSessions() { Screen -> Cursor = crSQLWait; TDateTime start = mcStartDate -> Date, finish = mcEndDate -> Date + 1; int projID = LCDbProjects::getCurrentID(); sessions = LCDbAuditTrail::getCurrent().read( start, finish, projID ); TDateTime followOn; int row = 1; for( ProcessList::iterator si = sessions.begin(); si != sessions.end(); ++ si, ++ row ) { // The current session has not finished yet; include recent records. if( row == 1 ) si -> finish = Now(); // If there's only one audit trail record, assume it's for the login. // The session would have finished by 9pm and/or before the next one. else if( si -> finish == si -> start ) { unsigned short year, month, day; si -> start.DecodeDate( &year, &month, &day ) ; TDateTime cutOff( year, month, day, 21, 0, 0, 0 ); si -> finish = followOn > cutOff ? cutOff : followOn; } followOn = si -> start; grid -> Cells[ PROCESS ][ row ] = si -> processID; grid -> Cells[ START ][ row ] = si -> start.FormatString( "dd/mm/yy hh:nn" ); grid -> Cells[ FINISH ][ row ] = si -> finish.FormatString( "hh:nn" ); const LCDbOperator * user = LCDbOperators::records().findByID( si -> operatorID ); if( user == NULL ) grid -> Cells[ OPERATOR ][ row ] = ""; else grid -> Cells[ OPERATOR ][ row ] = user -> getDescription(); const LCDbAnalyser * buddy = LCDbAnalysers::records().findByID( si -> buddyID ); if( buddy == NULL ) grid -> Cells[ MACHINE ][ row ] = ""; else grid -> Cells[ MACHINE ][ row ] = buddy -> getDescription(); } setCount( row ); Screen -> Cursor = crDefault; } //--------------------------------------------------------------------------- void TfrmSessionHistory::setCount( int rows ) { if( rows < 2 ) { grid -> RowCount = 2; for( int i = 0; i < grid -> ColCount; i ++ ) grid -> Cells[ i ][ 1 ] = ""; } else grid -> RowCount = rows; } //---------------------------------------------------------------------------
70b55ef265028e9507e8d5d7c1233610523d59df
a834b70f74642e869d06bd9f2c37ea6070bf48f2
/compile_failed_test/tp2.cpp
78f2d076c8738c4df4a6019035c1a4b18088b02d
[ "MIT" ]
permissive
scisxuepeng/sslink
f18ac1fe437fbc3574c4604ea90386c10fd8365a
29fa9eb96aa9a55cf9c09f47d8b5a739c85a55db
refs/heads/master
2021-01-21T06:39:52.875454
2017-02-27T05:01:51
2017-02-27T05:01:51
83,269,766
0
0
null
null
null
null
UTF-8
C++
false
false
1,379
cpp
/*********************************************** The MIT License (MIT) Copyright (c) 2012 Athrun Arthur <[email protected]> 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 "ff.h" #include <stdio.h> void func() { ff::para<> a; ff::para<> b; a[b].then([](){return 0;}); } int main(int argc, char *argv[]) { func(); return 0; }
f3c31583d441b1f12a8010788e729fae48b1731f
3bd7d50c9f1c13ea60a37f5212483022f4c85bfb
/01/main.cpp
670e5193dc91dd3799883531aea57c01c5be8464
[]
no_license
RomanovaDI/msu_spring_2019
685ce6c832ce12d456d68828a540d06ffdf5a7f7
49d07b5938a757bcfc1af8dc15dfee028112d5a1
refs/heads/master
2020-04-28T23:40:49.184406
2019-03-24T18:50:35
2019-03-24T18:50:35
175,665,247
0
0
null
null
null
null
UTF-8
C++
false
false
989
cpp
#include "numbers.dat" #include <iostream> using namespace std; #define MAX 100000 int isPrimeNumber(int n) { if (n < 2) return 0; if (n == 2) return 1; // 2 - простое if (n % 2 == 0) return 0; // четное -> не простое int d = 3; // начальный делитель while (d * d <= n) { if (n % d == 0) return 0; d += 2; // следующий делитель } return 1; // делителей не найдено -> простое } int main(int argc, char* argv[]) { if ((! (argc % 2)) || (argc < 3)) return -1; for (int i = 1; i < argc; i += 2) { int start = std::atoi(argv[i]); if ((start < 0) || (start > MAX)) return -1; int finish = std::atoi(argv[i + 1]); if ((finish < 0) || (finish > MAX)) return -1; int count = 0; for (int j = 0 ; j < Size; j++) { if (Data[j] < start) continue; if (Data[j] > finish) break; if (isPrimeNumber(Data[j])) count++; } std::cout << count << endl; } return 0; }
c232e0429288fb14763d5978194208664f89064d
5175bd24b43d8db699341997df5fecf21cc7afc1
/libs/asio/test/properties/cpp14/can_prefer_not_preferable_member_prefer.cpp
73312add76e6beb81d7149b7ca0689e527afce79
[ "BSL-1.0", "LicenseRef-scancode-proprietary-license" ]
permissive
quinoacomputing/Boost
59d1dc5ce41f94bbd9575a5f5d7a05e2b0c957bf
8b552d32489ff6a236bc21a5cf2c83a2b933e8f1
refs/heads/master
2023-07-13T08:03:53.949858
2023-06-28T20:18:05
2023-06-28T20:18:05
38,334,936
0
0
BSL-1.0
2018-04-02T14:17:23
2015-06-30T21:50:37
C++
UTF-8
C++
false
false
1,192
cpp
// // cpp14/can_prefer_not_preferable_member_prefer.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2021 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) // #include <boost/asio/prefer.hpp> #include <cassert> template <int> struct prop { template <typename> static constexpr bool is_applicable_property_v = true; static constexpr bool is_preferable = false; }; template <int> struct object { template <int N> constexpr object<N> prefer(prop<N>) const { return object<N>(); } }; int main() { static_assert(!boost::asio::can_prefer_v<object<1>, prop<2>>, ""); static_assert(!boost::asio::can_prefer_v<object<1>, prop<2>, prop<3>>, ""); static_assert(!boost::asio::can_prefer_v<object<1>, prop<2>, prop<3>, prop<4>>, ""); static_assert(!boost::asio::can_prefer_v<const object<1>, prop<2>>, ""); static_assert(!boost::asio::can_prefer_v<const object<1>, prop<2>, prop<3>>, ""); static_assert(!boost::asio::can_prefer_v<const object<1>, prop<2>, prop<3>, prop<4>>, ""); }
328bd183a2e13046c2105b73320bc0347546db7c
c322776b39fd9a7cd993f483a5384b700b0c520e
/glslopt.mod/glslopt/src/glsl/ir_variable_refcount.cpp
951682c13019802c67d888ff09883c8fdffd82ae
[ "MIT" ]
permissive
maxmods/bah.mod
c1af2b009c9f0c41150000aeae3263952787c889
6b7b7cb2565820c287eaff049071dba8588b70f7
refs/heads/master
2023-04-13T10:12:43.196598
2023-04-04T20:54:11
2023-04-04T20:54:11
14,444,179
28
26
null
2021-11-01T06:50:06
2013-11-16T08:29:27
C++
UTF-8
C++
false
false
4,131
cpp
/* * Copyright © 2010 Intel Corporation * * 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 (including the next * paragraph) 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. */ /** * \file ir_variable_refcount.cpp * * Provides a visitor which produces a list of variables referenced, * how many times they were referenced and assigned, and whether they * were defined in the scope. */ #include "ir.h" #include "ir_visitor.h" #include "ir_variable_refcount.h" #include "glsl_types.h" #include "main/hash_table.h" ir_variable_refcount_visitor::ir_variable_refcount_visitor() { this->mem_ctx = ralloc_context(NULL); this->ht = _mesa_hash_table_create(NULL, _mesa_key_pointer_equal); } static void free_entry(struct hash_entry *entry) { ir_variable_refcount_entry *ivre = (ir_variable_refcount_entry *) entry->data; delete ivre; } ir_variable_refcount_visitor::~ir_variable_refcount_visitor() { ralloc_free(this->mem_ctx); _mesa_hash_table_destroy(this->ht, free_entry); } // constructor ir_variable_refcount_entry::ir_variable_refcount_entry(ir_variable *var) { this->var = var; assign = NULL; assigned_count = 0; declaration = false; referenced_count = 0; } ir_variable_refcount_entry * ir_variable_refcount_visitor::get_variable_entry(ir_variable *var) { assert(var); struct hash_entry *e = _mesa_hash_table_search(this->ht, _mesa_hash_pointer(var), var); if (e) return (ir_variable_refcount_entry *)e->data; ir_variable_refcount_entry *entry = new ir_variable_refcount_entry(var); assert(entry->referenced_count == 0); _mesa_hash_table_insert(this->ht, _mesa_hash_pointer(var), var, entry); return entry; } ir_variable_refcount_entry * ir_variable_refcount_visitor::find_variable_entry(ir_variable *var) { assert(var); struct hash_entry *e = _mesa_hash_table_search(this->ht, _mesa_hash_pointer(var), var); if (e) return (ir_variable_refcount_entry *)e->data; return NULL; } ir_visitor_status ir_variable_refcount_visitor::visit(ir_variable *ir) { ir_variable_refcount_entry *entry = this->get_variable_entry(ir); if (entry) entry->declaration = true; return visit_continue; } ir_visitor_status ir_variable_refcount_visitor::visit(ir_dereference_variable *ir) { ir_variable *const var = ir->variable_referenced(); ir_variable_refcount_entry *entry = this->get_variable_entry(var); if (entry) entry->referenced_count++; return visit_continue; } ir_visitor_status ir_variable_refcount_visitor::visit_enter(ir_function_signature *ir) { /* We don't want to descend into the function parameters and * dead-code eliminate them, so just accept the body here. */ visit_list_elements(this, &ir->body); return visit_continue_with_parent; } ir_visitor_status ir_variable_refcount_visitor::visit_leave(ir_assignment *ir) { ir_variable_refcount_entry *entry; entry = this->get_variable_entry(ir->lhs->variable_referenced()); if (entry) { entry->assigned_count++; if (entry->assign == NULL) entry->assign = ir; } return visit_continue; }
[ "woollybah@b77917fb-863c-0410-9a43-030a88dac9d3" ]
woollybah@b77917fb-863c-0410-9a43-030a88dac9d3
019e8b13bf4d6dcb3500cb410484deff7c3bf3b6
aa333e18ea3a527bf75e96666af5d9287d144ac2
/WIFI/TridentTD_Linenotify-3.0.3/TridentTD_Linenotify-3.0.3/src/TridentTD_LineNotify.h
55f49c5b3e01b0c3515cc9e40ee947c8450b6e34
[ "MIT" ]
permissive
japoka410666/NCKU_Intelligent_manager_for_vehicles
458775323c562026df9c9dfa0407ca0810ecd430
ec914e4e1dfa953c04b2a483cb85b42282da09c0
refs/heads/main
2023-06-30T11:30:24.014086
2021-07-25T14:46:00
2021-07-25T14:46:00
371,681,413
0
1
null
null
null
null
UTF-8
C++
false
false
4,674
h
/* [TridentTD] : TridentTD's Esp8266, ESP32 IoT Library TridentTD_LineNotify.h - A simple way to send LINE NOTIFY Version 1.0 03/04/2560 Buddhism Era (2017) by TridentTD Version 1.1 15/02/2561 Buddhism Era (2018) by TridentTD Version 2.0 17/04/2561 Buddhism Era (2018) add notifySticker() and notifyPicure() by TridentTD Version 2.1 17/04/2561 Buddhism Era (2018) clean up code for smaller code by TridentTD Version 2.2 20/07/2561 Buddhism Era (2018) add notify(number) by TridentTD Version 2.3 rename DEBUG_PRINT Version 2.4 06/01/2562 Buddhism Era (2019) support 2.3.0, 2.4.0, 2.4.1, 2.4.2, 2.5.0-rc1, 2.5.0-rc2 ... by TridentTD Version 3.0 10/01/2562 Buddhism Era (2019) support send by imageFile and imageData Version 3.0.1 18/06/2562 Buddhism Era (2019) cleanup '\n' code message ending when sending message Version 3.0.2 07/04/2564 Buddhism Era (2021) support ESP32 version 1.0.5, 1.0.6 Version 3.0.3 18/05/2564 Buddhism Era (2021) support ESP8266 version 3.0.0 ( support all version 2.3.0 - 3.0.0 ) // 2.4.2 - 3.0.0 change to BearSSL Copyright (c) 2016-2021 TridentTD 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. */ #ifndef _TRIDENTTD_LINENOTIFY_H_ #define _TRIDENTTD_LINENOTIFY_H_ #include <Arduino.h> #if defined(ESP8266) #include <ESP8266WiFi.h> #include <FS.h> #elif defined (ESP32) #include <WiFi.h> #include <WiFiClientSecure.h> #include <FS.h> #include <SPIFFS.h> #endif #define LINENOTIFY_DEBUG_MODE 0 #if LINENOTIFY_DEBUG_MODE #define TD_DEBUG_PRINTER Serial #define TD_DEBUG_PRINT(...) { TD_DEBUG_PRINTER.print(__VA_ARGS__); } #define TD_DEBUG_PRINTLN(...) { TD_DEBUG_PRINTER.println(__VA_ARGS__); } #else #define TD_DEBUG_PRINT(...) { } #define TD_DEBUG_PRINTLN(...) { } #endif class TridentTD_LineNotify { public: TridentTD_LineNotify() { } TridentTD_LineNotify(String token) { _token = token; } String getVersion(); void setToken(String token) { _token = token; } void setToken(const char* token) { _token = token; } // LINE notify ด้วย ข้อความ bool notify(const char* message); bool notify(String message); // LINE notify ด้วย ตัวเลข bool notify(float value, uint8_t decimal = 2); bool notify(int value); // LINE notify ด้วย bool notifySticker(String message, int StickerPackageID, int StickerID); bool notifySticker(int StickerPackageID, int StickerID); // ส่ง รูปขึ้น LINE ด้วย url บนรูปบน Internet bool notifyPicture(String message, String picture_url); bool notifyPicture(String picture_url); // ส่ง รูปขึ้น LINE ด้วย file รูปภาพ (jpg/png) ที่อยู่บน SD หรือ SPIFFS ของ ESP8266/ESP32 bool notifyPicture(String message, fs::FS &fs, String path); bool notifyPicture(fs::FS &fs, String path); // ส่ง รูปขึ้น LINE ด้วย image data ESP8266/ESP32 bool notifyPicture(String message, uint8_t* image_data, size_t image_size); bool notifyPicture(uint8_t* image_data, size_t image_size); private: float _version = 3.03; String _token; // bool _notify(String message, int StickerPackageID=0, int StickerID=0, String picture_url=""); bool _notify(String message, int StickerPackageID=0, int StickerID=0, String picture_url="", fs::FS &fs=SPIFFS , String path="", uint8_t* image_data=NULL, size_t image_size=0); }; extern TridentTD_LineNotify LINE; #endif /* _TRIDENTTD_LINENOTIFY_H_ */
01b8474d6bdf18f6183718bbc26f5a6efeb7a7f7
7045bb4f95ada6e1669a3cd9520681b7e548c319
/Meijer/Source/AfxTransBroker/IOLib/IOLibDeviceMgr.h
3427ea028a2ba70cc40c0457f01904b81c29738a
[]
no_license
co185057/MeijerTESTSVN
0ffe207db43c8e881fdbad66c1c058e25fe451f5
3a3df97b2decc1a04e6efe7c8ab74eff5409f39f
refs/heads/master
2023-05-30T00:19:36.524059
2021-06-10T08:41:31
2021-06-10T08:41:31
375,576,064
0
0
null
null
null
null
UTF-8
C++
false
false
2,449
h
///////////////////////////////////////////////////////////////////// // // IOLibDeviceManager // -------------------- // Devices use I/O completion ports for communication, making the architecture // scalable to a large amount of devices. The CIOLib, CIOLibDeviceMgr, // CIOLibDevice and IOLibxxxDevice classes are generic and can be reused in // other projects as deemed necessary. These classes use STL and Win32 APIs exclusively. // NO MFC OBJECTS PLEASE! // // Author: Steve Antonakakis // // History: 04/28/2004 - Initial beta release. // #pragma once class CIOLibDeviceMgr { public: CIOLibDeviceMgr(void); virtual ~CIOLibDeviceMgr(void); CIOLibDevice & CreateDevice(CIOLib::DeviceType dt, long lDeviceID, long lPort, LPCTSTR szSetting = NULL); void WriteData(long lDeviceID, PVOID pvData, DWORD dwSize); virtual void OnDataReadComplete(CIOLibDevice & genDev, const LPVOID pvBuffer, DWORD dwBytesReceived) = 0; virtual void OnDataWriteComplete(CIOLibDevice & genDev) = 0; virtual void OnConnected(CIOLibDevice & genDev) = 0; virtual void OnTrace(CIOLib::TraceType tt, LPCTSTR szMessage) = 0; virtual void RemoveDevice(long lDeviceID); virtual void RemoveAllDevices(void); void PrimeReadData(long); protected: //if lNumThreads > 0, then it specifies the number of threads //if lnNumThreads < 0, then it specifies the number of threads per processor (-) //if lNumThreads == 0, then it defaults to 1 thread void Initialize(long lNumThreads); private: CIOLibDevice *GetDevice(long lDeviceID); std::list<HANDLE> m_listWorkerThreads; CIOLib::HANDLEVECTOR m_vecWorkersComplete; CIOLib::IOLibDEVICEMAP m_mapDevices; DWORD m_dwWorkerThreads; HANDLE m_hCompletionPort; BOOL m_bShuttingDown; CRITICAL_SECTION m_csDevices; BOOL m_bBeingDestructed; void AddDeviceToCompletionPort(CIOLibDevice & genDev); void Trace(CIOLib::TraceType tt, LPCTSTR pszFormat, ...); typedef struct _WORKERTHREADSTRUCT { CIOLibDeviceMgr * pDevMgr; HANDLE hThreadComplete; } WORKERTHREADSTRUCT, *PWORKERTHREADSTRUCT; void WorkerThread(HANDLE hThreadComplete); friend class CIOLibSerialDevice; friend class CIOLibSocketServer; friend class CIOLibSocketClient; friend DWORD WINAPI WorkerThreadProc(LPVOID pDevMgr); };
8f70e3372fdd7c896b4bb603e1d44b86412c43d4
12676cc44aeaf7ae604fdd7d3319052af7d0fbf2
/uva00679.cpp
f407dad45aebd9ae46b9f68e6bbbfc9a11f72522
[]
no_license
BIT-zhaoyang/competitive_programming
e42a50ae88fdd37b085cfaf64285bfd50ef0fbbc
a037dd40fd5665f3248dc9c6ff3254c7ab2addb2
refs/heads/master
2021-04-19T00:02:12.570233
2018-09-01T11:59:44
2018-09-01T11:59:44
51,271,209
1
0
null
null
null
null
UTF-8
C++
false
false
1,450
cpp
#include <bits/stdc++.h> #define _ ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0), cout.precision(15); using namespace std; int main(){ _ int tc; cin >> tc; while(tc--){ int D, I; cin >> D >> I; // same idea but runs slow // find the path consisting of the status of the nodes that the ball visited in the last traverse // vector<int> path(D, 0); // for(int i = 0; i < D; ++i){ // int nRound = (I + pow(2, i)-1) / pow(2, i); // int val = nRound % 2; // path[i] = val; // } // // based on this path we can determine the path of the ball // int curr, origin = 0, at = 1; // for(int i = 0; i < path.size()-1; ++i){ // don't have to consider the last statu // curr = path[i], origin = 1 - curr; // if(origin == 0) at = 2*at; // else at = 2*at + 1; // } // faster solution // 'I' has a special correspondence to the path status // 'I' is like a reverse binary representation of the path. // In normal binary representation, 0 is 00000, but here, 0 is 11111. Then 1 is 00001 but here, 1 is 11110, etc --I; int at = 1; for(int i = 0; i < D-1; ++i){ if(I & (1 << i)) at = 2*at + 1; else at *= 2; } cout << at << endl; } cin >> tc; // read the -1 return 0; }
cfe0511e57e8e18a48ab70aabb8244e2c486dbeb
155e12d1b6e8cacd27d8bd773b592876d8cd9829
/UsualEngineR/Graphics/Raytracing/BLASBuffer.cpp
adca20ee487120125d00227a28d958f28a41b40b
[]
no_license
kokoasann/UsualEngineR
dd6606f72b719ea1e3d684bde59af90f2a981280
cf803f96c3520bd485282c680be29f5248737b26
refs/heads/master
2023-03-07T12:18:52.795038
2021-02-25T17:21:59
2021-02-25T17:21:59
291,441,353
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,995
cpp
#include "PreCompile.h" #include "BLASBuffer.h" namespace UER { namespace raytracing { void BLASBuffer::Init(RenderContext& rc, const std::vector<InstancePtr>& instances) { for (auto& instance : instances) { D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS inputs = {}; inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; inputs.Flags = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_NONE; inputs.NumDescs = 1; inputs.pGeometryDescs = &instance->geometoryDesc; inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; auto d3dDevice = g_graphicsEngine->GetD3DDevice(); D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO info; d3dDevice->GetRaytracingAccelerationStructurePrebuildInfo(&inputs, &info); AccelerationStructureBuffers asbuffer; asbuffer.pScratch = CreateBuffer( d3dDevice, info.ScratchDataSizeInBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COMMON, kDefaultHeapProps); asbuffer.pResult = CreateBuffer( d3dDevice, info.ResultDataMaxSizeInBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE, kDefaultHeapProps); // Create the bottom-level AS D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC asDesc = {}; asDesc.Inputs = inputs; asDesc.DestAccelerationStructureData = asbuffer.pResult->GetGPUVirtualAddress(); asDesc.ScratchAccelerationStructureData = asbuffer.pScratch->GetGPUVirtualAddress(); rc.BuildRaytracingAccelerationStructure(asDesc); //レイトレーシングアクセラレーション構造のビルド完了待ちのバリアを入れる。 D3D12_RESOURCE_BARRIER uavBarrier = {}; uavBarrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; uavBarrier.UAV.pResource = asbuffer.pResult; rc.ResourceBarrier(uavBarrier); m_bottomLevelASBuffers.push_back(std::move(asbuffer)); } } }//namespace raytracing }
b54b662828b01596ce340cdae84b035285be8ef9
2f4789ff9ea1e2894a9e86e1116f67bc94e390cb
/S1_CPP/15_decimal_to_binary.cpp
3202bd3d699c5122c108d30eb77b240887a90721
[]
no_license
varunkverma/cpp_code
a0e2e1183f38ba7c7ed493c6159cce1d55fa8b7b
74291cb0db640254f3fafef5091d6275550cccf6
refs/heads/master
2022-11-23T08:46:54.442468
2020-07-28T11:43:54
2020-07-28T11:43:54
272,623,790
0
0
null
null
null
null
UTF-8
C++
false
false
572
cpp
#include <iostream> #include <algorithm> using namespace std; string convert_decimal_to_binary(long long int deci) { string bin; while (deci) { bin += (char)((deci & 1) + '0'); deci >>= 1; } reverse(bin.begin(), bin.end()); return bin; } int main() { int num1 = 7; int num2 = 8; int num3 = 29; cout << num1 << ": " << convert_decimal_to_binary(num1) << endl; cout << num2 << ": " << convert_decimal_to_binary(num2) << endl; cout << num3 << ": " << convert_decimal_to_binary(num3) << endl; return 0; }
cfdd5bce43bb821a624822b894d45f9b7e19c8f9
687bccfa22d3f0b184bc04b8a4ba4b4b2d5e7a24
/include/agf/renderer/light/PointLight.h
34b380f4b89d898094868eb154472bb1d2f04097
[]
no_license
wilkss/another-game-framework
589d9c81c57be5aac77df997c90f941e0cd54c2e
286b17827c4ee6ee9b795beb77d31e242720e144
refs/heads/master
2020-04-14T13:57:16.490478
2019-01-02T19:58:07
2019-01-02T19:58:07
163,883,554
0
0
null
null
null
null
UTF-8
C++
false
false
1,007
h
#pragma once #include "agf/renderer/light/Light.h" namespace agf { struct Attenuation { float constant; float linear; float quadratic; }; class Framebuffer; class PointLight : public Light { public: PointLight(const glm::vec3& color, unsigned shadowMapSize, const Attenuation& attenuation); ~PointLight(); void Update(Camera* camera) override; inline const Attenuation& GetAttenuation() const { return m_Attenuation; } inline float GetShadowDistance() const { return m_ShadowDistance; } inline Framebuffer* GetShadowFramebuffer() const { return m_ShadowFramebuffer; } inline const glm::mat4& GetShadowMapProjectionMatrix() const { return m_ShadowMapProjectionMatrix; } inline const glm::mat4& GetShadowMapViewMatrix(unsigned f) const { return m_ShadowMapViewMatrices[f]; } private: Attenuation m_Attenuation; float m_ShadowDistance = 25.0f; Framebuffer* m_ShadowFramebuffer; glm::mat4 m_ShadowMapProjectionMatrix; glm::mat4 m_ShadowMapViewMatrices[6]; }; }
2519a75cd96ce2b92107fb539727e6a871f8ff24
daa1e2490c3db49d3a60ebbc24e6823569ef7536
/examples/tutorial/tutorial02.cpp
53e05d50865f60b722b414d55dbd63e91597874f
[ "BSD-3-Clause" ]
permissive
harold-b/daScript
f3d3223277c81ab627da313a8ba9e4e312316a8d
7bbc63e064ee9fee2159f2ef8e7163262eeb89e4
refs/heads/master
2023-02-16T01:53:59.794703
2021-01-04T19:49:05
2021-01-04T19:49:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,186
cpp
#include "daScript/daScript.h" #include "msvc32.inc" using namespace das; // function, which we are going to expose to daScript float xmadd ( float a, float b, float c, float d ) { return a*b + c*d; } // making custom builtin module class Module_Tutorial02 : public Module { public: Module_Tutorial02() : Module("tutorial_02") { // module name, when used from das file ModuleLibrary lib; lib.addModule(this); lib.addBuiltInModule(); // adding constant to the module addConstant(*this,"SQRT2",sqrtf(2.0)); // adding function to the module addExtern<DAS_BIND_FUN(xmadd)>(*this, lib, "xmadd",SideEffects::none, "xmadd"); } }; // registering module, so that its available via 'NEED_MODULE' macro REGISTER_MODULE(Module_Tutorial02); #define TUTORIAL_NAME "/examples/tutorial/tutorial02.das" #include "tutorial.inc" int main( int, char * [] ) { // request all da-script built in modules NEED_ALL_DEFAULT_MODULES; // request our custom module NEED_MODULE(Module_Tutorial02); // run the tutorial tutorial(); // shut-down daScript, free all memory Module::Shutdown(); return 0; }
e95edfb031db610400d9419a2a72d8a5c093af22
04f9d6828588293522ce83fabcf56066fa0bb9a4
/mbed-iot-devkit-sdk/libraries/WiFi/src/AZ3166WiFiClient.cpp
9839cf8f9a77d097b55919596bbf0f2cf117937e
[ "MIT" ]
permissive
badsaarow/mxchip_az3166_firmware
31552ba2b94f30a8485eb6eb56668a889fbec0fd
b0fb6cdd4bb72470494ae7f60dc32badcd95e03c
refs/heads/master
2023-08-25T06:29:35.245467
2023-08-11T02:09:32
2023-08-11T02:09:32
191,081,947
0
0
MIT
2023-08-11T02:09:34
2019-06-10T02:23:17
C
UTF-8
C++
false
false
2,767
cpp
/* * 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 "AZ3166WiFi.h" #include "AZ3166WiFiClient.h" #include "SystemWiFi.h" WiFiClient::WiFiClient() { _pTcpSocket = NULL; _useServerSocket = false; } WiFiClient::WiFiClient(TCPSocket* socket) { _pTcpSocket = socket; _useServerSocket = true; } WiFiClient::~WiFiClient() { stop(); } int WiFiClient::peek() { return 0; } int WiFiClient::connect(const char* host, unsigned short port) { if (_pTcpSocket != NULL) { // Already connected return 0; } _pTcpSocket = new TCPSocket(); if (_pTcpSocket == NULL) { return 0; } if (_pTcpSocket->open(WiFiInterface()) != 0 || _pTcpSocket->connect(host, (uint16_t)port) != 0) { delete _pTcpSocket; _pTcpSocket = NULL; return 0; } _pTcpSocket->set_blocking(false); _pTcpSocket->set_timeout(1000); return 1; } int WiFiClient::connect(IPAddress ip, unsigned short port) { return connect(ip.get_address(), (uint16_t)port); } int WiFiClient::available() { return connected(); } unsigned int WiFiClient::write(unsigned char b) { return write(&b, 1); } unsigned int WiFiClient::write(const unsigned char *buf, unsigned int size) { if (_pTcpSocket != NULL) { return _pTcpSocket->send((void*)buf, (int)size); } return 0; } int WiFiClient::read() { uint8_t ch; int ret = read(&ch, 1); if (ret == 0) { // Connection closed stop(); } if ( ret <= 0 ) return -1; else return (int)ch; } int WiFiClient::read(unsigned char* buf, unsigned int size) { if (_pTcpSocket != NULL) { return _pTcpSocket->recv((void*)buf, (int)size); } return -1; } void WiFiClient::flush() { } void WiFiClient::stop() { if (_pTcpSocket != NULL) { _pTcpSocket->close(); if(!_useServerSocket) { delete _pTcpSocket; _pTcpSocket = NULL; } } } int WiFiClient::connected() { return ( _pTcpSocket == NULL || _pTcpSocket -> send(NULL, 0) == NSAPI_ERROR_NO_SOCKET) ? 0 : 1; } WiFiClient::operator bool() { return ( _pTcpSocket != NULL ) ; }
6669dc7bb3e86a6150a64bdeab0de9d4624f6588
121bc8316f81c94b1dd7c43ddc8291b0f672b2b2
/algo (1).cpp
7eea3336baa065372b8fe7d0573d9cf76a8e16af
[]
no_license
ppatoria/cpp
e05e1bef3cd562d4bc3cbdc254ff5a879f53e8bf
16ae7bf2854bd975aa0c24a0da8d901e9338143d
refs/heads/master
2021-01-10T05:18:38.822420
2016-02-27T20:12:43
2016-02-27T20:12:43
51,691,819
0
0
null
null
null
null
UTF-8
C++
false
false
2,391
cpp
// stl/algo1.cpp #include <algorithm> #include <vector> #include <iostream> using namespace std; int main() { // create vector with elements from 1 to 6 in arbitrary order vector<int> coll = { 2, 5, 4, 1, 6, 3 }; // find and print minimum and maximum elements auto minpos = min_element(coll.cbegin(),coll.cend()); cout << "min: " << *minpos << endl; auto maxpos = max_element(coll.cbegin(),coll.cend()); cout << "max: " << *maxpos << endl; // sort all elements sort (coll.begin(), coll.end()); // find the first element with value 3 // - no cbegin()/cend() be cause later we modify the elements pos3 refers to auto pos3 = find (coll.begin(), coll.end(), // range 3); // value // reverse the order of the found element with value 3 and all following elements reverse (pos3, coll.end()); // print all elements for (auto elem : coll) { cout << elem << ' '; } cout << endl; return 1; } // stl/algo1old.cpp #include <algorithm> #include <vector> #include <iostream> using namespace std; int main() { // create vector with elements from 1 to 6 in arbitrary order vector<int> coll; coll.push_back(2); coll.push_back(5); coll.push_back(4); coll.push_back(1); coll.push_back(6); coll.push_back(3); // find and print minimum and maximum elements vector<int>::const_iterator minpos = min_element(coll.begin(), coll.end()); cout << "min: " << *minpos << endl; vector<int>::const_iterator maxpos = max_element(coll.begin(), coll.end()); cout << "max: " << *maxpos << endl; // sort all elements sort (coll.begin(), coll.end()); // find the first element with value 3 vector<int>::iterator pos3; pos3 = find (coll.begin(), coll.end(), // range 3); // value // reverse the order of the found element with value 3 and all following elements reverse (pos3, coll.end()); // print all elements vector<int>::const_iterator pos; for (pos=coll.begin(); pos!=coll.end(); ++pos) { cout << *pos << ' '; } cout << endl; }
676c4e39898be0283333d04765323f5ea94d5a53
c086d0487a0fa9746580e8f3a8a4b16a8c1ea7f4
/OS/BANKER/banker.cpp
b0fd94a7b17e7bb7e276265907bb42b44a8f525f
[]
no_license
RealYoungk/Dong-A_University.github.io
4d26d563b70335e0036f1d778d5e8fb248d00692
e492afeff9f12826f239e684b65517397ed2deb2
refs/heads/master
2020-08-28T21:22:04.465328
2019-11-05T06:21:16
2019-11-05T06:21:16
217,824,613
1
0
null
null
null
null
UHC
C++
false
false
5,987
cpp
#include<iostream> #include<fstream> #include<string> #include<algorithm> #include<vector> using namespace std; typedef struct Request { string command; int pid; int source[50]; }; ifstream fin("banker.inp"); ofstream fout("banker.out"); int need[50][50], pmax[50][50], alloc[50][50]; int totalAlloc[50], availResource[50]; int resource_num, process_num; int req_index = 0; Request re; vector < Request > wait; vector < Request > req; vector < Request >::iterator iter = req.begin(); void setTotalResource() { // 총 사용 자원 개수 설정 for (int i = 0; i < resource_num; i++) { fin >> availResource[i]; } } void totalSubAlloc() { for (int i = 0; i < resource_num; i++) { availResource[i] -= totalAlloc[i]; } } void setMax() { // 프로세스가 최대 요청 가능한 자원 수 설정 for (int i = 0; i < process_num; i++) { for (int j = 0; j < resource_num; j++) { fin >> pmax[i][j]; } } } void setAlloc() { for (int i = 0; i < process_num; i++) { for (int j = 0; j < resource_num; j++) { fin >> alloc[i][j]; totalAlloc[j] += alloc[i][j]; } } } void renewResource() { for (int i = 0; i < resource_num; i++) { availResource[i] -= totalAlloc[i]; } } void setCommand() { fin >> re.command; fin >> re.pid; for (int i = 0; i < resource_num; i++) { fin >> re.source[i]; } req.push_back(re); } void setNeed() { for (int i = 0; i < process_num; i++) { for (int j = 0; j < resource_num; j++) { need[i][j] = pmax[i][j] - alloc[i][j]; } } } bool isSafe() { bool flag = false; int pid = re.pid; Request confirm_re; int virtual_avail[50]; int virtual_need[50][50]; for (int i = 0; i < resource_num; i++) { virtual_avail[i] = availResource[i]; } for (int i = 0; i < process_num; i++) { for (int j = 0; j < resource_num; j++) { virtual_need[i][j] = need[i][j]; } } // 현재이용가능 자원보다 요청 자원이 더 큰지 확인 for (int i = 0; i < resource_num; i++) { if (re.source[i] > availResource[i]) { return false; } } // 요청을 받아줬다고 가정했을때 // need에 실행 가능한 프로세스 있어야함 // 이 프로세스를 실행했을때 need 확인 if (req[req_index].command == "request") { confirm_re = req[req_index]; // } else if (req[req_index].command == "release") { confirm_re = re; } if (flag == false) { for (int k = 0; k < resource_num; k++) { virtual_avail[k] -= confirm_re.source[k]; virtual_need[confirm_re.pid][k] -= confirm_re.source[k]; } flag = true; } int j; for (int i = 0; i < process_num;i++) { for (j = 0; j < resource_num ; j++) { if (virtual_need[i][j] > virtual_avail[j]) { break; } } if (j == resource_num) { return true; } } return false; } bool isCorrectRequest() { // 필요한 자원보다 큰 요청(잘못된 요청) 거르기 int pid = re.pid; for (int i = 0; i < resource_num; i++) { if (need[pid][i] < re.source[i]) { return false; } } return true; } void pushWait() { wait.push_back(re); } int isPop(int iter=-1) { // wait큐에서 사용할 request가 있으면 wait index return 아니면 -1 Request now_re; for (int j,i = iter + 1; i < wait.size(); i++) { now_re = wait[i]; for (j = 0; j < resource_num; j++) { if (now_re.source[j] > availResource[j]) { break; } } if (j == resource_num) { // 할당할 자원이 충분한경우 return i; // 현재 요청의 wait index를 반환 } } return -1; } void printAvailableResource() { for (int i = 0; i < resource_num; i++) { fout << availResource[i] << ' '; } fout << '\n'; } void allocation() { for (int i = 0; i < resource_num; i++) { // 현재 사용가능 자원에서 추가 사용자원 차감 availResource[i] -= re.source[i]; // 현재 할당된 자원 증가 alloc[re.pid][i] += re.source[i]; // 총 할당 자원 증가 totalAlloc[i] += re.source[i]; } setNeed(); // max - alloc 사용가능한 자원 업데이트 } void returnResource() { for (int i = 0; i < resource_num; i++) { // 현재 사용가능 자원에서 반환받은 자원 추가 availResource[i] += re.source[i]; // 현재 할당된 자원 감소 alloc[re.pid][i] -= re.source[i]; // 총 할당자원 감소 totalAlloc[i] -= re.source[i]; } setNeed(); // max - alloc 사용가능한 자원 업데이트 } void processing() { if (re.command == "request") { // 프로세스가 자원을 요청한 경우 if (!isCorrectRequest()) { // 올바른 요청이 아니므로 종료 printAvailableResource(); } else { // 올바른 요청이 들어왔을때 if (isSafe()) { // 안전상태인경우 allocation(); printAvailableResource(); } else { // 안전 상태가 아닌경우 pushWait(); printAvailableResource(); } } } else if (re.command == "release") { // 프로세스가 자원을 반환한 경우 returnResource(); // 자원을 반환받았는데 큐에서 실행시킬 프로세스가 생겼나? int wait_index = isPop(); while (wait_index != -1) { // 큐에서 실행시킬 프로그램이 있는경우 re = wait[wait_index]; // 요청 불러옴 if (isCorrectRequest()) { if (isSafe()) { allocation(); wait.erase(wait.begin() + wait_index); wait_index--; } } wait_index = isPop(wait_index); } printAvailableResource(); } else { // quit 명령을 받은 경우 return; } } int main() { fin >> process_num >> resource_num; setTotalResource(); setMax(); setAlloc(); setNeed(); totalSubAlloc(); while (true) { setCommand(); if (re.command == "quit") { // quit명령시 종료 break; } } for (int i = 0; i < req.size(); i++) { re = req[i]; processing(); req_index++; } }
0079a2fdde0256e6c01bb342d9cf9560f7cdc270
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/AtCoder/abc116/A/4500616.cpp
9b1556d483b112cd1aded50f4700d41cb96b3b32
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
3,529
cpp
#ifndef _GLIBCXX_NO_ASSERT #include <cassert> #endif #include <cctype> #include <cerrno> #include <cfloat> #include <ciso646> #include <climits> #include <clocale> #include <cmath> #include <csetjmp> #include <csignal> #include <cstdarg> #include <cstddef> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #if __cplusplus >= 201103L #include <ccomplex> #include <cfenv> #include <cinttypes> #include <cstdbool> #include <cstdint> #include <ctgmath> #include <cwchar> #include <cwctype> #endif // C++ #include <algorithm> #include <bitset> #include <complex> #include <deque> #include <exception> #include <fstream> #include <functional> #include <iomanip> #include <ios> #include <iosfwd> #include <iostream> #include <istream> #include <iterator> #include <limits> #include <list> #include <locale> #include <map> #include <memory> #include <new> #include <numeric> #include <ostream> #include <queue> #include <set> #include <sstream> #include <stack> #include <stdexcept> #include <streambuf> #include <string> #include <typeinfo> #include <utility> #include <valarray> #include <vector> #if __cplusplus >= 201103L #include <array> #include <atomic> #include <chrono> #include <condition_variable> #include <forward_list> #include <future> #include <initializer_list> #include <mutex> #include <random> #include <ratio> #include <regex> #include <scoped_allocator> #include <system_error> #include <thread> #include <tuple> #include <typeindex> #include <type_traits> #include <unordered_map> #include <unordered_set> #endif using namespace std; // #define int long long struct Fast {Fast(){std::cin.tie(0);ios::sync_with_stdio(false);}} fast; #define rep(n) for (int i = 0; i < n; ++i) #define all(x) (x).begin(),(x).end() typedef long long ll; typedef unsigned long long ull; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<vvi> vvvi; typedef pair<int, int> pii; typedef double D; typedef complex<D> P; typedef vector<string> vs; #define SZ(x) ((int)(x).size()) #define fill(x,y) memset(x,y,sizeof(x)) // with compile option -DLOCAL #ifdef LOCAL #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define eprintf(...) 42 #endif template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; } template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; } #define pcnt __builtin_popcount #define pcntll __builtin_popcountll #define pb push_back #define mp make_pair #define eb emplace_back #define ALL(v) begin(v), end(v) #define RALL(v) rbegin(v), rend(v) #define F first #define S second #define y0 y3487465 #define y1 y8687969 #define j0 j1347829 #define j1 j234892 #define next asdnext #define prev asdprev inline bool inside(int y, int x, int H, int W) {return y >= 0 && x >= 0 && y < H && x < W;} int qp(int a,ll b){int ans=1;do{if(b&1)ans=1ll*ans*a;a=1ll*a*a;}while(b>>=1);return ans;} int qp(int a,ll b,int mo){int ans=1;do{if(b&1)ans=1ll*ans*a%mo;a=1ll*a*a%mo;}while(b>>=1);return ans;} int gcd(int a,int b){return b?gcd(b,a%b):a;} int dx[4]={1,0,-1,0}; int dy[4]={0,1,0,-1}; #define UNIQUE(v) v.erase( unique(v.begin(), v.end()), v.end() ); const int MOD = 1e9 + 7; const int INF = INT_MAX; signed main() { Fast(); int ab, bc, ca; cin >> ab >> bc >> ca; cout << (ab * bc) / 2.0 << endl; return 0; }
91e66a27e81f6357b334f707525ad2aec47fd48c
767419ca9e6a899d84db512e165c07c5842b6b27
/aurobotservers/trunk/include/urob4/uresclientifvar.h
1cea90dfd08348695086f23aa320dc66a6682a9a
[]
no_license
savnik/LaserNavigation
3bf7a95519456a96b34488cd821d4da4bee3ceed
614fce06425c79e1d7e783aad4bbc97479798a7c
refs/heads/master
2021-01-16T20:55:33.441230
2014-06-26T21:55:19
2014-06-26T21:55:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,751
h
/*************************************************************************** * Copyright (C) 2007 by DTU (Christian Andersen) * [email protected] * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef URESCLIENTIFVAR_H #define URESCLIENTIFVAR_H //#include "uclientfuncbase.h" //#include "uresvarpool.h" #include "uresifbase.h" class UResPoseHist; class USmlTag; /** Handling of messages that should be converted into simple variables in the var pool @author Christian <[email protected]> */ class UResIfVar : public UResIfBase //public UClientFuncBase, public UResVarPool { public: /** Constructor */ UResIfVar(const char * resID) { // set name and version number setResID(resID, 1515); verboseMessages = true; poseHist = NULL; poseUtm = NULL; poseMap = NULL; createVarSpace(5, 0, 0, "Variable related to a server interface client", false); //createBaseVar(); strncpy(tagList, "var", MAX_TAG_LIST_SIZE); }; /** Destructor */ ~UResIfVar(); /** * Static ID for this resource*/ /* static const char * getResClassID() { return "ifVar"; };*/ /** Called by the server core. Should return the name of function. There should be a first short part separated by a space to some additional info (e.g. version and author). The returned name is intended as informative to clients and should include a version number or compile data */ virtual const char * name(); /** Called by the server core when loaded, to get a list of keywords (commands) handled by this plugin. Return a list of handled functions in one string separated by a space (not case sensitive). e.g. return "COG Line". The functions should be unique on the server. */ virtual const char * commandList(); /** * Called by server after this module is integrated into the server core structure, * i.e. all core services are in place, but no commands are serviced for this module yet. * Create any resources that this modules needs and add these to the resource pool * to be integrated in the global variable pool and method sharing. * Remember to add to resource pool by a call to addResource(UResBase * newResource, this). * This module must also ensure that any resources creted are deleted (in the destructor of this class) * Resource shut-down code should be handled in the resource destructor. * \return true if any resources are created. */ virtual void createResources(); /** Create base variables in varPool for this interface type */ void createBaseVar(); /** Called when resource situation has changed. */ virtual bool setResource(UResBase * res, bool remove); /** Test if all needed resources are loaded. 'missingThese is a buffer where missing resources should be written. 'missingTheseCnt' isthe buffer size not to be resexceeded. Should return true if all resources are available. */ //virtual bool gotAllResources(char * missingThese, int missingTheseCnt); /** * New data handled by this object has arrived. Starting with this first tag. * The function should request all data from line until the corresponding end-tag * is received. (no action needed if the tag is a full tag.) */ void handleNewData(USmlTag * tag); /** Add tag type to list of handled tag types */ void addTags(const char * tags); /** Print status for this resource */ virtual char * snprint(const char * preString, char * buff, const int buffCnt); /** Print status for this resource */ virtual const char * print(const char * preString, char * buff, const int buffCnt) { return snprint(preString, buff, buffCnt); }; protected: /** Handle standard variable type tags */ void handleVar(USmlTag * tag); /** Handle pose hist relay messages (from a 'posehistpush i=x cmd="posehist pose"') */ void handlePoseHist(USmlTag * tag); /** Handle other data messages and try to add the result as variables */ void handleOther(USmlTag * tag); protected: /** Pointer to pose history plugin, if such is loaded */ UResPoseHist * poseHist; /** Pointer to pose history plugin for UTM coordinates, if such is loaded */ UResPoseHist * poseUtm; /** Pointer to pose history plugin for map coordinates, if such is loaded */ UResPoseHist * poseMap; private: /** Size of string with tag type names. */ static const int MAX_TAG_LIST_SIZE = 100; /** Tags handled by this function */ char tagList[MAX_TAG_LIST_SIZE]; /** flag for informint possible display function on update */ UVariable * varCallDispOnNewPose; }; #endif
[ "ex25@localhost.(none)" ]
ex25@localhost.(none)
b548e4509bdaa1601e5ccd4782e740b534481158
54bf4b43a580f8bb5c6cb4b96ef92fa0b9d0ee51
/main.cpp
b864dc3ddbfe4f9f5f6e2116cb12967ac102cb22
[]
no_license
CS1103/unidad-1-area-compuesta-JuanGA12
a1b9e21895ca1c549906c228465141b46dc8d8d7
adfce2db412c6726aebd6341796d326cefa1e1e9
refs/heads/master
2022-03-18T19:44:12.720936
2019-08-28T02:58:10
2019-08-28T02:58:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,593
cpp
#include <iostream> #include "Triangulo.h" #include "Rectangulo.h" #include "Circulo.h" #include "Figura.h" using namespace std; int main() { float Centroide_x; float Centroide_y; float base1, base2, altura1, altura2,radio,x1,x2,x3,y1,y2,y3; int verdad1,verdad2,verdad3; //Figura *x = nullptr; //x = new Triangulo(base1,altura1,verdad1,x1,x2); //x->area(); //delete x; //x = nullptr; //Triangulo *T1 = new Triangulo(x1,y1,verdad1,base1,altura1); //cout << "A :"<< T1->area()<<endl; //delete T1; cout << endl; cout << "Bienvenido, por favor seleccione las medidas y las componentes de las siguientes figuras: "<< endl; cout << "Triangulo"<<endl; cout << "Base: "; cin >> base1; cout << "Altura: "; cin >> altura1; cout << "Componente x: "; cin >> x1; cout << "Componente y: "; cin >> y1; cout << "¿Es hueco? (1 = no , 0 = si): "; cin >> verdad1; cout <<".............................."<<endl; cout << "Rectangulo"<<endl; cout << "Base: "; cin >> base2; cout << "Altura: "; cin >> altura2; cout << "Componente x: "; cin >> x2; cout << "Componente y: "; cin >> y2; cout << "¿Es hueco? (1 = no , 0 = si): "; cin >> verdad2; cout <<".............................."<<endl; cout << "Circulo"<<endl; cout << "Radio: "; cin >> radio; cout << "Componente x: "; cin >> x3; cout << "Componente y: "; cin >> y3; cout << "¿Es hueco? (1 = no , 0 = si): "; cin >> verdad3; cout <<".............................."<<endl; Triangulo Triangulo1; Triangulo1.setverdad(verdad1);//el objeto.setverdad va a validar si la figura se suma o se resta, si es 1, la figura se suma, si es 0 la figura se resta(se toma como hueca) Triangulo1.setbase(base1); Triangulo1.setaltura(altura1); Triangulo1.setx(x1); Triangulo1.sety(y1); cout << "Area del triangulo es: " << Triangulo1.area()<<endl; cout << "Area por x " << Triangulo1.area_por_x()<<endl; cout << "Area por y " << Triangulo1.area_por_y()<<endl; Rectangulo Rectangulo1; Rectangulo1.setverdad(verdad2); Rectangulo1.setbase(base2); Rectangulo1.setaltura(altura2); Rectangulo1.setx(x2); Rectangulo1.sety(y2); cout << "Area del rectangulo es: " << Rectangulo1.area()<<endl; cout << "Area por x " << Rectangulo1.area_por_x()<<endl; cout << "Area por y " << Rectangulo1.area_por_y()<<endl; Circulo Circulo1; Circulo1.setverdad(verdad3); Circulo1.setradio(radio); Circulo1.setx(x3); Circulo1.sety(y3); cout << "Area del circulo es: " << Circulo1.area()<<endl;// No existe area negativa pero para fines del problema si se va a restar la figura, se va a poner que el area es negativa. cout << "Area por x " << Circulo1.area_por_x()<<endl; cout << "Area por y " << Circulo1.area_por_y()<<endl; Centroide_x = ( ( Triangulo1.area_por_x() + Rectangulo1.area_por_x() + Circulo1.area_por_x() ) / ( Triangulo1.area() + Rectangulo1.area() + Circulo1.area() ) ); Centroide_y = ( ( Triangulo1.area_por_y() + Rectangulo1.area_por_y() + Circulo1.area_por_y() ) / ( Triangulo1.area() + Rectangulo1.area() + Circulo1.area() ) ); cout << "El centroide de la figura esta en el punto ( " << Centroide_x<< " , " << Centroide_y << " )" << endl; //Circulo1.~Circulo();// si se usa stack, el destructor se llama solo, llamarlo manualmente como este caso no es muy comun. //Rectangulo1.~Rectangulo(); //Triangulo1.~Triangulo(); return 0; }
b1ce9b95e63af72e41ba95af61ee82556d32f457
f8b35da33f4308139a6c5ca55f9eaa0cc33676e9
/tutorialApp/Classes/AppDelegate.h
c5cdc510fa119bf0a5b31257ebfe562cfa364d8d
[]
no_license
bacph178/tutorialApp
574311dce71b1cdab3b8f3f039b02e992daeb9f8
7231cd0dbbd9afd5dd7f61ebee88d413dc5681d0
refs/heads/master
2021-03-13T00:01:59.501973
2013-06-07T10:46:46
2013-06-07T10:46:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,152
h
// // tutorialAppAppDelegate.h // tutorialApp // // Created by macbook_016 on 2013/06/07. // Copyright __MyCompanyName__ 2013年. All rights reserved. // #ifndef _APP_DELEGATE_H_ #define _APP_DELEGATE_H_ #include "CCApplication.h" /** @brief The cocos2d Application. The reason to implement with private inheritance is to hide some interface details of CCDirector. */ class AppDelegate : private cocos2d::CCApplication { public: AppDelegate(); virtual ~AppDelegate(); /** @brief Implement CCDirector and CCScene init code here. @return true Initialize success, app continue. @return false Initialize failed, app terminate. */ virtual bool applicationDidFinishLaunching(); /** @brief The function is called when the application enters the background @param the pointer of the application instance */ virtual void applicationDidEnterBackground(); /** @brief The function is called when the application enters the foreground @param the pointer of the application instance */ virtual void applicationWillEnterForeground(); }; #endif // _APP_DELEGATE_H_
bdc5e778c59722418dd2ccfde5abd60b903e6c9e
d147941b964174578cedc1a54a783f6657d33081
/DAQ/DAQdesign/ip/DAQdesign_xlconstant_1_0/sim/DAQdesign_xlconstant_1_0.h
a5cbcaf3132af31a4bff3cb7e33bc138da3c0c1d
[]
no_license
pratikto/High-Speed-Measurement-Unit
48fa5ea48386bda9a8b32c4427d0d3e7187bd28b
8ee34042dfb7f94dc1f7fe7ec160e3f67364bad7
refs/heads/master
2022-12-04T05:15:17.065065
2020-08-26T10:20:21
2020-08-26T10:20:21
280,585,533
0
0
null
null
null
null
UTF-8
C++
false
false
2,631
h
// (c) Copyright 1995-2014 Xilinx, Inc. All rights reserved. // // This file contains confidential and proprietary information // of Xilinx, Inc. and is protected under U.S. and // international copyright and other intellectual property // laws. // // DISCLAIMER // This disclaimer is not a license and does not grant any // rights to the materials distributed herewith. Except as // otherwise provided in a valid license issued to you by // Xilinx, and to the maximum extent permitted by applicable // law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND // WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES // AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING // BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- // INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and // (2) Xilinx shall not be liable (whether in contract or tort, // including negligence, or under any other theory of // liability) for any loss or damage of any kind or nature // related to, arising under or in connection with these // materials, including for any direct, or any indirect, // special, incidental, or consequential loss or damage // (including loss of data, profits, goodwill, or any type of // loss or damage suffered as a result of any action brought // by a third party) even if such damage or loss was // reasonably foreseeable or Xilinx had been advised of the // possibility of the same. // // CRITICAL APPLICATIONS // Xilinx products are not designed or intended to be fail- // safe, or for use in any application requiring fail-safe // performance, such as life-support or safety devices or // systems, Class III medical devices, nuclear facilities, // applications related to the deployment of airbags, or any // other applications that could lead to death, personal // injury, or severe property or environmental damage // (individually and collectively, "Critical // Applications"). Customer assumes the sole risk and // liability of any use of Xilinx products in Critical // Applications, subject only to applicable laws and // regulations governing limitations on product liability. // // THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS // PART OF THIS FILE AT ALL TIMES. // // DO NOT MODIFY THIS FILE. // IP VLNV: xilinx.com:ip:xlconstant:1.1 // IP Revision: 1 #ifndef _DAQdesign_xlconstant_1_0_H_ #define _DAQdesign_xlconstant_1_0_H_ #include "xlconstant_v1_1_7.h" #include "systemc.h" class DAQdesign_xlconstant_1_0 : public sc_module { public: xlconstant_v1_1_7<16,0X0001> mod; sc_out< sc_bv<16> > dout; DAQdesign_xlconstant_1_0 (sc_core::sc_module_name name); }; #endif
ac3b9ff4c8cf6af90af65300685a7012e953c32f
0c117a5e7faaaade9ce1bb5fda6b7272930c5320
/Shooty/CircleBullet.h
e125e2045bc90739a5e7a5fd14bb8a53251a7630
[]
no_license
Lurgypai/Shooty
2bed6d349e62bd1fdb0db9c12e8bf053960e2725
143f3599f5ca42dc4793b36271ec1da6613659f1
refs/heads/master
2021-10-16T15:55:12.785260
2019-02-11T23:44:41
2019-02-11T23:44:41
110,046,936
0
0
null
null
null
null
UTF-8
C++
false
false
593
h
#pragma once #include "stdafx.h" #include "BulletBase.h" #include "EntityPlayer.h" class CircleBullet : public Bullet { private: bool canHit; float expandingSpeed; sf::CircleShape circle; public: CircleBullet(void); CircleBullet(float angle, sf::Vector2f position); float getExpandSpeed() const; bool getCanHit() const; void setExpandSpeed(float speed_); void setCanHit(bool canHit_); sf::CircleShape* getSprite(); sf::CircleShape* getDrawable(); sf::CircleShape* getTransformable(); void load(); void update(sf::RenderWindow& window, const Arena& arena, Player* player); };
b954918d0e1e9787a47b8a799311b12df9ee6885
9d9e354d378ad272194a529b667f19da2014c330
/practice/FizzBuzz.cpp
cdff28bde0f2186ae555639fadcc0530f7d423d7
[]
no_license
Ta-SeenJunaid/Data-Structures-and-Algorithm
e5ebd234b6266b2342d173128becc74c26824634
7d0619bba7f5624cda8d247a0953d9c0466a2b9a
refs/heads/master
2023-08-15T11:29:06.997531
2023-07-29T10:46:51
2023-07-29T10:46:51
150,042,053
0
0
null
null
null
null
UTF-8
C++
false
false
647
cpp
/*Write a short program that prints each number from 1 to 100 on a new line. For each multiple of 3, print "Fizz" instead of the number. For each multiple of 5, print "Buzz" instead of the number. For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.*/ #include <bits/stdc++.h> using namespace std; int main() { for(int i=1; i<=100; i++) { if((i%3 == 0) && (i%5 == 0)) printf("FizzBuzz\n"); else if (i%3==0) printf("Fizz\n"); else if (i%5==0) printf("Buzz\n"); else printf("%d\n",i); } }
d0d67960aae2d68643068855c80d52a31eb38134
67a8c824902b83f76daf5075e5ddb730980a15e8
/RevivalPlus/weapons/@Attachments/config.cpp
dcfd31b6fbc6207371084206ca9977155dd11601
[ "MIT" ]
permissive
benedikz/RevivalPlus
8004e8ec5f0f9369957e3c412e8afc49626f8397
b51d90ede21f457d78aba8e175e7c9463678cac1
refs/heads/master
2023-07-16T07:20:50.675598
2021-09-06T22:26:11
2021-09-06T22:26:11
294,627,453
0
0
null
null
null
null
UTF-8
C++
false
false
4,291
cpp
class CfgPatches { class RPL_Weapons_Attachments { units[] = {}; weapons[] = {}; requiredVersion = 0.1; requiredAddons[] = { "DZ_Data", "DZ_Weapons_Firearms" }; }; }; class CfgVehicles { // Rifle Buttstocks class AK_WoodBttstck; class RPL_AK_WoodBttstck_PaintBase : AK_WoodBttstck { scope = 0; }; class RPL_AK_WoodBttstck_Black : RPL_AK_WoodBttstck_PaintBase { scope = 2; color = "Black"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\AK\data\akm_wood_black_co.paa"}; }; class RPL_AK_WoodBttstck_Olive : RPL_AK_WoodBttstck_PaintBase { scope = 2; color = "Olive"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\AK\data\akm_wood_olive_co.paa"}; }; class RPL_AK_WoodBttstck_DarkTan : RPL_AK_WoodBttstck_PaintBase { scope = 2; color = "DarkTan"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\AK\data\akm_wood_darktan_co.paa"}; }; class RPL_AK_WoodBttstck_White : RPL_AK_WoodBttstck_PaintBase { scope = 2; color = "White"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\AK\data\akm_wood_white_co.paa"}; }; class AK74_WoodBttstck; class RPL_AK74_WoodBttstck_PaintBase : AK74_WoodBttstck { scope = 0; hiddenSelections[] = {"camo"}; hiddenSelectionsTextures[] = {""}; hiddenSelectionsMaterials[] = {""}; }; class RPL_AK74_WoodBttstck_Black : RPL_AK74_WoodBttstck_PaintBase { scope = 2; color = "Black"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\AK74\data\ak74_wood_black_co.paa"}; }; class RPL_AK74_WoodBttstck_Olive : RPL_AK74_WoodBttstck_PaintBase { scope = 2; color = "Olive"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\AK74\data\ak74_wood_olive_co.paa"}; }; class RPL_AK74_WoodBttstck_DarkTan : RPL_AK74_WoodBttstck_PaintBase { scope = 2; color = "DarkTan"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\AK74\data\ak74_wood_darktan_co.paa"}; }; class RPL_AK74_WoodBttstck_White : RPL_AK74_WoodBttstck_PaintBase { scope = 2; color = "White"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\AK74\data\ak74_wood_white_co.paa"}; }; class Fal_OeBttstck; class RPL_Fal_OeBttstck_PaintBase : Fal_OeBttstck { scope = 0; color = ""; hiddenSelections[] = {"camo"}; hiddenSelectionsTextures[] = {""}; hiddenSelectionsMaterials[] = {""}; }; class RPL_Fal_OeBttstck_Black : RPL_Fal_OeBttstck_PaintBase { scope = 2; color = "Black"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\FAL\data\fal_stock_oe_black_co.paa"}; }; class RPL_Fal_OeBttstck_Olive : RPL_Fal_OeBttstck_PaintBase { scope = 2; color = "Olive"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\FAL\data\fal_stock_oe_olive_co.paa"}; }; class RPL_Fal_OeBttstck_DarkTan : RPL_Fal_OeBttstck_PaintBase { scope = 2; color = "DarkTan"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\FAL\data\fal_stock_oe_darktan_co.paa"}; }; class RPL_Fal_OeBttstck_White : RPL_Fal_OeBttstck_PaintBase { scope = 2; color = "White"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\FAL\data\fal_stock_oe_white_co.paa"}; }; // Rifle Handguards class AK_WoodHndgrd; class RPL_AK_WoodHndgrd_PaintBase : AK_WoodHndgrd { scope = 0; }; class RPL_AK_WoodHndgrd_Black : RPL_AK_WoodHndgrd_PaintBase { scope = 2; color = "Black"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\AK\data\akm_wood_black_co.paa"}; }; class RPL_AK_WoodHndgrd_Olive : RPL_AK_WoodHndgrd_PaintBase { scope = 2; color = "Olive"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\AK\data\akm_wood_olive_co.paa"}; }; class RPL_AK_WoodHndgrd_DarkTan : RPL_AK_WoodHndgrd_PaintBase { scope = 2; color = "DarkTan"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\AK\data\akm_wood_darktan_co.paa"}; }; class RPL_AK_WoodHndgrd_White : RPL_AK_WoodHndgrd_PaintBase { scope = 2; color = "White"; hiddenSelectionsTextures[] = {"RevivalPlus\weapons\@Attachments\AK\data\akm_wood_white_co.paa"}; }; };
8e04e2c65198c64fc812b6956fb5c80d38462d73
0fe27e6c63a755fe7df003f36acc079490a338f3
/src/cpp/Relative-Sort-Array.cpp
ef6414c2cf303d71f0ec52508fcacc8670d9c717
[]
no_license
Finalcheat/leetcode
83f9ceb7bd10783554133434347803a41260a713
985deb6142c6841aa7025c9b582010b33f694e6c
refs/heads/master
2022-11-11T22:51:42.666150
2022-11-05T03:07:31
2022-11-05T03:07:31
53,241,690
2
1
null
null
null
null
UTF-8
C++
false
false
1,517
cpp
/** * @file Relative-Sort-Array.cpp * @brief 相对排序数组(https://leetcode.com/problems/relative-sort-array/) * @author Finalcheat * @date 2019-09-21 */ /** * Given two arrays arr1 and arr2, the elements of arr2 are distinct, and all elements in arr2 are also in arr1. * Sort the elements of arr1 such that the relative ordering of items in arr1 are the same as in arr2. Elements that don't appear in arr2 should be placed at the end of arr1 in ascending order. * Example 1: * Input: arr1 = [2,3,1,3,2,4,6,7,9,2,19], arr2 = [2,1,4,3,9,6] * Output: [2,2,2,1,4,3,3,9,6,7,19] */ /** * 使用hashtable作为辅助结构记录元素相对顺序,然后写排序比较函数即可。 */ class Solution { public: vector<int> relativeSortArray(vector<int>& arr1, vector<int>& arr2) { std::unordered_map<int, size_t> u; for (size_t i = 0; i < arr2.size(); ++i) { u[arr2[i]] = i; } std::sort(arr1.begin(), arr1.end(), [&](const int& l, const int& r) { const auto iterL = u.find(l); const auto iterR = u.find(r); if (iterL == u.end() && iterR == u.end()) { return l <= r; } else if (iterL == u.end()) { return false; } else if (iterR == u.end()) { return true; } return iterL->second <= iterR->second; }); return arr1; } };
08653e7efddeb8f09e0f5f8f566328028e257aa0
1fc09ef8c0ec74e24f712e390b92448eddc94119
/apps/wavelet2d/daubechies_generator.cpp
c495f2f9788f6996bd8da7f1cedf0680a6da3cfc
[ "BSD-3-Clause", "MIT", "LicenseRef-scancode-blas-2017", "Apache-2.0" ]
permissive
tufei/Halide
8c644bfbf375dafcd0e84a7665a760a6d2998006
624a3d26edab1b196ae0a6e7421752ea6e002375
refs/heads/master
2022-09-12T11:30:50.603032
2022-08-27T18:23:50
2022-08-27T18:23:50
118,275,351
0
1
null
2018-01-20T19:48:09
2018-01-20T19:48:08
null
UTF-8
C++
false
false
1,483
cpp
#include "Halide.h" #include "daubechies_constants.h" namespace { Halide::Var x("x"), y("y"), c("c"); class daubechies : public Halide::Generator<daubechies> { public: Input<Buffer<float>> in_{"in", 2}; Output<Buffer<float>> out_{"out", 3}; void generate() { Func in = Halide::BoundaryConditions::repeat_edge(in_); Func mid; mid(x, y, c) = mux(c, {D0 * in(2 * x - 1, y) + D1 * in(2 * x, y) + D2 * in(2 * x + 1, y) + D3 * in(2 * x + 2, y), D3 * in(2 * x - 1, y) - D2 * in(2 * x, y) + D1 * in(2 * x + 1, y) - D0 * in(2 * x + 2, y)}); out_(x, y, c) = mux(c, {D0 * mid(x, 2 * y - 1, 0) + D1 * mid(x, 2 * y, 0) + D2 * mid(x, 2 * y + 1, 0) + D3 * mid(x, 2 * y + 2, 0), D0 * mid(x, 2 * y - 1, 1) + D1 * mid(x, 2 * y, 1) + D2 * mid(x, 2 * y + 1, 1) + D3 * mid(x, 2 * y + 2, 1), D3 * mid(x, 2 * y - 1, 0) - D2 * mid(x, 2 * y, 0) + D1 * mid(x, 2 * y + 1, 0) - D0 * mid(x, 2 * y + 2, 0), D3 * mid(x, 2 * y - 1, 1) - D2 * mid(x, 2 * y, 1) + D1 * mid(x, 2 * y + 1, 1) - D0 * mid(x, 2 * y + 2, 1)}); out_.unroll(c, 4); } }; } // namespace HALIDE_REGISTER_GENERATOR(daubechies, daubechies)
a754d893d6f271e8f5b04d215423cb4807f53c00
4fd05729855c323116fbedf7e85634955d4c20d0
/devel/.private/mavros_msgs/include/mavros_msgs/LogRequestListRequest.h
1a9b88a312ccc51b74c40c6fbdfbab2cdea6f5e9
[]
no_license
zhenyibi/my-profile
3b588b68b0a67a2bbe3a463f6e494b8b433fa03e
1367ff0e67eb0a6638a4c2e4e146e52e205bfcf7
refs/heads/master
2020-11-27T09:07:30.023512
2019-12-21T06:05:18
2019-12-21T06:05:29
229,378,411
0
0
null
null
null
null
UTF-8
C++
false
false
5,702
h
// Generated by gencpp from file mavros_msgs/LogRequestListRequest.msg // DO NOT EDIT! #ifndef MAVROS_MSGS_MESSAGE_LOGREQUESTLISTREQUEST_H #define MAVROS_MSGS_MESSAGE_LOGREQUESTLISTREQUEST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace mavros_msgs { template <class ContainerAllocator> struct LogRequestListRequest_ { typedef LogRequestListRequest_<ContainerAllocator> Type; LogRequestListRequest_() : start(0) , end(0) { } LogRequestListRequest_(const ContainerAllocator& _alloc) : start(0) , end(0) { (void)_alloc; } typedef uint16_t _start_type; _start_type start; typedef uint16_t _end_type; _end_type end; typedef boost::shared_ptr< ::mavros_msgs::LogRequestListRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::mavros_msgs::LogRequestListRequest_<ContainerAllocator> const> ConstPtr; }; // struct LogRequestListRequest_ typedef ::mavros_msgs::LogRequestListRequest_<std::allocator<void> > LogRequestListRequest; typedef boost::shared_ptr< ::mavros_msgs::LogRequestListRequest > LogRequestListRequestPtr; typedef boost::shared_ptr< ::mavros_msgs::LogRequestListRequest const> LogRequestListRequestConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::mavros_msgs::LogRequestListRequest_<ContainerAllocator> & v) { ros::message_operations::Printer< ::mavros_msgs::LogRequestListRequest_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace mavros_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'geographic_msgs': ['/opt/ros/kinetic/share/geographic_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'mavros_msgs': ['/home/maybe/ros_ws/src/mavros/mavros_msgs/msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'uuid_msgs': ['/opt/ros/kinetic/share/uuid_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::mavros_msgs::LogRequestListRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::mavros_msgs::LogRequestListRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::mavros_msgs::LogRequestListRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::mavros_msgs::LogRequestListRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::mavros_msgs::LogRequestListRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::mavros_msgs::LogRequestListRequest_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::mavros_msgs::LogRequestListRequest_<ContainerAllocator> > { static const char* value() { return "43d5acd48e3ef1843fa7f45876501c02"; } static const char* value(const ::mavros_msgs::LogRequestListRequest_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x43d5acd48e3ef184ULL; static const uint64_t static_value2 = 0x3fa7f45876501c02ULL; }; template<class ContainerAllocator> struct DataType< ::mavros_msgs::LogRequestListRequest_<ContainerAllocator> > { static const char* value() { return "mavros_msgs/LogRequestListRequest"; } static const char* value(const ::mavros_msgs::LogRequestListRequest_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::mavros_msgs::LogRequestListRequest_<ContainerAllocator> > { static const char* value() { return "\n\ \n\ \n\ \n\ \n\ uint16 start\n\ uint16 end\n\ "; } static const char* value(const ::mavros_msgs::LogRequestListRequest_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::mavros_msgs::LogRequestListRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.start); stream.next(m.end); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct LogRequestListRequest_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::mavros_msgs::LogRequestListRequest_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::mavros_msgs::LogRequestListRequest_<ContainerAllocator>& v) { s << indent << "start: "; Printer<uint16_t>::stream(s, indent + " ", v.start); s << indent << "end: "; Printer<uint16_t>::stream(s, indent + " ", v.end); } }; } // namespace message_operations } // namespace ros #endif // MAVROS_MSGS_MESSAGE_LOGREQUESTLISTREQUEST_H
a9ac265dbe349a9109fad9b8130296b158a84da2
6e89098eabc4713a81d6ee8686e6c392760236f0
/src/timedata.cpp
fe638c52e742ea06c029c53e860148ab49114e03
[ "MIT" ]
permissive
15364097026/russellcoin-1
57c5e6a8becfcd17fd98deb3cc07413100edfbc7
631a6403af5ea54adf0b276cc537473430019f7d
refs/heads/master
2020-09-08T09:10:43.327474
2019-11-08T06:31:21
2019-11-08T06:31:21
221,089,041
1
0
MIT
2019-11-11T23:30:47
2019-11-11T23:30:47
null
UTF-8
C++
false
false
3,655
cpp
// Copyright (c) 2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "timedata.h" #include "netbase.h" #include "sync.h" #include "ui_interface.h" #include "util.h" #include "utilstrencodings.h" #include <boost/foreach.hpp> using namespace std; static CCriticalSection cs_nTimeOffset; static int64_t nTimeOffset = 0; /** * "Never go to sea with two chronometers; take one or three." * Our three time sources are: * - System clock * - Median of other nodes clocks * - The user (asking the user to fix the system clock if the first two disagree) */ int64_t GetTimeOffset() { LOCK(cs_nTimeOffset); return nTimeOffset; } int64_t GetAdjustedTime() { return GetTime() + GetTimeOffset(); } static int64_t abs64(int64_t n) { return (n >= 0 ? n : -n); } void AddTimeData(const CNetAddr& ip, int64_t nTime) { int64_t nOffsetSample = nTime - GetTime(); LOCK(cs_nTimeOffset); // Ignore duplicates static set<CNetAddr> setKnown; if (!setKnown.insert(ip).second) return; // Add data static CMedianFilter<int64_t> vTimeOffsets(200,0); vTimeOffsets.input(nOffsetSample); LogPrintf("Added time data, samples %d, offset %+d (%+d minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60); // There is a known issue here (see issue #4521): // // - The structure vTimeOffsets contains up to 200 elements, after which // any new element added to it will not increase its size, replacing the // oldest element. // // - The condition to update nTimeOffset includes checking whether the // number of elements in vTimeOffsets is odd, which will never happen after // there are 200 elements. // // But in this case the 'bug' is protective against some attacks, and may // actually explain why we've never seen attacks which manipulate the // clock offset. // // So we should hold off on fixing this and clean it up as part of // a timing cleanup that strengthens it in a number of other ways. // if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1) { int64_t nMedian = vTimeOffsets.median(); std::vector<int64_t> vSorted = vTimeOffsets.sorted(); // Only let other nodes change our time by so much if (abs64(nMedian) < 70 * 60) { nTimeOffset = nMedian; } else { nTimeOffset = 0; static bool fDone; if (!fDone) { // If nobody has a time different than ours but within 5 minutes of ours, give a warning bool fMatch = false; BOOST_FOREACH(int64_t nOffset, vSorted) if (nOffset != 0 && abs64(nOffset) < 5 * 60) fMatch = true; if (!fMatch) { fDone = true; string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong Dash Core will not work properly."); strMiscWarning = strMessage; LogPrintf("*** %s\n", strMessage); uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING); } } } if (fDebug) { BOOST_FOREACH(int64_t n, vSorted) LogPrintf("%+d ", n); LogPrintf("| "); } LogPrintf("nTimeOffset = %+d (%+d minutes)\n", nTimeOffset, nTimeOffset/60); } }
9076d4b6d4f4e597e15b0b37ce2240007863e507
1237bff76137031b8c1cafb8345f1232fcbf613b
/View/front_graphic.cpp
f0085fc88189e3c77a9f9f7eccc0bfab0f73fe81
[]
no_license
DamienCg/Calculator-Kalk-QT
9bf2b3c18f64a3c3175dc96eda9668e418d79ea7
fba0f1e4bd48e99473e1ab4ed16b3f11f11a5023
refs/heads/master
2022-06-28T17:09:16.773632
2020-11-05T18:30:19
2020-11-05T18:30:19
124,523,203
0
0
null
null
null
null
UTF-8
C++
false
false
2,605
cpp
#include "front_graphic.h" #include <QStackedWidget> #include <QMessageBox> #include <QVBoxLayout> void Front_graphic::OpenTypes(int a){ if( a != windowIndex) listatipi->switchToType(windowIndex); Stack->setCurrentIndex(a); } void Front_graphic::setWindowIndex(int i){ windowIndex = i; listatipi->switchToType(i); } void Front_graphic::setController(const Controller & c){ ctrl = c; } Front_graphic::Front_graphic(QStackedWidget* stack, QWidget *parent, Controller c): QWidget(parent), listatipi(new Choose_Type(this)), Stack(stack), mex(new QMessageBox(this)), layout(new QVBoxLayout(this)), ctrl(c){ layout->addWidget(listatipi,0,Qt::AlignTop); setWindowTitle("Kalk"); setLayout(layout); setStyleSheet(" QPushButton{background-color: #10AE5F; border-radius: 6px; height: 25px; color: black; border: 1px solid;}" " QLabel{color: white;}" " QLineEdit{background-color: #e6f3ff ; border-radius: 6px; height: 25px; color: black; border: 2px solid;}" ); connect(listatipi, SIGNAL(emetti(int)), this, SLOT(OpenTypes(int))); } bool Front_graphic::checkBeforeContinue(const QString & op1, const QString & op2, const QString & op)const{ if(op1 == "" && op2 ==""){ showMessagebox("No campi vuoti!"); return false; } else if(((op2.indexOf(QRegExp("^0+$"), 0) != -1) || op2=="" ) && op == "/"){ showMessagebox("Division By Zero!"); return false; } return true; } void Front_graphic::showMessagebox(const QString & x) const{ mex->setStyleSheet("color: black;"); mex->setText(x); mex->button(QMessageBox::Ok); mex->show(); } void Front_graphic::addLayout(QWidget* p, int stretch){ layout->addWidget(p,stretch,Qt::AlignTop); } QString Front_graphic::frontcalcolaoperazioniprimarie(const QString & op1, const QString & op2, const QString & op){ if(checkBeforeContinue(op1,op2,op)) return ctrl.CostruisciEcalcolaEConvertiop1op2(op1,op2,op); return QString(); } QString Front_graphic::frontcalcolaconversionetoType(const QString& input, const QString & op){ QString x = ""; if(op == "Bin") x = ctrl.CalcolatoOtherTypes(input,'B'); else if(op == "Hex") x = ctrl.CalcolatoOtherTypes(input,'H'); else if(op == "Oct") x = ctrl.CalcolatoOtherTypes(input,'O'); else if(op == "Dec") x = ctrl.CostruisciEcalcolaConversioneTtoD(input); else x = ctrl.CotruisciECalcolaRadice(input); return x; }
9503d7f36b3347fc6e7f91ee804c33366c20c6e6
9a43eaa182541cbd05415d6ca2e408c801b94e5e
/Apps/CustomModuleTest/Source/MainWindow.cpp
d032efda75f8c101f04e95d4ae2b35c0565dcab3
[]
no_license
LeoFabre/Juce_vst_tests
0e1e0eb3414391f68bcde32664ceb40354202ed5
dcc8014bc7c29a1bba628b0e2a25f9394ae98925
refs/heads/master
2023-06-16T07:16:24.783341
2021-07-08T13:14:59
2021-07-08T13:14:59
359,187,798
0
0
null
null
null
null
UTF-8
C++
false
false
815
cpp
#include "MainWindow.h" namespace Omni { constexpr bool isMobile() { #if JUCE_IOS || JUCE_ANDROID return true; #else return false; #endif } MainWindow::MainWindow(const String& name) : DocumentWindow(name, getBackgroundColour(), allButtons) { setUsingNativeTitleBar(true); setContentOwned(new MainComponent(), true); if (isMobile()) setFullScreen(true); else { setResizable(true, true); centreWithSize(getWidth(), getHeight()); } setVisible(true); } void MainWindow::closeButtonPressed() { juce::JUCEApplication::getInstance()->systemRequestedQuit(); } Colour MainWindow::getBackgroundColour() { return juce::Desktop::getInstance().getDefaultLookAndFeel().findColour( ResizableWindow::backgroundColourId); } } // namespace Omni
028065e305d65ae125e536f19cc6a001f66d8091
15d8fe4a6858378e350b9df832062bc2050a75ce
/014-normals-diffuse-lighting/014-normals-diffuse-lighting.h
1abd7587fe9ad0cd8c3334a9753ec02c70c72525
[ "MIT" ]
permissive
michalbb1/opengl4-tutorials-mbsoftworks
cdf6ea187914792f237e4f4c60194d40472ade60
85909d0d22f51a4ebff5f22ac3f7456d77a6058a
refs/heads/dev
2022-11-05T09:27:03.270344
2022-10-29T05:14:35
2022-10-29T05:14:35
123,883,165
71
21
MIT
2022-10-29T05:14:36
2018-03-05T07:43:53
C++
UTF-8
C++
false
false
383
h
#pragma once // Project #include "../common_classes/OpenGLWindow.h" namespace opengl4_mbsoftworks { namespace tutorial014 { class OpenGLWindow014 : public OpenGLWindow { public: void initializeScene() override; void renderScene() override; void updateScene() override; void releaseScene() override; }; } // namespace tutorial014 } // namespace opengl4_mbsoftworks
7e2852cac2c88cc8605353d8c118a03fcf77b7cc
035c23cff67a9e0fdce3d9a021807697fe266883
/common/tunicate/rootparitycollisiontest.cpp
76793a8019a202bb4afdb4525c03465f62adb819
[ "BSD-2-Clause" ]
permissive
joeedh/eltopo
bf6420ff11efc29ac36882e84ba0094b442d6f50
5db63d4df66816a07509fe3884299fca52d38665
refs/heads/master
2021-01-05T15:27:08.708465
2020-03-13T21:58:09
2020-03-13T21:58:09
241,061,523
0
0
BSD-2-Clause
2020-02-17T08:59:20
2020-02-17T08:59:20
null
UTF-8
C++
false
false
100,277
cpp
#include <rootparitycollisiontest.h> #include <cstdlib> namespace rootparity { namespace // unnamed namespace for local functions { /// /// Local helper functions /// template<unsigned int N, class T> inline void make_vector( const Vec<N,double>& in, Vec<N,T>& out ); template<class T> void point_triangle_collision_function(const Vec3d &d_x0, const Vec3d &d_x1, const Vec3d &d_x2, const Vec3d &d_x3, const Vec3d &d_x0new, const Vec3d &d_x1new, const Vec3d &d_x2new, const Vec3d &d_x3new, bool d_t, bool d_u, bool d_v, Vec<3,T>& out ); template<class T> void edge_edge_collision_function(const Vec3d &d_x0, const Vec3d &d_x1, const Vec3d &d_x2, const Vec3d &d_x3, const Vec3d &d_x0new, const Vec3d &d_x1new, const Vec3d &d_x2new, const Vec3d &d_x3new, bool d_t, bool d_u, bool d_v, Vec<3,T>& out ); template<class T> void get_quad_vertices(const Vec3d &d_x0old, const Vec3d &d_x1old, const Vec3d &d_x2old, const Vec3d &d_x3old, const Vec3d &d_x0new, const Vec3d &d_x1new, const Vec3d &d_x2new, const Vec3d &d_x3new, bool is_edge_edge, const Vec4b& ts, const Vec4b& us, const Vec4b& vs, Vec<3,T>& q0, Vec<3,T>& q1, Vec<3,T>& q2, Vec<3,T>& q3 ); template<class T> void get_triangle_vertices(const Vec3d &d_x0old, const Vec3d &d_x1old, const Vec3d &d_x2old, const Vec3d &d_x3old, const Vec3d &d_x0new, const Vec3d &d_x1new, const Vec3d &d_x2new, const Vec3d &d_x3new, bool is_edge_edge, const Vec3b& ts, const Vec3b& us, const Vec3b& vs, Vec<3,T>& q0, Vec<3,T>& q1, Vec<3,T>& q2 ); template<class T> static T orientation2d(const Vec<2,T>& x0, const Vec<2,T>& x1, const Vec<2,T>& x2); template<class T> T orientation3d(const Vec<3,T>& x0, const Vec<3,T>& x1, const Vec<3,T>& x2, const Vec<3,T>& x3); int expansion_simplex_intersection1d(int k, const expansion& x0, const expansion& x1, const expansion& x2, double* out_alpha0, double* out_alpha1, double* out_alpha2); int expansion_simplex_intersection2d(int k, const Vec2e& x0, const Vec2e& x1, const Vec2e& x2, double* out_alpha0, double* out_alpha1, double* out_alpha2 ); int expansion_simplex_intersection2d(int k, const Vec2e& x0, const Vec2e& x1, const Vec2e& x2, const Vec2e& x3, double* out_alpha0, double* out_alpha1, double* out_alpha2, double* out_alpha3); bool expansion_simplex_intersection3d(int k, const Vec3e& x0, const Vec3e& x1, const Vec3e& x2, const Vec3e& x3, double* alpha0, double* alpha1, double* alpha2, double* alpha3); int degenerate_point_tetrahedron_intersection(const Vec3e& x0, const Vec3e& x1, const Vec3e& x2, const Vec3e& x3, const Vec3e& x4, double* alpha0, double* alpha1, double* alpha2, double* alpha3, double* alpha4); int degenerate_point_tetrahedron_intersection(const Vec3Interval& x0, const Vec3Interval& x1, const Vec3Interval& x2, const Vec3Interval& x3, const Vec3Interval& x4, double* out_alpha0, double* out_alpha1, double* out_alpha2, double* out_alpha3, double* out_alpha4); template<class T> int point_tetrahedron_intersection(const Vec<3,T>& x0, const Vec<3,T>& x1, const Vec<3,T>& x2, const Vec<3,T>& x3, const Vec<3,T>& x4, double* out_alpha0, double* out_alpha1, double* out_alpha2, double* out_alpha3, double* out_alpha4 ); int degenerate_edge_triangle_intersection(const Vec3e& x0, const Vec3e& x1, const Vec3e& x2, const Vec3e& x3, const Vec3e& x4, double* alpha0, double* alpha1, double* alpha2, double* alpha3, double* alpha4); int degenerate_edge_triangle_intersection(const Vec3Interval& x0, const Vec3Interval& x1, const Vec3Interval& x2, const Vec3Interval& x3, const Vec3Interval& x4, double* out_alpha0, double* out_alpha1, double* out_alpha2, double* out_alpha3, double* out_alpha4); template<class T> int edge_triangle_intersection(const Vec<3,T>& x0, const Vec<3,T>& x1, const Vec<3,T>& x2, const Vec<3,T>& x3, const Vec<3,T>& x4, double* out_alpha0, double* out_alpha1, double* out_alpha2, double* out_alpha3, double* out_alpha4 ); bool edge_triangle_intersection(const Vec3d &d_x0old, const Vec3d &d_x1old, const Vec3d &d_x2old, const Vec3d &d_x3old, const Vec3d &d_x0new, const Vec3d &d_x1new, const Vec3d &d_x2new, const Vec3d &d_x3new, bool is_edge_edge, const Vec3b& ts, const Vec3b& us, const Vec3b& vs, const Vec3d& d_s0, const Vec3d& d_s1, double* alphas ); template<class T> T plane_dist( const Vec<3,T>& x, const Vec<3,T>& q, const Vec<3,T>& r, const Vec<3,T>& p ); template<class T> void implicit_surface_function( const Vec<3,T>& x, const Vec<3,T>& q0, const Vec<3,T>& q1, const Vec<3,T>& q2, const Vec<3,T>& q3, T& out ); bool test_with_triangles(const Vec3d &d_x0old, const Vec3d &d_x1old, const Vec3d &d_x2old, const Vec3d &d_x3old, const Vec3d &d_x0new, const Vec3d &d_x1new, const Vec3d &d_x2new, const Vec3d &d_x3new, bool is_edge_edge, const Vec4b& ts, const Vec4b& us, const Vec4b& vs, const Vec3d& s0, const Vec3d& s1, bool use_positive_triangles, bool& edge_hit ); // // Local function definitions // // -------------------------------------------------------- template<unsigned int N, class T> inline void make_vector( const Vec<N,double>& in, Vec<N,T>& out ) { for ( unsigned int i = 0; i < N; ++i ) { create_from_double( in[i], out[i] ); } } // -------------------------------------------------------- template<class T> inline void edge_edge_collision_function(const Vec3d &d_x0, const Vec3d &d_x1, const Vec3d &d_x2, const Vec3d &d_x3, const Vec3d &d_x0new, const Vec3d &d_x1new, const Vec3d &d_x2new, const Vec3d &d_x3new, bool b_t, bool b_u, bool b_v, Vec<3,T>& out ) { Vec<3,T> x0, x1, x2, x3; make_vector( d_x0, x0 ); make_vector( d_x1, x1 ); make_vector( d_x2, x2 ); make_vector( d_x3, x3 ); out = x0; out -= x2; if ( b_t ) { Vec<3,T> x0new, x1new, x2new, x3new; make_vector( d_x0new, x0new ); make_vector( d_x1new, x1new ); make_vector( d_x2new, x2new ); make_vector( d_x3new, x3new ); out += x0new; out -= x0; out -= x2new; out += x2; if ( b_u ) { out += x0; out -= x0new; out += x1new; out -= x1; } if ( b_v ) { out += x2new; out -= x2; out -= x3new; out += x3; } } if ( b_u ) { out += x1; out -= x0; } if ( b_v ) { out += x2; out -= x3; } } /// -------------------------------------------------------- inline void add( Vec3d& a, const Vec3d& b ) { a[0] += b[0]; a[1] += b[1]; a[2] += b[2]; } /// -------------------------------------------------------- inline void sub( Vec3d& a, const Vec3d& b ) { a[0] -= b[0]; a[1] -= b[1]; a[2] -= b[2]; } // -------------------------------------------------------- inline void edge_edge_collision_function(const Vec3d &d_x0, const Vec3d &d_x1, const Vec3d &d_x2, const Vec3d &d_x3, const Vec3d &d_x0new, const Vec3d &d_x1new, const Vec3d &d_x2new, const Vec3d &d_x3new, bool b_t, bool b_u, bool b_v, Vec<3,IntervalType>& out ) { Vec3d out_lower( -d_x0[0], -d_x0[1], -d_x0[2] ); add( out_lower, d_x2 ); Vec3d out_upper( d_x0[0], d_x0[1], d_x0[2] ); sub( out_upper, d_x2 ); if ( b_t ) { sub( out_lower, d_x0new ); add( out_lower, d_x0 ); add( out_lower, d_x2new ); sub( out_lower, d_x2 ); add( out_upper, d_x0new ); sub( out_upper, d_x0 ); sub( out_upper, d_x2new ); add( out_upper, d_x2 ); if ( b_u ) { sub( out_lower, d_x0 ); add( out_lower, d_x0new ); sub( out_lower, d_x1new ); add( out_lower, d_x1 ); add( out_upper, d_x0 ); sub( out_upper, d_x0new ); add( out_upper, d_x1new ); sub( out_upper, d_x1 ); } if ( b_v ) { sub( out_lower, d_x2new ); add( out_lower, d_x2 ); add( out_lower, d_x3new ); sub( out_lower, d_x3 ); add( out_upper, d_x2new ); sub( out_upper, d_x2 ); sub( out_upper, d_x3new ); add( out_upper, d_x3 ); } } if ( b_u ) { sub( out_lower, d_x1 ); add( out_lower, d_x0 ); add( out_upper, d_x1 ); sub( out_upper, d_x0 ); } if ( b_v ) { sub( out_lower, d_x2 ); add( out_lower, d_x3 ); add( out_upper, d_x2 ); sub( out_upper, d_x3 ); } out[0].v[0] = out_lower[0]; out[1].v[0] = out_lower[1]; out[2].v[0] = out_lower[2]; out[0].v[1] = out_upper[0]; out[1].v[1] = out_upper[1]; out[2].v[1] = out_upper[2]; } /// -------------------------------------------------------- template<class T> void point_triangle_collision_function(const Vec3d &d_x0, const Vec3d &d_x1, const Vec3d &d_x2, const Vec3d &d_x3, const Vec3d &d_x0new, const Vec3d &d_x1new, const Vec3d &d_x2new, const Vec3d &d_x3new, bool b_t, bool b_u, bool b_v, Vec<3,T>& out ) { Vec<3,T> x0, x1, x2, x3; make_vector( d_x0, x0 ); make_vector( d_x1, x1 ); make_vector( d_x2, x2 ); make_vector( d_x3, x3 ); out = x0; out -= x1; if ( b_t ) { Vec<3,T> x0new, x1new, x2new, x3new; make_vector( d_x0new, x0new ); make_vector( d_x1new, x1new ); make_vector( d_x2new, x2new ); make_vector( d_x3new, x3new ); out += x0new; out -= x0; out -= x1new; out += x1; if ( b_u ) { out += x1new; out -= x1; out -= x2new; out += x2; } if ( b_v ) { out += x1new; out -= x1; out -= x3new; out += x3; } } if ( b_u ) { out += x1; out -= x2; } if ( b_v ) { out += x1; out -= x3; } } /// -------------------------------------------------------- void point_triangle_collision_function(const Vec3d &d_x0, const Vec3d &d_x1, const Vec3d &d_x2, const Vec3d &d_x3, const Vec3d &d_x0new, const Vec3d &d_x1new, const Vec3d &d_x2new, const Vec3d &d_x3new, bool b_t, bool b_u, bool b_v, Vec<3,IntervalType>& out ) { Vec3d out_lower( -d_x0[0], -d_x0[1], -d_x0[2] ); Vec3d out_upper( d_x0[0], d_x0[1], d_x0[2] ); add( out_lower, d_x1 ); sub( out_upper, d_x1 ); if ( b_t ) { sub( out_lower, d_x0new ); add( out_lower, d_x0 ); add( out_lower, d_x1new ); sub( out_lower, d_x1 ); add( out_upper, d_x0new ); sub( out_upper, d_x0 ); sub( out_upper, d_x1new ); add( out_upper, d_x1 ); if ( b_u ) { sub( out_lower, d_x1new ); add( out_lower, d_x1 ); add( out_lower, d_x2new ); sub( out_lower, d_x2 ); add( out_upper, d_x1new ); sub( out_upper, d_x1 ); sub( out_upper, d_x2new ); add( out_upper, d_x2 ); } if ( b_v ) { sub( out_lower, d_x1new ); add( out_lower, d_x1 ); add( out_lower, d_x3new ); sub( out_lower, d_x3 ); add( out_upper, d_x1new ); sub( out_upper, d_x1 ); sub( out_upper, d_x3new ); add( out_upper, d_x3 ); } } if ( b_u ) { sub( out_lower, d_x1 ); add( out_lower, d_x2 ); add( out_upper, d_x1 ); sub( out_upper, d_x2 ); } if ( b_v ) { sub( out_lower, d_x1 ); add( out_lower, d_x3 ); add( out_upper, d_x1 ); sub( out_upper, d_x3 ); } out[0].v[0] = out_lower[0]; out[1].v[0] = out_lower[1]; out[2].v[0] = out_lower[2]; out[0].v[1] = out_upper[0]; out[1].v[1] = out_upper[1]; out[2].v[1] = out_upper[2]; } // -------------------------------------------------------- template<class T> void get_quad_vertices(const Vec3d &d_x0old, const Vec3d &d_x1old, const Vec3d &d_x2old, const Vec3d &d_x3old, const Vec3d &d_x0new, const Vec3d &d_x1new, const Vec3d &d_x2new, const Vec3d &d_x3new, bool is_edge_edge, const Vec4b& ts, const Vec4b& us, const Vec4b& vs, Vec<3,T>& q0, Vec<3,T>& q1, Vec<3,T>& q2, Vec<3,T>& q3 ) { T::begin_special_arithmetic(); if ( is_edge_edge ) { edge_edge_collision_function( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, ts[0], us[0], vs[0], q0 ); edge_edge_collision_function( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, ts[1], us[1], vs[1], q1 ); edge_edge_collision_function( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, ts[2], us[2], vs[2], q2 ); edge_edge_collision_function( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, ts[3], us[3], vs[3], q3 ); } else { point_triangle_collision_function( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, ts[0], us[0], vs[0], q0 ); point_triangle_collision_function( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, ts[1], us[1], vs[1], q1 ); point_triangle_collision_function( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, ts[2], us[2], vs[2], q2 ); point_triangle_collision_function( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, ts[3], us[3], vs[3], q3 ); } T::end_special_arithmetic(); } // -------------------------------------------------------- template<class T> void get_triangle_vertices(const Vec3d &d_x0old, const Vec3d &d_x1old, const Vec3d &d_x2old, const Vec3d &d_x3old, const Vec3d &d_x0new, const Vec3d &d_x1new, const Vec3d &d_x2new, const Vec3d &d_x3new, bool is_edge_edge, const Vec3b& ts, const Vec3b& us, const Vec3b& vs, Vec<3,T>& q0, Vec<3,T>& q1, Vec<3,T>& q2 ) { T::begin_special_arithmetic(); if ( is_edge_edge ) { edge_edge_collision_function( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, ts[0], us[0], vs[0], q0 ); edge_edge_collision_function( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, ts[1], us[1], vs[1], q1 ); edge_edge_collision_function( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, ts[2], us[2], vs[2], q2 ); } else { point_triangle_collision_function( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, ts[0], us[0], vs[0], q0 ); point_triangle_collision_function( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, ts[1], us[1], vs[1], q1 ); point_triangle_collision_function( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, ts[2], us[2], vs[2], q2 ); } T::end_special_arithmetic(); } // ---------------------------------------- template<class T> static T orientation2d(const Vec<2,T>& x0, const Vec<2,T>& x1, const Vec<2,T>& x2) { return x0[0]*x1[1] + -(x0[0])*x2[1] + x1[0]*x2[1] + -(x1[0])*x0[1] + x2[0]*x0[1] + -(x2[0])*x1[1]; } // ---------------------------------------- inline expansion orientation2d(const Vec<2,expansion>& x0, const Vec<2,expansion>& x1, const Vec<2,expansion>& x2) { expansion prod; expansion result; multiply( x0[0], x1[1], prod ); add( result, prod, result ); multiply( x0[0], x2[1], prod ); subtract( result, prod, result ); multiply( x1[0], x2[1], prod ); add( result, prod, result ); multiply( x1[0], x0[1], prod ); subtract( result, prod, result ); multiply( x2[0], x0[1], prod ); add( result, prod, result ); multiply( x2[0], x1[1], prod ); subtract( result, prod, result ); return result; } // -------------------------------------------------------- template<class T> void orientation3d(const Vec<3,T>& x0, const Vec<3,T>& x1, const Vec<3,T>& x2, const Vec<3,T>& x3, T& result ) { // avoid recomputing common factors T x00x11 = x0[0] * x1[1]; T x00x21 = x0[0] * x2[1]; T x00x31 = x0[0] * x3[1]; T x10x01 = x1[0] * x0[1]; T x10x21 = x1[0] * x2[1]; T x10x31 = x1[0] * x3[1]; T x20x01 = x2[0] * x0[1]; T x20x11 = x2[0] * x1[1]; T x20x31 = x2[0] * x3[1]; T x30x01 = x3[0] * x0[1]; T x30x11 = x3[0] * x1[1]; T x30x21 = x3[0] * x2[1]; result = ( x00x11 * ( x2[2] - x3[2] ) ) + ( x00x21 * ( x3[2] - x1[2] ) ) + ( x00x31 * ( x1[2] - x2[2] ) ) + ( x10x01 * ( x3[2] - x2[2] ) ) + ( x10x21 * ( x0[2] - x3[2] ) ) + ( x10x31 * ( x2[2] - x0[2] ) ) + ( x20x01 * ( x1[2]- x3[2] ) ) + ( x20x11 * ( x3[2] - x0[2] ) ) + ( x20x31 * ( x0[2] - x1[2] ) ) + ( x30x01 * ( x2[2] - x1[2] ) ) + ( x30x11 * ( x0[2] - x2[2] ) ) + ( x30x21 * ( x1[2] - x0[2] ) ); } // -------------------------------------------------------- inline void orientation3d(const Vec<3,expansion>& x0, const Vec<3,expansion>& x1, const Vec<3,expansion>& x2, const Vec<3,expansion>& x3, expansion& result ) { // avoid recomputing common factors expansion x00x11; multiply( x0[0], x1[1], x00x11 ); expansion x00x21; multiply( x0[0], x2[1], x00x21 ); expansion x00x31; multiply( x0[0], x3[1], x00x31 ); expansion x10x01; multiply( x1[0], x0[1], x10x01 ); expansion x10x21; multiply( x1[0], x2[1], x10x21 ); expansion x10x31; multiply( x1[0], x3[1], x10x31 ); expansion x20x01; multiply( x2[0], x0[1], x20x01 ); expansion x20x11; multiply( x2[0], x1[1], x20x11 ); expansion x20x31; multiply( x2[0], x3[1], x20x31 ); expansion x30x01; multiply( x3[0], x0[1], x30x01 ); expansion x30x11; multiply( x3[0], x1[1], x30x11 ); expansion x30x21; multiply( x3[0], x2[1], x30x21 ); expansion diff; subtract( x2[2], x3[2], diff ); multiply( x00x11, diff, result ); expansion prod; subtract( x3[2], x1[2], diff ); multiply( x00x21, diff, prod ); add( result, prod, result ); subtract( x1[2], x2[2], diff ); multiply( x00x31, diff, prod ); add( result, prod, result ); subtract( x3[2], x2[2], diff ); multiply( x10x01, diff, prod ); add( result, prod, result ); subtract( x0[2], x3[2], diff ); multiply( x10x21, diff, prod ); add( result, prod, result ); subtract( x2[2], x0[2], diff ); multiply( x10x31, diff, prod ); add( result, prod, result ); subtract( x1[2], x3[2], diff ); multiply( x20x01, diff, prod ); add( result, prod, result ); subtract( x3[2], x0[2], diff ); multiply( x20x11, diff, prod ); add( result, prod, result ); subtract( x0[2], x1[2], diff ); multiply( x20x31, diff, prod ); add( result, prod, result ); subtract( x2[2], x1[2], diff ); multiply( x30x01, diff, prod ); add( result, prod, result ); subtract( x0[2], x2[2], diff ); multiply( x30x11, diff, prod ); add( result, prod, result ); subtract( x1[2], x0[2], diff ); multiply( x30x21, diff, prod ); add( result, prod, result ); } // ---------------------------------------- int expansion_simplex_intersection1d(int k, const expansion& x0, const expansion& x1, const expansion& x2, double* out_alpha0, double* out_alpha1, double* out_alpha2) { assert( k == 1 ); assert(out_alpha0 && out_alpha1 && out_alpha2); assert(fegetround()== FE_TONEAREST); if( sign(x1-x2) < 0 ) { if( sign(x0-x1) < 0) return 0; else if ( sign(x0-x2) > 0 ) return 0; *out_alpha0=1; *out_alpha1=(x2.estimate()-x0.estimate())/(x2.estimate()-x1.estimate()); *out_alpha2=(x0.estimate()-x1.estimate())/(x2.estimate()-x1.estimate()); return 1; } else if( sign(x1-x2) > 0 ) { if( sign(x0-x2) < 0 ) return 0; else if( sign(x0-x1) > 0) return 0; *out_alpha0=1; *out_alpha1=(x2.estimate()-x0.estimate())/(x2.estimate()-x1.estimate()); *out_alpha2=(x0.estimate()-x1.estimate())/(x2.estimate()-x1.estimate()); return 1; } else { // x1 == x2 if( sign(x0-x1) != 0 ) return 0; *out_alpha0=1; *out_alpha1=0.5; *out_alpha2=0.5; return 1; } } // ---------------------------------------- int expansion_simplex_intersection2d(int k, const Vec2e& x0, const Vec2e& x1, const Vec2e& x2, double* out_alpha0, double* out_alpha1, double* out_alpha2 ) { assert(k==1); assert(fegetround()== FE_TONEAREST); // try projecting each coordinate out in turn double ax0, ax1, ax2; if(!expansion_simplex_intersection1d(1, x0[1], x1[1], x2[1], &ax0, &ax1, &ax2)) return 0; double ay0, ay1, ay2; if(!expansion_simplex_intersection1d(1, x0[0], x1[0], x2[0], &ay0, &ay1, &ay2)) return 0; // decide which solution is more accurate for barycentric coordinates double checkx=std::fabs(-ax0*x0[0].estimate()+ax1*x1[0].estimate()+ax2*x2[0].estimate()) +std::fabs(-ax0*x0[1].estimate()+ax1*x1[1].estimate()+ax2*x2[1].estimate()); double checky=std::fabs(-ay0*x0[0].estimate()+ay1*x1[0].estimate()+ay2*x2[0].estimate()) +std::fabs(-ay0*x0[1].estimate()+ay1*x1[1].estimate()+ay2*x2[1].estimate()); if(checkx<=checky) { *out_alpha0=ax0; *out_alpha1=ax1; *out_alpha2=ax2; } else { *out_alpha0=ay0; *out_alpha1=ay1; *out_alpha2=ay2; } return 1; } // ---------------------------------------- int expansion_simplex_intersection2d(int k, const Vec2e& x0, const Vec2e& x1, const Vec2e& x2, const Vec2e& x3, double* out_alpha0, double* out_alpha1, double* out_alpha2, double* out_alpha3) { assert(1<=k && k<=3); assert(fegetround()== FE_TONEAREST); switch(k) { case 1: // point vs. triangle { expansion alpha1 = -orientation2d(x0, x2, x3); expansion alpha2 = orientation2d(x0, x1, x3); if(certainly_opposite_sign(alpha1, alpha2)) return 0; expansion alpha3 = -orientation2d(x0, x1, x2); if(certainly_opposite_sign(alpha1, alpha3)) return 0; if(certainly_opposite_sign(alpha2, alpha3)) return 0; double sum2 = alpha1.estimate() + alpha2.estimate() + alpha3.estimate(); if(sum2) { *out_alpha0=1; *out_alpha1 = alpha1.estimate() / sum2; *out_alpha2 = alpha2.estimate() / sum2; *out_alpha3 = alpha3.estimate() / sum2; return 1; } else { // triangle is degenerate and point lies on same line if(expansion_simplex_intersection2d(1, x0, x1, x2, out_alpha0, out_alpha1, out_alpha2)) { *out_alpha3=0; return 1; } if(expansion_simplex_intersection2d(1, x0, x1, x3, out_alpha0, out_alpha1, out_alpha3)) { *out_alpha2=0; return 1; } if(expansion_simplex_intersection2d(1, x0, x2, x3, out_alpha0, out_alpha2, out_alpha3)) { *out_alpha1=0; return 1; } return 0; } } case 2: // segment vs. segment { expansion alpha0 = orientation2d(x1, x2, x3); expansion alpha1 = -orientation2d(x0, x2, x3); if( certainly_opposite_sign(alpha0, alpha1) ) return 0; expansion alpha2 = orientation2d(x0, x1, x3); expansion alpha3 = -orientation2d(x0, x1, x2); if( certainly_opposite_sign(alpha2, alpha3) ) return 0; double sum1, sum2; sum1= alpha0.estimate() + alpha1.estimate(); sum2= alpha2.estimate() + alpha3.estimate(); if(sum1 && sum2){ *out_alpha0 = alpha0.estimate() / sum1; *out_alpha1 = alpha1.estimate() / sum1; *out_alpha2 = alpha2.estimate() / sum2; *out_alpha3 = alpha3.estimate() / sum2; return 1; } else { // degenerate: segments lie on the same line if(expansion_simplex_intersection2d(1, x0, x2, x3, out_alpha0, out_alpha2, out_alpha3)){ *out_alpha1=0; return 1; } if(expansion_simplex_intersection2d(1, x1, x2, x3, out_alpha1, out_alpha2, out_alpha3)){ *out_alpha0=0; return 1; } if(expansion_simplex_intersection2d(1, x2, x0, x1, out_alpha2, out_alpha0, out_alpha1)){ *out_alpha3=0; return 1; } if(expansion_simplex_intersection2d(1, x3, x0, x1, out_alpha3, out_alpha0, out_alpha1)){ *out_alpha2=0; return 1; } return 0; } } break; default: assert(0); return -1; // should never get here } } // -------------------------------------------------------- // degenerate test in 3d - assumes four points lie on the same plane bool expansion_simplex_intersection3d(int k, const Vec3e& x0, const Vec3e& x1, const Vec3e& x2, const Vec3e& x3, double* alpha0, double* alpha1, double* alpha2, double* ) { assert(k<=2); assert(fegetround()== FE_TONEAREST); // try projecting each coordinate out in turn double ax0, ax1, ax2, ax3; if( !expansion_simplex_intersection2d(k, Vec2e(x0[1],x0[2]), Vec2e(x1[1],x1[2]), Vec2e(x2[1],x2[2]), Vec2e(x3[1],x3[2]), &ax0, &ax1, &ax2,&ax3) ) { return 0; } double ay0, ay1, ay2, ay3; Vec2e p0( x0[0], x0[2] ); Vec2e p1( x1[0], x1[2] ); Vec2e p2( x2[0], x2[2] ); Vec2e p3( x3[0], x3[2] ); if ( !expansion_simplex_intersection2d(k, p0, p1, p2, p3, &ay0, &ay1, &ay2, &ay3) ) { return 0; } double az0, az1, az2, az3; if( !expansion_simplex_intersection2d(k, Vec2e(x0[0],x0[1]), Vec2e(x1[0],x1[1]), Vec2e(x2[0],x2[1]), Vec2e(x3[0],x3[1]), &az0, &az1, &az2, &az3) ) { return 0; } // decide which solution is more accurate for barycentric coordinates double checkx, checky, checkz; Vec3d estx0( x0[0].estimate(), x0[1].estimate(), x0[2].estimate() ); Vec3d estx1( x1[0].estimate(), x1[1].estimate(), x1[2].estimate() ); Vec3d estx2( x2[0].estimate(), x2[1].estimate(), x2[2].estimate() ); Vec3d estx3( x3[0].estimate(), x3[1].estimate(), x3[2].estimate() ); if(k==1) { checkx=std::fabs(-ax0*estx0[0]+ax1*estx1[0]+ax2*estx2[0]+ax3*estx3[0]) +std::fabs(-ax0*estx0[1]+ax1*estx1[1]+ax2*estx2[1]+ax3*estx3[1]) +std::fabs(-ax0*estx0[2]+ax1*estx1[2]+ax2*estx2[2]+ax3*estx3[2]); checky=std::fabs(-ay0*estx0[0]+ay1*estx1[0]+ay2*estx2[0]+ay3*estx3[0]) +std::fabs(-ay0*estx0[1]+ay1*estx1[1]+ay2*estx2[1]+ay3*estx3[1]) +std::fabs(-ay0*estx0[2]+ay1*estx1[2]+ay2*estx2[2]+ay3*estx3[2]); checkz=std::fabs(-az0*estx0[0]+az1*estx1[0]+az2*estx2[0]+az3*estx3[0]) +std::fabs(-az0*estx0[1]+az1*estx1[1]+az2*estx2[1]+az3*estx3[1]) +std::fabs(-az0*estx0[2]+az1*estx1[2]+az2*estx2[2]+az3*estx3[2]); } else { checkx=std::fabs(-ax0*estx0[0]-ax1*estx1[0]+ax2*estx2[0]+ax3*estx3[0]) +std::fabs(-ax0*estx0[1]-ax1*estx1[1]+ax2*estx2[1]+ax3*estx3[1]) +std::fabs(-ax0*estx0[2]-ax1*estx1[2]+ax2*estx2[2]+ax3*estx3[2]); checky=std::fabs(-ay0*estx0[0]-ay1*estx1[0]+ay2*estx2[0]+ay3*estx3[0]) +std::fabs(-ay0*estx0[1]-ay1*estx1[1]+ay2*estx2[1]+ay3*estx3[1]) +std::fabs(-ay0*estx0[2]-ay1*estx1[2]+ay2*estx2[2]+ay3*estx3[2]); checkz=std::fabs(-az0*estx0[0]-az1*estx1[0]+az2*estx2[0]+az3*estx3[0]) +std::fabs(-az0*estx0[1]-az1*estx1[1]+az2*estx2[1]+az3*estx3[1]) +std::fabs(-az0*estx0[2]-az1*estx1[2]+az2*estx2[2]+az3*estx3[2]); } if(checkx<=checky && checkx<=checkz) { *alpha0=ax0; *alpha1=ax1; *alpha2=ax2; *alpha2=ax3; } else if(checky<=checkz) { *alpha0=ay0; *alpha1=ay1; *alpha2=ay2; *alpha2=ay3; } else { *alpha0=az0; *alpha1=az1; *alpha2=az2; *alpha2=az3; } return 1; } // -------------------------------------------------------- int degenerate_point_tetrahedron_intersection(const Vec3e& x0, const Vec3e& x1, const Vec3e& x2, const Vec3e& x3, const Vec3e& x4, double* alpha0, double* alpha1, double* alpha2, double* alpha3, double* alpha4) { assert(fegetround()== FE_TONEAREST); // degenerate: point and tetrahedron in same plane if (expansion_simplex_intersection3d(1, x0, x2, x3, x4, alpha0, alpha2, alpha3, alpha4)) { *alpha1=0; return 1; } if(expansion_simplex_intersection3d(1, x0, x1, x3, x4, alpha0, alpha1, alpha3, alpha4)) { *alpha2=0; return 1; } if(expansion_simplex_intersection3d(1, x0, x1, x2, x4, alpha0, alpha1, alpha2, alpha4)) { *alpha3=0; return 1; } if(expansion_simplex_intersection3d(1, x0, x1, x2, x3, alpha0, alpha1, alpha2, alpha3)) { *alpha4=0; return 1; } return 0; } // -------------------------------------------------------- int degenerate_point_tetrahedron_intersection(const Vec3Interval& , const Vec3Interval& , const Vec3Interval& , const Vec3Interval& , const Vec3Interval& , double* , double* , double* , double* , double* ) { return -1; } // -------------------------------------------------------- template<class T> int point_tetrahedron_intersection(const Vec<3,T>& x0, const Vec<3,T>& x1, const Vec<3,T>& x2, const Vec<3,T>& x3, const Vec<3,T>& x4, double* out_alpha0, double* out_alpha1, double* out_alpha2, double* out_alpha3, double* out_alpha4 ) { T::begin_special_arithmetic(); T alpha1; orientation3d(x0, x2, x3, x4, alpha1); alpha1 = -alpha1; T alpha2; orientation3d(x0, x1, x3, x4, alpha2); if( certainly_opposite_sign(alpha1, alpha2) ) { T::end_special_arithmetic(); return 0; } T alpha3; orientation3d(x0, x1, x2, x4, alpha3); alpha3 = -alpha3; if( certainly_opposite_sign(alpha1, alpha3) ) { T::end_special_arithmetic(); return 0; } if( certainly_opposite_sign(alpha2, alpha3) ) { T::end_special_arithmetic(); return 0; } T alpha4; orientation3d(x0, x1, x2, x3, alpha4); T::end_special_arithmetic(); if( certainly_opposite_sign(alpha1, alpha4) ) return 0; if( certainly_opposite_sign(alpha2, alpha4) ) return 0; if( certainly_opposite_sign(alpha3, alpha4) ) return 0; if ( alpha1.indefinite_sign() || alpha2.indefinite_sign() || alpha3.indefinite_sign() || alpha4.indefinite_sign() ) { // degenerate return -1; } double sum2 = alpha1.estimate() + alpha2.estimate() + alpha3.estimate() + alpha4.estimate(); if(sum2) { *out_alpha0 = 1; *out_alpha1 = alpha1.estimate() / sum2; *out_alpha2 = alpha2.estimate() / sum2; *out_alpha3 = alpha3.estimate() / sum2; *out_alpha4 = alpha4.estimate() / sum2; return 1; } else { // If T is IntervalType, returns -1 // If T is expansion, computes exact intersection by projecting to lower dimensions. return degenerate_point_tetrahedron_intersection( x0, x1, x2, x3, x4, out_alpha0, out_alpha1, out_alpha2, out_alpha3, out_alpha4 ); } } // -------------------------------------------------------- int degenerate_edge_triangle_intersection(const Vec3e& x0, const Vec3e& x1, const Vec3e& x2, const Vec3e& x3, const Vec3e& x4, double* alpha0, double* alpha1, double* alpha2, double* alpha3, double* alpha4) { // degenerate: segment and triangle in same plane if(expansion_simplex_intersection3d(1, x1, x2, x3, x4, alpha1, alpha2, alpha3, alpha4)){ *alpha0=0; return 1; } if(expansion_simplex_intersection3d(1, x0, x2, x3, x4, alpha0, alpha2, alpha3, alpha4)){ *alpha1=0; return 1; } if(expansion_simplex_intersection3d(2, x0, x1, x3, x4, alpha0, alpha1, alpha3, alpha4)){ *alpha2=0; return 1; } if(expansion_simplex_intersection3d(2, x0, x1, x2, x4, alpha0, alpha1, alpha2, alpha4)){ *alpha3=0; return 1; } if(expansion_simplex_intersection3d(2, x0, x1, x2, x3, alpha0, alpha1, alpha2, alpha3)){ *alpha4=0; return 1; } return 0; } // -------------------------------------------------------- int degenerate_edge_triangle_intersection(const Vec3Interval& , const Vec3Interval& , const Vec3Interval& , const Vec3Interval& , const Vec3Interval& , double* , double* , double* , double* , double* ) { return -1; } // -------------------------------------------------------- template<class T> int edge_triangle_intersection(const Vec<3,T>& x0, const Vec<3,T>& x1, const Vec<3,T>& x2, const Vec<3,T>& x3, const Vec<3,T>& x4, double* out_alpha0, double* out_alpha1, double* out_alpha2, double* out_alpha3, double* out_alpha4 ) { T::begin_special_arithmetic(); T alpha0; orientation3d(x1, x2, x3, x4,alpha0); T alpha1; orientation3d(x0, x2, x3, x4,alpha1); alpha1 = -alpha1; if( certainly_opposite_sign(alpha0, alpha1) ) { T::end_special_arithmetic(); return 0; } T alpha2; orientation3d(x0, x1, x3, x4, alpha2); T alpha3; orientation3d(x0, x1, x2, x4, alpha3); alpha3 = -alpha3; if( certainly_opposite_sign(alpha2, alpha3) ) { T::end_special_arithmetic(); return 0; } T alpha4; orientation3d(x0, x1, x2, x3, alpha4); if( certainly_opposite_sign(alpha2, alpha4) ) { T::end_special_arithmetic(); return 0; } if( certainly_opposite_sign(alpha3, alpha4) ) { T::end_special_arithmetic(); return 0; } T::end_special_arithmetic(); if ( alpha0.indefinite_sign() || alpha1.indefinite_sign() || alpha2.indefinite_sign() || alpha3.indefinite_sign() || alpha4.indefinite_sign() ) { // degenerate return -1; } double sum1 = alpha0.estimate() + alpha1.estimate(); double sum2 = alpha2.estimate() + alpha3.estimate() + alpha4.estimate(); if(sum1 && sum2) { *out_alpha0 = alpha0.estimate() / sum1; *out_alpha1 = alpha1.estimate() / sum1; *out_alpha2 = alpha2.estimate() / sum2; *out_alpha3 = alpha3.estimate() / sum2; *out_alpha4 = alpha4.estimate() / sum2; return 1; } else { // If T is IntervalType, returns -1 // If T is expansion, computes exact intersection by projecting to lower dimensions. return degenerate_edge_triangle_intersection( x0, x1, x2, x3, x4, out_alpha0, out_alpha1, out_alpha2, out_alpha3, out_alpha4 ); } } // ---------------------------------------- bool edge_triangle_intersection(const Vec3d &d_x0old, const Vec3d &d_x1old, const Vec3d &d_x2old, const Vec3d &d_x3old, const Vec3d &d_x0new, const Vec3d &d_x1new, const Vec3d &d_x2new, const Vec3d &d_x3new, bool is_edge_edge, const Vec3b& ts, const Vec3b& us, const Vec3b& vs, const Vec3d& d_s0, const Vec3d& d_s1, double* alphas ) { // TODO: These should be cached already Vec3Interval t0, t1, t2; get_triangle_vertices( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, is_edge_edge, ts, us, vs, t0, t1, t2 ); Vec3Interval s0, s1; make_vector( d_s0, s0 ); make_vector( d_s1, s1 ); int result = edge_triangle_intersection( s0, s1, t0, t1, t2, &alphas[0], &alphas[1], &alphas[2], &alphas[3], &alphas[4] ); // If degenerate, repeat test using expansion arithmetric if ( result < 0 ) { // TODO: These might be cached already Vec3e exp_t0, exp_t1, exp_t2; get_triangle_vertices( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, is_edge_edge, ts, us, vs, exp_t0, exp_t1, exp_t2 ); Vec3e exp_s0, exp_s1; make_vector( d_s0, exp_s0 ); make_vector( d_s1, exp_s1 ); result = edge_triangle_intersection( exp_s0, exp_s1, exp_t0, exp_t1, exp_t2, &alphas[0], &alphas[1], &alphas[2], &alphas[3], &alphas[4] ); } if ( result == 0 ) { return false; } return true; } // ---------------------------------------- template<class T> T plane_dist( const Vec<3,T>& x, const Vec<3,T>& q, const Vec<3,T>& r, const Vec<3,T>& p ) { return dot( x-p, cross( q-p, r-p ) ); } // ---------------------------------------- template<class T> void implicit_surface_function( const Vec<3,T>& x, const Vec<3,T>& q0, const Vec<3,T>& q1, const Vec<3,T>& q2, const Vec<3,T>& q3, T& out ) { T::begin_special_arithmetic(); T g012 = plane_dist( x, q0, q1, q2 ); T g132 = plane_dist( x, q1, q3, q2 ); T h12 = g012 * g132; T g013 = plane_dist( x, q0, q1, q3 ); T g032 = plane_dist( x, q0, q3, q2 ); T h03 = g013 * g032; out = h12 - h03; T::end_special_arithmetic(); } // ---------------------------------------- bool test_with_triangles(const Vec3d &d_x0old, const Vec3d &d_x1old, const Vec3d &d_x2old, const Vec3d &d_x3old, const Vec3d &d_x0new, const Vec3d &d_x1new, const Vec3d &d_x2new, const Vec3d &d_x3new, bool is_edge_edge, const Vec4b& ts, const Vec4b& us, const Vec4b& vs, const Vec3d& s0, const Vec3d& s1, bool use_positive_triangles, bool& edge_hit ) { // determine which two triangles are on the positive side of f // first try evaluating sign using interval arithmetic int sign_h12 = -2; { Vec3Interval q0, q1, q2, q3; // TODO: These should be cached already get_quad_vertices( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, is_edge_edge, ts, us, vs, q0, q1, q2, q3 ); IntervalType::begin_special_arithmetic(); Vec3Interval x = IntervalType(0.5) * ( q0 + q3 ); IntervalType g012 = plane_dist( x, q0, q1, q2 ); IntervalType g132 = plane_dist( x, q1, q3, q2 ); IntervalType h12 = g012 * g132; IntervalType::end_special_arithmetic(); if ( h12.is_certainly_negative() ) { sign_h12 = -1; } if ( h12.is_certainly_zero() ) { sign_h12 = 0; } if ( h12.is_certainly_positive() ) { sign_h12 = 1; } } if ( sign_h12 == -2 ) { // not sure about sign - compute using expansion Vec3e eq0, eq1, eq2, eq3; // TODO: These might be cached already get_quad_vertices( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, is_edge_edge, ts, us, vs, eq0, eq1, eq2, eq3 ); Vec3e x = expansion( 0.5 ) * ( eq0 + eq3 ); expansion g012 = plane_dist( x, eq0, eq1, eq2 ); expansion g132 = plane_dist( x, eq1, eq3, eq2 ); expansion h12 = g012 * g132; sign_h12 = sign( h12 ); } if ( sign_h12 == 0 ) { // use either pair of triangles sign_h12 = 1; } if ( sign_h12 > 0 ) { // positive side: 013, 032 // negative side: 012, 132 if ( use_positive_triangles ) { double b[5] = { 0.5, 0.5, 0.5, 0.5, 0.5 }; Vec3b t013( ts[0], ts[1], ts[3] ); Vec3b u013( us[0], us[1], us[3] ); Vec3b v013( vs[0], vs[1], vs[3] ); bool hit_a = edge_triangle_intersection( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, is_edge_edge, t013, u013, v013, s0, s1, b ); if ( b[2] == 0.0 || b[3] == 0.0 || b[4] == 0.0 ) { edge_hit = true; } if ( b[2] == 1.0 || b[3] == 1.0 || b[4] == 1.0 ) { edge_hit = true; } Vec3b t032( ts[0], ts[3], ts[2] ); Vec3b u032( us[0], us[3], us[2] ); Vec3b v032( vs[0], vs[3], vs[2] ); bool hit_b = edge_triangle_intersection( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, is_edge_edge, t032, u032, v032, s0, s1, b ); if ( b[2] == 0.0 || b[3] == 0.0 || b[4] == 0.0 ) { edge_hit = true; } if ( b[2] == 1.0 || b[3] == 1.0 || b[4] == 1.0 ) { edge_hit = true; } return hit_a || hit_b; } else { double b[5] = { 0.5, 0.5, 0.5, 0.5, 0.5 }; Vec3b t012( ts[0], ts[1], ts[2] ); Vec3b u012( us[0], us[1], us[2] ); Vec3b v012( vs[0], vs[1], vs[2] ); bool hit_a = edge_triangle_intersection( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, is_edge_edge, t012, u012, v012, s0, s1, b ); if ( b[2] == 0.0 || b[3] == 0.0 || b[4] == 0.0 ) { edge_hit = true; } if ( b[2] == 1.0 || b[3] == 1.0 || b[4] == 1.0 ) { edge_hit = true; } Vec3b t132( ts[1], ts[3], ts[2] ); Vec3b u132( us[1], us[3], us[2] ); Vec3b v132( vs[1], vs[3], vs[2] ); bool hit_b = edge_triangle_intersection( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, is_edge_edge, t132, u132, v132, s0, s1, b ); if ( b[2] == 0.0 || b[3] == 0.0 || b[4] == 0.0 ) { edge_hit = true; } if ( b[2] == 1.0 || b[3] == 1.0 || b[4] == 1.0 ) { edge_hit = true; } return hit_a || hit_b; } } else { // positive side: 012, 132 // negative side: 013, 032 if ( use_positive_triangles ) { double b[5] = { 0.5, 0.5, 0.5, 0.5, 0.5 }; Vec3b t012( ts[0], ts[1], ts[2] ); Vec3b u012( us[0], us[1], us[2] ); Vec3b v012( vs[0], vs[1], vs[2] ); bool hit_a = edge_triangle_intersection( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, is_edge_edge, t012, u012, v012, s0, s1, b ); if ( b[2] == 0.0 || b[3] == 0.0 || b[4] == 0.0 ) { edge_hit = true; } if ( b[2] == 1.0 || b[3] == 1.0 || b[4] == 1.0 ) { edge_hit = true; } Vec3b t132( ts[1], ts[3], ts[2] ); Vec3b u132( us[1], us[3], us[2] ); Vec3b v132( vs[1], vs[3], vs[2] ); bool hit_b = edge_triangle_intersection( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, is_edge_edge, t132, u132, v132, s0, s1, b ); if ( b[2] == 0.0 || b[3] == 0.0 || b[4] == 0.0 ) { edge_hit = true; } if ( b[2] == 1.0 || b[3] == 1.0 || b[4] == 1.0 ) { edge_hit = true; } return hit_a || hit_b; } else { double b[5] = { 0.5, 0.5, 0.5, 0.5, 0.5 }; Vec3b t013( ts[0], ts[1], ts[3] ); Vec3b u013( us[0], us[1], us[3] ); Vec3b v013( vs[0], vs[1], vs[3] ); bool hit_a = edge_triangle_intersection( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, is_edge_edge, t013, u013, v013, s0, s1, b ); if ( b[2] == 0.0 || b[3] == 0.0 || b[4] == 0.0 ) { edge_hit = true; } if ( b[2] == 1.0 || b[3] == 1.0 || b[4] == 1.0 ) { edge_hit = true; } Vec3b t032( ts[0], ts[3], ts[2] ); Vec3b u032( us[0], us[3], us[2] ); Vec3b v032( vs[0], vs[3], vs[2] ); bool hit_b = edge_triangle_intersection( d_x0old, d_x1old, d_x2old, d_x3old, d_x0new, d_x1new, d_x2new, d_x3new, is_edge_edge, t032, u032, v032, s0, s1, b ); if ( b[2] == 0.0 || b[3] == 0.0 || b[4] == 0.0 ) { edge_hit = true; } if ( b[2] == 1.0 || b[3] == 1.0 || b[4] == 1.0 ) { edge_hit = true; } return hit_a || hit_b; } } } /// -------------------------------------------------------- inline int plane_sign( const Vec3d& n, const Vec3Interval& x ) { IntervalType dist = IntervalType(n[0])*x[0] + IntervalType(n[1])*x[1] + IntervalType(n[2])*x[2]; if ( dist.is_certainly_negative() ) { return -1; } else if ( dist.is_certainly_positive() ) { return 1; } return 0; } /// -------------------------------------------------------- inline int quick_1_plane_sign( const Vec3i& normal, const Vec3Interval& x ) { IntervalType dist( 0, 0 ); if ( normal[0] < 0 ) { dist -= x[0]; } else if ( normal[0] > 0 ) { dist += x[0]; } if ( normal[1] < 0 ) { dist -= x[1]; } else if ( normal[1] > 0 ) { dist += x[1]; } if ( normal[2] < 0 ) { dist -= x[2]; } else if ( normal[2] > 0 ) { dist += x[2]; } if ( dist.is_certainly_negative() ) { return -1; } else if ( dist.is_certainly_positive() ) { return 1; } return 0; } } // end unnamed namespace for local helper functions // // Member function definitions // // ---------------------------------------- /// /// Determine if the given point is inside the tetrahedron given by tet_indices /// // ---------------------------------------- bool RootParityCollisionTest::point_tetrahedron_intersection( const Vec4ui& quad, const Vec4b& ts, const Vec4b& us, const Vec4b& vs, const Vec3d& d_x ) { Vec3Interval x; make_vector( d_x, x ); double s[5]; int result = rootparity::point_tetrahedron_intersection(x, m_interval_hex_vertices[quad[0]], m_interval_hex_vertices[quad[1]], m_interval_hex_vertices[quad[2]], m_interval_hex_vertices[quad[3]], &s[0], &s[1], &s[2], &s[3], &s[4] ); // If degenerate, repeat test using expansion arithmetric if ( result < 0 ) { // Check if the expansion vertices have been computed already for ( unsigned int i = 0; i < 4; ++i ) { if ( !m_expansion_hex_vertices_computed[ quad[i] ] ) { if ( m_is_edge_edge ) { edge_edge_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, ts[i], us[i], vs[i], m_expansion_hex_vertices[ quad[i] ] ); } else { point_triangle_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, ts[i], us[i], vs[i], m_expansion_hex_vertices[ quad[i] ] ); } m_expansion_hex_vertices_computed[ quad[i] ] = true; } } // now run the test in expansion arithmetic Vec3e exp_x; make_vector( d_x, exp_x ); result = rootparity::point_tetrahedron_intersection(exp_x, m_expansion_hex_vertices[ quad[0] ], m_expansion_hex_vertices[ quad[1] ], m_expansion_hex_vertices[ quad[2] ], m_expansion_hex_vertices[ quad[3] ], &s[0], &s[1], &s[2], &s[3], &s[4] ); } if ( result == 0 ) { return false; } return true; } // ---------------------------------------- /// /// Determine if the given segment intersects the triangle /// // ---------------------------------------- bool RootParityCollisionTest::edge_triangle_intersection( const Vec3ui& triangle, const Vec3b& ts, const Vec3b& us, const Vec3b& vs, const Vec3d& d_s0, const Vec3d& d_s1, double* alphas ) { const Vec3Interval& t0 = m_interval_hex_vertices[triangle[0]]; const Vec3Interval& t1 = m_interval_hex_vertices[triangle[1]]; const Vec3Interval& t2 = m_interval_hex_vertices[triangle[2]]; Vec3Interval s0, s1; make_vector( d_s0, s0 ); make_vector( d_s1, s1 ); int result = rootparity::edge_triangle_intersection( s0, s1, t0, t1, t2, &alphas[0], &alphas[1], &alphas[2], &alphas[3], &alphas[4] ); // If degenerate, repeat test using expansion arithmetric if ( result < 0 ) { Vec3e exp_t0, exp_t1, exp_t2; get_triangle_vertices( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, m_is_edge_edge, ts, us, vs, exp_t0, exp_t1, exp_t2 ); Vec3e exp_s0, exp_s1; make_vector( d_s0, exp_s0 ); make_vector( d_s1, exp_s1 ); result = rootparity::edge_triangle_intersection( exp_s0, exp_s1, exp_t0, exp_t1, exp_t2, &alphas[0], &alphas[1], &alphas[2], &alphas[3], &alphas[4] ); } if ( result == 0 ) { return false; } return true; } // ---------------------------------------- /// /// Compute the sign of the implicit surface function which is zero on the bilinear patch defined by quad. /// // ---------------------------------------- int RootParityCollisionTest::implicit_surface_function_sign( const Vec4ui& quad, const Vec4b& ts, const Vec4b& us, const Vec4b& vs, const Vec3d& d_x ) { // first try evaluating sign using interval arithmetic { const Vec3Interval& q0 = m_interval_hex_vertices[quad[0]]; const Vec3Interval& q1 = m_interval_hex_vertices[quad[1]]; const Vec3Interval& q2 = m_interval_hex_vertices[quad[2]]; const Vec3Interval& q3 = m_interval_hex_vertices[quad[3]]; Vec3Interval x; make_vector( d_x, x ); IntervalType f; implicit_surface_function( x, q0, q1, q2, q3, f ); if ( f.is_certainly_negative() ) { return -1; } if ( f.is_certainly_zero() ) { return 0; } if ( f.is_certainly_positive() ) { return 1; } } // not sure about sign - compute using expansion for ( unsigned int i = 0; i < 4; ++i ) { if ( !m_expansion_hex_vertices_computed[ quad[i] ] ) { if ( m_is_edge_edge ) { edge_edge_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, ts[i], us[i], vs[i], m_expansion_hex_vertices[ quad[i] ] ); } else { point_triangle_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, ts[i], us[i], vs[i], m_expansion_hex_vertices[ quad[i] ] ); } m_expansion_hex_vertices_computed[ quad[i] ] = true; } } Vec3e x; make_vector( d_x, x ); expansion ef; implicit_surface_function( x, m_expansion_hex_vertices[ quad[0] ], m_expansion_hex_vertices[ quad[1] ], m_expansion_hex_vertices[ quad[2] ], m_expansion_hex_vertices[ quad[3] ], ef ); return sign( ef ); } // ---------------------------------------- /// /// Test the segment s0-s1 against the bilinear patch defined by quad to determine whether there is an even or odd number of /// intersections. Returns true if odd. /// // ---------------------------------------- bool RootParityCollisionTest::ray_quad_intersection_parity( const Vec4ui& quad, const Vec4b& ts, const Vec4b& us, const Vec4b& vs, const Vec3d& ray_origin, const Vec3d& ray_head, bool& edge_hit, bool& origin_on_surface ) { bool point_in_tet0 = point_tetrahedron_intersection( quad, ts, us, vs, ray_origin ); if ( point_in_tet0 ) { int sign0 = implicit_surface_function_sign( quad, ts, us, vs, ray_origin ); if ( sign0 == 0 ) { origin_on_surface = true; return false; } // s0 is inside the tet, s1 is outside if ( sign0 > 0 ) { // use the triangles on the negative side of f() return test_with_triangles( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, m_is_edge_edge, ts, us, vs, ray_origin, ray_head, false, edge_hit ); } else { // use the triangles on the positive side of f() return test_with_triangles( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, m_is_edge_edge, ts, us, vs, ray_origin, ray_head, true, edge_hit ); } } else { // s0 is outside the tet // both outside // use either set of triangles bool hit_a, hit_b; { double b[5] = { 0.5, 0.5, 0.5, 0.5, 0.5 }; Vec3ui triangle013( quad[0], quad[1], quad[3] ); Vec3b t013( ts[0], ts[1], ts[3] ); Vec3b u013( us[0], us[1], us[3] ); Vec3b v013( vs[0], vs[1], vs[3] ); hit_a = edge_triangle_intersection( triangle013, t013, u013, v013, ray_origin, ray_head, b ); if ( b[2] == 0.0 || b[3] == 0.0 || b[4] == 0.0 ) { edge_hit = true; } if ( b[2] == 1.0 || b[3] == 1.0 || b[4] == 1.0 ) { edge_hit = true; } } { double b[5] = { 0.5, 0.5, 0.5, 0.5, 0.5 }; Vec3ui triangle032( quad[0], quad[3], quad[2] ); Vec3b t032( ts[0], ts[3], ts[2] ); Vec3b u032( us[0], us[3], us[2] ); Vec3b v032( vs[0], vs[3], vs[2] ); hit_b = edge_triangle_intersection( triangle032, t032, u032, v032, ray_origin, ray_head, b ); if ( b[2] == 0.0 || b[3] == 0.0 || b[4] == 0.0 ) { edge_hit = true; } if ( b[2] == 1.0 || b[3] == 1.0 || b[4] == 1.0 ) { edge_hit = true; } } return hit_a ^ hit_b; } assert( !"Should not get here" ); return true; } // -------------------------------------------------------- /// /// Determine the parity of the number of intersections between a ray from the origin and the generalized prism made up /// of f(G) where G = the vertices of the domain boundary. /// // -------------------------------------------------------- bool RootParityCollisionTest::ray_prism_parity_test() { Vec3d test_ray( m_ray ); double ray_len = mag( test_ray ); std::vector<Vec3ui> tris(2); tris[0] = Vec3ui( 0, 1, 2 ); tris[1] = Vec3ui( 3, 4, 5 ); std::vector<Vec4ui> quads(3); quads[0] = Vec4ui( 0, 1, 3, 4 ); quads[1] = Vec4ui( 1, 2, 4, 5 ); quads[2] = Vec4ui( 0, 2, 3, 5 ); const bool vertex_ts[6] = { 0, 0, 0, 1, 1, 1 }; const bool vertex_us[6] = { 0, 1, 0, 0, 1, 0 }; const bool vertex_vs[6] = { 0, 0, 1, 0, 0, 1 }; // for debugging purposes, store the result of each hit test std::vector<bool> tri_hits( 2, false ); std::vector<bool> quad_hits( 3, false ); bool good_hit = false; unsigned int num_tries = 0; while (!good_hit && num_tries++ < 10 ) { good_hit = true; // ray-cast against each tri and each quad for ( unsigned int i = 0; i < tris.size(); ++i ) { const Vec3ui& t = tris[i]; double bary[5] = { 0.5, 0.5, 0.5, 0.5, 0.5 }; Vec3b ts( vertex_ts[t[0]], vertex_ts[t[1]], vertex_ts[t[2]] ); Vec3b us( vertex_us[t[0]], vertex_us[t[1]], vertex_us[t[2]] ); Vec3b vs( vertex_vs[t[0]], vertex_vs[t[1]], vertex_vs[t[2]] ); tri_hits[i] = rootparity::edge_triangle_intersection( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, m_is_edge_edge, ts, us, vs, Vec3d(0,0,0), test_ray, bary ); if ( tri_hits[i] ) { if ( bary[2] == 0.0 || bary[3] == 0.0 || bary[4] == 0.0 ) { good_hit = false; } if ( bary[2] == 1.0 || bary[3] == 1.0 || bary[4] == 1.0 ) { good_hit = false; } if ( bary[0] == 1.0 ) { // origin is on surface return true; } } } for ( unsigned int i = 0; i < quads.size(); ++i ) { const Vec4ui& q = quads[i]; bool edge_hit = false; bool origin_on_surface = false; Vec4b ts( vertex_ts[q[0]], vertex_ts[q[1]], vertex_ts[q[2]], vertex_ts[q[3]] ); Vec4b us( vertex_us[q[0]], vertex_us[q[1]], vertex_us[q[2]], vertex_us[q[3]] ); Vec4b vs( vertex_vs[q[0]], vertex_vs[q[1]], vertex_vs[q[2]], vertex_vs[q[3]] ); quad_hits[i] = ray_quad_intersection_parity( q, ts, us, vs, Vec3d(0,0,0), test_ray, edge_hit, origin_on_surface ); if ( edge_hit ) { good_hit = false; break; } if ( origin_on_surface ) { return true; } } // check if any hit was not good if ( !good_hit ) { double r = rand() / (double)RAND_MAX * 2.0 * M_PI; test_ray[0] = cos(r) * ray_len; test_ray[1] = -sin(r) * ray_len; } } if ( !good_hit ) { return true; } unsigned int num_hits = 0; for ( unsigned int i = 0; i < tri_hits.size(); ++i ) { if ( tri_hits[i] ) { ++num_hits; } } for ( unsigned int i = 0; i < quad_hits.size(); ++i ) { if ( quad_hits[i] ) { ++num_hits; } } return ( num_hits % 2 == 1 ); } // -------------------------------------------------------- /// /// Determine the parity of the number of intersections between a ray from the origin and the generalized hexahedron made /// up of f(G) where G = the vertices of the domain boundary (corners of the unit cube). /// // -------------------------------------------------------- bool RootParityCollisionTest::ray_hex_parity_test( ) { const bool vertex_ts[8] = { 0, 1, 1, 0, 0, 1, 1, 0 }; const bool vertex_us[8] = { 0, 0, 1, 1, 0, 0, 1, 1 }; const bool vertex_vs[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; Vec3d test_ray( m_ray ); double ray_len = mag( test_ray ); bool good_hit = false; unsigned int num_tries = 0; // bilinear patch faces of the mapped hex std::vector<Vec4ui> quads(6); quads[0] = Vec4ui( 0, 1, 3, 2 ); quads[1] = Vec4ui( 0, 1, 4, 5 ); quads[2] = Vec4ui( 1, 2, 5, 6 ); quads[3] = Vec4ui( 2, 3, 6, 7 ); quads[4] = Vec4ui( 3, 0, 7, 4 ); quads[5] = Vec4ui( 4, 5, 7, 6 ); // for debugging purposes, store the result of each hit test std::vector<bool> hits( 6, false ); // (t,u,v) coordinates of each vertex on the hexahedron while (!good_hit && num_tries++ < 10 ) { good_hit = true; bool any_origin_on_surface = false; // ray-cast against each quad for ( int i = 0; i < 6; ++i ) { const Vec4ui& quad = quads[i]; Vec4b ts( vertex_ts[quad[0]], vertex_ts[quad[1]], vertex_ts[quad[2]], vertex_ts[quad[3]] ); Vec4b us( vertex_us[quad[0]], vertex_us[quad[1]], vertex_us[quad[2]], vertex_us[quad[3]] ); Vec4b vs( vertex_vs[quad[0]], vertex_vs[quad[1]], vertex_vs[quad[2]], vertex_vs[quad[3]] ); bool edge_hit = false; bool origin_on_surface = false; hits[i] = ray_quad_intersection_parity( quad, ts, us, vs, Vec3d(0,0,0), test_ray, edge_hit, origin_on_surface ); if ( edge_hit ) { good_hit = false; } if ( origin_on_surface ) { any_origin_on_surface = true; } } if ( any_origin_on_surface ) { return true; } // check if any hit was not okay if ( !good_hit ) { double r = rand() / (double)RAND_MAX * 2.0 * M_PI; test_ray[0] = cos(r) * ray_len; test_ray[1] = -sin(r) * ray_len; } } if ( !good_hit ) { return true; } unsigned int num_hits = 0; for ( unsigned int i = 0; i < hits.size(); ++i ) { if ( hits[i] ) { ++num_hits; } } return ( num_hits % 2 == 1 ); } /// -------------------------------------------------------- /// /// For each triangle, form the plane it lies on, and determine if all m_interval_hex_vertices are on one side of the plane. /// /// -------------------------------------------------------- bool RootParityCollisionTest::plane_culling( const std::vector<Vec3ui>& triangles, const std::vector<Vec3d>& boundary_vertices ) { std::size_t num_triangles = triangles.size(); std::size_t num_boundary_vertices = boundary_vertices.size(); for ( unsigned int i = 0; i < num_triangles; ++i ) { const Vec3ui& t = triangles[i]; Vec3d normal = cross( boundary_vertices[t[1]] - boundary_vertices[t[0]], boundary_vertices[t[2]] - boundary_vertices[t[0]] ); if ( mag(normal) == 0.0 ) { continue; } normal = normalized(normal); IntervalType::begin_special_arithmetic(); const int sgn = plane_sign( normal, m_interval_hex_vertices[0] ); IntervalType::end_special_arithmetic(); if ( sgn == 0 ) { continue; } bool all_same_side = true; for ( unsigned int v = 1; v < num_boundary_vertices; ++v ) { IntervalType::begin_special_arithmetic(); const int this_plane_sign = plane_sign( normal, m_interval_hex_vertices[v] ); IntervalType::end_special_arithmetic(); if ( this_plane_sign == 0 || this_plane_sign != sgn ) { all_same_side = false; break; } } if ( all_same_side ) { return true; } } IntervalType::end_special_arithmetic(); return false; } /// -------------------------------------------------------- /// /// Take a set of planes defined by the mapped domain boundary, and determine if all m_interval_hex_vertices on one side of /// any plane. /// /// -------------------------------------------------------- bool RootParityCollisionTest::edge_edge_interval_plane_culling() { std::vector<Vec3d> hex_vertices(8); for ( unsigned int i = 0; i < 8; ++i ) { hex_vertices[i][0] = m_interval_hex_vertices[i][0].estimate(); hex_vertices[i][1] = m_interval_hex_vertices[i][1].estimate(); hex_vertices[i][2] = m_interval_hex_vertices[i][2].estimate(); } std::vector<Vec3ui> triangles(12); triangles[0] = Vec3ui(0,1,3); triangles[1] = Vec3ui(0,3,2); triangles[2] = Vec3ui(0,1,4); triangles[3] = Vec3ui(0,4,5); triangles[4] = Vec3ui(1,2,5); triangles[5] = Vec3ui(1,5,6); triangles[6] = Vec3ui(2,3,6); triangles[7] = Vec3ui(2,6,7); triangles[8] = Vec3ui(3,0,7); triangles[9] = Vec3ui(3,7,4); triangles[10] = Vec3ui(4,5,7); triangles[11] = Vec3ui(4,7,6); return plane_culling( triangles, hex_vertices ); } /// -------------------------------------------------------- /// /// Take a set of planes defined by the mapped domain boundary, and determine if all m_interval_hex_vertices lie on one side of /// any plane. /// /// -------------------------------------------------------- bool RootParityCollisionTest::point_triangle_interval_plane_culling() { std::vector<Vec3d> hex_vertices(6); for ( unsigned int i = 0; i < 6; ++i ) { hex_vertices[i][0] = m_interval_hex_vertices[i][0].estimate(); hex_vertices[i][1] = m_interval_hex_vertices[i][1].estimate(); hex_vertices[i][2] = m_interval_hex_vertices[i][2].estimate(); } std::vector<Vec3ui> triangles(8); triangles[0] = Vec3ui(0,1,2); triangles[1] = Vec3ui(3,4,5); triangles[2] = Vec3ui(0,1,3); triangles[3] = Vec3ui(0,3,4); triangles[4] = Vec3ui(1,2,4); triangles[5] = Vec3ui(1,4,5); triangles[6] = Vec3ui(0,2,3); triangles[7] = Vec3ui(0,2,5); return plane_culling( triangles, hex_vertices ); } /// -------------------------------------------------------- /// /// Take a fixed set of planes and determine if all m_interval_hex_vertices lie on one side of any plane. /// /// -------------------------------------------------------- bool RootParityCollisionTest::fixed_plane_culling( unsigned int num_hex_vertices ) { for ( int i = -1; i < 1; ++i ) { for ( int j = -1; j < 1; ++j ) { for ( int k = -1; k < 1; ++k ) { Vec3i normal( i, k, j ); const int plane_sign = quick_1_plane_sign( normal, m_interval_hex_vertices[0] ); if ( plane_sign == 0 ) { continue; } bool all_same_side = true; for ( unsigned int v = 1; v < num_hex_vertices; ++v ) { const int this_plane_sign = quick_1_plane_sign( normal, m_interval_hex_vertices[v] ); if ( this_plane_sign == 0 || this_plane_sign != plane_sign ) { all_same_side = false; break; } } if ( all_same_side ) { return true; } } } } return false; } /// -------------------------------------------------------- /// /// Run edge-edge continuous collision detection /// /// -------------------------------------------------------- bool RootParityCollisionTest::edge_edge_collision( ) { static const bool vertex_ts[8] = { 0, 1, 1, 0, 0, 1, 1, 0 }; static const bool vertex_us[8] = { 0, 0, 1, 1, 0, 0, 1, 1 }; static const bool vertex_vs[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; // Get the transformed corners of the domain boundary in interval representation IntervalType::begin_special_arithmetic(); edge_edge_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, vertex_ts[0], vertex_us[0], vertex_vs[0], m_interval_hex_vertices[0] ); edge_edge_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, vertex_ts[1], vertex_us[1], vertex_vs[1], m_interval_hex_vertices[1] ); edge_edge_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, vertex_ts[2], vertex_us[2], vertex_vs[2], m_interval_hex_vertices[2] ); edge_edge_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, vertex_ts[3], vertex_us[3], vertex_vs[3], m_interval_hex_vertices[3] ); edge_edge_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, vertex_ts[4], vertex_us[4], vertex_vs[4], m_interval_hex_vertices[4] ); edge_edge_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, vertex_ts[5], vertex_us[5], vertex_vs[5], m_interval_hex_vertices[5] ); edge_edge_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, vertex_ts[6], vertex_us[6], vertex_vs[6], m_interval_hex_vertices[6] ); edge_edge_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, vertex_ts[7], vertex_us[7], vertex_vs[7], m_interval_hex_vertices[7] ); // Plane culling: check if all corners are on one side of the plane passing through the origin bool plane_culled = fixed_plane_culling(8); IntervalType::end_special_arithmetic(); bool hex_plane_culled = false; if ( !plane_culled ) { hex_plane_culled = edge_edge_interval_plane_culling(); } bool safe_parity = false; if ( !plane_culled && !hex_plane_culled ) { // Cast ray from origin against boundary image (6 quads) Vec3d xmin( 1e30 ), xmax( -1e30 ); for ( unsigned int i = 0; i < 8; ++i ) { Vec2d interval0 = m_interval_hex_vertices[i][0].get_actual_interval(); Vec2d interval1 = m_interval_hex_vertices[i][1].get_actual_interval(); Vec2d interval2 = m_interval_hex_vertices[i][2].get_actual_interval(); xmin[0] = std::min( xmin[0], interval0[0] ); xmin[1] = std::min( xmin[1], interval1[0] ); xmin[2] = std::min( xmin[2], interval2[0] ); xmax[0] = std::max( xmax[0], interval0[1] ); xmax[1] = std::max( xmax[1], interval1[1] ); xmax[2] = std::max( xmax[2], interval2[1] ); } const double ray_len = std::max( mag(xmin), mag(xmax) ) + 10.0; m_ray = Vec3d( ray_len, ray_len, 0 ); safe_parity = ray_hex_parity_test( ); } return safe_parity; } /// ---------------------------------------- /// /// Run point-triangle continuous collision detection /// /// ---------------------------------------- bool RootParityCollisionTest::point_triangle_collision( ) { static const bool vertex_ts[6] = { 0, 0, 0, 1, 1, 1 }; static const bool vertex_us[6] = { 0, 1, 0, 0, 1, 0 }; static const bool vertex_vs[6] = { 0, 0, 1, 0, 0, 1 }; // Get the transformed corners of the domain boundary in interval representation IntervalType::begin_special_arithmetic(); point_triangle_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, vertex_ts[0], vertex_us[0], vertex_vs[0], m_interval_hex_vertices[0] ); point_triangle_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, vertex_ts[1], vertex_us[1], vertex_vs[1], m_interval_hex_vertices[1] ); point_triangle_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, vertex_ts[2], vertex_us[2], vertex_vs[2], m_interval_hex_vertices[2] ); point_triangle_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, vertex_ts[3], vertex_us[3], vertex_vs[3], m_interval_hex_vertices[3] ); point_triangle_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, vertex_ts[4], vertex_us[4], vertex_vs[4], m_interval_hex_vertices[4] ); point_triangle_collision_function( m_x0old, m_x1old, m_x2old, m_x3old, m_x0new, m_x1new, m_x2new, m_x3new, vertex_ts[5], vertex_us[5], vertex_vs[5], m_interval_hex_vertices[5] ); // Plane culling: check if all corners are on one side of the plane passing through the origin bool plane_culled = fixed_plane_culling(6); IntervalType::end_special_arithmetic(); if ( plane_culled ) { return false; } bool prism_plane_culled = point_triangle_interval_plane_culling(); if ( prism_plane_culled ) { return false; } // Cast ray from origin against boundary image (3 quads + 2 triangles) Vec3d xmin( 1e30 ), xmax( -1e30 ); for ( unsigned int i = 0; i < 6; ++i ) { Vec2d interval0 = m_interval_hex_vertices[i][0].get_actual_interval(); Vec2d interval1 = m_interval_hex_vertices[i][1].get_actual_interval(); Vec2d interval2 = m_interval_hex_vertices[i][2].get_actual_interval(); xmin[0] = std::min( xmin[0], interval0[0] ); xmin[1] = std::min( xmin[1], interval1[0] ); xmin[2] = std::min( xmin[2], interval2[0] ); xmax[0] = std::max( xmax[0], interval0[1] ); xmax[1] = std::max( xmax[1], interval1[1] ); xmax[2] = std::max( xmax[2], interval2[1] ); } const double ray_len = std::max( mag(xmin), mag(xmax) ) + 10.0; m_ray = Vec3d( ray_len, ray_len, 0 ); bool safe_parity = ray_prism_parity_test( ); return safe_parity; } } // namespace rootparity
ca7f6a4d3d873d478f3495149eff37459f847cfd
05c8790d8d7ee113075d72e30079da9f2ce64fe1
/QT-Gui/FloatParameter.h
aefe1bed7f250b68c307e9318f1804854e66f7eb
[ "Apache-2.0" ]
permissive
knut0815/realsurf
ab3d059b105728dd2d46aa491c676a68b36dd85e
c0a98aa4762e8e44032bed0a0224ff33454cdf50
refs/heads/master
2021-02-08T17:27:52.015351
2013-11-05T12:38:19
2013-11-05T12:38:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,315
h
#ifndef __FLOATPARAMETER_H__ #define __FLOATPARAMETER_H__ #include "ui_floatParameter.h" #include "FloatParameterProperties.h" class FloatParameter : public QWidget, protected Ui_floatParameter { Q_OBJECT private: QDoubleSpinBox *valueSpinBox; QDoubleSpinBox *minSpinBox; QDoubleSpinBox *maxSpinBox; QSlider *valueSlider; QGroupBox *groupBox; public: FloatParameter( const QString &name, const FloatParameterProperties &fpp, QWidget *parent = 0 ); FloatParameterProperties getProperties() const; QString getName(); public slots: void setProperties( const FloatParameterProperties &fpp ); protected: void connectSubComponents(); void disconnectSubComponents(); protected slots: void spinBoxChanged(); void setValueFromSlider(); void setValueToSlider(); signals: void propertiesChanged( const QString & name, const FloatParameterProperties &fpp ); }; bool operator==( const FloatParameterProperties& fpp1, const FloatParameterProperties& fpp2 ); bool operator!=( const FloatParameterProperties& fpp1, const FloatParameterProperties& fpp2 ); QDataStream & operator<< ( QDataStream & stream, const FloatParameterProperties & fpp ); QDataStream & operator>> ( QDataStream & stream, FloatParameterProperties & fpp ); #endif
190e4464aaee67d052ccc7c7f518ac6b257d3d05
b07baaa9ec8b9f7ec745b97875bebe4f268f6775
/src/tools/vision/fuse_viewer/fuse_viewer_gui.h
20dd2b868301d3b2079be0ab0eced04d64faf09b
[]
no_license
timn/fawkes
9a56dc42aacbb87302ac813d5cc47af9337025db
bc3024b62963d2144dc085fb7edbff51b360cc51
refs/heads/master
2021-07-21T12:15:15.097567
2021-02-03T12:06:09
2021-02-03T12:06:09
1,030,913
0
0
null
2018-10-05T15:10:45
2010-10-28T05:30:51
C++
UTF-8
C++
false
false
2,632
h
/*************************************************************************** * fuse_viewer.h - Fuse (network camera) Viewer Gui * * Created: Thu Dec 18 14:16:23 2008 * Copyright 2008-2009 Christof Rath <[email protected]> * ****************************************************************************/ /* This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * Read the full text in the LICENSE.GPL file in the doc directory. */ #ifndef _FIREVISION_TOOLS_LOC_VIEWER_LOC_VIEWER_GUI_H_ #define _FIREVISION_TOOLS_LOC_VIEWER_LOC_VIEWER_GUI_H_ #define FUSE_PLUGIN_NAME "fvfountain" #define FOUNTAIN_PORT_PATH "/firevision/fountain/tcp_port" #include <netcomm/dns-sd/avahi_thread.h> #include <gtkmm.h> #include <map> namespace firevision { class NetworkCamera; class FuseImageListWidget; class ImageWidget; } // namespace firevision namespace fawkes { class AvahiDispatcher; } class FuseViewerGtkWindow : public Gtk::Window { public: FuseViewerGtkWindow(BaseObjectType *cobject, const Glib::RefPtr<Gtk::Builder> builder); virtual ~FuseViewerGtkWindow(); private: void on_service_added(fawkes::NetworkService *service); void on_service_removed(fawkes::NetworkService *service); void on_fuse_image_selected(); void on_auto_save_cbt_change(); void on_save_type_change(); void on_save_image_clicked(); void close_image(); void set_status(std::string img_id, std::string host = "", unsigned short port = 0); private: // widgets Gtk::ScrolledWindow * image_list_scroll_; Gtk::Viewport * image_viewport_; Gtk::AspectFrame * save_box_; Gtk::ComboBoxText * save_type_; Gtk::FileChooserButton *save_filechooser_; Gtk::CheckButton * auto_save_; Gtk::Button * save_btn_; Gtk::Statusbar * statusbar_; fawkes::AvahiThread * avahi_thread_; fawkes::AvahiDispatcher *avahi_dispatcher_; firevision::FuseImageListWidget *img_list_widget_; firevision::ImageWidget * img_widget_; firevision::NetworkCamera *cam_; std::map<std::string, std::string> host_service_map_; std::string cur_service_name_; unsigned int img_num_; }; #endif /* FIREVISION_TOOLS_LOC_VIEWER_LOC_VIEWER_GUI_H__ */
c500333683fce23f2561f2cb7044f2da574b55e2
ad5e5d5d620bd6faa9d6dad5c0f61212714e8131
/catkin_ws/src/data_acquisition/include/pcl_lidar_screenshot.hpp
17167f12d485d107bc75e7d78cfad6e26c3cb172
[ "Apache-2.0" ]
permissive
gromovnik1337/ROS_OD_SC
80805cc4134ce6c64957402e0c75a4b5f62e633d
e11ea0780e193a3b045b578d7bf3688ee4aa99f0
refs/heads/main
2023-08-10T17:19:26.520297
2021-09-20T13:24:14
2021-09-20T13:24:14
407,622,802
0
0
null
null
null
null
UTF-8
C++
false
false
609
hpp
#ifndef PCL_SCREENSHOT_HPP #define PCL_SCREENSHOT_HPP // Include necessary libraries //ROS #include <ros/ros.h> #include <sensor_msgs/PointCloud2.h> // PCL #include <pcl/point_cloud.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/visualization/pcl_visualizer.h> #include <pcl/io/pcd_io.h> class getAndView { private: // Create necessary ROS objects ros::NodeHandle _node_handle; // Create a subscriber ros::Subscriber _cloud_subscriber; public: getAndView(); ~getAndView(); void lidarRawDataCallback(const sensor_msgs::PointCloud2::ConstPtr& msg); }; #endif
bc0f6294b79f4c2be87f7afe93ee38a8262566a4
a0423109d0dd871a0e5ae7be64c57afd062c3375
/Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Float2Computer.h
2366272afe8e7ce7ffa9525307122e7c3903db92
[ "Apache-2.0" ]
permissive
marferfer/SpinOff-LoL
1c8a823302dac86133aa579d26ff90698bfc1ad6
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
refs/heads/master
2020-03-29T20:09:20.322768
2018-10-09T10:19:33
2018-10-09T10:19:33
150,298,258
0
0
null
null
null
null
UTF-8
C++
false
false
980
h
// This file was generated based on C:/Users/JuanJose/AppData/Local/Fusetools/Packages/Fuse.Marshal/1.9.0/Computer.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Computer1-1.h> #include <Uno.Float2.h> namespace g{namespace Fuse{struct Float2Computer;}} namespace g{ namespace Fuse{ // internal sealed class Float2Computer :224 // { ::g::Fuse::Computer1_type* Float2Computer_typeof(); void Float2Computer__ctor_2_fn(Float2Computer* __this); void Float2Computer__New1_fn(Float2Computer** __retval); void Float2Computer__TryOpImpl_fn(Float2Computer* __this, int32_t* op, ::g::Uno::Float2* a, ::g::Uno::Float2* b, bool* result, bool* __retval); void Float2Computer__TryOpImpl1_fn(Float2Computer* __this, int32_t* op, ::g::Uno::Float2* a, ::g::Uno::Float2* b, ::g::Uno::Float2* result, bool* __retval); struct Float2Computer : ::g::Fuse::Computer1 { void ctor_2(); static Float2Computer* New1(); }; // } }} // ::g::Fuse
e7e814d0315d708cad2be2ba6014ef00c980d589
547e084c5b075c118a917a937fac202a44abd045
/C++/58-HocDeQui/main.cpp
b35833fd74043c3377532d8b7ef4b2bd76a85123
[]
no_license
laquythi/laquythi.github.io
016c9b9220d3c115e722a4634bf4a83ccb809501
37c7285effce53e9076e6562e368c6f7378c973c
refs/heads/master
2022-07-15T10:24:07.922753
2021-06-24T09:05:25
2021-06-24T09:05:25
183,374,657
1
0
null
2022-06-03T03:33:10
2019-04-25T06:53:55
HTML
UTF-8
C++
false
false
737
cpp
#include <iostream> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int TinhGiaiThua(int n); void H10ToH2(int n); int main(int argc, char** argv) { // int gt=TinhGiaiThua(5); // cout<<"5!="<<gt<<endl; int n; cout<<"nhap n:"; cin>>n; int giaiThua = TinhGiaiThua(n); cout<<n<<"! = "<<giaiThua<<endl; H10ToH2(11); cout<<"\n"; H10ToH2(110); return 0; } // cach 1 //int TinhGiaiThua(int n){ // if(n<=1)return 1; // return n*TinhGiaiThua(n-1); //} // cach 2 : viet tuong minh hon int TinhGiaiThua(int n){ if(n <= 1){ return 1; }else{ return n*TinhGiaiThua(n-1); } } void H10ToH2(int n){ if(n>0){ int t=n%2; H10ToH2(n/2); cout<<t<<" "; } }
4588bc2db25ded59fe7f888d2a0219cc94459456
4d6ec3eb29b40e49728085e20c6074b817f65402
/leetcode-algorithms/376. Wiggle Subsequenc/376. Wiggle Subsequence.cpp
9efb851f929520c971355a62d42f560074557cc4
[]
no_license
ShuyiLU/leetcode
fba9960a0a2bb180a9103f1efff2c20a25bd1f57
f8784b271099b766e180e92313e331917c426844
refs/heads/master
2020-08-28T01:27:26.970875
2019-11-06T15:09:32
2019-11-06T15:09:32
217,546,725
0
0
null
null
null
null
GB18030
C++
false
false
605
cpp
#include<iostream> #include<vector> using namespace std; class Solution { public: int wiggleMaxLength(vector<int>& nums) { vector<int> up(nums.size(), 1); vector<int> down(nums.size(), 1); for(int i=1; i<nums.size(); i++){ if(nums[i] > nums[i-1]){ up[i] = down[i-1] + 1; //当前到下降时的最大长度 + 1 down[i] = down[i-1]; } else if(nums[i] < nums[i-1]){ down[i] = up[i-1] + 1; up[i] = up[i-1]; } else{ up[i] = up[i-1]; down[i] = down[i-1]; } } return max(up[nums.size()-1], down[nums.size()-1]); } };
35abcc3c7942308aba2c8e77c494b1fd4cb73e4c
e87da7a3b1e5fcad4ae4c2de4f4800d736194036
/engine/src/libCoreCommon/round_robin_service_selector.h
e4ddbfb01224b5df825a0ef7737e3b8f9af55ba7
[]
no_license
lxq2537664558/realtime_ex
ab7713c37a971d904d709880bccab9b3fcfde79d
f3e09f854e3a4ff0dcc6a53ceee82f795ba140cd
refs/heads/master
2021-05-13T16:16:44.309001
2017-11-10T05:48:52
2017-11-10T05:48:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
465
h
#pragma once #include "service_selector.h" namespace core { class CRoundRobinServiceSelector : public CServiceSelector { public: CRoundRobinServiceSelector(CServiceBase* pServiceBase); virtual ~CRoundRobinServiceSelector(); virtual uint32_t select(const std::string& szServiceType, uint32_t nServiceSelectorType, uint64_t nContext); virtual bool isCheckHealth() const { return false; } private: uint32_t m_nNextIndex; }; }
[ "379171482.qq.com" ]
379171482.qq.com
09c7294347f579a8b507db47a20188e1b67d329b
9cb6f5a6c0db98f7af43fb81ce91a5025ca3807e
/Beecrowd/1581.cpp
4c92bbc5f2353ceed5813b0bd761608d389e9c1f
[]
no_license
luizaes/competitive-programming
1af3393f0d75fa4d2736a54a44ca04713e998559
9742acbefc9c56ba94d57ead63048e995fa3d203
refs/heads/master
2022-07-30T04:41:45.587448
2022-07-07T19:39:34
2022-07-07T19:39:34
135,094,280
0
0
null
null
null
null
UTF-8
C++
false
false
593
cpp
/* Strings, 1581 - Conversa Internacional */ #include <iostream> using namespace std; int main() { int num_casos, cont = 0, pessoas, i; string lingua_falada, lingua; bool dif = false; char c; cin >> num_casos; while(cont < num_casos) { cin >> pessoas; cin.get(c); for(i = 0; i < pessoas; i++) { getline(cin, lingua); if(i == 0) { lingua_falada = lingua; } else if(lingua.compare(lingua_falada) != 0) { dif = true; } } if(dif) { cout << "ingles" << endl; } else { cout << lingua_falada << endl; } dif = false; cont++; } return 0; }
c39a916c87026912c9c8a07f41ac51fe803efdcb
c43b0d1e041d004d1fa8e1469f57b62d4d4bea88
/zircon/system/utest/usb-virtual-bus/usb-hid-test.cc
5003c0a6553629150800d3066c5d31b7d9a5aef9
[ "BSD-3-Clause", "MIT" ]
permissive
ZVNexus/fuchsia
75122894e09c79f26af828d6132202796febf3f3
c5610ad15208208c98693618a79c705af935270c
refs/heads/master
2023-01-12T10:48:06.597690
2019-07-04T05:09:11
2019-07-04T05:09:11
195,169,207
0
0
BSD-3-Clause
2023-01-05T20:35:36
2019-07-04T04:34:33
C++
UTF-8
C++
false
false
2,784
cc
// Copyright 2019 The Fuchsia 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 "usb-virtual-bus.h" #include "helper.h" #include <ddk/platform-defs.h> #include <dirent.h> #include <endian.h> #include <fbl/auto_call.h> #include <fbl/function.h> #include <fbl/unique_ptr.h> #include <fcntl.h> #include <fuchsia/hardware/input/c/fidl.h> #include <fuchsia/hardware/usb/peripheral/c/fidl.h> #include <fuchsia/hardware/usb/virtual/bus/c/fidl.h> #include <hid/boot.h> #include <lib/async-loop/cpp/loop.h> #include <lib/async-loop/loop.h> #include <lib/fdio/fd.h> #include <lib/fdio/fdio.h> #include <lib/fdio/namespace.h> #include <lib/fdio/spawn.h> #include <lib/fdio/unsafe.h> #include <lib/fdio/watcher.h> #include <lib/fidl-async/bind.h> #include <lib/fzl/fdio.h> #include <sys/stat.h> #include <unistd.h> #include <zircon/hw/usb.h> #include <zircon/processargs.h> #include <zircon/syscalls.h> #include <zxtest/zxtest.h> namespace { class UsbHidTest : public zxtest::Test { public: void SetUp() override { ASSERT_NO_FATAL_FAILURES(bus_.InitUsbHid(&devpath_)); bus_.GetHandles(&peripheral_, &virtual_bus_handle_); } void TearDown() override { ASSERT_EQ(ZX_OK, FidlCall(fuchsia_hardware_usb_peripheral_DeviceClearFunctions, peripheral_->get())); ASSERT_EQ(ZX_OK, FidlCall(fuchsia_hardware_usb_virtual_bus_BusDisable, virtual_bus_handle_->get())); } protected: usb_virtual_bus::USBVirtualBus bus_; fbl::String devpath_; zx::unowned_channel peripheral_; zx::unowned_channel virtual_bus_handle_; }; TEST_F(UsbHidTest, SetAndGetReport) { fbl::unique_fd fd_input(openat(bus_.GetRootFd(), devpath_.c_str(), O_RDWR)); ASSERT_GT(fd_input.get(), 0); fzl::FdioCaller input_fdio_caller_; input_fdio_caller_.reset(std::move(fd_input)); uint8_t buf[sizeof(hid_boot_mouse_report_t)] = {0xab, 0xbc, 0xde}; zx_status_t out_stat; size_t out_report_count; zx_status_t status = fuchsia_hardware_input_DeviceSetReport( input_fdio_caller_.borrow_channel(), fuchsia_hardware_input_ReportType_INPUT, 0, buf, sizeof(buf), &out_stat); ASSERT_EQ(status, ZX_OK); ASSERT_EQ(out_stat, ZX_OK); status = fuchsia_hardware_input_DeviceGetReport( input_fdio_caller_.borrow_channel(), fuchsia_hardware_input_ReportType_INPUT, 0, &out_stat, buf, sizeof(buf), &out_report_count); ASSERT_EQ(status, ZX_OK); ASSERT_EQ(out_stat, ZX_OK); ASSERT_EQ(out_report_count, sizeof(hid_boot_mouse_report_t)); ASSERT_EQ(0xab, buf[0]); ASSERT_EQ(0xbc, buf[1]); ASSERT_EQ(0xde, buf[2]); } } // namespace
81dd737f26e3322e67bb9a96946b8eaa112287d7
3d9df061cb4044dcb781b0c6a252fc590f85f399
/code/ray tracer/ray tracer/Shader.cpp
e340fa105a73aeaa2e82a5c97c83e63a0d6d8509
[]
no_license
jamesrogers93/real-time-ray-tracer
3d443594b185a64493d93c7c82f4eb6bda565eb7
e7d421a3048bc11406991cb43651c82b56b09ac4
refs/heads/master
2023-04-09T20:43:54.322350
2016-11-17T20:52:29
2016-11-17T20:52:29
60,629,722
0
0
null
null
null
null
UTF-8
C++
false
false
2,730
cpp
// // Shader.cpp // Simple Gravity // // Created by James Rogers on 28/12/2015. // Copyright © 2015 James Rogers. All rights reserved. // #include "Shader.h" Shader::Shader() { this->program = 0; } Shader::Shader(const GLchar* vertexPath, const GLchar* fragmentPath) { this->loadShader(vertexPath, fragmentPath); } void Shader::use() { glUseProgram(this->program); } void Shader::loadShader(const GLchar* vertexPath, const GLchar* fragmentPath) { string vertexCode, fragmentCode; ifstream vShaderFile, fShaderFile; //For throwing exceptions vShaderFile.exceptions(ifstream::badbit); fShaderFile.exceptions(ifstream::badbit); try { //Open the files. vShaderFile.open(vertexPath); fShaderFile.open(fragmentPath); stringstream vShaderStream, fShaderStream; //Read buffer contents in to streams. vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); //Close files. vShaderFile.close(); fShaderFile.close(); //Convert stream to vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); } catch (ifstream::failure e) { cout << "ERROR, shader file could not be read" << endl; } //Copy vertex and fragment code to GLchar*'s const GLchar* vShaderCode = vertexCode.c_str(); const GLchar* fShaderCode = fragmentCode.c_str(); //Vertex, Fragment shader pointers GLuint vertex, fragment; //For checking if shader loaded correctly and storing error message GLint success; GLchar infoLog[512]; //Vertex Shader vertex = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex, 1, &vShaderCode, NULL); glCompileShader(vertex); //Check for errors glGetShaderiv(vertex, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertex, 512, NULL, infoLog); cout << "ERROR, Vertex shader compilation failed " << infoLog << endl; } //Fragment Shader fragment = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment, 1, &fShaderCode, NULL); glCompileShader(fragment); //Check for errors glGetShaderiv(fragment, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragment, 512, NULL, infoLog); cout << "ERROR. Fragment shader compilation failed " << infoLog << endl; } //Link Shaders to program this->program = glCreateProgram(); glAttachShader(this->program, vertex); glAttachShader(this->program, fragment); glLinkProgram(this->program); //Check for errors glGetProgramiv(this->program, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(this->program, 512, NULL, infoLog); cout << "ERROR, Shader program compilation failed " << infoLog << endl; } //Now shaders are loaded into program, delete them glDeleteShader(vertex); glDeleteShader(fragment); }
[ "James Rogers" ]
James Rogers
ab00efa9682d3133cfcd4a20fde326573e11ce62
ff505338515523f56537ac0ac298e897c2ab6541
/src/c++/eigen/Eigen/src/SparseLU/SparseLU_SupernodalMatrix.h
2e5c7591a491acd9ac93b17f4fd6d459e18badc5
[]
no_license
yanlei2017/code-learning
f71b4cca223bdf9c7004759f245d1f45c77bc3b5
877aa62ed9cfbc8a2fe1c76957bb11962a3874b4
refs/heads/master
2021-07-09T10:06:57.386934
2020-10-13T16:19:16
2020-10-13T16:19:16
201,642,556
0
0
null
null
null
null
UTF-8
C++
false
false
10,335
h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2012 Désiré Nuentsa-Wakam <[email protected]> // Copyright (C) 2012 Gael Guennebaud <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_SPARSELU_SUPERNODAL_MATRIX_H #define EIGEN_SPARSELU_SUPERNODAL_MATRIX_H namespace Eigen { namespace internal { /** \ingroup SparseLU_Module * \brief a class to manipulate the L supernodal factor from the SparseLU factorization * * This class contain the data to easily store * and manipulate the supernodes during the factorization and solution phase of Sparse LU. * Only the lower triangular matrix has supernodes. * * NOTE : This class corresponds to the SCformat structure in SuperLU * */ /* TODO * InnerIterator as for sparsematrix * SuperInnerIterator to iterate through all supernodes * Function for triangular solve */ template <typename _Scalar, typename _StorageIndex> class MappedSuperNodalMatrix { public: typedef _Scalar Scalar; typedef _StorageIndex StorageIndex; typedef Matrix<StorageIndex,Dynamic,1> IndexVector; typedef Matrix<Scalar,Dynamic,1> ScalarVector; public: MappedSuperNodalMatrix() { } MappedSuperNodalMatrix(Index m, Index n, ScalarVector& nzval, IndexVector& nzval_colptr, IndexVector& rowind, IndexVector& rowind_colptr, IndexVector& col_to_sup, IndexVector& sup_to_col ) { setInfos(m, n, nzval, nzval_colptr, rowind, rowind_colptr, col_to_sup, sup_to_col); } ~MappedSuperNodalMatrix() { } /** * Set appropriate pointers for the lower triangular supernodal matrix * These infos are available at the end of the numerical factorization * FIXME This class will be modified such that it can be use in the course * of the factorization. */ void setInfos(Index m, Index n, ScalarVector& nzval, IndexVector& nzval_colptr, IndexVector& rowind, IndexVector& rowind_colptr, IndexVector& col_to_sup, IndexVector& sup_to_col ) { m_row = m; m_col = n; m_nzval = nzval.data(); m_nzval_colptr = nzval_colptr.data(); m_rowind = rowind.data(); m_rowind_colptr = rowind_colptr.data(); m_nsuper = col_to_sup(n); m_col_to_sup = col_to_sup.data(); m_sup_to_col = sup_to_col.data(); } /** * Number of rows */ Index rows() const { return m_row; } /** * Number of columns */ Index cols() const { return m_col; } /** * Return the array of nonzero values packed by column * * The size is nnz */ Scalar* valuePtr() { return m_nzval; } const Scalar* valuePtr() const { return m_nzval; } /** * Return the pointers to the beginning of each column in \ref valuePtr() */ StorageIndex* colIndexPtr() { return m_nzval_colptr; } const StorageIndex* colIndexPtr() const { return m_nzval_colptr; } /** * Return the array of compressed row indices of all supernodes */ StorageIndex* rowIndex() { return m_rowind; } const StorageIndex* rowIndex() const { return m_rowind; } /** * Return the location in \em rowvaluePtr() which starts each column */ StorageIndex* rowIndexPtr() { return m_rowind_colptr; } const StorageIndex* rowIndexPtr() const { return m_rowind_colptr; } /** * Return the array of column-to-supernode mapping */ StorageIndex* colToSup() { return m_col_to_sup; } const StorageIndex* colToSup() const { return m_col_to_sup; } /** * Return the array of supernode-to-column mapping */ StorageIndex* supToCol() { return m_sup_to_col; } const StorageIndex* supToCol() const { return m_sup_to_col; } /** * Return the number of supernodes */ Index nsuper() const { return m_nsuper; } class InnerIterator; template<typename Dest> void solveInPlace( MatrixBase<Dest>&X) const; protected: Index m_row; // Number of rows Index m_col; // Number of columns Index m_nsuper; // Number of supernodes Scalar* m_nzval; //array of nonzero values packed by column StorageIndex* m_nzval_colptr; //nzval_colptr[j] Stores the location in nzval[] which starts column j StorageIndex* m_rowind; // Array of compressed row indices of rectangular supernodes StorageIndex* m_rowind_colptr; //rowind_colptr[j] stores the location in rowind[] which starts column j StorageIndex* m_col_to_sup; // col_to_sup[j] is the supernode number to which column j belongs StorageIndex* m_sup_to_col; //sup_to_col[s] points to the starting column of the s-th supernode private : }; /** * \brief InnerIterator class to iterate over nonzero values of the current column in the supernodal matrix L * */ template<typename Scalar, typename StorageIndex> class MappedSuperNodalMatrix<Scalar,StorageIndex>::InnerIterator { public: InnerIterator(const MappedSuperNodalMatrix& mat, Index outer) : m_matrix(mat), m_outer(outer), m_supno(mat.colToSup()[outer]), m_idval(mat.colIndexPtr()[outer]), m_startidval(m_idval), m_endidval(mat.colIndexPtr()[outer+1]), m_idrow(mat.rowIndexPtr()[mat.supToCol()[mat.colToSup()[outer]]]), m_endidrow(mat.rowIndexPtr()[mat.supToCol()[mat.colToSup()[outer]]+1]) {} inline InnerIterator& operator++() { m_idval++; m_idrow++; return *this; } inline Scalar value() const { return m_matrix.valuePtr()[m_idval]; } inline Scalar& valueRef() { return const_cast<Scalar&>(m_matrix.valuePtr()[m_idval]); } inline Index index() const { return m_matrix.rowIndex()[m_idrow]; } inline Index row() const { return index(); } inline Index col() const { return m_outer; } inline Index supIndex() const { return m_supno; } inline operator bool() const { return ( (m_idval < m_endidval) && (m_idval >= m_startidval) && (m_idrow < m_endidrow) ); } protected: const MappedSuperNodalMatrix& m_matrix; // Supernodal lower triangular matrix const Index m_outer; // Current column const Index m_supno; // Current SuperNode number Index m_idval; // Index to browse the values in the current column const Index m_startidval; // Start of the column value const Index m_endidval; // End of the column value Index m_idrow; // Index to browse the row indices Index m_endidrow; // End index of row indices of the current column }; /** * \brief Solve with the supernode triangular matrix * */ template<typename Scalar, typename Index_> template<typename Dest> void MappedSuperNodalMatrix<Scalar,Index_>::solveInPlace( MatrixBase<Dest>&X) const { /* Explicit type conversion as the Index type of MatrixBase<Dest> may be wider than Index */ // eigen_assert(X.rows() <= NumTraits<Index>::highest()); // eigen_assert(X.cols() <= NumTraits<Index>::highest()); Index n = int(X.rows()); Index nrhs = Index(X.cols()); const Scalar * Lval = valuePtr(); // Nonzero values Matrix<Scalar,Dynamic,Dest::ColsAtCompileTime, ColMajor> work(n, nrhs); // working vector work.setZero(); for (Index k = 0; k <= nsuper(); k ++) { Index fsupc = supToCol()[k]; // First column of the current supernode Index istart = rowIndexPtr()[fsupc]; // Pointer index to the subscript of the current column Index nsupr = rowIndexPtr()[fsupc+1] - istart; // Number of rows in the current supernode Index nsupc = supToCol()[k+1] - fsupc; // Number of columns in the current supernode Index nrow = nsupr - nsupc; // Number of rows in the non-diagonal part of the supernode Index irow; //Current index row if (nsupc == 1 ) { for (Index j = 0; j < nrhs; j++) { InnerIterator it(*this, fsupc); ++it; // Skip the diagonal element for (; it; ++it) { irow = it.row(); X(irow, j) -= X(fsupc, j) * it.value(); } } } else { // The supernode has more than one column Index luptr = colIndexPtr()[fsupc]; Index lda = colIndexPtr()[fsupc+1] - luptr; // Triangular solve Map<const Matrix<Scalar,Dynamic,Dynamic, ColMajor>, 0, OuterStride<> > A( &(Lval[luptr]), nsupc, nsupc, OuterStride<>(lda) ); Map< Matrix<Scalar,Dynamic,Dest::ColsAtCompileTime, ColMajor>, 0, OuterStride<> > U (&(X(fsupc,0)), nsupc, nrhs, OuterStride<>(n) ); U = A.template triangularView<UnitLower>().solve(U); // Matrix-vector product new (&A) Map<const Matrix<Scalar,Dynamic,Dynamic, ColMajor>, 0, OuterStride<> > ( &(Lval[luptr+nsupc]), nrow, nsupc, OuterStride<>(lda) ); work.topRows(nrow).noalias() = A * U; //Begin Scatter for (Index j = 0; j < nrhs; j++) { Index iptr = istart + nsupc; for (Index i = 0; i < nrow; i++) { irow = rowIndex()[iptr]; X(irow, j) -= work(i, j); // Scatter operation work(i, j) = Scalar(0); iptr++; } } } } } } // end namespace internal } // end namespace Eigen #endif // EIGEN_SPARSELU_MATRIX_H
e61ef1e062500cef9e377e63b70a6800fce949cf
9f93116a1a67b9e2e56c9684eb968175fcdb37a4
/AGGRCOW.cpp
1c1d9b1b5598aa1aef0c4f397f2f8ea3f3ec8172
[]
no_license
Anmol2307/SpojProblems
72d7fa2b1b56f0228dcdd4c803a40ac97abb592e
9784e8149df8ff19f441d77fd30f829e4f1d551d
refs/heads/master
2016-08-03T07:43:26.350944
2014-11-20T10:06:12
2014-11-20T10:06:12
17,081,832
1
1
null
null
null
null
UTF-8
C++
false
false
651
cpp
#include<iostream> #include<cstdio> #include<algorithm> using namespace std; int arr[100001]; int c,n; int f(int x){ int cowsplaced=1; long long int lastpos=arr[0]; for(int i=1;i<n;i++){ if(arr[i]-lastpos>=x){ cowsplaced++; if(cowsplaced==c) return 1; lastpos=arr[i]; } } return 0; } int binSearch(){ int start=0,end=arr[n-1]; while(start<end){ int mid=(start+end)/2; if(f(mid)==1) start=mid+1; else end=mid; } return start-1; } int main(){ int t; scanf("%d",&t); while(t--){ scanf("%d %d",&n,&c); for(int i=0;i<n;i++) scanf("%d",&arr[i]); sort(arr,arr+n); printf("%d\n",binSearch()); } }
176b7a80e93b29e9fd835ad3780442ab38708052
4f91c76818c2312d501156ae9abfc0f6b055199d
/DODATKI/SORT/INTERNI/MAIN.CPP
795d1f8f2829f9e61064e0558d9e6431a9233e62
[]
no_license
MPrtenjak/cppZaVelikeInMale
3f77398755e9849c3109973d7e75c4a24e698c63
c6cb40974254772717fd046417caee73c88d11a0
refs/heads/master
2020-03-21T06:11:22.614385
2018-06-21T19:09:00
2018-06-21T19:09:00
138,204,639
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
3,456
cpp
/* Eden izmed dodanih primerov h knjigi "C++ za velike in male" AVTOR: Matjaž Prtenjak NAMEN: Glavna datoteka programa za sortiranje. OPERACIJSKI SISTEM: Vsi operacijski sistemi */ #include <iostream.h> // za tokove #include <iomanip.h> #include <time.h> // za merjenje časa #include "sort.hpp" TIP_PODATKA *Podatek; int Kolicina; /* SORTIRANJE Z MEHURČKI - BUBBLE SORT */ void bubble() { for (int i = 0; i < Kolicina; i++) for (int j = i + 1; j < Kolicina; j++) if ( manjsi(Podatek[j], Podatek[i]) ) zamenjaj(Podatek[j], Podatek[i]); } /* SORTIRANJE S STRESANJEM - SHAKE SORT */ void shake() { TIP_PODATKA *levi = Podatek, // levi rob *desni = Podatek + Kolicina - 1, // desni rob *start = Podatek; // začetek do { for (TIP_PODATKA *p = levi; p < desni; p++) if ( manjsi(*(p+1), *p) ) { zamenjaj(*p, *(p+1)); start = p; } desni = start; for (p = desni; p > levi; p--) if ( manjsi(*p, *(p-1)) ) { zamenjaj(*p, *(p-1)); start = p; } levi = start; } while (levi < desni); } /* SORTIRANJE Z VSTAVLJANJEM - INSSORT */ void inssort() { for (int i = 0; i < Kolicina; i++) { int k = i; TIP_PODATKA min = Podatek[k]; for (int j = i + 1; j < Kolicina; j++) if ( manjsi(Podatek[j], min) ) { k = j; min = Podatek[k]; } Podatek[k] = Podatek[i]; Podatek[i] = min; } } /* HITRO SORTIRANJE - QuickSort Ker je algoritem rekurziven, funkcija potrebuje parametre! */ void quicksort(TIP_PODATKA *p, int velikost) { do { int i = 0, j = velikost - 1; TIP_PODATKA x = p[ j/2 ]; do { while ( manjsi(p[i], x) ) i++; while ( manjsi(x ,p[j]) ) j--; if (i < j) zamenjaj(p[i], p[j]); } while (++i <= --j); if ( i == j + 3 ) { --i; ++j; } if ( j + 1 < velikost - i ) { if ( j > 0 ) quicksort(p, j+1); p += i; velikost -= i; } else { if ( i < velikost - 1 ) quicksort(p + i, velikost - i); velikost = j + 1; } } while ( velikost > 1 ); } int main() { char vhod[100 + 1], izhod[100 + 1]; int izbor; cout << "Program sortira podatke." << endl << endl; cout << "\t Vpišite vhodno datoteko ... "; cin >> setw(100) >> vhod; cout << "\t Vpišite izhodno datoteko ... "; cin >> setw(100) >> izhod; preberi(vhod); cout << endl; cout << "Izberite algoritem: " << endl; cout << "\t [1] Sortiranje z mehurčki" << endl; cout << "\t [2] Sortiranje s stresanjem" << endl; cout << "\t [3] Sortiranje z vstavljanjem" << endl; cout << "\t [4] Hitro sortiranje" << endl; cout << "\t -----------------------------" << endl; cout << "\t > "; cin >> izbor; time_t start = time(NULL); // sistemski čas switch (izbor) { case 1 : bubble(); break; case 2 : shake(); break; case 3 : inssort(); break; case 4 : quicksort(Podatek, Kolicina); break; default : bubble(); } time_t end = time(NULL); // sistemski čas double razlika = difftime(end, start); // razlika časov cout << endl << endl; cout << " Za sortiranje sem porabil " << razlika << " sekund."<< endl; zapisi(izhod); return VSE_OK; }
4990fb84e33d0c6db4ac811f5f05b2746f612820
5e117c7f994525ed76be9cab04a633fd99ef1d15
/AdvancedLevel/second time/1066.Root of AVL Tree(25)/main.cpp
60b7fe977ae27c77e747cbf5afbbed4a8c28eae6
[]
no_license
Weijun-H/PAT
05151dd355bb87e1b18d7a2139a9acd1b57b5d2e
923260408375f9d06f426f05c7d6654baf8a039c
refs/heads/master
2022-02-16T04:07:25.194752
2019-09-07T16:27:45
2019-09-07T16:27:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,960
cpp
#include <iostream> #include <algorithm> using namespace std; struct Node{ int data; int height; Node* lchild,*rchild; }; int getHeight(Node* root){ if(root==NULL)return 0; return root->height; } void updateHeight(Node* root){ root->height=max(getHeight(root->rchild),getHeight(root->lchild))+1; } int getBanlanceFactor(Node* root){ return getHeight(root->lchild)-getHeight(root->rchild); } void L(Node*& root){ Node* temp=root->rchild; root->rchild=temp->lchild; temp->lchild=root; updateHeight(root); updateHeight(temp); root=temp; } void R(Node*& root){ Node* temp=root->lchild; root->lchild=temp->rchild; temp->rchild=root; updateHeight(root); updateHeight(temp); root=temp; } void insert(Node*&root,int data){ if (root==NULL){ root = new Node; root->data=data; root->lchild=root->rchild=NULL; root->height=1; return; } if(data<root->data){ insert(root->lchild,data); updateHeight(root); if(getBanlanceFactor(root)==2){ if (getBanlanceFactor(root->lchild)==1){ R(root); } else if(getBanlanceFactor(root->lchild)==-1){ L(root->lchild); R(root); } } }else{ insert(root->rchild,data); updateHeight(root); if(getBanlanceFactor(root)==-2){ if(getBanlanceFactor(root->rchild)==-1){ L(root); } else if(getBanlanceFactor(root->rchild)==1){ R(root->rchild); L(root); } } } } Node* create(int data[],int n){ Node* root = NULL; for (int i = 0; i < n; ++i) { insert(root,data[i]); } return root; } int main() { int n; int data[25]; cin>>n; for (int i = 0; i < n; ++i) { cin>>data[i]; } Node* root = create(data,n); cout<<root->data<<endl; }
36ee5d2d92bf786bc1de78803d4b0a392451102c
4056438672d6d6f1ae517f60f5f2dd5a90c8e6a5
/Source/CustomerOrder.cpp
092efd76c52489697b6144a2d172adede48690ba
[]
no_license
Rad-tech-spec/Simulated-Assembly-Line
869da268fae295146b23853cb1ca35e7bd4f1310
3e1729486982feb9c220b147cc3cbbe61266ee3c
refs/heads/master
2023-04-23T18:13:48.473431
2021-05-02T20:44:00
2021-05-02T20:44:00
363,744,256
0
0
null
null
null
null
UTF-8
C++
false
false
3,636
cpp
#include "CustomerOrder.h" #include <vector> #include <iomanip> size_t CustomerOrder::m_widthField; CustomerOrder::CustomerOrder() { this->m_name = ""; this->m_product = ""; this->m_cntItem = 0u; this->m_1stItem = nullptr; } CustomerOrder::CustomerOrder(std::string& str) : CustomerOrder() { Utilities temp; bool flag = true; size_t currentP = 0u; size_t m_count = 1u; char delimi = temp.getDeilimiter(); for (auto i = 0u; i < str.size(); ++i) { if (str[i] == delimi) ++m_count; } std::vector<std::string> temperory; for (auto i = 0u; i < m_count; ++i) { if (flag) { switch (i) { case 0: this->m_name = temp.extractToken(str, currentP, flag); break; case 1: this->m_product = temp.extractToken(str, currentP, flag); break; default: temperory.push_back(temp.extractToken(str, currentP, flag)); break; } if(i < m_count - 1) if (temp.getFieldWidth() > m_widthField) m_widthField = temp.getFieldWidth(); } } m_cntItem = temperory.size(); m_1stItem = new Item * [m_cntItem]; for (auto i = 0u; i < m_cntItem; ++i) m_1stItem[i] = new Item(temperory[i]); } CustomerOrder::CustomerOrder(CustomerOrder& cus) { throw "----> ERROR: Cannot make copies."; } CustomerOrder::CustomerOrder(CustomerOrder&& cus) noexcept { this->operator=(std::move(cus)); } auto CustomerOrder::operator=(CustomerOrder&& cus) noexcept -> CustomerOrder& { if (this != &cus) { if (m_1stItem) { for (auto i = 0u; i < m_cntItem; ++i) delete m_1stItem[i]; delete[] m_1stItem; m_1stItem = nullptr; } this->m_name = cus.m_name; this->m_product = cus.m_product; this->m_widthField = cus.m_widthField; this->m_cntItem = cus.m_cntItem; this->m_1stItem = cus.m_1stItem; cus.m_name = ""; cus.m_product = ""; cus.m_cntItem = 0u; cus.m_1stItem = nullptr; } return *this; } auto CustomerOrder::isOrderFilled() const -> bool { size_t s = 0u; for (auto i = 0u; i < m_cntItem; ++i) if (m_1stItem[i]->m_isFilled) s++; if (s < m_cntItem) return false; else return true; } auto CustomerOrder::isItemFilled(const std::string& itemName) const -> bool { for (auto i = 0u; i < m_cntItem; ++i) if (m_1stItem[i]->m_itemName == itemName) { return m_1stItem[i]->m_isFilled; } return true; } auto CustomerOrder::fillItem(Station& station, std::ostream& os) -> void { for (auto i = 0u; i < m_cntItem; ++i) { if (station.getItemName() == m_1stItem[i]->m_itemName && station.getQuantity() > 0) { station.getQuantity(); m_1stItem[i]->m_serialNumber = station.getNextSerialNumber(); m_1stItem[i]->m_isFilled = true; station.updateQuantity(); os << " Filled " << m_name << ", " << m_product << " [" << station.getItemName() << "]" << std::endl; } if (station.getItemName() == m_1stItem[i]->m_itemName && station.getQuantity() <= 0) os << " Unable to fill " << m_name << ", " << m_product << " [" << station.getItemName() << "]" << std::endl; } } auto CustomerOrder::display(std::ostream& os) const -> void { std::string stat = ""; os << m_name << " - " << m_product << std::endl; for (auto i = 0u; i < m_cntItem; ++i) { if ((m_1stItem[i]->m_isFilled)) stat = "FILLED"; else stat = "MISSING"; os << "[" << std::right << std::setfill('0') << std::setw(6) << m_1stItem[i]->m_serialNumber << "] "; os << std::left << std::setfill(' ') << std::setw(m_widthField) << m_1stItem[i]->m_itemName << " - " << stat << std::endl; } } CustomerOrder::~CustomerOrder() { for (auto i = 0u; i < m_cntItem; ++i) delete this->m_1stItem[i]; delete[] this->m_1stItem; }
fadaf52c2d4ece2aafd6cd0eb2cf26b83dfe3d03
db96b049c8e27f723fcb2f3a99291e631f1a1801
/src/app/cn3d/sequence_viewer.cpp
06495073b3b56d8ea6cc0725777d52ec8d0eaa76
[]
no_license
Watch-Later/ncbi-cxx-toolkit-public
1c3a2502b21c7c5cee2c20c39e37861351bd2c05
39eede0aea59742ca4d346a6411b709a8566b269
refs/heads/master
2023-08-15T14:54:41.973806
2021-10-04T04:03:02
2021-10-04T04:03:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,849
cpp
/* $Id$ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Authors: Paul Thiessen * * File Description: * implementation of non-GUI part of main sequence/alignment viewer * * =========================================================================== */ #include <ncbi_pch.hpp> #include <corelib/ncbistd.hpp> #include <memory> #include <objects/seq/Bioseq.hpp> #include "remove_header_conflicts.hpp" #include "sequence_viewer.hpp" #include "sequence_viewer_window.hpp" #include "sequence_display.hpp" #include "messenger.hpp" #include "alignment_manager.hpp" #include "structure_set.hpp" #include "molecule_identifier.hpp" #include "cn3d_tools.hpp" #include "sequence_set.hpp" #include "cn3d_pssm.hpp" #include <wx/filename.h> USING_NCBI_SCOPE; USING_SCOPE(objects); BEGIN_SCOPE(Cn3D) SequenceViewer::SequenceViewer(AlignmentManager *alnMgr) : // not sure why this cast is necessary, but MSVC requires it... ViewerBase(reinterpret_cast<ViewerWindowBase**>(&sequenceWindow), alnMgr), sequenceWindow(NULL) { } SequenceViewer::~SequenceViewer(void) { } void SequenceViewer::CreateSequenceWindow(bool showNow) { if (sequenceWindow) { sequenceWindow->Show(showNow); if (showNow) GlobalMessenger()->PostRedrawSequenceViewer(this); } else { SequenceDisplay *display = GetCurrentDisplay(); if (display) { sequenceWindow = new SequenceViewerWindow(this); #ifdef __WXMAC__ // Nudge down a bit to compensate for the menubar at the top of the screen wxPoint p = sequenceWindow->GetPosition(); p.y += 20; sequenceWindow->Move(p); #endif sequenceWindow->NewDisplay(display, true); sequenceWindow->ScrollToColumn(display->GetStartingColumn()); sequenceWindow->Show(showNow); // ScrollTo causes immediate redraw, so don't need a second one GlobalMessenger()->UnPostRedrawSequenceViewer(this); } } } void SequenceViewer::SaveAlignment(void) { KeepCurrent(); // go back into the original pairwise alignment data and save according to the // current edited BlockMultipleAlignment and display row order vector < unsigned int > rowOrder; const SequenceDisplay *display = GetCurrentDisplay(); for (unsigned int i=0; i<display->rows.size(); ++i) { DisplayRowFromAlignment *alnRow = dynamic_cast<DisplayRowFromAlignment*>(display->rows[i]); if (alnRow) rowOrder.push_back(alnRow->row); } alignmentManager->SavePairwiseFromMultiple(GetCurrentAlignments().back(), rowOrder); } void SequenceViewer::DisplayAlignment(BlockMultipleAlignment *alignment) { SequenceDisplay *display = new SequenceDisplay(true, viewerWindow); for (unsigned int row=0; row<alignment->NRows(); ++row) display->AddRowFromAlignment(row, alignment); // set starting scroll to a few residues left of the first aligned block display->SetStartingColumn(alignment->GetFirstAlignedBlockPosition() - 5); AlignmentList alignments; alignments.push_back(alignment); InitData(&alignments, display); if (sequenceWindow) sequenceWindow->UpdateDisplay(display); else if (IsWindowedMode()) CreateSequenceWindow(false); } bool SequenceViewer::ReplaceAlignment(const BlockMultipleAlignment *origAln, BlockMultipleAlignment *newAln) { AlignmentList& alignments = GetCurrentAlignments(); SequenceDisplay *display = GetCurrentDisplay(); // sanity checks if (alignments.size() != 1 || alignments.front() != origAln || !sequenceWindow || !sequenceWindow->EditorIsOn()) { ERRORMSG("SequenceViewer::ReplaceAlignment() - bad parameters"); return false; } // empty out and then recreate the current alignment list and display (but not the undo stacks!) DELETE_ALL_AND_CLEAR(alignments, AlignmentList); alignments.push_back(newAln); display->Empty(); display->AddBlockBoundaryRow(newAln); for (unsigned int row=0; row<newAln->NRows(); ++row) display->AddRowFromAlignment(row, newAln); // set starting scroll to a few residues left of the first aligned block display->SetStartingColumn(newAln->GetFirstAlignedBlockPosition() - 5); Save(); // make this an undoable operation if (sequenceWindow) sequenceWindow->UpdateDisplay(display); return true; } void SequenceViewer::DisplaySequences(const SequenceList *sequenceList) { SequenceDisplay *display = new SequenceDisplay(false, viewerWindow); // populate each line of the display with one sequence, with blank lines inbetween SequenceList::const_iterator s, se = sequenceList->end(); for (s=sequenceList->begin(); s!=se; ++s) { // only do sequences from structure if this is a single-structure data file if (!(*s)->parentSet->IsMultiStructure() && (*s)->parentSet->objects.front()->mmdbID != (*s)->identifier->mmdbID) continue; if (display->NRows() > 0) display->AddRowFromString(""); // whole sequence on one row display->AddRowFromSequence(*s, 0, (*s)->Length() - 1); } InitData(NULL, display); if (sequenceWindow) sequenceWindow->UpdateDisplay(display); else if (IsWindowedMode()) CreateSequenceWindow(false); } void SequenceViewer::TurnOnEditor(void) { if (!sequenceWindow) CreateSequenceWindow(false); sequenceWindow->TurnOnEditor(); } static void DumpFASTA(bool isA2M, const BlockMultipleAlignment *alignment, const vector < int >& rowOrder, BlockMultipleAlignment::eUnalignedJustification justification, CNcbiOstream& os) { // do whole alignment for now unsigned int firstCol = 0, lastCol = alignment->AlignmentWidth() - 1, nColumns = 70; if (lastCol >= alignment->AlignmentWidth() || firstCol > lastCol || nColumns < 1) { ERRORMSG("DumpFASTA() - nonsensical display region parameters"); return; } // first fill out ids typedef map < const MoleculeIdentifier * , list < string > > IDMap; IDMap idMap; unsigned int row; bool anyRepeat = false; for (row=0; row<alignment->NRows(); ++row) { const Sequence *seq = alignment->GetSequenceOfRow(row); list < string >& titleList = idMap[seq->identifier]; CNcbiOstrstream oss; oss << '>'; if (titleList.size() == 0) { // create full title line for first instance of this sequence CBioseq::TId::const_iterator i, ie = seq->bioseqASN->GetId().end(); for (i=seq->bioseqASN->GetId().begin(); i!=ie; ++i) { if (i != seq->bioseqASN->GetId().begin()) oss << '|'; oss << (*i)->AsFastaString(); } string descr = seq->GetDescription(); if (descr.size() > 0) oss << ' ' << descr; } else { // add repeat id oss << "lcl|instance #" << (titleList.size() + 1) << " of " << seq->identifier->ToString(); anyRepeat = true; } oss << '\n'; titleList.resize(titleList.size() + 1); titleList.back() = (string) CNcbiOstrstreamToString(oss); } static const int eAllRepeats=0, eFakeRepeatIDs=1, eNoRepeats=2; int choice = eAllRepeats; if (anyRepeat) { wxArrayString choices; choices.Add("Include all repeats with normal IDs"); choices.Add("Include all repeats, but use unique IDs"); choices.Add("Include no repeated sequences"); choice = wxGetSingleChoiceIndex("How do you want to handle repeated sequences?", "Choose repeat type", choices); if (choice < 0) return; // cancelled } // output each alignment row (in order of the display) unsigned int paragraphStart, nParags = 0, i; char ch; Vector color, bgColor; bool highlighted, drawBG; for (row=0; row<alignment->NRows(); ++row) { const Sequence *seq = alignment->GetSequenceOfRow(rowOrder[row]); // output title list < string >& titleList = idMap[seq->identifier]; if (choice == eAllRepeats) { os << titleList.front(); // use full id } else if (choice == eFakeRepeatIDs) { os << titleList.front(); titleList.pop_front(); // move to next (fake) id } else if (choice == eNoRepeats) { if (titleList.size() > 0) { os << titleList.front(); titleList.clear(); // remove all ids after first instance } else { continue; } } // split alignment up into "paragraphs", each with nColumns for (paragraphStart=0; (firstCol+paragraphStart)<=lastCol; paragraphStart+=nColumns, ++nParags) { for (i=0; i<nColumns && (firstCol+paragraphStart+i)<=lastCol; ++i) { if (alignment->GetCharacterTraitsAt(firstCol+paragraphStart+i, rowOrder[row], justification, &ch, &color, &highlighted, &drawBG, &bgColor)) { if (ch == '~') os << (isA2M ? '.' : '-'); else os << (isA2M ? ch : (char) toupper((unsigned char) ch)); } else ERRORMSG("GetCharacterTraitsAt failed!"); } os << '\n'; } } } static string ShortAndEscapedString(const string& s) { string n; for (unsigned int i=0; i<s.size(); ++i) { if (s[i] == '\'') n += '\\'; n += s[i]; if (i > 500) break; } return n; } static void DumpText(bool doHTML, const BlockMultipleAlignment *alignment, const vector < int >& rowOrder, BlockMultipleAlignment::eUnalignedJustification justification, CNcbiOstream& os) { #define LEFT_JUSTIFY resetiosflags(IOS_BASE::right) << setiosflags(IOS_BASE::left) #define RIGHT_JUSTIFY resetiosflags(IOS_BASE::left) << setiosflags(IOS_BASE::right) // do whole alignment for now unsigned int firstCol = 0, lastCol = alignment->AlignmentWidth() - 1, nColumns = 60; if (lastCol >= alignment->AlignmentWidth() || firstCol > lastCol || nColumns < 1) { ERRORMSG("DumpText() - nonsensical display region parameters"); return; } // HTML colors static const string bgColor("#FFFFFF"), rulerColor("#700777"), numColor("#229922"); // set up the titles and uids, figure out how much space any seqLoc string will take vector < string > titles(alignment->NRows()), uids(doHTML ? alignment->NRows() : 0); unsigned int alnRow, row, maxTitleLength = 0, maxSeqLocStrLength = 0, leftMargin, decimalLength; for (alnRow=0; alnRow<alignment->NRows(); ++alnRow) { row = rowOrder[alnRow]; // translate display row -> data row const Sequence *sequence = alignment->GetSequenceOfRow(row); titles[row] = sequence->identifier->ToString(); if (titles[row].size() > maxTitleLength) maxTitleLength = titles[row].size(); decimalLength = ((int) log10((double) sequence->Length())) + 1; if (decimalLength > maxSeqLocStrLength) maxSeqLocStrLength = decimalLength; // uid for link to entrez if (doHTML) { // prefer gi's, since accessions can be outdated if (sequence->identifier->gi != MoleculeIdentifier::GI_NOT_SET) { uids[row] = NStr::NumericToString(sequence->identifier->gi); } else if (sequence->identifier->pdbID.size() > 0) { if (sequence->identifier->pdbID != "query" && sequence->identifier->pdbID != "consensus") { uids[row] = sequence->identifier->pdbID; #ifdef _STRUCTURE_USE_LONG_PDB_CHAINS_ if (sequence->identifier->pdbChain != " ") uids[row] += string("_") + sequence->identifier->pdbChain; #else if (sequence->identifier->pdbChain != ' ') uids[row] += string("_") + (char) sequence->identifier->pdbChain; #endif } } else { uids[row] = sequence->identifier->GetLabel(); } } } leftMargin = maxTitleLength + maxSeqLocStrLength + 2; // need to keep track of first, last seqLocs for each row in each paragraph; // find seqLoc of first residue >= firstCol vector < int > lastShownSeqLocs(alignment->NRows()); unsigned int alnLoc, i; char ch; Vector color, bgCol; bool highlighted, drawBG; for (alnRow=0; alnRow<alignment->NRows(); ++alnRow) { row = rowOrder[alnRow]; // translate display row -> data row lastShownSeqLocs[row] = -1; for (alnLoc=0; alnLoc<firstCol; ++alnLoc) { if (!alignment->GetCharacterTraitsAt(alnLoc, row, justification, &ch, &color, &highlighted, &drawBG, &bgCol)) ch = '~'; if (ch != '~') lastShownSeqLocs[row]++; } } // header if (doHTML) os << "<HTML><TITLE>Alignment Exported From Cn3D</TITLE>\n" << "<BODY BGCOLOR=" << bgColor << ">\n"; // split alignment up into "paragraphs", each with nColumns if (doHTML) os << "<TABLE>\n"; int paragraphStart, nParags = 0; for (paragraphStart=0; (firstCol+paragraphStart)<=lastCol; paragraphStart+=nColumns, ++nParags) { // start table row if (doHTML) os << "<tr><td><pre>\n"; else if (paragraphStart > 0) os << '\n'; // do ruler unsigned int nMarkers = 0, width; if (doHTML) os << "<font color=" << rulerColor << '>'; for (i=0; i<nColumns && (firstCol+paragraphStart+i)<=lastCol; ++i) { if ((paragraphStart+i+1)%10 == 0) { if (nMarkers == 0) width = leftMargin + i + 1; else width = 10; os << RIGHT_JUSTIFY << setw(width) << (paragraphStart+i+1); ++nMarkers; } } if (doHTML) os << "</font>"; os << '\n'; if (doHTML) os << "<font color=" << rulerColor << '>'; for (i=0; i<leftMargin; ++i) os << ' '; for (i=0; i<nColumns && (firstCol+paragraphStart+i)<=lastCol; ++i) { if ((paragraphStart+i+1)%10 == 0) os << '|'; else if ((paragraphStart+i+1)%5 == 0) os << '*'; else os << '.'; } if (doHTML) os << "</font>"; os << '\n'; int nDisplayedResidues; // output each alignment row for (alnRow=0; alnRow<alignment->NRows(); ++alnRow) { row = rowOrder[alnRow]; // translate display row -> data row const Sequence *sequence = alignment->GetSequenceOfRow(row); // actual sequence characters and colors; count how many non-gaps in each row nDisplayedResidues = 0; string rowChars; vector < string > rowColors; for (i=0; i<nColumns && (firstCol+paragraphStart+i)<=lastCol; ++i) { if (!alignment->GetCharacterTraitsAt(firstCol+paragraphStart+i, row, justification, &ch, &color, &highlighted, &drawBG, &bgCol)) ch = '?'; rowChars += ch; wxString colorStr; colorStr.Printf("#%02x%02x%02x", (int) (color[0]*255), (int) (color[1]*255), (int) (color[2]*255)); rowColors.push_back(WX_TO_STD(colorStr)); if (ch != '~') ++nDisplayedResidues; } // title if (doHTML && uids[row].size() > 0) { string descr = sequence->GetDescription(); os << "<a href=\"https://www.ncbi.nlm.nih.gov/protein/" << uids[row] << "\" onMouseOut=\"window.status=''\"\n" << "onMouseOver=\"window.status='" << ShortAndEscapedString((descr.size() > 0) ? descr : titles[row]) << "';return true\">" << setw(0) << titles[row] << "</a>"; } else { os << setw(0) << titles[row]; } os << setw(maxTitleLength+1-titles[row].size()) << ' '; // left start pos (output 1-numbered for humans...) if (doHTML) os << "<font color=" << numColor << '>'; if (nDisplayedResidues > 0) os << RIGHT_JUSTIFY << setw(maxSeqLocStrLength) << (lastShownSeqLocs[row]+2) << ' '; else os << RIGHT_JUSTIFY << setw(maxSeqLocStrLength) << ' ' << ' '; // dump sequence, applying color changes only when necessary if (doHTML) { string prevColor; for (i=0; i<rowChars.size(); ++i) { if (rowColors[i] != prevColor) { os << "</font><font color=" << rowColors[i] << '>'; prevColor = rowColors[i]; } os << rowChars[i]; } os << "</font>"; } else os << rowChars; // right end pos if (nDisplayedResidues > 0) { os << ' '; if (doHTML) os << "<font color=" << numColor << '>'; os << LEFT_JUSTIFY << setw(0) << (lastShownSeqLocs[row]+nDisplayedResidues+1); if (doHTML) os << "</font>"; } os << '\n'; // setup to begin next parag lastShownSeqLocs[row] += nDisplayedResidues; } // end table row if (doHTML) os << "</pre></td></tr>\n"; } if (doHTML) os << "</TABLE>\n" << "</BODY></HTML>\n"; // additional sanity check on seqloc markers if (firstCol == 0 && lastCol == alignment->AlignmentWidth()-1) { for (alnRow=0; alnRow<alignment->NRows(); ++alnRow) { row = rowOrder[alnRow]; // translate display row -> data row if (lastShownSeqLocs[row] != (int)alignment->GetSequenceOfRow(row)->Length() - 1) { ERRORMSG("DumpText: full display - seqloc markers don't add up for row " << row); break; } } if (alnRow != alignment->NRows()) ERRORMSG("DumpText: full display - seqloc markers don't add up correctly"); } } void SequenceViewer::ExportAlignment(eExportType type) { // get filename wxString extension, wildcard; if (type == asFASTA) { extension = ".fsa"; wildcard = "FASTA Files (*.fsa)|*.fsa"; } else if (type == asFASTAa2m) { extension = ".a2m"; wildcard = "A2M FASTA (*.a2m)|*.a2m"; } else if (type == asText) { extension = ".txt"; wildcard = "Text Files (*.txt)|*.txt"; } else if (type == asHTML) { extension = ".html"; wildcard = "HTML Files (*.html)|*.html"; } else if (type == asPSSM) { extension = ".pssm"; wildcard = "PSSM Files (*.pssm)|*.pssm"; } wxString outputFolder = wxString(GetUserDir().c_str(), GetUserDir().size() - 1); // remove trailing / wxString baseName, outputFile; wxFileName::SplitPath(GetWorkingFilename().c_str(), NULL, &baseName, NULL); wxFileDialog dialog(sequenceWindow, "Choose a file for alignment export:", outputFolder, #ifdef __WXGTK__ baseName + extension, #else baseName, #endif wildcard, wxFD_SAVE | wxFD_OVERWRITE_PROMPT); dialog.SetFilterIndex(0); if (dialog.ShowModal() == wxID_OK) outputFile = dialog.GetPath(); if (outputFile.size() > 0) { // create output stream unique_ptr<CNcbiOfstream> ofs(new CNcbiOfstream(WX_TO_STD(outputFile).c_str(), IOS_BASE::out)); if (!(*ofs)) { ERRORMSG("Unable to open output file " << outputFile.c_str()); return; } // map display row order to rows in BlockMultipleAlignment vector < int > rowOrder; const SequenceDisplay *display = GetCurrentDisplay(); for (unsigned int i=0; i<display->rows.size(); ++i) { DisplayRowFromAlignment *alnRow = dynamic_cast<DisplayRowFromAlignment*>(display->rows[i]); if (alnRow) rowOrder.push_back(alnRow->row); } // actually write the alignment if (type == asFASTA || type == asFASTAa2m) { INFOMSG("exporting" << (type == asFASTAa2m ? " A2M " : " ") << "FASTA to " << outputFile.c_str()); DumpFASTA((type == asFASTAa2m), alignmentManager->GetCurrentMultipleAlignment(), rowOrder, sequenceWindow->GetCurrentJustification(), *ofs); } else if (type == asText || type == asHTML) { INFOMSG("exporting " << (type == asText ? "text" : "HTML") << " to " << outputFile.c_str()); DumpText((type == asHTML), alignmentManager->GetCurrentMultipleAlignment(), rowOrder, sequenceWindow->GetCurrentJustification(), *ofs); } else if (type == asPSSM) { static string prevTitle; if (prevTitle.size() == 0) prevTitle = GetWorkingTitle(); string title = WX_TO_STD(wxGetTextFromUser( "Enter a name for this PSSM (to be used by other applications like PSI-BLAST or RPS-BLAST):", "PSSM Title?", prevTitle.c_str(), *viewerWindow).Strip(wxString::both)); if (title.size() > 0) { INFOMSG("exporting PSSM (" << title << ") to " << outputFile.c_str()); alignmentManager->GetCurrentMultipleAlignment()->GetPSSM().OutputPSSM(*ofs, title); prevTitle = title; } } } } END_SCOPE(Cn3D)
[ "ludwigf@78c7ea69-d796-4a43-9a09-de51944f1b03" ]
ludwigf@78c7ea69-d796-4a43-9a09-de51944f1b03
30d31d943cae94ffae38f9eb7bf886292d206c33
dd1c4797e587c5c939ef6870f974a6d87e776bdc
/my_cpp_code/stack using queues.cpp
13c651e67536bd8764b936ba48dd450969394e1e
[]
no_license
avnyaswanth/DS_AND_ALGO
b18d4d0385c604c2592fc48c526bc267460fb90c
7b4130d80e5d0266a6d3bf5e258d399dfcc054fa
refs/heads/master
2023-08-26T05:22:56.915863
2021-10-12T11:07:57
2021-10-12T11:07:57
309,110,548
0
1
null
2020-12-31T13:38:32
2020-11-01T14:12:10
C++
UTF-8
C++
false
false
646
cpp
#include<iostream> #include<queue> using namespace std; class Stk { queue<int> q1, q2; int size; public: Stk() { size = 0; } void push(int x) { q2.push(x); size++; while(q1.empty()!=1) { q2.push(q1.front()); q1.pop(); } queue<int> q = q1; q1 = q2; q2 = q; } void pop() { if(q1.empty()) return; q1.pop(); size--; } int top() { if(q1.empty()) return -1; return q1.front(); } int cur_size() { return size; } }; int main() { Stk s; s.push(1); s.push(2); s.push(3); s.push(4); s.push(5); cout<<s.top()<<endl; cout<<s.cur_size(); }
703bb6f4ea4c844a8a9b60269516cd22fffdb5f6
0a1be59f55b359866370c2815671af22bd96ff51
/dependencies/skse64/src/skse64/CommonLibSSE/include/RE/TESMagicTargetForm.h
31dc1658fddba33ad1671a9a6a75dbe411f1cb5d
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
joelday/papyrus-debug-server
ba18b18d313a414daefdf0d3472b60a12ca21385
f5c3878cd485ba68aaadf39bb830ca88bf53bfff
refs/heads/master
2023-01-12T14:34:52.919190
2019-12-06T18:41:39
2019-12-06T18:41:39
189,772,905
15
10
MIT
2022-12-27T11:31:04
2019-06-01T20:02:31
C++
UTF-8
C++
false
false
74
h
#pragma once namespace RE { class TESMagicTargetForm { public: }; }
5c512110b1466174368ae05c494b378e6d0858b2
47aca8bc7f4b89c3417dcffeae67c37862e39ec8
/include/nodamushi/svd/enum_helper.hpp
0b017a360e1d49989ccf482a1ea0957199738315
[ "CC0-1.0" ]
permissive
nodamushi/nsvd-reader
14fb366128d53013c3b2990f6cf502130c8f8e8b
cf3a840aaac78d5791df1cf045596ec20dc03257
refs/heads/master
2020-06-27T20:37:05.656337
2019-09-29T13:12:57
2019-09-29T13:12:57
200,042,564
1
0
null
null
null
null
UTF-8
C++
false
false
763
hpp
/* * These codes are licensed under CC0. * http://creativecommons.org/publicdomain/zero/1.0/ */ #ifndef NODAMUSHI_SVD_ENUM_HELPER_HPP #define NODAMUSHI_SVD_ENUM_HELPER_HPP # include <string> # include <cstring> # if __cplusplus >= 201703 # include <string_view> # include <optional> # endif namespace nodamushi{ namespace svd{ //! provide getter,setter template<typename T>struct enum_helper { //! enum_helper is defined static constexpr bool HAS_HELPER=false; // set enum to dst // static bool get(const std::string &name,T &dst) // static bool get(const char* &name,T &dst) // static bool get(std::string_view name,T &dst) // static const char* nameof(Access value) }; } } // end namespace nodamushi #endif //NODAMUSHI_ENUM_HELPER_HPP
ffdfb2905c2a101d70de606ba7246f6b297fb6c1
1a17167c38dc9a12c1f72dd0f3ae7288f5cd7da0
/Source/ThirdParty/angle/tools/clang/plugins/FindBadConstructsAction.cpp
e2395b94b43ef9044302517e34f9f9445f1daee6
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "Zlib", "LicenseRef-scancode-khronos", "BSL-1.0", "BSD-2-Clause" ]
permissive
elix22/Urho3D
c57c7ecb58975f51fabb95bcc4330bc5b0812de7
99902ae2a867be0d6dbe4c575f9c8c318805ec64
refs/heads/master
2023-06-01T01:19:57.155566
2021-12-07T16:47:20
2021-12-07T17:46:58
165,504,739
21
4
MIT
2021-11-05T01:02:08
2019-01-13T12:51:17
C++
UTF-8
C++
false
false
1,865
cpp
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "FindBadConstructsAction.h" #include "clang/AST/ASTConsumer.h" #include "clang/Frontend/FrontendPluginRegistry.h" #include "FindBadConstructsConsumer.h" using namespace clang; namespace chrome_checker { namespace { class PluginConsumer : public ASTConsumer { public: PluginConsumer(CompilerInstance* instance, const Options& options) : visitor_(*instance, options) {} void HandleTranslationUnit(clang::ASTContext& context) override { visitor_.Traverse(context); } private: FindBadConstructsConsumer visitor_; }; } // namespace FindBadConstructsAction::FindBadConstructsAction() { } std::unique_ptr<ASTConsumer> FindBadConstructsAction::CreateASTConsumer( CompilerInstance& instance, llvm::StringRef ref) { return std::make_unique<PluginConsumer>(&instance, options_); } bool FindBadConstructsAction::ParseArgs(const CompilerInstance& instance, const std::vector<std::string>& args) { bool parsed = true; for (size_t i = 0; i < args.size() && parsed; ++i) { if (args[i] == "check-base-classes") { // TODO(rsleevi): Remove this once http://crbug.com/123295 is fixed. options_.check_base_classes = true; } else if (args[i] == "check-ipc") { options_.check_ipc = true; } else if (args[i] == "check-gmock-objects") { options_.check_gmock_objects = true; } else { parsed = false; llvm::errs() << "Unknown clang plugin argument: " << args[i] << "\n"; } } return parsed; } } // namespace chrome_checker static FrontendPluginRegistry::Add<chrome_checker::FindBadConstructsAction> X( "find-bad-constructs", "Finds bad C++ constructs");
c5a4c37b25ba080e534d5f867e072f8dc9978831
5ef0d91085aff5495f9d1243f649b07f5e57afc2
/c++/graph theory/graphinput.cpp
d3c038f09b3619e472aea6442512cd98d5794c23
[]
no_license
NavalPangtey/Competitive-programming
ba925e934b7402aa105bfea1d51350f5045ba9d6
641123d6b98ce72479a923d24d6aca25f6d7a579
refs/heads/main
2022-12-30T13:30:21.361996
2020-10-21T13:54:09
2020-10-21T13:54:09
305,720,814
0
0
null
null
null
null
UTF-8
C++
false
false
469
cpp
//Adjacency list implimantaion #include<bits/stdc++.h> using namespace std; void read() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } int main() { read(); int a , b, n, m; cin >> n >> m; vector<int> v[n + 1]; for (int i = 0 ; i < m; i++) { cin >> a >> b; v[a].push_back(b); v[b].push_back(a); } for (int i = 1; i <= n; i++) { for (auto x : v[i]) cout << x << " "; cout << "\n"; } }
a188b783745e82d0741cc48f983f2c8901aa05f4
4f06b2bd0bf3266e1f064a8cffafd0b9eb502945
/TCRT_5000_IR_SENSOR_MODULE.ino
2b2aa52a3dab4774641c87bd015359dc3b2e73b9
[]
no_license
erkan-polat/arduino
5af119a85aecde641eb7124760e5a40b31c2d451
34f8b2e91dfbd00a6c065467a4e6552802620b99
refs/heads/main
2023-02-12T09:01:19.205380
2021-01-17T11:05:26
2021-01-17T11:05:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
453
ino
const int pinIRd = 8; const int pinIRa = A0; const int pinLED = 9; int IRvalueA = 0; int IRvalueD = 0; void setup() { Serial.begin(9600); pinMode(pinIRd,INPUT); pinMode(pinIRa,INPUT); pinMode(pinLED,OUTPUT); } void loop() { Serial.print("Analog Reading="); Serial.print(IRvalueA); Serial.print("\t Digital Reading="); Serial.println(IRvalueD); delay(1000); IRvalueA = analogRead(pinIRa); IRvalueD = digitalRead(pinIRd); }
6f1d0587dc9acafed44895d042b63eb0ff11ef34
a03ed9feb8ce4983baf67d431cbb2d6de91a70f5
/rendererCpp/material.cpp
6211ecc3b3691afce7eec2502356926b7604669d
[]
no_license
michcio12174/rendererCppOld
d71e3f538a7dff541a4f0243145aa1f3ce2c6781
18ececd0887d5b8589f4a1927436292c8c0fe4f3
refs/heads/master
2021-04-03T10:29:00.530168
2019-01-20T23:08:19
2019-01-20T23:08:19
124,757,245
0
0
null
null
null
null
UTF-8
C++
false
false
448
cpp
#include "stdafx.h" #include "material.h" material::material() { this->materialTexture = new texture(0.4f, 0.4f, 0.4f); } material::material(texture *materialTexture) { this->materialTexture = materialTexture; } material::~material() { } vector3 material::shade(rayHitInfo info) { return getTextureColor(info.hitPoint); } vector3 material::getTextureColor(vector3 localHitPoint) const { return materialTexture->getColor(localHitPoint); }
640b812b0c4289eb062b944f4041b9f88fb3944d
0bd6a68601a053427f463cccad5bfe95f6b134f7
/Bubblesort.cpp
f11c426f47ff206b4736f1d05f7b8555256cbba1
[]
no_license
heyOnuoha/Algorithms-C-
89498895953ea2dbe97ec3566806ad8ef24f069c
02986129e19b762b5126f72f1d453f2ccbc65ac2
refs/heads/master
2021-09-15T11:36:46.817878
2018-05-31T21:28:50
2018-05-31T21:28:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
415
cpp
#include "Bubblesort.h" Bubblesort::Bubblesort() { } Bubblesort::~Bubblesort() { } void Bubblesort::bubblesort(int array[], int size) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (array[i] < array[j]) { swap(array, i, j); } } } } void Bubblesort::swap(int list[], int left, int right) { int temp = list[left]; list[left] = list[right]; list[right] = temp; }
8c1343a7d9d511fcc226fd7c96cf004f904b2bf4
55d560fe6678a3edc9232ef14de8fafd7b7ece12
/libs/hana/example/replace_if.cpp
6ab4a517e3c3f5588cb04e27458663990a037a04
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
stardog-union/boost
ec3abeeef1b45389228df031bf25b470d3d123c5
caa4a540db892caa92e5346e0094c63dea51cbfb
refs/heads/stardog/develop
2021-06-25T02:15:10.697006
2020-11-17T19:50:35
2020-11-17T19:50:35
148,681,713
0
0
BSL-1.0
2020-11-17T19:50:36
2018-09-13T18:38:54
C++
UTF-8
C++
false
false
681
cpp
// Copyright Louis Dionne 2013-2017 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) #include <boost/hana/assert.hpp> #include <boost/hana/config.hpp> #include <boost/hana/equal.hpp> #include <boost/hana/replace_if.hpp> #include <boost/hana/tuple.hpp> namespace hana = boost::hana; BOOST_HANA_CONSTEXPR_LAMBDA auto negative = [](auto x) { return x < 0; }; int main() { BOOST_HANA_CONSTEXPR_CHECK( hana::replace_if(hana::make_tuple(-3, -2, -1, 0, 1, 2, 3), negative, 0) == hana::make_tuple(0, 0, 0, 0, 1, 2, 3) ); }
3f4f48a774dcbe4fded5c749e3cadf1dfcb999a5
c39924b2624e429d280dde795f7837c27a4fd3d2
/client/gui_part/include/Game_Window.hpp
8145cfae60efafbb65a1ecb1e04ec9e3aa3d8532
[]
no_license
trevisg/PSU_zappy_2017
89f697cd721e7e2f23dfa54662ea747f7ae79432
dac14b2d5f4b43d0e66295270bc26eb444a6da3e
refs/heads/master
2020-03-20T15:31:54.264089
2018-07-02T17:56:26
2018-07-02T17:56:26
137,515,428
1
0
null
null
null
null
UTF-8
C++
false
false
1,083
hpp
// // EPITECH PROJECT, 2018 // PSU_zappy_2017 Client GUI // File description: // Gui Game Window Header // #ifndef GAME_WINDOW_HPP_ #include "Network_Client.hpp" #include <map> #include <SFML/Audio.hpp> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> class GameWindow { public: GameWindow(); void _setgame_sound(); void _set_team_names(); void _set_team_details(); sf::Vector2u _set_map_size(); void _DrawBoard(int x_size, int y_size); void _DrawTeams(std::vector<std::string> _teams_names); sf::Text _init_text(std::string team_name); void _event_handler(sf::Event ev); bool _is_there_a_player_here(int y, int x); bool _start_me(); private: Network _client; sf::Font _font; sf::Text _titletext; sf::Music _gamemusic; sf::SoundBuffer _soundbuff; std::vector<std::string> _teams_names; std::vector<std::map<std::string, std::string>> _team_details; std::vector<sf::Text> _teams_text; std::map<std::string, sf::Sound> _gamesounds; }; extern sf::RenderWindow gamewindow; #endif /* !GAME_WINDOW_HPP_ */
9e1d446a3f9fadfa6e52cbef2a56f4c9b13c653b
a9c1d305400ce605870ee4a0dbafe241f55e1d95
/Coursera/Yandex_CppYellow/Week03_Task04_bus_manager.cpp
4a55a35b8d8151cabf3ac3f44c716240e43aa60a
[ "MIT" ]
permissive
zakhars/Education
8bcc6c72edd4ba16b818e7a493068de7a643bf84
88f4963868193e4f9fb4ec6681fa0c4669e156b8
refs/heads/master
2023-02-10T14:59:41.493239
2023-02-03T19:43:10
2023-02-03T19:43:10
101,640,996
0
0
null
null
null
null
UTF-8
C++
false
false
1,407
cpp
#include <map> #include <vector> #include <string> #include <iostream> #include "Week03_Task04_bus_manager.h" #include "Week03_Task04_responses.h" using namespace std; void BusManager::AddBus(const string& bus, const vector<string>& stops) { buses_to_stops[bus] = stops; for (const string& stop : stops) { stops_to_buses[stop].push_back(bus); } } BusesForStopResponse BusManager::GetBusesForStop(const string& stop) const { BusesForStopResponse r = { stop,{} }; if (stops_to_buses.count(stop) > 0) { r.buses = stops_to_buses.at(stop); } return r; } StopsForBusResponse BusManager::GetStopsForBus(const string& bus) const { StopsForBusResponse r = { bus,{} }; if (buses_to_stops.count(bus) > 0) { for (const string& stop : buses_to_stops.at(bus)) { vector<string> interchanges; for (const string& other_bus : stops_to_buses.at(stop)) { if (bus != other_bus) { interchanges.push_back(other_bus); } } r.stops.push_back({ stop, interchanges }); } } return r; } AllBusesResponse BusManager::GetAllBuses() const { AllBusesResponse r; for (const auto& bus_item : buses_to_stops) { r.buses.push_back({ bus_item.first, bus_item.second }); } return r; }
ed9986bd76a9b56a8c1d3d86ba7ec8f9933524c7
cbbef8580d0571c84ab4ce5a559e0fb9d660f485
/data/submissions/530621.cpp
8cab0ca1f3af34a24a03662ecb936ebeecdd618a
[]
no_license
yuantailing/tsinsen
efb4c0297e096b8fa64a3390d6bde3cbaaddb217
a92759dc965ed58a33536e8c6faaa19b0931afbc
refs/heads/main
2023-07-08T11:44:32.294152
2021-08-09T19:34:07
2021-08-09T19:34:07
394,414,206
1
0
null
null
null
null
UTF-8
C++
false
false
885
cpp
#include <iostream> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> using namespace std; int main() { int i,j,k,n,m; char p[100009]; char *a; int b[100009]; int c,d; int buf,tmp; cin >> buf; for (tmp=0;tmp<buf;++tmp){ a=p; a[0]=a[1]=a[2]=a[3]='0'; a=&p[3]; //scanf("%s",&a[2-((n-1)%3)]); scanf("%s",a); n=strlen(a); a=&p[1+((n-1)%3)]; m=(n+2)/3; for (i=0;i<100000;++i){ if (a[i]<='9') b[i]=a[i]-'0'; else b[i]=a[i]-'A'+10; } i=0; c=b[i]*16*16+b[i+1]*16+b[i+2]; d=c/8/8/8*1000+(c/8/8)%8*100+(c/8)%8*10+c%8; cout << d; for (i=3;i<m*3;i+=3){ c=b[i]*16*16+b[i+1]*16+b[i+2]; d=c/8/8/8*1000+(c/8/8)%8*100+(c/8)%8*10+c%8; cout << c/8/8/8 << (c/8/8)%8 << (c/8)%8 << c%8; } cout << endl; } //system("pause"); return 0; }
059140a1dc7f4b9667d33640adc379b2409a97d8
112eaf6e46be9feb0e711e1ee6658e0d5acbff2c
/include/Pins.h
48562893b7d32fe59691a59d1dbc4863dd18502a
[]
no_license
thepipster/funky-van-lights
2d0b71441e65164a6d1e10ddfe7dab1c6bce9774
9f9dcc2ca37b145dae595f735d57c80c5a0f39e0
refs/heads/main
2023-07-18T16:55:12.563631
2021-09-19T01:41:33
2021-09-19T01:41:33
406,593,628
0
0
null
null
null
null
UTF-8
C++
false
false
136
h
#ifndef PINS_H #define PINS_H #include <Arduino.h> class Pins { public: int buttonUp = A5; int buttonDown = A4; }; #endif
d3134a20edc0e771bc4c66bbe114a3b0b2ed950e
641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2
/third_party/crashpad/crashpad/handler/handler_main.cc
29c5ddc14e6c4a26b7842eebb813b00f7c5a2eec
[ "Apache-2.0", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "BSD-3-Clause" ]
permissive
massnetwork/mass-browser
7de0dfc541cbac00ffa7308541394bac1e945b76
67526da9358734698c067b7775be491423884339
refs/heads/master
2022-12-07T09:01:31.027715
2017-01-19T14:29:18
2017-01-19T14:29:18
73,799,690
4
4
BSD-3-Clause
2022-11-26T11:53:23
2016-11-15T09:49:29
null
UTF-8
C++
false
false
14,789
cc
// Copyright 2014 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "handler/handler_main.h" #include <getopt.h> #include <stdint.h> #include <stdlib.h> #include <map> #include <memory> #include <string> #include <utility> #include "base/auto_reset.h" #include "base/files/file_path.h" #include "base/files/scoped_file.h" #include "base/logging.h" #include "base/metrics/persistent_histogram_allocator.h" #include "base/scoped_generic.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "client/crash_report_database.h" #include "client/crashpad_client.h" #include "client/prune_crash_reports.h" #include "handler/crash_report_upload_thread.h" #include "handler/prune_crash_reports_thread.h" #include "tools/tool_support.h" #include "util/file/file_io.h" #include "util/stdlib/map_insert.h" #include "util/stdlib/string_number_conversion.h" #include "util/string/split_string.h" #include "util/synchronization/semaphore.h" #if defined(OS_MACOSX) #include <libgen.h> #include <signal.h> #include "base/mac/scoped_mach_port.h" #include "handler/mac/crash_report_exception_handler.h" #include "handler/mac/exception_handler_server.h" #include "util/mach/child_port_handshake.h" #include "util/mach/mach_extensions.h" #include "util/posix/close_stdio.h" #elif defined(OS_WIN) #include <windows.h> #include "handler/win/crash_report_exception_handler.h" #include "util/win/exception_handler_server.h" #include "util/win/handle.h" #include "util/win/initial_client_data.h" #endif // OS_MACOSX namespace crashpad { namespace { void Usage(const base::FilePath& me) { fprintf(stderr, "Usage: %" PRFilePath " [OPTION]...\n" "Crashpad's exception handler server.\n" "\n" " --annotation=KEY=VALUE set a process annotation in each crash report\n" " --database=PATH store the crash report database at PATH\n" #if defined(OS_MACOSX) " --handshake-fd=FD establish communication with the client over FD\n" " --mach-service=SERVICE register SERVICE with the bootstrap server\n" #elif defined(OS_WIN) " --initial-client-data=HANDLE_request_crash_dump,\n" " HANDLE_request_non_crash_dump,\n" " HANDLE_non_crash_dump_completed,\n" " HANDLE_pipe,\n" " HANDLE_client_process,\n" " Address_crash_exception_information,\n" " Address_non_crash_exception_information,\n" " Address_debug_critical_section\n" " use precreated data to register initial client\n" #endif // OS_MACOSX " --metrics-dir=DIR store metrics files in DIR (only in Chromium)\n" " --no-rate-limit don't rate limit crash uploads\n" #if defined(OS_MACOSX) " --reset-own-crash-exception-port-to-system-default\n" " reset the server's exception handler to default\n" #elif defined(OS_WIN) " --pipe-name=PIPE communicate with the client over PIPE\n" #endif // OS_MACOSX " --url=URL send crash reports to this Breakpad server URL,\n" " only if uploads are enabled for the database\n" " --help display this help and exit\n" " --version output version information and exit\n", me.value().c_str()); ToolSupport::UsageTail(me); } #if defined(OS_MACOSX) struct ResetSIGTERMTraits { static struct sigaction* InvalidValue() { return nullptr; } static void Free(struct sigaction* sa) { int rv = sigaction(SIGTERM, sa, nullptr); PLOG_IF(ERROR, rv != 0) << "sigaction"; } }; using ScopedResetSIGTERM = base::ScopedGeneric<struct sigaction*, ResetSIGTERMTraits>; ExceptionHandlerServer* g_exception_handler_server; // This signal handler is only operative when being run from launchd. void HandleSIGTERM(int sig, siginfo_t* siginfo, void* context) { DCHECK(g_exception_handler_server); g_exception_handler_server->Stop(); } #endif // OS_MACOSX #if defined(OS_WIN) LONG WINAPI UnhandledExceptionHandler(EXCEPTION_POINTERS* exception_pointers) { Metrics::HandlerCrashed(exception_pointers->ExceptionRecord->ExceptionCode); return EXCEPTION_CONTINUE_SEARCH; } #endif // OS_WIN } // namespace int HandlerMain(int argc, char* argv[]) { #if defined(OS_WIN) SetUnhandledExceptionFilter(&UnhandledExceptionHandler); #endif const base::FilePath argv0( ToolSupport::CommandLineArgumentToFilePathStringType(argv[0])); const base::FilePath me(argv0.BaseName()); enum OptionFlags { // Long options without short equivalents. kOptionLastChar = 255, kOptionAnnotation, kOptionDatabase, #if defined(OS_MACOSX) kOptionHandshakeFD, #endif // OS_MACOSX #if defined(OS_WIN) kOptionInitialClientData, #endif // OS_WIN #if defined(OS_MACOSX) kOptionMachService, #endif // OS_MACOSX kOptionMetrics, kOptionNoRateLimit, #if defined(OS_MACOSX) kOptionResetOwnCrashExceptionPortToSystemDefault, #elif defined(OS_WIN) kOptionPipeName, #endif // OS_MACOSX kOptionURL, // Standard options. kOptionHelp = -2, kOptionVersion = -3, }; struct { std::map<std::string, std::string> annotations; std::string url; const char* database; const char* metrics; #if defined(OS_MACOSX) int handshake_fd; std::string mach_service; bool reset_own_crash_exception_port_to_system_default; #elif defined(OS_WIN) std::string pipe_name; InitialClientData initial_client_data; #endif // OS_MACOSX bool rate_limit; } options = {}; #if defined(OS_MACOSX) options.handshake_fd = -1; #endif options.rate_limit = true; const option long_options[] = { {"annotation", required_argument, nullptr, kOptionAnnotation}, {"database", required_argument, nullptr, kOptionDatabase}, #if defined(OS_MACOSX) {"handshake-fd", required_argument, nullptr, kOptionHandshakeFD}, #endif // OS_MACOSX #if defined(OS_WIN) {"initial-client-data", required_argument, nullptr, kOptionInitialClientData}, #endif // OS_MACOSX #if defined(OS_MACOSX) {"mach-service", required_argument, nullptr, kOptionMachService}, #endif // OS_MACOSX {"metrics-dir", required_argument, nullptr, kOptionMetrics}, {"no-rate-limit", no_argument, nullptr, kOptionNoRateLimit}, #if defined(OS_MACOSX) {"reset-own-crash-exception-port-to-system-default", no_argument, nullptr, kOptionResetOwnCrashExceptionPortToSystemDefault}, #elif defined(OS_WIN) {"pipe-name", required_argument, nullptr, kOptionPipeName}, #endif // OS_MACOSX {"url", required_argument, nullptr, kOptionURL}, {"help", no_argument, nullptr, kOptionHelp}, {"version", no_argument, nullptr, kOptionVersion}, {nullptr, 0, nullptr, 0}, }; int opt; while ((opt = getopt_long(argc, argv, "", long_options, nullptr)) != -1) { switch (opt) { case kOptionAnnotation: { std::string key; std::string value; if (!SplitStringFirst(optarg, '=', &key, &value)) { ToolSupport::UsageHint(me, "--annotation requires KEY=VALUE"); return EXIT_FAILURE; } std::string old_value; if (!MapInsertOrReplace(&options.annotations, key, value, &old_value)) { LOG(WARNING) << "duplicate key " << key << ", discarding value " << old_value; } break; } case kOptionDatabase: { options.database = optarg; break; } #if defined(OS_MACOSX) case kOptionHandshakeFD: { if (!StringToNumber(optarg, &options.handshake_fd) || options.handshake_fd < 0) { ToolSupport::UsageHint(me, "--handshake-fd requires a file descriptor"); return EXIT_FAILURE; } break; } case kOptionMachService: { options.mach_service = optarg; break; } #elif defined(OS_WIN) case kOptionInitialClientData: { if (!options.initial_client_data.InitializeFromString(optarg)) { ToolSupport::UsageHint( me, "failed to parse --initial-client-data"); return EXIT_FAILURE; } break; } #endif // OS_MACOSX case kOptionMetrics: { options.metrics = optarg; break; } case kOptionNoRateLimit: { options.rate_limit = false; break; } #if defined(OS_MACOSX) case kOptionResetOwnCrashExceptionPortToSystemDefault: { options.reset_own_crash_exception_port_to_system_default = true; break; } #elif defined(OS_WIN) case kOptionPipeName: { options.pipe_name = optarg; break; } #endif // OS_MACOSX case kOptionURL: { options.url = optarg; break; } case kOptionHelp: { Usage(me); return EXIT_SUCCESS; } case kOptionVersion: { ToolSupport::Version(me); return EXIT_SUCCESS; } default: { ToolSupport::UsageHint(me, nullptr); return EXIT_FAILURE; } } } argc -= optind; argv += optind; #if defined(OS_MACOSX) if (options.handshake_fd < 0 && options.mach_service.empty()) { ToolSupport::UsageHint(me, "--handshake-fd or --mach-service is required"); return EXIT_FAILURE; } if (options.handshake_fd >= 0 && !options.mach_service.empty()) { ToolSupport::UsageHint( me, "--handshake-fd and --mach-service are incompatible"); return EXIT_FAILURE; } #elif defined(OS_WIN) if (!options.initial_client_data.IsValid() && options.pipe_name.empty()) { ToolSupport::UsageHint(me, "--initial-client-data or --pipe-name is required"); return EXIT_FAILURE; } if (options.initial_client_data.IsValid() && !options.pipe_name.empty()) { ToolSupport::UsageHint( me, "--initial-client-data and --pipe-name are incompatible"); return EXIT_FAILURE; } #endif // OS_MACOSX if (!options.database) { ToolSupport::UsageHint(me, "--database is required"); return EXIT_FAILURE; } if (argc) { ToolSupport::UsageHint(me, nullptr); return EXIT_FAILURE; } #if defined(OS_MACOSX) if (options.mach_service.empty()) { // Don’t do this when being run by launchd. See launchd.plist(5). CloseStdinAndStdout(); } if (options.reset_own_crash_exception_port_to_system_default) { CrashpadClient::UseSystemDefaultHandler(); } base::mac::ScopedMachReceiveRight receive_right; if (options.handshake_fd >= 0) { receive_right.reset( ChildPortHandshake::RunServerForFD( base::ScopedFD(options.handshake_fd), ChildPortHandshake::PortRightType::kReceiveRight)); } else if (!options.mach_service.empty()) { receive_right = BootstrapCheckIn(options.mach_service); } if (!receive_right.is_valid()) { return EXIT_FAILURE; } ExceptionHandlerServer exception_handler_server( std::move(receive_right), !options.mach_service.empty()); base::AutoReset<ExceptionHandlerServer*> reset_g_exception_handler_server( &g_exception_handler_server, &exception_handler_server); struct sigaction old_sa; ScopedResetSIGTERM reset_sigterm; if (!options.mach_service.empty()) { // When running from launchd, no no-senders notification could ever be // triggered, because launchd maintains a send right to the service. When // launchd wants the job to exit, it will send a SIGTERM. See // launchd.plist(5). // // Set up a SIGTERM handler that will call exception_handler_server.Stop(). struct sigaction sa = {}; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_SIGINFO; sa.sa_sigaction = HandleSIGTERM; int rv = sigaction(SIGTERM, &sa, &old_sa); PCHECK(rv == 0) << "sigaction"; reset_sigterm.reset(&old_sa); } #elif defined(OS_WIN) // Shut down as late as possible relative to programs we're watching. if (!SetProcessShutdownParameters(0x100, SHUTDOWN_NORETRY)) PLOG(ERROR) << "SetProcessShutdownParameters"; ExceptionHandlerServer exception_handler_server(!options.pipe_name.empty()); if (!options.pipe_name.empty()) { exception_handler_server.SetPipeName(base::UTF8ToUTF16(options.pipe_name)); } #endif // OS_MACOSX base::GlobalHistogramAllocator* histogram_allocator = nullptr; if (options.metrics) { const base::FilePath metrics_dir( ToolSupport::CommandLineArgumentToFilePathStringType(options.metrics)); static const char kMetricsName[] = "CrashpadMetrics"; const size_t kMetricsFileSize = 1 << 20; if (base::GlobalHistogramAllocator::CreateWithActiveFileInDir( metrics_dir, kMetricsFileSize, 0, kMetricsName)) { histogram_allocator = base::GlobalHistogramAllocator::Get(); histogram_allocator->CreateTrackingHistograms(kMetricsName); } } std::unique_ptr<CrashReportDatabase> database(CrashReportDatabase::Initialize( base::FilePath(ToolSupport::CommandLineArgumentToFilePathStringType( options.database)))); if (!database) { return EXIT_FAILURE; } // TODO(scottmg): options.rate_limit should be removed when we have a // configurable database setting to control upload limiting. // See https://crashpad.chromium.org/bug/23. CrashReportUploadThread upload_thread( database.get(), options.url, options.rate_limit); upload_thread.Start(); PruneCrashReportThread prune_thread(database.get(), PruneCondition::GetDefault()); prune_thread.Start(); CrashReportExceptionHandler exception_handler( database.get(), &upload_thread, &options.annotations); #if defined(OS_WIN) if (options.initial_client_data.IsValid()) { exception_handler_server.InitializeWithInheritedDataForInitialClient( options.initial_client_data, &exception_handler); } #endif // OS_WIN exception_handler_server.Run(&exception_handler); upload_thread.Stop(); prune_thread.Stop(); if (histogram_allocator) histogram_allocator->DeletePersistentLocation(); return EXIT_SUCCESS; } } // namespace crashpad
20d5a340658ba35235e21f05c67e22bd44faabd5
08d4e9313f915e848332e63375ae5b605dadf7eb
/player/src/main/cpp/Shader.cpp
0f65ccbc0b62557515cbbb1f25dd279251dbffa3
[]
no_license
playwind/LoserPlayer
a04a6638659175a8060fc8aff9c8619d1e957e00
66fcc2f4f75f29c1dee6bb35fe6a2d2dce626e8b
refs/heads/master
2023-05-21T02:30:15.489300
2021-06-10T01:51:02
2021-06-10T01:51:02
371,313,653
1
1
null
null
null
null
UTF-8
C++
false
false
8,049
cpp
#include "Shader.h" #include <AndroidLogger.h> #include <GLES2/gl2.h> #define GET_STR(x) #x // 顶点着色器 static const char *vertexShaderSource = GET_STR( attribute vec4 aPosition; // 顶点坐标 attribute vec2 aTexCoord; //材质顶点坐标 varying vec2 vTexCoord; // 输出的材质坐标 void main() { vTexCoord = vec2(aTexCoord.x, 1.0 - aTexCoord.y); gl_Position = aPosition; } ); static const char *fragmentYUV420P = GET_STR( precision mediump float; // 精度 varying vec2 vTexCoord; // 顶点着色器传递的坐标 uniform sampler2D yTexture; uniform sampler2D uTexture; uniform sampler2D vTexture; void main() { vec3 yuv; vec3 rgb; yuv.r = texture2D(yTexture, vTexCoord).r; yuv.g = texture2D(uTexture, vTexCoord).r - 0.5; yuv.b = texture2D(vTexture, vTexCoord).r - 0.5; rgb = mat3(1.0, 1.0, 1.0, 0.0, -0.39465, 2.03211, 1.13983, -0.58060, 0.0) * yuv; //输出像素颜色 gl_FragColor = vec4(rgb, 1.0); } ); //片元着色器,软解码和部分x86硬解码 static const char *fragNV12 = GET_STR( precision mediump float; //精度 varying vec2 vTexCoord; //顶点着色器传递的坐标 uniform sampler2D yTexture; //输入的材质(不透明灰度,单像素) uniform sampler2D uvTexture; void main() { vec3 yuv; vec3 rgb; yuv.r = texture2D(yTexture, vTexCoord).r; yuv.g = texture2D(uvTexture, vTexCoord).r - 0.5; yuv.b = texture2D(uvTexture, vTexCoord).a - 0.5; rgb = mat3(1.0, 1.0, 1.0, 0.0, -0.39465, 2.03211, 1.13983, -0.58060, 0.0) * yuv; //输出像素颜色 gl_FragColor = vec4(rgb, 1.0); } ); //片元着色器,软解码和部分x86硬解码 static const char *fragNV21 = GET_STR( precision mediump float; //精度 varying vec2 vTexCoord; //顶点着色器传递的坐标 uniform sampler2D yTexture; //输入的材质(不透明灰度,单像素) uniform sampler2D uvTexture; void main() { vec3 yuv; vec3 rgb; yuv.r = texture2D(yTexture, vTexCoord).r; yuv.g = texture2D(uvTexture, vTexCoord).a - 0.5; yuv.b = texture2D(uvTexture, vTexCoord).r - 0.5; rgb = mat3(1.0, 1.0, 1.0, 0.0, -0.39465, 2.03211, 1.13983, -0.58060, 0.0) * yuv; //输出像素颜色 gl_FragColor = vec4(rgb, 1.0); } ); static GLuint InitShader(const char *code, GLint type) { // 创建shader GLuint shader = glCreateShader(type); if (shader == 0) { LOGE("glCreateShader %d failed!!!", type); return 0; } // 加载shader glShaderSource(shader, 1, &code, nullptr); // 编译shader glCompileShader(shader); // 检查编译结果 GLint status; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if (status == 0) { LOGE("glCompileShader %d failed!!!", shader); return 0; } LOGI("glCompileShader %d success.", shader); return shader; } bool Shader::Init(ShaderType type) { Close(); mutex.lock(); // 顶点shader初始化 vertexShader = InitShader(vertexShaderSource, GL_VERTEX_SHADER); if (vertexShader == 0) { mutex.unlock(); LOGE("Init Vertex Shader failed!!!"); return false; } switch (type) { case SHADER_NV12: fragmentShader = InitShader(fragNV12, GL_FRAGMENT_SHADER); break; case SHADER_NV21: fragmentShader = InitShader(fragNV21, GL_FRAGMENT_SHADER); break; case SHADER_YUV420P: default: fragmentShader = InitShader(fragmentYUV420P, GL_FRAGMENT_SHADER); break; } if (fragmentShader == 0) { mutex.unlock(); LOGE("Init Fragment Shader failed!!!"); return false; } // 创建渲染程序 program = glCreateProgram(); if (program == 0) { mutex.unlock(); LOGE("glCreateProgram failed!!!"); return false; } // 加入着色器到程序 glAttachShader(program, vertexShader); glAttachShader(program, fragmentShader); // 链接程序 glLinkProgram(program); // 检查链接状态 GLint status; glGetProgramiv(program, GL_LINK_STATUS, &status); if (status != GL_TRUE) { mutex.unlock(); LOGE("glLinkProgram failed!!!"); return false; } glUseProgram(program); // 顶点坐标 static float vertexs[] = { 1.0f, -1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0, -1.0f, 1.0f, 0.0f }; // 启用顶点 GLuint aPosition = (GLuint) glGetAttribLocation(program, "aPosition"); glEnableVertexAttribArray(aPosition); // 传递顶点 glVertexAttribPointer(aPosition, 3, GL_FLOAT, GL_FALSE, 12, vertexs); // 材质坐标 static float txts[] = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f }; GLuint aTexCoord = glGetAttribLocation(program, "aTexCoord"); glEnableVertexAttribArray(aTexCoord); glVertexAttribPointer(aTexCoord, 2, GL_FLOAT, GL_FALSE, 8, txts); glUniform1i(glGetUniformLocation(program, "yTexture"), 0); switch (type) { case SHADER_NV21: case SHADER_NV12: glUniform1i(glGetUniformLocation(program, "uvTexture"), 1); break; case SHADER_YUV420P: default: glUniform1i(glGetUniformLocation(program, "uTexture"), 1); glUniform1i(glGetUniformLocation(program, "vTexture"), 2); break; } mutex.unlock(); return true; } void Shader::Close() { mutex.lock(); if (program) { glDeleteProgram(program); } if (fragmentShader) { glDeleteShader(fragmentShader); } if (vertexShader) { glDeleteShader(vertexShader); } // 释放材质 for (unsigned int texture : textures) { if (texture) { glDeleteTextures(1, &texture); } texture = 0; } mutex.unlock(); } void Shader::GetTexture(unsigned int index, int width, int height, unsigned char *buf, bool isa) { unsigned int format = GL_LUMINANCE; if (isa) format = GL_LUMINANCE_ALPHA; mutex.lock(); if (textures[index] == 0) { // 材质初始化 glGenTextures(1, &textures[index]); glBindTexture(GL_TEXTURE_2D, textures[index]); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // 设置纹理格式和大小 glTexImage2D(GL_TEXTURE_2D, 0, //指定详细程度编号。级别0是基本图像级别。级别n是第n个缩略图缩小图像。 format, //指定纹理的内部格式。必须是下列符号常量之一:GL_ALPHA,GL_LUMINANCE,GL_LUMINANCE_ALPHA,GL_RGB, width, //指定纹理图像的宽度。 height, //指定纹理图像的高度 0, //指定边框的宽度。必须为0。 format, GL_UNSIGNED_BYTE, // 指定纹理数据的数据类型。 NULL); } glActiveTexture(GL_TEXTURE0 + index); glBindTexture(GL_TEXTURE_2D, textures[index]); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, format, GL_UNSIGNED_BYTE, buf); mutex.unlock(); } void Shader::Draw() { mutex.lock(); if (!program) { mutex.unlock(); return; } glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); mutex.unlock(); }
e34e611a9ed792547f92a7ce5108bf3bb5c9999d
2c35da61dc41f8ff2c1588a2e66b61ca90cd1f3a
/src/lib/utils/noise/module/spheres.h
049d12ba37644a6b82dbd807f535582883746455
[]
no_license
vkaytsanov/AngryBirds
5858b3dad02940f21dfa849153a134645ecc2191
2cc1a7494f1c2c337461df73c4f43c57bfa57770
refs/heads/master
2023-06-17T10:27:37.254180
2021-07-08T11:37:00
2021-07-08T11:37:00
364,853,524
0
0
null
null
null
null
UTF-8
C++
false
false
3,518
h
// spheres.h // // Copyright (C) 2003, 2004 Jason Bevins // // 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 (COPYING.txt) 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 // // The developer's email is [email protected] (for great email, take // off every 'zig'.) // #ifndef NOISE_MODULE_SPHERES_H #define NOISE_MODULE_SPHERES_H #include "modulebase.h" namespace noise { namespace module { /// @addtogroup libnoise /// @{ /// @addtogroup m_modules /// @{ /// @addtogroup generatormodules /// @{ /// Default frequency value for the noise::module::Spheres noise module. const double DEFAULT_SPHERES_FREQUENCY = 1.0; /// Noise module that outputs concentric spheres. /// /// @image html modulespheres.png /// /// This noise module outputs concentric spheres centered on the origin /// like the concentric rings of an onion. /// /// The first sphere has a radius of 1.0. Each subsequent sphere has a /// radius that is 1.0 unit larger than the previous sphere. /// /// The output value from this noise module is determined by the distance /// between the input value and the the nearest spherical surface. The /// input values that are located on a spherical surface are given the /// output value 1.0 and the input values that are equidistant from two /// spherical surfaces are given the output value -1.0. /// /// An application can change the frequency of the concentric spheres. /// Increasing the frequency reduces the distances between spheres. To /// specify the frequency, call the SetFrequency() method. /// /// This noise module, modified with some low-frequency, low-power /// turbulence, is useful for generating agate-like textures. /// /// This noise module does not require any source m_modules. class Spheres : public Module { public: /// Constructor. /// /// The default frequency is set to /// noise::module::DEFAULT_SPHERES_FREQUENCY. Spheres(); /// Returns the frequency of the concentric spheres. /// /// @returns The frequency of the concentric spheres. /// /// Increasing the frequency increases the density of the concentric /// spheres, reducing the distances between them. double GetFrequency() const { return m_frequency; } virtual int GetSourceModuleCount() const { return 0; } virtual double GetValue(double x, double y, double z) const; /// Sets the frequenct of the concentric spheres. /// /// @param frequency The frequency of the concentric spheres. /// /// Increasing the frequency increases the density of the concentric /// spheres, reducing the distances between them. void SetFrequency(double frequency) { m_frequency = frequency; } protected: /// Frequency of the concentric spheres. double m_frequency; }; /// @} /// @} /// @} } } #endif
33b4f850c089d543f167ee5af51c48d38dfe321e
ee4646a74ac1bffc0d0d4f0dc33fef84ccd1959b
/TwoDiskinaRectangle/code/RandomConditions01.hpp
c7d90340aa8ec4bb2cc9da433abd0e5c679a01a9
[]
no_license
kzapfe/ProblemasSanders
b93900ec296553fb0ff9c82389ce03451761760f
d59fbf28124dcbc41ccce378b96d77f5df944123
refs/heads/master
2021-06-23T16:43:58.766280
2021-01-25T21:14:35
2021-01-25T21:14:35
19,159,390
0
0
null
2019-02-25T16:38:48
2014-04-25T20:17:52
Jupyter Notebook
UTF-8
C++
false
false
6,785
hpp
void RandomizaDiscos(Disco &Uno, Disco &Dos, double Energia, gsl_rng *r){ //Rutina que les da condiciones iniciales a los Discos // a partir de la energia y el espacio Disponible //Think about this...: No es posible poner Ni siquiera el primero donde sea. //especialmente si son gordos. El centro, por ejemplo, queda excluido. //Por lo tanto, escoge condiciones de Birkhoff. // For first try, very simple... una en cada lado del puto cuadrado. //They cannot overlap that way. //UUUUUPSSSSS: // eso solo es cierto si miden menos que la distancia que todavia les //permite hoppear... si no, es falso double a, b; a=0.00; b=widthmedia-Uno.radio; Uno.qx=gsl_ran_flat(r, a, b); a=-heightmedia+Uno.radio; b=-a; Uno.qy=gsl_ran_flat(r, a, b); a=-widthmedia+Uno.radio; b=0.00; Dos.qx=gsl_ran_flat(r, a, b); a=-heightmedia+Uno.radio; b=-a; Dos.qy=gsl_ran_flat(r, a, b); double EnergiaUno; double EnergiaDos; double RadioVirtualMomento; double ThetaMomento; //Distribuimos la energia entre dos. EnergiaUno=gsl_ran_flat(r, 0, Energia); EnergiaDos=Energia-EnergiaUno; //acuerdate que definiste los pinches Discos a la Hamilton, NO lagrange. //Disco Uno RadioVirtualMomento=sqrt(EnergiaUno*2.0*Uno.masa); ThetaMomento=gsl_ran_flat(r, 0, 6.28318530718); Uno.px=cos(ThetaMomento)*RadioVirtualMomento; Uno.py=sin(ThetaMomento)*RadioVirtualMomento; //Disco Dos RadioVirtualMomento=sqrt(EnergiaDos*2.0*Uno.masa); ThetaMomento=gsl_ran_flat(r, 0, 6.28318530718); Dos.px=cos(ThetaMomento)*RadioVirtualMomento; Dos.py=sin(ThetaMomento)*RadioVirtualMomento; return; } void AbsolutRandomDiscos(Disco &Uno, Disco &Dos, double Energia, gsl_rng *r){ /*Rutina que les da condiciones iniciales a los Discos a partir de la energia y el espacio Disponible Think about this...: No es posible poner Ni siquiera el primero donde sea. especialmente si son gordos. El centro, por ejemplo, queda excluido. Vas a tener que hacer un trial and error. Recuerda que mientras mas Gordos sean, mas dificil sera */ double distmincuad, distcuad; double auxx1,auxx2,auxy1,auxy2; double medioanchoefe1, medialturaefe1; double medioanchoefe2, medialturaefe2; distcuad=0.00; distmincuad=(Uno.radio+Dos.radio)*(Uno.radio+Dos.radio); //cout<<" Tienen que estar aleatoreamente a esta distancia cuadrada minima: "<< // distmincuad<<endl; int intentos=0; medioanchoefe1=widthmedia-Uno.radio; medioanchoefe2=widthmedia-Dos.radio; medialturaefe1=heightmedia-Uno.radio; medialturaefe2=heightmedia-Dos.radio; while(distcuad<distmincuad){ //repeat until it comes right... intentos++; auxx1=gsl_ran_flat(r, -medioanchoefe1,medioanchoefe1); auxx2=gsl_ran_flat(r, -medioanchoefe2,medioanchoefe2); auxy1=gsl_ran_flat(r, -medialturaefe1,medialturaefe1); auxy2=gsl_ran_flat(r, -medialturaefe2,medialturaefe2); //Norma euclidiana al cuadrado distcuad=(auxx1-auxx2)*(auxx1-auxx2)+(auxy1-auxy2)*(auxy1-auxy2); //cout<<" En el intento "<<intentos<<" me salio una distcuad de "<<distcuad<<endl; } //cout<<" Me tomo encontrar uno viable asi de veces "<< intentos<<endl; //cout<<" y se encuentran a una distancia de " <<sqrt(distcuad)<<endl; Uno.qx=auxx1; Uno.qy=auxy1; Dos.qx=auxx2; Dos.qy=auxy2; double EnergiaUno; double EnergiaDos; double RadioVirtualMomento; double ThetaMomento; //Distribuimos la energia entre dos. EnergiaUno=gsl_ran_flat(r, 0, Energia); EnergiaDos=Energia-EnergiaUno; //acuerdate que definiste los pinches Discos a la Hamilton, NO lagrange. //Disco Uno RadioVirtualMomento=sqrt(EnergiaUno*2.0*Uno.masa); ThetaMomento=gsl_ran_flat(r, 0, 6.28318530718); Uno.px=cos(ThetaMomento)*RadioVirtualMomento; Uno.py=sin(ThetaMomento)*RadioVirtualMomento; //Disco Dos RadioVirtualMomento=sqrt(EnergiaDos*2.0*Uno.masa); ThetaMomento=gsl_ran_flat(r, 0, 6.28318530718); Dos.px=cos(ThetaMomento)*RadioVirtualMomento; Dos.py=sin(ThetaMomento)*RadioVirtualMomento; // cout<< "ya voy a regresar los valores para los discos "<<endl; return; } void RandomAtEntrance(Disco &Uno, Disco &Dos, double Energia, double epsilon, gsl_rng *r){ /*Rutina que les da condiciones iniciales a los Discos a partir de la energia y epsilon. El disco uno estará en la puerta, y el segundo en algun lugar dentro. La puerta estara en la extrema derecha, a la mitad. Las velocidades de Uno seran hacia adentro forzosamente. No funciona bien para valores grandes de r o de epsilon. Gordos sean, mas dificil sera */ double distmincuad, distcuad; double auxx1,auxx2,auxy1,auxy2; double medioanchoefe1, medialturaefe1; double medioanchoefe2, medialturaefe2; distcuad=0.00; distmincuad=(Uno.radio+Dos.radio)*(Uno.radio+Dos.radio); //cout<<" Tienen que estar aleatoreamente a esta distancia cuadrada minima: "<< // distmincuad<<endl; int intentos=0; medioanchoefe1=widthmedia-Uno.radio; medioanchoefe2=widthmedia-Dos.radio; medialturaefe1=heightmedia-Uno.radio; medialturaefe2=heightmedia-Dos.radio; Uno.qx=medioanchoefe1; Uno.qy=gsl_ran_flat(r, -epsilon/2., epsilon/2.); auxx1=Uno.qx; auxx2=Uno.qy; //el primero va while(distcuad<distmincuad){ //repeat until it comes right... intentos++; auxy1=gsl_ran_flat(r, -medialturaefe1,medialturaefe1); auxy2=gsl_ran_flat(r, -medialturaefe2,medialturaefe2); //Norma euclidiana al cuadrado distcuad=(auxx1-auxx2)*(auxx1-auxx2)+(auxy1-auxy2)*(auxy1-auxy2); //cout<<" En el intento "<<intentos<<" me salio una distcuad de "<<distcuad<<endl; } //cout<<" Me tomo encontrar uno viable asi de veces "<< intentos<<endl; //cout<<" y se encuentran a una distancia de " <<sqrt(distcuad)<<endl; Dos.qx=auxx2; Dos.qy=auxy2; double EnergiaUno; double EnergiaDos; double RadioVirtualMomento; double ThetaMomento; //Distribuimos la energia entre dos. EnergiaUno=gsl_ran_flat(r, 0, Energia); EnergiaDos=Energia-EnergiaUno; //acuerdate que definiste los pinches Discos a la Hamilton, NO lagrange. //Disco Uno RadioVirtualMomento=sqrt(EnergiaUno*2.0*Uno.masa); //Las velocidades de Uno apuntan hacia la izquierda. ThetaMomento=gsl_ran_flat(r, 1.57079632679, 4.71238898); Uno.px=cos(ThetaMomento)*RadioVirtualMomento; Uno.py=sin(ThetaMomento)*RadioVirtualMomento; //Disco Dos RadioVirtualMomento=sqrt(EnergiaDos*2.0*Uno.masa); ThetaMomento=gsl_ran_flat(r, 0, 6.28318530718); Dos.px=cos(ThetaMomento)*RadioVirtualMomento; Dos.py=sin(ThetaMomento)*RadioVirtualMomento; // cout<< "ya voy a regresar los valores para los discos "<<endl; return; }
3e787f4580cde5333ead60855a43bf6969214f8b
dd80a584130ef1a0333429ba76c1cee0eb40df73
/bionic/libc/bionic/sbrk.cpp
6c9b534c322bce2462e19b2a501f276a2111987f
[ "MIT", "BSD-4-Clause-UC", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "Martin-Birgmeier", "dtoa", "HPND", "SunPro", "CMU-Mach", "ISC", "Apache-2.0", "BSD-2-Clause", "BSD-4-Clause", "BSD-4.3TAHOE", "LicenseRef-scancode-ibm-dhcp" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
2,009
cpp
/* * Copyright (C) 2008 The Android Open Source Project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <unistd.h> #include <errno.h> /* Shared with brk.c. */ extern "C" { void* __bionic_brk; // TODO: should be __LIBC_HIDDEN__ but accidentally exported by NDK :-( } void* sbrk(ptrdiff_t increment) { if (__bionic_brk == NULL) { __bionic_brk = __brk(NULL); } void* original_brk = __bionic_brk; void* desired_brk = (void*) ((uintptr_t) original_brk + increment); void* new_brk = __brk(desired_brk); if (new_brk == (void*) -1) { return new_brk; } else if (new_brk < desired_brk) { errno = ENOMEM; return (void*) -1; } __bionic_brk = new_brk; return original_brk; }
2bd178dfa92e6b565574467d733669ca73d3af47
cf26a6c225fe2aed5b0a97ea0d2ecc108bf68e61
/src/dict/dictMath.cpp
1660ea4910680a585d96ef2419cc861733bb6e65
[ "MIT" ]
permissive
0918nobita/Paraphrase
886f5c70fdebeb5cd15997a2b469ce02ba2e6b96
1c2a74d664ebd6f6ab663bbc41c4e72bed288c1a
refs/heads/master
2023-03-05T14:59:31.443171
2021-02-22T15:25:34
2021-02-22T15:25:34
340,126,593
0
0
MIT
2021-02-18T17:31:17
2021-02-18T17:31:16
null
UTF-8
C++
false
false
32,708
cpp
#define _USE_MATH_DEFINES #include <stdlib.h> #include <time.h> #include <math.h> #include <climits> #include <cfloat> #include <cmath> #include <boost/multiprecision/cpp_int.hpp> #include "externals.h" #include "typedValue.h" #include "stack.h" #include "word.h" #include "context.h" #include "mathMacro.h" const BigInt kBigInt_FLT_MAX(FLT_MAX); const BigInt kBigInt_Minus_FLT_MAX(-FLT_MAX); const BigInt kBigInt_DBL_MAX(DBL_MAX); const BigInt kBigInt_Minus_DBL_MAX(-DBL_MAX); static double deg2rad(double inTheta) { return inTheta/180.0*M_PI; } static BigFloat deg2rad(BigFloat inTheta) { return inTheta/180.0*M_PI; } static double rad2deg(double inTheta) { return inTheta/M_PI*180.0; } static BigFloat rad2deg(BigFloat inTheta) { return inTheta/M_PI*180.0; } static int maxOp(int inA,int inB) { return std::max(inA,inB); } static long maxOp(long inA,long inB) { return std::max(inA,inB); } static float maxOp(float inA,float inB) { return std::max(inA,inB); } static double maxOp(double inA,double inB) { return std::max(inA,inB); } static BigInt maxOp(BigInt inA,BigInt inB) { return inA>inB ? inA : inB; } static BigFloat maxOp(BigFloat inA,BigFloat inB) { return inA>inB ? inA : inB; } static int minOp(int inA,int inB) { return std::min(inA,inB); } static long minOp(long inA,long inB) { return std::min(inA,inB); } static float minOp(float inA,float inB) { return std::min(inA,inB); } static double minOp(double inA,double inB) { return std::min(inA,inB); } static BigInt minOp(BigInt inA,BigInt inB) { return inA<inB ? inA : inB; } static BigFloat minOp(BigFloat inA,BigFloat inB) { return inA<inB ? inA : inB; } void InitDict_Math() { Install(new Word("true",WORD_FUNC { inContext.DS.emplace_back(true); NEXT; })); Install(new Word("false",WORD_FUNC { inContext.DS.emplace_back(false); NEXT; })); Install(new Word("+",WORD_FUNC { TwoOp(+); },LVOP::LVOpSupported2args| LVOP::ADD)); Install(new Word("-",WORD_FUNC { TwoOp(-); },LVOP::LVOpSupported2args| LVOP::SUB)); Install(new Word("*",WORD_FUNC { TwoOp(*); },LVOP::LVOpSupported2args| LVOP::MUL)); Install(new Word("/",WORD_FUNC { TwoOp(/); },LVOP::LVOpSupported2args| LVOP::DIV)); Install(new Word("%",WORD_FUNC { if(inContext.DS.size()<2) { return inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2); } TypedValue tos=Pop(inContext.DS); CheckIntegerAndNonZero(tos); TypedValue& second=ReadTOS(inContext.DS); ModAssign(second,tos); // second %= tos; NEXT; })); Install(new Word("2*",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2); } TypedValue& tos=ReadTOS(inContext.DS); switch(tos.dataType) { case DataType::kTypeInt: tos.intValue *= 2; break; case DataType::kTypeLong: tos.longValue *= 2L; break; case DataType::kTypeBigInt: *(tos.bigIntPtr) *= 2; break; case DataType::kTypeFloat: tos.floatValue *= 2.0f; break; case DataType::kTypeDouble: tos.doubleValue *= 2.0; break; case DataType::kTypeBigFloat: *(tos.bigFloatPtr) *= 2; break; default: return inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos); } NEXT; },LVOP::LVOpSupported1args | LVOP::TWC)); Install(new Word("@+",WORD_FUNC { RefTwoOp(inContext.DS,+); })); Install(new Word("@-",WORD_FUNC { RefTwoOp(inContext.DS,-); })); Install(new Word("@*",WORD_FUNC { RefTwoOp(inContext.DS,*); })); Install(new Word("@/",WORD_FUNC { RefTwoOp(inContext.DS,/); })); Install(new Word("@%",WORD_FUNC { if(inContext.DS.size()<2) { return inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2); } TypedValue& tos=ReadTOS(inContext.DS); TypedValue& second=ReadSecond(inContext.DS); CheckIntegerAndNonZero(tos); RefMod(inContext.DS,second,tos); NEXT; })); Install(new Word("+@",WORD_FUNC { TwoOpAssignTOS(+); })); Install(new Word("-@",WORD_FUNC { TwoOpAssignTOS(-); })); Install(new Word("*@",WORD_FUNC { TwoOpAssignTOS(*); })); Install(new Word("/@",WORD_FUNC { TwoOpAssignTOS(/); })); Install(new Word("%@",WORD_FUNC { if(inContext.DS.size()<2) { return inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2); } TypedValue& tos=ReadTOS(inContext.DS); TypedValue& second=ReadSecond(inContext.DS); CheckIntegerAndNonZero(tos); ModAssignTOS(inContext,second,tos); NEXT; })); Install(new Word("&",WORD_FUNC { BitOp(&); })); Install(new Word("|",WORD_FUNC { BitOp(|); })); Install(new Word("^",WORD_FUNC { BitOp(^); })); Install(new Word(">>",WORD_FUNC { BitShiftOp(>>); })); Install(new Word("<<",WORD_FUNC { BitShiftOp(<<); })); Install(new Word("@&",WORD_FUNC { RefBitOp(&); })); Install(new Word("@|",WORD_FUNC { RefBitOp(|); })); Install(new Word("@^",WORD_FUNC { RefBitOp(^); })); Install(new Word("@>>",WORD_FUNC { RefBitShiftOp(>>); })); Install(new Word("@<<",WORD_FUNC { RefBitShiftOp(<<); })); // bitwise NOT. Install(new Word("~",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2); } TypedValue& tos=ReadTOS(inContext.DS); switch(tos.dataType) { case DataType::kTypeInt: tos.intValue=~tos.intValue; break; case DataType::kTypeLong: tos.longValue=~tos.longValue; break; case DataType::kTypeBigInt: *tos.bigIntPtr=~*tos.bigIntPtr; break; default: return inContext.Error(InvalidTypeErrorID::E_TOS_INT_OR_LONG_OR_BIGINT,tos); } NEXT; })); Install(new Word("@~",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2); } TypedValue& tos=ReadTOS(inContext.DS); switch(tos.dataType) { case DataType::kTypeInt: inContext.DS.emplace_back(~tos.intValue); break; case DataType::kTypeLong: inContext.DS.emplace_back(~tos.longValue); break; case DataType::kTypeBigInt: inContext.DS.emplace_back(~*tos.bigIntPtr); break; default: return inContext.Error(InvalidTypeErrorID::E_TOS_INT_OR_LONG_OR_BIGINT,tos); } NEXT; })); Install(new Word(">",WORD_FUNC { CmpOp(>); })); Install(new Word("<",WORD_FUNC { CmpOp(<); })); Install(new Word(">=",WORD_FUNC { CmpOp(>=); })); Install(new Word("<=",WORD_FUNC { CmpOp(<=); })); Install(new Word("==",WORD_FUNC { CmpOp(==); })); Install(new Word("!=",WORD_FUNC { CmpOp(!=); })); Install(new Word("@>",WORD_FUNC { RefCmpOp(>); })); Install(new Word("@<",WORD_FUNC { RefCmpOp(<); })); Install(new Word("@>=",WORD_FUNC { RefCmpOp(>=); })); Install(new Word("@<=",WORD_FUNC { RefCmpOp(<=); })); Install(new Word("@==",WORD_FUNC { RefCmpOp(==); })); Install(new Word("@!=",WORD_FUNC { RefCmpOp(!=); })); Install(new Word("&&",WORD_FUNC { BoolOp(&&); })); Install(new Word("||",WORD_FUNC { BoolOp(||); })); Install(new Word("xor",WORD_FUNC { BoolOp(!=); })); Install(new Word("not",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue& tos=ReadTOS(inContext.DS); if(tos.dataType!=DataType::kTypeBool) { return inContext.Error(InvalidTypeErrorID::E_TOS_BOOL,tos); } tos.boolValue = tos.boolValue != true; NEXT; })); Install(new Word("not-true?",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue tos=Pop(inContext.DS); inContext.DS.emplace_back(!(tos.dataType==DataType::kTypeBool && tos.boolValue==true)); NEXT; })); Install(new Word("sqrt",WORD_FUNC { OneArgFloatingFunc(sqrt); })); Install(new Word("square",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue& tos=ReadTOS(inContext.DS); switch(tos.dataType) { case DataType::kTypeInt: tos.intValue*=tos.intValue; break; case DataType::kTypeLong: tos.longValue*=tos.longValue; break; case DataType::kTypeBigInt: *(tos.bigIntPtr) *= *(tos.bigIntPtr); break; case DataType::kTypeFloat: tos.floatValue*=tos.floatValue; break; case DataType::kTypeDouble: tos.doubleValue*=tos.doubleValue; break; case DataType::kTypeBigFloat: *(tos.bigFloatPtr) *= *(tos.bigFloatPtr); break; default: return inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos); } NEXT; })); Install(new Word("exp", WORD_FUNC { OneParamFunc(exp); })); Install(new Word("log", WORD_FUNC { OneParamFunc(log); })); Install(new Word("log10", WORD_FUNC { OneParamFunc(log10); })); Install(new Word("sin",WORD_FUNC { OneParamFunc(sin); })); Install(new Word("cos",WORD_FUNC { OneParamFunc(cos); })); Install(new Word("tan",WORD_FUNC { OneParamFunc(tan); })); Install(new Word("asin",WORD_FUNC { OneParamFunc(asin); })); Install(new Word("acos",WORD_FUNC { OneParamFunc(acos); })); Install(new Word("atan",WORD_FUNC { OneParamFunc(atan); })); Install(new Word("abs",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue tos=Pop(inContext.DS); switch(tos.dataType) { case DataType::kTypeInt: inContext.DS.emplace_back(abs(tos.intValue)); break; case DataType::kTypeLong: inContext.DS.emplace_back(abs(tos.longValue)); break; case DataType::kTypeBigInt: inContext.DS.emplace_back(abs(*(tos.bigIntPtr))); break; case DataType::kTypeFloat: inContext.DS.emplace_back(abs(tos.floatValue)); break; case DataType::kTypeDouble: inContext.DS.emplace_back(abs(tos.doubleValue)); break; case DataType::kTypeBigFloat: inContext.DS.emplace_back(abs(*(tos.bigIntPtr))); break; default: return inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos); } NEXT; })); Install(new Word("floor",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue& tos=ReadTOS(inContext.DS); FloorOrCeil(floor,tos); NEXT; })); Install(new Word("ceil",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue& tos=ReadTOS(inContext.DS); FloorOrCeil(ceil,tos); NEXT; })); Install(new Word("deg-to-rad",WORD_FUNC { OneParamFunc(deg2rad); })); Install(new Word("rad-to-deg",WORD_FUNC { OneParamFunc(rad2deg); })); Install(new Word("pow",WORD_FUNC { using namespace boost::multiprecision; if(inContext.DS.size()<2) { return inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2); } TypedValue tos=Pop(inContext.DS); TypedValue& second=ReadTOS(inContext.DS); if(second.dataType==DataType::kTypeDouble) { switch(tos.dataType) { case DataType::kTypeInt: /* double x int -> double */ second.doubleValue=pow(second.doubleValue,(double)tos.intValue); break; case DataType::kTypeLong: /* double x long -> double */ second.doubleValue=pow(second.doubleValue,(double)tos.longValue); break; case DataType::kTypeFloat: /* double x float -> double */ second.doubleValue=pow(second.doubleValue,(double)tos.floatValue); break; case DataType::kTypeDouble: /* double x double -> dobule */ second.doubleValue=pow(second.doubleValue,tos.doubleValue); break; case DataType::kTypeBigInt: { /* double x bigInt -> bigFloat */ BigFloat *bigFloat=new BigFloat(); *bigFloat=pow(BigFloat(second.doubleValue), BigFloat(*tos.bigIntPtr)); second.bigFloatPtr=bigFloat; second.dataType=DataType::kTypeBigFloat; } break; case DataType::kTypeBigFloat: { /* double x bigFloat -> bigFloat */ BigFloat *bigFloat=new BigFloat(); *bigFloat=pow(BigFloat(second.doubleValue),*tos.bigFloatPtr); second.bigFloatPtr=bigFloat; second.dataType=DataType::kTypeBigFloat; } break; default: goto onError; } } else if(second.dataType==DataType::kTypeBigInt) { switch(tos.dataType) { case DataType::kTypeInt: /* bigInt x int -> bigInt */ *second.bigIntPtr=pow(*second.bigIntPtr,tos.intValue); break; case DataType::kTypeLong: /* bigInt x long -> bigInt */ *second.bigIntPtr=pow(*second.bigIntPtr,tos.longValue); break; case DataType::kTypeFloat: { /* bigInt x float -> bigFloat */ BigFloat *bigFloat=new BigFloat(); *bigFloat=pow(BigFloat(*second.bigIntPtr), BigFloat(tos.floatValue)); delete(second.bigIntPtr); second.bigFloatPtr=bigFloat; second.dataType=DataType::kTypeBigFloat; } break; case DataType::kTypeDouble: { /* bigInt x double -> bigFloat */ BigFloat *bigFloat=new BigFloat(); *bigFloat=pow(BigFloat(*second.bigIntPtr), BigFloat(tos.doubleValue)); delete(second.bigIntPtr); second.bigFloatPtr=bigFloat; second.dataType=DataType::kTypeBigFloat; } break; case DataType::kTypeBigInt: /* bigInt x bigInt -> bigInt */ return inContext.Error(InvalidTypeTosSecondErrorID::E_OUT_OF_SUPPORT_TOS_SECOND,tos,second); case DataType::kTypeBigFloat: { /* bigInt x bigFloat -> bigFloat */ BigFloat *bigFloat=new BigFloat(); *bigFloat=pow(BigFloat(*second.bigIntPtr),*tos.bigFloatPtr); delete(second.bigIntPtr); second.bigFloatPtr=bigFloat; second.dataType=DataType::kTypeBigFloat; } break; default: goto onError; } } else if(second.dataType==DataType::kTypeBigFloat) { switch(tos.dataType) { case DataType::kTypeInt: /* bigFloat x int -> bigFloat */ *second.bigFloatPtr=pow(*second.bigFloatPtr, BigFloat(tos.intValue)); break; case DataType::kTypeLong: /* bigFloat x long -> bigFloat */ *second.bigFloatPtr=pow(*second.bigFloatPtr, BigFloat(tos.longValue)); break; case DataType::kTypeFloat: /* bigFloat x float -> bigFloat */ *second.bigFloatPtr=pow(*second.bigFloatPtr, BigFloat(tos.floatValue)); break; case DataType::kTypeDouble: /* bigFloat x double -> bigFloat */ *second.bigFloatPtr=pow(*second.bigFloatPtr, BigFloat(tos.doubleValue)); break; case DataType::kTypeBigInt: /* bigFloat x bigInt -> bigFloat */ *second.bigFloatPtr=pow(*second.bigFloatPtr, BigFloat(*tos.bigIntPtr)); break; case DataType::kTypeBigFloat: /* bigFloat x bigFloat -> bigFloat */ *second.bigFloatPtr=pow(*second.bigFloatPtr,*tos.bigFloatPtr); break; default: goto onError; } } else if(second.dataType==DataType::kTypeInt) { switch(tos.dataType) { case DataType::kTypeInt: /* int x int -> int */ second.intValue=(int)pow(second.intValue,tos.intValue); break; case DataType::kTypeLong: /* int x long -> long */ second.longValue=(long)pow((long)second.intValue,tos.longValue); second.dataType=DataType::kTypeLong; break; case DataType::kTypeFloat: /* int x float -> float */ second.floatValue=(float)pow((float)second.intValue, tos.floatValue); second.dataType=DataType::kTypeFloat; break; case DataType::kTypeDouble: /* int x double -> double */ second.doubleValue=(double)pow((double)second.intValue, tos.doubleValue); second.dataType=DataType::kTypeDouble; break; case DataType::kTypeBigInt: /* int x bigInt -> OutOfSupport */ return inContext.Error(InvalidTypeTosSecondErrorID::E_OUT_OF_SUPPORT_TOS_SECOND,tos,second); case DataType::kTypeBigFloat: { /* int x bigFloat -> bigFloat */ BigFloat *bigFloat=new BigFloat(); *bigFloat=pow(BigFloat(second.intValue),*tos.bigFloatPtr); second.bigFloatPtr=bigFloat; second.dataType=DataType::kTypeBigFloat; } break; default: goto onError; } } else if(second.dataType==DataType::kTypeLong) { switch(tos.dataType) { case DataType::kTypeInt: /* long x int -> long */ second.longValue=(long)pow(second.longValue,(long)tos.intValue); break; case DataType::kTypeLong: /* long x long -> long */ second.longValue=(long)pow(second.longValue,tos.longValue); break; case DataType::kTypeFloat: /* long x float -> float */ second.floatValue=(float)pow((float)second.longValue, tos.floatValue); second.dataType=DataType::kTypeFloat; break; case DataType::kTypeDouble: /* long x double -> double */ second.doubleValue=(double)pow((double)second.longValue, tos.doubleValue); second.dataType=DataType::kTypeDouble; break; case DataType::kTypeBigInt: /* long x bigInt -> OutOfSupport */ return inContext.Error(InvalidTypeTosSecondErrorID::E_OUT_OF_SUPPORT_TOS_SECOND,tos,second); case DataType::kTypeBigFloat: { /* long x bigFloat -> bigFloat */ BigFloat *bigFloat=new BigFloat(); *bigFloat=pow(BigFloat(second.longValue),*tos.bigFloatPtr); second.bigFloatPtr=bigFloat; second.dataType=DataType::kTypeBigFloat; } break; default: goto onError; } } else if(second.dataType==DataType::kTypeFloat) { switch(tos.dataType) { case DataType::kTypeInt: /* float x int -> float */ second.floatValue=(float)pow((double)second.floatValue, (double)tos.intValue); break; case DataType::kTypeLong: /* float x long -> float*/ second.floatValue=(float)pow((double)second.floatValue, (double)tos.longValue); break; case DataType::kTypeFloat: /* float x float -> float */ second.floatValue=(float)pow((double)second.floatValue, (double)tos.floatValue); break; case DataType::kTypeDouble: /* float x double -> dobule */ second.doubleValue=pow((double)second.floatValue,tos.doubleValue); second.dataType=DataType::kTypeDouble; break; case DataType::kTypeBigInt: { /* float x bigInt -> bigFloat */ BigFloat *bigFloat=new BigFloat(); *bigFloat=pow(BigFloat(second.floatValue), BigFloat(*tos.bigIntPtr)); second.bigFloatPtr=bigFloat; second.dataType=DataType::kTypeBigFloat; } break; case DataType::kTypeBigFloat: { /* float x bigFloat -> bigFloat */ BigFloat *bigFloat=new BigFloat(); *bigFloat=pow(BigFloat(second.floatValue),*tos.bigFloatPtr); second.bigFloatPtr=bigFloat; second.dataType=DataType::kTypeBigFloat; } break; default: goto onError; } } else { onError: return inContext.Error(InvalidTypeTosSecondErrorID::E_INVALID_DATA_TYPE_TOS_SECOND,tos,second); } NEXT; })); Install(new Word("max",WORD_FUNC { if(inContext.DS.size()<2) { return inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2); } TypedValue tos=Pop(inContext.DS); TypedValue second=Pop(inContext.DS); PushFuncResult(inContext.DS,maxOp,second,tos); NEXT; })); Install(new Word("min",WORD_FUNC { if(inContext.DS.size()<2) { return inContext.Error(NoParamErrorID::E_DS_AT_LEAST_2); } TypedValue tos=Pop(inContext.DS); TypedValue second=Pop(inContext.DS); PushFuncResult(inContext.DS,minOp,second,tos); NEXT; })); Install(new Word("0?",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue& tos=ReadTOS(inContext.DS); switch(tos.dataType) { case DataType::kTypeInt: tos.dataType=DataType::kTypeBool; tos.boolValue=tos.intValue==0; break; case DataType::kTypeLong: tos.dataType=DataType::kTypeBool; tos.boolValue=tos.longValue==0; break; case DataType::kTypeBigInt: { BigInt *biPtr=tos.bigIntPtr; tos.dataType=DataType::kTypeBool; tos.boolValue=*biPtr==0; delete(biPtr); } break; case DataType::kTypeFloat: tos.dataType=DataType::kTypeBool; tos.boolValue=tos.floatValue==0; break; case DataType::kTypeDouble: tos.dataType=DataType::kTypeBool; tos.boolValue=tos.doubleValue==0; break; case DataType::kTypeBigFloat: { BigFloat *bfPtr=tos.bigFloatPtr; tos.dataType=DataType::kTypeBool; tos.boolValue=*bfPtr==0; delete(bfPtr); } break; default: return inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos); } NEXT; })); // equivalent to '1 +'. Install(new Word("1+",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue& tos=ReadTOS(inContext.DS); switch(tos.dataType) { case DataType::kTypeInt: tos.intValue+=1; break; case DataType::kTypeLong: tos.longValue+=1; break; case DataType::kTypeFloat: tos.floatValue+=1; break; case DataType::kTypeDouble: tos.doubleValue+=1; break; case DataType::kTypeBigInt: *tos.bigIntPtr+=1; break; case DataType::kTypeBigFloat: *tos.bigFloatPtr+=1; break; default: return inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos); } NEXT; },LVOP::LVOpSupported1args | LVOP::INC)); // equivalent to '1 -'. Install(new Word("1-",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue& tos=ReadTOS(inContext.DS); switch(tos.dataType) { case DataType::kTypeInt: tos.intValue-=1; break; case DataType::kTypeLong: tos.longValue-=1; break; case DataType::kTypeFloat: tos.floatValue-=1; break; case DataType::kTypeDouble: tos.doubleValue-=1; break; case DataType::kTypeBigInt: *tos.bigIntPtr-=1; break; case DataType::kTypeBigFloat: *tos.bigFloatPtr-=1;break; default: return inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos); } NEXT; },LVOP::LVOpSupported1args | LVOP::DEC)); Install(new Word("2/",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue& tos=ReadTOS(inContext.DS); switch(tos.dataType) { case DataType::kTypeInt: tos.intValue/=2; break; case DataType::kTypeLong: tos.longValue/=2; break; case DataType::kTypeFloat: tos.floatValue/=2.0f; break; case DataType::kTypeDouble: tos.doubleValue/=2.0; break; case DataType::kTypeBigInt: *tos.bigIntPtr/=2; break; case DataType::kTypeBigFloat: *tos.bigFloatPtr/=2.0; break; default: return inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos); } NEXT; })); Install(new Word("even?",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue& tos=ReadTOS(inContext.DS); switch(tos.dataType) { case DataType::kTypeInt: tos.boolValue = (tos.intValue & 0x01)==0; tos.dataType=DataType::kTypeBool; break; case DataType::kTypeLong: tos.boolValue = (tos.longValue & 0x01)==0; tos.dataType=DataType::kTypeBool; break; case DataType::kTypeBigInt: { bool result=(*tos.bigIntPtr & 0x01)==0; delete tos.bigIntPtr; tos.dataType=DataType::kTypeBool; tos.boolValue=result; } break; default: return inContext.Error(InvalidTypeErrorID::E_TOS_INT_OR_LONG_OR_BIGINT,tos); } NEXT; })); Install(new Word("@even?",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue& tos=ReadTOS(inContext.DS); bool result=false; switch(tos.dataType) { case DataType::kTypeInt: result = (tos.intValue & 0x01)==0; break; case DataType::kTypeLong: result = (tos.longValue & 0x01)==0; break; case DataType::kTypeBigInt: result = (*tos.bigIntPtr & 0x01)==0;break; default: return inContext.Error(InvalidTypeErrorID::E_TOS_INT_OR_LONG_OR_BIGINT,tos); } inContext.DS.emplace_back(result); NEXT; })); Install(new Word("rand-max",WORD_FUNC { inContext.DS.emplace_back(RAND_MAX); NEXT; })); // I --- Install(new Word("set-random-seed",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue tos=Pop(inContext.DS); if(tos.dataType!=DataType::kTypeInt) { return inContext.Error(InvalidTypeErrorID::E_TOS_INT,tos); } srand((unsigned int)tos.intValue); NEXT; })); // [0,RAND_MAX] Install(new Word("rand",WORD_FUNC { inContext.DS.emplace_back(rand()); NEXT; })); // [0,1] Install(new Word("random",WORD_FUNC { inContext.DS.emplace_back((float)rand()/(float)RAND_MAX); NEXT; })); Install(new Word("randomize",WORD_FUNC { srand((unsigned int)time(NULL)); NEXT; })); // n1 --- n2 // s.t. n2 is an integer where n2 in [0,n1). Install(new Word("rand-to",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue tos=Pop(inContext.DS); if(tos.dataType!=DataType::kTypeInt) { return inContext.Error(InvalidTypeErrorID::E_TOS_INT,tos); } const int n=tos.intValue; if(n<0 || RAND_MAX<n) { return inContext.Error(ErrorIdWithInt::E_TOS_POSITIVE_INT,n); } int t=(int)(rand()/((float)RAND_MAX+1)*n); inContext.DS.emplace_back(t); NEXT; })); Install(new Word("pi",WORD_FUNC { inContext.DS.emplace_back(M_PI); NEXT; })); Install(new Word(">int",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue& tos=ReadTOS(inContext.DS); if(tos.dataType==DataType::kTypeFloat) { if(tos.floatValue<INT_MIN || INT_MAX<tos.floatValue) { return inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_INT_DUE_TO_OVERFLOW); } tos.intValue=(int)tos.floatValue; } else if(tos.dataType==DataType::kTypeDouble) { if(tos.doubleValue<INT_MIN || INT_MAX<tos.doubleValue) { return inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_INT_DUE_TO_OVERFLOW); } tos.intValue=(int)tos.doubleValue; } else if(tos.dataType==DataType::kTypeLong) { if(tos.longValue<(long)INT_MIN || (long)INT_MAX<tos.longValue) { return inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_INT_DUE_TO_OVERFLOW); } tos.intValue=(int)tos.longValue; } else if(tos.dataType==DataType::kTypeBigInt) { if(*tos.bigIntPtr<INT_MIN || INT_MAX<*tos.bigIntPtr) { return inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_INT_DUE_TO_OVERFLOW); } tos.intValue=static_cast<int>(*tos.bigIntPtr); } else if(tos.dataType==DataType::kTypeAddress) { tos.dataType=DataType::kTypeInt; } else if(tos.dataType!=DataType::kTypeInt) { return inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos); } tos.dataType=DataType::kTypeInt; NEXT; })); Install(new Word(">long",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue& tos=ReadTOS(inContext.DS); if(tos.dataType==DataType::kTypeFloat) { if(tos.floatValue<LONG_MIN || LONG_MAX<tos.floatValue) { return inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_LONG_DUE_TO_OVERFLOW); } tos.longValue=(long)tos.floatValue; } else if(tos.dataType==DataType::kTypeDouble) { if(tos.doubleValue<LONG_MIN || LONG_MAX<tos.doubleValue) { return inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_LONG_DUE_TO_OVERFLOW); } tos.longValue=(long)tos.doubleValue; } else if(tos.dataType==DataType::kTypeInt) { tos.longValue=(long)tos.intValue; } else if(tos.dataType==DataType::kTypeBigInt) { if(*tos.bigIntPtr<LONG_MIN || LONG_MAX<*tos.bigIntPtr) { return inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_LONG_DUE_TO_OVERFLOW); } tos.longValue=static_cast<long>(*tos.bigIntPtr); } else if(tos.dataType!=DataType::kTypeLong) { return inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos); } tos.dataType=DataType::kTypeLong; NEXT; })); Install(new Word(">INT",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue tos=Pop(inContext.DS); BigInt bigInt; switch(tos.dataType) { case DataType::kTypeInt: bigInt=tos.intValue; break; case DataType::kTypeLong: bigInt=tos.longValue; break; case DataType::kTypeFloat: bigInt=static_cast<BigInt>(tos.floatValue); break; case DataType::kTypeDouble: bigInt=static_cast<BigInt>(tos.doubleValue); break; case DataType::kTypeString: bigInt=BigInt(*tos.stringPtr); break; case DataType::kTypeBigInt: // do nothing break; case DataType::kTypeBigFloat: bigInt=static_cast<BigInt>(*tos.bigFloatPtr); break; default: return inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER_OR_STRING,tos); } if(tos.dataType!=DataType::kTypeBigInt) { inContext.DS.emplace_back(bigInt); } else { inContext.DS.emplace_back(*tos.bigIntPtr); } NEXT; })); Install(new Word(">float",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue& tos=ReadTOS(inContext.DS); switch(tos.dataType) { case DataType::kTypeInt: tos.floatValue=(float)tos.intValue; tos.dataType=DataType::kTypeFloat; break; case DataType::kTypeLong: tos.floatValue=(float)tos.longValue; tos.dataType=DataType::kTypeFloat; break; case DataType::kTypeBigInt: { if(*tos.bigIntPtr>kBigInt_FLT_MAX || *tos.bigIntPtr<kBigInt_Minus_FLT_MAX) { return inContext.Error( NoParamErrorID::E_CAN_NOT_CONVERT_TO_FLOAT_DUE_TO_OVERFLOW); } float f=tos.ToFloat(inContext); delete tos.bigIntPtr; tos.floatValue=f; tos.dataType=DataType::kTypeFloat; } break; case DataType::kTypeFloat: // do nothing break; case DataType::kTypeDouble: if(tos.doubleValue>FLT_MAX || tos.doubleValue<-FLT_MAX) { return inContext.Error(NoParamErrorID::E_CAN_NOT_CONVERT_TO_FLOAT_DUE_TO_OVERFLOW); } tos.floatValue=(float)tos.doubleValue; tos.dataType=DataType::kTypeFloat; break; case DataType::kTypeBigFloat: { if(*tos.bigFloatPtr>FLT_MAX || *tos.bigFloatPtr<-FLT_MAX) { return inContext.Error( NoParamErrorID::E_CAN_NOT_CONVERT_TO_FLOAT_DUE_TO_OVERFLOW); } float f=tos.ToFloat(inContext); delete tos.bigFloatPtr; tos.floatValue=f; tos.dataType=DataType::kTypeFloat; } break; default: return inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos); } NEXT; })); Install(new Word(">double",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue& tos=ReadTOS(inContext.DS); switch(tos.dataType) { case DataType::kTypeInt: tos.doubleValue=(double)tos.intValue; tos.dataType=DataType::kTypeDouble; break; case DataType::kTypeLong: tos.doubleValue=(double)tos.longValue; tos.dataType=DataType::kTypeDouble; break; case DataType::kTypeBigInt: { if(*tos.bigIntPtr>kBigInt_DBL_MAX || *tos.bigIntPtr<kBigInt_Minus_DBL_MAX) { return inContext.Error( NoParamErrorID::E_CAN_NOT_CONVERT_TO_DOUBLE_DUE_TO_OVERFLOW); } double t=tos.ToDouble(inContext); delete tos.bigIntPtr; tos.doubleValue=t; tos.dataType=DataType::kTypeDouble; } break; case DataType::kTypeFloat: tos.doubleValue=(double)tos.floatValue; tos.dataType=DataType::kTypeDouble; break; case DataType::kTypeDouble: // do nothing break; case DataType::kTypeBigFloat: { if(*tos.bigFloatPtr>DBL_MAX || *tos.bigFloatPtr<-DBL_MAX) { return inContext.Error( NoParamErrorID::E_CAN_NOT_CONVERT_TO_DOUBLE_DUE_TO_OVERFLOW); } double t=tos.ToDouble(inContext); delete tos.bigFloatPtr; tos.doubleValue=t; tos.dataType=DataType::kTypeDouble; } break; default: return inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER,tos); } NEXT; })); Install(new Word(">FLOAT",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue tos=Pop(inContext.DS); BigFloat bigFloat; switch(tos.dataType) { case DataType::kTypeInt: bigFloat=tos.intValue; break; case DataType::kTypeLong: bigFloat=tos.longValue; break; case DataType::kTypeFloat: bigFloat=tos.floatValue; break; case DataType::kTypeDouble: bigFloat=tos.doubleValue; break; case DataType::kTypeString: bigFloat=BigFloat(*tos.stringPtr); break; case DataType::kTypeBigInt: bigFloat=static_cast<BigFloat>(*tos.bigIntPtr); break; case DataType::kTypeBigFloat: /* do nothing */ break; default: return inContext.Error(InvalidTypeErrorID::E_TOS_NUMBER_OR_STRING,tos); } if(tos.dataType!=DataType::kTypeBigFloat) { inContext.DS.emplace_back(bigFloat); } else { inContext.DS.emplace_back(*tos.bigFloatPtr); } NEXT; })); Install(new Word(">address",WORD_FUNC { if(inContext.DS.size()<1) { return inContext.Error(NoParamErrorID::E_DS_IS_EMPTY); } TypedValue& tos=ReadTOS(inContext.DS); if(tos.dataType!=DataType::kTypeInt && tos.dataType!=DataType::kTypeAddress) { return inContext.Error(InvalidTypeErrorID::E_TOS_INT,tos); } tos.dataType=DataType::kTypeAddress; NEXT; })); }
8da3f1899d97d82cc68e98b979f6eb1e6158958a
c0e2fc2049cdb611b44af8c3a656d2cd64b3b62b
/src/File/Unix2Dos/readahead.h
d7e92c60a34c80f6b013f36eff1f551ac6680150
[ "Apache-2.0" ]
permissive
github188/SimpleCode
f9e99fd6f3f73bb8cc6c1eea2a8fd84fff8dd77d
781500a3b820e979db64672e3f2b1dc6151c5246
refs/heads/master
2021-01-19T22:53:56.256905
2016-02-02T08:02:43
2016-02-02T08:02:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
462
h
#ifndef H__READAHEAD #define H__READAHEAD #include <stdio.h> class readahead { public: readahead(const char *filespecs, unsigned size, bool binary = false); ~readahead(); bool open() const {return fp != NULL;} int operator [](int i) const {return buffer[i];} void advance(unsigned count = 1); bool match(const char *s) const; private: int *buffer; unsigned psize; FILE *fp; bool eof; int get(void); }; #endif
b4acd87b4b1acee6054244b4c2016d268cd74672
243e8662495072d8f84ed2c6c55de15dcc219d6a
/tyrrellJustin_VGP463_newProject/Student.Point.h
0c815161b431d7feb7a683de3809c898ae99872e
[]
no_license
pdx1138/OpenGLRTE
1c0e9d5256bd7641342cc47ed2b6d2a54b15b3ea
f16fe5800808d92a67c3035deb2b51e0b6c0c2e8
refs/heads/master
2021-01-10T05:25:15.032264
2016-08-25T04:02:41
2016-08-25T04:02:41
53,845,542
0
0
null
null
null
null
UTF-8
C++
false
false
564
h
// Student.Point.h /////////////////////////////////////////////////////////////////////////////////////////////// #pragma once class Point { public: float x, y, z, w; Point(); Point(float x, float y, float z, float w); void Normalize(); float Length(); Point operator-(const Point &p) const; Point operator+(const Point &p) const; }; typedef Point Vector; float DotProduct(Vector a, Vector b); Point operator*(float a, const Point &p); Point Reflection(const Point &v, const Point &n); Point CrossProduct(const Point & v1, const Point &v2);
75a059e7939ad200b055b10cab14715eb2a3406c
bae731d82d044cf02239ee63954b7d60da2b8a04
/GitHubTutorial/Tutorial.cpp
7aa3f745fc34113ced4cc6948c5894af27dccd28
[]
no_license
ktj9279/GitHubTutorial
bf0bd63eb3246123c027fa01e87046bccf361c2b
bf0600a355eb43ebaba86b042b41aafc9e400013
refs/heads/master
2020-12-30T13:20:11.943397
2017-05-15T15:59:18
2017-05-15T15:59:18
91,345,529
0
0
null
null
null
null
UTF-8
C++
false
false
114
cpp
#include <iostream> using namespace std; int main(int argc, char* argv[]) { cout << "Hello world"; return 0; }
fa6a15eb82d679b596ea8c6057f59f07d076312e
5e99905feaadc98c4c89e6900151ec922d480735
/561.cpp
beb250755f4ae5c2955f103c1cfa897d3c42cd6f
[]
no_license
suraj021/LeetCode-Solutions
0bc7407fa35e1a9390fd32325c2fca2e50482c0f
02f3a4302f93443bf2c79935717770abd9b79d03
refs/heads/master
2020-06-10T05:57:06.344586
2020-03-21T07:22:00
2020-03-21T07:22:00
76,068,210
0
0
null
null
null
null
UTF-8
C++
false
false
256
cpp
class Solution { public: int arrayPairSum(vector<int>& nums) { sort(nums.begin(), nums.end()); int sum= 0; for(int i= 0; i< nums.size(); i+= 2){ sum+= nums[i]; } return sum; } };
ce32a8056f4e17b1394eda68a0efacb462cdb1de
5a60d60fca2c2b8b44d602aca7016afb625bc628
/aws-cpp-sdk-connect/include/aws/connect/model/UpdateSecurityProfileRequest.h
a8cdf60dc4961cad427dea4829b428f3ae88b144
[ "Apache-2.0", "MIT", "JSON" ]
permissive
yuatpocketgems/aws-sdk-cpp
afaa0bb91b75082b63236cfc0126225c12771ed0
a0dcbc69c6000577ff0e8171de998ccdc2159c88
refs/heads/master
2023-01-23T10:03:50.077672
2023-01-04T22:42:53
2023-01-04T22:42:53
134,497,260
0
1
null
2018-05-23T01:47:14
2018-05-23T01:47:14
null
UTF-8
C++
false
false
17,329
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/connect/Connect_EXPORTS.h> #include <aws/connect/ConnectRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/core/utils/memory/stl/AWSMap.h> #include <utility> namespace Aws { namespace Connect { namespace Model { /** */ class UpdateSecurityProfileRequest : public ConnectRequest { public: AWS_CONNECT_API UpdateSecurityProfileRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "UpdateSecurityProfile"; } AWS_CONNECT_API Aws::String SerializePayload() const override; /** * <p>The description of the security profile.</p> */ inline const Aws::String& GetDescription() const{ return m_description; } /** * <p>The description of the security profile.</p> */ inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; } /** * <p>The description of the security profile.</p> */ inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; } /** * <p>The description of the security profile.</p> */ inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); } /** * <p>The description of the security profile.</p> */ inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); } /** * <p>The description of the security profile.</p> */ inline UpdateSecurityProfileRequest& WithDescription(const Aws::String& value) { SetDescription(value); return *this;} /** * <p>The description of the security profile.</p> */ inline UpdateSecurityProfileRequest& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;} /** * <p>The description of the security profile.</p> */ inline UpdateSecurityProfileRequest& WithDescription(const char* value) { SetDescription(value); return *this;} /** * <p>The permissions granted to a security profile. For a list of valid * permissions, see <a * href="https://docs.aws.amazon.com/connect/latest/adminguide/security-profile-list.html">List * of security profile permissions</a>.</p> */ inline const Aws::Vector<Aws::String>& GetPermissions() const{ return m_permissions; } /** * <p>The permissions granted to a security profile. For a list of valid * permissions, see <a * href="https://docs.aws.amazon.com/connect/latest/adminguide/security-profile-list.html">List * of security profile permissions</a>.</p> */ inline bool PermissionsHasBeenSet() const { return m_permissionsHasBeenSet; } /** * <p>The permissions granted to a security profile. For a list of valid * permissions, see <a * href="https://docs.aws.amazon.com/connect/latest/adminguide/security-profile-list.html">List * of security profile permissions</a>.</p> */ inline void SetPermissions(const Aws::Vector<Aws::String>& value) { m_permissionsHasBeenSet = true; m_permissions = value; } /** * <p>The permissions granted to a security profile. For a list of valid * permissions, see <a * href="https://docs.aws.amazon.com/connect/latest/adminguide/security-profile-list.html">List * of security profile permissions</a>.</p> */ inline void SetPermissions(Aws::Vector<Aws::String>&& value) { m_permissionsHasBeenSet = true; m_permissions = std::move(value); } /** * <p>The permissions granted to a security profile. For a list of valid * permissions, see <a * href="https://docs.aws.amazon.com/connect/latest/adminguide/security-profile-list.html">List * of security profile permissions</a>.</p> */ inline UpdateSecurityProfileRequest& WithPermissions(const Aws::Vector<Aws::String>& value) { SetPermissions(value); return *this;} /** * <p>The permissions granted to a security profile. For a list of valid * permissions, see <a * href="https://docs.aws.amazon.com/connect/latest/adminguide/security-profile-list.html">List * of security profile permissions</a>.</p> */ inline UpdateSecurityProfileRequest& WithPermissions(Aws::Vector<Aws::String>&& value) { SetPermissions(std::move(value)); return *this;} /** * <p>The permissions granted to a security profile. For a list of valid * permissions, see <a * href="https://docs.aws.amazon.com/connect/latest/adminguide/security-profile-list.html">List * of security profile permissions</a>.</p> */ inline UpdateSecurityProfileRequest& AddPermissions(const Aws::String& value) { m_permissionsHasBeenSet = true; m_permissions.push_back(value); return *this; } /** * <p>The permissions granted to a security profile. For a list of valid * permissions, see <a * href="https://docs.aws.amazon.com/connect/latest/adminguide/security-profile-list.html">List * of security profile permissions</a>.</p> */ inline UpdateSecurityProfileRequest& AddPermissions(Aws::String&& value) { m_permissionsHasBeenSet = true; m_permissions.push_back(std::move(value)); return *this; } /** * <p>The permissions granted to a security profile. For a list of valid * permissions, see <a * href="https://docs.aws.amazon.com/connect/latest/adminguide/security-profile-list.html">List * of security profile permissions</a>.</p> */ inline UpdateSecurityProfileRequest& AddPermissions(const char* value) { m_permissionsHasBeenSet = true; m_permissions.push_back(value); return *this; } /** * <p>The identifier for the security profle.</p> */ inline const Aws::String& GetSecurityProfileId() const{ return m_securityProfileId; } /** * <p>The identifier for the security profle.</p> */ inline bool SecurityProfileIdHasBeenSet() const { return m_securityProfileIdHasBeenSet; } /** * <p>The identifier for the security profle.</p> */ inline void SetSecurityProfileId(const Aws::String& value) { m_securityProfileIdHasBeenSet = true; m_securityProfileId = value; } /** * <p>The identifier for the security profle.</p> */ inline void SetSecurityProfileId(Aws::String&& value) { m_securityProfileIdHasBeenSet = true; m_securityProfileId = std::move(value); } /** * <p>The identifier for the security profle.</p> */ inline void SetSecurityProfileId(const char* value) { m_securityProfileIdHasBeenSet = true; m_securityProfileId.assign(value); } /** * <p>The identifier for the security profle.</p> */ inline UpdateSecurityProfileRequest& WithSecurityProfileId(const Aws::String& value) { SetSecurityProfileId(value); return *this;} /** * <p>The identifier for the security profle.</p> */ inline UpdateSecurityProfileRequest& WithSecurityProfileId(Aws::String&& value) { SetSecurityProfileId(std::move(value)); return *this;} /** * <p>The identifier for the security profle.</p> */ inline UpdateSecurityProfileRequest& WithSecurityProfileId(const char* value) { SetSecurityProfileId(value); return *this;} /** * <p>The identifier of the Amazon Connect instance. You can find the instanceId in * the ARN of the instance.</p> */ inline const Aws::String& GetInstanceId() const{ return m_instanceId; } /** * <p>The identifier of the Amazon Connect instance. You can find the instanceId in * the ARN of the instance.</p> */ inline bool InstanceIdHasBeenSet() const { return m_instanceIdHasBeenSet; } /** * <p>The identifier of the Amazon Connect instance. You can find the instanceId in * the ARN of the instance.</p> */ inline void SetInstanceId(const Aws::String& value) { m_instanceIdHasBeenSet = true; m_instanceId = value; } /** * <p>The identifier of the Amazon Connect instance. You can find the instanceId in * the ARN of the instance.</p> */ inline void SetInstanceId(Aws::String&& value) { m_instanceIdHasBeenSet = true; m_instanceId = std::move(value); } /** * <p>The identifier of the Amazon Connect instance. You can find the instanceId in * the ARN of the instance.</p> */ inline void SetInstanceId(const char* value) { m_instanceIdHasBeenSet = true; m_instanceId.assign(value); } /** * <p>The identifier of the Amazon Connect instance. You can find the instanceId in * the ARN of the instance.</p> */ inline UpdateSecurityProfileRequest& WithInstanceId(const Aws::String& value) { SetInstanceId(value); return *this;} /** * <p>The identifier of the Amazon Connect instance. You can find the instanceId in * the ARN of the instance.</p> */ inline UpdateSecurityProfileRequest& WithInstanceId(Aws::String&& value) { SetInstanceId(std::move(value)); return *this;} /** * <p>The identifier of the Amazon Connect instance. You can find the instanceId in * the ARN of the instance.</p> */ inline UpdateSecurityProfileRequest& WithInstanceId(const char* value) { SetInstanceId(value); return *this;} /** * <p>The list of tags that a security profile uses to restrict access to resources * in Amazon Connect.</p> */ inline const Aws::Map<Aws::String, Aws::String>& GetAllowedAccessControlTags() const{ return m_allowedAccessControlTags; } /** * <p>The list of tags that a security profile uses to restrict access to resources * in Amazon Connect.</p> */ inline bool AllowedAccessControlTagsHasBeenSet() const { return m_allowedAccessControlTagsHasBeenSet; } /** * <p>The list of tags that a security profile uses to restrict access to resources * in Amazon Connect.</p> */ inline void SetAllowedAccessControlTags(const Aws::Map<Aws::String, Aws::String>& value) { m_allowedAccessControlTagsHasBeenSet = true; m_allowedAccessControlTags = value; } /** * <p>The list of tags that a security profile uses to restrict access to resources * in Amazon Connect.</p> */ inline void SetAllowedAccessControlTags(Aws::Map<Aws::String, Aws::String>&& value) { m_allowedAccessControlTagsHasBeenSet = true; m_allowedAccessControlTags = std::move(value); } /** * <p>The list of tags that a security profile uses to restrict access to resources * in Amazon Connect.</p> */ inline UpdateSecurityProfileRequest& WithAllowedAccessControlTags(const Aws::Map<Aws::String, Aws::String>& value) { SetAllowedAccessControlTags(value); return *this;} /** * <p>The list of tags that a security profile uses to restrict access to resources * in Amazon Connect.</p> */ inline UpdateSecurityProfileRequest& WithAllowedAccessControlTags(Aws::Map<Aws::String, Aws::String>&& value) { SetAllowedAccessControlTags(std::move(value)); return *this;} /** * <p>The list of tags that a security profile uses to restrict access to resources * in Amazon Connect.</p> */ inline UpdateSecurityProfileRequest& AddAllowedAccessControlTags(const Aws::String& key, const Aws::String& value) { m_allowedAccessControlTagsHasBeenSet = true; m_allowedAccessControlTags.emplace(key, value); return *this; } /** * <p>The list of tags that a security profile uses to restrict access to resources * in Amazon Connect.</p> */ inline UpdateSecurityProfileRequest& AddAllowedAccessControlTags(Aws::String&& key, const Aws::String& value) { m_allowedAccessControlTagsHasBeenSet = true; m_allowedAccessControlTags.emplace(std::move(key), value); return *this; } /** * <p>The list of tags that a security profile uses to restrict access to resources * in Amazon Connect.</p> */ inline UpdateSecurityProfileRequest& AddAllowedAccessControlTags(const Aws::String& key, Aws::String&& value) { m_allowedAccessControlTagsHasBeenSet = true; m_allowedAccessControlTags.emplace(key, std::move(value)); return *this; } /** * <p>The list of tags that a security profile uses to restrict access to resources * in Amazon Connect.</p> */ inline UpdateSecurityProfileRequest& AddAllowedAccessControlTags(Aws::String&& key, Aws::String&& value) { m_allowedAccessControlTagsHasBeenSet = true; m_allowedAccessControlTags.emplace(std::move(key), std::move(value)); return *this; } /** * <p>The list of tags that a security profile uses to restrict access to resources * in Amazon Connect.</p> */ inline UpdateSecurityProfileRequest& AddAllowedAccessControlTags(const char* key, Aws::String&& value) { m_allowedAccessControlTagsHasBeenSet = true; m_allowedAccessControlTags.emplace(key, std::move(value)); return *this; } /** * <p>The list of tags that a security profile uses to restrict access to resources * in Amazon Connect.</p> */ inline UpdateSecurityProfileRequest& AddAllowedAccessControlTags(Aws::String&& key, const char* value) { m_allowedAccessControlTagsHasBeenSet = true; m_allowedAccessControlTags.emplace(std::move(key), value); return *this; } /** * <p>The list of tags that a security profile uses to restrict access to resources * in Amazon Connect.</p> */ inline UpdateSecurityProfileRequest& AddAllowedAccessControlTags(const char* key, const char* value) { m_allowedAccessControlTagsHasBeenSet = true; m_allowedAccessControlTags.emplace(key, value); return *this; } /** * <p>The list of resources that a security profile applies tag restrictions to in * Amazon Connect.</p> */ inline const Aws::Vector<Aws::String>& GetTagRestrictedResources() const{ return m_tagRestrictedResources; } /** * <p>The list of resources that a security profile applies tag restrictions to in * Amazon Connect.</p> */ inline bool TagRestrictedResourcesHasBeenSet() const { return m_tagRestrictedResourcesHasBeenSet; } /** * <p>The list of resources that a security profile applies tag restrictions to in * Amazon Connect.</p> */ inline void SetTagRestrictedResources(const Aws::Vector<Aws::String>& value) { m_tagRestrictedResourcesHasBeenSet = true; m_tagRestrictedResources = value; } /** * <p>The list of resources that a security profile applies tag restrictions to in * Amazon Connect.</p> */ inline void SetTagRestrictedResources(Aws::Vector<Aws::String>&& value) { m_tagRestrictedResourcesHasBeenSet = true; m_tagRestrictedResources = std::move(value); } /** * <p>The list of resources that a security profile applies tag restrictions to in * Amazon Connect.</p> */ inline UpdateSecurityProfileRequest& WithTagRestrictedResources(const Aws::Vector<Aws::String>& value) { SetTagRestrictedResources(value); return *this;} /** * <p>The list of resources that a security profile applies tag restrictions to in * Amazon Connect.</p> */ inline UpdateSecurityProfileRequest& WithTagRestrictedResources(Aws::Vector<Aws::String>&& value) { SetTagRestrictedResources(std::move(value)); return *this;} /** * <p>The list of resources that a security profile applies tag restrictions to in * Amazon Connect.</p> */ inline UpdateSecurityProfileRequest& AddTagRestrictedResources(const Aws::String& value) { m_tagRestrictedResourcesHasBeenSet = true; m_tagRestrictedResources.push_back(value); return *this; } /** * <p>The list of resources that a security profile applies tag restrictions to in * Amazon Connect.</p> */ inline UpdateSecurityProfileRequest& AddTagRestrictedResources(Aws::String&& value) { m_tagRestrictedResourcesHasBeenSet = true; m_tagRestrictedResources.push_back(std::move(value)); return *this; } /** * <p>The list of resources that a security profile applies tag restrictions to in * Amazon Connect.</p> */ inline UpdateSecurityProfileRequest& AddTagRestrictedResources(const char* value) { m_tagRestrictedResourcesHasBeenSet = true; m_tagRestrictedResources.push_back(value); return *this; } private: Aws::String m_description; bool m_descriptionHasBeenSet = false; Aws::Vector<Aws::String> m_permissions; bool m_permissionsHasBeenSet = false; Aws::String m_securityProfileId; bool m_securityProfileIdHasBeenSet = false; Aws::String m_instanceId; bool m_instanceIdHasBeenSet = false; Aws::Map<Aws::String, Aws::String> m_allowedAccessControlTags; bool m_allowedAccessControlTagsHasBeenSet = false; Aws::Vector<Aws::String> m_tagRestrictedResources; bool m_tagRestrictedResourcesHasBeenSet = false; }; } // namespace Model } // namespace Connect } // namespace Aws
89f8919bc59d49f1755805cb6d61db604c6368f2
26ee8ad1a8675e07cc5f364dc1468f6091c10fba
/VertexStruct.h
ab85711b05cfebeb0bde30282ab177d67ac521ab
[]
no_license
Yuriy29/GL2DImageTo3DOOP
f989e8b74623cbd1c04d080a9b15fd4744b51131
cfc02dcf42364f8c2e919a99bd5e203833262147
refs/heads/master
2021-01-02T23:07:42.953408
2014-12-23T14:12:52
2014-12-23T14:12:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
253
h
#pragma once #include "glm/glm.hpp" #include "glm/gtx/transform.hpp" #include "glm/gtc/type_ptr.hpp" class VertexStruct { public: glm::vec3 *pos; glm::vec3 *normal; glm::vec2 *tex; VertexStruct(int u, int v); ~VertexStruct(void); };
c46144909dab589026a90a8ecf1b5c7d16dbeef8
c3bdc0d043569dc98e9724e06fd3147d7fac551b
/ezhg/2016whatever/tobbsor_mira1_vagynem/jav_stillnoorwat/Enor.txt
b2d730f947e84a3a503e502cbcafdd609f25f77f
[]
no_license
8emi95/elte-ik-prog
efc20783a60432a908fd3a56e0e94a37238f9de6
bf51ddd880d1d8e35b4020e6fdb3f8f95ba9127f
refs/heads/master
2020-07-25T09:10:54.122984
2019-03-16T22:47:27
2019-03-16T22:47:27
175,998,663
0
0
null
null
null
null
UTF-8
C++
false
false
565
txt
#ifndef ENOR_H #define ENOR_H #include<iostream> #include<vector> #include<fstream> struct Par { int adag; std::string tipus; }; struct Adat { std::vector<std::string> rovidetes; int asztalszam; std::string ido; std::vector<Par> p; }; class Enor { public: Enor(std::string fnev); ~Enor(); void First(); void Next(); Adat Current() const { return akt; } bool End() const { return vege; } private: std::ifstream x; Adat akt; bool vege; }; #endif // ENOR_H
a8984118ad9afcf91dc277366a6459ac221d570e
b480d9f90f05dc65615e902dec9a402589bc1f14
/player.cpp
7498d3427af1954b1f686ee1750bdf5eaf0c167f
[]
no_license
marcus-elia/random-terrain
fd99c35d49174f2877efb1915ff605b9813ed9bb
8be8d540cb9efb44a994f7fbaf09f2d57ed21512
refs/heads/master
2022-12-22T00:08:32.417374
2020-09-09T22:35:11
2020-09-09T22:35:11
292,424,849
0
0
null
null
null
null
UTF-8
C++
false
false
7,663
cpp
#include "player.h" Player::Player() { location = {0, 10, 0}; lookingAt = {0, 10, -10}; up = {0, 20, 0}; speed = 2; velocity = {0, 0, 0}; sensitivity = 0.1; height = 20; radius = 5; initializeAngles(); initializeSphericalDirection(); maxDistanceFromSpawn = 5120; isGrounded = true; gravity = -0.1; jumpAmount = 10; } Player::Player(Point inputLocation, Point inputLookingAt, Point inputUp, double inputSpeed, double inputSensitivity, double inputHeight, double inputRadius, int inputMaxDistanceFromSpawn, double inputGravity, double inputJumpAmount) { location = inputLocation; lookingAt = inputLookingAt; up = inputUp; speed = inputSpeed; velocity = {0, 0, 0}; sensitivity = inputSensitivity; height = inputHeight; radius = inputRadius; initializeAngles(); initializeSphericalDirection(); maxDistanceFromSpawn = inputMaxDistanceFromSpawn; isGrounded = true; gravity = inputGravity; jumpAmount = inputJumpAmount; } void Player::initializeAngles() { xzAngle = atan2(lookingAt.z - location.z, lookingAt.x - location.x); yAngle = atan2(lookingAt.y - location.y, distance2d(location, lookingAt)); } void Player::initializeSphericalDirection() { sphericalDirection.x = cos(xzAngle); sphericalDirection.z = sin(xzAngle); // Must scale the component in the xz plane for spherical coordinates double scaleAmount = cos(yAngle) / sqrt(sphericalDirection.x*sphericalDirection.x + sphericalDirection.z*sphericalDirection.z); sphericalDirection.x *= scaleAmount; sphericalDirection.z *= scaleAmount; sphericalDirection.y = sin(yAngle); } // ========================== // // Getters // // ========================== Point Player::getLocation() const { return location; } Point Player::getLookingAt() const { return lookingAt; } Point Player::getUp() const { return up; } Point Player::getVelocity() const { return velocity; } double Player::getSpeed() const { return speed; } double Player::getXZAngle() const { return xzAngle; } double Player::getYAngle() const { return yAngle; } double Player::getHeight() const { return height; } double Player::getRadius() const { return radius; } // ========================== // // Setters // // ========================== void Player::setLocation(Point inputLocation) { location = inputLocation; } void Player::setLookingAt(Point inputLookingAt) { lookingAt = inputLookingAt; } void Player::setUp(Point inputUp) { up = inputUp; } void Player::setSpeed(double inputSpeed) { speed = inputSpeed; } void Player::setSensitivity(double inputSensitivity) { sensitivity = inputSensitivity; } void Player::setXZAngle(double inputXZAngle) { xzAngle = inputXZAngle; } void Player::setYAngle(double inputYAngle) { yAngle = inputYAngle; } void Player::setCurrentTerrainHeight(double inputTerrainHeight) { currentTerrainHeight = inputTerrainHeight; } // =============================== // // Movement // // ============================== void Player::move() { moveXZ(); location.y += velocity.y; lookingAt.y += velocity.y; } void Player::moveXZ() { location.x += velocity.x; lookingAt.x += velocity.x; location.z += velocity.z; lookingAt.z += velocity.z; } void Player::correctGround() { if(location.y < currentTerrainHeight + height/2) { lookingAt.y += currentTerrainHeight + height/2 - location.y; location.y = currentTerrainHeight + height/2; isGrounded = true; velocity.y = 0; } } void Player::applyGravity() { if(!isGrounded) { velocity.y += gravity; } else { // If we moved and the terrain became lower, we need to fall down if(location.y > currentTerrainHeight + height/2) { lookingAt.y += currentTerrainHeight + height/2 - location.y; location.y = currentTerrainHeight + height/2; } } } void Player::stayWithinBoundary() { if(location.x > maxDistanceFromSpawn) { lookingAt.x -= maxDistanceFromSpawn - location.x; location.x = maxDistanceFromSpawn; } else if(location.x < -maxDistanceFromSpawn) { lookingAt.x += maxDistanceFromSpawn + location.x; location.x = -maxDistanceFromSpawn; } if(location.z > maxDistanceFromSpawn) { lookingAt.z -= maxDistanceFromSpawn - location.z; location.z = maxDistanceFromSpawn; } else if(location.z < -maxDistanceFromSpawn) { lookingAt.z += maxDistanceFromSpawn + location.z; location.z = -maxDistanceFromSpawn; } } // Based on which keys are pressed, set the velocity void Player::setVelocity(bool wKey, bool aKey, bool sKey, bool dKey) { bool forward = wKey && !sKey; bool backward = !wKey && sKey; bool left = aKey && !dKey; bool right = !aKey && dKey; // The angle the player should move based on input double angleToMove; if(forward) { if(right) { angleToMove = xzAngle + PI/4; } else if(left) { angleToMove = xzAngle - PI/4; } else { angleToMove = xzAngle; } } else if(backward) { if(right) { angleToMove = xzAngle - PI - PI/4; } else if(left) { angleToMove = xzAngle - PI + PI/4; } else { angleToMove = xzAngle - PI; } } else { if(right) { angleToMove = xzAngle + PI/2; } else if(left) { angleToMove = xzAngle - PI/2; } else // If no arrow keys are being held { velocity.x = 0; velocity.z = 0; return; } } velocity.x = speed * cos(angleToMove); velocity.z = speed * sin(angleToMove); } // Update the xzAngle and yAngle based on theta resulting from a mouse movement void Player::updateAngles(double theta, double distance) { double horizontalAmount = sensitivity * distance* cos(theta); xzAngle += horizontalAmount; if(xzAngle > 2*PI) { xzAngle -= 2*PI; } else if(xzAngle < 0) { xzAngle += 2*PI; } double verticalAmount = sensitivity * distance* sin(theta); yAngle -= verticalAmount; // negative sign since Glut's mouse functions treat +y as down if(yAngle > PI/2 - VERTICAL_LIMIT) { yAngle = PI/2 - VERTICAL_LIMIT; } else if(yAngle < -PI/2 + VERTICAL_LIMIT) { yAngle = -PI/2 + VERTICAL_LIMIT; } } // Use xzAngle, yAngle, and location to determine the spherical direction. void Player::updateSphericalDirectionBasedOnAngles() { sphericalDirection.x = cos(xzAngle); sphericalDirection.z = sin(xzAngle); // Must scale the component in the xz plane for spherical coordinates double scaleAmount = cos(yAngle) / sqrt(sphericalDirection.x*sphericalDirection.x + sphericalDirection.z*sphericalDirection.z); sphericalDirection.x *= scaleAmount; sphericalDirection.z *= scaleAmount; sphericalDirection.y = sin(yAngle); lookingAt.x = location.x + sphericalDirection.x; lookingAt.y = location.y + sphericalDirection.y; lookingAt.z = location.z + sphericalDirection.z; } void Player::tryToJump() { if(isGrounded) { velocity.y = jumpAmount; isGrounded = false; } } void Player::tick() { move(); correctGround(); applyGravity(); stayWithinBoundary(); }
56299c6b59839b5a8ffa191c66583a14a567156c
4e32963cbed9c80f04215ea77f8a5a4a224ae2db
/headers/ProjectiveTextureMapping.h
387a9eec461915e2d12c0f4b3fd1e4b97a09c58d
[]
no_license
DontSuCharlie/DualPhotography
9c7458f34e00abb147ab8c754a0e84b3873cba6e
6b895c61460e8bbbda71625b595ab639d381aea4
refs/heads/master
2020-03-08T19:20:17.775540
2018-04-26T08:25:47
2018-04-26T08:25:47
128,348,630
0
0
null
null
null
null
UTF-8
C++
false
false
209
h
#pragma once #include <vector> class ProjectiveTextureMapping { public: ProjectiveTextureMapping(vector<float> polygon_verts, Framebuffer img, function pointer for search alg, error function); private: };
e07b82a2411e1c0b8aee1c592d519c5e3b03d236
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/chrome/browser/ui/ash/launcher/arc_app_window.cc
cc201ceeba1f7e1c0423c08911351e6a3f776225
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
4,580
cc
// Copyright 2017 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/ash/launcher/arc_app_window.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/ui/app_list/arc/arc_app_icon.h" #include "chrome/browser/ui/app_list/arc/arc_app_utils.h" #include "chrome/browser/ui/ash/launcher/arc_app_window_launcher_controller.h" #include "chrome/browser/ui/ash/launcher/arc_app_window_launcher_item_controller.h" #include "components/exo/shell_surface.h" #include "extensions/common/constants.h" #include "ui/aura/window.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/image/image_skia_operations.h" #include "ui/views/widget/native_widget_aura.h" #include "ui/views/widget/widget.h" ArcAppWindow::ArcAppWindow(int task_id, const arc::ArcAppShelfId& app_shelf_id, views::Widget* widget, ArcAppWindowLauncherController* owner) : task_id_(task_id), app_shelf_id_(app_shelf_id), widget_(widget), owner_(owner) {} ArcAppWindow::~ArcAppWindow() { ImageDecoder::Cancel(this); } void ArcAppWindow::SetController( ArcAppWindowLauncherItemController* controller) { DCHECK(!controller_ || !controller); controller_ = controller; } void ArcAppWindow::SetFullscreenMode(FullScreenMode mode) { DCHECK(mode != FullScreenMode::NOT_DEFINED); fullscreen_mode_ = mode; } void ArcAppWindow::SetDescription( const std::string& title, const std::vector<uint8_t>& unsafe_icon_data_png) { if (!title.empty()) GetNativeWindow()->SetTitle(base::UTF8ToUTF16(title)); ImageDecoder::Cancel(this); if (unsafe_icon_data_png.empty()) { SetIcon(gfx::ImageSkia()); return; } if (ArcAppIcon::IsSafeDecodingDisabledForTesting()) { SkBitmap bitmap; if (gfx::PNGCodec::Decode(&unsafe_icon_data_png[0], unsafe_icon_data_png.size(), &bitmap)) { OnImageDecoded(bitmap); } else { OnDecodeImageFailed(); } } else { ImageDecoder::Start(this, unsafe_icon_data_png); } } bool ArcAppWindow::IsActive() const { return widget_->IsActive() && owner_->active_task_id() == task_id_; } bool ArcAppWindow::IsMaximized() const { NOTREACHED(); return false; } bool ArcAppWindow::IsMinimized() const { NOTREACHED(); return false; } bool ArcAppWindow::IsFullscreen() const { NOTREACHED(); return false; } gfx::NativeWindow ArcAppWindow::GetNativeWindow() const { return widget_->GetNativeWindow(); } gfx::Rect ArcAppWindow::GetRestoredBounds() const { NOTREACHED(); return gfx::Rect(); } ui::WindowShowState ArcAppWindow::GetRestoredState() const { NOTREACHED(); return ui::SHOW_STATE_NORMAL; } gfx::Rect ArcAppWindow::GetBounds() const { NOTREACHED(); return gfx::Rect(); } void ArcAppWindow::Show() { widget_->Show(); } void ArcAppWindow::ShowInactive() { NOTREACHED(); } void ArcAppWindow::Hide() { NOTREACHED(); } void ArcAppWindow::Close() { arc::CloseTask(task_id_); } void ArcAppWindow::Activate() { widget_->Activate(); } void ArcAppWindow::Deactivate() { NOTREACHED(); } void ArcAppWindow::Maximize() { NOTREACHED(); } void ArcAppWindow::Minimize() { widget_->Minimize(); } void ArcAppWindow::Restore() { NOTREACHED(); } void ArcAppWindow::SetBounds(const gfx::Rect& bounds) { NOTREACHED(); } void ArcAppWindow::FlashFrame(bool flash) { NOTREACHED(); } bool ArcAppWindow::IsAlwaysOnTop() const { NOTREACHED(); return false; } void ArcAppWindow::SetAlwaysOnTop(bool always_on_top) { NOTREACHED(); } void ArcAppWindow::SetIcon(const gfx::ImageSkia& icon) { if (!exo::ShellSurface::GetMainSurface(GetNativeWindow())) { // Support unit tests where we don't have exo system initialized. views::NativeWidgetAura::AssignIconToAuraWindow( GetNativeWindow(), gfx::ImageSkia() /* window_icon */, icon /* app_icon */); return; } exo::ShellSurface* shell_surface = static_cast<exo::ShellSurface*>( widget_->widget_delegate()->GetContentsView()); if (!shell_surface) return; shell_surface->SetIcon(icon); } void ArcAppWindow::OnImageDecoded(const SkBitmap& decoded_image) { SetIcon(gfx::ImageSkiaOperations::CreateResizedImage( gfx::ImageSkia(gfx::ImageSkiaRep(decoded_image, 1.0f)), skia::ImageOperations::RESIZE_BEST, gfx::Size(extension_misc::EXTENSION_ICON_SMALL, extension_misc::EXTENSION_ICON_SMALL))); }
cdd23a71ee3d6c329803fe457fbafdac5310d32e
97bb7da626def8ad206be815c64348778f550d38
/384.shuffle_an_array/ShuffleAnArray.h
9426096b573b29da262d30a55502100ad30bb0e1
[]
no_license
songkey7/leetcode
c242daafe33cc6035461fc2f3e751489d8b2551e
2f72c821bd0551313813c9b745ddf5207e1cb71c
refs/heads/master
2021-05-14T09:50:35.570822
2020-04-10T01:20:11
2020-04-10T01:20:11
116,336,985
0
0
null
null
null
null
UTF-8
C++
false
false
341
h
// // Created by Qi Song on 18/04/2018. // #ifndef LEETCODE_SHUFFLEANARRAY_H #define LEETCODE_SHUFFLEANARRAY_H #include "../Base.h" class ShuffleAnArray: public Base { vector<int> _vec; vector<int> reset(); vector<int> shuffle(); vector<int> shuffle2(); public: void run(); }; #endif //LEETCODE_SHUFFLEANARRAY_H
75eb35f6900edd26d64b901b648d1c7ac43f22d1
3c82ea39e4c0698b613e91a82c1b2d940742d16d
/CP_Air/CP_Air/MainForm.cpp
93325d5e54a3fa832c3ab62d3a5bb70b6b12fb1c
[]
no_license
SergeyGorbanenko/Gorbanenko_CourseProject
6463e47806ab212373721732d124002d9bf412f9
6368b13fb944403b44f5a7eaa2e3632a2b54efea
refs/heads/master
2021-07-01T03:41:13.437408
2017-09-22T05:56:36
2017-09-22T05:56:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
295
cpp
#include "MainForm.h" using namespace CP_Air; using namespace CP_Air::Windows::Forms; [STAThreadAttribute] int main(array<System::String ^> ^args){ Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); CP_Air::MainForm form; Application::Run(%form); }
43f2aee1d4802330a718f079c550386425c697cb
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_old_hunk_5033.cpp
b47d5cd9bce37d0eac29a31e091e2fee7ff43b78
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
283
cpp
} apr_file_open_stderr(&errfile, pool); rv = apr_getopt_init(&opt, pool, argc, argv); if (rv != APR_SUCCESS) { apr_file_printf(errfile, "Error: apr_getopt_init failed."NL NL); return 1; } if (argc <= 1) { usage(); return 1;
92a2a7869ea67931392747a28983dc977eb6ed3f
2fb12ae9a322f25c9fde98196aa37fb53d1d0c6a
/sir.cpp
7fba1101aa6392264e61f4c18f12a56a2004315b
[]
no_license
Theodorulus/HW-1-OOP
d090479828fed0fde2ba99fe8ea876be85c57fe6
749c621b8144396f4bfc657f23710a33938dd8ed
refs/heads/master
2023-06-09T03:34:32.540229
2021-06-26T08:26:58
2021-06-26T08:26:58
250,359,460
0
0
null
null
null
null
UTF-8
C++
false
false
2,791
cpp
#include <iostream> #include "sir.h" using namespace std; Sir::Sir () { s = new char[1]; s[0] = '\0'; } Sir::Sir(char *str) { int nr, i; for(nr = 0; str[nr] != '\0'; nr++); // len(str) s = new char[nr + 1]; // nr + 1 ca sa las un caracter liber pentru linistea mea for(i = 0; i < nr; i++) s[i] = str[i]; s[nr] = '\0'; } Sir::Sir(const Sir& str) { int nr, i; for(nr = 0; str.s[nr] != '\0'; nr++); s = new char[nr+1]; for(i = 0; i < nr; i++) s[i] = str.s[i]; s[nr] = '\0'; } Sir::~Sir() { delete[] s; } int Sir::Len() const { int nr; for(nr = 0; s[nr] != '\0'; nr++); return nr; } void Sir::Set(char* str) { delete[] s; int i; int nr; for(nr = 0; str[nr] != '\0'; nr++); s = new char[nr + 1]; for(int i = 0; i <= nr; i++) s[i] = str[i]; } bool Sir::operator ==(const Sir& sir) { if(Len() != sir.Len()) return 0; else { int n = Len(); for(int i = 0; i < n; i++) if(s[i] != sir.s[i]) return 0; } return 1; } Sir& Sir::operator +(const Sir& str) { int n1 = Len(); int n2 = str.Len(); for(int i = n1 ; i <= n1 + n2; i++) s[i] = str.s[i-n1]; return *this; } char Sir::operator [](int i) { if(i < Len()) return s[i]; } bool Sir::operator >(const Sir& str) { int n1 = Len(); int n2 = str.Len(); int n; if (n1 < n2) n = n1; else n = n2; for(int i = 0 ;i < n; i++) if(s[i] < str.s[i]) return 0; else if(s[i] > str.s[i]) return 1; //daca primele n cractere ale celor 2 string-uri sunt egale, atunci string-ul mai mare este cel cu lungimea mai mare if (n1 != n2) if(n == n1) return 0; else return 1; else return 0; } bool Sir::operator <(const Sir& str) { int n1 = Len(); int n2 = str.Len(); int n; if (n1 < n2) n = n1; else n = n2; for(int i = 0 ;i < n; i++) if(s[i] > str.s[i]) return 0; else if(s[i] < str.s[i]) return 1; //daca primele n cractere ale celor 2 string-uri sunt egale, atunci string-ul mai mic este cel cu lungimea mai mica if (n1 != n2) if(n == n1) return 1; else return 0; else return 0; } Sir& Sir::operator=(const Sir& str) { if(&str != this) { delete[] this->s; this->s = new char[str.Len()]; this->Set(str.s); } return *this; } ostream& operator<<(ostream& out, const Sir& str) { out << str.s; return out; } istream& operator>>(istream& in, Sir& str) { in>>str.s; return in; }
b80807145417010050f76fd09b086c4ec355ad83
8c0ce0f8a28e2a738bf6248e010fb9e9be55ad01
/PAT-Test/advanced/1017.cpp
0da8188b44d08b47ad32f971dbf5971e28b81e86
[ "MIT" ]
permissive
niuyi1017/algorithm-demos
ff0295a21e22454c8efe43e95fba84c1fd27f33e
298ef237a13e3f80a03f7780a3cbd52fb1cdac09
refs/heads/master
2020-03-29T21:48:37.048323
2019-09-08T11:34:23
2019-09-08T11:34:23
150,388,748
0
0
null
null
null
null
UTF-8
C++
false
false
1,268
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct node { int come, time; } tempCustomer; bool cmpl(node a, node b) { return a.come < b.come; } int main() { int n, k; cin >> n >> k; vector<node> customs; for (int i = 0; i < n; i++) { int hh, mm, ss, time; scanf("%d:%d:%d %d", &hh,&mm,&ss,&time); int cometime = hh * 3600 + mm * 60 + ss; if (cometime > 61200) { continue; } tempCustomer = {cometime, time * 60}; customs.push_back(tempCustomer); } sort(customs.begin(), customs.end(), cmpl); vector<int> windows(k, 28800); double result = 0.0; for (int i = 0; i < customs.size(); i++) { int tempIndex = 0, minFinish = windows[0]; for (int j = 1; j < k; j++) { if (minFinish > windows[j]) { minFinish = windows[j]; tempIndex = j; } } if (windows[tempIndex] <= customs[i].come) { windows[tempIndex] = customs[i].come + customs[i].time; } else { result += (windows[tempIndex] - customs[i].come); windows[tempIndex] += customs[i].time; } } if (customs.size() == 0) { printf("0.0"); } else { printf("%.1f", result / 60.0 / customs.size()); } return 0; }
4036f0254dae773e6da79d3cdb22ada2d2421243
027ba1e389d45e253dce892220555d6f9826f0cd
/packages/ipnoise-router/router-rc/src/objects/client/handlerTelnet/command/clientHandlerTelnetCommandGetContactList.h
1c5f0b6f2d29ea61d6e296b6e0ed6b183075f11d
[]
no_license
m0r1k/IPNoise
1f371ed6a7cd6ba5637edbbe8718190d7f514827
dbab828d48aa1ab626fd528e71b1c28e3702be09
refs/heads/master
2021-01-02T23:09:51.193762
2018-02-04T11:23:27
2018-02-04T11:23:27
99,478,087
1
4
null
null
null
null
UTF-8
C++
false
false
742
h
using namespace std; class ClientHandlerTelnetCommandGetContactList; #ifndef CLIENT_HANDLER_TELNET_COMMAND_GETCONTACTLIST_H #define CLIENT_HANDLER_TELNET_COMMAND_GETCONTACTLIST_H #include "objects/client/handlerTelnet/clientHandlerTelnetCommandAbstract.h" #include "objects/client/handlerTelnet/clientHandlerTelnetObject.h" class ClientHandlerTelnetCommandGetContactList : public ClientHandlerTelnetCommand { public: ClientHandlerTelnetCommandGetContactList( ClientHandlerTelnetObject *handler ); ~ClientHandlerTelnetCommandGetContactList(); const char *getName(); int run(int argc, char* const* argv); private: ClientHandlerTelnetObject *_handler; }; #endif
8fd37890d15b483ecb7af75560707283a6e8ccc8
412004775bc7b039b49c271da524768961dc2bd5
/Div2_B/Airport.cpp
0a111946ca68663ed3a04ecbef06f511cf122a40
[]
no_license
LUTLJS/CodeForces
6ee1f080dbbe9c733d2453f30a5eeaaa605b7cb2
ef74dc71a37f37356baa81bceb25899a83440b22
refs/heads/main
2023-04-22T17:56:48.782431
2021-05-10T07:49:42
2021-05-10T07:49:42
328,949,731
1
0
null
null
null
null
UTF-8
C++
false
false
816
cpp
#include <bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(0);cin.tie(0); int n,m;cin>>n>>m; int nn=n; int a[m],b[m]; for(int i=0;i<m;i++){int e;cin>>e;a[i]=e;b[i]=e;} sort(a,a+m,greater<int>()); sort(b,b+m,greater<int>()); int maxMoney=0; while(true){ int countMax=1,max=a[0]; a[0]--; for(int i=1;i<m;i++){ if(max==a[i]){countMax++;a[i]--;} else break; } if(n<=countMax){ maxMoney+=n*max; break; }else{ maxMoney+=countMax*max; n-=countMax; } } cout<<maxMoney<<" "; int minMoney=0; while(nn--) for(int i=m-1;i>=0;i--) if(b[i]!=0){minMoney+=b[i]--;break;} cout<<minMoney; return 0; }
f62398e008adf22553e576bc8a2ff6771aa7fc4c
4be23cbe9ee3d084360c5c2197de5cc7b64ef393
/DP/Miscellaneous/samSubstr.cpp
db3ba0a7afe40d0638ce7fc5f94d3cbad8291c9b
[]
no_license
Coderangshu/DP-Recursion
af539dcf850094e6d2055452f782a1ff44102ec8
08284609c59f2845dcf64b06e87b0103bb9075b0
refs/heads/master
2023-06-08T04:06:58.805759
2021-06-29T06:48:59
2021-06-29T06:48:59
362,504,755
0
0
null
null
null
null
UTF-8
C++
false
false
659
cpp
// Question link // https://www.hackerrank.com/challenges/sam-and-substrings/problem #include <bits/stdc++.h> #define llint long long int #define MOD 1000000007 using namespace std; llint memo[200001]; llint recursion(string s,llint ans){ llint n = stoi(s); if(memo[n]!=-1) return 0; if(s.length()==1){ memo[n] = n; return (ans+n)%MOD; } else{ memo[n] = n; return (ans+n+recursion(s.substr(0,s.length()-1),ans)+recursion(s.substr(1,s.length()),ans)%MOD); } } int main(){ ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); string s; cin>>s; memset(memo,-1,sizeof(memo)); llint ans = recursion(s,0); cout<<ans<<endl; return 0; }
c8f06a067819aa49c61a0d6789f49560bd5a284d
b6bfc9dc312ebc833b5eda2d8a4702dde090eff3
/modules/prediction/evaluator/vehicle/jointly_prediction_planning_evaluator.cc
d0b614cc1a0026fc8eb6786f88c52d3199b28754
[ "Apache-2.0" ]
permissive
ZZG5220/apollo
fb93c36fda9864338252f97e37243138bb7c949c
77de0aace2533db7d16c6ea8b995ca8bb8e3229d
refs/heads/master
2023-07-11T11:59:24.670534
2021-08-09T05:59:41
2021-08-09T05:59:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,171
cc
/****************************************************************************** * Copyright 2021 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/prediction/evaluator/vehicle/jointly_prediction_planning_evaluator.h" #include <limits> #include <omp.h> #include "Eigen/Dense" #include "cyber/common/file.h" #include "modules/common/math/linear_interpolation.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/prediction/common/prediction_map.h" #include "modules/prediction/common/prediction_system_gflags.h" #include "modules/prediction/common/prediction_util.h" #include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h" namespace apollo { namespace prediction { using apollo::common::TrajectoryPoint; using apollo::common::math::Vec2d; using apollo::common::math::InterpolateUsingLinearApproximation; using apollo::prediction::VectorNet; JointlyPredictionPlanningEvaluator::JointlyPredictionPlanningEvaluator() : device_(torch::kCPU) { evaluator_type_ = ObstacleConf::JOINTLY_PREDICTION_PLANNING_EVALUATOR; LoadModel(); } void JointlyPredictionPlanningEvaluator::Clear() {} bool JointlyPredictionPlanningEvaluator::Evaluate(Obstacle* obstacle_ptr, ObstaclesContainer* obstacles_container) { const ADCTrajectoryContainer* adc_trajectory_container; Evaluate(adc_trajectory_container, obstacle_ptr, obstacles_container); return true; } bool JointlyPredictionPlanningEvaluator::Evaluate( const ADCTrajectoryContainer* adc_trajectory_container, Obstacle* obstacle_ptr, ObstaclesContainer* obstacles_container) { omp_set_num_threads(1); obstacle_ptr->SetEvaluatorType(evaluator_type_); Clear(); CHECK_NOTNULL(obstacle_ptr); int id = obstacle_ptr->id(); if (!obstacle_ptr->latest_feature().IsInitialized()) { AERROR << "Obstacle [" << id << "] has no latest feature."; return false; } Feature* latest_feature_ptr = obstacle_ptr->mutable_latest_feature(); CHECK_NOTNULL(latest_feature_ptr); if (adc_trajectory_container == nullptr) { AERROR << "Null adc trajectory container"; return false; } // obs data vector // Extract features of pos_history std::vector<std::pair<double, double>> target_pos_history(20, {0.0, 0.0}); std::vector<std::pair<double, double>> all_obs_length; std::vector<std::vector<std::pair<double, double>>> all_obs_pos_history; // Process mask // process v_mask for obs torch::Tensor vector_mask = torch::zeros({450, 50}); if (!ExtractObstaclesHistory(obstacle_ptr, obstacles_container, &target_pos_history, &all_obs_length, &all_obs_pos_history, &vector_mask)) { ADEBUG << "Obstacle [" << id << "] failed to extract obstacle history"; return false; } // Query the map data vector FeatureVector map_feature; PidVector map_p_id; double pos_x = latest_feature_ptr->position().x(); double pos_y = latest_feature_ptr->position().y(); common::PointENU center_point; center_point.set_x(pos_x); center_point.set_y(pos_y); double heading = latest_feature_ptr->velocity_heading(); auto start_time_query = std::chrono::system_clock::now(); if (!vector_net_.query(center_point, heading, &map_feature, &map_p_id)) { return false; } auto end_time_query = std::chrono::system_clock::now(); std::chrono::duration<double> diff_query = end_time_query - start_time_query; ADEBUG << "vectors query used time: " << diff_query.count() * 1000 << " ms."; // Process all obs pos_history & obs pid auto start_time_data_prep = std::chrono::system_clock::now(); int obs_num = obstacles_container->curr_frame_considered_obstacle_ids().size(); torch::Tensor target_obstacle_pos = torch::zeros({20, 2}); torch::Tensor target_obstacle_pos_step = torch::zeros({20, 2}); for (int j = 0; j < 20; ++j) { target_obstacle_pos[19 - j][0] = target_pos_history[j].first; target_obstacle_pos[19 - j][1] = target_pos_history[j].second; if (j == 19 || (j > 0 && target_pos_history[j + 1].first == 0.0)) { break; } target_obstacle_pos_step[19 - j][0] = target_pos_history[j].first - target_pos_history[j + 1].first; target_obstacle_pos_step[19 - j][1] = target_pos_history[j].second - target_pos_history[j + 1].second; } torch::Tensor all_obstacle_pos = torch::zeros({obs_num, 20, 2}); torch::Tensor all_obs_p_id = torch::zeros({obs_num, 2}); for (int i = 0; i < obs_num; ++i) { std::vector<double> obs_p_id{std::numeric_limits<float>::max(), std::numeric_limits<float>::max()}; for (int j = 0; j < 20; ++j) { // Process obs pid if (obs_p_id[0] > all_obs_pos_history[i][j].first) { obs_p_id[0] = all_obs_pos_history[i][j].first; } if (obs_p_id[1] > all_obs_pos_history[i][j].second) { obs_p_id[1] = all_obs_pos_history[i][j].second; } // Process obs pos history all_obstacle_pos[i][19 - j][0] = all_obs_pos_history[i][j].first; all_obstacle_pos[i][19 - j][1] = all_obs_pos_history[i][j].second; } all_obs_p_id[i][0] = obs_p_id[0]; all_obs_p_id[i][1] = obs_p_id[1]; } // process map data & map p id & v_mask for map polyline int map_polyline_num = map_feature.size(); int data_length = ((obs_num + map_polyline_num) < 450) ? (obs_num + map_polyline_num) : 450; for (int i = 0; i < map_polyline_num && obs_num + i < 450; ++i) { size_t one_polyline_vector_size = map_feature[i].size(); if (one_polyline_vector_size < 50) { vector_mask.index_put_({obs_num + i, torch::indexing::Slice(one_polyline_vector_size, torch::indexing::None)}, 1); } } torch::Tensor map_data = torch::zeros({map_polyline_num, 50, 9}); torch::Tensor all_map_p_id = torch::zeros({map_polyline_num, 2}); auto opts = torch::TensorOptions().dtype(torch::kDouble); for (int i = 0; i < map_polyline_num && i + obs_num < 450; ++i) { all_map_p_id[i][0] = map_p_id[i][0]; all_map_p_id[i][1] = map_p_id[i][1]; int one_polyline_vector_size = map_feature[i].size(); for (int j = 0; j < one_polyline_vector_size && j < 50; ++j) { map_data.index_put_({i, j}, torch::from_blob(map_feature[i][j].data(), {9}, opts)); } } map_data = map_data.toType(at::kFloat); // process p mask torch::Tensor polyline_mask = torch::zeros({450}); if (data_length < 450) { polyline_mask.index_put_( {torch::indexing::Slice(data_length, torch::indexing::None)}, 1); } // Extend obs data to specific dimension torch::Tensor obs_pos_data = torch::cat( {all_obstacle_pos.index( {torch::indexing::Slice(), torch::indexing::Slice(torch::indexing::None, -1), torch::indexing::Slice()}), all_obstacle_pos.index({torch::indexing::Slice(), torch::indexing::Slice(1, torch::indexing::None), torch::indexing::Slice()})}, 2); // Add obs length torch::Tensor obs_length_tmp = torch::zeros({obs_num, 2}); for (int i = 0; i < obs_num; ++i) { obs_length_tmp[i][0] = all_obs_length[i].first; obs_length_tmp[i][1] = all_obs_length[i].second; } torch::Tensor obs_length = obs_length_tmp.unsqueeze(1).repeat({1, 19, 1}); // Add obs attribute torch::Tensor obs_attr_agent = torch::tensor({11.0, 4.0}).unsqueeze(0).unsqueeze(0).repeat({1, 19, 1}); torch::Tensor obs_attr_other = torch::tensor({10.0, 4.0}).unsqueeze(0).unsqueeze(0).repeat( {(obs_num - 1), 19, 1}); torch::Tensor obs_attr = torch::cat({obs_attr_agent, obs_attr_other}, 0); // ADD obs id // add 500 to avoid same id as in map_info torch::Tensor obs_id = torch::arange(500, obs_num + 500).unsqueeze(1).repeat( {1, 19}).unsqueeze(2); // Process obs data torch::Tensor obs_data_with_len = torch::cat({obs_pos_data, obs_length}, 2); torch::Tensor obs_data_with_attr = torch::cat({obs_data_with_len, obs_attr}, 2); torch::Tensor obs_data_with_id = torch::cat({obs_data_with_attr, obs_id}, 2); torch::Tensor obs_data_final = torch::cat({torch::zeros({obs_num, (50 - 19), 9}), obs_data_with_id}, 1); // Extend data & pid to specific demension torch::Tensor data_tmp = torch::cat({obs_data_final, map_data}, 0); torch::Tensor p_id_tmp = torch::cat({all_obs_p_id, all_map_p_id}, 0); torch::Tensor vector_data; torch::Tensor polyline_id; if (data_length < 450) { torch::Tensor data_zeros = torch::zeros({(450 - data_length), 50, 9}); torch::Tensor p_id_zeros = torch::zeros({(450 - data_length), 2}); vector_data = torch::cat({data_tmp, data_zeros}, 0); polyline_id = torch::cat({p_id_tmp, p_id_zeros}, 0); } else { vector_data = data_tmp; polyline_id = p_id_tmp; } // Empty rand mask as placeholder auto rand_mask = torch::zeros({450}).toType(at::kBool); // Change mask type to bool auto bool_vector_mask = vector_mask.toType(at::kBool); auto bool_polyline_mask = polyline_mask.toType(at::kBool); // Process ADC trajectory & Extract features of ADC trajectory std::vector<std::pair<double, double>> adc_traj_curr_pos(30, {0.0, 0.0}); torch::Tensor adc_trajectory = torch::zeros({1, 30, 6}); const auto& adc_traj = adc_trajectory_container->adc_trajectory(); size_t adc_traj_points_num = adc_traj.trajectory_point().size(); std::vector<TrajectoryPoint> adc_traj_points; // ADC trajectory info as model input needs to match with // the predicted obstalce's timestamp. double time_interval = obstacle_ptr->latest_feature().timestamp() - adc_traj.header().timestamp_sec(); for (size_t i = 0; i < adc_traj_points_num - 1; ++i) { double delta_time = time_interval - adc_traj.trajectory_point(0).relative_time(); adc_traj_points.emplace_back( InterpolateUsingLinearApproximation( adc_traj.trajectory_point(i), adc_traj.trajectory_point(i + 1), delta_time)); } if (!ExtractADCTrajectory(&adc_traj_points, obstacle_ptr, &adc_traj_curr_pos)) { ADEBUG << "Failed to extract adc trajectory"; return false; } size_t traj_points_num = adc_traj_points.size(); for (size_t j = 0; j < 30; ++j) { if (j > traj_points_num - 1) { adc_trajectory[0][j][0] = adc_traj_curr_pos[traj_points_num - 1].first; adc_trajectory[0][j][1] = adc_traj_curr_pos[traj_points_num - 1].second; adc_trajectory[0][j][2] = adc_traj_points[traj_points_num - 1].path_point().theta(); adc_trajectory[0][j][3] = adc_traj_points[traj_points_num - 1].v(); adc_trajectory[0][j][4] = adc_traj_points[traj_points_num - 1].a(); adc_trajectory[0][j][5] = adc_traj_points[traj_points_num - 1].path_point().kappa(); } else { adc_trajectory[0][j][0] = adc_traj_curr_pos[j].first; adc_trajectory[0][j][1] = adc_traj_curr_pos[j].second; adc_trajectory[0][j][2] = adc_traj_points[j].path_point().theta(); adc_trajectory[0][j][3] = adc_traj_points[j].v(); adc_trajectory[0][j][4] = adc_traj_points[j].a(); adc_trajectory[0][j][5] = adc_traj_points[j].path_point().kappa(); } } // Build input features for torch std::vector<torch::jit::IValue> torch_inputs; auto X_value = c10::ivalue::Tuple::create( {std::move(target_obstacle_pos.unsqueeze(0).to(device_)), std::move(target_obstacle_pos_step.unsqueeze(0).to(device_)), std::move(vector_data.unsqueeze(0).to(device_)), std::move(bool_vector_mask.unsqueeze(0).to(device_)), std::move(bool_polyline_mask.unsqueeze(0).to(device_)), std::move(rand_mask.unsqueeze(0).to(device_)), std::move(polyline_id.unsqueeze(0).to(device_))}); torch_inputs.push_back(c10::ivalue::Tuple::create( {X_value, std::move(adc_trajectory.to(device_))})); auto end_time_data_prep = std::chrono::system_clock::now(); std::chrono::duration<double> diff_data_prep = end_time_data_prep - start_time_data_prep; ADEBUG << "vectornet input tensor prepration used time: " << diff_data_prep.count() * 1000 << " ms."; // Compute pred_traj auto start_time_inference = std::chrono::system_clock::now(); at::Tensor torch_output_tensor = torch_default_output_tensor_; torch_output_tensor = torch_vehicle_model_.forward(torch_inputs).toTensor().to(torch::kCPU); auto end_time_inference = std::chrono::system_clock::now(); std::chrono::duration<double> diff_inference = end_time_inference - start_time_inference; ADEBUG << "vectornet-interaction inference used time: " << diff_inference.count() * 1000 << " ms."; // Get the trajectory auto torch_output = torch_output_tensor.accessor<float, 3>(); Trajectory* trajectory = latest_feature_ptr->add_predicted_trajectory(); trajectory->set_probability(1.0); for (int i = 0; i < 30; ++i) { double prev_x = pos_x; double prev_y = pos_y; if (i > 0) { const auto& last_point = trajectory->trajectory_point(i - 1).path_point(); prev_x = last_point.x(); prev_y = last_point.y(); } TrajectoryPoint* point = trajectory->add_trajectory_point(); double dx = static_cast<double>(torch_output[0][i][0]); double dy = static_cast<double>(torch_output[0][i][1]); double heading = latest_feature_ptr->velocity_heading(); Vec2d offset(dx, dy); Vec2d rotated_offset = offset.rotate(heading); double point_x = pos_x + rotated_offset.x(); double point_y = pos_y + rotated_offset.y(); point->mutable_path_point()->set_x(point_x); point->mutable_path_point()->set_y(point_y); if (i < 10) { // use origin heading for the first second point->mutable_path_point()->set_theta( latest_feature_ptr->velocity_heading()); } else { point->mutable_path_point()->set_theta( std::atan2(trajectory->trajectory_point(i).path_point().y() - trajectory->trajectory_point(i - 1).path_point().y(), trajectory->trajectory_point(i).path_point().x() - trajectory->trajectory_point(i - 1).path_point().x())); } point->set_relative_time(static_cast<double>(i) * FLAGS_prediction_trajectory_time_resolution); if (i == 0) { point->set_v(latest_feature_ptr->speed()); } else { double diff_x = point_x - prev_x; double diff_y = point_y - prev_y; point->set_v(std::hypot(diff_x, diff_y) / FLAGS_prediction_trajectory_time_resolution); } } return true; } bool JointlyPredictionPlanningEvaluator::ExtractObstaclesHistory( Obstacle* obstacle_ptr, ObstaclesContainer* obstacles_container, std::vector<std::pair<double, double>>* target_pos_history, std::vector<std::pair<double, double>>* all_obs_length, std::vector<std::vector<std::pair<double, double>>>* all_obs_pos_history, torch::Tensor* vector_mask) { const Feature& obs_curr_feature = obstacle_ptr->latest_feature(); double obs_curr_heading = obs_curr_feature.velocity_heading(); std::pair<double, double> obs_curr_pos = std::make_pair( obs_curr_feature.position().x(), obs_curr_feature.position().y()); // Extract target obstacle history for (std::size_t i = 0; i < obstacle_ptr->history_size() && i < 20; ++i) { const Feature& target_feature = obstacle_ptr->feature(i); if (!target_feature.IsInitialized()) { break; } target_pos_history->at(i) = WorldCoordToObjCoord(std::make_pair(target_feature.position().x(), target_feature.position().y()), obs_curr_pos, obs_curr_heading); } all_obs_length->emplace_back( std::make_pair(obs_curr_feature.length(), obs_curr_feature.width())); all_obs_pos_history->emplace_back(*target_pos_history); // Extract other obstacles & convert pos to traget obstacle relative coord std::vector<std::pair<double, double>> pos_history(20, {0.0, 0.0}); for (int id : obstacles_container->curr_frame_considered_obstacle_ids()) { Obstacle* obstacle = obstacles_container->GetObstacle(id); int target_id = obstacle_ptr->id(); if (id == target_id) { continue; } const Feature& other_obs_curr_feature = obstacle->latest_feature(); all_obs_length->emplace_back(std::make_pair( other_obs_curr_feature.length(), other_obs_curr_feature.width())); size_t obs_his_size = obstacle->history_size(); obs_his_size = obs_his_size <= 20 ? obs_his_size : 20; int cur_idx = all_obs_pos_history->size(); if (obs_his_size > 1) { vector_mask->index_put_({cur_idx, torch::indexing::Slice(torch::indexing::None, -(obs_his_size - 1))}, 1); } else { vector_mask->index_put_({cur_idx, torch::indexing::Slice(torch::indexing::None, -1)}, 1); } for (size_t i = 0; i < obs_his_size; ++i) { const Feature& feature = obstacle->feature(i); if (!feature.IsInitialized()) { break; } pos_history[i] = WorldCoordToObjCoord( std::make_pair(feature.position().x(), feature.position().y()), obs_curr_pos, obs_curr_heading); } all_obs_pos_history->emplace_back(pos_history); } return true; } bool JointlyPredictionPlanningEvaluator::ExtractADCTrajectory( std::vector<TrajectoryPoint>* trajectory_points, Obstacle* obstacle_ptr, std::vector<std::pair<double, double>>* adc_traj_curr_pos) { adc_traj_curr_pos->resize(30, {0.0, 0.0}); const Feature& obs_curr_feature = obstacle_ptr->latest_feature(); double obs_curr_heading = obs_curr_feature.velocity_heading(); std::pair<double, double> obs_curr_pos = std::make_pair( obs_curr_feature.position().x(), obs_curr_feature.position().y()); size_t adc_traj_points_num = trajectory_points->size(); for (size_t i = 0; i < 30; ++i) { if (i > adc_traj_points_num -1) { adc_traj_curr_pos->at(i) = adc_traj_curr_pos->at(adc_traj_points_num - 1); } else { adc_traj_curr_pos->at(i) = WorldCoordToObjCoord( std::make_pair(trajectory_points->at(i).path_point().x(), trajectory_points->at(i).path_point().y()), obs_curr_pos, obs_curr_heading); } } return true; } void JointlyPredictionPlanningEvaluator::LoadModel() { if (FLAGS_use_cuda && torch::cuda::is_available()) { ADEBUG << "CUDA is available"; device_ = torch::Device(torch::kCUDA); torch_vehicle_model_ = torch::jit::load(FLAGS_torch_vehicle_jointly_model_file, device_); } else { torch_vehicle_model_ = torch::jit::load(FLAGS_torch_vehicle_jointly_model_cpu_file, device_); } torch::set_num_threads(1); // Fake intput for the first frame torch::Tensor target_obstacle_pos = torch::randn({1, 20, 2}); torch::Tensor target_obstacle_pos_step = torch::randn({1, 20, 2}); torch::Tensor vector_data = torch::randn({1, 450, 50, 9}); torch::Tensor vector_mask = torch::randn({1, 450, 50}) > 0.9; torch::Tensor polyline_mask = torch::randn({1, 450}) > 0.9; torch::Tensor rand_mask = torch::zeros({1, 450}); torch::Tensor polyline_id = torch::randn({1, 450, 2}); torch::Tensor adc_trajectory = torch::zeros({1, 30, 6}); std::vector<torch::jit::IValue> torch_inputs; auto X_value = c10::ivalue::Tuple::create( {std::move(target_obstacle_pos.to(device_)), std::move(target_obstacle_pos_step.to(device_)), std::move(vector_data.to(device_)), std::move(vector_mask.to(device_)), std::move(polyline_mask.to(device_)), std::move(rand_mask.to(device_)), std::move(polyline_id.to(device_))}); torch_inputs.push_back(c10::ivalue::Tuple::create( {X_value, std::move(adc_trajectory.to(device_))})); // Run inference twice to avoid very slow first inference later torch_default_output_tensor_ = torch_vehicle_model_.forward(torch_inputs).toTensor().to(torch::kCPU); torch_default_output_tensor_ = torch_vehicle_model_.forward(torch_inputs).toTensor().to(torch::kCPU); } } // namespace prediction } // namespace apollo
140be8a93b05128eea4c6d3237f02a0d06e2a9d1
211ad6cdb983d71eedf79877889b6fb5d643dd24
/CA1-2018-s4901441/plane.h
cf96c3ea501131cbb2b8fc845e33ee4e70df8569
[]
no_license
s4901441/Physics-Engine-by_XiaoouNie
3d2221856f1287b6f63dc0f03afcbb629adef5eb
8e3e969d4f9e49881db7d3973d1a0a9ee92370e8
refs/heads/master
2022-05-27T21:19:59.828472
2020-05-01T12:45:39
2020-05-01T12:45:39
260,423,091
1
0
null
null
null
null
UTF-8
C++
false
false
657
h
#ifndef PLANE_H #define PLANE_H #include "Particles.h" #include <vector> #include <ngl/AbstractVAO.h> #include <memory> class plane : public Particles { public: plane(ngl::Vec3 _P, ngl::Vec3 _v, ngl::Vec3 _f, float _mass, const std::string &_shaderName, Emitter *_parent,ngl::Colour _c); virtual ~plane(); void draw() const; void update(); virtual inline ParticleType getType()const {return m_type;} virtual void setCollider(); private: const static ParticleType m_type = ParticleType::PLANE; ngl::Vec3 m_normal; float m_distance; std::vector<ngl::Vec3> verts; std::unique_ptr<ngl::AbstractVAO> m_vao; }; #endif // PLANE_H
0f9bbb1b4b77c4ff2d3a709fc259be2fdf3b9e22
f03d25a1bc27880f4763166e7d60f1415e9c2738
/condition_variable().cpp
3c6f79993b31896f7019a2d8e1bc3d2e622663ed
[]
no_license
bashar404/Threads
dc2644af98cf14def91de900fdc6ffc4e2291e5a
1257038a54d1870fdaf8b05ef012200f789c65c9
refs/heads/master
2023-02-18T01:12:48.125652
2020-12-29T00:54:04
2020-12-29T00:54:04
290,917,926
0
0
null
null
null
null
UTF-8
C++
false
false
1,759
cpp
// A condition variable is an object able to block the calling thread until notified to resume. // It uses a unique_lock (over a mutex) to lock the thread when one of its wait functions is called. The thread remains blocked until woken up by another thread that calls a notification function on the same condition_variable object. // Member functions: wait, wait_for, wait_until, notify_one, notify_all /* TOPIC: Condition Variable In C++ Threading NOTES: 1. Condition variables allow us to synchronize threads via notifications. a. notify_one(); b. notify_all(); 2. You need mutex to use condition variable 3. Condition variable is used to synchronize two or more threads. 4. Best use case of condition variable is Producer/Consumer problem. 5. Condition variables can be used for two purposes: a. Notify other threads b. Wait for some condition*/ #ifdef _WIN32 #include <Windows.h> #else #include <unistd.h> #endif> #include <cstdlib> #include<iostream> #include<thread> #include<mutex> #include<condition_variable> using namespace std; int balance=0; mutex m; condition_variable cv; void addMoney(int amount) { unique_lock<mutex>lock(m); balance=balance+amount; cout<<"Current amount is "<<balance<<endl; cv.notify_one(); } void withdraw (int amount) { unique_lock<mutex>lock(m); //must be same mutex cv.wait( lock, [] {return (balance!=0? true : false); } ); if(balance>amount) { int updated_amount=balance-amount; cout<<"Amount deduct: "<<amount<<","<<"New balance: "<<updated_amount<<endl; } else cout<<"You dont have sufficient amount"; } int main() { thread t1(withdraw,500); sleep(5); thread t2(addMoney,600); t1.join(); t2.join(); }
3c6e55d884e31ea325353a88597771b35ca816cb
fc84128b2d456fa241579c52d2af91582e4076f9
/20_app/Vision/VisionSourceDll/include/visionresourcedll.h
8ba62618d05e3c8a28ab6f5f72c088544bc11ae5
[]
no_license
RealCrond/Herman
ccaf5d436799fe5263da8cd9e21c4ab5d8c0445e
0559eee19cecfe47c14405892014cf52121cee02
refs/heads/master
2022-11-13T00:04:36.560217
2020-07-02T01:26:25
2020-07-02T01:26:25
255,483,055
1
0
null
null
null
null
UTF-8
C++
false
false
598
h
#pragma once #include <Windows.h> #include <tchar.h> //IDR_ZIPRES #include "resource.h" #ifdef VISIONSOURCEDLL_EXPORTS #define VISIONRES_API __declspec(dllexport) #else #define VISIONRES_API __declspec(dllimport) #endif // VISIONSOURCEDLL_EXPORTS class VISIONRES_API CVisionResHandle { public: CVisionResHandle() { m_hInstance = ::LoadLibraryEx(_T("VisionSourceDll.dll"), NULL, DONT_RESOLVE_DLL_REFERENCES); }; virtual ~CVisionResHandle() { ::FreeLibrary(m_hInstance); m_hInstance = NULL; }; HINSTANCE GetHandle() { return m_hInstance; }; private: HINSTANCE m_hInstance; };
bec2c116ba05bdc00a4bfce6004a9a07d1b142fc
b45d0da3f87dab3ad024642d918f0427c513490a
/MatrixGame.cpp
8f3ca904b020dc65390f740d5248ae15c0665a02
[]
no_license
Nikhil569/Codeforces
604c69ca738eef4c1a958bf7988c34dbd224f213
17c3ca67e1ca3f39e0858bdd675bf1557095ff99
refs/heads/master
2022-11-17T19:24:25.527564
2020-07-24T22:44:21
2020-07-24T22:44:21
256,477,176
0
0
null
null
null
null
UTF-8
C++
false
false
631
cpp
#include <bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { int t; cin>>t; for(int i=0;i<t;i++){ int n,m; cin>>n>>m; int a[n][m]; int count_row = 0; int count_col = 0; for(int j=0;j<n;j++){ int sum=0; for(int k=0;k<m;k++){ cin>>a[j][k]; sum = sum + a[j][k]; } if(sum==0) count_row++; } for(int j=0;j<m;j++){ int sum=0; for(int k=0;k<n;k++){ sum = sum + a[k][j]; } if(sum==0) count_col++; } int min; min = (count_col<=count_row) ? count_col:count_row; if(min%2==0) cout<<"Vivek"<<endl; else cout<<"Ashish"<<endl; } return 0; }