hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
c798c9b0820c4864c89849e547a44a61d0b182e0
1,655
hpp
C++
src/tensorrt/src/core/dataset/tensor_dataset.hpp
tfindlay-au/dlcookbook-dlbs
a4e65f022523a10531817533a4244c3050e9336d
[ "Apache-2.0" ]
null
null
null
src/tensorrt/src/core/dataset/tensor_dataset.hpp
tfindlay-au/dlcookbook-dlbs
a4e65f022523a10531817533a4244c3050e9336d
[ "Apache-2.0" ]
null
null
null
src/tensorrt/src/core/dataset/tensor_dataset.hpp
tfindlay-au/dlcookbook-dlbs
a4e65f022523a10531817533a4244c3050e9336d
[ "Apache-2.0" ]
null
null
null
/* (c) Copyright [2017] Hewlett Packard Enterprise Development LP 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 "core/dataset/dataset.hpp" #include "core/logger.hpp" #ifndef DLBS_TENSORRT_BACKEND_CORE_DATASET_TENSOR_DATASET #define DLBS_TENSORRT_BACKEND_CORE_DATASET_TENSOR_DATASET class tensor_dataset : public dataset { private: std::vector<std::string> file_names_; std::vector<std::thread*> prefetchers_; dataset_opts opts_; logger_impl& logger_; private: static void prefetcher_func(tensor_dataset* myself, const size_t prefetcher_id, const size_t num_prefetchers); public: tensor_dataset(const dataset_opts& opts, inference_msg_pool* pool, abstract_queue<inference_msg*>* request_queue, logger_impl& logger); void run() override; static float benchmark(const std::string dir, const size_t batch_size=512, const size_t img_size=227, const size_t num_prefetches=4, const size_t num_infer_msgs=10, const int num_warmup_batches=10, const int num_batches=100, const std::string& dtype="float"); }; #endif
38.488372
114
0.731118
tfindlay-au
c79e791e4125a5ba5f2590c5c55b8c367bb9c2ac
1,523
cpp
C++
src/zipalign/tests/src/align_test.cpp
Lzhiyong/android-sdk-tools
a2c5e32764f4140c13da017abe9f861ba462cc7c
[ "Apache-2.0" ]
22
2018-06-25T15:57:58.000Z
2020-03-26T15:42:23.000Z
src/zipalign/tests/src/align_test.cpp
Lzhiyong/android-sdk-tools
a2c5e32764f4140c13da017abe9f861ba462cc7c
[ "Apache-2.0" ]
3
2018-12-11T04:15:06.000Z
2020-05-01T00:06:46.000Z
src/zipalign/tests/src/align_test.cpp
Lzhiyong/android-sdk-tools
a2c5e32764f4140c13da017abe9f861ba462cc7c
[ "Apache-2.0" ]
6
2018-08-25T19:54:58.000Z
2020-03-26T15:42:26.000Z
#include "gmock/gmock.h" #include "gtest/gtest.h" #include "ZipAlign.h" #include <stdio.h> #include <string> #include <android-base/file.h> using namespace android; static std::string GetTestPath(const std::string& filename) { static std::string test_data_dir = android::base::GetExecutableDirectory() + "/tests/data/"; return test_data_dir + filename; } TEST(Align, Unaligned) { const std::string src = GetTestPath("unaligned.zip"); const std::string dst = GetTestPath("unaligned_out.zip"); int processed = process(src.c_str(), dst.c_str(), 4, true, false, 4096); ASSERT_EQ(0, processed); int verified = verify(dst.c_str(), 4, true, false); ASSERT_EQ(0, verified); } // Align a zip featuring a hole at the beginning. The // hole in the archive is a delete entry in the Central // Directory. TEST(Align, Holes) { const std::string src = GetTestPath("holes.zip"); const std::string dst = GetTestPath("holes_out.zip"); int processed = process(src.c_str(), dst.c_str(), 4, true, false, 4096); ASSERT_EQ(0, processed); int verified = verify(dst.c_str(), 4, false, true); ASSERT_EQ(0, verified); } // Align a zip where LFH order and CD entries differ. TEST(Align, DifferenteOrders) { const std::string src = GetTestPath("diffOrders.zip"); const std::string dst = GetTestPath("diffOrders_out.zip"); int processed = process(src.c_str(), dst.c_str(), 4, true, false, 4096); ASSERT_EQ(0, processed); int verified = verify(dst.c_str(), 4, false, true); ASSERT_EQ(0, verified); }
28.203704
94
0.698621
Lzhiyong
c79f7371907cf7d50c7badf1bdb7848151d2385b
128
hpp
C++
src/icebox/icebox/utils/path.hpp
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
521
2019-03-29T15:44:08.000Z
2022-03-22T09:46:19.000Z
src/icebox/icebox/utils/path.hpp
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
30
2019-06-04T17:00:49.000Z
2021-09-08T20:44:19.000Z
src/icebox/icebox/utils/path.hpp
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
99
2019-03-29T16:04:13.000Z
2022-03-28T16:59:34.000Z
#pragma once #include "icebox/types.hpp" namespace path { fs::path filename(const std::string& path); } // namespace path
14.222222
47
0.695313
Fimbure
c7a09c927211c77e9ba3528c5c77d3f11982d0ef
2,350
cpp
C++
cpp/pipe2.cpp
cs1730/cs1730-syscalls
868047de2a95d2abdcb5d22f34af1e55de8ffe42
[ "MIT" ]
1
2016-11-05T01:53:05.000Z
2016-11-05T01:53:05.000Z
cpp/pipe2.cpp
cs1730/cs1730-syscalls
868047de2a95d2abdcb5d22f34af1e55de8ffe42
[ "MIT" ]
null
null
null
cpp/pipe2.cpp
cs1730/cs1730-syscalls
868047de2a95d2abdcb5d22f34af1e55de8ffe42
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <cstdlib> #include <cstring> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> using namespace std; void close_pipe(int pipefd [2]); vector<char *> mk_cstrvec(vector<string> & strvec); void dl_cstrvec(vector<char *> & cstrvec); void nice_exec(vector<string> args); inline void nope_out(const string & sc_name); int main(const int argc, const char * argv []) { int pipefd [2]; int pid; // create pipe if (pipe(pipefd) == -1) nope_out("pipe"); if ((pid = fork()) == -1) { nope_out("fork"); } else if (pid == 0) { vector<string> strargs { "cat", "pipe2.cpp" }; if (dup2(pipefd[1], STDOUT_FILENO) == -1) nope_out("dup2"); close_pipe(pipefd); nice_exec(strargs); } // if if ((pid = fork()) == -1) { nope_out("fork"); } else if (pid == 0) { vector<string> strargs { "less" }; if (dup2(pipefd[0], STDIN_FILENO) == -1) nope_out("dup2"); close_pipe(pipefd); nice_exec(strargs); } // if close_pipe(pipefd); waitpid(pid, nullptr, 0); return EXIT_SUCCESS; } // main void close_pipe(int pipefd [2]) { if (close(pipefd[0]) == -1) nope_out("close"); if (close(pipefd[1]) == -1) nope_out("close"); } // close_pipe vector<char *> mk_cstrvec(vector<string> & strvec) { vector<char *> cstrvec; for (unsigned int i = 0; i < strvec.size(); ++i) { cstrvec.push_back(new char [strvec.at(i).size() + 1]); strcpy(cstrvec.at(i), strvec.at(i).c_str()); } // for cstrvec.push_back(nullptr); return cstrvec; } // mk_cstrvec void dl_cstrvec(vector<char *> & cstrvec) { for (unsigned int i = 0; i < cstrvec.size(); ++i) { delete[] cstrvec.at(i); } // for } // dl_cstrvec void nice_exec(vector<string> strargs) { vector<char *> cstrargs = mk_cstrvec(strargs); execvp(cstrargs.at(0), &cstrargs.at(0)); perror("execvp"); dl_cstrvec(cstrargs); exit(EXIT_FAILURE); } // nice_exec /** Prints out the latest errno error and exits the process with EXIT_FAILURE. * It should be noted that the name of this function is not portable. Most * persons older than you will NOT understand the name of this function. They * will be confused. Keep this in mind. */ inline void nope_out(const string & sc_name) { perror(sc_name.c_str()); exit(EXIT_FAILURE); } // nope_out
25.824176
78
0.64
cs1730
c7a6d631064fc09fc6d9b87ad01167f0329722ff
119
cpp
C++
Source/XeluIcons/Private/XeluIconsLog.cpp
mklabs/ue-xelu-icons
4aaf54ecb9533fc3689f457b280b79293b861b47
[ "MIT" ]
5
2022-02-01T22:49:51.000Z
2022-03-03T10:18:36.000Z
Source/XeluIcons/Private/XeluIconsLog.cpp
mklabs/ue-xelu-icons
4aaf54ecb9533fc3689f457b280b79293b861b47
[ "MIT" ]
1
2022-01-31T23:09:04.000Z
2022-01-31T23:09:04.000Z
Source/XeluIcons/Private/XeluIconsLog.cpp
mklabs/ue-xelu-icons
4aaf54ecb9533fc3689f457b280b79293b861b47
[ "MIT" ]
null
null
null
// Copyright 2022 Mickael Daniel. All Rights Reserved. #include "XeluIconsLog.h" DEFINE_LOG_CATEGORY(LogXeluIcons)
17
55
0.789916
mklabs
c7ab8df954b5e2dd2a4684c9ea99eba630034172
632
hpp
C++
include/rive/world_transform_component.hpp
kariem2k/rive-cpp
f58c3b3d48ea03947a76971bce17e7f567cf0de0
[ "MIT" ]
139
2020-08-17T20:10:24.000Z
2022-03-28T12:22:44.000Z
include/rive/world_transform_component.hpp
kariem2k/rive-cpp
f58c3b3d48ea03947a76971bce17e7f567cf0de0
[ "MIT" ]
89
2020-08-28T16:41:01.000Z
2022-03-28T19:10:49.000Z
include/rive/world_transform_component.hpp
kariem2k/rive-cpp
f58c3b3d48ea03947a76971bce17e7f567cf0de0
[ "MIT" ]
19
2020-10-19T00:54:40.000Z
2022-02-28T05:34:17.000Z
#ifndef _RIVE_WORLD_TRANSFORM_COMPONENT_HPP_ #define _RIVE_WORLD_TRANSFORM_COMPONENT_HPP_ #include "rive/generated/world_transform_component_base.hpp" #include "rive/math/mat2d.hpp" namespace rive { class TransformComponent; class WorldTransformComponent : public WorldTransformComponentBase { friend class TransformComponent; protected: Mat2D m_WorldTransform; public: void markWorldTransformDirty(); virtual float childOpacity(); Mat2D& mutableWorldTransform(); const Mat2D& worldTransform() const; void worldTranslation(Vec2D& result) const; void opacityChanged() override; }; } // namespace rive #endif
24.307692
67
0.803797
kariem2k
c7acc77edb9d93bde8ec7906f3fef668fcaa0b39
6,319
hpp
C++
blast/include/algo/blast/api/query_data.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
blast/include/algo/blast/api/query_data.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
blast/include/algo/blast/api/query_data.hpp
mycolab/ncbi-blast
e59746cec78044d2bf6d65de644717c42f80b098
[ "Apache-2.0" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
/* $Id: query_data.hpp 161402 2009-05-27 17:35:47Z camacho $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Christiam Camacho, Kevin Bealer * */ /** @file query_data.hpp * NOTE: This file contains work in progress and the APIs are likely to change, * please do not rely on them until this notice is removed. */ #ifndef ALGO_BLAST_API___BLAST_QUERY_DATA_HPP #define ALGO_BLAST_API___BLAST_QUERY_DATA_HPP #include <algo/blast/api/blast_aux.hpp> #include <algo/blast/core/blast_def.h> #include <objects/seqloc/Seq_loc.hpp> #include <objects/seqset/Bioseq_set.hpp> /** @addtogroup AlgoBlast * * @{ */ BEGIN_NCBI_SCOPE BEGIN_SCOPE(blast) /// Provides access (not ownership) to the C structures used to configure /// local BLAST search class implementations class NCBI_XBLAST_EXPORT ILocalQueryData : public CObject { public: /// Default constructor ILocalQueryData() : m_SumOfSequenceLengths(0) {} /// virtual destructor virtual ~ILocalQueryData() {} /// Accessor for the BLAST_SequenceBlk structure virtual BLAST_SequenceBlk* GetSequenceBlk() = 0; /// Accessor for the BlastQueryInfo structure virtual BlastQueryInfo* GetQueryInfo() = 0; /// Get the number of queries. virtual size_t GetNumQueries() = 0; /// Get the Seq_loc for the sequence indicated by index. virtual CConstRef<objects::CSeq_loc> GetSeq_loc(size_t index) = 0; /// Get the length of the sequence indicated by index. virtual size_t GetSeqLength(size_t index) = 0; /// Compute the sum of all the sequence's lengths size_t GetSumOfSequenceLengths(); /// Retrieve all error/warning messages void GetMessages(TSearchMessages& messages) const; /// Retrieve error/warning messages for a specific query void GetQueryMessages(size_t index, TQueryMessages& qmsgs); /// Determine if a given query sequence is valid or not bool IsValidQuery(size_t index); /// Determine if at least one query sequence is valid or not bool IsAtLeastOneQueryValid(); /// Frees the cached sequence data structure (as this is usually the larger /// data structure). This is to be used in the context of query splitting, /// when the sequence data is only needed to set up global data structures, /// but not in the actual search. void FlushSequenceData(); protected: /// Data member to cache the BLAST_SequenceBlk CBLAST_SequenceBlk m_SeqBlk; /// Data member to cache the BlastQueryInfo CBlastQueryInfo m_QueryInfo; /// Error/warning messages are stored here TSearchMessages m_Messages; private: void x_ValidateIndex(size_t index); size_t m_SumOfSequenceLengths; }; class IRemoteQueryData : public CObject { public: virtual ~IRemoteQueryData() {} /// Accessor for the CBioseq_set virtual CRef<objects::CBioseq_set> GetBioseqSet() = 0; /// Type definition for CSeq_loc set used as queries in the BLAST remote /// search class typedef list< CRef<objects::CSeq_loc> > TSeqLocs; /// Accessor for the TSeqLocs virtual TSeqLocs GetSeqLocs() = 0; protected: /// Data member to cache the CBioseq_set CRef<objects::CBioseq_set> m_Bioseqs; /// Data member to cache the TSeqLocs TSeqLocs m_SeqLocs; }; // forward declaration needed by IQueryFactory class CBlastOptions; /// Source of query sequence data for BLAST /// Provides an interface for search classes to retrieve sequence data to be /// used in local/remote searches without coupling them to the actual means /// of retrieving the data. /// /// Its subclasses define which types of inputs can be converted into ILocalQ /// @note Because this class caches the result of the Make*QueryData methods, /// the products created by this factory will have the same lifespan as /// the factory. class NCBI_XBLAST_EXPORT IQueryFactory : public CObject { public: virtual ~IQueryFactory() {} /// Creates and caches an ILocalQueryData CRef<ILocalQueryData> MakeLocalQueryData(const CBlastOptions* opts); /// Creates and caches an IRemoteQueryData CRef<IRemoteQueryData> MakeRemoteQueryData(); protected: CRef<ILocalQueryData> m_LocalQueryData; CRef<IRemoteQueryData> m_RemoteQueryData; /// factory method to create an ILocalQueryData, only called if the data /// members above are not set virtual CRef<ILocalQueryData> x_MakeLocalQueryData(const CBlastOptions* opts) = 0; /// factory method to create an IRemoteQueryData, only called if the data /// members above are not set virtual CRef<IRemoteQueryData> x_MakeRemoteQueryData() = 0; }; END_SCOPE(BLAST) END_NCBI_SCOPE /* @} */ #endif /* ALGO_BLAST_API___BLAST_QUERY_DATA__HPP */
35.700565
79
0.666403
mycolab
c7ad4046737db1af7a765380184a7a2030614c9e
10,143
hpp
C++
stf-inc/stf_fstream.hpp
sparcians/stf_lib
9e4933bff0c956dba464ced72e311e73507342dc
[ "MIT" ]
1
2022-02-17T00:48:44.000Z
2022-02-17T00:48:44.000Z
stf-inc/stf_fstream.hpp
sparcians/stf_lib
9e4933bff0c956dba464ced72e311e73507342dc
[ "MIT" ]
null
null
null
stf-inc/stf_fstream.hpp
sparcians/stf_lib
9e4933bff0c956dba464ced72e311e73507342dc
[ "MIT" ]
null
null
null
#ifndef __STF_FSTREAM_HPP__ #define __STF_FSTREAM_HPP__ #include <ios> #include <string_view> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <mutex> #include <set> #include <vector> #include "stf_exception.hpp" #include "stf_pc_tracker.hpp" #include "stf_vlen.hpp" namespace stf { /** * \class STFFstream * * Base class that all STF I/O classes inherit from */ class STFFstream { private: bool used_popen_ = false; /**< Indicates whether we opened the file with an external command */ static std::mutex open_streams_mutex_; /**< Mutex used to ensure atexit handler is thread-safe */ static bool lock_open_streams_; /**< Flag used to indicate whether close() methods should also remove STFFstreams from open_streams_ */ static std::set<STFFstream*> open_streams_; /**< Set containing all streams that need to be closed in the atexit handler */ static bool atexit_handler_registered_; /**< Flag used to indicate whether atexit handler has already been registered */ vlen_t vlen_ = 0; /**< Vector vlen parameter - if 0, the parameter has not been set and attempting to read/write a vector register record will cause an error */ protected: FILE* stream_ = nullptr; /**< Underlying file stream */ PCTracker pc_tracker_; /**< Tracks the current and next instruction PC */ size_t num_records_read_ = 0; /**< Number of records seen so far */ size_t num_insts_ = 0; /**< Number of instructions seen so far */ bool has_32bit_events_ = false; /**< If true, EventRecord event values are packed into 32 bits */ STFFstream() = default; /** * Checks whether the file extension matches the given extension * \param filename filename to check * \param ext extension to check for */ static inline bool check_extension_(const std::string_view filename, const std::string_view ext) { return filename.rfind(ext) != std::string_view::npos; } /** * Popens the given command on the given filename, in read or write mode * \param cmd command to run * \param filename filename to run command with * \param mode read-write mode */ static inline FILE* popen_cmd_(const std::string_view cmd, const std::string_view filename, const char* mode) { std::stringstream ss; ss << cmd << filename; return popen(ss.str().c_str(), mode); } /** * Calls fstat() on the stream and returns the result */ struct stat getFileStat_() const { stf_assert(!used_popen_, "Cannot get block size of a stream input."); stf_assert(stream_, "Attempted to query blocksize without opening a file first."); struct stat stat_result; stf_assert(fstat(fileno(stream_), &stat_result) == 0, "Failed to stat file"); return stat_result; } /** * Gets the block size of the filesystem we are reading from */ size_t getFSBlockSize_() const { struct stat stat_result = getFileStat_(); return static_cast<size_t>(stat_result.st_blksize); } /** * atexit handler that cleanly closes all open streams */ static void cleanupStreams_(); /** * Registers this instance with the atexit handler */ void registerExitHandler_() { // Ensuring that open_streams_mutex_, lock_open_streams_, and open_streams_ // are instantiated before we register the atexit handler std::lock_guard<std::mutex> l(open_streams_mutex_); lock_open_streams_ = false; open_streams_.insert(this); // Register the handler if it hasn't already been registered if(!atexit_handler_registered_) { stf_assert(atexit(cleanupStreams_) == 0, "Failed to register exit handler for STFFstream"); atexit_handler_registered_ = true; } } public: // Prevents copying any STF I/O objects STFFstream(const STFFstream&) = delete; void operator=(const STFFstream&) = delete; virtual ~STFFstream() { if (stream_) { STFFstream::close(); } } /** * Returns whether the stream is valid */ explicit virtual operator bool() const { return stream_; } /** * \brief Open a file using an external process through a pipe * \param cmd The command to run * \param filename The filename to run the command with * \param rw_mode R/W mode */ inline void openWithProcess(const std::string_view cmd, const std::string_view filename, const char* rw_mode) { stream_ = popen_cmd_(cmd, filename, rw_mode); used_popen_ = true; stf_assert(stream_, "Failed to run command: " << cmd << ' ' << filename); registerExitHandler_(); } /** * \brief Open a regular file * \param filename The file to open * \param rw_mode R/W mode */ inline void open(const std::string_view filename, const std::string_view rw_mode) { // special handling for stdin/stdout if(filename.compare("-") == 0) { if(rw_mode.compare("rb") == 0) { stream_ = stdin; } else if(rw_mode.compare("wb") == 0) { stream_ = stdout; } else { stf_throw("Attempted to open stdin/stdout with invalid mode: " << rw_mode); } } else { stream_ = fopen (filename.data(), rw_mode.data()); } used_popen_ = false; stf_assert(stream_, "Failed to open file: " << filename); registerExitHandler_(); } /** * \brief close the trace reader/writer */ virtual int close() { int retcode = 0; if (stream_) { if(stream_ == stdout) { fflush(stream_); // need to manually flush stdout } else if(stream_ != stdin) { // don't close stdin/stdout if (used_popen_) { retcode = pclose (stream_); } else if (stream_ != stdout) { retcode = fclose (stream_); } } stream_ = nullptr; } num_records_read_ = 0; num_insts_ = 0; // If we aren't closing this from the atexit handler, go ahead and remove ourselves // from open_streams_ if(!lock_open_streams_) { std::lock_guard<std::mutex> l(open_streams_mutex_); open_streams_.erase(this); } return retcode; } /** * Gets the current instruction PC */ uint64_t getPC() const { return pc_tracker_.getPC(); } /** * Updates the PC tracker with the given record * \param rec Record to update PC tracker with */ template<typename RecordType> void trackPC(const RecordType& rec) { pc_tracker_.track(rec); } /** * Callback for all record types - just counts how many records have been read/written */ void recordCallback() { ++num_records_read_; } /** * Gets how many records have been read/written */ size_t getNumRecords() const { return num_records_read_; } /** * Callback for instruction opcode record types - just counts how many instruction record groups have been read/written */ virtual void instructionRecordCallback() { // If this was an instruction record, increment the instruction count ++num_insts_; } /** * Gets how many instruction record groups have been read/written */ size_t getNumInsts() const { return num_insts_; } /** * Sets the vlen parameter * \param vlen Vlen value to set */ void setVLen(vlen_t vlen); /** * Gets the vlen parameter */ vlen_t getVLen() const { return vlen_; } /** * Returns whether the trace uses 32-bit event records */ bool has32BitEvents() const { return has_32bit_events_; } /** * Sets whether the trace uses 32-bit event records * \param has_32bit_events If true, the trace to be read/written uses 32-bit event records */ void set32BitEvents(const bool has_32bit_events) { has_32bit_events_ = has_32bit_events; } }; } // end namespace stf #endif
37.290441
147
0.506458
sparcians
c7b41672c7d475a0d9a0d7f83066cc93a594382e
17,506
cpp
C++
src/config/ui_preferences_display.cpp
dinfinity/foo_openlyrics
cf42d61ce172f374b76140b5922f7eae1aef33b3
[ "MIT" ]
132
2021-01-26T11:19:30.000Z
2022-03-28T09:52:45.000Z
src/config/ui_preferences_display.cpp
dinfinity/foo_openlyrics
cf42d61ce172f374b76140b5922f7eae1aef33b3
[ "MIT" ]
108
2021-04-08T10:57:27.000Z
2022-03-27T08:02:15.000Z
src/config/ui_preferences_display.cpp
dinfinity/foo_openlyrics
cf42d61ce172f374b76140b5922f7eae1aef33b3
[ "MIT" ]
13
2021-08-06T06:21:05.000Z
2022-03-28T08:19:37.000Z
#include "stdafx.h" #pragma warning(push, 0) #include "resource.h" #include "foobar2000/helpers/atl-misc.h" #pragma warning(pop) #include "config/config_auto.h" #include "config/config_font.h" #include "logging.h" #include "preferences.h" #include "ui_hooks.h" static const GUID GUID_PREFERENCES_PAGE_DISPLAY = { 0xa31b1608, 0xe77f, 0x4fe5, { 0x80, 0x4b, 0xcf, 0x8c, 0xc8, 0x17, 0xd8, 0x69 } }; static const GUID GUID_CFG_DISPLAY_CUSTOM_FONT = { 0x828be475, 0x8e26, 0x4504, { 0x87, 0x53, 0x22, 0xf5, 0x69, 0xd, 0x53, 0xb7 } }; static const GUID GUID_CFG_DISPLAY_CUSTOM_FOREGROUND_COLOUR = { 0x675418e1, 0xe0b0, 0x4c85, { 0xbf, 0xde, 0x1c, 0x17, 0x9b, 0xbc, 0xca, 0xa7 } }; static const GUID GUID_CFG_DISPLAY_CUSTOM_BACKGROUND_COLOUR = { 0x13da3237, 0xaa1d, 0x4065, { 0x82, 0xb0, 0xe4, 0x3, 0x31, 0xe0, 0x69, 0x5b } }; static const GUID GUID_CFG_DISPLAY_CUSTOM_HIGHLIGHT_COLOUR = { 0xfa2fed99, 0x593c, 0x4828, { 0xbf, 0x7d, 0x95, 0x8e, 0x99, 0x26, 0x9d, 0xcb } }; static const GUID GUID_CFG_DISPLAY_FONT = { 0xc06f95f7, 0x9358, 0x42ab, { 0xb7, 0xa0, 0x19, 0xe6, 0x74, 0x5f, 0xb9, 0x16 } }; static const GUID GUID_CFG_DISPLAY_FOREGROUND_COLOUR = { 0x36724d22, 0xe51e, 0x4c84, { 0x9e, 0xb2, 0x58, 0xa4, 0xd8, 0x23, 0xb3, 0x67 } }; static const GUID GUID_CFG_DISPLAY_BACKGROUND_COLOUR = { 0x7eaeeae6, 0xd41d, 0x4c0d, { 0x97, 0x86, 0x20, 0xa2, 0x8f, 0x27, 0x98, 0xd4 } }; static const GUID GUID_CFG_DISPLAY_HIGHLIGHT_COLOUR = { 0xfa16da6c, 0xb22d, 0x49cb, { 0x97, 0x53, 0x94, 0x8c, 0xec, 0xf8, 0x37, 0x35 } }; static const GUID GUID_CFG_DISPLAY_LINEGAP = { 0x4cc61a5c, 0x58dd, 0x47ce, { 0xa9, 0x35, 0x9, 0xbb, 0xfa, 0xc6, 0x40, 0x43 } }; static const GUID GUID_CFG_DISPLAY_SCROLL_TIME = { 0xc1c7dbf7, 0xd3ce, 0x40dc, { 0x83, 0x29, 0xed, 0xa0, 0xc6, 0xc8, 0xb6, 0x70 } }; static const GUID GUID_CFG_DISPLAY_SCROLL_DIRECTION = { 0x6b1f47ae, 0xa383, 0x434b, { 0xa7, 0xd2, 0x43, 0xbe, 0x55, 0x54, 0x2a, 0x33 } }; static const GUID GUID_CFG_DISPLAY_SCROLL_TYPE = { 0x3f2f17d8, 0x9309, 0x4721, { 0x9f, 0xa7, 0x79, 0x6d, 0x17, 0x84, 0x2a, 0x5d } }; static const COLORREF cfg_display_fg_colour_default = RGB(35,85,125); static const COLORREF cfg_display_bg_colour_default = RGB(255,255,255); static const COLORREF cfg_display_hl_colour_default = RGB(225,65,60); static const cfg_auto_combo_option<LineScrollDirection> g_scroll_direction_options[] = { {_T("Vertical"), LineScrollDirection::Vertical}, {_T("Horizontal"), LineScrollDirection::Horizontal}, }; static const cfg_auto_combo_option<LineScrollType> g_scroll_type_options[] = { {_T("Automatic"), LineScrollType::Automatic}, {_T("Manual"), LineScrollType::Manual}, }; static cfg_auto_bool cfg_display_custom_font(GUID_CFG_DISPLAY_CUSTOM_FONT, IDC_FONT_CUSTOM, false); static cfg_auto_bool cfg_display_custom_fg_colour(GUID_CFG_DISPLAY_CUSTOM_FOREGROUND_COLOUR, IDC_FOREGROUND_COLOUR_CUSTOM, false); static cfg_auto_bool cfg_display_custom_bg_colour(GUID_CFG_DISPLAY_CUSTOM_BACKGROUND_COLOUR, IDC_BACKGROUND_COLOUR_CUSTOM, false); static cfg_auto_bool cfg_display_custom_hl_colour(GUID_CFG_DISPLAY_CUSTOM_HIGHLIGHT_COLOUR, IDC_HIGHLIGHT_COLOUR_CUSTOM, false); static cfg_font_t cfg_display_font(GUID_CFG_DISPLAY_FONT); static cfg_int_t<uint32_t> cfg_display_fg_colour(GUID_CFG_DISPLAY_FOREGROUND_COLOUR, cfg_display_fg_colour_default); static cfg_int_t<uint32_t> cfg_display_bg_colour(GUID_CFG_DISPLAY_BACKGROUND_COLOUR, cfg_display_bg_colour_default); static cfg_int_t<uint32_t> cfg_display_hl_colour(GUID_CFG_DISPLAY_HIGHLIGHT_COLOUR, cfg_display_hl_colour_default); static cfg_auto_int cfg_display_linegap(GUID_CFG_DISPLAY_LINEGAP, IDC_RENDER_LINEGAP_EDIT, 4); static cfg_auto_ranged_int cfg_display_scroll_time(GUID_CFG_DISPLAY_SCROLL_TIME, IDC_DISPLAY_SCROLL_TIME, 10, 2000, 500); static cfg_auto_combo<LineScrollDirection, 2> cfg_display_scroll_direction(GUID_CFG_DISPLAY_SCROLL_DIRECTION, IDC_DISPLAY_SCROLL_DIRECTION, LineScrollDirection::Vertical, g_scroll_direction_options); static cfg_auto_combo<LineScrollType, 2> cfg_display_scroll_type(GUID_CFG_DISPLAY_SCROLL_TYPE, IDC_DISPLAY_SCROLL_TYPE, LineScrollType::Automatic, g_scroll_type_options); static cfg_auto_property* g_display_auto_properties[] = { &cfg_display_custom_font, &cfg_display_custom_fg_colour, &cfg_display_custom_bg_colour, &cfg_display_custom_hl_colour, &cfg_display_linegap, &cfg_display_scroll_time, &cfg_display_scroll_direction, &cfg_display_scroll_type, }; // // Globals // static HFONT g_display_font = nullptr; static COLORREF g_custom_colours[16] = { RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), }; // // Preference retrieval functions // t_ui_font preferences::display::font() { if(cfg_display_custom_font.get_value()) { if(g_display_font == nullptr) { LOG_INFO("Creating new display font handle"); g_display_font = CreateFontIndirect(&cfg_display_font.get_value()); } return g_display_font; } return nullptr; } std::optional<t_ui_color> preferences::display::foreground_colour() { if(cfg_display_custom_fg_colour.get_value()) { return (COLORREF)cfg_display_fg_colour.get_value(); } return {}; } std::optional<t_ui_color> preferences::display::background_colour() { if(cfg_display_custom_bg_colour.get_value()) { return (COLORREF)cfg_display_bg_colour.get_value(); } return {}; } std::optional<t_ui_color> preferences::display::highlight_colour() { if(cfg_display_custom_hl_colour.get_value()) { return (COLORREF)cfg_display_hl_colour.get_value(); } return {}; } int preferences::display::linegap() { return cfg_display_linegap.get_value(); } double preferences::display::scroll_time_seconds() { return ((double)cfg_display_scroll_time.get_value())/1000.0; } LineScrollDirection preferences::display::scroll_direction() { return cfg_display_scroll_direction.get_value(); } LineScrollType preferences::display::scroll_type() { return cfg_display_scroll_type.get_value(); } // // Preference page UI // class PreferencesDisplay : public CDialogImpl<PreferencesDisplay>, public auto_preferences_page_instance { public: // Constructor - invoked by preferences_page_impl helpers - don't do Create() in here, preferences_page_impl does this for us PreferencesDisplay(preferences_page_callback::ptr callback); ~PreferencesDisplay() override; // Dialog resource ID - Required by WTL/Create() enum {IDD = IDD_PREFERENCES_DISPLAY}; void apply() override; void reset() override; bool has_changed() override; //WTL message map BEGIN_MSG_MAP_EX(PreferencesDisplay) MSG_WM_INITDIALOG(OnInitDialog) MSG_WM_HSCROLL(OnScrollTimeChange) COMMAND_HANDLER_EX(IDC_FONT_CUSTOM, BN_CLICKED, OnCustomToggle) COMMAND_HANDLER_EX(IDC_FOREGROUND_COLOUR_CUSTOM, BN_CLICKED, OnCustomToggle) COMMAND_HANDLER_EX(IDC_BACKGROUND_COLOUR_CUSTOM, BN_CLICKED, OnCustomToggle) COMMAND_HANDLER_EX(IDC_HIGHLIGHT_COLOUR_CUSTOM, BN_CLICKED, OnCustomToggle) COMMAND_HANDLER_EX(IDC_FONT, BN_CLICKED, OnFontChange) COMMAND_HANDLER_EX(IDC_FOREGROUND_COLOUR, BN_CLICKED, OnFgColourChange) COMMAND_HANDLER_EX(IDC_BACKGROUND_COLOUR, BN_CLICKED, OnBgColourChange) COMMAND_HANDLER_EX(IDC_HIGHLIGHT_COLOUR, BN_CLICKED, OnHlColourChange) COMMAND_HANDLER_EX(IDC_RENDER_LINEGAP_EDIT, EN_CHANGE, OnUIChange) COMMAND_HANDLER_EX(IDC_DISPLAY_SCROLL_DIRECTION, CBN_SELCHANGE, OnUIChange) COMMAND_HANDLER_EX(IDC_DISPLAY_SCROLL_TYPE, CBN_SELCHANGE, OnUIChange) MESSAGE_HANDLER_EX(WM_CTLCOLORBTN, ColourButtonPreDraw) END_MSG_MAP() private: BOOL OnInitDialog(CWindow, LPARAM); void OnFontChange(UINT, int, CWindow); void OnFgColourChange(UINT, int, CWindow); void OnBgColourChange(UINT, int, CWindow); void OnHlColourChange(UINT, int, CWindow); void OnCustomToggle(UINT, int, CWindow); void OnUIChange(UINT, int, CWindow); void OnScrollTimeChange(int, int, HWND); LRESULT ColourButtonPreDraw(UINT, WPARAM, LPARAM); void UpdateFontButtonText(); void SelectBrushColour(HBRUSH& brush); void RepaintColours(); void UpdateScrollTimePreview(); LOGFONT m_font; HBRUSH m_brush_foreground; HBRUSH m_brush_background; HBRUSH m_brush_highlight; }; PreferencesDisplay::PreferencesDisplay(preferences_page_callback::ptr callback) : auto_preferences_page_instance(callback, g_display_auto_properties) { m_font = cfg_display_font.get_value(); m_brush_foreground = CreateSolidBrush(cfg_display_fg_colour.get_value()); m_brush_background = CreateSolidBrush(cfg_display_bg_colour.get_value()); m_brush_highlight = CreateSolidBrush(cfg_display_hl_colour.get_value()); } PreferencesDisplay::~PreferencesDisplay() { DeleteObject(m_brush_foreground); DeleteObject(m_brush_background); DeleteObject(m_brush_highlight); } void PreferencesDisplay::apply() { // Reset the global configured font handle so that it can be re-created with the new value DeleteObject(g_display_font); g_display_font = nullptr; cfg_display_font.set_value(m_font); LOGBRUSH brushes[3] = {}; GetObject(m_brush_foreground, sizeof(brushes[0]), &brushes[0]); GetObject(m_brush_background, sizeof(brushes[0]), &brushes[1]); GetObject(m_brush_highlight, sizeof(brushes[0]), &brushes[2]); cfg_display_fg_colour = brushes[0].lbColor; cfg_display_bg_colour = brushes[1].lbColor; cfg_display_hl_colour = brushes[2].lbColor; auto_preferences_page_instance::apply(); repaint_all_lyric_panels(); } void PreferencesDisplay::reset() { m_font = cfg_display_font.get_value(); DeleteObject(m_brush_foreground); DeleteObject(m_brush_background); DeleteObject(m_brush_highlight); m_brush_foreground = CreateSolidBrush(cfg_display_fg_colour_default); m_brush_background = CreateSolidBrush(cfg_display_bg_colour_default); m_brush_highlight = CreateSolidBrush(cfg_display_hl_colour_default); auto_preferences_page_instance::reset(); UpdateScrollTimePreview(); UpdateFontButtonText(); RepaintColours(); } bool PreferencesDisplay::has_changed() { LOGBRUSH brushes[3] = {}; GetObject(m_brush_foreground, sizeof(brushes[0]), &brushes[0]); GetObject(m_brush_background, sizeof(brushes[0]), &brushes[1]); GetObject(m_brush_highlight, sizeof(brushes[0]), &brushes[2]); bool changed = false; changed |= !(cfg_display_font == m_font); changed |= (cfg_display_fg_colour != brushes[0].lbColor); changed |= (cfg_display_bg_colour != brushes[1].lbColor); changed |= (cfg_display_hl_colour != brushes[2].lbColor); return changed || auto_preferences_page_instance::has_changed(); } BOOL PreferencesDisplay::OnInitDialog(CWindow, LPARAM) { init_auto_preferences(); UpdateFontButtonText(); UpdateScrollTimePreview(); RepaintColours(); return FALSE; } void PreferencesDisplay::OnFontChange(UINT, int, CWindow) { CHOOSEFONT fontOpts = {}; fontOpts.lStructSize = sizeof(fontOpts); fontOpts.hwndOwner = m_hWnd; fontOpts.lpLogFont = &m_font; fontOpts.Flags = CF_FORCEFONTEXIST | CF_INITTOLOGFONTSTRUCT; fontOpts.nFontType = SCREEN_FONTTYPE; BOOL font_selected = ChooseFont(&fontOpts); if(font_selected) { UpdateFontButtonText(); on_ui_interaction(); } on_ui_interaction(); } void PreferencesDisplay::OnFgColourChange(UINT, int, CWindow) { LRESULT custom = SendDlgItemMessage(IDC_FOREGROUND_COLOUR_CUSTOM, BM_GETCHECK, 0, 0); if(custom == BST_CHECKED) { SelectBrushColour(m_brush_foreground); } } void PreferencesDisplay::OnBgColourChange(UINT, int, CWindow) { LRESULT custom = SendDlgItemMessage(IDC_BACKGROUND_COLOUR_CUSTOM, BM_GETCHECK, 0, 0); if(custom == BST_CHECKED) { SelectBrushColour(m_brush_background); } } void PreferencesDisplay::OnHlColourChange(UINT, int, CWindow) { LRESULT custom = SendDlgItemMessage(IDC_HIGHLIGHT_COLOUR_CUSTOM, BM_GETCHECK, 0, 0); if(custom == BST_CHECKED) { SelectBrushColour(m_brush_highlight); } } void PreferencesDisplay::OnCustomToggle(UINT, int, CWindow) { UpdateFontButtonText(); RepaintColours(); on_ui_interaction(); } void PreferencesDisplay::OnUIChange(UINT, int, CWindow) { on_ui_interaction(); } void PreferencesDisplay::OnScrollTimeChange(int /*request_type*/, int /*new_position*/, HWND source_window) { // Docs say this handle will be the scroll bar that sent the message if any, otherwise null. // Currently the only scroll bar is the setting for synced-line-scroll-time if(source_window == nullptr) return; UpdateScrollTimePreview(); on_ui_interaction(); } LRESULT PreferencesDisplay::ColourButtonPreDraw(UINT, WPARAM, LPARAM lparam) { static_assert(sizeof(LRESULT) >= sizeof(HBRUSH)); HWND btn_handle = (HWND)lparam; int btn_id = ::GetDlgCtrlID(btn_handle); if(btn_id == IDC_FOREGROUND_COLOUR) { LRESULT custom_fg = SendDlgItemMessage(IDC_FOREGROUND_COLOUR_CUSTOM, BM_GETCHECK, 0, 0); if(custom_fg == BST_CHECKED) { return (LRESULT)m_brush_foreground; } } else if(btn_id == IDC_HIGHLIGHT_COLOUR) { LRESULT custom_hl = SendDlgItemMessage(IDC_HIGHLIGHT_COLOUR_CUSTOM, BM_GETCHECK, 0, 0); if(custom_hl == BST_CHECKED) { return (LRESULT)m_brush_highlight; } } else if(btn_id == IDC_BACKGROUND_COLOUR) { LRESULT custom_bg = SendDlgItemMessage(IDC_BACKGROUND_COLOUR_CUSTOM, BM_GETCHECK, 0, 0); if(custom_bg == BST_CHECKED) { return (LRESULT)m_brush_background; } } return FALSE; } void PreferencesDisplay::UpdateFontButtonText() { bool custom_font = (SendDlgItemMessage(IDC_FONT_CUSTOM, BM_GETCHECK, 0, 0) == BST_CHECKED); CWindow font_btn = GetDlgItem(IDC_FONT); assert(font_btn != nullptr); font_btn.EnableWindow(custom_font); HDC dc = GetDC(); int point_size = -MulDiv(m_font.lfHeight, 72, GetDeviceCaps(dc, LOGPIXELSY)); ReleaseDC(dc); const int point_buffer_len = 32; TCHAR point_buffer[point_buffer_len]; _sntprintf_s(point_buffer, point_buffer_len, _T(", %dpt"), point_size); std::tstring font_str; font_str += m_font.lfFaceName; font_str += point_buffer; if(m_font.lfWeight == FW_BOLD) { font_str += _T(", Bold"); } if(m_font.lfItalic) { font_str += _T(", Italic"); } font_btn.SetWindowText(font_str.c_str()); ReleaseDC(dc); } void PreferencesDisplay::SelectBrushColour(HBRUSH& handle) { LOGBRUSH brush = {}; GetObject(handle, sizeof(LOGBRUSH), &brush); CHOOSECOLOR colourOpts = {}; colourOpts.lStructSize = sizeof(colourOpts); colourOpts.hwndOwner = m_hWnd; colourOpts.rgbResult = brush.lbColor; colourOpts.lpCustColors = g_custom_colours; colourOpts.Flags = CC_ANYCOLOR | CC_FULLOPEN | CC_RGBINIT; BOOL colour_selected = ChooseColor(&colourOpts); if(colour_selected) { DeleteObject(handle); handle = CreateSolidBrush(colourOpts.rgbResult); RepaintColours(); on_ui_interaction(); } } void PreferencesDisplay::RepaintColours() { int ids_to_repaint[] = { IDC_FOREGROUND_COLOUR, IDC_BACKGROUND_COLOUR, IDC_HIGHLIGHT_COLOUR }; for(int id : ids_to_repaint) { CWindow handle = GetDlgItem(id); if(handle != nullptr) { handle.RedrawWindow(nullptr, nullptr, RDW_ERASE | RDW_INVALIDATE | RDW_UPDATENOW); } } } void PreferencesDisplay::UpdateScrollTimePreview() { // We get the position specifically because the value passed in the parameter is sometimes 0 LRESULT value = SendDlgItemMessage(IDC_DISPLAY_SCROLL_TIME, TBM_GETPOS, 0, 0); const int preview_length = 32; TCHAR preview[preview_length]; _sntprintf_s(preview, preview_length, _T("%d milliseconds"), value); SetDlgItemText(IDC_DISPLAY_SCROLL_TIME_PREVIEW, preview); } class PreferencesDisplayImpl : public preferences_page_impl<PreferencesDisplay> { public: const char* get_name() final { return "Display"; } GUID get_guid() final { return GUID_PREFERENCES_PAGE_DISPLAY; } GUID get_parent_guid() final { return GUID_PREFERENCES_PAGE_ROOT; } }; static preferences_page_factory_t<PreferencesDisplayImpl> g_preferences_page_display_factory;
37.405983
200
0.711299
dinfinity
c7b445038ae290e8cfb4937af50dcbfe98518160
4,559
hpp
C++
src/object.hpp
SkyVault/vault-lang
b50ddaa7b35b180066fe794a537bf25b032a03e0
[ "MIT" ]
3
2021-04-14T15:42:28.000Z
2021-08-25T14:35:01.000Z
src/object.hpp
SkyVault/vault-lang
b50ddaa7b35b180066fe794a537bf25b032a03e0
[ "MIT" ]
null
null
null
src/object.hpp
SkyVault/vault-lang
b50ddaa7b35b180066fe794a537bf25b032a03e0
[ "MIT" ]
null
null
null
#pragma once #include "vault.hpp" #include "gc.hpp" #include <cstdint> #include <cstdlib> #include <string_view> #include <sstream> #include <string> #include <cstring> #include <map> #include <memory> #include <functional> #include <cassert> #include "object_type.hpp" #include "gc.hpp" namespace Vault { Obj* fst(const Obj* list); Obj* snd(const Obj* list); void printObj(Obj* obj); Obj* newList(bool quoted=false); Obj* newNum(Number number=0.0); Obj* newBool(Bool flag=false); Obj* newStr(const std::string &str=""); Obj* newAtom(const std::string &atom="", bool quoted=false); Obj* newProgn(bool quoted=false); Obj* newDict(bool quoted=false); Obj* newPair(Obj* a=NULL, Obj* b=NULL, bool quoted=false); Obj* newCFun(CFun lambda); Obj* newFun(Obj* env, Obj* name, Obj* params, Obj* progn, bool quoted=false); Obj* newEnv(); Obj* findInEnv(Obj* env, Obj* atom); Obj* putInEnv(Obj* env, Obj* atom, Obj* value); Obj* putInEnvUnique(Obj* env, Obj* atom, Obj* value); Obj* putOrUpdateInEnv(Obj* env, Obj* atom, Obj* value); Obj* updateInEnv(Obj* env, Obj* atom, Obj* value); Obj* pushScope(Obj* env); Obj* popScope(Obj* env); static Obj* newUnit() { static Obj unit = {}; unit.type = ValueType::UNIT; unit.mark = true; // Keep alive, static object shouldn't be deallocated. return &unit; } template <typename T> T fromObj(Obj* obj) { static char buff[2048*4] = {0}; if constexpr (std::is_same_v<T, double> || std::is_same_v<T, float> || std::is_same_v<T, int>) return (T)obj->val.num; if constexpr (std::is_same_v<T, bool>) return (T)obj->val.boolean; if constexpr (std::is_same_v<T, std::string>) { std::stringstream ss; for (int i = 0; i < obj->val.str.len; i++) ss << obj->val.str.data[i]; return newStr(ss.str()); } if constexpr (std::is_same_v<T, const char*>) { for (int i = 0; i < obj->val.str.len; i++) buff[i] = obj->val.str.data[i]; buff[obj->val.str.len] = '\0'; return buff; } } template <typename T> Obj* toObj(T v) { if constexpr (std::is_same_v<T, double> || std::is_same_v<T, float> || std::is_same_v<T, int>) { return newNum(v); } if constexpr (std::is_same_v<T, bool>) { return newBool(v); } if constexpr (std::is_same_v<T, const char*>) { return newStr(v); } if constexpr (std::is_same_v<T, std::string>) { return newStr(v); } } struct FnBridge { virtual ~FnBridge() {} virtual Obj* operator()(const std::vector<Obj*>& params) = 0; }; // Concrete class that exposes a C++ function to the script engine. template <class Res, class ... Param> struct FnBridge_Impl : FnBridge { using funcType = Res(*)(Param...); virtual Obj* operator()(const std::vector<Obj*>& params) { if (sizeof...(Param) != params.size()) throw std::domain_error("Invalid size of parameter array"); if constexpr (std::is_void_v<Res>) { call_impl<std::tuple<Param...>>( func, params, std::make_index_sequence<sizeof...(Param)>() ); return newUnit(); } if constexpr (!std::is_void_v<Res>) { return toObj<Res>( call_impl<std::tuple<Param...>>( func, params, std::make_index_sequence<sizeof...(Param)>() ) ); } } template <class Tuple, std::size_t... N> Res call_impl(funcType func, const std::vector<Obj*>& params, std::index_sequence<N...>) { return func(fromObj<typename std::tuple_element<N, Tuple>::type>(params[N])...); }; funcType func; FnBridge_Impl(funcType func) : func(func) {} }; template <class Res, class ... Param> auto wrapNativeFn(Res(*func)(Param...)) { return new FnBridge_Impl<Res, Param...>(func); } template <class Res, class ... Param> Obj* newNative(Res(*func)(Param...)) { Obj* obj = Vault::Gc::alloc(); obj->type = ValueType::NATIVE_FUNC; obj->val.native = new FnBridge_Impl<Res, Param...>(func); return obj; } bool cmp(Obj* a, Obj* b); bool isTrue(Obj* v); // Lists void each(Obj* list, std::function<void(Obj*)> fn); size_t len(Obj* list); void push(Obj* list, Obj* value); Obj* cons(Obj* list, Obj* value); Obj* car(Obj* list); Obj* cdr(Obj* list); Obj* shift(Obj* &list); // Pops off the top // Dictionaries Obj* put(Obj* dict, Obj* key, Obj* value); Obj* get(Obj* dict, Obj* key); void printEnv(Obj* env); }
30.192053
122
0.601009
SkyVault
c7b485395c03893055e1620e229a5b814a8d6cac
759
cpp
C++
Cfiles/sayitahmin.cpp
HilalSolak/Cprojects
e7cec37cbcdbe227c74f1fc35e1c76c9223f3b3d
[ "MIT" ]
null
null
null
Cfiles/sayitahmin.cpp
HilalSolak/Cprojects
e7cec37cbcdbe227c74f1fc35e1c76c9223f3b3d
[ "MIT" ]
null
null
null
Cfiles/sayitahmin.cpp
HilalSolak/Cprojects
e7cec37cbcdbe227c74f1fc35e1c76c9223f3b3d
[ "MIT" ]
null
null
null
#include<stdio.h> #include<stdlib.h> void sayitahmin(int sayi){ int tahmin; printf(" Tahmin Gir:"); scanf("%d",&tahmin); if(tahmin<sayi){ printf("daha buyuk tahmin yap:"); sayitahmin(sayi); } else if(tahmin>sayi){ printf("daha kucuk tahmin yap:"); sayitahmin(sayi); } else{ printf("Tebrikler bildiniz"); int cevap; printf("\ndevam etmek istiyorsaniz 1, istemiyorsaniz -1 girin:"); scanf("%d",&cevap); if(cevap==1){ sayitahmin(sayi); } if(cevap==-1){ printf("----oyundan cikis yapildi----"); } if(cevap!=1 && cevap!=-1){ printf("hatali giris"); }}} int main(){ int sayi=56; sayitahmin(sayi); return 0; }
21.685714
75
0.536232
HilalSolak
c7b56f1866133878f851dcb11e3f009fdabf90d2
17,979
cpp
C++
Cube First Phase/cube.cpp
mriddell001/encryption-cube
fd3c8ecd1cffb44bfe0bcfb361165237299cb619
[ "Apache-2.0" ]
null
null
null
Cube First Phase/cube.cpp
mriddell001/encryption-cube
fd3c8ecd1cffb44bfe0bcfb361165237299cb619
[ "Apache-2.0" ]
null
null
null
Cube First Phase/cube.cpp
mriddell001/encryption-cube
fd3c8ecd1cffb44bfe0bcfb361165237299cb619
[ "Apache-2.0" ]
null
null
null
//Cube.cpp #include "cube.h" #include <string> #include <vector> #include <fstream> #include <iterator> #include <iostream> using namespace std; /** * Cube - Initial creation of cube. * * Notes: May be impacted by changing load order. Check when project reaches * applicable phase in development. Current load order: Front, Right, Top, * Back, Left, Bottom * * ################# * # Top # * # 16 17 18 # * # 19 $ 20 # * # 21 22 23 # * #################################################### * # Left # Front # Right # * # 32 33 34 # 0 1 2 # 8 9 10 # * # 35 $ 36 # 3 $ 4 # 11 $ 12 # * # 37 38 39 # 5 6 7 # 13 14 15 # * #################################################### * # Bottom # * # 40 41 42 # * # 43 $ 44 # * # 45 46 47 # * ################# * # Back # * # 31 30 29 # * # 28 $ 27 # * # 26 25 24 # * ################# * * Debugging: Confirmed data was loaded into bands 2D array. */ Cube::Cube() { init = 1; int nums[72] = {0, 1, 2, 8, 9, 10, 24, 25, 26, 32, 33, 34, //Band 0 5, 6, 7, 13, 14, 15, 29, 30, 31, 37, 38, 39, //Band 1 0, 3, 5, 40, 43, 45, 31, 28, 26, 16, 19, 21, //Band 2 2, 4, 7, 42, 44, 47, 29, 27, 24, 18, 20, 23, //Band 3 16, 17, 18, 10, 12, 15, 47, 46, 45, 37, 35, 32, //Band 4 21, 22, 23, 8, 11, 13, 42, 41, 40, 39, 36, 34}; //Band 5 int l = 0; for (int i = 0; i < 48; i++) { Pip *tmp = new Pip(); pips.push_back(tmp); } for (int i = 0; i < 6; i++) { for (int k = 0; k < 12; k++) { bands[i][k] = nums[l]; l++; } } } /** * initializeCube - function to take input stream and load cube with strings of * data in the order: Front, Right, Top, Back, Left, Bottom * @param {fstream} stream - input stream to load cube with data. * * Notes: Will be impacted by changing load order. Check when project reaches * applicable phase in development. */ void Cube::initializeCube(fstream& stream) { char ch; int index = 0; while (stream.get(ch)) { string str = ""; str.push_back(ch); pips[index]->data += str; index++; index = index % 48; } if (index != 0) { while(index != 0) { pips[index]->data += " "; index++; index = index % 48; } } init++; } /** * deconstructCube - function to print cube to output file. * @param {fstream} stream - output stream to offload cube data. * * Notes: Deconstruction cube should also call the destructor for the cube. This * still needs to be implimented. */ void Cube::deconstructCube(fstream& stream) { print(stream); } /** * transformationStream - accept input file of cube manipulations. * @param {fstream} stream - input stream of cube transformations. */ void Cube::transformationStream(fstream& stream) { string a = "", b = "", tmp = ""; while (getline(stream, tmp)) { a += tmp[0]; b += tmp[1]; } cout << "string a: " << a << "\tstring b: " << b << endl; transformationDispatch(a, b); } /** * transformationDispatch - function to take string of orders () * @param {String} a - string of faces to be opperated on * @param {String} b - string indication clockwise or counterclockwise. */ void Cube::transformationDispatch(string a, string b) { for (unsigned int i = 0; i < a.size(); i++) { int x, y; x = a[i] - '0'; y = b[i] - '0'; switch (x) { case 0:{ if(y == 0){clockwise(x);} else{counterclockwise(x);} break;} case 1:{ if(y == 0){clockwise(x);} else{counterclockwise(x);} break;} case 2:{ if(y == 0){clockwise(x);} else{counterclockwise(x);} break;} case 3:{ if(y == 0){clockwise(x);} else{counterclockwise(x);} break;} case 4:{ if(y == 0){clockwise(x);} else{counterclockwise(x);} break;} case 5:{ if(y == 0){clockwise(x);} else{counterclockwise(x);} break;} default: {//If input if formatted correctly, this should never trigger. ofstream err ("error.txt", ofstream::out); err << "Error occured in transformationDispatch"; err.close(); break; } } } } /** * clockwise - function that takes an instruction for which face to opperate on * and it preforms the shifting of the indicators in the clockwise * direction * @param {Int} a - numerical indicator of which face to manipulate. * * Notes: All cases are complete. Next step is to confirm by testing each case. * Case 0 is confirmed. Entire function needs reworked with vector instead * of array. */ void Cube::clockwise(int a) { vector<int> x; vector<int> y; switch (a) { case 0://Top - Back, Right, Front, Left {//0(0-11) = 0(3-11,0-2) threeBack(a); for (int i = 0; i < 3; i++) {//2(11-9) => 4(0-2) && 3(11-9) => 5(0-2) x.push_back(bands[4][i]); y.push_back(bands[5][i]); bands[4][i] = bands[2][11-i]; bands[5][i] = bands[3][11-i]; } for (int i = 9; i < 12; i++) {//4(0-2) => 3(9-11) && 5(0-2) => 2(9-11) bands[3][i] = x[i-9]; bands[2][i] = y[i-9]; } bands[2][0] = bands[a][0]; bands[2][8] = bands[a][8]; bands[3][0] = bands[a][2]; bands[3][8] = bands[a][6]; bands[4][3] = bands[a][5]; bands[4][11] = bands[a][9]; bands[5][3] = bands[a][3]; bands[5][11] = bands[a][11]; break; } case 1://Bottom - Front, Right, Back, Left {//1(0-11) = 1(9-11,0-8) //Take the last three elements and move them to the front of the array. threeFront(a); for (int i = 3; i < 6; i++) {//4(8-6) => 2(3-5) && 5(8-6) => 3(3-5) x.push_back(bands[2][i]); y.push_back(bands[3][i]); bands[2][i] = bands[4][11-i]; bands[3][i] = bands[5][11-i]; } for (int i = 6; i < 9; i++) {//2(3-5) => 5(6-8) && 3(3-5) => 4(6-8) bands[5][i] = x[i-6]; bands[4][i] = y[i-6]; } bands[2][2] = bands[a][0]; bands[2][6] = bands[a][8]; bands[3][2] = bands[a][2]; bands[3][6] = bands[a][6]; bands[4][5] = bands[a][5]; bands[4][9] = bands[a][9]; bands[5][5] = bands[a][3]; bands[5][9] = bands[a][11]; break; } case 2://Left - Top, Front, Bottom, Back {//2(0-11) = 2(9-11,0-8) //Take the last three elements and move them to the front of the array. threeFront(a); for (int i = 9; i < 12; i++) {//5(9-11) => 1(9-11) && 4(9-11) => 0(9-11) x.push_back(bands[0][i]); y.push_back(bands[1][i]); bands[0][i] = bands[4][i]; bands[1][i] = bands[5][i]; } for (int i = 9; i < 12; i++) {//0(11-9) => 5(9-11) && 3(11-9) => 4(9-11) bands[5][i] = x[11-i]; bands[4][i] = y[11-i]; } bands[0][0] = bands[a][0]; bands[0][8] = bands[a][8]; bands[1][0] = bands[a][2]; bands[1][8] = bands[a][6]; bands[4][0] = bands[a][9]; bands[4][8] = bands[a][5]; bands[5][0] = bands[a][11]; bands[5][8] = bands[a][3]; break; } case 3://Right - Top, Back, Bottom, Front {//3(0-11) = 3(3-11,0-2) threeBack(a); for (int i = 3; i < 6; i++) {//0(3-5) => 4(3-5) && 1(3-5) => 5(3-5) x.push_back(bands[0][i]); y.push_back(bands[1][i]); bands[0][i] = bands[5][8-i]; bands[1][i] = bands[4][8-i]; } for (int i = 3; i < 6; i++) {//5(5-3) => 0(3-5) && 4(5-3) => 1(3-5) bands[4][i] = x[i-3]; bands[5][i] = y[i-3]; } bands[0][2] = bands[a][0]; bands[0][6] = bands[a][8]; bands[1][2] = bands[a][2]; bands[1][6] = bands[a][6]; bands[4][2] = bands[a][9]; bands[4][6] = bands[a][5]; bands[5][2] = bands[a][11]; bands[5][6] = bands[a][3]; break; } case 4://Back - Top, Left, Bottom, Right {//4(0-11) = 4(3-11,0-2) threeBack(a); for (int i = 6; i < 9; i++) {//3(6-8) => 0(6-8) && 2(6-8) => 1(6-8) x.push_back(bands[0][i]); y.push_back(bands[1][i]); bands[0][i] = bands[3][i]; bands[1][i] = bands[2][i]; } for (int i = 6; i < 9; i++) {//0(6-8) => 2(8-6) && 1(6-8) => 3(8-6) bands[2][i] = x[8-i]; bands[3][i] = y[8-i]; } bands[0][5] = bands[a][3]; bands[0][9] = bands[a][11]; bands[1][5] = bands[a][5]; bands[1][9] = bands[a][9]; bands[2][5] = bands[a][8]; bands[2][9] = bands[a][0]; bands[3][5] = bands[a][6]; bands[3][9] = bands[a][2]; break; } case 5://Front - Top, Right, Bottom, Left {//5(0-11) = 5(9-11,0-8) //Take the last three elements and move them to the front of the array. threeFront(a); for (int i = 0; i < 3; i++) {//1(0-2) => 2(0-2) && 0(0-2) => 3(0-2) x.push_back(bands[2][i]); y.push_back(bands[3][i]); bands[2][i] = bands[1][i]; bands[3][i] = bands[0][i]; } for (int i = 0; i < 3; i++) {//0(11-9) => 5(9-11) && 3(11-9) => 4(9-11) bands[0][i] = x[2-i]; bands[1][i] = y[2-i]; } bands[0][3] = bands[a][3]; bands[0][11] = bands[a][11]; bands[1][3] = bands[a][5]; bands[1][11] = bands[a][9]; bands[2][3] = bands[a][8]; bands[2][11] = bands[a][0]; bands[3][3] = bands[a][6]; bands[3][11] = bands[a][2]; break; } } x.erase (x.begin(),x.begin()+3); y.erase (y.begin(),y.begin()+3); } /** * counterclockwise - function that takes an instruction for which face to * opperate on and it preforms the shifting of the indicators * in the counterclockwise direction * @param {Int} a - numerical indicator of which face to manipulate. * * Notes: This function cheats by calling the clockwise function three times. * This works because the changes are equal. */ void Cube::counterclockwise(int a) {clockwise(a); clockwise(a); clockwise(a);} /** * threeBack - accepts a band to move three elements to the back of the array. * @param {Int} a - numerical indicator of which face to manipulate. */ void Cube::threeBack(int a) { vector<int> v; for (int i = 0; i < 3; i++) {v.push_back(bands[a][i]);} for (int i = 3; i < 12; i++) {bands[a][i-3] = bands[a][i];} for (int i = 9; i < 12; i++) {bands[a][i] = v[i-9];} v.erase (v.begin(),v.begin()+3); } /** * threeFront - accepts a band to move three elements to the front of the array. * @param {Int} a - numerical indicator of which face to manipulate. */ void Cube::threeFront(int a) { vector<int> v; for (int i = 9; i < 12; i++) {v.push_back(bands[a][i]);} for (int i = 8; i > -1; i--) {bands[a][i+3] = bands[a][i];} for (int i = 0; i < 3; i++) {bands[a][i] = v[i];} v.erase (v.begin(),v.begin()+3); } /** * print - outputs the data on the cube in the face order that it was entered. * @param {fstream} stream - output stream to send the data from the cube. * * Notes: If the face order is changed then this hard coding will not work. this * only works in the case where the input order is: Front, Right, Top, * Back, Left, Bottom. * ################# * # Top # * # 16 17 18 # * # 19 $ 20 # * # 21 22 23 # * #################################################### * # Left # Front # Right # * # 32 33 34 # 0 1 2 # 8 9 10 # * # 35 $ 36 # 3 $ 4 # 11 $ 12 # * # 37 38 39 # 5 6 7 # 13 14 15 # * #################################################### * # Bottom # * # 40 41 42 # * # 43 $ 44 # * # 45 46 47 # * ################# * # Back # * # 31 30 29 # * # 28 $ 27 # * # 26 25 24 # * ################# */ void Cube::print(fstream& stream) { vector<int> v; //Print faces in order: Front, Right, Top, Back, Left, Bottom /* Front - band(0): 0, 1, 2 | band(2): 1 | band(3): 1 | band(1): 0, 1, 2 */ v.push_back(bands[0][0]); v.push_back(bands[0][1]); v.push_back(bands[0][2]); v.push_back(bands[2][1]); v.push_back(bands[3][1]); v.push_back(bands[1][0]); v.push_back(bands[1][1]); v.push_back(bands[1][2]); /* Right - band(0): 3, 4, 5 | band(5): 4 | band(4): 4 | band(1): 3, 4, 5 */ v.push_back(bands[0][3]); v.push_back(bands[0][4]); v.push_back(bands[0][5]); v.push_back(bands[5][4]); v.push_back(bands[4][4]); v.push_back(bands[1][3]); v.push_back(bands[1][4]); v.push_back(bands[1][5]); /* Top - band(4): 0, 1, 2 | band(2): 10 | band(3): 10 | band(5): 0, 1, 2 */ v.push_back(bands[4][0]); v.push_back(bands[4][1]); v.push_back(bands[4][2]); v.push_back(bands[2][10]); v.push_back(bands[3][10]); v.push_back(bands[5][0]); v.push_back(bands[5][1]); v.push_back(bands[5][2]); /* Back - band(0): 6, 7, 8 | band(2): 7 | band(3): 7 | band(1): 6, 7, 8 */ v.push_back(bands[0][6]); v.push_back(bands[0][7]); v.push_back(bands[0][8]); v.push_back(bands[3][7]); v.push_back(bands[2][7]); v.push_back(bands[1][6]); v.push_back(bands[1][7]); v.push_back(bands[1][8]); /* Left - band(0): 9, 10, 11 | band(4): 10 | band(5): 10 | band(1): 9, 10, 11 */ v.push_back(bands[0][9]); v.push_back(bands[0][10]); v.push_back(bands[0][11]); v.push_back(bands[4][10]); v.push_back(bands[5][10]); v.push_back(bands[1][9]); v.push_back(bands[1][10]); v.push_back(bands[1][11]); /* Bottom - band(5): 8, 7, 6 | band(2): 4 | band(3): 4 | band(4): 8, 7, 6 */ v.push_back(bands[5][8]); v.push_back(bands[5][7]); v.push_back(bands[5][6]); v.push_back(bands[2][4]); v.push_back(bands[3][4]); v.push_back(bands[4][8]); v.push_back(bands[4][7]); v.push_back(bands[4][6]); int index; for (auto it = begin(v); it!=end(v); ++it) { index = *it; stream << pips[index]->data; } v.erase (v.begin(),v.begin()+48); } /** * print - outputs the data on the cube in the face order that it was entered. * @param {fstream} stream - output stream to send the data from the cube. * * Notes: If the face order is changed then this hard coding will not work. this * only works in the case where the input order is: Front, Right, Top, * Back, Left, Bottom. * ################# * # Top # * # 16 17 18 # * # 19 $ 20 # * # 21 22 23 # * #################################################### * # Left # Front # Right # * # 32 33 34 # 0 1 2 # 8 9 10 # * # 35 $ 36 # 3 $ 4 # 11 $ 12 # * # 37 38 39 # 5 6 7 # 13 14 15 # * #################################################### * # Bottom # * # 40 41 42 # * # 43 $ 44 # * # 45 46 47 # * ################# * # Back # * # 31 30 29 # * # 28 $ 27 # * # 26 25 24 # * ################# */ void Cube::print() { vector<int> v; //Print faces in order: Front, Right, Top, Back, Left, Bottom /* Front - band(0): 0, 1, 2 | band(2): 1 | band(3): 1 | band(1): 0, 1, 2 */ v.push_back(bands[0][0]); v.push_back(bands[0][1]); v.push_back(bands[0][2]); v.push_back(bands[2][1]); v.push_back(bands[3][1]); v.push_back(bands[1][0]); v.push_back(bands[1][1]); v.push_back(bands[1][2]); /* Right - band(0): 3, 4, 5 | band(5): 4 | band(4): 4 | band(1): 3, 4, 5 */ v.push_back(bands[0][3]); v.push_back(bands[0][4]); v.push_back(bands[0][5]); v.push_back(bands[5][4]); v.push_back(bands[4][4]); v.push_back(bands[1][3]); v.push_back(bands[1][4]); v.push_back(bands[1][5]); /* Top - band(4): 0, 1, 2 | band(2): 10 | band(3): 10 | band(5): 0, 1, 2 */ v.push_back(bands[4][0]); v.push_back(bands[4][1]); v.push_back(bands[4][2]); v.push_back(bands[2][10]); v.push_back(bands[3][10]); v.push_back(bands[5][0]); v.push_back(bands[5][1]); v.push_back(bands[5][2]); /* Back - band(0): 6, 7, 8 | band(2): 7 | band(3): 7 | band(1): 6, 7, 8 */ v.push_back(bands[0][6]); v.push_back(bands[0][7]); v.push_back(bands[0][8]); v.push_back(bands[3][7]); v.push_back(bands[2][7]); v.push_back(bands[1][6]); v.push_back(bands[1][7]); v.push_back(bands[1][8]); /* Left - band(0): 9, 10, 11 | band(4): 10 | band(5): 10 | band(1): 9, 10, 11 */ v.push_back(bands[0][9]); v.push_back(bands[0][10]); v.push_back(bands[0][11]); v.push_back(bands[4][10]); v.push_back(bands[5][10]); v.push_back(bands[1][9]); v.push_back(bands[1][10]); v.push_back(bands[1][11]); /* Bottom - band(5): 8, 7, 6 | band(2): 4 | band(3): 4 | band(4): 8, 7, 6 */ v.push_back(bands[5][8]); v.push_back(bands[5][7]); v.push_back(bands[5][6]); v.push_back(bands[2][4]); v.push_back(bands[3][4]); v.push_back(bands[4][8]); v.push_back(bands[4][7]); v.push_back(bands[4][6]); int index; string str = ""; for (auto it = begin(v); it!=end(v); ++it) { index = *it; str += pips[index]->data; } cout << str << endl; v.erase (v.begin(),v.begin()+48); } void Cube::print_bands() { for (int i = 0; i < 6; i++) { for (int k = 0; k < 12; k++) { cout << bands[i][k] << "\t"; } cout << endl; } }
35.115234
81
0.47333
mriddell001
c7b997bd30d468336e60d9d3bb6a3d84c5325abc
511
hpp
C++
src/quail-ground/System.hpp
stanford-ssi/SpaceSalmon
79d8b17f02e317ef547e8097bbbb2277785ebabb
[ "MIT" ]
12
2019-03-30T00:09:33.000Z
2022-02-21T11:48:34.000Z
src/quail-ground/System.hpp
stanford-ssi/SpaceSalmon
79d8b17f02e317ef547e8097bbbb2277785ebabb
[ "MIT" ]
20
2019-02-09T06:41:46.000Z
2022-03-18T10:13:09.000Z
src/quail-ground/System.hpp
stanford-ssi/SpaceSalmon
79d8b17f02e317ef547e8097bbbb2277785ebabb
[ "MIT" ]
2
2019-09-18T13:13:17.000Z
2020-11-25T00:24:11.000Z
#pragma once class System; #include <Arduino.h> #include "LoggerTask.hpp" #include "RadioTask.hpp" #include "TXTask.hpp" #include "RXTask.hpp" class System { public: const bool shitl = false; const bool silent = true; class Tasks { public: LoggerTask logger = LoggerTask(5); //logs to USB/SD RadioTask radio = RadioTask(2); //controls radio TXTask test = TXTask(3); //test RXTask rx = RXTask(4); }; Tasks tasks; }; #include "main.hpp"
16.483871
59
0.612524
stanford-ssi
c7bb513026790fee3e2101bc66e07a701b498327
768
cpp
C++
Jugador.cpp
mikeandino/Lab4-P3-Grupo6
447be4989bb45ed7341b8da81896809e72e80dfb
[ "MIT" ]
null
null
null
Jugador.cpp
mikeandino/Lab4-P3-Grupo6
447be4989bb45ed7341b8da81896809e72e80dfb
[ "MIT" ]
null
null
null
Jugador.cpp
mikeandino/Lab4-P3-Grupo6
447be4989bb45ed7341b8da81896809e72e80dfb
[ "MIT" ]
null
null
null
#include "Jugador.h" Jugador::Jugador(string nombre,string usuario,string clave,int puntuacion){ this->nombre=nombre; this->usuario=usuario; this->clave=clave; this->puntuacion=puntuacion; } Jugador::Jugador(){ }void Jugador::setNombre(string nombre){ this-> nombre=nombre; } string Jugador::getNombre(){ return nombre; } void Jugador::setUsuario(string usuario){ this-> usuario=usuario; } string Jugador::getUsuario(){ return usuario; } void Jugador::setClave(string clave){ this-> clave=clave; } string Jugador::getClave(){ return clave; } void Jugador::setPuntuacion(int puntuacion){ this-> puntuacion=puntuacion; } int Jugador::getPuntuacion(){ return puntuacion; } Jugador::~Jugador(){ cout<<"El jugador a sido destruido."<<endl; }
20.210526
75
0.722656
mikeandino
c7be54e3819e4ae3845255f7944b014d29338612
1,864
cpp
C++
utils/files.cpp
Bill2462/calculon
8caa1b346eae5b1320b2786468ec3caac607d583
[ "MIT" ]
null
null
null
utils/files.cpp
Bill2462/calculon
8caa1b346eae5b1320b2786468ec3caac607d583
[ "MIT" ]
null
null
null
utils/files.cpp
Bill2462/calculon
8caa1b346eae5b1320b2786468ec3caac607d583
[ "MIT" ]
null
null
null
/** * @file files.cpp * @brief This source file contains code for saving and loading numpy array. * @author Krzysztof Adamkiewicz * @date 31/9/2019 */ // This file is part of measurements laboratory excercise solution. // Copyright (c) 2019 Krzysztof Adamkiewicz <kadamkiewicz835@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the “Software”), to deal in the // Software without restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, subject to the // following conditions: THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF // OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "utils.hpp" #include "cnpy/cnpy.h" /** * @brief Load signal from file. * @param fileName Name of the file. * @return Vector of data points. */ std::vector<double> loadSignal(const std::string& fileName) { cnpy::NpyArray arr = cnpy::npy_load(fileName); double* ptr = arr.data<double>(); return std::vector<double>(ptr, ptr+arr.shape[0]); } /** * @brief Save signal to a file. * @param signal Vector of signal points. * @param fileName Name of thw file. */ void saveSignal(const std::vector<double>& signal, const std::string& fileName) { cnpy::npy_save(fileName, &signal[0], {signal.size()}, "w"); }
39.659574
88
0.73176
Bill2462
c7c20785f62f1b31150de74d37b64e3c03b73d25
265
cpp
C++
Engine/Source/Runtime/GameplayAbilities/Private/GameplayEffectExtension.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/GameplayAbilities/Private/GameplayEffectExtension.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Runtime/GameplayAbilities/Private/GameplayEffectExtension.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "AbilitySystemPrivatePCH.h" #include "GameplayEffectExtension.h" UGameplayEffectExtension::UGameplayEffectExtension(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { }
24.090909
95
0.822642
PopCap
c7c5a05817b97764658b2f9ca69b2a485a7699fb
1,017
hpp
C++
src/integrated/IntegratedRunner.hpp
Person-93/aima-cpp
08d062dcb971edeaddb9a10083cf6da5a1b869f7
[ "MIT" ]
null
null
null
src/integrated/IntegratedRunner.hpp
Person-93/aima-cpp
08d062dcb971edeaddb9a10083cf6da5a1b869f7
[ "MIT" ]
null
null
null
src/integrated/IntegratedRunner.hpp
Person-93/aima-cpp
08d062dcb971edeaddb9a10083cf6da5a1b869f7
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <atomic> #include "forward.hpp" namespace aima::gui { struct ImGuiWrapper; } namespace aima::IntegratedRunner { /** * Represents an integrated runner that can run apps and demos */ class IntegratedRunner { public: IntegratedRunner(); IntegratedRunner( const IntegratedRunner& ) = delete; IntegratedRunner( IntegratedRunner&& ) = delete; ~IntegratedRunner(); IntegratedRunner& operator=( const IntegratedRunner& ) = delete; IntegratedRunner& operator=( IntegratedRunner&& ) = delete; /** * Show the window with the menu bar for running apps and demos * @param imGuiWrapper * @param shouldRun */ void run( gui::ImGuiWrapper& imGuiWrapper, const std::atomic_bool& shouldRun ); private: void menuBar( gui::ImGuiWrapper& imGuiWrapper ); std::vector<AppPtr> apps; std::vector<IntegratedDemoPtr> demos; }; }
24.804878
87
0.629302
Person-93
c7c69e7fe48fd4a92fafae09debcd9566310f795
1,605
hpp
C++
Array.hpp
ljacobson64/heat-solver
9ca4dde0e1e39c48b21c471809ea1651ceb57a32
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
Array.hpp
ljacobson64/heat-solver
9ca4dde0e1e39c48b21c471809ea1651ceb57a32
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
Array.hpp
ljacobson64/heat-solver
9ca4dde0e1e39c48b21c471809ea1651ceb57a32
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#ifndef ARRAY_H #define ARRAY_H #include "Common.hpp" template <class T> class Array { public: Array<T>(int, int); // Constructor ~Array<T>() {}; // Destructor // Arithmetic operators: two arrays Array<T> operator+(const Array<T>&) const; Array<T> operator-(const Array<T>&) const; Array<T> operator*(const Array<T>&) const; Array<T> operator/(const Array<T>&) const; // Assignment operators: two arrays Array<T>& operator+=(const Array<T>&); Array<T>& operator-=(const Array<T>&); Array<T>& operator*=(const Array<T>&); Array<T>& operator/=(const Array<T>&); // Arithmetic operators: array and constant Array<T> operator+(const T&) const; Array<T> operator-(const T&) const; Array<T> operator*(const T&) const; Array<T> operator/(const T&) const; // Assignment operators: array and constant Array<T>& operator+=(const T&); Array<T>& operator-=(const T&); Array<T>& operator*=(const T&); Array<T>& operator/=(const T&); // Fill an array Array<T>& fill(const Array<T>&); Array<T>& fill(const T&); Array<T>& fill_from_file(const std::string); // Data access T& operator()(const int&, const int&); const T& operator()(const int&, const int&) const; // Data access (1D) T& operator()(const int&); const T& operator()(const int&) const; void print(int, int); void print(int, int, const std::string); void printsci(int); void printsci(int, const std::string); int get_nx() const {return nx;}; int get_ny() const {return ny;}; int get_n() const {return n;}; private: int nx, ny, n; std::vector<T> data; }; #endif
25.078125
52
0.642368
ljacobson64
c7c6e7cd782a2322205594f208ab9c078d388df7
2,283
cpp
C++
More Advanced Topics/More Advanced Search Techniques/ More Challenging State-Space Search with BFS or Dijkstra's/Dancing Digits.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
3
2017-08-12T06:09:39.000Z
2018-09-16T02:31:27.000Z
More Advanced Topics/More Advanced Search Techniques/ More Challenging State-Space Search with BFS or Dijkstra's/Dancing Digits.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
More Advanced Topics/More Advanced Search Techniques/ More Challenging State-Space Search with BFS or Dijkstra's/Dancing Digits.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef vector <int> vi; vi a; bitset <32> bs; unordered_map <int, int> map1; void sieve(){ bs.set(); bs[0]=bs[1]=0; for(int i=2; i<20; i++) if(bs[i]){ for(int j=i*i; j<20; j += i) bs[j] = 0; } } inline int calc(const vi &b){ int sum = 1, res = 0; for(int i=7; i>=0; i--){ res += sum * abs(b[i]); sum *= 10; } return res; } inline void dance(vi &b, int x, int y, int z){ if(!z){ if(x + 1 == y) return; if(x < y){ b.insert(b.begin() + y, b[x]); b.erase(b.begin() + x); }else{ b.insert(b.begin() + y, b[x]); b.erase(b.begin()+x+1); } }else{ if(x - 1 == y) return; if(x < y){ b.insert(b.begin() + y + 1, b[x]); b.erase(b.begin() + x); }else{ b.insert(b.begin() + y + 1, b[x]); b.erase(b.begin()+x+1); } } } void bfs(){ queue <vi> q; q.push(a); queue <int> dist; dist.push(0); map1.clear(); map1[calc(a)] = 1; vi b, c; while(!dist.empty()){ c = q.front(); q.pop(); if(calc(c) == 12345678) break; int distance = dist.front(); dist.pop(); for(int i=0; i<8; i++){ for(int j=0; j<8; j++){ if(c[i]*c[j] < 0 && bs[abs(c[i])+abs(c[j])] && i != j){ for(int k=0; k<2; k++){ b = c; dance(b, i, j, k); if(map1.find(calc(b)) == map1.end()){ map1[calc(b)] = 1; q.push(b); dist.push(distance + 1); } } } } } } if(calc(c) == 12345678) cout << dist.front() << "\n"; else cout << "-1\n"; } int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); sieve(); int n; a.resize(8); int cas = 1; while(cin >> n, n){ cout << "Case " << cas++ << ": "; a[0] = n; for(int i=1; i<8; i++) cin >> a[i]; bfs(); } return 0; }
25.366667
71
0.38502
satvik007
c7c73b9ff219087d1cd00a932d0332e83f052dd7
7,318
cpp
C++
ProcessLib/ComponentTransport/CreateComponentTransportProcess.cpp
hosseinsotudeh/ogs
214afcb00af23e4393168a846c7ee8ce4f13e489
[ "BSD-4-Clause" ]
null
null
null
ProcessLib/ComponentTransport/CreateComponentTransportProcess.cpp
hosseinsotudeh/ogs
214afcb00af23e4393168a846c7ee8ce4f13e489
[ "BSD-4-Clause" ]
null
null
null
ProcessLib/ComponentTransport/CreateComponentTransportProcess.cpp
hosseinsotudeh/ogs
214afcb00af23e4393168a846c7ee8ce4f13e489
[ "BSD-4-Clause" ]
null
null
null
/** * \copyright * Copyright (c) 2012-2018, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license * */ #include "CreateComponentTransportProcess.h" #include "MaterialLib/Fluid/FluidProperties/CreateFluidProperties.h" #include "MaterialLib/PorousMedium/CreatePorousMediaProperties.h" #include "ProcessLib/Output/CreateSecondaryVariables.h" #include "ProcessLib/Parameter/ConstantParameter.h" #include "ProcessLib/Utils/ProcessUtils.h" #include "ComponentTransportProcess.h" #include "ComponentTransportProcessData.h" namespace ProcessLib { namespace ComponentTransport { std::unique_ptr<Process> createComponentTransportProcess( MeshLib::Mesh& mesh, std::unique_ptr<ProcessLib::AbstractJacobianAssembler>&& jacobian_assembler, std::vector<ProcessVariable> const& variables, std::vector<std::unique_ptr<ParameterBase>> const& parameters, unsigned const integration_order, BaseLib::ConfigTree const& config) { //! \ogs_file_param{prj__processes__process__type} config.checkConfigParameter("type", "ComponentTransport"); DBUG("Create ComponentTransportProcess."); auto const staggered_scheme = //! \ogs_file_param{prj__processes__process__ComponentTransport__coupling_scheme} config.getConfigParameterOptional<std::string>("coupling_scheme"); const bool use_monolithic_scheme = !(staggered_scheme && (*staggered_scheme == "staggered")); // Process variable. //! \ogs_file_param{prj__processes__process__ComponentTransport__process_variables} auto const pv_config = config.getConfigSubtree("process_variables"); std::vector<std::vector<std::reference_wrapper<ProcessVariable>>> process_variables; if (use_monolithic_scheme) // monolithic scheme. { auto per_process_variables = findProcessVariables( variables, pv_config, { //! \ogs_file_param_special{prj__processes__process__ComponentTransport__process_variables__concentration} "concentration", //! \ogs_file_param_special{prj__processes__process__ComponentTransport__process_variables__pressure} "pressure"}); process_variables.push_back(std::move(per_process_variables)); } else // staggered scheme. { std::array<std::string, 2> variable_names = { {"concentration", "pressure"}}; // double-braces required in C++11 (not in C++14) for (int i = 0; i < 2; i++) { auto per_process_variables = findProcessVariables(variables, pv_config, {variable_names[i]}); process_variables.push_back(std::move(per_process_variables)); } } MaterialLib::PorousMedium::PorousMediaProperties porous_media_properties{ MaterialLib::PorousMedium::createPorousMediaProperties( mesh, config, parameters)}; //! \ogs_file_param{prj__processes__process__ComponentTransport__fluid} auto const& fluid_config = config.getConfigSubtree("fluid"); auto fluid_properties = MaterialLib::Fluid::createFluidProperties(fluid_config); // Parameter for the density of the fluid. auto& fluid_reference_density= findParameter<double>( config, //! \ogs_file_param_special{prj__processes__process__ComponentTransport__fluid_reference_density} "fluid_reference_density", parameters, 1); DBUG("Use \'%s\' as fluid_reference_density parameter.", fluid_reference_density.name.c_str()); // Parameter for the longitudinal molecular diffusion coefficient. auto const& molecular_diffusion_coefficient = findParameter<double>( config, //! \ogs_file_param_special{prj__processes__process__ComponentTransport__molecular_diffusion_coefficient} "molecular_diffusion_coefficient", parameters, 1); DBUG("Use \'%s\' as molecular diffusion coefficient parameter.", molecular_diffusion_coefficient.name.c_str()); // Parameter for the longitudinal solute dispersivity. auto const& solute_dispersivity_longitudinal = findParameter<double>( config, //! \ogs_file_param_special{prj__processes__process__ComponentTransport__solute_dispersivity_longitudinal} "solute_dispersivity_longitudinal", parameters, 1); DBUG("Use \'%s\' as longitudinal solute dispersivity parameter.", solute_dispersivity_longitudinal.name.c_str()); // Parameter for the transverse solute dispersivity. auto const& solute_dispersivity_transverse = findParameter<double>( config, //! \ogs_file_param_special{prj__processes__process__ComponentTransport__solute_dispersivity_transverse} "solute_dispersivity_transverse", parameters, 1); DBUG("Use \'%s\' as transverse solute dispersivity parameter.", solute_dispersivity_transverse.name.c_str()); // Parameter for the retardation factor. auto const& retardation_factor = findParameter<double>(config, //! \ogs_file_param_special{prj__processes__process__ComponentTransport__retardation_factor} "retardation_factor", parameters, 1); // Parameter for the decay rate. auto const& decay_rate = findParameter<double>(config, //! \ogs_file_param_special{prj__processes__process__ComponentTransport__decay_rate} "decay_rate", parameters, 1); // Specific body force parameter. Eigen::VectorXd specific_body_force; std::vector<double> const b = //! \ogs_file_param{prj__processes__process__ComponentTransport__specific_body_force} config.getConfigParameter<std::vector<double>>("specific_body_force"); assert(b.size() > 0 && b.size() < 4); if (b.size() < mesh.getDimension()) OGS_FATAL( "specific body force (gravity vector) has %d components, mesh " "dimension is %d", b.size(), mesh.getDimension()); bool const has_gravity = MathLib::toVector(b).norm() > 0; if (has_gravity) { specific_body_force.resize(b.size()); std::copy_n(b.data(), b.size(), specific_body_force.data()); } ComponentTransportProcessData process_data{ std::move(porous_media_properties), fluid_reference_density, std::move(fluid_properties), molecular_diffusion_coefficient, solute_dispersivity_longitudinal, solute_dispersivity_transverse, retardation_factor, decay_rate, specific_body_force, has_gravity}; SecondaryVariableCollection secondary_variables; NumLib::NamedFunctionCaller named_function_caller( {"ComponentTransport_concentration_pressure"}); ProcessLib::createSecondaryVariables(config, secondary_variables, named_function_caller); return std::make_unique<ComponentTransportProcess>( mesh, std::move(jacobian_assembler), parameters, integration_order, std::move(process_variables), std::move(process_data), std::move(secondary_variables), std::move(named_function_caller), use_monolithic_scheme); } } // namespace ComponentTransport } // namespace ProcessLib
41.344633
118
0.715633
hosseinsotudeh
c7cf7c6d391920a9196732d9aefc37a83e4938ca
1,559
cpp
C++
src/iislua/cluahttpmodule.cpp
shibayan/iislua
b0fe6fb0c204748928b6dd3205d0fe42f899d20c
[ "Apache-2.0" ]
16
2015-10-09T08:03:24.000Z
2022-03-30T08:54:10.000Z
src/iislua/cluahttpmodule.cpp
shibayan/iislua
b0fe6fb0c204748928b6dd3205d0fe42f899d20c
[ "Apache-2.0" ]
6
2015-09-18T08:12:42.000Z
2020-04-05T07:00:14.000Z
src/iislua/cluahttpmodule.cpp
shibayan/iislua
b0fe6fb0c204748928b6dd3205d0fe42f899d20c
[ "Apache-2.0" ]
7
2017-09-12T09:53:20.000Z
2022-02-28T23:50:03.000Z
#include "stdafx.h" CLuaHttpModule::CLuaHttpModule(CLuaStatePool* pLuaStatePool) : L(nullptr), pLuaStatePool(pLuaStatePool) { } CLuaHttpModule::~CLuaHttpModule() { if (L != nullptr) { pLuaStatePool->Release(L); L = nullptr; } } REQUEST_NOTIFICATION_STATUS CLuaHttpModule::OnExecuteCore(IN IHttpContext* pHttpContext, IN IHttpEventProvider* pProvider, IN const char* name) { if (L == nullptr) { L = pLuaStatePool->Acquire(pHttpContext, pProvider); } lua_getglobal(L, name); if (!lua_isfunction(L, -1)) { lua_pop(L, 1); return RQ_NOTIFICATION_CONTINUE; } if (lua_pcall(L, 0, 1, 0)) { auto error = lua_tostring(L, -1); pHttpContext->GetResponse()->SetStatus(500, "Internal Server Error"); return RQ_NOTIFICATION_FINISH_REQUEST; } return iislua_finish_request(L); } REQUEST_NOTIFICATION_STATUS CLuaHttpModule::OnAsyncCompletion(IN IHttpContext* pHttpContext, IN DWORD dwNotification, IN BOOL fPostNotification, IN IHttpEventProvider* pProvider, IN IHttpCompletionInfo* pCompletionInfo) { UNREFERENCED_PARAMETER(pHttpContext); UNREFERENCED_PARAMETER(dwNotification); UNREFERENCED_PARAMETER(fPostNotification); UNREFERENCED_PARAMETER(pProvider); UNREFERENCED_PARAMETER(pCompletionInfo); auto storedContext = CLuaHttpStoredContext::GetContext(pHttpContext); storedContext->GetChildContext()->ReleaseClonedContext(); storedContext->SetChildContext(nullptr); return RQ_NOTIFICATION_CONTINUE; }
25.983333
219
0.717768
shibayan
c7d089ee746f7b991c88b51b978fe3b04a663a31
4,775
cpp
C++
src/Player.cpp
ScaredStorm/Platformer-Prototype
6ef4463e6e939f3bf06918150cb07933a40baa83
[ "MIT" ]
null
null
null
src/Player.cpp
ScaredStorm/Platformer-Prototype
6ef4463e6e939f3bf06918150cb07933a40baa83
[ "MIT" ]
null
null
null
src/Player.cpp
ScaredStorm/Platformer-Prototype
6ef4463e6e939f3bf06918150cb07933a40baa83
[ "MIT" ]
null
null
null
#include "Player.h" Player::Player(Level *level, SDL_Texture* sprite, float x, float y, int id) : Entity(sprite, x, y) , m_level(level) { std::printf("Player position: %fx%f\n", m_x, m_y); m_leftPressed = false; m_rightPressed = false; m_upPressed = false; m_downPressed = false; m_onGround = false; m_xVel = 0; m_yVel = 0; m_width = 16; m_height = 16; m_playerId = id; m_dir = 1; flip = SDL_FLIP_NONE; } void Player::update() { checkCollision(); m_x += m_xVel; m_y += m_yVel; if(!m_onGround) { if (m_yVel < 5.0f) m_yVel += 0.5f; } /* PLAYER MOVEMENT */ if(m_rightPressed) { m_dir = 1; m_xVel = 1.0f; flip = SDL_FLIP_NONE; } if(m_leftPressed) { m_dir = -1; m_xVel = -1.0f; flip = SDL_FLIP_HORIZONTAL; } if (!m_rightPressed && !m_leftPressed) { m_xVel = 0.0f; } if (m_upPressed && m_onGround) m_yVel = -6.0f; std::printf("yVel: %f, xVel: %f\n", m_yVel, m_xVel); } void Player::setPos(int x, int y) { m_x = (float)x; m_y = (float)y; } void Player::handleInput(SDL_Event &e) { // Key Pressed if(e.type == SDL_KEYDOWN) { SDL_Keycode k = e.key.keysym.sym; switch(k) { case SDLK_z: m_upPressed = true; break; case SDLK_DOWN: //m_downPressed = true; break; case SDLK_LEFT: m_leftPressed = true; break; case SDLK_RIGHT: m_rightPressed = true; break; } } // Key Released if(e.type == SDL_KEYUP) { SDL_Keycode k = e.key.keysym.sym; switch(k) { case SDLK_z: m_upPressed = false; break; case SDLK_DOWN: //m_downPressed = false; break; case SDLK_LEFT: m_leftPressed = false; m_xVel = 0.0f; break; case SDLK_RIGHT: m_rightPressed = false; m_xVel = 0.0f; break; } } } void Player::render(SDL_Renderer *renderer) { SDL_Rect src; SDL_Rect dst; src.x = m_playerId * 16; src.y = 0; src.w = dst.w = 16; src.h = dst.h = 16; dst.x = m_x; dst.y = m_y; SDL_RenderCopyEx(renderer, m_sprite, &src, &dst, 0.0, NULL, flip); // render weapon SDL_Rect wsrc; SDL_Rect wdst; wsrc.x = m_playerId * 16; wsrc.y = 32; wsrc.w = wdst.w = 16; wsrc.h = wdst.h = 16; wdst.x = m_x+(3 * m_dir); wdst.y = m_y; SDL_RenderCopyEx(renderer, m_sprite, &wsrc, &wdst, 0.0, NULL, flip); #ifdef _DEBUG SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255); SDL_RenderDrawLine(renderer, m_x + 8, m_y + 16, m_x + 8, m_y + 16 + m_yVel); #endif } void Player::checkCollision() { int currRow = (int)m_y/m_level->getTileSize(); int currColumn = (int)m_x/m_level->getTileSize(); int xdest, ydest, xtemp, ytemp; xdest = m_x + m_xVel; ydest = m_y + m_yVel; xtemp = m_x; ytemp = m_y; calculateCorners(m_x, ydest); if (m_yVel < 0) { if (m_topLeft || m_topRight) { m_yVel = 0; } } if (m_yVel > 0) { if (m_bottomLeft || m_bottomRight) { m_yVel = 0; m_onGround = true; } } if (!m_bottomLeft && !m_bottomRight) { m_onGround = false; } else { m_onGround = true; m_yVel = 0; } calculateCorners(xdest, m_y); if(m_xVel > 0) { if(m_topRight || m_bottomRight) { m_xVel = 0; //m_x = currColumn * m_level->getTileSize(); } } if(m_xVel < 0) { if(m_topLeft || m_bottomLeft) { m_xVel = 0; //m_x = currColumn * m_level->getTileSize(); } } } void Player::calculateCorners(float x, float y) { int left = (int)(x+2)/m_level->getTileSize(); int right = (int)(x+m_width-2)/m_level->getTileSize(); int top = (int)(y+4)/m_level->getTileSize(); int bottom = (int)(y+m_height-1)/m_level->getTileSize(); bool tl = m_level->canCollide(left, top); bool tr = m_level->canCollide(right, top); bool bl = m_level->canCollide(left, bottom); bool br = m_level->canCollide(right, bottom); m_topLeft = tl; m_topRight = tr; m_bottomLeft = bl; m_bottomRight = br; }
20.76087
78
0.493613
ScaredStorm
c7d3cb0b68196ff15483ee6a770f3849d60111ed
389
hpp
C++
UnsharpMask/Include/ImageFilter/ImageFilter.hpp
cristian-szabo/unsharp-mask-opencl
c760a45ff9af38089ca1fa5cfd99a9f85dc36bff
[ "MIT" ]
4
2017-10-28T08:54:55.000Z
2020-06-08T12:30:30.000Z
UnsharpMask/Include/ImageFilter/ImageFilter.hpp
cristian-szabo/unsharp-mask-opencl
c760a45ff9af38089ca1fa5cfd99a9f85dc36bff
[ "MIT" ]
null
null
null
UnsharpMask/Include/ImageFilter/ImageFilter.hpp
cristian-szabo/unsharp-mask-opencl
c760a45ff9af38089ca1fa5cfd99a9f85dc36bff
[ "MIT" ]
null
null
null
#pragma once #include "PPM.hpp" class ImageProcess; class UNSHARP_MASK_PUBLIC ImageFilter { public: virtual ~ImageFilter(); protected: virtual bool onLoad(std::shared_ptr<ImageProcess> proc); virtual void onBefore(std::uint32_t glTexId); virtual std::uint64_t onApply(const PPM& image) = 0; virtual void onAfter(); private: friend class ImageProcess; };
14.407407
60
0.714653
cristian-szabo
c7d7ad92d8c7affe12f540ca47bfb437d741eb77
3,076
cpp
C++
sequencediagrambuilder.cpp
abhinavarora/Model-Based-Testing-and-Test-Case-Prioritization-using-Genetic-Algorithm
6a6899b93e1911f50ad05c845aa1bf1325b37cf0
[ "MIT", "Unlicense" ]
4
2019-11-18T14:57:49.000Z
2021-04-21T09:36:32.000Z
sequencediagrambuilder.cpp
abhinavarora/Model-Based-Testing-and-Test-Case-Prioritization-using-Genetic-Algorithm
6a6899b93e1911f50ad05c845aa1bf1325b37cf0
[ "MIT", "Unlicense" ]
null
null
null
sequencediagrambuilder.cpp
abhinavarora/Model-Based-Testing-and-Test-Case-Prioritization-using-Genetic-Algorithm
6a6899b93e1911f50ad05c845aa1bf1325b37cf0
[ "MIT", "Unlicense" ]
2
2016-10-12T01:28:04.000Z
2017-07-11T21:50:58.000Z
#include "sequencediagrambuilder.h" #include "actorbuilder.h" #include "messagebuilder.h" #include "combinedfragmentbuilder.h" #include "node.h" #include <iostream> using namespace std; SequenceDiagramBuilder::SequenceDiagramBuilder(string inputFile) { (this->doc).LoadFile(); if(! (this->doc.LoadFile(inputFile.c_str()))) { cerr << doc.ErrorDesc() << endl; } (this->docEle) = (this->doc).FirstChildElement(); } void SequenceDiagramBuilder::build(SequenceDiagram& sd) { CombinedFragment cf_null(string(""),-1); vector<Message> msgList; vector<Actor> actorList = sd.getActorList(); ActorBuilder acb; acb.build(actorList,(this->docEle)); for(unsigned int i =0; i < actorList.size(); i++) { string var = actorList[i].toString(); cout<<var<<endl; } MessageBuilder mb; mb.build(actorList,msgList,(this->docEle)); for(unsigned int i =0; i<msgList.size();i++) { Message_List[msgList[i].getID()] = NULL; } vector<CombinedFragment> fragList; vector<TiXmlElement*> ele_fragList; ele_fragList = (this->docEle)->GetElementsByTagName("fragment",ele_fragList); if(ele_fragList.size()>0) { for(unsigned int i =0; i<ele_fragList.size(); i++) { if(ele_fragList[i]->Attribute("xmi:type")!=NULL && ele_fragList[i]->Attribute("xmi:type") == string("uml:CombinedFragment")) { CombinedFragment cf; CombinedFragmentBuilder cfb; cf = cfb.build(ele_fragList[i],msgList); fragList.push_back(cf); } } } vector<TiXmlElement*> nl; nl = (this->docEle)->GetElementsByTagName("uml:DiagramElement",nl); for(unsigned int i=0; i<nl.size(); i++) { if(nl[i]->Attribute("preferredShapeType")!= NULL && nl[i]->Attribute("preferredShapeType") == string("Message")) { for(unsigned int j =0; j<msgList.size(); j++) { if(nl[i]->Attribute("subject")!= NULL && nl[i]->Attribute("subject") == msgList[j].getID() && Message_List[msgList[j].getID()]==NULL) { Node temp(msgList[j].getType(),msgList[j]); sd.push_seq(temp); } } } else if(nl[i]->Attribute("preferredShapeType")!= NULL && nl[i]->Attribute("preferredShapeType") == string("CombinedFragment")) { for(unsigned int j =0; j<fragList.size(); j++) { if(nl[i]->Attribute("subject")!= NULL && nl[i]->Attribute("subject") == fragList[j].getID()) { CombinedFragment *tem = new CombinedFragment; *tem = fragList[j]; Node temp(tem->getType(),tem); sd.push_seq(temp); } } } } /*for (map<string, int>::const_iterator i = Partitions.begin(); i != Partitions.end(); ++i) cout << i->first << ": " << i->second << endl;*/ cout<<"asddfd "<<fragList.size()<<endl;; }
33.075269
149
0.558843
abhinavarora
93a0b6142ff0df5b83e8072db1d9f34ea015b464
2,785
cpp
C++
examples2/axFileGen/FileGenOps/Sequence.cpp
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
examples2/axFileGen/FileGenOps/Sequence.cpp
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
examples2/axFileGen/FileGenOps/Sequence.cpp
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
//=---------------------------------------------------------------------= // // $Id$ $Name$ // // The contents of this file are subject to the AAF SDK Public Source // License Agreement Version 2.0 (the "License"); You may not use this // file except in compliance with the License. The License is available // in AAFSDKPSL.TXT, or you may obtain a copy of the License from the // Advanced Media Workflow Association, Inc., or its successor. // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See // the License for the specific language governing rights and limitations // under the License. Refer to Section 3.3 of the License for proper use // of this Exhibit. // // WARNING: Please contact the Advanced Media Workflow Association, // Inc., for more information about any additional licenses to // intellectual property covering the AAF Standard that may be required // to create and distribute AAF compliant products. // (http://www.amwa.tv/policies). // // Copyright Notices: // The Original Code of this file is Copyright 1998-2009, licensor of the // Advanced Media Workflow Association. All rights reserved. // //=---------------------------------------------------------------------= #include <axFileGen.h> #include <AxDictionary.h> #include <AxComponent.h> namespace { //=---------------------------------------------------------------------= AXFG_OP( Sequence, L"Sequence", L"Create a sequence object.", L"FileName DataDefName SequenceName", L"", 4, 4 ) Sequence::~Sequence() {} void Sequence::Execute( const std::vector<AxString>& argv ) { AxString fileName = argv[1]; AxString dataDefName = argv[2]; AxString seqName = argv[3]; AxDictionary axDict( DictionaryFromFileOp( fileName ) ); IAAFSequenceSP spSeq; AxCreateInstance( axDict, spSeq ); AxSequence axSeq( spSeq ); IAAFDataDefSP spDataDef; GetInstance( dataDefName).GetCOM( spDataDef ); axSeq.Initialize( spDataDef ); SetCOM( spSeq ); RegisterInstance( seqName ); } //=---------------------------------------------------------------------= AXFG_OP( AppendComponent, L"AppendComponent", L"Append a component to a sequence.", L"SequenceName ComponentName", L"", 3, 3 ) AppendComponent::~AppendComponent() {} void AppendComponent::Execute( const std::vector<AxString>& argv ) { AxString seqName = argv[1]; AxString compName = argv[2]; IAAFSequenceSP spSeq; GetInstance( seqName ).GetCOM( spSeq ); AxSequence axSeq( spSeq ); IAAFComponentSP spComp; GetInstance( compName ).GetCOM( spComp ); axSeq.AppendComponent( spComp ); } //=---------------------------------------------------------------------= } // end of namespace
26.273585
73
0.622262
Phygon
93a1211d0f9019122eab720ba87137a45c60f187
11,386
hh
C++
include/vkpp/buffer.hh
clayne/vkhr
ffcc0394c0991049337011e45ff3da9f3bd1bbe5
[ "MIT" ]
403
2019-05-27T20:17:12.000Z
2022-03-19T17:32:16.000Z
include/vkpp/buffer.hh
tangxianbo/vkhr
22713d0d9a7d42f207a86fac1d02f626e6007217
[ "MIT" ]
5
2019-06-19T15:46:41.000Z
2021-11-26T00:12:39.000Z
include/vkpp/buffer.hh
tangxianbo/vkhr
22713d0d9a7d42f207a86fac1d02f626e6007217
[ "MIT" ]
31
2019-06-05T02:32:17.000Z
2022-02-04T04:13:29.000Z
#ifndef VKPP_BUFFER_HH #define VKPP_BUFFER_HH #include <vkpp/device_memory.hh> #include <vulkan/vulkan.h> #include <vector> #include <cstring> #include <set> namespace vkpp { class Queue; class CommandPool; class CommandBuffer; class Device; class Buffer { public: Buffer() = default; Buffer(Device& device, VkDeviceSize size_in_bytes, VkBufferUsageFlags usage); Buffer(Device& device, VkDeviceSize size, VkBufferUsageFlags usage, std::vector<Queue>& fam); virtual ~Buffer() noexcept; Buffer(Buffer&& buffer) noexcept; Buffer& operator=(Buffer&& buffer) noexcept; friend void swap(Buffer& lhs, Buffer& rhs); VkBuffer& get_handle(); VkDeviceSize get_size() const; VkDeviceMemory& get_bound_memory(); VkMemoryRequirements get_memory_requirements() const; VkSharingMode get_sharing_mode() const; VkBufferUsageFlags get_usage() const; void bind(DeviceMemory& device_memory, std::uint32_t offset = 0); protected: VkDeviceSize size_in_bytes; VkSharingMode sharing_mode; VkBufferUsageFlags usage; VkDeviceMemory memory { VK_NULL_HANDLE }; VkDevice device { VK_NULL_HANDLE }; VkBuffer handle { VK_NULL_HANDLE }; }; class DeviceBuffer : public Buffer { public: DeviceBuffer() = default; friend void swap(DeviceBuffer& lhs, DeviceBuffer& rhs); DeviceBuffer& operator=(DeviceBuffer&& buffer) noexcept; DeviceBuffer(DeviceBuffer&& buffer) noexcept; DeviceBuffer(Device& device, CommandPool& command_buffer, const void* buffer, VkDeviceSize size, VkBufferUsageFlags usage); DeviceBuffer(Device& device, VkDeviceSize size, VkBufferUsageFlags usage); DeviceMemory& get_device_memory(); protected: DeviceMemory device_memory; }; class VertexBuffer : public DeviceBuffer { public: struct Attribute { std::uint32_t location; VkFormat format; std::uint32_t offset { 0 }; }; using Bindings = std::vector<VkVertexInputBindingDescription>; using Attributes = std::vector<VkVertexInputAttributeDescription>; VertexBuffer() = default; friend void swap(VertexBuffer& lhs, VertexBuffer& rhs); VertexBuffer& operator=(VertexBuffer&& buffer) noexcept; VertexBuffer(VertexBuffer&& buffer) noexcept; template<typename T> VertexBuffer(Device& device, CommandPool& command_buffer, const std::vector<T>& vertices, std::uint32_t binding = 0, const std::vector<Attribute> attributes = {}); std::uint32_t get_binding_id() const; const VkVertexInputBindingDescription& get_binding() const; const Attributes& get_attributes() const; std::uint32_t count() const; private: VkDeviceSize element_count; VkVertexInputBindingDescription binding; std::vector<VkVertexInputAttributeDescription> attributes; }; class IndexBuffer : public DeviceBuffer { public: IndexBuffer() = default; friend void swap(IndexBuffer& lhs, IndexBuffer& rhs); IndexBuffer& operator=(IndexBuffer&& buffer) noexcept; IndexBuffer(IndexBuffer&& buffer) noexcept; IndexBuffer(Device& device, CommandPool& command_buffer, const std::vector<unsigned short>& indices); IndexBuffer(Device& device, CommandPool& command_buffer, const std::vector<unsigned>& indices); VkIndexType get_type() const; std::uint32_t count() const; private: VkDeviceSize element_count; VkIndexType index_type; }; class StorageBuffer : public DeviceBuffer { public: StorageBuffer() = default; friend void swap(StorageBuffer& lhs, StorageBuffer& rhs); StorageBuffer& operator=(StorageBuffer&& buffer) noexcept; StorageBuffer(StorageBuffer&& buffer) noexcept; template<typename T> StorageBuffer(Device& device, CommandPool& command_pool, const T& buffer); template<typename T> StorageBuffer(Device& device, CommandPool& command_pool, const std::vector<T>& vector); StorageBuffer(Device& device, VkDeviceSize size); Buffer& get_staging_buffer(); DeviceMemory& get_staging_memory(); template<typename T> void staged_copy(T& object, CommandBuffer& command_buffer); template<typename T> void staged_copy(T& object, CommandPool& command_pool); template<typename T> void staged_copy(std::vector<T>& vector, CommandBuffer& command_buffer); template<typename T> void staged_copy(std::vector<T>& vector, CommandPool& command_pool); private: Buffer staging_buffer; DeviceMemory staging_memory; }; class HostBuffer : public Buffer { public: HostBuffer() = default; friend void swap(HostBuffer& lhs, HostBuffer& rhs); HostBuffer& operator=(HostBuffer&& buffer) noexcept; HostBuffer(HostBuffer&& buffer) noexcept; HostBuffer(Device& device, const void* buffer, VkDeviceSize size, VkBufferUsageFlags usage); HostBuffer(Device& device, VkDeviceSize size, VkBufferUsageFlags usage); DeviceMemory& get_device_memory(); protected: DeviceMemory device_memory; }; class UniformBuffer : public HostBuffer { public: UniformBuffer() = default; friend void swap(UniformBuffer& lhs, UniformBuffer& rhs); UniformBuffer& operator=(UniformBuffer&& buffer) noexcept; UniformBuffer(UniformBuffer&& buffer) noexcept; template<typename T> UniformBuffer(Device& device, const T& buffer); template<typename T> UniformBuffer(Device& device, const std::vector<T>& vector); UniformBuffer(Device& device, VkDeviceSize size); static std::vector<UniformBuffer> create(Device& device, VkDeviceSize size, std::size_t n = 1, const char* name = ""); template<typename T> void update(std::vector<T>& vec); template<typename T> void update(T& uniform_data_obj); }; template<typename T> void StorageBuffer::staged_copy(T& object, CommandBuffer& command_buffer) { void* data = reinterpret_cast<void*>(&object); staging_memory.copy(sizeof(T), data); command_buffer.copy_buffer(staging_buffer, *this); } template<typename T> void StorageBuffer::staged_copy(T& object, CommandPool& command_pool) { auto command_buffer = command_pool.allocate_and_begin(); command_buffer.copy_buffer(*this, staging_buffer); command_buffer.end(); T* data { nullptr }; staging_memory.map(0, get_size(), (void**) &data); std::memcpy(&object, data, get_size()); staging_memory.unmap(); } template<typename T> void StorageBuffer::staged_copy(std::vector<T>& vector, CommandPool& command_pool) { auto command_buffer = command_pool.allocate_and_begin(); command_buffer.copy_buffer(*this, staging_buffer); command_buffer.end(); command_pool.get_queue().submit(command_buffer).wait_idle(); T* data { nullptr }; vector.resize(get_size() / sizeof(T)); staging_memory.map(0, get_size(), (void**) &data); std::memcpy(vector.data(), data, get_size()); staging_memory.unmap(); } template<typename T> void StorageBuffer::staged_copy(std::vector<T>& vector, CommandBuffer& command_buffer) { staging_memory.copy(sizeof(T) * vector.size(), vector.data()); command_buffer.copy_buffer(staging_buffer, *this); } template<typename T> VertexBuffer::VertexBuffer(Device& device, CommandPool& command_buffer, const std::vector<T>& vertices, std::uint32_t binding, const std::vector<Attribute> attributes) : DeviceBuffer { device, command_buffer, vertices.data(), sizeof(vertices[0]) * vertices.size(), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT } { this->attributes.reserve(attributes.size()); for (const auto& attribute : attributes) { this->attributes.push_back({ attribute.location, binding, attribute.format, attribute.offset }); } this->element_count = vertices.size(); this->binding = { binding, sizeof(vertices[0]), VK_VERTEX_INPUT_RATE_VERTEX }; } template<typename T> StorageBuffer::StorageBuffer(Device& device, CommandPool& command_pool, const T& buffer) : DeviceBuffer { device, command_pool, &buffer, sizeof(T), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT } { } template<typename T> StorageBuffer::StorageBuffer(Device& device, CommandPool& command_pool, const std::vector<T>& vector) : DeviceBuffer { device, command_pool, vector.data(), vector.size() * sizeof(T), VK_BUFFER_USAGE_STORAGE_BUFFER_BIT } { } template<typename T> UniformBuffer::UniformBuffer(Device& device, const T& buffer) : HostBuffer { device, &buffer, sizeof(T), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT } { } template<typename T> UniformBuffer::UniformBuffer(Device& device, const std::vector<T>& vector) : HostBuffer { device, vector.data(), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT } { } template<typename T> void UniformBuffer::update(T& data_object) { void* data = reinterpret_cast<void*>(&data_object); device_memory.copy(device_memory.get_size(), data); } template<typename T> void UniformBuffer::update(std::vector<T>& data_vector) { device_memory.copy(data_vector.size() * sizeof(T), data_vector.data()); } } #endif
34.08982
126
0.576497
clayne
93a2948703ae1c6bb6758b7ca11b3391cc6ff286
1,107
cpp
C++
src/imageprocessing/AddingBorderImage.cpp
snandasena/opencv-cpp-examples
7423445d52f38fff80df37698b77ac9f9f5e7945
[ "MIT" ]
null
null
null
src/imageprocessing/AddingBorderImage.cpp
snandasena/opencv-cpp-examples
7423445d52f38fff80df37698b77ac9f9f5e7945
[ "MIT" ]
1
2020-04-28T03:35:49.000Z
2020-04-28T03:35:49.000Z
src/imageprocessing/AddingBorderImage.cpp
snandasena/opencv-cpp-examples
7423445d52f38fff80df37698b77ac9f9f5e7945
[ "MIT" ]
null
null
null
#include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> using namespace cv; cv::Mat src, dst; int top, bottom, left, right; int borderType = cv::BORDER_CONSTANT; const char *window_name = "Copy border demo"; cv::RNG rng(12345); int main() { src = cv::imread("./images/cute-dog.jpg", cv::IMREAD_COLOR); if (src.empty()) { return -1; } cv::namedWindow(window_name, cv::WINDOW_AUTOSIZE); // initialize args for the filter top = (int) (0.05 * src.rows); bottom = top; left = (int) (0.05 * src.cols); right = left; while (true) { cv::Scalar value(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)); cv::copyMakeBorder(src, dst, top, bottom, left, right, borderType, value); cv::imshow(window_name, dst); auto c = (char) cv::waitKey(500); if (c == 27) { break; } else if (c == 'c') { borderType = cv::BORDER_CONSTANT; } else if (c == 'r') { borderType = cv::BORDER_REPLICATE; } } return 0; }
22.14
88
0.570912
snandasena
93a573fa04137ea2d7c1bfd9a3b0c52f5275f052
1,172
cpp
C++
data/dailyCodingProblem546.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
2
2020-09-04T20:56:23.000Z
2021-06-11T07:42:26.000Z
data/dailyCodingProblem546.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
data/dailyCodingProblem546.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* Given an array of integers, return a new array where each element in the new array is the number of smaller elements to the right of that element in the original input array. For example, given the array [3, 4, 9, 6, 1], return [1, 1, 2, 1, 0], since: There is 1 smaller element to the right of 3 There is 1 smaller element to the right of 4 There are 2 smaller elements to the right of 9 There is 1 smaller element to the right of 6 There are no smaller elements to the right of 1 */ vector<int> rightSmaller(vector<int> arr){ set<int> s; vector<int> ans(arr.size()); for(int i=arr.size()-1;i>=0;i--){ auto it = s.insert(arr[i]); ans[i] = distance(s.begin(), it.first); } return ans; } void testFunc(vector<vector<int>> v){ for(auto ans : v){ for(int i : rightSmaller(ans)) cout << i << " "; cout << "\n"; } } // main function int main(){ testFunc({ {12, 1, 2, 3, 0, 11, 4}, {5, 4, 3, 2, 1}, {1, 2, 3, 4, 5}, {12, 10, 5, 4, 2, 20, 6, 1, 0, 2}, {10, 6, 15, 20, 30, 5, 7} }); return 0; }
24.93617
105
0.574232
vidit1999
93a8f707ae5655d1ac5edefbb732624f9294292b
1,294
cpp
C++
Part 9 - Standard Template Library/Range_finding_pair_and_sets.cpp
rudrajit1729/CPP-Learning-Course
3c39b2f31b10b5e8dfd3214f924c6d8af021dc94
[ "MIT" ]
null
null
null
Part 9 - Standard Template Library/Range_finding_pair_and_sets.cpp
rudrajit1729/CPP-Learning-Course
3c39b2f31b10b5e8dfd3214f924c6d8af021dc94
[ "MIT" ]
null
null
null
Part 9 - Standard Template Library/Range_finding_pair_and_sets.cpp
rudrajit1729/CPP-Learning-Course
3c39b2f31b10b5e8dfd3214f924c6d8af021dc94
[ "MIT" ]
null
null
null
#include<iostream> #include<set> #include<algorithm> using namespace std; void problem() { /* add([2,3]) add([10,20]) add([30,400]) add([401,450]) - Now given a number output the interval */ set<pair<int, int>> S; // Insert in any random order but it will still be sorted - BST nature // Pair (a, b) smaller than (c, d) iff (a<c) or (a==c and b<d) // Insertion takes O(logn) S.insert({401, 450}); S.insert({2, 3}); S.insert({30, 400}); S.insert({10, 20}); //2,3 //10,20 //30,400 //401,450 //Given no. n we will create pair p {number, INT_MAX} -> Perform upper bound -> Get one index backwards // If no.present in that interval print yes else no int point = 13; auto it = S.upper_bound({point, INT_MAX}); if(it == S.begin())// Corner case - number lower than lowest index { cout<<"NOT PRESENT\n"; } it--; // One step backwards pair<int, int> current = *it; // Accessing elements of pair - pair.first , pair.second if(current.first <= point && point <= current.second) { cout<<"PRESENT\t"<<current.first<<" "<<current.second<<endl; } else { cout<<"NOT PRESENT\n"; } } int main() { problem(); }
23.107143
108
0.553323
rudrajit1729
93abe497a662d8cb28f3edee41c32ddbb680bced
1,880
cpp
C++
test_board/pal_arbiter_test.cpp
rdolbeau/XiBus
44d7267ff802b54cebda7e0a643a90cff71247e4
[ "MIT" ]
3
2021-12-11T21:53:57.000Z
2022-03-29T16:44:51.000Z
test_board/pal_arbiter_test.cpp
rdolbeau/XiBus
44d7267ff802b54cebda7e0a643a90cff71247e4
[ "MIT" ]
1
2021-12-06T07:49:41.000Z
2021-12-07T17:17:37.000Z
test_board/pal_arbiter_test.cpp
rdolbeau/XiBus
44d7267ff802b54cebda7e0a643a90cff71247e4
[ "MIT" ]
1
2021-12-11T09:31:00.000Z
2021-12-11T09:31:00.000Z
#include "PalArbiter.h" #include "verilated.h" struct TestCase { const char* name; uint8_t ID; uint8_t ARB_I; bool GRANT; }; int main(int argc, char **argv, char **env) { Verilated::commandArgs(argc, argv); PalArbiter* arbitera = new PalArbiter; PalArbiter* arbiterb = new PalArbiter; arbitera->ARBENA = 0; arbitera->ID = 0; arbitera->ARB_I = arbitera->ARB_O; arbitera->eval(); arbitera->ARBENA = 1; arbiterb->ARBENA = 0; arbiterb->ID = 0; arbiterb->ARB_I = arbiterb->ARB_O; arbiterb->eval(); arbiterb->ARBENA = 1; for(uint8_t ida = 0; ida < 16; ida++) { arbitera->ID = ida; for(uint8_t idb = 0; idb < 16; idb++) { if (ida == idb) continue; arbiterb->ID = idb; arbitera->ARB_I = arbitera->ARB_O | arbiterb->ARB_O; arbiterb->ARB_I = arbitera->ARB_O | arbiterb->ARB_O; arbitera->eval(); arbiterb->eval(); // because test require ouput signals on input we have to make two steps // first we produce outputs then second we copy output on input and make // one more step arbitera->ARB_I = arbitera->ARB_O | arbiterb->ARB_O; arbiterb->ARB_I = arbitera->ARB_O | arbiterb->ARB_O; arbitera->eval(); arbiterb->eval(); bool expected_grant = arbitera->ID > arbiterb->ID; if (expected_grant != arbitera->GRANT) { printf(" fail (%01X vs %01X) (expected GRANT=%01X but was %01X) (ARB_I=%01X ARB_Out=%01X)\n", arbitera->ID, arbiterb->ID, expected_grant, arbitera->GRANT, arbitera->ARB_I, arbitera->ARB_O); } else { printf("passed (%01X vs %01X) (ARB_Out=%01X)\n", arbitera->ID, arbiterb->ID, arbitera->ARB_O); } } } arbitera->final(); arbiterb->final(); delete arbitera; delete arbiterb; exit(0); }
26.857143
102
0.592021
rdolbeau
93aee3066fd17787a45d999067f915c156f9a4bd
39,428
cxx
C++
src/GaussianProcessEmulatorDirectoryFormatIO.cxx
scottedwardpratt/MADAI
9f9ee0dac704d77492d9905b4d90a57746201912
[ "BSD-3-Clause" ]
3
2015-04-02T17:37:35.000Z
2017-03-28T20:14:23.000Z
src/GaussianProcessEmulatorDirectoryFormatIO.cxx
scottedwardpratt/MADAI
9f9ee0dac704d77492d9905b4d90a57746201912
[ "BSD-3-Clause" ]
null
null
null
src/GaussianProcessEmulatorDirectoryFormatIO.cxx
scottedwardpratt/MADAI
9f9ee0dac704d77492d9905b4d90a57746201912
[ "BSD-3-Clause" ]
3
2015-08-20T14:07:41.000Z
2017-03-28T20:15:23.000Z
/*========================================================================= * * Copyright 2011-2013 The University of North Carolina at Chapel Hill * All rights reserved. * * Licensed under the MADAI Software License. You may obtain a copy of * this license at * * https://madai-public.cs.unc.edu/visualization/software-license/ * * 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 "GaussianProcessEmulatorDirectoryFormatIO.h" #include "GaussianDistribution.h" #include "GaussianProcessEmulator.h" #include "Paths.h" #include "RuntimeParameterFileReader.h" #include "System.h" #include "UniformDistribution.h" #include "WindowsWarnings.h" #include <madaisys/Directory.hxx> #include <madaisys/SystemTools.hxx> #include <algorithm> // std::find #include <cctype> // std::isspace #include <fstream> #include <iostream> // std::cerr #include <set> #include <boost/algorithm/string.hpp> using madaisys::SystemTools; namespace madai { GaussianProcessEmulatorDirectoryFormatIO ::GaussianProcessEmulatorDirectoryFormatIO() : m_Verbose( false ) { } GaussianProcessEmulatorDirectoryFormatIO ::~GaussianProcessEmulatorDirectoryFormatIO() { } void GaussianProcessEmulatorDirectoryFormatIO ::SetVerbose( bool value ) { m_Verbose = value; } bool GaussianProcessEmulatorDirectoryFormatIO ::GetVerbose() const { return m_Verbose; } namespace { /** * Get a line from an input file stream, breaking up the tokens by * whitespace charactors, and returning a vector of tokens. */ std::vector< std::string > getLineAsTokens( std::ifstream & is, std::string & line ) { std::vector< std::string > tokens; std::getline( is, line ); // First, split on comment character std::vector< std::string > contentAndComments; boost::split( contentAndComments, line, boost::is_any_of("#") ); if ( contentAndComments.size() == 0 ) { return tokens; } // Trim any leading or trailing spaces in the content boost::trim( contentAndComments[0] ); // Next, split only the non-comment content boost::split( tokens, contentAndComments[0], boost::is_any_of("\t "), boost::token_compress_on ); // If first token is empty string, remove it and return if ( tokens[0] == "" ) { tokens.erase( tokens.begin() ); return tokens; } return tokens; } /** * Get rid of whitespace from an input stream. */ inline void discardWhitespace(std::istream & input) { while (std::isspace(input.peek())) { input.get(); } } /** * Read a word from input. If it equals the expected value, return * true. Else print error message to std::cerr and return false. */ inline bool CheckWord(std::istream & input, const std::string & expected) { std::string s; if (! input.good()) { std::cerr << "premature end of input. (" << expected << ")\n"; return false; } input >> s; if (s == expected) return true; std::cerr << "format error. Expected \"" << expected << "', but got '" << s << "'.\n"; return false; } /** * Read an integer from input. If it equals the expected value, return * true. Else print error message to std::cerr and return false. */ inline bool CheckInteger(std::istream & input, int i, const std::string & errorMessage) { if (! input.good()) { std::cerr << "premature end of input. (" << errorMessage << ")\n"; return false; } int j; input >> j; if (i == j) return true; std::cerr << "format error. Expected '" << i << "', but got '" << j << "'. (" << errorMessage << ")\n"; return false; } /** * Parse an integer from an input stream. */ bool parseInteger( int & x, std::istream & input ) { if (! input.good()) return false; input >> x; return true; } /** * Given a vector of strings and a particular string, get the index of * that string in the vector. If not found, returns false and the * index is set to -1. If found, returns true and the index is set * appropriately. */ inline bool getIndex( const std::vector< std::string > & sv, const std::string & s, int & index) { std::vector< std::string >::const_iterator x = std::find(sv.begin(), sv.end(), s); if (x == sv.end()) { index = -1; return false; } else { index = x - sv.begin(); assert( static_cast< size_t >( index ) < sv.size() ); return true; } } /** Read the parameter_priors.dat file in statistical_analysis. */ bool parseExperimentalResults( GaussianProcessEmulator & gpe, const std::string & experimentalResultsFileName, bool verbose ) { const std::vector< std::string > & outputNames = gpe.m_OutputNames; int numberOutputs = gpe.m_NumberOutputs; if ( static_cast< size_t >( numberOutputs ) != outputNames.size()) { std::cerr << "numberOutputs != outputNames.size()"; return false; } if ( verbose ) { std::cout << "Opening experimental results file '" << experimentalResultsFileName << "'\n"; } if ( !System::IsFile( experimentalResultsFileName ) ) { std::cerr << "Expected '" << experimentalResultsFileName << "' to be a file, but it does not exist or is a directory.\n"; return false; } std::ifstream resultsFile( experimentalResultsFileName.c_str() ); if ( !resultsFile.good() ) { std::cerr << "Error opening " << experimentalResultsFileName << '\n'; return false; } // default values. gpe.m_ObservedValues = Eigen::VectorXd::Zero(numberOutputs); gpe.m_ObservedVariances = Eigen::VectorXd::Zero(numberOutputs); while ( resultsFile.good() ) { std::string line; std::vector< std::string > tokens = getLineAsTokens( resultsFile, line ); // Skip empty lines if ( tokens.size() == 0 ) { continue; } std::string formatMessage( "Format should be <name> <value> <uncertainty>" ); if ( tokens.size() < 3 ) { std::cerr << "Too few tokens in line '" << line << "' in file '" << experimentalResultsFileName << "'\n"; std::cerr << formatMessage << "\n"; resultsFile.close(); return false; } if ( tokens.size() > 3 && verbose ) { std::cout << "Extra tokens in line '" << line << "' in file '" << experimentalResultsFileName << "'\n"; std::cout << formatMessage << "\n"; } std::string name( tokens[0] ); double value = atof( tokens[1].c_str() ); double uncertainty = atof( tokens[2].c_str() ); int index = -1; bool success = getIndex( outputNames, name, index ); if ( success ) { if ( verbose ) { std::cout << "Parsed output '" << name << "' with value " << value << "\n"; } gpe.m_ObservedValues(index) = value; gpe.m_ObservedVariances(index) = uncertainty; } else if ( verbose ) { std::cout << "Ignoring value and uncertainty for unknown output name '" << name << "'\n"; } } resultsFile.close(); return true; } } // end anonymous namespace /** Read the parameter_priors.dat file in statistical_analysis. */ bool GaussianProcessEmulatorDirectoryFormatIO ::ParseParameters( std::vector< madai::Parameter > & parameters, int & numberParameters, const std::string & statisticalAnalysisDirectory, bool verbose ) { // First check to see if file exists std::string priorFileName = statisticalAnalysisDirectory + Paths::SEPARATOR + Paths::PARAMETER_PRIORS_FILE; if ( verbose ) { std::cout << "Opened parameter priors file '" << priorFileName << "'.\n"; } if ( !System::IsFile( priorFileName ) ) { std::cerr << "Expected '" << priorFileName << "' to be a file, but it does not exist or is a directory.\n"; return false; } std::ifstream input( priorFileName.c_str() ); if ( !input.good() ) { std::cerr << "Could not read parameter prior file '" << priorFileName << "\n"; return false; } parameters.clear(); // Empty the output vector while ( input.good() ) { std::string line; std::vector< std::string > tokens = getLineAsTokens( input, line ); // Skip empty or comment lines if ( tokens.size() == 0 ) continue; // Check that we have four tokens (distribution type, name, // distribution parameters) std::string formatMessage ( "Format should be <distribution type> <name> " "<distribution parameter 1> <distribution parameter 2>" ); if ( tokens.size() < 4 ) { std::cerr << "Too few tokens in line '" << line << "' in file '" << priorFileName << "'\n"; std::cerr << formatMessage << "\n"; input.close(); return false; } if ( tokens.size() > 4 && verbose ) { std::cout << "Extra tokens in line '" << line << "' in file '" << priorFileName << "'\n"; std::cout << formatMessage << "\n"; } std::string type( tokens[0] ); std::string name( tokens[1] ); boost::algorithm::to_lower( type ); // All supported distributions have two double parameters double distributionValues[2]; distributionValues[0] = atof( tokens[2].c_str() ); distributionValues[1] = atof( tokens[3].c_str() ); if ( type == "uniform" ) { madai::UniformDistribution priorDist; priorDist.SetMinimum( distributionValues[0] ); priorDist.SetMaximum( distributionValues[1] ); parameters.push_back( madai::Parameter( name, priorDist ) ); if ( verbose ) { std::cout << "Parsed '" << type << "'-distributed parameter '" << name << " with minimum " << distributionValues[0] << " and maximum " << distributionValues[1] << std::endl; } } else if ( type == "gaussian" ) { madai::GaussianDistribution priorDist; priorDist.SetMean( distributionValues[0] ); priorDist.SetStandardDeviation( distributionValues[1] ); parameters.push_back( madai::Parameter( name, priorDist ) ); if ( verbose ) { std::cout << "Parsed '" << type << "'-distributed parameter '" << name << " with mean " << distributionValues[0] << " and standard deviation " << distributionValues[1] << std::endl; } } else { std::cerr << "Expected uniform or gaussian, but got " << type << "\n"; input.close(); return false; } } input.close(); numberParameters = static_cast< int >( parameters.size() ); return ( numberParameters > 0 ); } bool GaussianProcessEmulatorDirectoryFormatIO::ParseOutputs( std::vector< std::string > & outputNames, int & numberOutputs, const std::string & statisticalAnalysisDirectory, bool verbose) { // First check to see if file exists std::string observablesFileName = statisticalAnalysisDirectory + Paths::SEPARATOR + Paths::OBSERVABLE_NAMES_FILE; if ( !System::IsFile( observablesFileName ) ) { std::cerr << "Expected '" << observablesFileName << "' to be a file, but it does not exist or is a directory.\n"; return false; } std::ifstream input( observablesFileName.c_str() ); if ( !input.good() ) { std::cerr << "Could not read observables file '" << observablesFileName << "'\n"; return false; } if ( verbose ) { std::cout << "Opened file '" << observablesFileName << "'.\n"; } outputNames.clear(); // Empty the output vector while ( input.good() ) { std::string line; std::vector< std::string > tokens = getLineAsTokens( input, line ); // Skip lines with no tokens if ( tokens.size() == 0 ) continue; // Warn if there is more than one token on a line if ( tokens.size() > 1 && verbose ) { std::cout << "Extra tokens in line '" << line << "' in file " << observablesFileName << "'\n"; std::cout << "Format should be <observable name>\n"; } outputNames.push_back( tokens[0] ); if ( verbose ) { std::cout << "Parsed output '" << tokens[0] << "'.\n"; } } input.close(); numberOutputs = static_cast< int >( outputNames.size() ); return (numberOutputs > 0); } // anonymous namespace namespace { /** Read the CovarianceFunctionType from the command line. */ bool parseCovarianceFunction( GaussianProcessEmulator::CovarianceFunctionType & covarianceType, std::istream & input) { if (! input.good()) return false; std::string s; input >> s; if (s == "POWER_EXPONENTIAL_FUNCTION") covarianceType = GaussianProcessEmulator::POWER_EXPONENTIAL_FUNCTION; else if (s == "SQUARE_EXPONENTIAL_FUNCTION") covarianceType = GaussianProcessEmulator::SQUARE_EXPONENTIAL_FUNCTION; else if (s == "MATERN_32_FUNCTION") covarianceType = GaussianProcessEmulator::MATERN_32_FUNCTION; else if (s == "MATERN_52_FUNCTION") covarianceType = GaussianProcessEmulator::MATERN_52_FUNCTION; else { return false; } return true; } /** * Parses the number of model runs. */ bool parseNumberOfModelRuns( int & x, const std::string & modelOutputDirectory ) { madaisys::Directory directory; if ( !directory.Load( modelOutputDirectory.c_str() ) ) { std::cerr << "Couldn't read directory '" << modelOutputDirectory << "'\n"; return false; } unsigned int runCounter = 0; for ( unsigned long i = 0; i < directory.GetNumberOfFiles(); ++i ) { // \todo Verify that the file staring with "run" is a directory std::string directoryName( directory.GetFile( i ) ); if ( directoryName.substr( 0, 3 ) == "run" ) { runCounter++; } } x = runCounter; assert ( x > 0 ); return true; } /** * Parse the parameter values and output values. */ template < typename TDerived > inline bool parseParameterAndOutputValues( Eigen::MatrixBase< TDerived > & parameterValues_, Eigen::MatrixBase< TDerived > & outputValues_, Eigen::MatrixBase< TDerived > & outputUncertainty_, const std::string & modelOutputDirectory, unsigned int numberTrainingPoints, std::vector< madai::Parameter > parameters, std::vector< std::string > outputNames, bool verbose ) { // Get the list of directories in model_outputs/ madaisys::Directory directory; if ( !directory.Load( modelOutputDirectory.c_str() ) ) { return false; } std::vector< std::string > runDirectories; for ( unsigned long i = 0; i < directory.GetNumberOfFiles(); ++i ) { std::string fileName( directory.GetFile( i ) ); std::string filePath( modelOutputDirectory + fileName ); if ( fileName.find_first_of( "run" ) == 0 ) { runDirectories.push_back( fileName ); } } std::sort( runDirectories.begin(), runDirectories.end() ); size_t numberParameters = parameters.size(); size_t numberOutputs = outputNames.size(); // Copy parameterValues_ Eigen::MatrixBase< TDerived > & parameterValues = const_cast< Eigen::MatrixBase< TDerived > & >( parameterValues_ ); // Copy outputValues_ Eigen::MatrixBase< TDerived > & outputValues = const_cast< Eigen::MatrixBase< TDerived > & >( outputValues_ ); // Copy outputUncertainty_ Eigen::MatrixBase< TDerived > & outputUncertainty = const_cast< Eigen::MatrixBase< TDerived > & >( outputUncertainty_ ); parameterValues.derived().resize( numberTrainingPoints, numberParameters ); outputValues.derived().resize( numberTrainingPoints, numberOutputs ); outputUncertainty.derived().resize( numberOutputs, 1 ); unsigned int runCounter = 0; std::vector< double > averageUncertainty( numberOutputs, 0.0 ); for ( size_t i = 0; i < runDirectories.size(); ++i ) { std::string directoryName( runDirectories[i] ); if ( verbose ) std::cout << "Run directory name: '" << directoryName << "'\n"; if ( directoryName.substr( 0, 3 ) == "run" ) { // Open the parameters file std::string parametersFileName = modelOutputDirectory + Paths::SEPARATOR + directoryName + Paths::SEPARATOR + Paths::PARAMETERS_FILE; if ( !System::IsFile( parametersFileName ) ) { std::cerr << "Expected '" << parametersFileName << "' to be a file, but it does not exist or is a directory.\n"; return false; } std::ifstream parametersFile( parametersFileName.c_str() ); if ( !parametersFile.good() ) { std::cerr << "Could not read parameter file '" << parametersFileName << "'\n"; return false; } if ( verbose ) { std::cout << "Opened file '" << parametersFileName << "'\n"; } // Keep track of which parameters were read std::set< std::string > parametersRemaining; for ( size_t p = 0; p < parameters.size(); ++p ) { parametersRemaining.insert( parameters[p].m_Name ); } while ( parametersFile.good() ) { std::string line; std::vector< std::string > tokens = getLineAsTokens( parametersFile, line ); // Skip lines with no tokens if ( tokens.size() == 0 ) continue; std::string formatString( "Format should be <parameter name> " "<parameter value>" ); if ( tokens.size() < 2 ) { std::cerr << "Too few tokens in line '" << line << "' in file '" << parametersFileName << "'\n"; std::cerr << formatString << "\n"; parametersFile.close(); return false; } if ( tokens.size() > 2 && verbose ) { std::cout << "Extra tokens in line '" << line << "' in file '" << parametersFileName << "' will be ignored.\n"; std::cout << formatString << "\n"; } std::string name( tokens[0] ); double value = atof( tokens[1].c_str() ); // Find the index of the parameter bool foundParameter = false; for ( unsigned int i = 0; i < parameters.size(); i++ ) { if ( name == parameters[i].m_Name ) { parameterValues( runCounter, i) = value; foundParameter = true; parametersRemaining.erase( name ); if ( verbose ) std::cout << "Parsed parameter '" << name << "' with value " << parameterValues( runCounter, i ) << std::endl; break; } } if ( !foundParameter && verbose ) { std::cout << "Unknown parameter name '" << name << "' in line '" << line << "' in file '" << parametersFileName << "' will be ignored.\n"; } } parametersFile.close(); // Check that we have read values for all parameters if ( parametersRemaining.size() > 0 ) { std::cerr << "Values were not read for all parameters in file '" << parametersFileName << "'\n"; std::cerr << "Missing values for:\n"; std::set< std::string >::iterator iter; for ( iter = parametersRemaining.begin(); iter != parametersRemaining.end(); ++iter ) { std::cerr << " " << *iter << "\n"; } return false; } // Open the results file std::string resultsFileName = modelOutputDirectory + Paths::SEPARATOR + directoryName + Paths::SEPARATOR + Paths::RESULTS_FILE; if ( !System::IsFile( resultsFileName ) ) { std::cerr << "Expected '" << resultsFileName << "' to be a file, but it does not exist or is a directory.\n"; return false; } std::ifstream resultsFile ( resultsFileName.c_str() ); if ( !resultsFile.good() ) { std::cerr << "Could not read results file '" << resultsFileName << "'\n"; return false; } if ( verbose ) std::cout << "Opened file " << resultsFileName << "'\n"; // Keep track of which parameters were read std::set< std::string > outputsRemaining; for ( size_t p = 0; p < outputNames.size(); ++p ) { outputsRemaining.insert( outputNames[p] ); } while ( resultsFile.good() ) { std::string line; std::vector< std::string > tokens = getLineAsTokens( resultsFile, line ); // Skip lines with no tokens if ( tokens.size() == 0 ) continue; std::string formatString( "Format should be <output name> " "<output value> [output uncertainty]\n" ); // Check for two few tokens if ( tokens.size() < 2 ) { std::cerr << "Too few tokens in line '" << line << "' in file '" << resultsFileName << "'\n"; std::cerr << formatString << "\n"; resultsFile.close(); return false; } // Too many tokens if ( tokens.size() > 4 && verbose ) { std::cout << "Extra tokens in line '" << line << "' in file '" << resultsFileName << "' will be ignored.\n"; std::cout << formatString << "\n"; } std::string name( tokens[0] ); // Find the output index int outputIndex = -1; if ( getIndex( outputNames, name, outputIndex ) ) { double value = atof( tokens[1].c_str() ); outputValues( runCounter, outputIndex ) = value; double uncertainty = 0.0; if ( tokens.size() == 3 ) { uncertainty = atof( tokens[2].c_str() ); } averageUncertainty[ outputIndex ] += uncertainty; outputsRemaining.erase( name ); } else if ( verbose ) { std::cout << "Unknown output name '" << name << "' in line '" << line << "' in file '" << resultsFileName << "' will be ignored.\n"; } } resultsFile.close(); // Check that we have read values for all parameters if ( outputsRemaining.size() > 0 ) { std::cerr << "Values were not read for all results in file '" << resultsFileName << "'\n"; std::cerr << "Missing values for:\n"; std::set< std::string >::iterator iter; for ( iter = outputsRemaining.begin(); iter != outputsRemaining.end(); ++iter ) { std::cerr << " " << *iter << "\n"; } return false; } runCounter++; } } // Average the uncertainty across model runs for ( unsigned int i = 0; i < numberOutputs; i++ ) { outputUncertainty( i, 0 ) = averageUncertainty[i] / double( runCounter ); } return true; } /** * Parses the model data in the directory structure. */ bool parseModelDataDirectoryStructure( GaussianProcessEmulator & gpme, const std::string & modelOutputDirectory, const std::string & statisticalAnalysisDirectory, bool verbose ) { if ( !GaussianProcessEmulatorDirectoryFormatIO::ParseParameters( gpme.m_Parameters, gpme.m_NumberParameters, statisticalAnalysisDirectory, verbose ) ) { std::cerr << "Couldn't parse parameters\n"; return false; } if ( !GaussianProcessEmulatorDirectoryFormatIO::ParseOutputs( gpme.m_OutputNames, gpme.m_NumberOutputs, statisticalAnalysisDirectory, verbose) ) { std::cerr << "Couldn't parse outputs\n"; return false; } // Initialize means and uncertainty scales gpme.m_TrainingOutputMeans = Eigen::VectorXd::Constant( gpme.m_NumberOutputs, 0.0 ); gpme.m_TrainingOutputVarianceMeans = Eigen::VectorXd::Constant( gpme.m_NumberOutputs, 0.0 ); if ( !parseNumberOfModelRuns( gpme.m_NumberTrainingPoints, modelOutputDirectory ) ) { std::cerr << "Couldn't parse number of model runs.\n"; return false; } Eigen::MatrixXd TMat( gpme.m_NumberOutputs, 1 ); if ( !parseParameterAndOutputValues( gpme.m_TrainingParameterValues, gpme.m_TrainingOutputValues, TMat, modelOutputDirectory, gpme.m_NumberTrainingPoints, gpme.m_Parameters, gpme.m_OutputNames, verbose ) ) { std::cerr << "parse Parameter and Output Values error\n"; return false; } gpme.m_TrainingOutputVarianceMeans = TMat.col(0); return true; } /** Read and save comments to a vector of strings. Will append comments to existing comments. */ bool parseComments( std::vector< std::string > & returnStrings, std::istream & i) { static const char comment_character = '#'; if (! i.good()) return false; int c = i.peek(); while ( i.good() && ( ( c == comment_character ) || ( c == '\n') ) ) { std::string s; std::getline(i, s); returnStrings.push_back(s); c = i.peek(); } if (i.fail()) return false; return true; } /** * Write the comments out to an output stream. */ std::ostream & serializeComments( const std::vector< std::string > & comments, std::ostream & o) { for (unsigned int i = 0; i < comments.size(); ++i) { o << comments[i] << '\n'; } return o; } /** Populates a matrix from a istream. Expects positive integers number_rows and number_columns to be listed first. Reads elements in row-major order. Returns false if reading from the istream fails. Otherwise true. */ template < typename TDerived > inline bool ReadMatrix( const Eigen::MatrixBase< TDerived > & m_, std::istream & ins) { unsigned int nrows, ncols; Eigen::MatrixBase< TDerived > & m = const_cast< Eigen::MatrixBase< TDerived > & >(m_); if (! ins.good()) return false; ins >> nrows >> ncols; m.derived().resize(nrows, ncols); for (size_t i = 0; i < nrows; ++i) for (size_t j = 0; j < ncols; ++j) { if (! ins.good()) return false; ins >> m(i,j); } return true; } /** Print a Matrix to output stream, preceded by its dimensions. Use row-major order. */ template < typename TDerived > static inline std::ostream & PrintMatrix( const Eigen::MatrixBase< TDerived > & m, std::ostream & o) { o << m.rows() << ' ' << m.cols() << '\n'; if (m.cols() > 0) { for (int i = 0; i < m.rows(); ++i) { for (int j = 0; j < (m.cols() - 1); ++j) o << m(i, j) << '\t'; o << m(i, m.cols() - 1) << '\n'; } } return o; } /** Populates a Vector from a istream. Expects positive integers number_elements to be listed first. Reads elements in order. Returns false if reading from the istream fails. Otherwise true. */ template < typename TDerived > inline bool ReadVector( const Eigen::MatrixBase< TDerived > & v_, std::istream & ins) { unsigned int nrows; Eigen::MatrixBase< TDerived > & v = const_cast< Eigen::MatrixBase< TDerived > & >(v_); if (! ins.good()) return false; ins >> nrows; v.derived().resize(nrows, 1); for (size_t i = 0; i < nrows; ++i) { if (! ins.good()) return false; ins >> v(i,0); } return true; } /** Print a Vector to output stream, preceded by its size. */ template < typename TDerived > static inline std::ostream & PrintVector( const Eigen::MatrixBase< TDerived > & v, std::ostream & o) { o << v.size() << '\n'; for (int i = 0; i < v.size(); ++i) { o << v(i) << '\n'; } return o; } /** * A covariance function can be represented as a string. */ const char * GetCovarianceFunctionString( GaussianProcessEmulator::CovarianceFunctionType cov) { switch (cov) { case GaussianProcessEmulator::POWER_EXPONENTIAL_FUNCTION: return "POWER_EXPONENTIAL_FUNCTION"; case GaussianProcessEmulator::SQUARE_EXPONENTIAL_FUNCTION: return "SQUARE_EXPONENTIAL_FUNCTION"; case GaussianProcessEmulator::MATERN_32_FUNCTION: return "MATERN_32_FUNCTION"; case GaussianProcessEmulator::MATERN_52_FUNCTION: return "MATERN_52_FUNCTION"; default: assert(false); return "UNKNOWN"; } } /** * Parse the submodels of the emulator. */ bool parseSubmodels( GaussianProcessEmulator::SingleModel & m, int modelIndex, std::istream & input) { std::string word; if (! CheckWord(input, "MODEL")) return false; if (! CheckInteger(input, modelIndex, "modelIndex")) return false; while (input.good()) { if (! input.good()) return false; input >> word; if (word == "COVARIANCE_FUNCTION") { if (!parseCovarianceFunction(m.m_CovarianceFunction, input)) { std::cerr << "Could not parse COVARIANCE_FUNCTION when reading " << "submodel " << modelIndex << "\n"; return false; } } else if (word == "REGRESSION_ORDER") { if (! parseInteger(m.m_RegressionOrder, input)) { std::cerr << "Could not parse REGRESSION_ORDER when reading " << "submodel " << modelIndex << "\n"; return false; } } else if (word == "THETAS") { if (! ReadVector(m.m_Thetas, input)) { std::cerr << "Could not parse THETAS when reading " << "submodel " << modelIndex << "\n"; return false; } } else if (word == "END_OF_MODEL") { return true; } else { std::cerr << "Unexpected keyword: '" << word << "' when reading " << "submodel.\n"; return false; } } return false; } /** * Parse the PCA decomposition data. */ bool parsePCADecomposition( GaussianProcessEmulator & gpme, std::istream & input ) { parseComments(gpme.m_Comments,input); bool outputMeansRead = false; bool outputUncertaintyScalesRead = false; bool outputPCAEigenvaluesRead = false; bool outputPCAEigenvectorsRead = false; std::string word; while (input.good()) { if (! input.good()) return false; input >> word; if (word == "OUTPUT_MEANS") { if (! ReadVector(gpme.m_TrainingOutputMeans, input)) { std::cerr << "Could not read OUTPUT_MEANS entry in PCA decomposition " << "file.\n"; return false; } outputMeansRead = true; } else if (word == "OUTPUT_UNCERTAINTY_SCALES") { if (! ReadVector(gpme.m_UncertaintyScales, input)) { std::cerr << "Could not read OUTPUT_UNCERTAINTY_SCALES in PCA " << "decomposition file.\n"; return false; } outputUncertaintyScalesRead = true; } else if (word == "OUTPUT_PCA_EIGENVALUES") { if (! ReadVector(gpme.m_PCAEigenvalues, input)) { std::cerr << "Could not read OUTPUT_PCA_EIGENVALUES in PCA " << "decomposition file.\n"; return false; } outputPCAEigenvaluesRead = true; } else if (word == "OUTPUT_PCA_EIGENVECTORS") { if (! ReadMatrix(gpme.m_PCAEigenvectors, input)) { std::cerr << "Could not read OUTPUT_PCA_EIGENVECTORS in PCA " << "decomposition file.\n"; return false; } outputPCAEigenvectorsRead = true; } else if (word == "END_OF_FILE") { break; } else { std::cerr << "Unexpected keyword: '" << word << "' in PCA " << "decomposition file.\n"; return false; } } if ( !( outputMeansRead && outputUncertaintyScalesRead && outputPCAEigenvaluesRead && outputPCAEigenvectorsRead ) ) { std::cerr << "Not all required PCA components read.\n"; std::cerr << "Missing:\n"; if ( !outputMeansRead ) std::cerr << "OUTPUT_MEANS\n"; if ( !outputUncertaintyScalesRead ) std::cerr << "OUTPUT_UNCERTAINTY_SCALES\n"; if ( !outputPCAEigenvaluesRead ) std::cerr << "OUTPUT_PCA_EIGENVALUES\n"; if ( !outputPCAEigenvectorsRead ) std::cerr << "OUTPUT_PCA_EIGENVECTORS\n"; return false; } return true; } /** * Write the PCA decomposition to an output stream. */ std::ostream & serializePCADecomposition( const GaussianProcessEmulator & gpme, std::ostream & o ) { serializeComments(gpme.m_Comments,o); o << "OUTPUT_MEANS\n"; PrintVector(gpme.m_TrainingOutputMeans, o); o << "OUTPUT_UNCERTAINTY_SCALES\n"; PrintVector(gpme.m_UncertaintyScales, o); o << "OUTPUT_PCA_EIGENVALUES\n"; PrintVector(gpme.m_PCAEigenvalues, o); o << "OUTPUT_PCA_EIGENVECTORS\n"; PrintMatrix(gpme.m_PCAEigenvectors, o); o << "END_OF_FILE\n"; return o; } /** * Write an emulator submodel to an output stream. */ std::ostream & serializeSubmodels( const GaussianProcessEmulator::SingleModel & m, int modelIndex, std::ostream & o) { o << "MODEL " << modelIndex << '\n'; o << "COVARIANCE_FUNCTION\t" << GetCovarianceFunctionString(m.m_CovarianceFunction) << '\n'; o << "REGRESSION_ORDER\t" << m.m_RegressionOrder << '\n'; o << "THETAS\n"; PrintVector(m.m_Thetas, o); o << "END_OF_MODEL\n"; return o; } /** * Write the emulator to an output stream. */ std::ostream & serializeGaussianProcessEmulator( const GaussianProcessEmulator & gpme, std::ostream & o) { o << "SUBMODELS\t" << gpme.m_NumberPCAOutputs << "\n"; for (int i = 0; i < gpme.m_NumberPCAOutputs; ++i) { serializeSubmodels(gpme.m_PCADecomposedModels[i],i,o); } o << "END_OF_FILE\n"; return o; } /** * Write the emulator to an output stream. */ bool parseGaussianProcessEmulator( GaussianProcessEmulator & gpme, const std::string & statisticalAnalysisDirectory) { std::string emulatorFile = statisticalAnalysisDirectory + Paths::SEPARATOR + Paths::EMULATOR_STATE_FILE; if ( !System::IsFile( emulatorFile ) ) { std::cerr << "Expected '" << emulatorFile << "' to be a file, but it does not exist or is a directory.\n"; return false; } std::ifstream input( emulatorFile.c_str() ); parseComments(gpme.m_Comments,input); std::string word; while (input.good()) { if (! input.good()) return false; input >> word; if (word == "SUBMODELS") { if (! parseInteger(gpme.m_NumberPCAOutputs, input)) { std::cerr << "Could not parse number of SUBMODELS when reading " << "emulator state.\n"; input.close(); return false; } gpme.m_PCADecomposedModels.resize(gpme.m_NumberPCAOutputs); for (int i = 0; i < gpme.m_NumberPCAOutputs; ++i) { if (! parseSubmodels(gpme.m_PCADecomposedModels[i],i,input)) { std::cerr << "Could not parse submodels when reading emulator " << "state.\n"; input.close(); return false; } gpme.m_PCADecomposedModels[i].m_Parent = &gpme; } } else if (word == "END_OF_FILE") { return true; } else { std::cerr << "Unexpected keyword: " << word << "\n"; input.close(); return false; } } input.close(); return true; } } // end anonymous namespace /** This takes an empty GPEM and loads training data. \returns true on success. */ bool GaussianProcessEmulatorDirectoryFormatIO ::LoadTrainingData(GaussianProcessEmulator * gpe, std::string modelOutputDirectory, std::string statisticalAnalysisDirectory, std::string experimentalResultsFileName) { if ( !parseModelDataDirectoryStructure(*gpe, modelOutputDirectory, statisticalAnalysisDirectory, m_Verbose ) ) return false; if (! parseExperimentalResults( *gpe, experimentalResultsFileName, this->m_Verbose )) { std::cerr << "Error in parseExperimentalResults()\n"; return false; } return (gpe->CheckStatus() == GaussianProcessEmulator::UNTRAINED); } /** This takes a GPEM and loads PCA data. \returns true on success. */ bool GaussianProcessEmulatorDirectoryFormatIO ::LoadPCA(GaussianProcessEmulator * gpe, const std::string & statisticsDirectory) { std::string PCAFile = statisticsDirectory + Paths::SEPARATOR + Paths::PCA_DECOMPOSITION_FILE; if ( !System::IsFile( PCAFile ) ) { std::cerr << "Expected '" << PCAFile << "' to be a file, but it does not exist or is a directory.\n"; return false; } std::ifstream input( PCAFile.c_str() ); if ( !parsePCADecomposition(*gpe, input) ) { std::cerr << "Error parsing PCA data.\n"; input.close(); return false; } // Initialize the retained principal components std::string runtimeParameterFile = statisticsDirectory + Paths::SEPARATOR + Paths::RUNTIME_PARAMETER_FILE; RuntimeParameterFileReader runtimeParameterReader; if ( !runtimeParameterReader.ParseFile( runtimeParameterFile ) ) { std::cerr << "Error parsing runtime parameters.\n" << std::endl; } double DEFAULT_PCA_FRACTION_RESOLVING_POWER = 0.95; // \todo should use madai::Defaults::PCA_FRACTION_RESOLVING_POWER double fractionalResolvingPower = runtimeParameterReader.GetOptionAsDouble( "PCA_FRACTION_RESOLVING_POWER", DEFAULT_PCA_FRACTION_RESOLVING_POWER); gpe->RetainPrincipalComponents( fractionalResolvingPower ); // We are finished reading the input files. return (gpe->CheckStatus() == GaussianProcessEmulator::UNTRAINED); } bool GaussianProcessEmulatorDirectoryFormatIO ::Write(GaussianProcessEmulator * gpe, std::ostream & output) const { output.precision(17); serializeGaussianProcessEmulator(*gpe, output); return true; } bool GaussianProcessEmulatorDirectoryFormatIO ::WritePCA(GaussianProcessEmulator * gpe, std::ostream & output) const { output.precision(17); serializePCADecomposition(*gpe,output); return true; } bool GaussianProcessEmulatorDirectoryFormatIO ::PrintThetas(GaussianProcessEmulator * gpe, std::ostream & output) const { output.precision(17); serializeComments(gpe->m_Comments,output); output << "THETAS_FILE\n"; output << "SUBMODELS\t" << gpe->m_NumberPCAOutputs << "\n\n"; for (int i = 0; i < gpe->m_NumberPCAOutputs; ++i) { const GaussianProcessEmulator::SingleModel & m = gpe->m_PCADecomposedModels[i]; output << "MODEL " << i << '\n'; output << "COVARIANCE_FUNCTION\t" << GetCovarianceFunctionString(m.m_CovarianceFunction) << '\n'; output << "REGRESSION_ORDER\t" << m.m_RegressionOrder << '\n'; output << "THETAS\n"; PrintVector(m.m_Thetas, output); output << "END_OF_MODEL\n\n"; } output << "END_OF_FILE\n"; return true; } /** This takes a GPEM and loads the emulator specific data (submodels with their thetas). \returns true on success. */ bool GaussianProcessEmulatorDirectoryFormatIO ::LoadEmulator(GaussianProcessEmulator * gpe, const std::string & statisticalAnalysisDirectory) { if ( !parseGaussianProcessEmulator(*gpe, statisticalAnalysisDirectory) ) { std::cerr << "Error parsing gaussian process emulator.\n"; return false; } // We are finished reading the input files. if ( gpe->CheckStatus() != GaussianProcessEmulator::UNCACHED ) { std::cerr << "Emulator already cached.\n"; std::cerr << gpe->GetStatusAsString() << "\n"; return false; } if ( !gpe->MakeCache() ) { std::cerr << "Error while making cache.\n"; return false; } return true; } } // end namespace madai
29.892343
98
0.610531
scottedwardpratt
93b0a056194e9fa637132278509c8638e439e692
8,243
cpp
C++
nersis/libstatemodule/luastate.cpp
MoltenPlastic/nersis-love
4fafd429643c8b546992f5b4a0dca5d4ae5d5427
[ "MIT" ]
null
null
null
nersis/libstatemodule/luastate.cpp
MoltenPlastic/nersis-love
4fafd429643c8b546992f5b4a0dca5d4ae5d5427
[ "MIT" ]
null
null
null
nersis/libstatemodule/luastate.cpp
MoltenPlastic/nersis-love
4fafd429643c8b546992f5b4a0dca5d4ae5d5427
[ "MIT" ]
null
null
null
//implementation of a lua state (this file is included in the middle of module.cpp) class LuaState : public State { lua_State *L; int id; public: LuaState(lua_State *L, int index); virtual ~LuaState(); virtual void enter() { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "enter"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { if (lua_pcall(L, 0, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, -1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual void leave() { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "leave"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { if (lua_pcall(L, 0, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, -1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } delete this; }; virtual void suspend() { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "suspend"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { if (lua_pcall(L, 0, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, -1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual void resume() { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "resume"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { if (lua_pcall(L, 0, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, -1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual void update(double dt) { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "update"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { lua_pushnumber(L, dt); if (lua_pcall(L, 1, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, -1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual void draw() { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "draw"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { if (lua_pcall(L, 0, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, -1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual void focus(bool windowFocus) { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "focus"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { lua_pushboolean(L, windowFocus); if (lua_pcall(L, 1, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, -1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual void keyPressed(love::keyboard::Keyboard::Key key, bool isRepeat) { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "keypressed"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { const char *keystring; love::keyboard::Keyboard::getConstant(key, keystring); lua_pushstring(L, keystring); lua_pushboolean(L, isRepeat); if (lua_pcall(L, 2, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, -1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual void keyReleased(love::keyboard::Keyboard::Key key) { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "keyreleased"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { const char *keystring; love::keyboard::Keyboard::getConstant(key, keystring); lua_pushstring(L, keystring); if (lua_pcall(L, 1, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, -1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual void mouseFocus(bool mouseFocus) { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "mousefocus"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { lua_pushboolean(L, mouseFocus); if (lua_pcall(L, 1, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, -1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual void mouseMoved(int x, int y, int dx, int dy) { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "mousemoved"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { lua_pushinteger(L, x); lua_pushinteger(L, y); lua_pushinteger(L, dx); lua_pushinteger(L, dy); if (lua_pcall(L, 4, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, -1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual void mousePressed(int x, int y, int button) { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "mousepressed"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { lua_pushinteger(L, x); lua_pushinteger(L, y); lua_pushinteger(L, button); if (lua_pcall(L, 3, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, -1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual void mouseReleased(int x, int y, int button) { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "mousereleased"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { lua_pushinteger(L, x); lua_pushinteger(L, y); lua_pushinteger(L, button); if (lua_pcall(L, 3, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, -1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual bool quit() { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "quit"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { if (lua_pcall(L, 0, 1, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, -1)); lua_pop(L, 1); } bool q = lua_toboolean(L, -1); lua_pop(L, 1); return q; } else { lua_pop(L, 1); } return false; }; virtual void resize(int w, int h) { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "resize"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { lua_pushinteger(L, w); lua_pushinteger(L, h); if (lua_pcall(L, 2, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, 1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual void textInput(std::string text) { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "textinput"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { lua_pushstring(L, text.c_str()); if (lua_pcall(L, 1, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, 1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual void threadError(love::thread::LuaThread *thread, std::string error) { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "threaderror"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { luax_pushtype(L, "Thread", THREAD_THREAD_ID, thread); lua_pushstring(L, error.c_str()); if (lua_pcall(L, 2, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, 1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual void visible(bool visibility) { lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */ lua_getfield(L, -1, "visible"); /* func table */ lua_remove(L, -2); /* func */ if (lua_isfunction(L, -1)) { lua_pushboolean(L, visibility); if (lua_pcall(L, 1, 0, 0) != 0) { /* error */ printf("Error in LuaState: %s\n",lua_tostring(L, 1)); lua_pop(L, 1); } } else { lua_pop(L, 1); } }; virtual void sdlEvent(SDL_Event e) {}; //TODO: SDL_Event wrapper maybe? }; LuaState::LuaState(lua_State *L, int index) { this->L = L; id = luaL_ref(L, LUA_REGISTRYINDEX); } LuaState::~LuaState() { luaL_unref(L, LUA_REGISTRYINDEX, id); }
28.32646
83
0.581584
MoltenPlastic
93b0ef45f8ade0888846179c87f40a57b484642c
2,577
cpp
C++
AABall/AABallConsole.cpp
tickelton/AABall
38534a2bfd46729a854caebcb06dfb116d359795
[ "0BSD" ]
null
null
null
AABall/AABallConsole.cpp
tickelton/AABall
38534a2bfd46729a854caebcb06dfb116d359795
[ "0BSD" ]
null
null
null
AABall/AABallConsole.cpp
tickelton/AABall
38534a2bfd46729a854caebcb06dfb116d359795
[ "0BSD" ]
null
null
null
#include "AABallConsole.h" AABallConsole::AABallConsole() { // Get a handle to the STDOUT screen buffer to copy from and // create a new screen buffer to copy to. hStdout = GetStdHandle(STD_OUTPUT_HANDLE); hScreenBuffers[0] = CreateConsoleScreenBuffer( GENERIC_READ | // read/write access GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, // shared NULL, // default security attributes CONSOLE_TEXTMODE_BUFFER, // must be TEXTMODE NULL); // reserved; must be NULL if (hStdout == INVALID_HANDLE_VALUE || hScreenBuffers[0] == INVALID_HANDLE_VALUE) { printf("CreateConsoleScreenBuffer failed - (%d)\n", GetLastError()); } else { // Make the new screen buffer the active screen buffer. if (!SetConsoleActiveScreenBuffer(hScreenBuffers[0])) { printf("SetConsoleActiveScreenBuffer failed - (%d)\n", GetLastError()); } } } void AABallConsole::drawFullImage(const LPCWSTR imageData[]) { bufCoord.X = 0; for (int i = 0; i < 30; ++i) { if (!imageData[i]) { continue; } bufCoord.Y = i; BOOL fSuccess = WriteConsoleOutputCharacter( hScreenBuffers[0], imageData[i], static_cast<DWORD>(wcslen(imageData[i])), bufCoord, &nCharsWritten ); if (!fSuccess) { printf("WriteConsoleOutput failed - (%d)\n", GetLastError()); } } } void AABallConsole::restoreStdout() { // Restore the original active screen buffer. if (!SetConsoleActiveScreenBuffer(hStdout)) { printf("SetConsoleActiveScreenBuffer failed - (%d)\n", GetLastError()); } } void AABallConsole::drawAt(const uint16_t x, const uint16_t y, const LPCWSTR imageData) { if (!imageData) { return; } bufCoord.X = x; bufCoord.Y = y; BOOL fSuccess = WriteConsoleOutputCharacter( hScreenBuffers[0], imageData, static_cast<DWORD>(wcslen(imageData)), bufCoord, &nCharsWritten ); if (!fSuccess) { printf("WriteConsoleOutput failed - (%d)\n", GetLastError()); } } void AABallConsole::drawBlockAt(const uint16_t x, const uint16_t y, const uint16_t nRows, const LPCWSTR imageData[]) { bufCoord.X = x; for (int i = 0; i < nRows; ++i) { if (!imageData[i]) { continue; } bufCoord.Y = y + i; BOOL fSuccess = WriteConsoleOutputCharacter( hScreenBuffers[0], imageData[i], static_cast<DWORD>(wcslen(imageData[i])), bufCoord, &nCharsWritten ); if (!fSuccess) { printf("WriteConsoleOutput failed - (%d)\n", GetLastError()); } } }
23.427273
117
0.642608
tickelton
93b415e4319d7228244f28553e9cb82f858419c6
72
cc
C++
gcj/apac2016/a/a.cc
stauntonknight/algorithm
39dbe6dc952ab7db3a469e1ca785003a4660fedb
[ "CNRI-Python" ]
null
null
null
gcj/apac2016/a/a.cc
stauntonknight/algorithm
39dbe6dc952ab7db3a469e1ca785003a4660fedb
[ "CNRI-Python" ]
null
null
null
gcj/apac2016/a/a.cc
stauntonknight/algorithm
39dbe6dc952ab7db3a469e1ca785003a4660fedb
[ "CNRI-Python" ]
null
null
null
#include <iostream> int getNum(int power, int n) { } int main() { }
7.2
30
0.597222
stauntonknight
93b906b8c4b078e5be06ce9ccf911b68e15f4c08
1,070
cpp
C++
lib/AST/ASTNode.cpp
mattapet/dusk-lang
928b027429a3fd38cece78a89a9619406dcdd9f0
[ "MIT" ]
1
2022-03-30T22:01:44.000Z
2022-03-30T22:01:44.000Z
lib/AST/ASTNode.cpp
mattapet/dusk-lang
928b027429a3fd38cece78a89a9619406dcdd9f0
[ "MIT" ]
null
null
null
lib/AST/ASTNode.cpp
mattapet/dusk-lang
928b027429a3fd38cece78a89a9619406dcdd9f0
[ "MIT" ]
null
null
null
//===--- ASTNode.cpp ------------------------------------------------------===// // // dusk-lang // This source file is part of a dusk-lang project, which is a semestral // assignement for BI-PJP course at Czech Technical University in Prague. // The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND. // //===----------------------------------------------------------------------===// #include "dusk/AST/ASTNode.h" #include "dusk/AST/ASTContext.h" #include "dusk/AST/ASTWalker.h" #include "dusk/AST/Decl.h" #include "dusk/AST/Expr.h" #include "dusk/AST/Stmt.h" using namespace dusk; void *ASTNode::operator new(size_t Bytes, ASTContext &Context) { return Context.Allocate(Bytes); } bool ASTNode::walk(ASTWalker &Walker) { if (auto D = dynamic_cast<Decl *>(this)) return D->walk(Walker); else if (auto E = dynamic_cast<Expr *>(this)) return E->walk(Walker) != nullptr; else if (auto S = dynamic_cast<Stmt *>(this)) return S->walk(Walker); else llvm_unreachable("Unexpected AST node found."); }
28.157895
80
0.581308
mattapet
93bb63d5c1711804e97eaf8c6a4d6d26818f3987
4,395
cpp
C++
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/jni/Polyfills.Window.g.cpp
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/jni/Polyfills.Window.g.cpp
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/jni/Polyfills.Window.g.cpp
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
// This file was generated based on '(multiple files)'. // WARNING: Changes might be lost if you edit this file directly. #include <Fuse.Scripting.Module.h> #include <Polyfills.Window.WindowModule.h> #include <Uno.Bool.h> #include <Uno.IO.Bundle.h> #include <Uno.IO.BundleFile.h> #include <Uno.Object.h> #include <Uno.String.h> #include <Uno.UX.FileSource.h> #include <Uno.UX.Resource.h> static uString* STRINGS[3]; namespace g{ namespace Polyfills{ namespace Window{ // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Polyfills.Window\1.9.0\WindowModule.uno // ------------------------------------------------------------------------------------------ // public sealed class WindowModule :10 // { static void WindowModule_build(uType* type) { ::STRINGS[0] = uString::Const("Polyfills/Window"); ::STRINGS[1] = uString::Const("Polyfills.Window"); ::STRINGS[2] = uString::Const("js/Window.js"); type->SetDependencies( ::g::Uno::IO::Bundle_typeof(), ::g::Uno::UX::Resource_typeof()); type->SetInterfaces( ::g::Uno::IDisposable_typeof(), offsetof(WindowModule_type, interface0), ::g::Fuse::Scripting::IModuleProvider_typeof(), offsetof(WindowModule_type, interface1)); type->SetFields(9, type, (uintptr_t)&WindowModule::_instance_, uFieldFlagsStatic, ::g::Uno::UX::FileSource_typeof(), (uintptr_t)&WindowModule::_fileSourceInstance_, uFieldFlagsStatic); type->Reflection.SetFunctions(2, new uFunction("GetModule", NULL, (void*)WindowModule__GetModule_fn, 0, false, ::g::Fuse::Scripting::Module_typeof(), 0), new uFunction(".ctor", NULL, (void*)WindowModule__New3_fn, 0, true, type, 0)); } WindowModule_type* WindowModule_typeof() { static uSStrong<WindowModule_type*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Fuse::Scripting::FileModule_typeof(); options.FieldCount = 11; options.InterfaceCount = 2; options.DependencyCount = 2; options.ObjectSize = sizeof(WindowModule); options.TypeSize = sizeof(WindowModule_type); type = (WindowModule_type*)uClassType::New("Polyfills.Window.WindowModule", options); type->fp_build_ = WindowModule_build; type->fp_ctor_ = (void*)WindowModule__New3_fn; type->interface1.fp_GetModule = (void(*)(uObject*, ::g::Fuse::Scripting::Module**))WindowModule__GetModule_fn; type->interface0.fp_Dispose = (void(*)(uObject*))::g::Fuse::Scripting::Module__Dispose_fn; return type; } // public WindowModule() :28 void WindowModule__ctor_3_fn(WindowModule* __this) { __this->ctor_3(); } // public Fuse.Scripting.Module GetModule() :12 void WindowModule__GetModule_fn(WindowModule* __this, ::g::Fuse::Scripting::Module** __retval) { *__retval = __this->GetModule(); } // private static Uno.UX.FileSource GetWindow() :20 void WindowModule__GetWindow_fn(::g::Uno::UX::FileSource** __retval) { *__retval = WindowModule::GetWindow(); } // public WindowModule New() :28 void WindowModule__New3_fn(WindowModule** __retval) { *__retval = WindowModule::New3(); } uSStrong<WindowModule*> WindowModule::_instance_; uSStrong< ::g::Uno::UX::FileSource*> WindowModule::_fileSourceInstance_; // public WindowModule() [instance] :28 void WindowModule::ctor_3() { uStackFrame __("Polyfills.Window.WindowModule", ".ctor()"); ctor_2(WindowModule::GetWindow()); if (WindowModule::_instance_ == NULL) ::g::Uno::UX::Resource::SetGlobalKey(WindowModule::_instance_ = this, ::STRINGS[0/*"Polyfills/W...*/]); } // public Fuse.Scripting.Module GetModule() [instance] :12 ::g::Fuse::Scripting::Module* WindowModule::GetModule() { return this; } // private static Uno.UX.FileSource GetWindow() [static] :20 ::g::Uno::UX::FileSource* WindowModule::GetWindow() { uStackFrame __("Polyfills.Window.WindowModule", "GetWindow()"); if (WindowModule::_fileSourceInstance_ == NULL) WindowModule::_fileSourceInstance_ = ::g::Uno::UX::FileSource::op_Implicit1(uPtr(::g::Uno::IO::Bundle::Get(::STRINGS[1/*"Polyfills.W...*/]))->GetFile(::STRINGS[2/*"js/Window.js"*/])); return WindowModule::_fileSourceInstance_; } // public WindowModule New() [static] :28 WindowModule* WindowModule::New3() { WindowModule* obj1 = (WindowModule*)uNew(WindowModule_typeof()); obj1->ctor_3(); return obj1; } // } }}} // ::g::Polyfills::Window
34.606299
191
0.687827
marferfer
93bc192e6e56eca126b4254ea8d1436324d903c5
2,019
cpp
C++
2021/day10.cpp
mly32/advent-of-code
8c07ac69b3933403357688efc02f6d4adf1d0592
[ "BSD-3-Clause" ]
null
null
null
2021/day10.cpp
mly32/advent-of-code
8c07ac69b3933403357688efc02f6d4adf1d0592
[ "BSD-3-Clause" ]
null
null
null
2021/day10.cpp
mly32/advent-of-code
8c07ac69b3933403357688efc02f6d4adf1d0592
[ "BSD-3-Clause" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ull = unsigned long long; struct solution { vector<string> lines; solution(const string& filename) { string line; ifstream input_file(filename); if (!input_file.is_open()) { cerr << "Could not open the file - '" << filename << "'" << endl; return; } while (getline(input_file, line)) { lines.push_back(line); } input_file.close(); } inline bool is_closing(const char c) { return c == ')' || c == ']' || c == '}' || c == '>'; } inline bool is_matching(const char b, const char c) { return (b == '(' && c == ')') || (b == '[' && c == ']') || (b == '{' && c == '}') || (b == '<' && c == '>'); } ull solve() { const map<char, int> points = {{'(', 1}, {'[', 2}, {'{', 3}, {'<', 4}, {')', 3}, {']', 57}, {'}', 1197}, {'>', 25137}}; ull res = 0; vector<ull> scores; for (const string& line : lines) { ull score_corrupt = 0, score_incomplete = 0; stack<char> stk; for (char c : line) { if (!is_closing(c)) { stk.push(c); continue; } if (stk.empty()) { score_corrupt += points.at(c); break; } else if (is_matching(stk.top(), c)) { stk.pop(); } else { score_corrupt += points.at(c); break; } } if (score_corrupt == 0) { while (!stk.empty()) { score_incomplete = 5 * score_incomplete + points.at(stk.top()); stk.pop(); } scores.push_back(score_incomplete); } res += score_corrupt; } sort(scores.begin(), scores.end()); printf("res: %llu, %llu\n", res, scores[scores.size() / 2]); return res; } }; int main() { const bool final = 1; const string filename = "./input/" + string(final ? "final" : "practice") + "/day10.txt"; solution(filename).solve(); }
24.621951
73
0.464091
mly32
93bd5138539c84a381d7e7b0d4b7629b9912ac63
447
hpp
C++
Engine/Networking/Packets.hpp
artur-kink/nhns
bc1ccef4e4a9cba9047051d73202ee2b1482066f
[ "Apache-2.0" ]
null
null
null
Engine/Networking/Packets.hpp
artur-kink/nhns
bc1ccef4e4a9cba9047051d73202ee2b1482066f
[ "Apache-2.0" ]
null
null
null
Engine/Networking/Packets.hpp
artur-kink/nhns
bc1ccef4e4a9cba9047051d73202ee2b1482066f
[ "Apache-2.0" ]
null
null
null
#ifndef _PACKETS_ #define _PACKETS_ #include <cstring> #include "Types.hpp" #include <stdlib.h> namespace Packet{ //Keep packet structure in alphabetic order //All packets must be packed. #pragma pack(push, 1) /** * Entity location information from the server. */ struct ServerEntityLocation { uint16_t id; byte direction; float x; float y; }; #pragma pack(pop) }; #endif
16.555556
51
0.621924
artur-kink
93bf27d1fbd5252030c3a7e7683ce4e9b0538823
3,047
cc
C++
src/player.cc
lxndr/node-gst
9f2d49ffbdac7cc938b411f57b4cbfc302edb84b
[ "MIT" ]
null
null
null
src/player.cc
lxndr/node-gst
9f2d49ffbdac7cc938b411f57b4cbfc302edb84b
[ "MIT" ]
null
null
null
src/player.cc
lxndr/node-gst
9f2d49ffbdac7cc938b411f57b4cbfc302edb84b
[ "MIT" ]
null
null
null
/* * Copyright 2018 Humanity */ #include <vector> #include <string> #include "player.h" static Nan::Persistent<v8::Function> constructor; v8::Local<v8::Function> Player::Init() { auto tpl = Nan::New<v8::FunctionTemplate>(New); tpl->SetClassName(Nan::New("GstPlayer").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "play", Play); Nan::SetPrototypeMethod(tpl, "pause", Pause); Nan::SetPrototypeMethod(tpl, "stop", Stop); Nan::SetPrototypeMethod(tpl, "seek", Seek); Nan::SetPrototypeMethod(tpl, "close", Close); auto inst = tpl->InstanceTemplate(); Nan::SetAccessor(inst, Nan::New("uri").ToLocalChecked(), UriGetter, UriSetter); Nan::SetAccessor(inst, Nan::New("duration").ToLocalChecked(), DurationGetter); Nan::SetAccessor(inst, Nan::New("position").ToLocalChecked(), PositionGetter); constructor.Reset(tpl->GetFunction()); return tpl->GetFunction(); } NAN_METHOD(Player::New) { if (info.IsConstructCall()) { auto self = new Player(); self->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { Nan::ThrowTypeError("Called as plain function is not permitted"); } } Player::Player() { m_gst_player = gst_player_new(NULL, NULL); } Player::~Player() { OnClose(); } void Player::OnClose() { gst_object_unref(m_gst_player); } NAN_METHOD(Player::Play) { auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder()); gst_player_play(self->m_gst_player); } NAN_METHOD(Player::Pause) { auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder()); gst_player_pause(self->m_gst_player); } NAN_METHOD(Player::Stop) { auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder()); gst_player_stop(self->m_gst_player); } NAN_METHOD(Player::Seek) { auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder()); if (info.Length() < 1) { Nan::ThrowTypeError("Argument #1 must be a number"); } auto pos = info[0]->NumberValue(); gst_player_seek(self->m_gst_player, static_cast<GstClockTime>(pos)); } NAN_METHOD(Player::Close) { auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder()); self->OnClose(); } NAN_GETTER(Player::UriGetter) { auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder()); auto uri = gst_player_get_uri(self->m_gst_player); info.GetReturnValue().Set(Nan::New((const char*) uri).ToLocalChecked()); g_free(uri); } NAN_SETTER(Player::UriSetter) { auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder()); Nan::Utf8String uri(value->ToString()); gst_player_set_uri(self->m_gst_player, *uri); info.GetReturnValue().Set(true); } NAN_GETTER(Player::DurationGetter) { auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder()); auto dur = gst_player_get_duration(self->m_gst_player); info.GetReturnValue().Set(static_cast<int32_t>(dur)); } NAN_GETTER(Player::PositionGetter) { auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder()); auto pos = gst_player_get_position(self->m_gst_player); info.GetReturnValue().Set(static_cast<double>(pos)); }
27.205357
81
0.70233
lxndr
93c2ea6cc089617b86204ee4dcccf32ddb5319e4
14,767
cpp
C++
code/steps/source/model/wtg_models/wt_pitch_model/wt_pitch_model_test.cpp
changgang/steps
9b8ea474581885129d1c1a1c3ad40bc8058a7e0a
[ "MIT" ]
29
2019-10-30T07:04:10.000Z
2022-02-22T06:34:32.000Z
code/steps/source/model/wtg_models/wt_pitch_model/wt_pitch_model_test.cpp
cuihantao/steps
60327bf42299cb7117ed5907a931583d7cdf590d
[ "MIT" ]
1
2021-09-25T15:29:59.000Z
2022-01-05T14:04:18.000Z
code/steps/source/model/wtg_models/wt_pitch_model/wt_pitch_model_test.cpp
changgang/steps
9b8ea474581885129d1c1a1c3ad40bc8058a7e0a
[ "MIT" ]
8
2019-12-20T16:13:46.000Z
2022-03-20T14:58:23.000Z
#include "header/basic/test_macro.h" #include "header/model/wtg_models/wt_pitch_model/wt_pitch_model_test.h" #include "header/basic/utility.h" #include "header/steps_namespace.h" #include "header/model/wtg_models/wt_generator_model/wt3g0.h" #include "header/model/wtg_models/wt_aerodynamic_model/aerd0.h" #include "header/model/wtg_models/wt_turbine_model/wt3t0.h" #include <cstdlib> #include <cstring> #include <istream> #include <iostream> #include <cstdio> #include <cmath> #ifdef ENABLE_STEPS_TEST using namespace std; WT_PITCH_MODEL_TEST::WT_PITCH_MODEL_TEST() { TEST_ADD(WT_PITCH_MODEL_TEST::test_get_model_type); TEST_ADD(WT_PITCH_MODEL_TEST::test_get_wt_generator_speed); TEST_ADD(WT_PITCH_MODEL_TEST::test_get_wt_generator_reference_speed); TEST_ADD(WT_PITCH_MODEL_TEST::test_get_bus_frequency); TEST_ADD(WT_PITCH_MODEL_TEST::test_get_bus_frequency_deviation); TEST_ADD(WT_PITCH_MODEL_TEST::test_get_initial_pitch_angle_in_deg_from_wt_aerodynamic_model); TEST_ADD(WT_PITCH_MODEL_TEST::test_set_get_frequency_upper_deadband); TEST_ADD(WT_PITCH_MODEL_TEST::test_set_get_frequency_lower_deadband); TEST_ADD(WT_PITCH_MODEL_TEST::test_get_standard_psse_string); TEST_ADD(WT_PITCH_MODEL_TEST::test_step_response_with_active_power_order_drop); TEST_ADD(WT_PITCH_MODEL_TEST::test_step_response_with_frequency_drop); } void WT_PITCH_MODEL_TEST::setup() { DYNAMIC_MODEL_DATABASE& dmdb = default_toolkit.get_dynamic_model_database(); WTG_MODEL_TEST::setup(); WT_GENERATOR* wt_gen = get_test_wt_generator(); wt_gen->set_p_generation_in_MW(28.0); wt_gen->set_rated_power_per_wt_generator_in_MW(1.5); wt_gen->set_number_of_lumped_wt_generators(20); WT3G0 genmodel(default_toolkit); genmodel.set_device_id(wt_gen->get_device_id()); genmodel.set_converter_activer_current_command_T_in_s(0.2); genmodel.set_converter_reactiver_voltage_command_T_in_s(0.2); genmodel.set_KPLL(20.0); genmodel.set_KIPLL(10.0); genmodel.set_PLLmax(0.1); LVPL lvpl; lvpl.set_low_voltage_in_pu(0.5); lvpl.set_high_voltage_in_pu(0.8); lvpl.set_gain_at_high_voltage(20.0); genmodel.set_LVPL(lvpl); genmodel.set_HVRC_voltage_in_pu(0.8); genmodel.set_HVRC_current_in_pu(20.0); genmodel.set_LVPL_max_rate_of_active_current_change(0.2); genmodel.set_LVPL_voltage_sensor_T_in_s(0.1); dmdb.add_model(&genmodel); AERD0 aeromodel(default_toolkit); aeromodel.set_device_id(wt_gen->get_device_id()); aeromodel.set_number_of_pole_pairs(2); aeromodel.set_generator_to_turbine_gear_ratio(100.0); aeromodel.set_gear_efficiency(1.0); aeromodel.set_turbine_blade_radius_in_m(25.0); aeromodel.set_nominal_wind_speed_in_mps(13.0); aeromodel.set_nominal_air_density_in_kgpm3(1.25); aeromodel.set_air_density_in_kgpm3(1.25); aeromodel.set_turbine_speed_mode(WT_UNDERSPEED_MODE); aeromodel.set_C1(0.22); aeromodel.set_C2(116.0); aeromodel.set_C3(0.4); aeromodel.set_C4(5.0); aeromodel.set_C5(12.5); aeromodel.set_C6(0.0); aeromodel.set_C1(0.5176); aeromodel.set_C2(116.0); aeromodel.set_C3(0.4); aeromodel.set_C4(5.0); aeromodel.set_C5(21.0); aeromodel.set_C6(0.0068); dmdb.add_model(&aeromodel); WT3T0 model(default_toolkit); model.set_device_id(wt_gen->get_device_id()); model.set_Hturbine_in_s(5.0); model.set_Hgenerator_in_s(3.0); model.set_Kshaft_in_pu(20.0); model.set_damping_in_pu(0.01); model.set_Dshaft_in_pu(1.0); dmdb.add_model(&model); } void WT_PITCH_MODEL_TEST::tear_down() { DYNAMIC_MODEL_DATABASE& dmdb = default_toolkit.get_dynamic_model_database(); dmdb.remove_the_last_model(); dmdb.remove_the_last_model(); dmdb.remove_the_last_model(); WTG_MODEL_TEST::tear_down(); } void WT_PITCH_MODEL_TEST::test_get_model_type() { WT_PITCH_MODEL* model = get_test_wt_pitch_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); TEST_ASSERT(model->get_model_type()=="WT PITCH"); } else TEST_ASSERT(false); } void WT_PITCH_MODEL_TEST::test_get_wt_generator_speed() { WT_PITCH_MODEL* model = get_test_wt_pitch_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); WT_TURBINE_MODEL* turbine = get_test_wt_turbine_model(); if(turbine==NULL) { TEST_ASSERT(false); } else { if(turbine->is_model_initialized()) { TEST_ASSERT(fabs(model->get_wt_generator_speed_in_pu()-turbine->get_generator_speed_in_pu())<FLOAT_EPSILON); } } } else TEST_ASSERT(false); } void WT_PITCH_MODEL_TEST::test_get_wt_generator_reference_speed() { WT_PITCH_MODEL* model = get_test_wt_pitch_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); WT_AERODYNAMIC_MODEL* aerd = get_test_wt_aerodynamic_model(); if(aerd==NULL) { TEST_ASSERT(false); } else { if(aerd->is_model_initialized()) { TEST_ASSERT(fabs(model->get_wt_generator_reference_speed_in_pu()-aerd->get_turbine_reference_speed_in_pu())<FLOAT_EPSILON); } } } else TEST_ASSERT(false); } void WT_PITCH_MODEL_TEST::test_get_bus_frequency() { WT_PITCH_MODEL* model = get_test_wt_pitch_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); WT_GENERATOR* gen = get_test_wt_generator(); unsigned int bus = gen->get_generator_bus(); POWER_SYSTEM_DATABASE& psdb = default_toolkit.get_power_system_database(); BUS* busptrr = psdb.get_bus(bus); TEST_ASSERT(fabs(model->get_bus_frequency_in_pu()-psdb.get_bus_frequency_in_pu(bus))<FLOAT_EPSILON); BUS_FREQUENCY_MODEL* freqmodel = busptrr->get_bus_frequency_model(); freqmodel->set_frequency_deviation_in_pu(0.05); TEST_ASSERT(fabs(model->get_bus_frequency_in_pu()-psdb.get_bus_frequency_in_pu(bus))<FLOAT_EPSILON); } else TEST_ASSERT(false); } void WT_PITCH_MODEL_TEST::test_get_bus_frequency_deviation() { WT_PITCH_MODEL* model = get_test_wt_pitch_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); WT_GENERATOR* gen = get_test_wt_generator(); unsigned int bus = gen->get_generator_bus(); POWER_SYSTEM_DATABASE& psdb = default_toolkit.get_power_system_database(); BUS* busptrr = psdb.get_bus(bus); TEST_ASSERT(fabs(model->get_bus_frequency_deviation_in_pu()-psdb.get_bus_frequency_deviation_in_pu(bus))<FLOAT_EPSILON); BUS_FREQUENCY_MODEL* freqmodel = busptrr->get_bus_frequency_model(); freqmodel->set_frequency_deviation_in_pu(0.05); TEST_ASSERT(fabs(model->get_bus_frequency_deviation_in_pu()-psdb.get_bus_frequency_deviation_in_pu(bus))<FLOAT_EPSILON); } else TEST_ASSERT(false); } void WT_PITCH_MODEL_TEST::test_get_initial_pitch_angle_in_deg_from_wt_aerodynamic_model() { WT_PITCH_MODEL* model = get_test_wt_pitch_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); WT_AERODYNAMIC_MODEL* aerd = get_test_wt_aerodynamic_model(); if(aerd==NULL) { TEST_ASSERT(false); } else { if(aerd->is_model_initialized()) { TEST_ASSERT(fabs(model->get_initial_pitch_angle_in_deg_from_wt_aerodynamic_model()-aerd->get_initial_pitch_angle_in_deg())<FLOAT_EPSILON); } } } else TEST_ASSERT(false); } void WT_PITCH_MODEL_TEST::test_set_get_frequency_upper_deadband() { WT_PITCH_MODEL* model = get_test_wt_pitch_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); model->set_frequency_upper_deadband_in_pu(1.0); TEST_ASSERT(fabs(model->get_frequency_upper_deadband_in_pu()-1.0)<FLOAT_EPSILON); model->set_frequency_upper_deadband_in_pu(1.1); TEST_ASSERT(fabs(model->get_frequency_upper_deadband_in_pu()-1.1)<FLOAT_EPSILON); } else TEST_ASSERT(false); } void WT_PITCH_MODEL_TEST::test_set_get_frequency_lower_deadband() { WT_PITCH_MODEL* model = get_test_wt_pitch_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); model->set_frequency_lower_deadband_in_pu(1.0); TEST_ASSERT(fabs(model->get_frequency_lower_deadband_in_pu()-1.0)<FLOAT_EPSILON); model->set_frequency_lower_deadband_in_pu(0.9); TEST_ASSERT(fabs(model->get_frequency_lower_deadband_in_pu()-0.9)<FLOAT_EPSILON); } else TEST_ASSERT(false); } void WT_PITCH_MODEL_TEST::test_get_standard_psse_string() { WT_PITCH_MODEL* model = get_test_wt_pitch_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); default_toolkit.show_information_with_leading_time_stamp(model->get_standard_psse_string()); } else TEST_ASSERT(false); } void WT_PITCH_MODEL_TEST::test_step_response_with_active_power_order_drop() { WT_PITCH_MODEL* model = get_test_wt_pitch_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); default_toolkit.open_log_file("test_log/"+model->get_model_name()+"_"+__FUNCTION__+".txt"); initialize_models(); run_to_time(1.0); apply_active_power_order_drop_of_5_percent(); run_to_time(6.0); default_toolkit.close_log_file(); } else TEST_ASSERT(false); } void WT_PITCH_MODEL_TEST::test_step_response_with_frequency_drop() { WT_PITCH_MODEL* model = get_test_wt_pitch_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); default_toolkit.open_log_file("test_log/"+model->get_model_name()+"_"+__FUNCTION__+".txt"); initialize_models(); run_to_time(1.0); apply_frequency_drop_of_5_percent(); run_to_time(6.0); default_toolkit.close_log_file(); } else TEST_ASSERT(false); } void WT_PITCH_MODEL_TEST::apply_active_power_order_drop_of_5_percent() { WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model(); genmodel->set_initial_active_current_command_in_pu_based_on_mbase(genmodel->get_initial_active_current_command_in_pu_based_on_mbase()*0.95); update_models(); } void WT_PITCH_MODEL_TEST::apply_frequency_drop_of_5_percent() { WT_GENERATOR* gen = get_test_wt_generator(); POWER_SYSTEM_DATABASE& psdb = default_toolkit.get_power_system_database(); unsigned int bus = gen->get_generator_bus(); BUS* busptr = psdb.get_bus(bus); BUS_FREQUENCY_MODEL* model = busptr->get_bus_frequency_model(); model->set_frequency_deviation_in_pu(0.05); update_models(); } void WT_PITCH_MODEL_TEST::initialize_models() { double delt = 0.001; default_toolkit.set_dynamic_simulation_time_step_in_s(delt); default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-2.0*delt); WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model(); WT_AERODYNAMIC_MODEL* aerd = get_test_wt_aerodynamic_model(); WT_TURBINE_MODEL* turbine = get_test_wt_turbine_model(); WT_PITCH_MODEL* model = get_test_wt_pitch_model(); genmodel->initialize(); aerd->initialize(); turbine->initialize(); model->initialize(); export_meter_title(); export_meter_values(); } void WT_PITCH_MODEL_TEST::update_models() { WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model(); WT_AERODYNAMIC_MODEL* aerd = get_test_wt_aerodynamic_model(); WT_TURBINE_MODEL* turbine = get_test_wt_turbine_model(); WT_PITCH_MODEL* model = get_test_wt_pitch_model(); model->run(UPDATE_MODE); turbine->run(UPDATE_MODE); aerd->run(UPDATE_MODE); genmodel->run(UPDATE_MODE); export_meter_values(); } void WT_PITCH_MODEL_TEST::run_to_time(double tend) { ostringstream osstream; WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model(); WT_AERODYNAMIC_MODEL* aerd = get_test_wt_aerodynamic_model(); WT_TURBINE_MODEL* turbine = get_test_wt_turbine_model(); WT_PITCH_MODEL* model = get_test_wt_pitch_model(); double delt =default_toolkit.get_dynamic_simulation_time_step_in_s(); while(true) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt); if(default_toolkit.get_dynamic_simulation_time_in_s()>tend) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt); break; } double pitch=0.0; while(true) { model->run(INTEGRATE_MODE); turbine->run(INTEGRATE_MODE); aerd->run(INTEGRATE_MODE); genmodel->run(INTEGRATE_MODE); if(fabs(pitch-model->get_pitch_angle_in_deg())<1e-6) break; pitch = model->get_pitch_angle_in_deg(); } model->run(UPDATE_MODE); turbine->run(UPDATE_MODE); aerd->run(UPDATE_MODE); genmodel->run(UPDATE_MODE); export_meter_values(); } } void WT_PITCH_MODEL_TEST::export_meter_title() { ostringstream osstream; osstream<<"TIME\tSPEED\tSPEEDREF\tFREQ\tPITCH"; default_toolkit.show_information_with_leading_time_stamp(osstream); } void WT_PITCH_MODEL_TEST::export_meter_values() { ostringstream osstream; WT_PITCH_MODEL* model = get_test_wt_pitch_model(); osstream<<setw(10)<<setprecision(6)<<fixed<<default_toolkit.get_dynamic_simulation_time_in_s()<<"\t" <<setw(10)<<setprecision(6)<<fixed<<model->get_wt_generator_speed_in_pu()<<"\t" <<setw(10)<<setprecision(6)<<fixed<<model->get_wt_generator_reference_speed_in_pu()<<"\t" <<setw(10)<<setprecision(6)<<fixed<<model->get_bus_frequency_in_pu()<<"\t" <<setw(10)<<setprecision(6)<<fixed<<model->get_pitch_angle_in_deg(); default_toolkit.show_information_with_leading_time_stamp(osstream); } #endif
33.334086
154
0.724521
changgang
93c4b43a82bd22e095c5d0b5e1ceed48a21471fb
2,501
cpp
C++
Estructura/plantilla de archivo binario/main.cpp
dkmaster17/DKM
ef22411e57cb37f18b9ddd2305001050855cd137
[ "MIT" ]
null
null
null
Estructura/plantilla de archivo binario/main.cpp
dkmaster17/DKM
ef22411e57cb37f18b9ddd2305001050855cd137
[ "MIT" ]
null
null
null
Estructura/plantilla de archivo binario/main.cpp
dkmaster17/DKM
ef22411e57cb37f18b9ddd2305001050855cd137
[ "MIT" ]
null
null
null
#include "Archivo.h" class Alumno { unsigned int ced; char nom[30]; public: Alumno() { ced=0; } Alumno( char *n, int c ) { ced=c; strcpy(nom,n); } int get_clave() { return ced; } char *get_nom() { return nom; } void set_nom(char *n) { strcpy(nom,n); } void set_ced(char *n) { ced= atoi(n); } void imprime() { cout<<ced<<" "<<nom<<endl; } }; class Materia { unsigned int cod; char tit[80], uc; public: Materia( char *n, int c, char v ) { cod=c; strcpy(tit,n); uc=v; } Materia() { cod=0; } int get_clave() { return cod; } char get_uc() { return uc; } char *get_tit() { return tit; } void set_tit(char *n) { strcpy(tit,n); } void set_cod(char *n) { cod= atoi(n); } void set_uc (char v) { uc=v; } void imprime() { cout<<cod<<" "<<tit<<" "<<uc<<endl;} }; class Semestre { unsigned int cod; unsigned int ced; public: Semestre ( int v1, int v2 ) { cod=v1; ced=v2; } Semestre ( ) { } int get_cod() { return cod; } int get_ced() { return ced; } int get_clave(int tipo=0){if(tipo==1){return cod;}else return ced;} void imprime() { cout<<cod<<" "<<ced<<endl; } }; int main(int argc, char *argv[]) { Alumno clabus("",19567987); Archivo <Alumno> objalu("Datos.dat"); Archivo <Materia> objmat("Materia.dat"); Archivo <Semestre> objsem("Inscritos.dat"); objmat.Abrir(ios::in | ios::binary); objalu.Abrir(ios::in | ios::binary); objsem.Abrir(ios::in | ios::binary); objalu.Imprimir(); if ( objalu.Buscar_Sec(clabus) ) { cout<<"Alumno encontrado:"<<endl; clabus.imprime(); Materia clamat("",111,' '); if ( objmat.Buscar_Sec(clamat) ) { cout<<"Materia encontrada: "; clamat.imprime(); } } else cout<<"No se localizo Alumno!"<<endl; cout<<endl; objmat.Imprimir(); cout<<endl; objsem.Imprimir(); objalu.Cerrar(); objmat.Cerrar(); objsem.Cerrar(); system("PAUSE"); return EXIT_SUCCESS; }
31.2625
74
0.458217
dkmaster17
93c87521b40d86e1102b745d288fd79e5e300ac7
194
cpp
C++
Challenges/codcad_par_ou_impar.cpp
oJordany/CodCad
d3c76d8631583428f5e32caf79a421f2487dbd4c
[ "MIT" ]
null
null
null
Challenges/codcad_par_ou_impar.cpp
oJordany/CodCad
d3c76d8631583428f5e32caf79a421f2487dbd4c
[ "MIT" ]
8
2021-12-23T13:55:40.000Z
2022-01-03T18:55:52.000Z
Challenges/codcad_par_ou_impar.cpp
oJordany/CodCad
d3c76d8631583428f5e32caf79a421f2487dbd4c
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(){ int b, c; cin >> b >> c; if ((b+c) % 2 == 0){ cout << "Bino"; }else{ cout << "Cino"; } return 0; }
12.933333
24
0.42268
oJordany
93cce3548d1fd7c581b417199c76c2ed045fac1d
3,133
cpp
C++
source/benchmarks/bmi-benchmarks/main.cpp
laugengebaeck/girgs
3756df317bc865aa8cd71c0a12607be0b2e57f12
[ "MIT" ]
15
2019-05-17T09:34:28.000Z
2022-01-14T15:07:03.000Z
source/benchmarks/bmi-benchmarks/main.cpp
laugengebaeck/girgs
3756df317bc865aa8cd71c0a12607be0b2e57f12
[ "MIT" ]
7
2019-10-11T07:33:42.000Z
2020-04-06T13:11:02.000Z
source/benchmarks/bmi-benchmarks/main.cpp
laugengebaeck/girgs
3756df317bc865aa8cd71c0a12607be0b2e57f12
[ "MIT" ]
3
2019-06-06T10:33:40.000Z
2022-01-14T15:07:07.000Z
#include <benchmark/benchmark.h> #include <random> #include <girgs/BitManipulation.h> template <typename Impl, unsigned D> static void BM_deposit(benchmark::State& state) { std::vector<std::array<uint32_t, D>> values(1024); { std::mt19937_64 gen; std::uniform_int_distribution<uint32_t> dist; for (auto& x : values) { for(auto& xx : x) xx = dist(gen); } } for(auto _ : state) { for(const auto& c: values) { const auto x = Impl::deposit(c); benchmark::DoNotOptimize(x); } } state.SetItemsProcessed(state.iterations() * values.size()); } #define DEPOSIT_BENCHMARK(X) \ BENCHMARK_TEMPLATE2(BM_deposit, X<1>, 1); \ BENCHMARK_TEMPLATE2(BM_deposit, X<2>, 2); \ BENCHMARK_TEMPLATE2(BM_deposit, X<3>, 3); \ BENCHMARK_TEMPLATE2(BM_deposit, X<4>, 4); \ BENCHMARK_TEMPLATE2(BM_deposit, X<5>, 5); \ DEPOSIT_BENCHMARK(girgs::BitManipulationDetails::Generic::Implementation) // specialisations using fewer pdep at the cost of some more shifts #ifdef __BMI2__ struct PImpl { constexpr static uint32_t highbits(int x) { return static_cast<uint32_t>((1llu << x) - 1); } static uint32_t impl_pdep(uint32_t a) noexcept { return a; } static uint32_t impl_pdep(uint32_t a, uint32_t b) noexcept { auto values = (b << 16) | (a & 0xffff); auto deposited = _pdep_u64(values, 0x5555555555555555ull); return static_cast<uint32_t>(deposited | (deposited >> 31)); } static uint32_t impl_pdep(uint32_t a, uint32_t b, uint32_t c) noexcept { const auto rec = impl_pdep(a, b); const auto values = ((c & highbits(10)) << 22) | (rec & highbits(22)); const auto deposited = _pdep_u64(values, 0x24924924db6db6db); // = 0b00'100100100100100100100100100100'11011011011011011011011011011011 return (deposited & highbits(32)) | (deposited >> 32); } static uint32_t impl_pdep(uint32_t a, uint32_t b, uint32_t c, uint32_t d) noexcept { return impl_pdep(impl_pdep(a, c), impl_pdep(b, d)); } static uint32_t impl_pdep(uint32_t a, uint32_t b, uint32_t c, uint32_t d, uint32_t e) noexcept { const auto rec = impl_pdep(a,b,c,d); const auto values = ((e & highbits(6)) << 26) | (rec & highbits(26)); const auto deposited = _pdep_u64(values, 0x21084210def7bdef); // 0b00'100001000010000100001000010000'11011110111101111011110111101111); return (deposited & highbits(32)) | (deposited >> 32); } }; template <unsigned D> struct SDeposit; #define ImplSpec(X, ...) \ template<> \ struct SDeposit<X> {\ static uint32_t deposit(const std::array<uint32_t, X>& c) noexcept { \ return PImpl::impl_pdep(__VA_ARGS__); \ } \ } ImplSpec(1, c[0]); ImplSpec(2, c[0], c[1]); ImplSpec(3, c[0], c[1], c[2]); ImplSpec(4, c[0], c[1], c[2], c[3]); ImplSpec(5, c[0], c[1], c[2], c[3], c[4]); DEPOSIT_BENCHMARK(SDeposit) DEPOSIT_BENCHMARK(girgs::BitManipulationDetails::BMI2::Implementation) #endif BENCHMARK_MAIN();
31.969388
144
0.635812
laugengebaeck
93cf34a5bb4da518ad3f64c17f1c1dd1937feb37
5,000
cpp
C++
test/board/board_test.cpp
portatlas/tictactoe-cpp
2bae6287881f02e8608c5e3cc7d0031724f09dda
[ "MIT" ]
null
null
null
test/board/board_test.cpp
portatlas/tictactoe-cpp
2bae6287881f02e8608c5e3cc7d0031724f09dda
[ "MIT" ]
null
null
null
test/board/board_test.cpp
portatlas/tictactoe-cpp
2bae6287881f02e8608c5e3cc7d0031724f09dda
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "../../lib/catch.hpp" #include "../../src/marker.hpp" #include "../../src/board/board.hpp" SCENARIO ("Board: Empty Board ", "[empty-board]") { std::vector<std::string> empty_grid = {" ", " ", " ", " ", " ", " ", " ", " ", " "}; GIVEN("Empty Board initialized with a size of 9") { Board board(9); WHEN("#getSize is called") { THEN("return the size of the board") { REQUIRE(board.getSize() == 9); } } WHEN("#getSlot is called for the first slot") { THEN("return an empty slot") { REQUIRE(board.getSlot(1) == " "); } } WHEN("#isSlotEmpty is called for the first slot") { THEN("return true") { REQUIRE(board.isSlotEmpty(1) == true); } } WHEN("#countMarker is called for X") { THEN("return 0") { REQUIRE(board.countMarker(X) == 0); } } WHEN("#countMarker is called for O") { THEN("return 0") { REQUIRE(board.countMarker(O) == 0); } } WHEN("#isGridFull is called") { THEN("return false") { REQUIRE(board.isGridFull() == false); } } WHEN("#validSlots is called") { THEN("return the values from 1 to 9") { std::vector<int> valid_slots = {1, 2, 3, 4, 5, 6, 7, 8, 9}; REQUIRE(board.validSlots() == valid_slots); } } } } SCENARIO("Board: Marked Board", "[marked-board]") { GIVEN("Marked Board with X on the first slot") { Board board(9); board.fillSlot(1, X); WHEN("#getSlot is called with the first slot") { THEN("return X since it was placed on the first slot") { REQUIRE(board.getSlot(1) == X); } } WHEN("#isSlotEmpty is called for the first slot") { THEN("return false") { REQUIRE(board.isSlotEmpty(1) == false); } } WHEN("#countMarker is called") { THEN("return 1") { REQUIRE(board.countMarker(X) == 1); } } WHEN("#validSlots is called") { THEN("return a vector with values from 2 to 9") { std::vector<int> empty_slots = {2, 3, 4, 5, 6, 7, 8, 9}; REQUIRE(board.validSlots() == empty_slots); } } WHEN("#fillSlot is called with 2") { board.fillSlot(2, O); AND_WHEN("#getSlot is called on 2") { THEN("return O") { REQUIRE(board.getSlot(2) == O); } AND_WHEN("#fillSlot is called with 7") { board.fillSlot(7, X); THEN("#getSlot on 7 returns X") { REQUIRE(board.getSlot(7) == X); } } } } } GIVEN("A board initialized with another grid") { std::vector<std::string> marked_grid = { X , X , X , " ", " ", " ", O , O , " "}; Board active_board(marked_grid); WHEN("#countMarker is called") { THEN("return 3 for X") { REQUIRE(active_board.countMarker(X) == 3); } } WHEN("#countMarker is called") { THEN("return 2 for O") { REQUIRE(active_board.countMarker(O) == 2); } } WHEN("#validSlots is called") { THEN("return the values from 4,5,6,9") { std::vector<int> valid_slots = {4, 5, 6, 9}; REQUIRE(active_board.validSlots() == valid_slots); } } } } SCENARIO("Board: Full board", "[full-board]") { GIVEN("A full 3x3 board") { std::vector<std::string> current_board = {X, O, X, O, X, O, X, O, X}; Board full_board(current_board); WHEN("#countMarker is called") { THEN("return 5 for X") { REQUIRE(full_board.countMarker(X) == 5); } } WHEN("#countMarker is called") { THEN("return 4 for O") { REQUIRE(full_board.countMarker(O) == 4); } } WHEN("#isGridFull is called") { THEN("return true") { REQUIRE(full_board.isGridFull() == true); } } WHEN("#validSlots is called") { THEN("#return an empty vector") { std::vector<int> empty_slots = {}; REQUIRE(full_board.validSlots() == empty_slots); } } } }
30.487805
75
0.4278
portatlas
93cfd92585dd834d156563d2de55120aebce2403
572
cpp
C++
Fractal Image Generator/Mandelbrot.cpp
PhantomSabre/Fractal-Image-Generator
9419be7638ea9e5522c09304af9e20f6cd1e2cb9
[ "MIT" ]
null
null
null
Fractal Image Generator/Mandelbrot.cpp
PhantomSabre/Fractal-Image-Generator
9419be7638ea9e5522c09304af9e20f6cd1e2cb9
[ "MIT" ]
null
null
null
Fractal Image Generator/Mandelbrot.cpp
PhantomSabre/Fractal-Image-Generator
9419be7638ea9e5522c09304af9e20f6cd1e2cb9
[ "MIT" ]
null
null
null
#include <complex> #include "Mandelbrot.h" namespace frctl { Mandelbrot::Mandelbrot() { } Mandelbrot::~Mandelbrot() {} //Mandelbrot Algorithm here int Mandelbrot::getIterations(double x, double y) { std::complex<double> z = 0; std::complex<double> c(x, y); //passing in two numbers into this; int iterations = 0; while (iterations < MAX_ITERATIONS) { z = z*z + c; //Mandelbrot algorithm if (abs(z) > 2) //catches numbers not in mandelbrot set (nums approaching infinity) { break; } iterations++; } return iterations; } }
15.459459
86
0.65035
PhantomSabre
93d13743765166a697c43974a5dcae7b9a26404a
581
cpp
C++
Part_Five/Net_income.cpp
ayushpareek179/CPP-course
b2b8b8d2dd06cd772e3c9838abd5b841237bb306
[ "MIT" ]
null
null
null
Part_Five/Net_income.cpp
ayushpareek179/CPP-course
b2b8b8d2dd06cd772e3c9838abd5b841237bb306
[ "MIT" ]
null
null
null
Part_Five/Net_income.cpp
ayushpareek179/CPP-course
b2b8b8d2dd06cd772e3c9838abd5b841237bb306
[ "MIT" ]
null
null
null
//To calculate the net income based on an allowance and deduction percentage #include <iostream> using namespace std; int main() { float income, net, allowance_percent, deduction_percent; cout<<"Enter the basic salary, percentage of allowances and percentage of deductions\n"; cin>>income>>allowance_percent>>deduction_percent; cout<<"For "<<allowance_percent<<"% allowances and "<<deduction_percent<<"% deductions on an income of $"<<income<<",\nNet income = $"; net = income + income*allowance_percent/100 - income*deduction_percent/100; cout<<net<<endl; return 0; }
34.176471
136
0.748709
ayushpareek179
93d4b924650078bb8d2ed5770c5e0d4ad625d61f
28
cc
C++
dev/form-poll/form-poll-srch.cc
chlewey/ilecto-util
a48afc43fb7a355b49d4f9ec4626a7f6dbb32c6c
[ "BSD-3-Clause" ]
null
null
null
dev/form-poll/form-poll-srch.cc
chlewey/ilecto-util
a48afc43fb7a355b49d4f9ec4626a7f6dbb32c6c
[ "BSD-3-Clause" ]
null
null
null
dev/form-poll/form-poll-srch.cc
chlewey/ilecto-util
a48afc43fb7a355b49d4f9ec4626a7f6dbb32c6c
[ "BSD-3-Clause" ]
null
null
null
#include "form-poll-srch.h"
14
27
0.714286
chlewey
93df3ed74c26c5224084bf3791fa5c00f74e9b64
1,749
cpp
C++
Algorithms/Merging_Intervals/merge_intervals.cpp
arslantalib3/algo_ds_101
a1293f407e00b8346f93e8770727f769e7add00e
[ "MIT" ]
182
2020-10-01T17:16:42.000Z
2021-10-04T17:52:49.000Z
Algorithms/Merging_Intervals/merge_intervals.cpp
arslantalib3/algo_ds_101
a1293f407e00b8346f93e8770727f769e7add00e
[ "MIT" ]
759
2020-10-01T00:12:21.000Z
2021-10-04T19:35:11.000Z
Algorithms/Merging_Intervals/merge_intervals.cpp
arslantalib3/algo_ds_101
a1293f407e00b8346f93e8770727f769e7add00e
[ "MIT" ]
1,176
2020-10-01T16:02:13.000Z
2021-10-04T19:20:19.000Z
#include<bits/stdc++.h> using namespace std; // An interval has start time and end time struct Interval { int start, end; }; // To compare two intervals accoridng to their start time bool myComp(Interval interval1, Interval interval2) { return (interval1.start < interval2.start); } // This function takes a set of intervals, merges // overlapping intervals and prints the result void mergeIntervals(Interval arr[], int n) { // Test if the given set has at least one interval if (n <= 0) return; // Create an empty stack of intervals stack<Interval> s; // sorting the intervals in increasing order of start time sort(arr, arr+n, myComp); // push the first interval to stack s.push(arr[0]); // Start from the next interval and merge if necessary for (int i = 1 ; i < n; i++) { // get interval from stack top Interval top = s.top(); // if current interval is not overlapping with stack top, // push it to the stack if (top.end < arr[i].start) s.push(arr[i]); // Otherwise update the ending time of top if ending of current // interval is more else if (top.end < arr[i].end) { top.end = arr[i].end; s.pop(); s.push(top); } } // Print contents of stack cout << "\n After merging Intervals are: "; while (!s.empty()) { Interval t = s.top(); cout << "[" << t.start << "," << t.end << "] "; s.pop(); } return; } int main() { Interval arr[]= {{1,6},{3,9},{11,13},{2,5}}; //creating an array int n = sizeof(arr)/sizeof(arr[0]); //size of the array mergeIntervals(arr,n); return 0; }
24.633803
71
0.573471
arslantalib3
93e950a39232154d4647947860306ddaa38a4dfa
332
cpp
C++
cards/MalaLapka.cpp
programistagd/TrachOnline
2acd9ffac0add87fd0f1824ae2b75132933496c7
[ "MIT" ]
3
2016-06-07T11:55:23.000Z
2016-06-09T17:17:52.000Z
cards/MalaLapka.cpp
radeusgd/TrachOnline
2acd9ffac0add87fd0f1824ae2b75132933496c7
[ "MIT" ]
25
2016-06-13T16:14:18.000Z
2017-07-29T08:12:23.000Z
cards/MalaLapka.cpp
radeusgd/TrachOnline
2acd9ffac0add87fd0f1824ae2b75132933496c7
[ "MIT" ]
null
null
null
#include "cards/MalaLapka.hpp" using namespace Cards; string MalaLapka::getName(){ return "mala_lapka"; } CardPtr MalaLapka::makeNew(){ return make_shared<MalaLapka>(); } void MalaLapka::reset(){ Feature::reset(); value = 1; } void MalaLapka::apply(GameServer::Player& player){ player.handCards -= value; }
15.809524
50
0.680723
programistagd
93eb077ffe00c08369ff5127a26010d2f26ac52d
670
cpp
C++
kittycat/forms/uigetpin.cpp
siilky/catomania
cb3a05cbef523d16b8929b390e190e0cd5924ee9
[ "MIT" ]
1
2021-02-05T23:20:07.000Z
2021-02-05T23:20:07.000Z
kittycat/forms/uigetpin.cpp
siilky/catomania
cb3a05cbef523d16b8929b390e190e0cd5924ee9
[ "MIT" ]
null
null
null
kittycat/forms/uigetpin.cpp
siilky/catomania
cb3a05cbef523d16b8929b390e190e0cd5924ee9
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ui_getpin.h" #include "uigetpin.h" GetPinView::GetPinView(QString email, QString pcName, QWidget *parent) : QDialog(parent, Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint) , ui(new Ui::GetPin) { ui->setupUi(this); ui->lbEmail->setText(email); ui->lbPcName->setText(pcName); ui->buttonBox->button(QDialogButtonBox::Save)->setEnabled(false); } GetPinView::~GetPinView() { } QString GetPinView::pin() const { return ui->lePin->text(); } void GetPinView::on_lePin_textChanged(const QString &text) { ui->buttonBox->button(QDialogButtonBox::Save)->setEnabled(!text.isEmpty()); }
20.9375
96
0.702985
siilky
93f1b5d463ad5f948dafe4ca4077ebeda6a6f920
2,399
cpp
C++
Game/Source/Collision.cpp
Omicrxn/Apollo-Mission
5eec170a9ca9250acfef27c81cc16c4608a78f9f
[ "MIT" ]
null
null
null
Game/Source/Collision.cpp
Omicrxn/Apollo-Mission
5eec170a9ca9250acfef27c81cc16c4608a78f9f
[ "MIT" ]
null
null
null
Game/Source/Collision.cpp
Omicrxn/Apollo-Mission
5eec170a9ca9250acfef27c81cc16c4608a78f9f
[ "MIT" ]
null
null
null
#include "Collision.h" RectCollision::RectCollision(SDL_Rect collider, Module* listener) { this->collider = collider; this->listener = listener; } bool RectCollision::Intersects(SDL_Rect& colliderB) { return (collider.x < (colliderB.x + colliderB.w) && (collider.x + collider.w) > colliderB.x && collider.y < (colliderB.y + colliderB.h) && (collider.y + collider.h) > colliderB.y); } bool RectCollision::Intersects(CircleCollider& colliderB) { iPoint closestPoint = { 0,0 }; if (colliderB.position.x < collider.x) { closestPoint.x = collider.x; } else if (colliderB.position.x > collider.x + collider.w) { closestPoint.x = collider.x + collider.w; } else { closestPoint.x = colliderB.position.x; } if (colliderB.position.y < collider.y) { closestPoint.y = collider.y; } else if (colliderB.position.y > collider.y + collider.h) { closestPoint.y = collider.y + collider.h; } else { closestPoint.y = colliderB.position.y; } iPoint colliderAPos = { collider.x,collider.y }; int distance = colliderAPos.DistanceTo(closestPoint); if (distance < colliderB.radius) { return true; } return false; } void RectCollision::SetPosition(Vec2f position) { this->collider.x = position.x; this->collider.y = position.y; } CircleCollision::CircleCollision(float x, float y, float radius, Module* listener) { this->collider.position.x = x; this->collider.position.y = y; this->collider.radius = radius; this->listener = listener; } bool CircleCollision::Intersects(CircleCollider& colliderB) { return this->collider.position.DistanceTo(colliderB.position) < (this->collider.radius + colliderB.radius); } bool CircleCollision::Intersects(SDL_Rect& colliderB) { iPoint closestPoint = { 0,0 }; if ( this->collider.position.x < colliderB.x) { closestPoint.x = colliderB.x; } else if (this->collider.position.x > colliderB.x + colliderB.w) { closestPoint.x = colliderB.x + colliderB.w; } else { closestPoint.x = this->collider.position.x; } if (this->collider.position.y< colliderB.y) { closestPoint.y = colliderB.y; } else if (this->collider.position.y > colliderB.y + colliderB.h) { closestPoint.y = colliderB.y + colliderB.h; } else { closestPoint.y = this->collider.position.y; } int distance = this->collider.position.DistanceTo(closestPoint); if (distance < this->collider.radius) { return true; } return false; }
23.291262
108
0.702793
Omicrxn
93f21977ed594d80eebd5ff4c14837e74471695c
2,064
cpp
C++
sources/Engine/Modules/Graphics/GraphicsSystem/Camera.cpp
n-paukov/swengine
ca7441f238e8834efff5d2b61b079627824bf3e4
[ "MIT" ]
22
2017-07-26T17:42:56.000Z
2022-03-21T22:12:52.000Z
sources/Engine/Modules/Graphics/GraphicsSystem/Camera.cpp
n-paukov/swengine
ca7441f238e8834efff5d2b61b079627824bf3e4
[ "MIT" ]
50
2017-08-02T19:37:48.000Z
2020-07-24T21:10:38.000Z
sources/Engine/Modules/Graphics/GraphicsSystem/Camera.cpp
n-paukov/swengine
ca7441f238e8834efff5d2b61b079627824bf3e4
[ "MIT" ]
4
2018-08-20T08:12:48.000Z
2020-07-19T14:10:05.000Z
#include "precompiled.h" #pragma hdrstop #include "Camera.h" Camera::Camera() : m_transform(new Transform()) { } Camera::~Camera() { } Transform* Camera::getTransform() const { return m_transform.get(); } const Frustum& Camera::getFrustum() { if (m_needFrustumUpdate || m_transform->isCacheOutdated()) { m_frustum = Frustum::extractFromViewProjection(getViewMatrix(), getProjectionMatrix()); m_needFrustumUpdate = false; } return m_frustum; } void Camera::setAspectRatio(float ratio) { m_aspectRatio = ratio; resetProjectionCache(); } float Camera::getAspectRatio() const { return m_aspectRatio; } void Camera::setNearClipDistance(float distance) { m_nearClipDistance = distance; resetProjectionCache(); } float Camera::getNearClipDistance() const { return m_nearClipDistance; } void Camera::setFarClipDistance(float distance) { m_farClipDistance = distance; resetProjectionCache(); } float Camera::getFarClipDistance() const { return m_farClipDistance; } void Camera::setFOVy(float fov) { m_FOVy = fov; resetProjectionCache(); } float Camera::getFOVy() const { return m_FOVy; } #include <boost/stacktrace.hpp> #include <boost/exception/error_info.hpp> glm::mat4x4 Camera::getProjectionMatrix() { if (m_needProjectionMatrixCacheUpdate) { m_projectionMatrixCache = glm::perspective(m_FOVy, m_aspectRatio, m_nearClipDistance, m_farClipDistance); m_needFrustumUpdate = true; m_needProjectionMatrixCacheUpdate = false; } return m_projectionMatrixCache; } glm::mat4x4 Camera::getViewMatrix() { if (m_transform->isCacheOutdated()) { m_viewMatrixCache = glm::lookAt(m_transform->getPosition(), m_transform->getPosition() + m_transform->getFrontDirection(), m_transform->getUpDirection()); // Trigger transformation cache update (void)m_transform->getTransformationMatrix(); m_needFrustumUpdate = true; } return m_viewMatrixCache; } void Camera::resetProjectionCache() { m_needProjectionMatrixCacheUpdate = true; m_needFrustumUpdate = true; }
17.491525
109
0.739341
n-paukov
93f2f04242d771dd7a604be5f80dadc16ea0037b
1,630
hpp
C++
src/wrappers/glfw/Exception.hpp
JoaoBaptMG/INF443-Project
8c43007a8092931b125cc7feae2adf162e04534e
[ "MIT" ]
8
2020-06-09T00:43:39.000Z
2021-09-27T13:55:46.000Z
src/wrappers/glfw/Exception.hpp
JoaoBaptMG/INF584-Project
a9cf6d4e7d32eb62e7b20fe465c9e75989cca6ac
[ "MIT" ]
1
2020-06-09T02:38:55.000Z
2020-06-09T13:28:13.000Z
src/wrappers/glfw/Exception.hpp
JoaoBaptMG/INF584-Project
a9cf6d4e7d32eb62e7b20fe465c9e75989cca6ac
[ "MIT" ]
3
2020-06-09T00:28:11.000Z
2020-12-30T08:07:34.000Z
#pragma once #include <glad/glad.h> #include <GLFW/glfw3.h> #include <stdexcept> namespace glfw { class Exception : public std::runtime_error { public: Exception(const char* what) : runtime_error(what) {} }; #define EXCEPTION_CLASS(name) class name final : public Exception \ {\ public:\ name(const char* what) : Exception(what) {}\ } EXCEPTION_CLASS(NotInitialized); EXCEPTION_CLASS(NoCurrentContext); EXCEPTION_CLASS(InvalidEnum); EXCEPTION_CLASS(InvalidValue); EXCEPTION_CLASS(OutOfMemory); EXCEPTION_CLASS(ApiUnavailable); EXCEPTION_CLASS(VersionUnavailable); EXCEPTION_CLASS(PlatformError); EXCEPTION_CLASS(FormatUnavailable); EXCEPTION_CLASS(NoWindowContext); #undef EXCEPTION_CLASS inline static void checkError(int code, const char* desc) { switch (code) { case GLFW_NOT_INITIALIZED: throw NotInitialized(desc); case GLFW_NO_CURRENT_CONTEXT: throw NoCurrentContext(desc); case GLFW_INVALID_ENUM: throw InvalidEnum(desc); case GLFW_INVALID_VALUE: throw InvalidValue(desc); case GLFW_OUT_OF_MEMORY: throw OutOfMemory(desc); case GLFW_API_UNAVAILABLE: throw ApiUnavailable(desc); case GLFW_VERSION_UNAVAILABLE: throw VersionUnavailable(desc); case GLFW_PLATFORM_ERROR: throw PlatformError(desc); case GLFW_FORMAT_UNAVAILABLE: throw FormatUnavailable(desc); case GLFW_NO_WINDOW_CONTEXT: throw NoWindowContext(desc); } } inline static void checkError() { const char* desc = nullptr; int error = glfwGetError(&desc); checkError(error, desc); } template <typename T> std::enable_if_t<!std::is_void_v<T>, T> checkError(T value) { checkError(); return value; } }
26.290323
67
0.770552
JoaoBaptMG
93f4fc6e924107501755d219494537308dd17f74
4,453
hpp
C++
remisen_run/include/shape/cube.hpp
tobanteGaming/template-opengl
7eac0d5c49f93b0567cc49fae2b88fd72686e554
[ "MIT" ]
4
2021-07-11T02:07:38.000Z
2022-03-19T06:14:32.000Z
remisen_run/include/shape/cube.hpp
tobanteGaming/template-opengl
7eac0d5c49f93b0567cc49fae2b88fd72686e554
[ "MIT" ]
null
null
null
remisen_run/include/shape/cube.hpp
tobanteGaming/template-opengl
7eac0d5c49f93b0567cc49fae2b88fd72686e554
[ "MIT" ]
null
null
null
#pragma once #include <GL/glew.h> namespace tobanteGaming { // Our vertices. Three consecutive floats give a 3D vertex; Three consecutive // vertices give a triangle. A cube has 6 faces with 2 triangles each, so this // makes 6*2=12 triangles, and 12*3 vertices static const GLfloat g_vertex_buffer_data[] = { -1.0f, -1.0f, -1.0f, // triangle 1 : begin // -1.0f, -1.0f, 1.0f, // -1.0f, 1.0f, 1.0f, // triangle 1 : end // 1.0f, 1.0f, -1.0f, // triangle 2 : begin // -1.0f, -1.0f, -1.0f, // -1.0f, 1.0f, -1.0f, // triangle 2 : end // 1.0f, -1.0f, 1.0f, // -1.0f, -1.0f, -1.0f, // 1.0f, -1.0f, -1.0f, // 1.0f, 1.0f, -1.0f, // 1.0f, -1.0f, -1.0f, // -1.0f, -1.0f, -1.0f, // -1.0f, -1.0f, -1.0f, // -1.0f, 1.0f, 1.0f, // -1.0f, 1.0f, -1.0f, // 1.0f, -1.0f, 1.0f, // -1.0f, -1.0f, 1.0f, // -1.0f, -1.0f, -1.0f, // -1.0f, 1.0f, 1.0f, // -1.0f, -1.0f, 1.0f, // 1.0f, -1.0f, 1.0f, // 1.0f, 1.0f, 1.0f, // 1.0f, -1.0f, -1.0f, // 1.0f, 1.0f, -1.0f, // 1.0f, -1.0f, -1.0f, // 1.0f, 1.0f, 1.0f, // 1.0f, -1.0f, 1.0f, // 1.0f, 1.0f, 1.0f, // 1.0f, 1.0f, -1.0f, // -1.0f, 1.0f, -1.0f, // 1.0f, 1.0f, 1.0f, // -1.0f, 1.0f, -1.0f, // -1.0f, 1.0f, 1.0f, // 1.0f, 1.0f, 1.0f, // -1.0f, 1.0f, 1.0f, // 1.0f, -1.0f, 1.0f // }; // One color for each vertex. They were generated randomly. static const GLfloat g_color_buffer_data[] = { 0.583f, 0.771f, 0.014f, // 0.609f, 0.115f, 0.436f, // 0.327f, 0.483f, 0.844f, // 0.822f, 0.569f, 0.201f, // 0.435f, 0.602f, 0.223f, // 0.310f, 0.747f, 0.185f, // 0.597f, 0.770f, 0.761f, // 0.559f, 0.436f, 0.730f, // 0.359f, 0.583f, 0.152f, // 0.483f, 0.596f, 0.789f, // 0.559f, 0.861f, 0.639f, // 0.195f, 0.548f, 0.859f, // 0.014f, 0.184f, 0.576f, // 0.771f, 0.328f, 0.970f, // 0.406f, 0.615f, 0.116f, // 0.676f, 0.977f, 0.133f, // 0.971f, 0.572f, 0.833f, // 0.140f, 0.616f, 0.489f, // 0.997f, 0.513f, 0.064f, // 0.945f, 0.719f, 0.592f, // 0.543f, 0.021f, 0.978f, // 0.279f, 0.317f, 0.505f, // 0.167f, 0.620f, 0.077f, // 0.347f, 0.857f, 0.137f, // 0.055f, 0.953f, 0.042f, // 0.714f, 0.505f, 0.345f, // 0.783f, 0.290f, 0.734f, // 0.722f, 0.645f, 0.174f, // 0.302f, 0.455f, 0.848f, // 0.225f, 0.587f, 0.040f, // 0.517f, 0.713f, 0.338f, // 0.053f, 0.959f, 0.120f, // 0.393f, 0.621f, 0.362f, // 0.673f, 0.211f, 0.457f, // 0.820f, 0.883f, 0.371f, // 0.982f, 0.099f, 0.879f // }; class Cube { public: Cube() { GLuint VBO; glGenVertexArrays(1, &m_vao); glGenBuffers(1, &VBO); // bind the Vertex Array Object first, then bind and set vertex // buffer(s), and then configure vertex attributes(s). glBindVertexArray(m_vao); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)nullptr); glEnableVertexAttribArray(0); // note that this is allowed, the call to glVertexAttribPointer // registered VBO as the vertex attribute's bound vertex buffer object // so afterwards we can safely unbind glBindBuffer(GL_ARRAY_BUFFER, 0); // remember: do NOT unbind the EBO while a VAO is active as the bound // element buffer object IS stored in the VAO; keep the EBO bound. // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // You can unbind the VAO afterwards so other VAO calls won't // accidentally modify this VAO, but this rarely happens. Modifying // other VAOs requires a call to glBindVertexArray anyways so we // generally don't unbind VAOs (nor VBOs) when it's not directly // necessary. glBindVertexArray(0); } GLuint getVAO() { return m_vao; } void render() { glBindVertexArray(m_vao); // 12*3 indices starting at 0 ->12 triangles -> 6 squares glDrawArrays(GL_TRIANGLES, 0, 12 * 3); // glDisableVertexAttribArray(0); } private: GLuint m_vao; }; } // namespace tobanteGaming
32.268116
78
0.525488
tobanteGaming
93f8503058898c5eae1871a38fcd9a79863fade2
479
cpp
C++
src/snek.cpp
aleksiy325/snek-two
da589b945e347c5178f6cc0c8b190a28651cce50
[ "MIT" ]
9
2018-03-13T03:34:46.000Z
2021-12-17T16:30:27.000Z
src/snek.cpp
mapld/snek-two
da589b945e347c5178f6cc0c8b190a28651cce50
[ "MIT" ]
null
null
null
src/snek.cpp
mapld/snek-two
da589b945e347c5178f6cc0c8b190a28651cce50
[ "MIT" ]
5
2018-03-13T03:41:38.000Z
2022-02-15T08:02:43.000Z
#include "strategies/random_snake.cpp" #include "strategies/eat_snake.cpp" #include "arena/arena.cpp" int main(int argc, char **argv){ Arena arena = Arena(10, 10, 5, 1000); RandomSnake rsnake = RandomSnake{}; Strategy* strat = &rsnake; EatSnake esnake = EatSnake{}; Strategy* estrat = &esnake; arena.addStrategy(strat); arena.addStrategy(strat); arena.addStrategy(estrat); arena.addStrategy(estrat); arena.execute(); }
23.95
40
0.655532
aleksiy325
93f86c81425598e98c8add36f7bc444ca7f0ff86
3,061
cpp
C++
example/up2date_client/main.cpp
rtsoft-gmbh/up2date-cpp
6df40513617d54d72813c49d95df236474379631
[ "Apache-2.0" ]
3
2022-03-24T14:56:29.000Z
2022-03-25T12:42:05.000Z
example/up2date_client/main.cpp
rtsoft-gmbh/up2date-cpp
6df40513617d54d72813c49d95df236474379631
[ "Apache-2.0" ]
9
2022-03-15T18:27:49.000Z
2022-03-25T13:00:28.000Z
example/up2date_client/main.cpp
rtsoft-gmbh/up2date-cpp
6df40513617d54d72813c49d95df236474379631
[ "Apache-2.0" ]
null
null
null
#include "basic_handler.hpp" #include "ritms_dps.hpp" #include <exception> #include <thread> const char *AUTH_CERT_PATH_ENV_NAME = "CERT_PATH"; const char *PROVISIONING_ENDPOINT_ENV_NAME = "PROVISIONING_ENDPOINT"; const char *X_APIG_TOKEN_ENV_NAME = "X_APIG_TOKEN"; using namespace ritms::dps; using namespace ddi; class DPSInfoReloadHandler : public AuthErrorHandler { std::unique_ptr<ProvisioningClient> client; public: explicit DPSInfoReloadHandler(std::unique_ptr<ProvisioningClient> client_) : client(std::move(client_)) {}; void onAuthError(std::unique_ptr<AuthRestoreHandler> ptr) override { for (;;) { try { std::cout << "==============================================" << std::endl; std::cout << "|DPSInfoReloadHandler| Starting provisioning..." << std::endl; auto payload = client->doProvisioning(); std::cout << "|DPSInfoReloadHandler| ... done" << std::endl; auto keyPair = payload->getKeyPair(); std::cout << "|DPSInfoReloadHandler| Setting TLS ..." << std::endl; ptr->setTLS(keyPair->getCrt(), keyPair->getKey()); std::cout << "|DPSInfoReloadHandler| Setting endpoint [" << payload->getUp2DateEndpoint() << "] ..." << std::endl; ptr->setEndpoint(payload->getUp2DateEndpoint()); std::cout << "==============================================" << std::endl; return; } catch (std::exception &e) { std::cout << "provisioning error: " << e.what() << " still trying..." << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(3000)); } } } }; int main() { std::cout << "up2date hawkBit-cpp client started..." << std::endl; auto clientCertificatePath = getEnvOrExit(AUTH_CERT_PATH_ENV_NAME); auto provisioningEndpoint = getEnvOrExit(PROVISIONING_ENDPOINT_ENV_NAME); // special variable for cloud auto xApigToken = getEnvOrExit(X_APIG_TOKEN_ENV_NAME); std::ifstream t((std::string(clientCertificatePath))); if (!t.is_open()) { std::cout << "File " << clientCertificatePath << " not exists" << std::endl; throw std::runtime_error(std::string("fail: cannot open file :").append(clientCertificatePath)); } std::string crt((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); auto dpsBuilder = CloudProvisioningClientBuilder::newInstance(); auto dpsClient = dpsBuilder->setEndpoint(provisioningEndpoint) ->setAuthCrt(crt) ->addHeader("X-Apig-AppCode", std::string(xApigToken)) ->build(); auto authErrorHandler = std::shared_ptr<AuthErrorHandler>(new DPSInfoReloadHandler(std::move(dpsClient))); auto builder = DDIClientBuilder::newInstance(); builder->setAuthErrorHandler(authErrorHandler) ->setEventHandler(std::shared_ptr<EventHandler>(new Handler())) ->build() ->run(); }
42.513889
130
0.608298
rtsoft-gmbh
93f95548b8c1b94f1ea60dfd5565674194a1788d
180
cpp
C++
contrib/gtm/test2/test.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
1
2020-06-30T15:00:50.000Z
2020-06-30T15:00:50.000Z
contrib/gtm/test2/test.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
null
null
null
contrib/gtm/test2/test.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
null
null
null
#include <stdio.h> int main(void) { char* ptr[1024]; int i; for (i = 0; i < 1024; i++) { fprintf(stderr, "ptr[%d] = %p\n", i, ptr[i]); } return 0; }
12.857143
53
0.45
wotchin
93fd448608a779c8db5c904028e225426c228234
721
cpp
C++
VModel - 2017/Vmodel2017S3E3 - Luchian.cpp
LoopieDoo/Variante-INFO
fe42ea7b1b2fb88594c5f103129ee4fa3971ba10
[ "MIT" ]
null
null
null
VModel - 2017/Vmodel2017S3E3 - Luchian.cpp
LoopieDoo/Variante-INFO
fe42ea7b1b2fb88594c5f103129ee4fa3971ba10
[ "MIT" ]
null
null
null
VModel - 2017/Vmodel2017S3E3 - Luchian.cpp
LoopieDoo/Variante-INFO
fe42ea7b1b2fb88594c5f103129ee4fa3971ba10
[ "MIT" ]
1
2021-09-24T22:44:08.000Z
2021-09-24T22:44:08.000Z
#include <iostream> using namespace std; /* Subprogramul nrDiv are doi parametri, a și b (a≤b), prin care primeste câte un număr natural din intervalul [1,10^9]. Subprogramul returnează numărul valorilor din intervalul [a,b] care pot fi scrise ca produs de două numere naturale consecutive. Scrieti definitia completă a subprogramului. */ unsigned int nrDiv(unsigned int a, unsigned int b) { unsigned int nr, i=1, contor=0; for (a; a<=b; a++) { nr = a; while (i*(i+1) <= nr) { if (i*(i+1) == nr) { contor++; break; } i++; } } return contor; } int main() { cout << nrDiv(10, 40); }
20.6
89
0.554785
LoopieDoo
9e02f89180c8e757402b76819f4aef2c6996d36b
910
cpp
C++
main/main.cpp
ivyknob/avionics_wifi
2e21b2af6dd01045663c69df119d5fabdfd25ff7
[ "MIT" ]
null
null
null
main/main.cpp
ivyknob/avionics_wifi
2e21b2af6dd01045663c69df119d5fabdfd25ff7
[ "MIT" ]
4
2020-04-13T09:09:34.000Z
2021-08-31T16:47:29.000Z
main/main.cpp
ivyknob/avionics_wifi
2e21b2af6dd01045663c69df119d5fabdfd25ff7
[ "MIT" ]
null
null
null
#include "main.hpp" DataStorage storage; // Status status; void init_system() { gpio_pad_select_gpio(BLINK_GPIO); gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT); // wifi_setup(); esp_err_t ret = nvs_flash_init(); if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { ESP_ERROR_CHECK(nvs_flash_erase()); ret = nvs_flash_init(); } ESP_ERROR_CHECK(ret); wifi_init_sta(); demo_init(); // gyro_init(); // gyro init fires gyro_task if everything is ok // if not ok, it adds fake gyro ws_server_start(); can_init(); xTaskCreate(&server_task, "server_task", 3000, NULL, 6, NULL); xTaskCreate(&server_handle_task, "server_handle_task", 4000, NULL, 6, NULL); xTaskCreate(&websockets_task, "websockets_task", 6000, NULL, 6, NULL); xTaskCreate(&status_task, "status_task", 7000, NULL, 6, NULL); } extern "C" void app_main() { init_system(); }
26.764706
81
0.708791
ivyknob
9e03c974d6652251b8fbb161bc1094e66b9e38ec
805
cpp
C++
just_a-graph.cpp
itzpankajpanwar/codechef
2d347a9e71d4a838b6b6c2554d1c7f4384ff4941
[ "Apache-2.0" ]
1
2021-09-10T18:59:18.000Z
2021-09-10T18:59:18.000Z
just_a-graph.cpp
itzpankajpanwar/codechef
2d347a9e71d4a838b6b6c2554d1c7f4384ff4941
[ "Apache-2.0" ]
null
null
null
just_a-graph.cpp
itzpankajpanwar/codechef
2d347a9e71d4a838b6b6c2554d1c7f4384ff4941
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define ll long long #define vvi vector<vecetor<int>> #define vi vector<int> #define vvll vector<vecetor<long long>> #define vll vector<long long> const ll MOD = 1e9 + 7; const ll INF = 1e9; int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif int t; cin>>t; while(t--) { int n; cin>>n; vector<int> v(n); unordered_map<int,int> my_map; for(int i=0;i<n;i++) { cin>>v[i]; my_map[v[i]-i-1]++; } if(my_map[v[0]-1]==n) cout<<n<<endl; else cout<<1<<endl; } return 0; }
21.184211
45
0.51677
itzpankajpanwar
9e050db072dfdc589b4a992bb87f189a0b6e481f
1,826
cpp
C++
src/test/cxx_api/TestJQuery.cpp
webosce/libpbnjson
6cd4815a81830bbf6b22647ae8bb4fc818148ee7
[ "Apache-2.0" ]
4
2018-03-20T15:15:50.000Z
2020-05-02T02:30:15.000Z
src/test/cxx_api/TestJQuery.cpp
webosce/libpbnjson
6cd4815a81830bbf6b22647ae8bb4fc818148ee7
[ "Apache-2.0" ]
null
null
null
src/test/cxx_api/TestJQuery.cpp
webosce/libpbnjson
6cd4815a81830bbf6b22647ae8bb4fc818148ee7
[ "Apache-2.0" ]
4
2018-03-19T12:43:43.000Z
2020-05-02T02:30:19.000Z
// Copyright (c) 2015-2018 LG Electronics, Inc. // // 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. // // SPDX-License-Identifier: Apache-2.0 #include <gtest/gtest.h> #include <pbnjson.hpp> using namespace std; using namespace pbnjson; auto json = JDomParser::fromString(R"([ { "k1": "qwe", "k2": "asd" }, { "k1": "zxc", "k2": 12 }, { "k1": 42, "k2": "qaz" } ])"); TEST(TestJQuery, TestValid) { JQuery q1 { ":has(.field)" }; ASSERT_TRUE((bool)q1); std::string q { "object" }; JQuery q2 { q }; ASSERT_TRUE((bool)q2); } TEST(TestJQuery, TestInvalid) { JQuery q { ":invalid()" }; ASSERT_FALSE((bool)q); } TEST(TestJQuery, TestClassic) { JQuery query { "string.k1" }; ASSERT_TRUE((bool)query); int cnt = 0; query.apply(json); for (JQuery::iterator it = query.begin(); it != query.end(); ++it) { JValue e = *it; ASSERT_TRUE(e.isString()); cnt++; } ASSERT_EQ(2, cnt); for (JQuery::iterator it = query.begin(); it != query.end(); ++it) { JValue e = *it; ASSERT_TRUE(e.isString()); cnt--; } ASSERT_EQ(0, cnt); } TEST(TestJQuery, TestCPP11) { JQuery q { "number.k1" }; ASSERT_TRUE((bool)q); int cnt = 0; for (auto e : q(json)) { ASSERT_TRUE(e.isNumber()); cnt++; } ASSERT_EQ(1, cnt); for (auto e : q(json)) { ASSERT_TRUE(e.isNumber()); cnt--; } ASSERT_EQ(0, cnt); }
21.482353
75
0.645674
webosce
9e0be4c95944c47b45f72799b9c89bcf8dd1a8e0
13,909
hpp
C++
framework/areg/base/SharedBuffer.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
70
2021-07-20T11:26:16.000Z
2022-03-27T11:17:43.000Z
framework/areg/base/SharedBuffer.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
32
2021-07-31T05:20:44.000Z
2022-03-20T10:11:52.000Z
framework/areg/base/SharedBuffer.hpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
40
2021-11-02T09:45:38.000Z
2022-03-27T11:17:46.000Z
#pragma once /************************************************************************ * This file is part of the AREG SDK core engine. * AREG SDK is dual-licensed under Free open source (Apache version 2.0 * License) and Commercial (with various pricing models) licenses, depending * on the nature of the project (commercial, research, academic or free). * You should have received a copy of the AREG SDK license description in LICENSE.txt. * If not, please contact to info[at]aregtech.com * * \copyright (c) 2017-2021 Aregtech UG. All rights reserved. * \file areg/base/SharedBuffer.hpp * \ingroup AREG SDK, Asynchronous Event Generator Software Development Kit * \author Artak Avetyan * \brief AREG Platform, Shared Buffer class * This Buffer is used for Read and Write of data and * it might be shared between different threads and objects. * The Data in buffer remains valid until the number of references * to the buffer is more than zero. * ************************************************************************/ /************************************************************************ * Include files. ************************************************************************/ #include "areg/base/GEGlobal.h" #include "areg/base/BufferStreamBase.hpp" #include "areg/base/private/BufferPosition.hpp" ////////////////////////////////////////////////////////////////////////// // SharedBuffer class declaration ////////////////////////////////////////////////////////////////////////// /** * \brief Shared Buffer uses instance of Byte Buffer and keeps track * of reference counter. Every time the same Byte Buffer is used * by other instance of Shared Buffer object, the reference * count will be increased by one. When Shared Buffer * release Byte Buffer, the reference count decreased by one. * The Byte Buffer will be freed when Reference Count is zero. * This mechanism prevents having multiple copy operation when * binary data is passed to multiple objects. * Any write operation preformed by one of Shared Buffer will have * impact on data shared between different instances. * The difference with Raw Buffer is that Raw Buffer object frees * Byte Buffer data in destructor without checking reference count. * By this, the user should prevent passing Byte Buffer object * instantiated by Raw Buffer object. Passing Byte Buffer to * Raw Buffer object is allowed, since Raw Buffer will make a * copy of data and any write operation will not have impact * on other instances of Shared Buffer. * * \note Shared Buffer is not thread safe. There is no data access * synchronization mechanism in this class. The SharedBuffer is * designed to avoid multiple copies of same data, rather than * to share data between different instances of thread. * The instance of Shared Buffer can be used for data streaming. **/ class AREG_API SharedBuffer : public BufferStreamBase // This is data streaming object , public BufferPosition // To control read and write operations { friend class FileBuffer; ////////////////////////////////////////////////////////////////////////// // Constructors / destructor ////////////////////////////////////////////////////////////////////////// public: /** * \brief Default constructor * \param blockSize The size of minimum block size to increase on resize. * It is aligned to NEMemory::BLOCK_SIZE (minimum size) **/ explicit SharedBuffer(unsigned int blockSize = NEMemory::BLOCK_SIZE); /** * \brief Constructor to reserve space for byte buffer object * \param reserveSize Size in bytes to reserve * \param blockSize The size of minimum block size to increase on resize. * It is aligned to NEMemory::BLOCK_SIZE (minimum size) **/ SharedBuffer( unsigned int reserveSize, unsigned int blockSize ); /** * \brief Initialization constructor, writes given data into byte buffer * \param buffer The data to initialize byte buffer * \param size The length in bytes of data * \param blockSize The size of minimum block size to increase on resize. * It is aligned to NEMemory::BLOCK_SIZE (minimum size) **/ SharedBuffer( const unsigned char * buffer, unsigned int size, unsigned int blockSize = NEMemory::BLOCK_SIZE ); /** * \brief Initialization constructor, writes given null-terminated string into byte buffer. * It will write including EOS character ('\0'). * If given string is null, it will write only end-of-string ('\0') character. * \param textString The byte buffer as a null-terminated string * \param blockSize The size of minimum block size to increase on resize. * It is aligned to NEMemory::BLOCK_SIZE (minimum size) **/ explicit SharedBuffer( const char * textString, unsigned int blockSize = NEMemory::BLOCK_SIZE ); explicit SharedBuffer( const wchar_t * textString, unsigned int blockSize = NEMemory::BLOCK_SIZE ); /** * \brief Copy constructor. It does not copy data from src, it will refer to the same shared * byte buffer object and will increase reference counter by one to prevent any other * shared buffer object deleting used data * \param src The source of shared buffer object instance. **/ SharedBuffer(const SharedBuffer& src); /** * \brief Moves data from given source. * \param src The source of shared buffer to mvoe data. **/ SharedBuffer( SharedBuffer && src ) noexcept; /** * \brief Destructor **/ virtual ~SharedBuffer( void ) = default; ////////////////////////////////////////////////////////////////////////// // Operators ////////////////////////////////////////////////////////////////////////// public: /** * \brief Compares 2 instances of shared buffer and returns true if they are equal * \param other Reference to another shared buffer object instance to compare * \return Returns true if 2 objects are same or have similar data. * If 2 objects are invalid, it will return false. **/ inline bool operator == (const SharedBuffer & other) const; /** * \brief Compares 2 instances of shared buffer and returns true if they are not equal * \param other Reference to another shared buffer object instance to compare * \return Returns true if 2 objects are having different data or they are invalid. **/ inline bool operator != (const SharedBuffer & other) const; /** * \brief Assigning operator, it does not copy source data, it increases * byte buffer reference counter by one to prevent other shared * object instance to delete buffer * \param src Reference to source object **/ SharedBuffer & operator = (const SharedBuffer & src); /** * \brief Moves shared buffer data from given source. * \param src The source to move data. **/ SharedBuffer & operator = ( SharedBuffer && src ) noexcept; /************************************************************************/ // Friend global operators to stream Shared Buffer /************************************************************************/ /** * \brief Friend operator declaration to make Shared Buffer streamable. * Writes the data from streaming object to Shared Buffer * \param stream The data streaming object to read data * \param input The Shared Buffer object to write data * \return Reference to Streaming object. **/ friend inline const IEInStream & operator >> ( const IEInStream & stream, SharedBuffer & input ); /** * \brief Friend global operator declaration to make Shared Buffer streamable. * Writes the data from shared buffer to streaming * \param stream The data streaming object to write data * \param input The Shared Buffer object to write data * \return Reference to Streaming object. **/ friend inline IEOutStream & operator << ( IEOutStream & stream, const SharedBuffer & output ); ////////////////////////////////////////////////////////////////////////// // Operations ////////////////////////////////////////////////////////////////////////// public: /** * \brief Returns true if either buffer is invalid, * or current position is equal to zero, * or current position is equal to IECursorPosition::INVALID_CURSOR_POSITION. * Otherwise, it returns false. **/ inline bool isBeginOfBuffer( void ) const; /** * \brief Returns true the buffer is valid and the current position * is equal to used size of buffer. * Otherwise, it returns false. **/ inline bool isEndOfBuffer( void ) const; /** * \brief Returns the pointer to the data buffer at current position. * If position is invalid (IECursorPosition::INVALID_CURSOR_POSITION), it will return nullptr * If it is a start position (IECursorPosition::START_CURSOR_POSITION), it will return pointer to complete buffer * If it is an end of position, it will return nullptr * In other cases it will return (GetBuffer() + GetCursorPosition()) **/ const unsigned char* getBufferAtCurrentPosition( void ) const; /** * \brief Returns the size of block set in the constructor. **/ inline unsigned int getBlockSize( void ) const; ////////////////////////////////////////////////////////////////////////// // Overrides ////////////////////////////////////////////////////////////////////////// /************************************************************************/ // IEByteBuffer interface overrides, not implemented in BufferStreamBase /************************************************************************/ /** * \brief Returns true if buffer is shared between several byte buffer instances. **/ virtual bool isShared( void ) const final; /** * \brief Returns true if buffer can be shared. * The Raw Buffer object should return false. * The Shared Buffer object should return true. **/ virtual bool canShare( void ) const final; /** * \brief Invalidates the buffer. Removes reference, assigns to invalid buffer, * invalidates writing and reading positions. **/ virtual void invalidate( void ) override; protected: /************************************************************************/ // IEByteBuffer protected overrides /************************************************************************/ /** * \brief Returns the offset value from the beginning of byte buffer, which should be set **/ virtual unsigned int getDataOffset( void ) const override; /** * \brief Returns the size of data byte structure to allocate. **/ virtual unsigned int getHeaderSize( void ) const override; /** * \brief Returns the size to align the buffer. By default it is sizeof(NEMemory::uAlign) **/ virtual unsigned int getAlignedSize( void ) const override; ////////////////////////////////////////////////////////////////////////// // Member variables ////////////////////////////////////////////////////////////////////////// protected: /** * \brief The size of block to increase at once every time when need to resize. * This value is a constant and cannot be changed. Set during initialization. **/ const unsigned int mBlockSize; ////////////////////////////////////////////////////////////////////////// // Local function member ////////////////////////////////////////////////////////////////////////// private: /** * \brief Returns reference to Shared Buffer. **/ inline SharedBuffer & self( void ); }; ////////////////////////////////////////////////////////////////////////// // SharedBuffer class inline function implementation ////////////////////////////////////////////////////////////////////////// inline bool SharedBuffer::operator == ( const SharedBuffer &other ) const { return isEqual(other); } inline bool SharedBuffer::operator != ( const SharedBuffer &other ) const { return (isEqual(other) == false); } inline bool SharedBuffer::isBeginOfBuffer( void ) const { unsigned int curPos = getPosition(); return ((isValid() == false) || (curPos == 0) || (curPos == IECursorPosition::INVALID_CURSOR_POSITION)); } inline bool SharedBuffer::isEndOfBuffer( void ) const { return ( isValid() && (getPosition() == getSizeUsed()) ); } inline unsigned int SharedBuffer::getBlockSize(void) const { return mBlockSize; } /************************************************************************/ // Friend streamable operators /************************************************************************/ inline const IEInStream & operator >> (const IEInStream & stream, SharedBuffer & input) { if ( static_cast<const IEInStream *>(&stream) != static_cast<const IEInStream *>(&input) ) { stream.read(input); input.moveToBegin(); } return stream; } inline IEOutStream & operator << (IEOutStream & stream, const SharedBuffer & output) { if ( static_cast<const IEOutStream *>(&stream) != static_cast<const IEOutStream *>(&output) ) { stream.write( output ); output.moveToBegin(); } return stream; }
42.405488
126
0.562226
Ali-Nasrolahi
9e0fdf84235adce70e045f60066e997f54415ef4
1,708
cpp
C++
hackathon/PengXie/decompose_swc/decompose_swc_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
hackathon/PengXie/decompose_swc/decompose_swc_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
hackathon/PengXie/decompose_swc/decompose_swc_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
/* decompose_swc_plugin.cpp * decompose an swc file into segments * 2018-11-19 : by Peng Xie */ #include "v3d_message.h" #include <vector> #include "decompose_swc_plugin.h" using namespace std; Q_EXPORT_PLUGIN2(decompose_swc, TestPlugin); QStringList TestPlugin::menulist() const { return QStringList() <<tr("menu1") <<tr("menu2") <<tr("about"); } QStringList TestPlugin::funclist() const { return QStringList() <<tr("to_multiple_swc") <<tr("func2") <<tr("help"); } void TestPlugin::domenu(const QString &menu_name, V3DPluginCallback2 &callback, QWidget *parent) { if (menu_name == tr("menu1")) { v3d_msg("To be implemented."); } else if (menu_name == tr("menu2")) { v3d_msg("To be implemented."); } else { v3d_msg(tr("decompose an swc file into segments. " "Developed by Peng Xie, 2018-11-19")); } } bool TestPlugin::dofunc(const QString & func_name, const V3DPluginArgList & input, V3DPluginArgList & output, V3DPluginCallback2 & callback, QWidget * parent) { vector<char*> infiles, inparas, outfiles; if(input.size() >= 1) infiles = *((vector<char*> *)input.at(0).p); if(input.size() >= 2) inparas = *((vector<char*> *)input.at(1).p); if(output.size() >= 1) outfiles = *((vector<char*> *)output.at(0).p); if (func_name == tr("to_multiple_swc")) { QString input_swc=QString(infiles.at(0)); QString output_folder=QString(outfiles.at(0)); NeuronTree nt = readSWC_file(input_swc); decompose_to_multiple_swc(nt, output_folder); } else if (func_name == tr("func2")) { v3d_msg("To be implemented."); } else if (func_name == tr("help")) { v3d_msg("To be implemented."); } else return false; return true; }
23.722222
159
0.663349
zzhmark
9e1260b1c4fe8ef58f2cc639b320e2b2b3d2ab1e
452
cpp
C++
Check Capital.cpp
Subhash3/Algorithms-For-Software-Developers
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
[ "BSD-2-Clause" ]
2
2021-10-01T04:20:04.000Z
2021-10-01T04:20:06.000Z
Check Capital.cpp
Subhash3/Algorithms-For-Software-Developers
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
[ "BSD-2-Clause" ]
1
2021-10-01T18:00:09.000Z
2021-10-01T18:00:09.000Z
Check Capital.cpp
Subhash3/Algorithms-For-Software-Developers
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
[ "BSD-2-Clause" ]
8
2021-10-01T04:20:38.000Z
2022-03-19T17:05:05.000Z
class Solution { public: bool detectCapitalUse(string word) { int u=0; int l=0; for(int i=0;i<word.size();i++){ if(word[i]>=65&&word[i]<=90) u++; else if(word[i]>=97&&word[i]<=122) l++; } if(u==word.size()||l==word.size()) return true; if(word[0]>=65&&word[0]<=90&&word.size()-1==l) return true; return false; } };
23.789474
47
0.426991
Subhash3
9e1b53cdb570a629d5a43418b190dda178e7a274
8,019
cpp
C++
plugins/vkeyboard/vkeyboard.cpp
eayus/wayfire
e71beff56eb8d82b16d02a48efc66fa127886d35
[ "MIT" ]
null
null
null
plugins/vkeyboard/vkeyboard.cpp
eayus/wayfire
e71beff56eb8d82b16d02a48efc66fa127886d35
[ "MIT" ]
null
null
null
plugins/vkeyboard/vkeyboard.cpp
eayus/wayfire
e71beff56eb8d82b16d02a48efc66fa127886d35
[ "MIT" ]
null
null
null
#include <core.hpp> #include <debug.hpp> #include <config.hpp> #include <view.hpp> #include <output.hpp> #include <plugin.hpp> #include <signal-definitions.hpp> #include <workspace-manager.hpp> #include <linux/input-event-codes.h> #include "proto/wayfire-shell-server.h" class vkeyboard : public wayfire_plugin_t { static weston_layer input_layer; static weston_seat *vseat; static weston_keyboard *vkbd; touch_gesture_callback swipe; key_callback disable_real_keyboard; std::string keyboard_exec_path = INSTALL_PREFIX "/lib/wayfire/wayfire-virtual-keyboard"; public: static wl_resource *resource; static wayfire_view view; void init(wayfire_config *config); void bind(wl_resource *resource); void show_keyboard(); void set_keyboard(wayfire_view view); void unset_keyboard(); void configure_keyboard(wayfire_view view, int x, int y); void send_key_up(uint32_t key); void send_key_down(uint32_t key); }; weston_layer vkeyboard::input_layer; weston_seat *vkeyboard::vseat = nullptr; weston_keyboard *vkeyboard::vkbd; wl_resource *vkeyboard::resource = nullptr; wayfire_view vkeyboard::view; void send_key_pressed(struct wl_client *client, struct wl_resource *resource, uint32_t key) { auto vk = (vkeyboard*) wl_resource_get_user_data(resource); vk->send_key_down(key); } void send_key_released(struct wl_client *client, struct wl_resource *resource, uint32_t key) { auto vk = (vkeyboard*) wl_resource_get_user_data(resource); vk->send_key_up(key); } void set_virtual_keyboard(struct wl_client *client, struct wl_resource *resource, struct wl_resource *surface) { auto vk = (vkeyboard*) wl_resource_get_user_data(resource); auto wsurf = (weston_surface*) wl_resource_get_user_data(surface); auto view = core->find_view(wsurf); vk->resource = resource; vk->set_keyboard(view); } void configure_keyboard(struct wl_client *client, struct wl_resource *resource, struct wl_resource *surface, int32_t x, int32_t y) { auto vk = (vkeyboard*) wl_resource_get_user_data(resource); auto wsurf = (weston_surface*) wl_resource_get_user_data(surface); auto view = core->find_view(wsurf); vk->configure_keyboard(view, x, y); } void start_interactive_move(struct wl_client *client, struct wl_resource *resource, struct wl_resource *surface) { auto wsurf = (weston_surface*) wl_resource_get_user_data(surface); auto view = core->find_view(wsurf); move_request_signal data; data.view = view; auto touch = weston_seat_get_touch(core->get_current_seat()); if (!touch) { auto ptr = weston_seat_get_pointer(core->get_current_seat()); data.serial = ptr->grab_serial; } else { data.serial = touch->grab_serial; } view->output->emit_signal("move-request", &data); } static const struct wayfire_virtual_keyboard_interface vk_iface = { send_key_pressed, send_key_released, set_virtual_keyboard, configure_keyboard, start_interactive_move }; void unbind_virtual_keyboard(wl_resource* resource) { vkeyboard *vk = (vkeyboard*) wl_resource_get_user_data(resource); vk->unset_keyboard(); } void bind_virtual_keyboard(wl_client *client, void *data, uint32_t version, uint32_t id) { vkeyboard *vk = (vkeyboard*) data; auto resource = wl_resource_create(client, &wayfire_virtual_keyboard_interface, 1, id); wl_resource_set_implementation(resource, &vk_iface, vk, unbind_virtual_keyboard); vk->bind(resource); } using default_grab_key_type = void (*) (weston_keyboard_grab*, const timespec*, uint32_t, uint32_t); default_grab_key_type default_grab_cb; wayfire_key disabling_key; weston_keyboard_grab_interface ignore_grab_iface; void ignore_key(weston_keyboard_grab* kbd, const timespec*, uint32_t key, uint32_t) { } void vkeyboard::init(wayfire_config *config) { grab_interface->name = "vkeyboard"; grab_interface->abilities_mask = 0; /* we must make sure that we do not create multiple interfaces */ if (core->get_num_outputs() == 0) { wl_global *kbd; if ((kbd = wl_global_create(core->ec->wl_display, &wayfire_virtual_keyboard_interface, 1, this, bind_virtual_keyboard)) == NULL) { errio << "Failed to create wayfire_shell interface" << std::endl; } weston_layer_init(&input_layer, core->ec); weston_layer_set_position(&input_layer, WESTON_LAYER_POSITION_TOP_UI); } swipe = [=] (wayfire_touch_gesture *gesture) { if (gesture->direction == GESTURE_DIRECTION_RIGHT) show_keyboard(); }; wayfire_touch_gesture show_gesture; show_gesture.type = GESTURE_EDGE_SWIPE; show_gesture.finger_count = 3; output->add_gesture(show_gesture, &swipe); auto section = config->get_section("vkeyboard"); disabling_key = section->get_key("disable_real_keyboard", {WLR_MODIFIER_ALT | WLR_MODIFIER_CTRL, KEY_K}); if (disabling_key.keyval) { disable_real_keyboard = [=] (weston_keyboard *kbd, uint32_t key) { ignore_grab_iface.cancel = kbd->default_grab.interface->cancel; ignore_grab_iface.modifiers = kbd->default_grab.interface->modifiers; ignore_grab_iface.key = kbd->default_grab.interface->key; if (ignore_grab_iface.key == ignore_key) { ignore_grab_iface.key = default_grab_cb; } else { default_grab_cb = kbd->default_grab.interface->key; ignore_grab_iface.key = ignore_key; } kbd->default_grab.interface = &ignore_grab_iface; }; output->add_key(disabling_key.mod, disabling_key.keyval, &disable_real_keyboard); } keyboard_exec_path = section->get_string("path", keyboard_exec_path); } void vkeyboard::bind(wl_resource *res) { GetTuple(sw, sh, output->get_screen_size()); wayfire_virtual_keyboard_send_match_output_size(res, sw, sh); if (!vseat) { vseat = new weston_seat; weston_seat_init(vseat, core->ec, "virtual-input"); weston_seat_init_keyboard(vseat, NULL); vkbd = weston_seat_get_keyboard(vseat); } } void vkeyboard::send_key_down(uint32_t key) { auto kbd = weston_seat_get_keyboard(core->get_current_seat()); weston_seat_set_keyboard_focus(vseat, kbd->focus); timespec t; timespec_get(&t, TIME_UTC); notify_key(vseat, &t, key, WL_KEYBOARD_KEY_STATE_PRESSED, STATE_UPDATE_AUTOMATIC); } void vkeyboard::send_key_up(uint32_t key) { timespec t; timespec_get(&t, TIME_UTC); notify_key(vseat, &t, key, WL_KEYBOARD_KEY_STATE_RELEASED, STATE_UPDATE_AUTOMATIC); } void vkeyboard::set_keyboard(wayfire_view view) { this->view = view; view->is_special = true; auto output = view->output; output->detach_view(view); view->output = output; weston_layer_entry_insert(&input_layer.view_list, &view->handle->layer_link); output->workspace->add_renderable_view(view); } void vkeyboard::unset_keyboard() { if (resource) { resource = NULL; view->output->workspace->rem_renderable_view(view); } } void vkeyboard::configure_keyboard(wayfire_view view, int x, int y) { view->move(x, y); } void vkeyboard::show_keyboard() { if (!resource) { core->run(keyboard_exec_path.c_str()); } else { wayfire_virtual_keyboard_send_show_virtual_keyboard(resource); } } extern "C" { wayfire_plugin_t *newInstance() { return new vkeyboard; } }
28.537367
100
0.667415
eayus
9e1d1a0125375d4de5f27d874f39293343130325
2,058
cpp
C++
cetty-core/src/cetty/handler/codec/http/CookieHeaderNames.cpp
frankee/cetty2
62ac0cd1438275097e47a9ba471e72efd2746ded
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause" ]
26
2015-11-08T10:58:21.000Z
2021-02-25T08:27:26.000Z
cetty-core/src/cetty/handler/codec/http/CookieHeaderNames.cpp
frankee/cetty2
62ac0cd1438275097e47a9ba471e72efd2746ded
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause" ]
1
2019-02-18T08:46:17.000Z
2019-02-18T08:46:17.000Z
cetty-core/src/cetty/handler/codec/http/CookieHeaderNames.cpp
frankee/cetty2
62ac0cd1438275097e47a9ba471e72efd2746ded
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause" ]
8
2016-02-27T02:37:10.000Z
2021-09-29T05:25:00.000Z
/* * Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com) * Distributed under under the Apache License, version 2.0 (the "License"). */ #include <map> #include <boost/algorithm/string/case_conv.hpp> #include <cetty/handler/codec/http/CookieHeaderNames.h> namespace cetty { namespace handler { namespace codec { namespace http { const std::string CookieHeaderNames::COOKIE_PATH = "Path"; const std::string CookieHeaderNames::COOKIE_EXPIRES = "Expires"; const std::string CookieHeaderNames::COOKIE_MAX_AGE = "Max-Age"; const std::string CookieHeaderNames::COOKIE_DOMAIN = "Domain"; const std::string CookieHeaderNames::COOKIE_SECURE = "Secure"; const std::string CookieHeaderNames::COOKIE_HTTP_ONLY = "HTTPOnly"; const std::string CookieHeaderNames::COOKIE_COMMENT = "Comment"; const std::string CookieHeaderNames::COOKIE_COMMENT_URL = "CommentURL"; const std::string CookieHeaderNames::COOKIE_DISCARD = "Discard"; const std::string CookieHeaderNames::COOKIE_PORT = "Port"; const std::string CookieHeaderNames::COOKIE_VERSION = "Version"; bool CookieHeaderNames::isReserved(const std::string& name) { static bool init = false; static std::map<std::string, int> reservedNames; if (!init) { reservedNames[boost::to_lower_copy(COOKIE_PATH)] = 1; reservedNames[boost::to_lower_copy(COOKIE_EXPIRES)] = 1; reservedNames[boost::to_lower_copy(COOKIE_MAX_AGE)] = 1; reservedNames[boost::to_lower_copy(COOKIE_DOMAIN)] = 1; reservedNames[boost::to_lower_copy(COOKIE_SECURE)] = 1; reservedNames[boost::to_lower_copy(COOKIE_HTTP_ONLY)] = 1; reservedNames[boost::to_lower_copy(COOKIE_COMMENT)] = 1; reservedNames[boost::to_lower_copy(COOKIE_COMMENT_URL)] = 1; reservedNames[boost::to_lower_copy(COOKIE_DISCARD)] = 1; reservedNames[boost::to_lower_copy(COOKIE_PORT)] = 1; reservedNames[boost::to_lower_copy(COOKIE_VERSION)] = 1; init = true; } return reservedNames.find(boost::to_lower_copy(name)) != reservedNames.end(); } } } } }
38.111111
81
0.733722
frankee
9e208c41429c363e1ae00723158281882173af82
952
cpp
C++
raygame/Enemy.cpp
JCoshua/SteeringBehaivors
9c14f69f9be4da46de9a5db693dc14a801a41712
[ "MIT" ]
null
null
null
raygame/Enemy.cpp
JCoshua/SteeringBehaivors
9c14f69f9be4da46de9a5db693dc14a801a41712
[ "MIT" ]
null
null
null
raygame/Enemy.cpp
JCoshua/SteeringBehaivors
9c14f69f9be4da46de9a5db693dc14a801a41712
[ "MIT" ]
null
null
null
#include "Enemy.h" #include "Transform2D.h" #include "SeekDecision.h" #include "IdleDecision.h" #include "WanderDecision.h" #include "IsAggressiveDecision.h" #include "InRangeDecision.h" #include "DecisionComponent.h" #include <Vector2.h> void Enemy::start() { Agent::start(); IdleDecision* idle = new IdleDecision(); WanderDecision* wander = new WanderDecision(); SeekDecision* seek = new SeekDecision(); IsAggressiveDecision* aggression = new IsAggressiveDecision(idle, wander); InRangeDecision* inRange = new InRangeDecision(aggression, seek); addComponent(new DecisionComponent(inRange)); } bool Enemy::getTargetInSight() { MathLibrary::Vector2 direction = getTarget()->getTransform()->getWorldPosition() - getTransform()->getWorldPosition(); float distance = direction.getMagnitude(); float fov = MathLibrary::Vector2::dotProduct(direction.getNormalized(), getTransform()->getForward()); return distance <= 300 && acos(fov) < 1; }
29.75
119
0.756303
JCoshua
9e208f8d3c31f4ab6a37df033f145eb11eb1089f
765
cpp
C++
shared/source/gmm_helper/windows/gmm_configure_device_address_space_drm_or_wddm.cpp
troels/compute-runtime
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
[ "Intel", "MIT" ]
778
2017-09-29T20:02:43.000Z
2022-03-31T15:35:28.000Z
shared/source/gmm_helper/windows/gmm_configure_device_address_space_drm_or_wddm.cpp
troels/compute-runtime
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
[ "Intel", "MIT" ]
478
2018-01-26T16:06:45.000Z
2022-03-30T10:19:10.000Z
shared/source/gmm_helper/windows/gmm_configure_device_address_space_drm_or_wddm.cpp
troels/compute-runtime
3269e719a3ee7bcd97c50ec2cfe78fc8674adec0
[ "Intel", "MIT" ]
215
2018-01-30T08:39:32.000Z
2022-03-29T11:08:51.000Z
/* * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/gmm_helper/client_context/gmm_client_context.h" #include "shared/source/gmm_helper/windows/gmm_memory_base.h" #include "shared/source/helpers/debug_helpers.h" #include "shared/source/os_interface/windows/windows_defs.h" namespace NEO { bool GmmMemoryBase::configureDeviceAddressSpace(GMM_ESCAPE_HANDLE hAdapter, GMM_ESCAPE_HANDLE hDevice, GMM_ESCAPE_FUNC_TYPE pfnEscape, GMM_GFX_SIZE_T svmSize, BOOLEAN bdwL3Coherency) { return true; } }; // namespace NEO
31.875
79
0.597386
troels
9e24d276b8f5690beca3a05b0978b80faa042c04
5,110
cc
C++
ch14_markov_decision_processes/src/main.cc
Amit10311/probabilistic_robotics
d31a9f1a3f5e500bd85d98d7fb4fb5743d1222ad
[ "MIT" ]
959
2018-05-21T00:29:23.000Z
2022-03-29T03:53:05.000Z
ch14_markov_decision_processes/src/main.cc
Amit10311/probabilistic_robotics
d31a9f1a3f5e500bd85d98d7fb4fb5743d1222ad
[ "MIT" ]
9
2018-11-10T10:43:07.000Z
2021-05-03T09:42:03.000Z
ch14_markov_decision_processes/src/main.cc
Amit10311/probabilistic_robotics
d31a9f1a3f5e500bd85d98d7fb4fb5743d1222ad
[ "MIT" ]
347
2018-05-17T13:18:08.000Z
2022-03-29T03:53:13.000Z
#include "markovdp.h" void move(const std::valarray<int>&, const std::valarray<int>&, std::map<std::valarray<int>, double, valarray_comp>&,double&); void move_rdm(const std::valarray<int>&, const std::valarray<int>&, std::map<std::valarray<int>, double, valarray_comp>&,double&); void warp(const std::valarray<int>&, std::map<std::valarray<int>, double, valarray_comp>&,double&); std::vector<tst_data> build_transitions(const mat&, std::vector<void (*)(const std::valarray<int>&, std::map<std::valarray<int>, double, valarray_comp>&,double&)>&); int main(int argc, char** argv){ mat occupancy; occupancy.load(arma::hdf5_name("occupancy_map.h5", "occupancy")); uint n = 0; for (size_t i = 0; i < occupancy.n_rows; i++) { for (size_t j = 0; j < occupancy.n_cols; j++) { if (occupancy(i,j) == 0) { occupancy(i,j) =n++; continue; } } } vec jvalues = zeros<vec>(54); //terminal states. jvalues(0) = +100; jvalues(1) = -100; jvalues(36) = -100; jvalues(37) = +100; std::vector<void (*)(const std::valarray<int>&, std::map<std::valarray<int>, double, valarray_comp>&,double&)> moves; moves.push_back([](const auto& from, auto& to, double& cost){ return move_rdm(std::valarray<int>({0,1,0}),from,to,cost);}); moves.push_back([](const auto& from, auto& to, double& cost){ return move_rdm(std::valarray<int>({1,0,0}),from,to,cost);}); moves.push_back([](const auto& from, auto& to, double& cost){ return move_rdm(std::valarray<int>({0,-1,0}),from,to,cost);}); moves.push_back([](const auto& from, auto& to, double& cost){ return move_rdm(std::valarray<int>({-1,0,0}),from,to,cost);}); moves.push_back(warp); std::vector<tst_data> transitions = build_transitions(occupancy, moves); MarkovDP mdp(jvalues, transitions); uvec policy(54); uint last_iter(0); double epsilon = 1e-2; uint max_iter = 1000; mdp.value_iteration(epsilon, max_iter, jvalues, policy, last_iter); std::cout << "converged in " << last_iter << " iterations." << '\n'; jvalues.print("Jvalues: "); policy.print("optimal policy: "); return 0; } void move(const std::valarray<int>& dxy, const std::valarray<int>& from, std::map<std::valarray<int>, double, valarray_comp>& to,double& cost) { cost = -1.0; if (from[0] == 0 || ( from[0] == 7 && from[1] == 6 && from[2] == 0 )) { return; } to[from + dxy] = 1.0; } void move_rdm(const std::valarray<int>& dxy, const std::valarray<int>& from, std::map<std::valarray<int>, double, valarray_comp>& to,double& cost) { cost = -1.0; if (from[0] == 0 || ( from[0] == 7 && from[1] == 6 && from[2] == 0 )) { return; } to[from + dxy] = 0.9; to[from - dxy] = 0.1/3; to[from + std::valarray<int>({dxy[1],dxy[0],dxy[2]})] = 0.1/3; to[from - std::valarray<int>({dxy[1],dxy[0],dxy[2]})] = 0.1/3; } void warp(const std::valarray<int>& from, std::map<std::valarray<int>, double, valarray_comp>& to,double& cost) { cost = 0.0; if (from[0] == 0 && from[2] == 0) { to[std::valarray<int>({from[0], from[1], 1})] = 0.5; to[std::valarray<int>({from[0], from[1], -1})] = 0.5; return; } if ( from[0] == 7 && from[1] == 6 && from[2] == 0) { to[std::valarray<int>({7, 6, 1})] = 0.5; to[std::valarray<int>({7, 6, -1})] = 0.5; return; } } inline uint to_linear(std::valarray<int> coord, const mat& occupancy) { return (coord[2]+1)*18 + (uint)occupancy(coord[0],coord[1]); } std::vector<tst_data> build_transitions(const mat& occupancy, std::vector<void (*)(const std::valarray<int>&, std::map<std::valarray<int>, double, valarray_comp>&,double&)>& moves) { std::vector<tst_data> transitions; for (size_t i = 0; i < moves.size(); i++) { transitions.push_back({sp_mat(54,54),vec(54)}); } int nr = occupancy.n_rows; int nc = occupancy.n_cols; for (int i = 0; i < nr; i++) { for (int j = 0; j < nc; j++) { if (occupancy(i,j)==-1) { continue; } for (int z = -1; z < 2; z++) { std::valarray<int> from({i, j, z}); uint lin_indx = to_linear(from, occupancy); for ( uint m=0; m < moves.size(); ++m) { std::map<std::valarray<int>, double, valarray_comp> to; double cost; moves[m](from,to,cost); double stay(0); for( auto const& tovtx : to ) { auto const& tocoord = tovtx.first; auto const& toprob = tovtx.second; if (tocoord[0] < 0 || tocoord[0] >= nr || tocoord[1] < 0 || tocoord[1] >= nc || occupancy(tocoord[0], tocoord[1]) == -1) { stay += toprob; } else { uint lin_indx1 = to_linear(tocoord, occupancy); transitions[m].tst_proba(lin_indx,lin_indx1) = toprob; } } transitions[m].tst_proba(lin_indx,lin_indx) = (to.size())?stay:1; transitions[m].tst_cost(lin_indx) = (stay<1)?cost:0; } } } } return transitions; }
33.398693
148
0.568102
Amit10311
9e2645ab9abce82e5ea7528495d5baa455e27140
456
cpp
C++
ProfessionalC++/Lambdas/count_if.cpp
zzragida/CppExamples
d627b097efc04209aa4012f7b7f9d82858da3f2d
[ "Apache-2.0" ]
null
null
null
ProfessionalC++/Lambdas/count_if.cpp
zzragida/CppExamples
d627b097efc04209aa4012f7b7f9d82858da3f2d
[ "Apache-2.0" ]
null
null
null
ProfessionalC++/Lambdas/count_if.cpp
zzragida/CppExamples
d627b097efc04209aa4012f7b7f9d82858da3f2d
[ "Apache-2.0" ]
null
null
null
#include <vector> #include <algorithm> #include <iostream> using namespace std; int main() { vector<int> vec = {1,2,3,4,5,6,7,8,9}; int value = 3; int cntLambdaCalled = 0; int cnt = count_if(vec.begin(), vec.end(), [=, &cntLambdaCalled](int i) { ++cntLambdaCalled; return i > value; }); cout << "The lambda expression was called " << cntLambdaCalled << " times." << endl; cout << "Found " << cnt << " value > " << value << endl; return 0; }
22.8
74
0.614035
zzragida
9e2790ee393aa1834c2123024d8bbb5ee6c4101f
3,150
cpp
C++
libs/anari_test_scenes/scenes/cornell_box_cylinder_geom.cpp
Piromancer/ANARI-SDK
636b8521b0f0c05a4d7b9cf50a643377d4cd00b9
[ "Apache-2.0" ]
null
null
null
libs/anari_test_scenes/scenes/cornell_box_cylinder_geom.cpp
Piromancer/ANARI-SDK
636b8521b0f0c05a4d7b9cf50a643377d4cd00b9
[ "Apache-2.0" ]
null
null
null
libs/anari_test_scenes/scenes/cornell_box_cylinder_geom.cpp
Piromancer/ANARI-SDK
636b8521b0f0c05a4d7b9cf50a643377d4cd00b9
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The Khronos Group // SPDX-License-Identifier: Apache-2.0 #include "cornell_box_cylinder_geom.h" namespace anari { namespace scenes { // cone mesh data static std::vector<glm::vec3> vertices = { // Cylinder {0.00f, 0.80f, 0.00f}, {0.00f, -0.80f, 0.00f}}; static std::vector<float> radiuses = { // Cylinder 0.5f}; static std::vector<glm::uint8> caps = { // Cylinder 1, 1}; static std::vector<glm::vec4> colors = { // Cone {1.0f, 0.0f, 0.0f, 1.0f}, {0.0f, 1.0f, 0.0f, 1.0f} }; // CornelBox definitions ////////////////////////////////////////////////////// CornellBoxCylinder::CornellBoxCylinder(anari::Device d) : TestScene(d) { m_world = anari::newObject<anari::World>(m_device); } CornellBoxCylinder::~CornellBoxCylinder() { anari::release(m_device, m_world); } anari::World CornellBoxCylinder::world() { return m_world; } void CornellBoxCylinder::commit() { auto d = m_device; auto geom = anari::newObject<anari::Geometry>(d, "cylinder"); anari::setAndReleaseParameter(d, geom, "vertex.position", anari::newArray1D(d, vertices.data(), vertices.size())); anari::setAndReleaseParameter(d, geom, "vertex.color", anari::newArray1D(d, colors.data(), colors.size())); anari::setAndReleaseParameter( d, geom, "vertex.cap", anari::newArray1D(d, caps.data(), caps.size())); anari::setAndReleaseParameter(d, geom, "primitive.radius", anari::newArray1D(d, radiuses.data(), radiuses.size())); anari::commit(d, geom); auto surface = anari::newObject<anari::Surface>(d); anari::setAndReleaseParameter(d, surface, "geometry", geom); auto mat = anari::newObject<anari::Material>(d, "matte"); anari::setParameter(d, mat, "color", "color"); anari::commit(d, mat); anari::setAndReleaseParameter(d, surface, "material", mat); anari::commit(d, surface); anari::setAndReleaseParameter( d, m_world, "surface", anari::newArray1D(d, &surface)); anari::release(d, surface); anari::Light light; float irradiance = 2.5f; float angularDiameter = 0.0f; float red = 0.22f; float green = 0.22f; float blue = 0.15f; float dirX = 0.0f; float dirY = 0.0f; float dirZ = 1.0f; if (anari::deviceImplements(d, "ANARI_KHR_AREA_LIGHTS")) { light = anari::newObject<anari::Light>(d, "directional"); anari::setParameter(d, light, "color", glm::vec3(red, green, blue)); anari::setParameter(d, light, "direction", glm::vec3(dirX, dirY, dirZ)); anari::setParameter(d, light, "irradiance", irradiance); anari::setParameter(d, light, "angularDiameter", angularDiameter); } else { light = anari::newObject<anari::Light>(d, "directional"); anari::setParameter(d, light, "direction", glm::vec3(0.f, -0.5f, 1.f)); } anari::commit(d, light); anari::setAndReleaseParameter( d, m_world, "light", anari::newArray1D(d, &light)); anari::release(d, light); anari::commit(d, m_world); } TestScene *sceneCornellBoxCylinder(anari::Device d) { return new CornellBoxCylinder(d); } } // namespace scenes } // namespace anari
24.80315
79
0.64
Piromancer
9e27fb41f8dafbf65d7ffc744aa8448a71f46e51
4,323
cpp
C++
src/MainController.cpp
pigatron-industries/xen_daisy_dsp
2ce00d8d5dbeb71fb15b3f2c92298cba7f1c8a37
[ "Unlicense" ]
null
null
null
src/MainController.cpp
pigatron-industries/xen_daisy_dsp
2ce00d8d5dbeb71fb15b3f2c92298cba7f1c8a37
[ "Unlicense" ]
null
null
null
src/MainController.cpp
pigatron-industries/xen_daisy_dsp
2ce00d8d5dbeb71fb15b3f2c92298cba7f1c8a37
[ "Unlicense" ]
null
null
null
#include <DaisyDuino.h> #include "MainController.h" #include "util/Profiler.h" #include "io/MemPool.h" #include "io/Config.h" #include "utility/gpio.h" MainController MainController::instance; DaisyHardware hardware; void MainController::audioCallback(float **in, float **out, size_t size) { MainController::instance.process(in, out, size); } void MainController::registerController(Controller* controller) { controllers[controllerSize] = controller; controllerSize++; controller->getDisplayPage()->setNumber(0, controllerSize); } void MainController::init() { hardware = DAISY.init(DAISY_SEED, AUDIO_SR_48K); sampleRate = DAISY.get_samplerate(); Hardware::hw.init(); refreshTimer.start(100000); activeController = Config::getSelectedApp(); if(activeController >= controllerSize) { activeController = 0; Config::setSelectedApp(0); } controllers[activeController]->init(sampleRate); Hardware::hw.display.setDisplayedPage(controllers[activeController]->getDisplayPage()); DAISY.begin(MainController::audioCallback); } void MainController::update() { UIEvent event = updateUIEvent(); switch(event) { case UIEvent::EVENT_CLOCKWISE: if(controllers[activeController]->getDisplayPage()->selectedItem == 0) { int controllerIndex = ((activeController + 1) % (controllerSize)); setActiveController(controllerIndex); } else { controllers[activeController]->event(event, controllers[activeController]->getDisplayPage()->selectedItem); } break; case UIEvent::EVENT_COUNTERCLOCKWISE: if(controllers[activeController]->getDisplayPage()->selectedItem == 0) { int controllerIndex = activeController > 0 ? activeController - 1 : controllerSize - 1; setActiveController(controllerIndex); } else { controllers[activeController]->event(event, controllers[activeController]->getDisplayPage()->selectedItem); } break; case UIEvent::EVENT_SHORT_PRESS: controllers[activeController]->getDisplayPage()->nextSelection(); break; case UIEvent::EVENT_LONG_PRESS: rebootToBootloader(); break; } controllers[activeController]->update(); if(refreshTimer.isStopped()) { controllers[activeController]->updateDisplay(); refreshTimer.start(100000); } Hardware::hw.display.render(); PROFILE_DUMP } void MainController::setActiveController(int controllerIndex) { DAISY.end(); MemPool::resetPool(); controllers[controllerIndex]->init(sampleRate); controllers[controllerIndex]->getDisplayPage()->setSelection(0); Hardware::hw.display.setDisplayedPage(controllers[controllerIndex]->getDisplayPage()); Config::setSelectedApp(controllerIndex); activeController = controllerIndex; DAISY.begin(MainController::audioCallback); DAISY.end(); DAISY.begin(MainController::audioCallback); } UIEvent MainController::updateUIEvent() { Hardware::hw.encoderButton.update(); Hardware::hw.encoder.update(); long movement = Hardware::hw.encoder.getMovement(); if(Hardware::hw.encoderButton.held() && Hardware::hw.encoderButton.duration() >= 1000) { return UIEvent::EVENT_LONG_PRESS; } if(movement > 0) { return UIEvent::EVENT_CLOCKWISE; } if(movement < 0) { return UIEvent::EVENT_COUNTERCLOCKWISE; } if(Hardware::hw.encoderButton.released() && Hardware::hw.encoderButton.previousDuration() < 1000) { return UIEvent::EVENT_SHORT_PRESS; } return UIEvent::EVENT_NONE; } void MainController::process(float **in, float **out, size_t size) { PROFILE_START controllers[activeController]->process(in, out, size); PROFILE_END } void MainController::rebootToBootloader() { Hardware::hw.display.alert("PROG"); // Initialize Boot Pin dsy_gpio_pin bootpin = {DSY_GPIOG, 3}; dsy_gpio pin; pin.mode = DSY_GPIO_MODE_OUTPUT_PP; pin.pin = bootpin; dsy_gpio_init(&pin); // Pull Pin HIGH dsy_gpio_write(&pin, 1); // wait a few ms for cap to charge delay(10); // Software Reset HAL_NVIC_SystemReset(); }
30.659574
123
0.675226
pigatron-industries
9e287519aa0fc0426501b3bbd19f6df8d2cc1ed2
910
cpp
C++
examples/qcor_demos/pirq_workshop/qcor/demo3_nisq_noise_mitigation/mitiq_noise_mitigation.cpp
ahayashi/qcor
929988b92cfec52d321c48e6cc01545e46edc024
[ "BSD-3-Clause" ]
null
null
null
examples/qcor_demos/pirq_workshop/qcor/demo3_nisq_noise_mitigation/mitiq_noise_mitigation.cpp
ahayashi/qcor
929988b92cfec52d321c48e6cc01545e46edc024
[ "BSD-3-Clause" ]
null
null
null
examples/qcor_demos/pirq_workshop/qcor/demo3_nisq_noise_mitigation/mitiq_noise_mitigation.cpp
ahayashi/qcor
929988b92cfec52d321c48e6cc01545e46edc024
[ "BSD-3-Clause" ]
null
null
null
/// mitiq_noise_mitigation.cpp: Run error mitigation with mitiq ZNE (zero-noise extrapolation) /// Compile: /// $ qcor -qpu aer[noise-model:noise_model.json] -shots 8192 -em mitiq-zne /// mitiq_noise_mitigation.cpp Execute: specify the number of repeating CNOT /// ./a.out N // Repeating CNOT's to evaluate noise mitigation. // This is a do-nothing circuit: qubits should return to the |00> state. __qpu__ void noisy_zero(qreg q, int cx_count) { H(q); for (int i = 0; i < cx_count; i++) { X::ctrl(q[0], q[1]); } H(q); Measure(q); } int main(int argc, char *argv[]) { // Default depth int CX_depth = 0; // Parse number of CX cycles: if (argc == 2) { CX_depth = std::stoi(argv[1]); } qreg q = qalloc(2); // noisy_zero::print_kernel(q, CX_depth); noisy_zero(q, CX_depth); // q.print(); std::cout << "CX depth: " << CX_depth << "; Expectation: " << q.exp_val_z() << "\n"; }
29.354839
94
0.637363
ahayashi
9e2d0f32d0e23b44fbf12189c4ee6b0c92526cf0
68,271
cpp
C++
Samples/System/UserManagement/GameScreens.cpp
acidburn0zzz/Xbox-GDK-Samples
0a998ca467f923aa04bd124a5e5ca40fe16c386c
[ "MIT" ]
1
2021-12-30T09:49:18.000Z
2021-12-30T09:49:18.000Z
Samples/System/UserManagement/GameScreens.cpp
acidburn0zzz/Xbox-GDK-Samples
0a998ca467f923aa04bd124a5e5ca40fe16c386c
[ "MIT" ]
null
null
null
Samples/System/UserManagement/GameScreens.cpp
acidburn0zzz/Xbox-GDK-Samples
0a998ca467f923aa04bd124a5e5ca40fe16c386c
[ "MIT" ]
null
null
null
//-------------------------------------------------------------------------------------- // GameScreens.cpp // // Advanced Technology Group (ATG) // Copyright (C) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #include "pch.h" #include "GameScreens.h" #include "UserManagement.h" using namespace ATG; using namespace DirectX; using namespace ATG::UITK; #pragma region Game Screen GameScreen::GameScreen(Sample* sample, UIManager* uiManager) : m_sample(sample) , m_uiManager(uiManager) { } GameScreen::~GameScreen() { } #pragma endregion #pragma region Game Screen - Title GameScreenTitle::GameScreenTitle(Sample* sample, UIManager* uiManager) : GameScreen(sample, uiManager) , m_titleState(TitleState::SignIn) { m_screen = m_uiManager->LoadLayoutFromFile("Assets/Layouts/title-screen.json"); m_startButton = m_screen->GetTypedSubElementById<UIButton>(ID("start_button")); // Get the console sandbox so it can be displayed. char sandboxId[XSystemXboxLiveSandboxIdMaxBytes]; size_t ignore; DX::ThrowIfFailed(XSystemGetXboxLiveSandboxId(XSystemXboxLiveSandboxIdMaxBytes, sandboxId, &ignore)); // Fill in the sandbox element. Changing the sandbox requires a restart so this only needs to happen once. char sandboxDisplayString[13 + XSystemXboxLiveSandboxIdMaxBytes]; sprintf_s(sandboxDisplayString, "Sandbox ID: %s", sandboxId); auto sandboxIdTextElement = m_screen->GetTypedSubElementById<UIStaticText>(ID("sandbox_text")); if (sandboxIdTextElement) { sandboxIdTextElement->SetDisplayText(sandboxDisplayString); } m_uiManager->AttachTo(m_screen, m_uiManager->GetRootElement()); m_screen->SetVisible(false); m_warningScreen = m_uiManager->LoadLayoutFromFile("Assets/Layouts/warning-screen.json"); m_uiManager->AttachTo(m_warningScreen, m_uiManager->GetRootElement()); m_warningScreen->SetVisible(false); m_warningSignInButton = m_warningScreen->GetTypedSubElementById<UIButton>(ID("sign_in_button")); m_warningContinueButton = m_warningScreen->GetTypedSubElementById<UIButton>(ID("continue_button")); m_warningSelectedOption = m_warningSignInButton; m_menuScreen = m_uiManager->LoadLayoutFromFile("Assets/Layouts/menu-screen.json"); m_uiManager->AttachTo(m_menuScreen, m_uiManager->GetRootElement()); m_menuScreen->SetVisible(false); auto menuSection = m_menuScreen->GetSubElementById(ID("menu_section")); m_menuSingleUserButton = menuSection->GetTypedSubElementById<UIButton>(ID("single_user_button")); m_menuMultipleUserButton = menuSection->GetTypedSubElementById<UIButton>(ID("multiple_user_button")); m_menuRestartButton = menuSection->GetTypedSubElementById<UIButton>(ID("restart_button")); m_restartDescriptionText = menuSection->GetSubElementById(ID("restart_description_text")); m_menuSelectedOption = m_menuSingleUserButton; } GameScreenTitle::~GameScreenTitle() { } void GameScreenTitle::Initialize() { m_screen->SetVisible(true); auto gameScreenManager = m_sample->GetGameScreenManager(); if (gameScreenManager) { if (gameScreenManager->HavePrimaryUser()) { SwitchTitleState(GameScreenTitle::TitleState::MenuWithUser); } else { SwitchTitleState(GameScreenTitle::TitleState::SignIn); } } } void GameScreenTitle::Cleanup() { m_screen->SetVisible(false); } void GameScreenTitle::Update(double /*dt*/) { switch (m_titleState) { case GameScreenTitle::TitleState::SignIn: UpdateSignIn(); break; case GameScreenTitle::TitleState::MenuWithUser: case GameScreenTitle::TitleState::MenuWithoutUser: UpdateMenu(); break; case GameScreenTitle::TitleState::NoUserWarning: UpdateNoUserWarning(); break; default: break; }; } void GameScreenTitle::UpdateSignIn() { const bool signInPressed = m_sample->GetGameInputCollection()->CheckInputAllDevices( [](const DirectX::GamePad::ButtonStateTracker& state) { return state.a == GamePad::ButtonStateTracker::PRESSED; }); if (signInPressed) { m_sample->GetGameScreenManager()->TryDefaultPrimaryUserSignIn(false); } } void GameScreenTitle::UpdateNoUserWarning() { assert(m_sample->GetGameScreenManager()->GetUserCount() == 0); const bool selectPressed = m_sample->GetGameInputCollection()->CheckInputAllDevices( [](const DirectX::GamePad::ButtonStateTracker& state) { return state.a == GamePad::ButtonStateTracker::PRESSED; }); const bool upPressed = m_sample->GetGameInputCollection()->CheckInputAllDevices( [](const DirectX::GamePad::ButtonStateTracker& state) { return state.dpadUp == GamePad::ButtonStateTracker::PRESSED; }); const bool downPressed = m_sample->GetGameInputCollection()->CheckInputAllDevices( [](const DirectX::GamePad::ButtonStateTracker& state) { return state.dpadDown == GamePad::ButtonStateTracker::PRESSED; }); if (selectPressed && m_warningSignInButton == m_warningSelectedOption) { SwitchTitleState(GameScreenTitle::TitleState::SignIn); } else if(selectPressed && m_warningContinueButton == m_warningSelectedOption) { SwitchTitleState(GameScreenTitle::TitleState::MenuWithoutUser); } if (upPressed) { m_warningSelectedOption = m_warningSignInButton; } if (downPressed) { m_warningSelectedOption = m_warningContinueButton; } } void GameScreenTitle::UpdateMenu() { const bool downPressed = m_sample->GetGameInputCollection()->CheckInputAllDevices( [](const DirectX::GamePad::ButtonStateTracker& state) { return state.dpadDown == GamePad::ButtonStateTracker::PRESSED; }); const bool upPressed = m_sample->GetGameInputCollection()->CheckInputAllDevices( [](const DirectX::GamePad::ButtonStateTracker& state) { return state.dpadUp == GamePad::ButtonStateTracker::PRESSED; }); if (upPressed) { NavigateToPrevOption(); } else if (downPressed) { NavigateToNextOption(); } const bool aPressed = m_sample->GetGameInputCollection()->CheckInputAllDevices( [](const DirectX::GamePad::ButtonStateTracker& state) { return state.a == GamePad::ButtonStateTracker::PRESSED; }); if (aPressed) { SelectCurrentOption(); } const bool switchUserPressed = m_sample->GetGameInputCollection()->CheckInputAllDevices( [](const DirectX::GamePad::ButtonStateTracker& state) { return state.y == GamePad::ButtonStateTracker::PRESSED; }); if (switchUserPressed) { m_sample->GetGameScreenManager()->SignInPrimaryUserWithUI(); } } void GameScreenTitle::Render() { switch (m_titleState) { case GameScreenTitle::TitleState::SignIn: //There is no additional rendering necessary for the SignIn screen other than the UITK layout break; case GameScreenTitle::TitleState::MenuWithUser: case GameScreenTitle::TitleState::MenuWithoutUser: RenderMenu(); break; case GameScreenTitle::TitleState::NoUserWarning: RenderNoUserWarning(); break; default: break; }; } void GameScreenTitle::RenderNoUserWarning() { //Change the styles of button subelements when the button is focused. //Currently there are issues transfering focus between screens in the UITK so focus and //style changes are being adjusted 'manually' in this sample but I hope to update this soon //with fixes to rely on more UITK functionality. std::shared_ptr<UIButton> buttonList[] = { m_warningSignInButton, m_warningContinueButton }; auto warningButtonsListLength = _countof(buttonList); for (unsigned int i = 0; i < warningButtonsListLength; i++) { if (buttonList[i] == m_warningSelectedOption) { buttonList[i]->SetStyleId(ID("button_focused_style")); buttonList[i]->GetSubElementById(ID("button_border"))->SetVisible(true); buttonList[i]->GetSubElementById(ID("button_label"))->SetStyleId(ID("button_focused_text_style")); } else { buttonList[i]->SetStyleId(ID("button_default_style")); buttonList[i]->GetSubElementById(ID("button_border"))->SetVisible(false); buttonList[i]->GetSubElementById(ID("button_label"))->SetStyleId(ID("button_default_text_style")); } } } void GameScreenTitle::RenderMenu() { m_sample->GetGameScreenManager()->GetDevicesView()->Render(); std::shared_ptr<UIButton> buttonList[] = { m_menuSingleUserButton, m_menuMultipleUserButton, m_menuRestartButton }; auto menuButtonsListLength = _countof(buttonList); for (unsigned int i = 0; i < menuButtonsListLength; i++) { if (buttonList[i] == m_menuSelectedOption) { buttonList[i]->SetStyleId(ID("button_focused_style")); buttonList[i]->GetSubElementById(ID("button_border"))->SetVisible(true); buttonList[i]->GetSubElementById(ID("button_label"))->SetStyleId(ID("button_focused_text_style")); } else { buttonList[i]->SetStyleId(ID("button_default_style")); buttonList[i]->GetSubElementById(ID("button_border"))->SetVisible(false); buttonList[i]->GetSubElementById(ID("button_label"))->SetStyleId(ID("button_default_text_style")); } } if (m_sample->GetGameScreenManager()->HavePrimaryUser() == false) { m_menuMultipleUserButton->SetStyleId(ID("button_disabled_style")); m_menuMultipleUserButton->GetSubElementById(ID("button_label"))->SetStyleId(ID("button_disabled_text_style")); } m_restartDescriptionText->SetVisible(m_menuRestartButton == m_menuSelectedOption); } void GameScreenTitle::NotifySignInResult(HRESULT result, XUserHandle /*newUserHandle*/, bool primaryUser, bool wasDefaultSignIn) { #ifdef _DEBUG assert(primaryUser); #else (void)primaryUser; #endif if (SUCCEEDED(result)) { SwitchTitleState(GameScreenTitle::TitleState::MenuWithUser); } else if (wasDefaultSignIn && result == E_GAMEUSER_NO_DEFAULT_USER) { // If default failed, just try again with the UI m_sample->GetGameScreenManager()->SignInPrimaryUserWithUI(); } else if(result == E_ABORT && m_titleState == GameScreenTitle::TitleState::SignIn) { SwitchTitleState(GameScreenTitle::TitleState::NoUserWarning); } else { char logBuffer[512] = {}; sprintf_s(logBuffer, 512, u8"GameScreenTitle::NotifySignInResult() : Failed to sign in with error hr=0x%08x\n", result); OutputDebugStringA(logBuffer); } } void GameScreenTitle::NotifySignedOut(XUserHandle userHandle) { if (m_sample->GetGameScreenManager()->GetPrimaryUserHandle() == userHandle) { SwitchTitleState(GameScreenTitle::TitleState::SignIn); } } void GameScreenTitle::NotifyGamerPicUpdated(XUserHandle userHandle) { auto gameScreenManager = m_sample->GetGameScreenManager(); if (gameScreenManager->GetPrimaryUserHandle() == userHandle) { UserData updatedUser; gameScreenManager->GetUserData(userHandle, &updatedUser); gameScreenManager->GetDevicesView()->SetGamerPic(updatedUser.m_gamerPic.data(), updatedUser.m_gamerPic.size()); } } void GameScreenTitle::NavigateToNextOption() { // Skip multi-user if no user is signed in if (m_menuSelectedOption == m_menuSingleUserButton && m_sample->GetGameScreenManager()->HavePrimaryUser()) { m_menuSelectedOption = m_menuMultipleUserButton; } else { m_menuSelectedOption = m_menuRestartButton; } } void GameScreenTitle::NavigateToPrevOption() { // Skip multi-user if no user is signed in if (m_menuSelectedOption == m_menuRestartButton && m_sample->GetGameScreenManager()->HavePrimaryUser()) { m_menuSelectedOption = m_menuMultipleUserButton; } else { m_menuSelectedOption = m_menuSingleUserButton; } } void GameScreenTitle::SelectCurrentOption() { if (m_menuSelectedOption == m_menuSingleUserButton) { HandleSingleUser(); } else if (m_menuSelectedOption == m_menuMultipleUserButton) { HandleMultiUser(); } else { HandleCrossRestart(); } } void GameScreenTitle::SwitchTitleState(TitleState newState) { m_titleState = newState; switch (m_titleState) { case GameScreenTitle::TitleState::SignIn: m_screen->SetVisible(true); m_screen->SetEnabled(true); m_warningScreen->SetVisible(false); m_warningScreen->SetEnabled(false); m_menuScreen->SetVisible(false); m_menuScreen->SetEnabled(false); m_sample->GetGameScreenManager()->GetDevicesView()->SetVisible(false); break; case GameScreenTitle::TitleState::MenuWithUser: case GameScreenTitle::TitleState::MenuWithoutUser: m_screen->SetVisible(false); m_screen->SetEnabled(false); m_warningScreen->SetVisible(false); m_warningScreen->SetEnabled(false); m_menuScreen->SetVisible(true); m_menuScreen->SetEnabled(true); m_sample->GetGameScreenManager()->GetDevicesView()->SetVisible(true); break; case GameScreenTitle::TitleState::NoUserWarning: m_warningScreen->SetVisible(true); m_warningScreen->SetEnabled(true); m_screen->SetVisible(true); m_screen->SetEnabled(false); m_menuScreen->SetVisible(false); m_menuScreen->SetEnabled(false); m_sample->GetGameScreenManager()->GetDevicesView()->SetVisible(false); break; default: break; }; } void GameScreenTitle::HandleSingleUser() { m_sample->GetGameScreenManager()->GoToScreen(EGS_SingleUser); } void GameScreenTitle::HandleMultiUser() { if (m_sample->GetGameScreenManager()->HavePrimaryUser()) { m_sample->GetGameScreenManager()->GoToScreen(EGS_MultiUser); } } void GameScreenTitle::HandleCrossRestart() { // For games that have a launcher or need to restart for special circumstances, XLaunchNewGame() can be used with a specified user and // arguments to support this scenario. This sample shows of that functionality by restarting the current title with the specified user // as the default user. Then, the restart will transition directly to the single user screen. m_sample->GetGameUserManager()->SignInUser( [&](HRESULT result, XUserHandle newUser) { if (FAILED(result)) { return; } // The debugger will disconnect here as the current process is ending and a new one is spawned XLaunchNewGame(u8"UserManagement.exe", u8"-crossrestart", newUser); }, false); } #pragma endregion #pragma region User View UserView::UserView(Sample* sample, UIElementPtr userPrefab) : m_sample(sample) , m_userPrefab(userPrefab) { m_userPanel = m_userPrefab->GetSubElementById(ID("have_user_panel")); m_noUserText = m_userPrefab->GetTypedSubElementById<UIStaticText>(ID("no_user_text")); m_inputButton = m_userPanel->GetTypedSubElementById<UIButton>(ID("button_input")); m_inputGlyphs = m_userPanel->GetTypedSubElementById<UIStaticText>(ID("active_button_label")); m_leaveButton = m_userPanel->GetTypedSubElementById<UIButton>(ID("leave_button")); m_deferralButton = m_userPanel->GetTypedSubElementById<UIButton>(ID("deferral_checkbox_button")); m_deferralCheckbox = m_deferralButton->GetSubElementById(ID("deferral_panel"))->GetTypedSubElementById<UICheckBox>(ID("deferral_toggle")); m_deferralActiveText = m_userPanel->GetTypedSubElementById<UIStaticText>(ID("deferral_active_text")); m_userSelectedButton = m_inputButton; } UserView::~UserView() { } bool UserView::LeavePressed(std::vector<APP_LOCAL_DEVICE_ID> devices) { if (m_userSelectedButton == m_leaveButton) { return m_sample->GetGameInputCollection()->CheckInput(devices, [](const DirectX::GamePad::ButtonStateTracker& state) { return state.a == GamePad::ButtonStateTracker::PRESSED; }); } return false; } bool UserView::DeferralPressed(std::vector<APP_LOCAL_DEVICE_ID> devices) { if (m_userSelectedButton == m_deferralButton) { return m_sample->GetGameInputCollection()->CheckInput(devices, [](const DirectX::GamePad::ButtonStateTracker& state) { return state.a == GamePad::ButtonStateTracker::PRESSED; }); } return false; } void UserView::SetGamerPic(uint8_t* gamerpicData, size_t gamerpicSize) { auto gamerpicImage = m_userPanel->GetTypedSubElementById<UIImage>(ID("profile_pic")); gamerpicImage->UseTextureData(gamerpicData, gamerpicSize); } void UserView::SetNoUserText(const char* newText) { m_noUserText->SetDisplayText(newText); } void UserView::SetPrimaryUser(bool isPrimaryUser) { //we make the primary user icon visible or invisible m_userPanel->GetSubElementById(ID("primary_image"))->SetVisible(isPrimaryUser); //and change the utton to either 'leave' or 'main menu' auto buttonText = m_leaveButton->GetTypedSubElementById<UIStaticText>(ID("button_label")); if (isPrimaryUser) { buttonText->SetDisplayText("Main Menu"); } else { buttonText->SetDisplayText("Leave"); } } void UserView::Update(std::vector<APP_LOCAL_DEVICE_ID> devices) { const bool downPressed = m_sample->GetGameInputCollection()->CheckInput(devices, [](const DirectX::GamePad::ButtonStateTracker& state) { return state.dpadDown == GamePad::ButtonStateTracker::PRESSED; }); const bool upPressed = m_sample->GetGameInputCollection()->CheckInput(devices, [](const DirectX::GamePad::ButtonStateTracker& state) { return state.dpadUp == GamePad::ButtonStateTracker::PRESSED; }); if (upPressed) { if (m_userSelectedButton == m_deferralButton) { m_userSelectedButton = m_leaveButton; } else { m_userSelectedButton = m_inputButton; } } else if (downPressed) { if (m_userSelectedButton == m_inputButton) { m_userSelectedButton = m_leaveButton; } else { m_userSelectedButton = m_deferralButton; } } } void UserView::Render(XUserHandle user) { if (user) { auto gameScreenManager = m_sample->GetGameScreenManager(); UserData userData; gameScreenManager->GetUserData(user, &userData); m_userPanel->SetVisible(true); m_noUserText->SetVisible(false); //set user id char idText[2]; sprintf_s(idText, "%llu", userData.m_localId.value); m_userPanel->GetSubElementById(ID("user_id_panel"))->GetTypedSubElementById<UIStaticText>(ID("user_id_text"))->SetDisplayText(idText); //set gamertag m_userPanel->GetTypedSubElementById<UIStaticText>(ID("gamer_tag"))->SetDisplayText(userData.m_gamertag); auto userDevices = m_sample->GetGameUserManager()->GetUserDevices(user); if (userDevices.size() == 0) { m_inputGlyphs->SetDisplayText("No paired gamepads"); } else { //render input glyphs if (m_userSelectedButton == m_inputButton) { std::string userInputStr = gameScreenManager->GetUserCombinedInputString(user); m_inputGlyphs->SetDisplayText(userInputStr); } else { m_inputGlyphs->SetDisplayText(""); } } //render either the deferral checkbox or the active deferral amount remaining if (userData.m_signOutDeferralHandle) { m_deferralButton->SetVisible(false); m_deferralActiveText->SetVisible(true); char deferralText[32]; sprintf_s(deferralText, "Sign Out Deferral Active: %.0f", userData.m_signOutDeferralRemaining); m_deferralActiveText->SetDisplayText(deferralText); } else { m_deferralButton->SetVisible(true); m_deferralActiveText->SetVisible(false); } //loop through buttons and hilight or not std::shared_ptr<UIButton> buttonList[] = { m_inputButton, m_leaveButton, m_deferralButton }; auto buttonsListLength = _countof(buttonList); for (unsigned int i = 0; i < buttonsListLength; i++) { if (buttonList[i] == m_userSelectedButton) { buttonList[i]->SetStyleId(ID("button_focused_style")); buttonList[i]->GetSubElementById(ID("button_border"))->SetVisible(true); buttonList[i]->GetSubElementById(ID("button_label"))->SetStyleId(ID("button_focused_text_style")); } else { buttonList[i]->SetStyleId(ID("button_default_style")); buttonList[i]->GetSubElementById(ID("button_border"))->SetVisible(false); buttonList[i]->GetSubElementById(ID("button_label"))->SetStyleId(ID("button_default_text_style")); } } if (userData.m_requestDeferral) { m_deferralCheckbox->SetStyleId(ID("checked_checkbox_style")); } else { m_deferralCheckbox->SetStyleId(ID("unchecked_checkbox_style")); } } else { m_userPanel->SetVisible(false); m_noUserText->SetVisible(true); } } #pragma endregion #pragma region Devices View DevicesView::DevicesView(Sample* sample, UIElementPtr devicesPrefab) : m_sample(sample) , m_devicesPrefab(devicesPrefab) { m_primaryUserPanel = m_devicesPrefab->GetSubElementById(ID("primary_user_panel")); m_gamertag = m_primaryUserPanel->GetTypedSubElementById<UIStaticText>(ID("primary_user_name")); m_devicesListPanel = m_devicesPrefab->GetSubElementById(ID("devices_list")); char device[8]; for (int i = 0; i < deviceListSize; i++) { sprintf_s(device, "device%d", i); m_devicesList[i] = m_devicesListPanel->GetSubElementById(ID(device)); } } DevicesView::~DevicesView() { } void DevicesView::SetGamerPic(uint8_t* gamerpicData, size_t gamerpicSize) { auto gamerpicImage = m_primaryUserPanel->GetTypedSubElementById<UIImage>(ID("primary_user_picture")); gamerpicImage->UseTextureData(gamerpicData, gamerpicSize); } void DevicesView::SetVisible(bool isVisible) { m_devicesPrefab->SetVisible(isVisible); } void DevicesView::Render() { auto gameScreenManager = m_sample->GetGameScreenManager(); const bool havePrimaryUser = gameScreenManager->HavePrimaryUser(); auto gameUserManager = m_sample->GetGameUserManager(); if (havePrimaryUser) { UserData userData; m_primaryUserPanel->SetVisible(true); gameScreenManager->GetUserData(gameScreenManager->GetPrimaryUserIndex(), &userData); m_gamertag->SetDisplayText(userData.m_gamertag); } else { m_primaryUserPanel->SetVisible(false); } int deviceIndex = 0; auto users = gameUserManager->GetUsers(); for (auto user : users) { UserData userData; gameScreenManager->GetUserData(user, &userData); auto userDevices = gameUserManager->GetUserDevices(user); for (auto device : userDevices) { if (deviceIndex < deviceListSize) { m_devicesList[deviceIndex]->SetVisible(true); //set user id auto userIdPanel = m_devicesList[deviceIndex]->GetSubElementById(ID("user_id_panel")); userIdPanel->SetVisible(true); char userIdText[2]; sprintf_s(userIdText, "%llu", userData.m_localId.value); auto userIdUIText = userIdPanel->GetTypedSubElementById<UIStaticText>(ID("user_id_text")); userIdUIText->SetDisplayText(userIdText); //set the device id auto deviceIdText = m_devicesList[deviceIndex]->GetTypedSubElementById<UIStaticText>(ID("device_id_text")); deviceIdText->SetDisplayText(gameScreenManager->GetInputDeviceIdString(device, true)); //set the current input glyphs for this device auto deviceGlyphsText = m_devicesList[deviceIndex]->GetTypedSubElementById<UIStaticText>(ID("input_glyphs_text")); deviceGlyphsText->SetDisplayText(gameScreenManager->GetInputDeviceGlyphsString(device)); deviceIndex++; } } } auto unpairedDevices = gameScreenManager->GetUnpairedDevices(); for (auto unpairedDevice : unpairedDevices) { if (deviceIndex < deviceListSize) { m_devicesList[deviceIndex]->SetVisible(true); //make the userid invisible auto userIdPanel = m_devicesList[deviceIndex]->GetSubElementById(ID("user_id_panel")); userIdPanel->SetVisible(false); //set the device id auto deviceIdText = m_devicesList[deviceIndex]->GetTypedSubElementById<UIStaticText>(ID("device_id_text")); deviceIdText->SetDisplayText(gameScreenManager->GetInputDeviceIdString(unpairedDevice, true)); //set the current input glyphs for this device auto deviceGlyphsText = m_devicesList[deviceIndex]->GetTypedSubElementById<UIStaticText>(ID("input_glyphs_text")); deviceGlyphsText->SetDisplayText(gameScreenManager->GetInputDeviceGlyphsString(unpairedDevice)); deviceIndex++; } } //if no gamepads are connected let the user know if (deviceIndex == 0) { auto userIdPanel = m_devicesList[deviceIndex]->GetSubElementById(ID("user_id_panel")); userIdPanel->SetVisible(false); auto deviceIdText = m_devicesList[deviceIndex]->GetTypedSubElementById<UIStaticText>(ID("device_id_text")); deviceIdText->SetDisplayText("No Gamepads Connected"); deviceIndex++; } for (; deviceIndex < deviceListSize; deviceIndex++) { m_devicesList[deviceIndex]->SetVisible(false); } } #pragma endregion #pragma region Game Screen - Single User GameScreenSingleUser::GameScreenSingleUser(Sample* sample, UIManager* uiManager) : GameScreen(sample, uiManager) , m_state(SingleUserState::Main) { m_screen = m_uiManager->LoadLayoutFromFile("Assets/Layouts/singleuser-screen.json"); m_uiManager->AttachTo(m_screen, m_uiManager->GetRootElement()); m_screen->SetVisible(false); m_playerScreen = std::make_unique<UserView>(sample, m_screen->GetSubElementById(ID("users"))->GetSubElementById(ID("user1"))); //in the single user case the user is always the primary user m_playerScreen->SetPrimaryUser(true); m_navigateLegend = m_screen->GetSubElementById(ID("navigate_legend"),true); m_selectLegend = m_screen->GetSubElementById(ID("select_legend"),true); m_unpairedGamepadLegend = m_screen->GetSubElementById(ID("unpaired_legend"), true); m_noUserPanel = m_screen->GetSubElementById(ID("no_user_panel"), true); } GameScreenSingleUser::~GameScreenSingleUser() { } void GameScreenSingleUser::Initialize() { // Always enter into the main state m_state = GameScreenSingleUser::SingleUserState::Main; m_screen->SetVisible(true); auto gameScreenManager = m_sample->GetGameScreenManager(); if (gameScreenManager->HavePrimaryUser()) { UserData primaryUser; gameScreenManager->GetUserData(gameScreenManager->GetPrimaryUserIndex(), &primaryUser); m_playerScreen->SetGamerPic(primaryUser.m_gamerPic.data(), primaryUser.m_gamerPic.size()); } } void GameScreenSingleUser::Cleanup() { m_screen->SetVisible(false); } void GameScreenSingleUser::Update(double /*dt*/) { switch (m_state) { case GameScreenSingleUser::SingleUserState::Main: UpdateMain(); break; case GameScreenSingleUser::SingleUserState::PromptForNewUser: UpdateNewUserPrompt(); break; case GameScreenSingleUser::SingleUserState::PromptForUserChange: UpdateUserChangePrompt(); break; default: break; }; } void GameScreenSingleUser::UpdateMain() { auto gameScreenManager = m_sample->GetGameScreenManager(); auto gameUserManager = m_sample->GetGameUserManager(); std::vector<APP_LOCAL_DEVICE_ID> userDevices; auto user = gameScreenManager->GetPrimaryUserHandle(); if (user) { userDevices = gameUserManager->GetUserDevices(user); // Check if we need to sign in an unpaired gamepad if (userDevices.size() == 0) { const bool signIn = m_sample->GetGameInputCollection()->CheckInputAllDevices( [](const DirectX::GamePad::ButtonStateTracker& state) { return state.a == GamePad::ButtonStateTracker::PRESSED; }); if (signIn) { // Start an extra sign-in. If it ends up being a new user, the notification function will handle it. // If it's the same user (which is what we're hoping for), then it will just return the already-existing // primary user. gameScreenManager->SignInExtraUserWithUI(false); } } else { m_playerScreen->Update(userDevices); if (m_playerScreen->LeavePressed(userDevices)) { gameScreenManager->GoToScreen(EGS_Title); } if (m_playerScreen->DeferralPressed(userDevices)) { gameScreenManager->ToggleDeferralRequest(gameScreenManager->GetPrimaryUserHandle()); } } } else { //If we enter 'gameplay' without a user just display device input //and let the user return to the main menu const bool returnToMenu = m_sample->GetGameInputCollection()->CheckInputAllDevices( [](const DirectX::GamePad::ButtonStateTracker& state) { return state.b == GamePad::ButtonStateTracker::PRESSED; }); if (returnToMenu) { gameScreenManager->GoToScreen(EGS_Title); } } } void GameScreenSingleUser::UpdateNewUserPrompt() { const bool returnToTitle = m_sample->GetGameInputCollection()->CheckInputAllDevices( [](const DirectX::GamePad::ButtonStateTracker& state) { return state.b == GamePad::ButtonStateTracker::PRESSED; }); if (returnToTitle) { m_sample->GetGameScreenManager()->GoToScreen(EGS_Title); return; } const bool signIn = m_sample->GetGameInputCollection()->CheckInputAllDevices( [](const DirectX::GamePad::ButtonStateTracker& state) { return state.a == GamePad::ButtonStateTracker::PRESSED; }); if (signIn) { assert(!m_sample->GetGameScreenManager()->HavePrimaryUser()); m_sample->GetGameScreenManager()->SignInPrimaryUserWithUI(); } } void GameScreenSingleUser::UpdateUserChangePrompt() { auto gameScreenManager = m_sample->GetGameScreenManager(); const bool switchPrimaryUser = m_sample->GetGameInputCollection()->CheckInputAllDevices( [](const DirectX::GamePad::ButtonStateTracker& state) { return state.a == GamePad::ButtonStateTracker::PRESSED; }); const bool cancelPrimaryUserChange = m_sample->GetGameInputCollection()->CheckInputAllDevices( [](const DirectX::GamePad::ButtonStateTracker& state) { return state.b == GamePad::ButtonStateTracker::PRESSED; }); if (switchPrimaryUser) { XUserHandle oldPrimaryUserHandle = gameScreenManager->GetPrimaryUserHandle(); gameScreenManager->MakeUserPrimary(m_cachedUserData.m_userHandle); gameScreenManager->SignOutUser(oldPrimaryUserHandle); m_state = GameScreenSingleUser::SingleUserState::Main; } else if (cancelPrimaryUserChange) { gameScreenManager->SignOutUser(m_cachedUserData.m_userHandle); m_state = GameScreenSingleUser::SingleUserState::Main; } } void GameScreenSingleUser::Render() { switch (m_state) { case GameScreenSingleUser::SingleUserState::Main: RenderMain(); break; case GameScreenSingleUser::SingleUserState::PromptForNewUser: RenderNewUserPrompt(); break; case GameScreenSingleUser::SingleUserState::PromptForUserChange: RenderUserChangePrompt(); break; default: break; }; } void GameScreenSingleUser::RenderMain() { XUserHandle primaryUser = m_sample->GetGameScreenManager()->GetPrimaryUserHandle(); if (!primaryUser) { m_playerScreen->SetNoUserText(" No User Signed In. \n Press [B] to Return to Title"); m_navigateLegend->SetVisible(false); m_selectLegend->SetVisible(false); m_noUserPanel->SetVisible(true); m_unpairedGamepadLegend->SetVisible(false); } else { m_navigateLegend->SetVisible(true); m_noUserPanel->SetVisible(false); //if the user does not have any paired devices show the legend for pairing a device auto userDevices = m_sample->GetGameUserManager()->GetUserDevices(primaryUser); m_selectLegend->SetVisible(userDevices.size() != 0); m_unpairedGamepadLegend->SetVisible(userDevices.size() == 0); } m_playerScreen->Render(primaryUser); m_sample->GetGameScreenManager()->GetDevicesView()->Render(); } void GameScreenSingleUser::RenderNewUserPrompt() { char userString[512] = {}; sprintf_s(userString, 512, u8"%s is no longer signed in.\nSign in to continue?\n[A] Sign In [B] Return to Title", m_cachedUserData.m_gamertag); m_playerScreen->SetNoUserText(userString); m_playerScreen->Render(nullptr); m_noUserPanel->SetVisible(true); m_navigateLegend->SetVisible(false); m_selectLegend->SetVisible(false); m_sample->GetGameScreenManager()->GetDevicesView()->Render(); } void GameScreenSingleUser::RenderUserChangePrompt() { auto gameScreenManager = m_sample->GetGameScreenManager(); assert(gameScreenManager->HavePrimaryUser()); assert(gameScreenManager->HaveUser(m_cachedUserData.m_userHandle)); UserData newUserData; gameScreenManager->GetUserData(m_cachedUserData.m_userHandle, &newUserData); UserData primaryUserData; gameScreenManager->GetUserData(gameScreenManager->GetPrimaryUserIndex(), &primaryUserData); char userString[512] = {}; sprintf_s(userString, 512, u8"%s is currently signed in and the primary user.\n Sign in %s as the new primary user?\n [A] Switch Primary User [B] Cancel Sign In", primaryUserData.m_gamertag, newUserData.m_gamertag); m_playerScreen->SetNoUserText(userString); m_playerScreen->Render(nullptr); m_noUserPanel->SetVisible(true); m_navigateLegend->SetVisible(false); m_selectLegend->SetVisible(false); m_sample->GetGameScreenManager()->GetDevicesView()->Render(); } void GameScreenSingleUser::NotifySignInResult(HRESULT result, XUserHandle newUserHandle, bool primaryUser, bool /*wasDefaultSignIn*/) { #ifndef _DEBUG (void)primaryUser; #endif if (FAILED(result)) { return; } if (m_state == GameScreenSingleUser::SingleUserState::PromptForNewUser) { assert(primaryUser); // No need to do any fixup since the new user is automatically the primary user m_state = GameScreenSingleUser::SingleUserState::Main; } else if (m_state == GameScreenSingleUser::SingleUserState::Main) { // If here, then the user tried to sign-in from the main screen due to controller needing to be paired assert(!primaryUser); if (newUserHandle != m_sample->GetGameScreenManager()->GetPrimaryUserHandle()) { // User tried to change users instead of just repair a new controller to the current user. // Change state to get a confirm/cancel from the user for this user change first. m_cachedUserData = UserData(); m_cachedUserData.m_userHandle = newUserHandle; m_state = GameScreenSingleUser::SingleUserState::PromptForUserChange; } } } void GameScreenSingleUser::NotifySignedOut(XUserHandle userHandle) { // Should be impossible to get a signout in this state since no user should be signed in assert(m_state != GameScreenSingleUser::SingleUserState::PromptForNewUser); auto gameScreenManager = m_sample->GetGameScreenManager(); // If currently checking to see if the user intended to do a user switch when pairing a new gamepad and a user is signed out, // then the user intent is too difficult to discern and the sample will just kick to the title. if (m_state == GameScreenSingleUser::SingleUserState::PromptForUserChange) { gameScreenManager->SignOutAllUsers(); gameScreenManager->GoToScreen(EGS_Title); return; } if (gameScreenManager->GetPrimaryUserHandle() == userHandle) { // XR-115 says that the title should either remove the player from the game and ensure good title state, or establish a new user. // To demonstrate both functionalities, the title will prompts for one or the other // Cache data as the primary user will be lost after this function returns gameScreenManager->GetUserData(m_sample->GetGameScreenManager()->GetPrimaryUserIndex(), &m_cachedUserData); // Switch state to the prompt m_state = GameScreenSingleUser::SingleUserState::PromptForNewUser; } } void GameScreenSingleUser::NotifyGamerPicUpdated(XUserHandle userHandle) { auto gameScreenManager = m_sample->GetGameScreenManager(); if (gameScreenManager->GetPrimaryUserHandle() == userHandle) { UserData updatedUser; gameScreenManager->GetUserData(userHandle, &updatedUser); m_playerScreen->SetGamerPic(updatedUser.m_gamerPic.data(), updatedUser.m_gamerPic.size()); gameScreenManager->GetDevicesView()->SetGamerPic(updatedUser.m_gamerPic.data(), updatedUser.m_gamerPic.size()); } } #pragma endregion #pragma region Game Screen - Multi User GameScreenMultiUser::GameScreenMultiUser(Sample* sample, UIManager* uiManager) : GameScreen(sample, uiManager) , m_signingIn(false) { m_screen = m_uiManager->LoadLayoutFromFile("Assets/Layouts/multiuser-screen.json"); m_uiManager->AttachTo(m_screen, m_uiManager->GetRootElement()); m_screen->SetVisible(false); m_playerScreens[0] = std::make_unique<UserView>(sample, m_screen->GetSubElementById(ID("user1"))); m_playerScreens[1] = std::make_unique<UserView>(sample, m_screen->GetSubElementById(ID("user2"))); m_playerScreens[2] = std::make_unique<UserView>(sample, m_screen->GetSubElementById(ID("user3"))); m_playerScreens[3] = std::make_unique<UserView>(sample, m_screen->GetSubElementById(ID("user4"))); //The primary user will always be displayed in the top left spot m_playerScreens[0]->SetPrimaryUser(true); } GameScreenMultiUser::~GameScreenMultiUser() { } void GameScreenMultiUser::Initialize() { // Upon entering the multi-user screen, we should be guaranteed to have a primary user only assert(m_sample->GetGameUserManager()->NumUsers() == 1); m_screen->SetVisible(true); auto gameScreenManager = m_sample->GetGameScreenManager(); UserData primaryUser; gameScreenManager->GetUserData(gameScreenManager->GetPrimaryUserIndex(), &primaryUser); m_playerScreens[0]->SetGamerPic(primaryUser.m_gamerPic.data(), primaryUser.m_gamerPic.size()); } void GameScreenMultiUser::Cleanup() { assert(!m_signingIn); // Sign out any signed-in extra users (not the primary user) for (unsigned int userIndex = 1; userIndex < m_sample->GetGameScreenManager()->s_maxUsers; ++userIndex) { m_sample->GetGameScreenManager()->SignOutUser(userIndex); } m_screen->SetVisible(false); } void GameScreenMultiUser::Update(double /*dt*/) { auto gameScreenManager = m_sample->GetGameScreenManager(); // Check for new sign-ins. This should be allowed if we're not at max users, or if a signed-in user doesn't have a paired gamepad bool userHasNoGamepads = false; for (unsigned int userIndex = 0; userIndex < gameScreenManager->s_maxUsers; ++userIndex) { if (gameScreenManager->HaveUser(userIndex) && m_sample->GetGameUserManager()->GetUserDevices(gameScreenManager->GetUserHandle(userIndex)).size() == 0) { userHasNoGamepads = true; break; } } if (!m_signingIn && (gameScreenManager->GetUserCount() < gameScreenManager->s_maxUsers || userHasNoGamepads)) { const bool startNewSignIn = m_sample->GetGameInputCollection()->CheckInput(gameScreenManager->GetUnpairedDevices(), [](const DirectX::GamePad::ButtonStateTracker& state) { return state.a == GamePad::ButtonStateTracker::PRESSED; }); if (startNewSignIn) { m_signingIn = gameScreenManager->SignInExtraUserWithUI(true); } } // Update each user looking for selection, signouts, and deferral changes for (unsigned int userIndex = 0; userIndex < gameScreenManager->s_maxUsers; ++userIndex) { if (!gameScreenManager->HaveUser(userIndex)) { continue; } auto userDevices = m_sample->GetGameUserManager()->GetUserDevices(gameScreenManager->GetUserHandle(userIndex)); m_playerScreens[userIndex]->Update(userDevices); if (m_playerScreens[userIndex]->LeavePressed(userDevices)) { if (userIndex == gameScreenManager->GetPrimaryUserIndex()) { m_sample->GetGameScreenManager()->GoToScreen(EGS_Title); } else { gameScreenManager->SignOutUser(userIndex); } } if (m_playerScreens[userIndex]->DeferralPressed(userDevices)) { gameScreenManager->ToggleDeferralRequest(gameScreenManager->GetUserHandle(userIndex)); } } } void GameScreenMultiUser::Render() { auto gameScreenManager = m_sample->GetGameScreenManager(); for (unsigned int userIndex = 0; userIndex < gameScreenManager->s_maxUsers; ++userIndex) { m_playerScreens[userIndex]->Render(gameScreenManager->GetUserHandle(userIndex)); } m_sample->GetGameScreenManager()->GetDevicesView()->Render(); } void GameScreenMultiUser::NotifySignInResult(HRESULT /*result*/, XUserHandle /*newUserHandle*/, bool /*primaryUser*/, bool /*wasDefaultSignIn*/) { m_signingIn = false; } void GameScreenMultiUser::NotifySignedOut(XUserHandle userHandle) { if (m_sample->GetGameScreenManager()->GetPrimaryUserHandle() == userHandle) { // XR-115 says that the title should either remove the player from the game and ensure good title state, or establish a new user. // In a multi-player experience, it is the best practice to allow other signed-in users to continue playing. For our case however, // we will just return to the title in the case that the primary user is removed as that is still compliant. See the single-player // screen to see another way of handling the user being lost m_sample->GetGameScreenManager()->GoToScreen(EGS_Title); } } void GameScreenMultiUser::NotifyGamerPicUpdated(XUserHandle userHandle) { auto gameScreenManager = m_sample->GetGameScreenManager(); unsigned int userIndex; if (gameScreenManager->GetUserIndex(userHandle, &userIndex)) { UserData data; gameScreenManager->GetUserData(userIndex, &data); m_playerScreens[userIndex]->SetGamerPic(data.m_gamerPic.data(), data.m_gamerPic.size()); } if (gameScreenManager->GetPrimaryUserHandle() == userHandle) { UserData updatedUser; gameScreenManager->GetUserData(userHandle, &updatedUser); gameScreenManager->GetDevicesView()->SetGamerPic(updatedUser.m_gamerPic.data(), updatedUser.m_gamerPic.size()); } } #pragma endregion #pragma region Game Screen Manager GameScreenManager::GameScreenManager(Sample* sample, UIManager* uiManager) : m_sample(sample) , m_currentGameScreen(EGS_Title) , m_pendingGameScreen(-1) , m_userEventCallbackHandle(0) { // Register callback for data changes m_userEventCallbackHandle = m_sample->GetGameUserManager()->RegisterUserEventCallback(&UserEventCallback, this); // Create the game screens m_gameScreens[EGS_Title] = std::make_unique<GameScreenTitle>(sample, uiManager); m_gameScreens[EGS_SingleUser] = std::make_unique<GameScreenSingleUser>(sample, uiManager); m_gameScreens[EGS_MultiUser] = std::make_unique<GameScreenMultiUser>(sample, uiManager); //all of the game screens need access to a single devices view auto devicesScreen = uiManager->LoadLayoutFromFile("Assets/Layouts/devices-panel.json"); uiManager->AttachTo(devicesScreen, uiManager->GetRootElement()); devicesScreen->SetVisible(false); m_devicesView = std::make_unique<DevicesView>(sample, devicesScreen); // Initialize the title screen GetCurrentGameScreen()->Initialize(); } GameScreenManager::~GameScreenManager() { } void GameScreenManager::Update(double dt) { // Update deferral for each user UpdateSignOutDeferral(dt); GetCurrentGameScreen()->Update(dt); // Update any game screen change if (m_pendingGameScreen >= 0) { assert(m_pendingGameScreen >= EGS_Title && m_pendingGameScreen < EGS_Count); GetCurrentGameScreen()->Cleanup(); m_currentGameScreen = m_pendingGameScreen; m_pendingGameScreen = -1; GetCurrentGameScreen()->Initialize(); } } void GameScreenManager::Render() { GetCurrentGameScreen()->Render(); } void GameScreenManager::OnSuspend() { // If there are any pending gamerpic requests, cancel them. If they fail from the suspend, they won't be useful. // If they succeed during the suspend, it will use rendering commands between SuspendX()/ResumeX() which isn't allowed. for (unsigned int userIndex = 0; userIndex < s_maxUsers; ++userIndex) { if (HaveUser(userIndex) && m_userData[userIndex].m_gamerpicAsyncInProgress) { m_sample->GetGameUserManager()->CancelGamerPicRequest(m_userData[userIndex].m_gamerpicAsyncHandle); m_userData[userIndex].m_gamerpicAsyncInProgress = false; m_userData[userIndex].m_gamerpicUploaded = false; } } } void GameScreenManager::OnResume() { // Re-start a gamerpic request on resume if the gamerpic isn't uploaded for (unsigned int userIndex = 0; userIndex < s_maxUsers; ++userIndex) { if (HaveUser(userIndex) && !m_userData[userIndex].m_gamerpicUploaded) { UpdateGamerPic(userIndex); } } } GameScreen* GameScreenManager::GetCurrentGameScreen() const { return m_gameScreens[m_currentGameScreen].get(); } void GameScreenManager::GoToScreen(EGameScreen screen) { assert(screen >= EGS_Title && screen < EGS_Count); if (screen == m_currentGameScreen) { return; } m_pendingGameScreen = screen; } DevicesView* GameScreenManager::GetDevicesView() { return m_devicesView.get(); } void GameScreenManager::HandleCrossRestart() { TryDefaultPrimaryUserSignIn(true); } void GameScreenManager::ToggleDeferralRequest(XUserHandle userHandle) { unsigned int userIndex = 0; GetUserIndex(userHandle, &userIndex); m_userData[userIndex].m_requestDeferral = !m_userData[userIndex].m_requestDeferral; } void GameScreenManager::TryDefaultPrimaryUserSignIn(bool autoTransitionToSinglePlayer) { if (HavePrimaryUser()) { return; } m_sample->GetGameUserManager()->SignInDefaultUser( [&, autoTransitionToSinglePlayer](HRESULT result, XUserHandle newUser) { if (SUCCEEDED(result)) { assert(!HavePrimaryUser()); InitUserData(newUser, true); if (autoTransitionToSinglePlayer) { m_devicesView->SetVisible(true); GoToScreen(EGS_SingleUser); } else { GetCurrentGameScreen()->NotifySignInResult(result, newUser, true, true); } } else { GetCurrentGameScreen()->NotifySignInResult(result, newUser, true, true); } }); } bool GameScreenManager::SignInPrimaryUserWithUI() { // The primary user is always slot 0. Therefore, if a primary is already signed in, this will replace that user upon success return m_sample->GetGameUserManager()->SignInUser( [&](HRESULT result, XUserHandle newUser) { if (SUCCEEDED(result)) { // If user is already signed-in, then a device association would occur in a callback // and no user lists needs to be changed. if (!HavePrimaryUser() || GetPrimaryUserHandle() != newUser) { // If this is a new user, then adjust the lists of users if (HavePrimaryUser()) { SignOutUser(0u); } // The primary user should not already be an extra user // If the primary user is lost, then all extra users should be removed as well upon returning to main menu assert(!HaveUser(newUser)); InitUserData(newUser, true); } } // Regardless of success/fail, notify game screen of result GetCurrentGameScreen()->NotifySignInResult(result, newUser, true, false); }, false); } bool GameScreenManager::SignInExtraUserWithUI(bool allowGuests) { assert(HavePrimaryUser()); return m_sample->GetGameUserManager()->SignInUser( [&](HRESULT result, XUserHandle newUser) { if (SUCCEEDED(result)) { // For pairing purposes, this function can be run even when at max use count for the title. // However, if we try to sign in more than max, cancel the sign-in if (GetUserCount() == s_maxUsers && !HaveUser(newUser)) { // Since we're not initializing data for this game screen manager, the user manager needs to close the handle m_sample->GetGameUserManager()->SignOutUser(newUser); result = E_ABORT; } else { // If user is already signed-in, then a device association would occur in a callback // and no user lists needs to be changed. // If this is a new user, then adjust the lists of users if (!HaveUser(newUser)) { InitUserData(newUser, false); } } } // Regardless of success/fail, notify game screen of result GetCurrentGameScreen()->NotifySignInResult(result, newUser, false, false); }, allowGuests); } void GameScreenManager::SignOutUser(unsigned int userIndex) { if (!m_userData[userIndex].m_userHandle) { return; } if (m_userData[userIndex].m_gamerpicAsyncInProgress) { m_sample->GetGameUserManager()->CancelGamerPicRequest(m_userData[userIndex].m_gamerpicAsyncHandle); } if (m_userData[userIndex].m_signOutDeferralHandle) { XUserCloseSignOutDeferralHandle(m_userData[userIndex].m_signOutDeferralHandle); } m_sample->GetGameUserManager()->SignOutUser(m_userData[userIndex].m_userHandle); m_userData[userIndex] = UserData(); } void GameScreenManager::SignOutUser(XUserHandle userHandle) { unsigned int userIndex = 0; if (GetUserIndex(userHandle, &userIndex)) { SignOutUser(userIndex); } } void GameScreenManager::SignOutAllUsers() { for (unsigned int userIndex = 0; userIndex < s_maxUsers; ++userIndex) { SignOutUser(userIndex); } } void GameScreenManager::MakeUserPrimary(unsigned int userIndex) { if (userIndex == 0) { return; } UserData oldPrimaryUserData = m_userData[0]; m_userData[0] = m_userData[userIndex]; m_userData[userIndex] = oldPrimaryUserData; UpdateGamerPic(0); UpdateGamerPic(userIndex); } void GameScreenManager::MakeUserPrimary(XUserHandle userHandle) { unsigned int userIndex = 0; if (GetUserIndex(userHandle, &userIndex)) { MakeUserPrimary(userIndex); } } bool GameScreenManager::HaveUser(XUserHandle userHandle) const { unsigned int UserIndex = 0; return GetUserIndex(userHandle, &UserIndex); } bool GameScreenManager::HaveUser(unsigned int userIndex) const { return m_userData[userIndex].m_userHandle != nullptr; } bool GameScreenManager::HavePrimaryUser() const { return HaveUser(0u); } bool GameScreenManager::GetUserIndex(XUserHandle userHandle, unsigned int* outUserIndex) const { assert(outUserIndex); for (unsigned int userIndex = 0; userIndex < s_maxUsers; ++userIndex) { if (m_userData[userIndex].m_userHandle == userHandle) { (*outUserIndex) = userIndex; return true; } } return false; } unsigned int GameScreenManager::GetUserCount() const { unsigned int userCount = 0; for (unsigned int userIndex = 0; userIndex < s_maxUsers; ++userIndex) { if (HaveUser(userIndex)) { ++userCount; } } return userCount; } unsigned int GameScreenManager::GetPrimaryUserIndex() const { return 0; } XUserHandle GameScreenManager::GetPrimaryUserHandle() const { return m_userData[GetPrimaryUserIndex()].m_userHandle; } XUserHandle GameScreenManager::GetUserHandle(unsigned int userIndex) const { // User handle can be null if there is no user. Use HaveUser() to get a bool on whether user is valid or not. return m_userData[userIndex].m_userHandle; } bool GameScreenManager::GetUserData(XUserHandle userHandle, UserData* outUserData) const { assert(outUserData); unsigned int userIndex = 0; if (GetUserIndex(userHandle, &userIndex)) { return GetUserData(userIndex, outUserData); } return false; } bool GameScreenManager::GetUserData(unsigned int userIndex, UserData* outUserData) const { assert(outUserData); if (HaveUser(userIndex)) { (*outUserData) = m_userData[userIndex]; return true; } return false; } std::string GameScreenManager::GetUserCombinedInputString(XUserHandle userHandle) { std::string outString = ""; auto& devices = m_sample->GetGameUserManager()->GetUserDevices(userHandle); for (auto& deviceId : devices) { outString += GetInputDeviceGlyphsString(deviceId); } return outString; } std::string GameScreenManager::GetInputDeviceGlyphsString(const APP_LOCAL_DEVICE_ID& deviceId) { std::string outString; GamePad::ButtonStateTracker state; if (m_sample->GetGameInputCollection()->GetDeviceState(deviceId, &state)) { if (state.dpadUp == GamePad::ButtonStateTracker::HELD) { outString += u8"[DPad]Up"; } if (state.dpadDown == GamePad::ButtonStateTracker::HELD) { outString += u8"[DPad]Down"; } if (state.dpadRight == GamePad::ButtonStateTracker::HELD) { outString += u8"[DPad]Right"; } if (state.dpadLeft == GamePad::ButtonStateTracker::HELD) { outString += u8"[DPad]Left"; } if (state.a == GamePad::ButtonStateTracker::HELD) { outString += u8"[A]"; } if (state.b == GamePad::ButtonStateTracker::HELD) { outString += u8"[B]"; } if (state.x == GamePad::ButtonStateTracker::HELD) { outString += u8"[X]"; } if (state.y == GamePad::ButtonStateTracker::HELD) { outString += u8"[Y]"; } if (state.leftShoulder == GamePad::ButtonStateTracker::HELD) { outString += u8"[LB]"; } if (state.rightShoulder == GamePad::ButtonStateTracker::HELD) { outString += u8"[RB]"; } if (state.leftStick == GamePad::ButtonStateTracker::HELD) { outString += u8"[LThumb]"; } if (state.rightStick == GamePad::ButtonStateTracker::HELD) { outString += u8"[RThumb]"; } if (state.menu == GamePad::ButtonStateTracker::HELD) { outString += u8"[Menu]"; } if (state.view == GamePad::ButtonStateTracker::HELD) { outString += u8"[View]"; } } return outString; } std::string GameScreenManager::GetInputDeviceIdString(const APP_LOCAL_DEVICE_ID& deviceId, bool shortDeviceId) { char deviceIdStringBuffer[512] = {}; if (shortDeviceId) { sprintf_s(deviceIdStringBuffer, 512, u8"{%08x...%08x}", *reinterpret_cast<const unsigned int*>(&deviceId.value[0]), *reinterpret_cast<const unsigned int*>(&deviceId.value[28]) ); } else { sprintf_s(deviceIdStringBuffer, 512, u8"DeviceId {%08x-%08x-%08x-%08x-%08x-%08x-%08x-%08x}", *reinterpret_cast<const unsigned int*>(&deviceId.value[0]), *reinterpret_cast<const unsigned int*>(&deviceId.value[4]), *reinterpret_cast<const unsigned int*>(&deviceId.value[8]), *reinterpret_cast<const unsigned int*>(&deviceId.value[12]), *reinterpret_cast<const unsigned int*>(&deviceId.value[16]), *reinterpret_cast<const unsigned int*>(&deviceId.value[20]), *reinterpret_cast<const unsigned int*>(&deviceId.value[24]), *reinterpret_cast<const unsigned int*>(&deviceId.value[28]) ); } return std::string(deviceIdStringBuffer); } std::vector<APP_LOCAL_DEVICE_ID> GameScreenManager::GetUnpairedDevices(std::vector<XUserHandle> knownUsers) const { std::vector<APP_LOCAL_DEVICE_ID> outDevices = m_sample->GetGameInputCollection()->GetAllDevices(); for (unsigned int userIndex = 0; userIndex < knownUsers.size(); ++userIndex) { if (!knownUsers[userIndex]) { continue; } // Remove all paired devices as reported by users std::vector<APP_LOCAL_DEVICE_ID> userDevices = m_sample->GetGameUserManager()->GetUserDevices(knownUsers[userIndex]); for (unsigned int userDeviceIndex = 0; userDeviceIndex < userDevices.size(); ++userDeviceIndex) { for (unsigned int outDeviceIndex = 0; outDeviceIndex < outDevices.size(); ++outDeviceIndex) { // If the user device was found, remove it if (userDevices[userDeviceIndex] == outDevices[outDeviceIndex]) { outDevices.erase(outDevices.begin() + outDeviceIndex); break; } } } } return outDevices; } std::vector<APP_LOCAL_DEVICE_ID> GameScreenManager::GetUnpairedDevices() const { std::vector<XUserHandle> knownUsers; for (unsigned int userIndex = 0; userIndex < s_maxUsers; ++userIndex) { if (m_userData[userIndex].m_userHandle) { knownUsers.push_back(m_userData[userIndex].m_userHandle); } } return GetUnpairedDevices(knownUsers); } void GameScreenManager::InitUserData(XUserHandle m_newUserHandle, bool primaryUser) { #ifdef _DEBUG assert(GetUserCount() < s_maxUsers); if (primaryUser) { assert(HavePrimaryUser() == false); } #endif // Primary user should always go in slot 0. // Extra users should go in 1+ arbitrarily. unsigned int userIndex = primaryUser ? 0u : 1u; unsigned int maxUsersToCheck = primaryUser ? 1u : s_maxUsers; for (; userIndex < maxUsersToCheck; ++userIndex) { if (!m_userData[userIndex].m_userHandle) { m_userData[userIndex].m_userHandle = m_newUserHandle; DX::ThrowIfFailed(XUserGetLocalId(m_userData[userIndex].m_userHandle, &m_userData[userIndex].m_localId)); DX::ThrowIfFailed(XUserGetIsGuest(m_userData[userIndex].m_userHandle, &m_userData[userIndex].m_guest)); size_t gamertagSize = 0; DX::ThrowIfFailed(XUserGetGamertag(m_userData[userIndex].m_userHandle, XUserGamertagComponent::UniqueModern, XUserGamertagComponentUniqueModernMaxBytes, m_userData[userIndex].m_gamertag, &gamertagSize)); UpdateGamerPic(userIndex); return; } } // Shouldn't ever happen throw std::exception(u8"GameScreenManager::InitUserData - Sample error"); } void GameScreenManager::UpdateGamerPic(unsigned int userIndex) { if (!HaveUser(userIndex) || m_userData[userIndex].m_gamerpicAsyncInProgress) { return; } m_userData[userIndex].m_gamerpicUploaded = false; // Start async request m_userData[userIndex].m_gamerpicAsyncInProgress = m_sample->GetGameUserManager()->GetGamerPicAsync(m_userData[userIndex].m_userHandle, XUserGamerPictureSize::Medium, [&](HRESULT result, XUserHandle userHandle, std::vector<uint8_t> gamerpicBuffer) { unsigned int userIndex = 0; if (!GetUserIndex(userHandle, &userIndex)) { return; } m_userData[userIndex].m_gamerpicAsyncInProgress = false; if (FAILED(result)) { char logBuffer[512] = {}; sprintf_s(logBuffer, 512, u8"GetGamerPicAsync Callback : Failed to get gamer pic for user %llu, Result = 0x%08x\n", m_userData[userIndex].m_localId.value, result); OutputDebugStringA(logBuffer); return; } //store the gamerpic so it can be set in the UI m_userData[userIndex].m_gamerPic = gamerpicBuffer; m_userData[userIndex].m_gamerpicUploaded = true; //Have the active screen update any gamerpics it is rendering GetCurrentGameScreen()->NotifyGamerPicUpdated(userHandle); }, &m_userData[userIndex].m_gamerpicAsyncHandle); } void GameScreenManager::UpdateSignOutDeferral(double dt) { for (unsigned int userIndex = 0; userIndex < s_maxUsers; ++userIndex) { if (HaveUser(userIndex) && m_userData[userIndex].m_signOutDeferralHandle) { m_userData[userIndex].m_signOutDeferralRemaining -= dt; if (m_userData[userIndex].m_signOutDeferralRemaining <= 0.0) { m_userData[userIndex].m_signOutDeferralRemaining = 0.0; XUserCloseSignOutDeferralHandle(m_userData[userIndex].m_signOutDeferralHandle); m_userData[userIndex].m_signOutDeferralHandle = nullptr; // Clear the gamerpic flag just do it doesn't chance to flicker before the final sign-out is triggered m_userData[userIndex].m_gamerpicUploaded = false; } } } } void GameScreenManager::UserEventCallback(void* context, XUserHandle userHandle, XUserChangeEvent event) { GameScreenManager* pThis = static_cast<GameScreenManager*>(context); unsigned int userIndex = 0; if (!pThis->GetUserIndex(userHandle, &userIndex)) { return; } if (event == XUserChangeEvent::Gamertag) { size_t gamertagSize = 0; DX::ThrowIfFailed(XUserGetGamertag(pThis->m_userData[userIndex].m_userHandle, XUserGamertagComponent::UniqueModern, XUserGamertagComponentUniqueModernMaxBytes, pThis->m_userData[userIndex].m_gamertag, &gamertagSize)); } else if (event == XUserChangeEvent::GamerPicture) { pThis->UpdateGamerPic(userIndex); } else if (event == XUserChangeEvent::SigningOut) { HRESULT hr = XUserGetSignOutDeferral(&pThis->m_userData[userIndex].m_signOutDeferralHandle); if (SUCCEEDED(hr)) { if (pThis->m_userData[userIndex].m_requestDeferral == false) { return; } //Maintain the deferral for 5 seconds to demonstrate pThis->m_userData[userIndex].m_signOutDeferralRemaining = 5.0; char stringBuf[256] = {}; sprintf_s(stringBuf, 256, u8"Deferring sign-out of user LocalId [%llu] for 5 seconds\n", pThis->m_userData[userIndex].m_localId.value); OutputDebugStringA(stringBuf); } else { char stringBuf[256] = {}; sprintf_s(stringBuf, 256, u8"Failed to get sign out deferral for user LocalId [%llu] with hr=0x%x\n", pThis->m_userData[userIndex].m_localId.value, hr ); OutputDebugStringA(stringBuf); } } else if (event == XUserChangeEvent::SignedOut) { // Notify current game screen before signing out in the manager so that the game screen can look up information it needs before it's lost pThis->GetCurrentGameScreen()->NotifySignedOut(userHandle); pThis->SignOutUser(userIndex); } } #pragma endregion
35.282171
180
0.645164
acidburn0zzz
9e364de25be765a96eed09a558dac3cc907c7fd2
22,479
hpp
C++
include/BStringt.hpp
ANOTHEL/Awesome-mix-vol.1
58134a7300ce057343d622511600623eaae10042
[ "Apache-2.0" ]
null
null
null
include/BStringt.hpp
ANOTHEL/Awesome-mix-vol.1
58134a7300ce057343d622511600623eaae10042
[ "Apache-2.0" ]
null
null
null
include/BStringt.hpp
ANOTHEL/Awesome-mix-vol.1
58134a7300ce057343d622511600623eaae10042
[ "Apache-2.0" ]
null
null
null
// Copyright 2021~2022 `anothel` All rights reserved #ifndef BSTRINGT_HPP_ #define BSTRINGT_HPP_ #include "include/amvalloc.hpp" #include "include/amvcore.hpp" #include "include/amvsimpstr.hpp" #include "salieri-src/salieri.h" namespace AMV { template <typename BaseType, class StringTraits> class BStringT : public CSimpleStringT<BaseType> { public: typedef CSimpleStringT<BaseType> CThisSimpleString; typedef StringTraits StrTraits; public: BStringT() throw() : CThisSimpleString(StringTraits::GetDefaultManager()) {} explicit BStringT(_In_ IAmvStringMgr* pStringMgr) throw() : CThisSimpleString(pStringMgr) {} // Copy constructor // explicit BStringT(_In_ const BStringT& strSrc) : CThisSimpleString(strSrc) // {} /* Todo(jpk, 20220118): 파라미터가 한개이기 때문에 explicit를 걸어서 암시적 * 형변환을 막아야 한다면 이 상황에서는 처치할 수가 없음 */ BStringT(_In_ const BStringT& strSrc) : CThisSimpleString(strSrc) {} // // Construct from CSimpleStringT // operator CSimpleStringT<BaseType>&() { // // return *(CSimpleStringT<BaseType>*)this; // } explicit BStringT(_In_ const CSimpleStringT<BaseType>& strSrc) : CThisSimpleString(strSrc) {} explicit BStringT(_In_opt_z_ const char* pszSrc) : CThisSimpleString(StringTraits::GetDefaultManager()) { *this = pszSrc; } BStringT(_In_opt_z_ const char* pszSrc, _In_ IAmvStringMgr* pStringMgr) : CThisSimpleString(pStringMgr) { *this = pszSrc; } BStringT(_In_opt_z_ const unsigned char* pszSrc, _In_ IAmvStringMgr* pStringMgr) : CThisSimpleString(pStringMgr) { *this = reinterpret_cast<const char*>(pszSrc); } BStringT(_In_reads_(nLength) const unsigned char* puch, _In_ int nLength) : CThisSimpleString(puch, nLength, StringTraits::GetDefaultManager()) {} // Destructor ~BStringT() throw() {} // Assignment operators BStringT& operator=(_In_ const BStringT& strSrc) { CThisSimpleString::operator=(strSrc); return (*this); } BStringT& operator=(_In_ const CSimpleStringT<BaseType>& strSrc) { CThisSimpleString::operator=(strSrc); return (*this); } BStringT& operator=(_In_opt_z_ const char* pszSrc) { CThisSimpleString::operator=(pszSrc); return (*this); } BStringT& operator=(_In_ char ch) { char ach[2] = {ch, 0}; return (operator=(ach)); } BStringT& operator+=(_In_ const CThisSimpleString& str) { CThisSimpleString::operator+=(str); return (*this); } BStringT& operator+=(_In_z_ const char* pszSrc) { CThisSimpleString::operator+=(pszSrc); return (*this); } template <int t_nSize> BStringT& operator+=(_In_ const CStaticString<char, t_nSize>& strSrc) { CThisSimpleString::operator+=(strSrc); return (*this); } BStringT& operator+=(_In_ char ch) { CThisSimpleString::operator+=(ch); return (*this); } BStringT& operator+=(_In_ unsigned char ch) { CThisSimpleString::operator+=(ch); return (*this); } // Override from base class IAmvStringMgr* GetManager() const throw() { IAmvStringMgr* pStringMgr = CThisSimpleString::GetManager(); if (pStringMgr) { return pStringMgr; } return StringTraits::GetDefaultManager()->Clone(); } // Comparison int Compare(_In_z_ const char* psz) const { AMVENSURE(AmvIsValidString(psz)); // AmvIsValidString guarantees that psz != NULL return (StringTraits::StringCompare(this->GetString(), psz)); } int CompareNoCase(_In_z_ const char* psz) const { AMVENSURE(AmvIsValidString(psz)); // AmvIsValidString guarantees that psz != NULL return (StringTraits::StringCompareIgnore(this->GetString(), psz)); } // Advanced manipulation // Delete 'nCount' characters, starting at index 'iIndex' int Delete(_In_ int iIndex, _In_ int nCount = 1) { if (iIndex < 0) iIndex = 0; if (nCount < 0) nCount = 0; int nLength = this->GetLength(); if ((::AMV::AmvAddThrow(nCount, iIndex)) > nLength) { nCount = nLength - iIndex; } if (nCount > 0) { int nNewLength = nLength - nCount; int nXCHARsToCopy = nLength - (iIndex + nCount) + 1; char* pszBuffer = this->GetBuffer(); memmove_s(pszBuffer + iIndex, nXCHARsToCopy * sizeof(char), pszBuffer + iIndex + nCount, nXCHARsToCopy * sizeof(char)); this->ReleaseBufferSetLength(nNewLength); } return (this->GetLength()); } // Insert character 'ch' before index 'iIndex' int Insert(_In_ int iIndex, _In_ char ch) { if (iIndex < 0) iIndex = 0; if (iIndex > this->GetLength()) { iIndex = this->GetLength(); } int nNewLength = this->GetLength() + 1; char* pszBuffer = this->GetBuffer(nNewLength); // move existing bytes down memmove_s(pszBuffer + iIndex + 1, (nNewLength - iIndex) * sizeof(char), pszBuffer + iIndex, (nNewLength - iIndex) * sizeof(char)); pszBuffer[iIndex] = ch; this->ReleaseBufferSetLength(nNewLength); return (nNewLength); } // Insert string 'psz' before index 'iIndex' int Insert(_In_ int iIndex, _In_z_ const char* psz) { if (iIndex < 0) iIndex = 0; if (iIndex > this->GetLength()) { iIndex = this->GetLength(); } // nInsertLength and nNewLength are in XCHARs int nInsertLength = StringTraits::SafeStringLen(psz); int nNewLength = this->GetLength(); if (nInsertLength > 0) { nNewLength += nInsertLength; char* pszBuffer = this->GetBuffer(nNewLength); // move existing bytes down memmove_s(pszBuffer + iIndex + nInsertLength, (nNewLength - iIndex - nInsertLength + 1) * sizeof(char), pszBuffer + iIndex, (nNewLength - iIndex - nInsertLength + 1) * sizeof(char)); memcpy_s(pszBuffer + iIndex, nInsertLength * sizeof(char), psz, nInsertLength * sizeof(char)); this->ReleaseBufferSetLength(nNewLength); } return (nNewLength); } // Replace all occurrences of character 'chOld' with character 'chNew' int Replace(_In_ char chOld, _In_ char chNew) { int nCount = 0; // short-circuit the nop case if (chOld != chNew) { // otherwise modify each character that matches in the string bool bCopied = false; // We don't actually write to pszBuffer until we've called GetBuffer(). char* pszBuffer = const_cast<char*>(this->GetString()); int nLength = this->GetLength(); int iChar = 0; while (iChar < nLength) { // replace instances of the specified character only if (pszBuffer[iChar] == chOld) { if (!bCopied) { bCopied = true; pszBuffer = this->GetBuffer(nLength); } pszBuffer[iChar] = chNew; nCount++; } iChar = static_cast<int>(StringTraits::CharNext(pszBuffer + iChar) - pszBuffer); } if (bCopied) { this->ReleaseBufferSetLength(nLength); } } return (nCount); } // Replace all occurrences of string 'pszOld' with string 'pszNew' int Replace(_In_z_ const char* pszOld, _In_z_ const char* pszNew) { // can't have empty or NULL lpszOld // nSourceLen is in XCHARs int nSourceLen = StringTraits::SafeStringLen(pszOld); if (nSourceLen == 0) return (0); // nReplacementLen is in XCHARs int nReplacementLen = StringTraits::SafeStringLen(pszNew); // loop once to figure out the size of the result string int nCount = 0; { const char* pszStart = this->GetString(); const char* pszEnd = pszStart + this->GetLength(); while (pszStart < pszEnd) { const char* pszTarget; while ((pszTarget = StringTraits::StringFindString(pszStart, pszOld)) != NULL) { nCount++; pszStart = pszTarget + nSourceLen; } pszStart += StringTraits::SafeStringLen(pszStart) + 1; } } // if any changes were made, make them if (nCount > 0) { // if the buffer is too small, just allocate a new buffer (slow but sure) int nOldLength = this->GetLength(); int nNewLength = nOldLength + (nReplacementLen - nSourceLen) * nCount; char* pszBuffer = this->GetBuffer(__max(nNewLength, nOldLength)); char* pszStart = pszBuffer; char* pszEnd = pszStart + nOldLength; // loop again to actually do the work while (pszStart < pszEnd) { char* pszTarget; while ((pszTarget = StringTraits::StringFindString(pszStart, pszOld)) != NULL) { int nBalance = nOldLength - static_cast<int>(pszTarget - pszBuffer + nSourceLen); memmove_s(pszTarget + nReplacementLen, nBalance * sizeof(char), pszTarget + nSourceLen, nBalance * sizeof(char)); memcpy_s(pszTarget, nReplacementLen * sizeof(char), pszNew, nReplacementLen * sizeof(char)); pszStart = pszTarget + nReplacementLen; pszTarget[nReplacementLen + nBalance] = 0; nOldLength += (nReplacementLen - nSourceLen); } pszStart += StringTraits::SafeStringLen(pszStart) + 1; } AMVASSERT(pszBuffer[nNewLength] == 0); this->ReleaseBufferSetLength(nNewLength); } return (nCount); } // Remove all occurrences of character 'chRemove' int Remove(_In_ char chRemove) { int nLength = this->GetLength(); char* pszBuffer = this->GetBuffer(nLength); char* pszSource = pszBuffer; char* pszDest = pszBuffer; char* pszEnd = pszBuffer + nLength; while (pszSource < pszEnd) { char* pszNewSource = StringTraits::CharNext(pszSource); if (*pszSource != chRemove) { /* Copy the source to the destination. Remember to copy all bytes of an * MBCS character */ size_t NewSourceGap = (pszNewSource - pszSource); char* pszNewDest = pszDest + NewSourceGap; size_t i = 0; for (i = 0; pszDest != pszNewDest && i < NewSourceGap; i++) { *pszDest = *pszSource; pszSource++; pszDest++; } } pszSource = pszNewSource; } *pszDest = 0; int nCount = static_cast<int>(pszSource - pszDest); this->ReleaseBufferSetLength(nLength - nCount); return (nCount); } // find routines // Find the first occurrence of character 'ch', starting at index 'iStart' int Find(_In_ char ch, _In_ int iStart = 0) const throw() { // iStart is in XCHARs AMVASSERT(iStart >= 0); // nLength is in XCHARs int nLength = this->GetLength(); if (iStart < 0 || iStart >= nLength) { return (-1); } // find first single character const char* psz = StringTraits::StringFindChar(this->GetString() + iStart, ch); // return -1 if not found and index otherwise return ((psz == NULL) ? -1 : static_cast<int>(psz - this->GetString())); } // look for a specific sub-string // Find the first occurrence of string 'pszSub', starting at index 'iStart' int Find(_In_z_ const char* pszSub, _In_ int iStart = 0) const throw() { // iStart is in XCHARs AMVASSERT(iStart >= 0); AMVASSERT(AmvIsValidString(pszSub)); if (pszSub == NULL) { return (-1); } // nLength is in XCHARs int nLength = this->GetLength(); if (iStart < 0 || iStart > nLength) { return (-1); } // find first matching substring const char* psz = StringTraits::StringFindString(this->GetString() + iStart, pszSub); // return -1 for not found, distance from beginning otherwise return ((psz == NULL) ? -1 : static_cast<int>(psz - this->GetString())); } // Find the first occurrence of any of the characters in string 'pszCharSet' int FindOneOf(_In_z_ const char* pszCharSet) const throw() { AMVASSERT(AmvIsValidString(pszCharSet)); const char* psz = StringTraits::StringScanSet(this->GetString(), pszCharSet); return ((psz == NULL) ? -1 : static_cast<int>(psz - this->GetString())); } // Find the last occurrence of character 'ch' int ReverseFind(_In_ char ch) const throw() { // find last single character const char* psz = StringTraits::StringFindCharRev(this->GetString(), ch); // return -1 if not found, distance from beginning otherwise return ((psz == NULL) ? -1 : static_cast<int>(psz - this->GetString())); } // trimming // Remove all trailing whitespace BStringT& TrimRight() { // find beginning of trailing spaces by starting at beginning (DBCS aware) const char* psz = this->GetString(); const char* pszLast = NULL; while (*psz != 0) { if (StringTraits::IsSpace(*psz)) { if (pszLast == NULL) pszLast = psz; } else { pszLast = NULL; } psz = StringTraits::CharNext(psz); } if (pszLast != NULL) { // truncate at trailing space start int iLast = static_cast<int>(pszLast - this->GetString()); this->Truncate(iLast); } return (*this); } // Remove all leading whitespace BStringT& TrimLeft() { // find first non-space character const char* psz = this->GetString(); while (StringTraits::IsSpace(*psz)) { psz = StringTraits::CharNext(psz); } if (psz != this->GetString()) { // fix up data and length int iFirst = static_cast<int>(psz - this->GetString()); char* pszBuffer = this->GetBuffer(this->GetLength()); psz = pszBuffer + iFirst; int nDataLength = this->GetLength() - iFirst; memmove_s(pszBuffer, (this->GetLength() + 1) * sizeof(char), psz, (nDataLength + 1) * sizeof(char)); this->ReleaseBufferSetLength(nDataLength); } return (*this); } // Remove all leading and trailing whitespace BStringT& Trim() { return (TrimRight().TrimLeft()); } // Remove all leading and trailing occurrences of character 'chTarget' BStringT& Trim(_In_ char chTarget) { return (TrimRight(chTarget).TrimLeft(chTarget)); } /* Remove all leading and trailing occurrences of any of the characters in the * string 'pszTargets' */ BStringT& Trim(_In_z_ const char* pszTargets) { return (TrimRight(pszTargets).TrimLeft(pszTargets)); } void Print() { printf("%s\n", this->GetString()); return; } // trimming anything (either side) // Remove all trailing occurrences of character 'chTarget' BStringT& TrimRight(_In_ char chTarget) { // find beginning of trailing matches // by starting at beginning (DBCS aware) const char* psz = this->GetString(); const char* pszLast = NULL; while (*psz != 0) { if (*psz == chTarget) { if (pszLast == NULL) { pszLast = psz; } } else { pszLast = NULL; } psz = StringTraits::CharNext(psz); } if (pszLast != NULL) { // truncate at left-most matching character int iLast = static_cast<int>(pszLast - this->GetString()); this->Truncate(iLast); } return (*this); } /* Remove all trailing occurrences of any of the characters in string * 'pszTargets' */ BStringT& TrimRight(_In_z_ const char* pszTargets) { // if we're not trimming anything, we're not doing any work if ((pszTargets == NULL) || (*pszTargets == 0)) { return (*this); } // find beginning of trailing matches // by starting at beginning (DBCS aware) const char* psz = this->GetString(); const char* pszLast = NULL; while (*psz != 0) { if (StringTraits::StringFindChar(pszTargets, *psz) != NULL) { if (pszLast == NULL) { pszLast = psz; } } else { pszLast = NULL; } psz = StringTraits::CharNext(psz); } if (pszLast != NULL) { // truncate at left-most matching character int iLast = static_cast<int>(pszLast - this->GetString()); this->Truncate(iLast); } return (*this); } // Remove all leading occurrences of character 'chTarget' BStringT& TrimLeft(_In_ char chTarget) { // find first non-matching character const char* psz = this->GetString(); while (chTarget == *psz) { psz = StringTraits::CharNext(psz); } if (psz != this->GetString()) { // fix up data and length int iFirst = static_cast<int>(psz - this->GetString()); char* pszBuffer = this->GetBuffer(this->GetLength()); psz = pszBuffer + iFirst; int nDataLength = this->GetLength() - iFirst; memmove_s(pszBuffer, (this->GetLength() + 1) * sizeof(char), psz, (nDataLength + 1) * sizeof(char)); this->ReleaseBufferSetLength(nDataLength); } return (*this); } /* Remove all leading occurrences of any of the characters in string * 'pszTargets' */ BStringT& TrimLeft(_In_z_ const char* pszTargets) { // if we're not trimming anything, we're not doing any work if ((pszTargets == NULL) || (*pszTargets == 0)) { return (*this); } const char* psz = this->GetString(); while ((*psz != 0) && (StringTraits::StringFindChar(pszTargets, *psz) != NULL)) { psz = StringTraits::CharNext(psz); } if (psz != this->GetString()) { // fix up data and length int iFirst = static_cast<int>(psz - this->GetString()); char* pszBuffer = this->GetBuffer(this->GetLength()); psz = pszBuffer + iFirst; int nDataLength = this->GetLength() - iFirst; memmove_s(pszBuffer, (this->GetLength() + 1) * sizeof(char), psz, (nDataLength + 1) * sizeof(char)); this->ReleaseBufferSetLength(nDataLength); } return (*this); } friend BStringT operator+(_In_ const BStringT& str1, _In_ const BStringT& str2) { BStringT strResult(str1.GetManager()); CThisSimpleString::Concatenate(strResult, str1, str1.GetLength(), str2, str2.GetLength()); return (strResult); } friend BStringT operator+(_In_ const BStringT& str1, _In_z_ const char* psz2) { BStringT strResult(str1.GetManager()); CThisSimpleString::Concatenate(strResult, str1, str1.GetLength(), psz2, CThisSimpleString::StringLength(psz2)); return (strResult); } friend BStringT operator+(_In_z_ const char* psz1, _In_ const BStringT& str2) { BStringT strResult(str2.GetManager()); CThisSimpleString::Concatenate(strResult, psz1, CThisSimpleString::StringLength(psz1), str2, str2.GetLength()); return (strResult); } friend BStringT operator+(_In_ const BStringT& str1, _In_ char ch2) { BStringT strResult(str1.GetManager()); CThisSimpleString::Concatenate(strResult, str1, str1.GetLength(), &ch2, 1); return (strResult); } friend BStringT operator+(_In_ char ch1, _In_ const BStringT& str2) { BStringT strResult(str2.GetManager()); CThisSimpleString::Concatenate(strResult, &ch1, 1, str2, str2.GetLength()); return (strResult); } friend bool operator==(_In_ const BStringT& str1, _In_ const BStringT& str2) throw() { return (str1.Compare(str2) == 0); } friend bool operator==(_In_ const BStringT& str1, _In_z_ const char* psz2) throw() { return (str1.Compare(psz2) == 0); } friend bool operator==(_In_z_ const char* psz1, _In_ const BStringT& str2) throw() { return (str2.Compare(psz1) == 0); } friend bool operator!=(_In_ const BStringT& str1, _In_ const BStringT& str2) throw() { return (str1.Compare(str2) != 0); } friend bool operator!=(_In_ const BStringT& str1, _In_z_ const char* psz2) throw() { return (str1.Compare(psz2) != 0); } friend bool operator!=(_In_z_ const char* psz1, _In_ const BStringT& str2) throw() { return (str2.Compare(psz1) != 0); } friend bool operator<(_In_ const BStringT& str1, _In_ const BStringT& str2) throw() { return (str1.Compare(str2) < 0); } friend bool operator<(_In_ const BStringT& str1, _In_z_ const char* psz2) throw() { return (str1.Compare(psz2) < 0); } friend bool operator<(_In_z_ const char* psz1, _In_ const BStringT& str2) throw() { return (str2.Compare(psz1) > 0); } friend bool operator>(_In_ const BStringT& str1, _In_ const BStringT& str2) throw() { return (str1.Compare(str2) > 0); } friend bool operator>(_In_ const BStringT& str1, _In_z_ const char* psz2) throw() { return (str1.Compare(psz2) > 0); } friend bool operator>(_In_z_ const char* psz1, _In_ const BStringT& str2) throw() { return (str2.Compare(psz1) < 0); } friend bool operator<=(_In_ const BStringT& str1, _In_ const BStringT& str2) throw() { return (str1.Compare(str2) <= 0); } friend bool operator<=(_In_ const BStringT& str1, _In_z_ const char* psz2) throw() { return (str1.Compare(psz2) <= 0); } friend bool operator<=(_In_z_ const char* psz1, _In_ const BStringT& str2) throw() { return (str2.Compare(psz1) >= 0); } friend bool operator>=(_In_ const BStringT& str1, _In_ const BStringT& str2) throw() { return (str1.Compare(str2) >= 0); } friend bool operator>=(_In_ const BStringT& str1, _In_z_ const char* psz2) throw() { return (str1.Compare(psz2) >= 0); } friend bool operator>=(_In_z_ const char* psz1, _In_ const BStringT& str2) throw() { return (str2.Compare(psz1) <= 0); } friend bool operator==(_In_ char ch1, _In_ const BStringT& str2) throw() { return ((str2.GetLength() == 1) && (str2[0] == ch1)); } friend bool operator==(_In_ const BStringT& str1, _In_ char ch2) throw() { return ((str1.GetLength() == 1) && (str1[0] == ch2)); } friend bool operator!=(_In_ char ch1, _In_ const BStringT& str2) throw() { return ((str2.GetLength() != 1) || (str2[0] != ch1)); } friend bool operator!=(_In_ const BStringT& str1, _In_ char ch2) throw() { return ((str1.GetLength() != 1) || (str1[0] != ch2)); } }; } // namespace AMV #endif // BSTRINGT_HPP_
30.132708
80
0.615196
ANOTHEL
9e3671d34f079f3ffe3b580e1f08082deb37ef71
177
cpp
C++
TestComponent/Class.cpp
jkotas/TestWinRT
e7682136641caf9713268761ec8188ca452e85f9
[ "MIT" ]
14
2019-10-29T02:39:37.000Z
2022-02-21T03:45:58.000Z
TestComponent/Class.cpp
jkotas/TestWinRT
e7682136641caf9713268761ec8188ca452e85f9
[ "MIT" ]
24
2020-01-30T16:28:35.000Z
2022-03-17T15:50:45.000Z
TestComponent/Class.cpp
jkotas/TestWinRT
e7682136641caf9713268761ec8188ca452e85f9
[ "MIT" ]
8
2019-10-31T13:51:54.000Z
2021-10-10T21:29:44.000Z
#include "pch.h" #include "Class.h" #include "Class.g.cpp" namespace winrt::TestComponent::implementation { int32_t Class::One() { return 1; } }
14.75
47
0.581921
jkotas
9e38b73cce6b3c456e9db8140791c625fa05cf02
6,145
cpp
C++
src/IKSolverRT.cpp
GuillaumeVDu/RTIKIDQualisys
9b70e2c0eb1f3492f74119c4339a6f5404ede290
[ "MIT" ]
2
2019-07-25T18:11:13.000Z
2019-09-08T16:02:23.000Z
src/IKSolverRT.cpp
GuillaumeVDu/RTIKIDQualisys
9b70e2c0eb1f3492f74119c4339a6f5404ede290
[ "MIT" ]
null
null
null
src/IKSolverRT.cpp
GuillaumeVDu/RTIKIDQualisys
9b70e2c0eb1f3492f74119c4339a6f5404ede290
[ "MIT" ]
null
null
null
// Copyright (c) 2015, Guillaume Durandau and Massimo Sartori // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #include "IKSolverRT.h" IKSolverRT::IKSolverRT(const OpenSim::Model &model, const std::vector<std::string>& markerNames, const std::vector<double>& markerWeights, double constraintWeight) : Solver(model), markerNames_(markerNames), markerWeights_(markerWeights), constraintWeight_(constraintWeight), enforceContraint_( false) { assembler_ = NULL; accuracy_ = 1e-4; } IKSolverRT::~IKSolverRT() { delete assembler_; //delete markerAssemblyCondition_; } void IKSolverRT::setupGoals(SimTK::State &s) { // Setup coordinates performed by the base class // Crate the IK solver. //delete assembler_; assembler_ = new SimTK::Assembler(getModel().getMultibodySystem()); // Set Accuracy of the IK. assembler_->setAccuracy(accuracy_); // Set the Assembler weight. assembler_->setSystemConstraintsWeight(constraintWeight_); // Enforce the constraint limit of each joint, if needed. if (enforceContraint_) { // Get model coordinates. const OpenSim::CoordinateSet &modelCoordSet = getModel().getCoordinateSet(); // Restrict solution to set range of any of the coordinates that are clamped. for (int i = 0; i < modelCoordSet.getSize(); ++i) { const OpenSim::Coordinate& coord = modelCoordSet[i]; if (coord.getClamped(s)) { assembler_->restrictQ(coord.getBodyIndex(), SimTK::MobilizerQIndex(coord.getMobilizerQIndex()), coord.getRangeMin(), coord.getRangeMax()); } } } // Create the markers for the IK solver. markerAssemblyCondition_ = new SimTK::Markers(); // get markers defined by the model const OpenSim::MarkerSet &modelMarkerSet = getModel().getMarkerSet(); int index = -1; // Loop through all markers in the reference. for (std::vector<std::string>::const_iterator it1 = markerNames_.begin(); it1 != markerNames_.end(); it1++) { // Check if we have this marker in the model, else ignore it index = modelMarkerSet.getIndex(*it1, index); if (index >= 0) { const OpenSim::Marker &marker = modelMarkerSet.get(*it1); const SimTK::MobilizedBody &mobod = getModel().getMatterSubsystem().getMobilizedBody( marker.getBody().getIndex()); markerAssemblyCondition_->addMarker(marker.getName(), mobod, marker.getOffset(), markerWeights_[std::distance<std::vector<std::string>::const_iterator>(markerNames_.begin(), it1)]); } } // Add marker goal to the IK objective. assembler_->adoptAssemblyGoal(markerAssemblyCondition_); // lock-in the order that the observations (markers) are in and this cannot change from frame to frame // and we can use an array of just the data for updating markerAssemblyCondition_->defineObservationOrder(markerNames_); updateGoals(s); } void IKSolverRT::updateGoals(const SimTK::State &s) { // update coordinates performed by the base class markerAssemblyCondition_->moveAllObservations(markerValues_); } void IKSolverRT::assemble(SimTK::State &state) { // Make a working copy of the state that will be used to set the internal state of the solver // This is necessary because we may wish to disable redundant constraints, but do not want this // to effect the state of constraints the user expects SimTK::State s = state; // Make sure goals are up-to-date. setupGoals(s); // Let assembler perform some internal setup assembler_->initialize(s); try { // Now do the assembly and return the updated state. assembler_->assemble(); // Update the q's in the state passed in assembler_->updateFromInternalState(s); state.updQ() = s.getQ(); state.updU() = s.getU(); // Get model coordinates const OpenSim::CoordinateSet &modelCoordSet = getModel().getCoordinateSet(); // Make sure the locks in original state are restored for (int i = 0; i < modelCoordSet.getSize(); ++i) { bool isLocked = modelCoordSet[i].getLocked(state); if (isLocked) modelCoordSet[i].setLocked(state, isLocked); } } catch (const std::exception& ex) { std::string msg = "AssemblySolver::assemble() Failed: "; msg += ex.what(); throw OpenSim::Exception(msg); } } void IKSolverRT::track(SimTK::State &s) { // move the target locations or angles, etc... just do not change number of goals // and their type (constrained vs. weighted) if (assembler_ && assembler_->isInitialized()) { updateGoals(s); } else { throw OpenSim::Exception("AssemblySolver::track() failed: assemble() must be called first."); } try { // Now do the assembly and return the updated state. assembler_->track(s.getTime()); // update the state from the result of the assembler assembler_->updateFromInternalState(s); } catch (const std::exception& ex) { std::cout << "AssemblySolver::track() attempt Failed: " << ex.what() << std::endl; throw OpenSim::Exception("AssemblySolver::track() attempt failed."); } }
33.579235
130
0.732954
GuillaumeVDu
9e39d0d2d60dbb335ec1964a098c52093298666e
8,083
hpp
C++
include/Value.hpp
MiguelMJ/MakeItPixel
aae0531a546ef80b1a1a839cfbcd430806ffdee1
[ "MIT" ]
5
2022-01-26T12:51:26.000Z
2022-03-30T03:17:13.000Z
include/Value.hpp
MiguelMJ/MakeItPixel
aae0531a546ef80b1a1a839cfbcd430806ffdee1
[ "MIT" ]
null
null
null
include/Value.hpp
MiguelMJ/MakeItPixel
aae0531a546ef80b1a1a839cfbcd430806ffdee1
[ "MIT" ]
null
null
null
#ifndef __MIPA_VALUE__ #define __MIPA_VALUE__ #include <string> #include <sstream> #include <SFML/Graphics.hpp> #include "Color.hpp" #include "Palette.hpp" #include "Quantization.hpp" namespace mipa{ typedef enum { COLOR = 1, PALETTE = 2, IMAGE = 4, QUANTIZER = 8, COLORSTRATEGY = 16, NUMBER = 32, STRING = 64 } ValueType; struct Value{ ValueType type; inline Value(ValueType t): type(t){} virtual std::string toString() const = 0; virtual Value* copy() const = 0; virtual ~Value(){} }; struct NumberValue: public Value{ float number; inline NumberValue(float n): Value(NUMBER), number(n){} inline std::string toString() const override{ return std::to_string(number); } inline Value* copy() const override{ return new NumberValue(number); } }; struct StringValue: public Value{ std::string string; inline StringValue(std::string s):Value(STRING), string(s){} inline std::string toString() const override{ return string; } inline Value* copy() const override{ return new StringValue(string); } }; struct ColorValue: public Value{ RGB color; inline ColorValue(const RGB& rgb):Value(COLOR),color(rgb){} inline std::string toString() const override{ std::stringstream ss; ss << color; return ss.str(); } inline Value* copy() const override{ return new ColorValue(color); } }; struct PaletteValue: public Value{ Palette palette; inline PaletteValue(const Palette& p):Value(PALETTE),palette(p){} inline std::string toString() const override{ std::stringstream ss; ss << "["; for(uint i=0; i < palette.size(); i++){ ss << palette[i]; if(i < palette.size()-1){ ss << ", "; } } ss << "]"; return ss.str(); } inline Value* copy() const override{ return new PaletteValue(palette); } }; struct ImageValue: public Value{ sf::Image image; inline ImageValue():Value(IMAGE){} inline ImageValue(const sf::Image& i):Value(IMAGE),image(i){} inline std::string toString() const override{ sf::Vector2u imgSize = image.getSize(); return "{Image: "+std::to_string(imgSize.x)+"x"+std::to_string(imgSize.y)+"}"; } inline Value* copy() const override{ return new ImageValue(image); } }; struct ColorStrategyValue: public Value{ inline ColorStrategyValue(): Value(COLORSTRATEGY){} virtual RGB operator()(const RGB& rgb) const{ return rgb; }; virtual std::string toString() const{ return "{Empty Color Strategy}"; }; virtual Value* copy() const override{ return new ColorStrategyValue; } virtual float recommended_sparsity() const{ return 254; }; }; struct PaletteColorStrategyValue: public ColorStrategyValue{ Palette palette; RGB (*picker)(const Palette& p, const RGB& in); inline RGB operator()(const RGB& rgb) const override{ return picker(palette, rgb); } inline std::string toString() const override{ std::stringstream ss; ss << "{Palette Picker " << PaletteValue(palette).toString() << "}"; return ss.str(); } inline Value* copy() const override{ auto pcsv = new PaletteColorStrategyValue; pcsv->palette = palette; pcsv->picker = picker; return pcsv; } virtual float recommended_sparsity() const{ return std::sqrt(palette.size()); }; }; struct DiscreteRGBColorStrategyValue: public ColorStrategyValue{ uint r_values; uint g_values; uint b_values; inline DiscreteRGBColorStrategyValue(uint r, uint g, uint b): ColorStrategyValue(), r_values(255/r), g_values(255/g), b_values(255/b) {} inline RGB operator()(const RGB& rgb) const override{ return RGB( rgb.r - rgb.r % r_values, rgb.g - rgb.g % g_values, rgb.b - rgb.b % b_values ); } inline std::string toString() const override{ std::stringstream ss; ss << "{Discrete RGB Picker: " << r_values << ", " << g_values << ", " << b_values << "}"; return ss.str(); } inline Value* copy() const override{ return new DiscreteRGBColorStrategyValue(*this); } virtual float recommended_sparsity() const{ return std::max(r_values, std::max(b_values, b_values)); }; }; struct DiscreteHSVColorStrategyValue: public ColorStrategyValue{ uint h_values; uint s_values; uint v_values; inline DiscreteHSVColorStrategyValue(uint h, uint s, uint v): ColorStrategyValue(), h_values(360/h), s_values(100/s), v_values(100/v) {} inline RGB operator()(const RGB& rgb) const override{ HSV hsv = toHSV(rgb); HSV out; out.h = hsv.h - ((int)hsv.h % h_values); out.s = hsv.s - (float)((int)(hsv.s * 100) % s_values)/100; out.v = hsv.v - (float)((int)(hsv.v * 100) % v_values)/100; return toRGB(out); } inline std::string toString() const override{ std::stringstream ss; ss << "{Discrete HSV Picker: " << h_values << ", " << s_values << ", " << v_values << "}"; return ss.str(); } inline Value* copy() const override{ return new DiscreteHSVColorStrategyValue(*this); } virtual float recommended_sparsity() const{ return std::max(h_values, std::max(s_values, v_values)); }; }; struct QuantizerValue: public Value{ inline QuantizerValue(): Value(QUANTIZER){} virtual void apply(sf::Image& img, ColorStrategyValue* strategy) const = 0; virtual std::string toString() const = 0; virtual Value* copy() const = 0; }; struct DirectQuantizerValue: public QuantizerValue{ void apply(sf::Image& img, ColorStrategyValue* strategy) const override{ directQuantize(img, strategy); } inline std::string toString() const override{ return "{Direct Quantizer}"; } inline Value* copy() const override{ return new DirectQuantizerValue(); } }; struct OrderedDitherQuantizerValue: public QuantizerValue{ std::string matrixName; float sparsity, threshold; void apply(sf::Image& img, ColorStrategyValue* strategy) const override{ float real_sparsity = sparsity; if(real_sparsity == -1){ real_sparsity = strategy->recommended_sparsity(); } ditherOrdered(img, strategy, matrices.at(matrixName), real_sparsity, threshold); } inline std::string toString() const override{ return "{Ordered Dither: "+matrixName+"}"; } inline Value* copy() const override{ return new OrderedDitherQuantizerValue(*this); } }; struct FSDitherQuantizerValue: public QuantizerValue{ float threshold; void apply(sf::Image& img, ColorStrategyValue* strategy) const override{ ditherFloydSteinberg(img, strategy, threshold); } inline std::string toString() const override{ return "{Error Propagation Dither}"; } inline Value* copy() const override{ return new FSDitherQuantizerValue(*this); } }; } #endif
34.991342
102
0.558703
MiguelMJ
9e3d12fb5ec3726a9bc8b01bfde2273c6ed4b9f5
2,779
cpp
C++
src/Switch.System.Drawing/src/Switch/System/Drawing/FontFamily.cpp
victor-timoshin/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
4
2020-02-11T13:22:58.000Z
2022-02-24T00:37:43.000Z
src/Switch.System.Drawing/src/Switch/System/Drawing/FontFamily.cpp
sgf/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
null
null
null
src/Switch.System.Drawing/src/Switch/System/Drawing/FontFamily.cpp
sgf/Switch
8e8e687a8bdc4f79d482680da3968e9b3e464b8b
[ "MIT" ]
2
2020-02-01T02:19:01.000Z
2021-12-30T06:44:00.000Z
#include <Switch/System/Collections/Generic/List.hpp> #include <Switch/System/NotImplementedException.hpp> #include "../../../../include/Switch/System/Drawing/FontFamily.hpp" #include "../../../../include/Switch/System/Drawing/Text/InstalledFontCollection.hpp" #include "../../../Native/Api.hpp" System::Drawing::FontFamily::FontFamily(const string& name) { if (name == "") throw ArgumentException(caller_); *this = Native::FontFamilyApi::GetFontFamilyFromName(name); } System::Drawing::FontFamily::FontFamily(System::Drawing::Text::GenericFontFamilies genericFamily) { if (genericFamily == System::Drawing::Text::GenericFontFamilies::Serif) *this = System::Drawing::FontFamily(Native::FontFamilyApi::GenericFontFamilySerifName()); else if (genericFamily == System::Drawing::Text::GenericFontFamilies::SansSerif) *this = System::Drawing::FontFamily(Native::FontFamilyApi::GenericFontFamilySansSerifName()); else *this = System::Drawing::FontFamily(Native::FontFamilyApi::GenericFontFamilyMonospaceName()); } System::Drawing::FontFamily::FontFamily(const string& name, const System::Drawing::Text::FontCollection& fontCollection) { for (FontFamily fontFamily : fontCollection.Families()) if (name == fontFamily.Name) { *this = fontFamily; return; } throw ArgumentException(caller_); } System::Drawing::FontFamily::~FontFamily() { if (this->data.IsUnique()) Native::FontFamilyApi::ReleaseResource(this->data().handle); } property_<System::Array<System::Drawing::FontFamily>, readonly_> System::Drawing::FontFamily::Families { [] {return System::Drawing::Text::InstalledFontCollection().Families();} }; property_<System::Drawing::FontFamily, readonly_> System::Drawing::FontFamily::GenericMonospace { [] {return FontFamily(System::Drawing::Text::GenericFontFamilies::Monospace);} }; property_<System::Drawing::FontFamily, readonly_> System::Drawing::FontFamily::GenericSansSerif { [] {return FontFamily(System::Drawing::Text::GenericFontFamilies::SansSerif);} }; property_<System::Drawing::FontFamily, readonly_> System::Drawing::FontFamily::GenericSerif { [] {return FontFamily(System::Drawing::Text::GenericFontFamilies::Serif);} }; int32 System::Drawing::FontFamily::GetCellAscent(FontStyle style) { return Native::FontFamilyApi::GetCellAscent(this->GetName(), style); } int32 System::Drawing::FontFamily::GetCellDescent(FontStyle style) { return Native::FontFamilyApi::GetCellDescent(this->GetName(), style); } string System::Drawing::FontFamily::GetName() const { return Native::FontFamilyApi::GetName(this->data().handle); } bool System::Drawing::FontFamily::IsStyleAvailable(System::Drawing::FontStyle style) const { return Native::FontFamilyApi::IsStyleAvailable(this->data().handle, style); }
42.106061
122
0.74955
victor-timoshin
9e3e06140c6a87070100198b4a429d647d7f41c7
624
cc
C++
ncstreamer_cef/src/client/client_display_handler.cc
ncsoft/ncstreamer
f9055e67d75d57e3bad2e793ad8a28e9b91ab746
[ "BSD-3-Clause" ]
9
2017-05-08T04:43:18.000Z
2022-01-02T19:24:32.000Z
ncstreamer_cef/src/client/client_display_handler.cc
ncsoft/ncstreamer
f9055e67d75d57e3bad2e793ad8a28e9b91ab746
[ "BSD-3-Clause" ]
null
null
null
ncstreamer_cef/src/client/client_display_handler.cc
ncsoft/ncstreamer
f9055e67d75d57e3bad2e793ad8a28e9b91ab746
[ "BSD-3-Clause" ]
8
2017-05-08T04:49:03.000Z
2022-02-03T08:44:04.000Z
/** * Copyright (C) 2017 NCSOFT Corporation */ #include "ncstreamer_cef/src/client/client_display_handler.h" #include <string> #include "include/wrapper/cef_helpers.h" #include "windows.h" // NOLINT namespace ncstreamer { ClientDisplayHandler::ClientDisplayHandler() { } ClientDisplayHandler::~ClientDisplayHandler() { } void ClientDisplayHandler::OnTitleChange(CefRefPtr<CefBrowser> browser, const CefString &title) { CEF_REQUIRE_UI_THREAD(); HWND hwnd = browser->GetHost()->GetWindowHandle(); ::SetWindowTextW(hwnd, title.c_str()); } } // namespace ncstreamer
20.129032
71
0.700321
ncsoft
9e41e68a8d0ce73e4f855465c80a039ada7218bf
3,253
cpp
C++
Messy_Test-master/demo/CppBaseTest/coding_optimizations.cpp
shenjl/Cplusplus
345c2f582bf160d663c8accfafbcabc2ff011e57
[ "MIT" ]
1
2019-11-10T08:23:00.000Z
2019-11-10T08:23:00.000Z
Messy_Test-master/demo/CppBaseTest/coding_optimizations.cpp
selonsy/Cplusplus
345c2f582bf160d663c8accfafbcabc2ff011e57
[ "MIT" ]
null
null
null
Messy_Test-master/demo/CppBaseTest/coding_optimizations.cpp
selonsy/Cplusplus
345c2f582bf160d663c8accfafbcabc2ff011e57
[ "MIT" ]
null
null
null
#include "coding_optimizations.hpp" #include <ctype.h> #include <string.h> #include <iostream> #include <chrono> #include <string> // Blog: https://blog.csdn.net/fengbingchun/article/details/85934251 namespace coding_optimizations_ { // reference: 《提高C++性能的编程技术》:第十三章:编码优化 namespace { static char uppercaseTable[256]; void initLookupTable() { for (int i = 0; i < 256; ++i) { uppercaseTable[i] = toupper(i); } } class Student1 { public: // C++保证在Student1的构造函数体执行之前,所有的成员对象已经创建完成,此处即string型的name对象。 // 既然我们没有显示告诉编译器如何构造它,编译器就插入了对string默认构造函数的调用。该调用在Student1的构造函数体执行之前进行。 Student1(char* nm) { name = nm; } private: std::string name; }; class Student2 { public: // 通过在Student2的构造函数初始化列表中显示指明string构造函数,可以避免Student1中的无效计算 // 由于我们明确告诉编译器使用哪个string构造函数,编译器将不再隐式地调用string默认构造函数。因此我们实现了一步完成string成员对象的构造 Student2(char* nm) : name(nm) {} private: std::string name; }; } // namespace int test_coding_optimizations_1() { initLookupTable(); std::chrono::high_resolution_clock::time_point time_start, time_end; const int count{10000}, count2{100000}; const char* header{"afaIELQEadsfjl943082jdfaadfajqwppreijfadfadfaoueheufiekasdLdamsaldfadfawweevKKA"}; int length = strlen(header); char ch; { // test lowercase letter to uppercase letter: normal time_start = std::chrono::high_resolution_clock::now(); for (int t = 0; t < count; ++t) { for (int i = 0; i < count; ++i) { char* p = const_cast<char*>(header); for (int j = 0; j < length; ++j) { ch = toupper(*p++); //fprintf(stdout, "%c", ch); } //fprintf(stdout, "\n"); } } time_end = std::chrono::high_resolution_clock::now(); fprintf(stdout, "lowercase letter to uppercase letter normal time spend: %f seconds\n", (std::chrono::duration_cast<std::chrono::duration<double>>(time_end-time_start)).count()); } { // test lowercase letter to uppercase letter: pre-calculated time_start = std::chrono::high_resolution_clock::now(); for (int t = 0; t < count; ++t) { for (int i = 0; i < count; ++i) { char* p = const_cast<char*>(header); for (int j = 0; j < length; ++j) { ch = uppercaseTable[*p++]; //fprintf(stdout, "%c", ch); } //fprintf(stdout, "\n"); } } time_end = std::chrono::high_resolution_clock::now(); fprintf(stdout, "lowercase letter to uppercase letter pre-calculated time spend: %f seconds\n", (std::chrono::duration_cast<std::chrono::duration<double>>(time_end-time_start)).count()); } { // test unuseful calculate: normal time_start = std::chrono::high_resolution_clock::now(); for (int t = 0; t < count2; ++t) { Student1 st("beijing"); } time_end = std::chrono::high_resolution_clock::now(); fprintf(stdout, "unuseful calculate normal time spend: %f seconds\n", (std::chrono::duration_cast<std::chrono::duration<double>>(time_end-time_start)).count()); } { // test unuseful calculate: list init time_start = std::chrono::high_resolution_clock::now(); for (int t = 0; t < count2; ++t) { Student2 st("beijing"); } time_end = std::chrono::high_resolution_clock::now(); fprintf(stdout, "unuseful calculate list init time spend: %f seconds\n", (std::chrono::duration_cast<std::chrono::duration<double>>(time_end-time_start)).count()); } return 0; } } // namespace coding_optimizations_
28.787611
103
0.696588
shenjl
9e42d79251e7022f24660c2137062505dfc3b13b
38,037
cpp
C++
server/ClientHandler.cpp
cjcliffe/SoapyRemote
aa8208879ef09c10350a1b4a95bd612ba544c50e
[ "BSL-1.0" ]
1
2021-05-16T21:00:09.000Z
2021-05-16T21:00:09.000Z
server/ClientHandler.cpp
cjcliffe/SoapyRemote
aa8208879ef09c10350a1b4a95bd612ba544c50e
[ "BSL-1.0" ]
null
null
null
server/ClientHandler.cpp
cjcliffe/SoapyRemote
aa8208879ef09c10350a1b4a95bd612ba544c50e
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2015-2015 Josh Blum // SPDX-License-Identifier: BSL-1.0 #include "ClientHandler.hpp" #include "ServerStreamData.hpp" #include "LogForwarding.hpp" #include "SoapyRemoteDefs.hpp" #include "FormatToElemSize.hpp" #include "SoapyURLUtils.hpp" #include "SoapyRPCSocket.hpp" #include "SoapyRPCPacker.hpp" #include "SoapyRPCUnpacker.hpp" #include "SoapyStreamEndpoint.hpp" #include <SoapySDR/Device.hpp> #include <SoapySDR/Logger.hpp> #include <iostream> #include <mutex> //! The device factory make and unmake requires a process-wide mutex static std::mutex factoryMutex; /*********************************************************************** * Client handler constructor **********************************************************************/ SoapyClientHandler::SoapyClientHandler(SoapyRPCSocket &sock): _sock(sock), _dev(nullptr), _logForwarder(nullptr), _nextStreamId(0) { return; } SoapyClientHandler::~SoapyClientHandler(void) { //stop all stream threads and close streams for (auto &data : _streamData) { data.second.stopThreads(); _dev->closeStream(data.second.stream); } //release the device handle if we have it if (_dev != nullptr) { std::lock_guard<std::mutex> lock(factoryMutex); SoapySDR::Device::unmake(_dev); _dev = nullptr; } //finally stop and cleanup log forwarding delete _logForwarder; } /*********************************************************************** * Transaction handler **********************************************************************/ bool SoapyClientHandler::handleOnce(void) { if (not _sock.selectRecv(SOAPY_REMOTE_SOCKET_TIMEOUT_US)) return true; //receive the client's request SoapyRPCUnpacker unpacker(_sock); SoapyRPCPacker packer(_sock); //handle the client's request bool again = true; try { again = this->handleOnce(unpacker, packer); } catch (const std::exception &ex) { packer & ex; } //send the result back packer(); return again; } /*********************************************************************** * Handler dispatcher implementation **********************************************************************/ bool SoapyClientHandler::handleOnce(SoapyRPCUnpacker &unpacker, SoapyRPCPacker &packer) { SoapyRemoteCalls call; unpacker & call; switch (call) { //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_FIND: //////////////////////////////////////////////////////////////////// { SoapySDR::Kwargs args; unpacker & args; packer & SoapySDR::Device::enumerate(args); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_MAKE: //////////////////////////////////////////////////////////////////// { SoapySDR::Kwargs args; unpacker & args; std::lock_guard<std::mutex> lock(factoryMutex); if (_dev == nullptr) _dev = SoapySDR::Device::make(args); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_UNMAKE: //////////////////////////////////////////////////////////////////// { std::lock_guard<std::mutex> lock(factoryMutex); if (_dev != nullptr) SoapySDR::Device::unmake(_dev); _dev = nullptr; packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_HANGUP: //////////////////////////////////////////////////////////////////// { packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_SERVER_ID: //////////////////////////////////////////////////////////////////// { packer & uniqueProcessId(); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_START_LOG_FORWARDING: //////////////////////////////////////////////////////////////////// { if (_logForwarder == nullptr) _logForwarder = new SoapyLogForwarder(_sock); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_STOP_LOG_FORWARDING: //////////////////////////////////////////////////////////////////// { if (_logForwarder != nullptr) delete _logForwarder; _logForwarder = nullptr; packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_DRIVER_KEY: //////////////////////////////////////////////////////////////////// { packer & _dev->getDriverKey(); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_HARDWARE_KEY: //////////////////////////////////////////////////////////////////// { packer & _dev->getHardwareKey(); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_HARDWARE_INFO: //////////////////////////////////////////////////////////////////// { packer & _dev->getHardwareInfo(); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_FRONTEND_MAPPING: //////////////////////////////////////////////////////////////////// { char direction = 0; std::string mapping; unpacker & direction; unpacker & mapping; _dev->setFrontendMapping(direction, mapping); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_FRONTEND_MAPPING: //////////////////////////////////////////////////////////////////// { char direction = 0; unpacker & direction; packer & _dev->getFrontendMapping(direction); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_NUM_CHANNELS: //////////////////////////////////////////////////////////////////// { char direction = 0; unpacker & direction; packer & int(_dev->getNumChannels(direction)); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_FULL_DUPLEX: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->getFullDuplex(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SETUP_STREAM: //////////////////////////////////////////////////////////////////// { char direction = 0; std::string format; std::vector<size_t> channels; SoapySDR::Kwargs args; std::string clientBindPort; std::string statusBindPort; unpacker & direction; unpacker & format; unpacker & channels; unpacker & args; unpacker & clientBindPort; unpacker & statusBindPort; //parse args for buffer configuration size_t mtu = SOAPY_REMOTE_DEFAULT_ENDPOINT_MTU; const auto mtuIt = args.find(SOAPY_REMOTE_KWARG_MTU); if (mtuIt != args.end()) mtu = size_t(std::stod(mtuIt->second)); size_t window = SOAPY_REMOTE_DEFAULT_ENDPOINT_WINDOW; const auto windowIt = args.find(SOAPY_REMOTE_KWARG_WINDOW); if (windowIt != args.end()) window = size_t(std::stod(windowIt->second)); double priority = SOAPY_REMOTE_DEFAULT_THREAD_PRIORITY; const auto priorityIt = args.find(SOAPY_REMOTE_KWARG_PRIORITY); if (priorityIt != args.end()) priority = std::stod(priorityIt->second); //create stream auto stream = _dev->setupStream(direction, format, channels, args); //load data structure auto &data = _streamData[_nextStreamId]; data.streamId = _nextStreamId++; data.device = _dev; data.stream = stream; data.format = format; for (const auto chan : channels) data.chanMask |= (1 << chan); data.priority = priority; //extract socket node information std::string serverBindPort; std::string localNode, remoteNode; std::string scheme, node, service; splitURL(_sock.getsockname(), scheme, localNode, service); splitURL(_sock.getpeername(), scheme, remoteNode, service); //bind the stream socket to an automatic port const auto bindURL = combineURL("udp", localNode, "0"); int ret = data.streamSock.bind(bindURL); if (ret != 0) { const std::string errorMsg = data.streamSock.lastErrorMsg(); _streamData.erase(data.streamId); throw std::runtime_error("SoapyRemote::setupStream("+bindURL+") -- bind FAIL: " + errorMsg); } SoapySDR::logf(SOAPY_SDR_INFO, "Server side stream bound to %s", data.streamSock.getsockname().c_str()); splitURL(data.streamSock.getsockname(), scheme, node, serverBindPort); //connect the stream socket to the specified port auto connectURL = combineURL("udp", remoteNode, clientBindPort); ret = data.streamSock.connect(connectURL); if (ret != 0) { const std::string errorMsg = data.streamSock.lastErrorMsg(); _streamData.erase(data.streamId); throw std::runtime_error("SoapyRemote::setupStream("+connectURL+") -- connect FAIL: " + errorMsg); } SoapySDR::logf(SOAPY_SDR_INFO, "Server side stream connected to %s", data.streamSock.getpeername().c_str()); //connect the status socket to the specified port connectURL = combineURL("udp", remoteNode, statusBindPort); ret = data.statusSock.connect(connectURL); if (ret != 0) { const std::string errorMsg = data.statusSock.lastErrorMsg(); _streamData.erase(data.streamId); throw std::runtime_error("SoapyRemote::setupStream("+connectURL+") -- connect FAIL: " + errorMsg); } SoapySDR::logf(SOAPY_SDR_INFO, "Server side status connected to %s", data.statusSock.getpeername().c_str()); //create endpoint data.endpoint = new SoapyStreamEndpoint(data.streamSock, data.statusSock, direction == SOAPY_SDR_TX, channels.size(), formatToSize(format), mtu, window); //start worker thread, this is not backwards, //receive from device means using a send endpoint //transmit to device means using a recv endpoint if (direction == SOAPY_SDR_RX) data.startSendThread(); if (direction == SOAPY_SDR_TX) data.startRecvThread(); data.startStatThread(); packer & data.streamId; packer & serverBindPort; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_CLOSE_STREAM: //////////////////////////////////////////////////////////////////// { int streamId = 0; unpacker & streamId; //cleanup data and stop worker thread auto &data = _streamData.at(streamId); data.stopThreads(); _dev->closeStream(data.stream); _streamData.erase(streamId); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_ACTIVATE_STREAM: //////////////////////////////////////////////////////////////////// { int streamId = 0; int flags = 0; long long timeNs = 0; int numElems = 0; unpacker & streamId; unpacker & flags; unpacker & timeNs; unpacker & numElems; auto &data = _streamData.at(streamId); packer & _dev->activateStream(data.stream, flags, timeNs, size_t(numElems)); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_DEACTIVATE_STREAM: //////////////////////////////////////////////////////////////////// { int streamId = 0; int flags = 0; long long timeNs = 0; unpacker & streamId; unpacker & flags; unpacker & timeNs; auto &data = _streamData.at(streamId); packer & _dev->deactivateStream(data.stream, flags, timeNs); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_LIST_ANTENNAS: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->listAntennas(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_ANTENNA: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; std::string name; unpacker & direction; unpacker & channel; unpacker & name; _dev->setAntenna(direction, channel, name); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_ANTENNA: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->getAntenna(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_HAS_DC_OFFSET_MODE: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->hasDCOffsetMode(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_DC_OFFSET_MODE: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; bool automatic = false; unpacker & direction; unpacker & channel; unpacker & automatic; _dev->setDCOffsetMode(direction, channel, automatic); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_DC_OFFSET_MODE: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->getDCOffsetMode(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_HAS_DC_OFFSET: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->hasDCOffset(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_DC_OFFSET: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; std::complex<double> offset; unpacker & direction; unpacker & channel; unpacker & offset; _dev->setDCOffset(direction, channel, offset); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_DC_OFFSET: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->getDCOffset(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_HAS_IQ_BALANCE_MODE: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->hasIQBalance(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_IQ_BALANCE_MODE: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; std::complex<double> balance; unpacker & direction; unpacker & channel; unpacker & balance; _dev->setIQBalance(direction, channel, balance); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_IQ_BALANCE_MODE: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->getIQBalance(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_LIST_GAINS: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->listGains(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_GAIN_MODE: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; bool automatic = false; unpacker & direction; unpacker & channel; unpacker & automatic; _dev->setGainMode(direction, channel, automatic); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_GAIN_MODE: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->getGainMode(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_GAIN: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; double value = 0; unpacker & direction; unpacker & channel; unpacker & value; _dev->setGain(direction, channel, value); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_GAIN_ELEMENT: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; std::string name; double value = 0; unpacker & direction; unpacker & channel; unpacker & name; unpacker & value; _dev->setGain(direction, channel, name, value); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_GAIN: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->getGain(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_GAIN_ELEMENT: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; std::string name; unpacker & direction; unpacker & channel; unpacker & name; packer & _dev->getGain(direction, channel, name); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_GAIN_RANGE: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->getGainRange(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_GAIN_RANGE_ELEMENT: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; std::string name; unpacker & direction; unpacker & channel; unpacker & name; packer & _dev->getGainRange(direction, channel, name); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_FREQUENCY: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; double value = 0; SoapySDR::Kwargs args; unpacker & direction; unpacker & channel; unpacker & value; unpacker & args; _dev->setFrequency(direction, channel, value, args); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_FREQUENCY_COMPONENT: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; std::string name; double value = 0; SoapySDR::Kwargs args; unpacker & direction; unpacker & channel; unpacker & name; unpacker & value; unpacker & args; _dev->setFrequency(direction, channel, name, value, args); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_FREQUENCY: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->getFrequency(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_FREQUENCY_COMPONENT: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; std::string name; unpacker & direction; unpacker & channel; unpacker & name; packer & _dev->getFrequency(direction, channel, name); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_LIST_FREQUENCIES: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->listFrequencies(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_FREQUENCY_RANGE: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->getFrequencyRange(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_FREQUENCY_RANGE_COMPONENT: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; std::string name; unpacker & direction; unpacker & channel; unpacker & name; packer & _dev->getFrequencyRange(direction, channel, name); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_SAMPLE_RATE: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; double rate = 0; unpacker & direction; unpacker & channel; unpacker & rate; _dev->setSampleRate(direction, channel, rate); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_SAMPLE_RATE: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->getSampleRate(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_LIST_SAMPLE_RATES: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->listSampleRates(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_BANDWIDTH: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; double bw = 0; unpacker & direction; unpacker & channel; unpacker & bw; _dev->setBandwidth(direction, channel, bw); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_BANDWIDTH: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->getBandwidth(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_LIST_BANDWIDTHS: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->listBandwidths(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_MASTER_CLOCK_RATE: //////////////////////////////////////////////////////////////////// { double rate = 0; unpacker & rate; _dev->setMasterClockRate(rate); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_MASTER_CLOCK_RATE: //////////////////////////////////////////////////////////////////// { packer & _dev->getMasterClockRate(); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_LIST_CLOCK_SOURCES: //////////////////////////////////////////////////////////////////// { packer & _dev->listClockSources(); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_CLOCK_SOURCE: //////////////////////////////////////////////////////////////////// { std::string source; unpacker & source; _dev->setClockSource(source); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_CLOCK_SOURCE: //////////////////////////////////////////////////////////////////// { packer & _dev->getClockSource(); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_LIST_TIME_SOURCES: //////////////////////////////////////////////////////////////////// { packer & _dev->listTimeSources(); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_TIME_SOURCE: //////////////////////////////////////////////////////////////////// { std::string source; unpacker & source; _dev->setTimeSource(source); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_TIME_SOURCE: //////////////////////////////////////////////////////////////////// { packer & _dev->getTimeSource(); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_HAS_HARDWARE_TIME: //////////////////////////////////////////////////////////////////// { std::string what; unpacker & what; packer & _dev->hasHardwareTime(what); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_GET_HARDWARE_TIME: //////////////////////////////////////////////////////////////////// { std::string what; unpacker & what; packer & _dev->getHardwareTime(what); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_HARDWARE_TIME: //////////////////////////////////////////////////////////////////// { long long timeNs = 0; std::string what; unpacker & timeNs; unpacker & what; _dev->setHardwareTime(timeNs, what); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_SET_COMMAND_TIME: //////////////////////////////////////////////////////////////////// { long long timeNs = 0; std::string what; unpacker & timeNs; unpacker & what; _dev->setCommandTime(timeNs, what); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_LIST_SENSORS: //////////////////////////////////////////////////////////////////// { packer & _dev->listSensors(); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_READ_SENSOR: //////////////////////////////////////////////////////////////////// { std::string name; unpacker & name; packer & _dev->readSensor(name); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_LIST_CHANNEL_SENSORS: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; unpacker & direction; unpacker & channel; packer & _dev->listSensors(direction, channel); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_READ_CHANNEL_SENSOR: //////////////////////////////////////////////////////////////////// { char direction = 0; int channel = 0; std::string name; unpacker & direction; unpacker & channel; unpacker & name; packer & _dev->readSensor(direction, channel, name); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_WRITE_REGISTER: //////////////////////////////////////////////////////////////////// { int addr = 0; int value = 0; unpacker & addr; unpacker & value; _dev->writeRegister(unsigned(addr), unsigned(value)); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_READ_REGISTER: //////////////////////////////////////////////////////////////////// { int addr = 0; unpacker & addr; packer & int(_dev->readRegister(unsigned(addr))); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_WRITE_SETTING: //////////////////////////////////////////////////////////////////// { std::string key; std::string value; unpacker & key; unpacker & value; _dev->writeSetting(key, value); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_READ_SETTING: //////////////////////////////////////////////////////////////////// { std::string key; unpacker & key; packer & _dev->readSetting(key); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_LIST_GPIO_BANKS: //////////////////////////////////////////////////////////////////// { packer & _dev->listGPIOBanks(); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_WRITE_GPIO: //////////////////////////////////////////////////////////////////// { std::string bank; int value = 0; unpacker & bank; unpacker & value; _dev->writeGPIO(bank, unsigned(value)); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_WRITE_GPIO_MASKED: //////////////////////////////////////////////////////////////////// { std::string bank; int value = 0; int mask = 0; unpacker & bank; unpacker & value; unpacker & mask; _dev->writeGPIO(bank, unsigned(value), unsigned(mask)); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_READ_GPIO: //////////////////////////////////////////////////////////////////// { std::string bank; unpacker & bank; packer & int(_dev->readGPIO(bank)); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_WRITE_GPIO_DIR: //////////////////////////////////////////////////////////////////// { std::string bank; int dir = 0; unpacker & bank; unpacker & dir; _dev->writeGPIODir(bank, unsigned(dir)); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_WRITE_GPIO_DIR_MASKED: //////////////////////////////////////////////////////////////////// { std::string bank; int dir = 0; int mask = 0; unpacker & bank; unpacker & dir; unpacker & mask; _dev->writeGPIODir(bank, unsigned(dir), unsigned(mask)); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_READ_GPIO_DIR: //////////////////////////////////////////////////////////////////// { std::string bank; unpacker & bank; packer & int(_dev->readGPIODir(bank)); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_WRITE_I2C: //////////////////////////////////////////////////////////////////// { int addr = 0; std::string data; unpacker & addr; unpacker & data; _dev->writeI2C(addr, data); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_READ_I2C: //////////////////////////////////////////////////////////////////// { int addr = 0; int numBytes = 0; unpacker & addr; unpacker & numBytes; packer & _dev->readI2C(addr, unsigned(numBytes)); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_TRANSACT_SPI: //////////////////////////////////////////////////////////////////// { int addr = 0; int data = 0; int numBits = 0; unpacker & addr; unpacker & data; unpacker & numBits; packer & int(_dev->transactSPI(addr, unsigned(data), size_t(numBits))); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_LIST_UARTS: //////////////////////////////////////////////////////////////////// { packer & _dev->listUARTs(); } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_WRITE_UART: //////////////////////////////////////////////////////////////////// { std::string which; std::string data; unpacker & which; unpacker & data; _dev->writeUART(which, data); packer & SOAPY_REMOTE_VOID; } break; //////////////////////////////////////////////////////////////////// case SOAPY_REMOTE_READ_UART: //////////////////////////////////////////////////////////////////// { std::string which; int timeoutUs = 0; unpacker & which; unpacker & timeoutUs; packer & _dev->readUART(which, long(timeoutUs)); } break; default: throw std::runtime_error( "SoapyClientHandler::handleOnce("+std::to_string(int(call))+") unknown call"); } return call != SOAPY_REMOTE_HANGUP; }
33.840747
116
0.396719
cjcliffe
9e4524c1626e6e4a249e6e3c004fb6d2bdc57ff9
4,493
cc
C++
PhysicsTools/PatExamples/bin/PatCleaningExercise.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
PhysicsTools/PatExamples/bin/PatCleaningExercise.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
PhysicsTools/PatExamples/bin/PatCleaningExercise.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include <vector> #include "TH1.h" #include "TFile.h" #include <TROOT.h> #include <TSystem.h> #include "DataFormats/Math/interface/deltaR.h" #include "DataFormats/FWLite/interface/Event.h" #include "DataFormats/Common/interface/Handle.h" #include "DataFormats/PatCandidates/interface/Jet.h" #include "FWCore/ParameterSet/interface/ProcessDesc.h" #include "FWCore/FWLite/interface/FWLiteEnabler.h" #include "PhysicsTools/FWLite/interface/TFileService.h" #include "FWCore/ParameterSetReader/interface/ProcessDescImpl.h" //using namespace std; //using namespace reco; //using namespace pat; int main(int argc, char* argv[]) { // ---------------------------------------------------------------------- // First Part: // // * enable FWLite // * book the histograms of interest // * open the input file // ---------------------------------------------------------------------- // load framework libraries gSystem->Load("libFWCoreFWLite"); FWLiteEnabler::enable(); // only allow one argument for this simple example which should be the // the python cfg file if (argc < 2) { std::cout << "Usage : " << argv[0] << " [parameters.py]" << std::endl; return 0; } // get the python configuration ProcessDescImpl builder(argv[1]); const edm::ParameterSet& fwliteParameters = builder.processDesc()->getProcessPSet()->getParameter<edm::ParameterSet>("FWLiteParams"); // now get each parameter std::string input_(fwliteParameters.getParameter<std::string>("inputFile")); std::string output_(fwliteParameters.getParameter<std::string>("outputFile")); std::string overlaps_(fwliteParameters.getParameter<std::string>("overlaps")); edm::InputTag jets_(fwliteParameters.getParameter<edm::InputTag>("jets")); // book a set of histograms fwlite::TFileService fs = fwlite::TFileService(output_); TFileDirectory theDir = fs.mkdir("analyzePatCleaning"); TH1F* emfAllJets_ = theDir.make<TH1F>("emfAllJets", "f_{emf}(All Jets)", 20, 0., 1.); TH1F* emfCleanJets_ = theDir.make<TH1F>("emfCleanJets", "f_{emf}(Clean Jets)", 20, 0., 1.); TH1F* emfOverlapJets_ = theDir.make<TH1F>("emfOverlapJets", "f_{emf}(Overlap Jets)", 20, 0., 1.); TH1F* deltaRElecJet_ = theDir.make<TH1F>("deltaRElecJet", "#DeltaR (elec, jet)", 10, 0., 0.5); TH1F* elecOverJet_ = theDir.make<TH1F>("elecOverJet", "E_{elec}/E_{jet}", 100, 0., 2.); TH1F* nOverlaps_ = theDir.make<TH1F>("nOverlaps", "Number of overlaps", 5, 0., 5.); // open input file (can be located on castor) TFile* inFile = TFile::Open(input_.c_str()); // ---------------------------------------------------------------------- // Second Part: // // * loop the events in the input file // * receive the collections of interest via fwlite::Handle // * fill the histograms // * after the loop close the input file // ---------------------------------------------------------------------- // loop the events unsigned int iEvent = 0; fwlite::Event ev(inFile); for (ev.toBegin(); !ev.atEnd(); ++ev, ++iEvent) { edm::EventBase const& event = ev; // break loop after end of file is reached // or after 1000 events have been processed if (iEvent == 1000) break; // simple event counter if (iEvent > 0 && iEvent % 1 == 0) { std::cout << " processing event: " << iEvent << std::endl; } // handle to jet collection edm::Handle<std::vector<pat::Jet> > jets; event.getByLabel(jets_, jets); // loop over the jets in the event for (std::vector<pat::Jet>::const_iterator jet = jets->begin(); jet != jets->end(); jet++) { if (jet->pt() > 20 && jet == jets->begin()) { emfAllJets_->Fill(jet->emEnergyFraction()); if (!jet->hasOverlaps(overlaps_)) { emfCleanJets_->Fill(jet->emEnergyFraction()); } else { //get all overlaps const reco::CandidatePtrVector overlaps = jet->overlaps(overlaps_); nOverlaps_->Fill(overlaps.size()); emfOverlapJets_->Fill(jet->emEnergyFraction()); //loop over the overlaps for (reco::CandidatePtrVector::const_iterator overlap = overlaps.begin(); overlap != overlaps.end(); overlap++) { float deltaR = reco::deltaR((*overlap)->eta(), (*overlap)->phi(), jet->eta(), jet->phi()); deltaRElecJet_->Fill(deltaR); elecOverJet_->Fill((*overlap)->energy() / jet->energy()); } } } } } inFile->Close(); return 0; }
37.756303
110
0.607167
ckamtsikis
9e4908e36ce15baf336b7934459ed7ff00ef8aa3
25,444
hpp
C++
disc-fe/src/evaluators/Panzer_GatherSolution_BlockedEpetra_decl.hpp
hillyuan/Panzer
13ece3ea4c145c4d7b6339e3ad6332a501932ea8
[ "BSD-3-Clause" ]
1
2022-03-22T03:49:50.000Z
2022-03-22T03:49:50.000Z
disc-fe/src/evaluators/Panzer_GatherSolution_BlockedEpetra_decl.hpp
hillyuan/Panzer
13ece3ea4c145c4d7b6339e3ad6332a501932ea8
[ "BSD-3-Clause" ]
null
null
null
disc-fe/src/evaluators/Panzer_GatherSolution_BlockedEpetra_decl.hpp
hillyuan/Panzer
13ece3ea4c145c4d7b6339e3ad6332a501932ea8
[ "BSD-3-Clause" ]
null
null
null
// @HEADER // *********************************************************************** // // Panzer: A partial differential equation assembly // engine for strongly coupled complex multiphysics systems // Copyright (2011) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact Roger P. Pawlowski (rppawlo@sandia.gov) and // Eric C. Cyr (eccyr@sandia.gov) // *********************************************************************** // @HEADER #ifndef __Panzer_GatherSolution_BlockedEpetra_decl_hpp__ #define __Panzer_GatherSolution_BlockedEpetra_decl_hpp__ /////////////////////////////////////////////////////////////////////////////// // // Include Files // /////////////////////////////////////////////////////////////////////////////// // Panzer #include "Panzer_BlockedVector_ReadOnly_GlobalEvaluationData.hpp" #include "Panzer_CloneableEvaluator.hpp" #include "Panzer_Dimension.hpp" #include "PanzerDiscFE_config.hpp" #include "Panzer_Evaluator_WithBaseImpl.hpp" #include "Panzer_Traits.hpp" // Phalanx #include "Phalanx_config.hpp" #include "Phalanx_Evaluator_Macros.hpp" #include "Phalanx_MDField.hpp" // Teuchos #include "Teuchos_ParameterList.hpp" /////////////////////////////////////////////////////////////////////////////// // // Forward Declarations // /////////////////////////////////////////////////////////////////////////////// namespace panzer { class GlobalIndexer; } namespace Thyra { template<typename> class ProductVectorBase; } namespace panzer { /** * \brief Gathers solution values from the Newton solution vector into the * nodal fields of the field manager. * * Currently makes an assumption that the stride is constant for degrees of * freedom (DOFs) and that the nmber of DOFs is equal to the size of the * solution names vector. */ template<typename EvalT, typename TRAITS, typename LO, typename GO> class GatherSolution_BlockedEpetra : public panzer::EvaluatorWithBaseImpl<TRAITS>, public PHX::EvaluatorDerived<panzer::Traits::Residual, TRAITS>, public panzer::CloneableEvaluator { public: /** * \brief The scalar type. */ typedef typename EvalT::ScalarT ScalarT; /** * \brief Constructor. * * For this unspecialized class, this constructor is empty; that is, it * doesn't do anything with the input `ParameterList`. * * \param[in] p A `ParameterList` that isn't used. */ GatherSolution_BlockedEpetra( const Teuchos::ParameterList& p) { } // end of Constructor /** * \brief Create a copy. * * For this unspecialized class, this actually just calls the Default * Constructor and doesn't copy anything. * * \param[in] pl A `ParameterList`, which is passed to the Default * Constructor. * * \returns A `GatherSolution_BlockedEpetra` created by the Default * Constructor. */ virtual Teuchos::RCP<CloneableEvaluator> clone( const Teuchos::ParameterList& pl) const { return Teuchos::rcp(new GatherSolution_BlockedEpetra<EvalT, TRAITS, LO, GO>(pl)); } // end of clone() /** * \brief Post-Registration Setup. * * For this unspecialized class, this routine does nothing. * * \param[in] d Unused. * \param[in] fm Unused. */ void postRegistrationSetup( typename TRAITS::SetupData d, PHX::FieldManager<TRAITS>& fm) { } // end of postRegistrationSetup() /** * \brief Evaluate Fields. * * For this unspecialized class, this routine does nothing, other than * tell you that you can't use it. * * \param[in] d Unused. */ void evaluateFields( typename TRAITS::EvalData d) { using PHX::print; using std::cout; using std::endl; cout << "Unspecialized version of \"GatherSolution_BlockedEpetra::" \ "evaluateFields\" on " + print<EvalT>() + "\" should not " \ "be used!" << endl; TEUCHOS_ASSERT(false); } // end of evaluateFields() }; // end of class GatherSolution_BlockedEpetra /** * \brief GatherSolution_BlockedEpetra (Residual Specialization). * * Gathers solution values from the Newton solution vector into the nodal * fields of the field manager. * * Currently makes an assumption that the stride is constant for degrees of * freedom (DOFs) and that the number of DOFs is equal to the size of the * solution names vector. */ template<typename TRAITS, typename LO, typename GO> class GatherSolution_BlockedEpetra<panzer::Traits::Residual, TRAITS, LO, GO> : public panzer::EvaluatorWithBaseImpl<TRAITS>, public PHX::EvaluatorDerived<panzer::Traits::Residual, TRAITS>, public panzer::CloneableEvaluator { public: /** * \brief Constructor. * * Simply saves the input `indexers` as this object's `indexers_`. * * \param[in] indexers The `vector` of `GlobalIndexer`s that * handle the global unknown numbering. */ GatherSolution_BlockedEpetra( const std::vector<Teuchos::RCP<const GlobalIndexer>>& indexers) : indexers_(indexers) { } // end of Constructor /** * \brief Initializing Constructor. * * Saves the input `indexers` as this object's `indexers_`, allocates * fields, sets up dependent tangent fields (if requested), and * determines the first active name. * * \param[in] indexers The `vector` of `GlobalIndexer`s that * handle the global unknown numbering. * \param[in] p A `ParameterList` used as input for * `GatherSolution_Input`. */ GatherSolution_BlockedEpetra( const std::vector<Teuchos::RCP<const GlobalIndexer>>& indexers, const Teuchos::ParameterList& p); /** * \brief Post-Registration Setup. * * Loops over the `gatherFields_` and sets the `indexerIds_` and * `subFieldIds_`. * * \param[in] d Unused. * \param[in] fm Unused. */ void postRegistrationSetup( typename TRAITS::SetupData d, PHX::FieldManager<TRAITS>& fm); /** * \brief Pre-Evaluate: Sets the solution vector. * * If using a `BlockedVector_ReadOnly_GlobalEvaluationData`, this saves * it for use later in `evaluateFields()`. If using the older * `BlockedEpetraLinearObjContainer`, this sets the solution vector. * * \param[in] d The `PreEvalData` containing the * `GlobalEvaluationDataContainer`. */ void preEvaluate( typename TRAITS::PreEvalData d); /** * \brief Evaluate Fields: Gather operation. * * Loops over the fields to be gathered, the cells in the workset, and * the basis functions, and fills in the fields. * * \param[in] d The `Workset` on which we're going to do all the work. */ void evaluateFields( typename TRAITS::EvalData d); /** * \brief Create a copy. * * Creates a `GatherSolution_BlockedEpetra` using the Initializing * Constructor and the current object's `indexers_`. * * \param[in] pl A `ParameterList` used as input for * `GatherSolution_Input`. * * \returns A `GatherSolution_BlockedEpetra` constructed with this * object's `indexers_` and the input `ParameterList`. */ virtual Teuchos::RCP<CloneableEvaluator> clone( const Teuchos::ParameterList& pl) const { using panzer::Traits; using Teuchos::rcp; return rcp(new GatherSolution_BlockedEpetra<Traits::Residual, TRAITS, LO, GO> (indexers_, pl)); } // end of clone() private: /** * \brief The evaluation type. */ typedef typename panzer::Traits::Residual EvalT; /** * \brief The scalar type. */ typedef typename panzer::Traits::Residual::ScalarT ScalarT; /** * \brief These map the local (field, element, basis) triplet to a * global ID for scattering. */ std::vector<Teuchos::RCP<const GlobalIndexer>> indexers_; /** * \brief The block index into `indexers_`. */ std::vector<int> indexerIds_; /** * \brief Sub-field IDs, which need to be mapped. */ std::vector<int> subFieldIds_; /** * \brief The fields to be gathered. */ std::vector<PHX::MDField<ScalarT, Cell, NODE>> gatherFields_; /** * \brief A list of the names of the fields to be gathered. */ std::vector<std::string> indexerNames_; /** * \brief A flag indicating whether we should be working with \f$ x \f$ * or \f$ \dot{x} \f$. */ bool useTimeDerivativeSolutionVector_; /** * \brief The key identifying the `GlobalEvaluationData`. */ std::string globalDataKey_; /** * \brief The solution vector. */ Teuchos::RCP<Thyra::ProductVectorBase<double>> x_; /** * \brief The `GlobalEvaluationData` containing both the owned and * ghosted solution vectors. */ Teuchos::RCP<panzer::BlockedVector_ReadOnly_GlobalEvaluationData> xBvRoGed_; /** * \brief A flag indicating whether or not we have tangent fields. */ bool hasTangentFields_; /** * \brief Fields for storing the tangent components * \f$\left(\frac{dx}{dp}\right)\f$ of the solution vector * \f$(x)\f$. * * These are not actually used by the residual specialization of this * evaluator, even if they are supplied, but it is useful to declare * them as dependencies anyway when saving the tangent components to the * output file. */ std::vector<std::vector<PHX::MDField<const ScalarT, Cell, NODE>>> tangentFields_; /** * \brief Default Constructor (disabled) */ GatherSolution_BlockedEpetra(); }; // end of class GatherSolution_BlockedEpetra (Residual Specialization) /** * \brief GatherSolution_BlockedEpetra (Tangent Specialization). * * Gathers solution values from the Newton solution vector into the nodal * fields of the field manager. * * Currently makes an assumption that the stride is constant for degrees of * freedom (DOFs) and that the nmber of DOFs is equal to the size of the * solution names vector. */ template<typename TRAITS, typename LO, typename GO> class GatherSolution_BlockedEpetra<panzer::Traits::Tangent, TRAITS, LO, GO> : public panzer::EvaluatorWithBaseImpl<TRAITS>, public PHX::EvaluatorDerived<panzer::Traits::Tangent, TRAITS>, public panzer::CloneableEvaluator { public: /** * \brief Constructor. * * Simply saves the input `indexers` as this object's `indexers_`. * * \param[in] indexers The `vector` of `GlobalIndexer`s that * handle the global unknown numbering. */ GatherSolution_BlockedEpetra( const std::vector<Teuchos::RCP<const GlobalIndexer>>& indexers) : indexers_(indexers) { } // end of Constructor /** * \brief Initializing Constructor. * * Saves the input `indexers` as this object's `indexers_`, allocates * fields, sets up dependent tangent fields (if requested), and * determines the first active name. * * \param[in] indexers The `vector` of `GlobalIndexer`s that * handle the global unknown numbering. * \param[in] p A `ParameterList` used as input for * `GatherSolution_Input`. */ GatherSolution_BlockedEpetra( const std::vector<Teuchos::RCP<const GlobalIndexer>>& indexers, const Teuchos::ParameterList& p); /** * \brief Post-Registration Setup. * * Loops over the `gatherFields_` and sets the `indexerIds_` and * `subFieldIds_`. * * \param[in] d Unused. * \param[in] fm Unused. */ void postRegistrationSetup( typename TRAITS::SetupData d, PHX::FieldManager<TRAITS>& fm); /** * \brief Pre-Evaluate: Sets the solution vector. * * If using a `BlockedVector_ReadOnly_GlobalEvaluationData`, this saves * it for use later in `evaluateFields()`. If using the older * `BlockedEpetraLinearObjContainer`, this sets the solution vector. * * \param[in] d The `PreEvalData` containing the * `GlobalEvaluationDataContainer`. */ void preEvaluate( typename TRAITS::PreEvalData d); /** * \brief Evaluate Fields: Gather operation. * * Loops over the fields to be gathered, the cells in the workset, and * the basis functions, and fills in the fields. Also sets derivative * information if tangent fields are enabled. * * \param[in] d The `Workset` on which we're going to do all the work. */ void evaluateFields( typename TRAITS::EvalData d); /** * \brief Create a copy. * * Creates a `GatherSolution_BlockedEpetra` using the Initializing * Constructor and the current object's `indexers_`. * * \param[in] pl A `ParameterList` used as input for * `GatherSolution_Input`. * * \returns A `GatherSolution_BlockedEpetra` constructed with this * object's `indexers_` and the input `ParameterList`. */ virtual Teuchos::RCP<CloneableEvaluator> clone( const Teuchos::ParameterList& pl) const { using panzer::Traits; using Teuchos::rcp; return rcp(new GatherSolution_BlockedEpetra<Traits::Tangent, TRAITS, LO, GO> (indexers_, pl)); } // end of clone() private: /** * \brief The evaluation type. */ typedef typename panzer::Traits::Tangent EvalT; /** * \brief The scalar type. */ typedef typename panzer::Traits::Tangent::ScalarT ScalarT; /** * \brief These map the local (field, element, basis) triplet to a * global ID for scattering. */ std::vector<Teuchos::RCP<const GlobalIndexer>> indexers_; /** * \brief The block index into `indexers_`. */ std::vector<int> indexerIds_; /** * \brief Sub-field IDs, which need to be mapped. */ std::vector<int> subFieldIds_; /** * \brief The fields to be gathered. */ std::vector<PHX::MDField<ScalarT, Cell, NODE>> gatherFields_; /** * \brief A list of the names of the fields to be gathered. */ std::vector<std::string> indexerNames_; /** * \brief A flag indicating whether we should be working with \f$ x \f$ * or \f$ \dot{x} \f$. */ bool useTimeDerivativeSolutionVector_; /** * \brief The key identifying the `GlobalEvaluationData`. */ std::string globalDataKey_; /** * \brief The solution vector. */ Teuchos::RCP<Thyra::ProductVectorBase<double>> x_; /** * \brief The `GlobalEvaluationData` containing both the owned and * ghosted solution vectors. */ Teuchos::RCP<panzer::BlockedVector_ReadOnly_GlobalEvaluationData> xBvRoGed_; /** * \brief A flag indicating whether or not we have tangent fields. */ bool hasTangentFields_; /** * \brief Fields for storing the tangent components * \f$\left(\frac{dx}{dp}\right)\f$ of the solution vector * \f$(x)\f$. * * These are not actually used by the residual specialization of this * evaluator, even if they are supplied, but it is useful to declare * them as dependencies anyway when saving the tangent components to the * output file. */ std::vector<std::vector<PHX::MDField<const ScalarT, Cell, NODE>>> tangentFields_; /** * \brief Default Constructor (disabled) */ GatherSolution_BlockedEpetra(); }; // end of class GatherSolution_BlockedEpetra (Tangent Specialization) /** * \brief GatherSolution_BlockedEpetra (Jacobian Specialization). * * Gathers solution values from the Newton solution vector into the nodal * fields of the field manager. * * Currently makes an assumption that the stride is constant for degrees of * freedom (DOFs) and that the nmber of DOFs is equal to the size of the * solution names vector. */ template<typename TRAITS, typename LO, typename GO> class GatherSolution_BlockedEpetra<panzer::Traits::Jacobian, TRAITS, LO, GO> : public panzer::EvaluatorWithBaseImpl<TRAITS>, public PHX::EvaluatorDerived<panzer::Traits::Jacobian, TRAITS>, public panzer::CloneableEvaluator { public: /** * \brief Constructor. * * Simply saves the input `indexers` as this object's `indexers_`. * * \param[in] indexers The `vector` of `GlobalIndexer`s that * handle the global unknown numbering. */ GatherSolution_BlockedEpetra( const std::vector<Teuchos::RCP<const GlobalIndexer>>& indexers) : indexers_(indexers) { } // end of Constructor /** * \brief Initializing Constructor. * * Saves the input `indexers` as this object's `indexers_`, allocates * fields, sets up dependent tangent fields (if requested), and * determines the first active name. * * \param[in] indexers The `vector` of `GlobalIndexer`s that * handle the global unknown numbering. * \param[in] p A `ParameterList` used as input for * `GatherSolution_Input`. */ GatherSolution_BlockedEpetra( const std::vector<Teuchos::RCP<const GlobalIndexer>>& indexers, const Teuchos::ParameterList& p); /** * \brief Post-Registration Setup. * * Loops over the `gatherFields_` and sets the `indexerIds_` and * `subFieldIds_`. * * \param[in] d Unused. * \param[in] fm Unused. */ void postRegistrationSetup( typename TRAITS::SetupData d, PHX::FieldManager<TRAITS>& fm); /** * \brief Pre-Evaluate: Sets the solution vector. * * If using a `BlockedVector_ReadOnly_GlobalEvaluationData`, this saves * it for use later in `evaluateFields()`. If using the older * `BlockedEpetraLinearObjContainer`, this sets the solution vector. * Also determines whether or not to apply sensitivities. * * \param[in] d The `PreEvalData` containing the * `GlobalEvaluationDataContainer`. */ void preEvaluate( typename TRAITS::PreEvalData d); /** * \brief Evaluate Fields: Gather operation. * * Loops over the fields to be gathered, the cells in the workset, and * the basis functions, and fills in the fields. If sensitivities are * to be applied, this also seeds the derivatives. * * \param[in] d The `Workset` on which we're going to do all the work. */ void evaluateFields( typename TRAITS::EvalData d); /** * \brief Create a copy. * * Creates a `GatherSolution_BlockedEpetra` using the Initializing * Constructor and the current object's `indexers_`. * * \param[in] pl A `ParameterList` used as input for * `GatherSolution_Input`. * * \returns A `GatherSolution_BlockedEpetra` constructed with this * object's `indexers_` and the input `ParameterList`. */ virtual Teuchos::RCP<CloneableEvaluator> clone( const Teuchos::ParameterList& pl) const { using panzer::Traits; using Teuchos::rcp; return rcp(new GatherSolution_BlockedEpetra<Traits::Jacobian, TRAITS, LO, GO> (indexers_, pl)); } // end of clone() private: /** * \brief The evaluation type. */ typedef typename panzer::Traits::Jacobian EvalT; /** * \brief The scalar type. */ typedef typename panzer::Traits::Jacobian::ScalarT ScalarT; /** * \brief These map the local (field, element, basis) triplet to a * global ID for scattering. */ std::vector<Teuchos::RCP<const GlobalIndexer>> indexers_; /** * \brief The block index into `indexers_`. */ std::vector<int> indexerIds_; /** * \brief Sub-field IDs, which need to be mapped. */ std::vector<int> subFieldIds_; /** * \brief The fields to be gathered. */ std::vector<PHX::MDField<ScalarT, Cell, NODE>> gatherFields_; /** * \brief A list of the names of the fields to be gathered. */ std::vector<std::string> indexerNames_; /** * \brief A flag indicating whether we should be working with \f$ x \f$ * or \f$ \dot{x} \f$. */ bool useTimeDerivativeSolutionVector_; /** * \brief Flag to disable sensitivities absolutely. */ bool disableSensitivities_; /** * \brief Sets which gather operations have sensitivities. */ std::string sensitivitiesName_; /** * \brief Used by `evaluateFields()` to turn on/off a certain set of * sensitivities. */ bool applySensitivities_; /** * \brief The key identifying the `GlobalEvaluationData`. */ std::string globalDataKey_; /** * \brief Which gather seed in the workset to use. * * If it's less than zero, then use alpha or beta as appropriate. */ int gatherSeedIndex_; /** * \brief The solution vector. */ Teuchos::RCP<Thyra::ProductVectorBase<double>> x_; /** * \brief The `GlobalEvaluationData` containing both the owned and * ghosted solution vectors. */ Teuchos::RCP<panzer::BlockedVector_ReadOnly_GlobalEvaluationData> xBvRoGed_; /** * \brief Default Constructor (disabled) */ GatherSolution_BlockedEpetra(); }; // end of class GatherSolution_BlockedEpetra (Jacobian Specialization) } // end of namespace panzer #ifdef Panzer_BUILD_HESSIAN_SUPPORT #include "Panzer_GatherSolution_BlockedEpetra_Hessian.hpp" #endif // Panzer_BUILD_HESSIAN_SUPPORT #endif // __Panzer_GatherSolution_BlockedEpetra_decl_hpp__
31.964824
79
0.591141
hillyuan
9e4a6a22b25123d459a150af8cd659e1bbbd7a3c
25,168
cpp
C++
code/Plugins/Renderer/Direct3D11/Source/T3DD3D11Mappings.cpp
answerear/Fluid
7b7992547a7d3ac05504dd9127e779eeeaddb3ab
[ "MIT" ]
1
2021-11-16T15:11:52.000Z
2021-11-16T15:11:52.000Z
code/Plugins/Renderer/Direct3D11/Source/T3DD3D11Mappings.cpp
answerear/Fluid
7b7992547a7d3ac05504dd9127e779eeeaddb3ab
[ "MIT" ]
null
null
null
code/Plugins/Renderer/Direct3D11/Source/T3DD3D11Mappings.cpp
answerear/Fluid
7b7992547a7d3ac05504dd9127e779eeeaddb3ab
[ "MIT" ]
null
null
null
/******************************************************************************* * This file is part of Tiny3D (Tiny 3D Graphic Rendering Engine) * Copyright (C) 2015-2020 Answer Wong * For latest info, see https://github.com/answerear/Tiny3D * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ #include "T3DD3D11Mappings.h" #include "T3DD3D11Context.h" namespace Tiny3D { //-------------------------------------------------------------------------- const char * const D3D11Mappings::POSITION = "POSITION"; const char * const D3D11Mappings::BLENDWEIGHT = "BLENDWEIGHT"; const char * const D3D11Mappings::BLENDINDICES = "BLENDINDICES"; const char * const D3D11Mappings::NORMAL = "NORMAL"; const char * const D3D11Mappings::COLOR = "COLOR"; const char * const D3D11Mappings::TEXCOORD = "TEXCOORD"; const char * const D3D11Mappings::TANGENT = "TANGENT"; const char * const D3D11Mappings::BINORMAL = "BINORMAL"; //-------------------------------------------------------------------------- const char *D3D11Mappings::get(VertexAttribute::Semantic semantic) { switch (semantic) { case VertexAttribute::Semantic::E_VAS_POSITION: return POSITION; break; case VertexAttribute::Semantic::E_VAS_BLENDWEIGHT: return BLENDWEIGHT; break; case VertexAttribute::Semantic::E_VAS_BLENDINDICES: return BLENDINDICES; break; case VertexAttribute::Semantic::E_VAS_NORMAL: return NORMAL; break; case VertexAttribute::Semantic::E_VAS_DIFFUSE: case VertexAttribute::Semantic::E_VAS_SPECULAR: return COLOR; break; case VertexAttribute::Semantic::E_VAS_TEXCOORD: return TEXCOORD; break; case VertexAttribute::Semantic::E_VAS_TANGENT: return TANGENT; break; case VertexAttribute::Semantic::E_VAS_BINORMAL: return BINORMAL; break; } return nullptr; } //-------------------------------------------------------------------------- DXGI_FORMAT D3D11Mappings::get(VertexAttribute::Type type) { DXGI_FORMAT d3dformat; switch (type) { case VertexAttribute::Type::E_VAT_COLOR: d3dformat = DXGI_FORMAT_R32G32B32A32_FLOAT; break; case VertexAttribute::Type::E_VAT_FLOAT1: d3dformat = DXGI_FORMAT_R32_FLOAT; break; case VertexAttribute::Type::E_VAT_FLOAT2: d3dformat = DXGI_FORMAT_R32G32_FLOAT; break; case VertexAttribute::Type::E_VAT_FLOAT3: d3dformat = DXGI_FORMAT_R32G32B32_FLOAT; break; case VertexAttribute::Type::E_VAT_FLOAT4: d3dformat = DXGI_FORMAT_R32G32B32A32_FLOAT; break; case VertexAttribute::Type::E_VAT_SHORT2: d3dformat = DXGI_FORMAT_R16G16_SINT; break; case VertexAttribute::Type::E_VAT_SHORT4: d3dformat = DXGI_FORMAT_R16G16B16A16_SINT; break; case VertexAttribute::Type::E_VAT_UBYTE4: d3dformat = DXGI_FORMAT_R8G8B8A8_UINT; break; } return d3dformat; } //-------------------------------------------------------------------------- D3D11_PRIMITIVE_TOPOLOGY D3D11Mappings::get(RenderContext::PrimitiveType primitive) { D3D11_PRIMITIVE_TOPOLOGY d3dPrimitive; switch (primitive) { case RenderContext::PrimitiveType::E_PT_POINT_LIST: d3dPrimitive = D3D11_PRIMITIVE_TOPOLOGY_POINTLIST; break; case RenderContext::PrimitiveType::E_PT_LINE_LIST: d3dPrimitive = D3D11_PRIMITIVE_TOPOLOGY_LINELIST; break; case RenderContext::PrimitiveType::E_PT_LINE_STRIP: d3dPrimitive = D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP; break; case RenderContext::PrimitiveType::E_PT_TRIANGLE_LIST: d3dPrimitive = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; break; case RenderContext::PrimitiveType::E_PT_TRIANGLE_STRIP: d3dPrimitive = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; break; default: d3dPrimitive = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST; break; } return d3dPrimitive; } //-------------------------------------------------------------------------- DXGI_FORMAT D3D11Mappings::get(HardwareIndexBuffer::Type idxType) { DXGI_FORMAT d3dFormat; switch (idxType) { case HardwareIndexBuffer::Type::E_IT_16BITS: d3dFormat = DXGI_FORMAT_R16_UINT; break; case HardwareIndexBuffer::Type::E_IT_32BITS: d3dFormat = DXGI_FORMAT_R32_UINT; break; default: d3dFormat = DXGI_FORMAT_R16_UINT; break; } return d3dFormat; } //-------------------------------------------------------------------------- TResult D3D11Mappings::get(HardwareBuffer::Usage usage, uint32_t mode, D3D11_USAGE &d3dUsage, uint32_t &d3dAccessFlag) { TResult ret = T3D_OK; do { switch (usage) { case HardwareBuffer::Usage::STATIC: { if (mode == HardwareBuffer::AccessMode::CPU_NONE) { // 静态缓冲,CPU不可读写,只能初始化时候设置数据 d3dUsage = D3D11_USAGE_IMMUTABLE; d3dAccessFlag = 0; } else if (mode == HardwareBuffer::AccessMode::CPU_WRITE) { d3dUsage = D3D11_USAGE_DEFAULT; d3dAccessFlag = 0; } else { // 其他 CPU 访问标签在这里都是非法 ret = T3D_ERR_INVALID_PARAM; T3D_LOG_ERROR(LOG_TAG_D3D11RENDERER, "Usage is STATIC, so access mode must be CPU_NONE " "or CPU_WRITE !"); } } break; case HardwareBuffer::Usage::DYNAMIC: case HardwareBuffer::Usage::STREAM: { if (mode == HardwareBuffer::AccessMode::CPU_NONE) { // CPU不读也不写,这里建议使用STATIC性能更好 d3dUsage = D3D11_USAGE_DEFAULT; d3dAccessFlag = 0; T3D_LOG_WARNING(LOG_TAG_D3D11RENDERER, "Usage is DYNAMIC, but CPU access mode is CPU_NONE." " Here suggests STATIC instead of DYNAMIC !"); } else if ((mode == (HardwareBuffer::AccessMode::CPU_READ | HardwareBuffer::AccessMode::CPU_WRITE))) { // CPU读写,GPU读写 d3dUsage = D3D11_USAGE_STAGING; d3dAccessFlag = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ; } else if (mode == HardwareBuffer::AccessMode::CPU_READ) { // CPU读,GPU读写 d3dUsage = D3D11_USAGE_STAGING; d3dAccessFlag = D3D11_CPU_ACCESS_READ; } else if (mode == HardwareBuffer::AccessMode::CPU_WRITE) { // CPU写,GPU读 d3dUsage = D3D11_USAGE_DYNAMIC; d3dAccessFlag = D3D11_CPU_ACCESS_WRITE; } else if (mode == HardwareBuffer::AccessMode::GPU_COPY) { // CPU读写,GPU读写 d3dUsage = D3D11_USAGE_STAGING; d3dAccessFlag = D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ; } else { // 无效 CPU 访问方式参数 ret = T3D_ERR_INVALID_PARAM; T3D_LOG_ERROR(LOG_TAG_D3D11RENDERER, "Invalid CPU access mode parameter !"); } } break; default: { ret = T3D_ERR_INVALID_PARAM; } break; } } while (0); return ret; } //-------------------------------------------------------------------------- D3D11_MAP D3D11Mappings::get(HardwareBuffer::LockOptions options) { D3D11_MAP d3dOpt = D3D11_MAP_READ; switch (options) { case HardwareBuffer::LockOptions::READ: { d3dOpt = D3D11_MAP_READ; } break; case HardwareBuffer::LockOptions::WRITE: { d3dOpt = D3D11_MAP_WRITE; } break; case HardwareBuffer::LockOptions::READ_WRITE: { d3dOpt = D3D11_MAP_READ_WRITE; } break; case HardwareBuffer::LockOptions::WRITE_DISCARD: { d3dOpt = D3D11_MAP_WRITE_DISCARD; } break; case HardwareBuffer::LockOptions::WRITE_NO_OVERWRITE: { d3dOpt = D3D11_MAP_WRITE_NO_OVERWRITE; } break; default: { T3D_LOG_ERROR(LOG_TAG_D3D11RENDERER, "Invalid LockOptions !"); } break; } return d3dOpt; } //-------------------------------------------------------------------------- DXGI_FORMAT D3D11Mappings::get(PixelFormat format) { DXGI_FORMAT fmt; switch (format) { case PixelFormat::E_PF_PALETTE8: break; case PixelFormat::E_PF_R5G6B5: break; case PixelFormat::E_PF_A1R5G5B5: break; case PixelFormat::E_PF_A4R4G4B4: break; case PixelFormat::E_PF_R8G8B8: break; case PixelFormat::E_PF_B8G8R8: break; case PixelFormat::E_PF_A8R8G8B8: fmt = DXGI_FORMAT_R8G8B8A8_UNORM; break; case PixelFormat::E_PF_B8G8R8A8: break; case PixelFormat::E_PF_X8R8G8B8: break; case PixelFormat::E_PF_B8G8R8X8: break; } return fmt; } //-------------------------------------------------------------------------- D3D11_COMPARISON_FUNC D3D11Mappings::get(CompareFunction func) { switch (func) { case CompareFunction::ALWAYS_FAIL: return D3D11_COMPARISON_NEVER; case CompareFunction::ALWAYS_PASS: return D3D11_COMPARISON_ALWAYS; case CompareFunction::LESS: return D3D11_COMPARISON_LESS; case CompareFunction::LESS_EQUAL: return D3D11_COMPARISON_LESS_EQUAL; case CompareFunction::EQUAL: return D3D11_COMPARISON_EQUAL; case CompareFunction::NOT_EQUAL: return D3D11_COMPARISON_NOT_EQUAL; case CompareFunction::GREATER_EQUAL: return D3D11_COMPARISON_GREATER_EQUAL; case CompareFunction::GREATER: return D3D11_COMPARISON_GREATER; }; return D3D11_COMPARISON_ALWAYS; } //-------------------------------------------------------------------------- D3D11_BLEND D3D11Mappings::get(BlendFactor factor) { switch (factor) { case BlendFactor::ONE: return D3D11_BLEND_ONE; case BlendFactor::ZERO: return D3D11_BLEND_ZERO; case BlendFactor::DEST_COLOR: return D3D11_BLEND_DEST_COLOR; case BlendFactor::SOURCE_COLOR: return D3D11_BLEND_SRC_COLOR; case BlendFactor::ONE_MINUS_DEST_COLOR: return D3D11_BLEND_INV_DEST_COLOR; case BlendFactor::ONE_MINUS_SOURCE_COLOR: return D3D11_BLEND_INV_SRC_COLOR; case BlendFactor::DEST_ALPHA: return D3D11_BLEND_DEST_ALPHA; case BlendFactor::SOURCE_ALPHA: return D3D11_BLEND_SRC_ALPHA; case BlendFactor::ONE_MINUS_DEST_ALPHA: return D3D11_BLEND_INV_DEST_ALPHA; case BlendFactor::ONE_MINUS_SOURCE_ALPHA: return D3D11_BLEND_INV_SRC_ALPHA; } return D3D11_BLEND_ONE; } //-------------------------------------------------------------------------- D3D11_BLEND_OP D3D11Mappings::get(BlendOperation op) { switch (op) { case BlendOperation::ADD: return D3D11_BLEND_OP_ADD; case BlendOperation::SUBTRACT: return D3D11_BLEND_OP_SUBTRACT; case BlendOperation::REVERSE_SUBTRACT: return D3D11_BLEND_OP_REV_SUBTRACT; case BlendOperation::MIN: return D3D11_BLEND_OP_MIN; case BlendOperation::MAX: return D3D11_BLEND_OP_MAX; } return D3D11_BLEND_OP_ADD; } //-------------------------------------------------------------------------- void D3D11Mappings::get(D3D11_BLEND_DESC &desc, const BlendState& state) { desc.AlphaToCoverageEnable = state.isAlpha2CoverageEnabled() ? TRUE : FALSE; desc.IndependentBlendEnable = state.isIndependentBlendEnabled(); if (desc.IndependentBlendEnable) { for (int32_t i = 0; i < BlendState::MAX_RENDER_TARGET; ++i) { desc.RenderTarget[i].BlendEnable = state.isBlendEnabled(i) ? TRUE : FALSE; desc.RenderTarget[i].SrcBlend = get(state.getSrcBlend(i)); desc.RenderTarget[i].DestBlend = get(state.getDstBlend(i)); desc.RenderTarget[i].BlendOp = get(state.getBlendOp(i)); desc.RenderTarget[i].SrcBlendAlpha = get(state.getSrcBlendAlpha(i)); desc.RenderTarget[i].DestBlendAlpha = get(state.getDstBlendAlpha(i)); desc.RenderTarget[i].BlendOpAlpha = get(state.getBlendOpAlpha(i)); desc.RenderTarget[i].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; } } else { desc.RenderTarget[0].BlendEnable = state.isBlendEnabled(0) ? TRUE : FALSE; desc.RenderTarget[0].SrcBlend = get(state.getSrcBlend(0)); desc.RenderTarget[0].DestBlend = get(state.getDstBlend(0)); desc.RenderTarget[0].BlendOp = get(state.getBlendOp(0)); desc.RenderTarget[0].SrcBlendAlpha = get(state.getSrcBlendAlpha(0)); desc.RenderTarget[0].DestBlendAlpha = get(state.getDstBlendAlpha(0)); desc.RenderTarget[0].BlendOpAlpha = get(state.getBlendOpAlpha(0)); desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; } } //-------------------------------------------------------------------------- D3D11_DEPTH_WRITE_MASK D3D11Mappings::get(DepthWriteMask mask) { switch (mask) { case DepthWriteMask::ZERO: return D3D11_DEPTH_WRITE_MASK_ZERO; case DepthWriteMask::ALL: return D3D11_DEPTH_WRITE_MASK_ALL; } return D3D11_DEPTH_WRITE_MASK_ALL; } //-------------------------------------------------------------------------- D3D11_STENCIL_OP D3D11Mappings::get(StencilOp op) { switch (op) { case StencilOp::KEEP: return D3D11_STENCIL_OP_KEEP; case StencilOp::ZERO: return D3D11_STENCIL_OP_ZERO; case StencilOp::REPLACE: return D3D11_STENCIL_OP_REPLACE; case StencilOp::INCR: return D3D11_STENCIL_OP_INCR_SAT; case StencilOp::INCR_WRAP: return D3D11_STENCIL_OP_INCR; case StencilOp::DECR: return D3D11_STENCIL_OP_DECR_SAT; case StencilOp::DECR_WRAP: return D3D11_STENCIL_OP_DECR; case StencilOp::INVERT: return D3D11_STENCIL_OP_INVERT; } return D3D11_STENCIL_OP_KEEP; } //-------------------------------------------------------------------------- void D3D11Mappings::get(D3D11_DEPTH_STENCIL_DESC &desc, const DepthStencilState& state) { desc.DepthEnable = state.isDepthTestEnabled() ? TRUE : FALSE; desc.DepthWriteMask = get(state.getDepthWriteMask()); desc.DepthFunc = get(state.getDepthFunction()); desc.StencilEnable = state.isStencilEnabled() ? TRUE : FALSE; desc.StencilReadMask = state.getStencilReadMask(); desc.StencilWriteMask = state.getStencilWriteMask(); StencilOp stencilFailOp, depthFailOp, passOp; state.getStencilOp(stencilFailOp, depthFailOp, passOp); desc.FrontFace.StencilFailOp = get(stencilFailOp); desc.FrontFace.StencilDepthFailOp = get(depthFailOp); desc.FrontFace.StencilPassOp = get(passOp); desc.FrontFace.StencilFunc = get(state.getStencilFunction()); } //-------------------------------------------------------------------------- D3D11_FILL_MODE D3D11Mappings::get(PolygonMode mode) { D3D11_FILL_MODE d3dMode = D3D11_FILL_SOLID; switch (mode) { case PolygonMode::POINT: case PolygonMode::WIREFRAME: d3dMode = D3D11_FILL_WIREFRAME; break; default: d3dMode = D3D11_FILL_SOLID; break; } return d3dMode; } //-------------------------------------------------------------------------- D3D11_CULL_MODE D3D11Mappings::get(CullingMode mode) { D3D11_CULL_MODE d3dMode = D3D11_CULL_NONE; switch (mode) { case CullingMode::CLOCKWISE: d3dMode = D3D11_CULL_BACK; break; case CullingMode::ANTICLOCKWISE: d3dMode = D3D11_CULL_FRONT; break; default: d3dMode = D3D11_CULL_NONE; break; } return d3dMode; } //-------------------------------------------------------------------------- void D3D11Mappings::get(D3D11_RASTERIZER_DESC &desc, const RasterizerState& state) { desc.FillMode = get(state.getPolygonMode()); desc.CullMode = get(state.getCullingMode()); desc.FrontCounterClockwise = TRUE; desc.DepthBias = state.getDepthBias(); desc.DepthBiasClamp = state.getDepthBiasClamp(); desc.SlopeScaledDepthBias = state.getSlopeScaledDepthBias(); desc.DepthClipEnable = state.isDepthClipEnabled() ? TRUE : FALSE; desc.ScissorEnable = state.isScissorEnabled() ? TRUE : FALSE; desc.MultisampleEnable = state.isMSAAEnabled() ? TRUE : FALSE; desc.AntialiasedLineEnable = FALSE; } //-------------------------------------------------------------------------- D3D11_TEXTURE_ADDRESS_MODE D3D11Mappings::get(TextureAddressMode mode) { if (D3D11_CONTEXT.getFeatureLevel() == D3D_FEATURE_LEVEL_9_1) return D3D11_TEXTURE_ADDRESS_WRAP; switch (mode) { case TextureAddressMode::WRAP: return D3D11_TEXTURE_ADDRESS_WRAP; case TextureAddressMode::MIRROR: return D3D11_TEXTURE_ADDRESS_MIRROR; case TextureAddressMode::CLAMP: return D3D11_TEXTURE_ADDRESS_CLAMP; case TextureAddressMode::BORDER: return D3D11_TEXTURE_ADDRESS_BORDER; } return D3D11_TEXTURE_ADDRESS_WRAP; } //-------------------------------------------------------------------------- D3D11_FILTER D3D11Mappings::get(FilterOptions min, FilterOptions mag, FilterOptions mip, bool comparison /* = false */) { if (min == FilterOptions::ANISOTROPIC || mag == FilterOptions::ANISOTROPIC || mip == FilterOptions::ANISOTROPIC) return comparison ? D3D11_FILTER_COMPARISON_ANISOTROPIC : D3D11_FILTER_ANISOTROPIC; // FilterOptions::FilterOptions::NONE is not supported #define MERGE_FOR_SWITCH(_comparison_, _min_ , _mag_, _mip_ ) \ ((_comparison_ ? 8 : 0) | (_min_ == FilterOptions::LINEAR ? 4 : 0) | (_mag_ == FilterOptions::LINEAR ? 2 : 0) | (_mip_ == FilterOptions::LINEAR ? 1 : 0)) switch ((MERGE_FOR_SWITCH(comparison, min, mag, mip))) { case MERGE_FOR_SWITCH(true, FilterOptions::POINT, FilterOptions::POINT, FilterOptions::POINT): return D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT; case MERGE_FOR_SWITCH(true, FilterOptions::POINT, FilterOptions::POINT, FilterOptions::LINEAR): return D3D11_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR; case MERGE_FOR_SWITCH(true, FilterOptions::POINT, FilterOptions::LINEAR, FilterOptions::POINT): return D3D11_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT; case MERGE_FOR_SWITCH(true, FilterOptions::POINT, FilterOptions::LINEAR, FilterOptions::LINEAR): return D3D11_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR; case MERGE_FOR_SWITCH(true, FilterOptions::LINEAR, FilterOptions::POINT, FilterOptions::POINT): return D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT; case MERGE_FOR_SWITCH(true, FilterOptions::LINEAR, FilterOptions::POINT, FilterOptions::LINEAR): return D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR; case MERGE_FOR_SWITCH(true, FilterOptions::LINEAR, FilterOptions::LINEAR, FilterOptions::POINT): return D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT; case MERGE_FOR_SWITCH(true, FilterOptions::LINEAR, FilterOptions::LINEAR, FilterOptions::LINEAR): return D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR; case MERGE_FOR_SWITCH(false, FilterOptions::POINT, FilterOptions::POINT, FilterOptions::POINT): return D3D11_FILTER_MIN_MAG_MIP_POINT; case MERGE_FOR_SWITCH(false, FilterOptions::POINT, FilterOptions::POINT, FilterOptions::LINEAR): return D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR; case MERGE_FOR_SWITCH(false, FilterOptions::POINT, FilterOptions::LINEAR, FilterOptions::POINT): return D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT; case MERGE_FOR_SWITCH(false, FilterOptions::POINT, FilterOptions::LINEAR, FilterOptions::LINEAR): return D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR; case MERGE_FOR_SWITCH(false, FilterOptions::LINEAR, FilterOptions::POINT, FilterOptions::POINT): return D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT; case MERGE_FOR_SWITCH(false, FilterOptions::LINEAR, FilterOptions::POINT, FilterOptions::LINEAR): return D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR; case MERGE_FOR_SWITCH(false, FilterOptions::LINEAR, FilterOptions::LINEAR, FilterOptions::POINT): return D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; case MERGE_FOR_SWITCH(false, FilterOptions::LINEAR, FilterOptions::LINEAR, FilterOptions::LINEAR): return D3D11_FILTER_MIN_MAG_MIP_LINEAR; } #undef MERGE_FOR_SWITCH return D3D11_FILTER_MIN_MAG_MIP_LINEAR; } //-------------------------------------------------------------------------- void D3D11Mappings::get(D3D11_SAMPLER_DESC &desc, const SamplerState& state) { FilterOptions minFilter, magFilter, mipFilter; state.getFilter(minFilter, magFilter, mipFilter); const UVWAddressMode &mode = state.getAddressMode(); const ColorRGBA &clrBorder = state.getBorderColor(); desc.Filter = get(minFilter, magFilter, mipFilter); desc.AddressU = get(mode.u); desc.AddressV = get(mode.v); desc.AddressW = get(mode.w); desc.MipLODBias = state.getMipmapBias(); desc.MaxAnisotropy = state.getAnisotropy(); desc.ComparisonFunc = get(state.getCompareFunction()); desc.BorderColor[0] = clrBorder.red(); desc.BorderColor[1] = clrBorder.green(); desc.BorderColor[2] = clrBorder.blue(); desc.BorderColor[3] = clrBorder.alpha(); } }
37.452381
157
0.560791
answerear
eafbf30cff755e79f9b6a2680e9c4834be8f1257
586
hpp
C++
source/lucio/core/callback.hpp
joserossini/lucioengine
643941cf29e23824af28e60df62bb1aaa0f6a7f1
[ "MIT" ]
null
null
null
source/lucio/core/callback.hpp
joserossini/lucioengine
643941cf29e23824af28e60df62bb1aaa0f6a7f1
[ "MIT" ]
null
null
null
source/lucio/core/callback.hpp
joserossini/lucioengine
643941cf29e23824af28e60df62bb1aaa0f6a7f1
[ "MIT" ]
null
null
null
#include <functional> namespace lucio { /* * CallBack * Use to call class member function from another class or Lambda. * * Example: * { * auto funcCallBack = new CallBack<void>([]() { * std::cout << "Hello World\n"; * }); * * funcCallBack->execute(); * } * * Note: Can also be use whit std::bind" */ template <typename T, typename... Args> class CallBack{ public: CallBack(std::function<T(Args...)> func) : _func(func) {}; void execute(Args... args) const { _func(std::forward<Args>(args)...); }; private: std::function<T(Args...)> _func; }; }
18.3125
76
0.602389
joserossini
eaff3a558d9b8924d4c9eeb2bd85e06f0e4d0359
5,162
hpp
C++
include/incavery/core.hpp
helixd2s/Incavery
b33737fc879fe9ef52158d8193b95633eef1321b
[ "BSD-3-Clause" ]
6
2021-02-14T22:51:28.000Z
2021-07-30T18:35:25.000Z
include/incavery/core.hpp
helixd2s/Incavery
b33737fc879fe9ef52158d8193b95633eef1321b
[ "BSD-3-Clause" ]
null
null
null
include/incavery/core.hpp
helixd2s/Incavery
b33737fc879fe9ef52158d8193b95633eef1321b
[ "BSD-3-Clause" ]
null
null
null
#pragma once // #include <glm/glm.hpp> #include <vkf/swapchain.hpp> // namespace icv { // struct DescriptorInfo { VkDescriptorSetLayout layout = VK_NULL_HANDLE; //VkPipelineLayout pipelineLayout = VK_NULL_HANDLE; }; // struct GraphicsPipelinePath { std::string vertex = ""; std::string geometry = ""; std::string fragment = ""; }; // struct ComputePipelinePath { std::string compute = ""; }; // Vulkan needs f&cking SoA, EVERY TIME! struct BuildInfo { std::vector<vkh::VkAccelerationStructureGeometryKHR> builds = {}; std::vector<vkh::VkAccelerationStructureBuildRangeInfoKHR> ranges = {}; vkh::VkAccelerationStructureBuildGeometryInfoKHR info = {}; }; // struct BufferCreateInfo { FLAGS(VkBufferUsage) usage; VkDeviceSize size = 16ull; VkDeviceSize stride = sizeof(uint8_t); VmaMemoryUsage memoryUsage = VMA_MEMORY_USAGE_GPU_ONLY; }; // struct ImageCreateInfo { FLAGS(VkImageUsage) usage; VkFormat format = VK_FORMAT_R32G32B32A32_SFLOAT; vkh::VkExtent3D extent = {}; bool isDepth = false; }; // enum class IndexType : uint32_t { None = 0u, Uint32 = 1u, Uint16 = 2u, Uint8 = 3u }; // class DeviceBased { protected: vkh::uni_ptr<vkf::Device> device = {}; vkh::VkAccelerationStructureDeviceAddressInfoKHR deviceAddressInfo = {}; vkh::VkBufferDeviceAddressInfo bufferAddressInfo = {}; // virtual VkDeviceAddress bufferDeviceAddress(vkh::VkDescriptorBufferInfo buffer) { return (device->dispatch->GetBufferDeviceAddress(bufferAddressInfo = buffer.buffer) + buffer.offset); }; // virtual vkf::VectorBase createBuffer(vkh::uni_arg<BufferCreateInfo> info) { // auto bufferCreateInfo = vkh::VkBufferCreateInfo{ .size = info->size, .usage = (info->memoryUsage == VMA_MEMORY_USAGE_GPU_ONLY ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u) | VkBufferUsageFlags(info->usage) }; auto vmaCreateInfo = vkf::VmaMemoryInfo{ .memUsage = info->memoryUsage, .instanceDispatch = device->instance->dispatch, .deviceDispatch = device->dispatch }; auto allocation = std::make_shared<vkf::VmaBufferAllocation>(device->allocator, bufferCreateInfo, vmaCreateInfo); return vkf::VectorBase(allocation, 0ull, info->size, sizeof(uint8_t)); }; // virtual vkf::ImageRegion createImage2D(vkh::uni_arg<ImageCreateInfo> info) { // vkh::VkImageCreateInfo imageCreateInfo = {}; imageCreateInfo.imageType = VK_IMAGE_TYPE_2D; imageCreateInfo.format = info->format; imageCreateInfo.extent = vkh::VkExtent3D{ info->extent.width, info->extent.height, 1u }; imageCreateInfo.mipLevels = 1u; imageCreateInfo.arrayLayers = 1u; imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imageCreateInfo.usage = info->usage | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; // auto vmaCreateInfo = vkf::VmaMemoryInfo{ .memUsage = VMA_MEMORY_USAGE_GPU_ONLY, .instanceDispatch = device->instance->dispatch, .deviceDispatch = device->dispatch }; // auto aspectFlags = info->isDepth ? (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT) : (VK_IMAGE_ASPECT_COLOR_BIT); // vkh::VkImageViewCreateInfo imageViewCreateInfo = {}; imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; imageViewCreateInfo.format = info->format; imageViewCreateInfo.components = vkh::VkComponentMapping{}; imageViewCreateInfo.subresourceRange = vkh::VkImageSubresourceRange{ .aspectMask = VkImageAspectFlags(aspectFlags), .baseMipLevel = 0u, .levelCount = 1u, .baseArrayLayer = 0u, .layerCount = 1u }; // auto allocation = std::make_shared<vkf::VmaImageAllocation>(device->allocator, imageCreateInfo, vmaCreateInfo); return vkf::ImageRegion(allocation, imageViewCreateInfo, info->isDepth?VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:VK_IMAGE_LAYOUT_GENERAL); }; // virtual VkIndexType getIndexType(IndexType indexType = IndexType::None) { // if (indexType == IndexType::None) { return VK_INDEX_TYPE_NONE_KHR; }; if (indexType == IndexType::Uint32) { return VK_INDEX_TYPE_UINT32; }; if (indexType == IndexType::Uint16) { return VK_INDEX_TYPE_UINT16; }; if (indexType == IndexType::Uint8) { return VK_INDEX_TYPE_UINT8_EXT; }; return VK_INDEX_TYPE_NONE_KHR; }; }; };
36.352113
207
0.623596
helixd2s
d802831f56e4e78ff6ca7bf64bfa12cce270be68
401
hpp
C++
old/Net.Server.Basic/inc/net/CFlushEvent.hpp
raduionita/project-hermes
7935a1486d7b0f3c05208d2c7a2e36552581a23b
[ "MIT" ]
null
null
null
old/Net.Server.Basic/inc/net/CFlushEvent.hpp
raduionita/project-hermes
7935a1486d7b0f3c05208d2c7a2e36552581a23b
[ "MIT" ]
null
null
null
old/Net.Server.Basic/inc/net/CFlushEvent.hpp
raduionita/project-hermes
7935a1486d7b0f3c05208d2c7a2e36552581a23b
[ "MIT" ]
null
null
null
#ifndef __net_cflushevent_hpp__ #define __net_cflushevent_hpp__ #include <core/CEvent.hpp> #include <net.hpp> #include <net/CConnection.hpp> namespace net { class CFlushEvent : public core::CEvent { public: CConnection& mConnection; public: CFlushEvent(CConnection& conn) : core::CEvent("flush"), mConnection(conn) { } }; } #endif // __net_cflushevent_hpp__
16.708333
77
0.690773
raduionita
d8028e946f1cbfa6ea591d4548a621d425fa4e94
1,032
cpp
C++
331.verify-preorder-serialization-of-a-binary-tree.cpp
lurenhaothu/Leetcode
a4aac47ff822deb861d6f6d9122d964090847d96
[ "MIT" ]
null
null
null
331.verify-preorder-serialization-of-a-binary-tree.cpp
lurenhaothu/Leetcode
a4aac47ff822deb861d6f6d9122d964090847d96
[ "MIT" ]
null
null
null
331.verify-preorder-serialization-of-a-binary-tree.cpp
lurenhaothu/Leetcode
a4aac47ff822deb861d6f6d9122d964090847d96
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=331 lang=cpp * * [331] Verify Preorder Serialization of a Binary Tree */ // @lc code=start class Solution { public: bool isValidSerialization(string preorder) { preorder+= ','; string seq; for(int i = 0; i < preorder.size(); i++){ char j = preorder[i]; if(j == ','){ if(i != 0 && preorder[i - 1] == '#') continue; else seq += 'K'; }else if(j == '#') seq += '#'; } //cout<<seq<<endl; string res; int index = 0; for(auto i : seq){ res += i; index = res.size() - 1; while(res.size() >= 3 && res[index] == '#' && res[index - 1] == '#' && res[index - 2] == 'K'){ res.pop_back(); res.pop_back(); res.pop_back(); res += '#'; index = res.size() - 1; } //cout<<res<<endl; } return res == "#"; } }; // @lc code=end
25.8
106
0.39438
lurenhaothu
d80293402defa5c3fd763d977595de32ba8ebfc4
7,520
cpp
C++
contract/lite-client/crypto/parser/lexer.cpp
TONCommunity/ton-sync-payments-channel
2e5cd4902406923fdba32b8309ab8c40db3ae5bc
[ "MIT" ]
5
2019-10-15T18:26:06.000Z
2020-05-09T14:09:49.000Z
contract/lite-client/crypto/parser/lexer.cpp
TONCommunity/ton-sync-payments-channel
2e5cd4902406923fdba32b8309ab8c40db3ae5bc
[ "MIT" ]
null
null
null
contract/lite-client/crypto/parser/lexer.cpp
TONCommunity/ton-sync-payments-channel
2e5cd4902406923fdba32b8309ab8c40db3ae5bc
[ "MIT" ]
2
2020-07-24T16:09:02.000Z
2021-08-18T17:08:28.000Z
/* This file is part of TON Blockchain Library. TON Blockchain Library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. TON Blockchain Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with TON Blockchain Library. If not, see <http://www.gnu.org/licenses/>. Copyright 2017-2019 Telegram Systems LLP */ #include "lexer.h" #include "symtable.h" #include <sstream> #include <cassert> namespace src { /* * * LEXER * */ std::string Lexem::lexem_name_str(int idx) { if (idx == Eof) { return "end of file"; } else if (idx == Ident) { return "identifier"; } else if (idx == Number) { return "number"; } else if (idx == String) { return "string"; } else if (idx == Special) { return "special"; } else if (sym::symbols.get_keyword(idx)) { return "`" + sym::symbols.get_keyword(idx)->str + "`"; } else { std::ostringstream os{"<unknown lexem of type "}; os << idx << ">"; return os.str(); } } std::string Lexem::name_str() const { if (tp == Ident) { return std::string{"identifier `"} + sym::symbols.get_name(val) + "`"; } else if (tp == String) { return std::string{"string \""} + str + '"'; } else { return lexem_name_str(tp); } } bool is_number(std::string str) { auto st = str.begin(), en = str.end(); if (st == en) { return false; } if (*st == '-') { st++; } bool hex = false; if (st + 1 < en && *st == '0' && st[1] == 'x') { st += 2; hex = true; } if (st == en) { return false; } while (st < en) { int c = *st; if (c >= '0' && c <= '9') { ++st; continue; } if (!hex) { return false; } c |= 0x20; if (c < 'a' || c > 'f') { return false; } ++st; } return true; } int Lexem::classify() { if (tp != Unknown) { return tp; } sym::sym_idx_t i = sym::symbols.lookup(str); if (i) { assert(str == sym::symbols[i]->str); str = sym::symbols[i]->str; sym::sym_idx_t idx = sym::symbols[i]->idx; tp = (idx < 0 ? -idx : Ident); val = i; } else if (is_number(str)) { tp = Number; } else { tp = lexem_is_special(str); } if (tp == Unknown) { tp = Ident; val = sym::symbols.lookup(str, 1); } return tp; } int Lexem::set(std::string _str, const SrcLocation& _loc, int _tp, int _val) { str = _str; loc = _loc; tp = _tp; val = _val; return classify(); } Lexer::Lexer(SourceReader& _src, bool init, std::string active_chars, std::string eol_cmts, std::string open_cmts, std::string close_cmts, std::string quote_chars) : src(_src), eof(false), lexem("", src.here(), Lexem::Undefined), peek_lexem("", {}, Lexem::Undefined) { std::memset(char_class, 0, sizeof(char_class)); unsigned char activity = cc::active; for (char c : active_chars) { if (c == ' ') { if (!--activity) { activity = cc::allow_repeat; } } else if ((unsigned)c < 0x80) { char_class[(unsigned)c] |= activity; } } set_spec(eol_cmt, eol_cmts); set_spec(cmt_op, open_cmts); set_spec(cmt_cl, close_cmts); for (int c : quote_chars) { if (c > ' ' && c <= 0x7f) { char_class[(unsigned)c] |= cc::quote_char; } } if (init) { next(); } } void Lexer::set_spec(std::array<int, 3>& arr, std::string setup) { arr[0] = arr[1] = arr[2] = -0x100; std::size_t n = setup.size(), i; for (i = 0; i < n; i++) { if (setup[i] == ' ') { continue; } if (i == n - 1 || setup[i + 1] == ' ') { arr[0] = setup[i]; } else if (i == n - 2 || (i < n - 2 && setup[i + 2] == ' ')) { arr[1] = setup[i]; arr[2] = setup[++i]; } else { while (i < n && setup[i] != ' ') { i++; } } } } void Lexer::expect(int exp_tp, const char* msg) { if (tp() != exp_tp) { throw ParseError{lexem.loc, (msg ? std::string{msg} : Lexem::lexem_name_str(exp_tp)) + " expected instead of " + cur().name_str()}; } next(); } const Lexem& Lexer::next() { if (peek_lexem.valid()) { lexem = std::move(peek_lexem); peek_lexem.clear({}, Lexem::Undefined); eof = (lexem.tp == Lexem::Eof); return lexem; } if (eof) { return lexem.clear(src.here(), Lexem::Eof); } long long comm = 1; while (!src.seek_eof()) { int cc = src.cur_char(), nc = src.next_char(); if (cc == eol_cmt[0] || (cc == eol_cmt[1] && nc == eol_cmt[2])) { src.load_line(); } else if (cc == cmt_op[1] && nc == cmt_op[2]) { src.advance(2); comm = comm * 2 + 1; } else if (cc == cmt_op[0]) { src.advance(1); comm *= 2; } else if (comm == 1) { break; } else if (cc == cmt_cl[1] && nc == cmt_cl[2]) { if (!(comm & 1)) { src.error(std::string{"a `"} + (char)cmt_op[0] + "` comment closed by `" + (char)cmt_cl[1] + (char)cmt_cl[2] + "`"); } comm >>= 1; src.advance(2); } else if (cc == cmt_cl[0]) { if (!(comm & 1)) { src.error(std::string{"a `"} + (char)cmt_op[1] + (char)cmt_op[2] + "` comment closed by `" + (char)cmt_cl[0] + "`"); } comm >>= 1; src.advance(1); } else { src.advance(1); } if (comm < 0) { src.error("too many nested comments"); } } if (src.seek_eof()) { eof = true; if (comm > 1) { if (comm & 1) { src.error(std::string{"`"} + (char)cmt_op[1] + (char)cmt_op[2] + "` comment extends past end of file"); } else { src.error(std::string{"`"} + (char)cmt_op[0] + "` comment extends past end of file"); } } return lexem.clear(src.here(), Lexem::Eof); } int c = src.cur_char(); const char* end = src.get_ptr(); if (is_quote_char(c) || c == '`') { int qc = c; ++end; while (end < src.get_end_ptr() && *end != qc) { ++end; } if (*end != qc) { src.error(qc == '`' ? "a `back-quoted` token extends past end of line" : "string extends past end of line"); } lexem.set(std::string{src.get_ptr() + 1, end}, src.here(), qc == '`' ? Lexem::Unknown : Lexem::String); src.set_ptr(end + 1); // std::cerr << lexem.name_str() << ' ' << lexem.str << std::endl; return lexem; } int len = 0, pc = -0x100; while (end < src.get_end_ptr()) { c = *end; bool repeated = (c == pc && is_repeatable(c)); if (c == ' ' || c == 9 || (len && is_left_active(c) && !repeated)) { break; } ++len; ++end; if (is_right_active(c) && !repeated) { break; } pc = c; } lexem.set(std::string{src.get_ptr(), end}, src.here()); src.set_ptr(end); // std::cerr << lexem.name_str() << ' ' << lexem.str << std::endl; return lexem; } const Lexem& Lexer::peek() { if (peek_lexem.valid()) { return peek_lexem; } if (eof) { return lexem.clear(src.here(), Lexem::Eof); } Lexem keep = std::move(lexem); next(); peek_lexem = std::move(lexem); lexem = std::move(keep); eof = false; return peek_lexem; } } // namespace src
26.020761
118
0.534574
TONCommunity
d802c2cc4b75ab95f2436f576382c3ea9e824257
420
hpp
C++
include/dr_util/expand.hpp
fizyr-private/dr_util
41d21712d7eceaa09e11b95f6635bd9df952481f
[ "Apache-2.0" ]
null
null
null
include/dr_util/expand.hpp
fizyr-private/dr_util
41d21712d7eceaa09e11b95f6635bd9df952481f
[ "Apache-2.0" ]
2
2019-08-05T11:58:20.000Z
2020-02-14T10:14:57.000Z
include/dr_util/expand.hpp
fizyr-private/dr_util
41d21712d7eceaa09e11b95f6635bd9df952481f
[ "Apache-2.0" ]
1
2019-08-05T05:24:56.000Z
2019-08-05T05:24:56.000Z
#include <map> #include <string> namespace dr { /// Expand variables in a string. /** * A variable can be written as $NAME or ${NAME}. */ std::string expandVariables(std::string const & source, std::map<std::string, std::string> const & variables); /// Expand environment variables in a string. /** * A variable can be written as $NAME or ${NAME}. */ std::string expandEnvironment(std::string const & source); }
22.105263
110
0.683333
fizyr-private
d80570a7b16f8796d43372bd2c4acfc544a396a0
1,675
cpp
C++
barzer_relbits.cpp
barzerman/barzer
3211507d5ed0294ee77986f58d781a2fa4142e0d
[ "MIT" ]
1
2018-10-22T12:53:13.000Z
2018-10-22T12:53:13.000Z
barzer_relbits.cpp
barzerman/barzer
3211507d5ed0294ee77986f58d781a2fa4142e0d
[ "MIT" ]
null
null
null
barzer_relbits.cpp
barzerman/barzer
3211507d5ed0294ee77986f58d781a2fa4142e0d
[ "MIT" ]
null
null
null
/// Copyright Barzer LLC 2012 /// Code is property Barzer for authorized use only /// #include "barzer_relbits.h" #include <fstream> #include <sstream> #include <ay/ay_logger.h> #include <ay/ay_util.h> /** Ok, so since we don't want to keep an enum for this, let's describe * the release bits here. * * 1: use synonyms autoexpansion. */ namespace barzer { RelBitsMgr::RelBitsMgr() : m_bits(static_cast<size_t>(RBMAX), false) { } RelBitsMgr& RelBitsMgr::inst() { static RelBitsMgr inst; return inst; } size_t RelBitsMgr::reparse (std::ostream& outStream, const char *filename) { m_bits = std::vector<bool>(static_cast<size_t>(RBMAX), false); FILE* fp = fopen( filename, "r" ); outStream << "loading release bits from " << filename << "..."; if( !fp ) { outStream << "failed to open " << filename << std::endl; return 0; } char buf[ 256 ]; size_t line=0; while (fgets( buf, sizeof(buf)-1, fp )) { size_t buf_len = strlen(buf); if( !buf_len ) continue; size_t buf_last = buf_len-1; if( buf[0] == '#' ) continue; if( buf[ buf_last ]=='\n' ) buf[ buf_last ] = 0; std::stringstream sstr(buf); size_t bitNum=0xffffffff; sstr >> bitNum; if( !setBit(bitNum) ) { AYLOG(ERROR) << "failed to set bit " << bitNum << " on line " << line << std::endl; } ++line; } outStream << line << " lines read" << std::endl; fclose(fp); return line; } }
25
99
0.529552
barzerman
d80bbfde1f94d2017e9863063c31759a920681f0
26
cpp
C++
src/external_library/bitmap/BitmapImage.cpp
MatthieuHernandez/StraightforwardNeuralNetwork
e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7
[ "Apache-2.0" ]
14
2019-08-29T07:20:19.000Z
2022-03-22T12:51:02.000Z
src/external_library/bitmap/BitmapImage.cpp
MatthieuHernandez/StraightforwardNeuralNetwork
e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7
[ "Apache-2.0" ]
7
2020-08-07T11:08:45.000Z
2021-05-08T17:11:12.000Z
src/external_library/bitmap/BitmapImage.cpp
MatthieuHernandez/StraightforwardNeuralNetwork
e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7
[ "Apache-2.0" ]
3
2020-08-07T10:53:52.000Z
2021-02-16T22:13:22.000Z
#include "BitmapImage.hpp"
26
26
0.807692
MatthieuHernandez
d80c7ea5404eb1fb95d99bc9225a5ccf76f71805
1,013
cpp
C++
3rdparty/diy/examples/simple/read-blocks.cpp
wgq-iapcm/Parvoro-
9459e1081ff948628358c59207d5fcd8ce60ef8f
[ "BSD-3-Clause" ]
43
2016-10-23T14:52:59.000Z
2022-03-18T20:47:06.000Z
3rdparty/diy/examples/simple/read-blocks.cpp
wgq-iapcm/Parvoro-
9459e1081ff948628358c59207d5fcd8ce60ef8f
[ "BSD-3-Clause" ]
39
2016-11-25T22:14:09.000Z
2022-01-13T21:44:51.000Z
3rdparty/diy/examples/simple/read-blocks.cpp
wgq-iapcm/Parvoro-
9459e1081ff948628358c59207d5fcd8ce60ef8f
[ "BSD-3-Clause" ]
21
2016-11-28T22:08:36.000Z
2022-03-16T10:31:32.000Z
#include <iostream> #include <diy/master.hpp> #include <diy/io/block.hpp> #include "block.h" void output(Block* b, const diy::Master::ProxyWithLink& cp) { std::cout << cp.gid() << " " << b->average << std::endl; for (int i = 0; i < cp.link()->size(); ++i) std::cout << " " << cp.link()->target(i).gid << " " << cp.link()->target(i).proc << std::endl; } int main(int argc, char* argv[]) { diy::mpi::environment env(argc, argv); diy::mpi::communicator world; diy::Master master(world, 1, -1, &create_block, // master will take ownership after read_blocks(), &destroy_block); // so it needs create and destroy functions diy::ContiguousAssigner assigner(world.size(), 0); //diy::RoundRobinAssigner assigner(world.size(), 0); // nblocks will be filled by read_blocks() diy::io::read_blocks("blocks.out", world, assigner, master, &load_block); master.foreach(&output); }
33.766667
110
0.574531
wgq-iapcm
d80cf59a55c78e5ad525148400e785da63fabd5d
656
cpp
C++
Source/GameService/Net/Network/Crypto/KeyExchange.cpp
BaekTaehyun/T1Project
d7d98c7cfc88e57513631124c32dfee8794307db
[ "MIT" ]
3
2019-06-25T05:09:47.000Z
2020-09-30T18:06:17.000Z
Source/GameService/Net/Network/Crypto/KeyExchange.cpp
BaekTaehyun/T1Project
d7d98c7cfc88e57513631124c32dfee8794307db
[ "MIT" ]
null
null
null
Source/GameService/Net/Network/Crypto/KeyExchange.cpp
BaekTaehyun/T1Project
d7d98c7cfc88e57513631124c32dfee8794307db
[ "MIT" ]
2
2018-10-15T08:09:16.000Z
2020-04-07T05:25:52.000Z
#include "KeyExchange.h" #include <cassert> std::vector<uint64_t> KeyExchange::getPublicKey(uint64_t p, uint64_t g, size_t count) { dhs_.clear(); std::vector<uint64_t> pk; for (size_t i = 0; i < count; ++i) { DiffieHellman dh; pk.push_back(dh.getPublicKey(p, g)); dhs_.push_back(dh); } return pk; } std::vector<uint8_t> KeyExchange::getSecretKey(const std::vector<uint64_t>& Bs) const { assert(dhs_.size() == Bs.size()); std::vector<uint8_t> sk; for (size_t i = 0; i < dhs_.size(); ++i) { if (i >= Bs.size()) { break; } auto s = dhs_[i].getSecretKey(Bs[i]); sk.insert(sk.end(), s.begin(), s.end()); } return sk; }
16
85
0.625
BaekTaehyun
d80ddb7432a2682168f55dff3ed25a45d4aba3c9
1,396
cpp
C++
examples/cpp/src/utils/Reader.cpp
TEE-AI/SAI
f2a43d704078057c8f957f4751317e8fea75a07f
[ "Apache-2.0" ]
34
2019-01-16T14:54:10.000Z
2021-11-16T11:19:15.000Z
examples/cpp/src/utils/Reader.cpp
TEE-AI/SAI
f2a43d704078057c8f957f4751317e8fea75a07f
[ "Apache-2.0" ]
2
2019-02-16T06:41:31.000Z
2019-04-23T05:34:01.000Z
examples/cpp/src/utils/Reader.cpp
TEE-AI/SAI
f2a43d704078057c8f957f4751317e8fea75a07f
[ "Apache-2.0" ]
4
2019-04-10T00:48:27.000Z
2021-04-12T01:21:01.000Z
#include "Reader.h" Reader::Reader(std::vector<std::string> *filelist) { filelist_ = filelist; fileIndex_ = 0; processor_ = 0; } Reader::~Reader() { filelist_ = 0; fileIndex_ = 0; processor_ = 0; } void Reader::register_processor(Preprocessor *processor) { processor_ = processor; } ImageReader::ImageReader(std::vector<std::string> *filelist) : Reader(filelist) {} cv::Mat ImageReader::get() { if (fileIndex_ < filelist_->size()) { cv::Mat cvImage= cv::imread((*filelist_)[fileIndex_++]); if (processor_) { cv::Mat procImage = processor_->process(cvImage); return procImage; } else { return cvImage; } } else { return cv::Mat(); } } /* VideoReader::VideoReader(std::vector<std::string> *filelist) : Reader(filelist) { // Open the first file if possible if (fileIndex_ < filelist_->size()) { videoCap_.open((*filelist_)[fileIndex_]); } } cv::Mat VideoReader::get() { cv::Mat rawImage; videoCap_.read(rawImage); if (rawImage.empty()) { // Reach the end of the current file fileIndex_++; if (fileIndex_ < filelist_->size()) { videoCap_.open((*filelist_)[fileIndex_]); videoCap_.read(rawImage); } } if (processor_) { cv::Mat procImage = processor_->process(rawImage); return procImage; } return rawImage; } */
21.151515
82
0.611032
TEE-AI
d81043c1f105b165bab2fecd6fb56885c07a40c1
20,769
cpp
C++
drlvm/vm/jitrino/src/codegenerator/ia32/Ia32CodeSelector.cpp
sirinath/Harmony
724deb045a85b722c961d8b5a83ac7a697319441
[ "Apache-2.0" ]
8
2015-11-04T06:06:35.000Z
2021-07-04T13:47:36.000Z
drlvm/vm/jitrino/src/codegenerator/ia32/Ia32CodeSelector.cpp
sirinath/Harmony
724deb045a85b722c961d8b5a83ac7a697319441
[ "Apache-2.0" ]
1
2021-10-17T13:07:28.000Z
2021-10-17T13:07:28.000Z
drlvm/vm/jitrino/src/codegenerator/ia32/Ia32CodeSelector.cpp
sirinath/Harmony
724deb045a85b722c961d8b5a83ac7a697319441
[ "Apache-2.0" ]
13
2015-11-27T03:14:50.000Z
2022-02-26T15:12:20.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author Intel, Vyacheslav P. Shakin */ #include <stdlib.h> #include "Ia32CodeGenerator.h" #include "Ia32CodeSelector.h" #include "Ia32CFG.h" #include "Ia32InstCodeSelector.h" #include "EMInterface.h" #include "XTimer.h" namespace Jitrino { namespace Ia32{ CountTime selectionTimer("ia32::selector::selection"); CountTime blockMergingTimer("ia32::selector::blockMerging"); CountTime fixNodeInfoTimer("ia32::selector::fixNodeInfo"); //_______________________________________________________________________________________________________________ // FP conversion internal helpers (temp solution to be optimized) //======================================================================================================== // class CfgCodeSelector //======================================================================================================== //_______________________________________________________________________________________________ /** Construct CFG builder */ CfgCodeSelector::CfgCodeSelector(::Jitrino::SessionAction* sa, CompilationInterface& compIntfc, MethodCodeSelector& methodCodeSel, MemoryManager& codeSelectorMM, U_32 nNodes, IRManager& irM ) : numNodes(nNodes), nextNodeId(0), compilationInterface(compIntfc), methodCodeSelector(methodCodeSel), irMemManager(irM.getMemoryManager()), codeSelectorMemManager(codeSelectorMM), irManager(irM), hasDispatchNodes(false), currBlock(NULL), returnOperand(0) { nextNodeId = 0; nodes = new (codeSelectorMemManager) Node*[numNodes]; U_32 i; for (i = 0; i < numNodes; i++) nodes[i] = NULL; InstCodeSelector::onCFGInit(irManager); flags.useInternalHelpersForInteger2FloatConv = sa->getBoolArg("useInternalHelpersForInteger2FloatConv", false); flags.slowLdString = sa->getBoolArg("SlowLdString", false); } //_______________________________________________________________________________________________ /** Create an exception handling (dispatching) node */ U_32 CfgCodeSelector::genDispatchNode(U_32 numInEdges,U_32 numOutEdges, const StlVector<MethodDesc*>& inlineEndMarkers, double cnt) { assert(nextNodeId < numNodes); U_32 nodeId = nextNodeId++; Node* node = irManager.getFlowGraph()->createDispatchNode(); node->setExecCount(cnt); nodes[nodeId] = node; hasDispatchNodes = true; for (StlVector<MethodDesc*>::const_iterator it = inlineEndMarkers.begin(), end = inlineEndMarkers.end(); it!=end; ++it) { MethodDesc* desc = *it; node->appendInst(irManager.newMethodEndPseudoInst(desc)); } return nodeId; } //_______________________________________________________________________________________________ /** Create a basic block */ U_32 CfgCodeSelector::genBlock(U_32 numInEdges, U_32 numOutEdges, BlockKind blockKind, BlockCodeSelector& codeSelector, double cnt) { assert(nextNodeId < numNodes); U_32 nodeId = nextNodeId++; Node* bb = irManager.getFlowGraph()->createBlockNode(); bb->setExecCount(cnt); nodes[nodeId] = bb; InstCodeSelector instCodeSelector(compilationInterface, *this, irManager, bb); currBlock = bb; { codeSelector.genCode(instCodeSelector); } currBlock = NULL; // Set prolog or epilogue node switch (blockKind) { case Prolog: { // Copy execution count into IA32 CFG prolog node and // create an edge from IA32 CFG prolog node to optimizer's prolog node Node* prolog = irManager.getFlowGraph()->getEntryNode(); prolog->setExecCount(cnt); irManager.getFlowGraph()->addEdge(prolog, bb, 1.0); break; } case Epilog: { assert(bb->isEmpty()); break; } case InnerBlock: break; // nothing to do } if (instCodeSelector.endsWithSwitch()) { // Generate an additional node that contains switch dispatch U_32 numTargets = instCodeSelector.getSwitchNumTargets(); Opnd * switchSrc = instCodeSelector.getSwitchSrc(); genSwitchBlock(bb, numTargets, switchSrc); } return nodeId; } //_______________________________________________________________________________________________ /** Create unwind node. This is a temporary node that exists only during code selection. We create it using code selector memory manager and insert it into its own CFG. */ U_32 CfgCodeSelector::genUnwindNode(U_32 numInEdges, U_32 numOutEdges, double cnt) { assert(nextNodeId < numNodes); U_32 nodeId = nextNodeId++; ControlFlowGraph* fg = irManager.getFlowGraph(); Node* unwindNode = fg->createDispatchNode(); fg->setUnwindNode(unwindNode); unwindNode->setExecCount(cnt); nodes[nodeId] = unwindNode; return nodeId; } //_______________________________________________________________________________________________ /** Create exit node */ U_32 CfgCodeSelector::genExitNode(U_32 numInEdges, double cnt) { assert(nextNodeId < numNodes); U_32 nodeId = nextNodeId++; ControlFlowGraph* fg = irManager.getFlowGraph(); Node* exitNode = fg->createExitNode(); exitNode->setExecCount(cnt); fg->setExitNode(exitNode); nodes[nodeId] = exitNode; return nodeId; } //_______________________________________________________________________________________________ /** Create a block for a switch statement */ void CfgCodeSelector::genSwitchBlock(Node *originalBlock, U_32 numTargets, Opnd * switchSrc) { Node *bb = irManager.getFlowGraph()->createBlockNode(); bb->setExecCount(originalBlock->getExecCount()); InstCodeSelector instSelector(compilationInterface, *this, irManager, bb); { instSelector.genSwitchDispatch(numTargets,switchSrc); } // Create an edge from the original block to bb genFalseEdge(originalBlock, bb, 1.0); } //_______________________________________________________________________________________________ /** Create true edge (i.e., edge that corresponds to a taken conditional branch) */ void CfgCodeSelector::genTrueEdge(U_32 tailNodeId,U_32 headNodeId, double prob) { Node* tailNode= nodes[tailNodeId]; Node * headNode = nodes[headNodeId]; genTrueEdge(tailNode, headNode, prob); } void CfgCodeSelector::genTrueEdge(Node* tailNode, Node* headNode, double prob) { assert(tailNode->isBlockNode() && headNode->isBlockNode()); Inst* inst = (Inst*)tailNode->getLastInst(); assert(inst!=NULL && inst->hasKind(Inst::Kind_BranchInst)); BranchInst* br = (BranchInst*)inst; br->setTrueTarget(headNode); irManager.getFlowGraph()->addEdge(tailNode, headNode, prob); } //_______________________________________________________________________________________________ /** Create false edge (i.e., edge that corresponds to a fallthrough after untaken conditional branch) */ void CfgCodeSelector::genFalseEdge(U_32 tailNodeId,U_32 headNodeId, double prob) { Node* tailNode = nodes[tailNodeId]; Node* headNode = nodes[headNodeId]; genFalseEdge(tailNode, headNode, prob); } void CfgCodeSelector::genFalseEdge(Node* tailNode,Node* headNode, double prob) { assert(tailNode->isBlockNode() && headNode->isBlockNode()); Inst* inst = (Inst*)tailNode->getLastInst(); assert(inst!=NULL && inst->hasKind(Inst::Kind_BranchInst)); BranchInst* br = (BranchInst*)inst; br->setFalseTarget(headNode); irManager.getFlowGraph()->addEdge(tailNode, headNode, prob); } //_______________________________________________________________________________________________ /** Create unconditional edge (i.e., edge that corresponds to fallthrough) */ void CfgCodeSelector::genUnconditionalEdge(U_32 tailNodeId,U_32 headNodeId, double prob) { Node * tailNode = nodes[tailNodeId]; Node * headNode = nodes[headNodeId]; assert(tailNode->isBlockNode()); assert(headNode->isBlockNode() || headNode == irManager.getFlowGraph()->getExitNode()); Inst* lastInst = (Inst*)tailNode->getLastInst(); if (lastInst!=NULL && lastInst->hasKind(Inst::Kind_BranchInst)) { BranchInst* br = (BranchInst*)lastInst; assert(br->getTrueTarget() != NULL); assert(br->getFalseTarget() == NULL); br->setFalseTarget(headNode); } irManager.getFlowGraph()->addEdge(tailNode, headNode, prob); } //_______________________________________________________________________________________________ /** Create switch edges */ void CfgCodeSelector::genSwitchEdges(U_32 tailNodeId, U_32 numTargets, U_32 *targets, double *probs, U_32 defaultTarget) { // // Switch structure: // // origBlock switchBlock // =========== Fallthrough ============= // .... =======> ....... // if (switchVar >= numTargets) swTarget= jmp [switchVar + swTableBase] // jmp defaultTarget // Node * origBlock = nodes[tailNodeId]; const Edges& outEdges=origBlock->getOutEdges(); assert(outEdges.size() == 1); Node * switchBlock= outEdges.front()->getTargetNode(); assert(switchBlock->isBlockNode()); assert(((Inst*)switchBlock->getLastInst())->hasKind(Inst::Kind_SwitchInst)); SwitchInst * swInst = (SwitchInst *)switchBlock->getLastInst(); double defaultEdgeProb = 1.0; defaultEdgeProb = 1.0; for (U_32 i = 0; i < numTargets; i++) { U_32 targetId = targets[i]; if ( targetId == defaultTarget) { defaultEdgeProb = probs[i]; break; } if (std::find(targets, targets+i, targetId)!=targets+i) { continue; //repeated target } if (probs[i] < 0) { defaultEdgeProb = 0; break; } defaultEdgeProb -= 1.0/(numTargets+1); } genTrueEdge(tailNodeId, defaultTarget, defaultEdgeProb); // Fix probability of fallthrough edge if (defaultEdgeProb!=0) { origBlock->getOutEdges().front()->setEdgeProb(1.0 - defaultEdgeProb); } // Generate edges from switchBlock to switch targets for (U_32 i = 0; i < numTargets; i++) { Node * targetNode = nodes[targets[i]]; // Avoid generating duplicate edges. Jump table however needs all entries if (! switchBlock->isConnectedTo(true, targetNode)) { irManager.getFlowGraph()->addEdge(switchBlock, targetNode, probs[i]); } swInst->setTarget(i, targetNode); } } //_______________________________________________________________________________________________ /** Create an edge to the exception dispatch node or unwind node */ void CfgCodeSelector::genExceptionEdge(U_32 tailNodeId, U_32 headNodeId, double prob) { Node * headNode = nodes[headNodeId]; Node * tailNode = nodes[tailNodeId]; assert(headNode->isDispatchNode() || headNode->isExitNode()); irManager.getFlowGraph()->addEdge(tailNode, headNode, prob); } //_______________________________________________________________________________________________ /** Create catch edge */ void CfgCodeSelector::genCatchEdge(U_32 tailNodeId, U_32 headNodeId, U_32 priority, Type* exceptionType, double prob) { Node * headNode = nodes[headNodeId]; Node * tailNode = nodes[tailNodeId]; assert(tailNode->isDispatchNode()); assert(headNode->isBlockNode()); CatchEdge* edge = (CatchEdge*)irManager.getFlowGraph()->addEdge(tailNode, headNode, prob); edge->setType(exceptionType); edge->setPriority(priority); } //_______________________________________________________________________________________________ /** Cfg code selector is notified that method contains calls */ void CfgCodeSelector::methodHasCalls(bool nonExceptionCall) { irManager.setHasCalls(); if (nonExceptionCall) irManager.setHasNonExceptionCalls(); } /////////////////////////////////////////////////////////////////////////////////// // // class VarGenerator // /////////////////////////////////////////////////////////////////////////////////// //_______________________________________________________________________________________________ U_32 VarGenerator::defVar(Type* varType, bool isAddressTaken, bool isPinned) { Opnd * opnd=irManager.newOpnd(varType); return opnd->getId(); } //_______________________________________________________________________________________________ void VarGenerator::setManagedPointerBase(U_32 managedPtrVarNum, U_32 baseVarNum) { } /////////////////////////////////////////////////////////////////////////////////// // // class MethodCodeSelector // /////////////////////////////////////////////////////////////////////////////////// //_______________________________________________________________________________________________ /** Generate variable operands */ void MethodCodeSelector::genVars(U_32 numVars, VarCodeSelector& varCodeSelector) { numVarOpnds = numVars; VarGenerator varCodeSelectorCallback(irManager,*this); varCodeSelector.genCode(varCodeSelectorCallback); } //_______________________________________________________________________________________________ /** Update register usage */ void MethodCodeSelector::updateRegUsage() { } //_______________________________________________________________________________________________ /** Set persistent ids, and others for nodes that exist only in the code generator CFG */ void CfgCodeSelector::fixNodeInfo() { MemoryManager tmpMM("Ia32CS:fixNodeInfoMM"); ControlFlowGraph* fg = irManager.getFlowGraph(); Nodes nodes(tmpMM); fg->getNodes(nodes); //copy nodes -> loop creates new ones, so we can't use reference to cfg->getNodes() for (Nodes::const_iterator it = nodes.begin(), end = nodes.end(); it!=end; ++it) { Node* node = *it; // connect throw nodes added during inst code selection to corresponding dispatch or unwind nodes if (node->isBlockNode()){ Inst * lastInst = (Inst*)node->getLastInst(); if (lastInst) { Inst * prevInst = lastInst->getPrevInst(); if(prevInst && prevInst->getKind() == Inst::Kind_BranchInst) { Edge * ftEdge = node->getFalseEdge(); Edge * dbEdge = node->getTrueEdge(); assert(ftEdge && dbEdge); Node* newBB = fg->createBlockNode(); Node* nextFT = ftEdge->getTargetNode(); Node* nextDB = dbEdge->getTargetNode(); fg->removeEdge(ftEdge); fg->removeEdge(dbEdge); newBB->appendInst(irManager.newBranchInst(lastInst->getMnemonic(), nextDB, nextFT)); lastInst->unlink(); //now fix prev branch successors BranchInst* prevBranch = (BranchInst*)prevInst; assert(prevBranch->getTrueTarget() == NULL && prevBranch->getFalseTarget() == NULL); prevBranch->setTrueTarget(lastInst->getMnemonic() == Mnemonic_JZ? nextFT : nextDB); prevBranch->setFalseTarget(newBB); fg->addEdge(node, lastInst->getMnemonic() == Mnemonic_JZ? nextFT : nextDB, 0); fg->addEdge(node, newBB, 0); fg->addEdge(newBB, nextDB, 0); fg->addEdge(newBB, nextFT, 0); } } if (node->getOutDegree() == 0){ // throw node assert(node->getInDegree()==1); Node* bbIn = node->getInEdges().front()->getSourceNode(); assert(bbIn!=NULL); Node * target=bbIn->getExceptionEdgeTarget(); assert(target!=NULL); fg->addEdge(node, target, 1.0); } // fixup empty catch blocks otherwise respective catchEdges will be lost // There is no [catchBlock]-->[catchHandler] edge. Catch block will be removed // as an empty one and exception handling will be incorrect if (node->isCatchBlock() && node->isEmpty()) { assert(node->getInDegree()==1); Edge* catchEdge = node->getInEdges().front(); assert(catchEdge->getSourceNode()->isDispatchNode()); assert(node->getOutDegree()==1); Node* succ = node->getUnconditionalEdgeTarget(); while( succ->isEmpty() && (succ->getOutDegree() == 1) ) { succ = succ->getUnconditionalEdgeTarget(); } assert(succ && ((Inst*)succ->getFirstInst())->hasKind(Inst::Kind_CatchPseudoInst)); fg->replaceEdgeTarget(catchEdge,succ,true/*keepOldBody*/); } } } } //_______________________________________________________________________________________________ /** Generate heap base initialization */ void MethodCodeSelector::genHeapBase() { } //_______________________________________________________________________________________________ /** Generate control flow graph */ MethodCodeSelector::MethodCodeSelector( ::Jitrino::SessionAction* _sa, CompilationInterface& compIntfc, MemoryManager& irMM, MemoryManager& codeSelectorMM, IRManager& irM) : sa(_sa), compilationInterface(compIntfc), irMemManager(irMM), codeSelectorMemManager(codeSelectorMM), irManager(irM), methodDesc(NULL), edgeProfile(NULL) { ProfilingInterface* pi = irManager.getProfilingInterface(); if (pi!=NULL && pi->isProfilingEnabled(ProfileType_Edge, JITProfilingRole_GEN)) { edgeProfile = pi->getEdgeMethodProfile(irMM, irM.getMethodDesc(), JITProfilingRole_GEN); } } void MethodCodeSelector::genCFG(U_32 numNodes, CFGCodeSelector& codeSelector, bool useEdgeProfile) { ControlFlowGraph* fg = irManager.getFlowGraph(); fg->setEdgeProfile(useEdgeProfile); CfgCodeSelector cfgCodeSelector(sa, compilationInterface, *this, codeSelectorMemManager,numNodes, irManager); { AutoTimer tm(selectionTimer); if( NULL == irManager.getEntryPointInst() ) { irManager.newEntryPointPseudoInst( irManager.getDefaultManagedCallingConvention() ); } codeSelector.genCode(cfgCodeSelector); } { AutoTimer tm(fixNodeInfoTimer); irManager.expandSystemExceptions(0); cfgCodeSelector.fixNodeInfo(); } { AutoTimer tm(blockMergingTimer); fg->purgeEmptyNodes(false, true); fg->mergeAdjacentNodes(true, false); fg->purgeUnreachableNodes(); } } //_______________________________________________________________________________________________ }; // namespace Ia32 };
39.186792
132
0.631711
sirinath
d8112d6d727919c9cd82b4e19ef74e99ee43676b
1,233
cpp
C++
benchmark/utils.cpp
Karamaz0V1/Higra
216d9e47641171b5a6f8b7e2b42c269b8dc34abd
[ "CECILL-B" ]
64
2019-08-18T19:23:23.000Z
2022-03-21T04:15:04.000Z
benchmark/utils.cpp
higra/Higra
e6d5984a585f652c87d303a6a6bec19f0eb7432e
[ "CECILL-B" ]
120
2019-08-16T09:10:35.000Z
2022-03-17T09:42:58.000Z
benchmark/utils.cpp
Karamaz0V1/Higra
216d9e47641171b5a6f8b7e2b42c269b8dc34abd
[ "CECILL-B" ]
12
2019-10-04T07:35:55.000Z
2021-01-10T19:59:11.000Z
/*************************************************************************** * Copyright ESIEE Paris (2021) * * * * Contributor(s) : Benjamin Perret * * * * Distributed under the terms of the CECILL-B License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #include "utils.h" using namespace hg; bool is_power_of_two(std::size_t x) { return (x != 0) && ((x & (x - 1)) == 0); } hg::tree get_complete_binary_tree(std::size_t num_leaves) { assert(is_power_of_two(num_leaves)); array_1d<std::size_t> parent = array_1d<std::size_t>::from_shape({num_leaves * 2 - 1}); for (std::size_t i = 0, j = num_leaves; i < parent.size() - 1; j++) { parent(i++) = j; parent(i++) = j; } parent(parent.size() - 1) = parent.size() - 1; return tree(std::move(parent)); }
44.035714
91
0.379562
Karamaz0V1
d8112d8960eb885acb99ea8d5b081331a5122bf0
94
cpp
C++
BASIC c++/beginning_with_cpp/before_oop/exercise of 4 .cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/beginning_with_cpp/before_oop/exercise of 4 .cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
BASIC c++/beginning_with_cpp/before_oop/exercise of 4 .cpp
jattramesh/Learning_git
5191ecc6c0c11b69b9786f2a8bdd3db7228987d6
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main() { int x,i; i=-2; cout<<-4*i++-6%4<<endl; }
10.444444
23
0.617021
jattramesh
d8120c0c46c988618764ba5662c38ae2c5bc925c
2,766
cpp
C++
qsimplespatial/paintscheme.cpp
folibis/qsimplespatial
e39b07678ced3199cc518adf251e683759442dc3
[ "MIT" ]
1
2020-03-16T09:59:28.000Z
2020-03-16T09:59:28.000Z
qsimplespatial/paintscheme.cpp
folibis/qsimplespatial
e39b07678ced3199cc518adf251e683759442dc3
[ "MIT" ]
null
null
null
qsimplespatial/paintscheme.cpp
folibis/qsimplespatial
e39b07678ced3199cc518adf251e683759442dc3
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 20014 Moukhlynin Ruslan <me@ruslan.pw> * * paintscheme.cpp * This file is part of the QSimpleSpatial. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "paintscheme.h" #include "maptranslator.h" #include <QColor> #include <QDateTime> PaintScheme::PaintScheme() : p_colorsInitialized(false), p_filter_func(NULL) { } PaintScheme::PaintScheme(const QPen &pen, const QBrush &brush) : p_colorsInitialized(true), p_filter_func(NULL) { init(pen,brush); } QPen PaintScheme::GetPen() const { return p_pen; } void PaintScheme::setPen(const QPen &pen) { p_pen = pen; } QBrush PaintScheme::GetBrush() const { return p_brush; } void PaintScheme::setBrush(const QBrush &brush) { p_brush = brush; } bool PaintScheme::IsDefault() { return (p_filter_func == NULL); } void PaintScheme::init(const QPen &pen, const QBrush &brush) { p_pen = pen; p_brush = brush; } QPair<QColor, QColor> PaintScheme::getGhostColors(Feature *feature) { if(p_ghostColors.contains(feature)) return p_ghostColors[feature]; qsrand(QDateTime::currentMSecsSinceEpoch()); return p_ghostColors.insert(feature,QPair<QColor,QColor>(QColor::fromRgb(rrand(130,255),rrand(130,255),rrand(130,255)), QColor::fromRgb(rrand(130,255),rrand(130,255),rrand(130,255)))) .value(); } void PaintScheme::SetFilterFunction(bool (*filter_func)(Feature *)) { p_filter_func = filter_func; } bool PaintScheme::TestFilter(Feature *feature) { if(p_filter_func == NULL) return false; return p_filter_func(feature); } QSimpleSpatial::ShapeTypes PaintScheme::getShapeType() { return QSimpleSpatial::NullShape; }
25.145455
123
0.720897
folibis