blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
7ac8c763834c5ce3b061c4dd6c45bd8ec835429d
9f48878caa37ac5f2ccf938fc476efa47c89c644
/src/Domain/CoordinateMaps/TimeDependent/ShapeMapTransitionFunctions/SphereTransition.hpp
f61567c5a8fd5c52e7d8ebee6a8e938342bfbaf2
[ "MIT" ]
permissive
sxs-collaboration/spectre
34f7733ab4c75dbca2f432028145fed110c9ef24
96f573cf158201f712da2bfb3378edf497a35a0d
refs/heads/develop
2023-08-19T11:18:18.465609
2023-08-19T04:24:25
2023-08-19T04:24:25
87,570,510
149
190
NOASSERTION
2023-09-14T20:10:35
2017-04-07T17:28:20
C++
UTF-8
C++
false
false
2,578
hpp
SphereTransition.hpp
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <array> #include <optional> #include <pup.h> #include "DataStructures/DataVector.hpp" #include "Domain/CoordinateMaps/TimeDependent/ShapeMapTransitionFunctions/ShapeMapTransitionFunction.hpp" namespace domain::CoordinateMaps::ShapeMapTransitionFunctions { /*! * \ingroup CoordMapsTimeDependentGroup * \brief A transition function that falls off as \f$f(r) = (ar + b) / r\f$. The * coefficients \f$a\f$ and \f$b\f$ are chosen so that the map falls off * linearly from 1 at `r_min` to 0 at `r_max`. */ class SphereTransition final : public ShapeMapTransitionFunction { public: explicit SphereTransition() = default; SphereTransition(double r_min, double r_max); double operator()(const std::array<double, 3>& source_coords) const override; DataVector operator()( const std::array<DataVector, 3>& source_coords) const override; std::optional<double> original_radius_over_radius( const std::array<double, 3>& target_coords, double distorted_radius) const override; double map_over_radius( const std::array<double, 3>& source_coords) const override; DataVector map_over_radius( const std::array<DataVector, 3>& source_coords) const override; std::array<double, 3> gradient( const std::array<double, 3>& source_coords) const override; std::array<DataVector, 3> gradient( const std::array<DataVector, 3>& source_coords) const override; WRAPPED_PUPable_decl_template(SphereTransition); explicit SphereTransition(CkMigrateMessage* const msg); void pup(PUP::er& p) override; std::unique_ptr<ShapeMapTransitionFunction> get_clone() const override { return std::make_unique<SphereTransition>(*this); } bool operator==(const ShapeMapTransitionFunction& other) const override; bool operator!=(const ShapeMapTransitionFunction& other) const override; private: template <typename T> T call_impl(const std::array<T, 3>& source_coords) const; template <typename T> T map_over_radius_impl(const std::array<T, 3>& source_coords) const; template <typename T> std::array<T, 3> gradient_impl(const std::array<T, 3>& source_coords) const; // checks that the magnitudes are all between `r_min_` and `r_max_` template <typename T> void check_magnitudes(const T& mag) const; double r_min_{}; double r_max_{}; double a_{}; double b_{}; static constexpr double eps_ = std::numeric_limits<double>::epsilon() * 100; }; } // namespace domain::CoordinateMaps::ShapeMapTransitionFunctions
4079453b99d87f57d37edb32d3efad577781eeb3
3c1d35ffab53397d95e74f9878eb14f11cd62baf
/src/PipeRTSP/ServerPipeRTSP.cpp
c0bb110724d434ebe00fac6ea3eb9644a37a0a28
[ "MIT" ]
permissive
TUM-CAMP-NARVIS/nvenc_rtsp
cf4f3e49f25ccbda27e67776d6652b5c29887854
1168e253bf0bbf07b90e328e34d7408deabbd42a
refs/heads/master
2020-06-03T23:06:59.340012
2019-11-28T14:49:29
2019-11-28T14:49:29
191,769,023
6
3
null
null
null
null
UTF-8
C++
false
false
8,861
cpp
ServerPipeRTSP.cpp
#include "nvenc_rtsp_common.h" #include "nvenc_rtsp/ServerPipeRTSP.h" /* ********************************************************************************** # # # Copyright (c) 2019, # # Research group MITI # # Technical University of Munich # # # # All rights reserved. # # Kevin Yu - kevin.yu@tum.de # # # # Redistribution and use in source and binary forms, with or without # # modification, are restricted to the following conditions: # # # # * The software is permitted to be used internally only by the research group # # MITI and CAMPAR and any associated/collaborating groups and/or individuals. # # * The software is provided for your internal use only and you may # # not sell, rent, lease or sublicense the software to any other entity # # without specific prior written permission. # # You acknowledge that the software in source form remains a confidential # # trade secret of the research group MITI and therefore you agree not to # # attempt to reverse-engineer, decompile, disassemble, or otherwise develop # # source code for the software or knowingly allow others to do so. # # * Redistributions of source code must retain the above copyright notice, # # this list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # # this list of conditions and the following disclaimer in the documentation # # and/or other materials provided with the distribution. # # * Neither the name of the research group MITI nor the names of its # # contributors may be used to endorse or promote products derived from this # # software without specific prior written permission. # # # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # # *************************************************************************************/ using namespace std; using namespace nvenc_rtsp; std::mutex ServerPipeRTSP::m_coutMutex; ServerPipeRTSP::ServerPipeRTSP(std::string _ipAddress, int _port, NvPipe_Format _encFormat, NvPipe_Compression _compression, NvPipe_Codec _codec, float _bitrateMbps, int _targetFPS) : Encoder(_encFormat, _compression, _codec, _bitrateMbps, _targetFPS), m_ipAddress(_ipAddress), m_port(_port) { } ServerPipeRTSP::ServerPipeRTSP(std::string _ipAddress, int _port, NvPipe_Format _encFormat, NvPipe_Compression _compression, NvPipe_Codec _codec) : ServerPipeRTSP(_ipAddress, _port, _encFormat, _compression, _codec, 32, 90) { } ServerPipeRTSP::ServerPipeRTSP(std::string _ipAddress, int _port, NvPipe_Format _encFormat, NvPipe_Compression _compression) : ServerPipeRTSP(_ipAddress, _port, _encFormat, _compression, NVPIPE_H264, 32, 90) { } bool ServerPipeRTSP::init_Loop(int _width, int _height, int _bytesPerPixel) { if(!init_Encoder(_width, _height, _bytesPerPixel)) return false; // RTSP ############################################################ m_rtspThread = thread([&, _width, _height, _bytesPerPixel]() { int clients = 0; std::string ip = m_ipAddress; // xop::NetInterface::getLocalIPAddress(); std::string rtspUrl; std::shared_ptr<xop::EventLoop> eventLoop(new xop::EventLoop()); m_server = new xop::RtspServer(eventLoop.get(), ip, m_port); xop::MediaSession *session = xop::MediaSession::createNew("live"); rtspUrl = "rtsp://" + ip + ":" + std::to_string(m_port) + "/" + session->getRtspUrlSuffix(); session->addMediaSource(xop::channel_0, xop::H264Source::createNew()); session->setMediaDescribeSDPAddon("a=x-dimensions:" + std::to_string(_width) + "," + std::to_string(_height) + "," + std::to_string(_bytesPerPixel) + "\n"); session->setNotifyCallback([&clients, &rtspUrl](xop::MediaSessionId sessionId, uint32_t numClients) { clients = numClients; std::lock_guard<std::mutex> lock(ServerPipeRTSP::m_coutMutex); std::cout << "[" << rtspUrl << "]" << " Online: " << clients << std::endl; }); m_sessionId = m_server->addMediaSession(session); std::cout << "URL: " << rtspUrl << std::endl << std::endl; eventLoop->loop(); }); // END RTSP ######################################################## return true; } ByteObject ServerPipeRTSP::send_frame(cv::Mat mat, uint32_t timestamp) { if(!is_initiated()) init_Loop(mat.size().width, mat.size().height, mat.elemSize()); m_timer.reset(); cudaMemcpy(m_gpuDevice, mat.data, m_dataSize, cudaMemcpyHostToDevice); double uploadMs = m_timer.getElapsedMilliseconds(); m_timer.reset(); uint64_t size = NvPipe_Encode(m_encoder, m_gpuDevice, m_width * m_bytesPerPixel, m_compressedBuffer.data(), m_dataSize, m_width, m_height, m_forceIFrame); m_forceIFrame = true; double encodeMs = m_timer.getElapsedMilliseconds(); // RTSP ############################################################ m_timer.reset(); int tail = 0; while (tail < size) { int length; int head; get_NalPackage(m_compressedBuffer.data(), size, &head, &tail, &length); xop::AVFrame videoFrame = {0}; videoFrame.type = 0; videoFrame.size = length; videoFrame.timestamp = timestamp != 0? timestamp : xop::H264Source::getTimeStamp(); videoFrame.buffer = &m_compressedBuffer.data()[head]; m_server->pushFrame(m_sessionId, xop::channel_0, videoFrame); } double socketMs = m_timer.getElapsedMilliseconds(); // END RTSP ############################################################ #ifdef DISPPIPETIME std::cout << uploadMs << std::setw(11) << encodeMs << std::setw(11) << socketMs << std::endl; #endif ByteObject result = {m_compressedBuffer.data(), size}; return result; } ssize_t ServerPipeRTSP::startCodePosition(uchar* buffer, int maxSize, size_t offset) { assert(offset < maxSize); /* Simplified Boyer-Moore, inspired by gstreamer */ while (offset < maxSize - 2) { switch((int)buffer[offset + 2]) { case 1: { if ((int)buffer[offset] == 0 && (int)buffer[offset + 1] == 0 ) { return offset; } offset += 3; break; } case 0: offset++; break; default: offset += 3; } } return -1; } void ServerPipeRTSP::get_NalPackage(uchar* buffer, int maxSize, int *head, int *tail, int *length) { int start = startCodePosition(buffer, maxSize, *tail); int end = startCodePosition(buffer, maxSize, start + 1); if(end < 0) end = maxSize; int packageLength = end - start; *head = start; *tail = end; *length = packageLength; } void ServerPipeRTSP::cleanUp() { if(!is_initiated()) return; delete m_server; m_rtspThread.join(); Encoder::cleanUp(); }
c850bac9c1068f72c55d63853e1b08c6f1fb16de
e3070bc5a6b028c3ca017a9b7e5c2aef5312908b
/Countries/Countries/Countries/Project.cpp
c4a14e1232c71488b7f4dce3d07624303d899029
[]
no_license
RostikGameStudio/Countries
01ecc19d4917269282396a2970670365d46ec416
8dd3f2e05e9ebc0d06f8dd1fb37cbf279ab3d7b5
refs/heads/master
2020-03-22T14:38:33.017343
2018-07-09T19:06:49
2018-07-09T19:06:49
140,194,168
1
2
null
null
null
null
UTF-8
C++
false
false
30
cpp
Project.cpp
#include "Project.h"
7a8b8160cd5d5239277e539c6152be0e97f9618a
81b60b253cc48d28c3f7a58894216ef09682c4d6
/test/testboard.cpp
5128e12ae65dcf670b9f48b998599c894b2a4d6d
[]
no_license
underkround/yazatrix
c22aff78975c63b38bc0a20de76ad65a751076d5
73de2aac6877106f6544aa1b7be627a0314b7ea5
refs/heads/master
2016-09-08T01:27:20.066374
2014-06-17T19:49:19
2014-06-17T19:49:19
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
4,826
cpp
testboard.cpp
#define __DEBUG #include "../TetrisBoard.h" #include "../TetrominoFactory.h" #include "../Tetromino.h" #include "../Graphics.h" #include "../BoardGraphics.h" #include <stdio.h> #include <iostream> #include <string> using namespace std; // Boardin toiminnan testausta //#define TEST1 // Palikoiden liikkumisen testausta #define TEST2 #define TEST2_GRAFIIKALLA //#define FUNKKARITULOSTE void printBoard(CTetrisBoard *board); void fillRow(CTetrisBoard *board, const int y, CELL_TYPE ct); void pause(void); bool boolReport(bool result, string testStr); #ifdef TEST2 int main(void) { CTetrisBoard *board = new CTetrisBoard(10, 10); CTetrominoFactory *factory = new CTetrominoFactory(); // CTetromino *blockA = factory->create(BLOCK_T); // CTetromino *blockB = factory->create(BLOCK_S); CTetromino *blockA = factory->createRandom(); CTetromino *blockB = factory->createRandom(); // filleripalikoita laudalle blockA->attach(board); blockA->drop(); blockA->detach(); blockB->attach(board); blockB->rotateLeft(); blockB->drop(); blockB->detach(); #ifdef TEST2_GRAFIIKALLA SGraphics *graphics = new SGraphics(); CBoardGraphics *boardGraphics = new CBoardGraphics(board, graphics, 16, 6); #endif // TEST2_GRAFIIKALLA // CTetromino *block = factory->create(BLOCK_T); CTetromino *block = factory->createRandom(); int i = 0; // --------- TESTEJÄ boolReport(block->attach(board), "Palikka laudassa" ); printBoard(board); pause(); boolReport(block->moveDown(), "Palikan tiputus"); printBoard(board); pause(); boolReport(block->rotateRight(), "Palikan kaanto"); printBoard(board); boolReport(block->rotateRight(), "Palikan kaanto"); printBoard(board); boolReport(block->rotateRight(), "Palikan kaanto"); printBoard(board); pause(); while(boolReport(block->moveLeft(), "Palikan siirto vasemmalle")); printBoard(board); pause(); while(boolReport(block->moveRight(), "Palikkan siirto oikealle")); printBoard(board); pause(); for(i=0; i<3; i++) boolReport(block->rotateRight(), "Palikan kaanto oikealle"); printBoard(board); pause(); for(i=0; i<3; i++) boolReport(block->moveLeft(), "Palikan siirto vasemmalle"); printBoard(board); pause(); for(i=0; i<3; i++) boolReport(block->rotateRight(), "Palikan kaanto oikealle"); printBoard(board); pause(); boolReport(block->drop(), "Palikan tiputus"); printBoard(board); // cout << block->hasLanded(); delete factory; delete blockA; delete blockB; delete block; delete board; #ifdef TEST2_GRAFIIKALLA delete graphics; delete boardGraphics; #endif // TEST2_GRAFIIKALLA return 0; } #endif // TEST2 // -------------------------------------------------------------------- #ifdef TEST1 int main(void) { CTetrisBoard *board = new CTetrisBoard(10, 10); board->setSlot(5, 1, BLOCK_T); board->setSlot(2, 2, BLOCK_T); board->setSlot(3, 4, BLOCK_I); board->setSlot(4, 6, BLOCK_O); board->setSlot(5, 6, BLOCK_O); board->setSlot(5, 8, BLOCK_Z); board->setSlot(4, 6, EMPTY); board->setSlot(4, 9, BLOCK_T); printBoard(board); fillRow(board, 3, BLOCK_S); fillRow(board, 2, BLOCK_Z); fillRow(board, 4, BLOCK_O); fillRow(board, 6, BLOCK_I); printBoard(board); board->clearFullLines(); printBoard(board); return 0; } #endif // TEST2 // -------------------------------------------------------------------- void fillRow(CTetrisBoard *board, const int y, CELL_TYPE ct) { for(int x=0; x<board->getWidth(); x++) board->setSlot(x, y, ct); } void printBoard(CTetrisBoard *board) { #ifdef FUNKKARITULOSTE cout << endl << " "; for(int x=0; x<board->getWidth(); x++) cout << x << " "; cout << endl; for(int y=board->getHeight()-1; y>=0; y--) { cout << " " << y << ": "; for(int x=0; x<board->getWidth(); x++) cout << board->getSlot(x, y) << " "; if(board->isEmpty(y)) cout << " IS EMPTY"; else cout << " NOTEMPTY"; if(board->isFull(y)) cout << " IS FULL"; else cout << " NOTFULL" << endl; } cout << " Removed lines: " << board->getRemovedLines(); cout << ", removed lines on last remove: " << board->getRemovedLinesLast() << endl << endl; #endif } void pause() { #ifdef FUNKKARITULOSTE cout << "----------------------------------------- "; cout << "Press ENTER ..." << endl; #endif fflush ( stdout ); getchar(); } bool boolReport(bool result, string testStr) { #ifdef FUNKKARITULOSTE if(result) cout << "(TEST) " << testStr << ": onnistui\n"; else cout << "(TEST) " << testStr << ": epaonnistui\n"; #endif return result; }
52b6a17577970ef7020cc41345a7304c17fa1c62
1aa185a6653722109b8b3e4be5e07bea4f1aa863
/base/include/{project_name}/{project_name}.h
642595f54a7390536506c62d238d6fc668c91274
[]
no_license
GAVLab/templates
e6f61fdd5859d01366945936940eec492ad670c1
0f4535ea36ff4be433e98c54a3f6154988cc3d6b
refs/heads/master
2020-06-08T20:34:40.507120
2012-07-27T18:19:22
2012-07-27T18:19:22
5,105,162
1
0
null
null
null
null
UTF-8
C++
false
false
582
h
{project_name}.h
/*! * \file {this_file} * \author {author} <{email}> * \version 0.0 * * \section LICENSE * {license_commented} * * \section DESCRIPTION * * Intial header for project {project_name}. REPLACE_ME with a description * of the project and file. */ #ifndef {project_name_caps}_H #define {project_name_caps}_H{header_hook_1} namespace {project_name} {{{header_hook_2} /*! * Class description */ class {project_name_camel} {{ public: {project_name_camel} (); ~{project_name_camel} ();{header_public_hook} private:{header_private_hook} }}; }} #endif
c573373bf990c6f6b755cf44231402b7898a4a2b
c8bb4cd63e577fadd1dc0ac820be166810d1a148
/Game/Game/Tilesets/Backgrounds/_Code/_code_Cloud.h
cbb56bb75fe682bf4c7c11d9008972a6d796a558
[]
no_license
rodrigobmg/Cloudberry-Kingdom-Port
c2a0aac9c7cb387775f6f00b3b12aae109a7ea39
74cd72e29ff5dfd8757d93abc92ed7e48a945fc8
refs/heads/master
2021-06-01T06:19:25.283550
2016-08-10T01:35:16
2016-08-10T01:35:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
709
h
_code_Cloud.h
#ifndef _CODE_CLOUD #define _CODE_CLOUD #include <small_header.h> namespace CloudberryKingdom { struct Background_Cloud : public BackgroundTemplate { virtual ~Background_Cloud() { #ifdef BOOST_BIN OnDestructor( "Background_Cloud" ); #endif } Background_Cloud( const std::wstring &Name ); virtual void Code( const boost::shared_ptr<Background> &b ); }; struct Background_CloudRain : public BackgroundTemplate { virtual ~Background_CloudRain() { #ifdef BOOST_BIN OnDestructor( "Background_CloudRain" ); #endif } Background_CloudRain( const std::wstring &Name ); virtual void Code( const boost::shared_ptr<Background> &b ); }; } #endif //#ifndef _CODE_CLOUD
ffcb914058cad512b2e94bac7743f8d217ea3b3b
6b217c91fb859d34e6492dd580705d93a34aac1d
/src/MayaBridge/PointCloudShape/PCEPointCloudData.h
f2fbb05e74d9ed9598134d5fe02e74efac1bc0b8
[ "MIT" ]
permissive
hustztz/pointCloudEditor
962ec79bb9ae144389f2a104d143bceeafee3cd2
b2f30a6625bfe54f7d0025d52a0f7edc8cf419d7
refs/heads/master
2021-01-17T12:59:26.283943
2016-08-15T05:27:54
2016-08-15T05:27:54
65,616,703
0
1
null
null
null
null
UTF-8
C++
false
false
2,543
h
PCEPointCloudData.h
/////////////////////////////////////////////////////////////////////////////// // // Provides a data type for some arbitrary user geometry. // // A users geometry class can exist in the DAG by creating an // MPxSurfaceShape (and UI) class for it and can also be passed through // DG connections by creating an MPxGeometryData class for it. // // MPxGeometryData is the same as MPxData except it provides // additional methods to modify the geometry data via an iterator. // /////////////////////////////////////////////////////////////////////////////// #ifndef _PCEPointCloudData #define _PCEPointCloudData #include "Shape/PCEPointCloud.h" #include <memory> #include <maya/MPxGeometryData.h> #include <maya/MTypeId.h> #include <maya/MString.h> class PCEPointCloudData : public MPxGeometryData { public: ////////////////////////////////////////////////////////////////// // // Overrides from MPxData // ////////////////////////////////////////////////////////////////// PCEPointCloudData(); virtual ~PCEPointCloudData(); virtual MStatus readASCII( const MArgList& argList, unsigned& idx ); virtual MStatus readBinary( istream& in, unsigned length ); virtual MStatus writeASCII( ostream& out ); virtual MStatus writeBinary( ostream& out ); virtual void copy ( const MPxData& ); virtual MTypeId typeId() const; virtual MString name() const; ////////////////////////////////////////////////////////////////// // // Overrides from MPxGeometryData // ////////////////////////////////////////////////////////////////// virtual MPxGeometryIterator* iterator( MObjectArray & componentList, MObject & component, bool useComponents); virtual MPxGeometryIterator* iterator( MObjectArray & componentList, MObject & component, bool useComponents, bool world) const; virtual bool updateCompleteVertexGroup( MObject & component ) const; ////////////////////////////////////////////////////////////////// // // Helper methods // ////////////////////////////////////////////////////////////////// MStatus readVerticesASCII( const MArgList&, unsigned& ); MStatus writeVerticesASCII( ostream& out ); static void * creator(); public: static const MString typeName; static const MTypeId id; // This is the geometry our data will pass though the DG // std::shared_ptr<PCEPointCloud> pCloudData; }; #endif /* _PCEPointCloudData */
5ca66c85758fd40ebb8fd4a0420829ba6662f452
c6e949cdf2ad2df22bf9552e2b6b62b04ba89109
/customizers/TrampolineCustomizer.cpp
8edeafcc7ba3ede4d7234cd132788c1172774dfc
[]
no_license
kyawawa/choreonoid_plugins
376d884bf554d156c58a244307d4ec5adaf84474
71914282600a8b10a9ff05067080f68f17f9cf35
refs/heads/master
2020-04-02T20:22:30.726825
2019-01-31T19:06:18
2019-01-31T19:06:18
154,766,857
0
0
null
2019-01-13T10:00:54
2018-10-26T02:38:42
C++
UTF-8
C++
false
false
3,413
cpp
TrampolineCustomizer.cpp
// // -*- mode: C++; coding: utf-8-unix; -*- // /** // * @file Customizer.cpp // * @brief Trampoline spring / damping simulation // * @author Shin'ichiro Nakaoka // * @editor Tatsuya Ishikawa // */ #define CNOID_BODY_CUSTOMIZER #ifdef CNOID_BODY_CUSTOMIZER #include <cnoid/BodyCustomizerInterface> #else #include <BodyCustomizerInterface.h> #endif #include <cstdlib> #include <iostream> #include <string> #include <fstream> #include "yaml-cpp/yaml.h" #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) #define DLL_EXPORT __declspec(dllexport) #else #define DLL_EXPORT #endif /* Windows */ using namespace cnoid; namespace { BodyInterface* bodyInterface = 0; BodyCustomizerInterface bodyCustomizerInterface; struct Customizer { double* pUpperJointPosition; double* pUpperJointVelocity; double* pUpperJointForce; double kp; double kd; }; const char** getTargetModelNames() { char *rname = getenv("CHOREONOID_ROBOT"); if (rname != NULL) { std::cerr << "[TrampolineCustomizer] CHOREONID_ROBOT =" << rname << std::endl; } static const char* names[] = {"TrampolineSpringModel", rname, 0}; return names; } BodyCustomizerHandle create(BodyHandle bodyHandle, const char* modelName) { // Customizer* customizer = new Customizer(); Customizer* customizer = 0; customizer = new Customizer; int upperJointIndex = bodyInterface->getLinkIndexFromName(bodyHandle, "UPPER"); customizer->pUpperJointPosition = bodyInterface->getJointValuePtr(bodyHandle, upperJointIndex); customizer->pUpperJointVelocity = bodyInterface->getJointVelocityPtr(bodyHandle, upperJointIndex); customizer->pUpperJointForce = bodyInterface->getJointForcePtr(bodyHandle, upperJointIndex); customizer->kp = 2500; customizer->kd = 5.0; if (char* conf_file = std::getenv("CUSTOMIZER_CONF_PATH")) { std::ifstream ifs(conf_file); if (ifs.is_open()) { YAML::Node spring = YAML::LoadFile(conf_file); customizer->kp = spring["trampoline"]["kp"].as<double>(); customizer->kd = spring["trampoline"]["kd"].as<double>(); std::cerr << "[TrampolineCustomizer] kp is set to " << customizer->kp << " and kd is set to " << customizer->kd << std::endl; } } return static_cast<BodyCustomizerHandle>(customizer); } void destroy(BodyCustomizerHandle customizerHandle) { Customizer* customizer = static_cast<Customizer*>(customizerHandle); if (customizer) { delete customizer; } } void setVirtualJointForces(BodyCustomizerHandle customizerHandle) { Customizer* c = static_cast<Customizer*>(customizerHandle); *c->pUpperJointForce = -c->kp * *c->pUpperJointPosition - c->kd * *c->pUpperJointVelocity; } } extern "C" DLL_EXPORT cnoid::BodyCustomizerInterface* getHrpBodyCustomizerInterface(cnoid::BodyInterface* bodyInterface_) { bodyInterface = bodyInterface_; bodyCustomizerInterface.version = cnoid::BODY_CUSTOMIZER_INTERFACE_VERSION; bodyCustomizerInterface.getTargetModelNames = getTargetModelNames; bodyCustomizerInterface.create = create; bodyCustomizerInterface.destroy = destroy; bodyCustomizerInterface.initializeAnalyticIk = NULL; bodyCustomizerInterface.calcAnalyticIk = NULL; bodyCustomizerInterface.setVirtualJointForces = setVirtualJointForces; return &bodyCustomizerInterface; }
4f781e5c180874b953b46794611934ecbbfc628c
9ae074dc6bfb0b9d2c0bba28cd75f7b0b5b7f95f
/cvision-scratch/experimental/src/exerciseone/color-distance.cpp
925fab7aef27eb2977cc2b23055e180da5471243
[]
no_license
aldwinhermanudin/side-projects
020a157d87c1c45ca56aab8ecfa920f8f0e249f7
cad4dcd5b4aee2d05e98548a0a81cda364896646
refs/heads/master
2021-03-27T13:09:08.743247
2019-05-11T05:06:29
2019-05-11T05:06:29
39,756,918
0
0
null
null
null
null
UTF-8
C++
false
false
566
cpp
color-distance.cpp
#include <iostream> #include <opencv2/opencv.hpp> using namespace std; typedef struct { unsigned char r, g, b; } RGB; double ColourDistance(RGB e1, RGB e2) { long rmean = ( (long)e1.r + (long)e2.r ) / 2; long r = (long)e1.r - (long)e2.r; long g = (long)e1.g - (long)e2.g; long b = (long)e1.b - (long)e2.b; return sqrt((((512+rmean)*r*r)>>8) + 4*g*g + (((767-rmean)*b*b)>>8)); } int main(){ RGB a,b; a.r = 208; a.g = 39; a.b = 0; b.r = 255; b.g = 70; b.b = 95; cout << ColourDistance(a,b); return 0; }
3c84dd439fadd0b6945d4db16d92efad137b9407
024c74f395b4a749b26cf2719b1e4efecd5331fc
/Codeforces/60B.cpp
e89a30e38535c42aec3c93fca76e23ce1e2f3d85
[]
no_license
thisisrajat/competitive-programming
28ed70f77e2c3892ee1d005341ef7d37930caad9
422cc7fac78a9908ca7a95a7c6eae724ed4a0631
refs/heads/master
2021-01-01T18:12:10.693796
2017-01-01T17:42:53
2017-01-01T17:42:53
17,668,936
0
0
null
null
null
null
UTF-8
C++
false
false
2,121
cpp
60B.cpp
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <vector> #include <string> #include <map> #include <set> #include <sstream> #include <utility> #include <functional> #include <numeric> #include <stack> #include <queue> #include <cmath> #include <cstdlib> #include <ctime> #include <cassert> #include <bitset> #include <list> #include <memory.h> using namespace std; int g[12][12][12]; int tmp[12][12][12]; int k, n, m; int s, e; struct p { int x, y, z; p(int xx, int yy, int zz) { x = xx; y = yy; z = zz; } }; inline bool range(int x, int y, int z) { return (1 <= x && x <= n && 1 <= y && y <= m && 1 <= z && z <= k); } const int dx[] = {-1, 0, 0, 1}; const int dy[] = {0, -1, 1, 0}; void bfs(int x, int y, int z) { queue< p > q; q.push(p(x, y, z)); while(!q.empty()) { x = q.front().x; y = q.front().y; z = q.front().z; g[x][y][z] = 2; q.pop(); for(int id = 0; id < 4; id++) { int u = dx[id] + x; int v = dy[id] + y; int w = z; if(!range(u, v, w) || g[u][v][w] == 2) continue; q.push(p(u, v, w)); g[u][v][w] = 2; } if (range(x, y, z - 1) && g[x][y][z - 1] == 1) { q.push(p(x, y, z - 1)); g[x][y][z] = 2; } if (range(x, y, z + 1) && g[x][y][z + 1] == 1) { q.push(p(x, y, z + 1)); g[x][y][z] = 2; } } } int main() { ios_base::sync_with_stdio(false); cin >> k >> n >> m; for(int i = 1; i <= k; i++) { for(int j = 1; j <= n; j++) { for(int l = 1; l <= m; l++) { char ch; cin >> ch; if(ch == '.') g[j][l][i] = 1; else if (ch == '#') g[j][l][i] = 2; else assert(false); } } } for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { for(int l = 1; l <= k; l++) { tmp[i][j][l] = g[i][j][l]; } } } cin >> s >> e; bfs(s, e, 1); int dif = 0; for(int i = 1; i <= n; i++) for(int j = 1; j <= m; j++) for(int l = 1; l <= k; l++) { if(tmp[i][j][l] == 1 && g[i][j][l] == 2) dif++; } cout << dif << endl; return 0; }
cf1d9aa3aa3d1cf8005501ed874e8e40dd96908e
7bbe6e930494a2a5538f4febdd20e85e674f742e
/homework/vec3.h
67392dab032f534b2bd5c5515d80e8c6d3366ad3
[ "MIT" ]
permissive
migon25/GameDevelopment
2d6eb4215dbf902520403556828dae353c21741c
7198ffeb51ee9316ce201834fc82f0c4df05c75c
refs/heads/main
2023-08-02T05:23:27.400813
2021-09-27T19:47:36
2021-09-27T19:47:36
410,627,239
0
0
null
null
null
null
UTF-8
C++
false
false
2,714
h
vec3.h
#pragma once #include <iostream> #include <cmath> #include "vec3.h" using namespace std; template <class T> class vec3 { public: T x, y, z; // 3 constructors vec3(float _x, float _y, float _z); vec3(float value); vec3(); // operators vec3<T> operator+(const vec3<T>& vector) const; vec3<T> operator-(const vec3<T>& vector) const; bool operator==(const vec3<T>& vector) const; void operator=(const vec3<T>& vector); // Changes the value void operator+=(const vec3<T>& vector); // Changes the value void operator-=(const vec3<T>& vector); // Changes the value // Methods void Normalize(); //Magnitude of vectors is set to 1. void Zero(); //Every member is set to zero bool IsZero() const; //Checks if any member is 0 float DistanceTo(const vec3<T>& vector) const; //Calculates the distance between 2 vectors ~vec3(); //Destructor }; template<class T> vec3<T>::vec3() { x = 0; y = 0; z = 0; } //Initialise the vector with 3 members template<class T> vec3<T>::vec3(float vx, float vy, float vz) { x = vx; y = vy; z = vz; } //Initialises the vector with the same number template<class T> vec3<T>::vec3(float num) { x = num; y = num; z = num; } //Plus operator template<class T> vec3<T> vec3<T>::operator+(const vec3<T>& v) const { vec3<T> result; result.x = x + v.x; result.y = y + v.y; result.z = z + v.z; return result; } template<class T> vec3<T> vec3<T>::operator-(const vec3<T>& vec) const { vec3<T> result; result.x = x - vec.x; result.y = y - vec.y; result.z = z - vec.z; return result; } template<class T> void vec3<T>::operator=(const vec3<T>& vec) { x = vec.x; y = vec.y; z = vec.z; } template<class T> void vec3<T>::operator+=(const vec3<T>& vec) { x += vec.x; y += vec.y; z += vec.z; } template<class T> void vec3<T>::operator-=(const vec3<T>& vec) { x -= vec.x; y -= vec.y; z -= vec.z; } template<class T> bool vec3<T>::operator==(const vec3<T>& vec) const { return x == vec.x && y == vec.y && z == vec.z; } template<class T> void vec3<T>::Normalize() { float magnitude = sqrtf(x * x + y * y + z * z); x = x / magnitude; y = y / magnitude; z = z / magnitude; } template<class T> void vec3<T>::Zero() { x = 0; y = 0; z = 0; } template<class T> bool vec3<T>::IsZero() const { return x == 0 && y == 0 && z == 0; } template<class T> float vec3<T>::DistanceTo(const vec3<T>& vec) const { vec3<T> diff(vec.x - x, vec.y - y, vec.z - z); return sqrtf(diff.x * diff.x + diff.y * diff.y + diff.z * diff.z); } template<class T> vec3<T>::~vec3() { }
e5f9c6cb19c6766384072dc269f70ae5759d11ee
fcdf00e61f079cd00dbdfa3727d07cb58e2e0dfc
/eventQueue.cpp
4edee36a1e4cbe1b32d10d6aee5cde45d777d800
[]
no_license
ZhenyuLiu46/os-lab2
7ac999182566653864e6b43ebe7765bb934109a3
4680239a35d7372bda99e690d63f577cdccda703
refs/heads/master
2022-04-06T21:45:40.191174
2020-03-08T19:03:42
2020-03-08T19:03:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
827
cpp
eventQueue.cpp
// // eventQueue.cpp // Lab2-working // // Created by Zhenyu Liu on 3/18/19. // Copyright © 2019 Zhenyu Liu. All rights reserved. // #include <iostream> #include "eventQueue.h" void EventQueue::put_event(Event *e) { int flag = 0; list<Event*>::iterator it; for(it = eventQue.begin(); it != eventQue.end(); it++){ if((*it)->timestamp > e->timestamp){ eventQue.insert(it, e); flag = 1; break; } } if(flag == 0) eventQue.insert(it, e); } //check if empty, and pop_front Event* EventQueue::get_event() { if(eventQue.size() == 0) return NULL; Event *temp = *eventQue.begin(); eventQue.pop_front(); return temp; } int EventQueue::getNextEventTime() { if(eventQue.size() == 0) return -1; return (*eventQue.begin())->timestamp; }
8e8e946d2dfd665c4eaab57bcfb4ca21f14c7242
4cbf5729bc1eb652347819e2bede978dae4841e1
/src/frontend/sdl.h
63fbdb8e897c58652d39fa2005be5e798f443205
[ "BSD-3-Clause" ]
permissive
fengjixuchui/heliage
d208f27fc0e4d2d7fb814ce5df77f133759e8361
b11af9949167b2663812c6dff5c4600d20091bfc
refs/heads/master
2020-09-29T12:49:59.344630
2020-07-28T06:10:50
2020-07-28T06:10:50
227,041,520
0
0
BSD-3-Clause
2020-07-28T06:10:51
2019-12-10T06:06:24
C++
UTF-8
C++
false
false
262
h
sdl.h
#pragma once #include "../gb.h" #include "../ppu.h" #include "../types.h" void HandleEvents(Joypad* joypad); u32 GetARGBColor(PPU::Color pixel); void DrawFramebuffer(std::array<PPU::Color, 160 * 144>& framebuffer); void Shutdown(); int main_SDL(char* argv[]);
5cd4e2d1d9a69b1c0c9a1ab99fe22946b69cf0f1
fead2d2ea15e43f058ce5b76ccd7a42786a66ea9
/7/res_x86/StdAfx.cpp
ec3901645bec361e361fb224e41f7ae27a489d18
[]
no_license
jsg2021/Simply-Transparent
adba084caba5a6f4a0f7f95a7a3d29c93de54810
bb875a8010d5c01e76a64e57dd3fe807d8f0fec0
refs/heads/master
2021-01-02T08:56:53.867936
2012-01-16T20:07:06
2012-01-16T20:07:06
2,200,338
3
0
null
null
null
null
UTF-8
C++
false
false
1,364
cpp
StdAfx.cpp
// stdafx.cpp : source file that includes just the standard includes // res_x86.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" #include "resource.h" /////////////////////////////////////////////////////////////////////////////// //// // void ErrorMessage( DWORD code ){ LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); MessageBox( 0, (LPCTSTR)lpMsgBuf, "Simply Transparet: res_x86 Error", MB_OK ); LocalFree( lpMsgBuf ); } /////////////////////////////////////////////////////////////////////////////// //// SendQuit( ) - Sends the Quit message to the main application WindProc // void SendQuit( ) { char class_s[MAX_PATH]; char title_s[MAX_PATH]; LoadString( GetMyInstanceHandle( ), IDS_APP_CLASS, class_s, MAX_PATH); LoadString( GetMyInstanceHandle( ), IDS_APP_TITLE, title_s, MAX_PATH); for( unsigned int x = 0; x<strlen( class_s ); x++ ) class_s[x] = tolower( class_s[x] ); HWND hwnd = FindWindow( class_s, title_s ); if( hwnd != NULL) SendMessage( hwnd, WM_QUIT, 0, 0 ); }
a9255dd4015976ffb023ae291fe118ecd2265e9b
6c996ca5146bd307a062f38819acec16d710656f
/workspace/iw8/code_source/src/bgame/asm/common_asm_util.cpp
ac28ee74483687a7ad1efa63a037cfae65cb72c8
[]
no_license
Omn1z/OpenIW8
d46f095d4d743d1d8657f7e396e6d3cf944aa562
6c01a9548e4d5f7e1185369a62846f2c6f8304ba
refs/heads/main
2023-08-15T22:43:01.627895
2021-10-10T20:44:57
2021-10-10T20:44:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,255
cpp
common_asm_util.cpp
/* ============== Common_Asm::Utils::GetCurrentStateByAssetName ============== */ const ASM_State *__fastcall Common_Asm::Utils::GetCurrentStateByAssetName(const ASM_Instance *pInst, scr_string_t asmName) { return ?GetCurrentStateByAssetName@Utils@Common_Asm@@SAPEBUASM_State@@PEBUASM_Instance@@W4scr_string_t@@@Z(pInst, asmName); } /* ============== Common_Asm::Utils::EventFired ============== */ bool __fastcall Common_Asm::Utils::EventFired(const ASM_Instance *pInst, const scr_string_t eventName) { return ?EventFired@Utils@Common_Asm@@SA_NPEBUASM_Instance@@W4scr_string_t@@@Z(pInst, eventName); } /* ============== Common_Asm::Utils::DebugRender_States3D ============== */ void __fastcall Common_Asm::Utils::DebugRender_States3D(const ASM_Instance *pInst, bool bShouldDrawHistory, vec3_t *drawPos, bool bFromServer, int duration) { ?DebugRender_States3D@Utils@Common_Asm@@SAXPEBUASM_Instance@@_NTvec3_t@@1H@Z(pInst, bShouldDrawHistory, drawPos, bFromServer, duration); } /* ============== Common_Asm::Utils::StateHasSubtree ============== */ bool __fastcall Common_Asm::Utils::StateHasSubtree(const ASM_State *pState, const scr_string_t subtreeName) { return ?StateHasSubtree@Utils@Common_Asm@@SA_NPEBUASM_State@@W4scr_string_t@@@Z(pState, subtreeName); } /* ============== Common_Asm::Utils::LogicGroup_IsAncestorOf ============== */ bool __fastcall Common_Asm::Utils::LogicGroup_IsAncestorOf(const ASM *pASM, int possibleAncestorGroupID, int groupID) { return ?LogicGroup_IsAncestorOf@Utils@Common_Asm@@SA_NPEBUASM@@HH@Z(pASM, possibleAncestorGroupID, groupID); } /* ============== Common_Asm::Utils::GetLogicGroup ============== */ const ASM_LogicGroup *__fastcall Common_Asm::Utils::GetLogicGroup(const ASM *pASM, int logicID) { return ?GetLogicGroup@Utils@Common_Asm@@SAPEBUASM_LogicGroup@@PEBUASM@@H@Z(pASM, logicID); } /* ============== Common_Asm::Utils::CurrentStateHasFlag ============== */ bool __fastcall Common_Asm::Utils::CurrentStateHasFlag(const ASM_Instance *pInst, const scr_string_t flagName) { return ?CurrentStateHasFlag@Utils@Common_Asm@@SA_NPEBUASM_Instance@@W4scr_string_t@@@Z(pInst, flagName); } /* ============== Common_Asm::HasState ============== */ bool __fastcall Common_Asm::HasState(Common_Asm *this, const ASM *pASM, const scr_string_t stateName) { return ?HasState@Common_Asm@@QEAA_NPEBUASM@@W4scr_string_t@@@Z(this, pASM, stateName); } /* ============== Common_Asm::Utils::FindEventFor ============== */ ASM_Event *__fastcall Common_Asm::Utils::FindEventFor(ASM_Event *eventTable, const scr_string_t eventName) { return ?FindEventFor@Utils@Common_Asm@@SAPEAUASM_Event@@PEAU3@W4scr_string_t@@@Z(eventTable, eventName); } /* ============== Common_Asm::Utils::GetStateTransitioningFrom ============== */ const ASM_State *__fastcall Common_Asm::Utils::GetStateTransitioningFrom(const ASM_Instance *pInst) { return ?GetStateTransitioningFrom@Utils@Common_Asm@@SAPEBUASM_State@@PEBUASM_Instance@@@Z(pInst); } /* ============== Common_Asm::Utils::DebugRender_Events ============== */ void __fastcall Common_Asm::Utils::DebugRender_Events(const ASM_Instance *pInst, const ASM_EphemeralEvent *pEphemeralEventTable, float topLeftX, float topLeftY, bool bFromServer, int duration) { ?DebugRender_Events@Utils@Common_Asm@@SAXPEBUASM_Instance@@PEBUASM_EphemeralEvent@@MM_NH@Z(pInst, pEphemeralEventTable, topLeftX, topLeftY, bFromServer, duration); } /* ============== Common_Asm::Utils::GetEventTime ============== */ int __fastcall Common_Asm::Utils::GetEventTime(const ASM_Instance *pInst, scr_string_t eventName) { return ?GetEventTime@Utils@Common_Asm@@SAHPEBUASM_Instance@@W4scr_string_t@@@Z(pInst, eventName); } /* ============== Common_Asm::Utils::EventFired ============== */ bool __fastcall Common_Asm::Utils::EventFired(const ASM_Instance *pInst, int numEvents, const scr_string_t eventName) { return ?EventFired@Utils@Common_Asm@@SA_NPEBUASM_Instance@@HW4scr_string_t@@@Z(pInst, numEvents, eventName); } /* ============== Common_Asm::Utils::CurrentStateHasAnyAnimFlags ============== */ bool __fastcall Common_Asm::Utils::CurrentStateHasAnyAnimFlags(const ASM_Instance *pInst, const AnimScriptFlags flags) { return ?CurrentStateHasAnyAnimFlags@Utils@Common_Asm@@SA_NPEBUASM_Instance@@W4AnimScriptFlags@@@Z(pInst, flags); } /* ============== Common_Asm::Utils::AddEventData_Internal ============== */ int __fastcall Common_Asm::Utils::AddEventData_Internal(scrContext_t *scrContext, unsigned int eventTableID, int paramIndex, VariableValue *pData) { return ?AddEventData_Internal@Utils@Common_Asm@@SAHAEAUscrContext_t@@IHPEAUVariableValue@@@Z(scrContext, eventTableID, paramIndex, pData); } /* ============== Common_Asm::Utils::GetSubtree ============== */ ASM_Instance *__fastcall Common_Asm::Utils::GetSubtree(const ASM_Instance *pInst, const scr_string_t subtreeName) { return ?GetSubtree@Utils@Common_Asm@@SAPEAUASM_Instance@@PEBU3@W4scr_string_t@@@Z(pInst, subtreeName); } /* ============== Common_Asm::Utils::DebugRender_EntDetails ============== */ void __fastcall Common_Asm::Utils::DebugRender_EntDetails(const ASM_Instance *pInst, const ASM_EphemeralEvent *pEphemeralEventTable, bool bFromServer, int duration) { ?DebugRender_EntDetails@Utils@Common_Asm@@SAXPEBUASM_Instance@@PEBUASM_EphemeralEvent@@_NH@Z(pInst, pEphemeralEventTable, bFromServer, duration); } /* ============== Common_Asm::Utils::GetState ============== */ const ASM_State *__fastcall Common_Asm::Utils::GetState(const ASM *pASM, int stateID) { return ?GetState@Utils@Common_Asm@@SAPEBUASM_State@@PEBUASM@@H@Z(pASM, stateID); } /* ============== Common_Asm::Utils::AddEventData_Internal ============== */ __int64 Common_Asm::Utils::AddEventData_Internal(scrContext_t *scrContext, unsigned int eventTableID, int paramIndex, VariableValue *pData) { const char *m_scriptPos; unsigned int NewArrayVariable; if ( !eventTableID && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 25, ASSERT_TYPE_ASSERT, "(eventTableID)", (const char *)&queryFormat, "eventTableID") ) __debugbreak(); if ( !pData && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 26, ASSERT_TYPE_ASSERT, "(pData)", (const char *)&queryFormat, "pData") ) __debugbreak(); if ( paramIndex == -1 ) paramIndex = GetArraySize(scrContext, eventTableID); m_scriptPos = ScriptContext_GetVarUsageScriptCodePos(scrContext).m_scriptPos; ScriptContext_SetVarUsagePos(scrContext, "<asm variable>"); NewArrayVariable = GetNewArrayVariable(scrContext, eventTableID, paramIndex); ScriptContext_SetVarUsageScriptCodePos(scrContext, (const ScriptCodePos)m_scriptPos); SetNewVariableValue(scrContext, NewArrayVariable, pData); AddRefToValue(scrContext, (unsigned __int8)pData->type, pData->u); return (unsigned int)paramIndex; } /* ============== Common_Asm::Utils::CurrentStateHasAnyAnimFlags ============== */ bool Common_Asm::Utils::CurrentStateHasAnyAnimFlags(const ASM_Instance *pInst, const AnimScriptFlags flags) { const ASM_State *State; State = Common_Asm::Utils::GetState(pInst->m_pASM, pInst->m_CurState); if ( !State && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 123, ASSERT_TYPE_ASSERT, "(pState)", (const char *)&queryFormat, "pState") ) __debugbreak(); if ( pInst->m_pASM->m_Mode != ASM_MODE_PLAYER && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 124, ASSERT_TYPE_ASSERT, "(pInst->m_pASM->m_Mode == ASM_MODE_PLAYER)", (const char *)&queryFormat, "pInst->m_pASM->m_Mode == ASM_MODE_PLAYER") ) __debugbreak(); return (flags & State->m_Flags) != 0; } /* ============== Common_Asm::Utils::CurrentStateHasFlag ============== */ char Common_Asm::Utils::CurrentStateHasFlag(const ASM_Instance *pInst, const scr_string_t flagName) { const ASM_State *State; unsigned int v5; __int64 v6; int m_Flags; unsigned int numFlags; char **flagNameArray; ASM_GetStateFlagDefs(pInst->m_pASM->m_Mode, (const char ***)&flagNameArray, &numFlags); if ( !flagNameArray && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 101, ASSERT_TYPE_ASSERT, "(flagNames)", (const char *)&queryFormat, "flagNames") ) __debugbreak(); if ( !numFlags && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 102, ASSERT_TYPE_ASSERT, "(numFlags)", (const char *)&queryFormat, "numFlags") ) __debugbreak(); State = Common_Asm::Utils::GetState(pInst->m_pASM, pInst->m_CurState); if ( !State && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 105, ASSERT_TYPE_ASSERT, "(pState)", (const char *)&queryFormat, "pState") ) __debugbreak(); if ( pInst->m_pASM->m_Mode ) { if ( CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 106, ASSERT_TYPE_ASSERT, "(pInst->m_pASM->m_Mode == ASM_MODE_AI)", (const char *)&queryFormat, "pInst->m_pASM->m_Mode == ASM_MODE_AI") ) __debugbreak(); } v5 = numFlags; v6 = 0i64; if ( !numFlags ) return 0; while ( 1 ) { m_Flags = State->m_Flags; if ( _bittest(&m_Flags, v6) ) break; LABEL_17: v6 = (unsigned int)(v6 + 1); if ( (unsigned int)v6 >= v5 ) return 0; } if ( SL_FindString(flagNameArray[v6]) != flagName ) { v5 = numFlags; goto LABEL_17; } return 1; } /* ============== Common_Asm::Utils::DebugRender_EntDetails ============== */ void Common_Asm::Utils::DebugRender_EntDetails(const ASM_Instance *pInst, const ASM_EphemeralEvent *pEphemeralEventTable, bool bFromServer, int duration) { BOOL fromServer; const ASM_State *State; const char *v9; __int128 v10; int v11; const ASM ***m_Subtrees; const ASM **v13; const ASM_State *v14; const char *v15; __int128 v16; char dest[1024]; fromServer = bFromServer; Com_sprintf(dest, 0x400ui64, "Ent: %d", (unsigned int)pInst->m_EntNum); CL_AddDebugString2D(100.0, 200.0, &colorYellow, 1.0, dest, fromServer, duration); State = Common_Asm::Utils::GetState(pInst->m_pASM, pInst->m_CurState); v9 = SL_ConvertToString(State->m_Name); Com_sprintf(dest, 0x400ui64, "%s | %s", pInst->m_pASM->m_szName, v9); CL_AddDebugString2D(100.0, 212.0, &colorYellow, 1.0, dest, fromServer, duration); v10 = LODWORD(FLOAT_224_0); v11 = 0; if ( pInst->m_NumSubtrees > 0 ) { m_Subtrees = (const ASM ***)pInst->m_Subtrees; do { v13 = *m_Subtrees; v14 = Common_Asm::Utils::GetState(**m_Subtrees, *((_DWORD *)*m_Subtrees + 4)); v15 = SL_ConvertToString(v14->m_Name); Com_sprintf(dest, 0x400ui64, " %s | %s", (*v13)->m_szName, v15); CL_AddDebugString2D(100.0, *(float *)&v10, &colorYellow, 1.0, dest, fromServer, duration); ++v11; ++m_Subtrees; v16 = v10; *(float *)&v16 = *(float *)&v10 + 12.0; v10 = v16; } while ( v11 < pInst->m_NumSubtrees ); } Common_Asm::Utils::DebugRender_Events(pInst, pEphemeralEventTable, 100.0, 400.0, fromServer, duration); } /* ============== Common_Asm::Utils::DebugRender_Events ============== */ void __fastcall Common_Asm::Utils::DebugRender_Events(const ASM_Instance *pInst, const ASM_EphemeralEvent *pEphemeralEventTable, float topLeftX, double topLeftY, bool bFromServer, int duration) { const ASM_EphemeralEvent *v6; __int128 v8; __int128 v9; int *p_m_Time; __int64 v11; scr_string_t v12; int v13; const char *v14; __int128 v15; int v16; ASM_Instance **m_Subtrees; const char ***v18; unsigned int *v19; __int64 v20; __int128 v21; scr_string_t v22; int v23; const char *v24; __int128 v25; __int128 v26; __int128 v27; int *p_m_ParamID; __int64 v29; scr_string_t v30; int v31; const char *v32; const char *v33; __int128 v34; __int64 fromServer; __int64 fromServera; __int64 v37; char dest[256]; v6 = pEphemeralEventTable; Com_sprintf(dest, 0x100ui64, "Events: %s", pInst->m_pASM->m_szName); CL_AddDebugString2D(topLeftX, *(float *)&topLeftY, &colorYellow, 1.0, dest, bFromServer, duration); v9 = *(_OWORD *)&topLeftY; *(float *)&v9 = *(float *)&topLeftY + 13.0; v8 = v9; p_m_Time = &pInst->m_EventTable[0].m_Time; v11 = 8i64; do { v12 = *(p_m_Time - 2); if ( v12 ) { v13 = *(p_m_Time - 1); v14 = SL_ConvertToString(v12); LODWORD(fromServer) = v13; Com_sprintf(dest, 0x100ui64, "%d %s %d", (unsigned int)*p_m_Time, v14, fromServer); CL_AddDebugString2D(topLeftX, *(float *)&v8, &colorYellow, 1.0, dest, bFromServer, duration); v15 = v8; *(float *)&v15 = *(float *)&v8 + 13.0; v8 = v15; } p_m_Time += 3; --v11; } while ( v11 ); v16 = 0; if ( pInst->m_NumSubtrees > 0 ) { m_Subtrees = pInst->m_Subtrees; do { v18 = (const char ***)*m_Subtrees; if ( (*m_Subtrees)->m_EventTable[0].m_Name ) { Com_sprintf(dest, 0x100ui64, " Events: %s", **v18); CL_AddDebugString2D(topLeftX, *(float *)&v8, &colorYellow, 1.0, dest, bFromServer, duration); v19 = (unsigned int *)(v18 + 10); v20 = 8i64; v21 = v8; *(float *)&v21 = *(float *)&v8 + 13.0; v8 = v21; do { v22 = *(v19 - 2); if ( v22 ) { v23 = *(v19 - 1); v24 = SL_ConvertToString(v22); LODWORD(fromServera) = v23; Com_sprintf(dest, 0x100ui64, " %d %s %d", *v19, v24, fromServera); CL_AddDebugString2D(topLeftX, *(float *)&v8, &colorYellow, 1.0, dest, bFromServer, duration); v25 = v8; *(float *)&v25 = *(float *)&v8 + 13.0; v8 = v25; } v19 += 3; --v20; } while ( v20 ); } ++v16; ++m_Subtrees; } while ( v16 < pInst->m_NumSubtrees ); v6 = pEphemeralEventTable; } v26 = v8; *(float *)&v26 = *(float *)&v8 + 13.0; if ( v6 ) { CL_AddDebugString2D(topLeftX, *(float *)&v26, &colorYellow, 1.0, "Ephemeral Events:", bFromServer, duration); *(float *)&v26 = *(float *)&v26 + 13.0; v27 = v26; p_m_ParamID = &v6->m_ParamID; v29 = 6i64; do { v30 = *(p_m_ParamID - 1); if ( v30 ) { v31 = *p_m_ParamID; v32 = SL_ConvertToString(v30); v33 = SL_ConvertToString((scr_string_t)*(p_m_ParamID - 2)); LODWORD(v37) = v31; Com_sprintf(dest, 0x100ui64, "%d %s %s %d", (unsigned int)p_m_ParamID[1], v33, v32, v37); CL_AddDebugString2D(topLeftX, *(float *)&v27, &colorYellow, 1.0, dest, bFromServer, duration); v34 = v27; *(float *)&v34 = *(float *)&v27 + 13.0; v27 = v34; } p_m_ParamID += 4; --v29; } while ( v29 ); } } /* ============== Common_Asm::Utils::DebugRender_States3D ============== */ void Common_Asm::Utils::DebugRender_States3D(const ASM_Instance *pInst, bool bShouldDrawHistory, vec3_t *drawPos, bool bFromServer, int duration) { const ASM *m_pASM; const vec4_t *v6; int m_CurState; int fromServer; const ASM_State *State; const char *v12; int v13; const ASM ***m_Subtrees; const ASM **v15; const ASM_State *v16; const char *v17; ASM_History *HistoryObject; ASM_History *v19; unsigned int Index; unsigned int v21; unsigned __int64 v22; __int64 v23; unsigned int *v24; int v25; __int128 *v26; vec4_t *p_color; const ASM_State *v28; const char *v29; vec4_t *v30; __int64 v31; const ASM_State *v32; const char *v33; unsigned int v35; ASM *pASM; ASM_History *v37; vec4_t result; vec4_t v39; vec4_t v40; __int128 v41; vec4_t color; vec4_t v43; char dest[1024]; m_pASM = pInst->m_pASM; v6 = &colorRed; m_CurState = pInst->m_CurState; fromServer = bFromServer; pASM = (ASM *)pInst->m_pASM; drawPos->v[2] = drawPos->v[2] + 80.0; if ( bFromServer ) v6 = &colorOrange; State = Common_Asm::Utils::GetState(m_pASM, m_CurState); v12 = SL_ConvertToString(State->m_Name); Com_sprintf(dest, 0x400ui64, "%d %s | %s", (unsigned int)pInst->m_EntNum, m_pASM->m_szName, v12); CL_AddDebugString(drawPos, v6, 0.5, dest, fromServer, duration); v13 = 0; drawPos->v[2] = drawPos->v[2] - 8.0; if ( pInst->m_NumSubtrees > 0 ) { m_Subtrees = (const ASM ***)pInst->m_Subtrees; do { v15 = *m_Subtrees; v16 = Common_Asm::Utils::GetState(**m_Subtrees, *((_DWORD *)*m_Subtrees + 4)); v17 = SL_ConvertToString(v16->m_Name); Com_sprintf(dest, 0x400ui64, " %s | %s", (*v15)->m_szName, v17); CL_AddDebugString(drawPos, v6, 0.5, dest, fromServer, duration); ++v13; ++m_Subtrees; drawPos->v[2] = drawPos->v[2] - 8.0; } while ( v13 < pInst->m_NumSubtrees ); m_pASM = pASM; } if ( bShouldDrawHistory ) { HistoryObject = ASM_GetHistoryObject(pInst->m_EntNum); v37 = HistoryObject; v19 = HistoryObject; if ( HistoryObject ) { Index = ASM_History::BeginIndex(HistoryObject); v21 = 0; v35 = ASM_History::Size(v19); if ( v35 ) { do { v22 = (unsigned __int64)Index << 6; v23 = *(unsigned int *)((char *)&v19->m_events[0].m_time + v22); v24 = (unsigned int *)((char *)v19->m_events + v22); if ( (int)v23 < 0 ) break; v25 = *(int *)((char *)&v19->m_events[0].m_fromState + v22); if ( v25 >= 0 ) { v28 = Common_Asm::Utils::GetState(m_pASM, v25); v29 = SL_ConvertToString(v28->m_Name); Com_sprintf(dest, 0x400ui64, "t:%d %s", *v24, v29); v30 = ASM_History::GetColor(&v39, Index); p_color = &color; color = *v30; } else { Com_sprintf(dest, 0x400ui64, "t:%d start", v23); v26 = (__int128 *)ASM_History::GetColor(&result, Index); p_color = (vec4_t *)&v41; v41 = *v26; } CL_AddDebugString(drawPos, p_color, 0.5, dest, fromServer, duration); drawPos->v[2] = drawPos->v[2] - 8.0; if ( v24[2] ) { v31 = 0i64; do { v32 = Common_Asm::Utils::GetState(pASM, **(_DWORD **)&v24[2 * v31 + 4]); v33 = SL_ConvertToString(v32->m_Name); Com_sprintf(dest, 0x400ui64, "|_> %s", v33); v43 = *ASM_History::GetColor(&v40, Index); CL_AddDebugString(drawPos, &v43, 0.5, dest, fromServer, duration); v31 = (unsigned int)(v31 + 1); drawPos->v[2] = drawPos->v[2] - 8.0; } while ( (unsigned int)v31 < v24[2] ); v19 = v37; } m_pASM = pASM; ++v21; Index = ASM_History::NextIndex(v19, Index); } while ( v21 < v35 ); } } } } /* ============== Common_Asm::Utils::EventFired ============== */ char Common_Asm::Utils::EventFired(const ASM_Instance *pInst, int numEvents, const scr_string_t eventName) { __int64 v3; __int64 v6; ASM_Event *i; v3 = numEvents; if ( numEvents > 8 && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 188, ASSERT_TYPE_ASSERT, "(numEvents <= MAX_ASM_EVENTS_PER_TABLE)", (const char *)&queryFormat, "numEvents <= MAX_ASM_EVENTS_PER_TABLE") ) __debugbreak(); if ( (int)v3 <= 0 ) return 0; v6 = 0i64; for ( i = pInst->m_EventTable; i->m_Name != eventName; ++i ) { if ( ++v6 >= v3 ) return 0; } return 1; } /* ============== Common_Asm::Utils::EventFired ============== */ char Common_Asm::Utils::EventFired(const ASM_Instance *pInst, const scr_string_t eventName) { __int64 v2; ASM_Event *i; v2 = 0i64; for ( i = pInst->m_EventTable; i->m_Name != eventName; ++i ) { if ( ++v2 >= 8 ) return 0; } return 1; } /* ============== Common_Asm::Utils::FindEventFor ============== */ ASM_Event *Common_Asm::Utils::FindEventFor(ASM_Event *eventTable, const scr_string_t eventName) { ASM_Event *v2; int m_Time; int v4; ASM_Event *v5; int v6; scr_string_t m_Name; v2 = NULL; m_Time = 0x7FFFFFFF; v4 = 0; v5 = eventTable; v6 = -1; while ( 1 ) { m_Name = v5->m_Name; if ( v5->m_Name && v5->m_Time < m_Time ) { v6 = v4; m_Time = v5->m_Time; } if ( v2 || m_Name ) break; v2 = &eventTable[v4]; LABEL_10: ++v4; ++v5; if ( v4 >= 8 ) goto LABEL_13; } if ( !eventName || m_Name != eventName ) goto LABEL_10; v2 = &eventTable[v4]; LABEL_13: if ( v2 || v6 < 0 ) return v2; else return &eventTable[v6]; } /* ============== Common_Asm::Utils::GetCurrentStateByAssetName ============== */ const ASM_State *Common_Asm::Utils::GetCurrentStateByAssetName(const ASM_Instance *pInst, scr_string_t asmName) { const ASM_Instance *v3; const ASM_State *result; v3 = pInst; if ( !pInst && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 210, ASSERT_TYPE_ASSERT, "(pInst)", (const char *)&queryFormat, "pInst") ) __debugbreak(); if ( v3->m_pASM->m_Name == asmName ) return Common_Asm::Utils::GetState(v3->m_pASM, v3->m_CurState); result = (const ASM_State *)Common_Asm::Utils::GetSubtree(v3, asmName); v3 = (const ASM_Instance *)result; if ( result ) return Common_Asm::Utils::GetState(v3->m_pASM, v3->m_CurState); return result; } /* ============== Common_Asm::Utils::GetEventTime ============== */ __int64 Common_Asm::Utils::GetEventTime(const ASM_Instance *pInst, scr_string_t eventName) { ASM_Event *m_EventTable; __int64 v5; if ( !pInst && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 239, ASSERT_TYPE_ASSERT, "(pInst)", (const char *)&queryFormat, "pInst") ) __debugbreak(); m_EventTable = pInst->m_EventTable; v5 = 0i64; while ( m_EventTable->m_Name != eventName ) { ++v5; ++m_EventTable; if ( v5 >= 8 ) return 0i64; } return (unsigned int)m_EventTable->m_Time; } /* ============== Common_Asm::Utils::GetLogicGroup ============== */ ASM_LogicGroup *Common_Asm::Utils::GetLogicGroup(const ASM *pASM, int logicID) { __int64 v2; __int64 v5; v2 = logicID; if ( !pASM && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 50, ASSERT_TYPE_ASSERT, "(pASM)", (const char *)&queryFormat, "pASM") ) __debugbreak(); if ( (unsigned int)v2 >= pASM->m_NumLogicGroups ) { LODWORD(v5) = v2; if ( CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 51, ASSERT_TYPE_ASSERT, "(unsigned)( logicID ) < (unsigned)( pASM->m_NumLogicGroups )", "logicID doesn't index pASM->m_NumLogicGroups\n\t%i not in [0, %i)", v5, pASM->m_NumLogicGroups) ) __debugbreak(); } return &pASM->m_LogicGroups[v2]; } /* ============== Common_Asm::Utils::GetState ============== */ ASM_State *Common_Asm::Utils::GetState(const ASM *pASM, int stateID) { __int64 v2; __int64 v5; v2 = stateID; if ( !pASM && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 16, ASSERT_TYPE_ASSERT, "(pASM)", (const char *)&queryFormat, "pASM") ) __debugbreak(); if ( (unsigned int)v2 >= pASM->m_NumStates ) { LODWORD(v5) = v2; if ( CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 17, ASSERT_TYPE_ASSERT, "(unsigned)( stateID ) < (unsigned)( pASM->m_NumStates )", "stateID doesn't index pASM->m_NumStates\n\t%i not in [0, %i)", v5, pASM->m_NumStates) ) __debugbreak(); } return &pASM->m_States[v2]; } /* ============== Common_Asm::Utils::GetStateTransitioningFrom ============== */ const ASM_State *Common_Asm::Utils::GetStateTransitioningFrom(const ASM_Instance *pInst) { int m_PrevState; if ( !pInst && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 227, ASSERT_TYPE_ASSERT, "(pInst)", (const char *)&queryFormat, "pInst") ) __debugbreak(); m_PrevState = pInst->m_PrevState; if ( m_PrevState == -1 ) return 0i64; else return Common_Asm::Utils::GetState(pInst->m_pASM, m_PrevState); } /* ============== Common_Asm::Utils::GetSubtree ============== */ ASM_Instance *Common_Asm::Utils::GetSubtree(const ASM_Instance *pInst, const scr_string_t subtreeName) { int v4; ASM_Instance **i; ASM_Instance *result; if ( !pInst && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 79, ASSERT_TYPE_ASSERT, "(pInst)", (const char *)&queryFormat, "pInst") ) __debugbreak(); v4 = 0; if ( pInst->m_NumSubtrees <= 0 ) return 0i64; for ( i = pInst->m_Subtrees; (*i)->m_pASM->m_Name != subtreeName; ++i ) { result = Common_Asm::Utils::GetSubtree(*i, subtreeName); if ( result ) return result; if ( ++v4 >= pInst->m_NumSubtrees ) return 0i64; } return *i; } /* ============== Common_Asm::HasState ============== */ bool Common_Asm::HasState(Common_Asm *this, const ASM *pASM, __int64 stateName) { return this->GetStateByName(this, pASM, stateName) != NULL; } /* ============== Common_Asm::Utils::LogicGroup_IsAncestorOf ============== */ char Common_Asm::Utils::LogicGroup_IsAncestorOf(const ASM *pASM, int possibleAncestorGroupID, int groupID) { unsigned int m_ParentID; ASM_LogicGroup *v6; __int64 v8; __int64 v9; m_ParentID = groupID; if ( possibleAncestorGroupID == -1 || groupID == -1 ) return 0; while ( m_ParentID != possibleAncestorGroupID ) { if ( !pASM && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 50, ASSERT_TYPE_ASSERT, "(pASM)", (const char *)&queryFormat, "pASM") ) __debugbreak(); if ( m_ParentID >= pASM->m_NumLogicGroups ) { LODWORD(v9) = pASM->m_NumLogicGroups; LODWORD(v8) = m_ParentID; if ( CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 51, ASSERT_TYPE_ASSERT, "(unsigned)( logicID ) < (unsigned)( pASM->m_NumLogicGroups )", "logicID doesn't index pASM->m_NumLogicGroups\n\t%i not in [0, %i)", v8, v9) ) __debugbreak(); } v6 = &pASM->m_LogicGroups[m_ParentID]; if ( !v6 && CoreAssert_Handler("c:\\workspace\\iw8\\code_source\\src\\bgame\\asm\\common_asm_util.cpp", 69, ASSERT_TYPE_ASSERT, "(pGroup)", (const char *)&queryFormat, "pGroup") ) __debugbreak(); m_ParentID = v6->m_ParentID; if ( m_ParentID == -1 ) return 0; } return 1; } /* ============== Common_Asm::Utils::StateHasSubtree ============== */ char Common_Asm::Utils::StateHasSubtree(const ASM_State *pState, const scr_string_t subtreeName) { __int64 v2; scr_string_t *i; if ( pState->m_NumSubtrees <= 0 ) return 0; v2 = 0i64; for ( i = pState->m_Subtrees; *i != subtreeName; ++i ) { if ( ++v2 >= pState->m_NumSubtrees ) return 0; } return 1; }
0a307fd2c73395e7e483f941eb77ae2bbffa4226
597fadca888b713cbe9eced88a3661901a908757
/Classes/Snake_fwd.h
270b752a12a204c87098a18212fd0736d3f889bb
[]
no_license
SLebedev777/CocoSnake
70d831a19603df49ba566782abf68d13eb0656f8
fc9ef8d5c7eabcbd4e34f9e0602e1ce243fe08d3
refs/heads/main
2023-04-17T02:54:20.719716
2021-05-12T08:54:00
2021-05-12T08:54:00
328,627,847
1
2
null
null
null
null
UTF-8
C++
false
false
464
h
Snake_fwd.h
#include <memory> namespace NS_Snake { class DirectedSprite; typedef std::unique_ptr<DirectedSprite> DirectedSpritePtr; class Snake; typedef std::unique_ptr<Snake> SnakePtr; class GameGrid; typedef std::shared_ptr<GameGrid> GameGridPtr; class IFood; typedef std::unique_ptr<IFood> IFoodPtr; class IFoodFactory; typedef std::unique_ptr<IFoodFactory> IFoodFactoryPtr; class FoodGenerator; typedef std::unique_ptr<FoodGenerator> FoodGeneratorPtr; }
1d6d18894b04eac87a93d3dc2387870856502a0b
98b1e51f55fe389379b0db00365402359309186a
/homework_3/case_2/60/p
6c618fa54602980732a4c6d1e001ee70ecb93363
[]
no_license
taddyb/597-009
f14c0e75a03ae2fd741905c4c0bc92440d10adda
5f67e7d3910e3ec115fb3f3dc89a21dcc9a1b927
refs/heads/main
2023-01-23T08:14:47.028429
2020-12-03T13:24:27
2020-12-03T13:24:27
311,713,551
1
0
null
null
null
null
UTF-8
C++
false
false
6,666
p
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 8 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "60"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 464 ( 2.62687e-08 1.3396e-06 6.18958e-06 1.33586e-05 2.3771e-05 3.72812e-05 5.45915e-05 7.46668e-05 0.000100567 0.000126048 0.000162946 0.000188215 -1.31798e-06 5.771e-08 5.18131e-06 1.27985e-05 2.37761e-05 3.79447e-05 5.59609e-05 7.6958e-05 0.000103821 0.000131218 0.000170029 0.000201065 -7.40529e-06 -6.61933e-06 -2.6759e-06 3.1519e-06 1.20786e-05 2.40841e-05 3.97474e-05 5.87826e-05 8.29171e-05 0.000109043 0.000142842 0.000174457 -1.41355e-05 -1.28204e-05 -7.66933e-06 -1.94692e-07 1.05189e-05 2.44467e-05 4.21107e-05 6.34654e-05 8.99411e-05 0.000119618 0.0001566 0.000194265 -2.94655e-05 -2.96848e-05 -2.70174e-05 -2.33096e-05 -1.6481e-05 -6.79518e-06 6.72191e-06 2.43505e-05 4.69766e-05 7.42497e-05 0.000107819 0.000145685 -3.32179e-05 -3.25863e-05 -2.86429e-05 -2.27963e-05 -1.40255e-05 -2.16691e-06 1.34684e-05 3.35295e-05 5.88183e-05 8.99079e-05 0.000127505 0.000172699 -6.78869e-05 -6.97021e-05 -6.81202e-05 -6.80598e-05 -6.38342e-05 -5.82661e-05 -4.81743e-05 -3.35883e-05 -1.33458e-05 1.42992e-05 4.70998e-05 9.49645e-05 -5.56591e-05 -5.63039e-05 -5.51944e-05 -5.27048e-05 -4.86503e-05 -4.14657e-05 -3.12518e-05 -1.54605e-05 5.16224e-06 3.62674e-05 7.1065e-05 0.000126701 -0.000118773 -0.000124014 -0.000123413 -0.000131249 -0.000130014 -0.000133262 -0.000128942 -0.000120899 -0.000108513 -8.02847e-05 -5.76763e-05 4.70098e-06 -7.83854e-05 -8.07339e-05 -8.4937e-05 -8.71428e-05 -9.26094e-05 -9.27104e-05 -9.50898e-05 -8.60953e-05 -8.13045e-05 -5.03167e-05 -3.35788e-05 3.7228e-05 -0.000174298 -0.000186635 -0.000186859 -0.000210425 -0.000212954 -0.000233554 -0.000238325 -0.000243941 -0.000248115 -0.000224973 -0.000226315 -0.000153667 -9.63451e-05 -0.0001007 -0.000113987 -0.000121122 -0.0001439 -0.000152227 -0.000180223 -0.000179223 -0.000208802 -0.000179951 -0.000207654 -0.000123236 -0.000218447 -0.000246232 -0.000246918 -0.000300372 -0.000307476 -0.000357947 -0.000376097 -0.000406141 -0.000437005 -0.000430284 -0.000477416 -0.000405368 -0.000101986 -0.000110843 -0.000135733 -0.000147911 -0.000195001 -0.000214281 -0.000281003 -0.000292808 -0.000375882 -0.000358215 -0.000459059 -0.000378478 -0.000215229 -0.000282527 -0.00028486 -0.000394843 -0.00040695 -0.000503049 -0.00053762 -0.00060331 -0.000668082 -0.000693665 -0.000802768 -0.000760166 -8.60421e-05 -0.000114821 -0.00014359 -0.000159809 -0.000230889 -0.000267993 -0.000382806 -0.000416291 -0.000564018 -0.000573078 -0.000754747 -0.000712395 -6.20444e-05 -0.000257452 -0.000284593 -0.000498494 -0.000516032 -0.000666638 -0.000717025 -0.000823002 -0.000916087 -0.000994119 -0.001125 -0.00117238 -5.39582e-05 -0.000165982 -0.000154405 -0.000144978 -0.000220244 -0.000290905 -0.000465464 -0.000533561 -0.000745695 -0.000800247 -0.00101241 -0.00105062 0.000449129 -0.000284121 -0.000295069 -0.000673391 -0.000634664 -0.000836986 -0.000901917 -0.00104899 -0.00115164 -0.00133129 -0.00131441 -0.00163821 -0.00108193 0.000281553 0.000169565 -1.13063e-05 -0.000203193 -0.000299107 -0.000635578 -0.000725854 -0.000986007 -0.00109314 -0.001236 -0.00136576 0.00024122 0.000267704 0.000296224 0.00031759 0.000337835 0.000352971 0.00036407 0.000368782 0.000259975 0.000289046 0.000322986 0.000347535 0.000370787 0.000388426 0.000401143 0.000406703 0.000216538 0.00025153 0.000289379 0.000323947 0.000354727 0.000381222 0.00039909 0.000408064 0.000242223 0.000284488 0.000328202 0.00036888 0.000404966 0.000437105 0.000458416 0.00046963 0.000188151 0.000237257 0.000284998 0.000341501 0.000385016 0.000434753 0.000462071 0.000481722 0.000224589 0.000283127 0.000339451 0.000407238 0.000459769 0.00052228 0.000556313 0.000583222 0.00013704 0.000211608 0.000266802 0.000366038 0.000425033 0.000526238 0.000568889 0.000618462 0.000181733 0.00026904 0.000336377 0.000455375 0.00052977 0.000660057 0.000717469 0.000790884 3.88372e-05 0.000148605 0.000203413 0.000378095 0.000454718 0.000668628 0.000742389 0.000884735 7.24279e-05 0.000209586 0.000273915 0.00048329 0.000582473 0.000860687 0.000971273 0.00119811 -0.000147629 3.93243e-06 2.75759e-05 0.000318305 0.000393271 0.000842024 0.000987059 0.00144465 -0.000144958 3.86314e-05 4.6546e-05 0.000395085 0.000482505 0.00105522 0.00129411 0.0020472 -0.000476798 -0.000274972 -0.000378765 4.3816e-05 -3.546e-05 0.000821392 0.00103423 0.00250112 -0.000513978 -0.000305152 -0.000499761 -3.34086e-05 -0.000259758 0.000749915 0.000675318 0.0027951 -0.000972265 -0.00076416 -0.00120541 -0.000658414 -0.00155743 -0.000335229 -0.00246179 0.000877101 -0.000990753 -0.000831511 -0.00139007 -0.000981726 -0.00231662 -0.00113523 -0.00465224 -0.00101879 -0.00147066 -0.00131966 -0.00211814 -0.00162635 -0.00310172 -0.00236482 -0.00456503 -0.0018991 -0.00133341 -0.00132539 -0.00187045 -0.00198263 -0.00304424 -0.00390931 -0.00545956 -0.000899429 -0.00170268 -0.00168963 -0.00273685 -0.00221223 -0.00425768 -0.00552188 -0.00624249 0.00155654 -0.00151652 -0.00150561 -0.00195266 -0.00189353 -0.00198443 -0.000473919 0.00331762 0.0187379 0.000329587 0.000330107 0.000331406 0.000332909 0.000334675 0.000336141 0.000337341 0.000337813 0.000331661 0.000332234 0.000333603 0.000335206 0.000336978 0.00033844 0.000339619 0.00034008 0.000325067 0.000325894 0.000327924 0.000330156 0.000332871 0.00033506 0.000336871 0.000337574 0.000331064 0.000332184 0.000334569 0.000337319 0.000340182 0.000342513 0.000344355 0.000345075 0.000315602 0.000317648 0.000321997 0.000326487 0.000331788 0.000335893 0.00033924 0.000340536 0.000325748 0.000328722 0.00033387 0.000339544 0.000345189 0.000349724 0.000353229 0.000354614 0.000294676 0.000301253 0.000311832 0.000321709 0.000332429 0.000340458 0.000346741 0.000349229 0.000308101 0.000318227 0.00033036 0.000342364 0.000353984 0.000363059 0.000369893 0.000372671 ) ; boundaryField { movingWall { type zeroGradient; } fixedWalls { type zeroGradient; } frontAndBack { type empty; } } // ************************************************************************* //
6fe39b1a84f043a82affa4f45b38e0be9b1af1c9
f84040cfa2477b5a09e17afde80eb19db43e84ec
/191 - Intersection.cpp
40a859e9a92ee18841701c8287b271f094e12601
[]
no_license
sbswarna/UVA
e2714047d5e4fa38a52c9ca33ff1c226079f8521
44dd179c1775dfc21c20fb6041cfc099dc34a0c2
refs/heads/main
2023-04-21T05:50:32.690008
2021-05-01T04:22:50
2021-05-01T04:22:50
347,542,297
0
0
null
null
null
null
UTF-8
C++
false
false
3,451
cpp
191 - Intersection.cpp
#include<bits/stdc++.h> using namespace std; int main() { long long tst; double x1,y1,a1,a2,b1,b2,p1,p2,p3,p4,q1,q2,q3,q4,x2,y2; cin>>tst; while(tst--) { cin>>x1>>y1>>x2>>y2>>a1>>b1>>a2>>b2; double a,b,c,d; if(a1>a2) { a=a2; b=a1; } else { a=a1; b=a2; } if(b1>b2) { c=b1; d=b2; } else { c=b2; d=b1; } // printf("a=%.3lf b=%.3lf c=%.3lf d=%.3lf\n",a,b,c,d); long long f=0; double m,n; if(x1>=a&&x1<=b&&x2>=a&&x2<=b&&y1>=d&&y1<=c&&y2>=d&&y2<=c) { f=1; } if(x1==x2&&y1==y2) { if(x1>=a&&x1<=b&&y1>=d&&y1<=c) { f=1; } } else { m=(y1-y2); n=(x1-x2); if(y1!=y2) { q1=b1; p1=((((q1-y1)/(m))*n)+x1); if(p1>=a&&p1<=b&&q1>=d&&q1<=c) { double x,y,z; x=pow((((x1-p1)*(x1-p1))+((y1-q1)*(y1-q1))),0.5); y=pow((((x2-p1)*(x2-p1))+((y2-q1)*(y2-q1))),0.5); z=pow((((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2))),0.5); if(x<=z&&y<=z) f=1; } //printf("%.3lf %.3lf\n",p1,q1); //cout<<f<<endl; } if(x1!=x2) { p2=a2; q2=((((p2-x1)/n)*m)+y1); if(p2>=a&&p2<=b&&q2>=d&&q2<=c) { double x,y,z; x=pow((((x1-p2)*(x1-p2))+((y1-q2)*(y1-q2))),0.5); y=pow((((x2-p2)*(x2-p2))+((y2-q2)*(y2-q2))),0.5); z=pow((((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2))),0.5); if(x<=z&&y<=z) f=1; } // printf("%.3lf %.3lf\n",p2,q2); //cout<<f<<endl; } if(y1!=y2) { q3=b2; p3=((((q3-y1)/(m))*n)+x1); if(p3>=a&&p3<=b&&q3>=d&&q3<=c) { double x,y,z; x=pow((((x1-p3)*(x1-p3))+((y1-q3)*(y1-q3))),0.5); y=pow((((x2-p3)*(x2-p3))+((y2-q3)*(y2-q3))),0.5); z=pow((((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2))),0.5); if(x<=z&&y<=z) f=1; } // printf("%.3lf %.3lf\n",p3,q3); //cout<<f<<endl; } if(x1!=x2) { p4=a1; q4=((((p4-x1)/n)*m)+y1); if(p4>=a&&p4<=b&&q4>=d&&q4<=c) { double x,y,z; x=pow((((x1-p4)*(x1-p4))+((y1-q4)*(y1-q4))),0.5); y=pow((((x2-p4)*(x2-p4))+((y2-q4)*(y2-q4))),0.5); z=pow((((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2))),0.5); if(x<=z&&y<=z) f=1; } // printf("%.3lf %.3lf\n",p4,q4); //cout<<f<<endl; } } if(f==1) { cout<<"T"<<endl; } else { cout<<"F"<<endl; } } return 0; }
926d4e463c788f30985e14d8c2058ef1c182e44e
2765d0a19de9e401cc086e5cacebbb4b83ebdd41
/src/gcli/xrc/DataGridDlg.cpp
7265d9273bb7d248d8e02da0bda94b938491926c
[]
no_license
mcejp/602sql11
d449eeda9194dc08422c0d544384f91fbcd83480
38915304dc33c818c8823d4f70d99ac729dca6c8
refs/heads/master
2020-03-30T03:40:45.755487
2008-08-06T07:28:57
2018-09-28T07:28:57
150,702,131
0
1
null
null
null
null
UTF-8
C++
false
false
4,374
cpp
DataGridDlg.cpp
///////////////////////////////////////////////////////////////////////////// // Name: DataGridDlg.cpp // Purpose: // Author: // Modified by: // Created: 12/15/06 09:38:36 // RCS-ID: // Copyright: // Licence: ///////////////////////////////////////////////////////////////////////////// #if defined(__GNUG__) && !defined(__APPLE__) //#pragma implementation "DataGridDlg.h" #endif // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif ////@begin includes ////@end includes #include "DataGridDlg.h" ////@begin XPM images ////@end XPM images /*! * DataGridDlg type definition */ IMPLEMENT_DYNAMIC_CLASS( DataGridDlg, wxDialog ) /*! * DataGridDlg event table definition */ BEGIN_EVENT_TABLE( DataGridDlg, wxDialog ) ////@begin DataGridDlg event table entries EVT_BUTTON( wxID_CLOSE, DataGridDlg::OnCloseClick ) ////@end DataGridDlg event table entries END_EVENT_TABLE() /*! * DataGridDlg constructors */ DataGridDlg::DataGridDlg( ) { } DataGridDlg::DataGridDlg(cdp_t cdpIn, wxString captIn, const char * queryIn, const char * formdefIn) { cdp=cdpIn; capt=captIn; query=queryIn; formdef=formdefIn; } /*! * DataGridDlg creator */ bool DataGridDlg::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { ////@begin DataGridDlg member initialisation mGridSizer = NULL; mGrid = NULL; ////@end DataGridDlg member initialisation ////@begin DataGridDlg creation SetExtraStyle(GetExtraStyle()|wxWS_EX_BLOCK_EVENTS); wxDialog::Create( parent, id, caption, pos, size, style ); CreateControls(); GetSizer()->Fit(this); GetSizer()->SetSizeHints(this); Centre(); ////@end DataGridDlg creation return TRUE; } /*! * Control creation for DataGridDlg */ void DataGridDlg::CreateControls() { ////@begin DataGridDlg content construction DataGridDlg* itemDialog1 = this; wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL); itemDialog1->SetSizer(itemBoxSizer2); mGridSizer = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer2->Add(mGridSizer, 1, wxGROW|wxALL, 0); mGrid = new wxStaticText; mGrid->Create( itemDialog1, CD_DGD_PLACEHOLDER, _("Static text"), wxDefaultPosition, wxDefaultSize, 0 ); mGridSizer->Add(mGrid, 0, wxALIGN_CENTER_VERTICAL|wxALL|wxADJUST_MINSIZE, 5); wxBoxSizer* itemBoxSizer5 = new wxBoxSizer(wxHORIZONTAL); itemBoxSizer2->Add(itemBoxSizer5, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 0); wxButton* itemButton6 = new wxButton; itemButton6->Create( itemDialog1, wxID_CLOSE, _("&Close"), wxDefaultPosition, wxDefaultSize, 0 ); itemBoxSizer5->Add(itemButton6, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); ////@end DataGridDlg content construction SetWindowStyleFlag(GetWindowStyleFlag() & ~wxTAB_TRAVERSAL); // otherwise Enter in the grid cell editors focuses the Close button (makes it the default button) SetTitle(capt); tcursnum cursnum; if (cd_SQL_execute(cdp, query, (uns32*)&cursnum)) { cd_Signalize2(cdp, this); return; } grid = new DataGrid(cdp); if (!grid) return; grid->translate_captions=true; if (!grid->open_form(this, cdp, formdef, cursnum, AUTO_CURSOR|CHILD_VIEW)) // deletes the grid on error, closes the cursor return; mGrid->Destroy(); mGridSizer->Prepend(grid, 1, wxGROW|wxALL, 0); mGridSizer->SetItemMinSize(grid, get_grid_width(grid), get_grid_height(grid, 7)); } /*! * Should we show tooltips? */ bool DataGridDlg::ShowToolTips() { return TRUE; } /*! * Get bitmap resources */ wxBitmap DataGridDlg::GetBitmapResource( const wxString& name ) { // Bitmap retrieval ////@begin DataGridDlg bitmap retrieval return wxNullBitmap; ////@end DataGridDlg bitmap retrieval } /*! * Get icon resources */ wxIcon DataGridDlg::GetIconResource( const wxString& name ) { // Icon retrieval ////@begin DataGridDlg icon retrieval return wxNullIcon; ////@end DataGridDlg icon retrieval } /*! * wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_CLOSE */ void DataGridDlg::OnCloseClick( wxCommandEvent& event ) { if (grid->IsCellEditControlEnabled()) grid->DisableCellEditControl(); if (grid->dgt->write_changes(OWE_CONT_OR_IGNORE)) EndModal(1); }
7e20bba61d5a76b36a7b3f4801ebb848c9e298b8
9f2e63f56c50aadabfebde6cb7d81c3e9d961651
/baekjoon/1181_2.cpp
40e954a898941a7ac2dfc9a285885e81bcb83ebb
[]
no_license
boomini/Algorithm
a797b3f0d34af7f7e830c1d971d7f463556c2de2
35a24200f57e6e3aeffa699133cd82ce9d5fde0d
refs/heads/master
2021-03-25T15:35:54.273035
2020-07-26T12:29:02
2020-07-26T12:29:02
247,629,753
0
0
null
null
null
null
UTF-8
C++
false
false
435
cpp
1181_2.cpp
#include <iostream> #include <algorithm> using namespace std; string word[20001]; int n; bool compare(string a, string b){ if(a.length()==b.length()) return a<b; else return a.length()<b.length(); } int main(void){ cin >> n; for(int i=0; i<n; i++){ cin >> word[i]; } sort(word,word+n,compare); for(int i=0; i<n; i++){ if(i>0 && word[i] == word[i-1]){ continue; }else{ cout << word[i] << "\n"; } } }
b2d3d6343f545b788bc5ae0a4d663dd537d76364
ae8ef15e88056158342007fc1795bdf187cb7eb3
/Device/FanController.ino
a225382fdb999bc0f45e245798b75f017b933d08
[]
no_license
zhoujh202020/InternetConnectedFan
8719e87296e500aaa1117668a1bc29e46aea574d
b836561c70b17cf2899213860aa49f922dc6ff90
refs/heads/master
2020-09-23T18:22:48.343217
2019-02-05T20:02:26
2019-02-05T20:02:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,941
ino
FanController.ino
#include "Arduino.h" #include "AZ3166WiFi.h" #include "DevKitMQTTClient.h" #include "SystemVersion.h" #include "Sensor.h" #include "parson.h" #include "PinNames.h" static bool hasWifi = false; static void initWifi() { Screen.print(2, "Connecting..."); if (WiFi.begin() == WL_CONNECTED) { IPAddress ip = WiFi.localIP(); Screen.print(1, ip.get_address()); hasWifi = true; Screen.print(2, "\r\n"); Screen.print(3, "Running... \r\n"); } else { hasWifi = false; Screen.print(1, "No Wi-Fi\r\n "); } } DevI2C *ext_i2c; HTS221Sensor *ht_sensor; RGB_LED rgbLed; static float temperature = 50; static int temperatureThreshold = 100; void initSensor() { ext_i2c = new DevI2C(D14, D15); ht_sensor = new HTS221Sensor(*ext_i2c); ht_sensor->init(NULL); } void getSensorData() { try { ht_sensor->enable(); ht_sensor->getTemperature(&temperature); ht_sensor->disable(); ht_sensor->reset(); char buff[128]; sprintf(buff, "Temp:%sC\r\n", f2s(temperature, 1)); Screen.print(1, buff); sprintf(buff, "Threshold:%sC\r\n", f2s(temperatureThreshold, 1)); Screen.print(2, buff); } catch(int error) { Screen.print(1, "Sensor error\r\n "); } } void parseTwinMessage(DEVICE_TWIN_UPDATE_STATE updateState, const char *message) { JSON_Value *root_value; root_value = json_parse_string(message); if (json_value_get_type(root_value) != JSONObject) { if (root_value != NULL) { json_value_free(root_value); } LogError("parse %s failed", message); return; } JSON_Object *root_object = json_value_get_object(root_value); if (updateState == DEVICE_TWIN_UPDATE_COMPLETE) { JSON_Object *desired_object = json_object_get_object(root_object, "desired"); if (desired_object != NULL) { if (json_object_has_value(desired_object, "temperatureThreshold")) { temperatureThreshold = json_object_get_number(desired_object, "temperatureThreshold"); } } } else { if (json_object_has_value(root_object, "temperatureThreshold")) { temperatureThreshold = json_object_get_number(root_object, "temperatureThreshold"); } } json_value_free(root_value); } static void DeviceTwinCallback(DEVICE_TWIN_UPDATE_STATE updateState, const unsigned char *payLoad, int size) { char *temp = (char *)malloc(size + 1); if (temp == NULL) { return; } memcpy(temp, payLoad, size); temp[size] = '\0'; parseTwinMessage(updateState, temp); free(temp); } void setup() { rgbLed.turnOff(); Screen.init(); Screen.print(0, "IoT Fan"); Screen.print(2, "Initializing..."); Screen.print(3, " > WiFi"); hasWifi = false; initWifi(); if (!hasWifi) { return; } initSensor(); Screen.print(3, " > IoT Hub"); DevKitMQTTClient_Init(true); DevKitMQTTClient_SetDeviceTwinCallback(DeviceTwinCallback); Screen.print(3, " "); pinMode(PB_0, OUTPUT); } void sendData(const char *data) { time_t t = time(NULL); char buf[sizeof "2011-10-08T07:07:09Z"]; strftime(buf, sizeof buf, "%FT%TZ", gmtime(&t)); EVENT_INSTANCE* message = DevKitMQTTClient_Event_Generate(data, MESSAGE); DevKitMQTTClient_Event_AddProp(message, "$$CreationTimeUtc", buf); DevKitMQTTClient_Event_AddProp(message, "$$MessageSchema", "fan-sensors;v1"); DevKitMQTTClient_Event_AddProp(message, "$$ContentType", "JSON"); DevKitMQTTClient_SendEventInstance(message); } void loop() { getSensorData(); char sensorData[200]; sprintf_s(sensorData, sizeof(sensorData), "{\"temperature\":%s,\"temperature_unit\":\"C\"}", f2s(temperature, 1)); sendData(sensorData); if (temperature >= temperatureThreshold) { rgbLed.setColor(255, 0, 0); digitalWrite(PB_0, HIGH); } else { rgbLed.setColor(0, 0, 255); digitalWrite(PB_0, LOW); } delay(5000); }
5be2a23a034ae54a61f2bb8b1d39c6edc20b4ff4
5812abcca9432a9e9135fd1bb84e1ab3214b98a5
/export.cpp
803be816d70c4b81e49bf08b95327bb063edc040
[]
no_license
lintean/CClassSchedule
0f61c005ac12e2b1cf63607057156343f8a8c651
d0c50afc08bda26f3687b5d0d5326c91d7e8ea76
refs/heads/master
2020-03-18T14:37:37.854298
2018-06-05T14:35:26
2018-06-05T14:35:26
134,857,669
0
0
null
null
null
null
UTF-8
C++
false
false
1,756
cpp
export.cpp
#include "export.h" #include<QString> #include<QVector> #include<QFile> #include<QDir> #include<QDebug> #include<fstream> Export::Export() { } bool Export::copyFileToPath(QString sourceDir ,QString toDir, bool coverFileIfExist) { toDir.replace("\\","/"); //如果选择目录和当前目录相同 if (sourceDir == toDir){ return true; } if (!QFile::exists(sourceDir)){ return false; } QDir *createfile = new QDir; //如果已经存在则删除原本的文件 bool exist = createfile->exists(toDir); if (exist){ if(coverFileIfExist){ createfile->remove(toDir); } }//end if if(!QFile::copy(sourceDir, toDir)) { return false; } return true; } bool Export::searchSchedule(QString ID,QVector<QString> &buf_out ) { ifstream file ; string buf; QString Qbuf; file.open("table.txt"); char buffer[100]; while(!file.eof()) { file.getline(buffer,100); buf = string(buffer); Qbuf = QString::fromStdString(buf); qDebug()<<Qbuf; if(Qbuf.contains("id "+ID)) { for(int i = 0 ; i<5; i++) { //日后课程名称过长的时候出现bug则与此大小有关 char temp_c[300]; string temp_s; file.getline(temp_c,300); temp_s = string(temp_c); buf_out.append(QString::fromStdString(temp_s)); qDebug()<<QString::fromStdString(temp_s)<<endl; } qDebug()<<buf_out; qDebug()<<buf_out.size(); return true; } } return false; }
448d74783416c8fe735859eaea659070274dd1d1
b5d4374a078069ea1330251d987b14a538721a6d
/Group.h
47a68034039a336c9910738b5def1a60715450a5
[]
no_license
sanjaydm/OOGSL
3f198881456cd33202e4d6b66ca2786d4907b523
2bace4f73567b410a30a2afc14d2177c72f34028
refs/heads/master
2022-04-10T11:20:32.061434
2020-03-31T14:12:18
2020-03-31T14:12:18
171,889,319
0
0
null
null
null
null
UTF-8
C++
false
false
1,744
h
Group.h
#ifndef GROUP_H #define GROUP_H #include "Vector.h" #include <vector> #include "Matrix.h" class Group{ public: vector<Matrix> _g; vector<Matrix> _gen; Group(); void constructGroup(){;} int order() {return _g.size();} int numGenerators() {return _gen.size();} void listElements(); }; class Cyclic: public Group{ public: int _n; Cyclic(int n); Cyclic(int n, Matrix gen); void constructGroup(); }; class Icosahedral: public Group{ public: Matrix _g2; Matrix _g3; Icosahedral(Matrix g2, Matrix g3); void constructGroup(); }; class D2: public Group{ public: Matrix _g2; Matrix _g22; D2(Matrix g2, Matrix g22); void constructGroup(); }; class D3: public Group{ public: Matrix _g2; Matrix _g3; D3(Matrix g2, Matrix g3); void constructGroup(); }; class D4: public Group{ public: Matrix _g2; Matrix _g4; D4(Matrix g2, Matrix g4); void constructGroup(); }; class D5: public Group{ public: Matrix _g2d; Matrix _g5; D5(Matrix g2d, Matrix g5); void constructGroup(); }; class D6: public Group{ public: Matrix _g2; Matrix _g6; D6(Matrix g2, Matrix g6); void constructGroup(); }; class D8: public Group{ public: Matrix _g2; Matrix _g8; D6(Matrix g2, Matrix g8); void constructGroup(); }; class D9: public Group{ public: Matrix _g2; Matrix _g9; D9(Matrix g2, Matrix g9); void constructGroup(); }; class Tetrahedral: public Group{ public: Matrix _g2; Matrix _g3d; Tetrahedral(Matrix g2, Matrix g3d); void constructGroup(); }; class Projection{ public: Group _group; Matrix _P; Projection() {;}; Projection(Group group); void computeProjection(); }; #endif
240ab4eb9f158e3ad9419719e697082ee3fa35de
92754bb891a128687f3fbc48a312aded752b6bcd
/Algorithms/C++/238-Product_of_Array_Except_Self.cpp
b3e9a484f98113df8a7864dfd4c422c5d543f5e1
[]
no_license
daidai21/Leetcode
ddecaf0ffbc66604a464c3c9751f35f3abe5e7e5
eb726b3411ed11e2bd00fee02dc41b77f35f2632
refs/heads/master
2023-03-24T21:13:31.128127
2023-03-08T16:11:43
2023-03-08T16:11:43
167,968,602
8
3
null
null
null
null
UTF-8
C++
false
false
620
cpp
238-Product_of_Array_Except_Self.cpp
// Runtime: 40 ms, faster than 82.80% of C++ online submissions for Product of Array Except Self. // Memory Usage: 12.4 MB, less than 98.48% of C++ online submissions for Product of Array Except Self. class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> res(nums.size(), 0); res[0] = 1; for (int i = 1; i < nums.size(); ++i) res[i] = nums[i - 1] * res[i - 1]; int tmp = 1; for (int i = nums.size() - 1; i >= 0; --i) { res[i] *= tmp; tmp *= nums[i]; } return res; } };
df8d94e6aaf8693aa079b97efd4750542d0bf414
5d3832a7b1b4916fbbcb2d540ae0412cf41c4320
/CG/HW5/HW5.cpp
414f54da0490f3824d6cca626e024957a53a24fc
[]
no_license
hhyx/CG
e150d7966cc00118b90c66156ad3fd44cf031b68
90a166692ed682e6d8332b9659beb2723522953a
refs/heads/master
2020-05-07T08:49:39.062857
2019-05-23T10:35:37
2019-05-23T10:35:37
180,348,119
0
0
null
null
null
null
GB18030
C++
false
false
9,239
cpp
HW5.cpp
#include "HW5.h" // 顶点着色器 const char *HW5vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "layout (location = 1) in vec3 aColor;\n" "out vec3 ourColor;\n" "uniform mat4 model;" "uniform mat4 view;" "uniform mat4 projection; " "void main()\n" "{\n" " gl_Position = projection * view * model * vec4(aPos, 1.0);\n" " ourColor = aColor;\n " "}\0"; // 片段着色器 const char *HW5fragmentShaderSource = "#version 330 core\n" "out vec4 FragColor;\n" "in vec3 ourColor;\n" "void main()\n" "{\n" " FragColor = vec4(ourColor, 1.0);\n" "}\n\0"; float HW5vertices[] = { // coordinate // color 2.0f, 2.0f, 2.0f, 1.0f, 0.0f, 0.0f, 2.0f, 2.0f, -2.0f, 0.0f, 1.0f, 0.0f, 2.0f, -2.0f, 2.0f, 0.0f, 0.0f, 1.0f, 2.0f, -2.0f, -2.0f, 1.0f, 1.0f, 0.0f, -2.0f, 2.0f, 2.0f, 1.0f, 0.0f, 1.0f, -2.0f, 2.0f, -2.0f, 0.0f, 1.0f, 1.0f, -2.0f, -2.0f, 2.0f, 0.5f, 0.5f, 1.0f, -2.0f, -2.0f, -2.0f, 0.5f, 1.0f, 0.5f }; unsigned int HW5indices[] ={ 0, 1, 2, 1, 2, 3, 1, 3, 5, 3, 5, 7, 0, 1, 5, 0, 4, 5, 4, 5, 7, 4, 6, 7, 0, 2, 4, 2, 4, 6, 2, 3, 7, 2, 6, 7 }; HW5::HW5() { HW5LinkShader(); draw(); } HW5::~HW5() { glDeleteProgram(shaderProgram); glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); } void HW5::HW5LinkShader() { // 顶点着色器 unsigned int vertexShader; vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &HW5vertexShaderSource, NULL); glCompileShader(vertexShader); // 检查顶点着色器出错 int success; char infoLog[521]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl; } // 片段着色器 unsigned int fragmentShader; fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &HW5fragmentShaderSource, NULL); glCompileShader(fragmentShader); // 检查片段着色器出错 glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog); std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl; } // 链接着色器 unsigned int shaderProgram_; shaderProgram_ = glCreateProgram(); glAttachShader(shaderProgram_, vertexShader); glAttachShader(shaderProgram_, fragmentShader); glLinkProgram(shaderProgram_); // 链接后删除无用的着色器 glDeleteShader(vertexShader); glDeleteShader(fragmentShader); // 检查链接着色器出错 glGetProgramiv(shaderProgram_, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; } shaderProgram = shaderProgram_; } unsigned int HW5::getShaderProgram() { return shaderProgram; } void HW5::draw() { glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(HW5vertices), HW5vertices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(HW5indices), HW5indices, GL_STATIC_DRAW); glUseProgram(shaderProgram); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0); glEnable(GL_DEPTH_TEST); } void HW5::cube() { glBindVertexArray(VAO); glm::mat4 model = glm::mat4(1.0f); model = glm::rotate(model, glm::radians(45.0f), glm::vec3(1.0f, 1.0f, 1.0f)); model = glm::scale(model, glm::vec3(0.25, 0.25, 0.25)); model = glm::translate(model, glm::vec3(-1.5, 0.5f, -1.5f)); glm::mat4 view = glm::mat4(1.0f); view = glm::translate(view, glm::vec3(0.0f, 0.0f, -5.0f)); glm::mat4 projection = glm::mat4(1.0f); projection = glm::perspective(glm::radians(45.0f), (float)800 / 600, 0.1f, 100.0f); int modelLoc = glGetUniformLocation(shaderProgram, "model"); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); int viewLoc = glGetUniformLocation(shaderProgram, "view"); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); int projectionLoc = glGetUniformLocation(shaderProgram, "projection"); glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection)); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0); } void HW5::projection(float left, float right, float bottom, float top, float znear, float zfar, bool flag) { glBindVertexArray(VAO); glm::mat4 model = glm::mat4(1.0f); model = glm::rotate(model, glm::radians(45.0f), glm::vec3(1.0f, 1.0f, 1.0f)); model = glm::scale(model, glm::vec3(0.25, 0.25, 0.25)); model = glm::translate(model, glm::vec3(-1.5, 0.5f, -1.5f)); glm::mat4 view = glm::mat4(1.0f); view = glm::translate(view, glm::vec3(0.0f, 0.0f, -5.0f)); glm::mat4 projection = glm::mat4(1.0f); if (flag) { projection = glm::ortho(left, right, bottom, top, znear, zfar); } else { projection = glm::perspective(glm::radians(45.0f), (top-bottom)/(right-left), znear, zfar); } int modelLoc = glGetUniformLocation(shaderProgram, "model"); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); int viewLoc = glGetUniformLocation(shaderProgram, "view"); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); int projectionLoc = glGetUniformLocation(shaderProgram, "projection"); glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection)); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0); } void HW5::viewChange() { glBindVertexArray(VAO); glm::mat4 model = glm::mat4(1.0f); model = glm::scale(model, glm::vec3(0.25, 0.25, 0.25)); glm::mat4 view = glm::mat4(1.0f); float radius = 5.0f; float camX = float(sin(glfwGetTime()) * radius); float camZ = float(cos(glfwGetTime()) * radius); view = glm::lookAt(glm::vec3(camX, 0.0, camZ), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0)); glm::mat4 projection = glm::mat4(1.0f); projection = glm::perspective(glm::radians(45.0f), (float)800 / 600, 0.1f, 100.0f); int modelLoc = glGetUniformLocation(shaderProgram, "model"); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); int viewLoc = glGetUniformLocation(shaderProgram, "view"); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); int projectionLoc = glGetUniformLocation(shaderProgram, "projection"); glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection)); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0); model = glm::mat4(1.0f); model = glm::rotate(model, glm::radians(45.0f), glm::vec3(1.0f, 1.0f, 1.0f)); model = glm::scale(model, glm::vec3(0.25, 0.25, 0.25)); model = glm::translate(model, glm::vec3(0.0f, 0.0f, -5.0f)); model = glm::translate(model, glm::vec3(-1.5, 0.5f, -1.5f)); view = glm::mat4(1.0f); view = glm::lookAt(glm::vec3(camX, 0.0, camZ), glm::vec3(0.0, 0.0, 0.0), glm::vec3(0.0, 1.0, 0.0)); projection = glm::mat4(1.0f); projection = glm::perspective(glm::radians(45.0f), (float)800 / 600, 0.1f, 100.0f); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection)); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0); } void HW5::useCamera(Camera camera) { glBindVertexArray(VAO); glm::mat4 model = glm::mat4(1.0f); model = glm::scale(model, glm::vec3(0.25, 0.25, 0.25)); glm::mat4 view = glm::mat4(1.0f); view = camera.GetViewMatrix(); glm::mat4 projection = glm::mat4(1.0f); projection = glm::perspective(glm::radians(camera.getZoom()), (float)800 / (float)600, 0.1f, 100.0f); int modelLoc = glGetUniformLocation(shaderProgram, "model"); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); int viewLoc = glGetUniformLocation(shaderProgram, "view"); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); int projectionLoc = glGetUniformLocation(shaderProgram, "projection"); glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection)); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0); model = glm::mat4(1.0f); model = glm::rotate(model, glm::radians(45.0f), glm::vec3(1.0f, 1.0f, 1.0f)); model = glm::scale(model, glm::vec3(0.25, 0.25, 0.25)); model = glm::translate(model, glm::vec3(0.0f, 0.0f, -5.0f)); model = glm::translate(model, glm::vec3(-1.5, 0.5f, -1.5f)); view = glm::mat4(1.0f); view = camera.GetViewMatrix(); projection = glm::mat4(1.0f); projection = glm::perspective(glm::radians(camera.getZoom()), (float)800 / (float)600, 0.1f, 100.0f); glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model)); glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(projection)); glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0); }
d48f04094d92250386966ede72c633a964633c2a
9e1cb2701686a2951eab65709cf49685a8334c29
/worker/threadpoolbase.cpp
d56ab3e7f967e08a078ac736fc8bac19ae2593d4
[ "BSD-2-Clause" ]
permissive
snewell/bureaucracy
c435454ac4a57eb11bf0fcd5beec230a46361b11
4932b0093c29698715ddb04829c1adaa3dc2aa3c
refs/heads/master
2020-05-22T06:44:58.596971
2018-10-20T05:54:00
2018-10-20T05:54:00
61,495,357
0
0
null
null
null
null
UTF-8
C++
false
false
3,326
cpp
threadpoolbase.cpp
#include <bureaucracy/threadpoolbase.hpp> #include <algorithm> #include <houseguest/synchronize.hpp> using bureaucracy::ThreadpoolBase; namespace { void threadWorker(bool & accepting, std::condition_variable & workReady, std::mutex & mutex, std::vector<bureaucracy::Worker::Work> & work) { houseguest::synchronize_unique( mutex, [&accepting, &workReady, &work](auto lock) { while(accepting) { while(!work.empty()) { auto nextItem = work.front(); work.erase(std::begin(work)); lock.unlock(); nextItem(); lock.lock(); } if(accepting) { // we may have stopped while calling the work functions, // check before waiting workReady.wait(lock); } } }); } } // namespace /// \cond false ThreadpoolBase::ThreadpoolBase(std::size_t maxThreads) : my_isAccepting{true} , my_isRunning{true} { if(maxThreads == 0) { throw std::invalid_argument{"Invalid thread count"}; } my_threads.reserve(maxThreads); } /// \cond false ThreadpoolBase::~ThreadpoolBase() noexcept { stop(); } /// \endcond void ThreadpoolBase::add(Worker::Work work) { houseguest::synchronize(my_mutex, [this, &work]() { if(my_isAccepting) { my_work.emplace_back(std::move(work)); my_workReady.notify_one(); } else { throw std::runtime_error{"Not accepting work"}; } }); } void ThreadpoolBase::stop() { houseguest::synchronize_unique(my_mutex, [this](auto lock) { if(my_isAccepting) { my_isAccepting = false; my_workReady.notify_all(); lock.unlock(); std::for_each(std::begin(my_threads), std::end(my_threads), [](auto & thread) { thread.join(); }); lock.lock(); my_isRunning = false; } }); } bool ThreadpoolBase::isAccepting() const noexcept { return houseguest::synchronize(my_mutex, [this]() { return my_isAccepting; }); } bool ThreadpoolBase::isRunning() const noexcept { return houseguest::synchronize(my_mutex, [this]() { return my_isRunning; }); } std::size_t ThreadpoolBase::getMaxThreads() const noexcept { return houseguest::synchronize(my_mutex, [this]() { return my_threads.capacity(); }); } std::size_t ThreadpoolBase::getAllocatedThreads() const noexcept { return houseguest::synchronize(my_mutex, [this]() { return my_threads.size(); }); } void ThreadpoolBase::addThread() { // assumes it's safe to add a thread here if(my_threads.size() != my_threads.capacity()) { my_threads.emplace_back(std::thread{[this]() { threadWorker(my_isAccepting, my_workReady, my_mutex, my_work); }}); } else { throw std::runtime_error{"threads are at capacity"}; } } /// \endcond
2e51273e9b8ca6e38de40b3daa7a6a36d7b52c29
d22bc53f68eac70f97ef1e398dd7646df4d33813
/effectivecpp/Chap04_DesignsDeclarations/Item25party2.cpp
795ebaf7fd168f0494367ecd8d382aade0a6187f
[]
no_license
jadyan/effectivecpp
082ff84ad4eaeb7d98a8f79fcc8144d5017712dc
48a0d43bce7a4adf2f6f1a3e2d06b0779c844ed3
refs/heads/main
2023-05-01T01:48:37.690351
2021-05-12T14:06:26
2021-05-12T14:06:26
366,735,437
0
0
null
null
null
null
UTF-8
C++
false
false
1,564
cpp
Item25party2.cpp
#include <iostream> #include <algorithm> class WidgetImpl { public: WidgetImpl(int x, int y, int z) : a(x), b(y), c(z) { } void show() { std::cout<<"a="<<a<<"b="<<b<<"c="<<c<<std::endl; } private: int a, b, c; }; class Widget { public: Widget(WidgetImpl* wi) : pImpl(wi) {} void swap(Widget& other) { //using std::swap; std::cout<<"swap 函数调用"<<std::endl; std::swap(pImpl, other.pImpl); } void show() { (*pImpl).show(); } private: WidgetImpl* pImpl; }; /* *这个函数开头的 "template<>" 表明这是一个针对 std::swap 的完全模板特化(total template specialization) (某些书中称为 "full template specialization" 或 "complete template specialization" ——译者注), 函数名后面的 "<Widget>" 表明特化是在 T 为 Widget 类型时发生的。换句话说,当通用的 swap 模板用于 Widgets 时,就应该使用这个实现。通常,我们改变 std namespace 中的内容是不被允许的,但允许为我们自己创建的类型(就像 Widget)完全特化标准模板(就像 swap)。这就是我们现在在这里做的事情 * */ namespace std { // total template specialization for std::swap //特化(全特化) template<> void swap<Widget>(Widget& a, Widget& b) { std::cout<<"调用重构(特化) std swap"<<std::endl; a.swap(b); } } int main(int argc, char ** argv) { Widget wg1(new WidgetImpl(1,2,3)); Widget wg2(new WidgetImpl(11,22,23)); wg1.show(); wg2.show(); //wg1.swap(wg2); std::swap(wg1, wg2); wg1.show(); wg2.show(); }
3d976989da80268738362188340a8d46f77dd7af
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chromecast/media/cma/backend/proxy/buffer_id_manager_unittest.cc
4399f95b376b41624b04263ab873bd84ce64832f
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
9,656
cc
buffer_id_manager_unittest.cc
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromecast/media/cma/backend/proxy/buffer_id_manager.h" #include <memory> #include "base/memory/ptr_util.h" #include "base/memory/scoped_refptr.h" #include "chromecast/media/api/cma_backend.h" #include "chromecast/media/api/monotonic_clock.h" #include "chromecast/media/api/test/mock_cma_backend.h" #include "chromecast/media/base/cast_decoder_buffer_impl.h" #include "chromecast/media/cma/backend/proxy/cma_proxy_handler.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromecast { namespace media { namespace { using testing::_; using testing::Mock; using testing::Return; ACTION_P(CompareBufferInfos, expected) { const BufferIdManager::TargetBufferInfo& actual = arg0; EXPECT_EQ(actual.buffer_id, expected.buffer_id); EXPECT_EQ(actual.timestamp_micros, expected.timestamp_micros); } class MockClock : public MonotonicClock { public: ~MockClock() override = default; MOCK_CONST_METHOD0(Now, int64_t()); }; class MockBufferIdManagerClient : public BufferIdManager::Client { public: MOCK_METHOD1(OnTimestampUpdateNeeded, void(BufferIdManager::TargetBufferInfo)); }; } // namespace class BufferIdManagerTest : public testing::Test { public: BufferIdManagerTest() { default_config_.bytes_per_channel = 100; default_config_.channel_number = 20; default_config_.samples_per_second = 5000; auto clock = std::make_unique<testing::StrictMock<MockClock>>(); clock_ = clock.get(); id_manager_ = base::WrapUnique<BufferIdManager>( new BufferIdManager(&audio_decoder_, &client_, std::move(clock))); } ~BufferIdManagerTest() override = default; protected: BufferIdManager::BufferId AssignBufferId(int64_t rendering_delay, int64_t timestamp, int64_t pts) { EXPECT_CALL(audio_decoder_, GetRenderingDelay()) .WillOnce(Return(MediaPipelineBackend::AudioDecoder::RenderingDelay( rendering_delay, timestamp))); auto buffer = base::MakeRefCounted<CastDecoderBufferImpl>(1); buffer->set_timestamp(base::Microseconds(pts)); auto result = id_manager_->AssignBufferId(*buffer); Mock::VerifyAndClearExpectations(&audio_decoder_); return result; } BufferIdManager::TargetBufferInfo GetCurrentlyProcessingBufferInfo( int64_t rendering_delay, int64_t timestamp, BufferIdManager::BufferId target_buffer) { auto buffer_info = id_manager_->GetCurrentlyProcessingBufferInfo(); EXPECT_EQ(buffer_info.buffer_id, target_buffer); EXPECT_EQ(buffer_info.timestamp_micros, timestamp); Mock::VerifyAndClearExpectations(&audio_decoder_); return buffer_info; } testing::StrictMock<MockCmaBackend::AudioDecoder> audio_decoder_; testing::StrictMock<MockBufferIdManagerClient> client_; MockClock* clock_; std::unique_ptr<BufferIdManager> id_manager_; AudioConfig default_config_; }; TEST_F(BufferIdManagerTest, TestDelayedFrames) { // Push 3 new buffers. EXPECT_CALL(*clock_, Now()).Times(3).WillRepeatedly(Return(0)); BufferIdManager::BufferId i = AssignBufferId(0, std::numeric_limits<int64_t>::min(), 30); ASSERT_GE(i, 0); BufferIdManager::BufferId j = AssignBufferId(0, std::numeric_limits<int64_t>::min(), 70); EXPECT_EQ(i + 1, j); BufferIdManager::BufferId k = AssignBufferId(0, std::numeric_limits<int64_t>::min(), 120); EXPECT_EQ(j + 1, k); Mock::VerifyAndClearExpectations(clock_); // Call UpdateAndGetCurrentlyProcessingBufferInfo() pulling no buffers off the // queue. EXPECT_CALL(*clock_, Now()).WillOnce(Return(0)); GetCurrentlyProcessingBufferInfo(100, 0, i); Mock::VerifyAndClearExpectations(clock_); int64_t rendering_delay = 100; int64_t renderer_timestamp = 0; int64_t returned_timestamp = 10; EXPECT_CALL(client_, OnTimestampUpdateNeeded(_)) .WillOnce(testing::WithArgs<0>(CompareBufferInfos( BufferIdManager::TargetBufferInfo{i, returned_timestamp}))); EXPECT_CALL(audio_decoder_, GetRenderingDelay()) .WillOnce(Return(MediaPipelineBackend::AudioDecoder::RenderingDelay( rendering_delay, renderer_timestamp))); auto buffer_info = id_manager_->UpdateAndGetCurrentlyProcessingBufferInfo(); EXPECT_EQ(buffer_info.buffer_id, i); EXPECT_EQ(buffer_info.timestamp_micros, returned_timestamp); Mock::VerifyAndClearExpectations(&audio_decoder_); Mock::VerifyAndClearExpectations(&client_); // No buffers should be pulled off when calling // GetCurrentlyProcessingBufferInfo() regardless of timestamp change. rendering_delay = 80; GetCurrentlyProcessingBufferInfo(rendering_delay, returned_timestamp, i); Mock::VerifyAndClearExpectations(clock_); // Pull the first buffer off the queue, and expect no callback because there's // been no rendering clock changes. renderer_timestamp = 20; returned_timestamp = 50; EXPECT_CALL(audio_decoder_, GetRenderingDelay()) .WillOnce(Return(MediaPipelineBackend::AudioDecoder::RenderingDelay( rendering_delay, renderer_timestamp))); buffer_info = id_manager_->UpdateAndGetCurrentlyProcessingBufferInfo(); EXPECT_EQ(buffer_info.buffer_id, j); EXPECT_EQ(buffer_info.timestamp_micros, returned_timestamp); Mock::VerifyAndClearExpectations(&audio_decoder_); // Pull the last buffer off the queue rendering_delay = 30; GetCurrentlyProcessingBufferInfo(rendering_delay, returned_timestamp, j); renderer_timestamp = 70; returned_timestamp = 100; EXPECT_CALL(audio_decoder_, GetRenderingDelay()) .WillOnce(Return(MediaPipelineBackend::AudioDecoder::RenderingDelay( rendering_delay, renderer_timestamp))); buffer_info = id_manager_->UpdateAndGetCurrentlyProcessingBufferInfo(); EXPECT_EQ(buffer_info.buffer_id, k); EXPECT_EQ(buffer_info.timestamp_micros, returned_timestamp); Mock::VerifyAndClearExpectations(&audio_decoder_); // When no buffer is remaining in the queue, return the id of the last // processed. rendering_delay = 0; GetCurrentlyProcessingBufferInfo(rendering_delay, returned_timestamp, k); renderer_timestamp = 100; returned_timestamp = 100; EXPECT_CALL(audio_decoder_, GetRenderingDelay()) .WillOnce(Return(MediaPipelineBackend::AudioDecoder::RenderingDelay( rendering_delay, renderer_timestamp))); buffer_info = id_manager_->UpdateAndGetCurrentlyProcessingBufferInfo(); EXPECT_EQ(buffer_info.buffer_id, k); EXPECT_EQ(buffer_info.timestamp_micros, returned_timestamp); } TEST_F(BufferIdManagerTest, TestUpdateTimestamp) { auto buffer = base::MakeRefCounted<CastDecoderBufferImpl>(1); // Push a new buffer. int64_t rendering_delay = 0; int64_t pts = 0; EXPECT_CALL(*clock_, Now()).WillOnce(Return(0)); BufferIdManager::BufferId i = AssignBufferId(0, std::numeric_limits<int64_t>::min(), pts); EXPECT_GE(i, 0); Mock::VerifyAndClearExpectations(clock_); // Push a second buffer, with the first one still pending. rendering_delay = 5; int64_t renderer_timestamp = 20; pts = 10; EXPECT_CALL(client_, OnTimestampUpdateNeeded(_)).Times(1); AssignBufferId(rendering_delay, renderer_timestamp, pts); Mock::VerifyAndClearExpectations(&client_); // When only 5 microseconds left in the queue, the first pushed buffer is // removed. rendering_delay = 15; renderer_timestamp = 30; pts = 20; AssignBufferId(rendering_delay, renderer_timestamp, pts); Mock::VerifyAndClearExpectations(&client_); // When a big change is detected, a client callback is sent. With only one // element in the queue, the rendering delay retrieved from the underlying // renderer is treated as exact. rendering_delay = 5; renderer_timestamp = 30000; pts = 40; EXPECT_CALL(client_, OnTimestampUpdateNeeded(_)) .WillOnce(testing::WithArgs<0>( CompareBufferInfos(BufferIdManager::TargetBufferInfo{ i + 2, renderer_timestamp + rendering_delay}))); AssignBufferId(rendering_delay, renderer_timestamp, pts); Mock::VerifyAndClearExpectations(&client_); // Push more buffers with none falling off the queue. No client callback // should be sent. rendering_delay = 15; renderer_timestamp += 1; pts += 10; AssignBufferId(rendering_delay, renderer_timestamp, pts); rendering_delay = 25; renderer_timestamp += 1; pts += 10; AssignBufferId(rendering_delay, renderer_timestamp, pts); rendering_delay = 35; renderer_timestamp += 1; pts += 10; auto last_buffer_id = AssignBufferId(rendering_delay, renderer_timestamp, pts); // During the next iteration, if multiple buffers are removed from the queue // when a timestamp update is needed, only update for the last one. rendering_delay = 5; renderer_timestamp = 1500000; EXPECT_CALL(client_, OnTimestampUpdateNeeded(_)) .WillOnce(testing::WithArgs<0>( CompareBufferInfos(BufferIdManager::TargetBufferInfo{ last_buffer_id, renderer_timestamp + rendering_delay}))); EXPECT_CALL(audio_decoder_, GetRenderingDelay()) .WillOnce(Return(MediaPipelineBackend::AudioDecoder::RenderingDelay( rendering_delay, renderer_timestamp))); auto buffer_info = id_manager_->UpdateAndGetCurrentlyProcessingBufferInfo(); EXPECT_EQ(buffer_info.buffer_id, last_buffer_id); EXPECT_EQ(buffer_info.timestamp_micros, renderer_timestamp + rendering_delay); Mock::VerifyAndClearExpectations(&audio_decoder_); } } // namespace media } // namespace chromecast
a84bb01e90ff7ac42ee45e3aa721dc2fd13192bd
d1dc50f8b94d61d618b3803c048347fb94715335
/C++/binaerySearch.cpp
f2d2c10328d4027c78f260300593b572ae34fa49
[]
no_license
wafarifki/Hacktoberfest2021
5360e7f57d45e2bec2e0626fb8d49d1e511fb57b
6c062feb71fb0d6225af64ed6b6df83f7924432d
refs/heads/main
2023-08-23T20:04:52.179436
2021-10-01T06:58:30
2021-10-01T06:58:30
412,358,558
3
1
null
2021-10-01T06:44:27
2021-10-01T06:44:26
null
UTF-8
C++
false
false
475
cpp
binaerySearch.cpp
#include <iostream> using namespace std; int binarySearch(int *input, int n, int val) { for(int i=0;i<n;i++) { if(input[i]==val) return i; } return -1; } int main() { int size; cin >> size; int *input = new int[size]; for(int i = 0; i < size; ++i) { cin >> input[i]; } int t; cin >> t; while (t--) { int val; cin >> val; cout << binarySearch(input, size, val) << endl; } delete [] input; return 0; }
8e4d02c2796959d68899861b2cfcbec9157fed2b
0f3905366a5ec88300f1134b084741785d540bda
/meas_croc/main.cpp
df203e9d6940998832d82eeae6681adac560ff35
[]
no_license
cgurleyuk/meas_croc
b3f53ad05bb80a30c644e7523c5343342554e9f6
e8b43105e26a8e5996e2c9c1160c89ebc84da28b
refs/heads/master
2020-04-29T19:37:39.300651
2019-04-09T21:05:56
2019-04-09T21:05:56
176,361,350
0
0
null
null
null
null
UTF-8
C++
false
false
1,279
cpp
main.cpp
#include <string> #include <sstream> #include <iomanip> #include <vector> #include <iostream> #include "interp.h" #include "spi.h" #include "test.h" #include "meas.h" spi mainSPI; int main(int argc, char* argv []) { interp interp; interp.register_func("spi_w", &main_spi_write); interp.register_func("spi_r", &main_spi_read); interp.register_func("spi_dump", &main_spi_dump_fpga); interp.register_func("test_sr", &test_sr); interp.register_func("test_daq", &test_daq); interp.register_func("test_bs_file", &test_bs_file); interp.register_func("test_meas", &test_meas); interp.register_func("test_instr", &test_instr); interp.register_func("test_instr_wfmgen", &test_agilent33622a); interp.register_func("test_instr_freqcnt", &test_agilent53230a); interp.register_func("test_instr_mm", &test_keithley2002); interp.register_func("test_tempctrl", &test_tempctrl); interp.register_func("test_tempctrl_sw", &test_tempctrl_sw); interp.register_func("test_oven", &test_vt4200); interp.register_func("meas_fsw", &meas_fsw); interp.register_func("meas_dco", &meas_dco); interp.register_func("meas_tsw", &meas_tsw); interp.register_func("meas_whb_trim", &meas_whb_trim); interp.register_func("meas_reset_fpga", &meas_reset_fpga); interp.loop(); return 0; }
b040187c80f0f198bb1b7c24cc696a2ca8110ee3
125ae0adb562478b184bbb35d40f2c43b335415c
/MFDUI/Panels/Sonar/tSonarPanelHeroic.cpp
583964e6b62863fa3d30f5739b4928e77afb0173
[]
no_license
dulton/53_hero
ff49ce6096c379931d7649b654c5fa76de4630de
48057fe05e75f57b500a395e6ff8ff9c06da6895
refs/heads/master
2020-02-25T04:19:18.632727
2016-05-20T03:44:44
2016-05-20T03:44:44
62,197,327
3
2
null
2016-06-29T05:11:41
2016-06-29T05:11:38
null
WINDOWS-1252
C++
false
false
29,230
cpp
tSonarPanelHeroic.cpp
/*****************************************************/ // Copyright © 2007-2012 Navico // Confidential and proprietary. All rights reserved. /*****************************************************/ //----------------------------------------------------------------------------- /*! \class tSonarPanelHeroic \brief Simrad Sonar Panel */ //----------------------------------------------------------------------------- #include <StdAfx.h> #include "tSonarPanelHeroic.h" #include "tSonarInfoWidgetSimrad.h" #include "tSonarCursorInfoBox.h" #include "tSonarCommonActions.h" #include "MFDUI/tGotoMenuSimrad.h" #include <MFDUI/Panels/Sonar/Widgets/tSonarPanelWidget.h> #include <MFDUI/Panels/Sonar/Widgets/tSonarWidgetSettings.h> #include <Sonar/tSonarSettings.h> #include <SonarClient/tSonarClient.h> #include <UI/Actions/tListAction.h> #include <UI/Actions/tSliderAdjAction.h> #include <UI/Widgets/ArcedIndicator.h> #include <Utils/Units/tUnitsSettings.h> #include <Utils/Units/Convert.h> #include <Core/Connect.h> //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- tSonarPanelHeroic::tSonarPanelHeroic( int instance, bool hasSonarIndicators, QWidget* pParent ) : tSonarPanelCommonHeroic( instance, new tSonarPanelWidget( instance , MakeConfig( true /* config.SidescanRangeAtTop */ , true /* config.m_ManualShiftWithUpDown */ , false /* config.DepthInfoNextToCursor */ , true /* config.AutoVisibleRangeLinkedToCursor */ , false /* config.AllowPanPastRange */ , true /* config.TempGraphRightSide */ , SonarCommon::m_cSimradSensitivityMax /* config.SensitivityMax */ , SonarCommon::m_cSimradColorRangeMin /* config.ColorRangeMin */ , SonarCommon::m_cSimradColorRangeMax /* config.ColorRangeMax */ , SonarCommon::m_cSimradColorRangeSteps /* config.ColorRangeSteps */ ) ) , pParent ) , m_pGainIndicator( 0 ) // Gain / Sensitivity , m_pColorIndicator( 0 ) , m_pStructureSensitivityIndicator( 0 ) , m_pStructureColorIndicator( 0 ) , m_pBottomColouringAct( 0 ) , m_pSensitivityAdjAct( 0 ) , m_pSimradSplitAct( 0 ) , m_pQuickSensitivityAdjustAct( 0 ) , m_pQuickColorAdjustAct( 0 ) , m_pQuickStructureSensitivityAdjustAct( 0 ) , m_pQuickStructureContrastAdjustAct( 0 ) , m_HasSonarIndicators(hasSonarIndicators) { CreateSimradActions(); // We have to know when we have transitioned to/from measure mode to display only the measure info item when appropriate // NSW-6308 Connect( m_pSonarPanelWidget, SIGNAL( MeasureModeChanged( bool ) ), this, SLOT( ConfigureCursorInfoVisibility( bool ) ) ); m_pInfo = new tSonarInfoWidgetSimrad( this, m_pSonarPanelWidget, false ); m_pInfo->UpdateFrequency(); //Don't add to the layout because that would change the parenting m_pInfo->move( 0, 0 ); m_pInfo->adjustSize(); m_pInfo->installEventFilter( this ); // to catch resize events allowing us to reposition the arced indicators properly if(m_HasSonarIndicators) { m_pStructureSensitivityIndicator = new tArcedIndicatorSlider( *m_pCommonActions->m_pOverlaySensitivityAct, 0, 0, Qt::AlignLeft ); m_pStructureColorIndicator = new tArcedIndicatorSlider( *m_pCommonActions->m_pOverlayColorRangeAct, 0, 0, Qt::AlignLeft ); Connect( m_pGainIndicator, SIGNAL( Clicked(tArcedIndicator*) ), this, SLOT( OpenQuickAdjustMenu(tArcedIndicator*) ) ); Connect( m_pColorIndicator, SIGNAL( Clicked(tArcedIndicator*) ), this, SLOT( OpenQuickAdjustMenu(tArcedIndicator*) ) ); Connect( m_pStructureSensitivityIndicator, SIGNAL( Clicked(tArcedIndicator*) ), this, SLOT( OpenQuickAdjustMenu(tArcedIndicator*) ) ); Connect( m_pStructureColorIndicator, SIGNAL( Clicked(tArcedIndicator*) ), this, SLOT( OpenQuickAdjustMenu(tArcedIndicator*) ) ); Connect( &m_QuickParamAdjustSM, SIGNAL( IndexChanged(int) ), this, SLOT( OnQuickParamAdjustIndexChanged(int) ) ); // The arced indicators are putted into a widget which will be positioned by hand in the resize event. // This allows us prevent any overlap with info box. m_pIndicatorsContainer = new QWidget( this ); QVBoxLayout* indicatorsLayout = new QVBoxLayout( m_pIndicatorsContainer ); indicatorsLayout->setSizeConstraint( QLayout::SetFixedSize ); indicatorsLayout->setContentsMargins( 5, 0, 0, 0 ); indicatorsLayout->setSpacing( 0 ); indicatorsLayout->addWidget( m_pGainIndicator ); indicatorsLayout->addWidget( m_pColorIndicator ); indicatorsLayout->addWidget( m_pStructureSensitivityIndicator ); indicatorsLayout->addWidget( m_pStructureColorIndicator ); } Connect( m_pSonarPanelWidget, SIGNAL( OverlayDownscanChanged( bool ) ), this, SLOT( OnOverlayDownscanChanged( bool ) ) ); OnAutoSensitivityChanged( m_pSonarPanelWidget->AutoSensitivity() ); Connect( m_pSonarPanelWidget, SIGNAL( PaletteChanged( const tSonarColor& ) ), this, SLOT( OnPaletteChanged( const tSonarColor& ) ) ); OnPaletteChanged( m_pSonarPanelWidget->Palette() ); UpdateActionList(); PopulateParamAdjustStateMachine( m_pSonarPanelWidget->OverlayDownscan() ); // make sure the info box and cursor info box are on top of everything else m_pInfo->raise(); m_pCursorInfoBox->raise(); } //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- void tSonarPanelHeroic::CreateSimradActions() { // m_pPaletteAct { QStringList paletteOptions; QList<QIcon> paletteIcons; int index( 0 ); m_pCommonActions->GetPaletteActionInfo(m_pCommonActions->m_HeroicPaletteInfo, paletteOptions, paletteIcons, index, tSonarWidgetSettings::Instance( tSonarWidgetSettings::eInstance_Primary )->WaterColorMode() ); m_pPaletteAct = CreateSonarPaletteAction( paletteOptions, paletteIcons, index ); m_pPaletteAct->setWhatsThis( tr("Controls the range of colors used by the echo panels", "'What's this' help text") ); Connect( m_pPaletteAct, SIGNAL( ValueChanged(int) ), this, SLOT( SetPalette(int) ) ); Connect( tSonarWidgetSettings::Instance( tSonarWidgetSettings::eInstance_Primary ), SIGNAL( PaletteIndexChanged( SonarCommon::eSonarColorMode, SonarCommon::eSonarColorMode ) ), this, SLOT( OnPaletteIndexChanged( SonarCommon::eSonarColorMode, SonarCommon::eSonarColorMode ) ) ); } //\ m_pPaletteAct // m_pOverlayPaletteAct { QStringList overlayPaletteOptions; QList<QIcon> overlayPaletteIcons; int index( 0 ); m_pCommonActions->GetPaletteActionInfo(m_pCommonActions->m_HeroicStructurePaletteInfo, overlayPaletteOptions, overlayPaletteIcons, index, tSonarWidgetSettings::Instance( tSonarWidgetSettings::eInstance_Primary )->OverlayPaletteIndex() ); m_pOverlayPaletteAct = CreateSonarPaletteAction( overlayPaletteOptions, overlayPaletteIcons, index ); m_pOverlayPaletteAct->setWhatsThis( tr("Controls the range of colors used when DownScan is overlaid on the regular echo screen", "'What's this' help text") ); Connect( m_pOverlayPaletteAct, SIGNAL( ValueChanged(int) ), this, SLOT( SetOverlayPalette(int) ) ); Connect( tSonarWidgetSettings::Instance( tSonarWidgetSettings::eInstance_Primary ), SIGNAL( OverlayPaletteIndexChanged( SonarCommon::eSonarColorMode ) ), this, SLOT( OnOverlayPaletteIndexChanged( SonarCommon::eSonarColorMode ) ) ); } //\ m_pOverlayPaletteAct // m_pStructureOverlayOptionsAct if ( m_pStructureOverlayOptionsAct != 0 ) { QList< tAction* > actionList = GetListActionsContent(eSonarCommonListAction_OverlayOptions); actionList.append( m_pCommonActions->m_pOverlayTvgAct ); m_pStructureOverlayOptionsAct->SetSubActions( actionList ); } //\ m_pStructureOverlayOptionsAct // m_pViewMenuAct { m_pBottomColouringAct = new tAction( tr( "Bottom coloring" ), this ); m_pBottomColouringAct->SetAbbreviation( tr( "Bottom col.", "[abbrev] for Bottom coloring") ); m_pBottomColouringAct->setWhatsThis( tr("Colors the sea floor with a solid color. This helps to distinguish the sea floor from the water column.", "'What's this' help text") ); m_pBottomColouringAct->setCheckable( true ); m_pBottomColouringAct->setChecked( tSonarWidgetSettings::Instance( tSonarWidgetSettings::eInstance_Primary )->BottomColoring() ); Connect( m_pBottomColouringAct, SIGNAL( toggled( bool ) ), this, SLOT( SetBottomColoring( bool ) ) ); // No need to connect up to a change signal from the settings. The change is handled through the palette indexes. // NOTE: options must be in the same order as tSonarPanelWidget::tSplits // Different to Lowrance to remove flasher option if( m_pSonarPanelWidget->Split() > 2 ) { m_pSonarPanelWidget->SetSplit( 0 ); } QStringList splitOptions; splitOptions << tr( "No split" ) << tr( "Zoom" ) << tr( "Bottom lock" ); m_pSimradSplitAct = new tListAction( tr( "Split", "BUTTON" ), splitOptions, m_pSonarPanelWidget->Split() ); m_pSimradSplitAct->SetAbbreviation( tr( "Split", "[abbrev] for Split") ); Connect( m_pSimradSplitAct, SIGNAL( ValueFinalised( int ) ), this, SLOT( SetSplit( int ) ) ); // Only ever changed from here - no need to connect a signal from the sonar widget QList< tAction* > paletteActions; paletteActions.append( m_pBottomColouringAct ); m_pPaletteAct->SetSubActions( paletteActions ); QList< tAction* > viewActions = GetListActionsContent(eSonarCommonListAction_ViewMenu); viewActions.prepend( m_pSimradSplitAct ); viewActions.insert ( 5, m_pZoomBarsAct ); m_pViewMenuAct = CreateSonarViewMenuAct(); m_pViewMenuAct->SetSubActions( viewActions ); } //\ m_pViewMenuAct //m_pSensitivityAdjAct { m_pSensitivityAdjAct = new tSliderAdjAction( m_pCommonActions->m_pSensitivityAct, true, this ); m_pCommonActions->m_pSensitivityAct->AppendSubAction(m_pAutoSensitivityAct); m_pCommonActions->m_pSensitivityAct->setText( tr( "Gain" ) ); m_pCommonActions->m_pSensitivityAct->SetAbbreviation( tr( "G", "abbreviation for Gain" ) ); m_pCommonActions->m_pOverlaySensitivityAct->setText( tr( "S Gain" ) ); m_pCommonActions->m_pOverlaySensitivityAct->SetAbbreviation( tr( "SG", "abbreviation for Structure Gain" ) ); m_pCommonActions->m_pOverlaySensitivityAct->SetSliderTextFormat( "%p" ); m_pCommonActions->m_pOverlayTvgAct->setText( tr( "S TVG" ) ); m_pCommonActions->m_pOverlayTvgAct->SetAbbreviation( tr( "STVG", "abbreviation for Structure TVG" ) ); m_pCommonActions->m_pOverlayTvgAct->SetSliderTextFormat( "%p" ); Connect( m_pCommonActions->m_pSensitivityAct, SIGNAL( triggered() ), m_pAutoSensitivityAct, SLOT( toggle() ) ); } //\m_pSensitivityAdjAct //m_pColorAct { m_pColorAct = new tSliderAction( tr( "Color", "Sonar adjustment - BUTTON" ), 0, SonarCommon::m_cSimradColorRangeSteps, tSonarWidgetSettings::Instance(tSonarWidgetSettings::eInstance_Primary)->ColorRange(), true, "%v", this ); m_pColorAct->SetAbbreviation( tr( "C", "[abbrev] for Color range") ); m_pColorAct->setWhatsThis( tr("Controls whether to enable the color range dial", "'What's this' help text") ); m_pColorAct->SetDefaultValue( m_pSonarPanelWidget->ColorRangeDefault() ); Connect( m_pColorAct, SIGNAL( HoldOffValueChanged(int) ), tSonarWidgetSettings::Instance(tSonarWidgetSettings::eInstance_Primary), SLOT( SetColorRange(int) ) ); Connect( m_pColorAct, SIGNAL( HoldOffValueChanged(int) ), tSonarWidgetSettings::Instance(tSonarWidgetSettings::eInstance_Secondary), SLOT( SetColorRange(int) ) ); } //\m_pColorAct //m_pSurfaceClarityAct { m_pSurfaceClarityAct = new tSliderAction( tr( "TVG" ), 0, 20, m_pSonarPanelWidget->Tvg(), true, "%v", this ); m_pSurfaceClarityAct->SetAbbreviation( tr( "TVG", "[abbrev] for Clarity" ) ); Connect( m_pSurfaceClarityAct, SIGNAL( HoldOffValueChanged(int) ), m_pSonarPanelWidget, SLOT( SetTvg(int) ) ); Connect( m_pSonarPanelWidget, SIGNAL( TvgChanged(int) ), m_pSurfaceClarityAct, SLOT( SetValue(int) ) ); } //\m_pSurfaceClarityAct //m_pCommonActions->m_pFishIconsAct { QList< tAction* > fishIDActions; fishIDActions.append( m_pCommonActions->m_pFishAudioAct ); m_pCommonActions->m_pFishIconsAct->SetSubActions( fishIDActions ); } //\m_pCommonActions->m_pFishIconsAct m_pStopChartAct->setText( tr( "Pause" ) ); m_pStopChartAct->SetAbbreviation( tr( "Pause", "[abbrev] for Pause") ); // Quick-access standard adjustable parameters m_pQuickSensitivityAdjustAct = new tSliderAdjAction( m_pCommonActions->m_pSensitivityAct, true, this ); Connect( m_pQuickSensitivityAdjustAct, SIGNAL( triggered() ), this, SLOT( UpdateParamAdjustState() ) ); Connect( m_pQuickSensitivityAdjustAct, SIGNAL( LongPress() ), m_pAutoSensitivityAct, SLOT( toggle() ) ); m_pQuickColorAdjustAct = new tSliderAdjAction( m_pColorAct, true, this ); Connect( m_pQuickColorAdjustAct, SIGNAL( triggered() ), this, SLOT( UpdateParamAdjustState() ) ); // Quick access structure overlay adjustable parameters m_pQuickStructureSensitivityAdjustAct = new tSliderAdjAction( m_pCommonActions->m_pOverlaySensitivityAct, true, this ); m_pQuickStructureSensitivityAdjustAct->setText( tr( "S Gain" ) ); m_pQuickStructureSensitivityAdjustAct->SetAbbreviation( tr( "SG", "abbreviation for Structure Gain" ) ); Connect( m_pQuickStructureSensitivityAdjustAct, SIGNAL( triggered() ), this, SLOT( UpdateParamAdjustState() ) ); m_pQuickStructureContrastAdjustAct = new tSliderAdjAction( m_pCommonActions->m_pOverlayColorRangeAct, true, this ); m_pQuickStructureContrastAdjustAct->setText( tr( "S Contrast" ) ); m_pQuickStructureContrastAdjustAct->SetAbbreviation( tr( "SC", "abbreviation for Structure Contrast" ) ); Connect( m_pQuickStructureContrastAdjustAct, SIGNAL( triggered() ), this, SLOT( UpdateParamAdjustState() ) ); Assert( m_pCommonActions->m_pSensitivityAct && m_pCommonActions->m_pOverlayColorRangeAct && m_pCommonActions->m_pOverlayTvgAct) ; if ( m_HasSonarIndicators ) { m_pGainIndicator = new tArcedIndicatorSlider( *m_pCommonActions->m_pSensitivityAct, m_pAutoSensitivityAct, 0, Qt::AlignLeft ); m_pColorIndicator = new tArcedIndicatorSlider( *m_pColorAct, 0, 0, Qt::AlignLeft ); } Assert( m_pCommonActions->m_pOverlaySensitivityAct && m_pCommonActions->m_pOverlayColorRangeAct && m_pCommonActions->m_pOverlayTvgAct ); QList< tAction* > rangeActionList; rangeActionList.append( m_pAutoRangeAct ); rangeActionList.append( m_pCustomDepthRangeAct ); m_pRangeAct->SetSubActions( rangeActionList ); } //----------------------------------------------------------------------------- //! Sets up the actions that are dependent on the split //----------------------------------------------------------------------------- void tSonarPanelHeroic::SetupSplitActions() { int split = m_pSonarPanelWidget->Split(); m_pCommonActions->m_pMeasureAct->setEnabled( split != tSonarPanelWidget::eSplit_Flasher ); } //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- void tSonarPanelHeroic::SetSplit( int split ) { m_pSonarPanelWidget->SetSplit( split ); SetupSplitActions(); } //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- void tSonarPanelHeroic::OnPaletteChanged( const tSonarColor& palette ) { UI::Appearance appearance = OnPaletteChangedCommon( palette ); if (m_pGainIndicator != 0 ) { m_pGainIndicator->SetAppearance( appearance ); } if (m_pColorIndicator != 0 ) { m_pColorIndicator->SetAppearance( appearance ); } if (m_pStructureSensitivityIndicator != 0 ) { m_pStructureSensitivityIndicator->SetAppearance( appearance ); } if (m_pStructureColorIndicator != 0 ) { m_pStructureColorIndicator->SetAppearance( appearance ); } } void tSonarPanelHeroic::GotoPressed( QKeyEvent* pEvent ) { // Override the default Goto menu to get "Goto cursor" to work if( pEvent->isAutoRepeat() ) return; tGotoMenuSimrad& gotoMenu = *new tGotoMenuSimrad( this ); if( m_pSonarPanelWidget->CursorMode() ) { // done as a slot so it can get the cursor position when the action is triggered gotoMenu.SetGotoCursorSlot( m_pSonarPanelWidget, SLOT( GotoCursor() ) ); } // Close all other popups while ( QApplication::activePopupWidget() ) { if ( !QApplication::activePopupWidget()->close() ) { break; } } gotoMenu.ShowAndDeleteOnClose(); } void tSonarPanelHeroic::VesselPressed( QKeyEvent* pEvent ) { if( pEvent->isAutoRepeat() ) return; if( m_pSonarPanelWidget->TraceMode() != TRACE_MODE_AUTO_SHIFT ) { m_pSonarPanelWidget->SetCursorMode( false ); } } //----------------------------------------------------------------------------- //! Demo: Set the gain //----------------------------------------------------------------------------- void tSonarPanelHeroic::DemoGainSet( int value ) { m_pCommonActions->m_pSensitivityAct->SetValue( value ); } //----------------------------------------------------------------------------- //! Returns the current gain value (use for demo) //----------------------------------------------------------------------------- int tSonarPanelHeroic::GainValue() { return m_pCommonActions->m_pSensitivityAct->Value(); } //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- void tSonarPanelHeroic::OnOverlayDownscanChanged( bool enabled ) { UpdateActionList(); PopulateParamAdjustStateMachine( enabled ); } //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- void tSonarPanelHeroic::ConfigureCursorInfoVisibility( bool inMeasureMode ) { if ( inMeasureMode ) { m_pCursorInfoBox->SetMeasureVisibleOnly(); } else { m_pCursorInfoBox->SetInfoVisibility( this->height() ); } } //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- void tSonarPanelHeroic::SetPalette( int index ) { tSonarPanelCommonHeroic::SetPalette( index ); CheckDebugPaletteIndexCombination( index ); } //----------------------------------------------------------------------------- /*! Sets the correct index on the palette action. Only look at the water color mode as the bottom color mode is based on the BottomColoring setting */ //----------------------------------------------------------------------------- void tSonarPanelHeroic::OnPaletteIndexChanged( SonarCommon::eSonarColorMode waterColorMode, SonarCommon::eSonarColorMode ) { m_pCommonActions->OnPaletteIndexChanged(m_pCommonActions->m_HeroicPaletteInfo, waterColorMode, (SonarCommon::eSonarColorMode)-1, m_pPaletteAct); } //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- void tSonarPanelHeroic::SetBottomColoring( bool enabled ) { tSonarWidgetSettings::Instance( tSonarWidgetSettings::eInstance_Primary )->SetBottomColoring( enabled ); tSonarWidgetSettings::Instance( tSonarWidgetSettings::eInstance_Secondary )->SetBottomColoring( enabled ); // Update the palette int index = m_pPaletteAct->Value(); SetPalette( index ); } //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- void tSonarPanelHeroic::SetOverlayPalette( int index ) { index = qBound( 0, index, m_pCommonActions->m_HeroicStructurePaletteInfo.size() ); tSonarWidgetSettings::Instance( tSonarWidgetSettings::eInstance_Primary )->SetOverlayPaletteIndex( m_pCommonActions->m_HeroicStructurePaletteInfo[index].m_WaterColorMode); tSonarWidgetSettings::Instance( tSonarWidgetSettings::eInstance_Secondary )->SetOverlayPaletteIndex( m_pCommonActions->m_HeroicStructurePaletteInfo[index].m_WaterColorMode); } //----------------------------------------------------------------------------- //! Sets the correct index on the overlay palette action. //----------------------------------------------------------------------------- void tSonarPanelHeroic::OnOverlayPaletteIndexChanged( SonarCommon::eSonarColorMode colorMode ) { m_pCommonActions->OnPaletteIndexChanged(m_pCommonActions->m_HeroicStructurePaletteInfo, colorMode, (SonarCommon::eSonarColorMode)-1, m_pOverlayPaletteAct); } //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- void tSonarPanelHeroic::PopulateParamAdjustStateMachine( bool includeOverlayActions ) { m_QuickParamAdjustSM.ClearAllActions(); tActionList sensList; sensList << m_pQuickSensitivityAdjustAct; sensList << m_pAutoSensitivityAct; int gainQuickActionIndex = m_QuickParamAdjustSM.AddActionList( sensList ); int colorQuickActionIndex = m_QuickParamAdjustSM.AddAction( m_pQuickColorAdjustAct ); // // Associate each tArcedIndicator with a QuickAction menu index. When the tArcedIndicator is // clicked/touched, open the quick adjust menu at the appropriate index. // m_IndicatorToQuickAdjustIndexMapping.clear(); if ( m_HasSonarIndicators ) { m_IndicatorToQuickAdjustIndexMapping[m_pGainIndicator] = gainQuickActionIndex; m_IndicatorToQuickAdjustIndexMapping[m_pColorIndicator] = colorQuickActionIndex; if ( includeOverlayActions ) { int structSensitivityQuickIndex = m_QuickParamAdjustSM.AddAction( m_pQuickStructureSensitivityAdjustAct ); int structColorQuickIndex = m_QuickParamAdjustSM.AddAction( m_pQuickStructureContrastAdjustAct ); m_IndicatorToQuickAdjustIndexMapping[m_pStructureSensitivityIndicator] = structSensitivityQuickIndex; m_IndicatorToQuickAdjustIndexMapping[m_pStructureColorIndicator] = structColorQuickIndex; m_pStructureSensitivityIndicator->setVisible(true); m_pStructureColorIndicator->setVisible(true); } else { m_pStructureSensitivityIndicator->setVisible(false); m_pStructureColorIndicator->setVisible(false); } } UpdateIndicatorsPositionAndVisibility(); } //----------------------------------------------------------------------------- //! //! Deselect (unhighlight) all tArcedIndicators //! //! \return Nothing. //! //----------------------------------------------------------------------------- void tSonarPanelHeroic::DeselectAllArcedIndicators() { if ( m_pGainIndicator != 0 ) { m_pGainIndicator->SetSelected( false ); } if ( m_pColorIndicator != 0 ) { m_pColorIndicator->SetSelected( false ); } } //----------------------------------------------------------------------------- //! //! Highlight the tArcedIndicator that corresponds to the quick adjust menu/index //! that has been selected. //! //! \param index The current index of the QuickAdjust menu. //! //! \return Nothing. //! //----------------------------------------------------------------------------- void tSonarPanelHeroic::OnQuickParamAdjustIndexChanged( int index ) { // // Iterate through all tArcedIndicator to QuickAdjust menu mappings, // deselecting all but the one that current in the QuickAdjust. // QMap<tArcedIndicator*, int>::Iterator it = m_IndicatorToQuickAdjustIndexMapping.begin(); for ( ; it != m_IndicatorToQuickAdjustIndexMapping.end(); ++it) { if (it.value() == index) { it.key()->SetSelected(true); } else { it.key()->SetSelected(false); } } } //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- void tSonarPanelHeroic::SetPaddingHint( int left, int top, int, int ) { m_pInfo->move( left, top ); } //----------------------------------------------------------------------------- //! Simplified Menu used initially for Floyd //----------------------------------------------------------------------------- QList< tAction* > tSonarPanelHeroic::BuildCommandBarActionListSimplified() { QList< tAction* > commandBarActions; if( m_pSonarPanelWidget->MeasureMode() ) { commandBarActions.append( m_pExitMeasurementAct ); commandBarActions.append( m_pMovingMeasurePoint ); } else if ( m_pSonarPanelWidget->CursorMode() ) { m_CursorEnabled = true; emit CursorEnabled( true ); commandBarActions.append( m_pCommonActions->m_pClearCursorAct ); commandBarActions.append( m_pCommonActions->m_pSaveWaypoint ); commandBarActions.append( m_pGotoCursor ); commandBarActions.append( m_pCommonActions->m_pSensitivityAct ); commandBarActions.append( m_pColorAct ); commandBarActions.append( m_pPaletteAct ); commandBarActions.append( m_pCommonActions->m_pMeasureAct ); commandBarActions.append( m_pStopChartAct ); } else { m_CursorEnabled = false; emit CursorEnabled( false ); commandBarActions.append( m_pRangeAct ); commandBarActions.append( m_pFrequencyAct ); commandBarActions.append( m_pLoggingAct ); commandBarActions.append( m_pCommonActions->m_pSensitivityAct ); commandBarActions.append( m_pColorAct ); commandBarActions.append( m_pPaletteAct ); //Add structurescan if the structure overlay is on if ( m_pSonarPanelWidget->OverlayDownscan() ) { QList< tAction* > actionList; actionList.append( m_pCommonActions->m_pOverlaySensitivityAct ); actionList.append( m_pCommonActions->m_pOverlayContrastAct ); actionList.append( m_pOverlayPaletteAct ); actionList.append( m_pStructureFrequencyAct ); m_pStructureOverlayOptionsAct->SetSubActions(actionList); commandBarActions.append( m_pStructureOverlayOptionsAct ); } else { commandBarActions.append( m_pDummyAct ); } commandBarActions.append( m_pStopChartAct ); bool NetworkChoicesAvailable = tSonarSettings::Instance()->NetworkSonarUsed(m_pSonarPanelWidget->GetServerClass()) && tHostsList::Instance()->CountSourcesWithFrequency(eSonarFrequency_ConventionalFrequencyBits) > 0; if( NetworkChoicesAvailable ) { commandBarActions << m_pSonarSourceAct; } } return commandBarActions; }
d533ce8a1c25d2fdc836d5f9205ce935e5c77390
ce545d7ab264b2bd71fc97b06b93d1140d7a6bf7
/fdlibm1028/k_tanf.cstmt_p.cpp
8ea5a22486df573d7567f865d0521b07325c9acd
[]
no_license
cigar1920/testprogram
b12685cf4bd6364588f55a580da84424642e6691
c20cbd6a870dc492d9a834b444937305901fb50d
refs/heads/main
2023-02-18T18:59:09.520606
2021-01-06T13:18:47
2021-01-06T13:18:47
327,315,745
0
0
null
null
null
null
UTF-8
C++
false
false
11,815
cpp
k_tanf.cstmt_p.cpp
#include "../ScDebug/scdebug.h" /* k_tanf.c -- float version of k_tan.c * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ #ifndef __FDLIBM_H__ #include "fdlibm.h" #endif float __kernel_tanf(float x, float y, int iy) { float z, r, v, w, s; int32_t ix, hx; static const float one = 1.0000000000e+00; /* 0x3f800000 */ static const float pio4 = 7.8539812565e-01; /* 0x3f490fda */ static const float pio4lo = 3.7748947079e-08; /* 0x33222168 */ static const float T[] = { 3.3333334327e-01, /* 0x3eaaaaab */ 1.3333334029e-01, /* 0x3e088889 */ 5.3968254477e-02, /* 0x3d5d0dd1 */ 2.1869488060e-02, /* 0x3cb327a4 */ 8.8632395491e-03, /* 0x3c11371f */ 3.5920790397e-03, /* 0x3b6b6916 */ 1.4562094584e-03, /* 0x3abede48 */ 5.8804126456e-04, /* 0x3a1a26c8 */ 2.4646313977e-04, /* 0x398137b9 */ 7.8179444245e-05, /* 0x38a3f445 */ 7.1407252108e-05, /* 0x3895c07a */ (0.0 - 1.8558637748e-05); double temp_var_for_const_0, temp_var_for_const_1; , /* 0xb79bae5f */ 2.5907305826e-05 /* 0x37d95384 */ }; GET_FLOAT_WORD(hx, x); ix = hx & IC(0x7fffffff); /* high word of |x| */ if (ix < IC(0x31800000)) /* x < 2**-28 */ { if ((int32_t)x == 0) { /* generate inexact */ if ((ix | (iy + 1)) == 0) return one / __ieee754_fabsf(x); else return (iy == 1) ? x : -one / x; } } if (ix >= IC(0x3f2ca140)) { /* |x|>=0.6744 */ if (hx < 0) { x = -x; y = -y; } z = pio4 - x; w = pio4lo - y; x = z + w; y = 0.0; if (__ieee754_fabsf(x) < 0x1p-13f) return (1 - ((hx >> 30) & 2)) * iy * (1.0f - 2 * iy * x); } z = x * x; float temp_var_for_tac_0; computeFSub((Addr)&temp_var_for_tac_0, {(Addr) &(temp_var_for_const_1 = 0.0), (Addr) &(temp_var_for_const_0 = 1.8558637748e-05)}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:66:9"); computeFMul((Addr)&z, {(Addr)&x, (Addr)&x}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:66:5"); w = z * z; computeFMul((Addr)&w, {(Addr)&z, (Addr)&z}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:67:5"); /* Break x^5*(T[1]+x^2*T[2]+...) into * x^5(T[1]+x^4*T[3]+...+x^20*T[11]) + * x^5(x^2*(T[2]+x^4*T[4]+...+x^22*[T12])) */ r = T[1] + w * (T[3] + w * (T[5] + w * (T[7] + w * (T[9] + w * T[11])))); float temp_var_for_const_2, temp_var_for_const_3, temp_var_for_const_4, temp_var_for_const_5, temp_var_for_const_6, temp_var_for_const_7; float temp_var_for_tac_1, temp_var_for_tac_2, temp_var_for_tac_3, temp_var_for_tac_4, temp_var_for_tac_5, temp_var_for_tac_6, temp_var_for_tac_7, temp_var_for_tac_8, temp_var_for_tac_9; computeFMul((Addr)&temp_var_for_tac_1, {(Addr)&w, (Addr) &(temp_var_for_const_2 = T[11])}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:72:60"); computeFAdd((Addr)&temp_var_for_tac_2, {(Addr) &(temp_var_for_const_3 = T[9]), (Addr)&temp_var_for_tac_1}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:72:52"); computeFMul((Addr)&temp_var_for_tac_3, {(Addr)&w, (Addr)&temp_var_for_tac_2}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:72:48"); computeFAdd((Addr)&temp_var_for_tac_4, {(Addr) &(temp_var_for_const_4 = T[7]), (Addr)&temp_var_for_tac_3}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:72:40"); computeFMul((Addr)&temp_var_for_tac_5, {(Addr)&w, (Addr)&temp_var_for_tac_4}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:72:36"); computeFAdd((Addr)&temp_var_for_tac_6, {(Addr) &(temp_var_for_const_5 = T[5]), (Addr)&temp_var_for_tac_5}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:72:28"); computeFMul((Addr)&temp_var_for_tac_7, {(Addr)&w, (Addr)&temp_var_for_tac_6}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:72:24"); computeFAdd((Addr)&temp_var_for_tac_8, {(Addr) &(temp_var_for_const_6 = T[3]), (Addr)&temp_var_for_tac_7}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:72:16"); computeFMul((Addr)&temp_var_for_tac_9, {(Addr)&w, (Addr)&temp_var_for_tac_8}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:72:12"); computeFAdd((Addr)&r, {(Addr) &(temp_var_for_const_7 = T[1]), (Addr)&temp_var_for_tac_9}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:72:5"); v = z * (T[2] + w * (T[4] + w * (T[6] + w * (T[8] + w * (T[10] + w * T[12]))))); float temp_var_for_const_8, temp_var_for_const_9, temp_var_for_const_10, temp_var_for_const_11, temp_var_for_const_12, temp_var_for_const_13; float temp_var_for_tac_10, temp_var_for_tac_11, temp_var_for_tac_12, temp_var_for_tac_13, temp_var_for_tac_14, temp_var_for_tac_15, temp_var_for_tac_16, temp_var_for_tac_17, temp_var_for_tac_18, temp_var_for_tac_19; computeFMul((Addr)&temp_var_for_tac_10, {(Addr)&w, (Addr) &(temp_var_for_const_8 = T[12])}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:74:62"); computeFAdd((Addr)&temp_var_for_tac_11, {(Addr) &(temp_var_for_const_9 = T[10]), (Addr)&temp_var_for_tac_10}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:74:53"); computeFMul((Addr)&temp_var_for_tac_12, {(Addr)&w, (Addr)&temp_var_for_tac_11}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:74:49"); computeFAdd((Addr)&temp_var_for_tac_13, {(Addr) &(temp_var_for_const_10 = T[8]), (Addr)&temp_var_for_tac_12}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:74:41"); computeFMul((Addr)&temp_var_for_tac_14, {(Addr)&w, (Addr)&temp_var_for_tac_13}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:74:37"); computeFAdd((Addr)&temp_var_for_tac_15, {(Addr) &(temp_var_for_const_11 = T[6]), (Addr)&temp_var_for_tac_14}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:74:29"); computeFMul((Addr)&temp_var_for_tac_16, {(Addr)&w, (Addr)&temp_var_for_tac_15}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:74:25"); computeFAdd((Addr)&temp_var_for_tac_17, {(Addr) &(temp_var_for_const_12 = T[4]), (Addr)&temp_var_for_tac_16}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:74:17"); computeFMul((Addr)&temp_var_for_tac_18, {(Addr)&w, (Addr)&temp_var_for_tac_17}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:74:13"); computeFAdd((Addr)&temp_var_for_tac_19, {(Addr) &(temp_var_for_const_13 = T[2]), (Addr)&temp_var_for_tac_18}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:73:9"); computeFMul((Addr)&v, {(Addr)&z, (Addr)&temp_var_for_tac_19}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:73:5"); s = z * x; computeFMul((Addr)&s, {(Addr)&z, (Addr)&x}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:75:5"); float temp_var_for_ext_0; temp_var_for_ext_0 = y + z * (s * (r + v) + y); float temp_var_for_tac_20, temp_var_for_tac_21, temp_var_for_tac_22, temp_var_for_tac_23; computeFAdd((Addr)&temp_var_for_tac_20, {(Addr)&r, (Addr)&v}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:77:35"); computeFMul((Addr)&temp_var_for_tac_21, {(Addr)&s, (Addr)&temp_var_for_tac_20}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:77:45"); computeFAdd((Addr)&temp_var_for_tac_22, {(Addr)&temp_var_for_tac_21, (Addr)&y}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:77:30"); computeFMul((Addr)&temp_var_for_tac_23, {(Addr)&z, (Addr)&temp_var_for_tac_22}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:77:26"); computeFAdd((Addr)&temp_var_for_ext_0, {(Addr)&y, (Addr)&temp_var_for_tac_23}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:77:22"); // r /*(x)(z)(y)(v)(r)(s)(z)(y)*/ r = temp_var_for_ext_0; AssignF({(Addr)&r}, (Addr)&temp_var_for_ext_0, "/home/shijia/Public/testprogram/k_tanf.c_e.c:79:5"); r += T[0] * s; float temp_var_for_const_14; w = x + r; float temp_var_for_tac_24; computeFMul((Addr)&temp_var_for_tac_24, {(Addr) &(temp_var_for_const_14 = T[0]), (Addr)&s}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:81:9"); computeFAdd((Addr)&w, {(Addr)&x, (Addr)&r}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:81:5"); if (ix >= IC(0x3f2ca140)) { v = (float)iy; return (float)(1 - ((hx >> 30) & 2)) * (v - 2.0f * (x - (w * w / (w + v) - r))); } if (iy == 1) { float temp_var_for_ext_1; temp_var_for_ext_1 = w; AssignF({(Addr)&temp_var_for_ext_1}, (Addr)&w, "/home/shijia/Public/testprogram/k_tanf.c_e.c:89:24"); callExpStack.push(getReal("temp_var_for_ext_1", (Addr)&temp_var_for_ext_1)); callExp++; /*identify the function is add move tmpShadow*/ return temp_var_for_ext_1; } else { /* if allow error up to 2 ulp, simply return -1.0/(x+r) here */ /* compute -1.0/(x+r) accurately */ float a, t; int32_t i; z = w; AssignF({(Addr)&z}, (Addr)&w, "/home/shijia/Public/testprogram/k_tanf.c_e.c:101:7"); GET_FLOAT_WORD(i, z); SET_FLOAT_WORD(z, i & UC(0xfffff000)); v = r - (z - x); float temp_var_for_tac_25; computeFSub((Addr)&temp_var_for_tac_25, {(Addr)&z, (Addr)&x}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:104:11"); computeFSub( (Addr)&v, {(Addr)&r, (Addr)&temp_var_for_tac_25}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:104:7"); /* z+v = r+x */ t = a = (0.0 - 1.0f) / w; float temp_var_for_const_15, temp_var_for_const_16; float temp_var_for_tac_26; computeDSub((Addr)&temp_var_for_tac_26, {(Addr) &(temp_var_for_const_16 = 0.0), (Addr) &(temp_var_for_const_15 = 1.0f)}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:105:26"); computeFDiv((Addr)&a, {(Addr)&temp_var_for_tac_26, (Addr)&w}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:105:11"); AssignF( {(Addr)&t}, (Addr)&a, "/home/shijia/Public/testprogram/k_tanf.c_e.c:105:7"); /* a = -1.0/w */ GET_FLOAT_WORD(i, t); SET_FLOAT_WORD(t, i & UC(0xfffff000)); s = 1.0f + t * z; float temp_var_for_const_17; float temp_var_for_tac_27; computeFMul((Addr)&temp_var_for_tac_27, {(Addr)&t, (Addr)&z}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:108:14"); computeFAdd((Addr)&s, {(Addr) &(temp_var_for_const_17 = 1.0f), (Addr)&temp_var_for_tac_27}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:108:7"); float temp_var_for_ext_2; temp_var_for_ext_2 = t + a * (s + t * v); float temp_var_for_tac_28, temp_var_for_tac_29, temp_var_for_tac_30; computeFMul((Addr)&temp_var_for_tac_28, {(Addr)&t, (Addr)&v}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:110:37"); computeFAdd((Addr)&temp_var_for_tac_29, {(Addr)&s, (Addr)&temp_var_for_tac_28}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:110:32"); computeFMul((Addr)&temp_var_for_tac_30, {(Addr)&a, (Addr)&temp_var_for_tac_29}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:110:28"); computeFAdd((Addr)&temp_var_for_ext_2, {(Addr)&t, (Addr)&temp_var_for_tac_30}, "/home/shijia/Public/testprogram/k_tanf.c_e.c:110:24"); callExpStack.push(getReal("temp_var_for_ext_2", (Addr)&temp_var_for_ext_2)); callExp++; /*identify the function is add move tmpShadow*/ return temp_var_for_ext_2; } }
43b208a92115f886de989c4936a60e15e2a7a228
3d506bd201cb738a788c140622595cfd819e6b2d
/netProject/EasyTcpServer/EasyTcpServer.h
cdba5e97d8b488dedf069ac46cbbedf48bc85eed
[]
no_license
hhaiz123/netProject
651c4c7420ddf6248b15f04727ccb650e830d1e7
084d86787a38df0fbc0ce3d938499aa0cbe340b7
refs/heads/master
2022-10-01T15:28:09.633671
2020-06-09T09:55:40
2020-06-09T09:55:40
270,895,887
0
0
null
null
null
null
UTF-8
C++
false
false
1,107
h
EasyTcpServer.h
#pragma once #ifndef _EasyTcpServer_h_ #define _EasyTcpServer_h_ #include<stdio.h> #include<vector> #include<atomic> #include"EasyTcpMassage.h" #include "CELLTimestamp.hpp" #include"ClientSocket.hpp" #include"CellServer.h" #include"INetEvent.h" class EasyTcpServer: public INetEvent { public: EasyTcpServer(); int InitSocket(); int Bind(unsigned short port); int Listen(int n); void StartAddThread(int count); int AcceptClient(); bool OnRun(); void addClientToCellThread(ClientSocket * _cSocket); void time4msg(); void Close(); bool IsRun(); int Send(SOCKET _cSock, DataHead *data); virtual void OnNetJoin(ClientSocket* pClient); virtual void OnNetLeave(ClientSocket* pClient); virtual void OnNetMsg(CellServer *pCellServer,ClientSocket* pClient, DataHead* header); virtual void OnNetRecv(ClientSocket* pClient); private: //std::vector<ClientSocket*> _clientArr; SOCKET _sock; std::vector<CellServer*>_cellServers; CELLTimestamp _tTime; int totalCount = 0; protected: std::atomic<int> _recvCount = 0; std::atomic<int> _msgCount = 0; std::atomic<int> _clientCount = 0; }; #endif
7f1247323aa6f1d7e37b49dba8a38843004392c5
45f2d9ced227984422441452ac1e66b6f14de4ea
/codeforces122B.cpp
d7287fc9a710372e7ddc924aea502ab746bc7d00
[]
no_license
NiladreeDatta/Ad-Hoc-problems
dfd73911ace2e15a8cec95163562197b3806f71c
6df0475f292a245f3e3ae097d4f9eea0c79ef489
refs/heads/master
2020-12-14T09:24:16.856797
2020-06-09T14:28:33
2020-06-09T14:28:33
234,698,286
0
0
null
null
null
null
UTF-8
C++
false
false
282
cpp
codeforces122B.cpp
#include<bits/stdc++.h> using namespace std; int main() { string s; cin >> s; auto four = count(s.begin(),s.end(),'4'); auto seven = count(s.begin(),s.end(),'7'); cout << (four == 0 && seven == 0 ? -1: four >= seven ? 4 : 7 ) << endl; return 0; }
0354436977715eb298f281466de707cfddc3f71d
6493ea59aec4f9dda75264671166dad966fbe848
/Project/Project/Superpixels.h
4767da03dc9537a38d8b0a853e5364b7ecb26399
[]
no_license
TommyR22/OpenCv-Superpixel-based-Video-Object-Segmentation
f0a1b6e01be08a5cef69e6046afed33c4c213f67
11c7cf227b7b033e65ef403596b33bffbd7fa1a1
refs/heads/master
2021-01-13T11:32:36.209830
2019-04-03T08:07:11
2019-04-03T08:07:11
81,190,235
3
3
null
null
null
null
UTF-8
C++
false
false
1,162
h
Superpixels.h
// // FgModeling.h // Project // // Created by Tommaso Ruscica on 15/09/15. // Copyright (c) 2015 Tommaso Ruscica. All rights reserved. // #ifndef __Project__FgModeling__ #define __Project__FgModeling__ #include <stdio.h> #include <opencv2/opencv.hpp> extern "C" { #include "/Users/TommyR22/Desktop/vlfeat/vl/generic.h" #include "/Users/TommyR22/Desktop/vlfeat/vl/slic.h" } #endif /* defined(__Project__FgModeling__) */ cv::Mat segmentVLFeat (cv::Mat image); //create superpixels std::vector<int> getMotionSuperpixels(cv::Mat image_superpixels, cv::Mat image_superpixels2, std::vector<std::pair<int,int>> vect_pair, double number_superpixels); //double getNumberSuperpixel (cv::Mat image_superpixels); //get number of superpixels std::vector<std::pair<int,int>> overlappingSuperpixel (cv::Mat image_superpixels,cv::Mat image_superpixels2); //vector of overlap superpixels between frame t and t+1 cv::Mat masking (cv::Mat image, int label); //mask image for each superpixel cv::Mat masking_motionSuperpixels(cv::Mat image_superpixels,std::vector<int> motionSuperpixels); cv::Mat segment( cv::Mat image, int &numberOfLabels, cv::Mat &imageSegmented);
dde5c3ea575f923d094abccec30e4a85b3d11c1a
d04827974bbfe5faa46a967af0b7e072ca9e1220
/hss/hssperf/include/s6as6d_impl.h
37ec3bb353cdf5cb26fdc130063a3a5a09e19f31
[ "Apache-2.0" ]
permissive
krsna1729/c3po
b8640eeba51b10dd9873c15aefd952cfafc469c8
df54425693014cfc0cbe10be897364df00f8523e
refs/heads/master
2022-03-07T02:06:51.784244
2022-02-24T20:37:13
2022-02-24T20:37:13
172,896,481
0
0
Apache-2.0
2022-02-25T02:02:39
2019-02-27T10:42:59
C++
UTF-8
C++
false
false
4,465
h
s6as6d_impl.h
/* * Copyright 2019-present Open Networking Foundation * Copyright (c) 2017 Sprint * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __S6AS6D_IMPL_H #define __S6AS6D_IMPL_H #include "s6as6d.h" class HSSPerformance; class ULRTest; class ULRTracker; class ULRTestThread; class AIRTracker; class AIRTestThread; class AttachTracker; class AttachTestThread; namespace s6as6d { // Member functions that customize the individual application class Application : public ApplicationBase { friend UPLRreq; friend CALRreq; friend AUIRreq; friend INSDRreq; friend DESDRreq; friend PUURreq; friend RERreq; public: Application(); ~Application(); //UPLRcmd &getUPLRcmd() { return m_cmd_uplr; } //CALRcmd &getCALRcmd() { return m_cmd_calr; } //AUIRcmd &getAUIRcmd() { return m_cmd_auir; } //INSDRcmd &getINSDRcmd() { return m_cmd_insdr; } //DESDRcmd &getDESDRcmd() { return m_cmd_desdr; } //PUURcmd &getPUURcmd() { return m_cmd_puur; } //RERcmd &getRERcmd() { return m_cmd_rer; } // Parameters for sendXXXreq, if present below, may be changed // based upon processing needs bool sendUPLRreq(FDPeer &peer); bool sendCALRreq(FDPeer &peer); bool sendAUIRreq(FDPeer &peer); bool sendINSDRreq(FDPeer &peer); bool sendDESDRreq(FDPeer &peer); bool sendPUURreq(FDPeer &peer); bool sendRERreq(FDPeer &peer); bool sendULRreq(const char *imsi, uint8_t *vplmnid, const char *host, const char *realm, ULRTest &ulrtest, ULRTracker &result); bool sendULRreq(const char *imsi, uint8_t *vplmnid, const char *host, const char *realm, ULRTestThread &ulrtest, ULRTracker &result); bool sendULRreq(const char *imsi, uint8_t *vplmnid, const char *host, const char *realm, AttachTestThread &ulrtest, AttachTracker &result); bool sendAIRreq(const char *imsi, uint8_t *vplmnid, const char *host, const char *realm, AIRTestThread &airtest, AIRTracker &result); bool sendAIRreq(const char *imsi, uint8_t *vplmnid, const char *host, const char *realm, AttachTestThread &airulrtest, AttachTracker &result); private: void registerHandlers(); //UPLRcmd m_cmd_uplr; //CALRcmd m_cmd_calr; //AUIRcmd m_cmd_auir; //INSDRcmd m_cmd_insdr; //DESDRcmd m_cmd_desdr; //PUURcmd m_cmd_puur; //RERcmd m_cmd_rer; // the parameters for createXXXreq, if present below, may be // changed based processing needs UPLRreq *createUPLRreq(FDPeer &peer); CALRreq *createCALRreq(FDPeer &peer); AUIRreq *createAUIRreq(FDPeer &peer); INSDRreq *createINSDRreq(FDPeer &peer); DESDRreq *createDESDRreq(FDPeer &peer); PUURreq *createPUURreq(FDPeer &peer); RERreq *createRERreq(FDPeer &peer); }; //////////////////////////////////////////////////////////////////////////////// class TestULRreq : public UPLRreq { public: TestULRreq( Application &app, ULRTest &ulrtest, ULRTracker &tracker ); ~TestULRreq(); virtual void processAnswer( FDMessageAnswer &ans ); private: ULRTest &m_ulrtest; ULRTracker &m_result; }; //////////////////////////////////////////////////////////////////////////////// class TestULRreq2 : public UPLRreq { public: TestULRreq2( Application &app, ULRTestThread &ulrtest, ULRTracker &tracker ); ~TestULRreq2(); virtual void processAnswer( FDMessageAnswer &ans ); private: ULRTestThread &m_ulrtest; ULRTracker &m_result; }; //////////////////////////////////////////////////////////////////////////////// class TestAIRreq : public AUIRreq { public: TestAIRreq( Application &app, AIRTestThread &airtest, AIRTracker &tracker ); ~TestAIRreq(); virtual void processAnswer( FDMessageAnswer &ans ); private: AIRTestThread &m_airtest; AIRTracker &m_result; }; //////////////////////////////////////////////////////////////////////////////// class TestAIRAttachreq : public AUIRreq { public: TestAIRAttachreq( Application &app, AttachTestThread &airtest, AttachTracker &tracker ); ~TestAIRAttachreq(); virtual void processAnswer( FDMessageAnswer &ans ); private: AttachTestThread &m_attachtest; AttachTracker &m_result; }; class TestULRAttachreq : public UPLRreq { public: TestULRAttachreq( Application &app, AttachTestThread &airtest, AttachTracker &tracker ); ~TestULRAttachreq(); virtual void processAnswer( FDMessageAnswer &ans ); private: AttachTestThread &m_attachtest; AttachTracker &m_result; }; } #endif // __S6AS6D_IMPL_H
0bfa6f05604a868833b561de5bf61c3db265ff03
240068625c0c5a23b134c85a2af170d474e46923
/src/audiomodules/scaleosc.cpp
b1ad7dadc4ec59c2ffa33da9f65069977193a494
[]
no_license
Xenakios/XenakiosModules
3c225c687e0863cb6a0ce6975b0b1c6df74cd6a7
022e96c0223f3aec2700cccdbeed64fd64775db4
refs/heads/master
2023-01-07T08:54:11.435380
2021-11-25T19:09:08
2021-11-25T19:09:08
219,061,725
8
5
null
2020-07-15T18:51:46
2019-11-01T20:58:18
C++
UTF-8
C++
false
false
32,676
cpp
scaleosc.cpp
#include "../plugin.hpp" #include "../helperwidgets.h" #include "../wtosc.h" #include <array> #include "../jcdp_envelope.h" inline simd::float_4 fmodex(simd::float_4 x) { x = simd::fmod(x,1.0f); simd::float_4 a = 1.0f - (-1.0f * x); simd::float_4 neg = x >= 0.0f; return simd::ifelse(neg,x,a); } inline void quantize_to_scale(float x, const std::vector<float>& g, float& out1, float& out2, float& outdiff) { if (g.empty()) // special handling for no scale { out1 = x; float maxd = 10.0f; float dtune = rescale(x,rack::dsp::FREQ_C4/16.0f,20000.0f,0.0f,maxd); dtune = clamp(dtune,0.0f,maxd); float m = std::fmod(x,maxd); out2 = x+dtune; outdiff = m*(1.0f/maxd); return; } auto t1=std::upper_bound(std::begin(g),std::end(g),x); if (t1<std::end(g)-1) { auto t0=std::begin(g); if (t1>std::begin(g)) t0=t1-1; out1 = *t0; out2 = *t1; if (out1 == out2) { outdiff = 1.0f; return; } outdiff = rescale(x,out1,out2,0.0,1.0); return; } out1 = g.back(); out2 = g.back(); outdiff = 1.0f; } class SIMDSimpleOsc { public: std::array<float,512> warp3table; SIMDSimpleOsc() { for (int i=0;i<warp3table.size();++i) { float x = rescale(float(i),0,warp3table.size()-1,0.0f,1.0f); const float n1 = 7.5625; const float d1 = 2.75; float y = x; if (x < 1 / d1) { y = n1 * x * x; } else if (x < 2 / d1) { y = n1 * (x -= 1.5 / d1) * x + 0.75; } else if (x < 2.5 / d1) { y = n1 * (x -= 2.25 / d1) * x + 0.9375; } else { y = n1 * (x -= 2.625 / d1) * x + 0.984375; } warp3table[i] = y; } } simd::float_4 m_phase = 0.0; simd::float_4 m_phase_inc = 0.0; float m_warp = 0.0f; int m_warp_mode = 2; void prepare(int numchans, double samplerate) { } void setFrequencies(float hz0, float hz1, float samplerate) { simd::float_4 hzs(hz0,hz1,hz0,hz1); m_phase_inc = simd::float_4(1.0f/samplerate)*hzs; } void setFrequency(float hz, float samplerate) { simd::float_4 hzs(hz); m_phase_inc = 1.0/samplerate*hzs; } float m_warp_steps = 128.0f; void setPhaseWarp(int mode, float amt) { amt = clamp(amt,0.0f,1.0f); m_warp_mode = mode; m_warp_steps = std::pow(2.0f,2.0f+(1.0f-amt)*4.0f); m_warp = std::pow(amt,2.0f); } simd::float_4 processSample(float) { simd::float_4 phase_to_use = m_phase; simd::float_4 gain = 1.0f; //#ifdef FOOSIMD if (m_warp_mode == 0) { phase_to_use = simd::float_4(1.0)+simd::float_4(m_warp)*simd::float_4(7.0f); phase_to_use = m_phase * phase_to_use; phase_to_use = simd::fmin(phase_to_use,1.0f); //if (phase_to_use>1.0) // phase_to_use = 1.0f; } else if (m_warp_mode == 1) { double steps = m_warp_steps; // std::pow(2.0f,2.0f+(1.0-m_warp)*6.0f); phase_to_use = simd::round(m_phase*steps)/steps; } else { for (int i=0;i<4;++i) { float ph = m_phase[i]; int ind = ph * (warp3table.size()-1); ind = clamp(ind,0,warp3table.size()-1); ph = warp3table[ind]; phase_to_use[i] = (1.0f-m_warp) * phase_to_use[i] + m_warp * ph; } //float pmult = rescale(m_warp,0.0f,1.0f,1.0f,8.0f); //gain = 1.0f-simd::fmod(m_phase,1.0f); //phase_to_use = simd::fmod(pmult*m_phase,simd::float_4(1.0f)); } //#endif simd::float_4 rs = simd::sin(simd::float_4(2*3.14159265359)*phase_to_use); //float r = std::sin(2*3.14159265359*phase_to_use); m_phase += m_phase_inc; //m_phase = std::fmod(m_phase,1.0); //m_phase = wrap_value(0.0,m_phase,1.0); //m_phase = simd::fmod(m_phase,simd::float_4(1.0f)); m_phase = fmodex(m_phase); return rs*gain; } }; class SimpleOsc { public: SimpleOsc() { } double m_phase = 0.0; double m_phase_inc = 0.0; double m_samplerate = 44100; float m_warp = 0.0f; int m_warp_mode = 2; void prepare(int numchans, double samplerate) { m_samplerate = samplerate; } void setFrequency(float hz) { //if (hz<0.01f) // hz = 0.01f; m_phase_inc = 1.0/m_samplerate*hz; } float m_warp_steps = 128.0f; void setPhaseWarp(int mode, float amt) { amt = clamp(amt,0.0f,1.0f); m_warp_mode = mode; m_warp_steps = std::pow(2.0f,2.0f+(1.0f-amt)*6.0f); m_warp = std::pow(amt,2.0f); } float processSample(float) { double phase_to_use; if (m_warp_mode == 0) { /* if (m_warp!=0.5f) { double w; if (m_warp<0.5) w = rescale(m_warp,0.0f,0.5,0.2f,1.0f); else w = rescale(m_warp,0.5f,1.0f,1.0f,4.0f); phase_to_use = std::pow(m_phase,w); } else phase_to_use = m_phase; */ phase_to_use = 1.0+m_warp*7.0; phase_to_use = m_phase * phase_to_use; if (phase_to_use>1.0) phase_to_use = 1.0f; } else if (m_warp_mode == 1) { double steps = m_warp_steps; // std::pow(2.0f,2.0f+(1.0-m_warp)*6.0f); /* double skewp = 0.05; if (m_warp<skewp) { steps = rescale(m_warp,0.00f,skewp,128.0f,16.0f); } else { steps = rescale(m_warp,skewp,1.0f,16.0f,3.0f); } */ phase_to_use = std::round(m_phase*steps)/steps; } else { double pmult = rescale(m_warp,0.0f,1.0f,0.5f,2.0f); phase_to_use = std::fmod(pmult*m_phase,1.0); } float r = std::sin(2*3.14159265359*phase_to_use); m_phase += m_phase_inc; //m_phase = std::fmod(m_phase,1.0); m_phase = wrap_value(0.0,m_phase,1.0); //if (m_phase>=1.0f) // m_phase-=m_phase_inc; return r; } }; class ScaleOscillator { public: float m_gain_smooth_amt = 0.99f; std::string getScaleName() { if (m_curScale>=0 && m_curScale<m_scalenames.size()) { return m_scalenames[m_curScale]; } return "No scale name"; } std::vector<std::string> m_scalenames; void initScales() { double root_freq = dsp::FREQ_C4/16.0; std::string dir = asset::plugin(pluginInstance, "res/scale_oscillator_scales"); auto scalafiles = rack::system::getEntriesRecursive(dir,3); for (auto& e : scalafiles) { auto pitches = loadScala(e,true,0.0,128); std::vector<float> scale; for (int i=0;i<pitches.size();++i) { double p = pitches[i]; //rescale(scale[i],-5.0f,5.0f,0.0f,120.0f); double freq = root_freq * std::pow(1.05946309436,p); scale.push_back(freq); } m_scale_bank.push_back(scale); m_scalenames.push_back(rack::string::filename(e)); } } ScaleOscillator() { m_fold_smoother.setAmount(0.99); for (int i=0;i<m_oscils.size();++i) { //m_oscils[i].initialise([](float x){ return sin(x); },4096); m_oscils[i].prepare(1,44100.0f); m_osc_gain_smoothers[i*2+0].setAmount(m_gain_smooth_amt); m_osc_gain_smoothers[i*2+1].setAmount(m_gain_smooth_amt); m_osc_freq_smoothers[i*2+0].setAmount(0.99); m_osc_freq_smoothers[i*2+1].setAmount(0.99); m_osc_gains[i*2+0] = 1.0f; m_osc_gains[i*2+1] = 1.0f; m_osc_freqs[i*2+0] = 440.0f; m_osc_freqs[i*2+1] = 440.0f; fms[i] = 0.0f; } m_norm_smoother.setAmount(0.999); std::array<float,9> ratios{81.0f/80.0f,9.0f/8.0f,1.2f,1.25f,1.333333f,1.5f,9.0f/5.0f,15.0f/8.0f,2.0f}; m_scale_bank.push_back(std::vector<float>()); m_scalenames.push_back("Continuum"); m_scalenames.push_back("Syntonic comma"); m_scalenames.push_back("Major tone (JI)"); m_scalenames.push_back("Minor third JI"); m_scalenames.push_back("Major third JI"); m_scalenames.push_back("Fourth JI"); m_scalenames.push_back("Fifth JI"); m_scalenames.push_back("Minor seventh JI"); m_scalenames.push_back("Major seventh JI"); m_scalenames.push_back("Octave"); double root_freq = dsp::FREQ_C4/16.0; for (int i=0;i<ratios.size();++i) { double freq = root_freq; std::vector<float> scale; while (freq<21000.0) { scale.push_back(freq); freq *= ratios[i]; } m_scale_bank.push_back(scale); } std::vector<std::string> scalafiles; std::string dir = asset::plugin(pluginInstance, "res/scala_scales"); scalafiles.push_back(dir+"/penta_opt.scl"); scalafiles.push_back(dir+"/Ancient Greek Archytas Enharmonic.scl"); scalafiles.push_back(dir+"/Ancient Greek Archytas Diatonic.scl"); scalafiles.push_back(dir+"/octone.scl"); scalafiles.push_back(dir+"/Chopi Xylophone.scl"); scalafiles.push_back(dir+"/bohlen_quintuple_j.scl"); scalafiles.push_back(dir+"/equally tempered minor.scl"); scalafiles.push_back(dir+"/12tet.scl"); scalafiles.push_back(dir+"/tritones.scl"); scalafiles.push_back(dir+"/tetra01.scl"); scalafiles.push_back(dir+"/major_chord_et.scl"); scalafiles.push_back(dir+"/major_chord_ji.scl"); scalafiles.push_back(dir+"/minor_chord_et.scl"); scalafiles.push_back(dir+"/minor_chord_ji.scl"); for (auto& e : scalafiles) { auto pitches = loadScala(e,true,0.0,128); std::vector<float> scale; for (int i=0;i<pitches.size();++i) { double p = pitches[i]; //rescale(scale[i],-5.0f,5.0f,0.0f,120.0f); double freq = root_freq * std::pow(1.05946309436,p); scale.push_back(freq); } m_scale_bank.push_back(scale); m_scalenames.push_back(rack::string::filename(e)); } double freq = root_freq; std::vector<float> scale; int i=1; while (freq<20000.0) { freq = i * root_freq; scale.push_back(freq); ++i; } m_scale_bank.push_back(scale); m_scalenames.push_back("Harmonic series"); m_scale.reserve(2048); m_scale = m_scale_bank[0]; updateOscFrequencies(); } void updateOscFrequencies() { double maxpitch = rescale(m_spread,0.0f,1.0f,m_root_pitch,72.0f); auto xfades = makeArray<float,16>(); int lastoscili = m_active_oscils-1; if (lastoscili==0) lastoscili = 1; //float roothz = rack::dsp::FREQ_C4*std::pow(1.05946309436,m_root_pitch); for (int i=0;i<m_active_oscils;++i) { float normpos = rescale((float)i,0,lastoscili,0.0f,1.0f); if (m_spread_dist<0.5) { float sh = rescale(m_spread_dist,0.0f,0.5f,3.0f,1.0f); normpos = std::pow(normpos,sh); } else { float sh = rescale(m_spread_dist,0.5f,1.0f,1.0f,3.0f); normpos = 1.0f-std::pow(1.0f-normpos,sh); } float pitch = rescale(normpos,0.0f,1.0f, m_root_pitch,m_root_pitch+(72.0f*m_spread)); float f = rack::dsp::FREQ_C4*std::pow(1.05946309436,pitch); //float f = rescale(normpos,0.0f,1.0f,roothz,roothz+12000.0f*m_spread); float f0 = f; float f1 = f; float diff = 0.5f; quantize_to_scale(f,m_scale,f0,f1,diff); xfades[i] = diff; //f = quantize_to_grid(f,m_scale,1.0); float detun0 = rescale((float)i,0,m_active_oscils,0.0f,f0*0.10f*m_detune); float detun1 = rescale((float)i,0,m_active_oscils,0.0f,f1*0.10f*m_detune); if (i % 2 == 1) { detun0 = -detun0; detun1 = -detun1; } f0 = clamp(f0*m_freqratio+detun0,1.0f,20000.0f); f1 = clamp(f1*m_freqratio+detun1,1.0f,20000.0f); m_osc_freqs[i*2+0] = f0; m_osc_freqs[i*2+1] = f1; } float xs0 = 0.0f; float xs1 = 1.0f; float ys0 = 1.0f; float ys1 = 1.0f; if (m_balance<0.25f) { xs0 = 0.0f; ys0 = 1.0f; xs1 = rescale(m_balance,0.0f,0.25f,0.01f,1.0f); ys1 = 0.0f; } else if (m_balance>=0.25f && m_balance<0.5f) { xs0 = 0.0f; ys0 = 1.0f; xs1 = 1.0f; ys1 = rescale(m_balance,0.25f,0.5f,0.0f,1.0f); } else if (m_balance>=0.5f && m_balance<0.75f) { xs0 = 0.0f; ys0 = rescale(m_balance,0.5f,0.75f,1.0f,0.0f); xs1 = 1.0f; ys1 = 1.0f; } else { xs0 = rescale(m_balance,0.75f,1.0f,0.0f,0.99f); ys0 = 0.0f; xs1 = 1.0f; ys1 = 1.0f; } for (int i=0;i<m_oscils.size();++i) { float bypassgain = 0.0f; if (i<m_active_oscils) bypassgain = 1.0f; /* int gtindex = rescale((float)i,0,m_active_oscils-1,0.0f,16.0f); if (gtindex>16) gtindex = 16; if (gtindex<0) gtindex = 0; float g0 = g_balance_tables[index0][gtindex]; float g1 = g_balance_tables[index1][gtindex]; float g2 = g0+(g1-g0)*frac; float db = rescale(g2,0.0f,1.0f,-60.0f,0.0f); //float db = rescale((float)i,0,m_active_oscils,gain0,gain1); */ /* float f = m_osc_freqs[i]; float f2 = f*f; float awamp = ((424.36f + f2) * std::sqrt((11599.3f + f2) * (544496.f + f2)) * (148693636.f + f2)) / (148693636.f * f2 * f2); awamp *= (1.0f/17); awamp = clamp(awamp,0.0f,1.0f); */ float normx = rescale((float)i,0,lastoscili,0.0f,1.0f); float amp = 0.0f; if (normx<=1.0f) { amp = rescale(normx,xs0,xs1,ys0,ys1); amp = clamp(amp,0.0f,1.0f); } //amp *= awamp; //float db = rescale(amp,0.0f,1.0f,-72.0,0.0f); //if (db<-72.0f) db = -72.0f; float gain = amp*bypassgain; //rack::dsp::dbToAmplitude(db)*bypassgain; m_osc_gains[i*2+0] = gain*(1.0-xfades[i]); m_osc_gains[i*2+1] = gain*xfades[i]; } } std::array<float,16> fms; void processNextFrame(float* outbuf, float samplerate) { int oscilsused = 0; int lastosci = m_active_oscils-1; if (m_fm_mode<2) { float hz0 = m_osc_freq_smoothers[0].process(m_osc_freqs[0]); float hz1 = m_osc_freq_smoothers[1].process(m_osc_freqs[1]); m_oscils[0].setFrequencies(hz0,hz1,samplerate); } else { float hz0 = m_osc_freq_smoothers[lastosci*2+0].process(m_osc_freqs[lastosci*2+0]); float hz1 = m_osc_freq_smoothers[lastosci*2+1].process(m_osc_freqs[lastosci*2+1]); m_oscils[lastosci].setFrequencies(hz0,hz1,samplerate); } float foldgain = m_fold_smoother.process((1.0f+m_fold*5.0f)); for (int i=0;i<m_oscils.size();++i) { float gain0 = m_osc_gain_smoothers[i*2+0].process(m_osc_gains[i*2+0]); float gain1 = m_osc_gain_smoothers[i*2+1].process(m_osc_gains[i*2+1]); simd::float_4 ss = m_oscils[i].processSample(0.0f); float s0 = ss[0]; float s1 = ss[1]; fms[i] = s0; float s2 = s0 * gain0 + s1 * gain1; s2 = reflect_value(-1.0f,s2*foldgain,1.0f); outbuf[i] = s2; } int fm_mode = m_fm_mode; if (fm_mode == 0) { for (int i=1;i<m_active_oscils;++i) { float hz0 = m_osc_freq_smoothers[i*2+0].process(m_osc_freqs[i*2+0]); hz0 = hz0+(fms[0]*m_fm_amt*hz0*2.0f); float hz1 = m_osc_freq_smoothers[i*2+1].process(m_osc_freqs[i*2+1]); hz1 = hz1+(fms[0]*m_fm_amt*hz1*2.0f); m_oscils[i].setFrequencies(hz0,hz1,samplerate); } } else if (fm_mode == 1) { for (int i=1;i<m_active_oscils;++i) { float hz0 = m_osc_freq_smoothers[i*2+0].process(m_osc_freqs[i*2+0]); hz0 = hz0+(fms[i-1]*m_fm_amt*hz0); float hz1 = m_osc_freq_smoothers[i*2+1].process(m_osc_freqs[i*2+1]); hz1 = hz1+(fms[i-1]*m_fm_amt*hz1); m_oscils[i].setFrequencies(hz0,hz1,samplerate); } } else if (m_fm_mode == 2) { for (int i=0;i<m_active_oscils-1;++i) { float hz0 = m_osc_freq_smoothers[i*2+0].process(m_osc_freqs[i*2+0]); hz0 = hz0+(fms[lastosci]*m_fm_amt*hz0*2.0f); float hz1 = m_osc_freq_smoothers[i*2+1].process(m_osc_freqs[i*2+1]); hz1 = hz1+(fms[lastosci]*m_fm_amt*hz1*2.0f); m_oscils[i].setFrequencies(hz0,hz1,samplerate); } } } int m_curScale = 0; void setScale(float x) { x = clamp(x,0.0f,1.0f); int i = x * (m_scale_bank.size()-1); if (i!=m_curScale) { m_curScale = i; m_scale = m_scale_bank[m_curScale]; } } void setFMAmount(float a) { a = clamp(a,0.0f,1.0f); m_fm_amt = std::pow(a,2.0f); } int m_warp_mode = 0; void setWarp(int mode,float w) { if (w!=m_warp || mode!=m_warp_mode) { w = clamp(w,0.0f,1.0f); m_warp = w; m_warp_mode = clamp(mode,0,2); for (int i=0;i<m_oscils.size();++i) m_oscils[i].setPhaseWarp(m_warp_mode,w); } } void setSpread(float s) { m_spread = clamp(s,0.0f,1.0f); } void setRootPitch(float p) { p = clamp(p,-36.0f,36.0f); m_root_pitch = p; //updateOscFrequencies(); } void setPitchOffset(float p) { p = clamp(p,-36.0f,36.0f); m_freqratio = std::pow(1.05946309436,p); //updateOscFrequencies(); } void setBalance(float b) { m_balance = clamp(b,0.0f,1.0f); } void setDetune(float d) { m_detune = clamp(d,0.0f,1.0f); } void setFold(float f) { f = clamp(f,0.0f,1.0f); m_fold = std::pow(f,3.0f); } void setOscCount(int c) { if (c<1) c = 1; if (c>16) c = 16; m_active_oscils = c; } int getOscCount() { return m_active_oscils; } void setFMMode(int m) { if (m<0) m = 0; if (m>2) m = 2; m_fm_mode = m; } void setSpreadDistribution(float x) { m_spread_dist = clamp(x,0.0f,1.0f); } void setFrequencySmoothing(float s) { if (s!=m_freq_smooth) { float shaped = 1.0f-std::pow(1.0f-s,3.0f); shaped = rescale(shaped,0.0f,1.0f,0.99f,0.99999f); for (int i=0;i<m_osc_freq_smoothers.size();++i) m_osc_freq_smoothers[i].setAmount(shaped); m_freq_smooth = s; } } OnePoleFilter m_norm_smoother; private: std::array<SIMDSimpleOsc,16> m_oscils; std::array<float,32> m_osc_gains; std::array<float,32> m_osc_freqs; std::array<OnePoleFilter,32> m_osc_gain_smoothers; std::array<OnePoleFilter,32> m_osc_freq_smoothers; OnePoleFilter m_fold_smoother; std::vector<float> m_scale; float m_spread = 1.0f; float m_root_pitch = 0.0f; float m_freqratio = 1.0f; float m_balance = 0.0f; float m_detune = 0.1; float m_fold = 0.0f; float m_fm_amt = 0.0f; int m_active_oscils = 16; float m_warp = 1.1f; int m_fm_mode = 0; float m_freq_smooth = -1.0f; float m_spread_dist = 0.5f; std::vector<std::vector<float>> m_scale_bank; }; class XScaleOsc : public Module { public: enum OUTPUTS { OUT_AUDIO_1, OUT_LAST }; enum INPUTS { IN_ROOT, IN_PITCH, IN_BALANCE, IN_SPREAD, IN_FOLD, IN_DETUNE, IN_NUM_OSCS, IN_FM_AMT, IN_WARP, IN_SCALE, IN_LAST }; enum PARAMETERS { PAR_ROOT, PAR_PITCH_OFFS, PAR_BALANCE, PAR_DETUNE, PAR_NUM_OSCS, PAR_FOLD, PAR_SPREAD, PAR_WARP, PAR_FM_AMT, PAR_FM_MODE, PAR_SCALE, PAR_SCALE_BANK, PAR_WARP_MODE, PAR_NUM_OUTPUTS, PAR_FREQSMOOTH, PAR_SPREAD_DIST, PAR_ROOT_ATTN, PAR_BAL_ATTN, PAR_PITCH_ATTN, PAR_SPREAD_ATTN, PAR_FM_ATTN, PAR_SCALE_ATTN, PAR_DETUNE_ATTN, PAR_FOLD_ATTN, PAR_WARP_ATTN, PAR_LAST }; XScaleOsc() { config(PAR_LAST,IN_LAST,OUT_LAST); configParam(PAR_BALANCE,0.0f,1.0f,0.4f,"Balance"); configParam(PAR_ROOT,-36.0f,36.0f,0.0f,"Root"); configParam(PAR_PITCH_OFFS,-36.0f,36.0f,0.0f,"Pitch offset"); configParam(PAR_DETUNE,0.0f,1.0f,0.0f,"Detune"); configParam(PAR_NUM_OSCS,1.0f,16.0f,16.0f,"Num oscillators"); configParam(PAR_FOLD,0.0f,1.0f,0.0f,"Fold"); configParam(PAR_SPREAD,0.0f,1.0f,0.5f,"Spread"); configParam(PAR_WARP,0.0f,1.0f,0.0f,"Warp"); configParam(PAR_FM_AMT,0.0f,1.0f,0.0f,"FM Amount"); configParam(PAR_FM_MODE,0.0f,2.0f,0.0f,"FM Mode"); configParam(PAR_SCALE,0.0f,1.0f,0.0f,"Scale"); configParam(PAR_SCALE_BANK,0.0f,1.0f,0.0f,"Scale bank"); configParam(PAR_WARP_MODE,0.0f,2.0f,0.0f,"Warp Mode"); configParam(PAR_NUM_OUTPUTS,1.0f,16.0f,1.0f,"Num outputs"); configParam(PAR_FREQSMOOTH,0.0f,1.0f,0.1f,"Pitch smoothing"); configParam(PAR_SPREAD_DIST,0.0f,1.0f,0.5f,"Spread distribution"); configParam(PAR_SPREAD_ATTN,-1.0f,1.0f,0.0f,"Spread CV level"); configParam(PAR_ROOT_ATTN,-1.0f,1.0f,1.0f,"Root CV level"); configParam(PAR_BAL_ATTN,-1.0f,1.0f,0.0f,"Balance CV level"); configParam(PAR_PITCH_ATTN,-1.0f,1.0f,1.0f,"Pitch CV level"); configParam(PAR_FM_ATTN,-1.0f,1.0f,0.0f,"FM CV level"); configParam(PAR_SCALE_ATTN,-1.0f,1.0f,0.0f,"Scale CV level"); configParam(PAR_FOLD_ATTN,-1.0f,1.0f,0.0f,"Fold CV level"); configParam(PAR_WARP_ATTN,-1.0f,1.0f,0.0f,"Warp CV level"); configParam(PAR_DETUNE_ATTN,-1.0f,1.0f,0.0f,"Detune CV level"); m_pardiv.setDivision(16); } float m_samplerate = 0.0f; inline float getModParValue(int parId, int inId, int attnId=-1, bool doClamp=false, float clampMin = 0.0f, float clampMax = 0.0f) { float p = params[parId].getValue(); if (attnId>=0) p += inputs[inId].getVoltage()*0.1f*params[attnId].getValue(); else p += inputs[inId].getVoltage()*0.1f; if (doClamp) p = clamp(p,clampMin,clampMax); return p; } void process(const ProcessArgs& args) override { if (m_samplerate!=args.sampleRate) { for (int i=0;i<16;++i) { float normfreq = 25.0/args.sampleRate; float q = sqrt(2.0)/2.0; m_hpfilts[i].setParameters(rack::dsp::BiquadFilter::HIGHPASS,normfreq,q,1.0f); } m_samplerate = args.sampleRate; } if (m_pardiv.process()) { float bal = getModParValue(PAR_BALANCE,IN_BALANCE,PAR_BAL_ATTN); m_osc.setBalance(bal); float detune = getModParValue(PAR_DETUNE,IN_DETUNE,PAR_DETUNE_ATTN); m_osc.setDetune(detune); float fold = getModParValue(PAR_FOLD,IN_FOLD,PAR_FOLD_ATTN); m_osc.setFold(fold); float pitch = params[PAR_PITCH_OFFS].getValue(); pitch += inputs[IN_PITCH].getVoltage()*12.0f*params[PAR_PITCH_ATTN].getValue(); pitch = clamp(pitch,-48.0f,48.0); m_osc.setPitchOffset(pitch); float root = params[PAR_ROOT].getValue(); root += inputs[IN_ROOT].getVoltage()*12.0f*params[PAR_ROOT_ATTN].getValue(); m_osc.setRootPitch(root); float osccount = params[PAR_NUM_OSCS].getValue(); osccount += inputs[IN_NUM_OSCS].getVoltage() * (16.0f/10.0f); m_osc.setOscCount(osccount); float spread = getModParValue(PAR_SPREAD,IN_SPREAD,PAR_SPREAD_ATTN); m_osc.setSpread(spread); float sdist = params[PAR_SPREAD_DIST].getValue(); m_osc.setSpreadDistribution(sdist); float warp = getModParValue(PAR_WARP,IN_WARP,PAR_WARP_ATTN); int wmode = params[PAR_WARP_MODE].getValue(); m_osc.setWarp(wmode,warp); float fm = getModParValue(PAR_FM_AMT,IN_FM_AMT,PAR_FM_ATTN); m_osc.setFMAmount(fm); int fmmode = params[PAR_FM_MODE].getValue(); m_osc.setFMMode(fmmode); float scale = getModParValue(PAR_SCALE,IN_SCALE,PAR_SCALE_ATTN); m_osc.setScale(scale); float psmooth = params[PAR_FREQSMOOTH].getValue(); m_osc.setFrequencySmoothing(psmooth); m_osc.updateOscFrequencies(); } float outs[16]; m_osc.processNextFrame(outs,args.sampleRate); int numOutputs = params[PAR_NUM_OUTPUTS].getValue(); int numOscs = m_osc.getOscCount(); outputs[OUT_AUDIO_1].setChannels(numOutputs); float mixed[16]; for (int i=0;i<numOutputs;++i) mixed[i] = 0.0f; for (int i=0;i<numOscs;++i) { int outindex = i % numOutputs; mixed[outindex] += outs[i]; } float nnosc = rescale((float)numOscs,1,16,0.0f,1.0f); float normscaler = 0.25f+0.75f*std::pow(1.0f-nnosc,3.0f); float outgain = m_osc.m_norm_smoother.process(normscaler); for (int i=0;i<numOutputs;++i) { float outsample = mixed[i]*5.0f*outgain; outsample = m_hpfilts[i].process(outsample); outputs[OUT_AUDIO_1].setVoltage(outsample,i); } } ScaleOscillator m_osc; dsp::ClockDivider m_pardiv; dsp::TBiquadFilter<float> m_hpfilts[16]; }; class XScaleOscWidget : public ModuleWidget { public: XScaleOscWidget(XScaleOsc* m) { setModule(m); box.size.x = RACK_GRID_WIDTH * 23; addChild(new LabelWidget({{1,6},{box.size.x,1}}, "SCALE OSCILLATOR",15,nvgRGB(255,255,255),LabelWidget::J_CENTER)); auto port = new PortWithBackGround(m,this,XScaleOsc::OUT_AUDIO_1,1,30,"AUDIO OUT 1",true); float xc = 1.0f; float yc = 80.0f; KnobInAttnWidget* kwid = nullptr; auto defrand = [](){ return random::uniform(); }; addChild(kwid = new KnobInAttnWidget(this,"ROOT",XScaleOsc::PAR_ROOT, XScaleOsc::IN_ROOT,XScaleOsc::PAR_ROOT_ATTN,xc,yc)); kwid->m_knob->GetRandomizedValue = defrand; xc+=82.0f; addChild(kwid = new KnobInAttnWidget(this,"BALANCE",XScaleOsc::PAR_BALANCE, XScaleOsc::IN_BALANCE,XScaleOsc::PAR_BAL_ATTN,xc,yc)); kwid->m_knob->GetRandomizedValue = defrand; xc+=82.0f; addChild(new KnobInAttnWidget(this,"PITCH",XScaleOsc::PAR_PITCH_OFFS, XScaleOsc::IN_PITCH,XScaleOsc::PAR_PITCH_ATTN,xc,yc)); xc+=82.0f; addChild(kwid = new KnobInAttnWidget(this,"SPREAD",XScaleOsc::PAR_SPREAD, XScaleOsc::IN_SPREAD,XScaleOsc::PAR_SPREAD_ATTN,xc,yc)); kwid->m_knob->GetRandomizedValue = defrand; xc = 1.0f; yc += 47.0f; addChild(kwid = new KnobInAttnWidget(this,"DETUNE",XScaleOsc::PAR_DETUNE, XScaleOsc::IN_DETUNE,XScaleOsc::PAR_DETUNE_ATTN,xc,yc)); kwid->m_knob->GetRandomizedValue = defrand; xc += 82.0f; addChild(kwid = new KnobInAttnWidget(this,"FOLD",XScaleOsc::PAR_FOLD, XScaleOsc::IN_FOLD,XScaleOsc::PAR_FOLD_ATTN,xc,yc)); kwid->m_knob->GetRandomizedValue = defrand; xc += 82.0f; addChild(new KnobInAttnWidget(this,"NUM OSCS",XScaleOsc::PAR_NUM_OSCS, XScaleOsc::IN_NUM_OSCS,-1,xc,yc,true)); xc += 82.0f; addChild(new KnobInAttnWidget(this,"WARP",XScaleOsc::PAR_WARP, XScaleOsc::IN_WARP,XScaleOsc::PAR_WARP_ATTN,xc,yc)); xc = 1.0f; yc += 47.0f; addChild(kwid = new KnobInAttnWidget(this,"FM AMOUNT",XScaleOsc::PAR_FM_AMT, XScaleOsc::IN_FM_AMT,XScaleOsc::PAR_FM_ATTN,xc,yc)); kwid->m_knob->GetRandomizedValue = defrand; xc += 82.0f; addChild(new KnobInAttnWidget(this,"FM MODE",XScaleOsc::PAR_FM_MODE, -1,-1,xc,yc,true)); xc += 82.0f; addChild(new KnobInAttnWidget(this,"SCALE",XScaleOsc::PAR_SCALE, XScaleOsc::IN_SCALE,XScaleOsc::PAR_SCALE_ATTN,xc,yc)); xc += 82.0f; addChild(new KnobInAttnWidget(this,"WARP MODE",XScaleOsc::PAR_WARP_MODE, -1,-1,xc,yc,true)); xc = 1.0f; yc += 47.0f; addChild(new KnobInAttnWidget(this,"NUM OUTPUTS",XScaleOsc::PAR_NUM_OUTPUTS, -1,-1,xc,yc,true)); xc += 82.0f; addChild(new KnobInAttnWidget(this,"PITCH SMOOTHING",XScaleOsc::PAR_FREQSMOOTH, -1,-1,xc,yc,false)); xc += 82.0f; addChild(new KnobInAttnWidget(this,"SPREAD DISTRIBUTION",XScaleOsc::PAR_SPREAD_DIST, -1,-1,xc,yc,false)); } void draw(const DrawArgs &args) override { nvgSave(args.vg); float w = box.size.x; float h = box.size.y; nvgBeginPath(args.vg); nvgFillColor(args.vg, nvgRGBA(0x50, 0x50, 0x50, 0xff)); nvgRect(args.vg,0.0f,0.0f,w,h); nvgFill(args.vg); XScaleOsc* m = dynamic_cast<XScaleOsc*>(module); if (m) { auto scalename = rack::string::filename(m->m_osc.getScaleName()); nvgFontSize(args.vg, 20); nvgFontFaceId(args.vg, getDefaultFont(0)->handle); nvgTextLetterSpacing(args.vg, -1); nvgFillColor(args.vg, nvgRGBA(0xff, 0xff, 0xff, 0xff)); nvgText(args.vg,1.0f,h-20.0f,scalename.c_str(),nullptr); } nvgRestore(args.vg); ModuleWidget::draw(args); } }; Model* modelXScaleOscillator = createModel<XScaleOsc, XScaleOscWidget>("XScaleOscillator");
43160386750013d6ae9f787251231b5d5f2ff106
4ae49b6818fd593bc8c4724c63f774b4401dbc8f
/src/mcmc/MHVariable.cpp
8ff0f775092afe971487b258f1effc2b83370f50
[]
no_license
Chronomodel/chronomodel
c2de58f8da03471631fdbf63739b79617752eace
f3b6082c00e251836f7b40f5b54016e45edf6b2e
refs/heads/master
2023-08-23T22:04:55.820153
2019-02-15T09:23:21
2019-02-15T09:23:21
29,787,037
14
1
null
null
null
null
UTF-8
C++
false
false
10,120
cpp
MHVariable.cpp
/* --------------------------------------------------------------------- Copyright or © or Copr. CNRS 2014 - 2018 Authors : Philippe LANOS Helori LANOS Philippe DUFRESNE This software is a computer program whose purpose is to create chronological models of archeological data using Bayesian statistics. This software is governed by the CeCILL V2.1 license under French law and abiding by the rules of distribution of free software. You can use, modify and/ or redistribute the software under the terms of the CeCILL license as circulated by CEA, CNRS and INRIA at the following URL "http://www.cecill.info". As a counterpart to the access to the source code and rights to copy, modify and redistribute granted by the license, users are provided only with a limited warranty and the software's author, the holder of the economic rights, and the successive licensors have only limited liability. In this respect, the user's attention is drawn to the risks associated with loading, using, modifying and/or developing or reproducing the software by the user in light of its specific status of free software, that may mean that it is complicated to manipulate, and that also therefore means that it is reserved for developers and experienced professionals having in-depth computer knowledge. Users are therefore encouraged to load and test the software's suitability as regards their requirements in conditions enabling the security of their systems and/or data to be ensured and, more generally, to use and operate it in the same conditions as regards security. The fact that you are presently reading this means that you have had knowledge of the CeCILL V2.1 license and that you accept its terms. --------------------------------------------------------------------- */ #include "MHVariable.h" #include "StdUtilities.h" #include "QtUtilities.h" #include "Generator.h" #include <QDebug> /** Default constructor */ MHVariable::MHVariable(): mLastAcceptsLength(0), mGlobalAcceptation(0), mHistoryAcceptRateMH(nullptr) { /*mAllAccepts = new (std::nothrow) QVector<bool>(); mHistoryAcceptRateMH = new (std::nothrow) QVector<double>();*/ mAllAccepts = new QVector<bool>(); mHistoryAcceptRateMH = new QVector<double>(); } /** Copy constructor */ MHVariable::MHVariable( const MHVariable& origin) { // MetropolisVariable(origin); mX = origin.mX; mRawTrace = new QVector<double>(origin.mRawTrace->size()); std::copy(origin.mRawTrace->begin(),origin.mRawTrace->end(),mRawTrace->begin()); mFormatedTrace = new QVector<double>(origin.mFormatedTrace->size()); std::copy(origin.mFormatedTrace->begin(),origin.mFormatedTrace->end(),mFormatedTrace->begin()); mSupport = origin.mSupport; mFormat = origin.mFormat; mHisto = origin.mHisto; mChainsHistos = origin.mChainsHistos; mCorrelations = origin.mCorrelations; mHPD = origin.mHPD; mCredibility = origin.mCredibility; mExactCredibilityThreshold = origin.mExactCredibilityThreshold; mResults = origin.mResults; mChainsResults = origin.mChainsResults; mfftLenUsed = origin.mBandwidthUsed; mBandwidthUsed = origin.mBandwidthUsed; mThresholdUsed = origin.mThresholdUsed; mtminUsed = origin.mtminUsed; mtmaxUsed = origin.mtmaxUsed; mAllAccepts = new QVector<bool>(origin.mAllAccepts->size()); mHistoryAcceptRateMH = new QVector<double>(origin.mHistoryAcceptRateMH->size()); } MHVariable::~MHVariable() { mAllAccepts->~QVector(); mHistoryAcceptRateMH->~QVector(); // mRawTrace and mFormatedTrace are destroye by the MetropolisVariable destructor // mRawTrace->~QVector();// = nullptr;; // mFormatedTrace->~QVector();// = nullptr;; } bool MHVariable::tryUpdate(const double x, const double rapport) { if (mLastAccepts.length() >= mLastAcceptsLength) mLastAccepts.removeAt(0); bool accepted (false); if (rapport >= 1.) accepted = true; else { const double uniform = Generator::randomUniform(); accepted = (rapport >= uniform); } if (accepted) mX = x; mLastAccepts.append(accepted); mAllAccepts->append(accepted); return accepted; } void MHVariable::reset() { MetropolisVariable::reset(); mLastAccepts.clear(); mAllAccepts->clear();// mAllAccepts.clear(); //don't clean, avalable for cumulate chain mLastAccepts.squeeze(); mAllAccepts->squeeze(); } void MHVariable::reserve(const int reserve) { MetropolisVariable::reserve(reserve); mAllAccepts->reserve(reserve); mHistoryAcceptRateMH->reserve(reserve); } MHVariable& MHVariable::copy(MHVariable const& origin) { mX = origin.mX; mRawTrace->resize(origin.mRawTrace->size()); std::copy(origin.mRawTrace->begin(),origin.mRawTrace->end(),mRawTrace->begin()); mFormatedTrace->resize(origin.mFormatedTrace->size()); std::copy(origin.mFormatedTrace->begin(),origin.mFormatedTrace->end(),mFormatedTrace->begin()); mSupport = origin.mSupport; mFormat = origin.mFormat; mHisto = origin.mHisto; mChainsHistos = origin.mChainsHistos; mCorrelations = origin.mCorrelations; mHPD = origin.mHPD; mCredibility = origin.mCredibility; mExactCredibilityThreshold = origin.mExactCredibilityThreshold; mResults = origin.mResults; mChainsResults = origin.mChainsResults; mfftLenUsed = origin.mBandwidthUsed; mBandwidthUsed = origin.mBandwidthUsed; mThresholdUsed = origin.mThresholdUsed; mtminUsed = origin.mtminUsed; mtmaxUsed = origin.mtmaxUsed; mSigmaMH = origin.mSigmaMH; mLastAccepts = origin.mLastAccepts; mLastAcceptsLength = origin.mLastAcceptsLength; mAllAccepts->resize(origin.mAllAccepts->size()); std::copy(origin.mAllAccepts->begin(),origin.mAllAccepts->end(),mAllAccepts->begin()); mGlobalAcceptation = origin.mGlobalAcceptation; mHistoryAcceptRateMH->resize(origin.mHistoryAcceptRateMH->size()); std::copy(origin.mHistoryAcceptRateMH->begin(),origin.mHistoryAcceptRateMH->end(),mHistoryAcceptRateMH->begin()); mProposal = origin.mProposal; return *this; } MHVariable& MHVariable::operator=( MHVariable const& origin) { copy(origin); return *this; } double MHVariable::getCurrentAcceptRate() { Q_ASSERT(!mLastAccepts.isEmpty()); double sum (0.); sum = std::accumulate(mLastAccepts.begin(), mLastAccepts.end(), sum,[](double s, double a){return s+(a ? 1. : 0.);}); //#include <numeric> sum = sum / (double)mLastAccepts.size(); return sum ; } void MHVariable::saveCurrentAcceptRate() { const double rate = 100. * getCurrentAcceptRate(); mHistoryAcceptRateMH->push_back(rate); } QVector<double> MHVariable::acceptationForChain(const QList<ChainSpecs> &chains, int index) { QVector<double> accept(0); int shift (0); const int reserveSize = (int) ceil(chains.at(index).mNumBurnIter + (chains.at(index).mBatchIndex * chains.at(index).mNumBatchIter) + chains.at(index).mNumRunIter / chains.at(index).mThinningInterval); accept.reserve(reserveSize); for (int i=0; i<chains.size(); ++i) { // We add 1 for the init const int chainSize = 1 +chains.at(i).mNumBurnIter + (chains.at(i).mBatchIndex * chains.at(i).mNumBatchIter) + chains.at(i).mNumRunIter / chains.at(i).mThinningInterval; if (i == index) { // could be done with //accept.resize(chainSize //std::copy(from_vector.begin(), from_vector.end(), to_vector.begin()); for (int j=0; j<chainSize; ++j) accept.append(mHistoryAcceptRateMH->at(shift + j)); break; } else shift += chainSize; } return accept; } void MHVariable::generateGlobalRunAcceptation(const QList<ChainSpecs> &chains) { double accepted (0.); double acceptsLength (0.); int shift (0); for (auto&& chain : chains) { int burnAdaptSize = chain.mNumBurnIter + (chain.mBatchIndex * chain.mNumBatchIter); int runSize = chain.mNumRunIter; shift += burnAdaptSize; for (int j=shift; (j<shift + runSize) && (j<mAllAccepts->size()); ++j) { if (mAllAccepts->at(j)) ++accepted; } shift += runSize; acceptsLength += runSize; } mGlobalAcceptation = accepted / acceptsLength; } void MHVariable::generateNumericalResults(const QList<ChainSpecs> &chains) { MetropolisVariable::generateNumericalResults(chains); generateGlobalRunAcceptation(chains); } QString MHVariable::resultsString(const QString& nl, const QString& noResultMessage, const QString& unit, DateConversion formatFunc, const bool forCSV) const { QString result = MetropolisVariable::resultsString(nl, noResultMessage, unit, formatFunc, forCSV); if (!mProposal.isEmpty()) { if (forCSV) result += nl + tr("Acceptance rate (all acquire iterations) : %1 % (%2)").arg(stringForCSV(mGlobalAcceptation*100.), mProposal); else result += nl + tr("Acceptance rate (all acquire iterations) : %1 % (%2)").arg(stringForLocal(mGlobalAcceptation*100.), mProposal); } return result; } QDataStream &operator<<( QDataStream &stream, const MHVariable &data ) { stream << dynamic_cast<const MetropolisVariable&>(data); /* owned by MHVariable*/ stream << *(data.mAllAccepts); stream << *(data.mHistoryAcceptRateMH); //*out << this->mProposal; // it's a QString, already set stream << data.mSigmaMH; return stream; } QDataStream &operator>>( QDataStream &stream, MHVariable &data ) { /* herited from MetropolisVariable*/ stream >> dynamic_cast<MetropolisVariable&>(data); if (data.mAllAccepts) data.mAllAccepts->clear(); else data.mAllAccepts = new QVector<bool>(); stream >> *(data.mAllAccepts); if (data.mHistoryAcceptRateMH) data.mHistoryAcceptRateMH->clear(); else data.mHistoryAcceptRateMH = new QVector<double>(); stream >> *(data.mHistoryAcceptRateMH); stream >> data.mSigmaMH; return stream; }
716e9f0a6d0fee90f21f747839e13d6274b55977
ac9fa0fdfc2624f83e7c05eeeee92c50d4fc1596
/c++/1.2 Polimorfismo de sobrecarga y sobre-escritura/1.2.2 Polimofrismo por sobrescritura/SeleccionV2/Futbolista.h
466fb865d59a0bb56c03dc5f1e8066cf37d5b57c
[]
no_license
renecruz/prog_ii
1a234c47b35dda1437e953a6f1fb27074b3a0c04
6db34154f379672036a45d4dd6418b6cca83b88d
refs/heads/master
2021-07-05T21:01:37.144892
2021-05-12T16:06:47
2021-05-12T16:06:47
238,100,730
0
2
null
null
null
null
UTF-8
C++
false
false
424
h
Futbolista.h
#include <iostream> using namespace std; class Futbolista : public Deportista { private: string posicion; public: Futbolista(string nombre, int edad, float estatura, string posicion) : Deportista(nombre, edad, estatura) { this->posicion = posicion; } string toString() { return "{" + Deportista::toString() + " posicion='" + posicion + "'" + "}"; } };
7584bcf1cc223c4bba796dc1ee385801fe10fbe6
5cc145f2ae438d267b9b40a0d3b91dbe9dba751f
/origin/render.cpp
9b7d0af50a89b51f4a3916cdc57d102f793b534b
[]
no_license
matengli/imgRender
3f9349f378633a30b7018a493fc6938e22845710
0e07c6c415daea2b7b1962a46e158dc413bd63b0
refs/heads/master
2020-12-01T11:09:54.443853
2020-01-20T06:18:57
2020-01-20T06:18:57
230,614,274
0
0
null
null
null
null
UTF-8
C++
false
false
4,653
cpp
render.cpp
// // Created by someone on 2020/1/14. // #include "render.h" const vec4f LIGHTDIR = vec4f(1,1,0,0).getNor(); const float LIGHT_INST = 10.0; Model* model; vec4f CENTER = vec4f(0,0,0,0); vec4f EYE = vec4f(0,0.,1.0,0); vec4f UP = vec4f(0.,1.,0,0); int WIDTH; int HEIGHT; Matrix mat_mv; Matrix mat_proj; Matrix mat_mvp; vec4f varying_vert[3]; vec4f varying_norm[3]; vec4f varying_uvs[3]; vec2i screen_verts[3]; TGAColor varying_frag_color; Ishader* shader; float* zBuffer; void renderer::init(TGAImage& image){ WIDTH = image.get_width(); HEIGHT = image.get_height(); model =new Model(); zBuffer = new float[WIDTH*HEIGHT]; shader = new Ishader(); for(int i=0;i<WIDTH*HEIGHT;i++){ zBuffer[i]=-std::numeric_limits<float>::max(); } model->readFromFile("Resource/diablo3_pose.obj"); model->readDiffTextureFromFile("Resource/diablo3_pose_diffuse.tga"); model->readNormalFromFile("Resource/diablo3_pose_nm.tga"); render(image); delete model; delete [] zBuffer; } vec4f renderer::getBaryCoord(vec2i* points, vec2i &endp){ vec2i a = points[0]-points[2]; vec2i b = points[1]-points[2]; vec2i c = endp-points[2]; float x = (c.x*b.y-c.y*b.x)/(float)(a.x*b.y-a.y*b.x); float y = (c.x*a.y-c.y*a.x)/(float)(b.x*a.y-b.y*a.x); vec4f result(x,y,1.0-x-y,0); if ((result.x>=0.&&result.x<=1.)&&(result.y>=0.&&result.y<=1.)&&(result.z>=0.&&result.z<=1.)){ return result; } else{ return vec4f(-1.,-1.,-1.,0); } } void renderer::drawTriangle(TGAImage &image){ for(int i=0;i<3;i++) screen_verts[i] = SCREENVEC2(varying_vert[i]); int xyMinMax[4] = {screen_verts[0].x, screen_verts[0].x, screen_verts[0].y, screen_verts[0].y}; for(int i=0;i<4;i++){ for(int j=0;j<3;j++){ int tval = i <= 1 ? screen_verts[j].x : screen_verts[j].y; bool isUpdate = (i % 2 == 0) ? xyMinMax[i] > tval : xyMinMax[i] < tval; xyMinMax[i] = isUpdate ? tval : xyMinMax[i]; } } float ins = 1.; for(int i=0;i<4;i++){ if(xyMinMax[i]<0||xyMinMax[i]>=WIDTH){ return; } } for(int x=xyMinMax[0];x<xyMinMax[1];x+=1){ for(int y=xyMinMax[2];y<xyMinMax[3];y+=1) { auto end = vec2i(x,y); auto result = getBaryCoord(screen_verts, end); float zbuf = zBuffer[y*WIDTH+x]; float z = result*vec4f(varying_vert[0].z, varying_vert[1].z, varying_vert[2].z, 0.); // 不在三角形内 if(!(result.x>=0.&&result.y>=0.&&result.z>=0.)) { continue; } if(z>=zbuf){ zBuffer[y*WIDTH+x] = z; } else{ continue; } if(shader->fragment_shader(result)){ image.set(x,y,varying_frag_color); } } } } void renderer::render(TGAImage& image){ mat_mv = Matrix::lookAt(CENTER,EYE,UP); mat_proj = Matrix::identity(4); mat_proj[3][2] = -0.5; mat_mvp = mat_proj*mat_mv; for (int i = 0; i <model->getFacesCount() ; i++) { for(int j=0;j<3;j++){ shader->vertex_shader(i,j); } drawTriangle(image); } } vec4f Ishader::vertex_shader(int face,int index){ vec4f vert = model->getFaceVecs(face,index); varying_vert[index] = (mat_mvp*Matrix(vert)).getVec4f(); varying_norm[index] = model->getFaceNors(face,index); varying_uvs[index] = model->getUvVecs(face,index); return varying_vert[index]; } bool Ishader::fragment_shader(vec4f batcoord){ vec4f uv = varying_uvs[0] * batcoord.x + varying_uvs[1] * batcoord.y + varying_uvs[2] * batcoord.z; vec4f normal = varying_norm[0]*batcoord.x+varying_norm[1]*batcoord.y+varying_norm[2]*batcoord.z; // normal = model->getNorFromMapByUv(uv); float ins = normal*LIGHTDIR*LIGHT_INST; // if(ins<0.2){ // ins = 0.2; // } if(ins>=0.8){ ins = 2.0; } else if(ins>=0.6){ ins = 1.0; } else if(ins>=0.4){ ins = 0.7; } else if(ins>=0.2){ ins = 0.5; } else{ ins = 0.2; } varying_frag_color = model->getDiffuseColorByUv(uv)*ins; float snowFactor = normal*vec4f(0,1.,0,0); if(snowFactor>=0.5){ varying_frag_color = TGAColor(255,255,255,0)*(snowFactor+0.3); } return true; } void Ishader::setupVertAttribute(int face,int index){ vec4f vert = model->getFaceVecs(face,index); varying_vert[index] = (mat_mvp*Matrix(vert)).getVec4f(); varying_norm[index] = model->getFaceNors(face,index); varying_uvs[index] = model->getUvVecs(face,index); }
735840a0228731f93cc7cc0865f1e38a3f73830f
43bca23381fd51b22d0d9b18d7da374b4f031978
/ui_logindlg.h
cf5aaabb9c42a79405eb8ec86d85d2fbb066648c
[]
no_license
koestlerWang/Face-Check_in
4661208be67814b1eec83b002a45747304d1dbe4
6bf96de7414417b612143736ae7b64bb3e29fb5f
refs/heads/master
2020-04-27T13:21:09.755423
2019-03-08T01:20:19
2019-03-08T01:20:19
174,366,659
0
0
null
null
null
null
UTF-8
C++
false
false
5,025
h
ui_logindlg.h
/******************************************************************************** ** Form generated from reading UI file 'logindlg.ui' ** ** Created by: Qt User Interface Compiler version 5.9.3 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_LOGINDLG_H #define UI_LOGINDLG_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QCommandLinkButton> #include <QtWidgets/QDialog> #include <QtWidgets/QGraphicsView> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> QT_BEGIN_NAMESPACE class Ui_loginDlg { public: QLineEdit *userLineEdit; QLineEdit *pwdLineEdit; QLabel *label_3; QLabel *label_4; QCommandLinkButton *commandLinkButton; QCommandLinkButton *commandLinkButton_2; QGraphicsView *graphicsView; QGraphicsView *graphicsView_2; void setupUi(QDialog *loginDlg) { if (loginDlg->objectName().isEmpty()) loginDlg->setObjectName(QStringLiteral("loginDlg")); loginDlg->resize(943, 662); QIcon icon; icon.addFile(QStringLiteral(":/iamges/san2.jpg"), QSize(), QIcon::Normal, QIcon::Off); loginDlg->setWindowIcon(icon); loginDlg->setStyleSheet(QStringLiteral("#loginDlg{background-image: url(:/iamges/BA.jpg);}")); userLineEdit = new QLineEdit(loginDlg); userLineEdit->setObjectName(QStringLiteral("userLineEdit")); userLineEdit->setGeometry(QRect(230, 210, 221, 41)); QFont font; font.setFamily(QString::fromUtf8("\351\273\221\344\275\223")); font.setPointSize(15); userLineEdit->setFont(font); pwdLineEdit = new QLineEdit(loginDlg); pwdLineEdit->setObjectName(QStringLiteral("pwdLineEdit")); pwdLineEdit->setGeometry(QRect(230, 280, 221, 41)); pwdLineEdit->setFont(font); label_3 = new QLabel(loginDlg); label_3->setObjectName(QStringLiteral("label_3")); label_3->setGeometry(QRect(210, 80, 381, 44)); label_3->setStyleSheet(QString::fromUtf8("font: 25pt \"\345\215\216\346\226\207\350\241\214\346\245\267\";")); label_4 = new QLabel(loginDlg); label_4->setObjectName(QStringLiteral("label_4")); label_4->setGeometry(QRect(820, 640, 111, 20)); commandLinkButton = new QCommandLinkButton(loginDlg); commandLinkButton->setObjectName(QStringLiteral("commandLinkButton")); commandLinkButton->setGeometry(QRect(160, 420, 131, 61)); commandLinkButton->setStyleSheet(QString::fromUtf8("font: 20pt \"\345\215\216\346\226\207\346\245\267\344\275\223\";")); QIcon icon1; icon1.addFile(QStringLiteral(":/iamges/login.png"), QSize(), QIcon::Normal, QIcon::Off); commandLinkButton->setIcon(icon1); commandLinkButton->setIconSize(QSize(50, 40)); commandLinkButton_2 = new QCommandLinkButton(loginDlg); commandLinkButton_2->setObjectName(QStringLiteral("commandLinkButton_2")); commandLinkButton_2->setGeometry(QRect(360, 420, 121, 61)); commandLinkButton_2->setStyleSheet(QString::fromUtf8("font: 20pt \"\345\215\216\346\226\207\346\245\267\344\275\223\";")); QIcon icon2; icon2.addFile(QStringLiteral(":/iamges/exit.png"), QSize(), QIcon::Normal, QIcon::Off); commandLinkButton_2->setIcon(icon2); commandLinkButton_2->setIconSize(QSize(50, 40)); graphicsView = new QGraphicsView(loginDlg); graphicsView->setObjectName(QStringLiteral("graphicsView")); graphicsView->setGeometry(QRect(180, 210, 41, 41)); graphicsView->setStyleSheet(QStringLiteral("border-image: url(:/iamges/head.png);")); graphicsView_2 = new QGraphicsView(loginDlg); graphicsView_2->setObjectName(QStringLiteral("graphicsView_2")); graphicsView_2->setGeometry(QRect(180, 280, 41, 41)); graphicsView_2->setStyleSheet(QStringLiteral("border-image: url(:/iamges/pass.png);")); retranslateUi(loginDlg); QMetaObject::connectSlotsByName(loginDlg); } // setupUi void retranslateUi(QDialog *loginDlg) { loginDlg->setWindowTitle(QApplication::translate("loginDlg", "welcome", Q_NULLPTR)); label_3->setText(QApplication::translate("loginDlg", "\347\224\265\345\255\220\346\265\213\351\207\217\347\253\231\350\200\203\345\213\244\347\263\273\347\273\237", Q_NULLPTR)); label_4->setText(QApplication::translate("loginDlg", "copyright@2018", Q_NULLPTR)); commandLinkButton->setText(QApplication::translate("loginDlg", "\347\231\273\345\275\225", Q_NULLPTR)); commandLinkButton_2->setText(QApplication::translate("loginDlg", "\351\200\200\345\207\272", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class loginDlg: public Ui_loginDlg {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_LOGINDLG_H
5f1882b6b6db5ef11d762b4ea1762200b8e7c262
e13d2229aaf4a771c2e1e4e1480cb871f7d92f7b
/tests/safeTests/src/PointerGuardTest.cpp
914a006c1bae88876125119520d28c699a934cef
[ "MIT" ]
permissive
amironov73/PlusIrbis
0a4c8f63f30f30fbbf03d193311909d9a96f5b58
c2eeed50c067badb597864e831d3c7a75b02108c
refs/heads/master
2022-10-26T16:23:55.991770
2022-10-03T08:24:41
2022-10-03T08:24:41
168,790,953
1
1
null
null
null
null
UTF-8
C++
false
false
547
cpp
PointerGuardTest.cpp
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com #include "catch.hpp" #include "irbis.h" #include "irbis_internal.h" #include "safeTests.h" #include "cstring" // ReSharper disable StringLiteralTypo TEST_CASE("PointerGuard_1", "[pointer]") { irbis::PointerGuard<int> guard (new int[10]); memset (guard.pointer(), 0, sizeof(int) * 10); guard[0] = 1; guard[1] = 2; CHECK (guard[0] == 1); CHECK (guard[1] == 2); }
edd11cd2a17ce3c12f45d809544468dcbdb5f20d
78ee7815950f2936280281d0b909f88302eaa204
/trajectory_opt/include/trajectory_opt/p_controller.h
6cf451f4e75c202b6057a73bddc75c4fffc04749
[]
no_license
Swarm-UST/MPC-CSLQ
6a78179bdeb31c9c6c410eae5d91d0b123ae25a9
1f7974f882613ce60b6e3dac9e3824eafe46f257
refs/heads/master
2023-03-03T10:36:01.240435
2021-02-02T13:28:05
2021-02-02T13:28:05
325,942,483
0
0
null
null
null
null
UTF-8
C++
false
false
203
h
p_controller.h
#ifndef P_CONTROLLER_H #define P_CONTROLLER_H #include <Eigen/Dense> #include <cmath> #include <iostream> Eigen::Vector2d p_controller(Eigen::Vector3d x,Eigen::Vector3d tar, double l,double r); #endif
5b12d60de8976e986f00abdf290c3e646e99a83c
b71cb3b46ed7b0ee65c06772edc76c69b1cb1fb9
/Examples/include/asposecpplib/system/predicate.h
98d9428c8eeebcf32e18d6ebf47dbc524c3f494b
[ "MIT" ]
permissive
min1129/Aspose.PDF-for-C
9fb98a78ecd8963e78c52729c2bbdcbf563585f3
9360531493d4f4d379557e96747fc3e2c4836768
refs/heads/master
2020-03-29T18:26:15.431415
2018-03-06T11:31:33
2018-03-06T11:31:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
213
h
predicate.h
#ifndef _aspose_system_predicate_h_ #define _aspose_system_predicate_h_ #include "system/multicast_delegate.h" namespace System { template<class T> using Predicate = MulticastDelegate<bool(T)>; } #endif
bde9e121b0a7fb22e9625bc6e5d916331da585f5
2b7cd629d53d8e3b6009574e11f395301e156ca0
/COMMON/SRC/SOC/ST710X_MS_V1/ATAPI/ST_SATA/st202t_sata_dma.cpp
39e7fdca4f29e6505f68656ff5d2c3e7477f4848
[]
no_license
zizilala/projects_etest
8b6a5782b9e2f6c1c05e508356a7f835dce29d92
84fa95bd0017b06dfbf15b861c179d4d8da1a475
refs/heads/master
2020-12-30T11:14:52.899545
2014-03-13T09:54:27
2014-03-13T09:54:27
15,964,924
1
0
null
null
null
null
UTF-8
C++
false
false
21,739
cpp
st202t_sata_dma.cpp
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Use of this sample source code is subject to the terms of the Microsoft // license agreement under which you licensed this sample source code. If // you did not accept the terms of the license agreement, you are not // authorized to use this sample source code. For the terms of the license, // please see the license agreement between you and Microsoft or, if applicable, // see the LICENSE.RTF on your install media or the root of your tools installation. // THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES. // //======================================================================= // COPYRIGHT (C) STMicroelectronics 2007. ALL RIGHTS RESERVED // // Use of this source code is subject to the terms of your STMicroelectronics // development license agreement. If you did not accept the terms of such a license, // you are not authorized to use this source code. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. //======================================================================== #include <satamain.h> #include <atapipci.h> #include <diskmain.h> #include <ceddk.h> #include <pm.h> #include <ST202T_sata.h> #include "debug.h" // ---------------------------------------------------------------------------- // Function: WaitForDMAInterrupt // Wait for an interrupt from the DMA controller or an error condition. // // Parameters: // dwTimeOut - // ---------------------------------------------------------------------------- BOOL CST202T_SATA::WaitForDMAInterrupt( DWORD dwTimeOut ) { BOOL fRet = TRUE; DWORD dwRet; static CONST HANDLE lpHandles[] = {m_pPort->m_hErrorEvent, m_pPort->m_hDMAEvent}; static DWORD dwCount = 2; // Wait for the DMA block transaction to complete or an error to occur. dwRet = WaitForMultipleObjects(dwCount, lpHandles, FALSE, dwTimeOut); if (dwRet == WAIT_TIMEOUT) { fRet = FALSE; } else if (dwRet == WAIT_OBJECT_0) { // SATA error condition detected DEBUGMSG(ZONE_IO|ZONE_ERROR, (_T( "Atapi!CST202T_SATA::WaitForDMAInterrupt> SError detected during DMA transaction.\r\n" ))); fRet = FALSE; } else // DMA controller is interrupting { if (DMAError() || m_pPort->m_bStatus & ATA_STATUS_ERROR) { DEBUGMSG(ZONE_IO|ZONE_ERROR, (_T( "Atapi!CST202T_SATA::WaitForDMAInterrupt> Error detected during DMA transaction.\r\n" ))); fRet = FALSE; } } return fRet; } // ---------------------------------------------------------------------------- // Function: TranslateAddress // Translate a system address to a bus address for the DMA controller. // // Parameters: // pdwAddr - // ---------------------------------------------------------------------------- BOOL CST202T_SATA::TranslateAddress( PDWORD pdwAddr ) { // translate a system address to a bus address for the DMA bus controller PHYSICAL_ADDRESS SystemLogicalAddress, TransLogicalAddress; DWORD dwBus; dwBus = m_pPort->m_pController->m_dwi.dwBusNumber; // translate address SystemLogicalAddress.HighPart = 0; SystemLogicalAddress.LowPart = *pdwAddr; if (!HalTranslateSystemAddress(Internal, dwBus, SystemLogicalAddress, &TransLogicalAddress)) { return FALSE; } *pdwAddr = TransLogicalAddress.LowPart; return TRUE; } // ---------------------------------------------------------------------------- // Function: SetupDMA // Prepare DMA transfer. Issues the first DMA transaction and // enables the DMA engine. The DMA engine must be initialized // before sending the DMA command to the drive. // // Parameters: // pSgBuf - // dwSgCount - // fRead - // ---------------------------------------------------------------------------- BOOL CST202T_SATA::SetupDMA( PSG_BUF pSgBuf, DWORD dwSgCount, BOOL fRead ) { BOOL bRet = FALSE; if(BuildLLITables(pSgBuf, dwSgCount, fRead)) { // Disable DMA channel EnableDMAChannel(FALSE); // Clear all interrupt status registers for this channel ClearDMAStatusRegs(); // Ensure global DMA enable bit is set. EnableDMAController(TRUE); // Populate fields for first DMA block transfer m_pRegDMA->dwSAR = m_LLITable[0].SAR; m_pRegDMA->dwDAR = m_LLITable[0].DAR; m_pRegDMA->dwLLP = (DWORD)m_LLITablePhys.LowPart & 0x1FFFFFFF; // DMA controller uses P0 region m_pRegDMA->dwCTL_LSB = m_LLITable[0].CTL_LSB; m_pRegDMA->dwCTL_MSB = m_LLITable[0].CTL_MSB; // The following values are constant throughout the DMA transaction. // Set them up once here. if (fRead) { m_pRegDMA->dwCFG_LSB = SATA_DMA_CFG_LSB_READ; m_pRegDMA->dwCFG_MSB = SATA_DMA_CFG_MSB_READ; m_pRegHBA->dwDBTSR = SATA_HBA_DBTSR_READ; m_pRegHBA->dwDMACR = SATA_HBA_DMACR_READ; } else { m_pRegDMA->dwCFG_LSB = SATA_DMA_CFG_LSB_WRITE; m_pRegDMA->dwCFG_MSB = SATA_DMA_CFG_MSB_WRITE; m_pRegHBA->dwDBTSR = SATA_HBA_DBTSR_WRITE; m_pRegHBA->dwDMACR = SATA_HBA_DMACR_WRITE; } bRet = TRUE; } return bRet; } // ---------------------------------------------------------------------------- // Function: BuildLLITables // Populate the "linked list item" table which is native to this // DMA controller. // // Parameters: // pSgBuf - // dwSgCount - // fRead - // ---------------------------------------------------------------------------- BOOL CST202T_SATA::BuildLLITables( PSG_BUF pSgBuf, DWORD dwSgCount, BOOL fRead ) { BOOL bRet = FALSE; int TableIndex = 0; pSATA_DMA_LLI LLIPhys; // Build generic PRD tables if (CPCIDisk::SetupDMA(pSgBuf, dwSgCount, fRead)) { // Convert generic PRD table into an LLI table. PDMATable pPRD = m_pPRD; USHORT currentFISDataCount = 0; BOOL bSplitDMADetected; do { if (fRead) { m_LLITable[TableIndex].SAR = 0; // sata1hostc_spec_1_4.pdf, section 3.4: start address should be 0 m_LLITable[TableIndex].DAR = pPRD->physAddr & 0x1FFFFFFF; // DMA controller uses P0 region m_LLITable[TableIndex].CTL_LSB = SATA_DMA_CTL_LSB_LINKED_READ; } else // Write { m_LLITable[TableIndex].SAR = pPRD->physAddr & 0x1FFFFFFF; // DMA controller uses P0 region m_LLITable[TableIndex].DAR = 0; // sata1hostc_spec_1_4.pdf, section 3.4: start address should be 0 m_LLITable[TableIndex].CTL_LSB = SATA_DMA_CTL_LSB_LINKED_WRITE; } //Unknown if these fields will be used by hardware m_LLITable[TableIndex].SSTAT = 0; m_LLITable[TableIndex].DSTAT = 0; // The maximum data transferred to the SATA controller by the drive per // FIS is 8192 bytes. We must ensure that no DMA block transfer passes // an 8192 byte FIS boundary, otherwise read underrun errors will occur // before the drive has time to transfer more data to the SATA controller. currentFISDataCount += pPRD->size; if (currentFISDataCount > SATA_MAX_FIS_SIZE) { DEBUGMSG(ZONE_IO || ZONE_WARNING, (_T( "Atapi!CST202T_SATA::BuildLLITables: Breaking up DMA that spanned FISes! \r\n" ))); // Break this DMA block up so that it does not span two data FISes USHORT dwBytesThisTransfer = pPRD->size - (currentFISDataCount % SATA_MAX_FIS_SIZE); // Size is given in DWORDs m_LLITable[TableIndex].CTL_MSB = dwBytesThisTransfer / 4; // Complete this PRD in the next LLI pPRD->size -= dwBytesThisTransfer; pPRD->physAddr += dwBytesThisTransfer; currentFISDataCount = 0; // We know we're on a FIS boundary; reset the counter bSplitDMADetected = TRUE; } else { // Size is given in DWORDs m_LLITable[TableIndex].CTL_MSB = pPRD->size / 4; currentFISDataCount %= SATA_MAX_FIS_SIZE; bSplitDMADetected = FALSE; } LLIPhys = (pSATA_DMA_LLI) (((DWORD)m_LLITablePhys.LowPart) & 0x1FFFFFFF); // DMA controller uses P0 region m_LLITable[TableIndex].LLP = &LLIPhys[TableIndex+1]; TableIndex++; } while (bSplitDMADetected || (pPRD++)->EOTpad == 0); //Increment pPRD only if split DMA was not detected m_LLITable[TableIndex-1].LLP = 0; #if 0 DEBUGMSG(ZONE_IO || ZONE_WARNING, (_T( "Atapi!CST202T_SATA::BuildLLITables: tableDump: \r\n" ))); int i =0; do { DEBUGMSG(ZONE_IO || ZONE_WARNING, (_T( "table %d: SAR = 0x%x, DAR=0x%x, LLP = 0x%x, CTL_MSB = 0x%x \r\n" ), i, m_LLITable[i].SAR, m_LLITable[i].DAR, m_LLITable[i].LLP, m_LLITable[i].CTL_MSB)); } while (m_LLITable[i].LLP && ++i); #endif bRet = TRUE; } return bRet; } // ---------------------------------------------------------------------------- // Function: StartDMATransaction // Program the DMA controller and initiate a block transaction. // // Parameters: // pSgBuf - // dwSgCount - // fRead - // ---------------------------------------------------------------------------- void CST202T_SATA::StartDMATransaction( BOOL fRead, const pSATA_DMA_LLI pLLITable ) { CacheSync(CACHE_SYNC_DISCARD); // Enable Block Transfer done interrupt for this channel EnableDMACTfrInt(TRUE); // Initiate transfer EnableDMAChannel(TRUE); return; } // ---------------------------------------------------------------------------- // Function: ProcessDMA // This function processes the entire DMA transaction, which possibly // involves multiple DMA block transactions. // // Parameters: // fRead - // ---------------------------------------------------------------------------- BOOL CST202T_SATA::ProcessDMA( BOOL fRead ) { BOOL bRet = TRUE; // Wait for transfer to complete. if ( !WaitForDMAInterrupt(m_dwDiskIoTimeOut) ) { DEBUGMSG(ZONE_IO || ZONE_WARNING, (_T( "Atapi!CST202T_SATA::ProcessDMA> Failed to wait for interrupt or error received\r\n" ))); bRet = FALSE; } // Wait for AHB bus to go idle (per instructions from ST) WaitForAHBIdle(); // DMA transfer is complete EnableDMACTfrInt(FALSE); return bRet; } // ---------------------------------------------------------------------------- // Function: EndDMA // End DMA transfer // // Parameters: // None // ---------------------------------------------------------------------------- BOOL CST202T_SATA::EndDMA( ) { DWORD ErrorStatus; BOOL bRet = FALSE; // Wait for AHB bus to go idle (per instructions from ST) WaitForAHBIdle(); ErrorStatus = GetDMAErrorStatus(); if (ErrorStatus != 0) { DEBUGMSG(ZONE_ERROR|ZONE_DMA, (_T( "Atapi!CST202T_SATA::EndDMA> Error\r\n" ))); } else { bRet = TRUE; } m_pRegHBA->dwDMACR = 0; EnableDMAChannel(FALSE); return bRet; } // ---------------------------------------------------------------------------- // Function: AbortDMA // Abort DMA transfer // // Parameters: // None // ---------------------------------------------------------------------------- BOOL CST202T_SATA::AbortDMA( ) { DWORD i; // Reset DMA controller's state m_pRegHBA->dwDMACR = 0; EnableDMACTfrInt(FALSE); EnableDMAChannel(FALSE); ClearDMAStatusRegs(); for (i = 0; i < m_dwSGCount; i++) { if (!m_pSGCopy[i].pDstAddress) { UnlockPages(m_pSGCopy[i].pSrcAddress, m_pSGCopy[i].dwSize); } } // free all but the first @MIN_PHYS_PAGES pages; these are fixed for (i = MIN_PHYS_PAGES; i < m_dwPhysCount; i++) { FreePhysMem(m_pPhysList[i].pVirtualAddress); } return FALSE; } // ---------------------------------------------------------------------------- // Function: ReadWriteDiskDMA // This function reads from/writes to an ATA device // // Parameters: // pIOReq - // fRead - // ---------------------------------------------------------------------------- DWORD CST202T_SATA::ReadWriteDiskDMA( PIOREQ pIOReq, BOOL fRead ) { DWORD dwError; BOOL bRetry; // Certain SATA errors are non-recoverable by the hardware but are transient in nature. // Fetch the number of times we should retry a command when an error is detected. DWORD dwRetriesRemaining = m_pPort->m_pController->m_pIdeReg->dwNumRetriesOnSATAError; Begin_DMA: bRetry = FALSE; // Perform DMA Transaction dwError = DoReadWriteDiskDMA(pIOReq, fRead); // We must check for SATA error conditions here to ensure that // we haven't read or written invalid data. switch (GetSATAError()) { case SATA_ERROR_NO_ERROR: // Check that the command completed successfully if ( (ERROR_READ_FAULT == dwError) || (ERROR_WRITE_FAULT == dwError) ) { m_dwErrorCount++; bRetry = TRUE; } break; case SATA_ERROR_PERSISTENT: RETAILMSG(ZONE_IO|ZONE_ERROR, (_T( "Atapi!CST202T_SATA::ReadWriteDiskDMA> Unrecoverable error detected. ABORT!\r\n" ))); m_dwErrorCount++; dwError = ERROR_GEN_FAILURE; break; case SATA_ERROR_TRANSIENT: m_dwErrorCount++; bRetry = TRUE; break; } if (bRetry) { if (dwRetriesRemaining--) { DEBUGMSG(ZONE_IO|ZONE_ERROR, (_T( "Atapi!CST202T_SATA::ReadWriteDiskDMA> Error detected. Resetting controller and retrying command. Error Count = %d\r\n" ), m_dwErrorCount)); ResetController(FALSE); goto Begin_DMA; } else { RETAILMSG(ZONE_IO|ZONE_ERROR, (_T( "Atapi!CST202T_SATA::ReadWriteDiskDMA> Error detected. %d retries failed. ABORT! Error Count = %d\r\n" ), m_pPort->m_pController->m_pIdeReg->dwNumRetriesOnSATAError, m_dwErrorCount)); dwError = ERROR_GEN_FAILURE; } } return dwError; } // ---------------------------------------------------------------------------- // Function: DoReadWriteDiskDMA // This function reads from/writes to a SATA device. This is largely // taken from CDisk::ReadWriteDiskDMA. Some modifications have been made // for the DMA controller on this platform. // // Parameters: // pIOReq - // fRead - // ---------------------------------------------------------------------------- DWORD CST202T_SATA::DoReadWriteDiskDMA( PIOREQ pIOReq, BOOL fRead ) { DWORD dwError = ERROR_SUCCESS; PSG_REQ pSgReq = (PSG_REQ)pIOReq->pInBuf; DWORD dwSectorsToTransfer; SG_BUF CurBuffer[MAX_SG_BUF]; BYTE bCmd; BOOL bErrorDetected = FALSE; // pIOReq->pInBuf is a sterile copy of the caller's SG_REQ if ((pSgReq == NULL) || (pIOReq->dwInBufSize < sizeof(SG_REQ))) { return ERROR_INVALID_PARAMETER; } if ((pSgReq->sr_num_sec == 0) || (pSgReq->sr_num_sg == 0)) { return ERROR_INVALID_PARAMETER; } if ((pSgReq->sr_start + pSgReq->sr_num_sec) > m_DiskInfo.di_total_sectors) { return ERROR_SECTOR_NOT_FOUND; } DEBUGMSG(ZONE_IO, (_T( "Atapi!CST202T_SATA::DoReadWriteDiskDMA> sr_start(%ld), sr_num_sec(%ld), sr_num_sg(%ld)\r\n" ), pSgReq->sr_start, pSgReq->sr_num_sec, pSgReq->sr_num_sg)); // We are not interested in the ATA interrupt during DMA transactions. // It will normally fire at the end of a DMA transaction, but we // rely on the DMA controller's block transfer done interrupt to // inform us that the transfer is complete. Disable the ATA interrupt // here, and re-enable it at the end of the DMA transaction. WriteAltDriveController(ATA_CTRL_DISABLE_INTR); // clear pending interrupts GetBaseStatus(); ClearSError(); ResetEvent(m_pPort->m_hSATAEvent); ResetEvent(m_pPort->m_hDMAEvent); ResetEvent(m_pPort->m_hErrorEvent); DWORD dwStartBufferNum = 0, dwEndBufferNum = 0, dwEndBufferOffset = 0; DWORD dwNumSectors = pSgReq->sr_num_sec; DWORD dwStartSector = pSgReq->sr_start; // process scatter/gather buffers in groups of MAX_SEC_PER_COMMAND sectors // each DMA request handles a new SG_BUF array which is a subset of the // original request, and may start/stop in the middle of the original buffer while (dwNumSectors) { // determine number of sectors to transfer dwSectorsToTransfer = (dwNumSectors > MAX_SECT_PER_COMMAND) ? MAX_SECT_PER_COMMAND : dwNumSectors; // determine size (in bytes) of transfer DWORD dwBufferLeft = dwSectorsToTransfer * BYTES_PER_SECTOR; DWORD dwNumSg = 0; // while the transfer is not complete while (dwBufferLeft) { // determine the size of the current scatter/gather buffer DWORD dwCurBufferLen = pSgReq->sr_sglist[dwEndBufferNum].sb_len - dwEndBufferOffset; if (dwBufferLeft < dwCurBufferLen) { CurBuffer[dwEndBufferNum - dwStartBufferNum].sb_buf = pSgReq->sr_sglist[dwEndBufferNum].sb_buf + dwEndBufferOffset; CurBuffer[dwEndBufferNum - dwStartBufferNum].sb_len = dwBufferLeft; dwEndBufferOffset += dwBufferLeft; dwBufferLeft = 0; } else { CurBuffer[dwEndBufferNum - dwStartBufferNum].sb_buf = pSgReq->sr_sglist[dwEndBufferNum].sb_buf + dwEndBufferOffset; CurBuffer[dwEndBufferNum - dwStartBufferNum].sb_len = dwCurBufferLen; dwEndBufferOffset = 0; dwEndBufferNum++; dwBufferLeft -= dwCurBufferLen; } dwNumSg++; } bCmd = fRead ? m_bDMAReadCommand : m_bDMAWriteCommand; // setup the DMA transfer if (!SetupDMA(CurBuffer, dwNumSg, fRead)) { dwError = fRead ? ERROR_READ_FAULT : ERROR_WRITE_FAULT; // We do not set bErrorDetected to true here, as the DMA // transfer was not initialized, and thus shouldn't be aborted. goto Exit; } // Wait for AHB bus to go idle (per instructions from ST) WaitForAHBIdle(); // Begin the DMA transfer StartDMATransaction(fRead, m_LLITable); // write the read/write command if (!SendIOCommand(dwStartSector, dwSectorsToTransfer, bCmd)) { bErrorDetected = TRUE; goto Exit; } // start the DMA transfer if (ProcessDMA(fRead)) { if (CheckIntrState() == ATA_INTR_ERROR) { DEBUGMSG(ZONE_IO || ZONE_WARNING, (_T( "Atapi!CST202T_SATA::DoReadWriteDiskDMA> Failed to wait for interrupt; device(%d)\r\n" ), m_dwDeviceId)); bErrorDetected = TRUE; goto Exit; } // stop the DMA transfer if (EndDMA()) { if (WaitOnBusy(FALSE) != 0) { DEBUGMSG(ZONE_IO || ZONE_WARNING, (_T( "Atapi!CST202T_SATA::DoReadWriteDiskDMA> Drive won't come out of busy state!\r\n" ))); bErrorDetected = TRUE; goto Exit; } else { CompleteDMA(CurBuffer, pSgReq->sr_num_sg, fRead); } } else // EndDMA returned an error condition { bErrorDetected = TRUE; goto Exit; } } else // ProcessDMA returned an error condition { bErrorDetected = TRUE; goto Exit; } // update transfer dwStartSector += dwSectorsToTransfer; dwStartBufferNum = dwEndBufferNum; dwNumSectors -= dwSectorsToTransfer; } Exit: if (bErrorDetected) { dwError = fRead ? ERROR_READ_FAULT : ERROR_WRITE_FAULT; AbortDMA(); } // ATA interrupt was disabled for the duration of the DMA // tranaction. Re-enable it now. GetBaseStatus(); // Clear any pending interrupt. WriteAltDriveController(ATA_CTRL_ENABLE_INTR); pSgReq->sr_status = dwError; return dwError; }
a18a76cb2f4f73ed093a87979867e162238ae4b4
06ddc1f8bfccbf198e1c90cc00bbb4a893bc8047
/Angela/Classes/Player.h
0da020509c234f2530c151e1b30e05aaaf7d4e3c
[]
no_license
lexshen/WarCastleChipmunk
8cfb0d8aca768115d75e970eb1d832191f9bb113
331492c5cf5628e147aa0ad5732d0816508f0a71
refs/heads/master
2021-01-10T21:23:59.404795
2014-02-21T15:31:15
2014-02-21T15:31:15
14,174,254
0
1
null
null
null
null
UTF-8
C++
false
false
239
h
Player.h
#pragma once #include "cocos2d.h" #include "GameObject.h" NS_CC_BEGIN class Player:public GameObject { public: //int people; //int coins; double lastCoinDrop; bool create(CCString* spriteFrameName); }; NS_CC_END
63b86d2d1ad78ce39aa26a5f3b50d1ec2a0cc5eb
9fba8a73fa7c870116c2cf99f646db3d16477b9c
/学生管理系统/学生管理系统/CAccountlist.h
e85da0a31372276df51eee9dad14db958f4872ee
[]
no_license
sghyj/student_second
754cfa120ca440f39f130ddce3f4953acfd1dcbb
8a88026ed447ca61aea63813ebb2dde7cd686da7
refs/heads/master
2021-01-10T04:15:06.273359
2013-03-03T16:08:50
2013-03-03T16:08:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
687
h
CAccountlist.h
#ifndef Header_CAccountlist #define Header_CAccountlist #include"CStudent.h" class CNode { public: CStudent & stu; CNode * next; CNode(CStudent & a) : stu(a), next(NULL){} bool operator == (const CNode & n) const { return this->stu.Get_iStudent_ID() == n.stu.Get_iStudent_ID(); } }; class CAccountlist { int size; CNode * head; CNode * tail; public: CAccountlist (): head(NULL), tail (NULL), size(0){}; CNode * GetHead () const { return head; } int GetSize() const { return size; } void add(CStudent & a); void remove(int iStudent_ID); CStudent * find (int iStudent_ID); bool isEmpty() const {return !size; }; void display() const; ~CAccountlist(); }; #endif
c5c0ffb285ec3b2ad5f9cb86deb9ef6ccc2fd9e1
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/contest/1542575667.cpp
bb8f65d7cfbf4ca4046676d43608d1ffe78eee71
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
1,556
cpp
1542575667.cpp
#include <bits/stdc++.h> using namespace std; #define eps 1e-8 #define INF 0x3f3f3f3f #define maxn 100005 #define LL long long bool check(double l,double r,double k) { if(l<=k&&k<=r) return 1; if(l>r) { if(k<=r) return 1; } return 0; } int main() { double h, m, s, t1, t2; scanf("%lf%lf%lf%lf%lf", &h, &m, &s, &t1, &t2); int flag = 0; h = h + m/60.0+s / 3600.0; m = (m + s / 60.0) / 5.0; s = s / 5.0; if(h>=12.0) h-=12.0; double pre=t1; int cnt = 0; for(double i = t1;; i += 1.0) { cnt++; if(cnt == 13) break; if(i >= 13.0) i = 1.0; if(check(pre,i,h) || check(pre,i,m) || check(pre,i,s) ) { flag = 1; break; } if(i == t2) break; pre=i; } if(flag == 0) { printf("YES\n"); return 0; } flag = 0; cnt = 0; pre=t1; for(double i = t1;; i -= 1.0) { cnt++; if(cnt == 13) break; if(i == 0.0) i = 12.0; if(check(i,pre,h) || check(i,pre,m) || check(i,pre,s)) { flag = 1; break; } if(i == t2) break; pre=i; } if(flag == 0) printf("YES\n"); else printf("NO\n"); return 0; }
5d1945458c39b1df1f1de35db70008f84cc74d9c
e1de1cc63a9325519ac1e070250bead0f22823ea
/textmagic-rest-cpp-v2/model/UpdateListObject.h
60f7274848f28450d103e23a837b711c0aad568c
[ "MIT" ]
permissive
WeilerWebServices/textmagic
03abd875726a0d548f789aa06f6d1b392c1f4a2b
f7ad8cb2989bccb7afba9e30915f8575dd1b0b81
refs/heads/master
2023-01-28T03:55:52.739564
2020-12-14T04:17:59
2020-12-14T04:17:59
321,150,541
1
0
null
null
null
null
UTF-8
C++
false
false
2,363
h
UpdateListObject.h
/** * TextMagic API * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: 2 * * * NOTE: This class is auto generated by the swagger code generator 2.4.8. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ /* * UpdateListObject.h * * */ #ifndef COM_TEXTMAGIC_CLIENT_MODEL_UpdateListObject_H_ #define COM_TEXTMAGIC_CLIENT_MODEL_UpdateListObject_H_ #include "../ModelBase.h" #include <cpprest/details/basic_types.h> namespace com { namespace textmagic { namespace client { namespace model { /// <summary> /// /// </summary> class UpdateListObject : public ModelBase { public: UpdateListObject(); virtual ~UpdateListObject(); ///////////////////////////////////////////// /// ModelBase overrides void validate() override; web::json::value toJson() const override; void fromJson(web::json::value& json) override; void toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) const override; void fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& namePrefix) override; ///////////////////////////////////////////// /// UpdateListObject members /// <summary> /// List name. /// </summary> utility::string_t getName() const; bool nameIsSet() const; void unsetName(); void setName(utility::string_t value); /// <summary> /// Make this list shared or not? /// </summary> bool isShared() const; bool sharedIsSet() const; void unsetShared(); void setShared(bool value); /// <summary> /// Is list favorited. /// </summary> bool isFavorited() const; bool favoritedIsSet() const; void unsetFavorited(); void setFavorited(bool value); /// <summary> /// Is list default for new contacts (web only). /// </summary> bool isIsDefault() const; bool isDefaultIsSet() const; void unsetIsDefault(); void setIsDefault(bool value); protected: utility::string_t m_Name; bool m_NameIsSet; bool m_Shared; bool m_SharedIsSet; bool m_Favorited; bool m_FavoritedIsSet; bool m_IsDefault; bool m_IsDefaultIsSet; }; } } } } #endif /* COM_TEXTMAGIC_CLIENT_MODEL_UpdateListObject_H_ */
74bee906123a8944c2e034f6c2969d547a81f99d
d3ea014fac2128691b7e58449786dc07fe50e263
/include/Personality.hpp
f1673dc279ff3ee79e4a961fc53903e81ae527f6
[]
no_license
AngelPn/L5R-card_game
dec8e3f7725d598723f3dceeea39124fca684f46
7e4de283a83aed17c2db8c5fdea041d907f2b8a5
refs/heads/master
2022-04-20T13:11:46.030096
2020-03-12T14:48:56
2020-03-12T14:48:56
240,680,742
3
0
null
null
null
null
UTF-8
C++
false
false
2,232
hpp
Personality.hpp
//file:Personality.hpp #ifndef _PERSONALITY_HPP_ #define _PERSONALITY_HPP_ #include "Card.hpp" #include <string> #include <list> #include "Follower.hpp" #include "Item.hpp" class Personality : public BlackCard { private: bool isDead; //0 alive, 1 dead unsigned int attack; unsigned int defense; unsigned int honour; std::list<Follower*> *followers; std::list<Item*> *items; unsigned int greenCardBound; public: //int type-> Personalities type Personality(const std::string name, int type); ~Personality(); int getType() const; //Accessors bool is_dead() const; unsigned int get_attack() const; unsigned int get_defense() const; unsigned int get_honour() const; virtual void print() const; bool hasFollowers(); void destroyFollower(int *lost_points); void tap_followers(); void decrement_durability(); void decrement_honour(); void performSeppuku(); bool belowBound() const; void applyBonus(GreenCard *card); void equip(GreenCard *card); }; class Attacker : public Personality { public: Attacker(const std::string name, int type) : Personality(name, type){} void print() const{ std::cout<< "\033[1;31mPersonality: ATTACKER\n\033[0m"; Personality::print(); } }; class Defender : public Personality { public: Defender(const std::string name, int type) : Personality(name, type){} void print() const{ std::cout<< "\033[1;31mPersonality: DEFENDER\n\033[0m"; Personality::print(); } }; class Champion : public Personality { public: Champion(const std::string name, int type) : Personality(name, type){} void print() const{ std::cout<< "\033[1;31mPersonality: CHAMPION\n\033[0m"; Personality::print(); } }; class Chancellor : public Personality { public: Chancellor(const std::string name, int type) : Personality(name, type){} void print() const{ std::cout<< "\033[1;31mPersonality: CHANCELLOR\n\033[0m"; Personality::print(); } }; class Shogun : public Personality { public: Shogun(const std::string name, int type) : Personality(name, type){} void print() const{ std::cout<< "\033[1;31mPersonality: SHOGUN\n\033[0m"; Personality::print(); } }; #endif
aa2f084ab703f68c6eb024324bd016a204dab170
a457b55ff90a57397b2ab5b6299495f2e9fdb4fa
/src/LoboFEM/Collision/CollisionDector/BVHCollisionDetector.cpp
7a1fe8dd23b32c3c4442df5e64dbf1f99820f059
[ "MIT" ]
permissive
lrquad/LoboFEM2
8b3e97f8ea18c68023fb4d9366000c599e550b97
4ac80bd7b6e347d5b1650f5241f7b7b53c9716f5
refs/heads/master
2022-08-15T15:53:09.424585
2020-05-17T21:14:34
2020-05-17T21:14:34
260,367,616
8
2
null
null
null
null
UTF-8
C++
false
false
3,830
cpp
BVHCollisionDetector.cpp
#include "BVHCollisionDetector.h" #include "BVHTriModel.h" #include "Functions/computeTriangle.h" #include <iostream> using namespace Eigen; BVHCollisionDetector::BVHCollisionDetector(Lobo::LoboMesh* trimesh) { this->trimesh = trimesh; setIsstatic(true); setSelfCollisionTest(false); initCollisionShape(); } BVHCollisionDetector::~BVHCollisionDetector() { delete bvhTriModel; } void BVHCollisionDetector::initCollisionShape() { bvhTriModel = new BVHTriModel(trimesh); bvhTriModel->BuildBVH(); } void BVHCollisionDetector::updateCollisionShape() { bvhTriModel->updateDeform(); bvhTriModel->RefitBVH(); } void BVHCollisionDetector::collideWith(BVHCollisionDetector* objtB) { BVHTriModel* other = objtB->getBVHmodel(); bvhTriModel->Collide(other); if (bvhTriModel->NumContact() != 0) { for (int i = 0;i < bvhTriModel->NumContact();i++) { //ShapeOpModel::s_rets; unsigned int triid1, triid2; bvhTriModel->GetContact(i, triid1, triid2); computeCollideInfo((int)triid1, (int)triid2, objtB); } } } void BVHCollisionDetector::selfCollision() { bvhTriModel->SelfCollide(); if (bvhTriModel->NumContact() != 0) { for (int i = 0;i < bvhTriModel->NumContact();i++) { //ShapeOpModel::s_rets; unsigned int triid1, triid2; bvhTriModel->GetContact(i, triid1, triid2); computeCollideInfo((int)triid1, (int)triid2, this); } } } void BVHCollisionDetector::addNewCollitionInfo(int triid, int nodeid, double displacemenet, Eigen::Vector3d norms) { CollideInfo newcollideinfo = { triid, nodeid, displacemenet, norms }; collitionInfo.push_back(newcollideinfo); } void BVHCollisionDetector::clearCollitionInfo() { collitionInfo.clear(); } void BVHCollisionDetector::computeCollideInfo(int tri1, int tri2, BVHCollisionDetector* objB) { BVHTriModel* other = objB->getBVHmodel(); int tri1_node[3]; int tri2_node[3]; tri1_node[0] = bvhTriModel->getTriAngleFaceNode(tri1, 0); tri1_node[1] = bvhTriModel->getTriAngleFaceNode(tri1, 1); tri1_node[2] = bvhTriModel->getTriAngleFaceNode(tri1, 2); tri2_node[0] = other->getTriAngleFaceNode(tri2, 0); tri2_node[1] = other->getTriAngleFaceNode(tri2, 1); tri2_node[2] = other->getTriAngleFaceNode(tri2, 2); Vector3d tri1_nodePosition[3]; Vector3d tri2_nodePosition[3]; tri1_nodePosition[0] = bvhTriModel->getTriNode(tri1_node[0]); tri1_nodePosition[1] = bvhTriModel->getTriNode(tri1_node[1]); tri1_nodePosition[2] = bvhTriModel->getTriNode(tri1_node[2]); tri2_nodePosition[0] = other->getTriNode(tri2_node[0]); tri2_nodePosition[1] = other->getTriNode(tri2_node[1]); tri2_nodePosition[2] = other->getTriNode(tri2_node[2]); Vector3d normal1, normal2; normal1 = bvhTriModel->getTriNorm(tri1); normal2 = other->getTriNorm(tri2); //computeTriangleNorm(tri1_nodePosition[0], tri1_nodePosition[1], tri1_nodePosition[2], normal1); //computeTriangleNorm(tri2_nodePosition[0], tri2_nodePosition[1], tri2_nodePosition[2], normal2); for (int i = 0; i < 3; i++) { double distance_Nodei_Trai2 = Lobo::computeDistancePointToTriangle(tri2_nodePosition[0], tri2_nodePosition[1], tri2_nodePosition[2], normal2, tri1_nodePosition[i]); bool intriangle = Lobo::checkPointTriangleProjection(tri2_nodePosition[0], tri2_nodePosition[1], tri2_nodePosition[2], tri1_nodePosition[i]); if (distance_Nodei_Trai2 < 0) { this->addNewCollitionInfo(tri1, tri1_node[i], distance_Nodei_Trai2, normal2); } double distance_Nodei_Trai1 = Lobo::computeDistancePointToTriangle(tri1_nodePosition[0], tri1_nodePosition[1], tri1_nodePosition[2], normal1, tri2_nodePosition[i]); intriangle = Lobo::checkPointTriangleProjection(tri1_nodePosition[0], tri1_nodePosition[1], tri1_nodePosition[2], tri2_nodePosition[i]); if (distance_Nodei_Trai1 < 0) { objB->addNewCollitionInfo(tri2, tri2_node[i], distance_Nodei_Trai1, normal1); } } }
664709ff7846885f528ef54636819cba34bd06ad
d32e7f1fb931b4969afd963249ea3be453fd15db
/src/imageholder.h
f8ea1b2502ec6674defcc9b1bc47f1db8ba3fcea
[ "BSD-2-Clause" ]
permissive
brandonkim88/QtCV
7b67a5ef7ceee25e16defe2020e32586c91e98a3
64fff05a390ef723ccbf97231418f3d899167283
refs/heads/master
2021-04-13T03:37:10.370195
2020-03-22T08:15:03
2020-03-22T08:15:03
249,133,640
1
0
BSD-2-Clause
2020-03-22T07:24:39
2020-03-22T07:24:38
null
UTF-8
C++
false
false
291
h
imageholder.h
#ifndef IMAGEHOLDER_H #define IMAGEHOLDER_H #include <QWidget> namespace Ui { class ImageHolder; } class ImageHolder : public QWidget { Q_OBJECT public: explicit ImageHolder(QWidget *parent = 0); ~ImageHolder(); private: Ui::ImageHolder *ui; }; #endif // IMAGEHOLDER_H
e69f0713a251306d951ad888d08bf45bc9915f87
22f8ce70cc780eda7cb11f93803058831f43c7c5
/Plugins/BlueprintTool/Source/BlueprintToolScript/Public/BTScript.h
66828f3f247fca774eb8d5e4858a099d2481790b
[]
no_license
VegetableWithChicken/SomeTest
4d26ebc44fbf8a387bec2ec9677d51485c7c9668
8659f9b99ec05f3e235ec9d7839671751c85cbf8
refs/heads/dev
2023-03-16T05:40:16.603350
2020-11-02T07:04:52
2020-11-02T07:04:52
508,117,547
1
0
null
2022-06-28T01:42:35
2022-06-28T01:42:34
null
WINDOWS-1252
C++
false
false
2,515
h
BTScript.h
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" enum EVMCommand { VMC_Undefined = 0x03, // Undefined VMC_LetBool = 0x14, // Let boolean variable. VMC_IntConst = 0x1D, // Int constant.^ VMC_FloatConst = 0x1E, // Floating point constant. VMC_StringConst = 0x1F, // String constant. VMC_ObjectConst = 0x20, // An object constant. VMC_NameConst = 0x21, // A name constant. VMC_RotationConst = 0x22, // A rotation constant. VMC_VectorConst = 0x23, // A vector constant. VMC_ByteConst = 0x24, // A byte constant. VMC_True = 0x27, // Bool True. VMC_False = 0x28, // Bool False. VMC_TextConst = 0x29, // FText constant VMC_NoObject = 0x2A, // NoObject. VMC_TransformConst = 0x2B, // A transform constant VMC_UnicodeStringConst = 0x34, // Unicode string constant. VMC_Int64Const = 0x35, // 64-bit integer constant. VMC_UInt64Const = 0x36, // 64-bit unsigned integer constant. VMC_EndOfScript = 0x53, // Last byte in script code VMC_LetObject = 0x5F, // assign to any object ref pointer VMC_LetName = 0x70, VMC_LetFloat = 0x71, VMC_SaveValue = 0x72, // Take out String constant. VMC_LetInt = 0x73, // Last int in script code VMC_LetInt64 = 0x74, VMC_LetUInt64 = 0x75, VMC_LetByte = 0x76, VMC_Funtion = 0x77, // Call funtion as frist VMC_LetString = 0x82, // Let String constant. VMC_LetText = 0x84, // Let Text constant. VMC_LetVector = 0x86, // Let Vector constant. VMC_LetRotator = 0x88, // Let Rotator constant. VMC_LetTransform = 0x8A, // Let Transform constant. VMC_Max = 0x100, }; class FBTOutParm :public TSharedFromThis<FBTOutParm> { public: void const* PropAddr; TSharedPtr<FBTOutParm> Nest; }; //ÐéÄâ»úÕ» struct FBTFrame { FBTFrame(UFunction *NewFunction); void AddOutParm(void const *Addr); template<typename TNumericType> TNumericType ReadInt(); float ReadFloat(); UProperty *ReadProperty(); FName ReadName(); FGuid ReadPinID(); UObject* ReadObject(); void Step(UObject* Context, void const * RefData); _declspec(dllexport) uint8 *GetParmAddr(); void ClearParm(); public: uint8* Code; UFunction *Function; protected: TSharedPtr<FBTOutParm> BTOutParm; }; template<typename TNumericType> TNumericType FBTFrame::ReadInt() { TNumericType Result = *(TNumericType*)Code; Code += sizeof(TNumericType); return Result; } typedef void(*FNativeBTFuncPtr)(UObject* Context, FBTFrame& TheStack, void const * RefData);
ae8b2e258dc2d5e53d50a50b58e226f4515c97f1
f4023dbecb7278ea79e9c5fd20f90a96b158da0f
/CS3307_SFTWENG/CS3307Group/src/choosedata.cpp
58dedcb5ba9edc80b2483fef941984b8e112e657
[]
no_license
aclar48/projects
f31393ac745468f32e08cff687eb44dacfe4cbbe
afd55260b04201c0cee40c0470b7eee5644ba1c9
refs/heads/master
2020-12-24T13:44:00.500834
2014-01-05T17:16:01
2014-01-05T17:16:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,357
cpp
choosedata.cpp
/** * @file choosedata.cpp * @author Melanie Imough, Alex Clarke, Jamie Finnigan * @version 1.0 * * @class ChooseData * @brief This class makes a screen that enables the user to start filtering data. * * This class makes the screen that comes right after the "welcome" screen. * The user must select the service measure. Then the user can activate * dialogbarchart, dialoglinechart, and dialogtable screens from this screen. * */ #include <QFileDialog> #include "choosedata.h" #include "ui_choosedata.h" #include "widgetbarchart.h" #include "widgetlinechart.h" #include "widgetcomplinechart.h" #include "widgettablechart.h" #include "filterdata.h" #include "servicetype.h" #include <iostream> #include <fstream> #include <sstream> /** * @brief Constructor that sets the screen that enables the user to choose * and filter data. * * This object contains a tree widget to list all the service measures, which * is populated by the filter data object. The a pointer to the selected measure(s) * is a member variable initialized to a default measure, and the slots are connected. * * * @param *parent Pointer to the QWidget * */ ChooseData::ChooseData(QWidget *parent) : QMainWindow(parent), ui(new Ui::ChooseData), _measure(new Measure()), _measure2(new Measure()) { ui->setupUi(this); this->setStyleSheet( "QPushButton#pushButtonTable {" "background-color: rgb(125,125,175);" "border-style: outset;" "border-width: 2px;" "border-color: rgb(50,50,75);" "font: bold 22px;" "border-radius: 5px;" "min-width: 7em;}" "QPushButton#pushButtonTable:hover:pressed {" "background-color: rgb(100,100,145);" "border-style:inset;}" "QPushButton#pushButtonTable:hover {" "background-color: rgb(130,130,180);}" "QPushButton#pushButtonBarChart {" "background-color: rgb(125,125,175);" "border-style: outset;" "border-width: 2px;" "border-color: rgb(50,50,75);" "font: bold 22px;" "border-radius: 5px;" "min-width: 7em;}" "QPushButton#pushButtonBarChart:hover:pressed {" "background-color: rgb(100,100,145);" "border-style:inset;}" "QPushButton#pushButtonBarChart:hover {" "background-color: rgb(130,130,180);}" "QPushButton#pushButtonLineChart {" "background-color: rgb(125,125,175);" "border-style: outset;" "border-width: 2px;" "border-color: rgb(50,50,75);" "font: bold 22px;" "border-radius: 5px;" "min-width: 7em;}" "QPushButton#pushButtonLineChart:hover:pressed {" "background-color: rgb(100,100,145);" "border-style:inset;}" "QPushButton#pushButtonLineChart:hover {" "background-color: rgb(130,130,180);}" "QPushButton#pushButtonActiveGraphs {" "background-color: rgb(125,125,175);" "border-style: outset;" "border-width: 2px;" "border-color: rgb(50,50,75);" "font: bold 18px;" "border-radius: 5px;" "min-width: 7em;}" "QPushButton#pushButtonActiveGraphs:hover:pressed {" "background-color: rgb(100,100,145);" "border-style:inset;}" "QPushButton#pushButtonActiveGraphs:hover {" "background-color: rgb(130,130,180);}" "QPushButton#pushButtonChooseFilter {" "background-color: rgb(125,125,175);" "border-style: outset;" "border-width: 2px;" "border-color: rgb(50,50,75);" "font: bold 22px;" "border-radius: 5px;" "min-width: 7em;}" "QPushButton#pushButtonChooseFilter:hover:pressed {" "background-color: rgb(100,100,145);" "border-style:inset;}" "QPushButton#pushButtonChooseFilter:hover {" "background-color: rgb(130,130,180);}" ); displayDialog = new DisplayWindow(); _fdata = new FilterData(); ui->treeWidget->clear(); ui->treeWidget->setColumnCount(2); ui->treeWidget->setColumnWidth(1,250); populateTreeWithServices(); QObject::connect(this, SIGNAL(serviceReady(QString)), _fdata, SLOT(parseService(QString))); QObject::connect(ui->treeWidget, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(getMeasuresForService(QTreeWidgetItem*))); QObject::connect(ui->treeWidget, SIGNAL(itemClicked(QTreeWidgetItem*,int)), this, SLOT(parseMeasures(QTreeWidgetItem*))); QObject::connect(_fdata, SIGNAL(measureReady(QString,QString,QString)), this, SLOT(addItem(QString,QString,QString))); QObject::connect(this, SIGNAL(measureReady(QString,QString)), _fdata, SLOT(parseMeasures(QString,QString))); QObject::connect(_fdata, SIGNAL(resultReady(Measure&)), this, SLOT(updateMeasure(Measure&))); loadState(); } /** * @brief Destructor that deletes the choosedata screen. * * @param *parent Pointer to the QWidget * */ ChooseData::~ChooseData() { delete ui; delete _fdata; delete displayDialog; } /** * @brief Slot to create a new dialog screen to view a table. * * The new widget is a part of the displayDialog window and is called WidgetTableChart. * The user will be able to see the data in a table and continue to filter the data. * */ void ChooseData::on_pushButtonTable_clicked() { if(_measure->name() != "") { displayDialog->addTab(new WidgetTableChart(displayDialog,*_measure),"Table:" + _measure->id()); displayDialog->show(); } } /** * @brief Slot to create a new dialog screen to view a bar chart. * * The new widget is a part of the displayDialog window and is called WidgetBarChart. * The user will be able to see the data in a bar chart format and continue to filter the data. * */ void ChooseData::on_pushButtonBarChart_clicked() { if(_measure->name() != "") { displayDialog->addTab(new widgetBarChart(displayDialog,*_measure,_measure->maxmin()),"Bar:" + _measure->id()); displayDialog->show(); } } /** * @brief Slot to create a new dialog screen to view a line chart. * * The new widget is a part of the displayDialog window. The user can select to view two * different service measures at once to in a line chart compare values, or may only view one. * The user be able to select municipalites and years to view in that widget. * */ void ChooseData::on_pushButtonLineChart_clicked() { if(_measure->name() != "" && !ui->chkbox->isChecked()) { displayDialog->addTab(new WidgetLineChart(displayDialog, *_measure,_measure->maxmin()),"Line:" + _measure->id()); displayDialog->show(); } else if(_measure->name() != "" && _measure2->name() != "" && ui->treeWidget->selectedItems().size() == 2){ displayDialog->addTab(new WidgetCompLineChart(displayDialog, *_measure,*_measure2),"Comp Line:" + _measure->id()); displayDialog->show(); } } /** * @brief ChooseData::populateTreeWithServices add the services to the service / measure tree */ void ChooseData:: populateTreeWithServices(){ for(QMap<QString,ServiceType>::const_iterator i = _fdata->serviceList().begin();i != _fdata->serviceList().end(); ++i){ QString name = _fdata->serviceName(i.key()); QTreeWidgetItem* item = new QTreeWidgetItem(); item->setText(0, name); item->setText(1, i.key()); ui->treeWidget->addTopLevelItem(item); } } /** * @brief ChooseData::getMeasuresForService slot for deciding the id of the service * @param item holding the ServiceType */ void ChooseData::getMeasuresForService(QTreeWidgetItem *item){ //qDebug()<<"In getMeasureForService"; if(item->childCount() == 0 && !item->parent()){ QString sID; for(QMap<QString,QString>::const_iterator i = _fdata->serviceNameList().begin();i != _fdata->serviceNameList().end(); ++i){ QString name = _fdata->serviceName(i.key()); if(name == item->text(0)) sID = i.key(); } _sID = sID; emit serviceReady(_sID); } } /** * @brief ChooseData::parseMeasures slot for preparing the sID and mID for parsing the measures, * @param item containing the serviceType */ void ChooseData::parseMeasures(QTreeWidgetItem *item){ //qDebug()<<"In in ParseMeasures()"; if(item->parent()){ QString sID; for(QMap<QString,QString>::const_iterator i = _fdata->serviceNameList().begin();i != _fdata->serviceNameList().end(); ++i){ QString name = _fdata->serviceName(i.key()); if(name == item->parent()->text(0)) sID = i.key(); } _sID = sID; emit measureReady( item->text(1),_sID); } } /** * @brief ChooseData::addItem adds measures to the QTreeWidget under their appropriate service type * @param sID id for the serviceType * @param measure id for the measure of interest * @param title description for the measure */ void ChooseData::addItem(QString sID, QString measure, QString title){ QTreeWidgetItem* item = new QTreeWidgetItem(); //set up new item item->setText(0,title); item->setText(1,measure); //determine who the parent is int parentID = 0; for(QMap<QString,QString>::const_iterator i = _fdata->serviceNameList().begin();i != _fdata->serviceNameList().end(); ++i){ if(sID == i.key()){ break; } parentID++; } //qDebug()<<"adding item to tree widget pnum = "<<parentID<< " sID = "<< sID<< "columnCount() "<< item->columnCount(); ui->treeWidget->topLevelItem(parentID)->addChild(item); } /** * @brief ChooseData::updateMeasure set the last measure parsed to the active measure for the QPlots * @param m measure parsed last */ void ChooseData::updateMeasure(Measure& m){ static bool loaded = false; if(!loaded){ *_measure = m; loaded = true; _measure->calcYearRange(); }else{ try { *_measure = _fdata->loadMeasure(ui->treeWidget->currentItem()->parent()->text(1),ui->treeWidget->currentItem()->text(1)); if(ui->treeWidget->selectedItems().size() > 1 && _measure->id() == ui->treeWidget->selectedItems()[0]->text(1)) *_measure2 = _fdata->loadMeasure(ui->treeWidget->selectedItems()[1]->parent()->text(1),ui->treeWidget->selectedItems()[1]->text(1)); else if(ui->treeWidget->selectedItems().size() > 1) *_measure2 = _fdata->loadMeasure(ui->treeWidget->selectedItems()[0]->parent()->text(1),ui->treeWidget->selectedItems()[0]->text(1)); _measure->calcYearRange(); _measure2->calcYearRange(); } catch(std::string s) { std::cout << s << std::endl; } } saveState(); } /** * @brief ChooseData::on_pushButtonActiveGraphs_clicked Display active graphs * * The user can close the displayDialog so this button allows the user to view the active graphs again. */ void ChooseData::on_pushButtonActiveGraphs_clicked() { displayDialog->show(); } /** * @brief ChooseData::on_treeWidget_itemSelectionChanged Handle limiting selections to two when in comparison mode */ void ChooseData::on_treeWidget_itemSelectionChanged() { if(ui->treeWidget->currentItem() != NULL){ if(ui->treeWidget->currentItem()->parent() == NULL) ui->treeWidget->currentItem()->setSelected(false); if(ui->treeWidget->selectedItems().size() > 2) ui->treeWidget->selectedItems()[0]->setSelected(false); if(!ui->treeWidget->currentItem()->isSelected() && ui->treeWidget->selectedItems().size() == 1) { ui->treeWidget->setCurrentItem(ui->treeWidget->selectedItems()[0]); ui->treeWidget->currentItem()->setSelected(true); } if(ui->treeWidget->selectedItems().size() == 0) { _measure = new Measure(); } } } /** * @brief ChooseData::on_chkbox_toggled Enable/Disable Comparison Mode * @param checked */ void ChooseData::on_chkbox_toggled(bool checked) { if(checked) { ui->treeWidget->setSelectionMode(QAbstractItemView::MultiSelection); ui->pushButtonBarChart->hide(); ui->pushButtonTable->hide(); } else { if(ui->treeWidget->selectedItems().size() == 2) ui->treeWidget->selectedItems()[1]->setSelected(false); ui->treeWidget->setSelectionMode(QAbstractItemView::SingleSelection); ui->pushButtonBarChart->show(); ui->pushButtonTable->show(); } } /** * @brief ChooseData::closeEvent close the open charts if this window closes * @param e */ void ChooseData::closeEvent(QCloseEvent *e) { displayDialog->close(); } /** * @brief ChooseData::saveState Saves the current mID, sID and opened top level nodes */ void ChooseData::saveState(){ //clear the file by overwriting it std::ofstream("persistance.txt", std::ios::out).close(); //create a stream object, check if its open, write to it and then close it std::ofstream f("persistance.txt"); if(f.is_open()) { f<<_sID.toStdString()<<std::endl<<_measure->id().toStdString()<<std::endl; for(int i = 0; i < ui->treeWidget->topLevelItemCount(); ++i) { if (ui->treeWidget->topLevelItem(i)->isExpanded()) { std::stringstream ss; ss<<i; f<<ss.str()<<std::endl; } } } f.close(); } /** * @brief ChooseData::loadState populates and loads in the previously opened nodes, and the last measure selected */ void ChooseData::loadState(){ std::ifstream f("persistance.txt"); if(f.is_open()){ std::string sID; std::string mID; std::string line; int nodeID; int count = 0; _sID = QString::fromStdString(sID); while(std::getline(f, line)){ if(count == 0) { sID = line; //std::cout<<sID<<std::endl; ++count; } else if(count == 1) { mID = line; //std::cout<<mID<<std::endl; ++count; } else { std::stringstream ss(line); if(ss>>nodeID) { //std::cout<<nodeID<<std::endl; getMeasuresForService(ui->treeWidget->topLevelItem(nodeID)); ui->treeWidget->topLevelItem(nodeID)->setExpanded(true); } } } emit serviceReady(QString::fromStdString(sID)); emit measureReady(QString::fromStdString(mID), QString::fromStdString(sID)); } f.close(); }
c32e767c14e65537ed6366f1942abb26da83a56a
58196ebb2e4a87cf11d8a0c48c3524c715403026
/include/IDisplayModule.hpp
f215746308492de3f89d8fb43029f8b4ec83a10f
[]
no_license
achillelrc/ArcadeFramework
2f7d8a7acb3d3ad7d6432ebbf624421742255a78
9ad09e2e19ab2469c63d5e22d9e03a3a71a16ad3
refs/heads/master
2022-08-24T12:26:40.807334
2019-11-12T17:15:19
2019-11-12T17:15:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,034
hpp
IDisplayModule.hpp
// // EPITECH PROJECT, 2018 // bootstrap-arcade // File description: // IDisplayModule.hpp // #ifndef IDISPLAYMODULE_HPP_ # define IDISPLAYMODULE_HPP_ #include <string> #include <vector> #include "ICoreProgram.hpp" class IGameModule; class IDisplayModule { public: virtual ~IDisplayModule() = default; virtual void init(ICoreProgram *) = 0; virtual void destroy() = 0; virtual void setHandler(void *) = 0; virtual void setGraphicLibName(std::vector<std::string>) = 0; virtual void setGameLibName(std::vector<std::string>) = 0; virtual void setScore(std::vector<std::string>) = 0; virtual void setUserName(std::string userName) = 0; virtual void *getHandler() const = 0; virtual const std::string &getName() const = 0; virtual const std::string &getUserName() const = 0; virtual void updateDisplay(IGameModule *) = 0; virtual int displayMenu() = 0; virtual void printText(std::string, long = 2000000) = 0; virtual std::string getKey() = 0; virtual void keyAction(std::string) = 0; }; #endif // IDISPLAYMODULE_HPP_
f4e061d14276728ba7b9818faae7f982f83bf660
f6ebac4643ef054b821af426db67a1b8e59d90aa
/src/Distances.cpp
5e97993db250e58c94635a8b786a47740446baf8
[]
no_license
bauerj4/Interaction_Networks
4ec318eaa631d66896ee046427a354b2ef6c18d0
d6591fe0536780727cc43a190a646476294f799d
refs/heads/master
2016-09-14T09:14:56.825841
2016-04-29T18:07:41
2016-04-29T18:07:41
57,036,852
0
0
null
null
null
null
UTF-8
C++
false
false
8,079
cpp
Distances.cpp
#include "../include/Proto.h" #include "../include/Node.h" #include "../include/Graph.h" #include "../include/Compile_Time_Options.h" #include <iostream> #include <vector> #include <stdio.h> #include <omp.h> #ifdef COSMIC_WEB void globalfns::Cosmic_GetAllPaths(Cosmic_Graph * graph) { unsigned int i,j; int count; FILE * fileout; #ifdef CALCULATE_BETWEENESS double betweeness_out; #endif fileout = fopen("OUTPUTS/cosmic_distances.bin","wb"); count = graph->GetNodeCount(); fwrite(&count, sizeof(int), 1, fileout); std::cout << "Getting distances and betweeness..." << std::endl; #ifdef OPENMP // Need to fix race condition for file writing #pragma omp parallel for #endif for (j=0; j < count; j++) { /* Get all paths */ std::vector<int> distances(count, -1); globalfns::Cosmic_PathLengthsFromNode(graph->GetNodes()[j], graph, distances); #ifdef OPENMP #pragma omp critical #endif for ( i = 0; i < count; i++ ) { /* Write and reset distances */ fwrite(&distances[i], sizeof(int), 1, fileout); distances[i] = -1; } } fclose(fileout); #ifdef CALCULATE_BETWEENESS fileout = fopen("OUTPUTS/cosmic_betweeness.bin","wb"); for (i=0; i<count; i++) { betweeness_out = graph->GetNodes()[i]->GetBetweeness(); /* Write betweenesses */ fwrite(&betweeness_out, sizeof(double), 1, fileout); } fclose(fileout); #endif } void globalfns::Cosmic_PathLengthsFromNode(Cosmic_Node * node, Cosmic_Graph * graph, std::vector<int> &distances) { unsigned int i; unsigned int j; unsigned int level; #ifdef CALCULATE_BETWEENESS double sigma_ratio; Cosmic_Node * ThisNode; std::vector<int> sigma(graph->GetNodeCount(), 0); std::vector<double> delta(graph->GetNodeCount(),0.); #endif // CALCULATE_BETWEENESS std::vector<Cosmic_Node *> NextShell; std::vector<Cosmic_Node *> CurrentShell; std::vector<Cosmic_Node *> MyNeighbors; #ifdef CALCULATE_BETWEENESS std::vector<Cosmic_Node *> BetweenessShell; std::vector<Cosmic_Node *> Predecessors; sigma[node->ID()] = 1; #endif // CALCULATE_BETWEENESS level = 0; distances[node->ID()]=0; CurrentShell.push_back(node); while (CurrentShell.size() != 0) { NextShell.clear(); // Empties vector for (i=0; i < CurrentShell.size(); i++) { #ifdef CALCULATE_BETWEENESS BetweenessShell.push_back(CurrentShell[i]); #endif MyNeighbors = CurrentShell[i]->GetNeighbors(); for (j=0; j < MyNeighbors.size(); j++) { if (distances[MyNeighbors[j]->ID()] == -1) { NextShell.push_back(MyNeighbors[j]); distances[MyNeighbors[j]->ID()] = level + 1; } #ifdef CALCULATE_BETWEENESS if (distances[MyNeighbors[j]->ID()] == distances[CurrentShell[i]->ID()] + 1) { /* Compute dependencies */ sigma[MyNeighbors[j]->ID()] += sigma[CurrentShell[i]->ID()]; Predecessors.push_back(CurrentShell[i]); } #endif // CALCULATE_BETWEENESS } } CurrentShell.clear(); for (i=0; i < NextShell.size(); i++) { CurrentShell.push_back(NextShell[i]); } level++; } #ifdef CALCULATE_BETWEENESS i = BetweenessShell.size() - 1; while (BetweenessShell.size() != 0) { ThisNode = BetweenessShell[i]; // ThisNode is Brande's node w BetweenessShell.pop_back(); for (j=0; j < Predecessors.size(); j++) { /* The predecessor node is Brande's v */ if (Predecessors[j]->ID() != ThisNode->ID() && Predecessors[j]->ID() != node->ID() && distances[Predecessors[j]->ID()] != -1) { sigma_ratio = ((double)sigma[Predecessors[j]->ID()] / (double)sigma[ThisNode->ID()] ); delta[Predecessors[j]->ID()] += sigma_ratio * (1. + (double)delta[ThisNode->ID()]); } else if (distances[Predecessors[j]->ID()] == -1) { delta[Predecessors[j]->ID()] += 0.; } else { delta[Predecessors[j]->ID()] = 1; } } if (node->ID() != ThisNode->ID()) { ThisNode->AddToBetweeness( delta[ThisNode->ID()]); } i--; // pop back index } #endif } #endif // COSMIC_WEB #ifdef RANDOM_SMALL_WORLD /* Do N BFS on the graph to get distance vectors and write them to hard disk */ void globalfns::SW_GetAllPaths(SW_Graph * graph)//, std::vector<int> &distances) { unsigned int i,j; int count; FILE * fileout; #ifdef CALCULATE_BETWEENESS double betweeness_out; #endif fileout = fopen("OUTPUTS/sw_distances.bin","wb"); count = NODES; fwrite(&count, sizeof(int), 1, fileout); //std::vector<int> distances(count, -1); #ifdef OPENMP // Need to fix race condition for file writing #pragma omp parallel for #endif for (j=0; j < NODES; j++) { std::vector<int> distances(count, -1); globalfns::SW_PathLengthsFromNode(graph->GetNodes()[j], graph, distances); #ifdef OPENMP #pragma omp critical #endif for ( i = 0; i < NODES; i++ ) { /* Write and update distances */ fwrite(&distances[i], sizeof(int), 1, fileout); distances[i] = -1; } } fclose(fileout); #ifdef CALCULATE_BETWEENESS fileout = fopen("OUTPUTS/sw_betweeness.bin","wb"); for (i=0; i<NODES; i++) { betweeness_out = graph->GetNodes()[i]->GetBetweeness(); /* Write betweenesses */ fwrite(&betweeness_out, sizeof(double), 1, fileout); } fclose(fileout); #endif } /* Do a BFS on the graph */ void globalfns::SW_PathLengthsFromNode(SW_Node * node, SW_Graph * graph, std::vector<int> &distances) { unsigned int i; unsigned int j; unsigned int level; #ifdef CALCULATE_BETWEENESS double sigma_ratio; SW_Node * ThisNode; std::vector<int> sigma(NODES, 0); std::vector<double> delta(NODES,0.); #endif std::vector<SW_Node *> NextShell; std::vector<SW_Node *> CurrentShell; std::vector<SW_Node *> MyNeighbors; #ifdef CALCULATE_BETWEENESS std::vector<SW_Node *> BetweenessShell; std::vector<SW_Node *> Predecessors; sigma[node->ID()] = 1; #endif level = 0; distances[node->ID()]=0; CurrentShell.push_back(node); while (CurrentShell.size() != 0) { NextShell.clear(); // Empties vector for (i=0; i < CurrentShell.size(); i++) { #ifdef CALCULATE_BETWEENESS BetweenessShell.push_back(CurrentShell[i]); #endif MyNeighbors = CurrentShell[i]->GetNeighbors(); for (j=0; j < MyNeighbors.size(); j++) { if (distances[MyNeighbors[j]->ID()] == -1) { NextShell.push_back(MyNeighbors[j]); distances[MyNeighbors[j]->ID()] = level + 1; } #ifdef CALCULATE_BETWEENESS if (distances[MyNeighbors[j]->ID()] == distances[CurrentShell[i]->ID()] + 1) { sigma[MyNeighbors[j]->ID()] += sigma[CurrentShell[i]->ID()]; Predecessors.push_back(CurrentShell[i]); } #endif } } CurrentShell.clear(); for (i=0; i < NextShell.size(); i++) { CurrentShell.push_back(NextShell[i]); } level++; } #ifdef CALCULATE_BETWEENESS i = BetweenessShell.size() - 1; while (BetweenessShell.size() != 0) { ThisNode = BetweenessShell[i]; // ThisNode is Brande's node w BetweenessShell.pop_back(); for (j=0; j < Predecessors.size(); j++) { /* The predecessor node is Brande's v */ if (Predecessors[j]->ID() != ThisNode->ID() && Predecessors[j]->ID() != node->ID()) { sigma_ratio = ((double)sigma[Predecessors[j]->ID()] / (double)sigma[ThisNode->ID()] ); delta[Predecessors[j]->ID()] += sigma_ratio * (1. + (double)delta[ThisNode->ID()]); } else { delta[Predecessors[j]->ID()] = sigma[Predecessors[j]->ID()]; } } if (node->ID() != ThisNode->ID()) { ThisNode->AddToBetweeness( delta[ThisNode->ID()]); } i--; } #endif } #endif // RANDOM_SMALL_WORLD
897ea1ddabc30f982a8fcd292ff3131791609745
982ec419ec331493e397fca3767d3fcdbdefb300
/Runtime/Collision/CCollisionEdge.cpp
fa3d14521f7136f00c8e06e49377f66dac36dad3
[ "MIT" ]
permissive
vtsingaras/urde
2dca712535b066262e05d200b33167971e0e84b1
86041281b24e698286b88f2576e4a8409462912b
refs/heads/master
2020-12-31T01:23:13.464965
2016-12-13T02:57:08
2016-12-13T02:57:08
66,197,163
0
0
null
2016-08-21T12:14:45
2016-08-21T12:14:45
null
UTF-8
C++
false
false
313
cpp
CCollisionEdge.cpp
#include "CCollisionEdge.hpp" namespace urde { CCollisionEdge::CCollisionEdge(CInputStream& in) { x0_index1 = in.readUint16Big(); x2_index2 = in.readUint16Big(); } u16 CCollisionEdge::GetVertIndex1() const { return x0_index1; } u16 CCollisionEdge::GetVertIndex2() const { return x2_index2; } }
62f4b2f2535a996e92384ed1bc9ebd83b4f7abae
9195ae417f7e9c524636009dc9355c3720120d37
/Damask/ast/node/operatornode.h
b49f67666149b431398cc7e518672f4b59bb8969
[ "MIT" ]
permissive
imefGames/Damask
eda60dafc5620019adb7c5b6648274c6b660f7aa
478a377517da93e8fd42cb5c68619f8840bf1561
refs/heads/master
2022-11-15T19:30:54.909999
2020-07-08T17:35:41
2020-07-08T17:35:41
273,797,264
0
0
null
null
null
null
UTF-8
C++
false
false
630
h
operatornode.h
#pragma once #include <ast/node/node.h> enum class EToken; namespace AST { class OperatorNode : public Node { public: OperatorNode(); inline EToken GetOperatorType() const { return m_OperatorType; } inline Node* GetLHSNode() { return m_LHSNode; } inline Node* GetRHSNode() { return m_RHSNode; } void SetOperatorType(EToken operatorType); void SetLHSNode(Node* lhsNode); void SetRHSNode(Node* rhsNode); void Accept(ASTVisitor& visitor) override; private: EToken m_OperatorType; Node* m_LHSNode; Node* m_RHSNode; }; }
2a2a639a18fdfe1d02747f03007ce1bdb841d518
070e3909b8cda5c914002b2aa1ec8655107affaa
/Computer_player.h
cdb1b3c0a634815a79b864d1448e4d0123978e32
[]
no_license
lkmlkm073/Othello
64bb0639cc12697950caf34752bef9ddcba4e2dd
12052ac2522709e726dcf2006e8f486f445ac4f5
refs/heads/master
2020-03-09T00:39:39.310526
2018-04-07T08:47:01
2018-04-07T08:47:01
128,493,756
0
0
null
null
null
null
UTF-8
C++
false
false
6,782
h
Computer_player.h
// Computer_player.h ///////////////////////////////////////////////////////////////////////// // // Student Info // ------------ // // Name : <Kevin Kyungmin Lee> // St.# : <301271170> // Email: <kla141@sfu.ca> // // // Statement of Originality // ------------------------ // // All the code and comments below are my own original work. For any non- // original work, I have provided citations in the comments with enough // detail so that someone can see the exact source and extent of the // borrowed work. // // In addition, I have not shared this work with anyone else, and I have // not seen solutions from other students, tutors, websites, books, // etc. // ///////////////////////////////////////////////////////////////////////// // This class is quite similar to the Human_player class // Only the difference is it will make a random moves in only valid places // and it will take corners prior to other valid places. using namespace std; // Human_player class that dervied from Player class class Computer_player : public Player { int comp_score; // contains user and comp score int user_score; Board board; public: // constructor Computer_player(Board B) : comp_score(0),user_score(0), board(B) { } // getters that return board and comp_score Board get_board() const { return board; } int get_score() const { return comp_score;} // get board from the opponent and use it void set_board( Board B ){ board = B; } // it counts how many blacks and whites are in the current board void set_score(){ user_score = 0; comp_score = 0; for(int i = 1; i < board.height()-1; i++){ for(int j = 1; j < board.width()-1; j++){ if(board.get(i, j) == Tile::Black){ user_score += 1; } if(board.get(i, j) == Tile::White){ comp_score += 1; } } } } // Now check board[r][c] is legal or not // 0 means false, 1 means true; // totally identical to the Human_player's method // only the opponent colour is different int is_valid_move(int r, int c){ int row_delta = 0; int col_delta = 0; int x = 0; int y = 0; int is_valid = 0; for(int i = 0; i < board.height(); i++){ for(int j = 0; j < board.width(); j++){ if(board.get(r,c) != Tile::Space) continue; for(row_delta = -1; row_delta <= 1; row_delta++){ for(col_delta = -1; col_delta <= 1; col_delta++){ if(r + row_delta < 0 || r + row_delta >= board.height() - 1 || c + col_delta < 0 || c + col_delta >= board.width() - 1 || (row_delta == 0 && col_delta == 0)) continue; if(board.get(r + row_delta, c + col_delta) == Tile::Black){ x = r + row_delta; y = c + col_delta; for(;;){ x += row_delta; y += col_delta; if(x < 0 || x >= board.height() - 1 || y < 0 || y >= board.width() - 1) break; if(board.get(x,y) == Tile::Space) break; if(board.get(x,y) == Tile::White){ is_valid = 1; break; } } } } } } } return is_valid; } // Same as well bool flip(int r, int c){ int row_delta = 0; int col_delta = 0; int x = 0; int y = 0; bool is_valid = true; for(int i = 0; i < board.height(); i++){ for(int j = 0; j < board.width(); j++){ if(board.get(r,c) != Tile::Space) continue; for(row_delta = -1; row_delta <= 1; row_delta++){ for(col_delta = -1; col_delta <= 1; col_delta++){ if(r + row_delta < 0 || r + row_delta >= board.height() - 1 || c + col_delta < 0 || c + col_delta >= board.width() - 1 || (row_delta == 0 && col_delta == 0)) continue; if(board.get(r + row_delta, c + col_delta) == Tile::Black){ x = r + row_delta; y = c + col_delta; for(;;){ x += row_delta; y += col_delta; if(x < 0 || x >= board.height() - 1 || y < 0 || y >= board.width() - 1) break; if(board.get(x,y) == Tile::Space) break; if(board.get(x,y) == Tile::White){ is_valid = false; for(;;){ x -= row_delta; y -= col_delta; board.set_loc(r,c,Tile::White); if(x == r && y == c) break; board.set_loc(x,y,Tile::White); } break; } } } } } } } return is_valid; } // This part is quite different // basically creating the array contains truth values of the valid moves are the Same // but this time it will make a move randomly and take important places first. void make_move(){ int row = 1; int col = 1; int valid_moves[64]; int index = 0; bool no_legal_move = true; // Here for(int i = 0; i < 64; i++){ valid_moves[i] = 0; } for(int i = 1; i <= 8; i++){ for(int j = 1; j <= 8; j++){ valid_moves[index] = is_valid_move(i,j); index++; } } for(int i = 0; i <= index; i++){ if(valid_moves[i] == 1){ no_legal_move = false; } } // to Here are same while(true){ if( no_legal_move ){ // if no more valid moves, automatically pass its turn cout << "Computer has no legal move. It is your turn again." << endl; break; } // Take corners is a prioritiy if(valid_moves[0] == 1){ flip(1,1); board.println(); break; } else if(valid_moves[7] == 1){ // valid_moves[7] = (1,8) ; row 1, col 8 flip(1,8); board.println(); break; } else if(valid_moves[56] == 1){ // valid_moves[56] = (8,1) ; row 8, col 1 flip(8,1); board.println(); break; } else if(valid_moves[63] == 1){ // and so on... flip(8,8); board.println(); break; } row = rand() % 8 + 1; // set random row and col 1 to 8 col = rand() % 8 + 1; if( !flip(row,col) ){ // if those randomly generated values have valid position board.println(); // then make a move and quit the loop break; } } } // print score method void print_score(){ set_score(); cout << "\t\tYour score : " << user_score << "\t\tComputer's score : " << comp_score << endl << endl; } };
b6e7c706173cab14ab4146383e90866005555b1e
88343b7efa89d20328df5be4961cf71c0a4ca15e
/Cpp/43. Multiply Strings.cpp
c27c419137a3de6b07b2ed57a309b2caca019aa4
[]
no_license
tonycar12002/leetcode
5396f4fb683edd4bad993968178e01621f4e656b
7334c7056bdbd041efa63610f9a9d378620c1cd8
refs/heads/master
2021-07-21T19:09:15.373392
2021-07-05T13:20:20
2021-07-05T13:20:20
185,445,635
0
0
null
null
null
null
UTF-8
C++
false
false
1,087
cpp
43. Multiply Strings.cpp
/* Author: Tony Hsiao Date: 2020/04/06 Topic: 43. Multiply Strings Speed: 16 ms, 6.8 MB Note: */ #include <iostream> #include <vector> #include <algorithm> #include <queue> #include <list> #include <map> using namespace std; class Solution { public: string multiply(string num1, string num2) { int size_1 = num1.size(), size_2 = num2.size(); vector<int> ans(size_2 + size_1, 0); for (int i=0; i<size_1; ++i) { for (int j=0; j<size_2; ++j) { ans[i+j] += (num1[size_1 - i - 1] - '0') * (num2[size_2 - j - 1] - '0'); } } for (int i=0; i<size_1+size_2; ++i) { if (ans[i] >= 10) { ans[i+1] += ans[i] / 10; ans[i] %= 10; } } string ans_string = ""; bool un_zero = false; for (int i=size_2+size_1-1 ;i>=0; --i) { if (ans[i] != 0 && un_zero == false) un_zero = true; if (un_zero) { ans_string += ans[i]+'0'; } } return ans_string; } };
622561d1f04cf1111bf10fdc5fdf0dc578dcb898
bc01d89e3b77b9b60afd6f5f8fcad5675b813f8e
/natplugins/natptraversalcontroller/tsrc/ut_NatTraversalController/src/ut_cnatbindingstunrefresher.cpp
08a81eb628910b0b12070bfb0a0ad6403101d7e4
[]
no_license
SymbianSource/oss.FCL.sf.mw.ipappsrv
fce862742655303fcfa05b9e77788734aa66724e
65c20a5a6e85f048aa40eb91066941f2f508a4d2
refs/heads/master
2021-01-12T15:40:59.380107
2010-09-17T05:32:38
2010-09-17T05:32:38
71,849,396
1
0
null
null
null
null
UTF-8
C++
false
false
8,171
cpp
ut_cnatbindingstunrefresher.cpp
/* * Copyright (c) 2004 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ // CLASS HEADER #include "ut_cnatbindingstunrefresher.h" // INTERNAL INCLUDES #include "CNATBindingSTUNRefresher.h" #include "CNATBinding.h" // EXTERNAL INCLUDES #include <digia/eunit/eunitmacros.h> #include "natfwstunclient.h" #include "natfwstunbinding.h" #include <CommDbConnPref.h> #include <SecureSocket.h> // CONSTANTS const TInt KRefreshInterval = 10; // CONSTRUCTION UT_CNATBindingSTUNRefresher* UT_CNATBindingSTUNRefresher::NewL() { UT_CNATBindingSTUNRefresher* self = UT_CNATBindingSTUNRefresher::NewLC(); CleanupStack::Pop(); return self; } UT_CNATBindingSTUNRefresher* UT_CNATBindingSTUNRefresher::NewLC() { UT_CNATBindingSTUNRefresher* self = new( ELeave ) UT_CNATBindingSTUNRefresher(); CleanupStack::PushL( self ); self->ConstructL(); return self; } // Destructor (virtual by CBase) UT_CNATBindingSTUNRefresher::~UT_CNATBindingSTUNRefresher() { } // Default constructor UT_CNATBindingSTUNRefresher::UT_CNATBindingSTUNRefresher() { } // Second phase construct void UT_CNATBindingSTUNRefresher::ConstructL() { // The ConstructL from the base class CEUnitTestSuiteClass must be called. // It generates the test case table. CEUnitTestSuiteClass::ConstructL(); } // METHODS void UT_CNATBindingSTUNRefresher::SetupL() { iDeltaTimer = CDeltaTimer::NewL(CActive::EPriorityStandard); User::LeaveIfError(iSocketServ.Connect()); User::LeaveIfError(iConnection.Open(iSocketServ)); TCommDbConnPref prefs; prefs.SetDialogPreference(ECommDbDialogPrefDoNotPrompt); prefs.SetDirection(ECommDbConnectionDirectionOutgoing); prefs.SetIapId(5); User::LeaveIfError(iConnection.Start(prefs)); User::LeaveIfError(iSocket.Open(iSocketServ, KAfInet, KSockDatagram, KProtocolInetUdp, iConnection)); iSTUNClient = CSTUNClient::NewL(2000,_L8("STUNServer"),0,_L8("stun"), iSocketServ,iConnection,*iDeltaTimer,*this); CSTUNBinding* STUNBinding = CSTUNBinding::NewLC(*iSTUNClient,iSocket); TInetAddr addr; iNATBinding = CNATBinding::NewL(89,iSocket,addr, *(MSIPNATTraversalRequestObserver*)NULL, *(MSIPNATBindingObserver*)NULL, *this); CleanupStack::Pop(STUNBinding); // Ownership is transferred iNATBinding->SetBinding(STUNBinding); iRefresher = new(ELeave)CNATBindingSTUNRefresher(*iDeltaTimer, KRefreshInterval, *this,*iNATBinding); } void UT_CNATBindingSTUNRefresher::Teardown() { iSocket.Close(); iConnection.Close(); iSocketServ.Close(); delete iRefresher; iRefresher = 0; delete iSTUNClient; iSTUNClient = 0; //iNATBinding owns iSTUNBinding delete iNATBinding; iNATBinding = 0; delete iDeltaTimer; iDeltaTimer = 0; } // From MNATBindingRefresherObserver void UT_CNATBindingSTUNRefresher::NATBindingRefreshComplete( TInt /*aCompletionCode*/) { } // From MSTUNClientObserver void UT_CNATBindingSTUNRefresher::STUNClientInitCompleted( const CSTUNClient& /*aClient*/, TInt /*aCompletionCode*/) { } // From MSTUNClientObserver void UT_CNATBindingSTUNRefresher::STUNBindingEventOccurredL( TSTUNBindingEvent /*aEvent*/, const CBinding& /*aBinding*/) { HBufC8* tmp = HBufC8::NewL(100); delete tmp; } // From MSTUNClientObserver void UT_CNATBindingSTUNRefresher::STUNBindingErrorOccurred( const CBinding& /*aBinding*/, TInt /*aError*/) { } // From MNATTraversalSocketManager TBool UT_CNATBindingSTUNRefresher::AddToSendingQueueL( MNATTraversalSocketUser& /*aUser*/) { // Make this function leave in low memory conditions delete HBufC8::NewL(100); return EFalse; } // From MNATTraversalSocketManager void UT_CNATBindingSTUNRefresher::SendingCompleted( MNATTraversalSocketUser& /*aUser*/) { } // Test functions void UT_CNATBindingSTUNRefresher::TestRefreshIntervalL() { // Generate 10 refresh values and check them for (TInt i=0; i<10; i++) { TInt interval = iRefresher->RefreshInterval(); EUNIT_ASSERT(interval >= KRefreshInterval*900000); EUNIT_ASSERT(interval <= KRefreshInterval*1100000); } // Invalid interval iRefresher->iRefreshInterval = 0; EUNIT_ASSERT_EQUALS(KErrUnderflow, iRefresher->RefreshInterval()); } void UT_CNATBindingSTUNRefresher::TestHasSocketL() { // Own UDP socket EUNIT_ASSERT_EQUALS(ETrue, iRefresher->HasSocket(iSocket)); //TCP socket RSocket tcpSocket; CleanupClosePushL(tcpSocket); User::LeaveIfError(tcpSocket.Open(iSocketServ,KAfInet,KSockStream, KProtocolInetTcp,iConnection)); // Because we have stubbed RSocket, normal subsessionhandle is not working // normally. Therefore we have to manually change its action here. tcpSocket.ChangeHandling(EFalse); // subsessionhandle, use own variation EUNIT_ASSERT_EQUALS(EFalse, iRefresher->HasSocket(tcpSocket)); tcpSocket.ChangeHandling(ETrue); // back to defaul behavior // TLS socket _LIT(KTLS1,"TLS1.0"); CSecureSocket* secureSocket = CSecureSocket::NewL(tcpSocket,KTLS1); CleanupStack::PushL(secureSocket); EUNIT_ASSERT_EQUALS(EFalse, iRefresher->CNATBindingRefresher::HasSocket(*secureSocket)); CleanupStack::PopAndDestroy(secureSocket); CleanupStack::PopAndDestroy(&tcpSocket); } void UT_CNATBindingSTUNRefresher::TestSetRefreshL() { EUNIT_ASSERT(!iRefresher->IsRefreshed()); iRefresher->SetRefresh(ETrue); EUNIT_ASSERT(iRefresher->IsRefreshed()); iRefresher->SetRefresh(ETrue); EUNIT_ASSERT(iRefresher->IsRefreshed()); iRefresher->SetRefresh(EFalse); EUNIT_ASSERT(!iRefresher->IsRefreshed()); iRefresher->SetRefresh(EFalse); EUNIT_ASSERT(!iRefresher->IsRefreshed()); } void UT_CNATBindingSTUNRefresher::TestContinueRefreshingL() { // Not refreshed EUNIT_ASSERT(!iRefresher->IsRefreshed()); iRefresher->ContinueRefreshing(); // Refreshed iRefresher->SetRefresh(ETrue); EUNIT_ASSERT(iRefresher->IsRefreshed()); iRefresher->ContinueRefreshing(); } void UT_CNATBindingSTUNRefresher::TestRefreshTimerExpiredL() { CNATBindingRefresher::RefreshTimerExpired(iRefresher); } // TEST TABLE EUNIT_BEGIN_TEST_TABLE( UT_CNATBindingSTUNRefresher, "Add test suite description here.", "UNIT" ) EUNIT_TEST( "TestRefreshIntervalL - test ", "UT_CNATBindingSTUNRefresher", "TestRefreshIntervalL", "FUNCTIONALITY", SetupL, TestRefreshIntervalL, Teardown) EUNIT_TEST( "TestHasSocketL - test ", "UT_CNATBindingSTUNRefresher", "TestHasSocketL", "FUNCTIONALITY", SetupL, TestHasSocketL, Teardown) EUNIT_TEST( "TestSetRefreshL - test ", "UT_CNATBindingSTUNRefresher", "TestSetRefreshL", "FUNCTIONALITY", SetupL, TestSetRefreshL, Teardown) EUNIT_TEST( "TestContinueRefreshingL - test ", "UT_CNATBindingSTUNRefresher", "TestContinueRefreshingL", "FUNCTIONALITY", SetupL, TestContinueRefreshingL, Teardown) EUNIT_TEST( "TestRefreshTimerExpiredL - test ", "UT_CNATBindingSTUNRefresher", "TestRefreshTimerExpiredL", "FUNCTIONALITY", SetupL, TestRefreshTimerExpiredL, Teardown) EUNIT_END_TEST_TABLE // END OF FILE
1d80fd37ed966efdd69ae40f628b0cce8c119ee5
aba99d1947e08cc171a67e544b5c825ce1c8bed8
/GameScreenTest.cpp
01c3ccebe658dd9d29a38833c701cb6512eacebb
[]
no_license
nicholasmirchandani/Stereotypical-Hacker
92053a56d6525f66a0a96bfeff515c77320487d7
0850f392a6cb57104f9d2ca020dee5a20451a2b7
refs/heads/master
2021-04-10T03:47:49.860302
2020-05-13T05:55:20
2020-05-13T05:55:20
248,907,933
0
0
null
2020-05-05T17:43:24
2020-03-21T04:42:41
null
UTF-8
C++
false
false
1,437
cpp
GameScreenTest.cpp
// Stereotypical-Hacker // GameScreen.cpp // Test for GameScreen class for typing mini-game. // Logan Welsh // 04/12/2020 #include "GameScreen.h" #include <iostream> #include <stdio.h> using namespace std; int main(int argc, char** argv) { int phraseAmt = 3; string phrases[phraseAmt] = { "No, I think we're just getting started.", "Sir; Finishing this fight.", "Wake me when you need me." }; GameScreen *gScrn = new GameScreen(); gScrn->getTilemap()->writeString(0, 0, "DEBUG INFO"); gScrn->getTilemap()->writeString(0, 1, "Last key pressed:"); gScrn->getTilemap()->writeString(0, 2, "Phrase number:"); gScrn->getTilemap()->writeString(0, 3, "Misses:"); gScrn->getTilemap()->writeString(0, 4, "Press '[' to skip a phrase (Debug only)"); char userInput = 0; for(int i = 0; i < phraseAmt; ++i) { gScrn->changePhrase(phrases[i]); gScrn->updateTerminal(); while(!gScrn->phraseComplete()) { system("stty raw"); userInput = getchar(); system("stty cooked"); if(userInput == '[') { break; } gScrn->charTyped(userInput); //gScrn->getTilemap()->setChar(7, 0, userInput); gScrn->getTilemap()->setChar(19, 1, userInput); gScrn->getTilemap()->writeString(19, 2, to_string(i)); gScrn->getTilemap()->writeString(19, 3, to_string(gScrn->getMisses())); gScrn->updateTerminal(); } } delete gScrn; return 0; }
3bf4b5a60a1cef2373e74cbb10386c6e006bab13
492976adfdf031252c85de91a185bfd625738a0c
/src/Game/AI/AI/aiKorokRailMove.h
80232a52ce64c0c405f1a17eab962c948664fb94
[]
no_license
zeldaret/botw
50ccb72c6d3969c0b067168f6f9124665a7f7590
fd527f92164b8efdb746cffcf23c4f033fbffa76
refs/heads/master
2023-07-21T13:12:24.107437
2023-07-01T20:29:40
2023-07-01T20:29:40
288,736,599
1,350
117
null
2023-09-03T14:45:38
2020-08-19T13:16:30
C++
UTF-8
C++
false
false
786
h
aiKorokRailMove.h
#pragma once #include "KingSystem/ActorSystem/actAiAi.h" namespace uking::ai { class KorokRailMove : public ksys::act::ai::Ai { SEAD_RTTI_OVERRIDE(KorokRailMove, ksys::act::ai::Ai) public: explicit KorokRailMove(const InitArg& arg); ~KorokRailMove() override; bool init_(sead::Heap* heap) override; void enter_(ksys::act::ai::InlineParamPack* params) override; void leave_() override; void loadParams_() override; protected: // static_param at offset 0x38 const float* mOnRailDistance_s{}; // static_param at offset 0x40 const float* mFarDistance_s{}; // static_param at offset 0x48 const bool* mIsIgnoreNoWaitStopPoint_s{}; // map_unit_param at offset 0x50 const float* mRailMoveSpeed_m{}; }; } // namespace uking::ai
6afc0d5265085034db80292477540e3dfbb855bf
66fc3d58e94e8340a0d825501776a1dea37c0198
/tests/cpu/ops/exposurecontrast/ExposureContrastOp_tests.cpp
4d69dd6aac78a2d7621e16a13f41e534387710a3
[ "BSD-3-Clause", "CC-BY-4.0" ]
permissive
AcademySoftwareFoundation/OpenColorIO
dad370b54be147ae94f18ed6414d53bd76e9ef74
96f528fdfb7f9fb24388e33f6a968d29a3909cf8
refs/heads/main
2023-08-29T08:51:45.625957
2023-08-29T01:42:37
2023-08-29T01:42:37
775,131
843
236
BSD-3-Clause
2023-09-14T02:56:01
2010-07-14T18:22:06
C++
UTF-8
C++
false
false
5,580
cpp
ExposureContrastOp_tests.cpp
// SPDX-License-Identifier: BSD-3-Clause // Copyright Contributors to the OpenColorIO Project. #include "ops/exposurecontrast/ExposureContrastOp.cpp" #include "testutils/UnitTest.h" namespace OCIO = OCIO_NAMESPACE; OCIO_ADD_TEST(ExposureContrastOp, create) { OCIO::TransformDirection direction = OCIO::TRANSFORM_DIR_FORWARD; OCIO::ExposureContrastOpDataRcPtr data = std::make_shared<OCIO::ExposureContrastOpData>(); OCIO::OpRcPtrVec ops; // Make it dynamic so that it is not a no op. data->getExposureProperty()->makeDynamic(); OCIO_CHECK_NO_THROW(OCIO::CreateExposureContrastOp(ops, data, direction)); OCIO_REQUIRE_EQUAL(ops.size(), 1); OCIO_REQUIRE_ASSERT(ops[0]); OCIO_CHECK_EQUAL(ops[0]->getInfo(), "<ExposureContrastOp>"); data = data->clone(); data->getContrastProperty()->makeDynamic(); OCIO_CHECK_NO_THROW(OCIO::CreateExposureContrastOp(ops, data, direction)); OCIO_REQUIRE_EQUAL(ops.size(), 2); OCIO_REQUIRE_ASSERT(ops[1]); OCIO::ConstOpRcPtr op1 = ops[1]; OCIO_CHECK_ASSERT(ops[0]->isSameType(op1)); } OCIO_ADD_TEST(ExposureContrastOp, inverse) { OCIO::TransformDirection direction = OCIO::TRANSFORM_DIR_FORWARD; OCIO::ExposureContrastOpDataRcPtr data = std::make_shared<OCIO::ExposureContrastOpData>(); data->setExposure(1.2); data->setPivot(0.5); OCIO::OpRcPtrVec ops; OCIO_CHECK_NO_THROW(OCIO::CreateExposureContrastOp(ops, data, direction)); OCIO_REQUIRE_EQUAL(ops.size(), 1); OCIO_REQUIRE_ASSERT(ops[0]); data = data->clone(); direction = OCIO::TRANSFORM_DIR_INVERSE; OCIO_CHECK_NO_THROW(OCIO::CreateExposureContrastOp(ops, data, direction)); OCIO_REQUIRE_EQUAL(ops.size(), 2); OCIO_REQUIRE_ASSERT(ops[1]); OCIO::ConstOpRcPtr op0 = ops[0]; OCIO::ConstOpRcPtr op1 = ops[1]; OCIO_CHECK_ASSERT(op0->isInverse(op1)); OCIO_CHECK_ASSERT(op1->isInverse(op0)); // Create op2 similar to op1 with different exposure. data = data->clone(); data->setExposure(1.3); OCIO_CHECK_NO_THROW(OCIO::CreateExposureContrastOp(ops, data, direction)); OCIO_REQUIRE_EQUAL(ops.size(), 3); OCIO_REQUIRE_ASSERT(ops[2]); OCIO::ConstOpRcPtr op2 = ops[2]; // As exposure from E/C is not dynamic and exposure is different, // op1 and op2 are different. OCIO_CHECK_ASSERT(op1 != op2); OCIO_CHECK_ASSERT(!op0->isInverse(op2)); // With dynamic property. data = data->clone(); data->getExposureProperty()->makeDynamic(); auto dp3 = data->getExposureProperty(); OCIO_CHECK_NO_THROW(OCIO::CreateExposureContrastOp(ops, data, direction)); OCIO_REQUIRE_EQUAL(ops.size(), 4); OCIO_REQUIRE_ASSERT(ops[3]); OCIO::ConstOpRcPtr op3 = ops[3]; data = data->clone(); auto dp4 = data->getExposureProperty(); direction = OCIO::TRANSFORM_DIR_FORWARD; OCIO_CHECK_NO_THROW(OCIO::CreateExposureContrastOp(ops, data, direction)); OCIO_REQUIRE_EQUAL(ops.size(), 5); OCIO_REQUIRE_ASSERT(ops[4]); // Exposure dynamic, same value, opposite direction. OCIO_CHECK_ASSERT(!ops[4]->isInverse(op3)); OCIO_CHECK_ASSERT(!ops[4]->isInverse(op1)); OCIO_CHECK_ASSERT(!ops[4]->isInverse(op0)); // When dynamic property is enabled they are never equal. dp4->setValue(-1.); OCIO_CHECK_ASSERT(dp3->getValue() != dp4->getValue()); OCIO_CHECK_ASSERT(!ops[4]->isInverse(op3)); dp3->setValue(-1.); OCIO_CHECK_ASSERT(dp3->getValue() == dp4->getValue()); OCIO_CHECK_ASSERT(!ops[4]->isInverse(op3)); } OCIO_ADD_TEST(ExposureContrastOp, create_transform) { OCIO::TransformDirection direction = OCIO::TRANSFORM_DIR_FORWARD; OCIO::ExposureContrastOpDataRcPtr data = std::make_shared<OCIO::ExposureContrastOpData>(); data->getContrastProperty()->makeDynamic(); data->setExposure(1.2); data->setPivot(0.5); data->setLogExposureStep(0.09); data->setLogMidGray(0.7); data->getFormatMetadata().addAttribute("name", "test"); OCIO::OpRcPtrVec ops; OCIO_CHECK_NO_THROW(OCIO::CreateExposureContrastOp(ops, data, direction)); OCIO_REQUIRE_EQUAL(ops.size(), 1); OCIO_REQUIRE_ASSERT(ops[0]); OCIO::GroupTransformRcPtr group = OCIO::GroupTransform::Create(); OCIO::ConstOpRcPtr op(ops[0]); OCIO::CreateExposureContrastTransform(group, op); OCIO_REQUIRE_EQUAL(group->getNumTransforms(), 1); auto transform = group->getTransform(0); OCIO_REQUIRE_ASSERT(transform); auto ecTransform = OCIO_DYNAMIC_POINTER_CAST<OCIO::ExposureContrastTransform>(transform); OCIO_REQUIRE_ASSERT(ecTransform); const auto & metadata = ecTransform->getFormatMetadata(); OCIO_REQUIRE_EQUAL(metadata.getNumAttributes(), 1); OCIO_CHECK_EQUAL(std::string(metadata.getAttributeName(0)), "name"); OCIO_CHECK_EQUAL(std::string(metadata.getAttributeValue(0)), "test"); OCIO_CHECK_EQUAL(ecTransform->getDirection(), OCIO::TRANSFORM_DIR_FORWARD); OCIO_CHECK_EQUAL(ecTransform->getExposure(), data->getExposure()); OCIO_CHECK_EQUAL(ecTransform->isExposureDynamic(), false); OCIO_CHECK_EQUAL(ecTransform->getContrast(), data->getContrast()); OCIO_CHECK_EQUAL(ecTransform->isContrastDynamic(), true); OCIO_CHECK_EQUAL(ecTransform->getGamma(), data->getGamma()); OCIO_CHECK_EQUAL(ecTransform->isGammaDynamic(), false); OCIO_CHECK_EQUAL(ecTransform->getPivot(), data->getPivot()); OCIO_CHECK_EQUAL(ecTransform->getLogExposureStep(), data->getLogExposureStep()); OCIO_CHECK_EQUAL(ecTransform->getLogMidGray(), data->getLogMidGray()); }
24ced701369620f604d71b25379574eacf45c69e
9c56a1548ee24fa679b831bca5e796fa86dbb583
/baekjoon/14927/source.cpp
4e30206e8b88ab84ac209b3fa3af17b95f56b4da
[ "CC-BY-4.0", "CC-BY-3.0" ]
permissive
qilip/ACMStudy
1a006f759d52dc6afbb0cd4b6c2060a8bf5377d8
da7361b09a4519b3c721d54cd6df6ff00337fa27
refs/heads/master
2023-04-21T17:50:52.806789
2023-04-10T17:39:57
2023-04-10T17:39:57
124,194,483
4
0
null
null
null
null
UTF-8
C++
false
false
965
cpp
source.cpp
#include <bits/stdc++.h> using namespace std; int n; int b[22][22] = {0}; pair<int, int> xy[] = {{0, -1}, {-1, 0}, {0, 0}, {1, 0}, {0, 1}}; int test(int cnt){ for(int i=2;i<=n;i++){ for(int j=1;j<=n;j++){ if(b[i-1][j]){ cnt++; for(auto[x, y]: xy){ b[i+x][j+y] ^= 1; } } } } int ans = 1; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(b[i][j]) ans = 0; } } return ans?cnt:-1; } int main(void){ scanf("%d", &n); for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ scanf("%d", &b[i][j]); } } int ans = 9999'9999; for(int i=0;i<=(1<<n)-1;i++){ int bak[22][22] = {0}; copy(&b[0][0], &b[21][22], &bak[0][0]); int cnt = 0; for(int j=0;j<=n-1;j++){ if((i>>j)&1){ cnt++; for(auto[x, y]: xy){ b[1+x][n-j+y] ^= 1; } } } int res = test(cnt); if(res!=-1) ans = min(ans, res); copy(&bak[0][0], &bak[21][22], &b[0][0]); } if(ans==9999'9999) ans = -1; printf("%d\n", ans); return 0; }
e8176f7ea5047fe4c62e38124114723be8709804
6486e74a34ef45761eae637e7ea0701aa40244b3
/Parking/components/map/proto/created_map.pb.cc
bfa4e2bd8ec41b13d2ec79972a64429c4f76dfdb
[]
no_license
mr-d-self-driving/WorkCode
2d3f85394c704bea33c58704ea64936857bb771e
13e028a217f6f9186b1eda04992cb6c00f941d3d
refs/heads/master
2022-12-13T19:17:58.641963
2020-09-17T12:13:22
2020-09-17T12:13:22
null
0
0
null
null
null
null
UTF-8
C++
false
true
51,848
cc
created_map.pb.cc
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: map/proto/created_map.proto #include "map/proto/created_map.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // This is a temporary google only hack #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) namespace protobuf_map_2fproto_2fcreated_5fmap_2eproto { extern PROTOBUF_INTERNAL_EXPORT_protobuf_map_2fproto_2fcreated_5fmap_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_CreatedMapPoint; } // namespace protobuf_map_2fproto_2fcreated_5fmap_2eproto namespace map { class CreatedMapConfigDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CreatedMapConfig> _instance; } _CreatedMapConfig_default_instance_; class CreatedMapPointDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CreatedMapPoint> _instance; } _CreatedMapPoint_default_instance_; class CreatedMapDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CreatedMap> _instance; } _CreatedMap_default_instance_; } // namespace map namespace protobuf_map_2fproto_2fcreated_5fmap_2eproto { static void InitDefaultsCreatedMapConfig() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::map::_CreatedMapConfig_default_instance_; new (ptr) ::map::CreatedMapConfig(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::map::CreatedMapConfig::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_CreatedMapConfig = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCreatedMapConfig}, {}}; static void InitDefaultsCreatedMapPoint() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::map::_CreatedMapPoint_default_instance_; new (ptr) ::map::CreatedMapPoint(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::map::CreatedMapPoint::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_CreatedMapPoint = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCreatedMapPoint}, {}}; static void InitDefaultsCreatedMap() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::map::_CreatedMap_default_instance_; new (ptr) ::map::CreatedMap(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::map::CreatedMap::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_CreatedMap = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsCreatedMap}, { &protobuf_map_2fproto_2fcreated_5fmap_2eproto::scc_info_CreatedMapPoint.base,}}; void InitDefaults() { ::google::protobuf::internal::InitSCC(&scc_info_CreatedMapConfig.base); ::google::protobuf::internal::InitSCC(&scc_info_CreatedMapPoint.base); ::google::protobuf::internal::InitSCC(&scc_info_CreatedMap.base); } ::google::protobuf::Metadata file_level_metadata[3]; const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapConfig, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapConfig, distance_thod_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapConfig, theta_thod_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapConfig, default_lane_left_width_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapConfig, default_lane_right_width_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapConfig, default_road_left_width_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapConfig, default_road_right_width_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapConfig, default_lane_number_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapPoint, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapPoint, id_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapPoint, x_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapPoint, y_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapPoint, theta_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapPoint, lane_left_width_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapPoint, lane_right_width_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapPoint, road_left_width_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapPoint, road_right_width_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapPoint, speed_limit_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMapPoint, lane_number_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMap, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::map::CreatedMap, points_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::map::CreatedMapConfig)}, { 12, -1, sizeof(::map::CreatedMapPoint)}, { 27, -1, sizeof(::map::CreatedMap)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::map::_CreatedMapConfig_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::map::_CreatedMapPoint_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::map::_CreatedMap_default_instance_), }; void protobuf_AssignDescriptors() { AddDescriptors(); AssignDescriptors( "map/proto/created_map.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 3); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n\033map/proto/created_map.proto\022\003map\"\340\001\n\020C" "reatedMapConfig\022\025\n\rdistance_thod\030\001 \001(\001\022\022" "\n\ntheta_thod\030\002 \001(\001\022\037\n\027default_lane_left_" "width\030\003 \001(\001\022 \n\030default_lane_right_width\030" "\004 \001(\001\022\037\n\027default_road_left_width\030\005 \001(\001\022 " "\n\030default_road_right_width\030\006 \001(\001\022\033\n\023defa" "ult_lane_number\030\007 \001(\001\"\322\001\n\017CreatedMapPoin" "t\022\n\n\002id\030\001 \001(\005\022\t\n\001x\030\002 \001(\001\022\t\n\001y\030\003 \001(\001\022\r\n\005t" "heta\030\004 \001(\001\022\027\n\017lane_left_width\030\005 \001(\001\022\030\n\020l" "ane_right_width\030\006 \001(\001\022\027\n\017road_left_width" "\030\007 \001(\001\022\030\n\020road_right_width\030\010 \001(\001\022\023\n\013spee" "d_limit\030\t \001(\001\022\023\n\013lane_number\030\n \001(\001\"2\n\nCr" "eatedMap\022$\n\006points\030\001 \003(\0132\024.map.CreatedMa" "pPointb\006proto3" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 534); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "map/proto/created_map.proto", &protobuf_RegisterTypes); } void AddDescriptors() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_map_2fproto_2fcreated_5fmap_2eproto namespace map { // =================================================================== void CreatedMapConfig::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CreatedMapConfig::kDistanceThodFieldNumber; const int CreatedMapConfig::kThetaThodFieldNumber; const int CreatedMapConfig::kDefaultLaneLeftWidthFieldNumber; const int CreatedMapConfig::kDefaultLaneRightWidthFieldNumber; const int CreatedMapConfig::kDefaultRoadLeftWidthFieldNumber; const int CreatedMapConfig::kDefaultRoadRightWidthFieldNumber; const int CreatedMapConfig::kDefaultLaneNumberFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CreatedMapConfig::CreatedMapConfig() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_map_2fproto_2fcreated_5fmap_2eproto::scc_info_CreatedMapConfig.base); SharedCtor(); // @@protoc_insertion_point(constructor:map.CreatedMapConfig) } CreatedMapConfig::CreatedMapConfig(const CreatedMapConfig& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&distance_thod_, &from.distance_thod_, static_cast<size_t>(reinterpret_cast<char*>(&default_lane_number_) - reinterpret_cast<char*>(&distance_thod_)) + sizeof(default_lane_number_)); // @@protoc_insertion_point(copy_constructor:map.CreatedMapConfig) } void CreatedMapConfig::SharedCtor() { ::memset(&distance_thod_, 0, static_cast<size_t>( reinterpret_cast<char*>(&default_lane_number_) - reinterpret_cast<char*>(&distance_thod_)) + sizeof(default_lane_number_)); } CreatedMapConfig::~CreatedMapConfig() { // @@protoc_insertion_point(destructor:map.CreatedMapConfig) SharedDtor(); } void CreatedMapConfig::SharedDtor() { } void CreatedMapConfig::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* CreatedMapConfig::descriptor() { ::protobuf_map_2fproto_2fcreated_5fmap_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_map_2fproto_2fcreated_5fmap_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const CreatedMapConfig& CreatedMapConfig::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_map_2fproto_2fcreated_5fmap_2eproto::scc_info_CreatedMapConfig.base); return *internal_default_instance(); } void CreatedMapConfig::Clear() { // @@protoc_insertion_point(message_clear_start:map.CreatedMapConfig) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; ::memset(&distance_thod_, 0, static_cast<size_t>( reinterpret_cast<char*>(&default_lane_number_) - reinterpret_cast<char*>(&distance_thod_)) + sizeof(default_lane_number_)); _internal_metadata_.Clear(); } bool CreatedMapConfig::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:map.CreatedMapConfig) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // double distance_thod = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(9u /* 9 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &distance_thod_))); } else { goto handle_unusual; } break; } // double theta_thod = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &theta_thod_))); } else { goto handle_unusual; } break; } // double default_lane_left_width = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(25u /* 25 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &default_lane_left_width_))); } else { goto handle_unusual; } break; } // double default_lane_right_width = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(33u /* 33 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &default_lane_right_width_))); } else { goto handle_unusual; } break; } // double default_road_left_width = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(41u /* 41 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &default_road_left_width_))); } else { goto handle_unusual; } break; } // double default_road_right_width = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(49u /* 49 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &default_road_right_width_))); } else { goto handle_unusual; } break; } // double default_lane_number = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(57u /* 57 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &default_lane_number_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:map.CreatedMapConfig) return true; failure: // @@protoc_insertion_point(parse_failure:map.CreatedMapConfig) return false; #undef DO_ } void CreatedMapConfig::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:map.CreatedMapConfig) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // double distance_thod = 1; if (this->distance_thod() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->distance_thod(), output); } // double theta_thod = 2; if (this->theta_thod() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->theta_thod(), output); } // double default_lane_left_width = 3; if (this->default_lane_left_width() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->default_lane_left_width(), output); } // double default_lane_right_width = 4; if (this->default_lane_right_width() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(4, this->default_lane_right_width(), output); } // double default_road_left_width = 5; if (this->default_road_left_width() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(5, this->default_road_left_width(), output); } // double default_road_right_width = 6; if (this->default_road_right_width() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(6, this->default_road_right_width(), output); } // double default_lane_number = 7; if (this->default_lane_number() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(7, this->default_lane_number(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:map.CreatedMapConfig) } ::google::protobuf::uint8* CreatedMapConfig::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:map.CreatedMapConfig) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // double distance_thod = 1; if (this->distance_thod() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->distance_thod(), target); } // double theta_thod = 2; if (this->theta_thod() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->theta_thod(), target); } // double default_lane_left_width = 3; if (this->default_lane_left_width() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->default_lane_left_width(), target); } // double default_lane_right_width = 4; if (this->default_lane_right_width() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(4, this->default_lane_right_width(), target); } // double default_road_left_width = 5; if (this->default_road_left_width() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(5, this->default_road_left_width(), target); } // double default_road_right_width = 6; if (this->default_road_right_width() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(6, this->default_road_right_width(), target); } // double default_lane_number = 7; if (this->default_lane_number() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(7, this->default_lane_number(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:map.CreatedMapConfig) return target; } size_t CreatedMapConfig::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:map.CreatedMapConfig) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // double distance_thod = 1; if (this->distance_thod() != 0) { total_size += 1 + 8; } // double theta_thod = 2; if (this->theta_thod() != 0) { total_size += 1 + 8; } // double default_lane_left_width = 3; if (this->default_lane_left_width() != 0) { total_size += 1 + 8; } // double default_lane_right_width = 4; if (this->default_lane_right_width() != 0) { total_size += 1 + 8; } // double default_road_left_width = 5; if (this->default_road_left_width() != 0) { total_size += 1 + 8; } // double default_road_right_width = 6; if (this->default_road_right_width() != 0) { total_size += 1 + 8; } // double default_lane_number = 7; if (this->default_lane_number() != 0) { total_size += 1 + 8; } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CreatedMapConfig::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:map.CreatedMapConfig) GOOGLE_DCHECK_NE(&from, this); const CreatedMapConfig* source = ::google::protobuf::internal::DynamicCastToGenerated<const CreatedMapConfig>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:map.CreatedMapConfig) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:map.CreatedMapConfig) MergeFrom(*source); } } void CreatedMapConfig::MergeFrom(const CreatedMapConfig& from) { // @@protoc_insertion_point(class_specific_merge_from_start:map.CreatedMapConfig) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.distance_thod() != 0) { set_distance_thod(from.distance_thod()); } if (from.theta_thod() != 0) { set_theta_thod(from.theta_thod()); } if (from.default_lane_left_width() != 0) { set_default_lane_left_width(from.default_lane_left_width()); } if (from.default_lane_right_width() != 0) { set_default_lane_right_width(from.default_lane_right_width()); } if (from.default_road_left_width() != 0) { set_default_road_left_width(from.default_road_left_width()); } if (from.default_road_right_width() != 0) { set_default_road_right_width(from.default_road_right_width()); } if (from.default_lane_number() != 0) { set_default_lane_number(from.default_lane_number()); } } void CreatedMapConfig::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:map.CreatedMapConfig) if (&from == this) return; Clear(); MergeFrom(from); } void CreatedMapConfig::CopyFrom(const CreatedMapConfig& from) { // @@protoc_insertion_point(class_specific_copy_from_start:map.CreatedMapConfig) if (&from == this) return; Clear(); MergeFrom(from); } bool CreatedMapConfig::IsInitialized() const { return true; } void CreatedMapConfig::Swap(CreatedMapConfig* other) { if (other == this) return; InternalSwap(other); } void CreatedMapConfig::InternalSwap(CreatedMapConfig* other) { using std::swap; swap(distance_thod_, other->distance_thod_); swap(theta_thod_, other->theta_thod_); swap(default_lane_left_width_, other->default_lane_left_width_); swap(default_lane_right_width_, other->default_lane_right_width_); swap(default_road_left_width_, other->default_road_left_width_); swap(default_road_right_width_, other->default_road_right_width_); swap(default_lane_number_, other->default_lane_number_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata CreatedMapConfig::GetMetadata() const { protobuf_map_2fproto_2fcreated_5fmap_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_map_2fproto_2fcreated_5fmap_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void CreatedMapPoint::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CreatedMapPoint::kIdFieldNumber; const int CreatedMapPoint::kXFieldNumber; const int CreatedMapPoint::kYFieldNumber; const int CreatedMapPoint::kThetaFieldNumber; const int CreatedMapPoint::kLaneLeftWidthFieldNumber; const int CreatedMapPoint::kLaneRightWidthFieldNumber; const int CreatedMapPoint::kRoadLeftWidthFieldNumber; const int CreatedMapPoint::kRoadRightWidthFieldNumber; const int CreatedMapPoint::kSpeedLimitFieldNumber; const int CreatedMapPoint::kLaneNumberFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CreatedMapPoint::CreatedMapPoint() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_map_2fproto_2fcreated_5fmap_2eproto::scc_info_CreatedMapPoint.base); SharedCtor(); // @@protoc_insertion_point(constructor:map.CreatedMapPoint) } CreatedMapPoint::CreatedMapPoint(const CreatedMapPoint& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&x_, &from.x_, static_cast<size_t>(reinterpret_cast<char*>(&id_) - reinterpret_cast<char*>(&x_)) + sizeof(id_)); // @@protoc_insertion_point(copy_constructor:map.CreatedMapPoint) } void CreatedMapPoint::SharedCtor() { ::memset(&x_, 0, static_cast<size_t>( reinterpret_cast<char*>(&id_) - reinterpret_cast<char*>(&x_)) + sizeof(id_)); } CreatedMapPoint::~CreatedMapPoint() { // @@protoc_insertion_point(destructor:map.CreatedMapPoint) SharedDtor(); } void CreatedMapPoint::SharedDtor() { } void CreatedMapPoint::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* CreatedMapPoint::descriptor() { ::protobuf_map_2fproto_2fcreated_5fmap_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_map_2fproto_2fcreated_5fmap_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const CreatedMapPoint& CreatedMapPoint::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_map_2fproto_2fcreated_5fmap_2eproto::scc_info_CreatedMapPoint.base); return *internal_default_instance(); } void CreatedMapPoint::Clear() { // @@protoc_insertion_point(message_clear_start:map.CreatedMapPoint) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; ::memset(&x_, 0, static_cast<size_t>( reinterpret_cast<char*>(&id_) - reinterpret_cast<char*>(&x_)) + sizeof(id_)); _internal_metadata_.Clear(); } bool CreatedMapPoint::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:map.CreatedMapPoint) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int32 id = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &id_))); } else { goto handle_unusual; } break; } // double x = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(17u /* 17 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &x_))); } else { goto handle_unusual; } break; } // double y = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(25u /* 25 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &y_))); } else { goto handle_unusual; } break; } // double theta = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(33u /* 33 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &theta_))); } else { goto handle_unusual; } break; } // double lane_left_width = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(41u /* 41 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &lane_left_width_))); } else { goto handle_unusual; } break; } // double lane_right_width = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(49u /* 49 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &lane_right_width_))); } else { goto handle_unusual; } break; } // double road_left_width = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(57u /* 57 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &road_left_width_))); } else { goto handle_unusual; } break; } // double road_right_width = 8; case 8: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(65u /* 65 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &road_right_width_))); } else { goto handle_unusual; } break; } // double speed_limit = 9; case 9: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(73u /* 73 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &speed_limit_))); } else { goto handle_unusual; } break; } // double lane_number = 10; case 10: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(81u /* 81 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &lane_number_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:map.CreatedMapPoint) return true; failure: // @@protoc_insertion_point(parse_failure:map.CreatedMapPoint) return false; #undef DO_ } void CreatedMapPoint::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:map.CreatedMapPoint) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 id = 1; if (this->id() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->id(), output); } // double x = 2; if (this->x() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->x(), output); } // double y = 3; if (this->y() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->y(), output); } // double theta = 4; if (this->theta() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(4, this->theta(), output); } // double lane_left_width = 5; if (this->lane_left_width() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(5, this->lane_left_width(), output); } // double lane_right_width = 6; if (this->lane_right_width() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(6, this->lane_right_width(), output); } // double road_left_width = 7; if (this->road_left_width() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(7, this->road_left_width(), output); } // double road_right_width = 8; if (this->road_right_width() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(8, this->road_right_width(), output); } // double speed_limit = 9; if (this->speed_limit() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(9, this->speed_limit(), output); } // double lane_number = 10; if (this->lane_number() != 0) { ::google::protobuf::internal::WireFormatLite::WriteDouble(10, this->lane_number(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:map.CreatedMapPoint) } ::google::protobuf::uint8* CreatedMapPoint::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:map.CreatedMapPoint) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 id = 1; if (this->id() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->id(), target); } // double x = 2; if (this->x() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->x(), target); } // double y = 3; if (this->y() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->y(), target); } // double theta = 4; if (this->theta() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(4, this->theta(), target); } // double lane_left_width = 5; if (this->lane_left_width() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(5, this->lane_left_width(), target); } // double lane_right_width = 6; if (this->lane_right_width() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(6, this->lane_right_width(), target); } // double road_left_width = 7; if (this->road_left_width() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(7, this->road_left_width(), target); } // double road_right_width = 8; if (this->road_right_width() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(8, this->road_right_width(), target); } // double speed_limit = 9; if (this->speed_limit() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(9, this->speed_limit(), target); } // double lane_number = 10; if (this->lane_number() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(10, this->lane_number(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:map.CreatedMapPoint) return target; } size_t CreatedMapPoint::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:map.CreatedMapPoint) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // double x = 2; if (this->x() != 0) { total_size += 1 + 8; } // double y = 3; if (this->y() != 0) { total_size += 1 + 8; } // double theta = 4; if (this->theta() != 0) { total_size += 1 + 8; } // double lane_left_width = 5; if (this->lane_left_width() != 0) { total_size += 1 + 8; } // double lane_right_width = 6; if (this->lane_right_width() != 0) { total_size += 1 + 8; } // double road_left_width = 7; if (this->road_left_width() != 0) { total_size += 1 + 8; } // double road_right_width = 8; if (this->road_right_width() != 0) { total_size += 1 + 8; } // double speed_limit = 9; if (this->speed_limit() != 0) { total_size += 1 + 8; } // double lane_number = 10; if (this->lane_number() != 0) { total_size += 1 + 8; } // int32 id = 1; if (this->id() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->id()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CreatedMapPoint::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:map.CreatedMapPoint) GOOGLE_DCHECK_NE(&from, this); const CreatedMapPoint* source = ::google::protobuf::internal::DynamicCastToGenerated<const CreatedMapPoint>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:map.CreatedMapPoint) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:map.CreatedMapPoint) MergeFrom(*source); } } void CreatedMapPoint::MergeFrom(const CreatedMapPoint& from) { // @@protoc_insertion_point(class_specific_merge_from_start:map.CreatedMapPoint) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.x() != 0) { set_x(from.x()); } if (from.y() != 0) { set_y(from.y()); } if (from.theta() != 0) { set_theta(from.theta()); } if (from.lane_left_width() != 0) { set_lane_left_width(from.lane_left_width()); } if (from.lane_right_width() != 0) { set_lane_right_width(from.lane_right_width()); } if (from.road_left_width() != 0) { set_road_left_width(from.road_left_width()); } if (from.road_right_width() != 0) { set_road_right_width(from.road_right_width()); } if (from.speed_limit() != 0) { set_speed_limit(from.speed_limit()); } if (from.lane_number() != 0) { set_lane_number(from.lane_number()); } if (from.id() != 0) { set_id(from.id()); } } void CreatedMapPoint::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:map.CreatedMapPoint) if (&from == this) return; Clear(); MergeFrom(from); } void CreatedMapPoint::CopyFrom(const CreatedMapPoint& from) { // @@protoc_insertion_point(class_specific_copy_from_start:map.CreatedMapPoint) if (&from == this) return; Clear(); MergeFrom(from); } bool CreatedMapPoint::IsInitialized() const { return true; } void CreatedMapPoint::Swap(CreatedMapPoint* other) { if (other == this) return; InternalSwap(other); } void CreatedMapPoint::InternalSwap(CreatedMapPoint* other) { using std::swap; swap(x_, other->x_); swap(y_, other->y_); swap(theta_, other->theta_); swap(lane_left_width_, other->lane_left_width_); swap(lane_right_width_, other->lane_right_width_); swap(road_left_width_, other->road_left_width_); swap(road_right_width_, other->road_right_width_); swap(speed_limit_, other->speed_limit_); swap(lane_number_, other->lane_number_); swap(id_, other->id_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata CreatedMapPoint::GetMetadata() const { protobuf_map_2fproto_2fcreated_5fmap_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_map_2fproto_2fcreated_5fmap_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void CreatedMap::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CreatedMap::kPointsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CreatedMap::CreatedMap() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_map_2fproto_2fcreated_5fmap_2eproto::scc_info_CreatedMap.base); SharedCtor(); // @@protoc_insertion_point(constructor:map.CreatedMap) } CreatedMap::CreatedMap(const CreatedMap& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), points_(from.points_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:map.CreatedMap) } void CreatedMap::SharedCtor() { } CreatedMap::~CreatedMap() { // @@protoc_insertion_point(destructor:map.CreatedMap) SharedDtor(); } void CreatedMap::SharedDtor() { } void CreatedMap::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* CreatedMap::descriptor() { ::protobuf_map_2fproto_2fcreated_5fmap_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_map_2fproto_2fcreated_5fmap_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const CreatedMap& CreatedMap::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_map_2fproto_2fcreated_5fmap_2eproto::scc_info_CreatedMap.base); return *internal_default_instance(); } void CreatedMap::Clear() { // @@protoc_insertion_point(message_clear_start:map.CreatedMap) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; points_.Clear(); _internal_metadata_.Clear(); } bool CreatedMap::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:map.CreatedMap) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .map.CreatedMapPoint points = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_points())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:map.CreatedMap) return true; failure: // @@protoc_insertion_point(parse_failure:map.CreatedMap) return false; #undef DO_ } void CreatedMap::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:map.CreatedMap) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .map.CreatedMapPoint points = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->points_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->points(static_cast<int>(i)), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:map.CreatedMap) } ::google::protobuf::uint8* CreatedMap::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:map.CreatedMap) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .map.CreatedMapPoint points = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->points_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, this->points(static_cast<int>(i)), deterministic, target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:map.CreatedMap) return target; } size_t CreatedMap::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:map.CreatedMap) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated .map.CreatedMapPoint points = 1; { unsigned int count = static_cast<unsigned int>(this->points_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->points(static_cast<int>(i))); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CreatedMap::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:map.CreatedMap) GOOGLE_DCHECK_NE(&from, this); const CreatedMap* source = ::google::protobuf::internal::DynamicCastToGenerated<const CreatedMap>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:map.CreatedMap) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:map.CreatedMap) MergeFrom(*source); } } void CreatedMap::MergeFrom(const CreatedMap& from) { // @@protoc_insertion_point(class_specific_merge_from_start:map.CreatedMap) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; points_.MergeFrom(from.points_); } void CreatedMap::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:map.CreatedMap) if (&from == this) return; Clear(); MergeFrom(from); } void CreatedMap::CopyFrom(const CreatedMap& from) { // @@protoc_insertion_point(class_specific_copy_from_start:map.CreatedMap) if (&from == this) return; Clear(); MergeFrom(from); } bool CreatedMap::IsInitialized() const { return true; } void CreatedMap::Swap(CreatedMap* other) { if (other == this) return; InternalSwap(other); } void CreatedMap::InternalSwap(CreatedMap* other) { using std::swap; CastToBase(&points_)->InternalSwap(CastToBase(&other->points_)); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata CreatedMap::GetMetadata() const { protobuf_map_2fproto_2fcreated_5fmap_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_map_2fproto_2fcreated_5fmap_2eproto::file_level_metadata[kIndexInFileMessages]; } // @@protoc_insertion_point(namespace_scope) } // namespace map namespace google { namespace protobuf { template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::map::CreatedMapConfig* Arena::CreateMaybeMessage< ::map::CreatedMapConfig >(Arena* arena) { return Arena::CreateInternal< ::map::CreatedMapConfig >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::map::CreatedMapPoint* Arena::CreateMaybeMessage< ::map::CreatedMapPoint >(Arena* arena) { return Arena::CreateInternal< ::map::CreatedMapPoint >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::map::CreatedMap* Arena::CreateMaybeMessage< ::map::CreatedMap >(Arena* arena) { return Arena::CreateInternal< ::map::CreatedMap >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope)
c29d0cf76c41690c8f51ab08ce176b30b5f019c6
f4cd5dfe8ededefc161442ae2fe4e9ea9db53adf
/Nspr/Src/Net/StatisticsConnection.cpp
63de38c0f12ce03a92c39cda3a85c2587e4700f4
[]
no_license
WillWellWill/nspr-psdinfo
e7079cedcf30ee8f57b44c9698a39db5b12dfc9d
ba0aed51b24c117847827eb90a18950e440ee959
refs/heads/master
2021-01-23T06:05:27.746544
2017-03-30T08:51:14
2017-03-30T08:51:14
86,335,501
0
0
null
null
null
null
UTF-8
C++
false
false
1,496
cpp
StatisticsConnection.cpp
#include "Nspr.h" #include "StatisticsConnection.h" namespace nspr { u_char StatisticsConnection::m_statistics[m_defaultMaxStatisticsLen]; int StatisticsConnection::m_statisticsLen = 0; StatisticsConnection::StatisticsConnection(ngx_connection_t *c) : MsgConnection(c) { NsprInfo("statistics connection created"); TimerStart(); } StatisticsConnection::~StatisticsConnection() { NsprInfo("statistics connection destroyed"); ngx_del_timer(&m_timer); } int StatisticsConnection::OnRecv(const u_char *msg, size_t len) { if (len < 4) { return NSPR_AGAIN; } uint32_t const msgLen = *(uint32_t *)msg; if (len < msgLen) { return NSPR_AGAIN; } int const dataLen = msgLen - 4; assert(m_defaultMaxStatisticsLen > dataLen); ngx_memcpy(m_statistics, msg + 4, dataLen); m_statistics[dataLen] = 0; m_statisticsLen = dataLen; return len - msgLen; } void StatisticsConnection::TimerStart() { ngx_memzero(&m_timer, sizeof(m_timer)); m_timer.handler = timerRunFunc; m_timer.log = ngx_cycle->log; m_timer.data = this; ngx_add_timer(&m_timer, m_defaultStatisticsGap); } void StatisticsConnection::RequestStatistics() { const u_char *request = (const u_char *)"hello"; Send(request, 5); ngx_add_timer(&m_timer, m_defaultStatisticsGap); } void timerRunFunc(ngx_event_t *ev) { StatisticsConnection *sc = (StatisticsConnection *)ev->data; sc->RequestStatistics(); } } // namespace nspr
24a2e45216cd0e3453a58c34acf21cef2a02025e
267194360fe91f3243ffd946ad92c7a5d84f974f
/korpo2/GPS_Jak_dojade .cpp
1bd00cba2ad33c94c5834d5a4340b720c898a3b7
[]
no_license
damianpuci/ProjektIO
ef0286f34c3ede784511cb8ac2e91fee52d6a4f3
2293e7c575936dd6205a14103fc546f892d4a34b
refs/heads/master
2020-05-29T11:04:14.244452
2016-01-14T00:26:38
2016-01-14T00:26:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
170
cpp
GPS_Jak_dojade .cpp
#include "GPS_Jak_dojade .h" void GPS_Jak_dojade_::pokaz_zadnie_na_mapie() { // TODO - implement GPS_Jak_dojade ::pokaz zadnie na mapie throw "Not yet implemented"; }
864bb05adaa83f7ece43b9febba9921b27e0cb14
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5670465267826688_1/C++/ivancastel94/3.cpp
5fdf197b56c2cc16c35bedb76d2d906d9f8dec30
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,854
cpp
3.cpp
#include<bits/stdc++.h> using namespace std; int main(){ freopen("c.in","r",stdin); freopen("c.out","w",stdout); int i,cases,c1; long long pi,pk,l,x; string s; int cuaternios[8][8] = { {0,1,2,3,4,5,6,7}, {1,4,3,6,5,0,7,2}, {2,7,4,1,6,3,0,5}, {3,2,5,4,7,6,1,0}, {4,5,6,7,0,1,2,3}, {5,0,7,2,1,4,3,6}, {6,3,0,5,2,7,4,1}, {7,6,1,0,3,2,5,4}, }; cin>>cases; for(c1=1;c1<=cases;c1++){ cin>>l>>x; int ade[4*l],atr[4*l]; cin>>s; pi=-1; if(s[0]=='i'){ pi=0LL; ade[0]=1; } if(s[0]=='j')ade[0]=2; if(s[0]=='k')ade[0]=3; for(i=1;i<4*l;i++){ if(s[i%l]=='i')ade[i]=cuaternios[ade[i-1]][1]; if(s[i%l]=='j')ade[i]=cuaternios[ade[i-1]][2]; if(s[i%l]=='k')ade[i]=cuaternios[ade[i-1]][3]; if(ade[i]==1&&pi==-1)pi=i; } cout<<"Case #"<<c1<<": "; if(ade[l-1]==0){ cout<<"NO"<<endl; continue; } if((ade[l-1]==4)&&(x%2==0)){ cout<<"NO"<<endl; continue; } if((ade[l-1]%4!=0)&&(x%4!=2)){ cout<<"NO"<<endl; continue; } pk=-1; if(s[l-1]=='i')atr[4*l-1]=1; if(s[l-1]=='j')atr[4*l-1]=2; if(s[l-1]=='k'){ pk=0LL; atr[4*l-1]=3; } for(i=4*l-2;i>=0;i--){ if(s[i%l]=='i')atr[i]=cuaternios[1][atr[i+1]]; if(s[i%l]=='j')atr[i]=cuaternios[2][atr[i+1]]; if(s[i%l]=='k')atr[i]=cuaternios[3][atr[i+1]]; if(atr[i]==3&&pk==-1)pk=4LL*l-1-i; } if((pi!=-1)&&(pk!=-1)&&(pi+pk)<l*x){ cout<<"YES"<<endl; } else{ cout<<"NO"<<endl; } } }
465f472e3d7f2ab556a0e47f5ebf6240060f713e
e49460d8d70b7179e6b1f5ea27a5129dfe51b895
/Ejercicio 6.cpp
56fde47498be871a209688521bf580677be14682
[]
no_license
carlos-shimabukuro/progra1-carlos_shimabukuro-simulacro--hoja1--estructuras-selectivas
198bd9931c9cf31a65928793cb2376f822d9363f
4e22e358c3d8c955a042e0d053a5e997ac0d39e4
refs/heads/master
2020-05-16T01:08:41.170484
2019-04-22T00:26:17
2019-04-22T00:26:17
182,595,661
0
0
null
null
null
null
UTF-8
C++
false
false
922
cpp
Ejercicio 6.cpp
// ConsoleApplication61.cpp : Este archivo contiene la función "main". La ejecución del programa comienza y termina ahí. // #include "pch.h" #include <iostream> #include <math.h> using namespace std; /* test */ int main() { // variables int a, b, c, d, x; double raizA, raizB; // datos de entrada cout << "Ingrese valor de A, B, C : " << endl; cin >> a >> b >> c; cout << "Ingrese valor a evaluar : " << endl; cin >> d; //logica raizA = (-1 * b + sqrt(b * b - (4 * a * c ))) / (2 * a); raizB = (-1 * b + -1 * sqrt(b * b - (4 * a * c))) / (2 * a); x = a * pow(d, 2) + (b * d) + (c); //datos de salida cout << "(" << a << ")" << d << "^2 + " << b << "(" << d << ")" << " + " << c << " = " << d << endl; cout << endl; cout << "Primero raiz : " << raizA * 1.00 << endl; cout << "Segunda raiz : " << raizB * 1.00 << endl; system("pause"); return 0; }
e6068a0e50746559211e54b484df5f18fbcfe333
f547772702fea7a806f2a8d9bb55ab1b20f048af
/src/geo_pos.cpp
91602551c39f3acffe879f7790b7656f00459387
[ "BSD-3-Clause" ]
permissive
kit-algo/InertialFlowCutter
862129d23aef69118135d63113c37858e79e7874
f3730a164dfd2731914a51a5be791a22e8265f72
refs/heads/master
2023-05-04T17:57:17.586530
2023-04-18T17:21:30
2023-04-18T17:21:30
194,085,091
16
11
BSD-3-Clause
2022-06-02T13:25:08
2019-06-27T11:45:26
C++
UTF-8
C++
false
false
5,502
cpp
geo_pos.cpp
#include "geo_pos.h" #include "io_helper.h" #include "tiny_id_func.h" #include "union_find.h" #include <string> #include <sstream> #include <cmath> std::vector<GeoPos> order_geo_positions_along_line(const std::vector<GeoPos>&pos){ int point_count = pos.size(); if(point_count <= 1) return pos; struct P{ int p, q; double dist; }; std::vector<P>candidate_segments; for(int i=0; i<point_count; ++i) for(int j=i+1; j<point_count; ++j) candidate_segments.push_back({i, j, geo_dist(pos[i], pos[j])}); std::sort(candidate_segments.begin(), candidate_segments.end(), [](P l, P r){return l.dist < r.dist;}); struct N{ N():u(-1), v(-1){} int u, v; bool is_full()const{return v != -1;} void add(int x){assert(!is_full()); if(u == -1) u = x; else v = x;} int count()const{ if(u==-1) return 0; if(v==-1) return 1; return 2; } int other(int x)const{if(x == u) return v; else return u;} }; std::vector<N>neighbors(point_count); UnionFind are_connected(point_count); int segment_count = 0; for(auto s:candidate_segments){ if(!neighbors[s.p].is_full() && !neighbors[s.q].is_full() && !are_connected.in_same(s.p, s.q)){ neighbors[s.p].add(s.q); neighbors[s.q].add(s.p); are_connected.unite(s.q, s.p); ++segment_count; if(segment_count == point_count - 1) break; } } int x = -1; for(int i=0; i<point_count; ++i) if(neighbors[i].count() == 1){ x = i; break; } assert(x != -1); int y = neighbors[x].u; std::vector<GeoPos>new_pos(point_count); int new_id = 0; for(;;){ new_pos[new_id++] = pos[x]; if(y == -1) break; int z = neighbors[y].other(x); x = y; y = z; } return new_pos; // NVRO } constexpr int dimacs_scale = 1000000; static void save_binary_geo_pos_impl(std::ostream&out, const ArrayIDFunc<GeoPos>&geo_pos){ int s = geo_pos.preimage_count(); out .write((const char*)&s, sizeof(s)) .write((const char*)geo_pos.begin(), s*sizeof(geo_pos[0])); } static void save_dimacs_geo_pos_impl(std::ostream&out, const ArrayIDFunc<GeoPos>&geo_pos){ out << "p aux sp co "<< geo_pos.preimage_count() << '\n'; for(int i=0; i<geo_pos.preimage_count(); ++i) out << "v " << (i+1) << ' ' << (int)std::round(dimacs_scale*geo_pos(i).lon) << ' ' << (int)std::round(dimacs_scale*geo_pos(i).lat) << '\n'; } static ArrayIDFunc<GeoPos> load_binary_geo_pos_impl(std::istream&in, long long size){ int s; if(!in.read((char*)&s, sizeof(s))) throw std::runtime_error("Could not read number of geo coordinates"); if(size != static_cast<long long>(sizeof(GeoPos))*s + static_cast<long long>(sizeof(s))) throw std::runtime_error("Binary GeoPos file has an invalid size"); ArrayIDFunc<GeoPos>f(s); if(!in.read((char*)f.begin(), sizeof(GeoPos)*s)) throw std::runtime_error("Could not read GeoPos data"); return f; // NVRO } static ArrayIDFunc<GeoPos> load_dimacs_geo_pos_impl(std::istream&in){ ArrayIDFunc<GeoPos>geo_pos; BitIDFunc seen; bool seen_header = false; int seen_count = 0; std::string line; int line_num = 0; while(std::getline(in, line)){ ++line_num; if(line.empty() || line[0] == 'c') continue; if(!seen_header){ std::istringstream l(line); std::string b; if(!(l>>b) || b != "p" || !(l>>b) || b != "aux" || !(l>>b) || b != "sp" || !(l>>b) || b != "co") throw std::runtime_error("Header broken in line "+std::to_string(line_num)); int s; if(!(l>>s)) throw std::runtime_error("Header missing size"); if(l >> b) throw std::runtime_error("The header in line "+std::to_string(line_num)+" contains extra charachters at the end of the line"); geo_pos = ArrayIDFunc<GeoPos>(s); seen = BitIDFunc(s); seen.fill(false); seen_header = true; }else{ std::istringstream l(line); std::string v; if(!(l>>v) || v != "v") throw std::runtime_error("Line "+std::to_string(line_num)+" is broken"); long long node, lon, lat; if(!(l >> node >> lon >> lat)) throw std::runtime_error("Could not read the data in line "+std::to_string(line_num)); if(l >> v) throw std::runtime_error("Line "+std::to_string(line_num)+" contains extra charachters at the end of the line"); --node; if(seen(node)) throw std::runtime_error("Node "+std::to_string(node)+" has a second pair of coordinates in line "+std::to_string(line_num)); seen.set(node, true); ++seen_count; geo_pos[node].lon = static_cast<double>(lon) / dimacs_scale; geo_pos[node].lat = static_cast<double>(lat) / dimacs_scale; } } if(!seen_header) throw std::runtime_error("File is missing header"); if(seen_count != geo_pos.preimage_count()) throw std::runtime_error("Not every node has a coordinate"); return geo_pos; // NVRO } ArrayIDFunc<GeoPos>load_binary_geo_pos(const std::string&file_name){ return load_binary_file(file_name, load_binary_geo_pos_impl); } void save_binary_geo_pos(const std::string&file_name, const ArrayIDFunc<GeoPos>&geo_pos){ save_binary_file(file_name, save_binary_geo_pos_impl, geo_pos); } void save_dimacs_geo_pos(const std::string&file_name, const ArrayIDFunc<GeoPos>&geo_pos){ save_text_file(file_name, save_dimacs_geo_pos_impl, geo_pos); } ArrayIDFunc<GeoPos>uncached_load_dimacs_geo_pos(const std::string&file_name){ return load_uncached_text_file(file_name, load_dimacs_geo_pos_impl); } ArrayIDFunc<GeoPos>load_dimacs_geo_pos(const std::string&file_name){ return load_cached_text_file(file_name, "dimacs_coord", load_dimacs_geo_pos_impl, load_binary_geo_pos_impl, save_binary_geo_pos_impl); }
af4f898e6f5242ed961e002a7335eb6188afe7e4
d27caec2706796684d22666c7b7bd44439a2337b
/Circle.h
cf0f02c8310a28ec94484c9c590379d8f104fc2a
[]
no_license
gallium-arsenide/messageProcessor
d22ceb10443d0f3eb04c1289684588870a9cb630
010ce3d64cc6aadbb4eb30e3bd665bcbdcce76f6
refs/heads/master
2022-01-19T17:11:16.467975
2019-07-21T00:12:44
2019-07-21T00:12:44
197,992,883
0
0
null
null
null
null
UTF-8
C++
false
false
129
h
Circle.h
#pragma once #include "ProcessableMessage.h" class Circle : public ProcessableMessage<Circle> { public: double radius; };
8d657cd4e6cc3b6417d3d4acce3ae92b404f5bd4
69b1f61d5a7f3264ed8157504816ffe28333cf7a
/HCI/HW4/src/search.h
890c4ff4cd35418909d1a453422153601053f7fd
[]
no_license
bheads/papers
70ae7ba4dd37d9e575bb99dfc07779155ed8a4f3
713086b711f6efdb79aacd4a0c6da3b7c327bbe7
refs/heads/master
2020-12-24T17:25:55.848217
2012-01-29T21:56:16
2012-01-29T21:56:16
2,048,243
0
0
null
null
null
null
UTF-8
C++
false
false
1,622
h
search.h
/////////////////////////////////////////////////////////////////////////// // C++ code generated with wxFormBuilder (version Dec 21 2009) // http://www.wxformbuilder.org/ // // PLEASE DO "NOT" EDIT THIS FILE! /////////////////////////////////////////////////////////////////////////// #ifndef __search__ #define __search__ #include <wx/string.h> #include <wx/stattext.h> #include <wx/gdicmn.h> #include <wx/font.h> #include <wx/colour.h> #include <wx/settings.h> #include <wx/textctrl.h> #include <wx/combobox.h> #include <wx/bitmap.h> #include <wx/image.h> #include <wx/icon.h> #include <wx/bmpbuttn.h> #include <wx/button.h> #include <wx/sizer.h> #include <wx/grid.h> #include <wx/scrolwin.h> #include <wx/dialog.h> /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /// Class MyDialog1 /////////////////////////////////////////////////////////////////////////////// class MyDialog1 : public wxDialog { private: protected: wxStaticText* m_staticText1; wxTextCtrl* m_textCtrl1; wxComboBox* m_comboBox1; wxBitmapButton* m_bpButton1; wxScrolledWindow* m_scrolledWindow1; wxGrid* m_grid1; // Virtual event handlers, overide them in your derived class virtual void Event_OnClose( wxCloseEvent& event ) { event.Skip(); } public: MyDialog1( wxWindow* parent, wxWindowID id = wxID_ANY, const wxString& title = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxDEFAULT_DIALOG_STYLE ); ~MyDialog1(); }; #endif //__search__
b6f081c976e32a594484d9d6bfcec99b1e9448cc
7ff1f31385f3ad711ebedc471fbc4590be96e178
/solutions/AtCoder/abc117/C.cpp
f82a8617a28f1ee1346bff21dc05a069608bfbc7
[ "Unlicense" ]
permissive
yumeno-ukihashi/competitive-programming
6bf303daa6ea0edfc333731ed8295802f0136978
5cc3a7938b62133d8dc71a179cb11dfe985315d3
refs/heads/master
2020-05-19T06:53:53.650508
2019-06-13T03:00:44
2019-06-13T03:00:44
184,885,681
0
0
null
null
null
null
UTF-8
C++
false
false
504
cpp
C.cpp
#include<bits/stdc++.h> #define REP(x,y,z) for(int x=y;x<=z;x++) #define MSET(x,y) memset(x,y,sizeof(x)) #define M 100005 using namespace std; int n,m,in[M]; int main() { while (~scanf("%d %d", &n, &m)) { REP(i,1,m) scanf("%d", &in[i]); sort(in+1, in+m+1); REP(i,1,m-1) in[i] = in[i+1]-in[i]; sort(in+1, in+m); if (n>=m) { puts("0"); } else { printf("%lld\n", accumulate(in+1, in+m-n+1, 0LL)); } } return 0; }
d68d83d9b4e752f3acff2e2328734a9f9f10304e
0c46b58f1154eb9f6c13b855e02172a93ef7f411
/twoclasses.cpp
fa513e476387bfea8ed78f88cb22133697ef5dc8
[]
no_license
Anu00parajuli/Miniprojects-on-Object-Oriented-Programming
b41dbb4917a8f2f376d95605be2711489f07c6a1
9b7873050f236bc917b6a2341219cb6152b3bb1e
refs/heads/master
2020-06-29T07:56:06.586527
2019-10-21T15:55:20
2019-10-21T15:55:20
200,479,598
0
0
null
null
null
null
UTF-8
C++
false
false
661
cpp
twoclasses.cpp
#include<iostream> #include<math.h> using namespace std; class XYZ; class ABC{ int num1; public: void fun1() { cout<<"Enter first number"<<endl; cin>>num1; } friend void max(ABC obj1,XYZ obj2); }; class XYZ{ int num2; public: void fun2() { cout<<"Enter second number"<<endl; cin>>num2; } friend void max(ABC obj1,XYZ obj2); }; void max(ABC obj1,XYZ obj2) { if(obj1.num1>obj2.num2) { cout<<"Greatest is "<<obj1.num1; } else { cout<<"Greatest is "<<obj2.num2; } } int main() { ABC obj1; XYZ obj2; obj1.fun1(); obj2.fun2(); max(obj1,obj2); return 0; }
c4f5a83020507dd8a4680536b3f9cd4016fe89b8
96cfaaa771c2d83fc0729d8c65c4d4707235531a
/EgammaAnalysis/EgammaEfficiencyAlgos/src/GeorgiosTagProbeAlgo.cc
90e930889439c96124be542b69cdfb0f381d6257
[]
no_license
khotilov/cmssw
a22a160023c7ce0e4d59d15ef1f1532d7227a586
7636f72278ee0796d0203ac113b492b39da33528
refs/heads/master
2021-01-15T18:51:30.061124
2013-04-20T17:18:07
2013-04-20T17:18:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,440
cc
GeorgiosTagProbeAlgo.cc
#include "EgammaAnalysis/EgammaEfficiencyAlgos/interface/GeorgiosTagProbeAlgo.h" // framework includes #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DataFormats/HLTReco/interface/HLTFilterObject.h" // root includes #include "Math/GenVector/VectorUtil.h" void GeorgiosTagProbeAlgo::initialise(const edm::ParameterSet &params) { std::cout << "GeorgiosTagProbeAlgo::initialise" << std::endl; tagProducer_ = params.getParameter<edm::InputTag>("tagProducer"); probeProducer_ = params.getParameter<edm::InputTag>("probeProducer"); massCutMin_ = params.getParameter<double>("massCutMin"); massCutMax_ = params.getParameter<double>("massCutMax"); requireOS_ = params.getParameter<bool>("requireOS"); deltaPVCut_ = params.getParameter<double>("deltaPVCut"); requireTagTrigger_ = params.getParameter<bool>("requireTagTrigger"); triggerProducer_ = params.getParameter<edm::InputTag>("triggerProducer"); std::cout << "GeorgiosTagProbeAlgo::initialise done" << std::endl; } void GeorgiosTagProbeAlgo::run(const edm::Event &event, EgEff::TagProbeAssociationCollection &tagProbeCol) { // Get input collections edm::Handle<EgEff::EmObjectCollection> tagHandle; edm::Handle<EgEff::EmObjectCollection> probeHandle; const EgEff::EmObjectCollection *tagCollection = 0; const EgEff::EmObjectCollection *probeCollection = 0; // for the trigger edm::Handle<reco::HLTFilterObjectWithRefs> filterObjHandle; const reco::HLTFilterObjectWithRefs *filterObj = 0; if (requireTagTrigger_) { edm::Handle<reco::HLTFilterObjectWithRefs> filterObjHandle; event.getByLabel(triggerProducer_, filterObjHandle); filterObj = filterObjHandle.product(); } try { event.getByLabel(tagProducer_, tagHandle); tagCollection = tagHandle.product(); } catch(cms::Exception &ex) { edm::LogError("GeorgiosTagProbeAlgo") << "Error! Can't get collection " << tagProducer_; throw ex; } try { event.getByLabel(probeProducer_, probeHandle); probeCollection = probeHandle.product(); } catch(cms::Exception &ex) { edm::LogError("GeorgiosTagProbeAlgo") << "Error! Can't get collection " << probeProducer_; throw ex; } // Iterate over all combinations of tags + probes, identifying candidates for(unsigned int i = 0; i < tagCollection->size(); ++i) { // Get tag object EDM ref const EgEff::EmObjectRef tag = edm::Ref<EgEff::EmObjectCollection>(tagHandle, i); // if needed check if tag passed the trigger bool tagMatchHLT = true; if (requireTagTrigger_) { tagMatchHLT = false; unsigned int k = 0; while((k < filterObj->size()) && !tagMatchHLT) { tagMatchHLT = triggerPass(filterObj->at(k), tag); k++; } } if (tagMatchHLT) { for(unsigned int j = 0; j < probeCollection->size(); ++j) { // Get probe object EDM ref const EgEff::EmObjectRef probe = edm::Ref<EgEff::EmObjectCollection>(probeHandle, j); bool goodCombination = true; // compute tag-probe invariant mass double invMass = ROOT::Math::VectorUtil::InvariantMass(tag->p4(), probe->p4()); if ((invMass < massCutMin_) || (invMass > massCutMax_)) goodCombination = false; // compute tag-probe delta z vertex double deltaPV = 0; if (tag->hasTrack() && probe->hasTrack()) { deltaPV = fabs(tag->genericTrack()->vz() - probe->genericTrack()->vz()); } if (deltaPV > deltaPVCut_) goodCombination = false; // compute product of sign of tag-probe int signProduct = tag->charge() * probe->charge(); if (requireOS_) { if (signProduct > 0) goodCombination = false; } // insert the tag-probe pair if they are good if(goodCombination) { tagProbeCol.insert(tag, probe); } } // end loop on probes } // end if tag passed HLT (or wasn't reqired to) } // end loop on tags } bool GeorgiosTagProbeAlgo::triggerPass(const reco::Candidate &trigCand, EgEff::EmObjectRef tagCand) { double dEta = trigCand.eta() - tagCand->eta(); double dPhi = trigCand.phi() - tagCand->phi(); double dRVal = sqrt(dEta*dEta + dPhi*dPhi); return (dRVal < 0.2); }
dc4737c9fdadf75a4449d0e7e71f541100736be0
a4adda6fde2f71f1c0fa230f90fc0faba0eee6dc
/tutorial_004_STL_algorithms/smooth_algo.hh
5843f8a45459d841651d042a0cff9ae6e3693242
[]
no_license
Nitta-K-git/OpenMesh_samples
88667aad8b39955545448a4896e8129e86672b70
41276c826a0c5a18251cb1c48888c230793359ad
refs/heads/master
2020-06-25T16:35:18.190031
2019-09-13T09:55:34
2019-09-13T09:55:34
199,367,145
1
0
null
null
null
null
UTF-8
C++
false
false
2,320
hh
smooth_algo.hh
#include <OpenMesh/Core/Utils/Property.hh> #include <algorithm> #ifndef DOXY_IGNORE_THIS template <class Mesh> class SmootherT { public: typedef typename Mesh::Point cog_t; typedef OpenMesh::VPropHandleT<cog_t> Property_cog; public: // construct with a given mesh explicit SmootherT(Mesh &_mesh) : mesh_(_mesh) { mesh_.add_property(cog_); } ~SmootherT() { mesh_.remove_property(cog_); } // smooth mesh _iterations times void smooth(unsigned int _iterations) { for(unsigned int i = 0; i < _iterations; ++i) { std::for_each(mesh_.vertices_begin(), mesh_.vertices_end(), ComputeCOG(mesh_, cog_)); std::for_each(mesh_.vertices_begin(), mesh_.vertices_end(), SetCOG(mesh_, cog_)); } } private: //--- private classes --- class ComputeCOG { public: ComputeCOG(Mesh &_mesh, Property_cog &_cog) : mesh_(_mesh), cog_(_cog) {} void operator()(const typename Mesh::VertexHandle &_vh) { typename Mesh::VertexVertexIter vv_it; typename Mesh::Scalar valence(0.0); // Get value for item represented by the handle. https://www.openmesh.org/media/Documentations/OpenMesh-Doc-Latest/a01841.html#ae6c656910d0ac162eccf3d70799c5604 mesh_.property(cog_, _vh) = typename Mesh::Point(0.0, 0.0, 0.0); for(vv_it = mesh_.vv_iter(_vh); vv_it.is_valid(); ++vv_it) { mesh_.property(cog_, _vh) += mesh_.point(*vv_it); ++valence; } mesh_.property(cog_, _vh) /= valence; } private: Mesh &mesh_; Property_cog &cog_; }; class SetCOG { public: SetCOG(Mesh &_mesh, Property_cog &_cog) : mesh_(_mesh), cog_(_cog) {} void operator()(const typename Mesh::VertexHandle &_vh) { if(!mesh_.is_boundary(_vh)) mesh_.set_point(_vh, mesh_.property(cog_, _vh)); } private: Mesh &mesh_; Property_cog &cog_; }; //--- private elements --- Mesh &mesh_; Property_cog cog_; }; #endif
34f2e3a7038d1d5b2f5a42057175d7e048c0332d
5c2e6de7f70111817af3040af8e1dc8ddacde038
/cf327/a.cpp
ccd94301e481e458f1f435b3e2c3f270e536fa88
[]
no_license
HiYellowC/ACM
0bb3c8dcc1e5136302893efd367cd52d2a82d738
c6b7d934f9cb42e6cbe36b74894beb811061c756
refs/heads/master
2021-01-18T22:41:17.623752
2016-09-07T14:26:02
2016-09-07T14:26:02
45,155,861
0
0
null
null
null
null
UTF-8
C++
false
false
250
cpp
a.cpp
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; int main() { int l; scanf("%d", &l); int q, p; scanf("%d%d", &q, &p); printf("%lf\n", (double)(l) * (double)(q) / (double)(q + p)); return 0; }
684951554e3adeba510d3ae6c2aa326790b7a0a4
464f4190b7f5071527c066353b5365cf58aa42f8
/MineSweeper/MFC_FinV2/Mine.h
9d04136047505e909a050fff6feb9765bebb12e5
[]
no_license
chinghsuanwei/MFC
f84b846212e508820ea07b2081ce857827021b7e
0be54182698af44035641ce1194c2246fd7ee38c
refs/heads/master
2020-07-30T08:37:28.924573
2019-09-24T02:29:42
2019-09-24T02:29:42
210,158,235
0
0
null
null
null
null
UTF-8
C++
false
false
622
h
Mine.h
#pragma once // CMine class CMine : public CButton { DECLARE_DYNAMIC(CMine) public: CMine(); virtual ~CMine(); void SetDownColor(COLORREF color); void SetUpColor(COLORREF color); bool IsFlag(); bool IsQuetion(); void CleanData(); enum {NONE, FLAG, QUETION}rightState; int bombNum; bool isbomb; bool isSelected; bool selected; COLORREF m_TextColor, m_DownColor, m_UpColor; protected: DECLARE_MESSAGE_MAP() public: afx_msg void OnRButtonDown(UINT nFlags, CPoint point); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); afx_msg void OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct); };
a0e79a5ab1a0c56d95a8f0ee3624c54b386d5a69
beaf49f9870143f3491b12cc3a5f2a8286d42ccc
/iectransreceiver.cpp
f3f691df141029db9e391726ec154abb4b87151c
[]
no_license
nistvan86/ar1541
dc296af486780238c9c449cb51ece587fcc4c40d
0b2556e86700250ec592ccdc207ddc897b36a5a4
refs/heads/master
2021-01-11T05:26:53.238109
2020-06-19T11:25:50
2020-06-19T11:25:50
4,627,683
9
1
null
null
null
null
UTF-8
C++
false
false
11,062
cpp
iectransreceiver.cpp
#include "iectransreceiver.h" // Idle states #define TRANSRECEIVER_STATE_RESET -1 #define TRANSRECEIVER_STATE_IDLE 0 // Listener states #define TRANSRECEIVER_STATE_WAIT_FOR_TALKER 1 #define TRANSRECEIVER_STATE_READY_FOR_DATA 2 #define TRANSRECEIVER_STATE_DATA_RECEIVED 3 // Talker states #define TRANSRECEIVER_STATE_BECOMING_TALKER 4 #define TRANSRECEIVER_STATE_TALKER_IDLE 5 #define TRANSRECEIVER_STATE_TALKER_WAIT_FOR_DATA_ACCEPT 6 #define TRANSRECEIVER_STATE_TALKER_WAIT_FOR_EOI_HANDSHAKE 7 #define TRANSRECEIVER_STATE_TALKER_WRITING_DATA_BITS 8 #define TRANSRECEIVER_STATE_TALKER_WAIT_FOR_FRAME_ACKNOWLEDGEMENT 9 IECTransreceiver::IECTransreceiver(IECDOSInterpreter * dosInterpreter) { this->dosInterpreter = dosInterpreter; InterruptRouter::getInstance().setInterruptListener(this); } void IECTransreceiver::reset() { if (state == TRANSRECEIVER_STATE_RESET) { return; } setState(TRANSRECEIVER_STATE_RESET); InterruptRouter::getInstance().stopTimer(); InterruptRouter::getInstance().disableInterrupt(DATA_INTERRUPT); InterruptRouter::getInstance().disableInterrupt(CLOCK_INTERRUPT); attention = false; listener = false; talker = false; eoiReceived = false; writePin(DATA_PIN, false); // Release data pin if it's hold down writePin(CLOCK_PIN, false); // Release the data line Serial.println("R"); } void IECTransreceiver::start() { if (state == TRANSRECEIVER_STATE_RESET) { Serial.print(">"); InterruptRouter::getInstance().enableInterrupt(CLOCK_INTERRUPT); goToIdleState(); } } boolean IECTransreceiver::sendByte(byte frame, boolean withEoi) { if (!talker || state == TRANSRECEIVER_STATE_RESET || state >= TRANSRECEIVER_STATE_TALKER_WAIT_FOR_DATA_ACCEPT) { return false; } currentDataByte = frame; currentDataBit = 0; sendingWithEoi = withEoi; setState(TRANSRECEIVER_STATE_TALKER_WAIT_FOR_DATA_ACCEPT); InterruptRouter::getInstance().enableInterrupt(DATA_INTERRUPT); writePin(CLOCK_PIN, false); // release the clock to flag that we are ready to send data return true; } void IECTransreceiver::releaseClockLine() { writePin(CLOCK_PIN, false); } void IECTransreceiver::atnLineChanged() { if (state == TRANSRECEIVER_STATE_RESET) return; byte atn = readPin(ATN_PIN); if (atn == LOW) { beginAttention(); } else { // ATN is HIGH endAttention(); } } void IECTransreceiver::clockLineChanged() { if (state == TRANSRECEIVER_STATE_RESET || (!listener && !attention && state != TRANSRECEIVER_STATE_BECOMING_TALKER)) { return; } byte clock = readPin(CLOCK_PIN); if (clock == HIGH) { if (state == TRANSRECEIVER_STATE_WAIT_FOR_TALKER) { // Talker signaled that it's ready to send data // TODO: Hold can be inserted here to prepare for the start of transmission beginReceivingData(); } else if (state == TRANSRECEIVER_STATE_READY_FOR_DATA) { // Talker sent us a bit processIncomingBit(); } else if (state == TRANSRECEIVER_STATE_DATA_RECEIVED) { // Talker waits for us to signal that it can send the next frame if (dataBufferLength == DATA_BUFFER_SIZE - 1) { // Handle overflow if required if (!attention) { processData(); } else { Serial.print('!'); } } beginReceivingData(); } else if (state == TRANSRECEIVER_STATE_BECOMING_TALKER) { // Turnaround. Previous talker releases the clock line and holds the data line as a listener. doTalkerTurnaround(); } } else { // CLOCK is LOW if (state == TRANSRECEIVER_STATE_READY_FOR_DATA) { // Talker started to prepare bit on the line InterruptRouter::getInstance().stopTimer(); // Stop the EOI timer. } } } void IECTransreceiver::dataLineChanged() { if (state == TRANSRECEIVER_STATE_RESET || !talker) return; byte data = readPin(DATA_PIN); if (data == HIGH) { if (state == TRANSRECEIVER_STATE_TALKER_WAIT_FOR_DATA_ACCEPT) { if (sendingWithEoi) { setState(TRANSRECEIVER_STATE_TALKER_WAIT_FOR_EOI_HANDSHAKE); } else { startTransmission(); } } else if (state == TRANSRECEIVER_STATE_TALKER_WAIT_FOR_EOI_HANDSHAKE) { startTransmission(); } } else { // DATA is LOW if (state == TRANSRECEIVER_STATE_TALKER_WAIT_FOR_EOI_HANDSHAKE) { // Stay in this state, HIGH edge will proceed. } else if (state == TRANSRECEIVER_STATE_TALKER_WAIT_FOR_FRAME_ACKNOWLEDGEMENT) { // Listener acknowledged the frame finishTransmission(); } } } void IECTransreceiver::timerInterrupt() { if (listener && state == TRANSRECEIVER_STATE_READY_FOR_DATA) { // EOI signaled confirmEoi(); } else if (talker && state == TRANSRECEIVER_STATE_TALKER_WRITING_DATA_BITS) { InterruptRouter::getInstance().stopTimer(); sendNextBit(); } } boolean IECTransreceiver::isTalker() { return state >= TRANSRECEIVER_STATE_TALKER_IDLE; } boolean IECTransreceiver::isTransmitting() { return state >= TRANSRECEIVER_STATE_TALKER_WAIT_FOR_DATA_ACCEPT; } void IECTransreceiver::goToIdleState() { setState(TRANSRECEIVER_STATE_IDLE); // Non addressed device goes back to idle state writePin(DATA_PIN, false); writePin(CLOCK_PIN, false); } void IECTransreceiver::beginAttention() { Serial.print('a'); // Stop in what we are doing and listen InterruptRouter::getInstance().stopTimer(); listener = false; talker = false; attention = true; resetDataBuffer(); setState (TRANSRECEIVER_STATE_WAIT_FOR_TALKER); writePin(CLOCK_PIN, false); InterruptRouter::getInstance().enableInterrupt(CLOCK_INTERRUPT); InterruptRouter::getInstance().disableInterrupt(DATA_INTERRUPT); writePin(DATA_PIN, true); } void IECTransreceiver::endAttention() { Serial.print('A'); attention = false; if (state == TRANSRECEIVER_STATE_DATA_RECEIVED && dataBufferLength > 0) { // Last frame of the attention message received if (dataBuffer[0] >= 0x20 && dataBuffer[0] <= 0x3F && dataBuffer[0] - 0x20 == DEVICE_NUMBER) { // LISTEN processListenCommand(); } else if (dataBuffer[0] >= 0x40 && dataBuffer[0] <= 0x5F && dataBuffer[0] - 0x40 == DEVICE_NUMBER) { // TALK processTalkCommand(); } else if (dataBuffer[0] == 0x3F) { // UNLISTEN processUnlistenCommand(); } else if (dataBuffer[0] == 0x5F) { // UNTALK processUntalkCommand(); } else { goToIdleState(); // Non addressed device goes back to idle state } } } void IECTransreceiver::processTalkCommand() { channelToTalk = dataBuffer[1] - 0x60; resetDataBuffer(); setState(TRANSRECEIVER_STATE_BECOMING_TALKER); } void IECTransreceiver::processListenCommand() { Serial.println(); Serial.print('L'); listener = true; talker = false; if (dataBuffer[1] >= 0xE0 && dataBuffer[1] <= 0xEE) { // OPEN the file/data channel with name transmitted next dosInterpreter->onChannelOpenCommand(dataBuffer[1] - 0xE0); } else if (dataBuffer[1] >= 0xF0 && dataBuffer[1] <= 0xFE) { // CLOSE the file/data channel dosInterpreter->onChannelCloseCommand(dataBuffer[1] - 0xF0); } resetDataBuffer(); setState (TRANSRECEIVER_STATE_WAIT_FOR_TALKER); // Data line is being hold down here by us, which is exactly we need. } void IECTransreceiver::processIncomingBit() { int dataBit = readPin(DATA_PIN); if (dataBit != LOW) { currentDataByte |= (1 << currentDataBit); } currentDataBit++; if (currentDataBit == 8) { // We got a frame of a byte dataBuffer[dataBufferLength] = currentDataByte; writePin(DATA_PIN, true); // Signal that we have received the byte dataBufferLength = (dataBufferLength + 1) % DATA_BUFFER_SIZE; if (eoiReceived) { // Both talker and listener ends current transmission delayMicroseconds(60); writePin(DATA_PIN, false); // Release the data line setState (TRANSRECEIVER_STATE_IDLE); if (!attention) { processData(); } resetDataBuffer(); } else { setState (TRANSRECEIVER_STATE_DATA_RECEIVED); } } } void IECTransreceiver::doTalkerTurnaround() { InterruptRouter::getInstance().disableInterrupt(CLOCK_INTERRUPT); // TALKER will generate clock so we are not interested about changes writePin(DATA_PIN, false); writePin(CLOCK_PIN, true); talker = true; listener = false; delayMicroseconds(80); // Talker acknowledge setState(TRANSRECEIVER_STATE_TALKER_IDLE); Serial.println(); Serial.print('T'); dosInterpreter->onBecameTalker(); } void IECTransreceiver::processUnlistenCommand() { Serial.println('l'); listener = false; goToIdleState(); } void IECTransreceiver::processUntalkCommand() { Serial.println('t'); talker = false; goToIdleState(); } void IECTransreceiver::confirmEoi() { Serial.print('e'); // EOI signaled InterruptRouter::getInstance().stopTimer(); eoiReceived = true; // EOI Timeout handshake writePin(DATA_PIN, true); delayMicroseconds(120); writePin(DATA_PIN, false); } void IECTransreceiver::startTransmission() { setDriveLed(true); InterruptRouter::getInstance().disableInterrupt(DATA_INTERRUPT); setState(TRANSRECEIVER_STATE_TALKER_WRITING_DATA_BITS); InterruptRouter::getInstance().startTimer(40); } void IECTransreceiver::sendNextBit() { if (currentDataBit == 8) { writePin(DATA_PIN, false); // Release data line setState(TRANSRECEIVER_STATE_TALKER_WAIT_FOR_FRAME_ACKNOWLEDGEMENT); InterruptRouter::getInstance().enableInterrupt(DATA_INTERRUPT); writePin(CLOCK_PIN, true); // Listener should send acknowledgment now } else { writePin(CLOCK_PIN, true); // preparing to send the next bit writePin(DATA_PIN, !(currentDataByte & (1 << currentDataBit))); delayMicroseconds(70); // wait 70us to data become stable writePin(CLOCK_PIN, false); // listener now becomes noticed that the data is stable currentDataBit++; InterruptRouter::getInstance().startTimer(60); } } void IECTransreceiver::finishTransmission() { // Listener acknowledged the frame if (sendingWithEoi) { delayMicroseconds(60); } else { delayMicroseconds(100); // wait time between bytes } setDriveLed(false); setState(TRANSRECEIVER_STATE_TALKER_IDLE); } void IECTransreceiver::setState(int newState) { state = newState; } void IECTransreceiver::beginReceivingData() { currentDataByte = 0; currentDataBit = 0; setState(TRANSRECEIVER_STATE_READY_FOR_DATA); eoiReceived = false; writePin(DATA_PIN, false); // Release the Data line and flag that we are listening. if (!attention) { InterruptRouter::getInstance().startTimer(250); } } void IECTransreceiver::resetDataBuffer() { dataBufferLength = 0; } void IECTransreceiver::printBuffer() { for (int i = 0; i < dataBufferLength; i++) { Serial.print('/'); Serial.print(dataBuffer[i], HEX); } } void IECTransreceiver::processData() { printBuffer(); } void IECTransreceiver::resetLineChanged() { byte reset = readPin(RESET_PIN); if (reset == LOW) { setDriveLed(true); this->reset(); dosInterpreter->onTransreceiverReset(); } else { setDriveLed(false); this->start(); } }
058cc41d4166f0a779f7e2957cc2ef0918c7b21c
79df31e52d5561595256fbe3a1a42c6dddcf2349
/src/App/App.h
ac7f7397bea5ad38478125327cb831aef99a1ce1
[]
no_license
gitcommit/geologist
ab2e4c0a1f21d99f827d96ff670c9d82e2f490cf
0cff4697cff6899b6263af712a86b9701e994f57
refs/heads/master
2021-01-01T06:32:47.007872
2010-12-17T10:16:23
2010-12-17T10:16:23
1,123,829
0
0
null
null
null
null
UTF-8
C++
false
false
1,642
h
App.h
#ifndef App_H #define App_H #include <QtGui/QApplication> #include <QtCore/QString> #include <Lib/DBModel/DBModel.h> #include <Lib/DB/ConnectionData.h> #include <Lib/DB/QueryThread.h> #include <Lib/Model/Core/SIPrefix.h> class DataManager; class Session; class App : public QApplication { Q_OBJECT; public: App(int argc, char** argv); virtual ~App(); qlonglong nextQueryId() { _lastQueryId++; return _lastQueryId; } QueryThread* databaseThread() { return &_dbThread; } DBModel* databaseModel() { return &_dbModel; } Session* session() { return _session; } signals: void beginRequest(); void commitRequest(); void rollbackRequest(); void savepointRequest(const QString& name); void rollbackToSavepointRequest(const QString& name); void connectRequest(const ConnectionData& cd); void disconnectRequest(); void databaseOpened(const QString& info); void databaseClosed(); void databaseMessage(const QString& msg); void debugMessage(const QString& msg); public slots: virtual void debug(const QString& msg); virtual void onOpenDB(); virtual void onCloseDB(); void onDatabaseMessage(const QString& msg); void onConnected(const QString& msg); void onDisconnected(); void onSIPrefixesLoaded(const QList<SIPrefix*>& lst); protected: virtual void registerMetatypes(); virtual void init(); virtual void configureManagers(); private: QueryThread _dbThread; ConnectionData _cd; qlonglong _lastQueryId; DBModel _dbModel; Session* _session; }; #endif
f71c10b48cbdcf2a82a0bca02846a106814aa82d
c3d85921c68a147b0ea2f337a635c3e82b3983e5
/task1001/src/Date.cpp
f5bdabe6a9427688e78f14555e32c1ab41328211
[]
no_license
AlexBrence/cpp_oop
b1a1580c870fd577af4c43df9768eedb35a35b97
28458aaebe4a3ab915218953fa3c786c90164541
refs/heads/main
2023-03-12T08:32:31.718690
2021-03-01T09:25:57
2021-03-01T09:25:57
314,003,385
0
0
null
null
null
null
UTF-8
C++
false
false
1,957
cpp
Date.cpp
#include "Date.h" #include "UnparseableDateException.h" #include <sstream> #include <cctype> Date::Date() : day(0), month(0), year(0) {} Date::Date(int day, int month, int year) : day(day), month(month), year(year) {} Date::Date(const Date& d) : day(d.day), month(d.month), year(d.year) {} Date::~Date() {} int Date::get_day() const { return day; } int Date::get_month() const { return month; } int Date::get_year() const { return year; } void Date::set_day(const int& day) { this->day = day; } void Date::set_month(const int& month) { this->month = month; } void Date::set_year(const int& year) { this->year = year; } std::string Date::to_string() const { std::stringstream ss; ss << day << ". " << month << ". " << year; return ss.str(); } Date Date::get_date_from_string(const std::string& date) { int number_of_dots = 0; int date_arr[3]; // If char is not digit nor dot throw an exception for (const auto& ch : date) { if (ch == '.') number_of_dots++; if (!isdigit(ch) && ch != '.') throw UnparseableDateException(date); } if (number_of_dots != 2) throw UnparseableDateException(date); // String to int, save into date_arr for later usage int index = 0; std::string tmp = ""; for (const auto& ch : date) { if (ch != '.') tmp += ch; else { date_arr[index++] = std::stoi(tmp); tmp = ""; } // If it is the last digit finish if (&ch == &date[date.length() - 1]) date_arr[index++] = std::stoi(tmp); } // If day or month is incorrect if (date_arr[0] < 1 || date_arr[0] > 31 || date_arr[1] < 1 || date_arr[1] > 12) throw UnparseableDateException(date); if (date_arr[2] < 1900 || date_arr[2] > 2021) throw UnparseableDateException(date); return Date(date_arr[0], date_arr[1], date_arr[2]); }
a4b5ee6e406a5e8a4e31b8d7a5309863c9a0642a
418211f8b27352110acd9cd4ef86219af9667740
/overview/4-C++-templates/4c/main.cpp
12fb3de78ab08f9a16404d4a9fb2bd4baec2000f
[]
no_license
douglascraigschmidt/CPlusPlus
4592f09dc6a57a3b00a01fa7d25e02c31105877a
4b67965f3a41bd99fbad8e8405be3d998fbbe1a2
refs/heads/master
2022-08-28T01:28:58.719964
2022-07-21T11:50:49
2022-07-21T11:50:49
251,707,132
130
81
null
2021-05-26T14:35:00
2020-03-31T19:16:16
C++
UTF-8
C++
false
false
1,696
cpp
main.cpp
#include <iostream> #include <algorithm> #include "stack.h" #include "throw_exception.h" using namespace std; int main() { try { // Multiple stacks that are created automatically. stack<throw_exception> s1(3), s2(10); cout << "begin copy constructor" << endl; stack<throw_exception> s3(s2); cout << "end copy constructor" << endl; cout << "begin move constructor" << endl; stack<throw_exception> s4(std::move(s2)); cout << "end move constructor" << endl; int item = 0; cout << "begin push()" << endl; while (!s1.full()) s1.push(item++); cout << "end push()" << endl; cout << "begin pop()" << endl; while (!s1.empty()) { cout << "top item = " << s1.top() << endl; s1.pop(); } cout << "end pop()" << endl; cout << "begin emplace()" << endl; while (!s1.full()) s1.emplace(item++); cout << "end emplace()" << endl; cout << "begin pop()" << endl; while (!s1.empty()) { cout << "top item = " << s1.top() << endl; s1.pop(); } cout << "end pop()" << endl; cout << "begin copy assignment operator" << endl; s1 = s2; // No aliasing problem with assignment cout << "end copy assignment operator" << endl; cout << "begin move assignment operator" << endl; s1 = std::move(s2); // move assignment. cout << "end move assignment operator" << endl; // Termination is handled automatically. } catch (std::out_of_range &ex) { cout << "caught out of range error" << endl; } return 0; }
480198bed93163bec22bb52c8460eb361510dc73
4adf1af00b34d5b9aa633f89d8405970e5f078bb
/Tic-Tac-Toe/tictactoe.cpp
20aeff5c5f93f8ce0fe982f53151166710beb243
[]
no_license
brettonw/Archive
b849ae7f2f5a8a4bae249a798d54b3bdfa088797
3e54ece5261b4eff5947848392da9d36db9254d5
refs/heads/master
2021-09-16T10:51:32.395809
2018-06-19T19:05:20
2018-06-19T19:05:20
12,793,011
0
0
null
null
null
null
UTF-8
C++
false
false
18,636
cpp
tictactoe.cpp
// hiq.cpp : Defines the entry point for the application. // #include "stdafx.h" #include <vector> #include "tictactoe.h" #include "assert.h" #include "debug.h" #include "free_list.h" #define MAX_LOADSTRING 100 //----------------------------------------------------------------------------- typedef unsigned char uchar; typedef unsigned int uint; //----------------------------------------------------------------------------- const int TTT_DIM = 3; const int PEG_SIZE = 12; const int SPACE_SIZE = 4; const int BOARD_SIZE = (PEG_SIZE * TTT_DIM) + (TTT_DIM - 1); const int CLICK_GRID_SIZE = BOARD_SIZE + SPACE_SIZE; const int LEVEL_LIMIT = 10; //----------------------------------------------------------------------------- int gLevelChild[LEVEL_LIMIT + 2]; //----------------------------------------------------------------------------- uchar test_board[TTT_DIM][TTT_DIM] = { {2, 1, 2}, {2, 1, 1}, {1, 2, 1} }; //----------------------------------------------------------------------------- uchar win_conditions[16][TTT_DIM][TTT_DIM] = { { {1, 1, 1}, {0, 0, 0}, {0, 0, 0} }, { {0, 0, 0}, {1, 1, 1}, {0, 0, 0} }, { {0, 0, 0}, {0, 0, 0}, {1, 1, 1}, }, { {1, 0, 0}, {1, 0, 0}, {1, 0, 0} }, { {0, 1, 0}, {0, 1, 0}, {0, 1, 0} }, { {0, 0, 1}, {0, 0, 1}, {0, 0, 1} }, { {1, 0, 0}, {0, 1, 0}, {0, 0, 1} }, { {0, 0, 1}, {0, 1, 0}, {1, 0, 0} }, { {2, 2, 2}, {0, 0, 0}, {0, 0, 0} }, { {0, 0, 0}, {2, 2, 2}, {0, 0, 0} }, { {0, 0, 0}, {0, 0, 0}, {2, 2, 2}, }, { {2, 0, 0}, {2, 0, 0}, {2, 0, 0} }, { {0, 2, 0}, {0, 2, 0}, {0, 2, 0} }, { {0, 0, 2}, {0, 0, 2}, {0, 0, 2} }, { {2, 0, 0}, {0, 2, 0}, {0, 0, 2} }, { {0, 0, 2}, {0, 2, 0}, {2, 0, 0} }, }; //----------------------------------------------------------------------------- struct TTT_move { char row; char column; /* void */ TTT_move (void) : row (0), column (0) {} /* void */ TTT_move (char _row, char _column) : row (_row), column (_column) {} /* void */ TTT_move (const TTT_move& position) : row (position.row), column (position.column) {} }; class TTT_move_list : public std::vector<TTT_move> {}; //----------------------------------------------------------------------------- struct TTT_board { enum { EMPTY_SPOT = 0, RED_PEG = 1, BLUE_PEG = 2 }; uint board; /* void */ TTT_board (void); /* void */ TTT_board (uchar init[TTT_DIM][TTT_DIM]); /* void */ TTT_board (const TTT_board& _board); bool IsWinner (void) const; bool IsEmpty (TTT_move move) const; TTT_move_list GetLegalMoveList (void) const; void ApplyMove (TTT_move move, uint peg); void Draw (HDC dc, RECT& rect, int children) const; static uint wins[16]; static void InitWins (void); }; //----------------------------------------------------------------------------- uint TTT_board::wins[16]; //----------------------------------------------------------------------------- struct TTT_node; class TTT_node_list : public std::vector<TTT_node*> {}; struct TTT_node : public FreeList<TTT_node, 1024 * 128> { TTT_move move; TTT_board board; TTT_node_list children; /* void */ TTT_node (TTT_move _move, const TTT_board& _board) : move (_move), board (_board) {} void EnumerateMoves (int level = 0); void StartDraw (HDC dc, RECT& rect) const; int Draw (HDC dc, RECT& rect, int draw_level, int current_level) const; }; //----------------------------------------------------------------------------- /* void */ TTT_board::TTT_board (void) { // init the board to dead regions board = EMPTY_SPOT; } //----------------------------------------------------------------------------- /* void */ TTT_board::TTT_board (uchar init[TTT_DIM][TTT_DIM]) { uint shift = 0; // copy the init values into the board for (uint i = 0; i < TTT_DIM; i++) for (uint j = 0; j < TTT_DIM; j++) { board |= (init[i][j] << shift); shift += 2; } } //----------------------------------------------------------------------------- /* void */ TTT_board::TTT_board (const TTT_board& _board) : board (_board.board) { } //----------------------------------------------------------------------------- inline bool TTT_board::IsWinner (void) const { // check the board for win conditions (there are only 16) for (uint c = 0; c < 16; c++) if ((board & wins[c]) == wins[c]) return true; // not a winner return false; } //----------------------------------------------------------------------------- inline bool TTT_board::IsEmpty (TTT_move move) const { uint shift = ((move.row * 3) + move.column) * 2; return (((board >> shift) & 3) == EMPTY_SPOT); } //----------------------------------------------------------------------------- TTT_move_list TTT_board::GetLegalMoveList (void) const { TTT_move_list move_list; if (not IsWinner ()) { // search the board for empty spots for (uint i = 0; i < TTT_DIM; i++) for (uint j = 0; j < TTT_DIM; j++) { TTT_move move (i, j); if (IsEmpty (move)) move_list.push_back (move); } } return move_list; } //----------------------------------------------------------------------------- inline void TTT_board::ApplyMove (TTT_move move, uint peg) { uint shift = ((move.row * 3) + move.column) * 2; board |= (peg << shift); } //----------------------------------------------------------------------------- void TTT_board::Draw (HDC dc, RECT& rect, int children) const { // check to see if this board is a winner only if it doesn't have any children if ((children == 0) and IsWinner ()) { HBRUSH winner_brush = CreateSolidBrush (RGB (0, 255, 0)); RECT board_rect; int board_size = ((PEG_SIZE + 1) * TTT_DIM) + 4; int left = rect.left - 2; int top = rect.top - 2; SetRect (&board_rect, left, top, left + board_size, top + board_size); FillRect (dc, &board_rect, winner_brush); DeleteObject(reinterpret_cast<HGDIOBJ> (winner_brush)); } HBRUSH empty_brush = CreateSolidBrush (RGB (200, 200, 200)); HBRUSH red_brush = CreateSolidBrush (RGB (255, 0, 0)); HBRUSH blue_brush = CreateSolidBrush (RGB (0, 0, 255)); uint shift = 0; int top = rect.top; for (int i = 0; i < TTT_DIM; i++) { int left = rect.left; for (int j = 0; j < TTT_DIM; j++) { RECT peg_rect; SetRect (&peg_rect, left, top, left + PEG_SIZE, top + PEG_SIZE); switch ((board >> shift) & 3) { case EMPTY_SPOT: FillRect (dc, &peg_rect, empty_brush); break; case RED_PEG: FillRect (dc, &peg_rect, red_brush); break; case BLUE_PEG: FillRect (dc, &peg_rect, blue_brush); break; } left += PEG_SIZE + 1; shift += 2; } top += PEG_SIZE + 1; } DeleteObject(reinterpret_cast<HGDIOBJ> (empty_brush)); DeleteObject(reinterpret_cast<HGDIOBJ> (red_brush)); DeleteObject(reinterpret_cast<HGDIOBJ> (blue_brush)); } //----------------------------------------------------------------------------- void TTT_board::InitWins (void) { for (uint c = 0; c < 16; c++) { uint shift = 0; wins[c] = 0; // copy the init values into the board for (uint i = 0; i < TTT_DIM; i++) for (uint j = 0; j < TTT_DIM; j++) { wins[c] |= (win_conditions[c][i][j] << shift); shift += 2; } } } //----------------------------------------------------------------------------- int gEnumCounter = 0; int gMoveCounter = 0; int gMoveCounterMax = 0; void TTT_node::EnumerateMoves (int level) { if (level < LEVEL_LIMIT) { // get the legal move list TTT_move_list move_list = board.GetLegalMoveList (); gEnumCounter++; gMoveCounter += int (move_list.size ()); if (int (move_list.size ()) > gMoveCounterMax) gMoveCounterMax = int (move_list.size ()); // char output[128]; // sprintf (output, "Level (%d): %d moves (%d total)\n", level, int (move_list.size ()), gMoveCounter); // OutputDebugString (output); // generate new nodes for each move in the move list TTT_move_list::iterator iter = move_list.begin (); TTT_move_list::iterator end = move_list.end (); while (iter != end) { TTT_move& move = *iter++; TTT_node* node = NewCall TTT_node (move, board); children.push_back (node); node->board.ApplyMove (move, (level & 1) + 1); node->EnumerateMoves (level + 1); } // nice if we could keep a "hash" of the board to limit duplication } } //----------------------------------------------------------------------------- void TTT_node::StartDraw (HDC dc, RECT& rect) const { //board.Draw (dc, rect, int (children.size ())); for (int i = 0; i < LEVEL_LIMIT; i++) { Draw (dc, rect, i, 0); rect.top += BOARD_SIZE + SPACE_SIZE; } } //----------------------------------------------------------------------------- int TTT_node::Draw (HDC dc, RECT& rect, int draw_level, int current_level) const { if ((current_level < draw_level) and (rect.left < rect.right)) { RECT drawRect = rect; int level_child = gLevelChild[current_level]; if ((level_child < -1) or (children.size () == 0)) { // draw no children return 0; } else { if (level_child >= int (children.size ())) { level_child = -1; for (int i = current_level; i < LEVEL_LIMIT; i++) gLevelChild[i] = -1; } if (level_child == -1) { TTT_node_list::const_iterator iter = children.begin (); TTT_node_list::const_iterator end = children.end (); if (iter != end) { const TTT_node* node = *iter++; drawRect.left += node->Draw (dc, drawRect, draw_level, current_level + 1); } while (iter != end) { drawRect.left += SPACE_SIZE; const TTT_node* node = *iter++; drawRect.left += node->Draw (dc, drawRect, draw_level, current_level + 1); } MoveToEx (dc, drawRect.left + (SPACE_SIZE / 2) + (SPACE_SIZE & 0x01), drawRect.top - 1, 0); LineTo (dc, drawRect.left + (SPACE_SIZE / 2) + (SPACE_SIZE & 0x01), drawRect.top + BOARD_SIZE + 1); } else { const TTT_node* node = children.at (level_child); drawRect.left += node->Draw (dc, drawRect, draw_level, current_level + 1); } return (drawRect.left - rect.left); } } else { board.Draw (dc, rect, int (children.size ())); return BOARD_SIZE; } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //TTT_board gBoard (test_board); TTT_board gBoard; TTT_move gMove; TTT_node gBaseNode (gMove, gBoard); // Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_HIQ, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); //gLevelChild[0] = -1; for (int i = 0; i < LEVEL_LIMIT; i++) gLevelChild[i] = -1; // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } TTT_board::InitWins (); gBaseNode.EnumerateMoves (); InvalidateRect (0, 0, TRUE); //int gEnumCounter = 0; //int gMoveCounter = 0; //int gMoveCounterMax = 0; char output[256]; sprintf (output, "Moves (%d), nodes (%d), average branch (%d), max branch (%d)\n", gMoveCounter, gEnumCounter, gMoveCounter / gEnumCounter, gMoveCounterMax); OutputDebugString (output); hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_HIQ); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // // COMMENTS: // // This function and its usage are only necessary if you want this code // to be compatible with Win32 systems prior to the 'RegisterClassEx' // function that was added to Windows 95. It is important to call this function // so that the application will get 'well formed' small icons associated // with it. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = (WNDPROC)WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_HIQ); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = (LPCTSTR)IDC_HIQ; wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL); return RegisterClassEx(&wcex); } // // FUNCTION: InitInstance(HANDLE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // FUNCTION: WndProc(HWND, unsigned, WORD, LONG) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; RECT drawRect; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... GetClientRect (hWnd, &drawRect); InflateRect (&drawRect, -SPACE_SIZE, -SPACE_SIZE); gBaseNode.StartDraw (hdc, drawRect); EndPaint(hWnd, &ps); break; case WM_LBUTTONDOWN: { int yPos = (HIWORD(lParam) / CLICK_GRID_SIZE) - 1; if ((yPos == 0) or ((yPos > 0) and (gLevelChild[yPos - 1] != -1))) { if (gLevelChild[yPos] == -1) { int xPos = LOWORD(lParam) / CLICK_GRID_SIZE; gLevelChild[yPos] = xPos; while (yPos < LEVEL_LIMIT) gLevelChild[++yPos] = -1; } else { gLevelChild[yPos] = -1; while (yPos < LEVEL_LIMIT) gLevelChild[++yPos] = -1; } InvalidateRect (0, 0, TRUE); } } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Message handler for about box. LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: return TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } return FALSE; }
810d957f792bf890a97d2818d8f82ee66bfcc2b5
595705d4b79ba5c53f936b8e541df2d19221083b
/include/picotorrent/core/is_valid_torrent_file.hpp
00b2c3aae212f27388f61c0ef237b8e191b8e366
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
lakeoftears/picotorrent
82908360ca25b85bd04205e37d336ae954299e56
e728c8f82663b6a175b525178a679fe00ccb3d82
refs/heads/develop
2021-01-15T00:45:12.205491
2015-11-09T21:50:39
2015-11-09T21:50:39
46,092,022
1
0
null
2015-11-13T01:31:46
2015-11-13T01:31:46
null
UTF-8
C++
false
false
162
hpp
is_valid_torrent_file.hpp
#pragma once namespace picotorrent { namespace filesystem { class path; } namespace core { bool is_valid_torrent_file(const filesystem::path& path); } }
f8d274d0616e19a3f854c1ecc5d423aee02e9951
2fea27dc201d0e36ad4c2ba77c0e905fbdc42f5c
/Arrays/ArrDelsorted.cpp
101fc3b16b4ccdd2ba0385f758045d9f4427e711
[]
no_license
Srutip04/DSA
37eb62a4473e7cfa005d32b7fef36e5f21aab0ed
57b9035449d4173ee04b3c3100751b423b88ce3e
refs/heads/master
2023-08-10T15:57:36.709501
2021-10-06T20:11:04
2021-10-06T20:11:04
397,841,687
2
0
null
2021-10-06T20:11:05
2021-08-19T06:34:28
C++
UTF-8
C++
false
false
1,157
cpp
ArrDelsorted.cpp
// C++ program to implement delete operation in a // sorted array #include <iostream> using namespace std; // To search a ley to be deleted int binarySearch(int arr[], int low, int high, int key); /* Function to delete an element */ int deleteElement(int arr[], int n, int key) { // Find position of element to be deleted int pos = binarySearch(arr, 0, n - 1, key); if (pos == -1) { cout << "Element not found"; return n; } // Deleting element int i; for (i = pos; i < n - 1; i++) arr[i] = arr[i + 1]; return n - 1; } int binarySearch(int arr[], int low, int high, int key) { if (high < low) return -1; int mid = (low + high) / 2; if (key == arr[mid]) return mid; if (key > arr[mid]) return binarySearch(arr, (mid + 1), high, key); return binarySearch(arr, low, (mid - 1), key); } // Driver code int main() { int i; int arr[] = { 10, 20, 30, 40, 50 }; int n = sizeof(arr) / sizeof(arr[0]); int key = 30; cout << "Array before deletion\n"; for (i = 0; i < n; i++) cout << arr[i] << " "; n = deleteElement(arr, n, key); cout << "\n\nArray after deletion\n"; for (i = 0; i < n; i++) cout << arr[i] << " "; }
d2fcbb912e7d7587a5d1c0c5868d40c0974cfc95
a157e1617e83305f36fb8197164f766711de9b71
/LinkedLists/App.cpp
248f65cddabb71c5bbf495c339517002c6166db2
[]
no_license
flippingtables/cpplibs
d2f54c77463d121ab6b5669f0f2b0431ecfedb6a
a39c0dff6f51af371b2e7a1dc5a1beb33e0569ec
refs/heads/master
2020-05-04T16:32:51.946830
2019-04-11T17:21:47
2019-04-11T17:21:47
179,280,858
0
0
null
null
null
null
UTF-8
C++
false
false
540
cpp
App.cpp
// LinkedLists.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include "LinkedList.h" int main() { try { LinkedList<int> ll; ll.remove(0); /*int veryLarge = 1; for (int i = 0; i < veryLarge; i++) { ll.insert(i); } ll.remove(5); x = ll.get(1000); ll.clear(); std::cout << "Press enter to close.\n"; */ std::cin.ignore(); } catch (const std::exception& e) { std::cout << e.what() << std::endl; } return 0; }
4e5ffc60bf8c3a953fa82a7ebb72e8a1aebdd3e6
95c8c1fd503c3d39fb311fe07da395393535c0d7
/examples/example_performance.cpp
f7b16f1644582797e836127665a432a37a66ebdd
[ "MIT" ]
permissive
deephealthproject/ecvl
ec72cf95095165de97377150f93347c99403800e
f15a9114e1287f96bba505c8661fc5a135400dc1
refs/heads/master
2022-04-30T09:21:46.581335
2022-04-29T10:38:42
2022-04-29T10:38:42
252,753,850
13
2
MIT
2022-03-16T10:24:19
2020-04-03T14:21:37
C++
IBM852
C++
false
false
4,039
cpp
example_performance.cpp
/* * ECVL - European Computer Vision Library * Version: 1.0.3 * copyright (c) 2021, UniversitÓ degli Studi di Modena e Reggio Emilia (UNIMORE), AImageLab * Authors: * Costantino Grana (costantino.grana@unimore.it) * Federico Bolelli (federico.bolelli@unimore.it) * Michele Cancilla (michele.cancilla@unimore.it) * Laura Canalini (laura.canalini@unimore.it) * Stefano Allegretti (stefano.allegretti@unimore.it) * All rights reserved. */ #include "ecvl/core.h" #include <iostream> #include <omp.h> #include <thread> #include <vector> using namespace ecvl; using namespace std; struct Benchmark { int n_test_ = 1000; cv::TickMeter tm_; Benchmark() {} Benchmark(int n_test) : n_test_(n_test) {} template <class Functor, class... Args> double Run(int processor_count, Functor f, Args&&... args) { vector<double> timings(n_test_); omp_set_num_threads(processor_count); for (int i = 0; i < n_test_; ++i) { tm_.reset(); tm_.start(); f(args...); tm_.stop(); timings[i] = tm_.getTimeMilli(); } return std::accumulate(timings.begin(), timings.end(), 0.) / timings.size(); } }; void print(double& timing, int processor_count = 1) { if (processor_count > 1) { cout << "Elapsed parallel " << processor_count << " threads: "; } else { cout << "Elapsed sequential: "; } cout << timing << " ms" << endl; } int main() { // Open an Image Image in, out; ImRead("../examples/data/test.jpg", in, ImReadMode::GRAYSCALE); Benchmark b; auto processor_count = std::thread::hardware_concurrency(); if (!processor_count) { return EXIT_FAILURE; } cout << "CPU Cores: " << processor_count << endl << endl; cout << "Benchmarking Threshold" << endl; auto timing = b.Run(1, Threshold, in, out, 128, 255., ThresholdingType::BINARY); print(timing); timing = b.Run(processor_count, Threshold, in, out, 128, 255., ThresholdingType::BINARY); print(timing, processor_count); cout << endl; cout << "Benchmarking Mirror2D" << endl; timing = b.Run(1, Mirror2D, in, out); print(timing); timing = b.Run(processor_count, Mirror2D, in, out); print(timing, processor_count); cout << endl; cout << "Benchmarking Flip2D" << endl; timing = b.Run(1, Flip2D, in, out); print(timing); timing = b.Run(processor_count, Flip2D, in, out); print(timing, processor_count); cout << endl; Image ccl_in; Threshold(in, ccl_in, 128, 255); cout << "Benchmarking ConnectedComponentsLabeling" << endl; timing = b.Run(1, ConnectedComponentsLabeling, ccl_in, out); print(timing); timing = b.Run(processor_count, ConnectedComponentsLabeling, ccl_in, out); print(timing, processor_count); cout << endl; cout << "Benchmarking HConcat" << endl; vector images{ in,in }; timing = b.Run(1, HConcat, images, out); print(timing); timing = b.Run(processor_count, HConcat, images, out); print(timing, processor_count); cout << endl; cout << "Benchmarking Stack" << endl; timing = b.Run(1, Stack, images, out); print(timing); timing = b.Run(processor_count, Stack, images, out); print(timing, processor_count); cout << endl; cout << "Benchmarking SaltAndPepper" << endl; timing = b.Run(1, SaltAndPepper, in, out, 0.5, false, 1U); print(timing); timing = b.Run(processor_count, SaltAndPepper, in, out, 0.5, false, 1U); print(timing, processor_count); cout << endl; /* cout << "Benchmarking SeparableFilter2D" << endl; vector<double> kernelX = { 1, 2, 1 }; vector<double> kernelY = { 1, 0, -1 }; timing = b.Run(1, SeparableFilter2D, in, out, kernelX, kernelY, DataType::none); print(timing); timing = b.Run(processor_count, SeparableFilter2D, in, out, kernelX, kernelY, DataType::none); print(timing, processor_count); cout << endl;*/ return EXIT_SUCCESS; }
3e8ff06925f34d9bde23db526cb13601e1a58b1e
c87095bd13b9080224324b3a6dd4fd538912d97e
/OpenGL/MD2 Animation/Main.cpp
5815adb938530188a54305b35979661f00d7b647
[ "MIT" ]
permissive
Agrelimos/tutorials
6a0a8ef6652a44bd5a35b59bf192326c831367ff
7d2953b8fbb5c56a921a17e7e3cac3d1f4fbb41b
refs/heads/master
2020-04-01T05:26:56.560609
2018-10-13T18:45:56
2018-10-13T18:45:56
152,903,588
0
0
MIT
2018-10-13T18:44:42
2018-10-13T18:44:42
null
WINDOWS-1252
C++
false
false
25,700
cpp
Main.cpp
//***********************************************************************// // // // - "Talk to me like I'm a 3 year old!" Programming Lessons - // // // // $Author: DigiBen digiben@gametutorials.com // // // // $Program: MD2 Animation // // // // $Description: Demonstrates how to animate a Quake2 MD2 Model // // // // //***********************************************************************// // This is a compiler directive that includes libraries (For Visual Studio). #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "glu32.lib") #pragma comment(lib, "winmm.lib") #include "main.h" // This includes our header file #include "Md2.h" // Include the MD2 header file. bool g_bFullScreen = true; // Set full screen as default HWND g_hWnd; // This is the handle for the window RECT g_rRect; // This holds the window dimensions HDC g_hDC; // General HDC - (handle to device context) HGLRC g_hRC; // General OpenGL_DC - Our Rendering Context for OpenGL HINSTANCE g_hInstance; // This holds the global hInstance for UnregisterClass() in DeInit() #define FILE_NAME "knight.md2" // This is the 3D file we will load. #define TEXTURE_NAME "knight.bmp" UINT g_Texture[MAX_TEXTURES] = {0}; // This holds the texture info, referenced by an ID CLoadMD2 g_LoadMd2; // This is MD2 class. This should go in a good model class. t3DModel g_3DModel; // This holds the 3D Model info that we load in int g_ViewMode = GL_TRIANGLES; // We want the default drawing mode to be normal float g_RotateX = 0.0f; // This is the current value at which the model is rotated float g_RotationSpeed = 0.0f; // This is the speed that our model rotates. (-speed rotates left) //////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** //////////////////// // This tutorial is the second tutorial to loading .MD2 models. In the previous // tutorial, we just loaded the model's first frame of animation. Now we // get to load the rest of the key frames and interpolate between them to create // the somewhat smooth animation that you see in Quake2 games. Let's go over some // of the more important vocabulary that you will need to understand for this tutorial: // // Key Frames Animation: Key frame animation is where you store only certain // parts of an animation, then interpolate between those frames to produce a // smooth animation. For instance, say you have a ball that starts from one // side of the room and rolls to the other side in a 100 frame animation. Do // we really need to store all 100 frames to recreate that animation? No, we // just need to store a key frame at frame 1 and frame 100, then interpolate // between them. This is how the Quake2 models work. There is just important // frames saved when ever the model moves it's body in a different position. // This is great and all, but what the heck does interpolation mean??!!? // // Interpolation: Gamedev.net's Game Dictionary say interpolation is "using a ratio // to step gradually a variable from one value to another." In our case, this // means that we gradually move our vertices from one key frame to another key frame. // There are many types of interpolation, but we are just going to use linear. // The equation for linear interpolation is this: // // p(t) = p0 + t(p1 - p0) // // t - The current time with 0 being the start and 1 being the end // p(t) - The result of the equation with time t // p0 - The starting position // p1 - The ending position // // Let's throw in an example with numbers to test this equation. If we have // a vertex stored at 0 along the X axis and we wanted to move the point to // 10 with 5 steps, see if you can fill in the equation without a time just yet. // // Finished? You should have come up with: // // p(t) = 0 + t(10 - 0) // p(t) = 0 + 10t // p(t) = 10t // // Now, all we need it a time from 0 to 1 to pass in, which will allow us to find any // point from 0 to 10, depending on the time. Since we wanted to find out the distance // we need to travel each frame if we want to reach the end point in 5 steps, we just // divide 1 by 5: 1/5 = 0.2 // // We can then pass this into our equation: // // p(0.2) = 10 * 0.2 // p(0.2) = 2 // // What does that tell us? It tells us we need to move the vertex along the x // axis each frame by a distance of 2 to reach 10 in 5 steps. Yah, yah, this isn't // rocket science, but it's important to know that what your mind would have done // immediately without thinking about it, is linear interpolation. // // Are you starting to see how this applies to our model? If we only read in key // frames, then we need to interpolate every vertex between the current and next // key frame for animation. To get a perfect idea of what is going on, try // taking out the interpolation and just render the key frames. You will notice // that you can still see what is kinda going on, but it moves at an incredible pace! // There is not smoothness, just a really fast jumpy animation. // // If you are wondering, animation isn't really done this way anymore. To perform // more realistic and dynamic animation, developers and artists moved to bone animation, // otherwise known as skeletal animation. If you look at the Quake3 .MD3 file format, // you'll notice this change to bones instead of key frames. With this technique, you // can allow the player to dynamically do things that don't have to be animated by // an artist, such as having the player look in the direction of another player as // it comes into the same room. Also, you can have the the player reach out for things // in the world that might be in different positions, say on a shelf or a table. The // arm can then move exactly to that object and pick it up. // // You might take note that in the last tutorial we calculated the face normals of our // model, but on second thought, I decided to not do it in our final MD2 tutorial because // the model's texture maps are created for their own lighting and just make it darker // than usual. Quake2 and many other games don't use dynamic lighting because it was // incredibly slow on older video cards without GPU's (Graphics Processing Units). // // In this tutorial, we do not start out spinning the model as we did in the last one, // you have to manually do it. That way we won't get confused between the rotations and // the actual animation. The current animation is displayed in the windows title bar. // That way you know exactly what is going on in the animation. // The controls for this application are: // // Left Mouse Button - Changes the render mode from normal to wire frame. // Right Mouse Button - Cycles through the animations // Left Arrow Key - Spins the model to the left // Right Arrow Key - Spins the model to the right // Escape - Quits // // If you decide to go find models you might find them in a format like .pk3. // This is just a .zip format, so rename it to .zip and unzip it. There should // be .Md2 and texture files. I think the textures are normally in .pcx, so you // will have to save them as BMP's to run it with this application. // // // //////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** //////////////////// ///////////////////////////////// INIT GAME WINDOW \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This function initializes the game window. ///// ///////////////////////////////// INIT GAME WINDOW \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* void Init(HWND hWnd) { g_hWnd = hWnd; // Assign the window handle to a global window handle GetClientRect(g_hWnd, &g_rRect); // Assign the windows rectangle to a global RECT InitializeOpenGL(g_rRect.right, g_rRect.bottom); // Init OpenGL with the global rect // Load the Quake2 model with it's file name and texture name g_LoadMd2.ImportMD2(&g_3DModel, FILE_NAME, TEXTURE_NAME); // Go through all the materials for(int i = 0; i < g_3DModel.numOfMaterials; i++) { // Check to see if there is a file name to load in this material if(strlen(g_3DModel.pMaterials[i].strFile) > 0) { // Use the name of the texture file to load the bitmap, with a texture ID (i). // We pass in our global texture array, the name of the texture, and an ID to reference it. CreateTexture(g_Texture[i], g_3DModel.pMaterials[i].strFile); } // Set the texture ID for this material g_3DModel.pMaterials[i].texureId = i; } // To make our model render somewhat faster, we do some front face culling. // It seems that Quake2 orders their polygons clock-wise. glEnable(GL_CULL_FACE); // Turn culling on glCullFace(GL_FRONT); // Quake2 uses front face culling apparently } ///////////////////////////////// ANIMATE NEXT FRAME \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This function keeps our rendering within a specified frame rate ///// ///////////////////////////////// ANIMATE NEXT FRAME \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* bool AnimateNextFrame(int desiredFrameRate) { static float lastTime = GetTickCount() * 0.001f; static float elapsedTime = 0.0f; float currentTime = GetTickCount() * 0.001f; // Get the time (milliseconds = seconds * .001) float deltaTime = currentTime - lastTime; // Get the slice of time float desiredFPS = 1.0f / desiredFrameRate; // Store 1 / desiredFrameRate elapsedTime += deltaTime; // Add to the elapsed time lastTime = currentTime; // Update lastTime // Check if the time since we last checked is greater than our desiredFPS if( elapsedTime > desiredFPS ) { elapsedTime -= desiredFPS; // Adjust our elapsed time // Return true, to animate the next frame of animation return true; } // We don't animate right now. return false; } ///////////////////////////////// MAIN LOOP \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This function handles the main program loop ///// ///////////////////////////////// MAIN LOOP \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* WPARAM MainLoop() { MSG msg; while(1) // Do our infinite loop { // Check if there was a message if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if(msg.message == WM_QUIT) // If the message wasn't to quit break; TranslateMessage(&msg); // Find out what the message does DispatchMessage(&msg); // Execute the message } else // If there wasn't a message { if(AnimateNextFrame(60)) // Make sure we only render 60 frames per second { RenderScene(); // Render the scene } } } // Go through all the objects in the scene for(int i = 0; i < g_3DModel.numOfObjects; i++) { // Free the faces, normals, vertices, and texture coordinates. if(g_3DModel.pObject[i].pFaces) delete [] g_3DModel.pObject[i].pFaces; if(g_3DModel.pObject[i].pNormals) delete [] g_3DModel.pObject[i].pNormals; if(g_3DModel.pObject[i].pVerts) delete [] g_3DModel.pObject[i].pVerts; if(g_3DModel.pObject[i].pTexVerts) delete [] g_3DModel.pObject[i].pTexVerts; } DeInit(); // Clean up and free all allocated memory return(msg.wParam); // Return from the program } //////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** //////////////////// ///////////////////////////////// RETURN CURRENT TIME \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This returns time t for the interpolation between the current and next key frame ///// ///////////////////////////////// RETURN CURRENT TIME \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* float ReturnCurrentTime(t3DModel *pModel, int &nextFrame) { static float elapsedTime = 0.0f; static float lastTime = 0.0f; // This function is very similar to finding the frames per second. // Instead of checking when we reach a second, we check if we reach // 1 second / our animation speed. (1000 ms / kAnimationSpeed). // That's how we know when we need to switch to the next key frame. // In the process, we get the t value for how we are at to going to the // next animation key frame. We use time to do the interpolation, that way // it runs the same speed on any persons computer, regardless of their specs. // It might look choppier on a junky computer, but the key frames still be // changing the same time as the other persons, it will just be not as smooth // of a transition between each frame. The more frames per second we get, the // smoother the animation will be. // Get the current time in milliseconds float time = (float)GetTickCount(); // Find the time that has elapsed since the last time that was stored elapsedTime = time - lastTime; // To find the current t we divide the elapsed time by the ratio of 1 second / our anim speed. // Since we aren't using 1 second as our t = 1, we need to divide the speed by 1000 // milliseconds to get our new ratio, which is a 5th of a second. float t = elapsedTime / (1000.0f / kAnimationSpeed); // If our elapsed time goes over a 5th of a second, we start over and go to the next key frame if (elapsedTime >= (1000.0f / kAnimationSpeed) ) { // Set our current frame to the next key frame (which could be the start of the anim) pModel->currentFrame = nextFrame; nextFrame = (pModel->currentFrame + 1) % pModel->pAnimations[pModel->currentAnim].endFrame; // Set our last time to the current time just like we would when getting our FPS. lastTime = time; } // Return the time t so we can plug this into our interpolation. return t; } ///////////////////////////////// ANIMATE MD2 MODEL \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This draws and animates the .md2 model by interpolated key frame animation ///// ///////////////////////////////// ANIMATE MD2 MODEL \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* void AnimateMD2Model(t3DModel *pModel) { // Now comes the juice of our tutorial. Fear not, this is actually very intuitive // if you drool over it for a while (stay away from the keyboard though...). // What's going on here is, we are getting our current animation that we are // on, finding the current frame of that animation that we are on, then interpolating // between that frame and the next frame. To make a smooth constant animation when // we get to the end frame, we interpolate between the last frame of the animation // and the first frame of the animation. That way, if we are doing the running // animation let's say, when the last frame of the running animation is hit, we don't // have a huge jerk when going back to the first frame of that animation. Remember, // because we have the texture and face information stored in the first frame of our // animation, we need to reference back to this frame every time when drawing the // model. The only thing the other frames store is the vertices, but no information // about them. // Make sure we have valid objects just in case. (size() is in the vector class) if(pModel->pObject.size() <= 0) return; // Here we grab the current animation that we are on from our model's animation list tAnimationInfo *pAnim = &(pModel->pAnimations[pModel->currentAnim]); // This gives us the current frame we are on. We mod the current frame plus // 1 by the current animations end frame to make sure the next frame is valid. // If the next frame is past our end frame, then we go back to zero. We check this next. int nextFrame = (pModel->currentFrame + 1) % pAnim->endFrame; // If the next frame is zero, that means that we need to start the animation over. // To do this, we set nextFrame to the starting frame of this animation. if(nextFrame == 0) nextFrame = pAnim->startFrame; // Get the current key frame we are on t3DObject *pFrame = &pModel->pObject[pModel->currentFrame]; // Get the next key frame we are interpolating to t3DObject *pNextFrame = &pModel->pObject[nextFrame]; // Get the first key frame so we have an address to the texture and face information. t3DObject *pFirstFrame = &pModel->pObject[0]; // Next, we want to get the current time that we are interpolating by. Remember, // if t = 0 then we are at the beginning of the animation, where if t = 1 we are at the end. // Anything from 0 to 1 can be thought of as a percentage from 0 to 100 percent complete. float t = ReturnCurrentTime(pModel, nextFrame); // Start rendering lines or triangles, depending on our current rendering mode (Lft Mouse Btn) glBegin(g_ViewMode); // Go through all of the faces (polygons) of the current frame and draw them for(int j = 0; j < pFrame->numOfFaces; j++) { // Go through each corner of the triangle and draw it. for(int whichVertex = 0; whichVertex < 3; whichVertex++) { // Get the index for each point of the face int vertIndex = pFirstFrame->pFaces[j].vertIndex[whichVertex]; // Get the index for each texture coordinate for this face int texIndex = pFirstFrame->pFaces[j].coordIndex[whichVertex]; // Make sure there was a UVW map applied to the object. Notice that // we use the first frame to check if we have texture coordinates because // none of the other frames hold this information, just the first by design. if(pFirstFrame->pTexVerts) { // Pass in the texture coordinate for this vertex glTexCoord2f(pFirstFrame->pTexVerts[ texIndex ].x, pFirstFrame->pTexVerts[ texIndex ].y); } // Now we get to the interpolation part! (*Bites his nails*) // Below, we first store the vertex we are working on for the current // frame and the frame we are interpolating to. Next, we use the // linear interpolation equation to smoothly transition from one // key frame to the next. // Store the current and next frame's vertex CVector3 vPoint1 = pFrame->pVerts[ vertIndex ]; CVector3 vPoint2 = pNextFrame->pVerts[ vertIndex ]; // By using the equation: p(t) = p0 + t(p1 - p0), with a time t // passed in, we create a new vertex that is closer to the next key frame. glVertex3f(vPoint1.x + t * (vPoint2.x - vPoint1.x), // Find the interpolated X vPoint1.y + t * (vPoint2.y - vPoint1.y), // Find the interpolated Y vPoint1.z + t * (vPoint2.z - vPoint1.z));// Find the interpolated Z } } // Stop rendering the triangles glEnd(); } //////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** //////////////////// ///////////////////////////////// RENDER SCENE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This function renders the entire scene. ///// ///////////////////////////////// RENDER SCENE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* void RenderScene() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer glLoadIdentity(); // Reset The matrix // Give OpenGL our position, then view, then up vector gluLookAt( 0, 1.5f, 100, 0, 0.5f, 0, 0, 1, 0); glRotatef(g_RotateX, 0, 1.0f, 0); // Rotate the object around the Y-Axis g_RotateX += g_RotationSpeed; // Increase the speed of rotation if any //////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** //////////////////// // This is where we call our animation function to draw and animate our character. // You can pass in any model into here and it will draw and animate it. Of course, // it would be a good idea to stick this function in your model class. AnimateMD2Model(&g_3DModel); //////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** //////////////////// SwapBuffers(g_hDC); // Swap the backbuffers to the foreground } ///////////////////////////////// WIN PROC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* ///// ///// This function handles the window messages. ///// ///////////////////////////////// WIN PROC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\* LRESULT CALLBACK WinProc(HWND hWnd,UINT uMsg, WPARAM wParam, LPARAM lParam) { LONG lRet = 0; PAINTSTRUCT ps; char strWindowTitle[255] = {0}; switch (uMsg) { case WM_SIZE: // If the window is resized if(!g_bFullScreen) // Do this only if we are NOT in full screen { SizeOpenGLScreen(LOWORD(lParam),HIWORD(lParam));// LoWord=Width, HiWord=Height GetClientRect(hWnd, &g_rRect); // Get the window rectangle } break; case WM_PAINT: // If we need to repaint the scene BeginPaint(hWnd, &ps); // Init the paint struct EndPaint(hWnd, &ps); // EndPaint, Clean up break; // Below we define our controls for this tutorial. The controls are: // Left Mouse Button - Changes the Render mode from normal to wireframe. // Right Mouse Button - Cycle through the animations // Left Arrow Key - Spins the model to the left // Right Arrow Key - Spins the model to the right // Escape - Quits case WM_LBUTTONDOWN: // If the left mouse button was clicked if(g_ViewMode == GL_TRIANGLES) { // We our drawing mode is at triangles g_ViewMode = GL_LINE_STRIP; // Go to line strips } else { g_ViewMode = GL_TRIANGLES; // Go to triangles } break; case WM_RBUTTONDOWN: // If the right mouse button was clicked //////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** //////////////////// // To cycle through the animations, we just increase the model's current animation // by 1. You'll notice that we also mod this result by the total number of // animations in our model, to make sure we go back to the beginning once we reach // the end of our animation list. // Increase the current animation and mod it by the max animations g_3DModel.currentAnim = (g_3DModel.currentAnim + 1) % (g_3DModel.numOfAnimations); // Set the current frame to be the starting frame of the new animation g_3DModel.currentFrame = g_3DModel.pAnimations[g_3DModel.currentAnim].startFrame; // Display the current animation in our window sprintf(strWindowTitle, "www.GameTutorials.com - Md2 Animation: %s", g_3DModel.pAnimations[g_3DModel.currentAnim].strName); SetWindowText(g_hWnd, strWindowTitle); //////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** //////////////////// break; case WM_KEYDOWN: // If we pressed a key switch(wParam) { // Check if we hit a key case VK_ESCAPE: // If we hit the escape key PostQuitMessage(0); // Send a QUIT message to the window break; case VK_LEFT: // If the LEFT arrow key was pressed g_RotationSpeed -= 0.05f; // Decrease the rotation speed (eventually rotates left) break; case VK_RIGHT: // If the RIGHT arrow key is pressed g_RotationSpeed += 0.05f; // Increase the rotation speed (rotates right) break; } break; case WM_CLOSE: // If the window is being closed PostQuitMessage(0); // Send a QUIT Message to the window break; default: // Return by default lRet = (LONG)DefWindowProc (hWnd, uMsg, wParam, lParam); break; } return lRet; // Return by default } ///////////////////////////////////////////////////////////////////////////////// // // * QUICK NOTES * // // This tutorial shows how to load and animate a .Md2 file. We learned about key frames // and how to interpolate using the linear interpolation equation: p(t) = p0 + t(p1 - p0). // key frames are not the best way to animate, but it's one of the easiest, besides just // storing every single frame of animation. When creating your 3D engine, you need to // weigh the pro's and cons of having less calculation during run-time (which doesn't // matter much with 1.6 ghz processors) or having less of a memory print in ram and on // the hard disk. In my opinion, with our technology, skeletal animation is the best // technique for animation. There is so many possibilities with it that can make your // game/program incredibly realistic. // // In this version of our .MD2 loader, we added 2 functions: // // float ReturnCurrentTime(t3DModel *pModel, int nextFrame); // // and // // void AnimateMD2Model(t3DModel *pModel); // // These help us to use linear interpolation to draw and animate the player model // according to time. That way it won't animate the model faster on a slower computer, // it will just animate it choppier. The faster the computer, the smoother the // animation will be. // // In the next tutorial on Quake model loading, I will show you how to load a .MD3. // This file format uses a skeletal/bone system to animate the players. This is // extremely advanced and takes a decent knowledge of quaternions and model loading. // There are 2 tutorials that cover loading .MD3 files. The first will be just as the // first tutorial on .MD2 loading. There will be no animation until the second tutorial. // That way we break up the huge topics into smaller, more easier to digest chunks. // // I would like to once again thank Daniel E. Schoenblum <dansch@hops.cs.jhu.edu> for help // with explaining the file format. // // Let me know if this helps you out! // // The Quake2 .Md2 file format is owned by ID Software. This tutorial is being used // as a teaching tool to help understand model loading and animation. This should // not be sold or used under any way for commercial use with out written consent // from ID Software. // // Quake, Quake2 and Quake3 are trademarks of ID Software. // All trademarks used are properties of their respective owners. // // © 2000-2005 GameTutorials
33e978313875a1a18293c5c14235bb076d671cce
2e270080c794b1caf52a1669cdea14704ef5842a
/DFS와 BFS/[구름 IDE] 비타알고 시즌2 졸업(★3).cpp
c1ba883871f97481bf9a16b1f57b6e51a954f816
[]
no_license
SnowFleur/Coding-Test-Collection
0db54cc8a2395f1ac21442f07093623cba64c45b
2a7fea8aa1231f142d91b8fdea91182b85c4cae9
refs/heads/master
2021-07-25T05:56:07.897399
2021-05-05T08:21:32
2021-05-05T08:21:32
249,441,381
0
0
null
null
null
null
UHC
C++
false
false
962
cpp
[구름 IDE] 비타알고 시즌2 졸업(★3).cpp
#include<iostream> #include<vector> #include<algorithm> #include<stack> using NODE = std::vector<std::vector<int>>; std::vector<bool> g_visited; void DFS(NODE& n,int S) { int weight=1; std::stack<int> s; s.emplace(S); while (s.empty() == false) { auto topVaule = s.top(); s.pop(); g_visited[topVaule] = true; for (const auto& node : n[topVaule]) { if (g_visited[node] == false) { ++weight; s.emplace(node); } } } std::cout << weight << "\n"; } int main() { //N 과목의 수, M 관계의 수 , 졸업하기 위해 들어야하는 과목 C int N, M, C; std::cin >> N >> M; NODE n(N + 1); g_visited.assign(N + 1, false); int s{}, e{}; for (int i = 0; i < M; ++i) { // s start, e end std::cin >> s >> e; //Reverse n[e].emplace_back(s); } std::cin >> C; DFS(n, C); }
7adf9301f706fc503991c834fd7ba86ecdc63e65
af119118a67e43b360fa24a385c6e97ff7165add
/cplusplus/zaluan/file.cpp
3506ba98bfb8bffa3d90531d344b31b251b953ab
[]
no_license
txgcwm/code_study
e03da3a29c3341c9c9ab53ea4a26928bf7a928ba
fe6313879df60bfa5ecc4fe8d995b1a7cb4607ef
refs/heads/master
2021-01-20T20:10:56.942126
2019-11-27T17:10:27
2019-11-27T17:10:27
64,046,593
1
2
null
null
null
null
UTF-8
C++
false
false
1,450
cpp
file.cpp
#include <string.h> #include <stdio.h> #include <string> int writeFile(std::string filename, const char* text, int size) { int ret = -1; int len = -1; FILE* file = NULL; file = fopen(filename.c_str(), "wb"); if(file == NULL) { printf("open file(%s) fail!\n", filename.c_str()); return ret; } len = fwrite(text, 1, size, file); if(len == size) { ret = 0; } else { printf("len(%d), write data to file fail!\n", len); } fclose(file); file = NULL; return ret; } int readFile(std::string filename) { int ret = -1; int len = -1; FILE* file = NULL; char buffer[1024] = {0}; file = fopen(filename.c_str(), "rb"); if(file == NULL) { printf("open file(%s) fail!\n", filename.c_str()); return ret; } len = fread(buffer, 1, sizeof(buffer), file); if(len <= 0) { printf("len(%d), can not read data from file!\n", len); } else { ret = 0; } printf("Read %d Byte (%s)\n", len, buffer); fclose(file); file = NULL; return ret; } int main(int argc, char** argv) { if(writeFile("test.txt", "nihaoa", strlen("nihaoa")) < 0) { printf("write file error!\n"); } else { printf("write file success!\n"); } if(readFile("test.txt") < 0) { printf("read file error!\n"); } else { printf("read file success!\n"); } return 0; }
b87517686b650f892b3d0783b9901d5ea740ae2e
d9bb656bd11f85e6419ebd786aec6fe3f917cb73
/modules/variants/assemble_testutil.cpp
4e2df106a448e43578cba74df531f3cc46d27ce7
[ "BSD-2-Clause" ]
permissive
spiralgenetics/biograph
55a91703a70429568107209ce20e71f6b96577df
5f40198e95b0626ae143e021ec97884de634e61d
refs/heads/main
2023-08-30T18:04:55.636103
2021-10-31T00:50:48
2021-10-31T00:51:08
386,059,959
21
10
NOASSERTION
2021-07-22T23:28:45
2021-07-14T19:52:15
HTML
UTF-8
C++
false
false
2,713
cpp
assemble_testutil.cpp
#include "modules/variants/assemble_testutil.h" namespace variants { void PrintTo(const assembly& as, std::ostream* os) { *os << "\n"; as.output_offsets(*os); as.output_other_info(*os); *os << ": "; aoffset_t left_anchor_len = as.left_anchor_len; aoffset_t right_anchor_len = as.right_anchor_len; if (left_anchor_len > aoffset_t(as.seq.size())) { left_anchor_len = as.seq.size(); } if (right_anchor_len > aoffset_t(as.seq.size())) { right_anchor_len = as.seq.size(); } aoffset_t right_anchor_start = aoffset_t(as.seq.size()) - right_anchor_len; dna_sequence left, main, right; if (int(as.seq.size()) >= (left_anchor_len + right_anchor_len)) { left = as.seq.subseq(0, left_anchor_len); right = as.seq.subseq(right_anchor_start, right_anchor_len); main = as.seq.subseq(left_anchor_len, right_anchor_start - left_anchor_len); } else { *os << "(ol) "; left = as.seq.subseq(0, right_anchor_start); right = as.seq.subseq(left_anchor_len, aoffset_t(as.seq.size()) - left_anchor_len); main = as.seq.subseq(right_anchor_start, left_anchor_len + right_anchor_len - aoffset_t(as.seq.size())); } *os << left << " " << main << " " << right << " id=" << as.assembly_id; int num_ids = 0; for (const auto id : as.merged_assembly_ids) { *os << "," << id; if (++num_ids > 2) { *os << "..."; break; } } *os << " score=" << as.score; if (as.strand_count) { *os << " strand_count=" << as.strand_count; } if (as.edge_coverage) { *os << " edge_coverage(" << *as.edge_coverage << ")"; } if (!as.sub_assemblies.empty()) { *os << ", " << as.sub_assemblies.size() << " subassemblies for phase_ids=("; bool first = true; for (const auto& pid : as.phase_ids) { if (!first) { *os << ","; } first = false; *os << pid; } *os << "):\n"; size_t n = 0; for (const auto& suba : as.sub_assemblies) { *os << " #" << n << ": "; ++n; (*suba)->output_offsets(*os); *os << ": " << (*suba)->seq << "\n"; } } *os << "\n"; } std::vector<dna_sequence> reads_for_seq(dna_sequence seq, unsigned read_length, unsigned read_distance) { std::vector<dna_sequence> reads; CHECK_LE(read_length, seq.size()); unsigned i = 0; while (i + read_length <= seq.size()) { reads.push_back(seq.subseq(i, read_length)); i += read_distance; } // In case seq.size() - read_length is not an exact multiple of // read_distance, fill in another read at the end. reads.push_back(seq.subseq(seq.size() - read_length, read_length)); return reads; } } // namespace variants
fd73bf5169fbd23f7c515f614abb16bab4d7eff0
b4d2c11218f4dee2856fb60b208143133ba2e0b2
/Qt_frontend/DLLPinCode/pindialog.cpp
d1c324f28d33c58bdedb869b8aa9f5c39c075337
[]
no_license
Akllu/BankSimul
92e13cf34ad45dcf0c54c352a3c076e4e41b0861
87e140f7955f1eadc1c5f6700a0d6722105fb9d8
refs/heads/main
2023-04-15T04:58:55.115916
2021-04-28T09:31:24
2021-04-28T09:31:24
352,922,685
0
0
null
null
null
null
UTF-8
C++
false
false
3,740
cpp
pindialog.cpp
#include "pindialog.h" #include "ui_pindialog.h" PinDialog::PinDialog(QWidget *parent) : QDialog(parent), ui(new Ui::PinDialog) { ui->setupUi(this); diaTimer = new QTimer(this); //Luodaan diaTimer-niminen ajastin diaTimer->setInterval(10000); //säädetään se "laukeamaan" 10s päästä diaTimer->setSingleShot(true); //säädetään se "laukeamaan" vain kerran connect(diaTimer, SIGNAL(timeout()), SLOT(timerRanOut())); //säädetään se sulkemaan ikkuna "lauetessaan" ui->pinLine->setValidator(new QIntValidator(0, 1000, this)); //Rajoitetaan käyttäjä syöttämään 4-numeroinen PIN-koodi qDebug() << "Luodaan PinDialog."; } PinDialog::~PinDialog() { qDebug() << "Tuhotaan PinDialog."; delete ui; } void PinDialog::timerRanOut() { // lähetetään signaali joka ilmoittaa ajastin sulkeutui emit timedOut(); this->close(); } QString PinDialog::returnPinCode() { // lähetetään syötetty pinkoodi takaisin return pinCode; } void PinDialog::on_okButton_clicked() { /******************************************* * Talletetaan käyttäjän syöttämä pinkoodi * * pinLine-elementistä, tyhjennetään se ja * * suljetaan dialogi-ikkuna. * *******************************************/ diaTimer->stop(); //pysäytetään ajastin koska dialogi sulkeutuu pinCode = ui->pinLine->text(); ui->pinLine->QLineEdit::clear(); emit pinInserted(); //lähetetään signaali että käyttäjä syötti koodin this -> close(); } void PinDialog::timerReset() { // Pysäytetään ja käynnistetään ajastin uudelleen sen nollaamiseksi. diaTimer->stop(); diaTimer->start(); qDebug() << "Timer Reset"; } void PinDialog::buttonCharInserter(QString i) { /****************************************** * Tallennetaan pinLine:ssä oleva teksti, * * lisätään sen perään metodiin annettu * * merkki. Syötetään tämä pinLine:lle. * ******************************************/ QString j = ui->pinLine->text(); j.append(i); ui->pinLine->setText(j); timerReset(); // nollataan ajastin jokaisella syötteellä } void PinDialog::on_clearButton_clicked() { // tyhjennetään pinLine käyttäjän pyynnöstä ui->pinLine->QLineEdit::clear(); timerReset(); } void PinDialog::on_numButton_0_clicked() { // syötetään merkki pinLine:lle QString i = "0"; buttonCharInserter(i); } void PinDialog::on_numButton_1_clicked() { // syötetään merkki pinLine:lle QString i = "1"; buttonCharInserter(i); } void PinDialog::on_numButton_2_clicked() { // syötetään merkki pinLine:lle QString i = "2"; buttonCharInserter(i); } void PinDialog::on_numButton_3_clicked() { // syötetään merkki pinLine:lle QString i = "3"; buttonCharInserter(i); } void PinDialog::on_numButton_4_clicked() { // syötetään merkki pinLine:lle QString i = "4"; buttonCharInserter(i); } void PinDialog::on_numButton_5_clicked() { // syötetään merkki pinLine:lle QString i = "5"; buttonCharInserter(i); } void PinDialog::on_numButton_6_clicked() { // syötetään merkki pinLine:lle QString i = "6"; buttonCharInserter(i); } void PinDialog::on_numButton_7_clicked() { // syötetään merkki pinLine:lle QString i = "7"; buttonCharInserter(i); } void PinDialog::on_numButton_8_clicked() { // syötetään merkki pinLine:lle QString i = "8"; buttonCharInserter(i); } void PinDialog::on_numButton_9_clicked() { // syötetään merkki pinLine:lle QString i = "9"; buttonCharInserter(i); }
91708f7a955686381eca22ae08519941c678982c
909010085dc065fd9683438e4e55aa3bf9adad49
/s32v234_vsdk_avnet_1.2.0/kernels/apu/sample_filtering_kernels/src/gauss_3x1_acf.cpp
2db16d8aa1c71014c845cc6af03331c5cfbd0440
[]
no_license
Avnet/S32V
2103f60a0a90a928d858b32905b4b80b62b8f992
758c8494e5b2db00ecfe6e64386b106c9ae9f056
refs/heads/master
2020-07-31T00:00:16.061738
2019-10-11T08:46:40
2019-10-11T08:58:17
210,406,182
3
3
null
null
null
null
UTF-8
C++
false
false
3,017
cpp
gauss_3x1_acf.cpp
/***************************************************************************** * * Freescale Confidential Proprietary * * Copyright (c) 2013 Freescale Semiconductor; * Copyright (c) 2017 NXP * * All Rights Reserved * ***************************************************************************** * * THIS SOFTWARE IS PROVIDED BY FREESCALE "AS IS" AND ANY EXPRESSED OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL FREESCALE OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /*! * \file gauss_3x1_acf.cpp * \addtogroup arithmetic * \addtogroup addition * \ingroup arithmetic * @{ * \brief Element-wise addition */ #ifdef APEX2_EMULATE #include "acf_kernel.hpp" // if using the ACF emulation library using namespace APEX2; #endif #ifdef ACF_KERNEL_METADATA #include "gauss_3x1_acf.h" /****************************************************************************/ /*! Addition kernel metadata. Adds pixelwise two unsigned 8bit images. Outputs 16bit unsigned addition result. \param ADD_KN Define for Kernel name \param 3 Number of ports \param "Port ADD_KN_INA" Define for name of first input image (unsigned 8bit) \param "Port ADD_KN_INB" Define for name of second input image (unsigned 8bit) \param "Port ADD_KN_OUT" Define for name of addition result of the two images (unsigned 16bit). *****************************************************************************/ KERNEL_INFO kernelInfoConcat(GAUSS3X1_K)//_kernel_info_apu_add ( GAUSS3X1_KN, 2, __port(__index(0), __identifier("INPUT_0"), __attributes(ACF_ATTR_VEC_IN), __spatial_dep(1, 1, 1, 1), __e0_data_type(d08u), __e0_size(1, 1), __ek_size(1, 1)), __port(__index(1), __identifier("OUTPUT_0"), __attributes(ACF_ATTR_VEC_OUT), __spatial_dep(0, 0, 0, 0), __e0_data_type(d08u), __e0_size(1, 1), __ek_size(1, 1)) ); #endif //#ifdef ACF_KERNEL_METADATA #ifdef ACF_KERNEL_IMPLEMENTATION #include "gauss_3x1_apu.h" void apu_gauss_3x1(kernel_io_desc in0, kernel_io_desc out0) { vec08u* lIn0 = (vec08u*)in0.pMem; vec08u* lOut0 = (vec08u*)out0.pMem; int32s inStrideW = in0.chunkSpan / sizeof(int08u); int32s outStrideW = out0.chunkSpan / sizeof(int08s); gauss_3x1(lOut0, lIn0, in0.chunkWidth, in0.chunkHeight, inStrideW, outStrideW); } #endif //#ifdef ACF_KERNEL_IMPLEMENTATION /*! @} */
6827d3159cc820ede182bb0d9dd969c3b877b74f
247304942e48ddc4302d21dc93653a2337faca79
/Autocomplete.cpp
df5e689f3c41207974b024ae8b9a8444cbe2e6cc
[]
no_license
victor-ludorum/CodeForces
288576bfcbb3af487ac89ce2aa6e3a24dfa648e3
9f742af8124bb87eb0c8e536667bad1d2cea4e69
refs/heads/master
2020-03-26T22:32:49.729176
2018-08-20T20:52:50
2018-08-20T20:52:50
145,467,571
0
0
null
null
null
null
UTF-8
C++
false
false
553
cpp
Autocomplete.cpp
#include <bits/stdc++.h> using namespace std; int main() { string a; cin>>a; int n; cin>>n; string s[n]; for(int i=0;i<n;++i) { cin>>s[i]; } sort(s,s+n); int l = a.length(); string r; bool flag = false; for(int i=0;i<n&&flag == false;++i) { char p = s[i][0]; if(p==a[0]) { int h = 1; for(int j=1;j<l;++j) { if(s[i][j]!=a[j]) break; else h++; } if(h==l) { flag = true; r.assign(s[i]); } } } if(flag) cout<<r<<endl; else cout<<a<<endl; }
e3b81de0d8e06ed1df845cacf12fadbea6c591cf
4bcc9806152542ab43fc2cf47c499424f200896c
/tensorflow/core/kernels/data/parallel_interleave_dataset_op.cc
aa24c0122ad463bae1a481f3886ab3d629446c8d
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
tensorflow/tensorflow
906276dbafcc70a941026aa5dc50425ef71ee282
a7f3934a67900720af3d3b15389551483bee50b8
refs/heads/master
2023-08-25T04:24:41.611870
2023-08-25T04:06:24
2023-08-25T04:14:08
45,717,250
208,740
109,943
Apache-2.0
2023-09-14T20:55:50
2015-11-07T01:19:20
C++
UTF-8
C++
false
false
75,580
cc
parallel_interleave_dataset_op.cc
/* Copyright 2017 The TensorFlow 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 "tensorflow/core/kernels/data/parallel_interleave_dataset_op.h" #include <sys/types.h> #include <algorithm> #include <atomic> #include <cmath> #include <deque> #include <memory> #include <utility> #include "absl/strings/str_format.h" #include "tensorflow/core/common_runtime/function.h" #include "tensorflow/core/common_runtime/input_colocation_exemption_registry.h" #include "tensorflow/core/data/captured_function.h" #include "tensorflow/core/data/dataset_utils.h" #include "tensorflow/core/data/name_utils.h" #include "tensorflow/core/data/stats_utils.h" #include "tensorflow/core/framework/dataset.h" #include "tensorflow/core/framework/metrics.h" #include "tensorflow/core/framework/model.h" #include "tensorflow/core/framework/partial_tensor_shape.h" #include "tensorflow/core/framework/stats_aggregator.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow/core/lib/gtl/cleanup.h" #include "tensorflow/core/lib/random/random.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/lib/strings/stringprintf.h" #include "tensorflow/core/platform/blocking_counter.h" #include "tensorflow/core/platform/cpu_info.h" #include "tensorflow/core/platform/errors.h" #include "tensorflow/core/platform/stringprintf.h" #include "tensorflow/core/profiler/lib/traceme.h" #include "tensorflow/core/profiler/lib/traceme_encode.h" namespace tensorflow { namespace data { // See documentation in ../../ops/dataset_ops.cc for a high-level // description of the following op. /* static */ constexpr const char* const ParallelInterleaveDatasetOp::kDatasetType; /* static */ constexpr const char* const ParallelInterleaveDatasetOp::kInputDataset; /* static */ constexpr const char* const ParallelInterleaveDatasetOp::kOtherArguments; /* static */ constexpr const char* const ParallelInterleaveDatasetOp::kCycleLength; /* static */ constexpr const char* const ParallelInterleaveDatasetOp::kBlockLength; /* static */ constexpr const char* const ParallelInterleaveDatasetOp::kBufferOutputElements; /* static */ constexpr const char* const ParallelInterleaveDatasetOp::kPrefetchInputElements; /* static */ constexpr const char* const ParallelInterleaveDatasetOp::kNumParallelCalls; /* static */ constexpr const char* const ParallelInterleaveDatasetOp::kFunc; /* static */ constexpr const char* const ParallelInterleaveDatasetOp::kTarguments; /* static */ constexpr const char* const ParallelInterleaveDatasetOp::kOutputTypes; /* static */ constexpr const char* const ParallelInterleaveDatasetOp::kOutputShapes; /* static */ constexpr const char* const ParallelInterleaveDatasetOp::kDeterministic; /* static */ constexpr const char* const ParallelInterleaveDatasetOp::kSloppy; namespace { constexpr char kParallelism[] = "parallelism"; constexpr char kBlockIndex[] = "block_index"; constexpr char kCycleIndex[] = "cycle_index"; constexpr char kMaxBufferedElements[] = "max_buffered_elements"; constexpr char kEndOfInput[] = "end_of_input"; constexpr char kElementIdCounter[] = "element_id_counter"; constexpr char kCurrentElements[] = "current_elements"; constexpr char kCurrentElementsSize[] = "current_elements.size"; constexpr char kFutureElements[] = "future_elements"; constexpr char kFutureElementsSize[] = "future_elements.size"; constexpr char kResultsSuffix[] = ".results"; constexpr char kCodeSuffix[] = ".code"; constexpr char kErrorMessageSuffix[] = ".error_message"; constexpr char kIdSuffix[] = ".id"; constexpr char kSizeSuffix[] = ".size"; constexpr char kInputsSuffix[] = ".inputs"; constexpr char kIsReadySuffix[] = ".is_ready"; constexpr char kElementUninitialized[] = "element_uninitialized"; constexpr char kRestoreIterator[] = "restore_iterator"; constexpr char kParallelInterleaveDatasetV2[] = "ParallelInterleaveDatasetV2"; constexpr char kParallelInterleaveDatasetV3[] = "ParallelInterleaveDatasetV3"; constexpr char kParallelInterleaveDatasetV4[] = "ParallelInterleaveDatasetV4"; // `kCyclePrefetchFactor * cycle_length` is the default number of future cycle // elements that will be prefetched ahead of time. The purpose of prefetching // future cycle elements is to overlap expensive initialization (e.g. opening of // a remote file) with other computation. constexpr int kDefaultCyclePrefetchFactor = 2; // `kPerIteratorPrefetchFactor * block_length + 1` is the default number of // per-iterator results that will be prefetched ahead of time. The `+ 1` is to // match the behavior of the original implementation. constexpr double kDefaultPerIteratorPrefetchFactor = 2.0L; // Period between reporting dataset statistics. constexpr int kStatsReportingPeriodMillis = 1000; inline int64_t CeilDiv(int64_t numerator, int64_t denominator) { return (numerator + denominator - 1) / denominator; } // Returns the `cycle_length` computed using the `input_cycle_length` and the // `num_parallel_calls`. If `cycle_length` is not to be autotuned, we set it to // the `input_cycle_length`. If parallelism is not to be autotuned, we set the // cycle length to match the `num_parallel_calls` or the number of schedulable // cores, whichever is smaller. If it is to be autotuned, we set it so that the // number of threads created for the current and future cycle elements roughly // matches the number of schedulable cores. int64_t ComputeCycleLength(int64_t input_cycle_length, int64_t num_parallel_calls) { int64_t cycle_length = input_cycle_length; if (cycle_length == model::kAutotune) { if (num_parallel_calls != model::kAutotune) { cycle_length = std::min(num_parallel_calls, static_cast<int64_t>(port::MaxParallelism())); } else { const int num_threads_per_cycle_length = kDefaultCyclePrefetchFactor + 1; cycle_length = CeilDiv(port::MaxParallelism(), num_threads_per_cycle_length); } } return cycle_length; } int64_t ComputeBufferOutputElements(int64_t configured_buffer_output_elements, int64_t block_length) { if (configured_buffer_output_elements != model::kAutotune) { return configured_buffer_output_elements; } return kDefaultPerIteratorPrefetchFactor * block_length + 1; } int64_t ComputePrefetchInputElements(int64_t configured_prefetch_input_elements, int64_t cycle_length) { if (configured_prefetch_input_elements != model::kAutotune) { return configured_prefetch_input_elements; } if (GetExperiments().contains("reduce_interleave_prefetch")) { return std::min( static_cast<int64_t>(8), static_cast<int64_t>(kDefaultCyclePrefetchFactor * cycle_length)); } return kDefaultCyclePrefetchFactor * cycle_length; } int64_t ComputeMaxBufferedElements(int64_t prefetch_input_elements, int64_t buffer_output_elements, int64_t cycle_length) { return (prefetch_input_elements + cycle_length) * buffer_output_elements; } int64_t OpVersionFromOpName(absl::string_view op_name) { if (op_name == kParallelInterleaveDatasetV2) { return 2; } else if (op_name == kParallelInterleaveDatasetV3) { return 3; } else { DCHECK_EQ(op_name, kParallelInterleaveDatasetV4); return 4; } } } // namespace // The motivation for creating an alternative implementation of parallel // interleave is to decouple the degree of parallelism from the cycle length. // This makes it possible to change the degree of parallelism (e.g. through // auto-tuning) without changing the cycle length (which would change the order // in which elements are produced). class ParallelInterleaveDatasetOp::Dataset : public DatasetBase { public: Dataset(OpKernelContext* ctx, const DatasetBase* input, std::unique_ptr<CapturedFunction> captured_func, int64_t cycle_length, int64_t block_length, int64_t buffer_output_elements, int64_t prefetch_input_elements, int64_t num_parallel_calls, DeterminismPolicy deterministic, const DataTypeVector& output_types, const std::vector<PartialTensorShape>& output_shapes, int op_version) : DatasetBase(DatasetContext(ctx)), input_(input), captured_func_(std::move(captured_func)), input_cycle_length_(cycle_length), cycle_length_(ComputeCycleLength(cycle_length, num_parallel_calls)), block_length_(block_length), buffer_output_elements_( ComputeBufferOutputElements(buffer_output_elements, block_length)), prefetch_input_elements_(ComputePrefetchInputElements( prefetch_input_elements, cycle_length_)), num_parallel_calls_(num_parallel_calls), deterministic_(deterministic), output_types_(output_types), output_shapes_(output_shapes), op_version_(op_version), traceme_metadata_( {{"autotune", num_parallel_calls == model::kAutotune ? "true" : "false"}, {"block_length", strings::Printf("%lld", static_cast<long long>(block_length))}, {"cycle_length", strings::Printf("%lld", static_cast<long long>(cycle_length))}, {"deterministic", deterministic.IsNondeterministic() ? "false" : "true"}}) { input_->Ref(); } ~Dataset() override { input_->Unref(); } std::unique_ptr<IteratorBase> MakeIteratorInternal( const string& prefix) const override { name_utils::IteratorPrefixParams params; params.op_version = op_version_; bool deterministic = deterministic_.IsDeterministic() || deterministic_.IsDefault(); return std::make_unique<ParallelInterleaveIterator>( ParallelInterleaveIterator::Params{ this, name_utils::IteratorPrefix( ParallelInterleaveDatasetOp::kDatasetType, prefix, params)}, deterministic); } const DataTypeVector& output_dtypes() const override { return output_types_; } const std::vector<PartialTensorShape>& output_shapes() const override { return output_shapes_; } string DebugString() const override { name_utils::DatasetDebugStringParams params; params.op_version = op_version_; return name_utils::DatasetDebugString( ParallelInterleaveDatasetOp::kDatasetType, params); } int64_t CardinalityInternal(CardinalityOptions options) const override { int64_t n = input_->Cardinality(options); if (n == kInfiniteCardinality) { return n; } return kUnknownCardinality; } Status InputDatasets(std::vector<const DatasetBase*>* inputs) const override { inputs->push_back(input_); return OkStatus(); } Status CheckExternalState() const override { TF_RETURN_IF_ERROR(captured_func_->CheckExternalState()); return input_->CheckExternalState(); } protected: Status AsGraphDefInternal(SerializationContext* ctx, DatasetGraphDefBuilder* b, Node** output) const override { std::vector<std::pair<size_t, Node*>> inputs; std::vector<std::pair<size_t, gtl::ArraySlice<Node*>>> list_inputs; int input_index = 0; Node* input_node; TF_RETURN_IF_ERROR(b->AddInputDataset(ctx, input_, &input_node)); inputs.emplace_back(input_index++, input_node); std::vector<Node*> other_arguments; DataTypeVector other_arguments_types; TF_RETURN_IF_ERROR(captured_func_->AddToGraph(ctx, b, &other_arguments, &other_arguments_types)); list_inputs.emplace_back(input_index++, other_arguments); Node* cycle_length_node; if (GetExperiments().contains("serialize_input_cycle_length")) { TF_RETURN_IF_ERROR(b->AddScalar(input_cycle_length_, &cycle_length_node)); } else { TF_RETURN_IF_ERROR(b->AddScalar(cycle_length_, &cycle_length_node)); } inputs.emplace_back(input_index++, cycle_length_node); Node* block_length_node; TF_RETURN_IF_ERROR(b->AddScalar(block_length_, &block_length_node)); inputs.emplace_back(input_index++, block_length_node); if (op_version_ >= 4) { Node* buffer_output_elements_node; TF_RETURN_IF_ERROR( b->AddScalar(buffer_output_elements_, &buffer_output_elements_node)); inputs.emplace_back(input_index++, buffer_output_elements_node); Node* prefetch_input_elements_node; TF_RETURN_IF_ERROR(b->AddScalar(prefetch_input_elements_, &prefetch_input_elements_node)); inputs.emplace_back(input_index++, prefetch_input_elements_node); } Node* num_parallel_calls_node; TF_RETURN_IF_ERROR( b->AddScalar(num_parallel_calls_, &num_parallel_calls_node)); inputs.emplace_back(input_index++, num_parallel_calls_node); std::vector<std::pair<StringPiece, AttrValue>> attrs; AttrValue f; b->BuildAttrValue(captured_func_->func(), &f); attrs.emplace_back(kFunc, f); AttrValue other_arguments_types_attr; b->BuildAttrValue(other_arguments_types, &other_arguments_types_attr); attrs.emplace_back(kTarguments, other_arguments_types_attr); if (op_version_ == 2) { AttrValue sloppy_attr; b->BuildAttrValue(deterministic_.IsNondeterministic(), &sloppy_attr); attrs.emplace_back(kSloppy, sloppy_attr); } if (op_version_ >= 3) { AttrValue deterministic_attr; b->BuildAttrValue(deterministic_.String(), &deterministic_attr); attrs.emplace_back(kDeterministic, deterministic_attr); } TF_RETURN_IF_ERROR(b->AddDataset(this, inputs, list_inputs, attrs, output)); return OkStatus(); } private: class ParallelInterleaveIterator : public DatasetIterator<Dataset> { public: ParallelInterleaveIterator(const Params& params, bool deterministic) : DatasetIterator<Dataset>(params), mu_(std::make_shared<mutex>()), num_parallel_calls_cond_var_(std::make_shared<condition_variable>()), num_parallel_calls_(std::make_shared<model::SharedState>( params.dataset->num_parallel_calls_, mu_, num_parallel_calls_cond_var_)), deterministic_(deterministic), current_elements_(params.dataset->cycle_length_) {} ~ParallelInterleaveIterator() override { CancelThreads(/*wait=*/true); } bool SymbolicCheckpointCompatible() const override { return deterministic_; } // TODO(jsimsa): Register cancellation callback once the implementation is // refactored not to hold mu_ while calling `GetNext` on the input. Status Initialize(IteratorContext* ctx) override { mutex_lock l(*mu_); interleave_depth_ = ctx->interleave_depth(); // Note that if `ctx->thread_pool()` is non-null, then instead of creating // a dedicated thread pool of size `num_threads`, computation will be // scheduled into the shared threadpool. The threadpool is guaranteed to // support `num_threads` concurrent tasks without blocking indefinitely. // // Allocate one thread for the worker manager, one thread for stats // collection, `cycle_length_` threads for the current workers, and // `future_elements_prefetch_` for the future workers. int max_current_workers = dataset()->cycle_length_; int future_workers = dataset()->prefetch_input_elements_ + dataset()->cycle_length_; int num_threads = 1 + max_current_workers + future_workers; if (ctx->stats_aggregator()) { num_threads++; } thread_pool_ = ctx->CreateThreadPool( "data_parallel_interleave_worker_pool", num_threads); if (num_parallel_calls_->value == model::kAutotune) { num_parallel_calls_->value = std::min( GetAutotuneDefaultParallelism(ctx), dataset()->cycle_length_); } cancellation_manager_ = std::make_unique<CancellationManager>(); IteratorContext::Params params(ctx); params.interleave_depth += 1; params.cancellation_manager = cancellation_manager_.get(); IteratorContext iter_ctx(std::move(params)); TF_RETURN_IF_ERROR(dataset()->input_->MakeIterator( &iter_ctx, this, prefix(), &input_impl_)); ctx->MergeCheckpoint(iter_ctx.checkpoint()); TF_RETURN_IF_ERROR(dataset()->captured_func_->Instantiate( ctx, &instantiated_captured_func_)); checkpoint_ = std::make_unique<MemoryCheckpoint>(ctx->id_registry()); if (ctx->warm_start() && !ctx->is_restoring()) { EnsureInitialElementsCreated(ctx); EnsureThreadsStarted(ctx); } return OkStatus(); } Status GetNextInternal(IteratorContext* ctx, std::vector<Tensor>* out_tensors, bool* end_of_sequence) override { std::shared_ptr<Result> result; { mutex_lock l(*mu_); EnsureInitialElementsCreated(ctx); EnsureThreadsStarted(ctx); while (!cancelled_ && !Consume(ctx, &result)) { RecordStop(ctx); if (deterministic_) { VLOG(3) << "Blocked waiting for element " << current_elements_[cycle_index_]->id; current_elements_[cycle_index_]->cond_var.wait(l); } else { any_element_available_cond_var_.wait(l); } RecordStart(ctx); } if (cancelled_) { return errors::Cancelled("Iterator was cancelled"); } if (result) { checkpoint_->Merge(&result->checkpoint); } } if (!result) { *end_of_sequence = true; return OkStatus(); } profiler::TraceMe traceme([&] { return profiler::TraceMeEncode("ParallelInterleaveConsume", {{"element_id", result->id}}); }); if (result->status.ok()) { *out_tensors = std::move(result->return_values); RecordBufferDequeue(ctx, *out_tensors); } *end_of_sequence = false; return result->status; } protected: std::shared_ptr<model::Node> CreateNode( IteratorContext* ctx, model::Node::Args args) const override { bool increase_min = GetExperiments().contains("min_outer_interleave_parallelism") && (ctx->interleave_depth() == 0); // When the `min_outer_interleave_parallelism` is enabled, we increase // the minimum parallelism based on empirical evidence (see // go/tf-data-max-autotuning for details). double min = increase_min ? std::min( static_cast<double>(dataset()->cycle_length_), std::ceil(std::pow(27 * dataset()->cycle_length_, 0.5))) : 1; return model::MakeAsyncInterleaveManyNode( std::move(args), {model::MakeParameter(kParallelism, num_parallel_calls_, /*min=*/min, /*max=*/dataset()->cycle_length_), model::MakeNonTunableParameter(kCycleLength, dataset()->cycle_length_), model::MakeNonTunableParameter(kDeterministic, deterministic_ ? 1.0 : 0.0), model::MakeNonTunableParameter( kMaxBufferedElements, ComputeMaxBufferedElements(dataset()->prefetch_input_elements_, dataset()->buffer_output_elements_, dataset()->cycle_length_))}); } Status SaveInternal(SerializationContext* ctx, IteratorStateWriter* writer) override { TF_RETURN_IF_ERROR(ctx->HandleCheckExternalStateStatus( dataset()->captured_func_->CheckExternalState())); mutex_lock l(*mu_); TF_RETURN_IF_ERROR(checkpoint_->Save(writer)); wait_for_checkpoint_ = true; // Wait for all in-flight calls to complete. while (num_active_workers_ > 0) { zero_active_workers_cond_var_.wait(l); } // Filter out elements with no input. for (auto& element : current_elements_) { if (element && element->no_input) { element.reset(); } } while (!future_elements_.empty() && future_elements_.back()->no_input) { future_elements_.pop_back(); } wait_for_checkpoint_ = false; DCHECK_EQ(num_active_workers_, 0); VLOG(4) << "State before save:\n" << DebugString(); TF_RETURN_IF_ERROR(SaveInput(ctx, writer, input_impl_)); TF_RETURN_IF_ERROR( writer->WriteScalar(prefix(), kBlockIndex, block_index_)); TF_RETURN_IF_ERROR( writer->WriteScalar(prefix(), kCycleIndex, cycle_index_)); TF_RETURN_IF_ERROR(writer->WriteScalar( prefix(), kEndOfInput, static_cast<int64_t>(end_of_input_))); TF_RETURN_IF_ERROR(writer->WriteScalar(prefix(), kElementIdCounter, element_id_counter_)); TF_RETURN_IF_ERROR(WriteCurrentElements(ctx, writer)); TF_RETURN_IF_ERROR(WriteFutureElements(ctx, writer)); // Wake workers back up. current_workers_cond_var_.notify_all(); future_workers_cond_var_.notify_all(); return OkStatus(); } Status RestoreInternal(IteratorContext* ctx, IteratorStateReader* reader) override { { mutex_lock l(*mu_); DCHECK(!threads_started_); DCHECK(!initial_elements_created_); TF_RETURN_IF_ERROR(RestoreInput(ctx, reader, input_impl_)); TF_RETURN_IF_ERROR( reader->ReadScalar(prefix(), kBlockIndex, &block_index_)); TF_RETURN_IF_ERROR( reader->ReadScalar(prefix(), kCycleIndex, &cycle_index_)); TF_RETURN_IF_ERROR(reader->ReadScalar(prefix(), kElementIdCounter, &element_id_counter_)); int64_t end_of_input; TF_RETURN_IF_ERROR( reader->ReadScalar(prefix(), kEndOfInput, &end_of_input)); end_of_input_ = static_cast<bool>(end_of_input); } TF_RETURN_IF_ERROR(ReadCurrentElements(ctx, reader)); TF_RETURN_IF_ERROR(ReadFutureElements(ctx, reader)); mutex_lock l(*mu_); initial_elements_created_ = false; for (int i = 0; i < current_elements_.size(); ++i) { int index = (cycle_index_ + i) % current_elements_.size(); auto element = current_elements_[index]; if (element) { elements_to_process_.push_back(index); element->initialized = true; element->cycle_index = index; initial_elements_created_ = true; } } for (const auto& element : future_elements_) { element->initialized = true; } last_valid_current_element_ = current_elements_.size() - 1; while (last_valid_current_element_ >= 0 && !current_elements_[last_valid_current_element_]) { last_valid_current_element_--; } if (ctx->warm_start()) { EnsureInitialElementsCreated(ctx); EnsureThreadsStarted(ctx); } VLOG(2) << "Parallel interleave iterator restored"; VLOG(4) << "State after restore:\n" << DebugString(); return OkStatus(); } TraceMeMetadata GetTraceMeMetadata() const override { int64_t parallelism = -1; int64_t results_ready = -1; int64_t active_elements = -1; // NOTE: We only set the parallelism value if the lock can be acquired // right away to avoid introducing tracing overhead. if (mu_->try_lock()) { parallelism = num_parallel_calls_->value; results_ready = 0; active_elements = 0; for (int i = 0; i < current_elements_.size(); ++i) { if (current_elements_[i]) { results_ready += current_elements_[i]->results.size(); if (current_elements_[i]->active) { active_elements++; } } } mu_->unlock(); } auto result = dataset()->traceme_metadata_; result.push_back(std::make_pair( "parallelism", parallelism == -1 ? kTraceInfoUnavailable : strings::Printf("%lld", static_cast<long long>(parallelism)))); result.push_back(std::make_pair( "results_ready", results_ready == -1 ? kTraceInfoUnavailable : strings::Printf("%lld", static_cast<long long>( results_ready)))); result.push_back(std::make_pair( "active_elements", results_ready == -1 ? kTraceInfoUnavailable : strings::Printf("%lld", static_cast<long long>( active_elements)))); result.push_back(std::make_pair( "interleave_depth", strings::Printf("%lld", static_cast<long long>(interleave_depth_)))); return result; } private: // Represents the result of fetching an element from a dataset. struct Result { explicit Result(IteratorContext* ctx) : checkpoint(MemoryCheckpoint{ctx->id_registry()}) {} Status status; int64_t id = -1; std::vector<Tensor> return_values; MemoryCheckpoint checkpoint; }; // The interleave transformation repeatedly inputs elements, applies the // user-provided function to transform the input elements to datasets, and // interleaves the elements of these datasets as its output. // // This structure represents an input element and derived state. struct Element { // Unique identifier, needed to support checkpointing. int64_t id TF_GUARDED_BY(&ParallelInterleaveIterator::mu_); // The actual input element. Iterator created from the input element. A // null value indicates that the element either reached end of input or // hasn't been initialized yet. std::unique_ptr<std::vector<Tensor>> inputs TF_GUARDED_BY(&ParallelInterleaveIterator::mu_); // Iterator created from the input element. A null value indicates that // the element either reached end of input or hasn't been initialized yet. std::unique_ptr<IteratorBase> iterator TF_GUARDED_BY(&ParallelInterleaveIterator::mu_); // Buffer for storing the outputs of `iterator`. std::deque<std::shared_ptr<Result>> TF_GUARDED_BY( &ParallelInterleaveIterator::mu_) results; // The element's index in the cycle, if it is in the current cycle. // -1 if the element is not in the current cycle. int64_t cycle_index TF_GUARDED_BY(&ParallelInterleaveIterator::mu_) = -1; // Whether the element is currently being processed by a worker thread. // This is used to ensure that only one thread at a time tries to process // an element. bool active TF_GUARDED_BY(&ParallelInterleaveIterator::mu_) = false; // Whether the inputs and iterator have been initialized. bool initialized TF_GUARDED_BY(&ParallelInterleaveIterator::mu_) = false; // Whether we tried to initialize the element, but the input iterator // was exhausted so we could produce no inputs. bool no_input TF_GUARDED_BY(&ParallelInterleaveIterator::mu_) = false; // Condition variable for communicating between current worker threads // and GetNext. condition_variable cond_var; std::string DebugString() TF_EXCLUSIVE_LOCKS_REQUIRED(&ParallelInterleaveIterator::mu_) { return absl::StrFormat( "Element(id: %d, iterator_null: %d, results_size: %d, " "cycle_index: %d, active: %d, initialized: %d, no_input: %d)", id, iterator == nullptr, results.size(), cycle_index, active, initialized, no_input); } }; // Sets the cancellation bit and wakes up all threads that need to be // cancelled. Optionally, the method waits until all threads finish // executing. void CancelThreads(bool wait) TF_LOCKS_EXCLUDED(mu_) { cancellation_manager_->StartCancel(); mutex_lock l(*mu_); cancelled_ = true; // Wake up all threads so that they can exit. This will also wake up any // threads waiting in GetNextInternal. for (const auto& element : current_elements_) { if (element) { element->cond_var.notify_all(); } } current_workers_cond_var_.notify_all(); future_workers_cond_var_.notify_all(); num_parallel_calls_cond_var_->notify_all(); stats_thread_cond_var_.notify_all(); while (wait && outstanding_threads_ > 0) { outstanding_threads_finished_cond_var_.wait(l); } any_element_available_cond_var_.notify_all(); zero_active_workers_cond_var_.notify_all(); } void EnsureInitialElementsCreated(IteratorContext* ctx) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { if (!initial_elements_created_) { for (int i = 0; i < dataset()->cycle_length_; ++i) { current_elements_[i] = MakeElement(ctx); if (!current_elements_[i]) { break; } current_elements_[i]->cycle_index = i; elements_to_process_.push_back(i); last_valid_current_element_ = i; } initial_elements_created_ = true; } } void EnsureThreadsStarted(IteratorContext* ctx) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { if (!threads_started_) { IncrementOutstandingThreads(); auto ctx_copy = std::make_shared<IteratorContext>(*ctx); thread_pool_->Schedule( [this, ctx_copy]() { WorkerManagerThread(ctx_copy); }); if (ctx->stats_aggregator()) { IncrementOutstandingThreads(); thread_pool_->Schedule([this, ctx_copy]() { StatsThread(ctx_copy); }); } threads_started_ = true; } } // Advances the position in the interleave cycle to the next cycle // element. void AdvanceToNextInCycle() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { DCHECK_NE(last_valid_current_element_, -1); block_index_ = 0; cycle_index_ = (cycle_index_ + 1) % (last_valid_current_element_ + 1); } // Advances the position in the interleave cycle by one. void AdvancePosition() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { ++block_index_; if (block_index_ == dataset()->block_length_) { AdvanceToNextInCycle(); } } // Consumes a result (if available), returning an indication of whether // a result is available. If `true` is returned, `result` either // points to a valid result or is null if end of input has been reached. bool Consume(IteratorContext* ctx, std::shared_ptr<Result>* result) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { if (deterministic_) { return ConsumeHelper(ctx, result); } // If we are allowed to be nondeterministic (i.e. return results out of // order), try to find an element in the cycle that has a result // available. for (int i = 0; i < dataset()->cycle_length_; ++i) { if (ConsumeHelper(ctx, result)) { return true; } AdvanceToNextInCycle(); } return false; } // Consumes a result (if available), returning an indication of whether // a result is available. If `true` is returned, `result` either // points to a valid result or is null if end of input has been reached. bool ConsumeHelper(IteratorContext* ctx, std::shared_ptr<Result>* result) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { while (true) { if (last_valid_current_element_ == -1) { // Reached end of input. return true; } for (int64_t i = 0; i < (last_valid_current_element_ + 1); ++i) { int64_t index = (cycle_index_ + i) % (last_valid_current_element_ + 1); if (current_elements_[index]) { cycle_index_ = index; if (i > 0) { block_index_ = 0; } break; } } DCHECK(current_elements_[cycle_index_]); std::shared_ptr<Element> element = current_elements_[cycle_index_]; if (!element->results.empty()) { // We found a result. std::swap(*result, element->results.front()); element->results.pop_front(); if (!element->active) { elements_to_process_.push_back(cycle_index_); current_workers_cond_var_.notify_one(); } AdvancePosition(); return true; } if (!element->initialized || element->iterator) { // The element is still producing results, so we wait. return false; } // We've consumed all results from the element. Get a new element from // future_elements, or create a new element if no future elements are // available. if (!future_elements_.empty()) { std::shared_ptr<Element> future_element = std::move(future_elements_.front()); future_elements_.pop_front(); if (future_element->iterator) { EnableAutotune(ctx, future_element->iterator.get()); } future_element->cycle_index = cycle_index_; current_elements_[cycle_index_] = std::move(future_element); future_workers_cond_var_.notify_one(); if (!current_elements_[cycle_index_]->active) { current_workers_cond_var_.notify_one(); } } else { current_elements_[cycle_index_] = MakeElement(ctx); if (current_elements_[cycle_index_]) { current_elements_[cycle_index_]->cycle_index = cycle_index_; elements_to_process_.push_back(cycle_index_); element->cycle_index = cycle_index_; current_workers_cond_var_.notify_one(); } while (last_valid_current_element_ >= 0 && !current_elements_[last_valid_current_element_]) { last_valid_current_element_--; if (cycle_index_ > last_valid_current_element_) { // We are about to move the cycle index below in // AdvanceToNextInCycle(). cycle_index_ = last_valid_current_element_; } } } if (last_valid_current_element_ != -1) { AdvanceToNextInCycle(); } } } // Creates a new element. std::shared_ptr<Element> MakeElement(IteratorContext* ctx) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { if (end_of_input_) { return nullptr; } auto element = std::make_shared<Element>(); element->id = element_id_counter_++; InitializeInput(ctx, *element); return element; } // Thread responsible for launching all worker threads. The thread stays // around after startup in case autotuning increases num_parallel_calls. void WorkerManagerThread(std::shared_ptr<IteratorContext> ctx) TF_LOCKS_EXCLUDED(mu_) { RecordStart(ctx.get()); auto cleanup = gtl::MakeCleanup([&]() { RecordStop(ctx.get()); mutex_lock l(*mu_); DecrementOutstandingThreads(); }); int initial_current_workers; // When elements are moved from `future_elements_` to `current_elements_`, // the future worker which created the element may continue to process // the element for some time. That is why we need an additional // `cycle_length_` future workers to guarantee that whenever // `future_element_.size() < future_elements_prefetch_`, there will be a // future worker available to create a new future element. int future_workers = dataset()->prefetch_input_elements_ + dataset()->cycle_length_; { mutex_lock l(*mu_); initial_current_workers = num_parallel_calls_->value; outstanding_threads_ += initial_current_workers + future_workers; num_current_workers_ += initial_current_workers; num_active_workers_ += initial_current_workers + future_workers; num_current_active_workers_ += initial_current_workers; } // Start current workers before future workers to improve startup time. for (int i = 0; i < initial_current_workers; ++i) { StartCurrentWorkerThread(ctx); } for (int i = 0; i < future_workers; ++i) { StartFutureWorkerThread(ctx); } while (true) { { mutex_lock l(*mu_); while (!cancelled_ && num_current_workers_ >= num_parallel_calls_->value) { RecordStop(ctx.get()); num_parallel_calls_cond_var_->wait(l); RecordStart(ctx.get()); } if (cancelled_ || end_of_input_) { return; } IncrementOutstandingThreads(); IncrementCurrentWorkers(); IncrementActiveWorkers(); IncrementCurrentActiveWorkers(); StartCurrentWorkerThread(ctx); } } } void StartCurrentWorkerThread(std::shared_ptr<IteratorContext> ctx) { thread_pool_->Schedule([this, ctx]() { CurrentWorkerThread(ctx); }); } void StartFutureWorkerThread(std::shared_ptr<IteratorContext> ctx) { thread_pool_->Schedule([this, ctx]() { FutureWorkerThread(ctx); }); } // Current workers are responsible for keeping elements in // `current_elements_` processed. An element is processed if it is either // done or its `results` buffer is full (contains `kPerIteratorPrefetch` // elements). // // Current workers cycle between two phases: (1) finding an element and (2) // processing it. When a worker is processing an element, it will // claim the element by setting `element->active`, then continue to produce // results for the element until enough results have been computed for the // current cycle and the results buffer is full. void CurrentWorkerThread(std::shared_ptr<IteratorContext> ctx) TF_LOCKS_EXCLUDED(mu_) { RecordStart(ctx.get()); auto done = [&]() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { RecordStop(ctx.get()); DecrementActiveWorkers(); DecrementCurrentActiveWorkers(); DecrementOutstandingThreads(); DecrementCurrentWorkers(); }; while (true) { int element_index; std::shared_ptr<Element> element; // Find an element to process. { mutex_lock l(*mu_); // In case autotune changes num_parallel_calls. if (num_current_workers_ > num_parallel_calls_->value) { done(); return; } // Look for an element that needs processing. element.reset(); while (!cancelled_) { while (!elements_to_process_.empty() && !wait_for_checkpoint_) { int index = elements_to_process_.front(); elements_to_process_.pop_front(); auto& e = current_elements_[index]; if (NeedsProcessing(e) && !e->active) { element_index = index; element = e; break; } } if (element) { break; } DecrementCurrentActiveWorkers(); WaitWorkerThread(ctx.get(), &current_workers_cond_var_, &l); IncrementCurrentActiveWorkers(); } if (cancelled_) { done(); return; } VLOG(3) << "Current worker woke up to process " << element->id; element->active = true; } // Loop on the element until we fill its results buffer or reach end of // input for the element. while (true) { ProcessElement(ctx.get(), element); { mutex_lock l(*mu_); // Check whether we have produced enough results for the current // cycle. if (!NeedsProcessing(element)) { element->active = false; break; } } } } } // Future workers process elements after the current interleave cycle. A // future worker's job is to keep `future_elements_` filled with elements. // Elements in `future_elements` have had their first `kPerIteratorPrefetch` // results computed. void FutureWorkerThread(std::shared_ptr<IteratorContext> ctx) TF_LOCKS_EXCLUDED(mu_) { RecordStart(ctx.get()); auto done = [&]() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { RecordStop(ctx.get()); DecrementActiveWorkers(); DecrementOutstandingThreads(); }; std::shared_ptr<Element> element; while (true) { { mutex_lock l(*mu_); if (element) { element->active = false; if (element->cycle_index != -1) { element->cond_var.notify_one(); // A current worker may need to process the element further. elements_to_process_.push_back(element->cycle_index); current_workers_cond_var_.notify_one(); } } while (!cancelled_ && (future_elements_.size() >= dataset()->prefetch_input_elements_ || wait_for_checkpoint_)) { WaitWorkerThread(ctx.get(), &future_workers_cond_var_, &l); } if (cancelled_) { done(); return; } element = MakeElement(ctx.get()); if (!element) { done(); return; } VLOG(3) << "Future worker created element " << element->id; element->active = true; future_elements_.push_back(element); } ProcessElement(ctx.get(), element); } } // Generates results for the given element until the element's results // buffer is full or the element is done producing results. void ProcessElement(IteratorContext* ctx, std::shared_ptr<Element> element) TF_LOCKS_EXCLUDED(mu_) { DCHECK(element != nullptr); IteratorBase* iterator; int64_t input_element_id; // Initialize the inputs and iterator if necessary. { mutex_lock l(*mu_); DCHECK(element->active); if (!element->iterator) { return; } input_element_id = element->id; // `iterator` will remain valid after releasing the lock because we have // marked the element as active, so no other thread will modify its // iterator. iterator = element->iterator.get(); } DCHECK(iterator != nullptr); // Process until the results queue is full or we reach end of input. while (true) { auto result = std::make_shared<Result>(ctx); profiler::TraceMe traceme([&] { result->id = profiler::TraceMe::NewActivityId(); return profiler::TraceMeEncode( "ParallelInterleaveProduce", {{"input_element_id", input_element_id}, {"element_id", result->id}}); }); bool end_of_input = false; IteratorContext nested_ctx = MakeNestedIteratorContext(ctx); result->status = iterator->GetNext(&nested_ctx, &result->return_values, &end_of_input); result->checkpoint.Merge(nested_ctx.checkpoint()); if (result->status.ok() && end_of_input) { mutex_lock l(*mu_); element->iterator.reset(); // If symbolic checkpointing is enabled, element inputs can only be // garbage collected after all element results have been consumed. if (!ctx->symbolic_checkpoint()) { element->inputs.reset(); } NotifyElementUpdate(*element); break; } RecordBufferEnqueue(ctx, result->return_values); mutex_lock l(*mu_); element->results.push_back(std::move(result)); NotifyElementUpdate(*element); if (element->results.size() == dataset()->buffer_output_elements_) { break; } } } void InitializeInput(IteratorContext* ctx, Element& element) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { element.initialized = true; // Check if we've already reached end of input. if (end_of_input_) { element.no_input = true; NotifyElementUpdate(element); return; } profiler::TraceMe traceme([input_element_id = element.id] { return profiler::TraceMeEncode( "ParallelInterleaveInitializeInput", {{"input_element_id", input_element_id}}); }); std::vector<Tensor> inputs; // TODO(aaudibert): Refactor the implementation to move calls of // `GetNext` out of the scope of `mu_`. Status status = input_impl_->GetNext(ctx, &inputs, &end_of_input_); checkpoint_->Merge(ctx->checkpoint()); if (!status.ok()) { AddErrorResult(ctx, element, status); return; } if (end_of_input_) { element.no_input = true; NotifyElementUpdate(element); return; } element.inputs = std::make_unique<std::vector<Tensor>>(std::move(inputs)); IteratorContext::Params params(ctx); params.interleave_depth += 1; IteratorContext nested_ctx(params); status = MakeIteratorFromInputElement( &nested_ctx, this, *element.inputs, element.id, *instantiated_captured_func_, prefix(), &element.iterator, model_node()); checkpoint_->Merge(nested_ctx.checkpoint()); if (!status.ok()) { element.inputs.reset(); element.iterator.reset(); AddErrorResult(ctx, element, status); return; } if (element.cycle_index == -1) { DisableAutotune(ctx, element.iterator.get()); } } // Adds an error result for the given element. void AddErrorResult(IteratorContext* ctx, Element& element, Status status) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { auto result = std::make_shared<Result>(ctx); result->status = status; element.results.push_back(std::move(result)); NotifyElementUpdate(element); } // Cancels all threads (including the manager) and waits for them to finish. void StopAllThreads(mutex_lock* l) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) {} // Waits on the given cond_var in a worker thread. void WaitWorkerThread(IteratorContext* ctx, condition_variable* cond_var, mutex_lock* l) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { DecrementActiveWorkers(); RecordStop(ctx); cond_var->wait(*l); RecordStart(ctx); IncrementActiveWorkers(); } void NotifyElementUpdate(Element& element) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { if (deterministic_) { element.cond_var.notify_one(); } else { any_element_available_cond_var_.notify_one(); } } bool NeedsProcessing(const std::shared_ptr<Element>& element) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { if (!element) { return false; } if (!element->initialized) { return true; } return element->iterator && element->results.size() < dataset()->buffer_output_elements_; } inline void IncrementCurrentWorkers() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { num_current_workers_++; } inline void DecrementCurrentWorkers() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { num_current_workers_--; } inline void IncrementActiveWorkers() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { num_active_workers_++; } inline void DecrementActiveWorkers() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { num_active_workers_--; if (num_active_workers_ == 0) { zero_active_workers_cond_var_.notify_one(); } } inline void IncrementCurrentActiveWorkers() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { num_current_active_workers_++; } inline void DecrementCurrentActiveWorkers() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { num_current_active_workers_--; } inline void IncrementOutstandingThreads() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { outstanding_threads_++; } inline void DecrementOutstandingThreads() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { outstanding_threads_--; if (outstanding_threads_ == 0) { outstanding_threads_finished_cond_var_.notify_one(); } } void StatsThread(std::shared_ptr<IteratorContext> ctx) { for (int64_t step = 0;; ++step) { int num_current_active_workers; int num_current_workers; { mutex_lock l(*mu_); if (step != 0 && !cancelled_) { stats_thread_cond_var_.wait_for( l, std::chrono::milliseconds(kStatsReportingPeriodMillis)); } if (cancelled_) { DecrementOutstandingThreads(); return; } num_current_active_workers = num_current_active_workers_; num_current_workers = num_current_workers_; } if (num_current_workers == 0) { // Avoid division by zero. num_current_workers = 1; } ctx->stats_aggregator()->AddScalar( stats_utils::ThreadUtilizationScalarName(dataset()->node_name()), static_cast<float>(num_current_active_workers) / static_cast<float>(num_current_workers), step); } } Status WriteStatusLocked(IteratorStateWriter* writer, const string& iterator_name, size_t idx, const Status& status) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { TF_RETURN_IF_ERROR(writer->WriteScalar( iterator_name, CodeKey(idx), static_cast<int64_t>(status.code()))); if (!status.ok()) { TF_RETURN_IF_ERROR(writer->WriteScalar(iterator_name, ErrorMessageKey(idx), std::string(status.message()))); } return OkStatus(); } Status ReadStatusLocked(IteratorStateReader* reader, const string& iterator_name, size_t idx, Status* status) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { int64_t code_int; TF_RETURN_IF_ERROR( reader->ReadScalar(iterator_name, CodeKey(idx), &code_int)); absl::StatusCode code = static_cast<absl::StatusCode>(code_int); if (code != absl::StatusCode::kOk) { tstring error_message; TF_RETURN_IF_ERROR(reader->ReadScalar( iterator_name, ErrorMessageKey(idx), &error_message)); *status = Status(code, error_message); } else { *status = OkStatus(); } return OkStatus(); } string CodeKey(size_t idx) { return absl::StrCat(kResultsSuffix, "[", idx, "]", kCodeSuffix); } string ErrorMessageKey(size_t idx) { return absl::StrCat(kResultsSuffix, "[", idx, "]", kErrorMessageSuffix); } Status WriteElement(SerializationContext* ctx, std::shared_ptr<Element> element, const string& key_prefix, IteratorStateWriter* writer) TF_EXCLUSIVE_LOCKS_REQUIRED(*mu_) { if (element->iterator || (ctx->symbolic_checkpoint() && !element->results.empty())) { TF_RETURN_IF_ERROR(SaveInput(ctx, writer, element->iterator)); TF_RETURN_IF_ERROR( writer->WriteScalar(key_prefix, kIdSuffix, element->id)); TF_RETURN_IF_ERROR(writer->WriteScalar( key_prefix, absl::StrCat(kInputsSuffix, kSizeSuffix), element->inputs->size())); for (int i = 0; i < element->inputs->size(); i++) { TF_RETURN_IF_ERROR(writer->WriteTensor( key_prefix, absl::StrCat(kInputsSuffix, "[", i, "]"), element->inputs->at(i))); } TF_RETURN_IF_ERROR(writer->WriteScalar(key_prefix, kRestoreIterator, static_cast<int64_t>(true))); } else { TF_RETURN_IF_ERROR(writer->WriteScalar(key_prefix, kRestoreIterator, static_cast<int64_t>(false))); } if (ctx->symbolic_checkpoint()) { return writer->WriteScalar( key_prefix, absl::StrCat(kResultsSuffix, kSizeSuffix), 0); } TF_RETURN_IF_ERROR(writer->WriteScalar( key_prefix, absl::StrCat(kResultsSuffix, kSizeSuffix), element->results.size())); for (size_t i = 0; i < element->results.size(); i++) { std::shared_ptr<Result> result = element->results[i]; TF_RETURN_IF_ERROR( WriteStatusLocked(writer, key_prefix, i, result->status)); TF_RETURN_IF_ERROR(writer->WriteScalar( key_prefix, absl::StrCat(kResultsSuffix, "[", i, "]", kSizeSuffix), result->return_values.size())); for (size_t j = 0; j < result->return_values.size(); j++) { TF_RETURN_IF_ERROR(writer->WriteTensor( key_prefix, absl::StrCat(kResultsSuffix, "[", i, "][", j, "]"), result->return_values[j])); } TF_RETURN_IF_ERROR(writer->WriteScalar( key_prefix, absl::StrCat(kResultsSuffix, "[", i, "]", kIsReadySuffix), "")); } return OkStatus(); } Status WriteCurrentElements(SerializationContext* ctx, IteratorStateWriter* writer) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { TF_RETURN_IF_ERROR(writer->WriteScalar(prefix(), kCurrentElementsSize, current_elements_.size())); for (int idx = 0; idx < current_elements_.size(); idx++) { const auto& key_prefix = absl::StrCat(prefix(), "::", kCurrentElements, "::", idx); TF_RETURN_IF_ERROR( writer->WriteScalar(key_prefix, kElementUninitialized, static_cast<int64_t>(!current_elements_[idx]))); if (current_elements_[idx]) { TF_RETURN_IF_ERROR( WriteElement(ctx, current_elements_[idx], key_prefix, writer)); } } return OkStatus(); } Status WriteFutureElements(SerializationContext* ctx, IteratorStateWriter* writer) TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { TF_RETURN_IF_ERROR(writer->WriteScalar(prefix(), kFutureElementsSize, future_elements_.size())); for (int idx = 0; idx < future_elements_.size(); idx++) { const auto& key_prefix = absl::StrCat(prefix(), "::", kFutureElements, "::", idx); TF_RETURN_IF_ERROR( writer->WriteScalar(key_prefix, kElementUninitialized, static_cast<int64_t>(!future_elements_[idx]))); if (future_elements_[idx]) { TF_RETURN_IF_ERROR( WriteElement(ctx, future_elements_[idx], key_prefix, writer)); } } return OkStatus(); } Status ReadElement(IteratorContext* ctx, IteratorStateReader* reader, int idx, const string& key_prefix, std::shared_ptr<Element>* out) { int64_t element_uninitialized; TF_RETURN_IF_ERROR(reader->ReadScalar(key_prefix, kElementUninitialized, &element_uninitialized)); if (static_cast<bool>(element_uninitialized)) { return OkStatus(); } std::unique_ptr<IteratorBase> iterator; auto element = std::make_shared<Element>(); { mutex_lock l(*mu_); int64_t results_size; TF_RETURN_IF_ERROR(reader->ReadScalar( key_prefix, absl::StrCat(kResultsSuffix, kSizeSuffix), &results_size)); element->results.resize(results_size); for (size_t i = 0; i < results_size; i++) { auto result = std::make_shared<Result>(ctx); TF_RETURN_IF_ERROR( ReadStatusLocked(reader, key_prefix, i, &result->status)); int64_t num_return_values; TF_RETURN_IF_ERROR(reader->ReadScalar( key_prefix, absl::StrCat(kResultsSuffix, "[", i, "]", kSizeSuffix), &num_return_values)); result->return_values.reserve(num_return_values); for (size_t j = 0; j < num_return_values; j++) { result->return_values.emplace_back(); TF_RETURN_IF_ERROR(reader->ReadTensor( ctx->flr(), key_prefix, absl::StrCat(kResultsSuffix, "[", i, "][", j, "]"), &result->return_values.back())); } RecordBufferEnqueue(ctx, result->return_values); element->results[i] = std::move(result); } int64_t restore_iterator; TF_RETURN_IF_ERROR(reader->ReadScalar(key_prefix, kRestoreIterator, &restore_iterator)); if (static_cast<bool>(!restore_iterator)) { element->iterator.reset(); *out = std::move(element); return OkStatus(); } int64_t inputs_size; TF_RETURN_IF_ERROR(reader->ReadScalar( key_prefix, absl::StrCat(kInputsSuffix, kSizeSuffix), &inputs_size)); element->inputs = std::make_unique<std::vector<Tensor>>(inputs_size); for (int i = 0; i < inputs_size; i++) { TF_RETURN_IF_ERROR(reader->ReadTensor( ctx->flr(), key_prefix, absl::StrCat(kInputsSuffix, "[", i, "]"), &element->inputs->at(i))); } TF_RETURN_IF_ERROR( reader->ReadScalar(key_prefix, kIdSuffix, &element->id)); IteratorContext::Params params(ctx); params.interleave_depth += 1; IteratorContext ctx_copy(params); TF_RETURN_IF_ERROR(MakeIteratorFromInputElement( &ctx_copy, this, *element->inputs, element->id, *instantiated_captured_func_.get(), prefix(), &iterator, model_node())); } IteratorContext nested_ctx = MakeNestedIteratorContext(ctx); TF_RETURN_IF_ERROR(RestoreInput(&nested_ctx, reader, iterator)); ctx->MergeCheckpoint(nested_ctx.checkpoint()); mutex_lock l(*mu_); element->iterator = std::move(iterator); *out = std::move(element); return OkStatus(); } Status ReadCurrentElements(IteratorContext* ctx, IteratorStateReader* reader) { int64_t size; { mutex_lock l(*mu_); TF_RETURN_IF_ERROR( reader->ReadScalar(prefix(), kCurrentElementsSize, &size)); if (current_elements_.size() != size) { // This could mean two things: (1) the user created their checkpoint // from a dataset with one cycle_length, then changed the cycle_length // and tried to restore from the old checkpoint, or (2) the user set // the cycle length to tf.data.AUTOTUNE, wrote the checkpoint from one // machine, then tried to restore the checkpoint on another machine // with a different CPU budget (causing autotune to pick a different // cycle length). return errors::FailedPrecondition( "The iterator cycle length ", current_elements_.size(), " is different from the cycle length to restore from the " "checkpoint: ", size); } } if (size == 0) { return OkStatus(); } std::vector<std::shared_ptr<Element>> elements; TF_RETURN_IF_ERROR( ReadElementsParallel(ctx, reader, size, kCurrentElements, &elements)); mutex_lock l(*mu_); for (auto& element : current_elements_) { DCHECK(element == nullptr); } for (int idx = 0; idx < size; ++idx) { current_elements_[idx] = std::move(elements[idx]); } return OkStatus(); } Status ReadFutureElements(IteratorContext* ctx, IteratorStateReader* reader) { int64_t size; { mutex_lock l(*mu_); TF_RETURN_IF_ERROR( reader->ReadScalar(prefix(), kFutureElementsSize, &size)); future_elements_.resize(size); } if (size == 0) { return OkStatus(); } std::vector<std::shared_ptr<Element>> elements; TF_RETURN_IF_ERROR( ReadElementsParallel(ctx, reader, size, kFutureElements, &elements)); mutex_lock l(*mu_); for (auto& element : future_elements_) { DCHECK(element == nullptr); } for (int idx = 0; idx < size; ++idx) { future_elements_[idx] = std::move(elements[idx]); } return OkStatus(); } Status ReadElementsParallel( IteratorContext* ctx, IteratorStateReader* reader, int64_t size, const string& name, std::vector<std::shared_ptr<Element>>* elements) { elements->resize(size); Status s = OkStatus(); BlockingCounter counter(size); for (int idx = 0; idx < size; ++idx) { thread_pool_->Schedule([this, ctx, reader, idx, name, &s, &counter, elements] { RecordStart(ctx); auto cleanup = gtl::MakeCleanup([this, ctx, &counter]() { RecordStop(ctx); counter.DecrementCount(); }); std::shared_ptr<Element> elem; const auto& key_prefix = absl::StrCat(prefix(), "::", name, "::", idx); IteratorContext ctx_copy(ctx); Status ret_status = ReadElement(&ctx_copy, reader, idx, key_prefix, &elem); mutex_lock l(*mu_); ctx->MergeCheckpoint(ctx_copy.checkpoint()); if (cancelled_) { s.Update(errors::Cancelled("Cancelled in ReadElementsParallel")); return; } if (!ret_status.ok()) { s.Update(ret_status); return; } (*elements)[idx] = elem; }); } counter.Wait(); return s; } std::string DebugString() TF_EXCLUSIVE_LOCKS_REQUIRED(mu_) { std::string result; result.append(strings::StrCat("Cycle index: ", cycle_index_, "\n")); result.append(strings::StrCat("Block index: ", block_index_, "\n")); result.append(strings::StrCat("End of input: ", end_of_input_, "\n")); { result.append("Current elements:\n"); for (int i = 0; i < current_elements_.size(); ++i) { string element_string = "null"; if (current_elements_[i]) { element_string = current_elements_[i]->DebugString(); } result.append(absl::StrFormat("%d: %s\n", i, element_string)); } } { result.append("Future elements:\n"); for (int i = 0; i < future_elements_.size(); ++i) { string element_string = "null"; if (future_elements_[i]) { element_string = future_elements_[i]->DebugString(); } result.append(absl::StrFormat("%d: %s\n", i, element_string)); } } return result; } // Indices of `current_elements_` which need to be processed by a current // worker. std::deque<int> elements_to_process_; // The last index in `current_elements_` containing a non-null element. // This allows us to optimize the situation when the cycle_length is large // but the input dataset doesn't have many elements. By tracking the index // of the last valid element, GetNext can avoid checking many null entries // each time through the cycle. // // TODO(aaudibert): Generalize this optimization by removing null elements // from `current_elements_`, e.g. by compacting the vector when x% of // its elements are null. int64_t last_valid_current_element_ TF_GUARDED_BY(mu_) = -1; // Identifies whether the current_elements_ vector has been initialized. bool initial_elements_created_ TF_GUARDED_BY(mu_) = false; // Identifies whether the element threads have been started. bool threads_started_ TF_GUARDED_BY(mu_) = false; // Used for coordination between the main thread, the manager threads, and // the worker threads. // // NOTE: We should never call GetNext on the input while holding this mutex. const std::shared_ptr<mutex> mu_; // Condition variable for waking up current workers. condition_variable current_workers_cond_var_; // Condition variable for waking up future workers. condition_variable future_workers_cond_var_; // Condition variable for waking up the stats thread. condition_variable stats_thread_cond_var_; // Number of active worker threads which might be processing elements, // including both current workers and future workers. Used by // checkpointing to wait for outstanding work to finish. int num_active_workers_ TF_GUARDED_BY(mu_) = 0; // Number of active current worker threads. int num_current_active_workers_ TF_GUARDED_BY(mu_) = 0; // Condition variable notified whenever the total number of active workers // drops to zero. Used for checkpointing. condition_variable zero_active_workers_cond_var_; // Condition notified whenever num_parallel_calls_ changes. Shared so that // autotuning can notify us when num_parallel_calls_ changes. std::shared_ptr<condition_variable> num_parallel_calls_cond_var_; // Identifies the maximum number of parallel calls. const std::shared_ptr<model::SharedState> num_parallel_calls_; // The number of current workers currently alive or scheduled to be started. // This includes current workers which are blocked waiting for work. int num_current_workers_ TF_GUARDED_BY(mu_) = 0; // Condition variable to signal that a result has been produced by some // element thread. Only used when `deterministic` is false. condition_variable any_element_available_cond_var_; // Determines whether outputs can be produced in deterministic order. const bool deterministic_; // Controls cancellation of `input_impl_`. Must be ordered before // `input_impl_` so that `input_impl_` is destroyed first. std::unique_ptr<CancellationManager> cancellation_manager_; // Iterator for input elements. std::unique_ptr<IteratorBase> input_impl_ TF_GUARDED_BY(mu_); // Identifies position in the interleave cycle. int64_t block_index_ TF_GUARDED_BY(mu_) = 0; // It is an invariant that either `last_valid_current_element_ == -1` or // `cycle_index_ <= last_valid_current_element_`. int64_t cycle_index_ TF_GUARDED_BY(mu_) = 0; // Elements of the current interleave cycle. std::vector<std::shared_ptr<Element>> current_elements_ TF_GUARDED_BY(mu_); // Elements to be used in the interleave cycle in the future. The element // at the front is the next element to add to the interleave cycle when a // current element is exhausted. std::deque<std::shared_ptr<Element>> future_elements_ TF_GUARDED_BY(mu_); // Identifies whether the global end of input has been reached. bool end_of_input_ TF_GUARDED_BY(mu_) = false; // The number of outstanding element threads. int outstanding_threads_ TF_GUARDED_BY(mu_) = 0; // Condition variable notified when outstanding_threads_ drops to 0. condition_variable outstanding_threads_finished_cond_var_; std::unique_ptr<thread::ThreadPool> thread_pool_; int64_t element_id_counter_ TF_GUARDED_BY(mu_) = 0; // Set to true during checkpointing to alert element threads that they // should pause operation. This is needed to prevent constantly-active // worker threads from blocking checkpointing indefinitely. bool wait_for_checkpoint_ = false; std::unique_ptr<InstantiatedCapturedFunction> instantiated_captured_func_; // Identifies whether background threads should be cancelled. bool cancelled_ TF_GUARDED_BY(mu_) = false; // Records the number of ParallelInterleave operations in the path from the // root node to this node (not including this node) in the input pipeline // tree. We record the interleave depth so that it can be included in the // trace metadata. int64 interleave_depth_ = -1; // The implementation of symbolic checkpointing of parallel interleave is // different from all other transformations. // // Unlike synchronous transformations which simply propagate state through // the `IteratorContext` provided by their caller, parallel interleave // executes asynchronously. However, unlike other asynchronous // transformations, parallel interleave contains state other than the // buffered elements, which needs to be stored in the symbolic checkpoint. // // The implementaiton uses a member variable to accumulate this state. // Notably, its contents are propagated to the caller in the `SaveInternal` // method (as opposed to the `GetNextInternal` method) so that the // checkpoint of upstream state is in sync with parallel interleave state. std::unique_ptr<MemoryCheckpoint> checkpoint_ TF_GUARDED_BY(mu_); }; const DatasetBase* const input_; const std::unique_ptr<CapturedFunction> captured_func_; const int64_t input_cycle_length_; const int64_t cycle_length_; const int64_t block_length_; const int64_t buffer_output_elements_; const int64_t prefetch_input_elements_; const int64_t num_parallel_calls_; const DeterminismPolicy deterministic_; const DataTypeVector output_types_; const std::vector<PartialTensorShape> output_shapes_; const int op_version_; const TraceMeMetadata traceme_metadata_; }; ParallelInterleaveDatasetOp::ParallelInterleaveDatasetOp( OpKernelConstruction* ctx) : UnaryDatasetOpKernel(ctx), op_version_(OpVersionFromOpName(ctx->def().op())) { OP_REQUIRES_OK(ctx, FunctionMetadata::Create(ctx, kFunc, /*params=*/{}, &func_metadata_)); OP_REQUIRES_OK(ctx, ctx->GetAttr(kOutputTypes, &output_types_)); OP_REQUIRES_OK(ctx, ctx->GetAttr(kOutputShapes, &output_shapes_)); if (op_version_ == 2) { bool sloppy; OP_REQUIRES_OK(ctx, ctx->GetAttr(kSloppy, &sloppy)); if (sloppy) { deterministic_ = DeterminismPolicy(DeterminismPolicy::Type::kNondeterministic); } else { deterministic_ = DeterminismPolicy(DeterminismPolicy::Type::kDefault); } } if (op_version_ >= 3) { std::string deterministic; OP_REQUIRES_OK(ctx, ctx->GetAttr(kDeterministic, &deterministic)); OP_REQUIRES_OK( ctx, DeterminismPolicy::FromString(deterministic, &deterministic_)); } } void ParallelInterleaveDatasetOp::MakeDataset(OpKernelContext* ctx, DatasetBase* input, DatasetBase** output) { int64_t block_length = 0; OP_REQUIRES_OK(ctx, ParseScalarArgument(ctx, kBlockLength, &block_length)); OP_REQUIRES(ctx, block_length > 0, errors::InvalidArgument("`block_length` must be > 0")); int64_t buffer_output_elements = model::kAutotune; int64_t prefetch_input_elements = model::kAutotune; if (op_version_ >= 4) { OP_REQUIRES_OK(ctx, ParseScalarArgument(ctx, kBufferOutputElements, &buffer_output_elements)); OP_REQUIRES(ctx, buffer_output_elements == model::kAutotune || buffer_output_elements > 0, errors::InvalidArgument("`buffer_output_elements` must be " "`tf.data.AUTOTUNE` or > 0 but is ", buffer_output_elements)); OP_REQUIRES_OK(ctx, ParseScalarArgument(ctx, kPrefetchInputElements, &prefetch_input_elements)); OP_REQUIRES(ctx, prefetch_input_elements == model::kAutotune || prefetch_input_elements >= 0, errors::InvalidArgument("`prefetch_input_elements` must be " "`tf.data.AUTOTUNE` or >= 0 but is ", prefetch_input_elements)); } int64_t num_parallel_calls = 0; OP_REQUIRES_OK( ctx, ParseScalarArgument(ctx, kNumParallelCalls, &num_parallel_calls)); OP_REQUIRES( ctx, num_parallel_calls > 0 || num_parallel_calls == model::kAutotune, errors::InvalidArgument("num_parallel_calls must be greater than zero.")); int64_t cycle_length = 0; OP_REQUIRES_OK(ctx, ParseScalarArgument(ctx, kCycleLength, &cycle_length)); OP_REQUIRES( ctx, cycle_length > 0 || cycle_length == model::kAutotune, errors::InvalidArgument( "`cycle_length` must be `tf.data.AUTOTUNE` or greater than 0 but is ", cycle_length)); OP_REQUIRES( ctx, num_parallel_calls <= cycle_length || cycle_length == model::kAutotune, errors::InvalidArgument( "If `cycle_length` is set to a fixed value, `num_parallel_calls` " "must be either `tf.data.AUTOTUNE` or a value less than or equal " "to `cycle_length`. However, `num_parallel_calls` is ", num_parallel_calls, " and `cycle_length` is ", cycle_length)); std::unique_ptr<CapturedFunction> captured_func; OP_REQUIRES_OK(ctx, CapturedFunction::Create(ctx, func_metadata_, kOtherArguments, &captured_func)); if (num_parallel_calls == model::kAutotune) { metrics::RecordTFDataAutotune(kDatasetType); } *output = new Dataset( ctx, input, std::move(captured_func), cycle_length, block_length, buffer_output_elements, prefetch_input_elements, num_parallel_calls, deterministic_, output_types_, output_shapes_, op_version_); } namespace { REGISTER_KERNEL_BUILDER(Name(kParallelInterleaveDatasetV2).Device(DEVICE_CPU), ParallelInterleaveDatasetOp); REGISTER_KERNEL_BUILDER(Name(kParallelInterleaveDatasetV3).Device(DEVICE_CPU), ParallelInterleaveDatasetOp); REGISTER_KERNEL_BUILDER(Name(kParallelInterleaveDatasetV4).Device(DEVICE_CPU), ParallelInterleaveDatasetOp); REGISTER_INPUT_COLOCATION_EXEMPTION(kParallelInterleaveDatasetV2); REGISTER_INPUT_COLOCATION_EXEMPTION(kParallelInterleaveDatasetV3); REGISTER_INPUT_COLOCATION_EXEMPTION(kParallelInterleaveDatasetV4); } // namespace } // namespace data } // namespace tensorflow
dc59e44fe5936dbac2d8071c0f4319f429a3f76d
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/windows/advcore/gdiplus/engine/entry/stringformat.hpp
e9022286491be64122056bc96fb5fb36a50eedcf
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
19,208
hpp
stringformat.hpp
/**************************************************************************\ * * Copyright (c) 1998 Microsoft Corporation * * Module Name: * * stringFormat.hpp * * Abstract: * * String and text format definition * * Revision History: * * 08/05/1999 dbrown * Created it. * \**************************************************************************/ #ifndef _STRINGFORMAT_HPP #define _STRINGFORMAT_HPP const REAL DefaultMargin = REAL(1.0/6.0); const REAL DefaultTracking = REAL(1.03); const REAL DefaultBottomMargin = REAL(1.0/8.0); const INT DefaultFormatFlags = 0; const StringTrimming DefaultTrimming = StringTrimmingCharacter; // Private StringFormatFlags const INT StringFormatFlagsPrivateNoGDI = 0x80000000; const INT StringFormatFlagsPrivateAlwaysUseFullImager = 0x40000000; const INT StringFormatFlagsPrivateUseNominalAdvance = 0x20000000; const INT StringFormatFlagsPrivateFormatPersisted = 0x10000000; class StringFormatRecordData : public ObjectData { public: INT32 Flags; LANGID Language; GpStringAlignment StringAlign; GpStringAlignment LineAlign; GpStringDigitSubstitute DigitSubstitute; LANGID DigitLanguage; REAL FirstTabOffset; INT32 HotkeyPrefix; REAL LeadingMargin; REAL TrailingMargin; REAL Tracking; StringTrimming Trimming; INT32 CountTabStops; INT32 RangeCount; }; // // Represent a string format object // class GpStringFormat : public GpObject { protected: VOID SetValid(BOOL valid) { GpObject::SetValid(valid ? ObjectTagStringFormat : ObjectTagInvalid); } public: GpStringFormat() : Flags (DefaultFormatFlags), Language (LANG_NEUTRAL), StringAlign (StringAlignmentNear), LineAlign (StringAlignmentNear), DigitSubstitute (StringDigitSubstituteUser), DigitLanguage (LANG_NEUTRAL), FirstTabOffset (0.0), TabStops (NULL), CountTabStops (0), HotkeyPrefix (HotkeyPrefixNone), LeadingMargin (DefaultMargin), TrailingMargin (DefaultMargin), Tracking (DefaultTracking), Trimming (StringTrimmingCharacter), Ranges (NULL), RangeCount (0), Permanent (FALSE) { SetValid(TRUE); // default is valid } GpStringFormat(INT flags, LANGID language) : Flags (flags), Language (language), StringAlign (StringAlignmentNear), LineAlign (StringAlignmentNear), DigitSubstitute (StringDigitSubstituteUser), DigitLanguage (LANG_NEUTRAL), FirstTabOffset (0.0), TabStops (NULL), CountTabStops (0), HotkeyPrefix (HotkeyPrefixNone), LeadingMargin (DefaultMargin), TrailingMargin (DefaultMargin), Tracking (DefaultTracking), Trimming (StringTrimmingCharacter), Ranges (NULL), RangeCount (0), Permanent (FALSE) { SetValid(TRUE); // default is valid } ~GpStringFormat() { if (TabStops) delete [] TabStops; if (Ranges) delete [] Ranges; } static GpStringFormat *GenericDefault(); static GpStringFormat *GenericTypographic(); static void DestroyStaticObjects() { // these objects are created as a static but constructed in the // GenericDefault() and GenericTypographic(). we need to destruct // it just in case the user called SetTapStop which allocate memory // inside this object and by this way we prevent any memory leak. if (GenericDefaultPointer != NULL) { GenericDefaultPointer->~GpStringFormat(); // Zero the memory - this is risky code, so we want the memory // to match what it was when GDI+ started up. memset(GenericDefaultPointer, 0, sizeof(GpStringFormat)); GenericDefaultPointer = NULL; } if (GenericTypographicPointer != NULL) { GenericTypographicPointer->~GpStringFormat(); // Zero the memory - this is risky code, so we want the memory // to match what it was when GDI+ started up. memset(GenericTypographicPointer, 0, sizeof(GpStringFormat)); GenericTypographicPointer = NULL; } return; } GpStringFormat *Clone() const; GpStatus SetFormatFlags(INT flags) { if (Flags != flags) { Flags = flags; UpdateUid(); } return Ok; } INT GetFormatFlags() const { return Flags; } GpStatus SetAlign(GpStringAlignment align) { if (StringAlign != align) { StringAlign = align; UpdateUid(); } return Ok; } GpStatus GetAlign(GpStringAlignment *align) const { *align = StringAlign; return Ok; } GpStringAlignment GetPhysicalAlignment() const { if ( !(Flags & StringFormatFlagsDirectionRightToLeft) || StringAlign == StringAlignmentCenter || Flags & StringFormatFlagsDirectionVertical) { return StringAlign; } else if (StringAlign == StringAlignmentNear) { return StringAlignmentFar; // RTL near = right } else { return StringAlignmentNear; // RTL far = left } } GpStringAlignment GetAlign() const { return StringAlign; } GpStatus SetLineAlign(GpStringAlignment align) { if (LineAlign != align) { LineAlign = align; UpdateUid(); } return Ok; } GpStatus GetLineAlign(GpStringAlignment *align) const { *align = LineAlign; return Ok; } GpStringAlignment GetLineAlign() const { return LineAlign; } GpStatus SetHotkeyPrefix (INT hotkeyPrefix) { if (HotkeyPrefix != hotkeyPrefix) { HotkeyPrefix = hotkeyPrefix; UpdateUid(); } return Ok; } GpStatus GetHotkeyPrefix (INT *hotkeyPrefix) const { if (!hotkeyPrefix) return InvalidParameter; *hotkeyPrefix = HotkeyPrefix; return Ok; } INT GetHotkeyPrefix () const { return HotkeyPrefix; } GpStatus SetTabStops ( REAL firstTabOffset, INT countTabStops, const REAL *tabStops ) { if (countTabStops > 0) { // We do not support negative tabulation (tab position // advances in the opposite direction of reading order) if (firstTabOffset < 0) { return NotImplemented; } for (INT i = 0; i < countTabStops; i++) { if (tabStops[i] < 0) { return NotImplemented; } } REAL *newTabStops = new REAL [countTabStops]; if (!newTabStops) { return OutOfMemory; } if (TabStops) { delete [] TabStops; } TabStops = newTabStops; GpMemcpy (TabStops, tabStops, sizeof(REAL) * countTabStops); CountTabStops = countTabStops; FirstTabOffset = firstTabOffset; UpdateUid(); } return Ok; } GpStatus GetTabStopCount ( INT *countTabStops ) const { if (!countTabStops) { return InvalidParameter; } *countTabStops = CountTabStops; return Ok; } GpStatus GetTabStops ( REAL *firstTabOffset, INT countTabStops, REAL *tabStops ) const { if ( !firstTabOffset || !tabStops) { return InvalidParameter; } INT count; if (countTabStops <= CountTabStops) count = countTabStops; else count = CountTabStops; GpMemcpy(tabStops, TabStops, sizeof(REAL) * count); *firstTabOffset = FirstTabOffset; return Ok; } INT GetTabStops ( REAL *firstTabOffset, REAL **tabStops ) const { *firstTabOffset = FirstTabOffset; *tabStops = TabStops; return CountTabStops; } GpStatus SetMeasurableCharacterRanges( INT rangeCount, const CharacterRange *ranges ); INT GetMeasurableCharacterRanges( CharacterRange **ranges = NULL ) const { if (ranges) { *ranges = Ranges; } return RangeCount; } GpStatus SetDigitSubstitution( LANGID language, StringDigitSubstitute substitute = StringDigitSubstituteNational ) { if (DigitSubstitute != substitute || DigitLanguage != language) { DigitSubstitute = substitute; DigitLanguage = language; UpdateUid(); } return Ok; } GpStatus GetDigitSubstitution( LANGID *language, StringDigitSubstitute *substitute ) const { if(substitute) { *substitute = DigitSubstitute; } if(language) { *language = DigitLanguage; } return Ok; } GpStatus SetLeadingMargin(REAL margin) { if (LeadingMargin != margin) { LeadingMargin = margin; UpdateUid(); } return Ok; } REAL GetLeadingMargin() const { return LeadingMargin; } GpStatus SetTrailingMargin(REAL margin) { if (TrailingMargin != margin) { TrailingMargin = margin; UpdateUid(); } return Ok; } REAL GetTrailingMargin() const { return TrailingMargin; } GpStatus SetTracking(REAL tracking) { if (Tracking != tracking) { Tracking = tracking; UpdateUid(); } return Ok; } REAL GetTracking() const { return Tracking; } GpStatus SetTrimming(StringTrimming trimming) { if (Trimming != trimming) { Trimming = trimming; UpdateUid(); } return Ok; } GpStatus GetTrimming(StringTrimming *trimming) const { ASSERT(trimming != NULL); if (trimming == NULL) { return InvalidParameter; } *trimming = Trimming; return Ok; } virtual BOOL IsValid() const { // If the string format came from a different version of GDI+, its tag // will not match, and it won't be considered valid. return GpObject::IsValid(ObjectTagStringFormat); } virtual ObjectType GetObjectType() const { return ObjectTypeStringFormat; } virtual GpStatus GetData(IStream * stream) const { ASSERT (stream); StringFormatRecordData stringFormatData; stringFormatData.Flags = Flags; stringFormatData.Language = Language; stringFormatData.StringAlign = StringAlign; stringFormatData.LineAlign = LineAlign; stringFormatData.DigitSubstitute = DigitSubstitute; stringFormatData.DigitLanguage = DigitLanguage; stringFormatData.FirstTabOffset = FirstTabOffset; stringFormatData.LineAlign = LineAlign; stringFormatData.CountTabStops = CountTabStops; stringFormatData.HotkeyPrefix = HotkeyPrefix; stringFormatData.LeadingMargin = LeadingMargin; stringFormatData.TrailingMargin = TrailingMargin; stringFormatData.Tracking = Tracking; stringFormatData.Trimming = Trimming; stringFormatData.CountTabStops = CountTabStops; stringFormatData.RangeCount = RangeCount; stream->Write( &stringFormatData, sizeof(stringFormatData), NULL ); stream->Write( TabStops, CountTabStops * sizeof(TabStops[0]), NULL ); stream->Write( Ranges, RangeCount * sizeof(Ranges[0]), NULL ); return Ok; } virtual UINT GetDataSize() const { UINT size = sizeof(StringFormatRecordData); size += (CountTabStops * sizeof(TabStops[0])); size += (RangeCount * sizeof(Ranges[0])); return size; } virtual GpStatus SetData(const BYTE * dataBuffer, UINT size) { if ((dataBuffer == NULL) || (size < (sizeof(StringFormatRecordData) - sizeof(REAL)))) { WARNING(("dataBuffer too small")); return InvalidParameter; } const StringFormatRecordData *stringFormatData = (const StringFormatRecordData *)dataBuffer; if (!stringFormatData->MajorVersionMatches()) { WARNING(("Version number mismatch")); return InvalidParameter; } Flags = stringFormatData->Flags | StringFormatFlagsPrivateFormatPersisted; Language = stringFormatData->Language; StringAlign = stringFormatData->StringAlign; LineAlign = stringFormatData->LineAlign; DigitSubstitute = stringFormatData->DigitSubstitute; DigitLanguage = stringFormatData->DigitLanguage; FirstTabOffset = stringFormatData->FirstTabOffset; LineAlign = stringFormatData->LineAlign; CountTabStops = stringFormatData->CountTabStops; HotkeyPrefix = stringFormatData->HotkeyPrefix; LeadingMargin = stringFormatData->LeadingMargin; TrailingMargin = stringFormatData->TrailingMargin; Tracking = stringFormatData->Tracking; Trimming = stringFormatData->Trimming; CountTabStops = stringFormatData->CountTabStops; RangeCount = stringFormatData->RangeCount; if (size < ( sizeof(StringFormatRecordData) + sizeof(TabStops[0]) * CountTabStops + sizeof(Ranges[0]) * RangeCount)) { return InvalidParameter; } // Propagate tab stops if (TabStops) { delete [] TabStops; } TabStops = new REAL [CountTabStops]; if (TabStops == NULL) { return OutOfMemory; } REAL *tabStops = (REAL *)(&stringFormatData[1]); for (INT i = 0; i < CountTabStops; i++) { TabStops[i] = tabStops[i]; } // Propagate ranges if (Ranges) { delete [] Ranges; } Ranges = new CharacterRange [RangeCount]; if (Ranges == NULL) { if (TabStops) { delete [] TabStops; } return OutOfMemory; } CharacterRange *ranges = (CharacterRange *)(&tabStops[CountTabStops]); for (INT i = 0; i < RangeCount; i++) { Ranges[i] = ranges[i]; } UpdateUid(); return Ok; } BOOL IsPermanent() const { return Permanent; } // we override the new operator for this class just to use it for object // placement. we didn't make the new placemenet global because it will // conflict with office because they link with GdiPlus statically. // we didn't override the delete operator because it is fine to use the // global one in \engine\runtime\Mem.h void* operator new(size_t size) { return GpMalloc(size); } void* operator new(size_t size, void* p) { return p; } // Digit Substitution const ItemScript GetDigitScript() const { return GetDigitSubstitutionsScript(DigitSubstitute, DigitLanguage); } private: INT Flags; LANGID Language; GpStringAlignment StringAlign; GpStringAlignment LineAlign; GpStringDigitSubstitute DigitSubstitute; LANGID DigitLanguage; REAL FirstTabOffset; REAL *TabStops; // absolute tab stops in world unit INT CountTabStops; INT HotkeyPrefix; REAL LeadingMargin; // relative to body font em size REAL TrailingMargin; // relative to body font em size REAL Tracking; // scale factor GpStringTrimming Trimming; CharacterRange *Ranges; // character ranges INT RangeCount; // number of ranges BOOL Permanent; GpStringFormat(const GpStringFormat &format) { // This should never get called! Use Clone instead! ASSERT(FALSE); } // The following static variables support the generic StringFormats // Pointers (initialised at load time to null) static GpStringFormat *GenericDefaultPointer; static GpStringFormat *GenericTypographicPointer; // Memory allocation for generic structures. Note that we must allocate // load time memory as BYTE arrays to avoid creating a dependency on // the CRT for class construction. // The definitions (which specify the size) are in StringFormat.cpp. static BYTE GenericDefaultStaticBuffer[]; static BYTE GenericTypographicStaticBuffer[]; }; #endif // !_STRINGFORMAT_HPP
18864ebbcfb2b35f2c72f8f86de559967838ba5b
bea2095dd7b4a9baa7c7ad1aa2c70d6a4add5229
/CMPS_385/prj_9/cmps385_prj_9_1.cpp
862d303ea4845aa7d3cd6d5c71c0112c57ff3dde
[]
no_license
fbrenyah/OOP_Projects
0c9181650859662f8955cc2528a449f176aa9419
a650a218b9dc0e50ad9599aee9c602da9f6df3c3
refs/heads/master
2021-01-18T21:43:23.157486
2016-04-15T22:16:51
2016-04-15T22:16:51
17,191,278
0
0
null
null
null
null
UTF-8
C++
false
false
5,147
cpp
cmps385_prj_9_1.cpp
/*----------------------------------------------------------------------------------------- Name Frank Brenyah Course CMPS-385 Project No.9 part 1 Date Nov. 19th, 2012 Professor Ray Ahmandnia Purpose: Provide a system to view and interact with accounts and balances. ------F.O. Brenyah Bank LLC------ A) Display all records B) Display name and balance C) Deposit D) Withdraw Please, enter choice(A, B, C, or D): a 10 Will $96.99 20 Frank $200 30 Ana $1000 40 Kriss $150 50 Elaine $330.3 60 Jozeph $666.66 CONTINUE?(Y/N) y Please, enter choice(A, B, C, or D): b Please, enter your ID number: 20 Account info: Frank $200 CONTINUE?(Y/N) y Please, enter choice(A, B, C, or D): c Please, enter your ID number: 20 How much do you want to deposit: 30 Your new balance is: $230 CONTINUE?(Y/N) y Please, enter choice(A, B, C, or D): d Please, enter your ID number: 20 How much do you want to withdraw: 120 Your new balance is: $110 CONTINUE?(Y/N) n -------------------------------------------------------------------------------------*/ #include <iostream> #include <string> #include <fstream> #include <cctype> using namespace std; class BST; int main() { //declare identifiers BST bank_accounts; char Continue; int ID_num[6]; string Name[6]; float Balance[6]; //retreive info from text file fstream File; File.open("CMPS385_9_info.txt", ios::in); for(int i=0; i<6; i++) File >> ID_num[i] >> Name[i] >> Balance[i]; File.close(); //build B.S. Tree for(int i=0; i<6; i++) bank_accounts.insert( ID_num[i], Name[i], Balance[i] ); char Choice; cout<<"\t------F.O. Brenyah Bank LLC------\n"; cout<<" A) Display all records\n"; cout<<" B) Display name and balance\n"; cout<<" C) Deposit\n"; cout<<" D) Withdraw\n"; do{ cout<<" Please, enter choice(A, B, C, or D): "; cin>>Choice; Choice = tolower(Choice); if( Choice == 'a' ) { //display all bank acounts bank_accounts.Display(); cout<<endl; } int id_temp; if( Choice == 'b' ) { //get info when ID_num is entered id_temp = 0; //ID number holder cout<<" Please, enter your ID number: "; cin>>id_temp; bank_accounts.find_Account(id_temp); } if( Choice == 'c' ) { //deposit money when ID_num is entered id_temp = 0; cout<<" Please, enter your ID number: "; cin>>id_temp; bank_accounts.do_Deposit(id_temp); } if( Choice == 'd' ) { //withdraw money when ID_num is entered id_temp = 0; cout<<" Please, enter your ID number: "; cin>>id_temp; bank_accounts.do_Withdraw(id_temp); } cout<<" CONTINUE?(Y/N) "; cin>>Continue; Continue = tolower(Continue); cout<<endl; }while( Continue == 'y' ); //end program system("PAUSE"); return 0; } // //class class BST { private: struct NODE { int id; string name; float amount; NODE* left, *right; }; NODE* root; public: BST() { root = NULL; } //constructor void insert( NODE* &P, int& x, string& y, float& z ) { if( P == NULL ) { P = new(NODE); P->id = x; P->name = y; P->amount = z; P->left = P->right = NULL; } if( x < P->id) insert( P->left, x, y, z ); if( x > P->id ) insert( P->right, x, y, z ); } void DisplayTree( NODE *P ) { if( P != NULL ) { DisplayTree(P->left); cout<< P->id <<"\t"<< P->name <<"\t$"<< P->amount <<'\n'; DisplayTree(P->right); } } //call display member void Display() { DisplayTree(root); } //call insert member void insert( int x, string y, float z ) { insert(root, x, y, z); } //search for account info void Account_Search( NODE *&P, int x ) { if( P == NULL ) cout<<"\tAccount "<< x <<" does not exist.\n"; else if( P->id == x ) { cout<<" Account info:\n"; cout<<" "<< P->name <<"\t$"<< P->amount <<endl; } else if( P->id < x ) Account_Search( P->left, x ); else Account_Search( P->right, x ); } //search for balance info then deposit void Deposit_Search( NODE *&P, int x ) { if( P == NULL ) cout<<"\tAccount "<< x <<" does not exist.\n"; else if( P->id == x ) { int depo_temp = 0; //hold deposit cout<<"\tHow much do you want to deposit: "; cin>>depo_temp; P->amount = (P->amount + depo_temp); cout<<"\t Your new balance is: $"<< P->amount <<endl; } else if( P->id < x ) Deposit_Search( P->left, x ); else Deposit_Search( P->right, x ); } //search for balance info then withdraw void Withdraw_Search( NODE *&P, int x ) { if( P == NULL ) cout<<"\tAccount "<< x <<" does not exist.\n"; else if( P->id == x ) { int wDRAW_temp = 0; //hold deposit cout<<"\tHow much do you want to withdraw: "; cin>>wDRAW_temp; P->amount = (P->amount - wDRAW_temp); cout<<"\t Your new balance is: $"<< P->amount <<endl; } else if( P->id < x ) Deposit_Search( P->left, x ); else Deposit_Search( P->right, x ); } //call search members void find_Account( int& x ) { Account_Search(root, x); } void do_Deposit( int& x ) { Deposit_Search(root, x); } void do_Withdraw( int& x ) { Withdraw_Search(root, x); } };
fffd89b5e3a782a5bfa35a3aec51089685c25646
964743cc9072f09d3d60a88ddd90971e48e8a956
/NewGeneUI/NewGene/Infrastructure/Settings/Base/inputprojectsettingsworkqueue_base.cpp
aa9c4557e915108620fc17af0f5a21272af32dab
[]
no_license
daniel347x/newgene
f6a7abae718bc4b3813c6adf2c2f991dca535954
dc0b5ddaeea441d905d627a4145d7a3e2eda78b5
refs/heads/master
2022-06-27T17:19:42.205690
2022-06-21T21:52:07
2022-06-21T21:52:07
9,526,888
0
2
null
2022-06-21T21:52:08
2013-04-18T16:55:22
C
UTF-8
C++
false
false
48
cpp
inputprojectsettingsworkqueue_base.cpp
#include "inputprojectsettingsworkqueue_base.h"
13f476c6e7d62192b0b54dd51df7242401e35117
dbbdcc830eb1cc6d85c82dbf95b0a8ca0ff1fdd1
/opengl/engine/Mesh.cpp
0e800bc71b0b14953569930d2418fa83941f6842
[]
no_license
VladislavKhudziakov/obj_viewer
042108453c7dc6b44d6ef25a72fb50c50b68f0ab
b7ed06259e3ce09b88025db64fa3c10854766156
refs/heads/master
2020-06-02T02:23:29.804323
2019-06-29T21:26:43
2019-06-29T21:26:43
191,004,420
1
0
null
null
null
null
UTF-8
C++
false
false
2,089
cpp
Mesh.cpp
// // Mesh.cpp // opengl // // Created by Vladislav Khudiakov on 6/12/19. // Copyright © 2019 Vladislav Khudiakov. All rights reserved. // #include "Mesh.hpp" namespace Engine { Mesh::Mesh(const aiMesh* mesh, const aiScene* scene) : IDrawable(), textures() { std::vector<float> positions; std::vector<unsigned int> indices; std::vector<float> uv; std::vector<float> normals; for (int i = 0; i < mesh->mNumVertices; i++) { if (mesh->HasPositions()) { positions.push_back(mesh->mVertices[i].x); positions.push_back(mesh->mVertices[i].y); positions.push_back(mesh->mVertices[i].z); } if (mesh->HasNormals()) { normals.push_back(mesh->mNormals[i].x); normals.push_back(mesh->mNormals[i].y); normals.push_back(mesh->mNormals[i].z); } if (mesh->HasTextureCoords(0)) { uv.push_back(mesh->mTextureCoords[0][i].x); uv.push_back(mesh->mTextureCoords[0][i].y); } } for (int i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; for (int j = 0; j < face.mNumIndices; j++) { indices.push_back(face.mIndices[j]); } } verticesData = VBO(positions, indices, normals, uv); } Mesh::Mesh(const std::vector<float>& vertices, const std::vector<float>& normals, const std::vector<float>& uv) : IDrawable(), textures() { verticesData = VBO(vertices, normals, uv); } Mesh::Mesh(const std::vector<float>& vertices, const std::vector<unsigned int>& indices, const std::vector<float>& normals, const std::vector<float>& uv) : IDrawable(), textures() { verticesData = VBO(vertices, indices, normals, uv); } void Mesh::draw() const { verticesData.draw(); } void Mesh::setTexture(const std::string& name, const Texture2D& texture) { textures[name] = texture; } const std::map<std::string, Texture2D>& Mesh::getTextures() { return textures; } }