blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bbb30ae8504b7a58f9fcc79f9ebf738cef8604ba | b489505f6e1e32e73dc52cc6fef544a699cd663c | /include/tris.h | 7d7ba78c4bf21749a9c395a97dc3772b9daec2d8 | [] | no_license | mastoo/gbvh | d8fbc7b5c963c3851c9a8123fe785aca3e51e305 | 3f1c77eb0648424eafe174b1899a45b812535efb | refs/heads/master | 2021-01-19T12:36:42.671011 | 2015-06-29T04:50:53 | 2015-06-29T04:50:53 | 34,753,000 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 248 | h | #ifndef __TRIS_H__
#define __TRIS_H__
#include <iostream>
#include "mesh.h"
//write the mesh in Moller–Trumbore format
void write_tris_ssv_mt(std::ostream &os,const mesh &m);
void write_tris_bin_mt(std::ostream &os,const mesh &m);
#endif
| [
"[email protected]"
] | |
0a8adffc9cfc75cd74dd4c0a87246c64c7acf5a3 | 2d62d6fe4aaff6e3b9b90feb3a8e862c078e3b8c | /12.1/cow.h | d15f0a4ae6ee81581884f82d3dd31a6d6b39d286 | [] | no_license | ameks94/PrataTasks | 91e57178f0187bd63ba147418755b0ecf75faf41 | 7defcbf5ca998908202231e7a7db090c7fc43c50 | refs/heads/master | 2021-01-19T05:48:30.704960 | 2014-03-13T17:10:31 | 2014-03-13T17:10:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 302 | h | #ifndef COW_H
#define COW_H
#include "CheckInput.h"
class Cow
{
private:
char name[20];
char * hobby;
double weight;
public:
Cow();
Cow(const char * nm, const char * ho, double wt);
Cow(const Cow & c);
~Cow() { delete[] hobby; }
Cow & operator=(const Cow & c);
void ShowCow() const;
};
#endif | [
"[email protected]"
] | |
26937e19f2cd9e67a67dc64901257b93601bf00f | 1575b21a65036e73bdf3aed5890fbe21b08965af | /Arduino/TimeLightPID/TimeLightPID.ino | ad8ea499b61dd03c6f55f8ce49f8a36f9c980452 | [] | no_license | DevNulPavel/Hardware | bc74c2fab3febc647663aabeee4c73170a269bd2 | 7f190cb646052d2466a1fcc804e81dc236ca6d66 | refs/heads/master | 2020-03-30T12:36:11.945287 | 2018-11-01T13:28:42 | 2018-11-01T13:28:42 | 151,231,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,677 | ino | #include <TimeLib.h>
#include <Wire.h>
#include <DS1307RTC.h>
#include <PID_v1.h>
//#define WITH_LOG
#define OUT_PIN 3
#define PHOTO_PIN 0
bool onStatus = false;
double targetValue = 0.0;
double currentValue = 0.0;
double resultValue = 0.0;
//Specify the links and initial tuning parameters
const double kp = 0.0;
const double ki = 0.01;
const double kd = 0.0;
PID pid(¤tValue, &resultValue, &targetValue, kp, ki, kd, DIRECT);
void setup() {
#ifdef WITH_LOG
Serial.begin(115200);
#endif
setSyncProvider(RTC.get); // the function to get the time from the RTC
pinMode(OUT_PIN, OUTPUT);
pid.SetMode(AUTOMATIC);
pid.SetSampleTime(50); // Раз в 50 миллисекунды будет рассчет
// Частота ШИМ для 3 ноги 3906.25гц
// http://kazus.ru/forums/showthread.php?t=107888
TCCR2B = TCCR2B & 0b11111000 | 0x02;
targetValue = 600.0;
}
void loop() {
int hourNow = hour();
int minNow = minute();
int testTime = hourNow*60 + minNow;
bool validStart = (testTime >= (9*60+0));
bool validEnd = (testTime < (21*60+30));
bool validTime = validStart && validEnd;
#ifdef WITH_LOG
Serial.print(hourNow);
Serial.print(":");
Serial.print(minNow);
Serial.print(", ");
Serial.print(validTime);
Serial.println();
#endif
currentValue = analogRead(PHOTO_PIN);
delay(1);
pid.Compute();
#ifdef WITH_LOG
Serial.print("Photo val: ");
Serial.print(currentValue);
Serial.print(", pid result val: ");
Serial.print(resultValue);
Serial.println();
Serial.println();
#endif
//int pinOutValue = map(resultValue, 0, targetValue, 0, 255);
analogWrite(OUT_PIN, resultValue);
delay(20);
}
| [
"[email protected]"
] | |
00432e80c1b120669cff33f34984b9303906d95e | f14626611951a4f11a84cd71f5a2161cd144a53a | /NETS/netlogin/AinMessage.cpp | 923d793dca623a3154e98d5454825387e4334d92 | [] | no_license | Deadmanovi4/mmo-resourse | 045616f9be76f3b9cd4a39605accd2afa8099297 | 1c310e15147ae775a59626aa5b5587c6895014de | refs/heads/master | 2021-05-29T06:14:28.650762 | 2015-06-18T01:16:43 | 2015-06-18T01:16:43 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,299 | cpp |
#include "stdafx.h"
#include "AinMessage.h"
extern void OnAinMessage(AinMessage* pAimMsg);
AinMessage* AinMessage::Create(LONG lType)
{
AinMessage* pRe = (AinMessage*)M_ALLOC(sizeof(AinMessage));
if(NULL != pRe)
new(pRe)AinMessage(lType);
return pRe;
}
VOID AinMessage::Release(AinMessage **ppAinMsg)
{
if(NULL == ppAinMsg || NULL == *ppAinMsg)return;
(*ppAinMsg)->~AinMessage();
M_FREE(*ppAinMsg, sizeof(AinMessage));
}
VOID AinMessage::AddByte(BYTE cData)
{
m_vData.push_back(cData);
}
VOID AinMessage::AddWord(WORD wData)
{
size_t lSize = m_vData.size();
m_vData.resize(lSize + sizeof(WORD));
memcpy(&m_vData[lSize], &wData, sizeof(WORD));
}
VOID AinMessage::AddDword(DWORD dwData)
{
size_t lSize = m_vData.size();
m_vData.resize(lSize + sizeof(DWORD));
memcpy(&m_vData[lSize], &dwData, sizeof(DWORD));
}
VOID AinMessage::AddStr(LPCSTR pStr)
{
if(NULL == pStr)
{
assert(false);
return;
}
WORD wStrLen = (WORD)strlen(pStr);
AddWord(wStrLen);
AddEx(pStr, wStrLen);
}
VOID AinMessage::AddEx(LPCVOID pData, DWORD dwAddSize)
{
size_t lSize = m_vData.size();
m_vData.resize(lSize + dwAddSize);
memcpy(&m_vData[lSize], pData, dwAddSize);
}
BYTE AinMessage::GetByte(VOID)
{
BYTE cRe = 0;
size_t lSize = m_vData.size();
if(m_dwPos + sizeof(BYTE) <= lSize)
{
cRe = m_vData[m_dwPos];
m_dwPos += sizeof(BYTE);
}
else
assert(false);
return cRe;
}
WORD AinMessage::GetWord(VOID)
{
WORD wRe = 0;
size_t lSize = m_vData.size();
if(m_dwPos + sizeof(WORD) <= lSize)
{
wRe = *(WORD*)(&m_vData[m_dwPos]);
m_dwPos += sizeof(WORD);
}
else
assert(false);
return wRe;
}
DWORD AinMessage::GetDword(VOID)
{
DWORD dwRe = 0;
size_t lSize = m_vData.size();
if(m_dwPos + sizeof(DWORD) <= lSize)
{
dwRe = *(DWORD*)(&m_vData[m_dwPos]);
m_dwPos += sizeof(DWORD);
}
else
assert(false);
return dwRe;
}
BOOL AinMessage::GetStr(LPSTR pStr, WORD dwBufMaxSize)
{
BOOL bRe = FALSE;
WORD wStrLen = GetWord();
WORD wLoadLen = min(wStrLen, dwBufMaxSize - 1);
size_t lSize = m_vData.size();
if(m_dwPos + wStrLen <= lSize)
{
memcpy(pStr, &(m_vData[m_dwPos]), wLoadLen);
m_dwPos += wStrLen;
bRe = TRUE;
}
else
assert(false);
return bRe;
}
BOOL AinMessage::GetEx(LPVOID pData, DWORD lGetSize)
{
BOOL bRe = FALSE;
size_t lSize = m_vData.size();
if(m_dwPos + lGetSize <= lSize)
{
memcpy(pData, &(m_vData[m_dwPos]), lGetSize);
m_dwPos += lGetSize;
bRe = TRUE;
}
else
assert(false);
return bRe;
}
VOID AinMessage::Run(VOID)
{
OnAinMessage(this);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
AinMsgQueue::AinMsgQueue(VOID)
:m_dwMinBeginTime(0xFFFFFFFF)
{
}
AinMsgQueue::~AinMsgQueue(VOID)
{
}
VOID AinMsgQueue::Release(VOID)
{
//! 执行最后队列的消息
list<AinMessage*> listMsg;
PopMessage(listMsg);
for(list<AinMessage*>::iterator ite = listMsg.begin(); listMsg.end() != ite; ite++)
{
if( NULL != *ite )
{
(*ite)->Run();
AinMessage::Release(&(*ite));
}
}
//! 定时为到的消息不执行了
map<DWORD, AinMessage*>::iterator ite = m_timeMsgQueue.begin();
for (; m_timeMsgQueue.end() != ite; ++ite)
{
AinMessage::Release(&(ite->second));
}
}
//! 得到消息数目
LONG AinMsgQueue::GetSize(VOID)
{
LONG lRe = 0;
m_Lock.Lock();
{
lRe = (LONG)m_msgQueue.size() + (LONG)m_timeMsgQueue.size();
}
m_Lock.UnLock();
return lRe;
}
//! 压入消息
BOOL AinMsgQueue::PushMessage(AinMessage* pMsg)
{
if(NULL == pMsg) return FALSE;
m_Lock.Lock();
{
m_msgQueue.push_back(pMsg);
}
m_Lock.UnLock();
return TRUE;
}
//! 压入一个定时消息
BOOL AinMsgQueue::PushTimeMessage(AinMessage* pMsg, DWORD dwMillisecond)
{
if(NULL == pMsg) return FALSE;
if(0 == dwMillisecond)
return PushMessage(pMsg);
DWORD dwCurrTime = timeGetTime();
DWORD dwBeginTime = dwCurrTime + dwMillisecond;
m_Lock.Lock();
{
do
{
if(m_timeMsgQueue.end() != m_timeMsgQueue.find(dwBeginTime))
++dwBeginTime;
else
break;
} while(true);
m_timeMsgQueue[dwBeginTime] = pMsg;
m_dwMinBeginTime = min(m_dwMinBeginTime, dwBeginTime);
}
m_Lock.UnLock();
return TRUE;
}
//! 弹出消息
VOID AinMsgQueue::PopMessage(list<AinMessage*> &listMsg)
{
//! 普通消息
m_Lock.Lock();
{
listMsg = m_msgQueue;
m_msgQueue.clear();
}
m_Lock.UnLock();
//! 定时消息
DWORD dwCurrTime = timeGetTime();
if(m_dwMinBeginTime <= dwCurrTime)
{
m_Lock.Lock();
{
while (0 != m_timeMsgQueue.size() && dwCurrTime < m_timeMsgQueue.begin()->first)
{
listMsg.push_back(m_timeMsgQueue.begin()->second);
m_timeMsgQueue.erase(m_timeMsgQueue.begin());
}
if(0 == m_timeMsgQueue.size())
m_dwMinBeginTime = 0xFFFFFFFF;
else
m_dwMinBeginTime = m_timeMsgQueue.begin()->first;
}
m_Lock.UnLock();
}
}
//! 清空消息(不释放内存)
VOID AinMsgQueue::Clear(VOID)
{
m_Lock.Lock();
m_msgQueue.clear();
m_Lock.UnLock();
} | [
"[email protected]"
] | |
17c7f82e76c6ae37209aa8ff29add16a88d6d2aa | 6aeccfb60568a360d2d143e0271f0def40747d73 | /sandbox/SOC/2008/spacial_indexing/geometry/copy.hpp | 31d37d46abd67447d0bfdeb884caab8865f5c1bd | [
"BSL-1.0"
] | permissive | ttyang/sandbox | 1066b324a13813cb1113beca75cdaf518e952276 | e1d6fde18ced644bb63e231829b2fe0664e51fac | refs/heads/trunk | 2021-01-19T17:17:47.452557 | 2013-06-07T14:19:55 | 2013-06-07T14:19:55 | 13,488,698 | 1 | 3 | null | 2023-03-20T11:52:19 | 2013-10-11T03:08:51 | C++ | UTF-8 | C++ | false | false | 1,825 | hpp | // Geometry Library
//
// Copyright Barend Gehrels, Geodan Holding B.V. Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef _GEOMETRY_COPY_HPP
#define _GEOMETRY_COPY_HPP
#include <geometry/geometry.hpp>
/*!
\defgroup copy copy: copy utility
The copy utility method copies coordinate values
*/
namespace geometry
{
namespace impl
{
namespace copy
{
template <typename PS, typename PD, int I, int N>
struct copy_coordinates
{
static void copy(const PS& source, PD& dest)
{
// Todo: use boost-conversion-tool for the cast
get<I>(dest) = (typename point_traits<PD>::coordinate_type) get<I>(source);
copy_coordinates<PS, PD, I+1, N>::copy(source, dest);
}
};
template <typename PS, typename PD, int N>
struct copy_coordinates<PS, PD, N, N>
{
static void copy(const PS& source, PD& dest)
{}
};
} // namespace copy
} // namespace impl
/*!
\brief Copies coordinates from source to destination point
\ingroup copy
\details The function copy_coordinates copies coordinates from one point to another point.
Source point and destination point might be of different types.
\param source Source point
\param dest Destination point
\note If destination type differs from source type, they must have the same coordinate count
*/
template <typename PS, typename PD>
void copy_coordinates(const PS& source, PD& dest)
{
BOOST_STATIC_ASSERT(point_traits<PD>::coordinate_count == point_traits<PS>::coordinate_count);
impl::copy::copy_coordinates<PS, PD, 0, point_traits<PS>::coordinate_count>::copy(source, dest);
}
} // namespace geometry
#endif // _GEOMETRY_COPY_HPP
| [
"[email protected]"
] | |
2a13c949d3a540d317e5c0d3cf6b6d9ccc497022 | dc25b23f8132469fd95cee14189672cebc06aa56 | /vendor/mediatek/proprietary/hardware/mtkcam/legacy/platform/mt6795/core/featureio/drv/nvram/nvram_drv.cpp | 713b5329f576915e819e8b9bf8a6d168bb7dcdbc | [] | no_license | nofearnohappy/alps_mm | b407d3ab2ea9fa0a36d09333a2af480b42cfe65c | 9907611f8c2298fe4a45767df91276ec3118dd27 | refs/heads/master | 2020-04-23T08:46:58.421689 | 2019-03-28T21:19:33 | 2019-03-28T21:19:33 | 171,048,255 | 1 | 5 | null | 2020-03-08T03:49:37 | 2019-02-16T20:25:00 | Java | UTF-8 | C++ | false | false | 39,690 | cpp | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*/
/* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
/********************************************************************************************
* LEGAL DISCLAIMER
*
* (Header of MediaTek Software/Firmware Release or Documentation)
*
* BY OPENING OR USING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") RECEIVED
* FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON AN "AS-IS" BASIS
* ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR
* A PARTICULAR PURPOSE OR NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY
* WHATSOEVER WITH RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK
* ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
* NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S SPECIFICATION
* OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
* BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE LIABILITY WITH
* RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION,
TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE
* FEES OR SERVICE CHARGE PAID BY BUYER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE WITH THE LAWS
* OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF LAWS PRINCIPLES.
************************************************************************************************/
#include <utils/Errors.h>
#include <utils/Log.h>
#include <fcntl.h>
#include "../inc/nvram_drv.h"
#include "nvram_drv_imp.h"
#include "libnvram.h"
#include "CFG_file_lid.h"
#include "camera_custom_AEPlinetable.h"
#include <aaa_types.h>
#include "flash_param.h"
#include "flash_tuning_custom.h"
#include "CFG_file_lid.h"//AP_CFG_RESERVED_1 for AudEnh
#include "Custom_NvRam_LID.h"
#include "libnvram.h"
#include "nvram_agent_client.h"
#include <cutils/properties.h>
#ifdef NVRAM_SUPPORT
#include "camera_custom_msdk.h"
#endif
/*******************************************************************************
*
********************************************************************************/
/*******************************************************************************
*
********************************************************************************/
#undef LOG_TAG
#define LOG_TAG "NvramDrv"
#define NVRAM_DRV_LOG(fmt, arg...) ALOGD(LOG_TAG " " fmt, ##arg)
#define NVRAM_DRV_ERR(fmt, arg...) ALOGE(LOG_TAG "Err: %5d: " fmt, __LINE__, ##arg)
#define logI(fmt, arg...) NVRAM_DRV_LOG(fmt, ##arg)
#define logE(fmt, arg...) NVRAM_DRV_ERR(fmt, ##arg)
#define INVALID_HANDLE_VALUE (-1)
using namespace android;
/*******************************************************************************
*
********************************************************************************/
static unsigned long const g_u4NvramDataSize[CAMERA_DATA_TYPE_NUM] =
{
sizeof(NVRAM_CAMERA_ISP_PARAM_STRUCT),
sizeof(NVRAM_CAMERA_3A_STRUCT),
sizeof(NVRAM_CAMERA_SHADING_STRUCT),
sizeof(NVRAM_LENS_PARA_STRUCT),
sizeof(AE_PLINETABLE_T),
sizeof(NVRAM_CAMERA_STROBE_STRUCT),
sizeof(CAMERA_TSF_TBL_STRUCT),
sizeof(NVRAM_CAMERA_GEOMETRY_STRUCT),
sizeof(NVRAM_CAMERA_FEATURE_STRUCT),
sizeof(NVRAM_CAMERA_VERSION_STRUCT),
};
static bool bCustomInit = 0; //[ALPS00424402] [CCT6589] Len shading page --> Save to NVRAM --> CCT reboot failed
/*******************************************************************************
*
********************************************************************************/
int binderWriteNvram(int file_lid, void *pBuf, int sh);
int binderReadNvram(int file_lid, void *pBuf, int sh);
NvramDrvBase*
NvramDrvBase::createInstance()
{
return NvramDrv::getInstance();
}
/*******************************************************************************
*
********************************************************************************/
NvramDrvBase*
NvramDrv::getInstance()
{
static NvramDrv singleton;
return &singleton;
}
void NvramDrv::setAndroidMode(int isAndroid)
{
Mutex::Autolock lock(mLock);
//mAndroidMode=isAndroid;
mAndroidMode=0;
}
/*******************************************************************************
*
********************************************************************************/
void
NvramDrv::destroyInstance()
{
}
/*******************************************************************************
*
********************************************************************************/
NvramDrv::NvramDrv()
: NvramDrvBase()
{
mAndroidMode=0;
}
/*******************************************************************************
*
********************************************************************************/
NvramDrv::~NvramDrv()
{
}
/*******************************************************************************
*
********************************************************************************/
int checkDataVersionNew(
CAMERA_DATA_TYPE_ENUM a_eNvramDataType,
int version
)
{
int err = NVRAM_NO_ERROR;
NVRAM_DRV_LOG("checkDataVersionNew");
//err = NVRAM_DATA_VERSION_ERROR;
int targetVersion=0;
if (a_eNvramDataType == CAMERA_NVRAM_DATA_ISP) // ISP
targetVersion = NVRAM_CAMERA_PARA_FILE_VERSION;
else if (a_eNvramDataType == CAMERA_NVRAM_DATA_3A) // 3A
targetVersion = NVRAM_CAMERA_3A_FILE_VERSION;
else if (a_eNvramDataType == CAMERA_NVRAM_DATA_SHADING) // Shading
targetVersion = NVRAM_CAMERA_SHADING_FILE_VERSION;
else if (a_eNvramDataType == CAMERA_NVRAM_DATA_LENS) // Lens
targetVersion = NVRAM_CAMERA_LENS_FILE_VERSION;
else if (a_eNvramDataType == CAMERA_NVRAM_DATA_STROBE) // strobe
targetVersion = NVRAM_CAMERA_STROBE_FILE_VERSION;
else if (a_eNvramDataType == CAMERA_NVRAM_DATA_GEOMETRY) // geometry
targetVersion = NVRAM_CAMERA_GEOMETRY_FILE_VERSION;
else if (a_eNvramDataType == CAMERA_NVRAM_DATA_FEATURE) // strobe
targetVersion = NVRAM_CAMERA_FEATURE_FILE_VERSION;
else if (a_eNvramDataType == CAMERA_DATA_AE_PLINETABLE) // strobe
targetVersion = NVRAM_CAMERA_PLINE_FILE_VERSION;
else
NVRAM_DRV_ERR("checkDataVersion(): incorrect data type\n");
NVRAM_DRV_LOG("checkDataVersionNew v=%d vTar=%d", version, targetVersion);
if(version!=targetVersion)
return NVRAM_DATA_VERSION_ERROR;
else
return NVRAM_NO_ERROR;
}
int NvramDrv::readNoDefault(CAMERA_DUAL_CAMERA_SENSOR_ENUM a_eSensorType,
CAMERA_DATA_TYPE_ENUM a_eNvramDataType,
void *a_pNvramData,
unsigned long a_u4NvramDataSize)
{
int err = NVRAM_NO_ERROR;
NVRAM_DRV_LOG("[readNoDefault] id=%d dev=%d",a_eSensorType,a_eNvramDataType);
err = readNvramData(a_eSensorType, a_eNvramDataType, a_pNvramData);
if (err != NVRAM_NO_ERROR)
NVRAM_DRV_ERR("readNvramData() error: ==> readDefaultData()\n");
return err;
}
int NvramDrv::readNvrameEx(CAMERA_DUAL_CAMERA_SENSOR_ENUM a_eSensorType,
unsigned long u4SensorID,
CAMERA_DATA_TYPE_ENUM a_eNvramDataType,
void *a_pNvramData,
unsigned long a_u4NvramDataSize,
int version)
{
int err = NVRAM_NO_ERROR;
NVRAM_DRV_LOG("[readNvrameEx] sensor type = %d; NVRAM data type = %d\n", a_eSensorType, a_eNvramDataType);
if(a_eSensorType == DUAL_CAMERA_MAIN_SENSOR || a_eSensorType == DUAL_CAMERA_SUB_SENSOR || a_eSensorType == DUAL_CAMERA_MAIN_SECOND_SENSOR)
;
else
{
NVRAM_DRV_LOG("[readNvrameEx] sensorId error, line=%d",__LINE__);
return NVRAM_READ_PARAMETER_ERROR;
}
if(a_pNvramData==0)
{
NVRAM_DRV_LOG("[readNvrameEx] buf adr error (=0), line=%d",__LINE__);
return NVRAM_READ_PARAMETER_ERROR;
}
if(a_eNvramDataType < CAMERA_DATA_TYPE_START || a_eNvramDataType>=CAMERA_DATA_TYPE_NUM)
{
NVRAM_DRV_LOG("[readNvrameEx] date type id error, line=%d",__LINE__);
return NVRAM_READ_PARAMETER_ERROR;
}
if(a_u4NvramDataSize != g_u4NvramDataSize[a_eNvramDataType])
{
NVRAM_DRV_LOG("[readNvrameEx] buf size is error, line=%d",__LINE__);
return NVRAM_READ_PARAMETER_ERROR;
}
if( a_eNvramDataType==CAMERA_DATA_TSF_TABLE)
{
err = readDefaultData(a_eSensorType, u4SensorID, a_eNvramDataType, a_pNvramData);
if (err != NVRAM_NO_ERROR)
NVRAM_DRV_ERR("readDefaultData() error:\n");
return err;
}
Mutex::Autolock lock(mLock);
if(checkDataVersionNew(a_eNvramDataType, version)==NVRAM_NO_ERROR)
{
switch(a_eNvramDataType)
{
case CAMERA_NVRAM_DATA_ISP:
case CAMERA_NVRAM_DATA_3A:
case CAMERA_NVRAM_DATA_SHADING:
case CAMERA_NVRAM_DATA_LENS:
case CAMERA_NVRAM_DATA_STROBE:
case CAMERA_NVRAM_DATA_GEOMETRY:
case CAMERA_NVRAM_DATA_FEATURE:
case CAMERA_DATA_AE_PLINETABLE:
err = readNvramData(a_eSensorType, a_eNvramDataType, a_pNvramData);
if (err != NVRAM_NO_ERROR)
{
NVRAM_DRV_ERR("readDefaultData() error:\n");
err = readDefaultData(a_eSensorType, u4SensorID, a_eNvramDataType, a_pNvramData);
if (err != NVRAM_NO_ERROR)
NVRAM_DRV_ERR("readDefaultData() error:\n");
}
default:
break;
}
}
else
{
err = readDefaultData(a_eSensorType, u4SensorID, a_eNvramDataType, a_pNvramData);
if (err != NVRAM_NO_ERROR)
NVRAM_DRV_ERR("readDefaultData() error:\n");
return err;
}
return err;
}
int
NvramDrv::readNvram(
CAMERA_DUAL_CAMERA_SENSOR_ENUM a_eSensorType,
unsigned long a_u4SensorID,
CAMERA_DATA_TYPE_ENUM a_eNvramDataType,
void *a_pNvramData,
unsigned long a_u4NvramDataSize
)
{
int err = NVRAM_NO_ERROR;
NVRAM_DRV_LOG("[readNvram] sensor type = %d; NVRAM data type = %d\n", a_eSensorType, a_eNvramDataType);
if ((a_eSensorType > DUAL_CAMERA_MAIN_SECOND_SENSOR) ||
(a_eSensorType < DUAL_CAMERA_MAIN_SENSOR) ||
//(a_eNvramDataType > CAMERA_DATA_AE_PLINETABLE) ||
(a_eNvramDataType >= CAMERA_DATA_TYPE_NUM) ||
(a_eNvramDataType < CAMERA_NVRAM_DATA_ISP) ||
(a_pNvramData == NULL) ||
(a_u4NvramDataSize != g_u4NvramDataSize[a_eNvramDataType]))
{
NVRAM_DRV_LOG("[readNvram] error: line=%d",__LINE__);
return NVRAM_READ_PARAMETER_ERROR;
}
Mutex::Autolock lock(mLock);
switch(a_eNvramDataType) {
case CAMERA_NVRAM_DATA_ISP:
case CAMERA_NVRAM_DATA_3A:
case CAMERA_NVRAM_DATA_SHADING:
case CAMERA_NVRAM_DATA_LENS:
case CAMERA_NVRAM_DATA_STROBE:
case CAMERA_DATA_AE_PLINETABLE:
err = readNvramData(a_eSensorType, a_eNvramDataType, a_pNvramData);
if (err != NVRAM_NO_ERROR) {
NVRAM_DRV_ERR("readNvramData() error: ==> readDefaultData()\n");
err = readDefaultData(a_eSensorType, a_u4SensorID, a_eNvramDataType, a_pNvramData);
if (err != NVRAM_NO_ERROR) {
NVRAM_DRV_ERR("readDefaultData() error:\n");
}
break;
}
if (checkDataVersion(a_eNvramDataType, a_pNvramData) != NVRAM_NO_ERROR) {
err = readDefaultData(a_eSensorType,a_u4SensorID, a_eNvramDataType, a_pNvramData);
if (err != NVRAM_NO_ERROR) {
NVRAM_DRV_ERR("readDefaultData() error:\n");
}
}
break;
case CAMERA_DATA_TSF_TABLE:
err = readDefaultData(a_eSensorType,a_u4SensorID, a_eNvramDataType, a_pNvramData);
if (err != NVRAM_NO_ERROR) {
NVRAM_DRV_ERR("readDefaultData() TSF table error:\n");
}
break;
default:
break;
}
return err;
}
/*******************************************************************************
*
********************************************************************************/
int
NvramDrv::writeNvram(
CAMERA_DUAL_CAMERA_SENSOR_ENUM a_eSensorType,
unsigned long a_u4SensorID,
CAMERA_DATA_TYPE_ENUM a_eNvramDataType,
void *a_pNvramData,
unsigned long a_u4NvramDataSize
)
{
int err = NVRAM_NO_ERROR;
NVRAM_DRV_LOG("[writeNvram] sensor type = %d; NVRAM data type = %d\n", a_eSensorType, a_eNvramDataType);
if(a_eSensorType == DUAL_CAMERA_MAIN_SENSOR || a_eSensorType == DUAL_CAMERA_SUB_SENSOR || a_eSensorType == DUAL_CAMERA_MAIN_SECOND_SENSOR)
;
else
{
NVRAM_DRV_LOG("[readNvrameEx] sensorId error, line=%d",__LINE__);
return NVRAM_READ_PARAMETER_ERROR;
}
if(a_pNvramData==0)
{
NVRAM_DRV_LOG("[readNvrameEx] buf adr error (=0), line=%d",__LINE__);
return NVRAM_READ_PARAMETER_ERROR;
}
if(a_eNvramDataType < CAMERA_DATA_TYPE_START || a_eNvramDataType>=CAMERA_DATA_TYPE_NUM)
{
NVRAM_DRV_LOG("[readNvrameEx] date type id error, line=%d",__LINE__);
return NVRAM_READ_PARAMETER_ERROR;
}
if(a_u4NvramDataSize != g_u4NvramDataSize[a_eNvramDataType])
{
NVRAM_DRV_LOG("[readNvrameEx] buf size is error, line=%d",__LINE__);
return NVRAM_READ_PARAMETER_ERROR;
}
Mutex::Autolock lock(mLock);
err = writeNvramData(a_eSensorType, a_eNvramDataType, a_pNvramData);
return err;
}
/*******************************************************************************
*
********************************************************************************/
int
NvramDrv::checkDataVersion(
CAMERA_DATA_TYPE_ENUM a_eNvramDataType,
void *a_pNvramData
)
{
int err = NVRAM_NO_ERROR;
NVRAM_DRV_LOG("[checkDataVersion]\n");
if (a_eNvramDataType == CAMERA_NVRAM_DATA_ISP) { // ISP
PNVRAM_CAMERA_ISP_PARAM_STRUCT pCameraNvramData = (PNVRAM_CAMERA_ISP_PARAM_STRUCT)a_pNvramData;
NVRAM_DRV_LOG("[ISP] NVRAM data version = %d; F/W data version = %d\n", pCameraNvramData->Version, NVRAM_CAMERA_PARA_FILE_VERSION);
if (pCameraNvramData->Version != NVRAM_CAMERA_PARA_FILE_VERSION) {
err = NVRAM_DATA_VERSION_ERROR;
}
}
else if (a_eNvramDataType == CAMERA_NVRAM_DATA_3A) { // 3A
PNVRAM_CAMERA_3A_STRUCT p3ANvramData = (PNVRAM_CAMERA_3A_STRUCT)a_pNvramData;
NVRAM_DRV_LOG("[3A] NVRAM data version = %d; F/W data version = %d\n", p3ANvramData->u4Version, NVRAM_CAMERA_3A_FILE_VERSION);
if (p3ANvramData->u4Version != NVRAM_CAMERA_3A_FILE_VERSION) {
err = NVRAM_DATA_VERSION_ERROR;
}
}
else if (a_eNvramDataType == CAMERA_NVRAM_DATA_SHADING) { // Shading
PNVRAM_CAMERA_SHADING_STRUCT pShadingNvramData = (PNVRAM_CAMERA_SHADING_STRUCT)a_pNvramData;
NVRAM_DRV_LOG("[Shading] NVRAM data version = %d; F/W data version = %d\n", pShadingNvramData->Shading.Version, NVRAM_CAMERA_SHADING_FILE_VERSION);
if (pShadingNvramData->Shading.Version != NVRAM_CAMERA_SHADING_FILE_VERSION) {
err = NVRAM_DATA_VERSION_ERROR;
}
}
else if (a_eNvramDataType == CAMERA_NVRAM_DATA_LENS) { // Lens
PNVRAM_LENS_PARA_STRUCT pLensNvramData = (PNVRAM_LENS_PARA_STRUCT)a_pNvramData;
NVRAM_DRV_LOG("[Lens] NVRAM data version = %d; F/W data version = %d\n", pLensNvramData->Version, NVRAM_CAMERA_LENS_FILE_VERSION);
if (pLensNvramData->Version != NVRAM_CAMERA_LENS_FILE_VERSION) {
err = NVRAM_DATA_VERSION_ERROR;
}
}
else if (a_eNvramDataType == CAMERA_NVRAM_DATA_STROBE) { // strobe
PNVRAM_CAMERA_STROBE_STRUCT pStrobeNvramData = (PNVRAM_CAMERA_STROBE_STRUCT)a_pNvramData;
NVRAM_DRV_LOG("[Strobe] NVRAM data version = %d; F/W data version = %d\n", pStrobeNvramData->u4Version, NVRAM_CAMERA_STROBE_FILE_VERSION);
if (pStrobeNvramData->u4Version != NVRAM_CAMERA_STROBE_FILE_VERSION) {
err = NVRAM_DATA_VERSION_ERROR;
}
}
else {
NVRAM_DRV_ERR("checkDataVersion(): incorrect data type\n");
}
return err;
}
static int getMs()
{
int t;
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
t = (ts.tv_sec*1000+ts.tv_nsec/1000000);
return t;
}
/*******************************************************************************
*
********************************************************************************/
int
NvramDrv::readNvramData(
CAMERA_DUAL_CAMERA_SENSOR_ENUM a_eSensorType,
CAMERA_DATA_TYPE_ENUM a_eNvramDataType,
void *a_pNvramData
)
{
NVRAM_DRV_LOG("[readNvramData]+ a_eSensorType=%d a_eNvramDataType=%d", a_eSensorType, a_eNvramDataType);
F_ID rNvramFileID;
int i4FileInfo;
int i4RecSize;
int i4RecNum;
//seanlin 121221 avoid camera has not inited>
//[ALPS00424402] [CCT6589] Len shading page --> Save to NVRAM --> CCT reboot failed
if (!bCustomInit) {
cameraCustomInit();
if((a_eSensorType==DUAL_CAMERA_MAIN_2_SENSOR) || (a_eSensorType==DUAL_CAMERA_MAIN_SECOND_SENSOR))
LensCustomInit(8);
else
LensCustomInit((unsigned int)a_eSensorType);
bCustomInit = 1;
}
//[ALPS00424402] [CCT6589] Len shading page --> Save to NVRAM --> CCT reboot failed
//seanlin 121221 avoid camera has not inited<
if(a_eNvramDataType==CAMERA_NVRAM_DATA_SHADING)
{
//int NvramDrv::readMultiNvram(void* buf, int bufSz, int* idList, int num, int dev)
int idList[]=
{
AP_CFG_RDCL_CAMERA_SHADING_LID,
AP_CFG_RDCL_CAMERA_SHADING2_LID,
AP_CFG_RDCL_CAMERA_SHADING3_LID,
AP_CFG_RDCL_CAMERA_SHADING4_LID,
AP_CFG_RDCL_CAMERA_SHADING5_LID,
AP_CFG_RDCL_CAMERA_SHADING6_LID,
AP_CFG_RDCL_CAMERA_SHADING7_LID,
AP_CFG_RDCL_CAMERA_SHADING8_LID,
AP_CFG_RDCL_CAMERA_SHADING9_LID,
AP_CFG_RDCL_CAMERA_SHADING10_LID,
AP_CFG_RDCL_CAMERA_SHADING11_LID,
AP_CFG_RDCL_CAMERA_SHADING12_LID,
};
int err;
err = readMultiNvram(a_pNvramData, sizeof(ISP_SHADING_STRUCT), idList, 12, a_eSensorType);
return err;
}
else if(a_eNvramDataType==CAMERA_DATA_AE_PLINETABLE)
{
//int NvramDrv::readMultiNvram(void* buf, int bufSz, int* idList, int num, int dev)
int idList[]=
{
AP_CFG_RDCL_CAMERA_PLINE_LID,
AP_CFG_RDCL_CAMERA_PLINE2_LID,
AP_CFG_RDCL_CAMERA_PLINE3_LID,
AP_CFG_RDCL_CAMERA_PLINE4_LID,
AP_CFG_RDCL_CAMERA_PLINE5_LID,
AP_CFG_RDCL_CAMERA_PLINE6_LID,
AP_CFG_RDCL_CAMERA_PLINE7_LID,
AP_CFG_RDCL_CAMERA_PLINE8_LID,
AP_CFG_RDCL_CAMERA_PLINE9_LID,
AP_CFG_RDCL_CAMERA_PLINE10_LID,
AP_CFG_RDCL_CAMERA_PLINE11_LID,
AP_CFG_RDCL_CAMERA_PLINE12_LID,
};
int err;
err = readMultiNvram(a_pNvramData, sizeof(AE_PLINETABLE_T), idList, 12, a_eSensorType);
return err;
}
switch (a_eNvramDataType) {
case CAMERA_NVRAM_DATA_ISP:
i4FileInfo = AP_CFG_RDCL_CAMERA_PARA_LID;
break;
case CAMERA_NVRAM_DATA_3A:
i4FileInfo = AP_CFG_RDCL_CAMERA_3A_LID;
break;
case CAMERA_NVRAM_DATA_SHADING:
i4FileInfo = AP_CFG_RDCL_CAMERA_SHADING_LID;
break;
case CAMERA_NVRAM_DATA_LENS:
i4FileInfo = AP_CFG_RDCL_CAMERA_LENS_LID;
break;
case CAMERA_NVRAM_DATA_STROBE:
i4FileInfo = AP_CFG_RDCL_CAMERA_DEFECT_LID;
break;
case CAMERA_NVRAM_DATA_FEATURE:
i4FileInfo = AP_CFG_RDCL_CAMERA_FEATURE_LID;
break;
case CAMERA_NVRAM_DATA_GEOMETRY:
i4FileInfo = AP_CFG_RDCL_CAMERA_GEOMETRY_LID;
break;
case CAMERA_DATA_AE_PLINETABLE:
i4FileInfo = AP_CFG_RDCL_CAMERA_PLINE_LID;
break;
case CAMERA_NVRAM_VERSION:
a_eSensorType = DUAL_CAMERA_MAIN_SENSOR;
i4FileInfo = AP_CFG_RDCL_CAMERA_VERSION_LID;
break;
default :
NVRAM_DRV_ERR("readNvramData(): incorrect data type\n");
return NVRAM_READ_PARAMETER_ERROR;
break;
}
#ifdef NVRAM_SUPPORT
int ms1;
int ms2;
ms1 = getMs();
while(1)
{
// logI("check nvram demon");
NVRAM_DRV_LOG("check nvram demon");
char nvram_init_val[PROPERTY_VALUE_MAX];
property_get("service.nvram_init", nvram_init_val, NULL);
if (strcmp(nvram_init_val, "Ready") == 0 || strcmp(nvram_init_val, "Pre_Ready") == 0)
{
break;
}
ms2 = getMs();
if((ms2-ms1)>3000)
{
logE("error demomn %d ms, timeout", ms2-ms1);
break;
}
usleep(100*1000);
}
if(mAndroidMode==0)
{
rNvramFileID = NVM_GetFileDesc(i4FileInfo, &i4RecSize, &i4RecNum, ISREAD);
if (rNvramFileID.iFileDesc == INVALID_HANDLE_VALUE) {
NVRAM_DRV_ERR("readNvramData(): create NVRAM file fail\n");
return NVRAM_CAMERA_FILE_ERROR;
}
if (a_eSensorType == DUAL_CAMERA_MAIN_SECOND_SENSOR) {
lseek(rNvramFileID.iFileDesc, i4RecSize, SEEK_SET);
}
if (a_eSensorType == DUAL_CAMERA_SUB_SENSOR) {
lseek(rNvramFileID.iFileDesc, i4RecSize*2, SEEK_SET);
}
read(rNvramFileID.iFileDesc, a_pNvramData, i4RecSize);
NVM_CloseFileDesc(rNvramFileID);
}
else
{
int sh=0;
if (a_eSensorType == DUAL_CAMERA_SUB_SENSOR)
sh=2;
else if (a_eSensorType == DUAL_CAMERA_MAIN_SECOND_SENSOR)
sh=1;
int ret;
ret = binderReadNvram(i4FileInfo, a_pNvramData, sh);
}
#endif
unsigned char* dd;
dd = (unsigned char*)a_pNvramData;
NVRAM_DRV_LOG("[readNvramData]- %d %d %d %d %d %d %d %d %d %d",
(int)dd[0], (int)dd[1], (int)dd[2], (int)dd[3], (int)dd[4],
(int)dd[5], (int)dd[6], (int)dd[7], (int)dd[8], (int)dd[9]);
return NVRAM_NO_ERROR;
}
/*******************************************************************************
*
********************************************************************************/
int
NvramDrv::writeNvramData(
CAMERA_DUAL_CAMERA_SENSOR_ENUM a_eSensorType,
CAMERA_DATA_TYPE_ENUM a_eNvramDataType,
void *a_pNvramData
)
{
F_ID rNvramFileID;
int i4FileInfo;
int i4RecSize;
int i4RecNum;
NVRAM_DRV_LOG("[writeNvramData]+ a_eSensorType=%d a_eNvramDataType=%d", a_eSensorType, a_eNvramDataType);
unsigned char* dd;
dd = (unsigned char*)a_pNvramData;
NVRAM_DRV_LOG("[writeNvramData] %d %d %d %d %d %d %d %d %d %d",
(int)dd[0], (int)dd[1], (int)dd[2], (int)dd[3], (int)dd[4],
(int)dd[5], (int)dd[6], (int)dd[7], (int)dd[8], (int)dd[9]);
if(a_eNvramDataType==CAMERA_NVRAM_DATA_SHADING)
{
//int NvramDrv::readMultiNvram(void* buf, int bufSz, int* idList, int num, int dev)
int idList[]=
{
AP_CFG_RDCL_CAMERA_SHADING_LID,
AP_CFG_RDCL_CAMERA_SHADING2_LID,
AP_CFG_RDCL_CAMERA_SHADING3_LID,
AP_CFG_RDCL_CAMERA_SHADING4_LID,
AP_CFG_RDCL_CAMERA_SHADING5_LID,
AP_CFG_RDCL_CAMERA_SHADING6_LID,
AP_CFG_RDCL_CAMERA_SHADING7_LID,
AP_CFG_RDCL_CAMERA_SHADING8_LID,
AP_CFG_RDCL_CAMERA_SHADING9_LID,
AP_CFG_RDCL_CAMERA_SHADING10_LID,
AP_CFG_RDCL_CAMERA_SHADING11_LID,
AP_CFG_RDCL_CAMERA_SHADING12_LID,
};
int err;
err = writeMultiNvram(a_pNvramData, sizeof(ISP_SHADING_STRUCT), idList, 12, a_eSensorType);
return err;
}
else if(a_eNvramDataType==CAMERA_DATA_AE_PLINETABLE)
{
//int NvramDrv::readMultiNvram(void* buf, int bufSz, int* idList, int num, int dev)
int idList[]=
{
AP_CFG_RDCL_CAMERA_PLINE_LID,
AP_CFG_RDCL_CAMERA_PLINE2_LID,
AP_CFG_RDCL_CAMERA_PLINE3_LID,
AP_CFG_RDCL_CAMERA_PLINE4_LID,
AP_CFG_RDCL_CAMERA_PLINE5_LID,
AP_CFG_RDCL_CAMERA_PLINE6_LID,
AP_CFG_RDCL_CAMERA_PLINE7_LID,
AP_CFG_RDCL_CAMERA_PLINE8_LID,
AP_CFG_RDCL_CAMERA_PLINE9_LID,
AP_CFG_RDCL_CAMERA_PLINE10_LID,
AP_CFG_RDCL_CAMERA_PLINE11_LID,
AP_CFG_RDCL_CAMERA_PLINE12_LID,
};
int err;
err = writeMultiNvram(a_pNvramData, sizeof(AE_PLINETABLE_T), idList, 12, a_eSensorType);
return err;
}
switch (a_eNvramDataType) {
case CAMERA_NVRAM_DATA_ISP:
i4FileInfo = AP_CFG_RDCL_CAMERA_PARA_LID;
break;
case CAMERA_NVRAM_DATA_3A:
i4FileInfo = AP_CFG_RDCL_CAMERA_3A_LID;
break;
case CAMERA_NVRAM_DATA_SHADING:
i4FileInfo = AP_CFG_RDCL_CAMERA_SHADING_LID;
break;
case CAMERA_NVRAM_DATA_LENS:
i4FileInfo = AP_CFG_RDCL_CAMERA_LENS_LID;
break;
case CAMERA_NVRAM_DATA_STROBE:
i4FileInfo = AP_CFG_RDCL_CAMERA_DEFECT_LID;
break;
case CAMERA_NVRAM_DATA_FEATURE:
i4FileInfo = AP_CFG_RDCL_CAMERA_FEATURE_LID;
break;
case CAMERA_NVRAM_DATA_GEOMETRY:
i4FileInfo = AP_CFG_RDCL_CAMERA_GEOMETRY_LID;
break;
case CAMERA_DATA_AE_PLINETABLE:
i4FileInfo = AP_CFG_RDCL_CAMERA_PLINE_LID;
break;
case CAMERA_NVRAM_VERSION:
a_eSensorType = DUAL_CAMERA_MAIN_SENSOR;
i4FileInfo = AP_CFG_RDCL_CAMERA_VERSION_LID;
break;
default:
NVRAM_DRV_ERR("writeNvramData(): incorrect data type\n");
return NVRAM_WRITE_PARAMETER_ERROR;
break;
}
#ifdef NVRAM_SUPPORT
int ms1;
int ms2;
ms1 = getMs();
while(1)
{
char nvram_init_val[PROPERTY_VALUE_MAX];
property_get("service.nvram_init", nvram_init_val, NULL);
if (strcmp(nvram_init_val, "Ready") == 0 || strcmp(nvram_init_val, "Pre_Ready") == 0)
{
break;
}
ms2 = getMs();
if((ms2-ms1)>3000)
{
logE("error demomn %d ms, timeout", ms2-ms1);
break;
}
usleep(100*1000);
}
if(mAndroidMode==0)
{
rNvramFileID = NVM_GetFileDesc(i4FileInfo, &i4RecSize, &i4RecNum, ISWRITE);
if (rNvramFileID.iFileDesc == INVALID_HANDLE_VALUE) {
NVRAM_DRV_ERR("writeNvramData(): create NVRAM file fail\n");
return NVRAM_CAMERA_FILE_ERROR;
}
if (a_eSensorType == DUAL_CAMERA_MAIN_SECOND_SENSOR) {
lseek(rNvramFileID.iFileDesc, i4RecSize, SEEK_SET);
}
if (a_eSensorType == DUAL_CAMERA_SUB_SENSOR) {
lseek(rNvramFileID.iFileDesc, i4RecSize*2, SEEK_SET);
}
write(rNvramFileID.iFileDesc, a_pNvramData, i4RecSize);
NVM_CloseFileDesc(rNvramFileID);
}
else
{
int sh=0;
if (a_eSensorType == DUAL_CAMERA_SUB_SENSOR)
sh=2;
else if (a_eSensorType == DUAL_CAMERA_MAIN_SECOND_SENSOR)
sh=1;
int ret;
ret = binderWriteNvram(i4FileInfo, a_pNvramData, sh);
}
#endif
NVRAM_DRV_LOG("[writeNvramData]-");
return NVRAM_NO_ERROR;
}
/*******************************************************************************
*
********************************************************************************/
int
NvramDrv::readDefaultData(
CAMERA_DUAL_CAMERA_SENSOR_ENUM a_eSensorType,
unsigned long a_u4SensorID,
CAMERA_DATA_TYPE_ENUM a_eNvramDataType,
void *a_pNvramData
)
{
// static bool bCustomInit = 0; //[ALPS00424402] [CCT6589] Len shading page --> Save to NVRAM --> CCT reboot failed
NVRAM_DRV_LOG("[readDefaultData] sensor ID = %ld; NVRAM data type = %d\n", a_u4SensorID, a_eNvramDataType);
#ifdef NVRAM_SUPPORT
if (!bCustomInit) {
cameraCustomInit();
if((a_eSensorType==DUAL_CAMERA_MAIN_2_SENSOR) || (a_eSensorType==DUAL_CAMERA_MAIN_SECOND_SENSOR))
LensCustomInit(8);
else
LensCustomInit((unsigned int)a_eSensorType);
bCustomInit = 1;
}
switch (a_eNvramDataType) {
case CAMERA_NVRAM_DATA_ISP:
GetCameraDefaultPara(a_u4SensorID, (PNVRAM_CAMERA_ISP_PARAM_STRUCT)a_pNvramData,NULL,NULL,NULL);
break;
case CAMERA_NVRAM_DATA_3A:
GetCameraDefaultPara(a_u4SensorID, NULL,(PNVRAM_CAMERA_3A_STRUCT)a_pNvramData,NULL,NULL);
break;
case CAMERA_NVRAM_DATA_SHADING:
GetCameraDefaultPara(a_u4SensorID, NULL,NULL,(PNVRAM_CAMERA_SHADING_STRUCT)a_pNvramData,NULL);
break;
case CAMERA_NVRAM_DATA_LENS:
GetLensDefaultPara((PNVRAM_LENS_PARA_STRUCT)a_pNvramData);
{
PNVRAM_LENS_PARA_STRUCT pLensNvramData = (PNVRAM_LENS_PARA_STRUCT)a_pNvramData;
pLensNvramData->Version = NVRAM_CAMERA_LENS_FILE_VERSION;
}
break;
case CAMERA_DATA_AE_PLINETABLE:
GetCameraDefaultPara(a_u4SensorID, NULL,NULL,NULL,(PAE_PLINETABLE_STRUCT)a_pNvramData);
break;
case CAMERA_NVRAM_DATA_STROBE:
int ret;
ret = cust_fillDefaultStrobeNVRam(a_eSensorType, a_pNvramData);
break;
case CAMERA_DATA_TSF_TABLE:
if (0 != GetCameraTsfDefaultTbl(a_u4SensorID, (PCAMERA_TSF_TBL_STRUCT)a_pNvramData))
{
return NVRAM_DEFAULT_DATA_READ_ERROR;
}
break;
case CAMERA_NVRAM_DATA_FEATURE:
//NVRAM_DRV_LOG("[readDefaultData] feature line=%d",__LINE__);
GetCameraFeatureDefault(a_u4SensorID, (NVRAM_CAMERA_FEATURE_STRUCT*)a_pNvramData);
break;
default:
break;
}
#endif
return NVRAM_NO_ERROR;
}
int nvGetFlickerPara(MUINT32 SensorId, int SensorMode, void* buf)
{
NVRAM_DRV_LOG("nvGetFlickerPara id=%d mode=%d", SensorId, SensorMode);
int err;
err = msdkGetFlickerPara(SensorId, SensorMode, buf);
if(err!=0)
NVRAM_DRV_LOG("nvGetFlickerPara error:=%d", err);
return err;
}
int binderGetNvramDisc(int file_lid, int& rec_size, int& rec_num)
{
//ALOGD("%s(), file_lid = %d, pBuf = %p, gUseBinderToAccessNVRam = %d", __FUNCTION__, file_lid, pBuf, gUseBinderToAccessNVRam);
//int rec_size = 0;
//int rec_num = 0;
NvRAMAgentClient *NvRAMClient = NvRAMAgentClient::create();
if (NvRAMClient == NULL)
{
ALOGE("%s(), NvRAMClient == NULL", __FUNCTION__);
return -1;
}
else
{
int result;
result = NvRAMClient->getFileDesSize(file_lid, rec_size, rec_num);
delete NvRAMClient;
if(result==0)
return -1;
else
return 0;
}
}
int binderReadNvram(int file_lid, void *pBuf, int sh)
{
//reference code:
//alps\mediatek\external\audiocustparam\AudioCustParam.cpp
//audioReadNVRamFile ()
//audioWriteNVRamFile()
logI("%s(), file_lid = %d, pBuf = %p sh=%d", __FUNCTION__, file_lid, pBuf, sh);
int ret;
int rec_size;
int rec_num;
ret = binderGetNvramDisc(file_lid, rec_size, rec_num);
if(ret!=0)
{
logE("binderGetNvramDisc");
return -1;
}
logI("file_lid = %d, rec_size=%d rec_num=%d", file_lid, rec_size, rec_num);
if (pBuf == NULL)
{
logE("%s(), pBuf == NULL, return 0", __FUNCTION__);
return -1;
}
int result = 0;
int read_size = 0;
NvRAMAgentClient *NvRAMClient = NvRAMAgentClient::create();
if (NvRAMClient == NULL)
{
logE("%s(), NvRAMClient == NULL", __FUNCTION__);
result = -1;
}
else
{
char *data = NvRAMClient->readFile(file_lid, read_size);
if (data == NULL)
{
logE("%s(), data == NULL", __FUNCTION__);
result = -1;
}
else
{
if(rec_size*rec_num!=read_size)
{
logE("size is not same read_size=%d", read_size);
result = -1;
}
else
{
logI("%s(), data = %p, read_size = %d", __FUNCTION__, data, read_size);
memcpy(pBuf, data+rec_size*sh, rec_size);
free(data);
result = 0;
}
}
delete NvRAMClient;
}
return result;
}
int binderWriteNvram(int file_lid, void *pBuf, int sh)
{
logI("%s() file_lid = %d, pBuf = %p, sh=%d", __FUNCTION__, file_lid, pBuf, sh);
logI("%s() buf[0]=%d", __FUNCTION__, (((int*)pBuf)[0]));
int ret;
int rec_size;
int rec_num;
ret = binderGetNvramDisc(file_lid, rec_size, rec_num);
if(ret!=0)
{
logE("binderGetNvramDisc");
return -1;
}
logI("file_lid = %d, rec_size=%d rec_num=%d", file_lid, rec_size, rec_num);
if (pBuf == NULL)
{
logE("%s(), pBuf == NULL, return 0", __FUNCTION__);
return -1;
}
int result = 0;
int write_size = 0;
NvRAMAgentClient *NvRAMClient = NvRAMAgentClient::create();
if (NvRAMClient == NULL)
{
logE("%s(), NvRAMClient == NULL", __FUNCTION__);
return -1;
}
else
{
write_size = NvRAMClient->writeFileEx(file_lid, sh, rec_size, (char *)pBuf);
delete NvRAMClient;
}
logI("%s() writeSize=%d", __FUNCTION__, write_size);
return 0;
}
int NvramDrv::writeNvramReal(void* buf, int id, int dev)
{
logI("writeNvramReal %p %d %d", buf, id, dev);
F_ID rNvramFileID;
int i4RecSize;
int i4RecNum;
#ifdef NVRAM_SUPPORT
if(mAndroidMode==0)
{
rNvramFileID = NVM_GetFileDesc(id, &i4RecSize, &i4RecNum, ISWRITE);
if (rNvramFileID.iFileDesc == INVALID_HANDLE_VALUE) {
NVRAM_DRV_ERR("writeNvramData(): create NVRAM file fail\n");
return NVRAM_CAMERA_FILE_ERROR;
}
if (dev == DUAL_CAMERA_MAIN_SECOND_SENSOR) {
lseek(rNvramFileID.iFileDesc, i4RecSize, SEEK_SET);
}
if (dev == DUAL_CAMERA_SUB_SENSOR) {
lseek(rNvramFileID.iFileDesc, i4RecSize*2, SEEK_SET);
}
write(rNvramFileID.iFileDesc, buf, i4RecSize);
NVM_CloseFileDesc(rNvramFileID);
}
else
{
int sh=0;
if (dev == DUAL_CAMERA_SUB_SENSOR)
sh=2;
else if (dev == DUAL_CAMERA_MAIN_SECOND_SENSOR)
sh=1;
int ret;
ret = binderWriteNvram(id, buf, sh);
}
#endif
logI("writeNvramReal-");
return 0;
}
int NvramDrv::readNvramReal(void* buf, int id, int dev)
{
logI("readNvramReal %p %d %d", buf, id, dev);
F_ID rNvramFileID;
//int i4FileInfo;
int i4RecSize;
int i4RecNum;
//seanlin 121221 avoid camera has not inited>
//[ALPS00424402] [CCT6589] Len shading page --> Save to NVRAM --> CCT reboot failed
if (!bCustomInit) {
cameraCustomInit();
if((dev==DUAL_CAMERA_MAIN_2_SENSOR) || (dev==DUAL_CAMERA_MAIN_SECOND_SENSOR))
LensCustomInit(8);
else
LensCustomInit((unsigned int)dev);
bCustomInit = 1;
}
//[ALPS00424402] [CCT6589] Len shading page --> Save to NVRAM --> CCT reboot failed
//seanlin 121221 avoid camera has not inited<
#ifdef NVRAM_SUPPORT
if(mAndroidMode==0)
{
rNvramFileID = NVM_GetFileDesc(id, &i4RecSize, &i4RecNum, ISREAD);
if (rNvramFileID.iFileDesc == INVALID_HANDLE_VALUE) {
NVRAM_DRV_ERR("readNvramData(): create NVRAM file fail\n");
return NVRAM_CAMERA_FILE_ERROR;
}
if (dev == DUAL_CAMERA_MAIN_SECOND_SENSOR) {
lseek(rNvramFileID.iFileDesc, i4RecSize, SEEK_SET);
}
if (dev == DUAL_CAMERA_SUB_SENSOR) {
lseek(rNvramFileID.iFileDesc, i4RecSize*2, SEEK_SET);
}
read(rNvramFileID.iFileDesc, buf, i4RecSize);
NVM_CloseFileDesc(rNvramFileID);
}
else
{
int sh=0;
if (dev == DUAL_CAMERA_SUB_SENSOR)
sh=2;
else if (dev == DUAL_CAMERA_MAIN_SECOND_SENSOR)
sh=1;
int ret;
ret = binderReadNvram(id, buf, sh);
}
#endif
logI("readNvramReal-");
return 0;
}
//i4FileInfo
//a_pNvramData
#define NV_REC_SZ 80000
int NvramDrv::readMultiNvram(void* buf, int bufSz, int* idList, int num, int dev)
{
if(num*NV_REC_SZ<bufSz)
logE("bufSz=%d readSize=%d (%dx%d)",bufSz, num*NV_REC_SZ, num, NV_REC_SZ);
int restSz=bufSz;
char* pCpBuf;
int cpSz;
int i;
char* b;
b = new char [NV_REC_SZ];
pCpBuf = (char*)buf;
for(i=0;i<num;i++)
{
if(restSz<=0)
break;
readNvramReal(b, idList[i], dev);
if(restSz>NV_REC_SZ)
cpSz = NV_REC_SZ;
else
cpSz = restSz;
memcpy(pCpBuf, b, cpSz);
pCpBuf += cpSz;
restSz-=cpSz;
}
delete []b;
return 0;
}
int NvramDrv::writeMultiNvram(void* buf, int bufSz, int* idList, int num, int dev)
{
if(num*NV_REC_SZ<bufSz)
logE("bufSz=%d readSize=%d (%dx%d)",bufSz, num*NV_REC_SZ, num, NV_REC_SZ);
int restSz=bufSz;
char* pCpBuf;
int cpSz;
int i;
char* b;
b = new char [NV_REC_SZ];
pCpBuf = (char*)buf;
for(i=0;i<num;i++)
{
if(restSz<=0)
break;
if(restSz>NV_REC_SZ)
cpSz = NV_REC_SZ;
else
cpSz = restSz;
memcpy(b, pCpBuf, cpSz);
writeNvramReal(b, idList[i], dev);
pCpBuf += cpSz;
restSz-=cpSz;
}
delete []b;
return 0;
}
| [
"[email protected]"
] | |
35e376aeb213acf03317714d0c725ef3d4465305 | 3422d206b07e4e47fe524ce543786bea6e1dda26 | /test/meta.cpp | 20a3cfdd432eb5dc725a6bf004f7fd32f6c6b337 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | arximboldi/zug | f085dc17e40f30227934eb8699cbe7dcff2dfb09 | 1123bffd415a96013ab93d70338bcf5113f8607d | refs/heads/master | 2023-08-30T20:08:31.413273 | 2023-08-21T08:48:45 | 2023-08-21T08:48:45 | 199,628,697 | 213 | 25 | BSL-1.0 | 2023-08-21T08:48:47 | 2019-07-30T10:20:35 | C++ | UTF-8 | C++ | false | false | 2,028 | cpp | //
// zug: transducers for C++
// Copyright (C) 2019 Juan Pedro Bolivar Puente
//
// This software is distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt
//
#include <zug/meta.hpp>
#include <zug/util.hpp>
#include <catch2/catch.hpp>
using namespace zug;
TEST_CASE("output_of, identity")
{
using meta::pack;
using identity_t = decltype(identity);
static_assert(output_of_t<identity_t>{} == pack<>{}, "");
static_assert(output_of_t<identity_t, int>{} == pack<int&&>{}, "");
static_assert(
output_of_t<identity_t, int, float>{} == pack<int&&, float&&>{}, "");
static_assert(output_of_t<identity_t, meta::pack<int, float>>{} ==
pack<int&&, float&&>{},
"");
static_assert(output_of_t<identity_t, int&>{} == pack<int&>{}, "");
static_assert(output_of_t<identity_t, int&, const float&>{} ==
pack<int&, const float&>{},
"");
static_assert(output_of_t<identity_t, int&&>{} == pack<int&&>{}, "");
static_assert(output_of_t<identity_t, const int&&, float&&>{} ==
pack<const int&&, float&&>{},
"");
}
TEST_CASE("result_of, identity")
{
using meta::pack;
using identity_t = decltype(identity);
static_assert(pack<result_of_t<identity_t>>{} == pack<std::tuple<>>{}, "");
static_assert(pack<result_of_t<identity_t, int>>{} == pack<int>{}, "");
static_assert(pack<result_of_t<identity_t, int, float>>{} ==
pack<std::tuple<int, float>>{},
"");
static_assert(pack<result_of_t<identity_t, meta::pack<int, float>>>{} ==
pack<std::tuple<int, float>>{},
"");
static_assert(pack<result_of_t<identity_t, int&>>{} == pack<int>{}, "");
static_assert(pack<result_of_t<identity_t, int&, float&>>{} ==
pack<std::tuple<int, float>>{},
"");
}
| [
"[email protected]"
] | |
968abe92c2e277f9e7346faea1efe5d7b22366ee | 043f873d808df18dddee13f10c4d07e8ea81ef6e | /1000CppExercise/LearningQuangLibrary/file.cpp | 27f5fe390da7f451b8afecfd78437c52c2752866 | [] | no_license | nguyenviettien13/CodeLearning | 3e318e527601ad44f5fe99760fb6138ed48e3871 | 666bacd5d9a1023171f481a330712357236e0439 | refs/heads/master | 2021-09-25T02:30:40.795527 | 2018-10-16T16:01:46 | 2018-10-16T16:01:46 | 153,311,228 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39,790 | cpp | #include "string.h"
#include "file.h"
/************************************************************************/
/* Các phương thức lớp file */
/************************************************************************/
/*constructor*/ file::file(const std::wstring &fullFileName)
{
int flagDot = 0;
this->fileFullName = fullFileName;
for (int i = 0; i < (int)fullFileName.size(); i++)
{
this->fileRealName += fullFileName[i];
if (fullFileName[i] == L'\\' || fullFileName[i] == L'/')
{
flagDot = 0;
this->fileRealName.clear();
}
else if (fullFileName[i] == L'.')
{
flagDot = 1;
}
}
if (flagDot == 1)
{
for (int i = int(this->fileRealName.size()) - 1; i >= 0; i--)
{
if (this->fileRealName[i] == L'.')
{
this->fileExtensionName = this->fileRealName.substr(i + 1, this->fileRealName.size());
this->fileRealName.erase(i, this->fileRealName.size() - 1);
i = -1;
}
}
}
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
std::ifstream fileInputStream(this->fileFullName, std::ifstream::in | std::ifstream::binary);
#else
std::ifstream fileInputStream(GetString(this->fileFullName), std::ifstream::in | std::ifstream::binary);
#endif
if (fileInputStream.is_open())
{
fileInputStream.seekg(0, std::ios_base::end);
this->fileSize = fileInputStream.tellg();
fileInputStream.close();
}
else this->fileSize = 0;
}
bool file::Read(std::wstring &buffer)
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
std::ifstream fileInputStream(fileFullName, std::ifstream::in | std::ifstream::binary);
#else
std::ifstream fileInputStream(GetString(fileFullName), std::ifstream::in | std::ifstream::binary);
#endif
if (fileInputStream.is_open())
{
fileInputStream.seekg(0, std::ios_base::end);
this->fileSize = fileInputStream.tellg();
fileInputStream.seekg(0, std::ios_base::beg);
if (this->fileSize <= 4)
{
char* utf8data = new char[this->fileSize + 10];
memset(utf8data, 0, this->fileSize + 10);
fileInputStream.seekg(0, std::ios_base::beg);
fileInputStream.read(utf8data, this->fileSize);
buffer += GetWString(utf8data, fileSize);
delete[] utf8data;
fileInputStream.close();
return true;
}
bool flagValidateToRead = true;
char byteOrderMark1 = 0;
char byteOrderMark2 = 0;
char byteOrderMark3 = 0;
char byteOrderMark4 = 0;
fileInputStream.read(&byteOrderMark1, 1);
fileInputStream.read(&byteOrderMark2, 1);
fileInputStream.read(&byteOrderMark3, 1);
fileInputStream.read(&byteOrderMark4, 1);
fileInputStream.seekg(0, std::ios_base::beg);
if (byteOrderMark1 == (char)0xFE && byteOrderMark2 == (char)0xFF)
{//Unicode Big Endian
gui::Show(std::wstring(L"Lỗi"), L"Error: Unsupported encode (Unicode Big Endian) with %ls \n", fileFullName.c_str());
flagValidateToRead = false;
}
else if (byteOrderMark1 == (char)0x00 && byteOrderMark2 == (char)0x00 && byteOrderMark3 == (char)0xFE && byteOrderMark4 == (char)0xFF)
{//UTF-32 Big Endian
gui::Show(std::wstring(L"Lỗi"), L"Error: Unsupported encode (UTF-32 Big Endian) with %ls \n", fileFullName.c_str());
flagValidateToRead = false;
}
else if (byteOrderMark1 == (char)0xFF && byteOrderMark2 == (char)0xFE && byteOrderMark3 == (char)0x00 && byteOrderMark4 == (char)0x00)
{//UTF-32 Little Endian
gui::Show(std::wstring(L"Lỗi"), L"Error: Unsupported encode (UTF-32 Little Endian) with %ls \n", fileFullName.c_str());
flagValidateToRead = false;
}
else if ((byteOrderMark1 == (char)0x2B && byteOrderMark2 == (char)0x2F && byteOrderMark3 == (char)0x76))
{//UTF-7
gui::Show(std::wstring(L"Lỗi"), L"Error: Unsupported encode (UTF-7) with %ls \n", fileFullName.c_str());
flagValidateToRead = false;
}
else if (byteOrderMark1 == (char)0xFF && byteOrderMark2 == (char)0xFE)
{//Unicode Little Endian
wchar_t* unicodeData = new wchar_t[this->fileSize * 2 + 10];
memset(unicodeData, 0, this->fileSize * 2 + 10);
fileInputStream.seekg(2, std::ios_base::beg);
fileInputStream.read((char*)unicodeData, this->fileSize);
buffer += unicodeData;
delete[] unicodeData;
}
else if (byteOrderMark1 == (char)0xEF && byteOrderMark2 == (char)0xBB && byteOrderMark3 == (char)0xBF)
{//utf8
char* utf8data = new char[this->fileSize + 10];
memset(utf8data, 0, this->fileSize + 10);
fileInputStream.seekg(3, std::ios_base::beg);
fileInputStream.read(utf8data, this->fileSize);
buffer += GetWString(utf8data, fileSize);
delete[] utf8data;
}
else
{//utf-8 without BOM
char* utf8data = new char[this->fileSize + 10];
memset(utf8data, 0, this->fileSize + 10);
fileInputStream.seekg(0, std::ios_base::beg);
fileInputStream.read(utf8data, this->fileSize);
buffer += GetWString(utf8data, fileSize);
delete[] utf8data;
}
fileInputStream.close();
return flagValidateToRead;
}
else
{
gui::Show(std::wstring(L"Lỗi"), L"Error: Can not open file %ls \n", fileFullName.c_str());
return false;
}
}
bool file::Read(void* buffer, long long int bufferSize)
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
std::ifstream fileInputStream(fileFullName, std::ifstream::in | std::ifstream::binary);
#else
std::ifstream fileInputStream(GetString(fileFullName), std::ifstream::in | std::ifstream::binary);
#endif
if (fileInputStream.is_open())
{
fileInputStream.seekg(0, std::ios_base::end);
this->fileSize = fileInputStream.tellg();
fileInputStream.seekg(0, std::ios_base::beg);
long long int readSize = 0;
for (long long int i = 0; i < bufferSize; i += 1024)
{
if (bufferSize - readSize > 1024) fileInputStream.read((char*)buffer + i, 1024);
else fileInputStream.read((char*)buffer + i, bufferSize - readSize);
readSize += fileInputStream.gcount();
}
if (readSize != bufferSize)
{
gui::Show(L"Cảnh báo", L"Cảnh báo khi đọc file %ls (buffer size == %d bytes, read == %d bytes)\n", this->fileFullName.c_str(), bufferSize, readSize);
return false;
}
}
else
{
gui::Show(std::wstring(L"Lỗi"), L"Error: Can not open file %ls \n", fileFullName.c_str());
return false;
}
return true;
}
bool file::Write(const std::wstring &buffer, bool truncate)
{
for (auto i = 0u; i < fileFullName.size(); i++)
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
if (fileFullName[i] == L'\\') ::CreateDirectoryW(fileFullName.substr(0, i).c_str(), 0);
#else
int mkdir(const char *path, mode_t mode);
if (fileFullName[i] == L'/') mkdir(GetString(fileFullName.substr(0, i)).c_str(), 0777);
#endif
}
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
std::ofstream fileHandle(fileFullName, std::ios_base::out | std::ios_base::binary | (truncate ? std::ios_base::trunc : (std::ios_base::app | std::ios_base::ate)));
#else
std::ofstream fileHandle(GetString(fileFullName), std::ios_base::out | std::ios_base::binary | (truncate ? std::ios_base::trunc : (std::ios_base::app | std::ios_base::ate)));
#endif
if (fileHandle.is_open())
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
int buffUtf8Size = buffer.size() * 2 + 10;
char* buffUtf8 = new char[buffUtf8Size];
WideCharToMultiByte(CP_UTF8, 0, buffer.c_str(), -1, buffUtf8, buffUtf8Size, 0, 0);
int writeSize = strlen(buffUtf8);
long long int beforeWriteOffset = fileHandle.tellp();
fileHandle.write(buffUtf8, writeSize);
long long int affterWriteOffset = fileHandle.tellp();
long long int writtenSize = affterWriteOffset - beforeWriteOffset;
delete[] buffUtf8;
fileHandle.close();
#else
std::string bufferToWrite = GetString(buffer);
INT64 writeSize = bufferToWrite.size();
INT64 beforeWriteOffset = fileHandle.tellp();
fileHandle.write(bufferToWrite.c_str(), writeSize);
INT64 affterWriteOffset = fileHandle.tellp();
INT64 writtenSize = affterWriteOffset - beforeWriteOffset;
fileHandle.close();
#endif
if (writtenSize != writeSize)
{
gui::Show(std::wstring(L"Lỗi"), L"Error: write file %ls (utf8 size == %d bytes, write == %d bytes)\n", this->fileFullName, writeSize, writtenSize);
return false;
}
else return true;
}
else
{
gui::Show(std::wstring(L"Lỗi"), L"Error: Can not open to write file %ls \n", this->fileFullName);
return false;
}
return false;
}
bool file::Write(const void* buffer, long long int bufferSize, bool truncate)
{
for (auto i = 0u; i < fileFullName.size(); i++)
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
if (fileFullName[i] == L'\\') ::CreateDirectoryW(fileFullName.substr(0, i).c_str(), 0);
#else
int mkdir(const char *path, mode_t mode);
if (fileFullName[i] == L'/') mkdir(GetString(fileFullName.substr(0, i)).c_str(), 0777);
#endif
}
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
std::ofstream fileHandle(fileFullName, std::ios_base::out | std::ios_base::binary | (truncate ? std::ios_base::trunc : (std::ios_base::app | std::ios_base::ate)));
#else
std::ofstream fileHandle(GetString(fileFullName), std::ios_base::out | std::ios_base::binary | (truncate ? std::ios_base::trunc : (std::ios_base::app | std::ios_base::ate)));
#endif
if (fileHandle.is_open())
{
long long int beforeWriteOffset = fileHandle.tellp();
fileHandle.write((const char*)buffer, bufferSize);
long long int affterWriteOffset = fileHandle.tellp();
long long int writtenSize = affterWriteOffset - beforeWriteOffset;
long long int writeSize = bufferSize;
fileHandle.close();
if (writtenSize != writeSize)
{
gui::Show(std::wstring(L"Lỗi"), L"Error: write file %ls (buffer size == %d bytes, write == %d bytes)\n", fileFullName.c_str(), writeSize, writtenSize);
return false;
}
else return true;
}
else
{
gui::Show(std::wstring(L"Lỗi"), L"Error: Can not open to write file %ls \n", fileFullName.c_str());
return false;
}
return false;
}
bool file::Exist(void)const
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
return (GetFileAttributesW(fileFullName.c_str()) != INVALID_FILE_ATTRIBUTES);
#else
std::ifstream f(GetString(fileFullName));
return f.good();
#endif
}
long long int file::Size(void)const
{
return fileSize;
}
const std::wstring& file::Log(const wchar_t* format, ...)
{
if (format)
{
wchar_t buffer[20240 + 1000];
va_list args;
va_start(args, format);
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
_vsnwprintf_s(buffer, 20240, format, args);
#else
vswprintf(buffer, 10240, format, args);
#endif
va_end(args);
fileLog += buffer;
}
return fileLog;
}
const std::wstring& file::Log(const std::wstring &wstr)
{
fileLog += wstr;
return fileLog;
}
const std::wstring& file::LogWstr(const std::wstring &wstr)
{
fileLog += wstr;
return fileLog;
}
void file::WriteLog(const std::wstring &logFileName, bool truncate)
{
WriteFile(logFileName, Log(), truncate);
fileLog.clear();
}
const std::wstring& file::RealFileName(void)const
{
return fileRealName;
}
const std::wstring& file::ExtensionFileName(void)const
{
return fileExtensionName;
}
/************************************************************************/
/* Các phương thức tĩnh thao tác với file */
/************************************************************************/
bool file::ExistsFile(const std::wstring &fileName)
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
return (GetFileAttributesW(fileName.c_str()) != INVALID_FILE_ATTRIBUTES);
#else
std::ifstream f(GetString(fileName));
return f.good();
#endif
}
std::wstring file::ReadFile(const std::wstring &fileName)
{
std::wstring bufferContent;
ReadFile(fileName, bufferContent);
return bufferContent;
}
bool file::ReadFile(const std::wstring &fileName, std::wstring &buffer)
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
std::ifstream fileInputStream(fileName, std::ifstream::in | std::ifstream::binary);
#else
std::ifstream fileInputStream(GetString(fileName), std::ifstream::in | std::ifstream::binary);
#endif
if (fileInputStream.is_open())
{
fileInputStream.seekg(0, std::ios_base::end);
long long fileSize = fileInputStream.tellg();
fileInputStream.seekg(0, std::ios_base::beg);
if (fileSize <= 4)
{
char* utf8data = new char[fileSize + 10];
memset(utf8data, 0, fileSize + 10);
fileInputStream.seekg(0, std::ios_base::beg);
fileInputStream.read(utf8data, fileSize);
buffer += GetWString(utf8data, fileSize);
delete[] utf8data;
fileInputStream.close();
return true;
}
bool flagValidateToRead = true;
char byteOrderMark1 = 0;
char byteOrderMark2 = 0;
char byteOrderMark3 = 0;
char byteOrderMark4 = 0;
fileInputStream.read(&byteOrderMark1, 1);
fileInputStream.read(&byteOrderMark2, 1);
fileInputStream.read(&byteOrderMark3, 1);
fileInputStream.read(&byteOrderMark4, 1);
fileInputStream.seekg(0, std::ios_base::beg);
if (byteOrderMark1 == (char)0xFE && byteOrderMark2 == (char)0xFF)
{//Unicode Big Endian
gui::Show(std::wstring(L"Lỗi"), L"Error: Unsupported encode (Unicode Big Endian) with %ls \n", fileName.c_str());
flagValidateToRead = false;
}
else if (byteOrderMark1 == (char)0x00 && byteOrderMark2 == (char)0x00 && byteOrderMark3 == (char)0xFE && byteOrderMark4 == (char)0xFF)
{//UTF-32 Big Endian
gui::Show(std::wstring(L"Lỗi"), L"Error: Unsupported encode (UTF-32 Big Endian) with %ls \n", fileName.c_str());
flagValidateToRead = false;
}
else if (byteOrderMark1 == (char)0xFF && byteOrderMark2 == (char)0xFE && byteOrderMark3 == (char)0x00 && byteOrderMark4 == (char)0x00)
{//UTF-32 Little Endian
gui::Show(std::wstring(L"Lỗi"), L"Error: Unsupported encode (UTF-32 Little Endian) with %ls \n", fileName.c_str());
flagValidateToRead = false;
}
else if ((byteOrderMark1 == (char)0x2B && byteOrderMark2 == (char)0x2F && byteOrderMark3 == (char)0x76))
{//UTF-7
gui::Show(std::wstring(L"Lỗi"), L"Error: Unsupported encode (UTF-7) with %ls \n", fileName.c_str());
flagValidateToRead = false;
}
else if (byteOrderMark1 == (char)0xFF && byteOrderMark2 == (char)0xFE)
{//Unicode Little Endian
wchar_t* unicodeData = new wchar_t[fileSize * 2 + 10];
memset(unicodeData, 0, fileSize * 2 + 10);
fileInputStream.seekg(2, std::ios_base::beg);
fileInputStream.read((char*)unicodeData, fileSize);
buffer += unicodeData;
delete[] unicodeData;
}
else if (byteOrderMark1 == (char)0xEF && byteOrderMark2 == (char)0xBB && byteOrderMark3 == (char)0xBF)
{//utf8
char* utf8data = new char[fileSize + 10];
memset(utf8data, 0, fileSize + 10);
fileInputStream.seekg(3, std::ios_base::beg);
fileInputStream.read(utf8data, fileSize);
buffer += GetWString(utf8data, fileSize);
delete[] utf8data;
}
else
{//utf-8 without BOM
char* utf8data = (char*)calloc(fileSize + 10, sizeof(char));
if (utf8data)
{
fileInputStream.seekg(0, std::ios_base::beg);
fileInputStream.read(utf8data, fileSize);
buffer += GetWString(utf8data, fileSize);
free(utf8data);
}
else
{
gui::Show(std::wstring(L"Lỗi"), L"Can not malloc to open file %ls \n", fileName.c_str());
}
}
fileInputStream.close();
return flagValidateToRead;
}
else
{
gui::Show(std::wstring(L"Lỗi"), L"Error: Can not open file %ls \n", fileName.c_str());
return false;
}
}
void file::ReadFile(const std::wstring &fileName, std::wstringset &bufferLineSet)
{
Split(file::ReadFile(fileName), bufferLineSet, L'\n');
}
void file::ReadFile(const std::wstring &fileName, std::wstringlist &bufferLineList)
{
Split(file::ReadFile(fileName), bufferLineList, L'\n');
}
void file::ReadFileBinary(const std::wstring &fileName, void* buffer, INT64 buffersize)
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
std::ifstream fileInputStream(fileName, std::ifstream::in | std::ifstream::binary);
#else
std::ifstream fileInputStream(GetString(fileName), std::ifstream::in | std::ifstream::binary);
#endif
if (fileInputStream.is_open())
{
fileInputStream.seekg(0, std::ios_base::end);
long long int currentFileSize = fileInputStream.tellg();
memset(buffer, 0, buffersize);
if (buffersize > currentFileSize) buffersize = currentFileSize;
fileInputStream.seekg(0, std::ios_base::beg);
for (int i = 0; i < buffersize; i += 1024)
{
int currentStepReadSize = buffersize - i;
if (currentStepReadSize > 1024) currentStepReadSize = 1024;
fileInputStream.read((char*)buffer + i, currentStepReadSize);
}
fileInputStream.close();
}
}
bool file::ReadFileSubSegment(const std::wstring &fileName, void * buffer, long long int offset, long long int length)
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
std::ifstream fileInputStream(fileName, std::ifstream::in | std::ifstream::binary);
#else
std::ifstream fileInputStream(GetString(fileName), std::ifstream::in | std::ifstream::binary);
#endif
if (fileInputStream.is_open())
{
fileInputStream.seekg(0, std::ios_base::end);
long long int currentFileSize = fileInputStream.tellg();
memset(buffer, 0, length);
if (offset > currentFileSize)
{
gui::Show(L"Lỗi", L"Lỗi ReadFileSubSegment (offset > currentFileSize) filename=%s,offset=%ld,currentFileSize=%ld", fileName.c_str(), offset, currentFileSize);
}
if (offset + length > currentFileSize) length = currentFileSize - offset;
long long int readSize = 0;
if (length > 0 && offset < currentFileSize && offset + length <= currentFileSize)
{
fileInputStream.seekg(offset, std::ios_base::beg);
for (int i = 0; i < length; i += 1024)
{
long long currentStepReadSize = length - i;
if (currentStepReadSize > 1024) currentStepReadSize = 1024;
fileInputStream.read((char*)buffer + i, currentStepReadSize);
readSize += fileInputStream.gcount();
}
}
fileInputStream.close();
if (readSize == length) return true;
else
{
gui::Show(L"Lỗi", L"Lỗi ReadFileSubSegment filename=%s,offset=%ld,length=%ld", fileName.c_str(), offset, length);
return false;
}
}
return false;
}
void file::ReadFile(const std::wstring &fileName, std::wstringintmap& dataMap)
{
std::wstringlist dataLineList;
file::ReadFile(fileName, dataLineList);
for (auto iLine = dataLineList.begin(); iLine != dataLineList.end(); iLine++)
{
std::wstringlist contentList;
Split(*iLine, contentList, L'\t');
if (contentList.size() == 2)
{
auto iContent = contentList.begin();
std::wstring fistValue = *iContent;
iContent++;
dataMap[fistValue] = GetFirstInt(*iContent);
}
}
}
void file::ReadFileLine(const std::wstring &fileName, std::wstringlist& bufferLineList/*delim is \r and \n*/, bool getEmptyLine /*= false*/)
{
std::wstring bufferContent;
file::ReadFile(fileName, bufferContent);
Split(bufferContent, bufferLineList, L'\n', getEmptyLine);
bufferContent.clear();
}
void file::ReadFileSyllable(const std::wstring &fileName, std::wstringlist& bufferSyllableList/*delim is space and \r and \n*/)
{
std::wstring bufferContent;
file::ReadFile(fileName, bufferContent);
Split(bufferContent, bufferSyllableList, L' ');
bufferContent.clear();
}
void file::ReadFileSyllable(const std::wstring &fileName, std::wstringset& bufferSyllableSet/*delim is space and \r and \n*/)
{
std::wstring bufferContent;
file::ReadFile(fileName, bufferContent);
Split(bufferContent, bufferSyllableSet, L' ');
bufferContent.clear();
}
void file::WriteFile(const std::wstring &fileName, const std::wstring &wstr, bool truncate)
{
for (auto i = 0u; i < fileName.size(); i++)
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
if (fileName[i] == L'\\') ::CreateDirectoryW(fileName.substr(0, i).c_str(), 0);
#else
int mkdir(const char *path, mode_t mode);
if (fileName[i] == L'/') mkdir(GetString(fileName.substr(0, i)).c_str(), 0777);
#endif
}
if (truncate) file::DeleteFile(fileName);
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
std::ofstream fileHandle(fileName, std::ios_base::out | std::ios_base::binary | (truncate ? std::ios_base::trunc : (std::ios_base::app | std::ios_base::ate)));
#else
std::ofstream fileHandle(GetString(fileName), std::ios_base::out | std::ios_base::binary | (truncate ? std::ios_base::trunc : (std::ios_base::app | std::ios_base::ate)));
#endif
if (fileHandle.is_open())
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
int buffUtf8Size = wstr.size() * 2 + 10;
char* buffUtf8 = new char[buffUtf8Size];
memset(buffUtf8, 0, buffUtf8Size);
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), wstr.size(), buffUtf8, buffUtf8Size, 0, 0);
fileHandle.write(buffUtf8, strlen(buffUtf8));
fileHandle.close();
delete[] buffUtf8;
#else
std::string bufferToWrite = GetString(wstr);
INT64 writeSize = bufferToWrite.size();
INT64 beforeWriteOffset = fileHandle.tellp();
fileHandle.write(bufferToWrite.c_str(), writeSize);
INT64 affterWriteOffset = fileHandle.tellp();
INT64 writtenSize = affterWriteOffset - beforeWriteOffset;
fileHandle.close();
if (writtenSize != writeSize)
{
gui::Show(std::wstring(L"Lỗi"), L"Error: write file %ls (utf8 size == %d bytes, write == %d bytes)\n", fileName.c_str(), writeSize, writtenSize);
//return false;
}
//else return true;
#endif
}
else
{
gui::Show(std::wstring(L"Lỗi"), L"Error: Can not open to write file %ls \n", fileName.c_str());
}
}
void file::WriteFile(const std::wstring &fileName, void* buffer, long long int buffersize, bool truncate)
{
for (unsigned int i = 0; i < fileName.size(); i++)
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
if (fileName[i] == L'\\') ::CreateDirectoryW(fileName.substr(0, i).c_str(), 0);
#else
int mkdir(const char *path, mode_t mode);
if (fileName[i] == L'/') mkdir(GetString(fileName.substr(0, i)).c_str(), 0777);
#endif
}
if (truncate) file::DeleteFile(fileName);
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
std::ofstream fileHandle(fileName, std::ios_base::out | std::ios_base::binary | (truncate ? std::ios_base::trunc : (std::ios_base::app | std::ios_base::ate)));
#else
std::ofstream fileHandle(GetString(fileName), std::ios_base::out | std::ios_base::binary | (truncate ? std::ios_base::trunc : (std::ios_base::app | std::ios_base::ate)));
#endif
if (fileHandle.is_open())
{
fileHandle.write((char*)buffer, buffersize);
fileHandle.close();
}
}
void file::WriteFile(const std::wstring &fileName, const std::wstringset& lineSet)
{
std::wstring bufferToWrite;
for (auto iline = lineSet.begin(); iline != lineSet.end(); iline++)
{
bufferToWrite += *iline;
bufferToWrite += L'\n';
}
file::WriteFile(fileName, bufferToWrite, true);
}
void file::WriteFile(const std::wstring &fileName, const std::vnwstringset& lineSet)
{
std::wstring bufferToWrite;
for (auto iline = lineSet.begin(); iline != lineSet.end(); iline++)
{
bufferToWrite += *iline;
bufferToWrite += L'\n';
}
file::WriteFile(fileName, bufferToWrite, true);
}
void file::WriteFile(const std::wstring &fileName, const std::wstringintmap& dataMap)
{
std::wstring bufferToWrite;
file::WriteFile(fileName, bufferToWrite, true);
for (auto iline = dataMap.begin(); iline != dataMap.end(); iline++)
{
bufferToWrite += iline->first;
bufferToWrite += L'\t';
bufferToWrite += iline->second;
bufferToWrite += L'\n';
if (bufferToWrite.size() > 1000000)
{
file::WriteFile(fileName, bufferToWrite, false);
bufferToWrite.clear();
}
}
file::WriteFile(fileName, bufferToWrite, false);
}
void file::WriteFile(const std::wstring &fileName, const std::vnwstringintmap& dataMap)
{
std::wstring bufferToWrite;
for (auto iline = dataMap.begin(); iline != dataMap.end(); iline++)
{
bufferToWrite += iline->first;
bufferToWrite += L'\t';
bufferToWrite += iline->second;
bufferToWrite += L'\n';
}
file::WriteFile(fileName, bufferToWrite, true);
}
void file::WriteFile(const std::wstring &fileName, const std::wstringdoublemap& dataMap)
{
file dataFile;
for (auto idata = dataMap.begin(); idata != dataMap.end(); idata++)
{
dataFile.Log(L"%ls %lf\n", idata->first.c_str(), idata->second);
}
dataFile.WriteLog(fileName, true);
}
void file::WriteFile(const std::wstring &fileName, const std::wstringmap& dataMap)
{
file dataFile;
for (auto idata = dataMap.begin(); idata != dataMap.end(); idata++)
{
dataFile.Log(L"%ls %ls\n", idata->first.c_str(), idata->second.c_str());
}
dataFile.WriteLog(fileName, true);
}
void file::DeleteFile(const std::wstring &fileName)
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
::DeleteFileW(fileName.c_str());
#else
remove(GetString(fileName).c_str());
#endif
}
void file::GetRealFileName(const std::wstring &filePath, std::wstring &rFilename)
{
rFilename.clear();
for (auto i = 0u; i < filePath.size(); i++)
{
if (filePath[i] == L'\\' || filePath[i] == L'/') rFilename.clear();
else rFilename += filePath[i];
}
auto pos = rFilename.find(L'.');
if (pos != std::wstring::npos) rFilename.erase(pos, rFilename.size() - pos);
}
std::wstring file::GetRealFileName(const std::wstring &filePath)
{
std::wstring rFilename;
file::GetRealFileName(filePath, rFilename);
return rFilename;
}
void file::GetExtensionFileName(const std::wstring &filePath, std::wstring &eFilename)
{
eFilename.clear();
for (auto i = 0u; i < filePath.size(); i++)
{
if (filePath[i] == L'\\' || filePath[i] == L'/') eFilename.clear();
else eFilename += filePath[i];
}
auto pos = eFilename.find(L'.');
if (pos != std::wstring::npos) eFilename.erase(0, pos + 1);
}
std::wstring file::GetCurrentFolderName(void)
{
std::wstring currentFolder;
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
wchar_t currentFolderBuffer[10000] = { 0 };
GetCurrentDirectoryW(999, currentFolderBuffer);
currentFolder = currentFolderBuffer;
#else
char currentFolderBuffer[10000] = { 0 };
char *getcwd(char *buf, size_t size);
currentFolder = GetWString(getcwd(currentFolderBuffer, 9999));
#endif
while (currentFolder.size() && currentFolder[currentFolder.size() - 1] == L'\\') currentFolder.erase(currentFolder.size() - 1);
auto spos = currentFolder.find(L"\\");
while (spos != std::wstring::npos)
{
currentFolder.erase(0, spos + 1);
spos = currentFolder.find(L"\\");
}
return currentFolder;
}
void file::SetCurrentFolderName(std::wstring folderName)
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
SetCurrentDirectoryW(folderName.c_str());
#else
int chdir(const char *path);
chdir(GetString(folderName).c_str());
#endif
}
void file::SplitBigTextToMultilFile(const std::wstring &filename, const std::wstring &subfilename)
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
std::ifstream bigFileStream(filename, std::ifstream::in | std::ifstream::binary);
#else
std::ifstream bigFileStream(GetString(filename), std::ifstream::in | std::ifstream::binary);
#endif
if (bigFileStream.is_open())
{
bigFileStream.seekg(0, std::ios_base::end);
long long buffFileSize = bigFileStream.tellg();
bigFileStream.seekg(0, std::ios_base::beg);
int subFileNameIndex = 1;
int subBufferSize = 20 * 1024 * 1024;
int nearFullBufferSize = 19 * 1024 * 1024;
char * subBuffer = (char*)calloc(subBufferSize, 1);
long long subBufferIndex = 0;
char * readBuffer = (char*)calloc(8100000, 1);
for (long long iChar = 0u; iChar < buffFileSize;)
{
long long readSize = buffFileSize - iChar;
if (readSize > 8000000) readSize = 8000000;
if (readSize > 0)
{
bigFileStream.read(readBuffer, readSize);
iChar += readSize;
if (subBufferIndex + readSize < nearFullBufferSize)
{
memcpy(subBuffer + subBufferIndex, readBuffer, readSize);
subBufferIndex += readSize;
}
else
{
int firstNewLineIndex = 0;
for (; readBuffer[firstNewLineIndex] != '\r'&&readBuffer[firstNewLineIndex] != '\n'&&readBuffer[firstNewLineIndex] != 0; firstNewLineIndex++)
{
subBuffer[subBufferIndex++] = readBuffer[firstNewLineIndex];
}
file::WriteFile(subfilename + (subFileNameIndex < 100 ? std::wstring(L"0") : std::wstring(L"")) + (subFileNameIndex < 10 ? std::wstring(L"0") : std::wstring(L"")) + subFileNameIndex++ + std::wstring(L".txt"), subBuffer, subBufferSize, 1);
subBufferIndex = 0;
memset(subBuffer, 0, subBufferSize);
if (readSize > firstNewLineIndex)
{
subBufferIndex = readSize - firstNewLineIndex;
memcpy(subBuffer, readBuffer + firstNewLineIndex, subBufferIndex);
}
}
}
}
free(subBuffer);
free(readBuffer);
}
}
/************************************************************************/
/* Các phương thức tĩnh thao tác với thư mục */
/************************************************************************/
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
#else
DIR *opendir(const char *);
struct dirent *readdir(DIR *);
int readdir_r(DIR *, struct dirent *, struct dirent **);
void rewinddir(DIR *);
void seekdir(DIR *, long int);
long int telldir(DIR *);
int closedir(DIR *);
#endif
void file::ScanFile(const std::wstring &path, const std::wstring &extension, std::wstringset &fileSet)
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
std::wstring wFolder = path;
if (wFolder.size() && wFolder[wFolder.size() - 1] != L'\\') wFolder += L'\\';
wFolder += extension;
WIN32_FIND_DATAW fd;
HANDLE hFind = FindFirstFileW(wFolder.c_str(), &fd);
if (hFind == INVALID_HANDLE_VALUE) return;
do
{
if (fd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
{//là thư mục
if (wcscmp(fd.cFileName, L".") && wcscmp(fd.cFileName, L".."))
{//không phải là thư mục đặc biệt
std::wstring child = path;
if (child.size() && child[child.size() - 1] != L'\\') child += L'\\';
child += fd.cFileName;
ScanFile(child, extension, fileSet);
}
}
else
{//là file
std::wstring filePath = path;
if (filePath.size() && filePath[filePath.size() - 1] != L'\\') filePath += L'\\';
filePath += fd.cFileName;
fileSet.insert(filePath);
}
} while (FindNextFileW(hFind, &fd));
FindClose(hFind);
#else
DIR *dir = opendir(GetString(path).c_str());
class dirent *ent;
class stat st;
while ((ent = readdir(dir)) != NULL)
{
if (ent->d_name)
{
const std::string file_name = ent->d_name;
const std::wstring full_file_name = path + L"/" + file_name;
if (file_name[0] == '.')
{
/*do nothing*/
}
else if (stat(GetString(full_file_name).c_str(), &st) == -1)
{
/*do nothing*/
}
else
{
const bool is_directory = (st.st_mode & S_IFDIR) != 0;
if (is_directory)
{
ScanFile(full_file_name, extension, fileSet);
}
else
{
fileSet.insert(full_file_name);
}
}
}
}
closedir(dir);
#endif
}
void file::ScanSubFolder(const std::wstring &path, std::wstringset &folderSet)
{
#if defined(WIN32) || defined(_WIN32) || defined(WIN64) || defined(_WIN64) || defined(_MSC_VER)
std::wstring wFolder = path;
if (wFolder.size() && wFolder[wFolder.size() - 1] != L'\\') wFolder += L'\\';
wFolder += L"*.*";
WIN32_FIND_DATAW fd;
HANDLE hFind = FindFirstFileW(wFolder.c_str(), &fd);
if (hFind == INVALID_HANDLE_VALUE) return;
do
{
if (fd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
{//là thư mục
if (wcscmp(fd.cFileName, L".") && wcscmp(fd.cFileName, L".."))
{//không phải là thư mục đặc biệt
folderSet.insert(fd.cFileName);
}
}
} while (FindNextFileW(hFind, &fd));
FindClose(hFind);
#else
DIR *dir = opendir(GetString(path).c_str());
class dirent *ent;
class stat st;
while ((ent = readdir(dir)) != NULL)
{
const std::string file_name = ent->d_name;
const std::wstring full_file_name = path + L"/" + file_name;
if (file_name[0] == '.')
{
/*do nothing*/
}
else if (stat(GetString(full_file_name).c_str(), &st) == -1)
{
/*do nothing*/
}
else
{
const bool is_directory = (st.st_mode & S_IFDIR) != 0;
if (is_directory)
{
folderSet.insert(full_file_name);
//ScanFile(full_file_name, extension, fileSet);
}
else
{
//fileSet.insert(full_file_name);
}
}
}
closedir(dir);
#endif
}
void file::CleanDirectory(const std::wstring &dirName)
{
std::wstringset fileList;
ScanFile(dirName, L"*.*", fileList);
for (auto i = fileList.begin(); i != fileList.end(); i++) file::DeleteFile(i->c_str());
}
/************************************************************************/
/* Các phương thức với lớp XML File */
/************************************************************************/
/*constructor*/ xml::xml(const std::wstring &xmlFileName, const std::wstring &nodeName) :file(xmlFileName)
{
std::wstring bufferFileContent;
file::Read(bufferFileContent);
std::wstring startOfNodeString = L"<" + nodeName + L">";
std::wstring endOfNodeString = L"</" + nodeName + L">";
auto posStart = bufferFileContent.find(startOfNodeString);
int currentIndex = 0;
while (posStart != std::wstring::npos)
{
auto posEnd = bufferFileContent.find(endOfNodeString);
if (posEnd != std::wstring::npos)
{
std::wstring bufferNode = bufferFileContent.substr(posStart, posEnd - posStart + endOfNodeString.size());
xmlContent.insert(xmlContent.end(), bufferNode);
bufferFileContent.erase(posStart, posEnd - posStart + startOfNodeString.size() + 1);
posStart = bufferFileContent.find(startOfNodeString);
currentIndex++;
}
else
{
wprintf(L"Tại %ls thứ %d không tìm thấy %ls\n", startOfNodeString.c_str(), currentIndex, endOfNodeString.c_str());
posStart = std::wstring::npos;
}
}
wprintf(L"Đọc được %d %ls.\n", currentIndex, nodeName.c_str());
}
int xml::Size(void)const
{
return int(xmlContent.size());
}
std::wstring xml::Attribute(int index, const std::wstring &attributeName)const
{
int countIndex = 0;
for (auto inode = xmlContent.begin(); inode != xmlContent.end() && countIndex <= index; inode++, countIndex++)
{
if (inode != xmlContent.end() && countIndex == index)
{
auto posStart = inode->find(L"<" + attributeName + L">");
auto posEnd = inode->find(L"</" + attributeName + L">");
if (posStart != std::wstring::npos && posEnd != std::wstring::npos && posStart < posEnd)
{
std::wstring result = inode->substr(posStart + attributeName.size() + 2, posEnd - posStart - attributeName.size() - 2);
while (result.size() && (result[0] == L'\n' || result[0] == L'\r' || result[0] == L' ' || result[0] == L'\t')) result.erase(0, 1);
while (result.size() && (result[result.size() - 1] == L'\n' || result[result.size() - 1] == L'\r' || result[result.size() - 1] == L' ' || result[result.size() - 1] == L'\t')) result.erase(result.size() - 1, 1);
return result;
}
}
}
return L"";
}
std::wstring xml::GetAndClearAttribute(int index, const std::wstring &attributeName)
{
int countIndex = 0;
for (auto inode = xmlContent.begin(); inode != xmlContent.end() && countIndex <= index; inode++, countIndex++)
{
if (inode != xmlContent.end() && countIndex == index)
{
auto posStart = inode->find(L"<" + attributeName + L">");
auto posEnd = inode->find(L"</" + attributeName + L">");
if (posStart != std::wstring::npos && posEnd != std::wstring::npos && posStart < posEnd)
{
std::wstring result = inode->substr(posStart + attributeName.size() + 2, posEnd - posStart - attributeName.size() - 2);
inode->erase(posStart, posEnd - posStart + attributeName.size() + 3);
while (result.size() && (result[0] == L'\n' || result[0] == L'\r' || result[0] == L' ' || result[0] == L'\t')) result.erase(0, 1);
while (result.size() && (result[result.size() - 1] == L'\n' || result[result.size() - 1] == L'\r' || result[result.size() - 1] == L' ' || result[result.size() - 1] == L'\t')) result.erase(result.size() - 1, 1);
Replace(result, L"\"", L"'");
Replace(result, L"\r", L" ");
Replace(result, L"\t", L" ");
Replace(result, L"\n", L"\t");
Replace(result, L" ", L" ");
Replace(result, L"\t ", L"\t");
Replace(result, L" \t", L"\t");
Replace(result, L"\t\t", L"\t");
return result;
}
}
}
return L"";
}
std::wstring xml::GetOriginalAttribute(int index, const std::wstring &attributeName)
{
int countIndex = 0;
for (auto inode = xmlContent.begin(); inode != xmlContent.end() && countIndex <= index; inode++, countIndex++)
{
if (inode != xmlContent.end() && countIndex == index)
{
auto posStart = inode->find(L"<" + attributeName + L">");
auto posEnd = inode->find(L"</" + attributeName + L">");
if (posStart != std::wstring::npos && posEnd != std::wstring::npos && posStart < posEnd)
{
std::wstring result = inode->substr(posStart + attributeName.size() + 2, posEnd - posStart - attributeName.size() - 2);
return result;
}
}
}
return L"";
}
void xml::ScanAllXMLTag(const std::wstring& xmlPath /*= L"DuLieuTuDienPhanLoaiTiengViet\\vcl_xml\\"*/, const std::wstring xmlTagFileName /*= L"xmlTag.txt"*/)
{
std::wstringset xmlFileSet;
file::ScanFile(xmlPath, L"*.xml", xmlFileSet);
std::wstringset xmlTag;
for (auto iFile = xmlFileSet.begin(); iFile != xmlFileSet.end(); iFile++)
{
wprintf(L"Scan file %ls\n", iFile->c_str());
std::wstring xmlContent = file::ReadFile(*iFile);
std::wstring currentTag;
for (auto i = 0u, scanStatus = 0u; i < xmlContent.size(); i++)
{
if (scanStatus == 1)
{
if (xmlContent[i] == L'>')
{
if (currentTag.size())
{
xmlTag.insert(L"<" + currentTag + L">");
currentTag.clear();
}
scanStatus = 0;
}
else currentTag += xmlContent[i];
}
else if (xmlContent[i] == L'<') scanStatus = 1;
}
}
file::WriteFile(xmlTagFileName, xmlTag);
}
| [
"[email protected]"
] | |
d3ba27038b5bd60926034766bf268c20d829fe44 | 187447bd8b2bd4851f45efbbebad55056df9df83 | /multiplier/mult_test.cpp | 71363470fa4f68525e2d5c62a36a871747bba0ca | [] | no_license | FreeBugs/cmake_conan_gtest | 86e27ec03e217032786bef369ba3eec518eccfe0 | bb854536043140876bc1dce88fbd39533c61e8d6 | refs/heads/main | 2023-02-11T04:50:58.341580 | 2021-01-06T09:27:10 | 2021-01-06T09:27:10 | 320,560,359 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 683 | cpp | #include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "multiplizierer.hpp"
#include "multiplizierer_optimierer.hpp"
using namespace testing;
class MultMock : public multiplizierer {
public:
MOCK_METHOD(long, mult, (int a, int b), (override));
};
class MultTest : public Test {
public:
MultMock mult_mock;
multiplizierer_optimierer objectUnderTest{mult_mock};
};
TEST_F(MultTest, a_is_greater_than_b_not_swapped) {
EXPECT_CALL(mult_mock, mult(1, 100)).WillOnce(Return(100));
objectUnderTest.mult(100, 1);
}
TEST_F(MultTest, a_is_smaller_than_b_swapped) {
EXPECT_CALL(mult_mock, mult(1, 100)).WillOnce(Return(100));
objectUnderTest.mult(1, 100);
} | [
"[email protected]"
] | |
1cc704e69058b8e90263fe7bb71db6f9c1b5349f | d3b8b714c5e37af1aebb85fa7a04818a7983b110 | /render.h | d58d3f709d2cc0fda0f0811925a9a3009b4f4439 | [] | no_license | Jyskman/PM | 02023d7c66bfd996b9db884f79d1ffaec8dc71dd | 9a70f2db776eaa3701dca60c4a477ac28f061d34 | refs/heads/master | 2023-02-03T11:21:25.442543 | 2020-12-22T09:34:06 | 2020-12-22T09:34:06 | 319,399,639 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,069 | h | // This is start of the header guard. ADD_H can be any unique name. By convention, we use the name of the header file.
#ifndef RENDER_H
#define RENDER_H
#include <iostream>
//~ #include "enemy.h"
#include "champ.h"
#include "enemy.h"
// This is the content of the .h file, which is where the declarations go
using namespace::std;
void particle_generator( int x_pos, int y_pos, int animation_type_as_index , int animation_type, bool random_v, int cycles, int random_factor );
void particle_generator( int x_pos, int y_pos, int animation_type_as_index , int animation_type, int v_x, int v_y, int cycles );
//specific for detruction of enemies
void particle_generator( enemy *parameter, int x_pos, int y_pos, int cycles );
void render_requests_quad( int sprite_nr, int x_loc, int y_loc, bool white_border, bool center, bool right_orientation );
void render_requests_dual( int sprite_nr, int x_loc, int y_loc, bool white_border, bool center, bool center_orientation );
void render_primitive_line( int x_start, int y_start, int x_stop, int y_stop, int orientation, int sprite_index );
class render_requests {
public:
render_requests(int sprite_nr, int x_pos, int y_pos, int palette);
render_requests(int sprite_nr, int x_pos, int y_pos, bool static_);
render_requests(int sprite_nr, int x_pos, int y_pos, int palette, bool right_orientation, bool up_orientation, int rot);
//~render_requests();
int sprite_nr;
int sprite_index;
int x_pos;
int y_pos;
bool draw;
bool draw_evaluate;
bool orientation;
bool up_down;
int rotation;
bool static_render = false;
bool checkers;
int getSprite_nr();
int current_palette;
bool getDraw(const render_requests & o);
int getX();
int getY();
};
extern vector<render_requests> render_req;
// Will create general animation req system
class animation_requests {
public:
animation_requests(int animation_nr_as_index, int animation_nr, int rot, bool facing_right, bool facing_up ,int cycles_to_terminate, int x_start, int y_start, int x_vel_start, int y_vel_start);
animation_requests( int profile_index, int x_start, int y_start, int x_vel_start, int y_vel_start );
animation_requests(int *x_start, int *y_start, int x_vel_start, int y_vel_start, bool upgrade_scan );
int update_position_case = 0;
int sprite_width;
int rotation = 1;
int anime_nr, x, y, x_v, y_v, cycles, sprite_nr, sprite_index, current_cycle, profile_nr;
int * x_pos;
int * y_pos;
bool destroy = false;
void sprite_setup( int index );
void profile_setup( int profile_index_parameter );
void render_animation();
void update_position( physics ¶meter, int room );
void modifier();
void animation_as_index();
int animation_as_nr;
int state =1;
bool right_orientation;
bool up_orientation;
float x_v_float = 0;
float y_v_float = 0;
float x_float = 0;
float y_float = 0;
int x_offset;
bool front = true;
};
extern vector<animation_requests> anime_req;
class render {
public:
int null_static = 1;
vector<render_requests> *internal;
int x_pos, y_pos;
int current_x_offset, current_y_offset;
int render_xlimit_upper, render_xlimit_lower, render_ylimit_upper, render_ylimit_lower;
int offset_parameter_x_left, offset_parameter_x_right;
int offset_parameter_y_low, offset_parameter_y_up;
int horisontal_p1; // for inversion based on direction parameter
int horisontal_p2; //for inversion based on direction parameter
int vertical_p1; // for inversion based on direction parameter
int vertical_p2; //for inversion based on direction parameter
int rotation_p1;
int rotation_p2;
int render_limit_p1;
int render_limit_p2;
unsigned char render_array[240][320*2];
unsigned char *render_array_pointer;
unsigned char byte_1, byte_2;
unsigned char R_888_byte, G_888_byte, B_888_byte;
char test = 0;
bool return_value; // for the check function
unsigned short RGB565;
int offset = 0;
render(int a); // constructor
void fillColor(int x, int y, unsigned short color);
// Below is fillcolor dev version
void fillColor_dev(int x, int y, unsigned char color, unsigned char color2 );
void render_clear();
void filler_dev(int roomnr);
void filler_general(int roomnr);
char getColor(int x, int y);
unsigned char mutateColor(int &RGB ,unsigned char &color, int &palette);
// 0, 50, 100, 150, 200
unsigned char palette_1[5][3] = {
{0,0,0},
{140,50,90},
{230,60,150},
{0,255,150},
{255,255,0}
};
int mutate_Y(int y);
void determine_current_offset(champ& parameter, int roomnr);
bool render_limit_check(int x_pos, int y_pos);
void render_req_filter();
int filter_w;
int filter_h;
//Will start with 10 hardcoded palettes with 5 color
unsigned char palettes_R[5][10] = {
{0, 0,0,0,0,0,0,0,0,0},
{140,0,0,0,0,0,0,0,0,0},
{230,0,0,0,0,0,0,0,0,0},
{0, 0,0,0,0,0,0,0,0,0},
{255,0,0,0,0,0,0,0,0,0}
};
unsigned char palettes_G[5][10] = {
{0,0,0,0,0,0,0,0,0,0},
{50,0,0,0,0,0,0,0,0,0},
{60,0,0,0,0,0,0,0,0,0},
{255,0,0,0,0,0,0,0,0,0},
{255,0,0,0,0,0,0,0,0,0}
};
unsigned char palettes_B[5][10] = {
{0,0,0,0,0,0,0,0,0,0},
{90,0,0,0,0,0,0,0,0,0},
{150,0,0,0,0,0,0,0,0,0},
{150,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0}
};
int R = 0, G = 1, B = 2;
int testpal = 0;
unsigned char palettes_RGB[15][10] = {
{0, 0,0,0,0,0,0,0,0,0},
{140,0,0,0,0,0,0,0,0,0},
{230,0,0,0,0,0,0,0,0,0},
{0, 0,0,0,0,0,0,0,0,0},
{255,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0},
{50,0,0,0,0,0,0,0,0,0},
{60,0,0,0,0,0,0,0,0,0},
{255,0,0,0,0,0,0,0,0,0},
{255,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0},
{90,0,0,0,0,0,0,0,0,0},
{150,0,0,0,0,0,0,0,0,0},
{150,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0}
};
// render will need to store the info of sprites, size and adress for increased speed and reduction of global vector variables. will need to remove all palette stuff prob
vector<unsigned char*> sprite_address;
vector<int> sprite_w;
vector<int> sprite_h;
void load_sprite_data( unsigned char* add, int width, int height );
vector<render_requests> internal_render_requests;
};
// New render req class attempt
// This is the end of the header guard
#endif
| [
"[email protected]"
] | |
fadb308893ffb1f94262eb8a703221cbefa170a4 | 6b248d2c69f050d5bd6a2728b140fb490108f8ac | /src/Point3D.cpp | 8124eb4f018c7944636c9dd1646297be565e5854 | [] | no_license | alittlezz/Fake-Paint | 09a447af7dccdfc8143eb338e84744fa5c231790 | e1cd0b98b38ec2d1f9592dc1f12ad272e39afe32 | refs/heads/master | 2020-03-30T21:10:05.666611 | 2018-10-04T17:44:40 | 2018-10-04T17:44:40 | 151,618,954 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,383 | cpp | #include <Point3D.h>
#include <iostream>
namespace Geom{
Point3D::Point3D(){
x = y = z = 0;
}
Point3D::Point3D(const double &val){
x = val;
y = val;
z = val;
}
Point3D::Point3D(const sf::Color &color){
x = color.r;
y = color.g;
z = color.b;
}
Point3D::Point3D(const sf::Vector3f &point){
x = point.x;
y = point.y;
z = point.z;
}
Point3D::Point3D(const sf::Vector3i &point){
x = point.x;
y = point.y;
z = point.z;
}
Point3D::Point3D(const double &_x, const double &_y, const double &_z){
x = _x;
y = _y;
z = _z;
}
void Point3D::setX(const double &_x){
x = _x;
}
void Point3D::setY(const double &_y){
y = _y;
}
void Point3D::setZ(const double &_z){
z = _z;
}
double Point3D::getX() const{
return x;
}
double Point3D::getY() const{
return y;
}
double Point3D::getZ() const{
return z;
}
Point3D Point3D::operator + (const Point3D &point) const{
return {this->x + point.getX(), this->y + point.getY(), this->z + point.getZ()};
}
Point3D Point3D::operator - (const Point3D &point) const{
return {this->x - point.getX(), this->y - point.getY(), this->z - point.getZ()};
}
Point3D Point3D::operator * (const Point3D &point) const{
return {this->x * point.getX(), this->y * point.getY(), this->z * point.getZ()};
}
Point3D Point3D::operator / (const Point3D &point) const{
if(point.getX() == 0 || point.getY() == 0 || point.getZ() == 0){
std::cout << "Can't divide by 0!";
exit(0);
}
return {this->x / point.getX(), this->y / point.getY(), this->z / point.getZ()};
}
Point3D Point3D::operator + (const double &val) const{
return {this->x + val, this->y + val, this->z + val};
}
Point3D Point3D::operator - (const double &val) const{
return {this->x - val, this->y - val, this->z - val};
}
Point3D Point3D::operator * (const double &val) const{
return {this->x * val, this->y * val, this->z * val};
}
Point3D Point3D::operator / (const double &val) const{
if(val == 0){
std::cout << "Can't divide by 0!";
exit(0);
}
return {this->x / val, this->y / val, this->z / val};
}
bool Point3D::operator == (const Point3D &point) const{
return this->x == point.getX() && this->y == point.getY() && this->z == point.getZ();
}
bool Point3D::operator != (const Point3D &point) const{
return !((*this) == point);
}
}
| [
"[email protected]"
] | |
8459b0c9079a1e432747be8d74b1e36e5372515b | 608919a5b53cf3950cd8849ff30dca3eb94b4ad8 | /codeforces/671b.cpp | 812132476d0bdcafb24dd68d90fefd8a0b4ee2c1 | [] | no_license | demerzel1/ACM-code | 302c693fbd9f4d40071e13e674ec3c9b8dc15a24 | 42e3f59a585832b0fc4556d130be4c158b3bd2ec | refs/heads/master | 2021-04-26T22:21:09.891295 | 2018-03-31T08:16:54 | 2018-03-31T08:16:54 | 124,077,438 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,428 | cpp | #include<bits/stdc++.h>
using namespace std;
#define maxn 500005
typedef long long LL;
int c[maxn];
LL sl[maxn];
LL sr[maxn];
int nl[maxn];
int nr[maxn];
LL sum=0;
map<int,int> num;
int main() {
int n,k;
scanf("%d%d",&n,&k);
for(int i=1; i<=n; i++) {
scanf("%d",&c[i]);
num[c[i]]++;
sum+=c[i];
}
sort(c+1,c+n+1);
int len=unique(c+1,c+n+1)-c-1;
int L=-1;
int R=-1;
nl[0]=0;
sl[0]=0;
c[0]=c[1];
for(int i=1; i<=len; i++) {
nl[i]=nl[i-1]+num[c[i]];
sl[i]=sl[i-1]+(LL)nl[i-1]*(c[i]-c[i-1]);
if(sl[i]>k&&L==-1)
L=i-1;
}
nr[len+1]=0;
sr[len+1]=0;
c[len+1]=c[len];
for(int i=len; i>=1; i--) {
nr[i]=nr[i+1]+num[c[i]];
sr[i]=sr[i+1]+(LL)nr[i+1]*(c[i+1]-c[i]);
if(sr[i]>k&&R==-1)
R=i+1;
}
if(L>=R) {
if(sum%n==0) {
printf("0\n");
} else {
printf("1\n");
}
} else {
int Min=c[L]+(k-sl[L])/nl[L];
int Max=c[R]-(k-sr[R])/nr[R];
// printf("min=%d cl=%d max=%d cr=%d\n",Min,c[L],Max,c[R]);
if(Min>=Max) {
if(sum%n==0) {
printf("0\n");
} else {
printf("1\n");
}
} else {
printf("%d\n",Max-Min);
}
}
return 0;
}
| [
"[email protected]"
] | |
30d48a4a15c47c40f7f04abba184eb55df9d7212 | 8ae7a23f05805fd71d4be13686cf35d8994762ed | /mame150/src/mame/video/atarimo.h | f343abe61ce16d9c96f3300f5155e48790433d12 | [] | no_license | cyberkni/276in1JAMMA | fb06ccc6656fb4346808a24beed8977996da91b2 | d1a68172d4f3490cf7f6e7db25d5dfd4cde3bb22 | refs/heads/master | 2021-01-18T09:38:36.974037 | 2013-10-07T18:30:02 | 2013-10-07T18:30:02 | 13,152,960 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,743 | h | /***************************************************************************
atarimo.h
Common motion object management functions for Atari raster games.
****************************************************************************
Copyright Aaron Giles
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 'MAME' 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 AARON GILES ''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 AARON GILES 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.
***************************************************************************/
#ifndef __ATARIMO__
#define __ATARIMO__
#include "sprite.h"
//**************************************************************************
// DEVICE CONFIGURATION MACROS
//**************************************************************************
#define MCFG_ATARI_MOTION_OBJECTS_ADD(_tag, _screen, _config) \
MCFG_DEVICE_ADD(_tag, ATARI_MOTION_OBJECTS, 0) \
MCFG_VIDEO_SET_SCREEN(_screen) \
atari_motion_objects_device::static_set_config(*device, _config);
//**************************************************************************
// TYPE DEFINITIONS
//**************************************************************************
// description of the motion objects
struct atari_motion_objects_config
{
struct entry { UINT16 data[4]; };
struct dual_entry { UINT16 data_lower[4]; UINT16 data_upper[4]; };
UINT8 m_gfxindex; // index to which gfx system
UINT8 m_bankcount; // number of motion object banks
bool m_linked; // are the entries linked?
bool m_split; // are the entries split?
bool m_reverse; // render in reverse order?
bool m_swapxy; // render in swapped X/Y order?
bool m_nextneighbor; // does the neighbor bit affect the next object?
UINT16 m_slipheight; // pixels per SLIP entry (0 for no-slip)
UINT8 m_slipoffset; // pixel offset for SLIPs
UINT16 m_maxperline; // maximum number of links to visit/scanline (0=all)
UINT16 m_palettebase; // base palette entry
UINT16 m_maxcolors; // maximum number of colors (remove me)
UINT8 m_transpen; // transparent pen index
entry m_link_entry; // mask for the link
dual_entry m_code_entry; // mask for the code index
dual_entry m_color_entry; // mask for the color/priority
entry m_xpos_entry; // mask for the X position
entry m_ypos_entry; // mask for the Y position
entry m_width_entry; // mask for the width, in tiles*/
entry m_height_entry; // mask for the height, in tiles
entry m_hflip_entry; // mask for the horizontal flip
entry m_vflip_entry; // mask for the vertical flip
entry m_priority_entry; // mask for the priority
entry m_neighbor_entry; // mask for the neighbor
entry m_absolute_entry; // mask for absolute coordinates
entry m_special_entry; // mask for the special value
UINT16 m_specialvalue; // resulting value to indicate "special"
};
// ======================> atari_motion_objects_device
// device type definition
extern const device_type ATARI_MOTION_OBJECTS;
class atari_motion_objects_device : public sprite16_device_ind16,
public device_video_interface,
public atari_motion_objects_config
{
static const int MAX_PER_BANK = 1024;
public:
// construction/destruction
atari_motion_objects_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
// static configuration helpers
static void static_set_config(device_t &device, const atari_motion_objects_config &config);
// getters
int bank() const { return m_bank; }
int xscroll() const { return m_xscroll; }
int yscroll() const { return m_yscroll; }
dynamic_array<UINT16> &code_lookup() { return m_codelookup; }
dynamic_array<UINT8> &color_lookup() { return m_colorlookup; }
dynamic_array<UINT8> &gfx_lookup() { return m_gfxlookup; }
// setters
void set_bank(int bank) { m_bank = bank; }
void set_xscroll(int xscroll) { m_xscroll = xscroll & m_bitmapxmask; }
void set_yscroll(int yscroll) { m_yscroll = yscroll & m_bitmapymask; }
void set_scroll(int xscroll, int yscroll) { set_xscroll(xscroll); set_yscroll(yscroll); }
void set_slipram(UINT16 *ram) { m_slipram.set_target(ram, 2); }
// rendering
virtual void draw(bitmap_ind16 &bitmap, const rectangle &cliprect);
void apply_stain(bitmap_ind16 &bitmap, UINT16 *pf, UINT16 *mo, int x, int y);
// memory access
UINT16 &slipram(int offset) { return m_slipram[offset]; }
// constants
static const int PRIORITY_SHIFT = 12;
static const UINT16 PRIORITY_MASK = (~0 << PRIORITY_SHIFT) & 0xffff;
static const UINT16 DATA_MASK = PRIORITY_MASK ^ 0xffff;
protected:
// device-level overrides
virtual void device_start();
virtual void device_reset();
virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr);
private:
// timer IDs
enum
{
TID_FORCE_UPDATE,
};
// internal helpers
int compute_log(int value);
int round_to_powerof2(int value);
void build_active_list(int link);
void render_object(bitmap_ind16 &bitmap, const rectangle &cliprect, const UINT16 *entry);
// a sprite parameter, which is a word index + shift + mask
class sprite_parameter
{
public:
sprite_parameter();
bool set(const atari_motion_objects_config::entry &input) { return set(input.data); }
bool set(const UINT16 input[4]);
UINT16 extract(const UINT16 *data) const { return (data[m_word] >> m_shift) & m_mask; }
UINT16 shift() const { return m_shift; }
UINT16 mask() const { return m_mask; }
private:
UINT16 m_word; // word index
UINT16 m_shift; // shift amount
UINT16 m_mask; // final mask
};
// a sprite parameter, which is a word index + shift + mask
class dual_sprite_parameter
{
public:
dual_sprite_parameter();
bool set(const atari_motion_objects_config::dual_entry &input);
UINT16 extract(const UINT16 *data) const { return m_lower.extract(data) | (m_upper.extract(data) << m_uppershift); }
UINT16 mask() const { return m_lower.mask() | (m_upper.mask() << m_uppershift); }
private:
sprite_parameter m_lower; // lower parameter
sprite_parameter m_upper; // upper parameter
UINT16 m_uppershift; // upper shift
};
// parameter masks
sprite_parameter m_linkmask; // mask for the link
sprite_parameter m_gfxmask; // mask for the graphics bank
dual_sprite_parameter m_codemask; // mask for the code index
dual_sprite_parameter m_colormask; // mask for the color
sprite_parameter m_xposmask; // mask for the X position
sprite_parameter m_yposmask; // mask for the Y position
sprite_parameter m_widthmask; // mask for the width, in tiles*/
sprite_parameter m_heightmask; // mask for the height, in tiles
sprite_parameter m_hflipmask; // mask for the horizontal flip
sprite_parameter m_vflipmask; // mask for the vertical flip
sprite_parameter m_prioritymask; // mask for the priority
sprite_parameter m_neighbormask; // mask for the neighbor
sprite_parameter m_absolutemask; // mask for absolute coordinates
sprite_parameter m_specialmask; // mask for the special value
// derived tile information
int m_tilewidth; // width of non-rotated tile
int m_tileheight; // height of non-rotated tile
int m_tilexshift; // bits to shift X coordinate when drawing
int m_tileyshift; // bits to shift Y coordinate when drawing
// derived bitmap information
int m_bitmapwidth; // width of the full playfield bitmap
int m_bitmapheight; // height of the full playfield bitmap
int m_bitmapxmask; // x coordinate mask for the playfield bitmap
int m_bitmapymask; // y coordinate mask for the playfield bitmap
// derived sprite information
int m_entrycount; // number of entries per bank
int m_entrybits; // number of bits needed to represent entrycount
int m_spriterammask; // combined mask when accessing sprite RAM with raw addresses
int m_spriteramsize; // total size of sprite RAM, in entries
int m_slipshift; // log2(pixels_per_SLIP)
int m_sliprammask; // combined mask when accessing SLIP RAM with raw addresses
int m_slipramsize; // total size of SLIP RAM, in entries
// live state
emu_timer * m_force_update_timer; // timer for forced updating
UINT32 m_bank; // current bank number
UINT32 m_xscroll; // xscroll offset
UINT32 m_yscroll; // yscroll offset
// arrays
optional_shared_ptr<UINT16> m_slipram; // pointer to the SLIP RAM
dynamic_array<UINT16> m_codelookup; // lookup table for codes
dynamic_array<UINT8> m_colorlookup; // lookup table for colors
dynamic_array<UINT8> m_gfxlookup; // lookup table for graphics
UINT16 m_activelist[MAX_PER_BANK*4]; // active list
UINT16 * m_activelast; // last entry in the active list
UINT32 m_last_xpos; // (during processing) the previous X position
UINT32 m_next_xpos; // (during processing) the next X position
};
#endif
| [
"[email protected]"
] | |
7b2bac1721a6a51deddd2fe7be2280e136be9e90 | a8e040babd225c00e884605fa76c355fc9560aab | /bofstream.h | a071bef6d6416984e828662a67de4163538fabf1 | [
"MIT"
] | permissive | DJMcMayhem/Huffman | 6d7e6b5338c59f2c4e12744436f6a85bf83a0b37 | 036ae6f43d4e057e8c1bc704f5a7726c7e4c77f8 | refs/heads/master | 2021-01-17T15:42:07.550072 | 2016-07-27T15:29:46 | 2016-07-27T15:29:46 | 50,272,197 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 425 | h | #pragma once
#include <fstream>
#include <vector>
class bofstream
{
public:
bofstream();
~bofstream();
public:
void open(const char *filePath);
void close();
bool good();
bool fail();
bool eof();
void clear();
void put(bool);
void put(std::vector<bool>);
private:
void flushBufferToFile();
private:
std::ofstream file;
unsigned char buffer;
short bitPosition;
};
| [
"[email protected]"
] | |
6dffb80907f4ca1ccdc4aee7cd01ce5b2e863c1a | 95e57bff6e7a9f6da93361017a5c464db23d4126 | /timeManager.h | af2c0c248aa50aeab5bd7fa99f056e937e82ade7 | [] | no_license | tsubaki4242/PokemonEm | c2f8fee24b916ec08e90a6e5c676b86e4b8c9de0 | 65f5d2d5bb58e1dd04550954b38153dc892d88d1 | refs/heads/master | 2023-08-11T08:26:25.056552 | 2021-09-29T04:20:25 | 2021-09-29T04:20:25 | 411,257,047 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 495 | h | #pragma once
#include "singletonBase.h"
#include "timer.h"
class timeManager : public singletonBase<timeManager>
{
private:
timer* _timer;
public:
timeManager();
~timeManager();
HRESULT init();
void release();
void update(float lock = 0.0f);
void render(HDC hdc);
inline float getElapsedTime() const { return _timer->getElapsedTime(); }
inline float getWorldTime() const { return _timer->getWorldTime(); }
inline int getFrameRate(void) const { return _timer->getFrameRate(); }
};
| [
"[email protected]"
] | |
7ebddbe7b3c4d2e90315aa328b7a1cf8882d90f7 | 243dd70b2592a7f2e75bc06598f61d400249627d | /kernel/src/platform/simics/8259.h | 8b38b47d7f07ae6a16f668c74647210b4a217ce9 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | vmlemon/Orion | 4d1445f750c8450f9c5ac1979eb846dbaed178f5 | 61f894826a802c24076c22c1c9439bc7382a276a | refs/heads/master | 2020-07-06T08:20:32.942117 | 2020-01-25T19:08:09 | 2020-01-25T19:08:09 | 202,951,911 | 6 | 0 | null | 2019-10-24T00:37:40 | 2019-08-18T02:40:09 | C | UTF-8 | C++ | false | false | 4,863 | h | /*********************************************************************
*
* Copyright (C) 2002, 2004-2003, Karlsruhe University
*
* File path: platform/pc99/8259.h
* Description: Driver for i8259 Programmable Interrupt Controller
*
* 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 THE AUTHOR 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 AUTHOR 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.
*
* $Id: 8259.h,v 1.4 2004/03/01 19:50:10 stoess Exp $
*
********************************************************************/
#ifndef __PLATFORM__PC99__8259_H__
#define __PLATFORM__PC99__8259_H__
#include INC_ARCH(ioport.h) /* for in_u8/out_u8 */
/**
* Driver for i8259 PIC
* @param base the base address of the registers
*
* The template parameter BASE enables compile-time resolution of the
* PIC's control register addresses.
*
* Note:
* Depending on whether CONFIG_X86_INKERNEL_PIC is defined or not
* objects will cache the mask register or not. Thus it is not wise
* to blindly instanciate them all over the place because the cached
* state would not be shared. Making the cached state static
* wouldn't work either because there are two PICs in a
* PC99. Intended use is a single object per PIC.
*
* Assumptions:
* - BASE can be passed as port to in_u8/out_u8
* - The PIC's A0=0 register is located at BASE
* - The PIC's A0=1 register is located at BASE+1
* - PICs in unbuffered cascade mode
*
* Uses:
* - out_u8, in_u8
*/
template<u16_t base> class i8259_pic_t {
private:
u8_t mask_cache;
public:
/**
* Unmask interrupt
* @param irq interrupt line to unmask
*/
void unmask(word_t irq)
{
u8_t mask_cache = in_u8(base+1);
mask_cache &= ~(1 << (irq));
out_u8(base+1, mask_cache);
}
/**
* Mask interrupt
* @param irq interrupt line to mask
*/
void mask(word_t irq)
{
u8_t mask_cache = in_u8(base+1);
mask_cache |= (1 << (irq));
out_u8(base+1, mask_cache);
}
/**
* Send specific EOI
* @param irq interrupt line to ack
*/
void ack(word_t irq)
{
out_u8(base, 0x60 + irq);
}
/**
* Send specific EOI
* @param irq interrupt line to ack
*/
bool is_masked(word_t irq)
{
return (mask_cache & (1 << irq));
}
/**
* initialize PIC
* @param vector_base 8086-style vector number base
* @param slave_info slave mask for master or slave id for slave
*
* Initializes the PIC in 8086-mode:
* - not special-fully-nested mode
* - reporting vectors VECTOR_BASE...VECTOR_BASE+7
* - all inputs masked
*/
void init(u8_t vector_base, u8_t slave_info)
{
mask_cache = 0xFF;
/*
ICW1:
0x10 | NEED_ICW4 | CASCADE_MODE | EDGE_TRIGGERED
*/
out_u8(base, 0x11);
/*
ICW2:
- 8086 mode irq vector base
PIN0->IRQ(base), ..., PIN7->IRQ(base+7)
*/
out_u8(base+1, vector_base);
/*
ICW3:
- master: slave list
Set bits mark input PIN as connected to a slave
- slave: slave id
This PIC is connected to the master's pin SLAVE_ID
Note: The caller knows whether its a master or not -
the handling is the same.
*/
out_u8(base+1, slave_info);
/*
ICW4:
8086_MODE | NORMAL_EOI | NONBUFFERED_MODE | NOT_SFN_MODE
*/
out_u8(base+1, 0x01); /* mode - *NOT* fully nested */
/*
OCW1:
- set initial mask
*/
out_u8(base+1, mask_cache);
//out_u8(base, 0x20);
}
};
#endif /* !__PLATFORM__PC99__8259_H__ */
| [
"[email protected]"
] | |
eefaaf4ef3066c21a8e82df1ea29aded20440d84 | b0e72f95e6dda5221fc1a7a655c00d93ea950534 | /Square.cpp | cc353cef8fc3f7e1aca382eba4f62c89e29d0f0f | [] | no_license | tahsinsiad/Problemsolving | 5a2d5d11739c9780d8af19a625d4f1eb8149be1e | 930454ad4f485864694bdc65a7f3ff4c9c5bee3d | refs/heads/master | 2020-03-28T01:04:22.883428 | 2018-09-05T07:30:43 | 2018-09-05T07:30:43 | 147,474,553 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | cpp | #include <iostream>
using namespace std;
int main()
{
long long N;
cin>>N;
if (N<9)
{
cout<<"0"<<endl;
}
else if (N==9)
cout <<"8"<< endl;
else
{
cout << 72 ;
for (int i=10;i<N;i++)
{
cout<<"0";
}
cout<<endl;
}
return 0;
}
| [
"[email protected]"
] | |
40ff60d85f346369dc0ebbad9510e10b0f6f9a7c | e3e3bf2a8cb16c8e87139237a7f03aa6807f7f2c | /cell_based/src/writers/population_count_writers/CellProliferativePhasesCountWriter.hpp | b670df90348254186b3d5917e61d6da87a50a233 | [
"BSD-3-Clause"
] | permissive | uofs-simlab/ChasteOS | f67b67f246befbc38edc3dc93b5e55a7bbf1fcfc | 04d98998e2ebad3f29086b8eaa1d89c08c6fccf6 | refs/heads/master | 2021-05-07T04:10:38.591384 | 2017-11-20T15:48:06 | 2017-11-20T15:48:06 | 111,127,403 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,954 | hpp | /*
Copyright (c) 2005-2016, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CELLPROLIFERATIVEPHASESCOUNTWRITER_HPP_
#define CELLPROLIFERATIVEPHASESCOUNTWRITER_HPP_
#include "AbstractCellPopulationCountWriter.hpp"
#include "ChasteSerialization.hpp"
#include <boost/serialization/base_object.hpp>
/**
* A class written using the visitor pattern for writing the number of cells in each proliferative phase to file.
*
* The output file is called cellcyclephases.dat by default.
*/
template<unsigned ELEMENT_DIM, unsigned SPACE_DIM>
class CellProliferativePhasesCountWriter : public AbstractCellPopulationCountWriter<ELEMENT_DIM, SPACE_DIM>
{
private:
/** Needed for serialization. */
friend class boost::serialization::access;
/**
* Serialize the object and its member variables.
*
* @param archive the archive
* @param version the current version of this class
*/
template<class Archive>
void serialize(Archive & archive, const unsigned int version)
{
archive & boost::serialization::base_object<AbstractCellPopulationCountWriter<ELEMENT_DIM, SPACE_DIM> >(*this);
}
public:
/**
* Default constructor.
*/
CellProliferativePhasesCountWriter();
/**
* Visit the population and write the number of cells in the population that have each proliferative phase.
*
* Outputs a line of tab-separated values of the form:
* [num G0 phase] [num G1 phase] [num S phase] [num G2 phase] [num M phase]
*
* where [num G0 phase] denotes the number of cells in the population that are in G0 phase,
* and so on. These counts are computed through the cell population method GetCellCyclePhaseCount().
*
* This line is appended to the output written by AbstractCellBasedWriter, which is a single
* value [present simulation time], followed by a tab.
*
* @param pCellPopulation the population to write.
*/
void VisitAnyPopulation(AbstractCellPopulation<SPACE_DIM, SPACE_DIM>* pCellPopulation);
/**
* Visit the population and write the number of cells in the population that have each proliferative phase.
*
* Outputs a line of tab-separated values of the form:
* [num G0 phase] [num G1 phase] [num S phase] [num G2 phase] [num M phase]
*
* where [num G0 phase] denotes the number of cells in the population that are in G0 phase,
* and so on. These counts are computed through the cell population method GetCellCyclePhaseCount().
*
* This line is appended to the output written by AbstractCellBasedWriter, which is a single
* value [present simulation time], followed by a tab.
*
* @param pCellPopulation a pointer to the MeshBasedCellPopulation to visit.
*/
virtual void Visit(MeshBasedCellPopulation<ELEMENT_DIM, SPACE_DIM>* pCellPopulation);
/**
* Visit the population and write the number of cells in the population that have each proliferative phase.
*
* Outputs a line of tab-separated values of the form:
* [num G0 phase] [num G1 phase] [num S phase] [num G2 phase] [num M phase]
*
* where [num G0 phase] denotes the number of cells in the population that are in G0 phase,
* and so on. These counts are computed through the cell population method GetCellCyclePhaseCount().
*
* This line is appended to the output written by AbstractCellBasedWriter, which is a single
* value [present simulation time], followed by a tab.
*
* @param pCellPopulation a pointer to the CaBasedCellPopulation to visit.
*/
virtual void Visit(CaBasedCellPopulation<SPACE_DIM>* pCellPopulation);
/**
* Visit the population and write the number of cells in the population that have each proliferative phase.
*
* Outputs a line of tab-separated values of the form:
* [num G0 phase] [num G1 phase] [num S phase] [num G2 phase] [num M phase]
*
* where [num G0 phase] denotes the number of cells in the population that are in G0 phase,
* and so on. These counts are computed through the cell population method GetCellCyclePhaseCount().
*
* This line is appended to the output written by AbstractCellBasedWriter, which is a single
* value [present simulation time], followed by a tab.
*
* @param pCellPopulation a pointer to the NodeBasedCellPopulation to visit.
*/
virtual void Visit(NodeBasedCellPopulation<SPACE_DIM>* pCellPopulation);
/**
* Visit the population and write the number of cells in the population that have each proliferative phase.
*
* Outputs a line of tab-separated values of the form:
* [num G0 phase] [num G1 phase] [num S phase] [num G2 phase] [num M phase]
*
* where [num G0 phase] denotes the number of cells in the population that are in G0 phase,
* and so on. These counts are computed through the cell population method GetCellCyclePhaseCount().
*
* This line is appended to the output written by AbstractCellBasedWriter, which is a single
* value [present simulation time], followed by a tab.
*
* @param pCellPopulation a pointer to the PottsBasedCellPopulation to visit.
*/
virtual void Visit(PottsBasedCellPopulation<SPACE_DIM>* pCellPopulation);
/**
* Visit the population and write the number of cells in the population that have each proliferative phase.
*
* Outputs a line of tab-separated values of the form:
* [num G0 phase] [num G1 phase] [num S phase] [num G2 phase] [num M phase]
*
* where [num G0 phase] denotes the number of cells in the population that are in G0 phase,
* and so on. These counts are computed through the cell population method GetCellCyclePhaseCount().
*
* This line is appended to the output written by AbstractCellBasedWriter, which is a single
* value [present simulation time], followed by a tab.
*
* @param pCellPopulation a pointer to the VertexBasedCellPopulation to visit.
*/
virtual void Visit(VertexBasedCellPopulation<SPACE_DIM>* pCellPopulation);
};
#include "SerializationExportWrapper.hpp"
// Declare identifier for the serializer
EXPORT_TEMPLATE_CLASS_ALL_DIMS(CellProliferativePhasesCountWriter)
#endif /*CELLPROLIFERATIVEPHASESCOUNTWRITER_HPP_*/
| [
"[email protected]"
] | |
2877b2fca1ea1c2e0bd521a1799cf6269eeae637 | 402269ff148adba75ef7f58fbcd23771ee92fff9 | /writeAB.cpp | 5fd512327e50f7a26b14eece44055cfcd006a24e | [] | no_license | seagods/myContinuedFracs | 8f081d867a799b3c1c146c5edb8d4b318523352b | ea7551de77b67d8e0d0ba085b333363cfd99717c | refs/heads/master | 2021-02-07T09:42:51.056897 | 2020-03-18T16:46:44 | 2020-03-18T16:46:44 | 244,010,669 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,949 | cpp | #include <stdio.h> //standard input output
#include <iostream> // input output (cin cout etc)
#include <fstream> //file stream
#include <stdlib.h> //string conversion + malloc and calloc
#include <math.h>
/* *************************************
USEFUL DOCOMENTATION IN
/libsMSwin/SOURCES/gmp-6.1.2/doc/gmp/index.htm
/libsMSwin/SOURCES/gmp-6.1.2/doc/gmp/GMP-basics.htm etc,
Sizes of types for g++ compiler
char=1 byte
short int = 2 bytes
int = 4 bytes
long int=4 bytes
long long int=8 bytes
check your compiler to see if they same for you!
*/
#include "C:\myIncludez\GMPfrac_Headers\GMPfrac.h"
//We are using C++ interface for GMP
using namespace::std;
main(){
ofstream writedata_out;
bool showit=false; bool printit=true;
writedata_out.open("ABdata.dat",ios::out);
bool sgn;
mpz_class a1,b1,c1;
mpz_class a2,b2,c2;
mpz_class ZERO; mpz_class ONE;
ZERO=0; ONE=1;
int ntermsmax=90;
int nterms=ntermsmax;
sgn=true;
mpz_class avec[ntermsmax+1],bvec[ntermsmax+1];
//MUST initialise
for(int i=0;i<=ntermsmax;i++){
avec[i]=ZERO; bvec[i]=ONE; }
int iopt=1;
cout << "iopt=1, Huygens CF for pi (15 terms max)\n";
cout << "iopt=2, pi=3+1^2||6+3^2||6+5^2||6+7^2||6+...\n";
cout << "iopt=3, pi=0+4||1^2+1||2^2+3|3^2||5+4^2||7+...\n";
cout << "iopt=4, pi=2+2||1+1*2||1+2*3||1+3*4||1+4*5||1+...";
cout << "iopt=5, pi=2+4||3+1*3||4+3*5||4+5*7||4+7*9||4+...";
cout << "iopt=6, pi=0+4||1+(1^2)||2+3^2||2+5^2||2+...\n";
cout << "iopt=7, 4/pi=1+1^2||2+3^2||2+(5^2)||7^2||2+...\n";
//Brouncker's continued fraction
cout << "iopt=8 e=2+... (a_n=1), (b_n=2,1,1,4,1,1,6,1,1,8,1,1,10...\n";
cout << "enter iopt\n";
cin >> iopt;
cout << "enter number of terms\n";
cin >> nterms;
int k=0;
//k is for kounting
if(iopt==1 && nterms>15){ cout << "nterms must be less than 15 for iopt=1"; exit(0); }
if(nterms>ntermsmax){ cout << "reducing nterms to ntermsmax=" << ntermsmax; nterms=ntermsmax; }
if(iopt>8){ cout << "No series for this value of iopt!\n"; exit(0); }
if(iopt==1){
for(int i=0;i<nterms;i++){avec[i]=1; }
avec[0]=0;
bvec[0]=3; bvec[1]=7; bvec[2]=15; bvec[3]=1; bvec[4]=292;
bvec[5]=1; bvec[6]=1; bvec[7]=1; bvec[8]=2; bvec[9]=2;
bvec[10]=3; bvec[11]=1; bvec[12]=14; bvec[13]=2; bvec[14]=1;
}
if(iopt==2){
for(int i=0;i<nterms;i++){
k=2*i-1; //avec[0] doesn't exist!
avec[i]=k*k; bvec[i]=6;
}
bvec[0]=3;
avec[0]=0;
}
if(iopt==3){
for(int i=0;i<nterms;i++){
k=2*i-1; //avec[0] doesn't exist!
avec[i]=(i-1)*(i-1); bvec[i]=k;
}
bvec[0]=0;
avec[0]=0;
avec[1]=4;
}
if(iopt==4){
for(int i=0;i<nterms;i++){
k=2*i-1; //avec[0] doesn't exist!
avec[i]=(i+1)*(i); bvec[i]=1;
}
bvec[0]=2;
avec[0]=2;
}
if(iopt==5){
for(int i=0;i<nterms;i++){
k=2*i-1; //avec[0] doesn't exist!
avec[i]=(k-2)*(k); bvec[i]=4;
}
bvec[0]=2;
bvec[1]=3;
avec[0]=0;
avec[1]=4;
}
if(iopt==6){
for(int i=0;i<nterms;i++){
k=2*i-1; //avec[0] doesn't exist!
avec[i]=(k-2)*(k-2); bvec[i]=2;
}
bvec[0]=0;
bvec[1]=1;
avec[0]=0;
avec[1]=4;
}
if(iopt==7){
//Brounkers CF for 4/pi
for(int i=0;i<nterms;i++){
k=2*i-1; //avec[0] doesn't exist!
avec[i]=(k)*(k); bvec[i]=2;
}
bvec[0]=0;
avec[0]=0;
}
if(iopt==8){
//Brounkers CF for 4/pi
for(int i=0;i<nterms;i++){
k=2*i-1; //avec[0] doesn't exist!
avec[i]=(k)*(k); bvec[i]=2;
}
bvec[0]=0;
avec[0]=0;
}
// -lgmpxx means that we can just use an overloaded <<
// NOTE: overloaded << doesn't support things like << a+b;
writedata_out << nterms << " " << iopt << endl;
for(int i=0;i<nterms;i++){
writedata_out << i << " " << avec[i] << " " << bvec[i] << endl;
}
writedata_out.close();
}
| [
"[email protected]"
] | |
ffede643b6ce2285f7b7bc0738600992cc1d2e81 | 30f1ea99942ebeca2d91eb83b338f6bb0f8cda8a | /fsm/boost/mpl/aux_/preprocessor/is_seq.hpp | c49d21f87be48f7e061dc6eae45d6892aa16ea92 | [] | no_license | thinkincforeveryone/putty-nd6x | 8d085839b72ad07092eb1b194e0a9b397a8c8ffd | e3efbcdf22bd5323004dccccafd81ce11a359a2f | refs/heads/master | 2020-09-26T18:04:11.415969 | 2019-12-06T10:50:35 | 2019-12-06T10:50:35 | 226,306,231 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,177 | hpp |
#ifndef BOOST_MPL_AUX_PREPROCESSOR_IS_SEQ_HPP_INCLUDED
#define BOOST_MPL_AUX_PREPROCESSOR_IS_SEQ_HPP_INCLUDED
// Copyright Paul Mensonides 2003
// Copyright Aleksey Gurtovoy 2003-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: is_seq.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-10 23:19:02 -0700 (Fri, 10 Oct 2008) $
// $Revision: 49267 $
#include <boost/preprocessor/seq/size.hpp>
#include <boost/preprocessor/arithmetic/dec.hpp>
#include <boost/preprocessor/punctuation/paren.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/config/config.hpp>
// returns 1 if 'seq' is a PP-sequence, 0 otherwise:
//
// BOOST_PP_ASSERT( BOOST_PP_NOT( BOOST_MPL_PP_IS_SEQ( int ) ) )
// BOOST_PP_ASSERT( BOOST_MPL_PP_IS_SEQ( (int) ) )
// BOOST_PP_ASSERT( BOOST_MPL_PP_IS_SEQ( (1)(2) ) )
#if (BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_BCC()) || defined(_MSC_VER) && defined(__INTEL_COMPILER) && __INTEL_COMPILER == 1010
# define BOOST_MPL_PP_IS_SEQ(seq) BOOST_PP_DEC( BOOST_PP_SEQ_SIZE( BOOST_MPL_PP_IS_SEQ_(seq) ) )
# define BOOST_MPL_PP_IS_SEQ_(seq) BOOST_MPL_PP_IS_SEQ_SEQ_( BOOST_MPL_PP_IS_SEQ_SPLIT_ seq )
# define BOOST_MPL_PP_IS_SEQ_SEQ_(x) (x)
# define BOOST_MPL_PP_IS_SEQ_SPLIT_(unused) unused)((unused)
#else
# if BOOST_PP_CONFIG_FLAGS() & BOOST_PP_CONFIG_MWCC()
# define BOOST_MPL_PP_IS_SEQ(seq) BOOST_MPL_PP_IS_SEQ_MWCC_((seq))
# define BOOST_MPL_PP_IS_SEQ_MWCC_(args) BOOST_MPL_PP_IS_SEQ_ ## args
# else
# define BOOST_MPL_PP_IS_SEQ(seq) BOOST_MPL_PP_IS_SEQ_(seq)
# endif
# define BOOST_MPL_PP_IS_SEQ_(seq) BOOST_PP_CAT(BOOST_MPL_PP_IS_SEQ_, BOOST_MPL_PP_IS_SEQ_0 seq BOOST_PP_RPAREN())
# define BOOST_MPL_PP_IS_SEQ_0(x) BOOST_MPL_PP_IS_SEQ_1(x
# define BOOST_MPL_PP_IS_SEQ_ALWAYS_0(unused) 0
# define BOOST_MPL_PP_IS_SEQ_BOOST_MPL_PP_IS_SEQ_0 BOOST_MPL_PP_IS_SEQ_ALWAYS_0(
# define BOOST_MPL_PP_IS_SEQ_BOOST_MPL_PP_IS_SEQ_1(unused) 1
#endif
#endif // BOOST_MPL_AUX_PREPROCESSOR_IS_SEQ_HPP_INCLUDED
| [
"[email protected]"
] | |
f94887be41dac2d97388a4a49dd84f6815829db0 | 591981da620df8074a996a45aa2fd1221d41c6c7 | /C Lessons/Userdefined Function/e.cpp | 3ba063f69812a7dd6edccb0518c534f1885c72c3 | [] | no_license | nngniraj/LearnCandCpp | 01771d298ac8941082cd3341d5303b48c95cee99 | 24e01fca6320687871bac6aa957e025141601382 | refs/heads/main | 2023-04-20T10:30:17.992003 | 2021-05-10T17:25:10 | 2021-05-10T17:25:10 | 366,121,275 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 351 | cpp | #include <stdio.h>
int main(){
char answer;
printf("\nWould you like to play? Enter Y or N: \n");
scanf(" %c", &answer);
printf("\n answer is %c\n", answer);
while (answer == 'Y'){
printf("Success!");
printf("\nDo you want to play again? Y or N: \n");
scanf(" %c", &answer);
printf("\n answer is %c\n", answer);
}
printf("GoodBye!");
return 0;
}
| [
"[email protected]"
] | |
fa94c572de4b8f6ce52ef3c108c3589445ae27ba | ee3b3f4d6fab9f7a092cbf21190916c46f88738b | /inc/MusicPlayerView.h | 5b78f98db7271fd7974c858d8be44c030dc4f29c | [] | no_license | lohanf/MLauncher | 5bb49de57d32e09df70bc4fd82517112b89c5d61 | cf080490cf0e11fd6507c69118978845aee7855d | refs/heads/master | 2021-01-22T17:57:38.948206 | 2013-04-06T06:42:56 | 2013-04-06T06:42:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,093 | h | /*
============================================================================
Name : MusicPlayerView.h
Author : Florin Lohan
Version : 1.0
Copyright : Florin Lohan
Description : CMusicPlayerView declaration
============================================================================
*/
#ifndef MUSICPLAYERVIEW_H
#define MUSICPLAYERVIEW_H
// INCLUDES
#include <aknview.h>
#include <MdaAudioSamplePlayer.h>
#include <remconcoreapitargetobserver.h>
#include <remconcoreapi.h>
#include <hwrmlight.h> //light manager
#include <aknkeylock.h>
#include <eiklbo.h> //list box observer
#include "TrackInfo.h"
#include "MLauncherAppUi.h"
#include "defs.h"
#ifdef __S60_32__
#include <maudiooutputobserver.h>
#endif
#ifdef __S60_50__
#include <accmonitor.h>
#endif
class CAudioEqualizerUtility;
class CBassBoost;
class CStereoWidening;
class CLoudness;
class CMusicPlayerContainer;
class CMLauncherPreferences;
class CRemConInterfaceSelector;
class CRemConCoreApiTarget;
class CMusicPlayerTelObs;
class CMusicPlayerView;
class CThemeManager;
class CTheme;
// CLASS DECLARATION
class CMetadata : public CBase
{
public:
CMetadata();
~CMetadata();
void Recycle();
void SetStringL(HBufC **aOwnString, const TDesC& aValue);
public:
HBufC *iTitle;
HBufC *iArtist;
HBufC *iAlbum;
HBufC *iGenre;
TFileDirEntry *iFileDirEntry;//not owned
TUint16 iDuration; //in seconds
TUint16 iTrack;
TUint16 iYear;
TUint16 iKbps;
HBufC8 *iCover;
};
class CTrack : public CBase, public MMdaAudioPlayerCallback
#ifdef __S60_32__
, public MAudioOutputObserver
#endif
{
public:
enum TPlayerStates
{
EStateNotInitialized=0,
EStateInitializing,
EStateInitialized, //or paused or stopped
EStatePlaying,
EStateInitializationFailed,
};
enum TFlags
{
EStartPlaying=1,
EKilledByTelephony=2,
ERegistered=4,
EPauseNeededWhenSeeking=8,
EVolumeAndEffectsApplied=16
};
public:
CTrack(CMusicPlayerView &aView);
~CTrack();
void Recycle();
void InitializeL(TFileDirEntry *iEntry, TBool aStartPlaying);
void StartPlaying(CTrack *aFadeOutTrack);
void RestartPlaying();
TBool HasFadeOutTrack(){return (TBool)iFadeOutTrack;}
void Stop();
void End(); //stops the playing, announces end of song
TInt Pause();
void SetPosition(const TTimeIntervalMicroSeconds &aPosition);
TInt GetPosition(TTimeIntervalMicroSeconds &aPosition);
const TTimeIntervalMicroSeconds &Duration();
//TInt GetVolume(TInt &aVolume);
//void SetVolume(TInt aVolume);
void SetVolumeFromView();
void ClearFadeOutTrackIfEqual(CTrack *aTrack){if(aTrack==iFadeOutTrack)iFadeOutTrack=NULL;}
CMdaAudioPlayerUtility* MdaPlayer(){return iMdaPlayer;}
protected: //from MMdaAudioPlayerCallback
virtual void MapcInitComplete(TInt aError, const TTimeIntervalMicroSeconds &aDuration);
virtual void MapcPlayComplete(TInt aError);
#ifdef __S60_32__
private: //from MAudioOutputObserver + own
void DefaultAudioOutputChanged(CAudioOutput& aAudioOutput, CAudioOutput::TAudioOutputPreference aNewDefault);
//own:
void RegisterAudioOutput(CMdaAudioPlayerUtility &aUtility);
#endif
private:
TInt GetMetadata();
void Play();
public:
//track info
TUint iFlags;
TPlayerStates iState;
CMetadata iMetadata;
private:
CTrack *iFadeOutTrack; //not owned
CMdaAudioPlayerUtility *iMdaPlayer;
CMusicPlayerView &iView;
TInt iVolumeStep,iMaxVolume; //we compute them once
#ifdef __S60_32__
CAudioOutput *iAudioOutput;
CAudioOutput::TAudioOutputPreference iCurrentAudioOutput;
#endif
};
/**
* CMusicPlayerView
*
*/
class CMusicPlayerView : public CAknView, public MRemConCoreApiTargetObserver/*, public MHWRMLightObserver*/
#ifdef __S60_50__
, public MAccMonitorObserver
#endif
{
public: //needed in the container as well
enum TFlags
{
EIsVisible=1,
//EGoToNextSong=2, //play the next song when it is done initializing
//EGoToPrevSong=4, //play the previous song when it is done initializing
ESongPreview=8,
EIsPlaying=16,
ESeekFirstPress=32,
EWasPausedBeforeSeek=64,
//EPeriodicWorkerStopDelayed=128,
EAllowScrolling=256,
ECrossfadingCannotBeUsed=512, //because we have BT headset/headphones and crossfading does not work with them
EReactivateCIdleAfterImgProcessingEnds=1024,
//last 8 bits used for typematic
EVolumeUpPressed=0x01000000,
EVolumeDownPressed=0x02000000,
EFastForwardPressed=0x04000000,
ERewindPressed=0x08000000
};
enum TIdleWorkerJobs
{
EJobConstruct2=1,
EJobPrepareNextSong=2,
EJobStartCrossfadingTimer=4,
EJobWaitSomeSeconds=8,
EJobAllowScrolling=16,
EJobInitNextSong=32,
};
enum TEffects
{
EBassBoost=1,
EStereoWidening,
ELoudness
};
public:
// Constructors and destructor
/**
* Destructor.
*/
~CMusicPlayerView();
/**
* Two-phased constructor.
*/
static CMusicPlayerView* NewL();
/**
* Two-phased constructor.
*/
static CMusicPlayerView* NewLC();
public: // from CAknView
TUid Id() const;
void DoActivateL(const TVwsViewId& aPrevViewId,TUid aCustomMessageId, const TDesC8& aCustomMessage);
void DoDeactivate();
// from MEikMenuObserver
void DynInitMenuPaneL(TInt aResourceId, CEikMenuPane *aMenuPane);
/**
* From CEikAppUi, HandleCommandL.
* Takes care of command handling.
* @param aCommand Command to be handled.
*/
void HandleCommandL(TInt aCommand);
void HandleForegroundEventL(TBool aForeground);
private:
//from MRemConCoreApiTargetObserver
void MrccatoCommand(TRemConCoreApiOperationId aOperationId, TRemConCoreApiButtonAction aButtonAct);
//from MHWRMLightObserver
//void LightStatusChanged(TInt aTarget, CHWRMLight::TLightStatus aStatus);
public: //own
CMLauncherAppUi* MyAppUi(){return (CMLauncherAppUi*)AppUi();};
TInt StartPlaylistL(CPlaylist *aPlaylist, TBool aIsPreview, TBool aStartPlaying);
TBool PlayPauseStop(TBool aStop); //aStop==ETrue if the command is to stop playback. Function returns ETrue if music is playing
void NextPreviousL(TInt aJump, TBool aCrossfade=EFalse); //aJump should be either 1 or -1
TInt Seek(TBool aFirstSeek,TBool aSeekForward, TTimeIntervalMicroSeconds *aPositionObserver=NULL);
void SeekEnd();//restores the state (play/pause) from before seek started
void ResumePlayback();
void VolumeUpDown(TBool aUp);
void StartTypematicL(TFlags aKeyPressed);
void StopTypematic();
static TInt TypematicCallback(TAny* aInstance);
void TrackInitializationComplete(CTrack *aTrack);
void TrackPlaybackComplete(CTrack *aTrack, TBool aEndedByItself);
void PrepareNextSongL();
void StartCrossfadingTimer();
void CurrentTrackInitializationComplete(); //called by the current theme
void SetStatusPaneVisibility();
void SaveBeforeExit();
TBool IsCrossfadingAllowed() const;
TBool IsCrossfadingUsed() const;
// Idle worker
TInt IdleWorker();
void ScheduleWorkerL(TInt aJobs);
TBool IsImgProcessingOngoing();
void ClearPlaylist();
//equalizer & effects
void EqualizerChanged(TInt aValue); //aValue can be a preset or an effect
void ApplyEqualizerPresetAndEffectsL(CMdaAudioPlayerUtility *aCurrentTrack);
void DeleteEqualizerAndEffectsL(); //applied to current track (iEEcurrent)
CDesCArrayFlat* GetEqualizerPresetsAndEffectsL(TInt aSelected, TBool aBassBoost, TBool aStereoWidening, TBool aLoudness);
TInt SetEqualizerPresetL(); //the preset to select is in iPreferences
TInt SetEffect(enum TEffects aEffect); //value taken from preferences
#ifdef __MSK_ENABLED__
void SetMSKPlayPause(TBool aPlay);
#endif
#ifdef __S60_50__
private: //from MAccMonitorObserver + own
void ConnectedL(CAccMonitorInfo* aAccessoryInfo);
void DisconnectedL(CAccMonitorInfo* aAccessoryInfo);
void AccMonitorObserverError(TInt /*aError*/){};
void StartMonitoringAccessories();
#endif
private:
//equalizer
void SelectEqualizerPresetL(); //returns ETrue if the selection changed
void JumpToSongL(TInt aJump, TBool aCrossfade);
static TInt CrossfadingStarter(TAny* aInstance);
static TInt WaitFuntion(TAny* aInstance);
//void CrossfadeToNextSong();
void StartPeriodicWorker();
void StopPeriodicWorker();
static TInt PeriodicFunction(TAny* aInstance);
private:
/**
* Constructor for performing 1st stage construction
*/
CMusicPlayerView();
/**
* EPOC default constructor for performing 2nd stage construction
*/
void ConstructL();
void Construct2L();
private: // Data
// idle worker
CPeriodic *iIdleDelayer;
TUint iJobsSaved;
CMusicPlayerTelObs *iTelObs;
//CHWRMLight *iLight; //this is in this class (and not in the container) so we do not initialize it each time we activate the container
RAknKeylock2 iLock;
CPeriodic *iTypematic;
#ifdef __MSK_ENABLED__
//MSK labels
HBufC *iMskPlay;
HBufC *iMskPause;
#endif
//TInt iIndex;
//seek
TInt iSeekIndex;
//volume
CRemConInterfaceSelector *iInterfaceSelector;
CRemConCoreApiTarget *iCoreTarget;
//next & previous track
CTrack *iNextTrack;
CTrack *iPrevTrack;
//how many times in a row initialization failed
TInt iNrFailedTracksInARow;
public:
CPlaylist *iPlaylist; //not owned
CTrack *iTrack;
TTimeIntervalMicroSeconds iPlaybackPosition;
TTimeIntervalMicroSeconds iTargetPlaybackPosition;
CPeriodic *iPeriodic;
TInt iStopDelay;
//TTime iStartTime; //time when current track started (excluding pause)
//crossfading
CPeriodic *iCrossfadingTimer;
TUint iFlags; //public, so the container can access them
//volume
//TInt *iVolume; //pointer to CMLauncherPreferences::iVolume, not owned
/**
* The container
* Owned by us
*/
CMusicPlayerContainer* iMusicPlayerContainer;
CMLauncherPreferences *iPreferences; //not owned, public so that the container can access them
CThemeManager *iThemeManager;
#ifdef __S60_50__
CAccMonitor *iAccMonitor;
#endif
//periodic worker
TUint iJobs; //jobs for the idle worker, see flags above
//equalizer & effects
CMdaAudioPlayerUtility *iEEcurrent;
CAudioEqualizerUtility *iEqualizerUtility;
TInt iNrPresets; //does NOT include the "equalizer off"
CBassBoost *iBassBoost;
CStereoWidening *iStereoWidening;
CLoudness *iLoudness;
};
#endif // MUSICPLAYERVIEW_H
| [
"[email protected]"
] | |
8f7c8ac6e25a50c71b77c30b057c1a1c9ea2e845 | 25183dd739ccb36603083b8efbe1ff7a79de1b3d | /src/objects/descriptor-array-inl.h | 821323235b18bf2d443d722aba5ad5b7703fb4a4 | [
"BSD-3-Clause",
"SunPro",
"bzip2-1.0.6"
] | permissive | cc861010/v8 | 29d93a2021ca96cd56fac0578f01aea432552ccf | 2b96d8aa00a614843aaea55f0b3e3aece635b59d | refs/heads/master | 2020-04-13T10:42:34.940831 | 2018-12-26T03:06:23 | 2018-12-26T03:47:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,726 | h | // Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_OBJECTS_DESCRIPTOR_ARRAY_INL_H_
#define V8_OBJECTS_DESCRIPTOR_ARRAY_INL_H_
#include "src/objects/descriptor-array.h"
#include "src/field-type.h"
#include "src/heap/heap-write-barrier.h"
#include "src/heap/heap.h"
#include "src/isolate.h"
#include "src/lookup-cache.h"
#include "src/objects/heap-object-inl.h"
#include "src/objects/maybe-object.h"
#include "src/objects/struct-inl.h"
#include "src/property.h"
// Has to be the last include (doesn't have include guards):
#include "src/objects/object-macros.h"
namespace v8 {
namespace internal {
OBJECT_CONSTRUCTORS_IMPL(DescriptorArray, HeapObject)
OBJECT_CONSTRUCTORS_IMPL(EnumCache, Tuple2)
CAST_ACCESSOR2(DescriptorArray)
CAST_ACCESSOR2(EnumCache)
ACCESSORS2(DescriptorArray, enum_cache, EnumCache, kEnumCacheOffset)
RELAXED_INT16_ACCESSORS(DescriptorArray, number_of_all_descriptors,
kNumberOfAllDescriptorsOffset)
RELAXED_INT16_ACCESSORS(DescriptorArray, number_of_descriptors,
kNumberOfDescriptorsOffset)
RELAXED_INT16_ACCESSORS(DescriptorArray, raw_number_of_marked_descriptors,
kRawNumberOfMarkedDescriptorsOffset)
RELAXED_INT16_ACCESSORS(DescriptorArray, filler16bits, kFiller16BitsOffset)
inline int16_t DescriptorArray::number_of_slack_descriptors() const {
return number_of_all_descriptors() - number_of_descriptors();
}
inline int DescriptorArray::number_of_entries() const {
return number_of_descriptors();
}
inline int16_t DescriptorArray::CompareAndSwapRawNumberOfMarkedDescriptors(
int16_t expected, int16_t value) {
return base::Relaxed_CompareAndSwap(
reinterpret_cast<base::Atomic16*>(
FIELD_ADDR(this, kRawNumberOfMarkedDescriptorsOffset)),
expected, value);
}
void DescriptorArray::CopyEnumCacheFrom(DescriptorArray array) {
set_enum_cache(array->enum_cache());
}
int DescriptorArray::Search(Name name, int valid_descriptors) {
DCHECK(name->IsUniqueName());
return internal::Search<VALID_ENTRIES>(this, name, valid_descriptors,
nullptr);
}
int DescriptorArray::Search(Name name, Map map) {
DCHECK(name->IsUniqueName());
int number_of_own_descriptors = map->NumberOfOwnDescriptors();
if (number_of_own_descriptors == 0) return kNotFound;
return Search(name, number_of_own_descriptors);
}
int DescriptorArray::SearchWithCache(Isolate* isolate, Name name, Map map) {
DCHECK(name->IsUniqueName());
int number_of_own_descriptors = map->NumberOfOwnDescriptors();
if (number_of_own_descriptors == 0) return kNotFound;
DescriptorLookupCache* cache = isolate->descriptor_lookup_cache();
int number = cache->Lookup(map, name);
if (number == DescriptorLookupCache::kAbsent) {
number = Search(name, number_of_own_descriptors);
cache->Update(map, name, number);
}
return number;
}
ObjectSlot DescriptorArray::GetFirstPointerSlot() {
return RawField(DescriptorArray::kPointersStartOffset);
}
ObjectSlot DescriptorArray::GetDescriptorSlot(int descriptor) {
// Allow descriptor == number_of_all_descriptors() for computing the slot
// address that comes after the last descriptor (for iterating).
DCHECK_LE(descriptor, number_of_all_descriptors());
return RawField(OffsetOfDescriptorAt(descriptor));
}
ObjectSlot DescriptorArray::GetKeySlot(int descriptor) {
DCHECK_LE(descriptor, number_of_all_descriptors());
ObjectSlot slot = GetDescriptorSlot(descriptor) + kEntryKeyIndex;
DCHECK((*slot)->IsObject());
return slot;
}
Name DescriptorArray::GetKey(int descriptor_number) const {
DCHECK(descriptor_number < number_of_descriptors());
return Name::cast(
get(ToKeyIndex(descriptor_number))->GetHeapObjectAssumeStrong());
}
int DescriptorArray::GetSortedKeyIndex(int descriptor_number) {
return GetDetails(descriptor_number).pointer();
}
Name DescriptorArray::GetSortedKey(int descriptor_number) {
return GetKey(GetSortedKeyIndex(descriptor_number));
}
void DescriptorArray::SetSortedKey(int descriptor_index, int pointer) {
PropertyDetails details = GetDetails(descriptor_index);
set(ToDetailsIndex(descriptor_index),
MaybeObject::FromObject(details.set_pointer(pointer).AsSmi()));
}
MaybeObjectSlot DescriptorArray::GetValueSlot(int descriptor) {
DCHECK_LT(descriptor, number_of_descriptors());
return MaybeObjectSlot(GetDescriptorSlot(descriptor) + kEntryValueIndex);
}
Object* DescriptorArray::GetStrongValue(int descriptor_number) {
DCHECK(descriptor_number < number_of_descriptors());
return get(ToValueIndex(descriptor_number))->cast<Object>();
}
void DescriptorArray::SetValue(int descriptor_index, Object* value) {
set(ToValueIndex(descriptor_index), MaybeObject::FromObject(value));
}
MaybeObject DescriptorArray::GetValue(int descriptor_number) {
DCHECK_LT(descriptor_number, number_of_descriptors());
return get(ToValueIndex(descriptor_number));
}
PropertyDetails DescriptorArray::GetDetails(int descriptor_number) {
DCHECK(descriptor_number < number_of_descriptors());
MaybeObject details = get(ToDetailsIndex(descriptor_number));
return PropertyDetails(details->ToSmi());
}
int DescriptorArray::GetFieldIndex(int descriptor_number) {
DCHECK_EQ(GetDetails(descriptor_number).location(), kField);
return GetDetails(descriptor_number).field_index();
}
FieldType DescriptorArray::GetFieldType(int descriptor_number) {
DCHECK_EQ(GetDetails(descriptor_number).location(), kField);
MaybeObject wrapped_type = GetValue(descriptor_number);
return Map::UnwrapFieldType(wrapped_type);
}
void DescriptorArray::Set(int descriptor_number, Name key, MaybeObject value,
PropertyDetails details) {
// Range check.
DCHECK(descriptor_number < number_of_descriptors());
set(ToKeyIndex(descriptor_number), MaybeObject::FromObject(key));
set(ToValueIndex(descriptor_number), value);
set(ToDetailsIndex(descriptor_number),
MaybeObject::FromObject(details.AsSmi()));
}
void DescriptorArray::Set(int descriptor_number, Descriptor* desc) {
Name key = *desc->GetKey();
MaybeObject value = *desc->GetValue();
Set(descriptor_number, key, value, desc->GetDetails());
}
void DescriptorArray::Append(Descriptor* desc) {
DisallowHeapAllocation no_gc;
int descriptor_number = number_of_descriptors();
DCHECK_LE(descriptor_number + 1, number_of_all_descriptors());
set_number_of_descriptors(descriptor_number + 1);
Set(descriptor_number, desc);
uint32_t hash = desc->GetKey()->Hash();
int insertion;
for (insertion = descriptor_number; insertion > 0; --insertion) {
Name key = GetSortedKey(insertion - 1);
if (key->Hash() <= hash) break;
SetSortedKey(insertion, GetSortedKeyIndex(insertion - 1));
}
SetSortedKey(insertion, descriptor_number);
}
void DescriptorArray::SwapSortedKeys(int first, int second) {
int first_key = GetSortedKeyIndex(first);
SetSortedKey(first, GetSortedKeyIndex(second));
SetSortedKey(second, first_key);
}
int DescriptorArray::length() const {
return number_of_all_descriptors() * kEntrySize;
}
MaybeObject DescriptorArray::get(int index) const {
DCHECK(index >= 0 && index < this->length());
return RELAXED_READ_WEAK_FIELD(this, offset(index));
}
void DescriptorArray::set(int index, MaybeObject value) {
DCHECK(index >= 0 && index < this->length());
RELAXED_WRITE_WEAK_FIELD(this, offset(index), value);
WEAK_WRITE_BARRIER(this, offset(index), value);
}
} // namespace internal
} // namespace v8
#include "src/objects/object-macros-undef.h"
#endif // V8_OBJECTS_DESCRIPTOR_ARRAY_INL_H_
| [
"[email protected]"
] | |
0cacc9fff64f6ee6325bd2b27a1740f7dc5e8c3b | cf11fae1f575a0ae94b243a3def424d6e5e508f4 | /SortingAndSearching/sort_anagrams.cpp | a553b55438a09749da2a4bea711683876dccf707 | [] | no_license | vcfrasineanu/Algorithms-and-Data-Structures | a669d62cdef81239773dad0200e51a5e358a7207 | 1000c54843e5b5a24fa5fdfd8e9b450633c5fc1b | refs/heads/master | 2020-12-11T05:22:05.257499 | 2016-08-15T20:25:27 | 2016-08-15T20:25:27 | 53,578,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,497 | cpp | /**
* Task: Given a list of strings (only lowercase letters), sort all strings
* such that all anagrams are next to each other
*/
// -----------------------------------------------------------------------------
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include <stdio.h>
using namespace std;
string get_key( string word )
{
int v[30];
unsigned int i;
for ( i=0; i<30; i++ ) v[i] = 0;
for ( i=0; i<word.size(); i++ ) v[(int)word[i] - 97]++;
stringstream ss;
for ( i=0; i<30; i++ )
{
if ( v[i] != 0 ) ss << ((char)(i+97))*v[i];
}
return ss.str();
}
// -----------------------------------------------------------------------------
void sort_anagrams( vector<string> vec )
{
map< string, vector<string> > mymap;
unsigned int i;
for ( i=0; i<vec.size(); i++ )
{
mymap[ get_key( vec[i] ) ].push_back( vec[i] );
}
map< string, vector<string> >::iterator it = mymap.begin();
while( it!=mymap.end() )
{
for ( i=0; i<it->second.size(); i++ )
{
cout << it->second[i] << " ";
}
it++;
}
cout << endl;
}
// -----------------------------------------------------------------------------
int main()
{
int size;
vector<string> vec;
string word;
cout << "Number of words: "; cin >> size;
getchar();
for ( int i=0; i<size; i++ )
{
getline( cin, word );
vec.push_back( word );
}
sort_anagrams( vec );
return 0;
}
// -----------------------------------------------------------------------------
| [
"[email protected]"
] | |
f30f94a1d0995d17062a0d7403ee5cefcde36677 | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/libs/asio/test/latency/high_res_clock.hpp | f1332266e7794b2768c91298a9f78410e29d032c | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,197 | hpp | //
// high_res_clock.hpp
// ~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef HIGH_RES_CLOCK_HPP
#define HIGH_RES_CLOCK_HPP
#include <sstd/boost/config.hpp>
#include <sstd/boost/cstdint.hpp>
#if defined(BOOST_ASIO_WINDOWS)
inline boost::uint64_t high_res_clock()
{
LARGE_INTEGER i;
QueryPerformanceCounter(&i);
return i.QuadPart;
}
#elif defined(__GNUC__) && defined(__x86_64__)
inline boost::uint64_t high_res_clock()
{
unsigned long low, high;
__asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high));
return (((boost::uint64_t)high) << 32) | low;
}
#else
#include <sstd/boost/date_time/posix_time/posix_time_types.hpp>
inline boost::uint64_t high_res_clock()
{
boost::posix_time::ptime now =
boost::posix_time::microsec_clock::universal_time();
boost::posix_time::ptime epoch(
boost::gregorian::date(1970, 1, 1),
boost::posix_time::seconds(0));
return (now - epoch).total_microseconds();
}
#endif
#endif // HIGH_RES_CLOCK_HPP
| [
"[email protected]"
] | |
7d594558e09af32997201837112ee4ff1c71f31e | e8a3c0b3722cacdb99e15693bff0a4333b7ccf16 | /Uva Oj/12802..Gift From the gods.cpp | d325e5915cb4c9254564edc1043de4d7207ae483 | [] | no_license | piyush1146115/Competitive-Programming | 690f57acd374892791b16a08e14a686a225f73fa | 66c975e0433f30539d826a4c2aa92970570b87bf | refs/heads/master | 2023-08-18T03:04:24.680817 | 2023-08-12T19:15:51 | 2023-08-12T19:15:51 | 211,923,913 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | cpp | #include<math.h>
#include<stdio.h>
int main()
{
long long int a, b, n, num, i, j, k, prime, x, y;
while(scanf("%lld",&n) == 1){
num = 0;
a = n * 2;
printf("%lld\n",a);
b = n;
while(b >= 1){
i = b % 10;
num = num * 10 + i;
b = b/10;
}
//printf("%lld", num)
if(num == n){
prime = 0;
j = sqrt(num);
for(x = 2; x <= j;x++){
if(num % x == 0){
prime = 1;
break;
}
}
if(prime == 0){
break;
}
}
}
return 0;
}
| [
"[email protected]"
] | |
09b3cd12f937cc89a33b79561d297004fe077aac | 027a9ac58e242f821908f19a6051b11f3e283b3d | /cocos2d/cocos/3d/CCTerrain.cpp | aba46b3eb0a7466add2eed7d9d27657461f52f16 | [] | no_license | Countly/countly-sdk-cocos2d-x | 59e4644eacae7b174451ef9c9beab69d24ad3a8c | 62673656741b2d0beb3f91110babcbd120e440ec | refs/heads/master | 2023-04-13T22:31:04.316043 | 2023-04-04T13:29:01 | 2023-04-04T13:29:01 | 39,017,405 | 13 | 11 | null | 2022-03-03T13:31:18 | 2015-07-13T14:34:30 | C++ | UTF-8 | C++ | false | false | 50,999 | cpp | /****************************************************************************
Copyright (c) 2015 Chukong Technologies Inc.
http://www.cocos2d-x.org
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 "CCTerrain.h"
USING_NS_CC;
#include <stdlib.h>
#include <CCImage.h>
#include "renderer/CCGLProgram.h"
#include "renderer/CCGLProgramCache.h"
#include "renderer/CCGLProgramState.h"
#include "renderer/CCRenderer.h"
#include "renderer/CCGLProgramStateCache.h"
#include "renderer/ccGLStateCache.h"
#include "renderer/CCRenderState.h"
#include "base/CCDirector.h"
#include "2d/CCCamera.h"
#include "base/CCEventType.h"
NS_CC_BEGIN
// check a number is power of two.
static bool isPOT(int number)
{
bool flag = false;
if((number>0)&&(number&(number-1))==0)
flag = true;
return flag;
}
Terrain * Terrain::create(TerrainData ¶meter, CrackFixedType fixedType)
{
Terrain * terrain = new (std::nothrow)Terrain();
terrain->setSkirtHeightRatio(parameter._skirtHeightRatio);
terrain->_terrainData = parameter;
terrain->_crackFixedType = fixedType;
terrain->_isCameraViewChanged = true;
//chunksize
terrain->_chunkSize = parameter._chunkSize;
bool initResult =true;
//init heightmap
initResult &= terrain->initHeightMap(parameter._heightMapSrc.c_str());
//init textures alpha map,detail Maps
initResult &= terrain->initTextures();
initResult &= terrain->initProperties();
terrain->autorelease();
if(!initResult)
{
CC_SAFE_DELETE(terrain);
}
return terrain;
}
bool Terrain::initProperties()
{
auto shader = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_3D_TERRAIN);
auto state = GLProgramState::create(shader);
setGLProgramState(state);
_stateBlock->setBlend(false);
_stateBlock->setDepthWrite(true);
_stateBlock->setDepthTest(true);
_stateBlock->setCullFace(true);
setDrawWire(false);
setIsEnableFrustumCull(true);
setAnchorPoint(Vec2(0,0));
return true;
}
void Terrain::draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &transform, uint32_t flags)
{
_customCommand.func = CC_CALLBACK_0(Terrain::onDraw, this, transform, flags);
renderer->addCommand(&_customCommand);
}
void Terrain::onDraw(const Mat4 &transform, uint32_t flags)
{
auto modelMatrix = getNodeToWorldTransform();
if(memcmp(&modelMatrix,&_terrainModelMatrix,sizeof(Mat4))!=0)
{
_terrainModelMatrix = modelMatrix;
_quadRoot->preCalculateAABB(_terrainModelMatrix);
}
auto glProgram = getGLProgram();
glProgram->use();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
if(_isDrawWire)
{
glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);
}else
{
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
}
#endif
_stateBlock->bind();
GL::enableVertexAttribs(1<<_positionLocation | 1 << _texcordLocation | 1<<_normalLocation);
glProgram->setUniformsForBuiltins(transform);
if(!_alphaMap)
{
glActiveTexture(GL_TEXTURE0);
GL::bindTexture2D(_detailMapTextures[0]->getName());
glUniform1i(_detailMapLocation[0],0);
glUniform1i(_alphaIsHasAlphaMapLocation,0);
}else
{
for(int i =0;i<_maxDetailMapValue;i++)
{
glActiveTexture(GL_TEXTURE0+i);
GL::bindTexture2D(_detailMapTextures[i]->getName());
glUniform1i(_detailMapLocation[i],i);
glUniform1f(_detailMapSizeLocation[i],_terrainData._detailMaps[i]._detailMapSize);
}
glUniform1i(_alphaIsHasAlphaMapLocation,1);
glActiveTexture(GL_TEXTURE4);
GL::bindTexture2D(_alphaMap->getName());
glUniform1i(_alphaMapLocation,4);
}
auto camera = Camera::getVisitingCamera();
if(memcmp(&_CameraMatrix,&camera->getViewMatrix(),sizeof(Mat4))!=0)
{
_isCameraViewChanged = true;
_CameraMatrix = camera->getViewMatrix();
}
if(_isCameraViewChanged )
{
auto m = camera->getNodeToWorldTransform();
//set lod
setChunksLOD(Vec3(m.m[12], m.m[13], m.m[14]));
}
if(_isCameraViewChanged )
{
_quadRoot->resetNeedDraw(true);//reset it
//camera frustum culling
_quadRoot->cullByCamera(camera,_terrainModelMatrix);
}
_quadRoot->draw();
if(_isCameraViewChanged)
{
_isCameraViewChanged = false;
}
glActiveTexture(GL_TEXTURE0);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
if(_isDrawWire)//reset state.
{
glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);
}
#endif
}
bool Terrain::initHeightMap(const char * heightMap)
{
_heightMapImage = new Image();
_heightMapImage->initWithImageFile(heightMap);
_data = _heightMapImage->getData();
_imageWidth =_heightMapImage->getWidth();
_imageHeight =_heightMapImage->getHeight();
//only the image size is the Powers Of Two(POT) or POT+1
if((isPOT(_imageWidth) &&isPOT(_imageHeight)) || (isPOT(_imageWidth-1) &&isPOT(_imageHeight -1)))
{
int chunk_amount_y = _imageHeight/_chunkSize.height;
int chunk_amount_x = _imageWidth/_chunkSize.width;
loadVertices();
calculateNormal();
memset(_chunkesArray, 0, sizeof(_chunkesArray));
for(int m =0;m<chunk_amount_y;m++)
{
for(int n =0; n<chunk_amount_x;n++)
{
_chunkesArray[m][n] = new Chunk();
_chunkesArray[m][n]->_terrain = this;
_chunkesArray[m][n]->_size = _chunkSize;
_chunkesArray[m][n]->generate(_imageWidth,_imageHeight,m,n,_data);
}
}
//calculate the neighbor
for(int m =0;m<chunk_amount_y;m++)
{
for(int n =0; n<chunk_amount_x;n++)
{
if(n-1>=0) _chunkesArray[m][n]->_left = _chunkesArray[m][n-1];
if(n+1<chunk_amount_x) _chunkesArray[m][n]->_right = _chunkesArray[m][n+1];
if(m-1>=0) _chunkesArray[m][n]->_back = _chunkesArray[m-1][n];
if(m+1<chunk_amount_y) _chunkesArray[m][n]->_front = _chunkesArray[m+1][n];
}
}
_quadRoot = new QuadTree(0,0,_imageWidth,_imageHeight,this);
setLODDistance(_chunkSize.width,2*_chunkSize.width,3*_chunkSize.width);
return true;
}else
{
CCLOG("warning: the height map size is not POT or POT + 1");
return false;
}
}
Terrain::Terrain()
: _alphaMap(nullptr)
, _stateBlock(nullptr)
{
_stateBlock = RenderState::StateBlock::create();
CC_SAFE_RETAIN(_stateBlock);
_customCommand.setTransparent(false);
_customCommand.set3D(true);
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
auto _backToForegroundListener = EventListenerCustom::create(EVENT_RENDERER_RECREATED,
[this](EventCustom*)
{
reload();
}
);
Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(_backToForegroundListener, 1);
#endif
}
void Terrain::setChunksLOD(Vec3 cameraPos)
{
int chunk_amount_y = _imageHeight/_chunkSize.height;
int chunk_amount_x = _imageWidth/_chunkSize.width;
for(int m=0;m<chunk_amount_y;m++)
for(int n =0;n<chunk_amount_x;n++)
{
AABB aabb = _chunkesArray[m][n]->_parent->_worldSpaceAABB;
auto center = aabb.getCenter();
float dist = Vec2(center.x, center.z).distance(Vec2(cameraPos.x, cameraPos.z));
_chunkesArray[m][n]->_currentLod = 3;
for(int i =0;i<3;i++)
{
if(dist<=_lodDistance[i])
{
_chunkesArray[m][n]->_currentLod = i;
break;
}
}
}
}
float Terrain::getHeight(float x, float z, Vec3 * normal) const
{
Vec2 pos(x,z);
//top-left
Vec2 tl(-1*_terrainData._mapScale*_imageWidth/2,-1*_terrainData._mapScale*_imageHeight/2);
auto result = getNodeToWorldTransform()*Vec4(tl.x,0.0f,tl.y,1.0f);
tl.set(result.x, result.z);
Vec2 to_tl = pos - tl;
//real size
Vec2 size(_imageWidth*_terrainData._mapScale,_imageHeight*_terrainData._mapScale);
result = getNodeToWorldTransform()*Vec4(size.x,0.0f,size.y,0.0f);
size.set(result.x, result.z);
float width_ratio = to_tl.x/size.x;
float height_ratio = to_tl.y/size.y;
float image_x = width_ratio * _imageWidth;
float image_y = height_ratio * _imageHeight;
float u =image_x - (int)image_x;
float v =image_y - (int)image_y;
float i = (int)image_x;
float j = (int)image_y;
if(image_x>=_imageWidth-1 || image_y >=_imageHeight-1 || image_x<0 || image_y<0)
{
if (normal)
{
normal->setZero();
}
return 0;
}else
{
float a = getImageHeight(i,j)*getScaleY();
float b = getImageHeight(i,j+1)*getScaleY();
float c = getImageHeight(i+1,j)*getScaleY();
float d = getImageHeight(i+1,j+1)*getScaleY();
if(normal)
{
normal->x = c - b;
normal->y = 2;
normal->z = d - a;
normal->normalize();
//(*normal) = (1-u)*(1-v)*getNormal(i,j)+ (1-u)*v*getNormal(i,j+1) + u*(1-v)*getNormal(i+1,j)+ u*v*getNormal(i+1,j+1);
}
float reuslt = (1-u)*(1-v)*getImageHeight(i,j)*getScaleY() + (1-u)*v*getImageHeight(i,j+1)*getScaleY() + u*(1-v)*getImageHeight(i+1,j)*getScaleY() + u*v*getImageHeight(i+1,j+1)*getScaleY();
return reuslt;
}
}
float Terrain::getHeight(Vec2 pos, Vec3*Normal) const
{
return getHeight(pos.x,pos.y,Normal);
}
float Terrain::getImageHeight(int pixel_x,int pixel_y) const
{
int byte_stride =1;
switch (_heightMapImage->getRenderFormat())
{
case Texture2D::PixelFormat::BGRA8888:
byte_stride = 4;
break;
case Texture2D::PixelFormat::RGB888:
byte_stride =3;
break;
case Texture2D::PixelFormat::I8:
byte_stride =1;
break;
default:
break;
}
return _data[(pixel_y*_imageWidth+pixel_x)*byte_stride]*1.0/255*_terrainData._mapHeight -0.5*_terrainData._mapHeight;
}
void Terrain::loadVertices()
{
_maxHeight = -99999;
_minHeight = 99999;
for(int i =0;i<_imageHeight;i++)
{
for(int j =0;j<_imageWidth;j++)
{
float height = getImageHeight(j,i);
TerrainVertexData v;
v._position = Vec3(j*_terrainData._mapScale- _imageWidth/2*_terrainData._mapScale, //x
height, //y
i*_terrainData._mapScale - _imageHeight/2*_terrainData._mapScale);//z
v._texcoord = Tex2F(j*1.0/_imageWidth,i*1.0/_imageHeight);
_vertices.push_back (v);
//update the min & max height;
if(height>_maxHeight) _maxHeight = height;
if(height<_minHeight) _minHeight = height;
}
}
}
void Terrain::calculateNormal()
{
_indices.clear();
//we generate whole terrain indices(global indices) for correct normal calculate
for(int i =0;i<_imageHeight-1;i+=1)
{
for(int j = 0;j<_imageWidth-1;j+=1)
{
int nLocIndex = i * _imageWidth + j;
_indices.push_back (nLocIndex);
_indices.push_back (nLocIndex + _imageWidth);
_indices.push_back (nLocIndex + 1);
_indices.push_back (nLocIndex + 1);
_indices.push_back (nLocIndex + _imageWidth);
_indices.push_back (nLocIndex + _imageWidth+1);
}
}
for (unsigned int i = 0 ; i < _indices.size() ; i += 3) {
unsigned int Index0 = _indices[i];
unsigned int Index1 = _indices[i + 1];
unsigned int Index2 = _indices[i + 2];
Vec3 v1 = _vertices[Index1]._position - _vertices[Index0]._position;
Vec3 v2 = _vertices[Index2]._position - _vertices[Index0]._position;
Vec3 Normal;
Vec3::cross(v1,v2,&Normal);
Normal.normalize();
_vertices[Index0]._normal += Normal;
_vertices[Index1]._normal += Normal;
_vertices[Index2]._normal += Normal;
}
for (unsigned int i = 0 ; i < _vertices.size() ; i++) {
_vertices[i]._normal.normalize();
}
//global indices no need at all
_indices.clear();
}
void Terrain::setDrawWire(bool bool_value)
{
_isDrawWire = bool_value;
}
void Terrain::setLODDistance(float lod_1, float lod_2, float lod_3)
{
_lodDistance[0] = lod_1;
_lodDistance[1] = lod_2;
_lodDistance[2] = lod_3;
}
void Terrain::setIsEnableFrustumCull(bool bool_value)
{
_isEnableFrustumCull = bool_value;
}
Terrain::~Terrain()
{
CC_SAFE_RELEASE(_stateBlock);
_alphaMap->release();
_heightMapImage->release();
delete _quadRoot;
for(int i=0;i<4;i++)
{
if(_detailMapTextures[i])
{
_detailMapTextures[i]->release();
}
}
for(int i = 0;i<MAX_CHUNKES;i++)
{
for(int j = 0;j<MAX_CHUNKES;j++)
{
if(_chunkesArray[i][j])
{
delete _chunkesArray[i][j];
}
}
}
for(int i =0;i<_chunkLodIndicesSet.size();i++)
{
glDeleteBuffers(1,&(_chunkLodIndicesSet[i]._chunkIndices._indices));
}
for(int i =0;i<_chunkLodIndicesSkirtSet.size();i++)
{
glDeleteBuffers(1,&(_chunkLodIndicesSkirtSet[i]._chunkIndices._indices));
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
Director::getInstance()->getEventDispatcher()->removeEventListener(_backToForegroundListener);
#endif
}
cocos2d::Vec3 Terrain::getNormal(int pixel_x, int pixel_y) const
{
float a = getImageHeight(pixel_x,pixel_y)*getScaleY();
float b = getImageHeight(pixel_x,pixel_y+1)*getScaleY();
float c = getImageHeight(pixel_x+1,pixel_y)*getScaleY();
float d = getImageHeight(pixel_x+1,pixel_y+1)*getScaleY();
Vec3 normal;
normal.x = c - b;
normal.y = 2;
normal.z = d - a;
normal.normalize();
return normal;
}
cocos2d::Vec3 Terrain::getIntersectionPoint(const Ray & ray) const
{
Vec3 dir = ray._direction;
dir.normalize();
Vec3 rayStep = _terrainData._chunkSize.width*0.25*dir;
Vec3 rayPos = ray._origin;
Vec3 rayStartPosition = ray._origin;
Vec3 lastRayPosition =rayPos;
rayPos += rayStep;
// Linear search - Loop until find a point inside and outside the terrain Vector3
Vec3 normal;
float height = getHeight(rayPos.x, rayPos.z, &normal);
while (rayPos.y > height)
{
lastRayPosition = rayPos;
rayPos += rayStep;
if (normal.isZero())
return Vec3(0, 0, 0);
height = getHeight(rayPos.x,rayPos.z);
}
Vec3 startPosition = lastRayPosition;
Vec3 endPosition = rayPos;
for (int i= 0; i< 32; i++)
{
// Binary search pass
Vec3 middlePoint = (startPosition + endPosition) * 0.5f;
if (middlePoint.y < height)
endPosition = middlePoint;
else
startPosition = middlePoint;
}
Vec3 collisionPoint = (startPosition + endPosition) * 0.5f;
return collisionPoint;
}
bool Terrain::getIntersectionPoint(const Ray & ray, Vec3 & intersectionPoint) const
{
Vec3 dir = ray._direction;
dir.normalize();
Vec3 rayStep = _terrainData._chunkSize.width*0.25*dir;
Vec3 rayPos = ray._origin;
Vec3 rayStartPosition = ray._origin;
Vec3 lastRayPosition = rayPos;
rayPos += rayStep;
// Linear search - Loop until find a point inside and outside the terrain Vector3
Vec3 normal;
float height = getHeight(rayPos.x, rayPos.z, &normal);
while (rayPos.y > height)
{
lastRayPosition = rayPos;
rayPos += rayStep;
if (normal.isZero())
{
intersectionPoint = Vec3(0, 0, 0);
return false;
}
height = getHeight(rayPos.x, rayPos.z);
}
Vec3 startPosition = lastRayPosition;
Vec3 endPosition = rayPos;
for (int i = 0; i < 32; i++)
{
// Binary search pass
Vec3 middlePoint = (startPosition + endPosition) * 0.5f;
if (middlePoint.y < height)
endPosition = middlePoint;
else
startPosition = middlePoint;
}
Vec3 collisionPoint = (startPosition + endPosition) * 0.5f;
intersectionPoint = collisionPoint;
return true;
}
void Terrain::setMaxDetailMapAmount(int max_value)
{
_maxDetailMapValue = max_value;
}
cocos2d::Vec2 Terrain::convertToTerrainSpace(Vec2 worldSpaceXZ)
{
Vec2 pos(worldSpaceXZ.x,worldSpaceXZ.y);
//top-left
Vec2 tl(-1*_terrainData._mapScale*_imageWidth/2,-1*_terrainData._mapScale*_imageHeight/2);
auto result = getNodeToWorldTransform()*Vec4(tl.x,0.0f,tl.y,1.0f);
tl.set(result.x, result.z);
Vec2 to_tl = pos - tl;
//real size
Vec2 size(_imageWidth*_terrainData._mapScale,_imageHeight*_terrainData._mapScale);
result = getNodeToWorldTransform()*Vec4(size.x,0.0f,size.y,0.0f);
size.set(result.x, result.z);
float width_ratio = to_tl.x/size.x;
float height_ratio = to_tl.y/size.y;
float image_x = width_ratio * _imageWidth;
float image_y = height_ratio * _imageHeight;
return Vec2(image_x,image_y);
}
void Terrain::resetHeightMap(const char * heightMap)
{
_heightMapImage->release();
_vertices.clear();
free(_data);
for(int i = 0;i<MAX_CHUNKES;i++)
{
for(int j = 0;j<MAX_CHUNKES;j++)
{
if(_chunkesArray[i][j])
{
delete _chunkesArray[i][j];
}
}
}
delete _quadRoot;
initHeightMap(heightMap);
}
float Terrain::getMinHeight()
{
return _minHeight;
}
float Terrain::getMaxHeight()
{
return _maxHeight;
}
cocos2d::AABB Terrain::getAABB()
{
return _quadRoot->_worldSpaceAABB;
}
Terrain::QuadTree * Terrain::getQuadTree()
{
return _quadRoot;
}
std::vector<float> Terrain::getHeightData() const
{
std::vector<float> data;
data.resize(_imageWidth * _imageHeight);
for (int i = 0; i < _imageHeight; i++) {
for (int j = 0; j < _imageWidth; j++) {
int idx = i * _imageWidth + j;
data[idx] = (_vertices[idx]._position.y);
}
}
return data;
}
void Terrain::setAlphaMap(cocos2d::Texture2D * newAlphaMapTexture)
{
_alphaMap->release();
_alphaMap = newAlphaMapTexture;
}
void Terrain::setDetailMap(unsigned int index, DetailMap detailMap)
{
if(index>4)
{
CCLOG("invalid DetailMap index %d\n",index);
}
_terrainData._detailMaps[index] = detailMap;
if(_detailMapTextures[index])
{
_detailMapTextures[index]->release();
}
_detailMapTextures[index] = new (std::nothrow)Texture2D();
auto textImage = new (std::nothrow)Image();
textImage->initWithImageFile(detailMap._detailMapSrc);
_detailMapTextures[index]->initWithImage(textImage);
delete textImage;
}
Terrain::ChunkIndices Terrain::lookForIndicesLOD(int neighborLod[4], int selfLod, bool * result)
{
(* result) =false;
ChunkIndices tmp;
tmp._indices = 0;
tmp._size = 0;
if(_chunkLodIndicesSet.empty())
{
(* result) =false;
return tmp;
}else
{
int test[5];
memcpy(test,neighborLod,sizeof(int [4]));
test[4] = selfLod;
for(int i =0;i<_chunkLodIndicesSet.size();i++)
{
if(memcmp(test,_chunkLodIndicesSet[i]._relativeLod,sizeof(test))==0)
{
(*result) = true;
return _chunkLodIndicesSet[i]._chunkIndices;
}
}
}
(* result) =false;
return tmp;
}
Terrain::ChunkIndices Terrain::insertIndicesLOD(int neighborLod[4], int selfLod, GLushort * indices,int size)
{
ChunkLODIndices lodIndices;
memcpy(lodIndices._relativeLod,neighborLod,sizeof(int [4]));
lodIndices._relativeLod[4] = selfLod;
lodIndices._chunkIndices._size = size;
glGenBuffers(1,&(lodIndices._chunkIndices._indices));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lodIndices._chunkIndices._indices);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(GLushort)*size,indices,GL_STATIC_DRAW);
this->_chunkLodIndicesSet.push_back(lodIndices);
return lodIndices._chunkIndices;
}
Terrain::ChunkIndices Terrain::lookForIndicesLODSkrit(int selfLod, bool * result)
{
ChunkIndices badResult;
badResult._indices = 0;
badResult._size = 0;
if(this->_chunkLodIndicesSkirtSet.empty())
{
(*result) = false;
return badResult;
}
for(int i =0;i<_chunkLodIndicesSkirtSet.size();i++)
{
if(_chunkLodIndicesSkirtSet[i]._selfLod == selfLod)
{
(*result) = true;
return _chunkLodIndicesSkirtSet[i]._chunkIndices;
}
}
(*result) = false;
return badResult;
}
Terrain::ChunkIndices Terrain::insertIndicesLODSkirt(int selfLod, GLushort * indices, int size)
{
ChunkLODIndicesSkirt skirtIndices;
skirtIndices._selfLod = selfLod;
skirtIndices._chunkIndices._size = size;
glGenBuffers(1,&(skirtIndices._chunkIndices._indices));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, skirtIndices._chunkIndices._indices);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(GLushort)*size,indices,GL_STATIC_DRAW);
this->_chunkLodIndicesSkirtSet.push_back(skirtIndices);
return skirtIndices._chunkIndices;
}
void Terrain::setSkirtHeightRatio(float ratio)
{
_skirtRatio = ratio;
}
void Terrain::onEnter()
{
Node::onEnter();
_terrainModelMatrix = getNodeToWorldTransform();
_quadRoot->preCalculateAABB(_terrainModelMatrix);
cacheUniformAttribLocation();
}
void Terrain::cacheUniformAttribLocation()
{
_positionLocation = glGetAttribLocation(this->getGLProgram()->getProgram(),"a_position");
_texcordLocation = glGetAttribLocation(this->getGLProgram()->getProgram(),"a_texCoord");
_normalLocation = glGetAttribLocation(this->getGLProgram()->getProgram(),"a_normal");
_alphaMapLocation = -1;
for(int i =0;i<4;i++)
{
_detailMapLocation[i] = -1;
_detailMapSizeLocation[i] = -1;
}
auto glProgram = getGLProgram();
_alphaIsHasAlphaMapLocation = glGetUniformLocation(glProgram->getProgram(),"u_has_alpha");
if(!_alphaMap)
{
_detailMapLocation[0] = glGetUniformLocation(glProgram->getProgram(),"u_texture0");
}else
{
for(int i =0;i<_maxDetailMapValue;i++)
{
char str[20];
sprintf(str,"u_texture%d",i);
_detailMapLocation[i] = glGetUniformLocation(glProgram->getProgram(),str);
sprintf(str,"u_detailSize[%d]",i);
_detailMapSizeLocation[i] = glGetUniformLocation(glProgram->getProgram(),str);
}
_alphaMapLocation = glGetUniformLocation(glProgram->getProgram(),"u_alphaMap");
}
}
bool Terrain::initTextures()
{
Texture2D::TexParams texParam;
texParam.wrapS = GL_REPEAT;
texParam.wrapT = GL_REPEAT;
if(!_terrainData._alphaMapSrc)
{
auto textImage = new (std::nothrow)Image();
textImage->initWithImageFile(_terrainData._detailMaps[0]._detailMapSrc);
auto texture = new (std::nothrow)Texture2D();
texture->initWithImage(textImage);
texture->generateMipmap();
_detailMapTextures[0] = texture;
texParam.minFilter = GL_LINEAR_MIPMAP_LINEAR;
texParam.magFilter = GL_LINEAR;
texture->setTexParameters(texParam);
delete textImage;
}else
{
//alpha map
auto image = new (std::nothrow)Image();
image->initWithImageFile(_terrainData._alphaMapSrc);
_alphaMap = new (std::nothrow)Texture2D();
_alphaMap->initWithImage(image);
texParam.wrapS = GL_CLAMP_TO_EDGE;
texParam.wrapT = GL_CLAMP_TO_EDGE;
texParam.minFilter = GL_LINEAR;
texParam.magFilter = GL_LINEAR;
_alphaMap->setTexParameters(texParam);
delete image;
for(int i =0;i<_terrainData._detailMapAmount;i++)
{
auto textImage = new (std::nothrow)Image();
textImage->initWithImageFile(_terrainData._detailMaps[i]._detailMapSrc);
auto texture = new (std::nothrow)Texture2D();
texture->initWithImage(textImage);
delete textImage;
texture->generateMipmap();
_detailMapTextures[i] = texture;
texParam.wrapS = GL_REPEAT;
texParam.wrapT = GL_REPEAT;
texParam.minFilter = GL_LINEAR_MIPMAP_LINEAR;
texParam.magFilter = GL_LINEAR;
texture->setTexParameters(texParam);
}
}
setMaxDetailMapAmount(_terrainData._detailMapAmount);
return true;
}
void Terrain::reload()
{
int chunk_amount_y = _imageHeight/_chunkSize.height;
int chunk_amount_x = _imageWidth/_chunkSize.width;
for(int m =0;m<chunk_amount_y;m++)
{
for(int n =0; n<chunk_amount_x;n++)
{
_chunkesArray[m][n]->finish();
}
}
initTextures();
_chunkLodIndicesSet.clear();
_chunkLodIndicesSkirtSet.clear();
}
void Terrain::Chunk::finish()
{
//genearate two VBO ,the first for vertices, we just setup datas once ,won't changed at all
//the second vbo for the indices, because we use level of detail technique to each chunk, so we will modified frequently
glGenBuffers(1,&_vbo);
//only set for vertices vbo
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(TerrainVertexData)*_originalVertices.size(), &_originalVertices[0], GL_STREAM_DRAW);
glBindBuffer(GL_ARRAY_BUFFER,0);
calculateSlope();
for(int i =0;i<4;i++)
{
int step = 1<<_currentLod;
//reserve the indices size, the first part is the core part of the chunk, the second part & thid part is for fix crack
int indicesAmount =(_terrain->_chunkSize.width/step+1)*(_terrain->_chunkSize.height/step+1)*6+(_terrain->_chunkSize.height/step)*6
+(_terrain->_chunkSize.width/step)*6;
_lod[i]._indices.reserve(indicesAmount);
}
_oldLod = -1;
}
void Terrain::Chunk::bindAndDraw()
{
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
if(_terrain->_isCameraViewChanged || _oldLod <0)
{
switch (_terrain->_crackFixedType)
{
case CrackFixedType::SKIRT:
updateIndicesLODSkirt();
break;
case CrackFixedType::INCREASE_LOWER:
updateVerticesForLOD();
updateIndicesLOD();
break;
default:
break;
}
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,_chunkIndices._indices);
unsigned long offset = 0;
//position
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, sizeof(TerrainVertexData), (GLvoid *)offset);
offset +=sizeof(Vec3);
//texcoord
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORD,2,GL_FLOAT,GL_FALSE,sizeof(TerrainVertexData),(GLvoid *)offset);
offset +=sizeof(Tex2F);
//normal
glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_NORMAL,3,GL_FLOAT,GL_FALSE,sizeof(TerrainVertexData),(GLvoid *)offset);
glDrawElements(GL_TRIANGLES, (GLsizei)_chunkIndices._size, GL_UNSIGNED_SHORT, 0);
CC_INCREMENT_GL_DRAWN_BATCHES_AND_VERTICES(1, _chunkIndices._size);
}
void Terrain::Chunk::generate(int imgWidth, int imageHei, int m, int n, const unsigned char * data)
{
_posY = m;
_posX = n;
switch (_terrain->_crackFixedType)
{
case CrackFixedType::SKIRT:
{
for(int i=_size.height*m;i<=_size.height*(m+1);i++)
{
if(i>=imageHei) break;
for(int j=_size.width*n;j<=_size.width*(n+1);j++)
{
if(j>=imgWidth)break;
auto v =_terrain->_vertices[i*imgWidth + j];
_originalVertices.push_back (v);
}
}
// add four skirts
float skirtHeight = _terrain->_skirtRatio *_terrain->_terrainData._mapScale*8;
//#1
_terrain->_skirtVerticesOffset[0] = (int)_originalVertices.size();
for(int i =_size.height*m;i<=_size.height*(m+1);i++)
{
auto v = _terrain->_vertices[i*imgWidth +_size.width*(n+1)];
v._position.y -= skirtHeight;
_originalVertices.push_back (v);
}
//#2
_terrain->_skirtVerticesOffset[1] = (int)_originalVertices.size();
for(int j =_size.width*n;j<=_size.width*(n+1);j++)
{
auto v = _terrain->_vertices[_size.height*(m+1)*imgWidth + j];
v._position.y -=skirtHeight;
_originalVertices.push_back (v);
}
//#3
_terrain->_skirtVerticesOffset[2] = (int)_originalVertices.size();
for(int i =_size.height*m;i<=_size.height*(m+1);i++)
{
auto v = _terrain->_vertices[i*imgWidth + _size.width*n];
v._position.y -= skirtHeight;
_originalVertices.push_back (v);
}
//#4
_terrain->_skirtVerticesOffset[3] = (int)_originalVertices.size();
for(int j =_size.width*n;j<=_size.width*(n+1);j++)
{
auto v = _terrain->_vertices[_size.height*m*imgWidth+j];
v._position.y -= skirtHeight;
//v.position.y = -5;
_originalVertices.push_back (v);
}
}
break;
case CrackFixedType::INCREASE_LOWER:
{
for(int i=_size.height*m;i<=_size.height*(m+1);i++)
{
if(i>=imageHei) break;
for(int j=_size.width*n;j<=_size.width*(n+1);j++)
{
if(j>=imgWidth)break;
auto v =_terrain->_vertices[i*imgWidth + j];
_originalVertices.push_back (v);
}
}
}
break;
}
calculateAABB();
finish();
}
Terrain::Chunk::Chunk()
{
_currentLod = 0;
_left = nullptr;
_right = nullptr;
_back = nullptr;
_front = nullptr;
_oldLod = -1;
for(int i =0;i<4;i++)
{
_neighborOldLOD[i] = -1;
}
}
void Terrain::Chunk::updateIndicesLOD()
{
int currentNeighborLOD[4];
if(_left)
{
currentNeighborLOD[0] = _left->_currentLod;
}else{currentNeighborLOD[0] = -1;}
if(_right)
{
currentNeighborLOD[1] = _right->_currentLod;
}else{currentNeighborLOD[1] = -1;}
if(_back)
{
currentNeighborLOD[2] = _back->_currentLod;
}else{currentNeighborLOD[2] = -1;}
if(_front)
{
currentNeighborLOD[3] = _front->_currentLod;
}else{currentNeighborLOD[3] = -1;}
if(_oldLod == _currentLod &&(memcmp(currentNeighborLOD,_neighborOldLOD,sizeof(currentNeighborLOD))==0) )
{
return;// no need to update
}
bool isOk;
_chunkIndices = _terrain->lookForIndicesLOD(currentNeighborLOD,_currentLod,&isOk);
if(isOk)
{
return;
}
memcpy(_neighborOldLOD,currentNeighborLOD,sizeof(currentNeighborLOD));
_oldLod = _currentLod;
int gridY = _size.height;
int gridX = _size.width;
int step = 1<<_currentLod;
if((_left&&_left->_currentLod > _currentLod) ||(_right&&_right->_currentLod > _currentLod)
||(_back&&_back->_currentLod > _currentLod) || (_front && _front->_currentLod > _currentLod))
//need update indices.
{
//t-junction inner
_lod[_currentLod]._indices.clear();
for(int i =step;i<gridY-step;i+=step)
{
for(int j = step;j<gridX-step;j+=step)
{
int nLocIndex = i * (gridX+1) + j;
_lod[_currentLod]._indices.push_back (nLocIndex);
_lod[_currentLod]._indices.push_back (nLocIndex + step * (gridX+1));
_lod[_currentLod]._indices.push_back (nLocIndex + step);
_lod[_currentLod]._indices.push_back (nLocIndex + step);
_lod[_currentLod]._indices.push_back (nLocIndex + step * (gridX+1));
_lod[_currentLod]._indices.push_back (nLocIndex + step * (gridX+1) + step);
}
}
//fix T-crack
int next_step = 1<<(_currentLod+1);
if(_left&&_left->_currentLod > _currentLod)//left
{
for(int i =0;i<gridY;i+=next_step)
{
_lod[_currentLod]._indices.push_back(i*(gridX+1)+step);
_lod[_currentLod]._indices.push_back(i*(gridX+1));
_lod[_currentLod]._indices.push_back((i+next_step)*(gridX+1));
_lod[_currentLod]._indices.push_back(i*(gridX+1)+step);
_lod[_currentLod]._indices.push_back((i+next_step)*(gridX+1));
_lod[_currentLod]._indices.push_back((i+step)*(gridX+1)+step);
_lod[_currentLod]._indices.push_back((i+step)*(gridX+1)+step);
_lod[_currentLod]._indices.push_back((i+next_step)*(gridX+1));
_lod[_currentLod]._indices.push_back((i+next_step)*(gridX+1)+step);
}
}else{
int start=0;
int end =gridY;
if(_front&&_front->_currentLod > _currentLod) end -=step;
if(_back&&_back->_currentLod > _currentLod) start +=step;
for(int i =start;i<end;i+=step)
{
_lod[_currentLod]._indices.push_back(i*(gridX+1)+step);
_lod[_currentLod]._indices.push_back(i*(gridX+1));
_lod[_currentLod]._indices.push_back((i+step)*(gridX+1));
_lod[_currentLod]._indices.push_back(i*(gridX+1)+step);
_lod[_currentLod]._indices.push_back((i+step)*(gridX+1));
_lod[_currentLod]._indices.push_back((i+step)*(gridX+1)+step);
}
}
if(_right&&_right->_currentLod > _currentLod)//LEFT
{
for(int i =0;i<gridY;i+=next_step)
{
_lod[_currentLod]._indices.push_back(i*(gridX+1)+gridX);
_lod[_currentLod]._indices.push_back(i*(gridX+1)+gridX-step);
_lod[_currentLod]._indices.push_back((i+step)*(gridX+1)+gridX-step);
_lod[_currentLod]._indices.push_back(i*(gridX+1)+gridX);
_lod[_currentLod]._indices.push_back((i+step)*(gridX+1)+gridX-step);
_lod[_currentLod]._indices.push_back((i+next_step)*(gridX+1)+gridX-step);
_lod[_currentLod]._indices.push_back(i*(gridX+1)+gridX);
_lod[_currentLod]._indices.push_back((i+next_step)*(gridX+1)+gridX-step);
_lod[_currentLod]._indices.push_back((i+next_step)*(gridX+1)+gridX);
}
}else{
int start=0;
int end =gridY;
if(_front&&_front->_currentLod > _currentLod) end -=step;
if(_back&&_back->_currentLod > _currentLod) start +=step;
for(int i =start;i<end;i+=step)
{
_lod[_currentLod]._indices.push_back(i*(gridX+1)+gridX);
_lod[_currentLod]._indices.push_back(i*(gridX+1)+gridX-step);
_lod[_currentLod]._indices.push_back((i+step)*(gridX+1)+gridX-step);
_lod[_currentLod]._indices.push_back(i*(gridX+1)+gridX);
_lod[_currentLod]._indices.push_back((i+step)*(gridX+1)+gridX-step);
_lod[_currentLod]._indices.push_back((i+step)*(gridX+1)+gridX);
}
}
if(_front&&_front->_currentLod > _currentLod)//front
{
for(int i =0;i<gridX;i+=next_step)
{
_lod[_currentLod]._indices.push_back((gridY-step)*(gridX+1)+i);
_lod[_currentLod]._indices.push_back(gridY*(gridX+1)+i);
_lod[_currentLod]._indices.push_back((gridY-step)*(gridX+1)+i+step);
_lod[_currentLod]._indices.push_back((gridY-step)*(gridX+1)+i+step);
_lod[_currentLod]._indices.push_back(gridY*(gridX+1)+i);
_lod[_currentLod]._indices.push_back(gridY*(gridX+1)+i+next_step);
_lod[_currentLod]._indices.push_back((gridY-step)*(gridX+1)+i+step);
_lod[_currentLod]._indices.push_back(gridY*(gridX+1)+i+next_step);
_lod[_currentLod]._indices.push_back((gridY-step)*(gridX+1)+i+next_step);
}
}else
{
for(int i =step;i<gridX-step;i+=step)
{
_lod[_currentLod]._indices.push_back((gridY-step)*(gridX+1)+i);
_lod[_currentLod]._indices.push_back(gridY*(gridX+1)+i);
_lod[_currentLod]._indices.push_back((gridY-step)*(gridX+1)+i+step);
_lod[_currentLod]._indices.push_back((gridY-step)*(gridX+1)+i+step);
_lod[_currentLod]._indices.push_back(gridY*(gridX+1)+i);
_lod[_currentLod]._indices.push_back(gridY*(gridX+1)+i+step);
}
}
if(_back&&_back->_currentLod > _currentLod)//back
{
for(int i =0;i<gridX;i+=next_step)
{
_lod[_currentLod]._indices.push_back(i);
_lod[_currentLod]._indices.push_back(step*(gridX+1) +i);
_lod[_currentLod]._indices.push_back(step*(gridX+1) +i+step);
_lod[_currentLod]._indices.push_back(i);
_lod[_currentLod]._indices.push_back(step*(gridX+1) +i+step);
_lod[_currentLod]._indices.push_back(i+next_step);
_lod[_currentLod]._indices.push_back(i+next_step);
_lod[_currentLod]._indices.push_back(step*(gridX+1) +i+step);
_lod[_currentLod]._indices.push_back(step*(gridX+1) +i+next_step);
}
}else{
for(int i =step;i<gridX-step;i+=step)
{
_lod[_currentLod]._indices.push_back(i);
_lod[_currentLod]._indices.push_back(step*(gridX+1)+i);
_lod[_currentLod]._indices.push_back(step*(gridX+1)+i+step);
_lod[_currentLod]._indices.push_back(i);
_lod[_currentLod]._indices.push_back(step*(gridX+1)+i+step);
_lod[_currentLod]._indices.push_back(i+step);
}
}
_chunkIndices = _terrain->insertIndicesLOD(currentNeighborLOD,_currentLod,&_lod[_currentLod]._indices[0],(int)_lod[_currentLod]._indices.size());
}else{
//No lod difference, use simple method
_lod[_currentLod]._indices.clear();
for(int i =0;i<gridY;i+=step)
{
for(int j = 0;j<gridX;j+=step)
{
int nLocIndex = i * (gridX+1) + j;
_lod[_currentLod]._indices.push_back (nLocIndex);
_lod[_currentLod]._indices.push_back (nLocIndex + step * (gridX+1));
_lod[_currentLod]._indices.push_back (nLocIndex + step);
_lod[_currentLod]._indices.push_back (nLocIndex + step);
_lod[_currentLod]._indices.push_back (nLocIndex + step * (gridX+1));
_lod[_currentLod]._indices.push_back (nLocIndex + step * (gridX+1) + step);
}
}
_chunkIndices = _terrain->insertIndicesLOD(currentNeighborLOD,_currentLod,&_lod[_currentLod]._indices[0],(int)_lod[_currentLod]._indices.size());
}
}
void Terrain::Chunk::calculateAABB()
{
std::vector<Vec3>pos;
for(int i =0;i<_originalVertices.size();i++)
{
pos.push_back(_originalVertices[i]._position);
}
_aabb.updateMinMax(&pos[0],pos.size());
}
void Terrain::Chunk::calculateSlope()
{
//find max slope
auto lowest = _originalVertices[0]._position;
for(int i = 0;i<_originalVertices.size();i++)
{
if(_originalVertices[i]._position.y< lowest.y)
{
lowest = _originalVertices[i]._position;
}
}
auto highest = _originalVertices[0]._position;
for(int i = 0;i<_originalVertices.size();i++)
{
if(_originalVertices[i]._position.y> highest.y)
{
highest = _originalVertices[i]._position;
}
}
Vec2 a(lowest.x,lowest.z);
Vec2 b(highest.x,highest.z);
float dist = a.distance(b);
_slope = (highest.y - lowest.y)/dist;
}
void Terrain::Chunk::updateVerticesForLOD()
{
if(_oldLod == _currentLod){ return;} // no need to update vertices
_currentVertices = _originalVertices;
int gridY = _size.height;
int gridX = _size.width;
if(_currentLod>=2 && std::abs(_slope)>1.2)
{
int step = 1<<_currentLod;
for(int i =step;i<gridY-step;i+=step)
for(int j = step; j<gridX-step;j+=step)
{
// use linear-sample adjust vertices height
float height = 0;
float count = 0;
for(int n = i-step/2;n<i+step/2;n++)
{
for(int m = j-step/2;m<j+step/2;m++)
{
float weight = (step/2 - std::abs(n-i))*(step/2 - std::abs(m-j));
height += _originalVertices[m*(gridX+1)+n]._position.y;
count += weight;
}
}
_currentVertices[i*(gridX+1)+j]._position.y = height/count;
}
}
glBufferData(GL_ARRAY_BUFFER, sizeof(TerrainVertexData)*_currentVertices.size(), &_currentVertices[0], GL_STREAM_DRAW);
}
Terrain::Chunk::~Chunk()
{
glDeleteBuffers(1,&_vbo);
}
void Terrain::Chunk::updateIndicesLODSkirt()
{
if(_oldLod == _currentLod) return;
_oldLod = _currentLod;
bool isOk;
_chunkIndices = _terrain->lookForIndicesLODSkrit(_currentLod,&isOk);
if(isOk) return;
int gridY = _size.height;
int gridX = _size.width;
int step = 1<<_currentLod;
int k =0;
for(int i =0;i<gridY;i+=step,k+=step)
{
for(int j = 0;j<gridX;j+=step)
{
int nLocIndex = i * (gridX+1) + j;
_lod[_currentLod]._indices.push_back (nLocIndex);
_lod[_currentLod]._indices.push_back (nLocIndex + step * (gridX+1));
_lod[_currentLod]._indices.push_back (nLocIndex + step);
_lod[_currentLod]._indices.push_back (nLocIndex + step);
_lod[_currentLod]._indices.push_back (nLocIndex + step * (gridX+1));
_lod[_currentLod]._indices.push_back (nLocIndex + step * (gridX+1) + step);
}
}
//add skirt
//#1
for(int i =0;i<gridY;i+=step)
{
int nLocIndex = i * (gridX+1) + gridX;
_lod[_currentLod]._indices.push_back (nLocIndex);
_lod[_currentLod]._indices.push_back (nLocIndex + step * (gridX+1));
_lod[_currentLod]._indices.push_back ((gridY+1) *(gridX+1)+i);
_lod[_currentLod]._indices.push_back ((gridY+1) *(gridX+1)+i);
_lod[_currentLod]._indices.push_back (nLocIndex + step * (gridX+1));
_lod[_currentLod]._indices.push_back ((gridY+1) *(gridX+1)+i+step);
}
//#2
for(int j =0;j<gridX;j+=step)
{
int nLocIndex = (gridY)* (gridX+1) + j;
_lod[_currentLod]._indices.push_back (nLocIndex);
_lod[_currentLod]._indices.push_back (_terrain->_skirtVerticesOffset[1] +j);
_lod[_currentLod]._indices.push_back (nLocIndex + step);
_lod[_currentLod]._indices.push_back (nLocIndex + step);
_lod[_currentLod]._indices.push_back (_terrain->_skirtVerticesOffset[1] +j);
_lod[_currentLod]._indices.push_back (_terrain->_skirtVerticesOffset[1] +j + step);
}
//#3
for(int i =0;i<gridY;i+=step)
{
int nLocIndex = i * (gridX+1);
_lod[_currentLod]._indices.push_back (nLocIndex);
_lod[_currentLod]._indices.push_back (_terrain->_skirtVerticesOffset[2]+i);
_lod[_currentLod]._indices.push_back ((i+step)*(gridX+1));
_lod[_currentLod]._indices.push_back ((i+step)*(gridX+1));
_lod[_currentLod]._indices.push_back (_terrain->_skirtVerticesOffset[2]+i);
_lod[_currentLod]._indices.push_back (_terrain->_skirtVerticesOffset[2]+i +step);
}
//#4
for(int j =0;j<gridX;j+=step)
{
int nLocIndex = j;
_lod[_currentLod]._indices.push_back (nLocIndex + step);
_lod[_currentLod]._indices.push_back (_terrain->_skirtVerticesOffset[3]+j);
_lod[_currentLod]._indices.push_back (nLocIndex);
_lod[_currentLod]._indices.push_back (_terrain->_skirtVerticesOffset[3] + j + step);
_lod[_currentLod]._indices.push_back (_terrain->_skirtVerticesOffset[3] +j);
_lod[_currentLod]._indices.push_back (nLocIndex + step);
}
_chunkIndices = _terrain->insertIndicesLODSkirt(_currentLod,&_lod[_currentLod]._indices[0], (int)_lod[_currentLod]._indices.size());
}
Terrain::QuadTree::QuadTree(int x, int y, int w, int h, Terrain * terrain)
{
_terrain = terrain;
_needDraw = true;
_parent = nullptr;
_tl =nullptr;
_tr =nullptr;
_bl =nullptr;
_br =nullptr;
_posX = x;
_posY = y;
this->_height = h;
this->_width = w;
if(_width> terrain->_chunkSize.width &&_height >terrain->_chunkSize.height) //subdivision
{
_isTerminal = false;
this->_tl = new QuadTree(x,y,_width/2,_height/2,terrain);
this->_tl->_parent = this;
this->_tr = new QuadTree(x+_width/2,y,_width/2,_height/2,terrain);
this->_tr->_parent = this;
this->_bl = new QuadTree(x,y+_height/2,_width/2,_height/2,terrain);
this->_bl->_parent = this;
this->_br = new QuadTree(x+_width/2,y+_height/2,_width/2,_height/2,terrain);
this->_br->_parent = this;
_localAABB.merge(_tl->_localAABB);
_localAABB.merge(_tr->_localAABB);
_localAABB.merge(_bl->_localAABB);
_localAABB.merge(_br->_localAABB);
}else // is terminal Node
{
int m = _posY/terrain->_chunkSize.height;
int n = _posX/terrain->_chunkSize.width;
_chunk = terrain->_chunkesArray[m][n];
_isTerminal = true;
_localAABB = _chunk->_aabb;
_chunk->_parent = this;
}
_worldSpaceAABB = _localAABB;
_worldSpaceAABB.transform(_terrain->getNodeToWorldTransform());
}
void Terrain::QuadTree::draw()
{
if(!_needDraw)return;
if(_isTerminal){
this->_chunk->bindAndDraw();
}else
{
this->_tl->draw();
this->_tr->draw();
this->_br->draw();
this->_bl->draw();
}
}
void Terrain::QuadTree::resetNeedDraw(bool value)
{
this->_needDraw = value;
if(!_isTerminal)
{
_tl->resetNeedDraw(value);
_tr->resetNeedDraw(value);
_bl->resetNeedDraw(value);
_br->resetNeedDraw(value);
}
}
void Terrain::QuadTree::cullByCamera(const Camera * camera, const Mat4 & worldTransform)
{
if(!camera->isVisibleInFrustum(&_worldSpaceAABB))
{
this->resetNeedDraw(false);
}else
{
if(!_isTerminal){
_tl->cullByCamera(camera,worldTransform);
_tr->cullByCamera(camera,worldTransform);
_bl->cullByCamera(camera,worldTransform);
_br->cullByCamera(camera,worldTransform);
}
}
}
void Terrain::QuadTree::preCalculateAABB(const Mat4 & worldTransform)
{
_worldSpaceAABB = _localAABB;
_worldSpaceAABB.transform(worldTransform);
if(!_isTerminal){
_tl->preCalculateAABB(worldTransform);
_tr->preCalculateAABB(worldTransform);
_bl->preCalculateAABB(worldTransform);
_br->preCalculateAABB(worldTransform);
}
}
Terrain::QuadTree::~QuadTree()
{
if(_tl) delete _tl;
if(_tr) delete _tr;
if(_bl) delete _bl;
if(_br) delete _br;
}
Terrain::TerrainData::TerrainData(const char * heightMapsrc , const char * textureSrc, const Size & chunksize, float height, float scale)
{
this->_heightMapSrc = heightMapsrc;
this->_detailMaps[0]._detailMapSrc = textureSrc;
this->_alphaMapSrc = nullptr;
this->_chunkSize = chunksize;
this->_mapHeight = height;
this->_mapScale = scale;
_skirtHeightRatio = 1;
}
Terrain::TerrainData::TerrainData(const char * heightMapsrc, const char * alphamap, const DetailMap& detail1, const DetailMap& detail2, const DetailMap& detail3, const DetailMap& detail4, const Size & chunksize, float height, float scale)
{
this->_heightMapSrc = heightMapsrc;
this->_alphaMapSrc = const_cast<char *>(alphamap);
this->_detailMaps[0] = detail1;
this->_detailMaps[1] = detail2;
this->_detailMaps[2] = detail3;
this->_detailMaps[3] = detail4;
this->_chunkSize = chunksize;
this->_mapHeight = height;
this->_mapScale = scale;
_detailMapAmount = 4;
_skirtHeightRatio = 1;
}
Terrain::TerrainData::TerrainData(const char* heightMapsrc, const char * alphamap, const DetailMap& detail1, const DetailMap& detail2, const DetailMap& detail3, const Size & chunksize /*= Size(32,32)*/, float height /*= 2*/, float scale /*= 0.1*/)
{
this->_heightMapSrc = heightMapsrc;
this->_alphaMapSrc = const_cast<char *>(alphamap);
this->_detailMaps[0] = detail1;
this->_detailMaps[1] = detail2;
this->_detailMaps[2] = detail3;
this->_detailMaps[3] = nullptr;
this->_chunkSize = chunksize;
this->_mapHeight = height;
this->_mapScale = scale;
_detailMapAmount = 3;
_skirtHeightRatio = 1;
}
Terrain::TerrainData::TerrainData()
{
}
Terrain::DetailMap::DetailMap(const char * detailMapPath, float size /*= 35*/)
{
this->_detailMapSrc = detailMapPath;
this->_detailMapSize = size;
}
Terrain::DetailMap::DetailMap()
{
_detailMapSrc = "";
_detailMapSize = 35;
}
NS_CC_END
| [
"[email protected]"
] | |
92767cb0db2c3b9c8fa5dc0b12c1ed2fa02af203 | 8af1c8d72e6b7e9471987f945ebff059278da526 | /CMSIS/DSP/Testing/Include/Benchmarks/BasicMathsBenchmarksF32.h | 1b1304192d544adbcb6e723c5573bd2fd256dd3a | [
"Apache-2.0"
] | permissive | WMXZ-EU/CMSIS_5 | 8899559de35d76516982536cd810f8af839e0c77 | 572825384134b9c7dcda421e357e9bcc433fb5fb | refs/heads/develop | 2021-01-12T14:54:15.304086 | 2020-06-09T17:18:14 | 2020-06-09T17:18:14 | 72,098,551 | 0 | 0 | Apache-2.0 | 2020-06-09T17:18:15 | 2016-10-27T10:42:38 | C | UTF-8 | C++ | false | false | 787 | h | #include "Test.h"
#include "Pattern.h"
class BasicMathsBenchmarksF32:public Client::Suite
{
public:
BasicMathsBenchmarksF32(Testing::testID_t id);
virtual void setUp(Testing::testID_t,std::vector<Testing::param_t>& params,Client::PatternMgr *mgr);
virtual void tearDown(Testing::testID_t,Client::PatternMgr *mgr);
private:
#include "BasicMathsBenchmarksF32_decl.h"
Client::Pattern<float32_t> input1;
Client::Pattern<float32_t> input2;
Client::LocalPattern<float32_t> output;
Client::RefPattern<float32_t> ref;
int nb;
float32_t *inp1;
float32_t *inp2;
float32_t *outp;
float32_t *refp;
};
| [
"[email protected]"
] | |
0087be7bd74ba11e1f6f7d1d0540a7633d0d5c82 | adff6cc4a18461fdfe1a3045e3724eed528016db | /src/init.cpp | 3df65847b940513ec66cc6b7c99cd19f2814a1b2 | [
"MIT"
] | permissive | Prabhatsingh411/NewlogosCoin | b820106db756c937df344587ddb3c474536cb198 | 224b3c5d37bca5a386fdf7ffb80cbe566f8ae27d | refs/heads/master | 2020-05-17T02:30:49.925805 | 2015-04-08T13:31:31 | 2015-04-08T13:31:31 | 33,608,526 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,995 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txdb.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "net.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <openssl/crypto.h>
#ifndef WIN32
#include <signal.h>
#endif
#if defined(USE_SSE2)
#if !defined(MAC_OSX) && (defined(_M_IX86) || defined(__i386__) || defined(__i386))
#ifdef _MSC_VER
// MSVC 64bit is unable to use inline asm
#include <intrin.h>
#else
// GCC Linux or i686-w64-mingw32
#include <cpuid.h>
#endif
#endif
#endif
using namespace std;
using namespace boost;
CWallet* pwalletMain;
CClientUIInterface uiInterface;
#ifdef WIN32
// Win32 LevelDB doesn't use filedescriptors, and the ones used for
// accessing block files, don't count towards to fd_set size limit
// anyway.
#define MIN_CORE_FILEDESCRIPTORS 0
#else
#define MIN_CORE_FILEDESCRIPTORS 150
#endif
// Used to pass flags to the Bind() function
enum BindFlags {
BF_NONE = 0,
BF_EXPLICIT = (1U << 0),
BF_REPORT_ERROR = (1U << 1)
};
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
//
// Thread management and startup/shutdown:
//
// The network-processing threads are all part of a thread group
// created by AppInit() or the Qt main() function.
//
// A clean exit happens when StartShutdown() or the SIGTERM
// signal handler sets fRequestShutdown, which triggers
// the DetectShutdownThread(), which interrupts the main thread group.
// DetectShutdownThread() then exits, which causes AppInit() to
// continue (it .joins the shutdown thread).
// Shutdown() is then
// called to clean up database connections, and stop other
// threads that should only be stopped after the main network-processing
// threads have exited.
//
// Note that if running -daemon the parent process returns from AppInit2
// before adding any threads to the threadGroup, so .join_all() returns
// immediately and the parent exits from main().
//
// Shutdown for Qt is very similar, only it uses a QTimer to detect
// fRequestShutdown getting set, and then does the normal Qt
// shutdown thing.
//
volatile bool fRequestShutdown = false;
void StartShutdown()
{
fRequestShutdown = true;
}
bool ShutdownRequested()
{
return fRequestShutdown;
}
static CCoinsViewDB *pcoinsdbview;
void Shutdown()
{
printf("Shutdown : In progress...\n");
static CCriticalSection cs_Shutdown;
TRY_LOCK(cs_Shutdown, lockShutdown);
if (!lockShutdown) return;
RenameThread("bitcoin-shutoff");
nTransactionsUpdated++;
StopRPCThreads();
ShutdownRPCMining();
if (pwalletMain)
bitdb.Flush(false);
GenerateBitcoins(false, NULL);
StopNode();
{
LOCK(cs_main);
if (pwalletMain)
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
if (pblocktree)
pblocktree->Flush();
if (pcoinsTip)
pcoinsTip->Flush();
delete pcoinsTip; pcoinsTip = NULL;
delete pcoinsdbview; pcoinsdbview = NULL;
delete pblocktree; pblocktree = NULL;
}
if (pwalletMain)
bitdb.Flush(true);
boost::filesystem::remove(GetPidFile());
UnregisterWallet(pwalletMain);
if (pwalletMain)
delete pwalletMain;
printf("Shutdown : done\n");
}
//
// Signal handlers are very limited in what they are allowed to do, so:
//
void DetectShutdownThread(boost::thread_group* threadGroup)
{
// Tell the main threads to shutdown.
while (!fRequestShutdown)
{
MilliSleep(200);
if (fRequestShutdown)
threadGroup->interrupt_all();
}
}
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
void HandleSIGHUP(int)
{
fReopenDebugLog = true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
#if !defined(QT_GUI)
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
boost::thread* detectShutdownThread = NULL;
bool fRet = false;
try
{
//
// Parameters
//
// If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main()
ParseParameters(argc, argv);
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
fprintf(stderr, "Error: Specified directory does not exist\n");
Shutdown();
}
ReadConfigFile(mapArgs, mapMultiArgs);
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to bitcoind / RPC client
std::string strUsage = _("Logos version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" logosd [options] " + "\n" +
" logosd [options] <command> [params] " + _("Send command to -server or logosd") + "\n" +
" logosd [options] help " + _("List commands") + "\n" +
" logosd [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage();
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "logos:"))
fCommandLine = true;
if (fCommandLine)
{
int ret = CommandLineRPC(argc, argv);
exit(ret);
}
#if !defined(WIN32)
fDaemon = GetBoolArg("-daemon");
if (fDaemon)
{
// Daemonize
pid_t pid = fork();
if (pid < 0)
{
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
CreatePidFile(GetPidFile(), pid);
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet) {
if (detectShutdownThread)
detectShutdownThread->interrupt();
threadGroup.interrupt_all();
}
if (detectShutdownThread)
{
detectShutdownThread->join();
delete detectShutdownThread;
detectShutdownThread = NULL;
}
Shutdown();
return fRet;
}
extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
// Connect bitcoind signal handlers
noui_connect();
fRet = AppInit(argc, argv);
if (fRet && fDaemon)
return 0;
return (fRet ? 0 : 1);
}
#endif
bool static InitError(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
return false;
}
bool static InitWarning(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
return true;
}
bool static Bind(const CService &addr, unsigned int flags) {
if (!(flags & BF_EXPLICIT) && IsLimited(addr))
return false;
std::string strError;
if (!BindListenPort(addr, strError)) {
if (flags & BF_REPORT_ERROR)
return InitError(strError);
return false;
}
return true;
}
// Core-specific options shared between UI and daemon
std::string HelpMessage()
{
string strUsage = _("Options:") + "\n" +
" -? " + _("This help message") + "\n" +
" -conf=<file> " + _("Specify configuration file (default: logos.conf)") + "\n" +
" -pid=<file> " + _("Specify pid file (default: logosd.pid)") + "\n" +
" -gen " + _("Generate coins (default: 0)") + "\n" +
" -datadir=<dir> " + _("Specify data directory") + "\n" +
" -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
" -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" +
" -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" +
" -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" +
" -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"
" -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" +
" -port=<port> " + _("Listen for connections on <port> (default: 9333 or testnet: 19333)") + "\n" +
" -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" +
" -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" +
" -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" +
" -change=<address> " + _("Send change only to the specified address(es)") + "\n" +
" -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" +
" -externalip=<ip> " + _("Specify your own public address") + "\n" +
" -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" +
" -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" +
" -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n" +
" -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" +
" -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n" +
" -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n" +
" -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" +
" -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" +
" -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" +
" -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" +
" -bloomfilters " + _("Allow peers to set bloom filters (default: 1)") + "\n" +
#ifdef USE_UPNP
#if USE_UPNP
" -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" +
#else
" -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" +
#endif
#endif
" -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" +
" -mininput=<amt> " + _("When creating transactions, ignore inputs with value less than this (default: 0.0001)") + "\n" +
#ifdef QT_GUI
" -server " + _("Accept command line and JSON-RPC commands") + "\n" +
#endif
#if !defined(WIN32) && !defined(QT_GUI)
" -daemon " + _("Run in the background as a daemon and accept commands") + "\n" +
#endif
" -testnet " + _("Use the test network") + "\n" +
" -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" +
" -debugnet " + _("Output extra network debugging information") + "\n" +
" -logtimestamps " + _("Prepend debug output with timestamp (default: 1)") + "\n" +
" -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" +
" -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" +
#ifdef WIN32
" -printtodebugger " + _("Send trace/debug info to debugger") + "\n" +
#endif
" -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" +
" -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" +
" -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)") + "\n" +
" -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" +
#ifndef QT_GUI
" -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" +
#endif
" -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n" +
" -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" +
" -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" +
" -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" +
" -upgradewallet " + _("Upgrade wallet to latest format") + "\n" +
" -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" +
" -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" +
" -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" +
" -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n" +
" -checklevel=<n> " + _("How thorough the block verification is (0-4, default: 3)") + "\n" +
" -txindex " + _("Maintain a full transaction index (default: 0)") + "\n" +
" -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + "\n" +
" -reindex " + _("Rebuild block chain index from current blk000??.dat files") + "\n" +
" -par=<n> " + _("Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)") + "\n" +
"\n" + _("Block creation options:") + "\n" +
" -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" +
" -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
" -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
"\n" + _("SSL options: (see the Logos Wiki for SSL setup instructions)") + "\n" +
" -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
" -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
" -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
" -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n";
return strUsage;
}
struct CImportingNow
{
CImportingNow() {
assert(fImporting == false);
fImporting = true;
}
~CImportingNow() {
assert(fImporting == true);
fImporting = false;
}
};
void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
{
RenameThread("bitcoin-loadblk");
// -reindex
if (fReindex) {
CImportingNow imp;
int nFile = 0;
while (true) {
CDiskBlockPos pos(nFile, 0);
FILE *file = OpenBlockFile(pos, true);
if (!file)
break;
printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
LoadExternalBlockFile(file, &pos);
nFile++;
}
pblocktree->WriteReindexing(false);
fReindex = false;
printf("Reindexing finished\n");
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
InitBlockIndex();
}
// hardcoded $DATADIR/bootstrap.dat
filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (filesystem::exists(pathBootstrap)) {
FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
CImportingNow imp;
filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
printf("Importing bootstrap.dat...\n");
LoadExternalBlockFile(file);
RenameOver(pathBootstrap, pathBootstrapOld);
}
}
// -loadblock=
BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) {
FILE *file = fopen(path.string().c_str(), "rb");
if (file) {
CImportingNow imp;
printf("Importing %s...\n", path.string().c_str());
LoadExternalBlockFile(file);
}
}
}
/** Initialize bitcoin.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit2(boost::thread_group& threadGroup)
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable Data Execution Prevention (DEP)
// Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
// A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
// which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2)
{
return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret));
}
#endif
#ifndef WIN32
umask(077);
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
#endif
#if defined(USE_SSE2)
unsigned int cpuid_edx=0;
#if !defined(MAC_OSX) && (defined(_M_IX86) || defined(__i386__) || defined(__i386))
// 32bit x86 Linux or Windows, detect cpuid features
#if defined(_MSC_VER)
// MSVC
int x86cpuid[4];
__cpuid(x86cpuid, 1);
cpuid_edx = (unsigned int)buffer[3];
#else
// Linux or i686-w64-mingw32 (gcc-4.6.3)
unsigned int eax, ebx, ecx;
__get_cpuid(1, &eax, &ebx, &ecx, &cpuid_edx);
#endif
#endif
#endif
// ********************************************************* Step 2: parameter interactions
fTestNet = GetBoolArg("-testnet");
fBloomFilters = GetBoolArg("-bloomfilters", true);
if (fBloomFilters)
nLocalServices |= NODE_BLOOM;
if (mapArgs.count("-bind")) {
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
SoftSetBoolArg("-listen", true);
}
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
SoftSetBoolArg("-dnsseed", false);
SoftSetBoolArg("-listen", false);
}
if (mapArgs.count("-proxy")) {
// to protect privacy, do not listen by default if a proxy server is specified
SoftSetBoolArg("-listen", false);
}
if (!GetBoolArg("-listen", true)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
SoftSetBoolArg("-upnp", false);
SoftSetBoolArg("-discover", false);
}
if (mapArgs.count("-externalip")) {
// if an explicit public IP is specified, do not try to find others
SoftSetBoolArg("-discover", false);
}
if (GetBoolArg("-salvagewallet")) {
// Rewrite just private keys: rescan to find transactions
SoftSetBoolArg("-rescan", true);
}
// Make sure enough file descriptors are available
int nBind = std::max((int)mapArgs.count("-bind"), 1);
nMaxConnections = GetArg("-maxconnections", 125);
nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
if (nFD < MIN_CORE_FILEDESCRIPTORS)
return InitError(_("Not enough file descriptors available."));
if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
// ********************************************************* Step 3: parameter-to-internal-flags
fDebug = GetBoolArg("-debug");
fBenchmark = GetBoolArg("-benchmark");
// -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
nScriptCheckThreads = GetArg("-par", 0);
if (nScriptCheckThreads <= 0)
nScriptCheckThreads += boost::thread::hardware_concurrency();
if (nScriptCheckThreads <= 1)
nScriptCheckThreads = 0;
else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
// -debug implies fDebug*
if (fDebug)
fDebugNet = true;
else
fDebugNet = GetBoolArg("-debugnet");
if (fDaemon)
fServer = true;
else
fServer = GetBoolArg("-server");
/* force fServer when running without GUI */
#if !defined(QT_GUI)
fServer = true;
#endif
fPrintToConsole = GetBoolArg("-printtoconsole");
fPrintToDebugger = GetBoolArg("-printtodebugger");
fLogTimestamps = GetBoolArg("-logtimestamps", true);
bool fDisableWallet = GetBoolArg("-disablewallet", false);
if (mapArgs.count("-timeout"))
{
int nNewTimeout = GetArg("-timeout", 5000);
if (nNewTimeout > 0 && nNewTimeout < 600000)
nConnectTimeout = nNewTimeout;
}
// Continue to put "/P2SH/" in the coinbase to monitor
// BIP16 support.
// This can be removed eventually...
const char* pszP2SH = "/P2SH/";
COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH));
// Fee-per-kilobyte amount considered the same as "free"
// If you are mining, be careful setting this:
// if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
if (mapArgs.count("-mintxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
CTransaction::nMinTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"].c_str()));
}
if (mapArgs.count("-minrelaytxfee"))
{
int64 n = 0;
if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
CTransaction::nMinRelayTxFee = n;
else
return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"].c_str()));
}
if (mapArgs.count("-paytxfee"))
{
if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee))
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str()));
if (nTransactionFee > 0.25 * COIN)
InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
}
if (mapArgs.count("-mininput"))
{
if (!ParseMoney(mapArgs["-mininput"], nMinimumInputValue))
return InitError(strprintf(_("Invalid amount for -mininput=<amount>: '%s'"), mapArgs["-mininput"].c_str()));
}
// ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
std::string strDataDir = GetDataDir().string();
// Make sure only a single Bitcoin process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Logos is probably already running."), strDataDir.c_str()));
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
printf("Logos version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
if (!fLogTimestamps)
printf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
printf("Default data directory %s\n", GetDefaultDataDir().string().c_str());
printf("Using data directory %s\n", strDataDir.c_str());
printf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
std::ostringstream strErrors;
if (fDaemon)
fprintf(stdout, "Logos server starting\n");
if (nScriptCheckThreads) {
printf("Using %u threads for script verification\n", nScriptCheckThreads);
for (int i=0; i<nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
}
int64 nStart;
// ********************************************************* Step 5: verify wallet database integrity
if (!fDisableWallet) {
uiInterface.InitMessage(_("Verifying wallet..."));
if (!bitdb.Open(GetDataDir()))
{
// try moving the database env out of the way
boost::filesystem::path pathDatabase = GetDataDir() / "database";
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRI64d".bak", GetTime());
try {
boost::filesystem::rename(pathDatabase, pathDatabaseBak);
printf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str());
} catch(boost::filesystem::filesystem_error &error) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try again
if (!bitdb.Open(GetDataDir())) {
// if it still fails, it probably means we can't even create the database env
string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str());
return InitError(msg);
}
}
if (GetBoolArg("-salvagewallet"))
{
// Recover readable keypairs:
if (!CWalletDB::Recover(bitdb, "wallet.dat", true))
return false;
}
if (filesystem::exists(GetDataDir() / "wallet.dat"))
{
CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK)
{
string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."), strDataDir.c_str());
InitWarning(msg);
}
if (r == CDBEnv::RECOVER_FAIL)
return InitError(_("wallet.dat corrupt, salvage failed"));
}
} // (!fDisableWallet)
// ********************************************************* Step 6: network initialization
int nSocksVersion = GetArg("-socks", 5);
if (nSocksVersion != 4 && nSocksVersion != 5)
return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion));
if (mapArgs.count("-onlynet")) {
std::set<enum Network> nets;
BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str()));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetLimited(net);
}
}
#if defined(USE_IPV6)
#if ! USE_IPV6
else
SetLimited(NET_IPV6);
#endif
#endif
CService addrProxy;
bool fProxy = false;
if (mapArgs.count("-proxy")) {
addrProxy = CService(mapArgs["-proxy"], 9050);
if (!addrProxy.IsValid())
return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str()));
if (!IsLimited(NET_IPV4))
SetProxy(NET_IPV4, addrProxy, nSocksVersion);
if (nSocksVersion > 4) {
#ifdef USE_IPV6
if (!IsLimited(NET_IPV6))
SetProxy(NET_IPV6, addrProxy, nSocksVersion);
#endif
SetNameProxy(addrProxy, nSocksVersion);
}
fProxy = true;
}
// -tor can override normal proxy, -notor disables tor entirely
if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) {
CService addrOnion;
if (!mapArgs.count("-tor"))
addrOnion = addrProxy;
else
addrOnion = CService(mapArgs["-tor"], 9050);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str()));
SetProxy(NET_TOR, addrOnion, 5);
SetReachable(NET_TOR);
}
// see Step 2: parameter interactions for more information about these
fNoListen = !GetBoolArg("-listen", true);
fDiscover = GetBoolArg("-discover", true);
fNameLookup = GetBoolArg("-dns", true);
bool fBound = false;
if (!fNoListen) {
if (mapArgs.count("-bind")) {
BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str()));
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
}
}
else {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
#ifdef USE_IPV6
fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
#endif
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
}
if (!fBound)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
}
if (mapArgs.count("-externalip")) {
BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str()));
AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
}
}
BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"])
AddOneShot(strDest);
// ********************************************************* Step 7: load block chain
#if defined(USE_SSE2)
scrypt_detect_sse2(cpuid_edx);
#endif
fReindex = GetBoolArg("-reindex");
// Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
filesystem::path blocksDir = GetDataDir() / "blocks";
if (!filesystem::exists(blocksDir))
{
filesystem::create_directories(blocksDir);
bool linked = false;
for (unsigned int i = 1; i < 10000; i++) {
filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
if (!filesystem::exists(source)) break;
filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
try {
filesystem::create_hard_link(source, dest);
printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str());
linked = true;
} catch (filesystem::filesystem_error & e) {
// Note: hardlink creation failing is not a disaster, it just means
// blocks will get re-downloaded from peers.
printf("Error hardlinking blk%04u.dat : %s\n", i, e.what());
break;
}
}
if (linked)
{
fReindex = true;
}
}
// cache size calculations
size_t nTotalCache = GetArg("-dbcache", 25) << 20;
if (nTotalCache < (1 << 22))
nTotalCache = (1 << 22); // total cache cannot be less than 4 MiB
size_t nBlockTreeDBCache = nTotalCache / 8;
if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false))
nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
nTotalCache -= nBlockTreeDBCache;
size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
nTotalCache -= nCoinDBCache;
nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
bool fLoaded = false;
while (!fLoaded) {
bool fReset = fReindex;
std::string strLoadError;
uiInterface.InitMessage(_("Loading block index..."));
nStart = GetTimeMillis();
do {
try {
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinsTip = new CCoinsViewCache(*pcoinsdbview);
if (fReindex)
pblocktree->WriteReindexing(true);
if (!LoadBlockIndex()) {
strLoadError = _("Error loading block database");
break;
}
// If the loaded chain has a wrong genesis, bail out immediately
// (we're likely using a testnet datadir, or the other way around).
if (!mapBlockIndex.empty() && pindexGenesisBlock == NULL)
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
// Initialize the block index (no-op if non-empty database was already loaded)
if (!InitBlockIndex()) {
strLoadError = _("Error initializing block database");
break;
}
// Check for changed -txindex state
if (fTxIndex != GetBoolArg("-txindex", false)) {
strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
break;
}
uiInterface.InitMessage(_("Verifying blocks..."));
if (!VerifyDB(GetArg("-checklevel", 3),
GetArg( "-checkblocks", 288))) {
strLoadError = _("Corrupted block database detected");
break;
}
} catch(std::exception &e) {
strLoadError = _("Error opening block database");
break;
}
fLoaded = true;
} while(false);
if (!fLoaded) {
// first suggest a reindex
if (!fReset) {
bool fRet = uiInterface.ThreadSafeMessageBox(
strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
"", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
if (fRet) {
fReindex = true;
fRequestShutdown = false;
} else {
return false;
}
} else {
return InitError(strLoadError);
}
}
}
// as LoadBlockIndex can take several minutes, it's possible the user
// requested to kill bitcoin-qt during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown)
{
printf("Shutdown requested. Exiting.\n");
return false;
}
printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
PrintBlockTree();
return false;
}
if (mapArgs.count("-printblock"))
{
string strMatch = mapArgs["-printblock"];
int nFound = 0;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
uint256 hash = (*mi).first;
if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0)
{
CBlockIndex* pindex = (*mi).second;
CBlock block;
block.ReadFromDisk(pindex);
block.BuildMerkleTree();
block.print();
printf("\n");
nFound++;
}
}
if (nFound == 0)
printf("No blocks matching %s were found\n", strMatch.c_str());
return false;
}
// ********************************************************* Step 8: load wallet
if (fDisableWallet) {
printf("Wallet disabled!\n");
pwalletMain = NULL;
} else {
uiInterface.InitMessage(_("Loading wallet..."));
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet("wallet.dat");
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
InitWarning(msg);
}
else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << _("Error loading wallet.dat: Wallet requires newer version of Logos") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strErrors << _("Wallet needed to be rewritten: restart Logos to complete") << "\n";
printf("%s", strErrors.str().c_str());
return InitError(strErrors.str());
}
else
strErrors << _("Error loading wallet.dat") << "\n";
}
if (GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
printf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
printf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < pwalletMain->GetVersion())
strErrors << _("Cannot downgrade wallet") << "\n";
pwalletMain->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) {
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), ""))
strErrors << _("Cannot write default address") << "\n";
}
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
}
printf("%s", strErrors.str().c_str());
printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = pindexBest;
if (GetBoolArg("-rescan"))
pindexRescan = pindexGenesisBlock;
else
{
CWalletDB walletdb("wallet.dat");
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = locator.GetBlockIndex();
else
pindexRescan = pindexGenesisBlock;
}
if (pindexBest && pindexBest != pindexRescan)
{
uiInterface.InitMessage(_("Rescanning..."));
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
nWalletDBUpdated++;
}
} // (!fDisableWallet)
// ********************************************************* Step 9: import blocks
// scan for better chains in the block chain database, that are not yet connected in the active best chain
CValidationState state;
if (!ConnectBestBlock(state))
strErrors << "Failed to connect best block";
std::vector<boost::filesystem::path> vImportFiles;
if (mapArgs.count("-loadblock"))
{
BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"])
vImportFiles.push_back(strFile);
}
threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
// ********************************************************* Step 10: load peers
uiInterface.InitMessage(_("Loading addresses..."));
nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
printf("Invalid or missing peers.dat; recreating\n");
}
printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
// ********************************************************* Step 11: start node
if (!CheckDiskSpace())
return false;
if (!strErrors.str().empty())
return InitError(strErrors.str());
RandAddSeedPerfmon();
//// debug print
printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
printf("mapWallet.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
StartNode(threadGroup);
// InitRPCMining is needed here so getwork/getblocktemplate in the GUI debug console works properly.
InitRPCMining();
if (fServer)
StartRPCThreads();
// Generate coins in the background
if (pwalletMain)
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
// ********************************************************* Step 12: finished
uiInterface.InitMessage(_("Done loading"));
if (pwalletMain) {
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
// Run a thread to flush wallet periodically
threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
}
return !fRequestShutdown;
}
| [
"[email protected]"
] | |
1e7110305077bde7193726589d8810d2ec5c95ca | 247326302397084ac73de487dcd652176fba93c7 | /G2G/mainwindow.h | 2740d490850dfa6befafd4bb706f66e6a0b99c7c | [] | no_license | 15831944/GERBER_X2_VisualStudio2019 | 0e7eb9503b3ce0a4d4315c722a4870694319f677 | 77ae75d92324adec9b8ff2dc48014e311274f70d | refs/heads/master | 2022-04-07T02:06:19.050288 | 2020-03-05T00:49:41 | 2020-03-05T00:49:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,638 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "point.h"
#include "ui_mainwindow.h"
#include <QSettings>
#include <QThread>
#include <qevent.h>
namespace Gerber {
class Parser;
}
namespace Excellon {
class Parser;
}
class DockWidget;
class Project;
class QProgressDialog;
class Scene;
class MainWindow : public QMainWindow, private Ui::MainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget* parent = nullptr);
~MainWindow() override;
// QMainWindow interface
QMenu* createPopupMenu() override;
signals:
void parseGerberFile(const QString& filename);
void parseExcellonFile(const QString& filename);
private:
enum { MaxRecentFiles = 20 };
DockWidget* dockWidget = nullptr;
Gerber::Parser* gerberParser;
Excellon::Parser* excellonParser;
QAction* m_closeAllAct = nullptr;
QAction* recentFileActs[MaxRecentFiles + 1];
QAction* recentFileSeparator = nullptr;
QAction* recentFileSubMenuAct = nullptr;
QMenu* fileMenu = nullptr;
QMenu* helpMenu = nullptr;
QMenu* recentMenu = nullptr;
QMenu* serviceMenu = nullptr;
QString lastPath;
QThread parserThread;
QToolBar* fileToolBar = nullptr;
QToolBar* toolpathToolBar = nullptr;
QToolBar* zoomToolBar = nullptr;
Scene* scene;
Project* m_project;
bool openFlag;
QMap<int, QAction*> toolpathActionList;
QMap<QString, QProgressDialog*> m_progressDialogs;
static MainWindow* m_instance;
inline QString fileKey();
inline QString recentFilesKey();
void about();
bool closeProject();
template<class T>
void createDockWidget(/*QWidget* dwContent,*/ int type);
void createPinsPath();
void fileError(const QString& fileName, const QString& error);
void fileProgress(const QString& fileName, int max, int value);
void initWidgets();
void onCustomContextMenuRequested(const QPoint& pos);
void openRecentFile();
void prependToRecentFiles(const QString& fileName);
void printDialog();
void readSettings();
void redo();
void resetToolPathsActions();
void selectAll();
void setRecentFilesVisible(bool visible);
void updateRecentFileActions();
void writeRecentFiles(const QStringList& files, QSettings& settings);
void writeSettings();
// create actions
void createActions();
void createActionsFile();
void createActionsEdit();
void createActionsService();
void createActionsHelp();
void createActionsZoom();
void createActionsToolPath();
void createActionsGraphics();
QString strippedName(const QString& fullFileName);
QStringList readRecentFiles(QSettings& settings);
bool hasRecentFiles();
void newFile();
void open();
bool save();
bool saveAs();
void documentWasModified();
bool maybeSave();
public:
void loadFile(const QString& fileName);
private:
bool saveFile(const QString& fileName);
void setCurrentFile(const QString& fileName);
void addFileToPro(AbstractFile* file);
// QWidget interface
protected:
void closeEvent(QCloseEvent* event) override;
void contextMenuEvent(QContextMenuEvent* event) override;
void showEvent(QShowEvent* event) override;
};
class DockWidget : public QDockWidget {
Q_OBJECT
public:
explicit DockWidget(QWidget* parent = nullptr)
: QDockWidget(parent)
{
hide();
}
~DockWidget() override = default;
// QWidget interface
protected:
void closeEvent(QCloseEvent* event) override
{
if (widget())
delete widget();
event->accept();
}
};
#endif // MAINWINDOW_H
| [
"[email protected]"
] | |
c1a9e91bf6a4abdfbac0f9f594dbaf274d6918fe | 1072392bee82f383793cd6e31690d2d76c3bfa19 | /httpcd/comm/client/httpc.cpp | 59498338efd2d7a2a49a1498d79bbf7b2c501de0 | [
"Apache-2.0"
] | permissive | Jim-CodeHub/httpcd | 3d4ef706b342ecb88496a26686c04c3754f85006 | d041da7fe1bddaf27d01000b10f1d1ed701368da | refs/heads/master | 2023-07-10T03:39:21.334097 | 2023-07-03T09:16:41 | 2023-07-03T09:16:41 | 214,114,810 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,326 | cpp | /**-----------------------------------------------------------------------------------------------------------------
* @file httpc.cpp
* @brief HTTP client-side communication
*
* Copyright (c) 2019-2019 Jim Zhang [email protected]
*------------------------------------------------------------------------------------------------------------------
*/
#include <httpcd/comm/client/httpc.hpp>
using namespace NS_HTTPCD;
/*
--------------------------------------------------------------------------------------------------------------------
*
* FUNCTIONS IMPLEMENT
*
--------------------------------------------------------------------------------------------------------------------
*/
/**
* @brief HTTP client init
* @param[in] ip - server ip address
* @param[out] None
* @return Standard sockect connect error
**/
int httpc::client_init( const char *ip )
{
return socketc_tcp_v4::client_init(ip, SOCKETCD_PORT_HTTP);
}
/**
* @brief HTTP client init
* @param[in] ip - server ip address
* @param[in] port - Application layer protocol port (for none-standard HTTP port)
* @param[out] None
* @return Standard sockect connect error
**/
int httpc::client_init( const char *ip, in_port_t port )
{
return socketc_tcp_v4::client_init( ip, port );
}
| [
"[email protected]"
] | |
1010b2920eeafc4bf95b825a21f49952afe7e99a | 9f88ad46837a18fa03a5a32fe95dfb0505d5e6bf | /App/integration/env.cpp | 09defd2ab3e43d00f1b73af76ede454e6dd4a99f | [] | no_license | anonysubmit/LPAD | d67bf229a1f8275e15595a8fb08915bdf2516ab5 | 6f097d09b6bb89641697fe962095341a0800cefb | refs/heads/master | 2021-05-05T05:11:08.853367 | 2018-08-07T01:45:08 | 2018-08-07T01:45:08 | 118,666,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,106 | cpp | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "env.h"
namespace leveldb {
Env::~Env() {
}
SequentialFile::~SequentialFile() {
}
RandomAccessFile::~RandomAccessFile() {
}
WritableFile::~WritableFile() {
}
Logger::~Logger() {
}
FileLock::~FileLock() {
}
void Log(Logger* info_log, const char* format, ...) {
if (info_log != NULL) {
va_list ap;
va_start(ap, format);
info_log->Logv(format, ap);
va_end(ap);
}
}
static Status DoWriteStringToFile(Env* env, const Slice& data,
const std::string& fname,
bool should_sync) {
WritableFile* file;
Status s = env->NewWritableFile(fname, &file);
if (!s.ok()) {
return s;
}
s = file->Append(data);
if (s.ok() && should_sync) {
s = file->Sync();
}
if (s.ok()) {
s = file->Close();
}
delete file; // Will auto-close if we did not close above
if (!s.ok()) {
env->DeleteFile(fname);
}
return s;
}
Status WriteStringToFile(Env* env, const Slice& data,
const std::string& fname) {
return DoWriteStringToFile(env, data, fname, false);
}
Status WriteStringToFileSync(Env* env, const Slice& data,
const std::string& fname) {
return DoWriteStringToFile(env, data, fname, true);
}
Status ReadFileToString(Env* env, const std::string& fname, std::string* data) {
data->clear();
SequentialFile* file;
Status s = env->NewSequentialFile(fname, &file);
if (!s.ok()) {
return s;
}
static const int kBufferSize = 8192;
char* space = new char[kBufferSize];
while (true) {
Slice fragment;
s = file->Read(kBufferSize, &fragment, space);
if (!s.ok()) {
break;
}
data->append(fragment.data(), fragment.size());
if (fragment.empty()) {
break;
}
}
delete[] space;
delete file;
return s;
}
EnvWrapper::~EnvWrapper() {
}
} // namespace leveldb
| [
"[email protected]"
] | |
4a2edaea73338b3625f15779d6cd14acbba34d3b | adf3f3d4097e7ff81ecdff377cb2f9ad744342b5 | /Forward/src/Forward/Log.h | 293985953d66f25180c09ebd5bb394f61adcf0b0 | [
"MIT"
] | permissive | ilkeraktug/Forward | 0af4d287b9403afa2316482a6397d32eb2813a41 | 02d64dec1c6165df60332d25e5035cb06d127851 | refs/heads/main | 2023-03-06T13:59:25.376598 | 2021-02-20T14:29:11 | 2021-02-20T14:29:11 | 308,385,787 | 0 | 0 | MIT | 2021-01-24T00:32:07 | 2020-10-29T16:25:07 | C++ | UTF-8 | C++ | false | false | 1,284 | h | #pragma once
#include "Core.h"
#include "spdlog/spdlog.h"
#include "spdlog/fmt/ostr.h"
namespace Forward {
class FORWARD_API Log {
public:
static void Init();
inline static std::shared_ptr<spdlog::logger>& GetCoreLogger() { return s_CoreLogger; }
inline static std::shared_ptr<spdlog::logger>& GetClientLogger() { return s_ClientLogger; }
private:
static std::shared_ptr<spdlog::logger> s_CoreLogger;
static std::shared_ptr<spdlog::logger> s_ClientLogger;
};
}
//Core log
#define FW_CORE_TRACE(...) ::Forward::Log::GetCoreLogger()->trace(__VA_ARGS__)
#define FW_CORE_INFO(...) ::Forward::Log::GetCoreLogger()->info(__VA_ARGS__)
#define FW_CORE_WARN(...) ::Forward::Log::GetCoreLogger()->warn(__VA_ARGS__)
#define FW_CORE_ERROR(...) ::Forward::Log::GetCoreLogger()->error(__VA_ARGS__)
#define FW_CORE_FATAL(...) ::Forward::Log::GetCoreLogger()->critical(__VA_ARGS__)
//Client log
#define FW_TRACE(...) ::Forward::Log::GetClientLogger()->trace(__VA_ARGS__)
#define FW_INFO(...) ::Forward::Log::GetClientLogger()->info(__VA_ARGS__)
#define FW_WARN(...) ::Forward::Log::GetClientLogger()->warn(__VA_ARGS__)
#define FW_ERROR(...) ::Forward::Log::GetClientLogger()->error(__VA_ARGS__)
#define FW_FATAL(...) ::Forward::Log::GetClientLogger()->critical(__VA_ARGS__) | [
"[email protected]"
] | |
8846ac551677458104eb385951a19a3e249cf780 | 061cf3330b0191da087e796af041b50caad31972 | /include/boost/text/trie_fwd.hpp | a13b6115ceebeec1745caa40e52b1d1d103bc66a | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | tzlaine/text | 22515600a70cc3f1c379a177096ca07ba2fbca34 | 0e62505317908caff9897b9f21dcc80ceab2de33 | refs/heads/master | 2023-07-19T20:54:58.386461 | 2023-05-25T12:49:52 | 2023-05-25T23:17:29 | 91,817,420 | 311 | 35 | BSL-1.0 | 2023-05-25T23:17:30 | 2017-05-19T15:02:03 | C++ | UTF-8 | C++ | false | false | 934 | hpp | // Copyright (C) 2020 T. Zachary Laine
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_TEXT_TRIE_FWD_HPP
#define BOOST_TEXT_TRIE_FWD_HPP
namespace boost { namespace text {
/** A statically polymorphic less-than compariason object type. This is
only necessary for pre-C++14 portablility. */
struct less
{
template<typename T>
bool operator()(T const & lhs, T const & rhs) const
{
return std::less<T>{}(lhs, rhs);
}
};
template<
typename Key,
typename Value,
typename Compare = less,
std::size_t KeySize = 0>
struct trie;
template<typename Key, typename Value, typename Compare = less>
struct trie_map;
template<typename Key, typename Compare = less>
struct trie_set;
}}
#endif
| [
"[email protected]"
] | |
a78b74d0e1783b31305212bced2354f3270cbb08 | b1e9a7fce5a036b29d7eefea930330e3365092af | /src/3D/cube.cpp | 660aced531981d6652d54364f2070e1b04c03050 | [] | no_license | VladBermishev/voronoi_diagram_bmp | b81b5a72683178ee8c65f7b4fd5bb4ff2ca0cd0b | 54a7409f97c23af841ecb33eb3d3fdce969bb260 | refs/heads/master | 2022-05-01T17:09:03.601643 | 2019-07-31T14:48:25 | 2019-07-31T14:48:25 | 199,839,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,923 | cpp | // SplashGeom (c) - open-source C++ library for geometry and linear algebra.
// Copyright (c) 2016, Ilya Zakharkin, Elena Kirilenko and Nadezhda Kasimova.
// All rights reserved.
/*
This file is part of SplashGeom.
SplashGeom is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SplashGeom 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 SplashGeom. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cube.hpp"
vector<Point3D> Cube::GetIntersection(const Ray3D &ray) const {
vector<Point3D> line = this->GetIntersection(Line3D(ray));
vector<Point3D> result;
for (auto it = line.begin(); it != line.end(); it++) {
if (ray.Contains(*it))
result.push_back(*it);
}
return result;
}
vector<Point3D> Cube::GetIntersection(const Segment3D &segment) const {
vector<Point3D> line = this->GetIntersection(Line3D(segment));
vector<Point3D> result;
for (auto it = line.begin(); it != line.end(); it++) {
if (segment.Contains(*it))
result.push_back(*it);
}
return result;
}
vector<Point3D> Cube::GetIntersection(const Line3D &line) const {
Point3D p1 = origin;
Point3D p2 = origin + Point3D(0, 0, side);
Point3D p3 = origin + Point3D(0, side, 0);
Point3D p4 = origin + Point3D(side, 0, 0);
Point3D p5 = origin + Point3D(side, side, 0);
Point3D p6 = origin + Point3D(side, 0, side);
Point3D p7 = origin + Point3D(0, side, side);
Plane plane1 = Plane(p1, p2, p3);
Plane plane2 = Plane(p1, p3, p4);
Plane plane3 = Plane(p1, p2, p4);
Plane plane4 = Plane(p3, p5, p7);
Plane plane5 = Plane(p2, p6, p7);
Plane plane6 = Plane(p4, p5, p6);
Point3D inter1 = plane1.GetIntersection(line);
Point3D inter2 = plane2.GetIntersection(line);
Point3D inter3 = plane3.GetIntersection(line);
Point3D inter4 = plane4.GetIntersection(line);
Point3D inter5 = plane5.GetIntersection(line);
Point3D inter6 = plane6.GetIntersection(line);
vector<Point3D> result;
if (this->Boundary(inter1))
result.push_back(inter1);
if (this->Boundary(inter2))
result.push_back(inter2);
if (this->Boundary(inter3))
result.push_back(inter3);
if (this->Boundary(inter4))
result.push_back(inter4);
if (this->Boundary(inter5))
result.push_back(inter5);
if (this->Boundary(inter6))
result.push_back(inter6);
return result;
}
void Cube::ScaleCube(double factor) {
assert(factor >= 0);
this->SetSide(side * cbrt(factor));
}
bool Cube::Contains(const Point3D &point) const {
return point.x >= origin.x &&
point.y >= origin.y &&
point.z >= origin.z &&
point.x <= origin.x + side &&
point.y <= origin.y + side &&
point.z <= origin.z + side;
}
bool Cube::Boundary(const Point3D &point) const {
return this->Contains(point) &&
(point.x == origin.x ||
point.x == origin.x + side ||
point.y == origin.y ||
point.y == origin.y + side ||
point.z == origin.z ||
point.z == origin.z + side);
}
double Cube::Volume() const {
return side * side * side;
}
double Cube::SurfaceArea() const {
return 6 * side * side;
}
Point3D Cube::GetOrigin() const {
return origin;
}
double Cube::GetSide() const {
return side;
}
void Cube::SetOrigin(const Point3D &origin_) {
origin = origin_;
}
void Cube::SetSide(double side_) {
side = side_;
}
| [
"[email protected]"
] | |
eab49bf9df5ac1776cc8eca3bf8e24413d20ad70 | 2549f2e7d73eca116a03c53f50fb08564ca3be08 | /src/InteractiveGraphicsComponent.cpp | 3f16d9467a37b22a8c60c8962ca56dc3a498c739 | [
"MIT"
] | permissive | Eduardojvr/NeonEdgeGame | a4a7f6f24830d6d2ce022635d31b0c22fdb5aeba | 1305853005052765e50d8f5351c23f8ec4ee786d | refs/heads/master | 2021-01-22T18:02:30.532792 | 2017-07-16T03:47:16 | 2017-07-16T03:47:16 | 100,743,895 | 0 | 0 | null | 2017-08-18T19:28:48 | 2017-08-18T19:28:48 | null | UTF-8 | C++ | false | false | 707 | cpp | #include "InteractiveGraphicsComponent.h"
#include "Interactive.h"
#include "Rect.h"
InteractiveGraphicsComponent::InteractiveGraphicsComponent(std::string baseName_):
GraphicsComponent(baseName_)
{
AddSprite(baseName,"Off",1,0);
AddSprite(baseName,"On",1,0);
sp = sprites["Off"];
surface = surfaces["Off"];
}
InteractiveGraphicsComponent::~InteractiveGraphicsComponent()
{
}
void InteractiveGraphicsComponent::Update(GameObject* obj, float dt)
{
Interactive* i = (Interactive*) obj;
mirror = (obj->facing == GameObject::LEFT);
if(i->Active())
{
UpdateSprite(obj, "On");
}
else
{
UpdateSprite(obj, "Off");
}
sp->Mirror(mirror);
sp->Update(dt);
}
| [
"[email protected]"
] | |
c045edcbfe80fc45ac655230a6ac9e3996b3e44a | 9d585217f50ed0c56ef7a0874470581c7689004b | /include/libcpp/memory.hpp | 6ea1b496e9ccd03e88673a0f66e7e9835d2ae11c | [
"MIT"
] | permissive | dgkimura/libcpp | a744214017f21534455947cf67b3488752765bee | 94aef336782d379d56a48f4dc897ef943a4a6b51 | refs/heads/master | 2021-09-12T12:02:27.424806 | 2018-04-15T05:25:38 | 2018-04-15T05:25:38 | 106,947,960 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,810 | hpp | #pragma once
namespace libcpp
{
template <typename T>
class unique_ptr
{
public:
unique_ptr()
: _ptr(nullptr)
{
}
unique_ptr(T* ptr)
: _ptr(ptr)
{
}
unique_ptr(const unique_ptr<T>& rhs) = delete;
unique_ptr<T>& operator=(const unique_ptr<T>& rhs) = delete;
unique_ptr<T>& operator=(unique_ptr<T>&& rhs)
{
swap(rhs);
return *this;
}
T* get()
{
return _ptr;
}
void release()
{
_ptr = nullptr;
}
void swap(unique_ptr& other)
{
T* t = other._ptr;
other._ptr = _ptr;
_ptr = t;
}
~unique_ptr()
{
delete _ptr;
}
private:
T* _ptr;
};
struct control_block
{
long strong_count;
long weak_count;
control_block() : strong_count(0), weak_count(0) {}
long increment()
{
strong_count += 1;
return strong_count;
}
long decrement()
{
strong_count -= 1;
return strong_count;
}
};
template <typename T>
class weak_ptr;
template <typename T>
class shared_ptr
{
public:
shared_ptr()
: _ptr(nullptr),
_count(new control_block())
{
}
shared_ptr(T* ptr)
: _ptr(ptr),
_count(new control_block())
{
_count->increment();
}
shared_ptr(const weak_ptr<T> rhs)
: _ptr(rhs.get()),
_count(rhs._count)
{
_count->increment();
}
shared_ptr(const shared_ptr<T>& rhs)
{
_decrement_count();
rhs._count->increment();
_count = rhs._count;
}
shared_ptr<T>& operator=(const shared_ptr<T>& rhs)
{
_decrement_count();
rhs._count->increment();
_count = rhs._count;
return *this;
}
T* get()
{
return _ptr;
}
long use_count()
{
return _count->strong_count;
}
~shared_ptr()
{
_decrement_count();
}
private:
T* _ptr;
control_block* _count;
void _decrement_count()
{
if (_count->decrement() <= 0)
{
delete _count;
delete _ptr;
}
}
// Allow weak_ptr to share private member variable _count.
template <typename _T> friend class weak_ptr;
};
template <typename T>
class weak_ptr
{
public:
weak_ptr()
: _ptr(nullptr),
_count(new control_block())
{
}
weak_ptr(T* ptr)
: _ptr(ptr),
_count(new control_block())
{
}
weak_ptr(shared_ptr<T> ptr)
: _ptr(ptr.get()),
_count(ptr._count)
{
ptr._count->weak_count += 1;
}
weak_ptr(const weak_ptr<T>& rhs)
: _ptr(rhs._ptr),
_count(rhs._count)
{
if (rhs._count)
{
rhs._count->weak_count += 1;
}
}
weak_ptr<T>& operator=(const weak_ptr<T>& rhs)
{
_count->weak_count -= 1;
rhs._count->weak_count += 1;
_count = rhs._count;
return *this;
}
T* get()
{
return _ptr;
}
long use_count()
{
return _count->strong_count;
}
bool expired()
{
return use_count() == 0;
}
shared_ptr<T> lock()
{
if (expired())
{
return nullptr;
}
shared_ptr<T> result(_ptr);
result._count = _count;
return result;
}
~weak_ptr()
{
}
private:
T* _ptr;
control_block* _count;
// Allow shared_ptr to share private member variable _count.
template <typename _T> friend class shared_ptr;
};
template <typename T>
class enable_shared_from_this
{
public:
shared_ptr<T> shared_from_this()
{
return shared_ptr<T>(_weak_this);
}
private:
weak_ptr<T> _weak_this;
};
}
| [
"[email protected]"
] | |
1ef266d398f82b45e056ba344584afe61afaaa0e | 4e0bba43939a6cbee38f04c678f32bc0e5bfa675 | /src/subscribe_test_core.cpp | 5b35946a1065533a0d61146dc56f32c53176a84b | [] | no_license | k0suke-murakami/subscribe_test | 999d048f70a5fb66906a4220c48b2ab0e5b2d2a7 | 1a9033fa8a89a0bdbc91a76527554b5c02fcee7b | refs/heads/master | 2023-03-29T20:06:56.279965 | 2021-03-23T03:39:08 | 2021-03-23T03:39:08 | 350,567,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,510 | cpp | // Copyright 2020 Tier IV, 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 <chrono>
#include <functional>
#include <memory>
#include <utility>
#include "subscribe_test/subscribe_test_core.hpp"
using std::placeholders::_1;
SubscribeTest::SubscribeTest()
: Node("subscribe_test", rclcpp::NodeOptions().allow_undeclared_parameters(true))
{
// subscriber
rclcpp::QoS qos{1};
sub_path_ = this->create_subscription<sensor_msgs::msg::PointCloud2>(
"pointcloud2", 1, std::bind(&SubscribeTest::callbackAutowarePath, this, _1));
// sub_path_with_lane_id_ = this->create_subscription<autoware_planning_msgs::msg::PathWithLaneId>(
// "input/autoware_path_with_lane_id", 1,
// std::bind(&SubscribeTest::callbackAutowarePathWithLaneId, this, _1));
}
void SubscribeTest::callbackAutowarePath(
const sensor_msgs::msg::PointCloud2::ConstSharedPtr msg_ptr)
{
// auto t_start = std::chrono::high_resolution_clock::now();
// const autoware_planning_msgs::msg::Path path = *msg_ptr;
// const int iter = count % 10 == 0 ? 1000000 : 10000;
// count++;
// for (int i = 0; i < iter; i++) {
// int * test;
// const int as = 100000; // array size
// test = (int *)malloc(sizeof(int) * as);
// test[0] = (int)msg_ptr->header.stamp.sec;
// test[1] = (int)msg_ptr->header.stamp.sec;
// const auto t = test[0] * test[1];
// RCLCPP_DEBUG_STREAM(this->get_logger(), "t " << t);
// free(test);
// }
// auto t_end = std::chrono::high_resolution_clock::now();
// float elapsed_ms = std::chrono::duration<float, std::milli>(t_end - t_start).count();
// RCLCPP_INFO_STREAM(this->get_logger(), "Path Subscribe " << elapsed_ms << "ms");
// RCLCPP_INFO_STREAM(this->get_logger(), "cnt " << cnt_);
std::cerr << 1 << std::endl;
}
// void SubscribeTest::callbackAutowarePathWithLaneId(
// const autoware_planning_msgs::msg::PathWithLaneId::ConstSharedPtr msg_ptr)
// {
// RCLCPP_INFO_STREAM(this->get_logger(), "PathWithLI-Subscribe");
// }
| [
"[email protected]"
] | |
a8df0c412f7b987f101c6592746545ab1b3fde8d | 423662aa4a73a355d292ff313f2d5061c0051df9 | /Arduino_code/code-master/code-master/Pi_Arduino/arduino/src/raspberryCom.ino | bab59a03df5a93b9c615f3ad8cb6ab131b0dbeae | [] | no_license | lbjarre/el2222 | 5150cb29bfca6edf9d34d1698c4156f35f4b779b | b599143825cd6b02b42314198000fc8abeae26d2 | refs/heads/master | 2021-09-04T19:13:55.375809 | 2018-01-21T15:41:14 | 2018-01-21T15:41:14 | 103,390,093 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,782 | ino | // Interpet the meaning of the commands received previously and respond accordingly.
void interpretSerialCmd(String cmd, String subCmd, int* values,
double* left_vel, double* right_vel,
bool* left_rev, bool* right_rev)
{
if ((String)"Hi.Arduino" == cmd) {
Serial.println("Hi.Raspberry");
}
else if ((String)"set.value" == cmd) {
/*if ((String)"lin_vel" == subCmd){
//Implement function to set Linear velocity
//Set values are passed back for debug
left_angular_vel = abs(value[0]);
right_angular_vel = abs(value[0]);
Serial.println(values[0]);
}
else if ((String)"ang_vel" == subCmd){
//Implement function to set angular velocity
//Set values are passed back for debug
Serial.println(values[0]);
}
else{
Serial.println("!!! error !!!!");
}*/
double left = values[0];
double right = values[0];
if (values[1] > 0){
left += values[1];
right -= values[1];
}
else{
left -= values[1];
right += values[1];
}
*left_rev = left < 0;
*right_rev = right > 0;
*left_vel = abs(left);
*right_vel = abs(right);
//Ensure the velocity will be set to zero
}
else if ((String)"get.value" == cmd){
Serial.println("!!! Implementation incomplete !!!!");
}
else{
Serial.println("Cmd_Error");
}
}
//Assuming that command format is ' cmd : sub_cmd value ' or ' cmd : sub_cmd '
//Read the serial data received from the Rpi and parse it for various commands
bool readSerialCmd(double* left_vel, double* right_vel, bool* left_rev, bool* right_rev){
String inCmd = "";
String inValue = "";
String inSubCmd = "";
bool subCmdPresent = false;
short int valueCount = 0;
int values[5];
values[0]=22;
bool newData = 0;
delay(5);
while(Serial.available() > 0){
newData = 1;
int inChar = Serial.read();
if (isDigit(inChar)){
inValue += (char)inChar;
}
else if(isSpace(inChar) || inChar == '\n'){
// Ignore for now
}
else if( inChar == ':' ){
subCmdPresent = true;
}
else if( inChar == ',' ){
if (inValue != ""){
values[valueCount] = inValue.toInt();
}
inValue = "";
valueCount++;
}
else if(isAscii(inChar)){
if(subCmdPresent){
inSubCmd += (char)inChar;
}
else{
inCmd += (char)inChar;
}
}
if (inChar == '\n'){
if (inValue != ""){
values[valueCount] = inValue.toInt();
}
interpretSerialCmd(inCmd,inSubCmd,&values[0], left_vel, right_vel, left_rev, right_rev);
}
}
return newData;
}
| [
"[email protected]"
] | |
8647e9b66ee95689b9cc01c5249320098d99d58a | 331b60fb2e6fa35f40da74425c13203b6d1360a7 | /RiotEngine/main.cpp | cbf0281518e06f4b10a8dfdd4d310cc2665502bd | [] | no_license | bart-proger/RiotEngine | af9935cafe8f477f3999b633b2d6ffb03cbc8e5b | 673576102e94a374b5cc7650fcd05703cdd7408a | refs/heads/master | 2021-01-21T10:34:14.801315 | 2017-02-28T15:37:10 | 2017-02-28T15:37:10 | 83,454,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 123 | cpp | #include <iostream>
int main()
{
std::cout << "*** RiotEngine *** used SDL2 + OpenGL\n";
std::cin.get();
return 0;
} | [
"BART@BART-PC2"
] | BART@BART-PC2 |
ccc8ab8ad6cc6fc5cf5f5d0a0baf73ae8313363a | 0966a64cf0e2799a534f5c84978783ea3b827186 | /IExperimentalMeasurement.h | 59bc4622d67d99a053f60970f677d23285543cb0 | [] | no_license | gclkaze/Experimentor | a9dca854632efba2bb5c79db5b53f3a15879d71e | 40a1b2ebe651d35370902630ed5e849303117d88 | refs/heads/master | 2021-01-23T04:09:58.850444 | 2017-03-26T12:42:19 | 2017-03-26T12:42:19 | 86,168,063 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 361 | h | #pragma once
#include <vector>
#include <string>
class IExperimentalMeasurement{
public:
virtual ~IExperimentalMeasurement(){}
virtual int get(int pos) = 0;
virtual void add(std::string&, int data) = 0;
virtual void calculate(std::vector<float> &storage) = 0;
virtual void getLabels(std::vector<std::string> &labels) = 0;
};
| [
"[email protected]"
] | |
40e40be13770f160caf0de088f93bb494e3c1726 | 4d25c9e286193db52205ce7927b2126ec666bc62 | /xx_chat_client/base/src/network/im_conn.h | feff9c6a6832fe34def8a24b508019f973e3ea66 | [] | no_license | AnonymousRookie/xx_chat | ef7410320f63667e64305efd1733d44cc39668f9 | 1a3a7e4dcf8fabd090de0d3c04af4d2a7402a69c | refs/heads/master | 2021-06-09T19:49:17.932952 | 2020-12-07T15:21:31 | 2020-12-07T15:21:31 | 139,589,005 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,656 | h | /**
* Copyright 2018-2019, AnonymousRookie. All rights reserved.
* https://github.com/AnonymousRookie/xx_chat
* Author: AnonymousRookie (357688981 at qq dot com)
* Description: 所有连接对象的基类ImConn
*/
#ifndef BASE_IM_CONN_H
#define BASE_IM_CONN_H
#include <unordered_map>
#include <memory>
#include "net_lib.h"
#include "util_pdu.h"
#include "im_pdu_base.h"
#define SERVER_HEARTBEAT_INTERVAL 5000
#define SERVER_TIMEOUT 30000
#define CLIENT_HEARTBEAT_INTERVAL 30000
#define CLIENT_TIMEOUT 120000
#define READ_BUF_SIZE 2048
class ImConn : public std::enable_shared_from_this<ImConn>
{
public:
ImConn();
virtual ~ImConn();
bool IsBusy() { return busy_; }
int SendPdu(ImPduPtr pdu);
int SendPdu(ImPdu* pdu);
int Send(void* data, int len);
virtual void OnConnect(net_handle_t handle) { handle_ = handle; }
virtual void OnConfirm() {}
virtual void OnRead();
virtual void OnWrite();
virtual void OnClose() {}
virtual void OnTimer(uint64_t curr_tick) {}
virtual void OnWriteCompelete() {}
virtual void HandlePdu(std::shared_ptr<ImPdu> pPdu) {}
protected:
net_handle_t handle_;
bool busy_;
std::string peerIp_;
uint16_t peerPort_;
SimpleBuffer inBuf_;
SimpleBuffer outBuf_;
uint32_t recvBytes_;
uint64_t lastSendTick_;
uint64_t lastRecvTick_;
uint64_t lastAllUserTick_;
};
typedef std::shared_ptr<ImConn> ImConnPtr;
typedef std::unordered_map<net_handle_t, ImConnPtr> ConnMap;
typedef std::unordered_map<uint32_t, ImConnPtr> UserMap;
void ImConnCallback(uint8_t msg, uint32_t handle, void* callbackData);
#endif // BASE_IM_CONN_H | [
"[email protected]"
] | |
1698dcb69dfa7d0ed322c66d9b4f129a1c76b79d | c23e1cd93ba9d94329e7b0ceca2552adbd1de204 | /IMAT2605/Lecture code/Week 7 - Unit Tests/stdafx.cpp | 67dfaf157579fcdf9c3e0298d3b05c554e8deff3 | [] | no_license | simonCoupland/teaching | 08486cf8bdd796b4bac834855a1b344d4b74930c | 63f88635ffccfef9cc138684d769c6daa388292c | refs/heads/master | 2021-05-03T06:28:54.766369 | 2018-02-07T14:54:16 | 2018-02-07T14:54:16 | 120,594,137 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 298 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Week 7 - Unit Tests.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]"
] | |
2a952711805b1dd27c49793804d4c7b904bf67c1 | 8928069586ba1b2b2d972f72418e3d198e3b62be | /AD.h | 17e85df37cc95c3ae218fbe2e15692c631e673eb | [] | no_license | pawelskrzy/auto_diff | dde7361ca1256e56ebb92e6bf0e043160b0d9485 | 3cf2cd9bd5f2d6db7fe078c79b2aa4164aee3e5e | refs/heads/master | 2020-09-10T22:16:38.615179 | 2016-11-27T16:50:55 | 2016-11-27T16:50:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,941 | h | #pragma once
#include <boost/numeric/ublas/matrix.hpp>
#include <map>
#include <vector>
#include <memory>
#include <iostream>
#include <atomic>
#include <boost/container/flat_map.hpp>
namespace AD {
class ResultType
{
public:
typedef boost::numeric::ublas::matrix<float> matrix;
private:
public:
float m_curValueFloat;
matrix m_curValueMatrix;
bool m_movedAway = false;
enum class CurValueType { scalar, matrix };
CurValueType m_curValueType = CurValueType::scalar;
ResultType();
ResultType(matrix&& m);
ResultType(const matrix& m);
ResultType(float v);
ResultType(int v);
ResultType(ResultType&& other);
ResultType(const ResultType& other);
void operator=(const ResultType& other);
void operator=(ResultType&& other);
~ResultType();
ResultType Transpose() const;
ResultType Product(const ResultType& other) const;
ResultType operator*(const ResultType& other) const;
// 1 to all
template<typename T>
ResultType ApplyUnaryFunc(const T& t) const
{
if (m_curValueType == CurValueType::scalar)
return t(m_curValueFloat);
//matrix m = m_curValueMatrix;
matrix m = MatrixCache::Get().GetMatrix(m_curValueMatrix.size1(), m_curValueMatrix.size2());
const size_t target = m.data().size();
for (size_t i = 0; i < target; i++)
{
m.data()[i] = t(m_curValueMatrix.data()[i]);
}
return m;
}
ResultType operator+(const ResultType& other) const;
ResultType operator-(const ResultType& other) const;
friend std::ostream & operator<<(std::ostream &os, const ResultType& p);
};
class Differentiable;
class Utils
{
public:
typedef boost::numeric::ublas::matrix<float> matrix;
// will create a matrix in 1 row
static matrix CreateRowMatrix(std::vector<float>&& v);
/**
{{0 1 2 3},
{2,3,4,1},
{4,4,4,4}} will create a 3x4 matrix
*/
static matrix CreateMatrix(std::vector<std::vector<float> >&&v);
};
class ExprWrapper
{
std::shared_ptr<Differentiable> m_holdedValue;
template<typename T, typename ...Args>
static std::shared_ptr<T> Make(Args&&... args)
{
return std::make_shared<T>(std::forward<Args>(args)...);
}
public:
ExprWrapper() {}
ExprWrapper(ResultType v);
ExprWrapper(std::shared_ptr<Differentiable> diff);
ExprWrapper operator+(const ExprWrapper& other) const;
ExprWrapper operator+(const ResultType& other) const;
ExprWrapper operator-(const ExprWrapper& other) const;
ExprWrapper operator-(const ResultType& other) const;
ExprWrapper operator*(const ExprWrapper& other) const;
ExprWrapper operator*(const ResultType& other) const;
ExprWrapper MatrixMult(const ResultType& other) const;
ExprWrapper MatrixMult(const ExprWrapper& other) const;
ExprWrapper Sigmoid() const;
ExprWrapper Pow(int powValue) const;
ExprWrapper Softmax() const;
ResultType Calc();
ResultType GetGradBy(ExprWrapper& other);
void Update(ResultType&& newValue);
};
} | [
"[email protected]"
] | |
8280df09c9ace7e33e08f3b73a5202184c92b60c | 18aa7f80167730b46bfad6c476ad509e3e48134d | /queue_from_stacks.cc | f9624fe0565e7f7940962e81fcab089f6cb3437a | [] | no_license | ritwika-reddy/google-prep | cda1f77e8f878098104581db3b1d2c68133a5e51 | cb9c9e2fa283fbe136fd1975f1a897864c6b6151 | refs/heads/master | 2020-04-07T00:16:41.911602 | 2018-11-17T18:59:11 | 2018-11-17T18:59:11 | 157,897,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,105 | cc | #include <stdexcept>
#include <string>
#include <vector>
#include "test_framework/generic_test.h"
#include "test_framework/serialization_traits.h"
#include "test_framework/test_failure.h"
using std::length_error;
using namespace std;
class Queue {
public:
void Enqueue(int x) {
enqueue_.push(x);
}
int Dequeue() {
int ans;
if(dequeue_.empty()){
while(!enqueue_.empty()){
dequeue_.push(enqueue_.top());
enqueue_.pop();
}
}
ans = dequeue_.top();
dequeue_.pop();
return ans;
}
private:
stack<int> enqueue_;
stack<int> dequeue_;
};
struct QueueOp {
enum { kConstruct, kDequeue, kEnqueue } op;
int argument;
QueueOp(const std::string& op_string, int arg) : argument(arg) {
if (op_string == "Queue") {
op = kConstruct;
} else if (op_string == "dequeue") {
op = kDequeue;
} else if (op_string == "enqueue") {
op = kEnqueue;
} else {
throw std::runtime_error("Unsupported queue operation: " + op_string);
}
}
};
template <>
struct SerializationTraits<QueueOp> : UserSerTraits<QueueOp, std::string, int> {
};
void QueueTester(const std::vector<QueueOp>& ops) {
try {
Queue q;
for (auto& x : ops) {
switch (x.op) {
case QueueOp::kConstruct:
break;
case QueueOp::kDequeue: {
int result = q.Dequeue();
if (result != x.argument) {
throw TestFailure("Dequeue: expected " +
std::to_string(x.argument) + ", got " +
std::to_string(result));
}
} break;
case QueueOp::kEnqueue:
q.Enqueue(x.argument);
break;
}
}
} catch (length_error&) {
throw TestFailure("Unexpected length_error exception");
}
}
int main(int argc, char* argv[]) {
std::vector<std::string> args{argv + 1, argv + argc};
std::vector<std::string> param_names{"ops"};
return GenericTestMain(args, "queue_from_stacks.cc", "queue_from_stacks.tsv",
&QueueTester, DefaultComparator{}, param_names);
}
| [
"[email protected]"
] | |
e8b10e18ba047c3be97b4560f5844ef779b24036 | bb20ba88cc104e320374612e00fdddd5fefe86d8 | /C++/3rd_Party/CGAL/include/CGAL/Box_intersection_d/Box_d.h | 2e81dffb62fce2d4f4e19f946bccfec9e21472fd | [] | no_license | cbtogu/3DLearning | 5949e22d16f14a57ab04e0eec0ef1c4364747c76 | 9cfc64ad1e0473aff4e2aef34da50731249d3433 | refs/heads/master | 2022-01-31T10:37:58.177148 | 2017-07-06T15:11:43 | 2017-07-06T15:11:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,289 | h | // Copyright (c) 2004 Max-Planck-Institute Saarbruecken (Germany).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
// You can redistribute it and/or modify it under the terms of the GNU
// General Public License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any later version.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id: Box_d.h,v 1.4 2017/02/06 12:37:03 Emmanuel.Pot Exp $
//
//
// Author(s) : Lutz Kettner <[email protected]>
// Andreas Meyer <[email protected]>
#ifndef CGAL_BOX_INTERSECTION_D_BOX_D_H
#define CGAL_BOX_INTERSECTION_D_BOX_D_H
#include <CGAL/basic.h>
#include <CGAL/Bbox_2.h>
#include <CGAL/Bbox_3.h>
#include <CGAL/Box_intersection_d/box_limits.h>
#include <algorithm>
namespace CGAL {
namespace Box_intersection_d {
// Pseudo template class to skip the need for a C file for the static counter
template <class Dummy>
struct Unique_numbers {
typedef std::size_t ID;
Unique_numbers() : i(n++) {}
std::size_t id() const { return i; }
private:
static std::size_t n;
std::size_t i;
};
template <class Dummy>
std::size_t Unique_numbers<Dummy>::n = 0;
// Policies for id-number of boxes
struct ID_NONE {};
struct ID_EXPLICIT {};
struct ID_FROM_BOX_ADDRESS {};
struct ID_FROM_HANDLE {};
// Generic template signature of boxes, specialized for policies
template<class NT_, int N, class IdPolicy = ID_EXPLICIT>
class Box_d;
// ID_NONE is used as base class and cannot be used directly in the algorithms
template<class NT_, int N>
class Box_d< NT_, N, ID_NONE> {
protected:
NT_ lo[N];
NT_ hi[N];
public:
typedef NT_ NT;
typedef std::size_t ID;
Box_d() {}
Box_d(bool complete) { init(complete); }
Box_d(NT l[N], NT h[N]) {
std::copy( l, l + N, lo );
std::copy( h, h + N, hi );
}
void init (bool complete = false) {
NT inf = box_limits<NT>::inf();
NT sup = box_limits<NT>::sup();
if(!complete)
std::swap(inf,sup);
std::fill( lo, lo+N, inf );
std::fill( hi, hi+N, sup );
}
void extend(NT p[N]) {
for( int dim = 0; dim < N; ++dim ) {
lo[dim] = (std::min)( lo[dim], p[dim] );
hi[dim] = (std::max)( hi[dim], p[dim] );
}
}
void extend(std::pair<NT,NT> p[N]) {
for( int dim = 0; dim < N; ++dim ) {
lo[dim] = (std::min)( lo[dim], p[dim].first );
hi[dim] = (std::max)( hi[dim], p[dim].second );
}
}
static int dimension() { return N; }
NT min_coord(int dim) const { return lo[dim]; }
NT max_coord(int dim) const { return hi[dim]; }
};
// Specialization for Bbox_2, i.e. double and dim 2.
template<>
class Box_d< double, 2, ID_NONE> {
protected:
Bbox_2 bbx;
public:
typedef double NT;
typedef std::size_t ID;
Box_d() {}
Box_d(bool complete) { init(complete); }
Box_d(NT l[2], NT h[2]) : bbx(l[0], l[1], h[0], h[1]) {}
Box_d( const Bbox_2& b) : bbx( b) {}
const Bbox_2& bbox() const { return bbx; }
void init () {
NT inf = box_limits<NT>::inf();
NT sup = box_limits<NT>::sup();
bbx = Bbox_2( sup, sup, inf, inf);
}
void init (bool complete) {
NT inf = box_limits<NT>::inf();
NT sup = box_limits<NT>::sup();
if ( complete)
bbx = Bbox_2( inf, inf, sup, sup);
else
bbx = Bbox_2( sup, sup, inf, inf);
}
void extend(NT p[2]) {
bbx = Bbox_2(
(std::min)( bbx.xmin(), p[0]),
(std::min)( bbx.ymin(), p[1]),
(std::max)( bbx.xmax(), p[0]),
(std::max)( bbx.ymax(), p[1]));
}
void extend(std::pair<NT,NT> p[2]) {
bbx = Bbox_2(
(std::min)( bbx.xmin(), p[0].first),
(std::min)( bbx.ymin(), p[1].first),
(std::max)( bbx.xmax(), p[0].second),
(std::max)( bbx.ymax(), p[1].second));
}
static int dimension() { return 2; }
NT min_coord(int dim) const { return (dim==0) ? bbx.xmin() : bbx.ymin();}
NT max_coord(int dim) const { return (dim==0) ? bbx.xmax() : bbx.ymax();}
};
// Specialization for Bbox_3, i.e. double and dim 3.
template<>
class Box_d< double, 3, ID_NONE> {
protected:
Bbox_3 bbx;
public:
typedef double NT;
typedef std::size_t ID;
Box_d() {}
Box_d(bool complete) { init(complete); }
Box_d(NT l[3], NT h[3]) : bbx(l[0], l[1], l[2], h[0], h[1], h[2]) {}
Box_d( const Bbox_3& b) : bbx( b) {}
const Bbox_3& bbox() const { return bbx; }
void init () {
NT inf = box_limits<NT>::inf();
NT sup = box_limits<NT>::sup();
bbx = Bbox_3( sup, sup, sup, inf, inf, inf);
}
void init (bool complete) {
NT inf = box_limits<NT>::inf();
NT sup = box_limits<NT>::sup();
if ( complete)
bbx = Bbox_3( inf, inf, inf, sup, sup, sup);
else
bbx = Bbox_3( sup, sup, sup, inf, inf, inf);
}
void extend(NT p[3]) {
bbx = Bbox_3(
(std::min)( bbx.xmin(), p[0]),
(std::min)( bbx.ymin(), p[1]),
(std::min)( bbx.zmin(), p[2]),
(std::max)( bbx.xmax(), p[0]),
(std::max)( bbx.ymax(), p[1]),
(std::max)( bbx.zmax(), p[2]));
}
void extend(std::pair<NT,NT> p[3]) {
bbx = Bbox_3(
(std::min)( bbx.xmin(), p[0].first),
(std::min)( bbx.ymin(), p[1].first),
(std::min)( bbx.zmin(), p[2].first),
(std::max)( bbx.xmax(), p[0].second),
(std::max)( bbx.ymax(), p[1].second),
(std::max)( bbx.zmax(), p[2].second));
}
static int dimension() { return 3; }
NT min_coord(int dim) const {
return (dim==0) ? bbx.xmin() : ((dim==1) ? bbx.ymin() : bbx.zmin());
}
NT max_coord(int dim) const {
return (dim==0) ? bbx.xmax() : ((dim==1) ? bbx.ymax() : bbx.zmax());
}
};
// ID_EXPLICIT
template<class NT_, int N>
class Box_d< NT_, N, ID_EXPLICIT> : public Box_d< NT_, N, ID_NONE>,
public Unique_numbers<int> {
public:
typedef Box_d< NT_, N, ID_NONE> Base;
typedef NT_ NT;
typedef typename Unique_numbers<int>::ID ID;
Box_d() {}
Box_d(bool complete) : Base(complete) {}
Box_d(NT l[N], NT h[N]) : Base( l, h) {}
Box_d( const Bbox_2& b) : Base( b) {}
Box_d( const Bbox_3& b) : Base( b) {}
};
// ID_FROM_BOX_ADDRESS
template<class NT_, int N>
class Box_d< NT_, N, ID_FROM_BOX_ADDRESS> : public Box_d< NT_, N, ID_NONE> {
public:
typedef Box_d< NT_, N, ID_NONE> Base;
typedef NT_ NT;
typedef std::size_t ID;
Box_d() {}
Box_d(bool complete) : Base(complete) {}
Box_d(NT l[N], NT h[N]) : Base( l, h) {}
Box_d( const Bbox_2& b) : Base( b) {}
Box_d( const Bbox_3& b) : Base( b) {}
ID id() const { return reinterpret_cast<ID>(this); }
};
} // end namespace Box_intersection_d
} //namespace CGAL
#endif
| [
"[email protected]"
] | |
d31f90d5d0f56b8fd6b6720e016c2f5c6228b593 | 1b9484f051414df045b4be62d44b2e095ba5a71f | /test/ofp/roundtrip_unittest.cpp | aaf51a41d9bf642a6331d384ad506e75ba06d266 | [
"MIT"
] | permissive | byllyfish/oftr | be1ad64864e56911e669849b4a40a2ef29e2ba3e | 5368b65d17d57286412478adcea84371ef5e4fc4 | refs/heads/master | 2022-02-17T15:37:56.907140 | 2022-02-01T04:24:44 | 2022-02-01T04:24:44 | 13,504,446 | 1 | 1 | MIT | 2022-02-01T04:24:44 | 2013-10-11T16:59:19 | C++ | UTF-8 | C++ | false | false | 5,752 | cpp | // Copyright (c) 2015-2018 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include "ofp/ofp.h"
#include "ofp/unittest.h"
using namespace ofp;
const UInt16 kTestingPort = 6666;
class TestController : public ChannelListener {
public:
TestController() {
log_debug("TestController constructed");
++GLOBAL_controllerCount;
}
~TestController() override {
log_debug("TestController destroyed");
--GLOBAL_controllerCount;
}
void onChannelUp(Channel *channel) override {
++GLOBAL_controllerCount;
log_debug("TestController::onChannelUp",
std::make_pair("connid", channel->connectionId()));
channel_ = channel;
DatapathID dpid{0x1234, MacAddress{"A1:B2:C3:D4:E5:F6"}};
EXPECT_EQ(dpid, channel->datapathId());
EXPECT_EQ(0, channel->auxiliaryId());
// TODO(bfish): Check DefaultHandshake parameters.
channel->driver()->stop(1000_ms);
if (GLOBAL_shutdownCount > 0) {
--GLOBAL_shutdownCount;
channel->shutdown();
}
}
void onChannelDown(Channel *channel) override {
--GLOBAL_controllerCount;
log_debug("TestController::onChannelDown",
std::make_pair("connid", channel->connectionId()));
}
void onMessage(Message *message) override {
log_debug("TestController::onMessage",
std::make_pair("connid", message->source()->connectionId()));
EXPECT_EQ(OFPT_FEATURES_REPLY, message->type());
}
static ChannelListener *factory() { return new TestController; }
static int GLOBAL_controllerCount;
static int GLOBAL_shutdownCount;
private:
Channel *channel_ = nullptr;
};
class TestAgent : public ChannelListener {
public:
TestAgent() {
++GLOBAL_agentCount;
log_debug("TestAgent constructed");
}
~TestAgent() override {
--GLOBAL_agentCount;
log_debug("TestAgent destroyed");
}
void onChannelUp(Channel *channel) override {
++GLOBAL_agentCount;
log_debug("TestAgent::onChannelUp",
std::make_pair("connid", channel->connectionId()));
// When agent channel comes up, we expect the datapathId to be all zeros.
DatapathID dpid;
EXPECT_EQ(dpid, channel->datapathId());
EXPECT_EQ(0, channel->auxiliaryId());
EXPECT_LT(0, channel->version());
EXPECT_GE(OFP_VERSION_LAST, channel->version());
}
void onChannelDown(Channel *channel) override {
--GLOBAL_agentCount;
log_debug("TestAgent::onChannelDown",
std::make_pair("connid", channel->connectionId()));
}
void onMessage(Message *message) override {
log_debug("TestAgent::onMessage",
std::make_pair("connid", message->source()->connectionId()));
if (message->type() == OFPT_FEATURES_REQUEST) {
DatapathID dpid{0x1234, MacAddress{"A1:B2:C3:D4:E5:F6"}};
FeaturesReplyBuilder reply{message->xid()};
reply.setDatapathId(dpid);
reply.send(message->source());
} else if (message->type() == OFPT_MULTIPART_REQUEST &&
message->subtype() == OFPMP_PORT_DESC) {
PortList ports; // empty for now
MultipartReplyBuilder reply;
reply.setReplyType(OFPMP_PORT_DESC);
reply.setReplyBody(ports.data(), ports.size());
reply.send(message->source());
}
}
static ChannelListener *factory() { return new TestAgent; }
static int GLOBAL_agentCount;
static int GLOBAL_auxCount;
};
int TestController::GLOBAL_controllerCount = 0;
int TestController::GLOBAL_shutdownCount = 0;
int TestAgent::GLOBAL_agentCount = 0;
int TestAgent::GLOBAL_auxCount = 0;
TEST(roundtrip, basic_test) {
// Before we start, there are no controller or agent listeners.
TestController::GLOBAL_controllerCount = 0;
TestAgent::GLOBAL_agentCount = 0;
{
Driver driver;
IPv6Address localhost{"127.0.0.1"};
std::error_code err1;
(void)driver.listen(ChannelOptions::FEATURES_REQ, 0,
IPv6Endpoint{localhost, kTestingPort},
ProtocolVersions::All, TestController::factory, err1);
// There should be no error on listen, unless the port is in use.
EXPECT_FALSE(err1);
(void)driver.connect(
ChannelOptions::NONE, 0, IPv6Endpoint{localhost, kTestingPort},
ProtocolVersions::All, TestAgent::factory,
[](Channel *, std::error_code err) { EXPECT_FALSE(err); });
// The driver will run until the Controller shuts it down.
driver.run();
EXPECT_EQ(2, TestController::GLOBAL_controllerCount);
EXPECT_EQ(2, TestAgent::GLOBAL_agentCount);
}
// Destruction is complete when Driver goes out of scope.
EXPECT_EQ(0, TestController::GLOBAL_controllerCount);
EXPECT_EQ(0, TestAgent::GLOBAL_agentCount);
}
TEST(roundtrip, shutdown_test) {
TestController::GLOBAL_controllerCount = 0;
TestAgent::GLOBAL_agentCount = 0;
{
Driver driver;
IPv6Address localhost{"127.0.0.1"};
std::error_code err1;
(void)driver.listen(ChannelOptions::FEATURES_REQ, 0,
IPv6Endpoint{localhost, kTestingPort},
ProtocolVersions::All, TestController::factory, err1);
EXPECT_FALSE(err1);
(void)driver.connect(
ChannelOptions::NONE, 0, IPv6Endpoint{localhost, kTestingPort},
ProtocolVersions::All, TestAgent::factory,
[](Channel *, std::error_code err) { EXPECT_FALSE(err); });
TestController::GLOBAL_shutdownCount = 1;
driver.run();
EXPECT_EQ(0, TestController::GLOBAL_shutdownCount);
EXPECT_EQ(0, TestController::GLOBAL_controllerCount);
EXPECT_EQ(0, TestAgent::GLOBAL_agentCount);
}
// Destruction is complete when Driver goes out of scope.
EXPECT_EQ(0, TestController::GLOBAL_controllerCount);
EXPECT_EQ(0, TestAgent::GLOBAL_agentCount);
}
| [
"[email protected]"
] | |
835fd1a1707ded2c0fd75e8378a0ee38fcaa3bb8 | 86d9fc764c6c04e4f5902fca8e15d90655e54de8 | /src/build/devel/include/dji_sdk/MissionWaypoint.h | 3dd464902b83949e7fe334e6352008cede14a4ca | [] | no_license | tianwailaike/DJICHALLENGE2016 | 57cef8cb78b1c3f916f80cdc4ab35c97701d27da | 0f6be72404aeda9d63f0bc1973aa774773080bc9 | refs/heads/master | 2021-04-09T11:55:56.379533 | 2016-07-22T13:44:58 | 2016-07-22T13:44:58 | 63,778,781 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,130 | h | // Generated by gencpp from file dji_sdk/MissionWaypoint.msg
// DO NOT EDIT!
#ifndef DJI_SDK_MESSAGE_MISSIONWAYPOINT_H
#define DJI_SDK_MESSAGE_MISSIONWAYPOINT_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
#include <dji_sdk/MissionWaypointAction.h>
namespace dji_sdk
{
template <class ContainerAllocator>
struct MissionWaypoint_
{
typedef MissionWaypoint_<ContainerAllocator> Type;
MissionWaypoint_()
: latitude(0.0)
, longitude(0.0)
, altitude(0.0)
, damping_distance(0.0)
, target_yaw(0)
, target_gimbal_pitch(0)
, turn_mode(0)
, has_action(0)
, action_time_limit(0)
, waypoint_action() {
}
MissionWaypoint_(const ContainerAllocator& _alloc)
: latitude(0.0)
, longitude(0.0)
, altitude(0.0)
, damping_distance(0.0)
, target_yaw(0)
, target_gimbal_pitch(0)
, turn_mode(0)
, has_action(0)
, action_time_limit(0)
, waypoint_action(_alloc) {
(void)_alloc;
}
typedef double _latitude_type;
_latitude_type latitude;
typedef double _longitude_type;
_longitude_type longitude;
typedef float _altitude_type;
_altitude_type altitude;
typedef float _damping_distance_type;
_damping_distance_type damping_distance;
typedef int16_t _target_yaw_type;
_target_yaw_type target_yaw;
typedef int16_t _target_gimbal_pitch_type;
_target_gimbal_pitch_type target_gimbal_pitch;
typedef uint8_t _turn_mode_type;
_turn_mode_type turn_mode;
typedef uint8_t _has_action_type;
_has_action_type has_action;
typedef uint16_t _action_time_limit_type;
_action_time_limit_type action_time_limit;
typedef ::dji_sdk::MissionWaypointAction_<ContainerAllocator> _waypoint_action_type;
_waypoint_action_type waypoint_action;
typedef boost::shared_ptr< ::dji_sdk::MissionWaypoint_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::dji_sdk::MissionWaypoint_<ContainerAllocator> const> ConstPtr;
}; // struct MissionWaypoint_
typedef ::dji_sdk::MissionWaypoint_<std::allocator<void> > MissionWaypoint;
typedef boost::shared_ptr< ::dji_sdk::MissionWaypoint > MissionWaypointPtr;
typedef boost::shared_ptr< ::dji_sdk::MissionWaypoint const> MissionWaypointConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::dji_sdk::MissionWaypoint_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::dji_sdk::MissionWaypoint_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace dji_sdk
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'nav_msgs': ['/opt/ros/indigo/share/nav_msgs/cmake/../msg'], 'dji_sdk': ['/root/Documents/roswork/DJIChallenge2016_new/src/dji_sdk/msg', '/root/Documents/roswork/DJIChallenge2016_new/src/build/devel/share/dji_sdk/msg'], 'actionlib_msgs': ['/opt/ros/indigo/share/actionlib_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/indigo/share/geometry_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::dji_sdk::MissionWaypoint_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::dji_sdk::MissionWaypoint_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::dji_sdk::MissionWaypoint_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::dji_sdk::MissionWaypoint_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::dji_sdk::MissionWaypoint_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::dji_sdk::MissionWaypoint_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::dji_sdk::MissionWaypoint_<ContainerAllocator> >
{
static const char* value()
{
return "d321a17884980812391aa8e2850409e4";
}
static const char* value(const ::dji_sdk::MissionWaypoint_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xd321a17884980812ULL;
static const uint64_t static_value2 = 0x391aa8e2850409e4ULL;
};
template<class ContainerAllocator>
struct DataType< ::dji_sdk::MissionWaypoint_<ContainerAllocator> >
{
static const char* value()
{
return "dji_sdk/MissionWaypoint";
}
static const char* value(const ::dji_sdk::MissionWaypoint_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::dji_sdk::MissionWaypoint_<ContainerAllocator> >
{
static const char* value()
{
return "float64 latitude\n\
float64 longitude\n\
float32 altitude\n\
float32 damping_distance\n\
int16 target_yaw\n\
int16 target_gimbal_pitch\n\
uint8 turn_mode\n\
uint8 has_action\n\
uint16 action_time_limit\n\
MissionWaypointAction waypoint_action\n\
\n\
================================================================================\n\
MSG: dji_sdk/MissionWaypointAction\n\
uint8 action_repeat\n\
uint8[15] command_list\n\
int16[15] command_parameter\n\
";
}
static const char* value(const ::dji_sdk::MissionWaypoint_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::dji_sdk::MissionWaypoint_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.latitude);
stream.next(m.longitude);
stream.next(m.altitude);
stream.next(m.damping_distance);
stream.next(m.target_yaw);
stream.next(m.target_gimbal_pitch);
stream.next(m.turn_mode);
stream.next(m.has_action);
stream.next(m.action_time_limit);
stream.next(m.waypoint_action);
}
ROS_DECLARE_ALLINONE_SERIALIZER;
}; // struct MissionWaypoint_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::dji_sdk::MissionWaypoint_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::dji_sdk::MissionWaypoint_<ContainerAllocator>& v)
{
s << indent << "latitude: ";
Printer<double>::stream(s, indent + " ", v.latitude);
s << indent << "longitude: ";
Printer<double>::stream(s, indent + " ", v.longitude);
s << indent << "altitude: ";
Printer<float>::stream(s, indent + " ", v.altitude);
s << indent << "damping_distance: ";
Printer<float>::stream(s, indent + " ", v.damping_distance);
s << indent << "target_yaw: ";
Printer<int16_t>::stream(s, indent + " ", v.target_yaw);
s << indent << "target_gimbal_pitch: ";
Printer<int16_t>::stream(s, indent + " ", v.target_gimbal_pitch);
s << indent << "turn_mode: ";
Printer<uint8_t>::stream(s, indent + " ", v.turn_mode);
s << indent << "has_action: ";
Printer<uint8_t>::stream(s, indent + " ", v.has_action);
s << indent << "action_time_limit: ";
Printer<uint16_t>::stream(s, indent + " ", v.action_time_limit);
s << indent << "waypoint_action: ";
s << std::endl;
Printer< ::dji_sdk::MissionWaypointAction_<ContainerAllocator> >::stream(s, indent + " ", v.waypoint_action);
}
};
} // namespace message_operations
} // namespace ros
#endif // DJI_SDK_MESSAGE_MISSIONWAYPOINT_H
| [
"[email protected]"
] | |
37d891cbd3ea85389182de91c4447500a290496b | 083100943aa21e05d2eb0ad745349331dd35239a | /aws-cpp-sdk-s3/include/aws/s3/model/PutBucketWebsiteRequest.h | 68a1fcbc44f851e93c4f1ecec69c5338a2344077 | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | bmildner/aws-sdk-cpp | d853faf39ab001b2878de57aa7ba132579d1dcd2 | 983be395fdff4ec944b3bcfcd6ead6b4510b2991 | refs/heads/master | 2021-01-15T16:52:31.496867 | 2015-09-10T06:57:18 | 2015-09-10T06:57:18 | 41,954,994 | 1 | 0 | null | 2015-09-05T08:57:22 | 2015-09-05T08:57:22 | null | UTF-8 | C++ | false | false | 3,555 | h | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/s3/S3_EXPORTS.h>
#include <aws/s3/S3Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/s3/model/WebsiteConfiguration.h>
namespace Aws
{
namespace S3
{
namespace Model
{
/*
*/
class AWS_S3_API PutBucketWebsiteRequest : public S3Request
{
public:
PutBucketWebsiteRequest();
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
inline const Aws::String& GetBucket() const{ return m_bucket; }
inline void SetBucket(const Aws::String& value) { m_bucketHasBeenSet = true; m_bucket = value; }
inline void SetBucket(Aws::String&& value) { m_bucketHasBeenSet = true; m_bucket = value; }
inline void SetBucket(const char* value) { m_bucketHasBeenSet = true; m_bucket.assign(value); }
inline PutBucketWebsiteRequest& WithBucket(const Aws::String& value) { SetBucket(value); return *this;}
inline PutBucketWebsiteRequest& WithBucket(Aws::String&& value) { SetBucket(value); return *this;}
inline PutBucketWebsiteRequest& WithBucket(const char* value) { SetBucket(value); return *this;}
inline const Aws::String& GetContentMD5() const{ return m_contentMD5; }
inline void SetContentMD5(const Aws::String& value) { m_contentMD5HasBeenSet = true; m_contentMD5 = value; }
inline void SetContentMD5(Aws::String&& value) { m_contentMD5HasBeenSet = true; m_contentMD5 = value; }
inline void SetContentMD5(const char* value) { m_contentMD5HasBeenSet = true; m_contentMD5.assign(value); }
inline PutBucketWebsiteRequest& WithContentMD5(const Aws::String& value) { SetContentMD5(value); return *this;}
inline PutBucketWebsiteRequest& WithContentMD5(Aws::String&& value) { SetContentMD5(value); return *this;}
inline PutBucketWebsiteRequest& WithContentMD5(const char* value) { SetContentMD5(value); return *this;}
inline const WebsiteConfiguration& GetWebsiteConfiguration() const{ return m_websiteConfiguration; }
inline void SetWebsiteConfiguration(const WebsiteConfiguration& value) { m_websiteConfigurationHasBeenSet = true; m_websiteConfiguration = value; }
inline void SetWebsiteConfiguration(WebsiteConfiguration&& value) { m_websiteConfigurationHasBeenSet = true; m_websiteConfiguration = value; }
inline PutBucketWebsiteRequest& WithWebsiteConfiguration(const WebsiteConfiguration& value) { SetWebsiteConfiguration(value); return *this;}
inline PutBucketWebsiteRequest& WithWebsiteConfiguration(WebsiteConfiguration&& value) { SetWebsiteConfiguration(value); return *this;}
private:
Aws::String m_bucket;
bool m_bucketHasBeenSet;
Aws::String m_contentMD5;
bool m_contentMD5HasBeenSet;
WebsiteConfiguration m_websiteConfiguration;
bool m_websiteConfigurationHasBeenSet;
};
} // namespace Model
} // namespace S3
} // namespace Aws
| [
"[email protected]"
] | |
b224da2be90b982f6b7d50f42c970d68c9524993 | 65bebe7c57d5631391b34f37864c64ae313bf10e | /recipes/shm/shmRead.cpp | 050fe443cabc616d4971c725e650d3ba9e15b4c1 | [] | no_license | VeblenXSYK/Learnmuduo | b2c6b151bb85656d63056589fe0a87f71d8cc576 | b7936c5b24a15b36be7c81a1df28be6fb18d2ff7 | refs/heads/master | 2022-05-06T16:46:22.355399 | 2022-04-16T13:32:44 | 2022-04-16T13:32:44 | 134,127,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,582 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "common.h"
#define BUFSZ 512
#define PATHNAME "."
int main(int argc, char *argv[])
{
// 显示路径信息
struct stat buf;
int ret = stat(PATHNAME, &buf);
if(ret) {
perror("stat\n");
exit(-1);
} else {
printf("pathname info: st_dev=%x, st_ino=%x\n", (int)buf.st_dev, (int)buf.st_ino);
}
// 创建key值
key_t key = ftok(PATHNAME, 0x38);
if(key == -1) {
perror("ftok\n");
exit(-1);
} else {
printf("key = %x\n", key);
}
// 打开共享内存
int shmid = shmget(key, sizeof(struct sm_msg), IPC_CREAT|0666);
if(shmid < 0) {
perror("shmget\n");
exit(-1);
}
// 映射共享内存到本进程的虚拟地址
char *shmadd = (char *)shmat(shmid, NULL, 0);
if(shmadd < 0) {
perror("shmat\n");
exit(-1);
}
// // 读共享内存区数据
// printf("data = [%s]\n", shmadd);
struct sm_msg *msg = (struct sm_msg *)shmadd;
char buffer[1024];
while(1) {
bzero(buffer, sizeof(buffer));
pthread_mutex_lock(&msg->sm_mutex);
memcpy(buffer, msg->buf, 100);
pthread_mutex_unlock(&msg->sm_mutex);
printf("read from shared-memory: %s\n", buffer);
}
// 分离共享内存和当前进程
ret = shmdt(shmadd);
if(ret < 0) {
perror("shmdt\n");
exit(-1);
}
// 删除共享内存
ret = shmctl(shmid, IPC_RMID, NULL);
if(ret < 0) {
perror("shmctl\n");
exit(-1);
} else {
printf("del shared-memory\n");
}
return 0;
}
| [
"[email protected]"
] | |
f17a028746e040ac78911fccc7d68e31e751db54 | beb45ea16265fca51f1005c89cea8c0394d43a7e | /lfq_gen/stdafx.cpp | a68c0e278fd04b8772670e18d1d1c41a9d59a833 | [] | no_license | doomsday/lfq_gen | cef916d3e602701da3d431916f1a11330d0f93fc | 8dd4f4727a1c5d507839ccd29f5155f0c2f5c151 | refs/heads/master | 2021-01-11T22:09:25.626064 | 2017-01-21T14:25:50 | 2017-01-21T14:25:50 | 78,925,003 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 286 | cpp | // stdafx.cpp : source file that includes just the standard includes
// lfq_gen.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]"
] | |
b3ee9c296fe649412f30aa4ea8fa199c56f43fde | 088c7a57cf1eb94b84f8f32e65bc12b71bb9ff68 | /1966/main.cpp | 092327e73f71878fb98e50b42e00d2d775e9c4a0 | [] | no_license | bleetoteelb/lg_sw_test | 1b6994c40ac27db71c83a517b3580570d3e1bc7b | 2c242da94ba5698a7ca12c64b2866ad8683e16a3 | refs/heads/master | 2020-05-02T03:28:32.334624 | 2019-04-26T11:37:48 | 2019-04-26T11:37:48 | 177,729,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,269 | cpp | //<done>
#include <iostream>
#include <queue>
using namespace std;
struct qu{
int pri;
bool wanted;
qu(int a, bool b) : pri(a), wanted(b){};
};
int main(){
int cases,N,M;
int tmp;
cin >> cases;
for(int i=0;i<cases;i++){
cin >> M >> N;
queue<qu> q;
int priority[10]={0,}, largest=0, order=1;
for(int ii=0;ii<M;ii++){
cin >> tmp;
priority[tmp]++;
if(largest<tmp) largest=tmp;
if(ii==N) q.push(qu(tmp,true));
else q.push(qu(tmp,false));
}
while(!q.empty()){
if(q.front().pri<largest) {
q.push(q.front());
q.pop();
} else {
priority[q.front().pri]--;
if(priority[q.front().pri]==0){
for(int i=largest;i>0;i--){
if(priority[i]!=0) {
largest=i;
break;
}
}
}
if(q.front().wanted) {
printf("%d\n",order);
break;
}
q.pop();
order++;
}
}
}
} | [
"[email protected]"
] | |
e5e2993aeb201a60553a71c27b39ddec1f3e3739 | 85d1ada18887d23fd27df9a4fde028a18d8529c1 | /AnimalsEditor/movedatabase.cpp | 3f841e12cf7de00015e65182d72a115735c7eb3c | [] | no_license | gartenriese2/animals | 814c5ae6ecd628bae6c8907ca3431732bfdf4962 | ef2ace328722ab6b4f9c9eb7adc3ea26f8633002 | refs/heads/master | 2021-01-21T06:11:08.006674 | 2015-06-28T23:12:02 | 2015-06-28T23:12:02 | 15,306,685 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,927 | cpp | #include "movedatabase.h"
#include <QFile>
#include <QIODevice>
#include <QtDebug>
#include <QXmlStreamReader>
#include <cassert>
namespace db {
const QString k_path("../AnimalsEditor/data/moves.xml");
const QString k_name("move");
MoveDatabase::MoveDatabase() {
parse();
}
MoveDatabase::~MoveDatabase() {
}
const std::map<unsigned int, Move> MoveDatabase::getByID() const {
std::map<unsigned int, Move> map;
for (const auto & p : m_data) {
map.emplace(p.second.getID(), p.second);
}
return map;
}
bool MoveDatabase::deleteData(const QString & name) {
if (m_data.count(name) == 0) {
return false;
}
const auto ID = m_data.at(name).getID();
for (auto & a : m_data) {
if (a.second.getID() > ID) {
a.second.setID(a.second.getID() - 1);
}
}
m_data.erase(name);
return true;
}
bool MoveDatabase::insertData(unsigned int ID, const Move & data) {
const auto map = getByID();
if (ID != 1 && map.count(ID - 1) == 0) {
return false;
}
for (auto & a : m_data) {
if (a.second.getID() >= ID) {
a.second.setID(a.second.getID() + 1);
}
}
m_data.emplace(data.getName(), data);
return true;
}
bool MoveDatabase::save() {
auto dataByID = getByID();
QFile file(k_path);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
qCritical() << "Could not open " << k_path;
return false;
}
QXmlStreamWriter writer(&file);
writer.setAutoFormatting(true);
writer.writeStartDocument();
writer.writeStartElement("moves");
for (const auto & p : dataByID) {
const auto data = p.second;
writer.writeStartElement(k_name);
writer.writeAttribute("id", QString::number(p.first));
writer.writeStartElement("name");
writer.writeCharacters(data.getName());
writer.writeEndElement();
writer.writeStartElement("basedamage");
writer.writeCharacters(QString::number(data.getBaseDamage()));
writer.writeEndElement();
writer.writeStartElement("type");
writer.writeCharacters(data.getType());
writer.writeEndElement();
writer.writeStartElement("category");
writer.writeCharacters(data.getCategory());
writer.writeEndElement();
writer.writeStartElement("accuracy");
writer.writeCharacters(QString::number(data.getAccuracy()));
writer.writeEndElement();
writer.writeStartElement("priority");
writer.writeCharacters(QString::number(data.getPriority()));
writer.writeEndElement();
writer.writeEndElement();
}
writer.writeEndElement();
writer.writeEndDocument();
return true;
}
bool MoveDatabase::parse() {
QFile file(k_path);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qCritical() << "Could not open" << k_path;
return false;
}
QXmlStreamReader reader(&file);
while (!reader.atEnd() && !reader.hasError()) {
reader.readNext();
if (reader.isStartElement() && reader.name() == k_name) {
const auto ID = reader.attributes().value("id").toUInt();
auto data = getData(reader);
data.setID(ID);
m_data.emplace(data.getName(), data);
}
}
return true;
}
const Move MoveDatabase::getData(QXmlStreamReader & reader) {
assert(reader.name() == k_name);
Move move;
auto attr = reader.attributes();
if (!attr.hasAttribute("id")) {
qWarning() << "Move has no ID!";
return move;
}
while(!(reader.isEndElement() && reader.name() == k_name)) {
reader.readNext();
if (reader.isEndElement()) {
continue;
}
const auto name = reader.name();
// name
if (name == "name") {
reader.readNext();
if(!reader.isCharacters()) {
qWarning() << "Name does not contain characters!";
return move;
} else {
move.setName(reader.text().toString());
}
} else
// basedamage
if (name == "basedamage") {
reader.readNext();
if(!reader.isCharacters()) {
qWarning() << "Base Damage does not contain characters!";
return move;
} else {
move.setBaseDamage(reader.text().toUInt());
}
} else
// type
if (name == "type") {
reader.readNext();
if(!reader.isCharacters()) {
qWarning() << "Type does not contain characters!";
return move;
} else {
move.setType(reader.text().toString());
}
} else
// category
if (name == "category") {
reader.readNext();
if(!reader.isCharacters()) {
qWarning() << "Category does not contain characters!";
return move;
} else {
move.setCategory(reader.text().toString());
}
} else
// accuracy
if (name == "accuracy") {
reader.readNext();
if(!reader.isCharacters()) {
qWarning() << "Accuracy does not contain characters!";
return move;
} else {
move.setAccuracy(reader.text().toUInt());
}
} else
// priority
if (name == "priority") {
reader.readNext();
if(!reader.isCharacters()) {
qWarning() << "Priority does not contain characters!";
return move;
} else {
move.setPriority(reader.text().toInt());
}
}
}
return move;
}
} // namespace db
| [
"[email protected]"
] | |
14b0906ca93b43abc58223357854dcc1bf552e69 | 73266ea6be2de149a4700798b221bd4c79525604 | /webserv/source/http/body/encoding/identity/IdentityEncoder.hpp | 8acc8da068e173c7ca70f25768d05b3c58365661 | [] | no_license | Caceresenzo/42 | de90b0262b573d4056102ad04ed0f6fbef169858 | df1e14c019994202da0abbe221455f1a6ee291e4 | refs/heads/master | 2023-08-15T06:14:08.625075 | 2023-08-13T17:19:00 | 2023-08-13T17:19:00 | 220,007,175 | 92 | 36 | null | null | null | null | UTF-8 | C++ | false | false | 1,416 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* IdentityEncoder.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ecaceres <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/09 01:24:18 by ecaceres #+# #+# */
/* Updated: 2021/01/09 01:24:18 by ecaceres ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef IDENTITYENCODER_HPP_
# define IDENTITYENCODER_HPP_
#include <http/body/encoding/IHTTPBodyEncoder.hpp>
#include <util/Singleton.hpp>
#include <string>
class IdentityEncoder :
public IHTTPBodyEncoder,
public Singleton<IdentityEncoder>
{
private:
IdentityEncoder(const IdentityEncoder &other);
IdentityEncoder&
operator=(const IdentityEncoder &other);
public:
IdentityEncoder();
virtual
~IdentityEncoder();
std::string
encode(const std::string &input);
};
#endif /* IDENTITYENCODER_HPP_ */
| [
"[email protected]"
] | |
9d239a0a1f3d610af186caf4eb171761545af213 | f21bc45901cdcac86070f12aa07f60b56f4dfeea | /144. BinaryTreePreorderTraversal/BinaryTreePreorderTraversal.cpp | 4ae09826735275fa33c4fe7d33122d518841cd75 | [] | no_license | chengtianle1997/Leetcode_Learning | f5758aeeb2f87e7abc68b6c5dbb14abecbbbcec7 | 8efd2f4a83eb72680ec53d0cbdc4585888c52dc9 | refs/heads/main | 2023-06-01T17:59:16.208025 | 2021-06-21T01:13:51 | 2021-06-21T01:13:51 | 360,046,691 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,984 | cpp | #include <iostream>
#include <vector>
#include <queue>
#include <stack>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// Recursion Approach
class Solution_Recursion {
public:
void traversal(TreeNode* node, std::vector<int>& result)
{
if (node == nullptr)
return;
result.emplace_back(node->val); // emplace_back is much faster than push_back here.
traversal(node->left, result);
traversal(node->right, result);
}
std::vector<int> preorderTraversal(TreeNode* root) {
std::vector<int> result;
if (root == nullptr)
return result;
traversal(root, result);
return result;
}
};
// Non-Recursion Approach: using stack
class Solution {
public:
std::vector<int> preorderTraversal(TreeNode* root) {
std::vector<int> result;
if (root == nullptr)
return result;
std::stack<TreeNode*> stack;
TreeNode* node = root;
stack.push(node);
while (!stack.empty())
{
node = stack.top();
result.emplace_back(node->val);
stack.pop();
// stack is a first in last out (FILO) structure, so push the right node first,
// and we will pop the left node first.
if (node->right)
stack.push(node->right);
if (node->left)
stack.push(node->left);
}
return result;
}
};
TreeNode* CreateTree(std::vector<int> nodes)
{
TreeNode* root = nullptr;
if (nodes.size() == 0 || nodes[0] == NULL)
return root;
int n = nodes.size();
root = new TreeNode(nodes[0]);
std::queue<std::pair<TreeNode*, int>> queue;
queue.push({ root, 0 });
while (!queue.empty())
{
auto node_info = queue.front();
TreeNode* node = node_info.first;
int node_id = node_info.second;
queue.pop();
// left child exists
if (node_id * 2 + 1 < n && nodes[node_id * 2 + 1] != NULL)
{
TreeNode* left = new TreeNode(nodes[node_id * 2 + 1]);
node->left = left;
queue.push({ left, node_id * 2 + 1 });
}
// right child exists
if (node_id * 2 + 2 < n && nodes[node_id * 2 + 2] != NULL)
{
TreeNode* right = new TreeNode(nodes[node_id * 2 + 2]);
node->right = right;
queue.push({ right, node_id * 2 + 2 });
}
}
return root;
}
void PrintResult(std::vector<int> result)
{
for (int i = 0; i < result.size(); i++)
std::cout << result[i] << " ";
std::cout << std::endl;
}
int main()
{
Solution solution;
TreeNode* root = nullptr;
PrintResult(solution.preorderTraversal(root));
std::vector<int> nodes = { 1, NULL, 2, NULL, NULL, 3 };
root = CreateTree(nodes);
PrintResult(solution.preorderTraversal(root));
} | [
"[email protected]"
] | |
b16a858f3f95bb38de80c9bed385f8bf8811f9f0 | 127c53f4e7e220f44dc82d910a5eed9ae8974997 | /ClientLib/Tools/MrSmith/MrSmith/PacketHandle/CGAskJoinMenpaiHandler.cpp | 3b2bf2a678ef40e95b6b9a8a7e4395ec766efb4d | [] | no_license | zhangf911/wxsj2 | 253e16265224b85cc6800176a435deaa219ffc48 | c8e5f538c7beeaa945ed2a9b5a9b04edeb12c3bd | refs/heads/master | 2020-06-11T16:44:14.179685 | 2013-03-03T08:47:18 | 2013-03-03T08:47:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 188 | cpp | #include "StdAfx.h"
#include "CGAskJoinMenpai.h"
using namespace Packets;
UINT CGAskJoinMenpaiHandler::Execute(CGAskJoinMenpai* pPacket, Player*)
{
return PACKET_EXE_CONTINUE;
}
| [
"[email protected]"
] | |
f1e2badf54b860559998661018a059d251c7c49d | 27e1a0831fa730f710c7f48125092b8bfa98c8c6 | /tests/datasets/system_tests/squeezenet/SqueezeNetConvolutionLayerDataset.h | f98d90a9d68057d991e30c1473fbce00e401d836 | [
"MIT"
] | permissive | adityagupta1089/ComputeLibrary | ff9c57f4f69b02d3789f72b5223bc9c1f28ad777 | 39945fde9bbb805e76c55baf3ca536a376fb00f4 | refs/heads/master | 2021-06-22T06:54:52.030052 | 2021-01-03T14:04:39 | 2021-01-03T14:04:39 | 158,011,217 | 2 | 1 | MIT | 2018-11-17T18:07:24 | 2018-11-17T18:07:24 | null | UTF-8 | C++ | false | false | 6,106 | h | /*
* Copyright (c) 2017 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef ARM_COMPUTE_TEST_SQUEEZENET_CONVOLUTION_LAYER_DATASET
#define ARM_COMPUTE_TEST_SQUEEZENET_CONVOLUTION_LAYER_DATASET
#include "tests/datasets/ConvolutionLayerDataset.h"
#include "utils/TypePrinter.h"
#include "arm_compute/core/TensorShape.h"
#include "arm_compute/core/Types.h"
namespace arm_compute
{
namespace test
{
namespace datasets
{
class SqueezeNetWinogradLayerDataset final : public ConvolutionLayerDataset
{
public:
SqueezeNetWinogradLayerDataset()
{
// fire2/expand3x3, fire3/expand3x3
add_config(TensorShape(55U, 55U, 16U), TensorShape(3U, 3U, 16U, 64U), TensorShape(64U), TensorShape(55U, 55U, 64U), PadStrideInfo(1, 1, 1, 1));
// fire4/expand3x3, fire5/expand3x3
add_config(TensorShape(27U, 27U, 32U), TensorShape(3U, 3U, 32U, 128U), TensorShape(128U), TensorShape(27U, 27U, 128U), PadStrideInfo(1, 1, 1, 1));
// fire6/expand3x3, fire7/expand3x3
add_config(TensorShape(13U, 13U, 48U), TensorShape(3U, 3U, 48U, 192U), TensorShape(192U), TensorShape(13U, 13U, 192U), PadStrideInfo(1, 1, 1, 1));
// fire8/expand3x3, fire9/expand3x3
add_config(TensorShape(13U, 13U, 64U), TensorShape(3U, 3U, 64U, 256U), TensorShape(256U), TensorShape(13U, 13U, 256U), PadStrideInfo(1, 1, 1, 1));
}
};
class SqueezeNetConvolutionLayerDataset final : public ConvolutionLayerDataset
{
public:
SqueezeNetConvolutionLayerDataset()
{
// conv1
add_config(TensorShape(224U, 224U, 3U), TensorShape(3U, 3U, 3U, 64U), TensorShape(64U), TensorShape(111U, 111U, 64U), PadStrideInfo(2, 2, 0, 0));
// fire2/squeeze1x1
add_config(TensorShape(55U, 55U, 64U), TensorShape(1U, 1U, 64U, 16U), TensorShape(16U), TensorShape(55U, 55U, 16U), PadStrideInfo(1, 1, 0, 0));
// fire2/expand1x1, fire3/expand1x1
add_config(TensorShape(55U, 55U, 16U), TensorShape(1U, 1U, 16U, 64U), TensorShape(64U), TensorShape(55U, 55U, 64U), PadStrideInfo(1, 1, 0, 0));
// fire2/expand3x3, fire3/expand3x3
add_config(TensorShape(55U, 55U, 16U), TensorShape(3U, 3U, 16U, 64U), TensorShape(64U), TensorShape(55U, 55U, 64U), PadStrideInfo(1, 1, 1, 1));
// fire3/squeeze1x1
add_config(TensorShape(55U, 55U, 128U), TensorShape(1U, 1U, 128U, 16U), TensorShape(16U), TensorShape(55U, 55U, 16U), PadStrideInfo(1, 1, 0, 0));
// fire4/squeeze1x1
add_config(TensorShape(27U, 27U, 128U), TensorShape(1U, 1U, 128U, 32U), TensorShape(32U), TensorShape(27U, 27U, 32U), PadStrideInfo(1, 1, 0, 0));
// fire4/expand1x1, fire5/expand1x1
add_config(TensorShape(27U, 27U, 32U), TensorShape(1U, 1U, 32U, 128U), TensorShape(128U), TensorShape(27U, 27U, 128U), PadStrideInfo(1, 1, 0, 0));
// fire4/expand3x3, fire5/expand3x3
add_config(TensorShape(27U, 27U, 32U), TensorShape(3U, 3U, 32U, 128U), TensorShape(128U), TensorShape(27U, 27U, 128U), PadStrideInfo(1, 1, 1, 1));
// fire5/squeeze1x1
add_config(TensorShape(27U, 27U, 256U), TensorShape(1U, 1U, 256U, 32U), TensorShape(32U), TensorShape(27U, 27U, 32U), PadStrideInfo(1, 1, 0, 0));
// fire6/squeeze1x1
add_config(TensorShape(13U, 13U, 256U), TensorShape(1U, 1U, 256U, 48U), TensorShape(48U), TensorShape(13U, 13U, 48U), PadStrideInfo(1, 1, 0, 0));
// fire6/expand1x1, fire7/expand1x1
add_config(TensorShape(13U, 13U, 48U), TensorShape(1U, 1U, 48U, 192U), TensorShape(192U), TensorShape(13U, 13U, 192U), PadStrideInfo(1, 1, 0, 0));
// fire6/expand3x3, fire7/expand3x3
add_config(TensorShape(13U, 13U, 48U), TensorShape(3U, 3U, 48U, 192U), TensorShape(192U), TensorShape(13U, 13U, 192U), PadStrideInfo(1, 1, 1, 1));
// fire7/squeeze1x1
add_config(TensorShape(13U, 13U, 384U), TensorShape(1U, 1U, 384U, 48U), TensorShape(48U), TensorShape(13U, 13U, 48U), PadStrideInfo(1, 1, 0, 0));
// fire8/squeeze1x1
add_config(TensorShape(13U, 13U, 384U), TensorShape(1U, 1U, 384U, 64U), TensorShape(64U), TensorShape(13U, 13U, 64U), PadStrideInfo(1, 1, 0, 0));
// fire8/expand1x1, fire9/expand1x1
add_config(TensorShape(13U, 13U, 64U), TensorShape(1U, 1U, 64U, 256U), TensorShape(256U), TensorShape(13U, 13U, 256U), PadStrideInfo(1, 1, 0, 0));
// fire8/expand3x3, fire9/expand3x3
add_config(TensorShape(13U, 13U, 64U), TensorShape(3U, 3U, 64U, 256U), TensorShape(256U), TensorShape(13U, 13U, 256U), PadStrideInfo(1, 1, 1, 1));
// fire9/squeeze1x1
add_config(TensorShape(13U, 13U, 512U), TensorShape(1U, 1U, 512U, 64U), TensorShape(64U), TensorShape(13U, 13U, 64U), PadStrideInfo(1, 1, 0, 0));
// conv10
add_config(TensorShape(13U, 13U, 512U), TensorShape(1U, 1U, 512U, 1000U), TensorShape(1000U), TensorShape(13U, 13U, 1000U), PadStrideInfo(1, 1, 0, 0));
}
};
} // namespace datasets
} // namespace test
} // namespace arm_compute
#endif /* ARM_COMPUTE_TEST_SQUEEZENET_CONVOLUTION_LAYER_DATASET */
| [
"[email protected]"
] | |
dddebb873a2550d6da6e5676359cd4a7a173491e | 4b9349defe810f6fc1750e977afe2b3f1bcede68 | /sources/context/src/AppState.cpp | 77724dc67ecceb2c06d472a665bf4684ae645f99 | [
"MIT"
] | permissive | dwlcj/context-project | 05754e24307e24ef344c40cf438dab510ff26044 | 91858fc894fd077c031b2840db24eea9ce7233e3 | refs/heads/master | 2022-09-16T22:56:35.854057 | 2020-06-02T14:19:36 | 2020-06-02T14:19:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,039 | cpp | /*
MIT License
Copyright (c) 2020 Andrey Vasiliev
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 "pcheader.hpp"
#include "AppState.hpp"
#include "ContextManager.hpp"
namespace Context {
//----------------------------------------------------------------------------------------------------------------------
AppState::AppState() {
}
//----------------------------------------------------------------------------------------------------------------------
AppState::~AppState() {
if (registered_) {
ContextManager::GetSingleton().GetOgreRootPtr()->removeFrameListener(this);
}
}
//----------------------------------------------------------------------------------------------------------------------
void AppState::SetupGlobals() {
SetOgreScene(ContextManager::GetSingleton().GetOgreScenePtr());
SetCameraMan(ContextManager::GetSingleton().GetCameraMan());
SetOgreCamera(ContextManager::GetSingleton().GetOgreCamera());
SetOgreViewport(ContextManager::GetSingleton().GetOgreViewport());
SetOgreRoot(ContextManager::GetSingleton().GetOgreRootPtr());
InputManager::GetSingleton().RegisterListener(this);
ContextManager::GetSingleton().GetOgreRootPtr()->addFrameListener(this);
registered_ = true;
}
//----------------------------------------------------------------------------------------------------------------------
void AppState::ResetGlobals() {
if (registered_) {
ContextManager::GetSingleton().GetOgreRootPtr()->removeFrameListener(this);
InputManager::GetSingleton().UnregisterListener(this);
}
}
void AppState::SetOgreRoot(Ogre::Root *ogre_root) {
AppState::ogre_root = ogre_root;
}
void AppState::SetOgreScene(Ogre::SceneManager *ogre_scene) {
ogre_scene_manager_ = ogre_scene;
}
void AppState::SetCameraMan(const std::shared_ptr<CameraMan> &camera_man) {
camera_man_ = camera_man;
}
void AppState::SetOgreCamera(Ogre::Camera *ogre_camera) {
ogre_camera_ = ogre_camera;
}
void AppState::SetOgreViewport(Ogre::Viewport *ogre_viewport) {
ogre_viewport_ = ogre_viewport;
}
} //namespace Context
| [
"[email protected]"
] | |
216e5356989403ab39bf81655b14bcf951ec7e71 | 896e13dea7e750cfb828d5e85978ff682571d73d | /day/d07/ex01/srcs/iter.cpp | e5b7f659bafa785b7ba0ba08080b0fdf80660feb | [] | no_license | thrichert/piscine_cpp | b26f0a4e2cea34db3b9d37b1985adfa1aec00233 | 0d5214abf70a0c1ffbec22ae7c73bb5a11a33d04 | refs/heads/master | 2020-03-30T12:27:00.590089 | 2018-01-19T01:45:46 | 2018-01-19T01:45:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,366 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* iter.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mikim <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/17 17:44:41 by mikim #+# #+# */
/* Updated: 2018/01/17 17:52:52 by mikim ### ########.fr */
/* */
/* ************************************************************************** */
#include <iostream>
void ft_f(int &elem)
{
elem *= 2;
}
template<typename T>
void iter(T *arr, int len, void (*f)(T &))
{
for (int i = 0; i < len; i++)
f(arr[i]);
}
int main()
{
int arr[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::cout << "before: ";
for (int i = 0; i < 9; i++)
std::cout << arr[i] << " ";
std::cout << std::endl;
iter(arr, 9, ft_f);
std::cout << "after : ";
for (int i = 0; i < 9; i++)
std::cout << arr[i] << " ";
std::cout << std::endl;
}
| [
"[email protected]"
] | |
a573ef63d0554e3d9813a198bc89d98830b0bf35 | 5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e | /main/source/src/core/chemical/ElementSet.hh | ef4e54ea77047e0a4491d1ec3bb5767fa11a70d9 | [] | no_license | MedicaicloudLink/Rosetta | 3ee2d79d48b31bd8ca898036ad32fe910c9a7a28 | 01affdf77abb773ed375b83cdbbf58439edd8719 | refs/heads/master | 2020-12-07T17:52:01.350906 | 2020-01-10T08:24:09 | 2020-01-10T08:24:09 | 232,757,729 | 2 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 3,847 | hh | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: [email protected].
/// @file core/chemical/bcl/ElementSet.hh
/// @author Rocco Moretti ([email protected])
#ifndef INCLUDED_core_chemical_ElementSet_hh
#define INCLUDED_core_chemical_ElementSet_hh
// Unit headers
#include <core/chemical/ElementSet.fwd.hh>
#include <core/chemical/Element.fwd.hh>
#include <core/chemical/Elements.hh>
// Project headers
// Utility headers
#include <utility/pointer/ReferenceCount.hh>
// C++ headers
#include <map>
#include <utility/vector1.hh>
#include <core/types.hh>
#ifdef SERIALIZATION
#include <utility/serialization/serialization.hh>
// Cereal headers
#include <cereal/types/polymorphic.fwd.hpp>
#endif // SERIALIZATION
namespace core {
namespace chemical {
/// @brief A set of Bcl Elements
///
/// @details This class contains a vector of pointers each of which points to an
/// Element and the vector index is looked up by an element_name string
/// in a map.
///
class ElementSet : public utility::pointer::ReferenceCount {
public:
ElementSet( std::string const & name = "");
~ElementSet() override;
/// @brief What the ChemicalManager knows this as, if relevant
std::string const &
name() const { return name_; }
/// @brief Number of elements in the set
Size
n_elements() const
{
return elements_.size();
}
/// @brief Check if there is an element_type associated with an element_symbol string
bool
contains_element_type( std::string const & element_symbol ) const;
/// @brief Lookup the element index by the element enum
Size
element_index( core::chemical::element::Elements ele ) const;
/// @brief Lookup the element index by the element_symbol string
Size
element_index( std::string const & element_symbol ) const;
/// @brief Lookup the element index by the element enum;
ElementCOP
element( core::chemical::element::Elements ele ) const;
/// @brief Lookup the element object by the element_symbol string
ElementCOP
element( std::string const & element_symbol ) const;
/// @brief Lookup an Element by 1-based indexing
ElementCOP
operator[] ( Size const index ) const;
/// @brief Load the ElementSet from a file
void
read_file( std::string const & filename );
// data
private:
/// @brief What the ChemicalManager knows this as, if relevant
std::string name_;
/// @brief element_index_ lookup map
///
/// @details element_index_ allows lookup of the element by its symbol
std::map< std::string, core::Size > element_index_;
/// @brief a collection of Elements,
///
/// @details Element has data of atom properties, and it can be
/// looked up by element_index.
utility::vector1< ElementOP > elements_;
};
#ifdef SERIALIZATION
/// @brief Serialize an ElementSet - assumes that they're all stored in the ChemicalManager
template < class Archive >
void serialize_element_set( Archive & arc, ElementSetCOP ptr );
/// @brief Deserialize an AtomTypeSet - assumes that they're all stored in the ChemicalManager
template < class Archive >
void deserialize_element_set( Archive & arc, ElementSetCOP & ptr );
#endif // SERIALIZATION
} // chemical
} // core
#ifdef SERIALIZATION
CEREAL_FORCE_DYNAMIC_INIT( core_chemical_ElementSet )
SPECIAL_COP_SERIALIZATION_HANDLING( core::chemical::ElementSet, core::chemical::serialize_element_set, core::chemical::deserialize_element_set )
#endif // SERIALIZATION
#endif
| [
"[email protected]"
] | |
8233cf82ff71bfae9f152528381b4573be770b54 | 73fbdb5146d71ebffecae20e75c31b1d6d20f72c | /prob1.cpp | 5cadb6a6892cecc407ec4cf51536d10e5876ab8b | [] | no_license | Croissanttttt/ALGORITHM | e27ed87d21a9c162f0bcc6b6bfd0ac43db185661 | 0681af4b0648c297196769e6a094d03cae704a21 | refs/heads/master | 2021-08-08T14:48:32.651772 | 2020-09-12T08:07:50 | 2020-09-12T08:07:50 | 218,828,130 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,722 | cpp | #include<iostream>
#include<string>
#include<vector>
using namespace std;
string solution(string new_id) {
string answer = "";
vector<int> temp;
//step1
for (int i = 0; i < new_id.length(); i++) {
temp.push_back(new_id[i]);
if (temp[i] >= 65 && temp[i] <= 90) {
temp[i] = temp[i] + 32;
}
}
//step2
for (int i = 0; i < temp.size(); i++) {
if((temp[i] >= 33 && temp[i] <= 44)||(temp[i] ==47)||(temp[i] == 96)||(temp[i] >= 58 && temp[i] <= 94)||(temp[i] >= 123 && temp[i]<=126)){
for (int j = i; j < temp.size(); j++) {
temp[j] = temp[j + 1];
}
i--;
temp.pop_back();
}
}
//step3
for(int i = 0; i < temp.size(); i++){
if(temp[i] == 46 && temp[i+1] == 46){
for(int j = i; j < temp.size(); j++){
temp[j] = temp[j + 1];
}
i--;
temp.pop_back();
}
}
//step4
for(int i = 0; i < temp.size(); i++){
bool a = 0;
if(temp[0]==46){
a = 1;
for(int j = 0; j < temp.size(); j++){
temp[j] = temp[j + 1];
}
temp.pop_back();
}
if(temp[temp.size()-1]==46){
temp.pop_back();
continue;
}
if(a == 1){
i--;
a = 0;
continue;
}
break;
}
//step5
if(temp.empty() == 1){
temp.push_back(97);
}
//step6
if(temp.size()>=16){
int a = temp.size();
for(int i = 0; i < (a-15); i++){
temp.pop_back();
}
if(temp[temp.size()-1]==46){
temp.pop_back();
}
}
//step7
if(temp.size() <= 2){
int a = 3 - temp.size();
for(int i = 0; i < a; i++){
temp.push_back(temp[temp.size()-1]);
}
}
for (int i = 0; i < temp.size(); i++) {
char temp_ans = temp[i];
answer.push_back(temp_ans);
}
cout<<answer<<endl;
return answer;
}
int main() {
string new_id = "...!@BaT#*..y.abcdefghijklm";
solution(new_id);
return 0;
}
| [
"[email protected]"
] | |
3f31ab7af824a7516b2aa591be6a85c539984939 | d43ba901274bb29daa478b933930888aae15a154 | /system/TimerWin.cpp | 66b173e46bc0f3f618c2b2dfba558092c1df849a | [] | no_license | DieHertz/win-macos-template | 50235fba516683f95130fc2525cc4ec299f7056f | a07cd29dac27ef680ec34e90b0f2408361a7feff | refs/heads/master | 2020-05-18T01:41:42.351585 | 2013-09-12T16:56:19 | 2013-09-12T16:56:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 565 | cpp | #include "TimerWin.h"
#include <windows.h>
Timer::Timer()
: m_elapsed(0.0)
, m_lastTime(0.0) {
}
void Timer::reset() {
m_elapsed = 0.0;
m_lastTime = this->now();
}
void Timer::update() {
double currentTime = this->now();
m_elapsed = currentTime - m_lastTime;
m_lastTime = currentTime;
}
double Timer::now() {
LARGE_INTEGER timeVal;
LARGE_INTEGER frequency;
::QueryPerformanceCounter(&timeVal);
::QueryPerformanceFrequency(&frequency);
return static_cast<double>(timeVal.QuadPart) / frequency.QuadPart;
}
float Timer::elapsed() {
return m_elapsed;
}
| [
"[email protected]"
] | |
e15ead6512030f7a548f4bcf2d48ccb02daf19cf | 93b833ca4cc03fe047dc896f42205d52443a0812 | /src/NetDriver/NetPacket.cpp | c40587e466982f0a7aa3f571cebee86f40e9a782 | [] | no_license | yiique/TranslationSystem | 26bdf4e04b1a1cbf0c459b279ca7f9c59ab4d96f | 8dd291f8a6a9a7d038bd989166121f6ea8fcc02c | refs/heads/master | 2020-04-06T07:06:48.212800 | 2016-09-12T09:27:43 | 2016-09-12T09:27:43 | 61,557,052 | 0 | 1 | null | 2016-09-12T09:27:44 | 2016-06-20T15:09:30 | C++ | GB18030 | C++ | false | false | 4,495 | cpp | //
// Created by 刘舒曼 on 16/7/21.
//
#include "NetPacket.h"
const string NetPacket::HEAD_REQUEST_TAG("Request:");
const string NetPacket::HEAD_RESPONSE_TAG("Response:");
const string NetPacket::HEAD_MSGTYPE_TAG("Msg-Type:");
const string NetPacket::HEAD_LENGTH_TAG("Content-Length:");
const string NetPacket::HEAD_SEP_TAG("\r\n");
const string NetPacket::HEAD_REQUEST_VER("1.0");
const string NetPacket::HEAD_RESPONSE_200("200 OK");
HeadStateMachine NetPacket::HSM_Start('\r', &NetPacket::HSM_Fir_R);
HeadStateMachine NetPacket::HSM_Fir_R('\n', &NetPacket::HSM_Fir_N);
HeadStateMachine NetPacket::HSM_Fir_N('\r', &NetPacket::HSM_Sec_R);
HeadStateMachine NetPacket::HSM_Sec_R('\n', &NetPacket::HSM_End_N);
HeadStateMachine NetPacket::HSM_End_N('0' , NULL);
NetPacket::NetPacket(sock_t sock): m_sock(sock),
m_write_offset(0),
m_body_size(0),
m_body_pos(0),
m_curr_hsm(&NetPacket::HSM_Start),
m_is_good(false)
{
}
NetPacket::~NetPacket(void)
{
}
//流模式读取data,解析成为NetPacket结构
PACKET_STATE_T NetPacket::Write(const char * buf, size_t len)
{
if(!buf || len == 0)
return WRITE_ERR_INPUT;
size_t idx = 0;
char byte;
//读取报文头
while( m_curr_hsm != &NetPacket::HSM_End_N )
{
if(idx >= len) //报文为空
{
return WRITE_NORMAL;
}
if(buf[idx] == '\0'){
++idx;
continue;
}
//写入头部
byte = buf[idx];
m_data += byte;
//步进状态机
if( byte == m_curr_hsm->input_b )
m_curr_hsm = m_curr_hsm->next_state;
else
m_curr_hsm = &NetPacket::HSM_Start;
if(m_curr_hsm == &NetPacket::HSM_End_N)
{
//解析报文头
PACKET_STATE_T res = parse_head();
if( res != PARSE_HEAD_SUC )
return res;
}
//增加偏移量
++idx;
if(idx >= MAX_HEAD_SIZE)
{
//超过最大长度
return WRITE_ERR_MAXHEAD;
}
}
//开始读取报文体
if(m_body_size == 0)
{
m_is_good = true;
return WRITE_FINISH;
}
while( idx < len)
{
if(buf[idx] == '\0'){
++idx;
continue;
}
m_data += buf[idx];
++idx;
if(m_data.size()-m_body_pos == m_body_size)
{
//接收完毕
m_is_good = true;
return WRITE_FINISH;
}
}
return WRITE_NORMAL;
}
//根据NetPacket实例的内容构造报文
PACKET_STATE_T NetPacket::Write(PACKET_HEAD_T head_type,
const string &msg_type,
const string &body,
const string &head_res_code)
{
stringstream buf;
m_is_good = false;
string h_field;
if( head_type == HEAD_REQUEST )
h_field = HEAD_REQUEST_TAG + HEAD_REQUEST_VER;
else
h_field = HEAD_RESPONSE_TAG +" " + head_res_code;
//构造报文头
buf << h_field << HEAD_SEP_TAG; //EX: Request: 1.0\r\n
buf << HEAD_MSGTYPE_TAG << msg_type << HEAD_SEP_TAG; //EX: Msg-Type: xxx\r\n
buf << HEAD_LENGTH_TAG << body.size() << HEAD_SEP_TAG; //EX: Content-Length: xxx\r\n
buf << HEAD_SEP_TAG; //EX: \r\n
//构造报文体
buf << body;
//给m_data赋值
m_data = buf.str();
m_is_good = true;
return WRITE_FINISH;
}
// 解析已读取入m_data的报头,从中读出m_msg_type, m_body_size, m_body_pos
PACKET_STATE_T NetPacket::parse_head()
{
//解析"Msg-Type"
if( !str_tag_find(m_data, NetPacket::HEAD_MSGTYPE_TAG, NetPacket::HEAD_SEP_TAG, m_msg_type) )
return WRITE_ERR_MSGTYPE;
del_head_tail_blank(m_msg_type);
//解析"Content-Length",读入m_body_size
string sbodylen;
if( !str_tag_find(m_data, NetPacket::HEAD_LENGTH_TAG, NetPacket::HEAD_SEP_TAG, sbodylen) )
return WRITE_ERR_CONTENTLEN;
int bodysize;
if( !cstr_2_num(sbodylen.c_str(), bodysize) )
return WRITE_ERR_CONTENTLEN;
if( bodysize < 0)
return WRITE_ERR_CONTENTLEN;
m_body_size = (size_t) bodysize;
//body置位
m_body_pos = m_data.size();
return PARSE_HEAD_SUC;
} | [
"[email protected]"
] | |
ec6c41fd7c1aa96d1560648799992ee9105da25c | 200bb009f32579a95c12fd4833af194479e10e0e | /app/src/main/jni/BasicUsageEnvironment/include/BasicUsageEnvironment_version.hh | 82fc7ac5e2939df130302edb87c04ee510f1b1a6 | [] | no_license | luofengliuchen/Androidlive555 | 3e9cf4b73c2fac8c2b1b3c2285b93fda8e7ef0f0 | b496de1cc7664458761bd5fde119e14b27755f7e | refs/heads/master | 2021-01-12T12:17:53.483432 | 2016-10-31T08:53:24 | 2016-10-31T08:53:24 | 72,418,966 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 354 | hh | // Version information for the "BasicUsageEnvironment" library
// Copyright (c) 1996-2016 Live Networks, Inc. All rights reserved.
#ifndef _BASICUSAGEENVIRONMENT_VERSION_HH
#define _BASICUSAGEENVIRONMENT_VERSION_HH
#define BASICUSAGEENVIRONMENT_LIBRARY_VERSION_STRING "2016.10.29"
#define BASICUSAGEENVIRONMENT_LIBRARY_VERSION_INT 1477699200
#endif
| [
"[email protected]"
] | |
88de96ca7baaa273255f5aa6e92ffc8ad38ecaf4 | 5d3c1be292f6153480f3a372befea4172c683180 | /trunk/ProxyLauncher/Software Proxies/SpeechRecognition/Mac OS X/SpeechServer/SpeechEventHeap.hpp | 25e07d9e580942c5e8ad40de36401442e6eb6afe | [
"Artistic-2.0"
] | permissive | BackupTheBerlios/istuff-svn | 5f47aa73dd74ecf5c55f83765a5c50daa28fa508 | d0bb9963b899259695553ccd2b01b35be5fb83db | refs/heads/master | 2016-09-06T04:54:24.129060 | 2008-05-02T22:33:26 | 2008-05-02T22:33:26 | 40,820,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 665 | hpp | /*
* SpeechEventHeap.h
* CarbonSpeechTest
*
* Created by Daniel Spelmezan on Thu Jun 03 2004.
* Copyright (c) 2004 __MyCompanyName__. All rights reserved.
*
*/
#include <Carbon/Carbon.h>
#include <eh2.h>
#include <idk_io.h>
// by inheriting eh2_Consts, you can omit prefix eh2_Consts:: when you use constant values
class SpeechEventHeap : protected eh2_Consts {
public:
SpeechEventHeap ();
~SpeechEventHeap ();
eh2_EventHeapPtr createEventHeap ();
void putEvent (eh2_EventHeap* eh);
void printEvent (const eh2_Event* event);
void waitForEvent (eh2_EventHeap* eh);
void getAll (eh2_EventHeap* eh);
//void getEvent2 (eh2)EventHeap* eh);
};
| [
"hemig@2a53cb5c-8ff1-0310-8b75-b3ec22923d26"
] | hemig@2a53cb5c-8ff1-0310-8b75-b3ec22923d26 |
442358059a33846683f903402515bf728ae83e18 | a8a094c010349b5f7e6bbc48f9537926257b3dc7 | /throw_exception/main.cpp | 4ec911394811d577651611893c0536e554ec3dc2 | [] | no_license | raffclar/cpp_stuff | 5c88a49b26cc3f51d494c769042e0465da4f3243 | 80c4573fb05f3bc93b4af377993c92c3db28d85a | refs/heads/master | 2023-05-26T04:26:50.462505 | 2023-05-21T08:27:31 | 2023-05-21T08:27:31 | 113,697,505 | 0 | 0 | null | 2018-07-05T12:17:16 | 2017-12-09T20:01:48 | C++ | UTF-8 | C++ | false | false | 71 | cpp | #include <stdexcept>
int main () {
throw std::exception();
}
| [
"[email protected]"
] | |
b610086aba88113c8a08d1f375342033e759cd81 | bbeaadef08cccb872c9a1bb32ebac7335d196318 | /Fontes/MultiObra/TNodeDetalhe.cpp | 190e75fc1a115983c39d901333570bebbc253870 | [] | no_license | danilodesouzapereira/plataformasinap_exportaopendss | d0e529b493f280aefe91b37e893359a373557ef8 | c624e9e078dce4b9bcc8e5b03dd4d9ea71c29b3f | refs/heads/master | 2023-03-20T20:37:21.948550 | 2021-03-12T17:53:12 | 2021-03-12T17:53:12 | 347,150,304 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 1,402 | cpp | // ---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "TNode.h"
#include "TNodeDetalhe.h"
#include "..\Obra\ItemObra\VTItemObra.h"
#include "..\Obra\VTAcao.h"
#include "..\Rede\VTEqpto.h"
#include "..\..\DLL_Inc\Funcao.h"
// ---------------------------------------------------------------------------
#pragma package(smart_init)
// ---------------------------------------------------------------------------
VTNode* __fastcall NewObjNodeDetalhe(void)
{
try
{
return (new TNodeDetalhe());
}
catch (Exception &e)
{
return (NULL);
}
}
// ---------------------------------------------------------------------------
__fastcall TNodeDetalhe::TNodeDetalhe(void)
{
// cria listas
lisAcao = new TList();
habilitado = false;
expandido = false;
itemObra = NULL;
estado = eND_INVALIDO;
tipoEqpto = eqptoINDEF;
tipoAcao = acaoINDEFINIDA;
}
// ---------------------------------------------------------------------------
__fastcall TNodeDetalhe::~TNodeDetalhe(void)
{
// destrói lista sem destruir seus objetos
if (lisAcao)
{
delete lisAcao;
lisAcao = NULL;
}
}
////---------------------------------------------------------------------------
// int __fastcall TNodeDetalhe::PM_GetEstado(void)
// {
// //verifica esta habilitado
// }
// ---------------------------------------------------------------------------
// eof
| [
"[email protected]"
] | |
0037c077652b43bf968e484ef70f89692c301726 | 2bdc85da8ec860be41ad14fceecedef1a8efc269 | /TestCode/source/main.cpp | b30ac16c0213679cbfe01ee7e59155a31eaf5250 | [] | no_license | BackupTheBerlios/pythonwrapper-svn | 5c41a03b23690c62693c7b29e81b240ee24f1a7f | 42879461c7302755f3c803cd1314e8da5a202c68 | refs/heads/master | 2016-09-05T09:53:14.554795 | 2005-12-26T07:52:41 | 2005-12-26T07:52:41 | 40,751,088 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 928 | cpp | #include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
#include <iostream>
#include "PWSystem.h"
int main(int argc, char* argv[])
{
// Setup the PythonWrapper
pw::System sys(true, "TestLog.txt", pw::LogManager::High);
sys.loadSwigModule("_TestSwig.dll");
sys.initialize();
// Get the top level suite from the registry
CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
// Adds the test to the list of test to run
CppUnit::TextUi::TestRunner runner;
runner.addTest(suite);
// Change the default outputter to a compiler error format outputter
runner.setOutputter(new CppUnit::CompilerOutputter(&runner.result(), std::cerr));
// Run the tests
bool wasSucessful = runner.run();
// Clean up
sys.finalize();
return wasSucessful ? 0 : 1;
}
| [
"cculver@827b5c2f-c6f0-0310-96fe-c05a662c181e"
] | cculver@827b5c2f-c6f0-0310-96fe-c05a662c181e |
5c5038c60c9f53598b1360c6d527e1417f75869f | 9384f74c2297a1de7096afa90930c5c0e6385af8 | /1_MathSet/Set.h | 464089e1e45e6b80259692a26d1f37878a5a570a | [] | no_license | mgarod/235_Assignments | 628fc917c5c70b0a91e51d8e240aa47d6ec78947 | 92e4b0cea7a1fd24b91147dbdafa98ac221f81f9 | refs/heads/master | 2021-01-10T06:34:24.672371 | 2015-12-30T20:03:28 | 2015-12-30T20:03:28 | 48,816,626 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,689 | h | /***************************************************************
Title: Set.h
Author: Michael Garod
Date Created: 2/12/2015
Class: Spring 2015, CSCI 235-01, Tues & Fri 12:45pm-2:00pm
Professor: Ilya Korsunsky
Purpose: Assignment #1
Description: Provides declarations for class Set and other
functions to simulate ADT Set which acts like a
mathematical set
***************************************************************/
#ifndef SET_H
#define SET_H
#include <iostream>
#include <cmath>
using namespace std;
// Class Declaration
template<class ItemType>
class Set
{
public:
Set(); // empty set of max size 4
Set(int); // empty set of max size int
Set(const ItemType&, int); // Singleton set of max size int
const void printSet() const;
bool isEmpty() const;
bool contains(const ItemType&) const; // "is an element of"
const int getIndexOf(const ItemType&) const;
bool add(const ItemType&);
bool remove(const ItemType&);
const int getSizeOfSet() const;
const ItemType getElement(int) const;
void setMaxSize(const int&);
const int getMaxSize() const;
void clear();
private:
ItemType* set_of_elements;
int size_of_set;
int max_size; // Default Constructor sets 4
};
// Client Functions
template<class ItemType>
Set<ItemType> uniteSets(const Set<ItemType>&,
const Set<ItemType>&);
template<class ItemType>
const void displaySet(const Set<ItemType>&);
template<class ItemType>
void TestSetImplementation();
template<class ItemType>
void TestUniteSets();
template<class ItemType>
Set<ItemType>* returnPowerSet(const Set<ItemType>&);
#include "Set.cpp"
#endif | [
"[email protected]"
] | |
2da16cf8dcb13b8683ebb3747d44c737486c6f40 | 9ca1e87ac44925130517765079157c2bf1ff4f5e | /ANDROID_SOURCE_CODE/external/clang/include/clang/Sema/CodeCompleteConsumer.h | 69003d0b4e4c06a80c282eb19b265adaca360677 | [
"NCSA",
"Apache-2.0"
] | permissive | zhxzhxustc/AFrame | ba4ac10726200a9c3d4749f9e85bf045a3c911ca | e79bcf659660746b937fda182189cf928f84657a | refs/heads/master | 2021-01-17T08:48:09.294888 | 2016-07-13T00:55:20 | 2016-07-13T00:55:20 | 63,128,807 | 3 | 1 | null | 2020-03-09T17:18:11 | 2016-07-12T05:23:26 | null | UTF-8 | C++ | false | false | 34,474 | h | //===---- CodeCompleteConsumer.h - Code Completion Interface ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the CodeCompleteConsumer class.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
#define LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
#include "clang/AST/Type.h"
#include "clang/AST/CanonicalType.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Allocator.h"
#include "clang-c/Index.h"
#include <string>
namespace clang {
class Decl;
/// \brief Default priority values for code-completion results based
/// on their kind.
enum {
/// \brief Priority for the next initialization in a constructor initializer
/// list.
CCP_NextInitializer = 7,
/// \brief Priority for an enumeration constant inside a switch whose
/// condition is of the enumeration type.
CCP_EnumInCase = 7,
/// \brief Priority for a send-to-super completion.
CCP_SuperCompletion = 20,
/// \brief Priority for a declaration that is in the local scope.
CCP_LocalDeclaration = 34,
/// \brief Priority for a member declaration found from the current
/// method or member function.
CCP_MemberDeclaration = 35,
/// \brief Priority for a language keyword (that isn't any of the other
/// categories).
CCP_Keyword = 40,
/// \brief Priority for a code pattern.
CCP_CodePattern = 40,
/// \brief Priority for a non-type declaration.
CCP_Declaration = 50,
/// \brief Priority for a type.
CCP_Type = CCP_Declaration,
/// \brief Priority for a constant value (e.g., enumerator).
CCP_Constant = 65,
/// \brief Priority for a preprocessor macro.
CCP_Macro = 70,
/// \brief Priority for a nested-name-specifier.
CCP_NestedNameSpecifier = 75,
/// \brief Priority for a result that isn't likely to be what the user wants,
/// but is included for completeness.
CCP_Unlikely = 80,
/// \brief Priority for the Objective-C "_cmd" implicit parameter.
CCP_ObjC_cmd = CCP_Unlikely
};
/// \brief Priority value deltas that are added to code-completion results
/// based on the context of the result.
enum {
/// \brief The result is in a base class.
CCD_InBaseClass = 2,
/// \brief The result is a C++ non-static member function whose qualifiers
/// exactly match the object type on which the member function can be called.
CCD_ObjectQualifierMatch = -1,
/// \brief The selector of the given message exactly matches the selector
/// of the current method, which might imply that some kind of delegation
/// is occurring.
CCD_SelectorMatch = -3,
/// \brief Adjustment to the "bool" type in Objective-C, where the typedef
/// "BOOL" is preferred.
CCD_bool_in_ObjC = 1,
/// \brief Adjustment for KVC code pattern priorities when it doesn't look
/// like the
CCD_ProbablyNotObjCCollection = 15,
/// \brief An Objective-C method being used as a property.
CCD_MethodAsProperty = 2
};
/// \brief Priority value factors by which we will divide or multiply the
/// priority of a code-completion result.
enum {
/// \brief Divide by this factor when a code-completion result's type exactly
/// matches the type we expect.
CCF_ExactTypeMatch = 4,
/// \brief Divide by this factor when a code-completion result's type is
/// similar to the type we expect (e.g., both arithmetic types, both
/// Objective-C object pointer types).
CCF_SimilarTypeMatch = 2
};
/// \brief A simplified classification of types used when determining
/// "similar" types for code completion.
enum SimplifiedTypeClass {
STC_Arithmetic,
STC_Array,
STC_Block,
STC_Function,
STC_ObjectiveC,
STC_Other,
STC_Pointer,
STC_Record,
STC_Void
};
/// \brief Determine the simplified type class of the given canonical type.
SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T);
/// \brief Determine the type that this declaration will have if it is used
/// as a type or in an expression.
QualType getDeclUsageType(ASTContext &C, NamedDecl *ND);
/// \brief Determine the priority to be given to a macro code completion result
/// with the given name.
///
/// \param MacroName The name of the macro.
///
/// \param LangOpts Options describing the current language dialect.
///
/// \param PreferredTypeIsPointer Whether the preferred type for the context
/// of this macro is a pointer type.
unsigned getMacroUsagePriority(StringRef MacroName,
const LangOptions &LangOpts,
bool PreferredTypeIsPointer = false);
/// \brief Determine the libclang cursor kind associated with the given
/// declaration.
CXCursorKind getCursorKindForDecl(Decl *D);
class FunctionDecl;
class FunctionType;
class FunctionTemplateDecl;
class IdentifierInfo;
class NamedDecl;
class NestedNameSpecifier;
class Sema;
/// \brief The context in which code completion occurred, so that the
/// code-completion consumer can process the results accordingly.
class CodeCompletionContext {
public:
enum Kind {
/// \brief An unspecified code-completion context.
CCC_Other,
/// \brief An unspecified code-completion context where we should also add
/// macro completions.
CCC_OtherWithMacros,
/// \brief Code completion occurred within a "top-level" completion context,
/// e.g., at namespace or global scope.
CCC_TopLevel,
/// \brief Code completion occurred within an Objective-C interface,
/// protocol, or category interface.
CCC_ObjCInterface,
/// \brief Code completion occurred within an Objective-C implementation
/// or category implementation.
CCC_ObjCImplementation,
/// \brief Code completion occurred within the instance variable list of
/// an Objective-C interface, implementation, or category implementation.
CCC_ObjCIvarList,
/// \brief Code completion occurred within a class, struct, or union.
CCC_ClassStructUnion,
/// \brief Code completion occurred where a statement (or declaration) is
/// expected in a function, method, or block.
CCC_Statement,
/// \brief Code completion occurred where an expression is expected.
CCC_Expression,
/// \brief Code completion occurred where an Objective-C message receiver
/// is expected.
CCC_ObjCMessageReceiver,
/// \brief Code completion occurred on the right-hand side of a member
/// access expression using the dot operator.
///
/// The results of this completion are the members of the type being
/// accessed. The type itself is available via
/// \c CodeCompletionContext::getType().
CCC_DotMemberAccess,
/// \brief Code completion occurred on the right-hand side of a member
/// access expression using the arrow operator.
///
/// The results of this completion are the members of the type being
/// accessed. The type itself is available via
/// \c CodeCompletionContext::getType().
CCC_ArrowMemberAccess,
/// \brief Code completion occurred on the right-hand side of an Objective-C
/// property access expression.
///
/// The results of this completion are the members of the type being
/// accessed. The type itself is available via
/// \c CodeCompletionContext::getType().
CCC_ObjCPropertyAccess,
/// \brief Code completion occurred after the "enum" keyword, to indicate
/// an enumeration name.
CCC_EnumTag,
/// \brief Code completion occurred after the "union" keyword, to indicate
/// a union name.
CCC_UnionTag,
/// \brief Code completion occurred after the "struct" or "class" keyword,
/// to indicate a struct or class name.
CCC_ClassOrStructTag,
/// \brief Code completion occurred where a protocol name is expected.
CCC_ObjCProtocolName,
/// \brief Code completion occurred where a namespace or namespace alias
/// is expected.
CCC_Namespace,
/// \brief Code completion occurred where a type name is expected.
CCC_Type,
/// \brief Code completion occurred where a new name is expected.
CCC_Name,
/// \brief Code completion occurred where a new name is expected and a
/// qualified name is permissible.
CCC_PotentiallyQualifiedName,
/// \brief Code completion occurred where an macro is being defined.
CCC_MacroName,
/// \brief Code completion occurred where a macro name is expected
/// (without any arguments, in the case of a function-like macro).
CCC_MacroNameUse,
/// \brief Code completion occurred within a preprocessor expression.
CCC_PreprocessorExpression,
/// \brief Code completion occurred where a preprocessor directive is
/// expected.
CCC_PreprocessorDirective,
/// \brief Code completion occurred in a context where natural language is
/// expected, e.g., a comment or string literal.
///
/// This context usually implies that no completions should be added,
/// unless they come from an appropriate natural-language dictionary.
CCC_NaturalLanguage,
/// \brief Code completion for a selector, as in an @selector expression.
CCC_SelectorName,
/// \brief Code completion within a type-qualifier list.
CCC_TypeQualifiers,
/// \brief Code completion in a parenthesized expression, which means that
/// we may also have types here in C and Objective-C (as well as in C++).
CCC_ParenthesizedExpression,
/// \brief Code completion where an Objective-C instance message is expcted.
CCC_ObjCInstanceMessage,
/// \brief Code completion where an Objective-C class message is expected.
CCC_ObjCClassMessage,
/// \brief Code completion where the name of an Objective-C class is
/// expected.
CCC_ObjCInterfaceName,
/// \brief Code completion where an Objective-C category name is expected.
CCC_ObjCCategoryName,
/// \brief An unknown context, in which we are recovering from a parsing
/// error and don't know which completions we should give.
CCC_Recovery
};
private:
enum Kind Kind;
/// \brief The type that would prefer to see at this point (e.g., the type
/// of an initializer or function parameter).
QualType PreferredType;
/// \brief The type of the base object in a member access expression.
QualType BaseType;
/// \brief The identifiers for Objective-C selector parts.
IdentifierInfo **SelIdents;
/// \brief The number of Objective-C selector parts.
unsigned NumSelIdents;
public:
/// \brief Construct a new code-completion context of the given kind.
CodeCompletionContext(enum Kind Kind) : Kind(Kind), SelIdents(NULL),
NumSelIdents(0) { }
/// \brief Construct a new code-completion context of the given kind.
CodeCompletionContext(enum Kind Kind, QualType T,
IdentifierInfo **SelIdents = NULL,
unsigned NumSelIdents = 0) : Kind(Kind),
SelIdents(SelIdents),
NumSelIdents(NumSelIdents) {
if (Kind == CCC_DotMemberAccess || Kind == CCC_ArrowMemberAccess ||
Kind == CCC_ObjCPropertyAccess || Kind == CCC_ObjCClassMessage ||
Kind == CCC_ObjCInstanceMessage)
BaseType = T;
else
PreferredType = T;
}
/// \brief Retrieve the kind of code-completion context.
enum Kind getKind() const { return Kind; }
/// \brief Retrieve the type that this expression would prefer to have, e.g.,
/// if the expression is a variable initializer or a function argument, the
/// type of the corresponding variable or function parameter.
QualType getPreferredType() const { return PreferredType; }
/// \brief Retrieve the type of the base object in a member-access
/// expression.
QualType getBaseType() const { return BaseType; }
/// \brief Retrieve the Objective-C selector identifiers.
IdentifierInfo **getSelIdents() const { return SelIdents; }
/// \brief Retrieve the number of Objective-C selector identifiers.
unsigned getNumSelIdents() const { return NumSelIdents; }
/// \brief Determines whether we want C++ constructors as results within this
/// context.
bool wantConstructorResults() const;
};
/// \brief A "string" used to describe how code completion can
/// be performed for an entity.
///
/// A code completion string typically shows how a particular entity can be
/// used. For example, the code completion string for a function would show
/// the syntax to call it, including the parentheses, placeholders for the
/// arguments, etc.
class CodeCompletionString {
public:
/// \brief The different kinds of "chunks" that can occur within a code
/// completion string.
enum ChunkKind {
/// \brief The piece of text that the user is expected to type to
/// match the code-completion string, typically a keyword or the name of a
/// declarator or macro.
CK_TypedText,
/// \brief A piece of text that should be placed in the buffer, e.g.,
/// parentheses or a comma in a function call.
CK_Text,
/// \brief A code completion string that is entirely optional. For example,
/// an optional code completion string that describes the default arguments
/// in a function call.
CK_Optional,
/// \brief A string that acts as a placeholder for, e.g., a function
/// call argument.
CK_Placeholder,
/// \brief A piece of text that describes something about the result but
/// should not be inserted into the buffer.
CK_Informative,
/// \brief A piece of text that describes the type of an entity or, for
/// functions and methods, the return type.
CK_ResultType,
/// \brief A piece of text that describes the parameter that corresponds
/// to the code-completion location within a function call, message send,
/// macro invocation, etc.
CK_CurrentParameter,
/// \brief A left parenthesis ('(').
CK_LeftParen,
/// \brief A right parenthesis (')').
CK_RightParen,
/// \brief A left bracket ('[').
CK_LeftBracket,
/// \brief A right bracket (']').
CK_RightBracket,
/// \brief A left brace ('{').
CK_LeftBrace,
/// \brief A right brace ('}').
CK_RightBrace,
/// \brief A left angle bracket ('<').
CK_LeftAngle,
/// \brief A right angle bracket ('>').
CK_RightAngle,
/// \brief A comma separator (',').
CK_Comma,
/// \brief A colon (':').
CK_Colon,
/// \brief A semicolon (';').
CK_SemiColon,
/// \brief An '=' sign.
CK_Equal,
/// \brief Horizontal whitespace (' ').
CK_HorizontalSpace,
/// \brief Verticle whitespace ('\n' or '\r\n', depending on the
/// platform).
CK_VerticalSpace
};
/// \brief One piece of the code completion string.
struct Chunk {
/// \brief The kind of data stored in this piece of the code completion
/// string.
ChunkKind Kind;
union {
/// \brief The text string associated with a CK_Text, CK_Placeholder,
/// CK_Informative, or CK_Comma chunk.
/// The string is owned by the chunk and will be deallocated
/// (with delete[]) when the chunk is destroyed.
const char *Text;
/// \brief The code completion string associated with a CK_Optional chunk.
/// The optional code completion string is owned by the chunk, and will
/// be deallocated (with delete) when the chunk is destroyed.
CodeCompletionString *Optional;
};
Chunk() : Kind(CK_Text), Text(0) { }
Chunk(ChunkKind Kind, const char *Text = "");
/// \brief Create a new text chunk.
static Chunk CreateText(const char *Text);
/// \brief Create a new optional chunk.
static Chunk CreateOptional(CodeCompletionString *Optional);
/// \brief Create a new placeholder chunk.
static Chunk CreatePlaceholder(const char *Placeholder);
/// \brief Create a new informative chunk.
static Chunk CreateInformative(const char *Informative);
/// \brief Create a new result type chunk.
static Chunk CreateResultType(const char *ResultType);
/// \brief Create a new current-parameter chunk.
static Chunk CreateCurrentParameter(const char *CurrentParameter);
};
private:
/// \brief The number of chunks stored in this string.
unsigned NumChunks : 16;
/// \brief The number of annotations for this code-completion result.
unsigned NumAnnotations : 16;
/// \brief The priority of this code-completion string.
unsigned Priority : 30;
/// \brief The availability of this code-completion result.
unsigned Availability : 2;
CodeCompletionString(const CodeCompletionString &); // DO NOT IMPLEMENT
CodeCompletionString &operator=(const CodeCompletionString &); // DITTO
CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
unsigned Priority, CXAvailabilityKind Availability,
const char **Annotations, unsigned NumAnnotations);
~CodeCompletionString() { }
friend class CodeCompletionBuilder;
friend class CodeCompletionResult;
public:
typedef const Chunk *iterator;
iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); }
iterator end() const { return begin() + NumChunks; }
bool empty() const { return NumChunks == 0; }
unsigned size() const { return NumChunks; }
const Chunk &operator[](unsigned I) const {
assert(I < size() && "Chunk index out-of-range");
return begin()[I];
}
/// \brief Returns the text in the TypedText chunk.
const char *getTypedText() const;
/// \brief Retrieve the priority of this code completion result.
unsigned getPriority() const { return Priority; }
/// \brief Retrieve the availability of this code completion result.
unsigned getAvailability() const { return Availability; }
/// \brief Retrieve the number of annotations for this code completion result.
unsigned getAnnotationCount() const;
/// \brief Retrieve the annotation string specified by \c AnnotationNr.
const char *getAnnotation(unsigned AnnotationNr) const;
/// \brief Retrieve a string representation of the code completion string,
/// which is mainly useful for debugging.
std::string getAsString() const;
};
/// \brief An allocator used specifically for the purpose of code completion.
class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
public:
/// \brief Copy the given string into this allocator.
const char *CopyString(StringRef String);
/// \brief Copy the given string into this allocator.
const char *CopyString(Twine String);
// \brief Copy the given string into this allocator.
const char *CopyString(const char *String) {
return CopyString(StringRef(String));
}
/// \brief Copy the given string into this allocator.
const char *CopyString(const std::string &String) {
return CopyString(StringRef(String));
}
};
} // end namespace clang
namespace llvm {
template <> struct isPodLike<clang::CodeCompletionString::Chunk> {
static const bool value = true;
};
}
namespace clang {
/// \brief A builder class used to construct new code-completion strings.
class CodeCompletionBuilder {
public:
typedef CodeCompletionString::Chunk Chunk;
private:
CodeCompletionAllocator &Allocator;
unsigned Priority;
CXAvailabilityKind Availability;
/// \brief The chunks stored in this string.
SmallVector<Chunk, 4> Chunks;
SmallVector<const char *, 2> Annotations;
public:
CodeCompletionBuilder(CodeCompletionAllocator &Allocator)
: Allocator(Allocator), Priority(0), Availability(CXAvailability_Available){
}
CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
unsigned Priority, CXAvailabilityKind Availability)
: Allocator(Allocator), Priority(Priority), Availability(Availability) { }
/// \brief Retrieve the allocator into which the code completion
/// strings should be allocated.
CodeCompletionAllocator &getAllocator() const { return Allocator; }
/// \brief Take the resulting completion string.
///
/// This operation can only be performed once.
CodeCompletionString *TakeString();
/// \brief Add a new typed-text chunk.
void AddTypedTextChunk(const char *Text) {
Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
}
/// \brief Add a new text chunk.
void AddTextChunk(const char *Text) {
Chunks.push_back(Chunk::CreateText(Text));
}
/// \brief Add a new optional chunk.
void AddOptionalChunk(CodeCompletionString *Optional) {
Chunks.push_back(Chunk::CreateOptional(Optional));
}
/// \brief Add a new placeholder chunk.
void AddPlaceholderChunk(const char *Placeholder) {
Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
}
/// \brief Add a new informative chunk.
void AddInformativeChunk(const char *Text) {
Chunks.push_back(Chunk::CreateInformative(Text));
}
/// \brief Add a new result-type chunk.
void AddResultTypeChunk(const char *ResultType) {
Chunks.push_back(Chunk::CreateResultType(ResultType));
}
/// \brief Add a new current-parameter chunk.
void AddCurrentParameterChunk(const char *CurrentParameter) {
Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
}
/// \brief Add a new chunk.
void AddChunk(Chunk C) { Chunks.push_back(C); }
void AddAnnotation(const char *A) { Annotations.push_back(A); }
};
/// \brief Captures a result of code completion.
class CodeCompletionResult {
public:
/// \brief Describes the kind of result generated.
enum ResultKind {
RK_Declaration = 0, //< Refers to a declaration
RK_Keyword, //< Refers to a keyword or symbol.
RK_Macro, //< Refers to a macro
RK_Pattern //< Refers to a precomputed pattern.
};
/// \brief The kind of result stored here.
ResultKind Kind;
union {
/// \brief When Kind == RK_Declaration, the declaration we are referring
/// to.
NamedDecl *Declaration;
/// \brief When Kind == RK_Keyword, the string representing the keyword
/// or symbol's spelling.
const char *Keyword;
/// \brief When Kind == RK_Pattern, the code-completion string that
/// describes the completion text to insert.
CodeCompletionString *Pattern;
/// \brief When Kind == RK_Macro, the identifier that refers to a macro.
IdentifierInfo *Macro;
};
/// \brief The priority of this particular code-completion result.
unsigned Priority;
/// \brief The cursor kind that describes this result.
CXCursorKind CursorKind;
/// \brief The availability of this result.
CXAvailabilityKind Availability;
/// \brief Specifies which parameter (of a function, Objective-C method,
/// macro, etc.) we should start with when formatting the result.
unsigned StartParameter;
/// \brief Whether this result is hidden by another name.
bool Hidden : 1;
/// \brief Whether this result was found via lookup into a base class.
bool QualifierIsInformative : 1;
/// \brief Whether this declaration is the beginning of a
/// nested-name-specifier and, therefore, should be followed by '::'.
bool StartsNestedNameSpecifier : 1;
/// \brief Whether all parameters (of a function, Objective-C
/// method, etc.) should be considered "informative".
bool AllParametersAreInformative : 1;
/// \brief Whether we're completing a declaration of the given entity,
/// rather than a use of that entity.
bool DeclaringEntity : 1;
/// \brief If the result should have a nested-name-specifier, this is it.
/// When \c QualifierIsInformative, the nested-name-specifier is
/// informative rather than required.
NestedNameSpecifier *Qualifier;
/// \brief Build a result that refers to a declaration.
CodeCompletionResult(NamedDecl *Declaration,
NestedNameSpecifier *Qualifier = 0,
bool QualifierIsInformative = false,
bool Accessible = true)
: Kind(RK_Declaration), Declaration(Declaration),
Priority(getPriorityFromDecl(Declaration)),
Availability(CXAvailability_Available), StartParameter(0),
Hidden(false), QualifierIsInformative(QualifierIsInformative),
StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
DeclaringEntity(false), Qualifier(Qualifier) {
computeCursorKindAndAvailability(Accessible);
}
/// \brief Build a result that refers to a keyword or symbol.
CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
: Kind(RK_Keyword), Keyword(Keyword), Priority(Priority),
Availability(CXAvailability_Available),
StartParameter(0), Hidden(false), QualifierIsInformative(0),
StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
DeclaringEntity(false), Qualifier(0) {
computeCursorKindAndAvailability();
}
/// \brief Build a result that refers to a macro.
CodeCompletionResult(IdentifierInfo *Macro, unsigned Priority = CCP_Macro)
: Kind(RK_Macro), Macro(Macro), Priority(Priority),
Availability(CXAvailability_Available), StartParameter(0),
Hidden(false), QualifierIsInformative(0),
StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
DeclaringEntity(false), Qualifier(0) {
computeCursorKindAndAvailability();
}
/// \brief Build a result that refers to a pattern.
CodeCompletionResult(CodeCompletionString *Pattern,
unsigned Priority = CCP_CodePattern,
CXCursorKind CursorKind = CXCursor_NotImplemented,
CXAvailabilityKind Availability = CXAvailability_Available)
: Kind(RK_Pattern), Pattern(Pattern), Priority(Priority),
CursorKind(CursorKind), Availability(Availability), StartParameter(0),
Hidden(false), QualifierIsInformative(0),
StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
DeclaringEntity(false), Qualifier(0)
{
}
/// \brief Retrieve the declaration stored in this result.
NamedDecl *getDeclaration() const {
assert(Kind == RK_Declaration && "Not a declaration result");
return Declaration;
}
/// \brief Retrieve the keyword stored in this result.
const char *getKeyword() const {
assert(Kind == RK_Keyword && "Not a keyword result");
return Keyword;
}
/// \brief Create a new code-completion string that describes how to insert
/// this result into a program.
///
/// \param S The semantic analysis that created the result.
///
/// \param Allocator The allocator that will be used to allocate the
/// string itself.
CodeCompletionString *CreateCodeCompletionString(Sema &S,
CodeCompletionAllocator &Allocator);
/// \brief Determine a base priority for the given declaration.
static unsigned getPriorityFromDecl(NamedDecl *ND);
private:
void computeCursorKindAndAvailability(bool Accessible = true);
};
bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y);
inline bool operator>(const CodeCompletionResult &X,
const CodeCompletionResult &Y) {
return Y < X;
}
inline bool operator<=(const CodeCompletionResult &X,
const CodeCompletionResult &Y) {
return !(Y < X);
}
inline bool operator>=(const CodeCompletionResult &X,
const CodeCompletionResult &Y) {
return !(X < Y);
}
raw_ostream &operator<<(raw_ostream &OS,
const CodeCompletionString &CCS);
/// \brief Abstract interface for a consumer of code-completion
/// information.
class CodeCompleteConsumer {
protected:
/// \brief Whether to include macros in the code-completion results.
bool IncludeMacros;
/// \brief Whether to include code patterns (such as for loops) within
/// the completion results.
bool IncludeCodePatterns;
/// \brief Whether to include global (top-level) declarations and names in
/// the completion results.
bool IncludeGlobals;
/// \brief Whether the output format for the code-completion consumer is
/// binary.
bool OutputIsBinary;
public:
class OverloadCandidate {
public:
/// \brief Describes the type of overload candidate.
enum CandidateKind {
/// \brief The candidate is a function declaration.
CK_Function,
/// \brief The candidate is a function template.
CK_FunctionTemplate,
/// \brief The "candidate" is actually a variable, expression, or block
/// for which we only have a function prototype.
CK_FunctionType
};
private:
/// \brief The kind of overload candidate.
CandidateKind Kind;
union {
/// \brief The function overload candidate, available when
/// Kind == CK_Function.
FunctionDecl *Function;
/// \brief The function template overload candidate, available when
/// Kind == CK_FunctionTemplate.
FunctionTemplateDecl *FunctionTemplate;
/// \brief The function type that describes the entity being called,
/// when Kind == CK_FunctionType.
const FunctionType *Type;
};
public:
OverloadCandidate(FunctionDecl *Function)
: Kind(CK_Function), Function(Function) { }
OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
: Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) { }
OverloadCandidate(const FunctionType *Type)
: Kind(CK_FunctionType), Type(Type) { }
/// \brief Determine the kind of overload candidate.
CandidateKind getKind() const { return Kind; }
/// \brief Retrieve the function overload candidate or the templated
/// function declaration for a function template.
FunctionDecl *getFunction() const;
/// \brief Retrieve the function template overload candidate.
FunctionTemplateDecl *getFunctionTemplate() const {
assert(getKind() == CK_FunctionTemplate && "Not a function template");
return FunctionTemplate;
}
/// \brief Retrieve the function type of the entity, regardless of how the
/// function is stored.
const FunctionType *getFunctionType() const;
/// \brief Create a new code-completion string that describes the function
/// signature of this overload candidate.
CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
Sema &S,
CodeCompletionAllocator &Allocator) const;
};
CodeCompleteConsumer() : IncludeMacros(false), IncludeCodePatterns(false),
IncludeGlobals(true), OutputIsBinary(false) { }
CodeCompleteConsumer(bool IncludeMacros, bool IncludeCodePatterns,
bool IncludeGlobals, bool OutputIsBinary)
: IncludeMacros(IncludeMacros), IncludeCodePatterns(IncludeCodePatterns),
IncludeGlobals(IncludeGlobals), OutputIsBinary(OutputIsBinary) { }
/// \brief Whether the code-completion consumer wants to see macros.
bool includeMacros() const { return IncludeMacros; }
/// \brief Whether the code-completion consumer wants to see code patterns.
bool includeCodePatterns() const { return IncludeCodePatterns; }
/// \brief Whether to include global (top-level) declaration results.
bool includeGlobals() const { return IncludeGlobals; }
/// \brief Determine whether the output of this consumer is binary.
bool isOutputBinary() const { return OutputIsBinary; }
/// \brief Deregisters and destroys this code-completion consumer.
virtual ~CodeCompleteConsumer();
/// \name Code-completion callbacks
//@{
/// \brief Process the finalized code-completion results.
virtual void ProcessCodeCompleteResults(Sema &S,
CodeCompletionContext Context,
CodeCompletionResult *Results,
unsigned NumResults) { }
/// \param S the semantic-analyzer object for which code-completion is being
/// done.
///
/// \param CurrentArg the index of the current argument.
///
/// \param Candidates an array of overload candidates.
///
/// \param NumCandidates the number of overload candidates
virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
OverloadCandidate *Candidates,
unsigned NumCandidates) { }
//@}
/// \brief Retrieve the allocator that will be used to allocate
/// code completion strings.
virtual CodeCompletionAllocator &getAllocator() = 0;
};
/// \brief A simple code-completion consumer that prints the results it
/// receives in a simple format.
class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
/// \brief The raw output stream.
raw_ostream &OS;
CodeCompletionAllocator Allocator;
public:
/// \brief Create a new printing code-completion consumer that prints its
/// results to the given raw output stream.
PrintingCodeCompleteConsumer(bool IncludeMacros, bool IncludeCodePatterns,
bool IncludeGlobals,
raw_ostream &OS)
: CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
false), OS(OS) {}
/// \brief Prints the finalized code-completion results.
virtual void ProcessCodeCompleteResults(Sema &S,
CodeCompletionContext Context,
CodeCompletionResult *Results,
unsigned NumResults);
virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
OverloadCandidate *Candidates,
unsigned NumCandidates);
virtual CodeCompletionAllocator &getAllocator() { return Allocator; }
};
} // end namespace clang
#endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
| [
"[email protected]"
] | |
b68c545eaa3f8e5af8222a6e561f869b396cb7f9 | ed1e2af90cfccf66ea1d6a341ced0a428c482751 | /Classes/GLES-Render.h | d718d926b835181a77d365ba407dd556b03537bc | [] | no_license | haidragon/shjs | 66a40f5675e93dfef36e5b79c61e79bd24f9812f | c4c7ad26a5d227070ab77983b2c397430be125ac | refs/heads/master | 2020-04-10T17:40:04.631591 | 2016-02-25T06:42:16 | 2016-02-25T06:42:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,182 | h | /*
* Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
*
* iPhone port by Simon Oliver - http://www.simonoliver.com - http://www.handcircus.com
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#ifndef RENDER_H
#define RENDER_H
#include "Box2D/Box2D.h"
#include "cocos2d.h"
struct b2AABB;
// This class implements debug drawing callbacks that are invoked
// inside b2World::Step.
class GLESDebugDraw : public b2Draw
{
float32 mRatio;
cocos2d::CCGLProgram* mShaderProgram;
GLint mColorLocation;
void initShader( void );
public:
GLESDebugDraw();
GLESDebugDraw( float32 ratio );
virtual void DrawPolygon(const b2Vec2* vertices, int vertexCount, const b2Color& color);
virtual void DrawSolidPolygon(const b2Vec2* vertices, int vertexCount, const b2Color& color);
virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color);
virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color);
virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color);
virtual void DrawTransform(const b2Transform& xf);
virtual void DrawPoint(const b2Vec2& p, float32 size, const b2Color& color);
virtual void DrawString(int x, int y, const char* string, ...);
virtual void DrawAABB(b2AABB* aabb, const b2Color& color);
};
#endif
| [
"[email protected]"
] | |
ddf10e4e315a56f45d3af27afae024c6a6e7f4d6 | dd3d11771fd5affedf06f9fcf174bc83a3f2b139 | /BotCore/DofusProtocol/MimicryObjectPreviewMessage.h | 68fc60ba7e6112e6b931f5bc776df1e2ad7ab50d | [] | no_license | Arkwell9112/arkwBot | d3f77ad3874e831594bd5712705983618e94f258 | 859f78dd5c777077b3005870800cb62eec1a9587 | refs/heads/master | 2023-03-17T12:45:07.560436 | 2021-03-16T11:22:35 | 2021-03-16T11:22:35 | 338,042,990 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 450 | h | #ifndef MIMICRYOBJECTPREVIEWMESSAGE
#define MIMICRYOBJECTPREVIEWMESSAGE
#include "../IO/ICustomDataInput.h"
#include "../NetworkInterface.h"
#include "ObjectItem.h"
#include "Item.h"
class MimicryObjectPreviewMessage : public NetworkInterface {
public:
ObjectItem result;
unsigned int protocolId = 4707;
void deserialize(ICustomDataInput &input);
void deserializeAs_MimicryObjectPreviewMessage(ICustomDataInput &input);
};
#endif | [
"[email protected]"
] | |
01282c8fa84e829b3176cc30aba7471705e86a03 | ed15181309dbda9c34b99172368bbd163e6bc3a3 | /libdevcore/FileSystem.cpp | 752a7bb8676f7e0415b35bf37b43087bd8ccf6a9 | [] | no_license | Utispace/UtispaceChain | f15b897712a6fb644e54de2aa178727dd6760520 | 43e4b99b198fbf1b8695c2971a01967e33bc6dba | refs/heads/master | 2020-12-11T09:56:55.045686 | 2020-01-14T11:00:02 | 2020-01-14T11:00:02 | 233,815,216 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,515 | cpp |
#include "FileSystem.h"
#include "Common.h"
#include "easylog.h"
#if defined(_WIN32)
#include <shlobj.h>
#else
#include <stdlib.h>
#include <stdio.h>
#include <pwd.h>
#include <unistd.h>
#endif
#include <boost/filesystem.hpp>
using namespace std;
using namespace dev;
static string s_ethereumDatadir __attribute__ ((init_priority (1000))); //centos
static string s_ethereumIpcPath;
static string s_ehtereumConfigPath;
static string s_caInitType;
static int s_cryptoMod;//加密方式
static map<int,string> s_dataKey;//datakey数据
static int s_cryptoprivatekeyMod;
static string s_privateKey;
static int s_ssl;
void dev::setCryptoPrivateKeyMod(int cryptoprivatekeyMod)
{
s_cryptoprivatekeyMod = cryptoprivatekeyMod;
}
int dev::getCryptoPrivateKeyMod()
{
return s_cryptoprivatekeyMod;
}
void dev::setPrivateKey(string const& privateKey)
{
s_privateKey = privateKey;
}
string dev::getPrivateKey()
{
return s_privateKey;
}
void dev::setCryptoMod(int cryptoMod)
{
s_cryptoMod = cryptoMod;
}
int dev::getCryptoMod()
{
return s_cryptoMod;
}
int dev::getSSL()
{
return s_ssl;
}
void dev::setSSL(int ssl)
{
s_ssl = ssl;
}
void dev::setDataKey(string const& dataKey1,string const& dataKey2,string const& dataKey3,string const& dataKey4)
{
s_dataKey[0] = dataKey1;
s_dataKey[1] = dataKey2;
s_dataKey[2] = dataKey3;
s_dataKey[3] = dataKey4;
}
map<int,string> dev::getDataKey()
{
return s_dataKey;
}
void dev::setDataDir(string const& _dataDir)
{
s_ethereumDatadir = _dataDir;
}
void dev::setIpcPath(string const& _ipcDir)
{
s_ethereumIpcPath = _ipcDir;
}
void dev::setConfigPath(string const& _configPath)
{
s_ehtereumConfigPath = _configPath;
}
void dev::setCaInitType(string const& _caInitType)
{
s_caInitType = _caInitType;
}
string dev::getCaInitType()
{
if (s_caInitType.empty())
{
return "cybervein";
}
return s_caInitType;
}
string dev::getConfigPath()
{
if (s_ehtereumConfigPath.empty())
{
return getDataDir() + "/config.json";
}
return s_ehtereumConfigPath;
}
string dev::getIpcPath()
{
if (s_ethereumIpcPath.empty())
return string(getDataDir());
else
{
size_t socketPos = s_ethereumIpcPath.rfind("geth.ipc");
if (socketPos != string::npos)
return s_ethereumIpcPath.substr(0, socketPos);
return s_ethereumIpcPath;
}
}
string dev::getDataDir(string _prefix)
{
if (_prefix.empty())
_prefix = "ethereum";
if (_prefix == "ethereum" && !s_ethereumDatadir.empty())
return s_ethereumDatadir;
if (_prefix == "web3" && !s_ethereumDatadir.empty())
return s_ethereumDatadir+".web3";
return getDefaultDataDir(_prefix);
}
string dev::getDefaultDataDir(string _prefix)
{
if (_prefix.empty())
_prefix = "ethereum";
#if defined(_WIN32)
_prefix[0] = toupper(_prefix[0]);
char path[1024] = "";
if (SHGetSpecialFolderPathA(NULL, path, CSIDL_APPDATA, true))
return (boost::filesystem::path(path) / _prefix).string();
else
{
#ifndef _MSC_VER // todo?
LOG(WARNING) << "getDataDir(): SHGetSpecialFolderPathA() failed.";
#endif
BOOST_THROW_EXCEPTION(std::runtime_error("getDataDir() - SHGetSpecialFolderPathA() failed."));
}
#else
boost::filesystem::path dataDirPath;
char const* homeDir = getenv("HOME");
if (!homeDir || strlen(homeDir) == 0)
{
struct passwd* pwd = getpwuid(getuid());
if (pwd)
homeDir = pwd->pw_dir;
}
if (!homeDir || strlen(homeDir) == 0)
dataDirPath = boost::filesystem::path("/");
else
dataDirPath = boost::filesystem::path(homeDir);
return (dataDirPath / ("." + _prefix)).string();
#endif
}
| [
"[email protected]"
] | |
dad60ab572855ef11dedef9cfca66bbd2be380f5 | ac372e2fdc9352414169b4791e58f43ec56b8922 | /Export/linux/obj/src/openfl/display3D/VertexBuffer3D.cpp | e559aa062c2a996e8960594a1d05a7aafdb558cc | [] | no_license | JavaDeva/HAXE_TPE | 4c7023811b153061038fe0effe913f055f531e22 | a201e718b73658bff943c268b097a86f858d3817 | refs/heads/master | 2022-08-15T21:33:14.010205 | 2020-05-28T15:34:32 | 2020-05-28T15:34:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 28,195 | cpp | // Generated by Haxe 4.1.1
#include <hxcpp.h>
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_haxe_Exception
#include <haxe/Exception.h>
#endif
#ifndef INCLUDED_haxe_io_Bytes
#include <haxe/io/Bytes.h>
#endif
#ifndef INCLUDED_lime__internal_backend_native_NativeOpenGLRenderContext
#include <lime/_internal/backend/native/NativeOpenGLRenderContext.h>
#endif
#ifndef INCLUDED_lime_graphics__WebGLRenderContext_WebGLRenderContext_Impl_
#include <lime/graphics/_WebGLRenderContext/WebGLRenderContext_Impl_.h>
#endif
#ifndef INCLUDED_lime_graphics_opengl_GLObject
#include <lime/graphics/opengl/GLObject.h>
#endif
#ifndef INCLUDED_lime_utils_ArrayBufferView
#include <lime/utils/ArrayBufferView.h>
#endif
#ifndef INCLUDED_lime_utils_TAError
#include <lime/utils/TAError.h>
#endif
#ifndef INCLUDED_openfl__Vector_FloatVector
#include <openfl/_Vector/FloatVector.h>
#endif
#ifndef INCLUDED_openfl__Vector_IVector
#include <openfl/_Vector/IVector.h>
#endif
#ifndef INCLUDED_openfl_display3D_Context3D
#include <openfl/display3D/Context3D.h>
#endif
#ifndef INCLUDED_openfl_display3D_VertexBuffer3D
#include <openfl/display3D/VertexBuffer3D.h>
#endif
#ifndef INCLUDED_openfl_display3D__Context3DBufferUsage_Context3DBufferUsage_Impl_
#include <openfl/display3D/_Context3DBufferUsage/Context3DBufferUsage_Impl_.h>
#endif
#ifndef INCLUDED_openfl_events_EventDispatcher
#include <openfl/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_events_IEventDispatcher
#include <openfl/events/IEventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_utils_ByteArrayData
#include <openfl/utils/ByteArrayData.h>
#endif
#ifndef INCLUDED_openfl_utils_IDataInput
#include <openfl/utils/IDataInput.h>
#endif
#ifndef INCLUDED_openfl_utils_IDataOutput
#include <openfl/utils/IDataOutput.h>
#endif
#ifndef INCLUDED_openfl_utils__ByteArray_ByteArray_Impl_
#include <openfl/utils/_ByteArray/ByteArray_Impl_.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_8e0849c8e2179fab_65_new,"openfl.display3D.VertexBuffer3D","new",0xf0b52080,"openfl.display3D.VertexBuffer3D.new","openfl/display3D/VertexBuffer3D.hx",65,0xb1ad396e)
HX_LOCAL_STACK_FRAME(_hx_pos_8e0849c8e2179fab_82_dispose,"openfl.display3D.VertexBuffer3D","dispose",0x6b6860bf,"openfl.display3D.VertexBuffer3D.dispose","openfl/display3D/VertexBuffer3D.hx",82,0xb1ad396e)
HX_LOCAL_STACK_FRAME(_hx_pos_8e0849c8e2179fab_108_uploadFromByteArray,"openfl.display3D.VertexBuffer3D","uploadFromByteArray",0x0096a806,"openfl.display3D.VertexBuffer3D.uploadFromByteArray","openfl/display3D/VertexBuffer3D.hx",108,0xb1ad396e)
HX_LOCAL_STACK_FRAME(_hx_pos_8e0849c8e2179fab_127_uploadFromTypedArray,"openfl.display3D.VertexBuffer3D","uploadFromTypedArray",0xeb97089a,"openfl.display3D.VertexBuffer3D.uploadFromTypedArray","openfl/display3D/VertexBuffer3D.hx",127,0xb1ad396e)
HX_LOCAL_STACK_FRAME(_hx_pos_8e0849c8e2179fab_153_uploadFromVector,"openfl.display3D.VertexBuffer3D","uploadFromVector",0xcf228b0e,"openfl.display3D.VertexBuffer3D.uploadFromVector","openfl/display3D/VertexBuffer3D.hx",153,0xb1ad396e)
namespace openfl{
namespace display3D{
void VertexBuffer3D_obj::__construct( ::openfl::display3D::Context3D context3D,int numVertices,int dataPerVertex,::String bufferUsage){
HX_STACKFRAME(&_hx_pos_8e0849c8e2179fab_65_new)
HXLINE( 66) this->_hx___context = context3D;
HXLINE( 67) this->_hx___numVertices = numVertices;
HXLINE( 68) this->_hx___vertexSize = dataPerVertex;
HXLINE( 70) ::lime::_internal::backend::native::NativeOpenGLRenderContext gl = this->_hx___context->gl;
HXLINE( 72) this->_hx___id = gl->createBuffer();
HXLINE( 73) this->_hx___stride = (this->_hx___vertexSize * 4);
HXLINE( 74) int _hx_tmp;
HXDLIN( 74) if (::hx::IsEq( ::openfl::display3D::_Context3DBufferUsage::Context3DBufferUsage_Impl__obj::fromString(bufferUsage),0 )) {
HXLINE( 74) _hx_tmp = gl->DYNAMIC_DRAW;
}
else {
HXLINE( 74) _hx_tmp = gl->STATIC_DRAW;
}
HXDLIN( 74) this->_hx___usage = _hx_tmp;
}
Dynamic VertexBuffer3D_obj::__CreateEmpty() { return new VertexBuffer3D_obj; }
void *VertexBuffer3D_obj::_hx_vtable = 0;
Dynamic VertexBuffer3D_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< VertexBuffer3D_obj > _hx_result = new VertexBuffer3D_obj();
_hx_result->__construct(inArgs[0],inArgs[1],inArgs[2],inArgs[3]);
return _hx_result;
}
bool VertexBuffer3D_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x5c924e78;
}
void VertexBuffer3D_obj::dispose(){
HX_STACKFRAME(&_hx_pos_8e0849c8e2179fab_82_dispose)
HXLINE( 83) ::lime::_internal::backend::native::NativeOpenGLRenderContext gl = this->_hx___context->gl;
HXLINE( 84) gl->deleteBuffer(this->_hx___id);
}
HX_DEFINE_DYNAMIC_FUNC0(VertexBuffer3D_obj,dispose,(void))
void VertexBuffer3D_obj::uploadFromByteArray( ::openfl::utils::ByteArrayData data,int byteArrayOffset,int startVertex,int numVertices){
HX_GC_STACKFRAME(&_hx_pos_8e0849c8e2179fab_108_uploadFromByteArray)
HXLINE( 110) int offset = (byteArrayOffset + (startVertex * this->_hx___stride));
HXLINE( 111) int length = (numVertices * this->_hx___vertexSize);
HXLINE( 113) ::Dynamic elements = null();
HXDLIN( 113) ::haxe::io::Bytes buffer = ::openfl::utils::_ByteArray::ByteArray_Impl__obj::toArrayBuffer(data);
HXDLIN( 113) ::cpp::VirtualArray array = null();
HXDLIN( 113) ::openfl::_Vector::FloatVector vector = null();
HXDLIN( 113) ::lime::utils::ArrayBufferView view = null();
HXDLIN( 113) ::Dynamic byteoffset = offset;
HXDLIN( 113) if (::hx::IsNull( byteoffset )) {
HXLINE( 113) byteoffset = 0;
}
HXDLIN( 113) ::lime::utils::ArrayBufferView this1;
HXDLIN( 113) if (::hx::IsNotNull( elements )) {
HXLINE( 113) this1 = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,elements,8);
}
else {
HXLINE( 113) if (::hx::IsNotNull( array )) {
HXLINE( 113) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8);
HXDLIN( 113) _this->byteOffset = 0;
HXDLIN( 113) _this->length = array->get_length();
HXDLIN( 113) _this->byteLength = (_this->length * _this->bytesPerElement);
HXDLIN( 113) ::haxe::io::Bytes this2 = ::haxe::io::Bytes_obj::alloc(_this->byteLength);
HXDLIN( 113) _this->buffer = this2;
HXDLIN( 113) _this->copyFromArray(array,null());
HXDLIN( 113) this1 = _this;
}
else {
HXLINE( 113) if (::hx::IsNotNull( vector )) {
HXLINE( 113) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8);
HXDLIN( 113) ::cpp::VirtualArray array = ( (::cpp::VirtualArray)(vector->__Field(HX_("__array",79,c6,ed,8f),::hx::paccDynamic)) );
HXDLIN( 113) _this->byteOffset = 0;
HXDLIN( 113) _this->length = array->get_length();
HXDLIN( 113) _this->byteLength = (_this->length * _this->bytesPerElement);
HXDLIN( 113) ::haxe::io::Bytes this2 = ::haxe::io::Bytes_obj::alloc(_this->byteLength);
HXDLIN( 113) _this->buffer = this2;
HXDLIN( 113) _this->copyFromArray(array,null());
HXDLIN( 113) this1 = _this;
}
else {
HXLINE( 113) if (::hx::IsNotNull( view )) {
HXLINE( 113) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8);
HXDLIN( 113) ::haxe::io::Bytes srcData = view->buffer;
HXDLIN( 113) int srcLength = view->length;
HXDLIN( 113) int srcByteOffset = view->byteOffset;
HXDLIN( 113) int srcElementSize = view->bytesPerElement;
HXDLIN( 113) int elementSize = _this->bytesPerElement;
HXDLIN( 113) if ((view->type == _this->type)) {
HXLINE( 113) int srcLength = srcData->length;
HXDLIN( 113) int cloneLength = (srcLength - srcByteOffset);
HXDLIN( 113) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(cloneLength);
HXDLIN( 113) _this->buffer = this1;
HXDLIN( 113) _this->buffer->blit(0,srcData,srcByteOffset,cloneLength);
}
else {
HXLINE( 113) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("unimplemented",09,2f,74,b4)));
}
HXDLIN( 113) _this->byteLength = (_this->bytesPerElement * srcLength);
HXDLIN( 113) _this->byteOffset = 0;
HXDLIN( 113) _this->length = srcLength;
HXDLIN( 113) this1 = _this;
}
else {
HXLINE( 113) if (::hx::IsNotNull( buffer )) {
HXLINE( 113) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8);
HXDLIN( 113) int in_byteOffset = ( (int)(byteoffset) );
HXDLIN( 113) if ((in_byteOffset < 0)) {
HXLINE( 113) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn()));
}
HXDLIN( 113) if ((::hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) {
HXLINE( 113) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn()));
}
HXDLIN( 113) int bufferByteLength = buffer->length;
HXDLIN( 113) int elementSize = _this->bytesPerElement;
HXDLIN( 113) int newByteLength = bufferByteLength;
HXDLIN( 113) if (::hx::IsNull( length )) {
HXLINE( 113) newByteLength = (bufferByteLength - in_byteOffset);
HXDLIN( 113) if ((::hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) {
HXLINE( 113) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn()));
}
HXDLIN( 113) if ((newByteLength < 0)) {
HXLINE( 113) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn()));
}
}
else {
HXLINE( 113) newByteLength = (length * _this->bytesPerElement);
HXDLIN( 113) int newRange = (in_byteOffset + newByteLength);
HXDLIN( 113) if ((newRange > bufferByteLength)) {
HXLINE( 113) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn()));
}
}
HXDLIN( 113) _this->buffer = buffer;
HXDLIN( 113) _this->byteOffset = in_byteOffset;
HXDLIN( 113) _this->byteLength = newByteLength;
HXDLIN( 113) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) )));
HXDLIN( 113) this1 = _this;
}
else {
HXLINE( 113) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid constructor arguments for Float32Array",8e,c1,f4,d4)));
}
}
}
}
}
HXDLIN( 113) this->uploadFromTypedArray(this1,null());
}
HX_DEFINE_DYNAMIC_FUNC4(VertexBuffer3D_obj,uploadFromByteArray,(void))
void VertexBuffer3D_obj::uploadFromTypedArray( ::lime::utils::ArrayBufferView data,::hx::Null< int > __o_byteLength){
int byteLength = __o_byteLength.Default(-1);
HX_STACKFRAME(&_hx_pos_8e0849c8e2179fab_127_uploadFromTypedArray)
HXLINE( 128) if (::hx::IsNull( data )) {
HXLINE( 128) return;
}
HXLINE( 129) ::lime::_internal::backend::native::NativeOpenGLRenderContext gl = this->_hx___context->gl;
HXLINE( 131) this->_hx___context->_hx___bindGLArrayBuffer(this->_hx___id);
HXLINE( 132) ::lime::graphics::_WebGLRenderContext::WebGLRenderContext_Impl__obj::bufferData(gl,gl->ARRAY_BUFFER,data,this->_hx___usage);
}
HX_DEFINE_DYNAMIC_FUNC2(VertexBuffer3D_obj,uploadFromTypedArray,(void))
void VertexBuffer3D_obj::uploadFromVector( ::openfl::_Vector::FloatVector data,int startVertex,int numVertices){
HX_GC_STACKFRAME(&_hx_pos_8e0849c8e2179fab_153_uploadFromVector)
HXLINE( 155) if (::hx::IsNull( data )) {
HXLINE( 155) return;
}
HXLINE( 156) ::lime::_internal::backend::native::NativeOpenGLRenderContext gl = this->_hx___context->gl;
HXLINE( 160) int start = (startVertex * this->_hx___vertexSize);
HXLINE( 161) int count = (numVertices * this->_hx___vertexSize);
HXLINE( 162) int length = (start + count);
HXLINE( 164) ::lime::utils::ArrayBufferView existingFloat32Array = this->_hx___tempFloat32Array;
HXLINE( 166) bool _hx_tmp;
HXDLIN( 166) if (::hx::IsNotNull( this->_hx___tempFloat32Array )) {
HXLINE( 166) _hx_tmp = (this->_hx___tempFloat32Array->length < count);
}
else {
HXLINE( 166) _hx_tmp = true;
}
HXDLIN( 166) if (_hx_tmp) {
HXLINE( 168) ::haxe::io::Bytes buffer = null();
HXDLIN( 168) ::cpp::VirtualArray array = null();
HXDLIN( 168) ::openfl::_Vector::FloatVector vector = null();
HXDLIN( 168) ::lime::utils::ArrayBufferView view = null();
HXDLIN( 168) ::Dynamic len = null();
HXDLIN( 168) ::lime::utils::ArrayBufferView this1;
HXDLIN( 168) if (::hx::IsNotNull( count )) {
HXLINE( 168) this1 = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,count,8);
}
else {
HXLINE( 168) if (::hx::IsNotNull( array )) {
HXLINE( 168) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8);
HXDLIN( 168) _this->byteOffset = 0;
HXDLIN( 168) _this->length = array->get_length();
HXDLIN( 168) _this->byteLength = (_this->length * _this->bytesPerElement);
HXDLIN( 168) ::haxe::io::Bytes this2 = ::haxe::io::Bytes_obj::alloc(_this->byteLength);
HXDLIN( 168) _this->buffer = this2;
HXDLIN( 168) _this->copyFromArray(array,null());
HXDLIN( 168) this1 = _this;
}
else {
HXLINE( 168) if (::hx::IsNotNull( vector )) {
HXLINE( 168) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8);
HXDLIN( 168) ::cpp::VirtualArray array = ( (::cpp::VirtualArray)(vector->__Field(HX_("__array",79,c6,ed,8f),::hx::paccDynamic)) );
HXDLIN( 168) _this->byteOffset = 0;
HXDLIN( 168) _this->length = array->get_length();
HXDLIN( 168) _this->byteLength = (_this->length * _this->bytesPerElement);
HXDLIN( 168) ::haxe::io::Bytes this2 = ::haxe::io::Bytes_obj::alloc(_this->byteLength);
HXDLIN( 168) _this->buffer = this2;
HXDLIN( 168) _this->copyFromArray(array,null());
HXDLIN( 168) this1 = _this;
}
else {
HXLINE( 168) if (::hx::IsNotNull( view )) {
HXLINE( 168) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8);
HXDLIN( 168) ::haxe::io::Bytes srcData = view->buffer;
HXDLIN( 168) int srcLength = view->length;
HXDLIN( 168) int srcByteOffset = view->byteOffset;
HXDLIN( 168) int srcElementSize = view->bytesPerElement;
HXDLIN( 168) int elementSize = _this->bytesPerElement;
HXDLIN( 168) if ((view->type == _this->type)) {
HXLINE( 168) int srcLength = srcData->length;
HXDLIN( 168) int cloneLength = (srcLength - srcByteOffset);
HXDLIN( 168) ::haxe::io::Bytes this1 = ::haxe::io::Bytes_obj::alloc(cloneLength);
HXDLIN( 168) _this->buffer = this1;
HXDLIN( 168) _this->buffer->blit(0,srcData,srcByteOffset,cloneLength);
}
else {
HXLINE( 168) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("unimplemented",09,2f,74,b4)));
}
HXDLIN( 168) _this->byteLength = (_this->bytesPerElement * srcLength);
HXDLIN( 168) _this->byteOffset = 0;
HXDLIN( 168) _this->length = srcLength;
HXDLIN( 168) this1 = _this;
}
else {
HXLINE( 168) if (::hx::IsNotNull( buffer )) {
HXLINE( 168) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,8);
HXDLIN( 168) int in_byteOffset = 0;
HXDLIN( 168) if ((in_byteOffset < 0)) {
HXLINE( 168) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn()));
}
HXDLIN( 168) if ((::hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) {
HXLINE( 168) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn()));
}
HXDLIN( 168) int bufferByteLength = buffer->length;
HXDLIN( 168) int elementSize = _this->bytesPerElement;
HXDLIN( 168) int newByteLength = bufferByteLength;
HXDLIN( 168) if (::hx::IsNull( len )) {
HXLINE( 168) newByteLength = (bufferByteLength - in_byteOffset);
HXDLIN( 168) if ((::hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) {
HXLINE( 168) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn()));
}
HXDLIN( 168) if ((newByteLength < 0)) {
HXLINE( 168) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn()));
}
}
else {
HXLINE( 168) newByteLength = (( (int)(len) ) * _this->bytesPerElement);
HXDLIN( 168) int newRange = (in_byteOffset + newByteLength);
HXDLIN( 168) if ((newRange > bufferByteLength)) {
HXLINE( 168) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(::lime::utils::TAError_obj::RangeError_dyn()));
}
}
HXDLIN( 168) _this->buffer = buffer;
HXDLIN( 168) _this->byteOffset = in_byteOffset;
HXDLIN( 168) _this->byteLength = newByteLength;
HXDLIN( 168) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) )));
HXDLIN( 168) this1 = _this;
}
else {
HXLINE( 168) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid constructor arguments for Float32Array",8e,c1,f4,d4)));
}
}
}
}
}
HXDLIN( 168) this->_hx___tempFloat32Array = this1;
HXLINE( 170) if (::hx::IsNotNull( existingFloat32Array )) {
HXLINE( 172) ::lime::utils::ArrayBufferView _this = this->_hx___tempFloat32Array;
HXDLIN( 172) ::cpp::VirtualArray array = null();
HXDLIN( 172) int offset = 0;
HXDLIN( 172) bool _hx_tmp;
HXDLIN( 172) if (::hx::IsNotNull( existingFloat32Array )) {
HXLINE( 172) _hx_tmp = ::hx::IsNull( array );
}
else {
HXLINE( 172) _hx_tmp = false;
}
HXDLIN( 172) if (_hx_tmp) {
HXLINE( 172) _this->buffer->blit((offset * _this->bytesPerElement),existingFloat32Array->buffer,existingFloat32Array->byteOffset,existingFloat32Array->byteLength);
}
else {
HXLINE( 172) bool _hx_tmp;
HXDLIN( 172) if (::hx::IsNotNull( array )) {
HXLINE( 172) _hx_tmp = ::hx::IsNull( existingFloat32Array );
}
else {
HXLINE( 172) _hx_tmp = false;
}
HXDLIN( 172) if (_hx_tmp) {
HXLINE( 172) _this->copyFromArray(array,offset);
}
else {
HXLINE( 172) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown(HX_("Invalid .set call. either view, or array must be not-null.",64,ba,b7,6c)));
}
}
}
}
HXLINE( 176) {
HXLINE( 176) int _g = start;
HXDLIN( 176) int _g1 = length;
HXDLIN( 176) while((_g < _g1)){
HXLINE( 176) _g = (_g + 1);
HXDLIN( 176) int i = (_g - 1);
HXLINE( 178) {
HXLINE( 178) ::lime::utils::ArrayBufferView this1 = this->_hx___tempFloat32Array;
HXDLIN( 178) Float val = data->get(i);
HXDLIN( 178) ::__hxcpp_memory_set_float(this1->buffer->b,(this1->byteOffset + ((i - start) * 4)),val);
}
}
}
HXLINE( 181) this->uploadFromTypedArray(this->_hx___tempFloat32Array,null());
}
HX_DEFINE_DYNAMIC_FUNC3(VertexBuffer3D_obj,uploadFromVector,(void))
::hx::ObjectPtr< VertexBuffer3D_obj > VertexBuffer3D_obj::__new( ::openfl::display3D::Context3D context3D,int numVertices,int dataPerVertex,::String bufferUsage) {
::hx::ObjectPtr< VertexBuffer3D_obj > __this = new VertexBuffer3D_obj();
__this->__construct(context3D,numVertices,dataPerVertex,bufferUsage);
return __this;
}
::hx::ObjectPtr< VertexBuffer3D_obj > VertexBuffer3D_obj::__alloc(::hx::Ctx *_hx_ctx, ::openfl::display3D::Context3D context3D,int numVertices,int dataPerVertex,::String bufferUsage) {
VertexBuffer3D_obj *__this = (VertexBuffer3D_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(VertexBuffer3D_obj), true, "openfl.display3D.VertexBuffer3D"));
*(void **)__this = VertexBuffer3D_obj::_hx_vtable;
__this->__construct(context3D,numVertices,dataPerVertex,bufferUsage);
return __this;
}
VertexBuffer3D_obj::VertexBuffer3D_obj()
{
}
void VertexBuffer3D_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(VertexBuffer3D);
HX_MARK_MEMBER_NAME(_hx___context,"__context");
HX_MARK_MEMBER_NAME(_hx___data,"__data");
HX_MARK_MEMBER_NAME(_hx___id,"__id");
HX_MARK_MEMBER_NAME(_hx___memoryUsage,"__memoryUsage");
HX_MARK_MEMBER_NAME(_hx___numVertices,"__numVertices");
HX_MARK_MEMBER_NAME(_hx___stride,"__stride");
HX_MARK_MEMBER_NAME(_hx___tempFloat32Array,"__tempFloat32Array");
HX_MARK_MEMBER_NAME(_hx___usage,"__usage");
HX_MARK_MEMBER_NAME(_hx___vertexSize,"__vertexSize");
HX_MARK_END_CLASS();
}
void VertexBuffer3D_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(_hx___context,"__context");
HX_VISIT_MEMBER_NAME(_hx___data,"__data");
HX_VISIT_MEMBER_NAME(_hx___id,"__id");
HX_VISIT_MEMBER_NAME(_hx___memoryUsage,"__memoryUsage");
HX_VISIT_MEMBER_NAME(_hx___numVertices,"__numVertices");
HX_VISIT_MEMBER_NAME(_hx___stride,"__stride");
HX_VISIT_MEMBER_NAME(_hx___tempFloat32Array,"__tempFloat32Array");
HX_VISIT_MEMBER_NAME(_hx___usage,"__usage");
HX_VISIT_MEMBER_NAME(_hx___vertexSize,"__vertexSize");
}
::hx::Val VertexBuffer3D_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"__id") ) { return ::hx::Val( _hx___id ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"__data") ) { return ::hx::Val( _hx___data ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"__usage") ) { return ::hx::Val( _hx___usage ); }
if (HX_FIELD_EQ(inName,"dispose") ) { return ::hx::Val( dispose_dyn() ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"__stride") ) { return ::hx::Val( _hx___stride ); }
break;
case 9:
if (HX_FIELD_EQ(inName,"__context") ) { return ::hx::Val( _hx___context ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"__vertexSize") ) { return ::hx::Val( _hx___vertexSize ); }
break;
case 13:
if (HX_FIELD_EQ(inName,"__memoryUsage") ) { return ::hx::Val( _hx___memoryUsage ); }
if (HX_FIELD_EQ(inName,"__numVertices") ) { return ::hx::Val( _hx___numVertices ); }
break;
case 16:
if (HX_FIELD_EQ(inName,"uploadFromVector") ) { return ::hx::Val( uploadFromVector_dyn() ); }
break;
case 18:
if (HX_FIELD_EQ(inName,"__tempFloat32Array") ) { return ::hx::Val( _hx___tempFloat32Array ); }
break;
case 19:
if (HX_FIELD_EQ(inName,"uploadFromByteArray") ) { return ::hx::Val( uploadFromByteArray_dyn() ); }
break;
case 20:
if (HX_FIELD_EQ(inName,"uploadFromTypedArray") ) { return ::hx::Val( uploadFromTypedArray_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
::hx::Val VertexBuffer3D_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"__id") ) { _hx___id=inValue.Cast< ::lime::graphics::opengl::GLObject >(); return inValue; }
break;
case 6:
if (HX_FIELD_EQ(inName,"__data") ) { _hx___data=inValue.Cast< ::openfl::_Vector::FloatVector >(); return inValue; }
break;
case 7:
if (HX_FIELD_EQ(inName,"__usage") ) { _hx___usage=inValue.Cast< int >(); return inValue; }
break;
case 8:
if (HX_FIELD_EQ(inName,"__stride") ) { _hx___stride=inValue.Cast< int >(); return inValue; }
break;
case 9:
if (HX_FIELD_EQ(inName,"__context") ) { _hx___context=inValue.Cast< ::openfl::display3D::Context3D >(); return inValue; }
break;
case 12:
if (HX_FIELD_EQ(inName,"__vertexSize") ) { _hx___vertexSize=inValue.Cast< int >(); return inValue; }
break;
case 13:
if (HX_FIELD_EQ(inName,"__memoryUsage") ) { _hx___memoryUsage=inValue.Cast< int >(); return inValue; }
if (HX_FIELD_EQ(inName,"__numVertices") ) { _hx___numVertices=inValue.Cast< int >(); return inValue; }
break;
case 18:
if (HX_FIELD_EQ(inName,"__tempFloat32Array") ) { _hx___tempFloat32Array=inValue.Cast< ::lime::utils::ArrayBufferView >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void VertexBuffer3D_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("__context",cf,e6,c5,9a));
outFields->push(HX_("__data",4a,b9,5b,f1));
outFields->push(HX_("__id",fb,b6,13,3f));
outFields->push(HX_("__memoryUsage",40,bf,50,c5));
outFields->push(HX_("__numVertices",3f,51,a4,9e));
outFields->push(HX_("__stride",39,8b,5f,b9));
outFields->push(HX_("__tempFloat32Array",b2,e6,d3,6c));
outFields->push(HX_("__usage",01,b6,8d,14));
outFields->push(HX_("__vertexSize",65,a5,a3,15));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo VertexBuffer3D_obj_sMemberStorageInfo[] = {
{::hx::fsObject /* ::openfl::display3D::Context3D */ ,(int)offsetof(VertexBuffer3D_obj,_hx___context),HX_("__context",cf,e6,c5,9a)},
{::hx::fsObject /* ::openfl::_Vector::FloatVector */ ,(int)offsetof(VertexBuffer3D_obj,_hx___data),HX_("__data",4a,b9,5b,f1)},
{::hx::fsObject /* ::lime::graphics::opengl::GLObject */ ,(int)offsetof(VertexBuffer3D_obj,_hx___id),HX_("__id",fb,b6,13,3f)},
{::hx::fsInt,(int)offsetof(VertexBuffer3D_obj,_hx___memoryUsage),HX_("__memoryUsage",40,bf,50,c5)},
{::hx::fsInt,(int)offsetof(VertexBuffer3D_obj,_hx___numVertices),HX_("__numVertices",3f,51,a4,9e)},
{::hx::fsInt,(int)offsetof(VertexBuffer3D_obj,_hx___stride),HX_("__stride",39,8b,5f,b9)},
{::hx::fsObject /* ::lime::utils::ArrayBufferView */ ,(int)offsetof(VertexBuffer3D_obj,_hx___tempFloat32Array),HX_("__tempFloat32Array",b2,e6,d3,6c)},
{::hx::fsInt,(int)offsetof(VertexBuffer3D_obj,_hx___usage),HX_("__usage",01,b6,8d,14)},
{::hx::fsInt,(int)offsetof(VertexBuffer3D_obj,_hx___vertexSize),HX_("__vertexSize",65,a5,a3,15)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo *VertexBuffer3D_obj_sStaticStorageInfo = 0;
#endif
static ::String VertexBuffer3D_obj_sMemberFields[] = {
HX_("__context",cf,e6,c5,9a),
HX_("__data",4a,b9,5b,f1),
HX_("__id",fb,b6,13,3f),
HX_("__memoryUsage",40,bf,50,c5),
HX_("__numVertices",3f,51,a4,9e),
HX_("__stride",39,8b,5f,b9),
HX_("__tempFloat32Array",b2,e6,d3,6c),
HX_("__usage",01,b6,8d,14),
HX_("__vertexSize",65,a5,a3,15),
HX_("dispose",9f,80,4c,bb),
HX_("uploadFromByteArray",e6,17,1b,ee),
HX_("uploadFromTypedArray",ba,7c,f4,d1),
HX_("uploadFromVector",2e,6f,6b,a8),
::String(null()) };
::hx::Class VertexBuffer3D_obj::__mClass;
void VertexBuffer3D_obj::__register()
{
VertexBuffer3D_obj _hx_dummy;
VertexBuffer3D_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("openfl.display3D.VertexBuffer3D",8e,20,03,ff);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(VertexBuffer3D_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< VertexBuffer3D_obj >;
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = VertexBuffer3D_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = VertexBuffer3D_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace openfl
} // end namespace display3D
| [
"[email protected]"
] | |
f7d85b6d2882e8aeef2e28cb45fdaaf97dc98911 | 4ff8262e3405fb570bd6ba32059564f4c9edaae7 | /1492/d/d.cpp | 117f7ad916039d386e2364800059ee519655f3a6 | [] | no_license | cppascalinux/codeforces | 2712b09d8f59921f9f989f18126ad5dd6ac86bb6 | 2c9f8202e00b1566f9c8b2b0a2660ff10f2c9627 | refs/heads/master | 2022-05-13T09:50:48.636366 | 2022-05-12T10:32:27 | 2022-05-12T10:32:27 | 179,010,908 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 837 | cpp | #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int p[200009],q[200009];
int main()
{
int a,b,k;
scanf("%d%d%d",&a,&b,&k);
b--;
if(k==0)
{
printf("Yes\n");
for(int i=1;i<=b+1;i++)
printf("1");
for(int i=1;i<=a;i++)
printf("0");
printf("\n");
for(int i=1;i<=b+1;i++)
printf("1");
for(int i=1;i<=a;i++)
printf("0");
return 0;
}
if(k>=a+b)
return printf("No"),0;
if(a==0||b==0)
return printf("No"),0;
p[1]=q[1]=1;
int n=a+b+1;
// printf("a:%d b:%d n:%d\n",a,b,n);
p[n]=0,q[n]=1;
p[n-k]=1,q[n-k]=0;
a--,b--;
for(int i=2;i<=n;i++)
if(i!=n-k&&i!=n)
{
if(a)
p[i]=q[i]=0,a--;
else
p[i]=q[i]=1,b--;
}
printf("Yes\n");
for(int i=1;i<=n;i++)
printf("%d",p[i]);
printf("\n");
for(int i=1;i<=n;i++)
printf("%d",q[i]);
return 0;
} | [
"[email protected]"
] | |
ad8905a813e349d4d4f616391fd8d01c473360e1 | 92ca0c6735c3a99bd9d76c9416a7cbf3417a3359 | /binary_task/binary_cnn/cnn/simd-functors.h | a971a42856a2172bce25d221d16c729ffb8e09b2 | [
"Apache-2.0"
] | permissive | zeeeyang/lexicon_rnn | c0d2eef9e57676e3dbf1438cef61aff931b0ab17 | 4d0185ccae50923049cf25e4ee02e6027a6d2148 | refs/heads/master | 2021-01-11T19:37:00.305847 | 2018-08-22T14:41:49 | 2018-08-22T14:41:49 | 69,038,619 | 37 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 7,356 | h | #ifndef CNN_XFUNCTORS_H
#define CNN_XFUNCTORS_H
#include <Eigen/Eigen>
#include "cnn/functors.h"
// these functors are implemented to exploit Eigen's internal logic for doing
// vectorized arithmetic. I'm putting them in a separate file since, if Eigen
// breaks backward compatibility by changing an internal interface, I want
// the necessary changes to be localized.
//
// to implement your own functor, you need to provide
// 1) operator() implemented on the scalar data type
// 2) packetOp implemented using vector ("packet") type
// 3) the functor_traits specialization for your functor
// that tells the compiler whether your architecture
// has vectorized support for the operations you need
// and an estimate of the cost of the operation
namespace cnn {
template<typename Scalar> struct const_add_op {
const_add_op(const Scalar& c) : c(c) {}
CNN_DEVICE_FUNC inline const Scalar operator() (const Scalar& x) const {
return c + x;
}
template <typename Packet>
CNN_DEVICE_FUNC inline Packet packetOp(const Packet& x) const {
using namespace Eigen::internal;
return padd(pset1<Packet>(c), x);
}
Scalar c;
};
}
namespace Eigen { namespace internal {
template<typename Scalar>
struct functor_traits<cnn::const_add_op<Scalar> > {
enum {
Cost = NumTraits<Scalar>::AddCost * 2,
PacketAccess = packet_traits<Scalar>::HasAdd
};
};
} }
namespace cnn {
template<typename Scalar> struct const_minus_op {
const_minus_op(const Scalar& c) : c(c) {}
CNN_DEVICE_FUNC inline const Scalar operator() (const Scalar& x) const {
return c - x;
}
template <typename Packet>
CNN_DEVICE_FUNC inline Packet packetOp(const Packet& x) const {
using namespace Eigen::internal;
return psub(pset1<Packet>(c), x);
}
Scalar c;
};
}
namespace Eigen { namespace internal {
template<typename Scalar>
struct functor_traits<cnn::const_minus_op<Scalar> > {
enum {
Cost = NumTraits<Scalar>::AddCost * 2,
PacketAccess = packet_traits<Scalar>::HasSub
};
};
} }
namespace cnn {
template<typename Scalar> struct scalar_logistic_sigmoid_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_logistic_sigmoid_op)
CNN_DEVICE_FUNC inline const Scalar operator() (const Scalar& x) const {
using std::exp;
const Scalar one = Scalar(1);
return one / (one + exp(-x));
}
template <typename Packet>
CNN_DEVICE_FUNC inline Packet packetOp(const Packet& x) const {
using namespace Eigen::internal;
const Packet one = pset1<Packet>(1);
return pdiv(one, padd(one, pexp(pnegate(x))));
}
};
}
namespace Eigen { namespace internal {
template<typename Scalar>
struct functor_traits<cnn::scalar_logistic_sigmoid_op<Scalar> > {
enum {
Cost = NumTraits<Scalar>::AddCost * 2 + NumTraits<Scalar>::MulCost * 6,
PacketAccess = packet_traits<Scalar>::HasAdd && packet_traits<Scalar>::HasDiv &&
packet_traits<Scalar>::HasNegate && packet_traits<Scalar>::HasExp
};
};
} }
namespace cnn {
template<typename Scalar> struct scalar_erf_backward_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_erf_backward_op)
CNN_DEVICE_FUNC inline const Scalar operator() (const Scalar& x, const Scalar& d) const {
using std::exp;
const Scalar sqrt_pi_over2(1.1283791670955125738961589);
return sqrt_pi_over2 * exp(-x * x) * d;
}
template <typename Packet>
CNN_DEVICE_FUNC inline Packet packetOp(const Packet& x, const Packet& d) const {
using namespace Eigen::internal;
const Packet sqrt_pi_over2 = pset1<Packet>(1.1283791670955125738961589);
return pmul(sqrt_pi_over2, pmul(pexp(pnegate(pmul(x, x))), d));
}
};
}
namespace Eigen { namespace internal {
template<typename Scalar>
struct functor_traits<cnn::scalar_erf_backward_op<Scalar> > {
enum {
Cost = NumTraits<Scalar>::MulCost * 8,
PacketAccess = packet_traits<Scalar>::HasExp && packet_traits<Scalar>::HasMul && packet_traits<Scalar>::HasNegate
};
};
} }
namespace cnn {
template<typename Scalar> struct scalar_logistic_sigmoid_backward_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_logistic_sigmoid_backward_op)
CNN_DEVICE_FUNC inline const Scalar operator() (const Scalar& t, const Scalar& d) const {
const Scalar one = Scalar(1);
return (one - t) * t * d;
}
template <typename Packet>
CNN_DEVICE_FUNC inline Packet packetOp(const Packet& t, const Packet& d) const {
using namespace Eigen::internal;
const Packet one = pset1<Packet>(1);
return pmul(psub(one, t), pmul(t, d));
}
};
}
namespace Eigen { namespace internal {
template<typename Scalar>
struct functor_traits<cnn::scalar_logistic_sigmoid_backward_op<Scalar> > {
enum {
Cost = NumTraits<Scalar>::AddCost + NumTraits<Scalar>::MulCost * 2,
PacketAccess = packet_traits<Scalar>::HasSub && packet_traits<Scalar>::HasMul
};
};
} }
namespace cnn {
template<typename Scalar> struct scalar_tanh_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_tanh_op)
CNN_DEVICE_FUNC inline const Scalar operator() (const Scalar& a) const { using std::tanh; return tanh(a); }
template <typename Packet>
CNN_DEVICE_FUNC inline Packet packetOp(const Packet& a) const { return Eigen::internal::ptanh(a); }
};
}
namespace Eigen { namespace internal {
template<typename Scalar>
struct functor_traits<cnn::scalar_tanh_op<Scalar> > {
enum {
Cost = 5 * NumTraits<Scalar>::MulCost,
PacketAccess = packet_traits<Scalar>::HasTanh
};
};
} }
namespace cnn {
template<typename Scalar> struct scalar_tanh_backward_op {
EIGEN_EMPTY_STRUCT_CTOR(scalar_tanh_backward_op)
CNN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& t, const Scalar& d) const { return (1 - t * t) * d; }
template<typename Packet>
CNN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& t, const Packet& d) const {
using namespace Eigen::internal;
const Packet one = pset1<Packet>(1);
return pmul(psub(one, pmul(t, t)), d);
}
};
}
namespace Eigen { namespace internal {
template<typename Scalar>
struct functor_traits<cnn::scalar_tanh_backward_op<Scalar> > {
enum {
Cost = NumTraits<Scalar>::AddCost + 2 * NumTraits<Scalar>::MulCost,
PacketAccess = packet_traits<Scalar>::HasSub && packet_traits<Scalar>::HasMul
};
};
}}
namespace cnn {
//this is slower than the dumb implementation, probably because of the pset operations
// which could be factored out into the constructor, but the Packet type isn't used
// then (and I think fixing this would be hard)
template<typename Scalar> struct scalar_nlsoftmax_backward_op {
scalar_nlsoftmax_backward_op(const Scalar& lz, const Scalar& err) : logz(lz), d(err) {}
CNN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator()(const Scalar& t) const {
using std::exp;
return exp(t - logz) * d;
}
template <typename Packet>
CNN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& t) const {
using namespace Eigen::internal;
const Packet lz = pset1<Packet>(logz);
const Packet dd = pset1<Packet>(d);
return pmul(pexp(psub(t, lz)), dd);
}
Scalar logz;
Scalar d;
};}
namespace Eigen { namespace internal {
template<typename Scalar>
struct functor_traits<cnn::scalar_nlsoftmax_backward_op<Scalar> > {
enum {
Cost = NumTraits<Scalar>::AddCost + 6 * NumTraits<Scalar>::MulCost,
PacketAccess = packet_traits<Scalar>::HasSub && packet_traits<Scalar>::HasExp
};
};
}}
#endif
| [
"[email protected]"
] | |
46a83bdde9ef3889cd20feec8d1eff07b3757d43 | 607a0c857428939d2a457e1ccfa04507873f6054 | /cpp/src/log.cpp | 868a9e2c5d23be6893588b6d247ac33b086e615b | [
"MIT",
"JSON"
] | permissive | billsioros/MMGP | 8928245f4711e22c40f8dfec715cd79db5463911 | d9cdd206e9baa4991ade1304dc4be53e1859b49d | refs/heads/master | 2022-07-10T13:51:37.843410 | 2018-11-17T15:20:53 | 2018-11-17T15:20:53 | 139,170,076 | 0 | 0 | NOASSERTION | 2018-11-17T15:19:36 | 2018-06-29T16:04:36 | C | UTF-8 | C++ | false | false | 1,864 | cpp |
#include "log.hpp"
#include <fstream> // std::ofstream
#include <string> // std::string
#include <iostream> // std::cerr
#include <unordered_map> // std::unordered_map
#include <chrono> // std::chrono
std::string Log::timestamp(const std::string& format)
{
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>
(
std::chrono::system_clock::now().time_since_epoch()
).count();
auto sec = static_cast<std::time_t>(ms / 1000);
std::tm time_info;
localtime_r(&sec, &time_info);
char buff[512];
snprintf(buff, sizeof(buff), format.c_str(),
1900 + time_info.tm_year, 1 + time_info.tm_mon, time_info.tm_mday,
time_info.tm_hour, time_info.tm_min, time_info.tm_sec, ms % 1000);
return std::string(buff);
}
Log::Log(const std::string& name)
:
info({ name + timestamp("%04d%02d%02d%02d%02d%02d%03lld") + ".log", false })
{
try
{
ofs.open(this->info.file, std::ios::trunc);
}
catch (std::exception& e)
{
std::cerr << "FatalLoggerError: " << e.what() << std::endl;
throw;
}
}
Log::~Log()
{
if (!info.dirty)
{
ofs.close(); std::remove(info.file.c_str());
}
}
void Log::operator()(Code code, const std::string& message)
{
const static std::unordered_map<Log::Code, std::string> prefixes =
{
{ Log::Code::Message, "<MSG>" },
{ Log::Code::Warning, "<WRN>" },
{ Log::Code::Error, "<ERR>" }
};
try
{
ofs
<< "[ " << timestamp("%04d-%02d-%02d %02d:%02d:%02d.%03lld") << " ]"
<< " : " << prefixes.at(code) << " : " << message << std::endl;
}
catch (std::exception& e)
{
std::cerr << "FatalLoggerError: " << e.what() << std::endl;
throw;
}
info.dirty |= (code != Log::Code::Message);
}
| [
"[email protected]"
] | |
26af44741b60e72a62490c6080b398e44aa8c772 | 2f10f807d3307b83293a521da600c02623cdda82 | /deps/boost/win/debug/include/boost/fiber/protected_fixedsize_stack.hpp | edf52fe177c9f930953924eb211498c9eef48b87 | [] | no_license | xpierrohk/dpt-rp1-cpp | 2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e | 643d053983fce3e6b099e2d3c9ab8387d0ea5a75 | refs/heads/master | 2021-05-23T08:19:48.823198 | 2019-07-26T17:35:28 | 2019-07-26T17:35:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 128 | hpp | version https://git-lfs.github.com/spec/v1
oid sha256:82670e097dbba4f2bf64ba7f459383383f601f93b226bcb2a3595934c2318348
size 739
| [
"[email protected]"
] | |
6a0537a240d08475acc108a7c2f1ca2122ba09e7 | 33392bbfbc4abd42b0c67843c7c6ba9e0692f845 | /dsp/L1/tests/hw/2dfft/fixed/impulse_test/complex_impulse/src/main_2d_fft_test.cpp | 81353a54d900acd0e774f52a80adc33653d9a5bb | [
"Apache-2.0",
"OFL-1.1",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"BSD-2-Clause",
"MIT"
] | permissive | Xilinx/Vitis_Libraries | bad9474bf099ed288418430f695572418c87bc29 | 2e6c66f83ee6ad21a7c4f20d6456754c8e522995 | refs/heads/main | 2023-07-20T09:01:16.129113 | 2023-06-08T08:18:19 | 2023-06-08T08:18:19 | 210,433,135 | 785 | 371 | Apache-2.0 | 2023-07-06T21:35:46 | 2019-09-23T19:13:46 | C++ | UTF-8 | C++ | false | false | 2,953 | cpp | /*
* Copyright 2019 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.
*/
//================================== End Lic =================================================
#define TEST_2D_FFT_
#ifdef TEST_2D_FFT_
#ifndef __SYNTHESIS__
#define _DEBUG_TYPES
#endif
#include <math.h>
#include <string>
#include <assert.h>
#include <stdio.h>
#include "top_2d_fft_test.hpp"
#include "mVerificationUtlityFunctions.hpp"
#include "vitis_fft/hls_ssr_fft_2d_modeling_utilities.hpp"
#include "vt_fft.hpp"
int main(int argc, char** argv) {
// 2d input matrix
T_elemType l_inMat[k_fftKernelSize][k_fftKernelSize];
T_outType l_outMat[k_fftKernelSize][k_fftKernelSize];
T_outType l_data2d_golden[k_fftKernelSize][k_fftKernelSize];
// init input matrix with complex impulse
for (int r = 0; r < k_fftKernelSize; ++r) {
for (int c = 0; c < k_fftKernelSize; ++c) {
if (r == 0 && c == 0)
l_inMat[r][c] = T_compleFloat(1, 1);
else
l_inMat[r][c] = T_compleFloat(0, 0);
}
}
// Wide Stream for reading and streaming a 2-d matrix
MemWideIFStreamTypeIn l_matToStream("matrixToStreaming");
MemWideIFStreamTypeOut fftOutputStream("fftOutputStream");
// Pass same data stream multiple times to measure the II correctly
for (int runs = 0; runs < 5; ++runs) {
stream2DMatrix<k_fftKernelSize, k_fftKernelSize, k_memWidth, T_elemType, MemWideIFTypeIn>(l_inMat,
l_matToStream);
top_fft2d(l_matToStream, fftOutputStream);
printMatStream<k_fftKernelSize, k_fftKernelSize, k_memWidth, MemWideIFTypeOut>(
fftOutputStream, "2D FFT Output Natural Order...");
streamToMatrix<k_fftKernelSize, k_fftKernelSize, k_memWidth, T_outType>(fftOutputStream, l_outMat);
} // runs loop
T_outType golden_result = T_elemType(1, 1);
for (int r = 0; r < k_fftKernelSize; ++r) {
for (int c = 0; c < k_fftKernelSize; ++c) {
if (golden_result != l_outMat[r][c]) return 1;
}
}
std::cout << "================================================================" << std::endl;
std::cout << "---------------------Impulse test Passed Successfully." << std::endl;
std::cout << "================================================================" << std::endl;
return 0;
}
#endif
| [
"[email protected]"
] | |
75770aa884006688fd1ea425d27fdcfafc2a1d46 | 4b0c57dddf8bd98c021e0967b5d94563d15372e1 | /MEPATNtuple/interface/ProbsForEPD.hh | a3c2cd8779657ca237de2ce4018f21e71ed9a952 | [] | no_license | aperloff/TAMUWW | fea6ed0066f3f2cef4d44c525ee843c6234460ba | c18e4b7822076bf74ee919509a6bd1f3cf780e11 | refs/heads/master | 2021-01-21T14:12:34.813887 | 2018-07-23T04:59:40 | 2018-07-23T04:59:40 | 10,922,954 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,404 | hh | #ifndef PROBSFOREPD_HH
#define PROBSFOREPD_HH
#include <string>
// Class for EPD is used in the EPD computation and contains as many members
// as elements in DEFS::EP::type and in the same order. Basically each
// matrix element probability has a member in this group.
class ProbsForEPD {
public:
// Default C'tor
ProbsForEPD();
// The set with initial value.
ProbsForEPD(double i);
// Make sure we have a quick assignment c'tor
ProbsForEPD(double , double , double ,
double , double , double ,
double , double , double ,
double , double , double ,
double , double , double );
// The multiplication operator
ProbsForEPD operator * (const ProbsForEPD & ) const;
// The multiplication assignement
ProbsForEPD& operator *=(const ProbsForEPD & );
// The members of the
double wh ; // for whatever mass we want
double hww ; // for whatever mass we want
double schan ;
double tchan ;
double tchan2 ;
double tt ;
double wlight ;
double zlight ;
double wbb ;
double wc ;
double wgg ;
double ww ;
double wz ;
double zz ;
double qcd ;
// This just print all the elements to screen
void show(std::string);
// This just prints how to call the
std::string getStringConstructor();
// This divides each member to the sum of all members
void normalize();
};
#endif
| [
""
] | |
d7632aa057b768704a07bc2c981570242b784fb8 | cee755aeca7e9f9fda66aa069e99c77c718542b7 | /Code/IMGF.ThirdParty/DXSDK/DXF/DXSDK/samples/Multimedia/DirectInput/DIConfig/ifrmwrk.h | 4425ac1affc57bc240a5cf702354f41ca5a38210 | [] | no_license | MexUK/IMGF | ca7dcd2637c3f5d017efcd96a38b25e50920d9f2 | 4efd904db678510b99906ed3e0d576f4332ad50e | refs/heads/master | 2021-09-14T18:31:58.255531 | 2018-02-27T06:03:53 | 2018-02-27T06:03:53 | 75,762,606 | 10 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 936 | h | //-----------------------------------------------------------------------------
// File: ifrmwrk.h
//
// Desc: Contains the interface definition for the UI framework.
//
// Copyright (C) 1999-2001 Microsoft Corporation. All Rights Reserved.
//-----------------------------------------------------------------------------
#ifndef _IFRMWRK_H
#define _IFRMWRK_H
class IDirectInputActionFramework : public IUnknown
{
public:
//IUnknown fns
STDMETHOD (QueryInterface) (REFIID iid, LPVOID *ppv) PURE;
STDMETHOD_(ULONG, AddRef) () PURE;
STDMETHOD_(ULONG, Release) () PURE;
//own fns
STDMETHOD (ConfigureDevices) (LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
LPDICONFIGUREDEVICESPARAMSW lpdiCDParams,
DWORD dwFlags,
LPVOID pvRefData
) PURE;
};
#endif // _IFRMWRK_H
| [
"[email protected]"
] | |
1a458f12cb6da40f88aeb3eb4b12d64e3e07fc3c | 65f3e6b0c62bd22e08a5ef447bef6a6c86e6cd06 | /ouzel/graphics/ShaderResource.hpp | e8017d1a4b71cc6f670417cfb8e0bbbdba3e4d02 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | whztt07/ouzel | f2dfb9f3e6d12d54edf3b5a724ebfb8a04f0b555 | f9a7d6dedd640ca4db429c6c62a72aec5332661c | refs/heads/master | 2020-03-24T22:37:44.426088 | 2018-07-25T08:37:29 | 2018-07-25T08:37:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,242 | hpp | // Copyright 2015-2018 Elviss Strazdins. All rights reserved.
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include "graphics/RenderResource.hpp"
#include "graphics/Shader.hpp"
#include "math/Vector3.hpp"
#include "math/Vector4.hpp"
#include "math/Matrix4.hpp"
namespace ouzel
{
namespace graphics
{
class RenderDevice;
class ShaderResource: public RenderResource
{
public:
virtual ~ShaderResource();
virtual void init(const std::vector<uint8_t>& newFragmentShader,
const std::vector<uint8_t>& newVertexShader,
const std::set<Vertex::Attribute::Usage>& newVertexAttributes,
const std::vector<Shader::ConstantInfo>& newFragmentShaderConstantInfo,
const std::vector<Shader::ConstantInfo>& newVertexShaderConstantInfo,
uint32_t newFragmentShaderDataAlignment = 0,
uint32_t newVertexShaderDataAlignment = 0,
const std::string& newFragmentShaderFunction = "",
const std::string& newVertexShaderFunction = "");
inline const std::set<Vertex::Attribute::Usage>& getVertexAttributes() const { return vertexAttributes; }
inline uint32_t getFragmentShaderAlignment() const { return fragmentShaderAlignment; }
inline uint32_t getVertexShaderAlignment() const { return vertexShaderAlignment; }
protected:
ShaderResource(RenderDevice& initRenderDevice);
RenderDevice& renderDevice;
std::set<Vertex::Attribute::Usage> vertexAttributes;
std::vector<uint8_t> fragmentShaderData;
std::vector<uint8_t> vertexShaderData;
std::string fragmentShaderFunction;
std::string vertexShaderFunction;
std::vector<Shader::ConstantInfo> fragmentShaderConstantInfo;
uint32_t fragmentShaderAlignment = 0;
std::vector<Shader::ConstantInfo> vertexShaderConstantInfo;
uint32_t vertexShaderAlignment = 0;
};
} // namespace graphics
} // namespace ouzel
| [
"[email protected]"
] | |
4988dd5d3fa1201d357b0b7658b9b86163cf4cb9 | 39ab815dfdbab9628ede8ec3b4aedb5da3fd456a | /aql/benchmark/lib_13/class_7.cpp | 8ab09b761acd8392f9651032bd1dd07f0e6540fa | [
"MIT"
] | permissive | menify/sandbox | c03b1bf24c1527b47eb473f1acc433f17bfb1d4f | 32166c71044f0d5b414335b2b6559adc571f568c | refs/heads/master | 2016-09-05T21:46:53.369065 | 2015-04-20T06:35:27 | 2015-04-20T06:35:27 | 25,891,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 308 | cpp | #include "class_7.h"
#include "class_9.h"
#include "class_6.h"
#include "class_4.h"
#include "class_5.h"
#include "class_2.h"
#include <lib_9/class_3.h>
#include <lib_12/class_9.h>
#include <lib_5/class_8.h>
#include <lib_0/class_4.h>
#include <lib_2/class_0.h>
class_7::class_7() {}
class_7::~class_7() {}
| [
"menify@a28edc5c-ec3e-0410-a3da-1b30b3a8704b"
] | menify@a28edc5c-ec3e-0410-a3da-1b30b3a8704b |
b839c97a06850539779da084a0c793338bb9f087 | b5347394eaa1030ee38f0590340d32f5700bc39d | /src/Base/StringTable.cpp | 7db6fb1d745608386e2b9b75d153f5c95cba527a | [
"MIT"
] | permissive | ZE4D/finch | e45b35b2e41d409028a4b4e2e500dd0e413cf6af | 7d934caa2c1e98faff5775228c1c98452d940ae1 | refs/heads/master | 2023-03-22T09:51:37.444433 | 2020-08-04T20:49:56 | 2020-08-04T20:49:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 681 | cpp | #include "StringTable.h"
namespace Finch
{
StringId StringTable::Add(const String & string)
{
// See if the string is already in the table. We must ensure each string
// only appears once in the table so that we can reliably compare
// strings just by index.
// TODO(bob): This is O(n). Optimize using a hashtable.
for (int i = 0; i < mStrings.Count(); i++)
{
if (mStrings[i] == string) return i;
}
// Not in the table, so add it.
mStrings.Add(string);
return mStrings.Count() - 1;
}
String StringTable::Find(StringId id)
{
return mStrings[id];
}
}
| [
"[email protected]"
] | |
e1d7b07891f16ed5f7d8804abb6ab0be35d7c893 | 94a748b9ec43c531dcce671cbb23801c8260c08d | /testprograms/SquaredSubsets.cpp | c52e681e0aeadcf629975f2a93722ba6541c2f28 | [] | no_license | Shubham28/TopCoder | 091948352bcfe2088cdce9a1d82ddec2cf38cfe9 | 25b6d34c391b8b79094bd0d971d86c2af943f4d3 | refs/heads/master | 2021-01-19T09:44:00.576213 | 2013-05-23T12:54:30 | 2013-05-23T12:54:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,126 | cpp | #include <vector>
#include <map>
#include <queue>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <set>
#include <numeric>
#define FOR(A,B,C) for(int A=B;A<C;A++)
#define EFOR(A,B,C) for(int A=B;A<=C;A++)
#define RFOR(A,B,C) for(int A=B;A>=C;A--)
#define PB(A,B) A.push_back(B);
#define SORT(A) sort( A.begin(),A.end() )
#define ALL(A) A.begin(),A.end()
#define MEM(A,B) memset(A,B,sizeof(A))
#define VI vector<int>
#define VS vector<string>
#define VD vector<double>
#define VB vector<bool>
#define SZ(A) int(A.size())
#define LL long long
using namespace std;
class SquaredSubsets {
public:
long long countSubsets(int, vector <int>, vector <int>);
};
long long SquaredSubsets::countSubsets(int n, vector <int> x, vector <int> y) {
}
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit 2.1.8 (beta) modified by pivanof
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool KawigiEdit_RunTest(int testNum, int p0, vector <int> p1, vector <int> p2, bool hasAnswer, long long p3) {
cout << "Test " << testNum << ": [" << p0 << "," << "{";
for (int i = 0; int(p1.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << p1[i];
}
cout << "}" << "," << "{";
for (int i = 0; int(p2.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << p2[i];
}
cout << "}";
cout << "]" << endl;
SquaredSubsets *obj;
long long answer;
obj = new SquaredSubsets();
clock_t startTime = clock();
answer = obj->countSubsets(p0, p1, p2);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p3 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p3;
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
all_right = true;
int p0;
vector <int> p1;
vector <int> p2;
long long p3;
{
// ----- test 0 -----
p0 = 5;
int t1[] = {-5,0,5};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
int t2[] = {0,0,0};
p2.assign(t2, t2 + sizeof(t2) / sizeof(t2[0]));
p3 = 5ll;
all_right = KawigiEdit_RunTest(0, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 1 -----
p0 = 10;
int t1[] = {-5,0,5};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
int t2[] = {0,0,0};
p2.assign(t2, t2 + sizeof(t2) / sizeof(t2[0]));
p3 = 5ll;
all_right = KawigiEdit_RunTest(1, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 2 -----
p0 = 100000000;
int t1[] = {-1,-1,-1,0,1,1,1};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
int t2[] = {-1,0,1,1,-1,0,1};
p2.assign(t2, t2 + sizeof(t2) / sizeof(t2[0]));
p3 = 21ll;
all_right = KawigiEdit_RunTest(2, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 3 -----
p0 = 5;
int t1[] = {5,3,6,2,1,6,4,4,7,-1,-4,-7,2,-2,0};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
int t2[] = {0,-1,8,-5,2,5,-8,8,-6,4,3,2,7,3,5};
p2.assign(t2, t2 + sizeof(t2) / sizeof(t2[0]));
p3 = 66ll;
all_right = KawigiEdit_RunTest(3, p0, p1, p2, true, p3) && all_right;
// ------------------
}
{
// ----- test 4 -----
p0 = 1;
int t1[] = {-1,0};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
int t2[] = {0,0};
p2.assign(t2, t2 + sizeof(t2) / sizeof(t2[0]));
p3 = 3ll;
all_right = KawigiEdit_RunTest(4, p0, p1, p2, true, p3) && all_right;
// ------------------
}
if (all_right) {
cout << "You're a stud (at least on the example cases)!" << endl;
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
// Author: Shubham Gupta
//Powered by KawigiEdit 2.1.8 (beta) modified by pivanof!
| [
"[email protected]"
] | |
afd6afa5446afd16c3a2bf425a39b948fc25394b | 0962d844db92aae1303061c8531a063bd68094e3 | /platforms/esp/32/clockless_block_esp32 copie 3.h | 2cde513e0d0a57f8cea0e23c9abf6041ff193e89 | [
"MIT"
] | permissive | hpwit/fastled2 | 4c962a1fac9dfe72299f9cb9ce6a571d9316af7b | c16ae7ef938f150d1b8b27eb962f00bc448ddfa6 | refs/heads/master | 2020-03-30T10:57:42.277767 | 2019-01-27T18:16:45 | 2019-01-27T18:16:45 | 151,146,134 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,198 | h | #ifndef __INC_CLOCKLESS_BLOCK_ESP8266_H
#define __INC_CLOCKLESS_BLOCK_ESP8266_H
#define FASTLED_HAS_BLOCKLESS 1
#define PORT_MASK4 (((1<<USED_LANES_FIRST)-1) & 0x0000FFFFL) //on dit que l'ion va en faire 10
#define FIX_BITS(bits) ( ((bits & 0xE0L) << 17) | ((bits & 0x1FL)<<2) )
#define FIX_BITS2(bits) ( ((bits & 0xFF00L)<<4) | ((bits & 0xE0L) << 15) | ((bits & 0x1EL)<<1) | (bits & 0x1L) )
#define PORT_MASK3 (((1<<USED_LANES_SECOND )-1) & 0x0000FFFFL)
#define PORT_MASK2 FIX_BITS(PORT_MASK3)
#define MIN(X,Y) (((X)<(Y)) ? (X):(Y))
//attempted to use other/more pins for the port
// #define USED_LANES (MIN(LANES,33))
#define USED_LANES (MIN(LANES,16))
#define USED_LANES_FIRST ( (LANES)>8 ? (8) :(LANES) )
#define USED_LANES_SECOND ( (LANES)>8 ? (LANES-8) :(0) )
#define REAL_FIRST_PIN 12
// #define LAST_PIN (12 + USED_LANES - 1)
#define LAST_PIN 35
#define SUBLANES 1<<LANES
//#define PORT_MASK_TOTAL PORT_MAX_T
//#define PORT_MASK PORT_MAX_T
#define PORT_MASK_TOTAL ( FIX_BITS2((1<<LANES)-1) )
#include "driver/gpio.h"
#include "driver/rtc_io.h"
FASTLED_NAMESPACE_BEGIN
#ifdef FASTLED_DEBUG_COUNT_FRAME_RETRIES
extern uint32_t _frame_cnt;
extern uint32_t _retry_cnt;
#endif
template <uint8_t LANES, int FIRST_PIN, int T1, int T2, int T3, EOrder RGB_ORDER = GRB, uint32_t PORT_MASK=0,int XTRA0 = 0, bool FLIP = false, int WAIT_TIME = 50>
class InlineBlockClocklessController : public CPixelLEDController<RGB_ORDER, LANES, PORT_MASK> {
typedef typename FastPin<FIRST_PIN>::port_ptr_t data_ptr_t;
typedef typename FastPin<FIRST_PIN>::port_t data_t;
PixelController<RGB_ORDER,LANES,PORT_MASK> *local_pixels = NULL;
data_t mPinMask;
data_ptr_t mPort;
CMinWait<WAIT_TIME> mWait;
TaskHandle_t handleRGBTHandle = NULL;
TaskHandle_t userRBGHandle = NULL;
public:
virtual int size() { return CLEDController::size() * LANES; }
void static handleRGB(void *pvParameters)
{
InlineBlockClocklessController* c = static_cast<InlineBlockClocklessController*>(pvParameters);
const TickType_t xMaxBlockTime = pdMS_TO_TICKS( 500 );
// -- Run forever...
for(;;) {
// -- Wait for the trigger
ulTaskNotifyTake(pdTRUE,portMAX_DELAY);
// -- Do the show (synchronously)
// noInterrupts();
// FastLED.delay(10);
// Serial.printf("on affiche");
c->showRGBInternal(*(c->local_pixels));
// FastLED.delay(10);
//interrupts();
// -- Notify the calling task
xTaskNotifyGive(c->userRBGHandle);
}
}
virtual void showPixels(PixelController<RGB_ORDER, LANES, PORT_MASK> & pixels) {
// mWait.wait();
local_pixels=&pixels;
// printf("core %d\n",xPortGetCoreID());
/*if(xPortGetCoreID()==0)
//if(false)
{
xTaskCreatePinnedToCore(handleRGB, "FastLEDshowRGB", 10000,(void*)this,2, &handleRGBTHandle, 1);
if (userRBGHandle == 0) {
const TickType_t xMaxBlockTime = pdMS_TO_TICKS( 200 );
// -- Store the handle of the current task, so that the show task can
// notify it when it's done
//noInterrupts();
userRBGHandle = xTaskGetCurrentTaskHandle();
// -- Trigger the show task
xTaskNotifyGive(handleRGBTHandle);
// -- Wait to be notified that it's done
ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS( 100 ));//portMAX_DELAY);
//delay(100);
//interrupts();
vTaskDelete(handleRGBTHandle);
userRBGHandle = 0;}
}
else
{*/
//Serial.println("ini");
showRGBInternal(pixels);
// }
// ets_intr_lock();
/*uint32_t clocks = */
uint32_t port;
/* if(PORT_MASK==0)
port=PORT_MASK_TOTAL;
else
port=PORT_MASK;
uint32_t porti=port;
for(int i=0;i<32;i++)
{
// Serial.printf("i:%d port:%ld result:%d\n",i,porti,porti&0x1);
if( (porti & 0x1)>0 )
{
pinMode(i,OUTPUT);
}
porti=porti>>1;
}*/
int cnt=FASTLED_INTERRUPT_RETRY_COUNT;
//showRGB32();
//Serial.printf(" one demarre %d\n",FASTLED_INTERRUPT_RETRY_COUNT);
/* while(!showRGBInternal(pixels) && cnt--) {
//Serial.printf(" one passe là retry %d\n",FASTLED_INTERRUPT_RETRY_COUNT);
ets_intr_unlock();
#ifdef FASTLED_DEBUG_COUNT_FRAME_RETRIES
_retry_cnt++;
#endif
delayMicroseconds(WAIT_TIME * 10);
ets_intr_lock();
}*/
// Serial.printf(" one fini\n");
/* porti=port;
for(int i=0;i<32;i++)
{
//Serial.printf("i:%d port:%ld result:%d\n",i,porti,porti&0x1);
if( (porti & 0x1)>0 )
{
pinMode(i,INPUT);
}
porti=porti>>1;
}*/
// ets_intr_unlock();
// delayMicroseconds(WAIT_TIME * 10);
// ets_intr_unlock();
// #if FASTLED_ALLOW_INTTERUPTS == 0
// Adjust the timer
// long microsTaken = CLKS_TO_MICROS(clocks);
// MS_COUNTER += (1 + (microsTaken / 1000));
// #endif
// mWait.mark();
//delayMicroseconds(WAIT_TIME *20);
}
template<int PIN> static void initPin() {
if(PIN >= 0 && PIN <= LAST_PIN) {
_ESPPIN<PIN, 1<<(PIN & 0xFF)>::setOutput();
// FastPin<PIN>::setOutput();
}
}
virtual void init() {
// Only supportd on pins 12-15
// SZG: This probably won't work (check pins definitions in fastpin_esp32)
/* void (* funcs[])() ={initPin<12>,initPin<13>,initPin<14>,initPin<15>,initPin<16>,initPin<17>,initPin<18>,initPin<19>,initPin<0>,initPin<2>,initPin<3>,initPin<4>,initPin<5>,initPin<21>,initPin<22>,initPin<23>};
// void (* funcs[])() ={initPin<12>, initPin<13>, initPin<14>, initPin<15>, initPin<4>, initPin<5>};
for (uint8_t i = 0; i < USED_LANES; ++i) {
funcs[i]();
}*/
uint32_t port;
if(PORT_MASK==0)
port=PORT_MASK_TOTAL;
else
port=PORT_MASK;
uint32_t porti=port;
/* for(int i=0;i<32;i++)
{
//Serial.printf("i:%d port:%ld result:%d\n",i,porti,porti&0x1);
if( (porti & 0x1)>0 )
{
pinMode(i,OUTPUT);
}
porti=porti>>1;
}
mPinMask = FastPin<FIRST_PIN>::mask();
mPort = FastPin<FIRST_PIN>::port();*/
pinMode(14,OUTPUT);
// Serial.print("Mask is "); Serial.println(PORT_MASK);
}
virtual uint16_t getMaxRefreshRate() const { return 400; }
typedef union {
uint8_t bytes[16];
uint16_t shorts[8];
uint32_t raw[2];
} Lines;
#define ESP_ADJUST 0 // (2*(F_CPU/24000000))
#define ESP_ADJUST2 0
template<int BITS,int PX> __attribute__ ((always_inline)) inline static void writeBits(register uint32_t & last_mark, register Lines & b, PixelController<RGB_ORDER, LANES, PORT_MASK> &pixels) { // , register uint32_t & b2) {
Lines b2=b ;
//Lines b4=b3;
transpose16x1_noinline(b.bytes,b2.shorts);
//transpose8x1_noinline(b3.bytes,b4.bytes);
uint32_t port=0;
register uint8_t d = pixels.template getd<PX>(pixels);
register uint8_t scale = pixels.template getscale<PX>(pixels);
if(PORT_MASK==0)
port=PORT_MASK_TOTAL ;
else
port=PORT_MASK;
//last_mark = __clock_cycles();
for(register uint32_t i = 0; i < 8; i++) { //USED_LANES
uint32_t nword=0;
uint32_t maskK=port;
uint32_t ert=0;
// if(PORT_MASK>0)
for (register uint32_t j=0;j< LANES;j++)
{
if((uint32_t)(~b2.shorts[7-i]) & (1<<j)) ///if(ert & 1) //on a une 1 a ecrire
{
nword= nword | ((maskK&(maskK-1) ) ^ maskK) ;
}
//ert=ert>>1;
maskK=maskK&(maskK-1);
}
// else
//nword = FIX_BITS2 ((uint32_t)(~b2.shorts[7-i])) & port;
//ert=(uint32_t)(~b2.shorts[7-i]);
//added by yves
//uint32_t nword = fixbit((uint32_t)(~b2.shorts[7-i]),PORT_MASK,(uint32_t)LANES);
while((__clock_cycles() - last_mark) < (T1+T2+T3));
last_mark = __clock_cycles();
///*FastPin<FIRST_PIN>::sport() = (PORT_MASK << REAL_FIRST_PIN ) | ( PORT_MASK2 );
*FastPin<FIRST_PIN>::sport() = port ;
//GPIO.out_w1ts=port;
// __asm__ __volatile__("nop;nop;nop;nop;nop;nop;nop;");
// uint32_t nword = ( ((uint32_t)(~b2.bytes[7-i]) & PORT_MASK) << REAL_FIRST_PIN ) | (FIX_BITS( (uint32_t)(~b4.bytes[7-i]) ) & PORT_MASK2) ; //((uint32_t)(~b4.bytes[7-i]) & PORT_MASK2) << 21 );//
//uint32_t nword = ( ( (uint32_t)(~b2.bytes[7-i]) << REAL_FIRST_PIN ) | FIX_BITS((uint32_t)(~b4.bytes[7-i])) ) & PORT_MASK_TOTAL ;
//uint32_t nword = FIX_BITS2 ((uint32_t)(~b2.shorts[7-i])) & PORT_MASK;
// Serial.printf("bit %#010x:\n",FIX_BITS2 ((uint32_t)(~b2.shorts[7-i])));
// if(PORT_MASK>0)
/* for (register uint32_t j=0;j< LANES;j++)
{
if((uint32_t)(~b2.shorts[7-i]) & (1<<j)) ///if(ert & 1) //on a une 1 a ecrire
{
nword= nword | ((maskK&(maskK-1) ) ^ maskK) ;
}
//ert=ert>>1;
maskK=maskK&(maskK-1);
}`*/
// else
// nword = FIX_BITS2 ((uint32_t)(~b2.shorts[7-i])) & port;
while((__clock_cycles() - last_mark) < (T1-6));
*FastPin<FIRST_PIN>::cport() = nword;
if(i<LANES)
b.bytes[i] = pixels.template loadAndScale<PX>(pixels,i,d,scale);
if(8+i<LANES)
b.bytes[i+8] = pixels.template loadAndScale<PX>(pixels,i+8,d,scale);
// GPIO.out_w1tc = nword;
//__asm__ __volatile__("nop;nop;nop;nop;nop;nop;nop;");
while((__clock_cycles() - last_mark) < (T1+T2));
*FastPin<FIRST_PIN>::cport() = port;
//*FastPin<FIRST_PIN>::cport() = (PORT_MASK << REAL_FIRST_PIN ) | ( PORT_MASK2 );
//GPIO.out_w1tc = port;
// __asm__ __volatile__("nop;nop;nop;nop;nop;nop;nop;");
/* if(i<USED_LANES_FIRST)
b.bytes[i] = pixels.template loadAndScale<PX>(pixels,i,d,scale);
if (i<USED_LANES_SECOND)
b.bytes[i+8] = pixels.template loadAndScale<PX>(pixels,i+8,d,scale);
`*/
//mettre le code pour moins de 8 lines et 16 lines
// b.bytes[i] = pixels.template loadAndScale<PX>(pixels,i,d,scale);
}
/* for(register uint32_t i = 0; i < LANES; i++) {
b.bytes[i] = pixels.template loadAndScale<PX>(pixels,i,d,scale);
}*/
/*for(register uint32_t i = 0; i < USED_LANES_FIRST; i++) {
b.bytes[i] = pixels.template loadAndScale<PX>(pixels,i,d,scale);
}
for(int i = 0; i < USED_LANES_SECOND; i++) {
b3.bytes[i] = pixels.template loadAndScale<PX>(pixels,i+8,d,scale);
}*/
/*for(register uint32_t i = USED_LANES; i < 8; i++) {
while((__clock_cycles() - last_mark) < (T1+T2+T3));
last_mark = __clock_cycles();
*FastPin<FIRST_PIN>::sport() = PORT_MASK << REAL_FIRST_PIN;
uint32_t nword = ((uint32_t)(~b2.bytes[7-i]) & PORT_MASK) << REAL_FIRST_PIN;
while((__clock_cycles() - last_mark) < (T1-6));
*FastPin<FIRST_PIN>::cport() = nword;
while((__clock_cycles() - last_mark) < (T1+T2));
*FastPin<FIRST_PIN>::cport() = PORT_MASK << REAL_FIRST_PIN;
}*/
}
// This method is made static to force making register Y available to use for data on AVR - if the method is non-static, then
// gcc will use register Y for the this pointer.
static uint32_t ICACHE_RAM_ATTR showRGBInternal(PixelController<RGB_ORDER, LANES, PORT_MASK> &allpixels) {
// Setup the pixel controller and load/scale the first byte
Lines b0,b1;
uint32_t port;
//uint32_t port;
if(PORT_MASK==0)
port=PORT_MASK_TOTAL;
else
port=PORT_MASK;
/*
uint32_t porti=port;
for(int i=0;i<32;i++)
{
//Serial.printf("i:%d port:%ld result:%d\n",i,porti,porti&0x1);
if( (porti & 0x1)>0 )
{
pinMode(i,OUTPUT);
}
porti=porti>>1;
}
mPinMask = FastPin<FIRST_PIN>::mask();
mPort = FastPin<FIRST_PIN>::port();*/
for(int i = 0; i < LANES; i++) {
//if(i<USED_LANES_FIRST)
b0.bytes[i] = allpixels.loadAndScale0(i);
//if (i<USED_LANES_SECOND)
// b0.bytes[i+8] = allpixels.loadAndScale0(i+8);
}
allpixels.preStepFirstByteDithering();
//ets_intr_lock();
uint32_t _start = __clock_cycles();
uint32_t last_mark = _start;
/* *FastPin<FIRST_PIN>::cport() = port;
while((__clock_cycles() - last_mark) < (NS(500000)));
_start = __clock_cycles();
last_mark = _start;*/
portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
portENTER_CRITICAL(&mux);
while((__clock_cycles() - last_mark) < (NS(500000)));
_start = __clock_cycles();
last_mark = _start;
//gpio_pulldown_en(GPIO_NUM_12 );
//gpio_set_pull_mode(GPIO_NUM_12, GPIO_FLOATING);
uint32_t porti=PORT_MASK;
for(int i=0;i<32;i++)
{
//Serial.printf("i:%d port:%ld result:%d\n",i,porti,porti&0x1);
if( (porti & 0x1)>0 )
{
gpio_set_direction((gpio_num_t)i, GPIO_MODE_OUTPUT_OD );
pinMode(i,OUTPUT);
}
porti=porti>>1;
}
/* gpio_set_direction(GPIO_NUM_12, GPIO_MODE_OUTPUT_OD );
//pinMode(13,OUTPUT);
pinMode(12,OUTPUT);
gpio_set_direction(GPIO_NUM_13, GPIO_MODE_OUTPUT_OD );
pinMode(13,OUTPUT);*/
//start
/* writeBits<8+XTRA0,1>(last_mark, b0,allpixels);
//last_mark = __clock_cycles();
// Write second byte, read 3rd byte
writeBits<8+XTRA0,2>(last_mark, b0, allpixels);
//last_mark = __clock_cycles();
// allpixels.advanceData();
// Write third byte
writeBits<8+XTRA0,0>(last_mark, b0,allpixels);*/
//on tente de clearer les ports
/* if(PORT_MASK==0)
port=PORT_MASK_TOTAL ;
else
port=PORT_MASK;
*FastPin<FIRST_PIN>::sport() = port;
ets_intr_unlock();
while((__clock_cycles() - last_mark) < (NS(500000)));
_start = __clock_cycles();
last_mark = _start;
_start = __clock_cycles();
last_mark = _start;*/
/*
for(int i = 0; i < LANES; i++) {
//if(i<USED_LANES_FIRST)
b0.bytes[i] = allpixels.loadAndScale0(i);
//if (i<USED_LANES_SECOND)
// b0.bytes[i+8] = allpixels.loadAndScale0(i+8);
}*/
//end
//ets_intr_lock();
while(allpixels.has(1)) {
// Write first byte, read next byte
//portDISABLE_INTERRUPTS();
writeBits<16+XTRA0,1>(last_mark, b0,allpixels);
//last_mark = __clock_cycles();
// Write second byte, read 3rd byte
writeBits<16+XTRA0,2>(last_mark, b0, allpixels);
//last_mark = __clock_cycles();
allpixels.advanceData();
// Write third byte
writeBits<16+XTRA0,0>(last_mark, b0,allpixels);
//portENABLE_INTERRUPTS();
#if (FASTLED_ALLOW_INTERRUPTS == 1)
ets_intr_unlock();
#endif
allpixels.stepDithering();
#if (FASTLED_ALLOW_INTERRUPTS == 1)
ets_intr_lock();
// if interrupts took longer than 45µs, punt on the current frame
if((int32_t)(__clock_cycles()-last_mark) > 0) {
if((int32_t)(__clock_cycles()-last_mark) > (T1+T2+T3+((WAIT_TIME-INTERRUPT_THRESHOLD)*CLKS_PER_US))) { ets_intr_unlock(); return 0; }
}
#endif
};
//last_mark=__clock_cycles();
//il faut mettre à zero odt 50micros seconds
/* if(PORT_MASK==0)
port=PORT_MASK_TOTAL ;
else
port=PORT_MASK;
*FastPin<FIRST_PIN>::cport() = port;
while((__clock_cycles() - last_mark) < (NS(50000)));*/
//*FastPin<FIRST_PIN>::cport() = port;
//ets_intr_unlock();
#ifdef FASTLED_DEBUG_COUNT_FRAME_RETRIES
_frame_cnt++;
#endif
porti=PORT_MASK;
for(int i=0;i<32;i++)
{
//Serial.printf("i:%d port:%ld result:%d\n",i,porti,porti&0x1);
if( (porti & 0x1)>0 )
{
pinMode(i,INPUT);
gpio_pulldown_en((gpio_num_t)i );
gpio_set_pull_mode((gpio_num_t)i, GPIO_FLOATING);
gpio_set_direction((gpio_num_t)i, GPIO_MODE_INPUT );
//gpio_set_direction((gpio_num_t)i, GPIO_MODE_OUTPUT_OD );
//pinMode(i,OUTPUT);
}
porti=porti>>1;
}
/* pinMode(12,INPUT);
gpio_pulldown_en((gpio_num_t)12 );
gpio_set_pull_mode((gpio_num_t)12, GPIO_FLOATING);
gpio_set_direction((gpio_num_t)12, GPIO_MODE_INPUT );
pinMode(13,INPUT);
gpio_pulldown_en((gpio_num_t)13 );
gpio_set_pull_mode((gpio_num_t)13, GPIO_FLOATING);
gpio_set_direction((gpio_num_t)13, GPIO_MODE_INPUT );*/
portEXIT_CRITICAL(&mux);
//Serial.printf(" on a :%ld\n",__clock_cycles() - _start);
return __clock_cycles() - _start;
/* if(PORT_MASK==0)
port=PORT_MASK_TOTAL;
else
port=PORT_MASK;
// uint32_t porti=port;
for(int i=0;i<32;i++)
{
//Serial.printf("i:%d port:%ld result:%d\n",i,porti,porti&0x1);
if( (porti & 0x1)>0 )
{
pinMode(i,INPUT);
}
porti=porti>>1;
}
mPinMask = FastPin<FIRST_PIN>::mask();
mPort = FastPin<FIRST_PIN>::port();*/
}
//pour lancer la function en semaphore
/* static void showRGB32()
{
if (this.userRBGHandle == 0) {
const TickType_t xMaxBlockTime = pdMS_TO_TICKS( 200 );
// -- Store the handle of the current task, so that the show task can
// notify it when it's done
//noInterrupts();
this.userRBGHandle = xTaskGetCurrentTaskHandle();
// -- Trigger the show task
xTaskNotifyGive(this.handleRGBTHandle);
// -- Wait to be notified that it's done
ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS( 100 ));//portMAX_DELAY);
//delay(100);
//interrupts();
this.userRBGHandle = 0;
}
}*/
};
FASTLED_NAMESPACE_END
#endif
| [
"[email protected]"
] | |
f4df5c181a5c44ddd79d0d5573129da95e633875 | 4517087b8d6138805ad06b1e2e25a5698c72296c | /03_GameSkeleton/src/main.cpp | 844c7e449172db9c67ac719c6e14b61dadf391bc | [] | no_license | odrevet/teach-yourself-game-programming-sdl2 | 46fe3a94ea7728b20a7eb72ec12ad8289c991b02 | ac7e5cf4f071f107e38c25a253fe08bb913fbf8d | refs/heads/master | 2022-10-27T12:29:30.391839 | 2022-09-17T08:13:31 | 2022-09-17T08:13:31 | 46,120,721 | 10 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,416 | cpp | #include <SDL.h>
#include <iostream>
#include "IGame.h"
#include "Game.h"
#include "GameEngine.h"
//-----------------------------------------------------------------
// Main function
//-----------------------------------------------------------------
int main(int argc, char *argv[])
{
// instanciante the game
IGame *pGame = new Game;
// get the game engine
GameEngine *pGameEngine = GameEngine::GetEngine();
static int iTickTrigger = 0;
int iTickCount;
bool done = false;
const char *game_name = "Game skeleton";
const char *game_icon = "res/Skeleton.ico";
// Initialize or quit if an error occured
if (!pGameEngine->Initialize(game_name, game_icon) ||
!pGame->Initialize())
{
std::cout << "INIT ERR" << std::endl;
return EXIT_FAILURE;
}
// start the game now
pGameEngine->SetSleep(false);
pGame->Start();
// Enter the main message loop
while (!done)
{
// Make sure the game engine isn't sleeping
if (!pGameEngine->GetSleep())
{
// Check the tick count to see if a game cycle has elapsed
iTickCount = SDL_GetTicks();
if (iTickCount > iTickTrigger)
{
iTickTrigger = iTickCount +
pGameEngine->GetFrameDelay();
pGame->Cycle();
}
}
pGameEngine->HandleEvent();
// Paint the game
pGame->Paint();
}
// End the game
pGame->End();
return EXIT_SUCCESS;
}
| [
"[email protected]"
] | |
c2ff8c1fb2debe1ca8931e4782cb5cde8218b31b | 835934c3035770bd2fb0cea752bbe5c93b8ddc83 | /VTKHeaders/vtkMutexLock.h | 259845c7a36faa066167a1609aa17a3fcc193c0d | [
"MIT"
] | permissive | jmah/OsiriX-Quad-Buffered-Stereo | d257c9fc1e9be01340fe652f5bf9d63f5c84cde1 | 096491358a5d4d8a0928dc03d7183ec129720c56 | refs/heads/master | 2016-09-05T11:08:48.274221 | 2007-05-02T15:06:45 | 2007-05-02T15:06:45 | 3,008,660 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,597 | h | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: vtkMutexLock.h,v $
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkMutexLock - mutual exclusion locking class
// .SECTION Description
// vtkMutexLock allows the locking of variables which are accessed
// through different threads. This header file also defines
// vtkSimpleMutexLock which is not a subclass of vtkObject.
#ifndef __vtkMutexVariable_h
#define __vtkMutexVariable_h
#include "vtkObject.h"
//BTX
#ifdef VTK_USE_SPROC
#include <abi_mutex.h> // Needed for SPROC implementation of mutex
typedef abilock_t vtkMutexType;
#endif
#if defined(VTK_USE_PTHREADS) || defined(VTK_HP_PTHREADS)
#include <pthread.h> // Needed for PTHREAD implementation of mutex
typedef pthread_mutex_t vtkMutexType;
#endif
#ifdef VTK_USE_WIN32_THREADS
typedef vtkWindowsHANDLE vtkMutexType;
#endif
#ifndef VTK_USE_SPROC
#ifndef VTK_USE_PTHREADS
#ifndef VTK_USE_WIN32_THREADS
typedef int vtkMutexType;
#endif
#endif
#endif
// Mutex lock that is not a vtkObject.
class VTK_COMMON_EXPORT vtkSimpleMutexLock
{
public:
// left public purposely
vtkSimpleMutexLock();
virtual ~vtkSimpleMutexLock();
static vtkSimpleMutexLock *New();
void Delete() {delete this;}
// Description:
// Lock the vtkMutexLock
void Lock( void );
// Description:
// Unlock the vtkMutexLock
void Unlock( void );
protected:
vtkMutexType MutexLock;
};
//ETX
class VTK_COMMON_EXPORT vtkMutexLock : public vtkObject
{
public:
static vtkMutexLock *New();
vtkTypeRevisionMacro(vtkMutexLock,vtkObject);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Lock the vtkMutexLock
void Lock( void );
// Description:
// Unlock the vtkMutexLock
void Unlock( void );
protected:
vtkSimpleMutexLock SimpleMutexLock;
vtkMutexLock() {};
private:
vtkMutexLock(const vtkMutexLock&); // Not implemented.
void operator=(const vtkMutexLock&); // Not implemented.
};
inline void vtkMutexLock::Lock( void )
{
this->SimpleMutexLock.Lock();
}
inline void vtkMutexLock::Unlock( void )
{
this->SimpleMutexLock.Unlock();
}
#endif
| [
"[email protected]"
] | |
0d5a8f8e9645d85fe69efe84804f207b6958b32a | 3f2a6b37008aedf900eab6cfaa39bca061526ffe | /Visual Studio 2010/Projects/CCC/Parallel/Parallel.cpp | 4a7120a7b7be07e6b73c4c3fa999929651088887 | [] | no_license | stalcker23/Course | b823c3b8b7c6272cec7a1e83f4ae8446b27afa3b | 4dddcba4f2bdb99ccc06ff5da545c6e2b25797c8 | refs/heads/master | 2021-01-01T05:15:59.758990 | 2016-05-25T22:30:44 | 2016-05-25T22:30:44 | 57,152,054 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 150 | cpp | // Parallel.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
| [
"[email protected]"
] | |
57ff0b51aa89da4c3ee00d91944588778340c821 | e311ed0128cb849ce1d73d08c8535d3f504142be | /Orbitersdk/Simpit/Simpit/HookObserver.cpp | a1c3230198f79302d2a64b8c2f33c2f7bb987aff | [
"MIT"
] | permissive | MarcLT/simpit-controller | e31808ede3155648e1e36d6dce2397cf2c232eec | ff42117334f74ebebdd470aaaa0fab462bb13e56 | refs/heads/master | 2020-12-25T12:57:24.038309 | 2014-02-08T20:27:37 | 2014-02-08T20:27:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 425 | cpp | //Copyright (c) 2013 Christopher Johnstone(meson800)
//The MIT License - See ../../../LICENSE for more info
#include "HookObserver.h"
HookObserver observer;
void HookObserver::h_handlePanelMouseEvent(int id, int ev, int mx, int my)
{
if (callbackClass)
callbackClass->handlePanelMouseEvent(id,ev,mx,my);
}
void HookObserver::setUpReciever(PanelClickRecorderOutput * _callbackClass)
{
callbackClass = _callbackClass;
} | [
"[email protected]"
] | |
afa848ca673ccccd113d62a530cc6eb6441361e7 | fe2362eda423bb3574b651c21ebacbd6a1a9ac2a | /VTK-7.1.1/IO/MPIImage/vtkMPIImageReader.cxx | 079281c8f5287cf717aba8150c399a1a8801b9e6 | [
"BSD-3-Clause"
] | permissive | likewatchk/python-pcl | 1c09c6b3e9de0acbe2f88ac36a858fe4b27cfaaf | 2a66797719f1b5af7d6a0d0893f697b3786db461 | refs/heads/master | 2023-01-04T06:17:19.652585 | 2020-10-15T21:26:58 | 2020-10-15T21:26:58 | 262,235,188 | 0 | 0 | NOASSERTION | 2020-05-08T05:29:02 | 2020-05-08T05:29:01 | null | UTF-8 | C++ | false | false | 17,464 | cxx | // -*- c++ -*-
/*=========================================================================
Program: Visualization Toolkit
Module: vtkMPIImageReader.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/*----------------------------------------------------------------------------
Copyright (c) Sandia Corporation
See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/
#include "vtkMPIImageReader.h"
#include "vtkMultiProcessController.h"
#include "vtkObjectFactory.h"
#include "vtkToolkits.h"
// Include the MPI headers and then determine if MPIIO is available.
#include "vtkMPI.h"
#ifdef MPI_VERSION
# if (MPI_VERSION >= 2)
# define VTK_USE_MPI_IO 1
# endif
#endif
#if !defined(VTK_USE_MPI_IO) && defined(ROMIO_VERSION)
# define VTK_USE_MPI_IO 1
#endif
#if !defined(VTK_USE_MPI_IO) && defined(MPI_SEEK_SET)
# define VTK_USE_MPI_IO 1
#endif
// If VTK_USE_MPI_IO is set, that means we will read the data ourself using
// MPIIO. Otherwise, just delegate everything to the superclass.
#ifdef VTK_USE_MPI_IO
// We only need these includes if we are actually loading the data.
#include "vtkByteSwap.h"
#include "vtkDataArray.h"
#include "vtkImageData.h"
#include "vtkMPIController.h"
#include "vtkPointData.h"
#include "vtkTransform.h"
#include "vtkType.h"
#include <algorithm>
// This macro can be wrapped around MPI function calls to easily report errors.
// Reporting errors is more important with file I/O because, unlike network I/O,
// they usually don't terminate the program.
#define MPICall(funcall) \
{ \
int __my_result = funcall; \
if (__my_result != MPI_SUCCESS) \
{ \
char errormsg[MPI_MAX_ERROR_STRING]; \
int dummy; \
MPI_Error_string(__my_result, errormsg, &dummy); \
vtkErrorMacro(<< "Received error when calling" << endl \
<< #funcall << endl << endl \
<< errormsg); \
} \
}
#endif // VTK_USE_MPI_IO
//=============================================================================
vtkStandardNewMacro(vtkMPIImageReader);
vtkCxxSetObjectMacro(vtkMPIImageReader, Controller, vtkMultiProcessController);
vtkCxxSetObjectMacro(vtkMPIImageReader, GroupedController,
vtkMultiProcessController);
//-----------------------------------------------------------------------------
#ifdef VTK_USE_MPI_IO
template<class T>
inline void vtkMPIImageReaderMaskBits(T *data, vtkIdType length,
vtkTypeUInt64 _mask)
{
T mask = (T)_mask;
// If the mask is the identity, just return.
if ((_mask == (vtkTypeUInt64)~0UL) || (mask == (T)~0) || (_mask == 0)) return;
for (vtkIdType i = 0; i < length; i++)
{
data[i] &= mask;
}
}
// Override float and double because masking bits for them makes no sense.
template<>
void vtkMPIImageReaderMaskBits(float *, vtkIdType, vtkTypeUInt64)
{
return;
}
template<>
void vtkMPIImageReaderMaskBits(double *, vtkIdType, vtkTypeUInt64)
{
return;
}
#endif //VTK_USE_MPI_IO
//-----------------------------------------------------------------------------
#ifdef VTK_USE_MPI_IO
namespace {
template<class T>
inline T MY_ABS(T x) { return (x < 0) ? -x : x; }
template<class T>
inline T MY_MIN(T x, T y) { return (x < y) ? x : y; }
};
#endif //VTK_USE_MPI_IO
//=============================================================================
vtkMPIImageReader::vtkMPIImageReader()
{
this->Controller = NULL;
this->SetController(vtkMultiProcessController::GetGlobalController());
this->GroupedController = NULL;
}
vtkMPIImageReader::~vtkMPIImageReader()
{
this->SetController(NULL);
this->SetGroupedController(NULL);
}
void vtkMPIImageReader::PrintSelf(ostream &os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Controller: " << this->Controller << endl;
}
//-----------------------------------------------------------------------------
int vtkMPIImageReader::GetDataScalarTypeSize()
{
switch (this->GetDataScalarType())
{
vtkTemplateMacro(return sizeof(VTK_TT));
default:
vtkErrorMacro("Unknown data type.");
return 0;
}
}
//-----------------------------------------------------------------------------
#ifdef VTK_USE_MPI_IO
void vtkMPIImageReader::PartitionController(const int extent[6])
{
// Number of points in the z direction of the whole data.
int numZ = this->DataExtent[5] - this->DataExtent[4] + 1;
if ((this->GetFileDimensionality() == 3) || (numZ == 1))
{
// Everyone reads from the same single file. No need to partion controller.
this->SetGroupedController(this->Controller);
return;
}
// The following algorithm will have overflow problems if there are more
// than 2^15 files. I doubt anyone will ever be crazy enough to set up a
// large 3D image with that many slice files, but just in case...
if (numZ >= 32768)
{
vtkErrorMacro("I do not support more than 32768 files.");
return;
}
// Hash the Z extent. This is guaranteed to be unique for any pair of
// extents (within the constraint given above).
int extentHash = ( extent[4]+this->DataExtent[4]
+ (extent[5]+this->DataExtent[4])*numZ );
vtkMultiProcessController *subController
= this->Controller->PartitionController(extentHash, 0);
this->SetGroupedController(subController);
subController->Delete();
}
#else // VTK_USE_MPI_IO
void vtkMPIImageReader::PartitionController(const int *)
{
vtkErrorMacro(<< "vtkMPIImageReader::PartitionController() called when MPIIO "
<< "not available.");
}
#endif // VTK_USE_MPI_IO
//-----------------------------------------------------------------------------
// Technically we should be returning a 64 bit number, but I doubt any header
// will be bigger than the value stored in an unsigned int. Thus, we just
// follow the convention of the superclass.
#ifdef VTK_USE_MPI_IO
unsigned long vtkMPIImageReader::GetHeaderSize(vtkMPIOpaqueFileHandle &file)
{
if (this->ManualHeaderSize)
{
return this->HeaderSize;
}
else
{
this->ComputeDataIncrements();
MPI_Offset size;
MPICall(MPI_File_get_size(file.Handle, &size));
return static_cast<unsigned long>
(size - this->DataIncrements[this->GetFileDimensionality()]);
}
}
#else // VTK_USE_MPI_IO
unsigned long vtkMPIImageReader::GetHeaderSize(vtkMPIOpaqueFileHandle &)
{
vtkErrorMacro(<< "vtkMPIImageReader::GetHeaderSize() called when MPIIO "
<< "not available.");
return 0;
}
#endif // VTK_USE_MPI_IO
//-----------------------------------------------------------------------------
#ifdef VTK_USE_MPI_IO
void vtkMPIImageReader::SetupFileView(vtkMPIOpaqueFileHandle &file,
const int extent[6])
{
int arrayOfSizes[3];
int arrayOfSubSizes[3];
int arrayOfStarts[3];
for (int i = 0; i < this->GetFileDimensionality(); i++)
{
arrayOfSizes[i] = this->DataExtent[i*2+1] - this->DataExtent[i*2] + 1;
arrayOfSubSizes[i] = extent[i*2+1] - extent[i*2] + 1;
arrayOfStarts[i] = extent[i*2];
}
// Adjust for base size of data type and tuple size.
int baseSize = this->GetDataScalarTypeSize() * this->NumberOfScalarComponents;
arrayOfSizes[0] *= baseSize;
arrayOfSubSizes[0] *= baseSize;
arrayOfStarts[0] *= baseSize;
// Create a view in MPIIO.
MPI_Datatype view;
MPICall(MPI_Type_create_subarray(this->GetFileDimensionality(),
arrayOfSizes, arrayOfSubSizes, arrayOfStarts,
MPI_ORDER_FORTRAN, MPI_BYTE, &view));
MPICall(MPI_Type_commit(&view));
MPICall(MPI_File_set_view(file.Handle, this->GetHeaderSize(file), MPI_BYTE,
view, const_cast<char *>("native"), MPI_INFO_NULL));
MPICall(MPI_Type_free(&view));
}
#else // VTK_USE_MPI_IO
void vtkMPIImageReader::SetupFileView(vtkMPIOpaqueFileHandle &, const int[6])
{
vtkErrorMacro(<< "vtkMPIImageReader::SetupFileView() called when MPIIO "
<< "not available.");
}
#endif // VTK_USE_MPI_IO
//-----------------------------------------------------------------------------
#ifdef VTK_USE_MPI_IO
void vtkMPIImageReader::ReadSlice(int slice, const int extent[6], void *buffer)
{
this->ComputeInternalFileName(slice);
vtkMPICommunicator *mpiComm = vtkMPICommunicator::SafeDownCast(
this->GroupedController->GetCommunicator());
// Open the file for this slice.
vtkMPIOpaqueFileHandle file;
int result;
result = MPI_File_open(*mpiComm->GetMPIComm()->GetHandle(),
this->InternalFileName, MPI_MODE_RDONLY,
MPI_INFO_NULL, &file.Handle);
if (!(result == MPI_SUCCESS))
{
vtkErrorMacro("Could not open file: " << this->InternalFileName);
return;
}
// Set up the file view based on the extents.
this->SetupFileView(file, extent);
// Figure out how many bytes to read.
vtkIdType length = this->GetDataScalarTypeSize();
length *= this->NumberOfScalarComponents;
length *= extent[1]-extent[0]+1;
length *= extent[3]-extent[2]+1;
if (this->GetFileDimensionality() == 3) length *= extent[5]-extent[4]+1;
vtkIdType pos = 0;
while (length > pos)
{
MPI_Status stat;
// we know this will fit in an int because it can't exceed VTK_INT_MAX.
const int remaining = static_cast<int>(std::min(length - pos,
static_cast<vtkIdType>(VTK_INT_MAX)));
MPICall(MPI_File_read(file.Handle, (static_cast<char*>(buffer)) + pos, remaining,
MPI_BYTE, &stat));
int rd = 0;
MPICall(MPI_Get_elements(&stat, MPI_BYTE, &rd));
if (MPI_UNDEFINED == rd)
{
vtkErrorMacro("Error obtaining number of values read in " << remaining <<
"-byte read.");
}
pos += static_cast<vtkIdType>(rd);
}
MPICall(MPI_File_close(&file.Handle));
}
#else // VTK_USE_MPI_IO
void vtkMPIImageReader::ReadSlice(int, const int [6], void *)
{
vtkErrorMacro(<< "vtkMPIImageReader::ReadSlice() called with MPIIO "
<< "not available.");
}
#endif // VTK_USE_MPI_IO
//-----------------------------------------------------------------------------
#ifdef VTK_USE_MPI_IO
// This method could be made a lot more efficient.
void vtkMPIImageReader::TransformData(vtkImageData *data)
{
if (!this->Transform) return;
vtkDataArray *fileData = data->GetPointData()->GetScalars();
vtkDataArray *dataData = fileData->NewInstance();
dataData->SetName(fileData->GetName());
dataData->SetNumberOfComponents(fileData->GetNumberOfComponents());
dataData->SetNumberOfTuples(fileData->GetNumberOfTuples());
int dataExtent[6];
data->GetExtent(dataExtent);
int fileExtent[6];
this->ComputeInverseTransformedExtent(dataExtent, fileExtent);
vtkIdType dataMinExtent[3];
vtkIdType fileMinExtent[3];
vtkIdType dataExtentSize[3];
vtkIdType fileExtentSize[3];
for (int i = 0; i < 3; i++)
{
dataMinExtent[i] = MY_MIN(dataExtent[2*i], dataExtent[2*i+1]);
fileMinExtent[i] = MY_MIN(fileExtent[2*i], fileExtent[2*i+1]);
dataExtentSize[i] = MY_ABS(dataExtent[2*i+1] - dataExtent[2*i]) + 1;
fileExtentSize[i] = MY_ABS(fileExtent[2*i+1] - fileExtent[2*i]) + 1;
}
for (vtkIdType file_k = 0; file_k < fileExtentSize[2]; file_k++)
{
for (vtkIdType file_j = 0; file_j < fileExtentSize[1]; file_j++)
{
for (vtkIdType file_i = 0; file_i < fileExtentSize[0]; file_i++)
{
double fileXYZ[3];
fileXYZ[0] = file_i + fileMinExtent[0];
fileXYZ[1] = file_j + fileMinExtent[1];
fileXYZ[2] = file_k + fileMinExtent[2];
double dataXYZ[3];
this->Transform->TransformPoint(fileXYZ, dataXYZ);
vtkIdType data_i = static_cast<vtkIdType>(dataXYZ[0])-dataMinExtent[0];
vtkIdType data_j = static_cast<vtkIdType>(dataXYZ[1])-dataMinExtent[1];
vtkIdType data_k = static_cast<vtkIdType>(dataXYZ[2])-dataMinExtent[2];
vtkIdType fileTuple
= ((file_k*fileExtentSize[1] + file_j)*fileExtentSize[0]) + file_i;
vtkIdType dataTuple
= ((data_k*dataExtentSize[1] + data_j)*dataExtentSize[0]) + data_i;
dataData->SetTuple(dataTuple, fileTuple, fileData);
}
}
}
data->GetPointData()->SetScalars(dataData);
dataData->Delete();
}
#else // VTK_USE_MPI_IO
void vtkMPIImageReader::TransformData(vtkImageData *)
{
vtkErrorMacro(<< "vtkMPIImageReader::TransformData() called with MPIIO "
<< "not available.");
}
#endif // VTK_USE_MPI_IO
//-----------------------------------------------------------------------------
void vtkMPIImageReader::ExecuteDataWithInformation(vtkDataObject *output,
vtkInformation *outInfo)
{
#ifdef VTK_USE_MPI_IO
vtkMPIController *MPIController
= vtkMPIController::SafeDownCast(this->Controller);
if (!MPIController)
{
this->Superclass::ExecuteDataWithInformation(output, outInfo);
return;
}
vtkImageData *data = this->AllocateOutputData(output, outInfo);
if (!this->FileName && !this->FilePattern && !this->FileNames)
{
vtkErrorMacro("Either a valid FileName, FileNames, or FilePattern"
" must be specified.");
return;
}
// VTK stores images in traditional "right handed" coordinates. That is, the
// origin is in the lower left corner. Many images, especially those with RGB
// colors, have the origin in the upper right corner. In this case, we have
// to flip the y axis.
vtkTransform *saveTransform = this->Transform;
if (!this->FileLowerLeft)
{
vtkTransform *newTransform = vtkTransform::New();
if (this->Transform)
{
newTransform->Concatenate(this->Transform);
}
else
{
newTransform->Identity();
}
newTransform->Scale(1.0, -1.0, 1.0);
this->Transform = newTransform;
}
// Get information on data partion requested.
int inExtent[6];
vtkIdType inIncrements[3];
data->GetExtent(inExtent);
data->GetIncrements(inIncrements);
vtkDataArray *outputDataArray = data->GetPointData()->GetScalars();
vtkIdType numValues = ( outputDataArray->GetNumberOfComponents()
* outputDataArray->GetNumberOfTuples() );
outputDataArray->SetName(this->ScalarArrayName);
vtkDebugMacro("Reading extent: "
<< inExtent[0] << ", " << inExtent[1] << ", "
<< inExtent[2] << ", " << inExtent[3] << ", "
<< inExtent[4] << ", " << inExtent[5]);
// Respect the Transform.
int outExtent[6];
vtkIdType outIncrements[3];
this->ComputeInverseTransformedExtent(inExtent, outExtent);
// The superclass' ComputeInverseTransformedIncrements does not give us
// increments we can use. It just reorders the inIncrements, (offsets in the
// target data structure). This does not give us valid offsets for the file.
// Instead, we just recompute them.
//this->ComputeInverseTransformedIncrements(inIncrements, outIncrements);
outIncrements[0] = inIncrements[0];
outIncrements[1] = outIncrements[0]*(MY_ABS(outExtent[1]-outExtent[0])+1);
outIncrements[2] = outIncrements[1]*(MY_ABS(outExtent[3]-outExtent[2])+1);
this->ComputeDataIncrements();
// Get information on data type.
int typeSize = this->GetDataScalarTypeSize();
// Group processes based on which files they read.
this->PartitionController(outExtent);
// Get the pointer to the data buffer. Don't worry. We support all the
// data types. I am just casting it to a char (byte) so that I can do
// byte arithmetic on the data.
char *dataBuffer = reinterpret_cast<char *>(data->GetScalarPointer());
if (this->GetFileDimensionality() == 3)
{
// Everything is in one big file. Read it all in one shot.
this->ReadSlice(0, outExtent, dataBuffer);
}
else // this->GetFileDimensionality() == 2
{
// Read everything slice-by-slice.
char *ptr = dataBuffer;
for (int slice = outExtent[4]; slice <= outExtent[5]; slice++)
{
this->UpdateProgress( (0.9*(slice-outExtent[4]))
/ (outExtent[5]-outExtent[4]+1));
this->ReadSlice(slice, outExtent, ptr);
ptr += typeSize*outIncrements[2];
}
}
this->UpdateProgress(0.9);
// Swap bytes as necessary.
if (this->GetSwapBytes() && typeSize > 1)
{
vtkByteSwap::SwapVoidRange(dataBuffer, numValues, typeSize);
}
// Mask bits as necessary.
switch (this->GetDataScalarType())
{
vtkTemplateMacro(vtkMPIImageReaderMaskBits((VTK_TT *)dataBuffer, numValues,
this->DataMask));
}
// Perform permutation transformation of data if necessary.
this->TransformData(data);
if (!this->FileLowerLeft)
{
this->Transform->Delete();
this->Transform = saveTransform;
}
// Done with this for now.
this->SetGroupedController(NULL);
#else // VTK_USE_MPI_IO
this->Superclass::ExecuteDataWithInformation(output, outInfo);
#endif // VTK_USE_MPI_IO
}
| [
"[email protected]"
] | |
ca5cd46c1247484690329be5412fa8ee7fd0e227 | d008bbc6caed65b6d101c049eac32def267cb72f | /0463_island_perimeter.cpp | 32823ef39f888d40b2844d6261bfb0b199c2c338 | [] | no_license | ShiboYao/Leetcode_cpp | 1e4cfd2aa8c672369dd39ee2489cc5f547f65e93 | 4005921f4b3bbf6d14db81cde244c8fdc1ab227f | refs/heads/master | 2020-06-05T06:12:11.706970 | 2020-01-31T01:39:32 | 2020-01-31T01:39:32 | 192,341,616 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 798 | cpp | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int islandPerimeter(vector<vector<int>>& grid) {
int count = 0;
int m = grid.size(), n = grid[0].size();
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
if (grid[i][j]){
count += (i == 0 || grid[i-1][j] == 0);
count += (i == m-1 || grid[i+1][j] == 0);
count += (j == 0 || grid[i][j-1] == 0);
count += (j == n-1 || grid[i][j+1] == 0);
}
}
}
return count;
}
};
int main(){
vector<vector<int>> a{{0,1,0,0},{1,1,1,0},{0,1,0,0},{1,1,0,0}};
Solution s;
cout << s.islandPerimeter(a) << endl;
return 0;
}
| [
"[email protected]"
] | |
87a0b4eb6f5ff361d89ed77634fcc88e783b5ba4 | 9478ad42528ee09c697f6833bba21b21c0452712 | /Reports/f_productquantityalerts.h | 094daf07f58dae318a50ff4f3502405ab246ebcd | [] | no_license | ashraf-kx/stock-manager | 2afc5e4e0d83fe97b9b145ddc2980b4cffb7e4f3 | e755063e23f10a60f39a125626e05a7ab6dd624f | refs/heads/master | 2020-05-09T17:29:09.623493 | 2017-08-17T12:12:53 | 2017-08-17T12:12:53 | 181,310,048 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | h | #ifndef F_PRODUCTQUANTITYALERTS_H
#define F_PRODUCTQUANTITYALERTS_H
#include <QFrame>
namespace Ui {
class F_ProductQuantityAlerts;
}
class F_ProductQuantityAlerts : public QFrame
{
Q_OBJECT
public:
explicit F_ProductQuantityAlerts(QWidget *parent = 0);
~F_ProductQuantityAlerts();
private:
Ui::F_ProductQuantityAlerts *ui;
};
#endif // F_PRODUCTQUANTITYALERTS_H
| [
"[email protected]"
] | |
fb935a3945d225086562a8dcdbdc1d81c5ceef04 | df7ae7e3ee327a42a5a14bc74c5ff6e3ebd80c4d | /test/HashTuple_test.cpp | 07ff133aca98b83975c9eab69f35492d5f18db0f | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | MichaelZhou-New/Mesh-processing-library | 246dcaf801dc787d34fe5a2a1b90b5326564b709 | aa8c952fbbb00774008060767650b821bf72fa10 | refs/heads/master | 2023-08-25T07:32:31.031032 | 2021-10-29T01:18:54 | 2021-10-29T01:18:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,562 | cpp | // -*- C++ -*- Copyright (c) Microsoft Corporation; see license.txt
#include "libHh/HashTuple.h" // std::hash<std::tuple<...>>
#include "libHh/Set.h"
using namespace hh;
int main() {
{
using TU = std::tuple<int, float, bool>;
TU tu1 = std::make_tuple(1, 2.f, true);
SHOW(tu1);
if (0) {
SHOW(std::hash<TU>()(tu1));
SHOW(std::hash<TU>()(std::make_tuple(1, 2.f, true)));
SHOW(std::hash<TU>()(std::make_tuple(1, 2.f, false)));
SHOW(std::hash<TU>()(std::make_tuple(1, 3.f, true)));
SHOW(std::hash<TU>()(std::make_tuple(2, 2.f, true)));
}
Set<size_t> set; // verify all unique
assertx(set.add(std::hash<TU>()(std::make_tuple(1, 2.f, true))));
assertx(set.add(std::hash<TU>()(std::make_tuple(1, 2.f, false))));
assertx(set.add(std::hash<TU>()(std::make_tuple(1, 3.f, true))));
assertx(set.add(std::hash<TU>()(std::make_tuple(2, 2.f, true))));
}
{
using TU = std::tuple<int, float, double*>;
double d1, d2;
TU tu1 = std::make_tuple(1, 2.f, &d1);
assertx(std::hash<TU>()(tu1) == std::hash<TU>()(std::make_tuple(1, 2.f, &d1)));
assertx(std::hash<TU>()(tu1) != std::hash<TU>()(std::make_tuple(1, 2.f, &d2)));
assertx(std::hash<TU>()(tu1) != std::hash<TU>()(std::make_tuple(1, 3.f, &d1)));
assertx(std::hash<TU>()(tu1) != std::hash<TU>()(std::make_tuple(2, 2.f, &d1)));
}
{
std::tuple<int> tu2(3);
SHOW(tu2);
SHOW(std::make_tuple(1, 2.f, false, 5.));
SHOW(std::make_pair(1, 2.f));
}
{
std::pair<int, bool> p{5, true};
SHOW(p);
}
}
| [
"[email protected]"
] | |
938814cc656664fb542b1d14ec831dbccee9102a | 15fd5c80f83b887c92f9046de60fc085ac08ec77 | /src/SLIPStream.h | 9a77cf5bf169172134db93fd0abab9fbaafd0650 | [
"BSD-3-Clause-Clear"
] | permissive | vshymanskyy/SLIPStream | 0b097e51d996e95e8d1c86cc20373c7fc7ee4ede | 7f3f779cb5ae74807c68b6663c61efddda174682 | refs/heads/master | 2023-03-18T06:21:20.555130 | 2019-02-25T23:30:10 | 2019-02-25T23:30:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,703 | h | // Library for reading and writing SLIP using an underlying Stream object.
// This implements [RFC 1055](https://tools.ietf.org/html/rfc1055).
// This file is part of the SLIPStream library.
// (c) 2018-2019 Shawn Silverman
#ifndef SLIPSTREAM_H_
#define SLIPSTREAM_H_
// C++ includes (Arduino doesn't have C++ headers, so check)
#if defined(ESP8266) // No __has_include here
#include <cstddef>
#include <cstdint>
#else
#if __has_include(<cstddef>)
#include <cstddef>
#else
#include <stddef.h>
#endif
#if __has_include(<cstdint>)
#include <cstdint>
#else
#include <stdint.h>
#endif
#endif
// Other includes
#include <Stream.h>
class SLIPStream : public Stream {
public:
// Read return values
static constexpr int END_FRAME = -2;
// Creates a new SLIPStream object.
// https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-explicit
explicit SLIPStream(Stream &stream);
// Not copyable or movable
// https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-copy-virtual
SLIPStream(const SLIPStream &) = delete;
SLIPStream &operator=(const SLIPStream &) = delete;
virtual ~SLIPStream() = default;
#if !defined(ARDUINO_ARCH_ESP8266) && !defined(ARDUINO_ARCH_ESP32) && \
!defined(ARDUINO_ARCH_STM32)
// Returns the number of bytes that can be written without blocking.
// Internally, this assumes that each byte will be written as two, so this
// returns half the underlying stream's non-blocking write size.
int availableForWrite() override;
#endif
// Writes a range of bytes. This may not write all the bytes if there was a
// write error or if the underlying stream was unable to write all the bytes.
// If this is the case then a write error will be set. This will return,
// however, the actual number of bytes written.
//
// It is assumed that buf is not nullptr and is at least as large as size.
size_t write(const uint8_t *buf, size_t size) override;
// Writes a single byte. This returns 1 if there was no error, otherwise this
// returns zero. If this returns zero then a write error will be set.
size_t write(uint8_t b) override;
// Writes a frame END marker. This behaves the same as the single-byte write.
//
// Note that this does not flush the stream.
size_t writeEnd();
// Flushes the stream. If there was a write error or if not all the bytes
// could be sent then a write error will be set.
void flush() override;
// This will return about half the underlying stream's available byte count,
// under the conservative assumption that each character potentially occupies
// two bytes in its encoded form. More bytes may actually be available.
//
// Note that a frame END marker is considered an available byte.
int available() override;
// Reads one character from the SLIP stream. All unknown escaped characters
// are a protocol violation and considered corrupt data.
//
// This will return -1 if there are no bytes available and -2 for
// end-of-frame. Corrupt data will be returned as-is, but isBadData() will
// return true until the next read() call.
//
// The END condition can be tested with isEnd(). For corrupt data, tested with
// isBadData(), the caller should read until the next END marker.
int read() override;
// Implements a multi-byte read and is designed as a replacement for
// `readBytes`. Reading stops under the same conditions that read() stops, and
// in addition, stops when corrupt data is encountered. Thus, both the isEnd()
// and isBadData() functions work as expected.
//
// Note that because corrupt data is part of the read count, it is possible
// that the returned value is equal to len even though the last byte is
// corrupt. Thus, this case can't be used to verify that there hasn't been any
// corrupt data.
//
// It is assumed that buf is not nullptr and that it has enough space to store
// all the requested bytes.
size_t read(uint8_t *buf, size_t len);
// Returns whether the last call to read() returned an END marker. This resets
// to false the next time read() is called.
bool isEnd() const {
return isEND_;
}
// Returns whether the last call to read() encountered corrupt data. This
// resets to false the next time read() is called.
bool isBadData() const {
return isBadData_;
}
// Peeks at one character from the SLIP stream. The character determination
// logic is the same as for read(). This also returns -1 for no data and -2
// for end-of-frame. Corrupt data will not be flagged and will be returned
// as-is.
//
// Don't use this function returning -1 as a substitute for determining data
// availability. This case may simply mean that the first byte of a two-byte
// sequence is available but the whole character is not. If read() is not
// called to advance the stream then this will always return -1, even if more
// data is available.
int peek() override;
private:
// Encodes and writes an encoded byte to the underlying stream. This returns
// whether the write was successful, 1 for success and 0 for no success.
//
// If the write was not successful then this stream's write error will be set.
// This does not check if the underlying stream has a write error set, so the
// caller will need to check. This avoids a check when doing multi-byte calls.
size_t writeByte(uint8_t b);
// The underlying stream.
Stream &stream_;
// Character read state.
bool inESC_;
// Indicates whether the last read() call returned an END marker.
bool isEND_;
// Indicates whether the last read() call encountered corrupt data.
bool isBadData_;
};
#endif // SLIPSTREAM_H_
| [
"[email protected]"
] | |
d6eb7afd492caf55c0dcb5c07bba9ac6bbd44f3f | b9a83ecf67f01ba6072264e62c272a049ea52f89 | /events/event_send_pak.h | 8bd4cb15e7e1deb10e7c916cdb2d7c2783a7df77 | [
"MIT"
] | permissive | Aergonus/Comcast | 8495a9dd9d945cae48ada39e57f2e1e47b136732 | 3bf10b484bd76dec4380df3a57db09b677e232de | refs/heads/master | 2021-11-23T17:20:29.482860 | 2016-07-19T00:13:55 | 2016-07-19T00:13:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 452 | h | /**
* ECE408
* event_send_pak.h
* Purpose: Sent Packet Event
*
* @author Kangqiao Lei
* @version 0.5.0 05/03/16
*/
#ifndef EVENT_SEND_PAK_H
#define EVENT_SEND_PAK_H
#include "event.h"
#include "../link.h"
class event_send_pak:public event{
private:
Link *l;
public:
event_send_pak(float time, Link *l):event(time), l(l){
setType("Send Packet Event");
};
~event_send_pak(){};
void handle_event(){
l->send_pak();
};
};
#endif | [
"[email protected]"
] | |
b2ab4829612fdf30bf899c3d1e6613d03e69710d | a1e110d93579e341f9046fb672670ae3ca459f68 | /ass9.cpp | fd7fbbe7e390cf5d080df11367d5609ccc2c0036 | [] | no_license | hieupoo16022001/ass9 | 7980feae44ca51638565adf48816ba49a27521be | 08df9e8c3d8a4078292a98aeab893e92178c7b4e | refs/heads/master | 2022-02-16T08:22:55.920863 | 2019-09-17T06:29:39 | 2019-09-17T06:29:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 258 | cpp | #include <stdio.h>
#include <string.h>
int main(){
char n[10];
char str[1];
for(int i=0;i<10;i++){
scanf("%s",n[i]);
}
printf("nhap str");
scanf("%s",str);
if(strcmp(n,str)==0){printf("co thuoc\n ");
}
return 0;
}
| [
"[email protected]"
] | |
fb291296e3202be9e0fb6ca8eaa6a615151d95f0 | 9f76d1ea6337e30c5b48a9b88839d2c5d7f27b93 | /resources/libzmq-master/tests/test_ipc_wildcard.cpp | 2f0ae176cc8e8c7b95a0fd7d45f6d4cb8e21b7e3 | [
"LGPL-3.0-only",
"LicenseRef-scancode-zeromq-exception-lgpl-3.0",
"LGPL-2.0-or-later",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"BSD-3-Clause"
] | permissive | DweebsUnited/CodeMonkey | 0271c782e76e1a846e2904f310edff2552f449e8 | 3b27e9c189c897b06002498aea639bb44671848a | refs/heads/master | 2023-03-10T01:41:39.426571 | 2021-01-22T19:12:25 | 2021-01-22T19:12:25 | 59,266,552 | 0 | 1 | BSD-3-Clause | 2023-02-25T00:42:45 | 2016-05-20T05:08:56 | HTML | UTF-8 | C++ | false | false | 1,990 | cpp | /*
Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file
This file is part of libzmq, the ZeroMQ core engine in C++.
libzmq is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
As a special exception, the Contributors give you permission to link
this library with independent modules to produce an executable,
regardless of the license terms of these independent modules, and to
copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the
terms and conditions of the license of that module. An independent
module is a module which is not derived from or based on this library.
If you modify this library, you must extend this exception to your
version of the library.
libzmq is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "testutil.hpp"
#include "testutil_unity.hpp"
SETUP_TEARDOWN_TESTCONTEXT
void test_ipc_wildcard ()
{
void *sb = test_context_socket (ZMQ_PAIR);
char endpoint[200];
bind_loopback_ipc (sb, endpoint, sizeof endpoint);
void *sc = test_context_socket (ZMQ_PAIR);
TEST_ASSERT_SUCCESS_ERRNO (zmq_connect (sc, endpoint));
bounce (sb, sc);
test_context_socket_close (sc);
test_context_socket_close (sb);
}
int main ()
{
setup_test_environment ();
UNITY_BEGIN ();
RUN_TEST (test_ipc_wildcard);
return UNITY_END ();
}
| [
"[email protected]"
] | |
d69a9a82378ed610f8028681120d6e069e316fe7 | b6c9433cefda8cfe76c8cb6550bf92dde38e68a8 | /epoc32/include/app/msgbiocontrol.h | 487850b6ee6e409867d8b55425dbae7875c2d6cd | [] | no_license | fedor4ever/public-headers | 667f8b9d0dc70aa3d52d553fd4cbd5b0a532835f | 3666a83565a8de1b070f5ac0b22cc0cbd59117a4 | refs/heads/master | 2021-01-01T05:51:44.592006 | 2010-03-31T11:33:34 | 2010-03-31T11:33:34 | 33,378,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,215 | h | /*
* Copyright (c) 2002-2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: Base class for bio controls.
*
*/
#ifndef MSGBIOCONTROL_H
#define MSGBIOCONTROL_H
// INCLUDES
#include <msvstd.h>
#include <coecntrl.h> // for CCoeControl
#include <mmsgbiocontrol.h> // for MMsgBioControl
#include <badesca.h> // for CDesCArray
#include <aknglobalnote.h>
#include <msgeditor.hrh> // for TMsgCursorLocation
// FORWARD DECLARATIONS
class MMsgBioControlObserver;
class CMsvSession;
class MMsgBioControlExtension;
// CLASS DECLARATION
/**
* The base class for Bio controls.
*/
class CMsgBioControl : public CCoeControl, public MMsgBioControl
{
public: //construction and destruction
/**
* Constructor. Call this from your Bio Control constructor.
* @param aObserver Reference to the Bio control observer.
* @param aSession Message Server session. Ownership not transferred.
* @param aId Id of the message in the server.
* @param aEditorOrViewerMode Sets Bio Control into editor or viewer mode.
* @param aFile Data file handle. Bio controls can also be file based. Not owned.
*/
IMPORT_C CMsgBioControl(
MMsgBioControlObserver& aObserver,
CMsvSession* aSession, //ownership is NOT transferred
TMsvId aId,
TMsgBioMode aEditorOrViewerMode,
const RFile* aFile); //ownership is NOT transferred
/**
* Destructor
*/
IMPORT_C ~CMsgBioControl();
public: // static helper functions
/**
* Pops a confirmation query. The result is given by the return value.
* The standard resource must have been loaded using
* LoadStandardBioResourceL().
* @param aText The text that is to be used in the query.
* @return A user confirmation results in ETrue, and vice versa.
*/
IMPORT_C static TBool ConfirmationQueryL(const TDesC& aText);
/**
* Pops a confirmation query. The result is given by the return value.
* The standard resource must have been loaded using
* LoadStandardBioResourceL(). Your resource must also be loaded, for
* eg. with LoadResourceL().
* CCoeEnv must exist.
* @param aStringResource The string resource id.
* @return A user confirmation results in ETrue, and vice versa.
*/
IMPORT_C static TBool ConfirmationQueryL(TInt aStringResource);
public: // from MMsgBioControl
/**
* The application can get the option menu recommendations using this
* function. The function comes from MMsgBioControl. This is the
* default implementation which returns the flags
* EMsgBioCallBack | EMsgBioDelete | EMsgBioMessInfo | EMsgBioMove |
* EMsgBioCreateCC | EMsgBioSend | EMsgBioAddRecipient | EMsgBioSave |
* EMsgBioSendingOpt | EMsgBioHelp | EMsgBioExit.
* Bio Controls should override this if it is not ok.
* @return The option menu permission flags. If the flag is off it
* means that the option menu command is not recommended with this
* Bio Control.
*/
IMPORT_C TUint32 OptionMenuPermissionsL() const;
/**
* Gives the height of the text in pixels.
* It is used by the scrolling framework.
* @return Height of the text in pixels.
*/
IMPORT_C TInt VirtualHeight();
/**
* Gives the cursor position in pixels.
* It is used by the scrolling framework.
* @return Cursor position in pixels.
*/
IMPORT_C TInt VirtualVisibleTop();
/**
* Tells whether the cursor is in the topmost or bottom position.
* It is used by the scrolling framework.
* @param aLocation Specifies either top or bottom.
* @return ETrue if the cursor is in the part specified by aLocation.
*/
IMPORT_C TBool IsCursorLocation(TMsgCursorLocation aLocation) const;
public: //new functions
/**
* Performs the internal scrolling of control if needed.
* Default implementation does not perform any scrolling and returns that
* zero pixels were scrolled.
* @since 3.2
* @param aPixelsToScroll Amount of pixels to scroll.
* @param aDirection Scrolling direction.
* @return Amount of pixels the where scrolled. Zero value means the component cannot
* be scrolled to that direction anymore and view should be moved.
*/
IMPORT_C TInt ScrollL( TInt aPixelsToScroll, TMsgScrollDirection aDirection );
/**
* Prepares control for viewing.
* @since 3.2
* @param aEvent The event type
* @param aParam Event related parameters
*/
IMPORT_C void NotifyViewEvent( TMsgViewEvent aEvent, TInt aParam );
protected: //new functions
/**
* Returns true if the control has been launched as editor,
* and false if it was launched as viewer.
* @return ETrue or EFalse
*/
IMPORT_C TBool IsEditor() const;
/**
* Is the Bio Control file based or not.
* @return ETrue if is file based.
*/
IMPORT_C TBool IsFileBased() const;
/**
* Accessor for MsvSession. The session exists only if the Bio Control
* has been created as message server based.
* @exception Panics if there is no session.
* @return CMsvSession&
*/
IMPORT_C CMsvSession& MsvSession() const;
/**
* Deprecated*
*
* Returns name of input file.
* @return Name of file.
* @exception Panics if the control is not file based.
*/
IMPORT_C const TFileName& FileName() const;
/**
* Deprecated* Handle is valid only at contsruction phase!!
* To be removed.
* Returns input file handle.
* @return handle of file.
* @exception Panics if the control is not file based.
*/
IMPORT_C const RFile& FileHandle() const;
/**
* Loads a resource file from /system/data/ into eikon env. This
* function should be used for loading the Bio Control resources.
* The resources are unloaded in the destructor of this class. The
* offsets are kept in iResourceOffsets.
* @param aFile File name mask, for eg. "vcalbc.r??".
*/
IMPORT_C void LoadResourceL(const TDesC& aFile);
/**
* Loads a resource file into eikon env. The resources are unloaded in
* the destructor of this class. (the offsets are kept in
* iResourceOffsets).
* @param aFile File name mask, for eg. "vcalbc.r??".
* @param aSearchPath Search path, for eg. "\\System\\libs\\".
*/
IMPORT_C void LoadResourceL(const TDesC& aFile,
const TDesC& aSearchPath);
/**
* This loads the msgeditorutils.rsc resource, which is needed by
* the dialogs and notes of this class.
*/
IMPORT_C void LoadStandardBioResourceL();
/**
* Adds a menu item to the menu pane which is given as a reference.
* @param aMenuPane Reference to the menu pane.
* @param aStringRes The string resource id.
* @param aCommandOffset The offset of the command from the first free
* command.
* @param aPosition The inserting position. The default is at the top.
*/
IMPORT_C void AddMenuItemL(CEikMenuPane& aMenuPane, TInt aStringRes,
TInt aCommandOffset, TInt aPosition = 0);
/**
* Notify editor view.
* This is used by the Bio Control for notifying the Editor Base
* framework of an event, and usually for requesting something to
* be done.
*/
IMPORT_C TBool NotifyEditorViewL(
TMsgBioControlEventRequest aRequest,
TInt aDelta = 0);
/**
* Call from base class if extension interface is supported.
* @param Interface for bio control extension. Ownership is not taken.
*/
IMPORT_C void SetExtension(MMsgBioControlExtension* aExt);
private: // new functions
/**
* Sets the bio body control reference.
* Used only by CMsgBioBodyControl.
* @param aBioBodyControl Address of the bio body control.
*/
void SetBioBodyControl( MMsgBioBodyControl* aBioBodyControl );
/// deprecated
TBool IsNear(TInt aLafPos, TInt aPos) const;
private: // not available
/**
* Default constructor hidden away
*/
CMsgBioControl();
/**
* Copy constructor prohibited.
*/
CMsgBioControl(const CMsgBioControl& aSource);
/**
* Assignment operator prohibited.
*/
const CMsgBioControl& operator=(const CMsgBioControl& aSource);
protected:
/// Reference to the MMsgBioControlObserver
MMsgBioControlObserver& iBioControlObserver;
/// Id of the message in the server.
TMsvId iId;
private:
/**
* Pointer to Message Server session. It is NOT owned here.
* The reason for using pointer type is that the session is optional.
* It can be NULL without implying any error.
* This session is accessed using the function MsvSession().
*/
CMsvSession* iMsvSession;
/// Tells if the control was launched in editor or viewer mode.
TMsgBioMode iMode;
/**
* * Deprecated -> To be removed*
* Handle is valid only during contruction phase.
* A pointer to the handle of the input file, not owned.
* Accessed using FileHandle().
* See also function FileBased().
*/
const RFile* iFile;
/**
* A pointer to Bio control extension interface. It is not owned here.
*/
MMsgBioControlExtension* iExt;
// Filler needed to keep this object's size the same.
// Let the compiler calculate the filler size needed using sizeof.
TUint8 iBCFiller[sizeof(TFileName) - sizeof(TFileName*) - sizeof(MMsgBioControlExtension*)];
/// This is the array of resource offsets.
CArrayFixFlat<TInt>* iResourceOffsets;
/// Pointer to the bio bodycontrol.
MMsgBioBodyControl* iBioBodyControl;
/// status flags
TInt iBCStatusFlags;
private:
friend class CMsgBioBodyControl;
};
#endif // MSGBIOCONTROL_H
// End of file
| [
"[email protected]"
] | |
57bf07da86100168301c9f170bad9a58eea0ddaf | 1f840c6029aa8f3ec881be5ce5912a2a5add4b2c | /pushbutton1/pushbutton1.ino | 6f806f18587167f87cfd58675534637bc6da7544 | [] | no_license | Jobenas/esp8266_samples_workshop | 4b9571a7b922d7e6b73c80a3141ed3b9ce21aa54 | 74fb08b92f762737690fe01151f963dc39819c8f | refs/heads/master | 2020-09-12T05:01:37.309108 | 2019-11-21T19:51:10 | 2019-11-21T19:51:10 | 222,315,529 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 611 | ino | //Definicion del estado del boton
int estadoBoton = 0;
//Definicion de los pines para el boton y el pulsador
int led = D8;
int boton = D1;
void setup() {
//Pin de salida para el LED
pinMode(led, OUTPUT);
//Pin de entrada para el pulsador
pinMode(boton, INPUT);
//apagamos el LED al comienzo
digitalWrite(led, LOW);
}
void loop() {
//Leemos el estado del pulsador
estadoBoton = digitalRead(boton);
//Revisamos el estado del pulsador
if(estadoBoton == HIGH)
{
//Prendemos el LED
digitalWrite(led, HIGH);
}
else
{
//apagamos el LED
digitalWrite(led, LOW);
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.