hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2cd047cb49cf95990ef36d087236e326539eca03 | 8,831 | cpp | C++ | kernels/plugins/dummy_tcp_stack/dummy_tcp_stack.cpp | TristanLaan/ACCL | 89b50a814c73571eb5c93d4c6a134328e3fa21c7 | [
"Apache-2.0"
] | null | null | null | kernels/plugins/dummy_tcp_stack/dummy_tcp_stack.cpp | TristanLaan/ACCL | 89b50a814c73571eb5c93d4c6a134328e3fa21c7 | [
"Apache-2.0"
] | null | null | null | kernels/plugins/dummy_tcp_stack/dummy_tcp_stack.cpp | TristanLaan/ACCL | 89b50a814c73571eb5c93d4c6a134328e3fa21c7 | [
"Apache-2.0"
] | null | null | null | # /*******************************************************************************
# Copyright (C) 2021 Xilinx, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# *******************************************************************************/
#include "ap_int.h"
#include "dummy_tcp_stack.h"
#include "Axi.h" //for axi::Stream
using namespace std;
#define DATA_WIDTH 512
#define DWIDTH512 512
#define DWIDTH128 128
#define DWIDTH64 64
#define DWIDTH32 32
#define DWIDTH16 16
#define DWIDTH8 8
typedef ap_axiu<DWIDTH512, 0, 0, 0> pkt512;
typedef ap_axiu<DWIDTH128, 0, 0, 0> pkt128;
typedef ap_axiu<DWIDTH64, 0, 0, 0> pkt64;
typedef ap_axiu<DWIDTH32, 0, 0, 0> pkt32;
typedef ap_axiu<DWIDTH16, 0, 0, 0> pkt16;
typedef ap_axiu<DWIDTH8, 0, 0, 0> pkt8;
void tx_handler (
STREAM<pkt32>& s_axis_tcp_tx_meta,
STREAM<stream_word>& s_axis_tcp_tx_data,
STREAM<pkt64>& m_axis_tcp_tx_status,
STREAM<stream_word>& out
){
#pragma HLS PIPELINE II=1 style=flp
#pragma HLS INLINE off
enum txFsmStateType {WAIT_META, WRITE_STATUS, TX_DATA};
static txFsmStateType txFsmState = WAIT_META;
static ap_uint<16> session = 0;
static ap_uint<16> length = 0;
static ap_uint<16> recvByte = 0;
switch(txFsmState)
{
case WAIT_META:
if (!STREAM_IS_EMPTY(s_axis_tcp_tx_meta))
{
pkt32 tx_meta_pkt = STREAM_READ(s_axis_tcp_tx_meta);
session = tx_meta_pkt.data(15,0);
length = tx_meta_pkt.data(31,16);
txFsmState = WRITE_STATUS;
}
break;
case WRITE_STATUS:
if (!STREAM_IS_FULL(m_axis_tcp_tx_status))
{
pkt64 tx_status_pkt;
tx_status_pkt.data(15,0) = session;
tx_status_pkt.data(31,16) = length;
tx_status_pkt.data(61,32) = 8000;
tx_status_pkt.data(63,62) = 0;
STREAM_WRITE(m_axis_tcp_tx_status, tx_status_pkt);
txFsmState = TX_DATA;
}
break;
case TX_DATA:
if (!STREAM_IS_EMPTY(s_axis_tcp_tx_data))
{
STREAM_WRITE(out, STREAM_READ(s_axis_tcp_tx_data));
recvByte = recvByte + 64;
if (recvByte >= length)
{
recvByte = 0;
txFsmState = WAIT_META;
}
}
break;
}//switch
}
void rx_handler(
STREAM<pkt128>& m_axis_tcp_notification,
STREAM<pkt32>& s_axis_tcp_read_pkg,
STREAM<pkt16>& m_axis_tcp_rx_meta,
STREAM<stream_word>& m_axis_tcp_rx_data,
STREAM<stream_word>& in
){
#pragma HLS PIPELINE II=1 style=flp
#pragma HLS INLINE off
#ifdef ACCL_SYNTHESIS
static hls::stream<hlslib::axi::Stream<ap_uint<DATA_WIDTH>, DEST_WIDTH> > rxDataBuffer;
#pragma HLS STREAM variable=rxDataBuffer depth=512
#else
static hlslib::Stream<hlslib::axi::Stream<ap_uint<DATA_WIDTH>, DEST_WIDTH>, 512> rxDataBuffer;
#endif
enum rxFsmStateType {BUFFER_DATA, SEND_NOTI, WAIT_REQ, SEND_MSG};
static rxFsmStateType rxFsmState = BUFFER_DATA;
static int msg_length = 0;
static int msg_session = 0;
stream_word currWord;
switch (rxFsmState)
{
case BUFFER_DATA:
if (!STREAM_IS_EMPTY(in)){
do {
#pragma HLS PIPELINE II=1
currWord = STREAM_READ(in);
STREAM_WRITE(rxDataBuffer, (hlslib::axi::Stream<ap_uint<DATA_WIDTH>, DEST_WIDTH>(currWord)));
for(int i=0; i<DATA_WIDTH/8; i++){
msg_length += currWord.keep(i,i);
}
} while(currWord.last == 0);
msg_session = currWord.dest;
rxFsmState = SEND_NOTI;
}
break;
case SEND_NOTI:
if (!STREAM_IS_FULL(m_axis_tcp_notification))
{
//we acutally don't care about session, ip, port since the
//rank is encoded in the header
pkt128 tcp_notification_pkt;
tcp_notification_pkt.data(15,0) = msg_session; //session
tcp_notification_pkt.data(31,16) = msg_length; //length of the data plus header
tcp_notification_pkt.data(63,32) = 0; //ip
tcp_notification_pkt.data(79,64) = 0; //port
tcp_notification_pkt.data(80,80) = 0; //close
STREAM_WRITE(m_axis_tcp_notification, tcp_notification_pkt);
rxFsmState = WAIT_REQ;
}
break;
case WAIT_REQ:
if (!STREAM_IS_EMPTY(s_axis_tcp_read_pkg))
{
STREAM_READ(s_axis_tcp_read_pkg);
pkt16 rx_meta_pkt;
rx_meta_pkt.data = 0; //we don't care about the session id in this dummy
STREAM_WRITE(m_axis_tcp_rx_meta, rx_meta_pkt);
rxFsmState = SEND_MSG;
}
break;
case SEND_MSG:
if (!STREAM_IS_EMPTY(rxDataBuffer))
{
do{
#pragma HLS PIPELINE II=1
currWord = STREAM_READ(rxDataBuffer);
STREAM_WRITE(m_axis_tcp_rx_data, currWord);
}while(currWord.last == 0);
msg_length = 0;
msg_session = 0;
rxFsmState = BUFFER_DATA;
}
break;
}//switch
}
//[15:0] session; [23:16] success; [55:24] ip; [71:56] port
void open_con_handler(
STREAM<pkt64>& s_axis_tcp_open_connection,
STREAM<pkt128>& m_axis_tcp_open_status
){
#pragma HLS PIPELINE II=1 style=flp
#pragma HLS INLINE off
static int sessionCnt = 0;
//openConReq and openConRsp
if (!STREAM_IS_EMPTY(s_axis_tcp_open_connection))
{
pkt64 openConnection_pkt = STREAM_READ(s_axis_tcp_open_connection);
ap_uint<32> ip = openConnection_pkt.data(31,0);
ap_uint<16> port = openConnection_pkt.data(47,32);
pkt128 open_status_pkt;
open_status_pkt.data(15,0) = sessionCnt;
open_status_pkt.data(23,16) = 1;
open_status_pkt.data(55,24) = ip;
open_status_pkt.data(71,56) = port;
STREAM_WRITE(m_axis_tcp_open_status, open_status_pkt);
sessionCnt ++;
}
}
void listen_port_handler(
STREAM<pkt16>& s_axis_tcp_listen_port,
STREAM<pkt8>& m_axis_tcp_port_status
){
#pragma HLS PIPELINE II=1 style=flp
#pragma HLS INLINE off
//listen port and listen port status
if (!STREAM_IS_EMPTY(s_axis_tcp_listen_port))
{
pkt16 listen_port_pkt = STREAM_READ(s_axis_tcp_listen_port);
pkt8 port_status_pkt;
port_status_pkt.data = 1;
STREAM_WRITE(m_axis_tcp_port_status, port_status_pkt);
}
}
void network_krnl(
STREAM<pkt128>& m_axis_tcp_notification,
STREAM<pkt32>& s_axis_tcp_read_pkg,
STREAM<pkt16>& m_axis_tcp_rx_meta,
STREAM<stream_word>& m_axis_tcp_rx_data,
STREAM<pkt32>& s_axis_tcp_tx_meta,
STREAM<stream_word>& s_axis_tcp_tx_data,
STREAM<pkt64>& m_axis_tcp_tx_status,
STREAM<pkt64>& s_axis_tcp_open_connection,
STREAM<pkt128>& m_axis_tcp_open_status,
STREAM<pkt16>& s_axis_tcp_listen_port,
STREAM<pkt8>& m_axis_tcp_port_status,
STREAM<stream_word>& net_rx,
STREAM<stream_word>& net_tx
){
#pragma HLS INTERFACE axis register both port=m_axis_tcp_notification
#pragma HLS INTERFACE axis register both port=s_axis_tcp_read_pkg
#pragma HLS INTERFACE axis register both port=m_axis_tcp_rx_meta
#pragma HLS INTERFACE axis register both port=m_axis_tcp_rx_data
#pragma HLS INTERFACE axis register both port=s_axis_tcp_tx_meta
#pragma HLS INTERFACE axis register both port=s_axis_tcp_tx_data
#pragma HLS INTERFACE axis register both port=m_axis_tcp_tx_status
#pragma HLS INTERFACE axis register both port=s_axis_tcp_open_connection
#pragma HLS INTERFACE axis register both port=m_axis_tcp_open_status
#pragma HLS INTERFACE axis register both port=s_axis_tcp_listen_port
#pragma HLS INTERFACE axis register both port=m_axis_tcp_port_status
#pragma HLS INTERFACE axis register both port=net_rx
#pragma HLS INTERFACE axis register both port=net_tx
#pragma HLS INTERFACE ap_ctrl_none port=return
#pragma HLS DATAFLOW disable_start_propagation
open_con_handler(s_axis_tcp_open_connection, m_axis_tcp_open_status);
listen_port_handler(s_axis_tcp_listen_port, m_axis_tcp_port_status);
rx_handler(
m_axis_tcp_notification,
s_axis_tcp_read_pkg,
m_axis_tcp_rx_meta,
m_axis_tcp_rx_data,
net_rx
);
tx_handler(
s_axis_tcp_tx_meta,
s_axis_tcp_tx_data,
m_axis_tcp_tx_status,
net_tx
);
}
| 32.707407 | 109 | 0.666516 | TristanLaan |
2cd2c0adfce8b919bd91624d1a48b2a47ef0087e | 1,031 | cpp | C++ | alakajam13_states/State.InPlay.Next.cpp | playdeezgames/tggd_alakajam13 | e4433a14d4e74cc4f711c7bb6610c87e2fd9b377 | [
"MIT"
] | null | null | null | alakajam13_states/State.InPlay.Next.cpp | playdeezgames/tggd_alakajam13 | e4433a14d4e74cc4f711c7bb6610c87e2fd9b377 | [
"MIT"
] | null | null | null | alakajam13_states/State.InPlay.Next.cpp | playdeezgames/tggd_alakajam13 | e4433a14d4e74cc4f711c7bb6610c87e2fd9b377 | [
"MIT"
] | null | null | null | #include "UIState.h"
#include "States.h"
#include <Game.Audio.Mux.h>
#include <Application.OnEnter.h>
#include <Application.Update.h>
#include <Application.UIState.h>
#include <Game.Actors.h>
#include <Game.ActorTypes.h>
namespace state::in_play
{
static const ::UIState CURRENT_STATE = ::UIState::IN_PLAY_NEXT;
static void OnEnter()
{
if (game::Actors::IsAnythingAlive())
{
auto actor = game::Actors::GetCurrent();
auto descriptor = game::ActorTypes::Read(actor.actorType);
while (!descriptor.playControlled)
{
game::Actors::Act();
game::Actors::Next();
actor = game::Actors::GetCurrent();
descriptor = game::ActorTypes::Read(actor.actorType);
}
application::UIState::Write(::UIState::IN_PLAY_BOARD);
return;
}
application::UIState::Write(::UIState::GAME_OVER);
}
static void OnUpdate(const unsigned int&)
{
OnEnter();
}
void Next::Start()
{
::application::OnEnter::AddHandler(CURRENT_STATE, OnEnter);
::application::Update::AddHandler(CURRENT_STATE, OnUpdate);
}
} | 23.976744 | 64 | 0.695441 | playdeezgames |
2cdb1d4f07e8ac447b1d5ba529a392cca7b05031 | 3,218 | cc | C++ | libcef_dll/cpptoc/media_event_callback_cpptoc.cc | frogbywyplay/appframeworks_cef | 12e3a6d32370b4f72707b493ab951a5d8cb3989d | [
"BSD-3-Clause"
] | null | null | null | libcef_dll/cpptoc/media_event_callback_cpptoc.cc | frogbywyplay/appframeworks_cef | 12e3a6d32370b4f72707b493ab951a5d8cb3989d | [
"BSD-3-Clause"
] | null | null | null | libcef_dll/cpptoc/media_event_callback_cpptoc.cc | frogbywyplay/appframeworks_cef | 12e3a6d32370b4f72707b493ab951a5d8cb3989d | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2016 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
#include "libcef_dll/cpptoc/media_event_callback_cpptoc.h"
namespace {
// MEMBER FUNCTIONS - Body may be edited by hand.
void CEF_CALLBACK media_event_callback_end_of_stream(
struct _cef_media_event_callback_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Execute
CefMediaEventCallbackCppToC::Get(self)->EndOfStream();
}
void CEF_CALLBACK media_event_callback_resolution_changed(
struct _cef_media_event_callback_t* self, int width, int height) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Execute
CefMediaEventCallbackCppToC::Get(self)->ResolutionChanged(
width,
height);
}
void CEF_CALLBACK media_event_callback_video_pts(
struct _cef_media_event_callback_t* self, int64 pts) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Execute
CefMediaEventCallbackCppToC::Get(self)->VideoPTS(
pts);
}
void CEF_CALLBACK media_event_callback_audio_pts(
struct _cef_media_event_callback_t* self, int64 pts) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Execute
CefMediaEventCallbackCppToC::Get(self)->AudioPTS(
pts);
}
void CEF_CALLBACK media_event_callback_have_enough(
struct _cef_media_event_callback_t* self) {
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
DCHECK(self);
if (!self)
return;
// Execute
CefMediaEventCallbackCppToC::Get(self)->HaveEnough();
}
} // namespace
// CONSTRUCTOR - Do not edit by hand.
CefMediaEventCallbackCppToC::CefMediaEventCallbackCppToC() {
GetStruct()->end_of_stream = media_event_callback_end_of_stream;
GetStruct()->resolution_changed = media_event_callback_resolution_changed;
GetStruct()->video_pts = media_event_callback_video_pts;
GetStruct()->audio_pts = media_event_callback_audio_pts;
GetStruct()->have_enough = media_event_callback_have_enough;
}
template<> CefRefPtr<CefMediaEventCallback> CefCppToC<CefMediaEventCallbackCppToC,
CefMediaEventCallback, cef_media_event_callback_t>::UnwrapDerived(
CefWrapperType type, cef_media_event_callback_t* s) {
NOTREACHED() << "Unexpected class type: " << type;
return NULL;
}
#ifndef NDEBUG
template<> base::AtomicRefCount CefCppToC<CefMediaEventCallbackCppToC,
CefMediaEventCallback, cef_media_event_callback_t>::DebugObjCt = 0;
#endif
template<> CefWrapperType CefCppToC<CefMediaEventCallbackCppToC,
CefMediaEventCallback, cef_media_event_callback_t>::kWrapperType =
WT_MEDIA_EVENT_CALLBACK;
| 28.732143 | 82 | 0.745183 | frogbywyplay |
2cdb4a03bd4bf1a1ecda55cbaf83fa1c792e3037 | 7,128 | cxx | C++ | ds/security/gina/gpext/appmgmt/cstore/cache.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/security/gina/gpext/appmgmt/cstore/cache.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/security/gina/gpext/appmgmt/cstore/cache.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1996 - 2001
//
// File: cache.cxx
//
// Contents: Class Store Binding cache
//
// Author: AdamEd
//
//-------------------------------------------------------------------------
#include "cstore.hxx"
CBinding::CBinding(
CServerContext* pServerContext,
WCHAR* wszClassStorePath,
PSID pSid,
IClassAccess* pClassAccess,
HRESULT hrBind,
HRESULT* phr)
{
ULONG ulSize;
*phr = E_OUTOFMEMORY;
Hr = hrBind;
ulSize = lstrlen( wszClassStorePath ) + 1;
szStorePath = (WCHAR*) CsMemAlloc(
ulSize * sizeof( *wszClassStorePath ) );
if ( szStorePath )
{
UINT dwBytesRequired;
*phr = StringCchCopy( szStorePath, ulSize, wszClassStorePath );
if ( SUCCEEDED( *phr ) && pServerContext )
{
*phr =ServerContext.Initialize( pServerContext );
}
if (SUCCEEDED(*phr))
{
dwBytesRequired = GetLengthSid(pSid);
Sid = (PSID) CsMemAlloc( dwBytesRequired );
if ( Sid )
{
BOOL bStatus;
bStatus = CopySid(
dwBytesRequired,
Sid,
pSid);
if ( ! bStatus )
{
LONG Status;
Status = GetLastError();
*phr = HRESULT_FROM_WIN32( Status );
}
else
{
*phr = S_OK;
}
}
}
}
if ( SUCCEEDED( *phr ) && pClassAccess )
{
pIClassAccess = pClassAccess;
pIClassAccess->AddRef();
}
}
CBinding::~CBinding()
{
if ( pIClassAccess )
{
pIClassAccess->Release();
}
CsMemFree( Sid );
CsMemFree( szStorePath );
}
BOOL
CBinding::Compare(
CServerContext* pServerContext,
WCHAR* wszClassStorePath,
PSID pSid)
{
LONG lCompare;
BOOL bStatus;
bStatus = FALSE;
lCompare = lstrcmp(
szStorePath,
wszClassStorePath);
if ( 0 == lCompare )
{
if ( ServerContext.Compare( pServerContext ) )
{
lCompare = 0;
}
else
{
lCompare = -1;
}
}
if ( 0 == lCompare )
{
bStatus = EqualSid(
Sid,
pSid);
}
return bStatus;
}
BOOL CBinding::IsExpired( FILETIME* pftCurrentTime )
{
SYSTEMTIME SystemTimeCurrent;
SYSTEMTIME SystemTimeExpiration;
BOOL bRetrievedTime;
bRetrievedTime = FileTimeToSystemTime(
pftCurrentTime,
&SystemTimeCurrent);
bRetrievedTime &= FileTimeToSystemTime(
&Time,
&SystemTimeExpiration);
if ( bRetrievedTime )
{
CSDBGPrint((
DM_VERBOSE,
IDS_CSTORE_CACHE_EXPIRE,
L"Current Time",
SystemTimeCurrent.wMonth,
SystemTimeCurrent.wDay,
SystemTimeCurrent.wYear,
SystemTimeCurrent.wHour,
SystemTimeCurrent.wMinute,
SystemTimeCurrent.wSecond));
CSDBGPrint((
DM_VERBOSE,
IDS_CSTORE_CACHE_EXPIRE,
L"Expire Time",
SystemTimeExpiration.wMonth,
SystemTimeExpiration.wDay,
SystemTimeExpiration.wYear,
SystemTimeExpiration.wHour,
SystemTimeExpiration.wMinute,
SystemTimeExpiration.wSecond));
}
//
// Compare the current time to the expiration time
//
LONG CompareResult;
CompareResult = CompareFileTime(
pftCurrentTime,
&Time);
//
// If the current time is later than the expired time,
// then we have expired
//
if ( CompareResult > 0 )
{
return TRUE;
}
return FALSE;
}
CBindingList::CBindingList() :
_cBindings( 0 )
{
memset( &_ListLock, 0, sizeof( _ListLock ) );
//
// InitializeCriticalSection has no return value --
// in extremely low memory situations, it may
// throw an exception
//
(void) InitializeCriticalSection( &_ListLock );
}
CBindingList::~CBindingList()
{
CBinding* pBinding;
for (
Reset();
pBinding = (CBinding*) GetCurrentItem();
)
{
//
// We must perform the MoveNext before the Delete
// since it alters the list and will render its
// current pointer invalid
//
MoveNext();
Delete( pBinding );
}
//
// Clean up the critical section allocated in the constructor
//
DeleteCriticalSection( &_ListLock );
}
void
CBindingList::Lock()
{
EnterCriticalSection( &_ListLock );
}
void
CBindingList::Unlock()
{
LeaveCriticalSection( &_ListLock );
}
CBinding*
CBindingList::Find(
CServerContext* pServerContext,
FILETIME* pCurrentTime,
WCHAR* wszClassStorePath,
PSID pSid)
{
CBinding* pCurrent;
CBinding* pExpired;
pCurrent = NULL;
for ( Reset();
pCurrent = (CBinding*) GetCurrentItem();
MoveNext(), Delete( pExpired ) )
{
BOOL bFound;
if ( pCurrent->IsExpired( pCurrentTime ) )
{
pExpired = pCurrent;
continue;
}
pExpired = NULL;
bFound = pCurrent->Compare(
pServerContext,
wszClassStorePath,
pSid);
if ( bFound )
{
CSDBGPrint((DM_WARNING,
IDS_CSTORE_CSCACHE_HIT,
wszClassStorePath));
return pCurrent;
}
}
return NULL;
}
CBinding*
CBindingList::AddBinding(
FILETIME* pCurrentTime,
CBinding* pBinding)
{
CBinding* pExisting;
pExisting = Find(
&(pBinding->ServerContext),
pCurrentTime,
pBinding->szStorePath,
pBinding->Sid);
if ( pExisting )
{
delete pBinding;
return pExisting;
}
if ( _cBindings >= MAXCLASSSTORES )
{
Reset();
Delete( (CBinding*) GetCurrentItem() );
}
GetExpiredTime(
pCurrentTime,
&(pBinding->Time));
InsertFIFO( pBinding );
_cBindings++;
return pBinding;
}
void
CBindingList::Delete( CBinding* pBinding )
{
if ( pBinding )
{
CSDBGPrint((DM_WARNING,
IDS_CSTORE_CSCACHEPURGE,
pBinding->szStorePath));
pBinding->Remove();
delete pBinding;
_cBindings--;
}
}
| 19.910615 | 76 | 0.488917 | npocmaka |
2cde5e689c7a16353dbaa80bf03cfbc0926ee344 | 294 | cpp | C++ | cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ComparisonWithWiderType/test3.cpp | timoles/codeql | 2d24387e9e300bf03be35694816b1e76ae88a50c | [
"MIT"
] | 4,036 | 2020-04-29T00:09:57.000Z | 2022-03-31T14:16:38.000Z | cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ComparisonWithWiderType/test3.cpp | timoles/codeql | 2d24387e9e300bf03be35694816b1e76ae88a50c | [
"MIT"
] | 2,970 | 2020-04-28T17:24:18.000Z | 2022-03-31T22:40:46.000Z | cpp/ql/test/query-tests/Security/CWE/CWE-190/semmle/ComparisonWithWiderType/test3.cpp | ScriptBox99/github-codeql | 2ecf0d3264db8fb4904b2056964da469372a235c | [
"MIT"
] | 794 | 2020-04-29T00:28:25.000Z | 2022-03-30T08:21:46.000Z | void test_issue_5850(unsigned char small, unsigned int large1) {
for(; small < static_cast<unsigned char>(large1 - 1); small++) { } // GOOD
}
void test_widening(unsigned char small, char large) {
for(; small < static_cast<unsigned int>(static_cast<short>(large) - 1); small++) { } // GOOD
}
| 36.75 | 93 | 0.693878 | timoles |
2ce05467170d8885f088e2d9166c4194db95a873 | 19,961 | cpp | C++ | Core/burn/drv/pre90s/d_marineb.cpp | atship/FinalBurn-X | 3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d | [
"Apache-2.0"
] | 17 | 2018-05-24T05:20:45.000Z | 2021-12-24T07:27:22.000Z | Core/burn/drv/pre90s/d_marineb.cpp | atship/FinalBurn-X | 3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d | [
"Apache-2.0"
] | 6 | 2016-10-20T02:36:07.000Z | 2017-03-08T15:23:06.000Z | Core/burn/drv/pre90s/d_marineb.cpp | atship/FinalBurn-X | 3ee18ccd6efc1bbb3a807d2c206106a5a4000e8d | [
"Apache-2.0"
] | 5 | 2019-01-21T00:45:00.000Z | 2021-07-20T08:34:22.000Z | // Based on original MAME driver writen by Zsolt Vasvari
#include "tiles_generic.h"
#include "z80_intf.h"
#include "driver.h"
extern "C" {
#include "ay8910.h"
}
enum { SPRINGER = 0, MARINEB };
static UINT8 *AllMem;
static UINT8 *MemEnd;
static UINT8 *RamStart;
static UINT8 *RamEnd;
static UINT32 *TempPalette;
static UINT32 *DrvPalette;
static UINT8 DrvRecalcPalette;
static UINT8 DrvInputPort0[8];
static UINT8 DrvInputPort1[8];
static UINT8 DrvInputPort2[8];
static UINT8 DrvDip;
static UINT8 DrvInput[3];
static UINT8 DrvReset;
static UINT8 *DrvZ80ROM;
static UINT8 *DrvZ80RAM;
static UINT8 *DrvColPROM;
static UINT8 *DrvVidRAM;
static UINT8 *DrvColRAM;
static UINT8 *DrvSprRAM;
static UINT8 *DrvGfxROM0;
static UINT8 *DrvGfxROM1;
static UINT8 *DrvGfxROM2;
static UINT8 DrvPaletteBank;
static UINT8 DrvColumnScroll;
static UINT8 ActiveLowFlipscreen;
static UINT8 DrvFlipScreenY;
static UINT8 DrvFlipScreenX;
static INT32 DrvInterruptEnable;
static INT32 hardware;
static INT16 *pAY8910Buffer[3];
static struct BurnInputInfo MarinebInputList[] =
{
{"P1 Coin" , BIT_DIGITAL , DrvInputPort2 + 0, "p1 coin" },
{"P1 Start" , BIT_DIGITAL , DrvInputPort2 + 2, "p1 start" },
{"P1 Up" , BIT_DIGITAL , DrvInputPort0 + 0, "p1 up" },
{"P1 Down" , BIT_DIGITAL , DrvInputPort0 + 1, "p1 down" },
{"P1 Left" , BIT_DIGITAL , DrvInputPort0 + 6, "p1 left" },
{"P1 Right" , BIT_DIGITAL , DrvInputPort0 + 7, "p1 right" },
{"P1 Fire" , BIT_DIGITAL , DrvInputPort2 + 4, "p1 fire 1" },
{"P2 Start" , BIT_DIGITAL , DrvInputPort2 + 3, "p2 start" },
{"P2 Up" , BIT_DIGITAL , DrvInputPort1 + 0, "p2 up" },
{"P2 Down" , BIT_DIGITAL , DrvInputPort1 + 1, "p2 down" },
{"P2 Left" , BIT_DIGITAL , DrvInputPort1 + 6, "p2 left" },
{"P2 Right" , BIT_DIGITAL , DrvInputPort1 + 7, "p2 right" },
{"P2 Fire" , BIT_DIGITAL , DrvInputPort2 + 5, "p2 fire 1" },
{"Reset" , BIT_DIGITAL , &DrvReset , "reset" },
{"Dip" , BIT_DIPSWITCH, &DrvDip , "dip" },
};
STDINPUTINFO(Marineb)
static struct BurnDIPInfo MarinebDIPList[]=
{
{0x0E, 0xFF, 0xFF, 0x40, NULL },
{0 , 0xFE, 0 , 4, "Lives" },
{0x0E, 0x01, 0x03, 0x00, "3" },
{0x0E, 0x01, 0x03, 0x01, "4" },
{0x0E, 0x01, 0x03, 0x02, "5" },
{0x0E, 0x01, 0x03, 0x03, "6" },
{0 , 0xFE, 0 , 2, "Coinage" },
{0x0E, 0x01, 0x1C, 0x00, "1 Coin 1 Credit" },
{0x0E, 0x01, 0x1C, 0x1C, "Free Play" },
{0 , 0xFE, 0 , 2, "Bonus Life" },
{0x0E, 0x01, 0x20, 0x00, "20000 50000" },
{0x0E, 0x01, 0x20, 0x20, "40000 70000" },
{0 , 0xFE, 0 , 2, "Cabinet" },
{0x0E, 0x01, 0x40, 0x40, "Upright" },
{0x0E, 0x01, 0x40, 0x00, "Cocktail" },
};
STDDIPINFO(Marineb)
static INT32 MemIndex()
{
UINT8 *Next; Next = AllMem;
DrvZ80ROM = Next; Next += 0x10000;
DrvColPROM = Next; Next += 0x200;
DrvGfxROM0 = Next; Next += 512 * 8 * 8;
DrvGfxROM1 = Next; Next += 64 * 16 * 16;
DrvGfxROM2 = Next; Next += 64 * 32 * 32;
TempPalette = (UINT32*)Next; Next += 0x100 * sizeof(UINT32); // calculate one time
DrvPalette = (UINT32*)Next; Next += 0x100 * sizeof(UINT32);
pAY8910Buffer[0] = (INT16*)Next; Next += nBurnSoundLen * sizeof(INT16);
pAY8910Buffer[1] = (INT16*)Next; Next += nBurnSoundLen * sizeof(INT16);
pAY8910Buffer[2] = (INT16*)Next; Next += nBurnSoundLen * sizeof(INT16);
RamStart = Next;
DrvZ80RAM = Next; Next += 0x800;
DrvVidRAM = Next; Next += 0x400;
DrvSprRAM = Next; Next += 0x100;
DrvColRAM = Next; Next += 0x400;
RamEnd = Next;
MemEnd = Next;
return 0;
}
static void CleanAndInitStuff()
{
DrvPaletteBank = 0;
DrvColumnScroll = 0;
DrvFlipScreenY = 0;
DrvFlipScreenX = 0;
DrvInterruptEnable = 0;
hardware = 0;
ActiveLowFlipscreen = 0;
memset(DrvInputPort0, 0, 8);
memset(DrvInputPort1, 0, 8);
memset(DrvInputPort2, 0, 8);
memset(DrvInput, 0, 3);
DrvDip = 0;
DrvReset = 0;
}
UINT8 __fastcall marineb_read(UINT16 address)
{
switch (address) {
case 0xa800:
return DrvInput[0];
case 0xa000:
return DrvInput[1];
case 0xb000:
return DrvDip;
case 0xb800:
return DrvInput[2];
}
return 0;
}
void __fastcall marineb_write(UINT16 address, UINT8 data)
{
switch (address) {
case 0x9800:
DrvColumnScroll = data;
return;
case 0x9a00:
DrvPaletteBank = (DrvPaletteBank & 0x02) | (data & 0x01);
return;
case 0x9c00:
DrvPaletteBank = (DrvPaletteBank & 0x01) | ((data & 0x01) << 1);
return;
case 0xa000:
DrvInterruptEnable = data;
return;
case 0xa001:
DrvFlipScreenY = data ^ ActiveLowFlipscreen;
return;
case 0xa002:
DrvFlipScreenX = data ^ ActiveLowFlipscreen;
return;
}
}
void __fastcall marineb_write_port(UINT16 port, UINT8 data)
{
switch (port & 0xFF) {
case 0x08:
case 0x09:
AY8910Write(0, port & 1, data);
break;
}
}
static INT32 DrvDoReset()
{
memset (RamStart, 0, RamEnd - RamStart);
ZetOpen(0);
ZetReset();
ZetClose();
AY8910Reset(0);
DrvPaletteBank = 0;
DrvColumnScroll = 0;
DrvFlipScreenY = 0;
DrvFlipScreenX = 0;
DrvInterruptEnable = 0;
return 0;
}
static void DrvCreatePalette()
{
for (INT32 i = 0; i < 256; i++)
{
INT32 bit0, bit1, bit2, r, g, b;
// Red
bit0 = (DrvColPROM[i] >> 0) & 0x01;
bit1 = (DrvColPROM[i] >> 1) & 0x01;
bit2 = (DrvColPROM[i] >> 2) & 0x01;
r = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
// Green
bit0 = (DrvColPROM[i] >> 3) & 0x01;
bit1 = (DrvColPROM[i + 256] >> 0) & 0x01;
bit2 = (DrvColPROM[i + 256] >> 1) & 0x01;
g = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
// Blue
bit0 = 0;
bit1 = (DrvColPROM[i + 256] >> 2) & 0x01;
bit2 = (DrvColPROM[i + 256] >> 3) & 0x01;
b = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2;
TempPalette[i] = (r << 16) | (g << 8) | (b << 0);
}
}
static INT32 MarinebCharPlane[2] = { 0, 4 };
static INT32 MarinebCharXOffs[8] = { 0, 1, 2, 3, 64, 65, 66, 67 };
static INT32 MarinebCharYOffs[8] = { 0, 8, 16, 24, 32, 40, 48, 56 };
static INT32 MarinebSmallSpriteCharPlane[2] = { 0, 65536 };
static INT32 MarinebSmallSpriteXOffs[16] = { 0, 1, 2, 3, 4, 5, 6, 7, 64, 65, 66, 67, 68, 69, 70, 71 };
static INT32 MarinebSmallSpriteYOffs[16] = { 0, 8, 16, 24, 32, 40, 48, 56, 128, 136, 144, 152, 160, 168, 176, 184 };
static INT32 MarinebBigSpriteCharPlane[2] = { 0, 65536 };
static INT32 MarinebBigSpriteXOffs[32] = { 0, 1, 2, 3, 4, 5, 6, 7, 64, 65, 66, 67, 68, 69, 70, 71, 256, 257, 258, 259, 260, 261, 262, 263, 320, 321, 322, 323, 324, 325, 326, 327 };
static INT32 MarinebBigSpriteYOffs[32] = { 0, 8, 16, 24, 32, 40, 48, 56, 128, 136, 144, 152, 160, 168, 176, 184, 512, 520, 528, 536, 544, 552, 560, 568, 640, 648, 656, 664, 672, 680, 688, 696 };
static INT32 MarinebLoadRoms()
{
// Load roms
// Z80
for (INT32 i = 0; i < 5; i++) {
if (BurnLoadRom(DrvZ80ROM + (i * 0x1000), i, 1)) return 1;
}
UINT8 *tmp = (UINT8*)BurnMalloc(0x4000);
if (tmp == NULL) return 1;
// Chars
memset(tmp, 0, 0x2000);
if (BurnLoadRom(tmp, 5, 1)) return 1;
GfxDecode(0x200, 2, 8, 8, MarinebCharPlane, MarinebCharXOffs, MarinebCharYOffs, 0x80, tmp, DrvGfxROM0);
// Sprites
memset(tmp, 0, 0x4000);
if (BurnLoadRom(tmp, 6, 1)) return 1;
if (BurnLoadRom(tmp + 0x2000, 7, 1)) return 1;
// Small Sprites
GfxDecode(0x40, 2, 16, 16, MarinebSmallSpriteCharPlane, MarinebSmallSpriteXOffs, MarinebSmallSpriteYOffs, 0x100, tmp, DrvGfxROM1);
// Big Sprites
GfxDecode(0x40, 2, 32, 32, MarinebBigSpriteCharPlane, MarinebBigSpriteXOffs, MarinebBigSpriteYOffs, 0x400, tmp, DrvGfxROM2);
BurnFree(tmp);
// ColorRoms
if (BurnLoadRom(DrvColPROM, 8, 1)) return 1;
if (BurnLoadRom(DrvColPROM + 0x100, 9, 1)) return 1;
return 0;
}
static INT32 SpringerLoadRoms()
{
// Load roms
// Z80
for (INT32 i = 0; i < 5; i++) {
if (BurnLoadRom(DrvZ80ROM + (i * 0x1000), i, 1)) return 1;
}
UINT8 *tmp = (UINT8*)BurnMalloc(0x4000);
if (tmp == NULL) return 1;
// Chars
memset(tmp, 0, 0x4000);
if (BurnLoadRom(tmp, 5, 1)) return 1;
if (BurnLoadRom(tmp + 0x1000, 6, 1)) return 1;
GfxDecode(0x200, 2, 8, 8, MarinebCharPlane, MarinebCharXOffs, MarinebCharYOffs, 0x80, tmp, DrvGfxROM0);
memset(tmp, 0, 0x4000);
if (BurnLoadRom(tmp, 7, 1)) return 1;
if (BurnLoadRom(tmp + 0x2000, 8, 1)) return 1;
// Small Sprites
GfxDecode(0x40, 2, 16, 16, MarinebSmallSpriteCharPlane, MarinebSmallSpriteXOffs, MarinebSmallSpriteYOffs, 0x100, tmp, DrvGfxROM1);
// Big Sprites
GfxDecode(0x40, 2, 32, 32, MarinebBigSpriteCharPlane, MarinebBigSpriteXOffs, MarinebBigSpriteYOffs, 0x400, tmp, DrvGfxROM2);
BurnFree(tmp);
// ColorRoms
if (BurnLoadRom(DrvColPROM, 9, 1)) return 1;
if (BurnLoadRom(DrvColPROM + 0x100, 10, 1)) return 1;
return 0;
}
static INT32 DrvInit()
{
AllMem = NULL;
MemIndex();
INT32 nLen = MemEnd - (UINT8 *)0;
if ((AllMem = (UINT8 *)BurnMalloc(nLen)) == NULL) return 1;
memset(AllMem, 0, nLen);
MemIndex();
switch(hardware) {
case MARINEB:
MarinebLoadRoms();
break;
case SPRINGER:
SpringerLoadRoms();
break;
}
DrvCreatePalette();
ZetInit(0);
ZetOpen(0);
ZetMapArea (0x0000, 0x7fff, 0, DrvZ80ROM);
ZetMapArea (0x0000, 0x7fff, 2, DrvZ80ROM);
ZetMapArea (0x8000, 0x87ff, 0, DrvZ80RAM);
ZetMapArea (0x8000, 0x87ff, 1, DrvZ80RAM);
ZetMapArea (0x8000, 0x87ff, 2, DrvZ80RAM);
ZetMapArea (0x8800, 0x8bff, 0, DrvVidRAM);
ZetMapArea (0x8800, 0x8bff, 1, DrvVidRAM);
ZetMapArea (0x8800, 0x8bff, 2, DrvVidRAM);
ZetMapArea (0x8c00, 0x8c3f, 0, DrvSprRAM);
ZetMapArea (0x8c00, 0x8c3f, 1, DrvSprRAM);
ZetMapArea (0x8c00, 0x8c3f, 2, DrvSprRAM);
ZetMapArea (0x9000, 0x93ff, 0, DrvColRAM);
ZetMapArea (0x9000, 0x93ff, 1, DrvColRAM);
ZetMapArea (0x9000, 0x93ff, 2, DrvColRAM);
ZetSetReadHandler(marineb_read);
ZetSetWriteHandler(marineb_write);
ZetSetOutHandler(marineb_write_port);
ZetClose();
AY8910Init(0, 1500000, nBurnSoundRate, NULL, NULL, NULL, NULL);
AY8910SetAllRoutes(0, 0.50, BURN_SND_ROUTE_BOTH);
GenericTilesInit();
DrvDoReset();
return 0;
}
static INT32 DrvExit()
{
GenericTilesExit();
ZetExit();
AY8910Exit(0);
BurnFree (AllMem);
CleanAndInitStuff();
return 0;
}
static void RenderMarinebBg()
{
INT32 TileIndex = 0;
for (INT32 my = 0; my < 32; my++) {
for (INT32 mx = 0; mx < 32; mx++) {
TileIndex = (my * 32) + mx;
INT32 code = DrvVidRAM[TileIndex];
INT32 color = DrvColRAM[TileIndex];
code |= ((color & 0xc0) << 2);
color &= 0x0f;
color |= DrvPaletteBank << 4;
INT32 flipx = (color >> 4) & 0x02;
INT32 flipy = (color >> 4) & 0x01;
INT32 x = mx << 3;
INT32 y = my << 3;
// stuff from 192 to 256 does not scroll
if ((x >> 3) < 24) {
y -= DrvColumnScroll;
if (y < -7) y += 256;
}
y -= 16;
if (flipy) {
if (flipx) {
Render8x8Tile_FlipXY_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
} else {
Render8x8Tile_FlipY_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
}
} else {
if (flipx) {
Render8x8Tile_FlipX_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
} else {
Render8x8Tile_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
}
}
}
}
}
static void RenderSpringerBg()
{
INT32 TileIndex = 0;
for (INT32 my = 0; my < 32; my++) {
for (INT32 mx = 0; mx < 32; mx++) {
TileIndex = (my * 32) + mx;
INT32 code = DrvVidRAM[TileIndex];
INT32 color = DrvColRAM[TileIndex];
code |= ((color & 0xc0) << 2);
color &= 0x0f;
color |= DrvPaletteBank << 4;
INT32 flipx = (color >> 4) & 0x02;
INT32 flipy = (color >> 4) & 0x01;
INT32 x = mx << 3;
INT32 y = my << 3;
y -= 16; // remove garbage on left side
if (flipy) {
if (flipx) {
Render8x8Tile_FlipXY_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
} else {
Render8x8Tile_FlipY_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
}
} else {
if (flipx) {
Render8x8Tile_FlipX_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
} else {
Render8x8Tile_Clip(pTransDraw, code, x, y, color, 2, 0, DrvGfxROM0);
}
}
}
}
}
static void MarinebDrawSprites()
{
// Render Tiles
RenderMarinebBg();
for (INT32 offs = 0x0f; offs >= 0; offs--) {
INT32 gfx, sx, sy, code, color, flipx, flipy, offs2;
if ((offs == 0) || (offs == 2))
continue;
if (offs < 8) {
offs2 = 0x0018 + offs;
} else {
offs2 = 0x03d8 - 8 + offs;
}
code = DrvVidRAM[offs2];
sx = DrvVidRAM[offs2 + 0x20];
sy = DrvColRAM[offs2];
color = (DrvColRAM[offs2 + 0x20] & 0x0f) + 16 * DrvPaletteBank;
flipx = code & 0x02;
flipy = !(code & 0x01);
if (offs < 4) {
gfx = 2;
code = (code >> 4) | ((code & 0x0c) << 2);
} else {
gfx = 1;
code >>= 2;
}
if (!DrvFlipScreenY) {
if (gfx == 1) {
sy = 256 - 16 - sy;
} else {
sy = 256 - 32 - sy;
}
flipy = !flipy;
}
if (DrvFlipScreenX) {
sx++;
}
sy -= 16; // proper alignement
// Small Sprites
if (gfx == 1) {
if (flipy) {
if (flipx) {
Render16x16Tile_Mask_FlipXY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
} else {
Render16x16Tile_Mask_FlipY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
}
} else {
if (flipx) {
Render16x16Tile_Mask_FlipX_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
} else {
Render16x16Tile_Mask_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
}
}
// Big sprites
} else {
if (flipy) {
if (flipx) {
Render32x32Tile_Mask_FlipXY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
} else {
Render32x32Tile_Mask_FlipY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
}
} else {
if (flipx) {
Render32x32Tile_Mask_FlipX_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
} else {
Render32x32Tile_Mask_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
}
}
}
}
}
static void SpringerDrawSprites()
{
// Render Tiles
RenderSpringerBg();
for (INT32 offs = 0x0f; offs >= 0; offs--)
{
INT32 gfx, sx, sy, code, color, flipx, flipy, offs2;
if ((offs == 0) || (offs == 2))
continue;
offs2 = 0x0010 + offs;
code = DrvVidRAM[offs2];
sx = 240 - DrvVidRAM[offs2 + 0x20];
sy = DrvColRAM[offs2];
color = (DrvColRAM[offs2 + 0x20] & 0x0f) + 16 * DrvPaletteBank;
flipx = !(code & 0x02);
flipy = !(code & 0x01);
if (offs < 4)
{
sx -= 0x10;
gfx = 2;
code = (code >> 4) | ((code & 0x0c) << 2);
}
else
{
gfx = 1;
code >>= 2;
}
if (!DrvFlipScreenY) {
if (gfx == 1) {
sy = 256 - 16 - sy;
} else {
sy = 256 - 32 - sy;
}
flipy = !flipy;
}
if (!DrvFlipScreenX)
{
sx--;
}
sy -= 16; // proper alignement
// Small Sprites
if (gfx == 1) {
if (flipy) {
if (flipx) {
Render16x16Tile_Mask_FlipXY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
} else {
Render16x16Tile_Mask_FlipY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
}
} else {
if (flipx) {
Render16x16Tile_Mask_FlipX_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
} else {
Render16x16Tile_Mask_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM1);
}
}
// Big Sprites
} else {
if (flipy) {
if (flipx) {
Render32x32Tile_Mask_FlipXY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
} else {
Render32x32Tile_Mask_FlipY_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
}
} else {
if (flipx) {
Render32x32Tile_Mask_FlipX_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
} else {
Render32x32Tile_Mask_Clip(pTransDraw, code, sx, sy, color, 2, 0, 0, DrvGfxROM2);
}
}
}
}
}
static INT32 DrvDraw()
{
if (DrvRecalcPalette) {
for (INT32 i = 0; i < 256; i++) {
UINT32 tmp = TempPalette[i];
// Recalc Colors
DrvPalette[i] = BurnHighCol((tmp >> 16) & 0xFF, (tmp >> 8) & 0xFF, tmp & 0xFF, 0);
}
DrvRecalcPalette = 0;
}
switch(hardware) {
case MARINEB:
MarinebDrawSprites();
break;
case SPRINGER:
SpringerDrawSprites();
break;
}
BurnTransferCopy(DrvPalette);
return 0;
}
static INT32 DrvFrame()
{
if (DrvReset) {
DrvDoReset();
}
DrvInput[0] = DrvInput[1] = DrvInput[2] = 0;
for (INT32 i = 0; i < 8; i++) {
DrvInput[0] |= (DrvInputPort0[i] & 1) << i;
DrvInput[1] |= (DrvInputPort1[i] & 1) << i;
DrvInput[2] |= (DrvInputPort2[i] & 1) << i;
}
ZetOpen(0);
ZetRun(3072000 / 60);
if (DrvInterruptEnable) ZetNmi();
ZetClose();
if (pBurnSoundOut) {
AY8910Render(&pAY8910Buffer[0], pBurnSoundOut, nBurnSoundLen, 0);
}
if (pBurnDraw) {
DrvDraw();
}
return 0;
}
static INT32 DrvScan(INT32 nAction,INT32 *pnMin)
{
struct BurnArea ba;
if (pnMin) {
*pnMin = 0x029708;
}
if (nAction & ACB_VOLATILE) {
memset(&ba, 0, sizeof(ba));
ba.Data = RamStart;
ba.nLen = RamEnd - RamStart;
ba.szName = "All Ram";
BurnAcb(&ba);
ZetScan(nAction);
AY8910Scan(nAction, pnMin);
}
return 0;
}
static INT32 MarinebInit()
{
CleanAndInitStuff();
hardware = MARINEB;
return DrvInit();
}
static INT32 SpringerInit()
{
CleanAndInitStuff();
ActiveLowFlipscreen = 1;
hardware = SPRINGER;
return DrvInit();
}
// Marine Boy
static struct BurnRomInfo MarinebRomDesc[] = {
{ "marineb.1", 0x1000, 0x661d6540, BRF_ESS | BRF_PRG }, // 0 maincpu
{ "marineb.2", 0x1000, 0x922da17f, BRF_ESS | BRF_PRG }, // 1
{ "marineb.3", 0x1000, 0x820a235b, BRF_ESS | BRF_PRG }, // 2
{ "marineb.4", 0x1000, 0xa157a283, BRF_ESS | BRF_PRG }, // 3
{ "marineb.5", 0x1000, 0x9ffff9c0, BRF_ESS | BRF_PRG }, // 4
{ "marineb.6", 0x2000, 0xee53ec2e, BRF_GRA }, // 5 gfx1
{ "marineb.8", 0x2000, 0xdc8bc46c, BRF_GRA }, // 6 gfx2
{ "marineb.7", 0x2000, 0x9d2e19ab, BRF_GRA }, // 7
{ "marineb.1b", 0x100, 0xf32d9472, BRF_GRA }, // 8 proms
{ "marineb.1c", 0x100, 0x93c69d3e, BRF_GRA }, // 9
};
STD_ROM_PICK(Marineb)
STD_ROM_FN(Marineb)
struct BurnDriver BurnDrvMarineb = {
"marineb", NULL, NULL, NULL, "1982",
"Marine Boy\0", NULL, "Orca", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING, 2, HARDWARE_MISC_PRE90S, 0, 0,
NULL, MarinebRomInfo, MarinebRomName, NULL, NULL, MarinebInputInfo, MarinebDIPInfo,
MarinebInit, DrvExit, DrvFrame, DrvDraw, DrvScan,
&DrvRecalcPalette, 0x100, 256, 224, 4, 3
};
// Springer
static struct BurnRomInfo SpringerRomDesc[] = {
{ "springer.1", 0x1000, 0x0794103a, BRF_ESS | BRF_PRG }, // 0 maincpu
{ "springer.2", 0x1000, 0xf4aecd9a, BRF_ESS | BRF_PRG }, // 1
{ "springer.3", 0x1000, 0x2f452371, BRF_ESS | BRF_PRG }, // 2
{ "springer.4", 0x1000, 0x859d1bf5, BRF_ESS | BRF_PRG }, // 3
{ "springer.5", 0x1000, 0x72adbbe3, BRF_ESS | BRF_PRG }, // 4
{ "springer.6", 0x1000, 0x6a961833, BRF_GRA }, // 5 gfx1
{ "springer.7", 0x1000, 0x95ab8fc0, BRF_GRA }, // 6
{ "springer.8", 0x1000, 0xa54bafdc, BRF_GRA }, // 7 gfx2
{ "springer.9", 0x1000, 0xfa302775, BRF_GRA }, // 8
{ "1b.vid", 0x100, 0xa2f935aa, BRF_GRA }, // 9 proms
{ "1c.vid", 0x100, 0xb95421f4, BRF_GRA }, // 10
};
STD_ROM_PICK(Springer)
STD_ROM_FN(Springer)
struct BurnDriver BurnDrvSpringer = {
"springer", NULL, NULL, NULL, "1982",
"Springer\0", NULL, "Orca", "Miscellaneous",
NULL, NULL, NULL, NULL,
BDF_GAME_WORKING | BDF_ORIENTATION_VERTICAL, 2, HARDWARE_MISC_PRE90S, 0, 0,
NULL, SpringerRomInfo, SpringerRomName, NULL, NULL, MarinebInputInfo, MarinebDIPInfo,
SpringerInit, DrvExit, DrvFrame, DrvDraw, DrvScan,
&DrvRecalcPalette, 0x100, 224, 256, 3, 4
};
| 23.791418 | 194 | 0.612645 | atship |
2ce10d66c6124032b15287bb1518341d0aad7bb8 | 13,938 | cc | C++ | test/typy/SkillParam.cc | ibelie/typy | 3616845fb91459aacd8df6bf82c5d91f4542bee7 | [
"MIT"
] | null | null | null | test/typy/SkillParam.cc | ibelie/typy | 3616845fb91459aacd8df6bf82c5d91f4542bee7 | [
"MIT"
] | null | null | null | test/typy/SkillParam.cc | ibelie/typy | 3616845fb91459aacd8df6bf82c5d91f4542bee7 | [
"MIT"
] | null | null | null | // Generated by the typy Cpp.GenerateExtention. DO NOT EDIT!
#include "SkillParam.h"
#include "list.h"
#include "dict.h"
TypyObjectBegin(SkillParam);
SkillParam::SkillParam() : Message() {
ZERO(SkillParam, p_buckID, _cached_size);
}
void SkillParam::Clear() {
::typy::Clear(p_buckID);
::typy::Clear(p_destPos);
::typy::Clear(p_destRot);
::typy::Clear(p_extraParam);
::typy::Clear(p_origPos);
::typy::Clear(p_origRot);
::typy::Clear(p_targetID);
::typy::Clear(p_targetIDs);
}
int SkillParam::Visit(visitproc visit, void* arg) {
register int result = 0;
if((result = ::typy::Visit(p_buckID, visit, arg)) != 0) { return result; }
if((result = ::typy::Visit(p_destPos, visit, arg)) != 0) { return result; }
if((result = ::typy::Visit(p_destRot, visit, arg)) != 0) { return result; }
if((result = ::typy::Visit(p_extraParam, visit, arg)) != 0) { return result; }
if((result = ::typy::Visit(p_origPos, visit, arg)) != 0) { return result; }
if((result = ::typy::Visit(p_origRot, visit, arg)) != 0) { return result; }
if((result = ::typy::Visit(p_targetID, visit, arg)) != 0) { return result; }
if((result = ::typy::Visit(p_targetIDs, visit, arg)) != 0) { return result; }
return result;
}
void SkillParam::MergeFrom(const SkillParam& from) {
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
::typy::MergeFrom(p_buckID, from.p_buckID);
::typy::MergeFrom(p_destPos, from.p_destPos);
::typy::MergeFrom(p_destRot, from.p_destRot);
::typy::MergeFrom(p_extraParam, from.p_extraParam);
::typy::MergeFrom(p_origPos, from.p_origPos);
::typy::MergeFrom(p_origRot, from.p_origRot);
::typy::MergeFrom(p_targetID, from.p_targetID);
::typy::MergeFrom(p_targetIDs, from.p_targetIDs);
}
void SkillParam::SerializeWithCachedSizes(CodedOutputStream* output) const {
::typy::Write(1, p_buckID, output);
::typy::Write(2, p_destPos, output);
::typy::Write(3, p_destRot, output);
::typy::Write(4, p_extraParam, output);
::typy::Write(5, p_origPos, output);
::typy::Write(6, p_origRot, output);
::typy::Write(7, p_targetID, output);
::typy::Write(8, p_targetIDs, output);
}
int SkillParam::ByteSize() const {
int total_size = 0;
::typy::ByteSize(total_size, 1, p_buckID);
::typy::ByteSize(total_size, 1, p_destPos);
::typy::ByteSize(total_size, 1, p_destRot);
::typy::ByteSize(total_size, 1, p_extraParam);
::typy::ByteSize(total_size, 1, p_origPos);
::typy::ByteSize(total_size, 1, p_origRot);
::typy::ByteSize(total_size, 1, p_targetID);
::typy::ByteSize(total_size, 1, p_targetIDs);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
bool SkillParam::MergePartialFromCodedStream(CodedInputStream* input) {
BEGINE_READ_CASE(8)
FIRST_READ_NORMAL_CASE(1, p_buckID, bytes)
NEXT_READ_NORMAL_CASE(2, p_destPos, Python<Shadow_Vector3>)
NEXT_READ_NORMAL_CASE(3, p_destRot, Python<Shadow_Vector3>)
NEXT_READ_REPEATED_OBJECT_CASE(4, p_extraParam, SINGLE_ARG(Dict<bytes, Vbbyfi >)::Entry, PREV_NO_REPEATED_OBJECT, NEXT_NO_REPEATED_OBJECT)
NEXT_READ_NORMAL_CASE(5, p_origPos, Python<Shadow_Vector3>)
NEXT_READ_NORMAL_CASE(6, p_origRot, Python<Shadow_Vector3>)
NEXT_READ_NORMAL_CASE(7, p_targetID, bytes)
NEXT_READ_NORMAL_CASE(8, p_targetIDs, bytes)
END_READ_CASE()
}
PyObject* SkillParam::Json(bool slim) {
PyObject* json = PyDict_New();
if (json == NULL) { return NULL; }
PyObject* value = PyString_FromString(SkillParam::Name);
if (value == NULL) { Py_DECREF(json); return NULL; }
PyDict_SetItemString(json, "_t", value);
Py_DECREF(value);
value = ::typy::Json(p_buckID, slim);
if (value != NULL) { PyDict_SetItemString(json, "buckID", value); Py_DECREF(value); }
value = ::typy::Json(p_destPos, slim);
if (value != NULL) { PyDict_SetItemString(json, "destPos", value); Py_DECREF(value); }
value = ::typy::Json(p_destRot, slim);
if (value != NULL) { PyDict_SetItemString(json, "destRot", value); Py_DECREF(value); }
value = ::typy::Json(p_extraParam, slim);
if (value != NULL) { PyDict_SetItemString(json, "extraParam", value); Py_DECREF(value); }
value = ::typy::Json(p_origPos, slim);
if (value != NULL) { PyDict_SetItemString(json, "origPos", value); Py_DECREF(value); }
value = ::typy::Json(p_origRot, slim);
if (value != NULL) { PyDict_SetItemString(json, "origRot", value); Py_DECREF(value); }
value = ::typy::Json(p_targetID, slim);
if (value != NULL) { PyDict_SetItemString(json, "targetID", value); Py_DECREF(value); }
value = ::typy::Json(p_targetIDs, slim);
if (value != NULL) { PyDict_SetItemString(json, "targetIDs", value); Py_DECREF(value); }
return json;
}
SkillParam* SkillParam::FromJson(PyObject* json) {
if (!PyObject_HasAttrString(json, "iteritems")) {
FormatTypeError(json, "FromJson expect dict, but ");
return NULL;
}
PyObject* value = PyObject_GetItem(json, ScopedPyObjectPtr(PyString_FromString("_t")).get());
if (value == NULL) {
FormatTypeError(json, "Json expect _t, ");
return NULL;
} else if (PyUnicode_Check(value)) {
PyObject* _value = PyUnicode_AsEncodedObject(value, "utf-8", NULL);
Py_DECREF(value);
value = _value;
} else if (!PyBytes_Check(value)) {
FormatTypeError(value, "Json _t expect String, but ");
return NULL;
}
if (strcmp(PyBytes_AS_STRING(value), SkillParam::Name)) {
PyErr_Format(PyExc_TypeError, "Object expect '%.100s', but Json has type %.100s",
SkillParam::Name, PyBytes_AS_STRING(value));
Py_DECREF(value);
return NULL;
}
PyErr_Clear();
Py_DECREF(value);
SkillParam* object = new SkillParam();
value = PyObject_GetItem(json, ScopedPyObjectPtr(PyString_FromString("buckID")).get()); PyErr_Clear();
if (value != NULL) { if (!::typy::FromJson(object->p_buckID, value)) { Py_DECREF(value); return NULL; } Py_DECREF(value); }
value = PyObject_GetItem(json, ScopedPyObjectPtr(PyString_FromString("destPos")).get()); PyErr_Clear();
if (value != NULL) { if (!::typy::FromJson(object->p_destPos, value)) { Py_DECREF(value); return NULL; } Py_DECREF(value); }
value = PyObject_GetItem(json, ScopedPyObjectPtr(PyString_FromString("destRot")).get()); PyErr_Clear();
if (value != NULL) { if (!::typy::FromJson(object->p_destRot, value)) { Py_DECREF(value); return NULL; } Py_DECREF(value); }
value = PyObject_GetItem(json, ScopedPyObjectPtr(PyString_FromString("extraParam")).get()); PyErr_Clear();
if (value != NULL) { if (!::typy::FromJson(object->p_extraParam, value)) { Py_DECREF(value); return NULL; } Py_DECREF(value); }
value = PyObject_GetItem(json, ScopedPyObjectPtr(PyString_FromString("origPos")).get()); PyErr_Clear();
if (value != NULL) { if (!::typy::FromJson(object->p_origPos, value)) { Py_DECREF(value); return NULL; } Py_DECREF(value); }
value = PyObject_GetItem(json, ScopedPyObjectPtr(PyString_FromString("origRot")).get()); PyErr_Clear();
if (value != NULL) { if (!::typy::FromJson(object->p_origRot, value)) { Py_DECREF(value); return NULL; } Py_DECREF(value); }
value = PyObject_GetItem(json, ScopedPyObjectPtr(PyString_FromString("targetID")).get()); PyErr_Clear();
if (value != NULL) { if (!::typy::FromJson(object->p_targetID, value)) { Py_DECREF(value); return NULL; } Py_DECREF(value); }
value = PyObject_GetItem(json, ScopedPyObjectPtr(PyString_FromString("targetIDs")).get()); PyErr_Clear();
if (value != NULL) { if (!::typy::FromJson(object->p_targetIDs, value)) { Py_DECREF(value); return NULL; } Py_DECREF(value); }
return object;
}
// ===================================================================
const int SkillParam::PropertyCount = 8;
char* SkillParam::Properties[] = {
"buckID",
"destPos",
"destRot",
"extraParam",
"origPos",
"origRot",
"targetID",
"targetIDs"
};
int SkillParam::PropertyByteSize(int tag) const {
int size = 0;
switch(tag) {
case 1: ::typy::ByteSize(size, 1, p_buckID); if (size == 0) { size = 1; } break;
case 2: ::typy::ByteSize(size, 1, p_destPos); if (size == 0) { size = 1; } break;
case 3: ::typy::ByteSize(size, 1, p_destRot); if (size == 0) { size = 1; } break;
case 4: ::typy::ByteSize(size, 1, p_extraParam); if (size == 0) { size = 1; } break;
case 5: ::typy::ByteSize(size, 1, p_origPos); if (size == 0) { size = 1; } break;
case 6: ::typy::ByteSize(size, 1, p_origRot); if (size == 0) { size = 1; } break;
case 7: ::typy::ByteSize(size, 1, p_targetID); if (size == 0) { size = 1; } break;
case 8: ::typy::ByteSize(size, 1, p_targetIDs); if (size == 0) { size = 1; } break;
}
return size;
}
void SkillParam::SerializeProperty(CodedOutputStream* output, int tag) const {
switch(tag) {
case 1:
::typy::Write(1, p_buckID, output);
if (output->ByteCount() <= 0) {
::typy::WriteTag(1, p_buckID, output);
}
break;
case 2:
::typy::Write(2, p_destPos, output);
if (output->ByteCount() <= 0) {
::typy::WriteTag(2, p_destPos, output);
}
break;
case 3:
::typy::Write(3, p_destRot, output);
if (output->ByteCount() <= 0) {
::typy::WriteTag(3, p_destRot, output);
}
break;
case 4:
::typy::Write(4, p_extraParam, output);
if (output->ByteCount() <= 0) {
::typy::WriteTag(4, p_extraParam, output);
}
break;
case 5:
::typy::Write(5, p_origPos, output);
if (output->ByteCount() <= 0) {
::typy::WriteTag(5, p_origPos, output);
}
break;
case 6:
::typy::Write(6, p_origRot, output);
if (output->ByteCount() <= 0) {
::typy::WriteTag(6, p_origRot, output);
}
break;
case 7:
::typy::Write(7, p_targetID, output);
if (output->ByteCount() <= 0) {
::typy::WriteTag(7, p_targetID, output);
}
break;
case 8:
::typy::Write(8, p_targetIDs, output);
if (output->ByteCount() <= 0) {
::typy::WriteTag(8, p_targetIDs, output);
}
break;
}
}
int SkillParam::DeserializeProperty(CodedInputStream* input) {
const void* data;
int size;
input->GetDirectBufferPointerInline(&data, &size);
CodedInputStream tagInput(reinterpret_cast<const uint8*>(data), size);
::std::pair<uint32, bool> p = tagInput.ReadTagWithCutoff(_MAXTAG(25)
<= 0x7F ? 0x7F : (_MAXTAG(25) <= 0x3FFF ? 0x3FFF : _MAXTAG(25)));
uint32 tag = p.first;
if (!p.second) { return 0; }
int index = WireFormatLite::GetTagFieldNumber(tag);
switch(index) {
case 1: ::typy::Clear(p_buckID); break;
case 2: ::typy::Clear(p_destPos); break;
case 3: ::typy::Clear(p_destRot); break;
case 4: ::typy::Clear(p_extraParam); break;
case 5: ::typy::Clear(p_origPos); break;
case 6: ::typy::Clear(p_origRot); break;
case 7: ::typy::Clear(p_targetID); break;
case 8: ::typy::Clear(p_targetIDs); break;
}
if (!tagInput.ExpectAtEnd()) {
MergePartialFromCodedStream(input);
}
return index;
}
bool SkillParam::SetPropertySequence(PyObject* args) {
for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(args); i++) {
switch(i) {
case 0: if (!::typy::CheckAndSet(PyTuple_GET_ITEM(args, 0), p_buckID, "Property 'buckID' expect bytes, but ")) { return false; } break;
case 1: if (!::typy::CheckAndSet(PyTuple_GET_ITEM(args, 1), p_destPos, "Property 'destPos' expect Python<Shadow_Vector3>, but ")) { return false; } break;
case 2: if (!::typy::CheckAndSet(PyTuple_GET_ITEM(args, 2), p_destRot, "Property 'destRot' expect Python<Shadow_Vector3>, but ")) { return false; } break;
case 3: if (!::typy::CheckAndSet(PyTuple_GET_ITEM(args, 3), p_extraParam, "Property 'extraParam' expect Dict(bytes -> Vbbyfi), but ")) { return false; } break;
case 4: if (!::typy::CheckAndSet(PyTuple_GET_ITEM(args, 4), p_origPos, "Property 'origPos' expect Python<Shadow_Vector3>, but ")) { return false; } break;
case 5: if (!::typy::CheckAndSet(PyTuple_GET_ITEM(args, 5), p_origRot, "Property 'origRot' expect Python<Shadow_Vector3>, but ")) { return false; } break;
case 6: if (!::typy::CheckAndSet(PyTuple_GET_ITEM(args, 6), p_targetID, "Property 'targetID' expect bytes, but ")) { return false; } break;
case 7: if (!::typy::CheckAndSet(PyTuple_GET_ITEM(args, 7), p_targetIDs, "Property 'targetIDs' expect List(bytes), but ")) { return false; } break;
default: PyErr_Format(PyExc_TypeError, "Unsurported property number %lu.", i); return false;
}
}
return true;
}
PyObject* SkillParam::GetPropertySequence() {
PyObject* result = PyTuple_New(8);
if (result == NULL) { return result; }
PyTuple_SET_ITEM(result, 0, ::typy::GetPyObject(p_buckID));
PyTuple_SET_ITEM(result, 1, ::typy::GetPyObject(p_destPos));
PyTuple_SET_ITEM(result, 2, ::typy::GetPyObject(p_destRot));
PyTuple_SET_ITEM(result, 3, ::typy::GetPyObject(p_extraParam));
PyTuple_SET_ITEM(result, 4, ::typy::GetPyObject(p_origPos));
PyTuple_SET_ITEM(result, 5, ::typy::GetPyObject(p_origRot));
PyTuple_SET_ITEM(result, 6, ::typy::GetPyObject(p_targetID));
PyTuple_SET_ITEM(result, 7, ::typy::GetPyObject(p_targetIDs));
return result;
}
// ===================================================================
TYPY_GETSET(SkillParam, p_buckID, bytes);
TYPY_GETSET(SkillParam, p_destPos, Python<Shadow_Vector3>);
TYPY_GETSET(SkillParam, p_destRot, Python<Shadow_Vector3>);
TYPY_GETSET(SkillParam, p_extraParam, Dict(bytes -> Vbbyfi));
TYPY_GETSET(SkillParam, p_origPos, Python<Shadow_Vector3>);
TYPY_GETSET(SkillParam, p_origRot, Python<Shadow_Vector3>);
TYPY_GETSET(SkillParam, p_targetID, bytes);
TYPY_GETSET(SkillParam, p_targetIDs, List(bytes));
template <> PyGetSetDef Object<SkillParam>::GetSet[] = {
{"buckID", (getter)Get_p_buckID, (setter)Set_p_buckID, "Property buckID"},
{"destPos", (getter)Get_p_destPos, (setter)Set_p_destPos, "Property destPos"},
{"destRot", (getter)Get_p_destRot, (setter)Set_p_destRot, "Property destRot"},
{"extraParam", (getter)Get_p_extraParam, (setter)Set_p_extraParam, "Property extraParam"},
{"origPos", (getter)Get_p_origPos, (setter)Set_p_origPos, "Property origPos"},
{"origRot", (getter)Get_p_origRot, (setter)Set_p_origRot, "Property origRot"},
{"targetID", (getter)Get_p_targetID, (setter)Set_p_targetID, "Property targetID"},
{"targetIDs", (getter)Get_p_targetIDs, (setter)Set_p_targetIDs, "Property targetIDs"},
{NULL}
};
TypyObjectEnd(SkillParam);
| 42.886154 | 161 | 0.693643 | ibelie |
f8ea3449a2b90471a1688f3323dae99fd5cf10cc | 33,461 | cc | C++ | src/system/proto/heartbeat.pb.cc | yipeiw/pserver | 2a856ba0cda744e4b8adcd925238dd7d4609bea7 | [
"Apache-2.0"
] | null | null | null | src/system/proto/heartbeat.pb.cc | yipeiw/pserver | 2a856ba0cda744e4b8adcd925238dd7d4609bea7 | [
"Apache-2.0"
] | null | null | null | src/system/proto/heartbeat.pb.cc | yipeiw/pserver | 2a856ba0cda744e4b8adcd925238dd7d4609bea7 | [
"Apache-2.0"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: system/proto/heartbeat.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "system/proto/heartbeat.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace PS {
namespace {
const ::google::protobuf::Descriptor* HeartbeatReport_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
HeartbeatReport_reflection_ = NULL;
} // namespace
void protobuf_AssignDesc_system_2fproto_2fheartbeat_2eproto() {
protobuf_AddDesc_system_2fproto_2fheartbeat_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"system/proto/heartbeat.proto");
GOOGLE_CHECK(file != NULL);
HeartbeatReport_descriptor_ = file->message_type(0);
static const int HeartbeatReport_offsets_[15] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, task_id_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, hostname_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, seconds_since_epoch_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, total_time_milli_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, busy_time_milli_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, net_in_mb_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, net_out_mb_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, process_cpu_usage_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, host_cpu_usage_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, process_rss_mb_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, process_virt_mb_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, host_in_use_gb_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, host_in_use_percentage_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, host_net_in_bw_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, host_net_out_bw_),
};
HeartbeatReport_reflection_ =
new ::google::protobuf::internal::GeneratedMessageReflection(
HeartbeatReport_descriptor_,
HeartbeatReport::default_instance_,
HeartbeatReport_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, _has_bits_[0]),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(HeartbeatReport, _unknown_fields_),
-1,
::google::protobuf::DescriptorPool::generated_pool(),
::google::protobuf::MessageFactory::generated_factory(),
sizeof(HeartbeatReport));
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_system_2fproto_2fheartbeat_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
HeartbeatReport_descriptor_, &HeartbeatReport::default_instance());
}
} // namespace
void protobuf_ShutdownFile_system_2fproto_2fheartbeat_2eproto() {
delete HeartbeatReport::default_instance_;
delete HeartbeatReport_reflection_;
}
void protobuf_AddDesc_system_2fproto_2fheartbeat_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\034system/proto/heartbeat.proto\022\002PS\"\373\002\n\017H"
"eartbeatReport\022\022\n\007task_id\030\001 \001(\005:\0010\022\020\n\010ho"
"stname\030\016 \001(\t\022\033\n\023seconds_since_epoch\030\002 \001("
"\r\022\030\n\020total_time_milli\030\r \001(\r\022\027\n\017busy_time"
"_milli\030\003 \001(\r\022\021\n\tnet_in_mb\030\004 \001(\r\022\022\n\nnet_o"
"ut_mb\030\005 \001(\r\022\031\n\021process_cpu_usage\030\006 \001(\r\022\026"
"\n\016host_cpu_usage\030\007 \001(\r\022\026\n\016process_rss_mb"
"\030\010 \001(\r\022\027\n\017process_virt_mb\030\t \001(\r\022\026\n\016host_"
"in_use_gb\030\n \001(\r\022\036\n\026host_in_use_percentag"
"e\030\017 \001(\r\022\026\n\016host_net_in_bw\030\013 \001(\r\022\027\n\017host_"
"net_out_bw\030\014 \001(\r", 416);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"system/proto/heartbeat.proto", &protobuf_RegisterTypes);
HeartbeatReport::default_instance_ = new HeartbeatReport();
HeartbeatReport::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_system_2fproto_2fheartbeat_2eproto);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_system_2fproto_2fheartbeat_2eproto {
StaticDescriptorInitializer_system_2fproto_2fheartbeat_2eproto() {
protobuf_AddDesc_system_2fproto_2fheartbeat_2eproto();
}
} static_descriptor_initializer_system_2fproto_2fheartbeat_2eproto_;
// ===================================================================
#ifndef _MSC_VER
const int HeartbeatReport::kTaskIdFieldNumber;
const int HeartbeatReport::kHostnameFieldNumber;
const int HeartbeatReport::kSecondsSinceEpochFieldNumber;
const int HeartbeatReport::kTotalTimeMilliFieldNumber;
const int HeartbeatReport::kBusyTimeMilliFieldNumber;
const int HeartbeatReport::kNetInMbFieldNumber;
const int HeartbeatReport::kNetOutMbFieldNumber;
const int HeartbeatReport::kProcessCpuUsageFieldNumber;
const int HeartbeatReport::kHostCpuUsageFieldNumber;
const int HeartbeatReport::kProcessRssMbFieldNumber;
const int HeartbeatReport::kProcessVirtMbFieldNumber;
const int HeartbeatReport::kHostInUseGbFieldNumber;
const int HeartbeatReport::kHostInUsePercentageFieldNumber;
const int HeartbeatReport::kHostNetInBwFieldNumber;
const int HeartbeatReport::kHostNetOutBwFieldNumber;
#endif // !_MSC_VER
HeartbeatReport::HeartbeatReport()
: ::google::protobuf::Message() {
SharedCtor();
}
void HeartbeatReport::InitAsDefaultInstance() {
}
HeartbeatReport::HeartbeatReport(const HeartbeatReport& from)
: ::google::protobuf::Message() {
SharedCtor();
MergeFrom(from);
}
void HeartbeatReport::SharedCtor() {
_cached_size_ = 0;
task_id_ = 0;
hostname_ = const_cast< ::std::string*>(&::google::protobuf::internal::kEmptyString);
seconds_since_epoch_ = 0u;
total_time_milli_ = 0u;
busy_time_milli_ = 0u;
net_in_mb_ = 0u;
net_out_mb_ = 0u;
process_cpu_usage_ = 0u;
host_cpu_usage_ = 0u;
process_rss_mb_ = 0u;
process_virt_mb_ = 0u;
host_in_use_gb_ = 0u;
host_in_use_percentage_ = 0u;
host_net_in_bw_ = 0u;
host_net_out_bw_ = 0u;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
HeartbeatReport::~HeartbeatReport() {
SharedDtor();
}
void HeartbeatReport::SharedDtor() {
if (hostname_ != &::google::protobuf::internal::kEmptyString) {
delete hostname_;
}
if (this != default_instance_) {
}
}
void HeartbeatReport::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* HeartbeatReport::descriptor() {
protobuf_AssignDescriptorsOnce();
return HeartbeatReport_descriptor_;
}
const HeartbeatReport& HeartbeatReport::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_system_2fproto_2fheartbeat_2eproto();
return *default_instance_;
}
HeartbeatReport* HeartbeatReport::default_instance_ = NULL;
HeartbeatReport* HeartbeatReport::New() const {
return new HeartbeatReport;
}
void HeartbeatReport::Clear() {
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
task_id_ = 0;
if (has_hostname()) {
if (hostname_ != &::google::protobuf::internal::kEmptyString) {
hostname_->clear();
}
}
seconds_since_epoch_ = 0u;
total_time_milli_ = 0u;
busy_time_milli_ = 0u;
net_in_mb_ = 0u;
net_out_mb_ = 0u;
process_cpu_usage_ = 0u;
}
if (_has_bits_[8 / 32] & (0xffu << (8 % 32))) {
host_cpu_usage_ = 0u;
process_rss_mb_ = 0u;
process_virt_mb_ = 0u;
host_in_use_gb_ = 0u;
host_in_use_percentage_ = 0u;
host_net_in_bw_ = 0u;
host_net_out_bw_ = 0u;
}
::memset(_has_bits_, 0, sizeof(_has_bits_));
mutable_unknown_fields()->Clear();
}
bool HeartbeatReport::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) return false
::google::protobuf::uint32 tag;
while ((tag = input->ReadTag()) != 0) {
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional int32 task_id = 1 [default = 0];
case 1: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
input, &task_id_)));
set_has_task_id();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(16)) goto parse_seconds_since_epoch;
break;
}
// optional uint32 seconds_since_epoch = 2;
case 2: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_seconds_since_epoch:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &seconds_since_epoch_)));
set_has_seconds_since_epoch();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(24)) goto parse_busy_time_milli;
break;
}
// optional uint32 busy_time_milli = 3;
case 3: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_busy_time_milli:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &busy_time_milli_)));
set_has_busy_time_milli();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(32)) goto parse_net_in_mb;
break;
}
// optional uint32 net_in_mb = 4;
case 4: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_net_in_mb:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &net_in_mb_)));
set_has_net_in_mb();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(40)) goto parse_net_out_mb;
break;
}
// optional uint32 net_out_mb = 5;
case 5: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_net_out_mb:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &net_out_mb_)));
set_has_net_out_mb();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(48)) goto parse_process_cpu_usage;
break;
}
// optional uint32 process_cpu_usage = 6;
case 6: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_process_cpu_usage:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &process_cpu_usage_)));
set_has_process_cpu_usage();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(56)) goto parse_host_cpu_usage;
break;
}
// optional uint32 host_cpu_usage = 7;
case 7: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_host_cpu_usage:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &host_cpu_usage_)));
set_has_host_cpu_usage();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(64)) goto parse_process_rss_mb;
break;
}
// optional uint32 process_rss_mb = 8;
case 8: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_process_rss_mb:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &process_rss_mb_)));
set_has_process_rss_mb();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(72)) goto parse_process_virt_mb;
break;
}
// optional uint32 process_virt_mb = 9;
case 9: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_process_virt_mb:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &process_virt_mb_)));
set_has_process_virt_mb();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(80)) goto parse_host_in_use_gb;
break;
}
// optional uint32 host_in_use_gb = 10;
case 10: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_host_in_use_gb:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &host_in_use_gb_)));
set_has_host_in_use_gb();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(88)) goto parse_host_net_in_bw;
break;
}
// optional uint32 host_net_in_bw = 11;
case 11: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_host_net_in_bw:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &host_net_in_bw_)));
set_has_host_net_in_bw();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(96)) goto parse_host_net_out_bw;
break;
}
// optional uint32 host_net_out_bw = 12;
case 12: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_host_net_out_bw:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &host_net_out_bw_)));
set_has_host_net_out_bw();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(104)) goto parse_total_time_milli;
break;
}
// optional uint32 total_time_milli = 13;
case 13: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_total_time_milli:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &total_time_milli_)));
set_has_total_time_milli();
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(114)) goto parse_hostname;
break;
}
// optional string hostname = 14;
case 14: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED) {
parse_hostname:
DO_(::google::protobuf::internal::WireFormatLite::ReadString(
input, this->mutable_hostname()));
::google::protobuf::internal::WireFormat::VerifyUTF8String(
this->hostname().data(), this->hostname().length(),
::google::protobuf::internal::WireFormat::PARSE);
} else {
goto handle_uninterpreted;
}
if (input->ExpectTag(120)) goto parse_host_in_use_percentage;
break;
}
// optional uint32 host_in_use_percentage = 15;
case 15: {
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
parse_host_in_use_percentage:
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::uint32, ::google::protobuf::internal::WireFormatLite::TYPE_UINT32>(
input, &host_in_use_percentage_)));
set_has_host_in_use_percentage();
} else {
goto handle_uninterpreted;
}
if (input->ExpectAtEnd()) return true;
break;
}
default: {
handle_uninterpreted:
if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
return true;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
return true;
#undef DO_
}
void HeartbeatReport::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// optional int32 task_id = 1 [default = 0];
if (has_task_id()) {
::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->task_id(), output);
}
// optional uint32 seconds_since_epoch = 2;
if (has_seconds_since_epoch()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(2, this->seconds_since_epoch(), output);
}
// optional uint32 busy_time_milli = 3;
if (has_busy_time_milli()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(3, this->busy_time_milli(), output);
}
// optional uint32 net_in_mb = 4;
if (has_net_in_mb()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(4, this->net_in_mb(), output);
}
// optional uint32 net_out_mb = 5;
if (has_net_out_mb()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(5, this->net_out_mb(), output);
}
// optional uint32 process_cpu_usage = 6;
if (has_process_cpu_usage()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(6, this->process_cpu_usage(), output);
}
// optional uint32 host_cpu_usage = 7;
if (has_host_cpu_usage()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(7, this->host_cpu_usage(), output);
}
// optional uint32 process_rss_mb = 8;
if (has_process_rss_mb()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(8, this->process_rss_mb(), output);
}
// optional uint32 process_virt_mb = 9;
if (has_process_virt_mb()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(9, this->process_virt_mb(), output);
}
// optional uint32 host_in_use_gb = 10;
if (has_host_in_use_gb()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(10, this->host_in_use_gb(), output);
}
// optional uint32 host_net_in_bw = 11;
if (has_host_net_in_bw()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(11, this->host_net_in_bw(), output);
}
// optional uint32 host_net_out_bw = 12;
if (has_host_net_out_bw()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(12, this->host_net_out_bw(), output);
}
// optional uint32 total_time_milli = 13;
if (has_total_time_milli()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(13, this->total_time_milli(), output);
}
// optional string hostname = 14;
if (has_hostname()) {
::google::protobuf::internal::WireFormat::VerifyUTF8String(
this->hostname().data(), this->hostname().length(),
::google::protobuf::internal::WireFormat::SERIALIZE);
::google::protobuf::internal::WireFormatLite::WriteString(
14, this->hostname(), output);
}
// optional uint32 host_in_use_percentage = 15;
if (has_host_in_use_percentage()) {
::google::protobuf::internal::WireFormatLite::WriteUInt32(15, this->host_in_use_percentage(), output);
}
if (!unknown_fields().empty()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
}
::google::protobuf::uint8* HeartbeatReport::SerializeWithCachedSizesToArray(
::google::protobuf::uint8* target) const {
// optional int32 task_id = 1 [default = 0];
if (has_task_id()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->task_id(), target);
}
// optional uint32 seconds_since_epoch = 2;
if (has_seconds_since_epoch()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(2, this->seconds_since_epoch(), target);
}
// optional uint32 busy_time_milli = 3;
if (has_busy_time_milli()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(3, this->busy_time_milli(), target);
}
// optional uint32 net_in_mb = 4;
if (has_net_in_mb()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(4, this->net_in_mb(), target);
}
// optional uint32 net_out_mb = 5;
if (has_net_out_mb()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(5, this->net_out_mb(), target);
}
// optional uint32 process_cpu_usage = 6;
if (has_process_cpu_usage()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(6, this->process_cpu_usage(), target);
}
// optional uint32 host_cpu_usage = 7;
if (has_host_cpu_usage()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(7, this->host_cpu_usage(), target);
}
// optional uint32 process_rss_mb = 8;
if (has_process_rss_mb()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(8, this->process_rss_mb(), target);
}
// optional uint32 process_virt_mb = 9;
if (has_process_virt_mb()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(9, this->process_virt_mb(), target);
}
// optional uint32 host_in_use_gb = 10;
if (has_host_in_use_gb()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(10, this->host_in_use_gb(), target);
}
// optional uint32 host_net_in_bw = 11;
if (has_host_net_in_bw()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(11, this->host_net_in_bw(), target);
}
// optional uint32 host_net_out_bw = 12;
if (has_host_net_out_bw()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(12, this->host_net_out_bw(), target);
}
// optional uint32 total_time_milli = 13;
if (has_total_time_milli()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(13, this->total_time_milli(), target);
}
// optional string hostname = 14;
if (has_hostname()) {
::google::protobuf::internal::WireFormat::VerifyUTF8String(
this->hostname().data(), this->hostname().length(),
::google::protobuf::internal::WireFormat::SERIALIZE);
target =
::google::protobuf::internal::WireFormatLite::WriteStringToArray(
14, this->hostname(), target);
}
// optional uint32 host_in_use_percentage = 15;
if (has_host_in_use_percentage()) {
target = ::google::protobuf::internal::WireFormatLite::WriteUInt32ToArray(15, this->host_in_use_percentage(), target);
}
if (!unknown_fields().empty()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
return target;
}
int HeartbeatReport::ByteSize() const {
int total_size = 0;
if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
// optional int32 task_id = 1 [default = 0];
if (has_task_id()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(
this->task_id());
}
// optional string hostname = 14;
if (has_hostname()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::StringSize(
this->hostname());
}
// optional uint32 seconds_since_epoch = 2;
if (has_seconds_since_epoch()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->seconds_since_epoch());
}
// optional uint32 total_time_milli = 13;
if (has_total_time_milli()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->total_time_milli());
}
// optional uint32 busy_time_milli = 3;
if (has_busy_time_milli()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->busy_time_milli());
}
// optional uint32 net_in_mb = 4;
if (has_net_in_mb()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->net_in_mb());
}
// optional uint32 net_out_mb = 5;
if (has_net_out_mb()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->net_out_mb());
}
// optional uint32 process_cpu_usage = 6;
if (has_process_cpu_usage()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->process_cpu_usage());
}
}
if (_has_bits_[8 / 32] & (0xffu << (8 % 32))) {
// optional uint32 host_cpu_usage = 7;
if (has_host_cpu_usage()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->host_cpu_usage());
}
// optional uint32 process_rss_mb = 8;
if (has_process_rss_mb()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->process_rss_mb());
}
// optional uint32 process_virt_mb = 9;
if (has_process_virt_mb()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->process_virt_mb());
}
// optional uint32 host_in_use_gb = 10;
if (has_host_in_use_gb()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->host_in_use_gb());
}
// optional uint32 host_in_use_percentage = 15;
if (has_host_in_use_percentage()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->host_in_use_percentage());
}
// optional uint32 host_net_in_bw = 11;
if (has_host_net_in_bw()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->host_net_in_bw());
}
// optional uint32 host_net_out_bw = 12;
if (has_host_net_out_bw()) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::UInt32Size(
this->host_net_out_bw());
}
}
if (!unknown_fields().empty()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void HeartbeatReport::MergeFrom(const ::google::protobuf::Message& from) {
GOOGLE_CHECK_NE(&from, this);
const HeartbeatReport* source =
::google::protobuf::internal::dynamic_cast_if_available<const HeartbeatReport*>(
&from);
if (source == NULL) {
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
MergeFrom(*source);
}
}
void HeartbeatReport::MergeFrom(const HeartbeatReport& from) {
GOOGLE_CHECK_NE(&from, this);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_task_id()) {
set_task_id(from.task_id());
}
if (from.has_hostname()) {
set_hostname(from.hostname());
}
if (from.has_seconds_since_epoch()) {
set_seconds_since_epoch(from.seconds_since_epoch());
}
if (from.has_total_time_milli()) {
set_total_time_milli(from.total_time_milli());
}
if (from.has_busy_time_milli()) {
set_busy_time_milli(from.busy_time_milli());
}
if (from.has_net_in_mb()) {
set_net_in_mb(from.net_in_mb());
}
if (from.has_net_out_mb()) {
set_net_out_mb(from.net_out_mb());
}
if (from.has_process_cpu_usage()) {
set_process_cpu_usage(from.process_cpu_usage());
}
}
if (from._has_bits_[8 / 32] & (0xffu << (8 % 32))) {
if (from.has_host_cpu_usage()) {
set_host_cpu_usage(from.host_cpu_usage());
}
if (from.has_process_rss_mb()) {
set_process_rss_mb(from.process_rss_mb());
}
if (from.has_process_virt_mb()) {
set_process_virt_mb(from.process_virt_mb());
}
if (from.has_host_in_use_gb()) {
set_host_in_use_gb(from.host_in_use_gb());
}
if (from.has_host_in_use_percentage()) {
set_host_in_use_percentage(from.host_in_use_percentage());
}
if (from.has_host_net_in_bw()) {
set_host_net_in_bw(from.host_net_in_bw());
}
if (from.has_host_net_out_bw()) {
set_host_net_out_bw(from.host_net_out_bw());
}
}
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
void HeartbeatReport::CopyFrom(const ::google::protobuf::Message& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
void HeartbeatReport::CopyFrom(const HeartbeatReport& from) {
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool HeartbeatReport::IsInitialized() const {
return true;
}
void HeartbeatReport::Swap(HeartbeatReport* other) {
if (other != this) {
std::swap(task_id_, other->task_id_);
std::swap(hostname_, other->hostname_);
std::swap(seconds_since_epoch_, other->seconds_since_epoch_);
std::swap(total_time_milli_, other->total_time_milli_);
std::swap(busy_time_milli_, other->busy_time_milli_);
std::swap(net_in_mb_, other->net_in_mb_);
std::swap(net_out_mb_, other->net_out_mb_);
std::swap(process_cpu_usage_, other->process_cpu_usage_);
std::swap(host_cpu_usage_, other->host_cpu_usage_);
std::swap(process_rss_mb_, other->process_rss_mb_);
std::swap(process_virt_mb_, other->process_virt_mb_);
std::swap(host_in_use_gb_, other->host_in_use_gb_);
std::swap(host_in_use_percentage_, other->host_in_use_percentage_);
std::swap(host_net_in_bw_, other->host_net_in_bw_);
std::swap(host_net_out_bw_, other->host_net_out_bw_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_unknown_fields_.Swap(&other->_unknown_fields_);
std::swap(_cached_size_, other->_cached_size_);
}
}
::google::protobuf::Metadata HeartbeatReport::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = HeartbeatReport_descriptor_;
metadata.reflection = HeartbeatReport_reflection_;
return metadata;
}
// @@protoc_insertion_point(namespace_scope)
} // namespace PS
// @@protoc_insertion_point(global_scope)
| 36.529476 | 122 | 0.677356 | yipeiw |
f8ee113d78812276f71e6cd6a599f54d34354199 | 729 | hpp | C++ | lib/DeviceConfigurator/DeviceConfigurator.hpp | OscarArgueyo/baliza-ic-dyasc | 33c9f8e577a2315982be5b223bbc3e3c38e23809 | [
"MIT"
] | null | null | null | lib/DeviceConfigurator/DeviceConfigurator.hpp | OscarArgueyo/baliza-ic-dyasc | 33c9f8e577a2315982be5b223bbc3e3c38e23809 | [
"MIT"
] | null | null | null | lib/DeviceConfigurator/DeviceConfigurator.hpp | OscarArgueyo/baliza-ic-dyasc | 33c9f8e577a2315982be5b223bbc3e3c38e23809 | [
"MIT"
] | null | null | null | #include <FS.h> //this needs to be first, or it all crashes and burns...
#include "SPIFFS.h"
#include <Arduino.h>
#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
#include <WiFi.h>
//needed for library
#include <DNSServer.h>
#include <WebServer.h>
#include <WiFiManager.h>
#ifndef DeviceConfigurator_HPP
#define DeviceConfigurator_HPP
class DeviceConfigurator
{
private:
public:
DeviceConfigurator();
void setAPCredentials(String ssid , String password);
void setCICredentials(String url , String token);
void setup();
void loop();
void cleanFileSystem();
bool isConnected();
String getURLEndpoint();
String getICToken();
};
#endif | 23.516129 | 90 | 0.684499 | OscarArgueyo |
f8ee19e56239025529cc96b901820b9086f333b1 | 14,580 | cpp | C++ | src/mongo/db/cst/cst_match_translation.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/cst/cst_match_translation.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/cst/cst_match_translation.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2020-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include <algorithm>
#include <boost/intrusive_ptr.hpp>
#include <boost/optional.hpp>
#include <iterator>
#include "mongo/base/string_data.h"
#include "mongo/bson/bsonmisc.h"
#include "mongo/db/cst/c_node.h"
#include "mongo/db/cst/cst_match_translation.h"
#include "mongo/db/cst/cst_pipeline_translation.h"
#include "mongo/db/cst/key_fieldname.h"
#include "mongo/db/cst/key_value.h"
#include "mongo/db/matcher/expression_expr.h"
#include "mongo/db/matcher/expression_tree.h"
#include "mongo/db/matcher/matcher_type_set.h"
#include "mongo/util/visit_helper.h"
namespace mongo::cst_match_translation {
namespace {
std::unique_ptr<MatchExpression> translateMatchPredicate(
const CNode::Fieldname& fieldName,
const CNode& cst,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback& extensionsCallback);
std::unique_ptr<MatchExpression> translatePathExpression(const UserFieldname& fieldName,
const CNode::ObjectChildren& object);
/**
* Walk an array of nodes and produce a vector of MatchExpressions.
*/
template <class Type>
std::unique_ptr<Type> translateTreeExpr(const CNode::ArrayChildren& array,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback& extensionsCallback) {
auto expr = std::make_unique<Type>();
for (auto&& node : array) {
// Tree expressions require each element to be it's own match expression object.
expr->add(translateMatchExpression(node, expCtx, extensionsCallback));
}
return expr;
}
// Handles predicates of the form <fieldname>: { $not: <argument> }
std::unique_ptr<MatchExpression> translateNot(const UserFieldname& fieldName,
const CNode& argument) {
// $not can accept a regex or an object expression.
if (auto regex = stdx::get_if<UserRegex>(&argument.payload)) {
auto regexExpr =
std::make_unique<RegexMatchExpression>(fieldName, regex->pattern, regex->flags);
return std::make_unique<NotMatchExpression>(std::move(regexExpr));
}
auto root = std::make_unique<AndMatchExpression>();
root->add(
translatePathExpression(fieldName, stdx::get<CNode::ObjectChildren>(argument.payload)));
return std::make_unique<NotMatchExpression>(std::move(root));
}
std::unique_ptr<MatchExpression> translateExists(const CNode::Fieldname& fieldName,
const CNode& argument) {
auto root = std::make_unique<ExistsMatchExpression>(stdx::get<UserFieldname>(fieldName));
if (stdx::visit(
visit_helper::Overloaded{
[&](const UserLong& userLong) { return userLong != 0; },
[&](const UserDouble& userDbl) { return userDbl != 0; },
[&](const UserDecimal& userDc) { return userDc.isNotEqual(Decimal128(0)); },
[&](const UserInt& userInt) { return userInt != 0; },
[&](const UserBoolean& b) { return b; },
[&](const UserNull&) { return false; },
[&](const UserUndefined&) { return false; },
[&](auto&&) { return true; }},
argument.payload)) {
return root;
}
return std::make_unique<NotMatchExpression>(root.release());
}
MatcherTypeSet getMatcherTypeSet(const CNode& argument) {
MatcherTypeSet ts;
auto add_individual_to_type_set = [&](const CNode& a) {
return stdx::visit(
visit_helper::Overloaded{
[&](const UserLong& userLong) {
auto valueAsInt =
BSON("" << userLong).firstElement().parseIntegerElementToInt();
ts.bsonTypes.insert(static_cast<BSONType>(valueAsInt.getValue()));
},
[&](const UserDouble& userDbl) {
auto valueAsInt = BSON("" << userDbl).firstElement().parseIntegerElementToInt();
ts.bsonTypes.insert(static_cast<BSONType>(valueAsInt.getValue()));
},
[&](const UserDecimal& userDc) {
auto valueAsInt = BSON("" << userDc).firstElement().parseIntegerElementToInt();
ts.bsonTypes.insert(static_cast<BSONType>(valueAsInt.getValue()));
},
[&](const UserInt& userInt) {
auto valueAsInt = BSON("" << userInt).firstElement().parseIntegerElementToInt();
ts.bsonTypes.insert(static_cast<BSONType>(valueAsInt.getValue()));
},
[&](const UserString& s) {
if (StringData{s} == MatcherTypeSet::kMatchesAllNumbersAlias) {
ts.allNumbers = true;
return;
}
auto optValue = findBSONTypeAlias(s);
invariant(optValue);
ts.bsonTypes.insert(*optValue);
},
[&](auto&&) { MONGO_UNREACHABLE; }},
a.payload);
};
if (auto children = stdx::get_if<CNode::ArrayChildren>(&argument.payload)) {
for (auto child : (*children)) {
add_individual_to_type_set(child);
}
} else {
add_individual_to_type_set(argument);
}
return ts;
}
// Handles predicates of the form <fieldname>: { ... }
// For example:
// { abc: {$not: 5} }
// { abc: {$eq: 0} }
// { abc: {$gt: 0, $lt: 2} }
// Examples of predicates not handled here:
// { abc: 5 }
// { $expr: ... }
// { $where: "return 1" }
// Note, this function does not require an ExpressionContext.
// The only MatchExpression that requires an ExpressionContext is $expr
// (if you include $where, which can desugar to $expr + $function).
std::unique_ptr<MatchExpression> translatePathExpression(const UserFieldname& fieldName,
const CNode::ObjectChildren& object) {
for (auto&& [op, argument] : object) {
switch (stdx::get<KeyFieldname>(op)) {
case KeyFieldname::notExpr:
return translateNot(fieldName, argument);
case KeyFieldname::existsExpr:
return translateExists(fieldName, argument);
case KeyFieldname::type:
return std::make_unique<TypeMatchExpression>(fieldName,
getMatcherTypeSet(argument));
case KeyFieldname::matchMod: {
const auto divisor =
stdx::get<CNode::ArrayChildren>(argument.payload)[0].numberInt();
const auto remainder =
stdx::get<CNode::ArrayChildren>(argument.payload)[1].numberInt();
return std::make_unique<ModMatchExpression>(fieldName, divisor, remainder);
}
default:
MONGO_UNREACHABLE;
}
}
MONGO_UNREACHABLE;
}
// Take a variant and either get (by copying) the T it holds, or construct a default value using
// the callable. For example:
// getOr<int>(123, []() { return 0; }) == 123
// getOr<int>("x", []() { return 0; }) == 0
template <class T, class V, class F>
T getOr(const V& myVariant, F makeDefaultValue) {
if (auto* value = stdx::get_if<T>(&myVariant)) {
return *value;
} else {
return makeDefaultValue();
}
}
// Handles predicates of the form <fieldname>: <anything>
// For example:
// { abc: 5 }
// { abc: {$lt: 5} }
// Examples of predicates not handled here:
// { $where: "return 1" }
// { $and: ... }
std::unique_ptr<MatchExpression> translateMatchPredicate(
const CNode::Fieldname& fieldName,
const CNode& cst,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback& extensionsCallback) {
if (auto keyField = stdx::get_if<KeyFieldname>(&fieldName)) {
// Top level match expression.
switch (*keyField) {
case KeyFieldname::andExpr:
return translateTreeExpr<AndMatchExpression>(
cst.arrayChildren(), expCtx, extensionsCallback);
case KeyFieldname::orExpr:
return translateTreeExpr<OrMatchExpression>(
cst.arrayChildren(), expCtx, extensionsCallback);
case KeyFieldname::norExpr:
return translateTreeExpr<NorMatchExpression>(
cst.arrayChildren(), expCtx, extensionsCallback);
case KeyFieldname::commentExpr:
// comment expr is not added to the tree.
return nullptr;
case KeyFieldname::expr: {
// The ExprMatchExpression maintains (shared) ownership of expCtx,
// which the Expression from translateExpression depends on.
return std::make_unique<ExprMatchExpression>(
cst_pipeline_translation::translateExpression(
cst, expCtx.get(), expCtx->variablesParseState),
expCtx);
}
case KeyFieldname::text: {
const auto& args = cst.objectChildren();
dassert(verifyFieldnames(
{
KeyFieldname::caseSensitive,
KeyFieldname::diacriticSensitive,
KeyFieldname::language,
KeyFieldname::search,
},
args));
TextMatchExpressionBase::TextParams params;
params.caseSensitive = getOr<bool>(args[0].second.payload, []() {
return TextMatchExpressionBase::kCaseSensitiveDefault;
});
params.diacriticSensitive = getOr<bool>(args[1].second.payload, []() {
return TextMatchExpressionBase::kDiacriticSensitiveDefault;
});
params.language = getOr<std::string>(args[2].second.payload, []() { return ""s; });
params.query = stdx::get<std::string>(args[3].second.payload);
return extensionsCallback.createText(std::move(params));
}
case KeyFieldname::where: {
std::string code;
if (auto str = stdx::get_if<UserString>(&cst.payload)) {
code = *str;
} else if (auto js = stdx::get_if<UserJavascript>(&cst.payload)) {
code = std::string{js->code};
} else {
MONGO_UNREACHABLE;
}
return extensionsCallback.createWhere(expCtx, {std::move(code)});
}
default:
MONGO_UNREACHABLE;
}
} else {
// Expression is over a user fieldname.
return stdx::visit(
visit_helper::Overloaded{
[&](const CNode::ObjectChildren& userObject) -> std::unique_ptr<MatchExpression> {
return translatePathExpression(stdx::get<UserFieldname>(fieldName), userObject);
},
[&](const CNode::ArrayChildren& userObject) -> std::unique_ptr<MatchExpression> {
MONGO_UNREACHABLE;
},
// Other types are always treated as equality predicates.
[&](auto&& userValue) -> std::unique_ptr<MatchExpression> {
return std::make_unique<EqualityMatchExpression>(
StringData{stdx::get<UserFieldname>(fieldName)},
cst_pipeline_translation::translateLiteralLeaf(cst),
nullptr, /* TODO SERVER-49486: Add ErrorAnnotation for MatchExpressions */
expCtx->getCollator());
}},
cst.payload);
}
MONGO_UNREACHABLE;
}
} // namespace
std::unique_ptr<MatchExpression> translateMatchExpression(
const CNode& cst,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback& extensionsCallback) {
auto root = std::make_unique<AndMatchExpression>();
for (const auto& [fieldName, expr] : cst.objectChildren()) {
// A nullptr for 'translatedExpression' indicates that the particular operator should not
// be added to 'root'. The $comment operator currently follows this convention.
if (auto translatedExpression =
translateMatchPredicate(fieldName, expr, expCtx, extensionsCallback);
translatedExpression) {
root->add(std::move(translatedExpression));
}
}
return root;
}
bool verifyFieldnames(const std::vector<CNode::Fieldname>& expected,
const std::vector<std::pair<CNode::Fieldname, CNode>>& actual) {
if (expected.size() != actual.size())
return false;
for (size_t i = 0; i < expected.size(); ++i) {
if (expected[i] != actual[i].first)
return false;
}
return true;
}
} // namespace mongo::cst_match_translation
| 44.181818 | 100 | 0.593827 | benety |
f8ee35e5a1fc89be617224c7ecc7149ca2a835c7 | 113 | hpp | C++ | examples/SimpleProject/src/simple_private.hpp | Neumann-A/CMakeJSON | 395c4fa4588f80727ddaddd7b61276c6823be6b8 | [
"BSL-1.0"
] | 10 | 2021-03-02T10:01:57.000Z | 2021-11-01T11:27:36.000Z | examples/SimpleProject/src/simple_private.hpp | Neumann-A/CMakeJSON | 395c4fa4588f80727ddaddd7b61276c6823be6b8 | [
"BSL-1.0"
] | 1 | 2021-03-03T10:02:28.000Z | 2021-03-03T14:17:16.000Z | examples/SimpleProject/src/simple_private.hpp | Neumann-A/CMakeJSON | 395c4fa4588f80727ddaddd7b61276c6823be6b8 | [
"BSL-1.0"
] | null | null | null |
#include <string_view>
static constexpr std::string_view hello_private = "Hello from the private libs parts!"; | 22.6 | 87 | 0.778761 | Neumann-A |
f8ef62c4ed42e265af5d6992862863bde4556aaa | 2,274 | hpp | C++ | libs/render/include/hamon/render/gl/wgl/context.hpp | shibainuudon/HamonEngine | 508a69b0cf589ccb2e5d403ce9e78ff2b85cc058 | [
"MIT"
] | null | null | null | libs/render/include/hamon/render/gl/wgl/context.hpp | shibainuudon/HamonEngine | 508a69b0cf589ccb2e5d403ce9e78ff2b85cc058 | [
"MIT"
] | 21 | 2022-03-02T13:11:59.000Z | 2022-03-30T15:12:41.000Z | libs/render/include/hamon/render/gl/wgl/context.hpp | shibainuudon/HamonEngine | 508a69b0cf589ccb2e5d403ce9e78ff2b85cc058 | [
"MIT"
] | null | null | null | /**
* @file context.hpp
*
* @brief Context
*/
#ifndef HAMON_RENDER_GL_WGL_CONTEXT_HPP
#define HAMON_RENDER_GL_WGL_CONTEXT_HPP
#include <hamon/window.hpp>
#include <hamon/render/gl/wgl/wglext.hpp>
namespace hamon
{
inline namespace render
{
namespace gl
{
class Context
{
public:
explicit Context(Window const& window)
: m_hwnd(window.GetNativeHandle())
, m_hdc(::GetDC(m_hwnd))
{
SetPixelFormat(m_hdc, 32);
// 仮のGLコンテキストの作成
auto hglrc_dummy = ::wglCreateContext(m_hdc);
::wglMakeCurrent(m_hdc, hglrc_dummy);
// 使用する OpenGL のバージョンとプロファイルの指定
static const int att[] =
{
WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
WGL_CONTEXT_MINOR_VERSION_ARB, 3,
WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_DEBUG_BIT_ARB,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0,
};
// 使用するGLコンテキストの作成
m_hglrc = gl::wglCreateContextAttribsARB(m_hdc, NULL, att);
::wglMakeCurrent(m_hdc, m_hglrc);
// 仮のGLコンテキストの削除
::wglDeleteContext(hglrc_dummy);
}
~Context()
{
::wglDeleteContext(m_hglrc);
::ReleaseDC(m_hwnd, m_hdc);
}
void SwapBuffers(void)
{
::SwapBuffers(m_hdc);
}
private:
static void SetPixelFormat(::HDC hdc, int color_depth)
{
::PIXELFORMATDESCRIPTOR const pfd =
{
sizeof(::PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, //Flags
PFD_TYPE_RGBA, //The kind of framebuffer. RGBA or palette.
(::BYTE)color_depth, //Colordepth of the framebuffer.
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
24, //Number of bits for the depthbuffer
8, //Number of bits for the stencilbuffer
0, //Number of Aux buffers in the framebuffer.
PFD_MAIN_PLANE,
0,
0, 0, 0
};
int const format = ::ChoosePixelFormat(hdc, &pfd);
if (format == 0)
{
return; // 該当するピクセルフォーマットが無い
}
// OpenGLが使うデバイスコンテキストに指定のピクセルフォーマットをセット
if (!::SetPixelFormat(hdc, format, &pfd))
{
return; // DCへフォーマットを設定するのに失敗
}
}
private:
::HWND m_hwnd = nullptr;
::HDC m_hdc = nullptr;
::HGLRC m_hglrc = nullptr;
};
} // namespace gl
} // inline namespace render
} // namespace hamon
#endif // HAMON_RENDER_GL_WGL_CONTEXT_HPP
| 19.947368 | 71 | 0.656992 | shibainuudon |
f8f4a9ff2bdd920ef8f40c94203b80965f96b06c | 1,913 | cpp | C++ | phxrpc/network/test_echo_client.cpp | bombshen/phxrpc | 465db10bd4c4bf6d95f6e8b431cc7abcda731ffb | [
"BSD-3-Clause"
] | 1,117 | 2017-08-02T06:03:59.000Z | 2022-03-31T18:36:53.000Z | phxrpc/network/test_echo_client.cpp | kuiwang/wechat-phxrpc | a5f5af70f27406880013d49780fc4819ba3b75ef | [
"BSD-3-Clause"
] | 31 | 2017-08-16T08:43:35.000Z | 2021-02-13T22:49:25.000Z | phxrpc/network/test_echo_client.cpp | kuiwang/wechat-phxrpc | a5f5af70f27406880013d49780fc4819ba3b75ef | [
"BSD-3-Clause"
] | 359 | 2017-08-04T07:32:41.000Z | 2022-03-31T10:19:45.000Z | /*
Tencent is pleased to support the open source community by making
PhxRPC available.
Copyright (C) 2016 THL A29 Limited, a Tencent company.
All rights reserved.
Licensed under the BSD 3-Clause License (the "License"); you may
not use this file except in compliance with the License. You may
obtain a copy of the License at
https://opensource.org/licenses/BSD-3-Clause
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.
See the AUTHORS file for names of contributors.
*/
#include <assert.h>
#include <memory>
#include <errno.h>
#include <string.h>
#include "socket_stream_block.h"
void test(int times) {
int step = (times < 20 ? 20 : times) / 20;
for (int i = 0; i < 20; i++) {
phxrpc::BlockTcpStream stream;
if (!phxrpc::BlockTcpUtils::Open(&stream, "127.0.0.1", 16161, 100, NULL, 0)) {
printf("Connect fail\n");
return;
}
char line[128] = { 0 };
if (!stream.getlineWithTrimRight(line, sizeof(line)).good()) {
printf("Welcome message fail, errno %d, %s\n", errno, strerror(errno));
return;
}
for (int i = 0; i < step; i++) {
stream << i << std::endl;
if (stream.getline(line, sizeof(line)).good()) {
assert(i == atoi(line));
} else {
break;
}
}
stream << "quit" << std::endl;
printf("#");
fflush (stdout);
}
printf("\n");
}
int main(int argc, char * argv[]) {
if (argc < 2) {
printf("Usage: %s <run times>\n", argv[0]);
return 0;
}
test(atoi(argv[1]));
return 0;
}
| 25.171053 | 86 | 0.594354 | bombshen |
f8fb86fb22532022ed7a5dda52dbbeaf3a3fc9ac | 12,315 | cpp | C++ | Source/Diagnostics/FieldIO.cpp | MaxThevenet/WarpX | d9606e22c2feb35bf2cfcd8843db7dfcbaf6c2f6 | [
"BSD-3-Clause-LBNL"
] | null | null | null | Source/Diagnostics/FieldIO.cpp | MaxThevenet/WarpX | d9606e22c2feb35bf2cfcd8843db7dfcbaf6c2f6 | [
"BSD-3-Clause-LBNL"
] | 1 | 2019-09-09T22:37:32.000Z | 2019-09-09T22:37:32.000Z | Source/Diagnostics/FieldIO.cpp | MaxThevenet/WarpX | d9606e22c2feb35bf2cfcd8843db7dfcbaf6c2f6 | [
"BSD-3-Clause-LBNL"
] | null | null | null |
#include <WarpX.H>
#include <FieldIO.H>
using namespace amrex;
void
PackPlotDataPtrs (Vector<const MultiFab*>& pmf,
const std::array<std::unique_ptr<MultiFab>,3>& data)
{
BL_ASSERT(pmf.size() == AMREX_SPACEDIM);
#if (AMREX_SPACEDIM == 3)
pmf[0] = data[0].get();
pmf[1] = data[1].get();
pmf[2] = data[2].get();
#elif (AMREX_SPACEDIM == 2)
pmf[0] = data[0].get();
pmf[1] = data[2].get();
#endif
}
/** \brief Takes an array of 3 MultiFab `vector_field`
* (representing the x, y, z components of a vector),
* averages it to the cell center, and stores the
* resulting MultiFab in mf_avg (in the components dcomp to dcomp+2)
*/
void
AverageAndPackVectorField( MultiFab& mf_avg,
const std::array< std::unique_ptr<MultiFab>, 3 >& vector_field,
const int dcomp, const int ngrow )
{
// The object below is temporary, and is needed because
// `average_edge_to_cellcenter` requires fields to be passed as Vector
Vector<const MultiFab*> srcmf(AMREX_SPACEDIM);
// Check the type of staggering of the 3-component `vector_field`
// and average accordingly:
// - Fully cell-centered field (no average needed; simply copy)
if ( vector_field[0]->is_cell_centered() ){
MultiFab::Copy( mf_avg, *vector_field[0], 0, dcomp , 1, ngrow);
MultiFab::Copy( mf_avg, *vector_field[1], 0, dcomp+1, 1, ngrow);
MultiFab::Copy( mf_avg, *vector_field[2], 0, dcomp+2, 1, ngrow);
// - Fully nodal
} else if ( vector_field[0]->is_nodal() ){
amrex::average_node_to_cellcenter( mf_avg, dcomp ,
*vector_field[0], 0, 1, ngrow);
amrex::average_node_to_cellcenter( mf_avg, dcomp+1,
*vector_field[1], 0, 1, ngrow);
amrex::average_node_to_cellcenter( mf_avg, dcomp+2,
*vector_field[2], 0, 1, ngrow);
// - Face centered, in the same way as B on a Yee grid
} else if ( vector_field[0]->is_nodal(0) ){
PackPlotDataPtrs(srcmf, vector_field);
amrex::average_face_to_cellcenter( mf_avg, dcomp, srcmf, ngrow);
#if (AMREX_SPACEDIM == 2)
MultiFab::Copy( mf_avg, mf_avg, dcomp+1, dcomp+2, 1, ngrow);
MultiFab::Copy( mf_avg, *vector_field[1], 0, dcomp+1, 1, ngrow);
#endif
// - Edge centered, in the same way as E on a Yee grid
} else if ( !vector_field[0]->is_nodal(0) ){
PackPlotDataPtrs(srcmf, vector_field);
amrex::average_edge_to_cellcenter( mf_avg, dcomp, srcmf, ngrow);
#if (AMREX_SPACEDIM == 2)
MultiFab::Copy( mf_avg, mf_avg, dcomp+1, dcomp+2, 1, ngrow);
amrex::average_node_to_cellcenter( mf_avg, dcomp+1,
*vector_field[1], 0, 1, ngrow);
#endif
} else {
amrex::Abort("Unknown staggering.");
}
}
/** \brief Take a MultiFab `scalar_field`
* averages it to the cell center, and stores the
* resulting MultiFab in mf_avg (in the components dcomp)
*/
void
AverageAndPackScalarField( MultiFab& mf_avg,
const MultiFab & scalar_field,
const int dcomp, const int ngrow )
{
// Check the type of staggering of the 3-component `vector_field`
// and average accordingly:
// - Fully cell-centered field (no average needed; simply copy)
if ( scalar_field.is_cell_centered() ){
MultiFab::Copy( mf_avg, scalar_field, 0, dcomp, 1, ngrow);
// - Fully nodal
} else if ( scalar_field.is_nodal() ){
amrex::average_node_to_cellcenter( mf_avg, dcomp, scalar_field, 0, 1, ngrow);
} else {
amrex::Abort("Unknown staggering.");
}
}
/** \brief Write the different fields that are meant for output,
* into the vector of MultiFab `mf_avg` (one MultiFab per level)
* after averaging them to the cell centers.
*/
void
WarpX::AverageAndPackFields ( Vector<std::string>& varnames,
amrex::Vector<MultiFab>& mf_avg, const int ngrow) const
{
// Count how many different fields should be written (ncomp)
const int ncomp = 3*3
+ static_cast<int>(plot_part_per_cell)
+ static_cast<int>(plot_part_per_grid)
+ static_cast<int>(plot_part_per_proc)
+ static_cast<int>(plot_proc_number)
+ static_cast<int>(plot_divb)
+ static_cast<int>(plot_dive)
+ static_cast<int>(plot_rho)
+ static_cast<int>(plot_F)
+ static_cast<int>(plot_finepatch)*6
+ static_cast<int>(plot_crsepatch)*6
+ static_cast<int>(costs[0] != nullptr);
// Loop over levels of refinement
for (int lev = 0; lev <= finest_level; ++lev)
{
// Allocate pointers to the `ncomp` fields that will be added
mf_avg.push_back( MultiFab(grids[lev], dmap[lev], ncomp, ngrow));
// Go through the different fields, pack them into mf_avg[lev],
// add the corresponding names to `varnames` and increment dcomp
int dcomp = 0;
AverageAndPackVectorField(mf_avg[lev], current_fp[lev], dcomp, ngrow);
if(lev==0) for(auto name:{"jx","jy","jz"}) varnames.push_back(name);
dcomp += 3;
AverageAndPackVectorField(mf_avg[lev], Efield_aux[lev], dcomp, ngrow);
if(lev==0) for(auto name:{"Ex","Ey","Ez"}) varnames.push_back(name);
dcomp += 3;
AverageAndPackVectorField(mf_avg[lev], Bfield_aux[lev], dcomp, ngrow);
if(lev==0) for(auto name:{"Bx","By","Bz"}) varnames.push_back(name);
dcomp += 3;
if (plot_part_per_cell)
{
MultiFab temp_dat(grids[lev],mf_avg[lev].DistributionMap(),1,0);
temp_dat.setVal(0);
// MultiFab containing number of particles in each cell
mypc->Increment(temp_dat, lev);
AverageAndPackScalarField( mf_avg[lev], temp_dat, dcomp, ngrow );
if(lev==0) varnames.push_back("part_per_cell");
dcomp += 1;
}
if (plot_part_per_grid)
{
const Vector<long>& npart_in_grid = mypc->NumberOfParticlesInGrid(lev);
// MultiFab containing number of particles per grid
// (stored as constant for all cells in each grid)
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(mf_avg[lev]); mfi.isValid(); ++mfi) {
(mf_avg[lev])[mfi].setVal(static_cast<Real>(npart_in_grid[mfi.index()]),
dcomp);
}
if(lev==0) varnames.push_back("part_per_grid");
dcomp += 1;
}
if (plot_part_per_proc)
{
const Vector<long>& npart_in_grid = mypc->NumberOfParticlesInGrid(lev);
// MultiFab containing number of particles per process
// (stored as constant for all cells in each grid)
long n_per_proc = 0;
#ifdef _OPENMP
#pragma omp parallel reduction(+:n_per_proc)
#endif
for (MFIter mfi(mf_avg[lev]); mfi.isValid(); ++mfi) {
n_per_proc += npart_in_grid[mfi.index()];
}
mf_avg[lev].setVal(static_cast<Real>(n_per_proc), dcomp,1);
if(lev==0) varnames.push_back("part_per_proc");
dcomp += 1;
}
if (plot_proc_number)
{
// MultiFab containing the Processor ID
#ifdef _OPENMP
#pragma omp parallel
#endif
for (MFIter mfi(mf_avg[lev]); mfi.isValid(); ++mfi) {
(mf_avg[lev])[mfi].setVal(static_cast<Real>(ParallelDescriptor::MyProc()),
dcomp);
}
if(lev==0) varnames.push_back("proc_number");
dcomp += 1;
}
if (plot_divb)
{
if (do_nodal) amrex::Abort("TODO: do_nodal && plot_divb");
ComputeDivB(mf_avg[lev], dcomp,
{Bfield_aux[lev][0].get(),
Bfield_aux[lev][1].get(),
Bfield_aux[lev][2].get()},
WarpX::CellSize(lev)
);
if(lev == 0) varnames.push_back("divB");
dcomp += 1;
}
if (plot_dive)
{
if (do_nodal) amrex::Abort("TODO: do_nodal && plot_dive");
const BoxArray& ba = amrex::convert(boxArray(lev),IntVect::TheUnitVector());
MultiFab dive(ba,DistributionMap(lev),1,0);
ComputeDivE( dive, 0,
{Efield_aux[lev][0].get(),
Efield_aux[lev][1].get(),
Efield_aux[lev][2].get()},
WarpX::CellSize(lev)
);
AverageAndPackScalarField( mf_avg[lev], dive, dcomp, ngrow );
if(lev == 0) varnames.push_back("divE");
dcomp += 1;
}
if (plot_rho)
{
AverageAndPackScalarField( mf_avg[lev], *rho_fp[lev], dcomp, ngrow );
if(lev == 0) varnames.push_back("rho");
dcomp += 1;
}
if (plot_F)
{
AverageAndPackScalarField( mf_avg[lev], *F_fp[lev], dcomp, ngrow);
if(lev == 0) varnames.push_back("F");
dcomp += 1;
}
if (plot_finepatch)
{
AverageAndPackVectorField( mf_avg[lev], Efield_fp[lev], dcomp, ngrow );
if(lev==0) for(auto name:{"Ex_fp","Ey_fp","Ez_fp"}) varnames.push_back(name);
dcomp += 3;
AverageAndPackVectorField( mf_avg[lev], Bfield_fp[lev], dcomp, ngrow );
if(lev==0) for(auto name:{"Bx_fp","By_fp","Bz_fp"}) varnames.push_back(name);
dcomp += 3;
}
if (plot_crsepatch)
{
if (lev == 0)
{
mf_avg[lev].setVal(0.0, dcomp, 3, ngrow);
}
else
{
if (do_nodal) amrex::Abort("TODO: do_nodal && plot_crsepatch");
std::array<std::unique_ptr<MultiFab>, 3> E = getInterpolatedE(lev);
AverageAndPackVectorField( mf_avg[lev], E, dcomp, ngrow );
}
if(lev==0) for(auto name:{"Ex_cp","Ey_cp","Ez_cp"}) varnames.push_back(name);
dcomp += 3;
// now the magnetic field
if (lev == 0)
{
mf_avg[lev].setVal(0.0, dcomp, 3, ngrow);
}
else
{
if (do_nodal) amrex::Abort("TODO: do_nodal && plot_crsepatch");
std::array<std::unique_ptr<MultiFab>, 3> B = getInterpolatedB(lev);
AverageAndPackVectorField( mf_avg[lev], B, dcomp, ngrow );
}
if(lev==0) for(auto name:{"Bx_cp","By_cp","Bz_cp"}) varnames.push_back(name);
dcomp += 3;
}
if (costs[0] != nullptr)
{
AverageAndPackScalarField( mf_avg[lev], *costs[lev], dcomp, ngrow );
if(lev==0) varnames.push_back("costs");
dcomp += 1;
}
BL_ASSERT(dcomp == ncomp);
} // end loop over levels of refinement
};
/** \brief Reduce the size of all the fields in `source_mf`
* by `coarse_ratio` and store the results in `coarse_mf`.
* Calculate the corresponding coarse Geometry from `source_geom`
* and store the results in `coarse_geom` */
void
coarsenCellCenteredFields(
Vector<MultiFab>& coarse_mf, Vector<Geometry>& coarse_geom,
const Vector<MultiFab>& source_mf, const Vector<Geometry>& source_geom,
int coarse_ratio, int finest_level )
{
// Check that the Vectors to be filled have an initial size of 0
AMREX_ALWAYS_ASSERT( coarse_mf.size()==0 );
AMREX_ALWAYS_ASSERT( coarse_geom.size()==0 );
// Fill the vectors with one element per level
int ncomp = source_mf[0].nComp();
for (int lev=0; lev<=finest_level; lev++) {
AMREX_ALWAYS_ASSERT( source_mf[lev].is_cell_centered() );
coarse_geom.push_back(amrex::coarsen( source_geom[lev], IntVect(coarse_ratio)));
BoxArray small_ba = amrex::coarsen(source_mf[lev].boxArray(), coarse_ratio);
coarse_mf.push_back( MultiFab(small_ba, source_mf[lev].DistributionMap(), ncomp, 0) );
average_down(source_mf[lev], coarse_mf[lev], 0, ncomp, IntVect(coarse_ratio));
}
};
| 37.318182 | 94 | 0.571092 | MaxThevenet |
f8fba5980867d0de70da86e2c3bd1df51d05e3e6 | 46,350 | cpp | C++ | extras/soundio/sd_play_all/sd_play_all.cpp | newdigate/teensy-resampling-sdreader | 98572b77f5e23e0d39bb10a846f3e0772d77334d | [
"MIT"
] | 18 | 2020-07-19T15:27:21.000Z | 2022-01-18T22:25:47.000Z | extras/soundio/sd_play_all/sd_play_all.cpp | newdigate/teensy-resampling-sdreader | 98572b77f5e23e0d39bb10a846f3e0772d77334d | [
"MIT"
] | 13 | 2020-12-02T14:05:42.000Z | 2021-09-24T20:45:41.000Z | extras/soundio/sd_play_all/sd_play_all.cpp | newdigate/teensy-resampling-sdreader | 98572b77f5e23e0d39bb10a846f3e0772d77334d | [
"MIT"
] | 7 | 2021-01-31T22:25:18.000Z | 2021-08-14T02:25:00.000Z | // Plays a RAW (16-bit signed) PCM audio file at slower or faster rate
// this example plays a sample stored in an array
#include <Arduino.h>
#include <Audio.h>
#include "playsdresmp.h"
#include "output_soundio.h"
#include <soundio/soundio.h>
#include <SD.h>
#include <iostream>
#include <execinfo.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <string>
#include <cassert>
// GUItool: begin automatically generated code
AudioPlaySdResmp playSd1; //xy=306,225
AudioRecordQueue queue1; //xy=609,267
AudioOutputSoundIO sio_out1; //xy=612,224
AudioConnection patchCord1(playSd1, 0, sio_out1, 0);
AudioConnection patchCord2(playSd1, 1, sio_out1, 1);
AudioConnection patchCord3(playSd1, 0, queue1, 0);
// GUItool: end automatically generated code
char** _filenames = nullptr;
uint16_t _fileIndex = 0;
uint16_t _numWaveFiles = 0;
int16_t buffer[512] = {0};
File frec;
unsigned long lastSamplePlayed = 0;
void my_handler(sig_atomic_t i);
static char stack_body[64*1024];
static stack_t sigseg_stack;
static struct sigaction sigseg_handler;
void crash_handler(sig_atomic_t i);
uint16_t getNumWavFilesInDirectory(char *directory);
void populateFilenames(char *directory, char **filenames);
void setup() {
Serial.begin(9600);
playSd1.setPlaybackRate(1.0f);
playSd1.enableInterpolation(true);
//rraw_a1.play((int16_t*)kick_raw, kick_raw_len/2);
Serial.println("setup done");
if (SD.exists("RECORD_SD.RAW")) {
// The SD library writes new data to the end of the
// file, so to start a new recording, the old file
// must be deleted before new data is written.
SD.remove("RECORD_SD.RAW");
}
frec = SD.open("RECORD_SD.RAW", O_WRITE);
_numWaveFiles = getNumWavFilesInDirectory("/");
Serial.printf("Num wave files: %d\n", _numWaveFiles);
_filenames = new char*[_numWaveFiles];
populateFilenames("/", _filenames);
Serial.println("Populated...");
AudioMemory(120);
if (frec) {
queue1.begin();
Serial.println("startRecording");
} else {
Serial.println("recording failed...");
}
}
void loop() {
unsigned currentMillis = millis();
if (currentMillis > lastSamplePlayed + 1000) {
if (!playSd1.isPlaying()) {
if (playSd1.playWav(_filenames[_fileIndex])) {
lastSamplePlayed = currentMillis;
Serial.printf("playing %s\n", _filenames[_fileIndex]);
} else
Serial.printf("failed to play%s\n", _filenames[_fileIndex]);
_fileIndex++;
_fileIndex %= _numWaveFiles;
Serial.print("Memory: ");
Serial.print(AudioMemoryUsage());
Serial.print(",");
Serial.print(AudioMemoryUsageMax());
Serial.println();
}
}
if (queue1.available() >= 1) {
int16_t* incomming = queue1.readBuffer();
//Serial.printf("sizeof(incomming)=%i\n", sizeof(incomming));
//if (incomming != NULL && sizeof(incomming) >= 256) {
if (incomming != NULL) {
memcpy(buffer, incomming, 256);
queue1.freeBuffer();
frec.write((unsigned char *)buffer, 256);
frec.flush();
}
//else {
// arduino_should_exit = true;
//Serial.printf("sizeof(incomming)=%i\n", sizeof(incomming));
//}
}
delay(1);
}
int main(int numArgs, char **args) {
if (numArgs < 2)
{
std::cout << "usage: " << args[0] << " <path-to-SDCard>";
exit(0);
}
std::cout << args[1] << std::endl;
signal (SIGINT,my_handler);
signal (SIGSEGV,crash_handler);
sigseg_stack.ss_sp = stack_body;
sigseg_stack.ss_flags = SS_ONSTACK;
sigseg_stack.ss_size = sizeof(stack_body);
// assert(!sigaltstack(&sigseg_stack, nullptr));
sigseg_handler.sa_flags = SA_ONSTACK;
sigseg_handler.sa_handler = &crash_handler;
// assert(!sigaction(SIGSEGV, &sigseg_handler, nullptr));
initialize_mock_arduino();
//SD.setSDCardFileData((char *) kick_raw, kick_raw_len);
SD.setSDCardFolderPath(args[1]);
setup();
while(!arduino_should_exit){
loop();
}
delay(1000);
frec.close();
}
uint16_t getNumWavFilesInDirectory(char *directory) {
File dir = SD.open(directory);
uint16_t numWaveFiles = 0;
while (true) {
File files = dir.openNextFile();
if (!files) {
//If no more files, break out.
break;
}
String curfile = files.name(); //put file in string
int m = curfile.lastIndexOf(".WAV");
int a = curfile.lastIndexOf(".wav");
int underscore = curfile.indexOf("_");
int underscore2 = curfile.indexOf("._");
// if returned results is more then 0 add them to the list.
if ((m > 0 || a > 0) && (underscore != 0) && (underscore2 != 0)) {
numWaveFiles++;
}
files.close();
}
// close
dir.close();
return numWaveFiles;
}
void populateFilenames(char *directory, char **filenames) {
File dir = SD.open(directory);
uint16_t index = 0;
while (true) {
File files = dir.openNextFile();
if (!files) {
//If no more files, break out.
break;
}
String curfile = files.name(); //put file in string
int m = curfile.lastIndexOf(".WAV");
int a = curfile.lastIndexOf(".wav");
int underscore = curfile.indexOf("_");
int underscore2 = curfile.indexOf("._");
// if returned results is more then 0 add them to the list.
if ((m > 0 || a > 0) && (underscore != 0) && (underscore2 != 0) ) {
Serial.printf(" ---- %s\n", curfile.c_str());
filenames[index] = new char[curfile.length()+1] {0};
memcpy(filenames[index], curfile.c_str(), curfile.length()+1);
Serial.printf(" ------ %s\n", filenames[index]);
index++;
}
files.close();
}
// close
dir.close();
}
void my_handler(sig_atomic_t i){
if ( i== SIGINT) {
arduino_should_exit = true;
printf("Caught signal %d\n",i);
} else
{
cerr << "sig seg fault handler" << endl;
const int asize = 10;
void *array[asize];
size_t size;
// get void*'s for all entries on the stack
size = backtrace(array, asize);
// print out all the frames to stderr
cerr << "stack trace: " << endl;
backtrace_symbols_fd(array, size, STDERR_FILENO);
cerr << "resend SIGSEGV to get core dump" << endl;
signal(i, SIG_DFL);
kill(getpid(), i);
}
}
void crash_handler(sig_atomic_t i){
cerr << "sig seg fault handler" << endl;
const int asize = 10;
void *array[asize];
size_t size;
// get void*'s for all entries on the stack
size = backtrace(array, asize);
// print out all the frames to stderr
cerr << "stack trace: " << endl;
backtrace_symbols_fd(array, size, STDERR_FILENO);
cerr << "resend SIGSEGV to get core dump" << endl;
signal(i, SIG_DFL);
kill(getpid(), i);
}
unsigned char kick_raw[] = {
0x99, 0x02, 0xd7, 0x02, 0xfa, 0x02, 0x5f, 0x03, 0xc1, 0x03, 0x2a, 0x04,
0xad, 0x04, 0xa5, 0x05, 0x76, 0x06, 0x2f, 0x07, 0x9e, 0x07, 0xe2, 0x07,
0x43, 0x08, 0x92, 0x08, 0xb2, 0x08, 0xe8, 0x08, 0x16, 0x09, 0xda, 0x08,
0x51, 0x08, 0x01, 0x08, 0x25, 0x08, 0x70, 0x08, 0xc3, 0x08, 0x23, 0x09,
0x95, 0x09, 0x19, 0x0a, 0x83, 0x0a, 0x7e, 0x0a, 0xd0, 0x0a, 0x65, 0x0b,
0xf6, 0x0b, 0x89, 0x0c, 0xd1, 0x0c, 0xcf, 0x0c, 0x1a, 0x0d, 0xe5, 0x0d,
0x5e, 0x0e, 0xbb, 0x0e, 0xec, 0x0e, 0xd9, 0x0e, 0x07, 0x0f, 0xc8, 0x0f,
0x2a, 0x10, 0x04, 0x10, 0x28, 0x10, 0x54, 0x11, 0x8e, 0x13, 0x4b, 0x16,
0x09, 0x19, 0x91, 0x1b, 0xf7, 0x1d, 0x55, 0x20, 0xd1, 0x22, 0xcb, 0x25,
0x4d, 0x29, 0xa8, 0x2c, 0x7f, 0x2f, 0xda, 0x31, 0xac, 0x34, 0x0a, 0x3a,
0x24, 0x47, 0x9d, 0x5b, 0xe9, 0x67, 0x29, 0x67, 0x24, 0x66, 0x26, 0x66,
0xd2, 0x65, 0x9c, 0x65, 0x38, 0x65, 0x05, 0x65, 0x9f, 0x64, 0x64, 0x64,
0x12, 0x64, 0xce, 0x63, 0x7c, 0x63, 0x32, 0x63, 0xe6, 0x62, 0x97, 0x62,
0x49, 0x62, 0x01, 0x62, 0xb3, 0x61, 0x63, 0x61, 0x15, 0x61, 0xc4, 0x60,
0x75, 0x60, 0x20, 0x60, 0xce, 0x5f, 0x7a, 0x5f, 0x28, 0x5f, 0xd5, 0x5e,
0x81, 0x5e, 0x2d, 0x5e, 0xd3, 0x5d, 0x80, 0x5d, 0x2e, 0x5d, 0xe6, 0x5c,
0x1a, 0x5c, 0x16, 0x5a, 0x01, 0x58, 0xb9, 0x56, 0x6d, 0x55, 0xf4, 0x53,
0x49, 0x52, 0x83, 0x50, 0x87, 0x4e, 0x5f, 0x4c, 0x68, 0x4a, 0x5c, 0x48,
0x62, 0x46, 0x5a, 0x44, 0xe2, 0x41, 0x08, 0x3f, 0x1c, 0x3c, 0x44, 0x39,
0x35, 0x36, 0xcb, 0x32, 0xaf, 0x2f, 0xc8, 0x2c, 0xf8, 0x29, 0x55, 0x27,
0x6a, 0x24, 0x0f, 0x21, 0x5e, 0x1d, 0xc3, 0x19, 0x7b, 0x16, 0x71, 0x13,
0x6c, 0x10, 0x00, 0x0d, 0xd2, 0x08, 0x7f, 0x04, 0x7a, 0x01, 0x43, 0xff,
0xb9, 0xfc, 0xfa, 0xf9, 0x3b, 0xf7, 0xcb, 0xf4, 0x2b, 0xf2, 0x02, 0xef,
0x0c, 0xec, 0x3d, 0xe9, 0x21, 0xe6, 0xa6, 0xe2, 0x8a, 0xdf, 0x00, 0xdd,
0xbc, 0xda, 0x9e, 0xd8, 0xc1, 0xd6, 0xd6, 0xd4, 0xd6, 0xd2, 0xad, 0xd0,
0x5f, 0xce, 0xf0, 0xcb, 0xe9, 0xc9, 0x61, 0xc8, 0x75, 0xc7, 0x97, 0xc6,
0x3e, 0xc5, 0x07, 0xc4, 0x8e, 0xc3, 0x18, 0xc3, 0x3a, 0xc2, 0x15, 0xc1,
0x0e, 0xc0, 0xb3, 0xbf, 0xcf, 0xbf, 0xf8, 0xbf, 0xcc, 0xbf, 0x72, 0xbf,
0x41, 0xbf, 0x2b, 0xbf, 0xe2, 0xbe, 0x99, 0xbe, 0x4e, 0xbe, 0x0e, 0xbe,
0xcd, 0xbd, 0x7c, 0xbd, 0x8a, 0xbd, 0x88, 0xbd, 0x04, 0xbd, 0x0c, 0xbc,
0xb3, 0xbb, 0xf6, 0xbb, 0xf1, 0xbb, 0x12, 0xbc, 0x6f, 0xbc, 0xcb, 0xbc,
0xe4, 0xbc, 0x33, 0xbd, 0x1b, 0xbe, 0xac, 0xbe, 0x1e, 0xbf, 0x91, 0xbf,
0x50, 0xc0, 0x40, 0xc1, 0x3d, 0xc2, 0x32, 0xc3, 0xdf, 0xc3, 0xad, 0xc4,
0x77, 0xc5, 0xbe, 0xc6, 0xc7, 0xc8, 0x1d, 0xcb, 0x0e, 0xcd, 0x83, 0xce,
0xf1, 0xcf, 0xb4, 0xd1, 0x7d, 0xd3, 0x86, 0xd5, 0x89, 0xd7, 0xd2, 0xd9,
0x34, 0xdc, 0x28, 0xde, 0x23, 0xe0, 0x33, 0xe2, 0x0a, 0xe4, 0x59, 0xe5,
0xfc, 0xe6, 0x98, 0xe9, 0x30, 0xec, 0x91, 0xee, 0xc2, 0xf0, 0x0d, 0xf3,
0x35, 0xf5, 0xf3, 0xf6, 0xc4, 0xf8, 0xcb, 0xfa, 0xef, 0xfc, 0x65, 0xff,
0x05, 0x02, 0x7c, 0x04, 0xde, 0x06, 0x75, 0x09, 0x2b, 0x0c, 0x9b, 0x0e,
0xf3, 0x10, 0xb3, 0x13, 0x3a, 0x16, 0xeb, 0x18, 0x55, 0x1c, 0xad, 0x1f,
0xa8, 0x22, 0x54, 0x25, 0xae, 0x27, 0x33, 0x2a, 0x16, 0x2d, 0x36, 0x30,
0x84, 0x33, 0x94, 0x36, 0xbd, 0x38, 0xa2, 0x3a, 0x7d, 0x3c, 0x06, 0x3e,
0x24, 0x3f, 0x27, 0x40, 0x7c, 0x41, 0xef, 0x42, 0x14, 0x44, 0xeb, 0x44,
0x06, 0x46, 0x53, 0x47, 0x47, 0x48, 0x9b, 0x48, 0xaf, 0x48, 0xd7, 0x48,
0x4c, 0x49, 0xa0, 0x49, 0xbe, 0x49, 0xd4, 0x49, 0xfa, 0x49, 0x5e, 0x4a,
0xcc, 0x4a, 0x14, 0x4b, 0xfe, 0x4a, 0x22, 0x4b, 0x10, 0x4c, 0x0c, 0x4d,
0xb2, 0x4d, 0x4c, 0x4e, 0x3e, 0x4e, 0x77, 0x4d, 0x98, 0x4c, 0xf6, 0x4b,
0x67, 0x4b, 0xf0, 0x4a, 0x2a, 0x4a, 0xea, 0x48, 0x06, 0x48, 0x47, 0x47,
0xb2, 0x46, 0xda, 0x45, 0xad, 0x44, 0x5c, 0x43, 0x43, 0x42, 0x9e, 0x41,
0x0a, 0x41, 0x49, 0x40, 0xa6, 0x3f, 0x9d, 0x3e, 0x3c, 0x3d, 0xc6, 0x3b,
0xf6, 0x39, 0x87, 0x37, 0xf6, 0x34, 0x87, 0x32, 0x2b, 0x30, 0x6f, 0x2d,
0xfa, 0x2a, 0x3d, 0x29, 0x48, 0x27, 0xc2, 0x24, 0x49, 0x22, 0xca, 0x1f,
0xa0, 0x1c, 0x7c, 0x19, 0x06, 0x17, 0xbf, 0x14, 0x9f, 0x12, 0x96, 0x10,
0xf9, 0x0d, 0x3e, 0x0b, 0xe8, 0x08, 0x5c, 0x06, 0xe7, 0x02, 0x6e, 0xff,
0xca, 0xfc, 0x5b, 0xfa, 0xa0, 0xf7, 0xe9, 0xf4, 0x9c, 0xf2, 0x66, 0xf0,
0xaf, 0xed, 0xfd, 0xea, 0xcc, 0xe8, 0x6e, 0xe6, 0x82, 0xe3, 0x97, 0xe0,
0xed, 0xdd, 0x62, 0xdb, 0x7b, 0xd8, 0xd3, 0xd5, 0x5f, 0xd3, 0x1a, 0xd1,
0x44, 0xcf, 0xeb, 0xcd, 0x89, 0xcc, 0xca, 0xca, 0x4d, 0xc9, 0x35, 0xc8,
0x53, 0xc7, 0x0c, 0xc6, 0x06, 0xc4, 0xca, 0xc1, 0x09, 0xc0, 0x9c, 0xbe,
0xa8, 0xbd, 0xfd, 0xbc, 0xf2, 0xbb, 0x9b, 0xba, 0x20, 0xb9, 0xe4, 0xb7,
0xc1, 0xb6, 0xcd, 0xb5, 0x12, 0xb5, 0x55, 0xb4, 0xd1, 0xb3, 0x86, 0xb3,
0x19, 0xb3, 0xe8, 0xb2, 0xd7, 0xb2, 0x72, 0xb2, 0x27, 0xb2, 0xb7, 0xb1,
0x67, 0xb1, 0x65, 0xb1, 0xae, 0xb1, 0x6b, 0xb1, 0xf2, 0xb0, 0xeb, 0xb0,
0x0f, 0xb1, 0xfe, 0xb0, 0xeb, 0xb0, 0xcf, 0xb0, 0x94, 0xb0, 0x3e, 0xb0,
0x29, 0xb0, 0x56, 0xb0, 0x0c, 0xb0, 0xb7, 0xaf, 0xfb, 0xaf, 0x37, 0xb0,
0x96, 0xb0, 0x42, 0xb1, 0xe8, 0xb1, 0xb5, 0xb2, 0xc5, 0xb3, 0x93, 0xb4,
0x93, 0xb4, 0xee, 0xb4, 0x59, 0xb6, 0xca, 0xb7, 0x87, 0xb8, 0x6f, 0xb8,
0x33, 0xb8, 0xaf, 0xb8, 0x4a, 0xb9, 0x9d, 0xb9, 0xf2, 0xb9, 0x48, 0xba,
0xd0, 0xba, 0xe5, 0xbb, 0x4e, 0xbd, 0xaf, 0xbe, 0xe9, 0xbf, 0xba, 0xc1,
0xc2, 0xc3, 0x73, 0xc5, 0xa6, 0xc6, 0x6a, 0xc7, 0x83, 0xc8, 0x42, 0xca,
0xc8, 0xcb, 0x34, 0xcd, 0x94, 0xce, 0xcc, 0xcf, 0x31, 0xd1, 0x27, 0xd3,
0x8c, 0xd5, 0x61, 0xd7, 0x78, 0xd9, 0x3b, 0xdc, 0x40, 0xdf, 0xdd, 0xe1,
0x0c, 0xe4, 0xe4, 0xe5, 0xd0, 0xe7, 0x65, 0xea, 0xc9, 0xec, 0xd7, 0xee,
0xfc, 0xf0, 0x7c, 0xf3, 0xf6, 0xf5, 0x09, 0xf8, 0xde, 0xf9, 0xca, 0xfb,
0xac, 0xfd, 0xc3, 0xff, 0x33, 0x02, 0xb1, 0x04, 0x24, 0x07, 0x57, 0x09,
0x5f, 0x0b, 0xe6, 0x0d, 0xd1, 0x10, 0x6d, 0x13, 0x8f, 0x15, 0xfb, 0x17,
0x43, 0x1a, 0x8e, 0x1c, 0x1a, 0x1f, 0x69, 0x21, 0x80, 0x23, 0x74, 0x25,
0x62, 0x27, 0x07, 0x29, 0xa1, 0x2a, 0xa5, 0x2c, 0xdf, 0x2e, 0x57, 0x31,
0xff, 0x33, 0xd1, 0x36, 0x6e, 0x39, 0x8a, 0x3b, 0x58, 0x3d, 0x32, 0x3f,
0xc8, 0x40, 0x1b, 0x42, 0x22, 0x43, 0x1a, 0x44, 0x25, 0x45, 0xe5, 0x45,
0x43, 0x46, 0x9b, 0x46, 0x6a, 0x47, 0x6f, 0x48, 0x69, 0x49, 0x6f, 0x4a,
0xc7, 0x4b, 0x0e, 0x4d, 0x03, 0x4e, 0x78, 0x4e, 0xdf, 0x4e, 0x0b, 0x4f,
0xea, 0x4e, 0xcb, 0x4e, 0x1b, 0x4f, 0x6e, 0x4f, 0xc3, 0x4f, 0xdc, 0x4f,
0xcb, 0x4f, 0xd2, 0x4f, 0x16, 0x50, 0x24, 0x50, 0xf2, 0x4f, 0x00, 0x50,
0x37, 0x50, 0x4e, 0x50, 0x5e, 0x50, 0x7c, 0x50, 0xab, 0x50, 0x69, 0x50,
0xad, 0x4f, 0xa3, 0x4e, 0xe6, 0x4d, 0x42, 0x4d, 0xdc, 0x4c, 0x7c, 0x4c,
0xbe, 0x4b, 0x08, 0x4b, 0x7b, 0x4a, 0xe4, 0x49, 0x14, 0x49, 0x07, 0x48,
0x98, 0x46, 0x2f, 0x45, 0x16, 0x44, 0x23, 0x43, 0x55, 0x42, 0xac, 0x41,
0x06, 0x41, 0x4b, 0x40, 0x8f, 0x3f, 0xde, 0x3e, 0xe1, 0x3d, 0x75, 0x3c,
0xc0, 0x3a, 0xe4, 0x38, 0x83, 0x37, 0x9a, 0x36, 0xe5, 0x35, 0xc0, 0x34,
0xf9, 0x32, 0xe1, 0x30, 0xfa, 0x2e, 0xd4, 0x2c, 0x4d, 0x2a, 0xed, 0x27,
0xb9, 0x25, 0xb2, 0x23, 0x7d, 0x21, 0xfd, 0x1e, 0x89, 0x1c, 0x38, 0x1a,
0xe2, 0x17, 0x67, 0x15, 0xf3, 0x12, 0xb3, 0x10, 0x9e, 0x0e, 0x79, 0x0c,
0xea, 0x09, 0x54, 0x07, 0x26, 0x05, 0x0a, 0x03, 0xd7, 0x00, 0x98, 0xfe,
0x41, 0xfc, 0x8d, 0xf9, 0x3c, 0xf7, 0x4f, 0xf5, 0x73, 0xf3, 0x7b, 0xf1,
0x68, 0xef, 0x6f, 0xed, 0x7a, 0xeb, 0x87, 0xe9, 0x48, 0xe7, 0xc6, 0xe4,
0x65, 0xe2, 0xf6, 0xdf, 0x86, 0xdd, 0x9f, 0xdb, 0x1b, 0xda, 0xa6, 0xd8,
0xce, 0xd6, 0xe4, 0xd4, 0xe3, 0xd2, 0x84, 0xd0, 0xec, 0xcd, 0x08, 0xcc,
0x89, 0xca, 0x1b, 0xc9, 0xe2, 0xc7, 0x9d, 0xc6, 0xe5, 0xc4, 0x79, 0xc3,
0x6d, 0xc2, 0xe3, 0xc0, 0x3c, 0xbf, 0xd3, 0xbd, 0x41, 0xbc, 0xd2, 0xba,
0x6a, 0xb9, 0xa1, 0xb7, 0xa9, 0xb5, 0x47, 0xb4, 0x91, 0xb3, 0xd5, 0xb2,
0xb7, 0xb1, 0x51, 0xb0, 0x14, 0xaf, 0xf5, 0xad, 0x95, 0xac, 0x34, 0xab,
0x05, 0xaa, 0xe1, 0xa8, 0xb3, 0xa7, 0xd9, 0xa6, 0x25, 0xa6, 0x6e, 0xa5,
0x2b, 0xa5, 0x7b, 0xa5, 0x9a, 0xa5, 0x88, 0xa5, 0xc3, 0xa5, 0xe7, 0xa5,
0xaf, 0xa5, 0x8b, 0xa5, 0x80, 0xa5, 0x65, 0xa5, 0x8c, 0xa5, 0x7e, 0xa5,
0x22, 0xa5, 0x40, 0xa5, 0xed, 0xa5, 0x27, 0xa6, 0x2b, 0xa6, 0x1c, 0xa6,
0xe5, 0xa5, 0x7b, 0xa5, 0x45, 0xa5, 0x37, 0xa5, 0x04, 0xa5, 0x91, 0xa4,
0x8d, 0xa4, 0x2d, 0xa5, 0x9f, 0xa5, 0xf6, 0xa5, 0x7e, 0xa6, 0x34, 0xa7,
0x14, 0xa8, 0x7e, 0xa8, 0x87, 0xa8, 0xc4, 0xa8, 0x51, 0xa9, 0xec, 0xa9,
0x74, 0xaa, 0xf7, 0xaa, 0x40, 0xab, 0xd9, 0xab, 0xca, 0xac, 0x6b, 0xad,
0xb3, 0xad, 0x08, 0xae, 0x10, 0xaf, 0x2c, 0xb0, 0xcb, 0xb0, 0x23, 0xb1,
0xac, 0xb1, 0x0e, 0xb2, 0x42, 0xb2, 0xd7, 0xb2, 0xef, 0xb3, 0x21, 0xb5,
0x30, 0xb6, 0xe9, 0xb6, 0x54, 0xb7, 0xf0, 0xb7, 0x9e, 0xb8, 0x2e, 0xb9,
0x03, 0xba, 0x55, 0xbb, 0xdf, 0xbc, 0x5f, 0xbe, 0xb8, 0xbf, 0x01, 0xc1,
0x83, 0xc2, 0x0c, 0xc4, 0x65, 0xc5, 0x7e, 0xc6, 0x86, 0xc7, 0xba, 0xc8,
0x11, 0xca, 0x66, 0xcb, 0x28, 0xcd, 0x4d, 0xcf, 0x60, 0xd1, 0x69, 0xd3,
0x7b, 0xd5, 0x5f, 0xd7, 0xe3, 0xd8, 0xca, 0xda, 0xda, 0xdc, 0xda, 0xde,
0xab, 0xe0, 0x59, 0xe2, 0x3b, 0xe4, 0x21, 0xe6, 0xfc, 0xe7, 0xcb, 0xe9,
0xbe, 0xeb, 0x9c, 0xed, 0x47, 0xef, 0x0b, 0xf1, 0xd3, 0xf2, 0xbc, 0xf4,
0x9c, 0xf6, 0x67, 0xf8, 0x2a, 0xfa, 0xc1, 0xfb, 0x7f, 0xfd, 0x41, 0xff,
0x12, 0x01, 0xd2, 0x02, 0xfc, 0x04, 0xe8, 0x06, 0x9a, 0x08, 0x59, 0x0a,
0x48, 0x0c, 0x36, 0x0e, 0x37, 0x10, 0x36, 0x12, 0x59, 0x14, 0x62, 0x16,
0x86, 0x18, 0xb9, 0x1a, 0xc2, 0x1c, 0xcd, 0x1e, 0xf1, 0x20, 0x27, 0x23,
0x7a, 0x25, 0xf9, 0x27, 0x2a, 0x2a, 0x1f, 0x2c, 0xf8, 0x2d, 0xa3, 0x2f,
0x23, 0x31, 0xf4, 0x32, 0x2c, 0x35, 0x40, 0x37, 0x23, 0x39, 0xfe, 0x3a,
0x11, 0x3d, 0x2c, 0x3f, 0xe8, 0x40, 0x8c, 0x42, 0x55, 0x44, 0x37, 0x46,
0x99, 0x47, 0xcb, 0x48, 0x12, 0x4a, 0x60, 0x4b, 0x86, 0x4c, 0x9b, 0x4d,
0xc8, 0x4e, 0xec, 0x4f, 0xe3, 0x50, 0x8a, 0x51, 0x23, 0x52, 0xd8, 0x52,
0x68, 0x53, 0x9b, 0x53, 0xb1, 0x53, 0x11, 0x54, 0x94, 0x54, 0xf7, 0x54,
0x4f, 0x55, 0xa4, 0x55, 0x03, 0x56, 0x51, 0x56, 0x92, 0x56, 0xfa, 0x56,
0x59, 0x57, 0xad, 0x57, 0xcd, 0x57, 0xc5, 0x57, 0xa8, 0x57, 0x64, 0x57,
0x49, 0x57, 0x63, 0x57, 0x64, 0x57, 0x40, 0x57, 0xf6, 0x56, 0xfc, 0x56,
0x36, 0x57, 0x3b, 0x57, 0x1e, 0x57, 0x1c, 0x57, 0x03, 0x57, 0xee, 0x56,
0xa5, 0x56, 0x80, 0x56, 0xd4, 0x56, 0xe4, 0x56, 0x92, 0x56, 0xf0, 0x55,
0x02, 0x55, 0xab, 0x53, 0xb5, 0x52, 0x51, 0x52, 0x08, 0x52, 0x80, 0x51,
0xb4, 0x50, 0xde, 0x4f, 0x27, 0x4f, 0x63, 0x4e, 0x58, 0x4d, 0x72, 0x4c,
0x82, 0x4b, 0x81, 0x4a, 0x87, 0x49, 0xb4, 0x48, 0xb1, 0x47, 0x99, 0x46,
0xb4, 0x45, 0x34, 0x45, 0xb8, 0x44, 0x2f, 0x44, 0x7f, 0x43, 0xa0, 0x42,
0xcb, 0x41, 0xd1, 0x40, 0xeb, 0x3f, 0x28, 0x3f, 0x3d, 0x3e, 0x09, 0x3d,
0x9d, 0x3b, 0x40, 0x3a, 0x1c, 0x39, 0xeb, 0x37, 0xd1, 0x36, 0xb3, 0x35,
0x8b, 0x34, 0x0b, 0x33, 0x51, 0x31, 0xfb, 0x2f, 0xb9, 0x2e, 0x54, 0x2d,
0xaf, 0x2b, 0xdf, 0x29, 0xf1, 0x27, 0x3a, 0x26, 0x6f, 0x24, 0x56, 0x22,
0x20, 0x20, 0x0a, 0x1e, 0x3b, 0x1c, 0x55, 0x1a, 0x6c, 0x18, 0xaa, 0x16,
0xef, 0x14, 0x0a, 0x13, 0x17, 0x11, 0x1c, 0x0f, 0x22, 0x0d, 0x46, 0x0b,
0x53, 0x09, 0x46, 0x07, 0x46, 0x05, 0x4d, 0x03, 0x1a, 0x01, 0xd3, 0xfe,
0x94, 0xfc, 0x8c, 0xfa, 0x8f, 0xf8, 0xc1, 0xf6, 0x27, 0xf5, 0x8f, 0xf3,
0xf2, 0xf1, 0x74, 0xf0, 0xfa, 0xee, 0x4d, 0xed, 0x9e, 0xeb, 0xa2, 0xe9,
0x73, 0xe7, 0xa9, 0xe5, 0x2d, 0xe4, 0xa3, 0xe2, 0xf9, 0xe0, 0x50, 0xdf,
0xb9, 0xdd, 0x34, 0xdc, 0xad, 0xda, 0x0b, 0xd9, 0x77, 0xd7, 0xb9, 0xd5,
0x37, 0xd4, 0xff, 0xd2, 0x8a, 0xd1, 0x14, 0xd0, 0xba, 0xce, 0x7d, 0xcd,
0x2c, 0xcc, 0xa1, 0xca, 0x22, 0xc9, 0xa9, 0xc7, 0x0e, 0xc6, 0x66, 0xc4,
0xfc, 0xc2, 0xa5, 0xc1, 0x4a, 0xc0, 0xff, 0xbe, 0xf7, 0xbd, 0x0e, 0xbd,
0x1d, 0xbc, 0x16, 0xbb, 0xad, 0xb9, 0x44, 0xb8, 0xd7, 0xb6, 0x9e, 0xb5,
0x9f, 0xb4, 0x97, 0xb3, 0x72, 0xb2, 0x5f, 0xb1, 0x67, 0xb0, 0x89, 0xaf,
0x9d, 0xae, 0xbe, 0xad, 0x08, 0xad, 0x5d, 0xac, 0x8b, 0xab, 0xad, 0xaa,
0xe4, 0xa9, 0x59, 0xa9, 0xc4, 0xa8, 0x02, 0xa8, 0x4d, 0xa7, 0xc2, 0xa6,
0x4a, 0xa6, 0x09, 0xa6, 0xd2, 0xa5, 0x50, 0xa5, 0xec, 0xa4, 0xc2, 0xa4,
0xd9, 0xa4, 0xbd, 0xa4, 0x97, 0xa4, 0xa5, 0xa4, 0xbf, 0xa4, 0xb4, 0xa4,
0x8f, 0xa4, 0x31, 0xa4, 0x39, 0xa4, 0x7d, 0xa4, 0xab, 0xa4, 0xc7, 0xa4,
0xb3, 0xa4, 0xab, 0xa4, 0xca, 0xa4, 0x05, 0xa5, 0x1e, 0xa5, 0x2a, 0xa5,
0x2c, 0xa5, 0x18, 0xa5, 0x01, 0xa5, 0x33, 0xa5, 0x8c, 0xa5, 0xb2, 0xa5,
0x81, 0xa5, 0x5c, 0xa5, 0x6e, 0xa5, 0x79, 0xa5, 0x4e, 0xa5, 0x17, 0xa5,
0xff, 0xa4, 0x1c, 0xa5, 0x45, 0xa5, 0x8a, 0xa5, 0xbf, 0xa5, 0xdb, 0xa5,
0x41, 0xa6, 0xfb, 0xa6, 0xc6, 0xa7, 0x86, 0xa8, 0x29, 0xa9, 0x97, 0xa9,
0x27, 0xaa, 0xd7, 0xaa, 0x6d, 0xab, 0xf4, 0xab, 0x34, 0xac, 0x69, 0xac,
0xc6, 0xac, 0x37, 0xad, 0xaa, 0xad, 0x34, 0xae, 0xd3, 0xae, 0x81, 0xaf,
0x16, 0xb0, 0x72, 0xb0, 0xc8, 0xb0, 0x36, 0xb1, 0x91, 0xb1, 0xe0, 0xb1,
0x3b, 0xb2, 0x8e, 0xb2, 0xe0, 0xb2, 0x2a, 0xb3, 0xab, 0xb3, 0x3a, 0xb4,
0xf1, 0xb4, 0xc0, 0xb5, 0xae, 0xb6, 0x91, 0xb7, 0x82, 0xb8, 0x98, 0xb9,
0x8f, 0xba, 0x88, 0xbb, 0x65, 0xbc, 0x20, 0xbd, 0xcb, 0xbd, 0xaf, 0xbe,
0x94, 0xbf, 0x84, 0xc0, 0x85, 0xc1, 0x7b, 0xc2, 0x67, 0xc3, 0x66, 0xc4,
0x7f, 0xc5, 0x89, 0xc6, 0x6b, 0xc7, 0x38, 0xc8, 0x29, 0xc9, 0x4a, 0xca,
0x82, 0xcb, 0xc1, 0xcc, 0x12, 0xce, 0x5e, 0xcf, 0xb0, 0xd0, 0x25, 0xd2,
0x66, 0xd3, 0xde, 0xd4, 0x6c, 0xd6, 0x28, 0xd8, 0xd7, 0xd9, 0x80, 0xdb,
0xf7, 0xdc, 0x6f, 0xde, 0xd0, 0xdf, 0x22, 0xe1, 0x7a, 0xe2, 0xe5, 0xe3,
0x7a, 0xe5, 0xea, 0xe6, 0x51, 0xe8, 0xeb, 0xe9, 0x70, 0xeb, 0xb3, 0xec,
0x01, 0xee, 0x60, 0xef, 0xcb, 0xf0, 0x1d, 0xf2, 0x7b, 0xf3, 0xcf, 0xf4,
0x39, 0xf6, 0xc8, 0xf7, 0x82, 0xf9, 0x4a, 0xfb, 0xf2, 0xfc, 0x8c, 0xfe,
0x01, 0x00, 0x68, 0x01, 0x15, 0x03, 0xe6, 0x04, 0xbc, 0x06, 0x42, 0x08,
0xbb, 0x09, 0x2b, 0x0b, 0xc7, 0x0c, 0x35, 0x0e, 0x94, 0x0f, 0xf2, 0x10,
0x59, 0x12, 0xbc, 0x13, 0x34, 0x15, 0xac, 0x16, 0x1c, 0x18, 0x79, 0x19,
0xdc, 0x1a, 0x6d, 0x1c, 0x21, 0x1e, 0xca, 0x1f, 0x70, 0x21, 0x02, 0x23,
0x6c, 0x24, 0x9e, 0x25, 0x45, 0x27, 0x02, 0x29, 0x95, 0x2a, 0xff, 0x2b,
0x72, 0x2d, 0xe8, 0x2e, 0x48, 0x30, 0x7c, 0x31, 0xd2, 0x32, 0x3d, 0x34,
0xac, 0x35, 0x26, 0x37, 0xbc, 0x38, 0x4c, 0x3a, 0x90, 0x3b, 0xef, 0x3c,
0x61, 0x3e, 0xe8, 0x3f, 0x59, 0x41, 0xab, 0x42, 0xf7, 0x43, 0x2d, 0x45,
0x6c, 0x46, 0x78, 0x47, 0xb4, 0x48, 0x2e, 0x4a, 0x8e, 0x4b, 0xd7, 0x4c,
0xf4, 0x4d, 0xee, 0x4e, 0xcb, 0x4f, 0xc3, 0x50, 0xc2, 0x51, 0xac, 0x52,
0x61, 0x53, 0xf3, 0x53, 0xac, 0x54, 0x5f, 0x55, 0xf4, 0x55, 0x7f, 0x56,
0x04, 0x57, 0x9c, 0x57, 0x1f, 0x58, 0x7c, 0x58, 0xbc, 0x58, 0x0b, 0x59,
0x71, 0x59, 0xc1, 0x59, 0x0b, 0x5a, 0x3e, 0x5a, 0x8b, 0x5a, 0xac, 0x5a,
0xa9, 0x5a, 0x8a, 0x5a, 0x6c, 0x5a, 0x4c, 0x5a, 0x39, 0x5a, 0x32, 0x5a,
0x40, 0x5a, 0x33, 0x5a, 0x44, 0x5a, 0x58, 0x5a, 0x79, 0x5a, 0x7a, 0x5a,
0x69, 0x5a, 0x49, 0x5a, 0x54, 0x5a, 0x78, 0x5a, 0x72, 0x5a, 0x5f, 0x5a,
0x31, 0x5a, 0x11, 0x5a, 0xf9, 0x59, 0xea, 0x59, 0xd1, 0x59, 0xa1, 0x59,
0x48, 0x59, 0xf0, 0x58, 0xa2, 0x58, 0x6e, 0x58, 0x60, 0x58, 0x46, 0x58,
0x3f, 0x58, 0x47, 0x58, 0x40, 0x58, 0x08, 0x58, 0x9c, 0x57, 0x11, 0x57,
0x83, 0x56, 0xd7, 0x55, 0x42, 0x55, 0xab, 0x54, 0x06, 0x54, 0x63, 0x53,
0xa6, 0x52, 0xf0, 0x51, 0x55, 0x51, 0xbc, 0x50, 0x1e, 0x50, 0x8e, 0x4f,
0xf3, 0x4e, 0x34, 0x4e, 0x6b, 0x4d, 0xc9, 0x4c, 0x30, 0x4c, 0x7d, 0x4b,
0xd8, 0x4a, 0x49, 0x4a, 0xad, 0x49, 0x11, 0x49, 0x6c, 0x48, 0xa4, 0x47,
0xec, 0x46, 0x6c, 0x46, 0xde, 0x45, 0x5d, 0x45, 0xbc, 0x44, 0xf1, 0x43,
0x34, 0x43, 0x8c, 0x42, 0xf8, 0x41, 0x47, 0x41, 0x6a, 0x40, 0x72, 0x3f,
0x8b, 0x3e, 0xb3, 0x3d, 0xf2, 0x3c, 0x2f, 0x3c, 0x5c, 0x3b, 0x96, 0x3a,
0xbc, 0x39, 0xb2, 0x38, 0x91, 0x37, 0x8c, 0x36, 0x75, 0x35, 0x63, 0x34,
0x5e, 0x33, 0x63, 0x32, 0x4b, 0x31, 0x3c, 0x30, 0x1e, 0x2f, 0x07, 0x2e,
0xd0, 0x2c, 0xb2, 0x2b, 0x84, 0x2a, 0x4d, 0x29, 0xfc, 0x27, 0xa5, 0x26,
0x2f, 0x25, 0x95, 0x23, 0x1f, 0x22, 0xad, 0x20, 0x3a, 0x1f, 0x9e, 0x1d,
0x10, 0x1c, 0x6e, 0x1a, 0xe3, 0x18, 0x56, 0x17, 0xdb, 0x15, 0x58, 0x14,
0xba, 0x12, 0x2a, 0x11, 0x8b, 0x0f, 0xf4, 0x0d, 0x5b, 0x0c, 0xd3, 0x0a,
0x5f, 0x09, 0xe5, 0x07, 0x4a, 0x06, 0xc0, 0x04, 0x3e, 0x03, 0xb6, 0x01,
0x37, 0x00, 0xca, 0xfe, 0x74, 0xfd, 0x00, 0xfc, 0xa5, 0xfa, 0x4a, 0xf9,
0xd1, 0xf7, 0x7e, 0xf6, 0x1c, 0xf5, 0x9d, 0xf3, 0x4f, 0xf2, 0x0e, 0xf1,
0xc0, 0xef, 0x3a, 0xee, 0xd8, 0xec, 0x69, 0xeb, 0x0c, 0xea, 0xad, 0xe8,
0x56, 0xe7, 0xf8, 0xe5, 0xbe, 0xe4, 0x98, 0xe3, 0x61, 0xe2, 0x03, 0xe1,
0x99, 0xdf, 0x4d, 0xde, 0x0e, 0xdd, 0xde, 0xdb, 0xad, 0xda, 0x84, 0xd9,
0x62, 0xd8, 0x32, 0xd7, 0x01, 0xd6, 0xb7, 0xd4, 0x87, 0xd3, 0x97, 0xd2,
0x89, 0xd1, 0x89, 0xd0, 0x6e, 0xcf, 0x65, 0xce, 0x5d, 0xcd, 0x44, 0xcc,
0x13, 0xcb, 0xf2, 0xc9, 0xd3, 0xc8, 0xad, 0xc7, 0x9b, 0xc6, 0x94, 0xc5,
0x8e, 0xc4, 0x7b, 0xc3, 0x92, 0xc2, 0xad, 0xc1, 0xb2, 0xc0, 0xb9, 0xbf,
0xb3, 0xbe, 0xc0, 0xbd, 0xd5, 0xbc, 0xf2, 0xbb, 0xe1, 0xba, 0xc7, 0xb9,
0xc7, 0xb8, 0xe8, 0xb7, 0x09, 0xb7, 0x2c, 0xb6, 0x66, 0xb5, 0xb1, 0xb4,
0xf6, 0xb3, 0x32, 0xb3, 0x53, 0xb2, 0x92, 0xb1, 0xdb, 0xb0, 0x0d, 0xb0,
0x46, 0xaf, 0x62, 0xae, 0x98, 0xad, 0xd1, 0xac, 0x3f, 0xac, 0xb0, 0xab,
0x34, 0xab, 0xb1, 0xaa, 0x45, 0xaa, 0xda, 0xa9, 0x6a, 0xa9, 0xf1, 0xa8,
0x7d, 0xa8, 0x04, 0xa8, 0xbb, 0xa7, 0x80, 0xa7, 0x41, 0xa7, 0x02, 0xa7,
0xb6, 0xa6, 0x68, 0xa6, 0x3b, 0xa6, 0x1c, 0xa6, 0x0d, 0xa6, 0xfc, 0xa5,
0xd4, 0xa5, 0xa6, 0xa5, 0x81, 0xa5, 0x76, 0xa5, 0x61, 0xa5, 0x54, 0xa5,
0x48, 0xa5, 0x47, 0xa5, 0x4b, 0xa5, 0x49, 0xa5, 0x38, 0xa5, 0x4b, 0xa5,
0x6c, 0xa5, 0xa3, 0xa5, 0xda, 0xa5, 0xfe, 0xa5, 0x21, 0xa6, 0x4a, 0xa6,
0x8a, 0xa6, 0xb4, 0xa6, 0xe0, 0xa6, 0xf3, 0xa6, 0x1b, 0xa7, 0x17, 0xa7,
0x40, 0xa7, 0x8e, 0xa7, 0xcd, 0xa7, 0x06, 0xa8, 0x3e, 0xa8, 0x86, 0xa8,
0xbd, 0xa8, 0xde, 0xa8, 0xf6, 0xa8, 0x1c, 0xa9, 0x49, 0xa9, 0x5c, 0xa9,
0x79, 0xa9, 0x93, 0xa9, 0xab, 0xa9, 0xe6, 0xa9, 0x2c, 0xaa, 0x82, 0xaa,
0xbc, 0xaa, 0xec, 0xaa, 0x32, 0xab, 0x69, 0xab, 0xa7, 0xab, 0xde, 0xab,
0x19, 0xac, 0x53, 0xac, 0xbb, 0xac, 0x14, 0xad, 0x8a, 0xad, 0xeb, 0xad,
0x6c, 0xae, 0xe1, 0xae, 0x62, 0xaf, 0xd9, 0xaf, 0x58, 0xb0, 0xc0, 0xb0,
0x36, 0xb1, 0x99, 0xb1, 0x11, 0xb2, 0x71, 0xb2, 0xdc, 0xb2, 0x58, 0xb3,
0xbb, 0xb3, 0x37, 0xb4, 0xb6, 0xb4, 0x46, 0xb5, 0xca, 0xb5, 0x50, 0xb6,
0xd9, 0xb6, 0x6c, 0xb7, 0x03, 0xb8, 0x7e, 0xb8, 0xf0, 0xb8, 0x64, 0xb9,
0xcf, 0xb9, 0x47, 0xba, 0xd3, 0xba, 0x60, 0xbb, 0xe8, 0xbb, 0x70, 0xbc,
0xf3, 0xbc, 0x82, 0xbd, 0x05, 0xbe, 0xa1, 0xbe, 0x2a, 0xbf, 0xae, 0xbf,
0x25, 0xc0, 0xac, 0xc0, 0x52, 0xc1, 0xde, 0xc1, 0x75, 0xc2, 0x11, 0xc3,
0xb5, 0xc3, 0x42, 0xc4, 0xc5, 0xc4, 0x6d, 0xc5, 0x0b, 0xc6, 0xb2, 0xc6,
0x4b, 0xc7, 0xf6, 0xc7, 0x9b, 0xc8, 0x4f, 0xc9, 0x17, 0xca, 0xf3, 0xca,
0xc6, 0xcb, 0x9a, 0xcc, 0x7b, 0xcd, 0x54, 0xce, 0x32, 0xcf, 0x09, 0xd0,
0xd7, 0xd0, 0xc9, 0xd1, 0xc1, 0xd2, 0xb8, 0xd3, 0xb6, 0xd4, 0xae, 0xd5,
0xbc, 0xd6, 0xca, 0xd7, 0xd2, 0xd8, 0xca, 0xd9, 0xbd, 0xda, 0xc8, 0xdb,
0xd8, 0xdc, 0xf9, 0xdd, 0x08, 0xdf, 0x1e, 0xe0, 0x39, 0xe1, 0x4e, 0xe2,
0x60, 0xe3, 0x7a, 0xe4, 0x96, 0xe5, 0xc1, 0xe6, 0xde, 0xe7, 0x0e, 0xe9,
0x2a, 0xea, 0x42, 0xeb, 0x7a, 0xec, 0x9f, 0xed, 0xbb, 0xee, 0xd6, 0xef,
0xef, 0xf0, 0x0e, 0xf2, 0x30, 0xf3, 0x55, 0xf4, 0x68, 0xf5, 0x7e, 0xf6,
0xa4, 0xf7, 0xc0, 0xf8, 0xea, 0xf9, 0x10, 0xfb, 0x41, 0xfc, 0x7d, 0xfd,
0xad, 0xfe, 0xe3, 0xff, 0x10, 0x01, 0x27, 0x02, 0x58, 0x03, 0x74, 0x04,
0xa4, 0x05, 0xd5, 0x06, 0x0b, 0x08, 0x36, 0x09, 0x5c, 0x0a, 0x76, 0x0b,
0x9a, 0x0c, 0xc1, 0x0d, 0xd8, 0x0e, 0xf5, 0x0f, 0x15, 0x11, 0x3f, 0x12,
0x70, 0x13, 0x8e, 0x14, 0xcc, 0x15, 0xf2, 0x16, 0x31, 0x18, 0x4b, 0x19,
0x82, 0x1a, 0xa1, 0x1b, 0xbc, 0x1c, 0xde, 0x1d, 0xe9, 0x1e, 0x13, 0x20,
0x33, 0x21, 0x6c, 0x22, 0x80, 0x23, 0xa7, 0x24, 0xbc, 0x25, 0xde, 0x26,
0xe7, 0x27, 0x07, 0x29, 0x28, 0x2a, 0x36, 0x2b, 0x4d, 0x2c, 0x71, 0x2d,
0x91, 0x2e, 0xbe, 0x2f, 0xd6, 0x30, 0xfb, 0x31, 0x20, 0x33, 0x46, 0x34,
0x59, 0x35, 0x7a, 0x36, 0xa1, 0x37, 0xc2, 0x38, 0xdf, 0x39, 0x01, 0x3b,
0x0f, 0x3c, 0x27, 0x3d, 0x1f, 0x3e, 0x2e, 0x3f, 0x43, 0x40, 0x5b, 0x41,
0x73, 0x42, 0x8e, 0x43, 0xaf, 0x44, 0xbc, 0x45, 0xcc, 0x46, 0xd8, 0x47,
0xec, 0x48, 0xe1, 0x49, 0xd1, 0x4a, 0xc4, 0x4b, 0xb6, 0x4c, 0xa9, 0x4d,
0x9d, 0x4e, 0x88, 0x4f, 0x75, 0x50, 0x4c, 0x51, 0x3b, 0x52, 0x05, 0x53,
0xd9, 0x53, 0xa1, 0x54, 0x6f, 0x55, 0x33, 0x56, 0xe5, 0x56, 0x7d, 0x57,
0x15, 0x58, 0xb3, 0x58, 0x4e, 0x59, 0xdb, 0x59, 0x55, 0x5a, 0xc8, 0x5a,
0x36, 0x5b, 0xa9, 0x5b, 0x09, 0x5c, 0x5a, 0x5c, 0xab, 0x5c, 0xf1, 0x5c,
0x34, 0x5d, 0x6a, 0x5d, 0x9e, 0x5d, 0xc1, 0x5d, 0xea, 0x5d, 0x0b, 0x5e,
0x28, 0x5e, 0x3d, 0x5e, 0x41, 0x5e, 0x51, 0x5e, 0x5f, 0x5e, 0x69, 0x5e,
0x79, 0x5e, 0x6a, 0x5e, 0x78, 0x5e, 0x76, 0x5e, 0x7f, 0x5e, 0x72, 0x5e,
0x70, 0x5e, 0x61, 0x5e, 0x61, 0x5e, 0x42, 0x5e, 0x36, 0x5e, 0x2f, 0x5e,
0x2c, 0x5e, 0x1a, 0x5e, 0xec, 0x5d, 0xbf, 0x5d, 0x94, 0x5d, 0x71, 0x5d,
0x4c, 0x5d, 0x24, 0x5d, 0xfa, 0x5c, 0xc3, 0x5c, 0x8c, 0x5c, 0x59, 0x5c,
0x3e, 0x5c, 0x0c, 0x5c, 0xd3, 0x5b, 0xb1, 0x5b, 0x78, 0x5b, 0x45, 0x5b,
0x14, 0x5b, 0xed, 0x5a, 0xc0, 0x5a, 0x89, 0x5a, 0x4f, 0x5a, 0x16, 0x5a,
0xe5, 0x59, 0xb5, 0x59, 0x84, 0x59, 0x4e, 0x59, 0x0d, 0x59, 0xcf, 0x58,
0xa6, 0x58, 0x79, 0x58, 0x3e, 0x58, 0xf8, 0x57, 0xc0, 0x57, 0x83, 0x57,
0x38, 0x57, 0x03, 0x57, 0xc1, 0x56, 0x65, 0x56, 0xe0, 0x55, 0x52, 0x55,
0xd0, 0x54, 0x4c, 0x54, 0xbe, 0x53, 0x32, 0x53, 0xa7, 0x52, 0x2a, 0x52,
0x95, 0x51, 0x09, 0x51, 0x76, 0x50, 0xe9, 0x4f, 0x69, 0x4f, 0xe2, 0x4e,
0x49, 0x4e, 0xc0, 0x4d, 0x38, 0x4d, 0xbd, 0x4c, 0x2d, 0x4c, 0x98, 0x4b,
0x07, 0x4b, 0x76, 0x4a, 0xdc, 0x49, 0x4a, 0x49, 0xb9, 0x48, 0x2d, 0x48,
0x9c, 0x47, 0x19, 0x47, 0x80, 0x46, 0xf9, 0x45, 0x66, 0x45, 0xd6, 0x44,
0x47, 0x44, 0xb5, 0x43, 0x14, 0x43, 0x74, 0x42, 0xd4, 0x41, 0x42, 0x41,
0xa4, 0x40, 0x18, 0x40, 0x85, 0x3f, 0xeb, 0x3e, 0x52, 0x3e, 0xb2, 0x3d,
0x0c, 0x3d, 0x7a, 0x3c, 0xdb, 0x3b, 0x3a, 0x3b, 0x87, 0x3a, 0xe0, 0x39,
0x29, 0x39, 0x88, 0x38, 0xd1, 0x37, 0x16, 0x37, 0x4d, 0x36, 0x9e, 0x35,
0xdc, 0x34, 0x19, 0x34, 0x4a, 0x33, 0x83, 0x32, 0xb7, 0x31, 0xec, 0x30,
0x1c, 0x30, 0x47, 0x2f, 0x71, 0x2e, 0x88, 0x2d, 0xa6, 0x2c, 0xbb, 0x2b,
0xd0, 0x2a, 0xd8, 0x29, 0xdb, 0x28, 0xe3, 0x27, 0xf5, 0x26, 0xf1, 0x25,
0xf8, 0x24, 0xdc, 0x23, 0xdb, 0x22, 0xca, 0x21, 0xa7, 0x20, 0x85, 0x1f,
0x5a, 0x1e, 0x30, 0x1d, 0x0a, 0x1c, 0xd5, 0x1a, 0xa6, 0x19, 0x6d, 0x18,
0x3d, 0x17, 0xff, 0x15, 0xbf, 0x14, 0x81, 0x13, 0x57, 0x12, 0x15, 0x11,
0xe0, 0x0f, 0xa2, 0x0e, 0x65, 0x0d, 0x27, 0x0c, 0xf1, 0x0a, 0xb2, 0x09,
0x77, 0x08, 0x4b, 0x07, 0x0a, 0x06, 0xc9, 0x04, 0x97, 0x03, 0x65, 0x02,
0x3b, 0x01, 0x03, 0x00, 0xd2, 0xfe, 0x95, 0xfd, 0x6f, 0xfc, 0x50, 0xfb,
0x19, 0xfa, 0xf0, 0xf8, 0xb8, 0xf7, 0x97, 0xf6, 0x65, 0xf5, 0x48, 0xf4,
0x24, 0xf3, 0xfe, 0xf1, 0xec, 0xf0, 0xd2, 0xef, 0xa9, 0xee, 0x95, 0xed,
0x76, 0xec, 0x64, 0xeb, 0x61, 0xea, 0x43, 0xe9, 0x3a, 0xe8, 0x21, 0xe7,
0x14, 0xe6, 0xff, 0xe4, 0x06, 0xe4, 0x04, 0xe3, 0x04, 0xe2, 0x01, 0xe1,
0x02, 0xe0, 0x04, 0xdf, 0x16, 0xde, 0x1f, 0xdd, 0x29, 0xdc, 0x2d, 0xdb,
0x3d, 0xda, 0x45, 0xd9, 0x5a, 0xd8, 0x6f, 0xd7, 0x74, 0xd6, 0x8a, 0xd5,
0x91, 0xd4, 0xa5, 0xd3, 0xbb, 0xd2, 0xdb, 0xd1, 0x01, 0xd1, 0x17, 0xd0,
0x42, 0xcf, 0x5e, 0xce, 0x94, 0xcd, 0xb1, 0xcc, 0xe8, 0xcb, 0x04, 0xcb,
0x29, 0xca, 0x4e, 0xc9, 0x78, 0xc8, 0x99, 0xc7, 0xc4, 0xc6, 0xff, 0xc5,
0x3d, 0xc5, 0x76, 0xc4, 0xa6, 0xc3, 0xe4, 0xc2, 0x17, 0xc2, 0x4e, 0xc1,
0x8a, 0xc0, 0xc5, 0xbf, 0x0b, 0xbf, 0x42, 0xbe, 0x8e, 0xbd, 0xd8, 0xbc,
0x20, 0xbc, 0x60, 0xbb, 0xbb, 0xba, 0x08, 0xba, 0x5a, 0xb9, 0xba, 0xb8,
0x08, 0xb8, 0x64, 0xb7, 0xb1, 0xb6, 0x0c, 0xb6, 0x5d, 0xb5, 0xbf, 0xb4,
0x10, 0xb4, 0x7b, 0xb3, 0xd0, 0xb2, 0x3d, 0xb2, 0xa1, 0xb1, 0x0f, 0xb1,
0x84, 0xb0, 0xf2, 0xaf, 0x63, 0xaf, 0xd3, 0xae, 0x50, 0xae, 0xbd, 0xad,
0x49, 0xad, 0xc1, 0xac, 0x4d, 0xac, 0xc6, 0xab, 0x56, 0xab, 0xe4, 0xaa,
0x83, 0xaa, 0x0d, 0xaa, 0xac, 0xa9, 0x49, 0xa9, 0xf3, 0xa8, 0x9e, 0xa8,
0x4e, 0xa8, 0x07, 0xa8, 0xc5, 0xa7, 0x8d, 0xa7, 0x56, 0xa7, 0x1d, 0xa7,
0xf6, 0xa6, 0xc7, 0xa6, 0xad, 0xa6, 0x8c, 0xa6, 0x74, 0xa6, 0x58, 0xa6,
0x47, 0xa6, 0x2d, 0xa6, 0x24, 0xa6, 0x23, 0xa6, 0x21, 0xa6, 0x19, 0xa6,
0x20, 0xa6, 0x1f, 0xa6, 0x28, 0xa6, 0x3c, 0xa6, 0x4e, 0xa6, 0x59, 0xa6,
0x6e, 0xa6, 0x84, 0xa6, 0x9a, 0xa6, 0xb7, 0xa6, 0xd4, 0xa6, 0xef, 0xa6,
0x0a, 0xa7, 0x2f, 0xa7, 0x53, 0xa7, 0x77, 0xa7, 0x9c, 0xa7, 0xbc, 0xa7,
0xe5, 0xa7, 0x10, 0xa8, 0x35, 0xa8, 0x6d, 0xa8, 0x9b, 0xa8, 0xcb, 0xa8,
0xf5, 0xa8, 0x23, 0xa9, 0x5a, 0xa9, 0x80, 0xa9, 0xb7, 0xa9, 0xee, 0xa9,
0x1c, 0xaa, 0x46, 0xaa, 0x78, 0xaa, 0xb2, 0xaa, 0xeb, 0xaa, 0x1a, 0xab,
0x57, 0xab, 0x84, 0xab, 0xba, 0xab, 0xef, 0xab, 0x22, 0xac, 0x55, 0xac,
0x88, 0xac, 0xc1, 0xac, 0xf5, 0xac, 0x2a, 0xad, 0x67, 0xad, 0x9f, 0xad,
0xe0, 0xad, 0x14, 0xae, 0x4c, 0xae, 0x82, 0xae, 0xb8, 0xae, 0xf8, 0xae,
0x2c, 0xaf, 0x6a, 0xaf, 0x9d, 0xaf, 0xd4, 0xaf, 0x05, 0xb0, 0x38, 0xb0,
0x77, 0xb0, 0xb2, 0xb0, 0xf8, 0xb0, 0x3c, 0xb1, 0x97, 0xb1, 0x05, 0xb2,
0x6f, 0xb2, 0xdf, 0xb2, 0x48, 0xb3, 0xb2, 0xb3, 0x16, 0xb4, 0x7b, 0xb4,
0xe5, 0xb4, 0x54, 0xb5, 0xc3, 0xb5, 0x26, 0xb6, 0x97, 0xb6, 0x03, 0xb7,
0x68, 0xb7, 0xce, 0xb7, 0x44, 0xb8, 0xae, 0xb8, 0x20, 0xb9, 0x87, 0xb9,
0xf1, 0xb9, 0x5d, 0xba, 0xc6, 0xba, 0x24, 0xbb, 0xa1, 0xbb, 0x05, 0xbc,
0x79, 0xbc, 0xdc, 0xbc, 0x4b, 0xbd, 0xba, 0xbd, 0x24, 0xbe, 0x9b, 0xbe,
0x07, 0xbf, 0x72, 0xbf, 0xe5, 0xbf, 0x46, 0xc0, 0xc3, 0xc0, 0x1f, 0xc1,
0x91, 0xc1, 0x01, 0xc2, 0x79, 0xc2, 0xf1, 0xc2, 0x66, 0xc3, 0xe5, 0xc3,
0x55, 0xc4, 0xc8, 0xc4, 0x3e, 0xc5, 0xb3, 0xc5, 0x2d, 0xc6, 0xa7, 0xc6,
0x27, 0xc7, 0x97, 0xc7, 0x1f, 0xc8, 0xa0, 0xc8, 0x29, 0xc9, 0xad, 0xc9,
0x36, 0xca, 0xad, 0xca, 0x3d, 0xcb, 0xc0, 0xcb, 0x47, 0xcc, 0xe9, 0xcc,
0x6f, 0xcd, 0x06, 0xce, 0x84, 0xce, 0x1a, 0xcf, 0xbb, 0xcf, 0x55, 0xd0,
0xf6, 0xd0, 0x8b, 0xd1, 0x30, 0xd2, 0xd2, 0xd2, 0x79, 0xd3, 0x1c, 0xd4,
0xcf, 0xd4, 0x83, 0xd5, 0x36, 0xd6, 0xe1, 0xd6, 0x96, 0xd7, 0x5f, 0xd8,
0x1c, 0xd9, 0xe2, 0xd9, 0xa8, 0xda, 0x6c, 0xdb, 0x43, 0xdc, 0x04, 0xdd,
0xd8, 0xdd, 0xac, 0xde, 0x8a, 0xdf, 0x5b, 0xe0, 0x39, 0xe1, 0x0b, 0xe2,
0xf5, 0xe2, 0xde, 0xe3, 0xbc, 0xe4, 0x9e, 0xe5, 0x83, 0xe6, 0x62, 0xe7,
0x51, 0xe8, 0x34, 0xe9, 0x1e, 0xea, 0x12, 0xeb, 0xf7, 0xeb, 0xe5, 0xec,
0xc5, 0xed, 0xc2, 0xee, 0xb1, 0xef, 0xa6, 0xf0, 0x90, 0xf1, 0x7e, 0xf2,
0x6f, 0xf3, 0x56, 0xf4, 0x48, 0xf5, 0x35, 0xf6, 0x29, 0xf7, 0x17, 0xf8,
0x0a, 0xf9, 0x00, 0xfa, 0xe7, 0xfa, 0xde, 0xfb, 0xc9, 0xfc, 0xc1, 0xfd,
0xac, 0xfe, 0xae, 0xff, 0xa2, 0x00, 0x8d, 0x01, 0x70, 0x02, 0x62, 0x03,
0x4e, 0x04, 0x3a, 0x05, 0x26, 0x06, 0x16, 0x07, 0xff, 0x07, 0xf3, 0x08,
0xda, 0x09, 0xbe, 0x0a, 0xb9, 0x0b, 0xa1, 0x0c, 0x9b, 0x0d, 0x7d, 0x0e,
0x66, 0x0f, 0x54, 0x10, 0x36, 0x11, 0x20, 0x12, 0x11, 0x13, 0xf3, 0x13,
0xea, 0x14, 0xd1, 0x15, 0xb6, 0x16, 0x9b, 0x17, 0x83, 0x18, 0x7f, 0x19,
0x58, 0x1a, 0x53, 0x1b, 0x37, 0x1c, 0x22, 0x1d, 0x0a, 0x1e, 0xf3, 0x1e,
0xda, 0x1f, 0xca, 0x20, 0xb1, 0x21, 0x96, 0x22, 0x70, 0x23, 0x55, 0x24,
0x39, 0x25, 0x39, 0x26, 0x1a, 0x27, 0x07, 0x28, 0xe1, 0x28, 0xc5, 0x29,
0xa7, 0x2a, 0x85, 0x2b, 0x70, 0x2c, 0x4e, 0x2d, 0x3e, 0x2e, 0x19, 0x2f,
0xf3, 0x2f, 0xdf, 0x30, 0xc0, 0x31, 0xaf, 0x32, 0x93, 0x33, 0x77, 0x34,
0x48, 0x35, 0x2a, 0x36, 0x0f, 0x37, 0xf8, 0x37, 0xd9, 0x38, 0xbe, 0x39,
0x8b, 0x3a, 0x74, 0x3b, 0x48, 0x3c, 0x2d, 0x3d, 0xfa, 0x3d, 0xe7, 0x3e,
0xb0, 0x3f, 0x98, 0x40, 0x67, 0x41, 0x3a, 0x42, 0x16, 0x43, 0xf4, 0x43,
0xd8, 0x44, 0xa4, 0x45, 0x7c, 0x46, 0x4c, 0x47, 0x2a, 0x48, 0x06, 0x49,
0xce, 0x49, 0xa5, 0x4a, 0x77, 0x4b, 0x4e, 0x4c, 0x13, 0x4d, 0xdf, 0x4d,
0xaa, 0x4e, 0x74, 0x4f, 0x3d, 0x50, 0xfc, 0x50, 0xbd, 0x51, 0x8c, 0x52,
0x3e, 0x53, 0xfe, 0x53, 0x99, 0x54, 0x57, 0x55, 0xfc, 0x55, 0xab, 0x56,
0x45, 0x57, 0xd6, 0x57, 0x87, 0x58, 0x2f, 0x59, 0xbf, 0x59, 0x48, 0x5a,
0xc7, 0x5a, 0x54, 0x5b, 0xc8, 0x5b, 0x45, 0x5c, 0xb4, 0x5c, 0x25, 0x5d,
0x7e, 0x5d, 0xda, 0x5d, 0x36, 0x5e, 0xa5, 0x5e, 0xe9, 0x5e, 0x37, 0x5f,
0x72, 0x5f, 0xab, 0x5f, 0xe5, 0x5f, 0x1d, 0x60, 0x4f, 0x60, 0x81, 0x60,
0x9c, 0x60, 0xc3, 0x60, 0xdc, 0x60, 0xf7, 0x60, 0x04, 0x61, 0x16, 0x61,
0x1b, 0x61, 0x21, 0x61, 0x20, 0x61, 0x0d, 0x61, 0x0b, 0x61, 0xf0, 0x60,
0xe5, 0x60, 0xc7, 0x60, 0xb3, 0x60, 0x98, 0x60, 0x7c, 0x60, 0x59, 0x60,
0x4c, 0x60, 0x24, 0x60, 0x0d, 0x60, 0xdf, 0x5f, 0xb7, 0x5f, 0x87, 0x5f,
0x6b, 0x5f, 0x44, 0x5f, 0x28, 0x5f, 0xf5, 0x5e, 0xbd, 0x5e, 0x8f, 0x5e,
0x5c, 0x5e, 0x2a, 0x5e, 0xfe, 0x5d, 0xcd, 0x5d, 0xa4, 0x5d, 0x75, 0x5d,
0x4d, 0x5d, 0x11, 0x5d, 0xdf, 0x5c, 0xa9, 0x5c, 0x78, 0x5c, 0x42, 0x5c,
0x13, 0x5c, 0xde, 0x5b, 0xaf, 0x5b, 0x75, 0x5b, 0x3e, 0x5b, 0xfd, 0x5a,
0xbc, 0x5a, 0x90, 0x5a, 0x54, 0x5a, 0x1f, 0x5a, 0xe5, 0x59, 0xc2, 0x59,
0x80, 0x59, 0x39, 0x59, 0x0a, 0x59, 0xd6, 0x58, 0x96, 0x58, 0x55, 0x58,
0x1e, 0x58, 0xf1, 0x57, 0xc8, 0x57, 0x7e, 0x57, 0x44, 0x57, 0x11, 0x57,
0xd4, 0x56, 0x93, 0x56, 0x4c, 0x56, 0x11, 0x56, 0xd7, 0x55, 0xae, 0x55,
0x72, 0x55, 0x3c, 0x55, 0x0c, 0x55, 0xd1, 0x54, 0x98, 0x54, 0x63, 0x54,
0x2b, 0x54, 0xf8, 0x53, 0xc6, 0x53, 0x81, 0x53, 0x4b, 0x53, 0x19, 0x53,
0xea, 0x52, 0xb2, 0x52, 0x7e, 0x52, 0x30, 0x52, 0xc5, 0x51, 0x46, 0x51,
0xca, 0x50, 0x55, 0x50, 0xd7, 0x4f, 0x5d, 0x4f, 0xe4, 0x4e, 0x79, 0x4e,
0xfb, 0x4d, 0x83, 0x4d, 0x02, 0x4d, 0x8a, 0x4c, 0x1f, 0x4c, 0x98, 0x4b,
0x20, 0x4b, 0xa7, 0x4a, 0x36, 0x4a, 0xc0, 0x49, 0x44, 0x49, 0xc3, 0x48,
0x44, 0x48, 0xd5, 0x47, 0x59, 0x47, 0xe6, 0x46, 0x63, 0x46, 0xf8, 0x45,
0x79, 0x45, 0xfa, 0x44, 0x80, 0x44, 0x01, 0x44, 0x7a, 0x43, 0x04, 0x43,
0x85, 0x42, 0x07, 0x42, 0x92, 0x41, 0x17, 0x41, 0x94, 0x40, 0x16, 0x40,
0x9f, 0x3f, 0x20, 0x3f, 0x9c, 0x3e, 0x29, 0x3e, 0x9c, 0x3d, 0x20, 0x3d,
0x88, 0x3c, 0x0c, 0x3c, 0x87, 0x3b, 0x07, 0x3b, 0x89, 0x3a, 0xfb, 0x39,
0x6f, 0x39, 0xe7, 0x38, 0x55, 0x38, 0xcf, 0x37, 0x43, 0x37, 0xb5, 0x36,
0x2a, 0x36, 0x9c, 0x35, 0x0a, 0x35, 0x83, 0x34, 0xe6, 0x33, 0x53, 0x33,
0xba, 0x32, 0x1d, 0x32, 0x78, 0x31, 0xcb, 0x30, 0x34, 0x30, 0x8e, 0x2f,
0xf6, 0x2e, 0x56, 0x2e, 0xab, 0x2d, 0xfe, 0x2c, 0x4c, 0x2c, 0x9f, 0x2b,
0xed, 0x2a, 0x36, 0x2a, 0x7b, 0x29, 0xb9, 0x28, 0x02, 0x28, 0x41, 0x27,
0x81, 0x26, 0xb9, 0x25, 0xfb, 0x24, 0x2d, 0x24, 0x66, 0x23, 0x98, 0x22,
0xc6, 0x21, 0xe9, 0x20, 0x0d, 0x20, 0x28, 0x1f, 0x4c, 0x1e, 0x64, 0x1d,
0x66, 0x1c, 0x8c, 0x1b, 0x96, 0x1a, 0xac, 0x19, 0xb2, 0x18, 0xbb, 0x17,
0xc2, 0x16, 0xc7, 0x15, 0xcb, 0x14, 0xcd, 0x13, 0xc4, 0x12, 0xca, 0x11,
0xb6, 0x10, 0xb8, 0x0f, 0xa3, 0x0e, 0x9e, 0x0d, 0x88, 0x0c, 0x86, 0x0b,
0x7b, 0x0a, 0x7c, 0x09, 0x6d, 0x08, 0x5b, 0x07, 0x4a, 0x06, 0x38, 0x05,
0x2f, 0x04, 0x1c, 0x03, 0x10, 0x02, 0xf6, 0x00, 0xe9, 0xff, 0xe5, 0xfe,
0xcf, 0xfd, 0xc8, 0xfc, 0xb1, 0xfb, 0xa7, 0xfa, 0x8d, 0xf9, 0x7b, 0xf8,
0x7e, 0xf7, 0x77, 0xf6, 0x68, 0xf5, 0x62, 0xf4, 0x49, 0xf3, 0x42, 0xf2,
0x41, 0xf1, 0x3e, 0xf0, 0x49, 0xef, 0x47, 0xee, 0x56, 0xed, 0x46, 0xec,
0x56, 0xeb, 0x5c, 0xea, 0x6c, 0xe9, 0x7d, 0xe8, 0x9c, 0xe7, 0x99, 0xe6,
0xbf, 0xe5, 0xc9, 0xe4, 0xe5, 0xe3, 0xfd, 0xe2, 0x17, 0xe2, 0x26, 0xe1,
0x44, 0xe0, 0x6d, 0xdf, 0x9f, 0xde, 0xc5, 0xdd, 0xec, 0xdc, 0x26, 0xdc,
0x58, 0xdb, 0x91, 0xda, 0xb7, 0xd9, 0xf5, 0xd8, 0x27, 0xd8, 0x63, 0xd7,
0x96, 0xd6, 0xd5, 0xd5, 0x1a, 0xd5, 0x52, 0xd4, 0x9d, 0xd3, 0xde, 0xd2,
0x27, 0xd2, 0x6c, 0xd1, 0xb3, 0xd0, 0xf6, 0xcf, 0x51, 0xcf, 0x98, 0xce,
0xe9, 0xcd, 0x2f, 0xcd, 0x88, 0xcc, 0xdc, 0xcb, 0x41, 0xcb, 0x9f, 0xca,
0x01, 0xca, 0x60, 0xc9, 0xc4, 0xc8, 0x13, 0xc8, 0x7e, 0xc7, 0xe2, 0xc6,
0x51, 0xc6, 0xb6, 0xc5, 0x1a, 0xc5, 0x8e, 0xc4, 0xf6, 0xc3, 0x74, 0xc3,
0xdf, 0xc2, 0x59, 0xc2, 0xd2, 0xc1, 0x47, 0xc1, 0xbe, 0xc0, 0x3b, 0xc0,
0xbe, 0xbf, 0x3e, 0xbf, 0xc4, 0xbe, 0x39, 0xbe, 0xbf, 0xbd, 0x3e, 0xbd,
0xd7, 0xbc, 0x5d, 0xbc, 0xec, 0xbb, 0x73, 0xbb, 0x07, 0xbb, 0x96, 0xba,
0x24, 0xba, 0xb5, 0xb9, 0x49, 0xb9, 0xdd, 0xb8, 0x76, 0xb8, 0x02, 0xb8,
0xa8, 0xb7, 0x3c, 0xb7, 0xee, 0xb6, 0x82, 0xb6, 0x2b, 0xb6, 0xc3, 0xb5,
0x6e, 0xb5, 0x14, 0xb5, 0xc4, 0xb4, 0x6b, 0xb4, 0x20, 0xb4, 0xd2, 0xb3,
0x78, 0xb3, 0x2c, 0xb3, 0xe6, 0xb2, 0x9e, 0xb2, 0x58, 0xb2, 0x1a, 0xb2,
0xea, 0xb1, 0xa6, 0xb1, 0x63, 0xb1, 0x2b, 0xb1, 0xf3, 0xb0, 0xb8, 0xb0,
0x7b, 0xb0, 0x4e, 0xb0, 0x20, 0xb0, 0xf9, 0xaf, 0xc6, 0xaf, 0xa2, 0xaf,
0x84, 0xaf, 0x5e, 0xaf, 0x44, 0xaf, 0x21, 0xaf, 0x06, 0xaf, 0xe9, 0xae,
0xe2, 0xae, 0xd0, 0xae, 0xc3, 0xae, 0xba, 0xae, 0xc1, 0xae, 0xaf, 0xae,
0xbc, 0xae, 0xb5, 0xae, 0xc0, 0xae, 0xc3, 0xae, 0xd7, 0xae, 0xdd, 0xae,
0xfb, 0xae, 0x0a, 0xaf, 0x16, 0xaf, 0x37, 0xaf, 0x4a, 0xaf, 0x70, 0xaf,
0x86, 0xaf, 0xa9, 0xaf, 0xc7, 0xaf, 0xec, 0xaf, 0x12, 0xb0, 0x42, 0xb0,
0x66, 0xb0, 0x91, 0xb0, 0xc0, 0xb0, 0xee, 0xb0, 0x1a, 0xb1, 0x4c, 0xb1,
0x77, 0xb1, 0xb3, 0xb1, 0xdd, 0xb1, 0x10, 0xb2, 0x47, 0xb2, 0x70, 0xb2,
0xb8, 0xb2, 0xef, 0xb2, 0x26, 0xb3, 0x64, 0xb3, 0x90, 0xb3, 0xd8, 0xb3,
0x07, 0xb4, 0x4b, 0xb4, 0x83, 0xb4, 0xc7, 0xb4, 0xf4, 0xb4, 0x35, 0xb5,
0x70, 0xb5, 0xbc, 0xb5, 0xf0, 0xb5, 0x39, 0xb6, 0x7d, 0xb6, 0xb7, 0xb6,
0xfa, 0xb6, 0x2e, 0xb7, 0x7d, 0xb7, 0xbb, 0xb7, 0x01, 0xb8, 0x39, 0xb8,
0x80, 0xb8, 0xbd, 0xb8, 0x05, 0xb9, 0x46, 0xb9, 0x94, 0xb9, 0xcd, 0xb9,
0x17, 0xba, 0x5b, 0xba, 0x9e, 0xba, 0xdf, 0xba, 0x27, 0xbb, 0x6a, 0xbb,
0xbc, 0xbb, 0xf6, 0xbb, 0x3a, 0xbc, 0x83, 0xbc, 0xc3, 0xbc, 0x16, 0xbd,
0x58, 0xbd, 0xa2, 0xbd, 0xe0, 0xbd, 0x24, 0xbe, 0x70, 0xbe, 0xa1, 0xbe,
0xfa, 0xbe, 0x37, 0xbf, 0x8d, 0xbf, 0xc9, 0xbf, 0x1d, 0xc0, 0x5d, 0xc0,
0xa6, 0xc0, 0xe6, 0xc0, 0x2f, 0xc1, 0x7a, 0xc1, 0xcb, 0xc1, 0x2f, 0xc2,
0x95, 0xc2, 0xfa, 0xc2, 0x55, 0xc3, 0xbb, 0xc3, 0x1e, 0xc4, 0x86, 0xc4,
0xec, 0xc4, 0x4b, 0xc5, 0xab, 0xc5, 0x04, 0xc6, 0x72, 0xc6, 0xc6, 0xc6,
0x3a, 0xc7, 0x8e, 0xc7, 0xfd, 0xc7, 0x5a, 0xc8, 0xc0, 0xc8, 0x17, 0xc9,
0x79, 0xc9, 0xd5, 0xc9, 0x43, 0xca, 0x98, 0xca, 0x05, 0xcb, 0x64, 0xcb,
0xc3, 0xcb, 0x1e, 0xcc, 0x81, 0xcc, 0xe3, 0xcc, 0x40, 0xcd, 0xa6, 0xcd,
0x0a, 0xce, 0x6a, 0xce, 0xc0, 0xce, 0x26, 0xcf, 0x81, 0xcf, 0xf0, 0xcf,
0x48, 0xd0, 0xad, 0xd0, 0x07, 0xd1, 0x71, 0xd1, 0xca, 0xd1, 0x2b, 0xd2,
0x8a, 0xd2, 0xed, 0xd2, 0x50, 0xd3, 0xa1, 0xd3, 0x0f, 0xd4, 0x6f, 0xd4,
0xd6, 0xd4, 0x30, 0xd5, 0x93, 0xd5, 0xf6, 0xd5, 0x55, 0xd6, 0xb5, 0xd6,
0x12, 0xd7, 0x7b, 0xd7, 0xde, 0xd7, 0x34, 0xd8, 0x93, 0xd8, 0xe9, 0xd8,
0x61, 0xd9, 0xbb, 0xd9, 0x2b, 0xda, 0x88, 0xda, 0xeb, 0xda, 0x4f, 0xdb,
0xb9, 0xdb, 0x21, 0xdc, 0x80, 0xdc, 0xf7, 0xdc, 0x53, 0xdd, 0xbb, 0xdd,
0x2b, 0xde, 0xa4, 0xde, 0x05, 0xdf, 0x74, 0xdf, 0xd8, 0xdf, 0x44, 0xe0,
0xb4, 0xe0, 0x26, 0xe1, 0x91, 0xe1, 0x01, 0xe2, 0x77, 0xe2, 0xeb, 0xe2,
0x5e, 0xe3, 0xc7, 0xe3, 0x44, 0xe4, 0xb2, 0xe4, 0x25, 0xe5, 0xa3, 0xe5,
0x15, 0xe6, 0x97, 0xe6, 0x0b, 0xe7, 0x8b, 0xe7, 0x10, 0xe8, 0x7d, 0xe8,
0x06, 0xe9, 0x74, 0xe9, 0xff, 0xe9, 0x82, 0xea, 0x01, 0xeb, 0x85, 0xeb,
0xfa, 0xeb, 0x91, 0xec, 0x07, 0xed, 0x8f, 0xed, 0x15, 0xee, 0x9a, 0xee,
0x26, 0xef, 0xa5, 0xef, 0x26, 0xf0, 0xb2, 0xf0, 0x3e, 0xf1, 0xca, 0xf1,
0x45, 0xf2, 0xcc, 0xf2, 0x51, 0xf3, 0xdc, 0xf3, 0x5c, 0xf4, 0xe8, 0xf4,
0x6e, 0xf5, 0xf9, 0xf5, 0x79, 0xf6, 0xf9, 0xf6, 0x7d, 0xf7, 0x08, 0xf8,
0x91, 0xf8, 0x18, 0xf9, 0x95, 0xf9, 0x18, 0xfa, 0xa5, 0xfa, 0x21, 0xfb,
0xa9, 0xfb, 0x2a, 0xfc, 0xa7, 0xfc, 0x23, 0xfd, 0xa3, 0xfd, 0x2b, 0xfe,
0x9c, 0xfe, 0x2b, 0xff, 0xa0, 0xff, 0x1c, 0x00, 0x9a, 0x00, 0x11, 0x01,
0x9a, 0x01, 0x14, 0x02, 0x8c, 0x02, 0x07, 0x03, 0x84, 0x03, 0xf7, 0x03,
0x75, 0x04, 0xf3, 0x04, 0x65, 0x05, 0xe8, 0x05, 0x54, 0x06, 0xd3, 0x06,
0x48, 0x07, 0xc2, 0x07, 0x38, 0x08, 0xad, 0x08, 0x28, 0x09, 0x99, 0x09,
0x11, 0x0a, 0x79, 0x0a, 0xf5, 0x0a, 0x5c, 0x0b, 0xd1, 0x0b, 0x3f, 0x0c,
0xb5, 0x0c, 0x2c, 0x0d, 0x9a, 0x0d, 0x0b, 0x0e, 0x74, 0x0e, 0xe6, 0x0e,
0x45, 0x0f, 0xbd, 0x0f, 0x2f, 0x10, 0x9a, 0x10, 0x05, 0x11, 0x6c, 0x11,
0xdb, 0x11, 0x40, 0x12, 0xaa, 0x12, 0x14, 0x13, 0x81, 0x13, 0xe9, 0x13,
0x4d, 0x14, 0xb9, 0x14, 0x18, 0x15, 0x88, 0x15, 0xe6, 0x15, 0x58, 0x16,
0xb9, 0x16, 0x1c, 0x17, 0x7e, 0x17, 0xe3, 0x17, 0x43, 0x18, 0xac, 0x18,
0x08, 0x19, 0x6d, 0x19, 0xce, 0x19, 0x34, 0x1a, 0x90, 0x1a, 0xf5, 0x1a,
0x53, 0x1b, 0xbb, 0x1b, 0x07, 0x1c, 0x6f, 0x1c, 0xc2, 0x1c, 0x28, 0x1d,
0x84, 0x1d, 0xe8, 0x1d, 0x35, 0x1e, 0xa2, 0x1e, 0xf8, 0x1e, 0x59, 0x1f,
0xb8, 0x1f, 0x0c, 0x20, 0x69, 0x20, 0xbe, 0x20, 0x19, 0x21, 0x66, 0x21,
0xc6, 0x21, 0x1f, 0x22, 0x70, 0x22, 0xbe, 0x22, 0x18, 0x23, 0x72, 0x23,
0xbf, 0x23, 0x0f, 0x24, 0x67, 0x24, 0xc0, 0x24, 0x08, 0x25, 0x51, 0x25,
0xa6, 0x25, 0xf4, 0x25, 0x42, 0x26, 0x93, 0x26, 0xd6, 0x26, 0x25, 0x27,
0x6c, 0x27, 0xb7, 0x27, 0x07, 0x28, 0x49, 0x28, 0x96, 0x28, 0xda, 0x28,
0x22, 0x29, 0x66, 0x29, 0xa4, 0x29, 0xe8, 0x29, 0x20, 0x2a, 0x62, 0x2a,
0xa9, 0x2a, 0xe5, 0x2a, 0x21, 0x2b, 0x5a, 0x2b, 0x97, 0x2b, 0xc1, 0x2b,
0xfe, 0x2b, 0x28, 0x2c, 0x57, 0x2c, 0x88, 0x2c, 0xae, 0x2c, 0xd3, 0x2c,
0xfa, 0x2c, 0x17, 0x2d, 0x33, 0x2d, 0x4b, 0x2d, 0x5d, 0x2d, 0x68, 0x2d,
0x81, 0x2d, 0x92, 0x2d, 0x9e, 0x2d, 0xa9, 0x2d, 0xbb, 0x2d, 0xc3, 0x2d,
0xcd, 0x2d, 0xd5, 0x2d, 0xcd, 0x2d, 0xdc, 0x2d, 0xe3, 0x2d, 0xe1, 0x2d,
0xdd, 0x2d, 0xd9, 0x2d, 0xd7, 0x2d, 0xcf, 0x2d, 0xe0, 0x2d, 0xd2, 0x2d,
0xd2, 0x2d, 0xcb, 0x2d, 0xb7, 0x2d, 0xb6, 0x2d, 0xa1, 0x2d, 0x9e, 0x2d,
0x8b, 0x2d, 0x84, 0x2d, 0x68, 0x2d, 0x6a, 0x2d, 0x4e, 0x2d, 0x45, 0x2d,
0x2f, 0x2d, 0x18, 0x2d, 0x15, 0x2d, 0xef, 0x2c, 0xe8, 0x2c, 0xc9, 0x2c,
0xc7, 0x2c, 0xaa, 0x2c, 0x9b, 0x2c, 0x7c, 0x2c, 0x64, 0x2c, 0x3c, 0x2c,
0x2e, 0x2c, 0x16, 0x2c, 0x05, 0x2c, 0xe1, 0x2b, 0xc8, 0x2b, 0xb5, 0x2b,
0x9a, 0x2b, 0x7c, 0x2b, 0x61, 0x2b, 0x3f, 0x2b, 0x21, 0x2b, 0x01, 0x2b,
0xee, 0x2a, 0xd0, 0x2a, 0xb3, 0x2a, 0x95, 0x2a, 0x6d, 0x2a, 0x50, 0x2a,
0x2b, 0x2a, 0x0b, 0x2a, 0xe9, 0x29, 0xd1, 0x29, 0xa8, 0x29, 0x97, 0x29,
0x6c, 0x29, 0x51, 0x29, 0x24, 0x29, 0x03, 0x29, 0xe6, 0x28, 0xbe, 0x28,
0xa1, 0x28, 0x80, 0x28, 0x64, 0x28, 0x38, 0x28, 0x12, 0x28, 0xf0, 0x27,
0xd3, 0x27, 0xac, 0x27, 0x94, 0x27, 0x67, 0x27, 0x4a, 0x27, 0x1c, 0x27,
0xf7, 0x26, 0xd1, 0x26, 0xb6, 0x26, 0x8d, 0x26, 0x6e, 0x26, 0x4b, 0x26,
0x25, 0x26, 0x02, 0x26, 0xd8, 0x25, 0xbe, 0x25, 0x93, 0x25, 0x7c, 0x25,
0x4a, 0x25, 0x27, 0x25, 0x07, 0x25, 0xdc, 0x24, 0xbb, 0x24, 0x9a, 0x24,
0x78, 0x24, 0x4c, 0x24, 0x26, 0x24, 0x00, 0x24, 0xd7, 0x23, 0xc0, 0x23,
0x94, 0x23, 0x71, 0x23, 0x45, 0x23, 0x1c, 0x23, 0x00, 0x23, 0xd4, 0x22,
0xb5, 0x22, 0x8e, 0x22, 0x67, 0x22, 0x39, 0x22, 0x00, 0x22, 0xbd, 0x21,
0x87, 0x21, 0x46, 0x21, 0x01, 0x21, 0xca, 0x20, 0x89, 0x20, 0x4a, 0x20,
0x17, 0x20, 0xd6, 0x1f, 0x9a, 0x1f, 0x5e, 0x1f, 0x20, 0x1f, 0xe0, 0x1e,
0xa3, 0x1e, 0x5f, 0x1e, 0x29, 0x1e, 0xf0, 0x1d, 0xb8, 0x1d, 0x78, 0x1d,
0x36, 0x1d, 0x04, 0x1d, 0xc6, 0x1c, 0x8b, 0x1c, 0x4d, 0x1c, 0x18, 0x1c,
0xd9, 0x1b, 0x97, 0x1b, 0x5c, 0x1b, 0x2b, 0x1b, 0xf4, 0x1a, 0xb1, 0x1a,
0x7c, 0x1a, 0x32, 0x1a, 0x02, 0x1a, 0xc6, 0x19, 0x8b, 0x19, 0x59, 0x19,
0x10, 0x19, 0xd7, 0x18, 0x9c, 0x18, 0x62, 0x18, 0x22, 0x18, 0xe8, 0x17,
0xb1, 0x17, 0x7c, 0x17, 0x34, 0x17, 0xf9, 0x16, 0xc0, 0x16, 0x8b, 0x16,
0x55, 0x16, 0x14, 0x16, 0xdd, 0x15, 0x9f, 0x15, 0x65, 0x15, 0x2b, 0x15,
0xea, 0x14, 0xb9, 0x14, 0x70, 0x14, 0x3d, 0x14, 0x05, 0x14, 0xc1, 0x13,
0x86, 0x13, 0x45, 0x13, 0x09, 0x13, 0xca, 0x12, 0x90, 0x12, 0x57, 0x12,
0x1a, 0x12, 0xe1, 0x11, 0x9b, 0x11, 0x61, 0x11, 0x1d, 0x11, 0xe1, 0x10,
0x9d, 0x10, 0x64, 0x10, 0x17, 0x10, 0xde, 0x0f, 0xa1, 0x0f, 0x60, 0x0f,
0x1b, 0x0f, 0xd8, 0x0e, 0x90, 0x0e, 0x5b, 0x0e, 0x0e, 0x0e, 0xd3, 0x0d,
0x86, 0x0d, 0x4d, 0x0d, 0xf5, 0x0c, 0xba, 0x0c, 0x68, 0x0c, 0x2a, 0x0c,
0xde, 0x0b, 0x94, 0x0b, 0x4e, 0x0b, 0x07, 0x0b, 0xbb, 0x0a, 0x6c, 0x0a,
0x25, 0x0a, 0xd4, 0x09, 0x89, 0x09, 0x39, 0x09, 0xe6, 0x08, 0xa3, 0x08,
0x4f, 0x08, 0x02, 0x08, 0xa7, 0x07, 0x5f, 0x07, 0x08, 0x07, 0xba, 0x06,
0x68, 0x06, 0x1f, 0x06, 0xc5, 0x05, 0x7a, 0x05, 0x1f, 0x05, 0xd7, 0x04,
0x85, 0x04, 0x31, 0x04, 0xde, 0x03, 0x89, 0x03, 0x3a, 0x03, 0xe9, 0x02,
0x96, 0x02, 0x47, 0x02, 0xf7, 0x01, 0xa4, 0x01, 0x5d, 0x01, 0x06, 0x01,
0xb9, 0x00, 0x00, 0x00
};
unsigned int kick_raw_len = 6352;
| 59.044586 | 74 | 0.641855 | newdigate |
f8fc1b11572be70b4491f7245d385e3855af1bae | 2,892 | hpp | C++ | include/Error.hpp | auroralimin/montador-assembly-inventado | b7deeb4a00f27e941636921a84d5222dd7b008a5 | [
"Apache-2.0"
] | null | null | null | include/Error.hpp | auroralimin/montador-assembly-inventado | b7deeb4a00f27e941636921a84d5222dd7b008a5 | [
"Apache-2.0"
] | null | null | null | include/Error.hpp | auroralimin/montador-assembly-inventado | b7deeb4a00f27e941636921a84d5222dd7b008a5 | [
"Apache-2.0"
] | null | null | null | #ifndef MONT_ERROR_HPP
#define MONT_ERROR_HPP
#include <string>
namespace mont {
/**
* @enum mont::errorType
* @brief Enum para os tipos de erro a serem mostrados
*/
enum errorType {
lexical,
sintatic,
semantic,
warning
};
/**
* @brief Classe responsável pelo tratamento e saída de erros
* Essa classe possui funções para impressão de erros e guarda se
* algum erro já foi detectado no código-fonte
*/
class Error {
public:
/**
* @brief Construtor da classe
*
* @param src é um std::string contendo o nome do arquivo de entrada
*/
Error(std::string src);
/**
* @brief Imprime um erro inspirado na formatação do clang++
*
* @param nLine é um int contendo o número da linha com o erro
* @param begin é um std::string contendo onde na linha o erro\
* começou
* @param msg é um std::string contendo o corpo da mensagem de erro
* @para type é um mont::errorType contendo o tipo do erro
*/
void printError(int nLine, std::string begin,
std::string msg, errorType type);
/**
* @brief Gera uma mensagem de erro para quantidade de operandos\
* inválida
*
* @param name é um std::string contendo o nome da instrução
* @param n1 é um int contendo o número de operandos esperado
* @param n2 é um int contendo o número de operandos obtido
*
* @retval eMsg < em todos os casos retorna a mensagem gerada
*/
std::string instError(std::string name, int n1, int n2);
/**
* @brief Seta a flag de erros indicando que houve erro(s)
*/
void hasError();
/**
* @brief Pega a flag que indica se houverão erros na montagem
*
* @retval true < caso haja um ou mais erros
* @retval false > caso não haja nenhum erro
*/
bool getErrorFlag();
/**
* @brief Checa se uma substring esta contida em uma linha do código
*
* @param nLine é o int com o número da linha do código-fonte
* @param substr é um std::string com a substring procurada
*
* @retval true < caso tenha encontrado a substring
* @retval false < caso não tenha encontrado a substring
*/
bool hasSubstr(int nLine, std::string substr);
private:
std::string src; /**< nome do arquivo fonte */
bool errorFlag; /**< flag que indica se um erro ocorreu */
};
}
#endif
| 33.241379 | 80 | 0.525242 | auroralimin |
f8fd44ee4ab5a777006ee2d55f567d2cfe3f847c | 549 | hpp | C++ | demos/glyph_paint/glyph_paint.hpp | thknepper/CPPurses | 4f35ba5284bc5ac563214f73f494bd75fd5bf73b | [
"MIT"
] | 1 | 2020-02-22T21:18:11.000Z | 2020-02-22T21:18:11.000Z | demos/glyph_paint/glyph_paint.hpp | thknepper/CPPurses | 4f35ba5284bc5ac563214f73f494bd75fd5bf73b | [
"MIT"
] | null | null | null | demos/glyph_paint/glyph_paint.hpp | thknepper/CPPurses | 4f35ba5284bc5ac563214f73f494bd75fd5bf73b | [
"MIT"
] | null | null | null | #ifndef DEMOS_GLYPH_PAINT_GLYPH_PAINT_HPP
#define DEMOS_GLYPH_PAINT_GLYPH_PAINT_HPP
#include "paint_area.hpp"
#include "side_pane.hpp"
#include <cppurses/widget/layouts/horizontal.hpp>
namespace demos {
namespace glyph_paint {
class Glyph_paint : public cppurses::layout::Horizontal<> {
public:
Glyph_paint();
private:
Paint_area& paint_area{this->make_child<Paint_area>()};
Side_pane& side_pane{this->make_child<Side_pane>()};
};
} // namespace glyph_paint
} // namespace demos
#endif // DEMOS_GLYPH_PAINT_GLYPH_PAINT_HPP
| 23.869565 | 59 | 0.763206 | thknepper |
f8fe4852816ae74326a9fa3f58c0f121ed8656fb | 4,061 | hpp | C++ | NodeContainer.hpp | chrisoldwood/XML | 78913e7b9fbc1fbfec3779652d034ebd150668bc | [
"MIT"
] | 1 | 2020-09-11T13:21:05.000Z | 2020-09-11T13:21:05.000Z | NodeContainer.hpp | chrisoldwood/XML | 78913e7b9fbc1fbfec3779652d034ebd150668bc | [
"MIT"
] | null | null | null | NodeContainer.hpp | chrisoldwood/XML | 78913e7b9fbc1fbfec3779652d034ebd150668bc | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
//! \file NodeContainer.hpp
//! \brief The NodeContainer class declaration.
//! \author Chris Oldwood
// Check for previous inclusion
#ifndef XML_NODECONTAINER_HPP
#define XML_NODECONTAINER_HPP
#if _MSC_VER > 1000
#pragma once
#endif
#include "Node.hpp"
#include <vector>
#include <Core/BadLogicException.hpp>
namespace XML
{
//! The default container type for a collection of Nodes.
typedef std::vector<NodePtr> Nodes;
////////////////////////////////////////////////////////////////////////////////
//! The mix-in class used for node types that can contain other nodes. The outer
//! parent node is held internally so that we can fix up the child nodes here
//! automatically.
class NodeContainer /*: private NotCopyable*/
{
public:
//! The container const iterator.
typedef Nodes::const_iterator const_iterator;
//! The container iterator.
typedef Nodes::iterator iterator;
//
// Properties.
//
//! Query if the node has any child nodes.
bool hasChildren() const;
//! Get the count of child nodes.
size_t getChildCount() const;
//! Get a child by its index.
NodePtr getChild(size_t index) const;
//! Get a child by its index.
template<typename T>
Core::RefCntPtr<T> getChild(size_t index) const;
//! Get the start iterator for the child nodes.
const_iterator beginChild() const;
//! Get the end iterator for the child nodes.
const_iterator endChild() const;
//! Get the start iterator for the child nodes.
iterator beginChild();
//! Get the end iterator for the child nodes.
iterator endChild();
//
// Methods.
//
//! Append a child node.
void appendChild(NodePtr& node);
//! Append a child node.
template<typename T>
void appendChild(Core::RefCntPtr<T> node);
protected:
//! Constructor.
NodeContainer(Node* parent);
//! Destructor.
virtual ~NodeContainer();
private:
//
// Members.
//
Node* m_parent; //!< The outer parent node.
Nodes m_childNodes; //!< The collection of child nodes.
// NotCopyable.
NodeContainer(const NodeContainer&);
NodeContainer& operator=(const NodeContainer);
};
////////////////////////////////////////////////////////////////////////////////
//! Query if the node has any child nodes.
inline bool NodeContainer::hasChildren() const
{
return !m_childNodes.empty();
}
////////////////////////////////////////////////////////////////////////////////
//! Get the count of child nodes.
inline size_t NodeContainer::getChildCount() const
{
return m_childNodes.size();
}
////////////////////////////////////////////////////////////////////////////////
//! Get a child by its index.
template<typename T>
inline Core::RefCntPtr<T> NodeContainer::getChild(size_t index) const
{
Core::RefCntPtr<T> node = Core::dynamic_ptr_cast<T>(getChild(index));
if (node.get() == nullptr)
throw Core::BadLogicException(TXT("Failed to downcast node type"));
return node;
}
////////////////////////////////////////////////////////////////////////////////
//! Get the start iterator for the child nodes.
inline NodeContainer::const_iterator NodeContainer::beginChild() const
{
return m_childNodes.begin();
}
////////////////////////////////////////////////////////////////////////////////
//! Get the end iterator for the child nodes.
inline NodeContainer::const_iterator NodeContainer::endChild() const
{
return m_childNodes.end();
}
////////////////////////////////////////////////////////////////////////////////
//! Get the start iterator for the child nodes.
inline NodeContainer::iterator NodeContainer::beginChild()
{
return m_childNodes.begin();
}
////////////////////////////////////////////////////////////////////////////////
//! Get the end iterator for the child nodes.
inline NodeContainer::iterator NodeContainer::endChild()
{
return m_childNodes.end();
}
//! Append a child node.
template<typename T>
inline void NodeContainer::appendChild(Core::RefCntPtr<T> node)
{
NodePtr p = node;
appendChild(p);
}
//namespace XML
}
#endif // XML_NODECONTAINER_HPP
| 23.748538 | 80 | 0.59542 | chrisoldwood |
5d06deaf663fa615ba011fd8b3608d128e365532 | 1,730 | cpp | C++ | source/generic/s3eYahooGamesAdTrack_register.cpp | salqadri/s3eYahooGamesAdTrack | 5183757b8fa03a6a1d368dc22e5364445209a290 | [
"MIT"
] | null | null | null | source/generic/s3eYahooGamesAdTrack_register.cpp | salqadri/s3eYahooGamesAdTrack | 5183757b8fa03a6a1d368dc22e5364445209a290 | [
"MIT"
] | null | null | null | source/generic/s3eYahooGamesAdTrack_register.cpp | salqadri/s3eYahooGamesAdTrack | 5183757b8fa03a6a1d368dc22e5364445209a290 | [
"MIT"
] | null | null | null | /*
* WARNING: this is an autogenerated file and will be overwritten by
* the extension interface script.
*/
/*
* This file contains the automatically generated loader-side
* functions that form part of the extension.
*
* This file is awlays compiled into all loaders but compiles
* to nothing if this extension is not enabled in the loader
* at build time.
*/
#include "s3eYahooGamesAdTrack_autodefs.h"
#include "s3eEdk.h"
#include "s3eYahooGamesAdTrack.h"
//Declarations of Init and Term functions
extern s3eResult s3eYahooGamesAdTrackInit();
extern void s3eYahooGamesAdTrackTerminate();
void s3eYahooGamesAdTrackRegisterExt()
{
/* fill in the function pointer struct for this extension */
void* funcPtrs[4];
funcPtrs[0] = (void*)ygnAdTrackStart;
funcPtrs[1] = (void*)ygnAdTrackStop;
funcPtrs[2] = (void*)ygnAdTrackTrackExternalPayment;
funcPtrs[3] = (void*)ygnAdTrackTrackGetInstalledSource;
/*
* Flags that specify the extension's use of locking and stackswitching
*/
int flags[4] = { 0 };
/*
* Register the extension
*/
s3eEdkRegister("s3eYahooGamesAdTrack", funcPtrs, sizeof(funcPtrs), flags, s3eYahooGamesAdTrackInit, s3eYahooGamesAdTrackTerminate, 0);
}
#if !defined S3E_BUILD_S3ELOADER
#if defined S3E_EDK_USE_STATIC_INIT_ARRAY
int s3eYahooGamesAdTrackStaticInit()
{
void** p = g_StaticInitArray;
void* end = p + g_StaticArrayLen;
while (*p) p++;
if (p < end)
*p = (void*)&s3eYahooGamesAdTrackRegisterExt;
return 0;
}
int g_s3eYahooGamesAdTrackVal = s3eYahooGamesAdTrackStaticInit();
#elif defined S3E_EDK_USE_DLLS
S3E_EXTERN_C S3E_DLL_EXPORT void RegisterExt()
{
s3eYahooGamesAdTrackRegisterExt();
}
#endif
#endif
| 27.03125 | 134 | 0.736416 | salqadri |
5d0833a25625749a373427e259501c8b3680a949 | 1,562 | hpp | C++ | src/org/apache/poi/wp/usermodel/CharacterRun.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/wp/usermodel/CharacterRun.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | src/org/apache/poi/wp/usermodel/CharacterRun.hpp | pebble2015/cpoi | 6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6 | [
"Apache-2.0"
] | null | null | null | // Generated from /POI/java/org/apache/poi/wp/usermodel/CharacterRun.java
#pragma once
#include <fwd-POI.hpp>
#include <java/lang/fwd-POI.hpp>
#include <org/apache/poi/wp/usermodel/fwd-POI.hpp>
#include <java/lang/Object.hpp>
struct poi::wp::usermodel::CharacterRun
: public virtual ::java::lang::Object
{
virtual bool isBold() = 0;
virtual void setBold(bool bold) = 0;
virtual bool isItalic() = 0;
virtual void setItalic(bool italic) = 0;
virtual bool isSmallCaps() = 0;
virtual void setSmallCaps(bool smallCaps) = 0;
virtual bool isCapitalized() = 0;
virtual void setCapitalized(bool caps) = 0;
virtual bool isStrikeThrough() = 0;
virtual void setStrikeThrough(bool strike) = 0;
virtual bool isDoubleStrikeThrough() = 0;
virtual void setDoubleStrikethrough(bool dstrike) = 0;
virtual bool isShadowed() = 0;
virtual void setShadow(bool shadow) = 0;
virtual bool isEmbossed() = 0;
virtual void setEmbossed(bool emboss) = 0;
virtual bool isImprinted() = 0;
virtual void setImprinted(bool imprint) = 0;
virtual int32_t getFontSize() = 0;
virtual void setFontSize(int32_t halfPoints) = 0;
virtual int32_t getCharacterSpacing() = 0;
virtual void setCharacterSpacing(int32_t twips) = 0;
virtual int32_t getKerning() = 0;
virtual void setKerning(int32_t kern) = 0;
virtual bool isHighlighted() = 0;
virtual ::java::lang::String* getFontName() = 0;
virtual ::java::lang::String* text() = 0;
// Generated
static ::java::lang::Class *class_();
};
| 35.5 | 73 | 0.68758 | pebble2015 |
5d0c66af633759297ec5898c41ea946db9d71e96 | 17,676 | cpp | C++ | src/software/ai/navigator/path_planner/theta_star_path_planner.cpp | EvanMorcom/Software | 586fb3cf8dc2d93de194d9815af5de63caa7e318 | [
"MIT"
] | null | null | null | src/software/ai/navigator/path_planner/theta_star_path_planner.cpp | EvanMorcom/Software | 586fb3cf8dc2d93de194d9815af5de63caa7e318 | [
"MIT"
] | null | null | null | src/software/ai/navigator/path_planner/theta_star_path_planner.cpp | EvanMorcom/Software | 586fb3cf8dc2d93de194d9815af5de63caa7e318 | [
"MIT"
] | null | null | null | #include "software/ai/navigator/path_planner/theta_star_path_planner.h"
#include <stack>
#include "software/logger/logger.h"
#include "software/new_geom/util/distance.h"
#include "software/new_geom/util/intersects.h"
ThetaStarPathPlanner::ThetaStarPathPlanner()
: num_grid_rows(0),
num_grid_cols(0),
max_navigable_x_coord(0),
max_navigable_y_coord(0)
{
}
bool ThetaStarPathPlanner::isCoordNavigable(const Coordinate &coord) const
{
// Returns true if row number and column number is in range
return (coord.row() < num_grid_rows) && (coord.col() < num_grid_cols);
}
bool ThetaStarPathPlanner::isUnblocked(const Coordinate &coord)
{
// If we haven't checked this Coordinate for obstacles before, check it now
unsigned long coord_key = computeMapKey(coord);
auto unblocked_grid_it = unblocked_grid.find(coord_key);
if (unblocked_grid_it == unblocked_grid.end())
{
bool blocked = false;
Point p = convertCoordToPoint(coord);
for (auto &obstacle : obstacles)
{
if (obstacle->contains(p))
{
blocked = true;
break;
}
}
// We use the opposite convention to indicate blocked or not
unblocked_grid[coord_key] = !blocked;
return !blocked;
}
return unblocked_grid_it->second;
}
double ThetaStarPathPlanner::coordDistance(const Coordinate &coord1,
const Coordinate &coord2) const
{
Point p1(coord1.row(), coord1.col());
Point p2(coord2.row(), coord2.col());
return distance(p1, p2);
}
bool ThetaStarPathPlanner::lineOfSight(const Coordinate &coord1, const Coordinate &coord2)
{
unsigned long coordinate_pair_key = computeMapKey(coord1, coord2);
// If we haven't checked this Coordinate pair for intersects before, check it now
auto line_of_sight_cache_it = line_of_sight_cache.find(coordinate_pair_key);
if (line_of_sight_cache_it == line_of_sight_cache.end())
{
Segment seg(convertCoordToPoint(coord1), convertCoordToPoint(coord2));
bool has_line_of_sight = true;
for (const auto &obstacle : obstacles)
{
if (obstacle->intersects(seg))
{
has_line_of_sight = false;
break;
}
}
// We use the opposite convention to indicate blocked or not
line_of_sight_cache[coordinate_pair_key] = has_line_of_sight;
return has_line_of_sight;
}
return line_of_sight_cache_it->second;
}
std::vector<Point> ThetaStarPathPlanner::tracePath(const Coordinate &end) const
{
Coordinate current = end;
std::vector<Point> path_points;
std::stack<Coordinate> path;
// loop until parent equals current
while (!(cell_heuristics[current.row()][current.col()].parent() == current))
{
path.push(current);
current = cell_heuristics[current.row()][current.col()].parent();
}
path.push(current);
while (!path.empty())
{
Coordinate p = path.top();
path.pop();
path_points.push_back(convertCoordToPoint(p));
}
return path_points;
}
bool ThetaStarPathPlanner::updateVertex(const Coordinate ¤t, const Coordinate &next,
const Coordinate &end)
{
// Only process this CellHeuristic if this is a navigable one
if (isCoordNavigable(next))
{
// If the successor is already on the closed list or if it is blocked, then ignore
// it. Else do the following
if (closed_list.find(next) == closed_list.end() && isUnblocked(next))
{
double updated_best_path_cost;
Coordinate next_parent;
Coordinate parent = cell_heuristics[current.row()][current.col()].parent();
if (lineOfSight(parent, next))
{
next_parent = parent;
updated_best_path_cost =
cell_heuristics[parent.row()][parent.col()].bestPathCost() +
coordDistance(parent, next);
}
else
{
next_parent = current;
updated_best_path_cost =
cell_heuristics[current.row()][current.col()].bestPathCost() +
coordDistance(current, next);
}
double next_start_to_end_cost_estimate =
updated_best_path_cost + coordDistance(next, end);
// If it isn’t on the open list, add it to the open list. Make the current
// square the parent of this square. Record start_to_end_cost_estimate,
// and best_path_cost of the square CellHeuristic
// OR
// If it is on the open list already, check to see if this path to that square
// is better, using start_to_end_cost_estimate as the measure.
if (!cell_heuristics[next.row()][next.col()].isInitialized() ||
cell_heuristics[next.row()][next.col()].pathCostAndEndDistHeuristic() >
next_start_to_end_cost_estimate)
{
open_list.insert(std::make_pair(next_start_to_end_cost_estimate, next));
// Update the details of this CellHeuristic
cell_heuristics[next.row()][next.col()].update(
next_parent, next_start_to_end_cost_estimate, updated_best_path_cost);
}
// If the end is the same as the current successor
if (next == end)
{
return true;
}
}
}
return false;
}
std::optional<Path> ThetaStarPathPlanner::findPath(
const Point &start, const Point &end, const Rectangle &navigable_area,
const std::vector<ObstaclePtr> &obstacles)
{
resetAndInitializeMemberVariables(navigable_area, obstacles);
Point closest_end = findClosestFreePoint(end);
Coordinate start_coord = convertPointToCoord(start);
Coordinate end_coord = convertPointToCoord(closest_end);
bool no_path_exists = adjustEndPointsAndCheckForNoPath(start_coord, end_coord);
if (no_path_exists)
{
return std::nullopt;
}
// if the start and end points are close enough, then return a straightline path
if ((start - end).length() < CLOSE_TO_END_THRESHOLD ||
((start - end).length() < SIZE_OF_GRID_CELL_IN_METERS))
{
return Path(std::vector<Point>({start, end}));
}
if ((start - closest_end).length() <
(CLOSE_TO_END_THRESHOLD * BLOCKED_END_OSCILLATION_MITIGATION))
{
return Path(std::vector<Point>({start, closest_end}));
}
// Initialising the parameters of the starting cell
cell_heuristics[start_coord.row()][start_coord.col()].update(start_coord, 0.0, 0.0);
open_list.insert(std::make_pair(0.0, start_coord));
bool found_end = findPathToEnd(end_coord);
if (found_end == false)
{
return std::nullopt;
}
auto path_points = tracePath(end_coord);
// The last point of path_points is the closest point on the grid to the end point, so
// we need to replace that point with actual end point
path_points.pop_back();
path_points.push_back(closest_end);
// The first point of path_points is the closest unblocked point on the grid to the
// start point, so we need to replace that point with actual start point
path_points.erase(path_points.begin());
path_points.insert(path_points.begin(), start);
return Path(path_points);
}
bool ThetaStarPathPlanner::adjustEndPointsAndCheckForNoPath(Coordinate &start_coord,
Coordinate &end_coord)
{
bool ret_no_path = false;
// If the source is out of range
if (isCoordNavigable(start_coord) == false)
{
LOG(WARNING) << "Source is not within navigable area; no path found" << std::endl;
ret_no_path = true;
}
// If the end is out of range
if (isCoordNavigable(end_coord) == false)
{
LOG(WARNING) << "End is not within navigable area; no path found" << std::endl;
ret_no_path = true;
}
// The source is blocked
if (isUnblocked(start_coord) == false)
{
auto closest_start_coord = findClosestUnblockedCell(start_coord);
if (closest_start_coord)
{
start_coord = *closest_start_coord;
}
else
{
ret_no_path = true;
}
}
// The end is blocked
if (isUnblocked(end_coord) == false)
{
auto closest_end_coord = findClosestUnblockedCell(end_coord);
if (closest_end_coord)
{
end_coord = *closest_end_coord;
}
else
{
ret_no_path = true;
}
}
return ret_no_path;
}
bool ThetaStarPathPlanner::findPathToEnd(const Coordinate &end_coord)
{
while (!open_list.empty())
{
Coordinate current_coord(open_list.begin()->second);
// Remove this vertex from the open list
open_list.erase(open_list.begin());
// Add this vertex to the closed list
closed_list.insert(current_coord);
if (visitNeighbours(current_coord, end_coord))
{
return true;
}
}
// When the end CellHeuristic is not found and the open list is empty, then we
// conclude that we failed to reach the end CellHeuristic. This may happen when the
// there is no way to end CellHeuristic (due to blockages)
return false;
}
bool ThetaStarPathPlanner::visitNeighbours(const Coordinate ¤t_coord,
const Coordinate &end_coord)
{
/*
Generating all the 8 successor of this CellHeuristic
Popped Cell --> (i, j)
<0,+y> --> (i-1, j)
<0,-y> --> (i+1, j)
<+x,0> --> (i, j+1)
<-x,0> --> (i, j-1)
<+x,+y> --> (i-1, j+1)
<-x,+y> --> (i-1, j-1)
<+x,-y> --> (i+1, j+1)
<-x,-y> --> (i+1, j-1)
*/
Coordinate next_coord;
unsigned int i = current_coord.row();
unsigned int j = current_coord.col();
for (int x_offset : {-1, 0, 1})
{
for (int y_offset : {-1, 0, 1})
{
next_coord = Coordinate(i + x_offset, j + y_offset);
// check for clipping obstacles
if (lineOfSight(current_coord, next_coord))
{
if (updateVertex(current_coord, next_coord, end_coord))
{
return true;
}
}
}
}
return false;
}
std::optional<ThetaStarPathPlanner::Coordinate>
ThetaStarPathPlanner::findClosestUnblockedCell(const Coordinate ¤t_cell)
{
// spiral out from current_cell looking for unblocked cells
unsigned int i = current_cell.row();
unsigned int j = current_cell.col();
Coordinate test_coord;
unsigned next_index, curr_index = 3;
int next_increment[4] = {1, 0, -1, 0};
for (unsigned int depth = 1; depth < num_grid_rows; depth++)
{
next_index = (curr_index + 1) % 4;
i += next_increment[next_index] * depth;
j += next_increment[curr_index] * depth;
test_coord = Coordinate(i, j);
if (isCoordNavigable(test_coord) && isUnblocked(test_coord))
{
return test_coord;
}
curr_index = next_index;
next_index = (curr_index + 1) % 4;
i += next_increment[next_index] * depth;
j += next_increment[curr_index] * depth;
test_coord = Coordinate(i, j);
if (isCoordNavigable(test_coord) && isUnblocked(test_coord))
{
return test_coord;
}
curr_index = next_index;
}
return std::nullopt;
}
Point ThetaStarPathPlanner::findClosestFreePoint(const Point &p)
{
// expanding a circle to search for free points
if (!isPointNavigableAndFreeOfObstacles(p))
{
int xc = static_cast<int>(p.x() * BLOCKED_END_SEARCH_RESOLUTION);
int yc = static_cast<int>(p.y() * BLOCKED_END_SEARCH_RESOLUTION);
for (int r = 1; r < max_navigable_x_coord * 2.0 * BLOCKED_END_SEARCH_RESOLUTION;
r++)
{
int x = 0, y = r;
int d = 3 - 2 * r;
for (int outer : {-1, 1})
{
for (int inner : {-1, 1})
{
Point p1 = Point(static_cast<double>(xc + outer * x) /
BLOCKED_END_SEARCH_RESOLUTION,
static_cast<double>(yc + inner * y) /
BLOCKED_END_SEARCH_RESOLUTION);
Point p2 = Point(static_cast<double>(xc + outer * y) /
BLOCKED_END_SEARCH_RESOLUTION,
static_cast<double>(yc + inner * x) /
BLOCKED_END_SEARCH_RESOLUTION);
if (isPointNavigableAndFreeOfObstacles(p1))
{
return p1;
}
if (isPointNavigableAndFreeOfObstacles(p2))
{
return p2;
}
}
}
while (y >= x)
{
x++;
// check for decision parameter
// and correspondingly
// update d, x, y
if (d > 0)
{
y--;
d = d + 4 * (x - y) + 10;
}
else
{
d = d + 4 * x + 6;
}
for (int outer : {-1, 1})
{
for (int inner : {-1, 1})
{
Point p1 =
Point((xc + outer * x) / BLOCKED_END_SEARCH_RESOLUTION,
(yc + inner * y) / BLOCKED_END_SEARCH_RESOLUTION);
Point p2 =
Point((xc + outer * y) / BLOCKED_END_SEARCH_RESOLUTION,
(yc + inner * x) / BLOCKED_END_SEARCH_RESOLUTION);
if (isPointNavigableAndFreeOfObstacles(p1))
{
return p1;
}
if (isPointNavigableAndFreeOfObstacles(p2))
{
return p2;
}
}
}
}
}
}
return p;
}
bool ThetaStarPathPlanner::isPointNavigableAndFreeOfObstacles(const Point &p)
{
if (!isPointNavigable(p))
{
return false;
}
for (auto &obstacle : obstacles)
{
if (obstacle->contains(p))
{
return false;
}
}
return true;
}
bool ThetaStarPathPlanner::isPointNavigable(const Point &p) const
{
return ((p.x() > -max_navigable_x_coord) && (p.x() < max_navigable_x_coord) &&
(p.y() > -max_navigable_y_coord) && (p.y() < max_navigable_y_coord));
}
Point ThetaStarPathPlanner::convertCoordToPoint(const Coordinate &coord) const
{
// account for robot radius
return Point((coord.row() * SIZE_OF_GRID_CELL_IN_METERS) - max_navigable_x_coord,
(coord.col() * SIZE_OF_GRID_CELL_IN_METERS) - max_navigable_y_coord);
}
ThetaStarPathPlanner::Coordinate ThetaStarPathPlanner::convertPointToCoord(
const Point &p) const
{
// account for robot radius
return Coordinate(
static_cast<int>((p.x() + max_navigable_x_coord) / SIZE_OF_GRID_CELL_IN_METERS),
static_cast<int>((p.y() + max_navigable_y_coord) / SIZE_OF_GRID_CELL_IN_METERS));
}
void ThetaStarPathPlanner::resetAndInitializeMemberVariables(
const Rectangle &navigable_area, const std::vector<ObstaclePtr> &obstacles)
{
// Initialize member variables
this->obstacles = obstacles;
max_navigable_x_coord =
std::max(navigable_area.xLength() / 2.0 - ROBOT_MAX_RADIUS_METERS, 0.0);
max_navigable_y_coord =
std::max(navigable_area.yLength() / 2.0 - ROBOT_MAX_RADIUS_METERS, 0.0);
num_grid_rows =
static_cast<int>((max_navigable_x_coord * 2.0 + ROBOT_MAX_RADIUS_METERS) /
SIZE_OF_GRID_CELL_IN_METERS);
num_grid_cols =
static_cast<int>((max_navigable_y_coord * 2.0 + ROBOT_MAX_RADIUS_METERS) /
SIZE_OF_GRID_CELL_IN_METERS);
// Reset data structures to path plan again
open_list.clear();
closed_list.clear();
unblocked_grid.clear();
line_of_sight_cache.clear();
cell_heuristics = std::vector<std::vector<CellHeuristic>>(
num_grid_rows,
std::vector<CellHeuristic>(num_grid_cols, ThetaStarPathPlanner::CellHeuristic()));
}
unsigned long ThetaStarPathPlanner::computeMapKey(const Coordinate &coord) const
{
return coord.row() + coord.col() * (num_grid_rows + 1);
}
unsigned long ThetaStarPathPlanner::computeMapKey(
const ThetaStarPathPlanner::Coordinate &coord1,
const ThetaStarPathPlanner::Coordinate &coord2) const
{
unsigned long key1 = computeMapKey(coord1);
unsigned long key2 = computeMapKey(coord2);
if (coord1.row() < coord2.row() ||
(coord1.row() == coord2.row() && coord1.col() < coord2.col()))
{
return key1 + key2 * (num_grid_cols + num_grid_rows + 1);
}
else
{
return key2 + key1 * (num_grid_cols + num_grid_rows + 1);
}
}
| 32.916201 | 90 | 0.577733 | EvanMorcom |
5d1418cc9a428bf63eb145d1ebb41f4dcee64a48 | 1,878 | cpp | C++ | Static_data_member/Static_data_member/main.cpp | b01703020/Financial_Computing | d98d4f6e784997129ece15cdaf33c506e0f35c9e | [
"MIT"
] | null | null | null | Static_data_member/Static_data_member/main.cpp | b01703020/Financial_Computing | d98d4f6e784997129ece15cdaf33c506e0f35c9e | [
"MIT"
] | null | null | null | Static_data_member/Static_data_member/main.cpp | b01703020/Financial_Computing | d98d4f6e784997129ece15cdaf33c506e0f35c9e | [
"MIT"
] | null | null | null | //
// main.cpp
// Static_data_member
//
// Created by wu yen sun on 2022/2/22.
//
#include <iostream>
using namespace std;
class Rectangle
{
private:
int length, width; // non static data members
static int count; // static data member
public:
// default constructor
Rectangle() :length(0), width(0)
{
count++;
cout << "Length = " << length << " Width = " << width << " Count = " << count << endl;
}
// constructor with parameters
Rectangle(int length_, int width_) :length(length_), width(width_)
{
count++;
cout << "Length = " << length << " Width = " << width << " Count = " << count << endl;
}
//copy constructor
Rectangle(const Rectangle& R) :length(R.length), width(R.width)
{
count++;
cout << "Length = " << length << " Width = " << width << " Count = " << count << endl;
}
// destructor
~Rectangle()
{
count--;
cout << "Length = " << length << " Width = " << width << " Count = " << count << endl;
}
static int GetCount() { return count; } // count is private
};
void RectangleQuestion(void)
{
Rectangle R1, R2(10, 2), R3 = R2;
// R1 is created default constructor,
// R2 by constructor with parameters,
// R3 by copy constructor
cout << "The number of rectangles = " << Rectangle::GetCount() << endl;
// 3
// destructor will be invoked for each object;
//last created object will be the 1st to destroy
}
int Rectangle::count = 0;
// static data member must be initialized outside constructor
int main(void)
{
RectangleQuestion();
// after the function is completed, all 3 objects are destroyed
return 0;
}
| 24.710526 | 98 | 0.528222 | b01703020 |
5d174d802d19486deba694a22ce7ff67af08559e | 724 | cpp | C++ | src/kernel/kernel_types.cpp | cbeck88/wes-kernel | 38296e9fcbda632b3cb332a807a590683dd26a1f | [
"MIT"
] | null | null | null | src/kernel/kernel_types.cpp | cbeck88/wes-kernel | 38296e9fcbda632b3cb332a807a590683dd26a1f | [
"MIT"
] | null | null | null | src/kernel/kernel_types.cpp | cbeck88/wes-kernel | 38296e9fcbda632b3cb332a807a590683dd26a1f | [
"MIT"
] | null | null | null | #include "kernel_types.hpp"
namespace wesnoth {
static map_location _helper(int x, int y) {
map_location ret;
ret.x = x;
ret.y = y;
return ret;
}
// TODO: Fix this to correct for C++ vs WML 0 - 1 difference
std::set<map_location> hex::neighbors(map_location a) {
std::set<map_location> res;
bool b = (a.x & 1) == 0;
res.emplace(_helper(a.x, a.y-1));
res.emplace(_helper(a.x+1, a.y - (b ? 1 : 0)));
res.emplace(_helper(a.x+1, a.y + (b ? 0 : 1)));
res.emplace(_helper(a.x, a.y+1));
res.emplace(_helper(a.x-1, a.y + (b ? 0 : 1)));
res.emplace(_helper(a.x-1, a.y + (b ? 1 : 0)));
return res;
}
bool hex::adjacent(map_location a, map_location b) {
return geometry::adjacent(a, b);
}
} // end namespace wesnoth
| 24.133333 | 60 | 0.629834 | cbeck88 |
5d17ac499a611eea64ac7663a4dfc97c7ec05a55 | 5,542 | cpp | C++ | src/text/regex.cpp | reubenscratton/oaknut | 03b37965ad84745bd5c077a27d8b53d58a173662 | [
"MIT"
] | 5 | 2019-10-04T05:10:06.000Z | 2021-02-03T23:29:10.000Z | src/text/regex.cpp | reubenscratton/oaknut | 03b37965ad84745bd5c077a27d8b53d58a173662 | [
"MIT"
] | null | null | null | src/text/regex.cpp | reubenscratton/oaknut | 03b37965ad84745bd5c077a27d8b53d58a173662 | [
"MIT"
] | 2 | 2019-09-27T00:34:36.000Z | 2020-10-27T09:44:26.000Z | //
// Copyright © 2018 Sandcastle Software Ltd. All rights reserved.
//
// This file is part of 'Oaknut' which is released under the MIT License.
// See the LICENSE file in the root of this installation for details.
//
#include <oaknut.h>
RegEx::RegEx(const string& pattern) {
uint32_t p = 0;
int currentGroup = -1;
int numCapturedGroups = 0;
while (p<pattern.lengthInBytes()) {
char32_t c = pattern.readChar(p);
// Start of group
if (c=='(') {
//_groups.emplace_back(Group {(int)_pattern.size(), -1});
currentGroup = numCapturedGroups++;
continue;
}
// End of group
if (c==')') {
//_groups.rbegin()->end = (int)_pattern.size();
currentGroup = -1;
continue;
}
// New token
Token t;
t.quantMin = t.quantMax = 0;
t.inverted = false;
t.group = currentGroup;
// Parse character class
if (c=='.') {
t.charClass = Any;
} else if (c=='\\') {
char32_t esc = pattern.readChar(p);
if (esc == 'w') t.charClass = Word;
else if (esc == 'W') {t.charClass = Word; t.inverted = true;}
else if (esc == 'd') t.charClass = Digit;
else if (esc == 'D') {t.charClass = Digit; t.inverted = true;}
else if (esc == 's') t.charClass = Whitespace;
else if (esc == 'S') {t.charClass = Whitespace; t.inverted = true;}
else if (esc == '+' || esc=='*' || esc=='?' || esc=='^' || esc=='$' || esc=='\\' || esc=='.' || esc=='[' || esc==']' || esc=='{' || esc=='}' || esc=='(' || esc==')' || esc=='|' || esc=='/' || esc==')') {t.charClass=Range; t.chars.push_back(esc);}
else log_warn("ignoring unknown escape");
} else if (c=='[') {
if (pattern.peekChar(p)=='^') {
t.inverted = true;
pattern.readChar(p);
}
while (p<pattern.lengthInBytes()) {
c = pattern.readChar(p);
if (c==']') {
break;
}
t.chars.push_back(c);
if (pattern.peekChar(p) == '-') { // range
assert(0); // todo
}
}
} else {
t.charClass = Range;
t.chars.push_back(c);
}
// Quantifiers
c = pattern.peekChar(p);
if (c=='?') {
t.quantMin = 0;
t.quantMax = 1;
pattern.readChar(p);
} else if (c=='+') {
t.quantMin = 1;
t.quantMax = INT32_MAX;
pattern.readChar(p);
} else if (c=='*') {
t.quantMin = 0;
t.quantMax = INT32_MAX;
pattern.readChar(p);
} else if (c=='{') {
pattern.readChar(p);
t.quantMin = pattern.readNumber(p).asInt();
c = pattern.peekChar(p);
if (c == ',') {
pattern.readChar(p);
if (pattern.peekChar(p)=='}') {
t.quantMax = INT32_MAX;
} else {
t.quantMax = pattern.readNumber(p).asInt();
assert(t.quantMax>=t.quantMin);
}
} else {
t.quantMax = t.quantMin;
}
c = pattern.readChar(p);
assert(c == '}');
} else {
t.quantMin = 1;
t.quantMax = 1;
}
_pattern.push_back(t);
}
}
RegEx::MatchResult RegEx::match(const string& str, vector<string>& matchedGroups) {
matchedGroups.clear();
if (str.length()==0) {
return MatchPartial;
}
uint32_t it = 0;
int tokenIndex = -1;
for (auto token : _pattern) {
tokenIndex++;
if (it>=str.lengthInBytes()) {
return MatchPartial;
}
int q = 0;
while (q<token.quantMax) {
bool match = false;
char32_t ch = str.peekChar(it);
switch (token.charClass) {
case Range:
for (auto c : token.chars) {
if (c == ch) {
match = true;
break;
}
}
break;
case Any:
match = true;
break;
case Word:
match = (ch>='A'&&ch<='Z') || (ch>='a'&&ch<='z') || ch=='_';
break;
case Digit:
match = (ch>='0'&&ch<='9');
break;
case Whitespace:
match = (ch==' '||ch=='\r'||ch=='\n'||ch=='\t');
break;
}
if (token.inverted) {
match = !match;
}
if (!match) {
break;
}
// Char matched the pattern
q++;
str.readChar(it);
// Add matched char to current group
if (token.group >= 0) {
while (matchedGroups.size() <= token.group) {
matchedGroups.push_back(string());
}
matchedGroups.at(token.group).append(ch);
}
}
if (q < token.quantMin) {
return q?MatchPartial:MatchNone;
}
}
return (it>=str.lengthInBytes()) ? MatchFull : MatchNone;
}
| 32.22093 | 258 | 0.411765 | reubenscratton |
5d193fbfbedc68cc2fbfd52ec2e7d353d691acf4 | 5,137 | cpp | C++ | src/qt/qtwebkit/Source/WebCore/Modules/encryptedmedia/MediaKeys.cpp | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 1 | 2015-05-27T13:52:20.000Z | 2015-05-27T13:52:20.000Z | src/qt/qtwebkit/Source/WebCore/Modules/encryptedmedia/MediaKeys.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtwebkit/Source/WebCore/Modules/encryptedmedia/MediaKeys.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2022-02-18T10:41:38.000Z | 2022-02-18T10:41:38.000Z | /*
* Copyright (C) 2013 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "MediaKeys.h"
#if ENABLE(ENCRYPTED_MEDIA_V2)
#include "CDM.h"
#include "EventNames.h"
#include "HTMLMediaElement.h"
#include "MediaKeyMessageEvent.h"
#include "MediaKeySession.h"
#include "UUID.h"
#include <wtf/HashSet.h>
namespace WebCore {
PassRefPtr<MediaKeys> MediaKeys::create(const String& keySystem, ExceptionCode& ec)
{
// From <http://dvcs.w3.org/hg/html-media/raw-file/tip/encrypted-media/encrypted-media.html#dom-media-keys-constructor>:
// The MediaKeys(keySystem) constructor must run the following steps:
// 1. If keySystem is null or an empty string, throw an INVALID_ACCESS_ERR exception and abort these steps.
if (keySystem.isNull() || keySystem.isEmpty()) {
ec = INVALID_ACCESS_ERR;
return 0;
}
// 2. If keySystem is not one of the user agent's supported Key Systems, throw a NOT_SUPPORTED_ERR and abort these steps.
if (!CDM::supportsKeySystem(keySystem)) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
// 3. Let cdm be the content decryption module corresponding to keySystem.
// 4. Load cdm if necessary.
OwnPtr<CDM> cdm = CDM::create(keySystem);
// 5. Create a new MediaKeys object.
// 5.1 Let the keySystem attribute be keySystem.
// 6. Return the new object to the caller.
return adoptRef(new MediaKeys(keySystem, cdm.release()));
}
MediaKeys::MediaKeys(const String& keySystem, PassOwnPtr<CDM> cdm)
: m_mediaElement(0)
, m_keySystem(keySystem)
, m_cdm(cdm)
{
m_cdm->setClient(this);
}
MediaKeys::~MediaKeys()
{
// From <http://dvcs.w3.org/hg/html-media/raw-file/tip/encrypted-media/encrypted-media.html#dom-media-keys-constructor>:
// When destroying a MediaKeys object, follow the steps in close().
for (size_t i = 0; i < m_sessions.size(); ++i) {
m_sessions[i]->close();
m_sessions[i]->setKeys(0);
}
}
PassRefPtr<MediaKeySession> MediaKeys::createSession(ScriptExecutionContext* context, const String& type, Uint8Array* initData, ExceptionCode& ec)
{
// From <http://dvcs.w3.org/hg/html-media/raw-file/tip/encrypted-media/encrypted-media.html#dom-createsession>:
// The createSession(type, initData) method must run the following steps:
// Note: The contents of initData are container-specific Initialization Data.
// 1. If type is null or an empty string and initData is not null or an empty string, throw an
// INVALID_ACCESS_ERR exception and abort these steps.
if ((type.isNull() || type.isEmpty()) && (!initData || initData->length())) {
ec = INVALID_ACCESS_ERR;
return 0;
}
// 2. If type contains a MIME type that is not supported or is not supported by the keySystem, throw
// a NOT_SUPPORTED_ERR exception and abort these steps.
if (!type.isNull() && !type.isEmpty() && !m_cdm->supportsMIMEType(type)) {
ec = NOT_SUPPORTED_ERR;
return 0;
}
// 3. Create a new MediaKeySession object.
// 3.1 Let the keySystem attribute be keySystem.
// 3.2 Let the sessionId attribute be a unique Session ID string. It may be generated by cdm.
RefPtr<MediaKeySession> session = MediaKeySession::create(context, this, keySystem());
// 4. Add the new object to an internal list of session objects.
m_sessions.append(session);
// 5. Schedule a task to generate a key request, providing type, initData, and the new object.
session->generateKeyRequest(type, initData);
// 6. Return the new object to the caller.
return session;
}
void MediaKeys::setMediaElement(HTMLMediaElement* element)
{
m_mediaElement = element;
}
MediaPlayer* MediaKeys::cdmMediaPlayer(const CDM*) const
{
if (m_mediaElement)
return m_mediaElement->player();
return 0;
}
}
#endif
| 37.772059 | 146 | 0.712673 | viewdy |
5d1b034911473ce16e6ab49c25f9f68719cc22b6 | 1,701 | cpp | C++ | clang/test/OpenMP/taskwait_depend_codegen.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | 605 | 2019-10-18T01:15:54.000Z | 2022-03-31T14:31:04.000Z | clang/test/OpenMP/taskwait_depend_codegen.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | 3,180 | 2019-10-18T01:21:21.000Z | 2022-03-31T23:25:41.000Z | clang/test/OpenMP/taskwait_depend_codegen.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | 275 | 2019-10-18T05:27:22.000Z | 2022-03-30T09:04:21.000Z | // RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp -x c++ -emit-llvm %s -o - | FileCheck %s
// RUN: %clang_cc1 -fopenmp -x c++ -triple x86_64-apple-darwin10 -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -x c++ -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s
// RUN: %clang_cc1 -verify -triple x86_64-apple-darwin10 -fopenmp-simd -x c++ -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple x86_64-apple-darwin10 -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple x86_64-apple-darwin10 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
// expected-no-diagnostics
#ifndef HEADER
#define HEADER
void foo() {}
template <class T>
T tmain(T &argc) {
static T a;
#pragma omp taskwait depend(in:argc)
return a + argc;
}
int main(int argc, char **argv) {
int n = 0;
#pragma omp task shared(n,argc) depend(out:n)
n = argc;
return tmain(n);
}
// CHECK-LABEL: @main
// CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num(%{{.+}}* @{{.+}})
// CHECK: [[ALLOC:%.+]] = call i8* @__kmpc_omp_task_alloc(%{{.+}}* @{{.+}}, i32 [[GTID]], i32 1, i64 40, i64 16, i32 (i32, i8*)* bitcast (i32 (i32, %{{.+}}*)* @{{.+}} to i32 (i32, i8*)*))
// CHECK: %{{.+}} = call i32 @__kmpc_omp_task_with_deps(%{{.+}}* @{{.+}}, i32 [[GTID]], i8* [[ALLOC]], i32 1, i8* %{{[0-9]*}}, i32 0, i8* null)
// CHECK-LABEL: tmain
// CHECK: [[GTID:%.+]] = call i32 @__kmpc_global_thread_num(%{{.+}}* @{{.+}})
// CHECK: call void @__kmpc_omp_wait_deps(%{{.+}}* @{{.+}}, i32 [[GTID]], i32 1, i8* %{{.}}, i32 0, i8* null)
#endif
| 43.615385 | 187 | 0.60435 | LaudateCorpus1 |
5d1ca9dbd6f974892faa0bc4127f56a90289b8dd | 15,271 | cpp | C++ | src/tests/unittests/CommandAllocatorTests.cpp | faro-oss/Dawn | 0ac7aa3386b597742a45368a28a2e045c122cb8c | [
"Apache-2.0"
] | 1 | 2022-02-05T01:08:06.000Z | 2022-02-05T01:08:06.000Z | src/tests/unittests/CommandAllocatorTests.cpp | sunnyps/dawn | afe91384086551ea3156fc67c525fdf864aa8437 | [
"Apache-2.0"
] | 1 | 2021-12-18T01:33:44.000Z | 2021-12-18T01:33:44.000Z | src/tests/unittests/CommandAllocatorTests.cpp | sunnyps/dawn | afe91384086551ea3156fc67c525fdf864aa8437 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 The Dawn Authors
//
// 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 <gtest/gtest.h>
#include "dawn_native/CommandAllocator.h"
#include <limits>
using namespace dawn_native;
// Definition of the command types used in the tests
enum class CommandType {
Draw,
Pipeline,
PushConstants,
Big,
Small,
};
struct CommandDraw {
uint32_t first;
uint32_t count;
};
struct CommandPipeline {
uint64_t pipeline;
uint32_t attachmentPoint;
};
struct CommandPushConstants {
uint8_t size;
uint8_t offset;
};
constexpr int kBigBufferSize = 65536;
struct CommandBig {
uint32_t buffer[kBigBufferSize];
};
struct CommandSmall {
uint16_t data;
};
// Test allocating nothing works
TEST(CommandAllocator, DoNothingAllocator) {
CommandAllocator allocator;
}
// Test iterating over nothing works
TEST(CommandAllocator, DoNothingAllocatorWithIterator) {
CommandAllocator allocator;
CommandIterator iterator(std::move(allocator));
iterator.MakeEmptyAsDataWasDestroyed();
}
// Test basic usage of allocator + iterator
TEST(CommandAllocator, Basic) {
CommandAllocator allocator;
uint64_t myPipeline = 0xDEADBEEFBEEFDEAD;
uint32_t myAttachmentPoint = 2;
uint32_t myFirst = 42;
uint32_t myCount = 16;
{
CommandPipeline* pipeline = allocator.Allocate<CommandPipeline>(CommandType::Pipeline);
pipeline->pipeline = myPipeline;
pipeline->attachmentPoint = myAttachmentPoint;
CommandDraw* draw = allocator.Allocate<CommandDraw>(CommandType::Draw);
draw->first = myFirst;
draw->count = myCount;
}
{
CommandIterator iterator(std::move(allocator));
CommandType type;
bool hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Pipeline);
CommandPipeline* pipeline = iterator.NextCommand<CommandPipeline>();
ASSERT_EQ(pipeline->pipeline, myPipeline);
ASSERT_EQ(pipeline->attachmentPoint, myAttachmentPoint);
hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Draw);
CommandDraw* draw = iterator.NextCommand<CommandDraw>();
ASSERT_EQ(draw->first, myFirst);
ASSERT_EQ(draw->count, myCount);
hasNext = iterator.NextCommandId(&type);
ASSERT_FALSE(hasNext);
iterator.MakeEmptyAsDataWasDestroyed();
}
}
// Test basic usage of allocator + iterator with data
TEST(CommandAllocator, BasicWithData) {
CommandAllocator allocator;
uint8_t mySize = 8;
uint8_t myOffset = 3;
uint32_t myValues[5] = {6, 42, 0xFFFFFFFF, 0, 54};
{
CommandPushConstants* pushConstants =
allocator.Allocate<CommandPushConstants>(CommandType::PushConstants);
pushConstants->size = mySize;
pushConstants->offset = myOffset;
uint32_t* values = allocator.AllocateData<uint32_t>(5);
for (size_t i = 0; i < 5; i++) {
values[i] = myValues[i];
}
}
{
CommandIterator iterator(std::move(allocator));
CommandType type;
bool hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::PushConstants);
CommandPushConstants* pushConstants = iterator.NextCommand<CommandPushConstants>();
ASSERT_EQ(pushConstants->size, mySize);
ASSERT_EQ(pushConstants->offset, myOffset);
uint32_t* values = iterator.NextData<uint32_t>(5);
for (size_t i = 0; i < 5; i++) {
ASSERT_EQ(values[i], myValues[i]);
}
hasNext = iterator.NextCommandId(&type);
ASSERT_FALSE(hasNext);
iterator.MakeEmptyAsDataWasDestroyed();
}
}
// Test basic iterating several times
TEST(CommandAllocator, MultipleIterations) {
CommandAllocator allocator;
uint32_t myFirst = 42;
uint32_t myCount = 16;
{
CommandDraw* draw = allocator.Allocate<CommandDraw>(CommandType::Draw);
draw->first = myFirst;
draw->count = myCount;
}
{
CommandIterator iterator(std::move(allocator));
CommandType type;
// First iteration
bool hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Draw);
CommandDraw* draw = iterator.NextCommand<CommandDraw>();
ASSERT_EQ(draw->first, myFirst);
ASSERT_EQ(draw->count, myCount);
hasNext = iterator.NextCommandId(&type);
ASSERT_FALSE(hasNext);
// Second iteration
hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Draw);
draw = iterator.NextCommand<CommandDraw>();
ASSERT_EQ(draw->first, myFirst);
ASSERT_EQ(draw->count, myCount);
hasNext = iterator.NextCommandId(&type);
ASSERT_FALSE(hasNext);
iterator.MakeEmptyAsDataWasDestroyed();
}
}
// Test large commands work
TEST(CommandAllocator, LargeCommands) {
CommandAllocator allocator;
const int kCommandCount = 5;
uint32_t count = 0;
for (int i = 0; i < kCommandCount; i++) {
CommandBig* big = allocator.Allocate<CommandBig>(CommandType::Big);
for (int j = 0; j < kBigBufferSize; j++) {
big->buffer[j] = count++;
}
}
CommandIterator iterator(std::move(allocator));
CommandType type;
count = 0;
int numCommands = 0;
while (iterator.NextCommandId(&type)) {
ASSERT_EQ(type, CommandType::Big);
CommandBig* big = iterator.NextCommand<CommandBig>();
for (int i = 0; i < kBigBufferSize; i++) {
ASSERT_EQ(big->buffer[i], count);
count++;
}
numCommands++;
}
ASSERT_EQ(numCommands, kCommandCount);
iterator.MakeEmptyAsDataWasDestroyed();
}
// Test many small commands work
TEST(CommandAllocator, ManySmallCommands) {
CommandAllocator allocator;
// Stay under max representable uint16_t
const int kCommandCount = 50000;
uint16_t count = 0;
for (int i = 0; i < kCommandCount; i++) {
CommandSmall* small = allocator.Allocate<CommandSmall>(CommandType::Small);
small->data = count++;
}
CommandIterator iterator(std::move(allocator));
CommandType type;
count = 0;
int numCommands = 0;
while (iterator.NextCommandId(&type)) {
ASSERT_EQ(type, CommandType::Small);
CommandSmall* small = iterator.NextCommand<CommandSmall>();
ASSERT_EQ(small->data, count);
count++;
numCommands++;
}
ASSERT_EQ(numCommands, kCommandCount);
iterator.MakeEmptyAsDataWasDestroyed();
}
/* ________
* / \
* | POUIC! |
* \_ ______/
* v
* ()_()
* (O.o)
* (> <)o
*/
// Test usage of iterator.Reset
TEST(CommandAllocator, IteratorReset) {
CommandAllocator allocator;
uint64_t myPipeline = 0xDEADBEEFBEEFDEAD;
uint32_t myAttachmentPoint = 2;
uint32_t myFirst = 42;
uint32_t myCount = 16;
{
CommandPipeline* pipeline = allocator.Allocate<CommandPipeline>(CommandType::Pipeline);
pipeline->pipeline = myPipeline;
pipeline->attachmentPoint = myAttachmentPoint;
CommandDraw* draw = allocator.Allocate<CommandDraw>(CommandType::Draw);
draw->first = myFirst;
draw->count = myCount;
}
{
CommandIterator iterator(std::move(allocator));
CommandType type;
bool hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Pipeline);
CommandPipeline* pipeline = iterator.NextCommand<CommandPipeline>();
ASSERT_EQ(pipeline->pipeline, myPipeline);
ASSERT_EQ(pipeline->attachmentPoint, myAttachmentPoint);
iterator.Reset();
hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Pipeline);
pipeline = iterator.NextCommand<CommandPipeline>();
ASSERT_EQ(pipeline->pipeline, myPipeline);
ASSERT_EQ(pipeline->attachmentPoint, myAttachmentPoint);
hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Draw);
CommandDraw* draw = iterator.NextCommand<CommandDraw>();
ASSERT_EQ(draw->first, myFirst);
ASSERT_EQ(draw->count, myCount);
hasNext = iterator.NextCommandId(&type);
ASSERT_FALSE(hasNext);
iterator.MakeEmptyAsDataWasDestroyed();
}
}
// Test iterating empty iterators
TEST(CommandAllocator, EmptyIterator) {
{
CommandAllocator allocator;
CommandIterator iterator(std::move(allocator));
CommandType type;
bool hasNext = iterator.NextCommandId(&type);
ASSERT_FALSE(hasNext);
iterator.MakeEmptyAsDataWasDestroyed();
}
{
CommandAllocator allocator;
CommandIterator iterator1(std::move(allocator));
CommandIterator iterator2(std::move(iterator1));
CommandType type;
bool hasNext = iterator2.NextCommandId(&type);
ASSERT_FALSE(hasNext);
iterator1.MakeEmptyAsDataWasDestroyed();
iterator2.MakeEmptyAsDataWasDestroyed();
}
{
CommandIterator iterator1;
CommandIterator iterator2(std::move(iterator1));
CommandType type;
bool hasNext = iterator2.NextCommandId(&type);
ASSERT_FALSE(hasNext);
iterator1.MakeEmptyAsDataWasDestroyed();
iterator2.MakeEmptyAsDataWasDestroyed();
}
}
template <size_t A>
struct alignas(A) AlignedStruct {
char dummy;
};
// Test for overflows in Allocate's computations, size 1 variant
TEST(CommandAllocator, AllocationOverflow_1) {
CommandAllocator allocator;
AlignedStruct<1>* data =
allocator.AllocateData<AlignedStruct<1>>(std::numeric_limits<size_t>::max() / 1);
ASSERT_EQ(data, nullptr);
}
// Test for overflows in Allocate's computations, size 2 variant
TEST(CommandAllocator, AllocationOverflow_2) {
CommandAllocator allocator;
AlignedStruct<2>* data =
allocator.AllocateData<AlignedStruct<2>>(std::numeric_limits<size_t>::max() / 2);
ASSERT_EQ(data, nullptr);
}
// Test for overflows in Allocate's computations, size 4 variant
TEST(CommandAllocator, AllocationOverflow_4) {
CommandAllocator allocator;
AlignedStruct<4>* data =
allocator.AllocateData<AlignedStruct<4>>(std::numeric_limits<size_t>::max() / 4);
ASSERT_EQ(data, nullptr);
}
// Test for overflows in Allocate's computations, size 8 variant
TEST(CommandAllocator, AllocationOverflow_8) {
CommandAllocator allocator;
AlignedStruct<8>* data =
allocator.AllocateData<AlignedStruct<8>>(std::numeric_limits<size_t>::max() / 8);
ASSERT_EQ(data, nullptr);
}
template <int DefaultValue>
struct IntWithDefault {
IntWithDefault() : value(DefaultValue) {
}
int value;
};
// Test that the allcator correctly defaults initalizes data for Allocate
TEST(CommandAllocator, AllocateDefaultInitializes) {
CommandAllocator allocator;
IntWithDefault<42>* int42 = allocator.Allocate<IntWithDefault<42>>(CommandType::Draw);
ASSERT_EQ(int42->value, 42);
IntWithDefault<43>* int43 = allocator.Allocate<IntWithDefault<43>>(CommandType::Draw);
ASSERT_EQ(int43->value, 43);
IntWithDefault<44>* int44 = allocator.Allocate<IntWithDefault<44>>(CommandType::Draw);
ASSERT_EQ(int44->value, 44);
CommandIterator iterator(std::move(allocator));
iterator.MakeEmptyAsDataWasDestroyed();
}
// Test that the allocator correctly default-initalizes data for AllocateData
TEST(CommandAllocator, AllocateDataDefaultInitializes) {
CommandAllocator allocator;
IntWithDefault<33>* int33 = allocator.AllocateData<IntWithDefault<33>>(1);
ASSERT_EQ(int33[0].value, 33);
IntWithDefault<34>* int34 = allocator.AllocateData<IntWithDefault<34>>(2);
ASSERT_EQ(int34[0].value, 34);
ASSERT_EQ(int34[0].value, 34);
IntWithDefault<35>* int35 = allocator.AllocateData<IntWithDefault<35>>(3);
ASSERT_EQ(int35[0].value, 35);
ASSERT_EQ(int35[1].value, 35);
ASSERT_EQ(int35[2].value, 35);
CommandIterator iterator(std::move(allocator));
iterator.MakeEmptyAsDataWasDestroyed();
}
// Tests flattening of multiple CommandAllocators into a single CommandIterator using
// AcquireCommandBlocks.
TEST(CommandAllocator, AcquireCommandBlocks) {
constexpr size_t kNumAllocators = 2;
constexpr size_t kNumCommandsPerAllocator = 2;
const uint64_t pipelines[kNumAllocators][kNumCommandsPerAllocator] = {
{0xDEADBEEFBEEFDEAD, 0xC0FFEEF00DC0FFEE},
{0x1337C0DE1337C0DE, 0xCAFEFACEFACECAFE},
};
const uint32_t attachmentPoints[kNumAllocators][kNumCommandsPerAllocator] = {{1, 2}, {3, 4}};
const uint32_t firsts[kNumAllocators][kNumCommandsPerAllocator] = {{42, 43}, {5, 6}};
const uint32_t counts[kNumAllocators][kNumCommandsPerAllocator] = {{16, 32}, {4, 8}};
std::vector<CommandAllocator> allocators(kNumAllocators);
for (size_t j = 0; j < kNumAllocators; ++j) {
CommandAllocator& allocator = allocators[j];
for (size_t i = 0; i < kNumCommandsPerAllocator; ++i) {
CommandPipeline* pipeline = allocator.Allocate<CommandPipeline>(CommandType::Pipeline);
pipeline->pipeline = pipelines[j][i];
pipeline->attachmentPoint = attachmentPoints[j][i];
CommandDraw* draw = allocator.Allocate<CommandDraw>(CommandType::Draw);
draw->first = firsts[j][i];
draw->count = counts[j][i];
}
}
CommandIterator iterator;
iterator.AcquireCommandBlocks(std::move(allocators));
for (size_t j = 0; j < kNumAllocators; ++j) {
for (size_t i = 0; i < kNumCommandsPerAllocator; ++i) {
CommandType type;
bool hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Pipeline);
CommandPipeline* pipeline = iterator.NextCommand<CommandPipeline>();
ASSERT_EQ(pipeline->pipeline, pipelines[j][i]);
ASSERT_EQ(pipeline->attachmentPoint, attachmentPoints[j][i]);
hasNext = iterator.NextCommandId(&type);
ASSERT_TRUE(hasNext);
ASSERT_EQ(type, CommandType::Draw);
CommandDraw* draw = iterator.NextCommand<CommandDraw>();
ASSERT_EQ(draw->first, firsts[j][i]);
ASSERT_EQ(draw->count, counts[j][i]);
}
}
CommandType type;
ASSERT_FALSE(iterator.NextCommandId(&type));
iterator.MakeEmptyAsDataWasDestroyed();
}
| 30.299603 | 99 | 0.669177 | faro-oss |
5d1d93acaa5a650f59709505279c3fd21c6b802a | 2,259 | cpp | C++ | base/SplashScreen.cpp | fmuecke/ipponboard_test | 2ba8f324af91bfcdd26e37940157a1796f3b1f64 | [
"BSD-2-Clause"
] | 3 | 2020-12-29T19:33:56.000Z | 2021-11-09T20:29:30.000Z | base/SplashScreen.cpp | fmuecke/ipponboard_test | 2ba8f324af91bfcdd26e37940157a1796f3b1f64 | [
"BSD-2-Clause"
] | 3 | 2020-12-30T10:34:26.000Z | 2021-01-05T08:55:12.000Z | base/SplashScreen.cpp | fmuecke/ipponboard_test | 2ba8f324af91bfcdd26e37940157a1796f3b1f64 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2018 Florian Muecke. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE.txt file.
#include "DonationManager.h"
#include "splashscreen.h"
#include "ui_splashscreen.h"
#include "versioninfo.h"
#include <algorithm>
using namespace std;
SplashScreen::SplashScreen(Data const& data, QWidget* parent)
: QDialog(parent)
, ui(new Ui::SplashScreen)
{
ui->setupUi(this);
// const int days_left = data.date.daysTo(QDate::currentDate());
// ui->label_valid->setText(
// "- " + QString::number( days_left ) +
// " " + tr("days left") + " -");
ui->textEdit_eula->setHtml(data.text);
ui->label_info->setText(data.info);
//ui->labelCopyright->setText(QString("© %1 Florian Mücke").arg(VersionInfo::CopyrightYear));
ui->commandLinkButton_donate->setText(DonationManager::GetDonationLabel());
/*std::vector<QCommandLinkButton*> buttons =
{
ui->commandLinkButton_donate,
ui->commandLinkButton_startSingleVersion,
ui->commandLinkButton_startTeamVersion
};
buttons.erase(
remove_if(
begin(buttons),
end(buttons),
[](QCommandLinkButton* b) { return !b->isEnabled(); }),
end(buttons));
auto r = qrand() % buttons.size();
buttons[r]->setFocus();
buttons[r]->setDefault(true);
//ui->commandLinkButton_donate->setFocus();
*/
setWindowFlags(Qt::Window);
}
SplashScreen::~SplashScreen()
{
delete ui;
}
void SplashScreen::SetImageStyleSheet(QString const& /*text*/)
{
//"image: url(:/res/images/logo.png);"
//ui->widget_image->setStyleSheet(text);
}
void SplashScreen::changeEvent(QEvent* e)
{
QWidget::changeEvent(e);
switch (e->type())
{
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
void SplashScreen::on_commandLinkButton_startSingleVersion_pressed()
{
accept();
}
void SplashScreen::on_commandLinkButton_startTeamVersion_pressed()
{
done(QDialog::Accepted + 1);
}
void SplashScreen::on_commandLinkButton_donate_pressed()
{
DonationManager::OpenUrl();
}
//void SplashScreen::on_commandLinkButton_cancel_pressed()
//{
// reject();
//}
| 23.05102 | 95 | 0.665781 | fmuecke |
5d209da5ebc8fd0b040e73902be37e64d13111f5 | 6,756 | cc | C++ | src/latbin/lattice-align-words-lexicon.cc | brucerennie/kaldi | d366a93aad98127683b010fd01e145093c1e9e08 | [
"Apache-2.0"
] | 36 | 2019-11-12T22:41:43.000Z | 2022-02-01T15:24:02.000Z | src/latbin/lattice-align-words-lexicon.cc | brucerennie/kaldi | d366a93aad98127683b010fd01e145093c1e9e08 | [
"Apache-2.0"
] | 8 | 2017-09-06T00:12:00.000Z | 2019-03-22T08:03:19.000Z | src/latbin/lattice-align-words-lexicon.cc | brucerennie/kaldi | d366a93aad98127683b010fd01e145093c1e9e08 | [
"Apache-2.0"
] | 29 | 2020-01-03T22:28:27.000Z | 2022-03-30T23:00:27.000Z | // latbin/lattice-align-words-lexicon.cc
// Copyright 2012 Johns Hopkins University (Author: Daniel Povey)
// See ../../COPYING for clarification regarding multiple authors
//
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "lat/kaldi-lattice.h"
#include "lat/word-align-lattice-lexicon.h"
#include "lat/lattice-functions.h"
#include "lat/lattice-functions-transition-model.h"
int main(int argc, char *argv[]) {
try {
using namespace kaldi;
using fst::StdArc;
using kaldi::int32;
const char *usage =
"Convert lattices so that the arcs in the CompactLattice format correspond with\n"
"words (i.e. aligned with word boundaries). This is the newest form, that\n"
"reads in a lexicon in integer format, where each line is (integer id of)\n"
" word-in word-out phone1 phone2 ... phoneN\n"
"(note: word-in is word before alignment, word-out is after, e.g. for replacing\n"
"<eps> with SIL or vice versa)\n"
"This may be more efficient if you first apply 'lattice-push'.\n"
"Usage: lattice-align-words-lexicon [options] <lexicon-file> <model> <lattice-rspecifier> <lattice-wspecifier>\n"
" e.g.: lattice-align-words-lexicon --partial-word-label=4324 --max-expand 10.0 --test true \\\n"
" data/lang/phones/align_lexicon.int final.mdl ark:1.lats ark:aligned.lats\n"
"See also: lattice-align-words, which is only applicable if your phones have word-position\n"
"markers, i.e. each phone comes in 5 versions like AA_B, AA_I, AA_W, AA_S, AA.\n";
ParseOptions po(usage);
bool output_if_error = true;
bool output_if_empty = false;
bool test = false;
bool allow_duplicate_paths = false;
po.Register("output-error-lats", &output_if_error, "Output lattices that aligned "
"with errors (e.g. due to force-out");
po.Register("output-if-empty", &output_if_empty, "If true: if algorithm gives "
"error and produces empty output, pass the input through.");
po.Register("test", &test, "If true, testing code will be activated "
"(the purpose of this is to validate the algorithm).");
po.Register("allow-duplicate-paths", &allow_duplicate_paths, "Only "
"has an effect if --test=true. If true, does not die "
"(only prints warnings) if duplicate paths are found. "
"This should only happen with very pathological lexicons, "
"e.g. as encountered in testing code.");
WordAlignLatticeLexiconOpts opts;
opts.Register(&po);
po.Read(argc, argv);
if (po.NumArgs() != 4) {
po.PrintUsage();
exit(1);
}
std::string
align_lexicon_rxfilename = po.GetArg(1),
model_rxfilename = po.GetArg(2),
lats_rspecifier = po.GetArg(3),
lats_wspecifier = po.GetArg(4);
std::vector<std::vector<int32> > lexicon;
{
bool binary_in;
Input ki(align_lexicon_rxfilename, &binary_in);
KALDI_ASSERT(!binary_in && "Not expecting binary file for lexicon");
if (!ReadLexiconForWordAlign(ki.Stream(), &lexicon)) {
KALDI_ERR << "Error reading alignment lexicon from "
<< align_lexicon_rxfilename;
}
}
TransitionModel tmodel;
ReadKaldiObject(model_rxfilename, &tmodel);
SequentialCompactLatticeReader clat_reader(lats_rspecifier);
CompactLatticeWriter clat_writer(lats_wspecifier);
WordAlignLatticeLexiconInfo lexicon_info(lexicon);
{ std::vector<std::vector<int32> > temp; lexicon.swap(temp); }
// No longer needed.
int32 num_done = 0, num_err = 0;
for (; !clat_reader.Done(); clat_reader.Next()) {
std::string key = clat_reader.Key();
const CompactLattice &clat = clat_reader.Value();
CompactLattice aligned_clat;
bool ok = WordAlignLatticeLexicon(clat, tmodel, lexicon_info, opts,
&aligned_clat);
if (ok && test) { // We only test if it succeeded.
if (!TestWordAlignedLattice(lexicon_info, tmodel, clat, aligned_clat,
allow_duplicate_paths)) {
KALDI_WARN << "Lattice failed test (activated because --test=true). "
<< "Probable code error, please contact Kaldi maintainers.";
ok = false;
}
}
if (!ok) {
num_err++;
if (output_if_empty && aligned_clat.NumStates() == 0 &&
clat.NumStates() != 0) {
KALDI_WARN << "Algorithm produced no output (due to --max-expand?), "
<< "so passing input through as output, for key " << key;
TopSortCompactLatticeIfNeeded(&aligned_clat);
clat_writer.Write(key, clat);
continue;
}
if (!output_if_error)
KALDI_WARN << "Lattice for " << key << " did not align correctly";
else {
if (aligned_clat.Start() != fst::kNoStateId) {
KALDI_WARN << "Outputting partial lattice for " << key;
TopSortCompactLatticeIfNeeded(&aligned_clat);
clat_writer.Write(key, aligned_clat);
} else {
KALDI_WARN << "Empty aligned lattice for " << key
<< ", producing no output.";
}
}
} else {
if (aligned_clat.Start() == fst::kNoStateId) {
num_err++;
KALDI_WARN << "Lattice was empty for key " << key;
} else {
num_done++;
KALDI_VLOG(2) << "Aligned lattice for " << key;
TopSortCompactLatticeIfNeeded(&aligned_clat);
clat_writer.Write(key, aligned_clat);
}
}
}
KALDI_LOG << "Successfully aligned " << num_done << " lattices; "
<< num_err << " had errors.";
return (num_done > num_err ? 0 : 1); // We changed the error condition slightly here,
// if there are errors in the word-boundary phones we can get situations
// where most lattices give an error.
} catch(const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
| 40.45509 | 121 | 0.623594 | brucerennie |
5d20b7caf134216cd8aec42ce48677e2ffb28593 | 255 | cpp | C++ | CCured/program-dependence-graph/SVF/Test-Suite/cpp_types/broken.cpp | Lightninghkm/DataGuard | 4ac1370f7607cec5fc81c3b57f5a62fb1d40f463 | [
"Apache-2.0"
] | 9 | 2022-02-25T01:48:43.000Z | 2022-03-20T04:48:44.000Z | CCured/program-dependence-graph/SVF/Test-Suite/cpp_types/broken.cpp | Lightninghkm/DataGuard | 4ac1370f7607cec5fc81c3b57f5a62fb1d40f463 | [
"Apache-2.0"
] | 1 | 2022-03-19T08:48:07.000Z | 2022-03-21T00:51:51.000Z | CCured/program-dependence-graph/SVF/Test-Suite/cpp_types/broken.cpp | Lightninghkm/DataGuard | 4ac1370f7607cec5fc81c3b57f5a62fb1d40f463 | [
"Apache-2.0"
] | null | null | null | void checkType(void* clz, char* ty){}
class A {
public:
A(){}
};
class B : public A {
public:
B(){}
};
class C : public B {
public:
C(){}
};
int main(void) {
A *a = new A();
checkType(a,"A");
}
| 11.086957 | 37 | 0.419608 | Lightninghkm |
5d2742c249ffa5a13b239bde8ab0b7ed8cb3b1d5 | 115 | cc | C++ | abc.cc | lh2debug/quartzmemkv2 | 664a85f4ee1869f4ff7fafd88f9cbe36ace30fc5 | [
"BSD-3-Clause"
] | null | null | null | abc.cc | lh2debug/quartzmemkv2 | 664a85f4ee1869f4ff7fafd88f9cbe36ace30fc5 | [
"BSD-3-Clause"
] | null | null | null | abc.cc | lh2debug/quartzmemkv2 | 664a85f4ee1869f4ff7fafd88f9cbe36ace30fc5 | [
"BSD-3-Clause"
] | null | null | null | #include "pmalloc.h"
int main(){
int *p = (int*)pmalloc(sizeof(int));
pfree((void*)p, sizeof(int));
return 0;
} | 16.428571 | 37 | 0.617391 | lh2debug |
5d278783c192dcee83bf53f80743a7fb618784fa | 3,031 | cpp | C++ | tools/fact-generator/src/PyFactGen.cpp | TheoKant/cclyzer-souffle | dfcd01daa592a2356e36aaeaa9c933305c253cba | [
"MIT"
] | 63 | 2016-02-06T21:06:40.000Z | 2021-11-16T19:58:27.000Z | tools/fact-generator/src/PyFactGen.cpp | TheoKant/cclyzer-souffle | dfcd01daa592a2356e36aaeaa9c933305c253cba | [
"MIT"
] | 11 | 2019-05-23T20:55:12.000Z | 2021-12-08T22:18:01.000Z | tools/fact-generator/src/PyFactGen.cpp | TheoKant/cclyzer-souffle | dfcd01daa592a2356e36aaeaa9c933305c253cba | [
"MIT"
] | 14 | 2016-02-21T17:12:36.000Z | 2021-09-26T02:48:41.000Z | /**
* This module is intended to provide a python interface to
* fact-generator, by leveraging the Boost.Python library.
**/
#include <boost/filesystem.hpp>
#include <boost/python.hpp>
#include "ParseException.hpp"
namespace fs = boost::filesystem;
namespace py = boost::python;
void
pyfactgen(py::list inputFiles, std::string outputDir, std::string delim = "\t")
{
int length = py::extract<int>(inputFiles.attr("__len__")());
std::vector<fs::path> files(length);
// Create list of input files
for (int i = 0; i < len(inputFiles); ++i) {
files[i] = py::extract<char const *>(inputFiles[i]);
// Check file existence
if (!fs::exists(files[i])) {
std::stringstream error_stream;
error_stream << "No such file or directory: "
<< files[i];
std::string err_msg = error_stream.str();
PyErr_SetString(PyExc_IOError, err_msg.c_str());
boost::python::throw_error_already_set();
return;
}
}
// Create non-existing directory
if (!fs::exists(outputDir))
fs::create_directory(outputDir);
if (!fs::is_directory(outputDir)) {
PyErr_SetString(PyExc_ValueError,
"Invalid output directory path");
boost::python::throw_error_already_set();
return;
}
// Remove old contents
for (fs::directory_iterator end, it(outputDir); it != end; ++it)
remove_all(it->path());
// Ensure output directory is empty
if (!fs::is_empty(outputDir)) {
PyErr_SetString(PyExc_ValueError,
"Output directory not empty");
boost::python::throw_error_already_set();
return;
}
void factgen2(std::vector<fs::path> files, fs::path outputDir, std::string delim);
// Run fact generation
factgen2(files, outputDir, delim);
}
// Translate parse exception to python
PyObject *parseExceptionType = NULL;
void translateParseException(ParseException const &e)
{
assert(parseExceptionType != NULL);
py::object pythonExceptionInstance(e);
PyErr_SetObject(parseExceptionType, pythonExceptionInstance.ptr());
}
// Create thin wrappers for overloaded function
BOOST_PYTHON_FUNCTION_OVERLOADS(pyfactgen_overloads, pyfactgen, 2, 3)
// Path converter
struct path_to_python_str
{
static PyObject* convert(fs::path const& p)
{
return boost::python::incref(
boost::python::object(p.string()).ptr());
}
};
// Declare boost python module
BOOST_PYTHON_MODULE(factgen)
{
using namespace boost::python;
// register exception
class_<ParseException>
parseExceptionClass("ParseException", py::init<fs::path>());
parseExceptionType = parseExceptionClass.ptr();
register_exception_translator<ParseException>
(&translateParseException);
// register the path-to-python converter
to_python_converter<fs::path, path_to_python_str>();
def("run", pyfactgen, pyfactgen_overloads());
}
| 26.356522 | 86 | 0.649951 | TheoKant |
5d28d6feca17579a23d3ee09b464972197b71316 | 1,604 | cc | C++ | questions/Algorithms/0002. Add Two Numbers/Solution.cc | TechStudyGroup/leetcode | e013436e52d16090a6138689804f714329388330 | [
"MIT"
] | 9 | 2019-08-15T05:09:40.000Z | 2021-05-01T09:26:59.000Z | questions/Algorithms/0002. Add Two Numbers/Solution.cc | TechStudyGroup/leetcode | e013436e52d16090a6138689804f714329388330 | [
"MIT"
] | 135 | 2019-09-26T03:40:11.000Z | 2022-02-02T04:15:39.000Z | questions/Algorithms/0002. Add Two Numbers/Solution.cc | TechStudyGroup/leetcode | e013436e52d16090a6138689804f714329388330 | [
"MIT"
] | 1 | 2022-01-05T01:43:17.000Z | 2022-01-05T01:43:17.000Z | #include <iostream>
#include <string.h>
#include <cc/ListNode.hpp>
// ------------------------------- solution begin -------------------------------
class Solution {
public:
struct ListNode *dummy = new ListNode(0);
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
int carry = 0;
struct ListNode *p = l1, *prev = dummy;
dummy->next = p;
while (l1 != NULL || l2 != NULL) {
int sum = 0;
int last_carry = carry;
if (l1 != NULL) {
if (p == NULL) {
prev->next = l1;
p = l1;
}
sum += l1->val;
l1 = l1->next;
}
if (l2 != NULL) {
if (p == NULL) {
prev->next = l2;
p = l2;
}
sum += l2->val;
l2 = l2->next;
}
sum += last_carry;
carry = sum / 10;
p->val = sum % 10;
prev = p;
p = p->next;
}
if (carry) {
p = new ListNode(0);
p->val = carry;
p->next = NULL;
prev->next = p;
}
return dummy->next;
}
};
// ------------------------------- solution end ---------------------------------
int main(int argc, char **argv) {
vector<int> arr1 = {2, 4, 6};
vector<int> arr2 = {5, 6, 4};
struct ListNode *l1 = ListNode_init(arr1);
struct ListNode *l2 = ListNode_init(arr2);
cout << "Input: " << ListNode_show(l1) << ", " << ListNode_show(l1) << endl;
Solution solution;
struct ListNode *res = solution.addTwoNumbers(l1, l2);
cout << "Output: " << ListNode_show(res) << endl;
ListNode_destory(solution.dummy);
ListNode_destory(l2);
return EXIT_SUCCESS;
}
| 21.972603 | 81 | 0.473815 | TechStudyGroup |
5d297a7743a19df780a62ca088bd0d4e6ea50962 | 686 | hpp | C++ | C-ATTL3/parameter_initialization/gpu/OneGPUParameterInitialization.hpp | ViktorC/CppNN | daf7207fdc047412957761ef412fa805b2656d65 | [
"MIT"
] | 16 | 2018-07-03T09:39:10.000Z | 2021-11-16T07:53:09.000Z | C-ATTL3/parameter_initialization/gpu/OneGPUParameterInitialization.hpp | Merlin1A/C-ATTL3 | daf7207fdc047412957761ef412fa805b2656d65 | [
"MIT"
] | null | null | null | C-ATTL3/parameter_initialization/gpu/OneGPUParameterInitialization.hpp | Merlin1A/C-ATTL3 | daf7207fdc047412957761ef412fa805b2656d65 | [
"MIT"
] | 5 | 2019-11-01T09:38:29.000Z | 2021-11-09T00:41:05.000Z | /*
* OneGPUParameterInitialization.hpp
*
* Created on: 12 Aug 2018
* Author: Viktor Csomor
*/
#ifndef C_ATTL3_PARAMETER_INITIALIZATION_GPU_ONEGPUPARAMETERINITIALIZATION_H_
#define C_ATTL3_PARAMETER_INITIALIZATION_GPU_ONEGPUPARAMETERINITIALIZATION_H_
#include "core/gpu/GPUParameterInitialization.hpp"
namespace cattle {
namespace gpu {
template<typename Scalar>
class OneGPUParameterInitialization : public GPUParameterInitialization<Scalar> {
public:
inline void apply(CuBLASMatrix<Scalar>& params) const {
params.set_values(1);
}
};
} /* namespace gpu */
} /* namespace cattle */
#endif /* C_ATTL3_PARAMETER_INITIALIZATION_GPU_ONEGPUPARAMETERINITIALIZATION_H_ */
| 24.5 | 82 | 0.801749 | ViktorC |
5d2b82d7c9cf05b8a8c2bf07e07dd0ff32ad11d8 | 2,696 | cpp | C++ | collection/cp/bcw_codebook-master/Contest/Daejeon2015/C.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | 1 | 2019-03-24T13:12:01.000Z | 2019-03-24T13:12:01.000Z | collection/cp/bcw_codebook-master/Contest/Daejeon2015/C.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | null | null | null | collection/cp/bcw_codebook-master/Contest/Daejeon2015/C.cpp | daemonslayer/Notebook | a9880be9bd86955afd6b8f7352822bc18673eda3 | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
#include<unistd.h>
using namespace std;
#define FZ(n) memset((n),0,sizeof(n))
#define FMO(n) memset((n),-1,sizeof(n))
#define F first
#define S second
#define PB push_back
#define ALL(x) begin(x),end(x)
#define SZ(x) ((int)(x).size())
#define IOS ios_base::sync_with_stdio(0); cin.tie(0)
#define REP(i,x) for (int i=0; i<(x); i++)
#define REP1(i,a,b) for (int i=(a); i<=(b); i++)
#ifdef ONLINE_JUDGE
#define FILEIO(name) \
freopen(name".in", "r", stdin); \
freopen(name".out", "w", stdout);
#else
#define FILEIO(name)
#endif
template<typename A, typename B>
ostream& operator <<(ostream &s, const pair<A,B> &p) {
return s<<"("<<p.first<<","<<p.second<<")";
}
template<typename T>
ostream& operator <<(ostream &s, const vector<T> &c) {
s<<"[ ";
for (auto it : c) s << it << " ";
s<<"]";
return s;
}
// Let's Fight!
struct Dinic{
static const int MXN = 10000;
struct Edge{ int v,f,re; };
int n,s,t,level[MXN];
vector<Edge> E[MXN];
void init(int _n, int _s, int _t){
n = _n; s = _s; t = _t;
for (int i=0; i<n; i++) E[i].clear();
}
void add_edge(int u, int v, int f){
E[u].PB({v,f,SZ(E[v])});
E[v].PB({u,0,SZ(E[u])-1});
}
bool BFS(){
FMO(level);
queue<int> que;
que.push(s);
level[s] = 0;
while (!que.empty()){
int u = que.front(); que.pop();
for (auto it : E[u]){
if (it.f > 0 && level[it.v] == -1){
level[it.v] = level[u]+1;
que.push(it.v);
}
}
}
return level[t] != -1;
}
int DFS(int u, int nf){
if (u == t) return nf;
int res = 0;
for (auto &it : E[u]){
if (it.f > 0 && level[it.v] == level[u]+1){
int tf = DFS(it.v, min(nf,it.f));
res += tf; nf -= tf; it.f -= tf;
E[it.v][it.re].f += tf;
if (nf == 0) return res;
}
}
if (!res) level[u] = -1;
return res;
}
int flow(int res=0){
while ( BFS() )
res += DFS(s,2147483647);
return res;
}
}flow;
int N,M;
int ip[55][55];
inline int getid(int i, int j) { return i * M + j; }
int main() {
IOS;
int ts;
cin >> ts;
while (ts--) {
cin >> N >> M;
REP(i,N) REP(j,M) cin >> ip[i][j];
int V = N * M + 2;
int S = V - 2;
int T = V - 1;
int sum = 0;
flow.init(V,S,T);
static const int dir[4][2] = {{1,0}, {-1,0}, {0,1}, {0,-1}};
REP(i,N) {
REP(j,M) {
sum += ip[i][j];
if ((i + j) & 1) {
flow.add_edge(S, getid(i,j), ip[i][j]);
REP(d,4) {
int x = i + dir[d][0];
int y = j + dir[d][1];
if (x < 0 or x >= N or y < 0 or y >= M) continue;
flow.add_edge(getid(i,j), getid(x,y), 2147483647);
}
} else {
flow.add_edge(getid(i,j), T, ip[i][j]);
}
}
}
int ans = sum - flow.flow();
cout << ans << endl;
}
return 0;
}
| 21.568 | 62 | 0.512611 | daemonslayer |
5d2d63e0d058226c1e41194642b755d655e13334 | 2,244 | hh | C++ | src/EDepSimRootPersistencyManager.hh | andrewmogan/edep-sim | 4e9923ccba8b2f65f47b72cbb41ed683f19f1123 | [
"MIT"
] | 15 | 2017-04-25T14:20:22.000Z | 2022-03-15T19:39:43.000Z | src/EDepSimRootPersistencyManager.hh | andrewmogan/edep-sim | 4e9923ccba8b2f65f47b72cbb41ed683f19f1123 | [
"MIT"
] | 24 | 2017-11-08T21:16:48.000Z | 2022-03-04T13:33:18.000Z | src/EDepSimRootPersistencyManager.hh | andrewmogan/edep-sim | 4e9923ccba8b2f65f47b72cbb41ed683f19f1123 | [
"MIT"
] | 20 | 2017-11-09T15:41:46.000Z | 2022-01-25T20:52:32.000Z | ////////////////////////////////////////////////////////////
// $Id: EDepSim::RootPersistencyManager.hh,v 1.31 2011/09/06 18:58:35 mcgrew Exp $
//
#ifndef EDepSim_RootPersistencyManager_hh_seen
#define EDepSim_RootPersistencyManager_hh_seen
#include <string>
#include <vector>
#include <map>
class TFile;
class TTree;
class TGeoManager;
#include "EDepSimPersistencyManager.hh"
/// Provide a root output for the geant 4 events. This just takes the summary
/// from EDepSim::PersistencyManager and dumps it as a tree.
namespace EDepSim {class RootPersistencyManager;}
class EDepSim::RootPersistencyManager : public EDepSim::PersistencyManager {
public:
/// Creates a root persistency manager. Through the "magic" of
/// G4VPersistencyManager the ultimate base class, this declared to the G4
/// persistency management system. You can only have one active
/// persistency class at any give moment.
RootPersistencyManager();
virtual ~RootPersistencyManager();
/// Return true if the ROOT output file is active. This means that the
/// output file is open and ready to accept data.
bool IsOpen();
/// Return a pointer to the current TFile.
TFile* GetTFile() const {return fOutput;}
/// Stores an event to the output file.
virtual G4bool Store(const G4Event* anEvent);
virtual G4bool Store(const G4Run* aRun);
virtual G4bool Store(const G4VPhysicalVolume* aWorld);
/// Retrieve information from a file. These are not implemented.
virtual G4bool Retrieve(G4Event *&e) {e=NULL; return false;}
virtual G4bool Retrieve(G4Run* &r) {r=NULL; return false;}
virtual G4bool Retrieve(G4VPhysicalVolume* &w) {w=NULL; return false;}
/// Interface with PersistencyMessenger (open and close the
/// database).
virtual G4bool Open(G4String dbname);
virtual G4bool Close(void);
private:
/// Make the MC Header and add it to truth.
void MakeMCHeader(const G4Event* src);
private:
/// The ROOT output file that events are saved into.
TFile *fOutput;
/// The event tree that contains the output events.
TTree *fEventTree;
/// The number of events saved to the output file since the last write.
int fEventsNotSaved;
};
#endif
| 33.492537 | 82 | 0.701872 | andrewmogan |
5d35a7a1bd2456f60d1fcfd987b92c18670c5bb6 | 7,938 | cpp | C++ | src/mongo/db/exec/and_sorted.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/exec/and_sorted.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/exec/and_sorted.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/db/exec/and_sorted.h"
#include <memory>
#include "mongo/db/exec/and_common.h"
#include "mongo/db/exec/scoped_timer.h"
#include "mongo/db/exec/working_set_common.h"
#include "mongo/util/str.h"
namespace mongo {
using std::numeric_limits;
using std::unique_ptr;
using std::vector;
// static
const char* AndSortedStage::kStageType = "AND_SORTED";
AndSortedStage::AndSortedStage(ExpressionContext* expCtx, WorkingSet* ws)
: PlanStage(kStageType, expCtx),
_ws(ws),
_targetNode(numeric_limits<size_t>::max()),
_targetId(WorkingSet::INVALID_ID),
_isEOF(false) {}
void AndSortedStage::addChild(std::unique_ptr<PlanStage> child) {
_children.emplace_back(std::move(child));
}
bool AndSortedStage::isEOF() {
return _isEOF;
}
PlanStage::StageState AndSortedStage::doWork(WorkingSetID* out) {
if (isEOF()) {
return PlanStage::IS_EOF;
}
if (0 == _specificStats.failedAnd.size()) {
_specificStats.failedAnd.resize(_children.size());
}
// If we don't have any nodes that we're work()-ing until they hit a certain RecordId...
if (0 == _workingTowardRep.size()) {
// Get a target RecordId.
return getTargetRecordId(out);
}
// Move nodes toward the target RecordId.
// If all nodes reach the target RecordId, return it. The next call to work() will set a new
// target.
return moveTowardTargetRecordId(out);
}
PlanStage::StageState AndSortedStage::getTargetRecordId(WorkingSetID* out) {
verify(numeric_limits<size_t>::max() == _targetNode);
verify(WorkingSet::INVALID_ID == _targetId);
verify(RecordId() == _targetRecordId);
// Pick one, and get a RecordId to work toward.
WorkingSetID id = WorkingSet::INVALID_ID;
StageState state = _children[0]->work(&id);
if (PlanStage::ADVANCED == state) {
WorkingSetMember* member = _ws->get(id);
// The child must give us a WorkingSetMember with a record id, since we intersect index keys
// based on the record id. The planner ensures that the child stage can never produce an WSM
// with no record id.
invariant(member->hasRecordId());
// We have a value from one child to AND with.
_targetNode = 0;
_targetId = id;
_targetRecordId = member->recordId;
// Ensure that the BSONObj underlying the WorkingSetMember is owned in case we yield.
member->makeObjOwnedIfNeeded();
// We have to AND with all other children.
for (size_t i = 1; i < _children.size(); ++i) {
_workingTowardRep.push(i);
}
return PlanStage::NEED_TIME;
} else if (PlanStage::IS_EOF == state) {
_isEOF = true;
return state;
} else {
if (PlanStage::NEED_YIELD == state) {
*out = id;
}
// NEED_TIME, NEED_YIELD.
return state;
}
}
PlanStage::StageState AndSortedStage::moveTowardTargetRecordId(WorkingSetID* out) {
verify(numeric_limits<size_t>::max() != _targetNode);
verify(WorkingSet::INVALID_ID != _targetId);
// We have nodes that haven't hit _targetRecordId yet.
size_t workingChildNumber = _workingTowardRep.front();
auto& next = _children[workingChildNumber];
WorkingSetID id = WorkingSet::INVALID_ID;
StageState state = next->work(&id);
if (PlanStage::ADVANCED == state) {
WorkingSetMember* member = _ws->get(id);
// The child must give us a WorkingSetMember with a record id, since we intersect index keys
// based on the record id. The planner ensures that the child stage can never produce an WSM
// with no record id.
invariant(member->hasRecordId());
if (member->recordId == _targetRecordId) {
// The front element has hit _targetRecordId. Don't move it forward anymore/work on
// another element.
_workingTowardRep.pop();
AndCommon::mergeFrom(_ws, _targetId, *member);
_ws->free(id);
if (0 == _workingTowardRep.size()) {
WorkingSetID toReturn = _targetId;
_targetNode = numeric_limits<size_t>::max();
_targetId = WorkingSet::INVALID_ID;
_targetRecordId = RecordId();
*out = toReturn;
return PlanStage::ADVANCED;
}
// More children need to be advanced to _targetRecordId.
return PlanStage::NEED_TIME;
} else if (member->recordId < _targetRecordId) {
// The front element of _workingTowardRep hasn't hit the thing we're AND-ing with
// yet. Try again later.
_ws->free(id);
return PlanStage::NEED_TIME;
} else {
// member->recordId > _targetRecordId.
// _targetRecordId wasn't successfully AND-ed with the other sub-plans. We toss it and
// try AND-ing with the next value.
_specificStats.failedAnd[_targetNode]++;
_ws->free(_targetId);
_targetNode = workingChildNumber;
_targetRecordId = member->recordId;
_targetId = id;
// Ensure that the BSONObj underlying the WorkingSetMember is owned in case we yield.
member->makeObjOwnedIfNeeded();
_workingTowardRep = std::queue<size_t>();
for (size_t i = 0; i < _children.size(); ++i) {
if (workingChildNumber != i) {
_workingTowardRep.push(i);
}
}
// Need time to chase after the new _targetRecordId.
return PlanStage::NEED_TIME;
}
} else if (PlanStage::IS_EOF == state) {
_isEOF = true;
_ws->free(_targetId);
return state;
} else {
if (PlanStage::NEED_YIELD == state) {
*out = id;
}
return state;
}
}
unique_ptr<PlanStageStats> AndSortedStage::getStats() {
_commonStats.isEOF = isEOF();
unique_ptr<PlanStageStats> ret =
std::make_unique<PlanStageStats>(_commonStats, STAGE_AND_SORTED);
ret->specific = std::make_unique<AndSortedStats>(_specificStats);
for (size_t i = 0; i < _children.size(); ++i) {
ret->children.emplace_back(_children[i]->getStats());
}
return ret;
}
const SpecificStats* AndSortedStage::getSpecificStats() const {
return &_specificStats;
}
} // namespace mongo
| 35.28 | 100 | 0.641723 | benety |
5d36a3a91d19830a053d6e2eb27a45be1dcff4d6 | 1,446 | cc | C++ | Player.cc | p-rivero/EDA-ThePurge2020 | 81a48df7bdaff6067792d037b9e6627739b959d1 | [
"MIT"
] | null | null | null | Player.cc | p-rivero/EDA-ThePurge2020 | 81a48df7bdaff6067792d037b9e6627739b959d1 | [
"MIT"
] | null | null | null | Player.cc | p-rivero/EDA-ThePurge2020 | 81a48df7bdaff6067792d037b9e6627739b959d1 | [
"MIT"
] | null | null | null | //////// STUDENTS DO NOT NEED TO READ BELOW THIS LINE ////////
#include "Player.hh"
void Player::reset (ifstream& is) {
// Should read what Board::print_state() prints.
// Should fill the same data structures as
// Board::Board (istream& is, int seed), except for settings and names.
// THESE DATA STRUCTURES MUST BE RESET: maps WITH clear(), etc.
*(Action*)this = Action();
citizens .clear();
player2builders .clear();
player2warriors .clear();
player2barricades.clear();
player2builders = vector<set<int>>(num_players());
player2warriors = vector<set<int>>(num_players());
player2barricades = vector<set<Pos>>(num_players());
read_grid(is);
string s;
is >> s >> rnd;
_my_assert(s == "round", "Expected 'round' while parsing.");
_my_assert(rnd >= 0 and rnd < num_rounds(), "Round is not ok.");
is >> s >> day;
_my_assert(s == "day", "Expected 'day' while parsing.");
is >> s;
_my_assert(s == "score", "Expected 'score' while parsing.");
scr = vector<int>(num_players());
for (auto& s : scr) {
is >> s;
_my_assert(s >= 0, "Score cannot be negative.");
}
is >> s;
_my_assert(s == "status", "Expected 'status' while parsing.");
stats = vector<double>(num_players());
for (auto& st : stats) {
is >> st;
_my_assert(st == -1 or (st >= 0 and st <= 1), "Status is not ok.");
}
_my_assert(ok(), "Invariants are not satisfied.");
// forget();
}
| 27.283019 | 73 | 0.612033 | p-rivero |
5d37e21f1f2a113a54bbe005cd72b14b5fd908e9 | 1,396 | hpp | C++ | Code/Engine/Scene/D3D11Scene.hpp | ntaylorbishop/Copycat | c02f2881f0700a33a2630fd18bc409177d80b8cd | [
"MIT"
] | 2 | 2017-10-02T03:18:55.000Z | 2018-11-21T16:30:36.000Z | Code/Engine/Scene/D3D11Scene.hpp | ntaylorbishop/Copycat | c02f2881f0700a33a2630fd18bc409177d80b8cd | [
"MIT"
] | null | null | null | Code/Engine/Scene/D3D11Scene.hpp | ntaylorbishop/Copycat | c02f2881f0700a33a2630fd18bc409177d80b8cd | [
"MIT"
] | null | null | null | #pragma once
#include "Engine/General/Core/EngineCommon.hpp"
class D3D11Model;
class D3D11Material;
class D3D11MeshRenderer;
const float ANIMATION_FPS = 30.f;
const float MESH_LOAD_ENGINE_SCALE = 0.4f;
class D3D11Scene {
public:
//LOADING SAVING
void AddModelsFromDirectory(const char* dir);
static D3D11Scene* LoadSceneFromDirectory(const char* sceneDir);
static D3D11Scene* LoadSceneFromFBXFile(const char* filename);
void SaveSceneToFile(const char* filepath);
//STRUCTORS
D3D11Scene() { }
~D3D11Scene() { }
//RENDER
void RenderForShadows(D3D11Material* shadowMat) const;
void RenderWithMaterial(D3D11Material* mat) const;
void Render(bool isRenderingTransparent = false, D3D11MeshRenderer* customMeshRenderer = nullptr) const;
void RenderSkybox(D3D11MeshRenderer* customMeshRenderer = nullptr) const;
//ADDING REMOVING
void AddModel(D3D11Model* newMesh);
void RemoveModel(D3D11Model* mesh);
void SetSkybox(D3D11Model* skybox) { m_skybox = skybox; }
void EnableDebugSorting() { m_debugShouldSort = true; }
void DisableDebugSorting() { m_debugShouldSort = false; }
private:
//PRIVATE ADD REMOVE
void AddStaticMeshToOpaquePass(D3D11Model* newMesh);
void RemoveStaticMeshFromOpaquePass(D3D11Model* mesh);
D3D11Model* m_opaqueMeshes = nullptr;
size_t m_numMeshes = 0;
D3D11Model* m_skybox = nullptr;
bool m_debugShouldSort = false;
}; | 28.489796 | 105 | 0.77149 | ntaylorbishop |
5d3976ed6c5b2959434579750f8e5ee37ca0872d | 3,045 | cpp | C++ | hoo/emitter/DefinitionEmitter.cpp | benoybose/hoolang | 4e280a03caec837be35c8aac948923e1bea96b85 | [
"BSD-3-Clause"
] | null | null | null | hoo/emitter/DefinitionEmitter.cpp | benoybose/hoolang | 4e280a03caec837be35c8aac948923e1bea96b85 | [
"BSD-3-Clause"
] | 14 | 2020-07-24T10:25:59.000Z | 2020-08-02T13:27:09.000Z | hoo/emitter/DefinitionEmitter.cpp | benoybose/hoolang | 4e280a03caec837be35c8aac948923e1bea96b85 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2021 Benoy Bose
*
* 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 <hoo/emitter/DefinitionEmitter.hh>
#include <hoo/emitter/ClassDefinitionEmitter.hh>
#include <hoo/emitter/EmitterException.hh>
#include <hoo/emitter/FunctionDefinitionEmitter.hh>
#include <hoo/ast/ClassDefinition.hh>
#include <hoo/ast/FunctionDefinition.hh>
#include <memory>
namespace hoo
{
namespace emitter
{
DefinitionEmitter::DefinitionEmitter(std::shared_ptr<Definition> definition,
const EmitterContext& context,
std::shared_ptr<ClassDefinition> parent_class_definition) :
EmitterBase(context),
_definition(definition),
_parent_class_definition (parent_class_definition)
{
}
std::shared_ptr<ClassDefinition> DefinitionEmitter::GetParentClass()
{
return _parent_class_definition;
}
void DefinitionEmitter::Emit()
{
auto const definitionType = _definition->GetDefinitionType();
switch (definitionType) {
case DEFINITION_CLASS:
{
auto classDefinition = std::dynamic_pointer_cast<ClassDefinition>(_definition);
ClassDefinitionEmitter emitter(classDefinition,
_emitter_context,
_parent_class_definition);
emitter.Emit();
break;
}
case DEFINITION_FUNCTION:
{
auto function_definition = std::dynamic_pointer_cast<FunctionDefinition>(_definition);
FunctionDefinitionEmitter emitter(function_definition,
_emitter_context,
_parent_class_definition);
emitter.Emit();
break;
}
default:
{
throw EmitterException(ERR_EMITTER_UNSUPPORTED_DEFINITION);
}
}
}
}
}
| 39.038462 | 106 | 0.649589 | benoybose |
5d39b30e65c6aa79ab650860f8d001bd3dfb1d96 | 472 | cpp | C++ | ConsoleApplication1/ConsoleApplication1/JsonParser.cpp | AndrFran/CodeInstrumentation | e58ab6d4a6dd5e70d00b5915820af5b0cd9dc33c | [
"MIT"
] | null | null | null | ConsoleApplication1/ConsoleApplication1/JsonParser.cpp | AndrFran/CodeInstrumentation | e58ab6d4a6dd5e70d00b5915820af5b0cd9dc33c | [
"MIT"
] | null | null | null | ConsoleApplication1/ConsoleApplication1/JsonParser.cpp | AndrFran/CodeInstrumentation | e58ab6d4a6dd5e70d00b5915820af5b0cd9dc33c | [
"MIT"
] | null | null | null | #include "JsonParser.h"
namespace WpfApplication2
{
JsonParser::JsonParser()
{
serializer = new JavaScriptSerializer();
}
std::unordered_map<std::wstring, std::any> JsonParser::Deserialize(const std::wstring &json)
{
serializer->Deserialize<std::unordered_map<std::wstring, std::any>>(json);
std::unordered_map<std::wstring, std::any> ParsedFunction = serializer->Deserialize<std::unordered_map<std::wstring, std::any>>(json);
return ParsedFunction;
}
}
| 26.222222 | 136 | 0.735169 | AndrFran |
5d3d86a01e721acc6d23cbf4297e7d43fb3098f4 | 4,677 | cc | C++ | virtual_file_provider/service.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | 5 | 2019-01-19T15:38:48.000Z | 2021-10-06T03:59:46.000Z | virtual_file_provider/service.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | null | null | null | virtual_file_provider/service.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | 1 | 2019-02-15T23:05:30.000Z | 2019-02-15T23:05:30.000Z | // Copyright 2017 The Chromium OS 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 "virtual_file_provider/service.h"
#include <fcntl.h>
#include <unistd.h>
#include <memory>
#include <string>
#include <utility>
#include <base/bind.h>
#include <base/guid.h>
#include <base/logging.h>
#include <base/posix/eintr_wrapper.h>
#include <chromeos/dbus/service_constants.h>
#include <dbus/bus.h>
#include <dbus/message.h>
#include <dbus/object_proxy.h>
namespace virtual_file_provider {
Service::Service(const base::FilePath& fuse_mount_path, SizeMap* size_map)
: fuse_mount_path_(fuse_mount_path),
size_map_(size_map),
weak_ptr_factory_(this) {
thread_checker_.DetachFromThread();
}
Service::~Service() {
DCHECK(thread_checker_.CalledOnValidThread());
if (bus_)
bus_->ShutdownAndBlock();
}
bool Service::Initialize() {
DCHECK(thread_checker_.CalledOnValidThread());
// Connect the bus.
dbus::Bus::Options options;
options.bus_type = dbus::Bus::SYSTEM;
bus_ = new dbus::Bus(options);
if (!bus_->Connect()) {
LOG(ERROR) << "Failed to initialize D-Bus connection.";
return false;
}
request_handler_proxy_ = bus_->GetObjectProxy(
chromeos::kVirtualFileRequestServiceName,
dbus::ObjectPath(chromeos::kVirtualFileRequestServicePath));
// Export methods.
exported_object_ = bus_->GetExportedObject(
dbus::ObjectPath(kVirtualFileProviderServicePath));
if (!exported_object_->ExportMethodAndBlock(
kVirtualFileProviderInterface,
kOpenFileMethod,
base::Bind(&Service::OpenFile, weak_ptr_factory_.GetWeakPtr()))) {
LOG(ERROR) << "Failed to export OpenFile method.";
return false;
}
// Request the ownership of the service name.
if (!bus_->RequestOwnershipAndBlock(kVirtualFileProviderServiceName,
dbus::Bus::REQUIRE_PRIMARY)) {
LOG(ERROR) << "Failed to own the service name";
return false;
}
return true;
}
void Service::SendReadRequest(const std::string& id,
int64_t offset,
int64_t size,
base::ScopedFD fd) {
DCHECK(thread_checker_.CalledOnValidThread());
dbus::MethodCall method_call(
chromeos::kVirtualFileRequestServiceInterface,
chromeos::kVirtualFileRequestServiceHandleReadRequestMethod);
dbus::MessageWriter writer(&method_call);
writer.AppendString(id);
writer.AppendInt64(offset);
writer.AppendInt64(size);
writer.AppendFileDescriptor(fd.get());
request_handler_proxy_->CallMethod(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
dbus::ObjectProxy::EmptyResponseCallback());
}
void Service::SendIdReleased(const std::string& id) {
DCHECK(thread_checker_.CalledOnValidThread());
dbus::MethodCall method_call(
chromeos::kVirtualFileRequestServiceInterface,
chromeos::kVirtualFileRequestServiceHandleIdReleasedMethod);
dbus::MessageWriter writer(&method_call);
writer.AppendString(id);
request_handler_proxy_->CallMethod(
&method_call,
dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
dbus::ObjectProxy::EmptyResponseCallback());
}
void Service::OpenFile(dbus::MethodCall* method_call,
dbus::ExportedObject::ResponseSender response_sender) {
DCHECK(thread_checker_.CalledOnValidThread());
dbus::MessageReader reader(method_call);
int64_t size = 0;
if (!reader.PopInt64(&size)) {
response_sender.Run(dbus::ErrorResponse::FromMethodCall(
method_call, DBUS_ERROR_INVALID_ARGS, "Size must be provided."));
return;
}
// Generate a new ID.
std::string id = base::GenerateGUID();
// Set the size of the ID.
// NOTE: Currently, updating the size value is not supported. If the virtual
// file gets modified later, the size map's value can contradict with the real
// value and it can result in read errors.
CHECK_EQ(-1, size_map_->GetSize(id));
size_map_->SetSize(id, size);
// An ID corresponds to a file name in the FUSE file system.
base::FilePath path = fuse_mount_path_.AppendASCII(id);
// Create a new FD associated with the ID.
base::ScopedFD fd(HANDLE_EINTR(open(path.value().c_str(),
O_RDONLY | O_CLOEXEC)));
// Send response.
std::unique_ptr<dbus::Response> response =
dbus::Response::FromMethodCall(method_call);
dbus::MessageWriter writer(response.get());
writer.AppendString(id);
writer.AppendFileDescriptor(fd.get());
response_sender.Run(std::move(response));
}
} // namespace virtual_file_provider
| 33.407143 | 80 | 0.704298 | emersion |
5d3f19f0f88d8408cda9573d89e1f1e95faad499 | 537 | cc | C++ | src/sigar_control_group_not_supported.cc | couchbase/sigar | 0eef65db1fb42b8f5e42692e9f59f1e8ebe95c6b | [
"Apache-2.0"
] | 7 | 2015-05-19T11:24:32.000Z | 2019-12-16T09:23:42.000Z | src/sigar_control_group_not_supported.cc | couchbase/sigar | 0eef65db1fb42b8f5e42692e9f59f1e8ebe95c6b | [
"Apache-2.0"
] | null | null | null | src/sigar_control_group_not_supported.cc | couchbase/sigar | 0eef65db1fb42b8f5e42692e9f59f1e8ebe95c6b | [
"Apache-2.0"
] | 6 | 2015-04-21T04:00:43.000Z | 2022-02-24T14:07:21.000Z | /*
* Copyright 2021-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#include <sigar_control_group.h>
void sigar_get_control_group_info(sigar_control_group_info_t* info) {
info->supported = false;
}
| 35.8 | 78 | 0.741155 | couchbase |
5d41558a4723b240fe82cae068b4139894708bdb | 1,217 | cpp | C++ | unittest/vslib/test_sai_vs_vlan.cpp | vmittal-msft/sonic-sairedis | 6baff35880005aee2854fdcde105c4322c28d04f | [
"Apache-2.0"
] | 50 | 2016-03-23T08:04:44.000Z | 2022-03-25T05:06:16.000Z | unittest/vslib/test_sai_vs_vlan.cpp | vmittal-msft/sonic-sairedis | 6baff35880005aee2854fdcde105c4322c28d04f | [
"Apache-2.0"
] | 589 | 2016-04-01T04:09:09.000Z | 2022-03-31T00:38:10.000Z | unittest/vslib/test_sai_vs_vlan.cpp | vmittal-msft/sonic-sairedis | 6baff35880005aee2854fdcde105c4322c28d04f | [
"Apache-2.0"
] | 234 | 2016-03-28T20:59:21.000Z | 2022-03-23T09:26:22.000Z | #include <gtest/gtest.h>
extern "C" {
#include "sai.h"
}
#include "swss/logger.h"
TEST(libsaivs, vlan)
{
sai_vlan_api_t *api = nullptr;
sai_api_query(SAI_API_VLAN, (void**)&api);
EXPECT_NE(api, nullptr);
sai_object_id_t id;
EXPECT_NE(SAI_STATUS_SUCCESS, api->create_vlan(&id,0,0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->remove_vlan(0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->set_vlan_attribute(0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->get_vlan_attribute(0,0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->create_vlan_member(&id,0,0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->remove_vlan_member(0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->set_vlan_member_attribute(0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->get_vlan_member_attribute(0,0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->create_vlan_members(0,0,0,0,SAI_BULK_OP_ERROR_MODE_IGNORE_ERROR,0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->remove_vlan_members(0,0,SAI_BULK_OP_ERROR_MODE_IGNORE_ERROR,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->get_vlan_stats(0,0,0,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->get_vlan_stats_ext(0,0,0,SAI_STATS_MODE_READ,0));
EXPECT_NE(SAI_STATUS_SUCCESS, api->clear_vlan_stats(0,0,0));
}
| 33.805556 | 109 | 0.750205 | vmittal-msft |
5d41b503b13fdb258fc80e6d5c1fe552b2ad1d56 | 3,234 | hpp | C++ | src/Property_reflect.hpp | cpp-ftw/tmp-lib | 6b4afd294b20d615abe9f409241409bed378eaa7 | [
"MIT"
] | null | null | null | src/Property_reflect.hpp | cpp-ftw/tmp-lib | 6b4afd294b20d615abe9f409241409bed378eaa7 | [
"MIT"
] | null | null | null | src/Property_reflect.hpp | cpp-ftw/tmp-lib | 6b4afd294b20d615abe9f409241409bed378eaa7 | [
"MIT"
] | null | null | null | #ifndef PROPERTY_HPP_INCLUDED
#define PROPERTY_HPP_INCLUDED
// mire jó: getter és setter helyettesítése egy publikus, fiktív adattaggal.
#define PROPERTY( parent, return_type, name) Property<parent, return_type, (& parent :: set ##name), (& parent :: get ##name)> name{this}
#define PROPERTY_(parent, return_type, name) Property<parent, return_type, (& parent :: set_##name), (& parent :: get_##name)> name{this}
// 1 db akármilyen típusú member pointert tárol
template<typename CLASS, typename T, T CLASS::* MPTR>
struct MptrHolder
{
static constexpr auto mptr = MPTR;
};
// n db akármilyen típusú member pointert tárol
template<typename CLASS, typename... MPTRS>
struct MptrCollection
{
// belső használatú fos, hátha jobban olvasható a variadic magic
#define SELF (static_cast< CLASS*>(self))
#define CSELF (static_cast<const CLASS*>(self))
static void set_objs(CLASS * self)
{
using swallow = int[];
(void) swallow {0, ((void)((SELF->*(MPTRS::mptr)).obj = SELF), 0)...};
}
#undef SELF
#undef CSELF
};
// levezeti 1 db member pointer osztályának típusát
template<typename CLASS, typename T>
CLASS make_mptr_class(T CLASS::* mptr);
// levezeti 1 db member pointer típusát
template<typename CLASS, typename T>
T make_mptr_type(T CLASS::* mptr);
// becsomagol 1 db member pointert egy típusba
#define PROPERTY_MAKE(x) MptrHolder<decltype(make_mptr_class(x)), decltype(make_mptr_type(x)), x>
// becsomagol n db member pointert egy típusba
#define PROPERTY_DECLARE(x, ...) using properties = MptrCollection<Vektor, __VA_ARGS__>
template<typename CLASS>
class PropertyCRTP;
template <typename CLASS, typename T,
void (CLASS::*SETTERPTR) (T const& newvalue),
T (CLASS::*GETTERPTR) () const>
class Property
{
friend class PropertyCRTP<CLASS>;
template<typename, typename...>
friend class MptrCollection;
CLASS * obj;
constexpr explicit Property (CLASS* obj) : obj (obj) {}
// no-op: a PropertyCRTP feladata a pointerek beállítgatása, és ezt még
// azelőtt megteszi, hogy ide eljutnánk, így itt nem szabad rajta piszkálni
// private + friend, azért, hogy ne lehessen leírni:
// auto x = foo.property;
constexpr Property() { }
constexpr Property(Property const&) { }
constexpr Property(Property&&) { }
friend CLASS;
public:
// property beállítása
Property& operator= (T const& newvalue)
{
((*obj).*SETTERPTR) (newvalue);
return *this;
}
// property lekérdezése
operator T () const
{
return ((*obj).*GETTERPTR) ();
}
// property = property eset kezelése
Property& operator= (Property const& the_other)
{
*this = the_other.operator T();
return *this;
}
};
// ebből kell leszármaznia a Property-t tartalmazó osztálynak
template<typename Derived>
class PropertyCRTP
{
void set_objs()
{
using d_prop = typename Derived::properties;
d_prop::set_objs(static_cast<Derived*>(this));
}
protected:
PropertyCRTP() {
set_objs();
}
PropertyCRTP(PropertyCRTP const&) {
set_objs();
}
PropertyCRTP(PropertyCRTP&&) {
set_objs();
}
};
#endif // PROPERTY_HPP_INCLUDED
| 27.40678 | 137 | 0.675943 | cpp-ftw |
5d432aa746aa0225813c1d57eaf4f88475be8ac2 | 4,153 | cpp | C++ | test/Vector3DTest.cpp | Tykky/Raytracer | f271671a2002a64e9bdfd4898e1bbb15f67a6795 | [
"MIT"
] | 15 | 2020-03-07T13:41:45.000Z | 2022-03-31T14:38:18.000Z | test/Vector3DTest.cpp | Tykky/Raytracer | f271671a2002a64e9bdfd4898e1bbb15f67a6795 | [
"MIT"
] | 15 | 2020-02-14T16:01:23.000Z | 2021-02-20T21:53:38.000Z | test/Vector3DTest.cpp | Tykky/Raytracer | f271671a2002a64e9bdfd4898e1bbb15f67a6795 | [
"MIT"
] | 2 | 2020-08-25T00:10:10.000Z | 2022-03-31T17:30:40.000Z | #include "gtest/gtest.h"
#include "core/Vector3D.h"
class Vector3DTest : public ::testing::Test {
protected:
Vector3D v1;
Vector3D v2;
virtual void SetUp() {
v1 = Vector3D(1, 2, 3);
v2 = Vector3D(3, 4, 5);
}
};
TEST_F(Vector3DTest, opPlusTest) {
+(v1);
EXPECT_FLOAT_EQ(1, v1.getX());
EXPECT_FLOAT_EQ(2, v1.getY());
EXPECT_FLOAT_EQ(3, v1.getZ());
}
TEST_F(Vector3DTest, opAddtVectorTest) {
v1 += v2;
EXPECT_FLOAT_EQ(4, v1.getX());
EXPECT_FLOAT_EQ(6, v1.getY());
EXPECT_FLOAT_EQ(8, v1.getZ());
}
TEST_F(Vector3DTest, opAddConstantTest) {
float c = 9;
v1 += c;
EXPECT_FLOAT_EQ(1 + c, v1.getX());
EXPECT_FLOAT_EQ(2 + c, v1.getY());
EXPECT_FLOAT_EQ(3 + c, v1.getZ());
}
TEST_F(Vector3DTest, opMinusTest) {
Vector3D negv1 = -v1;
EXPECT_FLOAT_EQ(-1, negv1.getX());
EXPECT_FLOAT_EQ(-2, negv1.getY());
EXPECT_FLOAT_EQ(-3, negv1.getZ());
}
TEST_F(Vector3DTest, opDecreaseVectorTest) {
v1 -= v2;
EXPECT_FLOAT_EQ(-2, v1.getX());
EXPECT_FLOAT_EQ(-2, v1.getY());
EXPECT_FLOAT_EQ(-2, v1.getZ());
}
TEST_F(Vector3DTest, opDecreaseConstantTest) {
float c = 5;
v1 -= c;
EXPECT_FLOAT_EQ(-4, v1.getX());
EXPECT_FLOAT_EQ(-3, v1.getY());
EXPECT_FLOAT_EQ(-2, v1.getZ());
}
TEST_F(Vector3DTest, opMultiplyVectorTest) {
v1 *= v2;
EXPECT_FLOAT_EQ(3, v1.getX());
EXPECT_FLOAT_EQ(8, v1.getY());
EXPECT_FLOAT_EQ(15, v1.getZ());
}
TEST_F(Vector3DTest, opMultiplyConstantTest) {
float c = 5;
v1 *= c;
EXPECT_FLOAT_EQ(5, v1.getX());
EXPECT_FLOAT_EQ(10, v1.getY());
EXPECT_FLOAT_EQ(15, v1.getZ());
}
TEST_F(Vector3DTest, opDivideVectorTest) {
v1 /= v2;
EXPECT_FLOAT_EQ(.3333333, v1.getX());
EXPECT_FLOAT_EQ(.5, v1.getY());
EXPECT_FLOAT_EQ(.6, v1.getZ());
}
TEST_F(Vector3DTest, opDivideConstantTest) {
float c = 5;
v1 /= c;
EXPECT_FLOAT_EQ(0.2, v1.getX());
EXPECT_FLOAT_EQ(0.4, v1.getY());
EXPECT_FLOAT_EQ(0.6, v1.getZ());
}
TEST_F(Vector3DTest, lengthTest) {
EXPECT_FLOAT_EQ(3.7416575, v1.length());
EXPECT_FLOAT_EQ(7.0710678, v2.length());
}
TEST_F(Vector3DTest, normalizeTest) {
v1.normalize();
EXPECT_FLOAT_EQ(0.26726124, v1.getX());
EXPECT_FLOAT_EQ(0.53452247, v1.getY());
EXPECT_FLOAT_EQ(0.80178368, v1.getZ());
}
TEST_F(Vector3DTest, dotTest) {
EXPECT_FLOAT_EQ(26, v1.dot(v2));
}
TEST_F(Vector3DTest, crossTest) {
Vector3D v3 = v1.cross(v2);
EXPECT_FLOAT_EQ(-2, v3.getX());
EXPECT_FLOAT_EQ(4, v3.getY());
EXPECT_FLOAT_EQ(-2, v3.getZ());
}
TEST_F(Vector3DTest, lengthSquaredTest) {
EXPECT_FLOAT_EQ(14, v1.lengthSquared());
EXPECT_FLOAT_EQ(50, v2.lengthSquared());
}
TEST_F(Vector3DTest, opIndexTest) {
EXPECT_FLOAT_EQ(1, v1[0]);
EXPECT_FLOAT_EQ(2, v1[1]);
EXPECT_FLOAT_EQ(3, v1[2]);
EXPECT_ANY_THROW(v1[3]);
}
TEST_F(Vector3DTest, opVplusVTest) {
Vector3D v3 = v1 + v2;
EXPECT_FLOAT_EQ(4, v3.getX());
EXPECT_FLOAT_EQ(6, v3.getY());
EXPECT_FLOAT_EQ(8, v3.getZ());
}
TEST_F(Vector3DTest, opVminusVTest) {
Vector3D v3 = v1 - v2;
EXPECT_FLOAT_EQ(-2, v3.getX());
EXPECT_FLOAT_EQ(-2, v3.getY());
EXPECT_FLOAT_EQ(-2, v3.getZ());
}
TEST_F(Vector3DTest, opVmultVTest) {
Vector3D v3 = v1 * v2;
EXPECT_FLOAT_EQ(3, v3.getX());
EXPECT_FLOAT_EQ(8, v3.getY());
EXPECT_FLOAT_EQ(15, v3.getZ());
}
TEST_F(Vector3DTest, opCmultVTest) {
float c = 5;
Vector3D v3 = c * v1;
EXPECT_FLOAT_EQ(5, v3.getX());
EXPECT_FLOAT_EQ(10, v3.getY());
EXPECT_FLOAT_EQ(15, v3.getZ());
}
TEST_F(Vector3DTest, opVmultCTest) {
float c = 5;
Vector3D v3 = v1 * c;
EXPECT_FLOAT_EQ(5, v3.getX());
EXPECT_FLOAT_EQ(10, v3.getY());
EXPECT_FLOAT_EQ(15, v3.getZ());
}
TEST_F(Vector3DTest, opVdivVTest) {
Vector3D v3 = v1 / v2;
EXPECT_FLOAT_EQ(.33333334, v3.getX());
EXPECT_FLOAT_EQ(.5, v3.getY());
EXPECT_FLOAT_EQ(.6, v3.getZ());
}
TEST_F(Vector3DTest, opVdivCTest) {
float c = 5;
Vector3D v3 = v1 / c;
EXPECT_FLOAT_EQ(0.2, v3.getX());
EXPECT_FLOAT_EQ(0.4, v3.getY());
EXPECT_FLOAT_EQ(0.6, v3.getZ());
} | 23.596591 | 46 | 0.636889 | Tykky |
5d45142574586ca17f544ff5d7b0d5013588d719 | 2,187 | cpp | C++ | gui/nodescene.cpp | ousttrue/noged | 7485ea1c18c93dc845b3976a3176122775d7ace4 | [
"MIT"
] | null | null | null | gui/nodescene.cpp | ousttrue/noged | 7485ea1c18c93dc845b3976a3176122775d7ace4 | [
"MIT"
] | null | null | null | gui/nodescene.cpp | ousttrue/noged | 7485ea1c18c93dc845b3976a3176122775d7ace4 | [
"MIT"
] | null | null | null | #include "nodescene.h"
#include "nodedefinition.h"
#include "node.h"
#include "nodeslot/nodeslot.h"
namespace plugnode
{
NodeScene::NodeScene()
{
}
NodeScene::~NodeScene()
{
}
std::shared_ptr<Node> NodeScene::CreateNode(const std::shared_ptr<NodeDefinition> &definition, float x, float y)
{
auto node = std::make_shared<Node>(definition, std::array<float, 2>{x, y});
for (auto &slot : node->m_inslots)
{
slot->Owner = node;
slot->GetPin()->Slot = slot;
}
for (auto &slot : node->m_outslots)
{
slot->Owner = node;
slot->GetPin()->Slot = slot;
}
m_nodes.push_back(node);
return node;
}
void NodeScene::Remove(const std::shared_ptr<Node> &node)
{
auto found = std::find(m_nodes.begin(), m_nodes.end(), node);
if(found==m_nodes.end())
{
return;
}
m_nodes.erase(found);
}
std::shared_ptr<Node> NodeScene::GetFromId(int id) const
{
for (auto &node : m_nodes)
{
if (node->GetId() == id)
{
return node;
}
}
return nullptr;
}
int NodeScene::GetIndex(const std::shared_ptr<Node> &node) const
{
for (int i = 0; i < m_nodes.size(); ++i)
{
if (m_nodes[i] == node)
{
return i;
}
}
return -1;
}
void NodeScene::Link(const std::shared_ptr<Node> &src, int src_slot,
const std::shared_ptr<Node> &dst, int dst_slot)
{
dst->m_inslots[dst_slot]->Link(src->m_outslots[src_slot]);
}
std::shared_ptr<OutSlotBase> NodeScene::GetHoverOutSlot() const
{
for (auto &node : m_nodes)
{
for (auto &slot : node->m_outslots)
{
if (slot->IsHover)
{
return slot;
}
}
}
return nullptr;
}
std::shared_ptr<InSlotBase> NodeScene::GetHoverInSlot() const
{
for (auto &node : m_nodes)
{
for (auto &slot : node->m_inslots)
{
if (slot->IsHover)
{
return slot;
}
}
}
return nullptr;
}
} // namespace plugnode | 20.828571 | 113 | 0.525377 | ousttrue |
5d467ab3ed5e73c364e210676a97cc7d1a1fcbcc | 12,126 | cpp | C++ | src/PFsLib/PFsLib.cpp | KurtE/UsbMscFat | 8c4f312b229af5db17a4b43852469466e542e3d0 | [
"MIT"
] | 2 | 2022-02-04T20:37:37.000Z | 2022-03-01T02:41:14.000Z | src/PFsLib/PFsLib.cpp | KurtE/UsbMscFat | 8c4f312b229af5db17a4b43852469466e542e3d0 | [
"MIT"
] | 1 | 2021-03-10T01:35:04.000Z | 2021-03-10T01:35:04.000Z | src/PFsLib/PFsLib.cpp | KurtE/UsbMscFat | 8c4f312b229af5db17a4b43852469466e542e3d0 | [
"MIT"
] | 3 | 2021-03-09T01:06:44.000Z | 2021-03-29T12:21:20.000Z | #include "PFsLib.h"
//Set to 0 for debug info
#define DBG_Print 1
#if defined(DBG_Print)
#define DBGPrintf Serial.printf
#else
void inline DBGPrintf(...) {};
#endif
//------------------------------------------------------------------------------
#define PRINT_FORMAT_PROGRESS 1
#if !PRINT_FORMAT_PROGRESS
#define writeMsg(str)
#elif defined(__AVR__)
#define writeMsg(str) if (m_pr) m_pr->print(F(str))
#else // PRINT_FORMAT_PROGRESS
#define writeMsg(str) if (m_pr) m_pr->write(str)
#endif // PRINT_FORMAT_PROGRESS
//----------------------------------------------------------------
#define SECTORS_2GB 4194304 // (2^30 * 2) / 512
#define SECTORS_32GB 67108864 // (2^30 * 32) / 512
#define SECTORS_127GB 266338304 // (2^30 * 32) / 512
//uint8_t partVols_drive_index[10];
//=============================================================================
bool PFsLib::deletePartition(BlockDeviceInterface *blockDev, uint8_t part, print_t* pr, Stream &Serialx)
{
uint8_t sectorBuffer[512];
m_pr = pr;
MbrSector_t* mbr = reinterpret_cast<MbrSector_t*>(sectorBuffer);
if (!blockDev->readSector(0, sectorBuffer)) {
writeMsg("\nERROR: read MBR failed.\n");
return false;
}
if ((part < 1) || (part > 4)) {
m_pr->printf("ERROR: Invalid Partition: %u, only 1-4 are valid\n", part);
return false;
}
writeMsg("Warning this will delete the partition are you sure, continue: Y? ");
int ch;
//..... TODO CIN for READ ......
while ((ch = Serialx.read()) == -1) ;
if (ch != 'Y') {
writeMsg("Canceled");
return false;
}
DBGPrintf("MBR Before");
#if(DBG_Print)
dump_hexbytes(&mbr->part[0], 4*sizeof(MbrPart_t));
#endif
// Copy in the higher numer partitions;
for (--part; part < 3; part++) memcpy(&mbr->part[part], &mbr->part[part+1], sizeof(MbrPart_t));
// clear out the last one
memset(&mbr->part[part], 0, sizeof(MbrPart_t));
DBGPrintf("MBR After");
#if(DBG_Print)
dump_hexbytes(&mbr->part[0], 4*sizeof(MbrPart_t));
#endif
return blockDev->writeSector(0, sectorBuffer);
}
//===========================================================================
//----------------------------------------------------------------
#define SECTORS_2GB 4194304 // (2^30 * 2) / 512
#define SECTORS_32GB 67108864 // (2^30 * 32) / 512
#define SECTORS_127GB 266338304 // (2^30 * 32) / 512
//uint8_t partVols_drive_index[10];
//----------------------------------------------------------------
// Function to handle one MS Drive...
//msc[drive_index].usbDrive()
void PFsLib::InitializeDrive(BlockDeviceInterface *dev, uint8_t fat_type, print_t* pr)
{
uint8_t sectorBuffer[512];
m_dev = dev;
m_pr = pr;
//TODO: have to see if this is still valid
PFsVolume partVol;
/*
for (int ii = 0; ii < count_partVols; ii++) {
if (partVols_drive_index[ii] == drive_index) {
while (Serial.read() != -1) ;
writeMsg("Warning it appears like this drive has valid partitions, continue: Y? ");
int ch;
while ((ch = Serial.read()) == -1) ;
if (ch != 'Y') {
writeMsg("Canceled");
return;
}
break;
}
}
if (drive_index == LOGICAL_DRIVE_SDIO) {
dev = sd.card();
} else if (drive_index == LOGICAL_DRIVE_SDSPI) {
dev = sdSPI.card();
} else {
if (!msDrives[drive_index]) {
writeMsg("Not a valid USB drive");
return;
}
dev = (USBMSCDevice*)msc[drive_index].usbDrive();
}
*/
uint32_t sectorCount = dev->sectorCount();
m_pr->printf("sectorCount = %u, FatType: %x\n", sectorCount, fat_type);
// Serial.printf("Blocks: %u Size: %u\n", msDrives[drive_index].msCapacity.Blocks, msDrives[drive_index].msCapacity.BlockSize);
if ((fat_type == FAT_TYPE_EXFAT) && (sectorCount < 0X100000 )) fat_type = 0; // hack to handle later
if ((fat_type == FAT_TYPE_FAT16) && (sectorCount >= SECTORS_2GB )) fat_type = 0; // hack to handle later
if ((fat_type == FAT_TYPE_FAT32) && (sectorCount >= SECTORS_127GB )) fat_type = 0; // hack to handle later
if (fat_type == 0) {
// assume 512 byte blocks here..
if (sectorCount < SECTORS_2GB) fat_type = FAT_TYPE_FAT16;
else if (sectorCount < SECTORS_32GB) fat_type = FAT_TYPE_FAT32;
else fat_type = FAT_TYPE_EXFAT;
}
// lets generate a MBR for this type...
memset(sectorBuffer, 0, 512); // lets clear out the area.
MbrSector_t* mbr = reinterpret_cast<MbrSector_t*>(sectorBuffer);
setLe16(mbr->signature, MBR_SIGNATURE);
// Temporary until exfat is setup...
if (fat_type == FAT_TYPE_EXFAT) {
m_pr->println("TODO createPartition on ExFat");
m_dev->writeSector(0, sectorBuffer);
createExFatPartition(m_dev, 2048, sectorCount, sectorBuffer, &Serial);
return;
} else {
// Fat16/32
m_dev->writeSector(0, sectorBuffer);
createFatPartition(m_dev, fat_type, 2048, sectorCount, sectorBuffer, &Serial);
}
m_dev->syncDevice();
writeMsg("Format Done\r\n");
}
void PFsLib::formatter(PFsVolume &partVol, uint8_t fat_type, bool dump_drive, bool g_exfat_dump_changed_sectors, Stream &Serialx)
{
uint8_t sectorBuffer[512];
if (fat_type == 0) fat_type = partVol.fatType();
if (fat_type != FAT_TYPE_FAT12) {
//
uint8_t buffer[512];
MbrSector_t *mbr = (MbrSector_t *)buffer;
if (!partVol.blockDevice()->readSector(0, buffer)) return;
MbrPart_t *pt = &mbr->part[partVol.part() - 1];
uint32_t sector = getLe32(pt->relativeSectors);
// I am going to read in 24 sectors for EXFat..
uint8_t *bpb_area = (uint8_t*)malloc(512*24);
if (!bpb_area) {
Serialx.println("Unable to allocate dump memory");
return;
}
// Lets just read in the top 24 sectors;
uint8_t *sector_buffer = bpb_area;
for (uint32_t i = 0; i < 24; i++) {
partVol.blockDevice()->readSector(sector+i, sector_buffer);
sector_buffer += 512;
}
if (dump_drive) {
sector_buffer = bpb_area;
for (uint32_t i = 0; i < 12; i++) {
Serialx.printf("\nSector %u(%u)\n", i, sector);
dump_hexbytes(sector_buffer, 512);
sector++;
sector_buffer += 512;
}
for (uint32_t i = 12; i < 24; i++) {
Serialx.printf("\nSector %u(%u)\n", i, sector);
compare_dump_hexbytes(sector_buffer, sector_buffer - (512*12), 512);
sector++;
sector_buffer += 512;
}
} else {
if (fat_type != FAT_TYPE_EXFAT) {
PFsFatFormatter::format(partVol, fat_type, sectorBuffer, &Serialx);
} else {
Serialx.println("ExFatFormatter - WIP");
PFsExFatFormatter::format(partVol, sectorBuffer, &Serial);
if (g_exfat_dump_changed_sectors) {
// Now lets see what changed
uint8_t *sector_buffer = bpb_area;
for (uint32_t i = 0; i < 24; i++) {
partVol.blockDevice()->readSector(sector, buffer);
Serialx.printf("Sector %u(%u)\n", i, sector);
if (memcmp(buffer, sector_buffer, 512)) {
compare_dump_hexbytes(buffer, sector_buffer, 512);
Serialx.println();
}
sector++;
sector_buffer += 512;
}
}
}
}
free(bpb_area);
}
else
Serialx.println("Cannot format an invalid partition");
}
//================================================================================================
void PFsLib::print_partion_info(PFsVolume &partVol, Stream &Serialx)
{
uint8_t buffer[512];
MbrSector_t *mbr = (MbrSector_t *)buffer;
if (!partVol.blockDevice()->readSector(0, buffer)) return;
MbrPart_t *pt = &mbr->part[partVol.part() - 1];
uint32_t starting_sector = getLe32(pt->relativeSectors);
uint32_t sector_count = getLe32(pt->totalSectors);
Serialx.printf("Starting Sector: %u, Sector Count: %u\n", starting_sector, sector_count);
FatPartition *pfp = partVol.getFatVol();
if (pfp) {
Serialx.printf("fatType:%u\n", pfp->fatType());
Serialx.printf("bytesPerClusterShift:%u\n", pfp->bytesPerClusterShift());
Serialx.printf("bytesPerCluster:%u\n", pfp->bytesPerCluster());
Serialx.printf("bytesPerSector:%u\n", pfp->bytesPerSector());
Serialx.printf("bytesPerSectorShift:%u\n", pfp->bytesPerSectorShift());
Serialx.printf("sectorMask:%u\n", pfp->sectorMask());
Serialx.printf("sectorsPerCluster:%u\n", pfp->sectorsPerCluster());
Serialx.printf("sectorsPerFat:%u\n", pfp->sectorsPerFat());
Serialx.printf("clusterCount:%u\n", pfp->clusterCount());
Serialx.printf("dataStartSector:%u\n", pfp->dataStartSector());
Serialx.printf("fatStartSector:%u\n", pfp->fatStartSector());
Serialx.printf("rootDirEntryCount:%u\n", pfp->rootDirEntryCount());
Serialx.printf("rootDirStart:%u\n", pfp->rootDirStart());
}
}
uint32_t PFsLib::mbrDmp(BlockDeviceInterface *blockDev, uint32_t device_sector_count, Stream &Serialx) {
MbrSector_t mbr;
uint32_t next_free_sector = 8192; // Some inital value this is default for Win32 on SD...
// bool valid = true;
if (!blockDev->readSector(0, (uint8_t*)&mbr)) {
Serialx.print("\nread MBR failed.\n");
//errorPrint();
return (uint32_t)-1;
}
Serialx.print("\nmsc # Partition Table\n");
Serialx.print("\tpart,boot,bgnCHS[3],type,endCHS[3],start,length\n");
for (uint8_t ip = 1; ip < 5; ip++) {
MbrPart_t *pt = &mbr.part[ip - 1];
uint32_t starting_sector = getLe32(pt->relativeSectors);
uint32_t total_sector = getLe32(pt->totalSectors);
if (starting_sector > next_free_sector) {
Serialx.printf("\t < unused area starting at: %u length %u >\n", next_free_sector, starting_sector-next_free_sector);
}
switch (pt->type) {
case 4:
case 6:
case 0xe:
Serial.print("FAT16:\t");
break;
case 11:
case 12:
Serial.print("FAT32:\t");
break;
case 7:
Serial.print("exFAT:\t");
break;
case 0xf:
Serial.print("Extend:\t");
break;
case 0x83: Serial.print("ext2/3/4:\t"); break;
default:
Serialx.print("pt_#");
Serialx.print(pt->type);
Serialx.print(":\t");
break;
}
Serialx.print( int(ip)); Serial.print( ',');
Serialx.print(int(pt->boot), HEX); Serial.print( ',');
for (int i = 0; i < 3; i++ ) {
Serialx.print("0x"); Serial.print(int(pt->beginCHS[i]), HEX); Serial.print( ',');
}
Serialx.print("0x"); Serial.print(int(pt->type), HEX); Serial.print( ',');
for (int i = 0; i < 3; i++ ) {
Serialx.print("0x"); Serial.print(int(pt->endCHS[i]), HEX); Serial.print( ',');
}
Serialx.print(starting_sector, DEC); Serial.print(',');
Serialx.println(total_sector);
// Lets get the max of start+total
if (starting_sector && total_sector) next_free_sector = starting_sector + total_sector;
}
if ((device_sector_count != (uint32_t)-1) && (next_free_sector < device_sector_count)) {
Serialx.printf("\t < unused area starting at: %u length %u >\n", next_free_sector, device_sector_count-next_free_sector);
}
return next_free_sector;
}
//----------------------------------------------------------------
void PFsLib::dump_hexbytes(const void *ptr, int len)
{
if (ptr == NULL || len <= 0) return;
const uint8_t *p = (const uint8_t *)ptr;
while (len) {
for (uint8_t i = 0; i < 32; i++) {
if (i > len) break;
m_pr->printf("%02X ", p[i]);
}
m_pr->print(":");
for (uint8_t i = 0; i < 32; i++) {
if (i > len) break;
m_pr->printf("%c", ((p[i] >= ' ') && (p[i] <= '~')) ? p[i] : '.');
}
m_pr->println();
p += 32;
len -= 32;
}
}
void PFsLib::compare_dump_hexbytes(const void *ptr, const uint8_t *compare_buf, int len)
{
if (ptr == NULL || len <= 0) return;
const uint8_t *p = (const uint8_t *)ptr;
while (len) {
for (uint8_t i = 0; i < 32; i++) {
if (i > len) break;
Serial.printf("%c%02X", (p[i]==compare_buf[i])? ' ' : '*',p[i]);
}
Serial.print(":");
for (uint8_t i = 0; i < 32; i++) {
if (i > len) break;
Serial.printf("%c", ((p[i] >= ' ') && (p[i] <= '~')) ? p[i] : '.');
}
Serial.println();
p += 32;
compare_buf += 32;
len -= 32;
}
}
| 33.131148 | 129 | 0.593023 | KurtE |
5d497c015d93af44a3e46ebf723e9fe4ae0b9e98 | 18,773 | cc | C++ | zetasql/reference_impl/type_parameter_constraints_test.cc | yarri-oss/zetasql | c2240edf7f20df40c1c810b520b5a3aab9626a97 | [
"Apache-2.0"
] | 1,779 | 2019-04-23T19:41:49.000Z | 2022-03-31T18:53:18.000Z | zetasql/reference_impl/type_parameter_constraints_test.cc | yarri-oss/zetasql | c2240edf7f20df40c1c810b520b5a3aab9626a97 | [
"Apache-2.0"
] | 94 | 2019-05-22T00:30:05.000Z | 2022-03-31T06:26:09.000Z | zetasql/reference_impl/type_parameter_constraints_test.cc | yarri-oss/zetasql | c2240edf7f20df40c1c810b520b5a3aab9626a97 | [
"Apache-2.0"
] | 153 | 2019-04-23T22:45:41.000Z | 2022-02-18T05:44:10.000Z | //
// Copyright 2019 Google LLC
//
// 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 "zetasql/reference_impl/type_parameter_constraints.h"
#include "zetasql/base/testing/status_matchers.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
using ::zetasql::BigNumericValue;
using ::zetasql::NumericValue;
using testing::HasSubstr;
using zetasql_base::testing::IsOk;
using zetasql_base::testing::StatusIs;
namespace zetasql {
namespace {
// A string with UTF-8 length of 7 and a byte length of 14. String says "Google"
// in Perso-Arabic script with 4 letters and 3 vowel diacritics (hence a UTF-8
// length of 7). We use this string so that its UTF-8 length differs from its
// byte length.
constexpr absl::string_view TEST_STRING = u8"گُوگِلْ";
TEST(TypeParametersTest, StringWithMaxLengthOk) {
Value string_value = Value::String(TEST_STRING);
StringTypeParametersProto proto;
proto.set_max_length(7);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeStringTypeParameters(proto));
EXPECT_THAT(ApplyConstraints(type_params, PRODUCT_INTERNAL, string_value),
IsOk());
}
TEST(TypeParametersTest, StringWithMaxLengthFails) {
Value string_value = Value::String(TEST_STRING);
StringTypeParametersProto proto;
proto.set_max_length(6);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeStringTypeParameters(proto));
EXPECT_THAT(
ApplyConstraints(type_params, PRODUCT_INTERNAL, string_value),
StatusIs(absl::StatusCode::kOutOfRange,
HasSubstr("maximum length 6 but got a value with length 7")));
}
TEST(TypeParametersTest, BytesWithMaxLengthOk) {
Value bytes_value = Value::Bytes(TEST_STRING);
StringTypeParametersProto proto;
proto.set_max_length(14);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeStringTypeParameters(proto));
EXPECT_THAT(ApplyConstraints(type_params, PRODUCT_INTERNAL, bytes_value),
IsOk());
}
TEST(TypeParametersTest, BytesWithMaxLengthFails) {
Value bytes_value = Value::Bytes(TEST_STRING);
StringTypeParametersProto proto;
proto.set_max_length(13);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeStringTypeParameters(proto));
EXPECT_THAT(
ApplyConstraints(type_params, PRODUCT_INTERNAL, bytes_value),
StatusIs(absl::StatusCode::kOutOfRange,
HasSubstr("maximum length 13 but got a value with length 14")));
}
TEST(TypeParametersTest, NumericEveryValidIntegerPrecisionAndScaleSucceeds) {
Value numeric_value = Value::Numeric(NumericValue(1));
for (int scale = 0; scale <= NumericValue::kMaxFractionalDigits; scale++) {
int max_precision = NumericValue::kMaxIntegerDigits + scale;
for (int precision = 1 + scale; precision <= max_precision; precision++) {
NumericTypeParametersProto proto;
proto.set_precision(precision);
proto.set_scale(scale);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
EXPECT_THAT(
ApplyConstraints(type_params, PRODUCT_INTERNAL, numeric_value),
IsOk());
}
}
}
TEST(TypeParametersTest, NumericEveryValidFractionalScaleSucceeds) {
Value numeric_value = Value::Numeric(NumericValue::FromString("0.1").value());
for (int scale = 1; scale <= NumericValue::kMaxFractionalDigits; scale++) {
NumericTypeParametersProto proto;
proto.set_precision(scale);
proto.set_scale(scale);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
EXPECT_THAT(ApplyConstraints(type_params, PRODUCT_INTERNAL, numeric_value),
IsOk());
}
}
TEST(TypeParametersTest, NumericPrecisionScaleFails) {
Value numeric_value = Value::Numeric(NumericValue(10000));
NumericTypeParametersProto proto;
proto.set_precision(4);
proto.set_scale(0);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
EXPECT_THAT(
ApplyConstraints(type_params, PRODUCT_INTERNAL, numeric_value),
StatusIs(
absl::StatusCode::kOutOfRange,
HasSubstr(
"precision 4 and scale 0 but got a value that is not in range")));
}
TEST(TypeParametersTest, NumericPrecisionScaleRoundsOk) {
Value numeric_value =
Value::Numeric(NumericValue::FromString("999999.994999999").value());
NumericTypeParametersProto proto;
proto.set_precision(8);
proto.set_scale(2);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
ZETASQL_ASSERT_OK(ApplyConstraints(type_params, PRODUCT_INTERNAL, numeric_value));
EXPECT_EQ(numeric_value.numeric_value(),
NumericValue::FromString("999999.99").value());
}
TEST(TypeParametersTest, NumericPrecisionScaleRoundFails) {
Value numeric_value =
Value::Numeric(NumericValue::FromString("999999.995").value());
NumericTypeParametersProto proto;
proto.set_precision(8);
proto.set_scale(2);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
EXPECT_THAT(
ApplyConstraints(type_params, PRODUCT_INTERNAL, numeric_value),
StatusIs(
absl::StatusCode::kOutOfRange,
HasSubstr(
"precision 8 and scale 2 but got a value that is not in range")));
}
TEST(TypeParametersTest, NumericPrecisionScaleMaxOverflowFails) {
Value numeric_value = Value::Numeric(
NumericValue::FromString("99999999999999999999999999999.999999999")
.value());
NumericTypeParametersProto proto;
proto.set_precision(31);
proto.set_scale(2);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
EXPECT_THAT(
ApplyConstraints(type_params, PRODUCT_INTERNAL, numeric_value),
StatusIs(absl::StatusCode::kOutOfRange, HasSubstr("numeric overflow")));
}
TEST(TypeParametersTest, NumericInvalidPrecisionScaleFails) {
Value numeric_value = Value::Numeric(NumericValue(1));
NumericTypeParametersProto proto;
proto.set_precision(35);
proto.set_scale(5);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
EXPECT_THAT(ApplyConstraints(type_params, PRODUCT_INTERNAL, numeric_value),
StatusIs(absl::StatusCode::kInternal,
HasSubstr("In NUMERIC(P, 5), P must be between 5 and "
"34, actual precision: 35")));
}
TEST(TypeParametersTest, BigNumericEveryValidIntegerPrecisionAndScaleSucceeds) {
Value bignumeric_value = Value::BigNumeric(BigNumericValue(1));
for (int scale = 0; scale <= BigNumericValue::kMaxFractionalDigits; scale++) {
int max_precision = BigNumericValue::kMaxIntegerDigits + scale;
for (int precision = 1 + scale; precision < max_precision; precision++) {
NumericTypeParametersProto proto;
proto.set_precision(precision);
proto.set_scale(scale);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
EXPECT_THAT(
ApplyConstraints(type_params, PRODUCT_INTERNAL, bignumeric_value),
IsOk());
}
}
}
TEST(TypeParametersTest, BigNumericEveryValidFractionalScaleSucceeds) {
Value bignumeric_value =
Value::BigNumeric(BigNumericValue::FromString("0.1").value());
for (int scale = 1; scale <= BigNumericValue::kMaxFractionalDigits; scale++) {
NumericTypeParametersProto proto;
proto.set_precision(scale);
proto.set_scale(scale);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
EXPECT_THAT(
ApplyConstraints(type_params, PRODUCT_INTERNAL, bignumeric_value),
IsOk());
}
}
TEST(TypeParametersTest, BigNumericPrecisionScaleFails) {
Value bignumeric_value = Value::BigNumeric(BigNumericValue(10000));
NumericTypeParametersProto proto;
proto.set_precision(4);
proto.set_scale(0);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
EXPECT_THAT(
ApplyConstraints(type_params, PRODUCT_INTERNAL, bignumeric_value),
StatusIs(
absl::StatusCode::kOutOfRange,
HasSubstr(
"precision 4 and scale 0 but got a value that is not in range")));
}
TEST(TypeParametersTest, BigNumericMaxPrecisionFails) {
Value bignumeric_value =
Value::BigNumeric(BigNumericValue::FromString(
"312345678901234567890123456789012345678.987654321")
.value());
NumericTypeParametersProto proto;
proto.set_precision(76);
proto.set_scale(38);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
EXPECT_THAT(ApplyConstraints(type_params, PRODUCT_INTERNAL, bignumeric_value),
StatusIs(absl::StatusCode::kOutOfRange,
HasSubstr("precision 76 and scale 38 but got a value "
"that is not in range")));
}
TEST(TypeParametersTest, BigNumericMaxLiteralSucceeds) {
Value bignumeric_value =
Value::BigNumeric(BigNumericValue::FromString(
"312345678901234567890123456789012345678.987654321")
.value());
NumericTypeParametersProto proto;
proto.set_is_max_precision(true);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
ZETASQL_ASSERT_OK(ApplyConstraints(type_params, PRODUCT_INTERNAL, bignumeric_value));
EXPECT_EQ(bignumeric_value.bignumeric_value(),
BigNumericValue::FromString(
"312345678901234567890123456789012345678.987654321")
.value());
}
TEST(TypeParametersTest, BigNumericMaxLiteralRoundingSucceeds) {
Value bignumeric_value =
Value::BigNumeric(BigNumericValue::FromString(
"312345678901234567890123456789012345678.987654321")
.value());
NumericTypeParametersProto proto;
proto.set_is_max_precision(true);
proto.set_scale(4);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
ZETASQL_ASSERT_OK(ApplyConstraints(type_params, PRODUCT_INTERNAL, bignumeric_value));
EXPECT_EQ(bignumeric_value.bignumeric_value(),
BigNumericValue::FromString(
"312345678901234567890123456789012345678.9877")
.value());
}
TEST(TypeParametersTest, BigNumericMaxLiteralMaxValueSucceeds) {
Value bignumeric_value = Value::BigNumeric(BigNumericValue::MaxValue());
NumericTypeParametersProto proto;
proto.set_is_max_precision(true);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
ZETASQL_ASSERT_OK(ApplyConstraints(type_params, PRODUCT_INTERNAL, bignumeric_value));
EXPECT_EQ(bignumeric_value.bignumeric_value(), BigNumericValue::MaxValue());
}
TEST(TypeParametersTest, BigNumericPrecisionScaleRoundsOk) {
Value bignumeric_value = Value::BigNumeric(
BigNumericValue::FromString("999999.994999999").value());
NumericTypeParametersProto proto;
proto.set_precision(8);
proto.set_scale(2);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
ZETASQL_ASSERT_OK(ApplyConstraints(type_params, PRODUCT_INTERNAL, bignumeric_value));
EXPECT_EQ(bignumeric_value.bignumeric_value(),
BigNumericValue::FromString("999999.99").value());
}
TEST(TypeParametersTest, BigNumericPrecisionScaleRoundFails) {
Value bignumeric_value =
Value::BigNumeric(BigNumericValue::FromString("999999.995").value());
NumericTypeParametersProto proto;
proto.set_precision(8);
proto.set_scale(2);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
EXPECT_THAT(
ApplyConstraints(type_params, PRODUCT_INTERNAL, bignumeric_value),
StatusIs(
absl::StatusCode::kOutOfRange,
HasSubstr(
"precision 8 and scale 2 but got a value that is not in range")));
}
TEST(TypeParametersTest, BigNumericInvalidPrecisionScaleFails) {
Value bignumeric_value = Value::BigNumeric(BigNumericValue(1));
NumericTypeParametersProto proto;
proto.set_precision(55);
proto.set_scale(5);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters type_params,
TypeParameters::MakeNumericTypeParameters(proto));
EXPECT_THAT(ApplyConstraints(type_params, PRODUCT_INTERNAL, bignumeric_value),
StatusIs(absl::StatusCode::kInternal,
HasSubstr("In BIGNUMERIC(P, 5), P must be between 5 and "
"43, actual precision: 55")));
}
TEST(TypeParametersTest, ArrayWithTypeParametersOk) {
// Create string array.
TypeFactory type_factory;
const Type* numeric_array = nullptr;
ZETASQL_ASSERT_OK(
type_factory.MakeArrayType(type_factory.get_numeric(), &numeric_array));
Value array_value =
Value::Array(numeric_array->AsArray(),
{Value::Numeric(NumericValue::FromString("123.987").value()),
Value::Numeric(NumericValue(2))});
// Create array type parameters.
std::vector<TypeParameters> child_list;
NumericTypeParametersProto proto;
proto.set_precision(10);
proto.set_scale(2);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters numeric_child,
TypeParameters::MakeNumericTypeParameters(proto));
child_list.push_back(numeric_child);
TypeParameters array_type_params =
TypeParameters::MakeTypeParametersWithChildList(child_list);
EXPECT_THAT(
ApplyConstraints(array_type_params, PRODUCT_INTERNAL, array_value),
IsOk());
EXPECT_EQ(array_value.element(0).numeric_value(),
NumericValue::FromString("123.99").value());
}
TEST(TypeParametersTest, ArrayWithTypeParametersFails) {
// Create string array.
TypeFactory type_factory;
const Type* numeric_array = nullptr;
ZETASQL_ASSERT_OK(
type_factory.MakeArrayType(type_factory.get_numeric(), &numeric_array));
Value array_value =
Value::Array(numeric_array->AsArray(),
{Value::Numeric(NumericValue::FromString("123.987").value()),
Value::Numeric(NumericValue(2))});
// Create array type parameters.
std::vector<TypeParameters> child_list;
NumericTypeParametersProto proto;
proto.set_precision(3);
proto.set_scale(2);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters numeric_child,
TypeParameters::MakeNumericTypeParameters(proto));
child_list.push_back(numeric_child);
TypeParameters array_type_params =
TypeParameters::MakeTypeParametersWithChildList(child_list);
EXPECT_THAT(
ApplyConstraints(array_type_params, PRODUCT_INTERNAL, array_value),
StatusIs(
absl::StatusCode::kOutOfRange,
HasSubstr(
"precision 3 and scale 2 but got a value that is not in range")));
}
TEST(TypeParametersTest, StructWithTypeParametersOk) {
// Create struct value.
TypeFactory type_factory;
const Type* struct_type = nullptr;
ZETASQL_ASSERT_OK(
type_factory.MakeStructType({{"string", type_factory.get_string()},
{"numeric", type_factory.get_numeric()}},
&struct_type));
Value struct_value =
Value::Struct(struct_type->AsStruct(),
{Value::String("hello"),
Value::Numeric(NumericValue::FromString("1.67").value())});
// Create struct type parameters.
std::vector<TypeParameters> child_list;
NumericTypeParametersProto proto;
proto.set_precision(2);
proto.set_scale(1);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters numeric_child,
TypeParameters::MakeNumericTypeParameters(proto));
child_list.push_back(TypeParameters());
child_list.push_back(numeric_child);
TypeParameters struct_type_params =
TypeParameters::MakeTypeParametersWithChildList(child_list);
EXPECT_THAT(
ApplyConstraints(struct_type_params, PRODUCT_INTERNAL, struct_value),
IsOk());
EXPECT_EQ(struct_value.field(1).numeric_value(),
NumericValue::FromString("1.7").value());
}
TEST(TypeParametersTest, StructWithTypeParametersFails) {
// Create struct value.
TypeFactory type_factory;
const Type* struct_type = nullptr;
ZETASQL_ASSERT_OK(
type_factory.MakeStructType({{"string", type_factory.get_string()},
{"numeric", type_factory.get_numeric()}},
&struct_type));
Value struct_value =
Value::Struct(struct_type->AsStruct(),
{Value::String("hello"),
Value::Numeric(NumericValue::FromString("1.67").value())});
// Create struct type parameters.
std::vector<TypeParameters> child_list;
NumericTypeParametersProto proto;
proto.set_precision(2);
proto.set_scale(2);
ZETASQL_ASSERT_OK_AND_ASSIGN(TypeParameters numeric_child,
TypeParameters::MakeNumericTypeParameters(proto));
child_list.push_back(TypeParameters());
child_list.push_back(numeric_child);
TypeParameters struct_type_params =
TypeParameters::MakeTypeParametersWithChildList(child_list);
EXPECT_THAT(
ApplyConstraints(struct_type_params, PRODUCT_INTERNAL, struct_value),
StatusIs(
absl::StatusCode::kOutOfRange,
HasSubstr(
"precision 2 and scale 2 but got a value that is not in range")));
}
} // namespace
} // namespace zetasql
| 41.078775 | 87 | 0.714484 | yarri-oss |
5d4b3af8036e4e9bcbfac2a2acb41882b3699e47 | 4,042 | cc | C++ | logga/fitness.cc | wahibium/KFF | 609e5afac8a9477dd1af31eacadbcd5b61530113 | [
"MIT"
] | 11 | 2015-06-08T22:16:47.000Z | 2022-03-19T15:11:14.000Z | logga/fitness.cc | wahibium/KFF | 609e5afac8a9477dd1af31eacadbcd5b61530113 | [
"MIT"
] | null | null | null | logga/fitness.cc | wahibium/KFF | 609e5afac8a9477dd1af31eacadbcd5b61530113 | [
"MIT"
] | 4 | 2015-06-12T21:24:47.000Z | 2021-04-23T09:58:33.000Z | // ================================================================================
// ================================================================================
//
// Instructions for adding a new fitness function:
// ------------------------------------------------
//
// 1. create a function with the same input parameters as other fitness functions
// defined in this file (e.g., onemax) that returns the value of the fitness
// given a binary chromosome of a particular length (sent as input parameters
// to the fitness)
//
// 2. put the function definition in the fitness.h header file (look at onemax
// as an example)
//
// 3. increase the counter numFitness and add a structure to the array of the
// fitness descriptions fitnessDesc below. For compatibility of recent input
// files, put it at the end of this array, in order not to change the numbers
// of already defined and used functions. The structure has the following items
// (in this order):
// a) a string description of the function (informative in output data files)
// b) a pointer to the function (simple "&" followed by the name of a function)
// c) a pointer to the function that returns true if an input solution is
// globally optimal and false if this is not the case. If such function is
// not available, just use NULL instead. The algorithm will understand...
// d) a pointer to the function for initialization of the particular fitness
// function (not used in any of these and probably not necessary for most
// of the functions, but in case reading input file would be necessary
// or so, it might be used in this way). Use NULL if there is no such
// function
// e) a pointer to the "done" function, called when the fitness is not to be
// used anymore, in case some memory is allocated in its initialization;
// here it can be freed. Use NULL if there is no need for such function
//
// 4. the function will be assigned a number equal to its ordering number in the
// array of function descriptions fitnessDesc minus 1 (the functions are
// assigned numbers consequently starting at 0); so its number will be equal
// to the number of fitness definitions minus 1 at the time it is added. Its
// description in output files will be the same as the description string
// (see 3a)
//
// ================================================================================
// ================================================================================
#include <stdio.h>
#include <stdlib.h>
#include "chromosome.h"
#include "fitness.h"
#include "gga.h"
#define numFitness 3
static Fitness fitnessDesc[numFitness] = {
{"Roofline Model",&roofline,&bestSolution,NULL,NULL},
{"Simple Model",&simplemodel,&bestSolution,NULL,NULL},
{"Complex Model",&complexmodel,&bestSolution,NULL,NULL},
};
Fitness *fitness;
long fitnessCalls_;
char BestSolution(Chromosome *chromosome)
{
register int i;
for (i=0; (i<n)&&(x[i]==1); i++);
return (i==n);
}
int SetFitness(int n)
{
if ((n>=0) && (n<numFitness))
fitness = &(fitnessDesc[n]);
else
{
fprintf(stderr,"ERROR: Specified fitness function doesn't exist (%u)!",n);
exit(-1);
}
return 0;
}
char* GetFitnessDesc(int n)
{
return fitnessDesc[n].description;
}
int InitializeFitness(GGAParams *ggaParams)
{
if (fitness->init)
return fitness->init(ggaParams);
return 0;
}
int DoneFitness(GGAParams *ggaParams)
{
if (fitness->done)
return fitness->done(ggaParams);
return 0;
}
float GetFitnessValue(Chromosome *chromosome)
{
fitnessCalled();
return fitness->fitness(x,n);
}
int IsBestDefined()
{
return (int) (fitness->isBest!=NULL);
}
int IsOptimal(char *x, int n)
{
return fitness->isBest(x,n);
}
int ResetFitnessCalls(void)
{
return (int) (fitnessCalls_=0);
}
long FitnessCalled(void)
{
return fitnessCalls_++;
}
long GetFitnessCalls(void)
{
return fitnessCalls_;
}
| 28.069444 | 84 | 0.621969 | wahibium |
5d4b625ade6f29c9ea58c410831b8a18a85053f9 | 896 | cpp | C++ | problemsets/UVA/11463.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | problemsets/UVA/11463.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | problemsets/UVA/11463.cpp | juarezpaulino/coderemite | a4649d3f3a89d234457032d14a6646b3af339ac1 | [
"Apache-2.0"
] | null | null | null | /**
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
*/
#include <cstdio>
#include <algorithm>
using namespace std;
int G[110][110];
int main() {
int T;
scanf("%d", &T);
for (int t = 1; t <= T; t++) {
printf("Case %d: ", t);
int N, M;
scanf("%d %d", &N, &M);
for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) G[i][j] = (i==j) ? 0 : (1<<29)-(i*N+j);
while (M--) {
int u, v;
scanf("%d %d", &u, &v);
G[u][v] = G[v][u] = 1;
}
for (int k = 0; k < N; k++) for (int i = 0; i < N; i++) for (int j = 0; j < N; j++)
G[i][j] = min(G[i][j],G[i][k]+G[k][j]);
int u, v;
scanf("%d %d", &u, &v);
int ret = -1;
for (int i = 0; i < N; i++) ret = max(ret,G[u][i]+G[i][v]);
printf("%d\n", ret);
}
return 0;
}
| 22.974359 | 103 | 0.379464 | juarezpaulino |
5d501887720db7190422ed846fed3fa07288f759 | 1,712 | cpp | C++ | querier/MergedSeriesSet.cpp | naivewong/timeunion | 8070492d2c6a2d68175e7d026c27b858c2aec8e6 | [
"Apache-2.0"
] | null | null | null | querier/MergedSeriesSet.cpp | naivewong/timeunion | 8070492d2c6a2d68175e7d026c27b858c2aec8e6 | [
"Apache-2.0"
] | null | null | null | querier/MergedSeriesSet.cpp | naivewong/timeunion | 8070492d2c6a2d68175e7d026c27b858c2aec8e6 | [
"Apache-2.0"
] | null | null | null | #include "querier/MergedSeriesSet.hpp"
#include "base/Logging.hpp"
#include "querier/ChainSeries.hpp"
namespace tsdb {
namespace querier {
// View it as a collections of blocks sorted by time.
MergedSeriesSet::MergedSeriesSet(const std::shared_ptr<SeriesSets> &ss)
: ss(ss), series(new Series()), err_(false) {
// To move one step for each SeriesInterface.
ss->next();
if (ss->empty()) {
// LOG_DEBUG << "no next";
err_ = true;
}
}
bool MergedSeriesSet::next_helper() const {
// To move one step for the former SeriesInterface s.
ss->next(id);
series->clear();
id.clear();
if (ss->empty()) {
err_ = true;
return false;
}
id.push_back(0);
for (int i = 1; i < ss->size(); i++) {
int cmp = label::lbs_compare(ss->at(i)->at()->labels(),
ss->at(0)->at()->labels());
if (cmp < 0) {
// series->clear();
id.clear();
// series->push_back((*ss)[i]->at());
id.push_back(i);
} else if (cmp == 0) {
// series->push_back((*ss)[i]->at());
id.push_back(i);
}
}
for (int i : id) series->push_back(ss->at(i)->at());
return true;
}
bool MergedSeriesSet::next() const {
if (err_) return false;
return next_helper();
}
std::unique_ptr<SeriesInterface> MergedSeriesSet::at() {
if (id.empty()) return nullptr;
// else if (id.size() == 1)
// return (*series)[0];
else {
// LOG_INFO << "Create ChainSeries(same lset in several SeriesSetInterface),
// num of SeriesInterface: " << series->size();
return std::unique_ptr<SeriesInterface>(new ChainSeries(series));
}
}
bool MergedSeriesSet::error() const { return err_; }
} // namespace querier
} // namespace tsdb | 24.811594 | 80 | 0.599883 | naivewong |
5d53daf83387b633254466c89b432cdcb386f0ac | 1,225 | cpp | C++ | grammar/src/numExpression.cpp | troeggla/blocky | ef2e32369065f7aff7c7c807712c67d9eb25f75d | [
"BSD-2-Clause"
] | null | null | null | grammar/src/numExpression.cpp | troeggla/blocky | ef2e32369065f7aff7c7c807712c67d9eb25f75d | [
"BSD-2-Clause"
] | null | null | null | grammar/src/numExpression.cpp | troeggla/blocky | ef2e32369065f7aff7c7c807712c67d9eb25f75d | [
"BSD-2-Clause"
] | null | null | null | #include "numExpression.hpp"
NumExpression::NumExpression(double value) {
this->value = new double;
*(this->value) = value;
}
NumExpression::NumExpression(BlockScope* scope, std::string var) : scope(scope), var(var) {
}
NumExpression::NumExpression(NumExpression *ex1, NumExpression *ex2, char op) : ex1(ex1), ex2(ex2), op(op) {
}
NumExpression::~NumExpression() {
delete value;
delete ex1;
delete ex2;
}
std::string NumExpression::getType() {
return "numerical";
}
double NumExpression::evaluate() {
if (this->value != 0) {
return *value;
} else if (scope != 0) {
return scope->get_var(var);
} else {
double val1 = ex1->evaluate();
double val2 = ex2->evaluate();
switch (op) {
case '+':
return ex1->evaluate() + ex2->evaluate();
case '-':
return ex1->evaluate() - ex2->evaluate();
case '*':
return ex1->evaluate() * ex2->evaluate();
case '/':
return ex1->evaluate() / ex2->evaluate();
case '^':
return pow(ex1->evaluate(), ex2->evaluate());
case '%':
return (int)ex1->evaluate() % (int)ex2->evaluate();
}
}
}
| 25 | 108 | 0.553469 | troeggla |
5d5b3ea3dbbe0076ad91cf27ec0691ef0f3b853a | 19,461 | hpp | C++ | Contrib-Inspur/bmcweb/redfish-core/lib/update_service.hpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 5 | 2019-11-11T07:57:26.000Z | 2022-03-28T08:26:53.000Z | redfish-core/lib/update_service.hpp | inspur-bmc/rmcweb | ec8ce2a09b851ff5da59b0b9faba5c035c5e0faf | [
"Apache-2.0"
] | 3 | 2019-09-05T21:47:07.000Z | 2019-09-17T18:10:45.000Z | Contrib-Inspur/bmcweb/redfish-core/lib/update_service.hpp | opencomputeproject/Rack-Manager | e1a61d3eeeba0ff655fe9c1301e8b510d9b2122a | [
"MIT"
] | 11 | 2019-07-20T00:16:32.000Z | 2022-01-11T14:17:48.000Z | /*
// Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#pragma once
#include "node.hpp"
#include <boost/container/flat_map.hpp>
#include <variant>
namespace redfish
{
static std::unique_ptr<sdbusplus::bus::match::match> fwUpdateMatcher;
class UpdateService : public Node
{
public:
UpdateService(CrowApp &app) : Node(app, "/redfish/v1/UpdateService/")
{
entityPrivileges = {
{boost::beast::http::verb::get, {{"Login"}}},
{boost::beast::http::verb::head, {{"Login"}}},
{boost::beast::http::verb::patch, {{"ConfigureComponents"}}},
{boost::beast::http::verb::put, {{"ConfigureComponents"}}},
{boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
{boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
}
private:
void doGet(crow::Response &res, const crow::Request &req,
const std::vector<std::string> ¶ms) override
{
res.jsonValue["@odata.type"] = "#UpdateService.v1_2_0.UpdateService";
res.jsonValue["@odata.id"] = "/redfish/v1/UpdateService";
res.jsonValue["@odata.context"] =
"/redfish/v1/$metadata#UpdateService.UpdateService";
res.jsonValue["Id"] = "UpdateService";
res.jsonValue["Description"] = "Service for Software Update";
res.jsonValue["Name"] = "Update Service";
res.jsonValue["HttpPushUri"] = "/redfish/v1/UpdateService";
// UpdateService cannot be disabled
res.jsonValue["ServiceEnabled"] = true;
res.jsonValue["FirmwareInventory"] = {
{"@odata.id", "/redfish/v1/UpdateService/FirmwareInventory"}};
res.end();
}
static void activateImage(const std::string &objPath)
{
crow::connections::systemBus->async_method_call(
[objPath](const boost::system::error_code error_code) {
if (error_code)
{
BMCWEB_LOG_DEBUG << "error_code = " << error_code;
BMCWEB_LOG_DEBUG << "error msg = " << error_code.message();
}
},
"xyz.openbmc_project.Software.BMC.Updater", objPath,
"org.freedesktop.DBus.Properties", "Set",
"xyz.openbmc_project.Software.Activation", "RequestedActivation",
std::variant<std::string>(
"xyz.openbmc_project.Software.Activation.RequestedActivations."
"Active"));
}
void doPost(crow::Response &res, const crow::Request &req,
const std::vector<std::string> ¶ms) override
{
BMCWEB_LOG_DEBUG << "doPost...";
// Only allow one FW update at a time
if (fwUpdateMatcher != nullptr)
{
res.addHeader("Retry-After", "30");
messages::serviceTemporarilyUnavailable(res, "3");
res.end();
return;
}
// Make this const static so it survives outside this method
static boost::asio::deadline_timer timeout(
*req.ioService, boost::posix_time::seconds(5));
timeout.expires_from_now(boost::posix_time::seconds(5));
timeout.async_wait([&res](const boost::system::error_code &ec) {
fwUpdateMatcher = nullptr;
if (ec == boost::asio::error::operation_aborted)
{
// expected, we were canceled before the timer completed.
return;
}
BMCWEB_LOG_ERROR
<< "Timed out waiting for firmware object being created";
BMCWEB_LOG_ERROR
<< "FW image may has already been uploaded to server";
if (ec)
{
BMCWEB_LOG_ERROR << "Async_wait failed" << ec;
return;
}
redfish::messages::internalError(res);
res.end();
});
auto callback = [&res](sdbusplus::message::message &m) {
BMCWEB_LOG_DEBUG << "Match fired";
bool flag = false;
if (m.is_method_error())
{
BMCWEB_LOG_DEBUG << "Dbus method error!!!";
res.end();
return;
}
std::vector<std::pair<
std::string,
std::vector<std::pair<std::string, std::variant<std::string>>>>>
interfacesProperties;
sdbusplus::message::object_path objPath;
m.read(objPath, interfacesProperties); // Read in the object path
// that was just created
// std::string str_objpath = objPath.str; // keep a copy for
// constructing response message
BMCWEB_LOG_DEBUG << "obj path = " << objPath.str; // str_objpath;
for (auto &interface : interfacesProperties)
{
BMCWEB_LOG_DEBUG << "interface = " << interface.first;
if (interface.first ==
"xyz.openbmc_project.Software.Activation")
{
// cancel timer only when
// xyz.openbmc_project.Software.Activation interface is
// added
boost::system::error_code ec;
timeout.cancel(ec);
if (ec)
{
BMCWEB_LOG_ERROR << "error canceling timer " << ec;
}
UpdateService::activateImage(objPath.str); // str_objpath);
redfish::messages::success(res);
BMCWEB_LOG_DEBUG << "ending response";
res.end();
fwUpdateMatcher = nullptr;
}
}
};
fwUpdateMatcher = std::make_unique<sdbusplus::bus::match::match>(
*crow::connections::systemBus,
"interface='org.freedesktop.DBus.ObjectManager',type='signal',"
"member='InterfacesAdded',path='/xyz/openbmc_project/software'",
callback);
std::string filepath(
"/tmp/images/" +
boost::uuids::to_string(boost::uuids::random_generator()()));
BMCWEB_LOG_DEBUG << "Writing file to " << filepath;
std::ofstream out(filepath, std::ofstream::out | std::ofstream::binary |
std::ofstream::trunc);
out << req.body;
out.close();
BMCWEB_LOG_DEBUG << "file upload complete!!";
}
};
class SoftwareInventoryCollection : public Node
{
public:
template <typename CrowApp>
SoftwareInventoryCollection(CrowApp &app) :
Node(app, "/redfish/v1/UpdateService/FirmwareInventory/")
{
entityPrivileges = {
{boost::beast::http::verb::get, {{"Login"}}},
{boost::beast::http::verb::head, {{"Login"}}},
{boost::beast::http::verb::patch, {{"ConfigureComponents"}}},
{boost::beast::http::verb::put, {{"ConfigureComponents"}}},
{boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
{boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
}
private:
void doGet(crow::Response &res, const crow::Request &req,
const std::vector<std::string> ¶ms) override
{
std::shared_ptr<AsyncResp> asyncResp = std::make_shared<AsyncResp>(res);
res.jsonValue["@odata.type"] =
"#SoftwareInventoryCollection.SoftwareInventoryCollection";
res.jsonValue["@odata.id"] =
"/redfish/v1/UpdateService/FirmwareInventory";
res.jsonValue["@odata.context"] =
"/redfish/v1/"
"$metadata#SoftwareInventoryCollection.SoftwareInventoryCollection";
res.jsonValue["Name"] = "Software Inventory Collection";
crow::connections::systemBus->async_method_call(
[asyncResp](
const boost::system::error_code ec,
const std::vector<std::pair<
std::string, std::vector<std::pair<
std::string, std::vector<std::string>>>>>
&subtree) {
if (ec)
{
messages::internalError(asyncResp->res);
return;
}
asyncResp->res.jsonValue["Members"] = nlohmann::json::array();
asyncResp->res.jsonValue["Members@odata.count"] = 0;
for (auto &obj : subtree)
{
const std::vector<
std::pair<std::string, std::vector<std::string>>>
&connections = obj.second;
// if can't parse fw id then return
std::size_t idPos;
if ((idPos = obj.first.rfind("/")) == std::string::npos)
{
messages::internalError(asyncResp->res);
BMCWEB_LOG_DEBUG << "Can't parse firmware ID!!";
return;
}
std::string swId = obj.first.substr(idPos + 1);
for (auto &conn : connections)
{
const std::string &connectionName = conn.first;
BMCWEB_LOG_DEBUG << "connectionName = "
<< connectionName;
BMCWEB_LOG_DEBUG << "obj.first = " << obj.first;
crow::connections::systemBus->async_method_call(
[asyncResp,
swId](const boost::system::error_code error_code,
const VariantType &activation) {
BMCWEB_LOG_DEBUG
<< "safe returned in lambda function";
if (error_code)
{
messages::internalError(asyncResp->res);
return;
}
const std::string *swActivationStatus =
std::get_if<std::string>(&activation);
if (swActivationStatus == nullptr)
{
messages::internalError(asyncResp->res);
return;
}
if (swActivationStatus != nullptr &&
*swActivationStatus !=
"xyz.openbmc_project.Software."
"Activation."
"Activations.Active")
{
// The activation status of this software is
// not currently active, so does not need to
// be listed in the response
return;
}
nlohmann::json &members =
asyncResp->res.jsonValue["Members"];
members.push_back(
{{"@odata.id", "/redfish/v1/UpdateService/"
"FirmwareInventory/" +
swId}});
asyncResp->res
.jsonValue["Members@odata.count"] =
members.size();
},
connectionName, obj.first,
"org.freedesktop.DBus.Properties", "Get",
"xyz.openbmc_project.Software.Activation",
"Activation");
}
}
},
"xyz.openbmc_project.ObjectMapper",
"/xyz/openbmc_project/object_mapper",
"xyz.openbmc_project.ObjectMapper", "GetSubTree",
"/xyz/openbmc_project/software", int32_t(1),
std::array<const char *, 1>{
"xyz.openbmc_project.Software.Version"});
}
};
class SoftwareInventory : public Node
{
public:
template <typename CrowApp>
SoftwareInventory(CrowApp &app) :
Node(app, "/redfish/v1/UpdateService/FirmwareInventory/<str>/",
std::string())
{
entityPrivileges = {
{boost::beast::http::verb::get, {{"Login"}}},
{boost::beast::http::verb::head, {{"Login"}}},
{boost::beast::http::verb::patch, {{"ConfigureComponents"}}},
{boost::beast::http::verb::put, {{"ConfigureComponents"}}},
{boost::beast::http::verb::delete_, {{"ConfigureComponents"}}},
{boost::beast::http::verb::post, {{"ConfigureComponents"}}}};
}
private:
void doGet(crow::Response &res, const crow::Request &req,
const std::vector<std::string> ¶ms) override
{
std::shared_ptr<AsyncResp> asyncResp = std::make_shared<AsyncResp>(res);
res.jsonValue["@odata.type"] =
"#SoftwareInventory.v1_1_0.SoftwareInventory";
res.jsonValue["@odata.context"] =
"/redfish/v1/$metadata#SoftwareInventory.SoftwareInventory";
res.jsonValue["Name"] = "Software Inventory";
res.jsonValue["Updateable"] = false;
res.jsonValue["Status"]["Health"] = "OK";
res.jsonValue["Status"]["HealthRollup"] = "OK";
res.jsonValue["Status"]["State"] = "Enabled";
if (params.size() != 1)
{
messages::internalError(res);
res.end();
return;
}
std::shared_ptr<std::string> swId =
std::make_shared<std::string>(params[0]);
res.jsonValue["@odata.id"] =
"/redfish/v1/UpdateService/FirmwareInventory/" + *swId;
crow::connections::systemBus->async_method_call(
[asyncResp, swId](
const boost::system::error_code ec,
const std::vector<std::pair<
std::string, std::vector<std::pair<
std::string, std::vector<std::string>>>>>
&subtree) {
BMCWEB_LOG_DEBUG << "doGet callback...";
if (ec)
{
messages::internalError(asyncResp->res);
return;
}
for (const std::pair<
std::string,
std::vector<
std::pair<std::string, std::vector<std::string>>>>
&obj : subtree)
{
if (boost::ends_with(obj.first, *swId) != true)
{
continue;
}
if (obj.second.size() < 1)
{
continue;
}
crow::connections::systemBus->async_method_call(
[asyncResp,
swId](const boost::system::error_code error_code,
const boost::container::flat_map<
std::string, VariantType> &propertiesList) {
if (error_code)
{
messages::internalError(asyncResp->res);
return;
}
boost::container::flat_map<
std::string, VariantType>::const_iterator it =
propertiesList.find("Purpose");
if (it == propertiesList.end())
{
BMCWEB_LOG_DEBUG
<< "Can't find property \"Purpose\"!";
messages::propertyMissing(asyncResp->res,
"Purpose");
return;
}
const std::string *swInvPurpose =
std::get_if<std::string>(&it->second);
if (swInvPurpose == nullptr)
{
BMCWEB_LOG_DEBUG
<< "wrong types for property\"Purpose\"!";
messages::propertyValueTypeError(asyncResp->res,
"", "Purpose");
return;
}
BMCWEB_LOG_DEBUG << "swInvPurpose = "
<< *swInvPurpose;
it = propertiesList.find("Version");
if (it == propertiesList.end())
{
BMCWEB_LOG_DEBUG
<< "Can't find property \"Version\"!";
messages::propertyMissing(asyncResp->res,
"Version");
return;
}
BMCWEB_LOG_DEBUG << "Version found!";
const std::string *version =
std::get_if<std::string>(&it->second);
if (version == nullptr)
{
BMCWEB_LOG_DEBUG
<< "Can't find property \"Version\"!";
messages::propertyValueTypeError(asyncResp->res,
"", "Version");
return;
}
asyncResp->res.jsonValue["Version"] = *version;
asyncResp->res.jsonValue["Id"] = *swId;
},
obj.second[0].first, obj.first,
"org.freedesktop.DBus.Properties", "GetAll",
"xyz.openbmc_project.Software.Version");
}
},
"xyz.openbmc_project.ObjectMapper",
"/xyz/openbmc_project/object_mapper",
"xyz.openbmc_project.ObjectMapper", "GetSubTree",
"/xyz/openbmc_project/software", int32_t(1),
std::array<const char *, 1>{
"xyz.openbmc_project.Software.Version"});
}
};
} // namespace redfish
| 42.584245 | 80 | 0.46159 | opencomputeproject |
5d5fca61eb70013bfa5cfa0b88ec29791f68293e | 1,689 | cpp | C++ | src/generator/constant.cpp | ikitayama/cobi | e9bc4a5675ead1874ad9ffa953de8edb3a763479 | [
"BSD-3-Clause"
] | null | null | null | src/generator/constant.cpp | ikitayama/cobi | e9bc4a5675ead1874ad9ffa953de8edb3a763479 | [
"BSD-3-Clause"
] | null | null | null | src/generator/constant.cpp | ikitayama/cobi | e9bc4a5675ead1874ad9ffa953de8edb3a763479 | [
"BSD-3-Clause"
] | 1 | 2018-12-14T02:45:41.000Z | 2018-12-14T02:45:41.000Z | /*****************************************************************************
** Cobi http://www.scalasca.org/ **
*****************************************************************************
** Copyright (c) 2009-2010 **
** Forschungszentrum Juelich, Juelich Supercomputing Centre **
** **
** See the file COPYRIGHT in the base directory for details **
*****************************************************************************/
/**
* @file constant.cpp
* @author Jan Mussler
* @brief Implements the constant AST nodes
*
* NullOp, String and Integer const expressions
*/
#include "generator.h"
using namespace gi::generator;
BPatch_snippet* NullOp::getSnippet(IContext* c) {
return new BPatch_nullExpr();
}
NullOp::~NullOp() {
}
NullOp::NullOp() {
}
Constant* Constant::createConstant(int i) {
return new IntConstant(i);
}
Constant* Constant::createConstant(std::string s) {
return new StrConstant(s);
}
IntConstant::IntConstant(int i) : value(i) {
}
string IntConstant::getStringValue(IContext* c) {
stringstream ss;
ss << value;
return ss.str();
}
BPatch_snippet* IntConstant::getSnippet(IContext* c) {
return new BPatch_constExpr(value);
}
StrConstant::StrConstant(std::string s) : value(s) {
}
string StrConstant::getStringValue(IContext* c) {
return value;
}
BPatch_snippet* StrConstant::getSnippet(IContext* c) {
return new BPatch_constExpr(value.c_str());
}
| 26.809524 | 80 | 0.492599 | ikitayama |
5d607d60ebc7507ac1f777c2ceeb83c592e23d27 | 3,348 | cc | C++ | ash/common/wm_shell.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | ash/common/wm_shell.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ash/common/wm_shell.cc | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2016 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 "ash/common/wm_shell.h"
#include "ash/common/focus_cycler.h"
#include "ash/common/keyboard/keyboard_ui.h"
#include "ash/common/shell_window_ids.h"
#include "ash/common/system/chromeos/session/logout_confirmation_controller.h"
#include "ash/common/system/tray/system_tray_delegate.h"
#include "ash/common/system/tray/system_tray_notifier.h"
#include "ash/common/wm/mru_window_tracker.h"
#include "ash/common/wm/overview/window_selector_controller.h"
#include "ash/common/wm_window.h"
#include "base/bind.h"
#include "base/logging.h"
namespace ash {
// static
WmShell* WmShell::instance_ = nullptr;
// static
void WmShell::Set(WmShell* instance) {
instance_ = instance;
}
// static
WmShell* WmShell::Get() {
return instance_;
}
void WmShell::NotifyPinnedStateChanged(WmWindow* pinned_window) {
FOR_EACH_OBSERVER(ShellObserver, shell_observers_,
OnPinnedStateChanged(pinned_window));
}
void WmShell::AddShellObserver(ShellObserver* observer) {
shell_observers_.AddObserver(observer);
}
void WmShell::RemoveShellObserver(ShellObserver* observer) {
shell_observers_.RemoveObserver(observer);
}
WmShell::WmShell()
: focus_cycler_(new FocusCycler),
system_tray_notifier_(new SystemTrayNotifier),
window_selector_controller_(new WindowSelectorController()) {}
WmShell::~WmShell() {}
bool WmShell::IsSystemModalWindowOpen() {
if (simulate_modal_window_open_for_testing_)
return true;
// Traverse all system modal containers, and find its direct child window
// with "SystemModal" setting, and visible.
for (WmWindow* root : GetAllRootWindows()) {
WmWindow* system_modal =
root->GetChildByShellWindowId(kShellWindowId_SystemModalContainer);
if (!system_modal)
continue;
for (const WmWindow* child : system_modal->GetChildren()) {
if (child->IsSystemModal() && child->GetTargetVisibility()) {
return true;
}
}
}
return false;
}
void WmShell::SetKeyboardUI(std::unique_ptr<KeyboardUI> keyboard_ui) {
keyboard_ui_ = std::move(keyboard_ui);
}
void WmShell::SetMediaDelegate(std::unique_ptr<MediaDelegate> delegate) {
media_delegate_ = std::move(delegate);
}
void WmShell::SetSystemTrayDelegate(
std::unique_ptr<SystemTrayDelegate> delegate) {
DCHECK(delegate);
DCHECK(!system_tray_delegate_);
// TODO(jamescook): Create via ShellDelegate once it moves to //ash/common.
system_tray_delegate_ = std::move(delegate);
system_tray_delegate_->Initialize();
#if defined(OS_CHROMEOS)
logout_confirmation_controller_.reset(new LogoutConfirmationController(
base::Bind(&SystemTrayDelegate::SignOut,
base::Unretained(system_tray_delegate_.get()))));
#endif
}
void WmShell::DeleteSystemTrayDelegate() {
DCHECK(system_tray_delegate_);
#if defined(OS_CHROMEOS)
logout_confirmation_controller_.reset();
#endif
system_tray_delegate_.reset();
}
void WmShell::DeleteWindowSelectorController() {
window_selector_controller_.reset();
}
void WmShell::CreateMruWindowTracker() {
mru_window_tracker_.reset(new MruWindowTracker);
}
void WmShell::DeleteMruWindowTracker() {
mru_window_tracker_.reset();
}
} // namespace ash
| 28.615385 | 78 | 0.753584 | Wzzzx |
5d62dadacc9740ce55d885e4a0aa7d6751eb4b75 | 2,419 | cpp | C++ | Permissions/Permissions/Private/Permissions.cpp | forced1988/Ark-Server-Plugins | a5f05fa0b1df467d001f7ce09de2e7468e22e5eb | [
"MIT"
] | 1 | 2021-01-25T13:41:34.000Z | 2021-01-25T13:41:34.000Z | Permissions/Permissions/Private/Permissions.cpp | forced1988/Ark-Server-Plugins | a5f05fa0b1df467d001f7ce09de2e7468e22e5eb | [
"MIT"
] | null | null | null | Permissions/Permissions/Private/Permissions.cpp | forced1988/Ark-Server-Plugins | a5f05fa0b1df467d001f7ce09de2e7468e22e5eb | [
"MIT"
] | 1 | 2020-05-24T18:01:41.000Z | 2020-05-24T18:01:41.000Z | #ifdef PERMISSIONS_ARK
#include "../Public/ArkPermissions.h"
#else
#include "../Public/AtlasPermissions.h"
#endif
#include "Main.h"
namespace Permissions
{
TArray<FString> GetPlayerGroups(uint64 steam_id)
{
return database->GetPlayerGroups(steam_id);
}
TArray<FString> GetGroupPermissions(const FString& group)
{
if (group.IsEmpty())
return {};
return database->GetGroupPermissions(group);
}
TArray<FString> GetAllGroups()
{
return database->GetAllGroups();
}
TArray<uint64> GetGroupMembers(const FString& group)
{
return database->GetGroupMembers(group);
}
bool IsPlayerInGroup(uint64 steam_id, const FString& group)
{
TArray<FString> groups = GetPlayerGroups(steam_id);
for (const auto& current_group : groups)
{
if (current_group == group)
return true;
}
return false;
}
std::optional<std::string> AddPlayerToGroup(uint64 steam_id, const FString& group)
{
return database->AddPlayerToGroup(steam_id, group);
}
std::optional<std::string> RemovePlayerFromGroup(uint64 steam_id, const FString& group)
{
return database->RemovePlayerFromGroup(steam_id, group);
}
std::optional<std::string> AddGroup(const FString& group)
{
return database->AddGroup(group);
}
std::optional<std::string> RemoveGroup(const FString& group)
{
return database->RemoveGroup(group);
}
bool IsGroupHasPermission(const FString& group, const FString& permission)
{
if (!database->IsGroupExists(group))
return false;
TArray<FString> permissions = GetGroupPermissions(group);
for (const auto& current_perm : permissions)
{
if (current_perm == permission)
return true;
}
return false;
}
bool IsPlayerHasPermission(uint64 steam_id, const FString& permission)
{
TArray<FString> groups = GetPlayerGroups(steam_id);
for (const auto& current_group : groups)
{
if (IsGroupHasPermission(current_group, permission) || IsGroupHasPermission(current_group, "*"))
return true;
}
return false;
}
std::optional<std::string> GroupGrantPermission(const FString& group, const FString& permission)
{
return database->GroupGrantPermission(group, permission);
}
std::optional<std::string> GroupRevokePermission(const FString& group, const FString& permission)
{
return database->GroupRevokePermission(group, permission);
}
}
| 23.038095 | 100 | 0.702356 | forced1988 |
5d63da1666829dbbde3b023b8dfce0c11ae41b22 | 6,867 | cpp | C++ | vendor/mysql-connector-c++-1.1.3/test/framework/test_listener.cpp | caiqingfeng/libmrock | bb7c94482a105e92b6d3e8640b13f9ff3ae49a83 | [
"Apache-2.0"
] | 1 | 2015-12-01T04:16:54.000Z | 2015-12-01T04:16:54.000Z | vendor/mysql-connector-c++-1.1.3/test/framework/test_listener.cpp | caiqingfeng/libmrock | bb7c94482a105e92b6d3e8640b13f9ff3ae49a83 | [
"Apache-2.0"
] | null | null | null | vendor/mysql-connector-c++-1.1.3/test/framework/test_listener.cpp | caiqingfeng/libmrock | bb7c94482a105e92b6d3e8640b13f9ff3ae49a83 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/C++ is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
MySQL Connectors. There are special exceptions to the terms and
conditions of the GPLv2 as it is applied to this software, see the
FLOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include "test_listener.h"
#include "test_timer.h"
namespace testsuite
{
TestsListener::TestsListener()
: curSuiteName("n/a")
, curTestName("n/a")
, curTestOrdNum(0)
, executed(0)
, exceptions(0)
, verbose(false)
, timing(false)
{
//TODO: Make StartOptions dependent
outputter.reset(new TAP());
}
void TestsListener::setVerbose(bool verbosity)
{
theInstance().verbose=verbosity;
}
bool TestsListener::doTiming(bool timing)
{
bool preserve= theInstance().timing;
theInstance().timing=timing;
return preserve;
}
//TODO: "set" counterparts
std::ostream & TestsListener::errorsLog()
{
if (theInstance().verbose)
return theInstance().outputter->errorsLog();
else
{
theInstance().devNull.str("");
return theInstance().devNull;
}
}
void TestsListener::errorsLog(const String::value_type * msg)
{
if (msg != NULL)
errorsLog() << msg << std::endl;
}
void TestsListener::errorsLog(const String & msg)
{
errorsLog() << msg << std::endl;
}
void TestsListener::errorsLog(const String::value_type * msg
, const String::value_type * file
, int line)
{
if (msg != NULL)
{
errorsLog() << msg << " File: " << file << " Line: " << line << std::endl;
}
}
std::ostream & TestsListener::messagesLog()
{
if (theInstance().verbose)
return theInstance().outputter->messagesLog();
else
{
theInstance().devNull.str("");
return theInstance().devNull;
}
}
void TestsListener::messagesLog(const String::value_type * msg)
{
if (msg != NULL)
messagesLog() << msg;
}
void TestsListener::messagesLog(const String & msg)
{
if (theInstance().verbose)
messagesLog() << msg;
}
void TestsListener::currentTestName(const String & name)
{
theInstance().curTestName=name;
}
const String & TestsListener::currentSuiteName()
{
return theInstance().curSuiteName;
}
String TestsListener::testFullName()
{
return theInstance().curSuiteName + "::" + theInstance().curTestName;
}
void TestsListener::incrementCounter(int incrVal)
{
theInstance().curTestOrdNum+=incrVal;
}
int TestsListener::recordFailed()
{
failedTests.push_back(curTestOrdNum);
return static_cast<int> (failedTests.size());
}
void TestsListener::nextSuiteStarts(const String & name, int testsNumber)
{
/*
if ( name.length() > 0 )
theInstance().messagesLog()
<< "=============== " << name << " ends. " << "==============="
<< std::endl;*/
theInstance().curSuiteName=name;
/*
theInstance().messagesLog()
<< "=============== " << name << " starts. " << "==============="
<< std::endl;*/
theInstance().outputter->SuiteHeader(name, theInstance().curTestOrdNum + 1
, testsNumber);
}
void TestsListener::testHasStarted()
{
//std::cout << ".";
++theInstance().executed;
theInstance().executionComment= "";
if (theInstance().timing)
{
Timer::startTest(testFullName());
}
}
void TestsListener::testHasFinished(TestRunResult result, const String & msg)
{
static String timingResult("");
if (theInstance().timing)
{
clock_t time=Timer::stopTest(testFullName());
float total = Timer::translate2seconds(time);
static std::stringstream tmp;
tmp.precision(10);
tmp.str("");
tmp << std::showpoint;
tmp << std::endl << "# " << std::setw(40) << std::left << "Total" << " = ";
tmp << std::setw(13) << std::right << total << "s";
tmp << " (100.00%)" << std::endl;
const List & names=Timer::getNames(testFullName());
ConstIterator it=names.begin();
for (; it != names.end(); ++it)
{
time=Timer::getTime(*it);
tmp << "# " << std::setw(38) << std::left << *it;
tmp << " = " << std::setw(13) << std::right << Timer::translate2seconds(time) << "s";
tmp << " (";
tmp << std::setw(6) << std::right;
if (total > 0.0) {
tmp.precision(5);
tmp << ((100 / total) * Timer::translate2seconds(time));
tmp.precision(10);
} else {
tmp << "n/a ";
}
tmp << "%)";
tmp << " (line " << Timer::getLine(*it) << ")" << std::endl;
}
timingResult=tmp.str();
}
else
timingResult="";
if (!msg.empty())
StringUtils::concatSeparated(theInstance().executionComment, msg);
if (!timingResult.empty())
StringUtils::concatSeparated(theInstance().executionComment, timingResult);
if (result != trrPassed)
{
// Output about test fail and recording info
theInstance().recordFailed();
if (result == trrThrown)
++theInstance().exceptions;
theInstance().outputter->TestFailed(theInstance().curTestOrdNum
, theInstance().curTestName
, theInstance().executionComment);
}
else
{
// Output about test success
theInstance().outputter->TestPassed(theInstance().curTestOrdNum
, theInstance().curTestName
, theInstance().executionComment);
}
}
void TestsListener::setTestExecutionComment(const String & msg)
{
theInstance().executionComment= msg;
}
void TestsListener::testHasFailed(const String & msg)
{
setTestExecutionComment(msg);
errorsLog(msg);
throw TestFailedException();
}
void TestsListener::summary()
{
outputter->Summary(executed
, failed() /*+ exceptions - exceptions are already counted in failed()*/
, failedTests);
}
bool TestsListener::allTestsPassed()
{
return theInstance().exceptions && !theInstance().failed() == 0;
}
void TestsListener::bailSuite(const String & reason)
{
static const String bail("BAIL ");
theInstance().outputter->Comment(bail + reason);
}
}
| 24.01049 | 93 | 0.631863 | caiqingfeng |
5d65cc6b1abef32c0c8e33f3ea14d46bbc57dc5a | 3,170 | cpp | C++ | editor/src/free_camera.cpp | trbflxr/xe | 13123869a848972e064cb8c6838c4215f034f3d9 | [
"MIT"
] | null | null | null | editor/src/free_camera.cpp | trbflxr/xe | 13123869a848972e064cb8c6838c4215f034f3d9 | [
"MIT"
] | null | null | null | editor/src/free_camera.cpp | trbflxr/xe | 13123869a848972e064cb8c6838c4215f034f3d9 | [
"MIT"
] | null | null | null | //
// Created by trbflxr on 3/31/2020.
//
#include "free_camera.hpp"
#include <xe/core/engine.hpp>
namespace xe {
FreeCamera::FreeCamera(const vec2u &resolution, float fovDeg, float aspect, float nearZ, float farZ,
float moveSpeed, float sprintSpeed, float mouseSensitivity) :
camera_(resolution, fovDeg, aspect, nearZ, farZ),
moveSpeed_(moveSpeed),
sprintSpeed_(sprintSpeed),
mouseSensitivity_(mouseSensitivity) {
windowSize_ = Engine::ref().window().size();
windowCenter_ = windowSize_ / 2.0f;
lastMousePosition_ = windowCenter_;
}
void FreeCamera::destroy() {
camera_.destroy();
}
void FreeCamera::onRender() {
camera_.updateUniforms();
}
void FreeCamera::onUpdate() {
auto ts = Engine::ref().delta();
if (mouseLocked_) {
vec2 mouseChange = Engine::getMousePosition() - lastMousePosition_;
//rotate
camera_.transform().rotate(quat(vec3::unitYN(), mouseChange.x * mouseSensitivity_), Transform::Space::Parent);
camera_.transform().rotate(quat(-camera_.transform().localRight(), mouseChange.y * mouseSensitivity_), Transform::Space::Parent);
Engine::executeInRenderThread([this]() {
lastMousePosition_ = Engine::getMousePosition();
Engine::setMousePosition(windowCenter_);
});
//move
float speed = Engine::isKeyPressed(Keyboard::LShift) ? moveSpeed_ * sprintSpeed_ : moveSpeed_;
if (Engine::isKeyPressed(Keyboard::W)) {
camera_.transform().translate(camera_.transform().localForward() * speed * ts, Transform::Space::Parent);
}
if (Engine::isKeyPressed(Keyboard::S)) {
camera_.transform().translate(-camera_.transform().localForward() * speed * ts, Transform::Space::Parent);
}
if (Engine::isKeyPressed(Keyboard::A)) {
camera_.transform().translate(-camera_.transform().localRight() * speed * ts, Transform::Space::Parent);
}
if (Engine::isKeyPressed(Keyboard::D)) {
camera_.transform().translate(camera_.transform().localRight() * speed * ts, Transform::Space::Parent);
}
if (Engine::isKeyPressed(Keyboard::Space)) {
camera_.transform().translate(vec3::unitY() * speed * ts, Transform::Space::Parent);
}
if (Engine::isKeyPressed(Keyboard::LControl)) {
camera_.transform().translate(vec3::unitYN() * speed * ts, Transform::Space::Parent);
}
}
}
bool FreeCamera::onKeyPressed(Event::Key key) {
if (key.code == Keyboard::Escape || key.code == Keyboard::R) {
mouseLocked_ = false;
return true;
}
return false;
}
bool FreeCamera::onMousePressed(Event::MouseButton mb) {
if (mb.button == Mouse::Right) {
mouseLocked_ = !mouseLocked_;
if (mouseLocked_) {
Engine::executeInRenderThread([this]() {
Engine::setMousePosition(windowCenter_);
});
}
Engine::ref().window().setCursorVisible(!mouseLocked_);
return true;
}
return false;
}
bool FreeCamera::onFocusLost() {
mouseLocked_ = false;
Engine::ref().window().setCursorVisible(!mouseLocked_);
return false;
}
}
| 31.386139 | 135 | 0.64511 | trbflxr |
5d6682dee091779de8d7e0978d6643e39d007eea | 18,298 | cpp | C++ | snack-machine-firmware/src/denhac/ui/MainWindow/MainWindow.cpp | Jnesselr/Vending-Machine | 811d2d018909188a5ed7a9cb4ba1b9488e02501a | [
"MIT"
] | 2 | 2020-05-25T17:45:29.000Z | 2020-09-21T16:23:05.000Z | snack-machine-firmware/src/denhac/ui/MainWindow/MainWindow.cpp | Jnesselr/Vending-Machine | 811d2d018909188a5ed7a9cb4ba1b9488e02501a | [
"MIT"
] | null | null | null | snack-machine-firmware/src/denhac/ui/MainWindow/MainWindow.cpp | Jnesselr/Vending-Machine | 811d2d018909188a5ed7a9cb4ba1b9488e02501a | [
"MIT"
] | 1 | 2021-10-31T05:57:33.000Z | 2021-10-31T05:57:33.000Z | #ifdef VENDING_MAIN_BOARD
#include "denhac/ui/MainWindow/MainWindow.h"
#include "denhac/ui/MainWindow/Callbacks.h"
#include "denhac/ProductManager.h"
#include "denhac/Session.h"
#include "ui/WindowManager.h"
#include "motors.h"
#include "utils.h"
#include <avr/wdt.h>
template<StaticCallbackType type, typename... Args>
MainWindow* StaticCallback<type, Args...>::mainWindow = nullptr;
template<StaticCallbackType type, typename... Args>
WindowCallback<Args...> StaticCallback<type, Args...>::windowCallback = nullptr;
#define CALL_ON_BUTTONS(function_call) \
if(state == MainWindowState::VEND_SCREEN) { \
cancelOrderButton.function_call; \
membershipButton.function_call; \
addItemButton.function_call; \
vendButton.function_call; \
} else if(state == MainWindowState::LETTERS_VISIBLE) { \
backButton.function_call; \
cellButtonA.function_call; \
cellButtonB.function_call; \
cellButtonC.function_call; \
cellButtonD.function_call; \
cellButtonE.function_call; \
cellButtonF.function_call; \
cellButtonG.function_call; \
cellButtonH.function_call; \
} else if(state == MainWindowState::NUMBERS_VISIBLE) { \
backButton.function_call; \
cellButton1.function_call; \
cellButton2.function_call; \
cellButton3.function_call; \
cellButton4.function_call; \
cellButton5.function_call; \
cellButton6.function_call; \
cellButton7.function_call; \
cellButton8.function_call; \
}
void MainWindow::show() {
setupMemberVariables();
display->gfx_BGcolour(WHITESMOKE);
display->gfx_Cls();
state = MainWindowState::LETTERS_VISIBLE;
oldLoopState = MainWindowState::VEND_SCREEN; // Technically not true, but it redraws the grid this way
drawCurrentCredit();
drawOrder();
Session::moneyAvailableCallback = callback<StaticCallbackType::MONEY_AVAILABLE, uint32_t>(moneyAvailable);
Session::onCustomerLookupStarted = callback<StaticCallbackType::CUSTOMER_LOOKUP_STARTED>(customerLookupStarted);
Session::onOrdersRetrieved = callback<StaticCallbackType::ORDERS_RETRIEVED>(ordersRetrieved);
Session::onUnknownCard = callback<StaticCallbackType::UNKNOWN_CARD>(unknownCard);
Session::onReset = callback<StaticCallbackType::SESSION_RESET>(sessionReset);
Session::onCurrentOrderUpdated = callback<StaticCallbackType::CURRENT_ORDER_UPDATED>(currentOrderUpdated);
}
void MainWindow::setupMemberVariables() {
// We only need to do setup once
if(memberVariablesSet) {
return;
}
screenWidth = WindowManager::getWidth();
screenHeight = WindowManager::getHeight();
gridLeft = GRID_PADDING;
gridRight = screenWidth - GRID_PADDING - 1;
gridBottom = screenHeight - GRID_PADDING - 1;
gridTop = gridBottom - 3 - (3 * CELL_HEIGHT);
backButton.display = display;
backButton.left = gridLeft + 1;
backButton.right = backButton.left + CELL_WIDTH - 1;
backButton.top = gridTop + 2 * CELL_HEIGHT + 3;
backButton.bottom = backButton.top + CELL_HEIGHT - 1;
backButton.tapped = callback<StaticCallbackType::BACK>(back);
cellButtonA.display = display;
cellButtonA.character = 'A';
cellButtonA.left = gridLeft + 1;
cellButtonA.right = cellButtonA.left + CELL_WIDTH - 1;
cellButtonA.top = gridTop + 1;
cellButtonA.bottom = cellButtonA.top + CELL_HEIGHT - 1;
RowCallback<0>::mainWindow = this;
cellButtonA.tapped = RowCallback<0>::tapped;
cellButtonB.display = display;
cellButtonB.character = 'B';
cellButtonB.left = gridLeft + CELL_WIDTH + 2;
cellButtonB.right = cellButtonB.left + CELL_WIDTH - 1;
cellButtonB.top = gridTop + 1;
cellButtonB.bottom = cellButtonB.top + CELL_HEIGHT - 1;
RowCallback<1>::mainWindow = this;
cellButtonB.tapped = RowCallback<1>::tapped;
cellButtonC.display = display;
cellButtonC.character = 'C';
cellButtonC.left = gridLeft + 2 * CELL_WIDTH + 3;
cellButtonC.right = cellButtonC.left + CELL_WIDTH - 1;
cellButtonC.top = gridTop + 1;
cellButtonC.bottom = cellButtonC.top + CELL_HEIGHT - 1;
RowCallback<2>::mainWindow = this;
cellButtonC.tapped = RowCallback<2>::tapped;
cellButtonD.display = display;
cellButtonD.character = 'D';
cellButtonD.left = gridLeft + 1;
cellButtonD.right = cellButtonD.left + CELL_WIDTH - 1;
cellButtonD.top = gridTop + CELL_HEIGHT + 2;
cellButtonD.bottom = cellButtonD.top + CELL_HEIGHT - 1;
RowCallback<3>::mainWindow = this;
cellButtonD.tapped = RowCallback<3>::tapped;
cellButtonE.display = display;
cellButtonE.character = 'E';
cellButtonE.left = gridLeft + CELL_WIDTH + 2;
cellButtonE.right = cellButtonE.left + CELL_WIDTH - 1;
cellButtonE.top = gridTop + CELL_HEIGHT + 2;
cellButtonE.bottom = cellButtonE.top + CELL_HEIGHT - 1;
RowCallback<4>::mainWindow = this;
cellButtonE.tapped = RowCallback<4>::tapped;
cellButtonF.display = display;
cellButtonF.character = 'F';
cellButtonF.left = gridLeft + 2 * CELL_WIDTH + 3;
cellButtonF.right = cellButtonF.left + CELL_WIDTH - 1;
cellButtonF.top = gridTop + CELL_HEIGHT + 2;
cellButtonF.bottom = cellButtonF.top + CELL_HEIGHT - 1;
RowCallback<5>::mainWindow = this;
cellButtonF.tapped = RowCallback<5>::tapped;
cellButtonG.display = display;
cellButtonG.character = 'G';
cellButtonG.left = gridLeft + CELL_WIDTH + 2;
cellButtonG.right = cellButtonG.left + CELL_WIDTH - 1;
cellButtonG.top = gridTop + 2 * CELL_HEIGHT + 3;
cellButtonG.bottom = cellButtonG.top + CELL_HEIGHT - 1;
RowCallback<6>::mainWindow = this;
cellButtonG.tapped = RowCallback<6>::tapped;
cellButtonH.display = display;
cellButtonH.character = 'H';
cellButtonH.left = gridLeft + 2 * CELL_WIDTH + 3;
cellButtonH.right = cellButtonH.left + CELL_WIDTH - 1;
cellButtonH.top = gridTop + 2 * CELL_HEIGHT + 3;
cellButtonH.bottom = cellButtonH.top + CELL_HEIGHT - 1;
RowCallback<7>::mainWindow = this;
cellButtonH.tapped = RowCallback<7>::tapped;
cellButton1.display = display;
cellButton1.character = '1';
cellButton1.left = gridLeft + 1;
cellButton1.right = cellButton1.left + CELL_WIDTH - 1;
cellButton1.top = gridTop + 1;
cellButton1.bottom = cellButton1.top + CELL_HEIGHT - 1;
ColCallback<0>::mainWindow = this;
cellButton1.tapped = ColCallback<0>::tapped;
cellButton2.display = display;
cellButton2.character = '2';
cellButton2.left = gridLeft + CELL_WIDTH + 2;
cellButton2.right = cellButton2.left + CELL_WIDTH - 1;
cellButton2.top = gridTop + 1;
cellButton2.bottom = cellButton2.top + CELL_HEIGHT - 1;
ColCallback<1>::mainWindow = this;
cellButton2.tapped = ColCallback<1>::tapped;
cellButton3.display = display;
cellButton3.character = '3';
cellButton3.left = gridLeft + 2 * CELL_WIDTH + 3;
cellButton3.right = cellButton3.left + CELL_WIDTH - 1;
cellButton3.top = gridTop + 1;
cellButton3.bottom = cellButton3.top + CELL_HEIGHT - 1;
ColCallback<2>::mainWindow = this;
cellButton3.tapped = ColCallback<2>::tapped;
cellButton4.display = display;
cellButton4.character = '4';
cellButton4.left = gridLeft + 1;
cellButton4.right = cellButton4.left + CELL_WIDTH - 1;
cellButton4.top = gridTop + CELL_HEIGHT + 2;
cellButton4.bottom = cellButton4.top + CELL_HEIGHT - 1;
ColCallback<3>::mainWindow = this;
cellButton4.tapped = ColCallback<3>::tapped;
cellButton5.display = display;
cellButton5.character = '5';
cellButton5.left = gridLeft + CELL_WIDTH + 2;
cellButton5.right = cellButton5.left + CELL_WIDTH - 1;
cellButton5.top = gridTop + CELL_HEIGHT + 2;
cellButton5.bottom = cellButton5.top + CELL_HEIGHT - 1;
ColCallback<4>::mainWindow = this;
cellButton5.tapped = ColCallback<4>::tapped;
cellButton6.display = display;
cellButton6.character = '6';
cellButton6.left = gridLeft + 2 * CELL_WIDTH + 3;
cellButton6.right = cellButton6.left + CELL_WIDTH - 1;
cellButton6.top = gridTop + CELL_HEIGHT + 2;
cellButton6.bottom = cellButton6.top + CELL_HEIGHT - 1;
ColCallback<5>::mainWindow = this;
cellButton6.tapped = ColCallback<5>::tapped;
cellButton7.display = display;
cellButton7.character = '7';
cellButton7.left = gridLeft + CELL_WIDTH + 2;
cellButton7.right = cellButton7.left + CELL_WIDTH - 1;
cellButton7.top = gridTop + 2 * CELL_HEIGHT + 3;
cellButton7.bottom = cellButton7.top + CELL_HEIGHT - 1;
ColCallback<6>::mainWindow = this;
cellButton7.tapped = ColCallback<6>::tapped;
cellButton8.display = display;
cellButton8.character = '8';
cellButton8.left = gridLeft + 2 * CELL_WIDTH + 3;
cellButton8.right = cellButton8.left + CELL_WIDTH - 1;
cellButton8.top = gridTop + 2 * CELL_HEIGHT + 3;
cellButton8.bottom = cellButton8.top + CELL_HEIGHT - 1;
ColCallback<7>::mainWindow = this;
cellButton8.tapped = ColCallback<7>::tapped;
vendButton.display = display;
vendButton.left = gridLeft;
vendButton.right = gridRight;
vendButton.bottom = gridBottom;
vendButton.top = vendButton.bottom - CELL_HEIGHT - 7;
vendButton.tapped = callback<StaticCallbackType::VEND>(vend);
vendButton.disable();
cancelOrderButton.display = display;
cancelOrderButton.left = gridLeft;
cancelOrderButton.right = 193;
cancelOrderButton.bottom = vendButton.top - 5;
cancelOrderButton.top = cancelOrderButton.bottom - 74 - 7;
cancelOrderButton.tapped = callback<StaticCallbackType::CANCEL_ORDER>(cancelOrder);
cancelOrderButton.disable();
addItemButton.display = display;
addItemButton.left = gridRight - 105;
addItemButton.right = gridRight;
addItemButton.bottom = vendButton.top - 5;
addItemButton.top = addItemButton.bottom - 74 - 7;
addItemButton.tapped = callback<StaticCallbackType::ADD_ITEM>(addItemScreen);
membershipButton.display = display;
membershipButton.left = cancelOrderButton.right + 5;
membershipButton.right = addItemButton.left - 5;
membershipButton.bottom = vendButton.top - 5;
membershipButton.top = addItemButton.top;
membershipButton.tapped = callback<StaticCallbackType::MEMBERSHIP_BUTTON_TAPPED>(membershipButtonTapped);
membershipButton.disable();
memberVariablesSet = true;
}
void MainWindow::loop() {
// This avoids the unsigned long rollover bug
if(current_loop_millis > 4000000000ul) {
// TOOD Check if session is active
while(true); // Force a reset with watchdog
}
if(current_loop_millis > lastGridValidityScan + 200) {
verifyGridValidity();
}
if(state.gridIsShown() && !oldLoopState.gridIsShown()) {
drawGrid();
verifyGridValidity();
} else if(!state.gridIsShown() && oldLoopState.gridIsShown()) {
// Currently only the VEND_SCREEN
display->gfx_RectangleFilled(0, gridTop, screenWidth - 1, gridBottom, WHITESMOKE);
}
CALL_ON_BUTTONS(show())
oldLoopState = state;
}
void MainWindow::touch(uint8_t touchMode, uint16_t x, uint16_t y) {
CALL_ON_BUTTONS(touch(touchMode, x, y))
}
void MainWindow::setState(MainWindowState state) {
if(this->state != state) {
this->state = state;
CALL_ON_BUTTONS(forceRedrawNeeded())
}
}
void MainWindow::drawGrid() {
// Cells are 156 x 104 (3 x 2 multiple of 52)
display->gfx_RectangleFilled(0, gridTop, screenWidth - 1, gridBottom, WHITESMOKE);
// Outside Box
display->gfx_Line(gridLeft, gridBottom, gridLeft, gridTop, BLACK);
display->gfx_Line(gridLeft, gridTop, gridRight, gridTop, BLACK);
display->gfx_Line(gridRight, gridBottom, gridRight, gridTop, BLACK);
display->gfx_Line(gridLeft, gridBottom, gridRight, gridBottom, BLACK);
// Columns
uint16_t column = gridLeft + CELL_WIDTH + 1;
display->gfx_Line(column, gridTop, column, gridBottom, BLACK);
column = column + CELL_WIDTH + 1;
display->gfx_Line(column, gridTop, column, gridBottom, BLACK);
// Rows
uint16_t row = gridTop + CELL_HEIGHT + 1;
display->gfx_Line(gridLeft, row, gridRight, row, BLACK);
row = row + CELL_HEIGHT + 1;
display->gfx_Line(gridLeft, row, gridRight, row, BLACK);
}
CellButton* MainWindow::rowButton(uint8_t row) {
switch(row) {
case 0: return &cellButtonA;
case 1: return &cellButtonB;
case 2: return &cellButtonC;
case 3: return &cellButtonD;
case 4: return &cellButtonE;
case 5: return &cellButtonF;
case 6: return &cellButtonG;
case 7: return &cellButtonH;
default: return nullptr;
}
}
CellButton* MainWindow::colButton(uint8_t col) {
switch(col) {
case 0: return &cellButton1;
case 1: return &cellButton2;
case 2: return &cellButton3;
case 3: return &cellButton4;
case 4: return &cellButton5;
case 5: return &cellButton6;
case 6: return &cellButton7;
case 7: return &cellButton8;
default: return nullptr;
}
}
void MainWindow::verifyGridValidity() {
lastGridValidityScan = current_loop_millis;
for (uint8_t i = 0; i < 8; i++)
{
CellButton* button = rowButton(i);
bool isEnabled = button->isEnabled();
bool shouldBeEnabled = Motors::rowExists(i) && ProductManager::hasStockAvailable(i);
if(isEnabled != shouldBeEnabled) {
if(state == MainWindowState::NUMBERS_VISIBLE && selectedRow == i) {
setState(MainWindowState::LETTERS_VISIBLE);
}
}
button->setEnabled(shouldBeEnabled);
}
if(state != MainWindowState::NUMBERS_VISIBLE) {
return;
}
for (uint8_t i = 0; i < 8; i++)
{
CellButton* button = colButton(i);
bool shouldBeEnabled = Motors::exists(selectedRow, i) && ProductManager::hasStockAvailable(selectedRow, i);
button->setEnabled(shouldBeEnabled);
}
}
void MainWindow::drawOrder() {
display->txt_Width(2);
display->txt_Height(2);
display->txt_FGcolour(BLACK);
display->txt_BGcolour(WHITESMOKE);
display->gfx_RectangleFilled(0, 24, screenWidth - 1, gridTop - 1, WHITESMOKE);
Order* order = Session::getCurrentOrder();
uint16_t dollars = order->total / 100;
uint8_t cents = order->total % 100;
uint8_t dollarsWidth = (uint8_t) log10(dollars) + 1;
// Max is 30 wide, 4 of those are $. and cents. 2 of those are spaces
display->txt_MoveCursor(0, 24 - dollarsWidth);
display->print(" ");
display->print('$');
display->print(dollars);
display->print('.');
if(cents < 10) {
display->print('0');
}
display->print(cents);
for (uint8_t i = 0; i < order->getNumItems(); i++)
{
display->txt_MoveCursor(2 * i + 1, 0);
Item item = order->getItem(i);
Product product = ProductManager::get(item.productId);
if(product.valid) {
display->print(product.name);
display->print(" => ");
display->print(item.quantity);
}
}
}
void MainWindow::drawCurrentCredit() {
display->txt_Width(2);
display->txt_Height(2);
display->txt_FGcolour(BLACK);
display->txt_BGcolour(WHITESMOKE);
uint32_t credit = Session::getCurrentAvailableMoney();
uint16_t dollars = credit / 100;
uint8_t cents = credit % 100;
display->txt_MoveCursor(0, 0);
display->print('$');
display->print(dollars);
display->print('.');
if(cents < 10) {
display->print('0');
}
display->print(cents);
display->print(" ");
}
void MainWindow::handleVendEnabled() {
if(Session::canVend()) {
vendButton.enable();
} else {
vendButton.disable();
}
}
template<StaticCallbackType type, typename... Args>
VariableCallback<Args...> MainWindow::callback(VariableCallback<MainWindow*, Args...> function) {
StaticCallback<type, Args...>::mainWindow = this;
StaticCallback<type, Args...>::windowCallback = function;
return StaticCallback<type, Args...>::callback;
}
template<StaticCallbackType type, typename... Args>
void StaticCallback<type, Args...>::callback(Args... args) {
windowCallback(mainWindow, args...);
}
void MainWindow::back(MainWindow* mainWindow) {
if(mainWindow->state == MainWindowState::LETTERS_VISIBLE) {
mainWindow->setState(MainWindowState::VEND_SCREEN);
} else if(mainWindow->state == MainWindowState::NUMBERS_VISIBLE) {
mainWindow->setState(MainWindowState::LETTERS_VISIBLE);
mainWindow->verifyGridValidity();
}
}
void MainWindow::cancelOrder(MainWindow* mainWindow) {
Session::reset();
mainWindow->drawOrder();
}
void MainWindow::vend(MainWindow* mainWindow) {
mainWindow->vendButton.disable();
mainWindow->cancelOrderButton.disable();
mainWindow->addItemButton.disable();
Session::vend();
}
void MainWindow::rowTapped(uint8_t row) {
if(state == MainWindowState::LETTERS_VISIBLE) {
selectedRow = row;
setState(MainWindowState::NUMBERS_VISIBLE);
verifyGridValidity();
}
}
void MainWindow::colTapped(uint8_t col) {
if(state == MainWindowState::NUMBERS_VISIBLE) {
Session::addToCurrentOrder(selectedRow, col);
setState(MainWindowState::VEND_SCREEN);
cancelOrderButton.enable();
}
}
void MainWindow::moneyAvailable(MainWindow* mainWindow, uint32_t amount) {
mainWindow->drawCurrentCredit();
if(amount == 0) {
return;
}
mainWindow->cancelOrderButton.enable();
mainWindow->handleVendEnabled();
}
void MainWindow::addItemScreen(MainWindow* mainWindow) {
mainWindow->setState(MainWindowState::LETTERS_VISIBLE);
}
void MainWindow::customerLookupStarted(MainWindow* mainWindow) {
mainWindow->membershipButton.setState(MembershipButtonState::PLEASE_WAIT);
mainWindow->membershipButton.disable();
mainWindow->cancelOrderButton.enable();
mainWindow->setState(MainWindowState::VEND_SCREEN);
}
void MainWindow::ordersRetrieved(MainWindow* mainWindow) {
mainWindow->membershipButton.setState(MembershipButtonState::NUM_ORDERS);
}
void MainWindow::unknownCard(MainWindow* mainWindow) {
mainWindow->membershipButton.setState(MembershipButtonState::UNKNOWN_CARD);
}
void MainWindow::sessionReset(MainWindow* mainWindow) {
mainWindow->membershipButton.setState(MembershipButtonState::SCAN_CARD);
mainWindow->membershipButton.disable();
mainWindow->cancelOrderButton.disable();
mainWindow->vendButton.disable();
mainWindow->addItemButton.enable();
}
void MainWindow::membershipButtonTapped(MainWindow* mainWindow) {
if(Session::getNumOrders() > 0) {
Session::setCurrentOrderNum(0);
}
// TODO What if the order count isn't 1?
}
void MainWindow::currentOrderUpdated(MainWindow* mainWindow) {
mainWindow->drawOrder();
mainWindow->handleVendEnabled();
Order* order = Session::getCurrentOrder();
if(order->getNumItems() > 0) {
mainWindow->cancelOrderButton.enable();
if(order->status == OrderStatus::PROCESSING) {
mainWindow->addItemButton.disable();
}
}
}
#endif | 32.792115 | 114 | 0.721281 | Jnesselr |
5d67ed157395edff6549590a1c433b0315941bea | 14,999 | cc | C++ | INET_EC/common/IntervalTree.cc | LarryNguyen/ECSim- | 0d3f848642e49845ed7e4c7b97dd16bd3d65ede5 | [
"Apache-2.0"
] | 12 | 2020-11-30T08:04:23.000Z | 2022-03-23T11:49:26.000Z | Simulation/OMNeT++/inet/src/inet/common/IntervalTree.cc | StarStuffSteve/masters-research-project | 47c1874913d0961508f033ca9a1144850eb8f8b7 | [
"Apache-2.0"
] | 1 | 2021-01-26T10:49:56.000Z | 2021-01-31T16:58:52.000Z | Simulation/OMNeT++/inet/src/inet/common/IntervalTree.cc | StarStuffSteve/masters-research-project | 47c1874913d0961508f033ca9a1144850eb8f8b7 | [
"Apache-2.0"
] | 8 | 2021-03-15T02:05:51.000Z | 2022-03-21T13:14:02.000Z | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* 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 Willow Garage, Inc. 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.
*/
/** \author Jia Pan */
#include "inet/common/IntervalTree.h"
#include <iostream>
#include <cstdlib>
namespace inet {
IntervalTreeNode::IntervalTreeNode()
{
}
IntervalTreeNode::IntervalTreeNode(const Interval* new_interval) :
stored_interval(new_interval), key(new_interval->low), high(new_interval->high), max_high(high)
{
}
IntervalTreeNode::~IntervalTreeNode()
{
delete stored_interval;
}
IntervalTree::IntervalTree()
{
nil = new IntervalTreeNode;
nil->left = nil->right = nil->parent = nil;
nil->red = false;
nil->key = nil->high = nil->max_high = -SimTime::getMaxTime(); //-std::numeric_limits<double>::max();
nil->stored_interval = nullptr;
root = new IntervalTreeNode;
root->parent = root->left = root->right = nil;
root->key = root->high = root->max_high = SimTime::getMaxTime(); // std::numeric_limits<double>::max();
root->red = false;
root->stored_interval = nullptr;
/// the following are used for the query function
recursion_node_stack_size = 128;
recursion_node_stack = (it_recursion_node*) malloc(recursion_node_stack_size * sizeof(it_recursion_node));
recursion_node_stack_top = 1;
recursion_node_stack[0].start_node = nullptr;
}
IntervalTree::~IntervalTree()
{
IntervalTreeNode* x = root->left;
std::deque<IntervalTreeNode*> nodes_to_free;
if (x != nil)
{
if (x->left != nil)
{
nodes_to_free.push_back(x->left);
}
if (x->right != nil)
{
nodes_to_free.push_back(x->right);
}
delete x;
while (nodes_to_free.size() > 0)
{
x = nodes_to_free.back();
nodes_to_free.pop_back();
if (x->left != nil)
{
nodes_to_free.push_back(x->left);
}
if (x->right != nil)
{
nodes_to_free.push_back(x->right);
}
delete x;
}
}
delete nil;
delete root;
free(recursion_node_stack);
}
void IntervalTree::leftRotate(IntervalTreeNode* x)
{
IntervalTreeNode* y;
y = x->right;
x->right = y->left;
if (y->left != nil)
y->left->parent = x;
y->parent = x->parent;
if (x == x->parent->left)
x->parent->left = y;
else
x->parent->right = y;
y->left = x;
x->parent = y;
x->max_high = std::max(x->left->max_high, std::max(x->right->max_high, x->high));
y->max_high = std::max(x->max_high, std::max(y->right->max_high, y->high));
}
void IntervalTree::rightRotate(IntervalTreeNode* y)
{
IntervalTreeNode* x;
x = y->left;
y->left = x->right;
if (nil != x->right)
x->right->parent = y;
x->parent = y->parent;
if (y == y->parent->left)
y->parent->left = x;
else
y->parent->right = x;
x->right = y;
y->parent = x;
y->max_high = std::max(y->left->max_high, std::max(y->right->max_high, y->high));
x->max_high = std::max(x->left->max_high, std::max(y->max_high, x->high));
}
/// @brief Inserts z into the tree as if it were a regular binary tree
void IntervalTree::recursiveInsert(IntervalTreeNode* z)
{
IntervalTreeNode* x;
IntervalTreeNode* y;
z->left = z->right = nil;
y = root;
x = root->left;
while (x != nil)
{
y = x;
if (x->key > z->key)
x = x->left;
else
x = x->right;
}
z->parent = y;
if ((y == root) || (y->key > z->key))
y->left = z;
else
y->right = z;
}
void IntervalTree::fixupMaxHigh(IntervalTreeNode* x)
{
while (x != root)
{
x->max_high = std::max(x->high, std::max(x->left->max_high, x->right->max_high));
x = x->parent;
}
}
IntervalTreeNode* IntervalTree::insert(const Interval* new_interval)
{
IntervalTreeNode* y;
IntervalTreeNode* x;
IntervalTreeNode* new_node;
x = new IntervalTreeNode(new_interval);
recursiveInsert(x);
fixupMaxHigh(x->parent);
new_node = x;
x->red = true;
while (x->parent->red)
{
/// use sentinel instead of checking for root
if (x->parent == x->parent->parent->left)
{
y = x->parent->parent->right;
if (y->red)
{
x->parent->red = false;
y->red = false;
x->parent->parent->red = true;
x = x->parent->parent;
}
else
{
if (x == x->parent->right)
{
x = x->parent;
leftRotate(x);
}
x->parent->red = false;
x->parent->parent->red = true;
rightRotate(x->parent->parent);
}
}
else
{
y = x->parent->parent->left;
if (y->red)
{
x->parent->red = false;
y->red = false;
x->parent->parent->red = true;
x = x->parent->parent;
}
else
{
if (x == x->parent->left)
{
x = x->parent;
rightRotate(x);
}
x->parent->red = false;
x->parent->parent->red = true;
leftRotate(x->parent->parent);
}
}
}
root->left->red = false;
return new_node;
}
IntervalTreeNode* IntervalTree::getMinimum(IntervalTreeNode *x) const
{
while (x->left != nil)
x = x->left;
return x;
}
IntervalTreeNode* IntervalTree::getMaximum(IntervalTreeNode *x) const
{
while (x->right != nil)
x = x->right;
return x;
}
IntervalTreeNode* IntervalTree::getSuccessor(IntervalTreeNode* x) const
{
IntervalTreeNode* y;
if (nil != x->right)
return getMinimum(x->right);
else
{
y = x->parent;
while (y != nil && x == y->right)
{
x = y;
y = y->parent;
}
return y;
}
}
IntervalTreeNode* IntervalTree::getPredecessor(IntervalTreeNode* x) const
{
IntervalTreeNode* y;
if (nil != x->left)
return getMaximum(x->left);
else
{
y = x->parent;
while (y != nil && x == y->left)
{
x = y;
y = y->parent;
}
return y;
}
}
void IntervalTreeNode::print(IntervalTreeNode* nil, IntervalTreeNode* root) const
{
stored_interval->print();
std::cout << ", k = " << key << ", h = " << high << ", mH = " << max_high;
std::cout << " l->key = ";
if (left == nil)
std::cout << "nullptr";
else
std::cout << left->key;
std::cout << " r->key = ";
if (right == nil)
std::cout << "nullptr";
else
std::cout << right->key;
std::cout << " p->key = ";
if (parent == root)
std::cout << "nullptr";
else
std::cout << parent->key;
std::cout << " red = " << (int) red << std::endl;
}
void IntervalTree::recursivePrint(IntervalTreeNode* x) const
{
if (x != nil)
{
recursivePrint(x->left);
x->print(nil, root);
recursivePrint(x->right);
}
}
void IntervalTree::print() const
{
recursivePrint(root->left);
}
void IntervalTree::deleteFixup(IntervalTreeNode* x)
{
IntervalTreeNode* w;
IntervalTreeNode* root_left_node = root->left;
while ((!x->red) && (root_left_node != x))
{
if (x == x->parent->left)
{
w = x->parent->right;
if (w->red)
{
w->red = false;
x->parent->red = true;
leftRotate(x->parent);
w = x->parent->right;
}
if ((!w->right->red) && (!w->left->red))
{
w->red = true;
x = x->parent;
}
else
{
if (!w->right->red)
{
w->left->red = false;
w->red = true;
rightRotate(w);
w = x->parent->right;
}
w->red = x->parent->red;
x->parent->red = false;
w->right->red = false;
leftRotate(x->parent);
x = root_left_node;
}
}
else
{
w = x->parent->left;
if (w->red)
{
w->red = false;
x->parent->red = true;
rightRotate(x->parent);
w = x->parent->left;
}
if ((!w->right->red) && (!w->left->red))
{
w->red = true;
x = x->parent;
}
else
{
if (!w->left->red)
{
w->right->red = false;
w->red = true;
leftRotate(w);
w = x->parent->left;
}
w->red = x->parent->red;
x->parent->red = false;
w->left->red = false;
rightRotate(x->parent);
x = root_left_node;
}
}
}
x->red = false;
}
void IntervalTree::deleteNode(const Interval* ivl)
{
IntervalTreeNode* node = recursiveSearch(root, ivl);
if (node != nil)
deleteNode(node);
}
IntervalTreeNode* IntervalTree::recursiveSearch(IntervalTreeNode* node, const Interval* ivl) const
{
if (node != nil)
{
if (node->stored_interval == ivl)
return node;
IntervalTreeNode* left = recursiveSearch(node->left, ivl);
if (left != nil)
return left;
IntervalTreeNode* right = recursiveSearch(node->right, ivl);
if (right != nil)
return right;
}
return nil;
}
const Interval* IntervalTree::deleteNode(IntervalTreeNode* z)
{
IntervalTreeNode* y;
IntervalTreeNode* x;
const Interval* node_to_delete = z->stored_interval;
y = ((z->left == nil) || (z->right == nil)) ? z : getSuccessor(z);
x = (y->left == nil) ? y->right : y->left;
if (root == (x->parent = y->parent))
{
root->left = x;
}
else
{
if (y == y->parent->left)
{
y->parent->left = x;
}
else
{
y->parent->right = x;
}
}
/// @brief y should not be nil in this case
/// y is the node to splice out and x is its child
if (y != z)
{
y->max_high = -SimTime::getMaxTime(); // -std::numeric_limits<double>::max();
y->left = z->left;
y->right = z->right;
y->parent = z->parent;
z->left->parent = z->right->parent = y;
if (z == z->parent->left)
z->parent->left = y;
else
z->parent->right = y;
fixupMaxHigh(x->parent);
if (!(y->red))
{
y->red = z->red;
deleteFixup(x);
}
else
y->red = z->red;
delete z;
}
else
{
fixupMaxHigh(x->parent);
if (!(y->red))
deleteFixup(x);
delete y;
}
return node_to_delete;
}
/// @brief returns 1 if the intervals overlap, and 0 otherwise
bool overlap(simtime_t a1, simtime_t a2, simtime_t b1, simtime_t b2)
{
if (a1 <= b1)
{
return (b1 <= a2);
}
else
{
return (a1 <= b2);
}
}
std::deque<const Interval*> IntervalTree::query(simtime_t low, simtime_t high)
{
std::deque<const Interval*> result_stack;
IntervalTreeNode* x = root->left;
bool run = (x != nil);
current_parent = 0;
while (run)
{
if (overlap(low, high, x->key, x->high))
{
result_stack.push_back(x->stored_interval);
recursion_node_stack[current_parent].try_right_branch = true;
}
if (x->left->max_high >= low)
{
if (recursion_node_stack_top == recursion_node_stack_size)
{
recursion_node_stack_size *= 2;
recursion_node_stack = (it_recursion_node *) realloc(recursion_node_stack,
recursion_node_stack_size * sizeof(it_recursion_node));
if (recursion_node_stack == nullptr)
exit(1);
}
recursion_node_stack[recursion_node_stack_top].start_node = x;
recursion_node_stack[recursion_node_stack_top].try_right_branch = false;
recursion_node_stack[recursion_node_stack_top].parent_index = current_parent;
current_parent = recursion_node_stack_top++;
x = x->left;
}
else
x = x->right;
run = (x != nil);
while ((!run) && (recursion_node_stack_top > 1))
{
if (recursion_node_stack[--recursion_node_stack_top].try_right_branch)
{
x = recursion_node_stack[recursion_node_stack_top].start_node->right;
current_parent = recursion_node_stack[recursion_node_stack_top].parent_index;
recursion_node_stack[current_parent].try_right_branch = true;
run = (x != nil);
}
}
}
return result_stack;
}
} // namespace inet
| 26.5 | 110 | 0.521435 | LarryNguyen |
5d69743b746878d5279f11d81aef20feb182a4f4 | 32,801 | cpp | C++ | bag_rdr.cpp | lukehutch/bag_rdr | e94c196a9449d69808dbf2127cec96ee7367c031 | [
"MIT"
] | null | null | null | bag_rdr.cpp | lukehutch/bag_rdr | e94c196a9449d69808dbf2127cec96ee7367c031 | [
"MIT"
] | null | null | null | bag_rdr.cpp | lukehutch/bag_rdr | e94c196a9449d69808dbf2127cec96ee7367c031 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2018 Starship Technologies, Inc.
*
* 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 "bag_rdr.hpp"
#include "common/array_view.hpp"
#include "common/file_handle.hpp"
#include "common/string_view.hpp"
#include "common/common_timestamp.hpp"
#include "common/common_optional.hpp"
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <numeric>
#ifndef DISABLE_BZ2
#include <bzlib.h>
#endif // DISABLE_BZ2
#ifdef BAG_RDR_USE_SYSTEM_LZ4
#include <lz4frame.h>
#else
#include <roslz4/lz4s.h>
#endif
using common::result;
using common::ok;
using common::unix_err;
static bool assert_print_base(bool result, const char* const statement)
{
if (!result)
fprintf(stderr, "bag_rdr: assertion failed: (%s)\n", statement);
return result;
}
static bool assert_print_base_value(bool result, const char* const statement, size_t actual_value)
{
if (!result)
fprintf(stderr, "bag_rdr: assertion failed: (%s) [value was %zu]\n", statement, actual_value);
return result;
}
#define assert_print(statement) (assert_print_base(statement, #statement))
#define assert_printv(statement, actual_value) (assert_print_base_value(statement, #statement, actual_value))
template <typename T>
bool extract_type(common::array_view<const char> from, T& to)
{
if (from.size() < sizeof(T))
return false;
to = *reinterpret_cast<const T*>(from.data());
return true;
}
template <>
bool extract_type<common::string_view>(common::array_view<const char> from, common::string_view& to)
{
to = common::string_view{from};
return true;
}
template <typename T>
common::array_view<const char> extract_advance(common::array_view<const char> from, T& to)
{
if (!extract_type(from, to))
return {};
return from.advance(sizeof(T));
}
static common::array_view<const char> extract_len_memory(common::array_view<const char> from)
{
uint32_t byte_count;
if (!extract_type<uint32_t>(from, byte_count))
return {};
const auto contained = from.advance(sizeof(uint32_t)).head(byte_count);
if (contained.end() > from.end())
return {};
return contained;
}
struct record
{
common::array_view<const char> real_range;
common::array_view<const char> memory_header;
common::array_view<const char> memory_data;
record(common::array_view<const char> memory_range)
{
if (!memory_range.size())
return;
if (!assert_printv(memory_range.size() >= sizeof(uint32_t), memory_range.size()))
return;
memory_header = extract_len_memory(memory_range);
if (!memory_header.size())
return;
common::array_view<const char> data_block {memory_header.end(), memory_range.end()};
memory_data = extract_len_memory(data_block);
if (!assert_print(memory_data.size()))
return;
real_range = {memory_range.begin(), memory_data.end()};
}
bool is_null_record() const
{
return (real_range.size() == 0);
}
};
struct header
{
common::array_view<const char> real_range;
common::string_view name, value;
header(common::array_view<const char> memory_range)
{
common::string_view inner {extract_len_memory(memory_range)};
if (!inner.size())
return;
real_range = {memory_range.begin(), inner.end()};
auto sep = std::find(inner.begin(), inner.end(), '=');
name = {inner.begin(), sep};
value = {sep+1, inner.end()};
}
enum class op
{
BAG_HEADER = 0x03,
CHUNK = 0x05,
CONNECTION = 0x07,
MESSAGE_DATA = 0x02,
INDEX_DATA = 0x04,
CHUNK_INFO = 0x06,
UNSET = 0xff,
};
static const char* op_string(op bag_op)
{
switch (bag_op) {
case op::BAG_HEADER: return "bag_header";
case op::CHUNK: return "chunk";
case op::CONNECTION: return "connection";
case op::MESSAGE_DATA: return "message_data";
case op::INDEX_DATA: return "index_data";
case op::CHUNK_INFO: return "chunk_info";
case op::UNSET: return "<op_unset>";
}
return "<op_invalid>";
}
};
struct headers
{
common::array_view<const char> memory_range;
headers(common::array_view<const char> memory_range)
: memory_range{memory_range}
{ }
struct iterator
{
common::array_view<const char> remaining;
header current;
iterator(common::array_view<const char> remaining)
: remaining(remaining)
, current(remaining)
{
}
const header& operator*() const
{
return current;
}
const header* operator->() const
{
return ¤t;
}
iterator operator++()
{
if (!current.real_range.size())
remaining = {};
else
remaining = {current.real_range.end(), remaining.end()};
current = remaining;
return *this;
}
bool operator!=(const iterator& other)
{
return remaining != other.remaining;
}
};
iterator begin() const
{
return iterator{memory_range};
}
iterator end() const
{
return iterator{{}};
}
template <typename T>
size_t extract_headers_inner(const header& hdr, const char* field, common::optional<T>& t)
{
if (hdr.name != field)
return 0;
T val;
if (extract_type(hdr.value, val)) {
t = std::move(val);
}
return 1;
}
template <typename T, typename... Ts>
size_t extract_headers_inner(const header& hdr, const char* field, common::optional<T>& t, Ts&... remaining_string_type_pairs)
{
return extract_headers_inner(hdr, field, t) || extract_headers_inner(hdr, remaining_string_type_pairs...);
}
template <typename... Ts>
size_t extract_headers(Ts&... string_type_pairs)
{
size_t count_filled = 0;
enum { TOTAL_PAIR_COUNT = sizeof...(string_type_pairs)/2 };
for (const header& h: *this) {
count_filled += extract_headers_inner(h, string_type_pairs...);
if (count_filled == TOTAL_PAIR_COUNT)
break;
}
return count_filled;
}
};
struct chunk_info
{
common::timestamp start_timestamp, end_timestamp;
int32_t message_count;
};
struct chunk
{
chunk(record r);
common::array_view<const char> outer_memory;
common::array_view<const char> memory;
common::array_view<const char> uncompressed;
std::vector<char> uncompressed_buffer;
int32_t uncompressed_size = 0;
chunk_info info;
enum chunk_type {
NORMAL,
BZ2,
LZ4,
} type;
bool decompress();
common::array_view<const char> get_uncompressed()
{
if (uncompressed.size())
return uncompressed;
if (decompress())
return uncompressed;
return common::array_view<const char>{};
}
};
struct index_record
{
uint32_t time_secs;
uint32_t time_nsecs;
int32_t offset;
common::timestamp to_stamp() const { return common::timestamp{time_secs, time_nsecs}; }
} __attribute__((packed));
struct index_block
{
common::array_view<const char> memory;
chunk* into_chunk;
size_t count() const { return memory.size() / sizeof(index_record); }
common::array_view<const index_record> as_records() const
{
return common::array_view<const index_record>{reinterpret_cast<const index_record*>(memory.data()), count()};
}
};
struct connection_data
{
common::string_view topic, type, md5sum, message_definition;
common::string_view callerid;
bool latching = false;
connection_data() = default;
connection_data(common::array_view<const char> memory)
{
common::optional<common::string_view> c_topic, c_type, c_md5sum, c_message_definition, c_callerid, c_latching;
headers{memory}.extract_headers("topic", c_topic, "type", c_type, "md5sum", c_md5sum,
"message_definition", c_message_definition, "callerid", c_callerid,
"latching", c_latching);
// The inner topic only applies for mapped topics
if (!assert_print(c_type && c_md5sum && c_message_definition))
return;
if (c_topic)
topic = c_topic.get();
type = c_type.get();
md5sum = c_md5sum.get();
message_definition = c_message_definition.get();
callerid = c_callerid.get_or({});
latching = c_latching && (c_latching.get() == "1");
}
};
struct bag_rdr::connection_record
{
std::vector<index_block> blocks;
common::string_view topic;
connection_data data;
};
chunk::chunk(record r)
: outer_memory(r.real_range)
, memory(r.memory_data)
, info{.start_timestamp={}, .end_timestamp={}, .message_count=0}
{
common::optional<int32_t> size;
common::optional<common::string_view> compression_string;
headers{r.memory_header}.extract_headers("size", size, "compression", compression_string);
if (!assert_print(size && compression_string))
return;
if (!assert_print((size.get() > 64) && (size.get() < 1*1024*1024*1024)))
return;
if (compression_string == "none") {
type = NORMAL;
uncompressed = memory;
} else if (compression_string == "bz2") {
type = BZ2;
uncompressed_size = size.get();
} else if (compression_string == "lz4") {
type = LZ4;
uncompressed_size = size.get();
} else {
fprintf(stderr, "chunk: unknown compression type '%.*s'\n", int(compression_string->size()), compression_string->data());
return;
}
}
#ifdef BAG_RDR_USE_SYSTEM_LZ4
struct lz4f_ctx
{
LZ4F_decompressionContext_t ctx{nullptr};
~lz4f_ctx() {
if (ctx)
LZ4F_freeDecompressionContext(ctx);
}
operator LZ4F_decompressionContext_t() {
return ctx;
}
};
static bool s_decompress_lz4(common::array_view<const char> memory, common::array_view<char> to)
{
lz4f_ctx ctx;
LZ4F_errorCode_t code = LZ4F_createDecompressionContext(&ctx.ctx, LZ4F_VERSION);
if (LZ4F_isError(code))
return code;
while (memory.size() && to.size()) {
size_t dest_size = to.size();
size_t src_size = memory.size();
size_t ret = LZ4F_decompress(ctx,
(void*) to.begin(), &dest_size,
(const void*) memory.begin(), &src_size,
nullptr);
if (LZ4F_isError(ret)) {
fprintf(stderr, "chunk::decompress: lz4 decompression returned %zu, expected %zu\n", ret, to.size());
return false;
}
memory = memory.advance(src_size);
to = to.advance(dest_size);
}
if (memory.size() || to.size())
fprintf(stderr, "chunk::decompress: lz4 decompression left %zu/%zu bytes in buffer\n", memory.size(), to.size());
return (memory.size() == 0) && (to.size() == 0);
}
#else
static bool s_decompress_lz4(common::array_view<const char> memory, common::array_view<char> to)
{
unsigned int dest_len = to.size();
int lz4_ret = roslz4_buffToBuffDecompress((char*)memory.data(), memory.size(),
to.data(), &dest_len);
if (lz4_ret != ROSLZ4_OK) {
fprintf(stderr, "chunk::decompress: lz4 decompression returned %d, expected %zu\n", lz4_ret, to.size());
return false;
}
return true;
}
#endif
bool chunk::decompress()
{
if (!assert_print((type == BZ2) || (type == LZ4)))
return false;
uncompressed_buffer.resize(uncompressed_size);
switch (type) {
case BZ2: {
#ifndef DISABLE_BZ2
const int bzapi_small = 0;
const int bzapi_verbosity = 0;
unsigned int dest_len = uncompressed_buffer.size();
int bzip2_ret = BZ2_bzBuffToBuffDecompress(uncompressed_buffer.data(), &dest_len,
(char*) memory.data(), memory.size(),
bzapi_small,
bzapi_verbosity);
if (bzip2_ret != BZ_OK) {
fprintf(stderr, "chunk::decompress: bzip2 decompression returned %d\n", bzip2_ret);
return false;
}
#else // DISABLE_BZ2
fprintf(stderr, "chunk::decompress: bzip2 disabled\n");
return false;
#endif // DISABLE_BZ2
break;
}
case LZ4: {
if (!s_decompress_lz4(memory, uncompressed_buffer))
return false;
}
case NORMAL: break;
}
uncompressed = uncompressed_buffer;
return true;
}
struct mmap_handle_t
{
common::array_view<char> memory;
mmap_handle_t& operator=(mmap_handle_t&& other)
{
std::swap(memory, other.memory);
return *this;
}
~mmap_handle_t()
{
if (memory.size()) {
if (::munmap(memory.data(), memory.size()) != 0)
fprintf(stderr, "bag_rdr: failed munmap (%m)\n");
}
}
};
struct bag_rdr::priv
{
std::string filename;
common::file_handle file_handle;
mmap_handle_t mmap_handle;
common::array_view<const char> memory;
common::string_view version_string;
common::array_view<const char> content;
std::vector<connection_record> connections;
std::vector<chunk> chunks;
};
bag_rdr::bag_rdr()
: d(new priv)
{
}
bag_rdr::~bag_rdr()
{
delete d;
}
bool bag_rdr::open(const char* filename)
{
return open_detailed(filename).is_ok();
}
result<ok, unix_err> bag_rdr::open_detailed(const char* filename)
{
result_try(internal_map_file(filename));
if (!internal_read_initial().size()) {
return unix_err{EFAULT};
}
if (!internal_load_records()) {
return unix_err{ESPIPE};
}
return ok{};
}
result<ok, unix_err> bag_rdr::open_memory(array_view<const char> memory)
{
d->memory = memory;
d->filename = "<memory>";
if (!internal_read_initial().size()) {
return unix_err{EFAULT};
}
if (!internal_load_records()) {
return unix_err{ESPIPE};
}
return ok{};
}
result<ok, unix_err> bag_rdr::internal_map_file(const char* filename)
{
result_try(d->file_handle.open(filename));
size_t file_size = d->file_handle.size();
if (!file_size)
return unix_err{ERANGE};
void* ptr = ::mmap(nullptr, file_size, PROT_READ, MAP_PRIVATE, ::fileno(d->file_handle.file), 0);
if (ptr == MAP_FAILED) {
fprintf(stderr, "bag_rdr: mmap of file '%s' failed (%m)\n", filename);
return unix_err::current();
}
d->memory = common::array_view<const char>{reinterpret_cast<const char*>(ptr), file_size};
d->mmap_handle = mmap_handle_t{common::array_view<char>{(char*)ptr, file_size}};
d->filename = filename;
return ok{};
}
common::string_view bag_rdr::internal_read_initial()
{
if (!assert_print(d->memory.size()))
return {};
common::string_view str {d->memory};
const common::string_view bag_magic_prefix {"#ROSBAG V"};
if (!assert_print(str.begins_with(bag_magic_prefix)))
return {};
common::string_view version_block = str.advance(bag_magic_prefix.size());
const void* newline_found = ::memchr(const_cast<char*>(version_block.data()), '\n', std::min<size_t>(str.size(), 256));
if (!assert_print(newline_found))
return {};
d->version_string = {version_block.data(), (const char*) newline_found};
d->content = {((const char*) newline_found) + 1, d->memory.end()};
return d->version_string;
}
bool bag_rdr::internal_load_records()
{
common::array_view<const char> remaining = d->content;
bool had_chunk = false;
// offset into file of first record after chunk/index_data
using lld_t = long long;
int64_t index_pos = 0;
while (remaining.size()) {
record r{remaining};
if (r.is_null_record()) {
const int64_t pos = remaining.data() - d->memory.begin();
if (pos < index_pos) {
remaining = {d->memory.data() + index_pos, d->memory.end()};
continue;
}
fprintf(stderr, "load_records: null record past bag_hdr.index_pos (%lld > %lld)\n", lld_t(pos), lld_t(index_pos));
return false;
}
headers hdrs{r.memory_header};
common::optional<int8_t> op_hdr;
hdrs.extract_headers("op", op_hdr);
remaining = remaining.advance(r.real_range.size());
if (!assert_print(bool(op_hdr)))
return false;
header::op op = header::op(op_hdr.get());
switch (op) {
case header::op::BAG_HEADER: {
common::optional<int32_t> conn_count, chunk_count;
common::optional<int64_t> c_index_pos;
hdrs.extract_headers("conn_count", conn_count, "chunk_count", chunk_count, "index_pos", c_index_pos);
if (!assert_print(conn_count && chunk_count && c_index_pos))
return false;
// the empty bag
if ((conn_count.get() == 0) && (chunk_count.get() == 0))
return true;
if (!assert_print((conn_count.get() > 0) && (chunk_count.get() > 0) && (c_index_pos.get() > 64)))
return false;
d->connections.resize(conn_count.get());
d->chunks.reserve(chunk_count.get());
index_pos = *c_index_pos;
break;
}
case header::op::CHUNK: {
had_chunk = true;
d->chunks.emplace_back(r);
break;
}
case header::op::INDEX_DATA: {
if (!assert_print(had_chunk))
return false;
common::optional<int32_t> ver, conn, count;
hdrs.extract_headers("ver", ver, "conn", conn, "count", count);
if (!assert_print(ver && conn && count))
continue;
assert_printv(count.get()*sizeof(index_record) == r.memory_data.size(), count.get()*sizeof(index_record));
const int32_t conn_id = conn.get();
if (!assert_print((conn_id >= 0) && (size_t(conn_id) < d->connections.size())))
continue;
d->connections[conn.get()].blocks.emplace_back(index_block{.memory=r.memory_data, .into_chunk=&d->chunks.back()});
break;
}
case header::op::CONNECTION: {
common::optional<int32_t> conn;
common::optional<common::string_view> topic;
hdrs.extract_headers("conn", conn, "topic", topic);
if (!assert_print(conn && topic))
continue;
const int32_t conn_id = conn.get();
if (!assert_print((conn_id >= 0) && (size_t(conn_id) < d->connections.size())))
continue;
connection_data data{r.memory_data};
if (!data.md5sum.size())
continue;
d->connections[conn_id].topic = topic.get();
d->connections[conn_id].data = data;
break;
}
case header::op::MESSAGE_DATA: {
break;
}
case header::op::CHUNK_INFO: {
common::optional<int64_t> chunk_pos;
common::optional<int32_t> ver, count;
common::optional<common::timestamp> start_time, end_time;
hdrs.extract_headers("ver", ver, "chunk_pos", chunk_pos, "count", count, "start_time", start_time, "end_time", end_time);
if (!assert_print(ver && chunk_pos && count && start_time && end_time))
continue;
auto chunk_it = std::find_if(d->chunks.begin(), d->chunks.end(), [this, &chunk_pos] (const chunk& c) {
return (c.outer_memory.data() - d->memory.data()) == chunk_pos.get();
});
if (!assert_print(chunk_it != d->chunks.end()))
continue;
assert_print(chunk_it->info.message_count == 0);
chunk_it->info = chunk_info{start_time.get(), end_time.get(), count.get()};
static_assert(sizeof(common::timestamp) == sizeof(int64_t), "size of common::timestamp not binary compatible with bag timestamps");
break;
}
case header::op::UNSET:
default:
fprintf(stderr, "bag_rdr: Unknown record operation 0x%hhx\n", int8_t(op));
}
}
return true;
}
common::timestamp bag_rdr::start_timestamp() const
{
if (d->chunks.empty())
return common::timestamp{};
return d->chunks.front().info.start_timestamp;
}
common::timestamp bag_rdr::end_timestamp() const
{
if (d->chunks.empty())
return common::timestamp{};
return d->chunks.back().info.end_timestamp;
}
size_t bag_rdr::size() const
{
size_t ret = 0;
for (const connection_record& c: d->connections)
for (const index_block& block: c.blocks)
ret += block.count();
return ret;
}
size_t bag_rdr::file_size() const
{
return d->file_handle.size();
}
bag_rdr::view::view(const bag_rdr& rdr)
: rdr(rdr)
{
}
void bag_rdr::view::ensure_indices()
{
if (m_connections)
return;
m_connections.reset_default();
m_connections->reserve(rdr.d->connections.size());
for (auto& conn : rdr.d->connections)
m_connections->push_back(&conn);
}
bag_rdr::view bag_rdr::get_view() const
{
return view{*this};
}
static void add_connection_ptr(std::vector<bag_rdr::connection_record*>& connection_ptrs, std::vector<bag_rdr::connection_record>& connections, common::string_view topic)
{
for (bag_rdr::connection_record& conn : connections) {
if (conn.data.topic.size() && (conn.topic != conn.data.topic)) {
fprintf(stderr, "bag_rdr: Inner topic [%zu]'%.*s' doesn't match outer '%.*s', not yet handled.\n",
conn.data.topic.size(), conn.data.topic.sizei(), conn.data.topic.data(),
conn.topic.sizei(), conn.topic.data());
}
if (conn.topic == topic) {
auto it = std::find(connection_ptrs.begin(), connection_ptrs.end(), &conn);
if (it != connection_ptrs.end())
break;
connection_ptrs.emplace_back(&conn);
}
}
}
void bag_rdr::view::set_topics(common::array_view<const std::string> topics)
{
m_connections.reset_default();
m_connections->reserve(topics.size());
for (const std::string& topic : topics)
add_connection_ptr(*m_connections, rdr.d->connections, topic);
}
void bag_rdr::view::set_topics(array_view<const char*> topics)
{
m_connections.reset_default();
m_connections->reserve(topics.size());
for (const char* topic : topics)
add_connection_ptr(*m_connections, rdr.d->connections, topic);
}
void bag_rdr::view::set_topics(std::initializer_list<const char*> topics)
{
m_connections.reset_default();
m_connections->reserve(topics.size());
for (const char* topic : topics)
add_connection_ptr(*m_connections, rdr.d->connections, topic);
}
void bag_rdr::view::set_topics(array_view<common::string_view> topics)
{
m_connections.reset_default();
m_connections->reserve(topics.size());
for (const common::string_view& topic : topics)
add_connection_ptr(*m_connections, rdr.d->connections, topic);
}
std::vector<common::string_view> bag_rdr::view::present_topics()
{
ensure_indices();
std::vector<common::string_view> ret;
for (const auto& conn : *m_connections) {
common::string_view topic = conn->data.topic;
auto it = std::find(ret.begin(), ret.end(), topic);
if (it == ret.end())
ret.emplace_back(std::move(topic));
}
return ret;
}
bool bag_rdr::view::has_topic(common::string_view topic)
{
ensure_indices();
for (const auto& conn : *m_connections) {
if (conn->data.topic == topic)
return true;
}
return false;
}
void bag_rdr::view::for_each_connection(const std::function<void (const connection_data& data)>& fn)
{
ensure_indices();
for (const auto& conn : *m_connections) {
fn(connection_data {
.topic = conn->topic,
.datatype = conn->data.type,
.md5sum = conn->data.md5sum,
.msg_def = conn->data.message_definition,
.callerid = conn->data.callerid,
.latching = conn->data.latching,
});
}
}
static bool increment_pos_ref(const bag_rdr::connection_record& conn, bag_rdr::view::iterator::pos_ref& pos)
{
assert_print(pos.block != -1);
const index_block& block = conn.blocks[pos.block];
if (++pos.record == int(block.as_records().size())) {
pos.record = 0;
if (++pos.block == int(conn.blocks.size())) {
pos.block = -1;
return false;
}
}
return true;
}
struct lowest_set
{
common::timestamp stamp;
int index = -1;
explicit operator bool() const
{
return index >= 0;
}
};
static common::timestamp pos_ref_timestamp(const bag_rdr::view::iterator& it, int32_t index)
{
const bag_rdr::view::iterator::pos_ref& pos = it.connection_positions[index];
const bag_rdr::connection_record& conn = *it.v.m_connections.value_unchecked()[index];
const index_block& block = conn.blocks[pos.block];
const index_record& record = block.as_records()[pos.record];
return record.to_stamp();
}
static void iterator_construct_connection_order(bag_rdr::view::iterator& it)
{
it.connection_order.clear();
for (size_t i = 0; i < it.connection_positions.size(); ++i) {
const bag_rdr::view::iterator::pos_ref& pos = it.connection_positions[i];
if (pos.block == -1)
continue;
const bag_rdr::connection_record& conn = *it.v.m_connections.value_unchecked()[i];
if ((size_t)pos.block >= conn.blocks.size()) {
fprintf(stderr, "bag_rdr: invalid bag: conn index referenced non-existent block (index: %d, conn.blocks.size(): %zu).\n", pos.block, conn.blocks.size());
continue;
}
it.connection_order.emplace_back(int32_t(i));
}
std::sort(it.connection_order.begin(), it.connection_order.end(), [&] (int32_t ia, int32_t ib) {
return pos_ref_timestamp(it, ia) < pos_ref_timestamp(it, ib);
});
}
// assumes we just consumed connection_order[0]
static void iterator_update_connection_order(bag_rdr::view::iterator& it)
{
size_t head_index = it.connection_order[0];
common::timestamp connection_next_stamp = pos_ref_timestamp(it, head_index);
if (it.v.m_end_time && (connection_next_stamp > it.v.m_end_time)) {
it.connection_order.erase(it.connection_order.begin());
return;
}
auto elem_above = std::lower_bound(it.connection_order.begin() + 1, it.connection_order.end(), connection_next_stamp, [&] (int32_t index, const common::timestamp& find_stamp) {
return pos_ref_timestamp(it, index) < find_stamp;
});
size_t index_after_first = std::distance(it.connection_order.begin(), elem_above) - 1;
if (index_after_first == 0)
return;
auto pos = std::move(it.connection_order.begin() + 1, elem_above, it.connection_order.begin());
*pos = head_index;
}
bag_rdr::view::iterator& bag_rdr::view::iterator::operator++()
{
if (connection_positions.empty())
return *this;
const size_t old_head_index = connection_order[0];
if (increment_pos_ref(*v.m_connections.value_unchecked()[old_head_index], connection_positions[old_head_index])) {
iterator_update_connection_order(*this);
} else {
connection_order.erase(connection_order.begin());
}
if (!connection_order.size()) {
connection_positions.clear();
} else {
const size_t head_index = connection_order[0];
const connection_record& conn = *v.m_connections.value_unchecked()[head_index];
const pos_ref& head = connection_positions[head_index];
const index_block& block = conn.blocks[head.block];
common::array_view<const char> chunk_memory = block.into_chunk->get_uncompressed();
if (!chunk_memory.size()) {
connection_positions.clear();
return *this;
}
}
return *this;
}
bag_rdr::view::iterator bag_rdr::view::begin()
{
ensure_indices();
return iterator{*this, iterator::constructor_start_tag{}};
}
bag_rdr::view::iterator bag_rdr::view::end()
{
return iterator{*this};
}
static bag_rdr::view::iterator::pos_ref find_starting_position(const bag_rdr::view& v,
const bag_rdr::connection_record& conn)
{
bag_rdr::view::iterator::pos_ref pos{0, 0};
for (; pos.block < int(conn.blocks.size()); ++pos.block) {
const index_block& block = conn.blocks[pos.block];
const auto block_records = block.as_records();
for (pos.record = 0; pos.record < int(block_records.size()); ++pos.record) {
const index_record& record = block_records[pos.record];
if (v.m_end_time && (record.to_stamp() > v.m_end_time)) {
pos.block = -1;
return {-1, 0};
}
if (record.to_stamp() >= v.m_start_time)
return pos;
}
}
return {-1, 0};
}
bag_rdr::view::iterator::iterator(const bag_rdr::view& v, constructor_start_tag)
: v(v)
{
connection_positions.resize(v.m_connections->size(), pos_ref{0, 0});
if (v.m_start_time) {
for (size_t i = 0; i < connection_positions.size(); ++i) {
const connection_record& conn = *v.m_connections.value_unchecked()[i];
connection_positions[i] = find_starting_position(v, conn);
}
}
iterator_construct_connection_order(*this);
if (!connection_order.size()) {
connection_positions.clear();
return;
}
const size_t head_index = connection_order[0];
const connection_record& conn = *v.m_connections.value_unchecked()[head_index];
const pos_ref& head = connection_positions[head_index];
const index_block& block = conn.blocks[head.block];
common::array_view<const char> chunk_memory = block.into_chunk->get_uncompressed();
if (!chunk_memory.size()) {
connection_positions.clear();
}
}
bag_rdr::view::message bag_rdr::view::iterator::operator*() const
{
if (!assert_print(connection_order.size() > 0))
abort();
const size_t head_index = connection_order[0];
const connection_record& conn = *v.m_connections.value_unchecked()[head_index];
const pos_ref& head = connection_positions[head_index];
const index_block& block = conn.blocks[head.block];
const index_record& rec = block.as_records()[head.record];
common::array_view<const char> chunk_memory = block.into_chunk->get_uncompressed();
if (!chunk_memory.size())
abort();
common::array_view<const char> record_memory = chunk_memory.advance(rec.offset);
record r{record_memory};
return message{.stamp=rec.to_stamp(), .md5=conn.data.md5sum, .message_data_block=r.memory_data, .connection=&conn};
}
common::string_view bag_rdr::view::message::topic() const
{
return connection->topic;
}
common::string_view bag_rdr::view::message::data_type() const
{
return connection->data.type;
}
common::string_view bag_rdr::view::message::message_definition() const
{
return connection->data.message_definition;
}
bool bag_rdr::view::message::is_latching() const
{
return connection->data.latching;
}
| 32.284449 | 180 | 0.622847 | lukehutch |
5d6a37543d884efb9d0ed977bd65758ab4d70d45 | 350 | cpp | C++ | week28/F.cpp | webturing/ACMProgramming2020 | 94c01645420c5fbc303a0eb1ed74ebb6679ab398 | [
"MIT"
] | 3 | 2020-05-31T08:41:56.000Z | 2020-09-27T15:14:03.000Z | week28/F.cpp | webturing/ACMProgramming2020 | 94c01645420c5fbc303a0eb1ed74ebb6679ab398 | [
"MIT"
] | null | null | null | week28/F.cpp | webturing/ACMProgramming2020 | 94c01645420c5fbc303a0eb1ed74ebb6679ab398 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
using namespace std;
int main(int argc, char const *argv[]) {
for (double n, a; cin >> n >> a;) {
double t = n * 1000 / 3600 / a;
cout << setiosflags(ios::fixed) << setprecision(3)
<< -n * 1000 / 3600 * t / 2 << endl;
}
return 0;
} | 26.923077 | 58 | 0.551429 | webturing |
5d6caa686364a210fef45b77563ab8c435466a96 | 9,044 | hpp | C++ | src/shared/charov.hpp | gtaisbetterthanfn/modloader | 18f85c2766d4e052a452c7b1d8f5860a6daac24b | [
"MIT"
] | 186 | 2015-01-18T05:46:11.000Z | 2022-03-22T10:03:44.000Z | src/shared/charov.hpp | AlisonMDL/modloader | 18f85c2766d4e052a452c7b1d8f5860a6daac24b | [
"MIT"
] | 82 | 2015-01-14T01:02:04.000Z | 2022-03-20T23:55:59.000Z | src/shared/charov.hpp | AlisonMDL/modloader | 18f85c2766d4e052a452c7b1d8f5860a6daac24b | [
"MIT"
] | 34 | 2015-01-07T11:17:00.000Z | 2022-02-28T00:16:20.000Z | /*
* Wide char overload for char functions
* (C) 2012 Denilson das Mercês Amorim <dma_2012@hotmail.com>
*
* This source code is offered for use in the public domain. You may
* use, modify or distribute it freely.
*
* This code is distributed in the hope that it will be useful but
* WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
* DISCLAIMED. This includes but is not limited to warranties of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#ifndef _CHAROV_HPP_
#define _CHAROV_HPP_
#include <cstdio>
#include <cstdarg>
#include <cwchar>
#if defined _WIN32
#if defined __GNUG__
// on MinGW, check if have broken vswprintf
#ifndef _GLIBCXX_HAVE_BROKEN_VSWPRINTF
#define CHAR_OVERLOAD_FIXED_BROKEN_SPRINTF
#endif
#elif _MSC_VER >= 1400 // MSVC 2005
#define CHAR_OVERLOAD_FIXED_BROKEN_SPRINTF
#endif
#endif
namespace cwc
{
//=================================== stdio ===================================//
// testing WEOF\EOF
inline bool is_eof(wint_t c)
{
return c == WEOF;
}
inline bool is_eof(wchar_t c)
{
return c == WEOF;
}
inline bool is_eof(int c)
{
return c == EOF;
}
inline bool is_eof(char c)
{
return c == EOF;
}
// printf & scanf //
inline int vfprintf(FILE* stream, const wchar_t* format, va_list arg)
{
return std::vfwprintf(stream, format, arg);
}
// sprintf is broken on windows, sorry for the incovenience
#if !defined(_WIN32) || defined CHAR_OVERLOAD_USE_BROKEN_SPRINTF || defined CHAR_OVERLOAD_FIXED_BROKEN_SPRINTF
#if !defined(_WIN32) || defined CHAR_OVERLOAD_FIXED_BROKEN_SPRINTF
#define CHAR_OVERLOAD_SPRINTF_IS_OKAY
#endif
inline int vsnprintf(wchar_t* s, size_t len, const wchar_t* format, va_list arg)
{
#ifdef CHAR_OVERLOAD_SPRINTF_IS_OKAY
return std::vswprintf(s, len, format, arg);
#else
return ::vswprintf(s, format, arg);
#endif
}
inline int vsprintf(wchar_t* s, const wchar_t* format, va_list arg)
{
return vsnprintf(s, -1, format, arg);
}
inline int snprintf(wchar_t* s, size_t n, const wchar_t* format, ...)
{
va_list va; int x; va_start(va, format);
x = vsnprintf(s, n, format, va);
va_end(va);
return x;
}
inline int sprintf(wchar_t* s, const wchar_t* format, ...)
{
va_list va; int x; va_start(va, format);
x = vsprintf(s, format, va);
va_end(va);
return x;
}
//#undef CHAR_OVERLOAD_SPRINTF_IS_OKAY
#endif // sprintf's
inline int vprintf(const wchar_t* format, va_list arg)
{
return std::vwprintf(format, arg);
}
inline int fprintf(FILE* stream, const wchar_t* format, ...)
{
va_list va; int x; va_start(va, format);
x = vfprintf(stream, format, va);
va_end(va);
return x;
}
inline int wprintf(const wchar_t* format, ...)
{
va_list va; int x; va_start(va, format);
x = vprintf(format, va);
va_end(va);
return x;
}
inline int vfscanf(FILE* stream, const wchar_t* format, va_list arg)
{
return std::vfwscanf(stream, format, arg);
}
inline int vsscanf(const wchar_t* s, const wchar_t* format, va_list arg)
{
return std::vswscanf(s, format, arg);
}
inline int vscanf(const wchar_t* format, va_list arg)
{
return std::vwscanf(format, arg);
}
inline int fscanf(FILE* stream, const wchar_t* format, ... )
{
va_list va; int x; va_start(va, format);
x = vfscanf(stream, format, va);
va_end(va);
return x;
}
inline int sscanf(const wchar_t* s, const wchar_t* format, ...)
{
va_list va; int x; va_start(va, format);
x = vsscanf(s, format, va);
va_end(va);
return x;
}
inline int wscanf(const wchar_t* format, ...)
{
va_list va; int x; va_start(va, format);
x = vscanf(format, va);
va_end(va);
return x;
}
// (un)(put/get) char //
inline wint_t fgetc(FILE* stream)
{
return std::fgetwc(stream);
}
inline wchar_t* fgets(wchar_t* str, int num, FILE* stream)
{
return std::fgetws(str, num, stream);
}
inline wint_t fputc(wchar_t c, FILE* stream )
{
return std::fputwc(c, stream);
}
inline int fputs(const wchar_t* str, FILE* stream)
{
return std::fputws(str, stream);
}
inline wint_t getc(FILE* stream)
{
return std::getwc(stream);
}
inline wint_t putc(wchar_t c, FILE* stream)
{
return std::putwc(c, stream);
}
inline wint_t putchar(wchar_t c)
{
return std::putwchar(c);
}
inline wint_t ungetc(wint_t c, FILE* stream)
{
return std::ungetwc(c, stream);
}
//=================================== stdlib ===================================//
inline double strtod(const wchar_t* str, wchar_t** endptr)
{
return wcstod(str, endptr);
}
inline float strtof(const wchar_t* str, wchar_t** endptr)
{
return wcstof(str, endptr);
}
inline long double strtold(const wchar_t* str, wchar_t ** endptr)
{
return wcstold(str, endptr);
}
inline long int strtol(const wchar_t* str, wchar_t** endptr, int base)
{
return wcstol(str, endptr, base);
}
inline long long int strtoll(const wchar_t* str, wchar_t** endptr, int base)
{
return wcstoll(str, endptr, base);
}
inline unsigned long int strtoul(const wchar_t* str, wchar_t** endptr, int base)
{
return wcstoul(str, endptr, base);
}
inline unsigned long long int strtoull(const wchar_t* str, wchar_t** endptr, int base)
{
return wcstoull(str, endptr, base);
}
//=================================== time ===================================//
inline size_t strftime(wchar_t* ptr, size_t maxsize, const wchar_t* format, const struct tm* timeptr)
{
return wcsftime(ptr, maxsize, format, timeptr);
}
//=================================== string ===================================//
////////////// this library funcs //////////////////////////
template<class T, class U>
inline T* strcpy(T* dest, const U* src, T replace_invalid_chars = 0)
{
T* p = dest;
do
{
if(*src > 0x7F) *p = replace_invalid_chars;
else *p = *src++;
}
while(*p++);
return dest;
}
template<class T, class U>
inline T* strncpy(T* dest, const U* src, size_t num, T replace_invalid_chars = 0)
{
T* p = dest;
bool found_null = false;
while(num-- != 0)
{
if(found_null)
{
*p = 0;
}
else
{
if(*src > 0x7F) *p = replace_invalid_chars;
else *p = *src++;
if(*p++ == 0) found_null = true;
}
}
return dest;
}
template<class T, class U>
inline size_t strncmp(const T* a, const U* b, size_t num)
{
while(num-- != 0)
{
if(*a != *b) return *a - *b;
else if(*a == 0) return 0;
++a, ++b;
}
return 0;
}
template<class T, class U>
inline size_t strcmp(const T* a, const U* b)
{
return strncmp(a, b, (size_t)(-1));
}
////////////// standard //////////////////////////
inline wchar_t* strcpy(wchar_t* dest, const wchar_t* src)
{
return wcscpy(dest, src);
}
inline size_t strcmp(const wchar_t* a, const wchar_t* b)
{
return wcscmp(a, b);
}
inline wchar_t* strncpy(wchar_t* dest, const wchar_t* src, size_t num)
{
return wcsncpy(dest, src, num);
}
inline size_t strncmp(const wchar_t* a, const wchar_t* b, size_t num)
{
return wcsncmp(a, b, num);
}
inline wchar_t* strcat(wchar_t* destination, const wchar_t* source) // <<
{
return wcscat(destination, source);
}
inline const wchar_t* strchr(const wchar_t* s, wchar_t c)
{
return wcschr(s, c);
}
inline wchar_t* strchr(wchar_t* s, wchar_t c)
{
return wcschr(s, c);
}
inline int strcoll(const wchar_t* str1, const wchar_t* str2)
{
return wcscoll(str1, str2);
}
inline size_t strcspn(const wchar_t* str1, const wchar_t* str2)
{
return wcscspn(str1, str2);
}
inline size_t strlen(const wchar_t* str)
{
return wcslen(str);
}
inline wchar_t* strncat(wchar_t* destination, wchar_t* source, size_t num)
{
return wcsncat(destination, source, num);
}
inline const wchar_t* strpbrk(const wchar_t* str1, const wchar_t* str2)
{
return wcspbrk(str1, str2);
}
inline wchar_t* strpbrk(wchar_t* str1, const wchar_t* str2)
{
return wcspbrk(str1, str2);
}
inline const wchar_t* strrchr(const wchar_t* s, wchar_t c)
{
return wcsrchr(s, c);
}
inline wchar_t* strrchr(wchar_t* s, wchar_t c)
{
return wcsrchr(s, c);
}
inline size_t strspn(const wchar_t* str1, const wchar_t* str2)
{
return wcsspn(str1, str2);
}
inline const wchar_t* strstr(const wchar_t* str1, const wchar_t* str2)
{
return wcsstr(str1, str2);
}
inline wchar_t* strstr(wchar_t* str1, const wchar_t* str2)
{
return wcsstr(str1, str2);
}
inline wchar_t* strtok(wchar_t* str, const wchar_t* delims)
{
#if _MSC_VER < 1900 || defined(_CRT_NON_CONFORMING_WCSTOK) // not VS2015 or [VS2015 and non conforming wcstok]
return wcstok(str, delims);
#else
static wchar_t* context = nullptr;
return wcstok(str, delims, &context);
#endif
}
inline size_t strxfrm(wchar_t* destination, const wchar_t* source, size_t num)
{
return wcsxfrm(destination, source, num);
}
#ifdef _WIN32
inline int stricmp(const wchar_t* a1, const wchar_t* a2)
{
return _wcsicmp(a1, a2);
}
inline int strnicmp(const wchar_t* a1, const wchar_t* a2, size_t num)
{
return _wcsnicmp(a1, a2, num);
}
#endif
//--------------------------------------------------------------------------
// NOT GOING TO OVERLOAD wmemXXX functions, makes non-sense in my mind
//--------------------------------------------------------------------------
} // namespace
#endif // include guard
| 20.232662 | 112 | 0.655573 | gtaisbetterthanfn |
5d6e126927efa63721d04377f68b84212fa8fb44 | 1,477 | cc | C++ | brick/resource/injected_js_resource_provider.cc | gridgentoo/Bitrix24Messenger | fc629c00147737edf036df2f216e3e07a062766e | [
"MIT"
] | 148 | 2015-01-12T13:05:57.000Z | 2022-02-09T04:14:14.000Z | brick/resource/injected_js_resource_provider.cc | gridgentoo/Bitrix24Messenger | fc629c00147737edf036df2f216e3e07a062766e | [
"MIT"
] | 92 | 2015-03-10T10:59:40.000Z | 2019-10-02T08:56:22.000Z | brick/resource/injected_js_resource_provider.cc | gridgentoo/Bitrix24Messenger | fc629c00147737edf036df2f216e3e07a062766e | [
"MIT"
] | 99 | 2015-01-12T14:12:10.000Z | 2022-02-10T11:34:32.000Z | // Copyright (c) 2015 The Brick Authors.
#include "brick/resource/injected_js_resource_provider.h"
#include "include/wrapper/cef_stream_resource_handler.h"
#include "brick/helper.h"
#include "brick/resource/resource_util.h"
namespace {
const char kMimeType[] = "application/javascript";
} // namespace
InjectedJsResourceProvider::InjectedJsResourceProvider(
const std::string& url_path,
AppSettings::client_scripts_map* scripts):
url_path_(url_path),
scripts_(scripts) {
DCHECK(!url_path_.empty());
DCHECK(scripts_);
}
bool
InjectedJsResourceProvider::OnRequest(scoped_refptr<CefResourceManager::Request> request) {
CEF_REQUIRE_IO_THREAD();
const std::string& url = request->url();
if (url.find(url_path_) != 0U) {
return false;
}
const std::string& file_path = GetFilePath(url);
if (file_path.empty()) {
return false;
}
CefRefPtr<CefStreamReader> stream = resource_util::GetBinaryFileReader(file_path);
if (!stream) {
LOG(WARNING) << "Injected JS not found: " << file_path;
request->Stop();
return false;
}
request->Continue(new CefStreamResourceHandler(
kMimeType,
stream
));
return true;
}
std::string
InjectedJsResourceProvider::GetFilePath(const std::string& url) {
std::string path_part = url.substr(url_path_.length());
if (scripts_->count(path_part)) {
// If we found our client script - load it :)
return scripts_->at(path_part);
}
return "";
}
| 23.444444 | 91 | 0.701422 | gridgentoo |
5d6f057de6f52fce9b6924a624470a38bbae2955 | 923 | cpp | C++ | 145_postorderTraversal.cpp | imxiaobo/leetcode-solutions | a59c4c9fa424787771c8faca7ba444cae4ed6a4e | [
"MIT"
] | null | null | null | 145_postorderTraversal.cpp | imxiaobo/leetcode-solutions | a59c4c9fa424787771c8faca7ba444cae4ed6a4e | [
"MIT"
] | null | null | null | 145_postorderTraversal.cpp | imxiaobo/leetcode-solutions | a59c4c9fa424787771c8faca7ba444cae4ed6a4e | [
"MIT"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode *root) {
stack<std::pair<TreeNode *, int>> stack;
vector<int> postorder;
if (root) {
stack.push(std::make_pair(root, 0));
while (!stack.empty()) {
std::pair<TreeNode *, int> &t = stack.top();
if (!t.first) {
stack.pop();
} else if (t.second == 0) {
++t.second;
stack.push(std::make_pair(t.first->left, 0));
} else if (t.second == 1) {
++t.second;
stack.push(std::make_pair(t.first->right, 0));
} else if (t.second == 2) {
postorder.push_back(t.first->val);
stack.pop();
}
}
}
return postorder;
}
};
| 23.666667 | 59 | 0.510293 | imxiaobo |
5d7076f8b4f5ab6d40a1d9263a8f80243a374880 | 998 | cpp | C++ | JEngine/src/Private/Renderer/Buffer.cpp | RaymondMcGuire/JEngine | aa12b70a8e6fd23b917803ea25574c664033d086 | [
"Apache-2.0"
] | 2 | 2020-09-26T17:22:25.000Z | 2021-03-24T04:24:30.000Z | JEngine/src/Private/Renderer/Buffer.cpp | RaymondMcGuire/JEngine | aa12b70a8e6fd23b917803ea25574c664033d086 | [
"Apache-2.0"
] | 1 | 2020-11-11T03:18:36.000Z | 2020-11-11T03:18:36.000Z | JEngine/src/Private/Renderer/Buffer.cpp | RaymondMcGuire/JEngine | aa12b70a8e6fd23b917803ea25574c664033d086 | [
"Apache-2.0"
] | 5 | 2020-10-26T07:47:05.000Z | 2022-02-22T13:29:31.000Z | #include "JE_PCH.h"
#include "Renderer/Buffer.h"
#include "Renderer/Renderer.h"
#include "Platform/OpenGL/OpenGLBuffer.h"
namespace JEngine
{
Ref<VertexBuffer> VertexBuffer::Create(float* vertices, uint32_t size)
{
switch (Renderer::GetRenderPlatform())
{
case RendererAPI::RenderPlatform::None:
JE_CORE_ASSERT(false, "Renderer API is not Supported");
return nullptr;
case RendererAPI::RenderPlatform::OpenGL:
return std::make_shared<OpenGLVertexBuffer>(vertices, size);
}
JE_CORE_ASSERT(false, "Unknown RendererAPI!");
return nullptr;
}
Ref<IndexBuffer> IndexBuffer::Create(uint32_t* vertices, uint32_t count)
{
switch (Renderer::GetRenderPlatform())
{
case RendererAPI::RenderPlatform::None:
JE_CORE_ASSERT(false, "Renderer API is not Supported");
return nullptr;
case RendererAPI::RenderPlatform::OpenGL:
return std::make_shared<OpenGLIndexBuffer>(vertices, count);
}
JE_CORE_ASSERT(false, "Unknown RendererAPI!");
return nullptr;
}
}
| 23.761905 | 73 | 0.741483 | RaymondMcGuire |
5d7132399c20435b79d204111ab0de85b6bd163c | 3,761 | hpp | C++ | core/src/api/Currency.hpp | tmpfork/lib-ledger-core | 8741e84f38f863fd941d3bd56a470f37eb36da04 | [
"MIT"
] | null | null | null | core/src/api/Currency.hpp | tmpfork/lib-ledger-core | 8741e84f38f863fd941d3bd56a470f37eb36da04 | [
"MIT"
] | null | null | null | core/src/api/Currency.hpp | tmpfork/lib-ledger-core | 8741e84f38f863fd941d3bd56a470f37eb36da04 | [
"MIT"
] | null | null | null | // AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from currency.djinni
#ifndef DJINNI_GENERATED_CURRENCY_HPP
#define DJINNI_GENERATED_CURRENCY_HPP
#include "../utils/optional.hpp"
#include "BitcoinLikeNetworkParameters.hpp"
#include "CurrencyUnit.hpp"
#include "EthereumLikeNetworkParameters.hpp"
#include "WalletType.hpp"
#include <cstdint>
#include <iostream>
#include <string>
#include <utility>
#include <vector>
namespace ledger { namespace core { namespace api {
/**Structure of cryptocurrency */
struct Currency final {
/**WalletType object defining the type of wallet the currency belongs to */
WalletType walletType;
/**String which represents currency name */
std::string name;
/**
*Integer cointype, part of BIP32 path
*One can refer to https://github.com/satoshilabs/slips/blob/master/slip-0044.md
*/
int32_t bip44CoinType;
/**String representing schemes allowing to send money to a cryptocurrency address (e.g. bitcoin) */
std::string paymentUriScheme;
/**List of CurrencyUnit objects (e.g. BTC, mBTC ...) */
std::vector<CurrencyUnit> units;
/**
*TODO: find a better solution to have only a networkParameters
*Optional BitcoinLikeNetworkParameters, for more details refer to BitcoinLikeNetworkParameters doc
*/
std::experimental::optional<BitcoinLikeNetworkParameters> bitcoinLikeNetworkParameters;
/**Optional EthereumLikeNetworkParameters, for more details refer to EthereumLikeNetworkParameters doc */
std::experimental::optional<EthereumLikeNetworkParameters> ethereumLikeNetworkParameters;
Currency(WalletType walletType_,
std::string name_,
int32_t bip44CoinType_,
std::string paymentUriScheme_,
std::vector<CurrencyUnit> units_,
std::experimental::optional<BitcoinLikeNetworkParameters> bitcoinLikeNetworkParameters_,
std::experimental::optional<EthereumLikeNetworkParameters> ethereumLikeNetworkParameters_)
: walletType(std::move(walletType_))
, name(std::move(name_))
, bip44CoinType(std::move(bip44CoinType_))
, paymentUriScheme(std::move(paymentUriScheme_))
, units(std::move(units_))
, bitcoinLikeNetworkParameters(std::move(bitcoinLikeNetworkParameters_))
, ethereumLikeNetworkParameters(std::move(ethereumLikeNetworkParameters_))
{}
Currency(const Currency& cpy) {
this->walletType = cpy.walletType;
this->name = cpy.name;
this->bip44CoinType = cpy.bip44CoinType;
this->paymentUriScheme = cpy.paymentUriScheme;
this->units = cpy.units;
this->bitcoinLikeNetworkParameters = cpy.bitcoinLikeNetworkParameters;
this->ethereumLikeNetworkParameters = cpy.ethereumLikeNetworkParameters;
}
Currency() = default;
Currency& operator=(const Currency& cpy) {
this->walletType = cpy.walletType;
this->name = cpy.name;
this->bip44CoinType = cpy.bip44CoinType;
this->paymentUriScheme = cpy.paymentUriScheme;
this->units = cpy.units;
this->bitcoinLikeNetworkParameters = cpy.bitcoinLikeNetworkParameters;
this->ethereumLikeNetworkParameters = cpy.ethereumLikeNetworkParameters;
return *this;
}
template <class Archive>
void load(Archive& archive) {
archive(walletType, name, bip44CoinType, paymentUriScheme, units, bitcoinLikeNetworkParameters, ethereumLikeNetworkParameters);
}
template <class Archive>
void save(Archive& archive) const {
archive(walletType, name, bip44CoinType, paymentUriScheme, units, bitcoinLikeNetworkParameters, ethereumLikeNetworkParameters);
}
};
} } } // namespace ledger::core::api
#endif //DJINNI_GENERATED_CURRENCY_HPP
| 39.177083 | 135 | 0.727998 | tmpfork |
5d737e64322e609ea7e0217c93277bd4afec7f69 | 2,621 | hxx | C++ | private/inet/mshtml/src/core/include/buttutil.hxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 11 | 2017-09-02T11:27:08.000Z | 2022-01-02T15:25:24.000Z | private/inet/mshtml/src/core/include/buttutil.hxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | null | null | null | private/inet/mshtml/src/core/include/buttutil.hxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 14 | 2019-01-16T01:01:23.000Z | 2022-02-20T15:54:27.000Z | //+------------------------------------------------------------------------
//
// File: buttutil.hxx
//
// Contents: Button Drawing routines common to scrollbar and dropbutton.
//
// History: 16-Aug-95 t-vuil Created
//
//-------------------------------------------------------------------------
#ifndef I_BUTTUTIL_HXX_
#define I_BUTTUTIL_HXX_
#pragma INCMSG("--- Beg 'buttutil.hxx'")
HRESULT BRDrawBorder(
CDrawInfo *pDI,
RECT * prc,
fmBorderStyle BorderStyle,
COLORREF colorBorder,
ThreeDColors * peffectColor,
DWORD dwFlags);
int BRGetBorderWidth(
fmBorderStyle BorderStyle);
HRESULT BRAdjustRectForBorder(
CTransform * pTransform,
RECT * prc,
fmBorderStyle BorderStyle);
HRESULT BRAdjustRectForBorderRev(
CTransform * pTransform,
RECT * prc,
fmBorderStyle BorderStyle);
HRESULT BRAdjustRectlForBorder(
RECTL * prcl,
fmBorderStyle BorderStyle);
HRESULT
BRAdjustSizelForBorder
(
SIZEL * psizel,
fmBorderStyle BorderStyle,
BOOL fSubtractAdd = 0); // 0 - subtract; 1 - add, default is subtract.
//
// Rect drawing helper. It tests for an empty rect, and very large rects
// which exceed 32K units.
//
class CUtilityButton
{
public:
void Invalidate(HWND hWnd, const RECT &rc, DWORD dwFlags = 0);
void DrawButton (
CDrawInfo *, HWND, BUTTON_GLYPH, BOOL pressed, BOOL enabled, BOOL focused,
const RECT &rcBounds, const SIZEL &sizelExtent, unsigned long padding );
virtual ThreeDColors & GetColors ( void );
private:
void DrawNull (
HDC hdc, HBRUSH, BUTTON_GLYPH glyph,
const RECT & rcBounds, const SIZEL & sizel );
void DrawArrow (
HDC hdc, HBRUSH, BUTTON_GLYPH glyph,
const RECT & rcBounds, const SIZEL & sizel );
void DrawDotDotDot (
HDC hdc, HBRUSH, BUTTON_GLYPH glyph,
const RECT & rcBounds, const SIZEL & sizel );
void DrawReduce (
HDC hdc, HBRUSH, BUTTON_GLYPH glyph,
const RECT & rcBounds, const SIZEL & sizel );
public:
BOOL _fFlat; // for flat scrollbars/buttons
#ifdef UNIX
BOOL _bMotifScrollBarBtn; // for Unix Motif scrollbar buttons
#endif
};
#pragma INCMSG("--- End 'buttutil.hxx'")
#else
#pragma INCMSG("*** Dup 'buttutil.hxx'")
#endif
| 26.744898 | 83 | 0.54979 | King0987654 |
5d74b13656ffaa4a8a9ab331222acd315f1826fd | 2,901 | hpp | C++ | include/codegen/include/GlobalNamespace/OVRInput_OVRControllerTouchpad.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/OVRInput_OVRControllerTouchpad.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/OVRInput_OVRControllerTouchpad.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: OVRInput
#include "GlobalNamespace/OVRInput.hpp"
// Including type: OVRInput/OVRControllerBase
#include "GlobalNamespace/OVRInput_OVRControllerBase.hpp"
// Completed includes
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: OVRInput/OVRControllerTouchpad
class OVRInput::OVRControllerTouchpad : public GlobalNamespace::OVRInput::OVRControllerBase {
public:
// private OVRPlugin/Vector2f moveAmount
// Offset: 0x104
GlobalNamespace::OVRPlugin::Vector2f moveAmount;
// private System.Single maxTapMagnitude
// Offset: 0x10C
float maxTapMagnitude;
// private System.Single minMoveMagnitude
// Offset: 0x110
float minMoveMagnitude;
// public System.Void .ctor()
// Offset: 0xE71180
// Implemented from: OVRInput/OVRControllerBase
// Base method: System.Void OVRControllerBase::.ctor()
// Base method: System.Void Object::.ctor()
static OVRInput::OVRControllerTouchpad* New_ctor();
// public override OVRInput/Controller Update()
// Offset: 0xE7A194
// Implemented from: OVRInput/OVRControllerBase
// Base method: OVRInput/Controller OVRControllerBase::Update()
GlobalNamespace::OVRInput::Controller Update();
// public override System.Void ConfigureButtonMap()
// Offset: 0xE7A350
// Implemented from: OVRInput/OVRControllerBase
// Base method: System.Void OVRControllerBase::ConfigureButtonMap()
void ConfigureButtonMap();
// public override System.Void ConfigureTouchMap()
// Offset: 0xE7A524
// Implemented from: OVRInput/OVRControllerBase
// Base method: System.Void OVRControllerBase::ConfigureTouchMap()
void ConfigureTouchMap();
// public override System.Void ConfigureNearTouchMap()
// Offset: 0xE7A5DC
// Implemented from: OVRInput/OVRControllerBase
// Base method: System.Void OVRControllerBase::ConfigureNearTouchMap()
void ConfigureNearTouchMap();
// public override System.Void ConfigureAxis1DMap()
// Offset: 0xE7A62C
// Implemented from: OVRInput/OVRControllerBase
// Base method: System.Void OVRControllerBase::ConfigureAxis1DMap()
void ConfigureAxis1DMap();
// public override System.Void ConfigureAxis2DMap()
// Offset: 0xE7A67C
// Implemented from: OVRInput/OVRControllerBase
// Base method: System.Void OVRControllerBase::ConfigureAxis2DMap()
void ConfigureAxis2DMap();
}; // OVRInput/OVRControllerTouchpad
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::OVRInput::OVRControllerTouchpad*, "", "OVRInput/OVRControllerTouchpad");
#pragma pack(pop)
| 42.661765 | 112 | 0.728025 | Futuremappermydud |
5d7b88138309789d20641a72271df3b35b949613 | 7,579 | cpp | C++ | tools/IO/cvt_amuseASCII2bonsai.cpp | sciserver/Bonsai | 8904dd3ebf395ccaaf0eacef38933002b49fc3ba | [
"Apache-2.0"
] | 40 | 2015-02-02T13:24:11.000Z | 2021-09-10T05:43:44.000Z | tools/IO/cvt_amuseASCII2bonsai.cpp | sciserver/Bonsai | 8904dd3ebf395ccaaf0eacef38933002b49fc3ba | [
"Apache-2.0"
] | 17 | 2015-02-20T08:29:57.000Z | 2022-02-17T17:26:40.000Z | tools/IO/cvt_amuseASCII2bonsai.cpp | sciserver/Bonsai | 8904dd3ebf395ccaaf0eacef38933002b49fc3ba | [
"Apache-2.0"
] | 24 | 2015-01-30T09:14:51.000Z | 2021-12-28T01:53:28.000Z | #include "BonsaiIO.h"
#include "IDType.h"
#include <array>
#include <fstream>
#include <sstream>
#include <iostream>
typedef struct real4
{
float x,y,z,w;
} real4;
#define DARKMATTERID 3000000000000000000
#define DISKID 0
#define BULGEID 2000000000000000000
static IDType lGetIDType (const long long id)
{
IDType ID;
ID.setID(id);
ID.setType(3); /* Everything is Dust until told otherwise */
if(id >= DISKID && id < BULGEID)
{
ID.setType(2); /* Disk */
ID.setID(id - DISKID);
}
else if(id >= BULGEID && id < DARKMATTERID)
{
ID.setType(1); /* Bulge */
ID.setID(id - BULGEID);
}
else if (id >= DARKMATTERID)
{
ID.setType(0); /* DM */
ID.setID(id - DARKMATTERID);
}
return ID;
};
void readAMUSEFile(std::vector<real4> &bodyPositions,
std::vector<real4> &bodyVelocities,
std::vector<IDType> &bodiesIDs,
std::string fileName,
const int reduceFactor) {
bodyPositions.clear();
char fullFileName[256];
sprintf(fullFileName, "%s", fileName.c_str());
std::cerr << "Trying to read file: " << fullFileName << std::endl;
std::ifstream inputFile(fullFileName, std::ios::in);
if(!inputFile.is_open())
{
std::cerr << "Can't open input file \n";
exit(0);
}
//Skip the header lines
std::string tempLine;
std::getline(inputFile, tempLine);
std::getline(inputFile, tempLine);
int pid = 0;
real4 positions;
real4 velocity;
int cntr = 0;
// float r2 = 0;
while(std::getline(inputFile, tempLine))
{
if(tempLine.empty()) continue; //Skip empty lines
std::stringstream ss(tempLine);
//Amuse format
// inputFile >> positions.w >> r2 >> r2 >>
// velocity.x >> velocity.y >> velocity.z >>
// positions.x >> positions.y >> positions.z;
ss >> positions.w >>
velocity.x >> velocity.y >> velocity.z >>
positions.x >> positions.y >> positions.z;
// positions.x /= 1000;
// positions.y /= 1000;
// positions.z /= 1000;
// idummy = pid; //particleIDtemp;
// cout << idummy << "\t"<< positions.w << "\t"<< positions.x << "\t"<< positions.y << "\t"<< positions.z << "\t"
// << velocity.x << "\t"<< velocity.y << "\t"<< velocity.z << "\t" << velocity.w << "\n";
if(reduceFactor > 0)
{
if(cntr % reduceFactor == 0)
{
positions.w *= reduceFactor;
bodyPositions.push_back(positions);
bodyVelocities.push_back(velocity);
//Convert the ID to a star (disk for now) particle
bodiesIDs.push_back(lGetIDType(pid++));
}
}
cntr++;
}
inputFile.close();
fprintf(stderr, "read %d bodies from dump file \n", cntr);
};
#if 1
template<typename IO, size_t N>
static double writeStars(std::vector<real4> &bodyPositions,
std::vector<real4> &bodyVelocities,
std::vector<IDType> &bodiesIDs,
IO &out,
std::array<size_t,N> &count)
{
double dtWrite = 0;
const int pCount = bodyPositions.size();
/* write IDs */
{
BonsaiIO::DataType<IDType> ID("Stars:IDType", pCount);
for (int i = 0; i< pCount; i++)
{
//ID[i] = lGetIDType(bodiesIDs[i]);
ID[i] = bodiesIDs[i];
assert(ID[i].getType() > 0);
if (ID[i].getType() < count.size())
count[ID[i].getType()]++;
}
double t0 = MPI_Wtime();
out.write(ID);
dtWrite += MPI_Wtime() - t0;
}
/* write pos */
{
BonsaiIO::DataType<real4> pos("Stars:POS:real4",pCount);
for (int i = 0; i< pCount; i++)
pos[i] = bodyPositions[i];
double t0 = MPI_Wtime();
out.write(pos);
dtWrite += MPI_Wtime() - t0;
}
/* write vel */
{
typedef float vec3[3];
BonsaiIO::DataType<vec3> vel("Stars:VEL:float[3]",pCount);
for (int i = 0; i< pCount; i++)
{
vel[i][0] = bodyVelocities[i].x;
vel[i][1] = bodyVelocities[i].y;
vel[i][2] = bodyVelocities[i].z;
}
double t0 = MPI_Wtime();
out.write(vel);
dtWrite += MPI_Wtime() - t0;
}
return dtWrite;
}
#endif
int main(int argc, char * argv[])
{
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Init(&argc, &argv);
int nranks, rank;
MPI_Comm_size(comm, &nranks);
MPI_Comm_rank(comm, &rank);
if (argc < 3)
{
if (rank == 0)
{
fprintf(stderr, " ------------------------------------------------------------------------\n");
fprintf(stderr, " Usage: \n");
fprintf(stderr, " %s baseName outputName [reduceStar]\n", argv[0]);
fprintf(stderr, " ------------------------------------------------------------------------\n");
}
exit(-1);
}
const std::string baseName(argv[1]);
const std::string outputName(argv[2]);
int reduceFactor = 1;
if(argc > 3) {
reduceFactor = atoi(argv[3]);
}
if( rank == 0) fprintf(stderr,"Basename: %s outputname: %s Reducing Stars by factor: %d \n", baseName.c_str(), outputName.c_str(), reduceFactor);
std::vector<real4> bodyPositions;
std::vector<real4> bodyVelocities;
std::vector<IDType> bodiesIDs;
readAMUSEFile(bodyPositions, bodyVelocities, bodiesIDs, baseName, reduceFactor);
if (rank == 0){
fprintf(stderr, " nTotal= %ld \n", bodyPositions.size());
}
const double tAll = MPI_Wtime();
{
const double tOpen = MPI_Wtime();
BonsaiIO::Core out(rank, nranks, comm, BonsaiIO::WRITE, outputName);
if (rank == 0)
fprintf(stderr, "Time= %g\n", 0.0); //data.time);
out.setTime(0.0); //start at t=0
double dtOpenLoc = MPI_Wtime() - tOpen;
double dtOpenGlb;
MPI_Allreduce(&dtOpenLoc, &dtOpenGlb, 1, MPI_DOUBLE, MPI_MAX,comm);
if (rank == 0) fprintf(stderr, "open file in %g sec \n", dtOpenGlb);
double dtWrite = 0;
std::array<size_t,10> ntypeloc, ntypeglb;
std::fill(ntypeloc.begin(), ntypeloc.end(), 0);
if (rank == 0) fprintf(stderr, " write Stars\n");
MPI_Barrier(comm);
dtWrite += writeStars(bodyPositions, bodyVelocities, bodiesIDs,out,ntypeloc);
MPI_Reduce(&ntypeloc, &ntypeglb, ntypeloc.size(), MPI_LONG_LONG, MPI_SUM, 0, comm);
if (rank == 0)
{
size_t nsum = 0;
for (int type = 0; type < (int)ntypeloc.size(); type++)
{
nsum += ntypeglb[type];
if (ntypeglb[type] > 0)
fprintf(stderr, "ptype= %d: np= %zu \n",type, ntypeglb[type]);
}
}
double dtWriteGlb;
MPI_Allreduce(&dtWrite, &dtWriteGlb, 1, MPI_DOUBLE, MPI_MAX,comm);
if (rank == 0) fprintf(stderr, "write file in %g sec \n", dtWriteGlb);
const double tClose = MPI_Wtime();
out.close();
double dtCloseLoc = MPI_Wtime() - tClose;
double dtCloseGlb;
MPI_Allreduce(&dtCloseLoc, &dtCloseGlb, 1, MPI_DOUBLE, MPI_MAX,comm);
if (rank == 0) fprintf(stderr, "close time in %g sec \n", dtCloseGlb);
if (rank == 0)
{
out.getHeader().printFields();
fprintf(stderr, " Bandwidth= %g MB/s\n", out.computeBandwidth()/1e6);
}
}
double dtAllLoc = MPI_Wtime() - tAll;
double dtAllGlb;
MPI_Allreduce(&dtAllLoc, &dtAllGlb, 1, MPI_DOUBLE, MPI_MAX,comm);
if (rank == 0)
fprintf(stderr, "All operations done in %g sec \n", dtAllGlb);
MPI_Finalize();
return 0;
}
| 26.407666 | 148 | 0.551524 | sciserver |
5d830c6bf4941b2fb8456adad3ed6957e5baafd3 | 2,132 | cc | C++ | components/ui_devtools/viz/viz_element.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | components/ui_devtools/viz/viz_element.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | components/ui_devtools/viz/viz_element.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2019 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 "components/ui_devtools/viz/viz_element.h"
#include <algorithm>
#include "components/ui_devtools/ui_element_delegate.h"
#include "components/ui_devtools/viz/frame_sink_element.h"
#include "components/ui_devtools/viz/surface_element.h"
namespace ui_devtools {
namespace {
bool IsVizElement(const UIElement* element) {
return element->type() == UIElementType::FRAMESINK ||
element->type() == UIElementType::SURFACE;
}
bool CompareVizElements(const UIElement* a, const UIElement* b) {
if (a->type() == UIElementType::FRAMESINK) {
if (b->type() == UIElementType::SURFACE)
return true;
// From() checks that |b| is a FrameSinkElement.
return FrameSinkElement::From(a) < FrameSinkElement::From(b);
} else {
if (b->type() == UIElementType::FRAMESINK)
return false;
// From() checks that |a| and |b| are SurfaceElements.
return SurfaceElement::From(a) < SurfaceElement::From(b);
}
}
} // namespace
VizElement::VizElement(const UIElementType type,
UIElementDelegate* delegate,
UIElement* parent)
: UIElement(type, delegate, parent) {}
VizElement::~VizElement() {}
void VizElement::AddToParentSorted(UIElement* parent, bool notify_delegate) {
parent->AddOrderedChild(this, &CompareVizElements, notify_delegate);
}
void VizElement::Reparent(UIElement* new_parent) {
if (parent() == new_parent)
return;
// Become a child of |new_parent| without calling OnUIElementRemoved or
// OnUIElementAdded on |delegate_|. Instead, call OnUIElementReordered, which
// destroys and rebuilds the DOM node in the new location.
parent()->RemoveChild(this, false);
AddToParentSorted(new_parent, false);
delegate()->OnUIElementReordered(new_parent, this);
set_parent(new_parent);
}
VizElement* VizElement::AsVizElement(UIElement* element) {
DCHECK(IsVizElement(element));
return static_cast<VizElement*>(element);
}
} // namespace ui_devtools
| 31.820896 | 79 | 0.717167 | sarang-apps |
5d830e987a5af7a53d61e2f4bab6e39697ff98f2 | 532 | inl | C++ | Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/PostProcessParams.inl | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/PostProcessParams.inl | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Gems/Atom/Feature/Common/Code/Include/Atom/Feature/PostProcess/PostProcessParams.inl | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
// Param definition for PostProcessSettings
// This file is used to auto-generate members, getters and setters for the
// Settings, SettingsInterface, ComponentConfig, ComponentController and Bus classes
AZ_GFX_UINT32_PARAM(Priority, m_priority, 0)
AZ_GFX_FLOAT_PARAM(OverrideFactor, m_overrideFactor, 1.0f)
| 33.25 | 100 | 0.783835 | cypherdotXd |
5d850acb324df49c7a3df716382af314f38f2025 | 285 | cpp | C++ | solutions/1198.find-smallest-common-element-in-all-rows.326220064.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 78 | 2020-10-22T11:31:53.000Z | 2022-02-22T13:27:49.000Z | solutions/1198.find-smallest-common-element-in-all-rows.326220064.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | null | null | null | solutions/1198.find-smallest-common-element-in-all-rows.326220064.ac.cpp | satu0king/Leetcode-Solutions | 2edff60d76c2898d912197044f6284efeeb34119 | [
"MIT"
] | 26 | 2020-10-23T15:10:44.000Z | 2021-11-07T16:13:50.000Z | class Solution {
public:
int smallestCommonElement(vector<vector<int>> &mat) {
int m[10001] = {};
for (auto j = 0; j < mat[0].size(); ++j)
for (auto i = 0; i < mat.size(); ++i)
if (++m[mat[i][j]] == mat.size())
return mat[i][j];
return -1;
}
};
| 23.75 | 55 | 0.491228 | satu0king |
5d850af6a4b8948f669234ddabaaf6e29b7f4058 | 1,134 | cpp | C++ | PokemanSafari_M1/Character.cpp | ilanisakov/RailShooter | 612945b96b37989927b99f50ffa96e2fe7e22e21 | [
"MIT"
] | null | null | null | PokemanSafari_M1/Character.cpp | ilanisakov/RailShooter | 612945b96b37989927b99f50ffa96e2fe7e22e21 | [
"MIT"
] | null | null | null | PokemanSafari_M1/Character.cpp | ilanisakov/RailShooter | 612945b96b37989927b99f50ffa96e2fe7e22e21 | [
"MIT"
] | null | null | null | /////////////////////////////////////////////////////////////////////
// File: Character.cpp
// DSA2 PokemanSafari_M1
// Authors:
// Ilan Isakov
// Marty Kurtz
// Mary Spencer
//
// Description:
//
/////////////////////////////////////////////////////////////////////
#include "Character.h"
/////////////////////////////////////////////////////////////////////
// Constructor
/////////////////////////////////////////////////////////////////////
Character::Character(CHARACTER_TYPE type, String name,
std::vector<vector3> VectorList,
std::vector<vector3> movementPath) :
MyBoundingObjectClass(VectorList, name)
{
this->path = movementPath; // path for the character
this->charType = type;
this->currentSeg = 0; //current line segment of the track
}
/////////////////////////////////////////////////////////////////
// Render()
/////////////////////////////////////////////////////////////////
void Character::UpdateRender()
{
}
/////////////////////////////////////////////////////////////////
// UpdateLocation()
/////////////////////////////////////////////////////////////////
void Character::UpdateLocation(){
} | 28.35 | 69 | 0.368607 | ilanisakov |
5d872b50248f3d7876c6910e699d896450e89eb2 | 244 | cpp | C++ | examples/physics/cmsToyGV/TBBProcessingDemo/TBBTestModules/busy_wait_scale_factor.cpp | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2016-10-16T14:37:42.000Z | 2018-04-05T15:49:09.000Z | examples/physics/cmsToyGV/TBBProcessingDemo/TBBTestModules/busy_wait_scale_factor.cpp | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | examples/physics/cmsToyGV/TBBProcessingDemo/TBBTestModules/busy_wait_scale_factor.cpp | Geant-RnD/geant | ffff95e23547531f3254ada2857c062a31f33e8f | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | //
// busy_wait_scale_factor.cpp
// DispatchProcessingDemo
//
// Created by Chris Jones on 10/3/11.
// Copyright 2011 FNAL. All rights reserved.
//
#include "busy_wait_scale_factor.h"
double busy_wait_scale_factor = 2.2e+07; //counts/sec
| 20.333333 | 53 | 0.733607 | Geant-RnD |
5d8e06c6d5a7671d4c9bd59fce419b4a8e2aa8c4 | 11,187 | cp | C++ | Linux/Sources/Application/Calendar/Component_Editing/CNewToDoDialog.cp | mbert/mulberry-main | 6b7951a3ca56e01a7be67aa12e55bfeafc63950d | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | Linux/Sources/Application/Calendar/Component_Editing/CNewToDoDialog.cp | SpareSimian/mulberry-main | e868f3f4d86efae3351000818a3cb2d72ae5eac3 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | Linux/Sources/Application/Calendar/Component_Editing/CNewToDoDialog.cp | SpareSimian/mulberry-main | e868f3f4d86efae3351000818a3cb2d72ae5eac3 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007-2011 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "CNewToDoDialog.h"
#include "CICalendar.h"
#include "CICalendarManager.h"
#include "CCalendarPopup.h"
#include "CCalendarView.h"
#include "CDateTimeZoneSelect.h"
#include "CErrorDialog.h"
#include "CMulberryApp.h"
#include "CNewComponentAlarm.h"
#include "CNewComponentAttendees.h"
#include "CNewComponentDetails.h"
#include "CNewComponentRepeat.h"
#include "CPreferences.h"
#include "CTabController.h"
#include "CTextField.h"
#include "CWindowsMenu.h"
#include "CXStringResources.h"
#include "CCalendarStoreManager.h"
#include "CICalendarLocale.h"
#include "CITIPProcessor.h"
#include "TPopupMenu.h"
#include <JXTextButton.h>
#include <JXTextCheckbox.h>
#include <JXUpRect.h>
#include <JXWindow.h>
#include <jXGlobals.h>
#include <cassert>
// ---------------------------------------------------------------------------
// CNewToDoDialog [public]
/**
Default constructor */
CNewToDoDialog::CNewToDoDialog(JXDirector* supervisor)
: CNewComponentDialog(supervisor)
{
}
// ---------------------------------------------------------------------------
// ~CNewToDoDialog [public]
/**
Destructor */
CNewToDoDialog::~CNewToDoDialog()
{
}
#pragma mark -
void CNewToDoDialog::OnCreate()
{
// Get UI items
CNewComponentDialog::OnCreate();
// begin JXLayout1
mCompleted =
new JXTextCheckbox("Completed", mContainer,
JXWidget::kFixedLeft, JXWidget::kFixedTop, 5,40, 90,20);
assert( mCompleted != NULL );
mCompletedDateTimeZone =
new CDateTimeZoneSelect(mContainer,
JXWidget::kHElastic, JXWidget::kVElastic, 94,35, 400,30);
assert( mCompletedDateTimeZone != NULL );
mCompletedNow =
new JXTextButton("Now", mContainer,
JXWidget::kHElastic, JXWidget::kVElastic, 495,40, 35,20);
assert( mCompletedNow != NULL );
mCompletedNow->SetFontSize(10);
// end JXLayout1
ListenTo(mCompleted);
ListenTo(mCompletedNow);
}
void CNewToDoDialog::InitPanels()
{
// Load each panel for the tabs
mPanels.push_back(new CNewComponentDetails(mTabs->GetCardEnclosure(), JXWidget::kFixedLeft, JXWidget::kFixedTop, 0,0, 500,300));
mTabs->AppendCard(mPanels.back(), "Details");
mPanels.push_back(new CNewComponentRepeat(mTabs->GetCardEnclosure(), JXWidget::kFixedLeft, JXWidget::kFixedTop, 0,0, 500,300));
mTabs->AppendCard(mPanels.back(), "Repeat");
mPanels.push_back(new CNewComponentAlarm(mTabs->GetCardEnclosure(), JXWidget::kFixedLeft, JXWidget::kFixedTop, 0,0, 500,300));
mTabs->AppendCard(mPanels.back(), "Alarms");
mPanels.push_back(new CNewComponentAttendees(mTabs->GetCardEnclosure(), JXWidget::kFixedLeft, JXWidget::kFixedTop, 0,0, 500,300));
mTabs->AppendCard(mPanels.back(), "Attendees");
}
void CNewToDoDialog::ListenTo_Message(long msg, void* param)
{
switch(msg)
{
case iCal::CICalendar::eBroadcast_Closed:
// Force dialog to close immediately as event is about to be deleted.
// Any changes so far will be lost.
OnCancel();
break;
default:;
}
}
// Handle controls
void CNewToDoDialog::Receive(JBroadcaster* sender, const Message& message)
{
if (message.Is(JXTextButton::kPushed))
{
if (sender == mCompletedNow)
{
DoNow();
return;
}
}
else if (message.Is(JXCheckbox::kPushed))
{
if (sender == mCompleted)
{
DoCompleted(mCompleted->IsChecked());
return;
}
}
CNewComponentDialog::Receive(sender, message);
}
void CNewToDoDialog::DoCompleted(bool set)
{
if (set && !mCompletedExists)
{
mActualCompleted.SetTimezone(iCal::CICalendarManager::sICalendarManager->GetDefaultTimezone());
mActualCompleted.SetNow();
mCompletedExists = true;
mCompletedDateTimeZone->SetDateTimeZone(mActualCompleted, false);
}
mCompletedDateTimeZone->SetVisible(set);
mCompletedNow->SetVisible(set);
}
void CNewToDoDialog::DoNow()
{
mActualCompleted.SetTimezone(iCal::CICalendarManager::sICalendarManager->GetDefaultTimezone());
mActualCompleted.SetNow();
mCompletedDateTimeZone->SetDateTimeZone(mActualCompleted, false);
}
void CNewToDoDialog::SetComponent(iCal::CICalendarComponentRecur& vcomponent, const iCal::CICalendarComponentExpanded* expanded)
{
CNewComponentDialog::SetComponent(vcomponent, expanded);
mCompletedExists = static_cast<iCal::CICalendarVToDo&>(vcomponent).HasCompleted();
mCompleted->SetState(mCompletedExists || (static_cast<iCal::CICalendarVToDo&>(vcomponent).GetStatus() == iCal::eStatus_VToDo_Completed));
if (mCompletedExists)
{
// COMPLETED is in UTC but we adjust to local timezone
mActualCompleted = static_cast<iCal::CICalendarVToDo&>(vcomponent).GetCompleted();
mActualCompleted.AdjustTimezone(iCal::CICalendarManager::sICalendarManager->GetDefaultTimezone());
mCompletedDateTimeZone->SetDateTimeZone(mActualCompleted, false);
}
DoCompleted(static_cast<iCal::CICalendarVToDo&>(vcomponent).GetStatus() == iCal::eStatus_VToDo_Completed);
}
void CNewToDoDialog::GetComponent(iCal::CICalendarComponentRecur& vcomponent)
{
CNewComponentDialog::GetComponent(vcomponent);
static_cast<iCal::CICalendarVToDo&>(vcomponent).EditStatus(mCompleted->IsChecked() ? iCal::eStatus_VToDo_Completed : iCal::eStatus_VToDo_NeedsAction);
// Changed completed date if needed
mCompletedDateTimeZone->GetDateTimeZone(mActualCompleted, false);
if (mCompleted->IsChecked() && (static_cast<iCal::CICalendarVToDo&>(vcomponent).GetCompleted() != mActualCompleted))
{
// Adjust to UTC and then change
mActualCompleted.AdjustToUTC();
static_cast<iCal::CICalendarVToDo&>(vcomponent).EditCompleted(mActualCompleted);
}
}
void CNewToDoDialog::SetReadOnly(bool read_only)
{
CNewComponentDialog::SetReadOnly(read_only);
mCompleted->SetActive(!mReadOnly);
mCompletedDateTimeZone->SetActive(!mReadOnly);
mCompletedNow->SetActive(!mReadOnly);
}
void CNewToDoDialog::ChangedMyStatus(const iCal::CICalendarProperty& attendee, const cdstring& new_status)
{
static_cast<CNewComponentAttendees*>(mPanels.back())->ChangedMyStatus(attendee, new_status);
}
bool CNewToDoDialog::DoNewOK()
{
// Check and get new calendar if different
iCal::CICalendarRef newcal;
iCal::CICalendar* new_cal = NULL;
if (!GetCalendar(0, newcal, new_cal))
// Return to dialog
return false;
// Get updated info
GetComponent(*mComponent);
// Look for change to calendar
if (newcal != mComponent->GetCalendar())
{
// Use new calendar
mComponent->SetCalendar(newcal);
// Set the default calendar for next time
const calstore::CCalendarStoreNode* node = calstore::CCalendarStoreManager::sCalendarStoreManager->GetNode(new_cal);
if (node != NULL)
CPreferences::sPrefs->mDefaultCalendar.SetValue(node->GetAccountName());
}
// Add to calendar (this will do the display update)
//iCal::CICalendar* cal = iCal::CICalendar::GetICalendar(mVToDo->GetCalendar());
new_cal->AddNewVToDo(static_cast<iCal::CICalendarVToDo*>(mComponent));
CCalendarView::ToDosChangedAll();
return true;
}
bool CNewToDoDialog::DoEditOK()
{
// Find the original calendar if it still exists
iCal::CICalendarRef oldcal = mComponent->GetCalendar();
iCal::CICalendar* old_cal = iCal::CICalendar::GetICalendar(oldcal);
if (old_cal == NULL)
{
// Inform user of missing calendar
CErrorDialog::StopAlert(rsrc::GetString("CNewToDoDialog::MissingOriginal"));
// Disable OK button
mOKBtn->SetActive(false);
return false;
}
// Find the original to do if it still exists
iCal::CICalendarVToDo* original = static_cast<iCal::CICalendarVToDo*>(old_cal->FindComponent(mComponent));
if (original == NULL)
{
// Inform user of missing calendar
CErrorDialog::StopAlert(rsrc::GetString("CNewToDoDialog::MissingOriginal"));
// Disable OK button and return to dialog
mOKBtn->SetActive(false);
return false;
}
// Check and get new calendar if different
iCal::CICalendarRef newcal;
iCal::CICalendar* new_cal = NULL;
if (!GetCalendar(oldcal, newcal, new_cal))
// Return to dialog
return false;
// Get updated info
GetComponent(*original);
// Look for change to calendar
if (new_cal != NULL)
{
// Remove from old calendar (without deleting)
old_cal->RemoveVToDo(original, false);
// Add to new calendar (without initialising)
original->SetCalendar(newcal);
new_cal->AddNewVToDo(original, true);
}
// Tell it it has changed (i.e. bump sequence, dirty calendar)
original->Changed();
CCalendarView::ToDosChangedAll();
return true;
}
void CNewToDoDialog::DoCancel()
{
// Delete the to do which we own and is not going to be used
delete mComponent;
mComponent = NULL;
}
void CNewToDoDialog::StartNew(const iCal::CICalendar* calin)
{
const iCal::CICalendarList& cals = calstore::CCalendarStoreManager::sCalendarStoreManager->GetActiveCalendars();
if (cals.size() == 0)
return;
const iCal::CICalendar* cal = calin;
if (cal == NULL)
{
// Default calendar is the first one
cal = cals.front();
// Check prefs for default calendar
const calstore::CCalendarStoreNode* node = calstore::CCalendarStoreManager::sCalendarStoreManager->GetNode(CPreferences::sPrefs->mDefaultCalendar.GetValue());
if ((node != NULL) && (node->GetCalendar() != NULL))
cal = node->GetCalendar();
}
// Start with an empty to do
iCal::CICalendarVToDo* vtodo = static_cast<iCal::CICalendarVToDo*>(iCal::CICalendarVToDo::Create(cal->GetRef()));
// Set event with initial timing
vtodo->EditTiming();
StartModeless(*vtodo, NULL, CNewToDoDialog::eNew);
}
void CNewToDoDialog::StartEdit(const iCal::CICalendarVToDo& original, const iCal::CICalendarComponentExpanded* expanded)
{
// Look for an existinf dialog for this event
for(std::set<CNewComponentDialog*>::const_iterator iter = sDialogs.begin(); iter != sDialogs.end(); iter++)
{
if ((*iter)->ContainsComponent(original))
{
(*iter)->GetWindow()->Raise();
return;
}
}
// Use a copy of the event
iCal::CICalendarVToDo* vtodo = new iCal::CICalendarVToDo(original);
StartModeless(*vtodo, expanded, CNewToDoDialog::eEdit);
}
void CNewToDoDialog::StartDuplicate(const iCal::CICalendarVToDo& original)
{
// Start with an empty new event
iCal::CICalendarVToDo* vtodo = new iCal::CICalendarVToDo(original);
vtodo->Duplicated();
StartModeless(*vtodo, NULL, CNewToDoDialog::eDuplicate);
}
void CNewToDoDialog::StartModeless(iCal::CICalendarVToDo& vtodo, const iCal::CICalendarComponentExpanded* expanded, EModelessAction action)
{
CNewToDoDialog* dlog = new CNewToDoDialog(JXGetApplication());
dlog->OnCreate();
dlog->SetAction(action);
dlog->SetComponent(vtodo, expanded);
dlog->Activate();
}
| 29.208877 | 160 | 0.729061 | mbert |
5d90141e91eaab1b66e07275ade6195d2c77477e | 15,556 | cpp | C++ | third_party/omr/compiler/infra/InterferenceGraph.cpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/compiler/infra/InterferenceGraph.cpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/compiler/infra/InterferenceGraph.cpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2000, 2019 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at http://eclipse.org/legal/epl-2.0
* or the Apache License, Version 2.0 which accompanies this distribution
* and is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License, v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception [1] and GNU General Public
* License, version 2 with the OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
#include "infra/InterferenceGraph.hpp"
#include <stdint.h>
#include <string.h>
#include "env/StackMemoryRegion.hpp"
#include "compile/Compilation.hpp"
#include "cs2/bitvectr.h"
#include "env/TRMemory.hpp"
#include "infra/Array.hpp"
#include "infra/Assert.hpp"
#include "infra/BitVector.hpp"
#include "infra/IGBase.hpp"
#include "infra/IGNode.hpp"
#include "infra/List.hpp"
#include "infra/Stack.hpp"
TR_InterferenceGraph::TR_InterferenceGraph(TR::Compilation *comp, int32_t estimatedNodes) :
_compilation(comp),
_nodeTable(NULL),
_nodeStack(NULL),
_trMemory(comp->trMemory()),
TR_IGBase()
{
TR_ASSERT(estimatedNodes > 0, "interference graph must be created with a node estimate!");
int32_t numBits = (estimatedNodes * (estimatedNodes - 1)) >> 1;
setInterferenceMatrix(new (trHeapMemory()) TR_BitVector(numBits, trMemory(), heapAlloc, growable));
_nodeTable = new (trHeapMemory()) TR_Array<TR_IGNode *>(trMemory(), estimatedNodes, false, heapAlloc);
_nodeStack = new (trHeapMemory()) TR_Stack<TR_IGNode *>(trMemory(), estimatedNodes, false, heapAlloc);
// TODO: allocate from stack memory
//
_entityHash._numBuckets = 73;
_entityHash._buckets = (HashTableEntry **)trMemory()->allocateHeapMemory(_entityHash._numBuckets*sizeof(HashTableEntry *));
memset(_entityHash._buckets, 0, _entityHash._numBuckets*sizeof(HashTableEntry *));
}
// Add a new, unique entity to the interference graph.
//
TR_IGNode *TR_InterferenceGraph::add(void *entity, bool ignoreDuplicates)
{
TR_IGNode *igNode = getIGNodeForEntity(entity);
if (igNode != NULL && ignoreDuplicates)
return igNode;
TR_ASSERT(!igNode,
"entity %p already exists in this interference graph\n", entity);
igNode = new (trHeapMemory()) TR_IGNode(entity, trMemory());
addIGNodeToEntityHash(igNode);
igNode->setIndex(getNumNodes());
((*_nodeTable)[getNumNodes()]) = igNode;
incNumNodes();
return igNode;
}
// Add an interference between two existing entities in an interference graph.
//
void TR_InterferenceGraph::addInterferenceBetween(TR_IGNode *igNode1,
TR_IGNode *igNode2)
{
IMIndex bitNum = getNodePairToBVIndex(igNode1->getIndex(), igNode2->getIndex());
if (igNode1 != igNode2 && !getInterferenceMatrix()->isSet(bitNum))
{
getInterferenceMatrix()->set(bitNum);
igNode2->getAdjList().add(igNode1);
igNode1->getAdjList().add(igNode2);
igNode2->incDegree();
igNode1->incDegree();
}
}
bool TR_InterferenceGraph::hasInterference(void *entity1,
void *entity2)
{
TR_IGNode *igNode1 = getIGNodeForEntity(entity1);
TR_IGNode *igNode2 = getIGNodeForEntity(entity2);
TR_ASSERT(igNode1, "hasInterference: entity1 %p does not exist in this interference graph\n", entity1);
TR_ASSERT(igNode2, "hasInterference: entity2 %p does not exist in this interference graph\n", entity2);
IMIndex bit = getNodePairToBVIndex(igNode1->getIndex(), igNode2->getIndex());
return getInterferenceMatrix()->isSet(bit);
}
void TR_InterferenceGraph::removeInterferenceBetween(TR_IGNode *igNode1, TR_IGNode *igNode2)
{
igNode1->getAdjList().remove(igNode2);
igNode2->getAdjList().remove(igNode1);
igNode1->decDegree();
igNode2->decDegree();
IMIndex bit = getNodePairToBVIndex(igNode1->getIndex(), igNode2->getIndex());
getInterferenceMatrix()->reset(bit);
}
void TR_InterferenceGraph::removeAllInterferences(void *entity)
{
TR_IGNode *igNode = getIGNodeForEntity(entity);
TR_ASSERT(igNode, "removeAllInterferences: entity %p is not in the interference graph\n", entity);
ListIterator<TR_IGNode> iterator(&igNode->getAdjList());
TR_IGNode *cursor = iterator.getFirst();
IMIndex bit;
while (cursor)
{
cursor->getAdjList().remove(igNode);
cursor->decDegree();
bit = getNodePairToBVIndex(igNode->getIndex(), igNode->getIndex());
getInterferenceMatrix()->reset(bit);
cursor = iterator.getNext();
}
// reset working degree?
igNode->setDegree(0);
igNode->getAdjList().deleteAll();
}
void TR_InterferenceGraph::addIGNodeToEntityHash(TR_IGNode *igNode)
{
void *entity = igNode->getEntity();
TR_ASSERT(entity, "addIGNodeToEntityHash: IGNode %p does not reference its data\n", igNode);
int32_t hashBucket = entityHashBucket(entity);
// TODO: allocate from stack memory
//
HashTableEntry *entry = (HashTableEntry *)trMemory()->allocateHeapMemory(sizeof(HashTableEntry));
entry->_igNode = igNode;
HashTableEntry *prevEntry = _entityHash._buckets[hashBucket];
if (prevEntry)
{
entry->_next = prevEntry->_next;
prevEntry->_next = entry;
}
else
entry->_next = entry;
_entityHash._buckets[hashBucket] = entry;
}
TR_IGNode * TR_InterferenceGraph::getIGNodeForEntity(void *entity)
{
int32_t hashBucket = entityHashBucket(entity);
HashTableEntry *firstEntry = _entityHash._buckets[hashBucket];
if (firstEntry)
{
HashTableEntry *entry = firstEntry;
do
{
if (entry->_igNode->getEntity() == entity)
{
return entry->_igNode;
}
entry = entry->_next;
}
while (entry != firstEntry);
}
return NULL;
}
// Doesn't actually remove a node from the IG, but adjusts the working degrees of its
// neighbours and itself to appear that way.
//
void TR_InterferenceGraph::virtualRemoveEntityFromIG(void *entity)
{
TR_IGNode *igNode = getIGNodeForEntity(entity);
igNode->decWorkingDegreeOfNeighbours();
igNode->setIsRemovedFromIG();
igNode->setWorkingDegree(0);
}
// Doesn't actually remove a node from the IG, but adjusts the working degrees of its
// neighbours and itself to appear that way.
//
void TR_InterferenceGraph::virtualRemoveNodeFromIG(TR_IGNode *igNode)
{
igNode->decWorkingDegreeOfNeighbours();
igNode->setIsRemovedFromIG();
igNode->setWorkingDegree(0);
}
// Partition the nodes identified by the 'workingSet' bit vector into sets
// based on their degree.
//
void TR_InterferenceGraph::partitionNodesIntoDegreeSets(CS2::ABitVector<TR::Allocator> &workingSet,
CS2::ABitVector<TR::Allocator> &colourableDegreeSet,
CS2::ABitVector<TR::Allocator> ¬ColourableDegreeSet)
{
int32_t i;
CS2::ABitVector<TR::Allocator>::Cursor bvc(workingSet);
TR_ASSERT(getNumColours() > 0,
"can't partition without knowing the number of available colours\n");
// Empty the existing degree sets.
//
colourableDegreeSet.Clear();
colourableDegreeSet.GrowTo(getNumColours());
notColourableDegreeSet.Clear();
notColourableDegreeSet.GrowTo(getNumColours());
// Partition the specified nodes into sets based on their working degree.
//
for(bvc.SetToFirstOne(); bvc.Valid(); bvc.SetToNextOne())
{
i = bvc;
if (getNodeTable(i)->getWorkingDegree() < getNumColours())
{
colourableDegreeSet[i] = 1;
}
else
{
notColourableDegreeSet[i] = 1;
}
}
#ifdef DEBUG
if (debug("traceIG"))
{
diagnostic("\nPartitioned Nodes\n");
diagnostic("-----------------\n");
diagnostic("\n[%4d] degree < %-10d : ", colourableDegreeSet.PopulationCount(), getNumColours());
(*comp()) << colourableDegreeSet;
diagnostic("\n[%4d] degree < MAX_DEGREE : ", notColourableDegreeSet.PopulationCount());
(*comp()) << notColourableDegreeSet;
diagnostic("\n\n");
}
#endif
}
IGNodeDegree TR_InterferenceGraph::findMaxDegree()
{
IGNodeDegree maxDegree = 0;
for (IGNodeIndex i=0; i<getNumNodes(); i++)
{
if (getNodeTable(i)->getDegree() > maxDegree)
{
maxDegree = getNodeTable(i)->getDegree();
}
}
return maxDegree;
}
// General Briggs graph colouring algorithm.
//
bool TR_InterferenceGraph::doColouring(IGNodeColour numColours)
{
bool success;
TR::StackMemoryRegion stackMemoryRegion(*trMemory());
TR_ASSERT(numColours > 0, "doColouring: invalid chromatic number\n");
setNumColours(numColours);
// TODO: reset stacks, colours?
//
if ((success = simplify()))
{
success = select();
}
if (debug("traceIG"))
{
if (!success)
{
diagnostic("COLOUR IG: Could not find a colouring for IG %p with %d colours.\n",
this, numColours);
}
else
{
diagnostic("COLOUR IG: IG %p coloured with %d colours.\n", this, getNumberOfColoursUsedToColour());
}
}
return success;
}
// Find the minimum number of colours required to colour this interference graph.
//
IGNodeColour TR_InterferenceGraph::findMinimumChromaticNumber()
{
return 0;
}
// Perform Simplify colouring phase on an interference graph.
//
bool TR_InterferenceGraph::simplify()
{
TR_IGNode *igNode,
*bestSpillNode;
int32_t i;
if (getNumNodes()==0) return true;
CS2::ABitVector<TR::Allocator> workingSet(comp()->allocator());
workingSet.SetAll(getNumNodes());
CS2::ABitVector<TR::Allocator> colourableDegreeSet(comp()->allocator());
CS2::ABitVector<TR::Allocator> notColourableDegreeSet(comp()->allocator());
colourableDegreeSet.GrowTo(getNumNodes());
notColourableDegreeSet.GrowTo(getNumNodes());
for (i=0; i<getNumNodes(); i++)
{
igNode = getNodeTable(i);
igNode->setWorkingDegree(igNode->getDegree());
igNode->resetIsRemovedFromIG();
igNode->setColour(UNCOLOURED);
}
while (!workingSet.IsZero())
{
partitionNodesIntoDegreeSets(workingSet,colourableDegreeSet,notColourableDegreeSet);
// Push nodes from the colourable set onto the stack and adjust the degrees of
// their neighbours until there are no nodes remaining in the colourable set.
//
if (!colourableDegreeSet.IsZero())
{
CS2::ABitVector<TR::Allocator>::Cursor colourableCursor(colourableDegreeSet);
for(colourableCursor.SetToFirstOne(); colourableCursor.Valid(); colourableCursor.SetToNextOne())
{
igNode = getNodeTable(colourableCursor);
if (debug("traceIG"))
{
diagnostic("SIMPLIFY: Selected colourable IG node #%d with degree %d: (igNode=%p, entity=%p)\n",
igNode->getIndex(), igNode->getWorkingDegree(), igNode, igNode->getEntity());
}
virtualRemoveNodeFromIG(igNode);
workingSet[igNode->getIndex()] = 0;
getNodeStack()->push(igNode);
}
// Repartition the nodes.
//
continue;
}
// There are no nodes left in the colourable set. Choose a spill candidate among nodes in
// the non-colourable degree set.
//
TR_ASSERT(!notColourableDegreeSet.IsZero(),
"not colourable set must contain at least one member\n");
CS2::ABitVector<TR::Allocator>::Cursor notColourableCursor(notColourableDegreeSet);
if (!notColourableDegreeSet.IsZero())
{
// Choose the node from this degree set with the largest degree
// and optimistically push it onto the stack.
//
int32_t degree = -1;
bestSpillNode = NULL;
for(notColourableCursor.SetToFirstOne(); notColourableCursor.Valid(); notColourableCursor.SetToNextOne())
{
igNode = getNodeTable(notColourableCursor);
if (igNode->getDegree() > degree)
{
degree = igNode->getDegree();
bestSpillNode = igNode;
}
}
TR_ASSERT(bestSpillNode, "Could not find a spill candidate.\n");
virtualRemoveNodeFromIG(bestSpillNode);
workingSet[bestSpillNode->getIndex()] = 0;
getNodeStack()->push(bestSpillNode);
}
}
return true;
}
// Perform Select colouring phase on an interference graph.
//
bool TR_InterferenceGraph::select()
{
TR_IGNode *igNode;
TR_BitVectorIterator bvi;
CS2::ABitVector<TR::Allocator> availableColours(comp()->allocator());
CS2::ABitVector<TR::Allocator> assignedColours(comp()->allocator());
availableColours.GrowTo(getNumColours());
assignedColours.GrowTo(getNumColours());
setNumberOfColoursUsedToColour(0);
while (!getNodeStack()->isEmpty())
{
igNode = getNodeStack()->pop();
availableColours.SetAll(getNumColours());
ListIterator<TR_IGNode> iterator(&igNode->getAdjList());
TR_IGNode *adjCursor = iterator.getFirst();
while (adjCursor)
{
if (adjCursor->getColour() != UNCOLOURED)
{
availableColours[adjCursor->getColour()] = 0;
}
adjCursor = iterator.getNext();
}
if (debug("traceIG"))
{
diagnostic("SELECT: For IG node #%d (%p), available colours = ", igNode->getIndex(), igNode);
(*comp()) << availableColours;
diagnostic("\n");
}
if (!availableColours.IsZero())
{
IGNodeColour colour = (IGNodeColour)availableColours.FirstOne();
igNode->setColour(colour);
assignedColours[colour] = 1;
if (debug("traceIG"))
{
diagnostic(" Selected colour: %d\n", colour);
}
}
else
{
// No colours are available. Colouring has failed.
//
if (debug("traceIG"))
{
diagnostic(" NO COLOURS AVAILABLE\n");
}
return false;
}
}
setNumberOfColoursUsedToColour(assignedColours.PopulationCount());
return true;
}
#ifdef DEBUG
void TR_InterferenceGraph::dumpIG(char *msg)
{
if (msg)
{
diagnostic("\nINTERFERENCE GRAPH %p: %s\n\n", this, msg);
}
else
{
diagnostic("\nINTERFERENCE GRAPH %p\n\n", this);
}
for (IGNodeIndex i=0; i<getNumNodes(); i++)
{
getNodeTable(i)->print(comp());
}
}
#endif
| 29.973025 | 135 | 0.63776 | xiacijie |
5d90bee147dfe8c48b075fc0324867a3507cd88b | 3,654 | cpp | C++ | Benchmarks/BenchmarkUtils.cpp | kirill-pinigin/Wuild | 1524c1d8a054f6455941538d5b824613fc028894 | [
"Apache-2.0"
] | 1 | 2019-06-20T04:30:43.000Z | 2019-06-20T04:30:43.000Z | Benchmarks/BenchmarkUtils.cpp | kirill-pinigin/Wuild | 1524c1d8a054f6455941538d5b824613fc028894 | [
"Apache-2.0"
] | null | null | null | Benchmarks/BenchmarkUtils.cpp | kirill-pinigin/Wuild | 1524c1d8a054f6455941538d5b824613fc028894 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2018 Smirnov Vladimir mapron1@gmail.com
* Source code 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 or in file COPYING-APACHE-2.0.txt
*
* 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.h
*/
#include "BenchmarkUtils.h"
#include <ByteOrderStreamTypes.h>
namespace Wuild
{
FileFrame::FileFrame()
{
m_writeLength = true;
}
void FileFrame::LogTo(std::ostream &os) const
{
SocketFrame::LogTo(os);
os << " file: [" << m_fileData.size();
;
}
SocketFrame::State FileFrame::ReadInternal(ByteOrderDataStreamReader &stream)
{
stream >> m_processTime;
stream >> m_fileData;
return stOk;
}
SocketFrame::State FileFrame::WriteInternal(ByteOrderDataStreamWriter &stream) const
{
stream << m_processTime;
stream << m_fileData;
return stOk;
}
namespace
{
const int segmentSize = 8192;
const int bufferSize = 64 * 1024;
const int testServicePort = 12345;
void ProcessServerData(const ByteArrayHolder & input, ByteArrayHolder & output)
{
output.resize(input.size());
for (size_t i = 0; i< input.size(); ++i)
output.data()[i] = input.data()[i] ^ uint8_t(0x80);
}
}
void TestService::startServer()
{
Syslogger(Syslogger::Info) << "Listening on:" << testServicePort;
SocketFrameHandlerSettings settings;
settings.m_recommendedRecieveBufferSize = bufferSize;
settings.m_recommendedSendBufferSize = bufferSize;
settings.m_segmentSize = segmentSize;
m_server = std::make_unique<SocketFrameService>( settings );
m_server->AddTcpListener(testServicePort, "*");
m_server->RegisterFrameReader(SocketFrameReaderTemplate<FileFrame>::Create([](const FileFrame &inputMessage, SocketFrameHandler::OutputCallback outputCallback)
{
FileFrame::Ptr response(new FileFrame());
TimePoint processStart(true);
ProcessServerData(inputMessage.m_fileData, response->m_fileData);
response->m_processTime = processStart.GetElapsedTime();
outputCallback(response);
}));
m_server->Start();
}
void TestService::startClient(const std::string & host)
{
Syslogger() << "startClient " << host << ":" << testServicePort;
SocketFrameHandlerSettings settings;
settings.m_recommendedSendBufferSize = bufferSize;
settings.m_recommendedRecieveBufferSize = bufferSize;
settings.m_segmentSize = segmentSize;
SocketFrameHandler::Ptr h(new SocketFrameHandler(settings));
h->RegisterFrameReader(SocketFrameReaderTemplate<FileFrame>::Create([this](const FileFrame &inputMessage, SocketFrameHandler::OutputCallback )
{
Syslogger(Syslogger::Info) << "process time:" << inputMessage.m_processTime.ToProfilingTime();
std::unique_lock<std::mutex> lock(taskStateMutex);
taskCount--;
taskStateCond.notify_one();
}));
h->SetLogContext("client");
h->SetTcpChannel(host, testServicePort);
m_client = h;
m_client->Start();
}
void TestService::sendFile(size_t size)
{
FileFrame::Ptr request(new FileFrame());
request->m_fileData.resize(size);
for (size_t i = 0; i < size; ++i)
request->m_fileData.data()[i] = uint8_t(i % 256);
m_client->QueueFrame(request);
std::unique_lock<std::mutex> lock(taskStateMutex);
taskCount++;
}
void TestService::waitForReplies()
{
std::unique_lock<std::mutex> lock(taskStateMutex);
taskStateCond.wait(lock, [this]{
return taskCount == 0;
});
}
}
| 29.232 | 160 | 0.749863 | kirill-pinigin |
5d92bbd820187dea53283279f100927a6d8aeca3 | 969 | cpp | C++ | mogupro/game/src/Sound/cSE.cpp | desspert/mogupro | ac39f5ec3fb670cf5044ef501951270d7d92a748 | [
"MIT"
] | null | null | null | mogupro/game/src/Sound/cSE.cpp | desspert/mogupro | ac39f5ec3fb670cf5044ef501951270d7d92a748 | [
"MIT"
] | null | null | null | mogupro/game/src/Sound/cSE.cpp | desspert/mogupro | ac39f5ec3fb670cf5044ef501951270d7d92a748 | [
"MIT"
] | null | null | null | #include <Sound/cSE.h>
#include <cinder/app/App.h>
namespace Sound
{
using namespace cinder;
cSE::cSE( std::string const& assetsSePath )
{
auto ctx = audio::master( );
ctx->enable( );
mGainRef = ctx->makeNode( new audio::GainNode( 1.0F ) );
mBufferPlayerRef = ctx->makeNode( new audio::BufferPlayerNode( ) );
mBufferPlayerRef->loadBuffer( audio::load( app::loadAsset( assetsSePath ) ) );
mBufferPlayerRef >> mGainRef >> ctx->getOutput( );
};
cSE::~cSE( )
{
stop( );
}
void cSE::play( )
{
mBufferPlayerRef->start( );
}
void cSE::stop( )
{
mBufferPlayerRef->stop( );
}
bool cSE::isPlaying( )
{
return mBufferPlayerRef->isEnabled( );
}
bool cSE::isLooping( )
{
return mBufferPlayerRef->isLoopEnabled( );
}
void cSE::setLooping( const bool islooping )
{
mBufferPlayerRef->setLoopEnabled( islooping );
}
void cSE::setGain( const float gain )
{
mGainRef->setValue( gain );
}
;
}
| 21.533333 | 83 | 0.625387 | desspert |
5d93a684b854063b4df7b8fedd29f58eeb77cecc | 10,716 | cc | C++ | targets/ARCH/ETHERNET/oran/5g/oran.cc | Ting-An-Lin/OAI_ORAN_FHI_integration | 0671d428ce5ad5d6040b393c90679d59c074bd2d | [
"Apache-2.0"
] | 1 | 2021-12-14T12:07:10.000Z | 2021-12-14T12:07:10.000Z | targets/ARCH/ETHERNET/oran/5g/oran.cc | Ting-An-Lin/OAI_ORAN_FHI_integration | 0671d428ce5ad5d6040b393c90679d59c074bd2d | [
"Apache-2.0"
] | null | null | null | targets/ARCH/ETHERNET/oran/5g/oran.cc | Ting-An-Lin/OAI_ORAN_FHI_integration | 0671d428ce5ad5d6040b393c90679d59c074bd2d | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698
*
* 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.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* contact@openairinterface.org
*/
#include <stdio.h>
#include "common_lib.h"
#include "ethernet_lib.h"
#include "shared_buffers.h"
#include "openair1/PHY/defs_nr_common.h"
#include "xran_lib_wrap.hpp"
typedef struct {
eth_state_t e;
shared_buffers buffers;
rru_config_msg_type_t last_msg;
int capabilities_sent;
void *oran_priv;
} oran_eth_state_t;
char *msg_type(int t)
{
static char *s[12] = {
"RAU_tick",
"RRU_capabilities",
"RRU_config",
"RRU_config_ok",
"RRU_start",
"RRU_stop",
"RRU_sync_ok",
"RRU_frame_resynch",
"RRU_MSG_max_num",
"RRU_check_sync",
"RRU_config_update",
"RRU_config_update_ok",
};
if (t < 0 || t > 11) return "UNKNOWN";
return s[t];
}
void xran_fh_rx_callback(void *pCallbackTag, xran_status_t status){
rte_pause();
}
void xran_fh_srs_callback(void *pCallbackTag, xran_status_t status){
rte_pause();
}
void xran_fh_rx_prach_callback(void *pCallbackTag, xran_status_t status){
rte_pause();
}
int trx_oran_start(openair0_device *device)
{
xranLibWraper *xranlib;
xranlib = new xranLibWraper;
if(xranlib->SetUp() < 0) {
return (-1);
}
xranlib->Init();
xranlib->Open(nullptr,
nullptr,
(void *)xran_fh_rx_callback,
(void *)xran_fh_rx_prach_callback,
(void *)xran_fh_srs_callback);
xranlib->Start();
printf("ORAN 5G: %s\n", __FUNCTION__);
return 0;
}
void trx_oran_end(openair0_device *device)
{
printf("ORAN: %s\n", __FUNCTION__);
}
int trx_oran_stop(openair0_device *device)
{
printf("ORAN: %s\n", __FUNCTION__);
return(0);
}
int trx_oran_set_freq(openair0_device* device,
openair0_config_t *openair0_cfg,
int exmimo_dump_config)
{
printf("ORAN: %s\n", __FUNCTION__);
return(0);
}
int trx_oran_set_gains(openair0_device* device,
openair0_config_t *openair0_cfg)
{
printf("ORAN: %s\n", __FUNCTION__);
return(0);
}
int trx_oran_get_stats(openair0_device* device)
{
printf("ORAN: %s\n", __FUNCTION__);
return(0);
}
int trx_oran_reset_stats(openair0_device* device)
{
printf("ORAN: %s\n", __FUNCTION__);
return(0);
}
int ethernet_tune(openair0_device *device,
unsigned int option,
int value)
{
printf("ORAN: %s\n", __FUNCTION__);
return 0;
}
int trx_oran_write_raw(openair0_device *device,
openair0_timestamp timestamp,
void **buff, int nsamps, int cc, int flags)
{
printf("ORAN: %s\n", __FUNCTION__);
return nsamps*4;
}
int trx_oran_read_raw(openair0_device *device,
openair0_timestamp *timestamp,
void **buff, int nsamps, int cc)
{
printf("ORAN: %s\n", __FUNCTION__);
return nsamps*4;
}
int trx_oran_ctlsend(openair0_device *device, void *msg, ssize_t msg_len)
{
RRU_CONFIG_msg_t *rru_config_msg = msg;
oran_eth_state_t *s = device->priv;
printf("ORAN 5G: %s\n", __FUNCTION__);
printf(" rru_config_msg->type %d [%s]\n", rru_config_msg->type,
msg_type(rru_config_msg->type));
s->last_msg = rru_config_msg->type;
return msg_len;
}
int trx_oran_ctlrecv(openair0_device *device, void *msg, ssize_t msg_len)
{
RRU_CONFIG_msg_t *rru_config_msg = msg;
oran_eth_state_t *s = device->priv;
printf("ORAN 5G: %s\n", __FUNCTION__);
if (s->last_msg == RAU_tick && s->capabilities_sent == 0) {
RRU_capabilities_t *cap;
rru_config_msg->type = RRU_capabilities;
rru_config_msg->len = sizeof(RRU_CONFIG_msg_t)-MAX_RRU_CONFIG_SIZE+sizeof(RRU_capabilities_t);
cap = (RRU_capabilities_t*)&rru_config_msg->msg[0];
cap->FH_fmt = ORAN_only;
cap->num_bands = 1;
cap->band_list[0] = 78;
cap->nb_rx[0] = 1;
cap->nb_tx[0] = 1;
cap->max_pdschReferenceSignalPower[0] = -27;
cap->max_rxgain[0] = 90;
s->capabilities_sent = 1;
return rru_config_msg->len;
}
// if (s->last_msg == RRU_config) {
// rru_config_msg->type = RRU_config_ok;
// return 0;
// }
printf("--------------- rru_config_msg->type %d [%s]\n", rru_config_msg->type,
msg_type(rru_config_msg->type));
if (s->last_msg == RRU_config) {
rru_config_msg->type = RRU_config_ok;
printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
s->oran_priv = oran_start(s->e.if_name, &s->buffers);
}
return 0;
}
/*This function reads the IQ samples from OAI, symbol by symbol.
It also handles the shared buffers. */
void oran_fh_if4p5_south_in(RU_t *ru,
int *frame,
int *slot)
{
oran_eth_state_t *s = ru->ifdevice.priv;
NR_DL_FRAME_PARMS *fp;
int symbol;
int32_t *rxdata;
int antenna = 0;
printf("Ann in oran.c: nr_oran_fh_if4p5_south_in\n");
lock_ul_buffers(&s->buffers, *slot);
next:
while (!(s->buffers.ul_busy[*slot] == 0x3fff ||
s->buffers.prach_busy[*slot] == 1))
wait_buffers(&s->buffers, *slot);
if (s->buffers.prach_busy[*slot] == 1) {
int i;
int antenna = 0;
uint16_t *in;
uint16_t *out;
in = (uint16_t *)s->buffers.prach[*slot];
out = (uint16_t *)ru->prach_rxsigF[antenna];
for (i = 0; i < 849; i++)
out[i] = ntohs(in[i]);
s->buffers.prach_busy[*slot] = 0;
ru->wakeup_prach_gNB(ru->gNB_list[0], ru, *frame, *slot);
goto next;
}
fp = ru->nr_frame_parms;
for (symbol = 0; symbol < 14; symbol++) {
int i;
uint16_t *p = (uint16_t *)(&s->buffers.ul[*slot][symbol*1272*4]);
for (i = 0; i < 1272*2; i++) {
p[i] = htons(p[i]);
}
rxdata = &ru->common.rxdataF[antenna][symbol * fp->ofdm_symbol_size];
#if 1
memcpy(rxdata + 2048 - 1272/2,
&s->buffers.ul[*slot][symbol*1272*4],
(1272/2) * 4);
memcpy(rxdata,
&s->buffers.ul[*slot][symbol*1272*4] + (1272/2)*4,
(1272/2) * 4);
#endif
}
s->buffers.ul_busy[*slot] = 0;
signal_buffers(&s->buffers, *slot);
unlock_buffers(&s->buffers, *slot);
//printf("ORAN: %s (f.sf %d.%d)\n", __FUNCTION__, *frame, *subframe);
RU_proc_t *proc = &ru->proc;
extern uint16_t sl_ahead;
int f = *frame;
int sl = *slot;
//calculate timestamp_rx, timestamp_tx based on frame and subframe
proc->tti_rx = sl;
proc->frame_rx = f;
proc->timestamp_rx = ((proc->frame_rx * 20) + proc->tti_rx ) * fp->samples_per_tti ;
if (get_nprocs()<=4) {
proc->tti_tx = (sl+sl_ahead)%20;
proc->frame_tx = (sl>(19-sl_ahead)) ? (f+1)&1023 : f;
}
}
void oran_fh_if4p5_south_out(RU_t *ru,
int frame,
int slot,
uint64_t timestamp)
{
oran_eth_state_t *s = ru->ifdevice.priv;
NR_DL_FRAME_PARMS *fp;
int symbol;
int32_t *txdata;
int aa = 0;
printf("Ann in oran.c: oran_fh_if4p5_south_out\n");
//printf("ORAN: %s (f.sf %d.%d ts %ld)\n", __FUNCTION__, frame, subframe, timestamp);
lock_dl_buffers(&s->buffers, slot);
fp = ru->nr_frame_parms;
if (ru->num_gNB != 1 || ru->nb_tx != 1 || fp->ofdm_symbol_size != 2048 ||
fp->Ncp != NORMAL || fp->symbols_per_slot != 14) {
printf("%s:%d:%s: unsupported configuration\n",
__FILE__, __LINE__, __FUNCTION__);
exit(1);
}
for (symbol = 0; symbol < 14; symbol++) {
txdata = &ru->common.txdataF_BF[aa][symbol * fp->ofdm_symbol_size];
#if 1
memcpy(&s->buffers.dl[slot][symbol*1272*4],
txdata + 2048 - (1272/2),
(1272/2) * 4);
memcpy(&s->buffers.dl[slot][symbol*1272*4] + (1272/2)*4,
txdata + 1,
(1272/2) * 4);
#endif
int i;
uint16_t *p = (uint16_t *)(&s->buffers.dl[slot][symbol*1272*4]);
for (i = 0; i < 1272*2; i++) {
p[i] = htons(p[i]);
}
}
s->buffers.dl_busy[slot] = 0x3fff;
unlock_buffers(&s->buffers, slot);
}
void *get_internal_parameter(char *name)
{
printf("BENETEL 5G: %s\n", __FUNCTION__);
if (!strcmp(name, "fh_if4p5_south_in"))
return oran_fh_if4p5_south_in;
if (!strcmp(name, "fh_if4p5_south_out"))
return oran_fh_if4p5_south_out;
return NULL;
}
__attribute__((__visibility__("default")))
int transport_init(openair0_device *device,
openair0_config_t *openair0_cfg,
eth_params_t * eth_params )
{
oran_eth_state_t *eth;
printf("Ann: ORANNNi 5g\n");
printf("ORAN 5g: %s\n", __FUNCTION__);
device->Mod_id = 0;
device->transp_type = ETHERNET_TP;
device->trx_start_func = trx_oran_start;
device->trx_get_stats_func = trx_oran_get_stats;
device->trx_reset_stats_func = trx_oran_reset_stats;
device->trx_end_func = trx_oran_end;
device->trx_stop_func = trx_oran_stop;
device->trx_set_freq_func = trx_oran_set_freq;
device->trx_set_gains_func = trx_oran_set_gains;
device->trx_write_func = trx_oran_write_raw;
device->trx_read_func = trx_oran_read_raw;
device->trx_ctlsend_func = trx_oran_ctlsend;
device->trx_ctlrecv_func = trx_oran_ctlrecv;
device->get_internal_parameter = get_internal_parameter;
eth = calloc(1, sizeof(oran_eth_state_t));
if (eth == NULL) {
AssertFatal(0==1, "out of memory\n");
}
eth->e.flags = ETH_RAW_IF4p5_MODE;
eth->e.compression = NO_COMPRESS;
eth->e.if_name = eth_params->local_if_name;
device->priv = eth;
device->openair0_cfg=&openair0_cfg[0];
eth->last_msg = -1;
init_buffers(ð->buffers);
return 0;
}
| 25.946731 | 99 | 0.616461 | Ting-An-Lin |
5d94c25e1c854ddf57fa85a8230f66057227d78c | 3,215 | cc | C++ | Engine/spcOpenGL/gl4/gl4texturecube.cc | marcellfischbach/SpiceEngine | e25e1e4145b7afaea9179bb8e33e4d184bd407c4 | [
"BSD-3-Clause"
] | null | null | null | Engine/spcOpenGL/gl4/gl4texturecube.cc | marcellfischbach/SpiceEngine | e25e1e4145b7afaea9179bb8e33e4d184bd407c4 | [
"BSD-3-Clause"
] | 1 | 2021-09-09T12:51:56.000Z | 2021-09-09T12:51:56.000Z | Engine/spcOpenGL/gl4/gl4texturecube.cc | marcellfischbach/SpiceEngine | e25e1e4145b7afaea9179bb8e33e4d184bd407c4 | [
"BSD-3-Clause"
] | null | null | null |
#include <spcOpenGL/gl4/gl4texturecube.hh>
#include <spcOpenGL/gl4/gl4pixelformatmap.hh>
#include <spcCore/graphics/image.hh>
#include <spcCore/graphics/isampler.hh>
#include <spcCore/math/math.hh>
#include <GL/glew.h>
namespace spc::opengl
{
GL4TextureCube::GL4TextureCube()
: iTextureCube()
, m_size(0)
, m_sampler(nullptr)
{
SPC_CLASS_GEN_CONSTR;
glGenTextures(1, &m_name);
}
GL4TextureCube::~GL4TextureCube()
{
glDeleteTextures(1, &m_name);
m_name = 0;
}
void GL4TextureCube::Bind()
{
glBindTexture(GL_TEXTURE_CUBE_MAP, m_name);
}
bool GL4TextureCube::Initialize(UInt16 size, ePixelFormat format, bool generateMipMaps)
{
m_size = size;
m_format = format;
Bind();
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_REPEAT);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
UInt8 level = 0;
while (true)
{
Level lvl;
lvl.Size = size;
m_level.push_back(lvl);
for (GLenum i=0; i<6; i++)
{
glTexImage2D(
GL_TEXTURE_CUBE_MAP_POSITIVE_X + i,
level,
GL4PixelFormatInternal[format],
size,
size,
0,
GL4PixelFormatClient[format],
GL4PixelFormatClientDataType[format],
nullptr
);
}
if (!generateMipMaps || size == 1)
{
break;
}
size = spcMax(size / 2, 1);
level++;
}
return true;
}
void GL4TextureCube::Data(eCubeFace face, const Image* image)
{
for (UInt16 l=0; l<image->GetNumberOfLayers(); l++)
{
Data(face, l, image->GetPixelFormat(), image->GetData(l));
}
}
void GL4TextureCube::Data(eCubeFace face, UInt16 level, const Image* image)
{
Data(face, level, image->GetPixelFormat(), image->GetData(level));
}
void GL4TextureCube::Data(eCubeFace face, UInt16 level, ePixelFormat format, const void* data)
{
if (level >= m_level.size())
{
return;
}
Level& lvl = m_level[level];
glTexSubImage2D(
GL_TEXTURE_CUBE_MAP_POSITIVE_X + static_cast<GLenum>(face),
level,
0, 0,
lvl.Size, lvl.Size,
GL4PixelFormatClient[format],
GL4PixelFormatClientDataType[format],
data
);
}
void GL4TextureCube::Data(eCubeFace face, UInt16 level, UInt16 x, UInt16 y, UInt16 width, UInt16 height, ePixelFormat format, const void* data)
{
if (level >= m_level.size())
{
return;
}
glTexSubImage2D(
GL_TEXTURE_CUBE_MAP_POSITIVE_X + static_cast<GLenum>(face),
level,
x, y,
width, height,
GL4PixelFormatClient[format],
GL4PixelFormatClientDataType[format],
data
);
}
void GL4TextureCube::SetSampler(iSampler* sampler)
{
SPC_SET(m_sampler, sampler);
}
iSampler* GL4TextureCube::GetSampler()
{
return m_sampler;
}
const iSampler* GL4TextureCube::GetSampler() const
{
return m_sampler;
}
ePixelFormat GL4TextureCube::GetFormat() const
{
return m_format;
}
}
| 21.870748 | 143 | 0.660653 | marcellfischbach |
5d9526abf5c7bea264daa0dccfd52e399b6a0bb7 | 2,363 | hpp | C++ | external/libcxx-test/support/nasty_macros.hpp | SenthilKumarGS/TizenRT | 691639aa9667de5d966f040f0291a402727ab6ae | [
"Apache-2.0"
] | 511 | 2017-03-29T09:14:09.000Z | 2022-03-30T23:10:29.000Z | external/libcxx-test/support/nasty_macros.hpp | SenthilKumarGS/TizenRT | 691639aa9667de5d966f040f0291a402727ab6ae | [
"Apache-2.0"
] | 4,673 | 2017-03-29T10:43:43.000Z | 2022-03-31T08:33:44.000Z | external/libcxx-test/support/nasty_macros.hpp | SenthilKumarGS/TizenRT | 691639aa9667de5d966f040f0291a402727ab6ae | [
"Apache-2.0"
] | 642 | 2017-03-30T20:45:33.000Z | 2022-03-24T17:07:33.000Z | /****************************************************************************
*
* Copyright 2018 Samsung Electronics 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.
*
****************************************************************************/
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef SUPPORT_NASTY_MACROS_HPP
#define SUPPORT_NASTY_MACROS_HPP
#define NASTY_MACRO This should not be expanded!!!
#define _A NASTY_MACRO
#define _B NASTY_MACRO
#define _C NASTY_MACRO
#define _D NASTY_MACRO
#define _E NASTY_MACRO
#define _F NASTY_MACRO
#define _G NASTY_MACRO
#define _H NASTY_MACRO
#define _I NASTY_MACRO
#define _J NASTY_MACRO
#define _K NASTY_MACRO
#define _L NASTY_MACRO
#define _M NASTY_MACRO
#define _N NASTY_MACRO
#define _O NASTY_MACRO
#define _P NASTY_MACRO
#define _Q NASTY_MACRO
#define _R NASTY_MACRO
#define _S NASTY_MACRO
#define _T NASTY_MACRO
#define _U NASTY_MACRO
#define _V NASTY_MACRO
#define _W NASTY_MACRO
#define _X NASTY_MACRO
#define _Y NASTY_MACRO
#define _Z NASTY_MACRO
// tchar.h defines these macros on Windows.
#define _UI NASTY_MACRO
#define _PUC NASTY_MACRO
#define _CPUC NASTY_MACRO
#define _PC NASTY_MACRO
#define _CRPC NASTY_MACRO
#define _CPC NASTY_MACRO
// Test that libc++ doesn't use names reserved by WIN32 API Macros.
// NOTE: Obviously we can only define these on non-windows platforms.
#ifndef _WIN32
#define __deallocate NASTY_MACRO
#define __out NASTY_MACRO
#endif
#define __output NASTY_MACRO
#define __input NASTY_MACRO
#endif // SUPPORT_NASTY_MACROS_HPP
| 31.092105 | 80 | 0.675413 | SenthilKumarGS |
5d9630bb657178c70776e9b77110e1e2b3f4d935 | 13,386 | cpp | C++ | enduser/windows.com/wuau/wuaulib/helpers.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | enduser/windows.com/wuau/wuaulib/helpers.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | enduser/windows.com/wuau/wuaulib/helpers.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //////////////////////////////////////////////////////////////////////////////
//
// SYSTEM: Windows Update AutoUpdate Client
//
// CLASS: N/A
// MODULE:
// FILE: helpers.CPP
// DESC: This file contains utility functions
//
//////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#pragma hdrstop
const LPTSTR HIDDEN_ITEMS_FILE = _T("hidden.xml");
const LPCTSTR AU_ENV_VARS::s_AUENVVARNAMES[] = {_T("AUCLTEXITEVT"),_T("EnableNo"), _T("EnableYes"), _T("RebootWarningMode"), _T("ManualReboot"), _T("StartTickCount")};
BOOL AU_ENV_VARS::ReadIn(void)
{
BOOL fRet = TRUE;
if (!GetBOOLEnvironmentVar(s_AUENVVARNAMES[3], &m_fRebootWarningMode))
{ // if not set, implies regular mode
m_fRebootWarningMode = FALSE;
}
if (m_fRebootWarningMode)
{
if (!GetBOOLEnvironmentVar(s_AUENVVARNAMES[1], &m_fEnableNo)
||!GetBOOLEnvironmentVar(s_AUENVVARNAMES[2], &m_fEnableYes)
||!GetBOOLEnvironmentVar(s_AUENVVARNAMES[4], &m_fManualReboot)
||!GetDWordEnvironmentVar(s_AUENVVARNAMES[5], &m_dwStartTickCount)
||!GetStringEnvironmentVar(s_AUENVVARNAMES[0], m_szClientExitEvtName, ARRAYSIZE(m_szClientExitEvtName)))
{
DEBUGMSG("AU_ENV_VARS fails to read in");
return FALSE;
}
// DEBUGMSG("AU_ENV_VARS read in fEnableYes = %d, fEnableNo = %d, fManualReboot = %d, dwStartTickCount = %d",
// m_fEnableYes, m_fEnableNo, m_fManualReboot, m_dwStartTickCount);
}
// DEBUGMSG("AU_ENV_VARS read in fRebootWarningMode = %d", m_fRebootWarningMode);
return TRUE;
}
BOOL AU_ENV_VARS::WriteOut(LPTSTR szEnvBuf,
size_t IN cchEnvBuf,
BOOL IN fEnableYes,
BOOL IN fEnableNo,
BOOL IN fManualReboot,
DWORD IN dwStartTickCount,
LPCTSTR IN szClientExitEvtName)
{
TCHAR buf2[s_AUENVVARBUFSIZE];
m_fEnableNo = fEnableNo;
m_fEnableYes = fEnableYes;
m_fManualReboot = fManualReboot;
m_dwStartTickCount = dwStartTickCount;
m_fRebootWarningMode = TRUE;
// DEBUGMSG("AU_ENV_VARS write out fEnableYes = %d, fEnableNo = %d, fManualReboot = %d, dwStartTickCount = %d",
// fEnableYes, fEnableNo, fManualReboot, dwStartTickCount);
if (FAILED(StringCchCopyEx(
m_szClientExitEvtName,
ARRAYSIZE(m_szClientExitEvtName),
szClientExitEvtName,
NULL,
NULL,
MISTSAFE_STRING_FLAGS)))
{
return FALSE;
}
*szEnvBuf = _T('\0');
for (int i = 0 ; i < ARRAYSIZE(s_AUENVVARNAMES); i++)
{
if (FAILED(GetStringValue(i, buf2, ARRAYSIZE(buf2))) ||
FAILED(StringCchCatEx(szEnvBuf, cchEnvBuf, s_AUENVVARNAMES[i], NULL, NULL, MISTSAFE_STRING_FLAGS)) ||
FAILED(StringCchCatEx(szEnvBuf, cchEnvBuf, _T("="), NULL, NULL, MISTSAFE_STRING_FLAGS)) ||
FAILED(StringCchCatEx(szEnvBuf, cchEnvBuf, buf2, NULL, NULL, MISTSAFE_STRING_FLAGS)) ||
FAILED(StringCchCatEx(szEnvBuf, cchEnvBuf, _T("&"), NULL, NULL, MISTSAFE_STRING_FLAGS)))
{
return FALSE;
}
}
// DEBUGMSG("AU Env variable is %S", szEnvBuf);
return TRUE;
}
HRESULT AU_ENV_VARS::GetStringValue(int index, LPTSTR buf, DWORD dwCchSize)
{
HRESULT hr = E_INVALIDARG;
switch (index)
{
case 0: hr = StringCchCopyEx(buf, dwCchSize, m_szClientExitEvtName, NULL, NULL, MISTSAFE_STRING_FLAGS);
break;
case 1: hr = StringCchCopyEx(buf, dwCchSize, m_fEnableNo? _T("true") : _T("false"), NULL, NULL, MISTSAFE_STRING_FLAGS);
break;
case 2: hr = StringCchCopyEx(buf, dwCchSize, m_fEnableYes? _T("true") : _T("false"), NULL, NULL, MISTSAFE_STRING_FLAGS);
break;
case 3: hr = StringCchCopyEx(buf, dwCchSize, m_fRebootWarningMode ? _T("true") : _T("false"), NULL, NULL, MISTSAFE_STRING_FLAGS);
break;
case 4: hr = StringCchCopyEx(buf, dwCchSize, m_fManualReboot ? _T("true") : _T("false"), NULL, NULL, MISTSAFE_STRING_FLAGS);
break;
case 5: hr = StringCchPrintfEx(buf, dwCchSize, NULL, NULL, MISTSAFE_STRING_FLAGS, _T("%lu"), m_dwStartTickCount);
break;
default:
AUASSERT(FALSE); //should never be here
break;
}
return hr;
}
BOOL AU_ENV_VARS::GetDWordEnvironmentVar(LPCTSTR szEnvVar, DWORD *pdwVal)
{
TCHAR szBuf[20];
*pdwVal = 0;
if (GetStringEnvironmentVar(szEnvVar, szBuf, ARRAYSIZE(szBuf)))
{
// DEBUGMSG("WUAUCLT got environment variable %S = %S ", szEnvVar, szBuf);
*pdwVal = wcstoul(szBuf, NULL , 10);
return TRUE;
}
return FALSE;
}
BOOL AU_ENV_VARS::GetBOOLEnvironmentVar(LPCTSTR szEnvVar, BOOL *pfVal)
{
TCHAR szBuf[20];
if (GetStringEnvironmentVar(szEnvVar, szBuf, ARRAYSIZE(szBuf)))
{
// DEBUGMSG("WUAUCLT got environment variable %S = %S ", szEnvVar, szBuf);
*pfVal =(0 == lstrcmpi(szBuf, _T("true")));
return TRUE;
}
return FALSE;
}
/////////////////////////////////////////////////////////////////////////////////////////////
// dwSize: size of szBuf in number of characters
////////////////////////////////////////////////////////////////////////////////////////////
BOOL AU_ENV_VARS::GetStringEnvironmentVar(LPCTSTR szEnvVar, LPTSTR szBuf, DWORD dwSize)
{
// Assume szEnvVar is not a proper substring in for any parameters in szCmdLine.
LPTSTR szCmdLine = GetCommandLine();
LPTSTR pTmp;
DWORD index = 0;
// DEBUGMSG("WUAUCLT read in command line %S", szCmdLine);
if (NULL == szCmdLine || 0 == dwSize || (NULL == (pTmp = StrStr(szCmdLine, szEnvVar))))
{
return FALSE;
}
pTmp += lstrlen(szEnvVar) + 1; //skip '='
while (_T('\0') != *pTmp && _T('&') != *pTmp)
{
if (index + 1 >= dwSize)
{
// insufficent buffer
return FALSE;
}
szBuf[index++] = *pTmp++;
}
szBuf[index] = _T('\0');
// DEBUGMSG(" read in %S = %S", szEnvVar, szBuf);
return TRUE;
}
#if 0
#ifdef DBG
void DBGCheckEventState(LPSTR szName, HANDLE hEvt)
{
DWORD dwRet = WaitForSingleObject(hEvt, 0);
DEBUGMSG("WUAU Event %s is %s signalled", szName,( WAIT_OBJECT_0 == dwRet) ? "" : "NOT");
return;
}
#endif
#endif
////////////////////////////////////////////////////////////////////////////////////////
// check whether it is win2k for the current system
////////////////////////////////////////////////////////////////////////////////////////
BOOL IsWin2K(void)
{
static int iIsWin2K = -1; // force first time path
if (iIsWin2K == -1)
{
OSVERSIONINFOEX osvi;
DWORDLONG dwlConditionMask = 0;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
// This is information that identifies win2K
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
osvi.dwMajorVersion = 5;
osvi.dwMinorVersion = 0;
// Initialize the condition mask.
VER_SET_CONDITION( dwlConditionMask, VER_MAJORVERSION, VER_EQUAL );
VER_SET_CONDITION( dwlConditionMask, VER_MINORVERSION, VER_EQUAL );
// Perform the test.
iIsWin2K = (VerifyVersionInfo(&osvi, VER_MAJORVERSION | VER_MINORVERSION, dwlConditionMask)? 1 : 0);
}
return iIsWin2K;
}
/////////////////////////////////////////////////////////////////////////////////////
// check whether a policy is set to deny current user access to AU
/////////////////////////////////////////////////////////////////////////////////////
BOOL fAccessibleToAU(void)
{
BOOL fAccessible = TRUE;
DWORD dwType;
DWORD dwValue;
DWORD dwSize = sizeof(dwValue);
DWORD dwResult = SHGetValue(HKEY_CURRENT_USER,
AUREGKEY_HKCU_USER_POLICY,
AUREGVALUE_DISABLE_WINDOWS_UPDATE_ACCESS,
&dwType,
&dwValue,
&dwSize);
if (ERROR_SUCCESS == dwResult && REG_DWORD == dwType && 1 == dwValue)
{
fAccessible = FALSE;
}
return fAccessible;
}
/*
BOOL IsAdministrator()
{
SID_IDENTIFIER_AUTHORITY SIDAuth = SECURITY_NT_AUTHORITY;
PSID pSID = NULL;
BOOL bResult = FALSE;
if (!AllocateAndInitializeSid(&SIDAuth, 2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&pSID) ||
!CheckTokenMembership(NULL, pSID, &bResult))
{
bResult = FALSE;
}
if(pSID)
{
FreeSid(pSID);
}
return bResult;
}
*/
// following are hidden item related functions
BOOL FHiddenItemsExist(void)
{
//USES_CONVERSION;
DEBUGMSG("FHiddenItemsExist()");
TCHAR szFile[MAX_PATH];
//Initialize the global path to WU Dir
if(!CreateWUDirectory(TRUE))
{
return FALSE;
}
return
SUCCEEDED(StringCchCopyEx(szFile, ARRAYSIZE(szFile), g_szWUDir, NULL, NULL, MISTSAFE_STRING_FLAGS)) &&
SUCCEEDED(StringCchCatEx(szFile, ARRAYSIZE(szFile), HIDDEN_ITEMS_FILE, NULL, NULL, MISTSAFE_STRING_FLAGS)) &&
fFileExists(szFile);
}
BOOL RemoveHiddenItems(void)
{
//USES_CONVERSION
DEBUGMSG("RemoveHiddenItems()");
TCHAR szFile[MAX_PATH];
AUASSERT(_T('\0') != g_szWUDir[0]);
return
SUCCEEDED(StringCchCopyEx(szFile, ARRAYSIZE(szFile), g_szWUDir, NULL, NULL, MISTSAFE_STRING_FLAGS)) &&
SUCCEEDED(StringCchCatEx(szFile, ARRAYSIZE(szFile), HIDDEN_ITEMS_FILE, NULL, NULL, MISTSAFE_STRING_FLAGS)) &&
AUDelFileOrDir(szFile);
}
/////////////////////////////////////////////////////////////////////////////////
// bstrRTFPath is URL for the RTF file on internet
// langid is the language id for the process who download this RTF
////////////////////////////////////////////////////////////////////////////////
BOOL IsRTFDownloaded(BSTR bstrRTFPath, LANGID langid)
{
TCHAR tszLocalFullFileName[MAX_PATH];
if (NULL == bstrRTFPath)
{
return FALSE;
}
if (FAILED(GetRTFDownloadPath(tszLocalFullFileName, ARRAYSIZE(tszLocalFullFileName), langid)) ||
FAILED(PathCchAppend(tszLocalFullFileName, ARRAYSIZE(tszLocalFullFileName), W2T(PathFindFileNameW(bstrRTFPath)))))
{
return FALSE;
}
// DEBUGMSG("Checking existence of local RTF file %S", T2W(tszLocalFullFileName));
BOOL fIsDir = TRUE;
BOOL fExists = fFileExists(tszLocalFullFileName, &fIsDir);
return fExists && !fIsDir;
}
void DisableUserInput(HWND hwnd)
{
int ControlIDs[] = { IDC_CHK_KEEPUPTODATE, IDC_OPTION1, IDC_OPTION2,
IDC_OPTION3, IDC_CMB_DAYS, IDC_CMB_HOURS,IDC_RESTOREHIDDEN };
for (int i = 0; i < ARRAYSIZE(ControlIDs); i++)
{
EnableWindow(GetDlgItem(hwnd, ControlIDs[i]), FALSE);
}
}
////////////////////////////////////////////////////////////////////////////
//
// Helper Function Hours2LocalizedString()
// helper function to standardized the way AU formats time string
// for a given time. For example "3:00 AM"
//
// Parameters:
// pst - ptr to SYSTEMTIME for localizing the time component
// ptszBuffer - buffer to hold the resulting localized string
// cbSize - size of buffer in TCHARs
// Return: TRUE if successful; FALSE otherwise
//
////////////////////////////////////////////////////////////////////////////
BOOL Hours2LocalizedString(SYSTEMTIME *pst, LPTSTR ptszBuffer, DWORD cbSize)
{
return (0 != GetTimeFormat(
LOCALE_SYSTEM_DEFAULT,
LOCALE_NOUSEROVERRIDE | TIME_NOSECONDS,
pst,
NULL,
ptszBuffer,
cbSize));
}
////////////////////////////////////////////////////////////////////////////
//
// Helper Function FillHrsCombo()
// helper function to standardized the way AU sets up the list
// of hour values in a combo box.
//
// Parameters:
// hwnd - handle to obtain the handle to the combobox
// dwSchedInstallTime - hour value to default the combobox selection to
// 3:00 AM will be used if this value is not valid.
// Return: TRUE if successful; FALSE otherwise
//
////////////////////////////////////////////////////////////////////////////
BOOL FillHrsCombo(HWND hwnd, DWORD dwSchedInstallTime)
{
HWND hComboHrs = GetDlgItem(hwnd,IDC_CMB_HOURS);
DWORD dwCurrentIndex = 3;
SYSTEMTIME st = {2000, 1, 5, 1, 0, 0, 0, 0}; // 01/01/2000 00:00:00 can be any valid date/time
for (WORD i = 0; i < 24; i++)
{
TCHAR tszHrs[30];
st.wHour = i;
if (!Hours2LocalizedString(&st, tszHrs, ARRAYSIZE(tszHrs)))
{
return FALSE;
}
LRESULT nIndex = SendMessage(hComboHrs,CB_ADDSTRING,0,(LPARAM)tszHrs);
SendMessage(hComboHrs,CB_SETITEMDATA,nIndex,i);
if( dwSchedInstallTime == i )
{
dwCurrentIndex = (DWORD)nIndex;
}
}
SendMessage(hComboHrs,CB_SETCURSEL,dwCurrentIndex,(LPARAM)0);
return TRUE;
}
BOOL FillDaysCombo(HINSTANCE hInstance, HWND hwnd, DWORD dwSchedInstallDay, UINT uMinResId, UINT uMaxResId)
{
HWND hComboDays = GetDlgItem(hwnd,IDC_CMB_DAYS);
DWORD dwCurrentIndex = 0;
for (UINT i = uMinResId, j = 0; i <= uMaxResId; i ++, j++)
{
WCHAR szDay[40];
LoadStringW(hInstance,i,szDay,ARRAYSIZE(szDay));
LRESULT nIndex = SendMessage(hComboDays,CB_ADDSTRING,0,(LPARAM)szDay);
SendMessage(hComboDays,CB_SETITEMDATA,nIndex,j);
if( dwSchedInstallDay == j )
{
dwCurrentIndex = (DWORD) nIndex;
}
}
SendMessage(hComboDays,CB_SETCURSEL,dwCurrentIndex,(LPARAM)0);
return TRUE;
}
| 32.411622 | 168 | 0.599059 | npocmaka |
4b690e38d0163d380e2cc6a60899ff1122c34528 | 1,382 | hpp | C++ | src-idgen/mode.hpp | bcrist/bengine-idgen | 33ef597d8ea533485516a212c3213111548a9742 | [
"MIT"
] | null | null | null | src-idgen/mode.hpp | bcrist/bengine-idgen | 33ef597d8ea533485516a212c3213111548a9742 | [
"MIT"
] | null | null | null | src-idgen/mode.hpp | bcrist/bengine-idgen | 33ef597d8ea533485516a212c3213111548a9742 | [
"MIT"
] | null | null | null | #pragma once
#ifndef BE_IDGEN_MODE_HPP_
#define BE_IDGEN_MODE_HPP_
#include <be/core/enum_traits.hpp>
/*!! include 'idgen/mode' !! 50 */
/* ################# !! GENERATED CODE -- DO NOT MODIFY !! ################# */
namespace be::idgen {
///////////////////////////////////////////////////////////////////////////////
enum class Mode : U8 {
fnv0 = 0,
fnv1,
fnv1a
};
bool is_valid(Mode constant) noexcept;
const char* mode_name(Mode constant) noexcept;
std::array<const Mode, 3> mode_values() noexcept;
std::ostream& operator<<(std::ostream& os, Mode constant);
} // be::idgen
namespace be {
///////////////////////////////////////////////////////////////////////////////
template <>
struct EnumTraits<::be::idgen::Mode> {
using type = ::be::idgen::Mode;
using underlying_type = typename std::underlying_type<type>::type;
static constexpr std::size_t count = 3;
static bool is_valid(type value) {
return ::be::idgen::is_valid(value);
}
static const char* name(type value) {
return ::be::idgen::mode_name(value);
}
template <typename C = std::array<const type, count>>
static C values() {
return {
::be::idgen::Mode::fnv0,
::be::idgen::Mode::fnv1,
::be::idgen::Mode::fnv1a,
};
}
};
} // be
/* ######################### END OF GENERATED CODE ######################### */
#endif
| 23.033333 | 79 | 0.517366 | bcrist |
4b6a79fb2046884c1984d607d60f2a19147573eb | 2,381 | hpp | C++ | include/hydro/utility/terminal_format.hpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | include/hydro/utility/terminal_format.hpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | include/hydro/utility/terminal_format.hpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | //
// __ __ __
// / / / /__ __ ____/ /_____ ____
// / /_/ // / / // __ // ___// __ \
// / __ // /_/ // /_/ // / / /_/ /
// /_/ /_/ \__, / \__,_//_/ \____/
// /____/
//
// The Hydro Programming Language
//
#ifndef __h3o_terminal_format__
#define __h3o_terminal_format__
#include <iostream>
#include "../vm/detect.hpp"
//the following are UBUNTU/LINUX, and MacOS ONLY terminal color codes.
namespace hydro
{
class terminal_format
{
public:
terminal_format() {}
terminal_format(const char *value) : m_value{value} {}
terminal_format(std::string value) : m_value{value} {}
terminal_format(const terminal_format &format) : m_value{format.m_value} {}
terminal_format(terminal_format &&format) : m_value{format.m_value} {}
~terminal_format() {}
std::string value() const { return m_value; }
bool empty() const { return m_value.empty(); }
operator bool() const { return !m_value.empty(); }
terminal_format &operator=(const terminal_format &rhs)
{
m_value = rhs.m_value;
return (*this);
}
terminal_format &operator=(terminal_format &&rhs)
{
m_value = rhs.m_value;
return (*this);
}
terminal_format operator+(const terminal_format &rhs) const
{
if(m_value == rhs.m_value)
return rhs;
return m_value + rhs.m_value;
}
static terminal_format txt256(uint8_t code) { return "\u001b[38;5;" + std::to_string(code) + "m"; }
static terminal_format bg256(uint8_t code) { return "\u001b[48;5;" + std::to_string(code) + "m"; }
private:
std::string m_value;
};
const terminal_format NIL_FORMAT;
const terminal_format RESET = "\033[0m";
const terminal_format BLACK = "\033[30m";
const terminal_format RED = "\033[31m";
const terminal_format GREEN = "\033[32m";
const terminal_format YELLOW = "\033[33m";
const terminal_format BLUE = "\033[34m";
const terminal_format MAGENTA = "\033[35m";
const terminal_format CYAN = "\033[36m";
const terminal_format WHITE = "\033[37m";
const terminal_format BOLD = "\u001b[1m";
const terminal_format UNDERLINE = "\u001b[4m";
std::ostream &operator<<(std::ostream &lhs, const terminal_format &rhs);
} // namespace hydro
#endif /* __h3o_terminal_format__ */
| 30.525641 | 103 | 0.616128 | hydraate |
4b6ac20c0e87ef1a12f8badc7fd4de80944a19ea | 7,172 | hpp | C++ | c++/include/util/cache/icache_cf.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 31 | 2016-12-09T04:56:59.000Z | 2021-12-31T17:19:10.000Z | c++/include/util/cache/icache_cf.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 6 | 2017-03-10T17:25:13.000Z | 2021-09-22T15:49:49.000Z | c++/include/util/cache/icache_cf.hpp | OpenHero/gblastn | a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8 | [
"MIT"
] | 20 | 2015-01-04T02:15:17.000Z | 2021-12-03T02:31:43.000Z | #ifndef UTIL_ICACHE_CF__HPP
#define UTIL_ICACHE_CF__HPP
/* $Id: icache_cf.hpp 112045 2007-10-10 20:43:07Z ivanovp $
* ===========================================================================
*
* public DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Anatoliy Kuznetsov
*
* File Description:
* Util library ICache class factory assistance functions
*
*/
#include <corelib/ncbistd.hpp>
#include <corelib/ncbistr.hpp>
#include <corelib/plugin_manager.hpp>
#include <corelib/plugin_manager_impl.hpp>
#include <util/cache/icache.hpp>
#include <util/error_codes.hpp>
BEGIN_NCBI_SCOPE
/// Utility class for ICache class factories
///
/// @internal
///
template<class TDriver>
class CICacheCF : public CSimpleClassFactoryImpl<ICache, TDriver>
{
public:
typedef
CSimpleClassFactoryImpl<ICache, TDriver> TParent;
public:
CICacheCF(const string& driver_name, int patch_level = -1)
: TParent(driver_name, patch_level)
{}
/// Utility function, configures common ICache parameters
void ConfigureICache(ICache* icache,
const TPluginManagerParamTree* params) const
{
if (!params) return;
// Timestamp configuration
{{
static const string kCFParam_timestamp = "timestamp";
const string& ts_flags_str =
this->GetParam(params, kCFParam_timestamp, false);
if (!ts_flags_str.empty()) {
ConfigureTimeStamp(icache, params, ts_flags_str);
}
}}
static const string kCFParam_keep_versions = "keep_versions";
const string& keep_versions_str =
this->GetParam(params, kCFParam_keep_versions, false);
if (!keep_versions_str.empty()) {
static const string kCFParam_keep_versions_all = "all";
static const string kCFParam_keep_versions_drop_old = "drop_old";
static const string kCFParam_keep_versions_drop_all = "drop_all";
ICache::EKeepVersions kv_policy = ICache::eKeepAll;
if (NStr::CompareNocase(keep_versions_str,
kCFParam_keep_versions_all)==0) {
kv_policy = ICache::eKeepAll;
} else
if (NStr::CompareNocase(keep_versions_str,
kCFParam_keep_versions_drop_old)==0) {
kv_policy = ICache::eDropOlder;
} else
if (NStr::CompareNocase(keep_versions_str,
kCFParam_keep_versions_drop_all)==0) {
kv_policy = ICache::eDropAll;
} else {
LOG_POST_XX(Util_Cache, 1, Warning
<< "ICache::ClassFactory: Unknown keep_versions"
" policy parameter: "
<< keep_versions_str);
}
icache->SetVersionRetention(kv_policy);
}
}
void ConfigureTimeStamp(ICache* icache,
const TPluginManagerParamTree* params,
const string& options) const
{
static
const string kCFParam_timeout = "timeout";
static
const string kCFParam_max_timeout = "max_timeout";
static
const string kCFParam_timestamp_onread = "onread";
static
const string kCFParam_timestamp_subkey = "subkey";
static
const string kCFParam_timestamp_expire_not_used = "expire_not_used";
static
const string kCFParam_timestamp_purge_on_startup = "purge_on_startup";
static
const string kCFParam_timestamp_check_expiration = "check_expiration";
list<string> opt;
NStr::Split(options, " \t", opt);
ICache::TTimeStampFlags ts_flag = 0;
ITERATE(list<string>, it, opt) {
const string& opt_value = *it;
if (NStr::CompareNocase(opt_value,
kCFParam_timestamp_onread)==0) {
ts_flag |= ICache::fTimeStampOnRead;
continue;
}
if (NStr::CompareNocase(opt_value,
kCFParam_timestamp_subkey)==0) {
ts_flag |= ICache::fTrackSubKey;
continue;
}
if (NStr::CompareNocase(opt_value,
kCFParam_timestamp_expire_not_used)==0) {
ts_flag |= ICache::fExpireLeastFrequentlyUsed;
continue;
}
if (NStr::CompareNocase(opt_value,
kCFParam_timestamp_purge_on_startup)==0) {
ts_flag |= ICache::fPurgeOnStartup;
continue;
}
if (NStr::CompareNocase(opt_value,
kCFParam_timestamp_check_expiration)==0) {
ts_flag |= ICache::fCheckExpirationAlways;
continue;
}
LOG_POST_XX(Util_Cache, 2, Warning
<< "ICache::ClassFactory: Unknown timeout policy parameter: "
<< opt_value);
} // ITERATE
unsigned int timeout = (unsigned int)
this->GetParamInt(params, kCFParam_timeout, false, 60 * 60);
unsigned int max_timeout = (unsigned int)
this->GetParamInt(params, kCFParam_max_timeout, false, 0);
if (max_timeout && max_timeout < timeout)
max_timeout = timeout;
if (ts_flag) {
icache->SetTimeStampPolicy(ts_flag, timeout, max_timeout);
}
}
};
END_NCBI_SCOPE
#endif /* UTIL_EXCEPTION__HPP */
| 37.94709 | 83 | 0.55396 | OpenHero |
4b73bb7e9df3a8596d28a75110b087189d20c162 | 323 | cpp | C++ | CurveScape/src/legacy/calculate.cpp | nathan-abraham/CurveScape | 1dbf89422daf9f2f9381411f2077713277966743 | [
"MIT"
] | 1 | 2021-12-31T20:47:30.000Z | 2021-12-31T20:47:30.000Z | CurveScape/src/legacy/calculate.cpp | nathan-abraham/CurveScape | 1dbf89422daf9f2f9381411f2077713277966743 | [
"MIT"
] | null | null | null | CurveScape/src/legacy/calculate.cpp | nathan-abraham/CurveScape | 1dbf89422daf9f2f9381411f2077713277966743 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <SFML/Graphics.hpp>
#include "dropdown.cpp"
#include "textbox.cpp"
class Calculate {
public:
std::string type;
DropdownMenu* options = NULL;
DropdownMenu* funcs = NULL;
TextBox* first = NULL;
TextBox* second = NULL;
Button* submit = NULL;
}; | 17.944444 | 33 | 0.643963 | nathan-abraham |
4b76480e75d23fa51b56931256f6b835a3be8d6a | 443 | cpp | C++ | C++ Practice Programs/Example_2.cpp | Ahtisham-Shakir/CPP_OOP | 308e7bdbd1e73c644a17f612fc5b919cb68c171c | [
"MIT"
] | null | null | null | C++ Practice Programs/Example_2.cpp | Ahtisham-Shakir/CPP_OOP | 308e7bdbd1e73c644a17f612fc5b919cb68c171c | [
"MIT"
] | null | null | null | C++ Practice Programs/Example_2.cpp | Ahtisham-Shakir/CPP_OOP | 308e7bdbd1e73c644a17f612fc5b919cb68c171c | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <bits/stdc++.h>
using namespace std;
int main() {
// Complete the code.
int a; long b; char c; float d; double e;
cout<<"Enter int, long, char, float, double: ";
cin >> a >> b >> c >> d >> e;
cout << a << endl;
cout << b << endl;
cout << c << endl;
cout << fixed << setprecision(3) << d << endl;
cout << fixed << setprecision(9) << e << endl;
return 0;
}
| 24.611111 | 51 | 0.534989 | Ahtisham-Shakir |
4b7819b68b51209a0c8b01327b7735150af1ec0d | 42 | cpp | C++ | c++/Test/Naming.cpp | taku-xhift/labo | 89dc28fdb602c7992c6f31920714225f83a11218 | [
"MIT"
] | null | null | null | c++/Test/Naming.cpp | taku-xhift/labo | 89dc28fdb602c7992c6f31920714225f83a11218 | [
"MIT"
] | null | null | null | c++/Test/Naming.cpp | taku-xhift/labo | 89dc28fdb602c7992c6f31920714225f83a11218 | [
"MIT"
] | null | null | null |
int main() {
int 1st = 0;
}
| 4.666667 | 14 | 0.333333 | taku-xhift |
4b7879257a7d891d99249a431e32191493163496 | 874 | cpp | C++ | Engine/Renderer/GLES3/src/GLES3UniformBufferManager.cpp | LiangYue1981816/AresEngine | c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67 | [
"BSD-2-Clause"
] | 3 | 2018-12-08T16:32:05.000Z | 2020-06-02T11:07:15.000Z | Engine/Renderer/GLES3/src/GLES3UniformBufferManager.cpp | LiangYue1981816/AresEngine | c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67 | [
"BSD-2-Clause"
] | null | null | null | Engine/Renderer/GLES3/src/GLES3UniformBufferManager.cpp | LiangYue1981816/AresEngine | c1cf040a1dffaf2bc585ed75e70ddd9322fe3f67 | [
"BSD-2-Clause"
] | 1 | 2019-09-12T00:26:05.000Z | 2019-09-12T00:26:05.000Z | #include "GLES3Renderer.h"
CGLES3UniformBufferManager::CGLES3UniformBufferManager(void)
{
}
CGLES3UniformBufferManager::~CGLES3UniformBufferManager(void)
{
for (const auto& itUniformBuffer : m_pUniformBuffers) {
delete itUniformBuffer.second;
}
}
CGLES3UniformBuffer* CGLES3UniformBufferManager::Create(size_t size)
{
mutex_autolock autolock(&lock);
{
if (CGLES3UniformBuffer* pUniformBuffer = new CGLES3UniformBuffer(this, size)) {
m_pUniformBuffers[pUniformBuffer] = pUniformBuffer;
return pUniformBuffer;
}
else {
return nullptr;
}
}
}
void CGLES3UniformBufferManager::Destroy(CGLES3UniformBuffer* pUniformBuffer)
{
ASSERT(pUniformBuffer);
{
mutex_autolock autolock(&lock);
{
if (m_pUniformBuffers.find(pUniformBuffer) != m_pUniformBuffers.end()) {
m_pUniformBuffers.erase(pUniformBuffer);
}
}
}
delete pUniformBuffer;
}
| 20.325581 | 82 | 0.763158 | LiangYue1981816 |
4b78b37c7a82626e4f04199ef872148e5cd0d2ff | 679 | cpp | C++ | AndroidC++/jni/Sprite.cpp | BenjaminNitschke/MobileCourse | 802ce81f7cd9ee44b35f13e4da302a9fbd29a2b6 | [
"Apache-2.0"
] | 1 | 2015-06-20T09:09:29.000Z | 2015-06-20T09:09:29.000Z | AndroidC++/jni/Sprite.cpp | BenjaminNitschke/MobileCourse | 802ce81f7cd9ee44b35f13e4da302a9fbd29a2b6 | [
"Apache-2.0"
] | null | null | null | AndroidC++/jni/Sprite.cpp | BenjaminNitschke/MobileCourse | 802ce81f7cd9ee44b35f13e4da302a9fbd29a2b6 | [
"Apache-2.0"
] | null | null | null | #include "Sprite.h"
#include <GLES/gl.h>
using namespace SpaceInvaders;
void Sprite::Draw(float x, float y)
{
glBindTexture(GL_TEXTURE_2D, texture->GetHandle());
glTexCoordPointer(2, GL_FLOAT, 0, uvBuffer);
vertices[0] = initialX + x - width; vertices[1] = initialY + y + height; // top left
vertices[3] = initialX + x - width; vertices[4] = initialY + y - height; // bottom left
vertices[6] = initialX + x + width; vertices[7] = initialY + y - height; // bottom right
vertices[9] = initialX + x + width; vertices[10] = initialY + y + height; // top right
glVertexPointer(3, GL_FLOAT, 0, vertices);
glDrawElements(GL_TRIANGLES, 2 * 3, GL_UNSIGNED_SHORT, indexBuffer);
} | 42.4375 | 89 | 0.69514 | BenjaminNitschke |
4b7e18cb4a70044c1fecc1cd3716fb9745dd1145 | 3,659 | hpp | C++ | src/xrCore/FMesh.hpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 2 | 2015-02-23T10:43:02.000Z | 2015-06-11T14:45:08.000Z | src/xrCore/FMesh.hpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 17 | 2022-01-25T08:58:23.000Z | 2022-03-28T17:18:28.000Z | src/xrCore/FMesh.hpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 1 | 2015-06-05T20:04:00.000Z | 2015-06-05T20:04:00.000Z | #ifndef fmeshH
#define fmeshH
#pragma once
// BOOL ValidateIndices (u32 vCount, u32 iCount, u16* pIndices);
///////////////////////////////////////////////////////////////////////////////////////////////////////
// MESH as it is represented in file
enum MT
{
MT_NORMAL = 0,
MT_HIERRARHY = 1,
MT_PROGRESSIVE = 2,
MT_SKELETON_ANIM = 3,
MT_SKELETON_GEOMDEF_PM = 4,
MT_SKELETON_GEOMDEF_ST = 5,
MT_LOD = 6,
MT_TREE_ST = 7,
MT_PARTICLE_EFFECT = 8,
MT_PARTICLE_GROUP = 9,
MT_SKELETON_RIGID = 10,
MT_TREE_PM = 11,
MT_3DFLUIDVOLUME = 12,
};
enum OGF_Chuncks
{
OGF_HEADER = 1,
OGF_TEXTURE = 2,
OGF_VERTICES = 3,
OGF_INDICES = 4,
OGF_P_MAP = 5, //---------------------- unused
OGF_SWIDATA = 6,
OGF_VCONTAINER = 7, // not used ??
OGF_ICONTAINER = 8, // not used ??
OGF_CHILDREN = 9, // * For skeletons only
OGF_CHILDREN_L = 10, // Link to child visuals
OGF_LODDEF2 = 11, // + 5 channel data
OGF_TREEDEF2 = 12, // + 5 channel data
OGF_S_BONE_NAMES = 13, // * For skeletons only
OGF_S_MOTIONS = 14, // * For skeletons only
OGF_S_SMPARAMS = 15, // * For skeletons only
OGF_S_IKDATA = 16, // * For skeletons only
OGF_S_USERDATA = 17, // * For skeletons only (Ini-file)
OGF_S_DESC = 18, // * For skeletons only
OGF_S_MOTION_REFS = 19, // * For skeletons only
OGF_SWICONTAINER = 20, // * SlidingWindowItem record container
OGF_GCONTAINER = 21, // * both VB&IB
OGF_FASTPATH = 22, // * extended/fast geometry
OGF_S_LODS = 23, // * For skeletons only (Ini-file)
OGF_S_MOTION_REFS2 = 24, // * changes in format
OGF_COLLISION_VERTICES = 25,
OGF_COLLISION_INDICES = 26,
OGF_forcedword = 0xFFFFFFFF
};
enum OGF_SkeletonVertType
{
OGF_VERTEXFORMAT_FVF_1L = 1 * 0x12071980,
OGF_VERTEXFORMAT_FVF_2L = 2 * 0x12071980,
OGF_VERTEXFORMAT_FVF_3L = 4 * 0x12071980,
OGF_VERTEXFORMAT_FVF_4L = 5 * 0x12071980,
OGF_VERTEXFORMAT_FVF_NL = 3 * 0x12071980,
};
const u16 xrOGF_SMParamsVersion = 4;
// OGF_DESC
struct XRCORE_API ogf_desc
{
shared_str source_file;
shared_str build_name;
time_t build_time;
shared_str create_name;
time_t create_time;
shared_str modif_name;
time_t modif_time;
ogf_desc() : build_time(0), create_time(0), modif_time(0) {}
void Load(IReader& F);
void Save(IWriter& F);
};
// OGF_BBOX
struct ogf_bbox
{
Fvector min;
Fvector max;
};
// OGF_BSPHERE
struct ogf_bsphere
{
Fvector c;
float r;
};
// OGF_HEADER
const u8 xrOGF_FormatVersion = 4;
struct ogf_header
{
u8 format_version; // = xrOGF_FormatVersion
u8 type; // MT
u16 shader_id; // should not be ZERO
ogf_bbox bb;
ogf_bsphere bs;
};
// Sliding Window Record
struct XRCORE_API FSlideWindow
{
u32 offset;
u16 num_tris;
u16 num_verts;
};
struct XRCORE_API FSlideWindowItem
{
FSlideWindow* sw;
u32 count;
u32 reserved[4];
FSlideWindowItem() : sw(0), count(0){};
};
// OGF_TEXTURE1
// Z-String - name
// Z-String - shader
// OGF_TEXTURE_L
// u32 T_link
// u32 S_link
// OGF_MATERIAL
// Fmaterial
// OGF_CHIELDS_L
// u32 Count
// u32 idx[0...Count-1]
// OGF_VERTICES
// u32 dwVertType; // Type of vertices it contains
// u32 dwVertCount; // Count of vertices
// ..vertices itself
// OGF_INDICES
// u32 Count
// ..indices itself (u16[Count]);
// OGF_VCONTAINER
// u32 CID; // Container ID
// u32 Offset; // Add for every IDX and use as the start vertex
// u32 Count; // Number of vertices
// OGF_BONES
// BYTE Count;
// BYTE Indices[...]
// OGF_TREEDEF
// xform : matrix4x4
// scale : vec4
// bias : vec4
#endif // fmeshH
| 22.447853 | 103 | 0.640612 | clayne |
4b80011363c33c66c08bae89d4b291682948401f | 2,911 | cpp | C++ | t/006_grapheme_iterator.t.cpp | pr8x/u5e | 3b970d5bc251fdef341d039d66c84ec5eaf4cb6a | [
"BSD-2-Clause"
] | 19 | 2015-09-18T14:06:40.000Z | 2021-07-20T19:51:34.000Z | t/006_grapheme_iterator.t.cpp | pr8x/u5e | 3b970d5bc251fdef341d039d66c84ec5eaf4cb6a | [
"BSD-2-Clause"
] | 6 | 2016-09-04T02:12:07.000Z | 2017-08-10T10:07:06.000Z | t/006_grapheme_iterator.t.cpp | pr8x/u5e | 3b970d5bc251fdef341d039d66c84ec5eaf4cb6a | [
"BSD-2-Clause"
] | 7 | 2015-10-12T15:36:34.000Z | 2021-02-19T05:15:25.000Z | #include "gtest/gtest.h"
#include <string>
#include <sstream>
#include <u5e/codepoint.hpp>
#include <u5e/utf8_string.hpp>
#include <u5e/utf8_string_grapheme.hpp>
#include <u5e/utf8_string_grapheme_iterator.hpp>
#include <u5e/utf32ne_string.hpp>
#include <u5e/utf32ne_string_grapheme.hpp>
#include <u5e/utf32ne_string_grapheme_iterator.hpp>
using u5e::codepoint;
using u5e::utf8_string;
using u5e::utf8_string_grapheme;
using u5e::utf8_string_grapheme_iterator;
using u5e::utf32ne_string;
using u5e::utf32ne_string_grapheme;
using u5e::utf32ne_string_grapheme_iterator;
TEST(t_006_utf8_string_grapheme_iterator, utf8) {
// this is a decomposed grapheme
utf8_string str("Ola\xCC\x81!");
// now we get a grapheme iterator from the utf8 iterator
utf8_string_grapheme_iterator gi(str.grapheme_begin());
// the current grapheme
utf8_string_grapheme g(*gi);
// has an inner iterator
utf8_string::const_iterator ci(g.codepoint_begin());
// which points to a codepoint
codepoint c(*ci);
// first grapheme
ASSERT_EQ('O', c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
// second grapheme
g = *gi;
ci = g.codepoint_begin();
c = *ci;
ASSERT_EQ('l', c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
// third grapheme
// this one has two codepoints
g = *gi;
ci = g.codepoint_begin();
c = *ci;
ASSERT_EQ('a', c);
ci++;
c = *ci;
ASSERT_EQ(769, c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
// fourth grapheme
g = *gi;
ci = g.codepoint_begin();
c = *ci;
ASSERT_EQ('!', c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
ASSERT_TRUE(gi == str.codepoint_cend());
};
TEST(t_006_utf8_string_grapheme_iterator, utf32ne) {
// this is a decomposed grapheme
utf32ne_string str({ 'O', 'l', 'a', 769, '!' });
// now we get a grapheme iterator from the utf32ne iterator
utf32ne_string_grapheme_iterator gi(str.grapheme_begin());
// the current grapheme
utf32ne_string_grapheme g(*gi);
// has an inner iterator
utf32ne_string::const_iterator ci(g.codepoint_begin());
// which points to a codepoint
codepoint c(*ci);
// first grapheme
ASSERT_EQ('O', c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
// second grapheme
g = *gi;
ci = g.codepoint_begin();
c = *ci;
ASSERT_EQ('l', c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
// third grapheme
// this one has two codepoints
g = *gi;
ci = g.codepoint_begin();
c = *ci;
ASSERT_EQ('a', c);
ci++;
c = *ci;
ASSERT_EQ(769, c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
// fourth grapheme
g = *gi;
ci = g.codepoint_begin();
c = *ci;
ASSERT_EQ('!', c);
ci++;
ASSERT_TRUE(ci == g.codepoint_end());
// advance
gi++;
ASSERT_TRUE(gi == str.codepoint_cend());
};
| 20.075862 | 61 | 0.655101 | pr8x |
4b81a5977bea4e6ed6c6ac939263c7d32fbbf2df | 121 | cpp | C++ | MultiMon.cpp | SegaraRai/EntisGLS4Build | 2587390738802394a38b3aaf2adc80295dde7ec4 | [
"CC0-1.0",
"Unlicense"
] | 3 | 2021-11-05T08:02:17.000Z | 2022-02-26T18:03:18.000Z | MultiMon.cpp | SegaraRai/EntisGLS4Build | 2587390738802394a38b3aaf2adc80295dde7ec4 | [
"CC0-1.0",
"Unlicense"
] | null | null | null | MultiMon.cpp | SegaraRai/EntisGLS4Build | 2587390738802394a38b3aaf2adc80295dde7ec4 | [
"CC0-1.0",
"Unlicense"
] | null | null | null | #ifdef DISABLE_ENTIS_GLS4_EXPORTS
# include <Windows.h>
# define COMPILE_MULTIMON_STUBS
# include <MultiMon.h>
#endif
| 13.444444 | 33 | 0.785124 | SegaraRai |
4b81b6d556681238f3e160e58706462aba636918 | 1,183 | cpp | C++ | src/Swoose/Swoose/MolecularMechanics/MMParameters.cpp | qcscine/swoose | 55a74259153845ade607784f26455fd96dddce07 | [
"BSD-3-Clause"
] | 2 | 2021-12-15T09:31:36.000Z | 2021-12-15T09:35:36.000Z | src/Swoose/Swoose/MolecularMechanics/MMParameters.cpp | qcscine/swoose | 55a74259153845ade607784f26455fd96dddce07 | [
"BSD-3-Clause"
] | null | null | null | src/Swoose/Swoose/MolecularMechanics/MMParameters.cpp | qcscine/swoose | 55a74259153845ade607784f26455fd96dddce07 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#include "MMParameters.h"
#include "MMExceptions.h"
namespace Scine {
namespace MolecularMechanics {
Bond MMParameters::getMMBond(std::string t1, std::string t2) const {
auto bond_ptr = bonds_.find(BondType(t1, t2));
if (bond_ptr == bonds_.end())
throw MMBondParametersNotAvailableException(t1, t2);
else
return bond_ptr->second.toMMBond();
}
Angle MMParameters::getMMAngle(std::string t1, std::string t2, std::string t3) const {
auto angle_ptr = angles_.find(AngleType(t1, t2, t3));
if (angle_ptr == angles_.end())
throw MMAngleParametersNotAvailableException(t1, t2, t3);
else
return angle_ptr->second.toMMAngle();
}
void MMParameters::addBond(BondType bondType, BondParameters bondParameters) {
bonds_.emplace(bondType, bondParameters);
}
void MMParameters::addAngle(AngleType angleType, AngleParameters angleParameters) {
angles_.emplace(angleType, angleParameters);
}
} // namespace MolecularMechanics
} // namespace Scine
| 29.575 | 86 | 0.730347 | qcscine |
4b8268f37171d1ffc0aff29e21d11c6bdc320d67 | 2,872 | cpp | C++ | source/request.cpp | kociap/rpp | 1c0009c1abcd9416c75c75a981b235f2db551e89 | [
"MIT"
] | null | null | null | source/request.cpp | kociap/rpp | 1c0009c1abcd9416c75c75a981b235f2db551e89 | [
"MIT"
] | null | null | null | source/request.cpp | kociap/rpp | 1c0009c1abcd9416c75c75a981b235f2db551e89 | [
"MIT"
] | null | null | null | #include "rpp/request.hpp"
#include "curl/curl.h"
namespace rpp {
Request::Request() : handle(curl_easy_init()), headers(nullptr) {}
Request::Request(Request&& req) : handle(req.handle), headers(req.headers) {
req.handle = nullptr;
req.headers = nullptr;
}
Request& Request::operator=(Request&& req) {
handle = req.handle;
headers = req.headers;
req.handle = nullptr;
req.headers = nullptr;
return *this;
}
Request::~Request() {
if (handle != nullptr) {
curl_easy_cleanup(handle);
}
if (headers != nullptr) {
curl_slist_free_all(headers);
}
}
void Request::set_verbose(bool verbose) {
curl_easy_setopt(handle, CURLOPT_VERBOSE, verbose);
}
void Request::set_verify_ssl(bool verify) {
curl_easy_setopt(handle, CURLOPT_SSL_VERIFYPEER, verify);
}
void Request::set_headers(Headers const& hs) {
if (hs.headers.empty()) {
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, NULL);
return;
}
if (headers != nullptr) {
curl_slist_free_all(headers);
headers = NULL;
}
for (auto const& [key, value] : hs.headers) {
if (value.empty()) {
headers = curl_slist_append(headers, (key + ";").data());
} else {
headers = curl_slist_append(headers, (key + ": " + value).data());
}
}
curl_easy_setopt(handle, CURLOPT_HTTPHEADER, headers);
}
size_t curl_write_function(char* data, size_t, size_t data_size, std::string* user_data) {
user_data->append(data, data_size);
return data_size;
}
Response Request::get(URL const& url) {
Response res;
std::string full_url = url.get_full_url();
curl_easy_setopt(handle, CURLOPT_URL, full_url.c_str());
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, curl_write_function);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &res.text);
curl_easy_perform(handle);
curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &res.status);
return res;
}
Response Request::post(URL const& url, Body const& body) {
Response res;
std::string data = body.to_string();
std::string full_url = url.get_full_url();
curl_easy_setopt(handle, CURLOPT_URL, full_url.c_str());
curl_easy_setopt(handle, CURLOPT_POST, 1);
curl_easy_setopt(handle, CURLOPT_POSTFIELDS, data.c_str());
curl_easy_setopt(handle, CURLOPT_WRITEFUNCTION, curl_write_function);
curl_easy_setopt(handle, CURLOPT_WRITEDATA, &res.text);
curl_easy_perform(handle);
curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &res.status);
return res;
}
} // namespace rpp | 30.231579 | 94 | 0.60968 | kociap |
4b85fba9ab89f08a9661331e0e503d4c95690e88 | 1,928 | hpp | C++ | include/codegen/include/Zenject/PoolableStaticMemoryPool_1.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/Zenject/PoolableStaticMemoryPool_1.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/Zenject/PoolableStaticMemoryPool_1.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:44 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Including type: Zenject.StaticMemoryPool`1
#include "Zenject/StaticMemoryPool_1.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Zenject
namespace Zenject {
// Forward declaring type: IPoolable
class IPoolable;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Autogenerated type: Zenject.PoolableStaticMemoryPool`1
template<typename TValue>
class PoolableStaticMemoryPool_1 : public Zenject::StaticMemoryPool_1<TValue> {
public:
// static private System.Void OnSpawned(TValue value)
// Offset: 0x15DB9E8
static void OnSpawned(TValue value) {
CRASH_UNLESS(il2cpp_utils::RunMethod(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<PoolableStaticMemoryPool_1<TValue>*>::get(), "OnSpawned", value));
}
// static private System.Void OnDespawned(TValue value)
// Offset: 0x15DBA98
static void OnDespawned(TValue value) {
CRASH_UNLESS(il2cpp_utils::RunMethod(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<PoolableStaticMemoryPool_1<TValue>*>::get(), "OnDespawned", value));
}
// public System.Void .ctor()
// Offset: 0x15DB918
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static PoolableStaticMemoryPool_1<TValue>* New_ctor() {
return (PoolableStaticMemoryPool_1<TValue>*)CRASH_UNLESS(il2cpp_utils::New(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<PoolableStaticMemoryPool_1<TValue>*>::get()));
}
}; // Zenject.PoolableStaticMemoryPool`1
}
DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(Zenject::PoolableStaticMemoryPool_1, "Zenject", "PoolableStaticMemoryPool`1");
#pragma pack(pop)
| 42.844444 | 180 | 0.729253 | Futuremappermydud |
4b863e877773836ce1b1ce3d02a9bd36ba641089 | 1,816 | cpp | C++ | src/Events/OE_Event.cpp | antsouchlos/OxygenEngine2 | 5a123a2dacbc3b66ba9e97b9e5db7d8c17490ddb | [
"MIT"
] | null | null | null | src/Events/OE_Event.cpp | antsouchlos/OxygenEngine2 | 5a123a2dacbc3b66ba9e97b9e5db7d8c17490ddb | [
"MIT"
] | 22 | 2020-05-19T18:18:45.000Z | 2022-03-31T12:11:08.000Z | src/Events/OE_Event.cpp | antsouchlos/OxygenEngine2 | 5a123a2dacbc3b66ba9e97b9e5db7d8c17490ddb | [
"MIT"
] | null | null | null | #include <OE_Math.h>
#include <Events/OE_Event.h>
#include <Carbon/CSL_Interpreter.h>
using namespace std;
bool OE_Event::finished = false;
OE_Event::OE_Event(){
active_=false;
name_ = "";
}
OE_Event::~OE_Event(){}
void OE_Event::setFunc(const OE_EVENTFUNC a_func){
lockMutex();
func_ = a_func;
unlockMutex();
}
//keyboard
OE_KeyboardEvent::OE_KeyboardEvent(){
type_ = OE_KEYBOARD_EVENT;
keystate = OE_BUTTON::RELEASE;
}
OE_KeyboardEvent::~OE_KeyboardEvent(){}
int OE_KeyboardEvent::call(){
return internal_call();
}
//mouse
int OE_MouseEvent::x = 0;
int OE_MouseEvent::y = 0;
int OE_MouseEvent::delta_x = 0;
int OE_MouseEvent::delta_y = 0;
int OE_MouseEvent::mouse_wheel = 0;
bool OE_MouseEvent::mousemoved = false;
OE_MouseEvent::OE_MouseEvent(){
type_ = OE_MOUSE_EVENT;
mousemoved = false;
keystate = OE_BUTTON::RELEASE;
}
OE_MouseEvent::~OE_MouseEvent(){}
int OE_MouseEvent::call(){
return internal_call();
}
//gamepad
OE_GamepadEvent::OE_GamepadEvent(){
type_ = OE_GAMEPAD_EVENT;
axis=0; axismoved = false;
}
OE_GamepadEvent::~OE_GamepadEvent(){}
int OE_GamepadEvent::call(){
return internal_call();
}
//custom
OE_CustomEvent::OE_CustomEvent(){
type_ = OE_CUSTOM_EVENT;
}
OE_CustomEvent::~OE_CustomEvent(){}
int OE_CustomEvent::call(){
return internal_call();
}
//error
OE_ErrorEvent::OE_ErrorEvent(){
type_ = OE_ERROR_EVENT;
}
OE_ErrorEvent::~OE_ErrorEvent(){}
int OE_ErrorEvent::call(){
/***************************/
///non-generic handling
if( this->importance == OE_FATAL) finished = true;
this->internal_call();
return 0;
}
//multiple events
OE_EventCombo::OE_EventCombo(){
type_ = OE_EVENT_COMBO;
}
OE_EventCombo::~OE_EventCombo(){}
int OE_EventCombo::call(){
return internal_call();
}
| 17.461538 | 51 | 0.69163 | antsouchlos |
4b885d81259ba9566e5e00996723b4d2b782cf79 | 21,827 | cc | C++ | third_party/blink/renderer/platform/scroll/scrollbar.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/platform/scroll/scrollbar.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/platform/scroll/scrollbar.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | /*
* Copyright (C) 2004, 2006, 2008 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "third_party/blink/renderer/platform/scroll/scrollbar.h"
#include <algorithm>
#include "third_party/blink/public/platform/web_gesture_event.h"
#include "third_party/blink/public/platform/web_mouse_event.h"
#include "third_party/blink/public/platform/web_scrollbar_overlay_color_theme.h"
#include "third_party/blink/renderer/platform/geometry/float_rect.h"
#include "third_party/blink/renderer/platform/graphics/paint/cull_rect.h"
#include "third_party/blink/renderer/platform/platform_chrome_client.h"
#include "third_party/blink/renderer/platform/scroll/scroll_animator_base.h"
#include "third_party/blink/renderer/platform/scroll/scrollable_area.h"
#include "third_party/blink/renderer/platform/scroll/scrollbar_theme.h"
namespace blink {
Scrollbar::Scrollbar(ScrollableArea* scrollable_area,
ScrollbarOrientation orientation,
ScrollbarControlSize control_size,
PlatformChromeClient* chrome_client,
ScrollbarTheme* theme)
: scrollable_area_(scrollable_area),
orientation_(orientation),
control_size_(control_size),
theme_(theme ? *theme : scrollable_area->GetPageScrollbarTheme()),
chrome_client_(chrome_client),
visible_size_(0),
total_size_(0),
current_pos_(0),
drag_origin_(0),
hovered_part_(kNoPart),
pressed_part_(kNoPart),
pressed_pos_(0),
scroll_pos_(0),
dragging_document_(false),
document_drag_pos_(0),
enabled_(true),
scroll_timer_(scrollable_area->GetTimerTaskRunner(),
this,
&Scrollbar::AutoscrollTimerFired),
elastic_overscroll_(0),
track_needs_repaint_(true),
thumb_needs_repaint_(true) {
theme_.RegisterScrollbar(*this);
// FIXME: This is ugly and would not be necessary if we fix cross-platform
// code to actually query for scrollbar thickness and use it when sizing
// scrollbars (rather than leaving one dimension of the scrollbar alone when
// sizing).
int thickness = theme_.ScrollbarThickness(control_size);
theme_scrollbar_thickness_ = thickness;
if (chrome_client_)
thickness = chrome_client_->WindowToViewportScalar(thickness);
frame_rect_ = IntRect(0, 0, thickness, thickness);
current_pos_ = ScrollableAreaCurrentPos();
}
Scrollbar::~Scrollbar() {
theme_.UnregisterScrollbar(*this);
}
void Scrollbar::Trace(blink::Visitor* visitor) {
visitor->Trace(scrollable_area_);
visitor->Trace(chrome_client_);
}
void Scrollbar::SetFrameRect(const IntRect& frame_rect) {
if (frame_rect == frame_rect_)
return;
frame_rect_ = frame_rect;
SetNeedsPaintInvalidation(kAllParts);
if (scrollable_area_)
scrollable_area_->ScrollbarFrameRectChanged();
}
ScrollbarOverlayColorTheme Scrollbar::GetScrollbarOverlayColorTheme() const {
return scrollable_area_ ? scrollable_area_->GetScrollbarOverlayColorTheme()
: kScrollbarOverlayColorThemeDark;
}
void Scrollbar::GetTickmarks(Vector<IntRect>& tickmarks) const {
if (scrollable_area_)
scrollable_area_->GetTickmarks(tickmarks);
}
bool Scrollbar::IsScrollableAreaActive() const {
return scrollable_area_ && scrollable_area_->IsActive();
}
bool Scrollbar::IsLeftSideVerticalScrollbar() const {
if (orientation_ == kVerticalScrollbar && scrollable_area_)
return scrollable_area_->ShouldPlaceVerticalScrollbarOnLeft();
return false;
}
void Scrollbar::OffsetDidChange() {
DCHECK(scrollable_area_);
float position = ScrollableAreaCurrentPos();
if (position == current_pos_)
return;
float old_position = current_pos_;
int old_thumb_position = GetTheme().ThumbPosition(*this);
current_pos_ = position;
ScrollbarPart invalid_parts =
GetTheme().InvalidateOnThumbPositionChange(*this, old_position, position);
SetNeedsPaintInvalidation(invalid_parts);
if (pressed_part_ == kThumbPart)
SetPressedPos(pressed_pos_ + GetTheme().ThumbPosition(*this) -
old_thumb_position);
}
void Scrollbar::DisconnectFromScrollableArea() {
scrollable_area_ = nullptr;
}
void Scrollbar::SetProportion(int visible_size, int total_size) {
if (visible_size == visible_size_ && total_size == total_size_)
return;
visible_size_ = visible_size;
total_size_ = total_size;
SetNeedsPaintInvalidation(kAllParts);
}
void Scrollbar::Paint(GraphicsContext& context,
const CullRect& cull_rect) const {
if (!cull_rect.IntersectsCullRect(FrameRect()))
return;
GetTheme().Paint(*this, context, cull_rect);
}
void Scrollbar::AutoscrollTimerFired(TimerBase*) {
AutoscrollPressedPart(GetTheme().AutoscrollTimerDelay());
}
bool Scrollbar::ThumbWillBeUnderMouse() const {
int thumb_pos = GetTheme().TrackPosition(*this) +
GetTheme().ThumbPosition(*this, ScrollableAreaTargetPos());
int thumb_length = GetTheme().ThumbLength(*this);
return PressedPos() >= thumb_pos && PressedPos() < thumb_pos + thumb_length;
}
void Scrollbar::AutoscrollPressedPart(double delay) {
// Don't do anything for the thumb or if nothing was pressed.
if (pressed_part_ == kThumbPart || pressed_part_ == kNoPart)
return;
// Handle the track.
if ((pressed_part_ == kBackTrackPart || pressed_part_ == kForwardTrackPart) &&
ThumbWillBeUnderMouse()) {
SetHoveredPart(kThumbPart);
return;
}
// Handle the arrows and track.
if (scrollable_area_ &&
scrollable_area_
->UserScroll(PressedPartScrollGranularity(),
ToScrollDelta(PressedPartScrollDirectionPhysical(), 1))
.DidScroll())
StartTimerIfNeeded(delay);
}
void Scrollbar::StartTimerIfNeeded(double delay) {
// Don't do anything for the thumb.
if (pressed_part_ == kThumbPart)
return;
// Handle the track. We halt track scrolling once the thumb is level
// with us.
if ((pressed_part_ == kBackTrackPart || pressed_part_ == kForwardTrackPart) &&
ThumbWillBeUnderMouse()) {
SetHoveredPart(kThumbPart);
return;
}
// We can't scroll if we've hit the beginning or end.
ScrollDirectionPhysical dir = PressedPartScrollDirectionPhysical();
if (dir == kScrollUp || dir == kScrollLeft) {
if (current_pos_ == 0)
return;
} else {
if (current_pos_ == Maximum())
return;
}
scroll_timer_.StartOneShot(delay, FROM_HERE);
}
void Scrollbar::StopTimerIfNeeded() {
scroll_timer_.Stop();
}
ScrollDirectionPhysical Scrollbar::PressedPartScrollDirectionPhysical() {
if (orientation_ == kHorizontalScrollbar) {
if (pressed_part_ == kBackButtonStartPart ||
pressed_part_ == kBackButtonEndPart || pressed_part_ == kBackTrackPart)
return kScrollLeft;
return kScrollRight;
} else {
if (pressed_part_ == kBackButtonStartPart ||
pressed_part_ == kBackButtonEndPart || pressed_part_ == kBackTrackPart)
return kScrollUp;
return kScrollDown;
}
}
ScrollGranularity Scrollbar::PressedPartScrollGranularity() {
if (pressed_part_ == kBackButtonStartPart ||
pressed_part_ == kBackButtonEndPart ||
pressed_part_ == kForwardButtonStartPart ||
pressed_part_ == kForwardButtonEndPart)
return kScrollByLine;
return kScrollByPage;
}
void Scrollbar::MoveThumb(int pos, bool dragging_document) {
if (!scrollable_area_)
return;
int delta = pos - pressed_pos_;
if (dragging_document) {
if (dragging_document_)
delta = pos - document_drag_pos_;
dragging_document_ = true;
ScrollOffset current_position =
scrollable_area_->GetScrollAnimator().CurrentOffset();
float destination_position =
(orientation_ == kHorizontalScrollbar ? current_position.Width()
: current_position.Height()) +
delta;
destination_position =
scrollable_area_->ClampScrollOffset(orientation_, destination_position);
scrollable_area_->SetScrollOffsetSingleAxis(
orientation_, destination_position, kUserScroll);
document_drag_pos_ = pos;
return;
}
if (dragging_document_) {
delta += pressed_pos_ - document_drag_pos_;
dragging_document_ = false;
}
// Drag the thumb.
int thumb_pos = GetTheme().ThumbPosition(*this);
int thumb_len = GetTheme().ThumbLength(*this);
int track_len = GetTheme().TrackLength(*this);
DCHECK_LE(thumb_len, track_len);
if (thumb_len == track_len)
return;
if (delta > 0)
delta = std::min(track_len - thumb_len - thumb_pos, delta);
else if (delta < 0)
delta = std::max(-thumb_pos, delta);
float min_offset = scrollable_area_->MinimumScrollOffset(orientation_);
float max_offset = scrollable_area_->MaximumScrollOffset(orientation_);
if (delta) {
float new_offset = static_cast<float>(thumb_pos + delta) *
(max_offset - min_offset) / (track_len - thumb_len) +
min_offset;
scrollable_area_->SetScrollOffsetSingleAxis(orientation_, new_offset,
kUserScroll);
}
}
void Scrollbar::SetHoveredPart(ScrollbarPart part) {
if (part == hovered_part_)
return;
if (((hovered_part_ == kNoPart || part == kNoPart) &&
GetTheme().InvalidateOnMouseEnterExit())
// When there's a pressed part, we don't draw a hovered state, so there's
// no reason to invalidate.
|| pressed_part_ == kNoPart)
SetNeedsPaintInvalidation(static_cast<ScrollbarPart>(hovered_part_ | part));
hovered_part_ = part;
}
void Scrollbar::SetPressedPart(ScrollbarPart part) {
if (pressed_part_ != kNoPart
// When we no longer have a pressed part, we can start drawing a hovered
// state on the hovered part.
|| hovered_part_ != kNoPart)
SetNeedsPaintInvalidation(
static_cast<ScrollbarPart>(pressed_part_ | hovered_part_ | part));
if (GetScrollableArea())
GetScrollableArea()->DidScrollWithScrollbar(part, Orientation());
pressed_part_ = part;
}
bool Scrollbar::GestureEvent(const WebGestureEvent& evt,
bool* should_update_capture) {
DCHECK(should_update_capture);
switch (evt.GetType()) {
case WebInputEvent::kGestureTapDown: {
IntPoint position = FlooredIntPoint(evt.PositionInRootFrame());
SetPressedPart(GetTheme().HitTest(*this, position));
pressed_pos_ = Orientation() == kHorizontalScrollbar
? ConvertFromRootFrame(position).X()
: ConvertFromRootFrame(position).Y();
*should_update_capture = true;
return true;
}
case WebInputEvent::kGestureTapCancel:
if (pressed_part_ != kThumbPart)
return false;
scroll_pos_ = pressed_pos_;
return true;
case WebInputEvent::kGestureScrollBegin:
switch (evt.SourceDevice()) {
case kWebGestureDeviceSyntheticAutoscroll:
case kWebGestureDeviceTouchpad:
// Update the state on GSB for touchpad since GestureTapDown
// is not generated by that device. Touchscreen uses the tap down
// gesture since the scrollbar enters a visual active state.
SetPressedPart(kNoPart);
pressed_pos_ = 0;
return false;
case kWebGestureDeviceTouchscreen:
if (pressed_part_ != kThumbPart)
return false;
scroll_pos_ = pressed_pos_;
return true;
default:
NOTREACHED();
return true;
}
break;
case WebInputEvent::kGestureScrollUpdate:
switch (evt.SourceDevice()) {
case kWebGestureDeviceSyntheticAutoscroll:
case kWebGestureDeviceTouchpad:
return false;
case kWebGestureDeviceTouchscreen:
if (pressed_part_ != kThumbPart)
return false;
scroll_pos_ += Orientation() == kHorizontalScrollbar
? evt.DeltaXInRootFrame()
: evt.DeltaYInRootFrame();
MoveThumb(scroll_pos_, false);
return true;
default:
NOTREACHED();
return true;
}
break;
case WebInputEvent::kGestureScrollEnd:
case WebInputEvent::kGestureLongPress:
case WebInputEvent::kGestureFlingStart:
scroll_pos_ = 0;
pressed_pos_ = 0;
SetPressedPart(kNoPart);
return false;
case WebInputEvent::kGestureTap: {
if (pressed_part_ != kThumbPart && pressed_part_ != kNoPart &&
scrollable_area_ &&
scrollable_area_
->UserScroll(
PressedPartScrollGranularity(),
ToScrollDelta(PressedPartScrollDirectionPhysical(), 1))
.DidScroll()) {
return true;
}
scroll_pos_ = 0;
pressed_pos_ = 0;
SetPressedPart(kNoPart);
return false;
}
default:
// By default, we assume that gestures don't deselect the scrollbar.
return true;
}
}
void Scrollbar::MouseMoved(const WebMouseEvent& evt) {
IntPoint position = FlooredIntPoint(evt.PositionInRootFrame());
if (pressed_part_ == kThumbPart) {
if (GetTheme().ShouldSnapBackToDragOrigin(*this, evt)) {
if (scrollable_area_) {
scrollable_area_->SetScrollOffsetSingleAxis(
orientation_,
drag_origin_ + scrollable_area_->MinimumScrollOffset(orientation_),
kUserScroll);
}
} else {
MoveThumb(orientation_ == kHorizontalScrollbar
? ConvertFromRootFrame(position).X()
: ConvertFromRootFrame(position).Y(),
GetTheme().ShouldDragDocumentInsteadOfThumb(*this, evt));
}
return;
}
if (pressed_part_ != kNoPart) {
pressed_pos_ = Orientation() == kHorizontalScrollbar
? ConvertFromRootFrame(position).X()
: ConvertFromRootFrame(position).Y();
}
ScrollbarPart part = GetTheme().HitTest(*this, position);
if (part != hovered_part_) {
if (pressed_part_ != kNoPart) {
if (part == pressed_part_) {
// The mouse is moving back over the pressed part. We
// need to start up the timer action again.
StartTimerIfNeeded(GetTheme().AutoscrollTimerDelay());
} else if (hovered_part_ == pressed_part_) {
// The mouse is leaving the pressed part. Kill our timer
// if needed.
StopTimerIfNeeded();
}
}
SetHoveredPart(part);
}
return;
}
void Scrollbar::MouseEntered() {
if (scrollable_area_)
scrollable_area_->MouseEnteredScrollbar(*this);
}
void Scrollbar::MouseExited() {
if (scrollable_area_)
scrollable_area_->MouseExitedScrollbar(*this);
SetHoveredPart(kNoPart);
}
void Scrollbar::MouseUp(const WebMouseEvent& mouse_event) {
bool is_captured = pressed_part_ == kThumbPart;
SetPressedPart(kNoPart);
pressed_pos_ = 0;
dragging_document_ = false;
StopTimerIfNeeded();
if (scrollable_area_) {
if (is_captured)
scrollable_area_->MouseReleasedScrollbar(orientation_);
ScrollbarPart part = GetTheme().HitTest(
*this, FlooredIntPoint(mouse_event.PositionInRootFrame()));
if (part == kNoPart) {
SetHoveredPart(kNoPart);
scrollable_area_->MouseExitedScrollbar(*this);
}
}
}
void Scrollbar::MouseDown(const WebMouseEvent& evt) {
// Early exit for right click
if (evt.button == WebPointerProperties::Button::kRight)
return;
IntPoint position = FlooredIntPoint(evt.PositionInRootFrame());
SetPressedPart(GetTheme().HitTest(*this, position));
int pressed_pos = Orientation() == kHorizontalScrollbar
? ConvertFromRootFrame(position).X()
: ConvertFromRootFrame(position).Y();
if ((pressed_part_ == kBackTrackPart || pressed_part_ == kForwardTrackPart) &&
GetTheme().ShouldCenterOnThumb(*this, evt)) {
SetHoveredPart(kThumbPart);
SetPressedPart(kThumbPart);
drag_origin_ = current_pos_;
int thumb_len = GetTheme().ThumbLength(*this);
int desired_pos = pressed_pos;
// Set the pressed position to the middle of the thumb so that when we do
// the move, the delta will be from the current pixel position of the thumb
// to the new desired position for the thumb.
pressed_pos_ = GetTheme().TrackPosition(*this) +
GetTheme().ThumbPosition(*this) + thumb_len / 2;
MoveThumb(desired_pos);
return;
}
if (pressed_part_ == kThumbPart) {
drag_origin_ = current_pos_;
if (scrollable_area_)
scrollable_area_->MouseCapturedScrollbar();
}
pressed_pos_ = pressed_pos;
AutoscrollPressedPart(GetTheme().InitialAutoscrollTimerDelay());
}
void Scrollbar::SetScrollbarsHiddenIfOverlay(bool hidden) {
if (scrollable_area_)
scrollable_area_->SetScrollbarsHiddenIfOverlay(hidden);
}
void Scrollbar::SetEnabled(bool e) {
if (enabled_ == e)
return;
enabled_ = e;
GetTheme().UpdateEnabledState(*this);
// We can skip thumb/track repaint when hiding an overlay scrollbar, but not
// when showing (since the proportions may have changed while hidden).
bool skipPartsRepaint = IsOverlayScrollbar() && scrollable_area_ &&
scrollable_area_->ScrollbarsHiddenIfOverlay();
SetNeedsPaintInvalidation(skipPartsRepaint ? kNoPart : kAllParts);
}
int Scrollbar::ScrollbarThickness() const {
int thickness = Orientation() == kHorizontalScrollbar ? Height() : Width();
if (!thickness || !chrome_client_)
return thickness;
return chrome_client_->WindowToViewportScalar(theme_scrollbar_thickness_);
}
bool Scrollbar::IsOverlayScrollbar() const {
return theme_.UsesOverlayScrollbars();
}
bool Scrollbar::ShouldParticipateInHitTesting() {
// Non-overlay scrollbars should always participate in hit testing.
if (!IsOverlayScrollbar())
return true;
return !scrollable_area_->ScrollbarsHiddenIfOverlay();
}
bool Scrollbar::IsWindowActive() const {
return scrollable_area_ && scrollable_area_->IsActive();
}
IntPoint Scrollbar::ConvertFromRootFrame(
const IntPoint& point_in_root_frame) const {
if (scrollable_area_) {
IntPoint parent_point =
scrollable_area_->ConvertFromRootFrame(point_in_root_frame);
return scrollable_area_
->ConvertFromContainingEmbeddedContentViewToScrollbar(*this,
parent_point);
}
return point_in_root_frame;
}
IntRect Scrollbar::ConvertToContainingEmbeddedContentView(
const IntRect& local_rect) const {
if (scrollable_area_) {
return scrollable_area_
->ConvertFromScrollbarToContainingEmbeddedContentView(*this,
local_rect);
}
return local_rect;
}
IntPoint Scrollbar::ConvertFromContainingEmbeddedContentView(
const IntPoint& parent_point) const {
if (scrollable_area_) {
return scrollable_area_
->ConvertFromContainingEmbeddedContentViewToScrollbar(*this,
parent_point);
}
return parent_point;
}
float Scrollbar::ScrollableAreaCurrentPos() const {
if (!scrollable_area_)
return 0;
if (orientation_ == kHorizontalScrollbar) {
return scrollable_area_->GetScrollOffset().Width() -
scrollable_area_->MinimumScrollOffset().Width();
}
return scrollable_area_->GetScrollOffset().Height() -
scrollable_area_->MinimumScrollOffset().Height();
}
float Scrollbar::ScrollableAreaTargetPos() const {
if (!scrollable_area_)
return 0;
if (orientation_ == kHorizontalScrollbar) {
return scrollable_area_->GetScrollAnimator().DesiredTargetOffset().Width() -
scrollable_area_->MinimumScrollOffset().Width();
}
return scrollable_area_->GetScrollAnimator().DesiredTargetOffset().Height() -
scrollable_area_->MinimumScrollOffset().Height();
}
void Scrollbar::SetNeedsPaintInvalidation(ScrollbarPart invalid_parts) {
if (theme_.ShouldRepaintAllPartsOnInvalidation())
invalid_parts = kAllParts;
if (invalid_parts & ~kThumbPart)
track_needs_repaint_ = true;
if (invalid_parts & kThumbPart)
thumb_needs_repaint_ = true;
if (scrollable_area_)
scrollable_area_->SetScrollbarNeedsPaintInvalidation(Orientation());
}
STATIC_ASSERT_ENUM(kWebScrollbarOverlayColorThemeDark,
kScrollbarOverlayColorThemeDark);
STATIC_ASSERT_ENUM(kWebScrollbarOverlayColorThemeLight,
kScrollbarOverlayColorThemeLight);
} // namespace blink
| 33.84031 | 80 | 0.693591 | zipated |