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
53b778497d67824a758b505d8509133ac53883c4
5,833
hpp
C++
include/RavEngine/unordered_vector.hpp
Ravbug/RavEngine
73249827cb2cd3c938bb59447e9edbf7b6f0defc
[ "Apache-2.0" ]
48
2020-11-18T23:14:25.000Z
2022-03-11T09:13:42.000Z
include/RavEngine/unordered_vector.hpp
Ravbug/RavEngine
73249827cb2cd3c938bb59447e9edbf7b6f0defc
[ "Apache-2.0" ]
1
2020-11-17T20:53:10.000Z
2020-12-01T20:27:36.000Z
include/RavEngine/unordered_vector.hpp
Ravbug/RavEngine
73249827cb2cd3c938bb59447e9edbf7b6f0defc
[ "Apache-2.0" ]
3
2020-12-22T02:40:39.000Z
2021-10-08T02:54:22.000Z
#pragma once #include <vector> #include <phmap.h> #include <functional> namespace RavEngine { /** The Unordered Vector provides: - O(1) erase by iterator All other complexities for valid behaviors are identical to a regular vector. Elements must be moveable. Note that the order of elements cannot be guareneed. */ template<typename T, typename vec = std::vector<T>> class unordered_vector{ vec underlying; public: typedef typename decltype(underlying)::iterator iterator_type; typedef typename decltype(underlying)::const_iterator const_iterator_type; typedef typename decltype(underlying)::size_type index_type; typedef typename decltype(underlying)::size_type size_type; /** Erase by iterator. Complexity is O(1). @param it the iterator to erase */ inline const_iterator_type erase(iterator_type it){ *it = std::move(underlying.back()); underlying.pop_back(); return it; } /** @return the underlying vector. Do not modify! */ inline const decltype(underlying)& get_underlying() const{ return underlying; } /** Erase by iterator. Complexity is O(n) @param value the data to erase */ inline const_iterator_type erase(const T& value){ auto it = std::find(underlying.begin(),underlying.end(),value); underlying.erase(it); return it; } /** Add an item to the container @param value the data to add @return a reference to the pushed item @note references may become invalid if an item is erased from the container */ inline T& insert(const T& value){ underlying.push_back(value); return underlying.back(); } /** Add an item to the container @param value the data to add @return a reference to the emplaced item @note references may become invalid if an item is erased from the container */ template<typename ... A> inline T& emplace(A ... args){ underlying.emplace_back(args...); return underlying.back(); } inline T& operator[](index_type idx){ return underlying[idx]; } const inline T& operator[](index_type idx) const{ return underlying[idx]; } inline T& at(index_type idx){ return underlying.at(idx); } const inline T& at(index_type idx) const{ return underlying.at(idx); } inline const_iterator_type begin() const{ return underlying.begin(); } inline const_iterator_type end() const{ return underlying.end(); } inline iterator_type end(){ return underlying.end(); } inline iterator_type begin(){ return underlying.begin(); } inline size_type size() const{ return underlying.size(); } inline void reserve(size_t num){ underlying.reserve(num); } inline void resize(size_t num){ underlying.resize(num); } inline bool empty() const{ return underlying.empty(); } inline void clear(){ underlying.clear(); } }; /** The Unordered Contiguous Set provides: - O(1) erase by value - O(1) erase by iterator All other complexities are identical to a regular vector. Elements must be moveable and hashable. Hashes must not have collisions. An imperfect hash will result in unpredictable behavior. Note that the order of elements cannot be guareneed. */ template<typename T,typename vec = std::vector<T>, typename _hash = std::hash<T>> class unordered_contiguous_set : public unordered_vector<T,vec>{ protected: phmap::flat_hash_map<size_t, typename unordered_vector<T,vec>::size_type> offsets; public: typedef typename unordered_vector<T,vec>::iterator_type iterator_type; typedef typename unordered_vector<T,vec>::iterator_type iterator; typedef typename unordered_vector<T,vec>::const_iterator_type const_iterator_type; typedef typename unordered_vector<T,vec>::const_iterator_type const_iterator; // for redundancy typedef typename unordered_vector<T,vec>::size_type index_type; typedef typename unordered_vector<T,vec>::size_type size_type; /** @return the hash for an element. This container does not need to include the element */ inline constexpr size_t hash_for(const T& value) const{ auto hasher = _hash(); return hasher(value); } /** Erase by iterator @param it the iterator to remove */ inline void erase(const typename unordered_vector<T,vec>::iterator_type& it){ // remove from the offset cache auto hasher = _hash(); auto hash = hasher(*it); if (offsets.contains(hash)) { // only erase if the container has the value offsets.erase(hash); // pop from back auto i = unordered_vector<T,vec>::erase(it); // update offset cache hash = hasher(*i); offsets[hash] = std::distance(this->begin(), it); } } /** Erase by element hash @param size_t hash the hash of the element to remove */ constexpr inline void erase_by_hash(size_t hash){ auto it = this->begin() + offsets[hash]; erase(it); } /** Erase by value @param value item to remove */ inline void erase(const T& value){ auto valuehash = _hash()(value); if (offsets.contains(valuehash)) { auto it = this->begin() + offsets[valuehash]; erase(it); } } inline void insert(const T& value){ auto hashcode = _hash()(value); if (!this->offsets.contains(hashcode)){ offsets.emplace(hashcode,this->size()); unordered_vector<T,vec>::insert(value); } } inline void contains(const T& value){ auto valuehash = _hash()(value); return offsets.contains(valuehash); } }; }
27.64455
188
0.652323
Ravbug
53ba76c61e98337aadf73ebd3e280e4db93c4c91
1,827
cpp
C++
book/CH02/S16_Presenting_an_image.cpp
THISISAGOODNAME/vkCookBook
d022b4151a02c33e5c58534dc53ca39610eee7b5
[ "MIT" ]
5
2019-03-02T16:29:15.000Z
2021-11-07T11:07:53.000Z
book/CH02/S16_Presenting_an_image.cpp
THISISAGOODNAME/vkCookBook
d022b4151a02c33e5c58534dc53ca39610eee7b5
[ "MIT" ]
null
null
null
book/CH02/S16_Presenting_an_image.cpp
THISISAGOODNAME/vkCookBook
d022b4151a02c33e5c58534dc53ca39610eee7b5
[ "MIT" ]
2
2018-07-10T18:15:40.000Z
2020-01-03T04:02:32.000Z
// // Created by aicdg on 2017/6/19. // // // Chapter: 02 Image Presentation // Recipe: 16 Presenting an image #include "S16_Presenting_an_image.h" namespace VKCookbook { bool PresentImage(VkQueue queue, std::vector<VkSemaphore> rendering_semaphores, std::vector<PresentInfo> images_to_present) { VkResult result; std::vector<VkSwapchainKHR> swapchains; std::vector<uint32_t> image_indices; for( auto & image_to_present : images_to_present ) { swapchains.emplace_back( image_to_present.Swapchain ); image_indices.emplace_back( image_to_present.ImageIndex ); } VkPresentInfoKHR present_info = { VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, // VkStructureType sType nullptr, // const void* pNext static_cast<uint32_t>(rendering_semaphores.size()), // uint32_t waitSemaphoreCount rendering_semaphores.data(), // const VkSemaphore * pWaitSemaphores static_cast<uint32_t>(swapchains.size()), // uint32_t swapchainCount swapchains.data(), // const VkSwapchainKHR * pSwapchains image_indices.data(), // const uint32_t * pImageIndices nullptr // VkResult* pResults }; result = vkQueuePresentKHR( queue, &present_info ); switch( result ) { case VK_SUCCESS: return true; default: return false; } } }
41.522727
116
0.509031
THISISAGOODNAME
53bf0759144880c94ad882e74dd18a42bbed8403
910
cpp
C++
lab2/Q1.cpp
jasonsie88/OOP-and-DS
fdf76d6e9b3c70e5c7a97401dfe93984b63e5e28
[ "MIT" ]
null
null
null
lab2/Q1.cpp
jasonsie88/OOP-and-DS
fdf76d6e9b3c70e5c7a97401dfe93984b63e5e28
[ "MIT" ]
null
null
null
lab2/Q1.cpp
jasonsie88/OOP-and-DS
fdf76d6e9b3c70e5c7a97401dfe93984b63e5e28
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; class Student { private: string name; string studentID; int score; public: Student(){ } Student(string name, string studentID, int score){ Student:: name=name; Student:: studentID=studentID; Student:: score=score; } string getName(){ return Student:: name; } string getStudentID(){ return Student:: studentID; } int getScore(){ return Student:: score; } }; int main() { string name; string studentID; int score; Student mStudent; cin >> name >> studentID >> score; mStudent = Student(name, studentID, score); cout << mStudent.getName() << "'s studentID is " << mStudent.getStudentID() << " and score is " << mStudent.getScore() << "." << endl; return 0; }
21.162791
80
0.552747
jasonsie88
53c1d1bfbc4f270184ff9e72daeba7920a071150
5,895
cpp
C++
source/QtCore/QFutureWatcherBaseSlots.cpp
kenny1818/qt4xhb
f62f40d8b17acb93761014317b52da9f919707d0
[ "MIT" ]
1
2021-03-07T10:44:03.000Z
2021-03-07T10:44:03.000Z
source/QtCore/QFutureWatcherBaseSlots.cpp
kenny1818/qt4xhb
f62f40d8b17acb93761014317b52da9f919707d0
[ "MIT" ]
null
null
null
source/QtCore/QFutureWatcherBaseSlots.cpp
kenny1818/qt4xhb
f62f40d8b17acb93761014317b52da9f919707d0
[ "MIT" ]
2
2020-07-19T03:28:08.000Z
2021-03-05T18:07:20.000Z
/* Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4 Copyright (C) 2021 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com> */ /* DO NOT EDIT THIS FILE - the content was created using a source code generator */ #include "QFutureWatcherBaseSlots.h" QFutureWatcherBaseSlots::QFutureWatcherBaseSlots( QObject * parent ) : QObject( parent ) { } QFutureWatcherBaseSlots::~QFutureWatcherBaseSlots() { } void QFutureWatcherBaseSlots::started() { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "started()" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); hb_vmEvalBlockV( cb, 1, pSender ); hb_itemRelease( pSender ); } } void QFutureWatcherBaseSlots::finished() { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "finished()" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); hb_vmEvalBlockV( cb, 1, pSender ); hb_itemRelease( pSender ); } } void QFutureWatcherBaseSlots::canceled() { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "canceled()" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); hb_vmEvalBlockV( cb, 1, pSender ); hb_itemRelease( pSender ); } } void QFutureWatcherBaseSlots::paused() { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "paused()" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); hb_vmEvalBlockV( cb, 1, pSender ); hb_itemRelease( pSender ); } } void QFutureWatcherBaseSlots::resumed() { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "resumed()" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); hb_vmEvalBlockV( cb, 1, pSender ); hb_itemRelease( pSender ); } } void QFutureWatcherBaseSlots::resultReadyAt( int resultIndex ) { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "resultReadyAt(int)" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); PHB_ITEM pResultIndex = hb_itemPutNI( NULL, resultIndex ); hb_vmEvalBlockV( cb, 2, pSender, pResultIndex ); hb_itemRelease( pSender ); hb_itemRelease( pResultIndex ); } } void QFutureWatcherBaseSlots::resultsReadyAt( int beginIndex, int endIndex ) { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "resultsReadyAt(int,int)" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); PHB_ITEM pBeginIndex = hb_itemPutNI( NULL, beginIndex ); PHB_ITEM pEndIndex = hb_itemPutNI( NULL, endIndex ); hb_vmEvalBlockV( cb, 3, pSender, pBeginIndex, pEndIndex ); hb_itemRelease( pSender ); hb_itemRelease( pBeginIndex ); hb_itemRelease( pEndIndex ); } } void QFutureWatcherBaseSlots::progressRangeChanged( int minimum, int maximum ) { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "progressRangeChanged(int,int)" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); PHB_ITEM pMinimum = hb_itemPutNI( NULL, minimum ); PHB_ITEM pMaximum = hb_itemPutNI( NULL, maximum ); hb_vmEvalBlockV( cb, 3, pSender, pMinimum, pMaximum ); hb_itemRelease( pSender ); hb_itemRelease( pMinimum ); hb_itemRelease( pMaximum ); } } void QFutureWatcherBaseSlots::progressValueChanged( int progressValue ) { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "progressValueChanged(int)" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); PHB_ITEM pProgressValue = hb_itemPutNI( NULL, progressValue ); hb_vmEvalBlockV( cb, 2, pSender, pProgressValue ); hb_itemRelease( pSender ); hb_itemRelease( pProgressValue ); } } void QFutureWatcherBaseSlots::progressTextChanged( const QString & progressText ) { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "progressTextChanged(QString)" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); PHB_ITEM pProgressText = hb_itemPutC( NULL, QSTRINGTOSTRING( progressText ) ); hb_vmEvalBlockV( cb, 2, pSender, pProgressText ); hb_itemRelease( pSender ); hb_itemRelease( pProgressText ); } } void QFutureWatcherBaseSlots_connect_signal( const QString & signal, const QString & slot ) { QFutureWatcherBase * obj = qobject_cast< QFutureWatcherBase * >( Qt4xHb::getQObjectPointerFromSelfItem() ); if( obj ) { QFutureWatcherBaseSlots * s = QCoreApplication::instance()->findChild<QFutureWatcherBaseSlots *>(); if( s == NULL ) { s = new QFutureWatcherBaseSlots(); s->moveToThread( QCoreApplication::instance()->thread() ); s->setParent( QCoreApplication::instance() ); } hb_retl( Qt4xHb::Signals_connection_disconnection( s, signal, slot ) ); } else { hb_retl( false ); } }
26.917808
110
0.674979
kenny1818
53c3ed79cdbaac28d59dd1e13c36a9e10713d41b
6,671
cc
C++
alljoyn_js/jni/ScriptableObject.cc
liuxiang88/core-alljoyn
549c966482d9b89da84aa528117584e7049916cb
[ "Apache-2.0" ]
33
2018-01-12T00:37:43.000Z
2022-03-24T02:31:36.000Z
alljoyn_js/jni/ScriptableObject.cc
liuxiang88/core-alljoyn
549c966482d9b89da84aa528117584e7049916cb
[ "Apache-2.0" ]
1
2020-01-05T05:51:27.000Z
2020-01-05T05:51:27.000Z
alljoyn_js/jni/ScriptableObject.cc
liuxiang88/core-alljoyn
549c966482d9b89da84aa528117584e7049916cb
[ "Apache-2.0" ]
30
2017-12-13T23:24:00.000Z
2022-01-25T02:11:19.000Z
/* * Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source * Project (AJOSP) Contributors and others. * * SPDX-License-Identifier: Apache-2.0 * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution, and is available at * http://www.apache.org/licenses/LICENSE-2.0 * * Copyright (c) Open Connectivity Foundation and Contributors to AllSeen * Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ #include "ScriptableObject.h" #include "NativeObject.h" #include "npn.h" #include <assert.h> #include <qcc/Debug.h> #include <string.h> #define QCC_MODULE "ALLJOYN_JS" #define CALL_MEMBER(o, m) ((*o).*(m)) std::map<qcc::String, int32_t> ScriptableObject::noConstants; ScriptableObject::ScriptableObject(Plugin& plugin) : plugin(plugin), getter(0), setter(0), deleter(0), enumerator(0), caller(0), constants(noConstants) { QCC_DbgTrace(("%s", __FUNCTION__)); } ScriptableObject::ScriptableObject(Plugin& plugin, std::map<qcc::String, int32_t>& constants) : plugin(plugin), getter(0), setter(0), deleter(0), enumerator(0), caller(0), constants(constants) { QCC_DbgTrace(("%s", __FUNCTION__)); } ScriptableObject::~ScriptableObject() { QCC_DbgTrace(("%s", __FUNCTION__)); } void ScriptableObject::Invalidate() { QCC_DbgTrace(("%s", __FUNCTION__)); } bool ScriptableObject::HasMethod(const qcc::String& name) { QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str())); std::map<qcc::String, Operation>::iterator it = operations.find(name); return (it != operations.end()); } bool ScriptableObject::Invoke(const qcc::String& name, const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str())); std::map<qcc::String, Operation>::iterator it = operations.find(name); if (it != operations.end()) { assert(it->second.call); return CALL_MEMBER(this, it->second.call) (args, argCount, result); } return false; } bool ScriptableObject::InvokeDefault(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_DbgTrace(("%s", __FUNCTION__)); if (caller) { return CALL_MEMBER(this, caller) (args, argCount, result); } return false; } bool ScriptableObject::HasProperty(const qcc::String& name) { QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str())); std::map<qcc::String, int32_t>::iterator cit = constants.find(name); if (cit != constants.end()) { return true; } std::map<qcc::String, Attribute>::iterator ait = attributes.find(name); return (ait != attributes.end()); } bool ScriptableObject::GetProperty(const qcc::String& name, NPVariant* result) { QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str())); std::map<qcc::String, int32_t>::iterator cit = constants.find(name); if (cit != constants.end()) { INT32_TO_NPVARIANT(cit->second, *result); return true; } std::map<qcc::String, Attribute>::iterator ait = attributes.find(name); if (ait != attributes.end()) { assert(ait->second.get); return CALL_MEMBER(this, ait->second.get) (result); } if (getter) { return CALL_MEMBER(this, getter) (name, result); } return false; } bool ScriptableObject::SetProperty(const qcc::String& name, const NPVariant* value) { QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str())); /* * Workaround for WebKit browsers. "delete obj.property" doesn't call RemoveProperty, so allow * "obj.property = undefined" to do the same thing. */ if (NPVARIANT_IS_VOID(*value)) { return RemoveProperty(name); } std::map<qcc::String, Attribute>::iterator it = attributes.find(name); if ((it != attributes.end()) && it->second.set) { return CALL_MEMBER(this, it->second.set) (value); } if (setter) { return CALL_MEMBER(this, setter) (name, value); } return false; } bool ScriptableObject::RemoveProperty(const qcc::String& name) { QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str())); if (deleter) { return CALL_MEMBER(this, deleter) (name); } return false; } bool ScriptableObject::Enumerate(NPIdentifier** value, uint32_t* count) { QCC_DbgTrace(("%s", __FUNCTION__)); *value = NULL; *count = 0; NPIdentifier* enumeratorValue = NULL; uint32_t enumeratorCount = 0; if (enumerator) { CALL_MEMBER(this, enumerator) (&enumeratorValue, &enumeratorCount); } *count = enumeratorCount + constants.size() + attributes.size() + operations.size(); if (*count) { *value = reinterpret_cast<NPIdentifier*>(NPN_MemAlloc(*count * sizeof(NPIdentifier))); NPIdentifier* v = *value; for (uint32_t i = 0; i < enumeratorCount; ++i) { *v++ = enumeratorValue[i]; } if (enumeratorValue) { NPN_MemFree(enumeratorValue); } for (std::map<qcc::String, int32_t>::iterator it = constants.begin(); it != constants.end(); ++it) { *v++ = NPN_GetStringIdentifier(it->first.c_str()); } for (std::map<qcc::String, Attribute>::iterator it = attributes.begin(); it != attributes.end(); ++it) { *v++ = NPN_GetStringIdentifier(it->first.c_str()); } for (std::map<qcc::String, Operation>::iterator it = operations.begin(); it != operations.end(); ++it) { *v++ = NPN_GetStringIdentifier(it->first.c_str()); } } return true; } bool ScriptableObject::Construct(const NPVariant* args, uint32_t argCount, NPVariant* result) { QCC_UNUSED(args); QCC_UNUSED(argCount); QCC_UNUSED(result); QCC_DbgTrace(("%s", __FUNCTION__)); return false; }
32.227053
115
0.653275
liuxiang88
53cc3cee63f5e72f8f8ef2ed867e47459b546d2b
8,973
cpp
C++
CGALib/src/Model.cpp
jorge-jcc/MarioCraftv2
f0870721685452b2b39df1004f4be26f2dfb3629
[ "Xnet", "X11" ]
null
null
null
CGALib/src/Model.cpp
jorge-jcc/MarioCraftv2
f0870721685452b2b39df1004f4be26f2dfb3629
[ "Xnet", "X11" ]
null
null
null
CGALib/src/Model.cpp
jorge-jcc/MarioCraftv2
f0870721685452b2b39df1004f4be26f2dfb3629
[ "Xnet", "X11" ]
null
null
null
/* * Model.cpp * * Created on: 13/09/2016 * Author: rey */ #include "Headers/Model.h" #include "Headers/TimeManager.h" #include "Headers/mathUtil.h" Model::Model() { this->aabb.mins.x = FLT_MAX; this->aabb.mins.y = FLT_MAX; this->aabb.mins.z = FLT_MAX; this->aabb.maxs.x = -FLT_MAX; this->aabb.maxs.y = -FLT_MAX; this->aabb.maxs.z = -FLT_MAX; this->animationIndex = 0; } Model::~Model() { for (GLuint i = 0; i < this->meshes.size(); i++){ delete this->meshes[i]->bones; delete this->meshes[i]; } for (int i = 0; i < this->textureLoaded.size(); i++) delete this->textureLoaded[i]; } void Model::render(glm::mat4 parentTrans) { float runningTime = TimeManager::Instance().GetRunningTime(); //float runningTime = TimeManager::Instance().DeltaTime; for (GLuint i = 0; i < this->meshes.size(); i++) { this->meshes[i]->setShader(this->getShader()); this->meshes[i]->setPosition(this->getPosition()); this->meshes[i]->setScale(this->getScale()); this->meshes[i]->setOrientation(this->getOrientation()); if(scene->mNumAnimations > 0){ this->meshes[i]->bones->setAnimationIndex(this->animationIndex); if(this->meshes[i]->bones != nullptr){ shader_ptr->setInt("numBones", this->meshes[i]->bones->getNumBones()); std::vector<glm::mat4> transforms; this->meshes[i]->bones->bonesTransform(runningTime, transforms, scene); for (unsigned int j = 0; j < transforms.size(); j++) { std::stringstream ss; ss << "bones[" << j << "]"; shader_ptr->setMatrix4(ss.str(), 1, GL_FALSE, glm::value_ptr(m_GlobalInverseTransform * transforms[j])); } } else parentTrans = m_GlobalInverseTransform * parentTrans; } this->meshes[i]->render(parentTrans); glActiveTexture(GL_TEXTURE0); shader_ptr->setInt("numBones", 0); } } void Model::loadModel(const std::string & path) { // Lee el archivo via ASSIMP scene = importer.ReadFile(path.c_str(), aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_GenSmoothNormals | aiProcess_CalcTangentSpace); // Revisa errores if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero { std::cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << std::endl; return; } CopyMat(scene->mRootNode->mTransformation, this->m_GlobalInverseTransform); this->m_GlobalInverseTransform = glm::inverse( this->m_GlobalInverseTransform); // Recupera el path del directorio del archivo. this->directory = path.substr(0, path.find_last_of('/')); // Se procesa el nodo raiz recursivamente. this->processNode(scene->mRootNode, scene); // Se crea la SBB this->sbb.c = glm::vec3((this->aabb.mins.x + this->aabb.maxs.x) / 2.0f, (this->aabb.mins.y + this->aabb.maxs.y) / 2.0f, (this->aabb.mins.z + this->aabb.maxs.z) / 2.0f); /*this->sbb.ratio = sqrt( pow(this->aabb.mins.x - this->aabb.maxs.x, 2) + pow(this->aabb.mins.y - this->aabb.maxs.y, 2) + pow(this->aabb.mins.z - this->aabb.maxs.z, 2)) / 2.0f;*/ float disX = fabs(this->aabb.mins.x - this->aabb.maxs.x); float disY = fabs(this->aabb.mins.y - this->aabb.maxs.y); float disZ = fabs(this->aabb.mins.z - this->aabb.maxs.z); float rtmp = std::max(disX, disY); rtmp = std::max(rtmp, disZ); this->sbb.ratio = rtmp / 2.f; // Se crea la obb this->obb.c = this->sbb.c; /*this->obb.e.x = aabb.maxs.x - aabb.mins.x; this->obb.e.y = aabb.maxs.y - aabb.mins.y; this->obb.e.z = aabb.maxs.z - aabb.mins.z;*/ this->obb.e = (aabb.maxs - aabb.mins) / 2.0f; this->obb.u = glm::quat(0.0, 0.0, 0.0, 1); } void Model::processNode(aiNode* node, const aiScene* scene) { // Procesa cada maya del nodo actual for (GLuint i = 0; i < node->mNumMeshes; i++) { aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; Mesh * meshModel = this->processMesh(mesh, scene); Bones * bones = new Bones(meshModel->getVAO(), mesh->mNumVertices); bones->loadBones(i, mesh); meshModel->bones = bones; this->meshes.push_back(meshModel); } for (GLuint i = 0; i < node->mNumChildren; i++) { this->processNode(node->mChildren[i], scene); } } Mesh * Model::processMesh(aiMesh* mesh, const aiScene* scene) { std::vector<AbstractModel::Vertex> vertices; std::vector<GLuint> indices; std::vector<Texture*> textures; // Recorre los vertices de cada maya for (GLuint i = 0; i < mesh->mNumVertices; i++) { AbstractModel::Vertex vertex; glm::vec3 vector; // Compute the AABB if (mesh->mVertices[i].x < aabb.mins.x) aabb.mins.x = mesh->mVertices[i].x; if (mesh->mVertices[i].x > aabb.maxs.x) aabb.maxs.x = mesh->mVertices[i].x; if (mesh->mVertices[i].y < aabb.mins.y) aabb.mins.y = mesh->mVertices[i].y; if (mesh->mVertices[i].y > aabb.maxs.y) aabb.maxs.y = mesh->mVertices[i].y; if (mesh->mVertices[i].z < aabb.mins.z) aabb.mins.z = mesh->mVertices[i].z; if (mesh->mVertices[i].z > aabb.maxs.z) aabb.maxs.z = mesh->mVertices[i].z; // Positions vector.x = mesh->mVertices[i].x; vector.y = mesh->mVertices[i].y; vector.z = mesh->mVertices[i].z; vertex.m_pos = vector; // Normals vector.x = mesh->mNormals[i].x; vector.y = mesh->mNormals[i].y; vector.z = mesh->mNormals[i].z; vertex.m_normal = vector; // Texture Coordinates if (mesh->mTextureCoords[0]) // Esto se ejecuta si la maya contiene texturas. { glm::vec2 vec; // Un vertice puede contener hasta 8 diferentes coordenadas de textura, unicamente se considera // que los modelos tiene una coordenada de textura por vertice, y corresponde a la primera en el arreglo. vec.x = mesh->mTextureCoords[0][i].x; vec.y = mesh->mTextureCoords[0][i].y; vertex.m_tex = vec; } else vertex.m_tex = glm::vec2(0.0f, 0.0f); vertices.push_back(vertex); } // Se recorre cada cara de la maya (una cara es un triangulo en la maya) y recupera su correspondiente indice del vertice. for (GLuint i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; // Recupera todos los indices de la cara y los almacena en el vector de indices for (GLuint j = 0; j < face.mNumIndices; j++) indices.push_back(face.mIndices[j]); } // Process materials if (mesh->mMaterialIndex >= 0) { aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex]; // We assume a convention for sampler names in the shaders. Each diffuse texture should be named // as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER. // Same applies to other texture as the following list summarizes: // Diffuse: texture_diffuseN // Specular: texture_specularN // Normal: texture_normalN // 1. Diffuse maps std::vector<Texture*> diffuseMaps = this->loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse"); textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end()); // 2. Specular maps std::vector<Texture*> specularMaps = this->loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular"); textures.insert(textures.end(), specularMaps.begin(), specularMaps.end()); // 3. Normal maps std::vector<Texture*> normalMaps = this->loadMaterialTextures(material, aiTextureType_NORMALS, "texture_normal"); textures.insert(textures.end(), normalMaps.begin(), normalMaps.end()); // 4. Height maps std::vector<Texture*> heightMaps = this->loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_height"); textures.insert(textures.end(), heightMaps.begin(), heightMaps.end()); } Mesh * meshModel = new Mesh(vertices, indices, textures); // Regresa la maya de un objeto creado de los datos extraidos. return meshModel; } std::vector<Texture*> Model::loadMaterialTextures(aiMaterial* mat, aiTextureType type, std::string typeName) { std::vector<Texture*> textures; for (GLuint i = 0; i < mat->GetTextureCount(type); i++) { aiString str; mat->GetTexture(type, i, &str); // Verifica si la textura fue cargada antes y si es as�, continua con la siguiente iteracion: en caso controaio se salta la carga GLboolean skip = false; for (GLuint j = 0; j < textureLoaded.size(); j++) { if (textureLoaded[j]->getFileName() == str.C_Str()) { textures.push_back(textureLoaded[j]); skip = true; break; } } if (!skip) { std::string filename = std::string(str.C_Str()); filename = this->directory + '/' + filename; Texture * texture = new Texture(GL_TEXTURE_2D, filename); texture->load(); texture->setType(typeName); textures.push_back(texture); this->textureLoaded.push_back(texture); // Store it as texture loaded for entire model, to ensure we won't unnecesery load duplicate textures. } } return textures; } bool Model::rayPicking(glm::vec3 init, glm::vec3 end, glm::vec3 &intersection) { return false; }
36.77459
146
0.657528
jorge-jcc
53cffcce8f6c207095d511f4629668bd41857bb6
10,689
cpp
C++
iOS/G3MApp/G3MApp/G3MHUDDemoScene.cpp
AeroGlass/g3m
a21a9e70a6205f1f37046ae85dafc6e3bfaeb917
[ "BSD-2-Clause" ]
null
null
null
iOS/G3MApp/G3MApp/G3MHUDDemoScene.cpp
AeroGlass/g3m
a21a9e70a6205f1f37046ae85dafc6e3bfaeb917
[ "BSD-2-Clause" ]
null
null
null
iOS/G3MApp/G3MApp/G3MHUDDemoScene.cpp
AeroGlass/g3m
a21a9e70a6205f1f37046ae85dafc6e3bfaeb917
[ "BSD-2-Clause" ]
null
null
null
// // G3MHUDDemoScene.cpp // G3MApp // // Created by Diego Gomez Deck on 12/2/14. // Copyright (c) 2014 Igo Software SL. All rights reserved. // #include "G3MHUDDemoScene.hpp" //#include <G3MiOSSDK/G3MWidget.hpp> #include <G3MiOSSDK/MapBoxLayer.hpp> #include <G3MiOSSDK/LayerSet.hpp> #include <G3MiOSSDK/CanvasImageBuilder.hpp> #include <G3MiOSSDK/ICanvas.hpp> #include <G3MiOSSDK/Color.hpp> #include <G3MiOSSDK/IStringUtils.hpp> #include <G3MiOSSDK/GFont.hpp> #include <G3MiOSSDK/Context.hpp> #include <G3MiOSSDK/HUDQuadWidget.hpp> #include <G3MiOSSDK/HUDRenderer.hpp> #include <G3MiOSSDK/HUDRelativePosition.hpp> #include <G3MiOSSDK/HUDRelativeSize.hpp> #include <G3MiOSSDK/LabelImageBuilder.hpp> #include <G3MiOSSDK/DownloaderImageBuilder.hpp> #include <G3MiOSSDK/HUDAbsolutePosition.hpp> #include <G3MiOSSDK/GTask.hpp> #include <G3MiOSSDK/G3MWidget.hpp> #include <G3MiOSSDK/PeriodicalTask.hpp> #include "G3MDemoModel.hpp" class AltimeterCanvasImageBuilder : public CanvasImageBuilder { private: float _altitude = 38500; float _step = 100; protected: void buildOnCanvas(const G3MContext* context, ICanvas* canvas) { const float width = canvas->getWidth(); const float height = canvas->getHeight(); canvas->setFillColor(Color::fromRGBA(0, 0, 0, 0.5)); canvas->fillRectangle(0, 0, width, height); canvas->setFillColor(Color::white()); const IStringUtils* su = context->getStringUtils(); int altitude = _altitude; canvas->setFont(GFont::monospaced(32)); for (int y = 0; y <= height; y += 16) { if ((y % 80) == 0) { canvas->fillRectangle(0, y-1.5f, width/6.0f, 3); const std::string label = su->toString(altitude); const Vector2F labelExtent = canvas->textExtent(label); canvas->fillText(label, width/6.0f * 1.25f, y - labelExtent._y/2); altitude -= 100; } else { canvas->fillRectangle(0, y-0.5f, width/8.0f, 1); } } canvas->setLineColor(Color::white()); canvas->setLineWidth(8); canvas->strokeRectangle(0, 0, width, height); } public: AltimeterCanvasImageBuilder() : CanvasImageBuilder(256, 256*3) { } bool isMutable() const { return true; } void step() { _altitude += _step; if (_altitude > 40000) { _altitude = 40000; _step *= -1; } if (_altitude < 0) { _altitude = 0; _step *= -1; } changed(); } }; class AnimateHUDWidgetsTask : public GTask { private: HUDQuadWidget* _compass1; HUDQuadWidget* _compass2; HUDQuadWidget* _ruler; LabelImageBuilder* _labelBuilder; AltimeterCanvasImageBuilder* _altimeterCanvasImageBuilder; double _angleInRadians; float _translationV; float _translationStep; public: AnimateHUDWidgetsTask(HUDQuadWidget* compass1, HUDQuadWidget* compass2, HUDQuadWidget* ruler, LabelImageBuilder* labelBuilder, AltimeterCanvasImageBuilder* altimeterCanvasImageBuilder) : _compass1(compass1), _compass2(compass2), _ruler(ruler), _labelBuilder(labelBuilder), _altimeterCanvasImageBuilder(altimeterCanvasImageBuilder), _angleInRadians(0), _translationV(0), _translationStep(0.002) { } void run(const G3MContext* context) { _angleInRadians += Angle::fromDegrees(2)._radians; // _labelBuilder->setText( Angle::fromRadians(_angleInRadians).description() ); double degrees = Angle::fromRadians(_angleInRadians)._degrees; while (degrees > 360) { degrees -= 360; } const std::string degreesText = IStringUtils::instance()->toString( IMathUtils::instance()->round( degrees ) ); _labelBuilder->setText( " " + degreesText ); // _compass1->setTexCoordsRotation(_angleInRadians, // 0.5f, 0.5f); _compass2->setTexCoordsRotation(-_angleInRadians, 0.5f, 0.5f); // _compass3->setTexCoordsRotation(Angle::fromRadians(_angle), // 0.5f, 0.5f); if (_translationV > 0.5 || _translationV < 0) { _translationStep *= -1; } _translationV += _translationStep; _ruler->setTexCoordsTranslation(0, _translationV); _altimeterCanvasImageBuilder->step(); } }; void G3MHUDDemoScene::rawActivate(const G3MContext *context) { G3MDemoModel* model = getModel(); G3MWidget* g3mWidget = model->getG3MWidget(); MapBoxLayer* layer = new MapBoxLayer("examples.map-m0t0lrpu", TimeInterval::fromDays(30), true, 2); model->getLayerSet()->addLayer(layer); HUDRenderer* hudRenderer = model->getHUDRenderer(); AltimeterCanvasImageBuilder* altimeterCanvasImageBuilder = new AltimeterCanvasImageBuilder(); HUDQuadWidget* test = new HUDQuadWidget(altimeterCanvasImageBuilder, new HUDRelativePosition(0, HUDRelativePosition::VIEWPORT_WIDTH, HUDRelativePosition::RIGHT, 10), new HUDRelativePosition(0.5, HUDRelativePosition::VIEWPORT_HEIGHT, HUDRelativePosition::MIDDLE), new HUDRelativeSize(0.22, HUDRelativeSize::VIEWPORT_MIN_AXIS), new HUDRelativeSize(0.66, HUDRelativeSize::VIEWPORT_MIN_AXIS) ); hudRenderer->addWidget(test); LabelImageBuilder* labelBuilder = new LabelImageBuilder("glob3", // text GFont::monospaced(38), // font 6, // margin Color::yellow(), // color Color::black(), // shadowColor 3, // shadowBlur 1, // shadowOffsetX -1, // shadowOffsetY Color::red(), // backgroundColor 4, // cornerRadius true // mutable ); HUDQuadWidget* label = new HUDQuadWidget(labelBuilder, new HUDAbsolutePosition(10), new HUDAbsolutePosition(10), new HUDRelativeSize(1, HUDRelativeSize::BITMAP_WIDTH), new HUDRelativeSize(1, HUDRelativeSize::BITMAP_HEIGHT) ); hudRenderer->addWidget(label); HUDQuadWidget* compass2 = new HUDQuadWidget(new DownloaderImageBuilder(URL("file:///CompassHeadings.png")), new HUDRelativePosition(0.5, HUDRelativePosition::VIEWPORT_WIDTH, HUDRelativePosition::CENTER), new HUDRelativePosition(0.5, HUDRelativePosition::VIEWPORT_HEIGHT, HUDRelativePosition::MIDDLE), new HUDRelativeSize(0.25, HUDRelativeSize::VIEWPORT_MIN_AXIS), new HUDRelativeSize(0.125, HUDRelativeSize::VIEWPORT_MIN_AXIS)); compass2->setTexCoordsRotation(Angle::fromDegrees(30), 0.5f, 0.5f); compass2->setTexCoordsScale(1, 0.5f); hudRenderer->addWidget(compass2); float visibleFactor = 3; HUDQuadWidget* ruler = new HUDQuadWidget(new DownloaderImageBuilder(URL("file:///altimeter-ruler-1536x113.png")), new HUDRelativePosition(1, HUDRelativePosition::VIEWPORT_WIDTH, HUDRelativePosition::LEFT, 10), new HUDRelativePosition(0.5, HUDRelativePosition::VIEWPORT_HEIGHT, HUDRelativePosition::MIDDLE), new HUDRelativeSize(2 * (113.0 / 1536.0), HUDRelativeSize::VIEWPORT_MIN_AXIS), new HUDRelativeSize(2 / visibleFactor, HUDRelativeSize::VIEWPORT_MIN_AXIS), new DownloaderImageBuilder(URL("file:///widget-background.png"))); ruler->setTexCoordsScale(1 , 1.0f / visibleFactor); hudRenderer->addWidget(ruler); g3mWidget->addPeriodicalTask(new PeriodicalTask(TimeInterval::fromMilliseconds(50), new AnimateHUDWidgetsTask(label, compass2, ruler, labelBuilder, altimeterCanvasImageBuilder))); }
41.27027
116
0.477874
AeroGlass
53d1654bd095104482205740dbd1d2022d6be557
1,346
hpp
C++
Hardware/src/hard/rpi_gpio.hpp
torunxxx001/BookCollectionSystem
cce2942e30c460949ba729db432f0efdd66f8465
[ "MIT" ]
null
null
null
Hardware/src/hard/rpi_gpio.hpp
torunxxx001/BookCollectionSystem
cce2942e30c460949ba729db432f0efdd66f8465
[ "MIT" ]
null
null
null
Hardware/src/hard/rpi_gpio.hpp
torunxxx001/BookCollectionSystem
cce2942e30c460949ba729db432f0efdd66f8465
[ "MIT" ]
null
null
null
/* 参考PDF[BCM2835-ARM-Peripherals.pdf] */ /* RaspberryPI用GPIO操作プログラム */ /* 対応表 PIN NAME 0 GPIO 2(SDA) 1 GPIO 3(SCL) 2 GPIO 4(GPCLK0) 3 GPIO 7(CE1) 4 GPIO 8(CE0) 5 GPIO 9(MISO) 6 GPIO 10(MOSI) 7 GPIO 11(SCLK) 8 GPIO 14(TXD) 9 GPIO 15(RXD) 10 GPIO 17 11 GPIO 18(PCM_CLK) 12 GPIO 22 13 GPIO 23 14 GPIO 24 15 GPIO 25 16 GPIO 27(PCM_DOUT) 17 GPIO 28 18 GPIO 29 19 GPIO 30 20 GPIO 31 */ #ifndef __RPI_GPIO_HPP__ #define __RPI_GPIO_HPP__ /* バスアクセス用物理アドレス(Page.6 - 1.2.3) */ #define PHADDR_OFFSET 0x20000000 /* GPIOコントロールレジスタへのオフセット(Page.90 - 6.1) */ #define GPIO_CONTROL_OFFSET (PHADDR_OFFSET + 0x200000) /* GPFSEL0からGPLEVまでのサイズ */ #define GPCONT_SIZE 0x3C /* 各レジスタへのオフセット */ #define GPFSEL_OFFSET 0x00 #define GPSET_OFFSET 0x1C #define GPCLR_OFFSET 0x28 #define GPLEV_OFFSET 0x34 /* モード定義 */ #define GPIO_INPUT 0 #define GPIO_OUTPUT 1 #define GPIO_ALT0 4 #define GPIO_ALT1 5 #define GPIO_ALT2 6 #define GPIO_ALT3 7 #define GPIO_ALT4 3 #define GPIO_ALT5 2 #define HIGH 1 #define LOW 0 extern const char* PINtoNAME[]; //GPIOコントロール用クラス class gpio { private: //GPIOマッピング用ポインタ static volatile unsigned int* gpio_control; static int instance_count; public: gpio(); ~gpio(); void mode_write(int pin, int mode); void mode_read(int pin, int* mode); void data_write(int pin, int data); void data_read(int pin, int* data); }; #endif
16.02381
54
0.732541
torunxxx001
53d19d2e5ac46e190dc814d6c6e9592c5831fbe9
1,137
cpp
C++
src/query_tatami.cpp
LTLA/diet.scran
c274bf058e10c174a06a409af50fcad225d40f0d
[ "MIT" ]
null
null
null
src/query_tatami.cpp
LTLA/diet.scran
c274bf058e10c174a06a409af50fcad225d40f0d
[ "MIT" ]
null
null
null
src/query_tatami.cpp
LTLA/diet.scran
c274bf058e10c174a06a409af50fcad225d40f0d
[ "MIT" ]
null
null
null
#include "tatami/tatami.h" #include "Rcpp.h" #include "tatamize.h" //[[Rcpp::export(rng=false)]] Rcpp::IntegerVector tatami_dim(SEXP x) { auto ptr = extract_NumericMatrix(x); return Rcpp::IntegerVector::create(ptr->nrow(), ptr->ncol()); } //[[Rcpp::export(rng=false)]] Rcpp::NumericMatrix tatami_rows(SEXP x, Rcpp::IntegerVector rows, int first, int last) { auto ptr = extract_NumericMatrix(x); size_t nc = last - first; Rcpp::NumericMatrix output(nc, rows.size()); double* optr = output.begin(); auto wrk = ptr->new_workspace(true); for (auto r : rows) { ptr->row_copy(r, optr, first, last, wrk.get()); } return Rcpp::transpose(output); } //[[Rcpp::export(rng=false)]] Rcpp::NumericMatrix tatami_columns(SEXP x, Rcpp::IntegerVector columns, int first, int last) { auto ptr = extract_NumericMatrix(x); size_t nr = last - first; Rcpp::NumericMatrix output(nr, columns.size()); double* optr = output.begin(); auto wrk = ptr->new_workspace(false); for (auto c : columns) { ptr->column_copy(c, optr, first, last, wrk.get()); } return output; }
27.071429
94
0.648197
LTLA
53d3d8fbf496c15a7e0b017d0d78183d4f70afc5
1,256
cpp
C++
Bit Manipulation/1835. Find XOR Sum of All Pairs Bitwise AND.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
138
2020-02-08T05:25:26.000Z
2021-11-04T11:59:28.000Z
Bit Manipulation/1835. Find XOR Sum of All Pairs Bitwise AND.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
null
null
null
Bit Manipulation/1835. Find XOR Sum of All Pairs Bitwise AND.cpp
beckswu/Leetcode
480e8dc276b1f65961166d66efa5497d7ff0bdfd
[ "MIT" ]
24
2021-01-02T07:18:43.000Z
2022-03-20T08:17:54.000Z
/* We all know the distributive property that (a1+a2)*(b1+b2) = a1*b1 + a1*b2 + a2*b1 + a2*b2 Explanation Distributive property is similar for AND and XOR here. (a1^a2) & (b1^b2) = (a1&b1) ^ (a1&b2) ^ (a2&b1) ^ (a2&b2) (I wasn't aware of this at first either) 另一种思路, 如果所有arr2 中的数 第一个bit 是奇数个(求所有数第一位bit的xor),if arr1[0] 第一个bit 为 1, 那么第一个 bit 可以留下来 如果所有arr2 中的数 第二个bit 是奇数个(求所有数第二位bit的xor),if arr1[0] 第二个bit 为 1, 那么第二个 bit 可以留下来 : : : : : : : : : : : : : : : : : : : : 如果所有arr2 中的数 第n个bit 是奇数个(求所有数第n位bit的xor),if arr1[0] 第n个bit 为 1, 那么第二个 bit 可以留下来 把这n 个 bit 结合到一起(xorb),就是 (arr1[0] & arr2 [0]) ^ (arr1[0] & arr2[1]) ... (arr1[0] & arr2[n2-1]) */ class Solution { public: int getXORSum(vector<int>& arr1, vector<int>& arr2) { int xora = 0, xorb = 0; for (int& a: arr1) xora ^= a; for (int& b: arr2) xorb ^= b; return xora & xorb; } }; class Solution { public: int getXORSum(vector<int>& arr1, vector<int>& arr2) { int xorb = 0; for (int& b: arr2) xorb ^= b; int ret = 0; for (int& a: arr1) ret ^= (xorb & a); return ret; } };
26.723404
104
0.514331
beckswu
53d43ebb01cd7590624edbe6e9033bcf44f6d4ad
291
cpp
C++
Graph/DSU.cpp
scortier/DSA-Complete-Sheet
925a5cb148d9addcb32192fe676be76bfb2915c7
[ "MIT" ]
1
2021-07-20T06:08:26.000Z
2021-07-20T06:08:26.000Z
Graph/DSU.cpp
scortier/DSA-Complete-Sheet
925a5cb148d9addcb32192fe676be76bfb2915c7
[ "MIT" ]
null
null
null
Graph/DSU.cpp
scortier/DSA-Complete-Sheet
925a5cb148d9addcb32192fe676be76bfb2915c7
[ "MIT" ]
null
null
null
#define MAX 20001 int par[MAX], sz[MAX]; void init(int v) { par[v] = v; sz[v] = 1; } int find(int v) { return v == par[v] ? v : par[v] = find(par[v]); } void join(int u, int v) { u = find(u), v = find(v); if(u != v) { if(sz[u] < sz[v]) swap(u, v); par[v] = u; sz[u] += sz[v]; } }
17.117647
48
0.484536
scortier
53d6db547db42be009f19c81dd2f8ad1d67d5f6a
1,070
cpp
C++
Pm2Service/Pm2Helper.cpp
thebecwar/PM2Service
594fdc39f734a425ccd61fd6132755f32882afb6
[ "MIT" ]
null
null
null
Pm2Service/Pm2Helper.cpp
thebecwar/PM2Service
594fdc39f734a425ccd61fd6132755f32882afb6
[ "MIT" ]
null
null
null
Pm2Service/Pm2Helper.cpp
thebecwar/PM2Service
594fdc39f734a425ccd61fd6132755f32882afb6
[ "MIT" ]
null
null
null
#include "Pm2Helper.h" #include "Process.h" #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <PathCch.h> #include <locale> #include <codecvt> #include <string> #include <sstream> void ConvertNarrowToWide(std::string& narrow, std::wstring& wide) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; wide = converter.from_bytes(narrow); } void FindPm2Path(std::wstring& path) { std::wstring command(L"node -e \"process.stdout.write(require.resolve('pm2/bin/pm2'))\""); wchar_t buf[MAX_PATH]; GetModuleFileNameW(NULL, buf, MAX_PATH); PathCchRemoveFileSpec(buf, MAX_PATH); std::wstring programPath(buf); Process proc(command); proc.SetWorkingDir(programPath); proc.StartProcess(); std::string pm2path; proc.ReadStdOut(pm2path); ConvertNarrowToWide(pm2path, path); } void BuildPm2Command(std::wstring& args, std::wstring& target) { std::wstring pm2path; FindPm2Path(pm2path); std::wstringstream ss; ss << L"node.exe \"" << pm2path << L"\" " << args; target = ss.str(); }
23.777778
94
0.692523
thebecwar
53d7aa80fd1ff968638b54548a45f3b42086a965
517
cpp
C++
unittest/tests/JsonTest/source/Application.cpp
Hurleyworks/Ketone
97c0c730a6e3155154a0ccb87a535e109dfa3c7d
[ "Apache-2.0" ]
1
2021-04-01T01:16:33.000Z
2021-04-01T01:16:33.000Z
unittest/tests/JsonTest/source/Application.cpp
Hurleyworks/Ketone
97c0c730a6e3155154a0ccb87a535e109dfa3c7d
[ "Apache-2.0" ]
null
null
null
unittest/tests/JsonTest/source/Application.cpp
Hurleyworks/Ketone
97c0c730a6e3155154a0ccb87a535e109dfa3c7d
[ "Apache-2.0" ]
null
null
null
#include "Jahley.h" #include <json.hpp> const std::string APP_NAME = "JsonTest"; #ifdef CHECK #undef CHECK #endif #define DOCTEST_CONFIG_IMPLEMENT #include "doctest.h" using json = nlohmann::json; class Application : public Jahley::App { public: Application(DesktopWindowSettings settings = DesktopWindowSettings(), bool windowApp = false) : Jahley::App(settings, windowApp) { doctest::Context().run(); } private: }; Jahley::App* Jahley::CreateApplication() { return new Application(); }
14.771429
98
0.709865
Hurleyworks
53d7f6e0454d6351e2ae3cdadf79ee85ae0b982e
265
cpp
C++
1480 Running Sum of 1d Array.cpp
akash2099/LeetCode-Problems
74c346146ca5ba2336d1e8d6dc26e3cd8920cb25
[ "MIT" ]
1
2021-11-14T01:06:38.000Z
2021-11-14T01:06:38.000Z
1480 Running Sum of 1d Array.cpp
akash2099/LeetCode-Problems
74c346146ca5ba2336d1e8d6dc26e3cd8920cb25
[ "MIT" ]
null
null
null
1480 Running Sum of 1d Array.cpp
akash2099/LeetCode-Problems
74c346146ca5ba2336d1e8d6dc26e3cd8920cb25
[ "MIT" ]
null
null
null
class Solution { public: vector<int> runningSum(vector<int>& nums) { // input: nums array nums = [1,2,3,4] for(int i=1;i<nums.size();i++){ nums[i]=nums[i-1]+nums[i]; } return nums; } };
18.928571
47
0.441509
akash2099
53d82a58d6860797fcbbc6ec091433cc8d8e9769
1,402
cpp
C++
FERMIONS/WILSON/LoopMacros.cpp
markmace/OVERLAP
2d26366aa862cbd36182db8ee3165d9fe4d3e704
[ "MIT" ]
1
2020-12-13T03:11:03.000Z
2020-12-13T03:11:03.000Z
FERMIONS/WILSON/LoopMacros.cpp
markmace/OVERLAP
2d26366aa862cbd36182db8ee3165d9fe4d3e704
[ "MIT" ]
null
null
null
FERMIONS/WILSON/LoopMacros.cpp
markmace/OVERLAP
2d26366aa862cbd36182db8ee3165d9fe4d3e704
[ "MIT" ]
null
null
null
#ifndef __LOOP_MACROS_CPP__ #define __LOOP_MACROS_CPP__ #define START_FERMION_LOOP(gMatrixCoupling) \ \ for(INT i=0;i<Nc;i++){ \ for(INT j=0;j<Nc;j++){ \ \ for(INT alpha=0;alpha<DiracAlgebra::SpinorComponents;alpha++){\ for(INT beta=0;beta<DiracAlgebra::SpinorComponents;beta++){ \ \ if(gMatrixCoupling[alpha][beta]!=0.0){ \ #define END_FERMION_LOOP \ }\ }\ }\ }\ } #define START_FERMION_LOOP_2(gMatrixCoupling,gMatrixCoupling2) \ \ for(INT i=0;i<Nc;i++){ \ for(INT j=0;j<Nc;j++){ \ \ for(INT alpha=0;alpha<DiracAlgebra::SpinorComponents;alpha++){\ for(INT beta=0;beta<DiracAlgebra::SpinorComponents;beta++){ \ \ if(gMatrixCoupling[alpha][beta]!=0.0 || gMatrixCoupling2[alpha][beta]!=0.0){ \ #define END_FERMION_LOOP \ }\ }\ }\ }\ } #define START_LOCAL_FERMION_LOOP(gMatrixCoupling) \ \ for(INT i=0;i<Nc;i++){ \ \ for(INT alpha=0;alpha<DiracAlgebra::SpinorComponents;alpha++){\ for(INT beta=0;beta<DiracAlgebra::SpinorComponents;beta++){ \ \ if(gMatrixCoupling[alpha][beta]!=0.0){ \ #define END_LOCAL_FERMION_LOOP \ }\ }\ }\ } #define START_LOCAL_FERMION_LOOP_2(gMatrixCoupling,gMatrixCoupling2) \ \ for(INT i=0;i<Nc;i++){ \ \ for(INT alpha=0;alpha<DiracAlgebra::SpinorComponents;alpha++){\ for(INT beta=0;beta<DiracAlgebra::SpinorComponents;beta++){ \ \ if(gMatrixCoupling[alpha][beta]!=0.0 || gMatrixCoupling2[alpha][beta]!=0.0){ \ #define END_LOCAL_FERMION_LOOP \ }\ }\ }\ } #endif
18.207792
78
0.702568
markmace
53dbaa396bff25abf48fc6ac3065b6f56a0bcd80
2,156
cpp
C++
sources/thelib/src/mediaformats/readers/mp4/atomhdlr.cpp
rdkcmf/rdkc-rms
65ab1efcee9e3de46a888c125f591cd48b815601
[ "Apache-2.0" ]
3
2020-07-30T19:41:00.000Z
2020-10-28T12:52:37.000Z
sources/thelib/src/mediaformats/readers/mp4/atomhdlr.cpp
rdkcmf/rdkc-rms
65ab1efcee9e3de46a888c125f591cd48b815601
[ "Apache-2.0" ]
null
null
null
sources/thelib/src/mediaformats/readers/mp4/atomhdlr.cpp
rdkcmf/rdkc-rms
65ab1efcee9e3de46a888c125f591cd48b815601
[ "Apache-2.0" ]
2
2020-05-11T03:19:00.000Z
2021-07-07T17:40:47.000Z
/** ########################################################################## # If not stated otherwise in this file or this component's LICENSE # file the following copyright and licenses apply: # # Copyright 2019 RDK Management # # 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. ########################################################################## **/ #ifdef HAS_MEDIA_MP4 #include "mediaformats/readers/mp4/atomhdlr.h" AtomHDLR::AtomHDLR(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start) : VersionedAtom(pDocument, type, size, start) { _componentType = 0; _componentSubType = 0; _componentManufacturer = 0; _componentFlags = 0; _componentFlagsMask = 0; _componentName = ""; } AtomHDLR::~AtomHDLR() { } uint32_t AtomHDLR::GetComponentSubType() { return _componentSubType; } bool AtomHDLR::ReadData() { if (!ReadUInt32(_componentType)) { FATAL("Unable to read component type"); return false; } if (!ReadUInt32(_componentSubType)) { FATAL("Unable to read component sub type"); return false; } if (!ReadUInt32(_componentManufacturer)) { FATAL("Unable to read component manufacturer"); return false; } if (!ReadUInt32(_componentFlags)) { FATAL("Unable to read component flags"); return false; } if (!ReadUInt32(_componentFlagsMask)) { FATAL("Unable to read component flags mask"); return false; } if (!ReadString(_componentName, _size - 32)) { FATAL("Unable to read component name"); return false; } return true; } string AtomHDLR::Hierarchy(uint32_t indent) { return string(4 * indent, ' ') + GetTypeString() + "(" + U32TOS(_componentSubType) + ")"; } #endif /* HAS_MEDIA_MP4 */
25.975904
90
0.678571
rdkcmf
53dbd15883fca8e4fb9012fbe7b16ae78429f8df
1,255
cpp
C++
ansi-c/fix_symbol.cpp
holao09/esbmc
659c006a45e9aaf8539b12484e2ec2b093cc6f02
[ "BSD-3-Clause" ]
null
null
null
ansi-c/fix_symbol.cpp
holao09/esbmc
659c006a45e9aaf8539b12484e2ec2b093cc6f02
[ "BSD-3-Clause" ]
null
null
null
ansi-c/fix_symbol.cpp
holao09/esbmc
659c006a45e9aaf8539b12484e2ec2b093cc6f02
[ "BSD-3-Clause" ]
null
null
null
/*******************************************************************\ Module: ANSI-C Linking Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ #include "fix_symbol.h" /*******************************************************************\ Function: fix_symbolt::fix_symbol Inputs: Outputs: Purpose: \*******************************************************************/ void fix_symbolt::fix_symbol(symbolt &symbol) { type_mapt::const_iterator it= type_map.find(symbol.name); if(it!=type_map.end()) symbol.name=it->second.id(); replace(symbol.type); replace(symbol.value); } /*******************************************************************\ Function: fix_symbolt::fix_context Inputs: Outputs: Purpose: \*******************************************************************/ void fix_symbolt::fix_context(contextt &context) { for(type_mapt::const_iterator t_it=type_map.begin(); t_it!=type_map.end(); t_it++) { symbolt* symb = context.find_symbol(t_it->first); assert(symb != nullptr); symbolt s = *symb; s.name = t_it->second.identifier(); context.erase_symbol(t_it->first); context.move(s); } }
19.920635
69
0.449402
holao09
53de116229cda7fec51a86c23c78b472d07a9197
1,214
cc
C++
src/leaderboard.cc
CS126SP20/final-project-teresa622
38b1e943383fe9e71cfffb42460f855444754820
[ "MIT" ]
null
null
null
src/leaderboard.cc
CS126SP20/final-project-teresa622
38b1e943383fe9e71cfffb42460f855444754820
[ "MIT" ]
null
null
null
src/leaderboard.cc
CS126SP20/final-project-teresa622
38b1e943383fe9e71cfffb42460f855444754820
[ "MIT" ]
null
null
null
// // Created by Teresa Dong on 4/17/20. // #include <string> #include "mylibrary/leaderboard.h" #include "mylibrary/player.h" namespace tetris { LeaderBoard::LeaderBoard(const std::string& db_path) : db_{db_path} { db_ << "CREATE TABLE if not exists leaderboard (\n" " name TEXT NOT NULL,\n" " score INTEGER NOT NULL\n" ");"; } void LeaderBoard::AddScoreToLeaderBoard(const Player& player) { db_ << u"insert into leaderboard (name,score) values (?,?);" << player.name << player.score; } std::vector<Player> GetPlayers(sqlite::database_binder* rows) { std::vector<Player> players; for (auto&& row : *rows) { std::string name; size_t score; row >> name >> score; Player player = {name, score}; players.push_back(player); } return players; } std::vector<Player> LeaderBoard::RetrieveHighScores(const size_t limit) { try { auto rows = db_<< "SELECT name,score FROM " "leaderboard ORDER BY score DESC LIMIT (?);" << limit; return GetPlayers(&rows); } catch (const std::exception& e) { std::cerr << "Query error at retrieve universal high scores"; } } } //namespace tetris
23.346154
73
0.623558
CS126SP20
53de483523e0636452f358b5f0779fb78869303d
628
cpp
C++
LuoguOJ/Luogu 2661.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
1
2018-02-11T09:41:54.000Z
2018-02-11T09:41:54.000Z
LuoguOJ/Luogu 2661.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
LuoguOJ/Luogu 2661.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define _ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); using namespace std; const int MAXN=2e6+10; int disjoint[MAXN],dis[MAXN]={0},ans=2e6+10; int getjoint(int s){ if(disjoint[s]!=s){ int last=disjoint[s]; disjoint[s]=getjoint(disjoint[s]); dis[s]+=dis[last]; } return disjoint[s]; } void link(int s,int t){ int x=getjoint(s),y=getjoint(t); if(x!=y){ disjoint[x]=y; dis[s]=dis[t]+1; } else ans=min(ans,dis[s]+dis[t]+1); } int main(){ int N; cin>>N; for(int i=1;i<=N;i++) disjoint[i]=i; for(int i=1;i<=N;i++){ int k; cin>>k; link(i,k); } cout<<ans<<'\n'; return 0; }
17.942857
57
0.600318
tico88612
53debfd17bffc22006b3728f7979ccc1a195d383
2,701
cpp
C++
graph-source-code/118-E/745508.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/118-E/745508.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/118-E/745508.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++ #include <map> #include <set> #include <list> #include <stack> #include <cmath> #include <queue> #include <ctime> #include <cfloat> #include <vector> #include <string> #include <cstdio> #include <climits> #include <cstdlib> #include <cstring> #include <cassert> #include <iomanip> #include <sstream> #include <utility> #include <iostream> #include <algorithm> #define INF 0x3F3F3F3F #define LINF 0x3F3F3F3FFFFFFFFFLL #define FILL(X, V) memset( X, V, sizeof(X) ) #define TI(X) __typeof((X).begin()) #define ALL(V) V.begin(), V.end() #define SIZE(V) int((V).size()) #define FOR(i, a, b) for(int i = a; i <= b; ++i) #define RFOR(i, b, a) for(int i = b; i >= a; --i) #define REP(i, N) for(int i = 0; i < N; ++i) #define RREP(i, N) for(int i = N-1; i >= 0; --i) #define FORIT(i, a) for( TI(a) i = a.begin(); i != a.end(); i++ ) #define PB push_back #define MP make_pair template<typename T> T inline SQR( const T &a ){ return a*a; } template<typename T> T inline ABS( const T &a ){ return a < 0 ? -a : a; } template<typename T> T inline MIN( const T& a, const T& b){ if( a < b ) return a; return b; } template<typename T> T inline MAX( const T& a, const T& b){ if( a > b ) return a; return b; } const double EPS = 1e-9; inline int SGN( double a ){ return ((a > EPS) ? (1) : ((a < -EPS) ? (-1) : (0))); } inline int CMP( double a, double b ){ return SGN(a - b); } typedef long long int64; typedef unsigned long long uint64; using namespace std; #define MAXN 100000 vector< vector<int> > gr; int parent[MAXN], low[MAXN], lbl[MAXN]; int dfsnum, bridges; void dfs( int u ){ lbl[u] = low[u] = dfsnum++; for( size_t i = 0, sz = gr[u].size(); i < sz; i++ ){ int v = gr[u][i]; if( lbl[v] == -1 ){ parent[v] = u; dfs( v ); if( low[u] > low[v] ) low[u] = low[v]; if( low[v] == lbl[v] ) bridges++; } else if( v != parent[u] ) low[u] = min( low[u], lbl[v] ); } } set< pair<int,int> > seen; void show( int u ){ lbl[u] = 0; for( size_t i = 0, sz = gr[u].size(); i < sz; i++ ){ int v = gr[u][i]; if( lbl[v] == -1 ){ cout << u+1 << " " << v+1 << "\n"; seen.insert( MP(min(u,v), max(u,v)) ); show( v ); } else if( seen.insert( MP(min(u,v),max(u,v))).second ) cout << u+1 << " " << v+1 << "\n"; } } int main( int argc, char* argv[] ){ ios::sync_with_stdio( false ); int n, m, u, v; cin >> n >> m; gr.resize(n); REP( i, n ){ gr[i].clear(); lbl[i] = low[i] = -1; parent[i] = -1; } REP( i, m ){ cin >> u >> v; u--, v--; gr[u].PB( v ); gr[v].PB( u ); } dfsnum = 0, bridges = 0; dfs( 0 ); if( bridges ) cout << "0" << "\n"; else{ REP( i, n ) lbl[i] = -1; show( 0 ); } return 0; }
20.007407
93
0.546835
AmrARaouf
53e19c7e9a43f973ed26aea01b09b554f826fbff
2,162
hpp
C++
src/camera.hpp
mvorbrodt/engine
0b9c5c1f6d293e98ea8bea3db3bfb67fee84b73c
[ "0BSD" ]
3
2019-04-25T11:39:13.000Z
2022-01-30T22:24:08.000Z
src/camera.hpp
mvorbrodt/engine
0b9c5c1f6d293e98ea8bea3db3bfb67fee84b73c
[ "0BSD" ]
null
null
null
src/camera.hpp
mvorbrodt/engine
0b9c5c1f6d293e98ea8bea3db3bfb67fee84b73c
[ "0BSD" ]
1
2019-11-20T07:58:38.000Z
2019-11-20T07:58:38.000Z
#pragma once #include <cassert> #include "types.hpp" #include "vector.hpp" #include "point.hpp" #include "matrix.hpp" #include "transforms.hpp" #define MIN_FOV 10.0f #define MAX_FOV 90.0f namespace engine { class camera { public: camera(real aspect, real fov = 60.0f, real _near = 1.0f, real _far = 100.0f, const point& origin = ORIGIN, const vector& direction = -UNIT_Z, const vector& up = UNIT_Y) : m_aspect{ aspect }, m_fov{ fov }, m_near{ _near }, m_far{ _far }, m_origin{ origin }, m_direction{ direction }, m_up{ up } { assert(aspect != 0.0f && aspect > 0.0f); assert(m_fov >= MIN_FOV && m_fov <= MAX_FOV); assert(m_near >= 1.0f && m_far >= 1.0f && m_near < m_far); m_direction.normalize(); m_up.normalize(); } real get_aspect() const { return m_aspect; } void set_aspect(real aspect) { m_aspect = aspect; } real get_fov() const { return m_fov; } void set_fov(real fov) { if(fov < MIN_FOV) fov = MIN_FOV; if(fov > MAX_FOV) fov = MAX_FOV; m_fov = fov; } real get_near() const { return m_near; } void set_near(real _near) { if(_near < 1.0f) _near = 1.0f; if(_near > m_far) _near = m_far - 1.0f; m_near = _near; } real get_far() const { return m_far; } void set_far(real _far) { if(_far < 1.0f) _far = 1.0f; if(_far < m_near) _far = m_near + 1.0f; m_far = _far; } void move(real forward, real side) { auto v = (m_up ^ m_direction).normal(); m_origin += forward * m_direction + side * v; } void turn(real angle) { auto m = engine::rotate(angle, m_up); m_direction *= m; } void look(real angle) { auto side = (m_up ^ m_direction).normal(); auto m = engine::rotate(angle, side); m_direction *= m; } void roll(real angle) { auto m = engine::rotate(angle, m_direction); m_up *= m; } matrix view_matrix() const { auto at = m_origin + m_direction; return look_at(m_origin, at, m_up); } matrix projection_matrix() { return projection(m_fov, m_aspect, m_near, m_far); } private: real m_aspect; real m_fov; real m_near; real m_far; point m_origin; vector m_direction; vector m_up; }; }
21.405941
170
0.630897
mvorbrodt
53e8532ad79bf9a0704c56fe0263f884d7dc31cc
446
cpp
C++
643-maximum-average-subarray-i/643-maximum-average-subarray-i.cpp
SouvikChan/-Leetcode_Souvik
cc4b72cb4a14a1c6b8be8bd8390de047443fe008
[ "MIT" ]
null
null
null
643-maximum-average-subarray-i/643-maximum-average-subarray-i.cpp
SouvikChan/-Leetcode_Souvik
cc4b72cb4a14a1c6b8be8bd8390de047443fe008
[ "MIT" ]
null
null
null
643-maximum-average-subarray-i/643-maximum-average-subarray-i.cpp
SouvikChan/-Leetcode_Souvik
cc4b72cb4a14a1c6b8be8bd8390de047443fe008
[ "MIT" ]
null
null
null
class Solution { public: double findMaxAverage(vector<int>& nums, int k) { int sum=0; for(int i=0;i<k;i++){ sum+=nums[i]; } double avg=(double)sum/k; int i=0, j=k; while(j<nums.size()){ sum -= nums[i]; sum += nums[j]; double a = (double)sum/k; avg = max(avg,a); i++; j++; } return avg; } };
22.3
53
0.394619
SouvikChan
53f20407d36b640aa7b0d498a7d180d06e7ac743
1,477
cpp
C++
linked-list/merge-sort-doublyLL.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
linked-list/merge-sort-doublyLL.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
linked-list/merge-sort-doublyLL.cpp
Strider-7/code
e096c0d0633b53a07bf3f295cb3bd685b694d4ce
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node *next, *prev; }; Node *merge(Node *a, Node *b) { // Base cases if (!a) return b; if (!b) return a; if (a->data <= b->data) { a->next = merge(a->next, b); a->next->prev = a; a->prev = NULL; return a; } else { b->next = merge(a, b->next); b->next->prev = b; b->prev = NULL; return b; } } pair<Node *, Node *> FrontBackSplit(Node *source) { Node *frontRef = nullptr, *backRef = nullptr; if (source == nullptr || source->next == nullptr) { frontRef = source; backRef = nullptr; return make_pair(frontRef, backRef); } struct Node *slow = source; struct Node *fast = source->next; while (fast != NULL) { fast = fast->next; if (fast != NULL) { slow = slow->next; fast = fast->next; } } frontRef = source; backRef = slow->next; slow->next = NULL; return make_pair(frontRef, backRef); } struct Node *sortDoubly(struct Node *head) { if (!head || !head->next) return head; pair<Node *, Node *> P = FrontBackSplit(head); Node *p = P.first, *q = P.second; p = sortDoubly(p); q = sortDoubly(q); head = merge(p, q); return head; }
19.181818
54
0.475288
Strider-7
53f50c53640f4dc2d832d2b71c9dd5101573236f
168
cpp
C++
vm/mterp/c/OP_DISPATCH_FF.cpp
ThirdProject/android_dalvik
6a9739380c73a0256f2484f2bcd0b8f908a2db52
[ "Apache-2.0" ]
null
null
null
vm/mterp/c/OP_DISPATCH_FF.cpp
ThirdProject/android_dalvik
6a9739380c73a0256f2484f2bcd0b8f908a2db52
[ "Apache-2.0" ]
null
null
null
vm/mterp/c/OP_DISPATCH_FF.cpp
ThirdProject/android_dalvik
6a9739380c73a0256f2484f2bcd0b8f908a2db52
[ "Apache-2.0" ]
null
null
null
HANDLE_OPCODE(OP_DISPATCH_FF) /* * Indicates extended opcode. Use next 8 bits to choose where to branch. */ DISPATCH_EXTENDED(INST_AA(inst)); OP_END
24
77
0.696429
ThirdProject
53fa031c22b8eed150594efa271ddde6a8d2a68e
9,895
cpp
C++
src/c++/lib/alignment/matchSelector/BinningFragmentStorage.cpp
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
13
2018-02-09T22:59:39.000Z
2021-11-29T06:33:22.000Z
src/c++/lib/alignment/matchSelector/BinningFragmentStorage.cpp
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
17
2018-01-26T11:36:07.000Z
2022-02-03T18:48:43.000Z
src/c++/lib/alignment/matchSelector/BinningFragmentStorage.cpp
Illumina/Isaac4
0924fba8b467868da92e1c48323b15d7cbca17dd
[ "BSD-3-Clause" ]
4
2018-10-19T20:00:00.000Z
2020-10-29T14:44:06.000Z
/** ** Isaac Genome Alignment Software ** Copyright (c) 2010-2017 Illumina, Inc. ** All rights reserved. ** ** This software is provided under the terms and conditions of the ** GNU GENERAL PUBLIC LICENSE Version 3 ** ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3 ** along with this program. If not, see ** <https://github.com/illumina/licenses/>. ** ** \file BinningFragmentStorage.cpp ** ** \author Roman Petrovski **/ #include <cerrno> #include <fstream> #include "common/Debug.hh" #include "common/Exceptions.hh" #include "alignment/BinMetadata.hh" #include "alignment/matchSelector/BinningFragmentStorage.hh" namespace isaac { namespace alignment { namespace matchSelector { /** * \brief creates bin data files at regular genomic intervals. * * \param contigsPerBinMax maximum number of different contigs to be associated with the * same data file path */ static boost::filesystem::path makeDataFilePath( std::size_t genomicOffset, const uint64_t targetBinLength, unsigned binIndex, const reference::ReferencePosition& binStartPos, const unsigned contigsPerBinMax, const reference::SortedReferenceMetadata::Contigs& contigs, const bfs::path& binDirectory, unsigned &lastBinLastContig, uint64_t& lastBinRoundedGenomicOffset, unsigned & lastBinContigs, uint64_t& lastFileNameGenomicOffset) { reference::ReferencePosition fileNameReferencePosition; uint64_t roundedGenomicOffset = (genomicOffset / targetBinLength) * targetBinLength; uint64_t fileNameGenomicOffset = roundedGenomicOffset; if (binIndex && lastBinRoundedGenomicOffset == roundedGenomicOffset) { if (lastBinLastContig != binStartPos.getContigId()) { ++lastBinContigs; } if (contigsPerBinMax < lastBinContigs) { fileNameGenomicOffset = genomicOffset; lastFileNameGenomicOffset = genomicOffset; lastBinContigs = 0; } else { fileNameGenomicOffset = lastFileNameGenomicOffset; } } else { lastBinRoundedGenomicOffset = roundedGenomicOffset; lastFileNameGenomicOffset = fileNameGenomicOffset; lastBinContigs = 0; } lastBinLastContig = binIndex ? binStartPos.getContigId() : 0; fileNameReferencePosition = reference::genomicOffsetToPosition(fileNameGenomicOffset, contigs); // ISAAC_THREAD_CERR << "roundedGenomicOffset:" << roundedGenomicOffset << std::endl; // ISAAC_THREAD_CERR << "fileNameReferencePosition:" << fileNameReferencePosition << std::endl; boost::filesystem::path binPath = // Pad file names well, so that we don't have to worry about them becoming of different length. // This is important for memory reservation to be stable binDirectory / (boost::format("bin-%08d-%09d.dat") % (binIndex ? (fileNameReferencePosition.getContigId() + 1) : 0) % (binIndex ? fileNameReferencePosition.getPosition() : 0)).str(); return binPath; } static void buildBinPathList( const alignment::matchSelector::BinIndexMap &binIndexMap, const bfs::path &binDirectory, const flowcell::BarcodeMetadataList &barcodeMetadataList, const reference::SortedReferenceMetadata::Contigs &contigs, const uint64_t targetBinLength, alignment::BinMetadataList &ret) { ISAAC_TRACE_STAT("before buildBinPathList"); ISAAC_ASSERT_MSG(!binIndexMap.empty(), "Empty binIndexMap is illegal"); ISAAC_ASSERT_MSG(!binIndexMap.back().empty(), "Empty binIndexMap entry is illegal" << binIndexMap); reference::SortedReferenceMetadata::Contigs offsetOderedContigs = contigs; std::sort(offsetOderedContigs.begin(), offsetOderedContigs.end(), [](const reference::SortedReferenceMetadata::Contig &left, const reference::SortedReferenceMetadata::Contig &right) {return left.genomicPosition_ < right.genomicPosition_;}); std::size_t genomicOffset = 0; static const unsigned CONTIGS_PER_BIN_MAX = 16; unsigned lastBinContigs = 0; unsigned lastBinLastContig = -1; uint64_t lastBinRoundedGenomicOffset = uint64_t(0) - 1; uint64_t lastFileNameGenomicOffset = uint64_t(0) - 1; BOOST_FOREACH(const std::vector<unsigned> &contigBins, binIndexMap) { ISAAC_ASSERT_MSG(!contigBins.empty(), "Unexpected empty contigBins"); // this offset goes in bin length increments. They don't sum up to the real contig length std::size_t binGenomicOffset = genomicOffset; for (unsigned i = contigBins.front(); contigBins.back() >= i; ++i) { const reference::ReferencePosition binStartPos = binIndexMap.getBinFirstPos(i); // binIndexMap contig 0 is unaligned bin ISAAC_ASSERT_MSG(!i || binIndexMap.getBinIndex(binStartPos) == i, "BinIndexMap is broken"); const boost::filesystem::path binPath = makeDataFilePath( binGenomicOffset, targetBinLength, i, binStartPos, CONTIGS_PER_BIN_MAX, offsetOderedContigs, binDirectory, lastBinLastContig, lastBinRoundedGenomicOffset, lastBinContigs, lastFileNameGenomicOffset); const uint64_t binLength = i ? binIndexMap.getBinFirstInvalidPos(i) - binStartPos : 0; ret.push_back( alignment::BinMetadata(barcodeMetadataList.size(), ret.size(), binStartPos, binLength, binPath)); // ISAAC_THREAD_CERR << "binPathList.back():" << binPathList.back() << std::endl; binGenomicOffset += binLength; } // ISAAC_THREAD_CERR << "contigBins.front():" << contigBins.front() << std::endl; if (!ret.back().isUnalignedBin()) { genomicOffset += contigs.at(ret.back().getBinStart().getContigId()).totalBases_; } } } BinningFragmentStorage::BinningFragmentStorage( const boost::filesystem::path &tempDirectory, const bool keepUnaligned, const BinIndexMap &binIndexMap, const reference::SortedReferenceMetadata::Contigs& contigs, const flowcell::BarcodeMetadataList &barcodeMetadataList, const bool preAllocateBins, const uint64_t expectedBinSize, const uint64_t targetBinLength, const unsigned threads, alignment::BinMetadataList &binMetadataList): FragmentBinner(keepUnaligned, binIndexMap, preAllocateBins ? expectedBinSize : 0, threads), binIndexMap_(binIndexMap), expectedBinSize_(expectedBinSize), binMetadataList_(binMetadataList) { buildBinPathList( binIndexMap, tempDirectory, barcodeMetadataList, contigs, targetBinLength, binMetadataList_); const std::size_t worstCaseEstimatedUnalignedBins = // This assumes that none of the data will align and we will need to // make as many unaligned bins as we expect the aligned ones to be there // This is both bad and weak. Bad because we allocate pile of memory // that will never be used with proper aligning data. // Weak because if in fact nothing will align, we might need more unaligned bins than we expect. // Keeping this here because we're talking about a few thousands relatively small structures, // so pile is not large enough to worry about, and the reallocation will occur while no other threads // are using the list, so it should not invalidate any references. binMetadataList_.size() * binIndexMap.getBinLength() / targetBinLength + // in case the above math returns 0, we'll have room for at least one unaligned bin 1; binMetadataList_.reserve(binMetadataList_.size() + worstCaseEstimatedUnalignedBins); unalignedBinMetadataReserve_.resize(worstCaseEstimatedUnalignedBins, binMetadataList_.back()); FragmentBinner::open(binMetadataList_.begin(), binMetadataList_.end()); } BinningFragmentStorage::~BinningFragmentStorage() { } void BinningFragmentStorage::store( const BamTemplate &bamTemplate, const unsigned barcodeIdx, const unsigned threadNumber) { common::StaticVector<char, READS_MAX * (sizeof(io::FragmentHeader) + FRAGMENT_BYTES_MAX)> buffer; if (2 == bamTemplate.getFragmentCount()) { packPairedFragment(bamTemplate, 0, barcodeIdx, binIndexMap_, std::back_inserter(buffer)); const io::FragmentAccessor &fragment0 = reinterpret_cast<const io::FragmentAccessor&>(buffer.front()); packPairedFragment(bamTemplate, 1, barcodeIdx, binIndexMap_, std::back_inserter(buffer)); const io::FragmentAccessor &fragment1 = *reinterpret_cast<const io::FragmentAccessor*>(&buffer.front() + fragment0.getTotalLength()); storePaired(fragment0, fragment1, binMetadataList_, threadNumber); } else { packSingleFragment(bamTemplate, barcodeIdx, std::back_inserter(buffer)); const io::FragmentAccessor &fragment = reinterpret_cast<const io::FragmentAccessor&>(buffer.front()); storeSingle(fragment, binMetadataList_, threadNumber); } } void BinningFragmentStorage::prepareFlush() noexcept { if (binMetadataList_.front().getDataSize() > expectedBinSize_) { ISAAC_ASSERT_MSG(!unalignedBinMetadataReserve_.empty(), "Unexpectedly ran out of reserved BinMetadata when extending the unaligned bin"); // does not cause memory allocation because of reserve in constructor binMetadataList_.resize(binMetadataList_.size() + 1); using std::swap; swap(binMetadataList_.back(), unalignedBinMetadataReserve_.back()); unalignedBinMetadataReserve_.pop_back(); binMetadataList_.back() = binMetadataList_.front(); binMetadataList_.front().startNew(); } } } //namespace matchSelector } // namespace alignment } // namespace isaac
41.57563
145
0.703183
Illumina
53fb4768f41b00844adfb9ec51edd9b7f4b37bdf
3,036
hpp
C++
src/OpenAnalysis/CallGraph/ManagerCallGraph.hpp
sriharikrishna/OpenAnalysis
0d0c3819bd091cc0c83db5555cc20bfbc07ecbdc
[ "BSD-3-Clause" ]
null
null
null
src/OpenAnalysis/CallGraph/ManagerCallGraph.hpp
sriharikrishna/OpenAnalysis
0d0c3819bd091cc0c83db5555cc20bfbc07ecbdc
[ "BSD-3-Clause" ]
null
null
null
src/OpenAnalysis/CallGraph/ManagerCallGraph.hpp
sriharikrishna/OpenAnalysis
0d0c3819bd091cc0c83db5555cc20bfbc07ecbdc
[ "BSD-3-Clause" ]
null
null
null
/*! \file \brief Declarations of the AnnotationManager that generates a CallGraphStandard. \authors Arun Chauhan (2001 as part of Mint), Nathan Tallent, Michelle Strout, Priyadarshini Malusare \version $Id: ManagerCallGraphStandard.hpp,v 1.6 2004/11/19 19:21:50 mstrout Exp $ Copyright (c) 2002-2005, Rice University <br> Copyright (c) 2004-2005, University of Chicago <br> Copyright (c) 2006, Contributors <br> All rights reserved. <br> See ../../../Copyright.txt for details. <br> */ /*! #ifndef CallGraphMANAGERSTANDARD_H #define CallGraphMANAGERSTANDARD_H */ #ifndef ManagerCallGraph_H #define ManagerCallGraph_H //-------------------------------------------------------------------- // standard headers #ifdef NO_STD_CHEADERS # include <string.h> #else # include <cstring> #endif // STL headers #include <list> #include <set> #include <map> // OpenAnalysis headers #include <OpenAnalysis/Utils/OA_ptr.hpp> #include <OpenAnalysis/Utils/Util.hpp> #include <OpenAnalysis/Location/Locations.hpp> #include <OpenAnalysis/CallGraph/CallGraph.hpp> #include <OpenAnalysis/Alias/InterAliasInterface.hpp> #include <OpenAnalysis/IRInterface/CallGraphIRInterface.hpp> namespace OA { namespace CallGraph { //-------------------------------------------------------------------- /*! The AnnotationManager for a CallGraphStandard Annotation. Knows how to build a CallGraphStandard, read one in from a file, and write one out to a file. */ class ManagerCallGraphStandard { //??? eventually public OA::AnnotationManager public: ManagerCallGraphStandard(OA_ptr<CallGraphIRInterface> _ir); virtual ~ManagerCallGraphStandard () {} //??? don't think this guy need AQM, but will eventually have //to have one so is standard with other AnnotationManagers //what type of handle are we going to attach the CallGraph to? virtual OA_ptr<CallGraph> performAnalysis(OA_ptr<IRProcIterator> procIter, OA_ptr<Alias::InterAliasInterface> interAlias ); //------------------------------------- // information access //------------------------------------- OA_ptr<CallGraphIRInterface> getIRInterface() { return mIR; } //------------------------------------------------------------------ // Exceptions //------------------------------------------------------------------ /*! COMMENTED OUT BY plm 08/18/06 class CallGraphException : public Exception { public: void report (std::ostream& os) const { os << "E! Unexpected." << std::endl; } }; */ private: //------------------------------------------------------------------ // Methods that build CallGraphStandard //------------------------------------------------------------------ void build_graph(OA_ptr<IRProcIterator> funcIter); private: OA_ptr<CallGraphIRInterface> mIR; OA_ptr<CallGraph> mCallGraph; OA_ptr<Alias::InterAliasInterface> mInterAlias; }; //-------------------------------------------------------------------- } // end of CallGraph namespace } // end of OA namespace #endif
30.979592
103
0.600132
sriharikrishna
53fc218fdcd65dc427360ddb202a4d1c73c959e3
3,611
cpp
C++
geometry/src/capsule.cpp
Ludophonic/JigLib
541ec63b345ccf01e58cce49eb2f73c21eaf6aa6
[ "Zlib" ]
10
2016-06-01T12:54:45.000Z
2021-09-07T17:34:37.000Z
geometry/src/capsule.cpp
Ludophonic/JigLib
541ec63b345ccf01e58cce49eb2f73c21eaf6aa6
[ "Zlib" ]
null
null
null
geometry/src/capsule.cpp
Ludophonic/JigLib
541ec63b345ccf01e58cce49eb2f73c21eaf6aa6
[ "Zlib" ]
4
2017-05-03T14:03:03.000Z
2021-01-04T04:31:15.000Z
//============================================================== // Copyright (C) 2004 Danny Chapman // danny@rowlhouse.freeserve.co.uk //-------------------------------------------------------------- // /// @file capsule.cpp // //============================================================== #include "capsule.hpp" #include "intersection.hpp" using namespace JigLib; //============================================================== // Clone //============================================================== tPrimitive* tCapsule::Clone() const { return new tCapsule(*this); } //============================================================== // SegmentIntersect //============================================================== bool tCapsule::SegmentIntersect(tScalar &frac, tVector3 &pos, tVector3 &normal, const class tSegment &seg) const { bool result; if (result = SegmentCapsuleIntersection(&frac, seg, *this)) { pos = seg.GetPoint(frac); normal = pos - mTransform.position; normal -= Dot(normal, mTransform.orientation.GetLook()) * mTransform.orientation.GetLook(); normal.NormaliseSafe(); } return result; } //============================================================== // GetMassProperties //============================================================== void tCapsule::GetMassProperties(const tPrimitiveProperties &primitiveProperties, tScalar &mass, tVector3 &centerOfMass, tMatrix33 &inertiaTensor) const { if (primitiveProperties.mMassType == tPrimitiveProperties::MASS) { mass = primitiveProperties.mMassOrDensity; } else { if (primitiveProperties.mMassDistribution == tPrimitiveProperties::SOLID) mass = GetVolume() * primitiveProperties.mMassOrDensity; else mass = GetSurfaceArea() * primitiveProperties.mMassOrDensity; } centerOfMass = GetPos() + 0.5f * GetLength() * GetOrient().GetLook(); /// todo check solid/shell // first cylinder tScalar cylinderMass = mass * PI * Sq(mRadius) * mLength / GetVolume(); tScalar Ixx = 0.5f * cylinderMass * Sq(mRadius); tScalar Iyy = 0.25f * cylinderMass * Sq(mRadius) + (1.0f / 12.0f) * cylinderMass * Sq(mLength); tScalar Izz = Iyy; // add ends tScalar endMass = mass - cylinderMass; Ixx += 0.2f * endMass * Sq(mRadius); Iyy += 0.4f * endMass * Sq(mRadius) + endMass * Sq(0.5f * mLength); Izz += 0.4f * endMass * Sq(mRadius) + endMass * Sq(0.5f * mLength); inertiaTensor.Set(Ixx, 0.0f, 0.0f, 0.0f, Iyy, 0.0f, 0.0f, 0.0f, Izz); // transform - e.g. see p664 of Physics-Based Animation // todo is the order correct here? Does it matter? // Calculate the tensor in a frame at the CoM, but aligned with the world axes inertiaTensor = mTransform.orientation * inertiaTensor * mTransform.orientation.GetTranspose(); // Transfer of axe theorem inertiaTensor(0, 0) = inertiaTensor(0, 0) + mass * (Sq(centerOfMass.y) + Sq(centerOfMass.z)); inertiaTensor(1, 1) = inertiaTensor(1, 1) + mass * (Sq(centerOfMass.z) + Sq(centerOfMass.x)); inertiaTensor(2, 2) = inertiaTensor(2, 2) + mass * (Sq(centerOfMass.x) + Sq(centerOfMass.y)); inertiaTensor(0, 1) = inertiaTensor(1, 0) = inertiaTensor(0, 1) - mass * centerOfMass.x * centerOfMass.y; inertiaTensor(1, 2) = inertiaTensor(2, 1) = inertiaTensor(1, 2) - mass * centerOfMass.y * centerOfMass.z; inertiaTensor(2, 0) = inertiaTensor(0, 2) = inertiaTensor(2, 0) - mass * centerOfMass.z * centerOfMass.x; }
39.681319
112
0.546109
Ludophonic
53fdbadfaa6215e4b01d0233392fe1f15fd914eb
244
cpp
C++
lib/cards/expansion_card.cpp
BioBoost/home_automator
acc77023003110bc18f376c5305dd26912b26a9a
[ "MIT" ]
null
null
null
lib/cards/expansion_card.cpp
BioBoost/home_automator
acc77023003110bc18f376c5305dd26912b26a9a
[ "MIT" ]
14
2018-08-19T09:03:06.000Z
2018-09-22T21:08:36.000Z
lib/cards/expansion_card.cpp
BioBoost/home_automator
acc77023003110bc18f376c5305dd26912b26a9a
[ "MIT" ]
null
null
null
#include "expansion_card.h" namespace BiosHomeAutomator { ExpansionCard::ExpansionCard(unsigned int id) { this->id = id; } ExpansionCard::~ExpansionCard(void) { } unsigned int ExpansionCard::get_id(void) { return id; } };
16.266667
49
0.684426
BioBoost
d87cc8d47fa687a1a4fa586a5d626144557df6fb
850
hpp
C++
poet/detail/utility.hpp
fmhess/libpoet
ca6a168a772a1452ac39745a851ba390e86fad30
[ "BSL-1.0" ]
1
2017-04-03T11:53:20.000Z
2017-04-03T11:53:20.000Z
poet/detail/utility.hpp
fmhess/libpoet
ca6a168a772a1452ac39745a851ba390e86fad30
[ "BSL-1.0" ]
null
null
null
poet/detail/utility.hpp
fmhess/libpoet
ca6a168a772a1452ac39745a851ba390e86fad30
[ "BSL-1.0" ]
null
null
null
// copyright (c) Frank Mori Hess <fmhess@users.sourceforge.net> 2008-04-13 // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef _POET_DETAIL_UTILITY_HPP #define _POET_DETAIL_UTILITY_HPP #include <boost/weak_ptr.hpp> namespace poet { namespace detail { // deadlock-free locking of a pair of locks with arbitrary locking order template<typename LockT, typename LockU> void lock_pair(LockT &a, LockU &b) { while(true) { a.lock(); if(b.try_lock()) return; a.unlock(); b.lock(); if(a.try_lock()) return; b.unlock(); } } template<typename T> boost::weak_ptr<T> make_weak(const boost::shared_ptr<T> &sp) { return boost::weak_ptr<T>(sp); } } } #endif // _POET_DETAIL_UTILITY_HPP
21.25
75
0.685882
fmhess
d886b626bba54bf7c1acdaf6800e7e362c9ca320
1,378
hpp
C++
GLSL-Pipeline/Toolkits/include/System/Func.hpp
GilFerraz/GLSL-Pipeline
d2fd965a4324e85b6144682f8104c306034057d6
[ "Apache-2.0" ]
null
null
null
GLSL-Pipeline/Toolkits/include/System/Func.hpp
GilFerraz/GLSL-Pipeline
d2fd965a4324e85b6144682f8104c306034057d6
[ "Apache-2.0" ]
null
null
null
GLSL-Pipeline/Toolkits/include/System/Func.hpp
GilFerraz/GLSL-Pipeline
d2fd965a4324e85b6144682f8104c306034057d6
[ "Apache-2.0" ]
null
null
null
#pragma once #include "DLL.hpp" #include <functional> namespace System { /** * \brief Encapsulates a method that has specified parameters and returns a value of the type specified by the TResult * parameter. Unlike in other .NET languages, the first paramenter correspondes to TResult. * \tparam TResult The type of the return value of the method that this delegate encapsulates. * \tparam Args The parameters of the method that this delegate encapsulates. */ template<typename TResult, typename ...Args> class DLLExport Func final { public: typedef std::function<TResult(Args...)> FuncType; Func(FuncType func); ~Func(); #pragma region Public Instance Methods TResult Invoke(Args&&... args); #pragma endregion private: FuncType func; }; template <typename TResult, typename ... Args> Func<TResult, Args...>::Func(FuncType func) { this->func = func; } template <typename TResult, typename ... Args> Func<TResult, Args...>::~Func() { } #pragma region Public Instance Methods template <typename TResult, typename ... Args> TResult Func<TResult, Args...>::Invoke(Args&&... args) { if (&func != nullptr) { return func(args...); } return nullptr; } #pragma endregion }
23.758621
122
0.624819
GilFerraz
d88756cddfe30e47e7f80e2cfebaaa7174008521
493
cc
C++
endo/module_wrap.cc
Qard/endo
6e3241b12e58344524711d4db4ed44d115fa8175
[ "MIT" ]
null
null
null
endo/module_wrap.cc
Qard/endo
6e3241b12e58344524711d4db4ed44d115fa8175
[ "MIT" ]
null
null
null
endo/module_wrap.cc
Qard/endo
6e3241b12e58344524711d4db4ed44d115fa8175
[ "MIT" ]
null
null
null
#include "module_wrap.h" namespace endo { ModuleWrap::ModuleWrap(Isolate* isolate, Local<Module> module, Local<String> url) : module_(isolate, module), url_(isolate, url) {}; bool ModuleWrap::operator==(Local<Module>& mod) { return module_.Get(Isolate::GetCurrent())->GetIdentityHash() == mod->GetIdentityHash(); } Local<Module> ModuleWrap::module() { return module_.Get(Isolate::GetCurrent()); } Local<String> ModuleWrap::url() { return url_.Get(Isolate::GetCurrent()); } }
22.409091
89
0.703854
Qard
d88790b0562948b7fa957ebf6c42c2c0eea6b303
2,542
cp
C++
Sources_Common/Application/Preferences/CSearchStyle.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
12
2015-04-21T16:10:43.000Z
2021-11-05T13:41:46.000Z
Sources_Common/Application/Preferences/CSearchStyle.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
2
2015-11-02T13:32:11.000Z
2019-07-10T21:11:21.000Z
Sources_Common/Application/Preferences/CSearchStyle.cp
mulberry-mail/mulberry4-client
cdaae15c51dd759110b4fbdb2063d0e3d5202103
[ "ECL-2.0", "Apache-2.0" ]
6
2015-01-12T08:49:12.000Z
2021-03-27T09:11:10.000Z
/* Copyright (c) 2007 Cyrus Daboo. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Search style data object // Stores hierarchical search criteria that can be saved in prefs or applied as filter #include "CSearchStyle.h" #include "char_stream.h" #pragma mark ____________________________CSearchStyle extern const char* cSpace; // Copy construct CSearchStyle::CSearchStyle(const CSearchStyle& copy) { mItem = nil; _copy(copy); } // Assignment with same type CSearchStyle& CSearchStyle::operator=(const CSearchStyle& copy) { if (this != &copy) { _tidy(); _copy(copy); } return *this; } // Compare with same type int CSearchStyle::operator==(const CSearchStyle& other) const { // Just compare names return mName == other.mName; } void CSearchStyle::_copy(const CSearchStyle& copy) { mName = copy.mName; mItem = new CSearchItem(*copy.mItem); } // Parse S-Expression element bool CSearchStyle::SetInfo(char_stream& txt, NumVersion vers_prefs) { bool result = true; txt.get(mName, true); mItem = new CSearchItem; mItem->SetInfo(txt); return result; } // Create S_Expression element cdstring CSearchStyle::GetInfo(void) const { cdstring all; cdstring temp = mName; temp.quote(); temp.ConvertFromOS(); all += temp; all += cSpace; all += mItem->GetInfo(); return all; } #pragma mark ____________________________CSearchStyleList // Find named style const CSearchStyle* CSearchStyleList::FindStyle(const cdstring& name) const { CSearchStyle temp(name); CSearchStyleList::const_iterator found = begin(); for(; found != end(); found++) { if (**found == temp) break; } if (found != end()) return *found; else return nil; } // Find index of named style long CSearchStyleList::FindIndexOf(const cdstring& name) const { CSearchStyle temp(name); CSearchStyleList::const_iterator found = begin(); for(; found != end(); found++) { if (**found == temp) break; } if (found != end()) return found - begin(); else return -1; }
20.336
86
0.709284
mulberry-mail
d88b09f7941ed97b33f164ff59b9cd7a0be36365
606
hpp
C++
Helios/src/Game.hpp
rgracari/helio_test
2d516d16da4252c8f92f5c265b6151c6e87bc907
[ "Apache-2.0" ]
null
null
null
Helios/src/Game.hpp
rgracari/helio_test
2d516d16da4252c8f92f5c265b6151c6e87bc907
[ "Apache-2.0" ]
null
null
null
Helios/src/Game.hpp
rgracari/helio_test
2d516d16da4252c8f92f5c265b6151c6e87bc907
[ "Apache-2.0" ]
null
null
null
#pragma once #include <SDL.h> #include <memory> #include "Texture.hpp" #include "Sprite.hpp" #include "Clock.hpp" #include "Input.hpp" #include "Event.hpp" #include "SceneStateMachine.hpp" #include "scenes/SceneSplashScreen.hpp" #include "scenes/SceneGame.hpp" namespace Helio { class Game { private: Event event; Clock clock; double deltaTime; SceneStateMachine sceneStateMachine; public: Game(); void CaptureEvent(); //void CaptureInput(); void ProcessInput(); void Update(); void LateUpdate(); void Draw(); void CalculateDeltaTime(); bool IsRunning(); ~Game(); }; }
15.947368
39
0.70132
rgracari
d88f5accbe4168ea1013c8b0dca216ac0573e7fd
29,740
hpp
C++
include/CameraModels/CameraModelUtils.hpp
lukier/camera_models
90196141fa4749148b6a7b0adc7af19cb1971039
[ "BSD-3-Clause" ]
34
2016-11-13T22:17:50.000Z
2021-01-20T19:59:25.000Z
include/CameraModels/CameraModelUtils.hpp
lukier/camera_models
90196141fa4749148b6a7b0adc7af19cb1971039
[ "BSD-3-Clause" ]
null
null
null
include/CameraModels/CameraModelUtils.hpp
lukier/camera_models
90196141fa4749148b6a7b0adc7af19cb1971039
[ "BSD-3-Clause" ]
6
2016-11-14T00:45:56.000Z
2019-04-02T11:56:50.000Z
/** * **************************************************************************** * Copyright (c) 2015, Robert Lukierski. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. * * **************************************************************************** * Common types and functions. * **************************************************************************** */ #ifndef CAMERA_MODEL_UTILS_HPP #define CAMERA_MODEL_UTILS_HPP #include <Eigen/Core> #include <Eigen/Dense> #include <Eigen/Geometry> #include <unsupported/Eigen/AutoDiff> #include <sophus/so2.hpp> #include <sophus/se2.hpp> #include <sophus/so3.hpp> #include <sophus/se3.hpp> // For future Eigen + CUDA #ifndef EIGEN_DEVICE_FUNC #define EIGEN_DEVICE_FUNC #endif // EIGEN_DEVICE_FUNC // If Cereal serializer is preferred #ifdef CAMERA_MODELS_SERIALIZER_CEREAL #define CAMERA_MODELS_HAVE_SERIALIZER #define CAMERA_MODELS_SERIALIZE(ARCHIVE,NAME,VAR) ARCHIVE(cereal::make_nvp(NAME,VAR)) #endif // CAMERA_MODELS_SERIALIZER_CEREAL // If Boost serializer is preferred #ifdef CAMERA_MODELS_SERIALIZER_BOOST #define CAMERA_MODELS_HAVE_SERIALIZER #define CAMERA_MODELS_SERIALIZE(ARCHIVE,NAME,VAR) ARCHIVE & boost::serialization::make_nvp(NAME,VAR) #endif // CAMERA_MODELS_SERIALIZER_BOOST #ifndef VISIONCORE_EIGEN_MISSING_BITS_HPP #define VISIONCORE_EIGEN_MISSING_BITS_HPP namespace Eigen { namespace numext { template<typename T> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE T atan2(const T& y, const T &x) { EIGEN_USING_STD_MATH(atan2); return atan2(y,x); } #ifdef __CUDACC__ template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE float atan2(const float& y, const float &x) { return ::atan2f(y,x); } template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE double atan2(const double& y, const double &x) { return ::atan2(y,x); } #endif } template<typename DerType> inline const Eigen::AutoDiffScalar<EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(typename Eigen::internal::remove_all<DerType>::type, typename Eigen::internal::traits<typename Eigen::internal::remove_all<DerType>::type>::Scalar, product)> atan(const Eigen::AutoDiffScalar<DerType>& x) { using namespace Eigen; EIGEN_UNUSED typedef typename Eigen::internal::traits<typename Eigen::internal::remove_all<DerType>::type>::Scalar Scalar; using numext::atan; return Eigen::MakeAutoDiffScalar(atan(x.value()),x.derivatives() * ( Scalar(1) / (Scalar(1) + x.value() * x.value()) )); } } #endif // VISIONCORE_EIGEN_MISSING_BITS_HPP namespace cammod { /** * Camera Models */ enum class CameraModelType { PinholeDistance = 0, PinholeDistanceDistorted, PinholeDisparity, PinholeDisparityDistorted, Generic, GenericDistorted, Spherical, SphericalPovRay, Fisheye, FisheyeDistorted, PinholeDisparityBrownConrady }; template<CameraModelType cmt> struct CameraModelToTypeAndName; /** * Collection of common 2D/3D types. */ template<typename T> struct ComplexTypes { typedef Sophus::SO3<T> RotationT; typedef Sophus::SE3<T> TransformT; typedef Eigen::Map<TransformT> TransformMapT; typedef Eigen::Map<const TransformT> ConstTransformMapT; typedef Eigen::Map<RotationT> RotationMapT; typedef Eigen::Map<const RotationT> ConstRotationMapT; typedef Sophus::SO2<T> Rotation2DT; typedef Sophus::SE2<T> Transform2DT; typedef Eigen::Map<Transform2DT> Transform2DMapT; typedef Eigen::Map<const Transform2DT> ConstTransform2DMapT; typedef Eigen::Map<Rotation2DT> Rotation2DMapT; typedef Eigen::Map<const Rotation2DT> ConstRotation2DMapT; typedef typename Sophus::SE3<T>::Tangent TangentTransformT; typedef Eigen::Map<typename Sophus::SE3<T>::Tangent> TangentTransformMapT; typedef Eigen::Map<const typename Sophus::SE3<T>::Tangent> ConstTangentTransformMapT; typedef typename Sophus::SE2<T>::Tangent TangentTransform2DT; typedef Eigen::Map<typename Sophus::SE2<T>::Tangent> TangentTransform2DMapT; typedef Eigen::Map<const typename Sophus::SE2<T>::Tangent> ConstTangentTransform2DMapT; typedef typename Sophus::SO3<T>::Tangent TangentRotationT; typedef Eigen::Map<typename Sophus::SO3<T>::Tangent> TangentRotationMapT; typedef Eigen::Map<const typename Sophus::SO3<T>::Tangent> ConstTangentRotationMapT; typedef typename Sophus::SO2<T>::Tangent TangentRotation2DT; typedef Eigen::Map<typename Sophus::SO2<T>::Tangent> TangentRotation2DMapT; typedef Eigen::Map<const typename Sophus::SO2<T>::Tangent> ConstTangentRotation2DMapT; typedef Eigen::Matrix<T,2,1> PixelT; typedef Eigen::Map<PixelT> PixelMapT; typedef Eigen::Map<const PixelT> ConstPixelMapT; typedef typename TransformT::Point PointT; typedef Eigen::Map<PointT> PointMapT; typedef Eigen::Map<const PointT> ConstPointMapT; typedef typename Transform2DT::Point Point2DT; typedef Eigen::Map<Point2DT> Point2DMapT; typedef Eigen::Map<const Point2DT> ConstPoint2DMapT; typedef Eigen::Quaternion<T> QuaternionT; typedef Eigen::Map<QuaternionT> QuaternionMapT; typedef Eigen::Map<const QuaternionT> ConstQuaternionMapT; typedef Eigen::Matrix<T,2,3> ForwardPointJacobianT; typedef Eigen::Map<ForwardPointJacobianT> ForwardPointJacobianMapT; typedef Eigen::Map<const ForwardPointJacobianT> ConstForwardPointJacobianMapT; typedef Eigen::Matrix<T,3,2> InversePointJacobianT; typedef Eigen::Map<InversePointJacobianT> InversePointJacobianMapT; typedef Eigen::Map<const InversePointJacobianT> ConstInversePointJacobianMapT; typedef Eigen::Matrix<T,2,2> DistortionJacobianT; typedef Eigen::Map<DistortionJacobianT> DistortionJacobianMapT; typedef Eigen::Map<const DistortionJacobianT> ConstDistortionJacobianMapT; template<int ParametersToOptimize> using ForwardParametersJacobianT = Eigen::Matrix<T,2,ParametersToOptimize>; template<int ParametersToOptimize> using ForwardParametersJacobianMapT = Eigen::Map<ForwardParametersJacobianT<ParametersToOptimize>>; template<int ParametersToOptimize> using ConstForwardParametersJacobianMapT = Eigen::Map<const ForwardParametersJacobianT<ParametersToOptimize>>; }; template<typename T> EIGEN_DEVICE_FUNC static inline T getFieldOfView(T focal, T width) { using Eigen::numext::atan; return T(2.0) * atan(width / (T(2.0) * focal)); } template<typename T> EIGEN_DEVICE_FUNC static inline T getFocalLength(T fov, T width) { using Eigen::numext::tan; return width / (T(2.0) * tan(fov / T(2.0))); } /** * Runtime polymorphic interface if one prefers that. */ template<typename T> class CameraInterface { public: virtual ~CameraInterface() { } virtual CameraModelType getModelType() const = 0; virtual const char* getModelName() const = 0; virtual bool pointValid(const typename ComplexTypes<T>::PointT& tmp_pt) const = 0; virtual bool pixelValid(T x, T y) const = 0; virtual bool pixelValidSquare(T x, T y) const = 0; virtual bool pixelValidSquare(const typename ComplexTypes<T>::PixelT& pt) const = 0; virtual bool pixelValidCircular(T x, T y) const = 0; virtual bool pixelValidCircular(const typename ComplexTypes<T>::PixelT& pt) const = 0; virtual typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::PointT& tmp_pt) const = 0; virtual typename ComplexTypes<T>::PointT inverse(T x, T y) const = 0; virtual typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PointT& pt) const = 0; virtual typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::RotationT& pose, const typename ComplexTypes<T>::PointT& pt) const = 0; virtual typename ComplexTypes<T>::PointT inverse(const typename ComplexTypes<T>::PixelT& pix) const = 0; virtual typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::PixelT& pix, T dist) const = 0; virtual typename ComplexTypes<T>::PointT inverseAtDistance(T x, T y, T dist) const = 0; virtual typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PixelT& pix, T dist) const = 0; virtual typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose, T x, T y, T dist) const = 0; virtual typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1, const typename ComplexTypes<T>::PixelT& pix, T dist, const typename ComplexTypes<T>::TransformT& pose2) const = 0; virtual typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1, T x, T y, T dist, const typename ComplexTypes<T>::TransformT& pose2) const = 0; }; /** * Functions / methods shared by all the camera models. */ template<typename Derived> class CameraFunctions { static constexpr unsigned int ParametersToOptimize = Eigen::internal::traits<Derived>::ParametersToOptimize; static constexpr bool HasForwardPointJacobian = Eigen::internal::traits<Derived>::HasForwardPointJacobian; static constexpr bool HasForwardParametersJacobian = Eigen::internal::traits<Derived>::HasForwardParametersJacobian; static constexpr bool HasInversePointJacobian = Eigen::internal::traits<Derived>::HasInversePointJacobian; static constexpr bool HasInverseParametersJacobian = Eigen::internal::traits<Derived>::HasInverseParametersJacobian; public: typedef typename Eigen::internal::traits<Derived>::Scalar Scalar; // ------------------- statics --------------------- template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT worldToCamera(const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PointT& pt) { return pose.inverse() * pt; // why! } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT cameraToWorld(const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PointT& pt) { return pose * pt; // why! } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT worldToCamera(const typename ComplexTypes<T>::RotationT& pose, const typename ComplexTypes<T>::PointT& pt) { return pose.inverse() * pt; // why! } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT cameraToWorld(const typename ComplexTypes<T>::RotationT& pose, const typename ComplexTypes<T>::PointT& pt) { return pose * pt; // why! } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValid(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pt) { return Derived::template pixelValidSquare<T>(ccd, pt(0), pt(1)); } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidCircular(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pt) { return Derived::template pixelValidCircular<T>(ccd, pt(0), pt(1)); } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidSquare(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pt) { return Derived::template pixelValidSquare<T>(ccd, pt(0), pt(1)); } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resizeViewport(Derived& ccd, const typename ComplexTypes<T>::PixelT& pt) { Derived::template resizeViewport<T>(ccd, pt(0), pt(1)); } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const Derived& ccd, const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PointT& pt) { return Derived::template forward<T>(ccd, worldToCamera<T>(pose, pt)); } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const Derived& ccd, const typename ComplexTypes<T>::RotationT& pose, const typename ComplexTypes<T>::PointT& pt) { return Derived::template forward<T>(ccd, worldToCamera<T>(pose, pt)); } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverse(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pix) { return Derived::template inverse<T>(ccd, pix(0), pix(1)); } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pix, T dist) { return Derived::template inverse<T>(ccd, pix(0), pix(1)) * dist; } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd, T x, T y, T dist) { return Derived::template inverse<T>(ccd, x, y) * dist; } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd, const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PixelT& pix, T dist) { return cameraToWorld<T>(pose, ((Derived::template inverse<T>(ccd,pix)) * dist)); } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd, const typename ComplexTypes<T>::TransformT& pose, T x, T y, T dist) { return cameraToWorld<T>(pose, ((Derived::template inverse<T>(ccd,x,y)) * dist)); } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const Derived& ccd, const typename ComplexTypes<T>::TransformT& pose1, const typename ComplexTypes<T>::PixelT& pix, T dist, const typename ComplexTypes<T>::TransformT& pose2) { return forward<T>(ccd, pose2, inverseAtDistance<T>(ccd, pose1, pix, dist)); } template<typename T = Scalar> static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const Derived& ccd, const typename ComplexTypes<T>::TransformT& pose1, T x, T y, T dist, const typename ComplexTypes<T>::TransformT& pose2) { return forward<T>(ccd, pose2, inverseAtDistance<T>(ccd, pose1, x, y, dist)); } // ------------------- non statics --------------------- template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resizeViewport(T x, T y) { Derived::template resizeViewport<T>(*static_cast<Derived*>(this), x, y); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resizeViewport(const typename ComplexTypes<T>::PixelT& pt) { Derived::template resizeViewport<T>(*static_cast<Derived*>(this), pt(0), pt(1)); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pointValid(const typename ComplexTypes<T>::PointT& pt) const { return Derived::template pointValid<T>(*static_cast<const Derived*>(this), pt); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValid(T x, T y) const { return Derived::template pixelValidSquare<T>(*static_cast<const Derived*>(this), x, y); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidSquare(T x, T y) const { return Derived::template pixelValidSquare<T>(*static_cast<const Derived*>(this), x, y); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidSquare(const typename ComplexTypes<T>::PixelT& pt) const { return Derived::template pixelValidSquare<T>(*static_cast<const Derived*>(this), pt(0), pt(1)); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidCircular(T x, T y) const { return Derived::template pixelValidCircular<T>(*static_cast<const Derived*>(this), x, y); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidCircular(const typename ComplexTypes<T>::PixelT& pt) const { return Derived::template pixelValidCircular<T>(*static_cast<const Derived*>(this), pt(0), pt(1)); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::PointT& tmp_pt) const { return Derived::template forward<T>(*static_cast<const Derived*>(this), tmp_pt); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverse(T x, T y) const { return Derived::template inverse<T>(*static_cast<const Derived*>(this), x, y); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PointT& pt) const { return CameraFunctions::forward<T>(*static_cast<const Derived*>(this), pose, pt); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::RotationT& pose, const typename ComplexTypes<T>::PointT& pt) const { return CameraFunctions::forward<T>(*static_cast<const Derived*>(this), pose, pt); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename std::enable_if<HasForwardPointJacobian, typename ComplexTypes<T>::ForwardPointJacobianT>::type forwardPointJacobian(const typename ComplexTypes<T>::PointT& pt) const { return Derived::template forwardPointJacobian<T>(*static_cast<const Derived*>(this), pt); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename std::enable_if<HasForwardParametersJacobian, typename ComplexTypes<T>::template ForwardParametersJacobianT<ParametersToOptimize> >::type forwardParametersJacobian(const typename ComplexTypes<T>::PointT& pt) const { return Derived::template forwardParametersJacobian<T>(*static_cast<const Derived*>(this), pt); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverse(const typename ComplexTypes<T>::PixelT& pix) const { return CameraFunctions::inverse<T>(*static_cast<const Derived*>(this), pix); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::PixelT& pix, T dist) const { return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), pix, dist); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(T x, T y, T dist) const { return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), x, y, dist); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PixelT& pix, T dist) const { return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), pose, pix, dist); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose, T x, T y, T dist) const { return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), pose, x, y, dist); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1, const typename ComplexTypes<T>::PixelT& pix, T dist, const typename ComplexTypes<T>::TransformT& pose2) const { return CameraFunctions::twoFrameProject<T>(*static_cast<const Derived*>(this), pose1, pix, dist, pose2); } template<typename T = Scalar> EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1, T x, T y, T dist, const typename ComplexTypes<T>::TransformT& pose2) const { return CameraFunctions::twoFrameProject<T>(*static_cast<const Derived*>(this), pose1, x, y, dist, pose2); } }; /** * Wraps templated typed camera model into a polymorphic class. */ template <typename ModelT> class CameraFromCRTP : public ModelT, public CameraInterface<typename ModelT::Scalar> { public: typedef ModelT Derived; typedef typename Derived::Scalar Scalar; CameraFromCRTP() = default; CameraFromCRTP(const Derived& d) : Derived(d) { } CameraFromCRTP(const CameraFromCRTP& other) = default; virtual ~CameraFromCRTP() { } virtual CameraModelType getModelType() const { return Derived::ModelType; } virtual const char* getModelName() const { return CameraModelToTypeAndName<Derived::ModelType>::Name; } virtual bool pointValid(const typename ComplexTypes<Scalar>::PointT& tmp_pt) const { return Derived::template pointValid<Scalar>(tmp_pt); } virtual bool pixelValid(Scalar x, Scalar y) const { return Derived::template pixelValid<Scalar>(x,y); } virtual bool pixelValidSquare(Scalar x, Scalar y) const { return Derived::template pixelValidSquare<Scalar>(x,y); } virtual bool pixelValidSquare(const typename ComplexTypes<Scalar>::PixelT& pt) const { return Derived::template pixelValidSquare<Scalar>(pt); } virtual bool pixelValidCircular(Scalar x, Scalar y) const { return Derived::template pixelValidCircular<Scalar>(x,y); } virtual bool pixelValidCircular(const typename ComplexTypes<Scalar>::PixelT& pt) const { return Derived::template pixelValidCircular<Scalar>(pt); } virtual typename ComplexTypes<Scalar>::PixelT forward(const typename ComplexTypes<Scalar>::PointT& tmp_pt) const { return Derived::template forward<Scalar>(tmp_pt); } virtual typename ComplexTypes<Scalar>::PointT inverse(Scalar x, Scalar y) const { return Derived::template inverse<Scalar>(x,y); } virtual typename ComplexTypes<Scalar>::PixelT forward(const typename ComplexTypes<Scalar>::TransformT& pose, const typename ComplexTypes<Scalar>::PointT& pt) const { return Derived::template forward<Scalar>(pose, pt); } virtual typename ComplexTypes<Scalar>::PixelT forward(const typename ComplexTypes<Scalar>::RotationT& pose, const typename ComplexTypes<Scalar>::PointT& pt) const { return Derived::template forward<Scalar>(pose, pt); } virtual typename ComplexTypes<Scalar>::PointT inverse(const typename ComplexTypes<Scalar>::PixelT& pix) const { return Derived::template inverse<Scalar>(pix); } virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(const typename ComplexTypes<Scalar>::PixelT& pix, Scalar dist) const { return Derived::template inverseAtDistance<Scalar>(pix,dist); } virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(Scalar x, Scalar y, Scalar dist) const { return Derived::template inverseAtDistance<Scalar>(x,y,dist); } virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(const typename ComplexTypes<Scalar>::TransformT& pose, const typename ComplexTypes<Scalar>::PixelT& pix, Scalar dist) const { return Derived::template inverseAtDistance<Scalar>(pose,pix,dist); } virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(const typename ComplexTypes<Scalar>::TransformT& pose, Scalar x, Scalar y, Scalar dist) const { return Derived::template inverseAtDistance<Scalar>(pose,x,y,dist); } virtual typename ComplexTypes<Scalar>::PixelT twoFrameProject(const typename ComplexTypes<Scalar>::TransformT& pose1, const typename ComplexTypes<Scalar>::PixelT& pix, Scalar dist, const typename ComplexTypes<Scalar>::TransformT& pose2) const { return Derived::template twoFrameProject<Scalar>(pose1,pix,dist,pose2); } virtual typename ComplexTypes<Scalar>::PixelT twoFrameProject(const typename ComplexTypes<Scalar>::TransformT& pose1, Scalar x, Scalar y, Scalar dist, const typename ComplexTypes<Scalar>::TransformT& pose2) const { return Derived::template twoFrameProject<Scalar>(pose1,x,y,dist,pose2); } }; } #endif // CAMERA_MODEL_UTILS_HPP
46.323988
263
0.648857
lukier
d8918e5ce4cd1348ab24b3521eb4ec70ebe62e0a
2,657
cc
C++
euler/core/kernels/sample_edge_op.cc
HuangLED/euler
a56b5fe3fe56123af062317ca0b4160ce3b3ace9
[ "Apache-2.0" ]
2,829
2019-01-12T09:16:03.000Z
2022-03-29T14:00:58.000Z
euler/core/kernels/sample_edge_op.cc
HuangLED/euler
a56b5fe3fe56123af062317ca0b4160ce3b3ace9
[ "Apache-2.0" ]
331
2019-01-17T21:07:49.000Z
2022-03-30T06:38:17.000Z
euler/core/kernels/sample_edge_op.cc
HuangLED/euler
a56b5fe3fe56123af062317ca0b4160ce3b3ace9
[ "Apache-2.0" ]
578
2019-01-16T10:48:53.000Z
2022-03-21T13:41:34.000Z
/* Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <string> #include "euler/core/framework/op_kernel.h" #include "euler/core/framework/dag_node.pb.h" #include "euler/common/logging.h" #include "euler/core/api/api.h" namespace euler { class SampleEdgeOp: public OpKernel { public: explicit SampleEdgeOp(const std::string& name): OpKernel(name) { } void Compute(const DAGNodeProto& node_def, OpKernelContext* ctx); }; void SampleEdgeOp::Compute(const DAGNodeProto& node_def, OpKernelContext* ctx) { if (node_def.inputs_size() != 2) { EULER_LOG(ERROR) << "Invalid input arguments"; return; } Tensor* edge_type_t = nullptr; auto s = ctx->tensor(node_def.inputs(0), &edge_type_t); if (!s.ok()) { EULER_LOG(ERROR) << "Retrieve edge_type input failed!"; return; } Tensor* count_t = nullptr; s = ctx->tensor(node_def.inputs(1), &count_t); if (!s.ok()) { EULER_LOG(ERROR) << "Retrieve count input failed!"; return; } std::vector<int> edge_types(edge_type_t->NumElements()); std::copy(edge_type_t->Raw<int32_t>(), edge_type_t->Raw<int32_t>() + edge_type_t->NumElements(), edge_types.begin()); int count = *count_t->Raw<int32_t>(); auto edge_id_vec = euler::SampleEdge(edge_types, count); if (edge_id_vec.size() != static_cast<size_t>(count)) { EULER_LOG(ERROR) << "Expect sample count: " << count << ", real got:" << edge_id_vec.size(); return; } std::string output_name = OutputName(node_def, 0); TensorShape shape({ static_cast<size_t>(count), 3ul }); Tensor* output = nullptr; s = ctx->Allocate(output_name, shape, DataType::kInt64, &output); if (!s.ok()) { EULER_LOG(ERROR) << "Allocate output tensor failed!"; return; } auto data = output->Raw<int64_t>(); for (auto& edge_id : edge_id_vec) { *data++ = std::get<0>(edge_id); *data++ = std::get<1>(edge_id); *data++ = std::get<2>(edge_id); } } REGISTER_OP_KERNEL("API_SAMPLE_EDGE", SampleEdgeOp); } // namespace euler
31.630952
80
0.666165
HuangLED
d894316a3388b78f662dc89b069e5ff4a9bf42f4
1,339
cpp
C++
src/lighting.cpp
armedturret/GlassWall
1ff438987d32be154ce81488a8f2729eaaf563ee
[ "MIT" ]
null
null
null
src/lighting.cpp
armedturret/GlassWall
1ff438987d32be154ce81488a8f2729eaaf563ee
[ "MIT" ]
null
null
null
src/lighting.cpp
armedturret/GlassWall
1ff438987d32be154ce81488a8f2729eaaf563ee
[ "MIT" ]
1
2018-12-23T01:46:41.000Z
2018-12-23T01:46:41.000Z
#include <lighting.h> GW::RenderEngine::Lighting::Lighting() { } GW::RenderEngine::Lighting::~Lighting() { } void GW::RenderEngine::Lighting::setDirectionalLight(const DirectionalLight & light) { m_directionalLight = light; } void GW::RenderEngine::Lighting::addPointLight(const PointLight & light) { m_pointLights.push_back(light); } void GW::RenderEngine::Lighting::addSpotLight(const SpotLight & light) { m_spotLights.push_back(light); } void GW::RenderEngine::Lighting::setPointLight(unsigned int index, const PointLight & light) { if (index < m_pointLights.size()) { m_pointLights[index] = light; } } void GW::RenderEngine::Lighting::setSpotLight(unsigned int index, const SpotLight & light) { if (index < m_spotLights.size()) { m_spotLights[index] = light; } } GW::RenderEngine::PointLight GW::RenderEngine::Lighting::getPointLight(unsigned int index) { if (index < m_pointLights.size()) { return m_pointLights[index]; } return GW::RenderEngine::PointLight(); } std::vector<GW::RenderEngine::PointLight> GW::RenderEngine::Lighting::getPointLights() { return m_pointLights; } std::vector<GW::RenderEngine::SpotLight> GW::RenderEngine::Lighting::getSpotLights() { return m_spotLights; } GW::RenderEngine::DirectionalLight GW::RenderEngine::Lighting::getDirectionalLight() { return m_directionalLight; }
21.253968
92
0.746826
armedturret
d894353cd687d3ce761962c40144ad58c01ad041
1,234
cpp
C++
EngineAttempt0/project/src/engine/general/Transform.cpp
MEEMEEMAN/EngineAttempt0
2d470af8d19b8f90c03b1bcdee9ae64f3cddd7b6
[ "MIT" ]
null
null
null
EngineAttempt0/project/src/engine/general/Transform.cpp
MEEMEEMAN/EngineAttempt0
2d470af8d19b8f90c03b1bcdee9ae64f3cddd7b6
[ "MIT" ]
null
null
null
EngineAttempt0/project/src/engine/general/Transform.cpp
MEEMEEMAN/EngineAttempt0
2d470af8d19b8f90c03b1bcdee9ae64f3cddd7b6
[ "MIT" ]
null
null
null
#include "Transform.h" void Transform::UpdateTRS() { mat4 modelMatrix = mat4(1); modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.x), vec3(1, 0, 0)); modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.y), vec3(0, 1, 0)); modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.z), vec3(0, 0, 1)); modelMatrix = glm::scale(modelMatrix, scale); mModelMatrix = modelMatrix; CalcDirections(); } void Transform::UpdateSRT() { mat4 modelMatrix = mat4(1); modelMatrix = glm::scale(modelMatrix, scale); modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.x), vec3(1, 0, 0)); modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.y), vec3(0, 1, 0)); modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.z), vec3(0, 0, 1)); modelMatrix = glm::translate(modelMatrix, position); mModelMatrix = modelMatrix; CalcDirections(); } void Transform::CalcDirections() { mat4 inverse = glm::inverse(mModelMatrix); mForward = glm::normalize(glm::vec3(inverse[2])); vec3 right = glm::normalize(glm::cross(mForward, vec3(0, 1, 0))); mRight = right; vec3 top = glm::normalize(glm::cross(mForward, mRight)); mUp = top; }
26.826087
81
0.703404
MEEMEEMAN
d89886f2c4165e5ace2f8f6e9b07abdfd2d5d458
233
cpp
C++
library/src/ButtonMatrix.cpp
StratifyLabs/LvglAPI
c869d5b38ad3aa148fa0801d12271f2d9a6043c5
[ "MIT" ]
1
2022-01-03T19:16:58.000Z
2022-01-03T19:16:58.000Z
library/src/ButtonMatrix.cpp
StratifyLabs/LvglAPI
c869d5b38ad3aa148fa0801d12271f2d9a6043c5
[ "MIT" ]
null
null
null
library/src/ButtonMatrix.cpp
StratifyLabs/LvglAPI
c869d5b38ad3aa148fa0801d12271f2d9a6043c5
[ "MIT" ]
null
null
null
#include "lvgl/ButtonMatrix.hpp" using namespace lvgl; LVGL_OBJECT_ASSERT_SIZE(ButtonMatrix); ButtonMatrix::ButtonMatrix(const char * name){ m_object = api()->btnmatrix_create(screen_object()); set_user_data(m_object,name); }
21.181818
54
0.776824
StratifyLabs
d8989ee0c5f697d49473166919b635c30401a505
15,067
cpp
C++
3rdparty/GPSTk/ext/apps/geomatics/relposition/ProcessRawData.cpp
mfkiwl/ICE
e660d031bb1bcea664db1de4946fd8781be5b627
[ "MIT" ]
50
2019-10-12T01:22:20.000Z
2022-02-15T23:28:26.000Z
3rdparty/GPSTk/ext/apps/geomatics/relposition/ProcessRawData.cpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
null
null
null
3rdparty/GPSTk/ext/apps/geomatics/relposition/ProcessRawData.cpp
wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation
2f1ff054b7c5059da80bb3b2f80c05861a02cc36
[ "MIT" ]
14
2019-11-05T01:50:29.000Z
2021-08-06T06:23:44.000Z
//============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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.0 of the License, or // any later version. // // The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= /** * @file ProcessRawData.cpp * Process raw data, including editing, buffering and computation of a pseudorange * solution using RAIM algorithm, part of program DDBase. */ //------------------------------------------------------------------------------------ // TD ProcessRawData put back EOP mean of date // TD ProcessRawData user input pseudorange limits in EditRawData(ObsFile& obsfile) //------------------------------------------------------------------------------------ // system includes // GPSTk #include "EphemerisRange.hpp" #include "TimeString.hpp" // DDBase //#include "PreciseRange.hpp" #include "DDBase.hpp" #include "index.hpp" //------------------------------------------------------------------------------------ using namespace std; using namespace gpstk; //------------------------------------------------------------------------------------ // local data static vector<SatID> Sats; // used by RAIM, bad ones come back marked (id < 0) //------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------ // prototypes -- this module only // ComputeRAIMSolution.cpp : int ComputeRAIMSolution(ObsFile& of,CommonTime& tt,vector<SatID>& Sats,ofstream *pofs) throw(Exception); void RAIMedit(ObsFile& of, vector<SatID>& Sats) throw(Exception); // those defined here void FillRawData(ObsFile& of) throw(Exception); void GetEphemerisRange(ObsFile& obsfile, CommonTime& timetag) throw(Exception); void EditRawData(ObsFile& of) throw(Exception); int BufferRawData(ObsFile& of) throw(Exception); //------------------------------------------------------------------------------------ int ProcessRawData(ObsFile& obsfile, CommonTime& timetag, ofstream *pofs) throw(Exception) { try { int iret; // fill RawDataMap for Station FillRawData(obsfile); // compute nominal elevation and ephemeris range; RecomputeFromEphemeris // will re-do after synchronization and before differencing GetEphemerisRange(obsfile,timetag); // Edit raw data for this station EditRawData(obsfile); // fill RawDataMap for Station, and compute pseudorange solution // return Sats, with bad satellites marked with (id < 0) iret = ComputeRAIMSolution(obsfile,timetag,Sats,pofs); if(iret) { if(CI.Verbose) oflog << " Warning - ProcessRawData for station " << obsfile.label << ", at time " << printTime(timetag,"%Y/%02m/%02d %2H:%02M:%6.3f=%F/%10.3g,") << " failed with code " << iret << (iret == 2 ? " (large RMS residual)" : (iret == 1 ? " (large slope)" : (iret == -1 ? " (no convergence)" : (iret == -2 ? " (singular)" : (iret == -3 ? " (not enough satellites)" : (iret == -4 ? " (no ephemeris)" : (iret == -5 ? " (invalid solution)" : " (unknown)"))))))) << endl; // TD change this -- or user input ? //if(iret > 0) iret = 0; // suspect solution if(iret) { Stations[obsfile.label].PRS.Valid = false; // remove data in RAIMedit } } // save statistics on PR solution Station& st=Stations[obsfile.label]; if(st.PRS.Valid) { st.PRSXstats.Add(st.PRS.Solution(0)); st.PRSYstats.Add(st.PRS.Solution(1)); st.PRSZstats.Add(st.PRS.Solution(2)); } // if user wants PRSolution2 as a priori, update it here so that the // elevation can be computed - this serves to eliminate the low-elevation // data from the raw data buffers and simplifies processing. // it does not seem to affect the final estimation processing at all... if(st.usePRS && st.PRSXstats.N() >= 10) { Position prs; prs.setECEF(st.PRSXstats.Average(), st.PRSYstats.Average(), st.PRSZstats.Average()); st.pos = prs; if(CI.Debug) oflog << "Update apriori=PR solution for " << obsfile.label << " at " << printTime(timetag,"%Y/%02m/%02d %2H:%02M:%6.3f=%F/%10.3g") << fixed << setprecision(5) << " " << setw(15) << st.PRSXstats.Average() << " " << setw(15) << st.PRSYstats.Average() << " " << setw(15) << st.PRSZstats.Average() << endl; } // edit based on RAIM, using Sats RAIMedit(obsfile,Sats); // buffer raw data, including ER(==0), EL and clock iret = BufferRawData(obsfile); if(iret) return iret; // always returns 0 return 0; } catch(Exception& e) { GPSTK_RETHROW(e); } catch(std::exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); } catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); } } // end ProcessRawData //------------------------------------------------------------------------------------ void FillRawData(ObsFile& of) throw(Exception) { try { //int nsvs; //double C1; GSatID sat; RinexObsData::RinexSatMap::const_iterator it; RinexObsData::RinexObsTypeMap otmap; RinexObsData::RinexObsTypeMap::const_iterator jt; Station& st=Stations[of.label]; st.RawDataMap.clear(); // assumes one file per site at each epoch // loop over sat=it->first, ObsTypeMap=it->second // fill DataStruct // Don't include L2 when user has specified --Freq L1 -- there have been // cases where L2 is present but bad, and user had no recourse but to edit // the RINEX file to remove L2 before processing //nsvs = 0; for(it=of.Robs.obs.begin(); it != of.Robs.obs.end(); ++it) { sat = it->first; otmap = it->second; // ignore non-GPS satellites if(sat.system != SatID::systemGPS) continue; // is the satellite excluded? if(index(CI.ExSV,sat) != -1) continue; // pull out the data DataStruct D; D.P1 = D.P2 = D.L1 = D.L2 = D.D1 = D.D2 = D.S1 = D.S2 = 0; if(of.inP1 > -1 && CI.Frequency != 2 && (jt=otmap.find(of.Rhead.obsTypeList[of.inP1])) != otmap.end()) D.P1 = jt->second.data; if(of.inP2 > -1 && CI.Frequency != 1 && (jt=otmap.find(of.Rhead.obsTypeList[of.inP2])) != otmap.end()) D.P2 = jt->second.data; if(of.inL1 > -1 && CI.Frequency != 2 && (jt=otmap.find(of.Rhead.obsTypeList[of.inL1])) != otmap.end()) D.L1 = jt->second.data; if(of.inL2 > -1 && CI.Frequency != 1 && (jt=otmap.find(of.Rhead.obsTypeList[of.inL2])) != otmap.end()) D.L2 = jt->second.data; if(of.inD1 > -1 && CI.Frequency != 2 && (jt=otmap.find(of.Rhead.obsTypeList[of.inD1])) != otmap.end()) D.D1 = jt->second.data; if(of.inD2 > -1 && CI.Frequency != 1 && (jt=otmap.find(of.Rhead.obsTypeList[of.inD2])) != otmap.end()) D.D2 = jt->second.data; if(of.inS1 > -1 && CI.Frequency != 2 && (jt=otmap.find(of.Rhead.obsTypeList[of.inS1])) != otmap.end()) D.S1 = jt->second.data; if(of.inS2 > -1 && CI.Frequency != 1 && (jt=otmap.find(of.Rhead.obsTypeList[of.inS2])) != otmap.end()) D.S2 = jt->second.data; //if(of.inC1 > -1 && CI.Frequency != 2 && // (jt=otmap.find(of.Rhead.obsTypeList[of.inC1])) != otmap.end()) // C1 = jt->second.data; // if P1 is not available, but C1 is, use C1 in place of P1 if((of.inP1 == -1 || D.P1 == 0) && of.inC1 > -1 && CI.Frequency != 2 && (jt=otmap.find(of.Rhead.obsTypeList[of.inC1])) != otmap.end()) D.P1 = jt->second.data; // temp - round L1 and L2 to 1/256 cycle //{ // double dL1 = D.L1 - long(D.L1); // double cL1 = double(long(256.*dL1))/256.; // D.L1 -= dL1 - cL1; //} st.RawDataMap[sat] = D; st.time = SolutionEpoch; //nsvs++; } // end loop over sats } catch(Exception& e) { GPSTK_RETHROW(e); } catch(std::exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); } catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); } } // end FillRawData() //------------------------------------------------------------------------------------ void GetEphemerisRange(ObsFile& obsfile, CommonTime& timetag) throw(Exception) { try { CorrectedEphemerisRange CER; // temp //PreciseRange CER; Station& st=Stations[obsfile.label]; map<GSatID,DataStruct>::iterator it; for(it=st.RawDataMap.begin(); it != st.RawDataMap.end(); it++) { // ER cannot be used until the a priori positions are computed -- // because user may want the PRSolution2 as the a priori, we must wait. // This will be updated in RecomputeFromEphemeris(), after Synchronization() it->second.ER = 0.0; // this will happen when user has chosen to use the PRSolution2 as the a priori // and the st.pos has not yet been updated if(st.pos.getCoordinateSystem() == Position::Unknown) { it->second.elev = 90.0; // include it in the PRS it->second.az = 0.0; continue; } // TD why did PreciseRange not throw here? // catch NoEphemerisFound and set elevation -90 --> edited out later try { //it->second.ER = CER.ComputeAtReceiveTime(timetag, st.pos, it->first, *pEph); it->second.elev = CER.elevation; // this will be compared to PRS elev Limit it->second.az = CER.azimuth; } catch(InvalidRequest& e) { if(CI.Verbose) oflog << "No ephemeris found for sat " << it->first << " at time " << printTime(timetag,"%Y/%02m/%02d %2H:%02M:%6.3f=%F/%10.3g") << endl; //it->second.ER = 0.0; it->second.elev = -90.0; // do not include it in the PRS it->second.az = 0.0; } } } catch(Exception& e) { GPSTK_RETHROW(e); } catch(std::exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); } catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); } } //------------------------------------------------------------------------------------ void EditRawData(ObsFile& obsfile) throw(Exception) { try { size_t i; Station& st=Stations[obsfile.label]; vector<GSatID> BadSVs; map<GSatID,DataStruct>::iterator it; for(it=st.RawDataMap.begin(); it != st.RawDataMap.end(); it++) { if( // DON'T DO THIS - clock may get large and negative, leading to negative PR // bad pseudorange // (CI.Frequency != 2 && it->second.P1 < 1000.0) || // TD // (CI.Frequency != 1 && it->second.P2 < 1000.0) || // below elevation cutoff (for PRS) (it->second.elev < CI.PRSMinElevation) ) { //end if BadSVs.push_back(it->first); } } // delete the bad satellites for(i=0; i<BadSVs.size(); i++) { st.RawDataMap.erase(BadSVs[i]); } } catch(Exception& e) { GPSTK_RETHROW(e); } catch(std::exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); } catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); } } // end EditRawData() //------------------------------------------------------------------------------------ // add good raw data in RawDataMap to RawDataBuffers for the appropriate station // and satellite. Also buffer the clock solution and sigma. // NB these buffers must remain parallel. int BufferRawData(ObsFile& obsfile) throw(Exception) { try { Station& st=Stations[obsfile.label]; map<GSatID,DataStruct>::iterator it; map<GSatID,RawData>::iterator jt; // loop over satellites for(it=st.RawDataMap.begin(); it != st.RawDataMap.end(); it++) { // find iterator for this sat in Buffers map jt = st.RawDataBuffers.find(it->first); if(jt == st.RawDataBuffers.end()) { RawData rd; st.RawDataBuffers[it->first] = rd; jt = st.RawDataBuffers.find(it->first); } // buffer the data -- keep parallel with count jt->second.count.push_back(Count); jt->second.L1.push_back(it->second.L1); jt->second.L2.push_back(it->second.L2); jt->second.P1.push_back(it->second.P1); jt->second.P2.push_back(it->second.P2); jt->second.ER.push_back(it->second.ER); jt->second.S1.push_back(it->second.S1); jt->second.S2.push_back(it->second.S2); jt->second.elev.push_back(it->second.elev); jt->second.az.push_back(it->second.az); } // buffer the clock solution and the timetag offset, and // buffer the (Station) count in parallel. // NB these are NOT necessarily parallel to raw data buffers if(st.PRS.isValid()) { st.ClockBuffer.push_back(st.PRS.Solution(3)); st.ClkSigBuffer.push_back(st.PRS.Covariance(3,3)); st.RxTimeOffset.push_back(SolutionEpoch - obsfile.Robs.time); } else { st.ClockBuffer.push_back(0.0); st.ClkSigBuffer.push_back(0.0); st.RxTimeOffset.push_back(0.0); } st.CountBuffer.push_back(Count); return 0; } catch(Exception& e) { GPSTK_RETHROW(e); } catch(std::exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); } catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); } } //------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------
38.338422
90
0.553727
mfkiwl
d89a1419d316000ed182f6a183475ebeb0a06af7
23,275
cpp
C++
codecparsers/vp9parser.cpp
genisysram/libyami
08d3ecbbfe1f5d23d433523f747a7093a0b3a13a
[ "Apache-2.0" ]
89
2015-01-09T10:31:13.000Z
2018-01-18T12:48:21.000Z
codecparsers/vp9parser.cpp
genisysram/libyami
08d3ecbbfe1f5d23d433523f747a7093a0b3a13a
[ "Apache-2.0" ]
626
2015-01-12T00:01:26.000Z
2018-01-23T18:58:58.000Z
codecparsers/vp9parser.cpp
genisysram/libyami
08d3ecbbfe1f5d23d433523f747a7093a0b3a13a
[ "Apache-2.0" ]
104
2015-01-12T04:02:09.000Z
2017-12-28T08:27:42.000Z
/* * Copyright 2016 Intel Corporation * * 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. */ /** * SECTION:vp9parser * @short_description: Convenience library for parsing vp9 video bitstream. * * For more details about the structures, you can refer to the * specifications: */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "bitReader.h" #include "vp9quant.h" #include "vp9parser.h" #include <string.h> #include <stdlib.h> #include "common/log.h" using YamiParser::BitReader; #define MAX_LOOP_FILTER 63 #define MAX_PROB 255 typedef struct _ReferenceSize { uint32_t width; uint32_t height; } ReferenceSize; typedef struct _Vp9ParserPrivate { BOOL subsampling_x; BOOL subsampling_y; VP9_COLOR_SPACE color_space; int8_t y_dc_delta_q; int8_t uv_dc_delta_q; int8_t uv_ac_delta_q; int16_t y_dequant[QINDEX_RANGE][2]; int16_t uv_dequant[QINDEX_RANGE][2]; /* for loop filters */ int8_t ref_deltas[VP9_MAX_REF_LF_DELTAS]; int8_t mode_deltas[VP9_MAX_MODE_LF_DELTAS]; BOOL segmentation_abs_delta; Vp9SegmentationInfoData segmentation[VP9_MAX_SEGMENTS]; ReferenceSize reference[VP9_REF_FRAMES]; } Vp9ParserPrivate; void init_dequantizer(Vp9Parser* parser); static void init_vp9_parser(Vp9Parser* parser, Vp9FrameHdr* const frame_hdr) { Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; memset(parser, 0, sizeof(Vp9Parser)); memset(priv, 0, sizeof(Vp9ParserPrivate)); parser->priv = priv; parser->bit_depth = frame_hdr->bit_depth; init_dequantizer(parser); } Vp9Parser* vp9_parser_new() { Vp9Parser* parser = (Vp9Parser*)malloc(sizeof(Vp9Parser)); if (!parser) return NULL; Vp9ParserPrivate* priv = (Vp9ParserPrivate*)malloc(sizeof(Vp9ParserPrivate)); if (!priv) { free(parser); return NULL; } parser->priv = priv; return parser; } void vp9_parser_free(Vp9Parser* parser) { if (parser) { if (parser->priv) free(parser->priv); free(parser); } } #define vp9_read_bit(br) br->read(1) #define vp9_read_bits(br, bits) br->read(bits) static int32_t vp9_read_signed_bits(BitReader* br, int bits) { assert(bits < 32); const int32_t value = vp9_read_bits(br, bits); return vp9_read_bit(br) ? -value : value; } static BOOL verify_frame_marker(BitReader* br) { #define VP9_FRAME_MARKER 2 uint8_t frame_marker = vp9_read_bits(br, 2); if (frame_marker != VP9_FRAME_MARKER) return FALSE; return TRUE; } static BOOL verify_sync_code(BitReader* const br) { #define VP9_SYNC_CODE_0 0x49 #define VP9_SYNC_CODE_1 0x83 #define VP9_SYNC_CODE_2 0x42 return vp9_read_bits(br, 8) == VP9_SYNC_CODE_0 && vp9_read_bits(br, 8) == VP9_SYNC_CODE_1 && vp9_read_bits(br, 8) == VP9_SYNC_CODE_2; } static VP9_PROFILE read_profile(BitReader* br) { uint8_t profile = vp9_read_bit(br); profile |= vp9_read_bit(br) << 1; if (profile > 2) profile += vp9_read_bit(br); return (VP9_PROFILE)profile; } static void read_frame_size(BitReader* br, uint32_t* width, uint32_t* height) { const uint32_t w = vp9_read_bits(br, 16) + 1; const uint32_t h = vp9_read_bits(br, 16) + 1; *width = w; *height = h; } static void read_display_frame_size(Vp9FrameHdr* frame_hdr, BitReader* br) { frame_hdr->display_size_enabled = vp9_read_bit(br); if (frame_hdr->display_size_enabled) { read_frame_size(br, &frame_hdr->display_width, &frame_hdr->display_height); } } static void read_frame_size_from_refs(const Vp9Parser* parser, Vp9FrameHdr* frame_hdr, BitReader* br) { BOOL found = FALSE; int i; const Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; for (i = 0; i < VP9_REFS_PER_FRAME; i++) { found = vp9_read_bit(br); if (found) { uint8_t idx = frame_hdr->ref_frame_indices[i]; frame_hdr->size_from_ref[i] = TRUE; frame_hdr->width = priv->reference[idx].width; frame_hdr->height = priv->reference[idx].height; break; } } if (!found) { read_frame_size(br, &frame_hdr->width, &frame_hdr->height); } } static VP9_INTERP_FILTER read_interp_filter(BitReader* br) { const VP9_INTERP_FILTER filter_map[] = { VP9_EIGHTTAP_SMOOTH, VP9_EIGHTTAP, VP9_EIGHTTAP_SHARP, VP9_BILINEAR }; return vp9_read_bit(br) ? VP9_SWITCHABLE : filter_map[vp9_read_bits(br, 2)]; } static void read_loopfilter(Vp9LoopFilter* lf, BitReader* br) { lf->filter_level = vp9_read_bits(br, 6); lf->sharpness_level = vp9_read_bits(br, 3); lf->mode_ref_delta_update = 0; lf->mode_ref_delta_enabled = vp9_read_bit(br); if (lf->mode_ref_delta_enabled) { lf->mode_ref_delta_update = vp9_read_bit(br); if (lf->mode_ref_delta_update) { int i; for (i = 0; i < VP9_MAX_REF_LF_DELTAS; i++) { lf->update_ref_deltas[i] = vp9_read_bit(br); if (lf->update_ref_deltas[i]) lf->ref_deltas[i] = vp9_read_signed_bits(br, 6); } for (i = 0; i < VP9_MAX_MODE_LF_DELTAS; i++) { lf->update_mode_deltas[i] = vp9_read_bit(br); if (lf->update_mode_deltas[i]) lf->mode_deltas[i] = vp9_read_signed_bits(br, 6); } } } } static int8_t read_delta_q(BitReader* br) { return vp9_read_bit(br) ? vp9_read_signed_bits(br, 4) : 0; } static void read_quantization(Vp9FrameHdr* frame_hdr, BitReader* br) { frame_hdr->base_qindex = vp9_read_bits(br, QINDEX_BITS); frame_hdr->y_dc_delta_q = read_delta_q(br); frame_hdr->uv_dc_delta_q = read_delta_q(br); frame_hdr->uv_ac_delta_q = read_delta_q(br); } static void read_segmentation(Vp9SegmentationInfo* seg, BitReader* br) { int i; seg->update_map = FALSE; seg->update_data = FALSE; seg->enabled = vp9_read_bit(br); if (!seg->enabled) return; seg->update_map = vp9_read_bit(br); if (seg->update_map) { for (i = 0; i < VP9_SEG_TREE_PROBS; i++) { seg->update_tree_probs[i] = vp9_read_bit(br); seg->tree_probs[i] = seg->update_tree_probs[i] ? vp9_read_bits(br, 8) : MAX_PROB; } seg->temporal_update = vp9_read_bit(br); if (seg->temporal_update) { for (i = 0; i < VP9_PREDICTION_PROBS; i++) { seg->update_pred_probs[i] = vp9_read_bit(br); seg->pred_probs[i] = seg->update_pred_probs[i] ? vp9_read_bits(br, 8) : MAX_PROB; } } else { for (i = 0; i < VP9_PREDICTION_PROBS; i++) { seg->pred_probs[i] = MAX_PROB; } } } seg->update_data = vp9_read_bit(br); if (seg->update_data) { /* clear all features */ memset(seg->data, 0, sizeof(seg->data)); seg->abs_delta = vp9_read_bit(br); for (i = 0; i < VP9_MAX_SEGMENTS; i++) { Vp9SegmentationInfoData* seg_data = seg->data + i; uint8_t data; /* SEG_LVL_ALT_Q */ seg_data->alternate_quantizer_enabled = vp9_read_bit(br); if (seg_data->alternate_quantizer_enabled) { data = vp9_read_bits(br, 8); seg_data->alternate_quantizer = vp9_read_bit(br) ? -data : data; } /* SEG_LVL_ALT_LF */ seg_data->alternate_loop_filter_enabled = vp9_read_bit(br); if (seg_data->alternate_loop_filter_enabled) { data = vp9_read_bits(br, 6); seg_data->alternate_loop_filter = vp9_read_bit(br) ? -data : data; } /* SEG_LVL_REF_FRAME */ seg_data->reference_frame_enabled = vp9_read_bit(br); if (seg_data->reference_frame_enabled) { seg_data->reference_frame = vp9_read_bits(br, 2); } seg_data->reference_skip = vp9_read_bit(br); } } } #define MIN_TILE_WIDTH_B64 4 #define MAX_TILE_WIDTH_B64 64 uint32_t get_max_lb_tile_cols(uint32_t sb_cols) { int log2 = 0; while ((sb_cols >> log2) >= MIN_TILE_WIDTH_B64) ++log2; if (log2) log2--; return log2; } uint32_t get_min_lb_tile_cols(uint32_t sb_cols) { uint32_t log2 = 0; while ((uint64_t)(MAX_TILE_WIDTH_B64 << log2) < sb_cols) ++log2; return log2; } /* align to 64, follow specification 6.2.6 Compute image size syntax */ #define SB_ALIGN(w) (((w) + 63) >> 6) static BOOL read_tile_info(Vp9FrameHdr* frame_hdr, BitReader* br) { const uint32_t sb_cols = SB_ALIGN(frame_hdr->width); uint32_t min_lb_tile_cols = get_min_lb_tile_cols(sb_cols); uint32_t max_lb_tile_cols = get_max_lb_tile_cols(sb_cols); uint32_t max_ones = max_lb_tile_cols - min_lb_tile_cols; /* columns */ frame_hdr->log2_tile_columns = min_lb_tile_cols; while (max_ones-- && vp9_read_bit(br)) frame_hdr->log2_tile_columns++; /* row */ frame_hdr->log2_tile_rows = vp9_read_bit(br); if (frame_hdr->log2_tile_rows) frame_hdr->log2_tile_rows += vp9_read_bit(br); return TRUE; } static void loop_filter_update(Vp9Parser* parser, const Vp9LoopFilter* lf) { Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; int i; for (i = 0; i < VP9_MAX_REF_LF_DELTAS; i++) { if (lf->update_ref_deltas[i]) priv->ref_deltas[i] = lf->ref_deltas[i]; } for (i = 0; i < VP9_MAX_MODE_LF_DELTAS; i++) { if (lf->update_mode_deltas[i]) priv->mode_deltas[i] = lf->mode_deltas[i]; } } BOOL compare_and_set(int8_t* dest, const int8_t src) { const int8_t old = *dest; *dest = src; return old != src; } void init_dequantizer(Vp9Parser* parser) { Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; int q; for (q = 0; q < QINDEX_RANGE; q++) { priv->y_dequant[q][0] = vp9_dc_quant(parser->bit_depth, q, priv->y_dc_delta_q); priv->y_dequant[q][1] = vp9_ac_quant(parser->bit_depth, q, 0); priv->uv_dequant[q][0] = vp9_dc_quant(parser->bit_depth, q, priv->uv_dc_delta_q); priv->uv_dequant[q][1] = vp9_ac_quant(parser->bit_depth, q, priv->uv_ac_delta_q); } } static void quantization_update(Vp9Parser* parser, const Vp9FrameHdr* frame_hdr) { BOOL update = FALSE; Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; update |= compare_and_set(&priv->y_dc_delta_q, frame_hdr->y_dc_delta_q); update |= compare_and_set(&priv->uv_dc_delta_q, frame_hdr->uv_dc_delta_q); update |= compare_and_set(&priv->uv_ac_delta_q, frame_hdr->uv_ac_delta_q); if (update) { init_dequantizer(parser); } parser->lossless_flag = frame_hdr->base_qindex == 0 && frame_hdr->y_dc_delta_q == 0 && frame_hdr->uv_dc_delta_q == 0 && frame_hdr->uv_ac_delta_q == 0; } uint8_t seg_get_base_qindex(const Vp9Parser* parser, const Vp9FrameHdr* frame_hdr, int segid) { int seg_base = frame_hdr->base_qindex; Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; const Vp9SegmentationInfoData* seg = priv->segmentation + segid; /* DEBUG("id = %d, seg_base = %d, seg enable = %d, alt eanble = %d, abs = %d, alt= %d\n",segid, seg_base, frame_hdr->segmentation.enabled, seg->alternate_quantizer_enabled, priv->segmentation_abs_delta, seg->alternate_quantizer); */ if (frame_hdr->segmentation.enabled && seg->alternate_quantizer_enabled) { if (priv->segmentation_abs_delta) seg_base = seg->alternate_quantizer; else seg_base += seg->alternate_quantizer; } return clamp(seg_base, 0, MAXQ); } uint8_t seg_get_filter_level(const Vp9Parser* parser, const Vp9FrameHdr* frame_hdr, int segid) { int seg_filter = frame_hdr->loopfilter.filter_level; Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; const Vp9SegmentationInfoData* seg = priv->segmentation + segid; if (frame_hdr->segmentation.enabled && seg->alternate_loop_filter_enabled) { if (priv->segmentation_abs_delta) seg_filter = seg->alternate_loop_filter; else seg_filter += seg->alternate_loop_filter; } return clamp(seg_filter, 0, MAX_LOOP_FILTER); } /*save segmentation info from frame header to parser*/ static void segmentation_save(Vp9Parser* parser, const Vp9FrameHdr* frame_hdr) { const Vp9SegmentationInfo* info = &frame_hdr->segmentation; if (!info->enabled) return; if (info->update_map) { ASSERT(sizeof(parser->mb_segment_tree_probs) == sizeof(info->tree_probs)); ASSERT(sizeof(parser->segment_pred_probs) == sizeof(info->pred_probs)); memcpy(parser->mb_segment_tree_probs, info->tree_probs, sizeof(info->tree_probs)); memcpy(parser->segment_pred_probs, info->pred_probs, sizeof(info->pred_probs)); } if (info->update_data) { Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; priv->segmentation_abs_delta = info->abs_delta; ASSERT(sizeof(priv->segmentation) == sizeof(info->data)); memcpy(priv->segmentation, info->data, sizeof(info->data)); } } static void segmentation_update(Vp9Parser* parser, const Vp9FrameHdr* frame_hdr) { int i = 0; const Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; const Vp9LoopFilter* lf = &frame_hdr->loopfilter; int default_filter = lf->filter_level; const int scale = 1 << (default_filter >> 5); segmentation_save(parser, frame_hdr); for (i = 0; i < VP9_MAX_SEGMENTS; i++) { uint8_t q = seg_get_base_qindex(parser, frame_hdr, i); Vp9Segmentation* seg = parser->segmentation + i; const Vp9SegmentationInfoData* info = priv->segmentation + i; seg->luma_dc_quant_scale = priv->y_dequant[q][0]; seg->luma_ac_quant_scale = priv->y_dequant[q][1]; seg->chroma_dc_quant_scale = priv->uv_dequant[q][0]; seg->chroma_ac_quant_scale = priv->uv_dequant[q][1]; if (lf->filter_level) { uint8_t filter = seg_get_filter_level(parser, frame_hdr, i); if (!lf->mode_ref_delta_enabled) { memset(seg->filter_level, filter, sizeof(seg->filter_level)); } else { int ref, mode; const int intra_filter = filter + priv->ref_deltas[VP9_INTRA_FRAME] * scale; seg->filter_level[VP9_INTRA_FRAME][0] = clamp(intra_filter, 0, MAX_LOOP_FILTER); for (ref = VP9_LAST_FRAME; ref < VP9_MAX_REF_FRAMES; ++ref) { for (mode = 0; mode < VP9_MAX_MODE_LF_DELTAS; ++mode) { const int inter_filter = filter + priv->ref_deltas[ref] * scale + priv->mode_deltas[mode] * scale; seg->filter_level[ref][mode] = clamp(inter_filter, 0, MAX_LOOP_FILTER); } } } } seg->reference_frame_enabled = info->reference_frame_enabled; ; seg->reference_frame = info->reference_frame; seg->reference_skip = info->reference_skip; } } static void reference_update(Vp9Parser* parser, const Vp9FrameHdr* const frame_hdr) { uint8_t flag = 1; uint8_t refresh_frame_flags; int i; Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; ReferenceSize* reference = priv->reference; if (frame_hdr->frame_type == VP9_KEY_FRAME) { refresh_frame_flags = 0xff; } else { refresh_frame_flags = frame_hdr->refresh_frame_flags; } for (i = 0; i < VP9_REF_FRAMES; i++) { if (refresh_frame_flags & flag) { reference[i].width = frame_hdr->width; reference[i].height = frame_hdr->height; } flag <<= 1; } } static inline int key_or_intra_only(const Vp9FrameHdr* frame_hdr) { return frame_hdr->frame_type == VP9_KEY_FRAME || frame_hdr->intra_only; } static void set_default_lf_deltas(Vp9Parser* parser) { Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; priv->ref_deltas[VP9_INTRA_FRAME] = 1; priv->ref_deltas[VP9_LAST_FRAME] = 0; priv->ref_deltas[VP9_GOLDEN_FRAME] = -1; priv->ref_deltas[VP9_ALTREF_FRAME] = -1; priv->mode_deltas[0] = 0; priv->mode_deltas[1] = 0; } static void set_default_segmentation_info(Vp9Parser* parser) { Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; memset(priv->segmentation, 0, sizeof(priv->segmentation)); priv->segmentation_abs_delta = FALSE; } static void setup_past_independence(Vp9Parser* parser, Vp9FrameHdr* const frame_hdr) { set_default_lf_deltas(parser); set_default_segmentation_info(parser); memset(frame_hdr->ref_frame_sign_bias, 0, sizeof(frame_hdr->ref_frame_sign_bias)); } static void color_config_update(Vp9Parser* parser, Vp9FrameHdr* const frame_hdr) { Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; priv->color_space = frame_hdr->color_space; priv->subsampling_x = frame_hdr->subsampling_x; priv->subsampling_y = frame_hdr->subsampling_y; } static Vp9ParseResult vp9_parser_update(Vp9Parser* parser, Vp9FrameHdr* const frame_hdr) { if (key_or_intra_only(frame_hdr) || frame_hdr->error_resilient_mode) { setup_past_independence(parser, frame_hdr); } color_config_update(parser, frame_hdr); loop_filter_update(parser, &frame_hdr->loopfilter); quantization_update(parser, frame_hdr); segmentation_update(parser, frame_hdr); reference_update(parser, frame_hdr); return VP9_PARSER_OK; } static Vp9ParseResult vp9_color_config(Vp9Parser* parser, Vp9FrameHdr* frame_hdr, BitReader* br) { if (frame_hdr->profile >= VP9_PROFILE_2) { frame_hdr->bit_depth = vp9_read_bit(br) ? VP9_BITS_12 : VP9_BITS_10; if (VP9_BITS_12 == frame_hdr->bit_depth) { ERROR("vp9 12 bits-depth is unsupported by now!"); return VP9_PARSER_UNSUPPORTED; } } else { frame_hdr->bit_depth = VP9_BITS_8; } frame_hdr->color_space = (VP9_COLOR_SPACE)vp9_read_bits(br, 3); if (frame_hdr->color_space != VP9_SRGB) { vp9_read_bit(br); //color_range if (frame_hdr->profile == VP9_PROFILE_1 || frame_hdr->profile == VP9_PROFILE_3) { frame_hdr->subsampling_x = vp9_read_bit(br); frame_hdr->subsampling_y = vp9_read_bit(br); if (vp9_read_bit(br)) { //reserved_zero ERROR("reserved bit"); return VP9_PARSER_ERROR; } } else { frame_hdr->subsampling_y = frame_hdr->subsampling_x = 1; } } else { ERROR("do not support SRGB"); return VP9_PARSER_UNSUPPORTED; } return VP9_PARSER_OK; } Vp9ParseResult vp9_parse_frame_header(Vp9Parser* parser, Vp9FrameHdr* frame_hdr, const uint8_t* data, uint32_t size) { #define FRAME_CONTEXTS_BITS 2 Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv; BitReader bit_reader(data, size); BitReader* br = &bit_reader; memset(frame_hdr, 0, sizeof(*frame_hdr)); /* Uncompressed Data Chunk */ if (!verify_frame_marker(br)) goto error; frame_hdr->profile = read_profile(br); if (frame_hdr->profile > MAX_VP9_PROFILES) goto error; frame_hdr->show_existing_frame = vp9_read_bit(br); if (frame_hdr->show_existing_frame) { frame_hdr->frame_to_show = vp9_read_bits(br, VP9_REF_FRAMES_LOG2); return VP9_PARSER_OK; } frame_hdr->frame_type = (VP9_FRAME_TYPE)vp9_read_bit(br); frame_hdr->show_frame = vp9_read_bit(br); frame_hdr->error_resilient_mode = vp9_read_bit(br); if (frame_hdr->frame_type == VP9_KEY_FRAME) { if (!verify_sync_code(br)) goto error; if (vp9_color_config(parser, frame_hdr, br) != VP9_PARSER_OK) goto error; init_vp9_parser(parser, frame_hdr); read_frame_size(br, &frame_hdr->width, &frame_hdr->height); read_display_frame_size(frame_hdr, br); } else { frame_hdr->intra_only = frame_hdr->show_frame ? 0 : vp9_read_bit(br); frame_hdr->reset_frame_context = frame_hdr->error_resilient_mode ? 0 : vp9_read_bits(br, 2); if (frame_hdr->intra_only) { if (!verify_sync_code(br)) goto error; if (frame_hdr->profile > VP9_PROFILE_0) { if (vp9_color_config(parser, frame_hdr, br) != VP9_PARSER_OK) goto error; } else { frame_hdr->color_space = VP9_BT_601; frame_hdr->subsampling_y = frame_hdr->subsampling_x = 1; frame_hdr->bit_depth = VP9_BITS_8; } if (frame_hdr->bit_depth != parser->bit_depth) { parser->bit_depth = frame_hdr->bit_depth; init_dequantizer(parser); } frame_hdr->refresh_frame_flags = vp9_read_bits(br, VP9_REF_FRAMES); read_frame_size(br, &frame_hdr->width, &frame_hdr->height); read_display_frame_size(frame_hdr, br); } else { int i; //copy color config frame_hdr->color_space = priv->color_space; frame_hdr->subsampling_x = priv->subsampling_x; frame_hdr->subsampling_y = priv->subsampling_y; frame_hdr->refresh_frame_flags = vp9_read_bits(br, VP9_REF_FRAMES); for (i = 0; i < VP9_REFS_PER_FRAME; i++) { frame_hdr->ref_frame_indices[i] = vp9_read_bits(br, VP9_REF_FRAMES_LOG2); frame_hdr->ref_frame_sign_bias[i] = vp9_read_bit(br); } read_frame_size_from_refs(parser, frame_hdr, br); read_display_frame_size(frame_hdr, br); frame_hdr->allow_high_precision_mv = vp9_read_bit(br); frame_hdr->mcomp_filter_type = read_interp_filter(br); } } if (!frame_hdr->error_resilient_mode) { frame_hdr->refresh_frame_context = vp9_read_bit(br); frame_hdr->frame_parallel_decoding_mode = vp9_read_bit(br); } else { frame_hdr->frame_parallel_decoding_mode = TRUE; } frame_hdr->frame_context_idx = vp9_read_bits(br, FRAME_CONTEXTS_BITS); read_loopfilter(&frame_hdr->loopfilter, br); read_quantization(frame_hdr, br); read_segmentation(&frame_hdr->segmentation, br); if (!read_tile_info(frame_hdr, br)) goto error; frame_hdr->first_partition_size = vp9_read_bits(br, 16); if (!frame_hdr->first_partition_size) goto error; frame_hdr->frame_header_length_in_bytes = (br->getPos() + 7) / 8; return vp9_parser_update(parser, frame_hdr); error: return VP9_PARSER_ERROR; }
34.17768
154
0.653792
genisysram
d89c9b95521a33dca025ff45cb1e46b31018c3f0
2,137
cc
C++
design-pattern/creational/factory_method.cc
curoky/my-own-x
825273af2d73dff76562422ca87a077635ee870b
[ "Apache-2.0" ]
null
null
null
design-pattern/creational/factory_method.cc
curoky/my-own-x
825273af2d73dff76562422ca87a077635ee870b
[ "Apache-2.0" ]
null
null
null
design-pattern/creational/factory_method.cc
curoky/my-own-x
825273af2d73dff76562422ca87a077635ee870b
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2018-2022 curoky(cccuroky@gmail.com). * * This file is part of my-own-x. * See https://github.com/curoky/my-own-x for further info. * * 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 <catch2/catch.hpp> // for SourceLineInfo, StringRef, TEST_CASE #include <iostream> // for operator<<, endl, basic_ostream, cout, ostream namespace { class Interviewer { public: virtual void ask_questions() = 0; virtual ~Interviewer() = default; }; class Developer : public Interviewer { public: void ask_questions() override { std::cout << "Asking about design patterns!" << std::endl; } }; class CommunityExecutive : public Interviewer { public: void ask_questions() override { std::cout << "Asking about community building" << std::endl; } }; class HiringManager { public: void takeInterview() { auto iv = make_interviewer(); iv->ask_questions(); delete iv; } virtual ~HiringManager() = default; private: virtual Interviewer* make_interviewer() = 0; }; class DevelopmentManager : public HiringManager { public: Interviewer* make_interviewer() override { return new Developer(); } }; class MarketingManager : public HiringManager { public: Interviewer* make_interviewer() override { return new CommunityExecutive(); } }; } // namespace TEST_CASE("", "[FactoryMethod]") { auto dev_manager = new DevelopmentManager(); dev_manager->takeInterview(); // Output: Asking about design patterns auto mk_manager = new MarketingManager(); mk_manager->takeInterview(); // Output: Asking about community building. delete dev_manager; delete mk_manager; }
28.493333
96
0.718297
curoky
d89f410ee574765481e3a36294c4bdb915b9e62a
2,261
cpp
C++
main.cpp
paramsingh/gameboy
b6e57d14e975975fb1cdb85634682918c54cdb43
[ "MIT" ]
31
2016-08-31T10:19:06.000Z
2022-01-11T00:04:21.000Z
main.cpp
paramsingh/gameboy
b6e57d14e975975fb1cdb85634682918c54cdb43
[ "MIT" ]
null
null
null
main.cpp
paramsingh/gameboy
b6e57d14e975975fb1cdb85634682918c54cdb43
[ "MIT" ]
18
2016-08-19T07:21:44.000Z
2022-03-19T14:35:45.000Z
#include <bits/stdc++.h> #include <SDL2/SDL.h> using namespace std; #include "cpu/cpu.hpp" #include "cpu/cpu.cpp" #include "ops/ops.hpp" #include "ops/ops.cpp" #include "gui/gui.hpp" #include "gui/gui.cpp" #include "gpu/gpu.hpp" #include "gpu/gpu.cpp" const int fps = 60; const int ticks_per_frame = 1000 / 60; // TODO: Get this stuff into a gameboy class maybe cpu c; gui screen; gpu g(&c, &screen); int flag = 0; inline void execute_instruction() { int extended = 0; uint16_t opcode = c.read(c.pc); if (flag == 1) { printf("opcode = %02x, pc = %04x\n", opcode, c.pc); } // if opcode is 0xcb then we have to execute the next byte // from the extended instruction set if (opcode == 0xcb) { extended = 1; opcode = c.read(c.pc + 1) + 0xff; c.pc += 1; } int executed = inst_set[opcode].func(&c); if (executed == 0) { if (extended) printf("extended instruction\n"); c.status(); exit(0); } else if (executed == 1) { c.pc += inst_set[opcode].size; //if (opcode == 0xf3) //printf("size = %d\n", inst_set[opcode].size); } c.time += c.t; if (c.pc == 0x0463) { //flag = 1; } if (flag == 1) { printf("%04x %02x %s\n", c.pc, opcode,inst_set[opcode].name.c_str()); c.status(); getchar(); } } int fc = 0; void emulate() { //int max_cycles = 69905; // frequency of gameboy / 60 int cycles = 0; execute_instruction(); if (c.pending_enable == 1 && c.read(c.pc - 1) != 0xfb) { c.interrupts_enabled = 1; c.pending_enable = 0; } if (c.pending_disable == 1 && c.read(c.pc - 1) != 0xf3) { c.interrupts_enabled = 0; c.pending_disable = 0; } g.step(); c.update_timers(); c.do_interrupts(); cycles += c.t; fc++; //printf("fc = %d\n", fc); } int main() { screen.init(); int quit = 0; SDL_Event e; //LTimer fps; while (!quit) { while(SDL_PollEvent(&e) != 0) { //User requests quit if(e.type == SDL_QUIT) { quit = 1; } } emulate(); } return 0; }
21.330189
77
0.513047
paramsingh
d8a38e5258811eb165bc3e3898308603f0c05dfd
174
cpp
C++
node2/src/init.cpp
eirikeve/ttk4155-byggern
07f33b70ed5e02214705f81d2537371b538716eb
[ "MIT" ]
null
null
null
node2/src/init.cpp
eirikeve/ttk4155-byggern
07f33b70ed5e02214705f81d2537371b538716eb
[ "MIT" ]
null
null
null
node2/src/init.cpp
eirikeve/ttk4155-byggern
07f33b70ed5e02214705f81d2537371b538716eb
[ "MIT" ]
null
null
null
#include "../include/init.h" // void init() { // init_timer(); // init_uart(); // can_init(); // ADC_internal& adc_internal = ADC_internal::getInstance(); // }
19.333333
64
0.58046
eirikeve
d8a4014bf20f395ce43b7168392b63d604bc2586
346
cpp
C++
C++/sum-of-digits-in-the-minimum-number.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/sum-of-digits-in-the-minimum-number.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/sum-of-digits-in-the-minimum-number.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(n * l), l is the max length of numbers // Space: O(l) class Solution { public: int sumOfDigits(vector<int>& A) { int min_num = *min_element(A.begin(),A.end()); int total = 0; while (min_num) { total += min_num % 10; min_num /= 10; } return total % 2 == 0; } };
21.625
54
0.488439
jaiskid
d8ad75d32fe936031a6c65bbb6bc7d6318b204cc
4,244
cpp
C++
src/platform/lpc17xx/power.cpp
wangyanjunmsn/vi-firmware
a5940ab6c773457d4c41e80273ae0ce327164d60
[ "BSD-3-Clause" ]
148
2015-01-01T18:32:25.000Z
2022-03-05T12:02:24.000Z
src/platform/lpc17xx/power.cpp
wangyanjunmsn/vi-firmware
a5940ab6c773457d4c41e80273ae0ce327164d60
[ "BSD-3-Clause" ]
109
2015-02-11T16:33:49.000Z
2021-01-04T16:14:00.000Z
src/platform/lpc17xx/power.cpp
wangyanjunmsn/vi-firmware
a5940ab6c773457d4c41e80273ae0ce327164d60
[ "BSD-3-Clause" ]
89
2015-02-04T00:39:29.000Z
2021-10-03T00:01:17.000Z
#include "power.h" #include "util/log.h" #include "gpio.h" #include "lpc17xx_pinsel.h" #include "lpc17xx_clkpwr.h" #include "lpc17xx_wdt.h" #define POWER_CONTROL_PORT 2 #define POWER_CONTROL_PIN 13 #define PROGRAM_BUTTON_PORT 2 #define PROGRAM_BUTTON_PIN 12 namespace gpio = openxc::gpio; using openxc::gpio::GPIO_VALUE_HIGH; using openxc::gpio::GPIO_VALUE_LOW; using openxc::gpio::GPIO_DIRECTION_OUTPUT; using openxc::util::log::debug; const uint32_t DISABLED_PERIPHERALS[] = { CLKPWR_PCONP_PCTIM0, CLKPWR_PCONP_PCTIM1, CLKPWR_PCONP_PCSPI, CLKPWR_PCONP_PCI2C0, CLKPWR_PCONP_PCRTC, CLKPWR_PCONP_PCSSP1, CLKPWR_PCONP_PCI2C1, CLKPWR_PCONP_PCSSP0, CLKPWR_PCONP_PCI2C2, }; void setPowerPassthroughStatus(bool enabled) { int pinStatus; debug("Switching 12v power passthrough "); if(enabled) { debug("on"); pinStatus = 0; } else { debug("off"); pinStatus = 1; } gpio::setValue(POWER_CONTROL_PORT, POWER_CONTROL_PIN, pinStatus ? GPIO_VALUE_HIGH : GPIO_VALUE_LOW); } void openxc::power::initialize() { // Configure 12v passthrough control as a digital output PINSEL_CFG_Type powerPassthroughPinConfig; powerPassthroughPinConfig.OpenDrain = 0; powerPassthroughPinConfig.Pinmode = 1; powerPassthroughPinConfig.Funcnum = 0; powerPassthroughPinConfig.Portnum = POWER_CONTROL_PORT; powerPassthroughPinConfig.Pinnum = POWER_CONTROL_PIN; PINSEL_ConfigPin(&powerPassthroughPinConfig); gpio::setDirection(POWER_CONTROL_PORT, POWER_CONTROL_PIN, GPIO_DIRECTION_OUTPUT); setPowerPassthroughStatus(true); debug("Turning off unused peripherals"); for(unsigned int i = 0; i < sizeof(DISABLED_PERIPHERALS) / sizeof(DISABLED_PERIPHERALS[0]); i++) { CLKPWR_ConfigPPWR(DISABLED_PERIPHERALS[i], DISABLE); } PINSEL_CFG_Type programButtonPinConfig; programButtonPinConfig.OpenDrain = 0; programButtonPinConfig.Pinmode = 1; programButtonPinConfig.Funcnum = 1; programButtonPinConfig.Portnum = PROGRAM_BUTTON_PORT; programButtonPinConfig.Pinnum = PROGRAM_BUTTON_PIN; PINSEL_ConfigPin(&programButtonPinConfig); } void openxc::power::handleWake() { // This isn't especially graceful, we just reset the device after a // wakeup. Then again, it makes the code a hell of a lot simpler because we // only have to worry about initialization of core peripherals in one spot, // setup() in vi_firmware.cpp and main.cpp. I'll leave this for now and we // can revisit it if there is some reason we need to keep state between CAN // wakeup events (e.g. fine_odometer_since_restart could be more persistant, // but then it actually might be more confusing since it'd be // fine_odometer_since_we_lost_power) NVIC_SystemReset(); } void openxc::power::suspend() { debug("Going to low power mode"); NVIC_EnableIRQ(CANActivity_IRQn); NVIC_EnableIRQ(EINT2_IRQn); setPowerPassthroughStatus(false); // Disable brown-out detection when we go into lower power LPC_SC->PCON |= (1 << 2); // TODO do we need to disable and disconnect the main PLL0 before ending // deep sleep, accoridn gto errata lpc1768-16.march2010? it's in some // example code from NXP. CLKPWR_DeepSleep(); } void openxc::power::enableWatchdogTimer(int microseconds) { WDT_Init(WDT_CLKSRC_IRC, WDT_MODE_RESET); WDT_Start(microseconds); } void openxc::power::disableWatchdogTimer() { // TODO this is nuts, but you can't change the WDMOD register until after // the WDT times out. But...we are using a RESET with the WDT, so the whole // board will reset and then we don't have any idea if the WDT should be // disabled or not! This makes it really difficult to use the WDT for both // normal runtime hard freeze protection and periodic wakeup from sleep (to // check if CAN is active via OBD-II). I have to disable the regular WDT for // now for this reason. LPC_WDT->WDMOD = 0x0; } void openxc::power::feedWatchdog() { WDT_Feed(); } extern "C" { void CANActivity_IRQHandler(void) { openxc::power::handleWake(); } void EINT2_IRQHandler(void) { openxc::power::handleWake(); } }
31.671642
85
0.723139
wangyanjunmsn
d8ad9b57ba96684e2d202bffd040cf4b8cd25d22
2,228
cpp
C++
src/time.cpp
kushaldalsania/haystack-cpp
95997ae2bca9ea096dc7e61c000291f3ac08d9d7
[ "AFL-3.0" ]
null
null
null
src/time.cpp
kushaldalsania/haystack-cpp
95997ae2bca9ea096dc7e61c000291f3ac08d9d7
[ "AFL-3.0" ]
null
null
null
src/time.cpp
kushaldalsania/haystack-cpp
95997ae2bca9ea096dc7e61c000291f3ac08d9d7
[ "AFL-3.0" ]
null
null
null
// // Copyright (c) 2015, J2 Innovations // Copyright (c) 2012 Brian Frank // Licensed under the Academic Free License version 3.0 // History: // 06 Jun 2011 Brian Frank Creation // 19 Aug 2014 Radu Racariu<radur@2inn.com> Ported to C++ // #include "time.hpp" #include <sstream> #include <ctime> //////////////////////////////////////////////// // Time //////////////////////////////////////////////// using namespace haystack; //////////////////////////////////////////////// // to zinc //////////////////////////////////////////////// // Encode as "hh:mm:ss.FFF" const std::string Time::to_zinc() const { std::stringstream os; if (hour < 10) os << '0'; os << hour << ':'; if (minutes < 10) os << '0'; os << minutes << ':'; if (sec < 10) os << '0'; os << sec; if (ms != 0) { os << '.'; if (ms < 10) os << '0'; if (ms < 100) os << '0'; os << ms; } return os.str(); } const Time& Time::MIDNIGHT = *new Time(0, 0, 0); //////////////////////////////////////////////// // Equal //////////////////////////////////////////////// bool Time::operator ==(const Time &other) const { return (hour == other.hour && minutes == other.minutes && sec == other.sec && ms == other.ms); } bool Time::operator==(const Val &other) const { if (type() != other.type()) return false; return *this == static_cast<const Time&>(other); } //////////////////////////////////////////////// // Comparators //////////////////////////////////////////////// bool Time::operator <(const Val &other) const { return type() == other.type() && compareTo(((Time&)other)) < 0; } bool Time::operator >(const Val &other) const { return type() == other.type() && compareTo(((Time&)other)) > 0; } Time::auto_ptr_t Time::clone() const { return auto_ptr_t(new Time(*this)); } int Time::compareTo(const Time &other) const { if (hour < other.hour) return -1; else if (hour > other.hour) return 1; if (minutes < other.minutes) return -1; else if (minutes > other.minutes) return 1; if (sec < other.sec) return -1; else if (sec > other.sec) return 1; if (ms < other.ms) return -1; else if (ms > other.ms) return 1; return 0; }
26.211765
98
0.480251
kushaldalsania
d8b3a99a7dacc8d1ee20bd5a58d8d53b7dd355e3
40,105
cpp
C++
geometrictools/utils/image_cpu.cpp
eth-sri/transformation-smoothing
12a653e881a6d61c5c63a3e16d58292435486cbd
[ "Apache-2.0" ]
3
2020-11-07T18:12:50.000Z
2021-06-11T22:56:09.000Z
geometrictools/utils/image_cpu.cpp
eth-sri/transformation-smoothing
12a653e881a6d61c5c63a3e16d58292435486cbd
[ "Apache-2.0" ]
null
null
null
geometrictools/utils/image_cpu.cpp
eth-sri/transformation-smoothing
12a653e881a6d61c5c63a3e16d58292435486cbd
[ "Apache-2.0" ]
null
null
null
#include "image.h" #include "image_cpu.h" #include "transforms/interpolation.h" #include "utils/utilities.h" using namespace std; Interval roundIntervalToInt(const Interval& i) { Interval in = i.meet({0, 1}); float inf = in.inf * 255.0f; int inf_lower = floorf(inf); if (inf_lower == roundf(inf)) { inf = pixelVals[inf_lower]; } else { inf = pixelVals[min(255, inf_lower + 1)]; } float sup = in.sup * 255.0f; int sup_lower = floorf(sup); if (sup_lower == roundf(sup)) { sup = pixelVals[sup_lower]; } else { sup = pixelVals[min(255, sup_lower + 1)]; } assert(inf <= sup); return {inf, sup}; } /*** constuctors and friends ***/ //empty ImageImpl::ImageImpl() {}; // from torch // ImageImpl(const torch::Tensor &img) { // assert(img.dim() == 3); // this->nRows = img.size(1); // this->nCols = img.size(2); // this->nChannels = img.size(0); // const size_t s = nRows * nCols * nChannels; // auto acc = img.accessor<float, 3>(); // this->a = new Interval[s]; // float _min = 0; // float _max = 0; // for(size_t i = 0; i < nRows; ++i) // for(size_t j = 0; j < nCols; ++j) // for(size_t k = 0; k < nChannels; ++k) // { // const size_t m = rcc_to_idx(i, j, k); // const float v = acc[k][i][j]; // a[m] = {v, v}; // _min = min(_min, v); // _max = max(_max, v); // } // cout << _min << " " << _max << endl; // } //from numpy ImageImpl::ImageImpl(PyArrayObject* np) { int dims = PyArray_NDIM(np); assert(dims == 2 || dims == 3); this->nRows = PyArray_DIM(np, 0); this->nCols = PyArray_DIM(np, 1); if (dims == 2) { this->nChannels = 1; } else { this->nChannels = PyArray_DIM(np, 2); } int image_typ = PyArray_TYPE(np); if (image_typ == NPY_UINT8) { const size_t s = nRows * nCols * nChannels; uint8_t* acc = (uint8_t*)PyArray_DATA(np); this->a = new Interval[s]; for(size_t i = 0; i < nRows; ++i) for(size_t j = 0; j < nCols; ++j) for(size_t k = 0; k < nChannels; ++k) { const uint8_t v = acc[i * nCols * nChannels + j * nChannels + k ]; const float vv = v / 255.0f; const size_t m = rcc_to_idx(i, j, k); a[m] = {vv, vv}; } } else if (image_typ == NPY_FLOAT32) { const size_t s = nRows * nCols * nChannels; float* acc = (float*)PyArray_DATA(np); this->a = new Interval[s]; for(size_t i = 0; i < nRows; ++i) for(size_t j = 0; j < nCols; ++j) for(size_t k = 0; k < nChannels; ++k) { const float v = acc[i * nCols * nChannels + j * nChannels + k ]; assert(v >= 0.0f); assert(v <= 255.0f); const size_t m = rcc_to_idx(i, j, k); a[m] = {v, v}; } } else { assert(false); } } //copy ImageImpl::ImageImpl(const ImageImpl &other) { this->nRows = other.nRows; this->nCols = other.nCols; this->nChannels = other.nChannels; const size_t s = nRows * nCols * nChannels; this->a = new Interval[s]; for(size_t i = 0; i < s; ++i) a[i] = other.a[i]; } //empty fixed size ImageImpl::ImageImpl(size_t nRows, size_t nCols, size_t nChannels) { this->nRows = nRows; this->nCols = nCols; this->nChannels = nChannels; this->a = new Interval[nRows * nCols * nChannels]; } // from string ImageImpl::ImageImpl(size_t nRows, size_t nCols, size_t nChannels, string line) { this->nRows = nRows; this->nCols = nCols; this->nChannels = nChannels; this->a = new Interval[nRows * nCols * nChannels]; string curr = ""; // Label of the image is the first digit size_t offset = 0; while (line[offset] != ',') { curr += line[offset++]; } // we currently don't need this // this->label = stoi(curr); curr = ""; // ImageImpl vector<Interval> its; for (size_t i = offset+1; i < line.size(); ++i) { if (line[i] == ',') { its.push_back({stof(curr), stof(curr)}); curr = ""; } else { curr += line[i]; } } its.push_back({stof(curr), stof(curr)}); assert((size_t)its.size() == nRows * nCols * nChannels); size_t nxt = 0; for (size_t r = 0; r < nRows; ++r) { for (size_t c = 0; c < nCols; ++c) { for (size_t i = 0; i < nChannels; ++i) { this->a[rcc_to_idx(r, c, i)] = its[nxt++]; } } } } // assignment ImageImpl& ImageImpl::operator = (const ImageImpl &other) { this->nRows = other.nRows; this->nCols = other.nCols; this->nChannels = other.nChannels; const size_t s = nRows * nCols * nChannels; // delete old pointer before changing to prevent memory leak if (this->a != 0) { delete[] this->a; this->a = 0; } this->a = new Interval[s]; for(size_t i = 0; i < s; ++i) a[i] = other.a[i]; return *this; } // destructor ImageImpl::~ImageImpl() { if (this->a != 0) { delete[] this->a; this->a = 0; } }; /*** other ***/ ImageImpl* ImageImpl::operator + (const ImageImpl& other) const { assert(nRows==other.nRows && nCols==other.nCols && nChannels==other.nChannels); ImageImpl* ret = new ImageImpl(nRows, nCols, nChannels); for (size_t k = 0; k < nChannels; ++k) { for (size_t i = 0; i < nRows; ++i) { for (size_t j = 0; j < nCols; ++j) { size_t m = rcc_to_idx(i, j, k); ret->a[m] = a[m] + other.a[m]; } } } return ret; } ImageImpl* ImageImpl::operator | (const ImageImpl& other) const { assert(nRows==other.nRows && nCols==other.nCols && nChannels==other.nChannels); ImageImpl* ret = new ImageImpl(nRows, nCols, nChannels); for (size_t k = 0; k < nChannels; ++k) { for (size_t i = 0; i < nRows; ++i) { for (size_t j = 0; j < nCols; ++j) { size_t m = rcc_to_idx(i, j, k); if (a[m].inf > 0 || other.a[m].inf > 0) ret->a[m] = {1, 1}; else ret->a[m] = {0, 0}; } } } return ret; } ImageImpl* ImageImpl::operator & (const ImageImpl& other) const { assert(nRows==other.nRows && nCols==other.nCols && nChannels==other.nChannels); ImageImpl* ret = new ImageImpl(nRows, nCols, nChannels); for (size_t k = 0; k < nChannels; ++k) { for (size_t i = 0; i < nRows; ++i) { for (size_t j = 0; j < nCols; ++j) { size_t m = rcc_to_idx(i, j, k); if (a[m].inf > 0 && other.a[m].inf > 0) ret->a[m] = {1, 1}; else ret->a[m] = {0, 0}; } } } return ret; } ImageImpl* ImageImpl::operator - (const ImageImpl& other) const { assert(nRows==other.nRows && nCols==other.nCols && nChannels==other.nChannels); ImageImpl *ret = new ImageImpl(nRows, nCols, nChannels); for (size_t k = 0; k < nChannels; ++k) { for (size_t i = 0; i < nRows; ++i) { for (size_t j = 0; j < nCols; ++j) { size_t m = rcc_to_idx(i, j, k); ret->a[m] = a[m] - other.a[m]; } } } return ret; } // Remark: works for even and odd image sizes Interval ImageImpl::valueAt(int x, int y, size_t i, Interval default_value) const { assert(unsigned(x % 2) != nCols % 2 && unsigned(y % 2) != nRows % 2 && "Off grid coordinates"); const int c = (x + (nCols - 1)) / 2; const int r = (y + (nRows - 1)) / 2; if (r < 0 || r >= signed(nRows) || c < 0 || c >= signed(nCols)) { return default_value; } size_t m = rcc_to_idx(r, c, i); assert(a != 0); return a[m]; } Interval ImageImpl::valueAt(int x, int y, size_t i) const { return valueAt(x, y, i, {0, 0}); } // Input: // 0 <= r <= nRows - 1 // 0 <= c <= nCols - 1 // Output: coordinates on the odd integer grid // // Remark: works for even and odd image sizes Coordinate<float> ImageImpl::getCoordinate(float r, float c, size_t channel) const { return {2 * c - (nCols - 1), 2 * r - (nRows - 1), channel}; } // Coordinate to rcc inex std::tuple<int, int> ImageImpl::getRc(float x, float y) const { int c = int(int(x + (nCols - 1)) / 2); int r = int(int(y + (nRows - 1)) / 2); return {r, c}; } float ImageImpl::l2norm() const { Interval sum_squared(0,0); for (size_t k = 0; k < nChannels; ++k) { for (size_t i = 0; i < nRows; ++i) { for (size_t j = 0; j < nCols; ++j) { size_t m = rcc_to_idx(i, j, k); sum_squared += a[m].square(); } } } return sqrt(sum_squared.sup); } std::tuple<float, float, float> ImageImpl::l2norm_channelwise() const { Interval sum_squared_0(0,0), sum_squared_1(0,0), sum_squared_2(0,0); for (size_t i = 0; i < nRows; ++i) { for (size_t j = 0; j < nCols; ++j) { sum_squared_0 += a[rcc_to_idx(i, j, 0)].square(); sum_squared_1 += a[rcc_to_idx(i, j, 1)].square(); sum_squared_2 += a[rcc_to_idx(i, j, 2)].square(); } } return {sqrt(sum_squared_0.sup), sqrt(sum_squared_1.sup), sqrt(sum_squared_2.sup)}; } float* ImageImpl::getFilter(float sigma, size_t filter_size) const { const size_t c = filter_size / 2; // use symmetry to only store 1 quarter of the filter float *G = new float[(c+1) * (c+1)]; getGaussianFilter(G, filter_size, sigma); return G; } void ImageImpl::delFilter(float *f) const { if (f != 0) delete[] f; } void ImageImpl::rect_vignetting(size_t filter_size) { for (size_t chan = 0; chan < nChannels; ++chan) { for (size_t i = 0; i < min(nRows, filter_size); ++i) { for (size_t j = 0; j < nCols; ++j) { size_t m = rcc_to_idx(i, j, chan); a[m] = {0, 0}; } } for (size_t i = max(nRows-filter_size, (size_t)0); i < nRows; ++i) { for (size_t j = 0; j < nCols; ++j) { size_t m = rcc_to_idx(i, j, chan); a[m] = {0, 0}; } } for (size_t i = 0; i < nRows; ++i) { for (size_t j = 0; j < min(nCols, filter_size); ++j) { size_t m = rcc_to_idx(i, j, chan); a[m] = {0, 0}; } for (size_t j = max(nRows-filter_size, (size_t)0); j < nCols; ++j) { size_t m = rcc_to_idx(i, j, chan); a[m] = {0, 0}; } } } } ImageImpl* ImageImpl::filter_vignetting(const float* filter, size_t filter_size, float radiusDecrease) const { assert(nRows == nCols); assert(filter_size % 2 == 1); // odd filter so we can correctly center it const size_t c = filter_size / 2; const bool do_radius = radiusDecrease >= 0; const bool do_filter = filter != 0; const float radius = do_radius ? min(nRows, nCols) - 1 - 2 * radiusDecrease : numeric_limits<float>::infinity(); const float radiusSq = radius*radius; ImageImpl *ret = new ImageImpl(nRows, nCols, nChannels); for (size_t chan = 0; chan < nChannels; ++chan) { for (size_t row = 0; row < nRows; ++row){ for (size_t col = 0; col < nCols; ++col) { const int x = 2 * col - (nCols - 1); const int y = 2 * row - (nRows - 1); //cout << do_filter << " " << x << " " << y << endl; if(x*x + y*y <= radiusSq) { if (do_filter) { Interval out = {0, 0}; for (int i = -c; i <= signed(c); ++i) for (int j = -c; j <= signed(c); ++j) { const int r_ = row + i; const int c_ = col + j; const int x_ = 2 * c_ - (nCols - 1); const int y_ = 2 * r_ - (nRows - 1); //cout << "a" << endl << flush; //cout << x_*x_ << " " << y_*y_ << " " << radiusSq << endl; if (r_ > 0 && r_ < signed(nRows) && c_ > 0 && c_ < signed(nCols) && (x_*x_ + y_*y_ <= radiusSq) ) { out += filter[abs(i) * (c+1) + abs(j)] * this->a[rcc_to_idx(r_, c_, chan)]; } } ret->a[rcc_to_idx(row, col, chan)] = out; } else { ret->a[rcc_to_idx(row, col, chan)] = a[rcc_to_idx(row, col, chan)]; } } else { ret->a[rcc_to_idx(row, col, chan)] = {0,0}; } //cout << rcc_to_idx(row, col, chan) << " " << ret->a[rcc_to_idx(row, col, chan)] << endl; } } } return ret; } void ImageImpl::saveBMP(string fn, bool inf) const { assert(nChannels == 1 || nChannels == 3); // based on https://stackoverflow.com/a/18675807 unsigned char file[14] = { 'B','M', // magic 0,0,0,0, // size in bytes 0,0, // app data 0,0, // app data 40+14,0,0,0 // start of data offset }; unsigned char info[40] = { 40,0,0,0, // info hd size 0,0,0,0, // width 0,0,0,0, // heigth 1,0, // number color planes 24,0, // bits per pixel 0,0,0,0, // compression is none 0,0,0,0, // image bits size 0x13,0x0B,0,0, // horz resoluition in pixel / m 0x13,0x0B,0,0, // vert resolutions (0x03C3 = 96 dpi, 0x0B13 = 72 dpi) 0,0,0,0, // #colors in pallete 0,0,0,0, // #important colors }; const size_t w = nCols; const size_t h = nRows; int padSize = (4-(w*3)%4)%4; int sizeData = w*h*3 + h*padSize; int sizeAll = sizeData + sizeof(file) + sizeof(info); file[ 2] = (unsigned char)( sizeAll ); file[ 3] = (unsigned char)( sizeAll>> 8); file[ 4] = (unsigned char)( sizeAll>>16); file[ 5] = (unsigned char)( sizeAll>>24); info[ 4] = (unsigned char)( w ); info[ 5] = (unsigned char)( w>> 8); info[ 6] = (unsigned char)( w>>16); info[ 7] = (unsigned char)( w>>24); info[ 8] = (unsigned char)( h ); info[ 9] = (unsigned char)( h>> 8); info[10] = (unsigned char)( h>>16); info[11] = (unsigned char)( h>>24); info[20] = (unsigned char)( sizeData ); info[21] = (unsigned char)( sizeData>> 8); info[22] = (unsigned char)( sizeData>>16); info[23] = (unsigned char)( sizeData>>24); ofstream stream; stream.open (fn); stream.write( (char*)file, sizeof(file) ); stream.write( (char*)info, sizeof(info) ); unsigned char pad[3] = {0,0,0}; for(size_t i = 0; i < h; i++) { size_t k = h-1-i; for(size_t j = 0; j < w; j++ ) { unsigned char pixel[3]; if (nChannels == 3) { if (inf) { assert( 0 <= a[rcc_to_idx(k, j, 0)].inf && a[rcc_to_idx(k, j, 0)].inf <= 1 ); assert( 0 <= a[rcc_to_idx(k, j, 1)].inf && a[rcc_to_idx(k, j, 1)].inf <= 1 ); assert( 0 <= a[rcc_to_idx(k, j, 2)].inf && a[rcc_to_idx(k, j, 2)].inf <= 1 ); pixel[2] = (unsigned char) round(a[rcc_to_idx(k, j, 0)].inf * 255); pixel[1] = (unsigned char) round(a[rcc_to_idx(k, j, 1)].inf * 255); pixel[0] = (unsigned char) round(a[rcc_to_idx(k, j, 2)].inf * 255); } else { assert( 0 <= a[rcc_to_idx(k, j, 0)].sup && a[rcc_to_idx(k, j, 0)].sup <= 1 ); assert( 0 <= a[rcc_to_idx(k, j, 1)].sup && a[rcc_to_idx(k, j, 1)].sup <= 1 ); assert( 0 <= a[rcc_to_idx(k, j, 2)].sup && a[rcc_to_idx(k, j, 2)].sup <= 1 ); pixel[2] = (unsigned char) round(a[rcc_to_idx(k, j, 0)].sup * 255); pixel[1] = (unsigned char) round(a[rcc_to_idx(k, j, 1)].sup * 255); pixel[0] = (unsigned char) round(a[rcc_to_idx(k, j, 2)].sup * 255); } } else { size_t m = rcc_to_idx(k, j, 0); if (inf) { if (!(0 <= a[rcc_to_idx(k, j, 0)].inf && a[rcc_to_idx(k, j, 0)].inf <= 1)) { cout << k << " " << j << " " << a[rcc_to_idx(k, j, 0)].inf << endl; } assert( 0 <= a[rcc_to_idx(k, j, 0)].inf && a[rcc_to_idx(k, j, 0)].inf <= 1 ); pixel[2] = (unsigned char) round(a[m].inf * 255); pixel[1] = (unsigned char) round(a[m].inf * 255); pixel[0] = (unsigned char) round(a[m].inf * 255); } else { if (!(0 <= a[rcc_to_idx(k, j, 0)].sup && a[rcc_to_idx(k, j, 0)].sup <= 1)) { cout << k << " " << j << " " << a[rcc_to_idx(k, j, 0)].sup << endl; } assert( 0 <= a[rcc_to_idx(k, j, 0)].sup && a[rcc_to_idx(k, j, 0)].sup <= 1 ); pixel[2] = (unsigned char) round(a[m].sup * 255); pixel[1] = (unsigned char) round(a[m].sup * 255); pixel[0] = (unsigned char) round(a[m].sup * 255); } } stream.write((char*)pixel, 3); } stream.write((char*)pad, padSize); } } void ImageImpl::zero() { for (size_t k = 0; k < nChannels; ++k) { for (size_t i = 0; i < nRows; ++i) { for (size_t j = 0; j < nCols; ++j) { size_t m = rcc_to_idx(i, j, k); a[m] = {0,0}; } } } } void ImageImpl::roundToInt() { for (size_t k = 0; k < nChannels; ++k) { for (size_t i = 0; i < nRows; ++i) { for (size_t j = 0; j < nCols; ++j) { size_t m = rcc_to_idx(i, j, k); if (!a[m].is_empty()) { cout << m << endl; a[m] = roundIntervalToInt(a[m]); } } } } } void ImageImpl::clip(const float min_val, const float max_val) { for (size_t k = 0; k < nChannels; ++k) { for (size_t i = 0; i < nRows; ++i) { for (size_t j = 0; j < nCols; ++j) { size_t m = rcc_to_idx(i, j, k); if (!a[m].is_empty()) { a[m] = {min(max(min_val, a[m].inf), max_val), min(max(min_val, a[m].sup), max_val)}; } } } } } ImageImpl* ImageImpl::threshold(const float val) { ImageImpl* ret = new ImageImpl(nRows, nCols, nChannels); for (size_t k = 0; k < nChannels; ++k) { for (size_t i = 0; i < nRows; ++i) { for (size_t j = 0; j < nCols; ++j) { size_t m = rcc_to_idx(i, j, k); if (!a[m].is_empty() && a[m].inf >= val) { ret->a[m] = {1, 1}; } else { ret->a[m] = {0, 0}; } } } } return ret; } ImageImpl* ImageImpl::center_crop(const size_t size) const { assert(size % 2 == 0); assert(this->nCols % 2 == 0); assert(this->nRows % 2 == 0); assert(this->nCols >= size); assert(this->nRows >= size); const size_t diffCols = this->nCols - size; const size_t diffRows = this->nRows - size; ImageImpl *ret = new ImageImpl(size, size, this->nChannels); for (size_t nChannel = 0; nChannel < this->nChannels; ++nChannel) { for (size_t nRow = 0; nRow < size; ++nRow) { for (size_t nCol = 0; nCol < size; ++nCol) { const size_t r = nRow + diffRows / 2; const size_t c = nCol + diffCols / 2; const size_t m = ret->rcc_to_idx(nRow, nCol, nChannel); const size_t n = this->rcc_to_idx(r, c, nChannel); //cout << m << " " << n << endl; ret->a[m] = this->a[n]; } } } // cout << " not here" << endl; return ret; } ImageImpl* ImageImpl::resize(const size_t new_nRows, const size_t new_nCols, const bool roundToInt) const { ImageImpl *ret = new ImageImpl(new_nRows, new_nCols, this->nChannels); for (size_t nChannel = 0; nChannel < ret->nChannels; ++nChannel) { for (size_t nRow = 0; nRow < ret->nRows; ++nRow) { for (size_t nCol = 0; nCol < ret->nCols; ++nCol) { Coordinate<float> new_coord = getCoordinate(nRow * this->nRows / (float) ret->nRows, nCol * this->nCols / (float) ret->nCols, nChannel); size_t m = ret->rcc_to_idx(nRow, nCol, nChannel); Interval out = BilinearInterpolation(new_coord, *this); if (roundToInt) { out = roundIntervalToInt(out); } ret->a[m] = out; //cout << m << " "<< nRow << " " << nCol << " " << nChannel<< " " << ret->a[m] << endl; } } } return ret; } ImageImpl* ImageImpl::resize(const size_t new_nRows, const size_t new_nCols, const bool roundToInt, const size_t size) const { assert(size % 2 == 0); //assert(this->nCols % 2 == 0); //assert(this->nRows % 2 == 0); assert(new_nRows >= size); assert(new_nCols >= size); const size_t diffCols = new_nCols - size; const size_t diffRows = new_nRows - size; ImageImpl *ret = new ImageImpl(size, size, this->nChannels); for (size_t nChannel = 0; nChannel < this->nChannels; ++nChannel) { for (size_t nRow = 0; nRow < size; ++nRow) { for (size_t nCol = 0; nCol < size; ++nCol) { const size_t r = nRow + diffRows / 2; const size_t c = nCol + diffCols / 2; const size_t m = ret->rcc_to_idx(nRow, nCol, nChannel); Coordinate<float> new_coord = getCoordinate(r * this->nRows / (float) new_nRows, c * this->nCols / (float) new_nCols, nChannel); Interval out = BilinearInterpolation(new_coord, *this); if (roundToInt) { out = roundIntervalToInt(out); } ret->a[m] = out; } } } return ret; } vector<ImageImpl*> ImageImpl::split_color_channels() const { vector<ImageImpl*> channels(nChannels); if (nChannels == 1) { channels[0] = new ImageImpl(*this); } else { for (size_t nChannel = 0; nChannel < nChannels; ++nChannel) { ImageImpl *im = new ImageImpl(nRows, nCols, 1); for (size_t i = 0; i < nRows; ++i) { for (size_t j = 0; j < nCols; ++j) { size_t m = im->rcc_to_idx(i, j, 0); size_t n = rcc_to_idx(i, j, nChannel); im->a[m] = a[n]; } } channels[nChannel] = im; } } return channels; } ImageImpl* ImageImpl::customVingette(const ImageImpl* vingette) const { ImageImpl *ret = new ImageImpl(this->nRows, this->nCols, this->nChannels); assert(vingette->nRows == nRows); assert(vingette->nCols == nCols); assert(vingette->nChannels == nChannels); for (size_t nChannel = 0; nChannel < this->nChannels; ++nChannel) { for (size_t nRow = 0; nRow < this->nRows; ++nRow) { for (size_t nCol = 0; nCol < this->nCols; ++nCol) { const size_t m = rcc_to_idx(nRow, nCol, nChannel); if (vingette->a[m].sup == 0) ret->a[m] = a[m]; else ret->a[m] = {0, 0}; } } } return ret; }; ImageImpl* ImageImpl::widthVingette(const ImageImpl* vingette, const float treshold) const { ImageImpl *ret = new ImageImpl(this->nRows, this->nCols, this->nChannels); assert(vingette->nRows == nRows); assert(vingette->nCols == nCols); assert(vingette->nChannels == nChannels); for (size_t nChannel = 0; nChannel < this->nChannels; ++nChannel) { for (size_t nRow = 0; nRow < this->nRows; ++nRow) { for (size_t nCol = 0; nCol < this->nCols; ++nCol) { const size_t m = rcc_to_idx(nRow, nCol, nChannel); if ((vingette->a[m].sup - vingette->a[m].inf) <= treshold) ret->a[m] = a[m]; else ret->a[m] = {0, 0}; } } } return ret; }; ImageImpl* ImageImpl::transform(std::function<Coordinate<Interval>(const Coordinate<float>)> T, const bool roundToInt) const { ImageImpl *ret = new ImageImpl(this->nRows, this->nCols, this->nChannels); for (size_t nChannel = 0; nChannel < this->nChannels; ++nChannel) { for (size_t nRow = 0; nRow < this->nRows; ++nRow) { for (size_t nCol = 0; nCol < this->nCols; ++nCol) { Interval out = BilinearInterpolation(T(this->getCoordinate(nRow, nCol, nChannel)), *this); if (roundToInt) { out = roundIntervalToInt(out); } ret->a[ret->rcc_to_idx(nRow, nCol, nChannel)] = out; } } } return ret; }; ImageImpl* ImageImpl::rotate(const Interval& params, const bool roundToInt) const { auto T = [&](const Coordinate<float> it) -> Coordinate<Interval>{ return Rotation(it, params); }; return transform(T, roundToInt); }; ImageImpl* ImageImpl::translate(const Interval& dx, const Interval& dy, const bool roundToInt) const { auto T = [&](const Coordinate<float> it) -> Coordinate<Interval>{ return Translation(it, dx, dy); }; return transform(T, roundToInt); }; vector<float> ImageImpl::bilinear_coefficients(int x_iter, int y_iter, float x, float y) const { assert(x_iter <= x && x <= x_iter + 2 && y_iter <= y && y <= y_iter + 2); float a_alpha = (x_iter + 2 - x) * (y_iter + 2 - y) / 4; float a_beta = (x_iter + 2 - x) * (y - y_iter) / 4; float a_gamma = (x - x_iter) * (y_iter + 2 - y) / 4; float a_delta = (x - x_iter) * (y - y_iter) / 4; return {a_alpha, a_beta, a_gamma, a_delta}; } bool ImageImpl::inverseRot(ImageImpl** out_ret, ImageImpl** out_vingette, const Interval gamma, const size_t refinements, const bool addIntegerError, const bool toIntegerValues, const bool computeVingette) const { auto T = [&](Coordinate<Interval> coord){ Coordinate<Interval> coord_out = Rotation(coord, gamma); return coord_out; }; auto Tinv = [&](Coordinate<Interval> coord){ Coordinate<Interval> coord_out = Rotation(coord, -gamma); return coord_out; }; assert(out_ret != 0); if(computeVingette) assert(out_vingette != 0); bool isEmpty = inverse(out_ret, out_vingette, T, Tinv, addIntegerError, toIntegerValues, refinements, computeVingette); assert(out_ret != 0); assert(*out_ret != 0); if(computeVingette) { assert(out_vingette != 0); assert(*out_vingette != 0); } return isEmpty; } bool ImageImpl::inverseTranslation(ImageImpl** out_ret, ImageImpl** out_vingette, const Interval dx, const Interval dy, const size_t refinements, const bool addIntegerError, const bool toIntegerValues, const bool computeVingette) const { auto T = [&](Coordinate<Interval> coord){ Coordinate<Interval> coord_out = Translation(coord, dx, dy); return coord_out; }; auto Tinv = [&](Coordinate<Interval> coord){ Coordinate<Interval> coord_out = Translation(coord, -dx, -dy); return coord_out; }; assert(out_ret != 0); if(computeVingette) assert(out_vingette != 0); bool isEmpty = inverse(out_ret, out_vingette, T, Tinv, addIntegerError, toIntegerValues, refinements, computeVingette); assert(out_ret != 0); assert(*out_ret != 0); if(computeVingette) { assert(out_vingette != 0); assert(*out_vingette != 0); } return isEmpty; } ostream& operator<<(ostream& os, const ImageImpl& img) { for (size_t k = 0; k < img.nChannels; ++k) { os << "Channel " << k << ":" << endl; for (size_t i = 0; i < img.nRows; ++i) { for (size_t j = 0; j < img.nCols; ++j) { size_t m = img.rcc_to_idx(i, j, k); os << img.a[m] << " "; } os << endl; } os << endl; } return os; } bool ImageImpl::inverse(ImageImpl **out, ImageImpl **vingette, const std::function<Coordinate<Interval>(Coordinate<Interval>)> T, const std::function<Coordinate<Interval>(Coordinate<Interval>)> invT, const bool addIntegerError, const bool toIntegerValues, const size_t nrRefinements, const bool computeVingette) const { ImageImpl *ret = new ImageImpl(this->nRows, this->nCols, this->nChannels); ImageImpl *constraints = 0; bool isEmpty = false; assert(out != 0); if (computeVingette) { assert(vingette != 0); *vingette = new ImageImpl(this->nRows, this->nCols, this->nChannels); } for(size_t it = 0; it < (1 + nrRefinements); ++it) { bool refine = it > 0; bool lastIt = (it == nrRefinements); if (refine) { ImageImpl *tmp = ret; ret = constraints; constraints = tmp; if (ret == 0) ret = new ImageImpl(this->nRows, this->nCols, this->nChannels); } for (size_t nRow = 0; nRow < this->nRows; ++nRow) for (size_t nCol = 0; nCol < this->nCols; ++nCol) { bool e = invert_pixel_on_bounding_box(nRow, nCol, ret, refine, constraints, T, invT, addIntegerError, lastIt && toIntegerValues, lastIt && computeVingette, (lastIt && computeVingette) ? *vingette : 0); isEmpty = isEmpty || e; if (isEmpty) {nRow = this->nRows; nCol=this->nCols;} // break loops } if (isEmpty) break; } if (constraints != 0) delete constraints; *out = ret; return isEmpty; } bool ImageImpl::invert_pixel_on_bounding_box(const size_t nRow, const size_t nCol, ImageImpl *ret, const bool refine, const ImageImpl *constraints, const std::function<Coordinate<Interval>(Coordinate<Interval>)> T, const std::function<Coordinate<Interval>(Coordinate<Interval>)> invT, const bool addIntegerError, const bool toIntegerValues, const bool computeVingette, ImageImpl *vingette) const { assert(ret != 0); if (refine) assert(constraints != 0); Coordinate<float> coord = getCoordinate(nRow, nCol, 0); Coordinate<Interval> coordI({coord.x-2, coord.x+2}, {coord.y-2, coord.y+2}, 0); Coordinate<Interval> coordI_pre = invT(coordI); // pixels to consider size_t parity_x = (nCols - 1) % 2; size_t parity_y = (nRows - 1) % 2; int lo_x, hi_x, lo_y, hi_y; tie(lo_x, hi_x, lo_y, hi_y) = calculateBoundingBox(coordI_pre.x, coordI_pre.y, parity_x, parity_y); //size_t m = rcc_to_idx(nRow, nCol, 0); //printf("%ld %ld %f %f %f %f %f %f %d %d %d %d\n", nRow, nCol, coordI_pre.x.inf, coordI_pre.x.sup, coordI_pre.y.inf, coordI_pre.y.sup, a[m].inf, a[m].sup, lo_x, hi_x, lo_y, hi_y); Interval inv_p[nChannels]; for (size_t chan = 0; chan < this->nChannels; ++chan) inv_p[chan] = Interval(0, 1); for (int x_iter = lo_x; x_iter <= hi_x; x_iter += 2) for (int y_iter = lo_y; y_iter <= hi_y; y_iter += 2) { Coordinate<Interval> coord_iter({(float)x_iter, (float)x_iter}, {(float)y_iter, (float)y_iter}, 0.0f ); Coordinate<Interval> coord_iterT = T(coord_iter); if (coord_iterT.x.meet(coordI.x).is_empty() || coord_iterT.y.meet(coordI.y).is_empty()) continue; Interval p[nChannels]; int r_iter, c_iter; tie(r_iter, c_iter) = getRc(x_iter, y_iter); if (0 <= r_iter && r_iter < signed(nRows) && 0 <= c_iter && c_iter < signed(nCols)) { for (size_t chan = 0; chan < this->nChannels; ++chan) { p[chan] = valueAt(x_iter, y_iter, chan, Interval(0, 1)); if (addIntegerError) { //this assumes that the pixel_values * 255 are integers in [0, 255] //and that the rounding mode is arithmetic rounding (and not for example floorfing) assert(p[chan].inf == p[chan].sup); float deltaUp = (0.5f - Constants::EPS)/255.0f; float deltaDown = 0.5f / 255.0f; p[chan] = Interval(p[chan].inf - deltaDown, p[chan].sup + deltaUp).meet({0, 1}); } } } else { for (size_t chan = 0; chan < this->nChannels; ++chan) p[chan] = Interval(0, 1); } Interval inv_corners[nChannels]; for (Corner c : {Corner::upper_left, Corner::lower_left, Corner::upper_right, Corner::lower_right}) { Interval inv_corner[nChannels]; invert_pixel(c, coord, coord_iterT, inv_corner, p, constraints, refine, false); // debug for (size_t chan = 0; chan < this->nChannels; ++chan) { inv_corners[chan] = inv_corners[chan].join(inv_corner[chan]); } } for (size_t chan = 0; chan < this->nChannels; ++chan) { // printf("%d %d %d %d %d [%f %f] [%f %f] [%f %f]\n", (int)nRow, (int)nCol, x_iter, y_iter, (int)chan, inv_p[chan].inf, inv_p[chan].sup, // inv_corners[chan].inf, inv_corners[chan].sup, // (inv_p[chan].meet(inv_corners[chan])).inf, // (inv_p[chan].meet(inv_corners[chan])).sup); inv_p[chan] = inv_p[chan].meet(inv_corners[chan]); } } bool isEmpty = false; for (size_t chan = 0; chan < this->nChannels; ++chan) { size_t m = rcc_to_idx(nRow, nCol, chan); if (toIntegerValues && !inv_p[chan].is_empty()) { float lower = inv_p[chan].inf; float upper = inv_p[chan].sup; if (lower > 0) { for(size_t k = 0; k < 255; k ++) { if(pixelVals[k] < lower && lower <= pixelVals[k+1] ) { lower = pixelVals[k+1]; break; } } } assert(lower >= inv_p[chan].inf); if(upper < 1) { for(size_t k = 256; k >= 1; k--) { if(pixelVals[k] > upper && upper >= pixelVals[k]) { upper = pixelVals[k]; break; } } } assert(upper <= inv_p[chan].sup); if (lower > upper) { inv_p[chan] = Interval(); } else { inv_p[chan] = Interval(lower, upper); } } ret->a[m] = inv_p[chan]; if (computeVingette) { if ((ret->a[m].sup - ret->a[m].inf) > 0.3f) vingette->a[m] = Interval(1, 1); else vingette->a[m] = Interval(0, 0); } isEmpty = isEmpty || ret->a[m].is_empty(); } return isEmpty; } void ImageImpl::invert_pixel(const Corner center, const Coordinate<float>& coord, const Coordinate<Interval>& coord_iterT, Interval* out, const Interval* pixel_values, const ImageImpl* constraints, const bool refine, const bool debug) const { Interval x_box, y_box; float x_ll, y_ll; vector<tuple<float, float>> corners; switch(center) { case lower_right: x_ll = coord.x; y_ll = coord.y; x_box = coord_iterT.x.meet(Interval(coord.x, coord.x+2)); y_box = coord_iterT.y.meet(Interval(coord.y, coord.y+2)); if (!refine) corners.push_back({x_box.sup, y_box.sup}); break; case upper_right: x_ll = coord.x; y_ll = coord.y - 2; x_box = coord_iterT.x.meet(Interval(coord.x, coord.x+2)); y_box = coord_iterT.y.meet(Interval(coord.y-2, coord.y)); if (!refine) corners.push_back({x_box.sup, y_box.inf}); break; case lower_left: x_ll = coord.x - 2; y_ll = coord.y; x_box = coord_iterT.x.meet(Interval(coord.x-2, coord.x)); y_box = coord_iterT.y.meet(Interval(coord.y, coord.y+2)); if (!refine) corners.push_back({x_box.inf, y_box.sup}); break; case upper_left: x_ll = coord.x - 2; y_ll = coord.y - 2; x_box = coord_iterT.x.meet(Interval(coord.x-2, coord.x)); y_box = coord_iterT.y.meet(Interval(coord.y-2, coord.y)); if (!refine) corners.push_back({x_box.inf, y_box.inf}); break; default: assert(false); }; if (debug) printf("%f %f %f %f %f %f %f %f %f %f\n", x_ll, y_ll, x_box.inf, x_box.sup, y_box.inf, y_box.sup, coord_iterT.x.inf, coord_iterT.x.sup, coord_iterT.y.inf, coord_iterT.y.sup); assert(out != 0); for (size_t chan = 0; chan < this->nChannels; ++chan) out[chan] = Interval(); if (x_box.is_empty() || y_box.is_empty()) { return; } assert(pixel_values != 0); if (refine) { assert(constraints != 0); corners.push_back({x_box.inf, y_box.inf}); corners.push_back({x_box.sup, y_box.inf}); corners.push_back({x_box.inf, y_box.sup}); corners.push_back({x_box.sup, y_box.sup}); } for (auto c : corners) { float x_coord = get<0>(c), y_coord = get<1>(c); Interval ret[nChannels]; //printf("%f %f %f\n", x_ll, x_coord, x_ll + 2); vector<float> coef = bilinear_coefficients(x_ll, y_ll, x_coord, y_coord); if (debug) printf("coefs %f %f %f %f\n", coef[0], coef[1], coef[2], coef[3]); if (coef[center] == 0) { for (size_t chan = 0; chan < this->nChannels; ++chan) ret[chan] = Interval(0, 1); } else { for (size_t chan = 0; chan < this->nChannels; ++chan) { ret[chan] = pixel_values[chan]; if (debug) printf("[%f %f]", ret[chan].inf, ret[chan].sup); } if (debug) printf("\n"); if(refine) { for(size_t k = 0; k < 4; ++k) { if (k == center) continue; float x_ = 0, y_ = 0; switch(k) { case 0: x_ = x_ll; y_ = y_ll; break; case 1: x_ = x_ll; y_ = y_ll + 2; break; case 2: x_ = x_ll + 2; y_ = y_ll; break; case 3: x_ = x_ll + 2; y_ = y_ll + 2; break; } for (size_t chan = 0; chan < this->nChannels; ++chan) { Interval con = constraints->valueAt(x_, y_, chan, {0, 1}); if (debug) printf("con [%f %f] %d \n", con.inf, con.sup, con.is_empty()); ret[chan] = ret[chan] - coef[k] * con; if (debug) printf("%d [%f %f]\n", (int)k, ret[chan].inf, ret[chan].sup); } } } else { float f = 0; for(size_t k = 0; k < 4; ++k) { if (k == center) continue; f += coef[k]; } Interval tmp = f * Interval(0,1); for (size_t chan = 0; chan < this->nChannels; ++chan) { ret[chan] = ret[chan] - tmp; if (debug) printf("[%f %f]\n", ret[chan].inf, ret[chan].sup); } } for (size_t chan = 0; chan < this->nChannels; ++chan) { ret[chan] = ret[chan] / coef[center]; if (debug) printf("%f [%f %f]\n", coef[center], ret[chan].inf, ret[chan].sup); } } for (size_t chan = 0; chan < this->nChannels; ++chan) { out[chan] = out[chan].join(ret[chan]); } } } ImageImpl* ImageImpl::erode() { ImageImpl* ret = new ImageImpl(nRows, nCols, nChannels); for (size_t k = 0; k < nChannels; ++k) { for (size_t i = 0; i < nRows; ++i) { for (size_t j = 0; j < nCols; ++j) { const size_t m = rcc_to_idx(i, j, k); Interval val = a[m]; for(int di=-1; di <= 1; ++di) for(int dj=-1; dj <= 1; ++dj) { int ii = (signed)i + di; int jj = (signed)j + dj; if (0 <= ii && ii < nRows && 0 <= jj && jj < nCols) { const size_t mm = rcc_to_idx((unsigned)ii, (unsigned)jj, k); Interval other = a[mm]; if (other.inf <= val.inf && other.sup <= val.sup) val = other; } } ret->a[m] = val; } } } } ImageImpl* ImageImpl::fill (const float value) const { ImageImpl* ret = new ImageImpl(nRows, nCols, nChannels); for (size_t k = 0; k < nChannels; ++k) { for (size_t i = 0; i < nRows; ++i) { for (size_t j = 0; j < nCols; ++j) { size_t m = rcc_to_idx(i, j, k); ret->a[m] = {value, value}; } } } return ret; }
32.792314
187
0.522279
eth-sri
d8b48ddfbda489b7b393ff79497c2ac72d382948
2,095
cpp
C++
simulation/Rendering/Window.cpp
Terae/3D_Langton_Ant
017dadbe2962018db043bf50e8a6dcd49ade0eac
[ "MIT" ]
null
null
null
simulation/Rendering/Window.cpp
Terae/3D_Langton_Ant
017dadbe2962018db043bf50e8a6dcd49ade0eac
[ "MIT" ]
null
null
null
simulation/Rendering/Window.cpp
Terae/3D_Langton_Ant
017dadbe2962018db043bf50e8a6dcd49ade0eac
[ "MIT" ]
null
null
null
// // Created by benji on 10/11/16. // #include "Window.h" #include "Context.h" void glfwErrorCallback(int error, const char* description) { std::cerr << _RED("There was a glfw error : ") << description << _RED(" (" + std::to_string(error) + ")") << std::endl; } Window::Window(std::string title) { std::cout << "Starting GLFW" << std::endl; // Init GLFW if(!glfwInit()) { std::cerr << "Error during glfw initializing" << std::endl; return; } glfwSetErrorCallback(glfwErrorCallback); // Set all the required options for GLFW glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_SAMPLES, 16); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); _window = glfwCreateWindow(800, 600, title.c_str(), nullptr, nullptr); if (!_window) { std::cout << "Failed to create the GLFW window" << std::endl; glfwTerminate(); return; } glfwMakeContextCurrent(_window); gladLoadGLLoader((GLADloadproc) glfwGetProcAddress); glfwSwapInterval(1); _context = std::make_unique<Context>(_window); glEnable(GL_MULTISAMPLE); } Window::~Window() { destroy(); } void Window::setTitle(std::string newTitle) { glfwSetWindowTitle(_window, newTitle.c_str()); } void Window::destroy() { if(_destroyed) return; _destroyed = true; glfwDestroyWindow(_window); glfwTerminate(); } bool Window::isWindowOpened() { return !glfwWindowShouldClose(_window); } void Window::setKeyCallback(GLFWkeyfun func) { glfwSetKeyCallback(_window, func); } void Window::setScrollCallback(GLFWscrollfun func) { glfwSetScrollCallback(_window, func); } void Window::setupFrame() { int width, height; glfwGetFramebufferSize(_window, &width, &height); glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); } void Window::finalizeFrame() { glfwSwapBuffers(_window); glfwPollEvents(); }
24.08046
123
0.681623
Terae
d8bab90ef5648fdbaf3215e78ab86b647e808d74
88
cpp
C++
src/core/Distributor.cpp
jozhalaj/gateway
49168dcbcf833da690048880bb33542ffbc90ce3
[ "BSD-3-Clause" ]
7
2018-06-09T05:55:59.000Z
2021-01-05T05:19:02.000Z
src/core/Distributor.cpp
jozhalaj/gateway
49168dcbcf833da690048880bb33542ffbc90ce3
[ "BSD-3-Clause" ]
1
2019-12-25T10:39:06.000Z
2020-01-03T08:35:29.000Z
src/core/Distributor.cpp
jozhalaj/gateway
49168dcbcf833da690048880bb33542ffbc90ce3
[ "BSD-3-Clause" ]
11
2018-05-10T08:29:05.000Z
2020-01-22T20:49:32.000Z
#include "core/Distributor.h" using namespace BeeeOn; Distributor::~Distributor() { }
11
29
0.738636
jozhalaj
d8befa451c1a63907b4b8ddd0f23ce49f4c051be
862
cpp
C++
atcoder/B - Palindrome-philia/AC.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
atcoder/B - Palindrome-philia/AC.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
atcoder/B - Palindrome-philia/AC.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: 2019-12-08 18:03:30 * solution_verdict: AC language: C++14 (GCC 5.4.1) * run_time: 1 ms memory_used: 256 KB * problem: https://atcoder.jp/contests/abc147/tasks/abc147_b ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6,inf=1e9; int main() { ios_base::sync_with_stdio(0);cin.tie(0); string s;cin>>s;int n=s.size(); int ans=0; for(int i=0;i<n/2;i++) if(s[i]!=s[n-1-i])ans++; cout<<ans<<endl; return 0; }
43.1
111
0.37123
kzvd4729
d8bf6f2fc9a378f878a916d6e37e9a41f08a12af
1,313
cpp
C++
libdocscript/src/runtime/procedure/lambda_procedure.cpp
sotvokun/docscript
0718c8943e895672b9570524cd9eb7ff019d079f
[ "MIT" ]
1
2021-12-11T11:04:21.000Z
2021-12-11T11:04:21.000Z
libdocscript/src/runtime/procedure/lambda_procedure.cpp
sotvokun/docscript
0718c8943e895672b9570524cd9eb7ff019d079f
[ "MIT" ]
null
null
null
libdocscript/src/runtime/procedure/lambda_procedure.cpp
sotvokun/docscript
0718c8943e895672b9570524cd9eb7ff019d079f
[ "MIT" ]
null
null
null
#include "libdocscript/runtime/datatype.h" #include "libdocscript/runtime/procedure.h" #include "libdocscript/runtime/value.h" #include "libdocscript/runtime/environment.h" #include "libdocscript/interpreter.h" namespace libdocscript::runtime { // +--------------------+ // Constructor // +--------------------+ LambdaProcedure::LambdaProcedure(const parm_list& parameters, func_body body) : Procedure(Procedure::Lambda), _parameters(parameters), _expression(body) {} // +--------------------+ // Public Functions // +--------------------+ Value LambdaProcedure::invoke(const args_list &args, Environment &env) const { if(_parameters.size() != args.size()) { throw UnexceptNumberOfArgument(_parameters.size(), args.size()); } Environment subenv = env.derive(); for(decltype(_parameters.size()) i = 0; i != _parameters.size(); ++i) { subenv.set<Value>(_parameters[i], args[i]); } return Interpreter(subenv).eval(_expression); } // +--------------------+ // Private Functions // +--------------------+ DataType *LambdaProcedure::rawptr_clone() const { return new LambdaProcedure(*this); } // +--------------------+ // Type Conversion // +--------------------+ LambdaProcedure::operator std::string() const { return "#lambda-procedure"; } }
25.745098
77
0.600914
sotvokun
d8c04a13313137cf5a7cf0c58c970a13042dcce3
376
cpp
C++
patterns/adapter/main.cpp
PotatoMaster101/pats
7429125a4b34fa1ba4ad6710a1753a547909f73c
[ "MIT" ]
null
null
null
patterns/adapter/main.cpp
PotatoMaster101/pats
7429125a4b34fa1ba4ad6710a1753a547909f73c
[ "MIT" ]
null
null
null
patterns/adapter/main.cpp
PotatoMaster101/pats
7429125a4b34fa1ba4ad6710a1753a547909f73c
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include "adapter.hpp" int main(int argc, const char *argv[]) { auto legacy = std::make_unique<legacy_rect>(1, 2, 3, 4); // x1 x2 y1 y2 auto modern = std::make_unique<rect_adapter>(1, 2, 3, 4); // x y w h legacy->legacy_print(); // prints 1 3 2 4 modern->print(); // prints 1 4 2 6 return 0; }
31.333333
78
0.582447
PotatoMaster101
d8c07138e588daf79752f92dbe2f0522ae53bc14
887
cpp
C++
ExemploExcecoesTryCatchThrow/ClasseHerdeiraException.cpp
lucaslgr/LearningCplusplus
579e4ddc8a55605af9b46e24bfb91897d3be0274
[ "MIT" ]
1
2020-07-14T16:49:52.000Z
2020-07-14T16:49:52.000Z
ExemploExcecoesTryCatchThrow/ClasseHerdeiraException.cpp
lucaslgr/LearningCplusplus
579e4ddc8a55605af9b46e24bfb91897d3be0274
[ "MIT" ]
null
null
null
ExemploExcecoesTryCatchThrow/ClasseHerdeiraException.cpp
lucaslgr/LearningCplusplus
579e4ddc8a55605af9b46e24bfb91897d3be0274
[ "MIT" ]
null
null
null
#include <iostream> #include <string.h> #include <exception> using namespace std; class ExcecaoCustomizada : public exception { protected: char msg[100]; public: ExcecaoCustomizada(const char* e) { strcpy(msg, e); } virtual const char* what() { return msg; } }; int fat (int n) { if (n < 0) { throw ExcecaoCustomizada("Numero negativo!!"); } if (n == 0 || n == 1) { return 1; } return (n * fat(n - 1)); } int main (int agrc, const char *agrv[]) { try { cout << "Fatorial de 5: " << fat(5) << endl; cout << "Fatorial de -5: " << fat(-5) << endl; } catch(ExcecaoCustomizada e) { std::cerr << "Erro:" << e.what() << '\n'; } catch(...) { cerr << "Qualquer erro!" << endl; } return 0; }
17.392157
54
0.470124
lucaslgr
d8cd55713bb6d0e47bcf9a195ec14a4b22825b20
765
cpp
C++
lib/Dialect/XTen/IR/XTenDialect.cpp
jcamacho1234/mlir-xten
721f97fc01dd39a2f54ef3b409ceb5a9528c61f4
[ "Apache-2.0" ]
10
2021-11-05T00:08:47.000Z
2022-02-09T20:12:56.000Z
lib/Dialect/XTen/IR/XTenDialect.cpp
jcamacho1234/mlir-xten
721f97fc01dd39a2f54ef3b409ceb5a9528c61f4
[ "Apache-2.0" ]
1
2022-01-27T17:21:14.000Z
2022-01-27T17:22:41.000Z
lib/Dialect/XTen/IR/XTenDialect.cpp
jcamacho1234/mlir-xten
721f97fc01dd39a2f54ef3b409ceb5a9528c61f4
[ "Apache-2.0" ]
6
2021-11-10T06:49:47.000Z
2021-12-22T19:02:48.000Z
//===- XTenDialect.cpp ------------------------------------------*- C++ -*-===// // // This file is licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // // (c) Copyright 2021 Xilinx Inc. // //===----------------------------------------------------------------------===// #include "xten/Dialect/XTen/XTenDialect.h" #include "xten/Dialect/XTen/XTenOps.h" #include "mlir/IR/DialectImplementation.h" #include "xten/Dialect/XTen/XTenOpsDialect.cpp.inc" using namespace mlir; using namespace xilinx::xten; void XTenDialect::initialize() { addOperations< #define GET_OP_LIST #include "xten/Dialect/XTen/XTenOps.cpp.inc" >(); }
27.321429
80
0.605229
jcamacho1234
d8d336b7d950ba8da6e2731acc03269305ba9c66
3,136
cpp
C++
Misc/foobarnowplayingannouncer.cpp
exscape/lyricusqt
69c9fc3c38833459493f136f65c9ede8940f0d77
[ "MIT" ]
null
null
null
Misc/foobarnowplayingannouncer.cpp
exscape/lyricusqt
69c9fc3c38833459493f136f65c9ede8940f0d77
[ "MIT" ]
null
null
null
Misc/foobarnowplayingannouncer.cpp
exscape/lyricusqt
69c9fc3c38833459493f136f65c9ede8940f0d77
[ "MIT" ]
null
null
null
#include "foobarnowplayingannouncer.h" #include <QDebug> #include <QThread> #include <QFile> // This should be more than enough, since the struct is smaller #define BUFSIZE 2048 struct songInfo { // These are in UTF-8; use QString::fromUtf8() to create a QString char artist[512]; char title[512]; char path[512]; }; FoobarNowPlayingAnnouncer::FoobarNowPlayingAnnouncer(QObject *parent) : QObject(parent) { } void FoobarNowPlayingAnnouncer::run() { char *responseData = (char *)HeapAlloc(GetProcessHeap(), 0, BUFSIZE); if (!responseData) { qWarning() << "Unable to allocate memory for foo_simpleserver_announce response data"; return; } bool initial_run = true; // Loop retrying to connect to the pipe, in case it fails (or disconnects after initially succeeding) while (true) { restart_loop: if (!initial_run) { QThread::sleep(5); } else initial_run = false; HANDLE hPipe = CreateFile(TEXT("\\\\.\\pipe\\foo_simpleserver_announce"), GENERIC_READ | FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING, 0, NULL); if (hPipe == INVALID_HANDLE_VALUE) { // qWarning() << "Unable to connect to foo_simpleserver_announce pipe"; continue; } DWORD mode = PIPE_READMODE_MESSAGE; if (!SetNamedPipeHandleState(hPipe, &mode, NULL, NULL)) { qWarning() << "Unable to set PIPE_READMODE_MESSAGE for foo_simpleserver_announce pipe"; CloseHandle(hPipe); continue; } // Loop while connected to this pipe while (true) { DWORD bytes_read = 0; bool success = ReadFile(hPipe, responseData, BUFSIZE, &bytes_read, NULL); if (!success) { qWarning() << "foo_simpleserver_announce ReadFile failed; GetLastError() ==" << GetLastError(); CloseHandle(hPipe); goto restart_loop; // Weee! } if (bytes_read != sizeof(struct songInfo)) { qWarning() << "foo_simpleserver_announce read failed: unexpected data size" << bytes_read << "bytes"; CloseHandle(hPipe); goto restart_loop; // Weee! } struct songInfo *info = reinterpret_cast<struct songInfo *>(responseData); QString artist = QString::fromUtf8(info->artist); QString title = QString::fromUtf8(info->title); QString path = QString::fromUtf8(info->path); if (path.startsWith("file://")) path = path.right(path.length() - 7); if (artist.length() > 0 && title.length() > 0) { lastArtist = artist; lastTitle = title; lastPath = path; emit newTrack(artist, title, path); // Note that path may be 0-length -- though it should never be } } } // This won't ever be reached... oh well. HeapFree(GetProcessHeap(), 0, responseData); } void FoobarNowPlayingAnnouncer::reEmitLastTrack() { emit newTrack(lastArtist, lastTitle, lastPath); }
34.461538
153
0.601403
exscape
d8d41db745f162d061bcb56fdf849608ac910537
1,179
cpp
C++
Shoot/src/Color.cpp
franticsoftware/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
3
2019-10-04T19:44:44.000Z
2021-07-27T15:59:39.000Z
Shoot/src/Color.cpp
franticsoftware/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
1
2019-07-20T05:36:31.000Z
2019-07-20T22:22:49.000Z
Shoot/src/Color.cpp
aminere/vlad-heavy-strike
a4da4df617e9ccd6ebd9819ad166d892924638ce
[ "MIT" ]
null
null
null
/* Amine Rehioui Created: May 1st 2010 */ #include "Shoot.h" #include "Color.h" namespace shoot { // static variables initialization Color Color::Red = Color(1.0f, 0.0f, 0.0f, 1.0f); Color Color::Green = Color(0.0f, 1.0f, 0.0f, 1.0f); Color Color::Blue = Color(0.0f, 0.0f, 1.0f, 1.0f); Color Color::White = Color(1.0f, 1.0f, 1.0f, 1.0f); Color Color::Black = Color(0.0f, 0.0f, 0.0f, 1.0f); Color Color::Yellow = Color(1.0f, 1.0f, 0.0f, 1.0f); Color Color::Zero = Color(0.0f, 0.0f, 0.0f, 0.0f); //! constructor Color::Color() : R(1.0f), G(1.0f), B(1.0f), A(1.0f) { } bool Color::operator == (const Color& other) const { return (Math::FEqual(R, other.R) && Math::FEqual(G, other.G) && Math::FEqual(B, other.B) && Math::FEqual(A, other.A)); } Color Color::operator + (const Color& other) const { Color result(R+other.R, G+other.G, B+other.B, A+other.A); return result; } Color Color::operator - (const Color& other) const { Color result(R-other.R, G-other.G, B-other.B, A-other.A); return result; } Color Color::operator * (f32 fValue) const { Color result(R*fValue, G*fValue, B*fValue, A*fValue); return result; } }
21.436364
59
0.617472
franticsoftware
d8deb83ab03c9ca632a51a4283072a78d2a0add6
9,846
cpp
C++
src/main.cpp
katsumin/HomeM5
ca0cf55e3d6a415d2a07d9adcc81b1f9c9a3b021
[ "MIT" ]
null
null
null
src/main.cpp
katsumin/HomeM5
ca0cf55e3d6a415d2a07d9adcc81b1f9c9a3b021
[ "MIT" ]
null
null
null
src/main.cpp
katsumin/HomeM5
ca0cf55e3d6a415d2a07d9adcc81b1f9c9a3b021
[ "MIT" ]
null
null
null
#include <queue> #include <M5Stack.h> #include <time.h> #include <WiFi.h> #include <WiFiMulti.h> #include <Ethernet.h> #include <Wire.h> #include <BME280_t.h> // import BME280 template library #include "InfluxDb.h" #include "smartmeter.h" #include "config.h" #include "debugView.h" #include "FunctionButton.h" #include "MainView.h" #include "HeadView.h" #include "PowerView.h" #include "Rtc.h" #include "EchonetUdp.h" #include "Ecocute.h" #include "Aircon.h" #include "log.h" #include "DataStore.h" #include "View.h" #define SCK 18 #define MISO 19 #define MOSI 23 #define CS 26 // #define TEST // instances FunctionButton btnA(&M5.BtnA); FunctionButton btnB(&M5.BtnB); FunctionButton btnC(&M5.BtnC); DebugView debugView(0, 100, 320, SCROLL_SIZE * 10); InfluxDb influx(INFLUX_SERVER, INFLUX_DB); SmartMeter sm; NtpClient ntp; Rtc rtc; DataStore dataStore; MainView mainView(&dataStore); PowerView powerView(&dataStore, &rtc); ViewController viewController; /* スマートメータ接続タスク */ void bp35c0_monitoring_task(void *arm) { // bJoined = false; Serial.println("task start"); // bTaskRunning = true; // スマートメータ接続 sm.disconnect(); delay(500); sm.connect(PWD, BID); Serial.println("task stop"); vTaskDelete(NULL); } #define TIMEZONE 9 * 3600 boolean rcvEv29 = false; void bp35c0_polling() { int res; char buf[1024]; RCV_CODE code = sm.polling(buf, sizeof(buf)); switch (code) { case RCV_CODE::ERXUDP: case RCV_CODE::OTHER: // UDP受信 debugView.output(buf); sd_log.out(buf); break; case RCV_CODE::ERXUDP_E7: dataStore.setPower(sm.getPower()); snprintf(buf, sizeof(buf), "power value=%ld", sm.getPower()); debugView.output(buf); res = influx.write(buf); debugView.output(res); break; case RCV_CODE::ERXUDP_EAB: dataStore.setWattHourPlus(sm.getWattHourPlus(), sm.getTimePlus() + TIMEZONE); dataStore.setWattHourMinus(sm.getWattHourMinus(), sm.getTimeMinus() + TIMEZONE); snprintf(buf, sizeof(buf), "+power value=%.1f %ld000000000", sm.getWattHourPlus(), sm.getTimePlus()); debugView.output(buf); res = influx.write(buf); debugView.output(res); snprintf(buf, sizeof(buf), "-power value=%.1f %ld000000000", sm.getWattHourMinus(), sm.getTimeMinus()); debugView.output(buf); res = influx.write(buf); debugView.output(res); if (rcvEv29) { // EVENT29受信からEVENT25受信しなかったら、再接続開始 xTaskCreate(&bp35c0_monitoring_task, "bp35c0r", 4096, NULL, 5, NULL); rcvEv29 = false; } break; case RCV_CODE::EVENT_25: // 接続完了 → 要求コマンドを開始 sm.setConnectState(CONNECT_STATE::CONNECTED); Serial.println("EV25"); sd_log.out("EV25"); sm.request(); rcvEv29 = false; break; case RCV_CODE::EVENT_26: // セッション切断要求 → 再接続開始 case RCV_CODE::EVENT_27: // PANA セッションの終了に成功 → 再接続開始 case RCV_CODE::EVENT_28: // PANA セッションの終了要求に対する応答がなくタイムアウトした(セッションは終了) → 再接続開始 Serial.println("EV26-28"); sd_log.out("EV26-28"); xTaskCreate(&bp35c0_monitoring_task, "bp35c0r", 4096, NULL, 5, NULL); break; case RCV_CODE::EVENT_29: // セッション期限切れ → 送信を止め、'EVENT 25'を待つ sm.setConnectState(CONNECT_STATE::CONNECTING); Serial.println("EV29"); sd_log.out("EV29"); rcvEv29 = true; break; case RCV_CODE::TIMEOUT: default: break; } } boolean bEco = false; void ecocuteCallback(Ecocute *ec) { // sd_log.out("Ecocute callback"); Serial.println("Ecocute callback"); bEco = true; } boolean bAir = false; void airconCallback(Aircon *ac) { // sd_log.out("Aircon callback"); Serial.println("Aircon callback"); bAir = true; } void callbackNtp(void *arg) { Serial.println("callbacked !"); btnB.enable("NTP"); } WiFiMulti wm; void nw_init() { Serial.println(); SPI.begin(SCK, MISO, MOSI, -1); Ethernet.init(CS); // Ethernet/Ethernet2 IPAddress addr; char buf[64]; UDP *udpNtp = nullptr; UDP *udpEchonet = nullptr; if (Ethernet.linkStatus() == LinkON) // Ethernet { // Ethernet Serial.println("Ethernet connected"); Serial.println("IP address: "); Ethernet.begin(mac); addr = Ethernet.localIP(); influx.setEthernet(true); snprintf(buf, sizeof(buf), "%s(Ethernet)", addr.toString().c_str()); headView.setNwType("Ethernet"); udpNtp = new EthernetUDP(); udpEchonet = new EthernetUDP(); } else { // WiFi Serial.print("Connecting to WIFI"); wm.addAP(WIFI_SSID, WIFI_PASS); while (wm.run() != WL_CONNECTED) { Serial.print("."); delay(100); } Serial.println("WiFi connected"); Serial.println("IP address: "); addr = WiFi.localIP(); influx.setEthernet(false); snprintf(buf, sizeof(buf), "%s(WiFi)", addr.toString().c_str()); headView.setNwType("WiFi"); udpNtp = new WiFiUDP(); udpEchonet = new WiFiUDP(); } Serial.println(buf); headView.setIpAddress(addr); // RTC ntp.init(udpNtp, (char *)NTP_SERVER, random(10000, 19999)); ntp.setCallback(callbackNtp, nullptr); rtc.init(&ntp); // echonet echonetUdp.init(udpEchonet); // ecocute ecocute.init(&echonetUdp, ECOCUTE_ADDRESS, ecocuteCallback); // aircon aircon.init(&echonetUdp, AIRCON_ADDRESS, airconCallback); } BME280<> BMESensor; // instantiate sensor void updateBme(boolean withInflux) { while (true) { BMESensor.refresh(); // read current sensor data float p = BMESensor.pressure; if (p >= 90000.0) break; Serial.println(p); delay(100); } dataStore.setTemperature(BMESensor.temperature); dataStore.setHumidity(BMESensor.humidity); dataStore.setPressure(BMESensor.pressure / 100.0F); if (withInflux) { char buf[64]; snprintf(buf, sizeof(buf), "room temp=%.1f,hum=%.1f,press=%.1f", BMESensor.temperature, BMESensor.humidity, BMESensor.pressure / 100.0F); debugView.output(buf); int res = influx.write(buf); debugView.output(res); } } #define VIEWKEY_MAIN ((const char *)"MAIN") #define VIEWKEY_POWER ((const char *)"POWER") CONNECT_STATE preState; void setup() { M5.begin(); // DataStore dataStore.init(); // View M5.Lcd.clear(); headView.init(); headView.setRtc(&rtc); sd_log.setRtc(&rtc); viewController.setView(VIEWKEY_MAIN, &mainView, VIEWKEY_POWER); viewController.setView(VIEWKEY_POWER, &powerView, VIEWKEY_MAIN); viewController.changeNext(); // スマートメータ sm.setDebugView(&debugView); sm.init(); preState = sm.getConnectState(); btnA.enable("JOIN"); btnC.enable(viewController.getNextKey()); // LAN btnB.disable("NTP"); nw_init(); // Sensor Wire.begin(GPIO_NUM_21, GPIO_NUM_22); // initialize I2C that connects to sensor #ifndef TEST BMESensor.begin(); // initalize bme280 sensor updateBme(true); #endif // delay(1000); ecocute.request(); aircon.request(); } time_t rtcTest = 0; float wattHourTest = 0.0; unsigned long preMeas = millis(); unsigned long preView = preMeas; #define INTERVAL (120 * 1000) #define VIEW_INTERVAL (1000) void loop() { CONNECT_STATE curState = sm.getConnectState(); if (curState != preState) { // スマートメータ 状態変化 switch (curState) { case CONNECT_STATE::CONNECTED: btnA.enable("TERM"); break; case CONNECT_STATE::DISCONNECTED: btnA.enable("JOIN"); break; case CONNECT_STATE::CONNECTING: btnA.disable("CONNECTING"); for (int i = 0; i < 7; i++) sd_log.out(sm.getScnannedParam(i)); break; case CONNECT_STATE::SCANNING: btnA.disable("SCANNING"); break; } } #ifndef TEST if (curState == CONNECT_STATE::CONNECTED || curState == CONNECT_STATE::CONNECTING) { bp35c0_polling(); } #else bp35c0_polling(); #endif preState = curState; long cur = millis(); long d = cur - preMeas; if (d < 0) d += ULONG_MAX; if (d >= INTERVAL) // debug { preMeas = cur; char buf[64]; snprintf(buf, sizeof(buf), "%ld -> %ld, memory(%d)", preMeas, d, xPortGetFreeHeapSize()); debugView.output(buf); // BME280 #ifndef TEST updateBme(true); #endif // smartmeter if (curState == CONNECT_STATE::CONNECTED) { // 要求コマンド送信 sm.request(); } // ecocute ecocute.request(); // aircon aircon.request(); } char buf[64]; if (bEco) { dataStore.setEcoPower(ecocute.getPower()); dataStore.setEcoTank(ecocute.getTank()); snprintf(buf, sizeof(buf), "ecocute power=%ld,powerSum=%ld,tank=%ld", ecocute.getPower(), ecocute.getTotalPower(), ecocute.getTank()); debugView.output(buf); int res = influx.write(buf); debugView.output(res); bEco = false; } if (bAir) { dataStore.setAirPower(aircon.getPower()); dataStore.setAirTempOut(aircon.getTempOut()); dataStore.setAirTempRoom(aircon.getTempRoom()); snprintf(buf, sizeof(buf), "aircon power=%ld,tempOut=%ld,tempRoom=%ld", aircon.getPower(), aircon.getTempOut(), aircon.getTempRoom()); debugView.output(buf); int res = influx.write(buf); debugView.output(res); bAir = false; } d = cur - preView; if (d < 0) d += ULONG_MAX; if (d >= VIEW_INTERVAL) { preView = cur; headView.update(); viewController.update(); } if (btnA.isEnable() && btnA.getButton()->wasPressed()) { switch (curState) { case CONNECT_STATE::CONNECTED: // 切断 sm.disconnect(); break; case CONNECT_STATE::DISCONNECTED: // 接続 xTaskCreate(&bp35c0_monitoring_task, "bp35c0r", 4096, NULL, 5, NULL); break; case CONNECT_STATE::CONNECTING: break; case CONNECT_STATE::SCANNING: break; } } else if (btnB.isEnable() && btnB.getButton()->wasPressed()) { rtc.adjust(); btnB.disable("NTP"); } else if (btnC.isEnable() && btnC.getButton()->wasPressed()) { viewController.changeNext(); btnC.enable(viewController.getNextKey()); } delay(1); M5.update(); }
24.132353
141
0.657323
katsumin
d8df3c1daffa3d064eeca194082eebff5b91e34e
311
cpp
C++
legion/engine/llri-dx/llri.cpp
Rythe-Interactive/Legion-LLRI
e0cc449cc8c2ba0701a73b8c07b80ccfd8f20477
[ "MIT" ]
16
2021-09-10T18:11:37.000Z
2022-01-26T06:28:51.000Z
legion/engine/llri-dx/llri.cpp
Rythe-Interactive/Legion-LLRI
e0cc449cc8c2ba0701a73b8c07b80ccfd8f20477
[ "MIT" ]
13
2021-09-12T16:28:47.000Z
2022-02-07T19:34:01.000Z
legion/engine/llri-dx/llri.cpp
Rythe-Interactive/Legion-LLRI
e0cc449cc8c2ba0701a73b8c07b80ccfd8f20477
[ "MIT" ]
1
2021-08-15T23:35:32.000Z
2021-08-15T23:35:32.000Z
/** * @file llri.cpp * @copyright 2021-2021 Leon Brands. All rights served. * @license: https://github.com/Legion-Engine/Legion-LLRI/blob/main/LICENSE */ #include <llri/llri.hpp> namespace llri { [[nodiscard]] implementation getImplementation() { return implementation::DirectX12; } }
19.4375
75
0.678457
Rythe-Interactive
d8e4153c4406f004e7438070813d1b8ed7ad35ac
958
cpp
C++
dev/test/simple_start_stop/main.cpp
Stiffstream/mosquitto_transport
b7bd85746b7b5ba9f96a9128a12292ebb0604454
[ "BSD-3-Clause" ]
3
2020-01-25T12:49:55.000Z
2021-11-08T10:42:09.000Z
dev/test/simple_start_stop/main.cpp
Stiffstream/mosquitto_transport
b7bd85746b7b5ba9f96a9128a12292ebb0604454
[ "BSD-3-Clause" ]
null
null
null
dev/test/simple_start_stop/main.cpp
Stiffstream/mosquitto_transport
b7bd85746b7b5ba9f96a9128a12292ebb0604454
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <mosquitto_transport/a_transport_manager.hpp> #include <so_5/all.hpp> using namespace std::chrono_literals; void do_test() { mosquitto_transport::lib_initializer_t mosq_lib; so_5::launch( [&mosq_lib]( auto & env ) { env.introduce_coop( [&mosq_lib]( so_5::coop_t & coop ) { using namespace mosquitto_transport; coop.make_agent< a_transport_manager_t >( std::ref(mosq_lib), connection_params_t{ "test-client", "localhost", 1883u, 5u }, spdlog::stdout_logger_mt( "mosqt" ) ); struct stop : so_5::signal_t {}; auto stopper = coop.define_agent(); stopper.on_start( [stopper]{ so_5::send_delayed< stop >( stopper, 15s ); } ); stopper.event< stop >( stopper, [&coop] { coop.deregister_normally(); } ); } ); } ); } int main() { try { do_test(); } catch( const std::exception & ex ) { std::cerr << "Oops! " << ex.what() << std::endl; } }
19.16
58
0.627349
Stiffstream
d8e694d86bf0df4afeb16f257b966127ed42f3fd
867
cpp
C++
projects/abuild/cache/abi.cpp
agnesoft/adev-alt
3df0329939e3048bbf5db252efb5f74de9c0f061
[ "Apache-2.0" ]
null
null
null
projects/abuild/cache/abi.cpp
agnesoft/adev-alt
3df0329939e3048bbf5db252efb5f74de9c0f061
[ "Apache-2.0" ]
null
null
null
projects/abuild/cache/abi.cpp
agnesoft/adev-alt
3df0329939e3048bbf5db252efb5f74de9c0f061
[ "Apache-2.0" ]
null
null
null
#ifndef __clang__ export module abuild.cache:abi; export import astl; #endif namespace abuild { //! The `ABI` represent the compiler toolchain //! application binary interface. export struct ABI { //! Processor architecture. enum class Architecture { //! ARM ARM, //! Intel x86 X86 }; //! Architecture's register size. enum class Bitness { //! 32 bits X32, //! 64 bits X64 }; //! Platform or operating system. enum class Platform { //! Linux Linux, //! Unix Unix, //! Windows Windows }; //! Processor architecture Architecture architecture = Architecture::X86; //! Register size Bitness bitness = Bitness::X64; //! Target platform Platform platform = Platform::Linux; }; }
15.763636
50
0.558247
agnesoft
d8e8d67e6a22e721c27a4f9ef527f81eb4c477a2
1,201
cpp
C++
9999/1197.cpp
rmagur1203/acmicpc
83c4018548e42fc758b3858e8290990701e69e73
[ "MIT" ]
null
null
null
9999/1197.cpp
rmagur1203/acmicpc
83c4018548e42fc758b3858e8290990701e69e73
[ "MIT" ]
null
null
null
9999/1197.cpp
rmagur1203/acmicpc
83c4018548e42fc758b3858e8290990701e69e73
[ "MIT" ]
1
2022-01-11T05:03:52.000Z
2022-01-11T05:03:52.000Z
#include <iostream> #include <tuple> #include <vector> #include <queue> using namespace std; vector<pair<int, int>> graph[10001]; int visited[10001]; int main() { cin.tie(NULL)->sync_with_stdio(false); int V, E; cin >> V >> E; for (int i = 0; i < E; i++) { int s, e, w; cin >> s >> e >> w; graph[s].push_back(make_pair(e, w)); graph[e].push_back(make_pair(s, w)); } int cost = 0; vector<int> mst_nodes; vector<pair<int, int>> mst_edges; priority_queue<tuple<int, int, int>> pq; mst_nodes.push_back(1); visited[1] = true; for (int i = 0; i < graph[1].size(); i++){ pq.push(make_tuple(-graph[1][i].second, 1, graph[1][i].first)); } while (!pq.empty()) { int w = -get<0>(pq.top()); int s = get<1>(pq.top()); int e = get<2>(pq.top()); pq.pop(); if (visited[e]) continue; mst_nodes.push_back(e); mst_edges.push_back(make_pair(s, e)); for (int i = 0; i < graph[e].size(); i++){ pq.push(make_tuple(-graph[e][i].second, e, graph[e][i].first)); } cost += w; visited[e] = true; } cout << cost; }
24.510204
75
0.512073
rmagur1203
d8e99a8f9376036a394248698698d57d76039d1d
12,337
cpp
C++
GraphicsSandbox/Engine.cpp
UberCelloCzar/GraphicsSandbox
3a96f99ca3693a67fdff69fdf7d338e8e5d21086
[ "MIT" ]
null
null
null
GraphicsSandbox/Engine.cpp
UberCelloCzar/GraphicsSandbox
3a96f99ca3693a67fdff69fdf7d338e8e5d21086
[ "MIT" ]
null
null
null
GraphicsSandbox/Engine.cpp
UberCelloCzar/GraphicsSandbox
3a96f99ca3693a67fdff69fdf7d338e8e5d21086
[ "MIT" ]
null
null
null
#include "Engine.h" #include "D11Graphics.h" Engine::Engine() { } Engine::~Engine() { } void Engine::Initialize() { assetManager = new AssetManager(); graphics = new D11Graphics(); // Create whichever graphics system we're using and initialize it graphics->Initialize(); GameSetup(); __int64 perfFreq; QueryPerformanceFrequency((LARGE_INTEGER*)&perfFreq); perfCounterSeconds = 1.0 / (double)perfFreq; __int64 now; QueryPerformanceCounter((LARGE_INTEGER*)&now); startTime = now; currentTime = now; previousTime = now; } void Engine::GameSetup() { /* Load Shaders */ assetManager->LoadVertexShader((char*)"BaseVS", "BaseVertexShader", graphics); assetManager->LoadPixelShader((char*)"BasePS", "BasePixelShader", graphics); assetManager->LoadVertexShader((char*)"SkyboxVS", "SkyboxVertexShader", graphics); assetManager->LoadPixelShader((char*)"SkyboxPS", "SkyboxPixelShader", graphics); /* Initialize Camera */ camera = new Camera(); camera->position = XMFLOAT3(0.f, 0.f, -10.f); camera->direction = XMFLOAT3(0.f, 0.f, 1.f); camera->up = XMFLOAT3(0.f, 1.f, 0.f); camera->rotationRads = XMFLOAT2(0.f, 0.f); //camera->rotationMatrix = glm::rotate(glm::rotate(glm::mat4(1.f), -.1f, glm::vec3(1, 0, 0)), .1f, glm::vec3(0,1,0)); // Identity matrix XMStoreFloat4(&camera->rotationQuaternion, XMQuaternionIdentity()); CalculateProjectionMatrix(); CalculateProjViewMatrix(); /* Load Models */ assetManager->LoadModel((char*)"Cube", "cube.obj", graphics); assetManager->LoadModel((char*)"Cone", "cone.obj", graphics); assetManager->LoadModel((char*)"Sphere", "sphere.obj", graphics); assetManager->LoadModel((char*)"Cerberus", "Cerberus.fbx", graphics); /* Load Textures */ { assetManager->LoadDDSTexture((char*)"SM_EnvMap", "SnowMachineEnv", graphics); assetManager->LoadDDSTexture((char*)"SM_IrrMap", "SnowMachineIrr", graphics); assetManager->LoadDDSTexture((char*)"SM_SpecMap", "SnowMachineSpec", graphics); assetManager->LoadDDSTexture((char*)"BRDF_LUT", "SnowMachineBrdf", graphics); assetManager->LoadWICTexture((char*)"M_100Metal", "solidgoldmetal.png", graphics); assetManager->LoadWICTexture((char*)"M_0Metal", "nometallic.png", graphics); assetManager->LoadWICTexture((char*)"A_Gold", "solidgoldbase.png", graphics); assetManager->LoadWICTexture((char*)"N_Plain", "solidgoldnormal.png", graphics); assetManager->LoadWICTexture((char*)"R_Gold", "solidgoldroughness.png", graphics); assetManager->LoadWICTexture((char*)"A_Snow", "Snow_001_COLOR.png", graphics); assetManager->LoadWICTexture((char*)"N_Snow", "Snow_001_NORM.png", graphics); assetManager->LoadWICTexture((char*)"R_Snow", "Snow_001_ROUGH.png", graphics); assetManager->LoadWICTexture((char*)"AO_Snow", "Snow_001_OCC.png", graphics); assetManager->LoadWICTexture((char*)"A_Rock", "holey-rock1-albedo.png", graphics); assetManager->LoadWICTexture((char*)"AO_Rock", "holey-rock1-ao.png", graphics); assetManager->LoadWICTexture((char*)"N_Rock", "holey-rock1-normal-ue.png", graphics); assetManager->LoadWICTexture((char*)"R_Rock", "holey-rock1-roughness.png", graphics); assetManager->LoadWICTexture((char*)"A_Cerberus", "Cerberus_A.jpg", graphics); assetManager->LoadWICTexture((char*)"N_Cerberus", "Cerberus_N.jpg", graphics); assetManager->LoadWICTexture((char*)"M_Cerberus", "Cerberus_M.jpg", graphics); assetManager->LoadWICTexture((char*)"R_Cerberus", "Cerberus_R.jpg", graphics); assetManager->LoadWICTexture((char*)"AO_Cerberus", "Cerberus_AO.jpg", graphics); } /* Create Game Objects */ GameEntity* cube = new GameEntity(); // Entity 0 should always be a unit cube cube->position = XMFLOAT3(0.f, 0.f, 0.f); cube->scale = XMFLOAT3(1.f, 1.f, 1.f); XMStoreFloat4(&cube->rotationQuaternion, XMQuaternionIdentity()); cube->modelKey = "Cube"; cube->albedoKey = "A_Gold"; cube->normalKey = "N_Plain"; cube->metallicKey = "M_100Metal"; cube->roughnessKey = "R_Gold"; cube->aoKey = "M_100Metal"; cube->vertexShaderConstants = {}; GameEntity* snowball = new GameEntity(); snowball->position = XMFLOAT3(0.f, 0.f, 5.0f); snowball->scale = XMFLOAT3(2.f, 2.f, 2.f); XMStoreFloat4(&snowball->rotationQuaternion, XMQuaternionIdentity()); snowball->modelKey = "Sphere"; snowball->albedoKey = "A_Snow"; snowball->normalKey = "N_Snow"; snowball->metallicKey = "M_0Metal"; snowball->roughnessKey = "R_Snow"; snowball->aoKey = "AO_Snow"; snowball->vertexShaderConstants = {}; GameEntity* rock = new GameEntity(); rock->scale = XMFLOAT3(2.f, 2.f, 2.f); rock->position = XMFLOAT3(5.f, 0.f, 5.0f); XMStoreFloat4(&rock->rotationQuaternion, XMQuaternionIdentity()); rock->modelKey = "Sphere"; rock->albedoKey = "A_Rock"; rock->normalKey = "N_Rock"; rock->metallicKey = "M_0Metal"; rock->roughnessKey = "R_Rock"; rock->aoKey = "AO_Rock"; rock->vertexShaderConstants = {}; GameEntity* block = new GameEntity(); block->scale = XMFLOAT3(1.f, 1.f, 1.f); block->position = XMFLOAT3(-5.f, 0.f, 5.0f); XMStoreFloat4(&block->rotationQuaternion, XMQuaternionIdentity()); block->modelKey = "Cube"; block->albedoKey = "A_Gold"; block->normalKey = "N_Plain"; block->metallicKey = "M_100Metal"; block->roughnessKey = "R_Gold"; block->aoKey = "M_100Metal"; block->vertexShaderConstants = {}; GameEntity* cerberus = new GameEntity(); cerberus->scale = XMFLOAT3(.1f, .1f, .1f); cerberus->position = XMFLOAT3(-10.f, 0.f, 20.0f); XMStoreFloat4(&cerberus->rotationQuaternion, XMQuaternionIdentity()); cerberus->modelKey = "Cerberus"; cerberus->albedoKey = "A_Cerberus"; cerberus->normalKey = "N_Cerberus"; cerberus->metallicKey = "M_Cerberus"; cerberus->roughnessKey = "R_Cerberus"; cerberus->aoKey = "AO_Cerberus"; cerberus->vertexShaderConstants = {}; entities.push_back(cube); entities.push_back(snowball); entities.push_back(rock); entities.push_back(block); entities.push_back(cerberus); for (auto& e : entities) { CalculateProjViewWorldMatrix(e); e->vertexShaderConstantBuffer = graphics->CreateConstantBuffer(&(e->vertexShaderConstants), sizeof(VShaderConstants)); } /* Create Constant Buffers */ pixelShaderConstants.cameraPosition.x = camera->position.x; pixelShaderConstants.cameraPosition.y = camera->position.y; pixelShaderConstants.cameraPosition.z = camera->position.z; pixelShaderConstants.lightPos1 = XMFLOAT3A(5.f, 2.f, 15.f); pixelShaderConstants.lightPos2 = XMFLOAT3A(10.f, 5.f, 3.f); pixelShaderConstants.lightPos3 = XMFLOAT3A(0.f, 10.f, 7.f); pixelShaderConstants.lightColor1 = XMFLOAT3A(.95f, .95f, 0.f); pixelShaderConstants.lightColor2 = XMFLOAT3A(0.f, .95f, .95f); pixelShaderConstants.lightColor3 = XMFLOAT3A(.95f, 0.f, .95f); skyboxVShaderConstants.projection = camera->projection; skyboxVShaderConstants.view = camera->view; skyboxVShaderConstants.projection = camera->projection; skyboxVShaderConstants.view = camera->view; pixelShaderConstantBuffer = graphics->CreateConstantBuffer(&pixelShaderConstants, sizeof(PShaderConstants)); skyboxVShaderConstantBuffer = graphics->CreateConstantBuffer(&skyboxVShaderConstants, sizeof(SkyboxVShaderConstants)); } void Engine::Run() { Initialize(); bool quit = false; while (!quit) { UpdateTimer(); graphics->UpdateStats(totalTime); Update(); Draw(); quit = graphics->HandleLowLevelEvents(GetAsyncKeyState(VK_ESCAPE)); } ShutDown(); } void Engine::UpdateTimer() { __int64 now; QueryPerformanceCounter((LARGE_INTEGER*)&now); // Gat current time currentTime = now; deltaTime = std::max((float)((currentTime - previousTime) * perfCounterSeconds), 0.0f); // Calc delta time, ensure it's not less than zero totalTime = (float)((currentTime - startTime) * perfCounterSeconds); // Calculate the total time from start to now previousTime = currentTime; // Save current time for next frame } void Engine::Update() { //printf("%f, %f\n", graphics->rotateBy.x, graphics->rotateBy.y); camera->Rotate(graphics->rotateBy.x, graphics->rotateBy.y); graphics->rotateBy = XMFLOAT2(0, 0); float right = 0; float forward = 0; float vert = 0; if (GetAsyncKeyState('A') & 0x8000) right -= 5 * deltaTime; if (GetAsyncKeyState('D') & 0x8000) right += 5 * deltaTime; if (GetAsyncKeyState('W') & 0x8000) forward += 5 * deltaTime; if (GetAsyncKeyState('S') & 0x8000) forward -= 5 * deltaTime; if (GetAsyncKeyState('Q') & 0x8000) vert -= 5 * deltaTime; if (GetAsyncKeyState('E') & 0x8000) vert += 5 * deltaTime; if (forward != 0 || right != 0 || vert != 0) camera->Move(forward, right, vert); } void Engine::Draw() { graphics->BeginNewFrame(); CalculateProjViewMatrix(); graphics->SetVertexShader(assetManager->GetVertexShader(std::string("BaseVS"))); graphics->SetPixelShader(assetManager->GetPixelShader(std::string("BasePS"))); pixelShaderConstants.cameraPosition.x = camera->position.x; pixelShaderConstants.cameraPosition.y = camera->position.y; pixelShaderConstants.cameraPosition.z = camera->position.z; for (size_t i = 1; i < entities.size(); ++i) { CalculateProjViewWorldMatrix(entities[i]); // Update the main matrix in the vertex shader constants area of the entity graphics->SetConstantBufferVS(entities[i]->vertexShaderConstantBuffer, &(entities[i]->vertexShaderConstants), sizeof(VShaderConstants)); graphics->SetConstantBufferPS(pixelShaderConstantBuffer, &pixelShaderConstants, sizeof(PShaderConstants)); graphics->SetTexture(assetManager->GetTexture(entities[i]->albedoKey), 0); graphics->SetTexture(assetManager->GetTexture(entities[i]->normalKey), 1); graphics->SetTexture(assetManager->GetTexture(entities[i]->metallicKey), 2); graphics->SetTexture(assetManager->GetTexture(entities[i]->roughnessKey), 3); graphics->SetTexture(assetManager->GetTexture(entities[i]->aoKey), 4); graphics->SetTexture(assetManager->GetTexture("BRDF_LUT"), 5); graphics->SetTexture(assetManager->GetTexture("SM_IrrMap"), 6); graphics->SetTexture(assetManager->GetTexture("SM_SpecMap"), 7); Model* model = assetManager->GetModel(entities[i]->modelKey); for (size_t j = 0; j < model->meshes.size(); ++j) { graphics->DrawMesh(model->meshes[j]); // If we have a bunch of the same object and we have time, I can add a render for instancing } } /* Draw the Skybox Last */ graphics->SetVertexShader(assetManager->GetVertexShader(std::string("SkyboxVS"))); graphics->SetPixelShader(assetManager->GetPixelShader(std::string("SkyboxPS"))); CalculateProjViewWorldMatrix(entities[0]); // Update the main matrix in the vertex shader constants area of the entity skyboxVShaderConstants.projection = camera->projection; skyboxVShaderConstants.view = camera->view; graphics->SetConstantBufferVS(skyboxVShaderConstantBuffer, &skyboxVShaderConstants, sizeof(SkyboxVShaderConstants)); graphics->SetTexture(assetManager->GetTexture("SM_EnvMap"), 0); Model* model = assetManager->GetModel(entities[0]->modelKey); graphics->DrawSkybox(model->meshes[0]); graphics->EndFrame(); } void Engine::ShutDown() { pixelShaderConstantBuffer->Release(); skyboxVShaderConstantBuffer->Release(); for (auto& e : entities) { e->vertexShaderConstantBuffer->Release(); delete e; } delete camera; assetManager->Destroy(); graphics->DestroyGraphics(); delete assetManager; delete graphics; } void Engine::CalculateProjectionMatrix() { XMStoreFloat4x4(&camera->projection, XMMatrixTranspose(XMMatrixPerspectiveFovLH(fov, graphics->aspectRatio, 0.1f, 1000.0f))); // Update with new w/h } void Engine::CalculateProjViewMatrix() { XMMATRIX view = XMMatrixTranspose(XMMatrixLookToLH(XMLoadFloat3(&camera->position), XMLoadFloat3(&camera->direction), XMLoadFloat3(&camera->up))); XMStoreFloat4x4(&camera->view, view); XMStoreFloat4x4(&camera->projView, XMLoadFloat4x4(&camera->projection) * view); } void Engine::CalculateProjViewWorldMatrix(GameEntity* entity) { XMMATRIX world = XMMatrixTranspose(XMMatrixScaling(entity->scale.x, entity->scale.y, entity->scale.z) * XMMatrixRotationQuaternion(XMLoadFloat4(&entity->rotationQuaternion)) * XMMatrixTranslation(entity->position.x, entity->position.y, entity->position.z)); XMStoreFloat4x4(&entity->vertexShaderConstants.world, world); XMStoreFloat4x4(&entity->vertexShaderConstants.projViewWorld, XMLoadFloat4x4(&camera->projView) * world); // This result is already transpose, as the individual matrices are transpose and the mult order is reversed }
39.415335
258
0.739078
UberCelloCzar
d8efad03b3048947dc4ca59b2e5113576c4760ba
475
cc
C++
extensions/basic/types_bucket/types_bucket.cc
blockspacer/chromium_base_conan
b4749433cf34f54d2edff52e2f0465fec8cb9bad
[ "Apache-2.0", "BSD-3-Clause" ]
6
2020-12-22T05:48:31.000Z
2022-02-08T19:49:49.000Z
extensions/basic/types_bucket/types_bucket.cc
blockspacer/chromium_base_conan
b4749433cf34f54d2edff52e2f0465fec8cb9bad
[ "Apache-2.0", "BSD-3-Clause" ]
4
2020-05-22T18:36:43.000Z
2021-05-19T10:20:23.000Z
extensions/basic/types_bucket/types_bucket.cc
blockspacer/chromium_base_conan
b4749433cf34f54d2edff52e2f0465fec8cb9bad
[ "Apache-2.0", "BSD-3-Clause" ]
2
2019-12-06T11:48:16.000Z
2021-09-16T04:44:47.000Z
#include "basic/types_bucket/types_bucket.h" // IWYU pragma: associated #include <base/memory/singleton.h> #include <base/no_destructor.h> #include <base/task/post_task.h> #include <base/threading/sequence_local_storage_slot.h> #include <base/threading/sequenced_task_runner_handle.h> #include <base/memory/ptr_util.h> #include <base/lazy_instance.h> #include <memory> namespace basic { TypesBucket::TypesBucket() {} TypesBucket::~TypesBucket() {} } // namespace basic
21.590909
71
0.772632
blockspacer
d8f3c20502910b642f3ca733a9c5e5b8a24ad94c
607
cpp
C++
C++/Dynamic_Programming/1003.cpp
SkydevilK/BOJ
4b79a258c52aca24683531d64736b91cbdfca3f2
[ "MIT" ]
null
null
null
C++/Dynamic_Programming/1003.cpp
SkydevilK/BOJ
4b79a258c52aca24683531d64736b91cbdfca3f2
[ "MIT" ]
null
null
null
C++/Dynamic_Programming/1003.cpp
SkydevilK/BOJ
4b79a258c52aca24683531d64736b91cbdfca3f2
[ "MIT" ]
null
null
null
#include<iostream> #include<cstring> using namespace std; int note_zero[41]; int note_one[41]; void dp() { for (int i = 2; i < 41; ++i) { note_zero[i] = note_zero[i - 2] + note_zero[i - 1]; note_one[i] = note_one[i - 2] + note_one[i - 1]; } } int main(void) { ios::sync_with_stdio(false); memset(note_zero, -1, sizeof(note_zero)); memset(note_one, -1, sizeof(note_one)); note_zero[0] = 1; note_one[0] = 0; note_zero[1] = 0; note_one[1] = 1; dp(); int T; cin >> T; for (int test = 1; test <= T; ++test) { int N = 0; cin >> N; cout << note_zero[N] << " " << note_one[N] << "\n"; } }
18.393939
53
0.578254
SkydevilK
d8f5827ed2e61a8b336526ab372312d3a21186ff
666
hpp
C++
Canteen.hpp
dianabacon/stalag-escape
445085f1d95bec4190f29d72843bf4878d8f45ac
[ "MIT" ]
null
null
null
Canteen.hpp
dianabacon/stalag-escape
445085f1d95bec4190f29d72843bf4878d8f45ac
[ "MIT" ]
null
null
null
Canteen.hpp
dianabacon/stalag-escape
445085f1d95bec4190f29d72843bf4878d8f45ac
[ "MIT" ]
null
null
null
/********************************************************************* ** Program Filename: Canteen.cpp ** Author: Diana Bacon ** Date: 2015-12-05 ** Description: Definition of the Canteen class. Functions and data ** related to the derived class for Canteen spaces. *********************************************************************/ #ifndef Canteen_hpp #define Canteen_hpp #include <iostream> #include "Space.hpp" class Canteen : public Space { private: public: Canteen(); // default constructor bool enter(Airman* const); // special function ~Canteen() {}; // destructor }; #endif /* Canteen_hpp */
25.615385
71
0.510511
dianabacon
d8f5f664fe03cf939591e9af0b3f1e7f625f0439
2,430
cc
C++
tests/libtests/bc/obsolete/TestBoundaryConditionPoints.cc
Grant-Block/pylith
f6338261b17551eba879da998a5aaf2d91f5f658
[ "MIT" ]
93
2015-01-08T16:41:22.000Z
2022-02-25T13:40:02.000Z
tests/libtests/bc/obsolete/TestBoundaryConditionPoints.cc
Grant-Block/pylith
f6338261b17551eba879da998a5aaf2d91f5f658
[ "MIT" ]
277
2015-02-20T16:27:35.000Z
2022-03-30T21:13:09.000Z
tests/libtests/bc/obsolete/TestBoundaryConditionPoints.cc
Grant-Block/pylith
f6338261b17551eba879da998a5aaf2d91f5f658
[ "MIT" ]
71
2015-03-24T12:11:08.000Z
2022-03-03T04:26:02.000Z
// -*- C++ -*- // // ---------------------------------------------------------------------- // // Brad T. Aagaard, U.S. Geological Survey // Charles A. Williams, GNS Science // Matthew G. Knepley, University of Chicago // // This code was developed as part of the Computational Infrastructure // for Geodynamics (http://geodynamics.org). // // Copyright (c) 2010-2017 University of California, Davis // // See COPYING for license information. // // ---------------------------------------------------------------------- // #include <portinfo> #include "TestBoundaryConditionPoints.hh" // Implementation of class methods #include "pylith/bc/PointForce.hh" // USES PointForce #include "data/PointForceDataTri3.hh" // USES PointForceDataTri3 #include "pylith/topology/Mesh.hh" // USES Mesh #include "pylith/topology/MeshOps.hh" // USES MeshOps::nondimensionalize() #include "pylith/topology/Stratum.hh" // USES Stratum #include "pylith/meshio/MeshIOAscii.hh" // USES MeshIOAscii #include "spatialdata/geocoords/CSCart.hh" // USES CSCart #include "spatialdata/units/Nondimensional.hh" // USES Nondimensional // ---------------------------------------------------------------------- CPPUNIT_TEST_SUITE_REGISTRATION( pylith::bc::TestBoundaryConditionPoints ); // ---------------------------------------------------------------------- // Test _getPoints(). void pylith::bc::TestBoundaryConditionPoints::testGetPoints(void) { // testGetPoints PYLITH_METHOD_BEGIN; topology::Mesh mesh; PointForce bc; PointForceDataTri3 data; meshio::MeshIOAscii iohandler; iohandler.filename(data.meshFilename); iohandler.read(&mesh); spatialdata::geocoords::CSCart cs; spatialdata::units::Nondimensional normalizer; cs.setSpaceDim(mesh.dimension()); cs.initialize(); mesh.coordsys(&cs); topology::MeshOps::nondimensionalize(&mesh, normalizer); bc.label(data.label); bc.BoundaryConditionPoints::_getPoints(mesh); const PetscDM dmMesh = mesh.dmMesh();CPPUNIT_ASSERT(dmMesh); topology::Stratum heightStratum(dmMesh, topology::Stratum::HEIGHT, 0); const PetscInt numCells = heightStratum.size(); const size_t numPoints = data.numForcePts; // Check points const int offset = numCells; CPPUNIT_ASSERT_EQUAL(numPoints, bc._points.size()); for (int i=0; i < numPoints; ++i) CPPUNIT_ASSERT_EQUAL(data.forcePoints[i]+offset, bc._points[i]); PYLITH_METHOD_END; } // testGetPoints // End of file
30.759494
76
0.654321
Grant-Block
d8f72b9194e0af9370f4ece7e39abd1393eef4a3
567
hpp
C++
src/palm/batch.hpp
leezhenghui/Mushroom
8aed2bdd80453d856145925d067bef5ed9d10ee0
[ "BSD-3-Clause" ]
351
2016-10-12T14:06:09.000Z
2022-03-24T14:53:54.000Z
src/palm/batch.hpp
leezhenghui/Mushroom
8aed2bdd80453d856145925d067bef5ed9d10ee0
[ "BSD-3-Clause" ]
7
2017-03-07T01:49:16.000Z
2018-07-27T08:51:54.000Z
src/palm/batch.hpp
UncP/Mushroom
8aed2bdd80453d856145925d067bef5ed9d10ee0
[ "BSD-3-Clause" ]
62
2016-10-31T12:46:45.000Z
2021-12-28T11:25:26.000Z
/** * > Author: UncP * > Github: www.github.com/UncP/Mushroom * > License: BSD-3 * > Time: 2018-7-28 15:33:00 **/ #ifndef _BATCH_HPP_ #define _BATCH_HPP_ #include "../include/utility.hpp" namespace Mushroom { class KeySlice; class Batch : private NoCopy { public: static uint32_t Size; static void SetSize(uint32_t size); Batch(); ~Batch(); void SetKeySlice(uint32_t idx, const char *key); const KeySlice* GetKeySlice(uint32_t idx) const; private: KeySlice **batch_; }; } // Mushroom #endif /* _BATCH_HPP_ */
14.921053
50
0.643739
leezhenghui
d8f7962309b2a67a96dd3175fe91d2d67fc5eb4e
10,980
cpp
C++
project/src/main.cpp
PhuNH/hpc-lab
25874fc36c87c57f2b6312d93897de9b898fbf26
[ "MIT" ]
null
null
null
project/src/main.cpp
PhuNH/hpc-lab
25874fc36c87c57f2b6312d93897de9b898fbf26
[ "MIT" ]
null
null
null
project/src/main.cpp
PhuNH/hpc-lab
25874fc36c87c57f2b6312d93897de9b898fbf26
[ "MIT" ]
null
null
null
#include <cmath> #include <iostream> #include <mpi.h> #include "tclap/CmdLine.h" #include "typedefs.h" #include "Simulator.h" #include "Grid.h" #include "InitialCondition.h" #include "RankDependentOutput.h" #include "GlobalMatrices.h" #include "microkernels.h" void computeAuxMatrices(GlobalConstants& globals) { double factorx = -globals.hx / (globals.hx * globals.hy), factory = -globals.hy / (globals.hx * globals.hy), hx_1 = 1.0 / globals.hx, hy_1 = 1.0 / globals.hy; for (int i = 0; i < GLOBAL_MATRIX_SIZE; ++i) { globals.hxKxiT[i] = (-hx_1) * (GlobalMatrices::KxiT[i]); globals.hyKetaT[i] = (-hy_1) * (GlobalMatrices::KetaT[i]); globals.hxKxi[i] = hx_1 * (GlobalMatrices::Kxi[i]); globals.hyKeta[i] = hy_1 * (GlobalMatrices::Keta[i]); globals.hxFxm0[i] = factorx * (GlobalMatrices::Fxm0[i]); globals.hxFxm1[i] = factorx * (GlobalMatrices::Fxm1[i]); globals.hyFym0[i] = factory * (GlobalMatrices::Fym0[i]); globals.hyFym1[i] = factory * (GlobalMatrices::Fym1[i]); globals.hxFxp0[i] = factorx * (GlobalMatrices::Fxp0[i]); globals.hxFxp1[i] = factorx * (GlobalMatrices::Fxp1[i]); globals.hyFyp0[i] = factory * (GlobalMatrices::Fyp0[i]); globals.hyFyp1[i] = factory * (GlobalMatrices::Fyp1[i]); } } void get_size_subgrid(int index_proc_axis, int nb_procs_axis, int grid_size, int * size_current, int * start) { int min_size = ((int) grid_size / nb_procs_axis), remainder = grid_size % nb_procs_axis; if (remainder > index_proc_axis) { *size_current = min_size + 1; *start = index_proc_axis * (*size_current); } else { *size_current = min_size; *start = remainder + index_proc_axis * min_size; } } void initScenario0(GlobalConstants& globals, LocalConstants& locals, Grid<Material>& materialGrid, Grid<DegreesOfFreedom>& degreesOfFreedomGrid) { for (int y = 0; y < globals.Y; ++y) { for (int x = 0; x < globals.X; ++x) { Material& material = materialGrid.get(x, y); material.rho0 = 1.; material.K0 = 4.; material.wavespeed = sqrt(4./1.); } } initialCondition(globals, locals, materialGrid, degreesOfFreedomGrid); } void initScenario1(GlobalConstants& globals, LocalConstants& locals, Grid<Material>& materialGrid, Grid<DegreesOfFreedom>& degreesOfFreedomGrid) { double checkerWidth = 0.25; for (int y = 0; y < globals.Y; ++y) { for (int x = 0; x < globals.X; ++x) { Material& material = materialGrid.get(x, y); int matId = static_cast<int>(x*globals.hx/checkerWidth) % 2 ^ static_cast<int>(y*globals.hy/checkerWidth) % 2; if (matId == 0) { material.rho0 = 1.; material.K0 = 2.; material.wavespeed = sqrt(2./1.); } else { material.rho0 = 2.; material.K0 = 0.5; material.wavespeed = sqrt(0.5/2.); } } } initialCondition(globals, locals, materialGrid, degreesOfFreedomGrid); } double sourceFunctionAntiderivative(double time) { return sin(time); } void initSourceTerm23(GlobalConstants& globals, SourceTerm& sourceterm) { sourceterm.quantity = 0; // pressure source double xs = 0.5; double ys = 0.5; sourceterm.x = static_cast<int>(xs / (globals.hx)); sourceterm.y = static_cast<int>(ys / (globals.hy)); double xi = (xs - sourceterm.x*globals.hx) / globals.hx; double eta = (ys - sourceterm.y*globals.hy) / globals.hy; initSourcetermPhi(xi, eta, sourceterm); sourceterm.antiderivative = sourceFunctionAntiderivative; } void initScenario2(GlobalConstants& globals, Grid<Material>& materialGrid, Grid<DegreesOfFreedom>& degreesOfFreedomGrid, SourceTerm& sourceterm) { for (int y = 0; y < globals.Y; ++y) { for (int x = 0; x < globals.X; ++x) { Material& material = materialGrid.get(x, y); material.rho0 = 1.; material.K0 = 2.; material.wavespeed = sqrt(2./1.); } } initSourceTerm23(globals, sourceterm); } void initScenario3(GlobalConstants& globals, Grid<Material>& materialGrid, Grid<DegreesOfFreedom>& degreesOfFreedomGrid, SourceTerm& sourceterm) { for (int y = 0; y < globals.Y; ++y) { for (int x = 0; x < globals.X; ++x) { Material& material = materialGrid.get(x, y); int matId; double xp = x*globals.hx; double yp = y*globals.hy; matId = (xp >= 0.25 && xp <= 0.75 && yp >= 0.25 && yp <= 0.75) ? 0 : 1; if (matId == 0) { material.rho0 = 1.; material.K0 = 2.; material.wavespeed = sqrt(2./1.); } else { material.rho0 = 2.; material.K0 = 0.5; material.wavespeed = sqrt(0.5/2.); } } } initSourceTerm23(globals, sourceterm); } int main(int argc, char** argv) { int scenario; double wfwInterval; std::string wfwBasename; GlobalConstants globals; LocalConstants locals; // Initialize MPI functions MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &locals.rank); MPI_Comm_size(MPI_COMM_WORLD, &globals.nb_procs); RankDependentOutput *rdOutput; try { TCLAP::CmdLine cmd("ADER-DG for linear acoustics.", ' ', "0.1"); TCLAP::ValueArg<int> scenarioArg("s", "scenario", "Scenario. 0=Convergence test. 1=Checkerboard.", true, 0, "int"); TCLAP::ValueArg<int> XArg("x", "x-number-of-cells", "Number of cells in x direction.", true, 0, "int"); TCLAP::ValueArg<int> YArg("y", "y-number-of-cells", "Number of cells in y direction.", true, 0, "int"); TCLAP::ValueArg<std::string> basenameArg("o", "output", "Basename of wavefield writer output. Leave empty for no output.", false, "", "string"); TCLAP::ValueArg<double> intervalArg("i", "interval", "Time interval of wavefield writer.", false, 0.1, "double"); TCLAP::ValueArg<double> timeArg("t", "end-time", "Final simulation time.", false, 0.5, "double"); TCLAP::ValueArg<int> horizontalArg("u", "hprocs", "Number of nodes - Horizontal axis", true, 0, "int"); TCLAP::ValueArg<int> verticalArg("v", "vprocs", "Number of nodes - Vertical axis", true, 0, "int"); cmd.add(scenarioArg); cmd.add(XArg); cmd.add(YArg); cmd.add(basenameArg); cmd.add(intervalArg); cmd.add(timeArg); cmd.add(horizontalArg); cmd.add(verticalArg); rdOutput = new RankDependentOutput(locals.rank); cmd.setOutput(rdOutput); cmd.parse(argc, argv); scenario = scenarioArg.getValue(); globals.X = XArg.getValue(); globals.Y = YArg.getValue(); wfwBasename = basenameArg.getValue(); wfwInterval = intervalArg.getValue(); globals.endTime = timeArg.getValue(); globals.dims_proc[0] = verticalArg.getValue(); globals.dims_proc[1] = horizontalArg.getValue(); delete rdOutput; if (scenario < 0 || scenario > 3) { if (locals.rank == 0) std::cerr << "Unknown scenario." << std::endl; return -1; } if (globals.X < 0 || globals.Y < 0) { if (locals.rank == 0) std::cerr << "X or Y smaller than 0. Does not make sense." << std::endl; return -1; } } catch (TCLAP::ArgException &e) { delete rdOutput; if (locals.rank == 0) std::cerr << "Error: " << e.error() << " for arg " << e.argId() << std::endl; return -1; } globals.hx = 1. / globals.X; globals.hy = 1. / globals.Y; // Initialize cartesian grid int periods[2] = {1, 1}, reorder = 0; MPI_Comm cartcomm; MPI_Cart_create(MPI_COMM_WORLD, 2, globals.dims_proc, periods, reorder, &cartcomm); MPI_Cart_coords(cartcomm, locals.rank, 2, locals.coords_proc); MPI_Cart_shift(cartcomm, 0, 1, &locals.adj_list[UP], &locals.adj_list[DOWN]); MPI_Cart_shift(cartcomm, 1, 1, &locals.adj_list[LEFT], &locals.adj_list[RIGHT]); MPI_Group worldGroup; MPI_Comm_group(MPI_COMM_WORLD, &worldGroup); for (int i = 0; i < 4; i++) MPI_Group_incl(worldGroup, 1, &locals.adj_list[i], &(locals.nbGroups[i])); // Initializing locals variable get_size_subgrid(locals.coords_proc[0], globals.dims_proc[0], globals.Y, &locals.elts_size[1], &locals.start_elts[1]); get_size_subgrid(locals.coords_proc[1], globals.dims_proc[1], globals.X, &locals.elts_size[0], &locals.start_elts[0]); //printf("Rank : %d -- iproc = %d -- jproc = %d -- (xstart = %d, ystart = %d) -- (xsize = %d, ysize = %d) \n",locals.rank,locals.coords_proc [0],locals.coords_proc[1],locals.start_elts[0],locals.start_elts[1],locals.elts_size[0],locals.elts_size[1]); Grid<DegreesOfFreedom> degreesOfFreedomGrid(locals.elts_size[0], locals.elts_size[1]); // Change with MPI structure Grid<Material> materialGrid(globals.X, globals.Y); // Each node stores all : could be optimized - to see later SourceTerm sourceterm; switch (scenario) { case 0: initScenario0(globals, locals, materialGrid, degreesOfFreedomGrid); break; case 1: initScenario1(globals, locals, materialGrid, degreesOfFreedomGrid); break; case 2: initScenario2(globals, materialGrid, degreesOfFreedomGrid, sourceterm); break; case 3: initScenario3(globals, materialGrid, degreesOfFreedomGrid, sourceterm); break; default: break; } globals.maxTimestep = determineTimestep(globals.hx, globals.hy, materialGrid); WaveFieldWriter waveFieldWriter(wfwBasename, globals, locals, wfwInterval, static_cast<int>(ceil( sqrt(NUMBER_OF_BASIS_FUNCTIONS) ))); double t1, t2; t1 = MPI_Wtime(); computeAuxMatrices(globals); globals.dgemm_beta_0 = microkernels[(CONVERGENCE_ORDER-2)*2]; globals.dgemm_beta_1 = microkernels[(CONVERGENCE_ORDER-2)*2+1]; int steps = simulate(globals, locals, materialGrid, degreesOfFreedomGrid, waveFieldWriter, sourceterm); t2 = MPI_Wtime(); if (scenario == 0) { double local_L2error_squared[NUMBER_OF_QUANTITIES]; L2error_squared(globals.endTime, globals, locals, materialGrid, degreesOfFreedomGrid, local_L2error_squared); //printf("rank %d p %f vx %f vy %f\n", locals.rank, local_L2error_squared[0], local_L2error_squared[1], local_L2error_squared[2]); double global_L2error_squared[NUMBER_OF_QUANTITIES]; MPI_Reduce(local_L2error_squared,global_L2error_squared,NUMBER_OF_QUANTITIES,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD); if (locals.rank == 0) { square_root_array(global_L2error_squared,NUMBER_OF_QUANTITIES); std::cout << "L2 error analysis" << std::endl << "=================" << std::endl; std::cout << "Pressue (p): " << global_L2error_squared[0] << std::endl; std::cout << "X-Velocity (u): " << global_L2error_squared[1] << std::endl; std::cout << "Y-Velocity (v): " << global_L2error_squared[2] << std::endl; } } if (locals.rank == 0) std::cout << "Total number of timesteps: " << steps << std::endl; MPI_Group_free(&worldGroup); for (int i = 0; i < 4; i++) MPI_Group_free(&locals.nbGroups[i]); MPI_Finalize(); printf("Simulation time: %f s\n", t2 - t1 ); return 0; }
37.220339
252
0.650546
PhuNH
d8f910b00400f6a61a3f8ce43feb3f07939971c1
912
cpp
C++
test/bench2_rosenbrock.cpp
marcorushdy/realGen
2441cbb81d034137926c0f50c7dcdc6777329b76
[ "MIT" ]
16
2017-04-23T23:24:08.000Z
2021-03-12T21:38:28.000Z
test/bench2_rosenbrock.cpp
marcorushdy/realGen
2441cbb81d034137926c0f50c7dcdc6777329b76
[ "MIT" ]
null
null
null
test/bench2_rosenbrock.cpp
marcorushdy/realGen
2441cbb81d034137926c0f50c7dcdc6777329b76
[ "MIT" ]
6
2017-06-14T11:50:37.000Z
2019-05-16T20:09:07.000Z
#include "testcommon.h" #include "fitnessfunction.h" class RosenbrockFitness : public FitnessFunction { public: RosenbrockFitness() {} double eval(const RealGenotype &g) { double dx1 = g.gene[0]*g.gene[0]-g.gene[1]; double dx2 = 1.0 - g.gene[0]; return 100.0*dx1*dx1+dx2*dx2; } }; void bench2_rosenbrock(RealGenOptions opt, GAResults &results) { vector<float> LB = { -2.048, -2.048 }; vector<float> UB = { 2.048, 2.048}; RosenbrockFitness *myFitnessFunction = new RosenbrockFitness(); strcpy(results.name, "Rosenbrock"); results.maxIter = 5000; results.Np = 200; opt.setPopulationSize(results.Np); opt.setChromosomeSize(2); opt.setBounds(LB, UB); RealGen ga(opt); ga.setFitnessFunction(myFitnessFunction); testRealGen(ga, results.maxIter, 1e-4, results); delete myFitnessFunction; }
26.823529
68
0.639254
marcorushdy
d8febc737fe1416c65cd87a7bace3dc194b673ca
3,369
cpp
C++
source_code/system_sys/source_code/gui/Sys_Output_Flag_Dia.cpp
dabachma/ProMaIDes_src
3fa6263c46f89abbdb407f2e1643843d54eb6ccc
[ "BSD-3-Clause" ]
null
null
null
source_code/system_sys/source_code/gui/Sys_Output_Flag_Dia.cpp
dabachma/ProMaIDes_src
3fa6263c46f89abbdb407f2e1643843d54eb6ccc
[ "BSD-3-Clause" ]
null
null
null
source_code/system_sys/source_code/gui/Sys_Output_Flag_Dia.cpp
dabachma/ProMaIDes_src
3fa6263c46f89abbdb407f2e1643843d54eb6ccc
[ "BSD-3-Clause" ]
null
null
null
#include "Sys_Headers_Precompiled.h" //#include "Sys_Output_Flag_Dia.h" // Constructor Sys_Output_Flag_Dia::Sys_Output_Flag_Dia(QWidget *parent) : QDialog(parent){ this->old_flag=false; this->new_flag=false; ui.setupUi(this); ui.checkBox->setChecked(this->old_flag); QObject::connect(ui.okButton, SIGNAL(clicked()), this, SLOT(accept())); QObject::connect(ui.cancelButton, SIGNAL(clicked()), this, SLOT(reject())); //count the memory Sys_Memory_Count::self()->add_mem((sizeof(Sys_Output_Flag_Dia)), _sys_system_modules::SYS_SYS); } // Destructor Sys_Output_Flag_Dia::~Sys_Output_Flag_Dia(void){ Sys_Memory_Count::self()->minus_mem(sizeof(Sys_Output_Flag_Dia), _sys_system_modules::SYS_SYS); } //___________ //public //Set the text for which moduls the outputflag should be changed void Sys_Output_Flag_Dia::set_txt_modul_type(_sys_system_modules type){ QIcon icon; switch (type){ case _sys_system_modules::SYS_SYS: this->text = "Change the flag for the Modul SYS"; ui.typeLineEdit->setText(text); ui.typeLineEdit->setReadOnly(true); icon.addFile(":prom_icon"); this->setWindowIcon(icon); break; case _sys_system_modules::FPL_SYS: this->text = "Change the flag for the Modul FPL"; ui.typeLineEdit->setText(text); ui.typeLineEdit->setReadOnly(true); icon.addFile(":fpl_icon"); this->setWindowIcon(icon); break; case _sys_system_modules::HYD_SYS: this->text = "Change the flag for the Modul HYD"; ui.typeLineEdit->setText(text); ui.typeLineEdit->setReadOnly(true); icon.addFile(":hyd_icon"); this->setWindowIcon(icon); break; case _sys_system_modules::MADM_SYS: this->text = "Change the flag for the Modul MADM"; ui.typeLineEdit->setText(text); ui.typeLineEdit->setReadOnly(true); icon.addFile(":madm_icon"); this->setWindowIcon(icon); break; case _sys_system_modules::DAM_SYS: this->text = "Change the flag for the Modul DAM"; ui.typeLineEdit->setText(text); ui.typeLineEdit->setReadOnly(true); icon.addFile(":dam_icon"); this->setWindowIcon(icon); break; case _sys_system_modules::RISK_SYS: this->text = "Change the flag for the Modul RISK"; ui.typeLineEdit->setText(text); ui.typeLineEdit->setReadOnly(true); icon.addFile(":risk_icon"); this->setWindowIcon(icon); break; case _sys_system_modules::ALT_SYS: this->text = "Change the flag for the Modul ALT"; ui.typeLineEdit->setText(text); ui.typeLineEdit->setReadOnly(true); icon.addFile(":alt_icon"); this->setWindowIcon(icon); break; case _sys_system_modules::COST_SYS: this->text = "Change the flag for the Modul COST"; ui.typeLineEdit->setText(text); ui.typeLineEdit->setReadOnly(true); icon.addFile(":cost_icon"); this->setWindowIcon(icon); break; default: this->text = "Change the flag for the Modul NOTKNOWN"; ui.typeLineEdit->setText(text); ui.typeLineEdit->setReadOnly(true); } } //Set the current output flag void Sys_Output_Flag_Dia::set_current_flag(const bool flag){ this->old_flag=flag; ui.checkBox->setChecked(this->old_flag); } //Make the dialog and get the new detailed flag bool Sys_Output_Flag_Dia::get_new_detailed_flag(void){ int decision =this->exec(); //rejected if(decision ==0){ return this->old_flag; } //accepted else{ this->new_flag=ui.checkBox->isChecked(); return this->new_flag; } }
30.908257
96
0.724844
dabachma
2b045b93305594bb73add275c035977d2754913a
322
cpp
C++
compendium/test_bundles/TestBundleDSDependentOptional/src/ServiceImpl.cpp
fmilano/CppMicroServices
b7e79edb558a63e45f6788e4a8b4e787cf956689
[ "Apache-2.0" ]
588
2015-10-07T15:55:08.000Z
2022-03-29T00:35:44.000Z
compendium/test_bundles/TestBundleDSDependentOptional/src/ServiceImpl.cpp
fmilano/CppMicroServices
b7e79edb558a63e45f6788e4a8b4e787cf956689
[ "Apache-2.0" ]
459
2015-10-05T23:29:59.000Z
2022-03-29T14:13:37.000Z
compendium/test_bundles/TestBundleDSDependentOptional/src/ServiceImpl.cpp
fmilano/CppMicroServices
b7e79edb558a63e45f6788e4a8b4e787cf956689
[ "Apache-2.0" ]
218
2015-11-04T08:19:48.000Z
2022-03-24T02:17:08.000Z
#include "ServiceImpl.hpp" namespace dependent { TestBundleDSDependentOptionalImpl::TestBundleDSDependentOptionalImpl( const std::shared_ptr<test::TestBundleDSUpstreamDependency>& c) : test::TestBundleDSDependent() , ref(c) {} TestBundleDSDependentOptionalImpl::~TestBundleDSDependentOptionalImpl() = default; }
24.769231
73
0.807453
fmilano
2b0b1a3c8acf26e971ecac158c0b31e96a01c8c3
3,581
cpp
C++
src/orocos_kinematics_dynamics/orocos_kdl/src/treeiksolverpos_nr_jl.cpp
matchRos/simulation_multirobots
286c5add84d521ad371b2c8961dea872c34e7da2
[ "BSD-2-Clause" ]
742
2017-07-05T02:49:36.000Z
2022-03-30T12:55:43.000Z
src/orocos_kinematics_dynamics/orocos_kdl/src/treeiksolverpos_nr_jl.cpp
matchRos/simulation_multirobots
286c5add84d521ad371b2c8961dea872c34e7da2
[ "BSD-2-Clause" ]
73
2017-07-06T12:50:51.000Z
2022-03-07T08:07:07.000Z
src/orocos_kinematics_dynamics/orocos_kdl/src/treeiksolverpos_nr_jl.cpp
matchRos/simulation_multirobots
286c5add84d521ad371b2c8961dea872c34e7da2
[ "BSD-2-Clause" ]
425
2017-07-04T22:03:29.000Z
2022-03-29T06:59:06.000Z
// Copyright (C) 2007-2008 Ruben Smits <ruben dot smits at mech dot kuleuven dot be> // Copyright (C) 2008 Mikael Mayer // Copyright (C) 2008 Julia Jesse // Version: 1.0 // Author: Ruben Smits <ruben dot smits at mech dot kuleuven dot be> // Maintainer: Ruben Smits <ruben dot smits at mech dot kuleuven dot be> // URL: http://www.orocos.org/kdl // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "treeiksolverpos_nr_jl.hpp" namespace KDL { TreeIkSolverPos_NR_JL::TreeIkSolverPos_NR_JL(const Tree& _tree, const std::vector<std::string>& _endpoints, const JntArray& _q_min, const JntArray& _q_max, TreeFkSolverPos& _fksolver, TreeIkSolverVel& _iksolver, unsigned int _maxiter, double _eps) : tree(_tree), q_min(_q_min), q_max(_q_max), iksolver(_iksolver), fksolver(_fksolver), delta_q(tree.getNrOfJoints()), endpoints(_endpoints), maxiter(_maxiter), eps(_eps) { for (size_t i = 0; i < endpoints.size(); i++) { frames.insert(Frames::value_type(endpoints[i], Frame::Identity())); delta_twists.insert(Twists::value_type(endpoints[i], Twist::Zero())); } } double TreeIkSolverPos_NR_JL::CartToJnt(const JntArray& q_init, const Frames& p_in, JntArray& q_out) { q_out = q_init; //First check if all elements in p_in are available: for(Frames::const_iterator f_des_it=p_in.begin();f_des_it!=p_in.end();++f_des_it) if(frames.find(f_des_it->first)==frames.end()) return -2; unsigned int k=0; while(++k <= maxiter) { for (Frames::const_iterator f_des_it=p_in.begin();f_des_it!=p_in.end();++f_des_it){ //Get all iterators for this endpoint Frames::iterator f_it = frames.find(f_des_it->first); Twists::iterator delta_twist = delta_twists.find(f_des_it->first); fksolver.JntToCart(q_out, f_it->second, f_it->first); delta_twist->second = diff(f_it->second, f_des_it->second); } double res = iksolver.CartToJnt(q_out, delta_twists, delta_q); if (res < eps) return res; Add(q_out, delta_q, q_out); for (unsigned int j = 0; j < q_min.rows(); j++) { if (q_out(j) < q_min(j)) q_out( j) = q_min(j); else if (q_out(j) > q_max(j)) q_out( j) = q_max(j); } } if (k <= maxiter) return 0; else return -3; } TreeIkSolverPos_NR_JL::~TreeIkSolverPos_NR_JL() { } }//namespace
42.129412
106
0.586987
matchRos
2b0c787652070af035f365871a15e179c7f10756
505
cpp
C++
src/test/config/schema.cpp
mpoeter/config
9a20b1dde685d42190310fa51ecd271e66d90ea0
[ "MIT" ]
1
2020-03-17T20:47:52.000Z
2020-03-17T20:47:52.000Z
src/test/config/schema.cpp
mpoeter/config
9a20b1dde685d42190310fa51ecd271e66d90ea0
[ "MIT" ]
null
null
null
src/test/config/schema.cpp
mpoeter/config
9a20b1dde685d42190310fa51ecd271e66d90ea0
[ "MIT" ]
null
null
null
// Copyright (c) 2019-2020 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/config/ #include <tao/config.hpp> #include <tao/config/schema.hpp> int main() { const auto tcs = tao::config::schema::from_file( "tests/schema.tcs" ); const auto data = tao::config::from_file( "tests/schema.jaxn" ); const auto error = tcs.validate( data ); if( error ) { std::cerr << std::setw( 2 ) << error << std::endl; } return !error ? 0 : 1; }
28.055556
76
0.645545
mpoeter
2b0dbed5783e7ff3c89e007e407fb39d6512d7d5
1,467
cpp
C++
src/mayaToCorona/src/Corona/CoronaRoundCorners.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
42
2015-01-03T15:07:25.000Z
2021-12-09T03:56:59.000Z
src/mayaToCorona/src/Corona/CoronaRoundCorners.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
66
2015-01-02T13:28:44.000Z
2022-03-16T14:00:57.000Z
src/mayaToCorona/src/Corona/CoronaRoundCorners.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
12
2015-02-07T05:02:17.000Z
2020-07-10T17:21:44.000Z
#include "Corona.h" #include "CoronaRoundCorners.h" #include <maya/MFnDependencyNode.h> #include "utilities/attrTools.h" #include "world.h" #include "renderGlobals.h" RoundCorners::RoundCorners(MObject shaderObject) { MFnDependencyNode depFn(shaderObject); radius = getFloatAttr("radius", depFn, 0.0f); samplesCount = getIntAttr("samples", depFn, 10); float globalScaleFactor = 1.0f; if (MayaTo::getWorldPtr()->worldRenderGlobalsPtr != nullptr) globalScaleFactor = MayaTo::getWorldPtr()->worldRenderGlobalsPtr->scaleFactor; else globalScaleFactor = MayaTo::getWorldPtr()->scaleFactor; radius *= globalScaleFactor; }; RoundCorners::RoundCorners() {}; RoundCorners::~RoundCorners(){}; Corona::Rgb RoundCorners::evalColor(const Corona::IShadeContext& context, Corona::TextureCache* cache, float& outAlpha) { outAlpha = 1.0f; float f = 1.0f; return Corona::Rgb(f, f, f); } float RoundCorners::evalMono(const Corona::IShadeContext& context, Corona::TextureCache* cache, float& outAlpha) { return evalColor(context, cache, outAlpha).grayValue(); } Corona::Dir RoundCorners::evalBump(const Corona::IShadeContext& context, Corona::TextureCache* cache) { Corona::Dir inNormal(0,0,0); if (normalCamera.getMap() != nullptr) inNormal = normalCamera.getMap()->evalBump(context, cache); return evalPerturbation(context, radius) + inNormal; } //void RoundCorners::renderTo(Corona::Bitmap<Corona::Rgb>& output) //{ // STOP; //currently not supported //}
28.764706
119
0.748466
haggi
2b0e369b3ee9925c6967788de2cba07a22e4465a
842
cc
C++
CPP/biweekly-contest-33/No1.cc
hxz1998/funny_leetcode
1d2c425af09b57a030fc018ddc1e1a5ffb966cd0
[ "Apache-2.0" ]
null
null
null
CPP/biweekly-contest-33/No1.cc
hxz1998/funny_leetcode
1d2c425af09b57a030fc018ddc1e1a5ffb966cd0
[ "Apache-2.0" ]
null
null
null
CPP/biweekly-contest-33/No1.cc
hxz1998/funny_leetcode
1d2c425af09b57a030fc018ddc1e1a5ffb966cd0
[ "Apache-2.0" ]
null
null
null
/** * Created by Xiaozhong on 2020/8/22. * Copyright (c) 2020/8/22 Xiaozhong. All rights reserved. */ #include "string" #include "vector" #include "iostream" #include "algorithm" using namespace std; class Solution { public: string thousandSeparator(int n) { if (n == 0) return "0"; if (n < 1000) return to_string(n); string s = to_string(n); int times = 0; string ans = ""; for (int i = s.length() - 1; i >= 0; i--) { ans.push_back(s[i]); if (++times % 3 == 0) { if (i != 0) ans.append("."); times = 0; } } reverse(ans.begin(), ans.end()); return ans; } }; int main() { Solution s; cout << s.thousandSeparator(51040) << endl; cout << s.thousandSeparator(123456789) << endl; }
23.388889
58
0.511876
hxz1998
2b0f385d3a233869388c2265c1633d8543717815
46,960
cpp
C++
Breeder/BR.cpp
wolqws/sws
4086745d38cc7375ee38843214a63bd8d285a84d
[ "MIT", "Unlicense" ]
null
null
null
Breeder/BR.cpp
wolqws/sws
4086745d38cc7375ee38843214a63bd8d285a84d
[ "MIT", "Unlicense" ]
null
null
null
Breeder/BR.cpp
wolqws/sws
4086745d38cc7375ee38843214a63bd8d285a84d
[ "MIT", "Unlicense" ]
null
null
null
/***************************************************************************** / BR.cpp / / Copyright (c) 2012-2014 Dominik Martin Drzic / http://forum.cockos.com/member.php?u=27094 / https://code.google.com/p/sws-extension / / Permission is hereby granted, free of charge, to any person obtaining a copy / of this software and associated documentation files (the "Software"), to deal / in the Software without restriction, including without limitation the rights to / use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies / of the Software, and to permit persons to whom the Software is furnished to / do so, subject to the following conditions: / / The above copyright notice and this permission notice shall be included in all / copies or substantial portions of the Software. / / THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, / EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES / OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND / NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT / HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, / WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING / FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR / OTHER DEALINGS IN THE SOFTWARE. / ******************************************************************************/ #include "stdafx.h" #include "BR.h" #include "BR_ContinuousActions.h" #include "BR_Envelope.h" #include "BR_Loudness.h" #include "BR_MidiEditor.h" #include "BR_Misc.h" #include "BR_ProjState.h" #include "BR_Tempo.h" #include "BR_Update.h" #include "BR_Util.h" #include "../reaper/localize.h" //!WANT_LOCALIZE_1ST_STRING_BEGIN:sws_actions static COMMAND_T g_commandTable[] = { /****************************************************************************** * Envelopes * ******************************************************************************/ { { DEFACCEL, "SWS/BR: Set closest envelope point's value to mouse cursor (perform until shortcut released)" }, "BR_ENV_PT_VAL_CLOSEST_MOUSE", SetEnvPointMouseValue, NULL, 0}, { { DEFACCEL, "SWS/BR: Set closest left side envelope point's value to mouse cursor (perform until shortcut released)" }, "BR_ENV_PT_VAL_CLOSEST_LEFT_MOUSE", SetEnvPointMouseValue, NULL, 1}, { { DEFACCEL, "SWS/BR: Move edit cursor to next envelope point" }, "SWS_BRMOVEEDITTONEXTENV", CursorToEnv1, NULL, 1}, { { DEFACCEL, "SWS/BR: Move edit cursor to next envelope point and select it" }, "SWS_BRMOVEEDITSELNEXTENV", CursorToEnv1, NULL, 2}, { { DEFACCEL, "SWS/BR: Move edit cursor to next envelope point and add to selection" }, "SWS_BRMOVEEDITTONEXTENVADDSELL", CursorToEnv2, NULL, 1}, { { DEFACCEL, "SWS/BR: Move edit cursor to previous envelope point" }, "SWS_BRMOVEEDITTOPREVENV", CursorToEnv1, NULL, -1}, { { DEFACCEL, "SWS/BR: Move edit cursor to previous envelope point and select it" }, "SWS_BRMOVEEDITSELPREVENV", CursorToEnv1, NULL, -2}, { { DEFACCEL, "SWS/BR: Move edit cursor to previous envelope point and add to selection" }, "SWS_BRMOVEEDITTOPREVENVADDSELL", CursorToEnv2, NULL, -1}, { { DEFACCEL, "SWS/BR: Select next envelope point" }, "BR_ENV_SEL_NEXT_POINT", SelNextPrevEnvPoint, NULL, 1}, { { DEFACCEL, "SWS/BR: Select previous envelope point" }, "BR_ENV_SEL_PREV_POINT", SelNextPrevEnvPoint, NULL, -1}, { { DEFACCEL, "SWS/BR: Expand envelope point selection to the right" }, "BR_ENV_SEL_EXPAND_RIGHT", ExpandEnvSel, NULL, 1}, { { DEFACCEL, "SWS/BR: Expand envelope point selection to the left" }, "BR_ENV_SEL_EXPAND_LEFT", ExpandEnvSel, NULL, -1}, { { DEFACCEL, "SWS/BR: Expand envelope point selection to the right (end point only)" }, "BR_ENV_SEL_EXPAND_RIGHT_END", ExpandEnvSelEnd, NULL, 1}, { { DEFACCEL, "SWS/BR: Expand envelope point selection to the left (end point only)" }, "BR_ENV_SEL_EXPAND_L_END", ExpandEnvSelEnd, NULL, -1}, { { DEFACCEL, "SWS/BR: Shrink envelope point selection from the right" }, "BR_ENV_SEL_SHRINK_RIGHT", ShrinkEnvSel, NULL, 1}, { { DEFACCEL, "SWS/BR: Shrink envelope point selection from the left" }, "BR_ENV_SEL_SHRINK_LEFT", ShrinkEnvSel, NULL, -1}, { { DEFACCEL, "SWS/BR: Shrink envelope point selection from the right (end point only)" }, "BR_ENV_SEL_SHRINK_RIGHT_END", ShrinkEnvSelEnd, NULL, 1}, { { DEFACCEL, "SWS/BR: Shrink envelope point selection from the left (end point only)" }, "BR_ENV_SEL_SHRINK_LEFT_END", ShrinkEnvSelEnd, NULL, -1}, { { DEFACCEL, "SWS/BR: Shift envelope point selection left" }, "BR_ENV_SHIFT_SEL_LEFT", ShiftEnvSelection, NULL, -1}, { { DEFACCEL, "SWS/BR: Shift envelope point selection right" }, "BR_ENV_SHIFT_SEL_RIGHT", ShiftEnvSelection, NULL, 1}, { { DEFACCEL, "SWS/BR: Select peaks in envelope (add to selection)" }, "BR_ENV_SEL_PEAKS_ADD", PeaksDipsEnv, NULL, 1}, { { DEFACCEL, "SWS/BR: Select peaks in envelope" }, "BR_ENV_SEL_PEAKS", PeaksDipsEnv, NULL, 2}, { { DEFACCEL, "SWS/BR: Select dips in envelope (add to selection)" }, "BR_ENV_SEL_DIPS_ADD", PeaksDipsEnv, NULL, -1}, { { DEFACCEL, "SWS/BR: Select dips in envelope" }, "BR_ENV_SEL_DIPS", PeaksDipsEnv, NULL, -2}, { { DEFACCEL, "SWS/BR: Unselect envelope points outside time selection" }, "BR_ENV_UNSEL_OUT_TIME_SEL", SelEnvTimeSel, NULL, -1}, { { DEFACCEL, "SWS/BR: Unselect envelope points in time selection" }, "BR_ENV_UNSEL_IN_TIME_SEL", SelEnvTimeSel, NULL, 1}, { { DEFACCEL, "SWS/BR: Set selected envelope points to next point's value" }, "BR_SET_ENV_TO_NEXT_VAL", SetEnvValToNextPrev, NULL, 1}, { { DEFACCEL, "SWS/BR: Set selected envelope points to previous point's value" }, "BR_SET_ENV_TO_PREV_VAL", SetEnvValToNextPrev, NULL, -1}, { { DEFACCEL, "SWS/BR: Set selected envelope points to last selected point's value" }, "BR_SET_ENV_TO_LAST_SEL_VAL", SetEnvValToNextPrev, NULL, 2}, { { DEFACCEL, "SWS/BR: Set selected envelope points to first selected point's value" }, "BR_SET_ENV_TO_FIRST_SEL_VAL", SetEnvValToNextPrev, NULL, -2}, { { DEFACCEL, "SWS/BR: Move closest envelope point to edit cursor" }, "BR_MOVE_CLOSEST_ENV_ECURSOR", MoveEnvPointToEditCursor, NULL, 0}, { { DEFACCEL, "SWS/BR: Move closest selected envelope point to edit cursor" }, "BR_MOVE_CLOSEST_SEL_ENV_ECURSOR", MoveEnvPointToEditCursor, NULL, 1}, { { DEFACCEL, "SWS/BR: Insert 2 envelope points at time selection" }, "BR_INSERT_2_ENV_POINT_TIME_SEL", Insert2EnvPointsTimeSelection, NULL, 1}, { { DEFACCEL, "SWS/BR: Fit selected envelope points to time selection" }, "BR_FIT_ENV_POINTS_TO_TIMESEL", FitEnvPointsToTimeSel, NULL}, { { DEFACCEL, "SWS/BR: Hide all but selected track envelope for all tracks" }, "BR_ENV_HIDE_ALL_BUT_ACTIVE", ShowActiveTrackEnvOnly, NULL, 0}, { { DEFACCEL, "SWS/BR: Hide all but selected track envelope for selected tracks" }, "BR_ENV_HIDE_ALL_BUT_ACTIVE_SEL", ShowActiveTrackEnvOnly, NULL, 1}, { { DEFACCEL, "SWS/BR: Insert new envelope point at mouse cursor using value at current position (obey snapping)" }, "BR_ENV_POINT_MOUSE_CURSOR", CreateEnvPointMouse, NULL}, { { DEFACCEL, "SWS/BR: Save envelope point selection, slot 1" }, "BR_SAVE_ENV_SEL_SLOT_1", SaveEnvSelSlot, NULL, 0}, { { DEFACCEL, "SWS/BR: Save envelope point selection, slot 2" }, "BR_SAVE_ENV_SEL_SLOT_2", SaveEnvSelSlot, NULL, 1}, { { DEFACCEL, "SWS/BR: Save envelope point selection, slot 3" }, "BR_SAVE_ENV_SEL_SLOT_3", SaveEnvSelSlot, NULL, 2}, { { DEFACCEL, "SWS/BR: Save envelope point selection, slot 4" }, "BR_SAVE_ENV_SEL_SLOT_4", SaveEnvSelSlot, NULL, 3}, { { DEFACCEL, "SWS/BR: Save envelope point selection, slot 5" }, "BR_SAVE_ENV_SEL_SLOT_5", SaveEnvSelSlot, NULL, 4}, { { DEFACCEL, "SWS/BR: Restore envelope point selection, slot 1" }, "BR_RESTORE_ENV_SEL_SLOT_1", RestoreEnvSelSlot, NULL, 0}, { { DEFACCEL, "SWS/BR: Restore envelope point selection, slot 2" }, "BR_RESTORE_ENV_SEL_SLOT_2", RestoreEnvSelSlot, NULL, 1}, { { DEFACCEL, "SWS/BR: Restore envelope point selection, slot 3" }, "BR_RESTORE_ENV_SEL_SLOT_3", RestoreEnvSelSlot, NULL, 2}, { { DEFACCEL, "SWS/BR: Restore envelope point selection, slot 4" }, "BR_RESTORE_ENV_SEL_SLOT_4", RestoreEnvSelSlot, NULL, 3}, { { DEFACCEL, "SWS/BR: Restore envelope point selection, slot 5" }, "BR_RESTORE_ENV_SEL_SLOT_5", RestoreEnvSelSlot, NULL, 4}, /****************************************************************************** * Loudness * ******************************************************************************/ { { DEFACCEL, "SWS/BR: Analyze loudness..." }, "BR_ANALAYZE_LOUDNESS_DLG", AnalyzeLoudness, NULL, 0, IsAnalyzeLoudnessVisible}, { { DEFACCEL, "SWS/BR: Normalize loudness of selected tracks..." }, "BR_NORMALIZE_LOUDNESS_TRACKS", NormalizeLoudness, NULL, 0, }, { { DEFACCEL, "SWS/BR: Normalize loudness of selected tracks to -23 LUFS" }, "BR_NORMALIZE_LOUDNESS_TRACKS23", NormalizeLoudness, NULL, 1, }, { { DEFACCEL, "SWS/BR: Normalize loudness of selected items..." }, "BR_NORMALIZE_LOUDNESS_ITEMS", NormalizeLoudness, NULL, 2, }, { { DEFACCEL, "SWS/BR: Normalize loudness of selected items to -23 LUFS" }, "BR_NORMALIZE_LOUDNESS_ITEMS23", NormalizeLoudness, NULL, 3, }, /****************************************************************************** * Midi editor - Media item preview * ******************************************************************************/ { { DEFACCEL, "SWS/BR: Stop media item preview" }, "BR_ME_STOP_PREV_ACT_ITEM", NULL, NULL, 0, NULL, 32060, ME_StopMidiTakePreview}, { { DEFACCEL, "SWS/BR: Preview active media item through track" }, "BR_ME_PREV_ACT_ITEM", NULL, NULL, 1111, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Preview active media item through track (start from mouse position)" }, "BR_ME_PREV_ACT_ITEM_POS", NULL, NULL, 1211, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Preview active media item through track (sync with next measure)" }, "BR_ME_PREV_ACT_ITEM_SYNC", NULL, NULL, 1311, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Preview active media item through track and pause during preview" }, "BR_ME_PREV_ACT_ITEM_PAUSE", NULL, NULL, 1112, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Preview active media item through track and pause during preview (start from mouse position)" }, "BR_ME_PREV_ACT_ITEM_PAUSE_POS", NULL, NULL, 1212, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Preview active media item (selected notes only) through track" }, "BR_ME_PREV_ACT_ITEM_NOTES", NULL, NULL, 1121, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Preview active media item (selected notes only) through track (start from mouse position)" }, "BR_ME_PREV_ACT_ITEM_NOTES_POS", NULL, NULL, 1221, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Preview active media item (selected notes only) through track (sync with next measure)" }, "BR_ME_PREV_ACT_ITEM_NOTES_SYNC", NULL, NULL, 1321, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Preview active media item (selected notes only) through track and pause during preview" }, "BR_ME_PREV_ACT_ITEM_NOTES_PAUSE", NULL, NULL, 1122, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Preview active media item (selected notes only) through track and pause during preview (start from mouse position)" }, "BR_ME_PREV_ACT_ITEM_NOTES_PAUSE_POS", NULL, NULL, 1222, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Toggle preview active media item through track" }, "BR_ME_TPREV_ACT_ITEM", NULL, NULL, 2111, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Toggle preview active media item through track (start from mouse position)" }, "BR_ME_TPREV_ACT_ITEM_POS", NULL, NULL, 2211, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Toggle preview active media item through track (sync with next measure)" }, "BR_ME_TPREV_ACT_ITEM_SYNC", NULL, NULL, 2311, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Toggle preview active media item through track and pause during preview" }, "BR_ME_TPREV_ACT_ITEM_PAUSE", NULL, NULL, 2112, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Toggle preview active media item through track and pause during preview (start from mouse position)" }, "BR_ME_TPREV_ACT_ITEM_PAUSE_POS", NULL, NULL, 2212, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Toggle preview active media item (selected notes only) through track" }, "BR_ME_TPREV_ACT_ITEM_NOTES", NULL, NULL, 2121, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Toggle preview active media item (selected notes only) through track (start from mouse position)" }, "BR_ME_TPREV_ACT_ITEM_NOTES_POS", NULL, NULL, 2221, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Toggle preview active media item (selected notes only) through track (sync with next measure)" }, "BR_ME_TPREV_ACT_ITEM_NOTES_SYNC", NULL, NULL, 2321, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Toggle preview active media item (selected notes only) through track and pause during preview" }, "BR_ME_TPREV_ACT_ITEM_NOTES_PAUSE", NULL, NULL, 2122, NULL, 32060, ME_PreviewActiveTake}, { { DEFACCEL, "SWS/BR: Toggle preview active media item (selected notes only) through track and pause during preview (start from mouse position)" }, "BR_ME_TPREV_ACT_ITEM_NOTES_PAUSE_POS", NULL, NULL, 2222, NULL, 32060, ME_PreviewActiveTake}, /****************************************************************************** * Midi editor - Misc * ******************************************************************************/ { { DEFACCEL, "SWS/BR: Play from mouse cursor position" }, "BR_ME_PLAY_MOUSECURSOR", NULL, NULL, 0, NULL, 32060, ME_PlaybackAtMouseCursor}, { { DEFACCEL, "SWS/BR: Play/pause from mouse cursor position" }, "BR_ME_PLAY_PAUSE_MOUSECURSOR", NULL, NULL, 1, NULL, 32060, ME_PlaybackAtMouseCursor}, { { DEFACCEL, "SWS/BR: Play/stop from mouse cursor position" }, "BR_ME_PLAY_STOP_MOUSECURSOR", NULL, NULL, 2, NULL, 32060, ME_PlaybackAtMouseCursor}, { { DEFACCEL, "SWS/BR: Save edit cursor position, slot 1" }, "BR_ME_SAVE_CURSOR_POS_SLOT_1", NULL, NULL, 0, NULL, 32060, ME_SaveCursorPosSlot}, { { DEFACCEL, "SWS/BR: Save edit cursor position, slot 2" }, "BR_ME_SAVE_CURSOR_POS_SLOT_2", NULL, NULL, 1, NULL, 32060, ME_SaveCursorPosSlot}, { { DEFACCEL, "SWS/BR: Save edit cursor position, slot 3" }, "BR_ME_SAVE_CURSOR_POS_SLOT_3", NULL, NULL, 2, NULL, 32060, ME_SaveCursorPosSlot}, { { DEFACCEL, "SWS/BR: Save edit cursor position, slot 4" }, "BR_ME_SAVE_CURSOR_POS_SLOT_4", NULL, NULL, 3, NULL, 32060, ME_SaveCursorPosSlot}, { { DEFACCEL, "SWS/BR: Save edit cursor position, slot 5" }, "BR_ME_SAVE_CURSOR_POS_SLOT_5", NULL, NULL, 4, NULL, 32060, ME_SaveCursorPosSlot}, { { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 1" }, "BR_ME_RESTORE_CURSOR_POS_SLOT_1", NULL, NULL, 0, NULL, 32060, ME_RestoreCursorPosSlot}, { { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 2" }, "BR_ME_RESTORE_CURSOR_POS_SLOT_2", NULL, NULL, 1, NULL, 32060, ME_RestoreCursorPosSlot}, { { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 3" }, "BR_ME_RESTORE_CURSOR_POS_SLOT_3", NULL, NULL, 2, NULL, 32060, ME_RestoreCursorPosSlot}, { { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 4" }, "BR_ME_RESTORE_CURSOR_POS_SLOT_4", NULL, NULL, 3, NULL, 32060, ME_RestoreCursorPosSlot}, { { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 5" }, "BR_ME_RESTORE_CURSOR_POS_SLOT_5", NULL, NULL, 4, NULL, 32060, ME_RestoreCursorPosSlot}, { { DEFACCEL, "SWS/BR: Save note selection from active take, slot 1" }, "BR_ME_SAVE_NOTE_SEL_SLOT_1", NULL, NULL, 0, NULL, 32060, ME_SaveNoteSelSlot}, { { DEFACCEL, "SWS/BR: Save note selection from active take, slot 2" }, "BR_ME_SAVE_NOTE_SEL_SLOT_2", NULL, NULL, 1, NULL, 32060, ME_SaveNoteSelSlot}, { { DEFACCEL, "SWS/BR: Save note selection from active take, slot 3" }, "BR_ME_SAVE_NOTE_SEL_SLOT_3", NULL, NULL, 2, NULL, 32060, ME_SaveNoteSelSlot}, { { DEFACCEL, "SWS/BR: Save note selection from active take, slot 4" }, "BR_ME_SAVE_NOTE_SEL_SLOT_4", NULL, NULL, 3, NULL, 32060, ME_SaveNoteSelSlot}, { { DEFACCEL, "SWS/BR: Save note selection from active take, slot 5" }, "BR_ME_SAVE_NOTE_SEL_SLOT_5", NULL, NULL, 4, NULL, 32060, ME_SaveNoteSelSlot}, { { DEFACCEL, "SWS/BR: Restore note selection to active take, slot 1" }, "BR_ME_RESTORE_NOTE_SEL_SLOT_1", NULL, NULL, 0, NULL, 32060, ME_RestoreNoteSelSlot}, { { DEFACCEL, "SWS/BR: Restore note selection to active take, slot 2" }, "BR_ME_RESTORE_NOTE_SEL_SLOT_2", NULL, NULL, 1, NULL, 32060, ME_RestoreNoteSelSlot}, { { DEFACCEL, "SWS/BR: Restore note selection to active take, slot 3" }, "BR_ME_RESTORE_NOTE_SEL_SLOT_3", NULL, NULL, 2, NULL, 32060, ME_RestoreNoteSelSlot}, { { DEFACCEL, "SWS/BR: Restore note selection to active take, slot 4" }, "BR_ME_RESTORE_NOTE_SEL_SLOT_4", NULL, NULL, 3, NULL, 32060, ME_RestoreNoteSelSlot}, { { DEFACCEL, "SWS/BR: Restore note selection to active take, slot 5" }, "BR_ME_RESTORE_NOTE_SEL_SLOT_5", NULL, NULL, 4, NULL, 32060, ME_RestoreNoteSelSlot}, { { DEFACCEL, "SWS/BR: Show only used CC lanes (detect 14-bit)" }, "BR_ME_SHOW_USED_CC_14_BIT", NULL, NULL, 0, NULL, 32060, ME_ShowUsedCCLanesDetect14Bit}, /****************************************************************************** * Misc * ******************************************************************************/ { { DEFACCEL, "SWS/BR: Split selected items at tempo markers" }, "SWS_BRSPLITSELECTEDTEMPO", SplitItemAtTempo}, { { DEFACCEL, "SWS/BR: Create project markers from selected tempo markers" }, "BR_TEMPO_TO_MARKERS", MarkersAtTempo}, { { DEFACCEL, "SWS/BR: Enable \"Ignore project tempo\" for selected MIDI items (use tempo at item's start)" }, "BR_MIDI_PROJ_TEMPO_ENB", MidiItemTempo, NULL, 0}, { { DEFACCEL, "SWS/BR: Disable \"Ignore project tempo\" for selected MIDI items" }, "BR_MIDI_PROJ_TEMPO_DIS", MidiItemTempo, NULL, 1}, { { DEFACCEL, "SWS/BR: Trim MIDI item to active content" }, "BR_TRIM_MIDI_ITEM_ACT_CONTENT", MidiItemTrim, NULL}, { { DEFACCEL, "SWS/BR: Create project markers from notes in selected MIDI items" }, "BR_MIDI_NOTES_TO_MARKERS", MarkersAtNotes}, { { DEFACCEL, "SWS/BR: Create project markers from stretch markers in selected items" }, "BR_STRETCH_MARKERS_TO_MARKERS", MarkersAtStretchMarkers}, { { DEFACCEL, "SWS/BR: Create project markers from selected items (name by item's notes)" }, "BR_ITEMS_TO_MARKERS_NOTES", MarkersRegionsAtItems, NULL, 0}, { { DEFACCEL, "SWS/BR: Create regions from selected items (name by item's notes)" }, "BR_ITEMS_TO_REGIONS_NOTES", MarkersRegionsAtItems, NULL, 1}, { { DEFACCEL, "SWS/BR: Toggle \"Grid snap settings follow grid visibility\"" }, "BR_OPTIONS_SNAP_FOLLOW_GRID_VIS", SnapFollowsGridVis, NULL, 0, IsSnapFollowsGridVisOn}, { { DEFACCEL, "SWS/BR: Toggle \"Playback position follows project timebase when changing tempo\"" }, "BR_OPTIONS_PLAYBACK_TEMPO_CHANGE", PlaybackFollowsTempoChange, NULL, 0, IsPlaybackFollowingTempoChange}, { { DEFACCEL, "SWS/BR: Set \"Apply trim when adding volume/pan envelopes\" to \"Always\"" }, "BR_OPTIONS_ENV_TRIM_ALWAYS", TrimNewVolPanEnvs, NULL, 0, IsTrimNewVolPanEnvsOn}, { { DEFACCEL, "SWS/BR: Set \"Apply trim when adding volume/pan envelopes\" to \"In read/write\"" }, "BR_OPTIONS_ENV_TRIM_READWRITE", TrimNewVolPanEnvs, NULL, 1, IsTrimNewVolPanEnvsOn}, { { DEFACCEL, "SWS/BR: Set \"Apply trim when adding volume/pan envelopes\" to \"Never\"" }, "BR_OPTIONS_ENV_TRIM_NEVER", TrimNewVolPanEnvs, NULL, 2, IsTrimNewVolPanEnvsOn}, { { DEFACCEL, "SWS/BR: Cycle through record modes" }, "BR_CYCLE_RECORD_MODES", CycleRecordModes}, { { DEFACCEL, "SWS/BR: Focus arrange window" }, "BR_FOCUS_ARRANGE_WND", FocusArrange}, { { DEFACCEL, "SWS/BR: Toggle media item online/offline" }, "BR_TOGGLE_ITEM_ONLINE", ToggleItemOnline}, { { DEFACCEL, "SWS/BR: Copy take media source file path of selected items to clipboard" }, "BR_TSOURCE_PATH_TO_CLIPBOARD", ItemSourcePathToClipBoard}, { { DEFACCEL, "SWS/BR: Play from mouse cursor position" }, "BR_PLAY_MOUSECURSOR", PlaybackAtMouseCursor, NULL, 0}, { { DEFACCEL, "SWS/BR: Play/pause from mouse cursor position" }, "BR_PLAY_PAUSE_MOUSECURSOR", PlaybackAtMouseCursor, NULL, 1}, { { DEFACCEL, "SWS/BR: Play/stop from mouse cursor position" }, "BR_PLAY_STOP_MOUSECURSOR", PlaybackAtMouseCursor, NULL, 2}, { { DEFACCEL, "SWS/BR: Save edit cursor position, slot 1" }, "BR_SAVE_CURSOR_POS_SLOT_1", SaveCursorPosSlot, NULL, 0}, { { DEFACCEL, "SWS/BR: Save edit cursor position, slot 2" }, "BR_SAVE_CURSOR_POS_SLOT_2", SaveCursorPosSlot, NULL, 1}, { { DEFACCEL, "SWS/BR: Save edit cursor position, slot 3" }, "BR_SAVE_CURSOR_POS_SLOT_3", SaveCursorPosSlot, NULL, 2}, { { DEFACCEL, "SWS/BR: Save edit cursor position, slot 4" }, "BR_SAVE_CURSOR_POS_SLOT_4", SaveCursorPosSlot, NULL, 3}, { { DEFACCEL, "SWS/BR: Save edit cursor position, slot 5" }, "BR_SAVE_CURSOR_POS_SLOT_5", SaveCursorPosSlot, NULL, 4}, { { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 1" }, "BR_RESTORE_CURSOR_POS_SLOT_1", RestoreCursorPosSlot, NULL, 0}, { { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 2" }, "BR_RESTORE_CURSOR_POS_SLOT_2", RestoreCursorPosSlot, NULL, 1}, { { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 3" }, "BR_RESTORE_CURSOR_POS_SLOT_3", RestoreCursorPosSlot, NULL, 2}, { { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 4" }, "BR_RESTORE_CURSOR_POS_SLOT_4", RestoreCursorPosSlot, NULL, 3}, { { DEFACCEL, "SWS/BR: Restore edit cursor position, slot 5" }, "BR_RESTORE_CURSOR_POS_SLOT_5", RestoreCursorPosSlot, NULL, 4}, /****************************************************************************** * Media item preview * ******************************************************************************/ { { DEFACCEL, "SWS/BR: Preview media item under mouse" }, "BR_PREV_ITEM_CURSOR", PreviewItemAtMouse, NULL, 1111}, { { DEFACCEL, "SWS/BR: Preview media item under mouse (start from mouse cursor position)" }, "BR_PREV_ITEM_CURSOR_POS", PreviewItemAtMouse, NULL, 1121}, { { DEFACCEL, "SWS/BR: Preview media item under mouse (sync with next measure)" }, "BR_PREV_ITEM_CURSOR_SYNC", PreviewItemAtMouse, NULL, 1131}, { { DEFACCEL, "SWS/BR: Preview media item under mouse and pause during preview" }, "BR_PREV_ITEM_PAUSE_CURSOR", PreviewItemAtMouse, NULL, 1112}, { { DEFACCEL, "SWS/BR: Preview media item under mouse and pause during preview (start from mouse cursor position)" }, "BR_PREV_ITEM_PAUSE_CURSOR_POS", PreviewItemAtMouse, NULL, 1122}, { { DEFACCEL, "SWS/BR: Preview media item under mouse at track fader volume" }, "BR_PREV_ITEM_CURSOR_FADER", PreviewItemAtMouse, NULL, 1211}, { { DEFACCEL, "SWS/BR: Preview media item under mouse at track fader volume (start from mouse position)" }, "BR_PREV_ITEM_CURSOR_FADER_POS", PreviewItemAtMouse, NULL, 1221}, { { DEFACCEL, "SWS/BR: Preview media item under mouse at track fader volume (sync with next measure)" }, "BR_PREV_ITEM_CURSOR_FADER_SYNC", PreviewItemAtMouse, NULL, 1231}, { { DEFACCEL, "SWS/BR: Preview media item under mouse at track fader volume and pause during preview" }, "BR_PREV_ITEM_PAUSE_CURSOR_FADER", PreviewItemAtMouse, NULL, 1212}, { { DEFACCEL, "SWS/BR: Preview media item under mouse at track fader volume and pause during preview (start from mouse cursor position)" }, "BR_PREV_ITEM_PAUSE_CURSOR_FADER_POS", PreviewItemAtMouse, NULL, 1222}, { { DEFACCEL, "SWS/BR: Preview media item under mouse through track" }, "BR_PREV_ITEM_CURSOR_TRACK", PreviewItemAtMouse, NULL, 1311}, { { DEFACCEL, "SWS/BR: Preview media item under mouse through track (start from mouse position)" }, "BR_PREV_ITEM_CURSOR_TRACK_POS", PreviewItemAtMouse, NULL, 1321}, { { DEFACCEL, "SWS/BR: Preview media item under mouse through track (sync with next measure)" }, "BR_PREV_ITEM_CURSOR_TRACK_SYNC", PreviewItemAtMouse, NULL, 1331}, { { DEFACCEL, "SWS/BR: Preview media item under mouse through track and pause during preview" }, "BR_PREV_ITEM_PAUSE_CURSOR_TRACK", PreviewItemAtMouse, NULL, 1312}, { { DEFACCEL, "SWS/BR: Preview media item under mouse through track and pause during preview (start from mouse cursor position)" }, "BR_PREV_ITEM_PAUSE_CURSOR_TRACK_POS", PreviewItemAtMouse, NULL, 1322}, { { DEFACCEL, "SWS/BR: Toggle preview media item under mouse" }, "BR_TPREV_ITEM_CURSOR", PreviewItemAtMouse, NULL, 2111}, { { DEFACCEL, "SWS/BR: Toggle preview media item under mouse (start from mouse position)" }, "BR_TPREV_ITEM_CURSOR_POS", PreviewItemAtMouse, NULL, 2121}, { { DEFACCEL, "SWS/BR: Toggle preview media item under mouse (sync with next measure)" }, "BR_TPREV_ITEM_CURSOR_SYNC", PreviewItemAtMouse, NULL, 2131}, { { DEFACCEL, "SWS/BR: Toggle preview media item under mouse and pause during preview" }, "BR_TPREV_ITEM_PAUSE_CURSOR", PreviewItemAtMouse, NULL, 2112}, { { DEFACCEL, "SWS/BR: Toggle preview media item under mouse and pause during preview (start from mouse cursor position)" }, "BR_TPREV_ITEM_PAUSE_CURSOR_POS", PreviewItemAtMouse, NULL, 2122}, { { DEFACCEL, "SWS/BR: Toggle preview media item under mouse at track fader volume" }, "BR_TPREV_ITEM_CURSOR_FADER", PreviewItemAtMouse, NULL, 2211}, { { DEFACCEL, "SWS/BR: Toggle preview media item under mouse at track fader volume (start from mouse position)" }, "BR_TPREV_ITEM_CURSOR_FADER_POS", PreviewItemAtMouse, NULL, 2221}, { { DEFACCEL, "SWS/BR: Toggle preview media item under mouse at track fader volume (sync with next measure)" }, "BR_TPREV_ITEM_CURSOR_FADER_SYNC", PreviewItemAtMouse, NULL, 2231}, { { DEFACCEL, "SWS/BR: Toggle preview media item under mouse at track fader volume and pause during preview" }, "BR_TPREV_ITEM_PAUSE_CURSOR_FADER", PreviewItemAtMouse, NULL, 2212}, { { DEFACCEL, "SWS/BR: Toggle preview media item under mouse at track fader volume and pause during preview (start from mouse cursor position)" }, "BR_TPREV_ITEM_PAUSE_CURSOR_FADER_POS", PreviewItemAtMouse, NULL, 2222}, { { DEFACCEL, "SWS/BR: Toggle preview media item under mouse through track" }, "BR_TPREV_ITEM_CURSOR_TRACK", PreviewItemAtMouse, NULL, 2311}, { { DEFACCEL, "SWS/BR: Toggle preview media item under mouse through track (start from mouse position)" }, "BR_TPREV_ITEM_CURSOR_TRACK_POS", PreviewItemAtMouse, NULL, 2321}, { { DEFACCEL, "SWS/BR: Toggle preview media item under mouse through track (sync with next measure)" }, "BR_TPREV_ITEM_CURSOR_TRACK_SYNC", PreviewItemAtMouse, NULL, 2331}, { { DEFACCEL, "SWS/BR: Toggle preview media item under mouse through track and pause during preview" }, "BR_TPREV_ITEM_PAUSE_CURSOR_TRACK", PreviewItemAtMouse, NULL, 2312}, { { DEFACCEL, "SWS/BR: Toggle preview media item under mouse through track and pause during preview (start from mouse cursor position)" }, "BR_TPREV_ITEM_PAUSE_CURSOR_TRACK_POS", PreviewItemAtMouse, NULL, 2322}, /****************************************************************************** * Grid * ******************************************************************************/ { { DEFACCEL, "SWS/BR: Move closest tempo marker to mouse cursor (perform until shortcut released)" }, "BR_MOVE_CLOSEST_TEMPO_MOUSE", MoveGridToMouse, NULL, 0}, { { DEFACCEL, "SWS/BR: Move closest grid line to mouse cursor (perform until shortcut released)" }, "BR_MOVE_GRID_TO_MOUSE", MoveGridToMouse, NULL, 1}, { { DEFACCEL, "SWS/BR: Move closest measure grid line to mouse cursor (perform until shortcut released)" }, "BR_MOVE_M_GRID_TO_MOUSE", MoveGridToMouse, NULL, 2}, { { DEFACCEL, "SWS/BR: Move closest grid line to edit cursor" }, "BR_MOVE_GRID_TO_EDIT_CUR", MoveGridToEditPlayCursor, NULL, 0}, { { DEFACCEL, "SWS/BR: Move closest grid line to play cursor" }, "BR_MOVE_GRID_TO_PLAY_CUR", MoveGridToEditPlayCursor, NULL, 1}, { { DEFACCEL, "SWS/BR: Move closest measure grid line to edit cursor" }, "BR_MOVE_M_GRID_TO_EDIT_CUR", MoveGridToEditPlayCursor, NULL, 2}, { { DEFACCEL, "SWS/BR: Move closest measure grid line to play cursor" }, "BR_MOVE_M_GRID_TO_PLAY_CUR", MoveGridToEditPlayCursor, NULL, 3}, { { DEFACCEL, "SWS/BR: Move closest left side grid line to edit cursor" }, "BR_MOVE_L_GRID_TO_EDIT_CUR", MoveGridToEditPlayCursor, NULL, 4}, { { DEFACCEL, "SWS/BR: Move closest right side grid line to edit cursor" }, "BR_MOVE_R_GRID_TO_EDIT_CUR", MoveGridToEditPlayCursor, NULL, 5}, /****************************************************************************** * Tempo * ******************************************************************************/ { { DEFACCEL, "SWS/BR: Move tempo marker forward 0.1 ms" }, "SWS_BRMOVETEMPOFORWARD01", MoveTempo, NULL, 1}, { { DEFACCEL, "SWS/BR: Move tempo marker forward 1 ms" }, "SWS_BRMOVETEMPOFORWARD1", MoveTempo, NULL, 10}, { { DEFACCEL, "SWS/BR: Move tempo marker forward 10 ms"}, "SWS_BRMOVETEMPOFORWARD10", MoveTempo, NULL, 100}, { { DEFACCEL, "SWS/BR: Move tempo marker forward 100 ms"}, "SWS_BRMOVETEMPOFORWARD100", MoveTempo, NULL, 1000}, { { DEFACCEL, "SWS/BR: Move tempo marker forward 1000 ms" }, "SWS_BRMOVETEMPOFORWARD1000", MoveTempo, NULL, 10000}, { { DEFACCEL, "SWS/BR: Move tempo marker back 0.1 ms"}, "SWS_BRMOVETEMPOBACK01", MoveTempo, NULL, -1}, { { DEFACCEL, "SWS/BR: Move tempo marker back 1 ms"}, "SWS_BRMOVETEMPOBACK1", MoveTempo, NULL, -10}, { { DEFACCEL, "SWS/BR: Move tempo marker back 10 ms"}, "SWS_BRMOVETEMPOBACK10", MoveTempo, NULL, -100}, { { DEFACCEL, "SWS/BR: Move tempo marker back 100 ms"}, "SWS_BRMOVETEMPOBACK100", MoveTempo, NULL, -1000}, { { DEFACCEL, "SWS/BR: Move tempo marker back 1000 ms"}, "SWS_BRMOVETEMPOBACK1000", MoveTempo, NULL, -10000}, { { DEFACCEL, "SWS/BR: Move tempo marker forward" }, "SWS_BRMOVETEMPOFORWARD", MoveTempo, NULL, 2}, { { DEFACCEL, "SWS/BR: Move tempo marker back" }, "SWS_BRMOVETEMPOBACK", MoveTempo, NULL, -2}, { { DEFACCEL, "SWS/BR: Move closest tempo marker to edit cursor" }, "BR_MOVE_CLOSEST_TEMPO", MoveTempo, NULL, 3}, { { DEFACCEL, "SWS/BR: Increase tempo marker 0.001 BPM (preserve overall tempo)" }, "BR_INC_TEMPO_0.001_BPM", EditTempo, NULL, 1}, { { DEFACCEL, "SWS/BR: Increase tempo marker 0.01 BPM (preserve overall tempo)" }, "BR_INC_TEMPO_0.01_BPM", EditTempo, NULL, 10}, { { DEFACCEL, "SWS/BR: Increase tempo marker 0.1 BPM (preserve overall tempo)" }, "BR_INC_TEMPO_0.1_BPM", EditTempo, NULL, 100}, { { DEFACCEL, "SWS/BR: Increase tempo marker 01 BPM (preserve overall tempo)" }, "BR_INC_TEMPO_1_BPM", EditTempo, NULL, 1000}, { { DEFACCEL, "SWS/BR: Decrease tempo marker 0.001 BPM (preserve overall tempo)" }, "BR_DEC_TEMPO_0.001_BPM", EditTempo, NULL, -1}, { { DEFACCEL, "SWS/BR: Decrease tempo marker 0.01 BPM (preserve overall tempo)" }, "BR_DEC_TEMPO_0.01_BPM", EditTempo, NULL, -10}, { { DEFACCEL, "SWS/BR: Decrease tempo marker 0.1 BPM (preserve overall tempo)" }, "BR_DEC_TEMPO_0.1_BPM", EditTempo, NULL, -100}, { { DEFACCEL, "SWS/BR: Decrease tempo marker 01 BPM (preserve overall tempo)" }, "BR_DEC_TEMPO_1_BPM", EditTempo, NULL, -1000}, { { DEFACCEL, "SWS/BR: Increase tempo marker 0.001% (preserve overall tempo)" }, "BR_INC_TEMPO_0.001_PERC", EditTempo, NULL, 2}, { { DEFACCEL, "SWS/BR: Increase tempo marker 0.01% (preserve overall tempo)" }, "BR_INC_TEMPO_0.01_PERC", EditTempo, NULL, 20}, { { DEFACCEL, "SWS/BR: Increase tempo marker 0.1% (preserve overall tempo)" }, "BR_INC_TEMPO_0.1_PERC", EditTempo, NULL, 200}, { { DEFACCEL, "SWS/BR: Increase tempo marker 01% (preserve overall tempo)" }, "BR_INC_TEMPO_1_PERC", EditTempo, NULL, 2000}, { { DEFACCEL, "SWS/BR: Decrease tempo marker 0.001% (preserve overall tempo)" }, "BR_DEC_TEMPO_0.001_PERC", EditTempo, NULL, -2}, { { DEFACCEL, "SWS/BR: Decrease tempo marker 0.01% (preserve overall tempo)" }, "BR_DEC_TEMPO_0.01_PERC", EditTempo, NULL, -20}, { { DEFACCEL, "SWS/BR: Decrease tempo marker 0.1% (preserve overall tempo)" }, "BR_DEC_TEMPO_0.1_PERC", EditTempo, NULL, -200}, { { DEFACCEL, "SWS/BR: Decrease tempo marker 01% (preserve overall tempo)" }, "BR_DEC_TEMPO_1_PERC", EditTempo, NULL, -2000}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 0.001 BPM)" }, "BR_INC_GR_TEMPO_0.001_BPM", EditTempoGradual, NULL, 1}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 0.01 BPM)" }, "BR_INC_GR_TEMPO_0.01_BPM", EditTempoGradual, NULL, 10}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 0.1 BPM)" }, "BR_INC_GR_TEMPO_0.1_BPM", EditTempoGradual, NULL, 100}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 01 BPM)" }, "BR_INC_GR_TEMPO_1_BPM", EditTempoGradual, NULL, 1000}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 0.001 BPM)" }, "BR_DEC_GR_TEMPO_0.001_BPM", EditTempoGradual, NULL, -1}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 0.01 BPM)" }, "BR_DEC_GR_TEMPO_0.01_BPM", EditTempoGradual, NULL, -10}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 0.1 BPM)" }, "BR_DEC_GR_TEMPO_0.1_BPM", EditTempoGradual, NULL, -100}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 01 BPM)" }, "BR_DEC_GR_TEMPO_1_BPM", EditTempoGradual, NULL, -1000}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 0.001%)" }, "BR_INC_GR_TEMPO_0.001_PERC", EditTempoGradual, NULL, 2}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 0.01%)" }, "BR_INC_GR_TEMPO_0.01_PERC", EditTempoGradual, NULL, 20}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 0.1%)" }, "BR_INC_GR_TEMPO_0.1_PERC", EditTempoGradual, NULL, 200}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (increase 01%)" }, "BR_INC_GR_TEMPO_1_PERC", EditTempoGradual, NULL, 2000}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 0.001%)" }, "BR_DEC_GR_TEMPO_0.001_PERC", EditTempoGradual, NULL, -2}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 0.01%)" }, "BR_DEC_GR_TEMPO_0.01_PERC", EditTempoGradual, NULL, -20}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 0.1%)" }, "BR_DEC_GR_TEMPO_0.1_PERC", EditTempoGradual, NULL, -200}, { { DEFACCEL, "SWS/BR: Alter slope of gradual tempo marker (decrease 01%)" }, "BR_DEC_GR_TEMPO_1_PERC", EditTempoGradual, NULL, -2000}, { { DEFACCEL, "SWS/BR: Delete tempo marker (preserve overall tempo and positions if possible)" }, "BR_DELETE_TEMPO", DeleteTempo}, { { DEFACCEL, "SWS/BR: Delete tempo marker and preserve position and length of items (including MIDI events)" }, "BR_DELETE_TEMPO_ITEMS", DeleteTempoPreserveItems, NULL, 0}, { { DEFACCEL, "SWS/BR: Delete tempo marker and preserve position and length of selected items (including MIDI events)" }, "BR_DELETE_TEMPO_ITEMS_SEL", DeleteTempoPreserveItems, NULL, 1}, { { DEFACCEL, "SWS/BR: Create tempo markers at grid after every selected tempo marker" }, "BR_TEMPO_GRID", TempoAtGrid}, { { DEFACCEL, "SWS/BR: Convert project markers to tempo markers..." }, "SWS_BRCONVERTMARKERSTOTEMPO", ConvertMarkersToTempoDialog, NULL, 0, IsConvertMarkersToTempoVisible}, { { DEFACCEL, "SWS/BR: Select and adjust tempo markers..." }, "SWS_BRADJUSTSELTEMPO", SelectAdjustTempoDialog, NULL, 0, IsSelectAdjustTempoVisible}, { { DEFACCEL, "SWS/BR: Randomize tempo markers..." }, "BR_RANDOMIZE_TEMPO", RandomizeTempoDialog}, { { DEFACCEL, "SWS/BR: Set tempo marker shape (options)..." }, "BR_TEMPO_SHAPE_OPTIONS", TempoShapeOptionsDialog, NULL, 0, IsTempoShapeOptionsVisible}, { { DEFACCEL, "SWS/BR: Set tempo marker shape to linear (preserve positions)" }, "BR_TEMPO_SHAPE_LINEAR", TempoShapeLinear}, { { DEFACCEL, "SWS/BR: Set tempo marker shape to square (preserve positions)" }, "BR_TEMPO_SHAPE_SQUARE", TempoShapeSquare}, { {}, LAST_COMMAND, }, }; //!WANT_LOCALIZE_1ST_STRING_END static void InitContinuousActions () { MoveGridToMouseInit(); SetEnvPointMouseValueInit(); } int BR_Init () { SWSRegisterCommands(g_commandTable); InitContinuousActions (); // call only after registering all actions ProjStateInit(); AnalyzeLoudnessInit(); VersionCheckInit(); return 1; } void BR_Exit () { AnalyzeLoudnessExit(); } bool BR_ActionHook (int cmd, int flag) { return ContinuousActionHook(cmd, flag); } void BR_CSurfSetPlayState (bool play, bool pause, bool rec) { MidiTakePreviewPlayState(play, rec); }
129.723757
246
0.549127
wolqws
2b0f49c1638c7ea6bf8f3d63268c53943d885bd0
21,707
hpp
C++
src/character/character.hpp
Galfurian/RadMud
1362cb0ee1b7a17386e57a98e29dd8baeea75af3
[ "MIT" ]
18
2016-05-26T18:11:31.000Z
2022-02-10T20:00:52.000Z
src/character/character.hpp
Galfurian/RadMud
1362cb0ee1b7a17386e57a98e29dd8baeea75af3
[ "MIT" ]
null
null
null
src/character/character.hpp
Galfurian/RadMud
1362cb0ee1b7a17386e57a98e29dd8baeea75af3
[ "MIT" ]
2
2016-06-30T15:20:01.000Z
2020-08-27T18:28:33.000Z
/// @file character.hpp /// @brief Define all the methods need to manipulate a character. /// @details It's the master class for both Player and Mobile, here are defined /// all the common methods needed to manipulate every dynamic living /// beeing that are playing. /// @author Enrico Fraccaroli /// @date Aug 23 2014 /// @copyright /// Copyright (c) 2016 Enrico Fraccaroli <enrico.fraccaroli@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 above copyright notice and this permission notice shall be included /// in all copies or substantial portions of the Software. /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL /// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING /// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER /// DEALINGS IN THE SOFTWARE. #pragma once #include "ability.hpp" #include "exit.hpp" #include "race.hpp" #include "item.hpp" #include "faction.hpp" #include "bodyPart.hpp" #include "stringBuilder.hpp" #include "effectManager.hpp" #include "processInput.hpp" #include "combatAction.hpp" #include "argumentHandler.hpp" #include "meleeWeaponItem.hpp" #include "rangedWeaponItem.hpp" #include "characterPosture.hpp" #include "characterVector.hpp" #include "skillManager.hpp" #include "itemUtils.hpp" #include <deque> #include <mutex> class Room; class Player; class Mobile; struct lua_State; /// The list of possible actions. using GenderType = enum class GenderType_t { None, ///< The character has no gender (robot). Female, ///< The character is a female. Male ///< The character is a male. }; /// Used to determine the flag of the character. using CharacterFlag = enum class CharacterFlag_t { None = 0, ///< No flag. IsGod = 1, ///< The character is a GOD. Invisible = 2 ///< The character is invisible. }; /// @brief Character class, father of Player and Mobile. /// @details /// It's the main class that contains all the information that both /// players and NPCs shares. In order to allow dynamic casting(polymorphism), /// i've created a method called isMobile, used to identify the subtype of the /// subclass. class Character : public UpdateInterface { public: /// Character name. std::string name; /// Character description. std::string description; /// Character gender. GenderType gender; /// Character weight. double weight; /// Character level. unsigned int level; /// Character flags. unsigned int flags; /// The character race. Race * race; /// The character faction. Faction * faction; /// Character health value. unsigned int health; /// Character stamina value. unsigned int stamina; /// Character level of hunger int hunger; /// Character level of thirst. int thirst; /// Character abilities. std::map<Ability, unsigned int> abilities; /// The current room the character is in. Room * room; /// Character's inventory. ItemVector inventory; /// Character's equipment. ItemVector equipment; /// Character's posture. CharacterPosture posture; /// The lua_State associated with this character. lua_State * L; /// Character current action. std::deque<std::shared_ptr<GeneralAction>> actionQueue; /// Mutex for the action queue. mutable std::mutex actionQueueMutex; /// The input handler. std::shared_ptr<ProcessInput> inputProcessor; /// Active effects on player. EffectManager effectManager; /// The player's list of skills. SkillManager skillManager; /// List of opponents. CombatHandler combatHandler; /// @brief Constructor. Character(); /// @brief Destructor. virtual ~Character(); /// @brief Disable copy constructor. Character(const Character & source) = delete; /// @brief Disable assign operator. Character & operator=(const Character &) = delete; /// @brief Check the correctness of the character information. /// @return <b>True</b> if the information are correct,<br> /// <b>False</b> otherwise. virtual bool check() const; /// @brief Used to identify if this character is an npc. /// @return <b>True</b> if is an NPC,<br> /// <b>False</b> otherwise. virtual bool isMobile() const; /// @brief Used to identify if this character is a player. /// @return <b>True</b> if is an NPC,<br> /// <b>False</b> otherwise. virtual bool isPlayer() const; /// @brief Fills the provided table with the information concerning the /// character. /// @param sheet The table that has to be filled. virtual void getSheet(Table & sheet) const; /// @brief Initializes the variables of the chracter. virtual void initialize(); /// @brief Return the name of the character with all lowercase characters. /// @return The name of the character. virtual std::string getName() const = 0; /// @brief Return the name of the character. /// @return The name of the character. std::string getNameCapital() const; /// @brief Return the static description of this character. /// @return The static description. std::string getStaticDesc() const; /// @brief Return the subject pronoun for the character. std::string getSubjectPronoun() const; /// @brief Return the possessive pronoun for the character. std::string getPossessivePronoun() const; /// @brief Return the object pronoun for the character. std::string getObjectPronoun() const; /// @brief Allows to set the value of a given ability. /// @param ability The ability to set. /// @param value The value to set. /// @return <b>True</b> if the value is correct,<br> /// <b>False</b> otherwise. bool setAbility(const Ability & ability, const unsigned int & value); /// @brief Provides the value of the given ability. /// @param ability The ability to retrieve. /// @param withEffects If set to false, this function just return the /// ability value without the contribution due to /// the active effects. /// @return The overall ability value. unsigned int getAbility(const Ability & ability, bool withEffects = true) const; /// @brief Provides the modifier of the given ability. /// @param ability The ability of which the modifier has to be /// retrieved. /// @param withEffects If set to false, this function just return the /// ability modifier without the contribution due /// to the active effects. /// @return The overall ability modifer. unsigned int getAbilityModifier(const Ability & ability, bool withEffects = true) const; /// @brief Provides the base ten logarithm of the desired ability /// modifier, multiplied by an optional multiplier. Also, /// a base value can be provided. /// @details Value = Base + (Multiplier * log10(AbilityModifier)) /// @param ability The ability of which the modifier has to be /// retrieved. /// @param base The base value to which the evaluated modifier is summed. /// @param multiplier The log10 modifer is multiplied by this value. /// @param withEffects If set to false, this function just return the /// ability modifier without the contribution due /// to the active effects. /// @return The overall base ten logarithm of the given ability modifer. unsigned int getAbilityLog( const Ability & ability, const double & base = 0.0, const double & multiplier = 1.0, const bool & withEffects = true) const; /// @brief Allows to SET the health value. /// @param value The value to set. /// @param force <b>True</b> if the value is greather than the maximum /// the function set the health to it and /// returns true,<br> /// <b>False</b> return false. /// @return <b>True</b> if the function has set the value,<br> /// <b>False</b> otherwise. bool setHealth(const unsigned int & value, const bool & force = false); /// @brief Allows to ADD a value to the current health value. /// @param value The value to add. /// @param force <b>True</b> if the resulting value is greather than /// the maximum the function set the health to it and /// returns true,<br> /// <b>False</b> return false. /// @return <b>True</b> if the function has added the value,<br> /// <b>False</b> otherwise. bool addHealth(const unsigned int & value, const bool & force = false); /// @brief Allows to REMOVE a value to the current health value. /// @param value The value to remove. /// @param force <b>True</b> if the resulting value is lesser than /// zero the function set the health to it and /// returns true,<br> /// <b>False</b> return false. /// @return <b>True</b> if the function has removed the value,<br> /// <b>False</b> otherwise. bool remHealth(const unsigned int & value, const bool & force = false); /// @brief Return the max health value. /// @param withEffects <b>True</b> also add the health due to effects,<br> /// <b>False</b> otherwise. /// @return The maximum health for this character. unsigned int getMaxHealth(bool withEffects = true) const; /// @brief Get character condition. /// @param self If the sentence has to be for another character or not. /// @return Condition of this character. std::string getHealthCondition(const bool & self = false); /// @brief Allows to SET the stamina value. /// @param value The value to set. /// @param force <b>True</b> if the value is greather than the maximum /// the function set the stamina to it and /// returns true,<br> /// <b>False</b> return false. /// @return <b>True</b> if the function has set the value,<br> /// <b>False</b> otherwise. bool setStamina(const unsigned int & value, const bool & force = false); /// @brief Allows to ADD a value to the current stamina value. /// @param value The value to add. /// @param force <b>True</b> if the resulting value is greather than /// the maximum the function set the stamina to it and /// returns true,<br> /// <b>False</b> return false. /// @return <b>True</b> if the function has added the value,<br> /// <b>False</b> otherwise. bool addStamina(const unsigned int & value, const bool & force = false); /// @brief Allows to REMOVE a value to the current stamina value. /// @param value The value to remove. /// @param force <b>True</b> if the resulting value is lesser than /// zero the function set the stamina to it and /// returns true,<br> /// <b>False</b> return false. /// @return <b>True</b> if the function has removed the value,<br> /// <b>False</b> otherwise. bool remStamina(const unsigned int & value, const bool & force = false); /// @brief Return the max stamina value. /// @param withEffects <b>True</b> also add the stamina due to effects,<br> /// <b>False</b> otherwise. /// @return The maximum stamina for this character. unsigned int getMaxStamina(bool withEffects = true) const; /// @brief Get the character stamina condition. /// @return Stamina condition of the character. std::string getStaminaCondition(); /// @brief Evaluate the maximum distance at which the character can still see. /// @return The maximum radius of view. int getViewDistance() const; /// @brief Allows to set an action. /// @param _action The action that has to be set. void pushAction(const std::shared_ptr<GeneralAction> & _action); /// @brief Provides a pointer to the action at the front position and /// then remove it from the queue. void popAction(); /// @brief Provides a pointer to the current action. std::shared_ptr<GeneralAction> & getAction(); /// @brief Provides a pointer to the current action. std::shared_ptr<GeneralAction> const & getAction() const; /// @brief Performs any pending action. void performAction(); /// @brief Allows to reset the entire action queue. void resetActionQueue(); /// @brief Search for the item in the inventory. /// @param key The item to search. /// @param number Position of the item we want to look for. /// @return The item, if it's in the character's inventory. inline Item * findInventoryItem(std::string const & key, int & number) { return ItemUtils::FindItemIn(inventory, key, number); } /// @brief Search for the item in equipment. /// @param key The item to search. /// @param number Position of the item we want to look for. /// @return The item, if it's in the character's equipment. Item * findEquipmentItem(std::string const & key, int & number) { return ItemUtils::FindItemIn(equipment, key, number); } /// @brief Search an item nearby, (eq, inv, room). /// @param key The item to search. /// @param number Position of the item we want to look for. /// @return The item, if it's found. Item * findNearbyItem(std::string const & key, int & number); /// @brief Search the item at given position and return it. /// @param bodyPart The body part where the method need to search the item. /// @return The item, if it's in the character's equipment. Item * findItemAtBodyPart(const std::shared_ptr<BodyPart> & bodyPart) const; /// @brief Add the passed item to character's inventory. /// @param item The item to add to inventory. virtual void addInventoryItem(Item *& item); /// @brief Equip the passed item. /// @param item The item to equip. virtual void addEquipmentItem(Item *& item); /// @brief Remove the passed item from the character's inventory. /// @param item The item to remove from inventory. /// @return <b>True</b> if the operation goes well,<br> /// <b>False</b> otherwise. virtual bool remInventoryItem(Item * item); /// @brief Remove from current equipment the item. /// @param item The item to remove. /// @return <b>True</b> if the operation goes well,<br> /// <b>False</b> otherwise. virtual bool remEquipmentItem(Item * item); /// @brief Check if the player can carry the item. /// @param item The item we want to check. /// @param quantity The amount of item to check (by default it is 1). /// @return <b>True</b> if the character can lift the item,<br> /// <b>False</b> otherwise. bool canCarry(Item * item, unsigned int quantity) const; /// @brief The total carrying weight for this character. /// @return The total carrying weight. double getCarryingWeight() const; /// @brief The maximum carrying weight for this character. /// @return The maximum carrying weight. double getMaxCarryingWeight() const; /// @brief Check if the character can wield a given item. /// @param item The item to wield. /// @param error The error message. /// @return Where the item can be wielded. std::vector<std::shared_ptr<BodyPart>> canWield(Item * item, std::string & error) const; /// @brief Check if the character can wear a given item. /// @param item The item to wear. /// @param error The error message. /// @return Where the item can be worn. std::vector<std::shared_ptr<BodyPart>> canWear(Item * item, std::string & error) const; /// @brief Checks if inside the inventory there is a light source. /// @return <b>True</b> if there is a light source,<br> /// <b>False</b> otherwise. bool inventoryIsLit() const; /// @brief Sums the given value to the current thirst. /// @param value The value to sum. void addThirst(const int & value); /// @brief Get character level of thirst. /// @return Thirst of this character. std::string getThirstCondition() const; /// @brief Sums the given value to the current hunger. /// @param value The value to sum. void addHunger(const int & value); /// @brief Get character level of hunger. /// @return Hunger of this character. std::string getHungerCondition() const; /// @brief Update the health. void updateHealth(); /// @brief Update the stamina. void updateStamina(); /// @brief Update the hunger. void updateHunger(); /// @brief Update the thirst. void updateThirst(); /// @brief Update the list of expired effects. void updateExpiredEffects(); /// @brief Update the list of activated effects. void updateActivatedEffects(); /// @brief Provide a detailed description of the character. /// @return A detailed description of the character. std::string getLook(); /// @brief Check if the current character can see the target character. /// @param target The target character. /// @return <b>True</b> if the can see the other character,<br> /// <b>False</b> otherwise. bool canSee(Character * target) const; // Combat functions. /// @brief Provides the overall armor class. /// @return The armor class. unsigned int getArmorClass() const; /// @brief Function which checks if the character can attack /// with a weapon equipped at the given body part. /// @param bodyPart The body part at which the weapon could be. /// @return <b>True</b> if the item is there,<br> /// <b>False</b> otherwise. bool canAttackWith(const std::shared_ptr<BodyPart> & bodyPart) const; /// @brief Checks if the given target is both In Sight and within the Range of Sight. /// @param target The target character. /// @param range The maximum range. /// @return <b>True</b> if the target is in sight,<br> /// <b>False</b> otherwise. bool isAtRange(Character * target, const int & range); /// @brief Handle what happend when this character die. virtual void kill(); /// @brief Create a corpse on the ground. /// @return A pointer to the corpse. Item * createCorpse(); /// @brief Handle character input. /// @param command Command that need to be handled. /// @return <b>True</b> if the command has been correctly executed,<br> /// <b>False</b> otherwise. bool doCommand(const std::string & command); /// @brief Returns the character <b>statically</b> casted to player. /// @return The player version of the character. Player * toPlayer(); /// @brief Returns the character <b>statically</b> casted to mobile. /// @return The mobile version of the character. Mobile * toMobile(); /// @brief Specific function used by lua to add an equipment item. void luaAddEquipment(Item * item); /// @brief Specific function used by lua to remove an equipment item. bool luaRemEquipment(Item * item); /// @brief Specific function used by lua to add an inventory item. void luaAddInventory(Item * item); /// @brief Specific function used by lua to remove an inventory item. bool luaRemInventory(Item * item); /// @brief Operator used to order the character based on their name. bool operator<(const class Character & source) const; /// @brief Operator used to order the character based on their name. bool operator==(const class Character & source) const; /// @brief Sends a message to the character. /// @param msg Message to send. virtual void sendMsg(const std::string & msg); /// @brief Sends a message to the character. /// @param msg The message to send /// @param args Packed arguments. template<typename ... Args> void sendMsg(const std::string & msg, const Args & ... args) { this->sendMsg(StringBuilder::build(msg, args ...)); } protected: void updateTicImpl() override; void updateHourImpl() override; }; /// @addtogroup FlagsToList /// @{ /// Return the string describing the type of Gender. std::string GetGenderTypeName(GenderType type); /// Return the string describing the given character flag. std::string GetCharacterFlagName(CharacterFlag flag); /// Return a list of string containg the Character flags contained inside the value. std::string GetCharacterFlagString(unsigned int flags); /// @}
39.111712
89
0.642466
Galfurian
2b108cb66775235bc0ce8abd982dc031aad83e6d
760
hpp
C++
TurbulentArena/DebugWindow.hpp
doodlemeat/Turbulent-Arena
9030f291693e670f7751e23538e649cc24dc929f
[ "MIT" ]
2
2017-02-03T04:30:29.000Z
2017-03-27T19:33:38.000Z
TurbulentArena/DebugWindow.hpp
doodlemeat/Turbulent-Arena
9030f291693e670f7751e23538e649cc24dc929f
[ "MIT" ]
null
null
null
TurbulentArena/DebugWindow.hpp
doodlemeat/Turbulent-Arena
9030f291693e670f7751e23538e649cc24dc929f
[ "MIT" ]
null
null
null
//DebugWindow.hpp #pragma once #include <sstream> namespace bjoernligan { class DebugWindow : public sf::Drawable { private: DebugWindow(const bool &p_bActive); DebugWindow(const DebugWindow&); DebugWindow& operator=(const DebugWindow&); public: typedef std::unique_ptr<DebugWindow> Ptr; static Ptr Create(const bool &p_bActive = false); bool Initialize(); void draw(sf::RenderTarget& target, sf::RenderStates states) const; void Update(const float &p_fDeltaTime); void SetActive(const bool &p_bActive); void SetPos(const float &p_x, const float &p_y); void SetPos(const sf::Vector2f &p_xPos); private: bool m_bActive; sf::Text m_xFps; std::stringstream m_xSStream; std::unique_ptr<sf::RectangleShape> m_xBgRect; }; }
22.352941
69
0.734211
doodlemeat
2b1308ba57844e88e867c04472f9112a469d6e1b
2,512
cpp
C++
code/src/pdflib/page_tree.cpp
jgresula/jagpdf
6c36958b109e6522e6b57d04144dd83c024778eb
[ "MIT" ]
54
2015-02-16T14:25:16.000Z
2022-03-16T07:54:25.000Z
code/src/pdflib/page_tree.cpp
jgresula/jagpdf
6c36958b109e6522e6b57d04144dd83c024778eb
[ "MIT" ]
null
null
null
code/src/pdflib/page_tree.cpp
jgresula/jagpdf
6c36958b109e6522e6b57d04144dd83c024778eb
[ "MIT" ]
30
2015-03-05T08:52:25.000Z
2022-02-17T13:49:15.000Z
// Copyright (c) 2005-2009 Jaroslav Gresula // // Distributed under the MIT license (See accompanying file // LICENSE.txt or copy at http://jagpdf.org/LICENSE.txt) // #include "precompiled.h" #include "page_tree.h" #include "page_tree_node.h" #include "page_object.h" #include <core/generic/refcountedimpl.h> #include <boost/ref.hpp> using namespace boost; namespace jag { namespace pdf { PageTreeBuilder::PageTreeBuilder(DocWriterImpl& doc, int t) : m_doc(doc) , m_t(t) , m_max_children(2*t) { } // // // TreeNode::TreeNodePtr PageTreeBuilder::BuildPageTree( boost::ptr_vector<PageObject>& nodes) { // copy page objects to buffer_a m_buffer_a.reserve(nodes.size()); boost::ptr_vector<PageObject>::iterator it; for (it = nodes.begin(); it != nodes.end(); ++it) { TreeNode::TreeNodePtr data(&*it); m_buffer_a.push_back(data); } m_source = &m_buffer_a; // reserve some memory in the buffer_b m_buffer_b.reserve(nodes.size() / m_max_children + 1); m_dest = &m_buffer_b; // build tree levels, one at a time do { BuildOneTreeLevel(); std::swap(m_source, m_dest); m_dest->resize(0); } while(m_source->size() > 1); if (m_source->size() == 1) { return (*m_source)[0]; } else { return TreeNode::TreeNodePtr(); } } // // // void PageTreeBuilder::BuildOneTreeLevel() { int remaining_nodes = static_cast<int>(m_source->size()); int start_offset = 0; while(remaining_nodes) { int num_kids_for_this_node = 0; if (remaining_nodes >= m_max_children + m_t) { // at least two nodes are going to be created num_kids_for_this_node = m_max_children; } else if (remaining_nodes <= m_max_children) { // only single node is going to be created num_kids_for_this_node = remaining_nodes; } else { // exactly two nodes are going to be created, none of them is full num_kids_for_this_node = remaining_nodes / 2; } TreeNode::TreeNodePtr new_node = m_nodes.construct(ref(m_doc)); m_dest->push_back(new_node); for (int i=start_offset; i<start_offset+num_kids_for_this_node; ++i) { new_node->add_kid(m_source->at(i)); } start_offset += num_kids_for_this_node; remaining_nodes -= num_kids_for_this_node; } } }} //namespace jag::pdf
23.045872
78
0.617834
jgresula
2b154804a41ee453695ad335d17a303a816c4e21
402
hpp
C++
raptor/gallery/par_matrix_market.hpp
lukeolson/raptor
526c88d0801634e6fb41375ae077f2d4aa3241a4
[ "BSD-2-Clause" ]
25
2017-11-20T21:45:43.000Z
2019-01-27T15:03:25.000Z
raptor/gallery/par_matrix_market.hpp
haoxiangmiao/raptor
866977b8166e39675a6a1fb883c57b7b9395d32f
[ "BSD-2-Clause" ]
3
2017-11-21T01:20:20.000Z
2018-11-16T17:33:06.000Z
raptor/gallery/par_matrix_market.hpp
haoxiangmiao/raptor
866977b8166e39675a6a1fb883c57b7b9395d32f
[ "BSD-2-Clause" ]
5
2017-11-20T22:03:57.000Z
2018-12-05T10:30:22.000Z
/* * Matrix Market I/O library for ANSI C * * See http://math.nist.gov/MatrixMarket for details. * * */ #ifndef PAR_MM_IO_H #define PAR_MM_IO_H #include "matrix_market.hpp" #include "core/types.hpp" #include "core/par_matrix.hpp" using namespace raptor; /* high level routines */ ParCSRMatrix* read_par_mm(const char *fname); void write_par_mm(ParCSRMatrix* A, const char *fname); #endif
15.461538
54
0.723881
lukeolson
2b15ae0c66fac4c2c4afbc7a6ce2c233d8fe5be9
867
hpp
C++
include/basic3d/zbuffer.hpp
MasterQ32/Basic3D
1da1ad64116018afe2b97372d9632d0b72b1ff95
[ "MIT" ]
1
2018-11-15T22:29:55.000Z
2018-11-15T22:29:55.000Z
include/basic3d/zbuffer.hpp
MasterQ32/Basic3D
1da1ad64116018afe2b97372d9632d0b72b1ff95
[ "MIT" ]
null
null
null
include/basic3d/zbuffer.hpp
MasterQ32/Basic3D
1da1ad64116018afe2b97372d9632d0b72b1ff95
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <array> #include <limits> namespace Basic3D { //! Provides a basic z-buffer template<int WIDTH, int HEIGHT, typename Depth = std::uint16_t> class ZBuffer { public: typedef Depth depth_t; private: std::array<depth_t, WIDTH * HEIGHT> zvalues; public: ZBuffer() : zvalues() { this->clear(); } void clear(depth_t depth = std::numeric_limits<depth_t>::max()) { for(int i = 0; i < WIDTH * HEIGHT; i++) this->zvalues[i] = depth; } public: void setDepth(int x, int y, depth_t const & value) { zvalues[y * WIDTH + x] = value; } depth_t const & getDepth(int x, int y) const { return zvalues[y * WIDTH + x]; } }; }
23.432432
74
0.509804
MasterQ32
2b18c1a58e5c452db93b6d20e5409e76dce55d31
1,331
cpp
C++
109. Convert Sorted List to Binary Search Tree/solution.cpp
KailinLi/LeetCode-Solutions
bad6aa401b290a203a572362e63e0b1085f7fc36
[ "MIT" ]
2
2017-03-27T09:53:32.000Z
2017-04-07T07:48:54.000Z
109. Convert Sorted List to Binary Search Tree/solution.cpp
KailinLi/LeetCode-Solutions
bad6aa401b290a203a572362e63e0b1085f7fc36
[ "MIT" ]
null
null
null
109. Convert Sorted List to Binary Search Tree/solution.cpp
KailinLi/LeetCode-Solutions
bad6aa401b290a203a572362e63e0b1085f7fc36
[ "MIT" ]
null
null
null
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* change(ListNode* start, int length) { if (length == 1) { TreeNode* get = new TreeNode(start->val); return get; } else if (length == 2) { TreeNode* get = new TreeNode(start->next->val); TreeNode* next = new TreeNode(start->val); get->left = next; return get; } ListNode *p = start; int half = length / 2 + 1; for (int i = 1; i < half; i++) { p = p->next; } TreeNode* get = new TreeNode(p->val); get->left = change(start, half - 1); get->right = change(p->next, length - half); return get; } TreeNode* sortedListToBST(ListNode* head) { ListNode* p = head; int length = 0; while (p) { p = p->next; length++; } if (length == 0) return nullptr; return change(head, length); } };
26.098039
59
0.486852
KailinLi
2b24d50623f5ba9c0ed59fd55b0cb00c616c6aa3
2,353
tpp
C++
src/algorithms/rem_factorial_EltZZ.tpp
adienes/remainder-tree
0aa76214ab6f2a4389ec45a239ea660749989a90
[ "MIT" ]
null
null
null
src/algorithms/rem_factorial_EltZZ.tpp
adienes/remainder-tree
0aa76214ab6f2a4389ec45a239ea660749989a90
[ "MIT" ]
null
null
null
src/algorithms/rem_factorial_EltZZ.tpp
adienes/remainder-tree
0aa76214ab6f2a4389ec45a239ea660749989a90
[ "MIT" ]
null
null
null
// included by rem_factorial_custom.tpp (in case we want to change the file location) #include <cassert> #include <NTL/ZZ_pX.h> #include <NTL/matrix.h> #include "../elements/element.hpp" #include "factorial_engine.hpp" using NTL::ZZ; using NTL::ZZ_p; using NTL::ZZ_pX; using NTL::Mat; Elt<ZZ> calculate_factorial(long n, const Elt<ZZ>& m, const std::function<vector<Elt<ZZ>> (long, long)>& get_A, const PolyMatrix& formula){ if (n == 0) { return Elt<ZZ>(1); } assert(("No formula given!" && not formula.empty())); assert(("Element given is not a square matrix." && (formula.size() == formula[0].size()))); // Matrix-type elements assert(("ZZ's must have 1x1 matrix formulas." && ((long)formula.size() <= 1))); // Do naive_factorial if n is small enough if(n < 30000 || formula.size() == 0){ return naive_factorial<Elt<ZZ>, Elt<ZZ>>(n, m, get_A); // TODO: write naive_factorial } long maxdeg = 0; for(const auto& term : formula[0][0]){ if(term.first > maxdeg){ maxdeg = term.first; } } // Linear and Polynomial-type elements if(n < 1000000000 || maxdeg >= 2){ // TODO: convert polynomial coefficients into ZZ_p and call poly_factorial() // Otherwise, do poly_factorial ZZ_pX poly; for(const auto& term : formula[0][0]){ ZZ_p coeff; coeff.init(m.t); coeff = term.second; SetCoeff(poly, term.first, coeff); } ZZ_p output; output.init(m.t); output = poly_factorial(n, m.t, poly); // TODO: write poly_factorial Elt<ZZ> output_elt(rep(output)); return output_elt; } // Large Linear-type elements else{ // TODO: convert polynomial coefficients into Mat<ZZ_p> and call matrix_factorial() Mat<ZZ_pX> matrix; matrix.SetDims(1, 1); ZZ_pX poly; for(const auto& term : formula[0][0]){ ZZ_p coeff; coeff.init(m.t); coeff = term.second; SetCoeff(poly, term.first, coeff); } matrix.put(0, 0, poly); Mat<ZZ_p> output; output.SetDims(1, 1); output = matrix_factorial(n, m.t, matrix); Elt<ZZ> output_elt(rep(output.get(0, 0))); return output_elt; } }
30.166667
139
0.576711
adienes
2b27eac05c8402f32f1dbad10a6b1ff5dc8f5ac5
2,363
cpp
C++
codeforces/round-278/div-2/candy_boxes.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-07-16T01:46:38.000Z
2020-07-16T01:46:38.000Z
codeforces/round-278/div-2/candy_boxes.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
null
null
null
codeforces/round-278/div-2/candy_boxes.cpp
Rkhoiwal/Competitive-prog-Archive
18a95a8b2b9ca1a28d6fe939c1db5450d541ddc9
[ "MIT" ]
1
2020-05-27T14:30:43.000Z
2020-05-27T14:30:43.000Z
#include <algorithm> #include <iostream> #include <vector> using namespace std; inline void use_io_optimizations() { ios_base::sync_with_stdio(false); cin.tie(nullptr); } inline void solve_with_four_left_boxes(const vector<unsigned int>& boxes) { if ((3 * boxes[0] == boxes[3]) && (boxes[1] + boxes[2] == 4 * boxes[0])) { cout << "YES\n"; } else { cout << "NO\n"; } } inline void solve_with_three_left_boxes(const vector<unsigned int>& boxes) { unsigned int missing_box; if (3 * boxes[0] == boxes[2]) { missing_box = 4 * boxes[0] - boxes[1]; } else if (boxes[1] + boxes[2] == 4 * boxes[0]) { missing_box = 3 * boxes[0]; } else if (4 * boxes[2] == 3 * (boxes[0] + boxes[1])) { missing_box = boxes[2] / 3; } else { cout << "NO\n"; return; } cout << "YES" << '\n' << missing_box << '\n'; } inline void solve_with_two_left_boxes(const vector<unsigned int>& boxes) { if (boxes[1] <= 3 * boxes[0]) { cout << "YES" << '\n' << 4 * boxes[0] - boxes[1] << '\n' << 3 * boxes[0] << '\n'; } else { cout << "NO\n"; } } inline void solve_with_one_left_box(const vector<unsigned int>& boxes) { cout << "YES" << '\n' << boxes[0] << '\n' << 3 * boxes[0] << '\n' << 3 * boxes[0] << '\n'; } inline void solve_with_zero_left_boxes(const vector<unsigned int>& boxes) { cout << "YES" << '\n' << 1 << '\n' << 1 << '\n' << 3 << '\n' << 3 << '\n'; } int main() { use_io_optimizations(); unsigned int left_boxes; cin >> left_boxes; vector<unsigned int> boxes(4); for (unsigned int i {0}; i < left_boxes; ++i) { cin >> boxes[i]; } sort(boxes.begin(), boxes.begin() + left_boxes); switch (left_boxes) { case 4: solve_with_four_left_boxes(boxes); break; case 3: solve_with_three_left_boxes(boxes); break; case 2: solve_with_two_left_boxes(boxes); break; case 1: solve_with_one_left_box(boxes); break; case 0: solve_with_zero_left_boxes(boxes); break; } return 0; }
19.211382
76
0.493017
Rkhoiwal
1a7098538ce52920df14b974fe6a6a1f795fb3b6
396
cpp
C++
src/ClosestBinarySearchTreeValue.cpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
43
2015-10-10T12:59:52.000Z
2018-07-11T18:07:00.000Z
src/ClosestBinarySearchTreeValue.cpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
null
null
null
src/ClosestBinarySearchTreeValue.cpp
yanzhe-chen/LeetCode
d82f0b9721ea613ab216c78e7286671d0e9e4187
[ "MIT" ]
11
2015-10-10T14:41:11.000Z
2018-07-28T06:03:16.000Z
#include "ClosestBinarySearchTreeValue.hpp" #include <cmath> using namespace std; int ClosestBinarySearchTreeValue::closestValue(TreeNode *root, double target) { int closest = root->val; while (root) { if (abs(root->val - target) < abs(closest - target)) closest = root->val; root = root->val < target ? root->right : root->left; } return closest; }
26.4
79
0.643939
yanzhe-chen
1a751dfcaf4dbf84cbd4870d1bb0d7be2d22a8ed
11,084
cpp
C++
src/lib/serialport/qserialportinfo_mac.cpp
Hayesie88/emstudio
0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b
[ "MIT" ]
8
2015-11-16T19:15:55.000Z
2021-02-17T23:58:33.000Z
src/lib/serialport/qserialportinfo_mac.cpp
Hayesie88/emstudio
0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b
[ "MIT" ]
5
2015-11-12T00:19:59.000Z
2020-03-23T10:18:19.000Z
src/lib/serialport/qserialportinfo_mac.cpp
Hayesie88/emstudio
0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b
[ "MIT" ]
11
2015-03-15T23:02:48.000Z
2021-09-05T14:17:13.000Z
/**************************************************************************** ** ** Copyright (C) 2011-2012 Denis Shienkov <denis.shienkov@gmail.com> ** Copyright (C) 2011 Sergey Belyashov <Sergey.Belyashov@gmail.com> ** Copyright (C) 2012 Laszlo Papp <lpapp@kde.org> ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtSerialPort module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qserialportinfo.h" #include "qserialportinfo_p.h" #include <sys/param.h> #include <CoreFoundation/CoreFoundation.h> #include <IOKit/IOKitLib.h> #include <IOKit/serial/IOSerialKeys.h> #include <IOKit/storage/IOStorageDeviceCharacteristics.h> // for kIOPropertyProductNameKey #include <IOKit/usb/USB.h> #if defined(MAC_OS_X_VERSION_10_4) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_4) # include <IOKit/serial/ioss.h> #endif #include <IOKit/IOBSD.h> QT_BEGIN_NAMESPACE enum { MATCHING_PROPERTIES_COUNT = 6 }; QList<QSerialPortInfo> QSerialPortInfo::availablePorts() { QList<QSerialPortInfo> serialPortInfoList; int matchingPropertiesCounter = 0; ::CFMutableDictionaryRef matching = ::IOServiceMatching(kIOSerialBSDServiceValue); if (!matching) return serialPortInfoList; ::CFDictionaryAddValue(matching, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes)); io_iterator_t iter = 0; kern_return_t kr = ::IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &iter); if (kr != kIOReturnSuccess) return serialPortInfoList; io_registry_entry_t service; while ((service = ::IOIteratorNext(iter))) { ::CFTypeRef device = 0; ::CFTypeRef portName = 0; ::CFTypeRef description = 0; ::CFTypeRef manufacturer = 0; ::CFTypeRef vendorIdentifier = 0; ::CFTypeRef productIdentifier = 0; io_registry_entry_t entry = service; // Find MacOSX-specific properties names. do { if (!device) { device = ::IORegistryEntrySearchCFProperty(entry, kIOServicePlane, CFSTR(kIOCalloutDeviceKey), kCFAllocatorDefault, 0); if (device) ++matchingPropertiesCounter; } if (!portName) { portName = ::IORegistryEntrySearchCFProperty(entry, kIOServicePlane, CFSTR(kIOTTYDeviceKey), kCFAllocatorDefault, 0); if (portName) ++matchingPropertiesCounter; } if (!description) { description = ::IORegistryEntrySearchCFProperty(entry, kIOServicePlane, CFSTR(kIOPropertyProductNameKey), kCFAllocatorDefault, 0); if (!description) description = ::IORegistryEntrySearchCFProperty(entry, kIOServicePlane, CFSTR(kUSBProductString), kCFAllocatorDefault, 0); if (!description) description = ::IORegistryEntrySearchCFProperty(entry, kIOServicePlane, CFSTR("BTName"), kCFAllocatorDefault, 0); if (description) ++matchingPropertiesCounter; } if (!manufacturer) { manufacturer = ::IORegistryEntrySearchCFProperty(entry, kIOServicePlane, CFSTR(kUSBVendorString), kCFAllocatorDefault, 0); if (manufacturer) ++matchingPropertiesCounter; } if (!vendorIdentifier) { vendorIdentifier = ::IORegistryEntrySearchCFProperty(entry, kIOServicePlane, CFSTR(kUSBVendorID), kCFAllocatorDefault, 0); if (vendorIdentifier) ++matchingPropertiesCounter; } if (!productIdentifier) { productIdentifier = ::IORegistryEntrySearchCFProperty(entry, kIOServicePlane, CFSTR(kUSBProductID), kCFAllocatorDefault, 0); if (productIdentifier) ++matchingPropertiesCounter; } // If all matching properties is found, then force break loop. if (matchingPropertiesCounter == MATCHING_PROPERTIES_COUNT) break; kr = ::IORegistryEntryGetParentEntry(entry, kIOServicePlane, &entry); } while (kr == kIOReturnSuccess); (void) ::IOObjectRelease(entry); // Convert from MacOSX-specific properties to Qt4-specific. if (matchingPropertiesCounter > 0) { QSerialPortInfo serialPortInfo; QByteArray buffer(MAXPATHLEN, 0); if (device) { if (::CFStringGetCString(CFStringRef(device), buffer.data(), buffer.size(), kCFStringEncodingUTF8)) { serialPortInfo.d_ptr->device = QString::fromUtf8(buffer); } ::CFRelease(device); } if (portName) { if (::CFStringGetCString(CFStringRef(portName), buffer.data(), buffer.size(), kCFStringEncodingUTF8)) { serialPortInfo.d_ptr->portName = QString::fromUtf8(buffer); } ::CFRelease(portName); } if (description) { if (::CFStringGetCString(CFStringRef(description), buffer.data(), buffer.size(), kCFStringEncodingUTF8)) { serialPortInfo.d_ptr->description = QString::fromUtf8(buffer); } ::CFRelease(description); } if (manufacturer) { if (::CFStringGetCString(CFStringRef(manufacturer), buffer.data(), buffer.size(), kCFStringEncodingUTF8)) { serialPortInfo.d_ptr->manufacturer = QString::fromUtf8(buffer); } ::CFRelease(manufacturer); } quint16 value = 0; if (vendorIdentifier) { serialPortInfo.d_ptr->hasVendorIdentifier = ::CFNumberGetValue(CFNumberRef(vendorIdentifier), kCFNumberIntType, &value); if (serialPortInfo.d_ptr->hasVendorIdentifier) serialPortInfo.d_ptr->vendorIdentifier = value; ::CFRelease(vendorIdentifier); } if (productIdentifier) { serialPortInfo.d_ptr->hasProductIdentifier = ::CFNumberGetValue(CFNumberRef(productIdentifier), kCFNumberIntType, &value); if (serialPortInfo.d_ptr->hasProductIdentifier) serialPortInfo.d_ptr->productIdentifier = value; ::CFRelease(productIdentifier); } serialPortInfoList.append(serialPortInfo); } (void) ::IOObjectRelease(service); } (void) ::IOObjectRelease(iter); return serialPortInfoList; } QT_END_NAMESPACE
40.600733
138
0.480603
Hayesie88
1a775015d67a723319faa41188ea368f93b840f6
764
cpp
C++
greedy_problems/maximum_frequency_of_element.cpp
sanathvernekar/Routine_codes
a898ca7e79cf39c289cb2fefaf764c9f8e0eb331
[ "MIT" ]
null
null
null
greedy_problems/maximum_frequency_of_element.cpp
sanathvernekar/Routine_codes
a898ca7e79cf39c289cb2fefaf764c9f8e0eb331
[ "MIT" ]
null
null
null
greedy_problems/maximum_frequency_of_element.cpp
sanathvernekar/Routine_codes
a898ca7e79cf39c289cb2fefaf764c9f8e0eb331
[ "MIT" ]
null
null
null
#include <vector> #include <map> #include<bits/stdc++.h> using namespace std; long long int max_frequency(vector<long long int> const& v) { map<long long int, long long int> frequencyMap; long long int maxFrequency = 0; long long int mostFrequentElement = 0; for (long long int x : v) { long long int f = ++frequencyMap[x]; if (f > maxFrequency) { maxFrequency = f; mostFrequentElement = x; } } return maxFrequency; } int main() { long long int t,n,i,j,temp; cin>>t; while(t--){ cin>>n; vector<long long int >v; for(i=0;i<n;i++){ cin>>temp; v.push_back(temp); } cout<<max_frequency(v)<<endl; } }
21.222222
59
0.537958
sanathvernekar
1a7d0a4b1f6fbfbd04070f3df6da1bcfbd53a229
1,077
cpp
C++
STRINGS/Upper case conversion.cpp
snanacha/Coding-questions
18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d
[ "MIT" ]
null
null
null
STRINGS/Upper case conversion.cpp
snanacha/Coding-questions
18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d
[ "MIT" ]
1
2021-03-30T14:00:56.000Z
2021-03-30T14:00:56.000Z
STRINGS/Upper case conversion.cpp
snanacha/Coding-questions
18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d
[ "MIT" ]
null
null
null
/* Upper case conversion School Accuracy: 72.51% Submissions: 1152 Points: 0 Given a string str, convert the first letter of each word in the string to uppercase. Example 1: Input: str = "i love programming" Output: "I Love Programming" Explanation: 'I', 'L', 'P' are the first letters of the three words. Your Task: You dont need to read input or print anything. Complete the function transform() which takes s as input parameter and returns the transformed string. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) to store resultant string Constraints: 1 <= N <= 104 The original string str only consists of lowercase alphabets and spaces to separate words. */ CODE ---- string transform(string s) { // code here int i; for(i=0;i<s.size();i++) // to check if first few characters of a string have spaces { if(s[i]!=' ') { s[i]=toupper(s[i]); break; } } for(;i<s.size();i++) { if(s[i]==' ') { s[i+1]=toupper(s[i+1]); } } return s; }
22.914894
150
0.622098
snanacha
1a7d59aa8da04b3bc9b6a7c6c73cdfb020f12695
2,133
cpp
C++
examples/sample2.cpp
SoultatosStefanos/preconditions
7c306219153e32afe6a915178f1e1c9fa1bdac8b
[ "MIT" ]
1
2021-09-07T21:10:05.000Z
2021-09-07T21:10:05.000Z
examples/sample2.cpp
SoultatosStefanos/preconditions
7c306219153e32afe6a915178f1e1c9fa1bdac8b
[ "MIT" ]
null
null
null
examples/sample2.cpp
SoultatosStefanos/preconditions
7c306219153e32afe6a915178f1e1c9fa1bdac8b
[ "MIT" ]
null
null
null
/** * @file sample2.cpp * @author Soultatos Stefanos (stefanoss1498@gmail.com) * @brief Contains sample code for the filters * @version 2.0 * @date 2021-10-29 * * @copyright Copyright (c) 2021 * */ #include "preconditions/filters.hpp" #include <array> #include <string> namespace { // Instead of: // // if (b.empty) // { // throw std::invalid_argument(); // } // return b; // // std::string verify_non_empty_string(const std::string b) { const auto not_empty = [&](const std::string x) { return x.empty(); }; return Preconditions::filter_argument<std::string>(b, not_empty); } // Instead of: // // if (b == 0) // { // throw std::domain_error(); // } // // int divide(const int a, const int b) { Preconditions::filter_domain<int>( b, [&](const int x) { return x != 0; }); // inline Preconditions::filter_domain<int>( b, [&](const int x) { return x != 0; }, "zero!"); // with msg return a / b; } // Instead of: // // if (length < 1) // { // throw std::length_error(); // } // // void peek_length(const int length) { Preconditions::filter_length<int>( length, [&](const int) { return length >= 1; }); // inline Preconditions::filter_length<int>( length, [&](const int) { return length >= 1; }, "illegal length"); // with msg } // Instead of: // // if (index >= 3) // { // throw std::out_of_range(); // } // // int get_index_of_array(const std::array<int, 3> a, const int index) { const auto in_range = [&](const int i) { return i <= 2; }; Preconditions::filter_range<int>(index, in_range); // inline Preconditions::filter_range<int>(index, in_range, "range!"); // with msg return a[index]; } class Entity { public: bool valid() const { return true; } }; // Instead of: // // if(!en.valid()) // { // ?? // } // // void do_wth_entity(const Entity& en) { const auto valid = [&](const Entity& e) { return e.valid(); }; Preconditions::filter_state<Entity>(en, valid); // inline Preconditions::filter_state<Entity>(en, valid, "invalid state"); // with msg } } // namespace
20.708738
76
0.586498
SoultatosStefanos
1a7e496044132273825225cbae15412343883b22
1,899
cpp
C++
Odyssey/OdysseyVulkanCore/OdysseyVulkanCore/Initialize/SubmitClasses/ImmediateSubmit.cpp
paulburgess1357/Odyssey
ad351d1df7eeb1b4223ffbdf91ec7e3307b87983
[ "MIT" ]
1
2022-03-10T02:45:04.000Z
2022-03-10T02:45:04.000Z
Odyssey/OdysseyVulkanCore/OdysseyVulkanCore/Initialize/SubmitClasses/ImmediateSubmit.cpp
paulburgess1357/Odyssey
ad351d1df7eeb1b4223ffbdf91ec7e3307b87983
[ "MIT" ]
null
null
null
Odyssey/OdysseyVulkanCore/OdysseyVulkanCore/Initialize/SubmitClasses/ImmediateSubmit.cpp
paulburgess1357/Odyssey
ad351d1df7eeb1b4223ffbdf91ec7e3307b87983
[ "MIT" ]
null
null
null
#include "OdysseyVulkanCore/OdysseyVulkanCore/Initialize/SubmitClasses/ImmediateSubmit.h" #include "OdysseyVulkanCore/OdysseyVulkanCore/Initialize/SubmitClasses/Exceptions.h" #include "OdysseyVulkanCore/OdysseyVulkanCore/Initialize/CreateInfo.h" #include "OdysseyVulkanCore/OdysseyVulkanCore/Utility/Macros.h" #include <functional> namespace OdysseyVulkanCore::Initialize { ImmediateSubmit::ImmediateSubmit(VkDevice vk_device, Handles::CommandPoolHandle m_short_term_cmd_pool, ScopedCommandBuffer scoped_buffer, Handles::FenceHandle fence) : m_vk_device{vk_device}, m_short_term_cmd_pool{std::move(m_short_term_cmd_pool)}, m_scoped_cmd_buffer{std::move(scoped_buffer)}, m_fence{std::move(fence)} { } void ImmediateSubmit::submit(std::function<void(VkCommandBuffer cmd)>&& function) const { auto vk_cmd_buffer = m_scoped_cmd_buffer.vk_cmd; const VkCommandBufferBeginInfo begin_info = CreateInfo::vk_command_buffer_begin_info( VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT); VK_ERROR(vkBeginCommandBuffer(vk_cmd_buffer, &begin_info), "Failed to begin command buffer recording!", Exceptions::CommandBufferRecordingException()) function(vk_cmd_buffer); VK_ERROR(vkEndCommandBuffer(vk_cmd_buffer), "Failed to end command buffer recording", Exceptions::CommandBufferRecordingException()) const VkSubmitInfo submit = CreateInfo::vk_submit_info(&vk_cmd_buffer); VK_ERROR(vkQueueSubmit(m_scoped_cmd_buffer.vk_submission_queue, 1, &submit, m_fence.m_handle), "Failed to submit command to queue (immediate submit)", Exceptions::CommandBufferSubmissionException()) vkWaitForFences(m_vk_device, 1, &m_fence.m_handle, VK_TRUE, UINT64_MAX); vkResetFences(m_vk_device, 1, &m_fence.m_handle); vkResetCommandPool(m_vk_device, m_short_term_cmd_pool.m_handle, 0); } } // namespace OdysseyVulkanCore::Initialize
52.75
114
0.796735
paulburgess1357
1a7e908bd3cc80291942a076353938cb2bee4a7b
7,925
cpp
C++
avdev-jni/src/main/cpp/dependencies/windows/mf/src/MFVideoCaptureDevice.cpp
lectureStudio/avdev
02b980705565ed2dcf3eacc4992bdf2f244f24a0
[ "Apache-2.0" ]
1
2021-08-10T02:59:58.000Z
2021-08-10T02:59:58.000Z
avdev-jni/src/main/cpp/dependencies/windows/mf/src/MFVideoCaptureDevice.cpp
lectureStudio/avdev
02b980705565ed2dcf3eacc4992bdf2f244f24a0
[ "Apache-2.0" ]
null
null
null
avdev-jni/src/main/cpp/dependencies/windows/mf/src/MFVideoCaptureDevice.cpp
lectureStudio/avdev
02b980705565ed2dcf3eacc4992bdf2f244f24a0
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016 Alex Andres * * 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 "MFVideoCaptureDevice.h" #include "MFVideoOutputStream.h" #include "MFTypeConverter.h" #include "MFInitializer.h" #include "WindowsHelper.h" #include <algorithm> #include <Mfreadwrite.h> #include <Mferror.h> namespace avdev { MFVideoCaptureDevice::MFVideoCaptureDevice(std::string name, std::string descriptor) : VideoCaptureDevice(name, descriptor) { MFInitializer initializer; jni::ComPtr<IMFMediaSource> mediaSource; mmf::CreateMediaSource(MFMediaType_Video, getDescriptor(), &mediaSource); mediaSource->QueryInterface(IID_IAMVideoProcAmp, (void**)&procAmp); mediaSource->QueryInterface(IID_IAMCameraControl, (void**)&cameraControl); } MFVideoCaptureDevice::~MFVideoCaptureDevice() { } std::list<PictureFormat> MFVideoCaptureDevice::getPictureFormats() { // Check, if formats already loaded. if (!formats.empty()) { return formats; } MFInitializer initializer; jni::ComPtr<IMFMediaSource> mediaSource; jni::ComPtr<IMFSourceReader> sourceReader; jni::ComPtr<IMFMediaType> type; DWORD typeIndex = 0; HRESULT hr; mmf::CreateMediaSource(MFMediaType_Video, getDescriptor(), &mediaSource); hr = MFCreateSourceReaderFromMediaSource(mediaSource, nullptr, &sourceReader); THROW_IF_FAILED(hr, "MMF: Create source reader from media source failed."); while (SUCCEEDED(hr)) { hr = sourceReader->GetNativeMediaType(0, typeIndex, &type); if (hr == MF_E_NO_MORE_TYPES) { break; } else if (SUCCEEDED(hr)) { UINT32 width, height; GUID guid; hr = MFGetAttributeSize(type, MF_MT_FRAME_SIZE, &width, &height); THROW_IF_FAILED(hr, "MMF: Get frame size failed."); hr = type->GetGUID(MF_MT_SUBTYPE, &guid); THROW_IF_FAILED(hr, "MMF: Get type guid failed."); formats.push_back(PictureFormat(width, height, MFTypeConverter::toPixelFormat(guid))); } ++typeIndex; } formats.unique(); return formats; } std::list<CameraControl> MFVideoCaptureDevice::getCameraControls() { // Check, if controls already loaded. if (!cameraControls.empty()) { return cameraControls; } if (!cameraControl) { // The device does not support IAMCameraControl. return cameraControls; } const MFTypeConverter::CameraControlMap controlMap = MFTypeConverter::getCameraControlMap(); HRESULT hr; for (auto const & kv : controlMap) { long min, max, delta, def, flags; hr = cameraControl->GetRange(kv.first, &min, &max, &delta, &def, &flags); if (FAILED(hr) || min == max) { continue; } bool autoMode = (flags & KSPROPERTY_CAMERACONTROL_FLAGS_AUTO); cameraControls.push_back(CameraControl(kv.second, min, max, delta, def, autoMode)); } return cameraControls; } std::list<PictureControl> MFVideoCaptureDevice::getPictureControls() { // Check, if controls already loaded. if (!pictureControls.empty()) { return pictureControls; } if (!procAmp) { // The device does not support IAMVideoProcAmp. return pictureControls; } const MFTypeConverter::PictureControlMap controlMap = MFTypeConverter::getPictureControlMap(); HRESULT hr; for (auto const & kv : controlMap) { long min, max, delta, def, flags; hr = procAmp->GetRange(kv.first, &min, &max, &delta, &def, &flags); if (FAILED(hr) || min == max) { continue; } bool autoMode = (flags & KSPROPERTY_VIDEOPROCAMP_FLAGS_AUTO); pictureControls.push_back(PictureControl(kv.second, min, max, delta, def, autoMode)); } return pictureControls; } void MFVideoCaptureDevice::setPictureControlAutoMode(PictureControlType type, bool autoMode) { if (!procAmp) { return; } long value = 0; long flags = 0; HRESULT hr = procAmp->Get(MFTypeConverter::toApiType(type), &value, &flags); THROW_IF_FAILED(hr, "MMF: Get picture control value failed."); flags = autoMode ? KSPROPERTY_VIDEOPROCAMP_FLAGS_AUTO : KSPROPERTY_VIDEOPROCAMP_FLAGS_MANUAL; hr = procAmp->Set(MFTypeConverter::toApiType(type), value, flags); THROW_IF_FAILED(hr, "MMF: Set picture control value failed."); } bool MFVideoCaptureDevice::getPictureControlAutoMode(PictureControlType type) { long value = getPictureControlValue(type); return value != 0; } void MFVideoCaptureDevice::setPictureControlValue(PictureControlType type, long value) { if (!procAmp) { return; } long min, max, delta, def, flags; HRESULT hr = procAmp->GetRange(MFTypeConverter::toApiType(type), &min, &max, &delta, &def, &flags); if (FAILED(hr)) { return; } // Respect the device range values. value = (std::max)(value, min); value = (std::min)(value, max); hr = procAmp->Set(MFTypeConverter::toApiType(type), value, flags); THROW_IF_FAILED(hr, "MMF: Set picture control value failed."); } long MFVideoCaptureDevice::getPictureControlValue(PictureControlType type) { if (!procAmp) { return 0; } long value = 0; long flags = 0; HRESULT hr = procAmp->Get(MFTypeConverter::toApiType(type), &value, &flags); THROW_IF_FAILED(hr, "MMF: Get picture control value failed."); return value; } void MFVideoCaptureDevice::setCameraControlAutoMode(CameraControlType type, bool autoMode) { if (!cameraControl) { return; } long value = 0; long flags = 0; HRESULT hr = cameraControl->Get(MFTypeConverter::toApiType(type), &value, &flags); THROW_IF_FAILED(hr, "MMF: Get camera control value failed."); flags = autoMode ? KSPROPERTY_CAMERACONTROL_FLAGS_AUTO : KSPROPERTY_CAMERACONTROL_FLAGS_MANUAL; hr = cameraControl->Set(MFTypeConverter::toApiType(type), value, flags); THROW_IF_FAILED(hr, "MMF: Set camera control value failed."); } bool MFVideoCaptureDevice::getCameraControlAutoMode(CameraControlType type) { long value = getCameraControlValue(type); return value != 0; } void MFVideoCaptureDevice::setCameraControlValue(CameraControlType type, long value) { if (!cameraControl) { return; } long min, max, delta, def, flags; HRESULT hr = cameraControl->GetRange(MFTypeConverter::toApiType(type), &min, &max, &delta, &def, &flags); if (FAILED(hr)) { return; } // Respect the device range values. value = (std::max)(value, min); value = (std::min)(value, max); hr = cameraControl->Set(MFTypeConverter::toApiType(type), value, KSPROPERTY_CAMERACONTROL_FLAGS_MANUAL); THROW_IF_FAILED(hr, "MMF: Set camera control value failed."); } long MFVideoCaptureDevice::getCameraControlValue(CameraControlType type) { if (!cameraControl) { return 0; } long value = 0; long flags = 0; HRESULT hr = cameraControl->Get(MFTypeConverter::toApiType(type), &value, &flags); THROW_IF_FAILED(hr, "MMF: Get camera control value failed."); return value; } void MFVideoCaptureDevice::setPictureFormat(PictureFormat format) { this->format = format; } PictureFormat const& MFVideoCaptureDevice::getPictureFormat() const { return format; } void MFVideoCaptureDevice::setFrameRate(float frameRate) { this->frameRate = frameRate; } float MFVideoCaptureDevice::getFrameRate() const { return frameRate; } PVideoOutputStream MFVideoCaptureDevice::createOutputStream(PVideoSink sink) { PVideoOutputStream stream = std::make_unique<MFVideoOutputStream>(getDescriptor(), sink); stream->setFrameRate(getFrameRate()); stream->setPictureFormat(getPictureFormat()); return stream; } }
26.155116
107
0.720505
lectureStudio
1a8046f70fc3a8f51fa385ecdcfba6767d5f840f
313
cpp
C++
Codeforces Round 323/Asphalting Roads/main.cpp
sqc1999-oi/Codeforces
5551e0e4b9dc66bb77c697568f0584aac3dbefae
[ "MIT" ]
1
2016-07-18T12:05:56.000Z
2016-07-18T12:05:56.000Z
Codeforces Round 323/Asphalting Roads/main.cpp
sqc1999/Codeforces
5551e0e4b9dc66bb77c697568f0584aac3dbefae
[ "MIT" ]
null
null
null
Codeforces Round 323/Asphalting Roads/main.cpp
sqc1999/Codeforces
5551e0e4b9dc66bb77c697568f0584aac3dbefae
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> using namespace std; bool vh[51], vv[51]; int main() { ios::sync_with_stdio(false); int n; cin >> n; for (int i = 1; i <= n*n; i++) { int h, v; cin >> h >> v; if (!vh[h] && !vv[v]) { vh[h] = vv[v] = true; cout << i << ' '; } } }
14.904762
32
0.456869
sqc1999-oi
1a8b5129949c5c0ff7268512f53daab7dcbdecd0
433
cpp
C++
binary_search.cpp
ankitelectronicsenemy/CppCodes
e2f274330c12e59a6c401c162e8d899690db0e14
[ "Apache-2.0" ]
null
null
null
binary_search.cpp
ankitelectronicsenemy/CppCodes
e2f274330c12e59a6c401c162e8d899690db0e14
[ "Apache-2.0" ]
null
null
null
binary_search.cpp
ankitelectronicsenemy/CppCodes
e2f274330c12e59a6c401c162e8d899690db0e14
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; int binary_search(int arr[],int n,int key) { int s=0; int e=n-1; while(s<=e) { int mid=(s+e)/2; if(arr[mid]==key) { return mid; } if(arr[mid]>key) { e=mid-1; } else if(arr[mid]<key) { s=mid+1; } else return -1 ; } return -1; } int main() { int n; cin>>n; int arr[n]; for(int i=0;i<n;i++) { cin>>arr[i]; } int key; cin>>key; cout<< binary_search(arr,n,key); }
8.836735
42
0.556582
ankitelectronicsenemy
1a8c74b4b5e597e0cc6288bffb2bbdcec3b8371b
2,585
cpp
C++
VC2010Samples/ATL/Advanced/mfcatl/objone.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2010Samples/ATL/Advanced/mfcatl/objone.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2010Samples/ATL/Advanced/mfcatl/objone.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
// ObjOne.cpp : implementation file // // This is a part of the Active Template Library. // Copyright (c) Microsoft Corporation. All rights reserved. // // This source code is only intended as a supplement to the // Active Template Library Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Active Template Library product. #include "premfcat.h" #include "MfcAtl.h" #include "ObjOne.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CObjectOne IMPLEMENT_DYNCREATE(CObjectOne, CCmdTarget) CObjectOne::CObjectOne() { EnableAutomation(); // To keep the application running as long as an OLE automation // object is active, the constructor calls AfxOleLockApp. AfxOleLockApp(); } CObjectOne::~CObjectOne() { // To terminate the application when all objects created with // with OLE automation, the destructor calls AfxOleUnlockApp. AfxOleUnlockApp(); } void CObjectOne::OnFinalRelease() { // When the last reference for an automation object is released // OnFinalRelease is called. The base class will automatically // deletes the object. Add additional cleanup required for your // object before calling the base class. CCmdTarget::OnFinalRelease(); } BEGIN_MESSAGE_MAP(CObjectOne, CCmdTarget) //{{AFX_MSG_MAP(CObjectOne) // NOTE - the ClassWizard will add and remove mapping macros here. //}}AFX_MSG_MAP END_MESSAGE_MAP() BEGIN_DISPATCH_MAP(CObjectOne, CCmdTarget) //{{AFX_DISPATCH_MAP(CObjectOne) DISP_FUNCTION(CObjectOne, "SayHello", SayHello, VT_BSTR, VTS_NONE) //}}AFX_DISPATCH_MAP END_DISPATCH_MAP() // Note: we add support for IID_IObjectOne to support typesafe binding // from VBA. This IID must match the GUID that is attached to the // dispinterface in the .ODL file. // {5D0CE84F-D909-11CF-91FC-00A0C903976F} static const IID IID_IObjectOne = { 0x5d0ce84f, 0xd909, 0x11cf, { 0x91, 0xfc, 0x0, 0xa0, 0xc9, 0x3, 0x97, 0x6f } }; BEGIN_INTERFACE_MAP(CObjectOne, CCmdTarget) INTERFACE_PART(CObjectOne, IID_IObjectOne, Dispatch) END_INTERFACE_MAP() // {5D0CE850-D909-11CF-91FC-00A0C903976F} IMPLEMENT_OLECREATE(CObjectOne, "MfcAtl.ObjectOne", 0x5d0ce850, 0xd909, 0x11cf, 0x91, 0xfc, 0x0, 0xa0, 0xc9, 0x3, 0x97, 0x6f) ///////////////////////////////////////////////////////////////////////////// // CObjectOne message handlers BSTR CObjectOne::SayHello() { return SysAllocString(OLESTR("Hello from Object One!")); }
28.406593
125
0.716441
alonmm
1a8e101fc9fd68633703ee9420f4a7abe1788773
954
cpp
C++
src/Gui/ExportToDotDialog.cpp
loganek/gstcreator
619f1a6f1ee39c7c5b883c0a676cd490f59ac81b
[ "BSD-3-Clause" ]
1
2015-10-10T23:21:00.000Z
2015-10-10T23:21:00.000Z
src/Gui/ExportToDotDialog.cpp
loganek/gstcreator
619f1a6f1ee39c7c5b883c0a676cd490f59ac81b
[ "BSD-3-Clause" ]
null
null
null
src/Gui/ExportToDotDialog.cpp
loganek/gstcreator
619f1a6f1ee39c7c5b883c0a676cd490f59ac81b
[ "BSD-3-Clause" ]
null
null
null
/* * gstcreator * ExportToDotDialog.cpp * * Created on: 24 sty 2014 * Author: Marcin Kolny <marcin.kolny@gmail.com> */ #include "ExportToDotDialog.h" #include "ui_ExportToDotDialog.h" #include <QCheckBox> #include <QFileDialog> #include <cstdlib> ExportToDotDialog::ExportToDotDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ExportToDotDialog) { ui->setupUi(this); ui->pathLineEdit->setText(getenv("GST_DEBUG_DUMP_DOT_DIR")); } ExportToDotDialog::~ExportToDotDialog() { delete ui; } int ExportToDotDialog::get_graph_details() const { return (ui->statesCheckBox->isChecked() << 0) | (ui->statesCheckBox->isChecked() << 1) | (ui->statesCheckBox->isChecked() << 2) | (ui->statesCheckBox->isChecked() << 3); } std::string ExportToDotDialog::get_filename() const { return ui->filenameLineEdit->text().toStdString(); } bool ExportToDotDialog::is_master_model() const { return ui->mainBinRadioButton->isChecked(); }
20.73913
61
0.715933
loganek
1a8e647f78fe3b7f6ef04a0cdfd2407338557fae
1,191
cpp
C++
components/system/sources/platform/android/android_crash_processor.cpp
untgames/funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
7
2016-03-30T17:00:39.000Z
2017-03-27T16:04:04.000Z
components/system/sources/platform/android/android_crash_processor.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2017-11-21T11:25:49.000Z
2018-09-20T17:59:27.000Z
components/system/sources/platform/android/android_crash_processor.cpp
untgames/Funner
c91614cda55fd00f5631d2bd11c4ab91f53573a3
[ "MIT" ]
4
2016-11-29T15:18:40.000Z
2017-03-27T16:04:08.000Z
#include "shared.h" using namespace syslib; using namespace syslib::android; namespace { typedef void (*sighandler_t)(int); sighandler_t prev_segv_handler = 0; //предыдущий обработчик сигнала SEGV // дамп карты памяти void dump_maps () { static char line [256]; FILE *fp = fopen ("/proc/self/maps", "r"); if (!fp) return; while (fgets (line, sizeof (line), fp)) { size_t len = strlen (line); len--; line [len] = 0; if (!strstr (line, "/system/") && !strstr (line, "/dev/") && !strstr (line, "[stack]") && line [len-1] != ' ') printf ("segment %s\n", line); } fclose (fp); fflush (stdout); Application::Sleep (1000); } // обработчик сигналогв void sighandler (int signum) { switch (signum) { case SIGSEGV: printf ("Crash detected\n"); dump_maps (); prev_segv_handler (signum); break; default: break; } } } namespace syslib { namespace android { /// регистрация обратчиков аварийного завершения void register_crash_handlers () { prev_segv_handler = signal(SIGSEGV, sighandler); } } }
16.315068
115
0.56927
untgames
1a8f43595b382c481b51b8c6c60c53c69bd2f49c
1,532
cpp
C++
blades/xbmc/xbmc/filesystem/SFTPDirectory.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
4
2016-04-26T03:43:54.000Z
2016-11-17T08:09:04.000Z
blades/xbmc/xbmc/filesystem/SFTPDirectory.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
17
2015-01-05T21:06:22.000Z
2015-12-07T20:45:44.000Z
blades/xbmc/xbmc/filesystem/SFTPDirectory.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
3
2016-04-26T03:43:55.000Z
2020-11-06T11:02:08.000Z
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "SFTPDirectory.h" #ifdef HAS_FILESYSTEM_SFTP #include "SFTPFile.h" #include "utils/log.h" #include "URL.h" using namespace XFILE; CSFTPDirectory::CSFTPDirectory(void) { } CSFTPDirectory::~CSFTPDirectory(void) { } bool CSFTPDirectory::GetDirectory(const CURL& url, CFileItemList &items) { CSFTPSessionPtr session = CSFTPSessionManager::CreateSession(url); return session->GetDirectory(url.GetWithoutFilename().c_str(), url.GetFileName().c_str(), items); } bool CSFTPDirectory::Exists(const CURL& url) { CSFTPSessionPtr session = CSFTPSessionManager::CreateSession(url); if (session) return session->DirectoryExists(url.GetFileName().c_str()); else { CLog::Log(LOGERROR, "SFTPDirectory: Failed to create session to check exists"); return false; } } #endif
27.854545
99
0.727807
krattai
1a94bd2c1627daf0ff179c9c0c565a1262e87623
1,528
cpp
C++
winml/lib/Api.Image/DisjointBufferHelpers.cpp
dennyac/onnxruntime
d5175795d2b7f2db18b0390f394a49238f814668
[ "MIT" ]
18
2020-05-19T12:48:07.000Z
2021-04-28T06:41:57.000Z
winml/lib/Api.Image/DisjointBufferHelpers.cpp
dennyac/onnxruntime
d5175795d2b7f2db18b0390f394a49238f814668
[ "MIT" ]
61
2021-05-31T05:15:41.000Z
2022-03-29T22:34:33.000Z
winml/lib/Api.Image/DisjointBufferHelpers.cpp
dennyac/onnxruntime
d5175795d2b7f2db18b0390f394a49238f814668
[ "MIT" ]
9
2021-05-14T20:17:26.000Z
2022-03-20T11:44:29.000Z
#include "pch.h" #include "inc/DisjointBufferHelpers.h" namespace _winml { static void LoadOrStoreDisjointBuffers( bool should_load_buffer, size_t num_buffers, std::function<gsl::span<byte>(size_t)> get_buffer, gsl::span<byte>& buffer_span) { auto size_in_bytes = buffer_span.size_bytes(); auto buffer = buffer_span.data(); size_t offset_in_bytes = 0; for (size_t i = 0; i < num_buffers && size_in_bytes > offset_in_bytes; i++) { auto span = get_buffer(i); auto current_size_in_bytes = span.size_bytes(); auto current_buffer = span.data(); if (size_in_bytes - offset_in_bytes < current_size_in_bytes) { current_size_in_bytes = size_in_bytes - offset_in_bytes; } auto offset_buffer = buffer + offset_in_bytes; if (should_load_buffer) { memcpy(offset_buffer, current_buffer, current_size_in_bytes); } else { memcpy(current_buffer, offset_buffer, current_size_in_bytes); } offset_in_bytes += current_size_in_bytes; } } void LoadSpanFromDisjointBuffers( size_t num_buffers, std::function<gsl::span<byte>(size_t)> get_buffer, gsl::span<byte>& buffer_span) { LoadOrStoreDisjointBuffers(true /*load into the span*/, num_buffers, get_buffer, buffer_span); } void StoreSpanIntoDisjointBuffers( size_t num_buffers, std::function<gsl::span<byte>(size_t)> get_buffer, gsl::span<byte>& buffer_span) { LoadOrStoreDisjointBuffers(false /*store into buffers*/, num_buffers, get_buffer, buffer_span); } } // namespace _winml
31.183673
97
0.725131
dennyac
1a98d628ebe2402e2871ca4d09c060ce8f3c353c
726
cpp
C++
homomorphic_evaluation/src/main.cpp
dklee0501/PLDI_20_242_artifact_publication
f2b73df9165c76e8b521d8ebd639d68321e3862b
[ "MIT" ]
1
2022-02-14T02:37:58.000Z
2022-02-14T02:37:58.000Z
homomorphic_evaluation/src/main.cpp
dklee0501/Lobster
f2b73df9165c76e8b521d8ebd639d68321e3862b
[ "MIT" ]
null
null
null
homomorphic_evaluation/src/main.cpp
dklee0501/Lobster
f2b73df9165c76e8b521d8ebd639d68321e3862b
[ "MIT" ]
null
null
null
#include "FHE.h" #include <timing.h> #include <EncryptedArray.h> #include <NTL/lzz_pXFactoring.h> #include <vector> #include <cassert> #include <cstdio> #include <iostream> #include <string> #include <string.h> #include <fstream> #include <vector> #include "NTL/ZZ_p.h" #include <NTL/ZZ_pX.h> #include <NTL/vec_ZZ_p.h> #include <assert.h> #include <stdlib.h> int main(int argc, const char *argv[]) { long m=0, p=127, r=1; // Native plaintext space // Computations will be 'modulo p' long L; // Levels long c=2; // Columns in key switching matrix long w=64; // Hamming weight of secret key long d=1; long security; long s; long bnd; ZZX G; return 0; }
20.742857
58
0.633609
dklee0501
1aa048d51d3dc8d3221ace15e82671a0cb56b13d
984
cpp
C++
Online Judges/HackerEarth/Grid.cpp
NelsonGomesNeto/ProgramC
e743b1b869f58f7f3022d18bac00c5e0b078562e
[ "MIT" ]
3
2018-12-18T13:39:42.000Z
2021-06-23T18:05:18.000Z
Online Judges/HackerEarth/Grid.cpp
NelsonGomesNeto/ProgramC
e743b1b869f58f7f3022d18bac00c5e0b078562e
[ "MIT" ]
1
2018-11-02T21:32:40.000Z
2018-11-02T22:47:12.000Z
Online Judges/HackerEarth/Grid.cpp
NelsonGomesNeto/ProgramC
e743b1b869f58f7f3022d18bac00c5e0b078562e
[ "MIT" ]
6
2018-10-27T14:07:52.000Z
2019-11-14T13:49:29.000Z
#include <bits/stdc++.h> using namespace std; const int maxN = 1e3; int n, m, q, si = 0, sj = 0; char grid[maxN][maxN + 1]; int dist[maxN][maxN], dy[4] = {0, 0, 1, -1}, dx[4] = {1, -1, 0, 0}; int valid(int i, int j) { return(!(i < 0 || i >= n || j < 0 || j >= m)); } void bfs() { memset(dist, -1, sizeof(dist)); queue<pair<int, int>> q; q.push({si, sj}); dist[si][sj] = 0; while (!q.empty()) { int i = q.front().first, j = q.front().second; q.pop(); for (int k = 0; k < 4; k ++) if (valid(i + dy[k], j + dx[k]) && dist[i + dy[k]][j + dx[k]] == -1 && grid[i + dy[k]][j + dx[k]] == 'O') q.push({i + dy[k], j + dx[k]}), dist[i + dy[k]][j + dx[k]] = dist[i][j] + 1; } } int main() { scanf("%d %d %d", &n, &m, &q); for (int i = 0; i < n; i ++) scanf("\n%s", grid[i]); scanf("%d %d", &si, &sj); si --, sj --; bfs(); while (q --) { int di, dj; scanf("%d %d", &di, &dj); di --, dj --; printf("%d\n", dist[di][dj]); } return(0); }
24.6
111
0.442073
NelsonGomesNeto