blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7b9e6603e8d79b6147a8319b1217ef0861722099 | 19e16f8406ce613c25f1bc8e5b81ec282e4265c5 | /pata_code/PAT-A1069 The Black Hole of Numbers.cpp | 0255dea99abee3e35d61d3ebb88674d569089378 | [] | no_license | lovenan95/PAT | a0cc411f7db202a441941776a116e3c64f4a01c5 | c993637ae05aadbc523cc80376e5a6a72c4ceb9f | refs/heads/master | 2020-04-09T17:18:37.534941 | 2018-12-06T12:44:36 | 2018-12-06T12:44:36 | 160,477,025 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 762 | cpp | #include<stdio.h>
#include<algorithm>
using namespace std;
bool cmp(int a,int b){
return a>b;
}
void toarr(int num,int arr[]){
for(int i=3;i>=0;i--){
arr[i]=num%10;
num=num/10;
}
}
int tonum(int arr[]){
int num2=0;
for(int i=0;i<4;i++){
num2=num2*10+arr[i];
}
return num2;
}
int main(){
int N,n1,sum,n2,num[4],s[4];
scanf("%d",&N);
if(N==6174)
{
printf("7641 - 1467 = 6174\n");
}
while(N!=0&&N!=6174){
toarr(N,num);
sort(num,num+4,cmp);
n1=tonum(num);
sort(num,num+4);
n2=tonum(num);
sum=n1-n2;
toarr(sum,s);
printf("%04d - %04d = %04d",n1,n2,sum);
if(sum!=6174&&sum!=0){
N=sum;
}else{
break;
}
printf("\n");
}
return 0;
} | [
"648607142@qq.com"
] | 648607142@qq.com |
dbd50240e7ecea1b8cab7d5b2fcf2a425eda5bba | b6961eed43e0bded5e38921624d47024429c15ba | /c_src/ErlangIO.cpp | f62b914243eb39bf3ad05520920f364fc1cf0930 | [
"BSD-3-Clause"
] | permissive | nkrylov/snffr | 38fda1ad465841c926aebddd8140a264fdb48681 | c4eaa81a2e57ac342d7fe763881052e7c9dd7ac6 | refs/heads/master | 2021-05-01T11:44:28.743461 | 2016-10-13T16:47:41 | 2016-10-13T16:47:41 | 56,833,684 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,942 | cpp |
#include <string>
#include <memory.h>
#include <stdio.h>
#include "ErlangIO.h"
#include "SnffrLog.h"
int ErlangRX::read_stream() {
if( m_len < STDIN_STREAM_BUFFER_SIZE )
{
int nbytes = read(0, m_buf + m_len, STDIN_STREAM_BUFFER_SIZE - m_len);
if(nbytes == -1)
{
LOG("read_stream(): STDIN stream error: errno=%d [%s]\n", errno, strerror(errno));
return -1;
}
if(nbytes == 0)
{
LOG("read_stream(): STDIN stream closed\n");
return -1;
}
m_len += nbytes;
}
else
{
LOG("read_stream(): STDIN stream buffer is full. Cannot read new commands\n");
}
return m_len;
}
int ErlangTX::write_stream() {
int nbytes = write(1, m_buf, m_len);
if(nbytes == -1)
{
LOG("write_stream(): STDOUT stream error: errno=%d [%s]\n", errno, strerror(errno));
return -1;
}
if(nbytes < m_len)
{
LOG("write_stream(): STDOUT stream is full\n");
int nrest = m_len - nbytes;
memmove(m_buf, m_buf + nbytes, nrest);
m_len = nrest;
}
else
{
m_len = 0;
}
return nbytes;
}
int ErlangRX::read_command(char *buf, int buflen, std::string& cmd, std::vector<std::string>& args) {
if(m_len < 2) return 0; //not enough data
int cmdlen = ((unsigned char)m_buf[0] << 8) | (unsigned char)m_buf[1];
if((cmdlen < 0) || (cmdlen > buflen))
{
LOG("read_command(): length %d is invalid or exceeds the buffer size %d\n", cmdlen, buflen);
memset(m_buf, 0, STDIN_STREAM_BUFFER_SIZE);
return -1;
}
if(cmdlen + 2 > m_len) return 0; //more data to grab on the next read
memset(buf, 0, buflen);
memcpy(buf, m_buf + 2, cmdlen);
memmove(m_buf, m_buf + cmdlen + 2, m_len - cmdlen - 2);
m_len -= (cmdlen + 2);
int i = 0, arity = 0;
if (-1 == ei_decode_version(buf, &i, &arity)) {
LOG("read_command(): wrong libei versions");
return -1;
}
ei_decode_tuple_header(buf, &i, &arity);
ei_decode_tuple_header(buf, &i, &arity);
memset((void *)&m_pid, 0, sizeof(erlang_pid));
ei_decode_pid(buf, &i, &m_pid);
memset((void *)&m_ref, 0, sizeof(erlang_ref));
ei_decode_ref(buf, &i, &m_ref);
ei_decode_tuple_header(buf, &i, &arity);
char cmd_name[MAXATOMLEN];
ei_decode_atom(buf, &i, cmd_name);
cmd = std::string(cmd_name);
arity = 0;
ei_decode_list_header(buf, &i, &arity);
for (auto arg = 0; arg < arity; arg++) {
char arg_name[MAXATOMLEN];
ei_decode_atom(buf, &i, arg_name);
args.push_back(arg_name);
}
return cmdlen;
}
int ErlangTX::write_response(ei_x_buff *buf) {
if(m_len + buf->index + 2 > STDOUT_STREAM_BUFFER_SIZE)
{
LOG("write_response(): Output Stream buffer is full, discarded\n");
return -1;
}
// length
unsigned char tmp = (unsigned char)((buf->index >> 8) & 0xff);
m_buf[m_len++] = tmp;
tmp = (unsigned char)(buf->index & 0xff);
m_buf[m_len++] = tmp;
// buffer
memcpy(m_buf + m_len, buf->buff, buf->index);
m_len += buf->index;
return write_stream();
}
int ErlangTX::encode_hdr(ei_x_buff& buf) {
ei_x_new_with_version(&buf);
ei_x_encode_tuple_header(&buf, 2);
ei_x_encode_tuple_header(&buf, 2);
ei_x_encode_pid(&buf, &m_pid);
ei_x_encode_ref(&buf, &m_ref);
return 0;
}
// {ok, [binary()]}
int ErlangTX::reply_ok( const std::vector<std::string>& reply) {
ei_x_buff buf;
encode_hdr(buf);
ei_x_encode_tuple_header(&buf, 2);
ei_x_encode_atom(&buf, "ok");
ei_x_encode_list_header(&buf, reply.size());
for (auto bin: reply) {
ei_x_encode_binary(&buf, bin.c_str(), bin.length());
}
ei_x_encode_empty_list(&buf);
int rv = write_response(&buf);
ei_x_free(&buf);
return rv;
}
// {error, Reason}
int ErlangTX::reply_error(const std::string& msg) {
ei_x_buff buf;
encode_hdr(buf);
ei_x_encode_tuple_header(&buf, 2);
ei_x_encode_atom(&buf, "error");
ei_x_encode_atom(&buf, msg.c_str());
int rv = write_response(&buf);
ei_x_free(&buf);
return rv;
}
| [
"nikita.krylov@gmail.com"
] | nikita.krylov@gmail.com |
1aefd981d054ac7a43b2a20c0b162b1028e5d61d | 400d20a0e5d6349d75de0afedc4758179a8fd9bf | /src/qt/qtipcserver.cpp | 6f11e6872782f2623c952dedcd5a849d7f110ec3 | [
"MIT"
] | permissive | ATXSilver/rawcoin | 1abaf526c3315ca9c4f722d5aa5262fd6c0631ea | d84b4b8371e61e0720423495484e939758d20a1b | refs/heads/master | 2021-01-20T16:39:01.004960 | 2014-09-16T19:49:59 | 2014-09-16T19:49:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,925 | cpp | // 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 <boost/version.hpp>
#if defined(WIN32) && BOOST_VERSION == 104900
#define BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME
#define BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME
#endif
#include "qtipcserver.h"
#include "guiconstants.h"
#include "ui_interface.h"
#include "util.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/version.hpp>
#if defined(WIN32) && (!defined(BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME) || !defined(BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME) || BOOST_VERSION < 104900)
#warning Compiling without BOOST_INTERPROCESS_HAS_WINDOWS_KERNEL_BOOTTIME and BOOST_INTERPROCESS_HAS_KERNEL_BOOTTIME uncommented in boost/interprocess/detail/tmp_dir_helpers.hpp or using a boost version before 1.49 may have unintended results see svn.boost.org/trac/boost/ticket/5392
#endif
using namespace boost;
using namespace boost::interprocess;
using namespace boost::posix_time;
#if defined MAC_OSX || defined __FreeBSD__
// URI handling not implemented on OSX yet
void ipcScanRelay(int argc, char *argv[]) { }
void ipcInit(int argc, char *argv[]) { }
#else
static void ipcThread2(void* pArg);
static bool ipcScanCmd(int argc, char *argv[], bool fRelay)
{
// Check for URI in argv
bool fSent = false;
for (int i = 1; i < argc; i++)
{
if (boost::algorithm::istarts_with(argv[i], "rawcoin:"))
{
const char *strURI = argv[i];
try {
boost::interprocess::message_queue mq(boost::interprocess::open_only, BITCOINURI_QUEUE_NAME);
if (mq.try_send(strURI, strlen(strURI), 0))
fSent = true;
else if (fRelay)
break;
}
catch (boost::interprocess::interprocess_exception &ex) {
// don't log the "file not found" exception, because that's normal for
// the first start of the first instance
if (ex.get_error_code() != boost::interprocess::not_found_error || !fRelay)
{
printf("main() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
break;
}
}
}
}
return fSent;
}
void ipcScanRelay(int argc, char *argv[])
{
if (ipcScanCmd(argc, argv, true))
exit(0);
}
static void ipcThread(void* pArg)
{
// Make this thread recognisable as the GUI-IPC thread
RenameThread("rawcoin-gui-ipc");
try
{
ipcThread2(pArg);
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ipcThread()");
} catch (...) {
PrintExceptionContinue(NULL, "ipcThread()");
}
printf("ipcThread exited\n");
}
static void ipcThread2(void* pArg)
{
printf("ipcThread started\n");
message_queue* mq = (message_queue*)pArg;
char buffer[MAX_URI_LENGTH + 1] = "";
size_t nSize = 0;
unsigned int nPriority = 0;
while (true)
{
ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(100);
if (mq->timed_receive(&buffer, sizeof(buffer), nSize, nPriority, d))
{
uiInterface.ThreadSafeHandleURI(std::string(buffer, nSize));
MilliSleep(1000);
}
if (fShutdown)
break;
}
// Remove message queue
message_queue::remove(BITCOINURI_QUEUE_NAME);
// Cleanup allocated memory
delete mq;
}
void ipcInit(int argc, char *argv[])
{
message_queue* mq = NULL;
char buffer[MAX_URI_LENGTH + 1] = "";
size_t nSize = 0;
unsigned int nPriority = 0;
try {
mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, MAX_URI_LENGTH);
// Make sure we don't lose any bitcoin: URIs
for (int i = 0; i < 2; i++)
{
ptime d = boost::posix_time::microsec_clock::universal_time() + millisec(1);
if (mq->timed_receive(&buffer, sizeof(buffer), nSize, nPriority, d))
{
uiInterface.ThreadSafeHandleURI(std::string(buffer, nSize));
}
else
break;
}
// Make sure only one bitcoin instance is listening
message_queue::remove(BITCOINURI_QUEUE_NAME);
delete mq;
mq = new message_queue(open_or_create, BITCOINURI_QUEUE_NAME, 2, MAX_URI_LENGTH);
}
catch (interprocess_exception &ex) {
printf("ipcInit() - boost interprocess exception #%d: %s\n", ex.get_error_code(), ex.what());
return;
}
if (!NewThread(ipcThread, mq))
{
delete mq;
return;
}
ipcScanCmd(argc, argv, false);
}
#endif
| [
"rawcoind@gmail.com"
] | rawcoind@gmail.com |
8103dda2fc4b72f5581ccf9394411d93ad186a01 | 01bcef56ade123623725ca78d233ac8653a91ece | /vgui2/vgui_controls/ProgressBar.cpp | 7cc0c628ffde6da4ae002579644d765e4ef1e410 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | SwagSoftware/Kisak-Strike | 1085ba3c6003e622dac5ebc0c9424cb16ef58467 | 4c2fdc31432b4f5b911546c8c0d499a9cff68a85 | refs/heads/master | 2023-09-01T02:06:59.187775 | 2022-09-05T00:51:46 | 2022-09-05T00:51:46 | 266,676,410 | 921 | 123 | null | 2022-10-01T16:26:41 | 2020-05-25T03:41:35 | C++ | WINDOWS-1252 | C++ | false | false | 12,708 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <vgui_controls/ProgressBar.h>
#include <vgui_controls/Controls.h>
#include <vgui/ILocalize.h>
#include <vgui/IScheme.h>
#include <vgui/ISurface.h>
#include <keyvalues.h>
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
using namespace vgui;
DECLARE_BUILD_FACTORY( ProgressBar );
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
ProgressBar::ProgressBar(Panel *parent, const char *panelName) : Panel(parent, panelName)
{
_progress = 0.0f;
m_pszDialogVar = NULL;
SetSegmentInfo( 4, 8 );
SetBarInset( 4 );
SetMargin( 0 );
m_iProgressDirection = PROGRESS_EAST;
}
//-----------------------------------------------------------------------------
// Purpose: Destructor
//-----------------------------------------------------------------------------
ProgressBar::~ProgressBar()
{
delete [] m_pszDialogVar;
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
void ProgressBar::SetSegmentInfo( int gap, int width )
{
_segmentGap = gap;
_segmentWide = width;
}
//-----------------------------------------------------------------------------
// Purpose: returns the number of segment blocks drawn
//-----------------------------------------------------------------------------
int ProgressBar::GetDrawnSegmentCount()
{
int wide, tall;
GetSize(wide, tall);
int segmentTotal = wide / (_segmentGap + _segmentWide);
return (int)(segmentTotal * _progress);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void ProgressBar::PaintBackground()
{
int wide, tall;
GetSize(wide, tall);
surface()->DrawSetColor(GetBgColor());
surface()->DrawFilledRect(0, 0, wide, tall);
}
void ProgressBar::PaintSegment( int &x, int &y, int tall, int wide )
{
switch( m_iProgressDirection )
{
case PROGRESS_EAST:
x += _segmentGap;
surface()->DrawFilledRect(x, y, x + _segmentWide, y + tall - (y * 2));
x += _segmentWide;
break;
case PROGRESS_WEST:
x -= _segmentGap + _segmentWide;
surface()->DrawFilledRect(x, y, x + _segmentWide, y + tall - (y * 2));
break;
case PROGRESS_NORTH:
y -= _segmentGap + _segmentWide;
surface()->DrawFilledRect(x, y, x + wide - (x * 2), y + _segmentWide );
break;
case PROGRESS_SOUTH:
y += _segmentGap;
surface()->DrawFilledRect(x, y, x + wide - (x * 2), y + _segmentWide );
y += _segmentWide;
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void ProgressBar::Paint()
{
int wide, tall;
GetSize(wide, tall);
// gaps
int segmentTotal = 0, segmentsDrawn = 0;
int x = 0, y = 0;
switch( m_iProgressDirection )
{
case PROGRESS_WEST:
wide -= 2 * m_iBarMargin;
x = wide - m_iBarMargin;
y = m_iBarInset;
segmentTotal = wide / (_segmentGap + _segmentWide);
segmentsDrawn = (int)(segmentTotal * _progress);
break;
case PROGRESS_EAST:
wide -= 2 * m_iBarMargin;
x = m_iBarMargin;
y = m_iBarInset;
segmentTotal = wide / (_segmentGap + _segmentWide);
segmentsDrawn = (int)(segmentTotal * _progress);
break;
case PROGRESS_NORTH:
tall -= 2 * m_iBarMargin;
x = m_iBarInset;
y = tall - m_iBarMargin;
segmentTotal = tall / (_segmentGap + _segmentWide);
segmentsDrawn = (int)(segmentTotal * _progress);
break;
case PROGRESS_SOUTH:
tall -= 2 * m_iBarMargin;
x = m_iBarInset;
y = m_iBarMargin;
segmentTotal = tall / (_segmentGap + _segmentWide);
segmentsDrawn = (int)(segmentTotal * _progress);
break;
}
surface()->DrawSetColor(GetFgColor());
for (int i = 0; i < segmentsDrawn; i++)
{
PaintSegment( x, y, tall, wide );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void ProgressBar::SetProgress(float progress)
{
if (progress != _progress)
{
// clamp the progress value within the range
if (progress < 0.0f)
{
progress = 0.0f;
}
else if (progress > 1.0f)
{
progress = 1.0f;
}
_progress = progress;
Repaint();
}
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
float ProgressBar::GetProgress()
{
return _progress;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void ProgressBar::ApplySchemeSettings(IScheme *pScheme)
{
Panel::ApplySchemeSettings(pScheme);
SetFgColor(GetSchemeColor("ProgressBar.FgColor", pScheme));
SetBgColor(GetSchemeColor("ProgressBar.BgColor", pScheme));
SetBorder(pScheme->GetBorder("ButtonDepressedBorder"));
}
//-----------------------------------------------------------------------------
// Purpose: utility function for calculating a time remaining string
//-----------------------------------------------------------------------------
bool ProgressBar::ConstructTimeRemainingString(wchar_t *output, int outputBufferSizeInBytes, float startTime, float currentTime, float currentProgress, float lastProgressUpdateTime, bool addRemainingSuffix)
{
Assert(lastProgressUpdateTime <= currentTime);
output[0] = 0;
// calculate pre-extrapolation values
float timeElapsed = lastProgressUpdateTime - startTime;
float totalTime = timeElapsed / currentProgress;
// calculate seconds
int secondsRemaining = (int)(totalTime - timeElapsed);
if (lastProgressUpdateTime < currentTime)
{
// old update, extrapolate
float progressRate = currentProgress / timeElapsed;
float extrapolatedProgress = progressRate * (currentTime - startTime);
float extrapolatedTotalTime = (currentTime - startTime) / extrapolatedProgress;
secondsRemaining = (int)(extrapolatedTotalTime - timeElapsed);
}
// if there's some time, make sure it's at least one second left
if ( secondsRemaining == 0 && ( ( totalTime - timeElapsed ) > 0 ) )
{
secondsRemaining = 1;
}
// calculate minutes
int minutesRemaining = 0;
while (secondsRemaining >= 60)
{
minutesRemaining++;
secondsRemaining -= 60;
}
char minutesBuf[16];
Q_snprintf(minutesBuf, sizeof( minutesBuf ), "%d", minutesRemaining);
char secondsBuf[16];
Q_snprintf(secondsBuf, sizeof( secondsBuf ), "%d", secondsRemaining);
if (minutesRemaining > 0)
{
wchar_t unicodeMinutes[16];
g_pVGuiLocalize->ConvertANSIToUnicode(minutesBuf, unicodeMinutes, sizeof( unicodeMinutes ));
wchar_t unicodeSeconds[16];
g_pVGuiLocalize->ConvertANSIToUnicode(secondsBuf, unicodeSeconds, sizeof( unicodeSeconds ));
const char *unlocalizedString = "#vgui_TimeLeftMinutesSeconds";
if (minutesRemaining == 1 && secondsRemaining == 1)
{
unlocalizedString = "#vgui_TimeLeftMinuteSecond";
}
else if (minutesRemaining == 1)
{
unlocalizedString = "#vgui_TimeLeftMinuteSeconds";
}
else if (secondsRemaining == 1)
{
unlocalizedString = "#vgui_TimeLeftMinutesSecond";
}
char unlocString[64];
Q_strncpy(unlocString, unlocalizedString,sizeof( unlocString ));
if (addRemainingSuffix)
{
Q_strncat(unlocString, "Remaining", sizeof(unlocString ), COPY_ALL_CHARACTERS);
}
g_pVGuiLocalize->ConstructString(output, outputBufferSizeInBytes, g_pVGuiLocalize->Find(unlocString), 2, unicodeMinutes, unicodeSeconds);
}
else if (secondsRemaining > 0)
{
wchar_t unicodeSeconds[16];
g_pVGuiLocalize->ConvertANSIToUnicode(secondsBuf, unicodeSeconds, sizeof( unicodeSeconds ));
const char *unlocalizedString = "#vgui_TimeLeftSeconds";
if (secondsRemaining == 1)
{
unlocalizedString = "#vgui_TimeLeftSecond";
}
char unlocString[64];
Q_strncpy(unlocString, unlocalizedString,sizeof(unlocString));
if (addRemainingSuffix)
{
Q_strncat(unlocString, "Remaining",sizeof(unlocString), COPY_ALL_CHARACTERS);
}
g_pVGuiLocalize->ConstructString(output, outputBufferSizeInBytes, g_pVGuiLocalize->Find(unlocString), 1, unicodeSeconds);
}
else
{
return false;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
void ProgressBar::SetBarInset( int pixels )
{
m_iBarInset = pixels;
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
int ProgressBar::GetBarInset( void )
{
return m_iBarInset;
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
void ProgressBar::SetMargin( int pixels )
{
m_iBarMargin = pixels;
}
//-----------------------------------------------------------------------------
// Purpose: data accessor
//-----------------------------------------------------------------------------
int ProgressBar::GetMargin()
{
return m_iBarMargin;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void ProgressBar::ApplySettings(KeyValues *inResourceData)
{
_progress = inResourceData->GetFloat("progress", 0.0f);
const char *dialogVar = inResourceData->GetString("variable", "");
if (dialogVar && *dialogVar)
{
delete[] m_pszDialogVar;
m_pszDialogVar = new char[strlen(dialogVar) + 1];
strcpy(m_pszDialogVar, dialogVar);
}
BaseClass::ApplySettings(inResourceData);
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void ProgressBar::GetSettings(KeyValues *outResourceData)
{
BaseClass::GetSettings(outResourceData);
outResourceData->SetFloat("progress", _progress );
if (m_pszDialogVar)
{
outResourceData->SetString("variable", m_pszDialogVar);
}
}
//-----------------------------------------------------------------------------
// Purpose: Returns a string description of the panel fields for use in the UI
//-----------------------------------------------------------------------------
const char *ProgressBar::GetDescription( void )
{
static char buf[1024];
_snprintf(buf, sizeof(buf), "%s, string progress, string variable", BaseClass::GetDescription());
return buf;
}
//-----------------------------------------------------------------------------
// Purpose: updates progress bar bases on values
//-----------------------------------------------------------------------------
void ProgressBar::OnDialogVariablesChanged(KeyValues *dialogVariables)
{
if (m_pszDialogVar)
{
int val = dialogVariables->GetInt(m_pszDialogVar, -1);
if (val >= 0.0f)
{
SetProgress(val / 100.0f);
}
}
}
DECLARE_BUILD_FACTORY( ContinuousProgressBar );
//-----------------------------------------------------------------------------
// Purpose: Constructor
//-----------------------------------------------------------------------------
ContinuousProgressBar::ContinuousProgressBar(Panel *parent, const char *panelName) : ProgressBar(parent, panelName)
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void ContinuousProgressBar::Paint()
{
int x = 0, y = 0;
int wide, tall;
GetSize(wide, tall);
surface()->DrawSetColor(GetFgColor());
switch( m_iProgressDirection )
{
case PROGRESS_EAST:
surface()->DrawFilledRect( x, y, x + (int)( wide * _progress ), y + tall );
break;
case PROGRESS_WEST:
surface()->DrawFilledRect( x + (int)( wide * ( 1.0f - _progress ) ), y, x + wide, y + tall );
break;
case PROGRESS_NORTH:
surface()->DrawFilledRect( x, y + (int)( tall * ( 1.0f - _progress ) ), x + wide, y + tall );
break;
case PROGRESS_SOUTH:
surface()->DrawFilledRect( x, y, x + wide, y + (int)( tall * _progress ) );
break;
}
}
| [
"bbchallenger100@gmail.com"
] | bbchallenger100@gmail.com |
212a7a428881c10a96bf86fe9349bbcb730302ef | 3fdb0447dbb68c77262f8d7a87342577a2ef32f8 | /test/unittests/compiler/graph-unittest.h | 18d3ca558d35781a3330cfcd6ed49d5dda3120db | [
"BSD-3-Clause",
"bzip2-1.0.6"
] | permissive | AbhiAgarwal/v8 | 102f072135b3640e03f248f8942bb4c9d77b2f63 | 232c2ae265f31bb3d601c839b36c92506367e454 | refs/heads/master | 2022-11-08T21:17:59.806926 | 2014-10-07T04:58:34 | 2014-10-07T04:58:34 | 24,877,336 | 1 | 1 | NOASSERTION | 2022-10-27T05:58:00 | 2014-10-07T04:58:07 | C++ | UTF-8 | C++ | false | false | 6,744 | h | // Copyright 2014 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_UNITTESTS_COMPILER_GRAPH_UNITTEST_H_
#define V8_UNITTESTS_COMPILER_GRAPH_UNITTEST_H_
#include "src/compiler/common-operator.h"
#include "src/compiler/graph.h"
#include "src/compiler/machine-operator.h"
#include "test/unittests/test-utils.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace v8 {
namespace internal {
// Forward declarations.
class HeapObject;
template <class T>
class Unique;
namespace compiler {
using ::testing::Matcher;
class GraphTest : public TestWithContext, public TestWithZone {
public:
explicit GraphTest(int parameters = 1);
virtual ~GraphTest();
protected:
Node* Parameter(int32_t index);
Node* Float32Constant(volatile float value);
Node* Float64Constant(volatile double value);
Node* Int32Constant(int32_t value);
Node* Int64Constant(int64_t value);
Node* NumberConstant(volatile double value);
Node* HeapConstant(const Unique<HeapObject>& value);
Node* FalseConstant();
Node* TrueConstant();
Matcher<Node*> IsFalseConstant();
Matcher<Node*> IsTrueConstant();
CommonOperatorBuilder* common() { return &common_; }
Graph* graph() { return &graph_; }
private:
CommonOperatorBuilder common_;
Graph graph_;
};
Matcher<Node*> IsBranch(const Matcher<Node*>& value_matcher,
const Matcher<Node*>& control_matcher);
Matcher<Node*> IsMerge(const Matcher<Node*>& control0_matcher,
const Matcher<Node*>& control1_matcher);
Matcher<Node*> IsIfTrue(const Matcher<Node*>& control_matcher);
Matcher<Node*> IsIfFalse(const Matcher<Node*>& control_matcher);
Matcher<Node*> IsValueEffect(const Matcher<Node*>& value_matcher);
Matcher<Node*> IsFinish(const Matcher<Node*>& value_matcher,
const Matcher<Node*>& effect_matcher);
Matcher<Node*> IsExternalConstant(
const Matcher<ExternalReference>& value_matcher);
Matcher<Node*> IsHeapConstant(
const Matcher<Unique<HeapObject> >& value_matcher);
Matcher<Node*> IsFloat32Constant(const Matcher<float>& value_matcher);
Matcher<Node*> IsFloat64Constant(const Matcher<double>& value_matcher);
Matcher<Node*> IsInt32Constant(const Matcher<int32_t>& value_matcher);
Matcher<Node*> IsInt64Constant(const Matcher<int64_t>& value_matcher);
Matcher<Node*> IsNumberConstant(const Matcher<double>& value_matcher);
Matcher<Node*> IsPhi(const Matcher<MachineType>& type_matcher,
const Matcher<Node*>& value0_matcher,
const Matcher<Node*>& value1_matcher,
const Matcher<Node*>& merge_matcher);
Matcher<Node*> IsProjection(const Matcher<size_t>& index_matcher,
const Matcher<Node*>& base_matcher);
Matcher<Node*> IsCall(const Matcher<CallDescriptor*>& descriptor_matcher,
const Matcher<Node*>& value0_matcher,
const Matcher<Node*>& value1_matcher,
const Matcher<Node*>& value2_matcher,
const Matcher<Node*>& value3_matcher,
const Matcher<Node*>& effect_matcher,
const Matcher<Node*>& control_matcher);
Matcher<Node*> IsNumberLessThan(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher);
Matcher<Node*> IsNumberSubtract(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher);
Matcher<Node*> IsLoad(const Matcher<LoadRepresentation>& rep_matcher,
const Matcher<Node*>& base_matcher,
const Matcher<Node*>& index_matcher,
const Matcher<Node*>& effect_matcher,
const Matcher<Node*>& control_matcher);
Matcher<Node*> IsStore(const Matcher<MachineType>& type_matcher,
const Matcher<WriteBarrierKind>& write_barrier_matcher,
const Matcher<Node*>& base_matcher,
const Matcher<Node*>& index_matcher,
const Matcher<Node*>& value_matcher,
const Matcher<Node*>& effect_matcher,
const Matcher<Node*>& control_matcher);
Matcher<Node*> IsWord32And(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher);
Matcher<Node*> IsWord32Sar(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher);
Matcher<Node*> IsWord32Shl(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher);
Matcher<Node*> IsWord32Ror(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher);
Matcher<Node*> IsWord32Equal(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher);
Matcher<Node*> IsWord64And(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher);
Matcher<Node*> IsWord64Shl(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher);
Matcher<Node*> IsWord64Sar(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher);
Matcher<Node*> IsWord64Equal(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher);
Matcher<Node*> IsInt32AddWithOverflow(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher);
Matcher<Node*> IsInt32Mul(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher);
Matcher<Node*> IsUint32LessThanOrEqual(const Matcher<Node*>& lhs_matcher,
const Matcher<Node*>& rhs_matcher);
Matcher<Node*> IsChangeFloat64ToInt32(const Matcher<Node*>& input_matcher);
Matcher<Node*> IsChangeFloat64ToUint32(const Matcher<Node*>& input_matcher);
Matcher<Node*> IsChangeInt32ToFloat64(const Matcher<Node*>& input_matcher);
Matcher<Node*> IsChangeInt32ToInt64(const Matcher<Node*>& input_matcher);
Matcher<Node*> IsChangeUint32ToFloat64(const Matcher<Node*>& input_matcher);
Matcher<Node*> IsChangeUint32ToUint64(const Matcher<Node*>& input_matcher);
Matcher<Node*> IsTruncateFloat64ToFloat32(const Matcher<Node*>& input_matcher);
Matcher<Node*> IsTruncateFloat64ToInt32(const Matcher<Node*>& input_matcher);
Matcher<Node*> IsTruncateInt64ToInt32(const Matcher<Node*>& input_matcher);
Matcher<Node*> IsFloat64Sqrt(const Matcher<Node*>& input_matcher);
} // namespace compiler
} // namespace internal
} // namespace v8
#endif // V8_UNITTESTS_COMPILER_GRAPH_UNITTEST_H_
| [
"me@abhiagarwal.com"
] | me@abhiagarwal.com |
3b1f2eeedd846cf62afd10fc30e0e67c9e49ccf7 | bfdb0a0da7d08dd4675f7ab96a0ae67df27f2083 | /C++/tutorial/userinput.cpp | 81f5b0fc12c6a206b47e38e8a1742cedb7ad2cf9 | [] | no_license | mixlaab/myWork | 7ecf213055eb420182e9520c67256ec5021dadb7 | b9bc13bd5e06a623c7d754e1c51b911184c00024 | refs/heads/master | 2021-06-17T05:01:31.883862 | 2020-05-09T18:29:16 | 2020-05-09T18:29:16 | 147,020,987 | 0 | 0 | null | 2021-02-08T20:27:47 | 2018-09-01T18:01:25 | JavaScript | UTF-8 | C++ | false | false | 299 | cpp | #include<iostream>
using namespace std;
int main(int argc, char const *argv[])
{
int age;
cout << "How old are you?" << endl;
cin >> age;
if(age < 18){
cout << "You're underage" << endl;
}
else {
cout << "You're a grown man" << endl;
}
return 0;
}
| [
"mixlaab.labs@gmail.com"
] | mixlaab.labs@gmail.com |
2104578047a8bebfa877b70b92985311f7e5e16d | 16dd60bd2e542a455ded1108329a8635d43d9a49 | /lib/Basic/Targets/Leros.h | 438e43f0afa05920707cd2b0efa18dc215364dce | [
"NCSA"
] | permissive | leros-dev/leros-clang | c7089c88b58d146ff9ee6ae804366e0f93ad026e | ba93d76b060e90d82b2f3f3ccc6488c308790562 | refs/heads/master | 2020-04-02T18:45:34.506745 | 2018-11-18T14:27:26 | 2018-11-18T14:27:26 | 154,712,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,092 | h | //===--- Leros.h - Declare Leros target feature support ---------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file declares Leros TargetInfo objects.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_LIB_BASIC_TARGETS_Leros_H
#define LLVM_CLANG_LIB_BASIC_TARGETS_Leros_H
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TargetOptions.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/Compiler.h"
namespace clang {
namespace targets {
// RISC-V Target
class LerosTargetInfo : public TargetInfo {
protected:
std::string ABI;
public:
LerosTargetInfo(const llvm::Triple &Triple, const TargetOptions &)
: TargetInfo(Triple) {
TLSSupported = false;
LongDoubleWidth = 128;
LongDoubleAlign = 128;
LongDoubleFormat = &llvm::APFloat::IEEEquad();
SuitableAlign = 128;
WCharType = SignedInt;
WIntType = UnsignedInt;
}
StringRef getABI() const override { return ABI; }
void getTargetDefines(const LangOptions &Opts,
MacroBuilder &Builder) const override;
ArrayRef<Builtin::Info> getTargetBuiltins() const override { return None; }
BuiltinVaListKind getBuiltinVaListKind() const override {
return TargetInfo::VoidPtrBuiltinVaList;
}
const char *getClobbers() const override { return ""; }
ArrayRef<const char *> getGCCRegNames() const override;
ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override;
bool validateAsmConstraint(const char *&Name,
TargetInfo::ConstraintInfo &Info) const override {
return false;
}
bool hasFeature(StringRef Feature) const override;
};
class LLVM_LIBRARY_VISIBILITY Leros32TargetInfo : public LerosTargetInfo {
public:
Leros32TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
: LerosTargetInfo(Triple, Opts) {
IntPtrType = SignedInt;
PtrDiffType = SignedInt;
SizeType = UnsignedInt;
resetDataLayout("e-m:e-p:32:32-i64:64-n32-S128");
}
bool setABI(const std::string &Name) override {
// TODO: support ilp32f and ilp32d ABIs.
if (Name == "ilp32") {
ABI = Name;
return true;
}
return false;
}
};
class LLVM_LIBRARY_VISIBILITY Leros64TargetInfo : public LerosTargetInfo {
public:
Leros64TargetInfo(const llvm::Triple &Triple, const TargetOptions &Opts)
: LerosTargetInfo(Triple, Opts) {
LongWidth = LongAlign = PointerWidth = PointerAlign = 64;
IntMaxType = Int64Type = SignedLong;
resetDataLayout("e-m:e-p:64:64-i64:64-i128:128-n64-S128");
}
bool setABI(const std::string &Name) override {
// TODO: support lp64f and lp64d ABIs.
if (Name == "lp64") {
ABI = Name;
return true;
}
return false;
}
};
} // namespace targets
} // namespace clang
#endif // LLVM_CLANG_LIB_BASIC_TARGETS_Leros_H
| [
"morten_bp@live.dk"
] | morten_bp@live.dk |
ae8b8d6abb2d31f2588e05ececc6a95a4ca25107 | 5c99de57e85d7c20f90fab2576bcccae3468e32c | /q412/q412/q412.cpp | 585ec17af074bf0d31a1ae23a0088ebaa03422e0 | [] | no_license | joesilverstein/cs-homeworks | 311a98ea957c69b1b489877d9ae0a02e421d579c | cd918bbecd320cdb59e755086d0dc2fd9ae21ad3 | refs/heads/master | 2021-01-11T05:39:12.266745 | 2016-10-22T00:59:23 | 2016-10-22T00:59:23 | 71,607,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,806 | cpp | /********************************************
** q412.cpp
** Looks up employee records in a class hierarchy.
** Joseph Silverstein, 4/4/11
*********************************************/
#include <iostream>
#include <string>
#include <fstream>
#include <map>
#include "employee_classes.h"
using namespace std;
/* given an iterator pointing to an employee record in the master_list,
** prints the record in an easy to read format
void printRecord(list<Employee>::iterator iter) {
cout << "Name: " << iter->get_name() << '\n'
<< "ID: " << iter->get_ID() << '\n'
<< "Age: " << iter->get_age() << '\n'
<< "Weight: " << iter->get_weight() << '\n'
<< "Salary: " << iter->get_salary();
cout << "\n\n";
return;
}*/
int main() {
char choice = 'y'; // either 'y' or 'n'
string filename; // name of the file
string employeeName; // format: "firstName lastName"
Employee tempEmployee; // for reading in file
ifstream fin; // for reading in file
//istream in; // for reading in types of employees
char type; // the type of employee
map<string, Employee*> names; //maps names to employees
cout << "Enter file name: ";
cin >> filename;
fin.open(filename.c_str());
// reads in data and organizes it into a linked list of Employee objects
while (fin >> tempEmployee) {
//in >> type;
// constructs hash table to map employee full names to newly-allocated employee objects
names[tempEmployee.get_firstName() + " " + tempEmployee.get_lastName()] = new Employee(tempEmployee);
}
fin.close();
// user can repeat as many times as needed
while (choice == 'y') {
cout << "Enter employee name: ";
cin >> employeeName;
//names[employeeName]->print(); //print record (calls different fxn for each type)
}
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
9eb7c62cc73bafaa9a617c0c4c51a8a16e6c5dda | 82fba7822cce0376e242019679ef9bdae7231ad3 | /ABACUS/source/src_parallel/parallel_common.cpp | ab6021a0c8ee45b183aff55eeb6ad59f5dbd5425 | [] | no_license | abacus-ustc/abacus-GPU | 968bf7f7f91b3922ff43ff332438fbeacc748fd1 | d326fe411c8cdd718ac101693645da3bc17b4a19 | refs/heads/master | 2023-04-15T08:07:00.917906 | 2021-04-09T16:50:34 | 2021-04-09T16:50:34 | 346,221,292 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,135 | cpp | #include "parallel_common.h"
#include <cstring>
#ifdef __MPI
void Parallel_Common::bcast_string(string &object) // Peize Lin fix bug 2019-03-18
{
int size = object.size();
MPI_Bcast(&size, 1, MPI_INT, 0, MPI_COMM_WORLD);
char *swap = new char[size+1];
if(0==MY_RANK) strcpy(swap, object.c_str());
MPI_Bcast(swap, size+1, MPI_CHAR, 0, MPI_COMM_WORLD);
if(0!=MY_RANK) object = static_cast<string>(swap);
delete[] swap;
return;
}
void Parallel_Common::bcast_string(string *object,const int n) // Peize Lin fix bug 2019-03-18
{
for(int i=0;i<n;i++)
bcast_string(object[i]);
return;
}
void Parallel_Common::bcast_complex_double(complex<double> &object)
{
double a = object.real();
double b = object.imag();
Parallel_Common::bcast_double(a);
Parallel_Common::bcast_double(b);
object = complex<double>( a, b);
return;
}
void Parallel_Common::bcast_complex_double(complex<double> *object, const int n)
{
double *a = new double[n];
double *b = new double[n];
for(int i=0; i<n; i++)
{
a[i] = object[i].real();
b[i] = object[i].imag();
}
Parallel_Common::bcast_double( a, n);
Parallel_Common::bcast_double( b, n);
for(int i=0; i<n; i++)
{
object[i] = complex<double>( a[i], b[i]);
}
delete[] a;
delete[] b;
}
void Parallel_Common::bcast_double(double &object)
{
MPI_Bcast(&object, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
// cout<<"\n"<<object;
return;
}
void Parallel_Common::bcast_double(double *object,const int n)
{
MPI_Bcast(object, n, MPI_DOUBLE, 0, MPI_COMM_WORLD);
}
void Parallel_Common::bcast_int(int &object)
{
MPI_Bcast(&object, 1, MPI_INT, 0, MPI_COMM_WORLD);
// cout<<"\n"<<object;
return;
}
void Parallel_Common::bcast_int(int *object,const int n)
{
MPI_Bcast(object,n,MPI_INT,0,MPI_COMM_WORLD);
}
void Parallel_Common::bcast_bool(bool &object)
{
int swap = object;
if(MY_RANK == 0)swap = object;
MPI_Bcast(&swap, 1, MPI_INT, 0, MPI_COMM_WORLD);
if(MY_RANK != 0)object = static_cast<bool>( swap );
// cout<<"\n"<<object;
return;
}
void Parallel_Common::bcast_char(char *object,const int n)
{
MPI_Bcast(object, n, MPI_CHAR, 0, MPI_COMM_WORLD);
return;
}
#endif
| [
"liuxiaohui@ustc.edu.cn"
] | liuxiaohui@ustc.edu.cn |
e79fcf17fee7ec974914a4f9a1203fde3a437bc0 | 524197c3058db52a4214b2c9789726721dae6b8e | /UVSphere.h | 5fb3a6f5c797f4c44f41a86df01d6dd0476287c0 | [] | no_license | rdenardis1/RayTracer | 6fedd8c08b001e2c4ebcdceb27c862e0ddb1c873 | a9e1b101fa20fcd0dd5a8991e773b9927433a661 | refs/heads/master | 2021-01-10T19:10:50.826970 | 2013-11-30T21:12:38 | 2013-11-30T21:12:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 471 | h | #ifndef UV_SPHERE_H
#define UV_SPHERE_H
#include "Shape.h"
#include "Vector3D.h"
#include "Ray3D.h"
#include "Material.h"
class UVSphere : public Shape
{
public:
UVSphere(const Vector3D& _center, float _radius, Material* _material);
//BB
bool hit(const Ray3D& r, float tmin, float tmax, float time, HitRecord& record) const;
bool shadowHit(const Ray3D& r, float tmin, float tmax, float time) const;
Vector3D center;
float radius;
Material* material;
};
#endif | [
"rdenardis1@gmail.com"
] | rdenardis1@gmail.com |
bd0368f75f57ae414dc1b1fce5852bddafb545f6 | 1df9106e475d7f1b4de615cb4f8122cc93305b7b | /Engine/PhysicsObject.cpp | 8b491516b008c19554694e0b6164229ec3c97f4a | [] | no_license | mcferront/anttrap-engine | 54517007911389a347e25542c928a0dd4276b730 | c284f7800becaa973101a14bf0b7ffb0d6b732b4 | refs/heads/master | 2021-06-26T08:48:59.814404 | 2019-02-16T05:37:43 | 2019-02-16T05:37:43 | 148,593,261 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 269 | cpp | #include "EnginePch.h"
#include "PhysicsObject.h"
#include "PhysicsWorld.h"
void PhysicsObject::AddToScene( void )
{
PhysicsWorld::Instance( ).AddObject( this );
}
void PhysicsObject::RemoveFromScene( void )
{
PhysicsWorld::Instance( ).RemoveObject( this );
}
| [
"trapper@trapzz.com"
] | trapper@trapzz.com |
1e2c67b611d44d275ce310dedd88e7892d4ebfb4 | ace2c6066a887b0f3aef3f6b1cbf17541cfbb71c | /lib/parsertl14/parsertl/debug.hpp | 7c9059f91b81655abe6f4009866311d22d392f26 | [
"BSD-2-Clause",
"BSL-1.0"
] | permissive | niac/parle | ef05105ff33b9e1c4700ec54920ef44178988c84 | 022be01d0a235e3eb795271795f88bf4478fc604 | refs/heads/master | 2021-08-16T09:44:46.256724 | 2017-11-19T14:15:30 | 2017-11-19T14:15:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,555 | hpp | // debug.hpp
// Copyright (c) 2014-2017 Ben Hanson (http://www.benhanson.net/)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file licence_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef PARSERTL_DEBUG_HPP
#define PARSERTL_DEBUG_HPP
#include "dfa.hpp"
#include <ostream>
#include "rules.hpp"
namespace parsertl
{
template<typename char_type>
class basic_debug
{
public:
using rules = basic_rules<char_type>;
using ostream = std::basic_ostream<char_type>;
static void dump(const rules &rules_, ostream &stream_)
{
const std::size_t start_ = rules_.start();
const production_vector &grammar_ = rules_.grammar();
const token_info_vector &tokens_info_ = rules_.tokens_info();
const std::size_t terminals_ = tokens_info_.size();
string_vector symbols_;
std::set<std::size_t> seen_;
token_map map_;
rules_.symbols(symbols_);
// Skip EOI token
for (std::size_t idx_ = 1, size_ = tokens_info_.size();
idx_ < size_; ++idx_)
{
const token_info &token_info_ = tokens_info_[idx_];
token_prec_assoc info_(token_info_._precedence,
token_info_._associativity);
typename token_map::iterator map_iter_ = map_.find(info_);
if (map_iter_ == map_.end())
{
map_.insert(token_pair(info_, symbols_[idx_]));
}
else
{
map_iter_->second += ' ';
map_iter_->second += symbols_[idx_];
}
}
for (const auto &pair_ : map_)
{
switch (pair_.first.second)
{
case rules::token_info::token:
token(stream_);
break;
case rules::token_info::precedence:
precedence(stream_);
break;
case rules::token_info::nonassoc:
nonassoc(stream_);
break;
case rules::token_info::left:
left(stream_);
break;
case rules::token_info::right:
right(stream_);
break;
}
stream_ << pair_.second << '\n';
}
if (start_ != static_cast<std::size_t>(~0))
{
stream_ << '\n';
start(stream_);
stream_ << symbols_[terminals_ + start_] << '\n' << '\n';
}
stream_ << '%' << '%' << '\n' << '\n';
for (auto iter_ = grammar_.cbegin(), end_ = grammar_.cend();
iter_ != end_; ++iter_)
{
if (seen_.find(iter_->_lhs) == seen_.end())
{
auto lhs_iter_ = iter_;
std::size_t index_ = lhs_iter_ - grammar_.begin();
stream_ << symbols_[terminals_ + lhs_iter_->_lhs];
stream_ << ':';
while (index_ != ~0)
{
if (lhs_iter_->_rhs.first.empty())
{
stream_ << ' ';
empty(stream_);
}
else
{
auto rhs_iter_ = lhs_iter_->_rhs.first.cbegin();
auto rhs_end_ = lhs_iter_->_rhs.first.cend();
for (; rhs_iter_ != rhs_end_; ++rhs_iter_)
{
const std::size_t id_ =
rhs_iter_->_type == symbol::TERMINAL ?
rhs_iter_->_id :
terminals_ + rhs_iter_->_id;
// Don't dump '$'
if (id_ > 0)
{
stream_ << ' ' << symbols_[id_];
}
}
}
if (!lhs_iter_->_rhs.second.empty())
{
stream_ << ' ';
prec(stream_);
stream_ << lhs_iter_->_rhs.second;
}
index_ = lhs_iter_->_next_lhs;
if (index_ != ~0)
{
const string &lhs_ =
symbols_[terminals_ + lhs_iter_->_lhs];
lhs_iter_ = grammar_.begin() + index_;
stream_ << '\n';
for (std::size_t i_ = 0, size_ = lhs_.size();
i_ < size_; ++i_)
{
stream_ << ' ';
}
stream_ << '|';
}
}
seen_.insert(iter_->_lhs);
stream_ << ';' << '\n' << '\n';
}
}
stream_ << '%' << '%' << '\n';
}
static void dump(const rules &rules_, const dfa &dfa_, ostream &stream_)
{
const production_vector &grammar_ = rules_.grammar();
const std::size_t terminals_ = rules_.tokens_info().size();
string_vector symbols_;
rules_.symbols(symbols_);
for (std::size_t idx_ = 0, dfa_size_ = dfa_.size();
idx_ < dfa_size_; ++idx_)
{
const dfa_state &state_ = dfa_[idx_];
const size_t_pair_vector &config_ = state_._closure;
state(idx_, stream_);
for (const auto &pair_ : config_)
{
const production &p_ = grammar_[pair_.first];
std::size_t j_ = 0;
stream_ << ' ' << ' ' << symbols_[terminals_ + p_._lhs] <<
' ' << '-' << '>';
for (; j_ < p_._rhs.size(); ++j_)
{
const symbol &symbol_ = p_._rhs[j_];
const std::size_t id_ = symbol_._type == symbol::TERMINAL ?
symbol_._id :
terminals_ + symbol_._id;
if (j_ == pair_.second)
{
stream_ << ' ' << '.';
}
stream_ << ' ' << symbols_[id_];
}
if (j_ == pair_.second)
{
stream_ << ' ' << '.';
}
stream_ << '\n';
}
if (!state_._transitions.empty())
stream_ << '\n';
for (const auto &pair_ : state_._transitions)
{
stream_ << ' ' << ' ' << symbols_[pair_.first] << ' ' << '-' <<
'>' << ' ' << pair_.second << '\n';
}
stream_ << '\n';
}
}
private:
using production = typename rules::production;
using production_vector = typename rules::production_vector;
using string = std::basic_string<char_type>;
using string_vector = typename rules::string_vector;
using symbol = typename rules::symbol;
using token_prec_assoc =
std::pair<std::size_t, typename rules::token_info::associativity>;
using token_info = typename rules::token_info;
using token_info_vector = typename rules::token_info_vector;
using token_map = std::map<token_prec_assoc, string>;
using token_pair = std::pair<token_prec_assoc, string>;
static void empty(std::ostream &stream_)
{
stream_ << "%empty";
}
static void empty(std::wostream &stream_)
{
stream_ << L"%empty";
}
static void left(std::ostream &stream_)
{
stream_ << "%left ";
}
static void left(std::wostream &stream_)
{
stream_ << L"%left ";
}
static void nonassoc(std::ostream &stream_)
{
stream_ << "%nonassoc ";
}
static void nonassoc(std::wostream &stream_)
{
stream_ << L"%nonassoc ";
}
static void prec(std::ostream &stream_)
{
stream_ << "%prec ";
}
static void prec(std::wostream &stream_)
{
stream_ << L"%prec ";
}
static void precedence(std::ostream &stream_)
{
stream_ << "%precedence ";
}
static void precedence(std::wostream &stream_)
{
stream_ << L"%precedence ";
}
static void right(std::ostream &stream_)
{
stream_ << "%right ";
}
static void right(std::wostream &stream_)
{
stream_ << L"%right ";
}
static void start(std::ostream &stream_)
{
stream_ << "%start ";
}
static void start(std::wostream &stream_)
{
stream_ << L"%start ";
}
static void state(const std::size_t row_, std::ostream &stream_)
{
stream_ << "state " << row_ << '\n' << '\n';
}
static void state(const std::size_t row_, std::wostream &stream_)
{
stream_ << L"state " << row_ << L'\n' << L'\n';
}
static void token(std::ostream &stream_)
{
stream_ << "%token ";
}
static void token(std::wostream &stream_)
{
stream_ << L"%token ";
}
};
using debug = basic_debug<char>;
using wdebug = basic_debug<wchar_t>;
}
#endif
| [
"ab@php.net"
] | ab@php.net |
405b811860f15a5b97ef206ac522c646b9f8b874 | faf1dcdfd557c10f5bc250d6935e9b36687ec6f9 | /src/cpp/ee/core/Platform.cpp | 403eb07c185838ddc359846b8c7032bb54550635 | [
"MIT"
] | permissive | ndpduc/ee-x | 3ead7e6a6285532b6c42dc412b53b76f27bc25ad | 1de6dad6c52a1c9a1f5798b48b9c1dee34ac1ead | refs/heads/master | 2023-04-19T23:51:04.325853 | 2021-05-06T11:31:25 | 2021-05-06T11:31:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,941 | cpp | //
// PlatformUtils.cpp
// Pods
//
// Created by eps on 6/16/20.
//
#include "ee/core/Platform.hpp"
#include <ee/nlohmann/json.hpp>
#include "ee/core/IMessageBridge.hpp"
#include "ee/core/Task.hpp"
#include "ee/core/Utils.hpp"
namespace ee {
namespace core {
namespace {
// clang-format off
const std::string kPrefix = "Platform_";
const auto kIsApplicationInstalled = kPrefix + "isApplicationInstalled";
const auto kOpenApplication = kPrefix + "openApplication";
const auto kGetApplicationId = kPrefix + "getApplicationId";
const auto kGetApplicationName = kPrefix + "getApplicationName";
const auto kGetVersionName = kPrefix + "getVersionName";
const auto kGetVersionCode = kPrefix + "getVersionCode";
const auto kGetApplicationSignatures = kPrefix + "getApplicationSignatures";
const auto kIsInstantApp = kPrefix + "isInstantApp";
const auto kIsTablet = kPrefix + "isTablet";
const auto kGetDensity = kPrefix + "getDensity";
const auto kGetViewSize = kPrefix + "getViewSize";
const auto kGetScreenSize = kPrefix + "getScreenSize";
const auto kGetDeviceId = kPrefix + "getDeviceId";
const auto kGetSafeInset = kPrefix + "getSafeInset";
const auto kSendMail = kPrefix + "sendMail";
const auto kTestConnection = kPrefix + "testConnection";
const auto kShowInstallPrompt = kPrefix + "showInstallPrompt";
const auto kGetInstallReferrer = kPrefix + "getInstallReferrer";
// clang-format on
} // namespace
using Self = Platform;
IMessageBridge* Self::bridge_ = nullptr;
void Self::initialize(IMessageBridge& bridge) {
bridge_ = &bridge;
}
bool Self::isApplicationInstalled(const std::string& applicationId) {
auto response = bridge_->call(kIsApplicationInstalled, applicationId);
return toBool(response);
}
bool Self::openApplication(const std::string& applicationId) {
auto response = bridge_->call(kOpenApplication, applicationId);
return toBool(response);
}
std::string Self::getApplicationId() {
return bridge_->call(kGetApplicationId);
}
std::string Self::getApplicationName() {
return bridge_->call(kGetApplicationName);
}
std::string Self::getVersionName() {
return bridge_->call(kGetVersionName);
}
std::string Self::getVersionCode() {
return bridge_->call(kGetVersionCode);
}
std::string Self::getSHA1CertificateFingerprint() {
#ifdef EE_X_ANDROID
nlohmann::json request;
request["algorithm"] = "SHA1";
auto response = bridge_->call(kGetApplicationSignatures, request.dump());
auto json = nlohmann::json::parse(response);
auto signatures = json["signatures"];
return signatures.empty() ? "" : signatures[0];
#else // EE_X_ANDROID
return "";
#endif // EE_X_ANDROID
}
bool Self::isInstantApp() {
#ifdef EE_X_ANDROID
auto response = bridge_->call(kIsInstantApp);
return toBool(response);
#else // EE_X_ANDROID
return false;
#endif // EE_X_ANDROID
}
bool Self::isTablet() {
auto response = bridge_->call(kIsTablet);
return toBool(response);
}
float Self::getDensity() {
auto response = bridge_->call(kGetDensity);
return std::stof(response);
}
std::pair<int, int> Self::getViewSize() {
auto response = bridge_->call(kGetViewSize);
auto json = nlohmann::json::parse(response);
return std::pair(json["width"], json["height"]);
}
std::pair<int, int> Self::getScreenSize() {
auto response = bridge_->call(kGetScreenSize);
auto json = nlohmann::json::parse(response);
return std::pair(json["width"], json["height"]);
}
Task<std::string> Self::getDeviceId() {
auto response = co_await bridge_->callAsync(kGetDeviceId);
co_return response;
}
SafeInset Self::getSafeInset() {
SafeInset result;
#ifdef EE_X_ANDROID
auto response = bridge_->call(kGetSafeInset);
auto json = nlohmann::json::parse(response);
result.left = json["left"];
result.right = json["right"];
result.top = json["top"];
result.bottom = json["bottom"];
#else // EE_X_ANDROID
// TODO.
result.left = 0;
result.right = 0;
result.top = 0;
result.bottom = 0;
#endif // EE_X_ANDROID
return result;
}
bool Self::sendMail(const std::string& recipient, const std::string& subject,
const std::string& body) {
nlohmann::json json;
json["recipient"] = recipient;
json["subject"] = subject;
json["body"] = body;
auto response = bridge_->call(kSendMail, json.dump());
return toBool(response);
}
Task<bool> Self::testConnection(const std::string& hostName, float timeOut) {
nlohmann::json json;
json["host_name"] = hostName;
json["time_out"] = timeOut;
auto response = co_await bridge_->callAsync(kTestConnection, json.dump());
co_return toBool(response);
}
void Self::showInstallPrompt(const std::string& url,
const std::string& referrer) {
#ifdef EE_X_ANDROID
nlohmann::json json;
json["url"] = url;
json["referrer"] = referrer;
bridge_->call(kShowInstallPrompt, json.dump());
#endif // EE_X_ANDROID
}
Task<InstallReferrer> Self::getInstallReferrer() {
InstallReferrer result;
#ifdef EE_X_ANDROID
auto response = co_await bridge_->callAsync(kGetInstallReferrer);
result.raw = response;
#else // EE_X_ANDROID
result.raw = "";
#endif // EE_X_ANDROID
auto params = core::split(result.raw, "&");
std::map<std::string, std::string> m;
for (auto&& param : params) {
auto entries = core::split(param, "=");
if (entries.size() >= 2) {
m[entries[0]] = entries[1];
}
}
result.utm_source = m["utm_source"];
result.utm_medium = m["utm_medium"];
result.utm_term = m["utm_term"];
result.utm_content = m["utm_content"];
result.utm_campaign = m["utm_campaign"];
co_return result;
}
} // namespace core
} // namespace ee
| [
"enrevol@gmail.com"
] | enrevol@gmail.com |
e8fa6331eecf7ca5346a038159ea943d067d1d7e | 8ddea20623ae83dab4497879f9c962cf10a75e28 | /CheckersGame_Keith_R/CheckersGame_Keith_R/CheckerPiece.h | c87136e7ece8c8cae0591bc97ee47dbc72e4879b | [] | no_license | keithrmathman/FullCheckersGameWithAI | 69ef9528a6e80346c3e6d8635d9d0209144fa033 | 010a324f3ff4a82ef1c44229a400869f32952f1a | refs/heads/master | 2020-04-12T21:35:06.455649 | 2019-01-08T01:06:56 | 2019-01-08T01:06:56 | 162,765,699 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 493 | h | #pragma once
#include <iostream>
class CheckerPiece
{
public:
enum CheckerPieceType
{
KING,
SINGLE
};
enum CheckerPieceColor
{
RED,
BLACK
};
CheckerPiece();
CheckerPiece(CheckerPieceColor Ccolor, CheckerPieceType Ctype);
~CheckerPiece();
//set new checker coordinates
void setCoord(int Xcoor, int Ycoor);
int getXcoor();
int getYcoor();
void setAsKing();
bool isKing();
private:
int XCoor;
int Ycoor;
CheckerPieceColor Ccolor;
CheckerPieceType Ctype;
};
| [
"keithrmathman@yahoo.com"
] | keithrmathman@yahoo.com |
2ffbe031f4e07533906ac27a2251c6ef62f6dac6 | 07c7bff25412d08e80a179d32d5f1f8b24b98637 | /build-ToDo-Desktop-Debug/moc_MainWindow.cpp | 9986b5ac46696760c776dcf70197d30eadce1d48 | [] | no_license | MahmoudAbdelazim/ToDo-qt5 | 81ee9489912a0891a10aea94104a2a858b52e71e | 0180d37b531fa65392dd72a87a0cefbd942dd06d | refs/heads/master | 2022-11-23T20:48:33.434096 | 2020-07-30T00:15:52 | 2020-07-30T00:15:52 | 283,628,342 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,627 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'MainWindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.8)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../ToDo/MainWindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'MainWindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.12.8. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MainWindow_t {
QByteArrayData data[7];
char stringdata0[60];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 0, 10), // "MainWindow"
QT_MOC_LITERAL(1, 11, 7), // "addTask"
QT_MOC_LITERAL(2, 19, 0), // ""
QT_MOC_LITERAL(3, 20, 10), // "removeTask"
QT_MOC_LITERAL(4, 31, 5), // "Task*"
QT_MOC_LITERAL(5, 37, 4), // "task"
QT_MOC_LITERAL(6, 42, 17) // "taskStatusChanged"
},
"MainWindow\0addTask\0\0removeTask\0Task*\0"
"task\0taskStatusChanged"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 29, 2, 0x0a /* Public */,
3, 1, 30, 2, 0x0a /* Public */,
6, 1, 33, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void,
QMetaType::Void, 0x80000000 | 4, 5,
QMetaType::Void, 0x80000000 | 4, 5,
0 // eod
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<MainWindow *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->addTask(); break;
case 1: _t->removeTask((*reinterpret_cast< Task*(*)>(_a[1]))); break;
case 2: _t->taskStatusChanged((*reinterpret_cast< Task*(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
switch (_id) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 1:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< Task* >(); break;
}
break;
case 2:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< Task* >(); break;
}
break;
}
}
}
QT_INIT_METAOBJECT const QMetaObject MainWindow::staticMetaObject = { {
&QMainWindow::staticMetaObject,
qt_meta_stringdata_MainWindow.data,
qt_meta_data_MainWindow,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0))
return static_cast<void*>(this);
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"mahmoud2011989@gmail.com"
] | mahmoud2011989@gmail.com |
5fa023b17f69b192f578514f824d710be8c33e5a | aaa0121876cf64e34793b7bdec9e5d5ea105fee3 | /QAQ.cpp | 69ed40d3e85ea7ca95e9d534df4b5f622964eb3f | [] | no_license | arpitsvm15/CodeForces | 4a7c40ad4c23ce37b74940a65cdb7143519c98e4 | a42608047ca66129f6cb047259e5c5ff9efb8dca | refs/heads/master | 2021-04-27T05:59:48.145247 | 2019-01-24T18:23:16 | 2019-01-24T18:23:16 | 122,605,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,133 | cpp | #include <bits/stdc++.h>
using namespace std;
long getWays(long n, vector < long > c){
long dp[c.size()+1][n+1];
for(int j=0;j<=c.size();j++)
fill_n(dp[j],n+1,0);
sort(c.begin(),c.end());
for(int j=1;j<=c.size();j++)
{
for(int i=1;i<=n;i++)
{
if(i<c[j-1])
dp[j][i]=dp[j-1][i];
else if(i==c[j-1])
{
dp[j][i]=dp[j-1][i]+1;
}
else
{
dp[j][i]=dp[j-1][i]+dp[j][i-c[j-1]];
}
}
}
return dp[c.size()][n];
// Complete this function
}
int main() {
int n;
int m;
cin >> n >> m;
vector<long> c(m);
for(int c_i = 0; c_i < m; c_i++)
{
cin >> c[c_i];
}
// Print the number of ways of making change for 'n' units using coins having the values given by 'c'
long ways = getWays(n, c);
cout<<ways<<endl;
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
dcd333f5264ae966cabb7404d4024f331cc0578a | a35b30a7c345a988e15d376a4ff5c389a6e8b23a | /boost/accumulators/framework/accumulators/value_accumulator.hpp | 6ae712f87b0fdc7cd11186ab764a197c7005560d | [] | no_license | huahang/thirdparty | 55d4cc1c8a34eff1805ba90fcbe6b99eb59a7f0b | 07a5d64111a55dda631b7e8d34878ca5e5de05ab | refs/heads/master | 2021-01-15T14:29:26.968553 | 2014-02-06T07:35:22 | 2014-02-06T07:35:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 99 | hpp | #include "thirdparty/boost_1_55_0/boost/accumulators/framework/accumulators/value_accumulator.hpp"
| [
"liuhuahang@xiaomi.com"
] | liuhuahang@xiaomi.com |
fc669960711f2628c9d7af599b40a8217743fa3b | 3de85d20dae566aa362fc6ce75bc4a3411c97a20 | /FloorplannerEA/Markup.h | 0041a892ac45ab675d7b4d1e1fe4349738c266c5 | [] | no_license | ignacioarnaldo/floorplanning | 4369668e6539c294cd1deacb126e64b3a96bfb83 | 48007af8b1da1bc3e9474d04711bbc26833cbd5e | refs/heads/master | 2021-01-01T19:06:28.579089 | 2014-12-07T16:24:44 | 2014-12-07T16:24:44 | 27,557,159 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 19,004 | h | // Markup.h: interface for the CMarkup class.
//
// Markup Release 11.4
// Copyright (C) 2011 First Objective Software, Inc. All rights reserved
// Go to www.firstobject.com for the latest CMarkup and EDOM documentation
// Use in commercial applications requires written permission
// This software is provided "as is", with no warranty.
#if !defined(_MARKUP_H_INCLUDED_)
#define _MARKUP_H_INCLUDED_
#include <stdlib.h>
#include <string.h> // memcpy, memset, strcmp...
// Major build options
// MARKUP_WCHAR wide char (2-byte UTF-16 on Windows, 4-byte UTF-32 on Linux and OS X)
// MARKUP_MBCS ANSI/double-byte strings on Windows
// MARKUP_STL (default except VC++) use STL strings instead of MFC strings
// MARKUP_SAFESTR to use string _s functions in VC++ 2005 (_MSC_VER >= 1400)
// MARKUP_WINCONV (default for VC++) for Windows API character conversion
// MARKUP_ICONV (default for GNU) for character conversion on Linux and OS X and other platforms
// MARKUP_STDCONV to use neither WINCONV or ICONV, falls back to setlocale based conversion for ANSI
//
#if _MSC_VER > 1000 // VC++
#pragma once
#if ! defined(MARKUP_SAFESTR) // not VC++ safe strings
#pragma warning(disable:4996) // VC++ 2005 deprecated function warnings
#endif // not VC++ safe strings
#if defined(MARKUP_STL) && _MSC_VER < 1400 // STL pre VC++ 2005
#pragma warning(disable:4786) // std::string long names
#endif // VC++ 2005 STL
#else // not VC++
#if ! defined(MARKUP_STL)
#define MARKUP_STL
#endif // not STL
#if defined(__GNUC__) && ! defined(MARKUP_ICONV) && ! defined(MARKUP_STDCONV) && ! defined(MARKUP_WINCONV)
#define MARKUP_ICONV
#endif // GNUC and not ICONV not STDCONV not WINCONV
#endif // not VC++
#if (defined(_UNICODE) || defined(UNICODE)) && ! defined(MARKUP_WCHAR)
#define MARKUP_WCHAR
#endif // _UNICODE or UNICODE
#if (defined(_MBCS) || defined(MBCS)) && ! defined(MARKUP_MBCS)
#define MARKUP_MBCS
#endif // _MBCS and not MBCS
#if ! defined(MARKUP_SIZEOFWCHAR)
#if __SIZEOF_WCHAR_T__ == 4 || __WCHAR_MAX__ > 0x10000
#define MARKUP_SIZEOFWCHAR 4
#else // sizeof(wchar_t) != 4
#define MARKUP_SIZEOFWCHAR 2
#endif // sizeof(wchar_t) != 4
#endif // not MARKUP_SIZEOFWCHAR
#if ! defined(MARKUP_WINCONV) && ! defined(MARKUP_STDCONV) && ! defined(MARKUP_ICONV)
#define MARKUP_WINCONV
#endif // not WINCONV not STDCONV not ICONV
#if ! defined(MARKUP_FILEBLOCKSIZE)
#define MARKUP_FILEBLOCKSIZE 16384
#endif
// Text type and function defines (compiler and build-option dependent)
//
#define MCD_ACP 0
#define MCD_UTF8 65001
#define MCD_UTF16 1200
#define MCD_UTF32 65005
#if defined(MARKUP_WCHAR)
#define MCD_CHAR wchar_t
#define MCD_PCSZ const wchar_t*
#define MCD_PSZLEN (int)wcslen
#define MCD_PSZCHR wcschr
#define MCD_PSZSTR wcsstr
#define MCD_PSZTOL wcstol
#if defined(MARKUP_SAFESTR) // VC++ safe strings
#define MCD_SSZ(sz) sz,(sizeof(sz)/sizeof(MCD_CHAR))
#define MCD_PSZCPY(sz,p) wcscpy_s(MCD_SSZ(sz),p)
#define MCD_PSZNCPY(sz,p,n) wcsncpy_s(MCD_SSZ(sz),p,n)
#define MCD_SPRINTF swprintf_s
#define MCD_FOPEN(f,n,m) {if(_wfopen_s(&f,n,m)!=0)f=NULL;}
#else // not VC++ safe strings
#if defined(__GNUC__)
#define MCD_SSZ(sz) sz,(sizeof(sz)/sizeof(MCD_CHAR))
#else // not GNUC
#define MCD_SSZ(sz) sz
#endif // not GNUC
#define MCD_PSZCPY wcscpy
#define MCD_PSZNCPY wcsncpy
#define MCD_SPRINTF swprintf
#define MCD_FOPEN(f,n,m) f=_wfopen(n,m)
#endif // not VC++ safe strings
#define MCD_T(s) L ## s
#if MARKUP_SIZEOFWCHAR == 4 // sizeof(wchar_t) == 4
#define MCD_ENC MCD_T("UTF-32")
#else // sizeof(wchar_t) == 2
#define MCD_ENC MCD_T("UTF-16")
#endif
#define MCD_CLEN(p) 1
#else // not MARKUP_WCHAR
#define MCD_CHAR char
#define MCD_PCSZ const char*
#define MCD_PSZLEN (int)strlen
#define MCD_PSZCHR strchr
#define MCD_PSZSTR strstr
#define MCD_PSZTOL strtol
#if defined(MARKUP_SAFESTR) // VC++ safe strings
#define MCD_SSZ(sz) sz,(sizeof(sz)/sizeof(MCD_CHAR))
#define MCD_PSZCPY(sz,p) strcpy_s(MCD_SSZ(sz),p)
#define MCD_PSZNCPY(sz,p,n) strncpy_s(MCD_SSZ(sz),p,n)
#define MCD_SPRINTF sprintf_s
#define MCD_FOPEN(f,n,m) {if(fopen_s(&f,n,m)!=0)f=NULL;}
#else // not VC++ safe strings
#define MCD_SSZ(sz) sz
#define MCD_PSZCPY strcpy
#define MCD_PSZNCPY strncpy
#define MCD_SPRINTF sprintf
#define MCD_FOPEN(f,n,m) f=fopen(n,m)
#endif // not VC++ safe strings
#define MCD_T(s) s
#if defined(MARKUP_MBCS) // MBCS/double byte
#define MCD_ENC MCD_T("")
#if defined(MARKUP_WINCONV)
#define MCD_CLEN(p) (int)_mbclen((const unsigned char*)p)
#else // not WINCONV
#define MCD_CLEN(p) (int)mblen(p,MB_CUR_MAX)
#endif // not WINCONV
#else // not MBCS/double byte
#define MCD_ENC MCD_T("UTF-8")
#define MCD_CLEN(p) 1
#endif // not MBCS/double byte
#endif // not MARKUP_WCHAR
#if _MSC_VER < 1000 // not VC++
#define MCD_STRERROR strerror(errno)
#endif // not VC++
// String type and function defines (compiler and build-option dependent)
// Define MARKUP_STL to use STL strings
//
#if defined(MARKUP_STL) // STL
#include <string>
#if defined(MARKUP_WCHAR)
#define MCD_STR std::wstring
#else // not MARKUP_WCHAR
#define MCD_STR std::string
#endif // not MARKUP_WCHAR
#define MCD_2PCSZ(s) s.c_str()
#define MCD_STRLENGTH(s) (int)s.size()
#define MCD_STRCLEAR(s) s.erase()
#define MCD_STRCLEARSIZE(s) MCD_STR t; s.swap(t)
#define MCD_STRISEMPTY(s) s.empty()
#define MCD_STRMID(s,n,l) s.substr(n,l)
#define MCD_STRASSIGN(s,p,n) s.assign(p,n)
#define MCD_STRCAPACITY(s) (int)s.capacity()
#define MCD_STRINSERTREPLACE(d,i,r,s) d.replace(i,r,s)
#define MCD_GETBUFFER(s,n) new MCD_CHAR[n+1]; if ((int)s.capacity()<(int)n) s.reserve(n)
#define MCD_RELEASEBUFFER(s,p,n) s.replace(0,s.size(),p,n); delete[]p
#define MCD_BLDRESERVE(s,n) s.reserve(n)
#define MCD_BLDCHECK(s,n,d) ;
#define MCD_BLDRELEASE(s) ;
#define MCD_BLDAPPENDN(s,p,n) s.append(p,n)
#define MCD_BLDAPPEND(s,p) s.append(p)
#define MCD_BLDAPPEND1(s,c) s+=(MCD_CHAR)(c)
#define MCD_BLDLEN(s) s.size()
#define MCD_BLDTRUNC(s,n) s.resize(n)
#else // not STL, i.e. MFC
// afx.h provides CString, to avoid "WINVER not defined" #include stdafh.x in Markup.cpp
#include <afx.h>
#define MCD_STR CString
#define MCD_2PCSZ(s) ((MCD_PCSZ)s)
#define MCD_STRLENGTH(s) s.GetLength()
#define MCD_STRCLEAR(s) s.Empty()
#define MCD_STRCLEARSIZE(s) s=MCD_STR()
#define MCD_STRISEMPTY(s) s.IsEmpty()
#define MCD_STRMID(s,n,l) s.Mid(n,l)
#define MCD_STRASSIGN(s,p,n) memcpy(s.GetBuffer(n),p,(n)*sizeof(MCD_CHAR));s.ReleaseBuffer(n);
#define MCD_STRCAPACITY(s) (((CStringData*)((MCD_PCSZ)s)-1)->nAllocLength)
#define MCD_GETBUFFER(s,n) s.GetBuffer(n)
#define MCD_RELEASEBUFFER(s,p,n) s.ReleaseBuffer(n)
#define MCD_BLDRESERVE(s,n) MCD_CHAR*pD=s.GetBuffer(n); int nL=0
#define MCD_BLDCHECK(s,n,d) if(nL+(int)(d)>n){s.ReleaseBuffer(nL);n<<=2;pD=s.GetBuffer(n);}
#define MCD_BLDRELEASE(s) s.ReleaseBuffer(nL)
#define MCD_BLDAPPENDN(s,p,n) MCD_PSZNCPY(&pD[nL],p,n);nL+=n
#define MCD_BLDAPPEND(s,p) MCD_PSZCPY(&pD[nL],p);nL+=MCD_PSZLEN(p)
#define MCD_BLDAPPEND1(s,c) pD[nL++]=(MCD_CHAR)(c)
#define MCD_BLDLEN(s) nL
#define MCD_BLDTRUNC(s,n) nL=n
#endif // not STL
#define MCD_STRTOINT(s) MCD_PSZTOL(MCD_2PCSZ(s),NULL,10)
// Allow function args to accept string objects as constant string pointers
struct MCD_CSTR
{
MCD_CSTR() { pcsz=NULL; };
MCD_CSTR( MCD_PCSZ p ) { pcsz=p; };
MCD_CSTR( const MCD_STR& s ) { pcsz = MCD_2PCSZ(s); };
operator MCD_PCSZ() const { return pcsz; };
MCD_PCSZ pcsz;
};
// On Linux and OS X, filenames are not specified in wchar_t
#if defined(MARKUP_WCHAR) && defined(__GNUC__)
#undef MCD_FOPEN
#define MCD_FOPEN(f,n,m) f=fopen(n,m)
#define MCD_T_FILENAME(s) s
#define MCD_PCSZ_FILENAME const char*
struct MCD_CSTR_FILENAME
{
MCD_CSTR_FILENAME() { pcsz=NULL; };
MCD_CSTR_FILENAME( MCD_PCSZ_FILENAME p ) { pcsz=p; };
MCD_CSTR_FILENAME( const std::string& s ) { pcsz = s.c_str(); };
operator MCD_PCSZ_FILENAME() const { return pcsz; };
MCD_PCSZ_FILENAME pcsz;
};
#else // not WCHAR GNUC
#define MCD_CSTR_FILENAME MCD_CSTR
#define MCD_T_FILENAME MCD_T
#define MCD_PCSZ_FILENAME MCD_PCSZ
#endif // not WCHAR GNUC
#if defined(__GNUC__)
#define MCD_FSEEK fseeko
#define MCD_FTELL ftello
#define MCD_INTFILEOFFSET off_t
#elif _MSC_VER >= 1000 && defined(MARKUP_HUGEFILE) // VC++ HUGEFILE
#if _MSC_VER < 1400 // before VC++ 2005
extern "C" int __cdecl _fseeki64(FILE *, __int64, int);
extern "C" __int64 __cdecl _ftelli64(FILE *);
#endif // before VC++ 2005
#define MCD_FSEEK _fseeki64
#define MCD_FTELL _ftelli64
#define MCD_INTFILEOFFSET __int64
#else // not GNU or VC++ HUGEFILE
#define MCD_FSEEK fseek
#define MCD_FTELL ftell
#define MCD_INTFILEOFFSET long
#endif // not GNU or VC++ HUGEFILE
struct FilePos;
struct TokenPos;
struct NodePos;
struct PathPos;
struct SavedPosMapArray;
struct ElemPosTree;
class CMarkup
{
public:
CMarkup() { x_InitMarkup(); SetDoc( NULL ); };
CMarkup( MCD_CSTR szDoc ) { x_InitMarkup(); SetDoc( szDoc ); };
CMarkup( int nFlags ) { x_InitMarkup(); SetDoc( NULL ); m_nDocFlags = nFlags; };
CMarkup( const CMarkup& markup ) { x_InitMarkup(); *this = markup; };
void operator=( const CMarkup& markup );
~CMarkup();
// Navigate
bool Load( MCD_CSTR_FILENAME szFileName );
bool SetDoc( MCD_PCSZ pDoc );
bool SetDoc( const MCD_STR& strDoc );
bool IsWellFormed();
bool FindElem( MCD_CSTR szName=NULL );
bool FindChildElem( MCD_CSTR szName=NULL );
bool IntoElem();
bool OutOfElem();
void ResetChildPos() { x_SetPos(m_iPosParent,m_iPos,0); };
void ResetMainPos() { x_SetPos(m_iPosParent,0,0); };
void ResetPos() { x_SetPos(0,0,0); };
MCD_STR GetTagName() const;
MCD_STR GetChildTagName() const { return x_GetTagName(m_iPosChild); };
MCD_STR GetData() { return x_GetData(m_iPos); };
MCD_STR GetChildData() { return x_GetData(m_iPosChild); };
MCD_STR GetElemContent() const { return x_GetElemContent(m_iPos); };
MCD_STR GetAttrib( MCD_CSTR szAttrib ) const { return x_GetAttrib(m_iPos,szAttrib); };
MCD_STR GetChildAttrib( MCD_CSTR szAttrib ) const { return x_GetAttrib(m_iPosChild,szAttrib); };
bool GetNthAttrib( int n, MCD_STR& strAttrib, MCD_STR& strValue ) const;
MCD_STR GetAttribName( int n ) const;
int FindNode( int nType=0 );
int GetNodeType() { return m_nNodeType; };
bool SavePos( MCD_CSTR szPosName=MCD_T(""), int nMap = 0 );
bool RestorePos( MCD_CSTR szPosName=MCD_T(""), int nMap = 0 );
bool SetMapSize( int nSize, int nMap = 0 );
MCD_STR GetError() const;
const MCD_STR& GetResult() const { return m_strResult; };
int GetDocFlags() const { return m_nDocFlags; };
void SetDocFlags( int nFlags ) { m_nDocFlags = (nFlags & ~(MDF_READFILE|MDF_WRITEFILE|MDF_APPENDFILE)); };
enum MarkupDocFlags
{
MDF_UTF16LEFILE = 1,
MDF_UTF8PREAMBLE = 4,
MDF_IGNORECASE = 8,
MDF_READFILE = 16,
MDF_WRITEFILE = 32,
MDF_APPENDFILE = 64,
MDF_UTF16BEFILE = 128,
MDF_TRIMWHITESPACE = 256,
MDF_COLLAPSEWHITESPACE = 512
};
enum MarkupNodeFlags
{
MNF_WITHCDATA = 0x01,
MNF_WITHNOLINES = 0x02,
MNF_WITHXHTMLSPACE = 0x04,
MNF_WITHREFS = 0x08,
MNF_WITHNOEND = 0x10,
MNF_ESCAPEQUOTES = 0x100,
MNF_NONENDED = 0x100000,
MNF_ILLDATA = 0x200000
};
enum MarkupNodeType
{
MNT_ELEMENT = 1, // 0x0001
MNT_TEXT = 2, // 0x0002
MNT_WHITESPACE = 4, // 0x0004
MNT_TEXT_AND_WHITESPACE = 6, // 0x0006
MNT_CDATA_SECTION = 8, // 0x0008
MNT_PROCESSING_INSTRUCTION = 16, // 0x0010
MNT_COMMENT = 32, // 0x0020
MNT_DOCUMENT_TYPE = 64, // 0x0040
MNT_EXCLUDE_WHITESPACE = 123, // 0x007b
MNT_LONE_END_TAG = 128, // 0x0080
MNT_NODE_ERROR = 32768 // 0x8000
};
// Create
bool Save( MCD_CSTR_FILENAME szFileName );
const MCD_STR& GetDoc() const { return m_strDoc; };
bool AddElem( MCD_CSTR szName, MCD_CSTR szData=NULL, int nFlags=0 ) { return x_AddElem(szName,szData,nFlags); };
bool InsertElem( MCD_CSTR szName, MCD_CSTR szData=NULL, int nFlags=0 ) { return x_AddElem(szName,szData,nFlags|MNF_INSERT); };
bool AddChildElem( MCD_CSTR szName, MCD_CSTR szData=NULL, int nFlags=0 ) { return x_AddElem(szName,szData,nFlags|MNF_CHILD); };
bool InsertChildElem( MCD_CSTR szName, MCD_CSTR szData=NULL, int nFlags=0 ) { return x_AddElem(szName,szData,nFlags|MNF_INSERT|MNF_CHILD); };
bool AddElem( MCD_CSTR szName, int nValue, int nFlags=0 ) { return x_AddElem(szName,nValue,nFlags); };
bool InsertElem( MCD_CSTR szName, int nValue, int nFlags=0 ) { return x_AddElem(szName,nValue,nFlags|MNF_INSERT); };
bool AddChildElem( MCD_CSTR szName, int nValue, int nFlags=0 ) { return x_AddElem(szName,nValue,nFlags|MNF_CHILD); };
bool InsertChildElem( MCD_CSTR szName, int nValue, int nFlags=0 ) { return x_AddElem(szName,nValue,nFlags|MNF_INSERT|MNF_CHILD); };
bool AddAttrib( MCD_CSTR szAttrib, MCD_CSTR szValue ) { return x_SetAttrib(m_iPos,szAttrib,szValue); };
bool AddChildAttrib( MCD_CSTR szAttrib, MCD_CSTR szValue ) { return x_SetAttrib(m_iPosChild,szAttrib,szValue); };
bool AddAttrib( MCD_CSTR szAttrib, int nValue ) { return x_SetAttrib(m_iPos,szAttrib,nValue); };
bool AddChildAttrib( MCD_CSTR szAttrib, int nValue ) { return x_SetAttrib(m_iPosChild,szAttrib,nValue); };
bool AddSubDoc( MCD_CSTR szSubDoc ) { return x_AddSubDoc(szSubDoc,0); };
bool InsertSubDoc( MCD_CSTR szSubDoc ) { return x_AddSubDoc(szSubDoc,MNF_INSERT); };
MCD_STR GetSubDoc() { return x_GetSubDoc(m_iPos); };
bool AddChildSubDoc( MCD_CSTR szSubDoc ) { return x_AddSubDoc(szSubDoc,MNF_CHILD); };
bool InsertChildSubDoc( MCD_CSTR szSubDoc ) { return x_AddSubDoc(szSubDoc,MNF_CHILD|MNF_INSERT); };
MCD_STR GetChildSubDoc() { return x_GetSubDoc(m_iPosChild); };
bool AddNode( int nType, MCD_CSTR szText ) { return x_AddNode(nType,szText,0); };
bool InsertNode( int nType, MCD_CSTR szText ) { return x_AddNode(nType,szText,MNF_INSERT); };
// Modify
bool RemoveElem();
bool RemoveChildElem();
bool RemoveNode();
bool SetAttrib( MCD_CSTR szAttrib, MCD_CSTR szValue, int nFlags=0 ) { return x_SetAttrib(m_iPos,szAttrib,szValue,nFlags); };
bool SetChildAttrib( MCD_CSTR szAttrib, MCD_CSTR szValue, int nFlags=0 ) { return x_SetAttrib(m_iPosChild,szAttrib,szValue,nFlags); };
bool SetAttrib( MCD_CSTR szAttrib, int nValue, int nFlags=0 ) { return x_SetAttrib(m_iPos,szAttrib,nValue,nFlags); };
bool SetChildAttrib( MCD_CSTR szAttrib, int nValue, int nFlags=0 ) { return x_SetAttrib(m_iPosChild,szAttrib,nValue,nFlags); };
bool SetData( MCD_CSTR szData, int nFlags=0 ) { return x_SetData(m_iPos,szData,nFlags); };
bool SetChildData( MCD_CSTR szData, int nFlags=0 ) { return x_SetData(m_iPosChild,szData,nFlags); };
bool SetData( int nValue ) { return x_SetData(m_iPos,nValue); };
bool SetChildData( int nValue ) { return x_SetData(m_iPosChild,nValue); };
bool SetElemContent( MCD_CSTR szContent ) { return x_SetElemContent(szContent); };
// Utility
static bool ReadTextFile( MCD_CSTR_FILENAME szFileName, MCD_STR& strDoc, MCD_STR* pstrResult=NULL, int* pnDocFlags=NULL, MCD_STR* pstrEncoding=NULL );
static bool WriteTextFile( MCD_CSTR_FILENAME szFileName, const MCD_STR& strDoc, MCD_STR* pstrResult=NULL, int* pnDocFlags=NULL, MCD_STR* pstrEncoding=NULL );
static MCD_STR EscapeText( MCD_CSTR szText, int nFlags = 0 );
static MCD_STR UnescapeText( MCD_CSTR szText, int nTextLength = -1, int nFlags = 0 );
static int UTF16To8( char *pszUTF8, const unsigned short* pwszUTF16, int nUTF8Count );
static int UTF8To16( unsigned short* pwszUTF16, const char* pszUTF8, int nUTF8Count );
static MCD_STR UTF8ToA( MCD_CSTR pszUTF8, int* pnFailed = NULL );
static MCD_STR AToUTF8( MCD_CSTR pszANSI );
static void EncodeCharUTF8( int nUChar, char* pszUTF8, int& nUTF8Len );
static int DecodeCharUTF8( const char*& pszUTF8, const char* pszUTF8End = NULL );
static void EncodeCharUTF16( int nUChar, unsigned short* pwszUTF16, int& nUTF16Len );
static int DecodeCharUTF16( const unsigned short*& pwszUTF16, const unsigned short* pszUTF16End = NULL );
static bool DetectUTF8( const char* pText, int nTextLen, int* pnNonASCII = NULL, bool* bErrorAtEnd = NULL );
static MCD_STR GetDeclaredEncoding( MCD_CSTR szDoc );
static int GetEncodingCodePage( MCD_CSTR pszEncoding );
protected:
#if defined(_DEBUG)
MCD_PCSZ m_pDebugCur;
MCD_PCSZ m_pDebugPos;
#endif // DEBUG
MCD_STR m_strDoc;
MCD_STR m_strResult;
int m_iPosParent;
int m_iPos;
int m_iPosChild;
int m_iPosFree;
int m_iPosDeleted;
int m_nNodeType;
int m_nNodeOffset;
int m_nNodeLength;
int m_nDocFlags;
FilePos* m_pFilePos;
SavedPosMapArray* m_pSavedPosMaps;
ElemPosTree* m_pElemPosTree;
enum MarkupNodeFlagsInternal
{
MNF_INSERT = 0x002000,
MNF_CHILD = 0x004000
};
#if defined(_DEBUG) // DEBUG
void x_SetDebugState();
#define MARKUP_SETDEBUGSTATE x_SetDebugState()
#else // not DEBUG
#define MARKUP_SETDEBUGSTATE
#endif // not DEBUG
void x_InitMarkup();
void x_SetPos( int iPosParent, int iPos, int iPosChild );
int x_GetFreePos();
bool x_AllocElemPos( int nNewSize = 0 );
int x_GetParent( int i );
bool x_ParseDoc();
int x_ParseElem( int iPos, TokenPos& token );
int x_FindElem( int iPosParent, int iPos, PathPos& path ) const;
MCD_STR x_GetPath( int iPos ) const;
MCD_STR x_GetTagName( int iPos ) const;
MCD_STR x_GetData( int iPos );
MCD_STR x_GetAttrib( int iPos, MCD_PCSZ pAttrib ) const;
static MCD_STR x_EncodeCDATASection( MCD_PCSZ szData );
bool x_AddElem( MCD_PCSZ pName, MCD_PCSZ pValue, int nFlags );
bool x_AddElem( MCD_PCSZ pName, int nValue, int nFlags );
MCD_STR x_GetSubDoc( int iPos );
bool x_AddSubDoc( MCD_PCSZ pSubDoc, int nFlags );
bool x_SetAttrib( int iPos, MCD_PCSZ pAttrib, MCD_PCSZ pValue, int nFlags=0 );
bool x_SetAttrib( int iPos, MCD_PCSZ pAttrib, int nValue, int nFlags=0 );
bool x_AddNode( int nNodeType, MCD_PCSZ pText, int nNodeFlags );
void x_RemoveNode( int iPosParent, int& iPos, int& nNodeType, int& nNodeOffset, int& nNodeLength );
static bool x_CreateNode( MCD_STR& strNode, int nNodeType, MCD_PCSZ pText );
int x_InsertNew( int iPosParent, int& iPosRel, NodePos& node );
void x_AdjustForNode( int iPosParent, int iPos, int nShift );
void x_Adjust( int iPos, int nShift, bool bAfterPos = false );
void x_LinkElem( int iPosParent, int iPosBefore, int iPos );
int x_UnlinkElem( int iPos );
int x_UnlinkPrevElem( int iPosParent, int iPosBefore, int iPos );
int x_ReleaseSubDoc( int iPos );
int x_ReleasePos( int iPos );
void x_CheckSavedPos();
bool x_SetData( int iPos, MCD_PCSZ szData, int nFlags );
bool x_SetData( int iPos, int nValue );
int x_RemoveElem( int iPos );
MCD_STR x_GetElemContent( int iPos ) const;
bool x_SetElemContent( MCD_PCSZ szContent );
void x_DocChange( int nLeft, int nReplace, const MCD_STR& strInsert );
};
#endif // !defined(_MARKUP_H_INCLUDED_)
| [
"nacho@nacho-HP-Folio-13-Notebook-PC"
] | nacho@nacho-HP-Folio-13-Notebook-PC |
5968ca20cc0712e98816d4a680dde733398d8529 | 839130d9e3097398288024ba4a14c3116cd426d2 | /2/Hw2/Task2.1/sorterTester.h | 88777b411fa09c536335a014b1dffaba3f35e569 | [] | no_license | Parean/Homeworks | d2a90e8380390ff836b5e239856149d393e805f8 | 02ddd2a79ba069697e56373229f937802f64ddee | refs/heads/master | 2021-01-18T21:43:27.195785 | 2017-06-02T08:17:34 | 2017-06-02T08:17:34 | 48,554,203 | 0 | 0 | null | 2017-06-02T08:17:35 | 2015-12-24T19:06:39 | C++ | UTF-8 | C++ | false | false | 1,378 | h | #pragma once
#include <QtCore/QObject>
#include <QtTest/QTest>
#include "bubbleSorter.h"
#include "quickSorter.h"
#include "insertionSorter.h"
class SorterTester : public QObject
{
Q_OBJECT
public:
explicit SorterTester(QObject *parent = 0) : QObject(parent) {}
private:
int size;
int *array;
Sorter *bubbleSorter;
Sorter *quickSorter;
Sorter *insertionSorter;
private slots:
void init()
{
size = 10;
array = new int[size];
for (int i = 0; i < size; i++)
array[i] = rand() % 100;
bubbleSorter = new BubbleSorter(array, size);
quickSorter = new QuickSorter(array, size);
insertionSorter = new InsertionSorter(array, size);
}
void cleanup()
{
delete array;
}
void testBubbleSort()
{
array = bubbleSorter->sort();
bool isSorted = true;
for (int i = 1; i < size; i++)
if(array[i] < array[i - 1])
isSorted = false;
QVERIFY2(isSorted, "The array sorted incorrectly");
}
void testInsertionSort()
{
array = insertionSorter->sort();
bool isSorted = true;
for (int i = 1; i < size; i++)
if(array[i] < array[i - 1])
isSorted = false;
QVERIFY2(isSorted, "The array sorted incorrectly");
}
void testQuickSort()
{
array = quickSorter->sort();
bool isSorted = true;
for (int i = 1; i < size; i++)
if(array[i] < array[i - 1])
isSorted = false;
QVERIFY2(isSorted, "The array sorted incorrectly");
}
};
| [
"smirnov.d.p.1997@gmail.com"
] | smirnov.d.p.1997@gmail.com |
5f554ae7bc78d3b36d87f7e685e0d0cfcddc7740 | 4a605a3b68c4770aa6fc341bc2776350ba5e0285 | /src/Update.cpp | 2287e379a653d1c9bc9d7ab5fb58d76a5174ce35 | [
"WTFPL"
] | permissive | mosra/absencoid | 187e86baf3ece9e5c99f7008e8ed1d3a34b7a0a5 | 1b1437df643b4318cb98c7d71ec174ad89dae882 | refs/heads/master | 2021-01-25T12:13:11.787577 | 2011-09-15T10:30:46 | 2011-09-15T10:30:46 | 2,391,818 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,378 | cpp | #include "Update.h"
#include <QSqlError>
#include <QSqlQuery>
#include <QDebug>
#include "Dump.h"
#include "TimetableModel.h"
#include "TeachersModel.h"
#include "ChangesModel.h"
#include "ClassesModel.h"
namespace Absencoid {
/* Konstruktor */
Update::Update(const QString& data, bool _doUpdate, QObject* parent):
QThread(parent), doUpdate(_doUpdate) {
/* Načtení dat */
QString errorMsg;
int errorLine, errorColumn;
if(!doc.setContent(data, &errorMsg, &errorLine, &errorColumn)) {
QString err = tr("Nepodařilo se načíst XML soubor!");
emit error(err);
qDebug() << err << errorMsg << errorLine << errorColumn;
return;
}
}
QString Update::date() {
QDomElement root = doc.documentElement();
/* Buď <update> nebo <dump>, obě mají podelement <date>. */
QDomElement something = root.firstChildElement();
QDomElement date = something.firstChildElement("date");
if(date.isNull()) {
QString err = tr("Nepodařilo se najít datum vytvoření souboru!");
emit error(err);
qDebug() << err;
return "";
}
return date.text();
}
/* Poznámka k aktualizaci */
QString Update::updateNote() {
try {
QDomElement root = doc.documentElement();
QDomElement update = root.firstChildElement("update");
if(update.isNull()) throw tr("Toto není aktualizační soubor!");
QDomElement note = update.firstChildElement("note");
if(note.isNull()) throw tr("Nepodařilo se najít popisek aktualizace!");
return note.text();
/* Ošetření výjimek */
} catch (QString e) {
emit error(e);
qDebug() << e;
return "";
}
}
/* Načtení updatu */
void Update::run() {
try {
/* Započetí transakce */
QSqlQuery query;
if(!query.exec("BEGIN EXCLUSIVE TRANSACTION;"))
throw SqlException(tr("Nepodařilo se začít aktualizaci!"), query);
QDomElement r = doc.documentElement();
QDomElement root = r.firstChildElement();
/* Zjištění typu souboru */
bool isUpdate;
/* Aktualizační soubor */
if(root.tagName() == "update") {
isUpdate = true;
/* Pokud chceme obnovovat zálohu z aktualizačního souboru, konec */
if(!doUpdate) throw tr("Nelze obnovovat zálohu z aktualizačního souboru!");
int version = root.attribute("version").toInt();
/* Ověření verze */
if(version != Dump::UPDATE_VERSION)
throw tr("Nepodporovaná verze aktualizačního souboru %1 (podporovaná je %2)")
.arg(version).arg(Dump::UPDATE_VERSION);
/* Zálohovací soubor */
} else if(root.tagName() == "dump") {
isUpdate = false;
/* Pokud chceme aktualizovat ze zálohy, konec */
if(doUpdate) throw tr("Nelze provádět aktualizaci ze souboru zálohy!");
int version = root.attribute("version").toInt();
/* Ověření verze */
if(version != Dump::DUMP_VERSION)
throw tr("Nepodporovaná verze souboru zálohy %1 (podporovaná: %2)")
.arg(version).arg(Dump::DUMP_VERSION);
/* Něco jiného */
} else throw tr("Neplatný soubor!");
/* Každá sekce je prováděná v jednom bloku {}, aby se nehromadily dávno
nepoužívané proměnné QDomElement */
/* <configuration> */ {
QDomElement configuration = root.firstChildElement("configuration");
if(configuration.isNull()) throw tr("Nenalezena sekce s konfigurací!");
/* <beginDate> */
QDomElement _beginDate = configuration.firstChildElement("beginDate");
if(_beginDate.isNull()) throw tr("Nenalezeno datum začátku pololetí!");
QString beginDate = _beginDate.text();
/* <endDate> */
QDomElement _endDate = configuration.firstChildElement("endDate");
if(_endDate.isNull()) throw tr("Nenalezeno datum konce pololetí!");
QString endDate = _endDate.text();
/* <webUpdateUrl> */
QDomElement _webUpdateUrl = configuration.firstChildElement("webUpdateUrl");
if(_webUpdateUrl.isNull()) throw tr("Nenalezena adresa pro aktualizaci z internetu!");
QString webUpdateUrl = _webUpdateUrl.text();
query.prepare("UPDATE configuration SET "
"beginDate = :beginDate, "
"endDate = :endDate, "
"webUpdateUrl = :webUpdateUrl;");
query.bindValue(":beginDate", beginDate);
query.bindValue(":endDate", endDate);
query.bindValue(":webUpdateUrl", webUpdateUrl);
if(!query.exec())
throw SqlException(tr("Nepodařilo se aktualizovat konfiguraci!"), query);
/* Elementy jen v zálohách */
if(!isUpdate) {
/* <lastUpdate> */
QDomElement _lastUpdate = configuration.firstChildElement("lastUpdate");
if(_lastUpdate.isNull()) throw tr("Nenalezeno datum poslední aktualizace!");
QString lastUpdate = _lastUpdate.text();
int flags = 0;
/* <updateOnStart> */
QDomElement _updateOnStart = configuration.firstChildElement("updateOnStart");
if(_updateOnStart.isNull()) throw tr("Nenalezena volba, zda aktualizovat po startu!");
if(!_updateOnStart.hasAttribute("value")) throw tr("Nenalezena hodnota volby, zda aktualizovat po startu!");
flags |= _updateOnStart.attribute("value", "true") == "true" ? Dump::UPDATE_ON_START : 0;
/* <dumpOnExit> */
QDomElement _dumpOnExit = configuration.firstChildElement("dumpOnExit");
if(_dumpOnExit.isNull()) throw tr("Nenalezena volba, zda zálohovat při ukončení!");
if(!_dumpOnExit.hasAttribute("value")) throw tr("Nenalezena hodnota volby, zda zálohovat při ukončení!");
flags |= _dumpOnExit.attribute("value", "false") == "true" ? Dump::DUMP_ON_EXIT : 0;
query.prepare("UPDATE configuration SET "
"lastUpdate = :lastUpdate, flags = :flags;");
query.bindValue(":lastUpdate", lastUpdate);
query.bindValue(":flags", flags);
if(!query.exec())
throw SqlException(tr("Nepodařilo se aktualizovat uživatelskou konfiguraci!"), query);
}
/* Signál o dokončení aktualizace konfigurace */
emit updated(tr("Dokončena aktualizace konfigurace"), 0);
/* <teachers> */ }{
QDomElement teachers = root.firstChildElement("teachers");
if(teachers.isNull()) throw tr("Nenalezena sekce s učiteli!");
/* Smazání dosavadních učitelů, zapsání jejich počtu do proměnné (pro statistiku) */
if(!query.exec("DELETE FROM teachers WHERE id > 0;"))
throw SqlException(tr("Nelpodařilo se smazat staré učitele!"), query);
int teachersCount = -query.numRowsAffected();
/* Resetování AUTOINCREMENT */
if(!query.exec("DELETE FROM sqlite_sequence WHERE name = \"teachers\";"))
throw SqlException(tr("Nelpodařilo se resetovat tabulku učitelů!"), query);
/* Předpřipravení dotazu pro vkládání nových učitelů */
query.prepare("INSERT INTO TEACHERS (gradeId, id, name, flags) VALUES (1, :id, :name, :flags);");
/* <teacher> */
QDomNodeList teacherNodes = teachers.elementsByTagName("teacher");
for(int i = 0; i != teacherNodes.count(); ++i) {
QDomElement teacher = teacherNodes.item(i).toElement();
/* Ošetření chyb (tj. i té, když je teacher nulový element) */
if(!teacher.hasAttribute("id")) throw tr("Nenalezeno ID učitele!");
if(!teacher.hasAttribute("counts")) throw tr("Nelze zjistit, zda učitel zapisuje absence!");
if(!teacher.hasAttribute("accepts")) throw tr("Nelze zjistit, zda učitel uznává školní akce!");
/* Odseknutí znaku 't' z ID, převedení na int */
/** @todo Nějaká kontrola */
int id = teacher.attribute("id").mid(1).toInt();
/* Flags */
int flags = (teacher.attribute("counts") == "true" ? TeachersModel::COUNTS : 0) |
(teacher.attribute("accepts") == "true" ? TeachersModel::ACCEPTS : 0);
/* Provedení dotazu */
query.bindValue(":id", id);
query.bindValue(":name", teacher.text());
query.bindValue(":flags", flags);
if(!query.exec()) throw SqlException(tr("Nepodařilo se přidat učitele!"), query);
/* Přičtení přidaného učitele do statistiky */
teachersCount++;
}
/* Emitujeme signál o dokončení importu učitelů */
emit updated(tr("Dokončena aktualizace učitelů"), teachersCount);
/* <classes> */ }{
QDomElement classes = root.firstChildElement("classes");
if(classes.isNull()) throw tr("Nenalezena sekce s předměty!");
/* Smazání dosavadních předmětů, zapsání jejich počtu do proměnné (statistika) */
if(!query.exec("DELETE FROM classes WHERE id > 0;"))
throw SqlException(tr("Nepodařilo se smazat staré předměty!"), query);
int classesCount = -query.numRowsAffected();
/* Resetování AUTOINCREMENT */
if(!query.exec("DELETE FROM sqlite_sequence WHERE name = \"classes\";"))
throw SqlException(tr("Nepodařilo se resetovat tabulku předmětů!"), query);
/* Předpřipravení dotazu pro vkládání nových předmětů */
query.prepare("INSERT INTO classes (gradeId, id, name, teacherId) VALUES (1, :id, :name, :teacherId);");
/* <class> */
QDomNodeList classesNode = classes.elementsByTagName("class");
for(int i = 0; i != classesNode.count(); ++i) {
QDomElement _class = classesNode.item(i).toElement();
/* Ošetření chyb (tj. i té, kdy je _class nulový element) */
if(!_class.hasAttribute("id")) throw tr("Nenalezeno ID předmětu!");
if(!_class.hasAttribute("teacherId")) throw tr("Nenalezeno ID učitele!");
/* Odseknutí znaku 'c' z ID, převedení na int */
/** @todo Nějaká kontrola */
int id = _class.attribute("id").mid(1).toInt();
/* Odesknutí znaku 't' z ID učitele, převedení na int */
int teacherId = _class.attribute("teacherId").mid(1).toInt();
/* Provedení dotazu */
query.bindValue(":id", id);
query.bindValue(":name", _class.text());
query.bindValue(":teacherId", teacherId);
if(!query.exec()) throw SqlException(tr("Nelpodařilo se přidat předmět!"), query);
/* Přičtení přidaného předmětu do statistiky */
classesCount++;
}
/* Emitování signálu o dokončení importu předmětů */
emit updated(tr("Dokončena aktualizace předmětů"), classesCount);
/* <timetables> */ }{
QDomElement timetables = root.firstChildElement("timetables");
if(timetables.isNull()) throw tr("Nenalezena sekce s rozvrhy!");
/* Nastavení ID aktuálního rozvrhu (ne pokud jenom aktualizujeme) */
if(!isUpdate) {
/* pokud parametr neexistuje (např. žádné rozvrhy nejsou), nebudeme nadávat */
int actualTimetableId = timetables.attribute("activeId", "1").mid(1).toInt();
query.prepare("UPDATE configuration SET activeTimetableId = :activeTimetableId;");
query.bindValue(":activeTimetableId", actualTimetableId);
if(!query.exec()) throw SqlException(tr("Nepodařilo se aktualizovat použitý rozvrh!"), query);
}
/* Smazání dosavadních rozvrhů, zapsání jejich počtu pro statistiku */
if(!query.exec("DELETE FROM timetables WHERE id > 0;"))
throw SqlException(tr("Nepodařilo se smazat staré rozvrhy!"), query);
int timetablesCount = -query.numRowsAffected();
int timetableDataCount = 0;
/* Resetování AUTOINCREMENT */
if(!query.exec("DELETE FROM sqlite_sequence WHERE name = \"timetables\";"))
throw SqlException(tr("Nepodařilo se resetovat tabulku rozvrhů!"), query);
/* Předpřipravení dotazu pro vkládání nových předmětů */
query.prepare("INSERT INTO timetables (gradeId, id, description, validFrom, followedBy) "
"VALUES (1, :id, :description, :validFrom, :followedBy);");
/* <timetable> */
QDomNodeList timetableNodes = timetables.elementsByTagName("timetable");
for(int i = 0; i != timetableNodes.count(); ++i) {
QDomElement timetable = timetableNodes.item(i).toElement();
/* Ošetření chyb */
if(!timetable.hasAttribute("id")) throw tr("Nenalezeno ID rozvrhu!");
if(!timetable.hasAttribute("next")) throw tr("Nenalezeno ID následujícího rozvrhu!");
/* Atributy (odseknutí 't' a převod na int) */
int id = timetable.attribute("id").mid(1).toInt();
int followedBy = timetable.attribute("next").mid(1).toInt();
/* <name> */
QDomElement _name = timetable.firstChildElement("name");
if(_name.isNull()) throw tr("Nenalezen popisek rozvrhu!");
QString name = _name.text();
/* <validFrom> */
QDomElement _validFrom = timetable.firstChildElement("validFrom");
if(_validFrom.isNull()) throw tr("Nenalezeno datum začátku platnosti rozvrhu!");
QString validFrom = _validFrom.text();
/* Přidání rozvrhu */
query.bindValue(":id", id);
query.bindValue(":description", name);
query.bindValue(":validFrom", validFrom);
query.bindValue(":followedBy", followedBy);
if(!query.exec()) throw SqlException(tr("Nepodařilo se přidat rozvrh!"), query);
/* Přičtení přidaného rozvrhu do statistiky rozvrhů */
timetablesCount++;
/* <lessons> */
QDomElement lessons = timetable.firstChildElement("lessons");
if(lessons.isNull()) throw tr("Nenalezeny předměty rozvrhu!");
/* Smazání dat tohoto rozvrhu (pokud aktualizujeme, smažeme jen pevná data) */
QSqlQuery lessonsQuery;
lessonsQuery.prepare("DELETE FROM timetableData WHERE timetableId = :timetableId AND classId > :classId;");
lessonsQuery.bindValue(":timetableId", id);
/* Pokud děláme aktualizaci, mazáme jen zamknuté hodiny */
if(isUpdate) lessonsQuery.bindValue(":classId", TimetableModel::FIXED);
else lessonsQuery.bindValue(":classId", 0);
if(!lessonsQuery.exec())
throw SqlException(tr("Nepodařilo se smazat staré předměty z rozvrhu!"), lessonsQuery);
timetableDataCount -= lessonsQuery.numRowsAffected();
/* Připravení dotazu pro vkládání předmětů */
lessonsQuery.prepare("INSERT INTO timetableData (gradeId, timetableId, dayHour, classId) "
"VALUES (1, :timetableId, :dayHour, :classId);");
/* <lesson> */
QDomNodeList lessonNodes = lessons.elementsByTagName("lesson");
for(int i = 0; i != lessonNodes.count(); ++i) {
QDomElement lesson = lessonNodes.item(i).toElement();
/* Ověření atributů */
if(!lesson.hasAttribute("classId")) throw tr("Nenalezen předmět rozvrhu!");
if(!lesson.hasAttribute("fixed")) throw tr("Nenalezena volba, zda je předmět zamknutý");
/* Odseknutí znaku 'c' z ID, převedení na int, přiORování hodnoty FIXED */
int classId = lesson.attribute("classId").mid(1).toInt();
classId |= lesson.attribute("fixed") == "true" ? TimetableModel::FIXED : 0;
/* <day> */
QDomElement day = lesson.firstChildElement("day");
if(day.isNull()) throw tr("Nelze zjistit den předmětu!");
/* <hour> */
QDomElement hour = lesson.firstChildElement("hour");
if(hour.isNull()) throw tr("Nelze zjistit hodinu předmětu!");
int dayHour = TimetableModel::dayHour(day.text().toInt(), hour.text().toInt());
lessonsQuery.bindValue(":timetableId", id);
lessonsQuery.bindValue(":dayHour", dayHour);
lessonsQuery.bindValue(":classId", classId);
if(!lessonsQuery.exec())
throw SqlException(tr("Nepodařilo se přidat předmět do rozvrhu!"), lessonsQuery);
/* Přičtení přidaného předmětu do statistiky předmětů */
timetableDataCount++;
}
}
/* Emitování signálu o dokončení importu rozvrhů */
emit updated(tr("Dokončena aktualizace rozvrhů"), timetablesCount);
/* Emitování signálu o dokončení importu předmětů rozvrhu */
emit updated(tr("Dokončena aktualizace předmětů v rozvrzích"), timetableDataCount);
/* <changes> */ }{
QDomElement changes = root.firstChildElement("changes");
if(changes.isNull()) throw tr("Nenalezena sekce se změnami!");
/* Smazání dosavadních změn, zapsání jejich počtu pro statistiku */
if(!query.exec("DELETE FROM changes WHERE id > 0;"))
throw SqlException(tr("Nelze smazat staré změny!"), query);
int changesCount = -query.numRowsAffected();
/* Resetování AUTOINCREMENT */
if(!query.exec("DELETE FROM sqlite_sequence WHERE name = \"changes\";"))
throw SqlException(tr("Nelze resetovat tabulku změn!"), query);
/* Připravení dotazu pro vkládání změn */
query.prepare("INSERT INTO changes (gradeId, id, date, hour, fromClassId, toClassId) "
"VALUES (1, :id, :date, :hour, :fromClassId, :toClassId);");
/* <change> */
QDomNodeList changeNodes = changes.elementsByTagName("change");
for(int i = 0; i != changeNodes.count(); ++i) {
QDomElement change = changeNodes.item(i).toElement();
/* ID změny (odseknutí 'x' a převod na int) */
if(!change.hasAttribute("id")) throw tr("Nenalezeno ID změny!");
int id = change.attribute("id").mid(1).toInt();
/* <date> */
QDomElement _date = change.firstChildElement("date");
if(_date.isNull()) throw tr("Nenalezeno datum změny!");
QString date = _date.text();
/* <hour> */
QDomElement _hour = change.firstChildElement("hour");
int hour;
/* <allHours> */
if(_hour.isNull()) {
QDomElement allHours = change.firstChildElement("allHours");
if(allHours.isNull()) throw tr("Nenalezena hodina změny!");
hour = ChangesModel::ALL_HOURS;
/* Dosazení hodiny */
} else hour = _hour.text().toInt();
/* <fromClass> */
QDomElement _fromClass = change.firstChildElement("fromClass");
int fromClassId;
/* <allClasses> */
if(_fromClass.isNull()) {
QDomElement allClasses = change.firstChildElement("allClasses");
if(allClasses.isNull()) throw tr("Nenalezen předmět, ze kterého se mění!");
fromClassId = ClassesModel::WHATEVER;
} else {
/* Pokud neexistuje atribut id, znamená to, že měníme z prádzného předmětu */
if(!_fromClass.hasAttribute("id")) fromClassId = 0;
/* Dosazení ID z atributu (odseknutí 'c' a převod na int) */
fromClassId = _fromClass.attribute("id").mid(1).toInt();
}
/* <toClass> */
QDomElement _toClass = change.firstChildElement("toClass");
if(_toClass.isNull()) throw tr("Nenalezen předmět, na který se mění!");
int toClassId;
/* Pokud neexistuje atribut id, znamená to, že měníme na prázdný předmět */
if(!_toClass.hasAttribute("id")) toClassId = 0;
/* Dosazení ID z atributu (odseknutí 'c' a převod na int) */
else toClassId = _toClass.attribute("id").mid(1).toInt();
/* Provedení dotazu */
query.bindValue(":id", id);
query.bindValue(":date", date);
query.bindValue(":hour", hour);
query.bindValue(":fromClassId", fromClassId);
query.bindValue(":toClassId", toClassId);
if(!query.exec()) throw SqlException(tr("Nelze přidat změnu!"), query);
/* Přičtení přidané změny ke statistice */
changesCount++;
}
/* Emitování signálu o dokončení importu změn */
emit updated(tr("Dokončena aktualizace změn"), changesCount);
/* <absences> (jen když načítáme zálohu) */ }
if(!isUpdate) {
QDomElement absences = root.firstChildElement("absences");
if(absences.isNull()) throw tr("Nebyla nalezena sekce s absencemi!");
/* Smazání starých absencí, uložení jejich počtu pro statistiku */
if(!query.exec("DELETE FROM absences WHERE id > 0;"))
throw SqlException(tr("Nelze smazat staré absence!"), query);
int absencesCount = -query.numRowsAffected();
/* Reset AUTOINCREMENT */
if(!query.exec("DELETE FROM sqlite_sequence WHERE name = \"absences\";"))
throw SqlException(tr("Nelze resetovat tabulku absencí!"), query);
/* Připravení dotazu pro vkládání absencí */
query.prepare("INSERT INTO absences (gradeId, id, date, hours) "
"VALUES (1, :id, :date, :hours);");
/* <absence> */
QDomNodeList absenceNodes = absences.elementsByTagName("absence");
for(int i = 0; i != absenceNodes.count(); ++i) {
QDomElement absence = absenceNodes.item(i).toElement();
/* ID absence (odseknutí 'x' a převod na int) */
if(!absence.hasAttribute("id")) throw tr("Nenalezeno ID absence!");
int id = absence.attribute("id").mid(1).toInt();
/* <date> */
QDomElement _date = absence.firstChildElement("date");
if(_date.isNull()) throw tr("Nenalezeno datum absence!");
QString date = _date.text();
/* <allHours> */
QDomElement allHours = absence.firstChildElement("allHours");
int hours = 0;
if(!allHours.isNull()) hours = ChangesModel::ALL_HOURS;
/* <hour> */
else {
QDomNodeList hourNodes = absence.elementsByTagName("hour");
for(int i = 0; i != hourNodes.count(); ++i) {
QDomElement hour = hourNodes.item(i).toElement();
hours |= 1 << hour.text().toInt();
}
}
/* Provedení dotazu */
query.bindValue(":id", id);
query.bindValue(":date", date);
query.bindValue(":hours", hours);
if(!query.exec()) throw SqlException(tr("Nelze přidat absenci!"), query);
/* Přičtení přidané absence ke statistice */
absencesCount++;
}
/* Emitování signálu o dokončení importu absencí */
emit updated(tr("Dokončena aktualizace absencí"), absencesCount);
}
/* Nastavení data poslední aktualizace */
if(isUpdate) {
query.prepare("UPDATE configuration SET lastUpdate = :lastUpdate;");
query.bindValue(":lastUpdate", QDate::currentDate().toString(Qt::ISODate));
if(!query.exec())
throw SqlException(tr("Nepodařilo se nastavit datum poslední aktualizace!"), query);
}
/* Vše proběhlo OK, commit */
if(!query.exec("COMMIT TRANSACTION;"))
throw SqlException(tr("Nepodařilo se korektně ukončit aktualizaci!"), query);
return;
/* Ošetření chyb zpracování XML */
} catch(QString e) {
emit error(e);
qDebug() << e;
/* Ošetření chyb při aktualizaci DB */
} catch(SqlException e) {
emit error(e.error());
qDebug() << e.error() << e.query().lastError() << e.query().lastQuery();
}
/* Sem se funkce normálně nedostane, takže zrušení transakce */
QSqlQuery queryEndTransaction;
if(!queryEndTransaction.exec("ROLLBACK TRANSACTION;")) {
/* Tohle by opravdu nemělo nikdy nastat! */
qDebug() << tr("Nepodařilo se zrušit transakci!")
<< queryEndTransaction.lastError() << queryEndTransaction.lastQuery();
return;
}
emit updated(tr("Databáze navrácena zpět do stavu před aktualizací"), 0);
}
}
| [
"mosra@centrum.cz"
] | mosra@centrum.cz |
e632a81eb1150671eb911df02fd6741e7b749778 | cf131fa5d63a4a32b0f89c364d1ba77a20fb0b59 | /src/Workflow/LearningWorkflow.hpp | 435abb3a676befe6336c8f66a1c34a65aaea8839 | [] | no_license | bvinhosa/BankingFramework | f26be91c9bb06f58567a6e063de5cb2f0a8a7f34 | 49fb91b4d456cc7a935ebabf7ba73de231a6b071 | refs/heads/master | 2020-09-08T19:14:54.420233 | 2018-04-08T15:51:07 | 2018-04-08T15:51:07 | 94,438,924 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 759 | hpp | #ifndef LEARNINGWORFLOW_HPP
#define LEARNINGWORFLOW_HPP
#include "CommonWorkflow.hpp"
#include "../Economy/StandardBankingSystem.hpp"
#include "LearningCycle.hpp"
#include "CommonIteration.hpp"
#include "CommonRepetition.hpp"
class LearningWorkflow : public Workflow {
public:
LearningWorkflow(int numReps,
int cyclesPerRep,
StandardBankingSystem::Parameters params,
std::vector<double> sizes);
virtual void execute(void);
virtual std::string exportResultsToString(void);
private:
const int numRepetitions;
StandardBankingSystem theSystem;
CommonRepetition theRepetition;
LearningCycle theCycle;
CommonIteration theIteration;
};
#endif //LEARNINGWORFLOW_HPP
| [
"bernardo.vinhosa@gmail.com"
] | bernardo.vinhosa@gmail.com |
2bc9096e854e1e77af7f334b99f6daeb9403eb02 | cb45f20f81823571cfece270c00eb43fead17f33 | /drill19/drill19.cpp | aa6a8652cd3a561ced8938b34ee7dfd9b7cac315 | [] | no_license | kovacskristofgabor/Prog1 | 1cade876d8cfd9ec0ebc77155ce413ebd0a625af | 277fca68e6b73a805e19456b7ded9145cdfcd31b | refs/heads/main | 2023-04-21T22:57:36.297768 | 2021-05-14T14:32:21 | 2021-05-14T14:32:21 | 343,153,994 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,815 | cpp | #include <iostream>
#include <string>
#include <vector>
template<typename T>
struct S {
explicit S(T vv = 0) : val{vv} { }
S& operator=(const T&);
T& get();
const T& get() const;
private:
T val;
};
template<typename T>
T& S<T>::get()
{
return val;
}
template<typename T>
const T& S<T>::get() const
{
return val;
}
template<typename T>
S<T>& S<T>::operator=(const T& s)
{
val = s;
return *this;
}
template<typename T>
std::ostream& operator<<(std::ostream& os, std::vector<T>& v)
{
os << "{ ";
for (int i = 0; i < v.size(); ++i) {
os << v[i] << (i < v.size() - 1 ? ", " : " ");
}
os << "}\n";
return os;
}
template<typename T>
std::istream& operator>>(std::istream& is, std::vector<T>& v)
{
char ch = 0;
is >> ch;
if (ch != '{') {
is.unget();
return is;
}
for (T val; is >> val; ) {
v.push_back(val);
is >> ch;
if (ch != ',') break;
}
return is;
}
template<typename T> void read_val(T& v)
{
std::cin >> v;
}
int main()
{
S<int> si {24};
S<char> sc {'k'};
S<double> sd {40.2};
S<std::string> s {"Hello!"};
S<std::vector<int>> svi { std::vector<int>{1, 2, 8, 4, 5, 9}};
std::cout << "S<int> : " << si.get() << '\n'
<< "S<char> : " << sc.get() << '\n'
<< "S<double> : " << sd.get() << '\n'
<< "S<string> : " << s.get() << '\n'
<< "S<vector<int>> : " << svi.get() << '\n';
sd = 3.14159;
std::cout << "S<double> : " << sd.get() << '\n';
std::cout << "Reads:\n";
std::cout << "Vector<int>: (format: { val1, val2, val3 }) ";
std::vector<int> vi2;
read_val(vi2);
S<std::vector<int>> svi2 {vi2};
std::cout << "S<vector<int>> read: " << svi2.get() << '\n';
}
| [
"noreply@github.com"
] | noreply@github.com |
eaff27b8bb540652514480f8482202a0c35e74c5 | 90ce76e9b9312afe7a65fc513e698378d4294d0f | /SRM540/RandomColoringDiv2_Kaiyang.cpp | 6714aab15d128faf6880bca3842479dbda80bbde | [] | no_license | FighterKing/TopCoder | 248946350aa535489d7f6d1eb1936aaf26a0eadc | d3420136cb8d2bbf6a0d0433f8c5736badac8868 | refs/heads/master | 2016-09-05T22:53:13.869535 | 2014-12-29T06:59:33 | 2014-12-29T06:59:33 | 19,060,759 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,837 | cpp | #include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
class RandomColoringDiv2 {
int getMost(int maxColor, int startColor, int d2) {
int most = min(d2, maxColor - startColor - 1);
most += startColor - max(0, startColor - d2) + 1;
return most;
}
int getLeastMost(int maxColor, int startColor, int d1, int d2) {
int least = 0;
int leastColor = 0;
if (startColor + d2 <= maxColor - 1)
maxColor = startColor + d2 + 1;
if (startColor - d2 >= 0)
leastColor = startColor - d2;
if (startColor + d1 <= maxColor - 1){
least += maxColor - (startColor + d1);
}
if (startColor - d1 >= leastColor) {
least += startColor - d1 - leastColor + 1;
}
if (0 == d1)
--least;
return least;
}
public:
int getCount(int maxR, int maxG, int maxB, int startR, int startG, int startB, int d1, int d2) {
int mostR = getMost(maxR, startR, d2);
int mostG = getMost(maxG, startG, d2);
int mostB = getMost(maxB, startB, d2);
int lmR = getLeastMost(maxR, startR, d1, d2);
int lmG = getLeastMost(maxG, startG, d1, d2);
int lmB = getLeastMost(maxB, startB, d1, d2);
int sum = mostR * mostG * mostB;
sum -= (mostR - lmR) * (mostG - lmG) * (mostB - lmB);
return sum;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit 2.1.4 (beta) modified by pivanof
bool KawigiEdit_RunTest(int testNum, int p0, int p1, int p2, int p3, int p4, int p5, int p6, int p7, bool hasAnswer, int p8) {
cout << "Test " << testNum << ": [" << p0 << "," << p1 << "," << p2 << "," << p3 << "," << p4 << "," << p5 << "," << p6 << "," << p7;
cout << "]" << endl;
RandomColoringDiv2 *obj;
int answer;
obj = new RandomColoringDiv2();
clock_t startTime = clock();
answer = obj->getCount(p0, p1, p2, p3, p4, p5, p6, p7);
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" << p8 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = answer == p8;
}
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;
int p1;
int p2;
int p3;
int p4;
int p5;
int p6;
int p7;
int p8;
{
// ----- test 0 -----
p0 = 5;
p1 = 1;
p2 = 1;
p3 = 2;
p4 = 0;
p5 = 0;
p6 = 0;
p7 = 1;
p8 = 3;
all_right = KawigiEdit_RunTest(0, p0, p1, p2, p3, p4, p5, p6, p7, true, p8) && all_right;
// ------------------
}
{
// ----- test 1 -----
p0 = 4;
p1 = 2;
p2 = 2;
p3 = 0;
p4 = 0;
p5 = 0;
p6 = 3;
p7 = 3;
p8 = 4;
all_right = KawigiEdit_RunTest(1, p0, p1, p2, p3, p4, p5, p6, p7, true, p8) && all_right;
// ------------------
}
{
// ----- test 2 -----
p0 = 4;
p1 = 2;
p2 = 2;
p3 = 0;
p4 = 0;
p5 = 0;
p6 = 5;
p7 = 5;
p8 = 0;
all_right = KawigiEdit_RunTest(2, p0, p1, p2, p3, p4, p5, p6, p7, true, p8) && all_right;
// ------------------
}
{
// ----- test 3 -----
p0 = 6;
p1 = 9;
p2 = 10;
p3 = 1;
p4 = 2;
p5 = 3;
p6 = 0;
p7 = 10;
p8 = 540;
all_right = KawigiEdit_RunTest(3, p0, p1, p2, p3, p4, p5, p6, p7, true, p8) && all_right;
// ------------------
}
{
// ----- test 4 -----
p0 = 6;
p1 = 9;
p2 = 10;
p3 = 1;
p4 = 2;
p5 = 3;
p6 = 4;
p7 = 10;
p8 = 330;
all_right = KawigiEdit_RunTest(4, p0, p1, p2, p3, p4, p5, p6, p7, true, p8) && all_right;
// ------------------
}
{
// ----- test 5 -----
p0 = 49;
p1 = 59;
p2 = 53;
p3 = 12;
p4 = 23;
p5 = 13;
p6 = 11;
p7 = 22;
p8 = 47439;
all_right = KawigiEdit_RunTest(5, p0, p1, p2, p3, p4, p5, p6, p7, true, p8) && 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
//Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
| [
"kevinlui598@gmail.com"
] | kevinlui598@gmail.com |
d0917117346e83b9782c0a8448d19e7f12e3d75e | 6c7520ea1c95f437ecde70fcdb202ab5cee54b17 | /90520_1/A.cpp | 3aa6be8c858ec8b11e9bdb870ffc6a9c9c08701b | [] | no_license | Ashish-uzumaki/contests | 997a8288c63f1e834b7689c2ff97e29e965b6139 | 0084adfc3b1a9bf496146c6e4db429720a1ce98c | refs/heads/master | 2021-01-16T04:07:38.303987 | 2020-08-09T16:49:47 | 2020-08-09T16:49:47 | 242,972,066 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,464 | cpp | #include <bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
typedef long long ll;
typedef long double lld;
typedef long long int lli;
using namespace std;
const int N = 1000001;
const int MOD=1e9+7;
const bool DEBUG = 1;
#define sd(x) scanf("%d", &x)
#define sd2(x, y) scanf("%d%d", &x, &y)
#define sd3(x, y, z) scanf("%d%d%d", &x, &y, &z)
#define endl "\n"
#define fi first
#define se second
#define eb emplace_back
#define fbo find_by_order
#define ook order_of_key
#define pb(x) push_back(x)
#define mp(x, y) make_pair(x, y)
#define LET(x, a) __typeof(a) x(a)
#define foreach(it, v) for (LET(it, v.begin()); it != v.end(); it++)
#define MEMS(a, b) memset(a, b, sizeof(a))
#define _ \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
#define __ \
freopen("input.txt", "r", stdin); \
freopen("output.txt", "w", stdout);
#define all(c) c.begin(), c.end()
#define inf 1000000000000000001
#define epsilon 1e-6
#define int ll
#define RUN_T \
int _t; \
cin >> _t; \
while (_t--)
#define tr(...) \
if (DEBUG) { \
cout << __FUNCTION__ << ' ' << __LINE__ << " = "; \
trace(#__VA_ARGS__, __VA_ARGS__); \
}
template <typename S, typename T>
ostream &operator<<(ostream &out, pair<S, T> const &p) {
out << '(' << p.fi << ", " << p.se << ')';
return out;
}
template <typename T>
ostream &operator<<(ostream &out, set<T> const &v) {
for (auto i = v.begin(); i != v.end(); i++)
out << (*i) << ' ';
return out;
}
template <typename T, typename V>
ostream &operator<<(ostream &out, map<T, V> const &v) {
for (auto i = v.begin(); i != v.end(); i++)
out << "\n" << (i->first) << ":" << (i->second);
return out;
}
template <typename T, typename V>
ostream &operator<<(ostream &out, unordered_map<T, V> const &v) {
for (auto i = v.begin(); i != v.end(); i++)
out << "\n" << (i->first) << ":" << (i->second);
return out;
}
template <typename T>
ostream &operator<<(ostream &out, multiset<T> const &v) {
for (auto i = v.begin(); i != v.end(); i++)
out << (*i) << ' ';
return out;
}
template <typename T>
ostream &operator<<(ostream &out, unordered_set<T> const &v) {
for (auto i = v.begin(); i != v.end(); i++)
out << (*i) << ' ';
return out;
}
template <typename T>
ostream &operator<<(ostream &out, unordered_multiset<T> const &v) {
for (auto i = v.begin(); i != v.end(); i++)
out << (*i) << ' ';
return out;
}
template <typename T> ostream &operator<<(ostream &out, vector<T> const &v) {
ll l = v.size();
for (ll i = 0; i < l - 1; i++)
out << v[i] << ' ';
if (l > 0)
out << v[l - 1];
return out;
}
template <typename T> void trace(const char *name, T &&arg1) {
cout << name << ":" << arg1 << endl;
}
template <typename T, typename... Args>
void trace(const char *names, T &&arg1, Args &&... args) {
const char *comma = strchr(names + 1, ',');
cout.write(names, comma - names) << ":" << arg1 << "|" ;
trace(comma + 1, args...);
}
template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
void add_self(int& a, int b) {
a += b;
if(a >= MOD) {
a -= MOD;
}
}
int32_t main() {
_
int n, m;
cin >> n >> m;
vector<int>a(n+1, 1e9),diff(n + 1, 0) ,t(m + 1), l(m + 1), r(m + 1), d(m + 1);
for(int i = 0; i < m; i++){
cin >> t[i] >> l[i] >> r[i] >> d[i];
l[i]--, r[i]--;
if(t[i] == 1){
for(int j = l[i]; j <= r[i]; j++){
diff[j] += d[i];
}
}else{
for(int j = l[i]; j <= r[i]; j++){
a[j] = min(a[j], d[i] - diff[j]);
}
}
}
vector<int>b = a;
for(int i = 0; i < m; i++){
if(t[i] == 1){
for(int j = l[i]; j <= r[i] ;j++){
b[j] += d[i];
}
}else{
int maxi = -1e9;
for(int j = l[i]; j <= r[i] ;j++){
maxi = max(b[j], maxi);
}
if(maxi != d[i]){
cout << "NO" <<endl;
return 0;
}
}
}
cout << "YES" << endl;
for(int i = 0 ; i < n; i++){
cout << a[i]<<" ";
}
} | [
"Ashish.singh@iiitb.org"
] | Ashish.singh@iiitb.org |
6b998ff0050e18cca6bca4d7ce6af8aaca70aaf7 | 2f8875802666be2637b32387ae12203d4e2458cc | /Cpp_primer/chapter_9/p301/p301.cpp | ec12cbe34af4bcd8d688f53c9e10dbea64efcc0e | [] | no_license | suzumiyayuhi/GrayHistory | 41394c87dc15cf2700b3c4b1e24b296442d9e143 | 72db503e5a8a13c890152c7c9143f1918a9ec8f5 | refs/heads/master | 2020-06-17T17:23:55.278186 | 2017-02-20T08:54:48 | 2017-02-20T08:55:58 | 74,980,202 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 287 | cpp | #include<vector>
#include<string>
#include<list>
#include<iostream>
using namespace std;
void create9_11() {
}
void create_9_13() {
list<int> a(10, 8);
vector<double> b(a.begin(), a.end());
for (auto x : b) {
cout << x;
}
}
int main() {
create_9_13();
getchar();
return 0;
} | [
"923051761@qq.com"
] | 923051761@qq.com |
7f2740091f858c5c0cd483ca04b4ba79e5b5279c | f90de00314d0a7fda3a9a2a9577a0e6a1469d88b | /cpp_primer/12/12_07.cpp | e52e85ff583740919c0791b032f9c40c531e9f59 | [] | no_license | 1iuyzh/exercise | fdb4c6c34c47e512c5474c4b90c7533f81c1177f | 95f0b9e91dd8fb7fd9c51566fd47eff4f033d1be | refs/heads/master | 2020-05-20T12:59:51.518359 | 2018-10-25T03:36:11 | 2018-10-25T03:36:11 | 80,420,443 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 573 | cpp | #include<iostream>
#include<vector>
#include<memory>
using std::cin; using std::cout; using std::endl;
using std::vector;
using std::ostream;
using std::shared_ptr;
using std::make_shared;
auto make_dynamically() {
return make_shared<vector<int>>();
}
auto save(shared_ptr<vector<int>> p) {
int i;
while (cin >> i)
p->push_back(i);
return p;
}
ostream& print(shared_ptr<vector<int>> p) {
for (auto i : *p)
cout << i << ' ';
return cout;
}
int main() {
auto p = save(make_dynamically());
print(p) << endl;
return 0;
} | [
"liuyzh@tju.edu.cn"
] | liuyzh@tju.edu.cn |
09948ba56b5c863515ec542a07853a561594fa97 | e9854cb02e90dab7ec0a49c65f658babba819d56 | /Curve Editor Framework/QT/src/gui/kernel/qguieventdispatcher_glib_p.h | e3d07e580d632b5cfaa2f1800f375189ac071f25 | [] | no_license | katzeforest/Computer-Animation | 2bbb1df374d65240ca2209b3a75a0b6a8b99ad58 | 01481111a622ae8812fb0b76550f5d66de206bab | refs/heads/master | 2021-01-23T19:46:13.455834 | 2015-06-08T21:29:02 | 2015-06-08T21:29:02 | 37,092,780 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,771 | h | /****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QGUIEVENTDISPATCHER_GLIB_P_H
#define QGUIEVENTDISPATCHER_GLIB_P_H
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists for the convenience
// of the QLibrary class. This header file may change from
// version to version without notice, or even be removed.
//
// We mean it.
//
#include <QtCore/private/qeventdispatcher_glib_p.h>
QT_BEGIN_NAMESPACE
class QGuiEventDispatcherGlibPrivate;
class QGuiEventDispatcherGlib : public QEventDispatcherGlib
{
Q_OBJECT
Q_DECLARE_PRIVATE(QGuiEventDispatcherGlib)
public:
explicit QGuiEventDispatcherGlib(QObject *parent = 0);
~QGuiEventDispatcherGlib();
bool processEvents(QEventLoop::ProcessEventsFlags flags);
void startingUp();
void flush();
};
QT_END_NAMESPACE
#endif // QGUIEVENTDISPATCHER_GLIB_P_H
| [
"sonyang@seas.upenn.edu"
] | sonyang@seas.upenn.edu |
b01bbfd308b0d320e19b48983af5c4c58249cb89 | e5b81565e4f27b4e036ca40fd5f46b0c8db69b97 | /TDebug0.5/TDebug/ExceptionEvent.h | 4f5b0c96aaa54faa3e14ca1b27e9c9666d1363c9 | [] | no_license | TTDemo/TDebugForWin32 | fb645f4a42b6554d6a42cfd2282e9515136fcfd1 | 0a6ac8decd2f7639dcc58585eef0fc14c0d93b10 | refs/heads/master | 2022-01-04T15:21:39.388577 | 2019-09-12T01:29:50 | 2019-09-12T01:29:50 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 453 | h | #pragma once
#include "TDebug.h"
class CExceptionEvent
{
public:
CExceptionEvent(TDebug* lpDbger, LPDEBUG_EVENT_CONTEXT lpDEC)
{
m_lpDbger = lpDbger;
m_lpDEC = lpDEC;
}
//ÏìÓ¦Òì³£´¦Àí
DWORD OnBreakPoint();
DWORD OnSingleStep();
DWORD OnAccessViolation();
private:
void OnSysInitBP();
private:
TDebug* m_lpDbger;
LPDEBUG_EVENT_CONTEXT m_lpDEC;
static BOOL g_bSysInitBP;
};
| [
"changle@changledeMacBook-Pro.local"
] | changle@changledeMacBook-Pro.local |
ae96d320d04d01d76ad840ca240c49222fad4a11 | b411e4861bc1478147bfc289c868b961a6136ead | /tags/DownhillRacing/IA.cpp | 3758168b77872e438cced295848db00cecb99c09 | [] | no_license | mvm9289/downhill-racing | d05df2e12384d8012d5216bc0b976bc7df9ff345 | 038ec4875db17a7898282d6ced057d813a0243dc | refs/heads/master | 2021-01-20T12:20:31.383595 | 2010-12-19T23:29:02 | 2010-12-19T23:29:02 | 32,334,476 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,825 | cpp | #include "IA.h"
#include <cstdlib>
#include <ctime>
#include <cmath>
IA::IA(unsigned int n) : nPlayers(n)
{
srand(clock());
turns = vector<int>(n, 0);
}
IA::~IA(void)
{
}
int IA::compute(unsigned int i, vector<Player*> pl) {
unsigned int ret = IA_NONE;
unsigned int r = 0;
int dX = pl[0]->getPosition().x - pl[i]->getPosition().x;
for (unsigned int j = 1; j < pl.size(); ++j){
if (j != i) dX += pl[0]->getPosition().x - pl[j]->getPosition().x;
}
int dY = pl[0]->getPosition().y - pl[i]->getPosition().y;
int dZ = pl[0]->getPosition().z - pl[i]->getPosition().z;
if (dZ < 0) { //player > computer
r = rand() % 100;
if (abs(dZ) > 10 && r > 95) ret += IA_TURBO;
r = rand() % 100;
if (abs(dZ) < 10 && r > 95 && !pl[0]->isJumping() && !pl[i]->isJumping()) ret += IA_JUMP;
}
else { //computer > player
r = rand() % 100;
if (abs(dZ) < 5 && r > 95) ret += IA_TURBO;
r = rand() % 100;
if (abs(dZ) < 5 && r > 80 && pl[0]->isJumping() && !pl[i]->isJumping()) ret += IA_JUMP;
}
if (turns[i] > 0) {
--turns[i];
ret += IA_TURN_RIGHT;
}
else if (turns[i] < 0) {
++turns[i];
ret += IA_TURN_LEFT;
}
else {
r = rand() % 100;
if (dZ < 0 && dX > 0 && r > 50) {
ret += IA_TURN_LEFT;
turns[i] = -TURN_STEPS;
}
else if (dZ < 0 && dX < 0 && r > 50) {
ret += IA_TURN_RIGHT;
turns[i] = TURN_STEPS;
}
else if (dZ > 0 && dX > 0 && r > 50) {
ret += IA_TURN_RIGHT;
turns[i] = TURN_STEPS;
}
else if (dZ > 0 && dX < 0 && r > 50) {
ret += IA_TURN_LEFT;
turns[i] = -TURN_STEPS;
}
else {
r = rand() % 100;
if (r < 20) {
ret += IA_TURN_LEFT;
turns[i] = -TURN_STEPS;
}
else if (r > 80) {
ret += IA_TURN_RIGHT;
turns[i] = TURN_STEPS;
}
}
}
return ret;
} | [
"mvm9289@06676c28-b993-0703-7cf1-698017e0e3c1"
] | mvm9289@06676c28-b993-0703-7cf1-698017e0e3c1 |
81661f33cdf519574114f2ee916ba89230e78c8c | e2b259476b2c47a701d87f16f2271ef760e02d5f | /include/tweedledee/qasm/ast/nodes/decl_ancilla.hpp | 150242b99182443209902013c4f74179baacf5b6 | [
"MIT"
] | permissive | meamy/tweedledee | d0da06ca6f3158ee4440d3e67b80cd6c38616761 | 8eeea0534f5a5e7a8d9332c9c1380603d95e337d | refs/heads/master | 2020-05-23T16:01:36.134853 | 2019-05-29T19:53:56 | 2019-05-29T19:53:56 | 186,840,339 | 0 | 0 | MIT | 2019-05-15T14:11:28 | 2019-05-15T14:11:27 | null | UTF-8 | C++ | false | false | 1,538 | hpp | /*-------------------------------------------------------------------------------------------------
| This file is distributed under the MIT License.
| See accompanying file /LICENSE for details.
| Author(s): Matthew Amy
*------------------------------------------------------------------------------------------------*/
#pragma once
#include "../ast_context.hpp"
#include "../ast_node.hpp"
#include "../ast_node_kinds.hpp"
#include <memory>
#include <string>
namespace tweedledee {
namespace qasm {
// This represents an ancilla (local) register declaration
class decl_ancilla final : public ast_node {
private:
//Configure bits
enum {
is_dirty_ = 0
};
public:
static decl_ancilla* build(ast_context* ctx, uint32_t location,
std::string_view identifier, uint32_t size, bool dirty)
{
return new (*ctx) decl_ancilla(location, identifier, size, dirty);
}
bool is_dirty() const
{
return ((this->config_bits_ >> is_dirty_) & 1) == 1;
}
std::string_view identifier() const
{
return identifier_;
}
uint32_t size() const
{
return size_;
}
private:
decl_ancilla(uint32_t location, std::string_view identifier, uint32_t size, bool dirty)
: ast_node(location)
, size_(size)
, identifier_(identifier)
{
this->config_bits_ |= (static_cast<int>(dirty) << is_dirty_);
}
ast_node_kinds do_get_kind() const override
{
return ast_node_kinds::decl_ancilla;
}
private:
uint32_t size_;
std::string identifier_;
};
} // namespace qasm
} // namespace tweedledee
| [
"matt.e.amy@gmail.com"
] | matt.e.amy@gmail.com |
a73c0d13af8f728c7c2fa2814815f86d49ccbab8 | dcb7dae56932f62292fd0d607e32dc2f238d5551 | /PST - Senior Training Qualification Contest-2018/main.cpp | 337336a2bb76e17b67ce481a11a925465c766555 | [] | no_license | alielrafeiFCIH/Problem_Solving | b5f330d115d3ca1c34613eb2639226c271f0052b | 15863cd43012831867fa2035fc92733a059dcfbf | refs/heads/master | 2020-06-27T03:33:15.668655 | 2019-09-03T09:49:26 | 2019-09-03T09:49:26 | 199,831,566 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,680 | cpp | #include <bits/stdc++.h>
using namespace std;
//int h[100000+9];
queue<int>q;
void expand(int node){
q.push(node*2);
q.push(node*2+1);
}
int main()
{
// freopen("notshort.in" , "r" , stdin);
// int t;
// int n;
// scanf("%d",&t);
// while(t--){
//
// scanf("%d",&n);
// int x;
// scanf("%d",&x);
// int molty_h =x;
// int h ;
// int count = 0;
// for(int i =1;i<n;i++){
// scanf("%d",&x);
// if(x>=molty_h)count++;
// }
// printf("%d\n",count);
// }
//----------------------------------------------------------------------------------------------------------
//freopen("morty.in" , "r" , stdin);
//int t;
//scanf("%d",&t);
//while(t--){
// long long n;
// cin>>n;
// long long ans = ((n*(n-1)/2))-n;
// cout<<ans<<endl;
//
//}
//-------------------------------------------------------------------------------------------------------------
//freopen("simple.in" , "r" , stdin);
//int t;
//scanf("%d",&t);
//long long int x,y;
//while(t--){
//cin>>x>>y;
//int ans = 0;
//if(x==y){
// printf("0\n");
//}else{
// if(x<0&&y<0){
// y = (-1)*y;
// x = (-1)*x;
// if(x>y){
// cout<<(-1)*y-(-1)*x<<endl;
// }else {
// cout<<y-x+2<<endl;
// }
//
// }else if(x>=0&&y>=0){
// if(x==0){
// cout<<y<<endl;
// }else if(y==0){
// cout<<x+1<<endl;
// } else if(x>y){
// cout<<x-y+2<<endl;
// }else{
// cout<<y-x<<endl;
// }
//
// }else if (x>=0&&y<0){
// if(x==0){
// cout<<((-1)*y)+1<<endl;
// }else if(x>((-1)*y)){
// cout<<x-((-1)*y)+1<<endl;
// }else{
// cout<<((-1)*y-x)+1<<endl;
// }
//
// } else if (x<0&&y>=0){
// if(y==0){
// cout<<(-1)*x<<endl;
// }else if(((-1)*x)>y){
// cout<<((-1)*x)-y+1<<endl;
// }else{
// cout<<(y-(-1)*x)+1<<endl;
// }
//
//
//
// }else if(x*(-1)==y){
// printf("1\n");
// }
//}
//}
//--------------------------------------------------------------------------------------------------------
//freopen("leaves.in" , "r" , stdin);
//int t;
//scanf("%d",&t);
//long long u,k;
//while(t--){
// cin>>u>>k;
//
// int l = 2*u;
// int r = 2*u+1;
// int ans = 0;
// q.push(l);
// q.push(r);
// int count = 0;
// while(!q.empty()||count!=k){
// l = q.front();
// q.pop();
// ans = l;
// count++;
// if(count==k)break;
// expand(l);
//
// r = q.front();
// q.pop();
// ans = r;
// count++;
//
// if(count==k)break;
// expand(r);
//
// }
// cout<<ans<<endl;
//
// queue<int> emptyy;
// swap(q,emptyy);
//
//}
//------------------------------------------------------------------------------------------------------------
//freopen("fractions.in" , "r" , stdin);
//int t;
//scanf("%d",&t);
//int n;
//int matrix [505][505];
//while(t--){
// scanf("%d",&n);
// int ans = n*((n*n -n)/2);
// for(int i =1;i<=n;i++){
// for(int j =1;j<n;j++){
// if(i>=j){
// matrix[i][j]=i/j;
// }else if(i<j){
// matrix[i][j]=0;
// }
// }
// }
//
//}
//-----------------------------------------------------------------------------------------------------------------------
//freopen("meetings.in" , "r" , stdin);
//int t;
//scanf("%d",&t);
//int n,k;
//while(t--){
// scanf("%d%d",&n,&k);
// long long duration_day,meeting_day,meeting_profit,meeting_type;
//
//}
return 0;
}
| [
"alielrafei.fcih@gmail.com"
] | alielrafei.fcih@gmail.com |
adb4142d1bdf9e5b0a08e8a83d2c76e222fe7e09 | b77b0ef9529e5385a79f092348301186d56b9696 | /Attempt2/PauseState.cpp | 0b2c3667e681658a99dfc6c653222891d2b14c57 | [] | no_license | GregVanK/Frogger | 5b54a2ce69b72cdce16d390945453729b6c3c141 | cb4c1f07a29a06c7e68de8459b36ee24c1a424c1 | refs/heads/master | 2020-04-06T14:51:23.236454 | 2018-11-14T14:08:51 | 2018-11-14T14:08:51 | 157,556,838 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,811 | cpp | /*
*@author: Greg VanKampen
*@file: PauseState.cpp
*@description: The state of the application when the pause menu is active
*/
#include "PauseState.h"
#include "Utility.h"
#include "FontManager.h"
PauseState::PauseState(GEX::StateStack & stack, Context context)
:State(stack,context),
_backgroundSprite(),
_pausedText(),
_instructionText()
{
_pausedText.setFont(GEX::FontManager::getInstance().getFont(GEX::FontID::Main));
_pausedText.setString("Game Paused");
_pausedText.setCharacterSize(40);
centerOrigin(_pausedText);
_instructionText.setFont(GEX::FontManager::getInstance().getFont(GEX::FontID::Main));
_instructionText.setString("(Press Backspace to return to the main menu");
_instructionText.setCharacterSize(40);
centerOrigin(_instructionText);
sf::Vector2f viewSize = context.window->getView().getSize();
_pausedText.setPosition(0.5f * viewSize.x, 0.4f * viewSize.y);
_instructionText.setPosition(0.5f * viewSize.x, 0.6f * viewSize.y);
context.music->setPaused(true);
}
PauseState::~PauseState()
{
getContext().music->setPaused(false);
}
void PauseState::draw()
{
sf::RenderWindow& window = *getContext().window;
window.setView(window.getDefaultView());
sf::RectangleShape backgroundShape;
backgroundShape.setFillColor(sf::Color(0, 0, 0, 150));
backgroundShape.setSize(window.getView().getSize());
window.draw(backgroundShape);
window.draw(_pausedText);
window.draw(_instructionText);
}
bool PauseState::update(sf::Time dt)
{
return false;
}
bool PauseState::handleEvents(const sf::Event & event)
{
if (event.type != sf::Event::KeyPressed)
return false;
if (event.key.code == sf::Keyboard::Escape)
requestStackPop();
if (event.key.code == sf::Keyboard::BackSpace)
{
requestStackClear();
requestStackPush(GEX::StateID::Menu);
}
return false;
}
| [
"gvankampen@upei.ca"
] | gvankampen@upei.ca |
297157d0e775ad8230d11749a138e9094ab400d9 | dbd57feba75c91c59195d4828def24feffb3c10f | /181/a.cpp | c5504fad01fbfdc9fe2f8666692e92a825dcd832 | [] | no_license | behnamhatami/sgu | e777e484a18557f9d1926d551b1fba1f7ad7d535 | 641271d423688d0777a671820025466dede69aab | refs/heads/master | 2020-06-05T05:38:06.434360 | 2013-04-08T18:00:08 | 2013-04-08T18:00:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 621 | cpp | #include <iostream>
#include <cstdlib>
using namespace std;
const int max_m = 1000;
int a, alpha, beta, gamma, m, k;
int mark[max_m];
void answer(int ans){
cout << ans << endl;
exit(0);
}
void clear(){
for(int i = 0; i < m; i++)
mark[i] = -1;
}
void loop(){
clear();
int lp, x = a % m;
for(int i = 0;; i++){
if(i == k)
answer(x);
if(mark[x] != -1){
lp = i - mark[x];
break;
}else mark[x] = i;
x = (alpha * x * x + beta * x + gamma) % m;
}
a = x;
k -= lp + mark[x];
k %= lp;
loop();
}
int main(){
cin >> a >> alpha >> beta >> gamma >> m >> k;
if(k == 0)
answer(a);
loop();
} | [
"behnamhatami@gmail.com"
] | behnamhatami@gmail.com |
662072ff99e4c6c49a6830b75c00974632d90ae9 | 8ae274674395d228d2620faa315ba978194ff7bb | /casting.cpp | e87da57fea86a7a0f083229aa5768f6dbfa06814 | [] | no_license | MehmetCeylanV/ModernC44 | 53ec348ea74235523a6b70efec6ad14907faa1e4 | a37fae24d1103bfd9d11e813a9e661b72296cdfb | refs/heads/master | 2022-12-16T17:24:13.025121 | 2020-09-03T09:35:57 | 2020-09-03T09:35:57 | 290,993,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 934 | cpp | #include <iostream>
using namespace std;
class Parent{
public:
virtual void something(){
}
};
class SubClass: public Parent{
};
class SubClass2: public Parent{
};
int main(){
Parent* p = new Parent();
SubClass* s = new SubClass();
SubClass2* s2 = new SubClass2();
//Good boy
SubClass* x = dynamic_cast<SubClass*>(p);
if (x == nullptr){
cout << "Invalid Cast" << endl;
}
else{
cout << "Succesfull Cast" << endl;
}
//Maybe
SubClass* y = static_cast<SubClass*>(p);
if (y == nullptr){
cout << "static_cast Invalid Cast" << endl;
}
else{
cout << "static_cast Succesfull Cast" << endl;
}
//Do not do that
SubClass2* z = reinterpret_cast<SubClass2*>(s2);
if (z == nullptr){
cout << "reinterpret_cast Invalid Cast" << endl;
}
else{
cout << "reinterpret_cast Succesfull Cast" << endl;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
1ffdd7a629eb307ec7b557e4775432fce164cef3 | cf593427687d1f2e528f8da4460917fda9d82df6 | /D3D11Plugins/source/GPUTiming.h | af461b3fa93fe495746a6a7b0331687e48eeed9d | [
"MIT"
] | permissive | jazzbre/UnityD3D11Plugins | 74c4a67c84bfc424aca4a48c4b619ad60acfe6ff | b0e84252964c813d6d78ccbd203b4690c11fa234 | refs/heads/master | 2021-04-09T13:57:02.240367 | 2018-03-17T10:25:46 | 2018-03-17T10:25:46 | 125,614,603 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,608 | h | #pragma once
#include <d3d11.h>
#include <vector>
// GPUTimer
struct GPUTimer {
bool Create(ID3D11Device* device) {
D3D11_QUERY_DESC queryDesc = {D3D11_QUERY_TIMESTAMP, 0};
for (int i = 0; i < 2; ++i) {
if (FAILED(device->CreateQuery(&queryDesc, &m_StartQuery[i]))) {
return false;
}
if (FAILED(device->CreateQuery(&queryDesc, &m_EndQuery[i]))) {
return false;
}
}
return true;
}
void Release() {
for (int i = 0; i < 2; ++i) {
if (m_StartQuery[i] != nullptr) {
m_StartQuery[i]->Release();
m_StartQuery[i] = nullptr;
}
if (m_EndQuery[i] != nullptr) {
m_EndQuery[i]->Release();
m_EndQuery[i] = nullptr;
}
}
}
void Begin(ID3D11DeviceContext* deviceContext, int frameIndex) {
deviceContext->End(m_StartQuery[frameIndex]);
}
void End(ID3D11DeviceContext* deviceContext, int frameIndex) {
deviceContext->End(m_EndQuery[frameIndex]);
}
void Update(ID3D11DeviceContext* deviceContext, int frameIndex, uint64_t frequency) {
uint64_t timestampStart = 0;
if (deviceContext->GetData(m_StartQuery[frameIndex], ×tampStart, sizeof(uint64_t), 0) != S_OK) {
return;
}
uint64_t timestampEnd = 0;
if (deviceContext->GetData(m_EndQuery[frameIndex], ×tampEnd, sizeof(uint64_t), 0) != S_OK) {
return;
}
m_Time = (float)((double)(timestampEnd - timestampStart) / (double)frequency);
}
float GetDuration() const {
return m_Time;
}
ID3D11Query* m_StartQuery[2] = {};
ID3D11Query* m_EndQuery[2] = {};
float m_Time = 0.0f;
};
// GPUDisjoint
struct GPUDisjoint {
bool Create(ID3D11Device* device) {
D3D11_QUERY_DESC queryDesc = {D3D11_QUERY_TIMESTAMP_DISJOINT, 0};
for (int i = 0; i < 2; ++i) {
if (FAILED(device->CreateQuery(&queryDesc, &m_Query[i]))) {
return false;
}
}
return true;
}
void Release() {
for (int i = 0; i < 2; ++i) {
if (m_Query[i] != nullptr) {
m_Query[i]->Release();
m_Query[i] = nullptr;
}
}
}
void Begin(ID3D11DeviceContext* deviceContext, int frameIndex) {
deviceContext->Begin(m_Query[frameIndex]);
}
void End(ID3D11DeviceContext* deviceContext, int frameIndex) {
deviceContext->End(m_Query[frameIndex]);
}
bool Update(ID3D11DeviceContext* deviceContext, int frameIndex, uint64_t* frequency) {
if (frequency == nullptr) {
return false;
}
// Wait for query
while (deviceContext->GetData(m_Query[frameIndex], NULL, 0, 0) == S_FALSE) {
Sleep(1);
}
D3D11_QUERY_DATA_TIMESTAMP_DISJOINT timestampDisjoint = {};
// Get data
auto result = deviceContext->GetData(m_Query[frameIndex], ×tampDisjoint, sizeof(timestampDisjoint), 0);
if (result != S_OK) {
return false;
}
// Check if frame is disjointed
if (timestampDisjoint.Disjoint) {
return false;
}
*frequency = timestampDisjoint.Frequency;
return true;
}
ID3D11Query* m_Query[2] = {};
};
// GPUTiming
struct GPUTiming {
bool Initialize(ID3D11Device* device) {
m_Device = device;
// Get context
m_Device->GetImmediateContext(&m_DeviceContext);
// Create disjoint query
if (!m_GPUDisjoint.Create(m_Device)) {
return false;
}
// Get default frame timer
m_FrameTimer.Create(m_Device);
return true;
}
void ReleaseTimers() {
EndFrame();
// Release timers
for (auto& gpuTimer : m_GPUTimers) {
gpuTimer.Release();
}
m_GPUTimers.clear();
}
void Release() {
ReleaseTimers();
// Release frame timer
m_FrameTimer.Release();
// Release disjoint
m_GPUDisjoint.Release();
// Release context
if (m_DeviceContext != nullptr) {
m_DeviceContext->Release();
m_DeviceContext = nullptr;
}
}
int CreateTimer() {
GPUTimer timer;
if (!timer.Create(m_Device)) {
return -1;
}
m_GPUTimers.push_back(timer);
return (int)m_GPUTimers.size() - 1;
}
void BeginFrame() {
if (m_BeginFrameCalled) {
return;
}
m_BeginFrameCalled = true;
m_GPUDisjoint.Begin(m_DeviceContext, m_FrameIndex);
m_FrameTimer.Begin(m_DeviceContext, m_FrameIndex);
}
void EndFrame() {
if (!m_BeginFrameCalled) {
return;
}
m_BeginFrameCalled = false;
m_FrameTimer.End(m_DeviceContext, m_FrameIndex);
m_GPUDisjoint.End(m_DeviceContext, m_FrameIndex);
// Update frame
++m_FrameCounter;
int activeFrameIndex = m_FrameIndex;
m_FrameIndex = !m_FrameIndex;
if (m_FrameCounter < 2) {
return;
}
// Check if disjointed and quit
uint64_t frequency = 0;
if (!m_GPUDisjoint.Update(m_DeviceContext, activeFrameIndex, &frequency)) {
return;
}
m_FrameTimer.Update(m_DeviceContext, activeFrameIndex, frequency);
for (auto& gpuTimer : m_GPUTimers) {
gpuTimer.Update(m_DeviceContext, activeFrameIndex, frequency);
}
}
void BeginTimer(int index) {
if (index < 0 || index >= (int)m_GPUTimers.size()) {
return;
}
m_GPUTimers[index].Begin(m_DeviceContext, m_FrameIndex);
}
void EndTimer(int index) {
if (index < 0 || index >= (int)m_GPUTimers.size()) {
return;
}
m_GPUTimers[index].End(m_DeviceContext, m_FrameIndex);
}
float GetTimerDuration(int index) {
if (index < 0 || index >= (int)m_GPUTimers.size()) {
return 0.0f;
}
return m_GPUTimers[index].GetDuration();
}
float GetFrameTimerDuration() {
return m_FrameTimer.GetDuration();
}
ID3D11Device* m_Device = nullptr;
ID3D11DeviceContext* m_DeviceContext = nullptr;
GPUDisjoint m_GPUDisjoint;
GPUTimer m_FrameTimer;
std::vector<GPUTimer> m_GPUTimers;
bool m_BeginFrameCalled = false;
int m_FrameIndex = 0;
uint64_t m_FrameCounter = 0;
};
| [
"jazzbre@gmail.com"
] | jazzbre@gmail.com |
ad1bfcd3b2eeb74ee3e04663be81f1ff3d21825a | 850a39e68e715ec5b3033c5da5938bbc9b5981bf | /drgraf4_0/MMgrSupp/dlg_supe.h | 01be0600aef7499d0e7b0443065dd8a86b795ee2 | [] | no_license | 15831944/drProjects | 8cb03af6d7dda961395615a0a717c9036ae1ce0f | 98e55111900d6a6c99376a1c816c0a9582c51581 | refs/heads/master | 2022-04-13T12:26:31.576952 | 2020-01-04T04:18:17 | 2020-01-04T04:18:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,870 | h | // Dlg_CurI.h : header file
//
#ifndef _DLG_SUPE_H
#define _DLG_SUPE_H
#include "Def_Supp.h"
#include "DrLinSup.h"
#include "MSupRsrc.h"
/////////////////////////////////////////////////////////////////////////////
// CDlg_SupE dialog
class AFX_EXT_CLASS CDlg_SupE : public CDialog
{
// Construction
public:
CDlg_SupE(CWnd* pParent = NULL); // standard constructor
CDlg_SupE( CDrLinSup* pDrLinSup,CWnd* pParent = NULL);
protected:
void Init();
void UpdateSupInfo();
void EnableControls();
void FillListAllNodeIDs_A();
void FillListAllNodeIDs_B();
protected:
CBitmapButton buttonOK,buttonCancel;
public:
// Dialog Data
//{{AFX_DATA(CDlg_SupE)
enum { IDD = IDD_SUP_EDIT };
double m_dFx;
double m_dFy;
double m_dFz;
double m_dMx;
double m_dMy;
double m_dMz;
BOOL m_bRx;
BOOL m_bRy;
BOOL m_bRz;
BOOL m_bTx;
BOOL m_bTy;
BOOL m_bTz;
BOOL m_bRxG;
BOOL m_bRyG;
BOOL m_bRzG;
BOOL m_bTxG;
BOOL m_bTyG;
BOOL m_bTzG;
CString m_aNid;
CString m_bNid;
BOOL m_bTan;
CString m_SupID;
CString m_strProc;
BOOL m_bCN_a;
BOOL m_bCN_b;
//}}AFX_DATA
BOOL m_bSkewed;
BOOL m_bPat;
BOOL m_bTanCur;
BOOL m_bTanPat;
BOOL m_bNorPat;
BOOL m_bTanHide;
BOOL m_bIdBHide;
SUPPPROC m_SuppProc;
UINT m_SupBased;
CDrLinSup* m_pDrLinSup;
protected:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CDlg_SupE)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CDlg_SupE)
virtual void OnOK();
virtual void OnCancel();
virtual BOOL OnInitDialog();
afx_msg void OnSelchangeNid();
afx_msg void OnTangent();
afx_msg void OnCnB();
afx_msg void OnCnA();
afx_msg void OnSelchangeNidb2();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//////////////////////////////////////
#endif
| [
"sray12345678@gmail.com"
] | sray12345678@gmail.com |
97e753e8d7c51b038484f4559f3dec8b108d0fcd | ab103b0120241d1bd9d19e18797905abad703c2c | /src/Cameras/MotionBlurCamera.h | 77abc9922a04b27fd9d64abbafeb43f3cff09196 | [
"Apache-2.0",
"CC0-1.0"
] | permissive | blizmax/PSRayTracing | 1ad6c0e2d2cdb41942ef1da0d8e1c89fbc53ad39 | 13ce9bd1c70741102903721bf5a207fad2a722c0 | refs/heads/master | 2023-07-19T12:51:46.985658 | 2021-08-24T19:19:28 | 2021-08-24T19:19:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 702 | h | #pragma once
#include "Camera.h"
// A camera that supports motion blue
class MotionBlurCamera : public Camera {
private:
// Data
rreal _time0, _time1; // Shutter open/close times
public:
explicit MotionBlurCamera(
const Vec3 &look_from,
const Vec3 &look_at,
const Vec3 &v_up,
const rreal vfov, // Vertical field of view
const rreal aspect_ratio,
const rreal aperature,
const rreal focus_dist,
const rreal t0, const rreal t1
) NOEXCEPT;
std::shared_ptr<ICamera> deep_copy() const NOEXCEPT override;
Ray get_ray(RandomGenerator &rng, const rreal s, const rreal t) const NOEXCEPT override;
};
| [
"def.pri.pub@gmail.com"
] | def.pri.pub@gmail.com |
675ce8dbe7c228364dc151c4a1faee4a1da5c29e | 2b92aa7b0c8b2657393cd4950745ec568d34280d | /idasdk/include/pro.h | be5cbe6110eb50f928f292f64ce30437a33185f2 | [] | no_license | Nomad-Group/IDASync | d600c3916ae973ff030b27bdb77e78f0dda5e343 | 6c2a3fa16b1c790328ff6975c823db87d0678856 | refs/heads/master | 2020-04-04T08:15:02.351312 | 2018-11-02T15:02:43 | 2018-11-02T15:02:43 | 155,776,719 | 10 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 127,860 | h | /*
* Interactive disassembler (IDA).
* Copyright (c) 1990-2015 Hex-Rays
* ALL RIGHTS RESERVED.
*
*/
#ifndef _PRO_H
#define _PRO_H
/*! \file pro.h
\brief This is the first header included in the IDA project.
It defines the most common types, functions and data.
Also, it tries to make system dependent definitions.
The following preprocessor macros are used in the project
(the list may be incomplete)
Platform must be specified as one of:
__OS2__ - OS/2 \n
__MSDOS__ - MS DOS 32-bit extender \n
__NT__ - MS Windows (all platforms) \n
__LINUX__ - Linux \n
__MAC__ - MAC OS X \n
__BSD__ - FreeBSD
UNDER_CE - Compiling for WindowsCE
__EA64__ - 64-bit address size (sizeof(ea_t)==8) \n
__X64__ - 64-bit IDA itself (sizeof(void*)==8)
__X86__ - Intel x86 processor (default) \n
__PPC__ - PowerPC \n
__ARM__ - ARM
*/
/// IDA SDK v6.8
#define IDA_SDK_VERSION 680
/// x86 processor by default
#ifndef __PPC__
#define __X86__
#endif
// Linux, Mac, or BSD imply Unix
#if defined(__LINUX__) || defined(__MAC__) || defined(__BSD__)
#define __UNIX__
#endif
// Only 64-bit IDA is available on 64-bit platforms
#ifdef __X64__
#undef __EA64__
#define __EA64__
#endif
/// \def{BADMEMSIZE, Invalid memory size}
#ifdef __X64__
#define BADMEMSIZE 0xFFFFFFFFFFFFFFFF
#else
#define BADMEMSIZE 0xFFFFFFFF
#endif
/// \def{ENUM_SIZE, Compiler-independent way to specify size of enum values}
#ifndef SWIG
#if defined(__VC__)
#define ENUM_SIZE(t) : t
#else
#define ENUM_SIZE(t)
#endif
#include <stdlib.h> /* size_t, NULL, memory */
#include <stdarg.h>
#include <stddef.h>
#include <assert.h>
#include <limits.h>
#include <ctype.h>
#include <time.h>
#include <new>
#if defined(__NT__)
# include <malloc.h>
#endif
/// \def{WIN32_LEAN_AND_MEAN, compile faster}
#if defined(__BORLANDC__)
# define WIN32_LEAN_AND_MEAN
# include <io.h>
# include <dir.h>
# include <mem.h>
# include <alloc.h>
#elif defined(_MSC_VER)
# define WIN32_LEAN_AND_MEAN
# include <string.h>
# ifndef UNDER_CE
# include <io.h>
# include <direct.h>
# endif
# include <map>
#else
# include <algorithm>
# include <wchar.h>
# include <string.h>
# include <unistd.h>
# include <sys/stat.h>
# include <errno.h>
#endif
#ifdef UNDER_CE // Many files are missing in Windows CE
void abort(void);
typedef int off_t;
#else
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#endif
#pragma pack(push, 4)
#define STL_SUPPORT_PRESENT
//---------------------------------------------------------------------------
/// \def{EXTERNC, specify C linkage}
/// \def{C_INCLUDE, helper for 'extern "C" {}' statements}
/// \def{C_INCLUDE_END, \copydoc C_INCLUDE}
/// \def{INLINE, inline keyword for c++}
#ifdef __cplusplus
#define EXTERNC extern "C"
#define C_INCLUDE EXTERNC {
#define C_INCLUDE_END }
#define INLINE inline
#else
#define EXTERNC
#define C_INCLUDE
#define C_INCLUDE_END
#define INLINE __inline
#endif
//---------------------------------------------------------------------------
#if !defined(__OS2__) && !defined(__MSDOS__) && !defined(__NT__) \
&& !defined(__LINUX__) && !defined(__MAC__) && !defined(__BSD__)
#error "Please define one of: __NT__, __OS2__, __MSDOS__, __LINUX__,__MAC__,__BSD__"
#endif
#endif // SWIG
//---------------------------------------------------------------------------
#ifndef MAXSTR
#define MAXSTR 1024 ///< maximum string size
#endif
#define SMAXSTR QSTRINGIZE(MAXSTR) ///< get #MAXSTR as a string
/// \def{NT_CDECL, Some NT functions require __cdecl calling convention}
#ifdef __NT__
#define NT_CDECL __cdecl
#else
#define NT_CDECL
#endif
/// \def{DEPRECATED, identifies parts of the IDA API that are considered deprecated}
/// \def{NORETURN, function does not return}
/// \def{PACKED, type is packed}
/// \def{AS_PRINTF, function accepts printf-style format and args}
/// \def{AS_SCANF, function accepts scanf-style format and args}
#if defined(SWIG)
#define DEPRECATED
#define NORETURN
#define PACKED
#define AS_PRINTF(format_idx, varg_idx)
#define AS_SCANF(format_idx, varg_idx)
#elif defined(__GNUC__)
#define DEPRECATED __attribute__((deprecated))
#define NORETURN __attribute__((noreturn))
#define PACKED __attribute__((__packed__))
#define AS_PRINTF(format_idx, varg_idx) __attribute__((format(printf, format_idx, varg_idx)))
#define AS_SCANF(format_idx, varg_idx) __attribute__((format(scanf, format_idx, varg_idx)))
#else
#define DEPRECATED __declspec(deprecated)
#define NORETURN __declspec(noreturn)
#define PACKED
#define AS_PRINTF(format_idx, varg_idx)
#define AS_SCANF(format_idx, varg_idx)
#endif
/// \def{GCC_DIAG_OFF, disable a specific GCC warning for the following code}
/// \def{GCC_DIAG_ON, enable or restore a specific GCC warning for the following code}
#if defined(__GNUC__) && !defined(SWIG) && ((__GNUC__ * 100) + __GNUC_MINOR__) >= 402
#define GCC_DIAG_JOINSTR(x,y) _QSTRINGIZE(x ## y)
# define GCC_DIAG_DO_PRAGMA(x) _Pragma (#x)
# define GCC_DIAG_PRAGMA(x) GCC_DIAG_DO_PRAGMA(GCC diagnostic x)
# if ((__GNUC__ * 100) + __GNUC_MINOR__) >= 406
# define GCC_DIAG_OFF(x) GCC_DIAG_PRAGMA(push) \
GCC_DIAG_PRAGMA(ignored GCC_DIAG_JOINSTR(-W,x))
# define GCC_DIAG_ON(x) GCC_DIAG_PRAGMA(pop)
# else
# define GCC_DIAG_OFF(x) GCC_DIAG_PRAGMA(ignored GCC_DIAG_JOINSTR(-W,x))
# define GCC_DIAG_ON(x) GCC_DIAG_PRAGMA(warning GCC_DIAG_JOINSTR(-W,x))
# endif
#else
# define GCC_DIAG_OFF(x)
# define GCC_DIAG_ON(x)
#endif
#if defined(DONT_DEPRECATE) || defined(__BORLANDC__)
#undef DEPRECATED
#define DEPRECATED
#endif
//---------------------------------------------------------------------------
#define __MF__ 0 ///< byte sex of our platform (Most significant byte First).
///< 0: little endian (Intel 80x86).
///< 1: big endian (PowerPC).
//---------------------------------------------------------------------------
/// Macro to avoid of message 'Parameter x is never used'
#define qnotused(x) (void)x
/// \def{va_argi, GNU C complains about some data types in va_arg because they are promoted to int and proposes to replace them by int}
#ifdef __GNUC__
#define va_argi(va, type) ((type)va_arg(va, int))
#else
#define va_argi(va, type) va_arg(va, type)
#endif
//---------------------------------------------------------------------------
#define CONST_CAST(x) const_cast<x> ///< cast a const to non-const
#define _QSTRINGIZE(x) #x ///< return x as a string. See #SMAXSTR for example
#define QSTRINGIZE(x) _QSTRINGIZE(x) ///< see #_QSTRINGIZE
//---------------------------------------------------------------------------
/// \def{idaapi, specifies __stdcall calling convention}
/// \def{ida_export, functions marked with this keyword are available as part of the IDA SDK}
/// \def{idaman, specifies c linkage}
/// \def{ida_export_data, data items marked with this keyword are available as part of the IDA SDK}
/// \def{ida_module_data, identifies a data item that will be exported}
/// \def{ida_local, identifies a non-public type definition}
#if defined(SWIG) // for SWIG
#define idaapi
#define idaman
#define ida_export
#define ida_export_data
#define ida_module_data
#define __fastcall
#define ida_local
#elif defined(__NT__) // MS Windows
#define idaapi __stdcall
#define ida_export idaapi
#ifdef _lint
// tell lint that this function will be exported
#define idaman EXTERNC __declspec(dllexport)
#else
#define idaman EXTERNC
#endif
#if defined(__IDP__) // modules
#define ida_export_data __declspec(dllimport)
#define ida_module_data __declspec(dllexport)
#else // kernel
#define ida_export_data
#define ida_module_data
#endif
#define ida_local
#elif defined(__UNIX__) // for unix
#define idaapi
#if defined(__MAC__)
#define idaman EXTERNC __attribute__((visibility("default")))
#define ida_local __attribute__((visibility("hidden")))
#else
#if __GNUC__ >= 4
#define idaman EXTERNC __attribute__ ((visibility("default")))
#define ida_local __attribute__((visibility("hidden")))
#else
#define idaman EXTERNC
#define ida_local
#endif
#endif
#define ida_export
#define ida_export_data
#define ida_module_data
#define __fastcall
#endif
/// Functions callable from any thread are marked with this keyword
#define THREAD_SAFE
//---------------------------------------------------------------------------
#ifndef __cplusplus
typedef int bool;
#define false 0
#define true 1
#endif
//---------------------------------------------------------------------------
// Linux C mode compiler already has these types defined
#if !defined(__LINUX__) || defined(__cplusplus)
typedef unsigned char uchar; ///< unsigned 8 bit value
typedef unsigned short ushort; ///< unsigned 16 bit value
typedef unsigned int uint; ///< unsigned 32 bit value
#endif
typedef char int8; ///< signed 8 bit value
typedef signed char sint8; ///< signed 8 bit value
typedef unsigned char uint8; ///< unsigned 8 bit value
typedef short int16; ///< signed 16 bit value
typedef unsigned short uint16; ///< unsigned 16 bit value
typedef int int32; ///< signed 32 bit value
typedef unsigned int uint32; ///< unsigned 32 bit value
#include <llong.hpp>
typedef longlong int64; ///< signed 64 bit value
typedef ulonglong uint64; ///< unsigned 64 bit value
/// \fn{int64 qatoll(const char *nptr), Convert string to 64 bit integer}
#if defined(__UNIX__)
inline int64 qatoll(const char *nptr) { return atoll(nptr); }
#elif defined(_MSC_VER)
inline int64 qatoll(const char *nptr) { return _atoi64(nptr); }
#else
inline int64 qatoll(const char *nptr) { return atol(nptr); }
#endif
/// \typedef{wchar16_t, 2-byte char}
/// \typedef{wchar32_t, 4-byte char}
#if defined(__BORLANDC__) || defined(_MSC_VER)
typedef wchar_t wchar16_t;
typedef uint32 wchar32_t;
#elif defined(__GNUC__)
typedef uint16 wchar16_t;
typedef uint32 wchar32_t;
#endif
/// Signed size_t - used to check for size overflows when the counter becomes
/// negative. Also signed size_t allows us to signal an error condition using
/// a negative value, for example, as a function return value.
#if !defined(_SSIZE_T_DEFINED) && !defined(__ssize_t_defined) && !defined(__GNUC__)
typedef ptrdiff_t ssize_t;
#endif
/// \def{FMT_64, compiler-specific printf format specifier for 64-bit numbers}
/// \def{FMT_Z, compiler-specific printf format specifier for size_t}
/// \def{FMT_ZS, compiler-specific printf format specifier for ssize_t}
#if defined(__GNUC__) && !defined(__MINGW32__)
#define FMT_64 "ll"
#define FMT_Z "zu"
#define FMT_ZS "zd"
#elif defined(_MSC_VER) || defined(__MINGW32__)
#define FMT_64 "I64"
#ifdef __X64__
#define FMT_Z "I64u"
#define FMT_ZS "I64d"
#else
#define FMT_Z "u"
#define FMT_ZS "d"
#endif
#elif defined(__BORLANDC__)
#define FMT_64 "L"
#define FMT_Z "u"
#define FMT_ZS "d"
#elif !defined(SWIG)
#error "unknown compiler"
#endif
/// \typedef{ea_t, effective address}
/// \typedef{sel_t, segment selector}
/// \typedef{asize_t, memory chunk size}
/// \typedef{adiff_t, address difference}
/// \def{SVAL_MIN, minimum value for an object of type int}
/// \def{SVAL_MAX, maximum value for an object of type int}
/// \def{FMT_EA, format specifier for ::ea_t values}
#ifdef __EA64__
typedef uint64 ea_t;
typedef uint64 sel_t;
typedef uint64 asize_t;
typedef int64 adiff_t;
#define FMT_EA FMT_64
#ifdef __GNUC__
#define SVAL_MIN LLONG_MIN
#define SVAL_MAX LLONG_MAX
#else
#define SVAL_MIN _I64_MIN
#define SVAL_MAX _I64_MAX
#endif
#else
typedef uint32 ea_t;
typedef uint32 sel_t;
typedef uint32 asize_t;
typedef int32 adiff_t;
#define SVAL_MIN INT_MIN
#define SVAL_MAX INT_MAX
#define FMT_EA ""
#endif
typedef asize_t uval_t; ///< unsigned value used by the processor.
///< - for 32-bit ::ea_t - ::uint32
///< - for 64-bit ::ea_t - ::uint64
typedef adiff_t sval_t; ///< signed value used by the processor.
///< - for 32-bit ::ea_t - ::int32
///< - for 64-bit ::ea_t - ::int64
#ifndef SWIG
#define BADADDR ea_t(-1) ///< this value is used for 'bad address'
#define BADSEL sel_t(-1) ///< 'bad selector' value
//-------------------------------------------------------------------------
// Time related functions
typedef int32 qtime32_t; ///< we use our own time type because time_t
///< can be 32-bit or 64-bit depending on the compiler
typedef uint64 qtime64_t; ///< 64-bit time value expressed as seconds and
///< microseconds since the Epoch
/// Get the 'seconds since the epoch' part of a qtime64_t
inline uint32 get_secs(qtime64_t t)
{
return uint32(t>>32);
}
/// Get the microseconds part of a qtime64_t
inline uint32 get_usecs(qtime64_t t)
{
return uint32(t);
}
/// Get a ::qtime64_t instance from a seconds value and microseconds value.
/// \param secs seconds
/// \param usecs microseconds
inline qtime64_t make_qtime64(uint32 secs, int32 usecs=0)
{
return (qtime64_t(secs) << 32) | usecs;
}
/// Converts calendar time into a string.
/// Puts 'wrong timestamp\\n' into the buffer if failed
/// \param buf output buffer
/// \param bufsize size of the output buffer
/// \param t calendar time
/// \return success
idaman THREAD_SAFE bool ida_export qctime(char *buf, size_t bufsize, qtime32_t t);
/// Converts calendar time into a string using Coordinated Universal Time (UTC).
/// Function is equivalent to asctime(gmtime(t)).
/// Puts 'wrong timestamp\\n' into the buffer if failed.
/// \param buf output buffer
/// \param bufsize of the output buffer
/// \param t calendar time
/// \return success
idaman THREAD_SAFE bool ida_export qctime_utc(char *buf, size_t bufsize, qtime32_t t);
/// Converts a time value to a tm structure.
/// \param[out] _tm result
/// \param t local time
/// \returns success
idaman THREAD_SAFE bool ida_export qlocaltime(struct tm *_tm, qtime32_t t);
/// Same as qlocaltime(struct tm *, qtime32_t), but accepts a 64-bit time value
inline THREAD_SAFE bool qlocaltime64(struct tm *_tm, qtime64_t t)
{
return qlocaltime(_tm, get_secs(t));
}
/// Get string representation of a qtime32_t.
/// Copies into 'buf' the content of 'format', expanding its format specifiers into the
/// corresponding values that represent the time described in 't', with a limit of 'bufsize' characters
/// see http://www.cplusplus.com/reference/ctime/strftime/ for more
/// \param buf output buffer
/// \param bufsize of the output buffer
/// \param format format string
/// \param t time value
/// \return length of the resulting string
idaman THREAD_SAFE size_t ida_export qstrftime(char *buf, size_t bufsize, const char *format, qtime32_t t);
/// Same as qstrftime(), but accepts a 64-bit time value
idaman THREAD_SAFE size_t ida_export qstrftime64(char *buf, size_t bufsize, const char *format, qtime64_t t);
/// Suspend execution for given number of milliseconds
idaman THREAD_SAFE void ida_export qsleep(int milliseconds);
/// High resolution timer.
/// On Unix systems, returns current time in nanoseconds.
/// On Windows, returns a high resolution counter (QueryPerformanceCounter)
/// \param[out] nsecs result
idaman THREAD_SAFE void ida_export get_nsec_stamp(uint64 *nsecs);
/// Get the current time with microsecond resolution (in fact the resolution
/// is worse on windows)
idaman THREAD_SAFE qtime64_t ida_export qtime64(void);
/// Generate a random buffer.
/// \param[out] buffer pointer to result
/// \param bufsz size of buffer
/// \return success
idaman THREAD_SAFE bool ida_export gen_rand_buf(void *buffer, size_t bufsz);
#define qoff64_t int64 ///< file offset
/// Describes miscellaneous file attributes
struct qstatbuf64
{
uint64 qst_dev; ///< ID of device containing file
uint32 qst_ino; ///< inode number
uint32 qst_mode; ///< protection
uint32 qst_nlink; ///< number of hard links
uint32 qst_uid; ///< user ID of owner
uint32 qst_gid; ///< group ID of owner
uint64 qst_rdev; ///< device ID (if special file)
qoff64_t qst_size; ///< total size, in bytes
int32 qst_blksize; ///< blocksize for file system I/O
int32 qst_blocks; ///< number of 512B blocks allocated
qtime64_t qst_atime; ///< time of last access
qtime64_t qst_mtime; ///< time of last modification
qtime64_t qst_ctime; ///< time of last status change
};
// non standard functions are missing:
#ifdef _MSC_VER
#if _MSC_VER <= 1200
#define for if(0) ; else for ///< MSVC <= 1200 is not compliant to the ANSI standard
#else
#pragma warning(disable : 4200) ///< zero-sized array in structure (non accept from cmdline)
#endif
/// \name VS posix names
/// Shut up Visual Studio (VS deprecated posix names but there seems to be no good reason for that)
//@{
#define chdir _chdir
#define fileno _fileno
#define getcwd _getcwd
#define memicmp _memicmp
//@}
#endif
/// Is this IDA kernel? If not, we are executing a standalone application
idaman bool ida_export_data is_ida_kernel;
//---------------------------------------------------------------------------
/* error codes */
/*--------------------------------------------------*/
#define eOk 0 ///< no error
#define eOS 1 ///< os error, see errno
#define eDiskFull 2 ///< disk full
#define eReadError 3 ///< read error
#define eFileTooLarge 4 ///< file too large
/// Error code (errno)
typedef int error_t;
/// Set qerrno
idaman THREAD_SAFE error_t ida_export set_qerrno(error_t code);
/// Get qerrno
idaman THREAD_SAFE error_t ida_export get_qerrno(void);
//---------------------------------------------------------------------------
/// Constant to specify which platform we're on
enum ostype_t
{
osMSDOS, ///< MS DOS 32-bit extender
osAIX_RISC, ///< IBM AIX RS/6000
osOS2, ///< OS/2
osNT, ///< MS Windows (all platforms)
osLINUX, ///< Linux
osMACOSX, ///< Mac OS X
osBSD, ///< FreeBSD
};
extern ostype_t ostype; ///< set based on which of __NT__, __MAC__, ... is defined
//---------------------------------------------------------------------------
// debugging macros
/// \def{ZZZ, debug print}
/// \def{BPT, trigger a breakpoint from IDA. also see #INTERR}
#define ZZZ msg("%s:%d\n", __FILE__, __LINE__)
#if defined(__BORLANDC__)
# define BPT __emit__(0xcc)
# define __FUNCTION__ __FUNC__
#elif defined(__GNUC__)
# ifdef __arm__
# ifdef __LINUX__
# define BPT __builtin_trap()
# else
# define BPT asm("trap")
# endif
# else
# define BPT asm("int3")
# endif
#elif defined(_MSC_VER) // Visual C++
# define BPT __debugbreak()
# ifdef _lint
NORETURN void __debugbreak(void);
# endif
#endif
/// \def{__CASSERT_N0__, compile time assertion}
/// \def{__CASSERT_N1__, compile time assertion}
/// \def{CASSERT, results in a compile error if the cnd is not true}
/// \def{CASSERT0, returns 0 if cnd is true - otherwise results in a compile error}
#ifdef _lint
#define CASSERT(cnd) extern int pclint_cassert_dummy_var
#define CASSERT0(cnd) 0
#else
#define __CASSERT_N0__(l) COMPILE_TIME_ASSERT_ ## l
#define __CASSERT_N1__(l) __CASSERT_N0__(l)
#define CASSERT(cnd) typedef char __CASSERT_N1__(__LINE__) [(cnd) ? 1 : -1]
#define CASSERT0(cnd) (sizeof(char [1 - 2*!(cnd)]) - 1)
#endif
/// \def{INTERR, Show internal error message and terminate execution abnormally.
/// When IDA is being run under a debugger this will ensure that
/// the debugger will break immediately.}
#if defined(UNDER_CE) || defined(_lint)
#define INTERR(code) interr(code)
#else
#define INTERR(code) do { if ( under_debugger ) BPT; interr(code); } while(1)
#endif
#define QASSERT(code, cond) do if ( !(cond) ) INTERR(code); while (0) ///< run time assertion
#define QBUFCHECK(buf, size, src) ida_fill_buffer(buf, size, src, __FILE__, __LINE__) ///< run time assertion
idaman bool ida_export_data under_debugger; ///< is IDA running under a debugger?
idaman THREAD_SAFE NORETURN void ida_export interr(int code); ///< Show internal error message and terminate execution
//---------------------------------------------------------------------------
idaman THREAD_SAFE void *ida_export qalloc(size_t size); ///< System independent malloc
idaman THREAD_SAFE void *ida_export qrealloc(void *alloc, size_t newsize); ///< System independent realloc
idaman THREAD_SAFE void *ida_export qcalloc(size_t nitems, size_t itemsize); ///< System independent calloc
idaman THREAD_SAFE void ida_export qfree(void *alloc); ///< System independent free
idaman THREAD_SAFE char *ida_export qstrdup(const char *string); ///< System independent strdup
#define qnew(t) ((t*)qalloc(sizeof(t))) ///< create a new object in memory
/// \def{qnewarray, qalloc_array() is safer than qnewarray}
#ifdef NO_OBSOLETE_FUNCS
#define qnewarray(t,n) use_qalloc_array
#else
#define qnewarray(t,n) ((t*)qcalloc((n),sizeof(t)))
#endif
/// Use this class to avoid integer overflows when allocating arrays
template <class T>
T *qalloc_array(size_t n)
{
return (T *)qcalloc(n, sizeof(T));
}
/// Use this class to avoid integer overflows when allocating arrays
template <class T>
T *qrealloc_array(T *ptr, size_t n)
{
size_t nbytes = n * sizeof(T);
if ( nbytes < n )
return NULL; // integer overflow
return (T *)qrealloc(ptr, nbytes);
}
/// \def{qnumber, determine capacity of an array}
#if defined(__GNUC__) || defined(UNDER_CE)
# define qnumber(arr) ( \
0 * sizeof(reinterpret_cast<const ::qnumber_check_type *>(arr)) + \
0 * sizeof(::qnumber_check_type::check_type((arr), &(arr))) + \
sizeof(arr) / sizeof((arr)[0]) )
struct qnumber_check_type
{
struct is_pointer;
struct is_array {};
template <typename T>
static is_pointer check_type(const T *, const T * const *);
static is_array check_type(const void *, const void *);
};
#elif defined(_MSC_VER) && !defined(__LINT__)
# define qnumber(array) _countof(array)
#else // poor man's implementation for other compilers and lint
# define qnumber(array) (sizeof(array)/sizeof(array[0]))
#endif
/// \def{qoffsetof, gcc complains about offsetof() - we had to make our version}
#ifdef __GNUC__
#define qoffsetof(type, name) size_t(((char *)&((type *)1)->name)-(char*)1)
#else
#define qoffsetof offsetof
#endif
/// \def{set_vva, extracts a va_list passed as a variadic function argument}
/// \def{va_copy, copy a va_list}
#if defined(__GNUC__) && defined(__X64__)
// gcc64 uses special array-type va_list, so we have to resort to tricks like these
#define set_vva(va2, vp) va_copy(va2, *(va_list*)va_arg(vp, void*))
#else
#ifndef va_copy
#define va_copy(dst, src) dst = src
#endif
#if defined(__clang__)
#define set_vva(va2, vp) va2 = va_arg(vp, va_list)
#else
#define set_vva(va2, vp) va_copy(va2, va_arg(vp, va_list))
#endif
#endif
/// Reverse memory block.
/// Analog of strrev() function
/// \param buf pointer to buffer to reverse
/// \param size size of buffer
/// \return pointer to buffer
idaman THREAD_SAFE void *ida_export memrev(void *buf, ssize_t size);
#ifdef __GNUC__
idaman THREAD_SAFE int ida_export memicmp(const void *x, const void *y, size_t size);
#endif
//---------------------------------------------------------------------------
/* strings */
/// \def{strnicmp, see 'VS posix names'}
/// \def{stricmp, see 'VS posix names'}
#ifdef __GNUC__
#define strnicmp strncasecmp
#define stricmp strcasecmp
#elif defined(_MSC_VER) && !defined(_lint)
#define strnicmp _strnicmp
#define stricmp _stricmp
#endif
/// Replace all occurrences of a character within a string.
/// \param str to modify
/// \param char1 char to be replaced
/// \param char2 replacement char
/// \return pointer to resulting string
idaman THREAD_SAFE char *ida_export strrpl(char *str, int char1, int char2);
/// Get tail of a string
inline char *tail( char *str) { return strchr(str, '\0'); }
/// \copydoc tail(char *)
inline const char *tail(const char *str) { return strchr(str, '\0'); }
/// A safer strncpy - makes sure that there is a terminating zero.
/// nb: this function doesn't fill the whole buffer zeroes as strncpy does
/// nb: ssize_t(dstsize) must be > 0
idaman THREAD_SAFE char *ida_export qstrncpy(char *dst, const char *src, size_t dstsize);
/// A safer stpncpy - returns pointer to the end of the destination
/// nb: ssize_t(dstsize) must be > 0
idaman THREAD_SAFE char *ida_export qstpncpy(char *dst, const char *src, size_t dstsize);
/// A safer strncat - accepts the size of the 'dst' as 'dstsize' and returns dst
/// nb: ssize_t(dstsize) must be > 0
idaman THREAD_SAFE char *ida_export qstrncat(char *dst, const char *src, size_t dstsize);
/// Thread-safe version of strtok
idaman THREAD_SAFE char *ida_export qstrtok(char *s, const char *delim, char **save_ptr);
/// Convert the string to lowercase
idaman THREAD_SAFE char *ida_export qstrlwr(char *str);
/// Convert the string to uppercase
idaman THREAD_SAFE char *ida_export qstrupr(char *str);
/// Find one string in another (Case insensitive analog of strstr()).
/// \param s1 string to be searched
/// \param s2 string to search for
/// \return a pointer to the first occurrence of s2 within s1, NULL if none exists
idaman THREAD_SAFE const char *ida_export stristr(const char *s1, const char *s2);
/// Same as stristr(const char *, const char *) but returns a non-const result
inline char *idaapi stristr(char *s1, const char *s2) { return CONST_CAST(char *)(stristr((const char *)s1, s2)); }
/// is...() functions misbehave with 'char' argument. introduce more robust function
inline bool ida_local qisspace(char c) { return isspace(uchar(c)) != 0; }
inline bool ida_local qisalpha(char c) { return isalpha(uchar(c)) != 0; } ///< see qisspace()
inline bool ida_local qisalnum(char c) { return isalnum(uchar(c)) != 0; } ///< see qisspace()
inline bool ida_local qispunct(char c) { return ispunct(uchar(c)) != 0; } ///< see qisspace()
inline bool ida_local qislower(char c) { return islower(uchar(c)) != 0; } ///< see qisspace()
inline bool ida_local qisupper(char c) { return isupper(uchar(c)) != 0; } ///< see qisspace()
inline bool ida_local qisprint(char c) { return isprint(uchar(c)) != 0; } ///< see qisspace()
inline bool ida_local qisdigit(char c) { return isdigit(uchar(c)) != 0; } ///< see qisspace()
inline bool ida_local qisxdigit(char c) { return isxdigit(uchar(c)) != 0; } ///< see qisspace()
/// Get lowercase equivalent of given char
inline char ida_local qtolower(char c) { return tolower(uchar(c)); }
/// Get uppercase equivalent of given char
inline char ida_local qtoupper(char c) { return toupper(uchar(c)); }
// We forbid using dangerous functions in IDA
#if !defined(USE_DANGEROUS_FUNCTIONS) && !defined(_lint)
#if defined(__BORLANDC__) && (__BORLANDC__ < 0x560 || __BORLANDC__ >= 0x580) // for BCB5 (YH)
#include <stdio.h>
#endif
#undef strcpy
#define strcpy dont_use_strcpy ///< use qstrncpy()
#define stpcpy dont_use_stpcpy ///< use qstpncpy()
#define strncpy dont_use_strncpy ///< use qstrncpy()
#define strcat dont_use_strcat ///< use qstrncat()
#define strncat dont_use_strncat ///< use qstrncat()
#define gets dont_use_gets ///< use qfgets()
#define sprintf dont_use_sprintf ///< use qsnprintf()
#define snprintf dont_use_snprintf ///< use qsnprintf()
#define wsprintfA dont_use_wsprintf ///< use qsnprintf()
#undef strcmpi
#undef strncmpi
#define strcmpi dont_use_strcmpi ///< use stricmp()
#define strncmpi dont_use_strncmpi ///< use strnicmp()
#define getenv dont_use_getenv ///< use qgetenv()
#define setenv dont_use_setenv ///< use qsetenv()
#define putenv dont_use_putenv ///< use qsetenv()
#define strtok dont_use_strrok ///< use qstrtok()
#undef strlwr
#undef strupr
#define strlwr dont_use_strlwr ///< use qstrlwr()
#define strupr dont_use_strupr ///< use qstrupr()
#define waitid dont_use_waitid ///< use qwait()
#define waitpid dont_use_waitpid ///< use qwait()
#define wait dont_use_wait ///< use qwait()
#endif
//---------------------------------------------------------------------------
#define streq(s1, s2) (strcmp((s1), (s2)) == 0) ///< convenient check for string equality
#define strieq(s1, s2) (stricmp((s1), (s2)) == 0) ///< see #streq
#define strneq(s1, s2, count) (strncmp((s1), (s2), (count)) == 0) ///< see #streq
#define strnieq(s1, s2, count) (strnicmp((s1), (s2), (count)) == 0) ///< see #streq
//---------------------------------------------------------------------------
/// \defgroup qsnprintf qsnprintf/qsscanf
/// safer versions of sprintf/sscanf
///
/// Our definitions of sprintf-like functions support one additional format specifier
///
/// "%a" which corresponds to ::ea_t
///
/// Usual optional fields like the width can be used too: %04a.
/// The width specifier will be doubled for 64-bit version.
/// These function return the number of characters _actually written_ to the output string.
/// excluding the terminating zero. (which is different from the snprintf).
/// They always terminate the output with a zero byte (if n > 0).
//@{
idaman AS_PRINTF(3, 4) THREAD_SAFE int ida_export qsnprintf(char *buffer, size_t n, const char *format, ...); ///< A safer snprintf
idaman AS_SCANF (2, 3) THREAD_SAFE int ida_export qsscanf(const char *input, const char *format, ...); ///< A safer sscanf
idaman AS_PRINTF(3, 0) THREAD_SAFE int ida_export qvsnprintf(char *buffer, size_t n, const char *format, va_list va); ///< See qsnprintf()
idaman AS_SCANF (2, 0) THREAD_SAFE int ida_export qvsscanf(const char *input, const char *format, va_list va); ///< See qsscanf()
idaman AS_PRINTF(3, 4) THREAD_SAFE int ida_export append_snprintf(char *buf, const char *end, const char *format, ...); ///< Append result of sprintf to 'buf'
//@}
//---------------------------------------------------------------------------
/// qsnprintf that does not check its arguments.
/// Normally gcc complains about the non-literal formats. However, sometimes we
/// still need to call qsnprintf with a dynamically built format string.
/// OTOH, there are absolutely no checks of the input arguments, so be careful!
GCC_DIAG_OFF(format-nonliteral);
inline int nowarn_qsnprintf(char *buf, size_t size, const char *format, ...)
{
va_list va;
va_start(va, format);
int code = ::qvsnprintf(buf, size, format, va);
va_end(va);
return code;
}
GCC_DIAG_ON(format-nonliteral);
//---------------------------------------------------------------------------
/// \def{QMAXPATH, maximum number of characters in a path specification}
/// \def{QMAXFILE, maximum number of characters in a filename specification}
#if defined(__NT__)
#define QMAXPATH 260
#define QMAXFILE 260
#else
#define QMAXPATH PATH_MAX
#define QMAXFILE PATH_MAX
#endif
idaman THREAD_SAFE char *ida_export vqmakepath(char *buf, size_t bufsize, const char *s1, va_list); ///< See qmakepath()
/// Construct a path from a null-terminated sequence of strings.
/// \param buf output buffer. Can be == s1, but must not be NULL
/// \param bufsize size of buffer
/// \return pointer to result
idaman THREAD_SAFE char *ida_export qmakepath(char *buf, size_t bufsize, const char *s1, ...);
/// Get the current working directory.
/// \param buf output buffer
/// \param bufsize size of buffer
/// This function calls error() if any problem occurs.
idaman void ida_export qgetcwd(char *buf, size_t bufsize);
/// Get the directory part of the path.
/// path and buf may point to the same buffer
/// \param[out] buf buffer for the directory part. can be NULL.
/// \param[out] bufsize size of this buffer
/// \param path path to split
/// \retval true ok
/// \retval false input buffer did not have the directory part.
/// In this case the buffer is filled with "."
idaman THREAD_SAFE bool ida_export qdirname(char *buf, size_t bufsize, const char *path);
/// Construct filename from base name and extension.
/// \param buf output buffer. Can be == base, but must not be NULL
/// \param bufsize size of buffer
/// \param base base name
/// \param ext extension
/// \return pointer to result
idaman THREAD_SAFE char *ida_export qmakefile(
char *buf,
size_t bufsize,
const char *base,
const char *ext);
/// Split filename into base name and extension.
/// \param file filename, may be changed
/// \param base filled with base part, can be NULL
/// \param ext filled with extension part, can be NULL
/// \return the base part
idaman THREAD_SAFE char *ida_export qsplitfile(char *file, char **base, char **ext);
/// Is the file name absolute (not relative to the current dir?)
idaman THREAD_SAFE bool ida_export qisabspath(const char *file);
/// Get the file name part of the given path.
/// \return NULL if path is NULL
idaman THREAD_SAFE const char *ida_export qbasename(const char *path);
#ifdef __cplusplus
/// Same as qbasename(const char *), but accepts and returns non-const char pointers
inline char *qbasename(char *path) { return CONST_CAST(char *)(qbasename((const char *)path)); }
#endif
/// Convert relative path to absolute path
idaman THREAD_SAFE char *ida_export qmake_full_path(char *dst, size_t dstsize, const char *src);
/// Search for a file in the PATH environment variable or the current directory.
/// \param file the file name to look for. If the file is an absolute path
/// then buf will return the file value.
/// \param buf output buffer to hold the full file path
/// \param bufsize output buffer size
/// \param search_cwd search the current directory if file was not found in the PATH
/// \return true if the file was found and false otherwise
idaman THREAD_SAFE bool ida_export search_path(
const char *file,
char *buf,
size_t bufsize,
bool search_cwd);
/// Delimiter of directory lists
#if defined(__UNIX__)
#define DELIMITER ":" ///< for Unix - ';' for Windows
#else
#define DELIMITER ";" ///< for MS DOS, Windows, other systems - ':' for Unix
#endif
/// Set file name extension unconditionally.
/// \param outbuf buffer to hold the answer. may be the same
/// as the file name.
/// \param bufsize output buffer size
/// \param file the file name
/// \param ext new extension (with or without '.')
/// \return pointer to the new file name
idaman THREAD_SAFE char *ida_export set_file_ext(
char *outbuf,
size_t bufsize,
const char *file,
const char *ext);
/// Get pointer to extension of file name.
/// \param file filename
/// \return pointer to the file extension or NULL if extension doesn't exist
idaman THREAD_SAFE const char *ida_export get_file_ext(const char *file);
/// Does the given file name have an extension?
#ifdef __cplusplus
inline bool idaapi has_file_ext(const char *file)
{ return get_file_ext(file) != NULL; }
#endif
/// Set file name extension if none exists.
/// This function appends the extension to a file name.
/// It won't change file name if extension already exists
/// \param buf output buffer
/// \param bufsize size of the output buffer
/// \param file file name
/// \param ext extension (with or without '.')
/// \return pointer to the new file name
#ifdef __cplusplus
inline char *idaapi make_file_ext(
char *buf,
size_t bufsize,
const char *file,
const char *ext)
{
if ( has_file_ext(file) )
return ::qstrncpy(buf, file, bufsize);
else
return set_file_ext(buf, bufsize, file, ext);
}
#endif
/// Sanitize the file name.
/// Remove the directory path, and replace wildcards ? * and chars<' ' with _.
/// If the file name is empty, then:
/// - namesize != 0: generate a new temporary name, return true
/// - namesize == 0: return false
idaman THREAD_SAFE bool ida_export sanitize_file_name(char *name, size_t namesize);
//---------------------------------------------------------------------------
/* input/output */
/*--------------------------------------------------*/
#if !defined(__MSDOS__) && !defined(__OS2__) && !defined(__NT__) && !defined(_MSC_VER)
#define O_BINARY 0
#endif
#ifndef SEEK_SET
#define SEEK_SET 0 ///< beginning of file
#define SEEK_CUR 1 ///< current position of the file *
#define SEEK_END 2 ///< end of file *
#endif
/*--------------------------------------------------*/
/* you should use these functions for file i/o */
/// Works the same as it's counterpart from Clib.
/// The only difference is that it sets 'qerrno' variable too
idaman THREAD_SAFE int ida_export qopen(const char *file, int mode);
/// Open file with given sharing_mode (use O_RDONLY, O_WRONLY, O_RDWR flags), sets qerrno
idaman THREAD_SAFE int ida_export qopen_shared(const char *file, int mode, int share_mode);
/// Create new file with O_RDWR, sets qerrno
idaman THREAD_SAFE int ida_export qcreate(const char *file, int stat);
idaman THREAD_SAFE int ida_export qread(int h, void *buf, size_t n); ///< \copydoc qopen
idaman THREAD_SAFE int ida_export qwrite(int h, const void *buf, size_t n); ///< \copydoc qopen
idaman THREAD_SAFE int32 ida_export qtell(int h); ///< \copydoc qopen
idaman THREAD_SAFE int32 ida_export qseek(int h, int32 offset, int whence); ///< \copydoc qopen
idaman THREAD_SAFE int ida_export qclose(int h); ///< \copydoc qopen
idaman THREAD_SAFE int ida_export qdup(int h); ///< \copydoc qopen
idaman THREAD_SAFE int ida_export qfsync(int h); ///< \copydoc qopen
/// Get the file size.
/// This function may return 0 if the file is not found or if the file is too large (>4GB).
/// Call get_qerrno() and compare against eFileTooLarge to tell between the two cases.
idaman THREAD_SAFE uint32 ida_export qfilesize(const char *fname);
/// Get file length in bytes.
/// \param h file descriptor
/// \return file length in bytes, -1 if error
idaman THREAD_SAFE uint32 ida_export qfilelength(int h);
/// Change file size.
/// \param h file descriptor
/// \param fsize desired size
/// \retval 0 on success
/// \retval -1 otherwise and qerrno is set
idaman THREAD_SAFE int ida_export qchsize(int h, uint32 fsize);
/// Create an empty directory.
/// \param file name (or full path) of directory to be created
/// \param mode permissions (only used on unix systems)
/// \return 0 success
/// \return -1 otherwise and qerrno is set
idaman THREAD_SAFE int ida_export qmkdir(const char *file, int mode);
/// Does the given file exist?
idaman THREAD_SAFE bool ida_export qfileexist(const char *file);
/// Does the given path specify a directory?
idaman THREAD_SAFE bool ida_export qisdir(const char *file);
/*--------------------------------------------------*/
idaman THREAD_SAFE qoff64_t ida_export qtell64(int h); ///< Same as qtell(), but with large file (>2Gb) support
idaman THREAD_SAFE qoff64_t ida_export qseek64(int h, qoff64_t offset, int whence); ///< Same as qseek(), but with large file (>2Gb) support
idaman THREAD_SAFE uint64 ida_export qfilesize64(const char *fname); ///< Same as qfilesize(), but with large file (>2Gb) support
idaman THREAD_SAFE uint64 ida_export qfilelength64(int h); ///< Same as qfilelength(), but with large file (>2Gb) support
idaman THREAD_SAFE int ida_export qchsize64(int h, uint64 fsize); ///< Same as qchsize(), but with large file (>2Gb) support
idaman THREAD_SAFE bool ida_export qfileexist64(const char *file); ///< Same as qfileexist(), but with large file (>2Gb) support
idaman THREAD_SAFE int ida_export qstat64(const char *path, qstatbuf64 *buf); ///< Same as qstat(), but with large file (>2Gb) support
idaman THREAD_SAFE int ida_export qfstat64(int h, qstatbuf64 *buf); ///< Same as qfstat(), but with large file (>2Gb) support
//---------------------------------------------------------------------------
/// Add a function to be called at exit time
idaman THREAD_SAFE void ida_export qatexit(void (idaapi *func)(void));
/// Remove a previously added exit-time function
idaman THREAD_SAFE void ida_export del_qatexit(void (idaapi*func)(void));
#endif // SWIG
/// Call qatexit functions, shut down UI and kernel, and exit.
/// \param code exit code
idaman THREAD_SAFE NORETURN void ida_export qexit(int code);
//---------------------------------------------------------------------------
#define qmin(a,b) ((a) < (b)? (a): (b)) ///< universal min
#define qmax(a,b) ((a) > (b)? (a): (b)) ///< universal max
#if defined(__EA64__) && defined(__VC__) && defined(__cplusplus)
#if _MSC_VER < 1600
static inline int64 abs(int64 n) { return _abs64(n); }
#endif
static inline int32 abs(uint32 n) { return abs((int32)n); }
#endif
//----------------------------------------------------------------------
/// Test if 'bit' is set in 'bitmap'
inline bool idaapi test_bit(const uchar *bitmap, size_t bit)
{
return (bitmap[bit/8] & (1<<(bit&7))) != 0;
}
/// Set 'bit' in 'bitmap'
inline void idaapi set_bit(uchar *bitmap, size_t bit)
{
uchar *p = bitmap + bit/8;
*p = uchar(*p | (1<<(bit&7)));
}
/// Clear 'bit' in 'bitmap'
inline void idaapi clear_bit(uchar *bitmap, size_t bit)
{
uchar *p = bitmap + bit/8;
*p = uchar(*p & ~(1<<(bit&7)));
}
/// Set first 'nbits' of 'bitmap'
inline void idaapi set_all_bits(uchar *bitmap, size_t nbits)
{
memset(bitmap, 0xFF, (nbits+7)/8);
if ( (nbits & 7) != 0 )
{
uchar *p = bitmap + nbits/8;
*p = uchar(*p & ~((1 << (nbits&7))-1));
}
}
/// Clear first 'nbits' of 'bitmap'
inline void idaapi clear_all_bits(uchar *bitmap, size_t nbits)
{
memset(bitmap, 0, (nbits+7)/8);
}
//----------------------------------------------------------------------
/// Functions to work with intervals
namespace interval
{
/// Do (off1,s1) and (off2,s2) overlap?
inline bool overlap(uval_t off1, asize_t s1, uval_t off2, asize_t s2)
{
return off2 < off1+s1 && off1 < off2+s2;
}
/// Does (off1,s1) include (off2,s2)?
inline bool includes(uval_t off1, asize_t s1, uval_t off2, asize_t s2)
{
return off2 >= off1 && off2+s2 <= off1+s1;
}
/// Does (off1,s1) contain off?
inline bool contains(uval_t off1, asize_t s1, uval_t off)
{
return off >= off1 && off < off1+s1;
}
}
//----------------------------------------------------------------------
#ifdef __cplusplus
/// Shift by the amount exceeding the operand size*8 is undefined by the standard.
/// Indeed, GNUC may decide not to rotate the operand in some cases.
/// We have to check this manually.
template <class T> T left_shift(const T &value, int shift)
{
return shift >= sizeof(T)*8 ? 0 : (value << shift);
}
/// \copydoc left_shift
template <class T> T right_ushift(const T &value, int shift)
{
return shift >= sizeof(T)*8 ? 0 : (value >> shift);
}
/// \copydoc left_shift
template <class T> T right_sshift(const T &value, int shift)
{
return shift >= sizeof(T)*8 ? (value >= 0 ? 0 : -1) : (value >> shift);
}
/// Rotate left
template<class T> T qrotl(T value, size_t count)
{
const size_t nbits = sizeof(T) * 8;
count %= nbits;
T high = value >> (nbits - count);
value <<= count;
value |= high;
return value;
}
/// Rotate right
template<class T> T qrotr(T value, size_t count)
{
const size_t nbits = sizeof(T) * 8;
count %= nbits;
T low = value << (nbits - count);
value >>= count;
value |= low;
return value;
}
/// Make a mask of 'count' bits
template <class T> T make_mask(int count)
{
return left_shift<T>(1, count) - 1;
}
/// Set a 'bit' in 'where' if 'value' if not zero
template<class T, class U> void idaapi setflag(T &where, U bit, bool cnd)
{
if ( cnd )
where = T(where | bit);
else
where = T(where & ~T(bit));
}
/// Check that unsigned multiplication does not overflow
template<class T> bool is_mul_ok(T count, T elsize)
{
CASSERT((T)(-1) > 0); // make sure T is unsigned
if ( elsize == 0 || count == 0 )
return true;
return count <= ((T)(-1)) / elsize;
}
/// Check that unsigned addition does not overflow
template<class T> bool is_add_ok(T x, T y)
{
CASSERT((T)(-1) > 0); // make sure T is unsigned
return y <= ((T)(-1)) - x;
}
/// \def{OPERATOR_NEW, GCC does not check for an integer overflow in 'operator new[]'. We have to do it
/// ourselves. Please note that 'char' arrays can still be allocated with
/// plain 'operator new'.}
#ifdef __GNUC__
# define OPERATOR_NEW(type, count) (is_mul_ok(size_t(count), sizeof(type)) \
? new type[count] \
: (type *)qalloc_or_throw(BADMEMSIZE))
#else
# define OPERATOR_NEW(type, count) new type[count]
#endif
#endif // __cplusplus
//-------------------------------------------------------------------------
/// Sign-, or zero-extend the value 'v' to occupy 64 bits.
/// The value 'v' is considered to be of size 'nbytes'.
idaman uint64 ida_export extend_sign(uint64 v, int nbytes, bool sign_extend);
/// We can not use multi-character constants because they are not portable - use this macro instead
#define MC2(c1, c2) ushort(((c2)<<8)|c1)
#define MC3(c1, c2, c3) uint32(((((c3)<<8)|(c2))<<8)|c1) ///< \copydoc MC2
#define MC4(c1, c2, c3, c4) uint32(((((((c4)<<8)|(c3))<<8)|(c2))<<8)|c1) ///< \copydoc MC2
//---------------------------------------------------------------------------
/// Read at most 4 bytes from file.
/// \param h file handle
/// \param res value read from file
/// \param size size of value in bytes (1,2,4)
/// \param mf is MSB first?
/// \return 0 on success, nonzero otherwise
idaman THREAD_SAFE int ida_export readbytes(int h, uint32 *res, int size, bool mf);
/// Write at most 4 bytes to file.
/// \param h file handle
/// \param l value to write
/// \param size size of value in bytes (1,2,4)
/// \param mf is MSB first?
/// \return 0 on success, nonzero otherwise
idaman THREAD_SAFE int ida_export writebytes(int h, uint32 l, int size, bool mf);
/// Read a 2 byte entity from a file.
/// \param h file handle
/// \param res value read from file
/// \param mf is MSB first?
/// \return 0 on success, nonzero otherwise
idaman THREAD_SAFE int ida_export read2bytes(int h, uint16 *res, bool mf);
#define read4bytes(h, res, mf) readbytes(h, res, 4, mf) ///< see readbytes()
#define write2bytes(h, l, mf) writebytes(h, l, 2, mf) ///< see writebytes()
#define write4bytes(h, l, mf) writebytes(h, l, 4, mf) ///< see writebytes()
//---------------------------------------------------------------------------
/// \fn{uint32 swap32(uint32 x), Switch endianness of given value}
/// \fn{ushort swap16(ushort x), \copydoc swap32}
/// \def{swap32, Switch endianness of given value}
/// \def{swap16, \copydoc swap32}
#ifdef __cplusplus
# ifndef swap32
inline uint32 swap32(uint32 x)
{ return (x>>24) | (x<<24) | ((x>>8) & 0x0000FF00L) | ((x<<8) & 0x00FF0000L); }
# endif
# ifndef swap16
inline ushort swap16(ushort x)
{ return ushort((x<<8) | (x>>8)); }
# endif
#else
# ifndef swap32
# define swap32(x) uint32((x>>24) | (x<<24) | ((x>>8) & 0x0000FF00L) | ((x<<8) & 0x00FF0000L))
# endif
# ifndef swap16
# define swap16(x) ushort((x<<8) | (x>>8))
# endif
#endif
/// \def{swapea, Switch endianness of an ::ea_t value}
#ifdef __EA64__
#define swapea swap64
#else
#define swapea swap32
#endif
/// \def{qhtons, \copydoc swap32}
/// \def{qntohs, \copydoc swap32}
/// \def{qhtonl, \copydoc swap32}
/// \def{qntohl, \copydoc swap32}
#if __MF__
#define qhtonl(x) (x)
#define qntohl(x) (x)
#define qhtons(x) (x)
#define qntohs(x) (x)
#else
#define qhtons(x) swap16(x)
#define qntohs(x) swap16(x)
#define qhtonl(x) swap32(x)
#define qntohl(x) swap32(x)
#endif
/// Swap endianness of a given value in memory.
/// \param dst result of swap
/// \param src value to be swapped
/// \param size size of value: can be 1, 2, 4, 8, or 16.
/// For any other values of size this function does nothing
idaman THREAD_SAFE void ida_export swap_value(void *dst, const void *src, int size);
idaman THREAD_SAFE void ida_export reloc_value(void *value, int size, adiff_t delta, bool mf);
/// Rotate left - can be used to rotate a value to the right if the count is negative.
/// \param x value to rotate
/// \param count shift amount
/// \param bits number of bits to rotate (32 will rotate a dword)
/// \param offset number of first bit to rotate.
/// (bits=8 offset=16 will rotate the third byte of the value)
/// \return the rotated value
idaman THREAD_SAFE uval_t ida_export rotate_left(uval_t x, int count, size_t bits, size_t offset);
#ifdef __cplusplus
/// Swap 2 objects of the same type using memory copies
template <class T> inline void qswap(T &a, T &b)
{
char temp[sizeof(T)];
memcpy(&temp, &a, sizeof(T));
memcpy(&a, &b, sizeof(T));
memcpy(&b, &temp, sizeof(T));
}
#endif
/// \name Safe buffer append
/// In the following macros, 'buf' must be always less than 'end'.
/// When we run up to the end, we put a 0 there and don't increase buf anymore
//@{
/// Append a character to the buffer checking the buffer size
#define APPCHAR(buf, end, chr) \
do \
{ \
char __chr = (chr); \
QASSERT(518, (buf) < (end)); \
*(buf)++ = __chr; \
if ( (buf) >= (end) ) \
{ \
(buf) = (end)-1; \
(buf)[0] = '\0'; \
} \
} while (0)
/// Put a zero byte at buffer.
/// NB: does not increase buf pointer!
#define APPZERO(buf, end) \
do \
{ \
QASSERT(519, (buf) < (end)); \
*(buf) = '\0'; \
} while (0)
/// Append a string to the buffer checking the buffer size
#define APPEND(buf, end, name) \
do \
{ \
QASSERT(520, (buf) < (end)); \
const char *__ida_in = (name); \
while ( true ) \
{ \
if ( (buf) == (end)-1 ) \
{ \
(buf)[0] = '\0'; \
break; \
} \
if (( *(buf) = *__ida_in++) == '\0' ) \
break; \
(buf)++; \
} \
} while ( 0 )
//@}
/// qalloc() 'size' bytes, and throw a "not enough memory" error if failed
idaman THREAD_SAFE void *ida_export qalloc_or_throw(size_t size);
/// qrealloc() 'ptr' by 'size', and throw a "not enough memory" error if failed
idaman THREAD_SAFE void *ida_export qrealloc_or_throw(void *ptr, size_t size);
/// Change capacity of given qvector.
/// \param vec a pointer to a qvector
/// \param old a pointer to the qvector's array
/// \param cnt number of elements to reserve
/// \param elsize size of each element
/// \return a pointer to the newly allocated array
idaman THREAD_SAFE void *ida_export qvector_reserve(void *vec, void *old, size_t cnt, size_t elsize);
#if defined(__cplusplus)
/// \def{PLACEMENT_DELETE, bcc complains about placement delete}
/// \def{DEFINE_MEMORY_ALLOCATION_FUNCS,
/// Convenience macro to declare memory allocation functions.
/// It must be used for all classes that can be allocated/freed by the IDA kernel.}
#if defined(SWIG)
#define DEFINE_MEMORY_ALLOCATION_FUNCS()
#else
#ifndef __BORLANDC__
#define PLACEMENT_DELETE void operator delete(void *, void *) {}
#else
#define PLACEMENT_DELETE
#endif
#define DEFINE_MEMORY_ALLOCATION_FUNCS() \
void *operator new (size_t _s) { return qalloc_or_throw(_s); } \
void *operator new[](size_t _s) { return qalloc_or_throw(_s); } \
void *operator new(size_t /*size*/, void *_v) { return _v; } \
void operator delete (void *_blk) { qfree(_blk); } \
void operator delete[](void *_blk) { qfree(_blk); } \
PLACEMENT_DELETE
#endif
/// Macro to declare standard inline comparison operators
#define DECLARE_COMPARISON_OPERATORS(type) \
bool operator==(const type &r) const { return compare(r) == 0; } \
bool operator!=(const type &r) const { return compare(r) != 0; } \
bool operator< (const type &r) const { return compare(r) < 0; } \
bool operator> (const type &r) const { return compare(r) > 0; } \
bool operator<=(const type &r) const { return compare(r) <= 0; } \
bool operator>=(const type &r) const { return compare(r) >= 0; }
/// Macro to declare comparisons for our classes.
/// All comparison operators call the compare() function which returns -1/0/1
#define DECLARE_COMPARISONS(type) \
DECLARE_COMPARISON_OPERATORS(type) \
friend int compare(const type &a, const type &b) { return a.compare(b); } \
int compare(const type &r) const
// Internal declarations to detect pod-types
/// \cond
struct ida_true_type {};
struct ida_false_type {};
template <class T> struct ida_type_traits { typedef ida_false_type is_pod_type; };
template <class T> struct ida_type_traits<T*> { typedef ida_true_type is_pod_type; };
template <> struct ida_type_traits< char> { typedef ida_true_type is_pod_type; };
template <> struct ida_type_traits<uchar> { typedef ida_true_type is_pod_type; };
template <> struct ida_type_traits< int> { typedef ida_true_type is_pod_type; };
template <> struct ida_type_traits< uint> { typedef ida_true_type is_pod_type; };
template <> struct ida_type_traits<short> { typedef ida_true_type is_pod_type; };
template <> struct ida_type_traits<ushort> { typedef ida_true_type is_pod_type; };
template <> struct ida_type_traits< long> { typedef ida_true_type is_pod_type; };
template <> struct ida_type_traits<unsigned long> { typedef ida_true_type is_pod_type; };
template <> struct ida_type_traits< int64> { typedef ida_true_type is_pod_type; };
template <> struct ida_type_traits<uint64> { typedef ida_true_type is_pod_type; };
inline bool check_type_trait(ida_false_type) { return false; }
inline bool check_type_trait(ida_true_type) { return true; }
template <class T> inline bool is_pod_type(void)
{
typedef typename ida_type_traits<T>::is_pod_type is_pod_type;
return check_type_trait(is_pod_type());
}
// Can we move around objects of type T using simple memcpy/memmove?.
// This class can be specialized for any type T to improve qvector's behavior.
template <class T> struct ida_movable_type
{
typedef typename ida_type_traits<T>::is_pod_type is_movable_type;
};
#define DECLARE_TYPE_AS_MOVABLE(T) template <> struct ida_movable_type<T> { typedef ida_true_type is_movable_type; }
template <class T> inline bool may_move_bytes(void)
{
typedef typename ida_movable_type<T>::is_movable_type mmb_t;
return check_type_trait(mmb_t());
}
/// \endcond
//---------------------------------------------------------------------------
/// Reimplementation of vector class from STL.
/// Only the most essential functions are implemented. \n
/// The vector container accepts objects agnostic to their positions
/// in the memory because it will move them arbitrarily (realloc and memmove). \n
/// The reason why we have it is because it is not compiler dependent
/// (hopefully) and therefore can be used in IDA API.
template <class T> class qvector
{
T *array;
size_t n, alloc;
friend void *ida_export qvector_reserve(void *vec, void *old, size_t cnt, size_t elsize);
/// Copy contents of given qvector into this one
qvector<T> &assign(const qvector<T> &x)
{
if ( x.n > 0 )
{
array = (T*)qalloc_or_throw(x.alloc * sizeof(T));
alloc = x.alloc;
while ( n < x.n )
{
new (array+n) T(x.array[n]);
++n;
}
}
return *this;
}
/// Move data down in memory.
/// \param dst destination ptr
/// \param src source ptr
/// \param cnt number of elements to move
void shift_down(T *dst, T *src, size_t cnt)
{
if ( may_move_bytes<T>() )
{
memmove(dst, src, cnt*sizeof(T));
}
else
{
ssize_t s = cnt;
while( --s >= 0 )
{
new(dst) T(*src);
src->~T();
++src;
++dst;
}
}
}
/// Move data up in memory.
/// \param dst destination ptr
/// \param src source ptr
/// \param cnt number of elements to move
void shift_up(T *dst, T *src, size_t cnt)
{
if ( may_move_bytes<T>() )
{
memmove(dst, src, cnt*sizeof(T));
}
else
{
ssize_t s = cnt;
dst += s;
src += s;
while( --s >= 0 )
{
--src;
--dst;
new(dst) T(*src);
src->~T();
}
}
}
public:
typedef T value_type; ///< the type of objects contained in this qvector
/// Constructor
qvector(void) : array(NULL), n(0), alloc(0) {}
/// Constructor - creates a new qvector identical to 'x'
qvector(const qvector<T> &x) : array(NULL), n(0), alloc(0) { assign(x); }
/// Destructor
~qvector(void) { clear(); }
DEFINE_MEMORY_ALLOCATION_FUNCS()
/// Append a new element to the end the qvector.
void push_back(const T &x)
{
reserve(n+1);
new (array+n) T(x);
++n;
}
/// Append a new empty element to the end of the qvector.
/// \return a reference to this new element
T &push_back(void)
{
reserve(n+1);
T *ptr = array + n;
new (ptr) T;
++n;
return *ptr;
}
/// Remove the last element in the qvector
void pop_back(void)
{
if ( n > 0 )
{
#ifdef UNDER_CE // clarm.exe is buggy
--n;
if ( !is_pod_type<T>() )
array[n].~T();
#else
array[--n].~T();
#endif
}
}
size_t size(void) const { return n; } ///< Get the number of elements in the qvector
bool empty(void) const { return n == 0; } ///< Does the qvector have 0 elements?
const T &operator[](size_t _idx) const { return array[_idx]; } ///< Allows use of typical c-style array indexing for qvectors
T &operator[](size_t _idx) { return array[_idx]; } ///< Allows use of typical c-style array indexing for qvectors
const T &at(size_t _idx) const { return array[_idx]; } ///< Get element at index '_idx'
T &at(size_t _idx) { return array[_idx]; } ///< Get element at index '_idx'
const T &front(void) const { return array[0]; } ///< Get the first element in the qvector
T &front(void) { return array[0]; } ///< Get the first element in the qvector
const T &back(void) const { return array[n-1]; } ///< Get the last element in the qvector
T &back(void) { return array[n-1]; } ///< Get the last element in the qvector
/// Destroy all elements but do not free memory
void qclear(void)
{
if ( is_pod_type<T>() )
{
n = 0;
}
else
{
while ( n > 0 )
{
array[n-1].~T();
--n;
}
}
}
/// Destroy all elements and free memory
void clear(void)
{
if ( array != NULL )
{
qclear();
qfree(array);
array = NULL;
alloc = 0;
}
}
/// Allow assignment of one qvector to another using '='
qvector<T> &operator=(const qvector<T> &x)
{
size_t mn = qmin(n, x.n);
for ( size_t i=0; i < mn; i++ )
array[i] = x.array[i];
if ( n > x.n )
{
if ( is_pod_type<T>() )
{
n = x.n;
}
else
{
while ( n > x.n )
{
array[n-1].~T();
--n;
}
}
}
else
{
reserve(x.n);
while ( n < x.n )
{
new(array+n) T(x.array[n]);
++n;
}
}
return *this;
}
/// Resize to the given size.
/// If the given size (_newsize) is less than the current size (n) of the qvector, then the last n - _newsize elements are simply deleted. \n
/// If the given size is greater than the current size, the qvector is grown to _newsize, and the last _newsize - n elements will be filled with copies of 'x'. \n
/// If the given size is equal to the current size, this function does nothing.
void resize(size_t _newsize, const T &x)
{
if ( _newsize < n )
{
if ( !is_pod_type<T>() )
for ( ssize_t i=ssize_t(n); --i >= ssize_t(_newsize); )
array[i].~T();
n = _newsize;
}
else
{
reserve(_newsize);
while ( n < _newsize )
{
new(array+n) T(x);
++n;
}
}
}
/// Same as resize(size_t, const T &), but extra space is filled with empty elements
void resize(size_t _newsize)
{
if ( is_pod_type<T>() )
{
if ( n < _newsize )
{
reserve(_newsize);
memset(array+n, 0, (_newsize-n)*sizeof(T));
}
n = _newsize;
}
else
{
resize(_newsize, T());
}
}
/// Add an element to the end of the qvector, which will be a new T() if x is not given
void grow(const T &x=T())
{
reserve(n+1);
new(array+n) T(x);
++n;
}
/// Get the number of elements that this qvector can contain - not the same
/// as the number of elements currently in the qvector (size())
size_t capacity(void) const { return alloc; }
/// Increase the capacity of the qvector. If cnt is not greater than the current capacity
/// this function does nothing.
void reserve(size_t cnt)
{
if ( cnt > alloc )
{
if ( may_move_bytes<T>() )
{
array = (T *)qvector_reserve(this, array, cnt, sizeof(T));
}
else
{
size_t old_alloc = alloc;
T *new_array = (T *)qvector_reserve(this, NULL, cnt, sizeof(T));
size_t new_alloc = alloc;
alloc = old_alloc;
shift_down(new_array, array, n);
qfree(array);
array = new_array;
alloc = new_alloc;
}
}
}
/// Shrink the capacity down to the current number of elements
void truncate(void)
{
if ( alloc > n )
{
array = (T*)qrealloc(array, n*sizeof(T)); // should not fail
alloc = n;
}
}
/// Replace all attributes of this qvector with that of 'r', and vice versa.
/// Effectively sets this = r and r = this without copying/allocating any memory.
void swap(qvector<T> &r)
{
T *array2 = array;
size_t n2 = n;
size_t alloc2 = alloc;
array = r.array;
n = r.n;
alloc = r.alloc;
r.array = array2;
r.n = n2;
r.alloc = alloc2;
}
/// Empty the qvector and return a pointer to it's contents.
/// The caller must free the result of this function
T *extract(void)
{
truncate();
alloc = 0;
n = 0;
T *res = array;
array = NULL;
return res;
}
/// Populate the qvector with dynamic memory.
/// The qvector must be empty before calling this method!
void inject(T *s, size_t len)
{
array = s;
alloc = len;
n = len;
}
/// Allow ability to test the equality of two qvectors using '=='.
bool operator == (const qvector<T> &r) const
{
if ( n != r.n )
return false;
for ( size_t i=0; i < n; i++ )
if ( array[i] != r[i] )
return false;
return true;
}
/// Allow ability to test equality of two qvectors using '!='
bool operator != (const qvector<T> &r) const { return !(*this == r); }
typedef T *iterator;
typedef const T *const_iterator;
iterator begin(void) { return array; } ///< Get an iterator that points to the first element in the qvector
iterator end(void) { return array + n; } ///< Get an iterator that points to the end of the qvector (NOT the last element)
const_iterator begin(void) const { return array; } ///< Get a const iterator that points to the first element in the qvector
const_iterator end(void) const { return array + n; } ///< Get a const iterator that points to the end of the qvector (NOT the last element)
/// Insert an element into the qvector at a specified position.
/// \param it an iterator that points to the desired position of the new element
/// \param x the element to insert
/// \return an iterator that points to the newly inserted element
iterator insert(iterator it, const T &x)
{
size_t idx = it - array;
reserve(n+1);
T *p = array + idx;
size_t rest = end() - p;
shift_up(p+1, p, rest);
new(p) T(x);
n++;
return iterator(p);
}
/// Insert a several elements to the qvector at a specified position.
/// \param it position at which new elements will be inserted
/// \param first pointer to first element to be inserted
/// \param last pointer to end of elements to be inserted (the element pointed to by 'last' will not be included)
/// \return an iterator that points to the first newly inserted element.
template <class it2> iterator insert(iterator it, it2 first, it2 last)
{
size_t cnt = last - first;
if ( cnt == 0 )
return it;
size_t idx = it - array;
reserve(n+cnt);
T *p = array + idx;
size_t rest = end() - p;
shift_up(p+cnt, p, rest);
while ( first != last )
{
new(p) T(*first);
++p;
++first;
}
n += cnt;
return iterator(array+idx);
}
/// Remove an element from the qvector.
/// \param it pointer to element to be removed
/// \return pointer to the element that took its place
iterator erase(iterator it)
{
it->~T();
size_t rest = end() - it - 1;
shift_down(it, it+1, rest);
n--;
return it;
}
/// Remove a subset of the qvector.
/// \param first pointer to head of subset to be removed
/// \param last pointer to end of subset to be removed (element pointed to by last will not be removed)
/// \return a pointer to the element that took the place of 'first'
iterator erase(iterator first, iterator last)
{
for ( T *p=first; p != last; ++p )
p->~T();
size_t rest = end() - last;
shift_down(first, last, rest);
n -= last - first;
return first;
}
// non-standard extensions:
/// Find an element in the qvector.
/// \param x element to find
/// \return an iterator that points to the first occurrence of 'x'
iterator find(const T &x)
{
iterator p;
const_iterator e;
for ( p=begin(), e=end(); p != e; ++p )
if ( x == *p )
break;
return p;
}
/// \copydoc find
const_iterator find(const T &x) const
{
const_iterator p, e;
for ( p=begin(), e=end(); p != e; ++p )
if ( x == *p )
break;
return p;
}
/// Does the qvector contain x?
bool has(const T &x) const { return find(x) != end(); }
/// Add an element to the end of the qvector - only if it isn't already present.
/// \param x the element to add
/// \return false if 'x' is already in the qvector, true otherwise
bool add_unique(const T &x)
{
if ( has(x) )
return false;
push_back(x);
return true;
}
/// Find an element and remove it.
/// \param x the element to remove
/// \return false if 'x' was not found, true otherwise
bool del(const T &x)
{
iterator p = find(x);
if ( p == end() )
return false;
erase(p);
return true;
}
};
/// Reimplementation of stack class from STL.
/// The reason why we have it is because it is not compiler dependent
/// (hopefully) and therefore can be used in IDA API
template<class T>
class qstack : public qvector<T>
{
typedef qvector<T> inherited;
public:
T pop(void)
{
T v = inherited::back();
inherited::pop_back();
return v;
}
const T &top(void) const
{
return inherited::back();
}
T &top(void) { return CONST_CAST(T&)(CONST_CAST(const qstack<T>*)(this)->top()); }
void push(const T &v)
{
inherited::push_back(v);
}
};
/// Standard lexical comparison.
/// \return -1 if a < b, 1 if a > b, and 0 if a == b
template <class T> int lexcompare(const T &a, const T &b)
{
if ( a < b )
return -1;
if ( a > b )
return 1;
return 0;
}
/// Lexical comparison of two vectors. Also see lexcompare().
/// \return 0 if the two vectors are identical
/// 1 if 'a' is larger than 'b'
/// -1 if 'a' is smaller than 'b'
/// otherwise return the first nonzero lexical comparison between each element in 'a' and 'b'
template <class T> int lexcompare_vectors(const T &a, const T &b)
{
if ( a.size() != b.size() )
return a.size() > b.size() ? 1 : -1;
for ( int i=0; i < a.size(); i++ )
{
int code = lexcompare(a[i], b[i]);
if ( code != 0 )
return code;
}
return 0;
}
/// Smart pointer to objects derived from ::qrefcnt_obj_t
template <class T>
class qrefcnt_t
{
T *ptr;
void delref(void)
{
if ( ptr != NULL && --ptr->refcnt == 0 )
ptr->release();
}
public:
explicit qrefcnt_t(T *p) : ptr(p) {}
qrefcnt_t(const qrefcnt_t &r) : ptr(r.ptr)
{
if ( ptr != NULL )
ptr->refcnt++;
}
qrefcnt_t &operator=(const qrefcnt_t &r)
{
delref();
ptr = r.ptr;
if ( ptr != NULL )
ptr->refcnt++;
return *this;
}
~qrefcnt_t(void)
{
delref();
}
void reset(void)
{
delref();
ptr = NULL;
}
operator T *() const
{
return ptr;
}
T *operator ->() const
{
return ptr;
}
T &operator *() const
{
return *ptr;
}
};
/// Base class for reference count objects
class qrefcnt_obj_t
{
public:
int refcnt; ///< counter
/// Constructor
qrefcnt_obj_t(void) : refcnt(1) {}
/// Call destructor.
/// We use release() instead of operator delete() to maintain binary
/// compatibility with all compilers (vc and gcc use different vtable layouts
/// for operator delete)
virtual void idaapi release(void) = 0;
};
/// Interface class for iterator types.
template <class T>
class qiterator : public qrefcnt_obj_t
{
public:
typedef T value_type;
virtual bool idaapi first(void) = 0;
virtual bool idaapi next(void) = 0;
virtual T idaapi operator *(void) = 0;
virtual T get(void) { return this->operator*(); }
};
/// \name strlen
/// Get the length of the given string
//@{
inline size_t idaapi qstrlen(const char *s) { return strlen(s); }
inline size_t idaapi qstrlen(const uchar *s) { return strlen((const char *)s); }
idaman THREAD_SAFE size_t ida_export qstrlen(const wchar16_t *s);
//@}
/// \name strcmp
/// Lexical comparison of strings.
/// \return 0 if two strings are identical
/// > 0 if 's1' is larger than 's2'
/// < 0 if 's2' is larger than 's1'
/// otherwise return first nonzero comparison between chars in 's1' and 's2'
//@{
inline int idaapi qstrcmp(const char *s1, const char *s2) { return strcmp(s1, s2); }
inline int idaapi qstrcmp(const uchar *s1, const uchar *s2) { return strcmp((const char *)s1, (const char *)s2); }
idaman THREAD_SAFE int ida_export qstrcmp(const wchar16_t *s1, const wchar16_t *s2);
//@}
/// \name strstr
/// Find a string within another string.
/// \return a pointer to the first occurrence of 's2' within 's1', NULL if s2 is not found in s1
//@{
inline const char *idaapi qstrstr(const char *s1, const char *s2) { return strstr(s1, s2); }
inline const uchar *idaapi qstrstr(const uchar *s1, const uchar *s2) { return (const uchar *)strstr((const char *)s1, (const char *)s2); }
//@}
/// \name strchr
/// Find a character within a string.
/// \return a pointer to the first occurrence of 'c' within 's1', NULL if c is not found in s1
//@{
inline char *idaapi qstrchr( char *s1, char c) { return strchr(s1, c); }
inline const char *idaapi qstrchr(const char *s1, char c) { return strchr(s1, c); }
inline uchar *idaapi qstrchr( uchar *s1, uchar c) { return ( uchar *)strchr(( char *)s1, c); }
inline const uchar *idaapi qstrchr(const uchar *s1, uchar c) { return (const uchar *)strchr((const char *)s1, c); }
idaman THREAD_SAFE const wchar16_t *ida_export qstrchr(const wchar16_t *s1, wchar16_t c);
inline THREAD_SAFE wchar16_t *ida_export qstrchr( wchar16_t *s1, wchar16_t c)
{ return (wchar16_t *)qstrchr((const wchar16_t *)s1, c); }
//@}
/// \name qstrrchr
/// Find a last occurrence of a character within a string.
/// \return a pointer to the last occurrence of 'c' within 's1', NULL if c is not found in s1
//@{
inline const char *idaapi qstrrchr(const char *s1, char c) { return strrchr(s1, c); }
inline char *idaapi qstrrchr( char *s1, char c) { return strrchr(s1, c); }
inline const uchar *idaapi qstrrchr(const uchar *s1, uchar c) { return (const uchar *)strrchr((const char *)s1, c); }
inline uchar *idaapi qstrrchr( uchar *s1, uchar c) { return ( uchar *)strrchr((const char *)s1, c); }
idaman THREAD_SAFE const wchar16_t *ida_export qstrrchr(const wchar16_t *s1, wchar16_t c);
inline THREAD_SAFE wchar16_t *ida_export qstrrchr( wchar16_t *s1, wchar16_t c)
{ return (wchar16_t *)qstrrchr((const wchar16_t *)s1, c); }
//@}
/// Reimplementation of the string class from STL.
/// Only the most essential functions are implemented.
/// The reason why we have this is because it is not compiler dependent
/// (hopefully) and therefore can be used in IDA API
template<class qchar>
class _qstring
{
qvector<qchar> body;
public:
/// Constructor
_qstring(void) {}
/// Constructor - creates a new qstring from an existing char *
_qstring(const qchar *ptr)
{
if ( ptr != NULL )
{
size_t len = ::qstrlen(ptr) + 1;
body.resize(len);
memcpy(body.begin(), ptr, len*sizeof(qchar));
}
}
/// Constructor - creates a new qstring using first 'len' chars from 'ptr'
_qstring(const qchar *ptr, size_t len)
{
if ( len > 0 )
{
body.resize(len+1);
memcpy(body.begin(), ptr, len*sizeof(qchar));
}
}
void swap(_qstring<qchar> &r) { body.swap(r.body); } ///< Swap contents of two qstrings. see qvector::swap()
size_t length(void) const { size_t l = body.size(); return l ? l - 1 : 0; } ///< Get number of chars in this qstring (not including terminating zero)
size_t size(void) const { return body.size(); } ///< Get number of chars in this qstring (including terminating zero)
/// Resize to the given size.
/// The resulting qstring will have length() = s, and size() = s+1 \n
/// if 's' is greater than the current size then the extra space is filled with 'c'. \n
/// if 's' is less than the current size then the trailing chars are removed
void resize(size_t s, qchar c)
{
size_t oldsize = body.size();
if ( oldsize != 0 && s >= oldsize )
body[oldsize-1] = c; // erase the terminating zero
body.resize(s+1, c);
body[s] = 0; // ensure the terminating zero
}
/// Similar to resize(size_t, qchar) - but any extra space is filled with zeroes
void resize(size_t s)
{
if ( s == 0 )
{
body.clear();
}
else
{
body.resize(s+1);
body[s] = 0; // ensure the terminating zero
}
}
void remove_last(int cnt=1)
{
ssize_t len = body.size() - cnt;
if ( len <= 1 )
{
body.clear();
}
else
{
body.resize(len);
body[len-1] = 0;
}
}
void reserve(size_t cnt) { body.reserve(cnt); } ///< Increase capacity the qstring. see qvector::reserve()
void clear(void) { body.clear(); } ///< Clear qstring and free memory
void qclear(void) { body.qclear(); } ///< Clear qstring but do not free memory yet
bool empty(void) const { return body.size() <= 1; } ///< Does the qstring have 0 non-null elements?
/// Convert the qstring to a char *
const qchar *c_str(void) const
{
static const qchar nullstr[] = { 0 };
return body.empty() ? nullstr : &body[0];
}
typedef qchar *iterator;
typedef const qchar *const_iterator;
iterator begin(void) { return body.begin(); } ///< Get a pointer to the beginning of the qstring
const_iterator begin(void) const { return body.begin(); } ///< Get a const pointer to the beginning of the qstring
iterator end(void) { return body.end(); } ///< Get a pointer to the end of the qstring (this is not the terminating zero)
const_iterator end(void) const { return body.end(); } ///< Get a const pointer to the end of the qstring (this is not the terminating zero)
/// Allow assignment of qstrings using '='
_qstring &operator=(const qchar *str)
{
size_t len = str == NULL ? 0 : ::qstrlen(str);
if ( len > 0 )
{
body.resize(len+1);
memcpy(body.begin(), str, len*sizeof(qchar));
body[len] = '\0';
}
else
{
qclear();
}
return *this;
}
/// Append a char using '+='
_qstring &operator+=(qchar c)
{
return append(c);
}
/// Append another qstring using '+='
_qstring &operator+=(const _qstring &r)
{
return append(r);
}
/// Get result of appending two qstrings using '+'
_qstring operator+(const _qstring &r) const
{
_qstring s = *this;
s += r;
return s;
}
/// Test equality of two qstrings using '=='
bool operator==(const _qstring &r) const
{
return ::qstrcmp(c_str(), r.c_str()) == 0;
}
/// Test equality of a qstring and a const char* using '=='
bool operator==(const qchar *r) const
{
return ::qstrcmp(c_str(), r) == 0;
}
bool operator!=(const _qstring &r) const { return !(*this == r); } ///< Test equality of two qstrings using '!='
bool operator!=(const qchar *r) const { return !(*this == r); } ///< Test equality of a qstring and a const char* with '!='
/// Compare two qstrings using '<'. see qstrcmp()
bool operator<(const _qstring &r) const
{
return ::qstrcmp(c_str(), r.c_str()) < 0;
}
/// Compare two qstrings using '<'. see qstrcmp()
bool operator<(const qchar *r) const
{
return ::qstrcmp(c_str(), r) < 0;
}
/// Retrieve char at index 'idx' using '[]'
const qchar &operator[](size_t idx) const
{
if ( !body.empty() || idx )
return body[idx];
static const qchar nullstr[] = { 0 };
return nullstr[0];
}
/// Retrieve char at index 'idx' using '[]'
qchar &operator[](size_t idx)
{
if ( !body.empty() || idx )
return body[idx];
static qchar nullstr[] = { 0 };
return nullstr[0];
}
const qchar &at(size_t idx) const { return body.at(idx); } ///< Retrieve const char at index 'idx'
qchar &at(size_t idx) { return body.at(idx); } ///< Retrieve char at index 'idx'
/// Extract C string from _qstring. Must qfree() it.
qchar *extract(void) { return body.extract(); }
/// Assign this qstring to an existing char *.
/// See qvector::inject(T *, size_t)
void inject(qchar *s, size_t len)
{
body.inject(s, len);
}
/// Same as to inject(qchar *, size_t), with len = strlen(s)
void inject(qchar *s)
{
if ( s != NULL )
{
size_t len = ::qstrlen(s) + 1;
body.inject(s, len);
}
}
/// Get the last qchar in the string (for concatenation checks)
qchar last(void) const
{
size_t len = length();
return len == 0 ? '\0' : body[len-1];
}
/// Find a substring.
/// \param str the substring to look for
/// \param pos starting position
/// \return the position of the beginning of the first occurrence of str, -1 of none exists
size_t find(const qchar *str, size_t pos=0) const
{
if ( pos <= length() )
{
const qchar *beg = c_str();
const qchar *ptr = ::qstrstr(beg+pos, str);
if ( ptr != NULL )
return ptr - beg;
}
return npos;
}
/// Replace all occurrences of 'what' with 'with'.
/// \return false if 'what' is not found in the qstring, true otherwise
bool replace(const qchar *what, const qchar *with)
{
_qstring result;
size_t len_what = ::qstrlen(what);
const qchar *_start = c_str();
const qchar *last_pos = _start;
while ( true )
{
const qchar *pos = ::qstrstr(last_pos, what);
if ( pos == NULL )
break;
size_t n = pos - last_pos;
if ( n > 0 )
result.append(last_pos, n);
result.append(with);
last_pos = pos + len_what;
}
// no match at all?
if ( last_pos == _start )
return false;
// any pending characters?
if ( *last_pos )
result.append(last_pos);
swap(result);
return true;
}
/// Same as find(const qchar *, size_t), but takes a qstring parameter
size_t find(const _qstring &str, size_t pos=0) const { return find(str.c_str(), pos); }
/// Find a character in the qstring.
/// \param c the character to look for
/// \param pos starting position
/// \return index of first occurrence of 'c' if c is found, -1 otherwise
size_t find(qchar c, size_t pos=0) const
{
if ( pos <= length() )
{
const qchar *beg = c_str();
const qchar *ptr = qstrchr(beg+pos, c);
if ( ptr != NULL )
return ptr - beg;
}
return npos;
}
/// Search backwards for a character in the qstring.
/// \param c the char to look for
/// \param pos starting position
/// \return index of first occurrence of 'c' if c is found, -1 otherwise
size_t rfind(qchar c, size_t pos=0) const
{
if ( pos <= length() )
{
const qchar *beg = c_str();
const qchar *ptr = qstrrchr(beg+pos, c);
if ( ptr != NULL )
return ptr - beg;
}
return npos;
}
/// Get a substring.
/// \param pos starting position
/// \param n ending position (non-inclusive)
/// \return the resulting substring
_qstring<qchar> substr(size_t pos=0, size_t n=npos) const
{
size_t endp = qmin(length(), n);
if ( pos >= endp )
pos = endp;
return _qstring<qchar>(c_str()+pos, endp-pos);
}
/// Remove characters from the qstring.
/// \param idx starting position
/// \param cnt number of characters to remove
_qstring& remove(size_t idx, size_t cnt)
{
size_t len = length();
if ( idx < len && cnt != 0 )
{
cnt += idx;
if ( cnt < len )
{
iterator p1 = body.begin() + cnt;
iterator p2 = body.begin() + idx;
memmove(p2, p1, (len-cnt)*sizeof(qchar));
idx += len - cnt;
}
body.resize(idx+1);
body[idx] = '\0';
}
return *this;
}
/// Insert a character into the qstring.
/// \param idx position of insertion (if idx >= length(), the effect is the same as append)
/// \param c char to insert
_qstring& insert(size_t idx, qchar c)
{
size_t len = length();
body.resize(len+2);
body[len+1] = '\0';
if ( idx < len )
{
iterator p1 = body.begin() + idx;
memmove(p1+1, p1, (len-idx)*sizeof(qchar));
len = idx;
}
body[len] = c;
return *this;
}
/// Insert a string into the qstring.
/// \param idx position of insertion (if idx >= length(), the effect is the same as append)
/// \param str the string to insert
/// \param addlen number of chars from 'str' to insert
_qstring& insert(size_t idx, const qchar *str, size_t addlen)
{
size_t len = length();
body.resize(len+addlen+1);
body[len+addlen] = '\0';
if ( idx < len )
{
iterator p1 = body.begin() + idx;
iterator p2 = p1 + addlen;
memmove(p2, p1, (len-idx)*sizeof(qchar));
len = idx;
}
memcpy(body.begin()+len, str, addlen*sizeof(qchar));
return *this;
}
/// Same as insert(size_t, const qchar *, size_t), but all chars in str are inserted
_qstring& insert(size_t idx, const qchar *str)
{
if ( str != NULL )
{
size_t addlen = ::qstrlen(str);
insert(idx, str, addlen);
}
return *this;
}
/// Same as insert(size_t, const qchar *), but takes a qstring parameter
_qstring& insert(size_t idx, const _qstring &qstr)
{
size_t len = length();
size_t add = qstr.length();
body.resize(len+add+1);
body[len+add] = '\0';
if ( idx < len )
{
iterator p1 = body.begin() + idx;
iterator p2 = p1 + add;
memmove(p2, p1, (len-idx)*sizeof(qchar));
len = idx;
}
memcpy(body.begin()+len, qstr.begin(), add*sizeof(qchar));
return *this;
}
_qstring& insert(qchar c) { return insert(0, c); } ///< Prepend the qstring with 'c'
_qstring& insert(const qchar *str) { return insert(0, str); } ///< Prepend the qstring with 'str'
_qstring& insert(const _qstring &qstr) { return insert(0, qstr); } ///< Prepend the qstring with 'qstr'
/// Append c to the end of the qstring
_qstring& append(qchar c)
{
size_t len = length();
body.resize(len+2);
body[len] = c;
body[len+1] = '\0';
return *this;
}
/// Append a string to the qstring.
/// \param str the string to append
/// \param addlen number of characters from 'str' to append
_qstring& append(const qchar *str, size_t addlen)
{
size_t len = length();
body.resize(len+addlen+1);
body[len+addlen] = '\0';
memcpy(body.begin()+len, str, addlen*sizeof(qchar));
return *this;
}
/// Same as append(const qchar *, size_t), but all chars in 'str' are appended
_qstring& append(const qchar *str)
{
if ( str != NULL )
{
size_t addlen = ::qstrlen(str);
append(str, addlen);
}
return *this;
}
/// Same as append(const qchar *), but takes a qstring argument
_qstring& append(const _qstring &qstr)
{
size_t add = qstr.length();
if ( add != 0 )
{
size_t len = length();
body.resize(len+add+1);
body[len+add] = '\0';
memcpy(body.begin()+len, qstr.begin(), add*sizeof(qchar));
}
return *this;
}
/// Append result of qvsnprintf() to qstring
AS_PRINTF(2, 0) _qstring& cat_vsprnt(const char *format, va_list va)
{ // since gcc64 forbids reuse of va_list, we make a copy for the second call:
va_list copy;
va_copy(copy, va);
size_t add = ::qvsnprintf(NULL, 0, format, va);
if ( add != 0 )
{
size_t len = length();
body.resize(len+add+1);
::qvsnprintf(body.begin()+len, add+1, format, copy);
}
return *this;
}
/// Replace qstring with the result of qvsnprintf()
AS_PRINTF(2, 0) _qstring& vsprnt(const char *format, va_list va)
{ // since gcc64 forbids reuse of va_list, we make a copy for the second call:
va_list copy;
va_copy(copy, va);
body.clear();
size_t add = ::qvsnprintf(NULL, 0, format, va);
if ( add != 0 )
{
body.resize(add+1);
::qvsnprintf(body.begin(), add+1, format, copy);
}
return *this;
}
/// Append result of qsnprintf() to qstring
AS_PRINTF(2, 3) _qstring& cat_sprnt(const char *format, ...)
{
va_list va;
va_start(va, format);
cat_vsprnt(format, va);
va_end(va);
return *this;
}
/// Replace qstring with the result of qsnprintf()
AS_PRINTF(2, 3) _qstring& sprnt(const char *format, ...)
{
va_list va;
va_start(va, format);
vsprnt(format, va);
va_end(va);
return *this;
}
/// Fill qstring with a character.
/// The qstring is resized if necessary until 'len' chars have been filled
/// \param pos starting position
/// \param c the character to fill
/// \param len number of positions to fill with 'c'
_qstring& fill(size_t pos, qchar c, size_t len)
{
size_t endp = pos + len + 1;
if ( body.size() < endp )
{
body.resize(endp);
body[endp-1] = '\0';
}
memset(body.begin()+pos, c, len);
return *this;
}
/// Clear contents of qstring and fill with 'c'
_qstring& fill(qchar c, size_t len)
{
body.qclear();
if ( len > 0 )
resize(len, c);
return *this;
}
/// Remove all instances of the specified char from the beginning of the qstring
_qstring& ltrim(qchar blank = ' ')
{
if ( !empty() )
{
iterator b = body.begin();
iterator e = body.end()-1;
while ( b < e && *b == blank )
b++;
if ( b > body.begin() )
{
memmove(body.begin(), b, sizeof(qchar)*(e-b+1));
resize(e-b);
}
}
return *this;
}
/// Remove all instances of the specified char from the end of the qstring
_qstring& rtrim(qchar blank = ' ')
{
if ( !empty() )
{
iterator b = body.begin();
iterator e = body.end()-1;
while ( e > b && *(e-1) == blank )
e--;
resize(e-b);
}
return *this;
}
/// Remove all instances of the specified char from both ends of the qstring
_qstring& trim2(qchar blank = ' ')
{
rtrim(blank);
ltrim(blank);
return *this;
}
// embedded visual studio and visual C/C++ 6.0 are not aware of
// static const varname = init_value;
/// Invalid position
#if defined(UNDER_CE) || defined(_MSC_VER) && _MSC_VER <= 1200
enum { npos = -1 };
#else
static const size_t npos = (size_t) -1;
#endif
};
typedef _qstring<char> qstring; ///< regular string
typedef _qstring<uchar> qtype; ///< type string
typedef _qstring<wchar16_t> qwstring; ///< unicode string
/// Vector of bytes (use for dynamic memory)
class bytevec_t: public qvector<uchar>
{
public:
/// Constructor
bytevec_t() {}
/// Constructor - fill bytevec with 'sz' bytes from 'buf'
bytevec_t(const void *buf, size_t sz) { append(buf, sz); }
/// Append bytes to the bytevec
/// \param buf pointer to buffer that will be appended
/// \param sz size of buffer
bytevec_t &append(const void *buf, size_t sz)
{
if ( sz > 0 )
{
size_t cur_sz = size();
size_t new_sz = cur_sz + sz;
if ( new_sz < cur_sz )
new_sz = BADMEMSIZE; // integer overflow, ask too much and it will throw
resize(new_sz);
memcpy(begin() + cur_sz, buf, sz);
}
return *this;
}
/// Grow the bytevec and fill with a value
/// \param sz number of bytes to add to bytevec
/// \param filler filler value
bytevec_t &growfill(size_t sz, uchar filler=0)
{
if ( sz > 0 )
{
size_t cur_sz = size();
size_t new_sz = cur_sz + sz;
if ( new_sz < cur_sz )
new_sz = BADMEMSIZE; // integer overflow, ask too much and it will throw
resize(new_sz, filler);
}
return *this;
}
/// See qvector::inject(T *, size_t)
void inject(void *buf, size_t len)
{
qvector<uchar>::inject((uchar *)buf, len);
}
/// Is the specified bit set in the bytevec?
bool test_bit(size_t bit) const { return ::test_bit(begin(), bit); }
/// Set the specified bit
void set_bit(size_t bit) { ::set_bit(begin(), bit); }
/// Clear the specified bit
void clear_bit(size_t bit) { ::clear_bit(begin(), bit); }
/// See set_all_bits(uchar *, size_t)
void set_all_bits(size_t nbits) { resize((nbits+7)/8); ::set_all_bits(begin(), nbits); }
/// See clear_all_bits(uchar *, size_t)
void clear_all_bits(size_t nbits) { ::clear_all_bits(begin(), nbits); }
/// For each bit that is set in 'b', set the corresponding bit in this bytevec
void set_bits(const bytevec_t &b)
{
size_t nbytes = b.size();
if ( size() < nbytes )
resize(nbytes);
for ( size_t i=0; i < nbytes; i++ )
at(i) |= b[i];
}
/// For each bit that is set in 'b', the clear the corresponding bit in this bytevec
void clear_bits(const bytevec_t &b)
{
size_t nbytes = qmin(size(), b.size());
iterator p = begin();
for ( size_t i=0; i < nbytes; i++, ++p )
*p = uchar(*p & ~b[i]);
}
};
/// Relocation information (relocatable objects - see ::relobj_t)
struct reloc_info_t : public bytevec_t
{
/// \defgroup RELOBJ_ Relocatable object info flags
/// used by relobj_t::ri
//@{
#define RELOBJ_MASK 0xF ///< the first byte describes the relocation entry types
#define RELSIZE_1 0 ///< 8-bit relocations
#define RELSIZE_2 1 ///< 16-bit relocations
#define RELSIZE_4 2 ///< 32-bit relocations
#define RELSIZE_8 3 ///< 64-bit relocations
#define RELSIZE_CUST 15 ///< custom relocations, should be handled internally
#define RELOBJ_CNT 0x80 ///< counter present (not used yet)
//@}
};
idaman THREAD_SAFE bool ida_export relocate_relobj(struct relobj_t *_relobj, ea_t ea, bool mf);
/// Relocatable object
struct relobj_t : public bytevec_t
{
ea_t base; ///< current base
reloc_info_t ri; ///< relocation info
relobj_t(void) : base(0) {}
bool relocate(ea_t ea, bool mf) { return relocate_relobj(this, ea, mf); } ///< mf=1:big endian
};
#define QLIST_DEFINED ///< signal that the qlist class has been defined
/// Linked list
template <class T> class qlist
{
struct listnode_t
{
listnode_t *next;
listnode_t *prev;
};
struct datanode_t : public listnode_t
{
T data;
};
listnode_t node;
size_t length;
void init(void)
{
node.next = &node;
node.prev = &node;
length = 0;
}
public:
typedef T value_type;
class const_iterator;
/// Used for defining the 'iterator' and 'const_iterator' classes for qlist
#define DEFINE_LIST_ITERATOR(iter, constness, cstr) \
class iter \
{ \
friend class qlist<T>; \
constness listnode_t *cur; \
iter(constness listnode_t *x) : cur(x) {} \
public: \
typedef constness T value_type; \
iter(void) {} \
iter(const iter &x) : cur(x.cur) {} \
cstr \
iter &operator=(const iter &x) { cur = x.cur; return *this; } \
bool operator==(const iter &x) const { return cur == x.cur; } \
bool operator!=(const iter &x) const { return cur != x.cur; } \
constness T &operator*(void) const { return ((datanode_t*)cur)->data; } \
constness T *operator->(void) const { return &(operator*()); } \
iter& operator++(void) /* prefix ++ */ \
{ \
cur = cur->next; \
return *this; \
} \
iter operator++(int) /* postfix ++ */ \
{ \
iter tmp = *this; \
++(*this); \
return tmp; \
} \
iter& operator--(void) /* prefix -- */ \
{ \
cur = cur->prev; \
return *this; \
} \
iter operator--(int) /* postfix -- */ \
{ \
iter tmp = *this; \
--(*this); \
return tmp; \
} \
};
DEFINE_LIST_ITERATOR(iterator, , friend class const_iterator;)
DEFINE_LIST_ITERATOR(const_iterator, const, const_iterator(const iterator &x) : cur(x.cur) {})
/// Used to define qlist::reverse_iterator and qlist::const_reverse_iterator
#define DEFINE_REVERSE_ITERATOR(riter, iter) \
class riter \
{ \
iter p; \
public: \
riter(void) {} \
riter(const iter &x) : p(x) {} \
typename iter::value_type &operator*(void) const { iter q=p; return *--q; } \
typename iter::value_type *operator->(void) const { return &(operator*()); } \
riter &operator++(void) { --p; return *this; } \
riter operator++(int) { iter q=p; --p; return q; } \
riter &operator--(void) { ++p; return *this; } \
riter operator--(int) { iter q=p; ++p; return q; } \
bool operator==(const riter& x) const { return p == x.p; } \
bool operator!=(const riter& x) const { return p != x.p; } \
};
DEFINE_REVERSE_ITERATOR(reverse_iterator, iterator)
DEFINE_REVERSE_ITERATOR(const_reverse_iterator, const_iterator)
#undef DEFINE_LIST_ITERATOR
#undef DEFINE_REVERSE_ITERATOR
/// Constructor
qlist(void) { init(); }
/// Constructor - creates a qlist identical to 'x'
qlist(const qlist<T> &x)
{
init();
insert(begin(), x.begin(), x.end());
}
/// Destructor
~qlist(void)
{
clear();
}
DEFINE_MEMORY_ALLOCATION_FUNCS()
/// Construct a new qlist using '='
qlist<T> &operator=(const qlist<T> &x)
{
if ( this != &x )
{
iterator first1 = begin();
iterator last1 = end();
const_iterator first2 = x.begin();
const_iterator last2 = x.end();
while ( first1 != last1 && first2 != last2 )
*first1++ = *first2++;
if ( first2 == last2 )
erase(first1, last1);
else
insert(last1, first2, last2);
}
return *this;
}
/// Set this = x and x = this, without copying any memory
void swap(qlist<T> &x)
{
std::swap(node, x.node);
std::swap(length, x.length);
}
iterator begin(void) { return node.next; } ///< Get a pointer to the head of the list
iterator end(void) { return &node; } ///< Get a pointer to the end of the list
bool empty(void) const { return length == 0; } ///< Get true if the list has 0 elements
size_t size(void) const { return length; } ///< Get the number of elements in the list
T &front(void) { return *begin(); } ///< Get the first element in the list
T &back(void) { return *(--end()); } ///< Get the last element in the list
const_iterator begin(void) const { return node.next; } ///< \copydoc begin
const_iterator end(void) const { return &node; } ///< \copydoc end
const T&front(void) const { return *begin(); } ///< \copydoc front
const T&back(void) const { return *(--end()); } ///< \copydoc end
reverse_iterator rbegin() { return reverse_iterator(end()); } ///< Get a reverse iterator that points to end of list. See DEFINE_REVERSE_ITERATOR
reverse_iterator rend() { return reverse_iterator(begin()); } ///< Get a reverse iterator that points to beginning of list. See DEFINE_REVERSE_ITERATOR
const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } ///< See rbegin()
const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } ///< See rend()
/// Insert an element into the qlist.
/// \param p the position to insert the element
/// \param x the element to be inserted
/// \return position of newly inserted element
iterator insert(iterator p, const T& x)
{
datanode_t *tmp = (datanode_t*)qalloc_or_throw(sizeof(datanode_t));
new (&(tmp->data)) T(x);
linkin(p, tmp);
return tmp;
}
/// Insert an empty element into the qlist.
/// \param p position to insert the element
/// \return reference to this new element
T &insert(iterator p)
{
datanode_t *tmp = (datanode_t*)qalloc_or_throw(sizeof(datanode_t));
new (&(tmp->data)) T();
linkin(p, tmp);
return tmp->data;
}
/// Insert all elements between 'first' and 'last' (non-inclusive)
/// at position pointed to by 'p'
template <class it2> void insert(iterator p, it2 first, it2 last)
{
while ( first != last )
insert(p, *first++);
}
/// Insert at beginning of list
void push_front(const T &x) { insert(begin(), x); }
/// Insert at end of list
void push_back(const T &x) { insert(end(), x); }
/// Insert empty element at end of list
T &push_back(void) { return insert(end()); }
/// Erase element at position pointed to by 'p'
void erase(iterator p)
{
p.cur->prev->next = p.cur->next;
p.cur->next->prev = p.cur->prev;
((datanode_t*)p.cur)->data.~T();
qfree(p.cur);
--length;
}
/// Erase all elements between 'p1' and 'p2'
void erase(iterator p1, iterator p2)
{
while ( p1 != p2 )
erase(p1++);
}
/// Erase all elements in the qlist
void clear(void) { erase(begin(), end()); }
/// Erase first element of the qlist
void pop_front(void) { erase(begin()); }
/// Erase last element of the qlist
void pop_back(void) { iterator tmp = end(); erase(--tmp); }
/// Compare two qlists with '=='
bool operator==(const qlist<T> &x) const
{
if ( length != x.length )
return false;
const_iterator q=x.begin();
for ( const_iterator p=begin(), e=end(); p != e; ++p,++q )
if ( *p != *q )
return false;
return true;
}
/// Compare two qlists with !=
bool operator!=(const qlist<T> &x) const { return !(*this == x); }
private:
void linkin(iterator p, listnode_t *tmp)
{
tmp->next = p.cur;
tmp->prev = p.cur->prev;
p.cur->prev->next = tmp;
p.cur->prev = tmp;
++length;
}
};
typedef qvector<uval_t> uvalvec_t; ///< vector of unsigned values
typedef qvector<sval_t> svalvec_t; ///< vector of signed values
typedef qvector<ea_t> eavec_t; ///< vector of addresses
typedef qvector<int> intvec_t; ///< vector of integers
typedef qvector<qstring> qstrvec_t; ///< vector of strings
typedef qvector<qwstring> qwstrvec_t; ///< vector of unicode strings
typedef qvector<bool> boolvec_t; ///< vector of bools
// Our containers do not care about their addresses. They can be moved around with simple memcpy
/// \cond
template <class T> struct ida_movable_type<qvector<T> > { typedef ida_true_type is_movable_type; };
template <class T> struct ida_movable_type<_qstring<T> > { typedef ida_true_type is_movable_type; };
template <class T> struct ida_movable_type<qlist<T> > { typedef ida_true_type is_movable_type; };
template <class T> struct ida_movable_type<qiterator<T> > { typedef ida_true_type is_movable_type; };
/// \endcond
//-------------------------------------------------------------------------
/// Resource janitor to facilitate use of the RAII idiom
template <typename T>
struct janitor_t
{
janitor_t(T &r) : resource(r) {} ///< Constructor
~janitor_t(); ///< We provide no implementation for this function, you should
///< provide specialized implementation yourself
protected:
T &resource;
};
//-------------------------------------------------------------------------
/// Align element up to nearest boundary
template <class T> T align_up(T val, int elsize)
{
int mask = elsize - 1;
val += mask;
val &= ~mask;
return val;
}
//-------------------------------------------------------------------------
/// Align element down to nearest boundary
template <class T> T align_down(T val, int elsize)
{
int mask = elsize - 1;
val &= ~mask;
return val;
}
//-------------------------------------------------------------------------
/// \def{DEFINE_VIRTUAL_DTOR,
/// GCC generates multiple destructors and they occupy multiple slots of the
/// virtual function table. Since it makes the vft incompatible with other
/// compilers - we simply never generate virtual destructors for gcc. This is not an
/// ideal solution but it works.
/// We have this problem only under MS Windows. On other platforms everything is
/// compiled with GCC so the vft layout is the same for the kernel and plugins.}
/// \def{DECLARE_VIRTUAL_DTOR, see #DEFINE_VIRTUAL_DTOR}
#if defined(SWIG)
#define DEFINE_VIRTUAL_DTOR(name)
#define DECLARE_VIRTUAL_DTOR(name)
#elif defined(__GNUC__) && defined(__NT__)
#define DEFINE_VIRTUAL_DTOR(name) virtual void idaapi dummy_dtor_for_gcc(void) {}
#define DECLARE_VIRTUAL_DTOR(name) virtual void idaapi dummy_dtor_for_gcc(void)
#else
#define DEFINE_VIRTUAL_DTOR(name) virtual idaapi ~name(void) {}
#define DECLARE_VIRTUAL_DTOR(name) virtual idaapi ~name(void)
#endif
/// Declare class as uncopyable.
/// (copy assignment and copy ctr are undefined, so if anyone calls them,
/// there will be a compilation or link error)
#define DECLARE_UNCOPYABLE(T) T &operator=(const T &); T(const T &);
#endif // __cplusplus
struct hit_counter_t;
idaman void ida_export reg_hit_counter(hit_counter_t *, bool do_reg);
/// Create new ::hit_counter_t with given name
idaman THREAD_SAFE hit_counter_t *ida_export create_hit_counter(const char *name);
idaman THREAD_SAFE void ida_export hit_counter_timer(hit_counter_t *, bool enable);
/// Statistical counter for profiling
struct hit_counter_t
{
const char *name; ///< name is owned by hit_counter_t
///< reg_hit_counter() allocates it
int total, misses;
uint64 elapsed; ///< number of elapsed counts
uint64 stamp; ///< start time
hit_counter_t(const char *_name)
: name(_name), total(0), misses(0), elapsed(0)
{ reg_hit_counter(this, true); }
virtual ~hit_counter_t(void) { reg_hit_counter(this, false); }
/// Prints the counter to the message window and resets it
virtual void print(void);
// time functions
void start(void) { hit_counter_timer(this, true); }
void stop(void) { hit_counter_timer(this, false); }
};
/// Formalized counter increment - see ::hit_counter_t
class incrementer_t
{
hit_counter_t &ctr;
public:
incrementer_t(hit_counter_t &_ctr) : ctr(_ctr) { ctr.total++; ctr.start(); }
~incrementer_t(void) { ctr.stop(); }
DEFINE_MEMORY_ALLOCATION_FUNCS()
void failed(void) { ctr.misses++; }
};
#ifndef UNICODE
#define cwstr(dst, src, dstsize) ::qstrncpy(dst, src, dstsize)
#define wcstr(dst, src, dstsize) ::qstrncpy(dst, src, dstsize)
#endif
/// Encode base64
idaman THREAD_SAFE bool ida_export base64_encode(qstring *output, const void *input, size_t size);
/// Decode base64
idaman THREAD_SAFE bool ida_export base64_decode(bytevec_t *output, const char *input, size_t size); ///< Decode base64
/// Convert tabulations to spaces
/// \param out output buffer to append to
/// \param str input string. can not be equal to out->c_str()
/// \param tabsize tabulation size
/// \returns true-replaced some tabs
idaman THREAD_SAFE bool ida_export replace_tabs(qstring *out, const char *str, int tabsize);
/// Unicode -> char
idaman THREAD_SAFE bool ida_export u2cstr(const wchar16_t *in, qstring *out, int nsyms=-1);
///< Char -> unicode
idaman THREAD_SAFE bool ida_export c2ustr(const char *in, qwstring *out, int nsyms=-1);
/// utf-8 -> 16bit unicode
idaman THREAD_SAFE int ida_export utf8_unicode(const char *in, wchar16_t *out, size_t outsize);
/// 16bit unicode -> utf8
idaman THREAD_SAFE bool ida_export unicode_utf8(qstring *res, const wchar16_t *in, int nsyms);
/// Windows utf-8 (<0xFFFF) -> idb representation (oem)
idaman THREAD_SAFE bool ida_export win_utf2idb(char *buf);
/// Read one utf-8 character from string. if error, return -1
idaman THREAD_SAFE wchar32_t ida_export get_utf8_char(const char **pptr);
#if defined(__NT__) && !defined(UNDER_CE)
/// Do not use windows CharToOem/OemToChar functions - ida can replace CodePage
idaman void ida_export char2oem(char *inout);
idaman void ida_export oem2char(char *inout); ///< \copydoc char2oem
#else
inline void idaapi char2oem(char* /*inout*/) { }
inline void idaapi oem2char(char* /*inout*/) { }
#endif
/// Set codepages to be used for char2oem/oem2char (Windows only).
/// if parameter == -1, use CP_ACP and CP_OEMCP
/// \return false if codepage unsupported
idaman bool ida_export set_codepages(int acp/* = CP_ACP*/, int oemcp/* = CP_OEMCP*/);
/// Get codepages used for char2oem/oem2char (Windows only).
/// \param[out] oemcp pointer to oem codepage
/// \return current codepage
idaman int ida_export get_codepages(int* oemcp);
#ifdef __NT__
/// Convert data from codepage incp to outcp.
/// Either codepage can be CP_UTF16 for Unicode text (buffer sizes are still in bytes!)
/// flags: 1: convert control characters (0x01-0x1F) to glyphs
/// \param insize insize == -1: input is null-terminated
/// \return number of bytes after conversion (not counting termination zero)
idaman int ida_export convert_codepage(const void* in, int insize, void* out, size_t outsize, int incp, int outcp, int flags = 0);
#else
inline int idaapi convert_codepage(const void* /*in*/, int /*insize*/, void* /*out*/, size_t /*outsize*/, int /*incp*/, int /*outcp*/, int /*flags*/ = 0) { return 0; }
#endif
/// Convert data from encoding fromcode into tocode.
/// \return number of input bytes converted (can be less than actual size if there was an invalid character)
/// -1 if source or target encoding is not supported
/// possible encoding names: windows codepages ("CP1251" etc), charset names ("Shift-JIS"), and many encodings supported by iconv
idaman int ida_export convert_encoding(const char *fromcode, const char *tocode, const bytevec_t *indata, bytevec_t *out, int flags = 0);
#ifndef CP_UTF8
#define CP_UTF8 65001 ///< utf-8 codepage
#endif
#ifndef CP_UTF16
#define CP_UTF16 1200 ///< utf-16 codepage
#endif
#ifdef __NT__
#ifndef INVALID_FILE_ATTRIBUTES
#define INVALID_FILE_ATTRIBUTES ((DWORD)-1) ///< old Visual C++ compilers were not defining this
#endif
#ifndef BELOW_NORMAL_PRIORITY_CLASS
#define BELOW_NORMAL_PRIORITY_CLASS 0x00004000 ///< \copydoc INVALID_FILE_ATTRIBUTES
#endif
#endif
idaman ida_export_data char SubstChar; ///< default char, used if a char cannot be represented in a codepage
typedef uint32 flags_t; ///< 32-bit flags for each address
typedef ea_t tid_t; ///< type id (for enums, structs, etc)
typedef uint32 bgcolor_t; ///< background color in RGB
#define DEFCOLOR bgcolor_t(-1) ///< default color (used in function, segment definitions)
//-------------------------------------------------------------------------
// Command line
//-------------------------------------------------------------------------
/// Tools for command line parsing
struct channel_redir_t
{
int fd; ///< channel number
qstring file; ///< file name to redirect to/from.
///< if empty, the channel must be closed.
int flags; ///< \ref IOREDIR_
/// \defgroup IOREDIR_ i/o redirection flags
/// used by channel_redir_t::flags
//@{
#define IOREDIR_INPUT 0x01 ///< input redirection
#define IOREDIR_OUTPUT 0x02 ///< output redirection
#define IOREDIR_APPEND 0x04 ///< append, do not overwrite the output file
#define IOREDIR_QUOTED 0x08 ///< the file name was quoted
//@}
bool is_input(void) const { return (flags & IOREDIR_INPUT) != 0; }
bool is_output(void) const { return (flags & IOREDIR_OUTPUT) != 0; }
bool is_append(void) const { return (flags & IOREDIR_APPEND) != 0; }
bool is_quoted(void) const { return (flags & IOREDIR_QUOTED) != 0; }
int start; ///< begin of the redirection string in the command line
int length; ///< length of the redirection string in the command line
};
typedef qvector<channel_redir_t> channel_redirs_t; ///< vector of channel_redir_t objects
/// Parse a space separated string (escaping with backslash is supported).
/// \param cmdline the string to be parsed
/// \param[out] args a string vector to hold the results
/// \param[out] redirs map of channel redirections found in cmdline
/// - if NULL, redirections won't be parsed
/// - if there are syntax errors in redirections, consider them as arguments
/// \param flags #LP_PATH_WITH_ARGS or 0
/// \return the number of parsed arguments
idaman THREAD_SAFE size_t ida_export parse_command_line3(
const char *cmdline,
qstrvec_t *args,
channel_redirs_t *redirs,
int flags);
/// Copy and expand command line arguments.
/// For '@filename' arguments the file contents are inserted into the resulting argv.
/// Format of the file: one switch per line, ';' for comment lines
/// \param[out] p_argc size of the returned argv array
/// \param argc number of entries in argv array
/// \param argv array of strings
/// \return new argv (terminated by NULL).
/// It must be freed with free_argv()
idaman char **ida_export expand_argv(int *p_argc, int argc, const char *const argv[]);
/// Free 'argc' elements of 'argv'
inline void free_argv(int argc, char **argv)
{
if ( argv != NULL )
{
for ( int i = 0; i < argc; i++ )
qfree(argv[i]);
qfree(argv);
}
}
/// Quote a command line argument if it contains escape characters.
/// For example, *.c will be converted into "*.c" because * may be inadvertently
/// expanded by the shell
/// \return true: modified 'arg'
idaman bool ida_export quote_cmdline_arg(qstring *arg);
/// Parse the -r command line switch (for instant debugging).
/// r_switch points to the value of the -r switch. Example: win32@localhost+
/// \return true-ok, false-parse error
idaman bool ida_export parse_dbgopts(struct instant_dbgopts_t *ido, const char *r_switch);
/// Options for instant debugging
struct instant_dbgopts_t
{
qstring debmod; ///< name of debugger module
qstring env; ///< config variables for debmod. example: DEFAULT_CPU=13;MAXPACKETSIZE=-1
qstring host; ///< remote hostname (if remote debugging)
qstring pass; ///< password for the remote debugger server
int port; ///< port number for the remote debugger server
int pid; ///< process to attach to (-1: ask the user)
int event_id; ///< event to trigger upon attaching
bool attach; ///< should attach to a process?
};
//-------------------------------------------------------------------------
// PROCESSES
//-------------------------------------------------------------------------
/// Information for launching a process with IDA API
struct launch_process_params_t
{
size_t cb; ///< size of this structure
int flags; ///< \ref LP_
/// \defgroup LP_ Launch process flags
/// used by launch_process_params_t::flags
//@{
#define LP_NEW_CONSOLE 0x0001 ///< create new console (only ms windows)
#define LP_TRACE 0x0002 ///< debug: unix: ptrace(TRACEME), windows: DEBUG_PROCESS
#define LP_PATH_WITH_ARGS 0x0004 ///< 'args' contains executable path too
#define LP_USE_SHELL 0x0008 ///< use shell to launch the command.
///< 'path' is ignored in this case.
#define LP_LAUNCH_32_BIT 0x0010 ///< prefer to launch 32-bit part of file (only mac)
#define LP_LAUNCH_64_BIT 0x0020 ///< prefer to launch 64-bit part of file (only mac)
///< only one of LP_LAUNCH_*_BIT bits can be specified
#define LP_NO_ASLR 0x0040 ///< disable ASLR (only mac)
#define LP_DETACH_TTY 0x0080 ///< detach the current tty (unix)
//@}
const char *path; ///< file to run
const char *args; ///< command line arguments
ssize_t in_handle; ///< handle for stdin or -1
ssize_t out_handle; ///< handle for stdout or -1
ssize_t err_handle; ///< handle for stderr or -1
char *env; ///< zero separated environment variables that will be appended
///< to the existing environment block (existing variables will be updated).
///< each variable has the following form: var=value\0
///< must be terminated with two zero bytes!
const char *startdir; ///< current directory for the new process
void *info; ///< os specific info (on windows it points to PROCESS_INFORMATION)
///< on unix, not used
launch_process_params_t(void) ///< constructor
: cb(sizeof(*this)), flags(0), path(NULL), args(NULL),
in_handle(-1), out_handle(-1), err_handle(-1),
env(NULL), startdir(NULL), info(NULL) {}
};
/// Launch the specified process in parallel.
/// \return handle (unix: child pid), NULL - error
idaman THREAD_SAFE void *ida_export launch_process(
const launch_process_params_t &lpp,
qstring *errbuf);
/// Forcibly terminate a running process.
/// \returns 0-ok, otherwise an error code that can be passed to winerr()
idaman THREAD_SAFE int ida_export term_process(void *handle);
/// Wait for state changes in a child process (UNIX only).
/// Here: child, status, flags - the same as in system call waitpid()
/// \param timeout_ms timeout in milliseconds
idaman THREAD_SAFE int ida_export qwait_timed(int child, int *status, int flags, int timeout_ms);
#if defined(__UNIX__)
# ifdef WCONTINUED
# define QWCONTINUED WCONTINUED
# else
# define QWCONTINUED 8
# endif
# ifdef WNOHANG
# define QWNOHANG WNOHANG
# else
# define QWNOHANG 1
# endif
inline int qwait(int child, int *status, int flags)
{
return qwait_timed(child, status, flags, (flags & QWNOHANG) != 0 ? 0 : -1);
}
#endif
/// Check whether process has terminated or not.
/// \param handle process handle to wait for
/// \param[out] exit_code pointer to the buffer for the exit code
/// \param msecs how long to wait. special values:
/// - 0: do not wait
/// - 1 or -1: wait infinitely
/// - other values: timeout in milliseconds
/// \retval 0 process has exited, and the exit code is available.
/// if *exit_code < 0: the process was killed with a signal -*exit_code
/// \retval 1 process has not exited yet
/// \retval -1 error happened, see error code for winerr() in *exit_code
idaman THREAD_SAFE int ida_export check_process_exit(
void *handle,
int *exit_code,
int msecs=-1);
/// Teletype control
enum tty_control_t
{
TCT_UNKNOWN = 0,
TCT_OWNER,
TCT_NOT_OWNER
};
/// Check if the current process is the owner of the TTY specified
/// by 'fd' (typically an opened descriptor to /dev/tty).
idaman THREAD_SAFE tty_control_t ida_export is_control_tty(int fd);
/// If the current terminal is the controlling terminal of the calling
/// process, give up this controlling terminal.
/// \note The current terminal is supposed to be /dev/tty
idaman THREAD_SAFE void ida_export qdetach_tty(void);
/// Make the current terminal the controlling terminal of the calling
/// process.
/// \note The current terminal is supposed to be /dev/tty
idaman THREAD_SAFE void ida_export qcontrol_tty(void);
//-------------------------------------------------------------------------
/// THREADS
//-------------------------------------------------------------------------
/// Thread callback function
typedef int (idaapi *qthread_cb_t)(void *ud);
/// Thread opaque handle
typedef struct __qthread_t {} *qthread_t;
/// Create a thread and return a thread handle
idaman THREAD_SAFE qthread_t ida_export qthread_create(qthread_cb_t thread_cb, void *ud);
/// Free a thread resource (does not kill the thread)
idaman THREAD_SAFE void ida_export qthread_free(qthread_t q);
/// Wait a thread until it terminates
idaman THREAD_SAFE bool ida_export qthread_join(qthread_t q);
/// Forcefully kill a thread (calls pthread_cancel under unix)
idaman THREAD_SAFE bool ida_export qthread_kill(qthread_t q);
/// Get current thread. Must call qthread_free() to free it!
idaman THREAD_SAFE qthread_t ida_export qthread_self(void);
/// Is the current thread the same as 'q'?
idaman THREAD_SAFE bool ida_export qthread_same(qthread_t q);
/// Are we running in the main thread?
idaman THREAD_SAFE bool ida_export is_main_thread(void);
/// Thread safe function to work with the environment
idaman THREAD_SAFE bool ida_export qsetenv(const char *varname, const char *value);
idaman THREAD_SAFE bool ida_export qgetenv(const char *varname, qstring *buf=NULL); ///< \copydoc qsetenv
//-------------------------------------------------------------------------
/// Semaphore.
/// Named semaphores are public, nameless ones are local to the process
//-------------------------------------------------------------------------
typedef struct __qsemaphore_t {} *qsemaphore_t;
idaman THREAD_SAFE qsemaphore_t ida_export qsem_create(const char *name, int init_count); ///< Create a new semaphore
idaman THREAD_SAFE bool ida_export qsem_free(qsemaphore_t sem); ///< Free a semaphore
idaman THREAD_SAFE bool ida_export qsem_post(qsemaphore_t sem); ///< Unlock a semaphore
idaman THREAD_SAFE bool ida_export qsem_wait(qsemaphore_t sem, int timeout_ms); ///< Lock and decrement a semaphore. timeout = -1 means block indefinitely
//-------------------------------------------------------------------------
/// Mutex
//-------------------------------------------------------------------------
typedef struct __qmutex_t {} *qmutex_t;
idaman THREAD_SAFE bool ida_export qmutex_free(qmutex_t m); ///< Free a mutex
idaman THREAD_SAFE qmutex_t ida_export qmutex_create(); ///< Create a new mutex
idaman THREAD_SAFE bool ida_export qmutex_lock(qmutex_t m); ///< Lock a mutex
idaman THREAD_SAFE bool ida_export qmutex_unlock(qmutex_t m); ///< Unlock a mutex
/// Mutex locker object. Will lock a given mutex upon creation and unlock it when the object is destroyed
class qmutex_locker_t
{
qmutex_t lock;
public:
qmutex_locker_t(qmutex_t _lock) : lock(_lock) { qmutex_lock(lock); }
~qmutex_locker_t(void) { qmutex_unlock(lock); }
};
//-------------------------------------------------------------------------
// PIPES
//-------------------------------------------------------------------------
#ifdef __NT__
typedef void *qhandle_t; ///< MS Windows HANDLE
#else
typedef int qhandle_t; ///< file handle in Unix
#endif
/// Create a pipe.
/// \param[out] handles
/// - handles[0] : read handle
/// - handles[1] : write handle
/// \return error code (0-ok)
idaman THREAD_SAFE int ida_export qpipe_create(qhandle_t handles[2]);
/// Read from a pipe. \return number of read bytes. -1-error
idaman THREAD_SAFE ssize_t ida_export qpipe_read(qhandle_t handle, void *buf, size_t size);
/// Write to a pipe. \return number of written bytes. -1-error
idaman THREAD_SAFE ssize_t ida_export qpipe_write(qhandle_t handle, const void *buf, size_t size);
/// Close a pipe. \return error code (0-ok)
idaman THREAD_SAFE int ida_export qpipe_close(qhandle_t handle);
/// Wait for file/socket/pipe handles.
/// \param handles handles to wait for
/// \param n number of handles
/// \param write_bitmask bitmask of indexes of handles opened for writing
/// \param idx handle index
/// \param timeout_ms timeout value in milliseconds
/// \return error code. on timeout, returns 0 and sets idx to -1
idaman THREAD_SAFE int ida_export qwait_for_handles(
const qhandle_t *handles,
int n,
uint32 write_bitmask,
int *idx,
int timeout_ms);
#ifndef NO_OBSOLETE_FUNCS
idaman DEPRECATED THREAD_SAFE size_t ida_export parse_command_line(const char *cmdline, qstrvec_t *args);
idaman DEPRECATED THREAD_SAFE size_t ida_export parse_command_line2(const char *cmdline, qstrvec_t *args, channel_redirs_t *redirs);
idaman DEPRECATED char *ida_export qsplitpath(char *path, char **dir, char **file);
idaman DEPRECATED void *ida_export init_process(const launch_process_params_t &lpi, qstring *errbuf);
idaman DEPRECATED THREAD_SAFE int ida_export get_process_exit_code(void *handle, int *exit_code);
idaman DEPRECATED NORETURN void ida_export vinterr(const char *file, int line, const char *format, va_list va);
idaman DEPRECATED error_t ida_export_data qerrno;
#if !defined(__BORLANDC__) && !defined(_MSC_VER)
idaman DEPRECATED THREAD_SAFE char *ida_export strlwr(char *s);
idaman DEPRECATED THREAD_SAFE char *ida_export strupr(char *s);
#endif
#define launch_process_t launch_process_params_t ///< for convenience
#ifndef __GNUC__
typedef uint32 ulong; ///< unsigned 32 bit value
#endif
#if defined(__VC__) && defined(__X64__)
#define __VC64__
#define qstat _stat64 // use qstat64()
#define qfstat _fstat64 // use qfstat64()
#define qstatbuf struct __stat64
#else
#define qstat stat
#define qfstat fstat
#define qstatbuf struct stat
#endif
#endif
#pragma pack(pop)
#endif /* _PRO_H */
| [
"jan.schmitter@gmail.com"
] | jan.schmitter@gmail.com |
cd34a0de5f684162731eb24911cf5ece92dfd5f4 | 1f7dd1ee955460f4f4d0ec5b4bc97e2380d2353d | /n个数最大公约数/n个数最大公约数.cpp | 4a7887998d6521934f9543e2da1867caf3716e09 | [] | no_license | KemononLine/Exercise | 2e48dd6e4d3213b8bf9f8ccccbf9c3a64a324971 | 873796dc55e0f51b2e51bb978ab18b9f7300128a | refs/heads/main | 2023-08-29T01:49:36.232354 | 2021-10-17T02:40:01 | 2021-10-17T02:40:01 | 412,754,858 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 252 | cpp | #include <stdio.h>
int main()
{
int n,a,b;
scanf("%d", &n);
scanf("%d", &a);
for(int i=1; i<n; i++)
{
scanf("%d", &b);
while( 1 )
{
int r=a%b;
if(r==0)
break;
a=b; b=r;
}
}
printf("%d\n", b);
return 0;
}
| [
"88575418+KemononLine@users.noreply.github.com"
] | 88575418+KemononLine@users.noreply.github.com |
f9c1aa85a37e7f23096ad0f223894a077228237e | 9bd0b56b165ee3bdcec9ddf21207b7f8fda66401 | /a4-1test/Statistics.cc | d53e9de20ae4c1c72de55291ee458b2d55d40285 | [
"MIT"
] | permissive | sanjay105/Database-Implementation | 5b92353c3707d6ccac388eb52cf49556118f00a3 | b311548a25c722996eb88c07d8600a3a06c772f6 | refs/heads/main | 2023-06-07T02:14:28.279710 | 2021-07-02T18:33:19 | 2021-07-02T18:33:19 | 332,828,570 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,652 | cc | #include "Statistics.h"
Attribute :: Attribute(){}
// Constructor to initialize attribute with name and unique tuples
Attribute :: Attribute(int num, string name){
uniqueTuples = num;
attributeName = name;
}
// Copy Constructor to perform deep copy of the attribute object
Attribute :: Attribute(const Attribute ©Me){
uniqueTuples = copyMe.uniqueTuples;
attributeName = copyMe.attributeName;
}
// Oveloading equals to operand to perform deep copy of the attribute object
Attribute &Attribute :: operator = (const Attribute ©Me){
uniqueTuples = copyMe.uniqueTuples;
attributeName = copyMe.attributeName;
return *this;
}
Attribute :: ~Attribute(){}
Relation :: Relation(){}
// Constructor to initialize relation with name and unique tuples
Relation :: Relation(int num,string name){
totalTuples = num;
relationName = name;
}
// Copy Constructor to perform deep copy of the relation object
Relation :: Relation(const Relation ©Me){
totalTuples = copyMe.totalTuples;
relationName = copyMe.relationName;
isJoint = copyMe.isJoint;
relJoint.insert(copyMe.relJoint.begin(),copyMe.relJoint.end());
attrMap.insert(copyMe.attrMap.begin(),copyMe.attrMap.end());
}
// Oveloading equals to operand to perform deep copy of the relation object
Relation &Relation :: operator = (const Relation ©Me){
totalTuples = copyMe.totalTuples;
relationName = copyMe.relationName;
isJoint = copyMe.isJoint;
relJoint.insert(copyMe.relJoint.begin(),copyMe.relJoint.end());
attrMap.insert(copyMe.attrMap.begin(),copyMe.attrMap.end());
return *this;
}
// checks and returns if there exsists a given relation or not
bool Relation :: isRelationPresent (string name){
if ( (name == relationName) || (relJoint.find(name)!=relJoint.end()) )return true;
return false;
}
Relation :: ~Relation(){}
Statistics::Statistics(){}
// Copy Constructor to perform deep copy of the statistics object
Statistics::Statistics(Statistics ©Me)
{
relMap.insert(copyMe.relMap.begin(),copyMe.relMap.end());
}
// Oveloading equals to operand to perform deep copy of the statistics object
Statistics &Statistics:: operator=(Statistics ©Me)
{
relMap.insert(copyMe.relMap.begin(),copyMe.relMap.end());
return *this;
}
Statistics::~Statistics(){}
// Returns 0 if there exsists a relation and copies the relation object to relationInfo else return -1
int Statistics :: GetRelationForOperand(Operand *op,char *relationName[],int numJoin,Relation &relationInfo){
if(op == NULL || relationName == NULL)return -1;
for(auto itr = relMap.begin();itr != relMap.end();itr++){
if( itr->second.attrMap.find(op->value)!=itr->second.attrMap.end()){
relationInfo = itr->second;
//cout<<"GETRELATIONFOROPERAND: relation name "<<itr->first<<" s_suppkey "<<itr->second.attrMap["s_suppkey"].uniqueTuples<<endl;
//cout<<"GETRELATIONFOROPERAND: relation name "<<itr->first<<" ps_suppkey "<<itr->second.attrMap["ps_suppkey"].uniqueTuples<<endl;
//cout<<"GETRELATIONFOROPERAND: relation name "<<itr->first<<" s_suppkey1 "<<relationInfo.attrMap["s_suppkey"].uniqueTuples<<endl;
//cout<<"GETRELATIONFOROPERAND: relation name "<<itr->first<<" ps_suppkey1 "<<relationInfo.attrMap["ps_suppkey"].uniqueTuples<<endl;
return 0;
}
}
return -1;
}
// calculates the selectivity of the given OrList
double Statistics :: OrOperand(OrList *orList,char *relationName[],int numJoin){
if(orList == NULL)return 0;
double l=0,r=0;
l = CompOperand(orList->left,relationName,numJoin);
int cnt = 1;
// cout<<"OrOperand: leftvalue:"<<orList->left->left->value<<" rightvalue:"<<orList->left->right->value<<" l:"<<l<<endl;
OrList *t = orList->rightOr;
char *attributeName = orList->left->left->value;
while(t){
if(strcmp(attributeName,t->left->left->value)==0)cnt++;
t = t->rightOr;
}
// cout<<"Count "<<cnt<<endl;
if(cnt > 1)return cnt*l;
r = OrOperand(orList->rightOr,relationName,numJoin);
// cout <<"OROPERAND: left "<<l<<" right "<<r<<endl;
return 1 - (1-l) * (1-r);
}
// calculates the selectivity of the given AndList
double Statistics :: AndOperand(AndList *andList,char *relationName[],int numJoin){
if (andList == NULL)return 1;
double l=0,r=0;
l = OrOperand(andList->left,relationName,numJoin);
r = AndOperand(andList->rightAnd,relationName,numJoin);
// cout <<"ANDOPERAND: left "<<l<<" right "<<r<<endl;
return l*r;
// return OrOperand(andList->left,relationName,numJoin) * AndOperand(andList->rightAnd,relationName,numJoin);
}
// calculates the selectivity of the given Comparison operand
double Statistics :: CompOperand(ComparisonOp *compOp,char *relationName[],int numJoin){
Relation lRel,rRel;
double l = 0, r = 0;
int lRes = GetRelationForOperand(compOp->left,relationName,numJoin,lRel);
int rRes = GetRelationForOperand(compOp->right,relationName,numJoin,rRel);
int code = compOp->code;
// cout<<compOp->left->value<<" "<<compOp->code<<" "<<compOp->right->value<<endl;
if(compOp->left->code==NAME){
if(lRes==-1){
l = 1;
}else{
//cout << "COMPOPERAND: Left relationname "<<lRel.relationName<<" compOp "<<compOp->left->value<<endl;
//cout << "COMPOPERAND: Left1 "<<lRel.attrMap[string(compOp->left->value)].uniqueTuples<<endl;
//cout << "COMPOPERAND: Left2 "<<lRel.attrMap[compOp->left->value].uniqueTuples<<endl;
l = lRel.attrMap[string(compOp->left->value)].uniqueTuples;
}
}else{
l = -1;
}
if(compOp->right->code==NAME){
if(rRes==-1){
r = 1;
}else{
//cout << "COMPOPERAND: Right relationname "<<rRel.relationName<<" compOp "<<compOp->right->value<<endl;
//cout << "COMPOPERAND: Right1 "<<lRel.attrMap[string(compOp->right->value)].uniqueTuples<<endl;
//cout << "COMPOPERAND: Right2 "<<lRel.attrMap[compOp->right->value].uniqueTuples<<endl;
r = rRel.attrMap[string(compOp->right->value)].uniqueTuples;
}
}else{
r = -1;
}
// cout <<"COMPOPERAND: Result left "<<l<<" right "<<r<<endl;
if(code == LESS_THAN || code == GREATER_THAN){
return 1.0/3.0;
}else if(code == EQUALS){
if(l>r){
return 1/l;
}else{
return 1/r;
}
}
return 0;
}
// Adds the relation to the current statistics object
void Statistics::AddRel(char *relName, int numTuples)
{
string relationName(relName);
Relation newRel(numTuples,relationName);
relMap[relationName] = newRel;
//cout<<"ADDREL: relationname "<<relationName<<" relmap size "<<relMap.size()<<endl;
}
// Adds the attribute to the given relation in the current statistics object
void Statistics::AddAtt(char *relName, char *attName, int numDistincts)
{
string relationName(relName),attributeName(attName);
if (numDistincts == -1){
numDistincts = relMap[relationName].totalTuples;
}
Attribute newAttribute(numDistincts,attributeName);
relMap[relationName].attrMap[attributeName] = newAttribute;
//cout<<"ADDATT: added "<<attributeName<<" attribute to "<<relationName<<" relation which has "<<newAttribute.uniqueTuples<<" tuples"<<endl;
}
// Makes a copy of the relation object with the new name
void Statistics::CopyRel(char *oldName, char *newName)
{
string newRelation(newName),oldRelation(oldName);
relMap[newRelation] = relMap[oldRelation];
relMap[newRelation].relationName = newRelation;
map<string,Attribute> newAttrMap;
for(auto itr = relMap[newRelation].attrMap.begin(); itr != relMap[newRelation].attrMap.end(); itr++){
Attribute temp(itr->second);
temp.attributeName = newRelation+"."+itr->first;
newAttrMap[temp.attributeName] = temp;
}
relMap[newRelation].attrMap = newAttrMap;
}
// Reads the data from the file and modifies the current statistics object
void Statistics::Read(char *fromWhere)
{
ifstream in(fromWhere);
if(!in){
//cout<<"File Doesn't exsist"<<endl;
exit(0);
}
relMap.clear();
int totalTuples, uniqueTuples, numJoint, numRelations, numAttributes;
string relationName, jointName, attributeName;
in >> numRelations;
for(int i=0;i<numRelations;i++){
in >> relationName;
in >> totalTuples;
AddRel(&relationName[0],totalTuples);
in >> relMap[relationName].isJoint;
if(relMap[relationName].isJoint){
in >> numJoint;
for(int j=0;j<numJoint;j++){
in >> jointName;
relMap[relationName].relJoint[jointName] = jointName;
}
}
in >> numAttributes;
for(int j=0;j<numAttributes;j++){
in >> attributeName;
in >> uniqueTuples;
AddAtt(&relationName[0],&attributeName[0],uniqueTuples);
}
}
}
// Writes the current statistics object into a file
void Statistics::Write(char *fromWhere)
{
ofstream out(fromWhere);
out << relMap.size()<<endl;
//cout << relMap.size()<<endl;
for( auto itr = relMap.begin();itr != relMap.end();itr++){
out << itr->second.relationName <<endl;
out << itr->second.totalTuples <<endl;
out << itr->second.isJoint <<endl;
//cout << itr->second.relationName <<endl;
//cout << itr->second.totalTuples <<endl;
//cout << itr->second.isJoint <<endl;
if(itr->second.isJoint){
out << itr->second.relJoint.size() <<endl;
//cout << itr->second.relJoint.size() <<endl;
for( auto itr1 = itr->second.relJoint.begin(); itr1 != itr->second.relJoint.end(); ++itr1){
out << itr1->second <<endl;
//cout << itr1->second <<endl;
}
}
out << itr->second.attrMap.size() <<endl;
//cout << itr->second.attrMap.size() <<endl;
for( auto itr1 = itr->second.attrMap.begin(); itr1 != itr->second.attrMap.end(); ++itr1){
out << itr1->second.attributeName << endl;
//cout << itr1->second.attributeName << endl;
out << itr1->second.uniqueTuples << endl;
//cout << itr1->second.uniqueTuples << endl;
}
}
}
// Modifies the statistics object after applying the given cnf
void Statistics::Apply(struct AndList *parseTree, char *relNames[], int numToJoin)
{
int ind = 0, numJoin = 0;
char *names[100];
Relation rel;
while (ind < numToJoin) {
string buffer (relNames[ind]);
auto iter = relMap.find (buffer);
if (iter != relMap.end ()) {
rel = iter->second;
names[numJoin++] = relNames[ind];
if (rel.isJoint) {
int size = rel.relJoint.size();
if (size <= numToJoin) {
for (int i = 0; i < numToJoin; i++) {
string buf (relNames[i]);
if (rel.relJoint.find (buf) == rel.relJoint.end () &&
rel.relJoint[buf] != rel.relJoint[buffer]) {
return;
}
}
}
}
else {
ind++;
continue;
}
}
ind++;
}
double estimation = Estimate (parseTree, names, numJoin);
ind = 1;
string firstRelName (names[0]);
Relation firstRel = relMap[firstRelName];
Relation temp;
relMap.erase (firstRelName);
firstRel.isJoint = true;
firstRel.totalTuples = estimation;
// cout << "APPLY: "<<firstRelName<<" "<<firstRel.totalTuples<<endl;
// //cout << firstRelName << endl;
// //cout << estimation << endl;
while (ind < numJoin) {
string buffer (names[ind]);
firstRel.relJoint[buffer] = buffer;
temp = relMap[buffer];
relMap.erase (buffer);
firstRel.attrMap.insert (temp.attrMap.begin (), temp.attrMap.end ());
ind++;
}
// relMap.insert ({firstRelName, firstRel});
//cout<<"APPLY: relmapsize before"<<relMap.size()<<endl;
relMap[firstRelName] = firstRel;
//cout<<"APPLY: relmapsize after"<<relMap.size()<<endl;
}
// Estimates the result record count after applying given cnf
double Statistics::Estimate(struct AndList *parseTree, char **relNames, int numToJoin)
{
int ind = 0;
double factor = 1.0, product = 1.0;
while (ind < numToJoin) {
string buffer (relNames[ind]);
if (relMap.find (buffer) != relMap.end ()) {
product *= (double) relMap[buffer].totalTuples;
}
ind++;
}
if (parseTree == NULL) return product;
factor = AndOperand (parseTree, relNames, numToJoin);
// cout <<"Product "<< product << endl;
// cout <<"Factor" << factor << endl;
// cout << product*factor <<endl;
return factor * product;
}
| [
"sanjayreddy.banda@gmail.com"
] | sanjayreddy.banda@gmail.com |
b11aa5ae98d2a217de9597d1c332dd3a7399c216 | f5f8349644e4775eafe571a9c91f2e48e30d2531 | /frameworks/cocos2d-x/cocos/editor-support/spine/Triangulator.h | 1868ba69b85caa4e25da2ed19db545d348090cc5 | [
"MIT"
] | permissive | lonag/cocos-lua | 465a87f335b13a8044980ea0194a04a7c29893af | b295461446a9ee15af1c4dc6cba258c22d04a296 | refs/heads/master | 2020-07-26T14:44:10.091803 | 2019-09-12T07:49:08 | 2019-09-12T07:49:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,619 | h | /******************************************************************************
* Spine Runtimes License Agreement
* Last updated May 1, 2019. Replaces all prior versions.
*
* Copyright (c) 2013-2019, Esoteric Software LLC
*
* Integration of the Spine Runtimes into software or otherwise creating
* derivative works of the Spine Runtimes is permitted under the terms and
* conditions of Section 2 of the Spine Editor License Agreement:
* http://esotericsoftware.com/spine-editor-license
*
* Otherwise, it is permitted to integrate the Spine Runtimes into software
* or otherwise create derivative works of the Spine Runtimes (collectively,
* "Products"), provided that each user of the Products must obtain their own
* Spine Editor license and redistribution of the Products in any form must
* include this license and copyright notice.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE LLC "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 ESOTERIC SOFTWARE LLC BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS
* INTERRUPTION, OR LOSS OF USE, DATA, OR PROFITS) 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 Spine_Triangulator_h
#define Spine_Triangulator_h
#include "spine/Vector.h"
#include "spine/Pool.h"
namespace spine {
class SP_API Triangulator : public SpineObject {
public:
~Triangulator();
Vector<int> &triangulate(Vector<float> &vertices);
Vector< Vector<float>* > &decompose(Vector<float> &vertices, Vector<int> &triangles);
private:
Vector<Vector < float>* > _convexPolygons;
Vector<Vector < int>* > _convexPolygonsIndices;
Vector<int> _indices;
Vector<bool> _isConcaveArray;
Vector<int> _triangles;
Pool <Vector<float> > _polygonPool;
Pool <Vector<int> > _polygonIndicesPool;
static bool isConcave(int index, int vertexCount, Vector<float> &vertices, Vector<int> &indices);
static bool positiveArea(float p1x, float p1y, float p2x, float p2y, float p3x, float p3y);
static int winding(float p1x, float p1y, float p2x, float p2y, float p3x, float p3y);
};
}
#endif /* Spine_Triangulator_h */
| [
"codetypes@gmail.com"
] | codetypes@gmail.com |
3b3f4244960667fb03c8ea7c4a8a9926aa3b5804 | 6bbaf735bd1af2833c5ca54c8ba2c94362c64d37 | /opencv-4.1.1/modules/videoio/perf/perf_input.cpp | 27fa11165edd764ae1f751c2a9defbdd9586b7ab | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | Jonsuff/AutoDeliverProject_Turtlebot3 | 93487927c97931457bed53825b47022fd0dbe90e | 7efe84c07f993d3457d5d5897c3f099688f68e75 | refs/heads/master | 2021-07-13T16:29:56.349212 | 2019-11-11T10:56:51 | 2019-11-11T10:56:51 | 212,256,298 | 0 | 1 | Apache-2.0 | 2020-10-13T16:58:32 | 2019-10-02T04:37:51 | C++ | UTF-8 | C++ | false | false | 1,000 | cpp | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html
#include "perf_precomp.hpp"
namespace opencv_test
{
using namespace perf;
typedef perf::TestBaseWithParam<std::string> VideoCapture_Reading;
const string bunny_files[] = {
"highgui/video/big_buck_bunny.avi",
"highgui/video/big_buck_bunny.mov",
"highgui/video/big_buck_bunny.mp4",
#ifndef HAVE_MSMF
// MPEG2 is not supported by Media Foundation yet
// http://social.msdn.microsoft.com/Forums/en-US/mediafoundationdevelopment/thread/39a36231-8c01-40af-9af5-3c105d684429
"highgui/video/big_buck_bunny.mpg",
#endif
"highgui/video/big_buck_bunny.wmv"
};
PERF_TEST_P(VideoCapture_Reading, ReadFile, testing::ValuesIn(bunny_files) )
{
string filename = getDataPath(GetParam());
VideoCapture cap;
TEST_CYCLE() cap.open(filename);
SANITY_CHECK_NOTHING();
}
} // namespace
| [
"dbwhdtjq92@gmail.com"
] | dbwhdtjq92@gmail.com |
3e1ae22c0e281e82c57df37b320c3a7e44ced356 | f5110ca088f5dc76f36f68a3af1423719680c628 | /ONP.cpp | d8159046630725a030c8c2c21f4082afc8f6bf4e | [] | no_license | tejas1995/SPOJ-solutions | 73ea196a170dd1b0c80c123b8e0c1bfe82d3da0b | fb7b1e8c1f729860661a09c9999405a734da902e | refs/heads/master | 2021-01-10T02:57:59.691488 | 2016-01-14T09:23:55 | 2016-01-14T09:23:55 | 47,422,853 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 576 | cpp | #include <iostream>
#include <string.h>
#include <stack>
using namespace std;
int main()
{
int t;
cin >> t;
cin.ignore();
char str[400];
stack <char> s;
while(t--)
{
cin.getline(str, 400);
int len = strlen (str);
for(int i=0;i<len;i++ )
{
if(isalpha(str[i]))
cout << str[i];
else if(str[i] == ')' )
{
cout << s.top ();
s.pop ();
}
else if (str[i] != '(' )
s.push (str[i]);
}
cout << endl;
}
} | [
"tejas.srinivasan95@gmail.com"
] | tejas.srinivasan95@gmail.com |
f02cc8c4eb246d72b0334106df1d4b2de3908508 | a339931fe5ccc7d1a3b03c7bdc733bb0fc93af78 | /Source/db/booktable.cpp | 2b134f67f763f56593c2f1e674efff89dc880ab7 | [] | no_license | aubele/library-software | 111a6ae17b7538ffa2b17caeee11c08cb1b3a3e7 | 035fb813eec53e12dfd639019c1f5a772f9a538c | refs/heads/master | 2023-01-24T11:03:24.571250 | 2020-10-25T14:09:53 | 2020-10-25T14:09:53 | 307,102,625 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 48,241 | cpp | #include "booktable.h"
#include <QSqlQuery>
#include <QSqlDatabase>
#include <QSqlRecord>
#include <QVariant>
//====================
// Implementation of BookTable
//====================
//--------------------
// Constructor
//--------------------
BookTable::BookTable(QString tablename, QString isbncolumn, QString titlecolumn, QString subtitlecolumn,
QString publishercolumn, QString authorcolumn, QString subjectcolumn, QString gradecolumn,
QString editioncolumn, QString pricecolumn, QString stockcolumn, QString availablecolumn,
QString commentcolumn, QString stocktakingcountcolumn, QString stocktakingdatecolumn) noexcept:
mTableName(tablename),
mIsbnColumn(isbncolumn),
mTitleColumn(titlecolumn),
mSubTitleColumn(subtitlecolumn),
mPublisherColumn(publishercolumn),
mAuthorColumn(authorcolumn),
mSubjectColumn(subjectcolumn),
mGradeColumn(gradecolumn),
mEditionColumn(editioncolumn),
mPriceColumn(pricecolumn),
mStockColumn(stockcolumn),
mAvailableColumn(availablecolumn),
mCommentColumn(commentcolumn),
mStockTakingCountColumn(stocktakingcountcolumn),
mStockTakingDateColumn(stocktakingdatecolumn)
{
}
//------------------
// Destructor
//------------------
BookTable::~BookTable() noexcept
{
}
//--------------------
// insert: adds a new book
// Parameter: isbn, title, subtitle, publisher, author, subject, grade, edition, price, stock, available, comment,
// stocktakingCount, stocktakingDate
//--------------------
bool BookTable::insert(QString isbn, QString title, QString subtitle, QString publisher, QString author,
QString subject, QList<int> grades, int edition, QString price, int stock, int available,
QString comment, int stocktakingCount, QString stocktakingDate) noexcept
{
bool success = false;
if(!QSqlDatabase::database().open())
{
return false;
}
QString dbGrades;
for(int grade : grades)
{
dbGrades.append(QString::number(grade));
dbGrades.append(",");
}
dbGrades.chop(1);
QSqlQuery query;
query.prepare("INSERT INTO " + mTableName + " (" + mIsbnColumn + ", " + mTitleColumn + ", " + mSubTitleColumn + ", " + mPublisherColumn
+ ", " + mAuthorColumn + ", " + mSubjectColumn + ", " + mGradeColumn + ", " + mEditionColumn + ", " + mPriceColumn
+ ", " + mStockColumn + ", " + mAvailableColumn + ", " + mCommentColumn + ", " + mStockTakingCountColumn + ", " +
mStockTakingDateColumn + ") VALUES ('" + isbn + "', '" + title + "', '" + subtitle + "', '" + publisher + "', '"
+ author + "', '" + subject + "', '" + dbGrades + "', '" + QString::number(edition) + "', '" + price +
"', '" + QString::number(stock) + "', '" + QString::number(available) + "', '" + comment + "', '" +
QString::number(stocktakingCount) + "', '" + stocktakingDate + "');");
if(query.exec())
{
success = true;
}
QSqlDatabase::database().close();
return success;
}
//--------------------
// insert: adds a new book
// Parameter: BookRow containing a book
//--------------------
bool BookTable::insert(BookRow book) noexcept
{
return insert(book.isbn, book.title, book.subtitle, book.publisher, book.author, book.subject, book.grade, book.edition, book.price,
book.stock, book.available, book.comment, book.stocktakingCount, book.stocktakingDate);
}
//--------------------
// remove: deletes a book from the database
// Parameter: isbn
//--------------------
bool BookTable::remove(QString isbn) noexcept
{
bool success = false;
if(!QSqlDatabase::database().open())
{
return false;
}
QSqlQuery query;
query.prepare("DELETE FROM " + mTableName + " WHERE " + mIsbnColumn + "='" + isbn + "';");
if(query.exec())
{
success = true;
}
QSqlDatabase::database().close();
return success;
}
//--------------------
// getBook: finds a book in the database and returns it as a BookRow
// Parameter: isbn
//--------------------
BookTable::BookRow* BookTable::getBook(QString isbn)
{
if(!QSqlDatabase::database().open())
{
throw QString("Error in code: Method getBook of BookTable: Database could not be opened!");
}
BookTable::BookRow* row = new BookTable::BookRow();
QSqlQuery query("SELECT * FROM " + mTableName + " WHERE " + mIsbnColumn + "='" + isbn + "';");
int idIsbn = query.record().indexOf(mIsbnColumn);
int idTitle = query.record().indexOf(mTitleColumn);
int idSubTitle = query.record().indexOf(mSubTitleColumn);
int idPublisher = query.record().indexOf(mPublisherColumn);
int idAuthor = query.record().indexOf(mAuthorColumn);
int idSubject = query.record().indexOf(mSubjectColumn);
int idGrade = query.record().indexOf(mGradeColumn);
int idEdition = query.record().indexOf(mEditionColumn);
int idPrice = query.record().indexOf(mPriceColumn);
int idStock = query.record().indexOf(mStockColumn);
int idAvailable = query.record().indexOf(mAvailableColumn);
int idComment = query.record().indexOf(mCommentColumn);
int idStockCount = query.record().indexOf(mStockTakingCountColumn);
int idStockDate = query.record().indexOf(mStockTakingDateColumn);
while (query.next())
{
row->isbn = query.value(idIsbn).toString();
row->title = query.value(idTitle).toString();
row->subtitle = query.value(idSubTitle).toString();
row->publisher = query.value(idPublisher).toString();
row->author = query.value(idAuthor).toString();
row->subject = query.value(idSubject).toString();
QList<QString> grades = query.value(idGrade).toString().split(",");
QList<int> rowgrades;
for(QString grade : grades)
{
rowgrades.append(grade.toInt());
}
row->grade = rowgrades;
row->edition = query.value(idEdition).toInt();
row->price = query.value(idPrice).toString();
row->stock = query.value(idStock).toInt();
row->available = query.value(idAvailable).toInt();
row->comment = query.value(idComment).toString();
row->stocktakingCount = query.value(idStockCount).toInt();
row->stocktakingDate = query.value(idStockDate).toString();
}
QSqlDatabase::database().close();
return row;
}
//--------------------
// getAllBooks: returns all books in the table
//--------------------
QList<BookTable::BookRow> BookTable::getAllBooks(BookTableOrder order)
{
if(!QSqlDatabase::database().open())
{
throw QString("Error in code: Method getAllBooks of BookTable: Database could not be opened!");
}
QList<BookTable::BookRow> rows;
QString sort = " ORDER BY ";
switch(order)
{
case BookTable::BookTitleAscending:
sort += mTitleColumn + " ASC";
break;
case BookTable::BookTitleDescanding:
sort += mTitleColumn + " DESC";
break;
}
QSqlQuery query("SELECT * FROM " + mTableName + sort + ";");
int idIsbn = query.record().indexOf(mIsbnColumn);
int idTitle = query.record().indexOf(mTitleColumn);
int idSubTitle = query.record().indexOf(mSubTitleColumn);
int idPublisher = query.record().indexOf(mPublisherColumn);
int idAuthor = query.record().indexOf(mAuthorColumn);
int idSubject = query.record().indexOf(mSubjectColumn);
int idGrade = query.record().indexOf(mGradeColumn);
int idEdition = query.record().indexOf(mEditionColumn);
int idPrice = query.record().indexOf(mPriceColumn);
int idStock = query.record().indexOf(mStockColumn);
int idAvailable = query.record().indexOf(mAvailableColumn);
int idComment = query.record().indexOf(mCommentColumn);
int idStockCount = query.record().indexOf(mStockTakingCountColumn);
int idStockDate = query.record().indexOf(mStockTakingDateColumn);
while (query.next())
{
BookRow row;
row.isbn = query.value(idIsbn).toString();
row.title = query.value(idTitle).toString();
row.subtitle = query.value(idSubTitle).toString();
row.publisher = query.value(idPublisher).toString();
row.author = query.value(idAuthor).toString();
row.subject = query.value(idSubject).toString();
QList<QString> grades = query.value(idGrade).toString().split(",");
QList<int> rowgrades;
for(QString grade : grades)
{
rowgrades.append(grade.toInt());
}
row.grade = rowgrades;
row.edition = query.value(idEdition).toInt();
row.price = query.value(idPrice).toString();
row.stock = query.value(idStock).toInt();
row.available = query.value(idAvailable).toInt();
row.comment = query.value(idComment).toString();
row.stocktakingCount = query.value(idStockCount).toInt();
row.stocktakingDate = query.value(idStockDate).toString();
rows.append(row);
}
QSqlDatabase::database().close();
return rows;
}
//--------------------
// searchBookByTitle: finds all books with the given title pattern and returns them as a list
// Parameter: title
//--------------------
QList<BookTable::BookRow> BookTable::searchBookByTitle(QString title)
{
if(!QSqlDatabase::database().open())
{
throw QString("Error in code: Method searchBookByTitle of BookTable: Database could not be opened!");
}
QSqlQuery pragmaQuery("PRAGMA case_sensitive_like = true;");
pragmaQuery.exec();
pragmaQuery.finish();
QList<BookTable::BookRow> rows;
QSqlQuery query("SELECT * FROM " + mTableName + " WHERE " + mTitleColumn + " LIKE '%" + title + "%';");
int idIsbn = query.record().indexOf(mIsbnColumn);
int idTitle = query.record().indexOf(mTitleColumn);
int idSubTitle = query.record().indexOf(mSubTitleColumn);
int idPublisher = query.record().indexOf(mPublisherColumn);
int idAuthor = query.record().indexOf(mAuthorColumn);
int idSubject = query.record().indexOf(mSubjectColumn);
int idGrade = query.record().indexOf(mGradeColumn);
int idEdition = query.record().indexOf(mEditionColumn);
int idPrice = query.record().indexOf(mPriceColumn);
int idStock = query.record().indexOf(mStockColumn);
int idAvailable = query.record().indexOf(mAvailableColumn);
int idComment = query.record().indexOf(mCommentColumn);
int idStockCount = query.record().indexOf(mStockTakingCountColumn);
int idStockDate = query.record().indexOf(mStockTakingDateColumn);
while (query.next())
{
BookRow row;
row.isbn = query.value(idIsbn).toString();
row.title = query.value(idTitle).toString();
row.subtitle = query.value(idSubTitle).toString();
row.publisher = query.value(idPublisher).toString();
row.author = query.value(idAuthor).toString();
row.subject = query.value(idSubject).toString();
QList<QString> grades = query.value(idGrade).toString().split(",");
QList<int> rowgrades;
for(QString grade : grades)
{
rowgrades.append(grade.toInt());
}
row.grade = rowgrades;
row.edition = query.value(idEdition).toInt();
row.price = query.value(idPrice).toString();
row.stock = query.value(idStock).toInt();
row.available = query.value(idAvailable).toInt();
row.comment = query.value(idComment).toString();
row.stocktakingCount = query.value(idStockCount).toInt();
row.stocktakingDate = query.value(idStockDate).toString();
rows.append(row);
}
QSqlDatabase::database().close();
return rows;
}
//--------------------
// searchBookBySubTitle: finds all books with the given subtitle pattern and returns them as a list
// Parameter: subtitle
//--------------------
QList<BookTable::BookRow> BookTable::searchBookBySubTitle(QString subtitle)
{
if(!QSqlDatabase::database().open())
{
throw QString("Error in code: Method searchBookBySubTitle of BookTable: Database could not be opened!");
}
QSqlQuery pragmaQuery("PRAGMA case_sensitive_like = true;");
pragmaQuery.exec();
pragmaQuery.finish();
QList<BookTable::BookRow> rows;
QSqlQuery query("SELECT * FROM " + mTableName + " WHERE " + mSubTitleColumn + " LIKE '%" + subtitle + "%';");
int idIsbn = query.record().indexOf(mIsbnColumn);
int idTitle = query.record().indexOf(mTitleColumn);
int idSubTitle = query.record().indexOf(mSubTitleColumn);
int idPublisher = query.record().indexOf(mPublisherColumn);
int idAuthor = query.record().indexOf(mAuthorColumn);
int idSubject = query.record().indexOf(mSubjectColumn);
int idGrade = query.record().indexOf(mGradeColumn);
int idEdition = query.record().indexOf(mEditionColumn);
int idPrice = query.record().indexOf(mPriceColumn);
int idStock = query.record().indexOf(mStockColumn);
int idAvailable = query.record().indexOf(mAvailableColumn);
int idComment = query.record().indexOf(mCommentColumn);
int idStockCount = query.record().indexOf(mStockTakingCountColumn);
int idStockDate = query.record().indexOf(mStockTakingDateColumn);
while (query.next())
{
BookRow row;
row.isbn = query.value(idIsbn).toString();
row.title = query.value(idTitle).toString();
row.subtitle = query.value(idSubTitle).toString();
row.publisher = query.value(idPublisher).toString();
row.author = query.value(idAuthor).toString();
row.subject = query.value(idSubject).toString();
QList<QString> grades = query.value(idGrade).toString().split(",");
QList<int> rowgrades;
for(QString grade : grades)
{
rowgrades.append(grade.toInt());
}
row.grade = rowgrades;
row.edition = query.value(idEdition).toInt();
row.price = query.value(idPrice).toString();
row.stock = query.value(idStock).toInt();
row.available = query.value(idAvailable).toInt();
row.comment = query.value(idComment).toString();
row.stocktakingCount = query.value(idStockCount).toInt();
row.stocktakingDate = query.value(idStockDate).toString();
rows.append(row);
}
QSqlDatabase::database().close();
return rows;
}
//--------------------
// searchBookByPublisher: finds all books with the given publisher pattern and returns them as a list
// Parameter: publisher
//--------------------
QList<BookTable::BookRow> BookTable::searchBookByPublisher(QString publisher)
{
if(!QSqlDatabase::database().open())
{
throw QString("Error in code: Method searchBookByPublisher of BookTable: Database could not be opened!");
}
QSqlQuery pragmaQuery("PRAGMA case_sensitive_like = true;");
pragmaQuery.exec();
pragmaQuery.finish();
QList<BookTable::BookRow> rows;
QSqlQuery query("SELECT * FROM " + mTableName + " WHERE " + mPublisherColumn + " LIKE '%" + publisher + "%';");
int idIsbn = query.record().indexOf(mIsbnColumn);
int idTitle = query.record().indexOf(mTitleColumn);
int idSubTitle = query.record().indexOf(mSubTitleColumn);
int idPublisher = query.record().indexOf(mPublisherColumn);
int idAuthor = query.record().indexOf(mAuthorColumn);
int idSubject = query.record().indexOf(mSubjectColumn);
int idGrade = query.record().indexOf(mGradeColumn);
int idEdition = query.record().indexOf(mEditionColumn);
int idPrice = query.record().indexOf(mPriceColumn);
int idStock = query.record().indexOf(mStockColumn);
int idAvailable = query.record().indexOf(mAvailableColumn);
int idComment = query.record().indexOf(mCommentColumn);
int idStockCount = query.record().indexOf(mStockTakingCountColumn);
int idStockDate = query.record().indexOf(mStockTakingDateColumn);
while (query.next())
{
BookRow row;
row.isbn = query.value(idIsbn).toString();
row.title = query.value(idTitle).toString();
row.subtitle = query.value(idSubTitle).toString();
row.publisher = query.value(idPublisher).toString();
row.author = query.value(idAuthor).toString();
row.subject = query.value(idSubject).toString();
QList<QString> grades = query.value(idGrade).toString().split(",");
QList<int> rowgrades;
for(QString grade : grades)
{
rowgrades.append(grade.toInt());
}
row.grade = rowgrades;
row.edition = query.value(idEdition).toInt();
row.price = query.value(idPrice).toString();
row.stock = query.value(idStock).toInt();
row.available = query.value(idAvailable).toInt();
row.comment = query.value(idComment).toString();
row.stocktakingCount = query.value(idStockCount).toInt();
row.stocktakingDate = query.value(idStockDate).toString();
rows.append(row);
}
QSqlDatabase::database().close();
return rows;
}
//--------------------
// searchBookByAuthor: finds all books with the given author pattern and returns them as a list
// Parameter: author
//--------------------
QList<BookTable::BookRow> BookTable::searchBookByAuthor(QString author)
{
if(!QSqlDatabase::database().open())
{
throw QString("Error in code: Method searchBookByAuthor of BookTable: Database could not be opened!");
}
QSqlQuery pragmaQuery("PRAGMA case_sensitive_like = true;");
pragmaQuery.exec();
pragmaQuery.finish();
QList<BookTable::BookRow> rows;
QSqlQuery query("SELECT * FROM " + mTableName + " WHERE " + mAuthorColumn + " LIKE '%" + author + "%';");
int idIsbn = query.record().indexOf(mIsbnColumn);
int idTitle = query.record().indexOf(mTitleColumn);
int idSubTitle = query.record().indexOf(mSubTitleColumn);
int idPublisher = query.record().indexOf(mPublisherColumn);
int idAuthor = query.record().indexOf(mAuthorColumn);
int idSubject = query.record().indexOf(mSubjectColumn);
int idGrade = query.record().indexOf(mGradeColumn);
int idEdition = query.record().indexOf(mEditionColumn);
int idPrice = query.record().indexOf(mPriceColumn);
int idStock = query.record().indexOf(mStockColumn);
int idAvailable = query.record().indexOf(mAvailableColumn);
int idComment = query.record().indexOf(mCommentColumn);
int idStockCount = query.record().indexOf(mStockTakingCountColumn);
int idStockDate = query.record().indexOf(mStockTakingDateColumn);
while (query.next())
{
BookRow row;
row.isbn = query.value(idIsbn).toString();
row.title = query.value(idTitle).toString();
row.subtitle = query.value(idSubTitle).toString();
row.publisher = query.value(idPublisher).toString();
row.author = query.value(idAuthor).toString();
row.subject = query.value(idSubject).toString();
QList<QString> grades = query.value(idGrade).toString().split(",");
QList<int> rowgrades;
for(QString grade : grades)
{
rowgrades.append(grade.toInt());
}
row.grade = rowgrades;
row.edition = query.value(idEdition).toInt();
row.price = query.value(idPrice).toString();
row.stock = query.value(idStock).toInt();
row.available = query.value(idAvailable).toInt();
row.comment = query.value(idComment).toString();
row.stocktakingCount = query.value(idStockCount).toInt();
row.stocktakingDate = query.value(idStockDate).toString();
rows.append(row);
}
QSqlDatabase::database().close();
return rows;
}
//--------------------
// searchBooksBySubject: finds all books with the given subject and returns them as a list
// Parameter: subject
//--------------------
QList<BookTable::BookRow> BookTable::searchBooksBySubject(QString subject)
{
if(!QSqlDatabase::database().open())
{
throw QString("Error in code: Method searchBooksBySubject of BookTable: Database could not be opened!");
}
QSqlQuery pragmaQuery("PRAGMA case_sensitive_like = true;");
pragmaQuery.exec();
pragmaQuery.finish();
QList<BookTable::BookRow> rows;
QSqlQuery query("SELECT * FROM " + mTableName + " WHERE " + mSubjectColumn + " LIKE '%" + subject + "%';");
int idIsbn = query.record().indexOf(mIsbnColumn);
int idTitle = query.record().indexOf(mTitleColumn);
int idSubTitle = query.record().indexOf(mSubTitleColumn);
int idPublisher = query.record().indexOf(mPublisherColumn);
int idAuthor = query.record().indexOf(mAuthorColumn);
int idSubject = query.record().indexOf(mSubjectColumn);
int idGrade = query.record().indexOf(mGradeColumn);
int idEdition = query.record().indexOf(mEditionColumn);
int idPrice = query.record().indexOf(mPriceColumn);
int idStock = query.record().indexOf(mStockColumn);
int idAvailable = query.record().indexOf(mAvailableColumn);
int idComment = query.record().indexOf(mCommentColumn);
int idStockCount = query.record().indexOf(mStockTakingCountColumn);
int idStockDate = query.record().indexOf(mStockTakingDateColumn);
while (query.next())
{
BookRow row;
row.isbn = query.value(idIsbn).toString();
row.title = query.value(idTitle).toString();
row.subtitle = query.value(idSubTitle).toString();
row.publisher = query.value(idPublisher).toString();
row.author = query.value(idAuthor).toString();
row.subject = query.value(idSubject).toString();
QList<QString> grades = query.value(idGrade).toString().split(",");
QList<int> rowgrades;
for(QString grade : grades)
{
rowgrades.append(grade.toInt());
}
row.grade = rowgrades;
row.edition = query.value(idEdition).toInt();
row.price = query.value(idPrice).toString();
row.stock = query.value(idStock).toInt();
row.available = query.value(idAvailable).toInt();
row.comment = query.value(idComment).toString();
row.stocktakingCount = query.value(idStockCount).toInt();
row.stocktakingDate = query.value(idStockDate).toString();
rows.append(row);
}
QSqlDatabase::database().close();
return rows;
}
//--------------------
// searchBooksByComment: finds all books with the given comment pattern and returns them as a list
// Parameter: comment
//--------------------
QList<BookTable::BookRow> BookTable::searchBooksByComment(QString comment)
{
if(!QSqlDatabase::database().open())
{
throw QString("Error in code: Method searchBooksByComment of BookTable: Database could not be opened!");
}
QSqlQuery pragmaQuery("PRAGMA case_sensitive_like = true;");
pragmaQuery.exec();
pragmaQuery.finish();
QList<BookTable::BookRow> rows;
QSqlQuery query("SELECT * FROM " + mTableName + " WHERE " + mCommentColumn + " LIKE '%" + comment + "%';");
int idIsbn = query.record().indexOf(mIsbnColumn);
int idTitle = query.record().indexOf(mTitleColumn);
int idSubTitle = query.record().indexOf(mSubTitleColumn);
int idPublisher = query.record().indexOf(mPublisherColumn);
int idAuthor = query.record().indexOf(mAuthorColumn);
int idSubject = query.record().indexOf(mSubjectColumn);
int idGrade = query.record().indexOf(mGradeColumn);
int idEdition = query.record().indexOf(mEditionColumn);
int idPrice = query.record().indexOf(mPriceColumn);
int idStock = query.record().indexOf(mStockColumn);
int idAvailable = query.record().indexOf(mAvailableColumn);
int idComment = query.record().indexOf(mCommentColumn);
int idStockCount = query.record().indexOf(mStockTakingCountColumn);
int idStockDate = query.record().indexOf(mStockTakingDateColumn);
while (query.next())
{
BookRow row;
row.isbn = query.value(idIsbn).toString();
row.title = query.value(idTitle).toString();
row.subtitle = query.value(idSubTitle).toString();
row.publisher = query.value(idPublisher).toString();
row.author = query.value(idAuthor).toString();
row.subject = query.value(idSubject).toString();
QList<QString> grades = query.value(idGrade).toString().split(",");
QList<int> rowgrades;
for(QString grade : grades)
{
rowgrades.append(grade.toInt());
}
row.grade = rowgrades;
row.edition = query.value(idEdition).toInt();
row.price = query.value(idPrice).toString();
row.stock = query.value(idStock).toInt();
row.available = query.value(idAvailable).toInt();
row.comment = query.value(idComment).toString();
row.stocktakingCount = query.value(idStockCount).toInt();
row.stocktakingDate = query.value(idStockDate).toString();
rows.append(row);
}
QSqlDatabase::database().close();
return rows;
}
//--------------------
// getBooksByGrade: finds all books with the given grade and returns them as a list
// Parameter: grade
//--------------------
QList<BookTable::BookRow> BookTable::getBooksByGrade(int grade)
{
if(!QSqlDatabase::database().open())
{
throw QString("Error in code: Method getBooksByGrade of BookTable: Database could not be opened!");
}
QList<BookTable::BookRow> rows;
QSqlQuery query("SELECT * FROM " + mTableName + " WHERE " + mGradeColumn + " LIKE '%" + QString::number(grade) + "%';");
int idIsbn = query.record().indexOf(mIsbnColumn);
int idTitle = query.record().indexOf(mTitleColumn);
int idSubTitle = query.record().indexOf(mSubTitleColumn);
int idPublisher = query.record().indexOf(mPublisherColumn);
int idAuthor = query.record().indexOf(mAuthorColumn);
int idSubject = query.record().indexOf(mSubjectColumn);
int idGrade = query.record().indexOf(mGradeColumn);
int idEdition = query.record().indexOf(mEditionColumn);
int idPrice = query.record().indexOf(mPriceColumn);
int idStock = query.record().indexOf(mStockColumn);
int idAvailable = query.record().indexOf(mAvailableColumn);
int idComment = query.record().indexOf(mCommentColumn);
int idStockCount = query.record().indexOf(mStockTakingCountColumn);
int idStockDate = query.record().indexOf(mStockTakingDateColumn);
while (query.next())
{
BookRow row;
row.isbn = query.value(idIsbn).toString();
row.title = query.value(idTitle).toString();
row.subtitle = query.value(idSubTitle).toString();
row.publisher = query.value(idPublisher).toString();
row.author = query.value(idAuthor).toString();
row.subject = query.value(idSubject).toString();
QList<QString> grades = query.value(idGrade).toString().split(",");
QList<int> rowgrades;
for(QString grade : grades)
{
rowgrades.append(grade.toInt());
}
row.grade = rowgrades;
row.edition = query.value(idEdition).toInt();
row.price = query.value(idPrice).toString();
row.stock = query.value(idStock).toInt();
row.available = query.value(idAvailable).toInt();
row.comment = query.value(idComment).toString();
row.stocktakingCount = query.value(idStockCount).toInt();
row.stocktakingDate = query.value(idStockDate).toString();
rows.append(row);
}
QSqlDatabase::database().close();
return rows;
}
//--------------------
// getBooksByEdition: gets all books with the given edition and returns them as a list
// Parameter: edition
//--------------------
QList<BookTable::BookRow> BookTable::getBooksByEdition(int edition)
{
if(!QSqlDatabase::database().open())
{
throw QString("Error in code: Method getBooksByEdition of BookTable: Database could not be opened!");
}
QList<BookTable::BookRow> rows;
QSqlQuery query("SELECT * FROM " + mTableName + " WHERE " + mEditionColumn + "='" + QString::number(edition) + "';");
int idIsbn = query.record().indexOf(mIsbnColumn);
int idTitle = query.record().indexOf(mTitleColumn);
int idSubTitle = query.record().indexOf(mSubTitleColumn);
int idPublisher = query.record().indexOf(mPublisherColumn);
int idAuthor = query.record().indexOf(mAuthorColumn);
int idSubject = query.record().indexOf(mSubjectColumn);
int idGrade = query.record().indexOf(mGradeColumn);
int idEdition = query.record().indexOf(mEditionColumn);
int idPrice = query.record().indexOf(mPriceColumn);
int idStock = query.record().indexOf(mStockColumn);
int idAvailable = query.record().indexOf(mAvailableColumn);
int idComment = query.record().indexOf(mCommentColumn);
int idStockCount = query.record().indexOf(mStockTakingCountColumn);
int idStockDate = query.record().indexOf(mStockTakingDateColumn);
while (query.next())
{
BookRow row;
row.isbn = query.value(idIsbn).toString();
row.title = query.value(idTitle).toString();
row.subtitle = query.value(idSubTitle).toString();
row.publisher = query.value(idPublisher).toString();
row.author = query.value(idAuthor).toString();
row.subject = query.value(idSubject).toString();
QList<QString> grades = query.value(idGrade).toString().split(",");
QList<int> rowgrades;
for(QString grade : grades)
{
rowgrades.append(grade.toInt());
}
row.grade = rowgrades;
row.edition = query.value(idEdition).toInt();
row.price = query.value(idPrice).toString();
row.stock = query.value(idStock).toInt();
row.available = query.value(idAvailable).toInt();
row.comment = query.value(idComment).toString();
row.stocktakingCount = query.value(idStockCount).toInt();
row.stocktakingDate = query.value(idStockDate).toString();
rows.append(row);
}
QSqlDatabase::database().close();
return rows;
}
//--------------------
// getBooksByStock: finds all books with the given stock and returns them as a list
// Parameter: stock
//--------------------
QList<BookTable::BookRow> BookTable::getBooksByStock(int stock)
{
if(!QSqlDatabase::database().open())
{
throw QString("Error in code: Method getBooksByStock of BookTable: Database could not be opened!");
}
QList<BookTable::BookRow> rows;
QSqlQuery query("SELECT * FROM " + mTableName + " WHERE " + mStockColumn + "='" + QString::number(stock) + "';");
int idIsbn = query.record().indexOf(mIsbnColumn);
int idTitle = query.record().indexOf(mTitleColumn);
int idSubTitle = query.record().indexOf(mSubTitleColumn);
int idPublisher = query.record().indexOf(mPublisherColumn);
int idAuthor = query.record().indexOf(mAuthorColumn);
int idSubject = query.record().indexOf(mSubjectColumn);
int idGrade = query.record().indexOf(mGradeColumn);
int idEdition = query.record().indexOf(mEditionColumn);
int idPrice = query.record().indexOf(mPriceColumn);
int idStock = query.record().indexOf(mStockColumn);
int idAvailable = query.record().indexOf(mAvailableColumn);
int idComment = query.record().indexOf(mCommentColumn);
int idStockCount = query.record().indexOf(mStockTakingCountColumn);
int idStockDate = query.record().indexOf(mStockTakingDateColumn);
while (query.next())
{
BookRow row;
row.isbn = query.value(idIsbn).toString();
row.title = query.value(idTitle).toString();
row.subtitle = query.value(idSubTitle).toString();
row.publisher = query.value(idPublisher).toString();
row.author = query.value(idAuthor).toString();
row.subject = query.value(idSubject).toString();
QList<QString> grades = query.value(idGrade).toString().split(",");
QList<int> rowgrades;
for(QString grade : grades)
{
rowgrades.append(grade.toInt());
}
row.grade = rowgrades;
row.edition = query.value(idEdition).toInt();
row.price = query.value(idPrice).toString();
row.stock = query.value(idStock).toInt();
row.available = query.value(idAvailable).toInt();
row.comment = query.value(idComment).toString();
row.stocktakingCount = query.value(idStockCount).toInt();
row.stocktakingDate = query.value(idStockDate).toString();
rows.append(row);
}
QSqlDatabase::database().close();
return rows;
}
//--------------------
// getBooksByAvailable: finds all books with the given available-number and returns them as a list
// Parameter: available
//--------------------
QList<BookTable::BookRow> BookTable::getBooksByAvailable(int available)
{
if(!QSqlDatabase::database().open())
{
throw QString("Error in code: Method getBooksByAvailable of BookTable: Database could not be opened!");
}
QList<BookTable::BookRow> rows;
QSqlQuery query("SELECT * FROM " + mTableName + " WHERE " + mAvailableColumn + "='" + QString::number(available) + "';");
int idIsbn = query.record().indexOf(mIsbnColumn);
int idTitle = query.record().indexOf(mTitleColumn);
int idSubTitle = query.record().indexOf(mSubTitleColumn);
int idPublisher = query.record().indexOf(mPublisherColumn);
int idAuthor = query.record().indexOf(mAuthorColumn);
int idSubject = query.record().indexOf(mSubjectColumn);
int idGrade = query.record().indexOf(mGradeColumn);
int idEdition = query.record().indexOf(mEditionColumn);
int idPrice = query.record().indexOf(mPriceColumn);
int idStock = query.record().indexOf(mStockColumn);
int idAvailable = query.record().indexOf(mAvailableColumn);
int idComment = query.record().indexOf(mCommentColumn);
int idStockCount = query.record().indexOf(mStockTakingCountColumn);
int idStockDate = query.record().indexOf(mStockTakingDateColumn);
while (query.next())
{
BookRow row;
row.isbn = query.value(idIsbn).toString();
row.title = query.value(idTitle).toString();
row.subtitle = query.value(idSubTitle).toString();
row.publisher = query.value(idPublisher).toString();
row.author = query.value(idAuthor).toString();
row.subject = query.value(idSubject).toString();
QList<QString> grades = query.value(idGrade).toString().split(",");
QList<int> rowgrades;
for(QString grade : grades)
{
rowgrades.append(grade.toInt());
}
row.grade = rowgrades;
row.edition = query.value(idEdition).toInt();
row.price = query.value(idPrice).toString();
row.stock = query.value(idStock).toInt();
row.available = query.value(idAvailable).toInt();
row.comment = query.value(idComment).toString();
row.stocktakingCount = query.value(idStockCount).toInt();
row.stocktakingDate = query.value(idStockDate).toString();
rows.append(row);
}
QSqlDatabase::database().close();
return rows;
}
//--------------------
// getBooksByStocktakingCount: finds all books with the given stocktakingCount and returns them as a list
// Parameter: stocktakingCount
//--------------------
QList<BookTable::BookRow> BookTable::getBooksByStocktakingCount(int stocktakingCount)
{
if(!QSqlDatabase::database().open())
{
throw QString("Error in code: Method getBooksByStocktakingCount of BookTable: Database could not be opened!");
}
QList<BookTable::BookRow> rows;
QSqlQuery query("SELECT * FROM " + mTableName + " WHERE " + mStockTakingCountColumn + "='" + QString::number(stocktakingCount) + "';");
int idIsbn = query.record().indexOf(mIsbnColumn);
int idTitle = query.record().indexOf(mTitleColumn);
int idSubTitle = query.record().indexOf(mSubTitleColumn);
int idPublisher = query.record().indexOf(mPublisherColumn);
int idAuthor = query.record().indexOf(mAuthorColumn);
int idSubject = query.record().indexOf(mSubjectColumn);
int idGrade = query.record().indexOf(mGradeColumn);
int idEdition = query.record().indexOf(mEditionColumn);
int idPrice = query.record().indexOf(mPriceColumn);
int idStock = query.record().indexOf(mStockColumn);
int idAvailable = query.record().indexOf(mAvailableColumn);
int idComment = query.record().indexOf(mCommentColumn);
int idStockCount = query.record().indexOf(mStockTakingCountColumn);
int idStockDate = query.record().indexOf(mStockTakingDateColumn);
while (query.next())
{
BookRow row;
row.isbn = query.value(idIsbn).toString();
row.title = query.value(idTitle).toString();
row.subtitle = query.value(idSubTitle).toString();
row.publisher = query.value(idPublisher).toString();
row.author = query.value(idAuthor).toString();
row.subject = query.value(idSubject).toString();
QList<QString> grades = query.value(idGrade).toString().split(",");
QList<int> rowgrades;
for(QString grade : grades)
{
rowgrades.append(grade.toInt());
}
row.grade = rowgrades;
row.edition = query.value(idEdition).toInt();
row.price = query.value(idPrice).toString();
row.stock = query.value(idStock).toInt();
row.available = query.value(idAvailable).toInt();
row.comment = query.value(idComment).toString();
row.stocktakingCount = query.value(idStockCount).toInt();
row.stocktakingDate = query.value(idStockDate).toString();
rows.append(row);
}
QSqlDatabase::database().close();
return rows;
}
//--------------------
// getBooksByStocktakingDate: finds all books with the given stocktakingDate and returns them as a list
// Parameter: stocktakingDate
//--------------------
QList<BookTable::BookRow> BookTable::getBooksByStocktakingDate(QString stocktakingDate)
{
if(!QSqlDatabase::database().open())
{
throw QString("Error in code: Method getBooksByStocktakingDate of BookTable: Database could not be opened!");
}
QList<BookTable::BookRow> rows;
QSqlQuery query("SELECT * FROM " + mTableName + " WHERE " + mStockTakingDateColumn + "='" + stocktakingDate + "';");
int idIsbn = query.record().indexOf(mIsbnColumn);
int idTitle = query.record().indexOf(mTitleColumn);
int idSubTitle = query.record().indexOf(mSubTitleColumn);
int idPublisher = query.record().indexOf(mPublisherColumn);
int idAuthor = query.record().indexOf(mAuthorColumn);
int idSubject = query.record().indexOf(mSubjectColumn);
int idGrade = query.record().indexOf(mGradeColumn);
int idEdition = query.record().indexOf(mEditionColumn);
int idPrice = query.record().indexOf(mPriceColumn);
int idStock = query.record().indexOf(mStockColumn);
int idAvailable = query.record().indexOf(mAvailableColumn);
int idComment = query.record().indexOf(mCommentColumn);
int idStockCount = query.record().indexOf(mStockTakingCountColumn);
int idStockDate = query.record().indexOf(mStockTakingDateColumn);
while (query.next())
{
BookRow row;
row.isbn = query.value(idIsbn).toString();
row.title = query.value(idTitle).toString();
row.subtitle = query.value(idSubTitle).toString();
row.publisher = query.value(idPublisher).toString();
row.author = query.value(idAuthor).toString();
row.subject = query.value(idSubject).toString();
QList<QString> grades = query.value(idGrade).toString().split(",");
QList<int> rowgrades;
for(QString grade : grades)
{
rowgrades.append(grade.toInt());
}
row.grade = rowgrades;
row.edition = query.value(idEdition).toInt();
row.price = query.value(idPrice).toString();
row.stock = query.value(idStock).toInt();
row.available = query.value(idAvailable).toInt();
row.comment = query.value(idComment).toString();
row.stocktakingCount = query.value(idStockCount).toInt();
row.stocktakingDate = query.value(idStockDate).toString();
rows.append(row);
}
QSqlDatabase::database().close();
return rows;
}
//--------------------
// updateTitle: writes a new title for the given book in the database
// Parameter: isbn, title
//--------------------
bool BookTable::updateTitle(QString isbn, QString title) noexcept
{
bool success = false;
if(!QSqlDatabase::database().open())
{
return false;
}
QSqlQuery query;
query.prepare("UPDATE " + mTableName + " SET " + mTitleColumn + "='" + title + "' WHERE " + mIsbnColumn +
"='" + isbn + "';");
if(query.exec())
{
success = true;
}
QSqlDatabase::database().close();
return success;
}
//--------------------
// updateSubTitle: writes a new subtitle for the given book in the database
// Parameter: isbn, subtitle
//--------------------
bool BookTable::updateSubTitle(QString isbn, QString subtitle) noexcept
{
bool success = false;
if(!QSqlDatabase::database().open())
{
return false;
}
QSqlQuery query;
query.prepare("UPDATE " + mTableName + " SET " + mSubTitleColumn + "='" + subtitle + "' WHERE " + mIsbnColumn +
"='" + isbn + "';");
if(query.exec())
{
success = true;
}
QSqlDatabase::database().close();
return success;
}
//--------------------
// updatePublisher: writes a new publisher for the given book in the database
// Parameter: isbn, publisher
//--------------------
bool BookTable::updatePublisher(QString isbn, QString publisher) noexcept
{
bool success = false;
if(!QSqlDatabase::database().open())
{
return false;
}
QSqlQuery query;
query.prepare("UPDATE " + mTableName + " SET " + mPublisherColumn + "='" + publisher + "' WHERE " + mIsbnColumn +
"='" + isbn + "';");
if(query.exec())
{
success = true;
}
QSqlDatabase::database().close();
return success;
}
//--------------------
// updateAuthor: writes a new author for the given book in the database
// Parameter: isbn, author
//--------------------
bool BookTable::updateAuthor(QString isbn, QString author) noexcept
{
bool success = false;
if(!QSqlDatabase::database().open())
{
return false;
}
QSqlQuery query;
query.prepare("UPDATE " + mTableName + " SET " + mAuthorColumn + "='" + author + "' WHERE " + mIsbnColumn +
"='" + isbn + "';");
if(query.exec())
{
success = true;
}
QSqlDatabase::database().close();
return success;
}
//--------------------
// updateSubject: writes a new subject for the given book in the database
// Parameter: isbn, subject
//--------------------
bool BookTable::updateSubject(QString isbn, QString subject) noexcept
{
bool success = false;
if(!QSqlDatabase::database().open())
{
return false;
}
QSqlQuery query;
query.prepare("UPDATE " + mTableName + " SET " + mSubjectColumn + "='" + subject + "' WHERE " + mIsbnColumn +
"='" + isbn + "';");
if(query.exec())
{
success = true;
}
QSqlDatabase::database().close();
return success;
}
//--------------------
// updateGrade: writes a new grade for the given book in the database
// Parameter: isbn, grade
//--------------------
bool BookTable::updateGrade(QString isbn, QList<int> grades) noexcept
{
bool success = false;
if(!QSqlDatabase::database().open())
{
return false;
}
QString dbGrades;
for(int grade : grades)
{
dbGrades.append(QString::number(grade));
dbGrades.append(",");
}
dbGrades.chop(1);
QSqlQuery query;
query.prepare("UPDATE " + mTableName + " SET " + mGradeColumn + "='" + dbGrades + "' WHERE " + mIsbnColumn +
"='" + isbn + "';");
if(query.exec())
{
success = true;
}
QSqlDatabase::database().close();
return success;
}
//--------------------
// updateEdition: writes a new edition for the given book in the database
// Parameter: isbn, edition
//--------------------
bool BookTable::updateEdition(QString isbn, int edition) noexcept
{
bool success = false;
if(!QSqlDatabase::database().open())
{
return false;
}
QSqlQuery query;
query.prepare("UPDATE " + mTableName + " SET " + mEditionColumn + " = '" + QString::number(edition) + "' WHERE " + mIsbnColumn +
"='" + isbn + "';");
if(query.exec())
{
success = true;
}
QSqlDatabase::database().close();
return success;
}
//--------------------
// updatePrice: writes a new price for the given book in the database
// Parameter: isbn, price
//--------------------
bool BookTable::updatePrice(QString isbn, QString price) noexcept
{
bool success = false;
if(!QSqlDatabase::database().open())
{
return false;
}
QSqlQuery query;
query.prepare("UPDATE " + mTableName + " SET " + mPriceColumn + " = '" + price + "' WHERE " + mIsbnColumn +
"='" + isbn + "';");
if(query.exec())
{
success = true;
}
QSqlDatabase::database().close();
return success;
}
//--------------------
// updateStock: writes a new stock for the given book in the database
// Parameter: isbn, stock
//--------------------
bool BookTable::updateStock(QString isbn, int stock) noexcept
{
bool success = false;
if(!QSqlDatabase::database().open())
{
return false;
}
QSqlQuery query;
query.prepare("UPDATE " + mTableName + " SET " + mStockColumn + " = '" + QString::number(stock) + "' WHERE " + mIsbnColumn +
"='" + isbn + "';");
if(query.exec())
{
success = true;
}
QSqlDatabase::database().close();
return success;
}
//--------------------
// updateAvailable: writes a new available-number for the given book in the database
// Parameter: isbn, available
//--------------------
bool BookTable::updateAvailable(QString isbn, int available) noexcept
{
bool success = false;
if(!QSqlDatabase::database().open())
{
return false;
}
QSqlQuery query;
query.prepare("UPDATE " + mTableName + " SET " + mAvailableColumn + "='" + QString::number(available) + "' WHERE " + mIsbnColumn +
"='" + isbn + "';");
if(query.exec())
{
success = true;
}
QSqlDatabase::database().close();
return success;
}
//--------------------
// updateComment: writes a new comment for the given book in the database
// Parameter: isbn, comment
//--------------------
bool BookTable::updateComment(QString isbn, QString comment) noexcept
{
bool success = false;
if(!QSqlDatabase::database().open())
{
return false;
}
QSqlQuery query;
query.prepare("UPDATE " + mTableName + " SET " + mCommentColumn + "='" + comment + "' WHERE " + mIsbnColumn +
"='" + isbn + "';");
if(query.exec())
{
success = true;
}
QSqlDatabase::database().close();
return success;
}
//--------------------
// updateStocktakingCount: writes a new stocktakingCount for the given book in the database
// Parameter: isbn, stocktakingCount
//--------------------
bool BookTable::updateStocktakingCount(QString isbn, int stocktakingCount) noexcept
{
bool success = false;
if(!QSqlDatabase::database().open())
{
return false;
}
QSqlQuery query;
query.prepare("UPDATE " + mTableName + " SET " + mStockTakingCountColumn + "='" + QString::number(stocktakingCount) +
"' WHERE " + mIsbnColumn + "='" + isbn + "';");
if(query.exec())
{
success = true;
}
QSqlDatabase::database().close();
return success;
}
//--------------------
// updateGrade: writes a new grade for the given book in the database
// Parameter: isbn, stocktakingDate
//--------------------
bool BookTable::updateStocktakingDate(QString isbn, QString stocktakingDate) noexcept
{
bool success = false;
if(!QSqlDatabase::database().open())
{
return false;
}
QSqlQuery query;
query.prepare("UPDATE " + mTableName + " SET " + mStockTakingDateColumn + "='" + stocktakingDate + "' WHERE " + mIsbnColumn +
"='" + isbn + "';");
if(query.exec())
{
success = true;
}
QSqlDatabase::database().close();
return success;
}
| [
"fabioaubele95@hotmail.de"
] | fabioaubele95@hotmail.de |
36dff624ec6695204cb7d7c2a0f1ed608a20b1f6 | 1e29330fbf4d53cf5dfac6f0290f660647109da7 | /yss/drv/clock/drv_clock_st_type_C_peripherals.cpp | 83c88ba17f2f619d88268f7aefc32aefe175483f | [] | no_license | bluelife85/yss | 2c9807bba61723a6fa578f80edadd9e8d6f9d1a9 | 1ada1bcc8579bf17e53d6f31525960703ef2f6b9 | refs/heads/master | 2023-01-16T02:12:26.099052 | 2020-11-26T01:18:43 | 2020-11-26T01:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,896 | cpp | ////////////////////////////////////////////////////////////////////////////////////////
//
// 저작권 표기 License_ver_2.0
// 본 소스코드의 소유권은 yss Embedded Operating System 네이버 카페 관리자와 운영진에게 있습니다.
// 운영진이 임의로 코드의 권한을 타인에게 양도할 수 없습니다.
// 본 소스코드는 아래 사항에 동의할 경우에 사용 가능합니다.
// 아래 사항에 대해 동의하지 않거나 이해하지 못했을 경우 사용을 금합니다.
// 본 소스코드를 사용하였다면 아래 사항을 모두 동의하는 것으로 자동 간주 합니다.
// 본 소스코드의 상업적 또는 비상업적 이용이 가능합니다.
// 본 소스코드의 내용을 임의로 수정하여 재배포하는 행위를 금합니다.
// 본 소스코드의 내용을 무단 전재하는 행위를 금합니다.
// 본 소스코드의 사용으로 인해 발생하는 모든 사고에 대해서 어떤한 법적 책임을 지지 않습니다.
//
// Home Page : http://cafe.naver.com/yssoperatingsystem
// Copyright 2020. yss Embedded Operating System all right reserved.
//
// 주담당자 : 아이구 (mymy49@nate.com) 2016.04.30 ~ 현재
// 부담당자 : -
//
////////////////////////////////////////////////////////////////////////////////////////
#if defined(STM32F427xx) || defined(STM32F437xx) || \
defined(STM32F429xx) || defined(STM32F439xx)
#include <__cross_studio_io.h>
#include <drv/peripherals.h>
#include <drv/clock/drv_st_clock_type_C_register.h>
#include <drv/clock/drv_st_power_type_C_register.h>
namespace drv
{
// ################################### AHB1ENR 시작 ########################################
#if defined(GPIOA)
void Peripheral::setGpioAEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_GPIOAEN_Msk;
}
void Peripheral::resetGpioA(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_GPIOARST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_GPIOARST_Msk;
}
#endif
#if defined(GPIOB)
void Peripheral::setGpioBEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOBEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_GPIOBEN_Msk;
}
void Peripheral::resetGpioB(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_GPIOBRST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_GPIOBRST_Msk;
}
#endif
#if defined(GPIOC)
void Peripheral::setGpioCEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOCEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_GPIOCEN_Msk;
}
void Peripheral::resetGpioC(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_GPIOCRST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_GPIOCRST_Msk;
}
#endif
#if defined(GPIOD)
void Peripheral::setGpioDEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_GPIODEN_Msk;
}
void Peripheral::resetGpioD(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_GPIODRST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_GPIODRST_Msk;
}
#endif
#if defined(GPIOE)
void Peripheral::setGpioEEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOEEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_GPIOEEN_Msk;
}
void Peripheral::resetGpioE(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_GPIOERST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_GPIOERST_Msk;
}
#endif
#if defined(GPIOF)
void Peripheral::setGpioFEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOFEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_GPIOFEN_Msk;
}
void Peripheral::resetGpioF(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_GPIOFRST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_GPIOFRST_Msk;
}
#endif
#if defined(GPIOG)
void Peripheral::setGpioGEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOGEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_GPIOGEN_Msk;
}
void Peripheral::resetGpioG(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_GPIOGRST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_GPIOGRST_Msk;
}
#endif
#if defined(GPIOH)
void Peripheral::setGpioHEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOHEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_GPIOHEN_Msk;
}
void Peripheral::resetGpioH(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_GPIOHRST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_GPIOHRST_Msk;
}
#endif
#if defined(GPIOI)
void Peripheral::setGpioIEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOIEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_GPIOIEN_Msk;
}
void Peripheral::resetGpioI(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_GPIOIRST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_GPIOIRST_Msk;
}
#endif
#if defined(GPIOJ)
void Peripheral::setGpioJEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOJEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_GPIOJEN_Msk;
}
void Peripheral::resetGpioJ(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_GPIOJRST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_GPIOJRST_Msk;
}
#endif
#if defined(GPIOK)
void Peripheral::setGpioKEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOKEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_GPIOKEN_Msk;
}
void Peripheral::resetGpioK(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_GPIOKRST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_GPIOKRST_Msk;
}
#endif
#if defined(CRC)
void Peripheral::setCrcEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_CRCEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_CRCEN_Msk;
}
void Peripheral::resetCrc(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_CRCRST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_CRCRST_Msk;
}
#endif
#if defined(BKPSRAM_BASE)
void Peripheral::setBackupSramEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_BKPSRAMEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_BKPSRAMEN_Msk;
}
#endif
#if defined(CCMDATARAM_BASE)
void Peripheral::setCcmRamEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_CCMDATARAMEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_CCMDATARAMEN_Msk;
}
#endif
#if defined(DMA1)
void Peripheral::setDmaEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_DMA1EN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_DMA1EN_Msk;
#if defined(DMA2)
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_DMA2EN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_DMA2EN_Msk;
#endif
}
void Peripheral::resetDma(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_DMA1RST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_DMA1RST_Msk;
#if defined(DMA2)
RCC->AHB1RSTR |= RCC_AHB1RSTR_DMA2RST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_DMA2RST_Msk;
#endif
}
#endif
#if defined(DMA2D)
void Peripheral::setDma2d(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_DMA2DEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_DMA2DEN_Msk;
}
void Peripheral::resetDma2d(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_DMA2DRST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_DMA2DRST_Msk;
}
#endif
#if defined(ETH)
void Peripheral::setEthernetMacEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_ETHMACEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_ETHMACEN_Msk;
}
void Peripheral::setEthernetRxEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_ETHMACRXEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_ETHMACRXEN_Msk;
}
void Peripheral::setEthernetTxEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_ETHMACTXEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_ETHMACTXEN_Msk;
}
void Peripheral::setEthernetPtpEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_ETHMACPTPEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_ETHMACPTPEN_Msk;
}
void Peripheral::resetEthernetMac(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_ETHMACRST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_ETHMACRST_Msk;
}
#endif
#if defined(USB_OTG_HS)
void Peripheral::setUsbdHsEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_OTGHSEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_OTGHSEN_Msk;
}
void Peripheral::setUsbdHsUlpiEn(bool en)
{
if(en)
RCC->AHB1ENR |= RCC_AHB1ENR_OTGHSULPIEN_Msk;
else
RCC->AHB1ENR &= ~RCC_AHB1ENR_OTGHSULPIEN_Msk;
}
void Peripheral::resetUsbHs(void)
{
RCC->AHB1RSTR |= RCC_AHB1RSTR_OTGHRST_Msk;
RCC->AHB1RSTR &= ~RCC_AHB1RSTR_OTGHRST_Msk;
}
#endif
// ################################### AHB1ENR 끝 ########################################
// ################################### AHB2ENR 시작 ########################################
#if defined(DCMI)
void Peripheral::setDcmiEn(bool en)
{
if(en)
RCC->AHB2ENR |= RCC_AHB2ENR_DCMIEN_Msk;
else
RCC->AHB2ENR &= ~RCC_AHB2ENR_DCMIEN_Msk;
}
void Peripheral::resetDcmi(void)
{
RCC->AHB2RSTR |= RCC_AHB2RSTR_DCMIRST_Msk;
RCC->AHB2RSTR &= ~RCC_AHB2RSTR_DCMIRST_Msk;
}
#endif
#if defined(CRYP)
void Peripheral::setCrypEn(bool en)
{
if(en)
RCC->AHB2ENR |= RCC_AHB2ENR_CRYPEN_Msk;
else
RCC->AHB2ENR &= ~RCC_AHB2ENR_CRYPEN_Msk;
}
void Peripheral::resetCryp(void)
{
RCC->AHB2RSTR |= RCC_AHB2RSTR_CRYPRST_Msk;
RCC->AHB2RSTR &= ~RCC_AHB2RSTR_CRYPRST_Msk;
}
#endif
#if defined(HASH)
void Peripheral::setHashEn(bool en)
{
if(en)
RCC->AHB2ENR |= RCC_AHB2ENR_HASHEN_Msk;
else
RCC->AHB2ENR &= ~RCC_AHB2ENR_HASHEN_Msk;
}
void Peripheral::resetHash(void)
{
RCC->AHB2RSTR |= RCC_AHB2RSTR_HASHRST_Msk;
RCC->AHB2RSTR &= ~RCC_AHB2RSTR_HASHRST_Msk;
}
#endif
#if defined(RNG)
void Peripheral::setRngEn(bool en)
{
if(en)
RCC->AHB2ENR |= RCC_AHB2ENR_RNGEN_Msk;
else
RCC->AHB2ENR &= ~RCC_AHB2ENR_RNGEN_Msk;
}
void Peripheral::resetRng(void)
{
RCC->AHB2RSTR |= RCC_AHB2RSTR_RNGRST_Msk;
RCC->AHB2RSTR &= ~RCC_AHB2RSTR_RNGRST_Msk;
}
#endif
#if defined(USB_OTG_FS)
void Peripheral::setUsbdFsEn(bool en)
{
if(en)
RCC->AHB2ENR |= RCC_AHB2ENR_OTGFSEN_Msk;
else
RCC->AHB2ENR &= ~RCC_AHB2ENR_OTGFSEN_Msk;
}
void Peripheral::resetUsbFs(void)
{
RCC->AHB2RSTR |= RCC_AHB2RSTR_OTGFSRST_Msk;
RCC->AHB2RSTR &= ~RCC_AHB2RSTR_OTGFSRST_Msk;
}
#endif
// ################################### AHB2ENR 끝 ########################################
// ################################### AHB3ENR 시작 ########################################
#if defined(FMC_Bank1)
void Peripheral::setFmcEn(bool en)
{
if(en)
RCC->AHB3ENR |= RCC_AHB3ENR_FMCEN_Msk;
else
RCC->AHB3ENR &= ~RCC_AHB3ENR_FMCEN_Msk;
}
void Peripheral::resetFmc(void)
{
RCC->AHB3RSTR |= RCC_AHB3RSTR_FMCRST_Msk;
RCC->AHB3RSTR &= ~RCC_AHB3RSTR_FMCRST_Msk;
}
#endif
// ################################### AHB3ENR 끝 ########################################
// ################################### APB1ENR 시작 ########################################
#if defined(TIM2)
void Peripheral::setTimer2En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_TIM2EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_TIM2EN_Msk;
}
void Peripheral::resetTimer2(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_TIM2RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_TIM2RST_Msk;
}
#endif
#if defined(TIM3)
void Peripheral::setTimer3En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_TIM3EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_TIM3EN_Msk;
}
void Peripheral::resetTimer3(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_TIM3RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_TIM3RST_Msk;
}
#endif
#if defined(TIM4)
void Peripheral::setTimer4En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_TIM4EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_TIM4EN_Msk;
}
void Peripheral::resetTimer4(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_TIM4RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_TIM4RST_Msk;
}
#endif
#if defined(TIM5)
void Peripheral::setTimer5En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_TIM5EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_TIM5EN_Msk;
}
void Peripheral::resetTimer5(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_TIM5RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_TIM5RST_Msk;
}
#endif
#if defined(TIM6)
void Peripheral::setTimer6En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_TIM6EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_TIM6EN_Msk;
}
void Peripheral::resetTimer6(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_TIM6RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_TIM6RST_Msk;
}
#endif
#if defined(TIM7)
void Peripheral::setTimer7En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_TIM7EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_TIM7EN_Msk;
}
void Peripheral::resetTimer7(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_TIM7RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_TIM7RST_Msk;
}
#endif
#if defined(TIM12)
void Peripheral::setTimer12En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_TIM12EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_TIM12EN_Msk;
}
void Peripheral::resetTimer12(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_TIM12RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_TIM12RST_Msk;
}
#endif
#if defined(TIM13)
void Peripheral::setTimer13En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_TIM13EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_TIM13EN_Msk;
}
void Peripheral::resetTimer13(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_TIM13RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_TIM13RST_Msk;
}
#endif
#if defined(TIM14)
void Peripheral::setTimer14En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_TIM14EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_TIM14EN_Msk;
}
void Peripheral::resetTimer14(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_TIM14RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_TIM14RST_Msk;
}
#endif
#if defined(WWDG)
void Peripheral::setWindowWatchdogEn(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_WWDGEN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_WWDGEN_Msk;
}
void Peripheral::resetWindowWatchdog(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_WWDGRST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_WWDGRST_Msk;
}
#endif
#if defined(SPI2)
void Peripheral::setSpi2En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_SPI2EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_SPI2EN_Msk;
}
void Peripheral::resetSpi2(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_SPI2RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_SPI2RST_Msk;
}
#endif
#if defined(SPI3)
void Peripheral::setSpi3En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_SPI3EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_SPI3EN_Msk;
}
void Peripheral::resetSpi3(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_SPI3RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_SPI3RST_Msk;
}
#endif
#if defined(USART2)
void Peripheral::setUart2En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_USART2EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_USART2EN_Msk;
}
void Peripheral::resetUart2(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_USART2RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_USART2RST_Msk;
}
#endif
#if defined(USART3)
void Peripheral::setUart3En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_USART3EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_USART3EN_Msk;
}
void Peripheral::resetUart3(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_USART3RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_USART3RST_Msk;
}
#endif
#if defined(UART4)
void Peripheral::setUart4En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_UART4EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_UART4EN_Msk;
}
void Peripheral::resetUart4(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_UART4RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_UART4RST_Msk;
}
#endif
#if defined(UART5)
void Peripheral::setUart5En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_UART5EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_UART5EN_Msk;
}
void Peripheral::resetUart5(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_UART5RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_UART5RST_Msk;
}
#endif
#if defined(I2C1)
void Peripheral::setI2c1En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_I2C1EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_I2C1EN_Msk;
}
void Peripheral::resetI2c1(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_I2C1RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_I2C1RST_Msk;
}
#endif
#if defined(I2C2)
void Peripheral::setI2c2En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_I2C2EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_I2C2EN_Msk;
}
void Peripheral::resetI2c2(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_I2C2RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_I2C2RST_Msk;
}
#endif
#if defined(I2C3)
void Peripheral::setI2c3En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_I2C3EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_I2C3EN_Msk;
}
void Peripheral::resetI2c3(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_I2C3RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_I2C3RST_Msk;
}
#endif
#if defined(CAN1)
void Peripheral::setCan1En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_CAN1EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_CAN1EN_Msk;
}
void Peripheral::resetCan1(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_CAN1RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_CAN1RST_Msk;
}
#endif
#if defined(CAN2)
void Peripheral::setCan2En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_CAN2EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_CAN2EN_Msk;
}
void Peripheral::resetCan2(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_CAN2RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_CAN2RST_Msk;
}
#endif
#if defined(PWR)
void Peripheral::setPwrEn(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_PWREN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_PWREN_Msk;
}
void Peripheral::resetPwr(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_PWRRST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_PWRRST_Msk;
}
#endif
#if defined(DAC1)
void Peripheral::setDacEn(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_DACEN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_DACEN_Msk;
}
void Peripheral::resetDac(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_DACRST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_DACRST_Msk;
}
#endif
#if defined(UART7)
void Peripheral::setUart7En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_UART7EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_UART7EN_Msk;
}
void Peripheral::resetUart7(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_UART7RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_UART7RST_Msk;
}
#endif
#if defined(UART8)
void Peripheral::setUart8En(bool en)
{
if(en)
RCC->APB1ENR |= RCC_APB1ENR_UART8EN_Msk;
else
RCC->APB1ENR &= ~RCC_APB1ENR_UART8EN_Msk;
}
void Peripheral::resetUart8(void)
{
RCC->APB1RSTR |= RCC_APB1RSTR_UART8RST_Msk;
RCC->APB1RSTR &= ~RCC_APB1RSTR_UART8RST_Msk;
}
#endif
// ################################### APB1ENR 끝 ########################################
// ################################### APB2ENR 시작 ########################################
#if defined(TIM1)
void Peripheral::setTimer1En(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_TIM1EN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_TIM1EN_Msk;
}
void Peripheral::resetTimer1(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_TIM1RST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_TIM1RST_Msk;
}
#endif
#if defined(TIM8)
void Peripheral::setTimer8En(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_TIM8EN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_TIM8EN_Msk;
}
void Peripheral::resetTimer8(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_TIM8RST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_TIM8RST_Msk;
}
#endif
#if defined(USART1)
void Peripheral::setUart1En(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_USART1EN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_USART1EN_Msk;
}
void Peripheral::resetUart1(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_USART1RST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_USART1RST_Msk;
}
#endif
#if defined(USART6)
void Peripheral::setUart6En(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_USART6EN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_USART6EN_Msk;
}
void Peripheral::resetUart6(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_USART6RST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_USART6RST_Msk;
}
#endif
#if defined(ADC1)
void Peripheral::setAdc1En(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_ADC1EN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_ADC1EN_Msk;
}
void Peripheral::resetAdc(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_ADCRST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_ADCRST_Msk;
}
#endif
#if defined(ADC2)
void Peripheral::setAdc2En(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_ADC2EN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_ADC2EN_Msk;
}
#endif
#if defined(ADC3)
void Peripheral::setAdc3En(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_ADC3EN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_ADC3EN_Msk;
}
#endif
#if defined(SDIO)
void Peripheral::setSdioEn(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_SDIOEN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_SDIOEN_Msk;
}
void Peripheral::resetSdio(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_SDIORST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_SDIORST_Msk;
}
#endif
#if defined(SPI1)
void Peripheral::setSpi1En(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_SPI1EN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_SPI1EN_Msk;
}
void Peripheral::resetSpi1(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_SPI1RST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_SPI1RST_Msk;
}
#endif
#if defined(SPI4)
void Peripheral::setSpi4En(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_SPI4EN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_SPI4EN_Msk;
}
void Peripheral::resetSpi4(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_SPI4RST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_SPI4RST_Msk;
}
#endif
#if defined(SYSCFG)
void Peripheral::setSyscfgEn(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_SYSCFGEN_Msk;
}
void Peripheral::resetSyscfg(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_SYSCFGRST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_SYSCFGRST_Msk;
}
#endif
#if defined(TIM9)
void Peripheral::setTimer9En(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_TIM9EN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_TIM9EN_Msk;
}
void Peripheral::resetTimer9(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_TIM9RST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_TIM9RST_Msk;
}
#endif
#if defined(TIM10)
void Peripheral::setTimer10En(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_TIM10EN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_TIM10EN_Msk;
}
void Peripheral::resetTimer10(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_TIM10RST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_TIM10RST_Msk;
}
#endif
#if defined(TIM11)
void Peripheral::setTimer11En(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_TIM11EN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_TIM11EN_Msk;
}
void Peripheral::resetTimer11(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_TIM11RST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_TIM11RST_Msk;
}
#endif
#if defined(SPI5)
void Peripheral::setSpi5En(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_SPI5EN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_SPI5EN_Msk;
}
void Peripheral::resetSpi5(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_SPI5RST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_SPI5RST_Msk;
}
#endif
#if defined(SPI6)
void Peripheral::setSpi6En(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_SPI6EN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_SPI6EN_Msk;
}
void Peripheral::resetSpi6(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_SPI6RST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_SPI6RST_Msk;
}
#endif
#if defined(SAI1)
void setSai1En(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_SAI1EN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_SAI1EN_Msk;
}
void Peripheral::resetSai1(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_SAI1RST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_SAI1RST_Msk;
}
#endif
#if defined(LTDC)
void Peripheral::setLtdcEn(bool en)
{
if(en)
RCC->APB2ENR |= RCC_APB2ENR_LTDCEN_Msk;
else
RCC->APB2ENR &= ~RCC_APB2ENR_LTDCEN_Msk;
}
void Peripheral::resetLtdc(void)
{
RCC->APB2RSTR |= RCC_APB2RSTR_LTDCRST_Msk;
RCC->APB2RSTR &= ~RCC_APB2RSTR_LTDCRST_Msk;
}
#endif
// ################################### APB2ENR 끝 ########################################
}
#endif
| [
"mymy49@nate.com"
] | mymy49@nate.com |
e83d9105fb99110b9bf54dd34eee2463e0d6026c | 4d6703bb2120f7765121c2de5d5ac98fe5bd6c6e | /3-nn.prj/solution1/syn/systemc/update_knn.cpp | e383cbca9ba52ee4f8370f9c3e4a4ebe1ac45d6f | [] | no_license | MingSung111/knn-fpga-hls | d8b9cde5e71cabb3b7143892cb17daa1213867dc | 223aea0ed55a87c667b8414c1c50690ca5d08b2f | refs/heads/master | 2020-09-26T10:40:40.560941 | 2018-04-03T20:50:22 | 2018-04-03T20:50:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,212 | cpp | // ==============================================================
// RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC
// Version: 2017.4
// Copyright (C) 1986-2017 Xilinx, Inc. All Rights Reserved.
//
// ===========================================================
#include "update_knn.h"
#include "AESL_pkg.h"
using namespace std;
namespace ap_rtl {
const sc_logic update_knn::ap_const_logic_1 = sc_dt::Log_1;
const sc_logic update_knn::ap_const_logic_0 = sc_dt::Log_0;
const sc_lv<5> update_knn::ap_ST_fsm_state1 = "1";
const sc_lv<5> update_knn::ap_ST_fsm_state2 = "10";
const sc_lv<5> update_knn::ap_ST_fsm_state3 = "100";
const sc_lv<5> update_knn::ap_ST_fsm_state4 = "1000";
const sc_lv<5> update_knn::ap_ST_fsm_state5 = "10000";
const sc_lv<32> update_knn::ap_const_lv32_0 = "00000000000000000000000000000000";
const sc_lv<32> update_knn::ap_const_lv32_1 = "1";
const sc_lv<1> update_knn::ap_const_lv1_0 = "0";
const sc_lv<32> update_knn::ap_const_lv32_2 = "10";
const sc_lv<32> update_knn::ap_const_lv32_3 = "11";
const sc_lv<32> update_knn::ap_const_lv32_4 = "100";
const sc_lv<6> update_knn::ap_const_lv6_0 = "000000";
const sc_lv<2> update_knn::ap_const_lv2_2 = "10";
const sc_lv<1> update_knn::ap_const_lv1_1 = "1";
const sc_lv<2> update_knn::ap_const_lv2_3 = "11";
const sc_lv<2> update_knn::ap_const_lv2_0 = "00";
const sc_lv<6> update_knn::ap_const_lv6_31 = "110001";
const sc_lv<6> update_knn::ap_const_lv6_1 = "1";
const bool update_knn::ap_const_boolean_1 = true;
update_knn::update_knn(sc_module_name name) : sc_module(name), mVcdFile(0) {
SC_METHOD(thread_ap_clk_no_reset_);
dont_initialize();
sensitive << ( ap_clk.pos() );
SC_METHOD(thread_ap_CS_fsm_state1);
sensitive << ( ap_CS_fsm );
SC_METHOD(thread_ap_CS_fsm_state2);
sensitive << ( ap_CS_fsm );
SC_METHOD(thread_ap_CS_fsm_state3);
sensitive << ( ap_CS_fsm );
SC_METHOD(thread_ap_CS_fsm_state4);
sensitive << ( ap_CS_fsm );
SC_METHOD(thread_ap_CS_fsm_state5);
sensitive << ( ap_CS_fsm );
SC_METHOD(thread_ap_done);
sensitive << ( ap_start );
sensitive << ( ap_CS_fsm_state1 );
sensitive << ( ap_CS_fsm_state3 );
sensitive << ( tmp_4_fu_192_p2 );
SC_METHOD(thread_ap_idle);
sensitive << ( ap_start );
sensitive << ( ap_CS_fsm_state1 );
SC_METHOD(thread_ap_ready);
sensitive << ( ap_CS_fsm_state3 );
sensitive << ( tmp_4_fu_192_p2 );
SC_METHOD(thread_dist_V_fu_181_p2);
sensitive << ( min_distance_last_el_reg_86 );
sensitive << ( tmp_1_cast_fu_177_p1 );
SC_METHOD(thread_exitcond_fu_158_p2);
sensitive << ( ap_CS_fsm_state2 );
sensitive << ( bvh_d_index_reg_97 );
SC_METHOD(thread_grp_fu_120_p2);
sensitive << ( i1_reg_108 );
SC_METHOD(thread_i_fu_164_p2);
sensitive << ( bvh_d_index_reg_97 );
SC_METHOD(thread_index_assign_cast2_fu_154_p1);
sensitive << ( bvh_d_index_reg_97 );
SC_METHOD(thread_min_distances_V_address0);
sensitive << ( min_distances_V_addr_reg_280 );
sensitive << ( ap_CS_fsm_state3 );
sensitive << ( ap_CS_fsm_state4 );
sensitive << ( tmp_6_fu_216_p2 );
sensitive << ( ap_CS_fsm_state5 );
sensitive << ( tmp_2_cast_fu_207_p1 );
sensitive << ( tmp_3_cast_fu_231_p1 );
SC_METHOD(thread_min_distances_V_address1);
sensitive << ( min_distances_V_addr_1_reg_295 );
sensitive << ( ap_CS_fsm_state5 );
SC_METHOD(thread_min_distances_V_ce0);
sensitive << ( ap_CS_fsm_state3 );
sensitive << ( ap_CS_fsm_state4 );
sensitive << ( tmp_6_fu_216_p2 );
sensitive << ( ap_CS_fsm_state5 );
SC_METHOD(thread_min_distances_V_ce1);
sensitive << ( ap_CS_fsm_state5 );
SC_METHOD(thread_min_distances_V_d0);
sensitive << ( min_distances_V_q0 );
sensitive << ( ap_CS_fsm_state4 );
sensitive << ( tmp_6_fu_216_p2 );
sensitive << ( ap_CS_fsm_state5 );
sensitive << ( temp_min_distance_la_fu_40 );
SC_METHOD(thread_min_distances_V_d1);
sensitive << ( min_distance_last_el_1_reg_285 );
sensitive << ( ap_CS_fsm_state5 );
SC_METHOD(thread_min_distances_V_offs_1_fu_126_p1);
sensitive << ( min_distances_V_offset );
SC_METHOD(thread_min_distances_V_we0);
sensitive << ( ap_CS_fsm_state4 );
sensitive << ( tmp_6_fu_216_p2 );
sensitive << ( tmp_6_reg_291 );
sensitive << ( ap_CS_fsm_state5 );
sensitive << ( tmp_9_fu_241_p2 );
SC_METHOD(thread_min_distances_V_we1);
sensitive << ( tmp_6_reg_291 );
sensitive << ( ap_CS_fsm_state5 );
sensitive << ( tmp_9_fu_241_p2 );
SC_METHOD(thread_r_V_fu_148_p2);
sensitive << ( test_inst_V );
sensitive << ( train_inst_V_cast_fu_144_p1 );
SC_METHOD(thread_tmp_1_cast_fu_177_p1);
sensitive << ( tmp_5_fu_170_p3 );
SC_METHOD(thread_tmp_1_fu_138_p2);
sensitive << ( tmp_fu_130_p3 );
sensitive << ( min_distances_V_offs_1_fu_126_p1 );
SC_METHOD(thread_tmp_2_cast_fu_207_p1);
sensitive << ( tmp_2_fu_202_p2 );
SC_METHOD(thread_tmp_2_fu_202_p2);
sensitive << ( tmp_1_reg_246 );
sensitive << ( tmp_5_cast_fu_198_p1 );
SC_METHOD(thread_tmp_3_cast_fu_231_p1);
sensitive << ( tmp_3_fu_226_p2 );
SC_METHOD(thread_tmp_3_fu_226_p2);
sensitive << ( tmp_1_reg_246 );
sensitive << ( tmp_8_cast_fu_222_p1 );
SC_METHOD(thread_tmp_4_fu_192_p2);
sensitive << ( ap_CS_fsm_state3 );
sensitive << ( i1_reg_108 );
SC_METHOD(thread_tmp_5_cast_fu_198_p1);
sensitive << ( i1_reg_108 );
SC_METHOD(thread_tmp_5_fu_170_p3);
sensitive << ( r_V_reg_252 );
sensitive << ( index_assign_cast2_fu_154_p1 );
SC_METHOD(thread_tmp_6_fu_216_p2);
sensitive << ( min_distances_V_q0 );
sensitive << ( ap_CS_fsm_state4 );
sensitive << ( temp_min_distance_la_fu_40 );
SC_METHOD(thread_tmp_8_cast_fu_222_p1);
sensitive << ( grp_fu_120_p2 );
SC_METHOD(thread_tmp_9_fu_241_p2);
sensitive << ( min_distances_V_q0 );
sensitive << ( min_distance_last_el_1_reg_285 );
sensitive << ( tmp_6_reg_291 );
sensitive << ( ap_CS_fsm_state5 );
SC_METHOD(thread_tmp_fu_130_p3);
sensitive << ( min_distances_V_offset );
SC_METHOD(thread_train_inst_V_cast_fu_144_p1);
sensitive << ( train_inst_V );
SC_METHOD(thread_ap_NS_fsm);
sensitive << ( ap_start );
sensitive << ( ap_CS_fsm );
sensitive << ( ap_CS_fsm_state1 );
sensitive << ( ap_CS_fsm_state2 );
sensitive << ( exitcond_fu_158_p2 );
sensitive << ( ap_CS_fsm_state3 );
sensitive << ( tmp_4_fu_192_p2 );
ap_CS_fsm = "00001";
static int apTFileNum = 0;
stringstream apTFilenSS;
apTFilenSS << "update_knn_sc_trace_" << apTFileNum ++;
string apTFn = apTFilenSS.str();
mVcdFile = sc_create_vcd_trace_file(apTFn.c_str());
mVcdFile->set_time_unit(1, SC_PS);
if (1) {
#ifdef __HLS_TRACE_LEVEL_PORT_HIER__
sc_trace(mVcdFile, ap_clk, "(port)ap_clk");
sc_trace(mVcdFile, ap_rst, "(port)ap_rst");
sc_trace(mVcdFile, ap_start, "(port)ap_start");
sc_trace(mVcdFile, ap_done, "(port)ap_done");
sc_trace(mVcdFile, ap_idle, "(port)ap_idle");
sc_trace(mVcdFile, ap_ready, "(port)ap_ready");
sc_trace(mVcdFile, test_inst_V, "(port)test_inst_V");
sc_trace(mVcdFile, train_inst_V, "(port)train_inst_V");
sc_trace(mVcdFile, min_distances_V_address0, "(port)min_distances_V_address0");
sc_trace(mVcdFile, min_distances_V_ce0, "(port)min_distances_V_ce0");
sc_trace(mVcdFile, min_distances_V_we0, "(port)min_distances_V_we0");
sc_trace(mVcdFile, min_distances_V_d0, "(port)min_distances_V_d0");
sc_trace(mVcdFile, min_distances_V_q0, "(port)min_distances_V_q0");
sc_trace(mVcdFile, min_distances_V_address1, "(port)min_distances_V_address1");
sc_trace(mVcdFile, min_distances_V_ce1, "(port)min_distances_V_ce1");
sc_trace(mVcdFile, min_distances_V_we1, "(port)min_distances_V_we1");
sc_trace(mVcdFile, min_distances_V_d1, "(port)min_distances_V_d1");
sc_trace(mVcdFile, min_distances_V_offset, "(port)min_distances_V_offset");
#endif
#ifdef __HLS_TRACE_LEVEL_INT__
sc_trace(mVcdFile, ap_CS_fsm, "ap_CS_fsm");
sc_trace(mVcdFile, ap_CS_fsm_state1, "ap_CS_fsm_state1");
sc_trace(mVcdFile, tmp_1_fu_138_p2, "tmp_1_fu_138_p2");
sc_trace(mVcdFile, tmp_1_reg_246, "tmp_1_reg_246");
sc_trace(mVcdFile, r_V_fu_148_p2, "r_V_fu_148_p2");
sc_trace(mVcdFile, r_V_reg_252, "r_V_reg_252");
sc_trace(mVcdFile, i_fu_164_p2, "i_fu_164_p2");
sc_trace(mVcdFile, ap_CS_fsm_state2, "ap_CS_fsm_state2");
sc_trace(mVcdFile, dist_V_fu_181_p2, "dist_V_fu_181_p2");
sc_trace(mVcdFile, exitcond_fu_158_p2, "exitcond_fu_158_p2");
sc_trace(mVcdFile, min_distances_V_addr_reg_280, "min_distances_V_addr_reg_280");
sc_trace(mVcdFile, ap_CS_fsm_state3, "ap_CS_fsm_state3");
sc_trace(mVcdFile, tmp_4_fu_192_p2, "tmp_4_fu_192_p2");
sc_trace(mVcdFile, min_distance_last_el_1_reg_285, "min_distance_last_el_1_reg_285");
sc_trace(mVcdFile, ap_CS_fsm_state4, "ap_CS_fsm_state4");
sc_trace(mVcdFile, tmp_6_fu_216_p2, "tmp_6_fu_216_p2");
sc_trace(mVcdFile, tmp_6_reg_291, "tmp_6_reg_291");
sc_trace(mVcdFile, min_distances_V_addr_1_reg_295, "min_distances_V_addr_1_reg_295");
sc_trace(mVcdFile, grp_fu_120_p2, "grp_fu_120_p2");
sc_trace(mVcdFile, ap_CS_fsm_state5, "ap_CS_fsm_state5");
sc_trace(mVcdFile, min_distance_last_el_reg_86, "min_distance_last_el_reg_86");
sc_trace(mVcdFile, bvh_d_index_reg_97, "bvh_d_index_reg_97");
sc_trace(mVcdFile, i1_reg_108, "i1_reg_108");
sc_trace(mVcdFile, tmp_2_cast_fu_207_p1, "tmp_2_cast_fu_207_p1");
sc_trace(mVcdFile, tmp_3_cast_fu_231_p1, "tmp_3_cast_fu_231_p1");
sc_trace(mVcdFile, temp_min_distance_la_fu_40, "temp_min_distance_la_fu_40");
sc_trace(mVcdFile, tmp_9_fu_241_p2, "tmp_9_fu_241_p2");
sc_trace(mVcdFile, tmp_fu_130_p3, "tmp_fu_130_p3");
sc_trace(mVcdFile, min_distances_V_offs_1_fu_126_p1, "min_distances_V_offs_1_fu_126_p1");
sc_trace(mVcdFile, train_inst_V_cast_fu_144_p1, "train_inst_V_cast_fu_144_p1");
sc_trace(mVcdFile, index_assign_cast2_fu_154_p1, "index_assign_cast2_fu_154_p1");
sc_trace(mVcdFile, tmp_5_fu_170_p3, "tmp_5_fu_170_p3");
sc_trace(mVcdFile, tmp_1_cast_fu_177_p1, "tmp_1_cast_fu_177_p1");
sc_trace(mVcdFile, tmp_5_cast_fu_198_p1, "tmp_5_cast_fu_198_p1");
sc_trace(mVcdFile, tmp_2_fu_202_p2, "tmp_2_fu_202_p2");
sc_trace(mVcdFile, tmp_8_cast_fu_222_p1, "tmp_8_cast_fu_222_p1");
sc_trace(mVcdFile, tmp_3_fu_226_p2, "tmp_3_fu_226_p2");
sc_trace(mVcdFile, ap_NS_fsm, "ap_NS_fsm");
#endif
}
}
update_knn::~update_knn() {
if (mVcdFile)
sc_close_vcd_trace_file(mVcdFile);
}
void update_knn::thread_ap_clk_no_reset_() {
if ( ap_rst.read() == ap_const_logic_1) {
ap_CS_fsm = ap_ST_fsm_state1;
} else {
ap_CS_fsm = ap_NS_fsm.read();
}
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) &&
esl_seteq<1,1,1>(exitcond_fu_158_p2.read(), ap_const_lv1_0))) {
bvh_d_index_reg_97 = i_fu_164_p2.read();
} else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) &&
esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_1))) {
bvh_d_index_reg_97 = ap_const_lv6_0;
}
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) &&
esl_seteq<1,1,1>(exitcond_fu_158_p2.read(), ap_const_lv1_1))) {
i1_reg_108 = ap_const_lv2_2;
} else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state5.read())) {
i1_reg_108 = grp_fu_120_p2.read();
}
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) &&
esl_seteq<1,1,1>(exitcond_fu_158_p2.read(), ap_const_lv1_0))) {
min_distance_last_el_reg_86 = dist_V_fu_181_p2.read();
} else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) &&
esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_1))) {
min_distance_last_el_reg_86 = ap_const_lv6_0;
}
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read()) &&
esl_seteq<1,1,1>(tmp_6_fu_216_p2.read(), ap_const_lv1_1))) {
temp_min_distance_la_fu_40 = min_distances_V_q0.read();
} else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) &&
esl_seteq<1,1,1>(exitcond_fu_158_p2.read(), ap_const_lv1_1))) {
temp_min_distance_la_fu_40 = min_distance_last_el_reg_86.read();
}
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read())) {
min_distance_last_el_1_reg_285 = min_distances_V_q0.read();
tmp_6_reg_291 = tmp_6_fu_216_p2.read();
}
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_6_fu_216_p2.read()))) {
min_distances_V_addr_1_reg_295 = (sc_lv<5>) (tmp_3_cast_fu_231_p1.read());
}
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state3.read()) && esl_seteq<1,1,1>(ap_const_lv1_0, tmp_4_fu_192_p2.read()))) {
min_distances_V_addr_reg_280 = (sc_lv<5>) (tmp_2_cast_fu_207_p1.read());
}
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) && esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_1))) {
r_V_reg_252 = r_V_fu_148_p2.read();
tmp_1_reg_246 = tmp_1_fu_138_p2.read();
}
}
void update_knn::thread_ap_CS_fsm_state1() {
ap_CS_fsm_state1 = ap_CS_fsm.read()[0];
}
void update_knn::thread_ap_CS_fsm_state2() {
ap_CS_fsm_state2 = ap_CS_fsm.read()[1];
}
void update_knn::thread_ap_CS_fsm_state3() {
ap_CS_fsm_state3 = ap_CS_fsm.read()[2];
}
void update_knn::thread_ap_CS_fsm_state4() {
ap_CS_fsm_state4 = ap_CS_fsm.read()[3];
}
void update_knn::thread_ap_CS_fsm_state5() {
ap_CS_fsm_state5 = ap_CS_fsm.read()[4];
}
void update_knn::thread_ap_done() {
if (((esl_seteq<1,1,1>(ap_const_logic_0, ap_start.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read())) ||
(esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state3.read()) &&
esl_seteq<1,1,1>(tmp_4_fu_192_p2.read(), ap_const_lv1_1)))) {
ap_done = ap_const_logic_1;
} else {
ap_done = ap_const_logic_0;
}
}
void update_knn::thread_ap_idle() {
if ((esl_seteq<1,1,1>(ap_const_logic_0, ap_start.read()) &&
esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()))) {
ap_idle = ap_const_logic_1;
} else {
ap_idle = ap_const_logic_0;
}
}
void update_knn::thread_ap_ready() {
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state3.read()) &&
esl_seteq<1,1,1>(tmp_4_fu_192_p2.read(), ap_const_lv1_1))) {
ap_ready = ap_const_logic_1;
} else {
ap_ready = ap_const_logic_0;
}
}
void update_knn::thread_dist_V_fu_181_p2() {
dist_V_fu_181_p2 = (!min_distance_last_el_reg_86.read().is_01() || !tmp_1_cast_fu_177_p1.read().is_01())? sc_lv<6>(): (sc_biguint<6>(min_distance_last_el_reg_86.read()) + sc_biguint<6>(tmp_1_cast_fu_177_p1.read()));
}
void update_knn::thread_exitcond_fu_158_p2() {
exitcond_fu_158_p2 = (!bvh_d_index_reg_97.read().is_01() || !ap_const_lv6_31.is_01())? sc_lv<1>(): sc_lv<1>(bvh_d_index_reg_97.read() == ap_const_lv6_31);
}
void update_knn::thread_grp_fu_120_p2() {
grp_fu_120_p2 = (!i1_reg_108.read().is_01() || !ap_const_lv2_3.is_01())? sc_lv<2>(): (sc_biguint<2>(i1_reg_108.read()) + sc_bigint<2>(ap_const_lv2_3));
}
void update_knn::thread_i_fu_164_p2() {
i_fu_164_p2 = (!bvh_d_index_reg_97.read().is_01() || !ap_const_lv6_1.is_01())? sc_lv<6>(): (sc_biguint<6>(bvh_d_index_reg_97.read()) + sc_biguint<6>(ap_const_lv6_1));
}
void update_knn::thread_index_assign_cast2_fu_154_p1() {
index_assign_cast2_fu_154_p1 = esl_zext<32,6>(bvh_d_index_reg_97.read());
}
void update_knn::thread_min_distances_V_address0() {
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state5.read()) ||
(esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read()) &&
esl_seteq<1,1,1>(tmp_6_fu_216_p2.read(), ap_const_lv1_1)))) {
min_distances_V_address0 = min_distances_V_addr_reg_280.read();
} else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_0, tmp_6_fu_216_p2.read()))) {
min_distances_V_address0 = (sc_lv<5>) (tmp_3_cast_fu_231_p1.read());
} else if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state3.read())) {
min_distances_V_address0 = (sc_lv<5>) (tmp_2_cast_fu_207_p1.read());
} else {
min_distances_V_address0 = "XXXXX";
}
}
void update_knn::thread_min_distances_V_address1() {
min_distances_V_address1 = min_distances_V_addr_1_reg_295.read();
}
void update_knn::thread_min_distances_V_ce0() {
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state3.read()) ||
(esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_0, tmp_6_fu_216_p2.read())) ||
esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state5.read()) ||
(esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read()) &&
esl_seteq<1,1,1>(tmp_6_fu_216_p2.read(), ap_const_lv1_1)))) {
min_distances_V_ce0 = ap_const_logic_1;
} else {
min_distances_V_ce0 = ap_const_logic_0;
}
}
void update_knn::thread_min_distances_V_ce1() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state5.read())) {
min_distances_V_ce1 = ap_const_logic_1;
} else {
min_distances_V_ce1 = ap_const_logic_0;
}
}
void update_knn::thread_min_distances_V_d0() {
if (esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state5.read())) {
min_distances_V_d0 = min_distances_V_q0.read();
} else if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read()) &&
esl_seteq<1,1,1>(tmp_6_fu_216_p2.read(), ap_const_lv1_1))) {
min_distances_V_d0 = temp_min_distance_la_fu_40.read();
} else {
min_distances_V_d0 = (sc_lv<6>) ("XXXXXX");
}
}
void update_knn::thread_min_distances_V_d1() {
min_distances_V_d1 = min_distance_last_el_1_reg_285.read();
}
void update_knn::thread_min_distances_V_offs_1_fu_126_p1() {
min_distances_V_offs_1_fu_126_p1 = esl_zext<6,4>(min_distances_V_offset.read());
}
void update_knn::thread_min_distances_V_we0() {
if (((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state4.read()) &&
esl_seteq<1,1,1>(tmp_6_fu_216_p2.read(), ap_const_lv1_1)) ||
(esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state5.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_0, tmp_6_reg_291.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_1, tmp_9_fu_241_p2.read())))) {
min_distances_V_we0 = ap_const_logic_1;
} else {
min_distances_V_we0 = ap_const_logic_0;
}
}
void update_knn::thread_min_distances_V_we1() {
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state5.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_0, tmp_6_reg_291.read()) &&
esl_seteq<1,1,1>(ap_const_lv1_1, tmp_9_fu_241_p2.read()))) {
min_distances_V_we1 = ap_const_logic_1;
} else {
min_distances_V_we1 = ap_const_logic_0;
}
}
void update_knn::thread_r_V_fu_148_p2() {
r_V_fu_148_p2 = (train_inst_V_cast_fu_144_p1.read() ^ test_inst_V.read());
}
void update_knn::thread_tmp_1_cast_fu_177_p1() {
tmp_1_cast_fu_177_p1 = esl_zext<6,1>(tmp_5_fu_170_p3.read());
}
void update_knn::thread_tmp_1_fu_138_p2() {
tmp_1_fu_138_p2 = (!tmp_fu_130_p3.read().is_01() || !min_distances_V_offs_1_fu_126_p1.read().is_01())? sc_lv<6>(): (sc_biguint<6>(tmp_fu_130_p3.read()) - sc_biguint<6>(min_distances_V_offs_1_fu_126_p1.read()));
}
void update_knn::thread_tmp_2_cast_fu_207_p1() {
tmp_2_cast_fu_207_p1 = esl_sext<64,6>(tmp_2_fu_202_p2.read());
}
void update_knn::thread_tmp_2_fu_202_p2() {
tmp_2_fu_202_p2 = (!tmp_1_reg_246.read().is_01() || !tmp_5_cast_fu_198_p1.read().is_01())? sc_lv<6>(): (sc_biguint<6>(tmp_1_reg_246.read()) + sc_biguint<6>(tmp_5_cast_fu_198_p1.read()));
}
void update_knn::thread_tmp_3_cast_fu_231_p1() {
tmp_3_cast_fu_231_p1 = esl_sext<64,6>(tmp_3_fu_226_p2.read());
}
void update_knn::thread_tmp_3_fu_226_p2() {
tmp_3_fu_226_p2 = (!tmp_1_reg_246.read().is_01() || !tmp_8_cast_fu_222_p1.read().is_01())? sc_lv<6>(): (sc_biguint<6>(tmp_1_reg_246.read()) + sc_biguint<6>(tmp_8_cast_fu_222_p1.read()));
}
void update_knn::thread_tmp_4_fu_192_p2() {
tmp_4_fu_192_p2 = (!i1_reg_108.read().is_01() || !ap_const_lv2_0.is_01())? sc_lv<1>(): sc_lv<1>(i1_reg_108.read() == ap_const_lv2_0);
}
void update_knn::thread_tmp_5_cast_fu_198_p1() {
tmp_5_cast_fu_198_p1 = esl_zext<6,2>(i1_reg_108.read());
}
void update_knn::thread_tmp_5_fu_170_p3() {
tmp_5_fu_170_p3 = (!index_assign_cast2_fu_154_p1.read().is_01() || sc_biguint<32>(index_assign_cast2_fu_154_p1.read()).to_uint() >= 49)? sc_lv<1>(): r_V_reg_252.read().range(sc_biguint<32>(index_assign_cast2_fu_154_p1.read()).to_uint(), sc_biguint<32>(index_assign_cast2_fu_154_p1.read()).to_uint());
}
void update_knn::thread_tmp_6_fu_216_p2() {
tmp_6_fu_216_p2 = (!temp_min_distance_la_fu_40.read().is_01() || !min_distances_V_q0.read().is_01())? sc_lv<1>(): (sc_biguint<6>(temp_min_distance_la_fu_40.read()) < sc_biguint<6>(min_distances_V_q0.read()));
}
void update_knn::thread_tmp_8_cast_fu_222_p1() {
tmp_8_cast_fu_222_p1 = esl_zext<6,2>(grp_fu_120_p2.read());
}
void update_knn::thread_tmp_9_fu_241_p2() {
tmp_9_fu_241_p2 = (!min_distance_last_el_1_reg_285.read().is_01() || !min_distances_V_q0.read().is_01())? sc_lv<1>(): (sc_biguint<6>(min_distance_last_el_1_reg_285.read()) < sc_biguint<6>(min_distances_V_q0.read()));
}
void update_knn::thread_tmp_fu_130_p3() {
tmp_fu_130_p3 = esl_concat<4,2>(min_distances_V_offset.read(), ap_const_lv2_0);
}
void update_knn::thread_train_inst_V_cast_fu_144_p1() {
train_inst_V_cast_fu_144_p1 = esl_zext<49,48>(train_inst_V.read());
}
void update_knn::thread_ap_NS_fsm() {
switch (ap_CS_fsm.read().to_uint64()) {
case 1 :
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state1.read()) && esl_seteq<1,1,1>(ap_start.read(), ap_const_logic_1))) {
ap_NS_fsm = ap_ST_fsm_state2;
} else {
ap_NS_fsm = ap_ST_fsm_state1;
}
break;
case 2 :
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state2.read()) && esl_seteq<1,1,1>(exitcond_fu_158_p2.read(), ap_const_lv1_1))) {
ap_NS_fsm = ap_ST_fsm_state3;
} else {
ap_NS_fsm = ap_ST_fsm_state2;
}
break;
case 4 :
if ((esl_seteq<1,1,1>(ap_const_logic_1, ap_CS_fsm_state3.read()) && esl_seteq<1,1,1>(tmp_4_fu_192_p2.read(), ap_const_lv1_1))) {
ap_NS_fsm = ap_ST_fsm_state1;
} else {
ap_NS_fsm = ap_ST_fsm_state4;
}
break;
case 8 :
ap_NS_fsm = ap_ST_fsm_state5;
break;
case 16 :
ap_NS_fsm = ap_ST_fsm_state3;
break;
default :
ap_NS_fsm = "XXXXX";
break;
}
}
}
| [
"veranki@buffalo.edu"
] | veranki@buffalo.edu |
f32df982a8430b53dd6d1f59930e37ae72098d45 | 293a364657d1289c345b9384a936b6a1b07414a4 | /Lab 4/Lab04/Lab04.cpp | c04280bde215a58c4c232e72eb73fec1ecd02590 | [] | no_license | DArtagan/csci262 | b53364d00bb8230059d54d5ccbf4bb040cf3714b | 145d70a268544c1dfe57917873e7a42ce3ba1282 | refs/heads/master | 2021-01-01T16:34:22.462112 | 2012-04-08T19:45:32 | 2012-04-08T19:45:32 | 2,401,206 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 613 | cpp | // Lab04.cpp : main project file.
#include "Form1.h"
using namespace ProgramForm;
// Actions performed every time when the scene is redrawn
void Scene::Draw(Graphics^ g)
{
MyShape* shape;
for (list.begin(); !list.end(); ++list)
{
shape = *list;
shape->draw(g);
}
}
[STAThreadAttribute]
int main(array<System::String ^> ^args)
{
// Enabling Windows XP visual effects before any controls are created
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
// Create the main window and run it
Application::Run(gcnew Scene());
return 0;
}
| [
"worldwidewilly@comcast.net"
] | worldwidewilly@comcast.net |
d12a3e5829722350dee4df17b39c2b4e08c24cc5 | 6c751abe3bd08e5262c928f73b454cd7bb154eb4 | /src/qt/qrcodedialog.cpp | fecaab51bd042b9e3762562a17547c031dcb7f1d | [
"MIT"
] | permissive | tech001/chief | ced5a0efe54a94a05617a2f89017c213b00b5b9f | e0b0257980808e9d85730c2e94c777a12d1187b4 | refs/heads/master | 2020-03-10T02:03:08.520604 | 2016-12-25T20:39:25 | 2016-12-25T20:39:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,365 | cpp | #include "qrcodedialog.h"
#include "ui_qrcodedialog.h"
#include "bitcoinunits.h"
#include "dialogwindowflags.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include <QPixmap>
#include <QUrl>
#include <qrencode.h>
QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) :
QDialog(parent, DIALOGWINDOWHINTS),
ui(new Ui::QRCodeDialog),
model(0),
address(addr)
{
ui->setupUi(this);
setWindowTitle(QString("%1").arg(address));
ui->chkReqPayment->setVisible(enableReq);
ui->lblAmount->setVisible(enableReq);
ui->lnReqAmount->setVisible(enableReq);
ui->lnLabel->setText(label);
ui->btnSaveAs->setEnabled(false);
genCode();
}
QRCodeDialog::~QRCodeDialog()
{
delete ui;
}
void QRCodeDialog::setModel(OptionsModel *model)
{
this->model = model;
if (model)
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void QRCodeDialog::genCode()
{
QString uri = getURI();
if (uri != "")
{
ui->lblQRCode->setText("");
QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
if (!code)
{
ui->lblQRCode->setText(tr("Error encoding URI into QR Code."));
return;
}
myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
myImage.fill(0xffffff);
unsigned char *p = code->data;
for (int y = 0; y < code->width; y++)
{
for (int x = 0; x < code->width; x++)
{
myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
p++;
}
}
QRcode_free(code);
ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300));
ui->outUri->setPlainText(uri);
}
}
QString QRCodeDialog::getURI()
{
QString ret = QString("TheChiefCoin:%1").arg(address);
int paramCount = 0;
ui->outUri->clear();
if (ui->chkReqPayment->isChecked())
{
if (ui->lnReqAmount->validate())
{
// even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21)
ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value()));
paramCount++;
}
else
{
ui->btnSaveAs->setEnabled(false);
ui->lblQRCode->setText(tr("The entered amount is invalid, please check."));
return QString("");
}
}
if (!ui->lnLabel->text().isEmpty())
{
QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text()));
ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl);
paramCount++;
}
if (!ui->lnMessage->text().isEmpty())
{
QString msg(QUrl::toPercentEncoding(ui->lnMessage->text()));
ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg);
paramCount++;
}
// limit URI length to prevent a DoS against the QR-Code dialog
if (ret.length() > MAX_URI_LENGTH)
{
ui->btnSaveAs->setEnabled(false);
ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message."));
return QString("");
}
ui->btnSaveAs->setEnabled(true);
return ret;
}
void QRCodeDialog::on_lnReqAmount_textChanged()
{
genCode();
}
void QRCodeDialog::on_lnLabel_textChanged()
{
genCode();
}
void QRCodeDialog::on_lnMessage_textChanged()
{
genCode();
}
void QRCodeDialog::on_btnSaveAs_clicked()
{
QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)"));
if (!fn.isEmpty())
myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn);
}
void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked)
{
if (!fChecked)
// if chkReqPayment is not active, don't display lnReqAmount as invalid
ui->lnReqAmount->setValid(true);
genCode();
}
void QRCodeDialog::updateDisplayUnit()
{
if (model)
{
// Update lnReqAmount with the current unit
ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit());
}
}
| [
"chiefcoin@scryptmail.com"
] | chiefcoin@scryptmail.com |
7f6fee09bcd173f400c9a6b6dc311002e6fea9bd | 128774befeda73b0e27317f46c8f3cf94668071e | /hdu/HDU1041.cpp | 1715c055477d04446c5c806860e6c0dc44e53d4f | [] | no_license | toFindMore/oj-pratice | 5932903284d9d0c583f09aa62950aa911e0236ad | 9a714aeb6a117250a622d3efebbeb39b2737355f | refs/heads/master | 2023-04-13T19:35:14.302216 | 2021-04-09T13:49:58 | 2021-04-09T13:49:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,534 | cpp | //
// Created by 周健 on 2020-07-02.
//
#include <stdio.h>
#include <string.h>
char dp[1005][400];
char g[1005][400];
void add(char *num1, char *num2, char *res) {
int len1 = strlen(num1);
int len2 = strlen(num2);
if (len1 > len2) {
char *tmp = num1;
num1 = num2;
num2 = tmp;
len1 = len2;
len2 = strlen(num2);
}
int step = 0;
int cnt = -1;
for (int i = 0; i < len1; i++) {
int tmp = (num1[i] - '0') + (num2[i] - '0') + step;
if (tmp >= 10) {
step = 1;
tmp -= 10;
} else {
step = 0;
}
res[++cnt] = tmp + '0';
}
for (int i = len1; i < len2; i++) {
int tmp = (num2[i] - '0') + step;
if (tmp >= 10) {
step = 1;
tmp -= 10;
} else {
step = 0;
}
res[++cnt] = tmp + '0';
}
if (step == 1) {
res[++cnt] = '1';
}
res[++cnt] = '\0';
}
void init() {
g[0][0] = '1';
g[0][1] = '\0';
for (int i = 0; i < 999; i++) {
add(g[i], g[i], g[i + 1]);
}
dp[1][0] = '0';
dp[1][1] = '\0';
dp[2][0] = '1';
dp[2][1] = '\0';
for (int i = 3; i <= 1000; i++) {
add(dp[i - 2], g[i - 3], dp[i]);
}
}
int main() {
// 初始化
init();
// 计算
int num;
while (scanf("%d", &num) != EOF) {
for (int i = strlen(dp[num])-1; i >= 0; i--) {
printf("%c", dp[num][i]);
}
printf("\n");
}
return 0;
} | [
"17855824057@163.com"
] | 17855824057@163.com |
3328c7f357ee49da97804c124856370844b8c2d9 | ac95734ca5915ee50364faed9562ddcc9e815e9a | /src/Bindings/itkHDF5ImageIOJSBinding.cxx | 6e324910db1aaa40c236a3d81081fe66e2c5dbf9 | [
"Apache-2.0"
] | permissive | HastingsGreer/itk-js | 5b117a485ee0fab8e75009886bb5edc1ef9de2c1 | d714374a39c188b58a827881275f7c4abf4e2d7a | refs/heads/master | 2020-09-11T05:34:50.952167 | 2019-11-11T17:33:51 | 2019-11-11T17:33:51 | 221,955,696 | 0 | 0 | Apache-2.0 | 2019-11-15T15:52:42 | 2019-11-15T15:52:41 | null | UTF-8 | C++ | false | false | 4,621 | cxx | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include <emscripten.h>
#include <emscripten/bind.h>
#include "itkHDF5ImageIO.h"
#include "itkImageIOBaseJSBinding.h"
typedef itk::ImageIOBaseJSBinding< itk::HDF5ImageIO > HDF5ImageIOJSBindingType;
EMSCRIPTEN_BINDINGS(itk_hdf5_image_io_js_binding) {
emscripten::register_vector<double>("AxisDirectionType");
emscripten::enum_<HDF5ImageIOJSBindingType::IOPixelType>("IOPixelType")
.value("UNKNOWNPIXELTYPE", itk::ImageIOBase::UNKNOWNPIXELTYPE)
.value("SCALAR", itk::ImageIOBase::SCALAR)
.value("RGB", itk::ImageIOBase::RGB)
.value("RGBA", itk::ImageIOBase::RGBA)
.value("OFFSET", itk::ImageIOBase::OFFSET)
.value("VECTOR", itk::ImageIOBase::VECTOR)
.value("POINT", itk::ImageIOBase::POINT)
.value("COVARIANTVECTOR", itk::ImageIOBase::COVARIANTVECTOR)
.value("SYMMETRICSECONDRANKTENSOR", itk::ImageIOBase::SYMMETRICSECONDRANKTENSOR)
.value("DIFFUSIONTENSOR3D", itk::ImageIOBase::DIFFUSIONTENSOR3D)
.value("COMPLEX", itk::ImageIOBase::COMPLEX)
.value("FIXEDARRAY", itk::ImageIOBase::FIXEDARRAY)
.value("MATRIX", itk::ImageIOBase::MATRIX)
;
emscripten::enum_<HDF5ImageIOJSBindingType::IOComponentType>("IOComponentType")
.value("UNKNOWNCOMPONENTTYPE", itk::ImageIOBase::UNKNOWNCOMPONENTTYPE)
.value("UCHAR", itk::ImageIOBase::UCHAR)
.value("CHAR", itk::ImageIOBase::CHAR)
.value("USHORT", itk::ImageIOBase::USHORT)
.value("SHORT", itk::ImageIOBase::SHORT)
.value("UINT", itk::ImageIOBase::UINT)
.value("INT", itk::ImageIOBase::INT)
.value("ULONG", itk::ImageIOBase::ULONG)
.value("LONG", itk::ImageIOBase::LONG)
.value("ULONGLONG", itk::ImageIOBase::ULONGLONG)
.value("LONGLONG", itk::ImageIOBase::LONGLONG)
.value("FLOAT", itk::ImageIOBase::FLOAT)
.value("DOUBLE", itk::ImageIOBase::DOUBLE)
;
emscripten::class_<HDF5ImageIOJSBindingType>("ITKImageIO")
.constructor<>()
.function("SetNumberOfDimensions", &HDF5ImageIOJSBindingType::SetNumberOfDimensions)
.function("GetNumberOfDimensions", &HDF5ImageIOJSBindingType::GetNumberOfDimensions)
.function("SetFileName", &HDF5ImageIOJSBindingType::SetFileName)
.function("GetFileName", &HDF5ImageIOJSBindingType::GetFileName)
.function("CanReadFile", &HDF5ImageIOJSBindingType::CanReadFile)
.function("ReadImageInformation", &HDF5ImageIOJSBindingType::ReadImageInformation)
.function("WriteImageInformation", &HDF5ImageIOJSBindingType::WriteImageInformation)
.function("SetDimensions", &HDF5ImageIOJSBindingType::SetDimensions)
.function("GetDimensions", &HDF5ImageIOJSBindingType::GetDimensions)
.function("SetOrigin", &HDF5ImageIOJSBindingType::SetOrigin)
.function("GetOrigin", &HDF5ImageIOJSBindingType::GetOrigin)
.function("SetSpacing", &HDF5ImageIOJSBindingType::SetSpacing)
.function("GetSpacing", &HDF5ImageIOJSBindingType::GetSpacing)
.function("SetDirection", &HDF5ImageIOJSBindingType::SetDirection)
.function("GetDirection", &HDF5ImageIOJSBindingType::GetDirection)
.function("GetDefaultDirection", &HDF5ImageIOJSBindingType::GetDefaultDirection)
.function("SetPixelType", &HDF5ImageIOJSBindingType::SetPixelType)
.function("GetPixelType", &HDF5ImageIOJSBindingType::GetPixelType)
.function("SetComponentType", &HDF5ImageIOJSBindingType::SetComponentType)
.function("GetComponentType", &HDF5ImageIOJSBindingType::GetComponentType)
.function("GetImageSizeInPixels", &HDF5ImageIOJSBindingType::GetImageSizeInPixels)
.function("GetImageSizeInBytes", &HDF5ImageIOJSBindingType::GetImageSizeInBytes)
.function("GetImageSizeInComponents", &HDF5ImageIOJSBindingType::GetImageSizeInComponents)
.function("SetNumberOfComponents", &HDF5ImageIOJSBindingType::SetNumberOfComponents)
.function("GetNumberOfComponents", &HDF5ImageIOJSBindingType::GetNumberOfComponents)
.function("Read", &HDF5ImageIOJSBindingType::Read)
;
}
| [
"matt.mccormick@kitware.com"
] | matt.mccormick@kitware.com |
01a87b504e0f0771a04926bed894b4c04d35c5fa | 57f24846a3fa3670c8519af87e658eca120f6d23 | /pisoFoam-cavity/ras/cavityCoupledU/system/fvSchemes | 99fdb15e607f73e3a2b2122a319845fb692b2d10 | [] | no_license | bshambaugh/openfoam-experiments | 82adb4b7d7eb0ec454d6f98eba274b279a6597d8 | a1dd4012cb9791836da2f9298247ceba8701211c | refs/heads/master | 2021-07-14T05:53:07.275777 | 2019-02-15T19:37:28 | 2019-02-15T19:37:28 | 153,547,385 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,466 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 4.1 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "system";
object fvSchemes;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
ddtSchemes
{
default Euler;
}
gradSchemes
{
default Gauss linear;
}
divSchemes
{
default none;
div(phi,U) Gauss limitedLinearV 1;
div(phi,k) Gauss limitedLinear 1;
div(phi,epsilon) Gauss limitedLinear 1;
div(phi,R) Gauss limitedLinear 1;
div(R) Gauss linear;
div(phi,nuTilda) Gauss limitedLinear 1;
div((nuEff*dev2(T(grad(U))))) Gauss linear;
}
laplacianSchemes
{
default Gauss linear corrected;
}
interpolationSchemes
{
default linear;
}
snGradSchemes
{
default corrected;
}
// ************************************************************************* //
| [
"brent.shambaugh@gmail.com"
] | brent.shambaugh@gmail.com | |
db246c536b5e03ab1b60ad0ec61bded75cc59d88 | 98b1e51f55fe389379b0db00365402359309186a | /homework_7/problem_2/cavity/0.23/U | 87c9fc79ba39a7099a4b2f3021dd5d5f3f5906a3 | [] | no_license | taddyb/597-009 | f14c0e75a03ae2fd741905c4c0bc92440d10adda | 5f67e7d3910e3ec115fb3f3dc89a21dcc9a1b927 | refs/heads/main | 2023-01-23T08:14:47.028429 | 2020-12-03T13:24:27 | 2020-12-03T13:24:27 | 311,713,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,883 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 8
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volVectorField;
location "0.23";
object U;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 1 -1 0 0 0 0];
internalField nonuniform List<vector>
400
(
(0.000253411 -0.000250251 0)
(0.000141256 0.00011149 0)
(-0.00117672 0.000564508 0)
(-0.00348034 0.000884783 0)
(-0.00637601 0.00104546 0)
(-0.00946725 0.00106148 0)
(-0.0124 0.000957609 0)
(-0.0148814 0.00076025 0)
(-0.0166856 0.000494525 0)
(-0.0176542 0.00018452 0)
(-0.0176981 -0.000145227 0)
(-0.0168012 -0.000468247 0)
(-0.0150267 -0.000755227 0)
(-0.0125223 -0.000974028 0)
(-0.00952433 -0.00109093 0)
(-0.00635366 -0.00107376 0)
(-0.00339999 -0.000897927 0)
(-0.00108629 -0.000556286 0)
(0.000196319 -9.03788e-05 0)
(0.00026778 0.000262301 0)
(-7.74016e-05 -0.000169124 0)
(-0.00161109 0.0016446 0)
(-0.00569148 0.00361652 0)
(-0.011716 0.00503365 0)
(-0.0188878 0.00574187 0)
(-0.0263945 0.00575884 0)
(-0.0334613 0.00517045 0)
(-0.0394176 0.00409156 0)
(-0.0437338 0.00264704 0)
(-0.0460365 0.000966743 0)
(-0.0461189 -0.00081298 0)
(-0.0439514 -0.00254643 0)
(-0.0396923 -0.00407765 0)
(-0.0336952 -0.00524386 0)
(-0.0265076 -0.0058852 0)
(-0.0188505 -0.00586353 0)
(-0.0115642 -0.00509364 0)
(-0.00551217 -0.00358868 0)
(-0.00149281 -0.00155887 0)
(-4.25878e-05 0.000227345 0)
(-0.000528446 0.00109149 0)
(-0.00371042 0.00573505 0)
(-0.0105863 0.0102221 0)
(-0.0199869 0.0134045 0)
(-0.0307575 0.0149428 0)
(-0.0418124 0.0148353 0)
(-0.0521077 0.0132526 0)
(-0.0607302 0.0104538 0)
(-0.0669541 0.00674051 0)
(-0.0702668 0.00243843 0)
(-0.0703848 -0.0021059 0)
(-0.0672693 -0.0065238 0)
(-0.0611388 -0.0104267 0)
(-0.052477 -0.0134179 0)
(-0.0420279 -0.01512 0)
(-0.0307673 -0.0152222 0)
(-0.0198248 -0.013553 0)
(-0.0103613 -0.0101767 0)
(-0.00354775 -0.00554993 0)
(-0.00047674 -0.000948697 0)
(-0.000927962 0.00347905 0)
(-0.00569006 0.0122178 0)
(-0.0152981 0.019917 0)
(-0.0279103 0.0251919 0)
(-0.0419758 0.0275905 0)
(-0.0561664 0.0271311 0)
(-0.0692366 0.0241034 0)
(-0.080108 0.0189496 0)
(-0.0879289 0.0121929 0)
(-0.0920988 0.00440431 0)
(-0.0922836 -0.00380679 0)
(-0.0884313 -0.0117935 0)
(-0.0807879 -0.0188775 0)
(-0.0699082 -0.0243705 0)
(-0.0566574 -0.0276212 0)
(-0.042186 -0.0280954 0)
(-0.0278508 -0.025492 0)
(-0.0150905 -0.0198873 0)
(-0.00550384 -0.0119251 0)
(-0.000861397 -0.00322421 0)
(-0.00127859 0.00687613 0)
(-0.00753428 0.0209487 0)
(-0.0198004 0.0325027 0)
(-0.0355273 0.0400938 0)
(-0.0527324 0.0432802 0)
(-0.0698441 0.0421831 0)
(-0.085446 0.0372691 0)
(-0.0983407 0.0292066 0)
(-0.107598 0.0187733 0)
(-0.112566 0.00681261 0)
(-0.112875 -0.00577857 0)
(-0.108453 -0.0180501 0)
(-0.0995431 -0.0290044 0)
(-0.0867227 -0.0376239 0)
(-0.0709223 -0.0429352 0)
(-0.0534201 -0.044119 0)
(-0.0357778 -0.0406697 0)
(-0.0197313 -0.0325854 0)
(-0.0073691 -0.0205861 0)
(-0.00120341 -0.00649675 0)
(-0.00160715 0.0112129 0)
(-0.00931613 0.0318671 0)
(-0.0242046 0.0479408 0)
(-0.0429946 0.0580587 0)
(-0.0632454 0.0619231 0)
(-0.0831378 0.0598677 0)
(-0.101106 0.0526166 0)
(-0.115872 0.0411169 0)
(-0.126466 0.0264316 0)
(-0.132214 0.00969138 0)
(-0.132727 -0.00791379 0)
(-0.127901 -0.0251257 0)
(-0.117946 -0.0406153 0)
(-0.103416 -0.0530071 0)
(-0.0852546 -0.0609525 0)
(-0.0648247 -0.0632661 0)
(-0.0438781 -0.0591292 0)
(-0.0244735 -0.048334 0)
(-0.00925266 -0.0315508 0)
(-0.00153745 -0.0107262 0)
(-0.00193969 0.0164733 0)
(-0.0111194 0.0449641 0)
(-0.0286459 0.0662187 0)
(-0.050472 0.079042 0)
(-0.0736737 0.0834281 0)
(-0.0961892 0.0800568 0)
(-0.116334 0.0700094 0)
(-0.132795 0.0545734 0)
(-0.14461 0.0351248 0)
(-0.151119 0.0130828 0)
(-0.151927 -0.0100833 0)
(-0.146894 -0.0328245 0)
(-0.136162 -0.0534873 0)
(-0.120206 -0.0703212 0)
(-0.0999188 -0.0815477 0)
(-0.0766908 -0.0855147 0)
(-0.0524329 -0.080947 0)
(-0.0295407 -0.0672634 0)
(-0.011282 -0.0449305 0)
(-0.00189977 -0.0159483 0)
(-0.00229973 0.0226901 0)
(-0.0130235 0.0602884 0)
(-0.033247 0.0873457 0)
(-0.0580731 0.102975 0)
(-0.0840651 0.107643 0)
(-0.108941 0.10254 0)
(-0.130953 0.0892262 0)
(-0.148818 0.0693972 0)
(-0.161648 0.0447634 0)
(-0.168849 0.0170176 0)
(-0.170044 -0.0121297 0)
(-0.165053 -0.0408835 0)
(-0.153913 -0.0672996 0)
(-0.136955 -0.0892545 0)
(-0.114931 -0.104491 0)
(-0.0891667 -0.110775 0)
(-0.0616644 -0.106192 0)
(-0.0351447 -0.0895628 0)
(-0.0135844 -0.0609383 0)
(-0.00232607 -0.0222734 0)
(-0.00271144 0.0299413 0)
(-0.0151069 0.0779421 0)
(-0.0381121 0.111335 0)
(-0.0658438 0.129726 0)
(-0.0943202 0.134292 0)
(-0.12109 0.12695 0)
(-0.144433 0.109882 0)
(-0.163201 0.0852663 0)
(-0.176674 0.0551578 0)
(-0.184393 0.0214844 0)
(-0.186044 -0.0138704 0)
(-0.181409 -0.0489457 0)
(-0.170383 -0.0815768 0)
(-0.153071 -0.109303 0)
(-0.129962 -0.129357 0)
(-0.102179 -0.138804 0)
(-0.0716849 -0.134864 0)
(-0.0414643 -0.11545 0)
(-0.016287 -0.0798823 0)
(-0.00285449 -0.0298847 0)
(-0.00320759 0.0383534 0)
(-0.0174658 0.0980737 0)
(-0.0433401 0.138167 0)
(-0.073755 0.15902 0)
(-0.104158 0.162874 0)
(-0.132029 0.152647 0)
(-0.155822 0.13132 0)
(-0.174674 0.101624 0)
(-0.188163 0.0659476 0)
(-0.196063 0.0263867 0)
(-0.198181 -0.0151081 0)
(-0.194278 -0.0565338 0)
(-0.184077 -0.0956244 0)
(-0.167362 -0.129667 0)
(-0.144212 -0.155398 0)
(-0.115336 -0.169071 0)
(-0.0824436 -0.166778 0)
(-0.0486348 -0.145103 0)
(-0.0195282 -0.102146 0)
(-0.00353346 -0.0390418 0)
(-0.00384405 0.0481224 0)
(-0.0202466 0.120878 0)
(-0.0490477 0.167729 0)
(-0.0816882 0.19034 0)
(-0.113055 0.19253 0)
(-0.140749 0.178589 0)
(-0.163625 0.15249 0)
(-0.181313 0.117576 0)
(-0.19385 0.0765248 0)
(-0.201365 0.0314914 0)
(-0.203861 -0.0156543 0)
(-0.201113 -0.0630389 0)
(-0.192651 -0.108473 0)
(-0.177859 -0.149148 0)
(-0.156225 -0.18139 0)
(-0.127781 -0.20058 0)
(-0.0936448 -0.201399 0)
(-0.0567333 -0.178552 0)
(-0.0234799 -0.128158 0)
(-0.00443553 -0.0500988 0)
(-0.00472562 0.0595653 0)
(-0.0236959 0.146602 0)
(-0.0553859 0.199735 0)
(-0.0893813 0.222766 0)
(-0.120129 0.221866 0)
(-0.145684 0.203163 0)
(-0.165641 0.171819 0)
(-0.180383 0.131794 0)
(-0.190593 0.08596 0)
(-0.196876 0.0363735 0)
(-0.199514 -0.0153664 0)
(-0.198347 -0.0677321 0)
(-0.192728 -0.11885 0)
(-0.181583 -0.166057 0)
(-0.163652 -0.205464 0)
(-0.137972 -0.231636 0)
(-0.104599 -0.237601 0)
(-0.0657352 -0.215504 0)
(-0.0283783 -0.158353 0)
(-0.00568218 -0.0635467 0)
(-0.00605195 0.0732233 0)
(-0.0282277 0.17555 0)
(-0.0625131 0.233552 0)
(-0.0962644 0.254724 0)
(-0.123867 0.248708 0)
(-0.144411 0.224004 0)
(-0.158686 0.187088 0)
(-0.168125 0.142447 0)
(-0.17422 0.0929597 0)
(-0.178138 0.0403762 0)
(-0.180504 -0.0141949 0)
(-0.181284 -0.0698115 0)
(-0.179712 -0.125196 0)
(-0.174284 -0.178161 0)
(-0.162906 -0.224951 0)
(-0.143325 -0.259565 0)
(-0.113943 -0.273307 0)
(-0.0753961 -0.255048 0)
(-0.0345574 -0.193077 0)
(-0.00748648 -0.0800992 0)
(-0.0081925 0.0900424 0)
(-0.0344849 0.20801 0)
(-0.0704175 0.267868 0)
(-0.101032 0.283587 0)
(-0.121587 0.269791 0)
(-0.133124 0.237821 0)
(-0.138182 0.195387 0)
(-0.139484 0.14722 0)
(-0.139391 0.095901 0)
(-0.139619 0.0426168 0)
(-0.141133 -0.0122301 0)
(-0.144078 -0.068499 0)
(-0.147689 -0.125781 0)
(-0.150187 -0.182753 0)
(-0.148735 -0.236305 0)
(-0.139654 -0.280427 0)
(-0.119102 -0.305006 0)
(-0.08494 -0.295142 0)
(-0.042442 -0.232366 0)
(-0.0102163 -0.100832 0)
(-0.0117679 0.111633 0)
(-0.0432619 0.243953 0)
(-0.0783027 0.300022 0)
(-0.100637 0.305077 0)
(-0.108364 0.280444 0)
(-0.105748 0.240367 0)
(-0.0975494 0.193267 0)
(-0.0877935 0.143538 0)
(-0.0795254 0.093029 0)
(-0.0748107 0.0420925 0)
(-0.0748282 -0.00972672 0)
(-0.0799149 -0.0632048 0)
(-0.089485 -0.11898 0)
(-0.101808 -0.176944 0)
(-0.113702 -0.23527 0)
(-0.120317 -0.288866 0)
(-0.115271 -0.327181 0)
(-0.092271 -0.331781 0)
(-0.0523174 -0.275394 0)
(-0.0144306 -0.127344 0)
(-0.0175497 0.140657 0)
(-0.0547665 0.28214 0)
(-0.082791 0.32471 0)
(-0.0880887 0.312463 0)
(-0.0751206 0.274444 0)
(-0.0526068 0.226759 0)
(-0.0274777 0.177278 0)
(-0.00453653 0.129127 0)
(0.0130749 0.0829074 0)
(0.023415 0.0379449 0)
(0.0253736 -0.00707211 0)
(0.0184835 -0.053754 0)
(0.00295791 -0.103745 0)
(-0.020016 -0.158311 0)
(-0.0477015 -0.217491 0)
(-0.0749966 -0.278349 0)
(-0.0935547 -0.33178 0)
(-0.0920682 -0.357673 0)
(-0.0632823 -0.319288 0)
(-0.0206339 -0.161971 0)
(-0.02545 0.18171 0)
(-0.065776 0.317769 0)
(-0.0733367 0.331357 0)
(-0.0480837 0.295394 0)
(-0.00558828 0.244204 0)
(0.0412051 0.192372 0)
(0.0846364 0.14504 0)
(0.120517 0.102966 0)
(0.146681 0.0651342 0)
(0.162025 0.02989 0)
(0.165919 -0.00467072 0)
(0.157914 -0.0406255 0)
(0.137712 -0.0802418 0)
(0.105423 -0.125912 0)
(0.0622479 -0.179719 0)
(0.0117949 -0.242013 0)
(-0.0378373 -0.307871 0)
(-0.0716836 -0.360137 0)
(-0.0700571 -0.356604 0)
(-0.0279126 -0.208374 0)
(-0.0296491 0.239176 0)
(-0.060842 0.335766 0)
(-0.0219447 0.3005 0)
(0.0505373 0.240124 0)
(0.127565 0.182945 0)
(0.196997 0.135385 0)
(0.254324 0.097395 0)
(0.298235 0.0668479 0)
(0.328808 0.0413533 0)
(0.346449 0.0187778 0)
(0.351358 -0.00279368 0)
(0.343285 -0.0252635 0)
(0.321453 -0.0507851 0)
(0.284628 -0.0820447 0)
(0.23156 -0.122442 0)
(0.162172 -0.175665 0)
(0.0798947 -0.243428 0)
(-0.00319319 -0.319133 0)
(-0.0546708 -0.36861 0)
(-0.0284596 -0.267617 0)
(0.00808317 0.281862 0)
(0.019783 0.294972 0)
(0.139065 0.210972 0)
(0.264458 0.143476 0)
(0.364363 0.0971843 0)
(0.440358 0.0657757 0)
(0.496734 0.0442359 0)
(0.536864 0.0288848 0)
(0.563435 0.0171981 0)
(0.578293 0.00748452 0)
(0.582368 -0.00149389 0)
(0.575684 -0.0108446 0)
(0.557298 -0.021846 0)
(0.525126 -0.0363336 0)
(0.475769 -0.0572581 0)
(0.404532 -0.0893826 0)
(0.305172 -0.13974 0)
(0.173415 -0.216385 0)
(0.0411713 -0.311654 0)
(0.0184301 -0.299995 0)
(0.299604 0.146091 0)
(0.396272 0.127503 0)
(0.55742 0.0760894 0)
(0.674487 0.043723 0)
(0.743887 0.0255718 0)
(0.787151 0.0152419 0)
(0.815482 0.00921205 0)
(0.833951 0.00550919 0)
(0.845381 0.00302705 0)
(0.851367 0.00114932 0)
(0.852661 -0.000499316 0)
(0.849378 -0.00221492 0)
(0.840996 -0.00433835 0)
(0.826137 -0.00742383 0)
(0.802075 -0.012532 0)
(0.763619 -0.0217726 0)
(0.699107 -0.0392827 0)
(0.583952 -0.07266 0)
(0.415827 -0.127868 0)
(0.308819 -0.149468 0)
)
;
boundaryField
{
movingWall
{
type fixedValue;
value uniform (1 0 0);
}
fixedWalls
{
type noSlip;
}
frontAndBack
{
type empty;
}
}
// ************************************************************************* //
| [
"tbindas@pop-os.localdomain"
] | tbindas@pop-os.localdomain | |
eeac27c995d186962a6e95cc2971caffe192d5b5 | 23521cb57ab92600ad9fe7945229f9c4a789b3d5 | /admin_ui/src/ros_task.cpp | 5fe943b4a342a3e031f2c33312734cd5d02f9660 | [] | no_license | benthebear93/Ui_donation_robot_2019Crashlab | d3ef834c3000c444217ae6746037d00bad314d82 | 39bd23ee0b040cc6850879da5ce674d530b05faf | refs/heads/master | 2021-06-30T04:15:50.382565 | 2021-02-26T06:35:21 | 2021-02-26T06:35:21 | 223,959,570 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,005 | cpp |
//task_node
#include <ros/ros.h>
#include <ros/network.h>
#include <std_msgs/Int32.h>
#include "admin_ui/ros_task.h"
#include <iostream>
using namespace std;
namespace admin_ui{
int psb_l_val = 0;
int psb_m_val = 0;
int psb_r_val = 0;
// psd value for each psd sensors
// need to be used in admin_ui.cpp, use the 'extern'
void callback_psdl(const std_msgs::Int32::ConstPtr& msg)
{
psb_l_val = msg->data;
}
void callback_psdm(const std_msgs::Int32::ConstPtr& msg)
{
psb_m_val = msg->data;
}
void callback_psdr(const std_msgs::Int32::ConstPtr& msg)
{
psb_r_val = msg->data;
}
ros_task::ros_task(int argc, char** argv) :
init_argc(argc),
init_argv(argv),
isConnected(false)
{
//need space
}
ros_task::~ros_task()
{
if(ros::isStarted())
{
ros::shutdown(); // explicitly needed since we use ros::start();
ros::waitForShutdown();
}
delete nh; // deallocate ndoe handle
wait();
}
bool ros_task::init()
{
//cout <<"init is here" <<endl;
ros::init(init_argc,init_argv,"admin_ui");
if ( ! ros::master::check() )
{
return false;
}
init_nh();
ros::start(); // explicitly needed since our nodehandle is going out of scope.
start();
return true;
}
void ros_task::init_nh()
{
nh = new ros::NodeHandle("admin_ui");
pub_ML = nh->advertise<std_msgs::Int32>("/admin_ui/test_ml", 10);
pub_M_both = nh->advertise<std_msgs::Int32>("/admin_ui/test_mboth", 10);
pub_MR = nh->advertise<std_msgs::Int32>("/admin_ui/test_mr", 10);
pub_M_stop = nh->advertise<std_msgs::Int32>("/admin_ui/test_stop", 10);
pub_Sound = nh->advertise<std_msgs::Int32>("/admin_ui/test_sound", 10);
end_w1_open = nh->advertise<std_msgs::Int32>("/admin_ui/test_end", 10);
psd_l =nh->subscribe("/psd_l", 10, callback_psdl);
psd_m =nh->subscribe("/psd_m", 10, callback_psdm);
psd_r =nh->subscribe("/psd_r", 10, callback_psdr);
isConnected = true;
}
void ros_task::run()
{
ros::Rate loop_rate(10);
while(ros::ok())
{
Q_EMIT sub_psd_l();
Q_EMIT sub_psd_m();
Q_EMIT sub_psd_r();
ros::spinOnce();
loop_rate.sleep();
}
std::cout << "Ros shutdown, proceeding to close the gui." << std::endl;
}
void ros_task::send_Test_ML()
{
pub_ML.publish(Test_ML);
}
void ros_task::send_Test_M_both()
{
pub_M_both.publish(Test_M_both);
}
void ros_task::send_Test_MR()
{
pub_MR.publish(Test_MR);
}
void ros_task::send_Test_M_stop()
{
pub_M_stop.publish(Test_M_stop);
}
void ros_task::send_Test_Sound()
{
pub_Sound.publish(Test_Sound);
}
void ros_task::send_Test_end()
{
end_w1_open.publish(Test_End);
}
}// namespace
| [
"nswve@naver.com"
] | nswve@naver.com |
daf1ab5cc55d7b59a747b7c3b2a575cb400d3820 | 3d07ae0b0ea8061af97e067c61fc26c63f21927f | /oneflow/user/ops/one_hot_op.cpp | e0b9355aaa42090af287a8661f3ead361bd93021 | [
"Apache-2.0"
] | permissive | maybemind/oneflow | 2a64843feb2c1169d9a2c4230f2e786f1f9cd4a0 | 95767e1e28b666e59d7b31018ffbcf30ab5b8db9 | refs/heads/master | 2023-04-06T04:45:54.957527 | 2021-04-12T11:29:43 | 2021-04-12T11:29:43 | 309,308,152 | 0 | 0 | Apache-2.0 | 2021-04-12T11:29:44 | 2020-11-02T08:43:47 | null | UTF-8 | C++ | false | false | 2,890 | cpp | /*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "oneflow/core/framework/framework.h"
#include "oneflow/core/common/balanced_splitter.h"
namespace oneflow {
REGISTER_USER_OP("one_hot")
.Input("indices")
.Output("out")
.Attr<int64_t>("depth")
.Attr<double>("floating_on_value")
.Attr<int64_t>("integer_on_value")
.Attr<double>("floating_off_value")
.Attr<int64_t>("integer_off_value")
.Attr<DataType>("dtype")
.SetTensorDescInferFn([](user_op::InferContext* ctx) -> Maybe<void> {
const int64_t depth = ctx->Attr<int64_t>("depth");
CHECK_GT_OR_RETURN(depth, 0);
const user_op::TensorDesc* indices_desc = ctx->TensorDesc4ArgNameAndIndex("indices", 0);
CHECK_GT_OR_RETURN(indices_desc->shape().NumAxes(), 0);
user_op::TensorDesc* out_desc = ctx->TensorDesc4ArgNameAndIndex("out", 0);
*out_desc->mut_is_dynamic() = indices_desc->is_dynamic();
DimVector dim_vec = indices_desc->shape().dim_vec();
dim_vec.push_back(depth);
*out_desc->mut_shape() = Shape(dim_vec);
return Maybe<void>::Ok();
})
.SetInputArgModifyFn([](user_op::GetInputArgModifier GetInputArgModifierFn,
const user_op::UserOpConfWrapper&) {
user_op::InputArgModifier* indices_modifier = GetInputArgModifierFn("indices", 0);
CHECK(indices_modifier != nullptr);
indices_modifier->set_requires_grad(false);
})
.SetGetSbpFn([](user_op::SbpContext* ctx) -> Maybe<void> {
const user_op::TensorDesc& indices_tensor =
ctx->LogicalTensorDesc4InputArgNameAndIndex("indices", 0);
FOR_RANGE(int64_t, i, 0, indices_tensor.shape().NumAxes()) {
ctx->NewBuilder()
.Split(user_op::OpArg("indices", 0), i)
.Split(user_op::OpArg("out", 0), i)
.Build();
}
return Maybe<void>::Ok();
})
.SetInferDataTypeFn([](user_op::InferContext* ctx) -> Maybe<void> {
const user_op::TensorDesc* indices_desc = ctx->TensorDesc4ArgNameAndIndex("indices", 0);
CHECK_OR_RETURN(IsIndexDataType(indices_desc->data_type()));
user_op::TensorDesc* out_desc = ctx->TensorDesc4ArgNameAndIndex("out", 0);
DataType dtype = ctx->Attr<DataType>("dtype");
*out_desc->mut_data_type() = dtype;
return Maybe<void>::Ok();
});
} // namespace oneflow
| [
"noreply@github.com"
] | noreply@github.com |
fe950b2775f936e6b6b33d66502dc91d8b3324de | 0805b803ad608e07810af954048359c927294a0e | /bvheditor/Wml/Source/ImageAnalysis/WmlBinary3D.cpp | 9dfef4036bbe5821278192e4124ba6bd529ca8c3 | [] | no_license | yiyongc/BvhEditor | 005feb3f44537544d66d54ab419186b73e184f57 | b512e240bc7b1ad5f54fd2e77f0a3194302aab2d | refs/heads/master | 2023-03-15T14:19:31.292081 | 2017-03-30T17:27:17 | 2017-03-30T17:27:17 | 66,918,016 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,731 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2004. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlBinary3D.h"
using namespace Wml;
//----------------------------------------------------------------------------
Binary3D::Binary3D (int iXBound, int iYBound, int iZBound, Eint* atData)
:
ImageInt3D(iXBound,iYBound,iZBound,atData)
{
}
//----------------------------------------------------------------------------
Binary3D::Binary3D (const Binary3D& rkImage)
:
ImageInt3D(rkImage)
{
}
//----------------------------------------------------------------------------
Binary3D::Binary3D (const char* acFilename)
:
ImageInt3D(acFilename)
{
}
//----------------------------------------------------------------------------
void Binary3D::GetComponents (int& riQuantity, ImageInt3D& rkComponents) const
{
// Create a temporary copy of image to store intermediate information
// during component labeling. The original image is embedded in an image
// with two more slices, two more rows, and two more columns so that the
// image boundary pixels are properly handled. This copy is initially
// zero.
ImageInt3D kTemp(GetBound(0)+2,GetBound(1)+2,GetBound(2)+2);
int iX, iY, iZ, iXP, iYP, iZP;
for (iZ = 0, iZP = 1; iZ < GetBound(2); iZ++, iZP++)
{
for (iY = 0, iYP = 1; iY < GetBound(1); iY++, iYP++)
{
for (iX = 0, iXP = 1; iX < GetBound(0); iX++, iXP++)
kTemp(iXP,iYP,iZP) = ( (*this)(iX,iY,iZ) ? 1 : 0 );
}
}
// label connected components in 1D array
int i, iComponent = 0;
for (i = 0; i < kTemp.GetQuantity(); i++)
{
if ( kTemp[i] )
{
iComponent++;
while ( kTemp[i] )
{
// loop terminates since kTemp is zero on its boundaries
kTemp[i++] = iComponent;
}
}
}
if ( iComponent == 0 )
{
// input image is identically zero
riQuantity = 0;
rkComponents = (Eint)0;
return;
}
// associative memory for merging
int* aiAssoc = new int[iComponent+1];
for (i = 0; i < iComponent + 1; i++)
aiAssoc[i] = i;
// Merge equivalent components. Voxel (x,y,z) has previous neighbors
// (x-1,y-1,z-1), (x,y-1,z-1), (x+1,y-1,z-1), (x-1,y,z-1), (x,y,z-1),
// (x+1,y,z-1), (x-1,y+1,z-1), (x,y+1,z-1), (x+1,y+1,z-1), (x-1,y-1,z),
// (x,y-1,z), (x+1,y-1,z), (x-1,y,z) [13 of 26 voxels visited before
// (x,y,z) is visited, get component labels from them].
for (iZ = 1; iZ < kTemp.GetBound(2)-1; iZ++)
{
for (iY = 1; iY < kTemp.GetBound(1)-1; iY++)
{
for (iX = 1; iX < kTemp.GetBound(0)-1; iX++)
{
int iValue = kTemp(iX,iY,iZ);
if ( iValue > 0 )
{
AddToAssociative(iValue,kTemp(iX-1,iY-1,iZ-1),aiAssoc);
AddToAssociative(iValue,kTemp(iX, iY-1,iZ-1),aiAssoc);
AddToAssociative(iValue,kTemp(iX+1,iY-1,iZ-1),aiAssoc);
AddToAssociative(iValue,kTemp(iX-1,iY ,iZ-1),aiAssoc);
AddToAssociative(iValue,kTemp(iX ,iY ,iZ-1),aiAssoc);
AddToAssociative(iValue,kTemp(iX+1,iY ,iZ-1),aiAssoc);
AddToAssociative(iValue,kTemp(iX-1,iY+1,iZ-1),aiAssoc);
AddToAssociative(iValue,kTemp(iX ,iY+1,iZ-1),aiAssoc);
AddToAssociative(iValue,kTemp(iX+1,iY+1,iZ-1),aiAssoc);
AddToAssociative(iValue,kTemp(iX-1,iY-1,iZ ),aiAssoc);
AddToAssociative(iValue,kTemp(iX ,iY-1,iZ ),aiAssoc);
AddToAssociative(iValue,kTemp(iX+1,iY-1,iZ ),aiAssoc);
AddToAssociative(iValue,kTemp(iX-1,iY ,iZ ),aiAssoc);
}
}
}
}
// replace each cycle of equivalent labels by a single label
riQuantity = 0;
for (i = 1; i <= iComponent; i++)
{
if ( i <= aiAssoc[i] )
{
riQuantity++;
int iCurrent = i;
while ( aiAssoc[iCurrent] != i )
{
int iNext = aiAssoc[iCurrent];
aiAssoc[iCurrent] = riQuantity;
iCurrent = iNext;
}
aiAssoc[iCurrent] = riQuantity;
}
}
// pack a relabeled image in smaller size output
for (iZ = 0, iZP = 1; iZ < rkComponents.GetBound(2); iZ++, iZP++)
{
for (iY = 0, iYP = 1; iY < rkComponents.GetBound(1); iY++, iYP++)
{
for (iX = 0, iXP = 1; iX < rkComponents.GetBound(0); iX++, iXP++)
rkComponents(iX,iY,iZ) = aiAssoc[kTemp(iXP,iYP,iZP)];
}
}
delete[] aiAssoc;
}
//----------------------------------------------------------------------------
void Binary3D::AddToAssociative (int i0, int i1, int* aiAssoc) const
{
// Adjacent voxels have labels i0 and i1. Associate them so that they
// represent the same component. [assert: i0 > 0]
if ( i1 == 0 || i1 == i0 )
return;
int iSearch = i1;
do
{
iSearch = aiAssoc[iSearch];
}
while ( iSearch != i1 && iSearch != i0 );
if ( iSearch == i1 )
{
int iSave = aiAssoc[i0];
aiAssoc[i0] = aiAssoc[i1];
aiAssoc[i1] = iSave;
}
}
//----------------------------------------------------------------------------
| [
"yiyong.cyy@gmail.com"
] | yiyong.cyy@gmail.com |
f4c7ee61bdce1c58dcc988ca229806af52988558 | 6f05f7d5a67b6bb87956a22b988067ec772ba966 | /data/train/cpp/623539f99fc206e52fcbdcca7cc093b21233b107Stream.cpp | 623539f99fc206e52fcbdcca7cc093b21233b107 | [
"MIT"
] | permissive | harshp8l/deep-learning-lang-detection | 93b6d24a38081597c610ecf9b1f3b92c7d669be5 | 2a54293181c1c2b1a2b840ddee4d4d80177efb33 | refs/heads/master | 2020-04-07T18:07:00.697994 | 2018-11-29T23:21:23 | 2018-11-29T23:21:23 | 158,597,498 | 0 | 0 | MIT | 2018-11-21T19:36:42 | 2018-11-21T19:36:41 | null | UTF-8 | C++ | false | false | 1,364 | cpp | #include <cudacpp/Stream.h>
#include <cuda.h>
#include <cuda_runtime.h>
namespace cudacpp
{
/// Constructor for stream 0 ***ONLY***.
Stream::Stream(const int ignored){}
/// Disable the copy constructor.
//inline Stream::Stream(const Stream & rhs) { }
/// Disable the operator =
//inline Stream::Stream & operator = (const Stream & rhs) { return * this; }
/// The default constructor. Simply calls cudaStreamCreate.
Stream::Stream()
{
//cudaStreamCreate(&handle);
}
/// Simply calls cudaStreamDestroy on the native handle.
Stream::~Stream()
{
//cudaStreamDestroy(handle);
}
/// Simply calls cudaStreamSynchronize on the native handle.
void Stream::sync()
{
//cudaStreamSynchronize(handle);
}
/*
* Simply calls cudaStreamQuery on the native handle.
*
* @return True iff cudaStreamQuery(handle) == cudaSuccess, or in other
* words, if all commands in the stream have executed successfully.
*/
bool Stream::query()
{
return false;
//return (cudaStreamQuery(handle) == cudaSuccess);
}//bool
Stream* Stream::nullStream = new Stream();
/*
* @return The native stream handle. Public as a side-effect of me hating
* the friend keyword.
*/
int* Stream::getHandle(){
return 0;//handle;
}
}
| [
"aliostad+github@gmail.com"
] | aliostad+github@gmail.com |
23e0388dbacc910006289105f97368a790044e1d | 6d3bb23428c196a3cf63efcf8d9654a0cc32adb6 | /Lightoj-1231 - Coin Change (I) .cpp | 4cf2cbdc7cd83d6d0c00b697d582f79093c22a72 | [] | no_license | antimatter007/DP-Problem-Solution | 2d1cd9773e4c646f318401df78bcd7ddf09b4dde | 98e120c73137c5b62ee19ed8d9a91ebbed4a0efb | refs/heads/master | 2023-04-09T12:02:24.360436 | 2021-03-10T20:49:44 | 2021-03-10T20:49:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,238 | cpp | #include<bits/stdc++.h>
using namespace std;
const long long mod = 100000007;
/// there are many recursion ways to solve this ,but I like dp by bottom-up approach
/// bottom- up approach
int main()
{
int tc;
scanf("%d",&tc);
int caso=0;
while(tc--)
{
caso++;
int n,k;
scanf("%d%d",&n,&k);
int arr[n];
int amount[n];
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
for(int j=0;j<n;j++)
{
scanf("%d",&amount[j]);
}
long long dp[n+1][k+1];
memset(dp,0,sizeof(dp));
dp[0][0]=1;
for(int i=0;i<n;i++)/// we can use n types of coins
{
for(int j=0;j<=k;j++)/// build k , check by making sub-sum
{
for(int times=0;times<=amount[i];times++)
{
if(times*arr[i]<=j)/// is it possible to make j with times*arr[i]?
{
dp[i+1][j]=dp[i+1][j]+dp[i][j-(times*arr[i])]%mod;
}
}
}
}
printf("Case %d: %lld\n",caso,dp[n][k]);/// by using n types of coins how many ways to make k
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
e8f1deccdd57b7530c0e7149cc4d2c870fc0292a | 0ae32e99bcc4662d5cb6e30f17a1fb6579f4903e | /cs507-spring2015-assignment4/Expr_Parser.cpp | 0224354eae9e389a6640e87784db3634c0ba005c | [] | no_license | ybanda/Calculator | 4c54f4fe92431f66b4ce5c0b449ce0f2f9cf0762 | d614bf06b24c6f67305d89f280e855621974d927 | refs/heads/master | 2021-01-10T01:15:01.545181 | 2016-01-11T20:41:56 | 2016-01-11T20:41:56 | 49,452,781 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,061 | cpp | // $Id: Expr_Parser.cpp 2015-03-25 banday $
// Honor Pledge:
//
// I pledge that I have neither given nor received any help
// on this assignment.
#include "Expr_Parser.h"
#include "Eval_Expr_Tree.h"
//
//Default Constructor Initialisation
//
Expr_Parser::Expr_Parser(void)
{
}
//
//Default Constructor Initialisation
//
Expr_Parser::~Expr_Parser(void)
{
}
//
//Method to parse the expression
//
bool Expr_Parser::parse_expr(std::string & infix, Expr_Builder & b, Tree_Factory_Builder & factory)
{
std::istringstream input(infix);
Expr_Node * node = 0;
std::string token;
int flag_Open = 0;
int flag_Close = 0;
//Starting a new Expression
b.build_expression();
while (!input.eof ())
{
input >> token;
if (token == "+")
b.build_add_operand(factory);
else if (token=="-")
b.build_subtract_operand(factory);
else if (token =="*")
b.build_multiply_operand(factory);
else if (token =="/")
b.build_divide_operand(factory);
else if (token =="%")
b.build_modulus_operand(factory);
else if(token.length()==1 && (std::isdigit(token[0])) )
b.build_number(factory,atoi(token.c_str()));
else if(token.length()>1 )
{
size_t index = 0;
if(token[0]=='-')
index = 1;
for(; index<token.length(); ++index)
{
if(!std::isdigit(token[index]))
{
std::cout<<"Invalid input Given ::"<<std::endl;
return false;
}
}
b.build_number(factory,atoi(token.c_str()));
}
else if (token=="(")
{
std::string infix_expr = "";
flag_Open = 1;
flag_Close = 0;
while(!input.eof() && flag_Open != flag_Close)
{
input >> token;
if(token=="(")
flag_Open++;
if(token==")")
flag_Close++;
if(flag_Open != flag_Close)
infix_expr.append(token+" ");
}
if(flag_Close != flag_Open)
{
std::cout<<"Invalid Expression Given"<<std::endl;
return false;
}
Expr_Parser parser;
int result;
std::string temp = infix_expr.substr(0, infix_expr.length() - 1);
parser.evaluate_expression(temp, result);
b.build_number(factory, result);
}
else
{
std::cout<<"Invalid Expression Given"<<std::endl;
return false;
}
}
return true;
}
//
//Method to evaluate the expression
//
bool Expr_Parser::evaluate_expression( std::string & infix, int & result)
{
Tree_Factory_Builder factory;
Expr_Tree_Builder builder ;
//visitor obj -- Eval_Expr_Tree
Eval_Expr_Tree visitor;
bool returnValue = true;
std::istringstream input(infix);
std::string token;
int flag =0;
while (!input.eof ())
{
if(token=="/"|| token =="%")
flag++;
input >> token;
if(flag>0 && atoi(token.c_str())==0)
{
divide_by_zero_exception();
return false;
}
}
if (!this->parse_expr (infix, builder,factory))
return false;
Expr_Tree * expr = builder.get_expression ();
if (0 == expr)
return false;
// evaluate the expression
result = expr->eval (visitor);
delete expr;
return true;
} | [
"bandayashwanth@gmail.com"
] | bandayashwanth@gmail.com |
fbe89434b9efe9da5c6c09b97ba0f5fadc29a33b | 7e18f24dbda3ba926b25e10a048097ac9bc78f45 | /move_p.h | 56fb1d379bd63434bba14cdb234fcc89a61b5b4d | [] | no_license | cerevra/2048 | ff3811fb2b0a70a296b488608395fa660eebede8 | 89ec9009d999f584eec4c525ef9ebd276ac25e8a | refs/heads/master | 2020-05-16T19:12:09.731789 | 2015-05-17T13:02:35 | 2015-05-17T13:02:35 | 23,630,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,027 | h | #ifndef MOVE_P_H
#define MOVE_P_H
#include <QPoint>
#include <functional>
#include <memory>
#include "node.h"
class Playground;
class Move
{
public:
virtual ~Move() {}
bool moveRoutine() const;
void moveToPoint() const;
void movePoint(SpNode& nodeFrom, SpNode& nodeTo, int indexTo) const;
virtual int& moveIndex(int& idx) const = 0;
virtual QPoint coords(int x1, int x2) const = 0;
protected:
virtual void init() = 0;
SpNode& getNodeColumnConst(int y, int x) const;
SpNode& getNodeRowConst(int x, int y) const;
quint8 fieldSize() const;
mutable Playground* m_parent;
std::function<int (int,int)> m_arithmOper;
std::function<bool (int,int)> m_compare;
std::function<SpNode&(const Move*, int,int)> m_access;
int m_indexInit;
int m_indexLimit;
mutable int m_indexTop;
mutable int m_indexTo;
mutable int m_indexFrom;
mutable bool m_result = false;
};
typedef std::shared_ptr<Move> SpMove;
#endif // MOVE_P_H
| [
"cerevra@gmail.com"
] | cerevra@gmail.com |
62be85b6955ad1500cdbe8f2c1f2b94bd5da382a | c9c773eac29b3b4decda72850c44f0a4ad23a23d | /OpenGL Maze & Solution/ModernOpenGL/Texture.cpp | 70d491165f69fa0af8213e6c94c1e7b382c513c9 | [] | no_license | tododes/OpenGL | 268b152c6c5716c5b68669096a8ad3f876a291bf | 7d14f3e77497b347d4553c1981482b5bdf8baf38 | refs/heads/master | 2021-01-25T04:27:09.263668 | 2017-06-05T20:51:13 | 2017-06-05T20:51:13 | 93,445,367 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,087 | cpp |
#include "Texture.h"
#include <cassert>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
Texture::Texture(const string& fileName)
{
LoadTexture(fileName);
}
void Texture::LoadTexture(const string& fileName)
{
int width, height, numComponents;
unsigned char* imageData = stbi_load(fileName.c_str(), &width, &height, &numComponents, 4);
glGenTextures(1, &ID);
glBindTexture(GL_TEXTURE_2D, ID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
stbi_image_free(imageData);
}
Texture::~Texture()
{
DestroyTexture();
}
void Texture::Bind(int unit)
{
assert(unit >= 0 && unit <= 31);
glActiveTexture(GL_TEXTURE0 + unit);
glBindTexture(GL_TEXTURE_2D, ID);
}
void Texture::DestroyTexture()
{
glBindTexture(GL_TEXTURE_2D, 0);
glDeleteTextures(1, &ID);
}
| [
"tododes3@gmail.com"
] | tododes3@gmail.com |
addebcee4b0d471057ab1236b9dabd766fafe19e | 4beb91adecb9dc1e8b7dddc4434e509588e81a2e | /SubDlgDeviceCfg.h | 1b90ec72d0af42ea5295091a3065171ccdf1cc46 | [] | no_license | omenyrobert/fingerprintauthentication | adfb5112978e076c81149434e1bd480f06f2db5a | d1fd29dbd3ad982369424854ff4926b5b584d994 | refs/heads/main | 2022-12-30T06:22:06.294220 | 2020-10-21T08:35:23 | 2020-10-21T08:35:23 | 305,954,884 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,613 | h | #pragma once
#include "HCEHomeCMS.h"
#include "afxwin.h"
// CSubDlgDeviceCfg dialog
class CSubDlgDeviceCfg : public CDialog
{
DECLARE_DYNAMIC(CSubDlgDeviceCfg)
public:
CSubDlgDeviceCfg(CWnd* pParent = NULL); // standard constructor
virtual ~CSubDlgDeviceCfg();
// Dialog Data
enum { IDD = IDD_SUB_DLG_DEVICE_CFG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
DECLARE_MESSAGE_MAP()
public:
virtual BOOL OnInitDialog();
BOOL CheckInitParam();
void CurCfgUpdate();
void CurCfgSetup();
CString GetDVRType(DWORD dwDVRType);
private:
int m_iDeviceIndex;
LONG m_lLoginID;
NET_EHOME_DEVICE_INFO m_struDevInfo;
NET_EHOME_VERSION_INFO m_struVerInfo;
NET_EHOME_DEVICE_CFG m_struDevCfg;
public:
CString m_strDeviceName;
BOOL m_bCycleRecord;
int m_iAnalogChanNum;
int m_iTotalChanNum;
int m_iVoiceNum;
CComboBox m_cmbAudioType;
CString m_strDeviceType;
int m_iStartChanNum;
CString m_strCellphoneNO;
int m_iAlarmInputNum;
int m_iAlarmOutputNum;
int m_iDiskNum;
int m_iZeroChanNum;
CString m_strDeviceSerialNO;
CString m_doaoioi;
int m_iRS232Num;
int m_iRS485Num;
int m_iNetportNum;
int m_iAuxoutNum;
CComboBox m_cmbMajorScale;
CComboBox m_cmbMinorScale;
int m_iTotalAlarmInputNum;
int m_iTotalAlarmOutputNum;
int m_iZeroStartChanNum;
int m_iMaxDigitalNum;
CString m_strSIMSerialNO;
int m_iDeviceNO;
CComboBox m_cmbSmartType;
};
| [
"noreply@github.com"
] | noreply@github.com |
1e829146c9d4f9074f308e780b8a761b666f7a63 | 1ddf91c020b61313ebfa0bbf654b5c6d4e18b97e | /BerSU_Ball.cpp | eca80fc1bbe9c3d8c318408cf8daa8aea7311f2f | [] | no_license | MFRSiam/RandomCodes | 3a47a1a549f17e0e657488238624c702fb599941 | 23314576e3ad66d933042c72dcd98f1fcb833a62 | refs/heads/main | 2022-12-28T15:49:34.772140 | 2020-10-17T03:30:13 | 2020-10-17T03:30:13 | 302,228,350 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 837 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m;
int boys[100]{0}, girls[100]{0};
int less, diff, count;
count = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> boys[i];
}
cin >> m;
for (int i = 0; i < m; i++)
{
cin >> girls[i];
}
sort(boys, boys + n);
sort(girls, girls + m);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
diff = abs(boys[i] - girls[j]);
if (diff <= 1 && boys[i] != -1 && girls[j] != -1)
{
count++;
boys[i] = -1;
girls[j] = -1;
}
//cout << " Diff: " << diff;
}
}
cout << endl;
cout << count << endl;
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
71c7dd400ed4d36c43799d0421025307f2b65a41 | 91153941bd2522538aee9cbf501c4ec42bac55d3 | /utils.cpp | 0ac62f08c8363a3a99b3d83cbec29410e383cee1 | [] | no_license | matosjoaops/trabalhoCAL | c6567ad2c8e4dd72324fd790e8488c6c9717e988 | 08fc7fc74f016cbe624b706bbf2f410af644aeee | refs/heads/master | 2022-09-10T12:36:12.358619 | 2020-05-25T10:55:08 | 2020-05-25T10:55:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,050 | cpp | #include "utils.h"
string elem_two_spaces(string str)
{
while (str.find(" ") != string::npos)
{
str.erase(str.find(" "), 1);
}
return str;
}
vector<string> string_split(string str, char sep)
{
vector<string> result;
string component = "";
for (int i = 0; i < str.size(); i++)
{
char ch = str.at(i);
if (ch != sep)
{
component.append(1, ch);
}
else
{
component = elem_two_spaces(component);
if (component.at(component.size() - 1) == ' ') component.pop_back();
if (component.at(0) == ' ') component.erase(0, 1);
result.push_back(component);
component = "";
}
if (i == (str.size() - 1))
{
component = elem_two_spaces(component);
if (component.at(component.size() - 1) == ' ') component.pop_back();
if (component.at(0) == ' ') component.erase(0, 1);
result.push_back(component);
}
}
return result;
}
| [
"matosjoaops@protonmail.com"
] | matosjoaops@protonmail.com |
abb0031aaec29f2f8cb3831ecc640bad35626569 | a61739604139b6afae25617b062be28b3344da44 | /wizualizer/author.cpp | 63f25a2e1621567478ab673d09f5cb875a0bf38d | [] | no_license | dorianJaniak/wds_sonar | 2d00f561b78b796e520a6324bbb77bc80e681729 | 1a2fc3cd1ef9012b60335e21884b58d723cd8640 | refs/heads/master | 2021-01-01T15:24:42.056597 | 2015-06-23T22:23:27 | 2015-06-23T22:23:27 | 32,487,416 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,335 | cpp | #include "author.h"
#include "ui_author.h"
Author::Author(QWidget *parent) :
QDialog(parent),
ui(new Ui::Author)
{
ui->setupUi(this);
ui->label->setText(tr("<html><head/><body><font style=\" font-weight:600;\">O autorze:"
"</font><br>Hej, jestem Dorian Janiak, studiuję na Politechnice Wrocławskiej "
"na Wydziale Elektroniki, kierunku: Automatyka i Robotyka i specjalności: Robotyka... "
"uff, dużo tego do wypisania było.<br><br><font style=\" font-weight:600;\">"
"O programie:</font><br>Program powstał w ramach projektu z kursu: wizualizacje danych sensorycznych,"
"<br>prowadzonego przez: dr inż. Bogdana Kreczmera<br>Zadaniem programu jest wizualizacja danych z "
"sonaru zamieszczonego na robocie mobilnym. Program powstawał w semestrze letnim roku akademickiego "
"2015/2016<br><br><font style=\" font-weight:600;\">O robocie:</font><br>"
"Robot powstaje w ramach kursu: roboty mobilne. Tworzony jest przez: Doriana Janiaka "
"oraz Marcina Ochmana.</body></html>"));
}
void Author::showEvent(QShowEvent *)
{
adjustSize();
}
Author::~Author()
{
delete ui;
}
| [
"dorianjaniak@wp.pl"
] | dorianjaniak@wp.pl |
ea81d0f9a77ac31a4f7313cf55de01a9789ec958 | 2a88b58673d0314ed00e37ab7329ab0bbddd3bdc | /blazemark/blazemark/armadillo/DMatInv.h | 913d0745d59787725e0332eb69e4f3190279d41b | [
"BSD-3-Clause"
] | permissive | shiver/blaze-lib | 3083de9600a66a586e73166e105585a954e324ea | 824925ed21faf82bb6edc48da89d3c84b8246cbf | refs/heads/master | 2020-09-05T23:00:34.583144 | 2016-08-24T03:55:17 | 2016-08-24T03:55:17 | 66,765,250 | 2 | 1 | NOASSERTION | 2020-04-06T05:02:41 | 2016-08-28T11:43:51 | C++ | UTF-8 | C++ | false | false | 3,016 | h | //=================================================================================================
/*!
// \file blazemark/armadillo/DMatInv.h
// \brief Header file for the Armadillo dense matrix inversion kernel
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group 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 _BLAZEMARK_ARMADILLO_DMATINV_H_
#define _BLAZEMARK_ARMADILLO_DMATINV_H_
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <blazemark/system/Types.h>
namespace blazemark {
namespace armadillo {
//=================================================================================================
//
// KERNEL FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*!\name Armadillo kernel functions */
//@{
double dmatinv( size_t N, size_t steps );
//@}
//*************************************************************************************************
} // namespace armadillo
} // namespace blazemark
#endif
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
37e6f078959a84c3050c36232a83162ed396ebdf | 15b84819b38c4098cb208ae62d1afa69a068df2c | /common/BSTmain.cpp | 39506af9d71a5fd761b5ed3239c0f7bdf6562810 | [] | no_license | zgjstudy/DataStructures | 2c378b2e78a6eefc30731f54b883de3514d37561 | f2f4d35e16b4d155a6232c0a60c5c3dacaa96ac6 | refs/heads/master | 2020-03-29T21:45:07.344363 | 2019-08-22T17:53:55 | 2019-08-22T17:53:55 | 150,385,281 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,381 | cpp | // From the software distribution accompanying the textbook
// "A Practical Introduction to Data Structures and Algorithm Analysis,
// Third Edition (C++)" by Clifford A. Shaffer.
// Source code Copyright (C) 2007-2011 by Clifford A. Shaffer.
// Program for testing the Binary Search Tree (BST) implementation
#include "book.h"
// BST implementation
#include "BST.h"
// Warning: This test driver has horrible memory leaks.
// Everytime the program does a remove to "it", the next time "it"
// gets used, that previous Int object gets clobbered.
int main()
{
BST<int, Int*> tree;
Int* it;
cout << "Size: " << tree.size() << "\n";
tree.insert(100, new Int(100));
tree.print();
cout << "Size: " << tree.size() << "\n";
it = tree.remove(10);
tree.print();
cout << "Size: " << tree.size() << "\n";
tree.clear();
cout << "Cleared.\n";
cout << "Size: " << tree.size() << "\n";
tree.insert(15, new Int(15));
cout << "Size: " << tree.size() << "\n";
if ((it = tree.find(20)) != NULL)
cout << "Found " << it << endl;
else cout << "No key 20\n";
if ((it = tree.find(15)) != NULL)
cout << "Found " << it << endl;
else cout << "No key 15\n";
tree.print();
if ((it = tree.remove(20)) != NULL)
cout << "Removed " << it << endl;
else cout << "No key 20\n";
cout << "Now, insert 20\n";
tree.insert(20, new Int(20));
tree.print();
if ((it = tree.remove(20)) != NULL)
cout << "Removed " << it << endl;
else cout << "No key 20\n";
tree.print();
tree.insert(700, new Int(700));
cout << "Size: " << tree.size() << "\n";
tree.insert(350, new Int(350));
tree.insert(201, new Int(201));
tree.insert(170, new Int(170));
tree.insert(151, new Int(151));
tree.insert(190, new Int(190));
tree.insert(1000, new Int(1000));
tree.insert(900, new Int(900));
tree.insert(950, new Int(950));
tree.insert(10, new Int(10));
tree.print();
if ((it = tree.find(1000)) != NULL)
cout << "Found " << it << endl;
else cout << "No key 1000\n";
if ((it = tree.find(999)) != NULL)
cout << "Found " << it << endl;
else cout << "No key 999\n";
if ((it = tree.find(20)) != NULL)
cout << "Found " << it << endl;
else cout << "No key 20\n";
cout << "Now do some delete tests.\n";
tree.print();
if ((it = tree.remove(15)) != NULL)
cout << "Removed " << it << endl;
else cout << "No key 15\n";
tree.print();
if ((it = tree.remove(151)) != NULL)
cout << "Removed " << it << endl;
else cout << "No key 151\n";
tree.print();
if ((it = tree.remove(151)) != NULL)
cout << "Removed " << it << endl;
else cout << "No key 151\n";
if ((it = tree.remove(700)) != NULL)
cout << "Removed " << it << endl;
else cout << "No key 700\n";
tree.print();
tree.clear();
tree.print();
cout << "Size: " << tree.size() << "\n";
cout << "Finally, test iterator\n";
tree.insert(3500, new Int(3500));
tree.insert(2010, new Int(2010));
tree.insert(1700, new Int(1700));
tree.insert(1510, new Int(1510));
tree.insert(1900, new Int(1900));
tree.insert(10000, new Int(10000));
tree.insert(9000, new Int(9000));
tree.insert(9500, new Int(9500));
tree.insert(100, new Int(100));
tree.print();
cout << "Start:\n";
Int* temp;
//while (tree.size() > 0) {
// temp = tree.removeAny();
// cout << temp << " ";
//}
cout << "\n";
system("Pause");
return 0;
}
| [
"981225888@qq.com"
] | 981225888@qq.com |
f35728287f2c59b360f721e7cdde733ccb13dbab | 0545e7cbae973e4f30adfab072f50a7158fc15b5 | /Light and Shadow Runners/GameMenu.h | 5e31cac198d2f48d588fbea95c0231a36b7f9a55 | [] | no_license | merche-o/LightAndShadowRunner | 1a34926a16a33eca7ec0165796fd4022eb751f02 | df88710544ba36176a43495b0f1dd20a35e8029d | refs/heads/master | 2021-06-07T23:37:06.966586 | 2016-02-09T22:06:13 | 2016-02-09T22:06:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,152 | h | #pragma once
#include "Display.h"
#include "Event.h"
#include "TextMenu.h"
#include "Parameters.h"
#include <utility>
#include <vector>
#include <map>
#include <string>
class GameMenu : public Display
{
public:
enum e_state
{
MAIN,
SETTING,
CREDITS,
WIN,
WIN2,
NONE
};
public:
sf::RenderWindow & win;
Parameters & param;
std::map<std::pair<e_state, int>, TextMenu*> textMenu;
std::map<std::pair<e_state, int>, void(GameMenu:: *)()> actionMenu;
std::map<std::pair<e_state, int>, TextMenu*> keyTextMenu;
std::map<e_state, int> sizeKeyTextMenu;
std::map<e_state, int> sizeTextMenu;
e_state currentState;
std::vector<e_state> beforeState;
int posMenu;
bool isPushed;
Event & event;
bool & start;
bool refresh;
int &winner;
public:
GameMenu(sf::RenderWindow & w, Event & e, Parameters &p, bool & s, int &win);
~GameMenu(void);
void run();
void displayCurrentMenu();
void winScreenRun();
void menuSettings();
void menuCredits();
void menuReturn();
void menuWin();
void menuPlay();
void addTextMenu(e_state state, TextMenu * text);
void addKeyTextMenu(e_state state, TextMenu * text, void(GameMenu:: *p)());
};
| [
"olivier.mercher@epitech.eu"
] | olivier.mercher@epitech.eu |
e0870f3ffc9d972f00820bae56e01409659a51c3 | 8c1dbeb23cb2bcf0fe44b62f703486dcc99f79a4 | /v2/Full/src/common/exception/InvalidParameterException.h | 0d34dd8ee595b4249c31fc5875df3ee164ab5f6e | [] | no_license | JefGrailet/treenet | 0e2bf104ea347ec0efd221e3b91f738d69ca90e8 | 10cfdcd7e94d73ab29c129ccffb07c4ba6dbcadd | refs/heads/master | 2020-12-24T06:42:31.569006 | 2019-10-14T10:06:17 | 2019-10-14T10:06:17 | 34,863,160 | 10 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 472 | h | /*
* InvalidParameterException.h
*
* Created on: Jul 28, 2008
* Author: root
*/
#ifndef INVALIDPARAMETEREXCEPTION_H_
#define INVALIDPARAMETEREXCEPTION_H_
#include <string>
using std::string;
#include "NTmapException.h"
class InvalidParameterException: public NTmapException {
public:
InvalidParameterException(const string & msg="The parameter given is invalid");
virtual ~InvalidParameterException()throw();
};
#endif /* INVALIDPARAMETEREXCEPTION_H_ */
| [
"Jean-Francois.Grailet@student.ulg.ac.be"
] | Jean-Francois.Grailet@student.ulg.ac.be |
9b0018397cebd6b8e8969deb27b6535160f23acd | 8bf747761f2b0f7bab7a1e7e087d7eabbe4b487e | /BookStoreManagement/ReportModule.cpp | 29e10260418b1f13580c902724f08219ab791025 | [] | no_license | effieguo/BookStoreManagement | cdb85ac533b1dfd2b75d6523c1eacfbbea8711ec | becd04630121a6f3d16e5e897bae29215eab6a8c | refs/heads/master | 2021-01-02T22:19:57.154146 | 2017-08-04T07:57:08 | 2017-08-04T07:57:08 | 99,317,999 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,109 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include "ReportModule.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include "Array.h"
#include "Book.h"
#include "BookDatabase.h"
using namespace std;
void ReportModule::Run()
{
int selectIndex;
do
{
HelpFuncs::DisplayTitle();
HelpFuncs::DisplayDate();
cout << setw(20) << "REPORT MENU" << endl << endl;
cout << " " << left << setw(5) << "1." << "Inventory Listing" << endl
<< " " << left << setw(5) << "2." << "Inventory Wholesale Value" << endl
<< " " << left << setw(5) << "3." << "Inventory Retail Value" << endl
<< " " << left << setw(5) << "4." << "Listing by Quantity" << endl
<< " " << left << setw(5) << "5." << "Listing by Cost" << endl
<< " " << left << setw(5) << "6." << "Listing by Age" << endl
<< " " << left << setw(5) << "7." << "Return to the Main Menu" << endl
<< " " << left << setw(5) << "Enter Your Choice: ";
selectIndex = HelpFuncs::GetMenuIndex();
switch (selectIndex)
{
case 1:
ListInventory();
break;
case 2:
ListWholeSaleValue();
break;
case 3:
ListRetailValue();
break;
case 4:
ListSortedByQuantity();
break;
case 5:
ListSortedByWholeSaleCost();
break;
case 6:
ListSortedByDate();
break;
case 7:
return;
break;
default:
cout << "Invalid input.";
return;
}
} while (selectIndex != 7);
}
void ReportModule::ListInventory()
{
bookDatabase.ListBookInfo(bookDatabase.GetBookArray(), Book::All);
}
void ReportModule::ListWholeSaleValue()
{
bookDatabase.ListBookInfo(bookDatabase.GetBookArray(), Book::WholeSaleValue);
}
void ReportModule::ListRetailValue()
{
bookDatabase.ListBookInfo(bookDatabase.GetBookArray(), Book::RetailValue);
}
void ReportModule::ListSortedByWholeSaleCost()
{
bookDatabase.ListSortedBookArrayByWholeSaleCost();
}
void ReportModule::ListSortedByQuantity()
{
bookDatabase.ListSortedBookArrayByQuantity();
}
void ReportModule::ListSortedByDate()
{
bookDatabase.ListSortedBookArrayByDate();
}
| [
"effie0711@gmail.com"
] | effie0711@gmail.com |
2f7c106d2c2772b1f61f40a69618184d9e6c63ce | f9031175d873ea3166bfe168b93a2fca0830b8d7 | /7.cpp | 794506520cc5fb29d888ea6b4c3745ce7e10649a | [] | no_license | angelineindahsi/ProgrammingChallenge-15 | 6aff3ff95ea6b2e3e8fa4dc54296c9f25b6454e7 | ea081b9bedc01a864efbcf6c08ce23adf7b379ce | refs/heads/master | 2021-01-18T22:19:56.145276 | 2016-10-31T14:50:47 | 2016-10-31T14:50:47 | 72,412,975 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,458 | cpp | #include <iostream>
#include <string>
using namespace std;
class PersonData
{
private:
string lastName;
string firstName;
string address;
string city;
string state;
int zip;
string phoneNo;
public:
void setData(string last, string first, string add, string cty, string statee, int zipp, string phone)
{
this->lastName = last;
this->firstName = first;
this->address = add;
this->city = cty;
this->state = statee;
this->zip = zipp;
this->phoneNo = phone;
}
void setLast (string lastNamee)
{
lastName = lastNamee;
}
void setFirst (string firstNamee)
{
firstName = firstNamee;
}
void setAddress (string addr)
{
address = addr;
}
void setCity(string cityy)
{
city = cityy;
}
void setState(string statee)
{
statee = statee;
}
void setZip (int zippp)
{
zip = zippp;
}
void setPhone (string number)
{
phoneNo = number;
}
string getFirstName()
{
return firstName;
}
string getLastName()
{
return lastName;
}
string getAddress()
{
return address;
}
string getCity()
{
return city;
}
string getState()
{
return state;
}
int getZip()
{
return zip;
}
string getPhoneNo()
{
return phoneNo;
}
};
class CustomerData:public PersonData
{
private:
int customerNumber;
bool mailingList;
public:
void setCustomerNumber(int custNo)
{
customerNumber = custNo;
}
void setMailingList(bool mailList)
{
if(mailList == 1)
{
mailingList = true;
} else
{
mailingList = false;
}
}
int getCustomerNumber()
{
return customerNumber;
}
int getMailingList()
{
return mailingList;
}
};
int main ()
{
string lastName, firstName, address, city, zipCod, phoneNum, customerNo;
int mailingListt;
CustomerData cust;
cout << "Last name: ";
getline(cin, lastName);
cout << "First name: ";
getline(cin, firstName);
cout << "Address: ";
getline(cin, address);
cout << "City: ";
getline(cin, city);
cout << "Zip Code: ";
getline(cin, zipCod);
cout << "Phone number: ";
getline(cin, phoneNum);
cout << "Customer number: ";
getline(cin, customerNo);
cout << "Do you want to be in the mailing list? 1.Yes 2.No" << endl;
cin >> mailingListt;
cust.setLast(lastName);
cust.setFirst(firstName);
cust.setAddress(address);
cust.setCity(city);
cust.setZip(zipCod);
cust.setPhone(phoneNum);
cust.setMailingList(mailingListt);
cout << "Name: " << cust.getFirstName() << " " << cust.getLastName() << endl;
cout << "Address: " << cust.getAddress() << endl;
cout << "City: " << cust.getCity() << endl;
cout << "State: " << cust.getState() << endl;
cout << "Zip Code: " << cust.getZip() << endl;
cout << "Phone number: " << cust.getPhoneNo() << endl;
cout << "Customer number: " << cust.getCustomerNumber() << endl;
if(cust.getMailingList())
{
cout << "You are in the mailing list." << endl;
} else
{
cout << "You are not in the mailing list." << endl;
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
8c4e6bb10959138cc428a514d24aeb0fed223448 | 109ab58e3ee319e887570af330879eee7a24c8a5 | /leetcode/cpp/234.cpp | 40530eea6ba945b59656ccdd5ea919415c554b19 | [] | no_license | alejolp/programming-exercises | b16123b2c7cf541e5c6eb6469900519c9256b7ef | 9ab2758af696e64bebcfee57ad2e6c07f0f79446 | refs/heads/master | 2021-07-09T12:34:44.174376 | 2021-06-30T20:40:40 | 2021-06-30T20:40:40 | 40,055,856 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,327 | cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int len(ListNode* head) {
int r = 0;
while (head) {
head = head->next;
++r;
}
return r;
}
ListNode* reverse(ListNode* half) {
ListNode* revhalf = 0;
while (half) {
ListNode* tmp = half->next;
half->next = revhalf;
revhalf = half;
half = tmp;
}
return revhalf;
}
bool isPalindrome(ListNode* head) {
int listlen = len(head); // O(n)
int i;
bool result = true;
ListNode *half = head, *halforig = 0, *headorig = head;
if(listlen < 2) return true; // O(1)
// O(n/2)
for(i=0;i<listlen/2; ++i) {
half = half->next;
}
if (listlen%2) {
half = half->next;
}
// O(n/2)
halforig = half;
half = reverse(half);
// O(n/2)
while (half && head) {
if (half->val != head->val) result = false;
half = half->next;
head = head->next;
}
// O(n/2)
reverse(halforig);
return result;
}
}; | [
"alejolp@gmail.com"
] | alejolp@gmail.com |
25009f9f60d90aa0b46f08954716cd1b343e8edc | 8ef0f61e484eb454df1839d24358675d7c95790e | /Matrix Collision Project/mainfile2OMP.cpp | 8859b721279c3c4acb16d20538eb82973b098d50 | [] | no_license | lssl4/SampleProjects | 6cd0ffb461037d505f0655b4d0f1f29ca678f6a6 | 5a2e0862a651355e0366b7d430784ce302512a28 | refs/heads/master | 2021-06-16T14:37:45.103388 | 2017-05-11T16:17:38 | 2017-05-11T16:17:38 | 41,460,529 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,113 | cpp | /*
This is the main file of our C++ implemented matrix collision program. This file requires other files such as finalNeighbors.cpp and type.h.
Require argument line arugments: ./(progname) data.txt keys.txt rows columns dia
This program generate blocks from columns of data with the same neighborhood.
Each row in the data text directly correspond with a key in the key array with the same index.
*/
//c directives
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
using namespace std;
//c++ directives
#include <unordered_map>
#include <vector>
#include <iostream>
#include <algorithm>
#define numThreads 4
#include "type.h"
unordered_map<long long int, vector<BLOCK>> collisionTable;
long long int *keys;
double **mat;
#include "finalNeighbors.cpp"
/*
Generate all the combinations of indices given an integer n and choosing r.
*/
vector<vector<int>> genCombos(int n, int r) {
vector<int> eachCom;
vector<vector<int>> listOfCombos;
//generates the eachCom with numbers up to r
for (int i = 0; i < r; i++){
eachCom.push_back(i);
}
if(r-1 >= 0){
while (eachCom[r - 1] < n) {
//put the just generated combo into the listOfCombos
listOfCombos.push_back(eachCom);
int t = r - 1;
while (t != 0 && eachCom[t] == n - r + t) t--;
eachCom[t]++;
for (int i = t + 1; i < r; i++) eachCom[i] = eachCom[i - 1] + 1;
}
}
return listOfCombos;
}
/*
After the 4 element combinations called blocks have been generated and modified,
Assign and declare each combinations to a Block type and push to the global variable hashmap, collisionTable
*/
void pushToCollisionTable(vector<vector<int>> c, vector<ELEMENT> vect){
int numOfElements =4;
omp_lock_t writelock;
omp_init_lock(&writelock);
// for each combinations generated in c, obtain the combination indices' elements from vect, the neighborhood, and generate blocks from them
// to be inserted to the collision table
#pragma omp parallel for num_threads(numThreads)
for(int k = 0; k < c.size(); k++) {
//for each element index in a combo generated, access vect to get the appropriate element in the neighborhood
//and put the row in the element list. and to get the keySum from keys array from the row index
long long int keysSum = 0;
BLOCK newBlock;
for (int j = 0; j < numOfElements; j++) {
ELEMENT el = vect[c[k][j]];
newBlock.rowIds.push_back(el.row);
newBlock.col = el.col;
keysSum += keys[el.row];
}
//add to collision table, if it doesn't exist, it makes a new entry
omp_set_lock(&writelock);//prevents other threads writing to the same location
collisionTable[keysSum].push_back(newBlock);
omp_unset_lock(&writelock);
} omp_destroy_lock(&writelock);
}
/*
Generate blocks given a vector of ELEMENTS and pivot. v.size() -1 because it also contains the pivot at the end of the vector of ELEMENTS
*/
int genBlocks(vector<ELEMENT> v, int pivot ){
//2 combos vectors for block generations and to prevent redundant blocks
vector<vector<int>> combos1;
vector<vector<int>> combos2;
int r =4;
int blocksGen = 0;
omp_lock_t writelock;
omp_init_lock(&writelock);
//if pivot is the same value as the v's size, then go straight ahead and generate the combos for whole ELEMENT vector
if(pivot==v.size()-1){
combos1 = genCombos( ((int)v.size())-1, r);
pushToCollisionTable(combos1, v);
//else if there's a pivot
}else{
if(pivot <(v.size() -1)&& pivot >= 0 ){
for(int k = 0 ; k < r; k++){
int n1 = pivot;
int r1 = r-k-1;
int n2 = (int)((v.size()-1)-pivot);
int r2 = k+1;
if( r1<=n1 &&r1 >=0 &&r2<=n2 &&r2 >=0 ){
vector<vector<int>> combinedCombos;
//iteratively decreasing r for the first combos
combos1 = genCombos(pivot, r-k-1);
//iteratively increasing r for the second combos
combos2 = genCombos((int)((v.size()-1)-pivot), k+1);
//adding all of the combos by pivot number in combos2 to match the latter half of array indices
#pragma omp parallel for
for(int x = 0; x < combos2.size() ; x++){
vector<int>eachCom = combos2[x];
//adding each element in eachCom by pivot
for(int y = 0 ; y < eachCom.size(); y++){
eachCom[y] += pivot;
}
combos2[x] = eachCom;
}
//after producing 2 sets of combos, combined them in a permutative manner
#pragma omp parallel for num_threads(numThreads) schedule(static)
for(int l = 0 ; l < combos1.size() ; l++){
vector<int> combA = combos1[l];
for(int m = 0 ; m < combos2.size(); m++){
vector<int> aCombinedCombo;
vector<int> combB = combos2[m];
//inserting combos1 first
aCombinedCombo.insert(aCombinedCombo.end(),combA.begin(), combA.end());
//inserting combos2 second
aCombinedCombo.insert(aCombinedCombo.end(),combB.begin(), combB.end());
omp_set_lock(&writelock);
//add the combined combo into the combinedCombos vector
combinedCombos.push_back( aCombinedCombo );
omp_unset_lock(&writelock);
} omp_destroy_lock(&writelock);
}
//After all of the combinedCombos have been generated, push the combinedCombs with the neighborhood v to the
//collision table
pushToCollisionTable(combinedCombos, v);
}
}
}
}
return blocksGen;
}
int main(int argc, char* argv[]){
if(argc < 6 || !isdigit(argv[3][0]) || !isdigit(argv[4][0]) || !isdigit(argv[5][0]) ){
printf("Please give the correct arguments: progName datafilename keysfilename rows columns dia\n");
return -1;
}
int rows = atoi(argv[3]);
int cols = atoi(argv[4]);
double dia = atof(argv[5]);
//initializing keys and mat
keys = (long long int*)malloc(rows*sizeof(long long int));
mat = (double**) malloc( sizeof(double *) * rows );
for(int x=0; x < rows; x++) {
mat[x] = (double *)malloc(sizeof(double)*cols);
}
//Reading in the keys.txt files
FILE *fp = fopen(argv[2], "r");
if(fp == NULL){
printf("File opening failed\n");
return -1;
}
//Getting every lli from the file
for(int x = 0 ; x < rows; x++){
fscanf(fp, "%lli", &keys[x]);
}
fclose(fp);
//Getting the data.txt
char buffer[5000] ; //big enough for 500 numbers
char *record;
char *line;
int i=0,j=0;
FILE *fstream = fopen(argv[1],"r");
if(fstream == NULL)
{
printf("\n file opening failed ");
return -1 ;
}
while((line=fgets(buffer,sizeof(buffer),fstream))!=NULL)
{
//always restart j whenever you get a new row
j =0;
record = strtok(line,",");
while(record != NULL)
{
//printf("recodrd: %s\n",record) ;
mat[i][j++] = atof(record) ;
record = strtok(NULL,",");
}
//increasing row number
++i ;
}
fclose(fstream);
//sorting and generating the column by column
#pragma omp num_threads(numThreads) for schedule(static)
for(int k = 0; k < cols; k++ ){
vector<ELEMENT> justAColumn(rows);
for(int x = 0 ; x < rows; x++){
ELEMENT el;
el.row = x;
el.col = 0;
el.datum = mat[x][k];
justAColumn[x] = el;
}
//call finalneighbors function (getNeighbors) where the column will be sorted in the function. Returns a list of neighborhoods
vector<vector<ELEMENT>> output = getNeighbours(justAColumn, dia);
for(int k = 0; k < output.size(); k ++){
genBlocks(output[k], (output[k][output[k].size()-1]).datum );
}
}
//printing out collision table summary
int collisionSum = 0;
int blocksGen = 0;
for ( auto it = collisionTable.begin(); it != collisionTable.end(); ++it )
{
//for each key add their value size
blocksGen += (*it).second.size();
if((*it).second.size() > 1){
collisionSum++;
}
}
cout<< "collisionSum: "<< collisionSum << " BlocksGen: " << blocksGen<<endl ;
free(keys);
free(mat);
}
| [
"noreply@github.com"
] | noreply@github.com |
198016786352688ca3020d2649b0eea70e2060de | 399847d9c95b97769af38d32fb46187769ca3a05 | /tracker/code/main/GLOB.h | 74dee9ac0b3a5129568e243ef4d74ee5d7c8700c | [] | no_license | ogre/pizero_tracker | 2b1915dff721f8e24cb859bc085a302dc23a7f29 | 42cb4efc4512a6ecceaf0867d3f176013ad7b2c6 | refs/heads/master | 2023-01-23T13:36:01.491067 | 2020-12-14T08:40:28 | 2020-12-14T08:40:28 | 251,083,244 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,603 | h | #pragma once
#include <string>
#include <vector>
#include <map>
#include <atomic>
#include <chrono>
#include "mtx2/mtx2.h"
#include "nmea/nmea.h"
#include "dynamics_t.h"
enum class flight_state_t : int
{
kUnknown = 0,
kStandBy = 1, // near launch position and average abs(dAlt/dTime) < 3 m/s
kAscend = 2, // average dAlt/dTime > 3 m/s
kDescend = 3, // average dAlt/dTime < -3 m/s
kFreefall = 4, // average abs(dAlt/dTime) < -8 m/s
kLanded = 5 // far from launch position and average abs(dAlt/dTime) < 3 m/s and alt<2000
};
// global options - singleton
class GLOB
{
private:
GLOB() {};
GLOB( const GLOB& ) = delete; // non construction-copyable
GLOB& operator=( const GLOB& ) = delete; // non copyable
std::atomic<nmea_t> nmea_; // GPS data
std::atomic<nmea_t> nmea_last_valid_; // GPS data - last valid
std::chrono::steady_clock::time_point gps_fix_timestamp_;
// sensors dynamics
std::map<std::string, dynamics_t> dynamics_; // index: value name (alt, temp1, etc.)
// flight state
std::atomic<flight_state_t> flight_state_{flight_state_t::kUnknown};
public:
static GLOB& get()
{
static GLOB g;
return g;
}
struct cli_t // command line interface options
{
std::string callsign;
float freqMHz = 0; //MegaHertz
baud_t baud = baud_t::kInvalid;
std::string ssdv_image; // ssdv encoded image path
std::string logsdir{"./"}; // logs dirs
int msg_num = 5; // number of telemetry sentences emitted between SSDV packets
int port = 6666; // zeroMQ server port
float lat = 0; // launch site latitude deg
float lon = 0; // launch site longitude deg
float alt = 0; // launch site altitude meters
bool testgps = false; // generate fake GPS for testing
bool watchdog = false; // enable watchdog
// hardware config
int hw_pin_radio_on = 0; // gpio numbered pin for radio enable. current board: 22
std::string hw_radio_serial; // serial device for MTX2 radio. for rPI4: /dev/serial0
std::string hw_ublox_device; // I2C device for uBLOX. for rPI4: /dev/i2c-7
};
cli_t cli;
void dynamics_add(const std::string& name, const dynamics_t::tp timestamp, const float value);
dynamics_t dynamics_get(const std::string& name) const;
std::vector<std::string> dynamics_keys() const; // names in dynamics_
void nmea_set(const nmea_t& in_nmea) {
get().nmea_ = in_nmea;
if(in_nmea.valid()) {
get().nmea_last_valid_ = in_nmea;
get().gps_fix_now();
}
}
nmea_t nmea_current() { nmea_t ret = get().nmea_; return ret; }
nmea_t nmea_last_valid() { nmea_t ret = get().nmea_last_valid_; return ret; }
void gps_fix_now() { gps_fix_timestamp_ = std::chrono::steady_clock::now(); }
int gps_fix_age() const { return (std::chrono::steady_clock::now() - gps_fix_timestamp_).count() / 1e9; }
void flight_state_set(const flight_state_t flight_state) { get().flight_state_ = flight_state; }
flight_state_t flight_state_get() const { return get().flight_state_; }
// runtime seconds
long long runtime_secs_ = 0;
std::string runtime_str() const; // return runtime in format HH:MM:SS
std::string str() const;
};
| [
"michal@cgarea.com"
] | michal@cgarea.com |
4836d02ae3417870a41d1487882ba09b6c216bfb | cd6cca2ee8ebcdaed8bd17297764b3b92a91e6b3 | /201816040314/Ex06_50.cpp | 2ff0c0fb25dbe224bfbf8d0e16f6f6069bc5dfc7 | [] | no_license | SE-OOP/Assignment_01 | 7febfa4ac0976648687c316476990ae1ec7cfa17 | b399768cd3793d02b7016bc294bc6b80b969b231 | refs/heads/master | 2022-10-27T01:10:17.078130 | 2019-12-28T15:31:02 | 2019-12-28T15:31:02 | 214,675,846 | 0 | 0 | null | 2023-03-09T07:05:12 | 2019-10-12T16:06:39 | C++ | UTF-8 | C++ | false | false | 787 | cpp | #include <iostream>
using namespace std;
int tripleByValue(int num){//函数:按值传递,不该变本身的值
return 3*num;
}
void tripleByReference(int & num){//函数:按引用传递,该变本身的值
num=3*num;
}
int main()
{
int count=0;//声明并初始化
cout<<"请输入一个整数count:";
cin>>count;
cout<<"调用tripleByValue()函数之前count的值为:"<<count<<endl;
cout<<"调用tripleByValue()函数返回的值为: "<<tripleByValue(count)<<endl;
cout<<"调用tripleByValue()函数之后count的值为:"<<count<<endl<<endl;
cout<<"调用tripleByReference()函数之前的count值为:"<<count<<endl;
cout<<"调用tripleByReference()函数之后的count值为:";
tripleByReference(count);
cout<<count<<endl;
}
| [
"noreply@github.com"
] | noreply@github.com |
2faa70c0c347abcf95f9b5e6d3368e4cfa613ea5 | 918cfcf7043db2a1039540d1ea0647a1bb9b1613 | /Assignment1/search_in_sorted_matrix.cpp | 47214f9341561a21d31c17e14b6b992cc82d96d1 | [] | no_license | Prerit73/CipherSchools_Assignment | 9842b3ba282edc5d82e6185ed9d71575709e42ec | 177aa7d1b1277b6d23e9bf37ec0c557a22ca650b | refs/heads/main | 2023-06-16T14:24:25.929655 | 2021-07-15T18:52:01 | 2021-07-15T18:52:01 | 338,549,118 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 577 | cpp | #include <bits/stdc++.h>
using namespace std;
void isExist(vector<vector<int>> matrix,int target){
int i=0,j=matrix[0].size();// took the top right element of matrix
while(i<matrix.size() && j>=0){
if(matrix[i][j]==target){
break;
}
if(matrix[i][j]>target){
j--;
}
else{
i++;
}
}
cout<<"Element is found at "<<i<<","<<j<<endl;
}
int main(){
vector<vector<int>> matrix={ {10, 20, 30, 40},{15, 25, 35, 45},{27, 29, 37, 48},{32, 33, 39, 50}};
isExist(matrix,29);
} | [
"prerit197@gmail.com"
] | prerit197@gmail.com |
e72fb504baf81fe30d901775b0068759ae955708 | bbfa470ececd273e994cb89bd1fdb3a536d314ac | /base/src/blocksignature.cpp | d7056c63a044a35e727d7468c610c5def6155ae6 | [
"MIT"
] | permissive | fruitsfuture/AsHa | 2fca95a0705ad83838e7f6de20c64e1e5b9baf6d | a6725d14a4cf65acaa45c20ca16019ff5943a43b | refs/heads/master | 2023-08-27T04:52:56.429024 | 2021-11-02T09:06:47 | 2021-11-02T09:06:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,280 | cpp | /***********************************************************************
*************Copyright (c) 2015-2017 The PIVX developers****************
******************Copyright (c) 2010-2019 Nur1Labs**********************
>Distributed under the MIT/X11 software license, see the accompanying
>file COPYING or http://www.opensource.org/licenses/mit-license.php.
************************************************************************/
#include "blocksignature.h"
#include "main.h"
bool SignBlockWithKey(CBlock& block, const CKey& key)
{
if (!key.Sign(block.GetHash(), block.vchBlockSig))
return error("%s: failed to sign block hash with key", __func__);
return true;
}
bool GetKeyIDFromUTXO(const CTxOut& txout, CKeyID& keyID)
{
std::vector<valtype> vSolutions;
txnouttype whichType;
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY) {
keyID = CPubKey(vSolutions[0]).GetID();
} else if (whichType == TX_PUBKEYHASH) {
keyID = CKeyID(uint160(vSolutions[0]));
}
return true;
}
bool SignBlock(CBlock& block, const CKeyStore& keystore)
{
CKeyID keyID;
if (block.IsProofOfWork()) {
bool fFoundID = false;
for (const CTxOut& txout :block.vtx[0].vout) {
if (!GetKeyIDFromUTXO(txout, keyID))
continue;
fFoundID = true;
break;
}
if (!fFoundID)
return error("%s: failed to find key for PoW", __func__);
} else {
if (!GetKeyIDFromUTXO(block.vtx[1].vout[1], keyID))
return error("%s: failed to find key for PoS", __func__);
}
CKey key;
if (!keystore.GetKey(keyID, key))
return error("%s: failed to get key from keystore", __func__);
return SignBlockWithKey(block, key);
}
bool CheckBlockSignature(const CBlock& block)
{
if (block.IsProofOfWork())
return block.vchBlockSig.empty();
if (block.vchBlockSig.empty())
return error("%s: vchBlockSig is empty!", __func__);
/** Each block is signed by the private key of the input that is staked. This can be either zMuBdI or normal UTXO
* zMuBdI: Each zMuBdI has a keypair associated with it. The serial number is a hash of the public key.
* UTXO: The public key that signs must match the public key associated with the first utxo of the coinstake tx.
*/
CPubKey pubkey;
bool fzMuBdIStake = block.vtx[1].IsZerocoinSpend();
if (fzMuBdIStake) {
libzerocoin::CoinSpend spend = TxInToZerocoinSpend(block.vtx[1].vin[0]);
pubkey = spend.getPubKey();
} else {
txnouttype whichType;
std::vector<valtype> vSolutions;
const CTxOut& txout = block.vtx[1].vout[1];
if (!Solver(txout.scriptPubKey, whichType, vSolutions))
return false;
if (whichType == TX_PUBKEY || whichType == TX_PUBKEYHASH) {
valtype& vchPubKey = vSolutions[0];
pubkey = CPubKey(vchPubKey);
}
}
if (!pubkey.IsValid())
return error("%s: invalid pubkey %s", __func__, pubkey.GetHex());
return pubkey.Verify(block.GetHash(), block.vchBlockSig);
}
| [
"crbru.yuthafiga@gmail.com"
] | crbru.yuthafiga@gmail.com |
373514a67023c5a3010490f5749796101793a488 | bac20f1cdb8d99dd84044069533465a75c304640 | /source/RDP/Models/DriverSettingsModel.cpp | 1b2ecaaae1127f3c159dd3faf5e34d6b332f3aa4 | [
"MIT"
] | permissive | play704611/dev_driver_tools | 5cb78583158bc1bb54dfe11868cbb2d57db8400d | 312d40afb533b623e441139797410a33ecab3182 | refs/heads/master | 2023-03-27T16:19:08.233450 | 2021-03-23T09:47:16 | 2021-03-23T09:47:16 | 350,657,143 | 0 | 0 | MIT | 2021-03-23T09:44:50 | 2021-03-23T09:44:50 | null | UTF-8 | C++ | false | false | 4,848 | cpp | //=============================================================================
/// Copyright (c) 2016-2017 Advanced Micro Devices, Inc. All rights reserved.
/// \author AMD Developer Tools Team
/// \file
/// \brief Driver Settings model class definition.
//=============================================================================
#include <QList>
#include <QVariant>
#include "gpuopen.h"
#include "ApplicationSettingsModel.h"
#include "DriverSettingsModel.h"
#include "DeveloperPanelModel.h"
#include "../RDPDefinitions.h"
#include "../Settings/RDPSettings.h"
#include "../../Common/ToolUtil.h"
using namespace DevDriver;
using namespace DevDriver::SettingsProtocol;
//-----------------------------------------------------------------------------
/// Constructor for DriverSettingsModel.
/// \param pPanelModel The main Panel model used to maintain a connection to RDS.
/// \param modelCount the number of models required.
//-----------------------------------------------------------------------------
DriverSettingsModel::DriverSettingsModel(DeveloperPanelModel* pPanelModel, ApplicationSettingsModel* pApplicationSettingsModel, uint32_t modelCount)
: DriverProtocolModel(pPanelModel, modelCount)
, m_pSettingsModel(pApplicationSettingsModel)
{
}
//-----------------------------------------------------------------------------
/// Destructor for DriverSettingsModel.
//-----------------------------------------------------------------------------
DriverSettingsModel::~DriverSettingsModel()
{
}
//-----------------------------------------------------------------------------
/// Initialize default values within the interface.
//-----------------------------------------------------------------------------
void DriverSettingsModel::InitializeDefaults()
{
}
//-----------------------------------------------------------------------------
/// Update the internal model members.
/// \param modelIndex The ID of the UI element that's being updated.
/// \param value The new value of the UI element.
//-----------------------------------------------------------------------------
void DriverSettingsModel::Update(DriverSettingsControls modelIndex, const QVariant& value)
{
SetModelData(modelIndex, value);
}
//-----------------------------------------------------------------------------
/// Update the existing driver settings with the incoming settings values.
/// \param settingsMap The new driver settings map to apply.
//-----------------------------------------------------------------------------
void DriverSettingsModel::UpdateDriverSettings(const DriverSettingsMap& settingsMap)
{
ApplicationSettingsModel* pSettingsModel = GetApplicationSettingsModel();
Q_ASSERT(pSettingsModel != nullptr);
if (pSettingsModel != nullptr)
{
ApplicationSettingsFile* pSettingsFile = pSettingsModel->GetSettingsFile();
if (pSettingsFile != nullptr)
{
DriverSettingsMap::const_iterator settingsStart = settingsMap.begin();
DriverSettingsMap::const_iterator settingsEnd = settingsMap.end();
DriverSettingsMap::const_iterator categoryIter;
for (categoryIter = settingsStart; categoryIter != settingsEnd; ++categoryIter)
{
const QString& categoryName = categoryIter.key();
const DriverSettingVector& settings = categoryIter.value();
for (int settingIndex = 0; settingIndex < settings.size(); ++settingIndex)
{
const DevDriver::SettingsProtocol::Setting& currentSetting = settings.at(settingIndex);
pSettingsFile->UpdateSetting(categoryName, currentSetting);
}
}
// Write the setting file after the change
RDPSettings::Get().WriteApplicationSettingsFile(pSettingsFile);
}
}
}
//-----------------------------------------------------------------------------
/// Update a single driver setting.
/// \param categoryName The name of the setting category for the setting
/// to update.
/// \param Setting struct to update.
//-----------------------------------------------------------------------------
void DriverSettingsModel::UpdateDriverSetting(QString categoryName, const DevDriver::SettingsProtocol::Setting& setting)
{
ApplicationSettingsModel* pSettingsModel = GetApplicationSettingsModel();
Q_ASSERT(pSettingsModel != nullptr);
if (pSettingsModel != nullptr)
{
ApplicationSettingsFile* pSettingsFile = pSettingsModel->GetSettingsFile();
if (pSettingsFile != nullptr)
{
// Update the setting
pSettingsFile->UpdateSetting(categoryName, setting);
// Write the setting file after each change
RDPSettings::Get().WriteApplicationSettingsFile(pSettingsFile);
}
}
}
| [
"Callan.McInally@amd.com"
] | Callan.McInally@amd.com |
4558aa8e03c675976a51f58335e3d16e7b336bad | b26f94db06b78e8382d4f8e17caea5dcbf94f9e4 | /2005/wtl/atluser.h | 4c101d24073e72f8e9ebe8ea865395d1aaf1fb0b | [] | no_license | thenfour/ColorReady | 902386cb1c5d0e8d3002bf9c7eb780093818c20d | c3f57fe74d2baf162439a8efe8bdbc5238110886 | refs/heads/master | 2016-09-05T17:12:10.059804 | 2014-02-18T01:35:40 | 2014-02-18T01:35:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,985 | h | // Windows Template Library - WTL version 8.0
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// This file is a part of the Windows Template Library.
// The use and distribution terms for this software are covered by the
// Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
// which can be found in the file CPL.TXT at the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by
// the terms of this license. You must not remove this notice, or
// any other, from this software.
#ifndef __ATLUSER_H__
#define __ATLUSER_H__
#pragma once
#ifndef __cplusplus
#error ATL requires C++ compilation (use a .cpp suffix)
#endif
#ifndef __ATLAPP_H__
#error atluser.h requires atlapp.h to be included first
#endif
///////////////////////////////////////////////////////////////////////////////
// Classes in this file:
//
// CMenuItemInfo
// CMenuT<t_bManaged>
// CAcceleratorT<t_bManaged>
// CIconT<t_bManaged>
// CCursorT<t_bManaged>
// CResource
//
// Global functions:
// AtlMessageBox()
namespace WTL
{
///////////////////////////////////////////////////////////////////////////////
// AtlMessageBox - accepts both memory and resource based strings
inline int AtlMessageBox(HWND hWndOwner, ATL::_U_STRINGorID message, ATL::_U_STRINGorID title = (LPCTSTR)NULL, UINT uType = MB_OK | MB_ICONINFORMATION)
{
ATLASSERT(hWndOwner == NULL || ::IsWindow(hWndOwner));
LPTSTR lpstrMessage = NULL;
if(IS_INTRESOURCE(message.m_lpstr))
{
for(int nLen = 256; ; nLen *= 2)
{
ATLTRY(lpstrMessage = new TCHAR[nLen]);
if(lpstrMessage == NULL)
{
ATLASSERT(FALSE);
return 0;
}
int nRes = ::LoadString(ModuleHelper::GetResourceInstance(), LOWORD(message.m_lpstr), lpstrMessage, nLen);
if(nRes < nLen - 1)
break;
delete [] lpstrMessage;
lpstrMessage = NULL;
}
message.m_lpstr = lpstrMessage;
}
LPTSTR lpstrTitle = NULL;
if(IS_INTRESOURCE(title.m_lpstr) && LOWORD(title.m_lpstr) != 0)
{
for(int nLen = 256; ; nLen *= 2)
{
ATLTRY(lpstrTitle = new TCHAR[nLen]);
if(lpstrTitle == NULL)
{
ATLASSERT(FALSE);
return 0;
}
int nRes = ::LoadString(ModuleHelper::GetResourceInstance(), LOWORD(title.m_lpstr), lpstrTitle, nLen);
if(nRes < nLen - 1)
break;
delete [] lpstrTitle;
lpstrTitle = NULL;
}
title.m_lpstr = lpstrTitle;
}
int nRet = ::MessageBox(hWndOwner, message.m_lpstr, title.m_lpstr, uType);
delete [] lpstrMessage;
delete [] lpstrTitle;
return nRet;
}
///////////////////////////////////////////////////////////////////////////////
// CMenu
#if (WINVER >= 0x0500)
#ifndef MII_SIZEOF_STRUCT
#define MII_SIZEOF_STRUCT(structname, member) (((int)((LPBYTE)(&((structname*)0)->member) - ((LPBYTE)((structname*)0)))) + sizeof(((structname*)0)->member))
#endif
#define MENUITEMINFO_SIZE_VERSION_400A MII_SIZEOF_STRUCT(MENUITEMINFOA, cch)
#define MENUITEMINFO_SIZE_VERSION_400W MII_SIZEOF_STRUCT(MENUITEMINFOW, cch)
#ifdef UNICODE
#define MENUITEMINFO_SIZE_VERSION_400 MENUITEMINFO_SIZE_VERSION_400W
#else
#define MENUITEMINFO_SIZE_VERSION_400 MENUITEMINFO_SIZE_VERSION_400A
#endif // !UNICODE
#endif // (WINVER >= 0x0500)
class CMenuItemInfo : public MENUITEMINFO
{
public:
CMenuItemInfo()
{
memset(this, 0, sizeof(MENUITEMINFO));
cbSize = sizeof(MENUITEMINFO);
#if (WINVER >= 0x0500)
// adjust struct size if running on older version of Windows
if(AtlIsOldWindows())
{
ATLASSERT(cbSize > MENUITEMINFO_SIZE_VERSION_400); // must be
cbSize = MENUITEMINFO_SIZE_VERSION_400;
}
#endif // (WINVER >= 0x0500)
}
};
// forward declarations
template <bool t_bManaged> class CMenuT;
typedef CMenuT<false> CMenuHandle;
typedef CMenuT<true> CMenu;
template <bool t_bManaged>
class CMenuT
{
public:
// Data members
HMENU m_hMenu;
// Constructor/destructor/operators
CMenuT(HMENU hMenu = NULL) : m_hMenu(hMenu)
{ }
~CMenuT()
{
if(t_bManaged && m_hMenu != NULL)
DestroyMenu();
}
CMenuT<t_bManaged>& operator =(HMENU hMenu)
{
Attach(hMenu);
return *this;
}
void Attach(HMENU hMenuNew)
{
ATLASSERT(::IsMenu(hMenuNew));
if(t_bManaged && m_hMenu != NULL && m_hMenu != hMenuNew)
::DestroyMenu(m_hMenu);
m_hMenu = hMenuNew;
}
HMENU Detach()
{
HMENU hMenu = m_hMenu;
m_hMenu = NULL;
return hMenu;
}
operator HMENU() const { return m_hMenu; }
bool IsNull() const { return (m_hMenu == NULL); }
BOOL IsMenu() const
{
return ::IsMenu(m_hMenu);
}
// Create/destroy methods
BOOL CreateMenu()
{
ATLASSERT(m_hMenu == NULL);
m_hMenu = ::CreateMenu();
return (m_hMenu != NULL) ? TRUE : FALSE;
}
BOOL CreatePopupMenu()
{
ATLASSERT(m_hMenu == NULL);
m_hMenu = ::CreatePopupMenu();
return (m_hMenu != NULL) ? TRUE : FALSE;
}
BOOL LoadMenu(ATL::_U_STRINGorID menu)
{
ATLASSERT(m_hMenu == NULL);
m_hMenu = ::LoadMenu(ModuleHelper::GetResourceInstance(), menu.m_lpstr);
return (m_hMenu != NULL) ? TRUE : FALSE;
}
#ifndef _WIN32_WCE
BOOL LoadMenuIndirect(const void* lpMenuTemplate)
{
ATLASSERT(m_hMenu == NULL);
m_hMenu = ::LoadMenuIndirect(lpMenuTemplate);
return (m_hMenu != NULL) ? TRUE : FALSE;
}
#endif // !_WIN32_WCE
BOOL DestroyMenu()
{
if (m_hMenu == NULL)
return FALSE;
BOOL bRet = ::DestroyMenu(m_hMenu);
if(bRet)
m_hMenu = NULL;
return bRet;
}
// Menu Operations
BOOL DeleteMenu(UINT nPosition, UINT nFlags)
{
ATLASSERT(::IsMenu(m_hMenu));
return ::DeleteMenu(m_hMenu, nPosition, nFlags);
}
BOOL TrackPopupMenu(UINT nFlags, int x, int y, HWND hWnd, LPCRECT lpRect = NULL)
{
ATLASSERT(::IsMenu(m_hMenu));
#ifndef _WIN32_WCE
#if (WINVER >= 0x0500)
x = _FixTrackMenuPopupX(x, y);
#endif // !(WINVER >= 0x0500)
return ::TrackPopupMenu(m_hMenu, nFlags, x, y, 0, hWnd, lpRect);
#else // CE specific
lpRect;
return ::TrackPopupMenuEx(m_hMenu, nFlags, x, y, hWnd, NULL);
#endif // _WIN32_WCE
}
BOOL TrackPopupMenuEx(UINT uFlags, int x, int y, HWND hWnd, LPTPMPARAMS lptpm = NULL)
{
ATLASSERT(::IsMenu(m_hMenu));
#if (WINVER >= 0x0500) && !defined(_WIN32_WCE)
x = _FixTrackMenuPopupX(x, y);
#endif // (WINVER >= 0x0500) && !defined(_WIN32_WCE)
return ::TrackPopupMenuEx(m_hMenu, uFlags, x, y, hWnd, lptpm);
}
#if (WINVER >= 0x0500) && !defined(_WIN32_WCE)
// helper that fixes popup menu X position when it's off-screen
static int _FixTrackMenuPopupX(int x, int y)
{
POINT pt = { x, y };
HMONITOR hMonitor = ::MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
if(hMonitor == NULL)
{
HMONITOR hMonitorNear = ::MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
if(hMonitorNear != NULL)
{
MONITORINFO mi = { 0 };
mi.cbSize = sizeof(MONITORINFO);
if(::GetMonitorInfo(hMonitorNear, &mi) != FALSE)
{
if(x < mi.rcWork.left)
x = mi.rcWork.left;
else if(x > mi.rcWork.right)
x = mi.rcWork.right;
}
}
}
return x;
}
BOOL GetMenuInfo(LPMENUINFO lpMenuInfo) const
{
ATLASSERT(::IsMenu(m_hMenu));
return ::GetMenuInfo(m_hMenu, lpMenuInfo);
}
BOOL SetMenuInfo(LPCMENUINFO lpMenuInfo)
{
ATLASSERT(::IsMenu(m_hMenu));
return ::SetMenuInfo(m_hMenu, lpMenuInfo);
}
#endif // (WINVER >= 0x0500) && !defined(_WIN32_WCE)
// Menu Item Operations
BOOL AppendMenu(UINT nFlags, UINT_PTR nIDNewItem = 0, LPCTSTR lpszNewItem = NULL)
{
ATLASSERT(::IsMenu(m_hMenu));
return ::AppendMenu(m_hMenu, nFlags, nIDNewItem, lpszNewItem);
}
BOOL AppendMenu(UINT nFlags, HMENU hSubMenu, LPCTSTR lpszNewItem)
{
ATLASSERT(::IsMenu(m_hMenu));
ATLASSERT(::IsMenu(hSubMenu));
return ::AppendMenu(m_hMenu, nFlags | MF_POPUP, (UINT_PTR)hSubMenu, lpszNewItem);
}
#ifndef _WIN32_WCE
BOOL AppendMenu(UINT nFlags, UINT_PTR nIDNewItem, HBITMAP hBmp)
{
ATLASSERT(::IsMenu(m_hMenu));
return ::AppendMenu(m_hMenu, nFlags | MF_BITMAP, nIDNewItem, (LPCTSTR)hBmp);
}
BOOL AppendMenu(UINT nFlags, HMENU hSubMenu, HBITMAP hBmp)
{
ATLASSERT(::IsMenu(m_hMenu));
ATLASSERT(::IsMenu(hSubMenu));
return ::AppendMenu(m_hMenu, nFlags | (MF_BITMAP | MF_POPUP), (UINT_PTR)hSubMenu, (LPCTSTR)hBmp);
}
#endif // !_WIN32_WCE
UINT CheckMenuItem(UINT nIDCheckItem, UINT nCheck)
{
ATLASSERT(::IsMenu(m_hMenu));
return (UINT)::CheckMenuItem(m_hMenu, nIDCheckItem, nCheck);
}
UINT EnableMenuItem(UINT nIDEnableItem, UINT nEnable)
{
ATLASSERT(::IsMenu(m_hMenu));
return ::EnableMenuItem(m_hMenu, nIDEnableItem, nEnable);
}
#ifndef _WIN32_WCE
BOOL HiliteMenuItem(HWND hWnd, UINT uIDHiliteItem, UINT uHilite)
{
ATLASSERT(::IsMenu(m_hMenu));
return ::HiliteMenuItem(hWnd, m_hMenu, uIDHiliteItem, uHilite);
}
int GetMenuItemCount() const
{
ATLASSERT(::IsMenu(m_hMenu));
return ::GetMenuItemCount(m_hMenu);
}
UINT GetMenuItemID(int nPos) const
{
ATLASSERT(::IsMenu(m_hMenu));
return ::GetMenuItemID(m_hMenu, nPos);
}
UINT GetMenuState(UINT nID, UINT nFlags) const
{
ATLASSERT(::IsMenu(m_hMenu));
return ::GetMenuState(m_hMenu, nID, nFlags);
}
int GetMenuString(UINT nIDItem, LPTSTR lpString, int nMaxCount, UINT nFlags) const
{
ATLASSERT(::IsMenu(m_hMenu));
return ::GetMenuString(m_hMenu, nIDItem, lpString, nMaxCount, nFlags);
}
int GetMenuStringLen(UINT nIDItem, UINT nFlags) const
{
ATLASSERT(::IsMenu(m_hMenu));
return ::GetMenuString(m_hMenu, nIDItem, NULL, 0, nFlags);
}
#ifndef _ATL_NO_COM
BOOL GetMenuString(UINT nIDItem, BSTR& bstrText, UINT nFlags) const
{
USES_CONVERSION;
ATLASSERT(::IsMenu(m_hMenu));
ATLASSERT(bstrText == NULL);
int nLen = GetMenuStringLen(nIDItem, nFlags);
if(nLen == 0)
{
bstrText = ::SysAllocString(OLESTR(""));
return (bstrText != NULL) ? TRUE : FALSE;
}
nLen++; // increment to include terminating NULL char
LPTSTR lpszText = (LPTSTR)_alloca((nLen) * sizeof(TCHAR));
if(!GetMenuString(nIDItem, lpszText, nLen, nFlags))
return FALSE;
bstrText = ::SysAllocString(T2OLE(lpszText));
return (bstrText != NULL) ? TRUE : FALSE;
}
#endif // !_ATL_NO_COM
#endif // !_WIN32_WCE
#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
int GetMenuString(UINT nIDItem, _CSTRING_NS::CString& strText, UINT nFlags) const
{
ATLASSERT(::IsMenu(m_hMenu));
int nLen = GetMenuStringLen(nIDItem, nFlags);
if(nLen == 0)
return 0;
nLen++; // increment to include terminating NULL char
LPTSTR lpstr = strText.GetBufferSetLength(nLen);
if(lpstr == NULL)
return 0;
int nRet = GetMenuString(nIDItem, lpstr, nLen, nFlags);
strText.ReleaseBuffer();
return nRet;
}
#endif // defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
CMenuHandle GetSubMenu(int nPos) const
{
ATLASSERT(::IsMenu(m_hMenu));
return CMenuHandle(::GetSubMenu(m_hMenu, nPos));
}
BOOL InsertMenu(UINT nPosition, UINT nFlags, UINT_PTR nIDNewItem = 0, LPCTSTR lpszNewItem = NULL)
{
ATLASSERT(::IsMenu(m_hMenu));
return ::InsertMenu(m_hMenu, nPosition, nFlags, nIDNewItem, lpszNewItem);
}
BOOL InsertMenu(UINT nPosition, UINT nFlags, HMENU hSubMenu, LPCTSTR lpszNewItem)
{
ATLASSERT(::IsMenu(m_hMenu));
ATLASSERT(::IsMenu(hSubMenu));
return ::InsertMenu(m_hMenu, nPosition, nFlags | MF_POPUP, (UINT_PTR)hSubMenu, lpszNewItem);
}
#ifndef _WIN32_WCE
BOOL InsertMenu(UINT nPosition, UINT nFlags, UINT_PTR nIDNewItem, HBITMAP hBmp)
{
ATLASSERT(::IsMenu(m_hMenu));
return ::InsertMenu(m_hMenu, nPosition, nFlags | MF_BITMAP, nIDNewItem, (LPCTSTR)hBmp);
}
BOOL InsertMenu(UINT nPosition, UINT nFlags, HMENU hSubMenu, HBITMAP hBmp)
{
ATLASSERT(::IsMenu(m_hMenu));
ATLASSERT(::IsMenu(hSubMenu));
return ::InsertMenu(m_hMenu, nPosition, nFlags | (MF_BITMAP | MF_POPUP), (UINT_PTR)hSubMenu, (LPCTSTR)hBmp);
}
BOOL ModifyMenu(UINT nPosition, UINT nFlags, UINT_PTR nIDNewItem = 0, LPCTSTR lpszNewItem = NULL)
{
ATLASSERT(::IsMenu(m_hMenu));
return ::ModifyMenu(m_hMenu, nPosition, nFlags, nIDNewItem, lpszNewItem);
}
BOOL ModifyMenu(UINT nPosition, UINT nFlags, HMENU hSubMenu, LPCTSTR lpszNewItem)
{
ATLASSERT(::IsMenu(m_hMenu));
ATLASSERT(::IsMenu(hSubMenu));
return ::ModifyMenu(m_hMenu, nPosition, nFlags | MF_POPUP, (UINT_PTR)hSubMenu, lpszNewItem);
}
BOOL ModifyMenu(UINT nPosition, UINT nFlags, UINT_PTR nIDNewItem, HBITMAP hBmp)
{
ATLASSERT(::IsMenu(m_hMenu));
return ::ModifyMenu(m_hMenu, nPosition, nFlags | MF_BITMAP, nIDNewItem, (LPCTSTR)hBmp);
}
BOOL ModifyMenu(UINT nPosition, UINT nFlags, HMENU hSubMenu, HBITMAP hBmp)
{
ATLASSERT(::IsMenu(m_hMenu));
ATLASSERT(::IsMenu(hSubMenu));
return ::ModifyMenu(m_hMenu, nPosition, nFlags | (MF_BITMAP | MF_POPUP), (UINT_PTR)hSubMenu, (LPCTSTR)hBmp);
}
#endif // !_WIN32_WCE
BOOL RemoveMenu(UINT nPosition, UINT nFlags)
{
ATLASSERT(::IsMenu(m_hMenu));
return ::RemoveMenu(m_hMenu, nPosition, nFlags);
}
#ifndef _WIN32_WCE
BOOL SetMenuItemBitmaps(UINT nPosition, UINT nFlags, HBITMAP hBmpUnchecked, HBITMAP hBmpChecked)
{
ATLASSERT(::IsMenu(m_hMenu));
return ::SetMenuItemBitmaps(m_hMenu, nPosition, nFlags, hBmpUnchecked, hBmpChecked);
}
#endif // !_WIN32_WCE
BOOL CheckMenuRadioItem(UINT nIDFirst, UINT nIDLast, UINT nIDItem, UINT nFlags)
{
ATLASSERT(::IsMenu(m_hMenu));
return ::CheckMenuRadioItem(m_hMenu, nIDFirst, nIDLast, nIDItem, nFlags);
}
BOOL GetMenuItemInfo(UINT uItem, BOOL bByPosition, LPMENUITEMINFO lpmii) const
{
ATLASSERT(::IsMenu(m_hMenu));
return (BOOL)::GetMenuItemInfo(m_hMenu, uItem, bByPosition, lpmii);
}
BOOL SetMenuItemInfo(UINT uItem, BOOL bByPosition, LPMENUITEMINFO lpmii)
{
ATLASSERT(::IsMenu(m_hMenu));
return (BOOL)::SetMenuItemInfo(m_hMenu, uItem, bByPosition, lpmii);
}
#ifndef _WIN32_WCE
BOOL InsertMenuItem(UINT uItem, BOOL bByPosition, LPMENUITEMINFO lpmii)
{
ATLASSERT(::IsMenu(m_hMenu));
return (BOOL)::InsertMenuItem(m_hMenu, uItem, bByPosition, lpmii);
}
UINT GetMenuDefaultItem(BOOL bByPosition = FALSE, UINT uFlags = 0U) const
{
ATLASSERT(::IsMenu(m_hMenu));
return ::GetMenuDefaultItem(m_hMenu, (UINT)bByPosition, uFlags);
}
BOOL SetMenuDefaultItem(UINT uItem = (UINT)-1, BOOL bByPosition = FALSE)
{
ATLASSERT(::IsMenu(m_hMenu));
return ::SetMenuDefaultItem(m_hMenu, uItem, (UINT)bByPosition);
}
BOOL GetMenuItemRect(HWND hWnd, UINT uItem, LPRECT lprcItem) const
{
ATLASSERT(::IsMenu(m_hMenu));
return ::GetMenuItemRect(hWnd, m_hMenu, uItem, lprcItem);
}
int MenuItemFromPoint(HWND hWnd, POINT point) const
{
ATLASSERT(::IsMenu(m_hMenu));
return ::MenuItemFromPoint(hWnd, m_hMenu, point);
}
// Context Help Functions
BOOL SetMenuContextHelpId(DWORD dwContextHelpId)
{
ATLASSERT(::IsMenu(m_hMenu));
return ::SetMenuContextHelpId(m_hMenu, dwContextHelpId);
}
DWORD GetMenuContextHelpId() const
{
ATLASSERT(::IsMenu(m_hMenu));
return ::GetMenuContextHelpId(m_hMenu);
}
#endif // !_WIN32_WCE
};
///////////////////////////////////////////////////////////////////////////////
// CAccelerator
template <bool t_bManaged>
class CAcceleratorT
{
public:
HACCEL m_hAccel;
// Constructor/destructor/operators
CAcceleratorT(HACCEL hAccel = NULL) : m_hAccel(hAccel)
{ }
~CAcceleratorT()
{
if(t_bManaged && m_hAccel != NULL)
::DestroyAcceleratorTable(m_hAccel);
}
CAcceleratorT<t_bManaged>& operator =(HACCEL hAccel)
{
Attach(hAccel);
return *this;
}
void Attach(HACCEL hAccel)
{
if(t_bManaged && m_hAccel != NULL)
::DestroyAcceleratorTable(m_hAccel);
m_hAccel = hAccel;
}
HACCEL Detach()
{
HACCEL hAccel = m_hAccel;
m_hAccel = NULL;
return hAccel;
}
operator HACCEL() const { return m_hAccel; }
bool IsNull() const { return m_hAccel == NULL; }
// Create/destroy methods
HACCEL LoadAccelerators(ATL::_U_STRINGorID accel)
{
ATLASSERT(m_hAccel == NULL);
m_hAccel = ::LoadAccelerators(ModuleHelper::GetResourceInstance(), accel.m_lpstr);
return m_hAccel;
}
HACCEL CreateAcceleratorTable(LPACCEL pAccel, int cEntries)
{
ATLASSERT(m_hAccel == NULL);
ATLASSERT(pAccel != NULL);
m_hAccel = ::CreateAcceleratorTable(pAccel, cEntries);
return m_hAccel;
}
void DestroyObject()
{
if(m_hAccel != NULL)
{
::DestroyAcceleratorTable(m_hAccel);
m_hAccel = NULL;
}
}
// Operations
#ifndef _WIN32_WCE
int CopyAcceleratorTable(LPACCEL lpAccelDst, int cEntries)
{
ATLASSERT(m_hAccel != NULL);
ATLASSERT(lpAccelDst != NULL);
return ::CopyAcceleratorTable(m_hAccel, lpAccelDst, cEntries);
}
int GetEntriesCount() const
{
ATLASSERT(m_hAccel != NULL);
return ::CopyAcceleratorTable(m_hAccel, NULL, 0);
}
#endif // !_WIN32_WCE
BOOL TranslateAccelerator(HWND hWnd, LPMSG pMsg)
{
ATLASSERT(m_hAccel != NULL);
ATLASSERT(::IsWindow(hWnd));
ATLASSERT(pMsg != NULL);
return ::TranslateAccelerator(hWnd, m_hAccel, pMsg);
}
};
typedef CAcceleratorT<false> CAcceleratorHandle;
typedef CAcceleratorT<true> CAccelerator;
///////////////////////////////////////////////////////////////////////////////
// CIcon
template <bool t_bManaged>
class CIconT
{
public:
HICON m_hIcon;
// Constructor/destructor/operators
CIconT(HICON hIcon = NULL) : m_hIcon(hIcon)
{ }
~CIconT()
{
if(t_bManaged && m_hIcon != NULL)
::DestroyIcon(m_hIcon);
}
CIconT<t_bManaged>& operator =(HICON hIcon)
{
Attach(hIcon);
return *this;
}
void Attach(HICON hIcon)
{
if(t_bManaged && m_hIcon != NULL)
::DestroyIcon(m_hIcon);
m_hIcon = hIcon;
}
HICON Detach()
{
HICON hIcon = m_hIcon;
m_hIcon = NULL;
return hIcon;
}
operator HICON() const { return m_hIcon; }
bool IsNull() const { return m_hIcon == NULL; }
// Create/destroy methods
HICON LoadIcon(ATL::_U_STRINGorID icon)
{
ATLASSERT(m_hIcon == NULL);
m_hIcon = ::LoadIcon(ModuleHelper::GetResourceInstance(), icon.m_lpstr);
return m_hIcon;
}
HICON LoadIcon(ATL::_U_STRINGorID icon, int cxDesired, int cyDesired, UINT fuLoad = 0)
{
ATLASSERT(m_hIcon == NULL);
m_hIcon = (HICON) ::LoadImage(ModuleHelper::GetResourceInstance(), icon.m_lpstr, IMAGE_ICON, cxDesired, cyDesired, fuLoad);
return m_hIcon;
}
#ifndef _WIN32_WCE
HICON LoadOEMIcon(LPCTSTR lpstrIconName)
{
ATLASSERT(m_hIcon == NULL);
ATLASSERT(IsOEMIcon(lpstrIconName));
m_hIcon = ::LoadIcon(NULL, lpstrIconName);
return m_hIcon;
}
HICON CreateIcon(int nWidth, int nHeight, BYTE cPlanes, BYTE cBitsPixel, CONST BYTE* lpbANDbits, CONST BYTE *lpbXORbits)
{
ATLASSERT(m_hIcon == NULL);
ATLASSERT(lpbANDbits != NULL);
ATLASSERT(lpbXORbits != NULL);
m_hIcon = ::CreateIcon(ModuleHelper::GetResourceInstance(), nWidth, nHeight, cPlanes, cBitsPixel, lpbANDbits, lpbXORbits);
return m_hIcon;
}
HICON CreateIconFromResource(PBYTE pBits, DWORD dwResSize, DWORD dwVersion = 0x00030000)
{
ATLASSERT(m_hIcon == NULL);
ATLASSERT(pBits != NULL);
m_hIcon = ::CreateIconFromResource(pBits, dwResSize, TRUE, dwVersion);
return m_hIcon;
}
HICON CreateIconFromResourceEx(PBYTE pbBits, DWORD cbBits, DWORD dwVersion = 0x00030000, int cxDesired = 0, int cyDesired = 0, UINT uFlags = LR_DEFAULTCOLOR)
{
ATLASSERT(m_hIcon == NULL);
ATLASSERT(pbBits != NULL);
ATLASSERT(cbBits > 0);
m_hIcon = ::CreateIconFromResourceEx(pbBits, cbBits, TRUE, dwVersion, cxDesired, cyDesired, uFlags);
return m_hIcon;
}
#endif // !_WIN32_WCE
HICON CreateIconIndirect(PICONINFO pIconInfo)
{
ATLASSERT(m_hIcon == NULL);
ATLASSERT(pIconInfo != NULL);
m_hIcon = ::CreateIconIndirect(pIconInfo);
return m_hIcon;
}
#ifndef _WIN32_WCE
HICON ExtractIcon(LPCTSTR lpszExeFileName, UINT nIconIndex)
{
ATLASSERT(m_hIcon == NULL);
ATLASSERT(lpszExeFileName != NULL);
m_hIcon = ::ExtractIcon(ModuleHelper::GetModuleInstance(), lpszExeFileName, nIconIndex);
return m_hIcon;
}
HICON ExtractAssociatedIcon(HINSTANCE hInst, LPTSTR lpIconPath, LPWORD lpiIcon)
{
ATLASSERT(m_hIcon == NULL);
ATLASSERT(lpIconPath != NULL);
ATLASSERT(lpiIcon != NULL);
m_hIcon = ::ExtractAssociatedIcon(hInst, lpIconPath, lpiIcon);
return m_hIcon;
}
#endif // !_WIN32_WCE
BOOL DestroyIcon()
{
ATLASSERT(m_hIcon != NULL);
BOOL bRet = ::DestroyIcon(m_hIcon);
if(bRet != FALSE)
m_hIcon = NULL;
return bRet;
}
// Operations
#ifndef _WIN32_WCE
HICON CopyIcon()
{
ATLASSERT(m_hIcon != NULL);
return ::CopyIcon(m_hIcon);
}
HICON DuplicateIcon()
{
ATLASSERT(m_hIcon != NULL);
return ::DuplicateIcon(NULL, m_hIcon);
}
#endif // !_WIN32_WCE
BOOL DrawIcon(HDC hDC, int x, int y)
{
ATLASSERT(m_hIcon != NULL);
#ifndef _WIN32_WCE
return ::DrawIcon(hDC, x, y, m_hIcon);
#else // CE specific
return ::DrawIconEx(hDC, x, y, m_hIcon, 0, 0, 0, NULL, DI_NORMAL);
#endif // _WIN32_WCE
}
BOOL DrawIcon(HDC hDC, POINT pt)
{
ATLASSERT(m_hIcon != NULL);
#ifndef _WIN32_WCE
return ::DrawIcon(hDC, pt.x, pt.y, m_hIcon);
#else // CE specific
return ::DrawIconEx(hDC, pt.x, pt.y, m_hIcon, 0, 0, 0, NULL, DI_NORMAL);
#endif // _WIN32_WCE
}
BOOL DrawIconEx(HDC hDC, int x, int y, int cxWidth, int cyWidth, UINT uStepIfAniCur = 0, HBRUSH hbrFlickerFreeDraw = NULL, UINT uFlags = DI_NORMAL)
{
ATLASSERT(m_hIcon != NULL);
return ::DrawIconEx(hDC, x, y, m_hIcon, cxWidth, cyWidth, uStepIfAniCur, hbrFlickerFreeDraw, uFlags);
}
BOOL DrawIconEx(HDC hDC, POINT pt, SIZE size, UINT uStepIfAniCur = 0, HBRUSH hbrFlickerFreeDraw = NULL, UINT uFlags = DI_NORMAL)
{
ATLASSERT(m_hIcon != NULL);
return ::DrawIconEx(hDC, pt.x, pt.y, m_hIcon, size.cx, size.cy, uStepIfAniCur, hbrFlickerFreeDraw, uFlags);
}
#ifndef _WIN32_WCE
BOOL GetIconInfo(PICONINFO pIconInfo) const
{
ATLASSERT(m_hIcon != NULL);
ATLASSERT(pIconInfo != NULL);
return ::GetIconInfo(m_hIcon, pIconInfo);
}
#if (_WIN32_WINNT >= 0x0600)
BOOL GetIconInfoEx(PICONINFOEX pIconInfo) const
{
ATLASSERT(m_hIcon != NULL);
ATLASSERT(pIconInfo != NULL);
return ::GetIconInfoEx(m_hIcon, pIconInfo);
}
#endif // (_WIN32_WINNT >= 0x0600)
#if defined(NTDDI_VERSION) && (NTDDI_VERSION >= NTDDI_LONGHORN)
HRESULT LoadIconMetric(ATL::_U_STRINGorID icon, int lims)
{
ATLASSERT(m_hIcon == NULL);
USES_CONVERSION;
return ::LoadIconMetric(ModuleHelper::GetResourceInstance(), T2CW(icon.m_lpstr), lims, &m_hIcon);
}
HRESULT LoadIconWithScaleDown(ATL::_U_STRINGorID icon, int cx, int cy)
{
ATLASSERT(m_hIcon == NULL);
USES_CONVERSION;
return ::LoadIconWithScaleDown(ModuleHelper::GetResourceInstance(), T2CW(icon.m_lpstr), cx, cy, &m_hIcon);
}
HRESULT LoadOEMIconMetric(LPCTSTR lpstrIconName, int lims)
{
ATLASSERT(m_hIcon == NULL);
ATLASSERT(IsOEMIcon(lpstrIconName));
return ::LoadIconMetric(NULL, (LPCWSTR)lpstrIconName, lims, &m_hIcon);
}
HRESULT LoadOEMIconWithScaleDown(LPCTSTR lpstrIconName, int cx, int cy)
{
ATLASSERT(m_hIcon == NULL);
ATLASSERT(IsOEMIcon(lpstrIconName));
USES_CONVERSION;
return ::LoadIconWithScaleDown(NULL, (LPCWSTR)lpstrIconName, cx, cy, &m_hIcon);
}
#endif // defined(NTDDI_VERSION) && (NTDDI_VERSION >= NTDDI_LONGHORN)
#endif // !_WIN32_WCE
// Helper
#ifndef _WIN32_WCE
static bool IsOEMIcon(LPCTSTR lpstrIconName)
{
#if (WINVER >= 0x0600)
return (lpstrIconName == IDI_APPLICATION || lpstrIconName == IDI_ASTERISK || lpstrIconName == IDI_EXCLAMATION ||
lpstrIconName == IDI_HAND || lpstrIconName == IDI_QUESTION || lpstrIconName == IDI_WINLOGO ||
lpstrIconName == IDI_SHIELD);
#else // !(WINVER >= 0x0600)
return (lpstrIconName == IDI_APPLICATION || lpstrIconName == IDI_ASTERISK || lpstrIconName == IDI_EXCLAMATION ||
lpstrIconName == IDI_HAND || lpstrIconName == IDI_QUESTION || lpstrIconName == IDI_WINLOGO);
#endif // !(WINVER >= 0x0600)
}
#endif // !_WIN32_WCE
};
typedef CIconT<false> CIconHandle;
typedef CIconT<true> CIcon;
///////////////////////////////////////////////////////////////////////////////
// CCursor
// protect template member from a winuser.h macro
#ifdef CopyCursor
#undef CopyCursor
#endif
template <bool t_bManaged>
class CCursorT
{
public:
HCURSOR m_hCursor;
// Constructor/destructor/operators
CCursorT(HCURSOR hCursor = NULL) : m_hCursor(hCursor)
{ }
~CCursorT()
{
if(t_bManaged && m_hCursor != NULL)
DestroyCursor();
}
CCursorT<t_bManaged>& operator =(HCURSOR hCursor)
{
Attach(hCursor);
return *this;
}
void Attach(HCURSOR hCursor)
{
if(t_bManaged && m_hCursor != NULL)
DestroyCursor();
m_hCursor = hCursor;
}
HCURSOR Detach()
{
HCURSOR hCursor = m_hCursor;
m_hCursor = NULL;
return hCursor;
}
operator HCURSOR() const { return m_hCursor; }
bool IsNull() const { return m_hCursor == NULL; }
// Create/destroy methods
HCURSOR LoadCursor(ATL::_U_STRINGorID cursor)
{
ATLASSERT(m_hCursor == NULL);
m_hCursor = ::LoadCursor(ModuleHelper::GetResourceInstance(), cursor.m_lpstr);
return m_hCursor;
}
HCURSOR LoadSysCursor(LPCTSTR lpstrCursorName)
{
ATLASSERT(m_hCursor == NULL);
#if (WINVER >= 0x0500)
ATLASSERT(lpstrCursorName == IDC_ARROW || lpstrCursorName == IDC_IBEAM || lpstrCursorName == IDC_WAIT ||
lpstrCursorName == IDC_CROSS || lpstrCursorName == IDC_UPARROW || lpstrCursorName == IDC_SIZE ||
lpstrCursorName == IDC_ICON || lpstrCursorName == IDC_SIZENWSE || lpstrCursorName == IDC_SIZENESW ||
lpstrCursorName == IDC_SIZEWE || lpstrCursorName == IDC_SIZENS || lpstrCursorName == IDC_SIZEALL ||
lpstrCursorName == IDC_NO || lpstrCursorName == IDC_APPSTARTING || lpstrCursorName == IDC_HELP ||
lpstrCursorName == IDC_HAND);
#else // !(WINVER >= 0x0500)
ATLASSERT(lpstrCursorName == IDC_ARROW || lpstrCursorName == IDC_IBEAM || lpstrCursorName == IDC_WAIT ||
lpstrCursorName == IDC_CROSS || lpstrCursorName == IDC_UPARROW || lpstrCursorName == IDC_SIZE ||
lpstrCursorName == IDC_ICON || lpstrCursorName == IDC_SIZENWSE || lpstrCursorName == IDC_SIZENESW ||
lpstrCursorName == IDC_SIZEWE || lpstrCursorName == IDC_SIZENS || lpstrCursorName == IDC_SIZEALL ||
lpstrCursorName == IDC_NO || lpstrCursorName == IDC_APPSTARTING || lpstrCursorName == IDC_HELP);
#endif // !(WINVER >= 0x0500)
m_hCursor = ::LoadCursor(NULL, lpstrCursorName);
return m_hCursor;
}
// deprecated
HCURSOR LoadOEMCursor(LPCTSTR lpstrCursorName)
{
return LoadSysCursor(lpstrCursorName);
}
HCURSOR LoadCursor(ATL::_U_STRINGorID cursor, int cxDesired, int cyDesired, UINT fuLoad = 0)
{
ATLASSERT(m_hCursor == NULL);
m_hCursor = (HCURSOR) ::LoadImage(ModuleHelper::GetResourceInstance(), cursor.m_lpstr, IMAGE_CURSOR, cxDesired, cyDesired, fuLoad);
return m_hCursor;
}
#ifndef _WIN32_WCE
HCURSOR LoadCursorFromFile(LPCTSTR pstrFilename)
{
ATLASSERT(m_hCursor == NULL);
ATLASSERT(pstrFilename != NULL);
m_hCursor = ::LoadCursorFromFile(pstrFilename);
return m_hCursor;
}
#endif // !_WIN32_WCE
#if !defined(_WIN32_WCE) || ((_WIN32_WCE >= 0x400) && !(defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP)))
HCURSOR CreateCursor(int xHotSpot, int yHotSpot, int nWidth, int nHeight, CONST VOID *pvANDPlane, CONST VOID *pvXORPlane)
{
ATLASSERT(m_hCursor == NULL);
m_hCursor = ::CreateCursor(ModuleHelper::GetResourceInstance(), xHotSpot, yHotSpot, nWidth, nHeight, pvANDPlane, pvXORPlane);
return m_hCursor;
}
#endif // !defined(_WIN32_WCE) || ((_WIN32_WCE >= 0x400) && !(defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP)))
#ifndef _WIN32_WCE
HCURSOR CreateCursorFromResource(PBYTE pBits, DWORD dwResSize, DWORD dwVersion = 0x00030000)
{
ATLASSERT(m_hCursor == NULL);
ATLASSERT(pBits != NULL);
m_hCursor = (HCURSOR)::CreateIconFromResource(pBits, dwResSize, FALSE, dwVersion);
return m_hCursor;
}
HCURSOR CreateCursorFromResourceEx(PBYTE pbBits, DWORD cbBits, DWORD dwVersion = 0x00030000, int cxDesired = 0, int cyDesired = 0, UINT uFlags = LR_DEFAULTCOLOR)
{
ATLASSERT(m_hCursor == NULL);
ATLASSERT(pbBits != NULL);
ATLASSERT(cbBits > 0);
m_hCursor = (HCURSOR)::CreateIconFromResourceEx(pbBits, cbBits, FALSE, dwVersion, cxDesired, cyDesired, uFlags);
return m_hCursor;
}
#endif // !_WIN32_WCE
BOOL DestroyCursor()
{
ATLASSERT(m_hCursor != NULL);
#if !defined(_WIN32_WCE) || ((_WIN32_WCE >= 0x400) && !(defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP)))
BOOL bRet = ::DestroyCursor(m_hCursor);
if(bRet != FALSE)
m_hCursor = NULL;
return bRet;
#else // !(!defined(_WIN32_WCE) || ((_WIN32_WCE >= 0x400) && !(defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP))))
ATLTRACE2(atlTraceUI, 0, _T("Warning: This version of Windows CE does not have ::DestroyCursor()\n"));
return FALSE;
#endif // !(!defined(_WIN32_WCE) || ((_WIN32_WCE >= 0x400) && !(defined(WIN32_PLATFORM_PSPC) || defined(WIN32_PLATFORM_WFSP))))
}
// Operations
#ifndef _WIN32_WCE
HCURSOR CopyCursor()
{
ATLASSERT(m_hCursor != NULL);
return (HCURSOR)::CopyIcon((HICON)m_hCursor);
}
#endif // !_WIN32_WCE
#if (WINVER >= 0x0500) && !defined(_WIN32_WCE)
BOOL GetCursorInfo(LPCURSORINFO pCursorInfo)
{
ATLASSERT(m_hCursor != NULL);
ATLASSERT(pCursorInfo != NULL);
return ::GetCursorInfo(pCursorInfo);
}
#endif // (WINVER >= 0x0500) && !defined(_WIN32_WCE)
};
typedef CCursorT<false> CCursorHandle;
typedef CCursorT<true> CCursor;
///////////////////////////////////////////////////////////////////////////////
// CResource - Wraps a generic Windows resource.
// Use it with custom resource types other than the
// standard RT_CURSOR, RT_BITMAP, etc.
class CResource
{
public:
HGLOBAL m_hGlobal;
HRSRC m_hResource;
// Constructor/destructor
CResource() : m_hGlobal(NULL), m_hResource(NULL)
{ }
~CResource()
{
Release();
}
// Load methods
bool Load(ATL::_U_STRINGorID Type, ATL::_U_STRINGorID ID)
{
ATLASSERT(m_hResource == NULL);
ATLASSERT(m_hGlobal == NULL);
m_hResource = ::FindResource(ModuleHelper::GetResourceInstance(), ID.m_lpstr, Type.m_lpstr);
if(m_hResource == NULL)
return false;
m_hGlobal = ::LoadResource(ModuleHelper::GetResourceInstance(), m_hResource);
if(m_hGlobal == NULL)
{
m_hResource = NULL;
return false;
}
return true;
}
#ifndef _WIN32_WCE
bool LoadEx(ATL::_U_STRINGorID Type, ATL::_U_STRINGorID ID, WORD wLanguage)
{
ATLASSERT(m_hResource == NULL);
ATLASSERT(m_hGlobal == NULL);
m_hResource = ::FindResourceEx(ModuleHelper::GetResourceInstance(), ID.m_lpstr, Type.m_lpstr, wLanguage);
if(m_hResource == NULL)
return false;
m_hGlobal = ::LoadResource(ModuleHelper::GetResourceInstance(), m_hResource);
if(m_hGlobal == NULL)
{
m_hResource = NULL;
return false;
}
return true;
}
#endif // !_WIN32_WCE
// Misc. operations
DWORD GetSize() const
{
ATLASSERT(m_hResource != NULL);
return ::SizeofResource(ModuleHelper::GetResourceInstance(), m_hResource);
}
LPVOID Lock()
{
ATLASSERT(m_hResource != NULL);
ATLASSERT(m_hGlobal != NULL);
LPVOID pVoid = ::LockResource(m_hGlobal);
ATLASSERT(pVoid != NULL);
return pVoid;
}
void Release()
{
if(m_hGlobal != NULL)
{
FreeResource(m_hGlobal);
m_hGlobal = NULL;
m_hResource = NULL;
}
}
};
}; // namespace WTL
#endif // __ATLUSER_H__
| [
"carlco@gmail.com"
] | carlco@gmail.com |
6f2db408f014efef46cb75e9e5485a49bce9fca0 | 8f9e7d1b57b4fa28ea067d71d4b1a72763af035e | /include/Gaffer/DeleteContextVariables.h | c7f7069375faf5be1891c5b6e4e2250b1b80f27e | [
"BSD-3-Clause"
] | permissive | hradec/gaffer | e4e798739b45df624595c9980b8c649cea04522c | 43ea3477775a4c425501f082548b67e8a1526273 | refs/heads/master | 2023-04-28T15:29:15.015254 | 2022-05-24T23:34:29 | 2022-05-24T23:34:29 | 9,508,356 | 0 | 1 | BSD-3-Clause | 2021-09-09T21:19:26 | 2013-04-17T21:52:17 | Python | UTF-8 | C++ | false | false | 2,768 | h | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2017, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided with
// the distribution.
//
// * Neither the name of John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#ifndef GAFFER_DELETECONTEXTVARIABLES_H
#define GAFFER_DELETECONTEXTVARIABLES_H
#include "Gaffer/ContextProcessor.h"
#include "Gaffer/StringPlug.h"
namespace Gaffer
{
class IECORE_EXPORT DeleteContextVariables : public ContextProcessor
{
public :
GAFFER_NODE_DECLARE_TYPE( Gaffer::DeleteContextVariables, DeleteContextVariablesTypeId, ContextProcessor );
DeleteContextVariables( const std::string &name=GraphComponent::defaultName<DeleteContextVariables>() );
~DeleteContextVariables() override;
StringPlug *variablesPlug();
const StringPlug *variablesPlug() const;
protected :
bool affectsContext( const Plug *input ) const override;
void processContext( Context::EditableScope &context, IECore::ConstRefCountedPtr &storage ) const override;
private :
static size_t g_firstPlugIndex;
};
IE_CORE_DECLAREPTR( DeleteContextVariables );
} // namespace Gaffer
#endif // GAFFER_DELETECONTEXTVARIABLES_H
| [
"thehaddonyoof@gmail.com"
] | thehaddonyoof@gmail.com |
cf9fde57a06ff32799e85131340aa0798a2dc4aa | f0280623b3b6cd80fa3a1102bf911e5cc736cc2b | /QtRptProject/QtRptDemo/tmp-lin64/ui_exampledlg8.h | 57c9bcfc8d4d3883027d29a9b0845a93e6823d38 | [] | no_license | xman199775/jeanscar | 1aea4dd5b35bab07462e2af3dfc98ee7813720fa | 1170c165ad0d6e50829d3d5db618406326a83c51 | refs/heads/master | 2021-05-05T06:09:14.336541 | 2018-06-25T12:49:52 | 2018-06-25T12:49:52 | 113,491,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,714 | h | /********************************************************************************
** Form generated from reading UI file 'exampledlg8.ui'
**
** Created by: Qt User Interface Compiler version 5.5.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_EXAMPLEDLG8_H
#define UI_EXAMPLEDLG8_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QTableWidget>
#include <QtWidgets/QVBoxLayout>
QT_BEGIN_NAMESPACE
class Ui_ExampleDlg8
{
public:
QVBoxLayout *verticalLayout;
QTableWidget *tableWidget;
QHBoxLayout *horizontalLayout;
QSpacerItem *horizontalSpacer;
QPushButton *btnPrint;
QPushButton *btnClose;
void setupUi(QDialog *ExampleDlg8)
{
if (ExampleDlg8->objectName().isEmpty())
ExampleDlg8->setObjectName(QStringLiteral("ExampleDlg8"));
ExampleDlg8->resize(697, 382);
verticalLayout = new QVBoxLayout(ExampleDlg8);
verticalLayout->setObjectName(QStringLiteral("verticalLayout"));
tableWidget = new QTableWidget(ExampleDlg8);
if (tableWidget->columnCount() < 2)
tableWidget->setColumnCount(2);
QTableWidgetItem *__qtablewidgetitem = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(0, __qtablewidgetitem);
QTableWidgetItem *__qtablewidgetitem1 = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(1, __qtablewidgetitem1);
tableWidget->setObjectName(QStringLiteral("tableWidget"));
tableWidget->horizontalHeader()->setVisible(true);
tableWidget->horizontalHeader()->setStretchLastSection(true);
tableWidget->verticalHeader()->setVisible(false);
verticalLayout->addWidget(tableWidget);
horizontalLayout = new QHBoxLayout();
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout->addItem(horizontalSpacer);
btnPrint = new QPushButton(ExampleDlg8);
btnPrint->setObjectName(QStringLiteral("btnPrint"));
horizontalLayout->addWidget(btnPrint);
btnClose = new QPushButton(ExampleDlg8);
btnClose->setObjectName(QStringLiteral("btnClose"));
horizontalLayout->addWidget(btnClose);
verticalLayout->addLayout(horizontalLayout);
retranslateUi(ExampleDlg8);
QObject::connect(btnClose, SIGNAL(clicked()), ExampleDlg8, SLOT(close()));
QMetaObject::connectSlotsByName(ExampleDlg8);
} // setupUi
void retranslateUi(QDialog *ExampleDlg8)
{
ExampleDlg8->setWindowTitle(QApplication::translate("ExampleDlg8", "Dialog", 0));
QTableWidgetItem *___qtablewidgetitem = tableWidget->horizontalHeaderItem(0);
___qtablewidgetitem->setText(QApplication::translate("ExampleDlg8", "No", 0));
QTableWidgetItem *___qtablewidgetitem1 = tableWidget->horizontalHeaderItem(1);
___qtablewidgetitem1->setText(QApplication::translate("ExampleDlg8", "Text", 0));
btnPrint->setText(QApplication::translate("ExampleDlg8", "Print", 0));
btnClose->setText(QApplication::translate("ExampleDlg8", "Close", 0));
} // retranslateUi
};
namespace Ui {
class ExampleDlg8: public Ui_ExampleDlg8 {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_EXAMPLEDLG8_H
| [
"xman199775@gmail.com"
] | xman199775@gmail.com |
db40264c59d3a4cad748d42911242b13f8d81c52 | 2ba94892764a44d9c07f0f549f79f9f9dc272151 | /Engine/Source/Editor/UnrealEd/Public/EditorActorFolders.h | 257f6a08f270fe8bcacfad25401324a1ca5d3e16 | [
"BSD-2-Clause",
"LicenseRef-scancode-proprietary-license"
] | permissive | PopCap/GameIdea | 934769eeb91f9637f5bf205d88b13ff1fc9ae8fd | 201e1df50b2bc99afc079ce326aa0a44b178a391 | refs/heads/master | 2021-01-25T00:11:38.709772 | 2018-09-11T03:38:56 | 2018-09-11T03:38:56 | 37,818,708 | 0 | 0 | BSD-2-Clause | 2018-09-11T03:39:05 | 2015-06-21T17:36:44 | null | UTF-8 | C++ | false | false | 4,819 | h | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "EditorActorFolders.generated.h"
/** Multicast delegates for broadcasting various folder events */
DECLARE_MULTICAST_DELEGATE_TwoParams(FOnActorFolderCreate, UWorld&, FName);
DECLARE_MULTICAST_DELEGATE_TwoParams(FOnActorFolderDelete, UWorld&, FName);
DECLARE_MULTICAST_DELEGATE_ThreeParams(FOnActorFolderMove, UWorld&, FName /* src */, FName /* dst */);
USTRUCT()
struct FActorFolderProps
{
GENERATED_USTRUCT_BODY()
FActorFolderProps() : bIsExpanded(true) {}
/** Serializer */
FORCEINLINE friend FArchive& operator<<(FArchive& Ar, FActorFolderProps& Folder)
{
return Ar << Folder.bIsExpanded;
}
bool bIsExpanded;
};
/** Actor Folder UObject. This is used to support undo/redo reliably */
UCLASS()
class UEditorActorFolders : public UObject
{
public:
GENERATED_BODY()
public:
virtual void Serialize(FArchive& Ar) override;
TMap<FName, FActorFolderProps> Folders;
};
/** Class responsible for managing an in-memory representation of actor folders in the editor */
struct UNREALED_API FActorFolders : public FGCObject
{
FActorFolders();
~FActorFolders();
// FGCObject Interface
virtual void AddReferencedObjects(FReferenceCollector& Collector) override;
// End FGCObject Interface
/** Check whether the singleton is valid */
static bool IsAvailable() { return Singleton != nullptr; }
/** Singleton access - only valid if IsAvailable() */
static FActorFolders& Get();
/** Initialize the singleton instance - called on Editor Startup */
static void Init();
/** Clean up the singleton instance - called on Editor Exit */
static void Cleanup();
/** Folder creation and deletion events. Called whenever a folder is created or deleted in a world. */
static FOnActorFolderCreate OnFolderCreate;
static FOnActorFolderMove OnFolderMove;
static FOnActorFolderDelete OnFolderDelete;
/** Check if the specified path is a child of the specified parent */
static bool PathIsChildOf(const FString& InPotentialChild, const FString& InParent);
/** Get a map of folder properties for the specified world (map of folder path -> properties) */
const TMap<FName, FActorFolderProps>& GetFolderPropertiesForWorld(UWorld& InWorld);
/** Get the folder properties for the specified path. Returns nullptr if no properties exist */
FActorFolderProps* GetFolderProperties(UWorld& InWorld, FName InPath);
/** Get a default folder name under the specified parent path */
FName GetDefaultFolderName(UWorld& InWorld, FName ParentPath = FName());
/** Get a new default folder name that would apply to the current selection */
FName GetDefaultFolderNameForSelection(UWorld& InWorld);
/** Create a new folder in the specified world, of the specified path */
void CreateFolder(UWorld& InWorld, FName Path);
/** Same as CreateFolder, but moves the current actor selection into the new folder as well */
void CreateFolderContainingSelection(UWorld& InWorld, FName Path);
/** Sets the folder path for all the selected actors */
void SetSelectedFolderPath(FName Path) const;
/** Delete the specified folder in the world */
void DeleteFolder(UWorld& InWorld, FName FolderToDelete);
/** Rename the specified path to a new name */
bool RenameFolderInWorld(UWorld& World, FName OldPath, FName NewPath);
private:
/** Returns true if folders have been created for the specified world */
bool FoldersExistForWorld(UWorld& InWorld) const;
/** Get or create a folder container for the specified world */
UEditorActorFolders& GetOrCreateFoldersForWorld(UWorld& InWorld);
/** Create and update a folder container for the specified world */
UEditorActorFolders& InitializeForWorld(UWorld& InWorld);
/** Rebuild the folder list for the specified world. This can be very slow as it
iterates all actors in memory to rebuild the array of actors for this world */
void RebuildFolderListForWorld(UWorld& InWorld);
/** Called when an actor's folder has changed */
void OnActorFolderChanged(const AActor* InActor, FName OldPath);
/** Called when the actor list of the current world has changed */
void OnLevelActorListChanged();
/** Called when the global map in the editor has changed */
void OnMapChange(uint32 MapChangeFlags);
/** Called after a world has been saved */
void OnWorldSaved(uint32 SaveFlags, UWorld* World, bool bSuccess);
/** Remove any references to folder arrays for dead worlds */
void Housekeeping();
/** Add a folder to the folder map for the specified world. Does not trigger any events. */
bool AddFolderToWorld(UWorld& InWorld, FName Path);
/** Transient map of folders, keyed on world pointer */
TMap<TWeakObjectPtr<UWorld>, UEditorActorFolders*> TemporaryWorldFolders;
/** Singleton instance maintained by the editor */
static FActorFolders* Singleton;
};
| [
"dkroell@acm.org"
] | dkroell@acm.org |
4322060529410eb9696d976673e89dde05b5c288 | 9e0225ec9ddea38ac9ea8f4b1920c93dce51b7ef | /codeeditor.h | ebc1f28a7ad93a9d605e0d16b6da89c8e1686018 | [] | no_license | vooron/Translator | c8322ab272c5dc9d3fbf2842efe5e66c530ec7f7 | 6b2a8a1276e4c2d8ddd770924dd5ec7b8d8bc892 | refs/heads/master | 2020-05-18T14:22:47.328136 | 2019-05-01T19:20:21 | 2019-05-01T19:20:21 | 184,468,424 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,189 | h | #ifndef CODEEDITOR_H
#define CODEEDITOR_H
#include <QPlainTextEdit>
#include <QObject>
#include <QDebug>
class QPaintEvent;
class QResizeEvent;
class QSize;
class QWidget;
class LineNumberArea;
class CodeEditor : public QPlainTextEdit
{
Q_OBJECT
public:
CodeEditor(QWidget *parent = nullptr);
void lineNumberAreaPaintEvent(QPaintEvent *event);
int lineNumberAreaWidth();
protected:
void resizeEvent(QResizeEvent *event) override;
private slots:
void updateLineNumberAreaWidth(int newBlockCount);
void highlightCurrentLine();
void updateLineNumberArea(const QRect &, int);
void highlightSyntax();
private:
QWidget *lineNumberArea;
};
class LineNumberArea : public QWidget
{
public:
LineNumberArea(CodeEditor *editor) : QWidget(editor) {
codeEditor = editor;
}
QSize sizeHint() const override {
return QSize(codeEditor->lineNumberAreaWidth(), 0);
}
protected:
void paintEvent(QPaintEvent *event) override {
codeEditor->lineNumberAreaPaintEvent(event);
}
private:
CodeEditor *codeEditor;
};
#endif // CODEEDITOR_H
| [
"noreply@github.com"
] | noreply@github.com |
659a85b278dd3a67ca50f3949c9c0ede1f4a76c4 | 6a4eae1058b066ca2240c5846ea3c645325aad6d | /enddialog.cpp | 64cc280e2afc3eaac20ccf8dfd205125674bf026 | [] | no_license | tohlh/Summer2021-Homework-1-Qt-Battle-Chess | 0c62ad2f5987e8d54d48b205d3cf17c5ceb76671 | 9b3963eac95a3506857badd53d83de7681652ada | refs/heads/master | 2023-07-15T04:45:41.505823 | 2021-08-28T08:32:25 | 2021-08-28T08:32:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 435 | cpp | #include "enddialog.h"
#include "ui_enddialog.h"
EndDialog::EndDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::EndDialog)
{
ui->setupUi(this);
}
EndDialog::~EndDialog()
{
delete ui;
}
void EndDialog::setWinColor(QString color)
{
QString text = QString("%1 wins!").arg(color);
ui->winTeam->setText(text);
}
void EndDialog::noWinner()
{
ui->winTeam->setText("Colors are not decided. No winner!");
}
| [
"tohliheng@gmail.com"
] | tohliheng@gmail.com |
0879bd71d77585047917ce5f968d2c0ef07c4aa6 | da0d1f0111b764ea2b15f4c296b55beb75b84bb4 | /Compiler/SemanticAction.cpp | fc0abb32ca6c20539b283d21665afa0ec5c83896 | [] | no_license | powellm123/Compiler | b75e5c2cd139c875a234b6fbde826791a3a7d150 | d01e66e2c67ab1affb8a8a0cfe223c1b02e73033 | refs/heads/master | 2021-05-27T16:43:49.408794 | 2012-05-10T21:05:11 | 2012-05-10T21:05:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,837 | cpp | #include "SemanticAction.h"
#include "symbleTable.h"
#include "Icode.h"
#include "syntax.h"
#include <vector>
namespace SemanticAction
{
////////////////Vars///////////////////////////
struct oper
{
string op;
int presidence;
};
static vector<sar*> SAStack;
static vector<oper> OPStack;
static int tempnumber = 0;
static string currentScope;
static int ERRORS = 0;
static int linenum = 0;
//for ICODE
//static vector<string> commands;
///////////////////////////////////////////////
///////////Helper function/////////////////////
void setlinenum(int x)
{
linenum = x;
}
const int& getlinenumber()
{
return linenum;
}
const int& getErrors()
{
return ERRORS;
}
void gen_error(const string& str)
{
cerr<<linenum << " SA ERROR: " << str<<endl;
ERRORS++;
}
void gen_error(const string& str, sar* s)
{
if(s->_id().scope != "")
cerr<<linenum<<" SA ERROR: "<<str<<" scope " << s->_id().scope<<" value " << s->_id().value <<endl;
else
cerr<<linenum<<" SA ERROR: A Symble is not Defined"<<endl;
ERRORS++;
}
void gen_error(const string& str, sar* s1, sar* s2)
{
cerr<<linenum<<" SA ERROR: "<<str<<" scope " << s1->_id().scope<<" value " << s1->_id().value <<" AND "
<<"scope " << s2->_id().scope<<" value " << s2->_id().value <<endl;
ERRORS++;
}
sar* gensym(const symbleTable::identifertype& id,const string& type, char symid = 't')
{
symbleTable::identifertype tid = id;
//if(symid == 'R')
// tid.data.type = "int";
//else
tid.data.type = type;
stringstream ss;
ss << tempnumber++;
tid.value = symid + ss.str();
tid.symid = symid + symbleTable::get_valuenumber();
tid.scope = syntax::get_scope();
tid.kind = id.kind;
symbleTable::putinSymTbl(tid.scope, tid);
return new sar(tid);
}
bool checkbool(sar* s)
{
return s->_id().data.type == "bool";
}
bool foundintable(sar *s)
{
return symbleTable::check_in_symbletable(s->_id().scope, s->_id().value);
}
bool checkinscope(sar* s1, sar* s2)
{
string scope = "g." + s1->_id().data.type;
return symbleTable::check_in_symbletable(scope, s2->_id().value);
}
symbleTable::identifertype getinscope(sar* s1, sar* s2)
{
string scope = "g." + s1->_id().data.type;
return symbleTable::get_symTbl(scope, s2->_id().value); // symbleTable::get_from_symbletable(scope, s2->_id().value);
}
int findPres(string op)
{
switch (op[0])
{
case '*':
case '/':
return 13;
case '+':
case '-':
return 11;
case '<':
case '>':
return 9;
case '!':
case '=':
if(op.size() > 1 && op[1] == '=')
return 7;
return 1;
case '(':
case '[':
return 15;
}
return 0;
}
void doSemAct(const oper &t)
{
switch (t.op[0])
{
case '*':
_star();
break;
case '/':
_div();
break;
case '+':
_plus();
break;
case '-':
_sub();
break;
case '<':
if(t.op == "<=")
_lessequal();
else
_less();
break;
case '>':
if(t.op == ">=")
_greaterequal();
else
_greater();
break;
case '=':
if(t.op == "==")
_equalequal();
else
_equal();
break;
case '(':
break;
case '[':
break;
default:
if(t.op == "&&")
_and();
if(t.op == "||")
_or();
if(t.op == "!=")
_notEqual();
break;
}
}
sar* pop_sar()
{
if(SAStack.empty()){
// gen_error("Nothing on the Semantic Action Stack");
return new sar();
}
sar *top_sar = SAStack.back();
SAStack.pop_back();
return top_sar;
}
bool sametype(sar *s1, sar *s2)
{
if(s1->_id().data.type == s2->_id().data.type /*|| /*s1->_id().symid.find('R') != -1 || s2->_id().symid.find('R') != -1*/ || s1->_id().value == "null" || s2->_id().value == "null" )
return true;
return false;
}
void setScope(const string& str)
{
currentScope = str;
}
bool foundFunc(const string& fun)
{
return symbleTable::funsign(fun);
}
////////////////////////////////////////////////////////////////
symbleTable::identifertype Get_topSASid()
{
return SAStack.back()->_id();
}
//////////////////SemanticAction functions//////////////////////
////////////////////////////////////////////////////
////////PUSH action/////////////////////////////////////////////
void _iPush(const symbleTable::identifertype &id){ // Identifier Push
SAStack.push_back(new id_sar(id));
}
void _lPush(const string& str, const string& type){ // Literal Push
sar* lsar = new lit_sar(str);
lsar->_id() = symbleTable::get_symTbl(symbleTable::get_symTbl("g", str).symid); //.data.type = type;
//lsar->_id().scope = "g";
//lsar->_id().symid = "l" + symbleTable::get_valuenumber();
//lsar->_id().kind = symbleTable::Kinds.noneK;
//lsar->_id().data.accessMod = symbleTable::AccessMod._public;
SAStack.push_back(lsar);
}
void _oPush(const string &operat){ // Operator Push
oper temp;
temp.op = operat;
temp.presidence = findPres(operat);
while(!OPStack.empty() && (OPStack.back().presidence >= temp.presidence))
{
doSemAct(OPStack.back());
OPStack.pop_back();
}
if(temp.presidence == 15)
temp.presidence = -1;
OPStack.push_back(temp);
}
void _tPush(const string &str){ // Type Push
SAStack.push_back(new type_sar(str));
}
void _vPush(const symbleTable::identifertype &id){ // Variable Push
SAStack.push_back(new sar(id));
}
/////////////////////////////////////
/////////Exist action////////////////
void _iExist(const string& scope){ // Identifier Exists
// Pop the top SAR (e.g., top_sar = SAS.pop()) \
// from the SAS. The top SAR can be a simple variable,\
// a function call or an array reference.\
// Test if the top SAR exists in the current scope. \
// Push a SAR onto the SAS to indicate that the \
// identifier exists (e.g., SAS.push(id_sar)) \
// or generate an error.
sar *top_sar = pop_sar();
if(top_sar->type == 4)
{
//auto idsar = new id_sar(symbleTable::get_symTbl(top_sar->_id().scope, top_sar->_id().value));
//idsar->_id().data.type = idsar->_id().data.type.substr(2, idsar->_id().data.type.size());
//cerr <<"I am An Array" << top_sar->_id().symid;
arr_sar* idsar = dynamic_cast<arr_sar*>( top_sar);
idsar->_id().data.type = idsar->_id().data.type.substr(2, idsar->_id().data.type.size());
auto arrayId = top_sar->_id();
string a;
if(arrayId.data.type == "int" || arrayId.data.type == "char" || arrayId.data.type == "bool" ){
idsar->_id().kind = symbleTable::Aref;
//a = "Aref";
}
else{
idsar->_id().kind = symbleTable::CAref;
//a = "CAref";
}
sar *temp = gensym(idsar->_id(), idsar->_id().data.type, 'R');
//cerr << "i am a " << a<<endl;
Icode_h::Math("ADD", arrayId.symid, idsar->exp->_id().symid, temp->_id().symid);
SAStack.push_back(temp);
} else if(top_sar->type == 5) //Kinds.Func
{
if(foundintable(top_sar)){
Icode_h::frame(top_sar->_id().symid, "this");
//SAStack.push_back(new id_sar(symbleTable::get_symTbl(top_sar->_id().scope, top_sar->_id().value)));
//cerr <<"I am A function" << top_sar->_id().symid;
func_sar* fs = dynamic_cast<func_sar*>( top_sar);
vector<string> prams;
for(vector<symbleTable::identifertype>::iterator arg = fs->theArgs().begin(); arg != fs->theArgs().end(); arg++)
{
prams.push_back(arg->symid);
}
// NOTE: Trying to add () on the end of DemoC
while( !prams.empty())
{
Icode_h::push(prams.back());
prams.pop_back();
}
Icode_h::call(top_sar->_id().value);
sar *temp = gensym(top_sar->_id(), top_sar->_id().data.type);
SAStack.push_back(temp);
Icode_h::peek(temp->_id().symid);
}
else{
gen_error("Function not defined in table for", top_sar);
return;
}
} else if(top_sar->_id().kind >= 3 || top_sar->_id().kind == symbleTable::Class) // Kinds.ivar through Kinds.tvar
{
if(foundintable(top_sar)){
SAStack.push_back(new id_sar(symbleTable::get_symTbl(top_sar->_id().scope, top_sar->_id().value)));
}
else{
gen_error("Varable not defined in table for", top_sar);
return ;
}
}
else{
gen_error("no defined kind for", top_sar);
return;
}
}
void _rExist(const string& scope, const symbleTable::identifertype& id){ // Member Reference Exists
sar *top_sar = pop_sar();
sar *next_sar = pop_sar();
func_sar *tsar = dynamic_cast<func_sar*>( top_sar);
if(!foundintable(next_sar)){
gen_error("not defined in table for", next_sar);
return ;
}
SAStack.push_back(new id_sar(symbleTable::get_symTbl(next_sar->_id().scope, next_sar->_id().value)));
next_sar = pop_sar();
if(!checkinscope(next_sar, top_sar)){
gen_error("not in scope", top_sar);
return;
}
SAStack.push_back(new id_sar(getinscope(next_sar, top_sar)));
top_sar = pop_sar();
if(top_sar->_id().data.accessMod != symbleTable::AccessMod::_public){
gen_error("not public", top_sar);
return;
}
if(top_sar->_id().kind >= symbleTable::Kinds::ivar &&top_sar->_id().kind <= symbleTable::Kinds::tvar)
{
//if(foundintable(top_sar)){
// SAStack.push_back(new id_sar(symbleTable::get_symTbl(top_sar->_id().scope, top_sar->_id().value)));
//}
//else{
// gen_error("Array not defined in table for", top_sar);
// return;
//}
sar *reftemp = gensym(top_sar->_id(), top_sar->_id().data.type, 'R');
Icode_h::ref(top_sar->_id().symid, next_sar->_id().symid, reftemp->_id().symid);
//SAStack.pop_back();
SAStack.push_back(new ref_sar(reftemp->_id()));
}else if( top_sar->_id().kind == symbleTable::Kinds::Func)
{
sar* templ = new new_sar( tsar);
Icode_h::frame(top_sar->_id().symid, next_sar->_id().symid);
vector<string> prams;
for(vector<symbleTable::identifertype>::iterator arg = tsar->theArgs().begin(); arg != tsar->theArgs().end(); arg++)
{
prams.push_back(arg->symid);
}
while( !prams.empty())
{
Icode_h::push(prams.back());
prams.pop_back();
}
Icode_h::call(templ->_id().value);
sar *temp = gensym(templ->_id(), templ->_id().data.type); // new new_sar(gensym(top_sar->_id(), top_sar->_id().data.type)->_id(), tsar);
SAStack.push_back(temp);
Icode_h::peek(temp->_id().symid);
} else if(top_sar->type == 4)
{
sar *reftemp = gensym(top_sar->_id(), top_sar->_id().data.type, 'R');
reftemp->_id().data.type = reftemp->_id().data.type.substr(2, reftemp->_id().data.type.size());
auto arrayId = top_sar->_id();
sar *temp = gensym(top_sar->_id(), top_sar->_id().data.type);
Icode_h::Math("ADD", arrayId.symid, reftemp->_id().symid, temp->_id().symid);
SAStack.push_back(new ref_sar(reftemp->_id()));
}else{
gen_error("no defined kind", top_sar);
return ;
}
}
void _tExist(const string& scope){ // Type Exists
sar *top_sar = pop_sar();
if(symbleTable::find_nonbasetype(top_sar->_id()) || top_sar->_id().data.type == "int" || top_sar->_id().data.type == "char"
|| top_sar->_id().data.type == "bool" || top_sar->_id().data.type == "void" )
{
}
else
{
gen_error("Not a defined type", top_sar);
}
}
/////////////////////////////////////
/////////Argument List///////////////
void _bal(){ // Beginning of Argument List
SAStack.push_back(new bal_sar("bal"));
}
void _eal(){ // End of Argument List
sar *top_sar;
symbleTable::identifertype id();
al_sar* alsar = new al_sar();
while(!SAStack.empty() && SAStack.back()->_id().value != "bal"){ //if not bal_sar add to al_sar
top_sar = pop_sar();
if(top_sar->_id().symid.find('R') == -1)
alsar->add(top_sar);
else{
alsar->add(top_sar);
//pop_sar();
}
}
alsar->end();
if(SAStack.empty()){
cerr << "ERROR SAStack Empty"<<endl;
return;
}
SAStack.pop_back();
//SAStack.push_
SAStack.push_back(alsar);
}
/////////////////////////////////////
void _func(){ // Function
sar *alsar = pop_sar();
//check if alsr is a al_sar
sar *idsr = pop_sar();
//check if idsr is a id_sar
al_sar* als = dynamic_cast<al_sar*> (alsar);
if(als != nullptr){
SAStack.push_back(new func_sar(idsr, als));
///////ICODE/////
//Icode_h::call(idsr->_id().symid);
////////////////
}
else{
gen_error("isnt a set of aruments", alsar);
return;
}
}
void _arr(){ // Array Reference
sar *exp = pop_sar();
sar *arrayname = pop_sar();
if(exp->_id().data.type != "int"){
gen_error("expresion isnt an int type", exp);
return;
}
auto ids = exp->_id();
ids.data.type = "int";
int size;
string type = arrayname->_id().data.type;
type = type.substr(2, type.size());
if(symbleTable::find_nonbasetype(type))
size = symbleTable::getclassmembersCount(type);
else
if(type == "char")
size = 1;
else
size = 4;
sar *tempamount = gensym(arrayname->_id(), type);
Icode_h::Math("MUL", exp->_id().symid, symbleTable::getLitSymb(size), tempamount->_id().symid);
SAStack.push_back(new arr_sar(arrayname, tempamount));
}
//////////Statment Actions///////////
void _if(){
// If
sar *exp = pop_sar();
if(!checkbool(exp)){
gen_error("not bool", exp);
return;
}
Icode_h::Branch("BF", exp->_id().symid, "if");
//Icode_h::Boolean("BF",
}
void _while(){
//While
sar *exp = pop_sar();
if(!checkbool(exp)){
gen_error("not bool", exp);
return;
}
Icode_h::Branch("BF", exp->_id().symid, "whilen");
}
void _return(const string& scope){
//Return
//sar *exp = pop_sar();
string str = scope.substr(scope.find_last_of(".")+1, scope.size());
string type = symbleTable::findfunctiontypefromscope(scope);
if(!((type == "" && str == "main") || type == "void"))
{
sar *exp = pop_sar();
if(exp->_id().data.type == type)
{
//////Icode/////////
Icode_h::RETURN(exp->_id().symid);
////////////////////
}else{
gen_error("not same type as return type", exp);
return;
}
}
else{
sar *exp = pop_sar();
if(exp->_id().kind != symbleTable::Func && exp->_id().data.type.size() != 0)
gen_error("Function is void can't return anything");
else{
SAStack.push_back(exp);
Icode_h::RTN();
}
}
}
void _cout(){ //Cout
sar *exp = pop_sar();
if(exp->_id().data.type != "char" && exp->_id().data.type != "int"){
gen_error("not char or a int", exp);
return;
}
/////Icode///////
if(exp->_id().data.type == "int")
Icode_h::writeI(exp->_id().symid);
else
Icode_h::writeC(exp->_id().symid);
///////////////////
}
void _cin(){ //Cin
sar *exp = pop_sar();
if(exp->_id().data.type != "char" && exp->_id().data.type != "int"){
gen_error("not char", exp);
return;
}
/////Icode///////
if(exp->_id().data.type == "int")
Icode_h::readI(exp->_id().symid);
else
Icode_h::readC(exp->_id().symid);
///////////////////
}
void _atoi(){ //ASCII To Integer
sar *exp = pop_sar();
if(exp->_id().data.type != "char"){
gen_error("not char", exp);
return;
}
//Push a SAR for the integer onto the SAS.
SAStack.push_back(gensym(exp->_id(), "int"));
}
void _itoa(){ // Integer to ASCII
sar *exp = pop_sar();
if(exp->_id().data.type != "int"){
gen_error("not int", exp);
return;
}
//Push a SAR for the character onto the SAS.
SAStack.push_back(gensym(exp->_id(), "char"));
}
/////////////////////////////////////
///////////New Actions///////////////
void _newObj(){ // New Object
sar *alsr = pop_sar();
al_sar* al = dynamic_cast<al_sar*>(alsr);
if(al != nullptr)
{
sar *tysar = pop_sar();
sar *theobj = pop_sar();
//func_sar* fun =
SAStack.push_back(theobj);
//sar* nsr = gensym(al->_id(),tysar->_id().data.type);
//nsr->_id() = symbleTable::get_symTbl("g." + tysar->_id().data.type, tysar->_id().data.type);
auto ids = symbleTable::get_symTbl("g." + tysar->_id().data.type, tysar->_id().data.type);
id_sar* idsar = new id_sar(ids);
//new_sar* func = new new_sar(idsar, al);
//dynamic_cast<al_sar*>(SAStack.pop_back());
//SAStack.push_back(new new_sar(nsr, al));
Icode_h::newi(idsar->_id().data.type, theobj->_id().symid);
Icode_h::frame(idsar->_id().symid, theobj->_id().symid);
string pr = "(";
vector<string> prams;
auto a = al->theArgs();
for(auto iter = a.begin(); iter != a.end(); ++iter)
{
prams.push_back(iter->symid);
if(iter == a.begin())
pr += iter->data.type;
else
pr += "," + iter->data.type;
}
pr += ")";
string f = idsar->_id().value + pr;
if(foundFunc(f)){
while(!prams.empty())
{
Icode_h::push(prams.back());
prams.pop_back();
}
// func_sar* fs = new func_sar(
// if(foundintable(pr)){
Icode_h::call(idsar->_id().value + pr);
sar *temp = gensym(idsar->_id(), idsar->_id().data.type);
SAStack.push_back(temp);
Icode_h::peek(temp->_id().symid);
}
else
gen_error("No constructor with given set pramaters " + f);
}
else{
gen_error("No Argument list given", alsr);
return;
}
}
void _newarray(const string& scope){ // New Array
sar *exp = pop_sar();
if(exp->_id().data.type != "int")
gen_error("Need int to put as size for Array", exp);
sar *tysar = pop_sar();
string type = tysar->_id().data.type;
if( !symbleTable::find_nonbasetype(type) && type != "int" && type != "char" && type != "bool")
gen_error(type + " is not a defined type");
auto ids = exp->_id();
ids.value += "[]"; // ids.data.type;
ids.data.type = "@:" + tysar->_id().data.type;
ids.scope = scope;
sar *tempamount = gensym(exp->_id(), tysar->_id().data.type);
Icode_h::Math("MUL", symbleTable::getLitSymb(4), exp->_id().symid, tempamount->_id().symid);
sar *temp = gensym(ids, ids.data.type);
Icode_h::newa(tempamount->_id().symid, temp->_id().symid);
SAStack.push_back(new new_sar(temp));
}
void _cd(const string& curclass, const string& str){
// Constructor Declaration
// Check that identifier for the constructor \
// matches the name of the class. \
// Note: The name of the class should be part \
// of the scope in which the constructor is declared.
// sar *topsar = pop_sar();
if(curclass == str)
{
///////ICODE/////
//Icode_h::call(idsr->_id().symid);
////////////////
}
else{
gen_error("Constructior isnt the same of the class name");
return;
}
}
//////////////////////////////////
////////Var Types/////////////////
void _dot(){ // Dot Operator (Not Used)
}
void _cParen(){ // Closing Parenthesis
while(!OPStack.empty() && OPStack.back().op != "(")
{
doSemAct(OPStack.back());
OPStack.pop_back();
}
if(OPStack.empty()){
gen_error("No ( for )");
return;
}
else
OPStack.pop_back();
}
void _cSquBracket(){ // Closing Square Bracket
while(!OPStack.empty() && OPStack.back().op != "[")
{
doSemAct(OPStack.back());
OPStack.pop_back();
}
if(OPStack.empty())
gen_error("No [ for ]");
else
OPStack.pop_back();
}
void _arg(){ // Argument #,
while(!OPStack.empty() && OPStack.back().op != "(")
{
doSemAct(OPStack.back());
OPStack.pop_back();
}
if(OPStack.empty()){
gen_error("No ( for ,");
return;
}
////ICODE/////////
// Icode_h::push(SAStack.back()->_id().symid);
/////////////////
}
void _eoe(bool removeSAS){ // End of Expression
while(!OPStack.empty())
{
doSemAct(OPStack.back());
OPStack.pop_back();
}
while(!SAStack.empty() && removeSAS)
{
SAStack.pop_back();
}
}
////////////////////////////////////
/////////Operator action////////////
void _plus(){ // Add Operator
sar* s1 = pop_sar();
sar* s2 = pop_sar();
if(!sametype(s1, s2)){
gen_error("Not Same Type", s1, s2);
return;
}
else
{
sar *temp = gensym(s2->_id(), s2->_id().data.type);
SAStack.push_back(temp);
//sar* news1 = get_temp(sar *s1);
Icode_h::Math("ADD", s1->_id().symid, s2->_id().symid, temp->_id().symid);
}
}
void _sub(){ // Subtract Operator
sar* s1 = pop_sar();
sar* s2 = pop_sar();
if(!sametype(s1, s2)){
gen_error("Not Same Type", s1, s2);
return;
}
else
{
sar *temp = gensym(s2->_id(), s2->_id().data.type);
SAStack.push_back(temp);
Icode_h::Math("SUB", s1->_id().symid, s2->_id().symid, temp->_id().symid);
}
}
void _star(){ // Multiply Operator
sar* s1 = pop_sar();
sar* s2 = pop_sar();
if(!sametype(s1, s2)){
gen_error("Not Same Type", s1, s2);
return;
}
else
{
sar *temp = gensym(s2->_id(), s2->_id().data.type);
SAStack.push_back(temp);
Icode_h::Math("MUL", s1->_id().symid, s2->_id().symid, temp->_id().symid);
}
}
void _div(){ // Divide Operator
sar* s1 = pop_sar();
sar* s2 = pop_sar();
if(!sametype(s1, s2)){
gen_error("Not Same Type", s1, s2);
return;
}
else
{
sar *temp = gensym(s2->_id(), s2->_id().data.type);
SAStack.push_back(temp);
Icode_h::Math("DIV", s1->_id().symid, s2->_id().symid, temp->_id().symid);
}
}
void _equal(){ // Assignment Operator
sar* s1 = pop_sar();
sar* s2 = pop_sar();
if(!sametype(s1, s2)){
gen_error("Not Same Type", s1, s2);
return;
}
else
{
sar *temp = gensym(s2->_id(), s2->_id().data.type);
SAStack.push_back(temp);
Icode_h::move(s1->_id().symid, s2->_id().symid);
}
}
void _less(){ // Less Than Operator
sar* s1 = pop_sar();
sar* s2 = pop_sar();
if(!sametype(s1, s2)){
gen_error("Not Same Type", s1, s2);
return;
}
else
{
sar *temp = gensym(s2->_id(), "bool");
SAStack.push_back(temp);
Icode_h::Boolean("LT", s1->_id().symid, s2->_id().symid, temp->_id().symid);
}
}
void _greater(){ // Greater Than Operator
sar* s1 = pop_sar();
sar* s2 = pop_sar();
if(!sametype(s1, s2))
gen_error("Not Same Type", s1, s2);
else
{
sar *temp = gensym(s2->_id(), "bool");
SAStack.push_back(temp);
Icode_h::Boolean("GT", s1->_id().symid, s2->_id().symid, temp->_id().symid);
}
}
void _equalequal(){ // Equal Operator
sar* s1 = pop_sar();
sar* s2 = pop_sar();
if(!sametype(s1, s2)){
gen_error("Not Same Type", s1, s2);
return;
}
else
{
sar *temp = gensym(s2->_id(), "bool");
SAStack.push_back(temp);
Icode_h::Boolean("EQ", s1->_id().symid, s2->_id().symid, temp->_id().symid);
}
}
void _lessequal(){ // Less Than or Equal Operator
sar* s1 = pop_sar();
sar* s2 = pop_sar();
if(!sametype(s1, s2)){
gen_error("Not Same Type", s1, s2);
return;
}
else
{
sar *temp = gensym(s2->_id(), "bool");
SAStack.push_back(temp);
Icode_h::Boolean("LE", s1->_id().symid, s2->_id().symid, temp->_id().symid);
}
}
void _greaterequal(){ // Greater Than or Equal Operator
sar* s1 = pop_sar();
sar* s2 = pop_sar();
if(!sametype(s1, s2)){
gen_error("Not Same Type", s1, s2);
return;
}
else
{
sar *temp = gensym(s2->_id(), "bool");
SAStack.push_back(temp);
Icode_h::Boolean("GE", s1->_id().symid, s2->_id().symid, temp->_id().symid);
}
}
void _and(){ // And Operator
sar* s1 = pop_sar();
sar* s2 = pop_sar();
if(!sametype(s1, s2)){
gen_error("Not Same Type", s1, s2);
return;
}
else
{
sar *temp = gensym(s2->_id(), "bool");
SAStack.push_back(temp);
Icode_h::Boolean("AND", s1->_id().symid, s2->_id().symid, temp->_id().symid);
}
}
void _or(){ // Or Operator
sar* s1 = pop_sar();
sar* s2 = pop_sar();
if(!sametype(s1, s2)){
gen_error("Not Same Type", s1, s2);
return;
}
else
{
sar *temp = gensym(s2->_id(), "bool");
SAStack.push_back(temp);
Icode_h::Boolean("OR", s1->_id().symid, s2->_id().symid, temp->_id().symid);
}
}
void _notEqual(){ // Not equal Operator
sar* s1 = pop_sar();
sar* s2 = pop_sar();
if(!sametype(s1, s2)){
gen_error("Not Same Type", s1, s2);
return;
}
else
{
sar *temp = gensym(s2->_id(), "bool");
SAStack.push_back(temp);
Icode_h::Boolean("NE", s1->_id().symid, s2->_id().symid, temp->_id().symid);
}
}
////////////////////////////////////
} | [
"powellm123@gmail.com"
] | powellm123@gmail.com |
78f85dbf48cf579b8a6104fce4dd9fd18df9f0aa | a75decf33a2c45ad158b099009d89dbc8a865e7e | /September LeetCoding Challenge(2022)/Day 08 Binary Tree Inorder Traversal.cpp | 812aaf4e3d0cf11d444237ca729c48104402beb5 | [] | no_license | chenghui-lee/leetcode | 2a2aa31a8a82462ccfa4759c60d1a41993671ac4 | d5861dfc413a27a1c3948ae7d6631a0634cf3854 | refs/heads/master | 2022-12-07T09:40:11.366532 | 2022-11-30T02:21:03 | 2022-11-30T02:21:03 | 219,287,018 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 703 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void inorder(TreeNode* root, vector<int>& res){
if (!root) return;
inorder(root->left, res);
res.push_back(root->val);
inorder(root->right, res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inorder(root, res);
return res;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
97181e73e8653e2edbd0d7c27caaf6663da8bb13 | f8b941dccf8b6039ec6653619691a01e2b6cbd62 | /external/succinct-cpp/core/include/succinct_core.h | 5994f65c15703b5ca0cc54a28f754898df4eb565 | [] | no_license | amplab/zipg | 90294a5666829cdc49bf95f8989d1c9b99c131ec | 7f2354269ed51f5c6b6a09fd4dd5894f032cfc21 | refs/heads/vldb15-linkbench | 2023-08-30T21:52:29.256693 | 2020-02-20T14:53:07 | 2020-02-20T14:53:07 | 241,912,130 | 12 | 5 | null | 2021-09-01T18:39:40 | 2020-02-20T14:58:42 | Java | UTF-8 | C++ | false | false | 5,970 | h | #ifndef SUCCINCT_CORE_H
#define SUCCINCT_CORE_H
#include <vector>
#include <fstream>
#include "npa/elias_delta_encoded_npa.h"
#include "npa/elias_gamma_encoded_npa.h"
#include "npa/npa.h"
#include "npa/wavelet_tree_encoded_npa.h"
#include "sampledarray/flat_sampled_array.h"
#include "sampledarray/layered_sampled_array.h"
#include "sampledarray/layered_sampled_isa.h"
#include "sampledarray/layered_sampled_sa.h"
#include "sampledarray/opportunistic_layered_sampled_array.h"
#include "sampledarray/opportunistic_layered_sampled_isa.h"
#include "sampledarray/opportunistic_layered_sampled_sa.h"
#include "sampledarray/sampled_by_index_isa.h"
#include "sampledarray/sampled_by_index_sa.h"
#include "sampledarray/sampled_by_value_isa.h"
#include "sampledarray/sampled_by_value_sa.h"
#include "succinct_base.h"
#include "utils/array_stream.h"
#include "utils/divsufsortxx.h"
#include "utils/divsufsortxx_utility.h"
typedef enum {
CONSTRUCT_IN_MEMORY = 0,
CONSTRUCT_MEMORY_MAPPED = 1,
LOAD_IN_MEMORY = 2,
LOAD_MEMORY_MAPPED = 3
} SuccinctMode;
class SuccinctCore : public SuccinctBase {
public:
typedef std::map<char, std::pair<uint64_t, uint32_t>> AlphabetMap;
typedef std::pair<int64_t, int64_t> Range;
/* Constructors */
SuccinctCore(const char *filename, SuccinctMode s_mode =
SuccinctMode::CONSTRUCT_IN_MEMORY,
uint32_t sa_sampling_rate = 32, uint32_t isa_sampling_rate = 32,
uint32_t npa_sampling_rate = 128, uint32_t context_len = 3,
SamplingScheme sa_sampling_scheme =
SamplingScheme::FLAT_SAMPLE_BY_INDEX,
SamplingScheme isa_sampling_scheme =
SamplingScheme::FLAT_SAMPLE_BY_INDEX,
NPA::NPAEncodingScheme npa_encoding_scheme =
NPA::NPAEncodingScheme::ELIAS_GAMMA_ENCODED,
uint32_t sampling_range = 1024);
virtual ~SuccinctCore() {
}
/* Lookup functions for each of the core data structures */
// Lookup NPA at index i
uint64_t LookupNPA(uint64_t i);
// Lookup SA at index i
uint64_t LookupSA(uint64_t i);
// Lookup ISA at index i
uint64_t LookupISA(uint64_t i);
// Get index of value v in C
uint64_t LookupC(uint64_t val);
// Get the character at index i
char CharAt(uint64_t i);
// Serialize succinct data structures
virtual size_t Serialize();
// Deserialize succinct data structures
virtual size_t Deserialize();
// Memory map succinct data structures
virtual size_t MemoryMap();
// Get size of original input
uint64_t GetOriginalSize();
// Get succinct core size
virtual size_t StorageSize();
virtual void PrintStorageBreakdown();
// Get SA
SampledArray *GetSA();
// Get ISA
SampledArray *GetISA();
// Get NPA
NPA *GetNPA();
// Get alphabet
char *GetAlphabet();
inline int Compare(std::string mgram, int64_t pos);
inline int Compare(std::string mgram, int64_t pos, size_t offset);
Range BwdSearch(std::string mgram);
Range ContinueBwdSearch(std::string mgram, Range range);
Range FwdSearch(std::string mgram);
Range ContinueFwdSearch(std::string mgram, Range range, size_t len);
protected:
/* Metadata */
std::string filename_; // Name of input file
std::string succinct_path_; // Name of succinct path
uint64_t input_size_; // Size of input
/* Primary data structures */
SampledArray *sa_; // Suffix Array
SampledArray *isa_; // Inverse Suffix Array
NPA *npa_; // Next Pointer Array
/* Auxiliary data structures */
char *alphabet_;
AlphabetMap alphabet_map_;
uint32_t alphabet_size_; // Size of the input alphabet_
private:
// Constructs the core data structures
void Construct(const char* filename, uint32_t sa_sampling_rate,
uint32_t isa_sampling_rate, uint32_t npa_sampling_rate,
uint32_t context_len, SamplingScheme sa_sampling_scheme,
SamplingScheme isa_sampling_scheme,
NPA::NPAEncodingScheme npa_encoding_scheme,
uint32_t sampling_range);
uint64_t ComputeContextValue(char* data, uint32_t i, uint32_t context_len) {
uint64_t val = 0;
uint64_t max = SuccinctUtils::Min(i + context_len, input_size_);
for (uint64_t t = i; t < max; t++) {
val = val * 256 + data[t];
}
if (max < i + context_len) {
for (uint64_t t = 0; t < (i + context_len) % input_size_; t++) {
val = val * 256 + data[t];
}
}
return val;
}
bool CompareContexts(char *data, uint64_t pos1, uint64_t pos2,
uint32_t context_len) {
for (uint64_t t = pos1; t < pos1 + context_len; t++) {
if (data[t] != data[pos2++]) {
return false;
}
}
return true;
}
// bool IsSampled(SamplingScheme scheme, uint32_t sampling_rate, uint64_t i,
// uint64_t val) {
// switch (scheme) {
// case SamplingScheme::FLAT_SAMPLE_BY_INDEX:
// case SamplingScheme::LAYERED_SAMPLE_BY_INDEX:
// case SamplingScheme::OPPORTUNISTIC_LAYERED_SAMPLE_BY_INDEX: {
// if (i % sampling_rate == 0) {
// return true;
// }
// return false;
// }
// case SamplingScheme::FLAT_SAMPLE_BY_VALUE: {
// if (val % sampling_rate == 0) {
// return true;
// }
// return false;
// }
// }
// return false;
// }
static Bitmap* ReadAsBitmap(size_t size, uint8_t bits,
SuccinctAllocator& s_allocator,
std::string& infile) {
Bitmap* B = new Bitmap;
InitBitmap(&B, size * bits, s_allocator);
std::ifstream in(infile);
for (uint64_t i = 0; i < size; i++) {
uint64_t val;
in.read(reinterpret_cast<char *>(&val), size * sizeof(uint64_t));
SetBitmapArray(&B, i, val, bits);
}
return B;
}
};
#endif
| [
"anuragk@berkeley.edu"
] | anuragk@berkeley.edu |
b23bf406fae0c89e311e5f6eff22243a78bcbfa0 | 438c7252734f7d5f162da44d46f5216934cdb027 | /source/ctrcommon/app.cpp | b23719f12bb30330910d103f1295353f8bf0279f | [
"MIT"
] | permissive | AlbertoSONIC/ctrcommon | c12ba8384c0b539e16477f17ff642f0212a492fb | 072d2045143e58f15befda6c51d386e3c424e3b3 | refs/heads/master | 2021-01-21T23:45:21.355074 | 2015-04-14T09:26:23 | 2015-04-14T09:26:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,913 | cpp | #include "ctrcommon/app.hpp"
#include "service.hpp"
#include <sys/errno.h>
#include <sys/stat.h>
#include <sys/unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iomanip>
#include <sstream>
#include <3ds.h>
#include <ctrcommon/app.hpp>
u8 appMediatypeToByte(MediaType mediaType) {
return mediaType == NAND ? mediatype_NAND : mediatype_SDMC;
}
AppPlatform appPlatformFromId(u16 id) {
switch(id) {
case 1:
return WII;
case 3:
return DSI;
case 4:
return THREEDS;
case 5:
return WIIU;
default:
return UNKNOWN_PLATFORM;
}
}
AppCategory appCategoryFromId(u16 id) {
if((id & 0x2) == 0x2) {
return DLC;
} else if((id & 0x6) == 0x6) {
return PATCH;
} else if((id & 0x10) == 0x10) {
return SYSTEM;
} else if((id & 0x8000) == 0x8000) {
return TWL;
}
return APP;
}
const std::string appGetResultString(AppResult result) {
std::stringstream resultMsg;
if(result == APP_SUCCESS) {
resultMsg << "Operation succeeded.";
} else if(result == APP_PROCESS_CLOSING) {
resultMsg << "Process closing.";
} else if(result == APP_OPERATION_CANCELLED) {
resultMsg << "Operation cancelled.";
} else if(result == APP_AM_INIT_FAILED) {
resultMsg << "Could not initialize AM service.";
} else if(result == APP_IO_ERROR) {
resultMsg << "I/O Error." << "\n" << strerror(errno);
} else if(result == APP_OPEN_FILE_FAILED) {
resultMsg << "Could not open file." << "\n" << strerror(errno);
} else if(result == APP_BEGIN_INSTALL_FAILED) {
resultMsg << "Could not begin installation." << "\n" << platformGetErrorString(platformGetError());
} else if(result == APP_INSTALL_ERROR) {
resultMsg << "Could not install app." << "\n" << platformGetErrorString(platformGetError());
} else if(result == APP_FINALIZE_INSTALL_FAILED) {
resultMsg << "Could not finalize installation." << "\n" << platformGetErrorString(platformGetError());
} else if(result == APP_DELETE_FAILED) {
resultMsg << "Could not delete app." << "\n" << platformGetErrorString(platformGetError());
} else if(result == APP_LAUNCH_FAILED) {
resultMsg << "Could not launch app." << "\n" << platformGetErrorString(platformGetError());
} else {
resultMsg << "Unknown error.";
}
return resultMsg.str();
}
const std::string appGetPlatformName(AppPlatform platform) {
switch(platform) {
case WII:
return "Wii";
case DSI:
return "DSi";
case THREEDS:
return "3DS";
case WIIU:
return "Wii U";
default:
return "Unknown";
}
}
const std::string appGetCategoryName(AppCategory category) {
switch(category) {
case APP:
return "App";
case DLC:
return "DLC";
case PATCH:
return "Patch";
case SYSTEM:
return "System";
case TWL:
return "TWL";
default:
return "Unknown";
}
}
std::vector<App> appList(MediaType mediaType) {
std::vector<App> titles;
if(!serviceRequire("am")) {
return titles;
}
u32 titleCount;
Result titleCountResult = AM_GetTitleCount(appMediatypeToByte(mediaType), &titleCount);
if(titleCountResult != 0) {
platformSetError(serviceParseError((u32) titleCountResult));
return titles;
}
u64 titleIds[titleCount];
Result titleListResult = AM_GetTitleIdList(appMediatypeToByte(mediaType), titleCount, titleIds);
if(titleListResult != 0) {
platformSetError(serviceParseError((u32) titleListResult));
return titles;
}
for(u32 i = 0; i < titleCount; i++) {
u64 titleId = titleIds[i];
App app;
app.titleId = titleId;
app.uniqueId = ((u32*) &titleId)[0];
AM_GetTitleProductCode(appMediatypeToByte(mediaType), titleId, app.productCode);
if(strcmp(app.productCode, "") == 0) {
strcpy(app.productCode, "<N/A>");
}
app.mediaType = mediaType;
app.platform = appPlatformFromId(((u16 *) &titleId)[3]);
app.category = appCategoryFromId(((u16 *) &titleId)[2]);
titles.push_back(app);
}
return titles;
}
AppResult appInstallFile(MediaType mediaType, const std::string path, std::function<bool(u64 pos, u64 totalSize)> onProgress) {
if(!serviceRequire("am")) {
return APP_AM_INIT_FAILED;
}
FILE* fd = fopen(path.c_str(), "r");
if(!fd) {
return APP_OPEN_FILE_FAILED;
}
struct stat st;
stat(path.c_str(), &st);
u64 size = (u64) (u32) st.st_size;
AppResult ret = appInstall(mediaType, fd, size, onProgress);
fclose(fd);
return ret;
}
AppResult appInstall(MediaType mediaType, FILE* fd, u64 size, std::function<bool(u64 pos, u64 totalSize)> onProgress) {
if(!serviceRequire("am")) {
return APP_AM_INIT_FAILED;
}
if(onProgress != NULL) {
onProgress(0, 0);
}
Handle ciaHandle;
Result startResult = AM_StartCiaInstall(appMediatypeToByte(mediaType), &ciaHandle);
if(startResult != 0) {
platformSetError(serviceParseError((u32) startResult));
return APP_BEGIN_INSTALL_FAILED;
}
u32 bufSize = 1024 * 16; // 16KB
void* buf = malloc(bufSize);
bool cancelled = false;
u64 pos = 0;
while(platformIsRunning()) {
if(onProgress != NULL && !onProgress(pos, size)) {
AM_CancelCIAInstall(&ciaHandle);
cancelled = true;
break;
}
u64 bytesRead = fread(buf, 1, bufSize, fd);
if(bytesRead == 0) {
if((errno != EAGAIN && errno != EWOULDBLOCK) || (size != 0 && pos == size)) {
break;
}
} else {
Result writeResult = FSFILE_Write(ciaHandle, NULL, pos, buf, (u32) bytesRead, FS_WRITE_NOFLUSH);
if(writeResult != 0) {
AM_CancelCIAInstall(&ciaHandle);
platformSetError(serviceParseError((u32) writeResult));
return APP_INSTALL_ERROR;
}
pos += bytesRead;
}
}
free(buf);
if(cancelled) {
return APP_OPERATION_CANCELLED;
}
if(!platformIsRunning()) {
AM_CancelCIAInstall(&ciaHandle);
return APP_PROCESS_CLOSING;
}
if(size != 0 && pos != size) {
AM_CancelCIAInstall(&ciaHandle);
return APP_IO_ERROR;
}
if(onProgress != NULL) {
onProgress(size, size);
}
Result finishResult = AM_FinishCiaInstall(appMediatypeToByte(mediaType), &ciaHandle);
if(finishResult != 0) {
platformSetError(serviceParseError((u32) finishResult));
return APP_FINALIZE_INSTALL_FAILED;
}
return APP_SUCCESS;
}
AppResult appDelete(App app) {
if(!serviceRequire("am")) {
return APP_AM_INIT_FAILED;
}
Result res = AM_DeleteTitle(appMediatypeToByte(app.mediaType), app.titleId);
if(res != 0) {
platformSetError(serviceParseError((u32) res));
return APP_DELETE_FAILED;
}
return APP_SUCCESS;
}
AppResult appLaunch(App app) {
u8 buf0[0x300];
u8 buf1[0x20];
aptOpenSession();
Result prepareResult = APT_PrepareToDoAppJump(NULL, 0, app.titleId, appMediatypeToByte(app.mediaType));
if(prepareResult != 0) {
aptCloseSession();
platformSetError(serviceParseError((u32) prepareResult));
return APP_LAUNCH_FAILED;
}
Result doResult = APT_DoAppJump(NULL, 0x300, 0x20, buf0, buf1);
if(doResult != 0) {
aptCloseSession();
platformSetError(serviceParseError((u32) doResult));
return APP_LAUNCH_FAILED;
}
aptCloseSession();
return APP_SUCCESS;
} | [
"Steveice10@gmail.com"
] | Steveice10@gmail.com |
e7442f3e5afbe145160f2fa43a4b15c9a04ee319 | 771b8d391585df59d8c7438e21e54976c4180011 | /src/interactive_mid_protocols/SigmaProtocolElGamalPrivateKey.cpp | 37be997c1ca3f6c2225e111e5320274dd51968d0 | [
"MIT"
] | permissive | cryptobiu/libscapi | 1f11f92065c1cea418e73b932c9810d374bac060 | 1f70a88548501eaca5fb635194443e7a2b871088 | refs/heads/master | 2023-08-10T08:34:21.304797 | 2022-08-16T16:48:20 | 2022-08-16T16:48:20 | 53,246,303 | 186 | 74 | MIT | 2023-07-20T11:01:17 | 2016-03-06T08:59:43 | C++ | UTF-8 | C++ | false | false | 7,001 | cpp | /**
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*
* Copyright (c) 2016 LIBSCAPI (http://crypto.biu.ac.il/SCAPI)
* This file is part of the SCAPI project.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* 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.
*
* We request that any publication and/or code referring to and/or based on SCAPI contain an appropriate citation to SCAPI, including a reference to
* http://crypto.biu.ac.il/SCAPI.
*
* Libscapi uses several open source libraries. Please see these projects for any further licensing issues.
* For more information , See https://github.com/cryptobiu/libscapi/blob/master/LICENSE.MD
*
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*
*/
#include "../../include/interactive_mid_protocols/SigmaProtocolElGamalPrivateKey.hpp"
/**
* Computes the simulator computation with the given challenge.
* @param input MUST be an instance of SigmaElGamalPrivateKeyCommonInput.
* @param challenge
* @return the output of the computation - (a, e, z).
* @throws CheatAttemptException if the received challenge's length is not equal to the soundness parameter.
* @throws IllegalArgumentException if the given input is not an instance of SigmaElGamalPrivateKeyCommonInput.
*/
shared_ptr<SigmaSimulatorOutput> SigmaElGamalPrivateKeySimulator::simulate(SigmaCommonInput* input, const vector<byte> & challenge) {
auto elGamalInput = dynamic_cast<SigmaElGamalPrivateKeyCommonInput*>(input);
if (elGamalInput == NULL) {
throw invalid_argument("the given input must be an instance of SigmaElGamalPrivateKeyCommonInput");
}
//Convert the input to match the required SigmaDlogSimulator's input.
SigmaDlogCommonInput * dlogInput = new SigmaDlogCommonInput(elGamalInput->getPublicKey().getH());
unique_ptr<SigmaDlogCommonInput> dlogInputP(dlogInput);
//Delegates the computation to the underlying Sigma Dlog simulator.
return dlogSim.simulate(dlogInputP.get(), challenge);
}
/**
* Computes the simulator computation with a randomly chosen challenge.
* @param input MUST be an instance of SigmaElGamalPrivateKeyCommonInput.
* @return the output of the computation - (a, e, z).
* @throws IllegalArgumentException if the given input is not an instance of SigmaElGamalPrivateKeyCommonInput.
*/
shared_ptr<SigmaSimulatorOutput> SigmaElGamalPrivateKeySimulator::simulate(SigmaCommonInput* input) {
auto elGamalInput = dynamic_cast<SigmaElGamalPrivateKeyCommonInput*>(input);
if (elGamalInput == NULL) {
throw invalid_argument("the given input must be an instance of SigmaElGamalPrivateKeyCommonInput");
}
//Convert the input to match the required SigmaDlogSimulator's input.
SigmaDlogCommonInput * dlogInput = new SigmaDlogCommonInput(elGamalInput->getPublicKey().getH());
unique_ptr<SigmaDlogCommonInput> dlogInputP(dlogInput);
//Delegates the computation to the underlying Sigma Dlog simulator.
return dlogSim.simulate(dlogInputP.get());
}
/**
* Constructor that gets the underlying DlogGroup, soundness parameter and SecureRandom.
* @param dlog
* @param t Soundness parameter in BITS.
* @param random
*/
SigmaElGamalPrivateKeyProverComputation::SigmaElGamalPrivateKeyProverComputation(const shared_ptr<DlogGroup> & dlog, int t, const shared_ptr<PrgFromOpenSSLAES> & prg)
: sigmaDlog(dlog, t, prg) {
this->prg = prg;
this->dlog = dlog;
this->t = t;
}
/**
* Computes the first message of the protocol.
* @param input MUST be an instance of SigmaElGamalPrivateKeyProverInput.
* @return the computed message
* @throws IllegalArgumentException if input is not an instance of SigmaElGamalPrivateKeyProverInput.
*/
shared_ptr<SigmaProtocolMsg> SigmaElGamalPrivateKeyProverComputation::computeFirstMsg(const shared_ptr<SigmaProverInput> & input){
auto in = dynamic_pointer_cast<SigmaElGamalPrivateKeyProverInput>(input);
if (in == NULL) {
throw invalid_argument("the given input must be an instance of SigmaElGamalPrivateKeyProverInput");
}
//Create an input object to the underlying sigma dlog prover.
//Delegates the computation to the underlying Sigma Dlog prover.
return sigmaDlog.computeFirstMsg(make_shared<SigmaDlogProverInput>(dynamic_pointer_cast<SigmaElGamalPrivateKeyCommonInput>(in->getCommonInput())->getPublicKey().getH(), in->getPrivateKey().getX()));
}
/**
* Computes the second message of the protocol.
* @param challenge
* @return the computed message.
* @throws CheatAttemptException if the received challenge's length is not equal to the soundness parameter.
*/
shared_ptr<SigmaProtocolMsg> SigmaElGamalPrivateKeyProverComputation::computeSecondMsg(const vector<byte> & challenge) {
//Delegates the computation to the underlying Sigma Dlog prover.
return sigmaDlog.computeSecondMsg(challenge);
}
/**
* Verifies the proof.
* @param z second message from prover
* @param input MUST be an instance of SigmaElGamalPrivateKeyCommonInput.
* @return true if the proof has been verified; false, otherwise.
* @throws IllegalArgumentException if input is not an instance of SigmaElGamalPrivateKeyCommonInput.
* @throws IllegalArgumentException if the first message of the prover is not an instance of SigmaGroupElementMsg
* @throws IllegalArgumentException if the second message of the prover is not an instance of SigmaBIMsg
*/
bool SigmaElGamalPrivateKeyVerifierComputation::verify(SigmaCommonInput* input, SigmaProtocolMsg* a, SigmaProtocolMsg* z) {
auto in = dynamic_cast<SigmaElGamalPrivateKeyCommonInput*>(input);
if (in == NULL) {
throw invalid_argument("the given input must be an instance of SigmaElGamalPrivateKeyCommonInput");
}
//Create an input object to the underlying sigma dlog verifier.
SigmaDlogCommonInput* underlyingInput = new SigmaDlogCommonInput(in->getPublicKey().getH());
unique_ptr<SigmaDlogCommonInput> inputP(underlyingInput);
return sigmaDlog.verify(inputP.get(), a, z);
} | [
"moriyaw@gmail.com"
] | moriyaw@gmail.com |
91d8b1d6f48e6a335d4c49f889bba71d5284846b | 92ee1c0b1c476110bdb6db6a029d764f9b79bd0f | /src/qt/askpassphrasedialog.cpp | d5244219138bff9a142e7f1f7d268312a6cc73a1 | [
"MIT"
] | permissive | Loop-Coin/AIZEUSCOIN | bb8b487f63b71f8858939b3703ef2b3c86281142 | 099eb08cd2bc064a7d78407f18bc806b4190b90e | refs/heads/master | 2020-03-21T00:09:05.609879 | 2018-06-19T08:18:33 | 2018-06-19T08:18:33 | 137,880,255 | 0 | 0 | null | 2018-06-19T11:07:43 | 2018-06-19T11:07:43 | null | UTF-8 | C++ | false | false | 9,908 | cpp | // Copyright (c) 2011-2013 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 "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include <QMessageBox>
#include <QPushButton>
#include <QKeyEvent>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->passLabel1->hide();
ui->passEdit1->hide();
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>."));
setWindowTitle(tr("Encrypt wallet"));
break;
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR AIZEUSS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("AIZEUS will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your aizeuss from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
| [
"root@ubuntu-s-2vcpu-4gb-ams3-01.localdomain"
] | root@ubuntu-s-2vcpu-4gb-ams3-01.localdomain |
1f3ddc92f19efd8b807b96bd7e01d82a062c15a0 | 895b3f891d4aab73f13f93091183477e7ba5c89f | /src/ewc_base/editor/plugin_ewsl_caret.h | 6a981aae8977d4245e16d265dca5c5e3504f5df0 | [
"Apache-2.0"
] | permissive | luoxz-ai/ew_base | 6e63877d0dcd992171e43729c804cc72018d0f19 | 8186f63d3e9ddbc16e63c807fec9140f28bc27b6 | refs/heads/master | 2021-06-20T02:24:11.759172 | 2017-08-09T09:22:54 | 2017-08-09T09:22:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,168 | h | #include "ewc_base/wnd/impl_wx/iwnd_stc.h"
#include "plugin_ewsl_iface.h"
EW_ENTER
class EwslIface;
class EwslCaret : public IWnd_stc
{
public:
typedef IWnd_stc basetype;
EwslIface& Handler;
long pos0; // cmd raw begin
long pos1; // cmd begin
long xpos; // cmd current pos
long line;
long ncmd;
enum
{
CARET_NONE =0,
CARET_MOVETO =1<<0,
CARET_NEWLINE =1<<1,
CARET_PROMPT =1<<2,
CARET_BUSY =1<<3,
};
void TestPos(int flag=CARET_MOVETO);
void Cut();
void Copy();
void Paste();
void Clear();
void ClearAll();
bool CanCut() const;
bool CanPaste() const;
EwslCaret(wxWindow* p,const WndPropertyEx& x,EwslIface& h);
~EwslCaret();
virtual void ChangeValue(const wxString& value);
void PendingAppend(const wxString& txt);
virtual wxString GetRange(long from, long to) const;
void PendingExecute();
void OnCharHook(wxKeyEvent& evt);
void OnCharAdd(wxStyledTextEvent &evt);
void OnDrag(wxStyledTextEvent &evt);
void OnCallTip(wxStyledTextEvent &evt);
void CmdPrepare(int flag=CARET_NEWLINE);
void OnMouseEvents(wxMouseEvent& evt);
arr_1t<wxString> m_vectCmdHistory;
protected:
DECLARE_EVENT_TABLE();
};
EW_LEAVE
| [
"hanwd@eastfdtd.com"
] | hanwd@eastfdtd.com |
cdd3c582448e4c67674c4275d621f36f9c408be6 | bd81f6135c3909579b6c59e767ec1e2aa09fc902 | /h_webserver/Timer.cc | d95278f1c7afc57938cfaa1a99cc919dc42d18c2 | [] | no_license | HhTtLllL/web_server | ff331a67e76da72538e68d3d0f94d834ed013059 | b0210b0dd53397bfb5bc822f0c505d35a7551199 | refs/heads/master | 2021-01-04T06:54:12.551652 | 2020-08-13T09:43:35 | 2020-08-13T09:43:35 | 240,437,444 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,614 | cc | #include "Timer.h"
#include <sys/time.h>
#include <unistd.h>
#include <queue>
using namespace tt;
using namespace net;
TimerNode::TimerNode(std::shared_ptr<HttpData> requestData, int timeout)
: deleted_(false), SPHttpData(requestData) {
struct timeval now;
gettimeofday(&now, NULL);
// 以毫秒计
expiredTime_ =
(((now.tv_sec % 10000) * 1000) + (now.tv_usec / 1000)) + timeout;
}
TimerNode::~TimerNode() {
if (SPHttpData) SPHttpData->handleClose();
}
TimerNode::TimerNode(TimerNode &tn)
: SPHttpData(tn.SPHttpData), expiredTime_(0) {}
void TimerNode::update(int timeout) {
struct timeval now;
gettimeofday(&now, NULL);
expiredTime_ =
(((now.tv_sec % 10000) * 1000) + (now.tv_usec / 1000)) + timeout;
}
bool TimerNode::isValid() {
struct timeval now;
gettimeofday(&now, NULL);
size_t temp = (((now.tv_sec % 10000) * 1000) + (now.tv_usec / 1000));
if (temp < expiredTime_)
return true;
else {
this->setDeleted();
return false;
}
}
void TimerNode::clearReq() {
SPHttpData.reset();
this->setDeleted();
}
TimerManager::TimerManager() {}
TimerManager::~TimerManager() {}
void TimerManager::addTimer(std::shared_ptr<HttpData> SPHttpData, int timeout) {
SPTimerNode new_node(new TimerNode(SPHttpData, timeout));
timerNodeQueue.push(new_node);
SPHttpData->linkTimer(new_node);
}
/* 处理逻辑是这样的~
因为(1) 优先队列不支持随机访问
(2) 即使支持,随机删除某节点后破坏了堆的结构,需要重新更新堆结构。
所以对于被置为deleted的时间节点,会延迟到它(1)超时 或
(2)它前面的节点都被删除时,它才会被删除。
一个点被置为deleted,它最迟会在TIMER_TIME_OUT时间后被删除。
这样做有两个好处:
(1) 第一个好处是不需要遍历优先队列,省时。
(2)
第二个好处是给超时时间一个容忍的时间,就是设定的超时时间是删除的下限(并不是一到超时时间就立即删除),如果监听的请求在超时后的下一次请求中又一次出现了,
就不用再重新申请RequestData节点了,这样可以继续重复利用前面的RequestData,减少了一次delete和一次new的时间。
*/
void TimerManager::handleExpiredEvent() {
// MutexLockGuard locker(lock);
while (!timerNodeQueue.empty()) {
SPTimerNode ptimer_now = timerNodeQueue.top();
if (ptimer_now->isDeleted())
timerNodeQueue.pop();
else if (ptimer_now->isValid() == false)
timerNodeQueue.pop();
else
break;
}
}
| [
"1430249706@qq.com"
] | 1430249706@qq.com |
97dfc1570e733a285647b9c13de0c651aba84cc4 | f6939676b9adaeeecb3401a0c46aae0996811bf9 | /menu.h | c951e433edb8ca8e16e695ef5eb9e844506b98ca | [] | no_license | Svetlana-Ignatova/Lab3 | 4c801fb56a9d3324b0020a3ae04f1f93298d3037 | d409d5828543b64205992dcb9b7a799afab35835 | refs/heads/main | 2023-06-13T08:25:24.555364 | 2021-07-05T09:03:19 | 2021-07-05T09:03:19 | 383,077,657 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 252 | h |
#ifndef S_LAB3_MENU_H
#define S_LAB3_MENU_H
#include <iostream>
#include "func.h"
#include "BinaryTree.h"
#include "Complex.h"
void sep();
void Menu();
void PrintTreeMenu();
int ToStr();
void MenuTreeFloat();
#endif //S_LAB3_MENU_H
| [
"noreply@github.com"
] | noreply@github.com |
353f6aa6b4fa5414a49d4cd3a6704ecc76b9babc | a147eef2d6420b02d093a7145e7976f4f04fc669 | /Module - Client Hors-Ligne/LoadingScreen.h | 2a68917cd195b5c251bb0cf6be0b754caeff6b8c | [] | no_license | Sea5hd0w/gameJam7seven | 6df8f89c49d8fb9da288fc449f6d7fae5d480746 | 7e5fe1c334d9fc1d5f0cf2da656fa062faa92d84 | refs/heads/master | 2021-08-30T01:18:44.251488 | 2017-12-15T14:08:40 | 2017-12-15T14:08:40 | 114,092,244 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 684 | h | #pragma once
#include "SDL.h"
#include <ctime>
#include <map>
#include <tuple>
#include <string>
#include <iostream>
#include <chrono>
#include <thread>
#include <time.h>
#include <iostream>
using namespace std;
class LoadingScreen
{
public:
LoadingScreen(SDL_Window* pWindow);
~LoadingScreen();
void getScreen(); //Print the screen make by the object
private:
SDL_Window* pWindow; //Pointer on MainWindow to print on it
map<int, SDL_Texture*> spritesLoadingScreen; //List of image of the loading
int gifCycle; //Curent position of the image to print
int gifCycle2; //Curent position of the image to print
void loadSprites(); //Load image of the loading animation
};
| [
"alexandre.montoro@viacesi.fr"
] | alexandre.montoro@viacesi.fr |
4ed786725e81b906a921fa18aee78f1db59e8ea6 | 4c1d7d1968d04226e5a7413a5543ab2b224a51a5 | /src/CQChartsFilterEdit.cpp | 7c44b8ee9b709144571ab2f07226292d79a5e512 | [
"MIT"
] | permissive | adam-urbanczyk/CQCharts | fa852a1884229e863f1aea6913ad7d52227646be | a560c616589f36c30ec18d992d877d20f7e842ec | refs/heads/master | 2020-08-27T12:33:32.103376 | 2019-10-21T00:18:41 | 2019-10-21T00:18:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,394 | cpp | #include <CQChartsFilterEdit.h>
#include <CQIconCombo.h>
#include <CQSwitch.h>
#include <CQUtil.h>
#include <QHBoxLayout>
#include <QButtonGroup>
#include <QKeyEvent>
#include <svg/filter_light_svg.h>
#include <svg/filter_dark_svg.h>
#include <svg/search_light_svg.h>
#include <svg/search_dark_svg.h>
CQChartsFilterEdit::
CQChartsFilterEdit(QWidget *parent) :
QFrame(parent)
{
setObjectName("filterEdit");
QHBoxLayout *layout = CQUtil::makeLayout<QHBoxLayout>(this, 0, 2);
edit_ = new CQChartsFilterEditEdit;
connect(edit_, SIGNAL(returnPressed()), this, SLOT(acceptSlot()));
connect(edit_, SIGNAL(escapePressed()), this, SLOT(escapeSlot()));
layout->addWidget(edit_);
combo_ = CQUtil::makeWidget<CQIconCombo>("combo");
combo_->addItem(CQPixmapCacheInst->getIcon("FILTER_LIGHT", "FILTER_DARK"), "Filter");
combo_->addItem(CQPixmapCacheInst->getIcon("SEARCH_LIGHT", "SEARCH_DARK"), "Search");
combo_->setFocusPolicy(Qt::NoFocus);
connect(combo_, SIGNAL(currentIndexChanged(int)), this, SLOT(comboSlot(int)));
layout->addWidget(combo_);
QFrame *opFrame = CQUtil::makeWidget<QFrame>("opFrame");
QHBoxLayout *opLayout = CQUtil::makeLayout<QHBoxLayout>(opFrame, 0, 2);
addReplaceSwitch_ = new CQSwitch("Replace", "Add");
addReplaceSwitch_->setObjectName("add_replace");
addReplaceSwitch_->setChecked(true);
addReplaceSwitch_->setHighlightOn(false);
addReplaceSwitch_->setFocusPolicy(Qt::NoFocus);
opLayout->addWidget(addReplaceSwitch_);
andOrSwitch_ = new CQSwitch("And", "Or");
andOrSwitch_->setObjectName("and");
andOrSwitch_->setChecked(true);
andOrSwitch_->setHighlightOn(false);
andOrSwitch_->setFocusPolicy(Qt::NoFocus);
connect(andOrSwitch_, SIGNAL(toggled(bool)), this, SLOT(andSlot()));
opLayout->addWidget(andOrSwitch_);
layout->addWidget(opFrame);
setFocusProxy(edit_);
}
void
CQChartsFilterEdit::
setFilterDetails(const QString &str)
{
filterDetails_ = str;
edit_->setToolTip(filterDetails_);
}
void
CQChartsFilterEdit::
setSearchDetails(const QString &str)
{
searchDetails_ = str;
edit_->setToolTip(searchDetails_);
}
void
CQChartsFilterEdit::
comboSlot(int /*ind*/)
{
if (combo_->currentIndex() == 0) {
edit_->setText(filterText_);
edit_->setToolTip(filterDetails_);
}
else {
edit_->setText(searchText_);
edit_->setToolTip(searchDetails_);
}
}
void
CQChartsFilterEdit::
andSlot()
{
bool b = andOrSwitch_->isChecked();
emit filterAnd(b);
}
void
CQChartsFilterEdit::
acceptSlot()
{
QString text = edit_->text();
if (combo_->currentIndex() == 0) {
if (text != filterText_) {
filterText_ = text;
filterDetails_ = "";
if (addReplaceSwitch_->isChecked())
emit replaceFilter(filterText_);
else
emit addFilter(filterText_);
}
}
else {
if (text != searchText_) {
searchText_ = text;
if (addReplaceSwitch_->isChecked())
emit replaceSearch(searchText_);
else
emit addSearch(searchText_);
}
}
}
void
CQChartsFilterEdit::
escapeSlot()
{
emit escapePressed();
}
//------
CQChartsFilterEditEdit::
CQChartsFilterEditEdit(QWidget *parent) :
CQLineEdit(parent)
{
setObjectName("edit");
}
void
CQChartsFilterEditEdit::
keyPressEvent(QKeyEvent *e)
{
if (e->key() == Qt::Key_Escape) {
emit escapePressed();
return;
}
CQLineEdit::keyPressEvent(e);
}
| [
"colinw@nc.rr.com"
] | colinw@nc.rr.com |
60c265daefd98d1cb301ceb4a266d132a77813cc | 682ce86c118a1b6f12c5bd4a5b62d8403df34496 | /SRC/Geometry/source/noding/SegmentNodeList.cpp | 6be2611f5d355bb508eb55c2115e226b6d7262b1 | [] | no_license | 15831944/applesales | 5596aca332384fe3210e03152b30334e48c344bd | 76aaf13d6b995ee59f8d83ecd9a1af155ed1911d | refs/heads/master | 2023-03-17T11:44:43.762650 | 2013-04-15T14:22:18 | 2013-04-15T14:22:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,845 | cpp | /**********************************************************************
* $Id: SegmentNodeList.cpp 1820 2006-09-06 16:54:23Z mloskot $
*
* GEOS - Geometry Engine Open Source
* http://geos.refractions.net
*
* Copyright (C) 2006 Refractions Research Inc.
* Copyright (C) 2001-2002 Vivid Solutions Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: noding/SegmentNodeList.java rev. 1.7 (JTS-1.7)
*
**********************************************************************/
#include <cassert>
#include <set>
#include <Geometry/profiler.h>
#include <Geometry/util/GEOSException.h>
#include <Geometry/noding/SegmentNodeList.h>
#include <Geometry/noding/SegmentString.h>
#include <Geometry/geom/Coordinate.h>
#include <Geometry/geom/CoordinateSequence.h>
#include <Geometry/geom/CoordinateArraySequence.h> // FIXME: should we really be using this ?
#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif
#ifdef GEOS_DEBUG
#include <iostream>
#endif
//using namespace std;
using namespace GEOMETRY::geom;
namespace GEOMETRY {
namespace noding { // geos.noding
#if PROFILE
static Profiler *profiler = Profiler::instance();
#endif
SegmentNodeList::~SegmentNodeList()
{
std::set<SegmentNode *, SegmentNodeLT>::iterator it=nodeMap.begin();
for(; it!=nodeMap.end(); it++)
{
delete *it;
}
for(size_t i=0, n=splitEdges.size(); i<n; ++i)
{
delete splitEdges[i];
}
for(size_t i=0, n=splitCoordLists.size(); i<n; ++i)
{
delete splitCoordLists[i];
}
}
SegmentNode*
SegmentNodeList::add(const Coordinate& intPt, size_t segmentIndex)
{
SegmentNode *eiNew=new SegmentNode(edge, intPt, segmentIndex,
edge.getSegmentOctant(segmentIndex));
std::pair<SegmentNodeList::iterator,bool> p = nodeMap.insert(eiNew);
if ( p.second ) { // new SegmentNode inserted
return eiNew;
} else {
// sanity check
assert(eiNew->coord.equals2D(intPt));
delete eiNew;
return *(p.first);
}
}
void SegmentNodeList::addEndpoints()
{
int maxSegIndex = edge.size() - 1;
add(&(edge.getCoordinate(0)), 0);
add(&(edge.getCoordinate(maxSegIndex)), maxSegIndex);
}
/* private */
void
SegmentNodeList::addCollapsedNodes()
{
std::vector<size_t> collapsedVertexIndexes;
findCollapsesFromInsertedNodes(collapsedVertexIndexes);
findCollapsesFromExistingVertices(collapsedVertexIndexes);
// node the collapses
for (std::vector<size_t>::iterator
i=collapsedVertexIndexes.begin(),
e=collapsedVertexIndexes.end();
i != e; ++i)
{
size_t vertexIndex = *i;
add(edge.getCoordinate(vertexIndex), vertexIndex);
}
}
/* private */
void
SegmentNodeList::findCollapsesFromExistingVertices(
std::vector<size_t>& collapsedVertexIndexes)
{
for (size_t i=0, n=edge.size()-2; i<n; ++i)
{
const Coordinate& p0 = edge.getCoordinate(i);
//const Coordinate& p1 = edge.getCoordinate(i + 1);
const Coordinate& p2 = edge.getCoordinate(i + 2);
if (p0.equals2D(p2)) {
// add base of collapse as node
collapsedVertexIndexes.push_back(i + 1);
}
}
}
/* private */
void
SegmentNodeList::findCollapsesFromInsertedNodes(
std::vector<size_t>& collapsedVertexIndexes)
{
size_t collapsedVertexIndex;
// there should always be at least two entries in the list,
// since the endpoints are nodes
iterator it = begin();
SegmentNode* eiPrev = *it;
++it;
for(iterator itEnd=end(); it!=itEnd; ++it)
{
SegmentNode *ei=*it;
bool isCollapsed = findCollapseIndex(*eiPrev, *ei,
collapsedVertexIndex);
if (isCollapsed)
collapsedVertexIndexes.push_back(collapsedVertexIndex);
eiPrev = ei;
}
}
/* private */
bool
SegmentNodeList::findCollapseIndex(SegmentNode& ei0, SegmentNode& ei1,
size_t& collapsedVertexIndex)
{
// only looking for equal nodes
if (! ei0.coord.equals2D(ei1.coord)) return false;
int numVerticesBetween = ei1.segmentIndex - ei0.segmentIndex;
if (! ei1.isInterior()) {
numVerticesBetween--;
}
// if there is a single vertex between the two equal nodes,
// this is a collapse
if (numVerticesBetween == 1) {
collapsedVertexIndex = ei0.segmentIndex + 1;
return true;
}
return false;
}
/* public */
void
SegmentNodeList::addSplitEdges(std::vector<SegmentString*>& edgeList)
{
// testingOnly
#if GEOS_DEBUG
std::cerr<<__FUNCTION__<<" entered"<<std::endl;
std::vector<SegmentString*> testingSplitEdges;
#endif
// ensure that the list has entries for the first and last
// point of the edge
addEndpoints();
addCollapsedNodes();
// there should always be at least two entries in the list
// since the endpoints are nodes
iterator it=begin();
SegmentNode *eiPrev=*it;
assert(eiPrev);
it++;
for(iterator itEnd=end(); it!=itEnd; ++it)
{
SegmentNode *ei=*it;
assert(ei);
if ( ! ei->compareTo(*eiPrev) ) continue;
SegmentString *newEdge=createSplitEdge(eiPrev, ei);
edgeList.push_back(newEdge);
#if GEOS_DEBUG
testingSplitEdges.push_back(newEdge);
#endif
eiPrev = ei;
}
#if GEOS_DEBUG
std::cerr<<__FUNCTION__<<" finished, now checking correctness"<<std::endl;
checkSplitEdgesCorrectness(testingSplitEdges);
#endif
}
void
SegmentNodeList::checkSplitEdgesCorrectness(std::vector<SegmentString*>& splitEdges)
{
const CoordinateSequence *edgePts=edge.getCoordinates();
assert(edgePts);
// check that first and last points of split edges
// are same as endpoints of edge
SegmentString *split0=splitEdges[0];
assert(split0);
const Coordinate& pt0=split0->getCoordinate(0);
if (!(pt0==edgePts->getAt(0)))
throw util::GEOSException("bad split edge start point at " + pt0.toString());
SegmentString *splitn=splitEdges[splitEdges.size()-1];
assert(splitn);
const CoordinateSequence *splitnPts=splitn->getCoordinates();
assert(splitnPts);
const Coordinate &ptn=splitnPts->getAt(splitnPts->getSize()-1);
if (!(ptn==edgePts->getAt(edgePts->getSize()-1)))
throw util::GEOSException("bad split edge end point at " + ptn.toString());
}
/*private*/
SegmentString*
SegmentNodeList::createSplitEdge(SegmentNode *ei0, SegmentNode *ei1)
{
assert(ei0);
assert(ei1);
size_t npts = ei1->segmentIndex - ei0->segmentIndex + 2;
const Coordinate &lastSegStartPt=edge.getCoordinate(ei1->segmentIndex);
// if the last intersection point is not equal to the its
// segment start pt, add it to the points list as well.
// (This check is needed because the distance metric is not
// totally reliable!)
// The check for point equality is 2D only - Z values are ignored
// Added check for npts being == 2 as in that case NOT using second point
// would mean creating a SegmentString with a single point
// FIXME: check with mbdavis about this, ie: is it a bug in the caller ?
//
bool useIntPt1 = npts == 2 || (ei1->isInterior() || ! ei1->coord.equals2D(lastSegStartPt));
if (! useIntPt1) {
npts--;
}
CoordinateSequence *pts = new CoordinateArraySequence(npts);
size_t ipt = 0;
pts->setAt(ei0->coord, ipt++);
for (size_t i=ei0->segmentIndex+1; i<=ei1->segmentIndex; i++)
{
pts->setAt(edge.getCoordinate(i),ipt++);
}
if (useIntPt1) pts->setAt(ei1->coord, ipt++);
SegmentString *ret = new SegmentString(pts, edge.getData());
#if GEOS_DEBUG
std::cerr<<" SegmentString created"<<std::endl;
#endif
splitEdges.push_back(ret);
// Keep track of created CoordinateSequence to release
// it at this SegmentNodeList destruction time
splitCoordLists.push_back(pts);
return ret;
}
std::ostream&
operator<< (std::ostream& os, const SegmentNodeList& nlist)
{
os << "Intersections: (" << nlist.nodeMap.size() << "):" << std::endl;
std::set<SegmentNode*,SegmentNodeLT>::const_iterator
it = nlist.nodeMap.begin(),
itEnd = nlist.nodeMap.end();
for(; it!=itEnd; it++)
{
SegmentNode *ei=*it;
os << " " << *ei;
}
return os;
}
} // namespace GEOMETRY.noding
} // namespace GEOMETRY
/**********************************************************************
* $Log$
* Revision 1.33 2006/06/12 11:29:23 strk
* unsigned int => size_t
*
* Revision 1.32 2006/05/05 10:19:06 strk
* droppped SegmentString::getContext(), new name is getData() to reflect change in JTS
*
* Revision 1.31 2006/05/04 08:35:15 strk
* noding/SegmentNodeList.cpp: cleanups, changed output operator to be more similar to JTS
*
* Revision 1.30 2006/03/15 09:51:12 strk
* streamlined headers usage
*
* Revision 1.29 2006/03/09 15:39:25 strk
* Fixed debugging lines
*
* Revision 1.28 2006/03/06 19:40:47 strk
* GEOMETRY::util namespace. New GeometryCollection::iterator interface, many cleanups.
*
* Revision 1.27 2006/03/03 10:46:21 strk
* Removed 'using namespace' from headers, added missing headers in .cpp files, removed useless includes in headers (bug#46)
*
* Revision 1.26 2006/03/02 12:12:00 strk
* Renamed DEBUG macros to GEOS_DEBUG, all wrapped in #ifndef block to allow global override (bug#43)
*
* Revision 1.25 2006/03/01 16:01:47 strk
* Fixed const correctness of operator<<(ostream&, SegmentNodeList&) [bug#37]
*
* Revision 1.24 2006/02/28 17:44:27 strk
* Added a check in SegmentNode::addSplitEdge to prevent attempts
* to build SegmentString with less then 2 points.
* This is a temporary fix for the buffer.xml assertion failure, temporary
* as Martin Davis review would really be needed there.
*
**********************************************************************/
| [
"lordfm@163.com"
] | lordfm@163.com |
e8a5d029b9d5843e33b71b6f7565d5e00d1a3e9a | 33d3e7cdc23d9f3116afc2b1a9804f019c9053ec | /qt/onlyCPPcase/openImg.cpp | f32ecee9894c8ac052e3cf720e65a44fc32422a1 | [] | no_license | alennex/2017_project | 320f829775d6daef01ec5d0e8d707b67e2b81e5d | b95affc9c52e3fdbb78b528087236e8b69c6b793 | refs/heads/master | 2020-12-02T17:45:12.330505 | 2017-08-16T02:29:27 | 2017-08-16T02:29:27 | 96,417,906 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 281 | cpp | #include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main(int argc, char* argv[]){
Mat img = imread(argv[1],-1);
cout << "cols: " << img.cols << endl;
cout << "rows: " << img.rows << endl;
return 0;
} | [
"alennex@gmail.com"
] | alennex@gmail.com |
55ce2757cce406aa9085d7f7ff88f99ac7fb6f43 | 1a218c67ad04f99e52c37425fdb933b053af6244 | /Ch15/ex15.35/binaryquery.hpp | af51461655162ea6984c47ff04e3d1c5d02f073d | [] | no_license | xiaonengmiao/Cpp_Primer | 5a91cd223c9b0870f4ab9a45c6f679333a98fa20 | be20a29b49be19f6959b7873077ea698da940bf6 | refs/heads/master | 2020-12-25T14:23:58.976008 | 2020-06-18T07:54:43 | 2020-06-18T07:54:43 | 66,343,361 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 788 | hpp | #ifndef BINARYQUERY_H
#define BINARYQUERY_H
#include "query_base.hpp"
#include "query.hpp"
/**
* @brief The BinaryQuery class
*An abstract class holds data needed by the query types that operate on two operands
*/
class BinaryQuery : public Query_base
{
protected:
BinaryQuery(const Query&l, const Query& r, std::string s):
lhs(l), rhs(r), opSym(s)
{
std::cout << "BinaryQuery::BinaryQuery() where s=" + s + "\n";
}
// @note: abstract class: BinaryQuery doesn't define eval
std::string rep() const override
{
std::cout << "BinaryQuery::rep()\n";
return "(" + lhs.rep() + " "
+ opSym + " "
+ rhs.rep() + ")";
}
Query lhs, rhs;
std::string opSym;
};
#endif // BINARYQUERY_H
| [
"hlibb@connect.ust.hk"
] | hlibb@connect.ust.hk |
3c9d7dd866e0ccb9d912dd39b938079bc9e808d1 | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mess/includes/tmc2000e.h | a879ec6c789f2d33498c54617bc6df3fb0d26284 | [] | no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,898 | h | #pragma once
#ifndef __TMC2000E__
#define __TMC2000E__
#define ADDRESS_MAP_MODERN
#include "emu.h"
#include "cpu/cosmac/cosmac.h"
#include "formats/basicdsk.h"
#include "imagedev/cassette.h"
#include "imagedev/flopdrv.h"
#include "imagedev/printer.h"
#include "machine/rescap.h"
#include "machine/ram.h"
#include "sound/cdp1864.h"
#define SCREEN_TAG "screen"
#define CDP1802_TAG "cdp1802"
#define CDP1864_TAG "cdp1864"
#define CASSETTE_TAG "cassette"
#define TMC2000E_COLORRAM_SIZE 0x100 // ???
class tmc2000e_state : public driver_device
{
public:
tmc2000e_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config),
m_maincpu(*this, CDP1802_TAG),
m_cti(*this, CDP1864_TAG),
m_cassette(*this, CASSETTE_TAG)
{ }
required_device<cpu_device> m_maincpu;
required_device<device_t> m_cti;
required_device<device_t> m_cassette;
virtual void machine_start();
virtual void machine_reset();
virtual bool screen_update(screen_device &screen, bitmap_t &bitmap, const rectangle &cliprect);
DECLARE_READ8_MEMBER( vismac_r );
DECLARE_WRITE8_MEMBER( vismac_w );
DECLARE_READ8_MEMBER( floppy_r );
DECLARE_WRITE8_MEMBER( floppy_w );
DECLARE_READ8_MEMBER( ascii_keyboard_r );
DECLARE_READ8_MEMBER( io_r );
DECLARE_WRITE8_MEMBER( io_w );
DECLARE_WRITE8_MEMBER( io_select_w );
DECLARE_WRITE8_MEMBER( keyboard_latch_w );
DECLARE_READ_LINE_MEMBER( rdata_r );
DECLARE_READ_LINE_MEMBER( bdata_r );
DECLARE_READ_LINE_MEMBER( gdata_r );
DECLARE_READ_LINE_MEMBER( clear_r );
DECLARE_READ_LINE_MEMBER( ef2_r );
DECLARE_READ_LINE_MEMBER( ef3_r );
DECLARE_WRITE_LINE_MEMBER( q_w );
DECLARE_WRITE8_MEMBER( dma_w );
/* video state */
int m_cdp1864_efx; /* EFx */
UINT8 *m_colorram; /* color memory */
UINT8 m_color;
/* keyboard state */
int m_keylatch; /* key latch */
int m_reset; /* reset activated */
};
#endif
| [
"Mike@localhost"
] | Mike@localhost |
6659ff35d1eabdf3a35296e641146e99a411ab38 | 6d981c49012f3b9d3b444240faf9f9f2c97d9bf8 | /flashlight/nn/modules/Normalize.h | 19435ea3e5a793f069da95cf2c84c7341ce9a97d | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | noticeable/flashlight | 7623d032361b86ee991aebb31a8410f3f3d62a12 | edfee0836b9c0f7d898b1da36fcbc005dfbf81b9 | refs/heads/master | 2022-12-31T12:29:45.187808 | 2020-10-26T15:08:03 | 2020-10-26T15:09:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,078 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include "flashlight/flashlight/nn/modules/Module.h"
namespace fl {
class Normalize : public UnaryModule {
public:
/**
* Constructs a Normalize module.
*
* @param value the target normalization value.
* @param axes reduce over specified axes
* @param p as p in Lp norm
* @param eps min clamping value to avoid overflows
* @param normalization mode, as supported by normalize()
*/
explicit Normalize(
const std::vector<int>& axes,
double p = 2,
double eps = 1e-12,
double value = 1);
Variable forward(const Variable& input) override;
std::string prettyString() const override;
private:
Normalize() = default;
std::vector<int> axes_;
double p_;
double eps_;
double value_;
FL_SAVE_LOAD_WITH_BASE(UnaryModule, axes_, p_, eps_, value_)
};
} // namespace fl
CEREAL_REGISTER_TYPE(fl::Normalize)
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
d38584de5df2fec62e567c757c267b9054bc464c | d40ee63566975dd11ae6ba6ea1c2889680c47c90 | /workspace/ros/aerostack_catkin_ws/devel/include/droneMsgsROS/AddBelief.h | f03422fd546806daa6bf3e234499b85c630ff622 | [] | no_license | la16k/TFG_Laura | 45e9df0f60ef94572260f14346c47969ab2c73b3 | f5e0661aa7ccd200ba056a40beb9e687f5f0d06e | refs/heads/master | 2022-12-27T02:49:05.549777 | 2020-10-05T10:48:57 | 2020-10-05T10:48:57 | 301,374,417 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,696 | h | // Generated by gencpp from file droneMsgsROS/AddBelief.msg
// DO NOT EDIT!
#ifndef DRONEMSGSROS_MESSAGE_ADDBELIEF_H
#define DRONEMSGSROS_MESSAGE_ADDBELIEF_H
#include <ros/service_traits.h>
#include <droneMsgsROS/AddBeliefRequest.h>
#include <droneMsgsROS/AddBeliefResponse.h>
namespace droneMsgsROS
{
struct AddBelief
{
typedef AddBeliefRequest Request;
typedef AddBeliefResponse Response;
Request request;
Response response;
typedef Request RequestType;
typedef Response ResponseType;
}; // struct AddBelief
} // namespace droneMsgsROS
namespace ros
{
namespace service_traits
{
template<>
struct MD5Sum< ::droneMsgsROS::AddBelief > {
static const char* value()
{
return "6d65075524dfe53f0efc88993a40725c";
}
static const char* value(const ::droneMsgsROS::AddBelief&) { return value(); }
};
template<>
struct DataType< ::droneMsgsROS::AddBelief > {
static const char* value()
{
return "droneMsgsROS/AddBelief";
}
static const char* value(const ::droneMsgsROS::AddBelief&) { return value(); }
};
// service_traits::MD5Sum< ::droneMsgsROS::AddBeliefRequest> should match
// service_traits::MD5Sum< ::droneMsgsROS::AddBelief >
template<>
struct MD5Sum< ::droneMsgsROS::AddBeliefRequest>
{
static const char* value()
{
return MD5Sum< ::droneMsgsROS::AddBelief >::value();
}
static const char* value(const ::droneMsgsROS::AddBeliefRequest&)
{
return value();
}
};
// service_traits::DataType< ::droneMsgsROS::AddBeliefRequest> should match
// service_traits::DataType< ::droneMsgsROS::AddBelief >
template<>
struct DataType< ::droneMsgsROS::AddBeliefRequest>
{
static const char* value()
{
return DataType< ::droneMsgsROS::AddBelief >::value();
}
static const char* value(const ::droneMsgsROS::AddBeliefRequest&)
{
return value();
}
};
// service_traits::MD5Sum< ::droneMsgsROS::AddBeliefResponse> should match
// service_traits::MD5Sum< ::droneMsgsROS::AddBelief >
template<>
struct MD5Sum< ::droneMsgsROS::AddBeliefResponse>
{
static const char* value()
{
return MD5Sum< ::droneMsgsROS::AddBelief >::value();
}
static const char* value(const ::droneMsgsROS::AddBeliefResponse&)
{
return value();
}
};
// service_traits::DataType< ::droneMsgsROS::AddBeliefResponse> should match
// service_traits::DataType< ::droneMsgsROS::AddBelief >
template<>
struct DataType< ::droneMsgsROS::AddBeliefResponse>
{
static const char* value()
{
return DataType< ::droneMsgsROS::AddBelief >::value();
}
static const char* value(const ::droneMsgsROS::AddBeliefResponse&)
{
return value();
}
};
} // namespace service_traits
} // namespace ros
#endif // DRONEMSGSROS_MESSAGE_ADDBELIEF_H
| [
"kunito.laura.ac@gmail.com"
] | kunito.laura.ac@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.