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 109 | 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 48.5k ⌀ | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6df79c99a5a5b748cfee99a1a127d7dc24fbd7e7 | 886 | cpp | C++ | src/remove-duplicates-from-sorted-list.cpp | Liuchang0812/leetcode | d71f87b0035e661d0009f4382b39c4787c355f89 | [
"MIT"
] | 9 | 2015-09-09T20:28:31.000Z | 2019-05-15T09:13:07.000Z | src/remove-duplicates-from-sorted-list.cpp | liuchang0812/leetcode | d71f87b0035e661d0009f4382b39c4787c355f89 | [
"MIT"
] | 1 | 2015-02-25T13:10:09.000Z | 2015-02-25T13:10:09.000Z | src/remove-duplicates-from-sorted-list.cpp | liuchang0812/leetcode | d71f87b0035e661d0009f4382b39c4787c355f89 | [
"MIT"
] | 1 | 2016-08-31T19:14:52.000Z | 2016-08-31T19:14:52.000Z | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* &front, ListNode* &rear) {
if (front && rear)
{
front->next = rear->next;
rear = front->next;
}
}
ListNode *deleteDuplicates(ListNode *head) {
ListNode *fnt, *rear;
if (head == NULL) return head;
if (head->next == NULL) return head;
fnt = head;
rear = head->next;
do
{
if (fnt->val == rear->val)
{
deleteNode(fnt, rear);
}
else
{
fnt = rear;
if(rear)
rear = rear->next;
else
rear = NULL;
}
}while(fnt != NULL && rear != NULL);
return head;
}
};
| 21.095238 | 56 | 0.454853 | Liuchang0812 |
6df9fc911a91003d2720ec935028cb47bc9fba9e | 473 | cpp | C++ | problem_solving/CodeForces/274A/18761704_AC_124ms_3968kB.cpp | cosmicray001/academic | 6aa142baeba4bb1ad73b8669e37305ca0b5102a7 | [
"MIT"
] | 2 | 2020-09-02T12:07:47.000Z | 2020-11-17T11:17:16.000Z | problem_solving/CodeForces/274A/18761704_AC_124ms_3968kB.cpp | cosmicray001/academic | 6aa142baeba4bb1ad73b8669e37305ca0b5102a7 | [
"MIT"
] | null | null | null | problem_solving/CodeForces/274A/18761704_AC_124ms_3968kB.cpp | cosmicray001/academic | 6aa142baeba4bb1ad73b8669e37305ca0b5102a7 | [
"MIT"
] | 4 | 2020-08-11T14:23:34.000Z | 2020-11-17T10:52:31.000Z | #include <bits/stdc++.h>
#define le 100005
#define ll long long int
using namespace std;
set<ll> st;
ll n[le];
int main(){
//freopen("input.txt", "r", stdin);
int len, a, b;
ll m;
scanf("%lld %lld", &len, &m);
for(int i = 0; i < len; scanf("%lld", &n[i]), i++);
sort(n, n + len);
for(int i = 0; i < len; i++){
if(n[i] % m != 0) st.insert(n[i]);
else{
if(!st.count(n[i] / m)) st.insert(n[i]);
}
}
printf("%d\n", st.size());
return 0;
}
| 20.565217 | 53 | 0.5074 | cosmicray001 |
a302f908ae638211ad933252152e4ecc29f1316b | 15,085 | hpp | C++ | System.Core/include/Switch/System/Threading/ThreadPool.hpp | kkptm/CppLikeCSharp | b2d8d9da9973c733205aa945c9ba734de0c734bc | [
"MIT"
] | 4 | 2021-10-14T01:43:00.000Z | 2022-03-13T02:16:08.000Z | System.Core/include/Switch/System/Threading/ThreadPool.hpp | kkptm/CppLikeCSharp | b2d8d9da9973c733205aa945c9ba734de0c734bc | [
"MIT"
] | null | null | null | System.Core/include/Switch/System/Threading/ThreadPool.hpp | kkptm/CppLikeCSharp | b2d8d9da9973c733205aa945c9ba734de0c734bc | [
"MIT"
] | 2 | 2022-03-13T02:16:06.000Z | 2022-03-14T14:32:57.000Z | /// @file
/// @brief Contains Switch::System::Threading::ThreadPool class.
#pragma once
#include "../../Types.hpp"
#include "../../RefPtr.hpp"
#include "../../Static.hpp"
#include "../TimeSpan.hpp"
#include "../Collections/Generic/List.hpp"
#include "Thread.hpp"
#include "RegisteredWaitHandle.hpp"
#include "WaitCallback.hpp"
#include "WaitHandle.hpp"
#include "WaitOrTimerCallback.hpp"
/// @brief The Switch namespace contains all fundamental classes to access Hardware, Os, System, and more.
namespace Switch {
/// @brief The System namespace contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions.
namespace System {
/// @brief The System::Threading namespace provides classes and interfaces that enable multithreaded programming.
/// In addition to classes for synchronizing thread activities and access to data ( Mutex, Monitor, Interlocked, AutoResetEvent, and so on), this namespace includes a ThreadPool class that allows you to use a pool of system-supplied threads, and a Timer class that executes callback methods on thread pool threads.
namespace Threading {
/// @brief Provides a pool of threads that can be used to post work items, process asynchronous I/O, wait on behalf of other threads, and process timers.
class core_export_ ThreadPool static_ {
public:
/// @brief Retrieves the difference between the maximum number of thread pool threads returned by the GetMaxThreads method, and the number currently active.
/// @param workerThreads The number of available worker threads
/// @param completionPortThreads The number of available asynchronous I/O threads.
/// @exception ArgumentNullException The workerThreads or completionPortThreads param is null.
/// @remarks When GetAvailableThreads returns, the variable specified by workerThreads contains the number of additional worker threads that can be started, and the variable specified by completionPortThreads contains the number of additional asynchronous I/O threads that can be started.
static void GetAvailableThreads(int32& workerThreads, int32& completionPortThreads);
/// @brief Retrieves the number of requests to the thread pool that can be active concurrently. All requests above that number remain queued until thread pool threads become available.
/// @param workerThreads The maximum number of worker threads in the thread pool.
/// @param completionPortThreads The maximum number of asynchronous I/O threads in the thread pool.
/// @exception ArgumentNullException The workerThreads or completionPortThreads param is null.
/// @remarks When GetMaxThreads returns, the variable specified by workerThreads contains the maximum number of worker threads allowed in the thread pool, and the variable specified by completionPortThreads contains the maximum number of asynchronous I/O threads allowed in the thread pool.
/// @remarks You can use the GetAvailableThreads method to determine the actual number of threads in the thread pool at any given time.
/// @remarks You can use the SetMaxThreads to set the maximum number of worker threads and asynchronous I/O threads in the thread pool.
static void GetMaxThreads(int32& workerThreads, int32& completionPortThreads);
/// @brief Retrieves the number of idle threads the thread pool maintains in anticipation of new requests. Always 0 for both.
/// @param workerThreads The maximum number of worker threads in the thread pool.
/// @param completionPortThreads The maximum number of asynchronous I/O threads in the thread pool.
/// @exception ArgumentNullException The workerThreads or completionPortThreads param is null.
/// @remarks To develop in the future for optimization.
static void GetMinThreads(int32& workerThreads, int32& completionPortThreads);
/// @brief Queues a method for execution. The method executes when a thread pool thread becomes available.
/// @param callBack A pointer function that represents the method to be executed.
/// @return Boolean true if the method is successfully queued; NotSupportException is thrown if the work item could not be queued
/// @exception ArgumentNullException The callBack param is null.
static bool QueueUserWorkItem(const WaitCallback& callBack);
/// @brief Queues a method for execution. The method executes when a thread pool thread becomes available.
/// @param callBack A pointer function that represents the method to be executed.
/// @param state An object containing data to be used by the method.
/// @return Boolean true if the method is successfully queued; NotSupportedException is thrown if the work item could not be queued
/// @exception ArgumentNullException The callBack param is null.
static bool QueueUserWorkItem(const WaitCallback& callBack, object& state);
/// @brief Registers a delegate to wait for a WaitHandle, specifying a 32-bit signed integer for the time-out in milliseconds.
/// @param waitObject The WaitHandle to register. Use a WaitHandle other than Mutex
/// @param callBack A pointer function to call when the waitObject parameter is signaled.
/// @param state The object that is passed to the callBack.
/// @param millisecondsTimeoutInterval The time-out in milliseconds. If the millisecondsTimeoutInterval parameter is 0 (zero), the function tests the object's state and returns immediately. If millisecondsTimeoutInterval is -1, the function's time-out interval never elapses.
/// @param executeOnlyOnce true to indicate that the thread will no longer wait on the waitObject parameter after the callBack has been called; false to indicate that the timer is reset every time the wait operation completes until the wait is unregistered.
/// @return RegisteredWaitHandle The RegisteredWaitHandle that encapsulates the native handle.
/// @exception ArgumentNullException The callBack param is null.
/// @exception ArgumentOutOfRangeException The millisecondsTimeoutInterval parameter is less than -1.
static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle& waitObject, const WaitOrTimerCallback& callBack, Object& state, int32 millisecondsTimeoutInterval, bool executeOnlyOnce);
/// @brief Registers a delegate to wait for a WaitHandle, specifying a 32-bit signed integer for the time-out in milliseconds.
/// @param waitObject The WaitHandle to register. Use a WaitHandle other than Mutex
/// @param callBack A pointer function to call when the waitObject parameter is signaled.
/// @param state The object that is passed to the callBack.
/// @param millisecondsTimeoutInterval The time-out in milliseconds. If the millisecondsTimeoutInterval parameter is 0 (zero), the function tests the object's state and returns immediately. If millisecondsTimeoutInterval is -1, the function's time-out interval never elapses.
/// @param executeOnlyOnce true to indicate that the thread will no longer wait on the waitObject parameter after the callBack has been called; false to indicate that the timer is reset every time the wait operation completes until the wait is unregistered.
/// @return RegisteredWaitHandle The RegisteredWaitHandle that encapsulates the native handle.
/// @exception ArgumentNullException The callBack param is null.
/// @exception ArgumentOutOfRangeException The millisecondsTimeoutInterval parameter is less than -1.
static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle& waitObject, const WaitOrTimerCallback& callBack, Object& state, int64 millisecondsTimeoutInterval, bool executeOnlyOnce) {return RegisterWaitForSingleObject(waitObject, callBack, state, TimeSpan::FromMilliseconds(as<int32>(millisecondsTimeoutInterval)), executeOnlyOnce);}
/// @brief Registers a delegate to wait for a WaitHandle, specifying a 32-bit signed integer for the time-out in milliseconds.
/// @param waitObject The WaitHandle to register. Use a WaitHandle other than Mutex
/// @param callBack A pointer function to call when the waitObject parameter is signaled.
/// @param state The object that is passed to the callBack.
/// @param timeout The time-out represented by a TimeSpan.If timeout is 0 (zero), the function tests the object's state and returns immediately.If timeout is -1, the function's time-out interval never elapses.
/// @param executeOnlyOnce true to indicate that the thread will no longer wait on the waitObject parameter after the callBack has been called; false to indicate that the timer is reset every time the wait operation completes until the wait is unregistered.
/// @return RegisteredWaitHandle The RegisteredWaitHandle that encapsulates the native handle.
/// @exception ArgumentNullException The callBack param is null.
/// @exception ArgumentOutOfRangeException The millisecondsTimeoutInterval parameter is less than -1.
static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle& waitObject, const WaitOrTimerCallback& callBack, Object& state, const TimeSpan& timeout, bool executeOnlyOnce) {return RegisterWaitForSingleObject(waitObject, callBack, state, as<int32>(timeout.TotalMilliseconds()), executeOnlyOnce);}
/// @brief Registers a delegate to wait for a WaitHandle, specifying a 32-bit signed integer for the time-out in milliseconds.
/// @param waitObject The WaitHandle to register. Use a WaitHandle other than Mutex
/// @param callBack A pointer function to call when the waitObject parameter is signaled.
/// @param state The object that is passed to the callBack.
/// @param millisecondsTimeoutInterval The time-out in milliseconds. If the millisecondsTimeoutInterval parameter is 0 (zero), the function tests the object's state and returns immediately. If millisecondsTimeoutInterval is -1, the function's time-out interval never elapses.
/// @param executeOnlyOnce true to indicate that the thread will no longer wait on the waitObject parameter after the callBack has been called; false to indicate that the timer is reset every time the wait operation completes until the wait is unregistered.
/// @return RegisteredWaitHandle The RegisteredWaitHandle that encapsulates the native handle.
/// @exception ArgumentNullException The callBack param is null.
static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle& waitObject, const WaitOrTimerCallback& callBack, object& state, uint32 millisecondsTimeoutInterval, bool executeOnlyOnce) {return RegisterWaitForSingleObject(waitObject, callBack, state, TimeSpan::FromMilliseconds(as<int32>(millisecondsTimeoutInterval)), executeOnlyOnce);}
/// @brief Sets the number of requests to the thread pool that can be active concurrently. All requests above that number remain queued until thread pool threads become available.
/// @param workerThreads The maximum number of worker threads in the thread pool.
/// @param completionPortThreads The maximum number of asynchronous I/O threads in the thread pool.
/// @return Boolean true if the change is successful; otherwise, false.
/// @exception ArgumentOutOfRangeException if the workerThreads is < 0 or > MaxThreads - or - if the completionPortThreads is < 0 or > MaxAsynchronousIoThreads.
/// @remarks The maximum value that can be set is 256.
/// @see MaxThreads
/// @see MaxAsynchronousIoThreads
static bool SetMaxThreads(int32 workerThreads, int32 completionPortThreads);
/// @brief Sets the number of idle threads the thread pool maintains in anticipation of new requests.
/// @param workerThreads The new minimum number of idle worker threads to be maintained by the thread pool.
/// @param completionPortThreads The new minimum number of idle asynchronous I/O threads to be maintained by the thread pool.
/// @return Boolean true if the change is successful; otherwise, false.
/// @exception ArgumentOutOfRangeException if the workerThreads is different of 0 - or - if the completionPortThreads is different of 0.
/// @remarks The only value that can be set is 0.
/// @remarks To develop in the future for optimization.
static bool SetMinThreads(int32 workerThreads, int32 completionPortThreads);
private:
static int32 maxThreads;
static int32 maxAsynchronousIOThreads;
static int32 minThreads;
static int32 minAsynchronousIOThreads;
static bool closed;
template<typename T>
struct ThreadItem : public Object {
ThreadItem() {}
ThreadItem(const T& callback) : callback(callback) {}
ThreadItem(const T& callback, object& state) : callback(callback), state(&state) {}
ThreadItem(const T& callback, object& state, WaitHandle& waitObject, int32 millisecondsTimeoutInterval, bool executeOnlyOnce) : callback(callback), state(&state), waitObject(&waitObject), millisecondsTimeoutInterval(millisecondsTimeoutInterval), executeOnlyOnce(executeOnlyOnce) {}
T callback;
Object* state = null;
WaitHandle* waitObject = null;
int32 millisecondsTimeoutInterval;
bool executeOnlyOnce = true;
bool unregistered = false;
void Run() {
do {
this->callback(*state);
} while (!executeOnlyOnce);
}
};
using ThreadPoolItem = ThreadItem<WaitCallback>;
using ThreadPoolAsynchronousIOItem = ThreadItem<WaitOrTimerCallback>;
using ThreadPoolItemCollection = System::Collections::Generic::List<refptr<ThreadPoolItem>>;
using ThreadPoolAsynchronousIOItemCollection = System::Collections::Generic::List<refptr<ThreadPoolAsynchronousIOItem>>;
static ThreadPoolItemCollection threadPoolItems;
static ThreadPoolAsynchronousIOItemCollection threadPoolAsynchronousIOItems;
static void Run();
static void AsynchronousIORun();
static void CreateThreads();
static void CreateAsynchronousIOThreads();
friend class RegisteredWaitHandle;
class ThreadArray : public Array<Thread> {
public:
ThreadArray() {}
ThreadArray(int32 count) : Array<Thread>(count) {}
~ThreadArray();
};
class AsynchronousThreadArray : public Array<Thread> {
public:
AsynchronousThreadArray() {}
AsynchronousThreadArray(int32 count) : Array<Thread>(count) {}
~AsynchronousThreadArray();
};
static ThreadArray threads;
static AsynchronousThreadArray asynchronousIOThreads;
};
}
}
}
using namespace Switch;
| 80.239362 | 349 | 0.742459 | kkptm |
a305a169228eceeac7bc4f8c8c6835624d5246d8 | 717 | cpp | C++ | Library/Private/Pegasus/Public/Pegasus/IndexBase.cpp | KonstantinTomashevich/Emergence | 83b1d52bb62bf619f9402e3081dd9de6b0cb232c | [
"Apache-2.0"
] | 3 | 2021-06-02T05:06:48.000Z | 2022-01-26T09:39:44.000Z | Library/Private/Pegasus/Public/Pegasus/IndexBase.cpp | KonstantinTomashevich/Emergence | 83b1d52bb62bf619f9402e3081dd9de6b0cb232c | [
"Apache-2.0"
] | null | null | null | Library/Private/Pegasus/Public/Pegasus/IndexBase.cpp | KonstantinTomashevich/Emergence | 83b1d52bb62bf619f9402e3081dd9de6b0cb232c | [
"Apache-2.0"
] | null | null | null | #include <Pegasus/IndexBase.hpp>
#include <Pegasus/Storage.hpp>
namespace Emergence::Pegasus
{
bool IndexBase::CanBeDropped () const noexcept
{
// Self reference is always here.
return GetReferenceCount () <= 1u && activeCursors == 0u;
}
const StandardLayout::Mapping &IndexBase::GetRecordMapping () const noexcept
{
return storage->GetRecordMapping ();
}
IndexBase::IndexBase (class Storage *_storage) noexcept : storage (_storage), activeCursors (0u)
{
assert (storage);
// Add self reference to prevent Handling from deleting this object.
// Storage owns indices and Handling is used only to check if dropping index is safe.
RegisterReference ();
}
} // namespace Emergence::Pegasus
| 28.68 | 96 | 0.730823 | KonstantinTomashevich |
a309a6f52f6e4d572f21ef3410ba2f33ac1c40b5 | 7,620 | cpp | C++ | src/widgets/numformatter.cpp | Evropa1/audacity | 3be57fce49d293bd64cb0904b3883c885503ab2e | [
"CC-BY-3.0"
] | 21 | 2015-08-02T20:43:37.000Z | 2022-02-06T04:19:16.000Z | src/widgets/numformatter.cpp | Evropa1/audacity | 3be57fce49d293bd64cb0904b3883c885503ab2e | [
"CC-BY-3.0"
] | null | null | null | src/widgets/numformatter.cpp | Evropa1/audacity | 3be57fce49d293bd64cb0904b3883c885503ab2e | [
"CC-BY-3.0"
] | 3 | 2016-05-15T05:35:57.000Z | 2018-09-21T20:50:11.000Z | /////////////////////////////////////////////////////////////////////////////
//
// Backport from wxWidgets-3.0-rc1
//
/////////////////////////////////////////////////////////////////////////////
// Name: src/common/numformatter.cpp
// Purpose: NumberFormatter
// Author: Fulvio Senore, Vadim Zeitlin
// Created: 2010-11-06
// Copyright: (c) 2010 wxWidgets team
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include <wx/wxprec.h>
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifdef __WIN32__
#include <wx/msw/private.h>
#endif
#include "../Audacity.h"
#include "numformatter.h"
#include "../Internat.h"
#include <wx/intl.h>
#include <locale.h> // for setlocale and LC_ALL
#include <cmath>
#include <limits>
#include <wx/log.h>
// ----------------------------------------------------------------------------
// local helpers
// ----------------------------------------------------------------------------
// ============================================================================
// NumberFormatter implementation
// ============================================================================
// ----------------------------------------------------------------------------
// Locale information accessors
// ----------------------------------------------------------------------------
wxChar NumberFormatter::GetDecimalSeparator()
{
#if wxUSE_INTL
struct lconv *info = localeconv();
wxString s = info ? wxString::FromUTF8(info->decimal_point) : wxT(".");
if (s.empty())
{
// We really must have something for decimal separator, so fall
// back to the C locale default.
s = wxT(".");
}
return s[0];
#else // !wxUSE_INTL
return wxT('.');
#endif // wxUSE_INTL/!wxUSE_INTL
}
bool NumberFormatter::GetThousandsSeparatorIfUsed(wxChar *sep)
{
#if wxUSE_INTL
struct lconv *info = localeconv();
wxString s = info ? wxString::FromUTF8(info->thousands_sep) : wxT("");
if (s.IsEmpty())
{
return false;
}
*sep = s[0];
return true;
#else // !wxUSE_INTL
wxUnusedVar(sep);
return false;
#endif // wxUSE_INTL/!wxUSE_INTL
}
// ----------------------------------------------------------------------------
// Conversion to string and helpers
// ----------------------------------------------------------------------------
wxString NumberFormatter::PostProcessIntString(const wxString &sArg, int style)
{
wxString s(sArg);
if ( style & Style_WithThousandsSep )
AddThousandsSeparators(s);
wxASSERT_MSG( !(style & Style_NoTrailingZeroes),
wxT("Style_NoTrailingZeroes can't be used with integer values") );
wxASSERT_MSG( !(style & Style_OneTrailingZero),
wxT("Style_OneTrailingZero can't be used with integer values") );
wxASSERT_MSG( !(style & Style_TwoTrailingZeroes),
wxT("Style_TwoTrailingZeroes can't be used with integer values") );
wxASSERT_MSG( !(style & Style_ThreeTrailingZeroes),
wxT("Style_ThreeTrailingZeroes can't be used with integer values") );
return s;
}
wxString NumberFormatter::ToString(long val, int style)
{
return PostProcessIntString(wxString::Format(wxT("%ld"), val), style);
}
#ifdef HAS_LONG_LONG_T_DIFFERENT_FROM_LONG
wxString NumberFormatter::ToString(wxLongLong_t val, int style)
{
return PostProcessIntString(wxString::Format("%" wxLongLongFmtSpec "d", val),
style);
}
#endif // HAS_LONG_LONG_T_DIFFERENT_FROM_LONG
wxString NumberFormatter::ToString(double val, int precision, int style)
{
wxString format;
if ( precision == -1 )
{
format = wxT("%g");
}
else // Use fixed precision.
{
format.Printf(wxT("%%.%df"), precision);
}
if (std::isnan(val))
{
return _("NaN");
}
if (std::isinf(val))
{
if (val == std::numeric_limits<double>::infinity())
{
return _("Infinity");
}
else
{
return _("-Infinity");
}
}
wxString s = wxString::Format(format, val);
if ( style & Style_WithThousandsSep )
AddThousandsSeparators(s);
if ( precision != -1 )
{
if ( style & Style_NoTrailingZeroes )
RemoveTrailingZeroes(s, 0);
if ( style & Style_OneTrailingZero )
RemoveTrailingZeroes(s, 1);
if ( style & Style_TwoTrailingZeroes )
RemoveTrailingZeroes(s, 2);
if ( style & Style_ThreeTrailingZeroes )
RemoveTrailingZeroes(s, 3);
}
return s;
}
void NumberFormatter::AddThousandsSeparators(wxString& s)
{
wxChar thousandsSep;
if ( !GetThousandsSeparatorIfUsed(&thousandsSep) )
return;
size_t pos = s.find(GetDecimalSeparator());
if ( pos == wxString::npos )
{
// Start grouping at the end of an integer number.
pos = s.length();
}
// End grouping at the beginning of the digits -- there could be at a sign
// before their start.
const size_t start = s.find_first_of(wxT("0123456789"));
// We currently group digits by 3 independently of the locale. This is not
// the right thing to do and we should use lconv::grouping (under POSIX)
// and GetLocaleInfo(LOCALE_SGROUPING) (under MSW) to get information about
// the correct grouping to use. This is something that needs to be done at
// wxLocale level first and then used here in the future (TODO).
const size_t GROUP_LEN = 3;
while ( pos > start + GROUP_LEN )
{
pos -= GROUP_LEN;
s.insert(pos, thousandsSep);
}
}
void NumberFormatter::RemoveTrailingZeroes(wxString& s, size_t retain /* = 0 */)
{
const size_t posDecSep = s.find(GetDecimalSeparator());
wxCHECK_RET( posDecSep != wxString::npos,
wxString::Format(wxT("No decimal separator in \"%s\""), s) );
wxCHECK_RET( posDecSep, wxT("Can't start with decimal separator" ));
// Find the last character to keep.
size_t posLastCharacterToKeep = s.find_last_not_of(wxT("0"));
// If it's the decimal separator itself, remove it.
if ((posLastCharacterToKeep == posDecSep) && (retain == 0)) {
posLastCharacterToKeep--;
} else if ((posLastCharacterToKeep - posDecSep) < retain) {
posLastCharacterToKeep = retain + posDecSep;
}
s.erase(posLastCharacterToKeep + 1);
}
// ----------------------------------------------------------------------------
// Conversion from strings
// ----------------------------------------------------------------------------
void NumberFormatter::RemoveThousandsSeparators(wxString& s)
{
wxChar thousandsSep;
if ( !GetThousandsSeparatorIfUsed(&thousandsSep) )
return;
s.Replace(wxString(thousandsSep), wxString());
}
bool NumberFormatter::FromString(const wxString &sArg, long *val)
{
wxString s(sArg);
RemoveThousandsSeparators(s);
return s.ToLong(val);
}
#ifdef HAS_LONG_LONG_T_DIFFERENT_FROM_LONG
bool NumberFormatter::FromString(const wxString &sArg, wxLongLong_t *val)
{
wxString s(sArg);
RemoveThousandsSeparators(s);
return s.ToLongLong(val);
}
#endif // HAS_LONG_LONG_T_DIFFERENT_FROM_LONG
bool NumberFormatter::FromString(const wxString &sArg, double *val)
{
wxString s(sArg);
RemoveThousandsSeparators(s);
return s.ToDouble(val);
}
| 28.539326 | 87 | 0.55315 | Evropa1 |
a30c60ff2aeca437a3aacc432563da53b1e9924d | 520 | cpp | C++ | libs/opencl/src/opencl/memory_object/create_image_format.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/opencl/src/opencl/memory_object/create_image_format.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/opencl/src/opencl/memory_object/create_image_format.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sge/opencl/memory_object/create_image_format.hpp>
cl_image_format
sge::opencl::memory_object::create_image_format(cl_channel_order const co, cl_channel_type const ct)
{
cl_image_format result;
result.image_channel_order = co;
result.image_channel_data_type = ct;
return result;
}
| 32.5 | 100 | 0.753846 | cpreh |
a30f41fabd942b546abb29c9023c42d10fc333bb | 1,389 | cpp | C++ | uHunt series 2015/Session 1 (Warming Up - Ad Hoc Problems)/1586 - Molar mass.cpp | Sohieeb/competitive-programming | fe3fca0d4d2a242053d097c7ae71667a135cfc45 | [
"MIT"
] | 1 | 2020-01-30T20:08:24.000Z | 2020-01-30T20:08:24.000Z | uHunt series 2015/Session 1 (Warming Up - Ad Hoc Problems)/1586 - Molar mass.cpp | Sohieb/competitive-programming | fe3fca0d4d2a242053d097c7ae71667a135cfc45 | [
"MIT"
] | null | null | null | uHunt series 2015/Session 1 (Warming Up - Ad Hoc Problems)/1586 - Molar mass.cpp | Sohieb/competitive-programming | fe3fca0d4d2a242053d097c7ae71667a135cfc45 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using namespace __gnu_cxx;
typedef double db;
typedef long long ll;
typedef pair<db, db> pdd;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
typedef unsigned long long ull;
#define F first
#define S second
#define pnl printf("\n")
#define sz(x) (int)x.size()
#define sf(x) scanf("%d",&x)
#define pf(x) printf("%d\n",x)
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define rep(i, n) for(int i = 0; i < n; ++i)
const db eps = 1e-9;
const db pi = acos(-1);
const int INF = 0x3f3f3f3f;
const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1000 * 1000 * 1000 + 7;
int T;
string str;
map<char, double> w;
void init() {
w['C'] = 12.01;
w['H'] = 1.008;
w['O'] = 16.00;
w['N'] = 14.01;
w['#'] = 0;
}
int main() {
init();
scanf("%d", &T);
char c, me;
int cnt = 0;
while (T--) {
cin >> str;
double out = 0;
me = '#';
cnt = 0;
for (int i = 0; i < sz(str); ++i) {
c = str[i];
if (isdigit(c)) {
cnt = cnt * 10 + (c - '0');
} else {
out += max(cnt, 1) * w[me];
me = c;
cnt = 0;
}
}
out += max(cnt, 1) * w[me];
printf("%.3f\n", out);
}
return 0;
}
| 21.045455 | 45 | 0.465803 | Sohieeb |
a30f9a1197ed08756ef282821eb18f79c63c19d1 | 1,214 | cpp | C++ | GameEngineCore/AnimationControllerActor.cpp | csyonghe/spire-engine | 9c98b277a6643688365f9ce308e8621d90af9c97 | [
"MIT"
] | 60 | 2016-12-02T17:12:51.000Z | 2022-01-23T09:23:19.000Z | GameEngineCore/AnimationControllerActor.cpp | csyonghe/spire-engine | 9c98b277a6643688365f9ce308e8621d90af9c97 | [
"MIT"
] | 5 | 2016-11-14T21:18:57.000Z | 2019-07-12T04:01:12.000Z | GameEngineCore/AnimationControllerActor.cpp | csyonghe/spire-engine | 9c98b277a6643688365f9ce308e8621d90af9c97 | [
"MIT"
] | 11 | 2016-11-14T21:11:46.000Z | 2020-09-10T07:29:01.000Z | #include "AnimationControllerActor.h"
#include "Engine.h"
#include "MeshBuilder.h"
namespace GameEngine
{
void AnimationControllerActor::TimeChanged()
{
EvalAnimation(Time.GetValue());
}
void AnimationControllerActor::IsPlayingChanged()
{
}
SkeletalMeshActor * AnimationControllerActor::GetTargetActor(int id)
{
if (id < TargetActors->Count())
{
auto rs = level->FindActor((*TargetActors)[id]);
return dynamic_cast<SkeletalMeshActor*>(rs);
}
else
{
return nullptr;
}
}
void AnimationControllerActor::OnLoad()
{
MeshBuilder mb;
mb.AddPyramid(40.0f, 40.0f, 40.0f);
SetGizmoCount(1);
SetGizmoMesh(0, mb.ToMesh(), GizmoStyle::Editor);
GizmoActor::OnLoad();
IsPlaying.OnChanged.Bind(this, &AnimationControllerActor::IsPlayingChanged);
Time.OnChanged.Bind(this, &AnimationControllerActor::TimeChanged);
}
void AnimationControllerActor::Tick()
{
Actor::Tick();
if (IsPlaying.GetValue())
{
Time = Time + Engine::Instance()->GetTimeDelta(EngineThread::GameLogic);
}
}
}
| 26.977778 | 84 | 0.60626 | csyonghe |
a3184b440d91969cf3dbb7c101ce800dbc4ba915 | 25,445 | cpp | C++ | dbbrain/src/v20210527/model/SlowLogTopSqlItem.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | dbbrain/src/v20210527/model/SlowLogTopSqlItem.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | dbbrain/src/v20210527/model/SlowLogTopSqlItem.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/dbbrain/v20210527/model/SlowLogTopSqlItem.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Dbbrain::V20210527::Model;
using namespace std;
SlowLogTopSqlItem::SlowLogTopSqlItem() :
m_lockTimeHasBeenSet(false),
m_lockTimeMaxHasBeenSet(false),
m_lockTimeMinHasBeenSet(false),
m_rowsExaminedHasBeenSet(false),
m_rowsExaminedMaxHasBeenSet(false),
m_rowsExaminedMinHasBeenSet(false),
m_queryTimeHasBeenSet(false),
m_queryTimeMaxHasBeenSet(false),
m_queryTimeMinHasBeenSet(false),
m_rowsSentHasBeenSet(false),
m_rowsSentMaxHasBeenSet(false),
m_rowsSentMinHasBeenSet(false),
m_execTimesHasBeenSet(false),
m_sqlTemplateHasBeenSet(false),
m_sqlTextHasBeenSet(false),
m_schemaHasBeenSet(false),
m_queryTimeRatioHasBeenSet(false),
m_lockTimeRatioHasBeenSet(false),
m_rowsExaminedRatioHasBeenSet(false),
m_rowsSentRatioHasBeenSet(false),
m_queryTimeAvgHasBeenSet(false),
m_rowsSentAvgHasBeenSet(false),
m_lockTimeAvgHasBeenSet(false),
m_rowsExaminedAvgHasBeenSet(false)
{
}
CoreInternalOutcome SlowLogTopSqlItem::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("LockTime") && !value["LockTime"].IsNull())
{
if (!value["LockTime"].IsLosslessDouble())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.LockTime` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_lockTime = value["LockTime"].GetDouble();
m_lockTimeHasBeenSet = true;
}
if (value.HasMember("LockTimeMax") && !value["LockTimeMax"].IsNull())
{
if (!value["LockTimeMax"].IsLosslessDouble())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.LockTimeMax` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_lockTimeMax = value["LockTimeMax"].GetDouble();
m_lockTimeMaxHasBeenSet = true;
}
if (value.HasMember("LockTimeMin") && !value["LockTimeMin"].IsNull())
{
if (!value["LockTimeMin"].IsLosslessDouble())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.LockTimeMin` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_lockTimeMin = value["LockTimeMin"].GetDouble();
m_lockTimeMinHasBeenSet = true;
}
if (value.HasMember("RowsExamined") && !value["RowsExamined"].IsNull())
{
if (!value["RowsExamined"].IsInt64())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.RowsExamined` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_rowsExamined = value["RowsExamined"].GetInt64();
m_rowsExaminedHasBeenSet = true;
}
if (value.HasMember("RowsExaminedMax") && !value["RowsExaminedMax"].IsNull())
{
if (!value["RowsExaminedMax"].IsInt64())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.RowsExaminedMax` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_rowsExaminedMax = value["RowsExaminedMax"].GetInt64();
m_rowsExaminedMaxHasBeenSet = true;
}
if (value.HasMember("RowsExaminedMin") && !value["RowsExaminedMin"].IsNull())
{
if (!value["RowsExaminedMin"].IsInt64())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.RowsExaminedMin` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_rowsExaminedMin = value["RowsExaminedMin"].GetInt64();
m_rowsExaminedMinHasBeenSet = true;
}
if (value.HasMember("QueryTime") && !value["QueryTime"].IsNull())
{
if (!value["QueryTime"].IsLosslessDouble())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.QueryTime` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_queryTime = value["QueryTime"].GetDouble();
m_queryTimeHasBeenSet = true;
}
if (value.HasMember("QueryTimeMax") && !value["QueryTimeMax"].IsNull())
{
if (!value["QueryTimeMax"].IsLosslessDouble())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.QueryTimeMax` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_queryTimeMax = value["QueryTimeMax"].GetDouble();
m_queryTimeMaxHasBeenSet = true;
}
if (value.HasMember("QueryTimeMin") && !value["QueryTimeMin"].IsNull())
{
if (!value["QueryTimeMin"].IsLosslessDouble())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.QueryTimeMin` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_queryTimeMin = value["QueryTimeMin"].GetDouble();
m_queryTimeMinHasBeenSet = true;
}
if (value.HasMember("RowsSent") && !value["RowsSent"].IsNull())
{
if (!value["RowsSent"].IsInt64())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.RowsSent` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_rowsSent = value["RowsSent"].GetInt64();
m_rowsSentHasBeenSet = true;
}
if (value.HasMember("RowsSentMax") && !value["RowsSentMax"].IsNull())
{
if (!value["RowsSentMax"].IsInt64())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.RowsSentMax` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_rowsSentMax = value["RowsSentMax"].GetInt64();
m_rowsSentMaxHasBeenSet = true;
}
if (value.HasMember("RowsSentMin") && !value["RowsSentMin"].IsNull())
{
if (!value["RowsSentMin"].IsInt64())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.RowsSentMin` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_rowsSentMin = value["RowsSentMin"].GetInt64();
m_rowsSentMinHasBeenSet = true;
}
if (value.HasMember("ExecTimes") && !value["ExecTimes"].IsNull())
{
if (!value["ExecTimes"].IsInt64())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.ExecTimes` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_execTimes = value["ExecTimes"].GetInt64();
m_execTimesHasBeenSet = true;
}
if (value.HasMember("SqlTemplate") && !value["SqlTemplate"].IsNull())
{
if (!value["SqlTemplate"].IsString())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.SqlTemplate` IsString=false incorrectly").SetRequestId(requestId));
}
m_sqlTemplate = string(value["SqlTemplate"].GetString());
m_sqlTemplateHasBeenSet = true;
}
if (value.HasMember("SqlText") && !value["SqlText"].IsNull())
{
if (!value["SqlText"].IsString())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.SqlText` IsString=false incorrectly").SetRequestId(requestId));
}
m_sqlText = string(value["SqlText"].GetString());
m_sqlTextHasBeenSet = true;
}
if (value.HasMember("Schema") && !value["Schema"].IsNull())
{
if (!value["Schema"].IsString())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.Schema` IsString=false incorrectly").SetRequestId(requestId));
}
m_schema = string(value["Schema"].GetString());
m_schemaHasBeenSet = true;
}
if (value.HasMember("QueryTimeRatio") && !value["QueryTimeRatio"].IsNull())
{
if (!value["QueryTimeRatio"].IsLosslessDouble())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.QueryTimeRatio` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_queryTimeRatio = value["QueryTimeRatio"].GetDouble();
m_queryTimeRatioHasBeenSet = true;
}
if (value.HasMember("LockTimeRatio") && !value["LockTimeRatio"].IsNull())
{
if (!value["LockTimeRatio"].IsLosslessDouble())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.LockTimeRatio` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_lockTimeRatio = value["LockTimeRatio"].GetDouble();
m_lockTimeRatioHasBeenSet = true;
}
if (value.HasMember("RowsExaminedRatio") && !value["RowsExaminedRatio"].IsNull())
{
if (!value["RowsExaminedRatio"].IsLosslessDouble())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.RowsExaminedRatio` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_rowsExaminedRatio = value["RowsExaminedRatio"].GetDouble();
m_rowsExaminedRatioHasBeenSet = true;
}
if (value.HasMember("RowsSentRatio") && !value["RowsSentRatio"].IsNull())
{
if (!value["RowsSentRatio"].IsLosslessDouble())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.RowsSentRatio` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_rowsSentRatio = value["RowsSentRatio"].GetDouble();
m_rowsSentRatioHasBeenSet = true;
}
if (value.HasMember("QueryTimeAvg") && !value["QueryTimeAvg"].IsNull())
{
if (!value["QueryTimeAvg"].IsLosslessDouble())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.QueryTimeAvg` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_queryTimeAvg = value["QueryTimeAvg"].GetDouble();
m_queryTimeAvgHasBeenSet = true;
}
if (value.HasMember("RowsSentAvg") && !value["RowsSentAvg"].IsNull())
{
if (!value["RowsSentAvg"].IsLosslessDouble())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.RowsSentAvg` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_rowsSentAvg = value["RowsSentAvg"].GetDouble();
m_rowsSentAvgHasBeenSet = true;
}
if (value.HasMember("LockTimeAvg") && !value["LockTimeAvg"].IsNull())
{
if (!value["LockTimeAvg"].IsLosslessDouble())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.LockTimeAvg` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_lockTimeAvg = value["LockTimeAvg"].GetDouble();
m_lockTimeAvgHasBeenSet = true;
}
if (value.HasMember("RowsExaminedAvg") && !value["RowsExaminedAvg"].IsNull())
{
if (!value["RowsExaminedAvg"].IsLosslessDouble())
{
return CoreInternalOutcome(Error("response `SlowLogTopSqlItem.RowsExaminedAvg` IsLosslessDouble=false incorrectly").SetRequestId(requestId));
}
m_rowsExaminedAvg = value["RowsExaminedAvg"].GetDouble();
m_rowsExaminedAvgHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void SlowLogTopSqlItem::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_lockTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "LockTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_lockTime, allocator);
}
if (m_lockTimeMaxHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "LockTimeMax";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_lockTimeMax, allocator);
}
if (m_lockTimeMinHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "LockTimeMin";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_lockTimeMin, allocator);
}
if (m_rowsExaminedHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RowsExamined";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_rowsExamined, allocator);
}
if (m_rowsExaminedMaxHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RowsExaminedMax";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_rowsExaminedMax, allocator);
}
if (m_rowsExaminedMinHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RowsExaminedMin";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_rowsExaminedMin, allocator);
}
if (m_queryTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "QueryTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_queryTime, allocator);
}
if (m_queryTimeMaxHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "QueryTimeMax";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_queryTimeMax, allocator);
}
if (m_queryTimeMinHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "QueryTimeMin";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_queryTimeMin, allocator);
}
if (m_rowsSentHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RowsSent";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_rowsSent, allocator);
}
if (m_rowsSentMaxHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RowsSentMax";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_rowsSentMax, allocator);
}
if (m_rowsSentMinHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RowsSentMin";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_rowsSentMin, allocator);
}
if (m_execTimesHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ExecTimes";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_execTimes, allocator);
}
if (m_sqlTemplateHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SqlTemplate";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_sqlTemplate.c_str(), allocator).Move(), allocator);
}
if (m_sqlTextHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SqlText";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_sqlText.c_str(), allocator).Move(), allocator);
}
if (m_schemaHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Schema";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_schema.c_str(), allocator).Move(), allocator);
}
if (m_queryTimeRatioHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "QueryTimeRatio";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_queryTimeRatio, allocator);
}
if (m_lockTimeRatioHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "LockTimeRatio";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_lockTimeRatio, allocator);
}
if (m_rowsExaminedRatioHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RowsExaminedRatio";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_rowsExaminedRatio, allocator);
}
if (m_rowsSentRatioHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RowsSentRatio";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_rowsSentRatio, allocator);
}
if (m_queryTimeAvgHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "QueryTimeAvg";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_queryTimeAvg, allocator);
}
if (m_rowsSentAvgHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RowsSentAvg";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_rowsSentAvg, allocator);
}
if (m_lockTimeAvgHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "LockTimeAvg";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_lockTimeAvg, allocator);
}
if (m_rowsExaminedAvgHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RowsExaminedAvg";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_rowsExaminedAvg, allocator);
}
}
double SlowLogTopSqlItem::GetLockTime() const
{
return m_lockTime;
}
void SlowLogTopSqlItem::SetLockTime(const double& _lockTime)
{
m_lockTime = _lockTime;
m_lockTimeHasBeenSet = true;
}
bool SlowLogTopSqlItem::LockTimeHasBeenSet() const
{
return m_lockTimeHasBeenSet;
}
double SlowLogTopSqlItem::GetLockTimeMax() const
{
return m_lockTimeMax;
}
void SlowLogTopSqlItem::SetLockTimeMax(const double& _lockTimeMax)
{
m_lockTimeMax = _lockTimeMax;
m_lockTimeMaxHasBeenSet = true;
}
bool SlowLogTopSqlItem::LockTimeMaxHasBeenSet() const
{
return m_lockTimeMaxHasBeenSet;
}
double SlowLogTopSqlItem::GetLockTimeMin() const
{
return m_lockTimeMin;
}
void SlowLogTopSqlItem::SetLockTimeMin(const double& _lockTimeMin)
{
m_lockTimeMin = _lockTimeMin;
m_lockTimeMinHasBeenSet = true;
}
bool SlowLogTopSqlItem::LockTimeMinHasBeenSet() const
{
return m_lockTimeMinHasBeenSet;
}
int64_t SlowLogTopSqlItem::GetRowsExamined() const
{
return m_rowsExamined;
}
void SlowLogTopSqlItem::SetRowsExamined(const int64_t& _rowsExamined)
{
m_rowsExamined = _rowsExamined;
m_rowsExaminedHasBeenSet = true;
}
bool SlowLogTopSqlItem::RowsExaminedHasBeenSet() const
{
return m_rowsExaminedHasBeenSet;
}
int64_t SlowLogTopSqlItem::GetRowsExaminedMax() const
{
return m_rowsExaminedMax;
}
void SlowLogTopSqlItem::SetRowsExaminedMax(const int64_t& _rowsExaminedMax)
{
m_rowsExaminedMax = _rowsExaminedMax;
m_rowsExaminedMaxHasBeenSet = true;
}
bool SlowLogTopSqlItem::RowsExaminedMaxHasBeenSet() const
{
return m_rowsExaminedMaxHasBeenSet;
}
int64_t SlowLogTopSqlItem::GetRowsExaminedMin() const
{
return m_rowsExaminedMin;
}
void SlowLogTopSqlItem::SetRowsExaminedMin(const int64_t& _rowsExaminedMin)
{
m_rowsExaminedMin = _rowsExaminedMin;
m_rowsExaminedMinHasBeenSet = true;
}
bool SlowLogTopSqlItem::RowsExaminedMinHasBeenSet() const
{
return m_rowsExaminedMinHasBeenSet;
}
double SlowLogTopSqlItem::GetQueryTime() const
{
return m_queryTime;
}
void SlowLogTopSqlItem::SetQueryTime(const double& _queryTime)
{
m_queryTime = _queryTime;
m_queryTimeHasBeenSet = true;
}
bool SlowLogTopSqlItem::QueryTimeHasBeenSet() const
{
return m_queryTimeHasBeenSet;
}
double SlowLogTopSqlItem::GetQueryTimeMax() const
{
return m_queryTimeMax;
}
void SlowLogTopSqlItem::SetQueryTimeMax(const double& _queryTimeMax)
{
m_queryTimeMax = _queryTimeMax;
m_queryTimeMaxHasBeenSet = true;
}
bool SlowLogTopSqlItem::QueryTimeMaxHasBeenSet() const
{
return m_queryTimeMaxHasBeenSet;
}
double SlowLogTopSqlItem::GetQueryTimeMin() const
{
return m_queryTimeMin;
}
void SlowLogTopSqlItem::SetQueryTimeMin(const double& _queryTimeMin)
{
m_queryTimeMin = _queryTimeMin;
m_queryTimeMinHasBeenSet = true;
}
bool SlowLogTopSqlItem::QueryTimeMinHasBeenSet() const
{
return m_queryTimeMinHasBeenSet;
}
int64_t SlowLogTopSqlItem::GetRowsSent() const
{
return m_rowsSent;
}
void SlowLogTopSqlItem::SetRowsSent(const int64_t& _rowsSent)
{
m_rowsSent = _rowsSent;
m_rowsSentHasBeenSet = true;
}
bool SlowLogTopSqlItem::RowsSentHasBeenSet() const
{
return m_rowsSentHasBeenSet;
}
int64_t SlowLogTopSqlItem::GetRowsSentMax() const
{
return m_rowsSentMax;
}
void SlowLogTopSqlItem::SetRowsSentMax(const int64_t& _rowsSentMax)
{
m_rowsSentMax = _rowsSentMax;
m_rowsSentMaxHasBeenSet = true;
}
bool SlowLogTopSqlItem::RowsSentMaxHasBeenSet() const
{
return m_rowsSentMaxHasBeenSet;
}
int64_t SlowLogTopSqlItem::GetRowsSentMin() const
{
return m_rowsSentMin;
}
void SlowLogTopSqlItem::SetRowsSentMin(const int64_t& _rowsSentMin)
{
m_rowsSentMin = _rowsSentMin;
m_rowsSentMinHasBeenSet = true;
}
bool SlowLogTopSqlItem::RowsSentMinHasBeenSet() const
{
return m_rowsSentMinHasBeenSet;
}
int64_t SlowLogTopSqlItem::GetExecTimes() const
{
return m_execTimes;
}
void SlowLogTopSqlItem::SetExecTimes(const int64_t& _execTimes)
{
m_execTimes = _execTimes;
m_execTimesHasBeenSet = true;
}
bool SlowLogTopSqlItem::ExecTimesHasBeenSet() const
{
return m_execTimesHasBeenSet;
}
string SlowLogTopSqlItem::GetSqlTemplate() const
{
return m_sqlTemplate;
}
void SlowLogTopSqlItem::SetSqlTemplate(const string& _sqlTemplate)
{
m_sqlTemplate = _sqlTemplate;
m_sqlTemplateHasBeenSet = true;
}
bool SlowLogTopSqlItem::SqlTemplateHasBeenSet() const
{
return m_sqlTemplateHasBeenSet;
}
string SlowLogTopSqlItem::GetSqlText() const
{
return m_sqlText;
}
void SlowLogTopSqlItem::SetSqlText(const string& _sqlText)
{
m_sqlText = _sqlText;
m_sqlTextHasBeenSet = true;
}
bool SlowLogTopSqlItem::SqlTextHasBeenSet() const
{
return m_sqlTextHasBeenSet;
}
string SlowLogTopSqlItem::GetSchema() const
{
return m_schema;
}
void SlowLogTopSqlItem::SetSchema(const string& _schema)
{
m_schema = _schema;
m_schemaHasBeenSet = true;
}
bool SlowLogTopSqlItem::SchemaHasBeenSet() const
{
return m_schemaHasBeenSet;
}
double SlowLogTopSqlItem::GetQueryTimeRatio() const
{
return m_queryTimeRatio;
}
void SlowLogTopSqlItem::SetQueryTimeRatio(const double& _queryTimeRatio)
{
m_queryTimeRatio = _queryTimeRatio;
m_queryTimeRatioHasBeenSet = true;
}
bool SlowLogTopSqlItem::QueryTimeRatioHasBeenSet() const
{
return m_queryTimeRatioHasBeenSet;
}
double SlowLogTopSqlItem::GetLockTimeRatio() const
{
return m_lockTimeRatio;
}
void SlowLogTopSqlItem::SetLockTimeRatio(const double& _lockTimeRatio)
{
m_lockTimeRatio = _lockTimeRatio;
m_lockTimeRatioHasBeenSet = true;
}
bool SlowLogTopSqlItem::LockTimeRatioHasBeenSet() const
{
return m_lockTimeRatioHasBeenSet;
}
double SlowLogTopSqlItem::GetRowsExaminedRatio() const
{
return m_rowsExaminedRatio;
}
void SlowLogTopSqlItem::SetRowsExaminedRatio(const double& _rowsExaminedRatio)
{
m_rowsExaminedRatio = _rowsExaminedRatio;
m_rowsExaminedRatioHasBeenSet = true;
}
bool SlowLogTopSqlItem::RowsExaminedRatioHasBeenSet() const
{
return m_rowsExaminedRatioHasBeenSet;
}
double SlowLogTopSqlItem::GetRowsSentRatio() const
{
return m_rowsSentRatio;
}
void SlowLogTopSqlItem::SetRowsSentRatio(const double& _rowsSentRatio)
{
m_rowsSentRatio = _rowsSentRatio;
m_rowsSentRatioHasBeenSet = true;
}
bool SlowLogTopSqlItem::RowsSentRatioHasBeenSet() const
{
return m_rowsSentRatioHasBeenSet;
}
double SlowLogTopSqlItem::GetQueryTimeAvg() const
{
return m_queryTimeAvg;
}
void SlowLogTopSqlItem::SetQueryTimeAvg(const double& _queryTimeAvg)
{
m_queryTimeAvg = _queryTimeAvg;
m_queryTimeAvgHasBeenSet = true;
}
bool SlowLogTopSqlItem::QueryTimeAvgHasBeenSet() const
{
return m_queryTimeAvgHasBeenSet;
}
double SlowLogTopSqlItem::GetRowsSentAvg() const
{
return m_rowsSentAvg;
}
void SlowLogTopSqlItem::SetRowsSentAvg(const double& _rowsSentAvg)
{
m_rowsSentAvg = _rowsSentAvg;
m_rowsSentAvgHasBeenSet = true;
}
bool SlowLogTopSqlItem::RowsSentAvgHasBeenSet() const
{
return m_rowsSentAvgHasBeenSet;
}
double SlowLogTopSqlItem::GetLockTimeAvg() const
{
return m_lockTimeAvg;
}
void SlowLogTopSqlItem::SetLockTimeAvg(const double& _lockTimeAvg)
{
m_lockTimeAvg = _lockTimeAvg;
m_lockTimeAvgHasBeenSet = true;
}
bool SlowLogTopSqlItem::LockTimeAvgHasBeenSet() const
{
return m_lockTimeAvgHasBeenSet;
}
double SlowLogTopSqlItem::GetRowsExaminedAvg() const
{
return m_rowsExaminedAvg;
}
void SlowLogTopSqlItem::SetRowsExaminedAvg(const double& _rowsExaminedAvg)
{
m_rowsExaminedAvg = _rowsExaminedAvg;
m_rowsExaminedAvgHasBeenSet = true;
}
bool SlowLogTopSqlItem::RowsExaminedAvgHasBeenSet() const
{
return m_rowsExaminedAvgHasBeenSet;
}
| 28.849206 | 155 | 0.695972 | sinjoywong |
a31aa12af5dc2ef9e0082d77174be0a120578d62 | 5,380 | cxx | C++ | Qt/Core/pq3DWidgetFactory.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 1 | 2021-07-31T19:38:03.000Z | 2021-07-31T19:38:03.000Z | Qt/Core/pq3DWidgetFactory.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | null | null | null | Qt/Core/pq3DWidgetFactory.cxx | matthb2/ParaView-beforekitwareswtichedtogit | e47e57d6ce88444d9e6af9ab29f9db8c23d24cef | [
"BSD-3-Clause"
] | 2 | 2019-01-22T19:51:40.000Z | 2021-07-31T19:38:05.000Z | /*=========================================================================
Program: ParaView
Module: $RCSfile$
Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include "pq3DWidgetFactory.h"
// ParaView Server Manager includes.
#include "vtkSMNewWidgetRepresentationProxy.h"
#include "vtkSmartPointer.h"
#include "vtkSMProxyManager.h"
// Qt Includes.
#include <QList>
#include <QtDebug>
// ParaView includes.
#include "pqApplicationCore.h"
#include "pqObjectBuilder.h"
#include "pqServerManagerObserver.h"
#include "pqServer.h"
class pq3DWidgetFactoryInternal
{
public:
typedef QList<vtkSmartPointer<vtkSMNewWidgetRepresentationProxy> > ListOfWidgetProxies;
ListOfWidgetProxies Widgets;
ListOfWidgetProxies WidgetsInUse;
};
//-----------------------------------------------------------------------------
pq3DWidgetFactory::pq3DWidgetFactory(QObject* _parent/*=null*/)
: QObject(_parent)
{
this->Internal = new pq3DWidgetFactoryInternal();
QObject::connect(pqApplicationCore::instance()->getServerManagerObserver(),
SIGNAL(proxyUnRegistered(QString, QString, vtkSMProxy*)), this,
SLOT(proxyUnRegistered(QString, QString, vtkSMProxy*)));
}
//-----------------------------------------------------------------------------
pq3DWidgetFactory::~pq3DWidgetFactory()
{
delete this->Internal;
}
//-----------------------------------------------------------------------------
vtkSMNewWidgetRepresentationProxy* pq3DWidgetFactory::get3DWidget(const QString& name,
pqServer* server)
{
pq3DWidgetFactoryInternal::ListOfWidgetProxies::iterator iter =
this->Internal->Widgets.begin();
for (; iter != this->Internal->Widgets.end(); iter++)
{
vtkSMNewWidgetRepresentationProxy* proxy = iter->GetPointer();
if (proxy && proxy->GetConnectionID() == server->GetConnectionID()
&& name == proxy->GetXMLName())
{
this->Internal->WidgetsInUse.push_back(proxy);
this->Internal->Widgets.erase(iter);
return proxy;
}
}
pqObjectBuilder* builder =
pqApplicationCore::instance()->getObjectBuilder();
// We register the 3DWidget proxy under prototypes so that it
// is never saved in state
vtkSMNewWidgetRepresentationProxy* proxy = vtkSMNewWidgetRepresentationProxy::SafeDownCast(
builder->createProxy("representations",
name.toAscii().data(), server,
"3d_widgets_prototypes"));
if (!proxy)
{
qDebug() << "Could not create the 3D widget with name: " << name;
return NULL;
}
this->Internal->WidgetsInUse.push_back(proxy);
return proxy;
}
//-----------------------------------------------------------------------------
void pq3DWidgetFactory::free3DWidget(vtkSMNewWidgetRepresentationProxy* widget)
{
pq3DWidgetFactoryInternal::ListOfWidgetProxies::iterator iter =
this->Internal->WidgetsInUse.begin();
for (; iter != this->Internal->WidgetsInUse.end(); iter++)
{
vtkSMNewWidgetRepresentationProxy* proxy = iter->GetPointer();
if (proxy == widget)
{
this->Internal->Widgets.push_back(proxy);
this->Internal->WidgetsInUse.erase(iter);
return;
}
}
// qDebug() << "free3DWidget called on a free widget on a widget not managed"
// " by this class.";
}
//-----------------------------------------------------------------------------
void pq3DWidgetFactory::proxyUnRegistered(QString group,
QString vtkNotUsed(name), vtkSMProxy* proxy)
{
vtkSMNewWidgetRepresentationProxy* widget;
if (group != "3d_widgets_prototypes" ||
(widget = vtkSMNewWidgetRepresentationProxy::SafeDownCast(proxy)) == 0)
{
return;
}
// Check if the unregistered proxy is the one managed by this class.
pq3DWidgetFactoryInternal::ListOfWidgetProxies::iterator iter;
for (iter = this->Internal->WidgetsInUse.begin();
iter != this->Internal->WidgetsInUse.end(); iter++)
{
if (iter->GetPointer() == widget)
{
this->Internal->WidgetsInUse.erase(iter);
break;
}
}
for (iter = this->Internal->Widgets.begin();
iter != this->Internal->Widgets.end(); ++iter)
{
if (iter->GetPointer() == widget)
{
this->Internal->Widgets.erase(iter);
break;
}
}
}
| 33.625 | 93 | 0.645725 | matthb2 |
a31e845b50b3df7345502861c9d0473c2b0dbbbf | 292 | cc | C++ | utility/std_stubs.cc | natersoz/nrf | f5fd98275e291f02ad53818aee857278ac23d7df | [
"Apache-2.0"
] | 3 | 2018-03-04T19:21:11.000Z | 2021-01-15T09:17:53.000Z | utility/std_stubs.cc | natersoz/nrf | f5fd98275e291f02ad53818aee857278ac23d7df | [
"Apache-2.0"
] | 37 | 2018-10-09T04:28:51.000Z | 2019-06-07T03:48:39.000Z | utility/std_stubs.cc | natersoz/nrf | f5fd98275e291f02ad53818aee857278ac23d7df | [
"Apache-2.0"
] | null | null | null | /**
* @file std_stubs.cc
* @copyright (c) 2018, natersoz. Distributed under the Apache 2.0 license.
*/
#include <cstddef>
// Under gcc using virtual destructors, even when no malloc is involved,
// requires a delete operator to satisy the linker.
void operator delete(void*, size_t)
{}
| 22.461538 | 75 | 0.719178 | natersoz |
a3216796b291da88a868b848bbb35ac4b32c75c4 | 2,184 | cpp | C++ | src/Engine/EngineSettings.cpp | Mac1512/engge | 50c203c09b57c0fbbcdf6284c60886c8db471e07 | [
"MIT"
] | null | null | null | src/Engine/EngineSettings.cpp | Mac1512/engge | 50c203c09b57c0fbbcdf6284c60886c8db471e07 | [
"MIT"
] | null | null | null | src/Engine/EngineSettings.cpp | Mac1512/engge | 50c203c09b57c0fbbcdf6284c60886c8db471e07 | [
"MIT"
] | null | null | null | #include <sstream>
#include <filesystem>
#include "System/Locator.hpp"
#include "Engine/Preferences.hpp"
#include "Engine/EngineSettings.hpp"
#include "../System/_Util.hpp"
namespace fs = std::filesystem;
namespace ng {
EngineSettings::EngineSettings() = default;
void EngineSettings::loadPacks() {
auto devPath = ng::Locator<ng::Preferences>::get().getUserPreference(PreferenceNames::DevPath,
PreferenceDefaultValues::DevPath);
auto path = devPath.empty() ? fs::current_path() : fs::path(devPath);
for (const auto &entry : fs::directory_iterator(path)) {
if (ng::startsWith(entry.path().extension().string(), ".ggpack")) {
auto pack = std::make_unique<GGPack>();
pack->open(entry.path().string());
_packs.push_back(std::move(pack));
}
}
}
bool EngineSettings::hasEntry(const std::string &name) {
std::ifstream is;
is.open(name);
if (is.is_open()) {
is.close();
return true;
}
auto it = std::find_if(_packs.begin(), _packs.end(), [&name](auto &pack) {
return pack->hasEntry(name);
});
return it != _packs.end();
}
void EngineSettings::readEntry(const std::string &name, std::vector<char> &data) {
// first try to find the resource in the filesystem
std::ifstream is;
is.open(name);
if (is.is_open()) {
is.seekg(0, std::ios::end);
auto size = is.tellg();
data.resize(size);
is.seekg(0, std::ios::beg);
is.read(data.data(), size);
is.close();
return;
}
// not found in filesystem, check in the pack files
auto it = std::find_if(_packs.begin(), _packs.end(), [&name](auto &pack) {
return pack->hasEntry(name);
});
if (it != _packs.end()) {
(*it)->readEntry(name, data);
}
}
void EngineSettings::readEntry(const std::string &name, GGPackValue &hash) {
auto it = std::find_if(_packs.begin(), _packs.end(), [&name](auto &pack) {
return pack->hasEntry(name);
});
if (it != _packs.end()) {
(*it)->readHashEntry(name, hash);
}
}
void EngineSettings::getEntries(std::vector<std::string> &entries) {
for (auto &pack : _packs) {
pack->getEntries(entries);
}
}
} // namespace ng
| 28.736842 | 105 | 0.624542 | Mac1512 |
a321c313fdbc1d18d9ff11bd7aed31a2b4491599 | 1,276 | cpp | C++ | src/battery.cpp | underscoredotspace/watchy-revolution | 9403314a47e53565e36172c37a75d9622657c51f | [
"MIT"
] | null | null | null | src/battery.cpp | underscoredotspace/watchy-revolution | 9403314a47e53565e36172c37a75d9622657c51f | [
"MIT"
] | null | null | null | src/battery.cpp | underscoredotspace/watchy-revolution | 9403314a47e53565e36172c37a75d9622657c51f | [
"MIT"
] | null | null | null | #include "battery.h"
#include <esp_adc_cal.h>
#include "Watchy.h" // for logging macros
namespace Watchy {
esp_adc_cal_characteristics_t *getADCCharacteristics() {
static esp_adc_cal_characteristics_t *adc_chars; // default is nullptr
if (!adc_chars) {
// only initialize it if we're actually going to use it.
adc_chars = new esp_adc_cal_characteristics_t();
adc1_config_width(ADC_WIDTH_BIT_12);
adc1_config_channel_atten(ADC1_GPIO33_CHANNEL, ADC_ATTEN_DB_11);
esp_adc_cal_value_t cal = esp_adc_cal_characterize(
ADC_UNIT_1, ADC_ATTEN_DB_11, ADC_WIDTH_BIT_12, 1100, adc_chars);
if (cal == ESP_ADC_CAL_VAL_DEFAULT_VREF) {
LOGW("adc calibration is using default vref. Accuracy will suffer.");
}
}
return adc_chars;
}
float getBatteryVoltage() {
// make sure ADC is initialized before we read it.
esp_adc_cal_characteristics_t *adcChar = getADCCharacteristics();
// average 4 samples to reduce noise
int raw =
(adc1_get_raw(ADC1_GPIO33_CHANNEL) + adc1_get_raw(ADC1_GPIO33_CHANNEL) +
adc1_get_raw(ADC1_GPIO33_CHANNEL) + adc1_get_raw(ADC1_GPIO33_CHANNEL) +
2) /
4;
return esp_adc_cal_raw_to_voltage(raw, adcChar) * 2.0 / 1000.0;
}
} // namespace Watchy | 35.444444 | 79 | 0.719436 | underscoredotspace |
a324632ff8f265c48f23dc594f631de7a5a1641b | 2,904 | cc | C++ | cpp/Max_submatrix_rectangle.cc | iskhanba/epicode | fda752e5e016ab64011083450be91bec9ee8358a | [
"MIT"
] | null | null | null | cpp/Max_submatrix_rectangle.cc | iskhanba/epicode | fda752e5e016ab64011083450be91bec9ee8358a | [
"MIT"
] | null | null | null | cpp/Max_submatrix_rectangle.cc | iskhanba/epicode | fda752e5e016ab64011083450be91bec9ee8358a | [
"MIT"
] | null | null | null | // Copyright (c) 2013 Elements of Programming Interviews. All rights reserved.
#include <algorithm>
#include <cassert>
#include <deque>
#include <iostream>
#include <limits>
#include <random>
#include <vector>
#include "./Max_submatrix_rectangle_brute_force.h"
using std::cout;
using std::default_random_engine;
using std::deque;
using std::endl;
using std::max;
using std::min;
using std::numeric_limits;
using std::random_device;
using std::uniform_int_distribution;
using std::vector;
// @include
struct MaxHW {
int h, w;
};
int MaxRectangleSubmatrix(const vector<deque<bool>>& A) {
// DP table stores (h, w) for each (i, j).
vector<vector<MaxHW>> table(A.size(), vector<MaxHW>(A.front().size()));
for (int i = A.size() - 1; i >= 0; --i) {
for (int j = A[i].size() - 1; j >= 0; --j) {
// Find the largest h such that (i, j) to (i + h - 1, j) are feasible.
// Find the largest w such that (i, j) to (i, j + w - 1) are feasible.
table[i][j] =
A[i][j] ? MaxHW{i + 1 < A.size() ? table[i + 1][j].h + 1 : 1,
j + 1 < A[i].size() ? table[i][j + 1].w + 1 : 1}
:
MaxHW{0, 0};
}
}
int max_rect_area = 0;
for (int i = 0; i < A.size(); ++i) {
for (int j = 0; j < A[i].size(); ++j) {
// Process (i, j) if it is feasible and is possible to update
// max_rect_area.
if (A[i][j] && table[i][j].w * table[i][j].h > max_rect_area) {
int min_width = numeric_limits<int>::max();
for (int a = 0; a < table[i][j].h; ++a) {
min_width = min(min_width, table[i + a][j].w);
max_rect_area = max(max_rect_area, min_width * (a + 1));
}
}
}
}
return max_rect_area;
}
// @exclude
int main(int argc, char* argv[]) {
default_random_engine gen((random_device())());
for (int times = 0; times < 1000; ++times) {
int n, m;
if (argc == 3) {
n = atoi(argv[1]), m = atoi(argv[2]);
} else {
uniform_int_distribution<int> dis(1, 50);
n = dis(gen), m = dis(gen);
}
vector<deque<bool>> A(n, deque<bool>(m));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
uniform_int_distribution<int> true_or_false(0, 1);
A[i][j] = true_or_false(gen) ? true : false;
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cout << A[i][j] << ' ';
}
cout << endl;
}
cout << MaxRectangleSubmatrix(A) << endl;
int test_area = MaxRectangleSubmatrixBruteForce(A);
cout << test_area << endl;
assert(test_area == MaxRectangleSubmatrix(A));
}
return 0;
}
| 31.225806 | 82 | 0.495179 | iskhanba |
a325b3ab4f22f8e883e3edf77e2400740cac78ca | 2,795 | hpp | C++ | streams/file_data_provider.hpp | aamshukov/compression | 3dd06242601798469145feddcd7441f295608454 | [
"MIT"
] | 1 | 2019-07-08T17:33:26.000Z | 2019-07-08T17:33:26.000Z | streams/file_data_provider.hpp | aamshukov/compression | 3dd06242601798469145feddcd7441f295608454 | [
"MIT"
] | null | null | null | streams/file_data_provider.hpp | aamshukov/compression | 3dd06242601798469145feddcd7441f295608454 | [
"MIT"
] | null | null | null | //..............................
// UI Lab Inc. Arthur Amshukov .
//..............................
#ifndef __COMPRESSION_FILE_DATA_PROVIDER_H__
#define __COMPRESSION_FILE_DATA_PROVIDER_H__
#pragma once
BEGIN_NAMESPACE(compression)
class file_data_provider : public data_provider<byte>
{
public:
using status_type = data_provider::status_type;
private:
using file_type = FILE*;
public:
file_type my_file;
errno_t my_status;
string_type my_file_name;
public:
file_data_provider(const string_type& file_name, const wchar_t* mode);
virtual ~file_data_provider();
bool eof() const override;
status_type status() const override;
bool get(byte& value) override;
bool put(const byte& value) override;
void flush() override;
void rewind();
};
inline file_data_provider::file_data_provider(const string_type& file_name, const wchar_t* mode)
: my_file(nullptr),
my_status(0),
my_file_name(file_name)
{
FILE* file(nullptr);
my_status = _wfopen_s(&file, file_name.c_str(), mode);
if(my_status == 0 && file != nullptr)
{
my_status = fseek(file, 0L, SEEK_SET);
if(my_status == 0)
{
my_file = file;
}
}
}
inline file_data_provider::~file_data_provider()
{
if(my_file != nullptr)
{
fflush(my_file);
fclose(my_file);
my_file = nullptr;
my_status = 0;
}
}
inline bool file_data_provider::eof() const
{
return feof(my_file);
}
inline typename file_data_provider::status_type file_data_provider::status() const
{
return my_status;
}
inline bool file_data_provider::get(byte& value)
{
bool result = false;
if(my_status == 0 && my_file != nullptr)
{
result = fread(&value, sizeof(byte), 1, my_file) == 1;
my_status = ferror(my_file);
}
return result;
}
inline bool file_data_provider::put(const byte& value)
{
bool result = false;
if(my_status == 0 && my_file != nullptr)
{
result = fwrite(&value, 1, sizeof(byte), my_file) == sizeof(byte);
my_status = ferror(my_file);
}
return result;
}
inline void file_data_provider::flush()
{
if(my_status == 0 && my_file != nullptr)
{
fflush(my_file);
}
}
inline void file_data_provider::rewind()
{
if(my_status == 0 && my_file != nullptr)
{
fseek(my_file, 0L, SEEK_SET);
}
}
END_NAMESPACE
#endif // __COMPRESSION_FILE_DATA_PROVIDER_H__
| 21.666667 | 97 | 0.561002 | aamshukov |
a325c834022c3335b957396c73a31deaaecba407 | 11,776 | cpp | C++ | dbms/src/IO/tests/write_buffer_aio.cpp | ssmike/ClickHouse | fafecb3c25a59777ed691c0a1936d66181d4d093 | [
"Apache-2.0"
] | 5 | 2018-05-10T14:40:44.000Z | 2020-12-13T11:43:15.000Z | dbms/src/IO/tests/write_buffer_aio.cpp | ssmike/ClickHouse | fafecb3c25a59777ed691c0a1936d66181d4d093 | [
"Apache-2.0"
] | null | null | null | dbms/src/IO/tests/write_buffer_aio.cpp | ssmike/ClickHouse | fafecb3c25a59777ed691c0a1936d66181d4d093 | [
"Apache-2.0"
] | 2 | 2020-05-23T04:55:22.000Z | 2020-05-24T11:30:51.000Z | #include <IO/WriteBufferAIO.h>
#include <Core/Defines.h>
#include <boost/filesystem.hpp>
#include <iostream>
#include <fstream>
#include <streambuf>
#include <cstdlib>
namespace
{
namespace fs = boost::filesystem;
void run();
void die(const std::string & msg);
void runTest(unsigned int num, const std::function<bool()> & func);
std::string createTmpFile();
std::string generateString(size_t n);
bool test1();
bool test2();
bool test3();
bool test4();
bool test5();
bool test6();
bool test7();
bool test8();
bool test9();
bool test10();
void run()
{
const std::vector<std::function<bool()>> tests =
{
test1,
test2,
test3,
test4,
test5,
test6,
test7,
test8,
test9,
test10
};
unsigned int num = 0;
for (const auto & test : tests)
{
++num;
runTest(num, test);
}
}
void die(const std::string & msg)
{
std::cout << msg;
::exit(EXIT_FAILURE);
}
void runTest(unsigned int num, const std::function<bool()> & func)
{
bool ok;
try
{
ok = func();
}
catch (const DB::Exception & ex)
{
ok = false;
std::cout << "Caught exception " << ex.displayText() << "\n";
}
catch (const std::exception & ex)
{
ok = false;
std::cout << "Caught exception " << ex.what() << "\n";
}
if (ok)
std::cout << "Test " << num << " passed\n";
else
std::cout << "Test " << num << " failed\n";
}
std::string createTmpFile()
{
char pattern[] = "/tmp/fileXXXXXX";
char * dir = ::mkdtemp(pattern);
if (dir == nullptr)
die("Could not create directory");
return std::string(dir) + "/foo";
}
std::string generateString(size_t n)
{
static const std::string symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
std::string buf;
buf.reserve(n);
for (size_t i = 0; i < n; ++i)
buf += symbols[i % symbols.length()];
return buf;
}
bool test1()
{
std::string filename = createTmpFile();
size_t n = 10 * DEFAULT_AIO_FILE_BLOCK_SIZE;
std::string buf = generateString(n);
{
DB::WriteBufferAIO out(filename, 3 * DEFAULT_AIO_FILE_BLOCK_SIZE);
if (out.getFileName() != filename)
return false;
if (out.getFD() == -1)
return false;
out.write(&buf[0], buf.length());
}
std::ifstream in(filename.c_str());
if (!in.is_open())
die("Could not open file");
std::string received{ std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>() };
in.close();
fs::remove_all(fs::path(filename).parent_path().string());
return (received == buf);
}
bool test2()
{
std::string filename = createTmpFile();
size_t n = 10 * DEFAULT_AIO_FILE_BLOCK_SIZE;
std::string buf = generateString(n);
{
DB::WriteBufferAIO out(filename, 3 * DEFAULT_AIO_FILE_BLOCK_SIZE);
if (out.getFileName() != filename)
return false;
if (out.getFD() == -1)
return false;
out.write(&buf[0], buf.length() / 2);
out.seek(DEFAULT_AIO_FILE_BLOCK_SIZE, SEEK_CUR);
out.write(&buf[buf.length() / 2], buf.length() / 2);
}
std::ifstream in(filename.c_str());
if (!in.is_open())
die("Could not open file");
std::string received{ std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>() };
in.close();
fs::remove_all(fs::path(filename).parent_path().string());
if (received.substr(0, buf.length() / 2) != buf.substr(0, buf.length() / 2))
return false;
if (received.substr(buf.length() / 2, DEFAULT_AIO_FILE_BLOCK_SIZE) != std::string(DEFAULT_AIO_FILE_BLOCK_SIZE, '\0'))
return false;
if (received.substr(buf.length() / 2 + DEFAULT_AIO_FILE_BLOCK_SIZE) != buf.substr(buf.length() / 2))
return false;
return true;
}
bool test3()
{
std::string filename = createTmpFile();
size_t n = 10 * DEFAULT_AIO_FILE_BLOCK_SIZE;
std::string buf = generateString(n);
{
DB::WriteBufferAIO out(filename, 3 * DEFAULT_AIO_FILE_BLOCK_SIZE);
if (out.getFileName() != filename)
return false;
if (out.getFD() == -1)
return false;
out.write(&buf[0], buf.length());
off_t pos1 = out.getPositionInFile();
out.truncate(buf.length() / 2);
off_t pos2 = out.getPositionInFile();
if (pos1 != pos2)
return false;
}
std::ifstream in(filename.c_str());
if (!in.is_open())
die("Could not open file");
std::string received{ std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>() };
in.close();
fs::remove_all(fs::path(filename).parent_path().string());
return (received == buf.substr(0, buf.length() / 2));
}
bool test4()
{
std::string filename = createTmpFile();
size_t n = 10 * DEFAULT_AIO_FILE_BLOCK_SIZE;
std::string buf = generateString(n);
{
DB::WriteBufferAIO out(filename, 3 * DEFAULT_AIO_FILE_BLOCK_SIZE);
if (out.getFileName() != filename)
return false;
if (out.getFD() == -1)
return false;
out.write(&buf[0], buf.length());
off_t pos1 = out.getPositionInFile();
out.truncate(3 * buf.length() / 2);
off_t pos2 = out.getPositionInFile();
if (pos1 != pos2)
return false;
}
std::ifstream in(filename.c_str());
if (!in.is_open())
die("Could not open file");
std::string received{ std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>() };
in.close();
fs::remove_all(fs::path(filename).parent_path().string());
if (received.substr(0, buf.length()) != buf)
return false;
if (received.substr(buf.length()) != std::string(buf.length() / 2, '\0'))
return false;
return true;
}
bool test5()
{
std::string filename = createTmpFile();
size_t n = 10 * DEFAULT_AIO_FILE_BLOCK_SIZE;
std::string buf = generateString(n);
{
DB::WriteBufferAIO out(filename, 3 * DEFAULT_AIO_FILE_BLOCK_SIZE);
if (out.getFileName() != filename)
return false;
if (out.getFD() == -1)
return false;
out.seek(1, SEEK_SET);
out.write(&buf[0], buf.length());
}
std::ifstream in(filename.c_str());
if (!in.is_open())
die("Could not open file");
std::string received{ std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>() };
in.close();
fs::remove_all(fs::path(filename).parent_path().string());
return received.substr(1) == buf;
}
bool test6()
{
std::string filename = createTmpFile();
size_t n = 10 * DEFAULT_AIO_FILE_BLOCK_SIZE;
std::string buf = generateString(n);
std::string buf2 = "1111111111";
{
DB::WriteBufferAIO out(filename, 3 * DEFAULT_AIO_FILE_BLOCK_SIZE);
if (out.getFileName() != filename)
return false;
if (out.getFD() == -1)
return false;
out.seek(3, SEEK_SET);
out.write(&buf[0], buf.length());
out.seek(-2 * DEFAULT_AIO_FILE_BLOCK_SIZE, SEEK_CUR);
out.write(&buf2[0], buf2.length());
}
std::ifstream in(filename.c_str());
if (!in.is_open())
die("Could not open file");
std::string received{ std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>() };
in.close();
fs::remove_all(fs::path(filename).parent_path().string());
if (received.substr(3, 8 * DEFAULT_AIO_FILE_BLOCK_SIZE) != buf.substr(0, 8 * DEFAULT_AIO_FILE_BLOCK_SIZE))
return false;
if (received.substr(3 + 8 * DEFAULT_AIO_FILE_BLOCK_SIZE, 10) != buf2)
return false;
if (received.substr(13 + 8 * DEFAULT_AIO_FILE_BLOCK_SIZE) != buf.substr(10 + 8 * DEFAULT_AIO_FILE_BLOCK_SIZE))
return false;
return true;
}
bool test7()
{
std::string filename = createTmpFile();
std::string buf2 = "11111111112222222222";
{
DB::WriteBufferAIO out(filename, DEFAULT_AIO_FILE_BLOCK_SIZE);
if (out.getFileName() != filename)
return false;
if (out.getFD() == -1)
return false;
out.seek(DEFAULT_AIO_FILE_BLOCK_SIZE - (buf2.length() / 2), SEEK_SET);
out.write(&buf2[0], buf2.length());
}
std::ifstream in(filename.c_str());
if (!in.is_open())
die("Could not open file");
std::string received{ std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>() };
if (received.length() != 4106)
return false;
if (received.substr(0, 4086) != std::string(4086, '\0'))
return false;
if (received.substr(4086, 20) != buf2)
return false;
in.close();
fs::remove_all(fs::path(filename).parent_path().string());
return true;
}
bool test8()
{
std::string filename = createTmpFile();
std::string buf2 = "11111111112222222222";
{
DB::WriteBufferAIO out(filename, 2 * DEFAULT_AIO_FILE_BLOCK_SIZE);
if (out.getFileName() != filename)
return false;
if (out.getFD() == -1)
return false;
out.seek(2 * DEFAULT_AIO_FILE_BLOCK_SIZE - (buf2.length() / 2), SEEK_SET);
out.write(&buf2[0], buf2.length());
}
std::ifstream in(filename.c_str());
if (!in.is_open())
die("Could not open file");
std::string received{ std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>() };
if (received.length() != 8202)
return false;
if (received.substr(0, 8182) != std::string(8182, '\0'))
return false;
if (received.substr(8182, 20) != buf2)
return false;
in.close();
fs::remove_all(fs::path(filename).parent_path().string());
return true;
}
bool test9()
{
std::string filename = createTmpFile();
size_t n = 3 * DEFAULT_AIO_FILE_BLOCK_SIZE;
std::string buf = generateString(n);
std::string buf2(DEFAULT_AIO_FILE_BLOCK_SIZE + 10, '1');
{
DB::WriteBufferAIO out(filename, 2 * DEFAULT_AIO_FILE_BLOCK_SIZE);
if (out.getFileName() != filename)
return false;
if (out.getFD() == -1)
return false;
out.seek(3, SEEK_SET);
out.write(&buf[0], buf.length());
out.seek(-DEFAULT_AIO_FILE_BLOCK_SIZE, SEEK_CUR);
out.write(&buf2[0], buf2.length());
}
std::ifstream in(filename.c_str());
if (!in.is_open())
die("Could not open file");
std::string received{ std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>() };
in.close();
fs::remove_all(fs::path(filename).parent_path().string());
if (received.substr(3, 2 * DEFAULT_AIO_FILE_BLOCK_SIZE) != buf.substr(0, 2 * DEFAULT_AIO_FILE_BLOCK_SIZE))
return false;
if (received.substr(3 + 2 * DEFAULT_AIO_FILE_BLOCK_SIZE, DEFAULT_AIO_FILE_BLOCK_SIZE + 10) != buf2)
return false;
return true;
}
bool test10()
{
std::string filename = createTmpFile();
size_t n = 10 * DEFAULT_AIO_FILE_BLOCK_SIZE + 3;
std::string buf = generateString(n);
{
DB::WriteBufferAIO out(filename, 3 * DEFAULT_AIO_FILE_BLOCK_SIZE);
if (out.getFileName() != filename)
return false;
if (out.getFD() == -1)
return false;
out.write(&buf[0], buf.length());
}
std::ifstream in(filename.c_str());
if (!in.is_open())
die("Could not open file");
std::string received{ std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>() };
in.close();
fs::remove_all(fs::path(filename).parent_path().string());
return (received == buf);
}
}
int main()
{
run();
return 0;
}
| 23.599198 | 121 | 0.591882 | ssmike |
a325fde9a26bb9974619a17beaf032294a21141e | 277 | cpp | C++ | test/compile_time_tests/test_state_invalid_type.cpp | doheide/thistam | 2ead48afc88bf8c6073b2558f2749b8ec06ec5ec | [
"MIT"
] | 1 | 2018-09-23T22:10:59.000Z | 2018-09-23T22:10:59.000Z | test/compile_time_tests/test_state_invalid_type.cpp | doheide/thism | 2ead48afc88bf8c6073b2558f2749b8ec06ec5ec | [
"MIT"
] | null | null | null | test/compile_time_tests/test_state_invalid_type.cpp | doheide/thism | 2ead48afc88bf8c6073b2558f2749b8ec06ec5ec | [
"MIT"
] | null | null | null | #include "thism/sm2.h"
struct E_Lala; MAKE_EVENT(E_Lala, 0);
struct EventList; MAKE_EVENT_LIST(EventList, E_Lala);
#include "base_test_sys_sm.h"
struct SM_Test;
Make_StateMachine( SM_Test, MarkInitialState<S_Main>, S_Tick, S_TickInner, S_TickInnerInner, S_Tack, int );
| 18.466667 | 107 | 0.776173 | doheide |
a327d419d11e8b17ad297a85ed00ae885bb2d9cf | 9,163 | cpp | C++ | tutorials/displacement_geometry/displacement_geometry_device.cpp | brechtvl/embree | ae029e2ff83bebbbe8742c88aba5b0521aba1a23 | [
"Apache-2.0"
] | 1,700 | 2015-01-02T15:40:58.000Z | 2022-03-30T19:58:13.000Z | tutorials/displacement_geometry/displacement_geometry_device.cpp | brechtvl/embree | ae029e2ff83bebbbe8742c88aba5b0521aba1a23 | [
"Apache-2.0"
] | 338 | 2015-01-06T08:47:31.000Z | 2022-03-21T14:32:34.000Z | tutorials/displacement_geometry/displacement_geometry_device.cpp | brechtvl/embree | ae029e2ff83bebbbe8742c88aba5b0521aba1a23 | [
"Apache-2.0"
] | 346 | 2015-01-13T09:44:09.000Z | 2022-03-31T23:27:37.000Z | // Copyright 2009-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include "../common/tutorial/tutorial_device.h"
namespace embree {
/* configuration */
#define EDGE_LEVEL 256.0f
#define ENABLE_SMOOTH_NORMALS 0
/* scene data */
RTCScene g_scene = nullptr;
/* previous camera position */
Vec3fa old_p;
__aligned(16) float cube_vertices[8][4] =
{
{ -1.0f, -1.0f, -1.0f, 0.0f },
{ 1.0f, -1.0f, -1.0f, 0.0f },
{ 1.0f, -1.0f, 1.0f, 0.0f },
{ -1.0f, -1.0f, 1.0f, 0.0f },
{ -1.0f, 1.0f, -1.0f, 0.0f },
{ 1.0f, 1.0f, -1.0f, 0.0f },
{ 1.0f, 1.0f, 1.0f, 0.0f },
{ -1.0f, 1.0f, 1.0f, 0.0f }
};
#if 1
#define NUM_INDICES 24
#define NUM_FACES 6
#define FACE_SIZE 4
unsigned int cube_indices[24] = {
0, 4, 5, 1,
1, 5, 6, 2,
2, 6, 7, 3,
0, 3, 7, 4,
4, 7, 6, 5,
0, 1, 2, 3,
};
unsigned int cube_faces[6] = {
4, 4, 4, 4, 4, 4
};
#else
#define NUM_INDICES 36
#define NUM_FACES 12
#define FACE_SIZE 3
unsigned int cube_indices[36] = {
1, 4, 5, 0, 4, 1,
2, 5, 6, 1, 5, 2,
3, 6, 7, 2, 6, 3,
4, 3, 7, 0, 3, 4,
5, 7, 6, 4, 7, 5,
3, 1, 2, 0, 1, 3
};
unsigned int cube_faces[12] = {
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3
};
#endif
float displacement(const Vec3fa& P)
{
float dN = 0.0f;
for (float freq = 1.0f; freq<40.0f; freq*= 2) {
float n = abs(noise(freq*P));
dN += 1.4f*n*n/freq;
}
return dN;
}
float displacement_du(const Vec3fa& P, const Vec3fa& dPdu)
{
const float du = 0.001f;
return (displacement(P+du*dPdu)-displacement(P))/du;
}
float displacement_dv(const Vec3fa& P, const Vec3fa& dPdv)
{
const float dv = 0.001f;
return (displacement(P+dv*dPdv)-displacement(P))/dv;
}
void displacementFunction(const struct RTCDisplacementFunctionNArguments* args)
{
const float* nx = args->Ng_x;
const float* ny = args->Ng_y;
const float* nz = args->Ng_z;
float* px = args->P_x;
float* py = args->P_y;
float* pz = args->P_z;
unsigned int N = args->N;
for (unsigned int i=0; i<N; i++) {
const Vec3fa P = Vec3fa(px[i],py[i],pz[i]);
const Vec3fa Ng = Vec3fa(nx[i],ny[i],nz[i]);
const Vec3fa dP = displacement(P)*Ng;
px[i] += dP.x; py[i] += dP.y; pz[i] += dP.z;
}
}
/* adds a cube to the scene */
unsigned int addCube (RTCScene scene_i)
{
/* create a triangulated cube with 6 quads and 8 vertices */
RTCGeometry geom = rtcNewGeometry(g_device, RTC_GEOMETRY_TYPE_SUBDIVISION);
rtcSetSharedGeometryBuffer(geom, RTC_BUFFER_TYPE_VERTEX, 0, RTC_FORMAT_FLOAT3, cube_vertices, 0, sizeof(Vec3fa), 8);
rtcSetSharedGeometryBuffer(geom, RTC_BUFFER_TYPE_INDEX, 0, RTC_FORMAT_UINT, cube_indices, 0, sizeof(unsigned int), NUM_INDICES);
rtcSetSharedGeometryBuffer(geom, RTC_BUFFER_TYPE_FACE, 0, RTC_FORMAT_UINT, cube_faces, 0, sizeof(unsigned int), NUM_FACES);
float* level = (float*) rtcSetNewGeometryBuffer(geom, RTC_BUFFER_TYPE_LEVEL, 0, RTC_FORMAT_FLOAT, sizeof(float), NUM_INDICES);
for (size_t i=0; i<NUM_INDICES; i++) level[i] = EDGE_LEVEL;
rtcSetGeometryDisplacementFunction(geom,displacementFunction);
rtcCommitGeometry(geom);
unsigned int geomID = rtcAttachGeometry(scene_i,geom);
rtcReleaseGeometry(geom);
return geomID;
}
/* adds a ground plane to the scene */
unsigned int addGroundPlane (RTCScene scene_i)
{
/* create a triangulated plane with 2 triangles and 4 vertices */
RTCGeometry geom = rtcNewGeometry (g_device, RTC_GEOMETRY_TYPE_TRIANGLE);
/* set vertices */
Vertex* vertices = (Vertex*) rtcSetNewGeometryBuffer(geom,RTC_BUFFER_TYPE_VERTEX,0,RTC_FORMAT_FLOAT3,sizeof(Vertex),4);
vertices[0].x = -10; vertices[0].y = -2; vertices[0].z = -10;
vertices[1].x = -10; vertices[1].y = -2; vertices[1].z = +10;
vertices[2].x = +10; vertices[2].y = -2; vertices[2].z = -10;
vertices[3].x = +10; vertices[3].y = -2; vertices[3].z = +10;
/* set triangles */
Triangle* triangles = (Triangle*) rtcSetNewGeometryBuffer(geom,RTC_BUFFER_TYPE_INDEX,0,RTC_FORMAT_UINT3,sizeof(Triangle),2);
triangles[0].v0 = 0; triangles[0].v1 = 1; triangles[0].v2 = 2;
triangles[1].v0 = 1; triangles[1].v1 = 3; triangles[1].v2 = 2;
rtcCommitGeometry(geom);
unsigned int geomID = rtcAttachGeometry(scene_i,geom);
rtcReleaseGeometry(geom);
return geomID;
}
/* called by the C++ code for initialization */
extern "C" void device_init (char* cfg)
{
/* create scene */
g_scene = rtcNewScene(g_device);
rtcSetSceneFlags(g_scene,RTC_SCENE_FLAG_ROBUST);
/* add ground plane */
addGroundPlane(g_scene);
/* add cube */
addCube(g_scene);
/* commit changes to scene */
rtcCommitScene (g_scene);
}
/* task that renders a single screen tile */
Vec3fa renderPixelStandard(float x, float y, const ISPCCamera& camera, RayStats& stats)
{
RTCIntersectContext context;
rtcInitIntersectContext(&context);
/* initialize ray */
Ray ray(Vec3fa(camera.xfm.p), Vec3fa(normalize(x*camera.xfm.l.vx + y*camera.xfm.l.vy + camera.xfm.l.vz)), 0.0f, inf);
/* intersect ray with scene */
rtcIntersect1(g_scene,&context,RTCRayHit_(ray));
RayStats_addRay(stats);
/* shade pixels */
Vec3fa color = Vec3fa(0.0f);
if (ray.geomID != RTC_INVALID_GEOMETRY_ID)
{
Vec3fa diffuse = ray.geomID != 0 ? Vec3fa(0.9f,0.6f,0.5f) : Vec3fa(0.8f,0.0f,0.0f);
color = color + diffuse*0.5f;
Vec3fa lightDir = normalize(Vec3fa(-1,-1,-1));
Vec3fa Ng = normalize(ray.Ng);
#if ENABLE_SMOOTH_NORMALS
Vec3fa P = ray.org + ray.tfar*ray.dir;
if (ray.geomID > 0) {
Vec3fa dPdu,dPdv;
unsigned int geomID = ray.geomID; {
rtcInterpolate1(rtcGetGeometry(g_scene,geomID),ray.primID,ray.u,ray.v,RTC_BUFFER_TYPE_VERTEX,0,nullptr,&dPdu.x,&dPdv.x,3);
}
Ng = normalize(cross(dPdu,dPdv));
dPdu = dPdu + Ng*displacement_du(P,dPdu);
dPdv = dPdv + Ng*displacement_dv(P,dPdv);
Ng = normalize(cross(dPdu,dPdv));
}
#endif
/* initialize shadow ray */
Ray shadow(ray.org + ray.tfar*ray.dir, neg(lightDir), 0.001f, inf, 0.0f);
/* trace shadow ray */
rtcOccluded1(g_scene,&context,RTCRay_(shadow));
RayStats_addShadowRay(stats);
/* add light contribution */
if (shadow.tfar >= 0.0f)
color = color + diffuse*clamp(-(dot(lightDir,Ng)),0.0f,1.0f);
}
return color;
}
/* renders a single screen tile */
void renderTileStandard(int taskIndex,
int threadIndex,
int* pixels,
const unsigned int width,
const unsigned int height,
const float time,
const ISPCCamera& camera,
const int numTilesX,
const int numTilesY)
{
const unsigned int tileY = taskIndex / numTilesX;
const unsigned int tileX = taskIndex - tileY * numTilesX;
const unsigned int x0 = tileX * TILE_SIZE_X;
const unsigned int x1 = min(x0+TILE_SIZE_X,width);
const unsigned int y0 = tileY * TILE_SIZE_Y;
const unsigned int y1 = min(y0+TILE_SIZE_Y,height);
for (unsigned int y=y0; y<y1; y++) for (unsigned int x=x0; x<x1; x++)
{
/* calculate pixel color */
Vec3fa color = renderPixelStandard((float)x,(float)y,camera,g_stats[threadIndex]);
/* write color to framebuffer */
unsigned int r = (unsigned int) (255.0f * clamp(color.x,0.0f,1.0f));
unsigned int g = (unsigned int) (255.0f * clamp(color.y,0.0f,1.0f));
unsigned int b = (unsigned int) (255.0f * clamp(color.z,0.0f,1.0f));
pixels[y*width+x] = (b << 16) + (g << 8) + r;
}
}
/* task that renders a single screen tile */
void renderTileTask (int taskIndex, int threadIndex, int* pixels,
const unsigned int width,
const unsigned int height,
const float time,
const ISPCCamera& camera,
const int numTilesX,
const int numTilesY)
{
renderTileStandard(taskIndex,threadIndex,pixels,width,height,time,camera,numTilesX,numTilesY);
}
extern "C" void renderFrameStandard (int* pixels,
const unsigned int width,
const unsigned int height,
const float time,
const ISPCCamera& camera)
{
/* render image */
const int numTilesX = (width +TILE_SIZE_X-1)/TILE_SIZE_X;
const int numTilesY = (height+TILE_SIZE_Y-1)/TILE_SIZE_Y;
parallel_for(size_t(0),size_t(numTilesX*numTilesY),[&](const range<size_t>& range) {
const int threadIndex = (int)TaskScheduler::threadIndex();
for (size_t i=range.begin(); i<range.end(); i++)
renderTileTask((int)i,threadIndex,pixels,width,height,time,camera,numTilesX,numTilesY);
});
}
/* called by the C++ code to render */
extern "C" void device_render (int* pixels,
const unsigned int width,
const unsigned int height,
const float time,
const ISPCCamera& camera)
{
}
/* called by the C++ code for cleanup */
extern "C" void device_cleanup ()
{
rtcReleaseScene (g_scene); g_scene = nullptr;
}
} // namespace embree
| 30.851852 | 134 | 0.629379 | brechtvl |
a32950870227c57fad10390ecdb6f71190ec1a9d | 2,181 | cpp | C++ | position-sender/src/positionstreamtest.cpp | keithel/helloworld-capnproto-streamer | 946b14465af4ea7ee5bea4d7e521b38abd6f4d1e | [
"Apache-2.0"
] | 1 | 2017-11-03T08:13:04.000Z | 2017-11-03T08:13:04.000Z | position-sender/src/positionstreamtest.cpp | keithel/helloworld-capnproto-streamer | 946b14465af4ea7ee5bea4d7e521b38abd6f4d1e | [
"Apache-2.0"
] | null | null | null | position-sender/src/positionstreamtest.cpp | keithel/helloworld-capnproto-streamer | 946b14465af4ea7ee5bea4d7e521b38abd6f4d1e | [
"Apache-2.0"
] | null | null | null | #include "positionstreamtest.h"
#include <iostream>
#include <list>
#include <vector>
#include <capnp/message.h>
#include <capnp/serialize.h>
#include "position.capnp.h"
#include <sys/socket.h>
#include <unistd.h>
typedef ::kj::Array< ::capnp::word> WordArray;
using std::list;
using std::vector;
vector<unsigned char> generateAlternatingMessage();
list<vector<unsigned char> > s_positionBuffers;
PositionStreamTest::PositionStreamTest(struct sockaddr_in addr, int fd, uint32_t rate)
: mAddr(addr)
, mFd(fd)
, mRate(rate)
{
initPositions();
}
void PositionStreamTest::initPositions()
{
for (int i = 0; i < 12; i = i + 11) {
::capnp::MallocMessageBuilder message;
L3::Position::Builder position = message.initRoot<L3::Position>();
position.setHeading(44 + i); // booogus values
position.setElevation(66 + i);
position.setLatitude(88 + i);
position.setLongitude(0 + i);
position.setHeightAboveEllipsoid(22 + i);
position.setRoll(44 + i);
WordArray array;
array = ::capnp::messageToFlatArray(message);
s_positionBuffers.push_back(vector<unsigned char>(array.asBytes().begin(), array.asBytes().end()));
//s_positionBuffers.push_back(array.asPtr());
}
}
void PositionStreamTest::sendTestPositions()
{
// now just sendto() the destination
while (1) {
static int printCount = 0;
vector<unsigned char> messageBytes = generateAlternatingMessage();
if ((printCount++) % RATE == 0)
std::cout << "Sending " << messageBytes.size() << " bytes" << std::endl;
if (sendto(mFd, messageBytes.data(), messageBytes.size(), 0, (struct sockaddr*)&mAddr,
sizeof(mAddr)) < 0) {
perror("sendto");
exit(1);
}
usleep(1000000 / mRate); // was 16450
}
}
vector<unsigned char> generateAlternatingMessage()
{
static list<vector<unsigned char> >::iterator bufIter = s_positionBuffers.begin();
vector<unsigned char>& messageArray = *(bufIter++);
if (bufIter == s_positionBuffers.end())
bufIter = s_positionBuffers.begin();
return messageArray;
}
| 29.876712 | 107 | 0.643283 | keithel |
a32a93c1f3b358e718cbd8fa2561bd7bb5e8f1c7 | 8,328 | hpp | C++ | src/serac/physics/materials/solid_functional_material.hpp | btalamini/serac | f7a1628d05393a3f5efce4d1808a0c3fde9bf188 | [
"BSD-3-Clause"
] | null | null | null | src/serac/physics/materials/solid_functional_material.hpp | btalamini/serac | f7a1628d05393a3f5efce4d1808a0c3fde9bf188 | [
"BSD-3-Clause"
] | null | null | null | src/serac/physics/materials/solid_functional_material.hpp | btalamini/serac | f7a1628d05393a3f5efce4d1808a0c3fde9bf188 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2019-2022, Lawrence Livermore National Security, LLC and
// other Serac Project Developers. See the top-level LICENSE file for
// details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
/**
* @file solid_functional_material.hpp
*
* @brief The material and load types for the solid functional physics module
*/
#pragma once
#include "serac/numerics/functional/functional.hpp"
/// SolidFunctional helper data types
namespace serac::solid_util {
/**
* @brief Linear isotropic elasticity material model
*
* @tparam dim Spatial dimension of the mesh
*/
template <int dim>
class LinearIsotropicSolid {
public:
/**
* @brief Construct a new Linear Isotropic Elasticity object
*
* @param density Density of the material
* @param shear_modulus Shear modulus of the material
* @param bulk_modulus Bulk modulus of the material
*/
LinearIsotropicSolid(double density = 1.0, double shear_modulus = 1.0, double bulk_modulus = 1.0)
: density_(density), bulk_modulus_(bulk_modulus), shear_modulus_(shear_modulus)
{
SLIC_ERROR_ROOT_IF(shear_modulus_ < 0.0,
"Shear modulus must be positive in the linear isotropic elasticity material model.");
SLIC_ERROR_ROOT_IF(density_ < 0.0, "Density must be positive in the linear isotropic elasticity material model.");
SLIC_ERROR_ROOT_IF(bulk_modulus_ < 0.0,
"Bulk modulus must be positive in the linear isotropic elasticity material model.");
double K = bulk_modulus;
double G = shear_modulus;
double poisson_ratio = (3 * K - 2 * G) / (6 * K + 2 * G);
SLIC_ERROR_ROOT_IF(poisson_ratio < 0.0,
"Poisson ratio must be positive in the linear isotropic elasticity material model.");
}
/**
* @brief Function defining the Kirchoff stress (constitutive response)
*
* @tparam T type of the Kirchoff stress (i.e. second order tensor)
* @param du_dX displacement gradient with respect to the reference configuration (du_dX)
* @return The Kirchoff stress (det(deformation gradient) * Cauchy stress) for the constitutive model
*/
template <typename T>
SERAC_HOST_DEVICE T operator()(const T& du_dX) const
{
auto I = Identity<dim>();
auto lambda = bulk_modulus_ - (2.0 / dim) * shear_modulus_;
auto strain = 0.5 * (du_dX + transpose(du_dX));
auto stress = lambda * tr(strain) * I + 2.0 * shear_modulus_ * strain;
return stress;
}
/**
* @brief The density (mass per volume) of the material model
*
* @tparam dim The dimension of the problem
* @return The density
*/
SERAC_HOST_DEVICE double density(const tensor<double, dim>& /* x */) const { return density_; }
private:
/// Density
double density_;
/// Bulk modulus
double bulk_modulus_;
/// Shear modulus
double shear_modulus_;
};
/**
* @brief Neo-Hookean material model
*
* @tparam dim The spatial dimension of the mesh
*/
template <int dim>
class NeoHookeanSolid {
public:
/**
* @brief Construct a new Neo-Hookean object
*
* @param density Density of the material
* @param shear_modulus Shear modulus of the material
* @param bulk_modulus Bulk modulus of the material
*/
NeoHookeanSolid(double density = 1.0, double shear_modulus = 1.0, double bulk_modulus = 1.0)
: density_(density), bulk_modulus_(bulk_modulus), shear_modulus_(shear_modulus)
{
SLIC_ERROR_ROOT_IF(shear_modulus_ < 0.0, "Shear modulus must be positive in the neo-Hookean material model.");
SLIC_ERROR_ROOT_IF(density_ < 0.0, "Density must be positive in the neo-Hookean material model.");
SLIC_ERROR_ROOT_IF(bulk_modulus_ < 0.0, "Bulk modulus must be positive in the neo-Hookean material model.");
double K = bulk_modulus;
double G = shear_modulus;
double poisson_ratio = (3 * K - 2 * G) / (6 * K + 2 * G);
SLIC_ERROR_ROOT_IF(poisson_ratio < 0.0, "Poisson ratio must be positive in the neo-Hookean material model.");
}
/**
* @brief Function defining the Kirchoff stress (constitutive response)
*
* @tparam T type of the Kirchoff stress (i.e. second order tensor)
* @param du_dX displacement gradient with respect to the reference configuration (du_dX)
* @return The Kirchoff stress (det(deformation gradient) * Cauchy stress) for the constitutive model
*/
template <typename T>
SERAC_HOST_DEVICE T operator()(const T& du_dX) const
{
auto I = Identity<dim>();
auto lambda = bulk_modulus_ - (2.0 / dim) * shear_modulus_;
auto B_minus_I = du_dX * transpose(du_dX) + transpose(du_dX) + du_dX;
auto J = det(du_dX + I);
// TODO this resolve to the correct std implementation of log when J resolves to a pure double. It can
// be removed by either putting the dual implementation of the global namespace or implementing a pure
// double version there. More investigation into argument-dependent lookup is needed.
using std::log;
auto stress = lambda * log(J) * I + shear_modulus_ * B_minus_I;
return stress;
}
/**
* @brief The density (mass per volume) of the material model
*
* @tparam dim The dimension of the problem
* @return The density
*/
SERAC_HOST_DEVICE double density(const tensor<double, dim>& /* x */) const { return density_; }
private:
/// Density
double density_;
/// Bulk modulus in the stress free configuration
double bulk_modulus_;
/// Shear modulus in the stress free configuration
double shear_modulus_;
};
/// Constant body force model
template <int dim>
struct ConstantBodyForce {
/// The constant body force
tensor<double, dim> force_;
/**
* @brief Evaluation function for the constant body force model
*
* @tparam T1 type of the displacement
* @tparam T2 type of the displacement gradient
* @tparam dim The dimension of the problem
* @return The body force value
*/
template <typename T1, typename T2>
SERAC_HOST_DEVICE tensor<double, dim> operator()(const tensor<double, dim>& /* x */, const double /* t */,
const T1& /* u */, const T2& /* du_dX */) const
{
return force_;
}
};
/// Constant traction boundary condition model
template <int dim>
struct ConstantTraction {
/// The constant traction
tensor<double, dim> traction_;
/**
* @brief Evaluation function for the constant traction model
*
* @return The traction value
*/
SERAC_HOST_DEVICE tensor<double, dim> operator()(const tensor<double, dim>& /* x */,
const tensor<double, dim>& /* n */, const double /* t */) const
{
return traction_;
}
};
/// Function-based traction boundary condition model
template <int dim>
struct TractionFunction {
/// The traction function
std::function<tensor<double, dim>(const tensor<double, dim>&, const tensor<double, dim>&, const double t)>
traction_func_;
/**
* @brief Evaluation for the function-based traction model
*
* @param x The spatial coordinate
* @param n The normal vector
* @param t The current time
* @return The traction to apply
*/
SERAC_HOST_DEVICE tensor<double, dim> operator()(const tensor<double, dim>& x, const tensor<double, dim>& n,
const double t) const
{
return traction_func_(x, n, t);
}
};
/// Constant pressure model
struct ConstantPressure {
/// The constant pressure
double pressure_;
/**
* @brief Evaluation of the constant pressure model
*
* @tparam dim Spatial dimension
*/
template <int dim>
SERAC_HOST_DEVICE double operator()(const tensor<double, dim>& /* x */, const double /* t */) const
{
return pressure_;
}
};
/// Function-based pressure boundary condition
template <int dim>
struct PressureFunction {
/// The pressure function
std::function<double(const tensor<double, dim>&, const double)> pressure_func_;
/**
* @brief Evaluation for the function-based pressure model
*
* @param x The spatial coordinate
* @param t The current time
* @return The pressure to apply
*/
SERAC_HOST_DEVICE double operator()(const tensor<double, dim>& x, const double t) const
{
return pressure_func_(x, t);
}
};
} // namespace serac::solid_util
| 31.665399 | 118 | 0.673631 | btalamini |
a32cae8cbd99a6bce6127730c804f34b4a154d9b | 2,935 | cpp | C++ | src/Client/Engine/ParticleHandler.cpp | fqhd/BuildBattle | f85ec857aa232313f4678514aa317af73c37de10 | [
"MIT"
] | 10 | 2021-08-17T20:55:52.000Z | 2022-03-28T00:45:14.000Z | src/Client/Engine/ParticleHandler.cpp | fqhd/BuildBattle | f85ec857aa232313f4678514aa317af73c37de10 | [
"MIT"
] | null | null | null | src/Client/Engine/ParticleHandler.cpp | fqhd/BuildBattle | f85ec857aa232313f4678514aa317af73c37de10 | [
"MIT"
] | 2 | 2021-07-05T18:49:56.000Z | 2021-07-10T22:03:17.000Z | #include "ParticleHandler.hpp"
#include "Converter.hpp"
#include <cstring>
const float GRAVITY = 38.0f;
void ParticleHandler::init(TextureArray* _array, BlockTextureHandler* _textureHandler){
m_blockTextureHandler = _textureHandler;
m_textureArray = _array;
m_quad.init();
m_shader.load("res/shaders/particle_vertex_shader.glsl", "res/shaders/particle_fragment_shader.glsl");
m_particles = new Particle[MAX_PARTICLES];
}
void ParticleHandler::update(float deltaTime){
for(unsigned int i = 0; i < m_currNumParticles; i++){
m_particles[i].velocity.y -= GRAVITY * deltaTime;
m_particles[i].position += m_particles[i].velocity * deltaTime;
m_particles[i].lifeLength -= deltaTime;
if(m_particles[i].lifeLength <= 0.0f){
memcpy(&m_particles[i], &m_particles[m_currNumParticles - 1], sizeof(Particle));
m_currNumParticles--;
}
}
}
void ParticleHandler::render(Camera& camera){
// Gathering particle data and sending it to GPU
m_particleStructs.resize(0);
for(unsigned int i = 0; i < m_currNumParticles; i++){
m_particleStructs.emplace_back(m_particles[i].position, m_particles[i].textureIndex, m_particles[i].size);
}
m_quad.pushData(m_particleStructs.data(), m_particleStructs.size() * sizeof(ParticleInstance));
// Rendering particles
m_shader.bind();
// Since we are rendering the particles as GL_POINTS, this uniform variable is necessary
// in order to scale the particles based on the width of the screen. Otherwise the particles
// will have a fixed size regardless of screen size.
m_shader.loadUniform("screenWidth", InputManager::getWindowSize().x);
m_shader.loadUniform("projection", camera.getProjectionMatrix());
m_shader.loadUniform("view", camera.getViewMatrix());
m_textureArray->bind();
glDisable(GL_CULL_FACE);
m_quad.render(m_particleStructs.size());
glEnable(GL_CULL_FACE);
m_textureArray->unbind();
m_shader.unbind();
}
// unsigned int getRandom(uint8_t a, uint8_t b, uint8_t c){
// int r = rand()%3;
// if(r == 2){
// return a;
// }else if(r == 1){
// return b;
// }
// return c;
// }
void ParticleHandler::placeParticlesAroundBlock(int x, int y, int z, uint8_t _blockID){
if(m_currNumParticles == MAX_PARTICLES) return;
BlockTexture b = m_blockTextureHandler->getTextureFromBlockID(_blockID);
for(unsigned int i = 0; i < PARTICLES_PER_DROP; i++){
math::vec3 pos(x + math::random(), y + math::random(), z + math::random());
math::vec3 direction = pos - (math::vec3(x, y, z) + math::vec3(0.5f, 0.0f, 0.5f));
math::vec3 velocity = math::vec3(direction.x * 3.0f, direction.y * 7.0f, direction.z * 3.0f);
//math::vec3 velocity((math::random() - 0.5f) * 3.0f, math::random() * 5, (math::random() - 0.5f) * 3.0f);
m_particles[m_currNumParticles + i] = Particle(pos, velocity, 1.0f, b.side, 50.0f + math::random() * 50.0f);
}
m_currNumParticles += PARTICLES_PER_DROP;
}
void ParticleHandler::destroy(){
m_quad.destroy();
m_shader.destroy();
}
| 34.940476 | 110 | 0.718569 | fqhd |
a32d4b4c9b42b63f5f2e34211f1b019ad161c476 | 8,790 | cpp | C++ | ProjectMajestic/Main.cpp | Edgaru089/ProjectMajestic | 16cda6f86fd5ad02baedc9481609d6140cdda62a | [
"MIT"
] | 1 | 2018-08-29T06:36:23.000Z | 2018-08-29T06:36:23.000Z | ProjectMajestic/Main.cpp | Edgaru089/ProjectMajestic | 16cda6f86fd5ad02baedc9481609d6140cdda62a | [
"MIT"
] | null | null | null | ProjectMajestic/Main.cpp | Edgaru089/ProjectMajestic | 16cda6f86fd5ad02baedc9481609d6140cdda62a | [
"MIT"
] | null | null | null |
#pragma warning(disable:4244)
#pragma warning(disable:4018)
#define NOMINMAX
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <thread>
#include <SFML/Graphics.hpp>
#include <SFML/Network.hpp>
#include "Main.hpp"
#include "LogSystem.hpp"
#include "App.hpp"
using namespace std;
void threadRendering() {
static Clock imguiDeltaClock;
Clock renderMetricsClock;
ImGui::SFML::Update(win, imguiDeltaClock.restart());
win.setActive(true);
renderClock.restart();
while (isReady) {
if (!win.isOpen()) {
sleep(milliseconds(5));
continue;
}
renderLock.lock();
renderMetricsClock.restart();
win.setActive(true);
win.clear();
logicDataLock.lock();
app->onRender(win);
appRenderTime = renderMetricsClock.restart();
app->runImGui();
runImGuiTime = renderMetricsClock.restart();
win.setView(View(FloatRect(0, 0, win.getSize().x, win.getSize().y)));
ImGui::SFML::Render(win);
imGuiRenderTime = renderMetricsClock.restart();
ImGui::SFML::Update(win, imguiDeltaClock.restart());
imGuiUpdateTime = renderMetricsClock.restart();
renderThreadTickTime = appRenderTime + runImGuiTime + imGuiRenderTime + imGuiUpdateTime;
logicDataLock.unlock();
frameCounter++;
win.display();
renderLock.unlock();
renderTime = renderClock.restart();
if (frameCounterClock.getElapsedTime() >= seconds(1.0f)) {
frameCounterClock.restart();
framePerSecond = frameCounter;
frameCounter = 0;
win.setTitle(StringParser::toStringF("%s | Async | TPS: %d, EPS: %d, FPS: %d", projectCode.c_str(), logicTickPerSecond, eventTickPerSecond, framePerSecond));
}
}
}
void threadLogicUpdate(int ticksPerSecond) {
Time tickTime;
if (ticksPerSecond != 0)
tickTime = seconds(1.0f / ticksPerSecond);
else
tickTime = Time::Zero;
Clock logicCycleClock;
Clock logicMetricsClock;
desktopUpdate.restart();
while (isReady && win.isOpen()) {
logicDataLock.lock();
logicMetricsClock.restart();
app->updateLogic(win);
logicThreadTickTime = logicMetricsClock.restart();
logicDataLock.unlock();
Time t;
if (logicTickCounterClock.getElapsedTime() > seconds(1.0f)) {
logicTickCounterClock.restart();
logicTickPerSecond = logicTickCounter;
logicTickCounter = 0;
}
logicTickCounter++;
if ((t = logicCycleClock.getElapsedTime()) < (tickTime == Time::Zero ? renderTime : tickTime))
sleep((tickTime == Time::Zero ? renderTime : tickTime) - t);
logicCycleClock.restart();
}
}
void initRenderWindow(Uint32 style = sf::Style::Default, bool useVSync = true, int framePerSecond = 120) {
sf::ContextSettings settings;
VideoMode desk = VideoMode::getDesktopMode();
settings.antialiasingLevel = 0;
win.create(style == sf::Style::Fullscreen ? desk : VideoMode(desk.width * 5 / 6, desk.height * 5 / 6), projectCode, style, settings);
win.clear();
win.display();
if (useVSync)
win.setVerticalSyncEnabled(true);
else
win.setFramerateLimit(framePerSecond);
win.setVisible(true);
}
#ifdef SFML_SYSTEM_WINDOWS
#include <Windows.h>
//Platform-Depedent: Windows
BOOL systemExitEventHandler(DWORD dwCtrlType) {
if (dwCtrlType == CTRL_C_EVENT)
mlog << Log::Error << "[Main/EVENT] Control-C Console Exit" << dlog << Log::Info;
else if (dwCtrlType == CTRL_BREAK_EVENT)
mlog << Log::Error << "[Main/EVENT] Control-Break Console Exit" << dlog << Log::Info;
else if (dwCtrlType == CTRL_CLOSE_EVENT)
mlog << Log::Error << "[Main/EVENT] Control-Close Console Exit" << dlog << Log::Info;
else if (dwCtrlType == CTRL_LOGOFF_EVENT)
mlog << Log::Error << "[Main/EVENT] System-Logoff Exit" << dlog << Log::Info;
else if (dwCtrlType == CTRL_SHUTDOWN_EVENT)
mlog << Log::Error << "[Main/EVENT] System-Shutdown Exit" << dlog << Log::Info;
else
return false;
logicDataLock.lock();
isReady = false;
logicDataLock.unlock();
waitUntilEqual(isProgramRunning, false);
return true;
}
#endif // SFML_SYSTEM_WINDOWS
int main(int argc, char* argv[]) {
isProgramRunning = true;
cout << projectCode << ' ' << projectSuffix << "\n Stage " << releaseStage << endl;
cout << "Version " << majorVersion << "." << minorVersion << "." << patchVersion << " " << releaseStage << ", Complie Time: " << compileTime << endl << endl;
//system("PAUSE>nul");
srand(time(NULL));
#ifdef OUTPUT_LOG_TO_STDOUT
dlog.addOutputStream(clog);
#endif
#ifdef OUTPUT_LOG_TO_FILE
dlog.addOutputStream(logout);
#endif
dlog.ignore(LOG_IGNORE_LEVEL);
Clock loadTimeClock;
mlog << "[Main] Pre-Initalaizing..." << dlog;
bool isFullscreen = false;
#ifdef SFML_SYSTEM_WINDOWS
SetConsoleCtrlHandler((PHANDLER_ROUTINE)systemExitEventHandler, true);
#endif // SFML_SYSTEM_WINDOWS
mlog << "[Main] Initalaizing ImGui..." << dlog;
ImGui::SFML::Init();
ImGui::StyleColorsClassic();
ImGuiStyle& style = ImGui::GetStyle();
style.FrameBorderSize = 1.0f;
style.ScrollbarRounding = 2.0;
style.WindowRounding = 2.0;
mlog << "[Main] Initalaizing App..." << dlog;
app = new App();
app->initalaizePreWindow();
mlog << "[Main] Done in " << loadTimeClock.restart().asMilliseconds() << "ms." << dlog;
mlog << "[Main] Bringing up the window..." << dlog;
initRenderWindow();
mlog << Log::Info << "[Main] Post-Initalaizing..." << dlog;
isReady = true;
app->initalaizePostWindow(win);
mlog << "[Main] Done in " << loadTimeClock.restart().asMilliseconds() << "ms." << dlog;
mlog << "[Main] Starting App..." << dlog;
app->start(win);
mlog << "[Main] App Started in " << loadTimeClock.restart().asMilliseconds() << "ms." << dlog;
#ifdef USE_ASYNC_RENDERING
mlog << Log::Warning << "Async Rendering/Logic Update Enabled. Unstable. Aware." << dlog << Log::Info;
win.setActive(false);
thread render(threadRendering);
thread logic(threadLogicUpdate, 90);
#else
Clock imguiDeltaClock;
#endif
//Time eventTickTime = seconds(1.0f / 60);
Time eventTickTime = microseconds(11111);
Clock eventCycleClock;
while (win.isOpen() && isReady) {
Event event;
while (win.pollEvent(event)) {
logicDataLock.lock();
ImGui::SFML::ProcessEvent(event);
if ((ImGui::GetIO().WantCaptureKeyboard &&
(event.type == Event::KeyPressed || event.type == Event::KeyReleased || event.type == Event::TextEntered)) ||
(ImGui::GetIO().WantCaptureMouse && (event.type == Event::MouseButtonPressed || event.type ==
Event::MouseButtonReleased || event.type == Event::MouseMoved))) {
logicDataLock.unlock();
continue;
}
app->handleEvent(win, event);
logicDataLock.unlock();
if (event.type == Event::Closed) {
logicDataLock.lock();
isReady = false;
win.close();
logicDataLock.unlock();
break;
}
else if (event.type == Event::Resized) {
win.setView(View(FloatRect(0, 0, event.size.width, event.size.height)));
}
else if (event.type == Event::KeyPressed) {
if (event.key.code == Keyboard::F11)
if (!isFullscreen) {
#ifdef USE_ASYNC_RENDERING
renderLock.lock();
logicDataLock.lock();
#endif
initRenderWindow(sf::Style::Fullscreen);
isFullscreen = true;
app->onViewportChange(win);
#ifdef USE_ASYNC_RENDERING
win.setActive(false);
logicDataLock.unlock();
renderLock.unlock();
#endif
}
else {
#ifdef USE_ASYNC_RENDERING
renderLock.lock();
logicDataLock.lock();
#endif
initRenderWindow();
isFullscreen = false;
app->onViewportChange(win);
#ifdef USE_ASYNC_RENDERING
win.setActive(false);
logicDataLock.unlock();
renderLock.unlock();
#endif
}
}
}
#ifndef USE_ASYNC_RENDERING
win.clear();
ImGui::SFML::Update(win, imguiDeltaClock.restart());
app->updateLogic(win);
app->onRender(win);
app->runImGui();
win.setView(View(FloatRect(0, 0, win.getSize().x, win.getSize().y)));
ImGui::SFML::Render(win);
win.display();
#endif
if (eventTickCounterClock.getElapsedTime() >= seconds(1.0f)) {
eventTickCounterClock.restart();
eventTickPerSecond = eventTickCounter;
eventTickCounter = 0;
#ifndef USE_ASYNC_RENDERING
win.setTitle(StringParser::toStringF("%s | Mono-Thread | FPS: %d", projectCode.c_str(), eventTickPerSecond));
#endif
}
eventTickCounter++;
#ifdef USE_ASYNC_RENDERING
Time t;
if ((t = eventCycleClock.getElapsedTime()) < (eventTickTime == Time::Zero ? renderTime : eventTickTime))
sleep((eventTickTime == Time::Zero ? renderTime : eventTickTime) - t);
#endif
eventCycleClock.restart();
}
win.close();
mlog << "Shutdown In Progress..." << dlog;
app->onStop();
#ifdef USE_ASYNC_RENDERING
mlog << "[*] Joining Render Thread..." << dlog;
render.join();
mlog << "[*] Joining Logic Update Thread..." << dlog;
logic.join();
mlog << "Complete." << dlog;
#endif
mlog << "Byebye!" << dlog;
sleep(milliseconds(500));
isProgramRunning = false;
return EXIT_SUCCESS;
}
#include "ImplList.hpp"
| 27.46875 | 160 | 0.686348 | Edgaru089 |
a32e4ee072614de748464cc290a5ed7f3801b5e4 | 329 | cpp | C++ | src/engine/camera/FPSCamera.cpp | Armanimani/Game-Engine | 8087cd999f7264488d24a5dc5571b659347a49dd | [
"MIT"
] | null | null | null | src/engine/camera/FPSCamera.cpp | Armanimani/Game-Engine | 8087cd999f7264488d24a5dc5571b659347a49dd | [
"MIT"
] | 1 | 2017-04-05T01:40:02.000Z | 2017-04-05T07:36:55.000Z | src/engine/camera/FPSCamera.cpp | Armanimani/Game-Engine | 8087cd999f7264488d24a5dc5571b659347a49dd | [
"MIT"
] | null | null | null | #include "FPSCamera.h"
#include <iostream>
const GLfloat MAX = 89.99f;
const GLfloat MIN = -89.99f;
void FPSCamera::rotateRight(const GLfloat & value)
{
GLfloat v = value;
if (theta + value >= MAX) v = MAX - theta;
else if (theta + value <= MIN) v = MIN - theta;
else v = value;
theta += v;
FreeCamera::rotateRight(v);
} | 20.5625 | 50 | 0.656535 | Armanimani |
a32ea93e9fa2c8593e4fbc37c285ce632676b08e | 11,711 | hpp | C++ | ct_core/include/ct/external/cppad/local/erf_op.hpp | vklemm/control-toolbox | f5f8cf9331c0aecd721ff6296154e2a55c72f679 | [
"BSD-2-Clause"
] | 1 | 2019-12-01T14:45:18.000Z | 2019-12-01T14:45:18.000Z | ct_core/include/external/cppad/local/erf_op.hpp | ADVRHumanoids/ct | 774ad978c032fda0ef3c2eed0dc3f25f829df7f8 | [
"Apache-2.0"
] | null | null | null | ct_core/include/external/cppad/local/erf_op.hpp | ADVRHumanoids/ct | 774ad978c032fda0ef3c2eed0dc3f25f829df7f8 | [
"Apache-2.0"
] | 1 | 2021-04-01T20:05:31.000Z | 2021-04-01T20:05:31.000Z | // $Id$
# ifndef CPPAD_ERF_OP_HPP
# define CPPAD_ERF_OP_HPP
# if CPPAD_USE_CPLUSPLUS_2011
/* --------------------------------------------------------------------------
CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-15 Bradley M. Bell
CppAD is distributed under multiple licenses. This distribution is under
the terms of the
Eclipse Public License Version 1.0.
A copy of this license is included in the COPYING file of this distribution.
Please visit http://www.coin-or.org/CppAD/ for information on other licenses.
-------------------------------------------------------------------------- */
# include <cppad/local/mul_op.hpp>
# include <cppad/local/sub_op.hpp>
# include <cppad/local/exp_op.hpp>
namespace CppAD { // BEGIN_CPPAD_NAMESPACE
/*!
\file erf_op.hpp
Forward and reverse mode calculations for z = erf(x).
*/
/*!
Forward mode Taylor coefficient for result of op = ErfOp.
The C++ source code corresponding to this operation is
\verbatim
z = erf(x)
\endverbatim
\par CPPAD_HAS_ERROF_FUNCTION
This macro is either zero or one and forward_erf_op is only defined
when it is one.
\tparam Base
base type for the operator; i.e., this operation was recorded
using AD< \a Base > and computations by this routine are done using type
\a Base.
\param p
lowest order of the Taylor coefficients that we are computing.
\param q
highest order of the Taylor coefficients that we are computing.
\param i_z
variable index corresponding to the last (primary) result for this operation;
i.e. the row index in \a taylor corresponding to z.
The auxillary result is called y has index \a i_z - 1.
\param arg
arg[0]: is the variable index corresponding to x.
\n
arg[1]: is the parameter index corresponding to the value zero.
\n
\arg[2]: is the parameter index correspodning to the value 2 / sqrt(pi).
\param parameter
parameter[ arg[1] ] is the value zero,
and parameter[ arg[2] ] is the value 2 / sqrt(pi).
\param cap_order
maximum number of orders that will fit in the \c taylor array.
\param taylor
\b Input:
taylor [ arg[0] * cap_order + k ]
for k = 0 , ... , q,
is the k-th order Taylor coefficient corresponding to x.
\n
\b Input:
taylor [ i_z * cap_order + k ]
for k = 0 , ... , p - 1,
is the k-th order Taylor coefficient corresponding to z.
\n
\b Input:
taylor [ ( i_z - j) * cap_order + k ]
for k = 0 , ... , p-1,
and j = 0 , ... , 4,
is the k-th order Taylor coefficient corresponding to the j-th result for z.
\n
\b Output:
taylor [ (i_z-j) * cap_order + k ],
for k = p , ... , q,
and j = 0 , ... , 4,
is the k-th order Taylor coefficient corresponding to the j-th result for z.
\par Checked Assertions
\li NumArg(op) == 3
\li NumRes(op) == 5
\li q < cap_order
\li p <= q
*/
template <class Base>
inline void forward_erf_op(
size_t p ,
size_t q ,
size_t i_z ,
const addr_t* arg ,
const Base* parameter ,
size_t cap_order ,
Base* taylor )
{
// check assumptions
CPPAD_ASSERT_UNKNOWN( NumArg(ErfOp) == 3 );
CPPAD_ASSERT_UNKNOWN( NumRes(ErfOp) == 5 );
CPPAD_ASSERT_UNKNOWN( q < cap_order );
CPPAD_ASSERT_UNKNOWN( p <= q );
// array used to pass parameter values for sub-operations
addr_t addr[2];
// convert from final result to first result
i_z -= 4; // 4 = NumRes(ErfOp) - 1;
// z_0 = x * x
addr[0] = arg[0]; // x
addr[1] = arg[0]; // x
forward_mulvv_op(p, q, i_z+0, addr, parameter, cap_order, taylor);
// z_1 = - x * x
addr[0] = arg[1]; // zero
addr[1] = i_z; // z_0
forward_subpv_op(p, q, i_z+1, addr, parameter, cap_order, taylor);
// z_2 = exp( - x * x )
forward_exp_op(p, q, i_z+2, i_z+1, cap_order, taylor);
// z_3 = (2 / sqrt(pi)) * exp( - x * x )
addr[0] = arg[2]; // 2 / sqrt(pi)
addr[1] = i_z + 2; // z_2
forward_mulpv_op(p, q, i_z+3, addr, parameter, cap_order, taylor);
// pointers to taylor coefficients for x , z_3, and z_4
Base* x = taylor + arg[0] * cap_order;
Base* z_3 = taylor + (i_z+3) * cap_order;
Base* z_4 = taylor + (i_z+4) * cap_order;
// calculte z_4 coefficients
if( p == 0 )
{ // zero order Taylor coefficient for z_4
z_4[0] = erf(x[0]);
p++;
}
for(size_t j = p; j <= q; j++)
{ Base base_j = static_cast<Base>(j);
z_4[j] = static_cast<Base>(0);
for(size_t k = 1; k <= j; k++)
z_4[j] += (Base(k) / base_j) * x[k] * z_3[j-k];
}
}
/*!
Zero order Forward mode Taylor coefficient for result of op = ErfOp.
The C++ source code corresponding to this operation is
\verbatim
z = erf(x)
\endverbatim
\par CPPAD_HAS_ERROF_FUNCTION
This macro is either zero or one and forward_erf_op is only defined
when it is one.
\tparam Base
base type for the operator; i.e., this operation was recorded
using AD< \a Base > and computations by this routine are done using type
\a Base.
\param i_z
variable index corresponding to the last (primary) result for this operation;
i.e. the row index in \a taylor corresponding to z.
The auxillary result is called y has index \a i_z - 1.
\param arg
arg[0]: is the variable index corresponding to x.
\n
arg[1]: is the parameter index corresponding to the value zero.
\n
\arg[2]: is the parameter index correspodning to the value 2 / sqrt(pi).
\param parameter
parameter[ arg[1] ] is the value zero,
and parameter[ arg[2] ] is the value 2 / sqrt(pi).
\param cap_order
maximum number of orders that will fit in the \c taylor array.
\param taylor
\b Input:
taylor [ arg[0] * cap_order + 0 ]
is the zero order Taylor coefficient corresponding to x.
\n
\b Input:
taylor [ i_z * cap_order + 0 ]
is the zero order Taylor coefficient corresponding to z.
\n
\b Output:
taylor [ (i_z-j) * cap_order + 0 ],
for j = 0 , ... , 4,
is the zero order Taylor coefficient for j-th result corresponding to z.
\par Checked Assertions
\li NumArg(op) == 3
\li NumRes(op) == 5
\li q < cap_order
\li p <= q
*/
template <class Base>
inline void forward_erf_op_0(
size_t i_z ,
const addr_t* arg ,
const Base* parameter ,
size_t cap_order ,
Base* taylor )
{
// check assumptions
CPPAD_ASSERT_UNKNOWN( NumArg(ErfOp) == 3 );
CPPAD_ASSERT_UNKNOWN( NumRes(ErfOp) == 5 );
CPPAD_ASSERT_UNKNOWN( 0 < cap_order );
// array used to pass parameter values for sub-operations
addr_t addr[2];
// convert from final result to first result
i_z -= 4; // 4 = NumRes(ErfOp) - 1;
// z_0 = x * x
addr[0] = arg[0]; // x
addr[1] = arg[0]; // x
forward_mulvv_op_0(i_z+0, addr, parameter, cap_order, taylor);
// z_1 = - x * x
addr[0] = arg[1]; // zero
addr[1] = i_z; // z_0
forward_subpv_op_0(i_z+1, addr, parameter, cap_order, taylor);
// z_2 = exp( - x * x )
forward_exp_op_0(i_z+2, i_z+1, cap_order, taylor);
// z_3 = (2 / sqrt(pi)) * exp( - x * x )
addr[0] = arg[2]; // 2 / sqrt(pi)
addr[1] = i_z + 2; // z_2
forward_mulpv_op_0(i_z+3, addr, parameter, cap_order, taylor);
// zero order Taylor coefficient for z_4
Base* x = taylor + arg[0] * cap_order;
Base* z_4 = taylor + (i_z + 4) * cap_order;
z_4[0] = erf(x[0]);
}
/*!
Compute reverse mode partial derivatives for result of op = ErfOp.
The C++ source code corresponding to this operation is
\verbatim
z = erf(x)
\endverbatim
\par CPPAD_HAS_ERROF_FUNCTION
This macro is either zero or one and reverse_tan_op is only defined
when it is one.
\tparam Base
base type for the operator; i.e., this operation was recorded
using AD< \a Base > and computations by this routine are done using type
\a Base.
\param d
highest order Taylor of the Taylor coefficients that we are computing
the partial derivatives with respect to.
\param i_z
variable index corresponding to the last (primary) result for this operation;
i.e. the row index in \a taylor corresponding to z.
The auxillary result is called y has index \a i_z - 1.
\param arg
arg[0]: is the variable index corresponding to x.
\n
arg[1]: is the parameter index corresponding to the value zero.
\n
\arg[2]: is the parameter index correspodning to the value 2 / sqrt(pi).
\param parameter
parameter[ arg[1] ] is the value zero,
and parameter[ arg[2] ] is the value 2 / sqrt(pi).
\param cap_order
maximum number of orders that will fit in the \c taylor array.
\param taylor
\b Input:
taylor [ arg[0] * cap_order + k ]
for k = 0 , ... , d,
is the k-th order Taylor coefficient corresponding to x.
\n
taylor [ (i_z - j) * cap_order + k ]
for k = 0 , ... , d,
and for j = 0 , ... , 4,
is the k-th order Taylor coefficient corresponding to the j-th result
for this operation.
\param nc_partial
number of columns in the matrix containing all the partial derivatives
\param partial
\b Input:
partial [ arg[0] * nc_partial + k ]
for k = 0 , ... , d,
is the partial derivative of G( z , x , w , u , ... ) with respect to
the k-th order Taylor coefficient for x.
\n
\b Input:
partial [ (i_z - j) * nc_partial + k ]
for k = 0 , ... , d,
and for j = 0 , ... , 4,
is the partial derivative of G( z , x , w , u , ... ) with respect to
the k-th order Taylor coefficient for the j-th result of this operation.
\n
\b Output:
partial [ arg[0] * nc_partial + k ]
for k = 0 , ... , d,
is the partial derivative of H( x , w , u , ... ) with respect to
the k-th order Taylor coefficient for x.
\n
\b Output:
partial [ (i_z-j) * nc_partial + k ]
for k = 0 , ... , d,
and for j = 0 , ... , 4,
may be used as work space; i.e., may change in an unspecified manner.
\par Checked Assertions
\li NumArg(op) == 3
\li NumRes(op) == 5
\li q < cap_order
\li p <= q
*/
template <class Base>
inline void reverse_erf_op(
size_t d ,
size_t i_z ,
const addr_t* arg ,
const Base* parameter ,
size_t cap_order ,
const Base* taylor ,
size_t nc_partial ,
Base* partial )
{
// check assumptions
CPPAD_ASSERT_UNKNOWN( NumArg(ErfOp) == 3 );
CPPAD_ASSERT_UNKNOWN( NumRes(ErfOp) == 5 );
CPPAD_ASSERT_UNKNOWN( d < cap_order );
// array used to pass parameter values for sub-operations
addr_t addr[2];
// If pz is zero, make sure this operation has no effect
// (zero times infinity or nan would be non-zero).
Base* pz = partial + i_z * nc_partial;
bool skip(true);
for(size_t i_d = 0; i_d <= d; i_d++)
skip &= IdenticalZero(pz[i_d]);
if( skip )
return;
// convert from final result to first result
i_z -= 4; // 4 = NumRes(ErfOp) - 1;
// Taylor coefficients and partials corresponding to x
const Base* x = taylor + arg[0] * cap_order;
Base* px = partial + arg[0] * nc_partial;
// Taylor coefficients and partials corresponding to z_3
const Base* z_3 = taylor + (i_z+3) * cap_order;
Base* pz_3 = partial + (i_z+3) * nc_partial;
// Taylor coefficients and partials corresponding to z_4
Base* pz_4 = partial + (i_z+4) * nc_partial;
// Reverse z_4
size_t j = d;
while(j)
{ pz_4[j] /= Base(j);
for(size_t k = 1; k <= j; k++)
{ px[k] += azmul(pz_4[j], z_3[j-k]) * Base(k);
pz_3[j-k] += azmul(pz_4[j], x[k]) * Base(k);
}
j--;
}
px[0] += azmul(pz_4[0], z_3[0]);
// z_3 = (2 / sqrt(pi)) * exp( - x * x )
addr[0] = arg[2]; // 2 / sqrt(pi)
addr[1] = i_z + 2; // z_2
reverse_mulpv_op(
d, i_z+3, addr, parameter, cap_order, taylor, nc_partial, partial
);
// z_2 = exp( - x * x )
reverse_exp_op(
d, i_z+2, i_z+1, cap_order, taylor, nc_partial, partial
);
// z_1 = - x * x
addr[0] = arg[1]; // zero
addr[1] = i_z; // z_0
reverse_subpv_op(
d, i_z+1, addr, parameter, cap_order, taylor, nc_partial, partial
);
// z_0 = x * x
addr[0] = arg[0]; // x
addr[1] = arg[0]; // x
reverse_mulvv_op(
d, i_z+0, addr, parameter, cap_order, taylor, nc_partial, partial
);
}
} // END_CPPAD_NAMESPACE
# endif // CPPAD_USE_CPLUSPLUS_2011
# endif // CPPAD_ERF_OP_INCLUDED
| 27.234884 | 77 | 0.649389 | vklemm |
cd144906d5fc8f5fabf2730a824c2fffd7a97435 | 730 | cpp | C++ | Problems/Timus/1581_Teamwork/src/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | null | null | null | Problems/Timus/1581_Teamwork/src/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | 1 | 2019-05-09T19:17:00.000Z | 2019-05-09T19:17:00.000Z | Problems/Timus/1581_Teamwork/src/main.cpp | grand87/timus | 8edcae276ab74b68fff18da3722460f492534a8a | [
"MIT"
] | null | null | null | /*
* @author v.sharayenko (grand87@yandex.ru)
*/
#pragma comment(linker, "/STACK:16777216")
#include <stdio.h>
//#define ONLINE_JUDGE
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "rt", stdin);
freopen("output.txt", "wt", stdout);
#endif
size_t length = 0;
scanf("%d", &length);
size_t value = 0;
size_t count = 1;
scanf("%d", &value);
for(int i = 1; i < length; ++i)
{
size_t nextValue = 0;
scanf("%d", &nextValue);
if(nextValue == value)
count++;
else
{
printf("%d %d ", count, value);
value = nextValue;
count = 1;
}
}
printf("%d %d", count, value);
return 0;
}
| 16.590909 | 43 | 0.50137 | grand87 |
cd164ebcbb11830a5d5df5c6c546ef0cfa6b1ac6 | 594 | cpp | C++ | aleatorios.cpp | JCSUCoder/introduccion-programacion-puj | 2c1149a18946eb915c593b84282a352e87067cc7 | [
"MIT"
] | 1 | 2021-02-16T16:40:07.000Z | 2021-02-16T16:40:07.000Z | aleatorios.cpp | JCSUCoder/introduccion-programacion-puj | 2c1149a18946eb915c593b84282a352e87067cc7 | [
"MIT"
] | null | null | null | aleatorios.cpp | JCSUCoder/introduccion-programacion-puj | 2c1149a18946eb915c593b84282a352e87067cc7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdlib>
#include <time.h>
// https://www.cplusplus.com/reference/cstdlib/rand
/**
* En los computadores no existe una forma de escojer algún número aleatorio,
* por lo que se usna números pseudoaleatorio
**/
using namespace std;
int main()
{
cout << "Inicializando con semilla aleatoria ..." << endl;
srand(time(NULL));
int v1 = rand() % 100; // v1 in the range 0 to 99
int v2 = rand() % 100 + 1; // v2 in the range 1 to 100
int v3 = rand() % 30 + 1985; // v3 in the range 1985-2014
cout << v1 << '\t' << v2 << '\t' << v3 << endl;
return 0;
} | 22.846154 | 78 | 0.62963 | JCSUCoder |
cd1f186f58e4b3913dd3399f8b90fa9e34ec8775 | 9,561 | hh | C++ | src/base/vnc/vncserver.hh | lokamdheeraj/gem5_comprehensive | bebf8e2ae8fef57284b56985c1f7d353a133011f | [
"BSD-3-Clause"
] | 31 | 2015-12-15T19:14:10.000Z | 2021-12-31T17:40:21.000Z | src/base/vnc/vncserver.hh | lokamdheeraj/gem5_comprehensive | bebf8e2ae8fef57284b56985c1f7d353a133011f | [
"BSD-3-Clause"
] | 5 | 2015-12-04T08:06:47.000Z | 2020-08-09T21:49:46.000Z | src/base/vnc/vncserver.hh | lokamdheeraj/gem5_comprehensive | bebf8e2ae8fef57284b56985c1f7d353a133011f | [
"BSD-3-Clause"
] | 21 | 2015-11-05T08:25:45.000Z | 2021-06-19T02:24:50.000Z | /*
* Copyright (c) 2010 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* 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 holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
* William Wang
*/
/** @file
* Declaration of a VNC server
*/
#ifndef __BASE_VNC_VNC_SERVER_HH__
#define __BASE_VNC_VNC_SERVER_HH__
#include <iostream>
#include "base/vnc/convert.hh"
#include "base/vnc/vncinput.hh"
#include "base/bitmap.hh"
#include "base/circlebuf.hh"
#include "base/pollevent.hh"
#include "base/socket.hh"
#include "params/VncServer.hh"
#include "sim/sim_object.hh"
/** @file
* Declaration of a VNC server
*/
class VncServer : public VncInput
{
public:
/**
* \defgroup VncConstants A set of constants and structs from the VNC spec
* @{
*/
/** Authentication modes */
const static uint32_t AuthInvalid = 0;
const static uint32_t AuthNone = 1;
/** Error conditions */
const static uint32_t VncOK = 0;
/** Server -> Client message IDs */
enum ServerMessages {
ServerFrameBufferUpdate = 0,
ServerSetColorMapEntries = 1,
ServerBell = 2,
ServerCutText = 3
};
/** Encoding types */
enum EncodingTypes {
EncodingRaw = 0,
EncodingCopyRect = 1,
EncodingHextile = 5,
EncodingDesktopSize = -223
};
/** keyboard/mouse support */
enum MouseEvents {
MouseLeftButton = 0x1,
MouseRightButton = 0x2,
MouseMiddleButton = 0x4
};
const char* vncVersion() const
{
return "RFB 003.008\n";
}
enum ConnectionState {
WaitForProtocolVersion,
WaitForSecurityResponse,
WaitForClientInit,
InitializationPhase,
NormalPhase
};
struct ServerInitMsg {
uint16_t fbWidth;
uint16_t fbHeight;
PixelFormat px;
uint32_t namelen;
char name[2]; // just to put M5 in here
} M5_ATTR_PACKED;
struct FrameBufferUpdate {
uint8_t type;
uint8_t padding;
uint16_t num_rects;
} M5_ATTR_PACKED;
struct FrameBufferRect {
uint16_t x;
uint16_t y;
uint16_t width;
uint16_t height;
int32_t encoding;
} M5_ATTR_PACKED;
struct ServerCutText {
uint8_t type;
uint8_t padding[3];
uint32_t length;
} M5_ATTR_PACKED;
/** @} */
protected:
/** ListenEvent to accept a vnc client connection */
class ListenEvent: public PollEvent
{
protected:
VncServer *vncserver;
public:
ListenEvent(VncServer *vs, int fd, int e);
void process(int revent);
};
friend class ListenEvent;
ListenEvent *listenEvent;
/** DataEvent to read data from vnc */
class DataEvent: public PollEvent
{
protected:
VncServer *vncserver;
public:
DataEvent(VncServer *vs, int fd, int e);
void process(int revent);
};
friend class DataEvent;
DataEvent *dataEvent;
int number;
int dataFd; // data stream file describer
ListenSocket listener;
void listen(int port);
void accept();
void data();
void detach();
public:
typedef VncServerParams Params;
VncServer(const Params *p);
~VncServer();
// RFB
protected:
/** The rfb prototol state the connection is in */
ConnectionState curState;
/** An update needs to be sent to the client. Without doing this the
* client will constantly request data that is pointless */
bool sendUpdate;
/** The one and only pixel format we support */
PixelFormat pixelFormat;
/** If the vnc client supports receiving raw data. It always should */
bool supportsRawEnc;
/** If the vnc client supports the desktop resize command */
bool supportsResizeEnc;
protected:
/**
* vnc client Interface
*/
/** Send an error message to the client
* @param error_msg text to send describing the error
*/
void sendError(const char* error_msg);
/** Read some data from the client
* @param buf the data to read
* @param len the amount of data to read
* @return length read
*/
size_t read(uint8_t *buf, size_t len);
/** Read len -1 bytes from the client into the buffer provided + 1
* assert that we read enough bytes. This function exists to handle
* reading all of the protocol structs above when we've already read
* the first byte which describes which one we're reading
* @param buf the address of the buffer to add one to and read data into
* @param len the amount of data + 1 to read
* @return length read
*/
size_t read1(uint8_t *buf, size_t len);
/** Templated version of the read function above to
* read simple data to the client
* @param val data to recv from the client
*/
template <typename T> size_t read(T* val);
/** Write a buffer to the client.
* @param buf buffer to send
* @param len length of the buffer
* @return number of bytes sent
*/
size_t write(const uint8_t *buf, size_t len);
/** Templated version of the write function above to
* write simple data to the client
* @param val data to send to the client
*/
template <typename T> size_t write(T* val);
/** Send a string to the client
* @param str string to transmit
*/
size_t write(const char* str);
/** Check the client's protocol verion for compatibility and send
* the security types we support
*/
void checkProtocolVersion();
/** Check that the security exchange was successful
*/
void checkSecurity();
/** Send client our idea about what the frame buffer looks like */
void sendServerInit();
/** Send an error message to the client when something goes wrong
* @param error_msg error to send
*/
void sendError(std::string error_msg);
/** Send a updated frame buffer to the client.
* @todo this doesn't do anything smart and just sends the entire image
*/
void sendFrameBufferUpdate();
/** Receive pixel foramt message from client and process it. */
void setPixelFormat();
/** Receive encodings message from client and process it. */
void setEncodings();
/** Receive message from client asking for updated frame buffer */
void requestFbUpdate();
/** Receive message from client providing new keyboard input */
void recvKeyboardInput();
/** Recv message from client providing new mouse movement or button click */
void recvPointerInput();
/** Receive message from client that there is text in it's paste buffer.
* This is a no-op at the moment, but perhaps we would want to be able to
* paste it at some point.
*/
void recvCutText();
/** Tell the client that the frame buffer resized. This happens when the
* simulated system changes video modes (E.g. X11 starts).
*/
void sendFrameBufferResized();
public:
/** The frame buffer uses this call to notify the vnc server that
* the frame buffer has been updated and a new image needs to be sent to the
* client
*/
void
setDirty()
{
VncInput::setDirty();
sendUpdate = true;
sendFrameBufferUpdate();
}
/** Set the mode of the data the frame buffer will be sending us
* @param mode the mode
*/
void setFrameBufferParams(VideoConvert::Mode mode, uint16_t width,
uint16_t height);
};
#endif
| 29.06079 | 80 | 0.664261 | lokamdheeraj |
cd25980111faa35ce011d73e550975772c9fea36 | 2,576 | hpp | C++ | include/boost/url/src.hpp | vgrigoriu/url | 8911d05c35123f978e90321fea863385b63525d4 | [
"BSL-1.0"
] | null | null | null | include/boost/url/src.hpp | vgrigoriu/url | 8911d05c35123f978e90321fea863385b63525d4 | [
"BSL-1.0"
] | null | null | null | include/boost/url/src.hpp | vgrigoriu/url | 8911d05c35123f978e90321fea863385b63525d4 | [
"BSL-1.0"
] | null | null | null | //
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/CPPAlliance/url
//
#ifndef BOOST_URL_SRC_HPP
#define BOOST_URL_SRC_HPP
/*
This file is meant to be included once,
in a translation unit of the program.
*/
// MUST COME FIRST
#ifndef BOOST_URL_SOURCE
#define BOOST_URL_SOURCE
#endif
// We include this in case someone is
// using src.hpp as their main header file
#include <boost/url.hpp>
#include <boost/url/detail/impl/any_path_iter.ipp>
#include <boost/url/detail/impl/any_query_iter.ipp>
#include <boost/url/detail/impl/copied_strings.ipp>
#include <boost/url/detail/impl/except.ipp>
#include <boost/url/detail/impl/path.ipp>
#include <boost/url/detail/impl/pct_encoding.ipp>
#include <boost/url/impl/authority_view.ipp>
#include <boost/url/impl/const_string.ipp>
#include <boost/url/impl/error.ipp>
#include <boost/url/impl/ipv4_address.ipp>
#include <boost/url/impl/ipv6_address.ipp>
#include <boost/url/impl/params.ipp>
#include <boost/url/impl/params_encoded.ipp>
#include <boost/url/impl/params_encoded_view.ipp>
#include <boost/url/impl/params_view.ipp>
#include <boost/url/impl/pct_encoding.ipp>
#include <boost/url/impl/scheme.ipp>
#include <boost/url/impl/segments.ipp>
#include <boost/url/impl/segments_encoded.ipp>
#include <boost/url/impl/segments_encoded_view.ipp>
#include <boost/url/impl/segments_view.ipp>
#include <boost/url/impl/static_pool.ipp>
#include <boost/url/impl/static_url.ipp>
#include <boost/url/impl/url.ipp>
#include <boost/url/impl/url_view.ipp>
#include <boost/url/grammar/impl/error.ipp>
#include <boost/url/rfc/impl/absolute_uri_rule.ipp>
#include <boost/url/rfc/impl/authority_rule.ipp>
#include <boost/url/rfc/impl/fragment_rule.ipp>
#include <boost/url/rfc/impl/hier_part_rule.ipp>
#include <boost/url/rfc/impl/host_rule.ipp>
#include <boost/url/rfc/impl/ip_literal_rule.ipp>
#include <boost/url/rfc/impl/ipv_future_rule.ipp>
#include <boost/url/rfc/impl/paths_rule.ipp>
#include <boost/url/rfc/impl/port_rule.ipp>
#include <boost/url/rfc/impl/query_rule.ipp>
#include <boost/url/rfc/impl/reg_name_rule.ipp>
#include <boost/url/rfc/impl/relative_part_rule.ipp>
#include <boost/url/rfc/impl/relative_ref_rule.ipp>
#include <boost/url/rfc/impl/scheme_rule.ipp>
#include <boost/url/rfc/impl/uri_rule.ipp>
#include <boost/url/rfc/impl/uri_reference_rule.ipp>
#include <boost/url/rfc/impl/userinfo_rule.ipp>
#endif
| 33.454545 | 79 | 0.778339 | vgrigoriu |
cd25aeb7658df87798dd2efb30780a6065e78190 | 1,089 | hpp | C++ | lib/test/exception_fixture.hpp | GreyMerlin/owl_cpp | ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6 | [
"BSL-1.0"
] | 10 | 2017-12-21T05:20:40.000Z | 2021-09-18T05:14:01.000Z | lib/test/exception_fixture.hpp | GreyMerlin/owl_cpp | ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6 | [
"BSL-1.0"
] | 2 | 2017-12-21T07:31:54.000Z | 2021-06-23T08:52:35.000Z | lib/test/exception_fixture.hpp | GreyMerlin/owl_cpp | ccc6128dbd08dcf7fcbe6679ec6acd714732bbb6 | [
"BSL-1.0"
] | 7 | 2016-02-17T13:20:31.000Z | 2021-11-08T09:30:43.000Z | /** @file "/owlcpp/lib/test/exception_fixture.hpp"
part of owlcpp project.
@n @n Distributed under the Boost Software License, Version 1.0; see doc/license.txt.
@n Copyright Mikhail K Levin 2012
*******************************************************************************/
#ifndef EXCEPTION_FIXTURE_HPP_
#define EXCEPTION_FIXTURE_HPP_
#include <iostream>
#include "boost/test/unit_test_monitor.hpp"
#include "owlcpp/exception.hpp"
namespace owlcpp{ namespace test{ namespace detail{
void translate(boost::exception const& e) {
std::cerr << boost::diagnostic_information(e) << std::endl;
throw boost::enable_current_exception(e);
}
}//namespace detail
/** Test fixture for printing exception info
*******************************************************************************/
struct Exception_fixture {
Exception_fixture() {
::boost::unit_test::unit_test_monitor.
register_exception_translator<boost::exception>(&detail::translate);
}
};
BOOST_GLOBAL_FIXTURE( Exception_fixture );
}//namespace test
}//namespace owlcpp
#endif /* EXCEPTION_FIXTURE_HPP_ */
| 32.029412 | 85 | 0.647383 | GreyMerlin |
cd260497c17ff46105c17f45c69f21a8e6c15747 | 6,381 | cpp | C++ | testMatrix2.cpp | benjamincommeau2/special_container | d36d3e8a12572dc5ef985b6ccd06336309eea4fa | [
"MIT"
] | null | null | null | testMatrix2.cpp | benjamincommeau2/special_container | d36d3e8a12572dc5ef985b6ccd06336309eea4fa | [
"MIT"
] | null | null | null | testMatrix2.cpp | benjamincommeau2/special_container | d36d3e8a12572dc5ef985b6ccd06336309eea4fa | [
"MIT"
] | null | null | null | /*
Copyright Benjamin Commeau
Use CamelCase for all names. Start types (such as classes, structs, and typedefs) with a capital letter, other names (functions, variables) with a lowercase letter. You may use an all-lowercase name with underscores if your class closely resembles an external construct (e.g., a standard library construct) named that way.
(1) C++ interfaces are named with a Interface suffix, and abstract base classes with an Abstract prefix.
(2) Member variables are named with a trailing underscore.
(3) Accessors for a variable foo_ are named foo() and setFoo().
(4) Global variables are named with a g_ prefix.
(5) Static class variables are named with a s_ prefix.
(6) Global constants are often named with a c_ prefix.
(7) If the main responsibility of a file is to implement a particular class, then the name of the file should match that class, except for possible abbreviations to avoid repetition in file names (e.g., if all classes within a module start with the module name, omitting or abbreviating the module name is OK). Currently, all source file names are lowercase, but this casing difference should be the only difference.
The rationale for the trailing underscore and the global/static prefixes is that it is immediately clear whether a variable referenced in a method is local to the function or has wider scope, improving the readability of the code.
*/
#include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <list>
#include <cstdio>
#include <complex>
#include <exception>
#include <memory>
#include <chrono>
#include <cmath>
#include <string>
#include <random>
#include "Matrix.hpp"
#include <sstream>
class Timer {
private:
std::chrono::time_point<std::chrono::high_resolution_clock>
start_ = std::chrono::high_resolution_clock::now();
std::chrono::time_point<std::chrono::high_resolution_clock>
end_ = std::chrono::high_resolution_clock::now();
std::chrono::duration<double>
duration_ = std::chrono::duration_cast
<std::chrono::nanoseconds>(end_-start_);
public:
void start() {
start_ = std::chrono::high_resolution_clock::now();
}
void stop(std::string statement) {
end_ = std::chrono::high_resolution_clock::now();
duration_ = std::chrono::duration_cast
<std::chrono::nanoseconds>(end_-start_);
std::cout << log2(duration_.count()) << " "+statement << std::endl;
start_ = std::chrono::high_resolution_clock::now();
}
};
typedef std::complex<double> V;
typedef uint32_t I;
struct T {
I x; I y; V v;
T() {}
T(const I& x_, const I& y_, const double& r_, const double& i_) {
x = x_; y = y_; v = V(r_,i_);
}
double r() {return v.real();}
double i() {return v.imag();}
};
void test_transpose() {
Matrix mat;
std::vector<T> t = {T(1,1,1,1),T(1,2,1,2),T(2,2,2,2),T(2,1,2,1),T(3,4,3,4),
T(4,3,4,3),T(5,5,5,5),T(1,6,1,6),T(2,4,2,4)};
for(uint32_t i = 0; i< t.size(); i++) {
//std::cout << "t[i].v=" << t[i].v.real() << " " << t[i].v.imag() << std::endl;
mat.add(t[i].x,t[i].y,t[i].v);
}
mat.map_.clear();
std::cout << "clear" << std::endl;
std::cout << mat.map_.to_string() << std::endl;
for(uint32_t i = 0; i<= 6; i++) {
//std::cout << "t[i].v=" << t[i].v.real() << " " << t[i].v.imag() << std::endl;
mat.add(t[i].x,t[i].y,t[i].v);
}
std::cout << mat.map_.to_string() << std::endl;
std::cout << "start transpose" << std::endl;
mat.transpose_emplace();
std::cout << mat.map_.to_string() << std::endl;
std::cout << "mat.map_.getClr()=" << mat.map_.getClr() << std::endl;
}
void test_pesABt() {
Matrix A;
std::vector<T> tA = {
T(0, 0, 0.9031785237401092,0),
T(0, 1, 0.5723564912601801,0),
T(0, 3, 0.6984202359093901,0),
T(1, 2 , 0.3614963440850427,0),
T(2, 0, 0.3917661949793543,0),
T(2, 1 , 0.6329631043924608,0),
T(3, 0 , 0.005159148556627802,0),
T(3, 2 , 0.6041319382476973,0)};
for(uint32_t i = 0; i< tA.size(); i++) {
A.add(tA[i].x,tA[i].y,tA[i].v);
}
std::cout << "A=" << std::endl;
std::cout << A.map_.to_string() << std::endl;
Matrix B;
std::vector<T> tB = {
T(0, 0 , 0.6743304229389547 ,0),
T(0, 2 , 0.01591036096127696, 0),
T(0, 3 , 0.39294230987084167, 0),
T(1, 0 , 0.6723172732412332, 0),
T(1, 1 , 0.5277647948207705, 0),
T(2, 0 , 0.3308392493496919, 0),
T(2, 2 , 0.8688014582078086, 0),
T(2, 3 , 0.6940315754218798,0)};
for(uint32_t i = 0; i< tB.size(); i++) {
B.add(tB[i].x,tB[i].y,tB[i].v);
}
std::cout << "B=" << std::endl;
std::cout << B.map_.to_string() << std::endl;
Matrix C;
std::vector<T> tC = {
T(0, 0 , 0.9938459114290126,0),
T(0, 1 , 0.3020696061742651,0),
T(0, 2 , 0.01436989632517839,0),
T(0, 3 , 0.3548970553441753,0),
T(1, 0 , 0.11959717911975347,0),
T(1, 2 , 0.31406855087787683,0),
T(1, 3 , 0.2508898771945921,0),
T(2, 0 , 0.6897318923610583,0),
T(2, 1 , 0.3340556429188051,0),
T(2, 2 , 0.006233141574547536,0),
T(2, 3 , 0.153941513584498,0),
T(3, 0 , 0.20334952778623833,0),
T(3, 2 , 0.5249527928152979,0),
T(3, 3 , 0.42131388861553126,0)};
for(uint32_t i = 0; i< tC.size(); i++) {
C.add(tC[i].x,tC[i].y,tC[i].v);
}
std::cout << "C=" << std::endl;
std::cout << C.map_.to_string() << std::endl;
B.transpose_emplace();
std::cout << "Transposed B" << std::endl;
Matrix Cn;
Cn.pesABt(1,A,B);
std::cout << "Cn=" << std::endl;
std::cout << Cn.map_.to_string() << std::endl;
std::cout << "C=" << std::endl;
std::cout << C.map_.to_string() << std::endl;
bool is_error = false;
for(uint32_t x = 0; x < 4; x++) {
for(uint32_t y = 0; y < 4; y++) {
if(std::abs(C.getCoeff(x,y)-Cn.getCoeff(x,y))>1.e-10) {
std::cout << "Error in testMatrix->ABteq->"
<< "( C.getCoeff(x,y) , Cn.getCoeff(x,y) )=" << std::endl;
std::cout << "( " << Matrix::V(C.getCoeff(x,y)).to_string() << " , "
<< Matrix::V(Cn.getCoeff(x,y)).to_string() << " ) " << std::endl;
is_error=true;
}
}
}
if(is_error == false) {
std::cout << "Passed pesABt test." << std::endl;
} else {
std::cout << "Failed pesABt test." << std::endl;
}
}
int main() {
// test_transpose();
test_pesABt();
return 0;
}
/*
*/
| 35.254144 | 416 | 0.601943 | benjamincommeau2 |
cd2a22f8413b198b8ce04dda1f7865272ee97a81 | 6,928 | cpp | C++ | src/oatpp/core/base/Environment.cpp | nuvo-legrand/oatpp | b9ecdb6be67884bece9d2b41f6e8b8b152d293ac | [
"Apache-2.0"
] | 1 | 2020-03-09T14:37:39.000Z | 2020-03-09T14:37:39.000Z | src/oatpp/core/base/Environment.cpp | Lisprez/oatpp | 7b0e629e2b55f841c17579d708eefafa07ad227f | [
"Apache-2.0"
] | null | null | null | src/oatpp/core/base/Environment.cpp | Lisprez/oatpp | 7b0e629e2b55f841c17579d708eefafa07ad227f | [
"Apache-2.0"
] | null | null | null | /***************************************************************************
*
* Project _____ __ ____ _ _
* ( _ ) /__\ (_ _)_| |_ _| |_
* )(_)( /(__)\ )( (_ _)(_ _)
* (_____)(__)(__)(__) |_| |_|
*
*
* Copyright 2018-present, Leonid Stryzhevskyi <lganzzzo@gmail.com>
*
* 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 "Environment.hpp"
#include <iostream>
#include <cstring>
#include <stdarg.h>
namespace oatpp { namespace base {
Logger* Environment::m_logger = nullptr;
std::unordered_map<std::string, std::unordered_map<std::string, void*>> Environment::m_components;
v_atomicCounter Environment::m_objectsCount(0);
v_atomicCounter Environment::m_objectsCreated(0);
thread_local v_counter Environment::m_threadLocalObjectsCount = 0;
thread_local v_counter Environment::m_threadLocalObjectsCreated = 0;
void Environment::init(){
checkTypes();
m_objectsCount = 0;
m_objectsCreated = 0;
m_threadLocalObjectsCount = 0;
m_threadLocalObjectsCreated = 0;
if(m_components.size() > 0) {
throw std::runtime_error("[oatpp::base::Environment]: Invalid state. Components were created before call to Environment::init()");
}
}
void Environment::destroy(){
if(m_components.size() > 0) {
throw std::runtime_error("[oatpp::base::Environment]: Invalid state. Leaking components");
}
}
void Environment::checkTypes(){
OATPP_ASSERT(sizeof(v_char8) == 1);
OATPP_ASSERT(sizeof(v_int16) == 2);
OATPP_ASSERT(sizeof(v_word16) == 2);
OATPP_ASSERT(sizeof(v_int32) == 4);
OATPP_ASSERT(sizeof(v_int64) == 8);
OATPP_ASSERT(sizeof(v_word32) == 4);
OATPP_ASSERT(sizeof(v_word64) == 8);
OATPP_ASSERT(sizeof(v_float64) == 8);
v_int32 vInt32 = ~1;
v_int64 vInt64 = ~1;
v_word32 vWord32 = ~1;
v_word64 vWord64 = ~1;
OATPP_ASSERT(vInt32 < 0);
OATPP_ASSERT(vInt64 < 0);
OATPP_ASSERT(vWord32 > 0);
OATPP_ASSERT(vWord64 > 0);
}
void Environment::incObjects(){
m_objectsCount ++;
m_objectsCreated ++;
m_threadLocalObjectsCount ++;
m_threadLocalObjectsCreated ++;
}
void Environment::decObjects(){
m_objectsCount --;
m_threadLocalObjectsCount --;
}
v_counter Environment::getObjectsCount(){
return m_objectsCount;
}
v_counter Environment::getObjectsCreated(){
return m_objectsCreated;
}
v_counter Environment::getThreadLocalObjectsCount(){
return m_threadLocalObjectsCount;
}
v_counter Environment::getThreadLocalObjectsCreated(){
return m_threadLocalObjectsCreated;
}
void Environment::setLogger(Logger* logger){
if(m_logger != nullptr){
delete m_logger;
}
m_logger = logger;
}
void Environment::printCompilationConfig() {
#ifdef OATPP_DISABLE_ENV_OBJECT_COUNTERS
OATPP_LOGD("oatpp/Config", "OATPP_DISABLE_ENV_OBJECT_COUNTERS");
#endif
#ifdef OATPP_DISABLE_POOL_ALLOCATIONS
OATPP_LOGD("oatpp/Config", "OATPP_DISABLE_POOL_ALLOCATIONS");
#endif
#ifdef OATPP_THREAD_HARDWARE_CONCURRENCY
OATPP_LOGD("oatpp/Config", "OATPP_THREAD_HARDWARE_CONCURRENCY=%d", OATPP_THREAD_HARDWARE_CONCURRENCY);
#endif
OATPP_LOGD("oatpp/Config", "OATPP_THREAD_DISTRIBUTED_MEM_POOL_SHARDS_COUNT=%d", OATPP_THREAD_DISTRIBUTED_MEM_POOL_SHARDS_COUNT);
OATPP_LOGD("oatpp/Config", "OATPP_ASYNC_EXECUTOR_THREAD_NUM_DEFAULT=%d\n", OATPP_ASYNC_EXECUTOR_THREAD_NUM_DEFAULT);
}
void Environment::log(v_int32 priority, const std::string& tag, const std::string& message) {
if(m_logger != nullptr) {
m_logger->log(priority, tag, message);
}
}
void Environment::logFormatted(v_int32 priority, const std::string& tag, const char* message, ...) {
if(message == nullptr) {
message = "[null]";
}
char buffer[4097];
va_list args;
va_start (args, message);
vsnprintf(buffer, 4096, message, args);
log(priority, tag, buffer);
va_end(args);
}
void Environment::registerComponent(const std::string& typeName, const std::string& componentName, void* component) {
auto& bucket = m_components[typeName];
auto it = bucket.find(componentName);
if(it != bucket.end()){
throw std::runtime_error("[oatpp::base::Environment]: Component with given name already exists: name='" + componentName + "'");
}
bucket[componentName] = component;
}
void Environment::unregisterComponent(const std::string& typeName, const std::string& componentName) {
auto bucketIt = m_components.find(typeName);
if(bucketIt == m_components.end() || bucketIt->second.size() == 0) {
throw std::runtime_error("[oatpp::base::Environment]: Component of given type does't exist: type='" + typeName + "'");
}
auto& bucket = bucketIt->second;
auto componentIt = bucket.find(componentName);
if(componentIt == bucket.end()) {
throw std::runtime_error("[oatpp::base::Environment]: Component with given name does't exist: name='" + componentName + "'");
}
bucket.erase(componentIt);
if(bucket.size() == 0) {
m_components.erase(bucketIt);
}
}
void* Environment::getComponent(const std::string& typeName) {
auto bucketIt = m_components.find(typeName);
if(bucketIt == m_components.end() || bucketIt->second.size() == 0) {
throw std::runtime_error("[oatpp::base::Environment]: Component of given type does't exist: type='" + typeName + "'");
}
auto bucket = bucketIt->second;
if(bucket.size() > 1){
throw std::runtime_error("[oatpp::base::Environment]: Ambiguous component reference. Multiple components exist for a given type: type='" + typeName + "'");
}
return bucket.begin()->second;
}
void* Environment::getComponent(const std::string& typeName, const std::string& componentName) {
auto bucketIt = m_components.find(typeName);
if(bucketIt == m_components.end() || bucketIt->second.size() == 0) {
throw std::runtime_error("[oatpp::base::Environment]: Component of given type does't exist: type='" + typeName + "'");
}
auto bucket = bucketIt->second;
auto componentIt = bucket.find(componentName);
if(componentIt == bucket.end()) {
throw std::runtime_error("[oatpp::base::Environment]: Component with given name does't exist: name='" + componentName + "'");
}
return componentIt->second;
}
v_int64 Environment::getMicroTickCount(){
std::chrono::microseconds ms = std::chrono::duration_cast<std::chrono::microseconds>
(std::chrono::system_clock::now().time_since_epoch());
return ms.count();
}
}}
| 32.834123 | 159 | 0.693707 | nuvo-legrand |
cd2f5bf692783f4a8773e85f6912079ba6950d20 | 2,642 | cpp | C++ | piel/gavcconstants.cpp | diakovliev/pie | eb957a5e44496ba802d8b4fcace64ad48be16871 | [
"BSD-3-Clause"
] | null | null | null | piel/gavcconstants.cpp | diakovliev/pie | eb957a5e44496ba802d8b4fcace64ad48be16871 | [
"BSD-3-Clause"
] | null | null | null | piel/gavcconstants.cpp | diakovliev/pie | eb957a5e44496ba802d8b4fcace64ad48be16871 | [
"BSD-3-Clause"
] | 1 | 2017-12-28T11:37:42.000Z | 2017-12-28T11:37:42.000Z | /*
* Copyright (c) 2017, Dmytro Iakovliev daemondzk@gmail.com
* 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 <organization> 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 Dmytro Iakovliev daemondzk@gmail.com ''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 Dmytro Iakovliev daemondzk@gmail.com BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <gavcconstants.h>
namespace art { namespace lib {
const char GavcConstants::delimiter = ':';
const char GavcConstants::extension_prefix = '@';
const char GavcConstants::latest_version = '+';
const char GavcConstants::oldest_version = '-';
const char GavcConstants::all_versions = '*';
const char GavcConstants::left_include_braket = '[';
const char GavcConstants::left_exclude_braket = '(';
const char GavcConstants::right_include_braket = ']';
const char GavcConstants::right_exclude_braket = ')';
const char GavcConstants::range_separator = ',';
const char GavcConstants::group_delimiter = '.';
const char GavcConstants::path_delimiter = '/';
const std::string GavcConstants::maven_metadata_filename = "maven-metadata.xml";
} } // namespace art::lib
| 52.84 | 87 | 0.682059 | diakovliev |
cd30ae75b9088c1eefee540387bed257c53210be | 486 | hh | C++ | source/src/vision/runner.hh | Dr-MunirShah/black-sheep | e908203d9516e01f90f4ed4c796cf4143d0df0c0 | [
"MIT"
] | 7 | 2019-07-25T10:06:31.000Z | 2021-02-20T06:00:51.000Z | source/src/vision/runner.hh | Dr-MunirShah/black-sheep | e908203d9516e01f90f4ed4c796cf4143d0df0c0 | [
"MIT"
] | null | null | null | source/src/vision/runner.hh | Dr-MunirShah/black-sheep | e908203d9516e01f90f4ed4c796cf4143d0df0c0 | [
"MIT"
] | 1 | 2019-08-31T23:32:02.000Z | 2019-08-31T23:32:02.000Z | #pragma once
#include "lut/colour.hh"
/**
* runner.hh
*
* A template for running image processing.
**/
class Runner{
public:
/**
* process()
*
* Process a given pixel.
*
* @param x The X position of the pixel.
* @param y The Y position of the pixel.
* @param p The pixel.
* @param l The pixel label.
* @return The replacement pixel.
**/
virtual unsigned int process(int x, int y, Colour::YUV p, unsigned char l) = 0;
};
| 19.44 | 83 | 0.582305 | Dr-MunirShah |
cd314901054369f8e53e28200400f5e656841956 | 4,698 | cpp | C++ | samples/gl-330-draw-instanced-array.cpp | galek/ogl-samples | 38cada7a9458864265e25415ae61586d500ff5fc | [
"MIT"
] | 571 | 2015-01-08T16:29:38.000Z | 2022-03-16T06:45:42.000Z | samples/gl-330-draw-instanced-array.cpp | galek/ogl-samples | 38cada7a9458864265e25415ae61586d500ff5fc | [
"MIT"
] | 45 | 2015-01-15T12:47:28.000Z | 2022-03-04T09:22:32.000Z | samples/gl-330-draw-instanced-array.cpp | galek/ogl-samples | 38cada7a9458864265e25415ae61586d500ff5fc | [
"MIT"
] | 136 | 2015-01-31T15:24:57.000Z | 2022-02-17T19:26:24.000Z | #include "test.hpp"
namespace
{
char const* VERT_SHADER_SOURCE("gl-330/instanced-array.vert");
char const* FRAG_SHADER_SOURCE("gl-330/instanced-array.frag");
GLsizei const VertexCount = 6;
GLsizeiptr const PositionSize = VertexCount * sizeof(glm::vec2);
glm::vec2 const PositionData[VertexCount] =
{
glm::vec2(-1.0f,-1.0f),
glm::vec2( 1.0f,-1.0f),
glm::vec2( 1.0f, 1.0f),
glm::vec2( 1.0f, 1.0f),
glm::vec2(-1.0f, 1.0f),
glm::vec2(-1.0f,-1.0f)
};
GLsizei const InstanceCount = 5;
GLsizeiptr const ColorSize = VertexCount * sizeof(glm::vec4);
glm::vec4 const ColorData[VertexCount] =
{
glm::vec4(1.0f, 0.0f, 0.0f, 1.0f),
glm::vec4(1.0f, 0.5f, 0.0f, 1.0f),
glm::vec4(1.0f, 1.0f, 0.0f, 1.0f),
glm::vec4(0.0f, 1.0f, 0.0f, 1.0f),
glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)
};
namespace shader
{
enum type
{
VERT,
FRAG,
MAX
};
}//namespace shader
namespace buffer
{
enum type
{
POSITION,
COLOR,
MAX
};
}//namespace buffer
std::vector<GLuint> BufferName(buffer::MAX);
GLuint VertexArrayName = 0;
GLuint ProgramName = 0;
GLint UniformMVP = 0;
}//namespace
class sample : public framework
{
public:
sample(int argc, char* argv[]) :
framework(argc, argv, "gl-330-draw-instanced-array", framework::CORE, 3, 3, glm::vec2(glm::pi<float>() * 0.2f))
{}
private:
bool initTest()
{
bool Validated = true;
glEnable(GL_DEPTH_TEST);
return Validated && this->checkError("initTest");
}
bool initProgram()
{
bool Validated = true;
if(Validated)
{
compiler Compiler;
GLuint VertShaderName = Compiler.create(GL_VERTEX_SHADER, getDataDirectory() + VERT_SHADER_SOURCE, "--version 330 --profile core");
GLuint FragShaderName = Compiler.create(GL_FRAGMENT_SHADER, getDataDirectory() + FRAG_SHADER_SOURCE, "--version 330 --profile core");
Validated = Validated && Compiler.check();
ProgramName = glCreateProgram();
glAttachShader(ProgramName, VertShaderName);
glAttachShader(ProgramName, FragShaderName);
glLinkProgram(ProgramName);
Validated = Validated && Compiler.check_program(ProgramName);
}
// Get variables locations
if(Validated)
{
UniformMVP = glGetUniformLocation(ProgramName, "MVP");
}
return Validated && this->checkError("initProgram");
}
bool initBuffer()
{
glGenBuffers(buffer::MAX, &BufferName[0]);
glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::POSITION]);
glBufferData(GL_ARRAY_BUFFER, PositionSize, PositionData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::COLOR]);
glBufferData(GL_ARRAY_BUFFER, ColorSize, ColorData, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return this->checkError("initBuffer");
}
bool initVertexArray()
{
glGenVertexArrays(1, &VertexArrayName);
glBindVertexArray(VertexArrayName);
glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::POSITION]);
glVertexAttribPointer(semantic::attr::POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribDivisor(semantic::attr::POSITION, 0);
glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::COLOR]);
glVertexAttribPointer(semantic::attr::COLOR, 4, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribDivisor(semantic::attr::COLOR, 2);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnableVertexAttribArray(semantic::attr::POSITION);
glEnableVertexAttribArray(semantic::attr::COLOR);
glBindVertexArray(0);
return this->checkError("initVertexArray");
}
bool begin()
{
bool Validated = true;
if(Validated)
Validated = initTest();
if(Validated)
Validated = initProgram();
if(Validated)
Validated = initBuffer();
if(Validated)
Validated = initVertexArray();
return Validated && this->checkError("begin");
}
bool end()
{
glDeleteBuffers(static_cast<GLsizei>(BufferName.size()), &BufferName[0]);
glDeleteProgram(ProgramName);
glDeleteVertexArrays(1, &VertexArrayName);
return this->checkError("end");
}
bool render()
{
glm::ivec2 WindowSize(this->getWindowSize());
glm::mat4 Projection = glm::perspective(glm::pi<float>() * 0.25f, 4.0f / 3.0f, 0.1f, 100.0f);
glm::mat4 Model = glm::mat4(1.0f);
glm::mat4 MVP = Projection * this->view() * Model;
glViewport(0, 0, WindowSize.x, WindowSize.y);
float Depth(1.0f);
glClearBufferfv(GL_DEPTH, 0, &Depth);
glClearBufferfv(GL_COLOR, 0, &glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)[0]);
glUseProgram(ProgramName);
glUniformMatrix4fv(UniformMVP, 1, GL_FALSE, &MVP[0][0]);
glBindVertexArray(VertexArrayName);
glDrawArraysInstanced(GL_TRIANGLES, 0, VertexCount, 10);
return true;
}
};
int main(int argc, char* argv[])
{
int Error = 0;
sample Sample(argc, argv);
Error += Sample();
return Error;
}
| 24.216495 | 136 | 0.697318 | galek |
cd317321e9cc065f112bd4145e17bdd43b71c376 | 1,244 | cpp | C++ | include/File.cpp | igorabrandao/Flood_IT | a590b1b8ac164c137c121dc74f719329589e28c8 | [
"MIT"
] | 1 | 2021-07-15T01:24:36.000Z | 2021-07-15T01:24:36.000Z | include/File.cpp | igorabrandao/Flood_IT | a590b1b8ac164c137c121dc74f719329589e28c8 | [
"MIT"
] | null | null | null | include/File.cpp | igorabrandao/Flood_IT | a590b1b8ac164c137c121dc74f719329589e28c8 | [
"MIT"
] | null | null | null | // ***************************************************
// ** Implements the functions related to the Game
// ** Interface class
// ***************************************************
#include "File.h"
// ***************************************************
// ** Functions
// ***************************************************
#ifdef __linux__
#include <unistd.h>
#else
inline int access(const char *pathname, int mode)
{
return _access(pathname, mode);
}
#endif
// ***************************************************
// ** Functions
// ***************************************************
/**
* Function to check the config file
*/
int File::checkConfigFile(const char *fname)
{
//return (access(fname, F_OK) != -1 ? 1 : 0);
return 0;
}
/**
* Function to generate the game config file
*/
void File::createConfigFile(const char *fname, CONFIG *config_)
{
/* Criação do arquivo e modo de escrita */
FILE *fp = fopen(fname, "w+");
/* Escrevendo as configurações no arquivo */
fprintf(fp, "difficultLevel = %i\n", config_->difficultLevel);
fprintf(fp, "maxNPlay = %i\n", config_->maxNPlay);
fprintf(fp, "boardSize = %i\n", config_->boardSize);
// Fechamento do arquivo
fclose(fp);
} | 25.916667 | 67 | 0.472669 | igorabrandao |
cd33ee77980344493844c714d70dcd754349a66b | 1,316 | cpp | C++ | Framework/Sources/o2/Utils/Tasks/TaskManager.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 181 | 2015-12-09T08:53:36.000Z | 2022-03-26T20:48:39.000Z | Framework/Sources/o2/Utils/Tasks/TaskManager.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 29 | 2016-04-22T08:24:04.000Z | 2022-03-06T07:06:28.000Z | Framework/Sources/o2/Utils/Tasks/TaskManager.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 13 | 2018-04-24T17:12:04.000Z | 2021-11-12T23:49:53.000Z | #include "o2/stdafx.h"
#include "TaskManager.h"
#include "o2/Utils/Tasks/Task.h"
namespace o2
{
DECLARE_SINGLETON(TaskManager);
void TaskManager::StopTask(int id)
{
for (auto task : mTasks)
{
if (task->mId == id)
{
delete task;
return;
}
}
}
void TaskManager::StopAllTasks()
{
auto tasks = mTasks;
for (auto task : tasks)
delete task;
}
Task* TaskManager::FindTask(int id)
{
return mTasks.FindOrDefault([&](auto x) { return x->mId == id; });
}
void TaskManager::Run(const Function<void(float)>& update, const Function<bool()> isDone)
{
auto task = mnew FunctionalTask();
task->update = update;
task->isDone = isDone;
}
void TaskManager::Run(const Function<void(float)>& update, float time)
{
auto task = mnew FunctionalTimeTask(time);
task->update = update;
}
void TaskManager::Invoke(const Function<void()> func, float delay /*= 0*/)
{
auto task = mnew FunctionalDelayedTask(delay);
task->doTask = func;
}
TaskManager::TaskManager():
mLastTaskId(0)
{}
TaskManager::~TaskManager()
{
StopAllTasks();
}
void TaskManager::Update(float dt)
{
Vector<Task*> doneTasks;
for (auto task : mTasks)
{
task->Update(dt);
if (task->IsDone())
doneTasks.Add(task);
}
for (auto doneTask : doneTasks)
delete doneTask;
}
}
| 17.315789 | 90 | 0.649696 | zenkovich |
cd36df2127a7435b12211eb3513b7d98601ec15b | 1,588 | hpp | C++ | stopwatch/stopwatch.hpp | helderdaniel/cpplib | d78dcaabf618a8f5e1596e17c2d6d98bfaaa808c | [
"MIT"
] | null | null | null | stopwatch/stopwatch.hpp | helderdaniel/cpplib | d78dcaabf618a8f5e1596e17c2d6d98bfaaa808c | [
"MIT"
] | null | null | null | stopwatch/stopwatch.hpp | helderdaniel/cpplib | d78dcaabf618a8f5e1596e17c2d6d98bfaaa808c | [
"MIT"
] | null | null | null | /**
* StopWatch class definition
* v2.0 hdaniel@ualg.pt 2011
* v2.1 hdaniel@ualg.pt 2019 apr
* v3.0 hdaniel@ualg.pt 2019 apr C++14
* v3.1 hdaniel@ualg.pt 2019 may C++14
* Changelog:
* return time() from last reset() to last lap()
* Note: Time is always real time, so it counts user inputs and event waits
*/
#ifndef __HAD_STOPWATCH_HPP__
#define __HAD_STOPWATCH_HPP__
#include <chrono>
#include <iostream>
using namespace std::chrono;
using std::ostream;
namespace had {
class StopWatch {
time_point <high_resolution_clock> start, stop;
double elapsedTime; //real elapsed time in seconds
public:
/**
* Creates StopWatch object and resets timer
*/
StopWatch() { reset(); }
/**
* sets start and stop times equals to current time
*/
StopWatch &reset() {
elapsedTime = 0;
start = stop = high_resolution_clock::now();
return *this; //for method chain
}
/**
* sets stop times equals to current time
*/
StopWatch &lap() {
stop = high_resolution_clock::now();
elapsedTime = duration<double>(stop - start).count();
return *this; //for method chain
}
/**
* Returns time elapsed since last reset() until last lap()
* DOES count user input like wait keypress
*/
double watch() const {
return elapsedTime;
//No method chain here, since returns time
}
friend ostream& operator << (ostream&, StopWatch&);
};
/**
* Prints real elapsed time in seconds
*/
ostream &operator<<(ostream &os, StopWatch &sw) {
os << sw.watch() << "s";
return os;
}
}
#endif //__HAD_STOPWATCH_HPP__
| 20.894737 | 81 | 0.65995 | helderdaniel |
cd38d18fa67c4ab2fa4a961eac204e81266f6773 | 1,110 | cpp | C++ | branch/MSP432/SaltyOS/Kernel/GUI/Text/FontAddressing.cpp | wtywtykk/STM32Framework_SaltyProject | ba52576006a9c4bdb3c0e6b0dbef2d261359da50 | [
"MIT"
] | 1 | 2019-04-03T12:17:25.000Z | 2019-04-03T12:17:25.000Z | branch/MSP432/SaltyOS/Kernel/GUI/Text/FontAddressing.cpp | wtywtykk/STM32Framework_SaltyProject | ba52576006a9c4bdb3c0e6b0dbef2d261359da50 | [
"MIT"
] | null | null | null | branch/MSP432/SaltyOS/Kernel/GUI/Text/FontAddressing.cpp | wtywtykk/STM32Framework_SaltyProject | ba52576006a9c4bdb3c0e6b0dbef2d261359da50 | [
"MIT"
] | 1 | 2021-06-09T11:20:08.000Z | 2021-06-09T11:20:08.000Z | #include "Kernel\Common\KCommon.h"
#include "FontAddressing.h"
#include <EmbeddedResources.h>
u32 GetStartAddress(const FONTINDEX* Index)
{
if (Index->StorageMode & AddressInFlash)
{
return Index->DataStart + (u32)&_binary_Resource_Pack_bin_start;
}
else
{
return Index->DataStart;
}
}
u32 GetEndAddress(const FONTINDEX* Index)
{
if (Index->StorageMode | AddressInFlash)
{
return Index->DataEnd + (u32)&_binary_Resource_Pack_bin_start;
}
else
{
return Index->DataEnd;
}
}
static u32 GetStandardAddressingOffset(const FONTINDEX* Index, u16 Char)
{
return Index->Size*(Char - Index->AscLBound);
}
static u32 GetGB2312AddressingOffset(const FONTINDEX* Index, u16 Char)
{
u32 Sub = Char - Index->AscLBound;
u32 Block = (Sub >> 8) & 0xFF;
u32 Bit = Sub & 0xFF;
return Index->Size*(94 * Block + Bit);
}
u32 GetAddressingOffset(const FONTINDEX* Index, u16 Char)
{
switch (Index->StorageMode & AddressingBits)
{
default:
case StandardAddressing:
return GetStandardAddressingOffset(Index, Char);
break;
case GB2312Addressing:
return GetGB2312AddressingOffset(Index, Char);
}
}
| 20.555556 | 72 | 0.734234 | wtywtykk |
cd39a0cc91ec7f47bc1eca92634909d780ede62d | 526 | cpp | C++ | ace/Intrusive_List_Node.cpp | BeiJiaan/ace | 2845970c894bb350d12d6a32e867d7ddf2487f25 | [
"DOC"
] | 16 | 2015-05-11T04:33:44.000Z | 2022-02-15T04:28:39.000Z | ace/Intrusive_List_Node.cpp | BeiJiaan/ace | 2845970c894bb350d12d6a32e867d7ddf2487f25 | [
"DOC"
] | null | null | null | ace/Intrusive_List_Node.cpp | BeiJiaan/ace | 2845970c894bb350d12d6a32e867d7ddf2487f25 | [
"DOC"
] | 7 | 2015-01-08T16:11:34.000Z | 2021-07-04T16:04:40.000Z | // $Id$
#ifndef ACE_INTRUSIVE_LIST_NODE_CPP
#define ACE_INTRUSIVE_LIST_NODE_CPP
#include "ace/Intrusive_List_Node.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#if !defined (__ACE_INLINE__)
#include "ace/Intrusive_List_Node.inl"
#endif /* __ACE_INLINE__ */
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
template<class T>
ACE_Intrusive_List_Node<T>::ACE_Intrusive_List_Node (void)
: prev_ (0)
, next_ (0)
{
}
ACE_END_VERSIONED_NAMESPACE_DECL
#endif /* ACE_INTRUSIVE_LIST_NODE_CPP */
| 18.785714 | 58 | 0.785171 | BeiJiaan |
cd3cb00269b44a1d3ca7158e9fd6db7d9c610197 | 1,846 | cpp | C++ | Entregas/ACM_Tarea25/P02/HW25P02.cpp | cesar-magana/Advanced_Programming | 7b5ff09cd2816b67ca9f68d5ede211c73fb73de5 | [
"MIT"
] | null | null | null | Entregas/ACM_Tarea25/P02/HW25P02.cpp | cesar-magana/Advanced_Programming | 7b5ff09cd2816b67ca9f68d5ede211c73fb73de5 | [
"MIT"
] | null | null | null | Entregas/ACM_Tarea25/P02/HW25P02.cpp | cesar-magana/Advanced_Programming | 7b5ff09cd2816b67ca9f68d5ede211c73fb73de5 | [
"MIT"
] | null | null | null | /*------------------------------------------------------------
PROGRAMACIÓN AVANZADA I HW25P01
César Magaña
cesar@cimat.mx
--------------------------------------------------------------*/
#include <iostream>
#define FOR(i, n) for( int i = 0, _n = (n); i < _n; i++ )
using namespace std;
//------------------------------------------------------------
void lee_matriz(int **T, const int N)
{
FOR (i,N)
T[i] = new int[N];
int k=5;
FOR (i,N)
FOR (j,N)
T[i][j] = 2*k++;
}
//------------------------------------------------------------
void pinta_matriz(int **T, const int N)
{
FOR (i,N)
{
FOR (j,N)
cout << T[i][j] << " ";
cout << endl;
}
}
//------------------------------------------------------------
int existe_entero(int **T, int n, int k)
{
int i=n-1,j=0;
while (i>0 && j<n-1)
{
cout << T[i][j] << "->";
if (abs(k-T[i-1][j]) < abs(k-T[i][j+1]) )
i--;
else
j++;
if (T[i][j]==k)
return T[i][j];
}
if (i==0)
for (int l=j; l<n;l++)
{
if(T[i][l]==k)
return T[i][l];
cout << T[i][l] << "->";
}
if (j==n-1)
for (int l=i; l>-1;l--)
{
if(T[l][j]==k)
return T[l][j];
cout << T[l][j] << "->";
}
return 0;
}
//------------------------------------------------------------
int main (int argc, char * const argv[]) {
const int N=10;
int existe;
int k=1;
//Aqui se crea la matriz
int **T;
T=new int*[N];
lee_matriz(T,N);
pinta_matriz(T,N);
cout << endl <<"Introducir el numero que se va a buscar: ";
cin >> k;
cout << endl << "Camino a seguir a partir de T[n-1][0]=" << T[N-1][0] << ":" << endl;
existe=existe_entero(T,N,k);
if (!existe)
cout << endl << "No existe el elemento "<< k << endl;
else cout << existe << endl;
FOR (i,N)
delete T[i];
delete T;
return 0;
}
//------------------------------------------------------------
| 19.849462 | 86 | 0.378115 | cesar-magana |
cd3e40a98dddec68b8dfd14429dc73c275f2d11b | 2,215 | cpp | C++ | tests/reflect/main.cpp | zhangguolian/cpp-framework | 47bdf67a9dd917fa25f4c0c1b9e57ea437967497 | [
"Apache-2.0"
] | 8 | 2019-06-06T06:20:03.000Z | 2022-03-13T23:44:20.000Z | tests/reflect/main.cpp | Guolian-Zhang/cpp-framework | 47bdf67a9dd917fa25f4c0c1b9e57ea437967497 | [
"Apache-2.0"
] | null | null | null | tests/reflect/main.cpp | Guolian-Zhang/cpp-framework | 47bdf67a9dd917fa25f4c0c1b9e57ea437967497 | [
"Apache-2.0"
] | 3 | 2019-12-02T04:06:57.000Z | 2021-08-11T14:01:51.000Z | /*
*
* Copyright 2018 Guolian Zhang.
*
* 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 <reflect/reflect.h>
#include <iostream>
#include <string>
struct Test {
// Define reflect params
REFLECT_DEFINE(int, a);
REFLECT_DEFINE(std::string, b);
REFLECT_DEFINE(float, c);
};
template<class T>
void ReflectMember(const T& data) {
// Parse all members of the object
auto members = REFLECT_MEMBERS(&data);
for (size_t i = 0; i < members.size(); i++) {
if (reflect::TypeIsInt(members[i].type)) {
printf("%s %s %d\n", members[i].type.c_str(), members[i].name.c_str(), *(int*)members[i].value);
// Modify the value of an object member
*(int*)members[i].value = 2;
} else if (reflect::TypeIsFloat(members[i].type)) {
printf("%s %s %f\n", members[i].type.c_str(), members[i].name.c_str(), *(float*)members[i].value);
} else if (reflect::TypeIsString(members[i].type)) {
printf("%s %s %s\n", members[i].type.c_str(), members[i].name.c_str(), (*(std::string*)members[i].value).c_str());
}
}
}
REFLECT_ARRAY(ArrayTest, Test);
int main() {
Test test;
test.a = 1;
test.b = "test";
test.c = 0.1;
ReflectMember(test);
// Verify that the modification was successful
printf("a:%d\n", test.a);
ArrayTest test_array;
test_array.push_back(test);
printf("test_array a:%d\n", test_array[0].a);
reflect::Array* array = static_cast<reflect::Array*>((void*)(&test_array));
if (array == NULL) {
printf("static_cast Array fail\n");
return -1;
}
printf("array size %d\n", int(array->size()));
return 0;
} | 30.342466 | 126 | 0.625734 | zhangguolian |
cd3f1cca82a86d4034556c654dc91c5f6f89c3fa | 744 | cpp | C++ | src/Ic3d/IcObject.cpp | simviu/IcEng | 52ca0359011f7b3a40d915fa526f1254fe131bbe | [
"BSD-3-Clause"
] | 10 | 2017-04-13T06:43:11.000Z | 2020-10-28T18:14:54.000Z | src/Ic3d/IcObject.cpp | simviu/IcEng | 52ca0359011f7b3a40d915fa526f1254fe131bbe | [
"BSD-3-Clause"
] | 1 | 2018-05-23T08:13:12.000Z | 2018-10-15T15:34:16.000Z | src/Ic3d/IcObject.cpp | simviu/IcEng | 52ca0359011f7b3a40d915fa526f1254fe131bbe | [
"BSD-3-Clause"
] | 2 | 2018-03-30T19:19:11.000Z | 2020-01-23T15:41:39.000Z | //
// IcObject.cpp
// DevEng
//
// Created by Sherman Chen on 3/11/16.
// Copyright (c) 2016 Simviu Technology Inc.
// All rights reserved.
// http://www.simviu.com/dev
//
#include "Ic3d.h"
#include "IcRenderEng.h"
namespace Ic3d {
//--------------------------------------------
// calcMat
//--------------------------------------------
TMat4 IcObject::calcMat() const
{
TMat4 m0;
TMat4 ms = glm::scale(m0, m_scale);
TMat4 mr = glm::mat4_cast(m_quat);
TMat4 mt = glm::translate(m0, m_pos);
return mt*mr*ms;
}
//--------------------------------------------
// draw
//--------------------------------------------
void IcObject::draw() const
{
if(m_pModel!=nullptr)
m_pModel->draw();
}
} // namespace Ic3d
| 19.076923 | 47 | 0.47043 | simviu |
cd45fde462adb73474e75a9b4a8619b7cf4e2094 | 2,708 | cpp | C++ | Engine/src/Graphics/DX12/ByteAddressBufferDX12.cpp | jpvanoosten/VolumeTiledForwardShading | daf27632cb173c05faace6db0b72a74ae0fe216c | [
"MIT"
] | 70 | 2017-11-12T08:25:47.000Z | 2022-03-10T03:16:06.000Z | Engine/src/Graphics/DX12/ByteAddressBufferDX12.cpp | jpvanoosten/VolumeTiledForwardShading | daf27632cb173c05faace6db0b72a74ae0fe216c | [
"MIT"
] | null | null | null | Engine/src/Graphics/DX12/ByteAddressBufferDX12.cpp | jpvanoosten/VolumeTiledForwardShading | daf27632cb173c05faace6db0b72a74ae0fe216c | [
"MIT"
] | 11 | 2017-12-18T12:42:32.000Z | 2022-02-04T08:19:53.000Z | #include <EnginePCH.h>
#include <Graphics/DX12/ByteAddressBufferDX12.h>
#include <Graphics/DX12/DeviceDX12.h>
#include <Graphics/DX12/GraphicsCommandBufferDX12.h>
#include <Common.h>
using namespace Graphics;
ByteAddressBufferDX12::ByteAddressBufferDX12( std::shared_ptr<DeviceDX12> device )
: BufferDX12( device )
, m_BufferSize( 0 )
, m_d3d12ShaderResourceView( {0} )
, m_d3d12UniformAccessView( {0} )
{
m_d3d12ShaderResourceView = device->AllocateDescriptors( D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV );
m_d3d12UniformAccessView = device->AllocateDescriptors( D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV );
}
ByteAddressBufferDX12::~ByteAddressBufferDX12()
{}
size_t ByteAddressBufferDX12::GetBufferSize() const
{
return m_BufferSize;
}
void ByteAddressBufferDX12::CreateViews( size_t numElements, size_t elementSize )
{
// Make sure buffer size is aligned to 4 bytes.
m_BufferSize = Math::AlignUp( numElements * elementSize, 4 );
D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER;
srvDesc.Format = DXGI_FORMAT_R32_TYPELESS;
srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
srvDesc.Buffer.NumElements = (UINT)m_BufferSize / 4;
srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW;
m_d3d12Device->CreateShaderResourceView( m_d3d12Resource.Get(), &srvDesc, m_d3d12ShaderResourceView );
D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
uavDesc.Buffer.NumElements = (UINT)m_BufferSize / 4;
uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
m_d3d12Device->CreateUnorderedAccessView( m_d3d12Resource.Get(), nullptr, &uavDesc, m_d3d12UniformAccessView );
}
D3D12_CPU_DESCRIPTOR_HANDLE ByteAddressBufferDX12::GetShaderResourceView( std::shared_ptr<GraphicsCommandBufferDX12> commandBuffer, uint32_t )
{
if ( commandBuffer )
{
if ( commandBuffer->GetD3D12CommandListType() == D3D12_COMMAND_LIST_TYPE_COMPUTE )
{
commandBuffer->TransitionResoure( shared_from_this(), ResourceState::NonPixelShader );
}
else
{
commandBuffer->TransitionResoure( shared_from_this(), ResourceState::PixelShader | ResourceState::NonPixelShader );
}
}
return m_d3d12ShaderResourceView;
}
D3D12_CPU_DESCRIPTOR_HANDLE ByteAddressBufferDX12::GetUnorderedAccessView( std::shared_ptr<GraphicsCommandBufferDX12> commandBuffer, uint32_t )
{
if ( commandBuffer )
{
commandBuffer->TransitionResoure( shared_from_this(), ResourceState::UAV );
}
return m_d3d12UniformAccessView;
}
| 36.106667 | 143 | 0.762925 | jpvanoosten |
cd479fcddefa78d26b7a89acf6ca68eb325f7900 | 777 | cpp | C++ | src/qnitecategoryaxis.cpp | sleihkauf/qnite | e13f56da7aab123df0f9fcdac8a7292c0e4138f8 | [
"MIT"
] | 90 | 2015-04-16T09:35:35.000Z | 2022-03-27T15:55:31.000Z | src/qnitecategoryaxis.cpp | sleihkauf/qnite | e13f56da7aab123df0f9fcdac8a7292c0e4138f8 | [
"MIT"
] | 37 | 2015-04-28T08:45:21.000Z | 2022-02-03T13:29:04.000Z | src/qnitecategoryaxis.cpp | sleihkauf/qnite | e13f56da7aab123df0f9fcdac8a7292c0e4138f8 | [
"MIT"
] | 18 | 2017-05-19T09:08:29.000Z | 2021-12-30T06:16:55.000Z | #include "qnitecategoryaxis.h"
#include "qnitelinearmapper.h"
QniteCategoryAxis::QniteCategoryAxis(QQuickItem *parent) : QniteAxis{parent} {
setMapper(new QniteLinearMapper(this));
}
void QniteCategoryAxis::setValues(const QStringList &v) {
if (m_values != v) {
m_values = v;
emit valuesChanged();
processData();
}
}
void QniteCategoryAxis::processData() {
if (mapper() == nullptr) {
return;
}
setLowerBound(0.0);
setUpperBound(1.0);
m_majorTicks.clear();
auto step = 1.0 / (m_values.size() + 1);
for (auto i = 0; i < m_values.size(); ++i) {
auto v = mapper()->mapTo(0.0, 1.0, 0.0, size(), step * (i + 1), flip());
m_majorTicks.push_back(v);
}
m_labels = m_values;
emit labelsChanged();
emit majorTicksChanged();
}
| 19.923077 | 78 | 0.644788 | sleihkauf |
cd4b8e837d81b280965f9fef892a3fdc682021f2 | 440 | cpp | C++ | raytracer/src/Materials/Material.cpp | noahssarcastic/raytracer | 672d9cd474a4ce1d5bf35f9612cf511eebc1113b | [
"MIT"
] | null | null | null | raytracer/src/Materials/Material.cpp | noahssarcastic/raytracer | 672d9cd474a4ce1d5bf35f9612cf511eebc1113b | [
"MIT"
] | null | null | null | raytracer/src/Materials/Material.cpp | noahssarcastic/raytracer | 672d9cd474a4ce1d5bf35f9612cf511eebc1113b | [
"MIT"
] | null | null | null | //
// Created by ninig on 4/19/2020.
//
#include <Constants.h>
#include "Material.h"
Material::Material() {}
Material::Material(const Material& material) = default;
Material::~Material() = default;
RGBColor
Material::shade(ShadeRec& sr) {
return BLACK;
}
Material&
Material::operator=(const Material& rhs) {
if (this == &rhs)
return *this;
return *this;
}
void Material::set_shadows(bool s) {
shadows = s;
}
| 14.666667 | 55 | 0.65 | noahssarcastic |
cd4d8c2ee43ed3d18ce8ff9cd412ba4bb5fefb7a | 9,164 | cc | C++ | chrome/browser/ui/views/apps/shaped_app_window_targeter_unittest.cc | lauer3912/chromium.src | 969c559f5e43b329295b68c49ae9bf46a833395c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-16T03:57:28.000Z | 2021-01-23T15:29:45.000Z | chrome/browser/ui/views/apps/shaped_app_window_targeter_unittest.cc | davgit/chromium.src | 29b19806a790a12fb0a64ee148d019e27db350db | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/views/apps/shaped_app_window_targeter_unittest.cc | davgit/chromium.src | 29b19806a790a12fb0a64ee148d019e27db350db | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2017-03-15T13:21:38.000Z | 2017-03-15T13:21:38.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/apps/shaped_app_window_targeter.h"
#include "chrome/browser/ui/views/apps/chrome_native_app_window_views.h"
#include "ui/aura/test/aura_test_base.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/wm/core/easy_resize_window_targeter.h"
class ShapedAppWindowTargeterTest : public aura::test::AuraTestBase {
public:
ShapedAppWindowTargeterTest()
: web_view_(NULL) {
}
virtual ~ShapedAppWindowTargeterTest() {}
views::Widget* widget() { return widget_.get(); }
apps::NativeAppWindow* app_window() { return &app_window_; }
ChromeNativeAppWindowViews* app_window_views() { return &app_window_; }
protected:
virtual void SetUp() OVERRIDE {
aura::test::AuraTestBase::SetUp();
widget_.reset(new views::Widget);
views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW);
params.remove_standard_frame = true;
params.bounds = gfx::Rect(30, 30, 100, 100);
params.context = root_window();
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget_->Init(params);
app_window_.set_web_view_for_testing(&web_view_);
app_window_.set_window_for_testing(widget_.get());
widget_->Show();
}
virtual void TearDown() OVERRIDE {
widget_.reset();
aura::test::AuraTestBase::TearDown();
}
private:
views::WebView web_view_;
scoped_ptr<views::Widget> widget_;
ChromeNativeAppWindowViews app_window_;
DISALLOW_COPY_AND_ASSIGN(ShapedAppWindowTargeterTest);
};
TEST_F(ShapedAppWindowTargeterTest, HitTestBasic) {
aura::Window* window = widget()->GetNativeWindow();
{
// Without any custom shapes, the event should be targeted correctly to the
// window.
ui::MouseEvent move(ui::ET_MOUSE_MOVED,
gfx::Point(40, 40), gfx::Point(40, 40),
ui::EF_NONE, ui::EF_NONE);
ui::EventDispatchDetails details =
event_processor()->OnEventFromSource(&move);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(window, move.target());
}
scoped_ptr<SkRegion> region(new SkRegion);
region->op(SkIRect::MakeXYWH(40, 0, 20, 100), SkRegion::kUnion_Op);
region->op(SkIRect::MakeXYWH(0, 40, 100, 20), SkRegion::kUnion_Op);
app_window()->UpdateShape(region.Pass());
{
// With the custom shape, the events that don't fall within the custom shape
// will go through to the root window.
ui::MouseEvent move(ui::ET_MOUSE_MOVED,
gfx::Point(40, 40), gfx::Point(40, 40),
ui::EF_NONE, ui::EF_NONE);
ui::EventDispatchDetails details =
event_processor()->OnEventFromSource(&move);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(root_window(), move.target());
// But events within the shape will still reach the window.
ui::MouseEvent move2(ui::ET_MOUSE_MOVED,
gfx::Point(80, 80), gfx::Point(80, 80),
ui::EF_NONE, ui::EF_NONE);
details = event_processor()->OnEventFromSource(&move2);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(window, move2.target());
}
}
TEST_F(ShapedAppWindowTargeterTest, HitTestOnlyForShapedWindow) {
// Install a window-targeter on the root window that allows a window to
// receive events outside of its bounds. Verify that this window-targeter is
// active unless the window has a custom shape.
gfx::Insets inset(-30, -30, -30, -30);
root_window()->SetEventTargeter(scoped_ptr<ui::EventTargeter>(
new wm::EasyResizeWindowTargeter(root_window(), inset, inset)));
aura::Window* window = widget()->GetNativeWindow();
{
// Without any custom shapes, an event within the window bounds should be
// targeted correctly to the window.
ui::MouseEvent move(ui::ET_MOUSE_MOVED,
gfx::Point(40, 40), gfx::Point(40, 40),
ui::EF_NONE, ui::EF_NONE);
ui::EventDispatchDetails details =
event_processor()->OnEventFromSource(&move);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(window, move.target());
}
{
// Without any custom shapes, an event that falls just outside the window
// bounds should also be targeted correctly to the window, because of the
// targeter installed on the root-window.
ui::MouseEvent move(ui::ET_MOUSE_MOVED,
gfx::Point(10, 10), gfx::Point(10, 10),
ui::EF_NONE, ui::EF_NONE);
ui::EventDispatchDetails details =
event_processor()->OnEventFromSource(&move);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(window, move.target());
}
scoped_ptr<SkRegion> region(new SkRegion);
region->op(SkIRect::MakeXYWH(40, 0, 20, 100), SkRegion::kUnion_Op);
region->op(SkIRect::MakeXYWH(0, 40, 100, 20), SkRegion::kUnion_Op);
app_window()->UpdateShape(region.Pass());
{
// With the custom shape, the events that don't fall within the custom shape
// will go through to the root window.
ui::MouseEvent move(ui::ET_MOUSE_MOVED,
gfx::Point(10, 10), gfx::Point(10, 10),
ui::EF_NONE, ui::EF_NONE);
ui::EventDispatchDetails details =
event_processor()->OnEventFromSource(&move);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(root_window(), move.target());
}
// Remove the custom shape. This should restore the behaviour of targeting the
// app window for events just outside its bounds.
app_window()->UpdateShape(scoped_ptr<SkRegion>());
{
ui::MouseEvent move(ui::ET_MOUSE_MOVED,
gfx::Point(10, 10), gfx::Point(10, 10),
ui::EF_NONE, ui::EF_NONE);
ui::EventDispatchDetails details =
event_processor()->OnEventFromSource(&move);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(window, move.target());
}
}
// Tests targeting of events on a window with an EasyResizeWindowTargeter
// installed on its container.
TEST_F(ShapedAppWindowTargeterTest, ResizeInsetsWithinBounds) {
aura::Window* window = widget()->GetNativeWindow();
{
// An event in the center of the window should always have
// |window| as its target.
ui::MouseEvent move(ui::ET_MOUSE_MOVED,
gfx::Point(80, 80), gfx::Point(80, 80),
ui::EF_NONE, ui::EF_NONE);
ui::EventDispatchDetails details =
event_processor()->OnEventFromSource(&move);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(window, move.target());
}
{
// Without an EasyResizeTargeter on the container, an event
// inside the window and within 5px of an edge should have
// |window| as its target.
ui::MouseEvent move(ui::ET_MOUSE_MOVED,
gfx::Point(32, 37), gfx::Point(32, 37),
ui::EF_NONE, ui::EF_NONE);
ui::EventDispatchDetails details =
event_processor()->OnEventFromSource(&move);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(window, move.target());
}
// The EasyResizeTargeter specifies an inset of 5px within the window.
app_window_views()->InstallEasyResizeTargeterOnContainer();
{
// Ensure that the window has an event targeter (there should be an
// EasyResizeWindowTargeter installed).
EXPECT_TRUE(static_cast<ui::EventTarget*>(window)->GetEventTargeter());
}
{
// An event in the center of the window should always have
// |window| as its target.
// TODO(mgiuca): This isn't really testing anything (note that it has the
// same expectation as the border case below). In the real environment, the
// target will actually be the RenderWidgetHostViewAura's window that is the
// child of the child of |window|, whereas in the border case it *will* be
// |window|. However, since this test environment does not have a
// RenderWidgetHostViewAura, we cannot differentiate the two cases. Fix
// the test environment so that the test can assert that non-border events
// bubble down to a child of |window|.
ui::MouseEvent move(ui::ET_MOUSE_MOVED,
gfx::Point(80, 80), gfx::Point(80, 80),
ui::EF_NONE, ui::EF_NONE);
ui::EventDispatchDetails details =
event_processor()->OnEventFromSource(&move);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(window, move.target());
}
{
// With an EasyResizeTargeter on the container, an event
// inside the window and within 5px of an edge should have
// |window| as its target.
ui::MouseEvent move(ui::ET_MOUSE_MOVED,
gfx::Point(32, 37), gfx::Point(32, 37),
ui::EF_NONE, ui::EF_NONE);
ui::EventDispatchDetails details =
event_processor()->OnEventFromSource(&move);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(window, move.target());
}
}
| 40.370044 | 80 | 0.672086 | lauer3912 |
cd4f9b72f88d76d30accfadd12d4bb069257a82a | 6,071 | cpp | C++ | src/pbrt/bssrdf.cpp | pierremoreau/pbrt-v4 | 9d2ec6ee56cd0171ebcb251f3bf0f647155dd97d | [
"Apache-2.0"
] | 5 | 2021-01-28T18:05:22.000Z | 2021-02-17T02:09:50.000Z | src/pbrt/bssrdf.cpp | pierremoreau/pbrt-v4 | 9d2ec6ee56cd0171ebcb251f3bf0f647155dd97d | [
"Apache-2.0"
] | null | null | null | src/pbrt/bssrdf.cpp | pierremoreau/pbrt-v4 | 9d2ec6ee56cd0171ebcb251f3bf0f647155dd97d | [
"Apache-2.0"
] | null | null | null | // pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys.
// The pbrt source code is licensed under the Apache License, Version 2.0.
// SPDX: Apache-2.0
#include <pbrt/bssrdf.h>
#include <pbrt/media.h>
#include <pbrt/shapes.h>
#include <pbrt/util/math.h>
#include <pbrt/util/memory.h>
#include <pbrt/util/parallel.h>
#include <pbrt/util/print.h>
#include <pbrt/util/sampling.h>
#include <cmath>
namespace pbrt {
std::string TabulatedBSSRDF::ToString() const {
return StringPrintf(
"[ TabulatedBSSRDF po: %s eta: %f ns: %s sigma_t: %s rho: %s table: %s ]", po,
eta, ns, sigma_t, rho, *table);
}
// BSSRDF Function Definitions
Float BeamDiffusionMS(Float sigma_s, Float sigma_a, Float g, Float eta, Float r) {
const int nSamples = 100;
Float Ed = 0;
// Precompute information for dipole integrand
// Compute reduced scattering coefficients $\sigmaps, \sigmapt$ and albedo $\rhop$
Float sigmap_s = sigma_s * (1 - g);
Float sigmap_t = sigma_a + sigmap_s;
Float rhop = sigmap_s / sigmap_t;
// Compute non-classical diffusion coefficient $D_\roman{G}$ using Equation
// $(\ref{eq:diffusion-coefficient-grosjean})$
Float D_g = (2 * sigma_a + sigmap_s) / (3 * sigmap_t * sigmap_t);
// Compute effective transport coefficient $\sigmatr$ based on $D_\roman{G}$
Float sigma_tr = SafeSqrt(sigma_a / D_g);
// Determine linear extrapolation distance $\depthextrapolation$ using Equation
// $(\ref{eq:dipole-boundary-condition})$
Float fm1 = FresnelMoment1(eta), fm2 = FresnelMoment2(eta);
Float ze = -2 * D_g * (1 + 3 * fm2) / (1 - 2 * fm1);
// Determine exitance scale factors using Equations $(\ref{eq:kp-exitance-phi})$ and
// $(\ref{eq:kp-exitance-e})$
Float cPhi = .25f * (1 - 2 * fm1), cE = .5f * (1 - 3 * fm2);
for (int i = 0; i < nSamples; ++i) {
// Sample real point source depth $\depthreal$
Float zr = -std::log(1 - (i + .5f) / nSamples) / sigmap_t;
// Evaluate dipole integrand $E_{\roman{d}}$ at $\depthreal$ and add to _Ed_
Float zv = -zr + 2 * ze;
Float dr = std::sqrt(r * r + zr * zr), dv = std::sqrt(r * r + zv * zv);
// Compute dipole fluence rate $\dipole(r)$ using Equation
// $(\ref{eq:diffusion-dipole})$
Float phiD =
Inv4Pi / D_g * (FastExp(-sigma_tr * dr) / dr - FastExp(-sigma_tr * dv) / dv);
// Compute dipole vector irradiance $-\N{}\cdot\dipoleE(r)$ using Equation
// $(\ref{eq:diffusion-dipole-vector-irradiance-normal})$
Float EDn = Inv4Pi *
(zr * (1 + sigma_tr * dr) * FastExp(-sigma_tr * dr) / (dr * dr * dr) -
zv * (1 + sigma_tr * dv) * FastExp(-sigma_tr * dv) / (dv * dv * dv));
// Add contribution from dipole for depth $\depthreal$ to _Ed_
Float E = phiD * cPhi + EDn * cE;
Float kappa = 1 - FastExp(-2 * sigmap_t * (dr + zr));
Ed += kappa * rhop * rhop * E;
}
return Ed / nSamples;
}
Float BeamDiffusionSS(Float sigma_s, Float sigma_a, Float g, Float eta, Float r) {
// Compute material parameters and minimum $t$ below the critical angle
Float sigma_t = sigma_a + sigma_s, rho = sigma_s / sigma_t;
Float tCrit = r * SafeSqrt(eta * eta - 1);
Float Ess = 0;
const int nSamples = 100;
for (int i = 0; i < nSamples; ++i) {
// Evaluate single-scattering integrand and add to _Ess_
Float ti = tCrit - std::log(1 - (i + .5f) / nSamples) / sigma_t;
// Determine length $d$ of connecting segment and $\cos\theta_\roman{o}$
Float d = std::sqrt(r * r + ti * ti);
Float cosTheta_o = ti / d;
// Add contribution of single scattering at depth $t$
Ess += rho * FastExp(-sigma_t * (d + tCrit)) / (d * d) *
HenyeyGreenstein(cosTheta_o, g) * (1 - FrDielectric(-cosTheta_o, eta)) *
std::abs(cosTheta_o);
}
return Ess / nSamples;
}
void ComputeBeamDiffusionBSSRDF(Float g, Float eta, BSSRDFTable *t) {
// Choose radius values of the diffusion profile discretization
t->radiusSamples[0] = 0;
t->radiusSamples[1] = 2.5e-3f;
for (int i = 2; i < t->radiusSamples.size(); ++i)
t->radiusSamples[i] = t->radiusSamples[i - 1] * 1.2f;
// Choose albedo values of the diffusion profile discretization
for (int i = 0; i < t->rhoSamples.size(); ++i)
t->rhoSamples[i] =
(1 - FastExp(-8 * i / (Float)(t->rhoSamples.size() - 1))) / (1 - FastExp(-8));
ParallelFor(0, t->rhoSamples.size(), [&](int i) {
// Compute the diffusion profile for the _i_th albedo sample
// Compute scattering profile for chosen albedo $\rho$
size_t nSamples = t->radiusSamples.size();
for (int j = 0; j < nSamples; ++j) {
Float rho = t->rhoSamples[i], r = t->radiusSamples[j];
t->profile[i * nSamples + j] = 2 * Pi * r *
(BeamDiffusionSS(rho, 1 - rho, g, eta, r) +
BeamDiffusionMS(rho, 1 - rho, g, eta, r));
}
// Compute effective albedo $\rho_{\roman{eff}}$ and CDF for importance sampling
t->rhoEff[i] = IntegrateCatmullRom(
t->radiusSamples,
pstd::span<const Float>(&t->profile[i * nSamples], nSamples),
pstd::span<Float>(&t->profileCDF[i * nSamples], nSamples));
});
}
// BSSRDFTable Method Definitions
BSSRDFTable::BSSRDFTable(int nRhoSamples, int nRadiusSamples, Allocator alloc)
: rhoSamples(nRhoSamples, alloc),
radiusSamples(nRadiusSamples, alloc),
profile(nRadiusSamples * nRhoSamples, alloc),
rhoEff(nRhoSamples, alloc),
profileCDF(nRadiusSamples * nRhoSamples, alloc) {}
std::string BSSRDFTable::ToString() const {
return StringPrintf("[ BSSRDFTable rhoSamples: %s radiusSamples: %s profile: %s "
"rhoEff: %s profileCDF: %s ]",
rhoSamples, radiusSamples, profile, rhoEff, profileCDF);
}
} // namespace pbrt
| 41.868966 | 90 | 0.598913 | pierremoreau |
cd5136a31aac9e8f830632b5c68a48e3cc587161 | 15,417 | cpp | C++ | match/match.cpp | valette/FROG | 5d36729b7c4309303baa39d472d6beaf795d1173 | [
"CECILL-B"
] | 15 | 2019-10-13T05:25:50.000Z | 2022-03-12T16:58:39.000Z | match/match.cpp | valette/FROG | 5d36729b7c4309303baa39d472d6beaf795d1173 | [
"CECILL-B"
] | 7 | 2020-10-22T20:05:42.000Z | 2020-11-18T19:41:03.000Z | match/match.cpp | valette/FROG | 5d36729b7c4309303baa39d472d6beaf795d1173 | [
"CECILL-B"
] | 1 | 2020-01-21T09:16:01.000Z | 2020-01-21T09:16:01.000Z | #include <sstream>
#include <string>
#include <vector>
#include <tuple>
#include <fstream>
#include <iostream>
#include <cmath>
#include <omp.h>
#include <assert.h>
#include <cfloat>
#include <stdio.h>
#include <chrono>
#include <thread>
# ifdef USE_SSE_FOR_MATCHING
#include <boost/align/aligned_allocator.hpp>
#include "immintrin.h"
#endif
#include <boost/filesystem.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include "../tools/pointIdType.h"
namespace fs = boost::filesystem;
using namespace std;
# ifdef USE_SSE_FOR_MATCHING
typedef vector<float, boost::alignment::aligned_allocator<float, 32> > Descriptor;
#else
typedef vector<float> Descriptor;
#endif
typedef pair<pointIdType, pointIdType> Match;
typedef vector<Match> MatchVect;
typedef std::tuple<unsigned short, unsigned short, MatchVect* > pairMatches;
typedef std::array<double, 3> v3;
struct CSVrow {
Descriptor desc;
vector<float> meta;
};
typedef vector< CSVrow > CSV;
// reads the keypoint list contained in filename (in CSV format)
CSV* readCSVGZ(string filename) {
std::string line;
CSV* myCSV = new CSV();
std::ifstream GZfile( filename, std::ios_base::in | std::ios_base::binary);
boost::iostreams::filtering_istream file;
file.push(boost::iostreams::gzip_decompressor());
file.push(GZfile);
while(std::getline(file,line)) {
CSVrow row;
std::stringstream lineStream(line);
std::string cell;
while(std::getline(lineStream,cell,',') && (int)cell[0] != 13 ) {
//cout << cell.length() << " : " << (int)cell[0] << endl;
if (row.meta.size() < 6) {
row.meta.push_back(std::stof(cell));
} else {
row.desc.push_back(std::stof(cell));
}
}
if (row.meta.size() > 0) myCSV->push_back(row);
}
return myCSV;
}
void writeCSV( CSV &csv, const char *fileName) {
ofstream file;
file.open(fileName, std::ofstream::out | std::ofstream::trunc);
for (auto i = 0; i != csv.size(); i++) {
CSVrow row = csv[ i ];
for ( auto j = 0; j < row.meta.size(); j++ ) {
file << csv[ i ].meta[ j ] << ",";
}
for ( auto j = 0; j < csv[ i ].desc.size(); j++ ) {
file << csv[ i ].desc[ j ];
if ( j < csv[ i ].desc.size() - 1 ) {
file << ",";
} else {
if ( i < csv.size() ) {
file << std::endl;
}
}
}
}
file.close();
}
// reads the keypoint list contained in filename (in CSV format)
CSV* readCSV(string filename) {
std::string line;
CSV* myCSV = new CSV();
ifstream file( filename );
while(std::getline(file,line)) {
CSVrow row;
std::stringstream lineStream(line);
std::string cell;
while(std::getline(lineStream,cell,',') && (int)cell[0] != 13 ) {
if (row.meta.size() < 6) {
row.meta.push_back(std::stof(cell));
} else {
row.desc.push_back(std::stof(cell));
}
}
if (row.meta.size() > 0) myCSV->push_back(row);
}
return myCSV;
}
// reads the keypoint list contained in filename (in binary format)
CSV* readBinary(string filename) {
FILE* file=fopen(filename.c_str(),"rb");
CSV* myCSV = new CSV();
while(!feof(file)) {
CSVrow row;
float valF;
int unused;
unused = fread(&valF, sizeof(float), 1, file);
row.meta.push_back(valF);
unused = fread(&valF, sizeof(float), 1, file);
row.meta.push_back(valF);
unused = fread(&valF, sizeof(float), 1, file);
row.meta.push_back(valF);
unused = fread(&valF, sizeof(float), 1, file);
row.meta.push_back(valF);
unused = fread(&valF, sizeof(float), 1, file);
row.meta.push_back(valF);
unused = fread(&valF, sizeof(float), 1, file);
row.meta.push_back(valF);
row.desc.resize(48);
unused = fread(row.desc.data(), sizeof(float), 48, file);
myCSV->push_back(row);
}
return myCSV;
}
# ifdef USE_SSE_FOR_MATCHING
static inline float _mm256_reduce_add_ps(__m256 x) {
/* ( x3+x7, x2+x6, x1+x5, x0+x4 ) */
const __m128 x128 = _mm_add_ps(_mm256_extractf128_ps(x, 1), _mm256_castps256_ps128(x));
/* ( -, -, x1+x3+x5+x7, x0+x2+x4+x6 ) */
const __m128 x64 = _mm_add_ps(x128, _mm_movehl_ps(x128, x128));
/* ( -, -, -, x0+x1+x2+x3+x4+x5+x6+x7 ) */
const __m128 x32 = _mm_add_ss(x64, _mm_shuffle_ps(x64, x64, 0x55));
/* Conversion to float is a no-op on x86-64 */
return _mm_cvtss_f32(x32);
}
// 75 op
inline float norm(Descriptor& pts1, Descriptor& pts2, int size) {
float result = .0;
float* a = pts1.data();
float* b = pts2.data();
for (int i = 0 ; i < size; i+=8) {
const __m256 x_1Vec = _mm256_load_ps(a+i);
const __m256 y_1Vec = _mm256_load_ps(b+i);
__m256 ans = _mm256_sub_ps(x_1Vec, y_1Vec); // Soustraction
ans = _mm256_mul_ps(ans, ans); // ^2
result += _mm256_reduce_add_ps(ans);
}
return result;
}
#else
inline float norm(Descriptor& pts1, Descriptor& pts2, int size) {
float result = .0;
for ( int i = 0 ; i < size; i++ ) {
result += ( pts1[ i ] - pts2[ i ] ) * ( pts1[ i ] - pts2[ i ] );
}
return result;
}
#endif
MatchVect* ComputeMatches(CSV &csv2, CSV &csv1, float threshold, float dist2second, bool matchAll, float anatVal, bool sym = false) {
MatchVect* matches = new MatchVect();
float d1, d2;
int match = 0;
int end1 = csv1.size();
for (int i = 0; i < end1 ; i++) {
d1 = d2 = FLT_MAX;
int end2 = csv2.size();
for ( int j = 0; j < end2 ; j++) {
//Laplacian
if (csv1[i].meta[4] != csv2[j].meta[4]) continue;
//Scale
if ((csv1[i].meta[3]/csv2[j].meta[3] > 1.3) ||
(csv2[j].meta[3]/csv1[i].meta[3] > 1.3) )
continue;
float dist = norm(csv1[i].desc, csv2[j].desc, csv1[i].desc.size() );
//Anatomical test (euclidian norm after transform)
if (anatVal != 0){
float x1 = csv1[i].meta[0];
float y1 = csv1[i].meta[1];
float z1 = csv1[i].meta[2];
float x2 = csv2[j].meta[0];
float y2 = csv2[j].meta[1];
float z2 = csv2[j].meta[2];
float euclNorm = sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) + (z1-z2)*(z1-z2));
if (euclNorm > anatVal){
continue;
}
}
if (matchAll && sqrt(dist) < threshold) {
if (sym) {
matches->push_back(make_pair(i, match));
} else {
matches->push_back(make_pair(match, i));
}
} else {
if(dist<d1) {
d2 = d1;
d1 = dist;
match = j;
} else if(dist<d2) {
d2 = dist;
}
}
}
if (!matchAll) {
if ( ( sqrt(d1/d2) < dist2second || (d2 == FLT_MAX) ) &&
(sqrt(d1) < threshold)) {
if (sym) {
matches->push_back(make_pair(i, match));
} else {
matches->push_back(make_pair(match, i));
}
}
}
}
return matches;
}
bool compareCSVrow (CSVrow i,CSVrow j) { return (i.meta[5]>j.meta[5]); }
int main( int argc, char *argv[] ) {
std::chrono::time_point<std::chrono::system_clock> start, end;
int N = 1000000; //something big enough
float sp = 0; //Seuil pour les points d'interets
int np = 1000000; //nb point d'interet max
int nt = std::thread::hardware_concurrency();
fs::path full_path = fs::system_complete( fs::path( argv[1] ) );
float dist = 0.22;
float dist2second = 1;
float zmin = -1e20;
float zmax = 1e20;
bool matchAll = false;
bool writePoints = false;
char* outputFileName = 0;
int argumentsIndex = 2;
float anatVal = 0.0;
bool symFlag = false;
int target = -1;
while (argumentsIndex < argc) {
char* key = argv[argumentsIndex];
char *value = argv[argumentsIndex + 1];
if (strcmp(key, "-n") == 0) {
N = atoi(value);
}
if (strcmp(key, "-sp") == 0) {
sp = atof(value);
}
if (strcmp(key, "-np") == 0) {
np = atoi(value);
}
if (strcmp(key, "-nt") == 0) {
nt = atoi(value);
}
if (strcmp(key, "-d") == 0) {
dist = atof(value);
}
if (strcmp(key, "-d2") == 0) {
dist2second = atof(value);
}
if (strcmp(key, "-zmin") == 0) {
zmin = atof(value);
}
if (strcmp(key, "-zmax") == 0) {
zmax = atof(value);
}
if (strcmp(key, "-o") == 0) {
outputFileName = value;
}
if (strcmp(key, "-all") == 0) {
matchAll = true;
}
if (strcmp(key, "-p") == 0) {
writePoints = true;
}
if (strcmp(key, "-anat") == 0){
anatVal = atof(value);
}
if (strcmp(key, "-sym") == 0){
symFlag = true;
argumentsIndex-=1;
}
if (strcmp(key, "-targ") == 0){
target = atoi(value);
}
argumentsIndex += 2;
}
vector< CSV* > csvs;
fs::directory_iterator end_iter;
int i = 0;
vector<v3> rigids;
std::vector<std::string> filenames;
if (fs::is_directory(full_path)) {
for ( fs::directory_iterator dir_itr( full_path );
dir_itr != end_iter;
++dir_itr ) {
if ( fs::is_regular_file( dir_itr->status() ) ) {
i++;
filenames.push_back(dir_itr->path().native());
}
}
} else if ( is_regular_file( full_path ) ) {
std::string line;
ifstream file( full_path.native() );
while(std::getline(file,line)) {
CSVrow row;
std::stringstream lineStream(line);
std::string cell;
std::getline(lineStream,cell,',');
if ( cell.find( "/" ) == 0 ) {
filenames.push_back( cell );
cout << cell << endl;
} else {
filenames.push_back(full_path.parent_path().native() + "/" + cell + ".csv");
cout << full_path.parent_path().native() + cell << endl;
}
v3 point;
point[ 0 ] = point[ 1 ] = point[ 2 ] = 0;
try {
std::getline(lineStream,cell,',');
point[0] = std::stof (cell);
std::getline(lineStream,cell,',');
point[1] = std::stof (cell);
std::getline(lineStream,cell,',');
point[2] = std::stof (cell);
} catch ( ... ) {}
rigids.push_back(point);
}
} else {
cerr << "Bad argument, first arg must be a valid file or a directory" << endl;
return 1;
}
cout << "Found " << filenames.size() << " files, loading : " << fmin(N, filenames.size()) << endl;
start = std::chrono::system_clock::now();
if (filenames.size() > N) filenames.resize(N);
omp_set_num_threads( nt );
int nb = filenames.size();
csvs.resize(nb);
#pragma omp parallel shared(filenames, csvs, cout)
{
//Full list
#pragma omp for schedule(dynamic)
for (auto it = 0 ; it < nb ; ++it) {
string ext = filenames[it].substr(filenames[it].find_last_of(".") + 1);
//cout << filenames[it] << endl;
CSV* mycsv;
if ( ext == "csv")
mycsv = readCSV(filenames[it]);
else if ( ext == "bin")
mycsv = readBinary(filenames[it]);
else if ( ext == "gz")
mycsv = readCSVGZ(filenames[it]);
else {
cerr << "Bad file format : " << ext << endl;
}
float zT = rigids.size() ? rigids[it][2] : 0;
auto pend = remove_if (mycsv->begin(), mycsv->end(),
[zT, zmin, zmax] (CSVrow &val){
float z = val.meta[2] + zT;
return z < zmin || z > zmax;
});
mycsv->erase (pend, mycsv->end());
#pragma omp critical
cout << "image " << it << " rigid : "
<< rigids[it][0] << ", " << rigids[it][1] << ", " << rigids[it][2]
<< " before : " << mycsv->size() << " points, after : " << mycsv->size() << endl << flush;
csvs[it] = mycsv;
}
}
end = std::chrono::system_clock::now();
cout << " : " << std::chrono::duration<float>(end-start).count() << "s" << endl;
start = end;
cout << csvs[ 0 ][ 0 ][ 0 ].desc.size() << " values per descriptor" << endl;
cout << "Sorting and pruning..." << endl;
nb = csvs.size();
#pragma omp parallel shared(filenames, csvs)
{
#pragma omp for schedule(dynamic)
for (auto it = 0 ; it < nb ; ++it) {
auto rit= remove_if (csvs[it]->begin(), csvs[it]->end(), [sp](CSVrow row){
return row.meta[5] < sp;
});
csvs[it]->erase(rit, csvs[it]->end());
if ( csvs[it]->size() > np) {
partial_sort(csvs[it]->begin(), csvs[it]->begin()+np, csvs[it]->end(), compareCSVrow);
csvs[it]->resize(np);
} /*else {
sort(csvs[it]->begin(), csvs[it]->end(), compareCSVrow);
}*/
cout << ". (" << csvs[it]->size() << ")"<< flush;
if ( writePoints ) {
std::stringstream outfilename;
outfilename << "points" << it << ".csv";
cout << " writing " << outfilename.str() << endl;
writeCSV( *csvs[it], outfilename.str().c_str() );
}
}
}
end = std::chrono::system_clock::now();
cout << " : " << std::chrono::duration<float>(end-start).count() << "s" << endl;
start = end;
int sum = 0;
vector< pair<int, int> > indices;
for (int i = 0 ; i < csvs.size()-1 ; i++) {
if (target >= 0){
if (i != target ){
indices.push_back( make_pair(i, target) );
}
} else {
for (int j = i+1 ; j < csvs.size() ; j++) {
indices.push_back( make_pair(i, j) );
}
}
}
vector < vector< MatchVect* > > pairs;
pairs.resize( nb );
for ( auto i = 0; i < nb; i++ ) {
pairs[ i ].resize(nb);
for ( auto j = 0; j < nb; j++ ) pairs[ i ][ j ] = 0;
}
cout << "Pairing... " << endl;
#pragma omp parallel shared(csvs, pairs)
{
#pragma omp for reduction(+:sum) schedule(dynamic)
for (int it = 0 ; it < indices.size() ; it++) {
MatchVect* matches = ComputeMatches(*csvs[ indices[it].first ], *csvs[ indices[it].second ], dist, dist2second, matchAll, anatVal);
if (symFlag){
MatchVect* matchesSym = ComputeMatches(*csvs[ indices[it].second ], *csvs[ indices[it].first ], dist, dist2second, matchAll, anatVal, true);
matches->insert(matches->end(), matchesSym->begin(), matchesSym->end());
}
#pragma omp critical
pairs[ indices[ it ].first ][ indices[ it ].second ] = matches;
sum += matches->size();
cout << "." << flush;
}
}
end = std::chrono::system_clock::now();
cout << " : " << std::chrono::duration<float>(end-start).count() << "s" << endl;
start = end;
cout << "Nb Match : " << sum << endl;
std::stringstream outfilename;
string f = full_path.stem().string();
if (outputFileName) {
string file(outputFileName);
outfilename << file;
} else {
outfilename << "out_" << f << "_" << filenames.size() << ".bin";
}
FILE * file = fopen(outfilename.str().c_str(),"wb");
if (file == NULL) {
cout << "write error : " << outfilename.str() << endl;
exit(1);
}
unsigned short nbAcq = filenames.size();
fwrite(&nbAcq, sizeof(unsigned short), 1, file);
for (auto it = 0 ; it < csvs.size() ; it++) {
// Write Filename
size_t found = filenames[it].find_last_of("/\\");
string currFile = filenames[it].substr(found+1);
unsigned short sizeString = currFile.size();
fwrite(&sizeString, sizeof(unsigned short), 1, file);
fwrite(currFile.c_str(), sizeof(char), currFile.size(), file);
// Write Rigid
v3 tmp;
if (rigids.size() > 0) {
tmp = rigids[it];
} else {
tmp[0] = 0.0; tmp[1] = 0.0; tmp[2] = 0.0;
}
fwrite(tmp.data(), sizeof(double), 3, file);
// Write Points
pointIdType nbPoints = csvs[it]->size();
fwrite(&nbPoints, sizeof(pointIdType), 1, file);
for (auto rowIt = 0 ; rowIt < csvs[it]->size() ; rowIt++) {
vector<float>* data = &csvs[it]->at(rowIt).meta;
fwrite(data->data(), sizeof(float), data->size(), file);
}
}
for ( auto i = 0; i < nb; i++ ) {
for ( auto j = 0; j < nb; j++ ) {
// Write local header
MatchVect* matches = pairs[i][j];
if ( !matches ) continue;
unsigned int size = matches->size();
fwrite(&i, sizeof(unsigned short), 1, file);
fwrite(&j, sizeof(unsigned short), 1, file);
fwrite(&size, sizeof(unsigned int), 1, file);
fwrite(matches->data(), sizeof(Match), size, file);
}
}
fclose(file);
cout << "Output file : " << outfilename.str() << endl;
}
| 22.311143 | 156 | 0.584031 | valette |
cd5175badc9f81aed30a719bd06064466699d7e1 | 615 | cpp | C++ | src/proposers.cpp | greymass/eosio-wps | d109674a7e268db95d94af1c9c4d9d1bf07c93dd | [
"MIT"
] | null | null | null | src/proposers.cpp | greymass/eosio-wps | d109674a7e268db95d94af1c9c4d9d1bf07c93dd | [
"MIT"
] | null | null | null | src/proposers.cpp | greymass/eosio-wps | d109674a7e268db95d94af1c9c4d9d1bf07c93dd | [
"MIT"
] | null | null | null | [[eosio::action]]
void wps::setproposer(const eosio::name proposer, const std::map<name, string> metadata_json )
{
require_auth( proposer );
const eosio::name ram_payer = proposer;
auto proposers_itr = _proposers.find( proposer.value );
if ( proposers_itr == _proposers.end() ) {
_proposers.emplace( ram_payer, [&]( auto& row ) {
row.proposer = proposer;
row.metadata_json = metadata_json;
});
} else {
_proposers.modify( proposers_itr, ram_payer, [&]( auto& row ) {
row.metadata_json = metadata_json;
});
}
}
| 30.75 | 94 | 0.596748 | greymass |
cd52554d57fcf8b2762f6153b3cca3e6402bf011 | 2,528 | cpp | C++ | src/dtkComposerSupport/dtkComposerNodeControl.cpp | eti-nne/dtk | b5095c7a181e7497391a6a1fa0bb37e71dfa4b56 | [
"BSD-3-Clause"
] | null | null | null | src/dtkComposerSupport/dtkComposerNodeControl.cpp | eti-nne/dtk | b5095c7a181e7497391a6a1fa0bb37e71dfa4b56 | [
"BSD-3-Clause"
] | null | null | null | src/dtkComposerSupport/dtkComposerNodeControl.cpp | eti-nne/dtk | b5095c7a181e7497391a6a1fa0bb37e71dfa4b56 | [
"BSD-3-Clause"
] | 1 | 2020-04-21T14:41:52.000Z | 2020-04-21T14:41:52.000Z | /* dtkComposerNodeControl.cpp ---
*
* Author: David Rey
* Copyright (C) 2008-2011 - David Rey, Inria.
* Created: Tue Feb 14 15:40:50 2012 (+0100)
* Version: $Id: cd52554d57fcf8b2762f6153b3cca3e6402bf011 $
* Last-Updated: mer. mars 28 13:58:30 2012 (+0200)
* By: Nicolas Niclausse
* Update #: 31
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkComposerNodeControl.h"
#include "dtkComposerTransmitterVariant.h"
#include <dtkCoreSupport/dtkGlobal.h>
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeControlPrivate definition
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeControlPrivate
{
public:
QList<dtkComposerTransmitterVariant *> input_twins;
QList<dtkComposerTransmitterVariant *> output_twins;
};
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeControl implementation
// /////////////////////////////////////////////////////////////////
dtkComposerNodeControl::dtkComposerNodeControl(void) : dtkComposerNode(), d(new dtkComposerNodeControlPrivate)
{
}
dtkComposerNodeControl::~dtkComposerNodeControl(void)
{
delete d;
d = NULL;
}
void dtkComposerNodeControl::appendInputTwin(dtkComposerTransmitterVariant *twin)
{
if (!d->input_twins.contains(twin))
d->input_twins << twin;
}
void dtkComposerNodeControl::removeInputTwin(dtkComposerTransmitterVariant *twin)
{
d->input_twins.removeOne(twin);
}
void dtkComposerNodeControl::appendOutputTwin(dtkComposerTransmitterVariant *twin)
{
if (!d->output_twins.contains(twin))
d->output_twins << twin;
}
void dtkComposerNodeControl::removeOutputTwin(dtkComposerTransmitterVariant *twin)
{
d->output_twins.removeOne(twin);
}
QList<dtkComposerTransmitterVariant *> dtkComposerNodeControl::inputTwins(void)
{
return d->input_twins;
}
QList<dtkComposerTransmitterVariant *> dtkComposerNodeControl::outputTwins(void)
{
return d->output_twins;
}
void dtkComposerNodeControl::setInputs(void)
{
DTK_DEFAULT_IMPLEMENTATION_NO_MOC;
}
void dtkComposerNodeControl::setOutputs(void)
{
DTK_DEFAULT_IMPLEMENTATION_NO_MOC;
}
void dtkComposerNodeControl::setVariables(void)
{
DTK_DEFAULT_IMPLEMENTATION_NO_MOC;
}
int dtkComposerNodeControl::selectBranch(void)
{
return -1;
}
void dtkComposerNodeControl::begin(void)
{
DTK_DEFAULT_IMPLEMENTATION_NO_MOC;
}
void dtkComposerNodeControl::end(void)
{
DTK_DEFAULT_IMPLEMENTATION_NO_MOC;
}
| 22.371681 | 110 | 0.673259 | eti-nne |
cd52b73af25bbf1ac24f07667db541953bec5d12 | 3,199 | hpp | C++ | code/contrafold/src/ComputationWrapper.hpp | jialiasus2/RNA-Contest-2021 | d8cd340061ac7a70e1c2bba67d36c89cbde2555c | [
"Apache-2.0"
] | null | null | null | code/contrafold/src/ComputationWrapper.hpp | jialiasus2/RNA-Contest-2021 | d8cd340061ac7a70e1c2bba67d36c89cbde2555c | [
"Apache-2.0"
] | null | null | null | code/contrafold/src/ComputationWrapper.hpp | jialiasus2/RNA-Contest-2021 | d8cd340061ac7a70e1c2bba67d36c89cbde2555c | [
"Apache-2.0"
] | null | null | null | //////////////////////////////////////////////////////////////////////
// ComputationWrapper.hpp
//
// This class provides a wrapper around the Computation class that
// provides a framework for translating basic queries into the format
// needed by the Computation class. This class also provides caching
// facilities for preventing redundant computations.
//////////////////////////////////////////////////////////////////////
#ifndef COMPUTATIONWRAPPER_HPP
#define COMPUTATIONWRAPPER_HPP
#include "ComputationEngine.hpp"
//////////////////////////////////////////////////////////////////////
// class ComputationWrapper
//
// Wrapper class for Computation.
//////////////////////////////////////////////////////////////////////
template<class RealT>
class ComputationWrapper
{
ComputationEngine<RealT> &computation_engine;
SharedInfo<RealT> shared_info;
std::vector<NonSharedInfo> nonshared_info;
// the following member variables are used to "cache" work to
// ensure that it is not repeated unnecessarily
bool cached_toggle_use_nonsmooth;
bool cached_toggle_use_loss;
std::vector<int> cached_units;
std::vector<double> cached_w;
std::vector<double> cached_function;
std::vector<double> cached_gradient;
public:
// constructor, destructor
ComputationWrapper(ComputationEngine<RealT> &computation_engine);
~ComputationWrapper();
// retrieve list of work units
std::vector<int> GetAllUnits() const;
// methods to act on vectors of work units
std::vector<int> FilterNonparsable(const std::vector<int> &units);
RealT ComputeSolutionNormBound(const std::vector<int> &units, const std::vector<RealT> &C, RealT log_base);
RealT ComputeGradientNormBound(const std::vector<int> &units, const std::vector<RealT> &C, RealT log_base);
void Predict(const std::vector<int> &units, const std::vector<RealT> &w, RealT gamma, RealT log_base);
RealT ComputeLoss(const std::vector<int> &units, const std::vector<RealT> &w, RealT log_base);
RealT ComputeFunction(const std::vector<int> &units, const std::vector<RealT> &w, bool toggle_use_nonsmooth, bool toggle_use_loss, RealT log_base);
std::vector<RealT> ComputeGradient(const std::vector<int> &units, const std::vector<RealT> &w, bool toggle_use_nonsmooth, bool toggle_use_loss, RealT log_base);
std::vector<RealT> ComputeHessianVectorProduct(const std::vector<int> &units, const std::vector<RealT> &w, const std::vector<RealT> &v, bool toggle_use_loss, RealT log_base);
// for debugging
void SanityCheckGradient(const std::vector<int> &units, const std::vector<RealT> &w);
// getters
const Options &GetOptions() const { return computation_engine.GetOptions(); }
const std::vector<FileDescription> &GetDescriptions() const { return computation_engine.GetDescriptions(); }
InferenceEngine<RealT> &GetInferenceEngine() { return computation_engine.GetInferenceEngine(); }
ParameterManager<RealT> &GetParameterManager() { return computation_engine.GetParameterManager(); }
ComputationEngine<RealT> &GetComputationEngine() { return computation_engine; }
};
#include "ComputationWrapper.ipp"
#endif
| 45.056338 | 178 | 0.682088 | jialiasus2 |
cd53d2245fd7d3e41ff9619ae3d2ceee2f46202d | 1,203 | hpp | C++ | src/terark/io/FileDataIO.hpp | rockeet/terark-zip | 3235373d04b7cf5d584259111b3a057c45cc1708 | [
"BSD-3-Clause"
] | 11 | 2021-11-19T04:57:42.000Z | 2022-03-27T12:44:17.000Z | src/terark/io/FileDataIO.hpp | rockeet/terark-zip | 3235373d04b7cf5d584259111b3a057c45cc1708 | [
"BSD-3-Clause"
] | null | null | null | src/terark/io/FileDataIO.hpp | rockeet/terark-zip | 3235373d04b7cf5d584259111b3a057c45cc1708 | [
"BSD-3-Clause"
] | 1 | 2022-02-17T10:17:01.000Z | 2022-02-17T10:17:01.000Z | #pragma once
#include "DataIO.hpp"
#include "FileStream.hpp"
#include "StreamBuffer.hpp"
namespace terark {
template<class DataIO>
class FileDataInput : public DataIO {
public:
FileStream file;
FileDataInput(const char* fname) : file(fname, "rb") {
this->attach(&file);
}
};
template<class DataIO>
class FileDataOutput : public DataIO {
public:
FileStream file;
FileDataOutput(const char* fname) : file(fname, "wb") {
this->attach(&file);
}
~FileDataOutput() {
this->flush();
this->attach(NULL);
}
};
typedef FileDataInput<NativeDataInput<InputBuffer> > NativeFileDataInput;
typedef FileDataOutput<NativeDataOutput<OutputBuffer> > NativeFileDataOutput;
typedef FileDataInput<PortableDataInput<InputBuffer> > PortableFileDataInput;
typedef FileDataOutput<PortableDataOutput<OutputBuffer> > PortableFileDataOutput;
typedef FileDataInput<BigEndianDataInput<InputBuffer> > BigEndianFileDataInput;
typedef FileDataOutput<BigEndianDataOutput<OutputBuffer> > BigEndianFileDataOutput;
typedef FileDataInput<LittleEndianDataInput<InputBuffer> > LittleEndianFileDataInput;
typedef FileDataOutput<LittleEndianDataOutput<OutputBuffer> > LittleEndianFileDataOutput;
}
| 30.846154 | 90 | 0.784705 | rockeet |
cd53d9496fc95563878a55d0cbd44d8e03ec5bc9 | 5,656 | cpp | C++ | src/ComDriverSpi.cpp | IGB-Germany/IGB-ComDriverSpi | 8ec0b370796f2ff8ec8eb331cc9d2d22fd10aa40 | [
"RSA-MD"
] | null | null | null | src/ComDriverSpi.cpp | IGB-Germany/IGB-ComDriverSpi | 8ec0b370796f2ff8ec8eb331cc9d2d22fd10aa40 | [
"RSA-MD"
] | null | null | null | src/ComDriverSpi.cpp | IGB-Germany/IGB-ComDriverSpi | 8ec0b370796f2ff8ec8eb331cc9d2d22fd10aa40 | [
"RSA-MD"
] | null | null | null | //SPI communication layer
#include "ComDriverSpi.h"
ComDriverSpi::ComDriverSpi()
//Initalization list
: _slaveSelectPin{slaveSelectPin},
_frequency {8000000},
_dataOrder {MSBFIRST},
_dataMode {SPI_MODE0},
_transferOption {transferStartEnd}
{
//start the SPI library
SPI.begin();
//initalize the slave select pin
pinMode(_slaveSelectPin, OUTPUT);
digitalWrite(_slaveSelectPin, HIGH);
}
ComDriverSpi::ComDriverSpi(uint8_t slaveSelectPin)
: _slaveSelectPin(slaveSelectPin),
_frequency {8000000},
_dataOrder {MSBFIRST},
_dataMode {SPI_MODE0},
_transferOption {transferStartEnd}
{
//start the SPI library
SPI.begin();
//initalize the slave select pin
pinMode(_slaveSelectPin, OUTPUT);
digitalWrite(_slaveSelectPin, HIGH);
}
ComDriverSpi::ComDriverSpi(uint8_t slaveSelectPin, uint32_t frequency)
: _slaveSelectPin(slaveSelectPin),
_frequency(frequency),
_dataOrder {MSBFIRST},
_dataMode {SPI_MODE0},
_transferOption {transferStartEnd}
{
//start the SPI library
SPI.begin();
//initalize the slave select pin
pinMode(_slaveSelectPin, OUTPUT);
digitalWrite(_slaveSelectPin, HIGH);
}
void ComDriverSpi::setSlaveSelectPin(uint8_t slaveSelectPin)
{
_slaveSelectPin = slaveSelectPin;
}
uint8_t ComDriverSpi::getSlaveSelectPin()
{
return _slaveSelectPin;
}
void ComDriverSpi::setFrequency(uint32_t frequency)
{
/*SPI_CLOCK_DIV2
SPI_CLOCK_DIV4
SPI_CLOCK_DIV8
SPI_CLOCK_DIV16
SPI_CLOCK_DIV32
SPI_CLOCK_DIV64
SPI_CLOCK_DIV128
*/
_frequency = frequency;
}
uint32_t ComDriverSpi::getFrequency()
{
return _frequency;
}
void ComDriverSpi::setDataMode(uint8_t dataMode)
{
_dataMode = dataMode;
}
uint8_t ComDriverSpi::getDataMode()
{
return _dataMode;
}
void ComDriverSpi::setDataOrder(uint8_t dataOrder)
{
_dataOrder = dataOrder;
}
uint8_t ComDriverSpi::getDataOrder()
{
return _dataOrder;
}
void ComDriverSpi::setTransferOption(transferOption_t transferOption)
{
_transferOption = transferOption;
}
ComDriverSpi::transferOption_t ComDriverSpi::getTransferOption()
{
return _transferOption;
}
bool ComDriverSpi::writeSpi(uint8_t data[], uint32_t sizeToWrite, transferOption_t transferOption)
{
//Set member
_transferOption = transferOption;
//Control the bus
SPI.beginTransaction(SPISettings(_frequency, _dataOrder, _dataMode));
//Select slave by pin low
if (_transferOption == transferStart || _transferOption == transferStartEnd)
{
digitalWrite(_slaveSelectPin, LOW);
}
//send data with datasize
SPI.transfer(data, sizeToWrite);
//Deselect slave by pin high at end of transfer
if (_transferOption == transferEnd || _transferOption == transferStartEnd)
{
digitalWrite(_slaveSelectPin, HIGH);
//Release the bus
SPI.endTransaction();
}
return true;
}
bool ComDriverSpi::readSpi(uint8_t data[], uint32_t sizeToRead, transferOption_t transferOption)
{
//Set member
_transferOption = transferOption;
//Control the bus
SPI.beginTransaction(SPISettings(_frequency, _dataOrder, _dataMode));
//Select slave by pin low
if (_transferOption == transferStart || _transferOption == transferStartEnd)
{
digitalWrite(_slaveSelectPin, LOW);
}
//Read data with datasize
SPI.transfer(data, sizeToRead);
//Deselect slave by pin high at end of transfer
if (_transferOption == transferEnd || _transferOption == transferStartEnd)
{
digitalWrite(_slaveSelectPin, HIGH);
//Release the bus
SPI.endTransaction();
}
return true;
}
bool ComDriverSpi::writeReadSpi(uint8_t dataWrite[], uint32_t sizeToWrite, uint8_t dataRead[], unsigned long sizeToRead, transferOption_t transferOption)
{
_transferOption = transferOption;
//Control the SPI bus
SPI.beginTransaction(SPISettings(_frequency, _dataOrder, _dataMode));
//Select slave by pin low
if (_transferOption == transferStart || _transferOption == transferStartEnd)
{
digitalWrite(_slaveSelectPin, LOW);
}
//send data and datasize
SPI.transfer(dataWrite, sizeToWrite);
SPI.transfer(dataRead, sizeToRead);
//Slave select pin high
if (_transferOption == transferEnd || _transferOption == transferStartEnd)
{
digitalWrite(_slaveSelectPin, HIGH);
//Release the SPI bus
SPI.endTransaction();
}
return true;
}
void ComDriverSpi::startWriteSpiManual(void)
{
//Control the SPI bus
SPI.beginTransaction(SPISettings(_frequency, _dataOrder, _dataMode));
//Slave select pin low
digitalWrite(_slaveSelectPin, LOW);
}
void ComDriverSpi::endWriteSpiManual(void)
{
digitalWrite(_slaveSelectPin, HIGH);
SPI.endTransaction();
}
void ComDriverSpi::writeSpiManual8(uint8_t data)
{
SPI.transfer(data);
}
uint8_t ComDriverSpi::readSpiManual8(void)
{
uint8_t data = 0xff;
return SPI.transfer(data);
}
void ComDriverSpi::writeSpiManual16(uint16_t data)
{
SPI.transfer16(data);
}
uint16_t ComDriverSpi::readSpiManual16(void)
{
uint16_t data = 0xffff;
return SPI.transfer16(data);
}
void ComDriverSpi::writeSpiManual32(uint32_t data)
{
SPI.transfer16(uint16_t(data >> 0xf));
SPI.transfer16(uint16_t(data && 0xffff));
}
uint32_t ComDriverSpi::readSpiManual32(void)
{
uint16_t dataLow = 0xffff;
uint16_t dataHigh = 0xffff;
uint32_t data = 0xffffffff;
dataLow = SPI.transfer16(dataLow);
dataHigh = SPI.transfer16(dataHigh);
data = (uint32_t) dataHigh << 0xf & dataLow;
return data;
}
void ComDriverSpi::writeSpiManual(uint8_t dataWrite[], uint32_t sizeToWrite)
{
SPI.transfer(dataWrite, sizeToWrite);
}
void ComDriverSpi::readSpiManual(uint8_t dataRead[], uint32_t sizeToRead)
{
SPI.transfer(dataRead, sizeToRead);
}
| 21.753846 | 153 | 0.74505 | IGB-Germany |
cd54aba1a846434828957915cdb3972798eb6030 | 11,054 | cpp | C++ | src/wul/store.cpp | OCEANOFANYTHING/writeurl | a3b43a6a6319cc0c46d355cc51319e2a8d1ad031 | [
"MIT"
] | 8 | 2018-01-27T18:24:10.000Z | 2021-05-05T22:13:42.000Z | src/wul/store.cpp | OCEANOFANYTHING/writeurl | a3b43a6a6319cc0c46d355cc51319e2a8d1ad031 | [
"MIT"
] | 3 | 2020-02-20T13:28:53.000Z | 2021-05-06T21:24:13.000Z | src/wul/store.cpp | OCEANOFANYTHING/writeurl | a3b43a6a6319cc0c46d355cc51319e2a8d1ad031 | [
"MIT"
] | 4 | 2018-03-17T17:01:50.000Z | 2021-07-13T17:17:27.000Z | #include <string>
#include <sstream>
#include <vector>
#include <map>
#include <cassert>
#include <rapidjson/reader.h>
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <rapidjson/error/en.h>
#include <writeurl/error.hpp>
#include <writeurl/store.hpp>
#include <writeurl/file.hpp>
#include <iostream> // REMOVE
using namespace writeurl;
namespace {
char char_at_index(int index)
{
assert(index >= 0 && index < 36);
if (index < 10)
return '0' + index;
else
return 'a' + (index - 10);
}
uint_fast64_t parse_uint(const std::string str, std::error_code& ec)
{
if (str.size() == 0) {
ec = Error::store_error;
return 0;
}
char* endptr;
uint_fast64_t result = strtoll(str.c_str(), &endptr, 10);
if (*endptr == '\0')
return result;
ec = Error::store_error;
return 0;
}
std::error_code create_document_dirs(const std::string& store_dir)
{
for (int i = 0; i < 36; ++i) {
char ch_1 = char_at_index(i);
std::string dir_1 = file::resolve(store_dir, std::string{ch_1});
if (!file::exists(dir_1)) {
std::error_code ec = file::mkdir(dir_1);
if (ec)
return ec;
}
for (int j = 0; j < 36; ++j) {
char ch_2 = char_at_index(j);
std::string dir_2 = file::resolve(dir_1, std::string{ch_2});
if (!file::exists(dir_2)) {
std::error_code ec = file::mkdir(dir_2);
if (ec)
return ec;
}
}
}
return std::error_code {};
}
std::string resolve_document_dir(const std::string& store_dir, const std::string& id)
{
assert(id.size() > 2);
std::vector<std::string> components(4);
components[0] = store_dir;
components[1] = id[0];
components[2] = id[1];
components[3] = id;
return file::resolve(components);
}
std::string resolve_ids(const std::string& document_dir)
{
return file::resolve(document_dir, "ids");
}
std::string resolve_noperation(const std::string& document_dir)
{
return file::resolve(document_dir, "noperation");
}
std::string resolve_nstate(const std::string& document_dir)
{
return file::resolve(document_dir, "nstate");
}
class IdsJSONHandler: public rapidjson::BaseReaderHandler<rapidjson::UTF8<>, IdsJSONHandler> {
public:
IdsJSONHandler(Store::Ids& ids):
m_ids {ids}
{
}
bool StartObject()
{
if (m_parser_state != ParserState::ExpectObjectStart)
return false;
m_parser_state = ParserState::ExpectKeyOrObjectEnd;
return true;
}
bool String(const char* str, rapidjson::SizeType size, bool)
{
switch(m_parser_state) {
case ParserState::ExpectObjectStart:
return false;
case ParserState::ExpectKeyOrObjectEnd:
m_parser_state = ParserState::ExpectValue;
m_key = std::string {str, size};
return true;
case ParserState::ExpectValue:
m_parser_state = ParserState::ExpectKeyOrObjectEnd;
m_map.insert(std::make_pair(m_key, std::string {str, size}));
return true;
}
}
bool EndObject(rapidjson::SizeType)
{
if (m_parser_state != ParserState::ExpectKeyOrObjectEnd)
return false;
auto search = m_map.find("id");
if (search == m_map.end())
return false;
m_ids.id = search->second;
search = m_map.find("read");
if (search == m_map.end())
return false;
m_ids.read_password = search->second;
search = m_map.find("write");
if (search == m_map.end())
return false;
m_ids.write_password = search->second;
return true;
}
bool Default()
{
return false;
}
private:
Store::Ids& m_ids;
std::string m_key;
std::map<std::string, std::string> m_map;
enum class ParserState {
ExpectObjectStart,
ExpectKeyOrObjectEnd,
ExpectValue
};
ParserState m_parser_state = ParserState::ExpectObjectStart;
};
void read_id_and_passwords(const std::string& document_dir, Store::Ids& ids, std::error_code& ec)
{
const std::string ids_path = resolve_ids(document_dir);
buffer::Buffer buf;
ec = file::read(ids_path, buf);
if (ec)
return;
rapidjson::Reader reader;
IdsJSONHandler handler {ids};
rapidjson::MemoryStream stream {buf.data(), buf.size()};
if (!reader.Parse(stream, handler)) {
ec = make_error_code(Error::store_json_parser_error);
return;
}
}
void read_noperation(const std::string& document_dir, Store::Ids& ids, std::error_code& ec)
{
const std::string noperation_path = resolve_noperation(document_dir);
buffer::Buffer buf;
ec = file::read(noperation_path, buf);
if (ec)
return;
ids.noperation = parse_uint(buf.to_string(), ec);
return;
}
void read_nstate(const std::string& document_dir, Store::Ids& ids, std::error_code& ec)
{
const std::string nstate_path = resolve_nstate(document_dir);
buffer::Buffer buf;
ec = file::read(nstate_path, buf);
if (ec)
return;
ids.nstate = parse_uint(buf.to_string(), ec);
return;
}
void write_id_and_passwords(const std::string& document_dir,
const std::string& id,
const std::string& read_password,
const std::string& write_password,
std::error_code& ec)
{
const std::string ids_path = resolve_ids(document_dir);
rapidjson::StringBuffer buf;
rapidjson::Writer<rapidjson::StringBuffer> writer {buf};
writer.StartObject();
writer.Key("prefix");
writer.String("text");
writer.Key("id");
writer.String(id.c_str());
writer.Key("read");
writer.String(read_password.c_str());
writer.Key("write");
writer.String(write_password.c_str());
writer.EndObject();
ec = file::write(ids_path, buf.GetString(), buf.GetSize());
return;
}
void write_noperation(const std::string& document_dir, uint_fast64_t noperation, std::error_code& ec)
{
const std::string noperation_path = resolve_noperation(document_dir);
std::ostringstream os;
os << noperation;
ec = file::write(noperation_path, os.str().c_str(), os.str().size());
return;
}
void write_nstate(const std::string& document_dir, uint_fast64_t nstate, std::error_code& ec)
{
const std::string nstate_path = resolve_nstate(document_dir);
std::ostringstream os;
os << nstate;
ec = file::write(nstate_path, os.str().c_str(), os.str().size());
return;
}
} // namespace
Store::Store(const std::string& store_dir):
m_store_dir {store_dir}
{
std::error_code ec = create_document_dirs(store_dir);
if (ec)
throw std::system_error(ec);
}
bool Store::exist(const std::string& id)
{
const std::string document_dir = resolve_document_dir(m_store_dir, id);
return file::exists(document_dir);
}
Store::Ids Store::get_ids(const std::string& id, std::error_code& ec)
{
Ids ids;
const std::string document_dir = resolve_document_dir(m_store_dir, id);
read_id_and_passwords(document_dir, ids, ec);
if (ec)
return {};
assert(id == ids.id);
read_noperation(document_dir, ids, ec);
if (ec)
return {};
read_nstate(document_dir, ids, ec);
if (ec)
return {};
return ids;
}
bool Store::create(const std::string& id,
const std::string& read_password,
const std::string& write_password)
{
if (exist(id))
return false;
const std::string document_dir = resolve_document_dir(m_store_dir, id);
std::error_code ec = file::mkdir(document_dir);
if (ec)
return false;
write_id_and_passwords(document_dir, id, read_password, write_password, ec);
if (ec)
return false;
write_noperation(document_dir, 0, ec);
if (ec)
return false;
write_nstate(document_dir, 0, ec);
if (ec)
return false;
return true;
}
//
//'use strict';
//
//var fs = require('fs');
//
//var ngroup = 100;
//
//var path = function (id) {
// return 'docs/' + id[0] + '/' + id[1] + '/' + id;
//};
//
//var read = function (id, name, json) {
// var content;
//
// content = fs.readFileSync(path(id) + '/' + name, 'utf8');
//
// return json ? JSON.parse(content) : content;
//};
//
//var write = function (id, name, content, json) {
// fs.writeFileSync(path(id) + '/' + name, json ? JSON.stringify(content) : content);
//};
//
//var read_group = function (id, g) {
// return read(id, 'operation-' + g, true);
//};
//
//var write_group = function (id, g, operations) {
// write(id, 'operation-' + g, operations, true);
//};
//
//exports.exist = function (id) {
// var stat;
//
// try {
// stat = fs.statSync(path(id));
// } catch (e) {
// stat = null;
// }
//
// return stat !== null;
//};
//
//exports.create = function (ids, state) {
// fs.mkdirSync(path(ids.id));
// write(ids.id, 'ids', ids, true);
// write(ids.id, 'noperation', 0, true);
// write(ids.id, 'state', state, false);
// write(ids.id, 'nstate', 0, true);
//};
//
//exports.get_ids = function (id) {
// return read(id, 'ids', true);
//};
//
//exports.get_state = function (id) {
// return read(id, 'state', false);
//};
//
//exports.put_state = function (id, state, nstate) {
// write(id, 'state', state, false);
// write(id, 'nstate', nstate, true);
//};
//
//exports.get_nstate = function (id) {
// try {
// return read(id, 'nstate', true);
// } catch (e) {
// return null;
// }
//};
//
//exports.get_noperation = function (id) {
// return read(id, 'noperation', true);
//};
//
//exports.get_operations = function (id, nstart) {
// var noperation, operations, g, group;
//
// noperation = exports.get_noperation(id);
// operations = [];
// while (nstart < noperation) {
// g = Math.floor(nstart / ngroup);
// group = read_group(id, g);
// operations = operations.concat(group.slice(nstart - g * ngroup, Math.min(ngroup, noperation - g * ngroup)));
// nstart = (g + 1) * ngroup;
// }
//
// return operations;
//};
//
//exports.put_operations = function (id, operations) {
// var noperation, g, tail, break_point, group, next_break_point;
//
// noperation = exports.get_noperation(id);
// g = Math.floor((noperation - 1) / ngroup);
// tail = (g + 1) * ngroup - noperation;
// if (tail > 0) {
// break_point = Math.min(tail, operations.length);
// group = read_group(id, g);
// write_group(id, g, group.concat(operations.slice(0, break_point)));
// } else {
// break_point = 0;
// }
//
// while (break_point < operations.length) {
// g = g + 1;
// next_break_point = Math.min(break_point + ngroup, operations.length);
// write_group(id, g, operations.slice(break_point, next_break_point));
// break_point = next_break_point;
// }
//
// write(id, 'noperation', noperation + operations.length, true);
//};
| 24.784753 | 112 | 0.609282 | OCEANOFANYTHING |
cd63c856938b59ff94af080e26edd1af47ed594c | 364 | cpp | C++ | tests/PulseInTest/stdafx.cpp | JustAddWires/galileo-sdk | 1a2b8a884db6ad2d0ba87f2c86c7e768877fa030 | [
"BSD-2-Clause"
] | 1 | 2017-04-22T07:07:35.000Z | 2017-04-22T07:07:35.000Z | tests/PulseInTest/stdafx.cpp | JustAddWires/galileo-sdk | 1a2b8a884db6ad2d0ba87f2c86c7e768877fa030 | [
"BSD-2-Clause"
] | null | null | null | tests/PulseInTest/stdafx.cpp | JustAddWires/galileo-sdk | 1a2b8a884db6ad2d0ba87f2c86c7e768877fa030 | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the BSD 2-Clause License.
// See License.txt in the project root for license information.
// stdafx.cpp : source file that includes just the standard includes
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| 33.090909 | 74 | 0.744505 | JustAddWires |
cd6611326be039f16e08571fcf1326aad74af2ed | 1,387 | cpp | C++ | n-ray tree/429 N-ary Tree Level Order Traversal.cpp | CoderQuinnYoung/leetcode | 6ea15c68124b16824bab9ed2e0e5a40c72eb3db1 | [
"BSD-3-Clause"
] | null | null | null | n-ray tree/429 N-ary Tree Level Order Traversal.cpp | CoderQuinnYoung/leetcode | 6ea15c68124b16824bab9ed2e0e5a40c72eb3db1 | [
"BSD-3-Clause"
] | null | null | null | n-ray tree/429 N-ary Tree Level Order Traversal.cpp | CoderQuinnYoung/leetcode | 6ea15c68124b16824bab9ed2e0e5a40c72eb3db1 | [
"BSD-3-Clause"
] | null | null | null | //
// 429 N-ary Tree Level Order Traversal.cpp
// Leetcode
//
// Created by Quinn on 2020/8/15.
// Copyright © 2020 Quinn. All rights reserved.
//
#include <vector>
#include <queue>
using namespace::std;
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
vector<vector<int>> result_vec;
if (!root) return result_vec;
queue<Node*> node_queue;
node_queue.push(root);
while (!node_queue.empty()) {
size_t size = node_queue.size();
vector<int> curr_level_vec;
for (int i = 0; i < size; ++i) {
Node *curr = node_queue.front();
curr_level_vec.push_back(curr->val);
node_queue.pop();
if (!curr->children.empty()) {
for (Node *node : curr->children) {
if (node) {
node_queue.push(node);
}
}
}
}
result_vec.push_back(curr_level_vec);
}
return result_vec;
}
};
| 22.015873 | 55 | 0.484499 | CoderQuinnYoung |
cd668d5e77b882b1a4c038a6099f963eff2647da | 10,616 | hpp | C++ | trunk/src/app/srs_app_server.hpp | daimaqiao/srs | f729bb9ac484a7ae452090e2583abb348385d2e9 | [
"MIT"
] | 24 | 2016-02-01T02:04:19.000Z | 2021-04-09T22:22:14.000Z | trunk/src/app/srs_app_server.hpp | darcy-shimmer/srs | 14be74ca5ea8f1341900768984798cfdd12f759b | [
"MIT"
] | 1 | 2020-01-02T05:56:07.000Z | 2020-01-02T05:56:07.000Z | trunk/src/app/srs_app_server.hpp | darcy-shimmer/srs | 14be74ca5ea8f1341900768984798cfdd12f759b | [
"MIT"
] | 37 | 2016-02-01T04:22:56.000Z | 2017-06-15T19:55:17.000Z | /*
The MIT License (MIT)
Copyright (c) 2013-2015 SRS(ossrs)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SRS_APP_SERVER_HPP
#define SRS_APP_SERVER_HPP
/*
#include <srs_app_server.hpp>
*/
#include <srs_core.hpp>
#include <vector>
#include <string>
#include <srs_app_st.hpp>
#include <srs_app_reload.hpp>
#include <srs_app_source.hpp>
#include <srs_app_hls.hpp>
#include <srs_app_listener.hpp>
#include <srs_app_conn.hpp>
class SrsServer;
class SrsConnection;
class SrsHttpServeMux;
class SrsHttpServer;
class SrsIngester;
class SrsHttpHeartbeat;
class SrsKbps;
class SrsConfDirective;
class ISrsTcpHandler;
class ISrsUdpHandler;
class SrsUdpListener;
class SrsTcpListener;
#ifdef SRS_AUTO_STREAM_CASTER
class SrsAppCasterFlv;
#endif
// listener type for server to identify the connection,
// that is, use different type to process the connection.
enum SrsListenerType
{
// RTMP client,
SrsListenerRtmpStream = 0,
// HTTP api,
SrsListenerHttpApi = 1,
// HTTP stream, HDS/HLS/DASH
SrsListenerHttpStream = 2,
// UDP stream, MPEG-TS over udp.
SrsListenerMpegTsOverUdp = 3,
// TCP stream, RTSP stream.
SrsListenerRtsp = 4,
// TCP stream, FLV stream over HTTP.
SrsListenerFlv = 5,
};
/**
* the common tcp listener, for RTMP/HTTP server.
*/
class SrsListener
{
protected:
SrsListenerType type;
protected:
std::string ip;
int port;
SrsServer* server;
public:
SrsListener(SrsServer* svr, SrsListenerType t);
virtual ~SrsListener();
public:
virtual SrsListenerType listen_type();
virtual int listen(std::string i, int p) = 0;
};
/**
* tcp listener.
*/
class SrsStreamListener : virtual public SrsListener, virtual public ISrsTcpHandler
{
private:
SrsTcpListener* listener;
public:
SrsStreamListener(SrsServer* server, SrsListenerType type);
virtual ~SrsStreamListener();
public:
virtual int listen(std::string ip, int port);
// ISrsTcpHandler
public:
virtual int on_tcp_client(st_netfd_t stfd);
};
#ifdef SRS_AUTO_STREAM_CASTER
/**
* the tcp listener, for rtsp server.
*/
class SrsRtspListener : virtual public SrsListener, virtual public ISrsTcpHandler
{
private:
SrsTcpListener* listener;
ISrsTcpHandler* caster;
public:
SrsRtspListener(SrsServer* svr, SrsListenerType t, SrsConfDirective* c);
virtual ~SrsRtspListener();
public:
virtual int listen(std::string i, int p);
// ISrsTcpHandler
public:
virtual int on_tcp_client(st_netfd_t stfd);
};
/**
* the tcp listener, for flv stream server.
*/
class SrsHttpFlvListener : virtual public SrsListener, virtual public ISrsTcpHandler
{
private:
SrsTcpListener* listener;
SrsAppCasterFlv* caster;
public:
SrsHttpFlvListener(SrsServer* svr, SrsListenerType t, SrsConfDirective* c);
virtual ~SrsHttpFlvListener();
public:
virtual int listen(std::string i, int p);
// ISrsTcpHandler
public:
virtual int on_tcp_client(st_netfd_t stfd);
};
#endif
/**
* the udp listener, for udp server.
*/
class SrsUdpStreamListener : public SrsListener
{
protected:
SrsUdpListener* listener;
ISrsUdpHandler* caster;
public:
SrsUdpStreamListener(SrsServer* svr, SrsListenerType t, ISrsUdpHandler* c);
virtual ~SrsUdpStreamListener();
public:
virtual int listen(std::string i, int p);
};
/**
* the udp listener, for udp stream caster server.
*/
#ifdef SRS_AUTO_STREAM_CASTER
class SrsUdpCasterListener : public SrsUdpStreamListener
{
public:
SrsUdpCasterListener(SrsServer* svr, SrsListenerType t, SrsConfDirective* c);
virtual ~SrsUdpCasterListener();
};
#endif
/**
* convert signal to io,
* @see: st-1.9/docs/notes.html
*/
class SrsSignalManager : public ISrsEndlessThreadHandler
{
private:
/* Per-process pipe which is used as a signal queue. */
/* Up to PIPE_BUF/sizeof(int) signals can be queued up. */
int sig_pipe[2];
st_netfd_t signal_read_stfd;
private:
SrsServer* _server;
SrsEndlessThread* pthread;
public:
SrsSignalManager(SrsServer* server);
virtual ~SrsSignalManager();
public:
virtual int initialize();
virtual int start();
// interface ISrsEndlessThreadHandler.
public:
virtual int cycle();
private:
// global singleton instance
static SrsSignalManager* instance;
/* Signal catching function. */
/* Converts signal event to I/O event. */
static void sig_catcher(int signo);
};
/**
* the handler to the handle cycle in SRS RTMP server.
*/
class ISrsServerCycle
{
public:
ISrsServerCycle();
virtual ~ISrsServerCycle();
public:
/**
* initialize the cycle handler.
*/
virtual int initialize() = 0;
/**
* do on_cycle while server doing cycle.
*/
virtual int on_cycle(int connections) = 0;
};
/**
* SRS RTMP server, initialize and listen,
* start connection service thread, destroy client.
*/
class SrsServer : virtual public ISrsReloadHandler
, virtual public ISrsSourceHandler
, virtual public IConnectionManager
{
private:
#ifdef SRS_AUTO_HTTP_API
// TODO: FIXME: rename to http_api
SrsHttpServeMux* http_api_mux;
#endif
#ifdef SRS_AUTO_HTTP_SERVER
SrsHttpServer* http_server;
#endif
#ifdef SRS_AUTO_HTTP_CORE
SrsHttpHeartbeat* http_heartbeat;
#endif
#ifdef SRS_AUTO_INGEST
SrsIngester* ingester;
#endif
private:
/**
* the pid file fd, lock the file write when server is running.
* @remark the init.d script should cleanup the pid file, when stop service,
* for the server never delete the file; when system startup, the pid in pid file
* maybe valid but the process is not SRS, the init.d script will never start server.
*/
int pid_fd;
/**
* all connections, connection manager
*/
std::vector<SrsConnection*> conns;
/**
* all listners, listener manager.
*/
std::vector<SrsListener*> listeners;
/**
* signal manager which convert gignal to io message.
*/
SrsSignalManager* signal_manager;
/**
* handle in server cycle.
*/
ISrsServerCycle* handler;
/**
* user send the signal, convert to variable.
*/
bool signal_reload;
bool signal_gmc_stop;
bool signal_gracefully_quit;
// parent pid for asprocess.
int ppid;
public:
SrsServer();
virtual ~SrsServer();
private:
/**
* the destroy is for gmc to analysis the memory leak,
* if not destroy global/static data, the gmc will warning memory leak.
* in service, server never destroy, directly exit when restart.
*/
virtual void destroy();
/**
* when SIGTERM, SRS should do cleanup, for example,
* to stop all ingesters, cleanup HLS and dvr.
*/
virtual void dispose();
// server startup workflow, @see run_master()
public:
/**
* initialize server with callback handler.
* @remark user must free the cycle handler.
*/
virtual int initialize(ISrsServerCycle* cycle_handler);
virtual int initialize_st();
virtual int initialize_signal();
virtual int acquire_pid_file();
virtual int listen();
virtual int register_signal();
virtual int http_handle();
virtual int ingest();
virtual int cycle();
// IConnectionManager
public:
/**
* callback for connection to remove itself.
* when connection thread cycle terminated, callback this to delete connection.
* @see SrsConnection.on_thread_stop().
*/
virtual void remove(SrsConnection* conn);
// server utilities.
public:
/**
* callback for signal manager got a signal.
* the signal manager convert signal to io message,
* whatever, we will got the signo like the orignal signal(int signo) handler.
* @remark, direclty exit for SIGTERM.
* @remark, do reload for SIGNAL_RELOAD.
* @remark, for SIGINT and SIGUSR2:
* no gmc, directly exit.
* for gmc, set the variable signal_gmc_stop, the cycle will return and cleanup for gmc.
*/
virtual void on_signal(int signo);
private:
/**
* the server thread main cycle,
* update the global static data, for instance, the current time,
* the cpu/mem/network statistic.
*/
virtual int do_cycle();
/**
* listen at specified protocol.
*/
virtual int listen_rtmp();
virtual int listen_http_api();
virtual int listen_http_stream();
virtual int listen_stream_caster();
/**
* close the listeners for specified type,
* remove the listen object from manager.
*/
virtual void close_listeners(SrsListenerType type);
/**
* resample the server kbs.
*/
virtual void resample_kbps();
// internal only
public:
/**
* when listener got a fd, notice server to accept it.
* @param type, the client type, used to create concrete connection,
* for instance RTMP connection to serve client.
* @param client_stfd, the client fd in st boxed, the underlayer fd.
*/
virtual int accept_client(SrsListenerType type, st_netfd_t client_stfd);
// interface ISrsReloadHandler.
public:
virtual int on_reload_listen();
virtual int on_reload_pid();
virtual int on_reload_vhost_added(std::string vhost);
virtual int on_reload_vhost_removed(std::string vhost);
virtual int on_reload_http_api_enabled();
virtual int on_reload_http_api_disabled();
virtual int on_reload_http_stream_enabled();
virtual int on_reload_http_stream_disabled();
virtual int on_reload_http_stream_updated();
// interface ISrsSourceHandler
public:
virtual int on_publish(SrsSource* s, SrsRequest* r);
virtual void on_unpublish(SrsSource* s, SrsRequest* r);
};
#endif
| 27.645833 | 97 | 0.710531 | daimaqiao |
cd6757ddc895a22f7328170db729ed46e202f45c | 836 | cpp | C++ | Refureku/Library/Source/TypeInfo/Namespace/NamespaceFragment.cpp | jsoysouvanh/Refureku | 7548cb3b196793119737a51c1cedc136aa60d3ee | [
"MIT"
] | 143 | 2020-04-07T21:38:21.000Z | 2022-03-30T01:06:33.000Z | Refureku/Library/Source/TypeInfo/Namespace/NamespaceFragment.cpp | jsoysouvanh/Refureku | 7548cb3b196793119737a51c1cedc136aa60d3ee | [
"MIT"
] | 7 | 2021-03-30T07:26:21.000Z | 2022-03-28T16:31:02.000Z | Refureku/Library/Source/TypeInfo/Namespace/NamespaceFragment.cpp | jsoysouvanh/Refureku | 7548cb3b196793119737a51c1cedc136aa60d3ee | [
"MIT"
] | 11 | 2020-06-06T09:45:12.000Z | 2022-01-25T17:17:55.000Z | #include "Refureku/TypeInfo/Namespace/NamespaceFragment.h"
#include "Refureku/TypeInfo/Namespace/NamespaceFragmentImpl.h"
#include "Refureku/TypeInfo/Entity/EntityUtility.h"
using namespace rfk;
NamespaceFragment::NamespaceFragment(char const* name, std::size_t id) noexcept:
Entity(new NamespaceFragmentImpl(name, id))
{
}
NamespaceFragment::~NamespaceFragment() noexcept = default;
bool NamespaceFragment::foreachNestedEntity(Visitor<Entity> visitor, void* userData) const
{
return EntityUtility::foreachEntity(getPimpl()->getNestedEntities(), visitor, userData);
}
void NamespaceFragment::addNestedEntity(Entity const* nestedEntity) noexcept
{
getPimpl()->addNestedEntity(nestedEntity);
}
void NamespaceFragment::setNestedEntitiesCapacity(std::size_t capacity) noexcept
{
getPimpl()->setNestedEntitiesCapacity(capacity);
} | 29.857143 | 90 | 0.811005 | jsoysouvanh |
cd67d7be62a612bdc28e6c3071584824715143f1 | 820 | hpp | C++ | Nacro/Offsets.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | null | null | null | Nacro/Offsets.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | null | null | null | Nacro/Offsets.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <iostream>
namespace Offsets
{
uintptr_t GEngineOffset = 0x674AB20; //Gloabal Engine*
uintptr_t GWorldOffset = 0x674CD00; //Global World*
uintptr_t GNamesOffset = 0x66587C8; //Global NameArray*
uintptr_t GUObjectArrayOffset = 0x6661380; //Global ObjectArray-Class*
uintptr_t TUObjectArrayOffset = 0x6661390; //Global ObjectArray*
uintptr_t ProcessEventOffset = 0x13D86E0; //UObject::ProcessEvent()
uintptr_t SCO_IOffset = 0x13DD730; //StaticContructObject_Internal()
uintptr_t SLO_IOffset = 0x13E0180; //StaticLoadObject_Internal()
uintptr_t SpawnActorOffset = 0x137DBC0; //UWorld::SpawnActor()
uintptr_t PlainNameStringOffset = 0x12F0FC0; //FNameEntry::GetPlainNameString()
uintptr_t CGInternalOffset = 0x137D380; //CollectGarbageInternal()
}; | 45.555556 | 82 | 0.760976 | Milxnor |
cd6e1b17fa937a3a3f7acfb7ac91082b43a58f28 | 6,420 | cpp | C++ | website/src/cimage.cpp | Wt-Works/saai.ir | 18b9e75616300994c8d5034f766b6e91c6a48c16 | [
"MIT",
"Unlicense"
] | 1 | 2021-08-28T01:24:22.000Z | 2021-08-28T01:24:22.000Z | website/src/cimage.cpp | Wt-Works/saai.ir | 18b9e75616300994c8d5034f766b6e91c6a48c16 | [
"MIT",
"Unlicense"
] | null | null | null | website/src/cimage.cpp | Wt-Works/saai.ir | 18b9e75616300994c8d5034f766b6e91c6a48c16 | [
"MIT",
"Unlicense"
] | null | null | null | #include <fstream>
#include <string>
#include <cstdlib>
#include <boost/lexical_cast.hpp>
#include <Magick++.h>
#include <b64/encode.h>
//#include <b64/decode.h>
#include "cimage.hpp"
using namespace std;
using namespace Magick;
using namespace SAAIIR;
unsigned int CImage::qDef = 85;
unsigned int CImage::dpiMin = 72;
unsigned int CImage::dpiMax = 96;
unsigned int CImage::sizeMin = 24576;
unsigned int CImage::sizeMax = 98304;
unsigned int CImage::pixMin = 480;
unsigned int CImage::pixMax = 720;
bool CImage::IsValidImage(const string& fileName) {
try {
Image image(fileName);
return true;
}
catch(...) {
}
return false;
}
bool CImage::IsValidImageFormat(const string& fileName) {
try {
Image image(fileName);
if ((image.format().find("JFIF") != string::npos)) {
return true;
}
}
catch(...) {
}
return false;
}
unsigned long CImage::ImageFileSize(const string& fileName) {
try {
Image image(fileName);
return image.fileSize();
}
catch(...) {
}
return 0;
}
bool CImage::IsImageFileSizeTooHigh(const string& fileName) {
if (ImageFileSize(fileName) <= sizeMax) {
return false;
}
return true;
}
bool CImage::IsImageFileSizeTooLow(const string& fileName) {
if (ImageFileSize(fileName) >= sizeMin) {
return false;
}
return true;
}
bool CImage::IsImageResolutionTooHigh(const string& fileName) {
try {
Image image(fileName);
if (image.xResolution() <= dpiMax && image.yResolution() <= dpiMax) {
return false;
}
}
catch(...) {
}
return true;
}
bool CImage::IsImageResolutionTooLow(const string& fileName) {
try {
Image image(fileName);
if (image.xResolution() >= dpiMin && image.yResolution() >= dpiMin) {
return false;
}
}
catch(...) {
}
return true;
}
bool CImage::IsValidImageResolution(const string& fileName) {
try {
Image image(fileName);
if ((image.xResolution() == dpiMin && image.yResolution() == dpiMin) ||
(image.xResolution() == dpiMax && image.yResolution() == dpiMax )) {
return true;
}
}
catch(...) {
}
return false;
}
bool CImage::IsImageSizeTooLow(const string& fileName) {
try {
Image image(fileName);
if (image.columns() >= pixMin && image.rows() >= pixMin) {
return false;
}
}
catch(...) {
}
return true;
}
bool CImage::IsImageSizeTooHigh(const string& fileName) {
try {
Image image(fileName);
if (image.columns() <= pixMax && image.rows() <= pixMax) {
return false;
}
}
catch(...) {
}
return true;
}
void CImage::OptimizeImage(const string& fileName) {
try {
Image image(fileName);
image.magick("JPEG");
image.quality(qDef);
int xRes = 0, yRes = 0;
if (image.xResolution() > dpiMax) {
xRes = dpiMax;
}
else if (image.xResolution() > dpiMin && image.xResolution() < dpiMax) {
xRes = dpiMin;
}
else {
xRes = image.xResolution();
}
if (image.yResolution() > dpiMax) {
yRes = dpiMax;
}
else if (image.yResolution() > dpiMin && image.yResolution() < dpiMax) {
yRes = dpiMin;
}
else {
yRes = image.yResolution();
}
if (xRes != yRes) {
xRes = dpiMin;
yRes = dpiMin;
}
image.resolutionUnits(PixelsPerInchResolution);
image.density(Geometry(xRes, yRes));
unsigned int x = 0, y = 0;
if ((image.columns() >= pixMin && image.columns() <= pixMax) &&
(image.rows() >= pixMin && image.rows() <= pixMax)) {
x = image.columns();
y = image.rows();
}
else {
bool found = false;
for (unsigned int i = pixMin; i <= pixMax; ++i) {
float div = image.columns() / (float)i;
x = image.columns() / div;
y = image.rows() / div;
if ((x >= pixMin && x <= pixMax) &&
(y >= pixMin && y <= pixMax)) {
found = true;
break;
}
}
if (!found) {
x = pixMax;
y = pixMax;
}
}
Geometry g(x, y);
//g.aspect(true);
//image.resize(g);
image.scale(g);
image.write(fileName);
}
catch(...) {
}
}
string CImage::B64Encode(const string& fileName) {
try {
ifstream inStream(fileName.c_str(), ios_base::in | ios_base::binary);
if (!inStream.is_open()) {
return "";
}
srand((unsigned)time(NULL));
string tempFile("../tmp/pic-");
tempFile += boost::lexical_cast<std::string>(rand());
tempFile += ".b64";
ofstream outStream(tempFile.c_str(), ios_base::out | ios_base::binary);
if (!outStream.is_open()) {
return "";
}
base64::encoder enc;
enc.encode(inStream, outStream);
if (inStream.is_open())
inStream.close();
if (outStream.is_open())
outStream.close();
string b64;
ifstream file(tempFile.c_str());
if (file.is_open()) {
string line;
while (!file.eof()) {
getline (file, line);
b64 += line + "\n";
}
file.close();
}
remove(tempFile.c_str());
return b64;
/*ifstream file(fileName.c_str(), ios::in | ios::binary | ios::ate);
if (file.is_open()) {
ifstream::pos_type size;
char *buffer;
size = file.tellg();
buffer = new char [size];
file.seekg (0, ios::beg);
file.read (buffer, size);
file.close();
char *res;
base64::encoder enc(16777216);
enc.encode(buffer, size, res);
delete[] buffer;
return res;
}*/
}
catch (...) {
}
return "";
}
/*
char *CImage::B64Decode(const string& data) {
try {
}
catch (...) {
}
return "";
}
*/
| 21.762712 | 80 | 0.502492 | Wt-Works |
cd7126013e418c21161fe1af438e3e808ab099b5 | 3,724 | cpp | C++ | src/LLC/random.cpp | bibbityjibbity/LLL-TAO | 4073ba412f71bf27d21fd297497a7c276ebd2d67 | [
"MIT"
] | null | null | null | src/LLC/random.cpp | bibbityjibbity/LLL-TAO | 4073ba412f71bf27d21fd297497a7c276ebd2d67 | [
"MIT"
] | null | null | null | src/LLC/random.cpp | bibbityjibbity/LLL-TAO | 4073ba412f71bf27d21fd297497a7c276ebd2d67 | [
"MIT"
] | null | null | null | /*__________________________________________________________________________________________
(c) Hash(BEGIN(Satoshi[2010]), END(Sunny[2012])) == Videlicet[2014] ++
(c) Copyright The Nexus Developers 2014 - 2019
Distributed under the MIT software license, see the accompanying
file COPYING or http://www.opensource.org/licenses/mit-license.php.
"ad vocem populi" - To the Voice of the People
____________________________________________________________________________________________*/
#include <LLC/include/random.h>
#include <openssl/rand.h>
#include <Util/include/convert.h>
#include <Util/include/debug.h>
#include <Util/include/runtime.h>
#ifdef WIN32
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0600 //targeting minimum Windows Vista version for winsock2, etc.
#endif
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1 //prevents windows.h from including winsock.h and messing up winsock2.h definitions we use
#endif
#ifndef NOMINMAX
#define NOMINMAX //prevents windows.h from including min/max and potentially interfering with std::min/std::max
#endif
#include <windows.h>
#else
#include <sys/time.h>
#endif
namespace LLC
{
int64_t GetPerformanceCounter()
{
int64_t nCounter = 0;
#ifdef WIN32
QueryPerformanceCounter((LARGE_INTEGER*)&nCounter);
#else
timeval t;
gettimeofday(&t, nullptr);
nCounter = t.tv_sec * 1000000 + t.tv_usec;
#endif
return nCounter;
}
void RandAddSeed()
{
// Seed with CPU performance counter
int64_t nCounter = GetPerformanceCounter();
RAND_add(&nCounter, sizeof(nCounter), 1.5);
memset(&nCounter, 0, sizeof(nCounter));
}
void RandAddSeedPerfmon()
{
RandAddSeed();
// This can take up to 2 seconds, so only do it every 10 minutes
static int64_t nLastPerfmon;
if(runtime::timestamp() < nLastPerfmon + 10 * 60)
return;
nLastPerfmon = runtime::timestamp();
#ifdef WIN32
// Don't need this on Linux, OpenSSL automatically uses /dev/urandom
// Seed with the entire set of perfmon data
uint8_t pdata[250000];
memset(pdata, 0, sizeof(pdata));
unsigned long nSize = sizeof(pdata);
long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", nullptr, nullptr, pdata, &nSize);
RegCloseKey(HKEY_PERFORMANCE_DATA);
if(ret == ERROR_SUCCESS)
{
RAND_add(pdata, nSize, nSize/100.0);
memset(pdata, 0, nSize);
debug::log(0, convert::DateTimeStrFormat(runtime::timestamp()), " RandAddSeed() ", nSize, " bytes");
}
#endif
}
uint64_t GetRand(uint64_t nMax)
{
if(nMax == 0)
return 0;
// The range of the random source must be a multiple of the modulus
// to give every possible output value an equal possibility
uint64_t nRange = (std::numeric_limits<uint64_t>::max() / nMax) * nMax;
uint64_t nRand = 0;
do
{
RAND_bytes((uint8_t*)&nRand, sizeof(nRand));
}
while(nRand >= nRange);
return (nRand % nMax);
}
int GetRandInt(int nMax)
{
return (int)GetRand(nMax);
}
uint256_t GetRand256()
{
uint256_t hash;
RAND_bytes((uint8_t*)&hash, sizeof(hash));
return hash;
}
uint512_t GetRand512()
{
uint512_t hash;
RAND_bytes((uint8_t*)&hash, sizeof(hash));
return hash;
}
uint1024_t GetRand1024()
{
uint1024_t hash;
RAND_bytes((uint8_t*)&hash, sizeof(hash));
return hash;
}
}
| 26.225352 | 121 | 0.632653 | bibbityjibbity |
cd73093798e8b85089a23bf06d81bdb6e78aefd7 | 35,314 | hpp | C++ | stan/math/rev/core/var.hpp | bayesmix-dev/math | 3616f7195adc95ef8e719a2af845d61102bc9272 | [
"BSD-3-Clause"
] | 1 | 2020-06-14T14:33:37.000Z | 2020-06-14T14:33:37.000Z | stan/math/rev/core/var.hpp | bayesmix-dev/math | 3616f7195adc95ef8e719a2af845d61102bc9272 | [
"BSD-3-Clause"
] | null | null | null | stan/math/rev/core/var.hpp | bayesmix-dev/math | 3616f7195adc95ef8e719a2af845d61102bc9272 | [
"BSD-3-Clause"
] | 1 | 2020-05-10T12:55:07.000Z | 2020-05-10T12:55:07.000Z | #ifndef STAN_MATH_REV_CORE_VAR_HPP
#define STAN_MATH_REV_CORE_VAR_HPP
#include <stan/math/rev/core/vari.hpp>
#include <stan/math/rev/core/grad.hpp>
#include <stan/math/rev/core/chainable_alloc.hpp>
#include <stan/math/prim/meta.hpp>
#include <stan/math/rev/meta/is_vari.hpp>
#include <stan/math/rev/meta/arena_type.hpp>
#include <stan/math/rev/core/reverse_pass_callback.hpp>
#include <ostream>
#include <vector>
#ifdef STAN_OPENCL
#include <stan/math/opencl/rev/vari.hpp>
#endif
namespace stan {
namespace math {
// forward declare
template <typename Vari>
static void grad(Vari* vi);
/**
* Independent (input) and dependent (output) variables for gradients.
*
* This class acts as a smart pointer, with resources managed by
* an arena-based memory manager scoped to a single gradient
* calculation.
*
* A var is constructed with a type `T` and used like any
* other scalar. Arithmetical functions like negation, addition,
* and subtraction, as well as a range of mathematical functions
* like exponentiation and powers are overridden to operate on
* var values objects.
* @tparam T An Floating point type.
*/
template <typename T>
class var_value<T, require_floating_point_t<T>> {
public:
using value_type = std::decay_t<T>; // type in vari_value.
using vari_type = vari_value<value_type>;
/**
* Pointer to the implementation of this variable.
*
* This value should not be modified, but may be accessed in
* <code>var</code> operators to construct `vari_value<T>`
* instances.
*/
vari_type* vi_;
/**
* Return `true` if this variable has been
* declared, but not been defined. Any attempt to use an
* undefined variable's value or adjoint will result in a
* segmentation fault.
*
* @return <code>true</code> if this variable does not yet have
* a defined variable.
*/
inline bool is_uninitialized() { return (vi_ == nullptr); }
/**
* Construct a variable for later assignment.
*
* This is implemented as a no-op, leaving the underlying implementation
* dangling. Before an assignment, the behavior is thus undefined just
* as for a basic double.
*/
var_value() : vi_(nullptr) {}
/**
* Construct a variable from the specified floating point argument
* by constructing a new `vari_value<value_type>`. This constructor is only
* valid when `S` is convertible to this `vari_value`'s `value_type`.
* @tparam S A type that is convertible to `value_type`.
* @param x Value of the variable.
*/
template <typename S, require_convertible_t<S&, value_type>* = nullptr>
var_value(S x) : vi_(new vari_type(x, false)) {} // NOLINT
/**
* Construct a variable from a pointer to a variable implementation.
* @param vi A vari_value pointer.
*/
var_value(vari_type* vi) : vi_(vi) {} // NOLINT
/**
* Return a constant reference to the value of this variable.
*
* @return The value of this variable.
*/
inline const auto& val() const { return vi_->val(); }
/**
* Return a reference of the derivative of the root expression with
* respect to this expression. This method only works
* after one of the `grad()` methods has been
* called.
*
* @return Adjoint for this variable.
*/
inline auto& adj() const { return vi_->adj(); }
/**
* Return a reference to the derivative of the root expression with
* respect to this expression. This method only works
* after one of the `grad()` methods has been
* called.
*
* @return Adjoint for this variable.
*/
inline auto& adj() { return vi_->adj_; }
/**
* Compute the gradient of this (dependent) variable with respect to
* the specified vector of (independent) variables, assigning the
* specified vector to the gradient.
*
* The grad() function does <i>not</i> recover memory. In Stan
* 2.4 and earlier, this function did recover memory.
*
* @tparam CheckContainer Not set by user. The default value of value_type
* is used to require that grad is only available for scalar `var_value`
* types.
* @param x Vector of independent variables.
* @param g Gradient vector of partial derivatives of this
* variable with respect to x.
*/
inline void grad(std::vector<var_value<T>>& x, std::vector<value_type>& g) {
stan::math::grad(vi_);
g.resize(x.size());
for (size_t i = 0; i < x.size(); ++i) {
g[i] = x[i].vi_->adj_;
}
}
/**
* Compute the gradient of this (dependent) variable with respect
* to all (independent) variables.
*
* @tparam CheckContainer Not set by user. The default value of value_type
* is used to require that grad is only available for scalar `var_value`
* types.
* The grad() function does <i>not</i> recover memory.
*/
void grad() { stan::math::grad(vi_); }
// POINTER OVERRIDES
/**
* Return a reference to underlying implementation of this variable.
*
* If <code>x</code> is of type <code>var</code>, then applying
* this operator, <code>*x</code>, has the same behavior as
* <code>*(x.vi_)</code>.
*
* <i>Warning</i>: The returned reference does not track changes to
* this variable.
*
* @return variable
*/
inline vari_type& operator*() { return *vi_; }
/**
* Return a pointer to the underlying implementation of this variable.
*
* If <code>x</code> is of type <code>var</code>, then applying
* this operator, <code>x-></code>, behaves the same way as
* <code>x.vi_-></code>.
*
* <i>Warning</i>: The returned result does not track changes to
* this variable.
*/
inline vari_type* operator->() { return vi_; }
// COMPOUND ASSIGNMENT OPERATORS
/**
* The compound add/assignment operator for variables (C++).
*
* If this variable is a and the argument is the variable b,
* then (a += b) behaves exactly the same way as (a = a + b),
* creating an intermediate variable representing (a + b).
*
* @param b The variable to add to this variable.
* @return The result of adding the specified variable to this variable.
*/
inline var_value<T>& operator+=(const var_value<T>& b);
/**
* The compound add/assignment operator for scalars (C++).
*
* If this variable is a and the argument is the scalar b, then
* (a += b) behaves exactly the same way as (a = a + b). Note
* that the result is an assignable lvalue.
*
* @param b The scalar to add to this variable.
* @return The result of adding the specified variable to this variable.
*/
inline var_value<T>& operator+=(T b);
/**
* The compound subtract/assignment operator for variables (C++).
*
* If this variable is a and the argument is the variable b,
* then (a -= b) behaves exactly the same way as (a = a - b).
* Note that the result is an assignable lvalue.
*
* @param b The variable to subtract from this variable.
* @return The result of subtracting the specified variable from
* this variable.
*/
inline var_value<T>& operator-=(const var_value<T>& b);
/**
* The compound subtract/assignment operator for scalars (C++).
*
* If this variable is a and the argument is the scalar b, then
* (a -= b) behaves exactly the same way as (a = a - b). Note
* that the result is an assignable lvalue.
*
* @param b The scalar to subtract from this variable.
* @return The result of subtracting the specified variable from this
* variable.
*/
inline var_value<T>& operator-=(T b);
/**
* The compound multiply/assignment operator for variables (C++).
*
* If this variable is a and the argument is the variable b,
* then (a *= b) behaves exactly the same way as (a = a * b).
* Note that the result is an assignable lvalue.
*
* @param b The variable to multiply this variable by.
* @return The result of multiplying this variable by the
* specified variable.
*/
inline var_value<T>& operator*=(const var_value<T>& b);
/**
* The compound multiply/assignment operator for scalars (C++).
*
* If this variable is a and the argument is the scalar b, then
* (a *= b) behaves exactly the same way as (a = a * b). Note
* that the result is an assignable lvalue.
*
* @param b The scalar to multiply this variable by.
* @return The result of multiplying this variable by the specified
* variable.
*/
inline var_value<T>& operator*=(T b);
/**
* The compound divide/assignment operator for variables (C++). If this
* variable is a and the argument is the variable b, then (a /= b)
* behaves exactly the same way as (a = a / b). Note that the
* result is an assignable lvalue.
*
* @param b The variable to divide this variable by.
* @return The result of dividing this variable by the
* specified variable.
*/
inline var_value<T>& operator/=(const var_value<T>& b);
/**
* The compound divide/assignment operator for scalars (C++).
*
* If this variable is a and the argument is the scalar b, then
* (a /= b) behaves exactly the same way as (a = a / b). Note
* that the result is an assignable lvalue.
*
* @param b The scalar to divide this variable by.
* @return The result of dividing this variable by the specified
* variable.
*/
inline var_value<T>& operator/=(T b);
/**
* Write the value of this autodiff variable and its adjoint to
* the specified output stream.
*
* @param os Output stream to which to write.
* @param v Variable to write.
* @return Reference to the specified output stream.
*/
friend std::ostream& operator<<(std::ostream& os, const var_value<T>& v) {
if (v.vi_ == nullptr) {
return os << "uninitialized";
}
return os << v.val();
}
};
/**
* Independent (input) and dependent (output) variables for gradients.
*
* This class acts as a smart pointer, with resources managed by
* an arena-based memory manager scoped to a single gradient
* calculation.
*
* A var is constructed with a type `T` and used like any
* other scalar. Arithmetical functions like negation, addition,
* and subtraction, as well as a range of mathematical functions
* like exponentiation and powers are overridden to operate on
* var values objects.
* @tparam T An Floating point type.
*/
template <typename T>
class var_value<
T, require_t<bool_constant<is_eigen<T>::value || is_matrix_cl<T>::value>>> {
static_assert(
std::is_floating_point<value_type_t<T>>::value,
"The template for must be a floating point or a container holding"
" floating point types");
public:
using value_type = T; // type in vari_value.
using vari_type = std::conditional_t<is_plain_type<value_type>::value,
vari_value<value_type>, vari_view<T>>;
static constexpr int RowsAtCompileTime{vari_type::RowsAtCompileTime};
static constexpr int ColsAtCompileTime{vari_type::ColsAtCompileTime};
/**
* Pointer to the implementation of this variable.
*
* This value should not be modified, but may be accessed in
* <code>var</code> operators to construct `vari_value<T>`
* instances.
*/
vari_type* vi_;
/**
* Return `true` if this variable has been
* declared, but not been defined. Any attempt to use an
* undefined variable's value or adjoint will result in a
* segmentation fault.
*
* @return <code>true</code> if this variable does not yet have
* a defined variable.
*/
inline bool is_uninitialized() { return (vi_ == nullptr); }
/**
* Construct a variable for later assignment.
*
* This is implemented as a no-op, leaving the underlying implementation
* dangling. Before an assignment, the behavior is thus undefined just
* as for a basic double.
*/
var_value() : vi_(nullptr) {}
/**
* Construct a variable from the specified floating point argument
* by constructing a new `vari_value<value_type>`. This constructor is only
* valid when `S` is convertible to this `vari_value`'s `value_type`.
* @tparam S A type that is convertible to `value_type`.
* @param x Value of the variable.
*/
template <typename S, require_assignable_t<value_type, S>* = nullptr>
var_value(S&& x) : vi_(new vari_type(std::forward<S>(x), false)) {} // NOLINT
/**
* Copy constructor for var_val.
* @tparam S type of the value in the `var_value` to assing
* @param other the value to assign
* @return this
*/
template <typename S, require_assignable_t<value_type, S>* = nullptr,
require_all_plain_type_t<T, S>* = nullptr>
var_value(const var_value<S>& other) : vi_(other.vi_) {}
/**
* Construct a `var_value` with a plain type
* from another `var_value` containing an expression.
* @tparam S type of the value in the `var_value` to assing
* @param other the value to assign
* @return this
*/
template <typename S, typename T_ = T,
require_assignable_t<value_type, S>* = nullptr,
require_not_plain_type_t<S>* = nullptr,
require_plain_type_t<T_>* = nullptr>
var_value(const var_value<S>& other) : vi_(new vari_type(other.vi_->val_)) {
reverse_pass_callback(
[this_vi = this->vi_, other_vi = other.vi_]() mutable {
other_vi->adj_ += this_vi->adj_;
});
}
/**
* Construct a variable from a pointer to a variable implementation.
* @param vi A vari_value pointer.
*/
var_value(vari_type* vi) : vi_(vi) {} // NOLINT
/**
* Return a constant reference to the value of this variable.
*
* @return The value of this variable.
*/
inline const auto& val() const { return vi_->val(); }
inline auto& val_op() { return vi_->val(); }
/**
* Return a reference to the derivative of the root expression with
* respect to this expression. This method only works
* after one of the `grad()` methods has been
* called.
*
* @return Adjoint for this variable.
*/
inline auto& adj() { return vi_->adj(); }
inline auto& adj() const { return vi_->adj(); }
inline auto& adj_op() { return vi_->adj(); }
inline Eigen::Index rows() const { return vi_->val_.rows(); }
inline Eigen::Index cols() const { return vi_->val_.cols(); }
inline Eigen::Index size() const { return vi_->val_.size(); }
// POINTER OVERRIDES
/**
* Return a reference to underlying implementation of this variable.
*
* If <code>x</code> is of type <code>var</code>, then applying
* this operator, <code>*x</code>, has the same behavior as
* <code>*(x.vi_)</code>.
*
* <i>Warning</i>: The returned reference does not track changes to
* this variable.
*
* @return variable
*/
inline vari_type& operator*() { return *vi_; }
/**
* Return a pointer to the underlying implementation of this variable.
*
* If <code>x</code> is of type <code>var</code>, then applying
* this operator, <code>x-></code>, behaves the same way as
* <code>x.vi_-></code>.
*
* <i>Warning</i>: The returned result does not track changes to
* this variable.
*/
inline vari_type* operator->() { return vi_; }
// COMPOUND ASSIGNMENT OPERATORS
/**
* The compound add/assignment operator for variables (C++).
*
* If this variable is a and the argument is the variable b,
* then (a += b) behaves exactly the same way as (a = a + b),
* creating an intermediate variable representing (a + b).
*
* @param b The variable to add to this variable.
* @return The result of adding the specified variable to this variable.
*/
inline var_value<T>& operator+=(const var_value<T>& b);
/**
* The compound add/assignment operator for scalars (C++).
*
* If this variable is a and the argument is the scalar b, then
* (a += b) behaves exactly the same way as (a = a + b). Note
* that the result is an assignable lvalue.
*
* @param b The scalar to add to this variable.
* @return The result of adding the specified variable to this variable.
*/
inline var_value<T>& operator+=(T b);
/**
* The compound subtract/assignment operator for variables (C++).
*
* If this variable is a and the argument is the variable b,
* then (a -= b) behaves exactly the same way as (a = a - b).
* Note that the result is an assignable lvalue.
*
* @param b The variable to subtract from this variable.
* @return The result of subtracting the specified variable from
* this variable.
*/
template <typename S, require_st_var<S>* = nullptr>
inline var_value<T>& operator-=(const S& b);
/**
* The compound subtract/assignment operator for scalars (C++).
*
* If this variable is a and the argument is the scalar b, then
* (a -= b) behaves exactly the same way as (a = a - b). Note
* that the result is an assignable lvalue.
*
* @param b The scalar to subtract from this variable.
* @return The result of subtracting the specified variable from this
* variable.
*/
template <typename S, require_st_arithmetic<S>* = nullptr>
inline var_value<T>& operator-=(const S& b);
/**
* The compound multiply/assignment operator for variables (C++).
*
* If this variable is a and the argument is the variable b,
* then (a *= b) behaves exactly the same way as (a = a * b).
* Note that the result is an assignable lvalue.
*
* @param b The variable to multiply this variable by.
* @return The result of multiplying this variable by the
* specified variable.
*/
inline var_value<T>& operator*=(const var_value<T>& b);
/**
* The compound multiply/assignment operator for scalars (C++).
*
* If this variable is a and the argument is the scalar b, then
* (a *= b) behaves exactly the same way as (a = a * b). Note
* that the result is an assignable lvalue.
*
* @param b The scalar to multiply this variable by.
* @return The result of multiplying this variable by the specified
* variable.
*/
inline var_value<T>& operator*=(T b);
/**
* The compound divide/assignment operator for variables (C++). If this
* variable is a and the argument is the variable b, then (a /= b)
* behaves exactly the same way as (a = a / b). Note that the
* result is an assignable lvalue.
*
* @param b The variable to divide this variable by.
* @return The result of dividing this variable by the
* specified variable.
*/
inline var_value<T>& operator/=(const var_value<T>& b);
/**
* The compound divide/assignment operator for scalars (C++).
*
* If this variable is a and the argument is the scalar b, then
* (a /= b) behaves exactly the same way as (a = a / b). Note
* that the result is an assignable lvalue.
*
* @param b The scalar to divide this variable by.
* @return The result of dividing this variable by the specified
* variable.
*/
inline var_value<T>& operator/=(T b);
/**
* A block view of the underlying Eigen matrices.
* @param start_row Starting row of block.
* @param start_col Starting columns of block.
* @param num_rows Number of rows to return.
* @param num_cols Number of columns to return.
*/
inline auto block(Eigen::Index start_row, Eigen::Index start_col,
Eigen::Index num_rows, Eigen::Index num_cols) const {
using vari_sub
= decltype(vi_->block(start_row, start_col, num_rows, num_cols));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(
new vari_sub(vi_->block(start_row, start_col, num_rows, num_cols)));
}
inline auto block(Eigen::Index start_row, Eigen::Index start_col,
Eigen::Index num_rows, Eigen::Index num_cols) {
using vari_sub
= decltype(vi_->block(start_row, start_col, num_rows, num_cols));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(
new vari_sub(vi_->block(start_row, start_col, num_rows, num_cols)));
}
/**
* View transpose of eigen matrix.
*/
inline auto transpose() const {
using vari_sub = decltype(vi_->transpose());
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->transpose()));
}
inline auto transpose() {
using vari_sub = decltype(vi_->transpose());
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->transpose()));
}
/**
* View of the head of Eigen vector types.
* @param n Number of elements to return from top of vector.
*/
inline auto head(Eigen::Index n) const {
using vari_sub = decltype(vi_->head(n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->head(n)));
}
inline auto head(Eigen::Index n) {
using vari_sub = decltype(vi_->head(n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->head(n)));
}
/**
* View of the tail of the Eigen vector types.
* @param n Number of elements to return from bottom of vector.
*/
inline auto tail(Eigen::Index n) const {
using vari_sub = decltype(vi_->tail(n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->tail(n)));
}
inline auto tail(Eigen::Index n) {
using vari_sub = decltype(vi_->tail(n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->tail(n)));
}
/**
* View block of N elements starting at position `i`
* @param i Starting position of block.
* @param n Number of elements in block
*/
inline auto segment(Eigen::Index i, Eigen::Index n) const {
using vari_sub = decltype(vi_->segment(i, n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->segment(i, n)));
}
inline auto segment(Eigen::Index i, Eigen::Index n) {
using vari_sub = decltype(vi_->segment(i, n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->segment(i, n)));
}
/**
* View row of eigen matrices.
* @param i Row index to slice.
*/
inline auto row(Eigen::Index i) const {
using vari_sub = decltype(vi_->row(i));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->row(i)));
}
inline auto row(Eigen::Index i) {
using vari_sub = decltype(vi_->row(i));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->row(i)));
}
/**
* View column of eigen matrices
* @param i Column index to slice
*/
inline auto col(Eigen::Index i) const {
using vari_sub = decltype(vi_->col(i));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->col(i)));
}
inline auto col(Eigen::Index i) {
using vari_sub = decltype(vi_->col(i));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->col(i)));
}
/**
* View element of eigen matrices. This creates a new
* vari_value<double> so unlike the other views this subset will not
* have the same adjoints as the original matrix and must be propogated
* back.
* @param i Element to access
*/
inline auto coeff(Eigen::Index i) const {
using vari_sub = decltype(vi_->coeff(i));
vari_sub* vari_coeff = new vari_sub(vi_->coeff(i));
reverse_pass_callback([this_vi = this->vi_, vari_coeff, i]() {
this_vi->adj_.coeffRef(i) += vari_coeff->adj_;
});
return var_value<value_type_t<vari_sub>>(vari_coeff);
}
inline auto coeff(Eigen::Index i) {
using vari_sub = decltype(vi_->coeff(i));
vari_sub* vari_coeff = new vari_sub(vi_->coeff(i));
reverse_pass_callback([this_vi = this->vi_, vari_coeff, i]() {
this_vi->adj_.coeffRef(i) += vari_coeff->adj_;
});
return var_value<value_type_t<vari_sub>>(vari_coeff);
}
/**
* View element of eigen matrices. This creates a new
* vari_value<double> so unlike the other views this subset will not
* have the same adjoints as the original matrix and must be propogated
* back.
* @param i Row to access
* @param j Column to access
*/
inline auto coeff(Eigen::Index i, Eigen::Index j) const {
using vari_sub = decltype(vi_->coeff(i, j));
vari_sub* vari_coeff = new vari_sub(vi_->coeff(i, j));
reverse_pass_callback([this_vi = this->vi_, vari_coeff, i, j]() {
this_vi->adj_.coeffRef(i, j) += vari_coeff->adj_;
});
return var_value<value_type_t<vari_sub>>(vari_coeff);
}
inline auto coeff(Eigen::Index i, Eigen::Index j) {
using vari_sub = decltype(vi_->coeff(i, j));
vari_sub* vari_coeff = new vari_sub(vi_->coeff(i, j));
reverse_pass_callback([this_vi = this->vi_, vari_coeff, i, j]() {
this_vi->adj_.coeffRef(i, j) += vari_coeff->adj_;
});
return var_value<value_type_t<vari_sub>>(vari_coeff);
}
/**
* View element of eigen matrices. This creates a new
* vari_value<double> so unlike the other views this subset will not
* have the same adjoints as the original matrix and must be propogated
* back.
* @param i Element to access
*/
inline auto operator()(Eigen::Index i) const { return this->coeff(i); }
inline auto operator()(Eigen::Index i) { return this->coeff(i); }
/**
* View element of eigen matrices. This creates a new
* vari_value<double> so unlike the other views this subset will not
* have the same adjoints as the original matrix and must be propogated
* back.
* @param i Row to access
* @param j Column to access
*/
inline auto operator()(Eigen::Index i, Eigen::Index j) const {
return this->coeff(i, j);
}
inline auto operator()(Eigen::Index i, Eigen::Index j) {
return this->coeff(i, j);
}
/**
* View element of eigen matrices. This creates a new
* vari_value<double> so unlike the other views this subset will not
* have the same adjoints as the original matrix and must be propogated
* back.
* @param i Element to access
*/
inline auto coeffRef(Eigen::Index i) const { return this->coeff(i); }
inline auto coeffRef(Eigen::Index i) { return this->coeff(i); }
/**
* View element of eigen matrices. This creates a new
* vari_value<double> so unlike the other views this subset will not
* have the same adjoints as the original matrix and must be propogated
* back.
* @param i Row to access
* @param j Column to access
*/
inline auto coeffRef(Eigen::Index i, Eigen::Index j) const {
return this->coeff(i, j);
}
inline auto coeffRef(Eigen::Index i, Eigen::Index j) {
return this->coeff(i, j);
}
/**
* Return an expression that operates on the rows of the matrix `vari`
*/
inline auto rowwise_reverse() const {
using vari_sub = decltype(vi_->rowwise_reverse());
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->rowwise_reverse()));
}
inline auto rowwise_reverse() {
using vari_sub = decltype(vi_->rowwise_reverse());
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->rowwise_reverse()));
}
/**
* Return an expression that operates on the columns of the matrix `vari`
*/
inline auto colwise_reverse() const {
using vari_sub = decltype(vi_->colwise_reverse());
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->colwise_reverse()));
}
inline auto colwise_reverse() {
using vari_sub = decltype(vi_->colwise_reverse());
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->colwise_reverse()));
}
/**
* Return an expression an expression to reverse the order of the coefficients
* inside of a `vari` matrix
*/
inline auto reverse() const {
using vari_sub = decltype(vi_->reverse());
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->reverse()));
}
inline auto reverse() {
using vari_sub = decltype(vi_->reverse());
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->reverse()));
}
/**
* Return a block consisting of the top rows
* @param n Number of rows
*/
inline auto topRows(Eigen::Index n) const {
using vari_sub = decltype(vi_->topRows(n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->topRows(n)));
}
inline auto topRows(Eigen::Index n) {
using vari_sub = decltype(vi_->topRows(n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->topRows(n)));
}
/**
* Return a block consisting of the bottom rows
* @param n Number of rows
*/
inline auto bottomRows(Eigen::Index n) const {
using vari_sub = decltype(vi_->bottomRows(n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->bottomRows(n)));
}
inline auto bottomRows(Eigen::Index n) {
using vari_sub = decltype(vi_->bottomRows(n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->bottomRows(n)));
}
/**
* Return a block consisting of rows in the middle.
* @param start_row Starting row index
* @param n Number of rows
*/
inline auto middleRows(Eigen::Index start_row, Eigen::Index n) const {
using vari_sub = decltype(vi_->middleRows(start_row, n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->middleRows(start_row, n)));
}
inline auto middleRows(Eigen::Index start_row, Eigen::Index n) {
using vari_sub = decltype(vi_->middleRows(start_row, n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->middleRows(start_row, n)));
}
/**
* Return a block consisting of the left-most columns
* @param n Number of columns
*/
inline auto leftCols(Eigen::Index n) const {
using vari_sub = decltype(vi_->leftCols(n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->leftCols(n)));
}
inline auto leftCols(Eigen::Index n) {
using vari_sub = decltype(vi_->leftCols(n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->leftCols(n)));
}
/**
* Return a block consisting of the right-most columns
* @param n Number of columns
*/
inline auto rightCols(Eigen::Index n) const {
using vari_sub = decltype(vi_->rightCols(n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->rightCols(n)));
}
inline auto rightCols(Eigen::Index n) {
using vari_sub = decltype(vi_->rightCols(n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->rightCols(n)));
}
/**
* Return a block consisting of columns in the middle.
* @param start_col Starting column index
* @param n Number of columns
*/
inline auto middleCols(Eigen::Index start_col, Eigen::Index n) const {
using vari_sub = decltype(vi_->middleCols(start_col, n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->middleCols(start_col, n)));
}
inline auto middleCols(Eigen::Index start_col, Eigen::Index n) {
using vari_sub = decltype(vi_->middleCols(start_col, n));
using var_sub = var_value<value_type_t<vari_sub>>;
return var_sub(new vari_sub(vi_->middleCols(start_col, n)));
}
/**
* Write the value of this autodiff variable and its adjoint to
* the specified output stream.
*
* @param os Output stream to which to write.
* @param v Variable to write.
* @return Reference to the specified output stream.
*/
friend std::ostream& operator<<(std::ostream& os, const var_value<T>& v) {
if (v.vi_ == nullptr) {
return os << "uninitialized";
}
return os << v.val();
}
/**
* Returns number of rows. Only available if `T` is a matrix.
* @return number of rows.
*/
template <typename U = T,
require_any_t<is_eigen<U>, is_matrix_cl<U>>* = nullptr>
inline auto rows() const {
return vi_->rows();
}
/**
* Returns number of columns. Only available if `T` is a matrix.
* @return number of columns.
*/
template <typename U = T,
require_any_t<is_eigen<U>, is_matrix_cl<U>>* = nullptr>
inline auto cols() const {
return vi_->cols();
}
/**
* Assignment of another plain var value, when this also contains a plain
* type.
* @tparam S type of the value in the `var_value` to assing
* @param other the value to assign
* @return this
*/
template <typename S, require_assignable_t<value_type, S>* = nullptr,
require_all_plain_type_t<T, S>* = nullptr>
inline var_value<T>& operator=(const var_value<S>& other) {
vi_ = other.vi_;
return *this;
}
/**
* Assignment of another var value, when either this or the other one does not
* contain a plain type.
* @tparam S type of the value in the `var_value` to assing
* @param other the value to assign
* @return this
*/
template <typename S, typename T_ = T,
require_assignable_t<value_type, S>* = nullptr,
require_any_not_plain_type_t<T_, S>* = nullptr>
inline var_value<T>& operator=(const var_value<S>& other) {
arena_t<plain_type_t<T>> prev_val = vi_->val_;
vi_->val_ = other.val();
// no need to change any adjoints - these are just zeros before the reverse
// pass
reverse_pass_callback(
[this_vi = this->vi_, other_vi = other.vi_, prev_val]() mutable {
this_vi->val_ = prev_val;
// we have no way of detecting aliasing between this->vi_->adj_ and
// other.vi_->adj_, so we must copy adjoint before reseting to zero
// we can reuse prev_val instead of allocating a new matrix
prev_val = this_vi->adj_;
this_vi->adj_.setZero();
other_vi->adj_ += prev_val;
});
return *this;
}
/**
* No-op to match with Eigen methods which call eval
*/
template <typename T_ = T, require_plain_type_t<T_>* = nullptr>
inline auto& eval() noexcept {
return *this;
}
template <typename T_ = T, require_plain_type_t<T_>* = nullptr>
inline const auto& eval() const {
return *this;
}
/**
* For non-plain types evaluate to the plain type
*/
template <typename T_ = T, require_not_plain_type_t<T_>* = nullptr>
inline auto eval() noexcept {
return var_value<plain_type_t<T>>(*this);
}
template <typename T_ = T, require_not_plain_type_t<T_>* = nullptr>
inline auto eval() const {
return var_value<plain_type_t<T>>(*this);
}
/**
* Copy assignment operator delegates to general assignment operator
* @param other the value to assign
* @return this
*/
inline var_value<T>& operator=(const var_value<T>& other) {
return operator=<T>(other);
}
};
// For backwards compatability the default value is double
using var = var_value<double>;
} // namespace math
/**
* Template specialization defining the scalar type of
* values stored in var_value.
*
* @tparam T type to check.
* @ingroup type_trait
*/
template <typename T>
struct scalar_type<T, std::enable_if_t<is_var<T>::value>> {
using type
= math::var_value<scalar_type_t<typename std::decay_t<T>::value_type>>;
};
} // namespace stan
#endif
| 33.98845 | 80 | 0.665742 | bayesmix-dev |
cd76cf0bd5126336dd3da95f7321f8290b69eaf9 | 1,936 | cpp | C++ | aws-cpp-sdk-frauddetector/source/model/TrainingResult.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-frauddetector/source/model/TrainingResult.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-frauddetector/source/model/TrainingResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/frauddetector/model/TrainingResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace FraudDetector
{
namespace Model
{
TrainingResult::TrainingResult() :
m_dataValidationMetricsHasBeenSet(false),
m_trainingMetricsHasBeenSet(false),
m_variableImportanceMetricsHasBeenSet(false)
{
}
TrainingResult::TrainingResult(JsonView jsonValue) :
m_dataValidationMetricsHasBeenSet(false),
m_trainingMetricsHasBeenSet(false),
m_variableImportanceMetricsHasBeenSet(false)
{
*this = jsonValue;
}
TrainingResult& TrainingResult::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("dataValidationMetrics"))
{
m_dataValidationMetrics = jsonValue.GetObject("dataValidationMetrics");
m_dataValidationMetricsHasBeenSet = true;
}
if(jsonValue.ValueExists("trainingMetrics"))
{
m_trainingMetrics = jsonValue.GetObject("trainingMetrics");
m_trainingMetricsHasBeenSet = true;
}
if(jsonValue.ValueExists("variableImportanceMetrics"))
{
m_variableImportanceMetrics = jsonValue.GetObject("variableImportanceMetrics");
m_variableImportanceMetricsHasBeenSet = true;
}
return *this;
}
JsonValue TrainingResult::Jsonize() const
{
JsonValue payload;
if(m_dataValidationMetricsHasBeenSet)
{
payload.WithObject("dataValidationMetrics", m_dataValidationMetrics.Jsonize());
}
if(m_trainingMetricsHasBeenSet)
{
payload.WithObject("trainingMetrics", m_trainingMetrics.Jsonize());
}
if(m_variableImportanceMetricsHasBeenSet)
{
payload.WithObject("variableImportanceMetrics", m_variableImportanceMetrics.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace FraudDetector
} // namespace Aws
| 21.511111 | 90 | 0.763946 | perfectrecall |
cd7a861acf79844671a8928c650fa1788f3990be | 952 | hpp | C++ | GPRO Net SDK/include/gpro-net/tile.hpp | Jacob-Rose/GPR-430-Network-Architecture | c56a1ec4dfc284b2a2fa957a5bcecace9723269b | [
"Apache-2.0"
] | null | null | null | GPRO Net SDK/include/gpro-net/tile.hpp | Jacob-Rose/GPR-430-Network-Architecture | c56a1ec4dfc284b2a2fa957a5bcecace9723269b | [
"Apache-2.0"
] | null | null | null | GPRO Net SDK/include/gpro-net/tile.hpp | Jacob-Rose/GPR-430-Network-Architecture | c56a1ec4dfc284b2a2fa957a5bcecace9723269b | [
"Apache-2.0"
] | null | null | null | #ifndef TILE_ENTITY_H
#define TILE_ENTITY_H
#include "entity.h"
#include "resource-manager.h"
namespace jr
{
class TileEntity;
}
class jr::TileEntity : public jr::Entity
{
public:
const float m_Scale = 1.0f;
sf::Vector2i m_Position;
char m_TileID;
TileEntity(int tileID, sf::Vector2i pos) : Entity(), m_TileID(tileID), m_Position(pos)
{
switch (tileID)
{
case 0:
m_Sprite.setTexture(*jr::ResourceManager::getSingleton()->getTextureFromID(jr::ResourceManager::TILE_GRASS_ID));
break;
case 1:
m_Sprite.setTexture(*jr::ResourceManager::getSingleton()->getTextureFromID(jr::ResourceManager::TILE_WALL_ID));
}
m_Sprite.setPosition(sf::Vector2f(pos.x * m_Sprite.getGlobalBounds().width * m_Scale, pos.y * m_Sprite.getGlobalBounds().height * m_Scale));
m_Sprite.setScale(sf::Vector2f(m_Scale, m_Scale));
}
~TileEntity()
{
}
void setTileID()
{
}
void update(EntityUpdateInfo updateInfo) override {}
};
#endif | 19.04 | 142 | 0.721639 | Jacob-Rose |
cd7abfe0b8c7394c212892456ac4991b63f9575f | 43,714 | cpp | C++ | tests/journald_tests.cpp | Oleksandr-Zasikan/dcos-mesos-modules | 7d91c7f92c94f483f427e74b55046e34df0420c7 | [
"Apache-2.0"
] | null | null | null | tests/journald_tests.cpp | Oleksandr-Zasikan/dcos-mesos-modules | 7d91c7f92c94f483f427e74b55046e34df0420c7 | [
"Apache-2.0"
] | null | null | null | tests/journald_tests.cpp | Oleksandr-Zasikan/dcos-mesos-modules | 7d91c7f92c94f483f427e74b55046e34df0420c7 | [
"Apache-2.0"
] | null | null | null | #include <map>
#include <string>
#include <vector>
#include <gmock/gmock.h>
#include <mesos/hook.hpp>
#include <mesos/mesos.hpp>
#include <mesos/resources.hpp>
#include <mesos/module/module.hpp>
#include <mesos/scheduler/scheduler.hpp>
#include <process/clock.hpp>
#include <process/future.hpp>
#include <process/gmock.hpp>
#include <process/gtest.hpp>
#include <process/network.hpp>
#include <process/owned.hpp>
#include <process/process.hpp>
#include <process/socket.hpp>
#include <process/time.hpp>
#include <stout/duration.hpp>
#include <stout/gtest.hpp>
#include <stout/json.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/path.hpp>
#include <stout/protobuf.hpp>
#include <stout/strings.hpp>
#include <stout/try.hpp>
#include <stout/os/pstree.hpp>
#include <stout/os/read.hpp>
#ifdef __linux__
#include "common/shell.hpp"
#endif // __linux__
#include "module/manager.hpp"
#include "slave/flags.hpp"
#include "slave/containerizer/docker.hpp"
#include "tests/mesos.hpp"
using namespace process;
using namespace mesos::internal::tests;
using std::vector;
using mesos::internal::master::Master;
using mesos::internal::slave::Containerizer;
using mesos::internal::slave::DockerContainerizer;
using mesos::internal::slave::Fetcher;
using mesos::internal::slave::MesosContainerizer;
using mesos::internal::slave::Slave;
using mesos::master::detector::MasterDetector;
using mesos::modules::ModuleManager;
#ifdef __linux__
using mesos::modules::common::runCommand;
#endif // __linux__
using testing::WithParamInterface;
#ifdef __linux__
namespace systemd {
// Forward declare a function and required class located in
// `src/linux/systemd.cpp`. This is not exposed in the Mesos public
// headers, but is necessary to start the test.
class Flags : public virtual flags::FlagsBase
{
public:
Flags() {
add(&Flags::enabled,
"enabled",
"Top level control of systemd support. When enabled, features such as\n"
"processes life-time extension are enabled unless there is an \n"
"explicit flag to disable these (see other flags).",
true);
add(&Flags::runtime_directory,
"runtime_directory",
"The path to the systemd system run time directory\n",
"/run/systemd/system");
add(&Flags::cgroups_hierarchy,
"cgroups_hierarchy",
"The path to the cgroups hierarchy root\n",
"/sys/fs/cgroup");
}
bool enabled;
std::string runtime_directory;
std::string cgroups_hierarchy;
};
Try<Nothing> initialize(const Flags& flags);
} // namespace systemd {
#endif // __linux__
namespace mesos {
namespace journald {
namespace tests {
const char JOURNALD_LOGGER_NAME[] = "com_mesosphere_mesos_JournaldLogger";
class JournaldLoggerTest : public MesosTest,
public WithParamInterface<std::string>
{
public:
static void SetUpTestCase()
{
#ifdef __linux__
// NOTE: This code is normally run in `src/slave/main.cpp`.
systemd::Flags systemdFlags;
Try<Nothing> initialize = systemd::initialize(systemdFlags);
if (initialize.isError()) {
EXIT(EXIT_FAILURE)
<< "Failed to initialize systemd: " + initialize.error();
}
// For convenience, set this value to path of libmesos.so.
// The logger's companion binary needs to be able to find
// libmesos from the agent's environment.
os::setenv("LD_LIBRARY_PATH", path::join(BUILD_DIR, "src/.libs"));
#endif // __linux__
}
virtual void SetUp()
{
MesosTest::SetUp();
// Read in the example `modules.json`.
Try<std::string> read =
os::read(path::join(MODULES_BUILD_DIR, "journald", "modules.json"));
ASSERT_SOME(read);
Try<JSON::Object> json = JSON::parse<JSON::Object>(read.get());
ASSERT_SOME(json);
Try<Modules> _modules = protobuf::parse<Modules>(json.get());
ASSERT_SOME(_modules);
modules = _modules.get();
// Initialize the modules.
Try<Nothing> result = ModuleManager::load(modules);
ASSERT_SOME(result);
}
virtual void TearDown()
{
// Unload all modules.
foreach (const Modules::Library& library, modules.libraries()) {
foreach (const Modules::Library::Module& module, library.modules()) {
if (module.has_name()) {
ASSERT_SOME(ModuleManager::unload(module.name()));
}
}
}
MesosTest::TearDown();
}
protected:
Modules modules;
};
#ifdef __linux__
// Loads the journald ContainerLogger module and runs a task.
// Then queries journald for the associated logs.
TEST_F(JournaldLoggerTest, ROOT_LogToJournaldWithBigLabel)
{
// Create a master, agent, and framework.
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
// We'll need access to these flags later.
mesos::internal::slave::Flags flags = CreateSlaveFlags();
// Use the journald container logger.
flags.container_logger = JOURNALD_LOGGER_NAME;
Fetcher fetcher(flags);
// We use an actual containerizer + executor since we want something to run.
Try<MesosContainerizer*> _containerizer =
MesosContainerizer::create(flags, false, &fetcher);
CHECK_SOME(_containerizer);
Owned<MesosContainerizer> containerizer(_containerizer.get());
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave =
StartSlave(detector.get(), containerizer.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL);
Future<FrameworkID> frameworkId;
EXPECT_CALL(sched, registered(&driver, _, _))
.WillOnce(FutureArg<1>(&frameworkId));
// Wait for an offer, and start a task.
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(frameworkId);
AWAIT_READY(offers);
EXPECT_NE(0u, offers.get().size());
const std::string specialString = "some-super-unique-string";
TaskInfo task = createTask(offers.get()[0], "echo " + specialString);
// Add a short label.
Label* label = task.mutable_labels()->add_labels();
label->set_key("TINY");
label->set_value("present");
// Add a huge label.
label = task.mutable_labels()->add_labels();
label->set_key("HUGE");
{
std::string fiftyKilobyteString;
fiftyKilobyteString.reserve(50000u);
for (int i = 0; i < 5000; i++) {
fiftyKilobyteString += "0123456789";
}
label->set_value(fiftyKilobyteString);
}
// Add another short label.
// This tests an implementation detail, where we exclude labels in their
// order of occurrence. This means, if you add a huge label at the beginning,
// all subsequent labels will also be excluded from the metadata.
label = task.mutable_labels()->add_labels();
label->set_key("SMALL");
label->set_value("excluded");
// Make sure the destination of the logs is journald.
Environment::Variable* variable =
task.mutable_command()->mutable_environment()->add_variables();
variable->set_name("CONTAINER_LOGGER_DESTINATION_TYPE");
variable->set_value("journald");
Future<TaskStatus> statusStarting;
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusFinished;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&statusStarting))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusFinished))
.WillRepeatedly(Return()); // Ignore subsequent updates.
driver.launchTasks(offers.get()[0].id(), {task});
AWAIT_READY(statusStarting);
EXPECT_EQ(TASK_STARTING, statusStarting.get().state());
AWAIT_READY(statusRunning);
EXPECT_EQ(TASK_RUNNING, statusRunning.get().state());
AWAIT_READY(statusFinished);
EXPECT_EQ(TASK_FINISHED, statusFinished.get().state());
driver.stop();
driver.join();
// Query journald via the FrameworkID (to disambiguate between test runs)
// and the freeform labels. The first freeform label should be present,
// but the second one should not.
Future<std::string> firstQuery = runCommand(
"journalctl",
{"journalctl",
"FRAMEWORK_ID=" + frameworkId.get().value(),
"TINY=present"});
Future<std::string> secondQuery = runCommand(
"journalctl",
{"journalctl",
"FRAMEWORK_ID=" + frameworkId.get().value(),
"SMALL=excluded"});
AWAIT_READY(firstQuery);
ASSERT_TRUE(strings::contains(firstQuery.get(), specialString));
AWAIT_READY(secondQuery);
ASSERT_FALSE(strings::contains(secondQuery.get(), specialString));
}
#endif // __WINDOWS__
// Loads the journald ContainerLogger module and checks for the
// non-existence of the logrotate config file.
TEST_F(JournaldLoggerTest, ROOT_LogrotateCustomOptions)
{
const std::string testFile = path::join(sandbox.get(), "CustomRotateOptions");
// Custom config consists of a postrotate script which creates
// an empty file in the temporary directory on log rotation.
const std::string customConfig =
"postrotate\n touch " + testFile + "\nendscript";
// There is no way to change a task's custom logrotate options except when
// loading the module. So this test will unload the module, change the
// logrotate options, and then reload the module.
ASSERT_SOME(ModuleManager::unload(JOURNALD_LOGGER_NAME));
foreach (Modules::Library& library, *modules.mutable_libraries()) {
foreach (Modules::Library::Module& module, *library.mutable_modules()) {
if (module.has_name() && module.name() == JOURNALD_LOGGER_NAME) {
Parameter* parameter = module.add_parameters();
parameter->set_key("logrotate_stdout_options");
parameter->set_value(customConfig);
}
}
}
// Initialize the modules.
Try<Nothing> result = ModuleManager::load(modules);
ASSERT_SOME(result);
// Create a master, agent, and framework.
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
// We'll need access to these flags later.
mesos::internal::slave::Flags flags = CreateSlaveFlags();
// Use the journald container logger.
flags.container_logger = JOURNALD_LOGGER_NAME;
Fetcher fetcher(flags);
// We use an actual containerizer + executor since we want something to run.
Try<MesosContainerizer*> _containerizer =
MesosContainerizer::create(flags, false, &fetcher);
CHECK_SOME(_containerizer);
Owned<MesosContainerizer> containerizer(_containerizer.get());
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave =
StartSlave(detector.get(), containerizer.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL);
Future<FrameworkID> frameworkId;
EXPECT_CALL(sched, registered(&driver, _, _))
.WillOnce(FutureArg<1>(&frameworkId));
// Wait for an offer, and start a task.
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(frameworkId);
AWAIT_READY(offers);
EXPECT_NE(0u, offers.get().size());
// Start a task that spams stdout with 2 MB of (mostly blank) output.
// The container logger module is loaded with parameters that limit
// the log size to files of 10 MB each. After the task completes,
// `logrotate` should trigger rotation of stdout logs, so the postrotate
// script is executed.
TaskInfo task = createTask(
offers.get()[0],
#ifndef __WINDOWS__
"i=0; while [ $i -lt 10240 ]; "
"do printf '%-1024d\\n' $i; i=$((i+1)); done");
#else
// There isn't a good alternative to printf on Windows,
// but this line will print about the same quantity of bits.
"FOR /L %a IN (1,1,327680) DO echo 12345678901234567890123456789012");
#endif // __WINDOWS__
// Make sure the destination of the logs is logrotate.
Environment::Variable* variable =
task.mutable_command()->mutable_environment()->add_variables();
variable->set_name("CONTAINER_LOGGER_DESTINATION_TYPE");
variable->set_value("logrotate");
// Add an override for the logger's stdout stream.
// This way of overriding custom options should be disabled,
// so we will check that these options are ignored.
// See MESOS-9564 for more context.
const std::string ignoredtestFile =
path::join(sandbox.get(), "ShouldNotBeCreated");
const std::string ignoredConfig =
"postrotate\n touch " + ignoredtestFile + "\nendscript";
variable = task.mutable_command()->mutable_environment()->add_variables();
variable->set_name("CONTAINER_LOGGER_LOGROTATE_STDOUT_OPTIONS");
variable->set_value(ignoredConfig);
Future<TaskStatus> statusStarting;
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusFinished;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&statusStarting))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusFinished))
.WillRepeatedly(Return()); // Ignore subsequent updates.
driver.launchTasks(offers.get()[0].id(), {task});
AWAIT_READY(statusStarting);
EXPECT_EQ(TASK_STARTING, statusStarting.get().state());
AWAIT_READY(statusRunning);
EXPECT_EQ(TASK_RUNNING, statusRunning.get().state());
#ifndef __WINDOWS__
AWAIT_READY(statusFinished);
#else
// Looping and echo-ing is excruciatingly slow on Windows.
AWAIT_READY_FOR(statusFinished, Seconds(120));
#endif // __WINDOWS__
EXPECT_EQ(TASK_FINISHED, statusFinished.get().state());
driver.stop();
driver.join();
// The ContainerLogger spawns some helper processes that continue running
// briefly after the container finishes. Once they finish reading/writing
// the container's pipe, they should exit.
const Duration maxReapWaitTime = Seconds(30);
Try<os::ProcessTree> pstrees = os::pstree(0);
ASSERT_SOME(pstrees);
foreach (const os::ProcessTree& pstree, pstrees->children) {
// Wait for the logger subprocesses to exit, for up to 30 seconds each.
Duration waited = Duration::zero();
do {
if (!os::exists(pstree.process.pid)) {
break;
}
// Push the clock ahead to speed up the reaping of subprocesses.
Clock::pause();
Clock::settle();
Clock::advance(Seconds(1));
Clock::resume();
os::sleep(Milliseconds(100));
waited += Milliseconds(100);
} while (waited < maxReapWaitTime);
EXPECT_LE(waited, maxReapWaitTime);
}
// Check that the sandbox was written to.
std::string sandboxDirectory = path::join(
flags.work_dir,
"slaves",
offers.get()[0].slave_id().value(),
"frameworks",
frameworkId.get().value(),
"executors",
statusRunning->executor_id().value(),
"runs",
"latest");
ASSERT_TRUE(os::exists(sandboxDirectory));
const std::string stdoutPath = path::join(sandboxDirectory, "stdout");
ASSERT_TRUE(os::exists(stdoutPath));
// An associated logrotate config file should not exist.
#ifndef __WINDOWS__
const std::string configPath =
path::join(sandboxDirectory, "stdout.logrotate.conf");
ASSERT_FALSE(os::exists(configPath));
#endif // __WINDOWS__
// Since some logs should have been rotated, the postrotate script should
// have created this file.
ASSERT_TRUE(os::exists(testFile));
ASSERT_FALSE(os::exists(ignoredtestFile));
}
#ifdef __linux__
// This test verfies that the executor information will be passed to
// the container logger the same way before and after an agent
// restart. Note that this is different than the behavior before Mesos
// 1.5, at which time we don't checkout ContainerConfig.
TEST_F(JournaldLoggerTest, ROOT_CGROUPS_LaunchThenRecoverThenLaunchNested)
{
mesos::internal::slave::Flags flags = CreateSlaveFlags();
flags.launcher = "linux";
flags.isolation = "cgroups/cpu,filesystem/linux,namespaces/pid";
// Use the journald container logger.
flags.container_logger = JOURNALD_LOGGER_NAME;
Fetcher fetcher(flags);
Try<MesosContainerizer*> create = MesosContainerizer::create(
flags,
false,
&fetcher);
ASSERT_SOME(create);
Owned<MesosContainerizer> containerizer(create.get());
// Generate an AgentID to "recover" the MesosContainerizer with.
mesos::internal::slave::state::SlaveState state;
state.id = SlaveID();
state.id.set_value(id::UUID::random().toString());
AWAIT_READY(containerizer->recover(state));
ContainerID containerId;
containerId.set_value(id::UUID::random().toString());
const std::string specialParentString = "special-parent-string";
// We want to print a special string to stdout and then sleep
// so that there is enough time to launch a nested container.
ExecutorInfo executorInfo = createExecutorInfo(
"executor",
"echo '" + specialParentString + "' && sleep 1000",
"cpus:1");
executorInfo.mutable_framework_id()->set_value(id::UUID::random().toString());
// Make a valid ExecutorRunPath, much like the
// `slave::paths::getExecutorRunPath` helper (that we don't have access to).
const std::string executorRunPath = path::join(
flags.work_dir,
"slaves", stringify(state.id),
"frameworks", stringify(executorInfo.framework_id()),
"executors", stringify(executorInfo.executor_id()),
"runs", stringify(containerId));
ASSERT_SOME(os::mkdir(executorRunPath));
// Launch the top-level/parent container.
// We need to checkpoint it so that it will survive recovery
// (hence the `forked.pid` argument).
Future<Containerizer::LaunchResult> launch = containerizer->launch(
containerId,
createContainerConfig(None(), executorInfo, executorRunPath),
std::map<std::string, std::string>(),
path::join(flags.work_dir,
"meta",
"slaves", stringify(state.id),
"frameworks", stringify(executorInfo.framework_id()),
"executors", stringify(executorInfo.executor_id()),
"runs", stringify(containerId),
"pids", "forked.pid"));
AWAIT_ASSERT_EQ(Containerizer::LaunchResult::SUCCESS, launch);
Future<ContainerStatus> status = containerizer->status(containerId);
AWAIT_READY(status);
ASSERT_TRUE(status->has_executor_pid());
pid_t pid = status->executor_pid();
// Emulate a Mesos agent restart by destroying and recreating the
// MesosContainerizer object.
containerizer.reset();
create = MesosContainerizer::create(
flags,
false,
&fetcher);
ASSERT_SOME(create);
containerizer.reset(create.get());
// Create a mock `SlaveState`.
mesos::internal::slave::state::ExecutorState executorState;
executorState.id = executorInfo.executor_id();
executorState.info = executorInfo;
executorState.latest = containerId;
mesos::internal::slave::state::RunState runState;
runState.id = containerId;
runState.forkedPid = pid;
executorState.runs.put(containerId, runState);
mesos::internal::slave::state::FrameworkState frameworkState;
frameworkState.id = executorInfo.framework_id();
frameworkState.executors.put(executorInfo.executor_id(), executorState);
mesos::internal::slave::state::SlaveState slaveState;
slaveState.id = state.id;
slaveState.frameworks.put(executorInfo.framework_id(), frameworkState);
// Recover by using the mock `SlaveState`.
AWAIT_READY(containerizer->recover(slaveState));
status = containerizer->status(containerId);
AWAIT_READY(status);
ASSERT_TRUE(status->has_executor_pid());
EXPECT_EQ(pid, status->executor_pid());
// Now launch the nested container.
ContainerID nestedContainerId;
nestedContainerId.mutable_parent()->CopyFrom(containerId);
nestedContainerId.set_value(id::UUID::random().toString());
const std::string specialChildString = "special-child-string";
// This one can be short lived.
// We just need it to print a child-specific string and then exit.
launch = containerizer->launch(
nestedContainerId,
createContainerConfig(createCommandInfo(
"echo '" + specialChildString + "'")),
std::map<std::string, std::string>(),
None());
AWAIT_ASSERT_EQ(Containerizer::LaunchResult::SUCCESS, launch);
status = containerizer->status(nestedContainerId);
AWAIT_READY(status);
ASSERT_TRUE(status->has_executor_pid());
// Wait for the nested container to finish.
Future<Option<mesos::slave::ContainerTermination>> nestedWait =
containerizer->wait(nestedContainerId);
AWAIT_READY(nestedWait);
ASSERT_SOME(nestedWait.get());
// Destroy the parent container.
Future<Option<mesos::slave::ContainerTermination>> wait =
containerizer->wait(containerId);
containerizer->destroy(containerId);
AWAIT_READY(wait);
ASSERT_SOME(wait.get());
ASSERT_TRUE(wait.get()->has_status());
EXPECT_WTERMSIG_EQ(SIGKILL, wait.get()->status());
// Now run two filters based on AGENT_ID and FRAMEWORK_ID.
// Normally, we would expect to get the same result from each filter.
// But in fact, we should *not* find the child string inside the
// query based on FRAMEWORK_ID because the MesosContainerizer
// will not persist that information after the emulated restart.
Future<std::string> firstQuery = runCommand(
"journalctl",
{"journalctl",
"AGENT_ID=" + stringify(state.id)});
Future<std::string> secondQuery = runCommand(
"journalctl",
{"journalctl",
"FRAMEWORK_ID=" + stringify(executorInfo.framework_id())});
AWAIT_READY(firstQuery);
EXPECT_TRUE(strings::contains(firstQuery.get(), specialParentString));
EXPECT_TRUE(strings::contains(firstQuery.get(), specialChildString));
AWAIT_READY(secondQuery);
EXPECT_TRUE(strings::contains(secondQuery.get(), specialParentString));
EXPECT_TRUE(strings::contains(secondQuery.get(), specialChildString));
}
// This verifies that the logger makes a special case for DEBUG containers
// and simply prints the output of DEBUG containers to the sandbox.
// This is the same behavior as the SandboxContainerLogger.
TEST_F(JournaldLoggerTest, ROOT_CGROUPS_DebugContainersLogToSandbox)
{
mesos::internal::slave::Flags flags = CreateSlaveFlags();
flags.launcher = "linux";
flags.isolation = "cgroups/cpu,filesystem/linux,namespaces/pid";
// Use the journald container logger.
flags.container_logger = JOURNALD_LOGGER_NAME;
Fetcher fetcher(flags);
Try<MesosContainerizer*> create = MesosContainerizer::create(
flags,
false,
&fetcher);
ASSERT_SOME(create);
Owned<MesosContainerizer> containerizer(create.get());
// Generate an AgentID to "recover" the MesosContainerizer with.
mesos::internal::slave::state::SlaveState state;
state.id = SlaveID();
state.id.set_value(id::UUID::random().toString());
AWAIT_READY(containerizer->recover(state));
ContainerID containerId;
containerId.set_value(id::UUID::random().toString());
const std::string specialParentString = "special-parent-string";
// We want to print a special string to stdout and then sleep
// so that there is enough time to launch a nested container.
ExecutorInfo executorInfo = createExecutorInfo(
"executor",
"echo '" + specialParentString + "' && sleep 1000",
"cpus:1");
executorInfo.mutable_framework_id()->set_value(id::UUID::random().toString());
// Make a valid ExecutorRunPath, much like the
// `slave::paths::getExecutorRunPath` helper (that we don't have access to).
const std::string executorRunPath = path::join(
flags.work_dir,
"slaves", stringify(state.id),
"frameworks", stringify(executorInfo.framework_id()),
"executors", stringify(executorInfo.executor_id()),
"runs", stringify(containerId));
ASSERT_SOME(os::mkdir(executorRunPath));
// Launch the top-level container.
Future<Containerizer::LaunchResult> launch = containerizer->launch(
containerId,
createContainerConfig(None(), executorInfo, executorRunPath),
std::map<std::string, std::string>(),
None());
AWAIT_ASSERT_EQ(Containerizer::LaunchResult::SUCCESS, launch);
Future<ContainerStatus> status = containerizer->status(containerId);
AWAIT_READY(status);
ASSERT_TRUE(status->has_executor_pid());
// Now launch the nested container.
ContainerID nestedContainerId;
nestedContainerId.mutable_parent()->CopyFrom(containerId);
nestedContainerId.set_value(id::UUID::random().toString());
const std::string specialChildString = "special-child-string";
// Mark this as a DEBUG container, much like health checks and
// other nested container sessions.
launch = containerizer->launch(
nestedContainerId,
createContainerConfig(
createCommandInfo("echo '" + specialChildString + "'"),
None(),
mesos::slave::ContainerClass::DEBUG),
std::map<std::string, std::string>(),
None());
AWAIT_ASSERT_EQ(Containerizer::LaunchResult::SUCCESS, launch);
status = containerizer->status(nestedContainerId);
AWAIT_READY(status);
ASSERT_TRUE(status->has_executor_pid());
// Wait for the nested container to finish.
Future<Option<mesos::slave::ContainerTermination>> nestedWait =
containerizer->wait(nestedContainerId);
AWAIT_READY(nestedWait);
ASSERT_SOME(nestedWait.get());
// Destroy the parent container.
Future<Option<mesos::slave::ContainerTermination>> wait =
containerizer->wait(containerId);
containerizer->destroy(containerId);
AWAIT_READY(wait);
ASSERT_SOME(wait.get());
ASSERT_TRUE(wait.get()->has_status());
EXPECT_WTERMSIG_EQ(SIGKILL, wait.get()->status());
// Filter the output of journald via AGENT_ID. This should contain the
// output of the parent container, but not the child (debug) container.
Future<std::string> firstQuery = runCommand(
"journalctl",
{"journalctl",
"AGENT_ID=" + stringify(state.id)});
AWAIT_READY(firstQuery);
EXPECT_TRUE(strings::contains(firstQuery.get(), specialParentString));
EXPECT_FALSE(strings::contains(firstQuery.get(), specialChildString));
// Check the debug container's sandbox for the expected output.
const std::string debugContainerStdout =
path::join(
executorRunPath,
"containers",
nestedContainerId.value(),
"stdout");
ASSERT_TRUE(os::exists(debugContainerStdout));
Result<std::string> stdout = os::read(debugContainerStdout);
ASSERT_SOME(stdout);
EXPECT_TRUE(strings::contains(stdout.get(), specialChildString));
}
#endif // __linux__
#ifdef __linux__
INSTANTIATE_TEST_CASE_P(
LoggingMode,
JournaldLoggerTest,
::testing::Values(
std::string("journald"),
std::string("journald+logrotate"),
std::string("logrotate")));
#else
INSTANTIATE_TEST_CASE_P(
LoggingMode,
JournaldLoggerTest,
::testing::Values(std::string("logrotate")));
#endif // __linux__
#ifdef __linux__
// Loads the journald ContainerLogger module and runs a task.
// Then queries journald for the associated logs.
TEST_P(JournaldLoggerTest, ROOT_LogToJournald)
{
// Create a master, agent, and framework.
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
// We'll need access to these flags later.
mesos::internal::slave::Flags flags = CreateSlaveFlags();
// Use the journald container logger.
flags.container_logger = JOURNALD_LOGGER_NAME;
Fetcher fetcher(flags);
// We use an actual containerizer + executor since we want something to run.
Try<MesosContainerizer*> _containerizer =
MesosContainerizer::create(flags, false, &fetcher);
CHECK_SOME(_containerizer);
Owned<MesosContainerizer> containerizer(_containerizer.get());
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave =
StartSlave(detector.get(), containerizer.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL);
Future<FrameworkID> frameworkId;
EXPECT_CALL(sched, registered(&driver, _, _))
.WillOnce(FutureArg<1>(&frameworkId));
// Wait for an offer, and start a task.
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(frameworkId);
AWAIT_READY(offers);
EXPECT_NE(0u, offers.get().size());
const std::string specialString = "some-super-unique-string";
TaskInfo task = createTask(offers.get()[0], "echo " + specialString);
// Change the destination of the logs based on the parameterized test.
Environment::Variable* variable =
task.mutable_command()->mutable_environment()->add_variables();
variable->set_name("CONTAINER_LOGGER_DESTINATION_TYPE");
variable->set_value(GetParam());
variable = task.mutable_command()->mutable_environment()->add_variables();
variable->set_name("CONTAINER_LOGGER_EXTRA_LABELS");
variable->set_value(
"{"
" \"EXTRA_LABEL\":\"extra_label\","
" \"EXTRA_LABEL_INVALID\":10"
"}");
Future<TaskStatus> statusStarting;
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusFinished;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&statusStarting))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusFinished))
.WillRepeatedly(Return()); // Ignore subsequent updates.
driver.launchTasks(offers.get()[0].id(), {task});
AWAIT_READY(statusStarting);
EXPECT_EQ(TASK_STARTING, statusStarting.get().state());
AWAIT_READY(statusRunning);
EXPECT_EQ(TASK_RUNNING, statusRunning.get().state());
AWAIT_READY(statusFinished);
EXPECT_EQ(TASK_FINISHED, statusFinished.get().state());
driver.stop();
driver.join();
if (GetParam() == "journald" ||
GetParam() == "journald+logrotate") {
// Query journald via the FrameworkID, AgentID, and ExecutorID
// and check for the special string.
Future<std::string> frameworkQuery = runCommand(
"journalctl",
{"journalctl",
"FRAMEWORK_ID=" + frameworkId.get().value()});
Future<std::string> agentQuery = runCommand(
"journalctl",
{"journalctl",
"AGENT_ID=" + offers.get()[0].slave_id().value()});
Future<std::string> executorQuery = runCommand(
"journalctl",
{"journalctl",
"EXECUTOR_ID=" + statusRunning->executor_id().value()});
Future<std::string> extraLabelQuery = runCommand(
"journalctl",
{"journalctl",
"FRAMEWORK_ID=" + frameworkId.get().value(),
"EXTRA_LABEL=extra_label"});
Future<std::string> extraLabelInvalidQuery = runCommand(
"journalctl",
{"journalctl",
"FRAMEWORK_ID=" + frameworkId.get().value(),
"EXTRA_LABEL_INVALID=10"});
AWAIT_READY(frameworkQuery);
ASSERT_TRUE(strings::contains(frameworkQuery.get(), specialString));
AWAIT_READY(agentQuery);
ASSERT_TRUE(strings::contains(agentQuery.get(), specialString));
AWAIT_READY(executorQuery);
ASSERT_TRUE(strings::contains(executorQuery.get(), specialString));
AWAIT_READY(extraLabelQuery);
ASSERT_TRUE(strings::contains(extraLabelQuery.get(), specialString));
AWAIT_READY(extraLabelInvalidQuery);
ASSERT_FALSE(strings::contains(
extraLabelInvalidQuery.get(),
specialString));
}
std::string sandboxDirectory = path::join(
flags.work_dir,
"slaves",
offers.get()[0].slave_id().value(),
"frameworks",
frameworkId.get().value(),
"executors",
statusRunning->executor_id().value(),
"runs",
"latest");
ASSERT_TRUE(os::exists(sandboxDirectory));
const std::string stdoutPath = path::join(sandboxDirectory, "stdout");
if (GetParam() == "journald") {
// Check that the sandbox was *not* written to. This is best-effort with
// the current container logger architecture: a write may occur *after* a
// terminal status update is sent.
//
// TODO(josephw): This file exists as other parts of the agent will create
// it. We should invert this assertion when we fix this in Mesos.
ASSERT_TRUE(os::exists(stdoutPath));
Result<std::string> stdout = os::read(stdoutPath);
ASSERT_SOME(stdout);
EXPECT_FALSE(strings::contains(stdout.get(), specialString))
<< "Not expected " << specialString << " to appear in " << stdout.get();
}
if (GetParam() == "logrotate" ||
GetParam() == "journald+logrotate") {
// Check that the sandbox was written to as well.
ASSERT_TRUE(os::exists(stdoutPath));
// We expect stdout to be updated by the container logger no later than 30s
// after a terminal status update has been sent.
bool containsSpecialString = false;
Result<std::string> stdout = None();
const Duration timeout = Seconds(30);
const Time start = Clock::now();
do {
stdout = os::read(stdoutPath);
ASSERT_SOME(stdout);
if (strings::contains(stdout.get(), specialString)) {
containsSpecialString = true;
break;
}
os::sleep(Milliseconds(100));
} while (Clock::now() - start < timeout);
EXPECT_TRUE(containsSpecialString)
<< "Expected " << specialString << " to appear in " << stdout.get();
}
}
#endif // __linux__
class FluentbitLoggerTest : public JournaldLoggerTest
{
public:
virtual void SetUp() override
{
// NOTE: We explicitly do not call the JournaldLoggerTest::SetUp function
// as we need to modify some module parameters before loading them.
MesosTest::SetUp();
// Create the mock Fluent Bit server.
Try<network::inet::Socket> server = network::inet::Socket::create();
ASSERT_SOME(server);
fluentbit_server = server.get();
Try<network::inet::Address> bind =
fluentbit_server->bind(
network::inet::Address(net::IP(process::address().ip), 0));
ASSERT_SOME(bind);
// This setup assumes one task is run, leading to two connections.
Try<Nothing> listen = fluentbit_server->listen(2);
ASSERT_SOME(listen);
// Read in the example `modules.json`.
Try<std::string> read =
os::read(path::join(MODULES_BUILD_DIR, "journald", "modules.json"));
ASSERT_SOME(read);
Try<JSON::Object> json = JSON::parse<JSON::Object>(read.get());
ASSERT_SOME(json);
Try<Modules> _modules = protobuf::parse<Modules>(json.get());
ASSERT_SOME(_modules);
modules = _modules.get();
// Replace the dummy values for `fluentbit_ip` and `fluentbit_port`
// with the server bind address above.
foreach (Modules::Library& library, *modules.mutable_libraries()) {
foreach (Modules::Library::Module& module, *library.mutable_modules()) {
if (module.has_name() && module.name() == JOURNALD_LOGGER_NAME) {
foreach (Parameter& parameter, *module.mutable_parameters()) {
if (parameter.key() == "fluentbit_ip") {
parameter.set_value(stringify(bind.get().ip));
} else if (parameter.key() == "fluentbit_port") {
parameter.set_value(stringify(bind.get().port));
}
}
}
}
}
// Initialize the modules.
Try<Nothing> result = ModuleManager::load(modules);
ASSERT_SOME(result);
}
protected:
Option<network::inet::Socket> fluentbit_server;
};
INSTANTIATE_TEST_CASE_P(
LoggingMode,
FluentbitLoggerTest,
::testing::Values(
std::string("fluentbit"),
std::string("fluentbit+logrotate")));
// Sets up a TCP to mock the Fluent Bit component and then loads the
// ContainerLogger module and runs a task.
// We expect a known string logged by the task to reach the mock Fluent Bit.
TEST_P(FluentbitLoggerTest, ROOT_LogToFluentbit)
{
// Create a master, agent, and framework.
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
// We'll need access to these flags later.
mesos::internal::slave::Flags flags = CreateSlaveFlags();
// Use the journald container logger.
flags.container_logger = JOURNALD_LOGGER_NAME;
Fetcher fetcher(flags);
// We use an actual containerizer + executor since we want something to run.
Try<MesosContainerizer*> _containerizer =
MesosContainerizer::create(flags, false, &fetcher);
CHECK_SOME(_containerizer);
Owned<MesosContainerizer> containerizer(_containerizer.get());
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave =
StartSlave(detector.get(), containerizer.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL);
EXPECT_CALL(sched, registered(&driver, _, _));
// Wait for an offer, and start a task.
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(offers);
EXPECT_NE(0u, offers.get().size());
const std::string specialString = "some-super-unique-string";
TaskInfo task = createTask(offers.get()[0], "echo " + specialString);
// Change the destination of the logs based on the parameterized test.
Environment::Variable* variable =
task.mutable_command()->mutable_environment()->add_variables();
variable->set_name("CONTAINER_LOGGER_DESTINATION_TYPE");
variable->set_value(GetParam());
Future<TaskStatus> statusStarting;
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusFinished;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&statusStarting))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusFinished))
.WillRepeatedly(Return()); // Ignore subsequent updates.
driver.launchTasks(offers.get()[0].id(), {task});
AWAIT_READY(statusStarting);
EXPECT_EQ(TASK_STARTING, statusStarting.get().state());
// We expect two connections to be made with our `fluentbit_server`:
// one for stdout and one for stderr.
Future<network::inet::Socket> _client1 = fluentbit_server->accept();
AWAIT_ASSERT_READY(_client1);
Future<network::inet::Socket> _client2 = fluentbit_server->accept();
AWAIT_ASSERT_READY(_client2);
AWAIT_READY(statusRunning);
EXPECT_EQ(TASK_RUNNING, statusRunning.get().state());
AWAIT_READY(statusFinished);
EXPECT_EQ(TASK_FINISHED, statusFinished.get().state());
driver.stop();
driver.join();
// Remove const-ness.
network::inet::Socket client1 = _client1.get();
network::inet::Socket client2 = _client2.get();
// Read everything. This also acts to wait until the loggers exit,
// and thereby close the connections.
Future<std::string> data1 = client1.recv(-1);
Future<std::string> data2 = client2.recv(-1);
AWAIT_ASSERT_READY(data1);
AWAIT_ASSERT_READY(data2);
// From the server side, we don't actually know which connection is
// stdout or stderr. We expect the special string to be in stdout.
std::string combinedOutput = data1.get() + data2.get();
ASSERT_TRUE(strings::contains(combinedOutput, specialString));
// Log lines should also contain some metadata about the source of logs.
// We check for this summarily, since one of these outputs could be empty.
// And we don't want to implement a JSON object stream parser.
EXPECT_TRUE(strings::contains(combinedOutput, "FRAMEWORK_ID"));
EXPECT_TRUE(strings::contains(combinedOutput, "AGENT_ID"));
EXPECT_TRUE(strings::contains(combinedOutput, "EXECUTOR_ID"));
EXPECT_TRUE(strings::contains(combinedOutput, "CONTAINER_ID"));
EXPECT_TRUE(strings::contains(combinedOutput, "STREAM"));
}
#ifdef __linux__
class JournaldLoggerDockerTest : public JournaldLoggerTest {};
INSTANTIATE_TEST_CASE_P(
TaskIDSuffix,
JournaldLoggerDockerTest,
::testing::Values(
std::string(""),
std::string(":something")));
// Then queries journald for the associated logs.
TEST_P(JournaldLoggerDockerTest, ROOT_DOCKER_LogToJournald)
{
// Create a master, agent, and framework.
Try<Owned<cluster::Master>> master = StartMaster();
ASSERT_SOME(master);
// We'll need access to these flags later.
mesos::internal::slave::Flags flags = CreateSlaveFlags();
// Use the journald container logger.
flags.container_logger = JOURNALD_LOGGER_NAME;
Fetcher fetcher(flags);
Try<DockerContainerizer*> _containerizer =
DockerContainerizer::create(flags, &fetcher);
CHECK_SOME(_containerizer);
Owned<DockerContainerizer> containerizer(_containerizer.get());
Owned<MasterDetector> detector = master.get()->createDetector();
Try<Owned<cluster::Slave>> slave =
StartSlave(detector.get(), containerizer.get(), flags);
ASSERT_SOME(slave);
MockScheduler sched;
MesosSchedulerDriver driver(
&sched, DEFAULT_FRAMEWORK_INFO, master.get()->pid, DEFAULT_CREDENTIAL);
Future<FrameworkID> frameworkId;
EXPECT_CALL(sched, registered(&driver, _, _))
.WillOnce(FutureArg<1>(&frameworkId));
// Wait for an offer, and start a task.
Future<vector<Offer>> offers;
EXPECT_CALL(sched, resourceOffers(&driver, _))
.WillOnce(FutureArg<1>(&offers))
.WillRepeatedly(Return()); // Ignore subsequent offers.
driver.start();
AWAIT_READY(frameworkId);
AWAIT_READY(offers);
EXPECT_NE(0u, offers.get().size());
const std::string specialString = "some-super-unique-string";
TaskInfo task = createTask(offers.get()[0], "echo " + specialString);
// Add a parameterized suffix to the TaskID.
task.mutable_task_id()->set_value(task.task_id().value() + GetParam());
ContainerInfo containerInfo;
containerInfo.set_type(ContainerInfo::DOCKER);
ContainerInfo::DockerInfo dockerInfo;
dockerInfo.set_image("alpine");
containerInfo.mutable_docker()->CopyFrom(dockerInfo);
task.mutable_container()->CopyFrom(containerInfo);
Future<TaskStatus> statusStarting;
Future<TaskStatus> statusRunning;
Future<TaskStatus> statusFinished;
EXPECT_CALL(sched, statusUpdate(&driver, _))
.WillOnce(FutureArg<1>(&statusStarting))
.WillOnce(FutureArg<1>(&statusRunning))
.WillOnce(FutureArg<1>(&statusFinished))
.WillRepeatedly(Return()); // Ignore subsequent updates.
driver.launchTasks(offers.get()[0].id(), {task});
AWAIT_READY(statusStarting);
EXPECT_EQ(TASK_STARTING, statusStarting.get().state());
AWAIT_READY(statusRunning);
EXPECT_EQ(TASK_RUNNING, statusRunning.get().state());
AWAIT_READY(statusFinished);
EXPECT_EQ(TASK_FINISHED, statusFinished.get().state());
driver.stop();
driver.join();
// Query journald via the FrameworkID, AgentID, and ExecutorID
// and check for the special string.
Future<std::string> frameworkQuery = runCommand(
"journalctl",
{"journalctl",
"FRAMEWORK_ID=" + frameworkId.get().value()});
Future<std::string> agentQuery = runCommand(
"journalctl",
{"journalctl",
"AGENT_ID=" + offers.get()[0].slave_id().value()});
Future<std::string> executorQuery = runCommand(
"journalctl",
{"journalctl",
"EXECUTOR_ID=" + statusRunning->executor_id().value()});
AWAIT_READY(frameworkQuery);
ASSERT_TRUE(strings::contains(frameworkQuery.get(), specialString));
AWAIT_READY(agentQuery);
EXPECT_TRUE(strings::contains(agentQuery.get(), specialString));
AWAIT_READY(executorQuery);
ASSERT_TRUE(strings::contains(executorQuery.get(), specialString));
}
#endif // __linux__
} // namespace tests {
} // namespace journald {
} // namespace mesos {
| 31.908029 | 80 | 0.705861 | Oleksandr-Zasikan |
cd7fa3cf500458b6612751f061b87dd27deaf0b7 | 6,439 | cpp | C++ | aten/src/ATen/native/TensorTransformations.cpp | sigmunjr/pytorch | 526e12029274cf0257954616d5cd5260b1021f52 | [
"Intel"
] | 1 | 2021-05-11T11:53:47.000Z | 2021-05-11T11:53:47.000Z | aten/src/ATen/native/TensorTransformations.cpp | sigmunjr/pytorch | 526e12029274cf0257954616d5cd5260b1021f52 | [
"Intel"
] | 1 | 2021-05-10T01:18:33.000Z | 2021-05-10T01:18:33.000Z | aten/src/ATen/native/TensorTransformations.cpp | sigmunjr/pytorch | 526e12029274cf0257954616d5cd5260b1021f52 | [
"Intel"
] | null | null | null | #include <ATen/native/TensorTransformations.h>
#include <ATen/WrapDimUtilsMulti.h>
#include <ATen/NativeFunctions.h>
#include <ATen/Parallel.h>
#include <c10/util/Exception.h>
#include <algorithm>
#include <vector>
namespace at {
namespace native {
constexpr size_t dim_bitset_size = 64;
template <typename scalar_t>
void inline flip_cpu_kernel(
const int64_t total_dims,
const std::vector<int64_t>& stride_contiguous_v,
const std::bitset<dim_bitset_size>& flip_dims_b,
const Tensor& in_tensor,
Tensor& out_tensor
){
const int64_t numel = in_tensor.numel();
const scalar_t* in_tensor_d = in_tensor.data_ptr<scalar_t>();
scalar_t* out_tensor_d = out_tensor.data_ptr<scalar_t>();
auto sizes_v = in_tensor.sizes().vec();
auto strides_v = in_tensor.strides().vec();
at::parallel_for(0, numel, 1000, [&](int64_t start, int64_t end) {
for (auto i = start; i < end; i++) {
int64_t cur_indices = i;
int64_t rem = 0;
int64_t dst_offset = 0;
for (int64_t d = 0; d < total_dims; d++) {
int64_t temp = cur_indices;
cur_indices = cur_indices / stride_contiguous_v[d];
rem = temp - cur_indices * stride_contiguous_v[d];
dst_offset += flip_dims_b[d] ? (sizes_v[d] - 1 - cur_indices) * strides_v[d] : cur_indices * strides_v[d];
cur_indices = rem;
}
out_tensor_d[i] = in_tensor_d[dst_offset];
}
});
}
Tensor flip_cpu(const Tensor& self, IntArrayRef dims) {
auto in_tensor = self;
const int64_t total_dims = in_tensor.dim();
auto flip_dims_b = at::dim_list_to_bitset(dims, total_dims);
Tensor out_tensor = at::empty_like(in_tensor, LEGACY_CONTIGUOUS_MEMORY_FORMAT);
// create contiguous strides for input tensor
auto stride_contiguous_v = std::vector<int64_t>(total_dims);
for (int64_t i = total_dims - 1; i >= 0; i--) {
if (i == total_dims - 1) {
stride_contiguous_v[i] = 1;
} else {
stride_contiguous_v[i] = std::max<int64_t>(in_tensor.size(i + 1), 1) * stride_contiguous_v[i + 1];
}
}
if (in_tensor.is_quantized()) {
// NOLINTNEXTLINE(clang-diagnostic-unused-variable)
AT_DISPATCH_QINT_AND_SUB_BYTE_TYPES(in_tensor.scalar_type(),
"flip_quantized_cpu", [&] {
flip_cpu_kernel<scalar_t>(
total_dims,
stride_contiguous_v,
flip_dims_b,
in_tensor,
out_tensor
);
});
} else {
AT_DISPATCH_ALL_TYPES_AND_COMPLEX_AND3(kBool, kHalf, kBFloat16,
in_tensor.scalar_type(),
"flip_cpu", [&] {
flip_cpu_kernel<scalar_t>(
total_dims,
stride_contiguous_v,
flip_dims_b,
in_tensor,
out_tensor
);
});
}
return out_tensor;
}
Tensor roll_cpu(const Tensor& self, IntArrayRef shifts, IntArrayRef dims) {
if (dims.size() != 1 || shifts.size() != 1) {
return roll_common(self, shifts, dims);
}
// avoid a div zero error below.
if (self.numel() == 0) {
return self.clone(at::MemoryFormat::Preserve);
}
int64_t dim = dims[0];
int64_t size = self.size(dim);
int64_t start = (size - shifts[0]) % size;
// Behavior of % is different in C++ vs Python for negative numbers. This
// corrects the difference.
if (start < 0) {
start = start + size;
}
auto t0 = self.narrow(dim, start, size-start);
auto t1 = self.narrow(dim, 0, start);
return at::cat({t0, t1}, dim);
}
Tensor rot90(const Tensor& self, int64_t k, IntArrayRef dims) {
const int64_t total_dims = self.dim(), total_rot_dims = dims.size();
TORCH_CHECK(total_rot_dims == 2,
"expected total rotation dims == 2, but got dims = ", total_rot_dims);
TORCH_CHECK(total_dims >= 2,
"expected total dims >= 2, but got total dims = ", total_dims);
TORCH_CHECK(dims[0] != dims[1] && std::abs(dims[0] - dims[1]) != total_dims,
"expected rotation dims to be different, but got dim0 = ", dims[0],
" and dim1 = ", dims[1]);
// check range of dims
TORCH_CHECK(dims[0] < total_dims && dims[0] >= -total_dims,
"Rotation dim0 out of range, dim0 = ", dims[0]);
TORCH_CHECK(dims[1] < total_dims && dims[1] >= -total_dims,
"Rotation dim1 out of range, dim1 = ", dims[1]);
// handle modulo with negative k
k = (4 + (k % 4)) % 4;
switch(k) {
case 1:
return self.flip({dims[1]}).transpose_(dims[0], dims[1]);
case 2:
return self.flip(dims);
case 3:
return self.flip({dims[0]}).transpose_(dims[0], dims[1]);
default:
return self.clone(at::MemoryFormat::Contiguous);
}
}
Tensor fliplr(const Tensor& self) {
TORCH_CHECK(self.dim() >= 2, "Input must be >= 2-d.");
return self.flip({1});
}
Tensor flipud(const Tensor& self) {
TORCH_CHECK(self.dim() >= 1, "Input must be >= 1-d.");
return self.flip({0});
}
Tensor atleast_1d(const Tensor& self) {
switch (self.dim()) {
case 0:
return self.reshape({1});
default:
return self;
}
}
std::vector<Tensor> atleast_1d(TensorList tensors) {
std::vector<Tensor> result(tensors.size());
auto transform_lambda = [](const Tensor& input) -> Tensor {
return at::native::atleast_1d(input);
};
std::transform(tensors.cbegin(), tensors.cend(), result.begin(), transform_lambda);
return result;
}
Tensor atleast_2d(const Tensor& self) {
switch (self.dim()) {
case 0:
return self.reshape({1, 1});
case 1: {
return self.unsqueeze(0);
}
default:
return self;
}
}
std::vector<Tensor> atleast_2d(TensorList tensors) {
std::vector<Tensor> result(tensors.size());
auto transform_lambda = [](const Tensor& input) -> Tensor {
return at::native::atleast_2d(input);
};
std::transform(tensors.cbegin(), tensors.cend(), result.begin(), transform_lambda);
return result;
}
Tensor atleast_3d(const Tensor& self) {
switch (self.dim()) {
case 0:
return self.reshape({1, 1, 1});
case 1: {
return self.unsqueeze(0).unsqueeze(-1);
}
case 2: {
return self.unsqueeze(-1);
}
default:
return self;
}
}
std::vector<Tensor> atleast_3d(TensorList tensors) {
std::vector<Tensor> result(tensors.size());
auto transform_lambda = [](const Tensor& input) -> Tensor {
return at::native::atleast_3d(input);
};
std::transform(tensors.cbegin(), tensors.cend(), result.begin(), transform_lambda);
return result;
}
}} // namespace at::native
| 28.617778 | 114 | 0.634881 | sigmunjr |
cd85207b0c9ec8743b782b8e30cb67fbb8aa9e09 | 4,972 | cpp | C++ | CaptureManagerSource/Scheduler/ScheduleWorkImpl.cpp | luoyingwen/CaptureManagerSDK | e96395a120175a45c56ff4e2b3283b807a42fd75 | [
"MIT"
] | null | null | null | CaptureManagerSource/Scheduler/ScheduleWorkImpl.cpp | luoyingwen/CaptureManagerSDK | e96395a120175a45c56ff4e2b3283b807a42fd75 | [
"MIT"
] | null | null | null | CaptureManagerSource/Scheduler/ScheduleWorkImpl.cpp | luoyingwen/CaptureManagerSDK | e96395a120175a45c56ff4e2b3283b807a42fd75 | [
"MIT"
] | null | null | null | /*
MIT License
Copyright(c) 2020 Evgeny Pereguda
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 "ScheduleWorkImpl.h"
#include "../MediaFoundationManager/MediaFoundationManager.h"
#include "../LogPrintOut/LogPrintOut.h"
#include "../Common/Common.h"
namespace CaptureManager
{
namespace Core
{
namespace Scheduler
{
ScheduleWorkImpl::ScheduleWorkImpl(
ISchedulerCallback* aPtrCallback) :
mPtrCallback(aPtrCallback)
{
}
ScheduleWorkImpl::~ScheduleWorkImpl()
{
}
HRESULT ScheduleWorkImpl::init(
INT64 aFrameDuration100nseconds)
{
HRESULT lresult;
do
{
lCycleMax = 4;
lCycleCount = 0;
LOG_INVOKE_MF_FUNCTION(MFCreateAsyncResult,
nullptr,
this,
nullptr,
&mAsyncResult);
mFrameDuration100nseconds = aFrameDuration100nseconds;
mPartFrameDuration100nsecondsTimeout = mFrameDuration100nseconds / lCycleMax;
mPartFrameDurationMillSecTimeout = mPartFrameDuration100nsecondsTimeout / 10000;
} while (false);
return lresult;
}
HRESULT ScheduleWorkImpl::start()
{
HRESULT lresult;
do
{
auto lInitTime = MediaFoundation::MediaFoundationManager::MFGetSystemTime();
if (lInitTime == 0)
{
lInitTime = MediaFoundation::MediaFoundationManager::MFGetSystemTime();
}
LOG_CHECK_STATE(lInitTime == 0);
mLastTme = 0;
mInitTime = 0;
mShiftTime = 0;
mStopFlag = false;
LOG_INVOKE_MF_FUNCTION(MFScheduleWorkItemEx,
mAsyncResult,
mPartFrameDurationMillSecTimeout,
&mCancelKey);
} while (false);
return lresult;
}
HRESULT ScheduleWorkImpl::stop()
{
std::unique_lock<std::mutex> lLock(mStopMutex);
mStopFlag = true;
HRESULT lresult(E_FAIL);
do
{
LOG_INVOKE_MF_FUNCTION(MFCancelWorkItem,
mCancelKey);
} while (false);
//mStopCondition.wait_for(lLock, std::chrono::microseconds(mFrameDuration100nseconds/10));
mStopCondition.wait_for(lLock, std::chrono::milliseconds(100));
return S_OK;
}
STDMETHODIMP ScheduleWorkImpl::GetParameters(DWORD*, DWORD*)
{
return E_NOTIMPL;
}
int j = 0;
STDMETHODIMP ScheduleWorkImpl::Invoke(IMFAsyncResult* pAsyncResult)
{
if (mStopFlag)
{
std::lock_guard<std::mutex> lLock(mStopMutex);
mStopCondition.notify_one();
return S_OK;
}
//auto lInitTime = MediaFoundation::MediaFoundationManager::MFGetSystemTime();
//if (mLastTme == 0)
//{
// HRESULT lresult;
// mLastTme = lInitTime;
// mInitTime = lInitTime;
// lCycleCount = 0;
// do
// {
// LOG_INVOKE_MF_FUNCTION(MFScheduleWorkItemEx,
// mAsyncResult,
// -mPartFrameDurationMillSecTimeout,
// &mCancelKey);
// } while (false);
// return S_OK;
//}
//if (++lCycleCount >= lCycleMax)
//{
// if (mPtrCallback != nullptr)
// mPtrCallback->callback();
// lCycleCount = 0;
// auto lduration = (lInitTime - mLastTme);
// mShiftTime += lduration - mFrameDuration100nseconds;
// mLastTme = lInitTime;
// auto lTemp = mShiftTime;
// while (lTemp >= mPartFrameDuration100nsecondsTimeout)
// {
// if (++lCycleCount >= lCycleMax)
// break;
// lTemp -= mPartFrameDuration100nsecondsTimeout;
// }
// //LogPrintOut::getInstance().printOutln(
// // LogPrintOut::ERROR_LEVEL,
// // L" mShiftTime: ",
// // mShiftTime,
// // L", lduration: ",
// // lduration,
// // L", Time: ",
// // lInitTime - mInitTime,
// // L", lCycleCount: ",
// // lCycleCount,
// // L", J: ",
// // ++j);
//}
HRESULT lresult;
do
{
if (mPtrCallback != nullptr)
mPtrCallback->callback();
LOG_INVOKE_MF_FUNCTION(MFScheduleWorkItemEx,
mAsyncResult,
-mPartFrameDurationMillSecTimeout,
&mCancelKey);
} while (false);
return S_OK;
}
}
}
} | 21.247863 | 94 | 0.661504 | luoyingwen |
cd892e5833cff1835e9ce8025c01382166bee38d | 845 | cpp | C++ | 4344.cpp | gcjjyy/acmicpc | 763e7a3ec5aabdab6935b9e9970561baafb07729 | [
"MIT"
] | null | null | null | 4344.cpp | gcjjyy/acmicpc | 763e7a3ec5aabdab6935b9e9970561baafb07729 | [
"MIT"
] | null | null | null | 4344.cpp | gcjjyy/acmicpc | 763e7a3ec5aabdab6935b9e9970561baafb07729 | [
"MIT"
] | null | null | null | /*
문제
대학생 새내기들의 90%는 자신이 반에서 평균은 넘는다고 생각한다. 당신은 그들에게 슬픈 진실을 알려줘야 한다.
입력
첫째 줄에는 테스트케이스 C가 주어진다.
둘째 줄부터 각 테스트케이스 마다 첫 수로 정수 N(1 <= N <= 1000)명의 학생이 주어지고 그 다음으로 N명의 0부터 100 사이의 점수가 이어서 주어진다.
출력
각 케이스마다 한줄씩 평균을 넘는 학생들의 비율을 소수점 넷째자리에서 반올림하여 출력한다.
*/
#include <stdio.h>
int C;
int A[1001];
int count;
int total;
double average;
int main() {
scanf("%d", &C);
for(int c = 1; c <= C; ++c) {
scanf("%d", &count);
total = 0;
for(int j = 1; j <= count; ++j) {
scanf("%d", &A[j]);
total += A[j];
}
average = (double)total / (double)count;
total = 0;
for(int j = 1; j <= count; ++j) {
if((double)A[j] > average) {
total++;
}
}
printf("%.3lf%%\n", (double)total / (double)count * 100.0);
}
return 0;
} | 20.119048 | 92 | 0.486391 | gcjjyy |
cd8b29698f27bd382fdf1931ada265e793a1048c | 6,118 | cc | C++ | coursera/accelerated_cs/c3w3_union/dsunion.cc | e-dnx/courses | d21742a51447496f541dc8ec32b0df79d709dbff | [
"MIT"
] | null | null | null | coursera/accelerated_cs/c3w3_union/dsunion.cc | e-dnx/courses | d21742a51447496f541dc8ec32b0df79d709dbff | [
"MIT"
] | null | null | null | coursera/accelerated_cs/c3w3_union/dsunion.cc | e-dnx/courses | d21742a51447496f541dc8ec32b0df79d709dbff | [
"MIT"
] | null | null | null | #include <iostream>
#include <unordered_map>
#include <algorithm>
// You are provided this version of a DisjointSets class.
// See below for the tasks to complete.
// (Please note: You may not edit the primary class definition here.)
class DisjointSets {
public:
// We'll statically allocate space for at most 256 nodes.
// (We could easily make this extensible by using STL containers
// instead of static arrays.)
static constexpr int MAX_NODES = 256;
// For a given vertex of index i, leader[i] is -1 if that vertex "leads"
// the set, and otherwise, leader[i] is the vertex index that refers back
// to the eventual leader, recursively. (See the function "find_leader".)
// In this problem we'll interpret sets to represent connected components,
// once the sets have been unioned as much as possible.
int leader[MAX_NODES];
// For a given vertex of index i, has_cycle[i] should be "true" if that
// vertex is part of a connected component that has a cycle, and otherwise
// "false". (However, this is only required to be accurate for a current
// set leader, so that the function query_cycle can return the correct
// value.)
bool has_cycle[MAX_NODES];
// The number of components found.
int num_components;
DisjointSets() {
// Initialize leaders to -1
for (int i = 0; i < MAX_NODES; i++) leader[i] = -1;
// Initialize cycle detection to false
for (int i = 0; i < MAX_NODES; i++) has_cycle[i] = false;
// The components will need to be counted.
num_components = 0;
}
// If the leader for vertex i is set to -1, then report vertex i as its
// own leader. Otherwise, keep looking for the leader recursively.
int find_leader(int i) {
if (leader[i] < 0) return i;
else return find_leader(leader[i]);
}
// query_cycle(i) returns true if vertex i is part of a connected component
// that has a cycle. Otherwise, it returns false. This relies on the
// has_cycle array being maintained correctly for leader vertices.
bool query_cycle(int i) {
int root_i = find_leader(i);
return has_cycle[root_i];
}
// Please see the descriptions of the next two functions below.
// (Do not edit these functions here; edit them below.)
void dsunion(int i, int j);
void count_comps(int n);
};
// TASK 1:
// dsunion performs disjoint set union. The reported leader of vertex j
// will become the leader of vertex i as well.
// Assuming it is only called once per pair of vertices i and j,
// it can detect when a set is including an edge that completes a cycle.
// This is evident when a vertex is assigned a leader that is the same
// as the one it was already assigned previously.
// Also, if you join two sets where either set already was known to
// have a cycle, then the joined set still has a cycle.
// Modify the implementation of dsunion below to properly adjust the
// has_cycle array so that query_cycle(root_j) accurately reports
// whether the connected component of root_j contains a cycle.
void DisjointSets::dsunion(int i, int j) {
bool i_had_cycle = query_cycle(i);
bool j_had_cycle = query_cycle(j);
int root_i = find_leader(i);
int root_j = find_leader(j);
if (root_i != root_j) {
leader[root_i] = root_j;
root_i = root_j;
}
else {
// A cycle is detected when dsunion is performed on an edge
// where both vertices already report the same set leader.
// TODO: Your work here! Update has_cycle accordingly.
has_cycle[i] = true;
has_cycle[j] = true;
}
// Also, if either one of the original sets was known to have a cycle
// already, then the newly joined set still has a cycle.
// TODO: Your work here!
if(i_had_cycle)
has_cycle[j] = true;
if(j_had_cycle)
has_cycle[i] = true;
}
// TASK 2:
// count_comps should count how many connected components there are in
// the graph, and it should set the num_components member variable
// to that value. The input n is the number of vertices in the graph.
// (Remember, the vertices are numbered with indices 0 through n-1.)
void DisjointSets::count_comps(int n) {
// Insert code here to count the number of connected components
// and store it in the "num_components" member variable.
// Hint: If you've already performed set union on all the apparent edges,
// what information can you get from the leaders now?
std::unordered_map<int, int> mymap{};
std::cout << leader[0];
for (int i = 0; i < MAX_NODES; i++){
int root = find_leader(i);
if(mymap.find(root)!=std::end(mymap)){
mymap.at(root)++;
}else{
mymap[root] = 1;
}
}
num_components = std::count_if(std::begin(mymap), std::end(mymap), [](std::pair<const int, int> x){return x.second > 1;});
}
int main() {
constexpr int NUM_EDGES = 9;
constexpr int NUM_VERTS = 8;
int edges[NUM_EDGES][2] = {{0,1},{1,2},{3,4},{4,5},{5,6},{6,7},{7,3},{3,5},{4,6}};
DisjointSets d;
// The union operations below should also maintain information
// about whether leaders are part of connected components that
// contain cycles. (See TASK 1 above where dsunion is defined.)
for (int i = 0; i < NUM_EDGES; i++)
d.dsunion(edges[i][0],edges[i][1]);
// The count_comps call below should count the number of components.
// (See TASK 2 above where count_comps is defined.)
d.count_comps(NUM_VERTS);
std::cout << "For edge list: ";
for (int i = 0; i < NUM_EDGES; i++) {
std::cout << "(" << edges[i][0] << ","
<< edges[i][1] << ")"
// This avoids displaying a comma at the end of the list.
<< ((i < NUM_EDGES-1) ? "," : "\n");
}
std::cout << "You counted num_components: " << d.num_components << std::endl;
// The output for the above set of edges should be:
// You counted num_components: 2
std::cout << "Cycle reported for these vertices (if any):" << std::endl;
for (int i=0; i<NUM_VERTS; i++) {
if (d.query_cycle(i)) std::cout << i << " ";
}
std::cout << std::endl;
// The cycle detection output for the above set of edges should be:
// Cycle reported for these vertices (if any):
// 3 4 5 6 7
return 0;
}
| 36.201183 | 124 | 0.676038 | e-dnx |
cd8e5f362435eb31aad76c453bcbbfa3bc64c823 | 301 | cpp | C++ | tests/dsn7/src/Main.cpp | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 13 | 2015-02-26T22:46:18.000Z | 2020-03-24T11:53:06.000Z | tests/dsn7/src/Main.cpp | PacificBiosciences/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 5 | 2016-02-25T17:08:19.000Z | 2018-01-20T15:24:36.000Z | tests/dsn7/src/Main.cpp | TonyBrewer/OpenHT | 63898397de4d303ba514d88b621cc91367ffe2a6 | [
"BSD-3-Clause"
] | 12 | 2015-04-13T21:39:54.000Z | 2021-01-15T01:00:13.000Z | #include "Ht.h"
using namespace Ht;
int main(int argc, char **argv)
{
CHtHif *pHtHif = new CHtHif();
CHtSuUnit *pSuUnit = new CHtSuUnit(pHtHif);
pSuUnit->SendCall_cxr1();
// wait for return
while (!pSuUnit->RecvReturn_cxr1()) usleep(1000);
delete pHtHif;
printf("PASSED\n");
return 0;
}
| 15.05 | 50 | 0.681063 | TonyBrewer |
cd92a471b97ac69e681ab7fd68c5a3c0be79bb14 | 732 | cpp | C++ | Code/Modules/mutant/mutant/binary_io_psp.cpp | mrneo240/suicide-barbie | c8b01f9c04755e7f6d1d261fc4a1600cd6705b96 | [
"MIT"
] | 57 | 2021-01-02T00:18:22.000Z | 2022-03-27T14:40:25.000Z | Code/Modules/mutant/mutant/binary_io_psp.cpp | mrneo240/suicide-barbie | c8b01f9c04755e7f6d1d261fc4a1600cd6705b96 | [
"MIT"
] | 1 | 2021-01-05T20:43:02.000Z | 2021-01-11T23:04:41.000Z | Code/Modules/mutant/mutant/binary_io_psp.cpp | mrneo240/suicide-barbie | c8b01f9c04755e7f6d1d261fc4a1600cd6705b96 | [
"MIT"
] | 8 | 2021-01-01T22:34:43.000Z | 2022-03-22T01:21:26.000Z | #include "binary_io_psp.h"
//#include "types_ios.h"
#include <pspiofilemgr.h>
namespace mutant
{
file_input::file_input( std::string const& name )
: mFile( 0 )
{
if( (mFile = sceIoOpen( name.c_str(), PSP_O_RDONLY, 0777 )) > 0 )
{
sceIoLseek(mFile, 0, PSP_SEEK_SET);
}
}
file_input::~file_input() {
if( mFile )
sceIoClose( mFile );
}
void file_input::read( void* dest, int n, int* wasRead ) {
int bytesRead = 0;
if( mFile )
bytesRead = sceIoRead( mFile, dest, n );
if( wasRead )
*wasRead = bytesRead;
}
file_output::file_output( std::string const& name ) {
}
file_output::~file_output() {
}
void file_output::write( void const* src, int n, int* wasWritten ) {
*wasWritten = 0;
}
}
| 17.023256 | 69 | 0.63388 | mrneo240 |
cd93562a63f2687ad478fa2ad239374c69326e5d | 447 | cpp | C++ | code/GravitationalObject.cpp | gtnardy/flappy_cow | bde49ac7e67194355e0011a53b88cf99ecd5ab83 | [
"MIT"
] | null | null | null | code/GravitationalObject.cpp | gtnardy/flappy_cow | bde49ac7e67194355e0011a53b88cf99ecd5ab83 | [
"MIT"
] | 2 | 2019-05-06T17:59:29.000Z | 2019-05-06T18:02:17.000Z | code/GravitationalObject.cpp | gtnardy/flappy_cow | bde49ac7e67194355e0011a53b88cf99ecd5ab83 | [
"MIT"
] | null | null | null | #include "GravitationalObject.h"
GravitationalObject::GravitationalObject(Vector2 _size, Vector2 _position, string image_path, double _weight): Object(_size, _position, image_path) {
weight = _weight;
}
GravitationalObject::~GravitationalObject() {
}
bool GravitationalObject::draw(bool paused) {
if (!paused)
tick();
return Object::draw(paused);
}
void GravitationalObject::tick() {
timeFree++;
position.y += timeFree / weight;
}
| 17.88 | 149 | 0.742729 | gtnardy |
cd938fe1c190186b315f5154df89e9b4185f3725 | 17,401 | cpp | C++ | goto-programs/goto_convert_functions.cpp | holao09/esbmc | 659c006a45e9aaf8539b12484e2ec2b093cc6f02 | [
"BSD-3-Clause"
] | null | null | null | goto-programs/goto_convert_functions.cpp | holao09/esbmc | 659c006a45e9aaf8539b12484e2ec2b093cc6f02 | [
"BSD-3-Clause"
] | null | null | null | goto-programs/goto_convert_functions.cpp | holao09/esbmc | 659c006a45e9aaf8539b12484e2ec2b093cc6f02 | [
"BSD-3-Clause"
] | null | null | null | /*******************************************************************\
Module: Goto Programs with Functions
Author: Daniel Kroening
Date: June 2003
\*******************************************************************/
#include <assert.h>
#include <base_type.h>
#include <prefix.h>
#include <std_code.h>
#include <std_expr.h>
#include <type_byte_size.h>
#include <c_types.h>
#include "goto_convert_functions.h"
#include "goto_inline.h"
#include "remove_skip.h"
#include "i2string.h"
goto_convert_functionst::goto_convert_functionst(
contextt &_context,
optionst &_options,
goto_functionst &_functions,
message_handlert &_message_handler):
goto_convertt(_context, _options, _message_handler),
functions(_functions)
{
if (options.get_bool_option("no-inlining"))
inlining=false;
else
inlining=true;
}
goto_convert_functionst::~goto_convert_functionst()
{
}
void goto_convert_functionst::goto_convert()
{
// warning! hash-table iterators are not stable
symbol_listt symbol_list;
context.Foreach_operand_in_order(
[&symbol_list] (symbolt& s)
{
if(!s.is_type && s.type.is_code())
symbol_list.push_back(&s);
}
);
for(symbol_listt::iterator
it=symbol_list.begin();
it!=symbol_list.end();
it++)
{
convert_function(**it);
}
functions.compute_location_numbers();
}
bool goto_convert_functionst::hide(const goto_programt &goto_program)
{
for(goto_programt::instructionst::const_iterator
i_it=goto_program.instructions.begin();
i_it!=goto_program.instructions.end();
i_it++)
{
for(goto_programt::instructiont::labelst::const_iterator
l_it=i_it->labels.begin();
l_it!=i_it->labels.end();
l_it++)
{
if(*l_it=="__ESBMC_HIDE")
return true;
}
}
return false;
}
void goto_convert_functionst::add_return(
goto_functiont &f,
const locationt &location)
{
if(!f.body.instructions.empty() &&
f.body.instructions.back().is_return())
return; // not needed, we have one already
// see if we have an unconditional goto at the end
if(!f.body.instructions.empty() &&
f.body.instructions.back().is_goto() &&
is_constant_bool2t(f.body.instructions.back().guard) &&
to_constant_bool2t(f.body.instructions.back().guard).constant_value)
return;
goto_programt::targett t=f.body.add_instruction();
t->make_return();
t->location=location;
const typet &thetype = (f.type.return_type().id() == "symbol")
? ns.follow(f.type.return_type())
: f.type.return_type();
exprt rhs=exprt("sideeffect", thetype);
rhs.statement("nondet");
expr2tc tmp_expr;
migrate_expr(rhs, tmp_expr);
t->code = code_return2tc(tmp_expr);
}
void goto_convert_functionst::convert_function(const irep_idt &identifier)
{
symbolt *s = context.find_symbol(identifier);
assert(s != nullptr);
convert_function(*s);
}
/*******************************************************************\
Function: goto_convert_functionst::convert_function
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void goto_convert_functionst::convert_function(symbolt &symbol)
{
irep_idt identifier = symbol.name;
// Apply a SFINAE test: discard unused C++ templates.
if (symbol.value.get("#speculative_template") == "1" &&
symbol.value.get("#template_in_use") != "1")
return;
// make tmp variables local to function
tmp_symbol_prefix=id2string(symbol.name)+"::$tmp::";
temporary_counter=0;
goto_functiont &f=functions.function_map[identifier];
f.type=to_code_type(symbol.type);
f.body_available=symbol.value.is_not_nil();
if(!f.body_available) return;
if(!symbol.value.is_code())
{
err_location(symbol.value);
throw "got invalid code for function `"+id2string(identifier)+"'";
}
const code_typet::argumentst &arguments=f.type.arguments();
std::list<irep_idt> arg_ids;
// add as local variables
for(code_typet::argumentst::const_iterator
it=arguments.begin();
it!=arguments.end();
it++)
{
const irep_idt &identifier=it->get_identifier();
assert(identifier!="");
arg_ids.push_back(identifier);
}
if(!symbol.value.is_code())
{
err_location(symbol.value);
throw "got invalid code for function `"+id2string(identifier)+"'";
}
codet tmp(to_code(symbol.value));
locationt end_location;
if(to_code(symbol.value).get_statement()=="block")
end_location=static_cast<const locationt &>(
symbol.value.end_location());
else
end_location.make_nil();
targets=targetst();
targets.return_set=true;
targets.return_value=
f.type.return_type().id()!="empty" &&
f.type.return_type().id()!="constructor" &&
f.type.return_type().id()!="destructor";
goto_convert_rec(tmp, f.body);
// add non-det return value, if needed
if(targets.return_value)
add_return(f, end_location);
// add "end of function"
goto_programt::targett t=f.body.add_instruction();
t->type=END_FUNCTION;
t->location=end_location;
//t->code.identifier(identifier);
//XXXjmorse, disabled in migration, don't think this does anything
if(to_code(symbol.value).get_statement()=="block")
t->location=static_cast<const locationt &>(
symbol.value.end_location());
// do local variables
Forall_goto_program_instructions(i_it, f.body)
{
i_it->add_local_variables(arg_ids);
i_it->function=identifier;
}
// remove_skip depends on the target numbers
f.body.compute_target_numbers();
remove_skip(f.body);
f.body.update();
if(hide(f.body))
f.type.hide(true);
}
void goto_convert(
contextt &context,
optionst &options,
goto_functionst &functions,
message_handlert &message_handler)
{
goto_convert_functionst goto_convert_functions(
context, options, functions, message_handler);
try
{
goto_convert_functions.thrash_type_symbols();
goto_convert_functions.fixup_unions();
goto_convert_functions.goto_convert();
}
catch(int)
{
goto_convert_functions.error();
}
catch(const char *e)
{
goto_convert_functions.error(e);
}
catch(const std::string &e)
{
goto_convert_functions.error(e);
}
if(goto_convert_functions.get_error_found())
throw 0;
}
void
goto_convert_functionst::collect_type(const irept &type, typename_sett &deps)
{
if (type.id() == "pointer")
return;
if (type.id() == "symbol") {
deps.insert(type.identifier());
return;
}
collect_expr(type, deps);
return;
}
void
goto_convert_functionst::collect_expr(const irept &expr, typename_sett &deps)
{
if (expr.id() == "pointer")
return;
forall_irep(it, expr.get_sub()) {
collect_expr(*it, deps);
}
forall_named_irep(it, expr.get_named_sub()) {
if (it->first == "type" || it->first == "subtype")
collect_type(it->second, deps);
else
collect_type(it->second, deps);
}
forall_named_irep(it, expr.get_comments()) {
collect_type(it->second, deps);
}
return;
}
void
goto_convert_functionst::rename_types(irept &type, const symbolt &cur_name_sym,
const irep_idt &sname)
{
if (type.id() == "pointer")
return;
// Some type symbols aren't entirely correct. This is because (in the current
// 27_exStbFb test) some type symbols get the module name inserted into the
// name -- so c::int32_t becomes c::main::int32_t.
//
// Now this makes entire sense, because int32_t could be something else in
// some other file. However, because type symbols aren't squashed at type
// checking time (which, you know, might make sense) we now don't know what
// type symbol to link "c::int32_t" up to. So; instead we test to see whether
// a type symbol is linked correctly, and if it isn't we look up what module
// the current block of code came from and try to guess what type symbol it
// should have.
typet type2;
if (type.id() == "symbol") {
if (type.identifier() == sname) {
// A recursive symbol -- the symbol we're about to link to is in fact the
// one that initiated this chain of renames. This leads to either infinite
// loops or segfaults, depending on the phase of the moon.
// It should also never happen, but with C++ code it does, because methods
// are part of the type, and methods can take a full struct/object as a
// parameter, not just a reference/pointer. So, that's a legitimate place
// where we have this recursive symbol dependancy situation.
// The workaround to this is to just ignore it, and hope that it doesn't
// become a problem in the future.
return;
}
const symbolt *sym;
if (!ns.lookup(type.identifier(), sym)) {
// If we can just look up the current type symbol, use that.
type2 = ns.follow((typet&)type);
} else {
// Otherwise, try to guess the namespaced type symbol
std::string ident = type.identifier().as_string();
std::string ident2;
// Detect module prefix, then insert module name after it.
if (ident.c_str()[0] == 'c' && ident.c_str()[1] == 'p' &&
ident.c_str()[2] == 'p') {
ident2 = "cpp::" + cur_name_sym.module.as_string() + "::" +
ident.substr(5, std::string::npos);
} else {
ident2 = "c::" + cur_name_sym.module.as_string() + "::" +
ident.substr(3, std::string::npos);
}
// Try looking that up.
if (!ns.lookup(irep_idt(ident2), sym)) {
irept tmptype = type;
tmptype.identifier(irep_idt(ident2));
type2 = ns.follow((typet&)tmptype);
} else {
// And if we fail
std::cerr << "Can't resolve type symbol " << ident;
std::cerr << " at symbol squashing time" << std::endl;
abort();
}
}
type = type2;
return;
}
rename_exprs(type, cur_name_sym, sname);
return;
}
void
goto_convert_functionst::rename_exprs(irept &expr, const symbolt &cur_name_sym,
const irep_idt &sname)
{
if (expr.id() == "pointer")
return;
Forall_irep(it, expr.get_sub())
rename_exprs(*it, cur_name_sym, sname);
Forall_named_irep(it, expr.get_named_sub()) {
if (it->first == "type" || it->first == "subtype") {
rename_types(it->second, cur_name_sym, sname);
} else {
rename_exprs(it->second, cur_name_sym, sname);
}
}
Forall_named_irep(it, expr.get_comments())
rename_exprs(it->second, cur_name_sym, sname);
return;
}
void
goto_convert_functionst::wallop_type(irep_idt name,
std::map<irep_idt, std::set<irep_idt> > &typenames,
const irep_idt &sname)
{
// If this type doesn't depend on anything, no need to rename anything.
std::set<irep_idt> &deps = typenames.find(name)->second;
if (deps.size() == 0)
return;
// Iterate over our dependancies ensuring they're resolved.
for (std::set<irep_idt>::iterator it = deps.begin(); it != deps.end(); it++)
wallop_type(*it, typenames, sname);
// And finally perform renaming.
symbolt* s = context.find_symbol(name);
rename_types(s->type, *s, sname);
deps.clear();
return;
}
void
goto_convert_functionst::thrash_type_symbols(void)
{
// This function has one purpose: remove as many type symbols as possible.
// This is easy enough by just following each type symbol that occurs and
// replacing it with the value of the type name. However, if we have a pointer
// in a struct to itself, this breaks down. Therefore, don't rename types of
// pointers; they have a type already; they're pointers.
// Collect a list of all type names. This it required before this entire
// thing has no types, and there's no way (in C++ converted code at least)
// to decide what name is a type or not.
typename_sett names;
context.foreach_operand(
[this, &names] (const symbolt& s)
{
collect_expr(s.value, names);
collect_type(s.type, names);
}
);
// Try to compute their dependencies.
typename_mapt typenames;
context.foreach_operand(
[this, &names, &typenames] (const symbolt& s)
{
if (names.find(s.name) != names.end())
{
typename_sett list;
collect_expr(s.value, list);
collect_type(s.type, list);
typenames[s.name] = list;
}
}
);
for (typename_mapt::iterator it = typenames.begin(); it != typenames.end(); it++)
it->second.erase(it->first);
// Now, repeatedly rename all types. When we encounter a type that contains
// unresolved symbols, resolve it first, then include it into this type.
// This means that we recurse to whatever depth of nested types the user
// has. With at least a meg of stack, I doubt that's really a problem.
std::map<irep_idt, std::set<irep_idt> >::iterator it;
for (it = typenames.begin(); it != typenames.end(); it++)
wallop_type(it->first, typenames, it->first);
// And now all the types have a fixed form, rename types in all existing code.
context.Foreach_operand(
[this] (symbolt& s)
{
rename_types(s.type, s, s.name);
rename_exprs(s.value, s, s.name);
}
);
return;
}
void
goto_convert_functionst::fixup_unions(void)
{
// Iterate over all types and expressions, replacing:
// * Non-pointer union types with byte arrays of corresponding size
// * All union member accesses with the following pattern:
// dataobj.field => ((uniontype*)&dataobj)->field
// Thus ensuring that all unions become byte arrays, and all accesses to
// them _as_ unions get converted into byte array accesses at the pointer
// dereference layer.
context.Foreach_operand(
[this] (symbolt& s)
{
fix_union_type(s.type, false);
fix_union_expr(s.value);
}
);
}
void
goto_convert_functionst::fix_union_type(typet &type, bool is_pointer)
{
if (!is_pointer && type.is_union()) {
// Replace with byte array. Must use migrated type though, because we need
// one authorative type_byte_size function
type2tc new_type;
migrate_type(type, new_type);
auto size = type_byte_size(*new_type);
new_type = type2tc(new array_type2t(get_uint8_type(),
gen_ulong(size.to_uint64()), false));
type = migrate_type_back(new_type);
return;
}
// Otherwise, recurse, taking care to handle pointers appropriately. All
// pointers to unions should remain union types.
if (type.is_pointer()) {
fix_union_type(type.subtype(), true);
} else {
Forall_irep(it, type.get_sub())
fix_union_type((typet&)*it, false);
Forall_named_irep(it, type.get_named_sub())
fix_union_type((typet&)it->second, false);
}
}
void
goto_convert_functionst::fix_union_expr(exprt &expr)
{
// We care about one kind of expression: member expressions that access a
// union field. We also need to rewrite types as we come across them.
if (expr.is_member()) {
// Are we accessing a union? If it's already a dereference, that's fine.
if (expr.op0().type().is_union() && !expr.op0().is_dereference()) {
// Rewrite 'dataobj.field' to '((uniontype*)&dataobj)->field'
expr2tc dataobj;
migrate_expr(expr.op0(), dataobj);
type2tc union_type = dataobj->type;
auto size = type_byte_size(*union_type);
type2tc array_type = type2tc(new array_type2t(get_uint8_type(),
gen_ulong(size.to_uint64()), false));
type2tc union_pointer(new pointer_type2t(union_type));
address_of2tc addrof(array_type, dataobj);
typecast2tc cast(union_pointer, addrof);
dereference2tc deref(union_type, cast);
expr.op0() = migrate_expr_back(deref);
// Fix type -- it needs to remain a union at the top level
fix_union_type(expr.type(), false);
fix_union_expr(expr.op0());
} else {
Forall_operands(it, expr)
fix_union_expr(*it);
fix_union_type(expr.type(), false);
}
} else if (expr.is_union()) {
// There may be union types embedded within this type; those need their
// types fixing too.
Forall_operands(it, expr)
fix_union_expr(*it);
fix_union_type(expr.type(), false);
// A union expr is a constant/literal union. This needs to be flattened
// out at this stage. Handle this by migrating immediately (which will
// eliminate anything on union type), and overwriting this expression.
expr2tc new_expr;
migrate_expr(expr, new_expr);
expr = migrate_expr_back(new_expr);
} else if (expr.is_dereference()) {
// We want the dereference of a union pointer to evaluate to a union type,
// as that can be picked apart by the pointer handling code. However, do
// rewrite types if it points at a struct that contains a union, because
// the correct type of a struct reference with a union is it, has it's
// fields rewritten to be arrays. Actual accesses to that union field will
// be transformed into a dereference to one of the fields _within_ the
// union, so we never up constructing a union reference.
Forall_operands(it, expr)
fix_union_expr(*it);
fix_union_type(expr.type(), true);
} else {
// Default action: recurse and beat types.
fix_union_type(expr.type(), false);
Forall_operands(it, expr)
fix_union_expr(*it);
}
}
| 28.714521 | 83 | 0.655882 | holao09 |
cd964d39477eb22aec62da3c0f8f403efdb6969a | 2,554 | cpp | C++ | BehaviroalPatterns/observer/Observer.cpp | enuguru/design_patterns | 7b5a70d65811c39d15cbfa8b7a0603a16a851265 | [
"MIT"
] | null | null | null | BehaviroalPatterns/observer/Observer.cpp | enuguru/design_patterns | 7b5a70d65811c39d15cbfa8b7a0603a16a851265 | [
"MIT"
] | null | null | null | BehaviroalPatterns/observer/Observer.cpp | enuguru/design_patterns | 7b5a70d65811c39d15cbfa8b7a0603a16a851265 | [
"MIT"
] | null | null | null | /*
* C++ Design Patterns:
* Author: Junzhuo Du [github.com/Junzhuodu]
* 2020
*
*/
#include <iostream>
#include <vector>
class Subject;
class Observer {
public:
Observer(const int id) : id_(id) {}
virtual ~Observer() {}
virtual int getState() = 0;
virtual void update(Subject* subject) = 0;
virtual int getId() = 0;
protected:
int id_;
};
class ConcreteObserver : public Observer {
public:
ConcreteObserver(const int state, const int id)
: object_state_(state), Observer(id) {}
~ConcreteObserver() {}
int getState() {
return object_state_;
}
int getId() {
return id_;
}
void update(Subject* subject);
private:
int object_state_;
};
class Subject {
public:
virtual ~Subject() {}
void attach(Observer* observer) {
observers_.push_back(observer);
}
void detach(const int id) {
for (auto it = observers_.begin(); it != observers_.end(); ++it) {
if ((*it)->getId() == id) {
observers_.erase(it);
}
}
}
void notify() {
for (auto observer : observers_) {
observer->update(this);
}
}
virtual int getState() = 0;
virtual void setState(const int state) = 0;
private:
std::vector<Observer*> observers_;
};
class ConcreteSubject : public Subject {
public:
~ConcreteSubject() {}
int getState() {
return subject_state_;
}
void setState(const int state) {
subject_state_ = state;
}
private:
int subject_state_;
};
void ConcreteObserver::update(Subject *subject) {
object_state_ = subject->getState();
std::cout << "Observer(id=" << id_ << ") update state to: " << object_state_ << std::endl;
}
int main() {
ConcreteObserver observer1(1000, 1);
ConcreteObserver observer2(2000, 2);
std::cout << "Observer1 state: " << observer1.getState() << std::endl;
std::cout << "Observer2 state: " << observer2.getState() << std::endl;
Subject* subject = new ConcreteSubject();
subject->attach(&observer1);
subject->attach(&observer2);
subject->setState(10);
subject->notify();
std::cout << "Observer1 state: " << observer1.getState() << std::endl;
std::cout << "Observer2 state: " << observer2.getState() << std::endl;
subject->detach(0);
subject->setState(100);
subject->notify();
std::cout << "Observer1 state: " << observer1.getState() << std::endl;
std::cout << "Observer2 state: " << observer2.getState() << std::endl;
}
| 20.764228 | 94 | 0.596711 | enuguru |
cd9c5957cd1ea5eebce0b60ec671b3d6e987a1a9 | 2,724 | cpp | C++ | exptree.cpp | sushithreddy75/DATA-STRUCTURES | ec948dbaadd0c675596ba1b6fd7c71ef14c9d656 | [
"MIT"
] | 1 | 2021-07-22T04:19:46.000Z | 2021-07-22T04:19:46.000Z | exptree.cpp | sushithreddy75/DATA-STRUCTURES | ec948dbaadd0c675596ba1b6fd7c71ef14c9d656 | [
"MIT"
] | null | null | null | exptree.cpp | sushithreddy75/DATA-STRUCTURES | ec948dbaadd0c675596ba1b6fd7c71ef14c9d656 | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
struct etnode
{
etnode *lc;
int tag;
union
{
int x;
char c;
}data;
etnode *rc;
};
typedef etnode * etptr;
struct stack
{
etptr data;
stack *next;
};
struct snode
{
char data;
snode* next;
};
typedef snode* stk;
void push(stk &s,char t)
{
if(s==NULL)
{
s=new(snode);
s->data=t;
s->next=NULL;
return;
}
stk t1=new(snode);
t1->data=t;
t1->next=s;
s=t1;
}
typedef stack* sptr;
void push(sptr &s,etptr t)
{
if(s==NULL)
{
s=new(stack);
s->data=t;
s->next=NULL;
return;
}
sptr t1=new(stack);
t1->data=t;
t1->next=s;
s=t1;
}
void construct(sptr &st,string s,int &i)
{
if(s[i]=='\0')
return;
while(s[i]==' ')
i++;
if(s[i]>='0' && s[i]<='9')
{
int x=0;
while(s[i]!='\0' && s[i]>='0' && s[i]<='9')
{
x*=10;
x+=s[i]-'0';
i++;
}
i++;
etptr t=new(etnode);
t->tag=1;
t->lc=t->rc=NULL;
t->data.x=x;
push(st,t);
return construct(st,s,i);
}
etptr t=new(etnode);
t->data.c=s[i];
t->tag=0;
if(st)
{
t->rc=st->data;
st=st->next;
}
else
t->rc=NULL;
if(st)
{
t->lc=st->data;
st=st->next;
}
else
t->lc=NULL;
push(st,t);
i++;
while(s[i]==' ')
i++;
construct(st,s,i);
}
void print(etptr t)
{
if(t==NULL)
return;
print(t->lc);
print(t->rc);
if(t->tag==1)
cout<<t->data.x<<" ";
else
cout<<t->data.c<<" ";
}
int eval(etptr t)
{
if(t==NULL)
return 0;
if(t->tag==1)
return t->data.x;
int x=eval(t->lc);
int y=eval(t->rc);
//cout<<x<<" "<<y<<" "<<t->data.c<<endl;
if(t->data.c=='*')
return x*y;
if(t->data.c=='/')
return x/y;
if(t->data.c=='-')
return x-y;
return x+y;
}
void infixtopostfix(string &s,string s1,int &i,stk &st)
{
if(s1[i]=='(')
{
push(st,s1[i]);
i++;
return infixtopostfix(s,s1,i,st);
}
if(s1[i]=='\0')
{
while(st!=NULL)
{
s+=st->data;
//s+=' ';
st=st->next;
}
return;
}
if(s1[i]==')')
{
i++;
while(st->data!='(')
{
s+=st->data;
//s+=' ';
st=st->next;
}
st=st->next;
return infixtopostfix(s,s1,i,st);
}
if(s1[i]==' '||(s1[i]>='0' && s1[i]<='9'))
{
s+=' ';
while((s1[i]>='0' && s1[i]<='9'))
{
s+=s1[i];
i++;
}
s+=' ';
return infixtopostfix(s,s1,i,st);
}
if(s1[i]=='+'||s1[i]=='-')
{
while(st!=NULL && st->data!='(')
{
s+=st->data;
st=st->next;
}
}
else
{
while(st!=NULL && (st->data=='*' || st->data=='/'))
{
s+=st->data;
st=st->next;
}
}
push(st,s1[i]);
i++;
infixtopostfix(s,s1,i,st);
}
int main()
{
string s;
getline(cin,s);
int i=0;
sptr st=NULL;
string s1="";//int i=0;
stk st1=NULL;
infixtopostfix(s1,s,i,st1);
i=0;
construct(st,s1,i);
etptr T=st->data;
//print(T);cout<<endl;
cout<<eval(T)<<endl;
//cout<<s1<<endl;
} | 13.287805 | 55 | 0.497063 | sushithreddy75 |
cd9c6382f865ff964a32975d1d352451dae02f73 | 6,250 | cpp | C++ | tests/MinMaxManagerTestSuite.cpp | psobow/TicTacToeCpp | 479ba81b9fcb37be4776ef528f0e8d81bed4245c | [
"MIT"
] | null | null | null | tests/MinMaxManagerTestSuite.cpp | psobow/TicTacToeCpp | 479ba81b9fcb37be4776ef528f0e8d81bed4245c | [
"MIT"
] | null | null | null | tests/MinMaxManagerTestSuite.cpp | psobow/TicTacToeCpp | 479ba81b9fcb37be4776ef528f0e8d81bed4245c | [
"MIT"
] | null | null | null | #include "../libs/catch.hpp"
#include "MinMaxManagerTestSuite.hh"
/* TEST TEMPLATE
SCENARIO( "", "[MinMaxManager]" ){
GIVEN( "MinMaxManager, BoardManager initialization, Clean up board" ) {
BoardManager *boardManager = BoardManager::getInstance();
boardManager->resetEverySlot();
WHEN( "CASE 1" ){
THEN( "Result" ){
REQUIRE( );
}
}
}
}
*/
static BoardManager *boardManager = BoardManager::getInstance();
static MinMaxManager *minMaxManager = MinMaxManager::getInstance();
static MinMaxManagerTestSuite bridgeToTestClass;
SCENARIO( "executeTheBestComputerMove", "[MinMaxManager]" ){
GIVEN( "Clean up board" ) {
boardManager->resetEverySlot();
WHEN( "CASE 1: Empty board" ){
minMaxManager->executeTheBestComputerMove();
THEN( "Result" ){
REQUIRE( bridgeToTestClass.getTheBestMove().equals(Coordinates(0,0)) );
}
}
WHEN( "CASE 2: ") {
boardManager->addNewCharacter(Coordinates(0,1), Participant::HUMAN);
boardManager->addNewCharacter(Coordinates(1,2), Participant::HUMAN);
boardManager->addNewCharacter(Coordinates(2,2), Participant::HUMAN);
boardManager->addNewCharacter(Coordinates(2,0), Participant::COMPUTER);
boardManager->addNewCharacter(Coordinates(2,1), Participant::COMPUTER);
minMaxManager->executeTheBestComputerMove();
THEN( "Result" ){ // expected move Coordinates (0,2)
REQUIRE( bridgeToTestClass.getTheBestMove().equals(Coordinates(0,2)) );
}
}
WHEN( "CASE 3: ") { // computer will lose in next oponent move in every case. in this scenario expceted computer move is first empty slot
boardManager->addNewCharacter(Coordinates(0,2), Participant::COMPUTER);
boardManager->addNewCharacter(Coordinates(2,0), Participant::COMPUTER);
boardManager->addNewCharacter(Coordinates(0,0), Participant::HUMAN);
boardManager->addNewCharacter(Coordinates(1,0), Participant::HUMAN);
boardManager->addNewCharacter(Coordinates(1,1), Participant::HUMAN);
minMaxManager->executeTheBestComputerMove();
THEN( "Result" ){ // expected move Coordinates (0,1)
REQUIRE( bridgeToTestClass.getTheBestMove().equals(Coordinates(0,1)) );
}
}
}
}
SCENARIO( "scoreGameFromComputerPOV", "[MinMaxManager]" ){
// findWinner algorithm required at least 5 taken slots on 3x3 board to search for winner
GIVEN( "Clean up board" ) {
boardManager->resetEverySlot();
WHEN( "CASE 1: Board contatin win state for Computer" ){
boardManager->addNewCharacter(Coordinates(0,0), Participant::COMPUTER);
boardManager->addNewCharacter(Coordinates(0,1), Participant::COMPUTER);
boardManager->addNewCharacter(Coordinates(0,2), Participant::COMPUTER);
boardManager->addNewCharacter(Coordinates(2,0), Participant::HUMAN);
boardManager->addNewCharacter(Coordinates(2,1), Participant::HUMAN);
const int DEPTH = 1;
const int RESULT = bridgeToTestClass.scoreGameFromComputerPOV(DEPTH);
THEN( "Result" ){
REQUIRE( RESULT == 999 );
}
}
WHEN( "CASE 2: Board contatin win state for Player" ){
boardManager->addNewCharacter(Coordinates(0,0), Participant::HUMAN);
boardManager->addNewCharacter(Coordinates(0,1), Participant::HUMAN);
boardManager->addNewCharacter(Coordinates(0,2), Participant::HUMAN);
boardManager->addNewCharacter(Coordinates(2,0), Participant::COMPUTER);
boardManager->addNewCharacter(Coordinates(2,1), Participant::COMPUTER);
const int DEPTH = 1;
const int RESULT = bridgeToTestClass.scoreGameFromComputerPOV(DEPTH);
THEN( "Result" ){
REQUIRE( RESULT == -999 );
}
}
WHEN( "CASE 3: Board does not contatin win state" ){
boardManager->addNewCharacter(Coordinates(0,0), Participant::COMPUTER);
boardManager->addNewCharacter(Coordinates(0,1), Participant::HUMAN);
boardManager->addNewCharacter(Coordinates(0,2), Participant::COMPUTER);
boardManager->addNewCharacter(Coordinates(2,0), Participant::HUMAN);
boardManager->addNewCharacter(Coordinates(2,1), Participant::HUMAN);
boardManager->addNewCharacter(Coordinates(2,2), Participant::COMPUTER);
const int DEPTH = 1;
const int RESULT = bridgeToTestClass.scoreGameFromComputerPOV(DEPTH);
THEN( "Result" ){
REQUIRE( RESULT == 0 );
}
}
}
}
SCENARIO( "get Min & Max value index", "[MinMaxManager]" ){
GIVEN( "Vector initialization" ) {
const std::vector<int> EXAMPLE_VECTOR {0,1,2,3,4,5};
WHEN( "CASE 1: get MIN value index" ){
const int RESULT = bridgeToTestClass.getMinValueIndex(EXAMPLE_VECTOR);
THEN( "Result" ){
REQUIRE( RESULT == 0 );
}
}
WHEN( "CASE 2: get MAX value index" ){
const int RESULT = bridgeToTestClass.getMaxValueIndex(EXAMPLE_VECTOR);
THEN( "Result" ){
REQUIRE( RESULT == 5 );
}
}
}
}
const int MinMaxManagerTestSuite::scoreGameFromComputerPOV(const int DEPTH) const{
return minMaxManager->scoreGameFromComputerPOV(DEPTH);
}
const int MinMaxManagerTestSuite::calculateTheBestMoveFor(const Participant& TURN_TAKING_PLAYER, int depth, int alpha, int beta){
return minMaxManager->calculateTheBestMoveFor(TURN_TAKING_PLAYER, depth, alpha, beta);
}
const int MinMaxManagerTestSuite::getMaxValueIndex(const std::vector<int>& VEC) const{
return minMaxManager->getMaxValueIndex(VEC);
}
const int MinMaxManagerTestSuite::getMinValueIndex(const std::vector<int>& VEC) const{
return minMaxManager->getMinValueIndex(VEC);
}
const Coordinates& MinMaxManagerTestSuite::getTheBestMove() const{
return minMaxManager->theBestMoveCoordinates;
}
| 36.127168 | 145 | 0.6384 | psobow |
cda09f848cfc0043102546f4ba1d6bca8968177f | 8,851 | cpp | C++ | HW6 Lights and Shading/HW6 Lights and Shading/main.cpp | Gongzq5/2019-sysu-CG | 3b594f3e1d1d7724a0b56f7546c50a31bb12fb45 | [
"Apache-2.0"
] | 2 | 2021-09-16T15:52:48.000Z | 2021-09-16T15:52:49.000Z | HW6 Lights and Shading/Submission/src/main.cpp | Gongzq5/2019-sysu-CG | 3b594f3e1d1d7724a0b56f7546c50a31bb12fb45 | [
"Apache-2.0"
] | null | null | null | HW6 Lights and Shading/Submission/src/main.cpp | Gongzq5/2019-sysu-CG | 3b594f3e1d1d7724a0b56f7546c50a31bb12fb45 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include "imgui.h"
#include "imgui_impl_glfw.h"
#include "imgui_impl_opengl3.h"
#include "HW4.h"
#include <iostream>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "Camera.h"
#include "shader.h"
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 800;
int main()
{
// glfw: initialize and configure
// ------------------------------
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X
#endif
// glfw window creation
// --------------------
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
ImGui::StyleColorsClassic();
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init("#version 330");
ImVec4 clear_color = ImVec4(1.0f, 1.0f, 1.0f, 1.00f);
glm::vec3 lightPos(1.2f, 1.0f, 2.0f);
// build and compile our shader program
// ------------------------------------
// vertex shader
Shader phongShader("hw6.vs", "hw6.fs");
Shader gouraudShader("hw6_gouraud.vs", "hw6_gouraud.fs");
std::vector<float> cubeVertices {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f
};
unsigned int cubeVAO, cubeVBO;
HW4::bind(cubeVertices, cubeVAO, cubeVBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
enum Homework_number {
B1, B2
};
int HW_choose = B1;
glm::mat4 model = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first
glm::mat4 view = glm::mat4(1.0f);
glm::mat4 projection = glm::ortho(1.0f, 1.0f, 1.0f, 1.0f, 0.1f, 100.0f);
float ambient = 0.1f, diffuse = 0.0f, specular = 0.5f;
float lightPosSlider[3] = { 1.2f, 1.0f, 2.0f };
// render loop
// -----------
while (!glfwWindowShouldClose(window))
{
// input
// -----
processInput(window);
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
{
ImGui::Begin("Choose radio to toggle different homework.");
ImGui::RadioButton("Basic 1 Projection", &HW_choose, B1);
ImGui::RadioButton("Basic 2 View Changing", &HW_choose, B2);
{
ImGui::Begin("Change your datas.");
ImGui::SliderFloat("ambient", &ambient, 0, 1);
ImGui::SliderFloat("specular", &specular, 0, 1);
ImGui::SliderFloat("diffuse", &diffuse, 0, 1);
ImGui::End();
}
{
ImGui::Begin("Change light pos.");
ImGui::SliderFloat("x", &lightPosSlider[0], -3.0f, 3.0f);
ImGui::SliderFloat("y", &lightPosSlider[1], -3.0f, 3.0f);
ImGui::SliderFloat("z", &lightPosSlider[2], -3.0f, 3.0f);
ImGui::End();
}
ImGui::End();
}
ImGui::Render();
int display_w, display_h;
glfwMakeContextCurrent(window);
glfwGetFramebufferSize(window, &display_w, &display_h);
glViewport(0, 0, display_w, display_h);
// render
// ------
// update shader uniform
glEnable(GL_DEPTH_TEST);
model = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first
view = glm::mat4(1.0f);
model = glm::rotate(model, glm::radians(50.0f) * (float)glfwGetTime(), glm::vec3(0.5f, 1.0f, 0.0f));
view = glm::translate(view, glm::vec3(0.0f, 0.0f, -5.0f));
projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.01f, 50.0f);
lightPos = glm::vec3(lightPosSlider[0], lightPosSlider[1], lightPosSlider[2]);
if (HW_choose == B1) {
phongShader.use();
phongShader.setVec3("objectColor", 1.0f, 0.5f, 0.31f);
phongShader.setVec3("lightColor", 1.0f, 1.0f, 1.0f);
phongShader.setVec3("lightPos", lightPos);
phongShader.setMat4("model", model);
phongShader.setMat4("view", view);
phongShader.setMat4("projection", projection);
phongShader.setFloat("ambientStrength", ambient);
phongShader.setFloat("diffuseStrength", diffuse);
phongShader.setFloat("specularStrength", specular);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindVertexArray(cubeVAO);
//glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);
glDrawArrays(GL_TRIANGLES, 0, 36);
} else {
gouraudShader.use();
gouraudShader.setVec3("objectColor", 0.5f, 0.5f, 0.7f);
gouraudShader.setVec3("lightColor", 1.0f, 1.0f, 1.0f);
gouraudShader.setVec3("lightPos", lightPos);
gouraudShader.setMat4("model", model);
gouraudShader.setMat4("view", view);
gouraudShader.setMat4("projection", projection);
gouraudShader.setFloat("ambientStrength", ambient);
gouraudShader.setFloat("diffuseStrength", diffuse);
gouraudShader.setFloat("specularStrength", specular);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glBindVertexArray(cubeVAO);
//glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glfwMakeContextCurrent(window);
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
}
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(1, &cubeVAO);
glDeleteBuffers(1, &cubeVBO);
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate();
return 0;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window) {
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
| 32.903346 | 108 | 0.610552 | Gongzq5 |
cda0c8a69080a82eb24627e04c7c8612cb759469 | 742 | cpp | C++ | user/drivers/filesystem/src/util/Path.cpp | tristanseifert/kush-os | 1ffd595aae8f3dc880e798eff72365b8b6c631f0 | [
"0BSD"
] | 4 | 2021-06-22T20:52:30.000Z | 2022-02-04T00:19:44.000Z | user/drivers/filesystem/src/util/Path.cpp | tristanseifert/kush-os | 1ffd595aae8f3dc880e798eff72365b8b6c631f0 | [
"0BSD"
] | null | null | null | user/drivers/filesystem/src/util/Path.cpp | tristanseifert/kush-os | 1ffd595aae8f3dc880e798eff72365b8b6c631f0 | [
"0BSD"
] | null | null | null | #include "Path.h"
#include <cstddef>
#include <string>
using namespace util;
/// Path separator character
constexpr static const char kPathSeparator{'/'};
/**
* Splits the path into its individual components. The path should be absolute (that is, have a
* leading slash) for this to work right. No escaping of slashes is allowed; they are always
* interpreted as a path separator.
*/
void util::SplitPath(const std::string &path,
std::vector<std::string> &outComponents) {
size_t start{0};
size_t end{0};
while ((start = path.find_first_not_of(kPathSeparator, end)) != std::string::npos) {
end = path.find(kPathSeparator, start);
outComponents.push_back(path.substr(start, end - start));
}
}
| 27.481481 | 95 | 0.691375 | tristanseifert |
cdb2b732fd19adef0f3459f0dea6dc376e933559 | 275 | cpp | C++ | tests/engine/physic/test_collision_info.cpp | LorenzoDiStefano/Frogger | 372782b3d9e7cb9c77b4b9524940aa169a1d2f3c | [
"MIT"
] | null | null | null | tests/engine/physic/test_collision_info.cpp | LorenzoDiStefano/Frogger | 372782b3d9e7cb9c77b4b9524940aa169a1d2f3c | [
"MIT"
] | null | null | null | tests/engine/physic/test_collision_info.cpp | LorenzoDiStefano/Frogger | 372782b3d9e7cb9c77b4b9524940aa169a1d2f3c | [
"MIT"
] | null | null | null | #include "../../pch.h"
TEST(collision_info_test, init)
{
collision_info_t collision_info;
collision_info_init(&collision_info);
EXPECT_TRUE(
collision_info.collider == NULL &&
collision_info.delta.x == 0 &&
collision_info.delta.y == 0
);
}
| 21.153846 | 42 | 0.654545 | LorenzoDiStefano |
cdb66ab7841543220a89ced48e72bdcc187db613 | 1,601 | ipp | C++ | implement/oglplus/enums/reset_notif_strategy_def.ipp | jnbrq/oglplus | 2e072e91292643e0871565ae5147584403846290 | [
"BSL-1.0"
] | null | null | null | implement/oglplus/enums/reset_notif_strategy_def.ipp | jnbrq/oglplus | 2e072e91292643e0871565ae5147584403846290 | [
"BSL-1.0"
] | null | null | null | implement/oglplus/enums/reset_notif_strategy_def.ipp | jnbrq/oglplus | 2e072e91292643e0871565ae5147584403846290 | [
"BSL-1.0"
] | null | null | null | // File implement/oglplus/enums/reset_notif_strategy_def.ipp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oglplus/reset_notif_strategy.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2017 Matus Chochlik.
// 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
//
#ifdef OGLPLUS_LIST_NEEDS_COMMA
# undef OGLPLUS_LIST_NEEDS_COMMA
#endif
#if defined GL_NO_RESET_NOTIFICATION
# ifdef OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined NoResetNotification
# pragma push_macro("NoResetNotification")
# undef NoResetNotification
OGLPLUS_ENUM_CLASS_VALUE(NoResetNotification, GL_NO_RESET_NOTIFICATION)
# pragma pop_macro("NoResetNotification")
# else
OGLPLUS_ENUM_CLASS_VALUE(NoResetNotification, GL_NO_RESET_NOTIFICATION)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_LOSE_CONTEXT_ON_RESET
# ifdef OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined LoseContextOnReset
# pragma push_macro("LoseContextOnReset")
# undef LoseContextOnReset
OGLPLUS_ENUM_CLASS_VALUE(LoseContextOnReset, GL_LOSE_CONTEXT_ON_RESET)
# pragma pop_macro("LoseContextOnReset")
# else
OGLPLUS_ENUM_CLASS_VALUE(LoseContextOnReset, GL_LOSE_CONTEXT_ON_RESET)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#ifdef OGLPLUS_LIST_NEEDS_COMMA
# undef OGLPLUS_LIST_NEEDS_COMMA
#endif
| 30.788462 | 74 | 0.818863 | jnbrq |
cdb70998f4c21f0676d05505c8c2fd29e84e2a28 | 6,605 | cpp | C++ | td/telegram/ThemeManager.cpp | d351d3r/td | ab4736df2897c452af18528840d343cb476045c2 | [
"BSL-1.0"
] | null | null | null | td/telegram/ThemeManager.cpp | d351d3r/td | ab4736df2897c452af18528840d343cb476045c2 | [
"BSL-1.0"
] | null | null | null | td/telegram/ThemeManager.cpp | d351d3r/td | ab4736df2897c452af18528840d343cb476045c2 | [
"BSL-1.0"
] | null | null | null | //
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "td/telegram/ThemeManager.h"
#include "td/telegram/BackgroundManager.h"
#include "td/telegram/Global.h"
#include "td/telegram/net/NetQueryCreator.h"
#include "td/telegram/Td.h"
#include "td/utils/algorithm.h"
#include "td/utils/buffer.h"
#include "td/utils/logging.h"
namespace td {
class GetChatThemesQuery final : public Td::ResultHandler {
Promise<telegram_api::object_ptr<telegram_api::account_ChatThemes>> promise_;
public:
explicit GetChatThemesQuery(Promise<telegram_api::object_ptr<telegram_api::account_ChatThemes>> &&promise)
: promise_(std::move(promise)) {
}
void send(int32 hash) {
send_query(G()->net_query_creator().create(telegram_api::account_getChatThemes(hash)));
}
void on_result(uint64 id, BufferSlice packet) final {
auto result_ptr = fetch_result<telegram_api::account_getChatThemes>(packet);
if (result_ptr.is_error()) {
return on_error(id, result_ptr.move_as_error());
}
promise_.set_value(result_ptr.move_as_ok());
}
void on_error(uint64 id, Status status) final {
promise_.set_error(std::move(status));
}
};
ThemeManager::ThemeManager(Td *td, ActorShared<> parent) : td_(td), parent_(std::move(parent)) {
}
void ThemeManager::tear_down() {
parent_.reset();
}
void ThemeManager::get_chat_themes(Promise<td_api::object_ptr<td_api::chatThemes>> &&promise) {
pending_get_chat_themes_queries_.push_back(std::move(promise));
if (pending_get_chat_themes_queries_.size() == 1) {
auto request_promise = PromiseCreator::lambda(
[actor_id = actor_id(this)](Result<telegram_api::object_ptr<telegram_api::account_ChatThemes>> result) {
send_closure(actor_id, &ThemeManager::on_get_chat_themes, std::move(result));
});
td_->create_handler<GetChatThemesQuery>(std::move(request_promise))->send(chat_themes_.hash);
}
}
td_api::object_ptr<td_api::themeSettings> ThemeManager::get_theme_settings_object(const ThemeSettings &settings) const {
auto fill = [colors = settings.message_colors]() mutable -> td_api::object_ptr<td_api::BackgroundFill> {
if (colors.size() >= 3) {
return td_api::make_object<td_api::backgroundFillFreeformGradient>(std::move(colors));
}
CHECK(!colors.empty());
if (colors.size() == 1 || colors[0] == colors[1]) {
return td_api::make_object<td_api::backgroundFillSolid>(colors[0]);
}
return td_api::make_object<td_api::backgroundFillGradient>(colors[1], colors[0], 0);
}();
// ignore settings.base_theme for now
return td_api::make_object<td_api::themeSettings>(
settings.accent_color,
td_->background_manager_->get_background_object(settings.background_id, false, &settings.background_type),
std::move(fill), settings.animate_message_colors);
}
td_api::object_ptr<td_api::chatTheme> ThemeManager::get_chat_theme_object(const ChatTheme &theme) const {
return td_api::make_object<td_api::chatTheme>(theme.emoji, get_theme_settings_object(theme.light_theme),
get_theme_settings_object(theme.dark_theme));
}
td_api::object_ptr<td_api::chatThemes> ThemeManager::get_chat_themes_object() const {
return td_api::make_object<td_api::chatThemes>(
transform(chat_themes_.themes, [this](const ChatTheme &theme) { return get_chat_theme_object(theme); }));
}
void ThemeManager::on_get_chat_themes(Result<telegram_api::object_ptr<telegram_api::account_ChatThemes>> result) {
auto promises = std::move(pending_get_chat_themes_queries_);
CHECK(!promises.empty());
reset_to_empty(pending_get_chat_themes_queries_);
if (result.is_error()) {
// do not clear chat_themes_
auto error = result.move_as_error();
for (auto &promise : promises) {
promise.set_error(error.clone());
}
return;
}
auto chat_themes_ptr = result.move_as_ok();
LOG(DEBUG) << "Receive " << to_string(chat_themes_ptr);
if (chat_themes_ptr->get_id() == telegram_api::account_chatThemesNotModified::ID) {
for (auto &promise : promises) {
promise.set_value(get_chat_themes_object());
}
return;
}
auto chat_themes = telegram_api::move_object_as<telegram_api::account_chatThemes>(chat_themes_ptr);
LOG(INFO) << "Receive " << to_string(chat_themes);
chat_themes_.hash = chat_themes->hash_;
chat_themes_.themes.clear();
for (auto &chat_theme : chat_themes->themes_) {
if (chat_theme->emoticon_.empty()) {
LOG(ERROR) << "Receive " << to_string(chat_theme);
continue;
}
ChatTheme theme;
theme.emoji = std::move(chat_theme->emoticon_);
theme.light_theme = get_chat_theme_settings(std::move(chat_theme->theme_->settings_));
theme.dark_theme = get_chat_theme_settings(std::move(chat_theme->dark_theme_->settings_));
chat_themes_.themes.push_back(std::move(theme));
}
for (auto &promise : promises) {
promise.set_value(get_chat_themes_object());
}
}
ThemeManager::BaseTheme ThemeManager::get_base_theme(
const telegram_api::object_ptr<telegram_api::BaseTheme> &base_theme) {
CHECK(base_theme != nullptr);
switch (base_theme->get_id()) {
case telegram_api::baseThemeClassic::ID:
return BaseTheme::Classic;
case telegram_api::baseThemeDay::ID:
return BaseTheme::Day;
case telegram_api::baseThemeNight::ID:
return BaseTheme::Night;
case telegram_api::baseThemeTinted::ID:
return BaseTheme::Tinted;
case telegram_api::baseThemeArctic::ID:
return BaseTheme::Arctic;
default:
UNREACHABLE();
return BaseTheme::Classic;
}
}
ThemeManager::ThemeSettings ThemeManager::get_chat_theme_settings(
telegram_api::object_ptr<telegram_api::themeSettings> settings) {
ThemeSettings result;
if (settings != nullptr && !settings->message_colors_.empty() && settings->message_colors_.size() <= 4) {
auto background =
td_->background_manager_->on_get_background(BackgroundId(), string(), std::move(settings->wallpaper_), false);
result.accent_color = settings->accent_color_;
result.background_id = background.first;
result.background_type = std::move(background.second);
result.base_theme = get_base_theme(settings->base_theme_);
result.message_colors = std::move(settings->message_colors_);
result.animate_message_colors = settings->message_colors_animated_;
}
return result;
}
} // namespace td
| 37.106742 | 120 | 0.725208 | d351d3r |
cdb8058891e2023870a48616522c85725cdd7065 | 11,808 | cpp | C++ | Neko98/AlwaysOnTopPet.cpp | leiqunni/Neko98 | 4e1a1d0888c4edb620c806a532657da30c68894f | [
"BSD-Source-Code"
] | 16 | 2019-09-02T19:47:49.000Z | 2022-03-03T01:40:13.000Z | Neko98/AlwaysOnTopPet.cpp | leiqunni/Neko98 | 4e1a1d0888c4edb620c806a532657da30c68894f | [
"BSD-Source-Code"
] | 2 | 2018-04-07T17:44:23.000Z | 2021-09-11T20:25:11.000Z | Neko98/AlwaysOnTopPet.cpp | leiqunni/Neko98 | 4e1a1d0888c4edb620c806a532657da30c68894f | [
"BSD-Source-Code"
] | 5 | 2019-09-04T18:10:16.000Z | 2021-07-10T19:31:51.000Z | // AlwaysOnTopPet.cpp: implementation of the CAlwaysOnTopPet class.
//
//////////////////////////////////////////////////////////////////////
#include "AlwaysOnTopPet.h"
//class name constant
static const char* g_szOnTopClassName = "NekoOnTop_Wnd";
//forward declaration
LRESULT CALLBACK WndProc_OnTop(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
//static member
BOOL CAlwaysOnTopPet::m_fRegisteredClass = FALSE;
//external global variable
extern HINSTANCE g_hInstance;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CAlwaysOnTopPet::CAlwaysOnTopPet() : CPet()
{
//clear regions
m_hRgns = NULL;
//initialise members
m_fBeingDragged = FALSE;
m_hWndOnTop = NULL;
//register class
if (m_fRegisteredClass == FALSE) {
WNDCLASS wc;
wc.style = CS_OWNDC | CS_DBLCLKS | CS_SAVEBITS;
wc.lpfnWndProc = (WNDPROC)WndProc_OnTop;
wc.cbClsExtra = 0;
wc.cbWndExtra = sizeof(LPVOID);
wc.hInstance = g_hInstance;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW));
wc.hbrBackground = NULL;
wc.lpszMenuName = NULL;
wc.lpszClassName = g_szOnTopClassName;
m_fRegisteredClass = RegisterClass(&wc);
}
//set bounding rectangle
SetRect(&m_rcBounds, 0, 0, GetSystemMetrics(SM_CXVIRTUALSCREEN) - 1, GetSystemMetrics(SM_CYVIRTUALSCREEN) - 1);
//move this pet off-screen to start with
m_ptPosition.x = m_rcBounds.right;
m_ptPosition.y = m_rcBounds.bottom;
}
CAlwaysOnTopPet::~CAlwaysOnTopPet()
{
DestroyWindow(m_hWndOnTop);
}
//////////////////////////////////////////////////////////////////////
// Member Functions
//////////////////////////////////////////////////////////////////////
void CAlwaysOnTopPet::Draw(int nImage)
{
//only draw if it's different && not being dragged
if (nImage != m_nLastIcon && m_fBeingDragged == FALSE) {
//clip the window to the shape of the icon
HRGN hRgnCopy = CreateRectRgn(0, 0, m_sizeImage.cx, m_sizeImage.cy);
CombineRgn(hRgnCopy, m_hRgns[nImage], NULL, RGN_COPY);
SetWindowRgn(m_hWndOnTop, hRgnCopy, TRUE);
//draw the current frame on the window
HDC hDC = GetDC(m_hWndOnTop);
DrawIconEx(hDC, 0, 0, m_hIcons[nImage], m_sizeImage.cx, m_sizeImage.cy, 0, NULL, DI_NORMAL);
ReleaseDC(m_hWndOnTop, hDC);
}
}
void CAlwaysOnTopPet::Erase()
{
//do nothing
}
void CAlwaysOnTopPet::SetImages(HICON * hIconTable, int nIcons)
{
//remove current region handles
DestroyRegions();
//call base class
CPet::SetImages(hIconTable, nIcons);
//prepare region handles
BuildRegions();
//create the window if it doesn't exist already
if (m_hWndOnTop == NULL) {
m_hWndOnTop = CreateWindowEx(WS_EX_TOPMOST | WS_EX_TOOLWINDOW, g_szOnTopClassName, NULL, WS_POPUP, m_ptPosition.x, m_ptPosition.y, m_sizeImage.cx, m_sizeImage.cy, NULL, NULL, g_hInstance, NULL);
if (m_hWndOnTop) {
SetWindowLong(m_hWndOnTop, 0, (LONG)this);
ShowWindow(m_hWndOnTop, SW_SHOWNA);
UpdateWindow(m_hWndOnTop);
}
}
//FIXME: don't change it in the whole class, just this window!!!
//change it's default icon
//SetClassLong( m_hWndOnTop, GCL_HICON, m_hIcons[0] );
}
void CAlwaysOnTopPet::DestroyImages()
{
//call base class
CPet::DestroyImages();
//delete regions
DestroyRegions();
}
void CAlwaysOnTopPet::DrawOnTarget(int x, int y, HICON hIcon)
{
//grab the device context of the display
HDC hDC = GetDC(NULL);
//draw the icon on it
DrawIconEx(hDC, x, y, hIcon, 0, 0, 0, NULL, DI_NORMAL);
//release the device context
ReleaseDC(NULL, hDC);
}
//////////////////////////////////////////////////////////////////////
// On Top Window Procedure
//////////////////////////////////////////////////////////////////////
LRESULT CALLBACK WndProc_OnTop(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg) {
case WM_PAINT:
{
//draw the most recent icon if the window is being dragged
CAlwaysOnTopPet* pPet = (CAlwaysOnTopPet*)GetWindowLong(hWnd, 0);
if (pPet->m_fBeingDragged) {
//draw the current icon onto the window (we can't call draw because it checks for icon index and changes the window's region
HDC hDC = GetDC(hWnd);
DrawIconEx(hDC, 0, 0, pPet->m_hIcons[pPet->m_nLastIcon], pPet->GetSize().cx, pPet->GetSize().cy, 0, NULL, DI_NORMAL);
ReleaseDC(hWnd, hDC);
}
ValidateRect(hWnd, NULL);
break;
}
case WM_SYSCOMMAND:
//if the user alt+F4s us or (somehow) minimises or maximises us, ignore it
if (LOWORD(wParam) != SC_CLOSE && LOWORD(wParam) != SC_MINIMIZE && LOWORD(wParam) != SC_MAXIMIZE)
return DefWindowProc(hWnd, uMsg, wParam, lParam);
break;
case WM_ERASEBKGND:
return TRUE; //don't erase the background
//pass mouse messages onto the class
case WM_LBUTTONDOWN: ((CAlwaysOnTopPet*)GetWindowLong(hWnd, 0))->OnLButtonDown(); break;
case WM_LBUTTONUP: ((CAlwaysOnTopPet*)GetWindowLong(hWnd, 0))->OnLButtonUp(); break;
case WM_LBUTTONDBLCLK: ((CAlwaysOnTopPet*)GetWindowLong(hWnd, 0))->OnLButtonDblClk(); break;
case WM_MBUTTONDOWN: ((CAlwaysOnTopPet*)GetWindowLong(hWnd, 0))->OnMButtonDown(); break;
case WM_MBUTTONUP: ((CAlwaysOnTopPet*)GetWindowLong(hWnd, 0))->OnMButtonUp(); break;
case WM_MBUTTONDBLCLK: ((CAlwaysOnTopPet*)GetWindowLong(hWnd, 0))->OnMButtonDblClk(); break;
case WM_RBUTTONDOWN: ((CAlwaysOnTopPet*)GetWindowLong(hWnd, 0))->OnRButtonDown(); break;
case WM_RBUTTONUP: ((CAlwaysOnTopPet*)GetWindowLong(hWnd, 0))->OnRButtonUp(); break;
case WM_RBUTTONDBLCLK: ((CAlwaysOnTopPet*)GetWindowLong(hWnd, 0))->OnRButtonDblClk(); break;
//window is being dragged
case WM_ENTERSIZEMOVE:
{
CAlwaysOnTopPet* pPet = (CAlwaysOnTopPet*)GetWindowLong(hWnd, 0);
pPet->m_fBeingDragged = TRUE;
break;
}
//window is being dropped
case WM_EXITSIZEMOVE:
{
CAlwaysOnTopPet* pPet = (CAlwaysOnTopPet*)GetWindowLong(hWnd, 0);
pPet->m_fBeingDragged = FALSE;
RECT rc;
GetWindowRect(hWnd, &rc);
pPet->MoveTo(rc.left, rc.top);
break;
}
default:
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return 0;
}
void CAlwaysOnTopPet::OnLButtonDown()
{
//default left button handler - begin window dragging
SendMessage(m_hWndOnTop, WM_SYSCOMMAND, SC_MOVE + 2, 0);
}
void CAlwaysOnTopPet::DestroyRegions()
{
if (m_hRgns) {
//delete all regions and free the array
for (int i = 0; i < m_nIcons; i++) if (m_hRgns[i]) DeleteObject(m_hRgns[i]);
delete[] m_hRgns;
m_hRgns = NULL;
}
}
void CAlwaysOnTopPet::MoveTo(int nNewX, int nNewY)
{
if (m_fBeingDragged == FALSE) {
//store current position
m_ptOldPosition.x = m_ptPosition.x;
m_ptOldPosition.y = m_ptPosition.y;
//change current position
m_ptPosition.x = nNewX;
m_ptPosition.y = nNewY;
//move the window if it's not being moved by something else
MoveWindow(m_hWndOnTop, nNewX, nNewY, m_sizeImage.cx, m_sizeImage.cy, TRUE);
}
}
void CAlwaysOnTopPet::SetImageAndMoveTo(int nImage, int nNewX, int nNewY)
{
if (m_fBeingDragged == FALSE) {
//move
MoveTo(nNewX, nNewY);
//change image
Draw(nImage);
m_nLastIcon = nImage;
}
}
void CAlwaysOnTopPet::SetImage(int nImage)
{
if (m_fBeingDragged == FALSE) CPet::SetImage(nImage);
}
//This function was based on the BitmapToRegion function found in www.codeguru.com's "bitmaps and palettes" section
// Author : Jean-Edouard Lachand-Robert (http://www.geocities.com/Paris/LeftBank/1160/resume.htm), June 1998.
void CAlwaysOnTopPet::BuildRegions()
{
//create a memory DC inside which we will scan the bitmap content
HDC hMemDC = CreateCompatibleDC(NULL);
//create a 32 bits depth bitmap and select it into the memory DC
BITMAPINFOHEADER bi = { sizeof(BITMAPINFOHEADER), int(m_sizeImage.cx / m_fScale), int(m_sizeImage.cy / m_fScale), 1, 16, BI_RGB, 0, 0, 0, 0, 0 };
VOID* pBitsDib;
HBITMAP hBmDib = CreateDIBSection(hMemDC, (BITMAPINFO*)&bi, DIB_RGB_COLORS, &pBitsDib, NULL, 0);
HBITMAP hOldMemBmp = (HBITMAP)SelectObject(hMemDC, hBmDib);
//create a DC just to copy the bitmap into the memory DC
HDC hDC = CreateCompatibleDC(hMemDC);
//get how many bytes per row we have for the bitmap bits (rounded up to 32 bits)
BITMAP bmDib;
GetObject(hBmDib, sizeof(bmDib), &bmDib);
while (bmDib.bmWidthBytes % 4) bmDib.bmWidthBytes++;
//calculate scaling matrix
XFORM xForm = { m_fScale, 0.0, 0.0, m_fScale, 0.0, 0.0 };
//allocate the region array
m_hRgns = new HRGN[m_nIcons];
//build all regions
for (int i = 0; i < m_nIcons; i++) {
HRGN hRgn = NULL;
//extract icon mask image
ICONINFO ii;
GetIconInfo(m_hIcons[i], &ii);
DeleteObject(ii.hbmColor);
//get bitmap size
BITMAP bm;
GetObject(ii.hbmMask, sizeof(bm), &bm);
//copy the bitmap into the memory DC
HBITMAP hOldBmp = (HBITMAP)SelectObject(hDC, ii.hbmMask);
BitBlt(hMemDC, 0, 0, bm.bmWidth, bm.bmHeight, hDC, 0, 0, SRCCOPY);
//For better performances, we will use the ExtCreateRegion() function to create the
//region. This function take a RGNDATA structure on entry. We will add rectangles by
//amount of ALLOC_UNIT number in this structure.
#define ALLOC_UNIT 100
DWORD dwMaxRects = ALLOC_UNIT;
HANDLE hData = GlobalAlloc(GMEM_MOVEABLE, sizeof(RGNDATAHEADER) + (sizeof(RECT) * dwMaxRects));
RGNDATA* pData = (RGNDATA *)GlobalLock(hData);
pData->rdh.dwSize = sizeof(RGNDATAHEADER);
pData->rdh.iType = RDH_RECTANGLES;
pData->rdh.nCount = pData->rdh.nRgnSize = 0;
SetRect(&pData->rdh.rcBound, MAXLONG, MAXLONG, 0, 0);
//scan each bitmap row from bottom to top (the bitmap is inverted vertically)
BYTE* pDib = (BYTE*)bmDib.bmBits + (bmDib.bmHeight - 1) * bmDib.bmWidthBytes;
for (int y = 0; y < bm.bmHeight; y++) {
//scan each bitmap pixel from left to right
for (int x = 0; x < bm.bmWidth; x++) {
//search for a continuous range of "non transparent pixels"
int x0 = x;
WORD* p = (WORD*)pDib + x;
while (x < bm.bmWidth) {
if (*p != 0)
//This pixel is "transparent"
break;
p++;
x++;
}
if (x > x0) {
//Add the pixels (x0, y) to (x, y+1) as a new rectangle in the region
if (pData->rdh.nCount >= dwMaxRects) {
GlobalUnlock(hData);
dwMaxRects += ALLOC_UNIT;
hData = GlobalReAlloc(hData, sizeof(RGNDATAHEADER) + (sizeof(RECT) * dwMaxRects), GMEM_MOVEABLE);
pData = (RGNDATA*)GlobalLock(hData);
}
RECT* pr = (RECT*)&pData->Buffer;
SetRect(&pr[pData->rdh.nCount], x0, y, x, y + 1);
if (x0 < pData->rdh.rcBound.left) pData->rdh.rcBound.left = x0;
if (y < pData->rdh.rcBound.top) pData->rdh.rcBound.top = y;
if (x > pData->rdh.rcBound.right) pData->rdh.rcBound.right = x;
if (y + 1 > pData->rdh.rcBound.bottom) pData->rdh.rcBound.bottom = y + 1;
pData->rdh.nCount++;
//On Windows98, ExtCreateRegion() may fail if the number of rectangles is too
//large (ie: > 4000). Therefore, we have to create the region by multiple steps.
if (pData->rdh.nCount == 2000) {
HRGN h = ExtCreateRegion(&xForm, sizeof(RGNDATAHEADER) + (sizeof(RECT) * dwMaxRects), pData);
if (hRgn) {
CombineRgn(hRgn, hRgn, h, RGN_OR);
DeleteObject(h);
} else
hRgn = h;
pData->rdh.nCount = 0;
SetRect(&pData->rdh.rcBound, MAXLONG, MAXLONG, 0, 0);
}
}
}
//go to next row (remember, the bitmap is inverted vertically)
pDib -= bmDib.bmWidthBytes;
}
//create or extend the region with the remaining rectangles
HRGN h = ExtCreateRegion(&xForm, sizeof(RGNDATAHEADER) + (sizeof(RECT) * dwMaxRects), pData);
if (hRgn) {
CombineRgn(hRgn, hRgn, h, RGN_OR);
DeleteObject(h);
} else
hRgn = h;
//clean up
DeleteObject(SelectObject(hDC, hOldBmp));
GlobalFree(hData);
//store the region
m_hRgns[i] = hRgn;
}
//clean up
DeleteDC(hDC);
DeleteObject(SelectObject(hMemDC, hOldMemBmp));
DeleteDC(hMemDC);
}
| 30.122449 | 196 | 0.672849 | leiqunni |
cdb87c36b130e099fed5c7f5863d8449ae70c0bc | 3,781 | cpp | C++ | users-archive/attachments/20130529/afd792d4/attachment-0003.cpp | zayenz/gecode.github.io | e759c2c1940d9a018373bcc6c316d9cb04efa5a0 | [
"MIT-feh"
] | 1 | 2020-10-28T06:11:30.000Z | 2020-10-28T06:11:30.000Z | users-archive/attachments/20130529/afd792d4/attachment-0003.cpp | zayenz/gecode.github.io | e759c2c1940d9a018373bcc6c316d9cb04efa5a0 | [
"MIT-feh"
] | 1 | 2019-05-05T11:10:31.000Z | 2019-05-05T11:10:31.000Z | users-archive/attachments/20130529/afd792d4/attachment-0003.cpp | zayenz/gecode.github.io | e759c2c1940d9a018373bcc6c316d9cb04efa5a0 | [
"MIT-feh"
] | 4 | 2019-05-03T18:43:19.000Z | 2020-12-17T04:06:59.000Z | // Square Packing.cpp : Defines the entry point for the console application.
//
#include <gecode/int.hh>
#include <gecode/search.hh>
#include <gecode/gist.hh>
#include <gecode/driver.hh>
#include <gecode/minimodel.hh>
#include <type_traits>
#include <array>
#include <cmath>
void nooverlap(Gecode::Home home,
const Gecode::IntVarArgs& x, const Gecode::IntArgs& width,
const Gecode::IntVarArgs& y, const Gecode::IntArgs& height);
namespace Impl
{
// Calculate upper bound for s and coordinates (x, y)
template<size_t N>
struct CalcUpperSizeBound
{
static const size_t val = N + CalcUpperSizeBound<N - 1>::val;
};
template<>
struct CalcUpperSizeBound<0>
{
static const size_t val = 0;
};
}
template<int N>
class XSquarePacking: public Gecode::MinimizeScript //: public XGecodeBase<XSquarePacking<N>, Gecode::MinimizeScript>
{
private:
static_assert(N > 0, "N must be greater than 0.");
typedef typename std::remove_const<decltype(N)>::type It_t;
// Variables
Gecode::IntVarArray m_x, m_y;
Gecode::IntVar m_s;
// Return the size of a squares, where VarIndex is the index of the square
It_t SizeOfSquare(size_t VarIndex) const
{
typedef It_t value_type;
static std::array<value_type, N> SizeTbl;
static bool TblInitialized = false;
if (!TblInitialized)
{
for (size_t ArrayIdx = 0, Size = N; ArrayIdx < SizeTbl.size(); ArrayIdx++, Size--)
SizeTbl.at(ArrayIdx) = static_cast<value_type>(Size);
TblInitialized = true;
}
return SizeTbl.at(VarIndex);
}
public:
// Worst case scenario: all squares are packed vertically or horizontally.
// In that case, we need 1 + 2 + ... + N units of width or length to fit them
// all.
// The minimal size of s must be at least N because otherwise the square of
// length NxN cannot fit. Likewise, it must be N + N-1, otherwise we cannot
// fit the NxN square AND the N-1 square because there must be at least
// N + N-1 units of length available on either the width or height.
XSquarePacking(const Gecode::Options&):
m_x(*this, N, 0, Impl::CalcUpperSizeBound<N>::val),
m_y(*this, N, 0, Impl::CalcUpperSizeBound<N>::val),
m_s(*this, (int)std::ceil(std::sqrt((N*(N + 1)*(2*N + 1))/6)), Impl::CalcUpperSizeBound<N>::val)
{
auto PropagationStrength = Gecode::ICL_VAL;
// Make sure no squares overlap (no overlap propagator)
// <--------------- BLOCK A START
auto SizeTbl = Gecode::IntArgs::create(N, N, -1);
::nooverlap(*this, m_x, SizeTbl, m_y, SizeTbl);
//Gecode::nooverlap(*this, m_x.c, SizeTbl, m_y.c, SizeTbl, Gecode::ICL_BND);
// ---------------> BLOCK A END
// Make sure that all squares stay inside s.
for (It_t i = 0; i < N; i++)
{
Gecode::rel(*this, m_x[i] + SizeOfSquare(i) <= m_s, PropagationStrength);
Gecode::rel(*this, m_y[i] + SizeOfSquare(i) <= m_s, PropagationStrength);
}
// Branch on s, then x0, y1, x1, y1 ... xN-1, yN-1
Gecode::branch(*this, m_s, Gecode::INT_VAL_MIN());
for (It_t i = 0; i < m_x.size(); i++)
{
Gecode::branch(*this, m_y[i], Gecode::INT_VAL_SPLIT_MIN());
Gecode::branch(*this, m_x[i], Gecode::INT_VAL_SPLIT_MIN());
}
}
XSquarePacking(XSquarePacking<N>& that, bool share): Gecode::MinimizeScript(share, that)
{
m_x.update(*this, share, that.m_x);
m_y.update(*this, share, that.m_y);
m_s.update(*this, share, that.m_s);
}
virtual Gecode::Space* copy(bool share)
{
return new XSquarePacking<N>(*this, share);
}
virtual Gecode::IntVar cost() const { return m_s; }
};
int main()
{
typedef XSquarePacking<8> Model_t;
Gecode::Options opt("Square Packing");
opt.mode(Gecode::SM_GIST);
Gecode::MinimizeScript::run<Model_t, Gecode::BAB>(opt);
return 0;
}
| 31.247934 | 118 | 0.658556 | zayenz |
cdbf2aff7a8887464b0de7911e195e3397ee7f7e | 1,188 | cpp | C++ | test/Splines/Tangent.cpp | kurocha/splines | 00ba452d378f71b26bddbfe787f68dea6e6160ad | [
"MIT",
"Unlicense"
] | null | null | null | test/Splines/Tangent.cpp | kurocha/splines | 00ba452d378f71b26bddbfe787f68dea6e6160ad | [
"MIT",
"Unlicense"
] | null | null | null | test/Splines/Tangent.cpp | kurocha/splines | 00ba452d378f71b26bddbfe787f68dea6e6160ad | [
"MIT",
"Unlicense"
] | null | null | null | //
// Tangent.cpp
// This file is part of the "Splines" project and released under the MIT License.
//
// Created by Samuel Williams on 9/6/2020.
// Copyright, 2020, by Samuel Williams. All rights reserved.
//
#include <UnitTest/UnitTest.hpp>
#include <Splines/Polyline.hpp>
#include <Splines/Spline.hpp>
#include <Splines/Tangent.hpp>
namespace Splines
{
using namespace UnitTest::Expectations;
UnitTest::Suite TangentTestSuite {
"Splines::Tangent",
{"it can calculate tangent",
[](UnitTest::Examiner & examiner) {
using Point = Polyline<2>::Point;
Polyline<2> polyline({{0.0, 0.0}, {1.0, 0.0}});
Spline spline(polyline);
Tangent tangent(spline);
examiner.expect(spline[0.5]).to(be == Point{0.5, 0.0});
examiner.expect(tangent[0.5]).to(be == Point{1.0, 0.0});
}
},
{"it can compute nominal times",
[](UnitTest::Examiner & examiner) {
using Point = Polyline<2>::Point;
Polyline<2> polyline({{0.0, 0.0}, {1.0, 0.0}});
Spline spline(polyline);
Tangent tangent(spline);
auto times = tangent.times_for_segments();
examiner.expect(times).to(be_sequence(0.0, 0.5, 1.0));
}
},
};
}
| 23.76 | 82 | 0.63468 | kurocha |
02cc53c73971a07c61e6d069df192913b347eefe | 3,229 | cpp | C++ | src/zisa/model/all_variables.cpp | 1uc/ZisaFVM | 75fcedb3bece66499e011228a39d8a364b50fd74 | [
"MIT"
] | null | null | null | src/zisa/model/all_variables.cpp | 1uc/ZisaFVM | 75fcedb3bece66499e011228a39d8a364b50fd74 | [
"MIT"
] | null | null | null | src/zisa/model/all_variables.cpp | 1uc/ZisaFVM | 75fcedb3bece66499e011228a39d8a364b50fd74 | [
"MIT"
] | 1 | 2021-08-24T11:52:51.000Z | 2021-08-24T11:52:51.000Z | // SPDX-License-Identifier: MIT
// Copyright (c) 2021 ETH Zurich, Luc Grosheintz-Laval
#include <zisa/model/all_variables.hpp>
namespace zisa {
bool operator==(const AllVariablesDimensions &a,
const AllVariablesDimensions &b) {
return (a.n_cells == b.n_cells) && (a.n_cvars == b.n_cvars)
&& (a.n_avars == b.n_avars);
}
std::ostream &operator<<(std::ostream &os, const AllVariablesDimensions &dims) {
os << "{ " << dims.n_cells << ", " << dims.n_cvars << ", " << dims.n_avars
<< "}";
return os;
}
AllVariables::AllVariables(GridVariables cvars, GridVariables avars)
: cvars(std::move(cvars)), avars(std::move(avars)) {}
AllVariables::AllVariables(const AllVariablesDimensions &dims) {
allocate(dims);
}
void AllVariables::allocate(const AllVariablesDimensions &dims) {
auto n_cells = dims.n_cells;
cvars = GridVariables(shape_t<2>{n_cells, dims.n_cvars});
avars = GridVariables(shape_t<2>{n_cells, dims.n_avars});
}
double AllVariables::operator[](int_t i) const {
auto n_conserved_elements = cvars.size();
if (i < n_conserved_elements) {
return cvars[i];
} else {
return avars[i - n_conserved_elements];
}
}
double &AllVariables::operator[](int_t i) {
auto n_conserved_elements = cvars.size();
if (i < n_conserved_elements) {
return cvars[i];
} else {
return avars[i - n_conserved_elements];
}
}
int_t AllVariables::size() const { return cvars.size() + avars.size(); }
AllVariablesDimensions AllVariables::dims() const {
AllVariablesDimensions dims{};
dims.n_cells = cvars.shape(0);
dims.n_cvars = cvars.shape(1);
dims.n_avars = avars.shape(1);
return dims;
}
std::vector<std::string> numbered_labels(const std::string &pattern,
int_t n_labels) {
std::vector<std::string> labels;
for (int_t i = 0; i < n_labels; ++i) {
labels.push_back(string_format(pattern.c_str(), i));
}
return labels;
}
void save(HierarchicalWriter &writer,
const AllVariables &all_variables,
const std::vector<std::string> &labels) {
const auto &cvars = all_variables.cvars;
const auto &avars = all_variables.avars;
// conserved variables
save(writer, cvars, labels);
// advected variables
int_t n_avars = avars.shape(1);
writer.write_scalar(n_avars, "n_avars");
save(writer, avars, numbered_labels("mq%d", n_avars));
}
[[nodiscard]] AllVariables
AllVariables::load(HierarchicalReader &reader,
const std::vector<std::string> &labels) {
auto all_vars = AllVariables{};
all_vars.cvars = GridVariables::load(reader, labels);
auto n_avars = reader.read_scalar<int_t>("n_avars");
auto avar_labels = numbered_labels("mq%d", n_avars);
all_vars.avars = GridVariables::load(reader, avar_labels);
return all_vars;
}
void AllVariables::load(HierarchicalReader &reader,
AllVariables &all_vars,
const std::vector<std::string> &labels) {
GridVariables::load(reader, all_vars.cvars, labels);
auto n_avars = reader.read_scalar<int_t>("n_avars");
auto avar_labels = numbered_labels("mq%d", n_avars);
GridVariables::load(reader, all_vars.avars, avar_labels);
}
} // namespace zisa
| 27.836207 | 80 | 0.673893 | 1uc |
02d13bc0cd9f702c6482eab0542a1207f80ca09e | 7,357 | cpp | C++ | serial/dataanalysis.cpp | dreamtravel/Sensor_PC | 7fa7b4acd217fd97ada5c19a7127d0332b1e6256 | [
"MIT"
] | null | null | null | serial/dataanalysis.cpp | dreamtravel/Sensor_PC | 7fa7b4acd217fd97ada5c19a7127d0332b1e6256 | [
"MIT"
] | null | null | null | serial/dataanalysis.cpp | dreamtravel/Sensor_PC | 7fa7b4acd217fd97ada5c19a7127d0332b1e6256 | [
"MIT"
] | null | null | null | /*****************************************************************************
**
**Copyright (C) 2014 UP-TECH Corporation and/or its subsidiary(-ies).
**All rights reserved.
**Contact: UP-TECH Corporation (anld@up-tech.com)
**
**This file is part of the Sensor Data Analysis Thread.
**
*****************************************************************************/
#include "dataanalysis.h"
#include "cmd/sensorprotocol.h"
#include "serial/data.h"
#include <stddef.h>
#include <QMessageBox>
DataAnalysis::DataAnalysis()
{
runFlag=1;
state = SOP_STATE;
allSensorInfoCMD(data);
myCom = new Win_QextSerialPort("COM1", QextSerialBase::Polling);
}
DataAnalysis::~DataAnalysis()
{
myCom->close();
}
int DataAnalysis::COMOpen()
{
if(myCom->open(QIODevice::ReadWrite))
{
myCom->setBaudRate(BAUD115200);
myCom->setFlowControl(FLOW_OFF);
myCom->setTimeout(10);
myCom->setDataBits(DATA_8);
myCom->setStopBits(STOP_1);
myCom->setParity(PAR_NONE);
return 1;
}
else
{
QMessageBox::information(NULL,tr("提示:"),tr("串口被占用"));
return 0;
}
}
void DataAnalysis::run()
{
while(runFlag){
myCom->write((const char*)data, 4);
dataProcessing();
sleep(2);
}
}
void DataAnalysis::stop()
{
runFlag=0;
myCom->close();
delete myCom;
}
int DataAnalysis::setPort(QString port,BaudRateType baud)
{
myCom = new Win_QextSerialPort(port, QextSerialBase::Polling);
myCom->flush();
if(myCom->open(QIODevice::ReadWrite))
{
myCom->setBaudRate(baud);
myCom->setFlowControl(FLOW_OFF);
myCom->setTimeout(10);
myCom->setDataBits(DATA_8);
myCom->setStopBits(STOP_1);
myCom->setParity(PAR_NONE);
runFlag=1;
this->start();
return 1;
}
else
{
QMessageBox::information(NULL,tr("提示:"),tr("打开失败"));
runFlag=0;
return 0;
}
}
/*
*函数名:dataProcessing
*函数功能描述:按照通信协议对串口数据进行解析并发送
*函数参数:无
*函数返回值:无
*/
void DataAnalysis::dataProcessing()
{
uchar ch;
int available;
extern Sensor_Info_All sensor_info_all;
while(myCom->bytesAvailable() > 0){ // 判断串口是否有可度数据
myCom->read((char*)&ch, 1);
switch(state){
/*读取帧起始域*/
case SOP_STATE:
if(ch == APPPRO_SOP_INFO)
state = LEN_STATE;
break;
/*读取帧长度域,帧长度域为 TYPE+DATA */
case LEN_STATE:
len = ch - 1; // 去除1字节的TYPE位
temp_len = 0; // 初始化已读取字节标志
state = TYPE_STATE;
break;
/*读取传感器类型*/
case TYPE_STATE:
type = ch;
if(len > 0)
state = DATA_STATE;
else
state = FCS_STATE;
break;
/*读取帧数据域*/
case DATA_STATE:
buffer[temp_len++] = ch;
available = myCom->bytesAvailable();
/*缓存数据不足,将缓存数据全部读取*/
if(available <= len - temp_len){
myCom->read((char*)&buffer[temp_len], available);
temp_len += available;
}
/*缓存数据充足,仅读取数据域剩余部分*/
else{
myCom->read((char*)&buffer[temp_len], len-temp_len);
temp_len += (len - temp_len);
}
if(temp_len == len)
state = FCS_STATE;
break;
/*读取帧结束域*/
case FCS_STATE:
if(ch == APPPRO_FCS_INFO){
//switch 语句的嵌套使用
switch(type){
case APPTYP_HALL_INFO: //干簧门磁/霍尔开关
sensor_info_all.HALL_Info[0]=buffer[0];
sensor_info_all.HALL_Info[1]=buffer[1];
break;
case APPTYP_GAS_INFO: //广谱气体传感器
sensor_info_all.GAS_Info=buffer[0];
break;
case APPTYP_IRDS_INFO: //红外对射传感器
sensor_info_all.IRDS_Info=buffer[0];
break;
case APPTYP_IRFS_INFO: //接近/红外反射传感器
sensor_info_all.IRFS_Info[0]=buffer[0];
sensor_info_all.IRFS_Info[1]=buffer[1];
break;
case APPTYP_RSIR_INFO: //热释红外传感器
sensor_info_all.RSIR_Info=buffer[0];
break;
case APPTYP_MCPH_INFO: //声响开关/光敏
sensor_info_all.MCPH_Info[0]=buffer[0];
sensor_info_all.MCPH_Info[1]=buffer[1];
break;
case APPTYP_RNSW_INFO: //雨雪传感器
sensor_info_all.RNSW_Info=buffer[0];
break;
case APPTYP_SHK_INFO: //震动传感器
sensor_info_all.SHK_Info=buffer[0];
break;
case APPTYP_MFS_INFO: //磁场强度传感器
for(int i=0;i<6;i++)
sensor_info_all.MFS_Info[i]=buffer[i];
break;
case APPTYP_ILIN_INFO: //光照强度传感器
sensor_info_all.BH1750_Info[0]=buffer[0];
sensor_info_all.BH1750_Info[1]=buffer[1];
break;
case APPTYP_AIPR_INFO: //气压传感器
sensor_info_all.AIPR_Info[0]=buffer[0];
sensor_info_all.AIPR_Info[1]=buffer[1];
break;
case APPTYP_TRAC_INFO: //三轴加速度传感器
for(int i=0;i<6;i++)
sensor_info_all.TRAC_Info[i]=buffer[i];
break;
case APPTYP_SHT_INFO: //温湿度传感器
for(int i=0;i<4;i++)
sensor_info_all.SHT_Info[i]=buffer[i];
break;
case APPTYP_DIP_INFO: //单轴倾角传感器
sensor_info_all.DIP_Info[0]=buffer[0];
sensor_info_all.DIP_Info[1]=buffer[1];
break;
case APPTYP_AMP_INFO: //电流传感器
sensor_info_all.AMP_Info[0]=buffer[0];
sensor_info_all.AMP_Info[1]=buffer[1];
break;
case APPTYP_DUST_INFO: //粉尘传感器
sensor_info_all.DUST_Info[0]=buffer[0];
sensor_info_all.DUST_Info[1]=buffer[1];
break;
case APPTYP_IRCJ_INFO: //颜色传感器
sensor_info_all.IRCJ_Info[0]=buffer[0];
sensor_info_all.IRCJ_Info[1]=buffer[1];
sensor_info_all.IRCJ_Info[2]=buffer[2];
break;
case APPTYP_INAM_INFO: //仪表放大
sensor_info_all.INAM_Info[0]=buffer[0];
sensor_info_all.INAM_Info[1]=buffer[1];
break;
case APPTYP_ULR_INFO: //紫外线传感器
sensor_info_all.ULR_Info[0]=buffer[0];
sensor_info_all.ULR_Info[1]=buffer[1];
break;
case APPTYP_THE_INFO: //热电偶传感器
sensor_info_all.THE_Info[0]=buffer[0];
sensor_info_all.THE_Info[1]=buffer[1];
break;
default:
break;
}
// emit dataSend();
}
state = SOP_STATE;
break;
default:
break;
}
}
}
| 31.042194 | 79 | 0.488922 | dreamtravel |
02d1ad7743661964343baa4cdfefc1a656b7f90a | 11,202 | cpp | C++ | Framework/Source/C++11/LWCore/LWCrypto.cpp | slicer4ever/Lightwaver | 1f444e42eab9988632f541ab3c8f491d557c7de7 | [
"MIT"
] | 3 | 2017-10-24T08:04:49.000Z | 2018-08-28T10:08:08.000Z | Framework/Source/C++11/LWCore/LWCrypto.cpp | slicer4ever/Lightwave | 1f444e42eab9988632f541ab3c8f491d557c7de7 | [
"MIT"
] | null | null | null | Framework/Source/C++11/LWCore/LWCrypto.cpp | slicer4ever/Lightwave | 1f444e42eab9988632f541ab3c8f491d557c7de7 | [
"MIT"
] | null | null | null | #include "LWCore/LWCrypto.h"
#include "LWCore/LWByteBuffer.h"
#include <cstring>
#include <iostream>
uint32_t LWCrypto::HashMD5(const char *InBuffer, uint32_t InBufferLen, char *OutBuffer){
char Buffer[64];
uint32_t Table[] = { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 };
uint32_t Shift[] = { 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 };
uint32_t A = 0x67452301;
uint32_t B = 0xefcdab89;
uint32_t C = 0x98badcfe;
uint32_t D = 0x10325476;
for (uint32_t i = 0; i < InBufferLen+9;i+=64){
const uint32_t *Buf = (const uint32_t*)(InBuffer + i);
if(i+64>InBufferLen){
Buf = (const uint32_t*)Buffer;
std::memset(Buffer, 0, sizeof(Buffer));
if (i < InBufferLen){
std::memcpy(Buffer, InBuffer + i, sizeof(char)*(InBufferLen - i));
if (i + 64 != InBufferLen) Buffer[InBufferLen - i] = '\x80';
} else if (i == InBufferLen) Buffer[0] = '\x80';
if (i + 56 >= InBufferLen) *(((uint64_t*)Buffer) + 7) = InBufferLen * 8;
}
uint32_t tA = A;
uint32_t tB = B;
uint32_t tC = C;
uint32_t tD = D;
for (uint32_t d = 0; d < 64;d++){
uint32_t F = 0;
uint32_t g = 0;
if(d<16){
F = (tB&tC) | ((~tB)&tD);
g = d;
} else if (d < 32){
F = (tD&tB) | ((~tD)&tC);
g = (5 * d + 1) % 16;
}else if(d<48){
F = tB^tC^tD;
g = (3 * d + 5) % 16;
}else{
F = tC ^ (tB | (~tD));
g = (7 * d) % 16;
}
uint32_t n = (tA + F + Table[d] + Buf[g]);
tA = tD;
tD = tC;
tC = tB;
tB = tB + ((n << Shift[d]) | (n >> (32 - Shift[d])));
}
A += tA;
B += tB;
C += tC;
D += tD;
}
if(OutBuffer){
*(uint32_t*)OutBuffer = (A << 24) | (A >> 24) | ((A & 0xFF00) << 8) | ((A & 0xFF0000) >> 8);
*(((uint32_t*)OutBuffer) + 1) = (B << 24) | (B >> 24) | ((B & 0xFF00) << 8) | ((B & 0xFF0000) >> 8);
*(((uint32_t*)OutBuffer) + 2) = (C << 24) | (C >> 24) | ((C & 0xFF00) << 8) | ((C & 0xFF0000) >> 8);
*(((uint32_t*)OutBuffer) + 3) = (D << 24) | (D >> 24) | ((D & 0xFF00) << 8) | ((D & 0xFF0000) >> 8);
}
return 16;
}
uint32_t LWCrypto::HashSHA1(const char *InBuffer, uint32_t InBufferLen, char *OutBuffer){
char Buffer[320];
auto OrderSwap = [](uint32_t Value)->uint32_t {
return Value;
//return (Value & 0xFF) << 24 | (Value & 0xFF00) << 8 | (Value & 0xFF0000) >> 8 | (Value & 0xFF000000) >> 24;
};
uint32_t A = 0x67452301;
uint32_t B = 0xefcdab89;
uint32_t C = 0x98badcfe;
uint32_t D = 0x10325476;
uint32_t E = 0xC3D2E1F0;
for (uint32_t i = 0; i < InBufferLen + 9; i += 64){
if (i + 64 > InBufferLen){
std::memset(Buffer, 0, sizeof(Buffer));
if (i < InBufferLen){
std::memcpy(Buffer, InBuffer + i, sizeof(char)*(InBufferLen - i));
if (i + 64 != InBufferLen) Buffer[InBufferLen - i] = '\x80';
} else if (i == InBufferLen) Buffer[0] = '\x80';
if (i + 56 >= InBufferLen){
uint64_t Len = LWByteBuffer::MakeBig(InBufferLen * 8);
*(((uint32_t*)Buffer) + 14) = (uint32_t)(Len >> 32);
*(((uint32_t*)Buffer) + 15) = (uint32_t)Len;
}
} else std::memcpy(Buffer, InBuffer + i, sizeof(char) * 64);
uint32_t *Buf = (uint32_t*)Buffer;
for (uint32_t d = 0; d < 16; d++) Buf[d] = LWByteBuffer::MakeBig(Buf[d]);
uint32_t tA = A;
uint32_t tB = B;
uint32_t tC = C;
uint32_t tD = D;
uint32_t tE = E;
for (uint32_t d = 16; d < 80; d++){
uint32_t n = (Buf[d - 3] ^ Buf[d - 8] ^ Buf[d - 14] ^ Buf[d - 16]);
Buf[d] = (n << 1) | (n >> 31);
}
for (uint32_t d = 0; d < 80; d++){
uint32_t F = 0;
uint32_t k = 0;
if (d < 20){
F = (tB&tC) | ((~tB)&tD);
k = 0x5A827999;
} else if (d < 40){
F = tB^tC^tD;
k = 0x6ED9EBA1;
} else if (d < 60){
F = (tB&tC) | (tB&tD) | (tC&tD);
k = 0x8F1BBCDC;
} else{
F = tB^tC^tD;
k = 0xCA62C1D6;
}
uint32_t n = ((tA << 5) | (tA >> 27)) + F + tE + k + Buf[d];
tE = tD;
tD = tC;
tC = (tB << 30) | (tB >> 2);
tB = tA;
tA = n;
}
A += tA;
B += tB;
C += tC;
D += tD;
E += tE;
}
if (OutBuffer){
*(uint32_t*)OutBuffer = OrderSwap(A);
*(((uint32_t*)OutBuffer) + 1) = OrderSwap(B);
*(((uint32_t*)OutBuffer) + 2) = OrderSwap(C);
*(((uint32_t*)OutBuffer) + 3) = OrderSwap(D);
*(((uint32_t*)OutBuffer) + 4) = OrderSwap(E);
}
return 20;
}
uint32_t LWCrypto::Base64Encode(const char *InBuffer, uint32_t InBufferLen, char *OutBuffer, uint32_t OutBufferLen){
if (!OutBuffer) return (InBufferLen + 2) / 3 * 4;
char CodeTable[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" };
char *OutLast = OutBuffer + OutBufferLen;
for (uint32_t i = 0; i < InBufferLen;i+=3){
uint32_t iA = InBuffer[i];
uint32_t iB = (i + 1) < InBufferLen ? InBuffer[i + 1] : 0;
uint32_t iC = (i + 2) < InBufferLen ? InBuffer[i + 2] : 0;
uint32_t oA = (iA & 0xFC) >> 2;
uint32_t oB = ((iA & 0x3) << 4) | ((iB & 0xF0) >> 4);
uint32_t oC = (iB & 0xF) << 2 | (iC & 0xC0) >> 6;
uint32_t oD = (iC & 0x3F);
if (OutBuffer != OutLast) *OutBuffer++ = CodeTable[oA];
if (OutBuffer != OutLast) *OutBuffer++ = CodeTable[oB];
if (OutBuffer != OutLast) *OutBuffer++ = (i + 1) < InBufferLen ? CodeTable[oC] : '=';
if (OutBuffer != OutLast) *OutBuffer++ = (i + 2) < InBufferLen ? CodeTable[oD] : '=';
}
return (InBufferLen + 2) / 3 * 4;
}
uint32_t LWCrypto::Base64Decode(const char *InBuffer, uint32_t InBufferLen, char *OutBuffer, uint32_t OutBufferLen){
if (!OutBuffer) return (InBufferLen + 3) / 4 * 3;
char CodeTable[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" };
char *OutLast = OutBuffer + OutBufferLen;
for (uint32_t i = 0; i < InBufferLen;i+=4){
uintptr_t iA = (uintptr_t)(strchr(CodeTable, InBuffer[i]) - CodeTable);
uintptr_t iB = (uintptr_t)(strchr(CodeTable, InBuffer[i+1]) - CodeTable);
uintptr_t iC = (uintptr_t)(strchr(CodeTable, InBuffer[i+2]));
uintptr_t iD = (uintptr_t)(strchr(CodeTable, InBuffer[i+3]));
iC = iC == 0 ? iC : (iC - (uintptr_t)CodeTable);
iD = iD == 0 ? iD : (iD - (uintptr_t)CodeTable);
if (OutBuffer != OutLast) *OutBuffer++ = (char)((iA << 2) | ((iB & 0x30) >> 4));
if (OutBuffer != OutLast) *OutBuffer++ = (char)(((iB & 0x0F) << 4) | ((iC & 0x3C) >> 2));
if (OutBuffer != OutLast) *OutBuffer++ = (char)(((iC & 0x03) << 6) | iD);
}
return (InBufferLen + 3) / 4 * 3;
}
uint32_t LWCrypto::CRC32(const uint8_t *Data, uint32_t DataLen, uint32_t CRCCurr, bool Finished) {
constexpr uint32_t crc32Table[256] = {
0x00000000u, 0x77073096u, 0xee0e612cu, 0x990951bau, 0x076dc419u, 0x706af48fu, 0xe963a535u, 0x9e6495a3u,
0x0edb8832u, 0x79dcb8a4u, 0xe0d5e91eu, 0x97d2d988u, 0x09b64c2bu, 0x7eb17cbdu, 0xe7b82d07u, 0x90bf1d91u,
0x1db71064u, 0x6ab020f2u, 0xf3b97148u, 0x84be41deu, 0x1adad47du, 0x6ddde4ebu, 0xf4d4b551u, 0x83d385c7u,
0x136c9856u, 0x646ba8c0u, 0xfd62f97au, 0x8a65c9ecu, 0x14015c4fu, 0x63066cd9u, 0xfa0f3d63u, 0x8d080df5u,
0x3b6e20c8u, 0x4c69105eu, 0xd56041e4u, 0xa2677172u, 0x3c03e4d1u, 0x4b04d447u, 0xd20d85fdu, 0xa50ab56bu,
0x35b5a8fau, 0x42b2986cu, 0xdbbbc9d6u, 0xacbcf940u, 0x32d86ce3u, 0x45df5c75u, 0xdcd60dcfu, 0xabd13d59u,
0x26d930acu, 0x51de003au, 0xc8d75180u, 0xbfd06116u, 0x21b4f4b5u, 0x56b3c423u, 0xcfba9599u, 0xb8bda50fu,
0x2802b89eu, 0x5f058808u, 0xc60cd9b2u, 0xb10be924u, 0x2f6f7c87u, 0x58684c11u, 0xc1611dabu, 0xb6662d3du,
0x76dc4190u, 0x01db7106u, 0x98d220bcu, 0xefd5102au, 0x71b18589u, 0x06b6b51fu, 0x9fbfe4a5u, 0xe8b8d433u,
0x7807c9a2u, 0x0f00f934u, 0x9609a88eu, 0xe10e9818u, 0x7f6a0dbbu, 0x086d3d2du, 0x91646c97u, 0xe6635c01u,
0x6b6b51f4u, 0x1c6c6162u, 0x856530d8u, 0xf262004eu, 0x6c0695edu, 0x1b01a57bu, 0x8208f4c1u, 0xf50fc457u,
0x65b0d9c6u, 0x12b7e950u, 0x8bbeb8eau, 0xfcb9887cu, 0x62dd1ddfu, 0x15da2d49u, 0x8cd37cf3u, 0xfbd44c65u,
0x4db26158u, 0x3ab551ceu, 0xa3bc0074u, 0xd4bb30e2u, 0x4adfa541u, 0x3dd895d7u, 0xa4d1c46du, 0xd3d6f4fbu,
0x4369e96au, 0x346ed9fcu, 0xad678846u, 0xda60b8d0u, 0x44042d73u, 0x33031de5u, 0xaa0a4c5fu, 0xdd0d7cc9u,
0x5005713cu, 0x270241aau, 0xbe0b1010u, 0xc90c2086u, 0x5768b525u, 0x206f85b3u, 0xb966d409u, 0xce61e49fu,
0x5edef90eu, 0x29d9c998u, 0xb0d09822u, 0xc7d7a8b4u, 0x59b33d17u, 0x2eb40d81u, 0xb7bd5c3bu, 0xc0ba6cadu,
0xedb88320u, 0x9abfb3b6u, 0x03b6e20cu, 0x74b1d29au, 0xead54739u, 0x9dd277afu, 0x04db2615u, 0x73dc1683u,
0xe3630b12u, 0x94643b84u, 0x0d6d6a3eu, 0x7a6a5aa8u, 0xe40ecf0bu, 0x9309ff9du, 0x0a00ae27u, 0x7d079eb1u,
0xf00f9344u, 0x8708a3d2u, 0x1e01f268u, 0x6906c2feu, 0xf762575du, 0x806567cbu, 0x196c3671u, 0x6e6b06e7u,
0xfed41b76u, 0x89d32be0u, 0x10da7a5au, 0x67dd4accu, 0xf9b9df6fu, 0x8ebeeff9u, 0x17b7be43u, 0x60b08ed5u,
0xd6d6a3e8u, 0xa1d1937eu, 0x38d8c2c4u, 0x4fdff252u, 0xd1bb67f1u, 0xa6bc5767u, 0x3fb506ddu, 0x48b2364bu,
0xd80d2bdau, 0xaf0a1b4cu, 0x36034af6u, 0x41047a60u, 0xdf60efc3u, 0xa867df55u, 0x316e8eefu, 0x4669be79u,
0xcb61b38cu, 0xbc66831au, 0x256fd2a0u, 0x5268e236u, 0xcc0c7795u, 0xbb0b4703u, 0x220216b9u, 0x5505262fu,
0xc5ba3bbeu, 0xb2bd0b28u, 0x2bb45a92u, 0x5cb36a04u, 0xc2d7ffa7u, 0xb5d0cf31u, 0x2cd99e8bu, 0x5bdeae1du,
0x9b64c2b0u, 0xec63f226u, 0x756aa39cu, 0x026d930au, 0x9c0906a9u, 0xeb0e363fu, 0x72076785u, 0x05005713u,
0x95bf4a82u, 0xe2b87a14u, 0x7bb12baeu, 0x0cb61b38u, 0x92d28e9bu, 0xe5d5be0du, 0x7cdcefb7u, 0x0bdbdf21u,
0x86d3d2d4u, 0xf1d4e242u, 0x68ddb3f8u, 0x1fda836eu, 0x81be16cdu, 0xf6b9265bu, 0x6fb077e1u, 0x18b74777u,
0x88085ae6u, 0xff0f6a70u, 0x66063bcau, 0x11010b5cu, 0x8f659effu, 0xf862ae69u, 0x616bffd3u, 0x166ccf45u,
0xa00ae278u, 0xd70dd2eeu, 0x4e048354u, 0x3903b3c2u, 0xa7672661u, 0xd06016f7u, 0x4969474du, 0x3e6e77dbu,
0xaed16a4au, 0xd9d65adcu, 0x40df0b66u, 0x37d83bf0u, 0xa9bcae53u, 0xdebb9ec5u, 0x47b2cf7fu, 0x30b5ffe9u,
0xbdbdf21cu, 0xcabac28au, 0x53b39330u, 0x24b4a3a6u, 0xbad03605u, 0xcdd70693u, 0x54de5729u, 0x23d967bfu,
0xb3667a2eu, 0xc4614ab8u, 0x5d681b02u, 0x2a6f2b94u, 0xb40bbe37u, 0xc30c8ea1u, 0x5a05df1bu, 0x2d02ef8du,
};
for (uint32_t i = 0; i < DataLen; i++) {
CRCCurr = crc32Table[(uint8_t)(Data[i] ^ CRCCurr)] ^ CRCCurr >> 8;
}
if (Finished) CRCCurr ^= 0xFFFFFFFF;
return CRCCurr;
} | 47.668085 | 118 | 0.644885 | slicer4ever |
02d73d0103383a1d6bbc883a23a2426a9f770aac | 700 | cpp | C++ | src/particle.cpp | robdan7/Impact | 75dfce522b569bbd2f4dfb549aa78d2196c8e793 | [
"MIT"
] | null | null | null | src/particle.cpp | robdan7/Impact | 75dfce522b569bbd2f4dfb549aa78d2196c8e793 | [
"MIT"
] | null | null | null | src/particle.cpp | robdan7/Impact | 75dfce522b569bbd2f4dfb549aa78d2196c8e793 | [
"MIT"
] | null | null | null | //
// Created by Robin on 2021-06-22.
//
#include "particle.h"
namespace Impact {
Same_arena_allocator<1,uint16_t,particle> particle::s_allocator;
private_ptr<particle>
particle::Create(const vec3 &position, const vec3 &velocity, scalar inverse_mass, const vec3 &acceleration) {
auto ID = (ptr_primitive)s_allocator.alloc(position,velocity,inverse_mass,acceleration);
return private_ptr<particle>(ID, (Container<particle>*)&s_allocator);
}
private_ptr<particle> particle::Create(const vec3 &acceleration) {
auto ID = (ptr_primitive)s_allocator.alloc(acceleration);
return private_ptr<particle>(ID, (Container<particle>*)&s_allocator);
}
} | 35 | 113 | 0.718571 | robdan7 |
02d74315f5be49263ec8ebe3d6e405305898d227 | 507 | hpp | C++ | include/yall/timer.hpp | Bajron/yall | b1d191b884c94a8a6e55271837f9c778d101784f | [
"MIT"
] | null | null | null | include/yall/timer.hpp | Bajron/yall | b1d191b884c94a8a6e55271837f9c778d101784f | [
"MIT"
] | null | null | null | include/yall/timer.hpp | Bajron/yall | b1d191b884c94a8a6e55271837f9c778d101784f | [
"MIT"
] | null | null | null | #pragma once
#include "yall/logger.hpp"
#include <chrono>
namespace yall {
template <class T = std::chrono::steady_clock>
struct Timer {
Logger logger;
typename T::time_point last;
Timer(Logger logger): logger(logger), last(T::now()) {
logger("Timer starts");
}
void operator()(const std::string& message = "") {
auto now = T::now();
logger() << message << " "
<< std::chrono::duration_cast<std::chrono::milliseconds>(now - last).count() << " ms";
last = now;
}
};
}
| 19.5 | 92 | 0.615385 | Bajron |
02dad15413d8f093655f32e1ae7647226174a299 | 2,271 | inl | C++ | BG3Extender/GameDefinitions/PropertyMaps/SurfaceActions.inl | Norbyte/bg3se | 209275d5c99d92c65f47c07906f4e9bdcf28a073 | [
"MIT"
] | 3 | 2021-11-08T22:29:01.000Z | 2022-01-23T03:19:56.000Z | BG3Extender/GameDefinitions/PropertyMaps/SurfaceActions.inl | Norbyte/bg3se | 209275d5c99d92c65f47c07906f4e9bdcf28a073 | [
"MIT"
] | 2 | 2021-09-14T22:37:46.000Z | 2021-12-26T17:08:47.000Z | BG3Extender/GameDefinitions/PropertyMaps/SurfaceActions.inl | Norbyte/bg3se | 209275d5c99d92c65f47c07906f4e9bdcf28a073 | [
"MIT"
] | null | null | null | BEGIN_CLS(esv::SurfaceAction)
P(StoryActionID)
P_REF(Originator)
P_RO(Handle)
END_CLS()
BEGIN_CLS(esv::CreateSurfaceActionBase)
INHERIT(esv::SurfaceAction)
P(Owner)
P(Duration)
P(IsControlledByConcentration)
P(Position)
P(SurfaceType)
END_CLS()
BEGIN_CLS(esv::CreateSurfaceAction)
INHERIT(esv::CreateSurfaceActionBase)
P_RO(InitialChangesPushed)
P(Radius)
P(ExcludeRadius)
P(MaxHeight)
P(IgnoreIrreplacableSurfaces)
P(CheckExistingSurfaces)
P(LineCheckBlock)
P(Timer)
P(GrowTimer)
P(GrowStep)
P(CurrentCellCount)
P_RO(SurfaceLayer)
P_REF(SpellId)
P_RO(SurfaceConcentrationTarget)
END_CLS()
BEGIN_CLS(esv::CreatePuddleAction)
INHERIT(esv::CreateSurfaceActionBase)
P(SurfaceCells)
P(Step)
P(GrowSpeed)
P_RO(IsFinished)
P(IgnoreIrreplacableSurfaces)
P(GrowTimer)
END_CLS()
BEGIN_CLS(esv::ExtinguishFireAction)
INHERIT(esv::CreateSurfaceActionBase)
P(Position)
P(Radius)
P(Percentage)
P(GrowTimer)
P(Step)
END_CLS()
BEGIN_CLS(esv::ZoneActionParams)
P(Shape)
P(Radius)
P(ZoneParam)
P(FrontOffset)
P(MaxHeight)
P(Height)
P(Flags)
END_CLS()
BEGIN_CLS(esv::ZoneAction)
INHERIT(esv::CreateSurfaceActionBase)
P_REF(Spell)
P(TextKey)
P(Target)
P_REF(Params)
P(GrowStep)
P_REF(Targets)
P_RO(CurrentCellCount)
P(Flags)
END_CLS()
BEGIN_CLS(esv::TransformSurfaceAction)
INHERIT(esv::SurfaceAction)
P(Timer)
P(SurfaceTransformAction)
P(OriginSurface)
P(SurfaceLayer)
P(GrowCellPerSecond)
P_RO(Finished)
P(OwnerHandle)
P(Position)
P(Position)
P(SurfaceLifetime)
P(PlayerCharacterNearby)
END_CLS()
BEGIN_CLS(esv::ChangeSurfaceOnPathAction)
INHERIT(esv::CreateSurfaceActionBase)
P(FollowHandle)
P(Radius)
P(IsFinished)
P(IgnoreIrreplacableSurfaces)
P(CheckExistingSurfaces)
P(IgnoreOwnerCells)
END_CLS()
BEGIN_CLS(esv::RectangleSurfaceAction)
INHERIT(esv::CreateSurfaceActionBase)
P(Target)
P(SurfaceArea_M)
P(Width)
P(Length)
P(GrowTimer)
P(MaxHeight)
P(GrowStep)
// TODO - DamageList
P(DeathType)
P(LineCheckBlock)
// TODO - SkillProperties_M, CurrentGrowTimer_M
P_REF(Characters)
P_REF(Items)
P_RO(CurrentCellCount)
END_CLS()
BEGIN_CLS(esv::PolygonSurfaceAction)
INHERIT(esv::CreateSurfaceActionBase)
P(PolygonVertices)
// TODO - DamageList
P(CurrentGrowTimer)
P(GrowTimer)
P(SomePosition)
P(GrowStep)
P(LastSurfaceCellCount)
P_REF(Characters)
P_REF(Items)
END_CLS()
| 16.221429 | 47 | 0.810216 | Norbyte |
02e030a012a432beec829074eeb8ab806fed386a | 1,351 | hpp | C++ | platforms/magnum/include/tangram/platform_magnum.hpp | mathisloge/tangram-es | 36899751d86f8899d864414784b8c88e4ce42349 | [
"MIT"
] | null | null | null | platforms/magnum/include/tangram/platform_magnum.hpp | mathisloge/tangram-es | 36899751d86f8899d864414784b8c88e4ce42349 | [
"MIT"
] | null | null | null | platforms/magnum/include/tangram/platform_magnum.hpp | mathisloge/tangram-es | 36899751d86f8899d864414784b8c88e4ce42349 | [
"MIT"
] | null | null | null | #pragma once
#include "map.h"
#include "platform.h"
#include <Magnum/GL/Texture.h>
#include <memory>
#include <tangram_export.h>
#include <utility>
namespace Tangram {
void TANGRAM_EXPORT setContext(Magnum::GL::Context& ctx);
class TANGRAM_EXPORT MagnumTexture {
public:
explicit MagnumTexture(const int width, const int height, const std::string& scene_file,
const std::string& api_env_name = "", const std::string& api_env_scene_key = "",
uint32_t maxActiveTasks = 20, uint32_t connectionTimeoutMs = 3000,
uint32_t requestTimeoutMs = 30000);
Magnum::GL::Texture2D& texture();
void render(const double time);
void setApiKeyFromEnv(const std::string& env_name, const std::string& scene_key);
void updateApiKey();
void setSceneFile(const std::string& scene_file);
std::pair<int, int> getSize() const;
void resizeScene(const int width, const int height);
void handleClick(const double x, const double y);
void handleDoubleClick(const double x, const double y);
void handleStartDrag(const double x, const double y);
void handleDrag(const double x, const double y);
void handleEndDrag();
void zoomDelta(float factor);
~MagnumTexture();
private:
class Impl;
Impl* impl_;
};
} // namespace Tangram
| 30.022222 | 107 | 0.680237 | mathisloge |
02e2649d890fa2c0b0438de3d478fc1254d1dc99 | 3,646 | cpp | C++ | src/Dynamics/ParticleSystem/ParticleSystem.cpp | regnore/peridyno | 4cc45d8436cc4406edd9f044307cf92ecd7f1244 | [
"Apache-2.0"
] | 2 | 2022-01-29T08:51:50.000Z | 2022-02-22T12:07:09.000Z | src/Dynamics/ParticleSystem/ParticleSystem.cpp | regnore/peridyno | 4cc45d8436cc4406edd9f044307cf92ecd7f1244 | [
"Apache-2.0"
] | null | null | null | src/Dynamics/ParticleSystem/ParticleSystem.cpp | regnore/peridyno | 4cc45d8436cc4406edd9f044307cf92ecd7f1244 | [
"Apache-2.0"
] | null | null | null | #include "ParticleSystem.h"
#include "Topology/PointSet.h"
namespace dyno
{
IMPLEMENT_TCLASS(ParticleSystem, TDataType)
template<typename TDataType>
ParticleSystem<TDataType>::ParticleSystem(std::string name)
: Node(name)
{
auto ptSet = std::make_shared<PointSet<TDataType>>();
this->stateTopology()->setDataPtr(ptSet);
}
template<typename TDataType>
ParticleSystem<TDataType>::~ParticleSystem()
{
}
template<typename TDataType>
void ParticleSystem<TDataType>::loadParticles(std::string filename)
{
auto ptSet = TypeInfo::cast<PointSet<TDataType>>(this->stateTopology()->getDataPtr());
ptSet->loadObjFile(filename);
}
template<typename TDataType>
void ParticleSystem<TDataType>::loadParticles(Coord center, Real r, Real distance)
{
std::vector<Coord> vertList;
Coord lo = center - r;
Coord hi = center + r;
for (Real x = lo[0]; x <= hi[0]; x += distance)
{
for (Real y = lo[1]; y <= hi[1]; y += distance)
{
for (Real z = lo[2]; z <= hi[2]; z += distance)
{
Coord p = Coord(x, y, z);
if ((p-center).norm() < r)
{
vertList.push_back(Coord(x, y, z));
}
}
}
}
auto ptSet = TypeInfo::cast<PointSet<TDataType>>(this->stateTopology()->getDataPtr());
ptSet->setPoints(vertList);
vertList.clear();
}
template<typename TDataType>
void ParticleSystem<TDataType>::loadParticles(Coord lo, Coord hi, Real distance)
{
std::vector<Coord> vertList;
for (Real x = lo[0]; x <= hi[0]; x += distance)
{
for (Real y = lo[1]; y <= hi[1]; y += distance)
{
for (Real z = lo[2]; z <= hi[2]; z += distance)
{
Coord p = Coord(x, y, z);
vertList.push_back(Coord(x, y, z));
}
}
}
auto ptSet = TypeInfo::cast<PointSet<TDataType>>(this->stateTopology()->getDataPtr());
ptSet->setPoints(vertList);
std::cout << "particle number: " << vertList.size() << std::endl;
vertList.clear();
}
template<typename TDataType>
bool ParticleSystem<TDataType>::translate(Coord t)
{
auto ptSet = TypeInfo::cast<PointSet<TDataType>>(this->stateTopology()->getDataPtr());
ptSet->translate(t);
return true;
}
template<typename TDataType>
bool ParticleSystem<TDataType>::scale(Real s)
{
auto ptSet = TypeInfo::cast<PointSet<TDataType>>(this->stateTopology()->getDataPtr());
ptSet->scale(s);
return true;
}
// template<typename TDataType>
// void ParticleSystem<TDataType>::setVisible(bool visible)
// {
// if (m_pointsRender == nullptr)
// {
// m_pointsRender = std::make_shared<PointRenderModule>();
// this->addVisualModule(m_pointsRender);
// }
//
// Node::setVisible(visible);
// }
template<typename TDataType>
void ParticleSystem<TDataType>::updateTopology()
{
if (!this->statePosition()->isEmpty())
{
auto ptSet = TypeInfo::cast<PointSet<TDataType>>(this->stateTopology()->getDataPtr());
int num = this->statePosition()->getElementCount();
auto& pts = ptSet->getPoints();
if (num != pts.size())
{
pts.resize(num);
}
pts.assign(this->statePosition()->getData());
}
}
template<typename TDataType>
void ParticleSystem<TDataType>::resetStates()
{
auto ptSet = TypeInfo::cast<PointSet<TDataType>>(this->stateTopology()->getDataPtr());
if (ptSet == nullptr) return;
auto pts = ptSet->getPoints();
if (pts.size() > 0)
{
this->statePosition()->setElementCount(pts.size());
this->stateVelocity()->setElementCount(pts.size());
this->stateForce()->setElementCount(pts.size());
this->statePosition()->getData().assign(pts);
this->stateVelocity()->getDataPtr()->reset();
}
Node::resetStates();
}
DEFINE_CLASS(ParticleSystem);
} | 23.986842 | 89 | 0.655513 | regnore |
02e62bdd77b56323811501590f0a0feb86fa30ab | 14,000 | cpp | C++ | es-app/src/guis/GuiRomsManager.cpp | digitalLumberjack/EmulationStation | 15ce9ce0c40faee69611c69ffcb1cf57d0182330 | [
"MIT"
] | 51 | 2015-11-15T12:17:15.000Z | 2020-12-30T18:36:06.000Z | es-app/src/guis/GuiRomsManager.cpp | digitalLumberjack/EmulationStation | 15ce9ce0c40faee69611c69ffcb1cf57d0182330 | [
"MIT"
] | 78 | 2015-11-18T11:56:30.000Z | 2018-03-29T17:45:51.000Z | es-app/src/guis/GuiRomsManager.cpp | digitalLumberjack/EmulationStation | 15ce9ce0c40faee69611c69ffcb1cf57d0182330 | [
"MIT"
] | 81 | 2015-12-27T11:09:20.000Z | 2021-06-04T09:42:47.000Z | /*
* Copyright (c) 2015 Filipe Azevedo <pasnox@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.
*/
#include "GuiRomsManager.h"
#include "views/gamelist/BasicGameListView.h"
#include "SystemData.h"
#include "Settings.h"
#include "Util.h"
#include "Window.h"
#include "guis/GuiTextEditPopup.h"
#include "components/FileSystemSelectorComponent.h"
#include <boost/format.hpp>
#include <boost/system/error_code.hpp>
namespace fs = boost::filesystem;
#define SMALL_FONT_LIGHT Font::get(FONT_SIZE_SMALL, FONT_PATH_LIGHT)
#define DEFAULT_FONT_COLOR 0x777777FF
#define DEFAULT_ROMS_PATH_KEY "DefaultRomsPath"
#define DEFAULT_EXTERNAL_ROMS_PATH_KEY "DefaultExternalRomsPath"
#define PLATFORM_EXTERNAL_ROMS_PATH_KEY_FORMAT "ExternalRomsPath_%1%"
#define STRING_SETTING(KEY) Settings::getInstance()->getString(KEY)
namespace {
bool fileDataLessThan(const FileData* lhs, const FileData* rhs) {
const std::string leftName = strToUpper(lhs->getName());
const std::string rightName = strToUpper(rhs->getName());
if (lhs->getType() == rhs->getType()) {
return leftName.compare(rightName) < 0;
}
return lhs->getType() == FOLDER;
}
bool createDirectories(const fs::path& target) {
boost::system::error_code ec;
fs::create_directories(target, ec);
return ec.value() == boost::system::errc::success;
}
bool removeDirectories(const fs::path& target) {
boost::system::error_code ec;
fs::remove_all(target);
return ec.value() == boost::system::errc::success;
}
bool createDirectorySymLink(const fs::path& source, const fs::path& target) {
boost::system::error_code ec;
fs::create_directory_symlink(source, target, ec);
return ec.value() == boost::system::errc::success;
}
bool removeDirectorySymLink(const fs::path& source) {
boost::system::error_code ec;
fs::remove(source, ec);
return ec.value() == boost::system::errc::success;
}
bool createFileSymLink(const fs::path& source, const fs::path& target) {
boost::system::error_code ec;
fs::create_symlink(source, target, ec);
return ec.value() == boost::system::errc::success;
}
bool removeFileSymLink(const fs::path& source) {
boost::system::error_code ec;
fs::remove(source, ec);
return ec.value() == boost::system::errc::success;
}
}
class RomsListView : public BasicGameListView
{
private:
GuiRomsManager::PlatformData m_data;
public:
RomsListView(Window* window, FileData* fileData, const GuiRomsManager::PlatformData& data)
: BasicGameListView(window, fileData)
, m_data(data)
{
const fs::path themePath = ThemeData::getThemeFromCurrentSet(m_data.name);
auto theme = std::make_shared<ThemeData>();
try {
theme->loadFile(themePath.string());
}
catch(...) {
}
setTheme(theme);
mList.setAlignment(mList.ALIGN_LEFT);
fileData->changePath(m_data.externalRomsPath);
fileData->lazyPopulate();
fileData->sort(fileDataLessThan, true);
populateList(fileData->getChildren());
}
virtual std::vector<HelpPrompt> getHelpPrompts() override {
std::vector<HelpPrompt> prompts;
prompts.push_back(HelpPrompt("left/right", "link-switch"));
prompts.push_back(HelpPrompt("up/down", "move"));
if (fs::is_directory(getCursor()->getPath())) {
prompts.push_back(HelpPrompt("b", "cd in"));
}
prompts.push_back(HelpPrompt("a", "cd up / back"));
return prompts;
}
virtual bool input(InputConfig* config, Input input) override {
if (config->isMappedTo("up", input) || config->isMappedTo("down", input) || config->isMappedTo("pageup", input) || config->isMappedTo("pagedown", input)) {
return BasicGameListView::input(config, input);
}
else if (input.value != 0) {
if (config->isMappedTo("b", input)) {
FileData* cursor = getCursor();
if (cursor->getType() == FOLDER) {
if(cursor->getChildren().empty()) {
cursor->lazyPopulate();
cursor->sort(fileDataLessThan, true);
}
mCursorStack.push(cursor);
populateList(cursor->getChildren());
}
}
else if (config->isMappedTo("a", input)) {
if (mCursorStack.size()) {
populateList(mCursorStack.top()->getParent()->getChildren());
setCursor(mCursorStack.top());
mCursorStack.pop();
}
else {
onFocusLost();
delete this;
}
}
else if (config->isMappedTo("right", input) || config->isMappedTo("left", input)) {
// Create / Delete symlink
FileData* cursor = getCursor();
const int cursorId = mList.getCursor();
const fs::path fileName = cursor->getPath().filename();
const fs::path platformRomsPath = m_data.romsPath;
const fs::path platformRomFilePath = fs::absolute(fileName, platformRomsPath);
const bool isSymLink = fs::is_symlink(platformRomFilePath);
// Don't handle existing non symlink files.
if (fs::exists(platformRomFilePath) && !isSymLink) {
return true;
}
if (cursor->getType() == GAME) {
if (isSymLink) {
if (removeFileSymLink(platformRomFilePath)) {
updateCursor(cursorId, cursor);
}
}
else {
if (createFileSymLink(cursor->getPath(), platformRomFilePath)) {
updateCursor(cursorId, cursor);
}
}
}
else if (cursor->getType() == FOLDER) {
if (isSymLink) {
if (removeDirectorySymLink(platformRomFilePath)) {
updateCursor(cursorId, cursor);
}
}
else {
if (createDirectorySymLink(cursor->getPath(), platformRomFilePath)) {
updateCursor(cursorId, cursor);
}
}
}
}
}
return true;
}
virtual void populateList(const std::vector<FileData*>& files) override {
mList.clear();
const FileData* root = getRoot();
const SystemData* systemData = root->getSystem();
const fs::path platformRomsPath = m_data.romsPath;
mHeaderText.setText(systemData ? systemData->getFullName() : root->getCleanName());
for (auto it = files.begin(); it != files.end(); it++) {
const fs::path fileName = (*it)->getPath().filename();
const fs::path platformRomFilePath = fs::absolute(fileName, platformRomsPath);
const bool isSymLink = fs::is_symlink(platformRomFilePath);
mList.add(formatName((*it)->getName(), isSymLink), *it, ((*it)->getType() == FOLDER));
}
}
protected:
virtual void launch(FileData*) override {
}
std::string formatName(const std::string& name, bool isLinked) const {
return str(boost::format("%1% %2%") %(isLinked ? "\u00A4" : " ") %name);
}
void updateCursor(const int cursorId, FileData* fileData) {
const fs::path fileName = fileData->getPath().filename();
const fs::path platformRomsPath = m_data.romsPath;
const fs::path platformRomFilePath = fs::absolute(fileName, platformRomsPath);
const bool isSymLink = fs::is_symlink(platformRomFilePath);
mList.changeCursorName(cursorId, formatName(fileData->getName(), isSymLink));
}
};
GuiRomsManager::GuiRomsManager(Window *window)
: MenuComponent(window, "ROMS MANAGER")
, m_fileData(std::make_shared< FileData >(FOLDER, fs::path(), nullptr))
, m_defaultRomsPath(std::make_shared<TextComponent>(window, std::string(), SMALL_FONT_LIGHT, DEFAULT_FONT_COLOR))
, m_defaultExternalRomsPath(std::make_shared<TextComponent>(window, std::string(), SMALL_FONT_LIGHT, DEFAULT_FONT_COLOR))
, m_platforms(std::make_shared< OptionListComponent<PlatformIds::PlatformId> >(window, "PLATFORM", false))
, m_platformExternalRomsPath(std::make_shared<TextComponent>(window, std::string(), SMALL_FONT_LIGHT, DEFAULT_FONT_COLOR))
, m_settingsEdited(false)
{
m_defaultRomsPath->setText(STRING_SETTING(DEFAULT_ROMS_PATH_KEY));
m_defaultExternalRomsPath->setText(STRING_SETTING(DEFAULT_EXTERNAL_ROMS_PATH_KEY));
for (int i = PlatformIds::PLATFORM_UNKNOWN +1; i < PlatformIds::PLATFORM_COUNT; ++i) {
const PlatformIds::PlatformId id = PlatformIds::PlatformId(i);
if (id == PlatformIds::PLATFORM_IGNORE) {
continue;
}
const std::string platformName = PlatformIds::getPlatformName(id);
m_platforms->add(platformName, id, id == PlatformIds::THREEDO);
}
m_platformExternalRomsPath->setText(currentPlatformData().externalRomsPath.string());
addWithLabel("ROMS", m_defaultRomsPath, true, true, [this](){ editDefaultRomsPath(); });
addWithLabel("EXTERNAL ROMS", m_defaultExternalRomsPath, false, true, [this](){ editDefaultExternalRomsPath(); });
addWithLabel("PLATFORM", m_platforms);
addWithLabel("PLATFORM ROMS", m_platformExternalRomsPath, false, true, [this](){ editCurrentPlatformExternalRomsPath(); });
m_platforms->setSelectedChangedCallback([this](const PlatformIds::PlatformId&){
m_platformExternalRomsPath->setText(currentPlatformData().externalRomsPath.string());
onSizeChanged();
});
setSize(Renderer::getScreenWidth() * 0.95f, Renderer::getScreenHeight() * 0.747f);
setPosition((Renderer::getScreenWidth() - mSize.x()) / 2, (Renderer::getScreenHeight() - mSize.y()) / 2);
}
GuiRomsManager::~GuiRomsManager()
{
if (m_settingsEdited) {
Settings::getInstance()->saveFile();
}
}
bool GuiRomsManager::input(InputConfig* config, Input input)
{
if (config->isMappedTo("x", input) && input.value != 0) {
showCurrentPlatformRomsManager();
return true;
}
else if (config->isMappedTo("a", input) && input.value != 0) {
delete this;
return true;
}
return MenuComponent::input(config, input);
}
std::vector<HelpPrompt> GuiRomsManager::getHelpPrompts()
{
std::vector<HelpPrompt> prompts = MenuComponent::getHelpPrompts();
prompts.push_back(HelpPrompt("x", "manage platform roms"));
prompts.push_back(HelpPrompt("b", "edit"));
prompts.push_back(HelpPrompt("a", "back"));
return prompts;
}
std::string GuiRomsManager::platformIdExternalRomsKey(PlatformIds::PlatformId platform)
{
const std::string name = PlatformIds::getPlatformName(platform);
return str(boost::format(PLATFORM_EXTERNAL_ROMS_PATH_KEY_FORMAT) % name);
}
fs::path GuiRomsManager::platformIdRomsPath(PlatformIds::PlatformId platform)
{
const std::string path = getExpandedPath(STRING_SETTING(DEFAULT_ROMS_PATH_KEY));
const std::string name = PlatformIds::getPlatformName(platform);
if (!path.empty()) {
return fs::absolute(name, path);
}
return fs::path();
}
fs::path GuiRomsManager::platformIdExternalRomsPath(PlatformIds::PlatformId platform)
{
if (platform == PlatformIds::PLATFORM_UNKNOWN) {
return fs::path();
}
const std::string key = platformIdExternalRomsKey(platform);
return getExpandedPath(STRING_SETTING(key));
}
GuiRomsManager::PlatformData GuiRomsManager::currentPlatformData() const
{
PlatformData data;
data.id = m_platforms->getSelected();
data.name = PlatformIds::getPlatformName(data.id);
data.romsPath = platformIdRomsPath(data.id);
data.externalRomsPath = platformIdExternalRomsPath(data.id);
return data;
}
void GuiRomsManager::editDefaultRomsPath()
{
const fs::path path = getExpandedPath(STRING_SETTING(DEFAULT_ROMS_PATH_KEY));
auto updateValue = [this](const fs::path& filePath) {
Settings::getInstance()->setString(DEFAULT_ROMS_PATH_KEY, filePath.string());
m_defaultRomsPath->setText(filePath.string());
m_settingsEdited = true;
onSizeChanged();
};
auto fileChooser = new FileSystemSelectorComponent(mWindow, path, FileSystemSelectorComponent::FoldersHideFiles);
fileChooser->setAcceptCallback(updateValue);
mWindow->pushGui(fileChooser);
}
void GuiRomsManager::editDefaultExternalRomsPath()
{
const fs::path path = getExpandedPath(STRING_SETTING(DEFAULT_EXTERNAL_ROMS_PATH_KEY));
auto updateValue = [this](const fs::path& filePath) {
Settings::getInstance()->setString(DEFAULT_EXTERNAL_ROMS_PATH_KEY, filePath.string());
m_defaultExternalRomsPath->setText(filePath.string());
m_settingsEdited = true;
onSizeChanged();
};
auto fileChooser = new FileSystemSelectorComponent(mWindow, path, FileSystemSelectorComponent::FoldersHideFiles);
fileChooser->setAcceptCallback(updateValue);
mWindow->pushGui(fileChooser);
}
void GuiRomsManager::editCurrentPlatformExternalRomsPath()
{
const GuiRomsManager::PlatformData data = currentPlatformData();
const std::string key = platformIdExternalRomsKey(data.id);
const fs::path defaultPath = getExpandedPath(STRING_SETTING(DEFAULT_EXTERNAL_ROMS_PATH_KEY));
const fs::path path = data.externalRomsPath.empty() ? defaultPath : data.externalRomsPath;
auto updateValue = [this, key](const fs::path& filePath) {
Settings::getInstance()->setString(key, filePath.string());
m_platformExternalRomsPath->setText(filePath.string());
m_settingsEdited = true;
onSizeChanged();
};
auto fileChooser = new FileSystemSelectorComponent(mWindow, path, FileSystemSelectorComponent::FoldersHideFiles);
fileChooser->setAcceptCallback(updateValue);
mWindow->pushGui(fileChooser);
}
void GuiRomsManager::showCurrentPlatformRomsManager()
{
const GuiRomsManager::PlatformData data = currentPlatformData();
if (data.romsPath.empty() || !fs::is_directory(data.externalRomsPath)) {
return;
}
if (!fs::exists(data.romsPath)) {
if (!createDirectories(data.romsPath)) {
return;
}
}
mWindow->pushGui(new RomsListView(mWindow, m_fileData.get(), data));
}
| 33.898305 | 157 | 0.729643 | digitalLumberjack |
02e9d3fe2e6161eea8ec8aa49e781617ebc1819c | 1,134 | cpp | C++ | Wonderland/Wonderland/Editor/Foundation/Shader/ShaderBase.cpp | RodrigoHolztrattner/Wonderland | ffb71d47c1725e7cd537e2d1380962b5dfdc3d75 | [
"MIT"
] | 3 | 2018-04-09T13:01:07.000Z | 2021-03-18T12:28:48.000Z | Wonderland/Wonderland/Editor/Foundation/Shader/ShaderBase.cpp | RodrigoHolztrattner/Wonderland | ffb71d47c1725e7cd537e2d1380962b5dfdc3d75 | [
"MIT"
] | null | null | null | Wonderland/Wonderland/Editor/Foundation/Shader/ShaderBase.cpp | RodrigoHolztrattner/Wonderland | ffb71d47c1725e7cd537e2d1380962b5dfdc3d75 | [
"MIT"
] | 1 | 2021-03-18T12:28:50.000Z | 2021-03-18T12:28:50.000Z | ////////////////////////////////////////////////////////////////////////////////
// Filename: ShaderBase.cpp
////////////////////////////////////////////////////////////////////////////////
#include "ShaderBase.h"
/*
ShaderBase::ShaderBase()
{
}
ShaderBase::ShaderBase(const ShaderBase& other)
{
}
ShaderBase::~ShaderBase()
{
}
*/
/*
bool ShaderBase::SetShaderParameters(float* worldMatrix, float* viewMatrix, float* projectionMatrix)
{
unsigned int location;
// Set the world matrix in the vertex shader.
location = glGetUniformLocation(m_shaderProgram, "worldMatrix");
if (location == -1)
{
return false;
}
glUniformMatrix4fv(location, 1, false, worldMatrix);
// Set the view matrix in the vertex shader.
location = glGetUniformLocation(m_shaderProgram, "viewMatrix");
if (location == -1)
{
return false;
}
glUniformMatrix4fv(location, 1, false, viewMatrix);
// Set the projection matrix in the vertex shader.
location = glGetUniformLocation(m_shaderProgram, "projectionMatrix");
if (location == -1)
{
return false;
}
glUniformMatrix4fv(location, 1, false, projectionMatrix);
return true;
}
*/ | 20.25 | 100 | 0.620811 | RodrigoHolztrattner |
02ea66375f730b7ce666e6b6878c17178e74c9fe | 935 | cpp | C++ | matrix.cpp | ikamei15/ikamei | 53f979f431b257a11baa2b280b280936c9182156 | [
"MIT"
] | null | null | null | matrix.cpp | ikamei15/ikamei | 53f979f431b257a11baa2b280b280936c9182156 | [
"MIT"
] | null | null | null | matrix.cpp | ikamei15/ikamei | 53f979f431b257a11baa2b280b280936c9182156 | [
"MIT"
] | null | null | null | #include<conio.h>
#include<iostream.h>
main()
{
int a,b;
int matrix1[2][2];
int matrix2[2][2];
int matrix3[2][2];
clrscr();
cout<<"\t**Tugas Logika Algoritma**\n\n";
for(a=0;a<=1;a++)
{
for(b=0;b<=1;b++)
{
cout<<"Masukkan nilai ke - "<<a<<" "<<b<<" ";cin>>matrix1[a][b];
}
}
cout<<"\nmatrix1\n";
for(a=0;a<=1;a++)
{
for(b=0;b<=1;b++)
{
cout<<matrix1[a][b];
}
cout<<"\n";
}
cout<<"\n";
for(a=0;a<=1;a++)
{
for(b=0;b<=1;b++)
{
cout<<"Masukkan nilai ke - "<<a<<" "<<b<<" ";cin>>matrix2[a][b];
}
}
cout<<"\nmatrix2\n";
for(a=0;a<=1;a++)
{
for(b=0;b<=1;b++)
{
cout<<matrix2[a][b];
}
cout<<"\n";
}
for(a=0;a<=1;a++)
{
for(b=0;b<=1;b++)
{
matrix3[a][b]=matrix1[a][b]+matrix2[a][b];
}
} cout<<"\hasil (penjumlahan)\n";
for(a=0;a<=1;a++)
{
for(b=0;b<=1;b++)
{
cout<<matrix3[a][b];
}
cout<<"\n";
}
getch();
}
| 15.080645 | 69 | 0.435294 | ikamei15 |
02ed89884a3cda0aec7a5d1455a1b7e142769d0f | 1,413 | cpp | C++ | Source/PyramidMath/SupplyContainer.cpp | andriuchap/summer-ue4jam-2019 | 125a67cffe6b98d5d6a04b762a07e2c75256d86b | [
"Apache-2.0"
] | null | null | null | Source/PyramidMath/SupplyContainer.cpp | andriuchap/summer-ue4jam-2019 | 125a67cffe6b98d5d6a04b762a07e2c75256d86b | [
"Apache-2.0"
] | null | null | null | Source/PyramidMath/SupplyContainer.cpp | andriuchap/summer-ue4jam-2019 | 125a67cffe6b98d5d6a04b762a07e2c75256d86b | [
"Apache-2.0"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "SupplyContainer.h"
#include "PyramidMathCharacter.h"
#include "Components/StaticMeshComponent.h"
#include "Components/BoxComponent.h"
ASupplyContainer::ASupplyContainer(const FObjectInitializer& ObjInitializer)
{
bIsLooted = false;
SupplyMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("SupplyMesh"));
RootComponent = SupplyMesh;
SupplyMesh->SetCollisionProfileName(FName("NoCollision"));
InteractionBox = CreateDefaultSubobject<UBoxComponent>(TEXT("InteractionBox"));
InteractionBox->SetupAttachment(SupplyMesh);
InteractionBox->SetCollisionProfileName(FName("OverlapAllDynamic"));
InteractionBox->SetGenerateOverlapEvents(true);
}
bool ASupplyContainer::IsInteractableComponent(UPrimitiveComponent * InOverlappedComponent)
{
return true;
}
bool ASupplyContainer::CanInteract(APyramidMathCharacter * InCharacter)
{
return !bIsLooted;
}
bool ASupplyContainer::Interact(APyramidMathCharacter * InCharacter)
{
bIsLooted = true;
if (InCharacter)
{
InCharacter->AddAmmo(ContainedAmmo);
InCharacter->AddHealth(ContainedHealth);
InCharacter->AddTorchFuel(ContainedTorchFuel);
}
OnLooted();
return true;
}
FText ASupplyContainer::GetInteractionName()
{
return NSLOCTEXT("PyramidMath", "INTERACTION_SEARCH_SUPPLIES", "Search");
}
void ASupplyContainer::BeginPlay()
{
Super::BeginPlay();
} | 26.166667 | 91 | 0.801132 | andriuchap |
02f0a4cb8b9c54b99df844cb8231e3c485341e14 | 351 | hpp | C++ | src/graphics/graphics.hpp | otgaard/zap | d50e70b5baf5f0fbf7a5a98d80c4d1bcc6166215 | [
"MIT"
] | 8 | 2016-04-24T21:02:59.000Z | 2021-11-14T20:37:17.000Z | src/graphics/graphics.hpp | otgaard/zap | d50e70b5baf5f0fbf7a5a98d80c4d1bcc6166215 | [
"MIT"
] | null | null | null | src/graphics/graphics.hpp | otgaard/zap | d50e70b5baf5f0fbf7a5a98d80c4d1bcc6166215 | [
"MIT"
] | 1 | 2018-06-09T19:51:38.000Z | 2018-06-09T19:51:38.000Z | //
// Created by otgaard on 2018/02/11.
//
#ifndef ZAP_GRAPHICS_HPP
#define ZAP_GRAPHICS_HPP
#if defined(_WIN32)
#if !defined(GRAPHICS_EXPORT)
#if defined(ZAP_STATIC)
#include "graphics_exports_s.h"
#else
#include "graphics_exports.h"
#endif
#else
#include GRAPHICS_EXPORT
#endif
#else
#define ZAPGRAPHICS_EXPORT
#endif
#endif //ZAP_GRAPHICS_HPP
| 14.04 | 36 | 0.774929 | otgaard |
02f5254cf6f71a05d3b3d24f8df09ae7257af5d6 | 1,259 | cpp | C++ | test/data-tests/testcases/test-101.cpp | zhaitianduo/libosmium | 42fc3238f942baac47d8520425664376478718b1 | [
"BSL-1.0"
] | 4,526 | 2015-01-01T15:31:00.000Z | 2022-03-31T17:33:49.000Z | test/data-tests/testcases/test-101.cpp | zhaitianduo/libosmium | 42fc3238f942baac47d8520425664376478718b1 | [
"BSL-1.0"
] | 4,497 | 2015-01-01T15:29:12.000Z | 2022-03-31T19:19:35.000Z | test/data-tests/testcases/test-101.cpp | zhaitianduo/libosmium | 42fc3238f942baac47d8520425664376478718b1 | [
"BSL-1.0"
] | 3,023 | 2015-01-01T18:40:53.000Z | 2022-03-30T13:30:46.000Z |
#include <stdexcept>
#include "common.hpp"
class TestHandler101 : public osmium::handler::Handler {
public:
TestHandler101() :
osmium::handler::Handler() {
}
void node(const osmium::Node& node) const {
constexpr const double epsilon = 0.00000001;
if (node.id() == 101000) {
REQUIRE(node.version() == 1);
REQUIRE(node.location().lon() == Approx(1.12).epsilon(epsilon));
REQUIRE(node.location().lat() == Approx(1.02).epsilon(epsilon));
} else if (node.id() == 101001) {
REQUIRE(node.version() == 1);
REQUIRE(node.location().lon() == Approx(1.12).epsilon(epsilon));
REQUIRE(node.location().lat() == Approx(1.03).epsilon(epsilon));
} else if (node.id() == 101002) {
} else if (node.id() == 101003) {
} else {
throw std::runtime_error{"Unknown ID"};
}
}
}; // class TestHandler101
TEST_CASE("101") {
osmium::io::Reader reader{dirname + "/1/101/data.osm"};
CheckBasicsHandler check_basics_handler{101, 4, 0, 0};
CheckWKTHandler check_wkt_handler{dirname, 101};
TestHandler101 test_handler;
osmium::apply(reader, check_basics_handler, check_wkt_handler, test_handler);
}
| 29.27907 | 81 | 0.597299 | zhaitianduo |
02fa59699466b1edc0b01eaa013012d0141b6164 | 12,994 | cpp | C++ | Modules/Classification/CLMiniApps/CLVoxelFeatures.cpp | samsmu/MITK | c93dce6dc38d8f4c961de4440e4dd113b9841c8c | [
"BSD-3-Clause"
] | 5 | 2015-02-05T10:58:41.000Z | 2019-04-17T15:04:07.000Z | Modules/Classification/CLMiniApps/CLVoxelFeatures.cpp | kometa-dev/MITK | 984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d | [
"BSD-3-Clause"
] | 141 | 2015-03-03T06:52:01.000Z | 2020-12-10T07:28:14.000Z | Modules/Classification/CLMiniApps/CLVoxelFeatures.cpp | kometa-dev/MITK | 984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d | [
"BSD-3-Clause"
] | 4 | 2015-02-19T06:48:13.000Z | 2020-06-19T16:20:25.000Z | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef mitkCLVoxeFeatures_cpp
#define mitkCLVoxeFeatures_cpp
#include "time.h"
#include <sstream>
#include <fstream>
#include <mitkIOUtil.h>
#include <mitkImageAccessByItk.h>
#include <mitkImageCast.h>
#include "mitkCommandLineParser.h"
#include <mitkGIFCooccurenceMatrix.h>
#include <mitkGIFGrayLevelRunLength.h>
#include "itkDiscreteGaussianImageFilter.h"
#include <itkLaplacianRecursiveGaussianImageFilter.h>
#include "itkHessianRecursiveGaussianImageFilter.h"
#include "itkUnaryFunctorImageFilter.h"
#include <itkMultiHistogramFilter.h>
#include "vnl/algo/vnl_symmetric_eigensystem.h"
#include <itkSubtractImageFilter.h>
static std::vector<double> splitDouble(std::string str, char delimiter) {
std::vector<double> internal;
std::stringstream ss(str); // Turn the string into a stream.
std::string tok;
double val;
while (std::getline(ss, tok, delimiter)) {
std::stringstream s2(tok);
s2 >> val;
internal.push_back(val);
}
return internal;
}
namespace Functor
{
template <class TInput, class TOutput>
class MatrixFirstEigenvalue
{
public:
MatrixFirstEigenvalue() {}
virtual ~MatrixFirstEigenvalue() {}
int order;
inline TOutput operator ()(const TInput& input)
{
double a,b,c;
if (input[0] < 0.01 && input[1] < 0.01 &&input[2] < 0.01 &&input[3] < 0.01 &&input[4] < 0.01 &&input[5] < 0.01)
return 0;
vnl_symmetric_eigensystem_compute_eigenvals(input[0], input[1],input[2],input[3],input[4],input[5],a,b,c);
switch (order)
{
case 0: return a;
case 1: return b;
case 2: return c;
default: return a;
}
}
bool operator !=(const MatrixFirstEigenvalue) const
{
return false;
}
bool operator ==(const MatrixFirstEigenvalue& other) const
{
return !(*this != other);
}
};
}
template<typename TPixel, unsigned int VImageDimension>
void
GaussianFilter(itk::Image<TPixel, VImageDimension>* itkImage, double variance, mitk::Image::Pointer &output)
{
typedef itk::Image<TPixel, VImageDimension> ImageType;
typedef itk::DiscreteGaussianImageFilter< ImageType, ImageType > GaussFilterType;
typename GaussFilterType::Pointer gaussianFilter = GaussFilterType::New();
gaussianFilter->SetInput( itkImage );
gaussianFilter->SetVariance(variance);
gaussianFilter->Update();
mitk::CastToMitkImage(gaussianFilter->GetOutput(), output);
}
template<typename TPixel, unsigned int VImageDimension>
void
DifferenceOfGaussFilter(itk::Image<TPixel, VImageDimension>* itkImage, double variance, mitk::Image::Pointer &output)
{
typedef itk::Image<TPixel, VImageDimension> ImageType;
typedef itk::DiscreteGaussianImageFilter< ImageType, ImageType > GaussFilterType;
typedef itk::SubtractImageFilter<ImageType, ImageType, ImageType> SubFilterType;
typename GaussFilterType::Pointer gaussianFilter1 = GaussFilterType::New();
gaussianFilter1->SetInput( itkImage );
gaussianFilter1->SetVariance(variance);
gaussianFilter1->Update();
typename GaussFilterType::Pointer gaussianFilter2 = GaussFilterType::New();
gaussianFilter2->SetInput( itkImage );
gaussianFilter2->SetVariance(variance*0.66*0.66);
gaussianFilter2->Update();
typename SubFilterType::Pointer subFilter = SubFilterType::New();
subFilter->SetInput1(gaussianFilter1->GetOutput());
subFilter->SetInput2(gaussianFilter2->GetOutput());
subFilter->Update();
mitk::CastToMitkImage(subFilter->GetOutput(), output);
}
template<typename TPixel, unsigned int VImageDimension>
void
LaplacianOfGaussianFilter(itk::Image<TPixel, VImageDimension>* itkImage, double variance, mitk::Image::Pointer &output)
{
typedef itk::Image<TPixel, VImageDimension> ImageType;
typedef itk::DiscreteGaussianImageFilter< ImageType, ImageType > GaussFilterType;
typedef itk::LaplacianRecursiveGaussianImageFilter<ImageType, ImageType> LaplacianFilter;
typename GaussFilterType::Pointer gaussianFilter = GaussFilterType::New();
gaussianFilter->SetInput( itkImage );
gaussianFilter->SetVariance(variance);
gaussianFilter->Update();
typename LaplacianFilter::Pointer laplaceFilter = LaplacianFilter::New();
laplaceFilter->SetInput(gaussianFilter->GetOutput());
laplaceFilter->Update();
mitk::CastToMitkImage(laplaceFilter->GetOutput(), output);
}
template<typename TPixel, unsigned int VImageDimension>
void
HessianOfGaussianFilter(itk::Image<TPixel, VImageDimension>* itkImage, double variance, std::vector<mitk::Image::Pointer> &out)
{
typedef itk::Image<TPixel, VImageDimension> ImageType;
typedef itk::Image<double, VImageDimension> FloatImageType;
typedef itk::HessianRecursiveGaussianImageFilter <ImageType> HessianFilterType;
typedef typename HessianFilterType::OutputImageType VectorImageType;
typedef Functor::MatrixFirstEigenvalue<typename VectorImageType::PixelType, double> DeterminantFunctorType;
typedef itk::UnaryFunctorImageFilter<VectorImageType, FloatImageType, DeterminantFunctorType> DetFilterType;
typename HessianFilterType::Pointer hessianFilter = HessianFilterType::New();
hessianFilter->SetInput(itkImage);
hessianFilter->SetSigma(std::sqrt(variance));
for (int i = 0; i < VImageDimension; ++i)
{
typename DetFilterType::Pointer detFilter = DetFilterType::New();
detFilter->SetInput(hessianFilter->GetOutput());
detFilter->GetFunctor().order = i;
detFilter->Update();
mitk::CastToMitkImage(detFilter->GetOutput(), out[i]);
}
}
template<typename TPixel, unsigned int VImageDimension>
void
LocalHistograms(itk::Image<TPixel, VImageDimension>* itkImage, std::vector<mitk::Image::Pointer> &out, double offset, double delta)
{
typedef itk::Image<TPixel, VImageDimension> ImageType;
typedef itk::Image<double, VImageDimension> FloatImageType;
typedef itk::MultiHistogramFilter <ImageType,ImageType> MultiHistogramType;
typename MultiHistogramType::Pointer filter = MultiHistogramType::New();
filter->SetInput(itkImage);
filter->SetOffset(offset);
filter->SetDelta(delta);
filter->Update();
for (int i = 0; i < VImageDimension; ++i)
{
mitk::Image::Pointer img = mitk::Image::New();
mitk::CastToMitkImage(filter->GetOutput(), img);
out.push_back(img);
}
}
int main(int argc, char* argv[])
{
mitkCommandLineParser parser;
parser.setArgumentPrefix("--", "-");
// required params
parser.addArgument("image", "i", mitkCommandLineParser::InputImage, "Input Image", "Path to the input VTK polydata", us::Any(), false);
parser.addArgument("output", "o", mitkCommandLineParser::OutputFile, "Output text file", "Target file. The output statistic is appended to this file.", us::Any(), false);
parser.addArgument("gaussian","g",mitkCommandLineParser::String, "Gaussian Filtering of the input images", "Gaussian Filter. Followed by the used variances seperated by ';' ",us::Any());
parser.addArgument("difference-of-gaussian","dog",mitkCommandLineParser::String, "Difference of Gaussian Filtering of the input images", "Difference of Gaussian Filter. Followed by the used variances seperated by ';' ",us::Any());
parser.addArgument("laplace-of-gauss","log",mitkCommandLineParser::String, "Laplacian of Gaussian Filtering", "Laplacian of Gaussian Filter. Followed by the used variances seperated by ';' ",us::Any());
parser.addArgument("hessian-of-gauss","hog",mitkCommandLineParser::String, "Hessian of Gaussian Filtering", "Hessian of Gaussian Filter. Followed by the used variances seperated by ';' ",us::Any());
parser.addArgument("local-histogram", "lh", mitkCommandLineParser::String, "Local Histograms", "Calculate the local histogram based feature. Specify Offset and Delta, for exampel -3;0.6 ", us::Any());
// Miniapp Infos
parser.setCategory("Classification Tools");
parser.setTitle("Global Image Feature calculator");
parser.setDescription("Calculates different global statistics for a given segmentation / image combination");
parser.setContributor("MBI");
std::map<std::string, us::Any> parsedArgs = parser.parseArguments(argc, argv);
if (parsedArgs.size()==0)
{
return EXIT_FAILURE;
}
if ( parsedArgs.count("help") || parsedArgs.count("h"))
{
return EXIT_SUCCESS;
}
bool useCooc = parsedArgs.count("cooccurence");
mitk::Image::Pointer image = mitk::IOUtil::LoadImage(parsedArgs["image"].ToString());
std::string filename=parsedArgs["output"].ToString();
////////////////////////////////////////////////////////////////
// CAlculate Gaussian Features
////////////////////////////////////////////////////////////////
MITK_INFO << "Check for Local Histogram...";
if (parsedArgs.count("local-histogram"))
{
std::vector<mitk::Image::Pointer> outs;
auto ranges = splitDouble(parsedArgs["local-histogram"].ToString(), ';');
if (ranges.size() < 2)
{
MITK_INFO << "Missing Delta and Offset for Local Histogram";
}
else
{
AccessByItk_3(image, LocalHistograms, outs, ranges[0], ranges[1]);
for (int i = 0; i < outs.size(); ++i)
{
std::string name = filename + "-lh" + us::any_value_to_string<int>(i)+".nii.gz";
mitk::IOUtil::SaveImage(outs[i], name);
}
}
}
////////////////////////////////////////////////////////////////
// CAlculate Gaussian Features
////////////////////////////////////////////////////////////////
MITK_INFO << "Check for Gaussian...";
if (parsedArgs.count("gaussian"))
{
MITK_INFO << "Calculate Gaussian... " << parsedArgs["gaussian"].ToString();
auto ranges = splitDouble(parsedArgs["gaussian"].ToString(),';');
for (int i = 0; i < ranges.size(); ++i)
{
mitk::Image::Pointer output;
AccessByItk_2(image, GaussianFilter, ranges[i], output);
std::string name = filename + "-gaussian-" + us::any_value_to_string(ranges[i])+".nii.gz";
mitk::IOUtil::SaveImage(output, name);
}
}
////////////////////////////////////////////////////////////////
// CAlculate Difference of Gaussian Features
////////////////////////////////////////////////////////////////
MITK_INFO << "Check for DoG...";
if (parsedArgs.count("difference-of-gaussian"))
{
MITK_INFO << "Calculate Difference of Gaussian... " << parsedArgs["difference-of-gaussian"].ToString();
auto ranges = splitDouble(parsedArgs["difference-of-gaussian"].ToString(),';');
for (int i = 0; i < ranges.size(); ++i)
{
mitk::Image::Pointer output;
AccessByItk_2(image, DifferenceOfGaussFilter, ranges[i], output);
std::string name = filename + "-dog-" + us::any_value_to_string(ranges[i])+".nii.gz";
mitk::IOUtil::SaveImage(output, name);
}
}
MITK_INFO << "Check for LoG...";
////////////////////////////////////////////////////////////////
// CAlculate Laplacian Of Gauss Features
////////////////////////////////////////////////////////////////
if (parsedArgs.count("laplace-of-gauss"))
{
MITK_INFO << "Calculate LoG... " << parsedArgs["laplace-of-gauss"].ToString();
auto ranges = splitDouble(parsedArgs["laplace-of-gauss"].ToString(),';');
for (int i = 0; i < ranges.size(); ++i)
{
mitk::Image::Pointer output;
AccessByItk_2(image, LaplacianOfGaussianFilter, ranges[i], output);
std::string name = filename + "-log-" + us::any_value_to_string(ranges[i])+".nii.gz";
mitk::IOUtil::SaveImage(output, name);
}
}
MITK_INFO << "Check for HoG...";
////////////////////////////////////////////////////////////////
// CAlculate Hessian Of Gauss Features
////////////////////////////////////////////////////////////////
if (parsedArgs.count("hessian-of-gauss"))
{
MITK_INFO << "Calculate HoG... " << parsedArgs["hessian-of-gauss"].ToString();
auto ranges = splitDouble(parsedArgs["hessian-of-gauss"].ToString(),';');
for (int i = 0; i < ranges.size(); ++i)
{
std::vector<mitk::Image::Pointer> outs;
outs.push_back(mitk::Image::New());
outs.push_back(mitk::Image::New());
outs.push_back(mitk::Image::New());
AccessByItk_2(image, HessianOfGaussianFilter, ranges[i], outs);
std::string name = filename + "-hog0-" + us::any_value_to_string(ranges[i])+".nii.gz";
mitk::IOUtil::SaveImage(outs[0], name);
name = filename + "-hog1-" + us::any_value_to_string(ranges[i])+".nii.gz";
mitk::IOUtil::SaveImage(outs[1], name);
name = filename + "-hog2-" + us::any_value_to_string(ranges[i])+".nii.gz";
mitk::IOUtil::SaveImage(outs[2], name);
}
}
return 0;
}
#endif | 39.615854 | 232 | 0.667693 | samsmu |
02fc0bb1c3985caa2abc873795acae251811786d | 22,561 | cpp | C++ | TouchGFX/target/HW_Init.cpp | argandas/STM32F746G-DISCO_TouchGFX_Demo-Graph | 0375fad81b314bd1b9ec8f9101b51ac077d5ea81 | [
"MIT"
] | 3 | 2019-12-30T21:16:50.000Z | 2021-05-11T05:28:25.000Z | TouchGFX/target/HW_Init.cpp | argandas/STM32F746G-DISCO_TouchGFX_Demo-Graph | 0375fad81b314bd1b9ec8f9101b51ac077d5ea81 | [
"MIT"
] | null | null | null | TouchGFX/target/HW_Init.cpp | argandas/STM32F746G-DISCO_TouchGFX_Demo-Graph | 0375fad81b314bd1b9ec8f9101b51ac077d5ea81 | [
"MIT"
] | 1 | 2020-03-15T14:35:46.000Z | 2020-03-15T14:35:46.000Z | /**
******************************************************************************
* @file HW_Init.cpp
* @author MCD Application Team
* @version V1.0.0RC1
* @date 19-June-2017
* @brief This file implements the hardware configuration for the GUI library
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2016 STMicroelectronics International N.V.
* All rights reserved.</center></h2>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted, provided that the following conditions are met:
*
* 1. Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of other
* contributors to this software may be used to endorse or promote products
* derived from this software without specific written permission.
* 4. This software, including modifications and/or derivative works of this
* software, must execute solely and exclusively on microcontroller or
* microprocessor devices manufactured by or for STMicroelectronics.
* 5. Redistribution and use of this software other than as permitted under
* this license is void and will automatically terminate your rights under
* this license.
*
* THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
* RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
* SHALL STMICROELECTRONICS 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.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "HW_Init.hpp"
/* USER CODE BEGIN user includes */
/* USER CODE END user includes */
/** @addtogroup HARDWARE CONFIGURATION
* @{
*/
/** @defgroup HARDWARE CONFIGURATION_Private_Variables
* @{
*/
LTDC_HandleTypeDef hltdc;
DMA2D_HandleTypeDef hdma2d;
SDRAM_HandleTypeDef hsdram1;
#define REFRESH_COUNT 1835
#define SDRAM_TIMEOUT ((uint32_t)0xFFFF)
#define SDRAM_MODEREG_BURST_LENGTH_1 ((uint16_t)0x0000)
#define SDRAM_MODEREG_BURST_LENGTH_2 ((uint16_t)0x0001)
#define SDRAM_MODEREG_BURST_LENGTH_4 ((uint16_t)0x0002)
#define SDRAM_MODEREG_BURST_LENGTH_8 ((uint16_t)0x0004)
#define SDRAM_MODEREG_BURST_TYPE_SEQUENTIAL ((uint16_t)0x0000)
#define SDRAM_MODEREG_BURST_TYPE_INTERLEAVED ((uint16_t)0x0008)
#define SDRAM_MODEREG_CAS_LATENCY_2 ((uint16_t)0x0020)
#define SDRAM_MODEREG_CAS_LATENCY_3 ((uint16_t)0x0030)
#define SDRAM_MODEREG_OPERATING_MODE_STANDARD ((uint16_t)0x0000)
#define SDRAM_MODEREG_WRITEBURST_MODE_PROGRAMMED ((uint16_t)0x0000)
#define SDRAM_MODEREG_WRITEBURST_MODE_SINGLE ((uint16_t)0x0200)
static FMC_SDRAM_CommandTypeDef Command;
/**
* @brief Initialize the LCD Controller.
* @param LayerIndex : layer Index.
* @retval None
*/
void MX_LCD_Init(void)
{
LTDC_LayerCfgTypeDef pLayerCfg;
/* De-Initialize LTDC */
HAL_LTDC_DeInit(&hltdc);
/* Configure LTDC */
hltdc.Instance = LTDC;
hltdc.Init.HSPolarity = LTDC_HSPOLARITY_AL;
hltdc.Init.VSPolarity = LTDC_VSPOLARITY_AL;
hltdc.Init.DEPolarity = LTDC_DEPOLARITY_AL;
hltdc.Init.PCPolarity = LTDC_PCPOLARITY_IPC;
hltdc.Init.HorizontalSync = 40;
hltdc.Init.VerticalSync = 9;
hltdc.Init.AccumulatedHBP = 53;
hltdc.Init.AccumulatedVBP = 11;
hltdc.Init.AccumulatedActiveW = 533;
hltdc.Init.AccumulatedActiveH = 283;
hltdc.Init.TotalWidth = 565;
hltdc.Init.TotalHeigh = 285;
hltdc.Init.Backcolor.Blue = 0;
hltdc.Init.Backcolor.Green = 0;
hltdc.Init.Backcolor.Red = 0;
if (HAL_LTDC_Init(&hltdc) != HAL_OK)
{
Error_Handler();
}
pLayerCfg.WindowX0 = 0;
pLayerCfg.WindowX1 = 480;
pLayerCfg.WindowY0 = 0;
pLayerCfg.WindowY1 = 272;
pLayerCfg.PixelFormat = LTDC_PIXEL_FORMAT_RGB888;
pLayerCfg.Alpha = 255;
pLayerCfg.Alpha0 = 0;
pLayerCfg.BlendingFactor1 = LTDC_BLENDING_FACTOR1_PAxCA;
pLayerCfg.BlendingFactor2 = LTDC_BLENDING_FACTOR2_PAxCA;
pLayerCfg.FBStartAdress = 0xC0000000;
pLayerCfg.ImageWidth = 480;
pLayerCfg.ImageHeight = 272;
pLayerCfg.Backcolor.Blue = 0;
pLayerCfg.Backcolor.Green = 0;
pLayerCfg.Backcolor.Red = 0;
if (HAL_LTDC_ConfigLayer(&hltdc, &pLayerCfg, 0) != HAL_OK)
{
Error_Handler();
}
HAL_LTDC_SetPitch(&hltdc, 480, 0);
}
/**
* @brief Initializes LCD IO.
*/
void MX_FMC_Init(void)
{
/* FMC initialization function */
FMC_SDRAM_TimingTypeDef SdramTiming;
/** Perform the SDRAM1 memory initialization sequence
*/
hsdram1.Instance = FMC_SDRAM_DEVICE;
/* hsdram1.Init */
hsdram1.Init.SDBank = FMC_SDRAM_BANK1;
hsdram1.Init.ColumnBitsNumber = FMC_SDRAM_COLUMN_BITS_NUM_8;
hsdram1.Init.RowBitsNumber = FMC_SDRAM_ROW_BITS_NUM_12;
hsdram1.Init.MemoryDataWidth = FMC_SDRAM_MEM_BUS_WIDTH_16;
hsdram1.Init.InternalBankNumber = FMC_SDRAM_INTERN_BANKS_NUM_4;
hsdram1.Init.CASLatency = FMC_SDRAM_CAS_LATENCY_3;
hsdram1.Init.WriteProtection = FMC_SDRAM_WRITE_PROTECTION_DISABLE;
hsdram1.Init.SDClockPeriod = FMC_SDRAM_CLOCK_PERIOD_2;
hsdram1.Init.ReadBurst = FMC_SDRAM_RBURST_ENABLE;
hsdram1.Init.ReadPipeDelay = FMC_SDRAM_RPIPE_DELAY_0;
/* SdramTiming */
SdramTiming.LoadToActiveDelay = 2;
SdramTiming.ExitSelfRefreshDelay = 7;
SdramTiming.SelfRefreshTime = 4;
SdramTiming.RowCycleDelay = 7;
SdramTiming.WriteRecoveryTime = 3;
SdramTiming.RPDelay = 2;
SdramTiming.RCDDelay = 2;
if (HAL_SDRAM_Init(&hsdram1, &SdramTiming) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief Programs the SDRAM device.
* @retval None
*/
void MX_SDRAM_InitEx(void)
{
__IO uint32_t tmpmrd = 0;
/* Step 1: Configure a clock configuration enable command */
Command.CommandMode = FMC_SDRAM_CMD_CLK_ENABLE;
Command.CommandTarget = FMC_SDRAM_CMD_TARGET_BANK1;
Command.AutoRefreshNumber = 1;
Command.ModeRegisterDefinition = 0;
/* Send the command */
HAL_SDRAM_SendCommand(&hsdram1, &Command, SDRAM_TIMEOUT);
/* Step 2: Insert 100 us minimum delay */
/* Inserted delay is equal to 1 ms due to systick time base unit (ms) */
HAL_Delay(1);
/* Step 3: Configure a PALL (precharge all) command */
Command.CommandMode = FMC_SDRAM_CMD_PALL;
Command.CommandTarget = FMC_SDRAM_CMD_TARGET_BANK1;
Command.AutoRefreshNumber = 1;
Command.ModeRegisterDefinition = 0;
/* Send the command */
HAL_SDRAM_SendCommand(&hsdram1, &Command, SDRAM_TIMEOUT);
/* Step 4: Configure an Auto Refresh command */
Command.CommandMode = FMC_SDRAM_CMD_AUTOREFRESH_MODE;
Command.CommandTarget = FMC_SDRAM_CMD_TARGET_BANK1;
Command.AutoRefreshNumber = 8;
Command.ModeRegisterDefinition = 0;
/* Send the command */
HAL_SDRAM_SendCommand(&hsdram1, &Command, SDRAM_TIMEOUT);
/* Step 5: Program the external memory mode register */
tmpmrd = (uint32_t)SDRAM_MODEREG_BURST_LENGTH_1 | \
SDRAM_MODEREG_BURST_TYPE_SEQUENTIAL | \
SDRAM_MODEREG_CAS_LATENCY_3 | \
SDRAM_MODEREG_OPERATING_MODE_STANDARD | \
SDRAM_MODEREG_WRITEBURST_MODE_SINGLE;
Command.CommandMode = FMC_SDRAM_CMD_LOAD_MODE;
Command.CommandTarget = FMC_SDRAM_CMD_TARGET_BANK1;
Command.AutoRefreshNumber = 1;
Command.ModeRegisterDefinition = tmpmrd;
/* Send the command */
HAL_SDRAM_SendCommand(&hsdram1, &Command, SDRAM_TIMEOUT);
/* Step 6: Set the refresh rate counter */
/* Set the device refresh rate */
HAL_SDRAM_ProgramRefreshRate(&hsdram1, REFRESH_COUNT);
}
/* DMA2D init function */
void MX_DMA2D_Init(void)
{
/* Configure the DMA2D default mode */
hdma2d.Instance = DMA2D;
hdma2d.Init.Mode = DMA2D_M2M;
hdma2d.Init.ColorMode = DMA2D_OUTPUT_ARGB8888;
hdma2d.Init.OutputOffset = 0;
hdma2d.LayerCfg[1].InputOffset = 0;
hdma2d.LayerCfg[1].InputColorMode = DMA2D_INPUT_ARGB8888;
hdma2d.LayerCfg[1].AlphaMode = DMA2D_NO_MODIF_ALPHA;
hdma2d.LayerCfg[1].InputAlpha = 0;
if (HAL_DMA2D_Init(&hdma2d) != HAL_OK)
{
Error_Handler();
}
if (HAL_DMA2D_ConfigLayer(&hdma2d, 1) != HAL_OK)
{
Error_Handler();
}
}
/* MSPInit/deInit Implementation */
void HAL_LTDC_MspInit(LTDC_HandleTypeDef* ltdcHandle)
{
GPIO_InitTypeDef GPIO_InitStruct;
if (ltdcHandle->Instance == LTDC)
{
/* USER CODE BEGIN LTDC_MspInit 0 */
/* USER CODE END LTDC_MspInit 0 */
/* Enable Peripheral clock */
__HAL_RCC_LTDC_CLK_ENABLE();
/**LTDC GPIO Configuration
PE4 ------> LTDC_B0
PJ13 ------> LTDC_B1
PK7 ------> LTDC_DE
PK6 ------> LTDC_B7
PK5 ------> LTDC_B6
PG12 ------> LTDC_B4
PJ14 ------> LTDC_B2
PI10 ------> LTDC_HSYNC
PK4 ------> LTDC_B5
PJ15 ------> LTDC_B3
PI9 ------> LTDC_VSYNC
PK1 ------> LTDC_G6
PK2 ------> LTDC_G7
PI15 ------> LTDC_R0
PJ11 ------> LTDC_G4
PK0 ------> LTDC_G5
PI14 ------> LTDC_CLK
PJ8 ------> LTDC_G1
PJ10 ------> LTDC_G3
PJ7 ------> LTDC_G0
PJ9 ------> LTDC_G2
PJ6 ------> LTDC_R7
PJ4 ------> LTDC_R5
PJ5 ------> LTDC_R6
PJ3 ------> LTDC_R4
PJ2 ------> LTDC_R3
PJ0 ------> LTDC_R1
PJ1 ------> LTDC_R2
*/
GPIO_InitStruct.Pin = LCD_B0_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF14_LTDC;
HAL_GPIO_Init(LCD_B0_GPIO_Port, &GPIO_InitStruct);
GPIO_InitStruct.Pin = LCD_B1_Pin | LCD_B2_Pin | LCD_B3_Pin | LCD_G4_Pin
| LCD_G1_Pin | LCD_G3_Pin | LCD_G0_Pin | LCD_G2_Pin
| LCD_R7_Pin | LCD_R5_Pin | LCD_R6_Pin | LCD_R4_Pin
| LCD_R3_Pin | LCD_R1_Pin | LCD_R2_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF14_LTDC;
HAL_GPIO_Init(GPIOJ, &GPIO_InitStruct);
GPIO_InitStruct.Pin = LCD_DE_Pin | LCD_B7_Pin | LCD_B6_Pin | LCD_B5_Pin
| LCD_G6_Pin | LCD_G7_Pin | LCD_G5_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF14_LTDC;
HAL_GPIO_Init(GPIOK, &GPIO_InitStruct);
GPIO_InitStruct.Pin = LCD_B4_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF9_LTDC;
HAL_GPIO_Init(LCD_B4_GPIO_Port, &GPIO_InitStruct);
GPIO_InitStruct.Pin = LCD_HSYNC_Pin | LCD_VSYNC_Pin | LCD_R0_Pin | LCD_CLK_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Alternate = GPIO_AF14_LTDC;
HAL_GPIO_Init(GPIOI, &GPIO_InitStruct);
/* Peripheral interrupt init */
HAL_NVIC_SetPriority(LTDC_IRQn, 5, 0);
HAL_NVIC_EnableIRQ(LTDC_IRQn);
/* USER CODE BEGIN LTDC_MspInit 1 */
/* USER CODE END LTDC_MspInit 1 */
}
}
void HAL_LTDC_MspDeInit(LTDC_HandleTypeDef* ltdcHandle)
{
if (ltdcHandle->Instance == LTDC)
{
/* USER CODE BEGIN LTDC_MspDeInit 0 */
/* USER CODE END LTDC_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_LTDC_CLK_DISABLE();
/**LTDC GPIO Configuration
PE4 ------> LTDC_B0
PJ13 ------> LTDC_B1
PK7 ------> LTDC_DE
PK6 ------> LTDC_B7
PK5 ------> LTDC_B6
PG12 ------> LTDC_B4
PJ14 ------> LTDC_B2
PI10 ------> LTDC_HSYNC
PK4 ------> LTDC_B5
PJ15 ------> LTDC_B3
PI9 ------> LTDC_VSYNC
PK1 ------> LTDC_G6
PK2 ------> LTDC_G7
PI15 ------> LTDC_R0
PJ11 ------> LTDC_G4
PK0 ------> LTDC_G5
PI14 ------> LTDC_CLK
PJ8 ------> LTDC_G1
PJ10 ------> LTDC_G3
PJ7 ------> LTDC_G0
PJ9 ------> LTDC_G2
PJ6 ------> LTDC_R7
PJ4 ------> LTDC_R5
PJ5 ------> LTDC_R6
PJ3 ------> LTDC_R4
PJ2 ------> LTDC_R3
PJ0 ------> LTDC_R1
PJ1 ------> LTDC_R2
*/
HAL_GPIO_DeInit(LCD_B0_GPIO_Port, LCD_B0_Pin);
HAL_GPIO_DeInit(GPIOJ, LCD_B1_Pin | LCD_B2_Pin | LCD_B3_Pin | LCD_G4_Pin
| LCD_G1_Pin | LCD_G3_Pin | LCD_G0_Pin | LCD_G2_Pin
| LCD_R7_Pin | LCD_R5_Pin | LCD_R6_Pin | LCD_R4_Pin
| LCD_R3_Pin | LCD_R1_Pin | LCD_R2_Pin);
HAL_GPIO_DeInit(GPIOK, LCD_DE_Pin | LCD_B7_Pin | LCD_B6_Pin | LCD_B5_Pin
| LCD_G6_Pin | LCD_G7_Pin | LCD_G5_Pin);
HAL_GPIO_DeInit(LCD_B4_GPIO_Port, LCD_B4_Pin);
HAL_GPIO_DeInit(GPIOI, LCD_HSYNC_Pin | LCD_VSYNC_Pin | LCD_R0_Pin | LCD_CLK_Pin);
/* Peripheral interrupt Deinit*/
HAL_NVIC_DisableIRQ(LTDC_IRQn);
/* USER CODE BEGIN LTDC_MspDeInit 1 */
/* USER CODE END LTDC_MspDeInit 1 */
}
}
static uint32_t FMC_Initialized = 0;
static void HAL_FMC_MspInit(void)
{
/* USER CODE BEGIN FMC_MspInit 0 */
/* USER CODE END FMC_MspInit 0 */
GPIO_InitTypeDef GPIO_InitStruct;
if (FMC_Initialized)
{
return;
}
FMC_Initialized = 1;
/* Peripheral clock enable */
__HAL_RCC_FMC_CLK_ENABLE();
/** FMC GPIO Configuration
PE1 ------> FMC_NBL1
PE0 ------> FMC_NBL0
PG15 ------> FMC_SDNCAS
PD0 ------> FMC_D2
PD1 ------> FMC_D3
PF0 ------> FMC_A0
PF1 ------> FMC_A1
PF2 ------> FMC_A2
PF3 ------> FMC_A3
PG8 ------> FMC_SDCLK
PF4 ------> FMC_A4
PH5 ------> FMC_SDNWE
PH3 ------> FMC_SDNE0
PF5 ------> FMC_A5
PD15 ------> FMC_D1
PD10 ------> FMC_D15
PC3 ------> FMC_SDCKE0
PD14 ------> FMC_D0
PD9 ------> FMC_D14
PD8 ------> FMC_D13
PF12 ------> FMC_A6
PG1 ------> FMC_A11
PF15 ------> FMC_A9
PF13 ------> FMC_A7
PG0 ------> FMC_A10
PE8 ------> FMC_D5
PG5 ------> FMC_BA1
PG4 ------> FMC_BA0
PF14 ------> FMC_A8
PF11 ------> FMC_SDNRAS
PE9 ------> FMC_D6
PE11 ------> FMC_D8
PE14 ------> FMC_D11
PE7 ------> FMC_D4
PE10 ------> FMC_D7
PE12 ------> FMC_D9
PE15 ------> FMC_D12
PE13 ------> FMC_D10
*/
GPIO_InitStruct.Pin = FMC_NBL1_Pin | FMC_NBL0_Pin | FMC_D5_Pin | FMC_D6_Pin
| FMC_D8_Pin | FMC_D11_Pin | FMC_D4_Pin | FMC_D7_Pin
| FMC_D9_Pin | FMC_D12_Pin | FMC_D10_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF12_FMC;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
GPIO_InitStruct.Pin = FMC_SDNCAS_Pin | FMC_SDCLK_Pin | FMC_A11_Pin | FMC_A10_Pin
| FMC_BA1_Pin | FMC_BA0_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF12_FMC;
HAL_GPIO_Init(GPIOG, &GPIO_InitStruct);
GPIO_InitStruct.Pin = FMC_D2_Pin | FMC_D3_Pin | FMC_D1_Pin | FMC_D15_Pin
| FMC_D0_Pin | FMC_D14_Pin | FMC_D13_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF12_FMC;
HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
GPIO_InitStruct.Pin = FMC_A0_Pin | FMC_A1_Pin | FMC_A2_Pin | FMC_A3_Pin
| FMC_A4_Pin | FMC_A5_Pin | FMC_A6_Pin | FMC_A9_Pin
| FMC_A7_Pin | FMC_A8_Pin | FMC_SDNRAS_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF12_FMC;
HAL_GPIO_Init(GPIOF, &GPIO_InitStruct);
GPIO_InitStruct.Pin = FMC_SDNME_Pin | FMC_SDNE0_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF12_FMC;
HAL_GPIO_Init(GPIOH, &GPIO_InitStruct);
GPIO_InitStruct.Pin = FMC_SDCKE0_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF12_FMC;
HAL_GPIO_Init(FMC_SDCKE0_GPIO_Port, &GPIO_InitStruct);
/* USER CODE BEGIN FMC_MspInit 1 */
/* USER CODE END FMC_MspInit 1 */
}
void HAL_SDRAM_MspInit(SDRAM_HandleTypeDef* hsdram)
{
/* USER CODE BEGIN SDRAM_MspInit 0 */
/* USER CODE END SDRAM_MspInit 0 */
HAL_FMC_MspInit();
/* USER CODE BEGIN SDRAM_MspInit 1 */
/* USER CODE END SDRAM_MspInit 1 */
}
static uint32_t FMC_DeInitialized = 0;
static void HAL_FMC_MspDeInit(void)
{
/* USER CODE BEGIN FMC_MspDeInit 0 */
/* USER CODE END FMC_MspDeInit 0 */
if (FMC_DeInitialized)
{
return;
}
FMC_DeInitialized = 1;
/* Peripheral clock enable */
__HAL_RCC_FMC_CLK_DISABLE();
/** FMC GPIO Configuration
PE1 ------> FMC_NBL1
PE0 ------> FMC_NBL0
PG15 ------> FMC_SDNCAS
PD0 ------> FMC_D2
PD1 ------> FMC_D3
PF0 ------> FMC_A0
PF1 ------> FMC_A1
PF2 ------> FMC_A2
PF3 ------> FMC_A3
PG8 ------> FMC_SDCLK
PF4 ------> FMC_A4
PH5 ------> FMC_SDNWE
PH3 ------> FMC_SDNE0
PF5 ------> FMC_A5
PD15 ------> FMC_D1
PD10 ------> FMC_D15
PC3 ------> FMC_SDCKE0
PD14 ------> FMC_D0
PD9 ------> FMC_D14
PD8 ------> FMC_D13
PF12 ------> FMC_A6
PG1 ------> FMC_A11
PF15 ------> FMC_A9
PF13 ------> FMC_A7
PG0 ------> FMC_A10
PE8 ------> FMC_D5
PG5 ------> FMC_BA1
PG4 ------> FMC_BA0
PF14 ------> FMC_A8
PF11 ------> FMC_SDNRAS
PE9 ------> FMC_D6
PE11 ------> FMC_D8
PE14 ------> FMC_D11
PE7 ------> FMC_D4
PE10 ------> FMC_D7
PE12 ------> FMC_D9
PE15 ------> FMC_D12
PE13 ------> FMC_D10
*/
HAL_GPIO_DeInit(GPIOE, FMC_NBL1_Pin | FMC_NBL0_Pin | FMC_D5_Pin | FMC_D6_Pin
| FMC_D8_Pin | FMC_D11_Pin | FMC_D4_Pin | FMC_D7_Pin
| FMC_D9_Pin | FMC_D12_Pin | FMC_D10_Pin);
HAL_GPIO_DeInit(GPIOG, FMC_SDNCAS_Pin | FMC_SDCLK_Pin | FMC_A11_Pin | FMC_A10_Pin
| FMC_BA1_Pin | FMC_BA0_Pin);
HAL_GPIO_DeInit(GPIOD, FMC_D2_Pin | FMC_D3_Pin | FMC_D1_Pin | FMC_D15_Pin
| FMC_D0_Pin | FMC_D14_Pin | FMC_D13_Pin);
HAL_GPIO_DeInit(GPIOF, FMC_A0_Pin | FMC_A1_Pin | FMC_A2_Pin | FMC_A3_Pin
| FMC_A4_Pin | FMC_A5_Pin | FMC_A6_Pin | FMC_A9_Pin
| FMC_A7_Pin | FMC_A8_Pin | FMC_SDNRAS_Pin);
HAL_GPIO_DeInit(GPIOH, FMC_SDNME_Pin | FMC_SDNE0_Pin);
HAL_GPIO_DeInit(FMC_SDCKE0_GPIO_Port, FMC_SDCKE0_Pin);
/* USER CODE BEGIN FMC_MspDeInit 1 */
/* USER CODE END FMC_MspDeInit 1 */
}
void HAL_SDRAM_MspDeInit(SDRAM_HandleTypeDef* hsdram)
{
/* USER CODE BEGIN SDRAM_MspDeInit 0 */
/* USER CODE END SDRAM_MspDeInit 0 */
HAL_FMC_MspDeInit();
/* USER CODE BEGIN SDRAM_MspDeInit 1 */
/* USER CODE END SDRAM_MspDeInit 1 */
}
void HAL_DMA2D_MspInit(DMA2D_HandleTypeDef* dma2dHandle)
{
if (dma2dHandle->Instance == DMA2D)
{
/* USER CODE BEGIN DMA2D_MspInit 0 */
/* USER CODE END DMA2D_MspInit 0 */
/* Enable Peripheral clock */
__HAL_RCC_DMA2D_CLK_ENABLE();
/* Peripheral interrupt init */
HAL_NVIC_SetPriority(DMA2D_IRQn, 5, 0);
HAL_NVIC_EnableIRQ(DMA2D_IRQn);
/* USER CODE BEGIN DMA2D_MspInit 1 */
/* USER CODE END DMA2D_MspInit 1 */
}
}
void HAL_DMA2D_MspDeInit(DMA2D_HandleTypeDef* dma2dHandle)
{
if (dma2dHandle->Instance == DMA2D)
{
/* USER CODE BEGIN DMA2D_MspDeInit 0 */
/* USER CODE END DMA2D_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_DMA2D_CLK_DISABLE();
/* Peripheral interrupt Deinit*/
HAL_NVIC_DisableIRQ(DMA2D_IRQn);
/* USER CODE BEGIN DMA2D_MspDeInit 1 */
/* USER CODE END DMA2D_MspDeInit 1 */
}
}
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| 33.723468 | 89 | 0.621027 | argandas |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.