text
stringlengths 8
6.88M
|
|---|
#include <Poco/Exception.h>
#include <cppunit/extensions/HelperMacros.h>
#include "util/WithTrace.h"
using namespace std;
using namespace Poco;
using BeeeOn::ForPoco::WithTrace;
namespace BeeeOn {
class WithTraceTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(WithTraceTest);
CPPUNIT_TEST(testThrowCatch);
CPPUNIT_TEST(testTraceOf);
CPPUNIT_TEST_SUITE_END();
public:
void testThrowCatch();
void testTraceOf();
};
CPPUNIT_TEST_SUITE_REGISTRATION(WithTraceTest);
void WithTraceTest::testThrowCatch()
{
CPPUNIT_ASSERT_THROW(throw WithTrace<RuntimeException>("basic"),
RuntimeException);
CPPUNIT_ASSERT_THROW(throw WithTrace<IOException>("I/O"),
IOException);
CPPUNIT_ASSERT_THROW(throw WithTrace<RangeException>("range"),
LogicException);
CPPUNIT_ASSERT_THROW(throw WithTrace<Exception>("throwable"),
Throwable);
}
void WithTraceTest::testTraceOf()
{
if (!Backtrace::supported)
return;
try {
throw Exception("test");
} catch (const Exception &e) {
CPPUNIT_ASSERT(Throwable::traceOf(e).size() == 0);
}
try {
throw WithTrace<Exception>("test");
} catch (const Exception &e) {
const Backtrace &trace(Throwable::traceOf(e));
CPPUNIT_ASSERT(trace.size() > 4);
CPPUNIT_ASSERT(trace[0].find("Backtrace") != string::npos);
CPPUNIT_ASSERT(trace[1].find("Throwable") != string::npos);
CPPUNIT_ASSERT(trace[2].find("Exception") != string::npos);
CPPUNIT_ASSERT(trace[3].find("testTraceOf") != string::npos);
CPPUNIT_ASSERT(e.displayText().find("Exception: test: \n ") == 0);
}
}
}
|
/* this is class for holding the information concerning a camera:
* Field of vision
* Size of display
* Clip near and far
* and the combination of these for a quick and ready projection matrix
* Location vector
*/
//Currently the Camera deals with a lot of the transform logic. I may be removing this down the
//road if I move the cameras as a concept up into openCL. I may still be able to use glm there, but
//for this application, I think I could get more effecient code if I hand wrote it to optimize the
//particulars of the situation. So for now, here are the gl math libraries:
#include "Camera.h"
//include gaurd.
#ifndef CAMERA_CPP
#define CAMERA_CPP
//the constructor. You must name:
// field of vision: a half angle on the y. because the aspect ratio is known, the fov
// for the x will be solved for.
// x,y: the size of the window. x is width, y is height. example: 800x600, 1920x1080
// clipping near and far: these are the clipping planes. anything closer than near
// will not get rendered, and anything further than far is out of sight.
// loc: the initial location of the camera.
Camera::Camera(int _fov, int _x, int _y, float _near, float _far)
{
fov = _fov;
x = _x;
y = _y;
near = _near;
far = _far;
newProj = 0;
}
Camera::Camera(xml_node self)
{//the constructor method for constructing form a the xml. most of these are self explanitory.
fov = self.attribute("fov").as_float();
x = self.attribute("dimX").as_float();
y = self.attribute("dimY").as_float();
near = self.attribute("clipNear").as_float();
far = self.attribute("clipFar").as_float();
newProj = 0;
move(self.attribute("locX").as_float(),
self.attribute("locY").as_float(),
self.attribute("locZ").as_float());
ID = globalRM->RequestID();
globalRM->AssignID(ID,this);
if(self.attribute("LTI"))
{//register the load time identifier to the resource manager.
TRACE(3);
globalRM->RegisterLTI(self.attribute("LTI").value(),ID);
}
if(self.attribute("focus"))
{//set the focus of the camera to some other object. this is done with an LTI.
TRACE(3);
Event e;
e.args[0].datum.v_asInt[0] = (int)20;
e.receiver = ID;
e.type = EVENT_DELAYED_REQUEST;
strcpy(e.args[2].datum.v_asChar,self.attribute("focus").value());
globalRM->RegisterRequest(e);
}
}
//destructor. is as you would expect.
Camera::~Camera()
{
delete &projection;
fov = 0;
x = 0;
y = 0;
near = 0.0;
far = 0.0;
newProj = 0;
}
glm::mat4 Camera::lookAt(glm::vec3 val)
{//wrapper method for glm::lookAt function. this way the camera can be used to wrap this up
//neatly. you just have to tell the camera to look at something and it will manage the rest
TRACE(3);
if(parent)
{
TRACE(3);
return glm::lookAt(getGlobalLoc(),val,glm::vec3(0.0f,1.0f,0.0f));
}
TRACE(3);
return glm::lookAt(getGlobalLoc(),val,glm::vec3(0.0f,1.0f,0.0f));
}
glm::mat4 Camera::view()
{
TRACE(3);
if(focus)
{
TRACE(3);
return lookAt(focus->getGlobalLoc());
}
TRACE(3);
return lookAt(glm::vec3(1.0f));
}
glm::mat4 Camera::model()
{
return glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, loc.z));
}
glm::mat4 Camera::newProjection()
{//this method is used to create the new projection matrix. is calls the appropriate glm
// function and sends to it the local data values it maintains.
projection = glm::perspective(fov, 1.0f*x/y, near, far);
newProj = 1;
return projection;
}
bool Camera::onEvent(const Event& event)
{
TRACE(3);
if(event.type == EVENT_DELAYED_REQUEST)
{
TRACE(2);
if(event.args[0].datum.v_asInt[0] == 20)
{
TRACE(3);
string s(event.args[2].datum.v_asChar);
TRACE(5);
GeoObject* temp = (GeoObject*)(globalRM->GetIDRetaining(globalRM->ResolveLTI(s)));
TRACE(5);
setFocus(temp);
TRACE(5);
return true;
}
TRACE(3);
}
TRACE(5);
return GeoObject::onEvent(event);
}
#endif
/*.S.D.G.*/
|
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head || !(head->next))
return head;
ListNode* even = head;
ListNode* odd = head->next;
ListNode* odd_first = odd;
while(odd && odd->next){
even->next = odd->next;
odd->next = odd->next->next;
even = even->next;
odd = odd->next;
}
even->next = odd_first;
return head;
}
};
ListNode* createLinkedList(const vector<int>& nums, int index) {
if(nums.size() == index)
return nullptr;
ListNode* node = new ListNode(nums[index]);
node->next = createLinkedList(nums, ++index);
return node;
}
ListNode* createLinkedList(const vector<int>& nums) {
return createLinkedList(nums, 0);
}
int main(void){
vector<int> nums = {1, 2, 3, 4, 5};
ListNode* root = createLinkedList(nums);
Solution sol;
ListNode* node = sol.oddEvenList(root);
while(node){
cout << node->val << " ";
node = node->next;
}
cout << endl;
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
/**
* @file unistream.cpp
* This file contains code for stream classes that support Unicode.
*/
#include "core/pch.h"
#include "modules/encodings/charconverter.h"
#include "modules/encodings/decoders/inputconverter.h"
#include "modules/encodings/encoders/outputconverter.h"
#include "modules/util/opfile/unistream.h"
#include "modules/encodings/detector/charsetdetector.h"
#include "modules/hardcore/mem/mem_man.h"
#include "modules/pi/OpSystemInfo.h"
#include "modules/util/opfile/opfile.h"
#include "modules/util/opcrypt.h"
// ===== Functions =======================================================
UnicodeInputStream* createUnicodeInputStream(OpFileDescriptor *inFile, URLContentType content, OP_STATUS *status, BOOL stripbom)
{
UnicodeFileInputStream *in = OP_NEW(UnicodeFileInputStream, ());
if (!in)
{
if (status) *status = OpStatus::ERR_NO_MEMORY;
return NULL;
}
if (OpStatus::IsError(in->Construct(inFile,content,stripbom)))
{
if (status) *status = OpStatus::ERR_FILE_NOT_FOUND;
OP_DELETE(in);
return NULL;
}
return in;
}
// ===== UnicodeFileInputStream ==========================================
UnicodeFileInputStream::UnicodeFileInputStream() :
m_fp(0),
m_tmpbuf(NULL),
m_buflen(0),
m_bytes_in_buf(0),
m_buf(NULL),
m_conv(NULL),
m_bytes_converted(0)
{
}
OP_STATUS UnicodeFileInputStream::Construct(OpFileDescriptor *inFile, URLContentType content, BOOL stripbom)
{
m_stripbom = stripbom;
OP_STATUS rc = SharedConstruct(inFile);
if (OpStatus::IsSuccess(rc))
{
unsigned long size = (unsigned long)m_bytes_in_buf;
const char *encoding = NULL;
switch(content)
{
// FIXME: Duplicated
case URL_CSS_CONTENT:
encoding = CharsetDetector::GetCSSEncoding(m_tmpbuf, size);
break;
case URL_HTML_CONTENT:
encoding = CharsetDetector::GetHTMLEncoding(m_tmpbuf, size);
break;
case URL_XML_CONTENT:
encoding = CharsetDetector::GetXMLEncoding(m_tmpbuf, size);
break;
default:
break;
}
if (!encoding) encoding = "iso-8859-1";
if (OpStatus::IsError(InputConverter::CreateCharConverter(encoding, &m_conv)))
rc = InputConverter::CreateCharConverter("iso-8859-1", &m_conv);
}
return rc;
}
OP_STATUS UnicodeFileInputStream::Construct(OpFileDescriptor *inFile, LocalContentType content, BOOL stripbom)
{
m_stripbom = stripbom;
OP_STATUS rc = SharedConstruct(inFile);
if (OpStatus::IsSuccess(rc))
{
const char * OP_MEMORY_VAR encoding = NULL;
unsigned long size = (unsigned long)m_bytes_in_buf;
switch (content)
{
// FIXME: Duplicated
#ifdef PREFS_HAS_LNG
case LANGUAGE_FILE:
encoding = CharsetDetector::GetLanguageFileEncoding(m_tmpbuf, size);
break;
#endif
case TEXT_FILE:
encoding = CharsetDetector::GetUTFEncodingFromBOM(m_tmpbuf, size);
break;
case UTF8_FILE:
encoding = "utf-8";
break;
default:
break;
}
if (!encoding)
{
// Assume system default
if (g_op_system_info)
{
//Current implementation of GetSystemEncodingL does not leave.
TRAP(rc, encoding = g_op_system_info->GetSystemEncodingL());
}
else
{
encoding = "iso-8859-1";
}
}
if (OpStatus::IsSuccess(rc))
{
if (OpStatus::IsError(InputConverter::CreateCharConverter(encoding, &m_conv)))
rc = InputConverter::CreateCharConverter("iso-8859-1", &m_conv);
}
}
return rc;
}
OP_STATUS UnicodeFileInputStream::SharedConstruct(OpFileDescriptor *inFile)
{
OP_ASSERT(inFile);
if (inFile==NULL)
return OpStatus::ERR_NULL_POINTER;
m_fp = inFile;
RETURN_IF_ERROR(m_fp->Open(OPFILE_READ));
m_buflen = UTIL_UNICODE_INPUT_BUFLEN;
m_tmpbuf = OP_NEWA(char, (unsigned long)m_buflen+1);
if (m_tmpbuf == NULL)
{
return OpStatus::ERR_NO_MEMORY;
}
m_tmpbuf[m_buflen] = 0;
m_oom_error = FALSE;
m_buf = OP_NEWA(uni_char, (unsigned long)m_buflen+1);
if (m_buf == NULL)
{
return OpStatus::ERR_NO_MEMORY;
}
m_buf[m_buflen] = 0;
RETURN_IF_ERROR(m_fp->Read(m_tmpbuf, m_buflen, &m_bytes_in_buf));
m_bytes_converted = 0;
return OpStatus::OK;
}
OP_STATUS UnicodeFileInputStream::Construct(const uni_char *filename,
URLContentType content,
LocalContentType extended_content,
BOOL stripbom)
{
m_stripbom = stripbom;
RETURN_IF_ERROR(m_in_file.Construct(filename));
RETURN_IF_ERROR(m_in_file.Open(OPFILE_READ));
m_buflen = UTIL_UNICODE_INPUT_BUFLEN;
m_tmpbuf = OP_NEWA(char, (unsigned long)m_buflen+1);
if (m_tmpbuf == NULL)
{
return OpStatus::ERR_NO_MEMORY;
}
m_tmpbuf[m_buflen] = 0;
m_oom_error = FALSE;
m_buf = OP_NEWA(uni_char, (unsigned long)m_buflen+1);
if (m_buf == NULL)
{
return OpStatus::ERR_NO_MEMORY;
}
m_buf[m_buflen] = 0;
RETURN_IF_ERROR(m_in_file.Read(m_tmpbuf, m_buflen, &m_bytes_in_buf));
m_bytes_converted = 0;
const char *encoding = NULL;
unsigned long size = (unsigned long)m_bytes_in_buf;
switch(content)
{
// FIXME: Duplicated
case URL_CSS_CONTENT:
encoding = CharsetDetector::GetCSSEncoding(m_tmpbuf, size);
break;
case URL_HTML_CONTENT:
encoding = CharsetDetector::GetHTMLEncoding(m_tmpbuf, size);
break;
case URL_UNDETERMINED_CONTENT:
switch (extended_content)
{
#ifdef PREFS_HAS_LNG
case LANGUAGE_FILE:
encoding = CharsetDetector::GetLanguageFileEncoding(m_tmpbuf, size);
break;
#endif
case TEXT_FILE:
encoding = CharsetDetector::GetUTFEncodingFromBOM(m_tmpbuf, size);
break;
case UTF8_FILE:
encoding = "utf-8";
break;
}
break;
default:
;
}
if (!encoding) encoding = "iso-8859-1";
if (OpStatus::IsError(InputConverter::CreateCharConverter(encoding, &m_conv)))
return InputConverter::CreateCharConverter("iso-8859-1", &m_conv);
return OpStatus::OK;
}
BOOL UnicodeFileInputStream::has_more_data()
{
return ((m_fp && m_fp->IsOpen() && !m_fp->Eof())
|| (OpFileLength)m_bytes_converted < m_bytes_in_buf*2 && !m_oom_error);
}
BOOL UnicodeFileInputStream::no_errors()
{
return (m_in_file.IsOpen() || m_fp) && !m_oom_error;
}
uni_char* UnicodeFileInputStream::get_block(int& length)
{
length = 0;
if (!no_errors())
{
return NULL;
}
if ((OpFileLength)m_bytes_converted < m_bytes_in_buf)
{
// Convert the data still in the current buffer
int tmp;
length = m_conv->Convert(m_tmpbuf + m_bytes_converted, (unsigned long)m_bytes_in_buf - m_bytes_converted,
m_buf, (unsigned long)m_buflen * 2, &tmp);
if (length == -1)
{
length = 0;
m_oom_error = TRUE;
return NULL;
}
m_bytes_converted += tmp;
}
else
{
// Get a new chunk of data and convert it
OP_STATUS s;
if (m_fp)
{
s = m_fp->Read(m_tmpbuf, m_buflen, &m_bytes_in_buf);
}
else
{
s = m_in_file.Read(m_tmpbuf, m_buflen, &m_bytes_in_buf);
}
m_oom_error = (OpStatus::IsMemoryError(s));
if (m_oom_error)
{
return NULL;
}
m_bytes_converted = 0;
length = m_conv->Convert(m_tmpbuf, (unsigned long)m_bytes_in_buf, m_buf, (unsigned long)m_buflen * 2, &m_bytes_converted);
if (length == -1)
{
length = 0;
m_oom_error = TRUE;
return NULL;
}
}
// Bug#94132, #130048: Strip initial byte order mark (U+FEFF), if we need to.
if (m_stripbom && length)
{
m_stripbom = FALSE;
if (m_buf[0] == 0xFEFF)
{
op_memmove(m_buf, m_buf + 1, length - sizeof (uni_char));
length -= sizeof (uni_char);
}
}
return m_buf;
}
UnicodeFileInputStream::~UnicodeFileInputStream()
{
if(m_fp)
m_fp->Close();
else
m_in_file.Close();
OP_DELETEA(m_tmpbuf);
OP_DELETEA(m_buf);
OP_DELETE(m_conv);
}
#ifdef UTIL_STRING_STREAM
// ===== UnicodeStringOutputStream =========================================
void UnicodeStringOutputStream::WriteStringL(const uni_char* str, int len)
{
if (!str || !m_string || len==0)
return;
if (len == -1)
{
len = uni_strlen(str);
}
if ((m_stringlen + len) > m_string->Capacity())
{
m_string->Reserve((m_string->Capacity() + len)*2);
}
if (m_string->Append(str, len) == OpStatus::OK)
m_stringlen += len;
}
OP_STATUS UnicodeStringOutputStream::Construct(const OpString* string)
{
if (!string)
return OpStatus::ERR_NULL_POINTER;
m_string = (OpString*)string;
m_stringlen = m_string->Length();
return OpStatus::OK;
}
OP_STATUS UnicodeStringOutputStream::Close()
{
return OpStatus::OK;
}
#endif // UTIL_STRING_STREAM
// ===== UnicodeFileOutputStream =========================================
UnicodeFileOutputStream::UnicodeFileOutputStream() :
m_tmpbuf(NULL),
m_buflen(0),
m_bytes_in_buf(0),
m_buf(NULL),
m_conv(NULL)
{
}
UnicodeFileOutputStream::~UnicodeFileOutputStream()
{
OpStatus::Ignore(Close());
OP_DELETEA(m_tmpbuf);
m_tmpbuf = NULL;
OP_DELETEA(m_buf);
m_buf = NULL;
OP_DELETE(m_conv);
m_conv = NULL;
}
OP_STATUS UnicodeFileOutputStream::Close()
{
OP_STATUS rc = OpStatus::OK;
if (m_file.IsOpen())
{
rc = Flush();
if (OpStatus::IsSuccess(rc))
rc = m_file.Close();
else
return rc;
}
OP_DELETEA(m_tmpbuf);
m_tmpbuf = NULL;
OP_DELETEA(m_buf);
m_buf = NULL;
OP_DELETE(m_conv);
m_conv = NULL;
return rc;
}
OP_STATUS UnicodeFileOutputStream::Construct(const uni_char* filename, const char* encoding)
{
RETURN_IF_ERROR(m_file.Construct(filename));
RETURN_IF_ERROR(m_file.Open(OPFILE_WRITE));
m_buflen = (int)(UTIL_UNICODE_OUTPUT_BUFLEN * 1.5) + 10;
m_tmpbuf = OP_NEWA(char, m_buflen+1);
if (!m_tmpbuf)
return OpStatus::ERR_NO_MEMORY;
m_tmpbuf[m_buflen] = 0;
m_buf = OP_NEWA(uni_char, UTIL_UNICODE_OUTPUT_BUFLEN+1);
if (!m_buf)
return OpStatus::ERR_NO_MEMORY;
m_buf[UTIL_UNICODE_OUTPUT_BUFLEN] = 0;
OP_STATUS rc = OutputConverter::CreateCharConverter(encoding, &m_conv, FALSE, TRUE);
if (!m_tmpbuf || !m_buf || OpStatus::IsError(rc))
{
m_file.Close();
return OpStatus::IsError(rc) ? rc : OpStatus::ERR_NO_MEMORY;
}
return OpStatus::OK;
}
void UnicodeFileOutputStream::WriteStringL(const uni_char* str, int len)
{
if (!str)
LEAVE(OpStatus::ERR_NULL_POINTER);
if (len == -1)
{
len = uni_strlen(str);
}
// strategy: fill up unicode buffer first. when full, do conversion
// and write to file.
len *= sizeof(uni_char);
char* srcbuf = (char*)str;
while (len)
{
int bufspace = UTIL_UNICODE_OUTPUT_BUFLEN - m_bytes_in_buf;
int copylen = len > bufspace ? bufspace : len;
op_memcpy(((char*)m_buf)+m_bytes_in_buf, srcbuf, copylen); // don't copy \0-termination
m_bytes_in_buf += copylen;
len -= copylen;
srcbuf += copylen;
if (m_bytes_in_buf == UTIL_UNICODE_OUTPUT_BUFLEN)
{
LEAVE_IF_ERROR(Flush());
}
}
}
OP_STATUS UnicodeFileOutputStream::Flush()
{
if (m_bytes_in_buf == 0)
{
return OpStatus::OK;
}
int read;
int m_bytes_converted = m_conv->Convert(m_buf, m_bytes_in_buf,
m_tmpbuf, m_buflen, &read);
if (m_bytes_converted == -1)
{
return OpStatus::ERR_NO_MEMORY;
}
else
{
OP_ASSERT(read == m_bytes_in_buf); // must consume all input
RETURN_IF_ERROR(m_file.Write(m_tmpbuf, m_bytes_converted));
// Please note that we flush the buffer below, even if we fail
// to save it. This should most probably be considered a bug,
// but until we actually tell our caller we have an error, not
// flushing the buffer would throw us into an infinite loop.
}
m_bytes_in_buf = 0;
return OpStatus::OK;
}
|
// Переставьте соседние элементы массива (A[0] c A[1], A[2] c A[3] и т.д.). Если элементов нечетное число, то последний элемент остается на своем месте.
// Формат входных данных
// В первой строке вводится количество элементов в массиве. Во второй строке вводятся элементы массива.
// Формат выходных данных
// Выведите ответ на задачу.
#include <iostream>
#include <vector>
using namespace std;
int main() {
//ввод
int n;
cin >> n;
vector<int> a(n);
//считывание
for (int i = 0; i < n; i++) {
cin >> a[i];
}
//обработка
for (int i = 0; i < n - 1; i += 2) {
int temp;
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
for (auto elm : a) {
cout << elm << " ";
}
return 0;
}
|
/************************************************************************/
/*题目:输入一个正数 n,输出所有和为 n 连续正数序列。
例如输入 15,由于 1+2+3+4+5=4+5+6=7+8=15,所以输出 3 个连续序列 1-5、 4- 6 和 7-8。
分析:这是网易的一道面试题*/
/************************************************************************/
/************************************************************************/
/* 解法:
* 首先设置两个指针,一个指向首部,一个指向尾部,如果sum > n.则前移首部指针,如果sum < n则前移尾部指针。可以尾部指针最多在 n / 2 + 1处终止。*/
/************************************************************************/
#include <vector>
#include <map>
using namespace std;
class Solution{
public:
vector<pair<int, int> > GetSequence(int n){
vector<pair<int, int> > result;
int sum = 0;
int startPos = 1;
int endPos = startPos;
for(; sum <= n; ++endPos){
sum += endPos;
if(sum == n){
result.push_back(make_pair(startPos, endPos));
}
}
--endPos;//strange , after it break out the loop, endPos still plus one
sum -= startPos;
++startPos;
while(endPos < n / 2 + 2){
if(sum > n){
sum -= startPos;
++startPos;
}
else{
if(sum == n){
result.push_back(make_pair(startPos, endPos));
}
++endPos;
sum += endPos;
}
}
return result;
}
};
//int main(){
// Solution solution;
// solution.GetSequence(130);
// return 0;
//}
|
#pragma once
#include "envoy/network/address.h"
#include "envoy/network/socket.h"
#include "common/singleton/threadsafe_singleton.h"
namespace Envoy {
namespace Network {
class SocketInterfaceImpl : public SocketInterface {
public:
IoHandlePtr socket(Socket::Type socket_type, Address::Type addr_type,
Address::IpVersion version) override;
IoHandlePtr socket(Socket::Type socket_type, const Address::InstanceConstSharedPtr addr) override;
IoHandlePtr socket(os_fd_t fd) override;
bool ipFamilySupported(int domain) override;
};
using SocketInterfaceSingleton = InjectableSingleton<SocketInterface>;
using SocketInterfaceLoader = ScopedInjectableLoader<SocketInterface>;
} // namespace Network
} // namespace Envoy
|
#pragma once
#include <Tanker/Groups/IAccessor.hpp>
#include <Tanker/ContactStore.hpp>
#include <Tanker/Groups/Group.hpp>
#include <Tanker/Groups/IRequester.hpp>
#include <Tanker/ProvisionalUserKeysStore.hpp>
#include <Tanker/Trustchain/GroupId.hpp>
#include <Tanker/UserKeyStore.hpp>
#include <tconcurrent/coroutine.hpp>
#include <optional>
namespace Tanker
{
class ITrustchainPuller;
class GroupStore;
class GroupAccessor : public Groups::IAccessor
{
public:
GroupAccessor(Trustchain::UserId const& myUserId,
Groups::IRequester* requester,
ITrustchainPuller* trustchainPuller,
ContactStore const* contactStore,
GroupStore* groupstore,
UserKeyStore const* userKeyStore,
ProvisionalUserKeysStore const* provisionalUserKeysStore);
GroupAccessor() = delete;
GroupAccessor(GroupAccessor const&) = delete;
GroupAccessor(GroupAccessor&&) = delete;
GroupAccessor& operator=(GroupAccessor const&) = delete;
GroupAccessor& operator=(GroupAccessor&&) = delete;
tc::cotask<InternalGroupPullResult> getInternalGroups(
std::vector<Trustchain::GroupId> const& groupIds) override;
tc::cotask<PublicEncryptionKeyPullResult> getPublicEncryptionKeys(
std::vector<Trustchain::GroupId> const& groupIds) override;
// This function can only return keys for groups you are a member of
tc::cotask<std::optional<Crypto::EncryptionKeyPair>> getEncryptionKeyPair(
Crypto::PublicEncryptionKey const& publicEncryptionKey) override;
private:
Trustchain::UserId _myUserId;
Groups::IRequester* _requester;
ITrustchainPuller* _trustchainPuller;
ContactStore const* _contactStore;
GroupStore* _groupStore;
UserKeyStore const* _userKeyStore;
ProvisionalUserKeysStore const* _provisionalUserKeysStore;
tc::cotask<void> fetch(gsl::span<Trustchain::GroupId const> groupIds);
tc::cotask<GroupAccessor::GroupPullResult> getGroups(
std::vector<Trustchain::GroupId> const& groupIds);
};
}
|
/*
* Copyright (C) 2013 Tom Wong. All rights reserved.
*/
#ifndef __PDF_DOCUMENT_H__
#define __PDF_DOCUMENT_H__
#include "gtabstractdocument.h"
#include <QtCore/qplugin.h>
extern "C" {
#include "mupdf-internal.h"
}
GT_BEGIN_NAMESPACE
class PdfDocument : public GtAbstractDocument
{
public:
explicit PdfDocument();
~PdfDocument();
public:
bool load(QIODevice *device);
QString title();
int countPages();
GtAbstractPage* loadPage(int index);
GtAbstractOutline* loadOutline();
protected:
void parseLabels(pdf_obj *tree);
QString indexToLabel(int index);
protected:
static int readPdfStream(fz_stream *stm, unsigned char *buf, int len);
static void seekPdfStream(fz_stream *stm, int offset, int whence);
static void closePdfStream(fz_context *ctx, void *state);
static QString objToString(pdf_obj *obj);
static QString toRoman(int number, bool uppercase);
static QString toLatin(int number, bool uppercase);
protected:
class LabelRange;
private:
fz_context *_context;
fz_document *document;
QList<LabelRange*> labelRanges;
};
GT_END_NAMESPACE
#endif /* __PDF_DOCUMENT_H__ */
|
#include "many.h"
int many(int x, int y)
{
if(x<y){
return y;
}
return x;
}
|
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#include<queue>
using namespace std;
#define MAX_SIZE 6677
#define MOD 747474747
#define ull unsigned long long int
#define INFINITY 1<<31
int n,d,counter1,counter2;
struct vertex
{
int id,c[5],marked,key,count,tcount;
};
vector<vertex> a;
ull distance1(vertex v1,vertex v2)
{
ull i,v=0,temp;
for(i=0;i<d;i++)
{
temp=(v1.c[i]-v2.c[i])*(v1.c[i]-v2.c[i]);
if(temp>=MOD)
temp%=MOD;
v+=temp;
if(v>=MOD)
v%=MOD;
}
return v;
}
ull fastpow(int a, int b)
{
if(b==0)
return 1;
if(b==1)
return a;
else
{
ull t=fastpow(a,b/2);
t=t*t;
if(t>=MOD)
t%=MOD;
t=t*fastpow(a,b%2);
if(t>=MOD)
t%=MOD;
return t;
}
}
struct edge{
int id1,id2;
ull distance;
};
bool compare(const edge &i, const edge &j)
{
return i.distance>j.distance;
}
vector <edge> b;
int equal(vertex a, vertex b)
{
int i;
for(i=0;i<d && a.c[i]==b.c[i];i++);
if(i<d)
return 0;
else
return 1;
}
void swap(int &a,int &b)
{
int c=a;
a=b;
b=c;
}
int main()
{
counter1=0;
int t,e,from,to;
ull score,s1,s2,tempscore;
vertex temp;
edge t1;
scanf("%d",&t);
while(t--)
{
a.clear();
b.clear();
score=1;
scanf("%d%d",&n,&d);
e=n;
for(int i=0,j;i<n;i++)
{
for(j=0;j<d;j++)
{
scanf("%d",&temp.c[j]);
}
temp.id=i;
temp.marked=0;
for(j=0;j<a.size();j++)
{
if(equal(a[j],temp))
{
a[j].count++;
a[j].tcount++;
break;
}
}
if(j==a.size())
{
temp.count=1;
temp.tcount=1;
a.push_back(temp);
}
}
//Gonna do kruskals
for(int i=0;i<a.size();i++)
{
t1.id1=i;
for(int j=i+1;j<a.size();j++)
{
t1.id2=j;
t1.distance=distance1(a[i],a[j]);
b.push_back(t1);
}
}
sort(b.begin(),b.end(),compare);
for(int i=0;i<b.size() && e;i++)
{
if(a[b[i].id1].marked && a[b[i].id2].marked && a[b[i].id1].tcount==a[b[i].id1].count && a[b[i].id2].tcount==a[b[i].id2].count)
continue;
else
{
from=b[i].id1,to=b[i].id2;
if(!a[from].marked && !a[to].marked)
{
if(a[from].count>a[to].count)
{
swap(from,to);
}
a[from].tcount=a[from].count ;
a[from].marked=1;
a[to].tcount=a[to].count;
a[to].marked=1;
e-=a[from].count;
e-=a[to].count;
tempscore=fastpow(b[i].distance,a[to].count);
if(tempscore>MOD)
score*=(tempscore%MOD);
else
score*=(tempscore);
if(score>=MOD)
score%=MOD;
}
else
{
if(!a[from].marked && a[to].marked)
{
swap(from,to);
}
a[to].tcount=a[to].count;
a[to].marked=1;
e-=a[to].count;
tempscore=fastpow(b[i].distance,a[to].count);
if(tempscore>=MOD)
tempscore%=MOD;
score*=tempscore;
if(score>=MOD)
score%=MOD;
}
}
}
printf("%lld\n",score);
}
return 0;
}
|
/*
* Stopping Times
* Copyright (C) Leonardo Marchetti 2011 <leonardomarchetti@gmail.com>
*/
#ifndef _DE_SOLVER_H_
#define _DE_SOLVER_H_
#include <boost/function.hpp>
#include "de-solver.h"
namespace StoppingTimes{
/* FP is a template for Floating Point types. */
template<typename FP>
class DESolver {
public:
FP solve(boost::function<FP(FP, FP, FP)> ddf, FP xf, FP f0, FP df0, int n);
protected:
private:
FP RungeKutta(boost::function<FP(FP, FP, FP)> ddf, FP xf, FP f0, FP df0, int n);
};
#include "de-solver.inl"
}
#endif // _DE_SOLVER_H_
|
//===-- apps/odb-cli/cli.hh - CLI class definition --------------*- C++ -*-===//
//
// ODB Library
// Author: Steven Lariau
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Centralize client/server interface to communicate with debugger
///
//===----------------------------------------------------------------------===//
#pragma once
#include "odb/client/db-client-impl-data.hh"
#include "odb/mess/db-client.hh"
#include "odb/mess/simple-cli-client.hh"
class CLI {
public:
CLI(int argc, char **argv);
// Is state switched from VM stopped to running ?
// If true, usually needs to display infos
bool state_switched();
/// Wait until ready for next command
/// Returns false if deconneted
bool next();
/// Exec command with SimpleCLIClient
std::string exec(const std::string &cmd);
private:
odb::DBClient _db_client;
odb::SimpleCLIClient _cli;
bool _state_switch;
void _setup();
void _wait_stop();
};
|
#include <vector>
#include <unordered_map>
#include <string>
using namespace std;
/**
* This solution has not survived all the test cases;
*/
class Solution {
public:
int myAtoi(string str) {
unordered_map<char, int> validDigits = {
{'0', 0}, {'1', 1}, {'2', 2}, {'3', 3}, {'4', 4}, {'5', 5},
{'6', 6}, {'7', 7}, {'8', 8}, {'9', 9}};
vector<char> result;
int prefix = 0;
for (auto i = 0; i < str.length(); i++) {
char c = str.at(i);
// " 0000000000012345678";
if (c == ' ') {
// " +0 123";
continue;
} else if (c == '0' && result.size() == 0) {
continue;
} else if (validDigits.find(c) != validDigits.end()) {
// valid nums;
result.push_back(c);
} else {
// "+-2";
if (c == '-' && prefix == 0) {
prefix = -1;
} else if (c == '+' && prefix == 0) {
prefix = 1;
} else {
break;
}
}
}
// get the digits sequence of the maxmium number for comparison;
int max = numeric_limits<int>::max();
vector<int> seq;
while(true) {
seq.push_back(max % 10);
if (max <= 9 && max >= -9) { break; }
max /= 10;
}
// transform to number;
int num = 0;
const int size = result.size();
for (auto x = 0; x < size; x++) {
const int c = result[x];
if (validDigits.find(c) != validDigits.end()) {
if (size > seq.size()) {
return (prefix > 0 && prefix == 1) ? numeric_limits<int>::max() : numeric_limits<int>::min();
} else if (size == seq.size()) {
// MSB -> LSB;
if (validDigits[c] > seq[size - x - 1]) {
return (prefix > 0 && prefix == 1) ? numeric_limits<int>::max() : numeric_limits<int>::min();
}
num += validDigits[c] * pow(10, (size - x - 1));
} else {
// safe number;
num += validDigits[c] * pow(10, (size - x - 1));
}
}
}
return prefix == 0 ? num : num * prefix;
}
};
|
/*
* Clarinet.cpp
*
* Created on: Jun 16, 2016
* Author: g33z
*/
#include "Clarinet.h"
void Clarinet::play(Enote n){
cout << "Tüdelü in Clarinet" << endl;
Woodwind::play(n);
}
|
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@gmail.com *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#include <view/openGl/OpenGl.h>
#include <util/Exceptions.h>
#include "GraphicsService.h"
#include <android_native_app_glue.h>
#include <Platform.h>
#include <util/Config.h>
namespace U = Util;
/****************************************************************************/
GraphicsService::GraphicsService (android_app *a) :
app (a),
display (EGL_NO_DISPLAY),
surface (EGL_NO_SURFACE),
context (EGL_NO_CONTEXT)
{
}
/****************************************************************************/
bool GraphicsService::initDisplay (Util::Config *)
{
if (eglGetCurrentContext () != EGL_NO_CONTEXT) {
return true;
}
display = eglGetDisplay (EGL_DEFAULT_DISPLAY);
if (display == EGL_NO_DISPLAY) {
throw U::InitException ("eglGetDisplay returned EGL_NO_DISPLAY");
}
/*
* Initializing an already initialized EGL display connection has no effect besides returning the version numbers.
*/
if (eglInitialize (display, NULL, NULL) == EGL_FALSE) {
EGLint error = eglGetError ();
if (error == EGL_BAD_DISPLAY) {
throw U::InitException ("eglInitialize returned EGL_BAD_DISPLAY : display is not an EGL display connection.");
}
if (error == EGL_NOT_INITIALIZED) {
throw U::InitException ("eglInitialize returned EGL_NOT_INITIALIZED : display cannot be initialized.");
}
}
printlog ("GraphicsService::initDisplay : eglInitialize (initialized or re-initialized). app->window=%p.", app->window);
/*
* Here specify the attributes of the desired configuration.
* Below, we select an EGLConfig with at least 8 bits per color
* component compatible with on-screen windows
*/
const EGLint attribs[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
// EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_NONE
};
// Może być wywołane wielokrotnie
EGLint numConfigs;
eglChooseConfig (display, attribs, NULL, 0, &numConfigs);
if (numConfigs < 1) {
throw U::InitException ("eglChooseConfig returned 0 configs matching supplied attribList.");
}
/*
* Here, the application chooses the configuration it desires. In this
* sample, we have a very simplified selection process, where we pick
* the first EGLConfig that matches our criteria
*/
EGLConfig config;
// Może być wywołane wielokrotnie
if (eglChooseConfig (display, attribs, &config, 1, &numConfigs) == EGL_FALSE) {
switch (eglGetError ()) {
case EGL_BAD_DISPLAY:
throw U::InitException ("eglChooseConfig returned EGL_BAD_DISPLAY : display is not an EGL display connection.");
case EGL_BAD_ATTRIBUTE:
throw U::InitException ("eglChooseConfig returned EGL_BAD_ATTRIBUTE : attribute_list contains an invalid frame buffer configuration attribute or an attribute value that is unrecognized or out of range.");
case EGL_NOT_INITIALIZED:
throw U::InitException ("eglChooseConfig returned EGL_NOT_INITIALIZED : display has not been initialized.");
case EGL_BAD_PARAMETER:
throw U::InitException ("eglChooseConfig returned EGL_BAD_PARAMETER : num_config is NULL.");
}
}
// Ta metoda powinna być zawołana najwcześniej z onSurfaceCreated i wtedy app->window nie będzie null.
if (!app->window) {
return false;
}
/*
* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
* guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
* As soon as we picked a EGLConfig, we can safely reconfigure the
* ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID.
*/
EGLint format;
eglGetConfigAttrib (display, config, EGL_NATIVE_VISUAL_ID, &format);
ANativeWindow_setBuffersGeometry (app->window, 0, 0, format);
if (this->surface == EGL_NO_SURFACE) {
EGLSurface surface = eglCreateWindowSurface (display, config, app->window, NULL);
if (surface == EGL_NO_SURFACE) {
throw U::InitException ("eglCreateWindowSurface returned EGL_NO_SURFACE.");
}
this->surface = surface;
printlog ("GraphicsService::initDisplay : eglCreateWindowSurface...");
}
if (this->context == EGL_NO_CONTEXT) {
const EGLint attribList[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
EGLContext context = eglCreateContext (display, config, NULL, attribList);
if (context == EGL_NO_CONTEXT) {
throw U::InitException ("eglCreateContext returned EGL_NO_CONTEXT.");
}
this->context = context;
printlog ("GraphicsService::initDisplay : eglCreateContext...");
}
printlog ("GraphicsService::initDisplay : eglMakeCurrent (%p, %p, %p, %p);", display, surface, surface, context);
if (eglMakeCurrent (display, surface, surface, context) == EGL_FALSE) {
printlog ("GraphicsService::initDisplay : eglMakeCurrent (%p, %p, %p, %p); FAILED. Throwing an exception!", display, surface, surface, context);
switch (eglGetError ()) {
case EGL_BAD_DISPLAY: throw U::InitException ("EGL_BAD_DISPLAY is generated if display is not an EGL display connection.");
case EGL_NOT_INITIALIZED: throw U::InitException ("EGL_NOT_INITIALIZED is generated if display has not been initialized.");
case EGL_BAD_SURFACE: throw U::InitException ("EGL_BAD_SURFACE is generated if draw or read is not an EGL surface.");
case EGL_BAD_CONTEXT: throw U::InitException ("EGL_BAD_CONTEXT is generated if context is not an EGL rendering context.");
case EGL_BAD_MATCH: throw U::InitException ("EGL_BAD_MATCH is generated if draw or read are not compatible with context, or if context is set to EGL_NO_CONTEXT and draw or read are not set to EGL_NO_SURFACE, or if draw or read are set to EGL_NO_SURFACE and context is not set to EGL_NO_CONTEXT.");
case EGL_BAD_ACCESS: throw U::InitException ("EGL_BAD_ACCESS is generated if context is current to some other thread.");
case EGL_BAD_NATIVE_PIXMAP: throw U::InitException ("EGL_BAD_NATIVE_PIXMAP may be generated if a native pixmap underlying either draw or read is no longer valid.");
case EGL_BAD_NATIVE_WINDOW: throw U::InitException ("EGL_BAD_NATIVE_WINDOW may be generated if a native window underlying either draw or read is no longer valid.");
case EGL_BAD_CURRENT_SURFACE: throw U::InitException ("EGL_BAD_CURRENT_SURFACE is generated if the previous context has unflushed commands and the previous surface is no longer valid.");
case EGL_BAD_ALLOC: throw U::InitException ("EGL_BAD_ALLOC may be generated if allocation of ancillary buffers for draw or read were delayed until eglMakeCurrent is called, and there are not enough resources to allocate them.");
case EGL_CONTEXT_LOST: throw U::InitException ("EGL_CONTEXT_LOST is generated if a power management event has occurred. The application must destroy all contexts and reinitialise OpenGL ES state and objects to continue rendering.");
}
}
return true;
}
/****************************************************************************/
void GraphicsService::termDisplay ()
{
if (this->display != EGL_NO_DISPLAY) {
if (eglMakeCurrent (this->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT) == EGL_FALSE) {
throw U::InitException ("eglMakeCurrent failed");
}
if (this->context != EGL_NO_CONTEXT) {
if (eglDestroyContext (this->display, this->context) == EGL_FALSE) {
throw U::InitException ("eglDestroyContext failed");
}
}
if (this->surface != EGL_NO_SURFACE) {
if (eglDestroySurface (this->display, this->surface) == EGL_FALSE) {
throw U::InitException ("eglDestroySurface failed");
}
}
eglTerminate (this->display);
printlog ("GraphicsService::termDisplay : terminated.");
}
this->display = EGL_NO_DISPLAY;
this->context = EGL_NO_CONTEXT;
this->surface = EGL_NO_SURFACE;
}
/****************************************************************************/
void GraphicsService::unbindSurfaceAndContext ()
{
/*
* When we receive a surfaceDestroyed callback, we must immediately unbind the
* EGLSurface and EGLContext (eglMakeCurrent with display, NULL, NULL) and
* must stop rendering.
*
*/
if (this->display != EGL_NO_DISPLAY) {
if (eglMakeCurrent (display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT) == EGL_FALSE) {
throw U::InitException ("eglMakeCurrent failed");
}
}
if (surface != EGL_NO_SURFACE) {
if (eglDestroySurface (display, surface) == EGL_FALSE) {
throw U::InitException ("eglDestroySurface failed");
}
surface = EGL_NO_SURFACE;
}
printlog ("GraphicsService::unbindSurfaceAndContext : done.");
}
/****************************************************************************/
bool GraphicsService::saveScreenDimensionsInConfig (Util::Config *config)
{
/*
* Ponieważ ten event lubi pojawiać się w losowych momentach, należy sprawdzić, czy
* display i surface są OK.
*/
if (display == EGL_NO_DISPLAY || surface == EGL_NO_SURFACE) {
return false;
}
EGLint w, h;
if (eglQuerySurface (display, surface, EGL_WIDTH, &w) == EGL_FALSE) {
throw U::InitException ("eglQuerySurface failed");
}
if (eglQuerySurface (display, surface, EGL_HEIGHT, &h) == EGL_FALSE) {
throw U::InitException ("eglQuerySurface failed");
}
config->autoViewport = true;
config->viewportWidth = w;
config->viewportHeight = h;
if (config->autoProjection) {
config->projectionWidth = w;
config->projectionHeight = h;
}
printlog ("GraphicsService::saveScreenDimensionsInConfig : w=%d, h=%d, autoProjection=%d.", w, h, config->autoProjection);
return true;
}
/****************************************************************************/
void GraphicsService::swapBuffers ()
{
// glFlush ();
// glFinish ();
eglSwapBuffers (display, surface);
}
|
#pragma once
/*
It's an interface for IP headers used within the project.
It allow to create different IP headers for different platforms, consequently, the cross-platform is easily implementable.
All IP headers within in the project must inherit of this interface.
*/
#include <stdint.h>
class IIPHeader
{
public:
virtual ~IIPHeader() {}
//Mutators methods, set all fields for the IP header
virtual void set_ihl(uint8_t ihl) = 0;
virtual void set_version(uint8_t version) = 0;
virtual void set_tos(uint8_t tos) = 0;
virtual void set_tot_len(uint16_t tot_len) = 0;
virtual void set_id(uint16_t id) = 0;
virtual void inc_id() = 0;
virtual void set_frag_off(uint16_t frag_off) = 0;
virtual void set_ttl(uint8_t ttl) = 0;
virtual void set_protocol(uint8_t protocol) = 0;
virtual void set_check(uint16_t check) = 0;
virtual void set_saddr(uint32_t saddr) = 0;
virtual void set_daddr(uint32_t daddr) = 0;
virtual void setOptionsField(void *data, unsigned int size) = 0;
virtual void setSizeOptionsFieldsExpected(unsigned int size) = 0;
//Accessors methods for the data header
virtual void *getData() = 0;
virtual void *getOptionsFields() = 0;
virtual unsigned int getSize() const = 0;
virtual uint8_t get_ihl() const = 0;
virtual uint8_t get_version() const = 0;
virtual uint8_t get_tos() const = 0;
virtual uint16_t get_tot_len() const = 0;
virtual uint16_t get_id() const = 0;
virtual uint16_t get_frag_off() const = 0;
virtual uint8_t get_ttl() const = 0;
virtual uint8_t get_protocol() const = 0;
virtual uint16_t get_check() const = 0;
virtual uint32_t get_saddr() const = 0;
virtual uint32_t get_daddr() const = 0;
//Load the header from the data received
virtual bool load(const void *data) = 0;
};
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "InventoryManagerComponent.h"
#include "InventoryComponent.h"
// Sets default values for this component's properties
UInventoryManagerComponent::UInventoryManagerComponent()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = false;
// ...
}
// Called when the game starts
void UInventoryManagerComponent::BeginPlay()
{
Super::BeginPlay();
// ...
}
// Called every frame
void UInventoryManagerComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// ...
}
void UInventoryManagerComponent::ServerMoveItemFromExternalInventoryAtIndex_Implementation(UInventoryComponent *ToInventory, UInventoryComponent *FromInventory, int32 ToIndex, int32 FromIndex)
{
if (ToInventory == nullptr || FromInventory == nullptr)
{
UE_LOG(LogTemp, Warning, TEXT("One of incoming components is null"));
return;
}
bool Result = ToInventory->MoveItemFromExternalInventoryAtIndex(FromInventory, ToIndex, FromIndex);
UE_LOG(LogTemp, Warning, TEXT("%s added item"), Result ? TEXT("Successfully") : TEXT("Unsuccessfully"));
}
void UInventoryManagerComponent::ServerMoveItemFromExternalInventory_Implementation(UInventoryComponent * ToInventory, UInventoryComponent * FromInventory, int32 FromIndex)
{
if (ToInventory == nullptr || FromInventory == nullptr)
{
UE_LOG(LogTemp, Warning, TEXT("One of incoming components is null"));
return;
}
bool Result = ToInventory->MoveItemFromExternalInventory(FromInventory, FromIndex);
UE_LOG(LogTemp, Warning, TEXT("%s added item"), Result ? TEXT("Successfully") : TEXT("Unsuccessfully"))
}
void UInventoryManagerComponent::SetPlayerInventoryComponentReference(UInventoryComponent * NewPlayerInventoryComponent)
{
PlayerInventoryComponent = NewPlayerInventoryComponent;
}
void UInventoryManagerComponent::UpdateExternalInventoryComponentReference(UInventoryComponent * NewExternalInventoryComponent)
{
ExternalInventoryComponent = NewExternalInventoryComponent;
}
|
#include "drawable_cloud.h"
#include <math.h>
void DrawableCloud::Draw() const
{
// fprintf(stderr, "DrawableCloud::Draw()\n");
if (!_cloud_ptr)
{
throw std::runtime_error("DrawableCloud has no cloud to draw.");
}
// fprintf(stderr, "DrawableCloud::Draw() after _cloud_ptr check\n");
glPushMatrix();
glPointSize(_pointSize);
glBegin(GL_POINTS);
// glColor3f(_color[0], _color[1], _color[2]);
// fprintf(stderr, "there has about %ld points\n", _cloud_ptr->size());
// bool multiColor = ((*_cloud_ptr)[0].classID != -1);
bool multiColor = (_numCluster != -1);
for (const auto & point : _cloud_ptr->points())
{
if (!multiColor)
{
glColor3f(_color[0], _color[1], _color[2]);
}
else
{
int classID = point.classID % _param.RANDOM_COLORS.size();
// fprintf(stderr, "classID[%d]\n", classID);
glColor3f((float)_param.RANDOM_COLORS[classID][0] / 255,
(float)_param.RANDOM_COLORS[classID][1] / 255,
(float)_param.RANDOM_COLORS[classID][2] / 255
);
}
auto real_point = point.AsEigenVector();
// fprintf(stderr, "(%f, %f, %f)\n", real_point.x(), real_point.y(), real_point.z());
glVertex3f(real_point.x(), real_point.y(), real_point.z());
}
glEnd();
glPopMatrix();
}
DrawableCloud::Ptr DrawableCloud::FromCloud(const Cloud::ConstPtr& cloud,
const Eigen::Vector3f& color,
const GLfloat & pointSize,
const int numCluster)
{
return std::make_shared<DrawableCloud>(DrawableCloud(cloud, color, pointSize, numCluster));
}
|
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <math.h>
#include <cstdlib>
#include <cstring>
#include <string>
using namespace std;
class o1strings{
public :
int k;
static int testcase;
char value;
string str = "0";
string rev_str;
void buildstring(){
for( long long i=1;i<22;i++){
rev_str ="";
for(long long j=str.length()-1;j>=0;j--){
rev_str += str[j];
}
for(long long k=0;k<rev_str.length();k++){
if(rev_str[k] == '0'){
rev_str[k] = '1';
}
else{
rev_str[k] = '0';
}
}
str.push_back('0');
str.append(rev_str);
}
}
void getdetails(string temp_line){
//cin>>k;
int k = atoi(temp_line.c_str());
if(k > pow(10,5) || k < 1){exit(0);}
int find_pos = k-1;
//cout<<"find pos"<<find_pos<<endl;
for(int i=0;i<str.length();i++){
if(i == find_pos)
value = str[find_pos];
}
// cout<<"Case #"<<o1strings::testcase<<" : ";
//cout<<value<<endl;
}
};
int o1strings::testcase=0;
int main()
{
ofstream outfile;
ifstream infile;
string line;
infile.open("A-large.in");
outfile.open("outputfile.txt");
getline(infile,line);
int tests = atoi(line.c_str());
vector<o1strings> objects;
//cin>>tests;
if(tests >100 || tests < 1){return 0;}
objects.resize(tests);
for(int i=0;i<objects.size();i++){
o1strings::testcase += 1;
objects[i].buildstring();
string temp_line;
getline(infile,temp_line);
objects[i].getdetails(temp_line);
}
for(int i=0;i<objects.size();i++){
cout<<"Case #"<<i+1<<": ";
cout<<objects[i].value<<endl;
outfile<<"Case #"<<i+1<<": ";
outfile<<objects[i].value<<'\n';
}
return 0;
}
|
#include <iostream>
#include <vector>
using namespace std;
int contComp=0;
//&function
void Particion(vector<int> &d, int ini, int fin, int &pivote){
int elempivote = d[ini], j = ini;
for(int i = ini + 1 ; i <= fin; i++)
{
if(d[i] < elempivote)
{
swap(d[i], d[++j]);
}
contComp++;
}
pivote = j;
swap(d[ini],d[pivote]);
}
void QuickSort(vector<int> &d, int ini, int fin){
int pivote;
if(ini < fin)
{
Particion( d , ini , fin , pivote);
QuickSort( d , ini , pivote -1);
QuickSort( d , pivote + 1, fin);
}
}
int main(){
int n;
cin >> n;
vector<int> datos(n);
for (int i=0; i<n; i++){
cin>>datos[i];
}
QuickSort(datos, 0, n-1);
cout << contComp<<endl;
for (int i=0; i<n; i++){
cout<<datos[i]<< " ";
}
cout << endl;
}
|
//
// MachineDefinition.cpp
// Landru
//
// Created by Nick Porcino on 10/28/14.
//
//
#include "MachineDefinition.h"
#include "Property.h"
#include "State.h"
namespace Landru {
MachineDefinition::~MachineDefinition() {
for (auto i : states)
delete i.second;
for (auto i : properties)
delete i.second;
}
}
|
#include "Button.h"
Button::Button(SDL_Rect *r, /*SDL_Texture *t*/SDL_Surface *s):GameInterface(r,/*t*/s)
{
}
bool Button::isActive(Uint32 mouseState, SDL_Event event)
{
return mouseState == SDL_BUTTON_LEFT&&event.type==SDL_MOUSEBUTTONUP;
}
|
#include "Ad.h"
#include "Utils.h"
Ad::Ad()
: QWidget()
{
idEmploye = 0;
day = 0;
setAd();
}
void Ad::setAd()
{
layoutAd = new QGridLayout(this);
teamValueDisplay = new QLabel("+100%", this);
QLabel* valueText = new QLabel(tr("Last performance"), this);
QGroupBox* groupTeam = new QGroupBox(tr("Team"), this);
QVBoxLayout* layoutGroupTemporaire = new QVBoxLayout(this);
QWidget* widgetTeam = new QWidget(this);
QHBoxLayout* layoutGroup = new QHBoxLayout(this);
DropEmployee* manager = new DropEmployee(this);
QVBoxLayout* layoutManager = new QVBoxLayout(this);
DropEmployee* designer = new DropEmployee(this);
QVBoxLayout* layoutDesigner = new QVBoxLayout(this);
DropEmployee* artisana = new DropEmployee(this);
QVBoxLayout* layoutArtisan = new QVBoxLayout(this);
QGroupBox* groupCommercial = new QGroupBox(tr("Commercial"), this);
QVBoxLayout* widgetCommercial = new QVBoxLayout(this);
DropEmployee* commercial = new DropEmployee(this);
layoutcommercial = new QVBoxLayout(this);
QGroupBox* groupNew = new QGroupBox(tr("New"), this);
QVBoxLayout* layoutNewT = new QVBoxLayout(this);
QWidget* widgetNewT = new QWidget(this);
widgetNew = new QVBoxLayout(this);
displayNewEmploye = new QWidget(this);
QWidget* widgetTrash = new QWidget(this);
QVBoxLayout* layoutTrash = new QVBoxLayout(this);
DropEmployee* trash = new DropEmployee(this);
QVBoxLayout* trashlayout = new QVBoxLayout(this);
QLabel* trashlabel = new QLabel(this);
this->setLayout(layoutAd);
layoutAd->addWidget(teamValueDisplay, 1, 0, 1, 4);
layoutAd->addWidget(valueText, 0, 0, 1, 4);
layoutAd->addWidget(groupTeam, 2, 0, 2, 6);
groupTeam->setLayout(layoutGroupTemporaire);
layoutGroupTemporaire->addWidget(widgetTeam);
widgetTeam->setLayout(layoutGroup);
layoutGroup->addWidget(manager);
layoutGroup->addWidget(designer);
layoutGroup->addWidget(artisana);
manager->setLayout(layoutManager);
designer->setLayout(layoutDesigner);
artisana->setLayout(layoutArtisan);
layoutAd->addWidget(groupNew, 0, 6, 2, 1);
groupNew->setLayout(layoutNewT);
layoutNewT->addWidget(widgetNewT);
widgetNewT->setLayout(widgetNew);
widgetNew->addWidget(displayNewEmploye);
layoutAd->addWidget(widgetTrash, 1, 5, 1, 1);
widgetTrash->setLayout(layoutTrash);
layoutTrash->addWidget(trash);
trash->setLayout(trashlayout);
trashlayout->addWidget(trashlabel);
layoutAd->addWidget(groupCommercial, 2, 6, 2, 1);
groupCommercial->setLayout(widgetCommercial);
widgetCommercial->addWidget(commercial);
commercial->setLayout(layoutcommercial);
manager->setObjectName("0");
designer->setObjectName("1");
artisana->setObjectName("2");
layoutManager->setObjectName("l0");
layoutDesigner->setObjectName("l1");
layoutArtisan->setObjectName("l2");
commercial->setAcceptCommercial(true);
displayNewEmploye->setObjectName("new");
trash->setObjectName("trash");
callNewEmploye();
trash->setIsTrash(true);
SingleData* getData = getData->getInstance();
getData->addLabelToAdaptOnTheme("trash", trashlabel);
getData->addLabelToAdaptOnFont(4, teamValueDisplay);
connect(manager, SIGNAL(transfertDataEmployee(const int&, const int&)), this, SLOT(employeChanged(const int&, const int&)));
connect(designer, SIGNAL(transfertDataEmployee(const int&, const int&)), this, SLOT(employeChanged(const int&, const int&)));
connect(artisana, SIGNAL(transfertDataEmployee(const int&, const int&)), this, SLOT(employeChanged(const int&, const int&)));
connect(trash, SIGNAL(transfertDataEmployee(const int&, const int&)), this, SLOT(employeeToTrash(const int&, const int&)));
connect(commercial, SIGNAL(transfertDataEmployee(const int&, const int&)), this, SLOT(commercialChanged(const int&, const int&)));
//Theme
groupTeam->setMinimumHeight(200);
groupTeam->setMinimumWidth(500);
layoutGroupTemporaire->setSpacing(0);
layoutGroup->setContentsMargins(0, 0, 0, 0);
groupNew->setMinimumHeight(195);
groupNew->setMinimumWidth(groupNew->height() * 0.90);
layoutTrash->setContentsMargins(0, 0, 0, 0);
trashlayout->setContentsMargins(0, 0, 0, 0);
layoutAd->setAlignment(groupNew, Qt::AlignBottom);
layoutAd->setAlignment(valueText, Qt::AlignBottom | Qt::AlignRight);
layoutAd->setAlignment(teamValueDisplay, Qt::AlignTop | Qt::AlignRight);
trashlayout->setAlignment(trashlabel, Qt::AlignBottom | Qt::AlignRight);
manager->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
designer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
artisana->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
teamValueDisplay->setObjectName("titleAd");
groupTeam->setObjectName("groupTeam");
groupCommercial->setObjectName("groupCommercial");
groupNew->setObjectName("groupNew");
teamValueDisplay->setToolTip(tr("Increase in sales volume due to your team"));
}
void Ad::callNewEmploye()
{
DragEmployee* getNew = this->findChild<DragEmployee*>("new");
delete getNew;
getNew = nullptr;
DragEmployee* newEmplo1 = new DragEmployee();
widgetNew->addWidget(newEmplo1);
newEmplo1->setObjectName("new");
}
QString Ad::getSalary_Efficiency(int addDays)
{
day += addDays;
int lvls = 0;
int salary = 0;
double efficiency = 1;
double actualEfficiency = 0;
int sizeList = (int)employeList.size();
for (int i = 0; i < sizeList; i++)
{
lvls = employeList.at(i)->getLvl();
actualEfficiency = 1;
for (int i = 0; i < lvls; i++)
{
actualEfficiency *= 1.20 + Utils::randOnlyPositivePercentage(10);
}
efficiency += actualEfficiency - 1;
salary += employeList.at(i)->getSalary();
}
if (day < 30)
{
salary = 0;
}
else
{
day -= 30;
}
teamValueDisplay->setText("+" + QString::number(round(efficiency * 100)) + "%");
teamValueDisplay->setStyleSheet("color:#b2ff59; font-size:80px;background-color:transparent;");
callNewEmploye();
return QString("%1$%2").arg(salary).arg(efficiency);
}
void Ad::employeChanged(const int& id, const int& pos)
{
bool emptyDestination = true;
int sizeList = (int)employeList.size();
int idOldEmploye = 0;
for (int i = 0; i < sizeList; i++)
{
if (employeList.at(i)->getPos() == sender()->objectName().toInt())
{
emptyDestination = false;
idOldEmploye = i;
}
}
if (id == -1)
{
if (!emptyDestination)
{
delete employeList.at(idOldEmploye);
employeList.at(idOldEmploye) = nullptr;
employeList.erase(employeList.begin() + idOldEmploye);
}
DragEmployee* getNewE = this->findChild<DragEmployee*>("new");
layoutAd->removeWidget(getNewE);
QVBoxLayout* layoutToAdd = this->findChild<QVBoxLayout*>("l" + sender()->objectName());
layoutToAdd->addWidget(getNewE);
employeList.push_back(getNewE);
getNewE->setObjectName("z");
getNewE->setId(idEmploye++);
getNewE->setTrashable(true);
getNewE->setPos(sender()->objectName().toInt());
return;
}
if (emptyDestination)
{
int pos1 = -2;
int pos1List = -2;
for (int i = 0; i < sizeList; i++)
{
if (employeList.at(i)->getPos() == pos)
{
pos1 = employeList.at(i)->getPos();
pos1List = i;
}
}
QVBoxLayout* getLFrom = this->findChild<QVBoxLayout*>("l" + QString::number(pos1));
getLFrom->removeWidget(employeList.at(pos1List));
QVBoxLayout* getLTo = this->findChild<QVBoxLayout*>("l" + sender()->objectName());
getLTo->addWidget(employeList.at(pos1List));
employeList.at(pos1List)->setPos(sender()->objectName().toInt());
}
else
{
int pos1 = -2;
int pos1List = -2;
int pos2 = -2;
int pos2List = -2;
for (int i = 0; i < sizeList; i++)
{
if (employeList.at(i)->getPos() == pos)
{
pos1 = employeList.at(i)->getPos();
pos1List = i;
}
if (employeList.at(i)->getPos() == sender()->objectName().toInt())
{
pos2 = employeList.at(i)->getPos();
pos2List = i;
}
}
QVBoxLayout* getLFrom = this->findChild<QVBoxLayout*>("l" + QString::number(pos1));
getLFrom->removeWidget(employeList.at(pos1List));
QVBoxLayout* getLTo = this->findChild<QVBoxLayout*>("l" + QString::number(pos2));
getLTo->removeWidget(employeList.at(pos2List));
getLTo->addWidget(employeList.at(pos1List));
getLFrom->addWidget(employeList.at(pos2List));
employeList.at(pos1List)->setPos(sender()->objectName().toInt());
employeList.at(pos2List)->setPos(pos);
}
}
void Ad::employeeToTrash(const int& id, const int& pos)
{
int sizeEmploye = (int)employeList.size();
if (commercialCurrent.size() > 0)
{
if (commercialCurrent.at(0)->getId() == id)
{
delete commercialCurrent.at(0);
commercialCurrent.at(0) = nullptr;
commercialCurrent.erase(commercialCurrent.begin());
emit fireCommercial();
return;
}
}
for (int i = 0; i < sizeEmploye; i++)
{
if (employeList.at(i)->getId() == id)
{
delete employeList.at(i);
employeList.at(i) = nullptr;
employeList.erase(employeList.begin() + i);
return;
}
}
}
void Ad::commercialChanged(const int& id, const int& pos)
{
if (id == -1)
{
if (commercialCurrent.size() > 0)
{
delete commercialCurrent.at(0);
commercialCurrent.at(0) = nullptr;
commercialCurrent.erase(commercialCurrent.begin());
}
DragEmployee* getNewC = this->findChild<DragEmployee*>("new");
layoutAd->removeWidget(getNewC);
layoutcommercial->addWidget(getNewC);
commercialCurrent.push_back(getNewC);
getNewC->setId(idEmploye++);
getNewC->setTrashable(true);
getNewC->setObjectName("z");
emit newCommercial(getNewC);
}
}
void Ad::teamPushToDB()
{
ItemDAO::getInstance()->pushEmployee(employeList, commercialCurrent);
}
void Ad::setNewTableLoaded()
{
qDeleteAll(employeList.begin(), employeList.end());
qDeleteAll(commercialCurrent.begin(), commercialCurrent.end());
employeList.clear();
commercialCurrent.clear();
std::vector<DragEmployee*> temporaryList = ItemDAO::getInstance()->getEmployeList();
int pos = 0;
int sizeList = (int)temporaryList.size();
for (int i = 0; i < sizeList; i++)
{
if (temporaryList.at(i)->getIsCommercial())
{
layoutcommercial->addWidget(temporaryList.at(i));
temporaryList.at(i)->setId(idEmploye++);
temporaryList.at(i)->setTrashable(true);
temporaryList.at(i)->setObjectName("z");
commercialCurrent.push_back(temporaryList.at(i));
}
else
{
QVBoxLayout* layoutToAdd = this->findChild<QVBoxLayout*>("l" + QString::number(pos));
layoutToAdd->addWidget(temporaryList.at(i));
temporaryList.at(i)->setObjectName("z");
temporaryList.at(i)->setId(idEmploye++);
temporaryList.at(i)->setTrashable(true);
temporaryList.at(i)->setPos(pos++);
employeList.push_back(temporaryList.at(i));
}
}
if (commercialCurrent.size() > 0)
{
emit newCommercial(commercialCurrent.at(0));
}
}
|
#pragma once
#include <QWidget>
#include "ToDoWidgets/TaskWidget/Priority/specialtypes.h"
namespace Ui {
class PriorityWidget;
}
class PriorityWidget : public QWidget
{
Q_OBJECT
public:
PriorityWidget();
~PriorityWidget();
importanceDegree getImportance();
private:
Ui::PriorityWidget *ui;
};
|
/*
* op.cpp
*
* Created on: 2 mars 2014
* Author: droper
*/
#include <memory>
#include "op.h"
op::op() {
}
op::~op() {
child1.reset();
child2.reset();
}
void op::setChild1(std::shared_ptr<node> child) {
child1 = child;
}
void op::setChild2(std::shared_ptr<node> child) {
child2 = child;
}
std::shared_ptr<node> op::getChild1() {
return child1;
}
std::shared_ptr<node> op::getChild2() {
return child1;
}
size_t op::getDeep() {
size_t d1, d2;
if (child1 != NULL) {
d1 = child1->getDeep();
} else {
d1 = 0;
}
if (child2 != NULL) {
d2 = child2->getDeep();
} else {
d2 = 0;
}
return (d1 > d2 ? d1 : d2) + 1;
}
|
#ifndef SOLARSYSTEM_H
#define SOLARSYSTEM_H
#include "SimConstants.h"
#include "world.h"
#include <glm/glm.hpp>
#include "custom_sim_exceptions.h"
namespace Simulation {
class SolarSystem {
public:
SolarSystem(int ID);
~SolarSystem(void);
void Init(glm::vec2);
void Update(float dt);
void AddWorld (World* newworld);
int getID() { return this->ID; }
glm::vec2 getPosition() { return this->position; }
int getWorldCount() { return this->world_count; }
World** getWorlds() { return this->worlds; }
private:
int ID;
glm::vec2 position = glm::vec2(MAX_XY_WORLDPOS+1, MAX_XY_WORLDPOS+1);
World* worlds[MAX_WORLDS_PER_SOLARSYSTEM] = {NULL};
int world_count = 0;
};
}
#endif
|
// Parses a sequence of texts into separate lines. Client defines
// the delimiter. Parsed output is returned as a vector of strings.
#ifndef UTILS_QSORT_QSORT_H_
#define UTILS_QSORT_QSORT_H_
#include <fstream> // TODO: Remove after FileWriter is implemented
#include <iostream> // DEBUG
#include <string>
#include <vector>
#include "utils/error_handling/status.h"
#include "utils/file/filewriter.h"
namespace utils {
namespace sort {
using utils::error_handling::Status;
using utils::file::filewriter::FileWriter;
template <typename T>
class QuickSort {
public:
QuickSort(std::vector<T> v) : v_(std::move(v)) {}
void Sort() { Sorthelper(0, v_.size() - 1); }
// Writes v_ to file, then empties it.
utils::error_handling::Status WriteToFile(const std::string& filepath) {
// TODO: Define a filewriter interface and implement.
// Ideally, it's a library for serializing data.
// FileWriter::WriteTo(filepath);
std::ofstream fp(filepath);
std::cout << "writing to " << filepath << std::endl; // DEBUG
if (!fp) {
std::cout << "couldn't open" << filepath << std::endl; // DEBUG
return utils::error_handling::Status::kError;
}
for (auto& element : v_) {
std::cout << "writing: " << element << std::endl;
fp << element << std::endl; // TODO: Does ostream make a copy?
}
v_.empty();
return utils::error_handling::Status::kOk;
}
// DEBUG
void Print() {
for (const auto& i : v_) std::cout << i << " ";
std::cout << std::endl;
}
protected:
void Sorthelper(int low, int high) {
if (low < high) {
int p = Partition(low, high);
Sorthelper(low, p - 1);
Sorthelper(p + 1, high);
}
}
int Partition(int low, int high) {
T pivot_element = v_[high];
int back_index = low - 1;
for (int front_index = low; front_index < high; ++front_index) {
auto& current_element = v_[front_index];
if (current_element < pivot_element) {
Swap(++back_index, front_index);
}
}
Swap(++back_index, high);
return back_index;
}
void Swap(int i, int j) {
T tmp = std::move(v_[i]);
v_[i] = std::move(v_[j]);
v_[j] = std::move(tmp);
}
private:
std::vector<T> v_;
};
// Factory function
template <typename T>
QuickSort<T> MakeQuickSort(std::vector<T>& v) {
return QuickSort<T>(v);
}
} // namespace sort
} // namespace utils
#endif
|
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <bitset>
#include <queue>
#include <algorithm>
#include <functional>
#include <cmath>
#include <cstdio>
#include <sstream>
#include <stack>
#include <istream>
#define INF 2000000001
#define SIZE 8
using namespace std;
typedef pair<int, int> P;
vector<vector<long long> > es(SIZE,vector<long long>(SIZE,INF));
class ThreeTeleports {
public:
int shortestDistance(int xMe, int yMe, int xHome, int yHome, vector <string> teleports)
{
vector<pair<long long, long long> > point;
point.push_back(make_pair(xMe, yMe));
point.push_back(make_pair(xHome, yHome));
vector<int> p(4);
for (int i=0; i<teleports.size(); ++i) {
for (int j=0; j<4; ++j) {
size_t pos = teleports[i].find(" ");
string s = teleports[i].substr(0,pos);
stringstream ss;
ss << s;
ss >> p[j];
teleports[i] = teleports[i].substr(pos+1,teleports[i].size());
}
point.push_back(make_pair(p[0], p[1]));
point.push_back(make_pair(p[2], p[3]));
es[(i+1)*2][(i+1)*2+1] = 10;
es[(i+1)*2+1][(i+1)*2] = 10;
}
for (int from=0; from<SIZE; ++from) {
for (int to=0; to<SIZE; ++to) {
if (from == to) {
continue;
}
if (es[from][to] == INF) {
es[from][to] = abs(point[from].first-point[to].first) + abs(point[from].second - point[to].second);
es[to][from] = es[from][to];
}
}
}
vector<long long> d(9,INF);
d[0] = 0;
priority_queue<P,vector<P>,greater<P> > q;
q.push(P(0,0));
while (!q.empty()) {
P p = q.top(); q.pop();
int v = p.second;
if (d[v] < p.first) {
continue;
}
for (int i=0; i<es[v].size(); ++i) {
if (d[i] > d[v] + es[v][i]) {
d[i] = d[v] + es[v][i];
q.push(P(d[i],i));
}
}
}
return static_cast<int>(d[1]);
}
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2011 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef OPURLFILTERAPI_H
#define OPURLFILTERAPI_H
#ifdef URL_FILTER
class URLFilterListener;
class AsyncURLFilterListener;
/**
* Interface for setting the URL filter listeners
*/
class OpUrlFilterApi
{
public:
virtual ~OpUrlFilterApi() {}
/** Set listener for the URL filter*/
virtual void SetURLFilterListener(URLFilterListener* listener) = 0;
#ifdef GOGI_URL_FILTER
/** Set listener for the asynchronous URL filter*/
virtual void SetAsyncURLFilterListener(AsyncURLFilterListener* listener) = 0;
#endif // GOGI_URL_FILTER
};
#endif // URL_FILTER
#endif // OPURLFILTERAPI_H
|
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <queue>
#include <set>
using namespace std;
struct ListNode{
int val;
ListNode* next;
ListNode(int x):val(x),next(NULL){}
};
void printLL(ListNode* head){
ListNode* temp = head;
while(temp!=NULL){
cout<<temp->val<<"->";
temp = temp->next;
}
}
ListNode* addNode(ListNode* head, int val){
if(head==NULL){
head = new ListNode(val);
}
else{
ListNode* temp = head;
while(temp->next!=NULL){
temp = temp->next;
}
temp->next = new ListNode(val);
}
return head;
}ListNode* insertionSort(ListNode* A){
ListNode* curr = A;
ListNode* ins = A;
while(ins->next){
curr = ins->next;
while(curr){
if(curr->val<ins->val){
int temp = curr->val;
curr->val = ins->val;
ins->val = temp;
}
curr = curr->next;
}
ins = ins->next;
}
return A;
}
int main(){
ListNode *head = NULL;
// = new ListNode();
int n,x;
cin>>n>>x;
for(int i =0;i<n;i++){
int val;
cin>>val;
head = addNode(head,val);
}
// printLL(head);
head = insertionSort(head);
printLL(head);
}
|
/*
* ReverseString.cpp
*
* @author: Collin Guarino
* Created: May 15, 2014
*/
#include <iostream>
using namespace std;
string inputString;
int main() {
cout << "Reverse String\n" << endl;
while(1) {
cout << "String to reverse: ";
cin >> inputString;
cout << string(inputString.rbegin(), inputString.rend()) << endl;
}
}
|
#pragma once
#ifndef __TEST02_H
#define __TEST02_H
#include <iostream>
#include <string>
#include "cpp_primer_config.h"
#ifdef USE_TEST02_H
class Test02
{
public:
void showBookInfo(void) const;
public:
Test02(std::string Name, unsigned int ID);
~Test02();
private:
std::string BookName;
unsigned int BookID;
};
#endif
#endif
|
#pragma once
#include <string>
#include "Cart.hpp"
class MyAccount
{
public:
MyAccount();
MyAccount(const std::string& name, const std::string& email, const std::string& password);
void enter_name(std::string name);
void enter_emai(std::string email);
void enter_password(std::string password);
void set_name(const std::string& new_name);
void set_email(const std::string& new_email);
void set_password(const std::string& new_password);
std::string get_username()const;
private:
std::string name;
std::string email;
std::string password;
Cart MyCart;
};
|
#include "pch.h"
#include "core.h"
using namespace System;
int main()
{
int n = 4, m = 7;
char InputAction;
bool checkForCycle = true, CheckForNegative, CheckForP = false, CheckForQ = false;
array<int, 2>^ P, ^ Q;
array<int>^ R, ^ T;
Console::Write("Lab 2\nSpecify values for integer elements of matrixes P and Q with dimension 4 by 7\nand form arrays R and T from the sums of negative elements of matrix rows P and\nQ respectively.\n");
while (checkForCycle) {
Console::WriteLine("Please choose action:");
Console::WriteLine("[1] - Generate matrix P.");
Console::WriteLine("[2] - Generate matrix Q.");
Console::WriteLine("[3] - Out matrix P.");
Console::WriteLine("[4] - Out matrix Q.");
Console::WriteLine("[5] - Calculate array P and out.");
Console::WriteLine("[6] - Calculate array T and out.");
Console::WriteLine("[0] - To finish.");
Console::Write("Your choice: ");
InputAction = Console::Read();
Console::ReadLine();
switch (InputAction - 48)
{
case 1:
P = MatrixIn(n, m);
CheckForP = true;
Console::WriteLine("\nMatrix P generate!\n");
break;
case 2:
Q = MatrixIn(n, m);
CheckForQ = true;
Console::WriteLine("\nMatrix Q generate!\n");
break;
case 3:
if (CheckForP)
{
Console::Write("\nMatrix P:");
MatrixOut(n, m, P);
}
else
Console::WriteLine("\nError! Enter the matrix P.\n");
break;
case 4:
if (CheckForQ)
{
Console::Write("\nMatrix Q:");
MatrixOut(n, m, Q);
}
else
Console::WriteLine("\nError! Enter the matrix Q.\n");
break;
case 5:
if (CheckForP)
{
R = Sum(n, m, P);
CheckForNegative = false;
for (int i = 0; i < n; i++)
if (R[i] == 0)
CheckForNegative = true;
if (CheckForNegative)
Console::WriteLine("Error! There is no one negative elements in the one of the rows.");
else
{
Console::Write("\nMatrix R:");
MatrixOut(R);
}
}
else
Console::WriteLine("\nError! Enter the matrix P.\n");
break;
case 6:
if (CheckForQ)
{
T = Sum(n, m, Q);
CheckForNegative = false;
for (int i = 0; i < n; i++)
if (T[i] == 0)
CheckForNegative = true;
if (CheckForNegative)
Console::WriteLine("Error! There is no one negative elements in the one of the rows.");
else
{
Console::Write("\nMatrix T:");
MatrixOut(T);
}
}
else
Console::WriteLine("\nError! Enter the matrix Q.\n");
break;
case 0:
checkForCycle = false;
break;
default:
Console::WriteLine("Wrong action!");
break;
}
}
return 0;
}
|
#pragma once
using boost::asio::ip::udp;
class AppDealer;
class UdpDealer
{
public:
UdpDealer(boost::asio::io_service& io_service, short port);
void do_receive();
void do_send(const std::string& data);
private:
boost::shared_ptr<AppDealer> _app_do;
udp::socket socket_;
udp::endpoint sender_endpoint_;
enum { max_length = 2048 };
char data_[max_length];
};
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp1 = fopen("F1.txt", "r");
FILE *fp2 = fopen("F_2.txt", "w");
char c;
while ((c = fgetc(fp1)) != EOF)
fputc(c, fp2);
fclose(fp1);
fclose(fp2);
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
**
** Copyright (C) 2004 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Morten Stenshorne
**
*/
/* This is the implementation of WAP Provisioning binary XML decoder, as
* specified in OMA-WAP-ProvCont-v1_1-20021112-C
*/
CONST_ARRAY(Provisioning_WBXML_tag_tokens, uni_char*)
CONST_ENTRY(UNI_L("wap-provisioningdoc")), // 0x05
CONST_ENTRY(UNI_L("characteristic")),
CONST_ENTRY(UNI_L("parm"))
CONST_END(Provisioning_WBXML_tag_tokens)
// code page 0
CONST_ARRAY(Provisioning_WBXML_attr_start_tokens, uni_char*)
CONST_ENTRY(UNI_L("name=\"")), // 0x05
CONST_ENTRY(UNI_L("value=\"")),
CONST_ENTRY(UNI_L("name=\"NAME")),
CONST_ENTRY(UNI_L("name=\"NAP-ADDRESS")), // 0x08
CONST_ENTRY(UNI_L("name=\"NAP-ADDRTYPE")),
CONST_ENTRY(UNI_L("name=\"CALLTYPE")),
CONST_ENTRY(UNI_L("name=\"VALIDUNTIL")),
CONST_ENTRY(UNI_L("name=\"AUTHTYPE")),
CONST_ENTRY(UNI_L("name=\"AUTHNAME")),
CONST_ENTRY(UNI_L("name=\"AUTHSECRET")),
CONST_ENTRY(UNI_L("name=\"LINGER")),
CONST_ENTRY(UNI_L("name=\"BEARER")), // 0x10
CONST_ENTRY(UNI_L("name=\"NAPID")),
CONST_ENTRY(UNI_L("name=\"COUNTRY")),
CONST_ENTRY(UNI_L("name=\"NETWORK")),
CONST_ENTRY(UNI_L("name=\"INTERNET")),
CONST_ENTRY(UNI_L("name=\"PROXY-ID")),
CONST_ENTRY(UNI_L("name=\"PROXY-PROVIDER-ID")),
CONST_ENTRY(UNI_L("name=\"DOMAIN")),
CONST_ENTRY(UNI_L("name=\"PROVURL")), // 0x18
CONST_ENTRY(UNI_L("name=\"PXAUTH-TYPE")),
CONST_ENTRY(UNI_L("name=\"PXAUTH-ID")),
CONST_ENTRY(UNI_L("name=\"PXAUTH-PW")),
CONST_ENTRY(UNI_L("name=\"STARTPAGE")),
CONST_ENTRY(UNI_L("name=\"BASAUTH-ID")),
CONST_ENTRY(UNI_L("name=\"BASAUTH-PW")),
CONST_ENTRY(UNI_L("name=\"PUSHENABLED")),
CONST_ENTRY(UNI_L("name=\"PXADDR")), // 0x20
CONST_ENTRY(UNI_L("name=\"PXADDRTYPE")),
CONST_ENTRY(UNI_L("name=\"TO-NAPID")),
CONST_ENTRY(UNI_L("name=\"PORTNBR")),
CONST_ENTRY(UNI_L("name=\"SERVICE")),
CONST_ENTRY(UNI_L("name=\"LINKSPEED")),
CONST_ENTRY(UNI_L("name=\"DNLINKSPEED")),
CONST_ENTRY(UNI_L("name=\"LOCAL-ADDR")),
CONST_ENTRY(UNI_L("name=\"LOCAL-ADDRTYPE")), // 0x28
CONST_ENTRY(UNI_L("name=\"CONTEXT-ALLOW")),
CONST_ENTRY(UNI_L("name=\"TRUST")),
CONST_ENTRY(UNI_L("name=\"MASTER")),
CONST_ENTRY(UNI_L("name=\"SID")),
CONST_ENTRY(UNI_L("name=\"SOC")),
CONST_ENTRY(UNI_L("name=\"WSP-VERSION")),
CONST_ENTRY(UNI_L("name=\"PHYSICAL-PROXY-ID")),
CONST_ENTRY(UNI_L("name=\"CLIENT-ID")), // 0x30
CONST_ENTRY(UNI_L("name=\"DELIVERY-ERR-SDU")),
CONST_ENTRY(UNI_L("name=\"DELIVERY-ORDER")),
CONST_ENTRY(UNI_L("name=\"TRAFFIC-CLASS")),
CONST_ENTRY(UNI_L("name=\"MAX-SDU-SIZE")),
CONST_ENTRY(UNI_L("name=\"MAX-BITRATE-UPLINK")),
CONST_ENTRY(UNI_L("name=\"MAX-BITRATE-DNLINK")),
CONST_ENTRY(UNI_L("name=\"RESIDUAL-BER")),
CONST_ENTRY(UNI_L("name=\"SDU-ERROR-RATIO")), // 0x38
CONST_ENTRY(UNI_L("name=\"TRAFFIC-HANDL-PRIO")),
CONST_ENTRY(UNI_L("name=\"TRANSFER-DELAY")),
CONST_ENTRY(UNI_L("name=\"GUARANTEED-BITRATE-UPLINK")),
CONST_ENTRY(UNI_L("name=\"GUARANTEED-BITRATE-DNLINK")),
CONST_ENTRY(UNI_L("name=\"PXADDR-FQDN")),
CONST_ENTRY(UNI_L("name=\"PROXY-PW")),
CONST_ENTRY(UNI_L("name=\"PPGAUTH-TYPE")),
CONST_ENTRY(0), // 0x40
CONST_ENTRY(0), // 0x41
CONST_ENTRY(0), // 0x42
CONST_ENTRY(0), // 0x43
CONST_ENTRY(0), // 0x44
CONST_ENTRY(UNI_L("version=\"")), // 0x45
CONST_ENTRY(UNI_L("version=\"1.0")),
CONST_ENTRY(UNI_L("name=\"PULLENABLED")),
CONST_ENTRY(UNI_L("name=\"DNS-ADDR")),
CONST_ENTRY(UNI_L("name=\"MAX-NUM-RETRY")),
CONST_ENTRY(UNI_L("name=\"FIRST-RETRY-TIMEOUT")),
CONST_ENTRY(UNI_L("name=\"REREG-THRESHOLD")),
CONST_ENTRY(UNI_L("name=\"T-BIT")),
CONST_ENTRY(0), // 0x4d
CONST_ENTRY(UNI_L("name=\"AUTH-ENTITY")),
CONST_ENTRY(UNI_L("name=\"SPI")),
CONST_ENTRY(UNI_L("type=\"")), // 0x50
CONST_ENTRY(UNI_L("type=\"PXLOGICAL")),
CONST_ENTRY(UNI_L("type=\"PXPHYSICAL")),
CONST_ENTRY(UNI_L("type=\"PORT")),
CONST_ENTRY(UNI_L("type=\"VALIDITY")),
CONST_ENTRY(UNI_L("type=\"NAPDEF")),
CONST_ENTRY(UNI_L("type=\"BOOTSTRAP")),
CONST_ENTRY(UNI_L("type=\"VENDORCONFIG")),
CONST_ENTRY(UNI_L("type=\"CLIENTIDENTITY")),
CONST_ENTRY(UNI_L("type=\"PXAUTHINFO")),
CONST_ENTRY(UNI_L("type=\"NAPAUTHINFO")),
CONST_ENTRY(UNI_L("type=\"ACCESS"))
CONST_END(Provisioning_WBXML_attr_start_tokens)
// codes shared between code page 0 and 1
const UINT8 Provisioning_WBXML_attr_start_tokens_shared[] = {
0x05, 0x06, 0x07, 0x14, 0x1c, 0x22, 0x23, 0x24, 0x50, 0x53, 0x58 };
// code page 1
CONST_ARRAY(Provisioning_WBXML_attr_start_tokens_cp1, uni_char*)
CONST_ENTRY(UNI_L("name=\"AACCEPT")), // 0x2e
CONST_ENTRY(UNI_L("name=\"AAUTHDATA")),
CONST_ENTRY(UNI_L("name=\"AAUTHLEVEL")), // 0x30
CONST_ENTRY(UNI_L("name=\"AAUTHNAME")),
CONST_ENTRY(UNI_L("name=\"AAUTHSECRET")),
CONST_ENTRY(UNI_L("name=\"AAUTHTYPE")),
CONST_ENTRY(UNI_L("name=\"ADDR")),
CONST_ENTRY(UNI_L("name=\"ADDRTYPE")),
CONST_ENTRY(UNI_L("name=\"APPID")),
CONST_ENTRY(UNI_L("name=\"APROTOCOL")),
CONST_ENTRY(UNI_L("name=\"PROVIDER-ID")), // 0x38
CONST_ENTRY(UNI_L("name=\"TO-PROXY")),
CONST_ENTRY(UNI_L("name=\"URI")),
CONST_ENTRY(UNI_L("name=\"RULE")),
CONST_ENTRY(UNI_L(0)), // 0x3c
CONST_ENTRY(UNI_L(0)), // 0x3d
CONST_ENTRY(UNI_L(0)), // 0x3e
CONST_ENTRY(UNI_L(0)), // 0x3f
CONST_ENTRY(UNI_L(0)), // 0x40
CONST_ENTRY(UNI_L(0)), // 0x41
CONST_ENTRY(UNI_L(0)), // 0x42
CONST_ENTRY(UNI_L(0)), // 0x43
CONST_ENTRY(UNI_L(0)), // 0x44
CONST_ENTRY(UNI_L(0)), // 0x45
CONST_ENTRY(UNI_L(0)), // 0x46
CONST_ENTRY(UNI_L(0)), // 0x47
CONST_ENTRY(UNI_L(0)), // 0x48
CONST_ENTRY(UNI_L(0)), // 0x49
CONST_ENTRY(UNI_L(0)), // 0x4a
CONST_ENTRY(UNI_L(0)), // 0x4b
CONST_ENTRY(UNI_L(0)), // 0x4c
CONST_ENTRY(UNI_L(0)), // 0x4d
CONST_ENTRY(UNI_L(0)), // 0x4e
CONST_ENTRY(UNI_L(0)), // 0x4f
CONST_ENTRY(UNI_L(0)), // 0x50 // take from code page 0
CONST_ENTRY(UNI_L(0)), // 0x51
CONST_ENTRY(UNI_L(0)), // 0x52
CONST_ENTRY(UNI_L(0)), // 0x53 // take from code page 0
CONST_ENTRY(UNI_L(0)), // 0x54
CONST_ENTRY(UNI_L("type=\"APPLICATION")),
CONST_ENTRY(UNI_L("type=\"APPADDR")),
CONST_ENTRY(UNI_L("type=\"APPAUTH")),
CONST_ENTRY(UNI_L(0)), // 0x58 // take from code page 0
CONST_ENTRY(UNI_L("type=\"RESOURCE"))
CONST_END(Provisioning_WBXML_attr_start_tokens_cp1)
// code page 0
CONST_ARRAY(Provisioning_WBXML_attr_value_tokens, uni_char*)
CONST_ENTRY(UNI_L("IPV4")), // 0x85
CONST_ENTRY(UNI_L("IPV6")),
CONST_ENTRY(UNI_L("E164")),
CONST_ENTRY(UNI_L("ALPHA")),
CONST_ENTRY(UNI_L("APN")),
CONST_ENTRY(UNI_L("SCODE")),
CONST_ENTRY(UNI_L("TETRA-ITSI")),
CONST_ENTRY(UNI_L("MAN")),
CONST_ENTRY(UNI_L(0)), // 0x8d
CONST_ENTRY(UNI_L(0)), // 0x8e
CONST_ENTRY(UNI_L(0)), // 0x8f
CONST_ENTRY(UNI_L("ANALOG-MODEM")),
CONST_ENTRY(UNI_L("V.120")),
CONST_ENTRY(UNI_L("V.110")),
CONST_ENTRY(UNI_L("X.31")),
CONST_ENTRY(UNI_L("BIT-TRANSPARENT")),
CONST_ENTRY(UNI_L("DIRECT-ASYNCHRONOUS-DATA-SERVICE")),
CONST_ENTRY(UNI_L(0)), // 0x96
CONST_ENTRY(UNI_L(0)), // 0x97
CONST_ENTRY(UNI_L(0)), // 0x98
CONST_ENTRY(UNI_L(0)), // 0x99
CONST_ENTRY(UNI_L("PAP")),
CONST_ENTRY(UNI_L("CHAP")),
CONST_ENTRY(UNI_L("HTTP-BASIC")),
CONST_ENTRY(UNI_L("HTTP-DIGEST")),
CONST_ENTRY(UNI_L("WTLS-SS")),
CONST_ENTRY(UNI_L("MD5")),
CONST_ENTRY(UNI_L(0)), // 0xa0
CONST_ENTRY(UNI_L(0)), // 0xa1
CONST_ENTRY(UNI_L("GSM-USSD")),
CONST_ENTRY(UNI_L("GSM-SMS")),
CONST_ENTRY(UNI_L("ANSI-136-GUTS")),
CONST_ENTRY(UNI_L("IS-95-CDMA-SMS")),
CONST_ENTRY(UNI_L("IS-95-CDMA-CSD")),
CONST_ENTRY(UNI_L("IS-95-CDMA-PACKET")),
CONST_ENTRY(UNI_L("ANSI-136-CSD")),
CONST_ENTRY(UNI_L("ANSI-136-GPRS")),
CONST_ENTRY(UNI_L("GSM-CSD")),
CONST_ENTRY(UNI_L("GSM-GPRS")),
CONST_ENTRY(UNI_L("AMPS-CDPD")),
CONST_ENTRY(UNI_L("PDC-CSD")),
CONST_ENTRY(UNI_L("PDC-PACKET")),
CONST_ENTRY(UNI_L("IDEN-SMS")),
CONST_ENTRY(UNI_L("IDEN-CSD")),
CONST_ENTRY(UNI_L("IDEN-PACKET")),
CONST_ENTRY(UNI_L("FLEX/REFLEX")),
CONST_ENTRY(UNI_L("PHS-SMS")),
CONST_ENTRY(UNI_L("PHS-CSD")),
CONST_ENTRY(UNI_L("TETRA-SDS")),
CONST_ENTRY(UNI_L("TETRA-PACKET")),
CONST_ENTRY(UNI_L("ANSI-136-GHOST")),
CONST_ENTRY(UNI_L("MOBITEX-MPAK")),
CONST_ENTRY(UNI_L("CDMA2000-1X-SIMPLE-IP")),
CONST_ENTRY(UNI_L("CDMA2000-1X-MOBILE-IP")),
CONST_ENTRY(UNI_L(0)), // 0xbb
CONST_ENTRY(UNI_L(0)), // 0xbc
CONST_ENTRY(UNI_L(0)), // 0xbd
CONST_ENTRY(UNI_L(0)), // 0xbe
CONST_ENTRY(UNI_L(0)), // 0xbf
CONST_ENTRY(UNI_L(0)), // 0xc0
CONST_ENTRY(UNI_L(0)), // 0xc1
CONST_ENTRY(UNI_L(0)), // 0xc2
CONST_ENTRY(UNI_L(0)), // 0xc3
CONST_ENTRY(UNI_L(0)), // 0xc4
CONST_ENTRY(UNI_L("AUTOBAUDING")),
CONST_ENTRY(UNI_L(0)), // 0xc6
CONST_ENTRY(UNI_L(0)), // 0xc7
CONST_ENTRY(UNI_L(0)), // 0xc8
CONST_ENTRY(UNI_L(0)), // 0xc9
CONST_ENTRY(UNI_L("CL-WSP")),
CONST_ENTRY(UNI_L("CO-WSP")),
CONST_ENTRY(UNI_L("CL-SEC-WSP")),
CONST_ENTRY(UNI_L("CO-SEC-WSP")),
CONST_ENTRY(UNI_L("CL-SEC-WTA")),
CONST_ENTRY(UNI_L("CO-SEC-WTA")),
CONST_ENTRY(UNI_L("OTA-HTTP-TO")), // 0xd0
CONST_ENTRY(UNI_L("OTA-HTTP-TLS-TO")),
CONST_ENTRY(UNI_L("OTA-HTTP-PO")),
CONST_ENTRY(UNI_L("OTA-HTTP-TLS-PO")),
CONST_ENTRY(UNI_L(0)), // 0xd4
CONST_ENTRY(UNI_L(0)), // 0xd5
CONST_ENTRY(UNI_L(0)), // 0xd6
CONST_ENTRY(UNI_L(0)), // 0xd7
CONST_ENTRY(UNI_L(0)), // 0xd8
CONST_ENTRY(UNI_L(0)), // 0xd9
CONST_ENTRY(UNI_L(0)), // 0xda
CONST_ENTRY(UNI_L(0)), // 0xdb
CONST_ENTRY(UNI_L(0)), // 0xdc
CONST_ENTRY(UNI_L(0)), // 0xdd
CONST_ENTRY(UNI_L(0)), // 0xde
CONST_ENTRY(UNI_L(0)), // 0xdf
CONST_ENTRY(UNI_L("AAA")), // 0xe0
CONST_ENTRY(UNI_L("HA"))
CONST_END(Provisioning_WBXML_attr_value_tokens)
// codes shared between code page 0 and 1
const UINT8 Provisioning_WBXML_attr_value_tokens_shared[] = {
0x86, 0x87, 0x88
};
// code page 1
CONST_ARRAY(Provisioning_WBXML_attr_value_tokens_cp1, uni_char*)
CONST_ENTRY(UNI_L(",")), // 0x80
CONST_ENTRY(UNI_L("HTTP-")),
CONST_ENTRY(UNI_L("BASIC")),
CONST_ENTRY(UNI_L("DIGEST")),
CONST_ENTRY(UNI_L(0)), // 0x84
CONST_ENTRY(UNI_L(0)), // 0x85
CONST_ENTRY(UNI_L(0)), // 0x86 // take from code page 0
CONST_ENTRY(UNI_L(0)), // 0x87 // take from code page 0
CONST_ENTRY(UNI_L(0)), // 0x88 // take from code page 0
CONST_ENTRY(UNI_L(0)), // 0x89
CONST_ENTRY(UNI_L(0)), // 0x8a
CONST_ENTRY(UNI_L(0)), // 0x8b
CONST_ENTRY(UNI_L(0)), // 0x8c
CONST_ENTRY(UNI_L("APPSRV")), // 0x8d
CONST_ENTRY(UNI_L("OBEX"))
CONST_END(Provisioning_WBXML_attr_value_tokens_cp1)
class Provisioning_WBXML_ContentHandler : public WBXML_ContentHandler
{
public:
Provisioning_WBXML_ContentHandler(WBXML_Parser *parser)
: WBXML_ContentHandler(parser) {}
OP_WXP_STATUS Init();
const uni_char *TagHandler(UINT32 tok);
const uni_char *AttrStartHandler(UINT32 tok);
const uni_char *AttrValueHandler(UINT32 tok);
};
OP_WXP_STATUS Provisioning_WBXML_ContentHandler::Init()
{
return OpStatus::OK;
}
const uni_char *Provisioning_WBXML_ContentHandler::TagHandler(UINT32 tok)
{
if (tok < 0x05 || tok > 0x07)
return 0;
return Provisioning_WBXML_tag_tokens[tok - 0x05];
}
const uni_char *Provisioning_WBXML_ContentHandler::AttrStartHandler(UINT32 tok)
{
UINT32 cp = GetParser()->GetCodePage();
if (cp != 0 && cp != 1)
return 0;
if (cp == 0)
{
if (tok < 0x05 || tok > 0x5b)
return 0;
return Provisioning_WBXML_attr_start_tokens[tok - 0x05];
}
int i;
for (i=0; i<sizeof(Provisioning_WBXML_attr_start_tokens_shared); i++)
{
if (tok == Provisioning_WBXML_attr_start_tokens_shared[i])
return Provisioning_WBXML_attr_start_tokens[tok - 0x05];
}
if (tok < 0x2e || tok > 0x59)
return 0;
return Provisioning_WBXML_attr_start_tokens_cp1[tok - 0x2e];
}
const uni_char *Provisioning_WBXML_ContentHandler::AttrValueHandler(UINT32 tok)
{
UINT32 cp = GetParser()->GetCodePage();
if (cp != 0 && cp != 1)
return 0;
if (cp == 0)
{
if (tok < 0x85 || tok > 0xe1)
return 0;
return Provisioning_WBXML_attr_value_tokens[tok - 0x85];
}
int i;
for (i=0; i<sizeof(Provisioning_WBXML_attr_value_tokens_shared); i++)
{
if (tok == Provisioning_WBXML_attr_value_tokens_shared[i])
return Provisioning_WBXML_attr_value_tokens[tok - 0x85];
}
if (tok < 0x80 || tok > 0x8e)
return 0;
return Provisioning_WBXML_attr_value_tokens_cp1[tok - 0x80];
}
|
#include "stdafx.h"
#include "voxelList.h"
#include "voxelObject.h"
#include "neighbor.h"
voxelList::voxelList()
{
}
voxelList::~voxelList()
{
}
void voxelList::init()
{
updateBoundingBox();
}
void voxelList::updateBoundingBox()
{
Box b = getBoundingOfVoxels(m_voxelIdxs);
m_curLeftDown3F = b.leftDown;
m_curRightUp3F = b.rightUp;
}
Vec3f voxelList::centerPoint()
{
if (s_corressBondP->m_type == CENTER_BONE)
{
Vec3f sizef = m_curRightUp3F - m_curLeftDown3F;
sizef[0] = sizef[0] * 2;
return m_curLeftDown3F + sizef / 2;
}
else
{
return (m_curLeftDown3F + m_curRightUp3F) / 2;
}
}
Box voxelList::getBoundingOfVoxels(arrayInt idxs)
{
std::vector<voxelBox> *boxes = &s_voxelObj->m_boxes;
// Get current bounding box
Vec3f LD(MAX, MAX, MAX);
Vec3f RU(MIN, MIN, MIN);
Box b(LD, RU);
for (int i = 0; i < idxs.size(); i++)
{
voxelBox curB = boxes->at(idxs[i]);
b = combineBox(b, Box(curB.leftDown, curB.rightUp));
}
return b;
}
Box voxelList::combineBox(Box box1, Box box2)
{
Box newBox;
for (int i = 0; i < 3; i++)
{
newBox.leftDown[i] = Util::min_(box1.leftDown[i], box2.leftDown[i]);
newBox.rightUp[i] = Util::max_(box1.rightUp[i], box2.rightUp[i]);
}
return newBox;
}
arrayFloat voxelList::getErrorAssumeVoxelList(arrayInt idxs)
{
std::vector<voxelBox> *boxes = &s_voxelObj->m_boxes;
float voxelSize = s_voxelObj->m_voxelSizef;
// Optimize later if work
Box b = getBoundingOfVoxels(idxs);
// Volume
float volRatio = (float)idxs.size() / boxes->size();
float volumeE = Util::normSquareAbs(getExpectedVolumeRatioSym(), volRatio);
// aspect error
Vec3f curSize = b.rightUp - b.leftDown;
Vec3f xyzR = getSizeSym();
float e2 = 0;
for (int i = 0; i < 3; i++)
{
e2 += Util::normSquareAbs(xyzR[i]/xyzR[0], curSize[i] / curSize[0]);
}
float aspectE = e2 / 3;
// Fill error
float volF = idxs.size()*pow(voxelSize, 3);
float boxVolF = curSize[0] * curSize[1] * curSize[2];
float fillRatio = volF / boxVolF;
// Assign
arrayFloat err;
err.resize(ERROR_TYPE_NUM);
err[ASPECT_ERROR] = aspectE;
err[VOLUME_ERROR] = volumeE;
err[FILL_RATIO] = 1 - fillRatio;
return err;
}
float voxelList::getExpectedVolumeRatioSym()
{
if (s_corressBondP->m_type == CENTER_BONE)
{
return m_volumeRatio / 2.0;
}
else
{
return m_volumeRatio;
}
}
Vec3f voxelList::getSizeSym()
{
Vec3f s = m_BoxSize3F;
if (s_corressBondP->m_type == CENTER_BONE)
{
s[0] = s[0] / 2;
}
return s;
}
void voxelList::updateIdxs(arrayInt idxs)
{
m_voxelIdxs = idxs;
updateBoundingBox();
}
void voxelList::drawWire()
{
std::vector<voxelBox> * boxes = &s_voxelObj->m_boxes;
for (int i = 0; i < m_voxelIdxs.size(); i++)
{
voxelBox curB = boxes->at(m_voxelIdxs[i]);
Util_w::drawBoxWireFrame(curB.leftDown, curB.rightUp);
}
}
void voxelList::drawFace()
{
std::vector<voxelBox> * boxes = &s_voxelObj->m_boxes;
for (int i = 0; i < m_voxelIdxs.size(); i++)
{
voxelBox curB = boxes->at(m_voxelIdxs[i]);
Util_w::drawBoxSurface(curB.leftDown, curB.rightUp);
}
}
|
#pragma once
#pragma unmanaged
#include <BWAPI\Force.h>
#include <BWAPI\Forceset.h>
#pragma managed
#include "IIdentifiedObject.h"
using namespace System;
using namespace System::Collections::Generic;
namespace BroodWar
{
namespace Api
{
ref class Player;
public ref class Force sealed : public IIdentifiedObject
{
private:
BWAPI::Force instance;
internal:
Force(BWAPI::Force force);
public:
virtual property int Id { int get(); }
property String^ Name { String^ get(); }
property HashSet<Player^>^ Players { HashSet<Player^>^ get(); }
virtual int GetHashCode() override;
virtual bool Equals(Object^ o) override;
bool Equals(Api::Force^ other);
static bool operator == (Api::Force^ first, Api::Force^ second);
static bool operator != (Api::Force^ first, Api::Force^ second);
};
Force^ ConvertForce(BWAPI::Force force);
}
}
|
//======================================================================
#include <upl/input.hpp>
#include <cstdio>
//======================================================================
namespace UPL {
//======================================================================
UTF8FileStream::UTF8FileStream (Path const & file_path, Error::Reporter & rep)
: InputStream (rep)
, m_file (nullptr)
{
reporter().pushFileName (file_path);
m_file = fopen (file_path.c_str(), "rb");
if (nullptr == m_file)
{
setError();
reporter().newInputError (location(), 1, L"Cannot open input file.");
}
else
pop ();
}
//----------------------------------------------------------------------
UTF8FileStream::~UTF8FileStream ()
{
if (nullptr != m_file)
fclose (m_file);
reporter().popFileName ();
}
//----------------------------------------------------------------------
//----------------------------------------------------------------------
Char UTF8FileStream::readOne ()
{
if (error() || eoi())
return InvalidChar();
assert (nullptr != m_file);
auto sb = readStartByte ();
if (eoi() || error() || sb < 0 || sb > 255)
return InvalidChar();
auto dsb = DecodeStartByte (uint8_t(sb));
uint64_t acc = dsb.second;
for (int i = 0; i < dsb.first; ++i)
acc = (acc << 6) | readContinuationByte();
// Note: acc should not be larger than 0x10FFFF, but even that won't fit in a wchar_t. :-(
if (msc_BOM == acc) // Ignore a Byte Order Mark
return readOne();
else
return Char(acc);
}
//----------------------------------------------------------------------
//----------------------------------------------------------------------
int UTF8FileStream::readByte ()
{
auto c = fgetc (m_file);
if (EOF == c)
{
if (feof(m_file)) setEOI ();
if (ferror(m_file)) setError ();
return -1;
}
return c;
}
//----------------------------------------------------------------------
int UTF8FileStream::readStartByte ()
{
auto c = readByte();
if (eoi() || error())
return c;
if (!ValidStartByte(uint8_t(c)))
reporter().newInputWarning (location(), 2, L"Suspicious UTF-8 byte sequence: invalid start byte.");
while (!ValidStartByte(uint8_t(c)) && !eoi() && !error())
c = readByte();
return c;
}
//----------------------------------------------------------------------
unsigned UTF8FileStream::readContinuationByte ()
{
auto c = readByte();
if ((c & 0xC0) != 0x80)
{
ungetc (c, m_file); // !!!
reporter().newInputWarning (location(), 3, L"Invalid UTF-8 continuation byte detected.");
return 0;
}
return c & 0x3F;
}
//----------------------------------------------------------------------
//----------------------------------------------------------------------
bool UTF8FileStream::ValidStartByte (uint8_t start_byte)
{
return !(((start_byte & 0xC0) == 0x80) || (start_byte > 0xF4));
}
//----------------------------------------------------------------------
// First element is the number of additional bytes to read,
// the second element is the bit values from this byte that contribute to the final character code
std::pair<int, unsigned> UTF8FileStream::DecodeStartByte (uint8_t sb)
{
if (sb < 0x80) return {0, sb};
else if (sb < 0xC0) return {0, 0}; // This should not happen
else if (sb < 0xE0) return {1, sb & 0x1F};
else if (sb < 0xF0) return {2, sb & 0x0F};
else if (sb < 0xF8) return {3, sb & 0x07};
else if (sb < 0xFC) return {4, sb & 0x03}; // This should not happen
else if (sb < 0xFE) return {5, sb & 0x01}; // This should not happen
else return {6, 0}; // This should not happen
}
//----------------------------------------------------------------------
//======================================================================
} // namespace UPL
//======================================================================
|
#include <iostream>
#include <vector>
using namespace std;
// Problem specific constants.
const int POWER = 500500;
const long long MODULO = 500500507;
// Return a vector of the first n primes.
vector<int> getNPrimes(int n)
{
vector<bool> prime(15 * POWER, true);
prime[0] = prime[1] = false;
vector<int> ret;
for (int p = 2;p < 15 * POWER && ret.size() < n; p++)
if (prime[p]) {
ret.push_back(p);
for (int q = 2 * p;q < 15 * POWER; q += p)
prime[q] = false;
}
return ret;
}
// For integers a > 1 and v > 0, return the smallest exponent e
// s.t a ^ e <= v.
int getMaxExponent(int a, int v)
{
int ret = 0, tmp = 1;
while (tmp <= v / a) {
ret++;
tmp = tmp * a;
}
return ret;
}
long long getPower(int a, int x)
{
long long ret = 1;
for (int i = 0;i < x; ++i)
ret = ret * a;
return ret;
}
long long get(int p, int X)
{
long long ret = 1;
for (int i = 1;i <= X; i++) {
ret = ret * getPower(p, 1 << (i - 1)) % MODULO;
}
return ret;
}
int main(int argc, char *argv[])
{
// Start with the default solution of 2^1 . 3^1 ... . 500500^1 and take
// away as many large prime factors as possible.
vector<int> p = getNPrimes(POWER);
vector<int> X(POWER, 1);
for (int i = POWER - 1;i >= 0; i--) {
long long factorGone = p[i] + 1;
int jj = -1;
for (int j = 0;j < i; j++) {
// p[j] ^ (2 ^ X[j] - 1) -> p[j] ^ (2 ^ (X[j] + 1) - 1)
// result goes up by the factor p[j] ^ (2 ^ X[j])
if (X[j] == 1 && p[j] * 1LL * p[j] >= p[i])
break;
int maxE = getMaxExponent(p[j], p[i]);
if (X[j] > getMaxExponent(2, maxE))
continue;
long long factor = getPower(p[j], getPower(2, X[j]));
if (factorGone > factor) {
factorGone = factor;
jj = j;
}
}
if (factorGone > p[i] )
break;
X[jj]++;
X[i]--;
}
long long ret = 1;
for (int i = 0;i < POWER; ++i)
ret = ret * get(p[i], X[i]) % MODULO;
cout << ret << endl;
return 0;
}
|
// Copyright (c) 2021 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef OpenGl_GlTypes_HeaderFile
#define OpenGl_GlTypes_HeaderFile
// required for correct APIENTRY definition
#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#if defined(__APPLE__)
#import <TargetConditionals.h>
#endif
#ifndef APIENTRY
#define APIENTRY
#endif
#ifndef APIENTRYP
#define APIENTRYP APIENTRY *
#endif
#ifndef GLAPI
#define GLAPI extern
#endif
#ifndef GL_APICALL
#define GL_APICALL GLAPI
#endif
// exclude modern definitions and system-provided glext.h, should be defined before gl.h inclusion
#ifndef GL_GLEXT_LEGACY
#define GL_GLEXT_LEGACY
#endif
#ifndef GLX_GLXEXT_LEGACY
#define GLX_GLXEXT_LEGACY
#endif
#include <OpenGl_khrplatform.h>
typedef khronos_int8_t GLbyte;
typedef khronos_float_t GLclampf;
typedef khronos_int32_t GLfixed;
typedef short GLshort;
typedef unsigned short GLushort;
typedef void GLvoid;
typedef struct __GLsync *GLsync;
typedef khronos_int64_t GLint64;
typedef khronos_uint64_t GLuint64;
typedef unsigned int GLenum;
typedef unsigned int GLuint;
typedef char GLchar;
typedef khronos_float_t GLfloat;
typedef khronos_ssize_t GLsizeiptr;
typedef khronos_intptr_t GLintptr;
typedef unsigned int GLbitfield;
typedef int GLint;
typedef unsigned char GLboolean;
typedef int GLsizei;
typedef khronos_uint8_t GLubyte;
typedef double GLdouble;
typedef double GLclampd;
#define GL_NONE 0
#define GL_DEPTH_BUFFER_BIT 0x00000100
#define GL_STENCIL_BUFFER_BIT 0x00000400
#define GL_COLOR_BUFFER_BIT 0x00004000
#define GL_FALSE 0
#define GL_TRUE 1
#define GL_POINTS 0x0000
#define GL_LINES 0x0001
#define GL_LINE_LOOP 0x0002
#define GL_LINE_STRIP 0x0003
#define GL_TRIANGLES 0x0004
#define GL_TRIANGLE_STRIP 0x0005
#define GL_TRIANGLE_FAN 0x0006
#define GL_ZERO 0
#define GL_ONE 1
#define GL_SRC_COLOR 0x0300
#define GL_ONE_MINUS_SRC_COLOR 0x0301
#define GL_SRC_ALPHA 0x0302
#define GL_ONE_MINUS_SRC_ALPHA 0x0303
#define GL_DST_ALPHA 0x0304
#define GL_ONE_MINUS_DST_ALPHA 0x0305
#define GL_DST_COLOR 0x0306
#define GL_ONE_MINUS_DST_COLOR 0x0307
#define GL_SRC_ALPHA_SATURATE 0x0308
#define GL_FUNC_ADD 0x8006
#define GL_BLEND_EQUATION 0x8009
#define GL_BLEND_EQUATION_RGB 0x8009
#define GL_BLEND_EQUATION_ALPHA 0x883D
#define GL_FUNC_SUBTRACT 0x800A
#define GL_FUNC_REVERSE_SUBTRACT 0x800B
#define GL_BLEND_DST_RGB 0x80C8
#define GL_BLEND_SRC_RGB 0x80C9
#define GL_BLEND_DST_ALPHA 0x80CA
#define GL_BLEND_SRC_ALPHA 0x80CB
#define GL_CONSTANT_COLOR 0x8001
#define GL_ONE_MINUS_CONSTANT_COLOR 0x8002
#define GL_CONSTANT_ALPHA 0x8003
#define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004
#define GL_BLEND_COLOR 0x8005
#define GL_ARRAY_BUFFER 0x8892
#define GL_ELEMENT_ARRAY_BUFFER 0x8893
#define GL_ARRAY_BUFFER_BINDING 0x8894
#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895
#define GL_STREAM_DRAW 0x88E0
#define GL_STATIC_DRAW 0x88E4
#define GL_DYNAMIC_DRAW 0x88E8
#define GL_BUFFER_SIZE 0x8764
#define GL_BUFFER_USAGE 0x8765
#define GL_CURRENT_VERTEX_ATTRIB 0x8626
#define GL_FRONT_LEFT 0x0400
#define GL_FRONT_RIGHT 0x0401
#define GL_BACK_LEFT 0x0402
#define GL_BACK_RIGHT 0x0403
#define GL_FRONT 0x0404
#define GL_BACK 0x0405
#define GL_LEFT 0x0406
#define GL_RIGHT 0x0407
#define GL_FRONT_AND_BACK 0x0408
#define GL_TEXTURE_2D 0x0DE1
#define GL_CULL_FACE 0x0B44
#define GL_BLEND 0x0BE2
#define GL_DITHER 0x0BD0
#define GL_STENCIL_TEST 0x0B90
#define GL_DEPTH_TEST 0x0B71
#define GL_SCISSOR_TEST 0x0C11
#define GL_POLYGON_OFFSET_FACTOR 0x8038
#define GL_POLYGON_OFFSET_UNITS 0x2A00
#define GL_POLYGON_OFFSET_POINT 0x2A01
#define GL_POLYGON_OFFSET_LINE 0x2A02
#define GL_POLYGON_OFFSET_FILL 0x8037
#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E
#define GL_SAMPLE_COVERAGE 0x80A0
#define GL_NO_ERROR 0
#define GL_INVALID_ENUM 0x0500
#define GL_INVALID_VALUE 0x0501
#define GL_INVALID_OPERATION 0x0502
#define GL_OUT_OF_MEMORY 0x0505
#define GL_CW 0x0900
#define GL_CCW 0x0901
#define GL_LINE_WIDTH 0x0B21
#define GL_ALIASED_POINT_SIZE_RANGE 0x846D
#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E
#define GL_CULL_FACE_MODE 0x0B45
#define GL_FRONT_FACE 0x0B46
#define GL_DEPTH_RANGE 0x0B70
#define GL_DEPTH_WRITEMASK 0x0B72
#define GL_DEPTH_CLEAR_VALUE 0x0B73
#define GL_DEPTH_FUNC 0x0B74
#define GL_STENCIL_CLEAR_VALUE 0x0B91
#define GL_STENCIL_FUNC 0x0B92
#define GL_STENCIL_FAIL 0x0B94
#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95
#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96
#define GL_STENCIL_REF 0x0B97
#define GL_STENCIL_VALUE_MASK 0x0B93
#define GL_STENCIL_WRITEMASK 0x0B98
#define GL_STENCIL_BACK_FUNC 0x8800
#define GL_STENCIL_BACK_FAIL 0x8801
#define GL_STENCIL_BACK_PASS_DEPTH_FAIL 0x8802
#define GL_STENCIL_BACK_PASS_DEPTH_PASS 0x8803
#define GL_STENCIL_BACK_REF 0x8CA3
#define GL_STENCIL_BACK_VALUE_MASK 0x8CA4
#define GL_STENCIL_BACK_WRITEMASK 0x8CA5
#define GL_VIEWPORT 0x0BA2
#define GL_SCISSOR_BOX 0x0C10
#define GL_COLOR_CLEAR_VALUE 0x0C22
#define GL_COLOR_WRITEMASK 0x0C23
#define GL_UNPACK_LSB_FIRST 0x0CF1 // only desktop
#define GL_UNPACK_ROW_LENGTH 0x0CF2
#define GL_UNPACK_SKIP_ROWS 0x0CF3
#define GL_UNPACK_SKIP_PIXELS 0x0CF4
#define GL_UNPACK_ALIGNMENT 0x0CF5
#define GL_PACK_LSB_FIRST 0x0D01 // only desktop
#define GL_PACK_ROW_LENGTH 0x0D02
#define GL_PACK_SKIP_ROWS 0x0D03
#define GL_PACK_SKIP_PIXELS 0x0D04
#define GL_PACK_ALIGNMENT 0x0D05
#define GL_MAX_TEXTURE_SIZE 0x0D33
#define GL_MAX_VIEWPORT_DIMS 0x0D3A
#define GL_SUBPIXEL_BITS 0x0D50
#define GL_RED_BITS 0x0D52
#define GL_GREEN_BITS 0x0D53
#define GL_BLUE_BITS 0x0D54
#define GL_ALPHA_BITS 0x0D55
#define GL_DEPTH_BITS 0x0D56
#define GL_STENCIL_BITS 0x0D57
#define GL_POLYGON_OFFSET_UNITS 0x2A00
#define GL_POLYGON_OFFSET_FACTOR 0x8038
#define GL_TEXTURE_BINDING_2D 0x8069
#define GL_SAMPLE_BUFFERS 0x80A8
#define GL_SAMPLES 0x80A9
#define GL_SAMPLE_COVERAGE_VALUE 0x80AA
#define GL_SAMPLE_COVERAGE_INVERT 0x80AB
#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2
#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3
#define GL_DONT_CARE 0x1100
#define GL_FASTEST 0x1101
#define GL_NICEST 0x1102
#define GL_GENERATE_MIPMAP_HINT 0x8192
#define GL_BYTE 0x1400
#define GL_UNSIGNED_BYTE 0x1401
#define GL_SHORT 0x1402
#define GL_UNSIGNED_SHORT 0x1403
#define GL_INT 0x1404
#define GL_UNSIGNED_INT 0x1405
#define GL_FLOAT 0x1406
#define GL_FIXED 0x140C
#define GL_DEPTH_COMPONENT 0x1902
#define GL_ALPHA 0x1906
#define GL_RGB 0x1907
#define GL_RGBA 0x1908
#define GL_LUMINANCE 0x1909
#define GL_LUMINANCE_ALPHA 0x190A
#define GL_NEVER 0x0200
#define GL_LESS 0x0201
#define GL_EQUAL 0x0202
#define GL_LEQUAL 0x0203
#define GL_GREATER 0x0204
#define GL_NOTEQUAL 0x0205
#define GL_GEQUAL 0x0206
#define GL_ALWAYS 0x0207
#define GL_KEEP 0x1E00
#define GL_REPLACE 0x1E01
#define GL_INCR 0x1E02
#define GL_DECR 0x1E03
#define GL_INVERT 0x150A
#define GL_INCR_WRAP 0x8507
#define GL_DECR_WRAP 0x8508
#define GL_VENDOR 0x1F00
#define GL_RENDERER 0x1F01
#define GL_VERSION 0x1F02
#define GL_EXTENSIONS 0x1F03
#define GL_NEAREST 0x2600
#define GL_LINEAR 0x2601
#define GL_NEAREST_MIPMAP_NEAREST 0x2700
#define GL_LINEAR_MIPMAP_NEAREST 0x2701
#define GL_NEAREST_MIPMAP_LINEAR 0x2702
#define GL_LINEAR_MIPMAP_LINEAR 0x2703
#define GL_TEXTURE_MAG_FILTER 0x2800
#define GL_TEXTURE_MIN_FILTER 0x2801
#define GL_TEXTURE_WRAP_S 0x2802
#define GL_TEXTURE_WRAP_T 0x2803
#define GL_TEXTURE 0x1702
#define GL_TEXTURE_CUBE_MAP 0x8513
#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514
#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515
#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516
#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517
#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518
#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519
#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A
#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C
#define GL_TEXTURE0 0x84C0
#define GL_TEXTURE1 0x84C1
#define GL_TEXTURE2 0x84C2
#define GL_TEXTURE3 0x84C3
#define GL_TEXTURE4 0x84C4
#define GL_TEXTURE5 0x84C5
#define GL_TEXTURE6 0x84C6
#define GL_TEXTURE7 0x84C7
#define GL_TEXTURE8 0x84C8
#define GL_TEXTURE9 0x84C9
#define GL_TEXTURE10 0x84CA
#define GL_TEXTURE11 0x84CB
#define GL_TEXTURE12 0x84CC
#define GL_TEXTURE13 0x84CD
#define GL_TEXTURE14 0x84CE
#define GL_TEXTURE15 0x84CF
#define GL_TEXTURE16 0x84D0
#define GL_TEXTURE17 0x84D1
#define GL_TEXTURE18 0x84D2
#define GL_TEXTURE19 0x84D3
#define GL_TEXTURE20 0x84D4
#define GL_TEXTURE21 0x84D5
#define GL_TEXTURE22 0x84D6
#define GL_TEXTURE23 0x84D7
#define GL_TEXTURE24 0x84D8
#define GL_TEXTURE25 0x84D9
#define GL_TEXTURE26 0x84DA
#define GL_TEXTURE27 0x84DB
#define GL_TEXTURE28 0x84DC
#define GL_TEXTURE29 0x84DD
#define GL_TEXTURE30 0x84DE
#define GL_TEXTURE31 0x84DF
#define GL_ACTIVE_TEXTURE 0x84E0
#define GL_CLAMP 0x2900
#define GL_REPEAT 0x2901
#define GL_CLAMP_TO_EDGE 0x812F
#define GL_MIRRORED_REPEAT 0x8370
#define GL_FLOAT_VEC2 0x8B50
#define GL_FLOAT_VEC3 0x8B51
#define GL_FLOAT_VEC4 0x8B52
#define GL_INT_VEC2 0x8B53
#define GL_INT_VEC3 0x8B54
#define GL_INT_VEC4 0x8B55
#define GL_BOOL 0x8B56
#define GL_BOOL_VEC2 0x8B57
#define GL_BOOL_VEC3 0x8B58
#define GL_BOOL_VEC4 0x8B59
#define GL_FLOAT_MAT2 0x8B5A
#define GL_FLOAT_MAT3 0x8B5B
#define GL_FLOAT_MAT4 0x8B5C
#define GL_SAMPLER_2D 0x8B5E
#define GL_SAMPLER_CUBE 0x8B60
#define GL_COLOR 0x1800
#define GL_DEPTH 0x1801
#define GL_STENCIL 0x1802
#define GL_RED 0x1903
#define GL_RGB8 0x8051
#define GL_RGBA8 0x8058
// only in desktop OpenGL
#define GL_LUMINANCE16 0x8042
// in core since OpenGL ES 3.0, extension GL_OES_rgb8_rgba8
#define GL_LUMINANCE8 0x8040
// GL_EXT_texture_format_BGRA8888
#define GL_BGRA_EXT 0x80E1 // same as GL_BGRA on desktop
#define GL_R16 0x822A
#define GL_RGB4 0x804F
#define GL_RGB5 0x8050
#define GL_RGB10 0x8052
#define GL_RGB12 0x8053
#define GL_RGB16 0x8054
#define GL_RGB10_A2 0x8059
#define GL_RGBA12 0x805A
#define GL_RGBA16 0x805B
#define GL_ALPHA8 0x803C
#define GL_ALPHA16 0x803E
#define GL_RG16 0x822C
#define GL_R16_SNORM 0x8F98
#define GL_RG16_SNORM 0x8F99
#define GL_RGB16_SNORM 0x8F9A
#define GL_RGBA16_SNORM 0x8F9B
#define GL_RED_SNORM 0x8F90
#define GL_RG_SNORM 0x8F91
#define GL_RGB_SNORM 0x8F92
#define GL_RGBA_SNORM 0x8F93
#define GL_DRAW_BUFFER 0x0C01
#define GL_READ_BUFFER 0x0C02
#define GL_DOUBLEBUFFER 0x0C32
#define GL_STEREO 0x0C33
#define GL_PROXY_TEXTURE_2D 0x8064
#define GL_TEXTURE_WIDTH 0x1000
#define GL_TEXTURE_HEIGHT 0x1001
#define GL_TEXTURE_INTERNAL_FORMAT 0x1003
// OpenGL ES 3.0+ or OES_texture_half_float
#define GL_HALF_FLOAT_OES 0x8D61
#endif // OpenGl_GlTypes_HeaderFile
|
#include "AA_SIPP_O.h"
AA_SIPP_O::AA_SIPP_O(double weight, bool breakingties)
{
this->weight = weight;
this->breakingties = breakingties;
closeSize = 0;
openSize = 0;
}
AA_SIPP_O::~AA_SIPP_O()
{
}
double AA_SIPP_O::calculateDistanceFromCellToCell(double start_i, double start_j, double fin_i, double fin_j)
{
return sqrt(double((start_i - fin_i)*(start_i - fin_i) + (start_j - fin_j)*(start_j - fin_j)));
}
void AA_SIPP_O::initStates(int numOfCurAgent, const cMap &Map)
{
std::vector<std::pair<double, double>> begins(0);
double g, h(calculateDistanceFromCellToCell(Map.start_i[numOfCurAgent], Map.start_j[numOfCurAgent], Map.goal_i[numOfCurAgent], Map.goal_j[numOfCurAgent]));
Node n(Map.start_i[numOfCurAgent], Map.start_j[numOfCurAgent],h,0,h,true,0,constraints.getSafeInterval(Map.start_i[numOfCurAgent],Map.start_j[numOfCurAgent],0).second,1);
n.best_g = 0;
states.insert(n);
auto parent = states.getParentPtr();
for(int i = 0; i < Map.height; i++)
for(int j = 0; j < Map.width; j++)
{
if(Map.CellIsObstacle(i,j))
constraints.removeSafeIntervals(i,j);
begins = constraints.getSafeBegins(i, j);
g = calculateDistanceFromCellToCell(i, j, Map.start_i[numOfCurAgent], Map.start_j[numOfCurAgent]);
h = calculateDistanceFromCellToCell(i, j, Map.goal_i[numOfCurAgent], Map.goal_j[numOfCurAgent]);
n = Node(i,j,g+h,g,h);
n.Parent = parent;
for(int k = 0; k < begins.size(); k++)
{
n.interval_begin = begins[k].first;
n.interval_end = begins[k].second;
if(i == Map.start_i[numOfCurAgent] && j == Map.start_j[numOfCurAgent])
{
if(k==0)
continue;
n.g = CN_INFINITY;
n.F = CN_INFINITY;
n.Parent = nullptr;
n.consistent = 2;
n.parents.clear();
states.insert(n);
continue;
}
if(n.interval_begin > n.g)
{
n.g = n.interval_begin;
n.F = n.g + n.h;
}
n.parents={parent, n.g};
if(n.g <= n.interval_end)
states.insert(n);
}
}
h = (calculateDistanceFromCellToCell(Map.start_i[numOfCurAgent], Map.start_j[numOfCurAgent], Map.goal_i[numOfCurAgent], Map.goal_j[numOfCurAgent]));
begins = constraints.getSafeBegins(i, j);
n = Node(Map.start_i[numOfCurAgent], Map.start_j[numOfCurAgent],h,0,h,true,0,begins[0].second,1);
states.expand(n);
}
ResultPathInfo AA_SIPP_O::findPath(cLogger *Log, const SearchResult &sresult, const cMap &Map)
{
#ifdef __linux__
timeval begin, end;
gettimeofday(&begin, NULL);
#else
LARGE_INTEGER begin, end, freq;
QueryPerformanceCounter(&begin);
QueryPerformanceFrequency(&freq);
#endif
constraints.init(Map.width, Map.height);
constraints.collision_obstacles.resize(Map.agents,0);
for(int i=0; i<sresult.pathInfo.size(); i++)
if(sresult.pathInfo[i].pathfound)
constraints.addConstraints(sresult.pathInfo[i].sections, i);
ResultPathInfo resultPath;
states.clear();
states.map = ⤅
initStates(Map.agents - 1, Map);
Node curNode(states.getMin());
Node newNode;
bool pathFound(false);
int numOfCurAgent = Map.agents -1;
int expanded(0);
int checked(0);
LineOfSight los;
while(curNode.g < CN_INFINITY)//if curNode.g=CN_INFINITY => there are only unreachable non-consistent states => path cannot be found
{
newNode = curNode;
checked++;
if(newNode.Parent->i == Map.start_i[Map.agents - 1] && newNode.Parent->j == Map.start_j[Map.agents - 1])
if(!los.checkLine(newNode.i,newNode.j,newNode.Parent->i,newNode.Parent->j,Map))
{
newNode.g = CN_INFINITY;
states.update(newNode,false);
curNode = states.getMin();
continue;
}
if(newNode.g < newNode.best_g)
{
newNode.g = constraints.findEAT(newNode);
if(newNode.g < newNode.best_g)
{
newNode.best_g = newNode.g;
newNode.best_Parent = newNode.Parent;
states.update(newNode, true);
}
else
states.update(newNode, false);
}
curNode = states.getMin();
if((newNode.best_g + newNode.h - curNode.F) < CN_EPSILON)
{
expanded++;
states.expand(newNode);
states.updateNonCons(newNode);
if(newNode.i == Map.goal_i[numOfCurAgent] && newNode.j == Map.goal_j[numOfCurAgent] && newNode.interval_end == CN_INFINITY)
{
newNode.g = newNode.best_g;
newNode.Parent = newNode.best_Parent;
pathFound = true;
break;
}
curNode = states.getMin();
}
}
if(pathFound)
{
makePrimaryPath(newNode);
for(int i = 1; i < hppath.size(); i++)
if((hppath[i].g - (hppath[i - 1].g + calculateDistanceFromCellToCell(hppath[i].i, hppath[i].j, hppath[i - 1].i, hppath[i - 1].j))) > CN_EPSILON)
{
Node add = hppath[i - 1];
add.g = hppath[i].g - calculateDistanceFromCellToCell(hppath[i].i, hppath[i].j, hppath[i - 1].i,hppath[i - 1].j);
hppath.emplace(hppath.begin() + i, add);
i++;
}
#ifdef __linux__
gettimeofday(&end, NULL);
resultPath.time = (end.tv_sec - begin.tv_sec) + static_cast<double>(end.tv_usec - begin.tv_usec) / 1000000;
#else
QueryPerformanceCounter(&end);
resultPath.time = static_cast<double long>(end.QuadPart-begin.QuadPart) / freq.QuadPart;
#endif
resultPath.sections = hppath;
makeSecondaryPath(newNode);
resultPath.nodescreated = openSize + closeSize;
resultPath.pathfound = true;
resultPath.path = lppath;
resultPath.numberofsteps = closeSize;
resultPath.pathlength = newNode.g;
}
else
{
#ifdef __linux__
gettimeofday(&end, NULL);
resultPath.time = (end.tv_sec - begin.tv_sec) + static_cast<double>(end.tv_usec - begin.tv_usec) / 1000000;
#else
QueryPerformanceCounter(&end);
resultPath.time = static_cast<double long>(end.QuadPart-begin.QuadPart) / freq.QuadPart;
#endif
std::cout<<numOfCurAgent<<" PATH NOT FOUND!\n";
resultPath.nodescreated = closeSize;
resultPath.pathfound = false;
resultPath.path.clear();
resultPath.sections.clear();
resultPath.pathlength = 0;
resultPath.numberofsteps = closeSize;
}
std::pair<std::vector<Node>,std::vector<Node>> openclosed=states.getExpanded();
//Log->writeToLogOpenClose(openclosed.first,openclosed.second);
int obs(0);
for(int k=0; k<Map.agents; k++)
obs+=bool(constraints.collision_obstacles[k]);
std::cout<<obs<<" "<<expanded<<" "<<checked<<" ";
std::ofstream out("optimal_vs_point_warehouse.txt",std::ios::app);
out<<obs<<" "<<expanded<<" "<<checked<<" ";
states.printStats();
return resultPath;
}
/*std::vector<conflict> AA_SIPP_O::CheckConflicts()
{
std::vector<conflict> conflicts(0);
conflict conf;
Node cur, check;
std::vector<std::vector<conflict>> positions;
positions.resize(sresult.agents);
for(int i = 0; i < sresult.agents; i++)
{
if(!sresult.pathInfo[i].pathfound)
continue;
positions[i].resize(0);
int k = 0;
double part = 1;
for(int j = 1; j<sresult.pathInfo[i].sections.size(); j++)
{
cur = sresult.pathInfo[i].sections[j];
check = sresult.pathInfo[i].sections[j-1];
int di = cur.i - check.i;
int dj = cur.j - check.j;
double dist = (cur.g - check.g)*10;
int steps = (cur.g - check.g)*10;
if(dist - steps + part >= 1)
{
steps++;
part = dist - steps;
}
else
part += dist - steps;
double stepi = double(di)/dist;
double stepj = double(dj)/dist;
double curg = double(k)*0.1;
double curi = check.i + (curg - check.g)*di/(cur.g - check.g);
double curj = check.j + (curg - check.g)*dj/(cur.g - check.g);
conf.i = curi;
conf.j = curj;
conf.g = curg;
if(curg <= cur.g)
{
positions[i].push_back(conf);
k++;
}
while(curg <= cur.g)
{
if(curg + 0.1 > cur.g)
break;
curi += stepi;
curj += stepj;
curg += 0.1;
conf.i = curi;
conf.j = curj;
conf.g = curg;
positions[i].push_back(conf);
k++;
}
}
if(double(k - 1)*0.1 < sresult.pathInfo[i].sections.back().g)
{
conf.i = sresult.pathInfo[i].sections.back().i;
conf.j = sresult.pathInfo[i].sections.back().j;
conf.g = sresult.pathInfo[i].sections.back().g;
positions[i].push_back(conf);
}
}
int max = 0;
for(int i = 0; i < positions.size(); i++)
if(positions[i].size() > max)
max = positions[i].size();
for(int i = 0; i < sresult.agents; i++)
{
for(int k = 0; k < max; k++)
{
for(int j = i + 1; j < sresult.agents; j++)
{
if(!sresult.pathInfo[j].pathfound || !sresult.pathInfo[i].pathfound)
continue;
conflict a, b;
if(positions[i].size() > k)
a = positions[i][k];
else
a = positions[i].back();
if(positions[j].size() > k)
b = positions[j][k];
else
b = positions[j].back();
if(sqrt((a.i - b.i)*(a.i - b.i) + (a.j - b.j)*(a.j - b.j)) + CN_EPSILON < 1.0)
{
// std::cout<<a.i<<" "<<a.j<<" "<<b.i<<" "<<b.j<<" "<<sqrt((a.i - b.i)*(a.i - b.i) + (a.j - b.j)*(a.j - b.j))<<"\n";
conf.i = b.i;
conf.j = b.j;
conf.agent1 = i;
conf.agent2 = j;
conf.g = b.g;
conflicts.push_back(conf);
}
}
}
}
return conflicts;
}*/
void AA_SIPP_O::makePrimaryPath(Node curNode)
{
hppath.clear();
hppath.shrink_to_fit();
std::list<Node> path;
Node n(curNode.i, curNode.j, curNode.F, curNode.g);
path.push_front(n);
if(curNode.Parent != nullptr)
{
curNode = *curNode.Parent;
if(curNode.Parent != nullptr)
{
do
{
Node n(curNode.i, curNode.j, curNode.F, curNode.g);
path.push_front(n);
curNode = *curNode.Parent;
}
while(curNode.Parent != nullptr);
}
Node n(curNode.i, curNode.j, curNode.F, curNode.g);
path.push_front(n);
}
for(auto it = path.begin(); it != path.end(); it++)
hppath.push_back(*it);
return;
}
void AA_SIPP_O::makeSecondaryPath(Node curNode)
{
lppath.clear();
if(curNode.Parent != nullptr)
{
std::vector<Node> lineSegment;
do
{
calculateLineSegment(lineSegment, *curNode.Parent, curNode);
lppath.insert(lppath.begin(), ++lineSegment.begin(), lineSegment.end());
curNode = *curNode.Parent;
}
while(curNode.Parent != nullptr);
lppath.push_front(*lineSegment.begin());
}
else
lppath.push_front(curNode);
}
void AA_SIPP_O::calculateLineSegment(std::vector<Node> &line, const Node &start, const Node &goal)
{
int i1 = start.i;
int i2 = goal.i;
int j1 = start.j;
int j2 = goal.j;
int delta_i = std::abs(i1 - i2);
int delta_j = std::abs(j1 - j2);
int step_i = (i1 < i2 ? 1 : -1);
int step_j = (j1 < j2 ? 1 : -1);
int error = 0;
int i = i1;
int j = j1;
if (delta_i > delta_j)
{
for (; i != i2; i += step_i)
{
line.push_back(Node(i,j));
error += delta_j;
if ((error << 1) > delta_i)
{
j += step_j;
error -= delta_i;
}
}
}
else
{
for (; j != j2; j += step_j)
{
line.push_back(Node(i,j));
error += delta_i;
if ((error << 1) > delta_j)
{
i += step_i;
error -= delta_j;
}
}
}
return;
}
|
#include "flex_typeclass_plugin/Tooling.hpp" // IWYU pragma: associated
#include "flex_typeclass_plugin/flex_typeclass_plugin_settings.hpp"
#include <flexlib/per_plugin_settings.hpp>
#include <flexlib/reflect/ReflTypes.hpp>
#include <flexlib/reflect/ReflectAST.hpp>
#include <flexlib/reflect/ReflectionCache.hpp>
#include <flexlib/ToolPlugin.hpp>
#include <flexlib/core/errors/errors.hpp>
#include <flexlib/utils.hpp>
#include <flexlib/funcParser.hpp>
#include <flexlib/inputThread.hpp>
#include <flexlib/clangUtils.hpp>
#include <flexlib/clangPipeline.hpp>
#include <flexlib/annotation_parser.hpp>
#include <flexlib/annotation_match_handler.hpp>
#include <flexlib/matchers/annotation_matcher.hpp>
#include <flexlib/options/ctp/options.hpp>
#if defined(CLING_IS_ON)
#include "flexlib/ClingInterpreterModule.hpp"
#endif // CLING_IS_ON
#include <clang/Rewrite/Core/Rewriter.h>
#include <clang/ASTMatchers/ASTMatchFinder.h>
#include <clang/AST/RecursiveASTVisitor.h>
#include <clang/AST/ASTContext.h>
#include <clang/Lex/Preprocessor.h>
#include <clang/AST/DeclTemplate.h>
#include <clang/AST/RecordLayout.h>
#include <llvm/Support/raw_ostream.h>
#include <base/cpu.h>
#include <base/bind.h>
#include <base/command_line.h>
#include <base/debug/alias.h>
#include <base/debug/stack_trace.h>
#include <base/memory/ptr_util.h>
#include <base/sequenced_task_runner.h>
#include <base/strings/string_util.h>
#include <base/trace_event/trace_event.h>
#include <base/logging.h>
#include <base/files/file_util.h>
#include <base/path_service.h>
#include <any>
#include <string>
#include <vector>
#include <regex>
#include <iostream>
#include <fstream>
#include <sstream>
namespace plugin {
static constexpr const char kSingleComma = ',';
static const char kIsMoveOnlyFieldName[] = "kIsMoveOnly";
TypeclassTooling::TypeclassTooling(
const ::plugin::ToolPlugin::Events::RegisterAnnotationMethods& event
#if defined(CLING_IS_ON)
, ::cling_utils::ClingInterpreter* clingInterpreter
#endif // CLING_IS_ON
) : clingInterpreter_(clingInterpreter)
{
DCHECK(clingInterpreter_)
<< "clingInterpreter_";
// load settings from C++ script interpreted by Cling
/// \note skip on fail of settings loading,
/// fallback to defaults
{
cling::Value clingResult;
/**
* EXAMPLE Cling script:
namespace flex_typeclass_plugin {
// Declaration must match plugin version.
struct Settings {
// output directory for generated files
std::string outDir;
};
void loadSettings(Settings& settings)
{
settings.outDir
= "${flextool_outdir}";
}
} // namespace flex_typeclass_plugin
*/
cling::Interpreter::CompilationResult compilationResult
= clingInterpreter_->callFunctionByName(
// function name
"flex_typeclass_plugin::loadSettings"
// argument as void
, static_cast<void*>(&settings_)
// code to cast argument from void
, "*(flex_typeclass_plugin::Settings*)"
, clingResult);
if(compilationResult
!= cling::Interpreter::Interpreter::kSuccess) {
DCHECK(settings_.outDir.empty());
DVLOG(9)
<< "failed to execute Cling script, "
"skipping...";
} else {
DVLOG(9)
<< "settings_.outDir: "
<< settings_.outDir;
}
DCHECK(clingResult.hasValue()
// we expect |void| as result of function call
? clingResult.isValid() && clingResult.isVoid()
// skip on fail of settings loading
: true);
}
DETACH_FROM_SEQUENCE(sequence_checker_);
DCHECK(event.sourceTransformPipeline)
<< "event.sourceTransformPipeline";
::clang_utils::SourceTransformPipeline& sourceTransformPipeline
= *event.sourceTransformPipeline;
sourceTransformRules_
= &sourceTransformPipeline.sourceTransformRules;
if (!base::PathService::Get(base::DIR_EXE, &dir_exe_)) {
NOTREACHED();
}
DCHECK(!dir_exe_.empty());
outDir_ = dir_exe_.Append("generated");
if(!settings_.outDir.empty()) {
outDir_ = base::FilePath{settings_.outDir};
}
if(!base::PathExists(outDir_)) {
base::File::Error dirError = base::File::FILE_OK;
// Returns 'true' on successful creation,
// or if the directory already exists
const bool dirCreated
= base::CreateDirectoryAndGetError(outDir_, &dirError);
if (!dirCreated) {
LOG(ERROR)
<< "failed to create directory: "
<< outDir_
<< " with error code "
<< dirError
<< " with error string "
<< base::File::ErrorToString(dirError);
}
}
{
// Returns an empty path on error.
// On POSIX, this function fails if the path does not exist.
outDir_ = base::MakeAbsoluteFilePath(outDir_);
DCHECK(!outDir_.empty());
VLOG(9)
<< "outDir_= "
<< outDir_;
}
}
TypeclassTooling::~TypeclassTooling()
{
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
clang_utils::SourceTransformResult
TypeclassTooling::typeclass(
const clang_utils::SourceTransformOptions& sourceTransformOptions)
{
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
VLOG(9)
<< "typeclass called...";
// used by code generator of inline (in-place) typeclass
InlineTypeclassSettings inlineTypeclassSettings;
TypeclassSettings typeclassSettings;
flexlib::args typeclassBaseNames =
sourceTransformOptions.func_with_args.parsed_func_.args_;
clang::SourceManager &SM
= sourceTransformOptions.rewriter.getSourceMgr();
const clang::CXXRecordDecl* nodeRecordDecl =
sourceTransformOptions.matchResult.Nodes.getNodeAs<
clang::CXXRecordDecl>("bind_gen");
clang::PrintingPolicy printingPolicy(
sourceTransformOptions.rewriter.getLangOpts());
const clang::LangOptions& langOptions
= sourceTransformOptions.rewriter.getLangOpts();
if (!nodeRecordDecl) {
LOG(ERROR)
<< "CXXRecordDecl not found ";
CHECK(false);
return clang_utils::SourceTransformResult{nullptr};
}
/// \todo support custom namespaces
reflection::NamespacesTree m_namespaces;
std::string fullBaseType;
/*
* example input:
struct
_typeclass(
"generator = InPlace"
", BufferSize = 64")
MagicLongType
: public MagicTemplatedTraits<std::string, int>
, public ParentTemplatedTraits_1<const char *>
, public ParentTemplatedTraits_2<const int &>
{};
*
* exatracted node->bases()
* via clang::Lexer::getSourceText(clang::CharSourceRange) are:
*
* public MagicTemplatedTraits<std::string, int>
* , public ParentTemplatedTraits_1<const char *>
* , public ParentTemplatedTraits_2<const int &>
*/
std::string baseClassesCode;
if (nodeRecordDecl) {
reflection::AstReflector reflector(
sourceTransformOptions.matchResult.Context);
std::vector<clang::CXXRecordDecl *> nodes;
std::vector<reflection::ClassInfoPtr> structInfos;
/// \todo replace with std::vector<MethodInfoPtr>
reflection::ClassInfoPtr structInfo;
for(const auto& field
: nodeRecordDecl->fields())
{
const std::string& name = field->getNameAsString();
DVLOG(9)
<< "reflected class "
<< nodeRecordDecl->getNameAsString()
<< " has field "
<< name;
if(name == kIsMoveOnlyFieldName) {
DVLOG(9)
<< "reflected class "
<< nodeRecordDecl->getNameAsString()
<< " marked for move-only types";
}
typeclassSettings.moveOnly = true;
}
DCHECK(nodeRecordDecl->bases().begin()
!= nodeRecordDecl->bases().end())
<< "(typeclass) no bases for: "
<< nodeRecordDecl->getNameAsString();
/// \todo make recursive (support bases of bases)
for(const clang::CXXBaseSpecifier& it
: nodeRecordDecl->bases())
{
{
clang::SourceRange varSourceRange
= it.getSourceRange();
clang::CharSourceRange charSourceRange(
varSourceRange,
true // IsTokenRange
);
clang::SourceLocation initStartLoc
= charSourceRange.getBegin();
if(varSourceRange.isValid()) {
StringRef sourceText
= clang::Lexer::getSourceText(
charSourceRange
, SM, langOptions, 0);
DCHECK(initStartLoc.isValid());
baseClassesCode += sourceText.str();
baseClassesCode += kSingleComma;
} else {
DCHECK(false);
}
}
CHECK(it.getType()->getAsCXXRecordDecl())
<< "failed getAsCXXRecordDecl for "
<< it.getTypeSourceInfo()->getType().getAsString();
if(it.getType()->getAsCXXRecordDecl()) {
nodes.push_back(
it.getType()->getAsCXXRecordDecl());
const reflection::ClassInfoPtr refled
= reflector.ReflectClass(
it.getType()->getAsCXXRecordDecl()
, &m_namespaces
, false // recursive
);
DCHECK(refled);
CHECK(!refled->methods.empty())
<< "no methods in "
<< refled->name;
structInfos.push_back(refled);
if(!structInfo) {
structInfo = refled;
} else {
for(const auto& it : refled->members) {
structInfo->members.push_back(it);
}
for(const auto& it : refled->methods) {
structInfo->methods.push_back(it);
}
for(const auto& it : refled->innerDecls) {
structInfo->innerDecls.push_back(it);
}
}
std::string preparedFullBaseType
= it.getType().getAsString();
preparedFullBaseType
= clang_utils::extractTypeName(
preparedFullBaseType
);
structInfo->compoundId.push_back(
preparedFullBaseType);
fullBaseType += preparedFullBaseType;
fullBaseType += kSingleComma;
}
}
// remove last comma
if (!baseClassesCode.empty()) {
DCHECK(baseClassesCode.back() == kSingleComma);
baseClassesCode.pop_back();
}
VLOG(9)
<< "baseClassesCode: "
<< baseClassesCode
<< " of "
<< nodeRecordDecl->getNameAsString();
// remove last comma
if (!fullBaseType.empty()) {
DCHECK(fullBaseType.back() == kSingleComma);
fullBaseType.pop_back();
}
if(nodes.empty() || structInfos.empty()
|| !structInfo) {
CHECK(false);
return clang_utils::SourceTransformResult{""};
}
const std::string& targetTypeName
= nodeRecordDecl->getNameAsString();
std::string targetGenerator;
for(const auto& tit : typeclassBaseNames.as_vec_) {
if(tit.name_ == "generator")
{
targetGenerator = tit.value_;
prepareTplArg(targetGenerator);
DCHECK(targetGenerator == "InPlace"
|| targetGenerator == "InHeap");
}
else if(tit.name_ == "BufferSize")
{
inlineTypeclassSettings.BufferSize
= tit.value_;
prepareTplArg(inlineTypeclassSettings.BufferSize);
DCHECK(!inlineTypeclassSettings.BufferSize.empty());
}
else if(tit.name_ == "BufferAlignment")
{
inlineTypeclassSettings.BufferAlignment
= tit.value_;
prepareTplArg(inlineTypeclassSettings.BufferAlignment);
DCHECK(!inlineTypeclassSettings.BufferAlignment.empty());
}
}
VLOG(9)
<< "targetTypeName: "
<< targetTypeName;
{
const clang::QualType& paramType =
//template_type->getDefaultArgument();
sourceTransformOptions.matchResult.Context
->getTypeDeclType(nodeRecordDecl);
std::string registryTargetName =
clang_utils::extractTypeName(
paramType.getAsString(printingPolicy)
);
VLOG(9) << "ReflectionRegistry... for record " <<
registryTargetName;
VLOG(9)
<< "registering type for trait..."
<< registryTargetName
<< " "
<< fullBaseType;
/// \todo template support
DCHECK(!structInfo->templateParams.size());
VLOG(9) << "templateParams.size"
<< structInfo->templateParams.size();
VLOG(9) << "genericParts.size"
<< structInfo->genericParts.size();
std::string fileTargetName =
targetTypeName.empty()
? fullBaseType
: targetTypeName;
clang_utils::normalizeFileName(fileTargetName);
base::FilePath gen_hpp_name
= outDir_.Append(fileTargetName + ".typeclass.generated.hpp");
base::FilePath gen_cpp_name
= outDir_.Append(fileTargetName + ".typeclass.generated.cpp");
{
std::string headerGuard = "";
std::string generator_path
= TYPECLASS_TEMPLATE_HPP;
DCHECK(!generator_path.empty())
<< TYPECLASS_TEMPLATE_HPP
<< "generator_path.empty()";
const auto fileID = SM.getMainFileID();
const auto fileEntry = SM.getFileEntryForID(
SM.getMainFileID());
std::string full_file_path = fileEntry->getName();
std::vector<std::string> generator_includes{
clang_utils::buildIncludeDirective(
full_file_path),
clang_utils::buildIncludeDirective(
R"raw(type_erasure_common.hpp)raw")
};
reflection::ClassInfoPtr ReflectedStructInfo
= structInfo;
DCHECK(ReflectedStructInfo);
// squarets will generate code from template file
// and append it after annotated variable
/// \note FILE_PATH defined by CMakeLists
/// and passed to flextool via
/// --extra-arg=-DFILE_PATH=...
_squaretsFile(
TYPECLASS_TEMPLATE_HPP
)
std::string squarets_output = "";
{
DCHECK(squarets_output.size());
const int writeResult = base::WriteFile(
gen_hpp_name
, squarets_output.c_str()
, squarets_output.size());
// Returns the number of bytes written, or -1 on error.
if(writeResult == -1) {
LOG(ERROR)
<< "Unable to write file: "
<< gen_hpp_name;
} else {
LOG(INFO)
<< "saved file: "
<< gen_hpp_name;
}
}
}
{
std::string headerGuard = "";
std::string generator_path
= TYPECLASS_TEMPLATE_CPP;
DCHECK(!generator_path.empty())
<< TYPECLASS_TEMPLATE_CPP
<< "generator_path.empty()";
reflection::ClassInfoPtr ReflectedStructInfo
= structInfo;
DCHECK(ReflectedStructInfo);
const auto fileID = SM.getMainFileID();
const auto fileEntry = SM.getFileEntryForID(
SM.getMainFileID());
std::string full_file_path = fileEntry->getName();
std::vector<std::string> generator_includes{
clang_utils::buildIncludeDirective(
/// \todo utf8 support
gen_hpp_name.AsUTF8Unsafe()),
clang_utils::buildIncludeDirective(
R"raw(type_erasure_common.hpp)raw")
};
// squarets will generate code from template file
// and append it after annotated variable
/// \note FILE_PATH defined by CMakeLists
/// and passed to flextool via
/// --extra-arg=-DFILE_PATH=...
_squaretsFile(
TYPECLASS_TEMPLATE_CPP
)
std::string squarets_output = "";
{
DCHECK(squarets_output.size());
const int writeResult = base::WriteFile(
gen_cpp_name
, squarets_output.c_str()
, squarets_output.size());
// Returns the number of bytes written, or -1 on error.
if(writeResult == -1) {
LOG(ERROR)
<< "Unable to write file: "
<< gen_cpp_name;
} else {
LOG(INFO)
<< "saved file: "
<< gen_cpp_name;
}
}
}
}
}
return clang_utils::SourceTransformResult{nullptr};
}
clang_utils::SourceTransformResult
TypeclassTooling::typeclass_instance(
const clang_utils::SourceTransformOptions& sourceTransformOptions)
{
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
VLOG(9)
<< "typeclass_instance called...";
TypeclassImplSettings typeclassImplSettings;
// EXAMPLE:
// _typeclass_impl(
// typeclass_instance(target = "FireSpell", "Printable")
// )
// Here |typeclassBaseNames| will contain:
// (target = "FireSpell", "Printable")
flexlib::args typeclassBaseNames =
sourceTransformOptions.func_with_args.parsed_func_.args_;
clang::SourceManager &SM
= sourceTransformOptions.rewriter.getSourceMgr();
clang::PrintingPolicy printingPolicy(
sourceTransformOptions.rewriter.getLangOpts());
std::string targetName;
std::string typeclassQualType;
std::string typeclassBaseTypeIdentifier;
// hold type of "typeclass_target" argument
clang::QualType typeclassArgQualType;
const clang::CXXRecordDecl *node =
sourceTransformOptions.matchResult.Nodes.getNodeAs<
clang::CXXRecordDecl>("bind_gen");
CHECK(node)
<< "node must be CXXRecordDecl";
const clang::LangOptions& langOptions
= sourceTransformOptions.rewriter.getLangOpts();
CHECK(node->getDescribedClassTemplate())
<< "node "
<< node->getNameAsString()
<< " must be template";
/// \brief Retrieves the class template that is described by this
/// class declaration.
///
/// Every class template is represented as a ClassTemplateDecl and a
/// CXXRecordDecl. The former contains template properties (such as
/// the template parameter lists) while the latter contains the
/// actual description of the template's
/// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
/// CXXRecordDecl that from a ClassTemplateDecl, while
/// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
/// a CXXRecordDecl.
if(node->getDescribedClassTemplate()) {
clang::TemplateDecl* templateDecl =
node->getDescribedClassTemplate();
DCHECK(templateDecl);
clang::TemplateParameterList *tp =
templateDecl->getTemplateParameters();
DCHECK(tp);
//clang::TemplateParameterList *tArgs =
// templateDecl->getTemplateA();
for(clang::NamedDecl *parameter_decl: *tp) {
DCHECK(parameter_decl);
CHECK(!parameter_decl->isParameterPack())
<< node->getNameAsString();
// example: namespace::IntSummable
std::string parameterQualType;
// example: IntSummable (without namespace)
std::string parameterBaseTypeIdentifier;
clang::QualType defaultArgQualType;
/// \brief Declaration of a template type parameter.
///
/// For example, "T" in
/// \code
/// template<typename T> class vector;
/// \endcode
if (clang::TemplateTypeParmDecl* template_type
= clang::dyn_cast<clang::TemplateTypeParmDecl>(parameter_decl))
{
DCHECK(template_type);
CHECK(template_type->wasDeclaredWithTypename())
<< node->getNameAsString();
CHECK(template_type->hasDefaultArgument())
<< node->getNameAsString();
CHECK(parameterQualType.empty())
<< node->getNameAsString();
defaultArgQualType =
template_type->getDefaultArgument();
parameterQualType
= clang_utils::extractTypeName(
defaultArgQualType.getAsString(printingPolicy)
);
CHECK(!parameterQualType.empty())
<< node->getNameAsString();
if(defaultArgQualType.getBaseTypeIdentifier()) {
parameterBaseTypeIdentifier
= clang_utils::extractTypeName(
defaultArgQualType.getBaseTypeIdentifier()->getName().str()
);
}
}
/// NonTypeTemplateParmDecl - Declares a non-type template parameter,
/// e.g., "Size" in
/// @code
/// template<int Size> class array { };
/// @endcode
else if (clang::NonTypeTemplateParmDecl* non_template_type
= clang::dyn_cast<clang::NonTypeTemplateParmDecl>(parameter_decl))
{
DCHECK(non_template_type);
CHECK(parameterQualType.empty())
<< node->getNameAsString();
CHECK(non_template_type->hasDefaultArgument())
<< node->getNameAsString();
llvm::raw_string_ostream out(parameterQualType);
defaultArgQualType =
template_type->getDefaultArgument();
non_template_type->getDefaultArgument()->printPretty(
out
, nullptr // clang::PrinterHelper
, printingPolicy
, 0 // indent
);
CHECK(!parameterQualType.empty())
<< node->getNameAsString();
}
CHECK(!parameterQualType.empty())
<< node->getNameAsString();
DVLOG(9)
<< " template parameter decl: "
<< parameter_decl->getNameAsString()
<< " parameterQualType: "
<< parameterQualType;
/**
* Example input:
template<
IntSummable typeclass_target
, FireSpell impl_target
>
struct
_typeclass_instance()
FireSpell_MagicItem
{};
**/
if(parameter_decl->getNameAsString() == "typeclass_target") {
CHECK(typeclassQualType.empty())
<< node->getNameAsString();
CHECK(!parameterQualType.empty())
<< node->getNameAsString();
typeclassQualType
= clang_utils::extractTypeName(parameterQualType);
CHECK(!parameterBaseTypeIdentifier.empty())
<< node->getNameAsString();
typeclassBaseTypeIdentifier
= clang_utils::extractTypeName(parameterBaseTypeIdentifier);
CHECK(!defaultArgQualType.isNull())
<< node->getNameAsString();
CHECK(defaultArgQualType->getAsCXXRecordDecl())
<< node->getNameAsString();
typeclassArgQualType = defaultArgQualType;
}
else if(parameter_decl->getNameAsString() == "impl_target") {
CHECK(targetName.empty())
<< node->getNameAsString();
CHECK(!parameterQualType.empty())
<< node->getNameAsString();
targetName
= clang_utils::extractTypeName(parameterQualType);
} else {
LOG(ERROR)
<< "Unknown argument "
<< parameter_decl->getNameAsString()
<< " in typeclass instance: "
<< node->getNameAsString();
CHECK(false)
<< node->getNameAsString();
}
}
}
if (targetName.empty()) {
LOG(ERROR)
<< "target for typeclass instance not found ";
CHECK(false)
<< node->getNameAsString();
return clang_utils::SourceTransformResult{nullptr};
}
CHECK(!targetName.empty())
<< node->getNameAsString();
CHECK(!typeclassQualType.empty())
<< node->getNameAsString();
{
VLOG(9)
<< "typeclassQualType = "
<< typeclassQualType;
VLOG(9)
<< "target = "
<< targetName;
VLOG(9)
<< "node->getNameAsString() = "
<< node->getNameAsString();
if(typeclassQualType.empty()) {
CHECK(false);
return clang_utils::SourceTransformResult{""};
}
DVLOG(9) << "typeclassQualType = "
<< typeclassQualType;
const auto fileID = SM.getMainFileID();
const auto fileEntry = SM.getFileEntryForID(
SM.getMainFileID());
std::string original_full_file_path
= fileEntry->getName();
VLOG(9)
<< "original_full_file_path = "
<< original_full_file_path;
{
DCHECK(!typeclassBaseTypeIdentifier.empty());
std::string fileTypeclassBaseName
= typeclassBaseTypeIdentifier;
clang_utils::normalizeFileName(fileTypeclassBaseName);
DCHECK(!fileTypeclassBaseName.empty());
DCHECK(!node->getNameAsString().empty());
base::FilePath gen_hpp_name
= outDir_.Append(
node->getNameAsString()
+ ".typeclass_instance.generated.hpp");
base::FilePath gen_base_typeclass_hpp_name
= outDir_.Append(fileTypeclassBaseName
+ ".typeclass.generated.hpp");
/*
* Used by:
* struct _tc_impl_t<ImplTypeclassName, TypeclassBasesCode>
>*/
std::string& ImplTypeclassName
= targetName;
reflection::AstReflector reflector(
sourceTransformOptions.matchResult.Context);
DCHECK(typeclassArgQualType->getAsCXXRecordDecl());
/// \todo support custom namespaces
reflection::NamespacesTree m_namespaces;
reflection::ClassInfoPtr ReflectedBaseTypeclass
= reflector.ReflectClass(
typeclassArgQualType->getAsCXXRecordDecl()
, &m_namespaces
, true // recursive
);
DVLOG(9)
<< "reflected class "
<< typeclassArgQualType.getAsString();
DCHECK(ReflectedBaseTypeclass);
CHECK(typeclassArgQualType
->getAsCXXRecordDecl()->hasDefinition())
<< "no definition in "
<< typeclassArgQualType
->getAsCXXRecordDecl()->getNameAsString();
DCHECK(typeclassArgQualType
->getAsCXXRecordDecl()->bases().begin()
!= typeclassArgQualType
->getAsCXXRecordDecl()->bases().end())
<< "(typeclass instance) no bases for: "
<< typeclassArgQualType
->getAsCXXRecordDecl()->getNameAsString();
for(const auto& field
: typeclassArgQualType->getAsCXXRecordDecl()->fields())
{
const std::string& name = field->getNameAsString();
DVLOG(9)
<< "reflected class "
<< typeclassArgQualType->getAsCXXRecordDecl()->getNameAsString()
<< " has field "
<< name;
if(name == kIsMoveOnlyFieldName) {
DVLOG(9)
<< "reflected class "
<< typeclassArgQualType->getAsCXXRecordDecl()->getNameAsString()
<< " marked for move-only types";
}
typeclassImplSettings.moveOnly = true;
}
/// \todo make recursive (support bases of bases)
for(const clang::CXXBaseSpecifier& it
: typeclassArgQualType->getAsCXXRecordDecl()->bases())
{
CHECK(it.getType()->getAsCXXRecordDecl())
<< "failed getAsCXXRecordDecl for "
<< it.getTypeSourceInfo()->getType().getAsString();
if(it.getType()->getAsCXXRecordDecl()) {
const reflection::ClassInfoPtr refled
= reflector.ReflectClass(
it.getType()->getAsCXXRecordDecl()
, &m_namespaces
, false // recursive
);
DVLOG(9)
<< "reflected base "
<< typeclassArgQualType.getAsString();
DCHECK(refled);
CHECK(!refled->methods.empty())
<< "no methods in "
<< refled->name;
DCHECK(ReflectedBaseTypeclass);
{
for(const auto& it : refled->members) {
ReflectedBaseTypeclass->members.push_back(it);
}
for(const auto& it : refled->methods) {
ReflectedBaseTypeclass->methods.push_back(it);
}
for(const auto& it : refled->innerDecls) {
ReflectedBaseTypeclass->innerDecls.push_back(it);
}
}
}
}
CHECK(!ReflectedBaseTypeclass->methods.empty())
<< "no methods in "
<< ReflectedBaseTypeclass->name;
bool hasAtLeastOneValidMethod = false;
for(const reflection::MethodInfoPtr& method
: ReflectedBaseTypeclass->methods)
{
DCHECK(method);
const size_t methodParamsSize = method->params.size();
const bool needPrint = isTypeclassMethod(method);
if(needPrint) {
hasAtLeastOneValidMethod = needPrint;
}
// log all methods
VLOG(9)
<< "ReflectedBaseTypeclass: "
<< ReflectedBaseTypeclass->name
<< " method: "
<< method->name;
}
CHECK(hasAtLeastOneValidMethod)
<< "no valid methods in "
<< ReflectedBaseTypeclass->name;
/*
* example input:
struct
_typeclass(
"generator = InPlace"
", BufferSize = 64")
MagicLongType
: public MagicTemplatedTraits<std::string, int>
, public ParentTemplatedTraits_1<const char *>
, public ParentTemplatedTraits_2<const int &>
{};
*
* exatracted node->bases()
* via clang::Lexer::getSourceText(clang::CharSourceRange) are:
*
* MagicTemplatedTraits<std::string, int>
* , ParentTemplatedTraits_1<const char *>
* , ParentTemplatedTraits_2<const int &>
*
* (without access specifiers like public/private)
*/
std::string TypeclassBasesCode;
{
DCHECK(typeclassArgQualType->getAsCXXRecordDecl()->bases().begin()
!= typeclassArgQualType->getAsCXXRecordDecl()->bases().end())
<< "(ReflectedBaseTypeclass) no bases for: "
<< ReflectedBaseTypeclass->decl->getNameAsString();
for(const clang::CXXBaseSpecifier& it
: typeclassArgQualType->getAsCXXRecordDecl()->bases())
{
clang::SourceRange varSourceRange
= it.getSourceRange();
clang::CharSourceRange charSourceRange(
varSourceRange,
true // IsTokenRange
);
clang::SourceLocation initStartLoc
= charSourceRange.getBegin();
if(varSourceRange.isValid()) {
DCHECK(initStartLoc.isValid());
TypeclassBasesCode
+= clang_utils::extractTypeName(
it.getType().getAsString(printingPolicy)
);
TypeclassBasesCode += kSingleComma;
} else {
DCHECK(false);
}
}
// remove last comma
if (!TypeclassBasesCode.empty()) {
DCHECK(TypeclassBasesCode.back() == kSingleComma);
TypeclassBasesCode.pop_back();
}
}
CHECK(!TypeclassBasesCode.empty())
<< "invalid bases for: "
<< ReflectedBaseTypeclass->decl->getNameAsString();
DVLOG(9) <<
"TypeclassBasesCode: "
<< TypeclassBasesCode
<< " for: "
<< ReflectedBaseTypeclass->decl->getNameAsString();
std::string headerGuard = "";
std::string generator_path
= TYPECLASS_INSTANCE_TEMPLATE_CPP;
DCHECK(!generator_path.empty())
<< TYPECLASS_INSTANCE_TEMPLATE_CPP
<< "generator_path.empty()";
std::vector<std::string> generator_includes{
//clang_utils::buildIncludeDirective(
/// \todo utf8 support
// gen_base_typeclass_hpp_name.AsUTF8Unsafe()),
clang_utils::buildIncludeDirective(
original_full_file_path),
clang_utils::buildIncludeDirective(
R"raw(type_erasure_common.hpp)raw")
};
// squarets will generate code from template file
// and append it after annotated variable
/// \note FILE_PATH defined by CMakeLists
/// and passed to flextool via
/// --extra-arg=-DFILE_PATH=...
_squaretsFile(
TYPECLASS_INSTANCE_TEMPLATE_CPP
)
std::string squarets_output = "";
{
DCHECK(squarets_output.size());
const int writeResult = base::WriteFile(
gen_hpp_name
, squarets_output.c_str()
, squarets_output.size());
// Returns the number of bytes written, or -1 on error.
if(writeResult == -1) {
LOG(ERROR)
<< "Unable to write file: "
<< gen_hpp_name;
} else {
LOG(INFO)
<< "saved file: "
<< gen_hpp_name;
}
}
}
}
return clang_utils::SourceTransformResult{nullptr};
}
#if 0
clang_utils::SourceTransformResult
TypeclassTooling::typeclass_combo(
const clang_utils::SourceTransformOptions& sourceTransformOptions)
{
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
VLOG(9)
<< "typeclass_combo called...";
// EXAMPLE:
// _typeclass_impl(
// typeclass_instance(target = "FireSpell", "Printable")
// )
// Here |typeclassBaseNames| will contain:
// (target = "FireSpell", "Printable")
flexlib::args typeclassBaseNames =
sourceTransformOptions.func_with_args.parsed_func_.args_;
clang::SourceManager &SM
= sourceTransformOptions.rewriter.getSourceMgr();
std::string combinedTypeclassNames;
std::vector<std::string> typeclassNames;
std::vector<
std::pair<std::string, reflection::ClassInfoPtr>
> ReflectedTypeclasses;
std::vector<std::string> generator_includes;
std::string targetTypeName;
std::string typeAlias;
for(const auto& tit : typeclassBaseNames.as_vec_) {
if(tit.name_ == "type") {
typeAlias = tit.value_;
CHECK(false)
<< "custom type for typeclass combo not supported: "
<< tit.name_
<< " "
<< tit.value_;
prepareTplArg(typeAlias);
}
if(tit.name_ =="name") {
targetTypeName = tit.value_;
prepareTplArg(targetTypeName);
}
}
const size_t typeclassBaseNamesSize
= typeclassBaseNames.as_vec_.size();
size_t titIndex = 0;
size_t processedTimes = 0;
std::string fullBaseType;
for(const auto& tit : typeclassBaseNames.as_vec_) {
if(tit.name_ == "type") {
continue;
}
if(tit.name_ == "name") {
continue;
}
processedTimes++;
std::string typeclassBaseName = tit.value_;
VLOG(9)
<< "typeclassBaseName = "
<< typeclassBaseName;
if(typeclassBaseName.empty()) {
CHECK(false);
return clang_utils::SourceTransformResult{""};
}
if(reflection::ReflectionRegistry::getInstance()->
reflectionCXXRecordRegistry.find(typeclassBaseName)
== reflection::ReflectionRegistry::getInstance()->
reflectionCXXRecordRegistry.end())
{
LOG(ERROR)
<< "typeclassBaseName = "
<< typeclassBaseName
<< " not found!";
CHECK(false);
return clang_utils::SourceTransformResult{""};
}
std::string validTypeAlias = typeAlias;
if(std::map<std::string, std::string>
::const_iterator it
= traitToItsType_.find(typeclassBaseName)
; it != traitToItsType_.end())
{
if(!typeAlias.empty() && typeAlias != it->second) {
LOG(ERROR)
<< "user provided invalid type "
<< typeAlias
<< " for trait: "
<< it->first
<< " Valid type is: "
<< it->second;
CHECK(false);
}
validTypeAlias = it->second;
fullBaseType += validTypeAlias;
fullBaseType += kSingleComma;
} else {
LOG(ERROR)
<< "user not registered typeclass"
<< " for trait: "
<< typeclassBaseName;
CHECK(false);
}
const reflection::ReflectionCXXRecordRegistry*
ReflectedBaseTypeclassRegistry =
reflection::ReflectionRegistry::getInstance()->
reflectionCXXRecordRegistry[typeclassBaseName].get();
combinedTypeclassNames
+= typeclassBaseName
+ (titIndex < (typeclassBaseNamesSize - 1) ? "_" : "");
DCHECK(!validTypeAlias.empty());
typeclassNames.push_back(
validTypeAlias.empty()
? ReflectedBaseTypeclassRegistry->classInfoPtr_->name
: validTypeAlias
);
generator_includes.push_back(
clang_utils::buildIncludeDirective(
typeclassBaseName + R"raw(.typeclass.generated.hpp)raw"));
DVLOG(9)
<< "ReflectedBaseTypeclass->classInfoPtr_->name = "
<< ReflectedBaseTypeclassRegistry->classInfoPtr_->name;
DVLOG(9)
<< "typeclassBaseName = "
<< typeclassBaseName;
VLOG(9)
<< "ReflectedBaseTypeclass is record = "
<< ReflectedBaseTypeclassRegistry->classInfoPtr_->name;
if(reflection::ReflectionRegistry::getInstance()->
reflectionCXXRecordRegistry.find(typeclassBaseName)
== reflection::ReflectionRegistry::getInstance()->
reflectionCXXRecordRegistry.end())
{
LOG(ERROR)
<< "typeclassBaseName = "
<< typeclassBaseName
<< " not found!";
CHECK(false);
return clang_utils::SourceTransformResult{""};
}
ReflectedTypeclasses.push_back(std::make_pair(
typeclassBaseName
, ReflectedBaseTypeclassRegistry->classInfoPtr_));
titIndex++;
}
if(processedTimes <= 0) {
LOG(ERROR)
<< "nothing to do with "
<< sourceTransformOptions.func_with_args.func_with_args_as_string_;
CHECK(false);
}
// remove last comma
if (!fullBaseType.empty()) {
DCHECK(fullBaseType.back() == kSingleComma);
fullBaseType.pop_back();
}
if(typeclassNames.empty()) {
LOG(ERROR)
<< "typeclassNames = empty!";
CHECK(false);
return clang_utils::SourceTransformResult{""};
}
clang::SourceLocation startLoc
= sourceTransformOptions.decl->getLocStart();
clang::SourceLocation endLoc
= sourceTransformOptions.decl->getLocEnd();
clang_utils::expandLocations(
startLoc, endLoc, sourceTransformOptions.rewriter);
auto codeRange = clang::SourceRange{startLoc, endLoc};
std::string OriginalTypeclassBaseCode =
sourceTransformOptions.rewriter.getRewrittenText(codeRange);
base::FilePath gen_hpp_name
= outDir_.Append(
(targetTypeName.empty()
? combinedTypeclassNames
: targetTypeName)
+ ".typeclass_combo.generated.hpp");
generator_includes.push_back(
clang_utils::buildIncludeDirective(R"raw(type_erasure_common.hpp)raw"));
{
std::string headerGuard = "";
std::string generator_path
= TYPECLASS_COMBO_TEMPLATE_CPP;
DCHECK(!generator_path.empty())
<< "generator_path.empty()"
<< TYPECLASS_COMBO_TEMPLATE_CPP;
const auto fileID = SM.getMainFileID();
const auto fileEntry = SM.getFileEntryForID(
SM.getMainFileID());
std::string full_file_path = fileEntry->getName();
// squarets will generate code from template file
// and append it after annotated variable
/// \note FILE_PATH defined by CMakeLists
/// and passed to flextool via
/// --extra-arg=-DFILE_PATH=...
_squaretsFile(
TYPECLASS_COMBO_TEMPLATE_HPP
)
std::string squarets_output = "";
{
DCHECK(squarets_output.size());
const int writeResult = base::WriteFile(
gen_hpp_name
, squarets_output.c_str()
, squarets_output.size());
// Returns the number of bytes written, or -1 on error.
if(writeResult == -1) {
LOG(ERROR)
<< "Unable to write file: "
<< gen_hpp_name;
} else {
LOG(INFO)
<< "saved file: "
<< gen_hpp_name;
}
}
}
{
std::string headerGuard = "";
base::FilePath gen_cpp_name
= outDir_.Append(
(targetTypeName.empty()
? combinedTypeclassNames
: targetTypeName)
+ ".typeclass_combo.generated.cpp");
std::map<std::string, std::any> cxtpl_params;;
std::string generator_path
= TYPECLASS_COMBO_TEMPLATE_HPP;
DCHECK(!generator_path.empty())
<< "generator_path.empty()"
<< TYPECLASS_COMBO_TEMPLATE_HPP;
generator_includes.push_back(
clang_utils::buildIncludeDirective(
/// \todo utf8 support
gen_hpp_name.AsUTF8Unsafe()));
const auto fileID = SM.getMainFileID();
const auto fileEntry = SM.getFileEntryForID(
SM.getMainFileID());
std::string full_file_path = fileEntry->getName();
// squarets will generate code from template file
// and append it after annotated variable
/// \note FILE_PATH defined by CMakeLists
/// and passed to flextool via
/// --extra-arg=-DFILE_PATH=...
_squaretsFile(
TYPECLASS_COMBO_TEMPLATE_CPP
)
std::string squarets_output = "";
{
DCHECK(squarets_output.size());
const int writeResult = base::WriteFile(
gen_cpp_name
, squarets_output.c_str()
, squarets_output.size());
// Returns the number of bytes written, or -1 on error.
if(writeResult == -1) {
LOG(ERROR)
<< "Unable to write file: "
<< gen_cpp_name;
} else {
LOG(INFO)
<< "saved file: "
<< gen_cpp_name;
}
}
}
return clang_utils::SourceTransformResult{nullptr};
}
#endif // 0
} // namespace plugin
|
#pragma once
#include "stdafx.h"
#include "DataTypes/define.h"
#include "nodeGenFuncs.h"
class VoxelObj;
#define ZERO_INT 0
class sumTable
{
public:
sumTable();
~sumTable();
void initSumTable(VoxelObj *obj);
void setTablePointer(int ***table){m_table = table;};
void computeSum();
int volumeInBox(Boxi b);
int volumeInBox(Vec3i leftDown, Vec3i rightUp);
int sumValueAt(int i, int j, int k);
int sumValueAt(Vec3i p);
void setSumValue(Vec3i p, int val);
void setSumValue(int i, int j, int k, int val);
void initFromNode(nodeGeneration &nodeGen);
float readVoxelData(char* filePath);
public:
Vec3i m_leftDown;
int ***m_table;
Vec3i m_tableSize;
};
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define show(x) for(auto i: x){cout << i << " ";}
typedef long long ll;
int main()
{
int n;
cin >> n;
vector<pair<string, int>> a;
rep(i ,n){
string s;
int num;
cin >> s >> num;
a.push_back(make_pair(s, num));
}
string x;
cin >> x;
int flag = 0;
int ans = 0;
rep(i, n){
if(flag) ans += a[i].second;
if (a[i].first == x){
flag = 1;
}
}
cout << ans << endl;
}
|
//
// VertexBufferLayout.hpp
// Neverland
//
// Created by Admin on 14.07.2021.
//
#pragma once
#include <OpenGLES/ES3/gl.h>
#include <glm/glm.hpp>
#include <vector>
struct Vertex {
// position
glm::vec3 Position;
// texCoords
glm::vec2 TexCoords;
Vertex(glm::vec3 aPosition, glm::vec2 aTexCoords)
: Position(aPosition)
, TexCoords(aTexCoords){};
};
struct VertexBufferElement {
unsigned int type;
unsigned int count;
unsigned char normalized;
static unsigned int getSizeOfType(unsigned int type) {
switch (type) {
case GL_FLOAT:
return 4;
case GL_UNSIGNED_INT:
return 4;
case GL_UNSIGNED_BYTE:
return 1;
}
assert(false);
return 0;
}
};
class VertexBufferLayout {
private:
std::vector<VertexBufferElement> m_Elements;
unsigned int m_Stride;
public:
VertexBufferLayout()
: m_Stride(0) {}
~VertexBufferLayout(){};
template<typename T>
void push(unsigned int count) {
assert(false);
}
template<>
void push<float>(unsigned int count) {
VertexBufferElement element = {GL_FLOAT, count, GL_FALSE};
m_Elements.push_back(element);
m_Stride += count * VertexBufferElement::getSizeOfType(GL_FLOAT);
}
template<>
void push<unsigned int>(unsigned int count) {
VertexBufferElement element = {GL_UNSIGNED_INT, count, GL_FALSE};
m_Elements.push_back(element);
m_Stride += count * VertexBufferElement::getSizeOfType(GL_UNSIGNED_INT);
}
template<>
void push<char>(unsigned int count) {
VertexBufferElement element = {GL_UNSIGNED_BYTE, count, GL_TRUE};
m_Elements.push_back(element);
m_Stride += count * VertexBufferElement::getSizeOfType(GL_UNSIGNED_BYTE);
}
template<>
void push<glm::vec3>(unsigned int count) {
VertexBufferElement element = {GL_FLOAT, count * 3, GL_FALSE};
m_Elements.push_back(element);
m_Stride += count * VertexBufferElement::getSizeOfType(GL_FLOAT) * 3;
}
template<>
void push<glm::vec2>(unsigned int count) {
VertexBufferElement element = {GL_FLOAT, count * 2, GL_FALSE};
m_Elements.push_back(element);
m_Stride += count * VertexBufferElement::getSizeOfType(GL_FLOAT) * 2;
}
void pushVector() {
// positions
push<glm::vec3>(1);
// texture coordinates
push<glm::vec2>(1);
}
inline const std::vector<VertexBufferElement> getElements() const {
return m_Elements;
}
inline unsigned int getStride() const {
return m_Stride;
}
};
|
#ifndef SEARCHMAP_HEADER
#define SEARCHMAP_HEADER
#include "Node.h"
#include <vector>
#include <set>
class Map;
class SearchNode;
class SearchMap
{
// The start and goal node for the A*
SearchNode* m_start;
SearchNode* m_goal;
// List of all the open node to search
std::vector<SearchNode*> openList;
// List of all the node the algorithm already search
std::vector<SearchNode*> closedList;
// All the node to go through the start to the goal
std::vector<unsigned int> m_pathToGoal;
// List of the type we can access
std::set<Node::NodeType> m_forbiddenType;
bool m_isGoalFound = false;
bool m_isInitialized = false;
public:
SearchMap() = delete;
SearchMap(SearchNode* start, SearchNode* goal) : m_start(start), m_goal(goal)
{}
SearchMap(Node* start, Node* goal);
SearchMap(Node* start, Node* goal, std::set<Node::NodeType> forbiddenType);
// Initialise the map between two nodes
void initSearchMap(Node*, Node*, std::set<Node::NodeType> forbiddenType = {Node::NodeType::FORBIDDEN, Node::NodeType::OCCUPIED});
// Execute the search function to get a path
std::vector<unsigned int> search();
// Prepare the node to add it in the open list
void prepareNode(Node*, unsigned int, SearchNode*);
// Return the next node to be in the closed list (lowest cost)
SearchNode* getNextNodeToSearch();
// Calcule the manhattan distance
unsigned int calculateManhattan(const SearchNode* start, const SearchNode* goal) const;
};
#endif // SEARCHMAP_HEADER
|
#include "HashTable.h"
//#include "LinkedList.h"
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
/*
int main() {
std::cout << "start" << std::endl << " ----------------------" << std::endl;
HashTable ht1(9);
ht1.insert("bat");
ht1.insert("cat");
ht1.insert("rhinoceros");
ht1.insert("ocelot");
ht1.insert("elephant");
ht1.insert("hippopotamus");
ht1.insert("giraffe");
ht1.insert("camel");
ht1.insert("lion");
ht1.insert("panther");
ht1.insert("bear");
ht1.insert("wolf");
// search
cout << "search" << endl;
string test1 = "frog";
string test2 = "camel";
cout << test1 << ": " << ht1.search(test1) << endl;
cout << test2 << ": " << ht1.search(test2) << endl;
// copy constructor and remove
HashTable ht2(ht1);
ht2.remove("ocelot");
ht2.remove("camel");
ht2.remove("rhinoceros");
// set difference
cout << endl << "set difference" << endl;
vector<string> difference = ht1.difference(ht2);
for(unsigned int i=0; i < difference.size(); ++i){
cout << difference[i] << endl;
}
return 0;
}
*/
int main() {
std::cout << "start" << std::endl << " ----------------------" << std::endl;
HashTable ht1(9);
ht1.insert("bat");
ht1.insert("cat");
ht1.insert("rhinoceros");
ht1.insert("ocelot");
ht1.insert("elephant");
ht1.insert("hippopotamus");
ht1.insert("giraffe");
ht1.insert("camel");
ht1.insert("lion");
ht1.insert("panther");
ht1.insert("bear");
ht1.insert("wolf");
// search
cout << "search" << endl;
string test1 = "frog";
string test2 = "camel";
cout << test1 << ": " << ht1.search(test1) << endl;
cout << test2 << ": " << ht1.search(test2) << endl;
// copy constructor and remove
HashTable ht2(ht1);
ht2.remove("ocelot");
ht2.remove("camel");
ht2.remove("rhinoceros");
// set difference
cout << endl << "set difference" << endl;
vector<string> difference = ht1.difference(ht2);
for(unsigned int i=0; i < difference.size(); ++i){
cout << difference[i] << endl;
}
return 0;
/*
std::cout << "start" << std::endl << " ----------------------" << std::endl;
HashTable ht1(9);
ht1.insert("bat");
ht1.insert("cat");
ht1.insert("rhinoceros");
ht1.insert("ocelot");
// ht1.insert("elephant");
// ht1.insert("hippopotamus");
// ht1.insert("giraffe");
ht1.insert("camel");
ht1.insert("lion");
ht1.insert("panther");
ht1.insert("bear");
ht1.insert("wolf");
// search
cout << "search" << endl;
string test1 = "frog";
string test2 = "camel";
cout << test1 << ": " << ht1.search(test1) << endl;
cout << test2 << ": " << ht1.search(test2) << endl;
// copy constructor and remove
HashTable ht2(ht1);
ht2.insert("bat");
ht2.insert("cat");
ht2.insert("rhinoceros");
ht2.insert("ocelot");
// ht1.insert("elephant");
// ht1.insert("hippopotamus");
// ht1.insert("giraffe");
ht2.insert("camel");
ht2.insert("lion");
ht2.insert("panther");
ht2.insert("bear");
ht2.insert("wolf");
ht2.remove("ocelot");
ht2.remove("camel");
ht2.remove("rhinoceros");
cout << endl << "set difference" << endl;
vector<string> difference = ht1.difference(ht2);
for(unsigned int i=0; i < difference.size(); ++i){
cout << difference[i] << endl;
}
return 0;
*/
/*
LinkedList ls;
ls.insert("apple");
ls.insert("corn");
ls.insert("apple");
ls.insert("pie");
LinkedList copy = ls;
ls.print();
copy.remove("corn");
copy.insert("cake");
copy.insert("pudding");
copy.remove("apple");
copy.print();
LinkedList duplicate;
duplicate = copy;
duplicate.insert("bike");
duplicate.print();
std::vector<std::string> vectorTest;
vectorTest = duplicate.get();
std::cout << std::endl << std::endl << "Vector contains: ";
for(unsigned int i = 0; i < vectorTest.size(); i++) {
std::cout << vectorTest[i] << " ";
}
std::vector<std::string> v1;
std::vector<std::string> v2;
std::vector<std::string> v3;
std::vector<std::string> v4;
std::vector<std::string> v5;
v3.push_back("honda");
v3.push_back("yamaha");
v3.push_back("suzuki");
v2.push_back("accord");
v2.push_back("civic");
v2.push_back("corolla");
v2.insert(v2.end(), v3.begin(), v3.end());
std::cout << std::endl << "V2 contains: ";
for(unsigned int i = 0; i < v2.size(); i++) {
std::cout << v2[i] << " ";
}
v1 = v2;
std::cout << std::endl << "V1 contains: ";
for(unsigned int i = 0; i < v1.size(); i++) {
std::cout << v1[i] << " ";
}
v1.insert(v1.end(), v4.begin(), v4.end());
std::cout << std::endl << "V1 contains when adding v4 which is empty: ";
for(unsigned int i = 0; i < v1.size(); i++) {
std::cout << v1[i] << " ";
}
v5.insert(v5.end(), v4.begin(), v4.end());
std::cout << std::endl << "V5 is empty adding v4 which is empty: ";
for(unsigned int i = 0; i < v5.size(); i++) {
std::cout << v5[i] << " ";
}
int a = 0;
int b = 2;
int c = 3;
a = std::pow(b,c);
std::cout << std::endl << std::endl << "A = " << a << std::endl;
LinkedList test[2];
test[0].insert("apple");
test[0].insert("orange");
test[1].insert("derp");
test[1].insert("herp");
test[1].print();
test[0].print();
test[1].insert("herp");
HashTable tester(5);
tester.insert("apple");
tester.insert("orange");
tester.insert("banana");
std::cout <<"inserting in different key" << std::endl;
tester.insert("grape");
tester.insert("melon");
tester.insert("plum");
HashTable test1(3);
int p = test1.maxSize();
std::cout << "Test1 array size: " << p << std::endl;
test1.insert("fox");
test1.insert("cat");
test1.insert("grape");
test1.insert("dog");
test1.insert("plum");
test1.insert("lion");
test1.insert("wolf");
int howmany;
howmany = test1.size();
std::cout << "Test 1 contains: " << howmany << " entries" << std::endl;
test1.search("abc");
test1.search("dog");
tester.intersection(test1);
tester.unions(test1);
tester.difference(test1);
*/
}
|
#pragma once
namespace keng::memory
{
class VirtualMemoryChunk
{
public:
VirtualMemoryChunk();
VirtualMemoryChunk(size_t bytes, size_t pageSize);
VirtualMemoryChunk(const VirtualMemoryChunk&) = delete;
VirtualMemoryChunk(VirtualMemoryChunk&& that);
~VirtualMemoryChunk();
void Commit(size_t bytes);
void* GetData() const;
VirtualMemoryChunk& operator=(const VirtualMemoryChunk&) = delete;
VirtualMemoryChunk& operator=(VirtualMemoryChunk&& that);
protected:
size_t BytesToPages(size_t bytes) const;
void MoveFrom(VirtualMemoryChunk& that);
void Release();
void Invalidate();
bool IsValid() const;
private:
size_t m_pageSize = 100;
size_t m_usedPages = 0;
size_t m_reservedPages = 0;
void* m_data = nullptr;
};
}
|
/*****************************************
* (This comment block is added by the Judge System)
* Submission ID: 13545
* Submitted at: 2015-03-16 19:49:43
*
* User ID: 94
* Username: 53064064
* Problem ID: 176
* Problem Name: Internet Bandwidth (UVa 820)
*/
#include<iostream>
#include<queue>
#include<stack>
#include<vector>
#include<stdio.h>
#include<algorithm>
#include<string>
#include<string.h>
#include<sstream>
#include<math.h>
#include<iomanip>
#include<map>
#define N 105
#define INF 1500
using namespace std;
int n,s,t,c,x,y,w;
int aug[N];
int pre[N];
int cap[N][N];
//int flow[N][N];
int EdmondsKarp(){
queue<int> q;
//memset(flow,0,sizeof(flow));
int f=0;
while(true){
memset(aug, 0, sizeof(aug));
aug[s] = INF;
q.push(s);
while(!q.empty()){
int u = q.front();
q.pop();
for(int v =1; v<=n; v++){
if(!aug[v] && cap[u][v]){
pre[v] = u;
q.push(v);
aug[v] = min(aug[u],cap[u][v]);
}
}
}
if(aug[t] == 0) break;
int temp = t;
while(temp!=s){
cap[pre[temp]][temp] -= aug[t];
cap[temp][pre[temp]] += aug[t];
temp = pre[temp];
}
f += aug[t];
}
return f;
}
int main(){
int set = 1;
while(scanf("%d", &n)){
memset(cap,0,sizeof(cap));
if(n == 0) break;
scanf("%d %d %d", &s, &t, &c);
for(int i=0; i<c; i++){
scanf("%d %d %d", &x, &y, &w);
cap[x][y] += w;
cap[y][x] += w;
}
printf("Network %d\nThe bandwidth is %d.\n\n", set++, EdmondsKarp());
}
return 0;
}
|
#ifndef POINT_H
#define POINT_H
class Point
{
public:
Point(float x, float y);
~Point() = default;
const float abs() const;
Point operator+ (const Point& rhs) { return Point(x + rhs.x, y + rhs.y); }
friend bool operator== (const Point& lhs, const Point& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; }
friend bool operator< (const Point& lhs, const Point& rhs) { return lhs.abs() < rhs.abs();}
friend bool operator> (const Point& lhs, const Point& rhs) { return rhs < lhs;}
friend bool operator<= (const Point& lhs, const Point& rhs) { return !(lhs > rhs); }
friend bool operator>= (const Point& lhs, const Point& rhs) { return !(lhs < rhs); }
float GetX();
float GetY();
private:
float x, y;
};
#endif
|
#ifndef Snake_h
#define Snake_h
#include "Position.h"
#include "Point.h"
using namespace std;
struct Snake
{
Position positionH, positionT;
int sizeS, num, stepX, stepY, times;
vector <Position> position_arr;
Snake();
void render(SDL_Renderer* renderer, const int& head, SDL_Texture** const Image) const;
void move();
void turnUp();
void turnDown();
void turnLeft();
void turnRight();
void eat(Point& point, long long& num_score, int& time_to_minus, const int& wallSize);
};
#endif
|
#include "Real.h"
#include <iostream>
#include <iomanip>
Real::Real(int n, int d)
{
setReal(n, d);
}
void Real::setReal(int n, int d)
{
setNumerador(n);
setDenominador(d);
reducir();
}
void Real::setNumerador(int n)
{
numerador = n;
}
void Real::setDenominador(int d)
{
if (d < 0) //si denominador es negativo
{
setNumerador(getNumerador() * -1);
denominador = d * -1;
}
else
{
denominador = d;
}
}
int Real::getNumerador()
{
return numerador;
}
int Real::getDenominador()
{
return denominador;
}
void Real::imprimir()
{
if (getDenominador() == 0)
std::cout << "Indefinido" << std::endl;
else if (getNumerador() == 0)
std::cout << "0" << std::endl;
else
{
std::cout << getNumerador() << "/" << getDenominador() << std::endl
<< std::setprecision(5) << (double)getNumerador() / (double)getDenominador() << std::endl;
}
}
void Real::reducir()
{
if ((getDenominador() * getNumerador()) != 0)
{
//Algoritmo de euclides
int n = (getNumerador() < 0) ? (getNumerador() * -1) : getNumerador(), d = getDenominador(), r = n % d;
while (n % d != 0)
{
r = n % d;
n = d;
d = r;
}
setNumerador(getNumerador() / d);
setDenominador(getDenominador() / d);
}
}
Real Real::suma(Real a, Real b)
{
Real c = Real(a.getNumerador() * b.getDenominador() + a.getDenominador() * b.getNumerador(), a.getDenominador() * b.getDenominador());
return c;
}
Real Real::resta(Real a, Real b)
{
Real c = Real(a.getNumerador() * b.getDenominador() - a.getDenominador() * b.getNumerador(), a.getDenominador() * b.getDenominador());
return c;
}
Real Real::multiplicacion(Real a, Real b)
{
Real c = Real(a.getNumerador() * b.getNumerador(), a.getDenominador() * b.getDenominador());
return c;
}
Real Real::divicion(Real a, Real b)
{
Real c = Real(a.getNumerador() * b.getDenominador(), a.getDenominador() * b.getNumerador());
return c;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
**
*/
#include "core/pch.h"
#include "modules/encodings/utility/charsetnames.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#include "modules/util/opfile/opfile.h"
#include "modules/url/url2.h"
#include "modules/url/url_ds.h"
#include "modules/url/url_rep.h"
#include "modules/url/url_man.h"
#include "modules/cache/url_cs.h"
#include "modules/cache/cache_int.h"
#include "modules/cache/multimedia_cache.h"
#ifdef PI_ASYNC_FILE_OP
#include "modules/cache/cache_exporter.h"
#endif // PI_ASYNC_FILE_OP
#include "modules/olddebug/timing.h"
#if CACHE_SMALL_FILES_SIZE>0
#include "modules/cache/simple_stream.h"
#endif
#if CACHE_CONTAINERS_ENTRIES>0
#include "modules/cache/cache_container.h"
#endif
#ifdef _DEBUG
#ifdef YNP_WORK
#include "modules/olddebug/tstdump.h"
#include "modules/url/tools/url_debug.h"
#define _DEBUG_DD
#define _DEBUG_DD1
#endif
#endif
/// Create a read only file descriptor based on a buffer; it's a simplified implementation
class ReadOnlyBufferFileDescriptor: public OpFileDescriptor
{
private:
/// Buffer that contains the data; it is owned by the creator, not by this object
UINT8 *buf;
/// Size of the buffer
UINT32 size;
/// Current position
UINT32 pos;
public:
/**
Constructor
@param buffer Buffer that contains the data. The buffer is not copied, so it cannot be deleted while this object is alive
@param length Length of the buffer
*/
ReadOnlyBufferFileDescriptor(void *buffer, UINT32 length) { OP_ASSERT(buffer); buf=(UINT8 *)buffer; size=length; pos=0; }
virtual OpFileType Type() const {
return OPFILE;
}
// The following methods are equivalent to those in OpLowLevelFile.
// See modules/pi/system/OpLowLevelFile.h for further documentation.
virtual BOOL IsWritable() const { return FALSE; }
virtual OP_STATUS Open(int mode) { if(mode!=OPFILE_READ) return OpStatus::ERR_NOT_SUPPORTED; return OpStatus::OK; }
virtual BOOL IsOpen() const { return TRUE; }
virtual OP_STATUS Close() { return OpStatus::OK; }
virtual BOOL Eof() const { return pos>=size; }
virtual OP_STATUS Exists(BOOL& exists) const { exists=TRUE; return OpStatus::OK; }
virtual OP_STATUS GetFilePos(OpFileLength& position) const { position=pos; return OpStatus::OK; };
virtual OP_STATUS SetFilePos(OpFileLength position, OpSeekMode seek_mode=SEEK_FROM_START) { OP_ASSERT(position<size); OP_ASSERT(seek_mode==SEEK_FROM_START); if(seek_mode!=SEEK_FROM_START) return OpStatus::ERR_NOT_SUPPORTED; pos=(UINT32)position; return OpStatus::OK; } ;
virtual OP_STATUS GetFileLength(OpFileLength& length) const { length=size; return OpStatus::OK; }
virtual OP_STATUS Write(const void* data, OpFileLength len) { return OpStatus::ERR_NOT_SUPPORTED; }
virtual OP_STATUS Read(void* data, OpFileLength len, OpFileLength* bytes_read=NULL)
{
if(bytes_read)
*bytes_read=0;
if(pos==size)
return OpStatus::OK;
if(pos>size)
return OpStatus::ERR_OUT_OF_RANGE;
UINT32 bytes=(UINT32) (pos+len>size?size-pos:len);
op_memcpy(data, buf+pos, bytes);
pos+=bytes;
if(bytes_read)
*bytes_read=bytes;
return OpStatus::OK;
}
virtual OP_STATUS ReadLine(OpString8& str) { return OpStatus::ERR_NOT_SUPPORTED; }
virtual OpFileDescriptor* CreateCopy() const { return OP_NEW(ReadOnlyBufferFileDescriptor, (buf, size)); }
};
unsigned long GetFileError(OP_STATUS op_err, URL_Rep *url, const uni_char *operation);
OpFileDescriptor* Cache_Storage::CreateAndOpenFile(const OpStringC &filename, OpFileFolder folder, OpFileOpenMode mode, OP_STATUS &op_err, int flags)
{
op_err = OpStatus::OK;
if(filename.HasContent())
{
__DO_START_TIMING(TIMING_FILE_OPERATION);
CacheFile *fil = OP_NEW(CacheFile, ());
if(!fil)
op_err = OpStatus::ERR_NO_MEMORY;
if(OpStatus::IsSuccess(op_err))
{
op_err = fil->Construct(filename.CStr(), folder, flags);
if(OpStatus::IsSuccess(op_err))
{
op_err = fil->Open(mode);
}
}
__DO_STOP_TIMING(TIMING_FILE_OPERATION);
if(OpStatus::IsError(op_err))
{
OP_DELETE(fil);
fil = NULL;
//url->HandleError(GetFileError(op_err, url,UNI_L("open")));
}
return fil;
}
else
{
op_err=OpStatus::ERR_OUT_OF_RANGE;
return NULL;
}
}
Cache_Storage::Cache_Storage(URL_Rep *url_rep)
{
InternalInit(url_rep, NULL);
}
Cache_Storage::Cache_Storage(Cache_Storage *old)
{
InternalInit(NULL, old);
}
void Cache_Storage::InternalInit(URL_Rep *url_rep, Cache_Storage *old)
{
OP_ASSERT((url_rep && !old) || (!url_rep && old));
storage_id = g_url_storage_id_counter++;
content_size = 0;
read_only = FALSE;
save_position=FILE_LENGTH_NONE;
in_setfinished = FALSE;
if(!url_rep && old)
url = old->url;
else
url = url_rep;
OP_ASSERT(url);
#if defined __OEM_EXTENDED_CACHE_MANAGEMENT && defined __OEM_OPERATOR_CACHE_MANAGEMENT
never_flush = FALSE;
#endif
http_response_code = (unsigned short) url->GetAttribute(URL::KHTTP_Response_Code);
content_type = (URLContentType) url->GetAttribute(URL::KContentType);
charset_id = (unsigned short) url->GetAttribute(URL::KMIME_CharSetId);
g_charsetManager->IncrementCharsetIDReference(charset_id);
OP_MEMORY_VAR URLType type= (URLType) url_rep->GetAttribute(URL::KType);
cache_content.SetIsSensitive(type == URL_HTTPS ? TRUE : FALSE);
#ifdef CACHE_ENABLE_LOCAL_ZIP
encode_storage = NULL;
#endif
#ifdef CACHE_STATS
retrieved_from_disk=FALSE;
stats_flushed=0;
#endif
#if CACHE_SMALL_FILES_SIZE>0
embedded=FALSE;
#endif
#if CACHE_CONTAINERS_ENTRIES>0
container_id=0;
prevent_delete=FALSE;
#ifdef SELFTEST
checking_container=FALSE;
#endif
#endif
#ifdef SELFTEST
bypass_asserts=FALSE;
debug_simulate_store_error=FALSE;
num_disk_read=0;
#endif
#if (CACHE_SMALL_FILES_SIZE>0 || CACHE_CONTAINERS_ENTRIES>0)
plain_file=FALSE;
#endif
if(old)
{
url = old->url;
old->cache_content.ResetRead();
TRAPD(op_err, cache_content.AddContentL(&old->cache_content));
OpStatus::Ignore(op_err); // FIXME: report errors;
content_size= old->content_size;
read_only = old->read_only;
#if defined __OEM_EXTENDED_CACHE_MANAGEMENT && defined __OEM_OPERATOR_CACHE_MANAGEMENT
never_flush = old->never_flush;
#endif
URL_DataDescriptor *item;
while((item = old->First()) != NULL)
{
item->Out();
item->Into(this);
item->SetStorage(this);
}
}
}
Cache_Storage::~Cache_Storage()
{
InternalDestruct();
}
void Cache_Storage::TruncateAndReset()
{
OP_NEW_DBG("Cache_Storage::TruncateAndReset", "cache.limit");
OP_DBG((UNI_L("URL: %s - %x - content_size: %d - cache_content: %d - ctx id: %d - read_only: %d\n"), url->GetAttribute(URL::KUniName).CStr(), url, (UINT32) content_size, cache_content.GetLength(), url->GetContextId(), read_only));
#if CACHE_SMALL_FILES_SIZE>0
if(IsEmbedded())
{
urlManager->DecEmbeddedSize(cache_content.GetLength());
embedded=FALSE;
}
#endif
ResetForLoading();
content_encoding.Empty();
}
void Cache_Storage::InternalDestruct()
{
SubFromCacheUsage(url, IsRAMContentComplete(), IsDiskContentAvailable() && HasContentBeenSavedToDisk());
#ifdef SELFTEST
GetContextManager()->VerifyURLSizeNotCounted(url, TRUE, TRUE);
#endif // SELFTEST
url = NULL;
content_size= 0;
read_only = FALSE;
g_charsetManager->DecrementCharsetIDReference(charset_id);
#ifdef CACHE_ENABLE_LOCAL_ZIP
OP_DELETE(encode_storage);
encode_storage = NULL;
#endif
URL_DataDescriptor *desc;
while((desc = First()) != NULL)
{
desc->SetStorage(NULL);
desc->Out();
}
}
BOOL Cache_Storage::Purge()
{
return FlushMemory();
}
#if CACHE_SMALL_FILES_SIZE>0
BOOL Cache_Storage::ManageEmbedding()
{
// "Plain" files are not embedded
if(plain_file)
return FALSE;
// Small files are kept in memory and stored in the index
if(IsEmbedded())
return TRUE;
// Check if it can be embedded
if(IsEmbeddable())
{
UINT32 size=cache_content.GetLength();
#ifdef CACHE_SMALL_FILES_LIMIT
OP_ASSERT(CACHE_SMALL_FILES_LIMIT>0); // Instead of putting a limit of 0, disable CACHE_SMALL_FILES_SIZE
if(urlManager->GetEmbeddedSize()+size<=CACHE_SMALL_FILES_LIMIT)
#else
// This combination is not supposed to be enabled, because memory can grow too much...
// An high limit should be fine
OP_ASSERT(FALSE);
#endif
{
embedded=TRUE;
urlManager->IncEmbeddedSize(size);
return TRUE;
}
}
return FALSE;
}
void Cache_Storage::RollBackEmbedding()
{
OP_ASSERT(IsEmbedded());
if(IsEmbedded())
{
urlManager->DecEmbeddedSize(cache_content.GetLength());
embedded=FALSE;
}
}
#endif // CACHE_SMALL_FILES_SIZE
void Cache_Storage::SetCharsetID(unsigned short id)
{
g_charsetManager->IncrementCharsetIDReference(id);
g_charsetManager->DecrementCharsetIDReference(charset_id);
charset_id=id;
}
void Cache_Storage::AddToDiskOrOEMSize(OpFileLength size_to_add, URL_Rep *url, BOOL add_url_size_estimantion)
{
#if defined __OEM_EXTENDED_CACHE_MANAGEMENT && defined __OEM_OPERATOR_CACHE_MANAGEMENT
if(never_flush)
urlManager->GetMainContext()->AddToOCacheSize(size_to_add, url, add_url_size_estimantion);
#ifndef RAMCACHE_ONLY
else
#endif // RAMCACHE_ONLY
#endif // defined __OEM_EXTENDED_CACHE_MANAGEMENT && defined __OEM_OPERATOR_CACHE_MANAGEMENT
#ifndef RAMCACHE_ONLY
GetContextManager()->AddToCacheSize(size_to_add, url, add_url_size_estimantion);
#endif // RAMCACHE_ONLY
SetContentAlreadyStoredOnDisk(GetContentAlreadyStoredOnDisk() + size_to_add);
SetDiskContentComputed(TRUE);
}
void Cache_Storage::SubFromDiskOrOEMSize(OpFileLength size_to_sub, URL_Rep *url, BOOL enable_checks)
{
#if defined __OEM_EXTENDED_CACHE_MANAGEMENT && defined __OEM_OPERATOR_CACHE_MANAGEMENT
if(never_flush)
urlManager->GetMainContext()->SubFromOCacheSize(size_to_sub, url, enable_checks);
#ifndef RAMCACHE_ONLY
else
#endif // RAMCACHE_ONLY
#endif // defined __OEM_EXTENDED_CACHE_MANAGEMENT && defined __OEM_OPERATOR_CACHE_MANAGEMENT
#ifndef RAMCACHE_ONLY
GetContextManager()->SubFromCacheSize(size_to_sub, url, enable_checks);
#endif // RAMCACHE_ONLY
SetContentAlreadyStoredOnDisk(GetContentAlreadyStoredOnDisk() - size_to_sub);
}
void Cache_Storage::AddToCacheUsage(URL_Rep *url, BOOL ram, BOOL disk_oem, BOOL add_url_size_estimantion)
{
OP_NEW_DBG("Cache_Storage::AddToCacheUsage()", "cache.limit");
OP_DBG((UNI_L("URL: %s - %x - content_size: %d - cache_content: %d - ctx id: %d - ram: %d - disk_oem: %d - add_url_size_estimantion:%d\n"), url->GetAttribute(URL::KUniName).CStr(), url, (UINT32) content_size, cache_content.GetLength(), url->GetContextId(), ram, disk_oem, add_url_size_estimantion));
if(ram)
{
if(!GetMemoryOnlyStorage())
GetContextManager()->AddToRamCacheSize(cache_content.GetLength(), url, add_url_size_estimantion);
}
if(disk_oem && (content_size || add_url_size_estimantion))
AddToDiskOrOEMSize(content_size, url, add_url_size_estimantion);
}
void Cache_Storage::SubFromCacheUsage(URL_Rep *url, BOOL ram, BOOL disk_oem)
{
OP_NEW_DBG("Cache_Storage::SubFromCacheUsage()", "cache.limit");
OP_DBG((UNI_L("URL: %s - %x - content_size: %d - cache_content: %d - ctx id: %d - ram: %d - disk_oem: %d\n"), url->GetAttribute(URL::KUniName).CStr(), url, (UINT32) content_size, cache_content.GetLength(), url->GetContextId(), ram, disk_oem));
if(ram)
{
if(!GetMemoryOnlyStorage())
GetContextManager()->SubFromRamCacheSize(cache_content.GetLength(), url);
}
if(disk_oem && (GetContentAlreadyStoredOnDisk() || GetDiskContentComputed()))
{
// GetContentAlreadyStoredOnDisk() should be set only if GetDiskContentComputed() is TRUE
OP_ASSERT(GetDiskContentComputed());
SubFromDiskOrOEMSize(GetContentAlreadyStoredOnDisk(), url, TRUE);
OP_ASSERT(GetContentAlreadyStoredOnDisk()==0);
SetDiskContentComputed(FALSE);
}
#ifdef SELFTEST
GetContextManager()->VerifyURLSizeNotCounted(url, ram, disk_oem);
#endif // SELFTEST
}
void Cache_Storage::SetFinished(BOOL)
{
OP_NEW_DBG("Cache_Storage::SetFinished()", "cache.limit");
OP_DBG((UNI_L("URL: %s - %x - content_size: %d - cache_content: %d - ctx id: %d - read_only: %d ==> TRUE - IsDiskContentAvailable: %d - HasContentBeenSavedToDisk: %d\n"), url->GetAttribute(URL::KUniName).CStr(), url, (UINT32) content_size, cache_content.GetLength(), url->GetContextId(), read_only, IsDiskContentAvailable(), HasContentBeenSavedToDisk()));
if (in_setfinished)
{
// Already in setfinished so we can't do anything here
OP_ASSERT(1==0 && !"SetFinished entered recursively!");
return;
}
in_setfinished = TRUE;
if(!read_only)
{
#ifdef CACHE_ENABLE_LOCAL_ZIP
if(encode_storage)
{
OpStatus::Ignore(encode_storage->FinishStorage(this)); // FIXME
OP_DELETE(encode_storage);
encode_storage = NULL;
}
#endif
TRAPD(op_err, cache_content.FinishedAddingL());
OpStatus::Ignore(op_err); // FIXME
content_size += cache_content.GetLength();
}
#ifdef SELFTEST
GetContextManager()->VerifyURLSizeNotCounted(url, !IsRAMContentComplete(), FALSE /* Content on disk can already have been written during StoreData() */);
#endif // SELFTEST
AddToCacheUsage(url, !IsRAMContentComplete(), IsDiskContentAvailable() && !HasContentBeenSavedToDisk(), TRUE);
read_only = TRUE;
in_setfinished = FALSE;
}
void Cache_Storage::UnsetFinished()
{
#ifdef SELFTEST
if(!read_only)
GetContextManager()->VerifyURLSizeNotCounted(url, TRUE, FALSE);
#endif // SELFTEST
if(!read_only)
return;
SubFromCacheUsage(url, TRUE, FALSE);
read_only = FALSE;
}
OP_STATUS Cache_Storage::StoreDataEncode(const unsigned char *buffer, unsigned long buf_len)
{
#ifdef CACHE_ENABLE_LOCAL_ZIP
if(encode_storage)
return encode_storage->StoreData(this, buffer, buf_len);
#endif
return StoreData(buffer, buf_len);
}
OP_STATUS Cache_Storage::StoreData(const unsigned char *buffer, unsigned long buf_len, OpFileLength start_position)
{
OP_NEW_DBG("Cache_Storage::StoreData()", "cache.storage");
OP_DBG((UNI_L("URL: %s - %x - Len: %d - URL points to me: %d\n"), url->GetAttribute(URL::KUniName).CStr(), url, (int) buf_len, url->GetDataStorage() && url->GetDataStorage()->GetCacheStorage()==this));
if(read_only || buffer == NULL || buf_len == 0)
return OpStatus::OK;
OP_STATUS op_err = OpStatus::OK;
#if CACHE_SMALL_FILES_SIZE>0
OP_ASSERT(CACHE_SMALL_FILES_SIZE<=4*FL_MAX_SMALL_PAYLOAD);
#endif
// that version will not assert on what we are doing
if(cache_content.GetLength() == 0)
{
OpFileLength content_len=0;
url->GetAttribute(URL::KContentSize, &content_len);
if(content_len && content_len <= 4*FL_MAX_SMALL_PAYLOAD)
{
// Preallocate the expected length of content
// As we have not specified fixed length or direct access
// the object will naturally convert to large payload.
TRAP(op_err, cache_content.ResizeL((uint32) content_len, TRUE));
}
}
if(OpStatus::IsSuccess(op_err))
TRAP(op_err, cache_content.AddContentL(buffer, buf_len));
#ifdef SELFTEST
if(debug_simulate_store_error)
op_err=OpStatus::ERR_NO_MEMORY;
#endif
if(OpStatus::IsError(op_err))
{
if(OpStatus::IsMemoryError(op_err))
{
BOOL unsafe=url->GetDataStorage() && url->GetDataStorage()->GetCacheStorage() && url->GetDataStorage()->GetCacheStorage()->CircularReferenceDetected(this);
url->HandleError(ERR_SSL_ERROR_HANDLED);
g_memory_manager->RaiseCondition( op_err );
if(unsafe)
return op_err;
}
TRAP(op_err, cache_content.AddContentL(buffer, buf_len));
if(OpStatus::IsError(op_err))
{
url->HandleError(ERR_SSL_ERROR_HANDLED);
if(OpStatus::IsMemoryError(op_err))
g_memory_manager->RaiseCondition( op_err );
}
}
//OP_NEW_DBG("Cache_Storage::StoreData()", "cache.storage");
OP_DBG((UNI_L("URL: %s - %x - bytes stored: %d\n"), url->GetAttribute(URL::KUniName).CStr(), url, buf_len));
return op_err;
}
unsigned long Cache_Storage::RetrieveData(URL_DataDescriptor *desc,BOOL &more)
{
OP_NEW_DBG("Cache_Storage::RetrieveData()", "cache.storage");
OP_DBG((UNI_L("URL: %s - %x"), url->GetAttribute(URL::KUniName).CStr(), url));
more = FALSE;
if( desc == NULL || !desc->RoomForContent() || cache_content.GetLength() == 0)
{
if(desc && cache_content.GetLength() > 0)
more = TRUE;
return (desc ? desc->GetBufSize() : 0);
}
cache_content.SetReadPos((uint32) desc->GetPosition()+desc->GetBufSize());
// CORE-27718: optimization to reduce the allocation of memory when the content length is available
if(!desc->GetBuffer())
{
OpFileLength content_len=0;
url->GetAttribute(URL::KContentSize, &content_len);
if(content_len)
desc->Grow((unsigned long)content_len, URL_DataDescriptor::GROW_SMALL);
}
TRAPD(err, desc->AddContentL(&cache_content, NULL, 0));
if(OpStatus::IsMemoryError(err))
{
g_memory_manager->RaiseCondition( OpStatus::ERR_NO_MEMORY );
return (desc ? desc->GetBufSize() : 0);
}
if(cache_content.MoreData())
{
if(!desc->PostedMessage())
desc->PostMessage(MSG_URL_DATA_LOADED, url->GetID(), 0);
more = TRUE;
}
else
{
/**
A multipart URL has a storage of type Multipart_CacheStorage,
which when iterating over the parts creates a Cache_Storage for
each. So, in that situation, GetIsMultipart() is FALSE but
url->GetDataStorage()->GetCacheStorage()->GetIsMultipart() is TRUE.
In that case the message cannot be posted because that is handled
by the Multipart_CacheStorage.
*/
Cache_Storage *cs = url->GetDataStorage()->GetCacheStorage();
if (!cs || !cs->GetIsMultipart())
if (desc->GetBufSize() > 0 && !desc->PostedMessage())
desc->PostMessage(MSG_URL_DATA_LOADED, url->GetID(), 0);
//OP_ASSERT(desc->GetPosition()+desc->GetBufSize() == cache_content.GetLength() &&(!GetFinished() || (URLStatus) url->GetAttribute(URL::KLoadStatus) != URL_LOADING));
if(!GetFinished() && (URLStatus) url->GetAttribute(URL::KLoadStatus) == URL_LOADING && desc->HasMessageHandler())
more = TRUE;
}
OP_DBG((UNI_L("URL: %s - more: %d\n"), url->GetAttribute(URL::KUniName).CStr(), more));
#ifdef _DEBUG_DD1
PrintfTofile("urldd1.txt","\nCS Retrieve Data2- %s - %u:%u %s - %s - %s\n",
DebugGetURLstring(url),
cache_content.GetReadPos(), cache_content.GetLength(),
(url->GetAttribute(URL::KLoadStatus) == URL_LOADING ? "Not Loaded" : "Loaded"),
(GetFinished() ? "Finished" : "Not Finished"),
(desc->HasMessageHandler() ? "MH" : "not MH")
);
#endif
return desc->GetBufSize();
}
#ifdef UNUSED_CODE
BOOL Cache_Storage::OOMForceFlush()
{
SetFinished();
if(!Flush())
return FALSE;
UnsetFinished();
return TRUE;
}
#endif
#ifdef CACHE_RESOURCE_USED
OpFileLength Cache_Storage::ResourcesUsed(ResourceID resource)
{
return (resource == MEMORY_RESOURCE ? cache_content.GetLength() : 0);
}
#endif
URL_DataDescriptor *Cache_Storage::GetDescriptor(MessageHandler *mh, BOOL get_raw_data, BOOL get_decoded_data, Window *window,
URLContentType override_content_type, unsigned short override_charset_id, BOOL get_original_content, unsigned short parent_charset_id)
{
URL_DataDescriptor * OP_MEMORY_VAR desc;
if(override_content_type == URL_UNDETERMINED_CONTENT)
override_content_type = content_type;
if(override_charset_id == 0)
override_charset_id = charset_id;
desc = OP_NEW(URL_DataDescriptor, (url, mh, override_content_type, override_charset_id, parent_charset_id));
if(desc == NULL)
g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY);
else if(OpStatus::IsError(desc->Init(get_raw_data, window)))
{
OP_DELETE(desc);
desc = NULL;
}
if(desc)
{
#ifdef _HTTP_COMPRESS
//OpStringS8 *encoding = url->GetHTTPEncoding();
if(content_encoding.Length() && get_decoded_data
#ifdef _MIME_SUPPORT_
&& !IsProcessed()
#endif // _MIME_SUPPORT_
)
{
TRAPD(op_err,desc->SetupContentDecodingL(content_encoding.CStr()));
if(OpStatus::IsError(op_err))
{
OP_DELETE(desc);
desc = NULL;
return NULL;
}
}
#endif // _HTTP_COMPRESS
AddDescriptor(desc);
}
return desc;
}
void Cache_Storage::AddDescriptor(URL_DataDescriptor *desc)
{
desc->SetStorage(this);
desc->Into(this);
}
void Cache_Storage::CloseFile()
{
// Nothing to do in this case
// To be overloaded by storages that really use a file
}
OpFileDescriptor* Cache_Storage::AccessReadOnly(OP_STATUS &op_err)
{
cache_content.SetNeedDirectAccess(TRUE);
OpFileDescriptor *fd=OP_NEW(ReadOnlyBufferFileDescriptor, (cache_content.GetDirectPayload(), cache_content.GetLength()));
op_err=fd ? OpStatus::OK : OpStatus::ERR_NO_MEMORY;
return fd;
}
OP_STATUS Cache_Storage::CheckExportAsFile(BOOL allow_embedded_and_containers)
{
// These checks are a bit too much restrictive, but basically this feature is used to speed up the saving
// of big images and video files (video tag)
// Check CORE-31730 and DSK-292617
if( (URLStatus)url->GetAttribute(URL::KLoadStatus) != URL_LOADED ||
!GetFinished() || GetIsMultipart())
return OpStatus::ERR_NOT_SUPPORTED;
URLType type=(URLType)url->GetAttribute(URL::KType);
if( type != URL_HTTP && type!=URL_HTTPS)
return OpStatus::ERR_NOT_SUPPORTED;
#ifndef RAMCACHE_ONLY
if(url->GetAttribute(URL::KCachePolicy_NoStore))
return OpStatus::ERR_NOT_SUPPORTED;
#endif
#ifdef MULTIMEDIA_CACHE_SUPPORT
// Fails for incomplete Multimedia files
OP_ASSERT(IsExportAllowed());
if(!IsExportAllowed())
return OpStatus::ERR_NOT_SUPPORTED;
#endif
// Embedded files are kept in RAM
if(!allow_embedded_and_containers && IsEmbedded())
return OpStatus::ERR_NOT_SUPPORTED;
// Container files are not readable
if(!allow_embedded_and_containers && GetContainerID()>0)
return OpStatus::ERR_NOT_SUPPORTED;
//OpFileFolder folder;
//OpStringC cache_file=FileName(folder);
//// If the file name is not yet available, a part of the saving will be synchronous
//if(!allow_embedded_and_containers && cache_file.IsEmpty())
//return OpStatus::ERR_NOT_SUPPORTED;
return OpStatus::OK;
}
OpFile *Cache_Storage::OpenCacheFileForExportAsReadOnly(OP_STATUS &ops)
{
OpFile *file=NULL;
// Storage object without name are not supposed to be saved with this function
OpFileFolder folder;
OpStringC name=FileName(folder);
if(!name.HasContent())
ops=OpStatus::ERR_NOT_SUPPORTED;
else
{
// Open the file as read only
file=OP_NEW(OpFile, ());
if(!file)
ops=OpStatus::ERR_NO_MEMORY;
else if(OpStatus::IsSuccess(ops=file->Construct(name, folder)))
ops=file->Open(OPFILE_READ);
if(OpStatus::IsError(ops))
{
OP_DELETE(file);
file=NULL;
}
}
return file;
}
OP_STATUS Cache_Storage::ExportAsFile(const OpStringC &file_name)
{
OP_STATUS ops=OpStatus::OK;
OpFileDescriptor *desc=NULL;
RETURN_IF_ERROR(CheckExportAsFile(TRUE)); // Allow embedded files and containers
// Check if the Context Manager bypass the save
if(GetContextManager()->BypassStorageSave(this, file_name, ops))
return ops;
desc=AccessReadOnly(ops);
// Copy of the file
OpFile file;
if( OpStatus::IsSuccess(ops) &&
OpStatus::IsSuccess(ops=file.Construct(file_name)) &&
desc &&
OpStatus::IsSuccess(ops=file.Open(OPFILE_WRITE)))
{
UINT8 buf[STREAM_BUF_SIZE]; // ARRAY OK 2010-08-09 lucav
OpFileLength bytes_read=0;
OpFileLength total_bytes=0;
while( OpStatus::IsSuccess(ops) &&
OpStatus::IsSuccess(ops=desc->Read(buf, STREAM_BUF_SIZE, &bytes_read)) &&
bytes_read>0)
{
ops=file.Write(buf, bytes_read);
if(bytes_read>0 && bytes_read!=FILE_LENGTH_NONE)
total_bytes+=bytes_read;
}
#ifdef SELFTEST
OpFileLength len=0;
desc->GetFileLength(len);
OP_ASSERT(total_bytes==len);
#endif
desc->Close();
}
#if (CACHE_SMALL_FILES_SIZE>0 || CACHE_CONTAINERS_ENTRIES>0)
if(embedded)
cache_content.SetNeedDirectAccess(FALSE);
#endif
OP_DELETE(desc);
return ops;
}
#ifdef PI_ASYNC_FILE_OP
OP_STATUS Cache_Storage::ExportAsFileAsync(const OpStringC &file_name, AsyncExporterListener *listener, UINT32 param, BOOL delete_if_error, BOOL safe_fall_back)
{
OP_ASSERT(listener);
if(!listener)
return OpStatus::ERR_NULL_POINTER;
OP_STATUS ops=CheckExportAsFile(FALSE); // Embedded files and container need to be managed in the "safe" way
BOOL safe=FALSE;
if(OpStatus::IsError(ops))
{
if(!safe_fall_back)
return ops;
else
safe=TRUE;
}
CacheAsyncExporter *exporter=OP_NEW(CacheAsyncExporter, (listener, url, safe, delete_if_error, param));
RETURN_OOM_IF_NULL(exporter);
// The object will delete itself when appropriate
ops=exporter->StartExport(file_name);
if(OpStatus::IsError(ops))
OP_DELETE(exporter);
return ops;
}
#endif // PI_ASYNC_FILE_OP
OpFileDescriptor *Cache_Storage::OpenFile(OpFileOpenMode mode, OP_STATUS &op_err, int flags)
{
__DO_START_TIMING(TIMING_FILE_OPERATION);
OpFileFolder folder1 = OPFILE_ABSOLUTE_FOLDER;
OpStringC name(FileName(folder1,FALSE));
OpAutoPtr<OpFileDescriptor> fil( CreateAndOpenFile(name, folder1, mode, op_err, flags) );
__DO_STOP_TIMING(TIMING_FILE_OPERATION);
if(OpStatus::IsError(op_err))
{
OP_NEW_DBG("Cache_Storage::OpenFile()", "cache.storage");
OP_DBG((UNI_L("Cannot open file %s\n"), name.CStr()));
url->HandleError(GetFileError(op_err, url,UNI_L("open")));
return NULL;
}
return fil.release();
}
#if !defined NO_SAVE_SUPPORT || !defined RAMCACHE_ONLY
DataStream_GenericFile *Cache_Storage::OpenDataFile(const OpStringC &name, OpFileFolder folder,OpFileOpenMode mode, OP_STATUS &op_err, OpFileLength start_position, int flags)
{
OpFileFolder folder1 = folder;
OpStringC name1(name.HasContent() ? name : FileName(folder1, ((mode & OPFILE_WRITE) != 0 ? FALSE: TRUE)));
OpAutoPtr<OpFileDescriptor> fil0( CreateAndOpenFile(name1, folder1, mode, op_err, flags) );
__DO_STOP_TIMING(TIMING_FILE_OPERATION);
OpAutoPtr<DataStream_GenericFile> fil(NULL);
if(OpStatus::IsSuccess(op_err))
{
if(start_position != FILE_LENGTH_NONE)
SetWritePosition(fil0.get(), start_position);
fil.reset(OP_NEW(DataStream_GenericFile, (fil0.get(), ((mode & OPFILE_READ) != 0 ? FALSE : TRUE))));
if(fil.get() != NULL)
{
fil0.release();
TRAP(op_err, fil->InitL());
}
else
op_err = OpStatus::ERR_NO_MEMORY;
}
if(OpStatus::IsError(op_err))
{
url->HandleError(GetFileError(op_err, url,UNI_L("open")));
return NULL;
}
return fil.release();
}
#endif
#if !defined NO_SAVE_SUPPORT || !defined RAMCACHE_ONLY
OP_STATUS Cache_Storage::CopyCacheFile(const OpStringC &source_name, OpFileFolder source_folder,
const OpStringC &target_name, OpFileFolder target_folder,
BOOL source_is_memory, BOOL target_is_memory, OpFileLength start_position)
{
/*#if CACHE_SMALL_FILES_SIZE>0
OP_ASSERT( (source_is_memory && cache_content.GetLength()==content_size) ||
(source_is_memory && cache_content.GetLength()==content_size)
);
if(source_is_memory && cache_content.GetLength()<=CACHE_SMALL_FILES_SIZE)
target_is_memory=TRUE;
#endif*/
if(!!source_is_memory == !!target_is_memory && source_name.Compare(target_name) == 0)
// Source == target
return OpStatus::OK;
DataStream * OP_MEMORY_VAR source;
OpAutoPtr<DataStream_GenericFile> source_file(NULL);
OP_STATUS op_err = OpStatus::OK;
if(source_name.HasContent() || !source_is_memory)
{
source_file.reset(OpenDataFile(source_name, source_folder, OPFILE_READ, op_err));
RETURN_IF_ERROR(op_err);
source = source_file.get();
}
else
{
cache_content.ResetRead();
source = &cache_content;
}
BOOL target_has_content;
/*#if CACHE_SMALL_FILES_SIZE>0
if(content_size>0 && content_size<=CACHE_SMALL_FILES_SIZE)
{
target_is_memory=TRUE;
target_has_content=FALSE;
}
else
#endif*/
target_has_content=target_name.HasContent();
DataStream * OP_MEMORY_VAR target;
OpAutoPtr<DataStream_GenericFile> target_file(NULL);
if(target_has_content || !target_is_memory)
{
target_file.reset(OpenDataFile(target_name, target_folder, OPFILE_WRITE, op_err, start_position));
RETURN_IF_ERROR(op_err);
target = target_file.get();
}
else
{
cache_content.ResetRecord();
target = &cache_content;
}
// target can be zero in OOM conditions!
if(!target)
return OpStatus::ERR_NO_MEMORY;
#ifdef SELFTEST
if(urlManager->emulateOutOfDisk != 0)
return OpStatus::ERR_NO_DISK;
#endif //SELFTEST
TRAP(op_err, source->ExportDataL(target));
RETURN_IF_ERROR(op_err);
#ifdef DATASTREAM_ENABLE_FILE_OPENED
// If the file for some reason was closed, it indicates an error.
if(!target_file.get()->Opened())
op_err = OpStatus::ERR;
#endif
//TRAP(op_err, target->AddContentL(source));
return op_err;
}
#endif // !defined NO_SAVE_SUPPORT || !defined RAMCACHE_ONLY
unsigned long Cache_Storage::SaveToFile(const OpStringC &filename)
{
OP_STATUS ops;
if(GetContextManager()->BypassStorageSave(this, filename, ops))
return ops;
//#if CACHE_SMALL_FILES_SIZE>0
// OP_ASSERT(!ManageEmbedding());
//#endif
#if defined NO_SAVE_SUPPORT && !defined DISK_CACHE_SUPPORT
OP_STATUS op_err = OpStatus::ERR_NOT_SUPPORTED;
#else
OpFileFolder folder1 = OPFILE_ABSOLUTE_FOLDER;
OpStringC empty;
OpStringC src_name(filename.HasContent() ? FileName(folder1) : empty);
__DO_START_TIMING(TIMING_FILE_OPERATION);
OP_STATUS op_err = CopyCacheFile(src_name, folder1, filename, OPFILE_ABSOLUTE_FOLDER, src_name.IsEmpty(), FALSE, save_position);
__DO_STOP_TIMING(TIMING_FILE_OPERATION);
#endif
if(OpStatus::IsError(op_err))
{
unsigned long err = url->HandleError(GetFileError(op_err, url,UNI_L("write")));
if(OpStatus::IsMemoryError(op_err))
g_memory_manager->RaiseCondition(op_err);
return err;
}
__DO_ADD_TIMING_PROCESSED(TIMING_FILE_OPERATION,cache_content.GetLength());
return 0;
}
void Cache_Storage::ResetForLoading()
{
OP_NEW_DBG("Cache_Storage::ResetForLoading", "cache.limit");
OP_DBG((UNI_L("URL: %s - %x - content_size: %d - cache_content: %d - ctx id: %d - read_only: %d\n"), url->GetAttribute(URL::KUniName).CStr(), url, (UINT32) content_size, cache_content.GetLength(), url->GetContextId(), read_only));
SubFromCacheUsage(url, IsRAMContentComplete(), IsDiskContentAvailable() && HasContentBeenSavedToDisk());
#ifdef SELFTEST
GetContextManager()->VerifyURLSizeNotCounted(url, IsRAMContentComplete(), IsDiskContentAvailable() && HasContentBeenSavedToDisk());
#endif // SELFTEST
cache_content.ResetRecord();
content_size = 0;
read_only = FALSE;
}
BOOL Cache_Storage::FlushMemory(BOOL force)
{
OP_NEW_DBG("Cache_Storage::FlushMemory", "cache.limit");
OP_DBG((UNI_L("URL: %s - %x - content_size: %d - cache_content: %d - ctx id: %d - read_only: %d\n"), url->GetAttribute(URL::KUniName).CStr(), url, (UINT32) content_size, cache_content.GetLength(), url->GetContextId(), read_only));
if(!force && Cardinal())
return FALSE;
#ifdef SELFTEST
if(!read_only)
GetContextManager()->VerifyURLSizeNotCounted(url, TRUE, FALSE);
#endif // SELFTEST
if(read_only)
{
SubFromCacheUsage(url, TRUE, FALSE);
read_only = FALSE;
}
cache_content.ResetRecord();
return TRUE;
}
OP_STATUS Cache_Storage::FilePathName(OpString &name, BOOL get_original_body) const
{
OpFileFolder folder1 = OPFILE_ABSOLUTE_FOLDER;
OpStringC fname(FileName(folder1, get_original_body));
if(folder1 == OPFILE_ABSOLUTE_FOLDER)
return name.Set(fname.CStr());
name.Empty();
OpFile fil;
RETURN_IF_ERROR(fil.Construct(fname.CStr(), folder1));
return name.Set(fil.GetFullPath());
}
void Cache_Storage::DecFileCount()
{
}
void Cache_Storage::SetMemoryOnlyStorage(BOOL flag)
{
}
BOOL Cache_Storage::GetMemoryOnlyStorage()
{
return FALSE;
}
BOOL Cache_Storage::IsPersistent()
{
#if defined __OEM_EXTENDED_CACHE_MANAGEMENT && defined __OEM_OPERATOR_CACHE_MANAGEMENT
// never-flush files are always persistent
if(never_flush)
return TRUE;
#endif
// Failed/aborted loads are not persistent
URLStatus stat = (URLStatus) url->GetAttribute(URL::KLoadStatus);
if(stat != URL_LOADED && stat != URL_LOADING && stat != URL_UNLOADED)
return FALSE;
// Only used by cache files. True if it is to be preserved for the next session; DEFAULT TRUE
switch((URLContentType) url->GetAttribute(URL::KContentType))
{
// Document cache
case URL_HTML_CONTENT:
case URL_XML_CONTENT:
case URL_TEXT_CONTENT:
return g_pcnet->GetIntegerPref(PrefsCollectionNetwork::CacheDocs);
// Image cache
case URL_GIF_CONTENT:
case URL_JPG_CONTENT:
case URL_XBM_CONTENT:
case URL_BMP_CONTENT:
case URL_WEBP_CONTENT:
case URL_CPR_CONTENT:
#ifdef _PNG_SUPPORT_
case URL_PNG_CONTENT:
#endif
#ifdef HAS_ATVEF_SUPPORT
case URL_TV_CONTENT: // This is an "image" also.
#endif /* HAS_ATVEF_SUPPORT */
#ifdef _WML_SUPPORT_
case URL_WBMP_CONTENT:
#endif
return g_pcnet->GetIntegerPref(PrefsCollectionNetwork::CacheFigs);
default:
break;
}
// Other cache
return g_pcnet->GetIntegerPref(PrefsCollectionNetwork::CacheOther);
}
#ifdef CACHE_ENABLE_LOCAL_ZIP
OP_STATUS Cache_Storage::ConfigureEncode()
{
if(encode_storage)
return OpStatus::OK;
encode_storage = OP_NEW(InternalEncoder, (DataStream_Deflate));
if(encode_storage == NULL)
return OpStatus::OK; // encoder is not critical (at this time; it may be for a future encryption mode)
if( OpStatus::IsError(encode_storage->Construct()) ||
OpStatus::IsError(content_encoding.Set("deflate"))
)
{
OP_DELETE(encode_storage);
encode_storage = NULL;
return OpStatus::OK; // encoder is not critical (at this time; it may be for a future encryption mode)
}
return OpStatus::OK;
}
Cache_Storage::InternalEncoder::InternalEncoder(DataStream_Compress_alg alg)
: compression_fifo(), compressor(alg, TRUE, &compression_fifo, FALSE)
{
}
OP_STATUS Cache_Storage::InternalEncoder::Construct()
{
compression_fifo.SetIsFIFO();
RETURN_IF_LEAVE(compressor.InitL());
return OpStatus::OK;
}
OP_STATUS Cache_Storage::InternalEncoder::StoreData(Cache_Storage *target, const unsigned char *buffer, unsigned long buf_len)
{
OP_ASSERT(target);
OP_ASSERT(buffer);
RETURN_IF_LEAVE(compressor.WriteDataL(buffer, buf_len));
return WriteToStorage(target);
}
OP_STATUS Cache_Storage::InternalEncoder::FinishStorage(Cache_Storage *target)
{
OP_ASSERT(target);
RETURN_IF_LEAVE(compressor.FlushL());
return WriteToStorage(target);
}
OP_STATUS Cache_Storage::InternalEncoder::WriteToStorage(Cache_Storage *target)
{
unsigned long buf_len2 = compression_fifo.GetLength();
if(buf_len2 && target)
{
RETURN_IF_ERROR(target->StoreData(compression_fifo.GetDirectPayload(), buf_len2));
RETURN_IF_LEAVE(compression_fifo.CommitSampledBytesL(buf_len2));
}
return OpStatus::OK;
}
#endif
#ifdef _MIME_SUPPORT_
BOOL Cache_Storage::GetAttachment(int i, URL &url)
{
url = URL();
return FALSE;
}
#endif // _MIME_SUPPORT_
#if CACHE_SMALL_FILES_SIZE>0
OP_STATUS Cache_Storage::RetrieveEmbeddedContent(DiskCacheEntry *entry)
{
// Check and resets
OP_ASSERT(IsEmbedded());
OP_ASSERT(entry);
if(!entry)
return OpStatus::ERR_NULL_POINTER;
OP_ASSERT(entry->GetEmbeddedContentSize()==0);
if(entry->GetEmbeddedContentSizeReserved()==0)
RETURN_IF_ERROR(entry->ReserveSpaceForEmbeddedContent(CACHE_SMALL_FILES_SIZE));
cache_content.ResetRead();
UINT32 OP_MEMORY_VAR len=cache_content.GetLength();
if(!len)
{
entry->SetEmbeddedContentSize(0);
return OpStatus::OK;
}
UINT32 OP_MEMORY_VAR read_len=0;
OP_ASSERT(len<=entry->GetEmbeddedContentSizeReserved());
OP_ASSERT(len<=CACHE_SMALL_FILES_SIZE);
if(len<=entry->GetEmbeddedContentSize())
return OpStatus::ERR;
// Embed the file
RETURN_IF_LEAVE(read_len=cache_content.ReadDataL(entry->GetEmbeddedContent(), len, DataStream::KSampleOnly));
OP_ASSERT(read_len==len);
if(read_len!=len)
return OpStatus::ERR;
entry->SetEmbeddedContentSize(read_len);
OP_ASSERT(entry->GetEmbeddedContentSize()==len);
return OpStatus::OK;
}
OP_STATUS Cache_Storage::StoreEmbeddedContent(DiskCacheEntry *entry)
{
OP_ASSERT(entry && entry->GetEmbeddedContentSize());
OP_ASSERT(!embedded);
embedded=FALSE;
if(!entry)
return OpStatus::ERR_NULL_POINTER;
if(!entry->GetEmbeddedContentSize())
return OpStatus::OK;
OP_ASSERT(!cache_content.GetLength());
RETURN_IF_LEAVE(cache_content.WriteDataL(entry->GetEmbeddedContent(), entry->GetEmbeddedContentSize()));
UINT32 write_len=cache_content.GetLength();
OP_ASSERT(write_len==entry->GetEmbeddedContentSize());
if(write_len!=entry->GetEmbeddedContentSize())
return OpStatus::ERR;
embedded=TRUE;
urlManager->IncEmbeddedSize(write_len);
return OpStatus::OK;
}
#endif
#if CACHE_CONTAINERS_ENTRIES>0
OP_STATUS Cache_Storage::StoreInContainer(CacheContainer *cont, UINT id)
{
// Some check
OP_ASSERT(cont && id);
if(!cont)
return OpStatus::ERR_NULL_POINTER;
if(!id)
return OpStatus::ERR_OUT_OF_RANGE;
int len=cache_content.GetLength();
OP_ASSERT(len);
if(!len)
return OpStatus::ERR_OUT_OF_RANGE;
OP_ASSERT(len<=CACHE_CONTAINERS_FILE_LIMIT);
if(len>CACHE_CONTAINERS_FILE_LIMIT)
return OpStatus::ERR_OUT_OF_RANGE;
// Allocate a pointer and update the container
unsigned char *ptr=OP_NEWA(unsigned char, len);
if(!ptr)
return OpStatus::ERR_NO_MEMORY;
if(!cont->UpdatePointerByID(id, ptr, len))
{
OP_ASSERT(FALSE);
OP_DELETEA(ptr);
return OpStatus::ERR_NO_SUCH_RESOURCE;
}
// Read the cache content
int OP_MEMORY_VAR read_len=0;
cache_content.ResetRead();
RETURN_IF_LEAVE(read_len=cache_content.ReadDataL(ptr, len, DataStream::KSampleOnly));
if(len!=read_len)
return OpStatus::ERR;
OP_ASSERT(CheckContainer());
return OpStatus::OK;
}
#ifdef SELFTEST
BOOL Cache_Storage::CheckContainer()
{
if(checking_container)
return TRUE;
Context_Manager *ctx=GetContextManager();
checking_container=TRUE;
BOOL b = !ctx || ctx->CheckCacheStorage(this);
checking_container=FALSE;
return b;
}
#endif // SELFTEST
#endif // CACHE_CONTAINERS_ENTRIES>0
Context_Manager *Cache_Storage::GetContextManager()
{
Context_Manager *cman = urlManager->FindContextManager(Url()->GetContextId());
OP_ASSERT(cman);
return cman;
}
#ifdef _OPERA_DEBUG_DOC_
void Cache_Storage::GetMemUsed(DebugUrlMemory &debug)
{
debug.memory_loaded += sizeof(*this) + cache_content.GetLength();
/* if(small_content)
{
debug.number_ramcache++;
debug.memory_ramcache += content_size;
}
else if(content)
{
debug.number_ramcache++;
debug.memory_ramcache += content->GetMemSize();
}*/
}
#endif
OP_STATUS Cache_Storage::GetUnsortedCoverage(OpAutoVector<StorageSegment> &out_segments, OpFileLength start, OpFileLength len)
{
OpFileLength size = (content_size > cache_content.GetLength()) ? content_size : cache_content.GetLength();
if(start>size)
return OpStatus::ERR_NO_SUCH_RESOURCE;
if(start==FILE_LENGTH_NONE)
return OpStatus::ERR_OUT_OF_RANGE;
StorageSegment *seg;
RETURN_OOM_IF_NULL(seg=OP_NEW(StorageSegment, ()));
OpFileLength end = (len<size) ? len : size;
seg->content_start = start;
seg->content_length = end-seg->content_start;
OP_STATUS ops=out_segments.Add(seg);
if(OpStatus::IsError(ops))
OP_DELETE(seg);
return ops;
}
OP_STATUS Cache_Storage::GetSortedCoverage(OpAutoVector<StorageSegment> &out_segments, OpFileLength start, OpFileLength len, BOOL merge)
{
// One segment is always sorted...
return GetUnsortedCoverage(out_segments, start, len);
}
void Cache_Storage::GetPartialCoverage(OpFileLength position, BOOL &available, OpFileLength &length, BOOL multiple_segments)
{
OpFileLength loaded=ContentLoaded();
if(position==FILE_LENGTH_NONE || position>=loaded)
{
available=FALSE;
length=0;
}
else
{
available=TRUE;
length=loaded-position;
}
}
#ifdef CACHE_FAST_INDEX
SimpleStreamReader *Cache_Storage::CreateStreamReader()
{
UINT32 size=cache_content.GetLength();
if(size>0) // Stream buffer from datastream
{
cache_content.SetNeedDirectAccess(TRUE);
SimpleBufferReader *reader=OP_NEW(SimpleBufferReader, (cache_content.GetDirectPayload(), size));
cache_content.SetNeedDirectAccess(FALSE);
if(reader)
{
if(OpStatus::IsError(reader->Construct()))
{
OP_DELETE(reader);
reader=NULL;
}
return reader;
}
}
return NULL;
}
#endif
|
#include"cXmlLogger.h"
cXmlLogger::cXmlLogger(float loglvl)
{
loglevel = loglvl;
LogFileName = "";
doc = 0;
}
cXmlLogger::~cXmlLogger()
{
if (doc)
{
doc->Clear();
delete doc;
}
}
bool cXmlLogger::getLog(const char *FileName)
{
std::string value;
TiXmlDocument doc_xml(FileName);
if(!doc_xml.LoadFile())
{
std::cout << "Error opening XML-file in getLog";
return false;
}
value = FileName;
size_t dotPos = value.find_last_of(".");
if(dotPos != std::string::npos)
value.insert(dotPos,CN_LOG);
else
value += CN_LOG;
LogFileName = value;
doc_xml.SaveFile(LogFileName.c_str());
doc = new TiXmlDocument(LogFileName.c_str());
doc->LoadFile();
TiXmlElement *msg;
TiXmlElement *root;
root = doc->FirstChildElement(CNS_TAG_ROOT);
TiXmlElement *log = new TiXmlElement(CNS_TAG_LOG);
root->LinkEndChild(log);
msg = new TiXmlElement(CNS_TAG_MAPFN);
msg->LinkEndChild(new TiXmlText(FileName));
log->LinkEndChild(msg);
msg = new TiXmlElement(CNS_TAG_SUM);
log->LinkEndChild(msg);
TiXmlElement* path = new TiXmlElement(CNS_TAG_PATH);
log->LinkEndChild(path);
{
TiXmlElement *lowlevel = new TiXmlElement(CNS_TAG_LOWLEVEL);
log->LinkEndChild(lowlevel);
}
return true;
}
void cXmlLogger::saveLog()
{
if (loglevel == CN_LOGLVL_NO) return;
doc->SaveFile(LogFileName.c_str());
}
void cXmlLogger::writeToLogSummary(const SearchResult &sresult)
{
TiXmlElement *element=doc->FirstChildElement(CNS_TAG_ROOT);
element = element->FirstChildElement(CNS_TAG_LOG);
element = element->FirstChildElement(CNS_TAG_SUM);
unsigned int maxnodes = 0;
float relPathfound, relAgentSolved = 0;
int k = 0;
int j = 0;
float pathlenght = 0;
unsigned int totalnodes=0;
unsigned int numof_pathfound = 0;
unsigned int num_of_path = 0;
unsigned int num_of_agents_solved = 0;
unsigned int num_of_agents = 0;
unsigned int agent_is_solved = 0;
for(k = 0; k < sresult.agents; k++)
{
agent_is_solved = 0;
num_of_path += 1;
if (sresult.pathInfo[k].pathfound)
{
numof_pathfound += 1;
agent_is_solved = 1;
pathlenght += sresult.pathInfo[k].pathlength;
totalnodes += sresult.pathInfo[k].nodescreated;
}
if (sresult.pathInfo[k].nodescreated > maxnodes)
maxnodes = sresult.pathInfo[k].nodescreated;
num_of_agents += 1;
num_of_agents_solved += agent_is_solved;
}
relPathfound = (float)numof_pathfound / num_of_path;
relAgentSolved = (float)num_of_agents_solved / num_of_agents;
element->SetDoubleAttribute(CNS_TAG_ATTR_AGENTSSOLVED, relAgentSolved);
element->SetAttribute(CNS_TAG_ATTR_MAXNODESCR, maxnodes);
element->SetAttribute(CNS_TAG_ATTR_NODESCREATED, totalnodes);
element->SetDoubleAttribute(CNS_TAG_ATTR_SUMLENGTH, pathlenght);
element->SetDoubleAttribute(CNS_TAG_ATTR_AVGLENGTH, pathlenght/num_of_agents_solved);
element->SetDoubleAttribute(CNS_TAG_ATTR_TIME, sresult.time);
}
void cXmlLogger::writeToLogPath(const SearchResult &sresult)
{
TiXmlElement *element=doc->FirstChildElement(CNS_TAG_ROOT);
element = element->FirstChildElement(CNS_TAG_LOG);
TiXmlElement *agent, *summary, *path, *lplevel, *hplevel, *node;
for(int i = sresult.agents-1; i < sresult.agents; i++)
{
agent = new TiXmlElement(CNS_TAG_AGENT);
agent->SetAttribute(CNS_TAG_ATTR_NUM,i);
element->LinkEndChild(agent);
std::list<Node>::const_iterator iterNode;
summary = new TiXmlElement(CNS_TAG_SUM);
if (sresult.pathInfo[i].pathfound)
summary->SetAttribute(CNS_TAG_ATTR_SOLVED,CNS_TAG_ATTR_TRUE);
else
summary->SetAttribute(CNS_TAG_ATTR_SOLVED,CNS_TAG_ATTR_FALSE);
summary->SetAttribute(CNS_TAG_ATTR_PATHSFOUND, sresult.pathInfo[i].pathfound);
summary->SetAttribute(CNS_TAG_ATTR_MAXNODESCR, sresult.pathInfo[i].nodescreated);
summary->SetDoubleAttribute(CNS_TAG_ATTR_SUMLENGTH, sresult.pathInfo[i].pathlength);
summary->SetDoubleAttribute(CNS_TAG_ATTR_AVGLENGTH, sresult.pathInfo[i].pathlength);
summary->SetDoubleAttribute(CNS_TAG_ATTR_TIME,sresult.pathInfo[i].time);
agent->LinkEndChild(summary);
path = new TiXmlElement(CNS_TAG_PATH);
path->SetAttribute(CNS_TAG_ATTR_NUM,0);
if(sresult.pathInfo[i].pathfound)
{
path->SetAttribute(CNS_TAG_ATTR_PATHFOUND,CNS_TAG_ATTR_TRUE);
path->SetDoubleAttribute(CNS_TAG_ATTR_LENGTH,sresult.pathInfo[i].pathlength);
}
else
{
path->SetAttribute(CNS_TAG_ATTR_PATHFOUND,CNS_TAG_ATTR_FALSE);
path->SetAttribute(CNS_TAG_ATTR_LENGTH,0);
}
path->SetAttribute(CNS_TAG_ATTR_NODESCREATED,sresult.pathInfo[i].nodescreated);
path->SetDoubleAttribute(CNS_TAG_ATTR_TIME,sresult.pathInfo[i].time);
agent->LinkEndChild(path);
if (loglevel >= 1 && sresult.pathInfo[i].pathfound)
{
int k = 0;
hplevel = new TiXmlElement(CNS_TAG_HPLEVEL);
path->LinkEndChild(hplevel);
k = 0;
auto iter = sresult.pathInfo[i].sections.begin();
auto it = sresult.pathInfo[i].sections.begin();
int partnumber=0;
TiXmlElement *part;
part = new TiXmlElement(CNS_TAG_SECTION);
part->SetAttribute(CNS_TAG_ATTR_NUM, partnumber);
part->SetAttribute(CNS_TAG_ATTR_SX, it->j);
part->SetAttribute(CNS_TAG_ATTR_SY, it->i);
part->SetAttribute(CNS_TAG_ATTR_FX, iter->j);
part->SetAttribute(CNS_TAG_ATTR_FY, iter->i);
part->SetDoubleAttribute(CNS_TAG_ATTR_LENGTH, iter->g);
hplevel->LinkEndChild(part);
partnumber++;
while(iter != --sresult.pathInfo[i].sections.end())
{
part = new TiXmlElement(CNS_TAG_SECTION);
part->SetAttribute(CNS_TAG_ATTR_NUM, partnumber);
part->SetAttribute(CNS_TAG_ATTR_SX, it->j);
part->SetAttribute(CNS_TAG_ATTR_SY, it->i);
iter++;
part->SetAttribute(CNS_TAG_ATTR_FX, iter->j);
part->SetAttribute(CNS_TAG_ATTR_FY, iter->i);
part->SetDoubleAttribute(CNS_TAG_ATTR_LENGTH, iter->g - it->g);
hplevel->LinkEndChild(part);
it++;
partnumber++;
}
if (loglevel == CN_LOGLVL_LOW)
{
lplevel = new TiXmlElement(CNS_TAG_LPLEVEL);
path->LinkEndChild(lplevel);
for(iterNode = sresult.pathInfo[i].path.begin();
iterNode != sresult.pathInfo[i].path.end(); iterNode++)
{
node = new TiXmlElement(CNS_TAG_NODE);
node->SetAttribute(CNS_TAG_ATTR_NUM,k);
node->SetAttribute(CNS_TAG_ATTR_X,(*iterNode).j);
node->SetAttribute(CNS_TAG_ATTR_Y,(*iterNode).i);
lplevel->LinkEndChild(node);
k++;
}
}
}
}
}
void cXmlLogger::writeToLogMap(const cMap &map, const SearchResult &sresult)
{
std::string text;
int *curLine;
curLine = new int[map.width];
for(int i = 0; i < map.width; i++)
curLine[i] = 0;
TiXmlElement *element = doc->FirstChildElement(CNS_TAG_ROOT);
element = element->FirstChildElement(CNS_TAG_LOG);
element = element->FirstChildElement(CNS_TAG_PATH);
TiXmlElement* msg;
std::string Value;
std::stringstream stream;
for(int i=0; i<map.height; i++)
{
msg = new TiXmlElement(CNS_TAG_ROW);
msg->SetAttribute(CNS_TAG_ATTR_NUM, i);
text = "";
std::list<Node>::const_iterator iter;
for(int k = 0; k < sresult.agents; k++)
for(iter = sresult.pathInfo[k].path.begin(); iter != sresult.pathInfo[k].path.end(); iter++)
{
if((*iter).i == i)
curLine[(*iter).j] = 1;
}
for(int j = 0; j < map.width; j++)
if(curLine[j] != 1)
{
stream << map.Grid[i][j];
stream >> Value;
stream.clear();
stream.str("");
text = text + Value + " ";
}
else
{ text = text + "*" + " ";
curLine[j] = 0;
}
msg->LinkEndChild(new TiXmlText(text.c_str()));
element->LinkEndChild(msg);
}
delete [] curLine;
}
void cXmlLogger::writeToLogOpenClose(const std::vector<Node> &open, const std::vector<Node>& close)
{
int iterate = 0;
TiXmlElement *element = new TiXmlElement(CNS_TAG_STEP);
TiXmlNode *child = 0, *lowlevel = doc->FirstChild(CNS_TAG_ROOT);
lowlevel = lowlevel -> FirstChild(CNS_TAG_LOG) -> FirstChild(CNS_TAG_LOWLEVEL);
while (child = lowlevel -> IterateChildren(child))
iterate++;
element -> SetAttribute(CNS_TAG_ATTR_NUM, iterate);
lowlevel -> InsertEndChild(*element);
lowlevel = lowlevel -> LastChild();
element = new TiXmlElement (CNS_TAG_OPEN);
lowlevel -> InsertEndChild(*element);
child = lowlevel -> LastChild();
for (auto it = open.begin(); it != open.end(); ++it) {
element = new TiXmlElement(CNS_TAG_NODE);
element -> SetAttribute(CNS_TAG_ATTR_X, it->j);
element -> SetAttribute(CNS_TAG_ATTR_Y, it->i);
element -> SetDoubleAttribute(CNS_TAG_ATTR_F, it->F);
element -> SetDoubleAttribute(CNS_TAG_ATTR_G, it->g);
element -> SetDoubleAttribute("parents", it->parents.size());
//if (it->g > 0) {
// element -> SetAttribute(CNS_TAG_ATTR_PARX, it->Parent->j);
// element -> SetAttribute(CNS_TAG_ATTR_PARY, it->Parent->i);
//}
child -> InsertEndChild(*element);
}
element = new TiXmlElement (CNS_TAG_CLOSE);
lowlevel -> InsertEndChild(*element);
child = lowlevel -> LastChild();
for (auto it = close.begin(); it != close.end(); ++it) {
element = new TiXmlElement(CNS_TAG_NODE);
element -> SetAttribute(CNS_TAG_ATTR_X, it->j);
element -> SetAttribute(CNS_TAG_ATTR_Y, it->i);
element -> SetDoubleAttribute(CNS_TAG_ATTR_F, it->F);
element -> SetDoubleAttribute(CNS_TAG_ATTR_G, it->best_g);
if (it->g > 0) {
element -> SetAttribute(CNS_TAG_ATTR_PARX, it->Parent->j);
element -> SetAttribute(CNS_TAG_ATTR_PARY, it->Parent->i);
}
child -> InsertEndChild(*element);
}
}
|
#include <iostream>
using namespace std;
int mult(int n, int m) {
if (m < 0) {
return -mult(n, -m);
} else if (m == 0) {
return 0;
} else if (m == 1) {
return n;
} else {
return n + mult(n, m - 1);
}
}
int main() {
cout << mult(4, 2) << endl;
cout << mult(4, 0) << endl;
cout << mult(4, -4) << endl;
cout << mult(-5, -4) << endl;
cout << mult(-5, 10) << endl;
}
|
#include <iostream>
using namespace std;
#include "Entry.h"
#include <fstream>
#include "mapVector.h"
#include "dictionary.h"
int main()
{
dictionary d;
d.userInterface();
return 0;
}
|
//Created by: Mark Marsala, Marshall Farris, and Johnathon Franco Sosa
//Date: 5/4/2021
//Reading and writing for an 16 bit mono wav file
#include <string>
#include <fstream>
#include <iostream>
#include "mono16.h"
using namespace std;
Mono16::Mono16(string newFile)
{
fileName = newFile;
}
void Mono16::readFile()
{
std::ifstream file(fileName,std::ios::binary | std::ios::in);
if(file.is_open())
{
file.read((char*)&waveHeader, sizeof(wav_header));
buffer = new short[waveHeader.data_bytes];
file.read(reinterpret_cast<char *>(buffer), waveHeader.data_bytes);
file.close();
cout << "Reading 16 bit mono file" << endl;
}
}
short* Mono16::getBuffer()
{
return buffer;
}
void Mono16::writeFile(const std::string &outFileName)
{
std::ofstream outFile(outFileName, std::ios::out | std::ios::binary);
outFile.write((char*)&waveHeader,sizeof(wav_header));
outFile.write(reinterpret_cast<char*>(buffer), waveHeader.data_bytes);
outFile.close();
cout << "Writing 16 bit mono file" << endl;
}
Mono16::~Mono16()
{
if(buffer != NULL)
{
delete[] buffer;
}
}
int Mono16::getBufferSize() const
{
return waveHeader.data_bytes;
}
|
// Copyright (c) 2018 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <pika/future.hpp>
#include <pika/init.hpp>
#include <pika/testing.hpp>
#include <functional>
#include <string>
#include <vector>
///////////////////////////////////////////////////////////////////////////////
void test_nullary_void()
{
pika::future<void> f1 = pika::make_ready_future();
PIKA_TEST(f1.is_ready());
pika::future<void> f2 = pika::make_ready_future<void>();
PIKA_TEST(f2.is_ready());
}
struct A
{
A() = default;
};
void test_nullary()
{
pika::future<A> f1 = pika::make_ready_future<A>();
PIKA_TEST(f1.is_ready());
}
struct B
{
B(int i)
: i_(i)
{
}
int i_;
};
void test_unary()
{
B lval(42);
pika::future<B> f1 = pika::make_ready_future(B(42));
PIKA_TEST(f1.is_ready());
PIKA_TEST_EQ(f1.get().i_, 42);
pika::future<B> f2 = pika::make_ready_future(lval);
PIKA_TEST(f2.is_ready());
PIKA_TEST_EQ(f2.get().i_, 42);
pika::future<B> f3 = pika::make_ready_future<B>(42);
PIKA_TEST(f3.is_ready());
PIKA_TEST_EQ(f3.get().i_, 42);
pika::future<B&> f4 = pika::make_ready_future(std::ref(lval));
PIKA_TEST(f4.is_ready());
PIKA_TEST_EQ(&f4.get().i_, &lval.i_);
pika::future<B&> f5 = pika::make_ready_future<B&>(lval);
PIKA_TEST(f5.is_ready());
PIKA_TEST_EQ(&f5.get().i_, &lval.i_);
}
struct C
{
C(int i)
: i_(i)
, j_(0)
{
}
C(int i, int j)
: i_(i)
, j_(j)
{
}
C(C const&) = delete;
C(C&& rhs)
: i_(rhs.i_)
, j_(rhs.j_)
{
}
int i_;
int j_;
};
void test_variadic()
{
pika::future<C> f1 = pika::make_ready_future(C(42));
PIKA_TEST(f1.is_ready());
C r1 = f1.get();
PIKA_TEST_EQ(r1.i_, 42);
PIKA_TEST_EQ(r1.j_, 0);
pika::future<C> f2 = pika::make_ready_future<C>(42);
PIKA_TEST(f2.is_ready());
C r2 = f2.get();
PIKA_TEST_EQ(r2.i_, 42);
PIKA_TEST_EQ(r2.j_, 0);
pika::future<C> f3 = pika::make_ready_future(C(42, 43));
PIKA_TEST(f3.is_ready());
C r3 = f3.get();
PIKA_TEST_EQ(r3.i_, 42);
PIKA_TEST_EQ(r3.j_, 43);
pika::future<C> f4 = pika::make_ready_future<C>(42, 43);
PIKA_TEST(f4.is_ready());
C r4 = f4.get();
PIKA_TEST_EQ(r4.i_, 42);
PIKA_TEST_EQ(r4.j_, 43);
}
///////////////////////////////////////////////////////////////////////////////
int pika_main()
{
test_nullary_void();
test_nullary();
test_unary();
test_variadic();
return pika::finalize();
}
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
// We force this test to use several threads by default.
std::vector<std::string> const cfg = {"pika.os_threads=all"};
// Initialize and run pika
pika::init_params init_args;
init_args.cfg = cfg;
PIKA_TEST_EQ(pika::init(pika_main, argc, argv, init_args), 0);
return 0;
}
|
//
// proj07_functions.cpp
//
// Created by Kristjan von Bulow.
// Copyright © 2018 Kristjan von Bulow. All rights reserved.
//
#include<string>
using std::string;
using std::getline;
using std::stod;
using std::to_string;
#include<vector>
using std::vector;
#include<map>
using std::map;
#include<fstream>
using std::ifstream;
#include<utility>
using std::pair;
using std::make_pair;
#include <iostream>
#include <math.h>
using std::ostream;
using std::endl;
using std::cout;
using std::fixed;
#include <sstream>
using std::stringstream;
using std::ostringstream;
#include <algorithm>
using std::sort;
using std::transform;
using std::copy;
using std::back_inserter;
#include <iomanip>
using std::setprecision;
#include <iterator>
using std::ostream_iterator;
#include "proj07_functions.h"
/*
Input string s, char delim
Outputs vector<string>
Will split string into vector according to delim
*/
vector<string> split(const string &s, char delim){
vector<string> result_v;
string temp;
stringstream sstream;
sstream.str(s);
while (getline(sstream,temp,delim)){ // this splits from delim
result_v.push_back(temp);
}
return result_v;
}
/*
Takes input stream and converts into map
*/
void read_data(map<vector<double>, string> &m, unsigned int feature_count, ifstream &inf){
string temp_s;
string temp_last_s;
vector<string> string_v;
vector<double> temp_d;
char delim = ',';
while (getline(inf,temp_s)){
string_v = split(temp_s,delim); // uses function to convert string to vector<string>
temp_last_s = string_v.back(); // saves last element to temp string
string_v.pop_back(); // removes last element
transform(string_v.begin(), string_v.end(),back_inserter(temp_d), // lambda function converts string to double
[](const string& iter){
return stod(iter);
});
m.insert(make_pair(temp_d,temp_last_s)); // inserts pair into map
temp_d.clear();
temp_last_s.clear();
}
}
/*
Takes a pair and converts it to string
*/
string pair_to_string(const pair<vector<double>, string> &p){
ostringstream oss; // declares ostringstream
oss << fixed << setprecision(3); // for precision
copy(p.first.begin(), p.first.end(), ostream_iterator<double>(oss, " "));
oss << p.second;
return oss.str(); // returns ostringstream as string
}
/*
Takes a map and prints according to ostream
*/
void print_map(const map<vector<double>, string> &m,ostream &out){
transform(m.begin(),m.end(),ostream_iterator<string>(out, "\n"), pair_to_string); // uses transform function to print according to &
}
/*
Uses the Euclidean distance in order to figure out distance between two vectors
*/
double distance(const vector<double> &v1, const vector<double> &v2, unsigned int feature_count){
double answer;
double temp;
int j = v1.size();
for(int i = 0; i < j; ++i){ // part of Euclidean distance formula
double temp_2 = v2[i] - v1[i];
temp = pow(temp_2, 2);
answer += temp;
}
answer = sqrt(answer);
return answer; // Returns distance
}
/*
This will determine the closest k neighbors to test vector<double>
*/
map<vector<double>, string> k_neighbors(const map<vector<double>, string> &m, const vector<double> &test, int k){
map<vector<double>,string> map_answer;
map<double,vector<double>> new_map_key;
vector<double> temp_v;
vector<double> temp_v_final;
for(auto iter = m.cbegin(); iter != m.cend(); ++iter){ //goes through map
double distance_final = distance(test,iter->first,0); // determines distance between test vector and vector of iteration
new_map_key[distance_final] = iter->first; // makes new map to use distance as keys, helps for later on
if (distance_final > 0.000002){ // makes sure test isn't referenced
temp_v.push_back(distance_final);
}
}
sort(temp_v.begin(), temp_v.end()); // sorts according to lowest value of distance
for (int i = 0; i < k; i++){
vector<double> temp_double;
string temp_string;
temp_double = new_map_key.find(temp_v[i])->second; // uses distance as key in new map to find original vector<double>
temp_string = m.find(temp_double)->second; // uses original vector<double> as key to find string associated
map_answer[temp_double] = temp_string; // new map with only k-nearest neighbors
}
return map_answer; // returns new map
}
/*
This will take one pair and use k_neighbor function to get closet neighbors. Will check how close function worked from 0.0 to 1.0. Return answer as double
*/
double test_one(const map<vector<double>, string> &m, pair<vector<double>, string> test, int k){
double answer = 0.0;
double answer_int = 0.0;
double counter = 0.0;
map<vector<double>, string> comparison_map = k_neighbors(m,test.first,k);
for(auto iter = comparison_map.cbegin(); iter != comparison_map.cend(); ++iter){ // iterates throughout new map to compare with test
if (iter->second == test.second){ // if the strings from key are equal, they are equal
answer_int += 1.0;
}
counter += 1.0;
}
answer = answer_int/counter; // this will find the double of how accurate the function was
return answer;
}
/*
This goes through the whole map and uses each iteration as a pair for test_one function. This will test whole map for accuracy. Each double from test_one will return and be added up to calculate total accuracy.
*/
double test_all(const map<vector<double>, string> &m, int k){
double input;
double count = 0.0;
for(auto iter = m.cbegin(); iter != m.cend(); ++iter){ // iterates through map
input += test_one(m,*iter,k); // takes pair of *iter and compares with rest of map
count += 1.0;
}
input = input/count; // compares total accuracy with each test to count
return input; // returns total accuracy
}
|
/*
* angleblocker.h
* deflektor-ds
*
* Created by Hugh Cole-Baker on 1/18/09.
* Blocks the beam unless it enters at a certain angle.
*
*/
#ifndef deflektor_angleblocker_h
#define deflektor_angleblocker_h
#include "spinblocker.h"
class AngleBlocker : public SpinBlocker
{
protected:
bool destroyed;
public:
AngleBlocker(int bg, int x, int y, unsigned int palIdx, unsigned int tile, BeamDirection setAngle);
virtual void drawUpdate();
virtual BeamResult beamEnters(unsigned int x, unsigned int y, BeamDirection atAngle);
virtual void destroy();
};
#endif
|
/*
Name : Aman Jain
Date : 05-07-2020
Question-> Top down approach Fibonacci
Time complexity : O(n)
Space Complexity : O(n) (Memoization)
*/
#include<bits/stdc++.h>
using namespace std;
int fibonacci(int n, int dp[]){
if(n<2)
return n;
if(dp[n]!=0)
return dp[n];
int ans= fibonacci(n-1,dp)+fibonacci(n-2,dp);
return dp[n]=ans;
}
int main(){
int n;
cin>>n;
int dp[100]={0};
cout<<fibonacci(n,dp)<<endl;
}
|
#include "SceneHandler.h"
#include "DebugScene.h"
SceneHandler::SceneHandler(WindowRef window)
{
setWindow(window);
start();
}
void SceneHandler::setWindow(WindowRef window) {
this->window = window;
}
void SceneHandler::start() {
currentState = START_SCENE;
switchScene();
}
void SceneHandler::switchScene()
{
delete RunningScene;
switch (currentState) {
case Scene::DEBUG:
RunningScene = new DebugScene(window);
break;
case Scene::TITLE:
break;
case Scene::LEVEL:
break;
case Scene::CREDITS:
break;
default:
break;
}
}
void SceneHandler::tick() {
currentState = RunningScene->tick();
switch (currentState) {
case Scene::CURRENT:
return;
case Scene::STOP:
isRunning = false;
return;
default:
switchScene();
}
}
int SceneHandler::getStatus() const
{
return isRunning;
}
|
#pragma once
using namespace Ogre;
static void HK_CALL errorReport(const char* msg, void* userArgGivenToInit);
class CPhysicsManager : public Singleton<CPhysicsManager>
{
public:
CPhysicsManager();
~CPhysicsManager();
void Create();
void Destroy();
void Update();
void SetHeightfieldData();
hkpWorld* GetPhysicsWorld() const;
static CPhysicsManager& getSingleton(void);
static CPhysicsManager* getSingletonPtr(void);
hkMallocAllocator mallocBase;
hkJobThreadPool* threadPool;
hkJobQueue* jobQueue;
hkpWorld* physicsWorld;
hkArray<hkProcessContext*> contexts;
hkpPhysicsContext* context;
hkVisualDebugger* vdb;
private:
hkUint16* m_heightData;
unsigned long last_time;
hkReal timestep;
};
|
/**
* Copyright (c) 2020, Timothy Stack
*
* 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 Timothy Stack 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "top_status_source.hh"
#include "config.h"
#include "lnav.hh"
#include "md2attr_line.hh"
#include "md4cpp.hh"
#include "shlex.hh"
#include "sqlitepp.client.hh"
#include "top_status_source.cfg.hh"
static const char* MSG_QUERY = R"(
SELECT message FROM lnav_user_notifications
WHERE message IS NOT NULL AND
(expiration IS NULL OR expiration > datetime('now')) AND
(views IS NULL OR
json_contains(views, (SELECT name FROM lnav_top_view)))
ORDER BY priority DESC
LIMIT 1
)";
top_status_source::top_status_source(auto_sqlite3& db,
const top_status_source_cfg& cfg)
: tss_config(cfg),
tss_user_msgs_stmt(prepare_stmt(db.in(), MSG_QUERY).unwrap())
{
this->tss_fields[TSF_TIME].set_width(28);
this->tss_fields[TSF_TIME].set_role(role_t::VCR_STATUS_INFO);
this->tss_fields[TSF_USER_MSG].set_share(1);
this->tss_fields[TSF_USER_MSG].right_justify(true);
this->tss_fields[TSF_USER_MSG].set_role(role_t::VCR_STATUS_INFO);
}
void
top_status_source::update_time(const timeval& current_time)
{
auto& sf = this->tss_fields[TSF_TIME];
char buffer[32];
tm current_tm;
buffer[0] = ' ';
strftime(&buffer[1],
sizeof(buffer) - 1,
this->tss_config.tssc_clock_format.c_str(),
localtime_r(¤t_time.tv_sec, ¤t_tm));
sf.set_value(buffer);
}
void
top_status_source::update_time()
{
struct timeval tv;
gettimeofday(&tv, nullptr);
this->update_time(tv);
}
void
top_status_source::update_user_msg()
{
auto& al = this->tss_fields[TSF_USER_MSG].get_value();
al.clear();
this->tss_user_msgs_stmt.reset();
auto fetch_res = this->tss_user_msgs_stmt.fetch_row<std::string>();
fetch_res.match(
[&al](const std::string& value) {
shlex lexer(value);
std::string user_note;
lexer.with_ignore_quotes(true).eval(
user_note,
scoped_resolver{&lnav_data.ld_exec_context.ec_global_vars});
md2attr_line mdal;
auto parse_res = md4cpp::parse(user_note, mdal);
if (parse_res.isOk()) {
al = parse_res.unwrap();
} else {
log_error("failed to parse user note as markdown: %s",
parse_res.unwrapErr().c_str());
al = user_note;
}
scrub_ansi_string(al.get_string(), &al.get_attrs());
al.append(" ");
},
[](const prepared_stmt::end_of_rows&) {},
[](const prepared_stmt::fetch_error& fe) {
log_error("failed to execute user-message expression: %s",
fe.fe_msg.c_str());
});
}
|
/*
* Copyright (c) 2016-2020 Morwenn
* SPDX-License-Identifier: MIT
*/
#ifndef CPPSORT_DETAIL_STABLE_ADAPTER_SELF_SORT_ADAPTER_H_
#define CPPSORT_DETAIL_STABLE_ADAPTER_SELF_SORT_ADAPTER_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <forward_list>
#include <list>
#include <type_traits>
#include <utility>
#include <cpp-sort/sorter_facade.h>
#include <cpp-sort/sorter_traits.h>
#include <cpp-sort/utility/adapter_storage.h>
#include <cpp-sort/utility/as_function.h>
#include "checkers.h"
namespace cppsort
{
template<typename Sorter>
struct stable_adapter<self_sort_adapter<Sorter>>:
utility::adapter_storage<stable_t<Sorter>>,
detail::check_iterator_category<Sorter>,
detail::sorter_facade_fptr<
stable_adapter<self_sort_adapter<Sorter>>,
std::is_empty<Sorter>::value
>
{
////////////////////////////////////////////////////////////
// Construction
stable_adapter() = default;
constexpr explicit stable_adapter(self_sort_adapter<Sorter> sorter):
utility::adapter_storage<stable_t<Sorter>>(
stable_t<Sorter>(std::move(sorter.get()))
)
{}
////////////////////////////////////////////////////////////
// Generic cases
template<typename Iterable, typename... Args>
auto operator()(Iterable&& iterable, Args&&... args) const
-> std::enable_if_t<
detail::has_stable_sort_method<Iterable, Args...>,
decltype(std::forward<Iterable>(iterable).stable_sort(utility::as_function(args)...))
>
{
return std::forward<Iterable>(iterable).stable_sort(utility::as_function(args)...);
}
template<typename Iterable, typename... Args>
auto operator()(Iterable&& iterable, Args&&... args) const
-> std::enable_if_t<
not detail::has_stable_sort_method<Iterable, Args...>,
decltype(this->get()(std::forward<Iterable>(iterable), std::forward<Args>(args)...))
>
{
return this->get()(std::forward<Iterable>(iterable), std::forward<Args>(args)...);
}
template<typename Iterator, typename... Args>
auto operator()(Iterator first, Iterator last, Args&&... args) const
-> decltype(this->get()(first, last, std::forward<Args>(args)...))
{
return this->get()(first, last, std::forward<Args>(args)...);
}
////////////////////////////////////////////////////////////
// Special cases for standard library lists whose sort
// method implements a stable sort
template<typename T>
auto operator()(std::forward_list<T>& iterable) const
-> void
{
iterable.sort();
}
template<
typename T,
typename Compare,
typename = std::enable_if_t<not is_projection_v<Compare, std::forward_list<T>&>>
>
auto operator()(std::forward_list<T>& iterable, Compare compare) const
-> void
{
iterable.sort(utility::as_function(compare));
}
template<typename T>
auto operator()(std::list<T>& iterable) const
-> void
{
iterable.sort();
}
template<
typename T,
typename Compare,
typename = std::enable_if_t<not is_projection_v<Compare, std::list<T>&>>
>
auto operator()(std::list<T>& iterable, Compare compare) const
-> void
{
iterable.sort(utility::as_function(compare));
}
////////////////////////////////////////////////////////////
// Sorter traits
using is_always_stable = std::true_type;
using type = stable_adapter<self_sort_adapter<Sorter>>;
};
}
#endif // CPPSORT_DETAIL_STABLE_ADAPTER_SELF_SORT_ADAPTER_H_
|
#include<iostream>
#include<cstdio>
#define MAX 70
#define getint(n) scanf("%d",&n)
#define putint(n) printf("%d\n",n)
#define ll long long int
using namespace std;
ll dp[MAX][MAX];
void preprocess() {
dp[0][0] = 1;
for(int i = 0 ; i < MAX; i++) {
for(int j=0 ; j < MAX ; j++) {
if( i == 0 && j == 0)
continue;
if( i-1 < 0 )
dp[i][j] = dp[i][j-1];
else if( j-1 < 0)
dp[i][j] = dp[i-1][j];
else
dp[i][j] = dp[i][j-1] + dp[i-1][j];
}
}
}
int main() {
preprocess();
int t,n,m,k,val,mini,maxi,v1,v2,v3;
getint(t);
while(t--) {
getint(n);
getint(m);
getint(k);
if(n==1 || m==1 || k==1) val = k;
else {
mini = min(dp[n-2][m-1], dp[n-1][m-2]);
maxi = max(dp[n-2][m-1], dp[n-1][m-2]);
v1 = k/(mini + maxi);
v2 = k%(mini + maxi);
val = maxi * v1;
if(v2 < 2*mini)
val += v2/2;
else
val += (v2 - mini);
}
putint(val);
}
return 0;
}
|
/**
* @file test/test_sdp.cc
* @brief
* @version 0.1
* @date 2021-01-14
*
* @copyright Copyright (c) 2021 Tencent. All rights reserved.
*
*/
#include <iostream>
#include "mini_sdp.h"
using namespace std;
using namespace mini_sdp;
string origin_sdp =
"v=0\r\no=- 1 0 IN IP4 127.0.0.1\r\n"
"s=webrtc_core\r\nt=0 0\r\na=group:BUNDLE 0 1\r\n"
"a=msid-semantic: WMS 0_xxxx_d71956d9cc93e4a467b11e06fdaf039a\r\nm=audio 1 "
"UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=rtcp:1 IN IP4 "
"0.0.0.0\r\na=candidate:foundation 1 udp 100 127.0.0.1 8000 typ srflx "
"raddr 127.0.0.1 rport 8000 generation "
"0\r\na=ice-ufrag:0_xxxx_d71956d9cc93e4a467b11e06fdaf039a_"
"de71a64097d807c3\r\na=ice-pwd:be8577c0a03b0d3ffa4e5235\r\na=fingerprint:"
"sha-256 "
"8A:BD:A6:61:75:AF:31:4C:02:81:2A:FA:12:92:4C:48:7B:9F:23:DD:BF:3D:51:30:"
"E7:59:5C:9B:17:3D:92:34\r\na=setup:passive\r\na=sendrecv\r\na=extmap:9 "
"http://www.webrtc.org/experiments/rtp-hdrext/"
"decoding-timestamp\r\na=extmap:10 "
"uri:webrtc:rtc:rtp-hdrext:video:CompositionTime\r\na=extmap:21 "
"http://www.webrtc.org/experiments/rtp-hdrext/meta-data-01\r\na=extmap:22 "
"http://www.webrtc.org/experiments/rtp-hdrext/meta-data-02\r\na=extmap:23 "
"http://www.webrtc.org/experiments/rtp-hdrext/meta-data-03\r\na=extmap:2 "
"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=extmap:3 "
"http://www.ietf.org/id/"
"draft-holmer-rmcat-transport-wide-cc-extensions-01\r\na=mid:0\r\na=rtcp-"
"mux\r\na=rtpmap:111 MP4A-ADTS/48000/2\r\na=rtcp-fb:111 nack\r\na=rtcp-fb:111 "
"transport-cc\r\na=fmtp:111 "
"minptime=10;stereo=1;useinbandfec=1;PS-enabled=1;SBR-enabled=1;object=5;cpresent=0;config=4002420adca1fe0\r\n"
"a=rtpmap:124 flexfec-03/48000/2\r\n"
"a=rtpmap:125 flexfec-03/44100/2\r\n"
"a=ssrc-group:FEC-FR 27172315 50331648\r\n"
"a=ssrc:27172315 "
"cname:webrtccore\r\na=ssrc:27172315 "
"msid:0_xxxx_d71956d9cc93e4a467b11e06fdaf039a opus\r\na=ssrc:27172315 "
"mslabel:0_xxxx_d71956d9cc93e4a467b11e06fdaf039a\r\na=ssrc:27172315 "
"label:opus\r\n"
"a=ssrc:50331648 cname:webrtccore\r\n"
"a=ssrc:50331648 msid:0_xxxx_d71956d9cc93e4a467b11e06fdaf039a opus\r\n"
"a=ssrc:50331648 mslabel:0_xxxx_d71956d9cc93e4a467b11e06fdaf039a\r\n"
"a=ssrc:50331648 label:opus\r\n"
"m=video 1 UDP/TLS/RTP/SAVPF 102 108 123 124 125 127\r\nc=IN "
"IP4 0.0.0.0\r\na=rtcp:1 IN IP4 0.0.0.0\r\na=candidate:foundation 1 udp "
"100 127.0.0.1 8000 typ srflx raddr 127.0.0.1 rport 8000 "
"generation "
"0\r\na=ice-ufrag:0_xxxx_d71956d9cc93e4a467b11e06fdaf039a_"
"de71a64097d807c3\r\na=ice-pwd:be8577c0a03b0d3ffa4e5235\r\na=extmap:9 "
"http://www.webrtc.org/experiments/rtp-hdrext/"
"decoding-timestamp\r\na=extmap:10 "
"http://www.webrtc.org/experiments/rtp-hdrext/"
"video-composition-time\r\na=extmap:21 "
"http://www.webrtc.org/experiments/rtp-hdrext/meta-data-01\r\na=extmap:22 "
"http://www.webrtc.org/experiments/rtp-hdrext/meta-data-02\r\na=extmap:23 "
"http://www.webrtc.org/experiments/rtp-hdrext/meta-data-03\r\na=extmap:14 "
"urn:ietf:params:rtp-hdrext:toffset\r\na=extmap:2 "
"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=extmap:13 "
"urn:3gpp:video-orientation\r\na=extmap:3 "
"http://www.ietf.org/id/"
"draft-holmer-rmcat-transport-wide-cc-extensions-01\r\na=extmap:12 "
"http://www.webrtc.org/experiments/rtp-hdrext/"
"playout-delay\r\na=extmap:30 "
"http://www.webrtc.org/experiments/rtp-hdrext/video-frame-type\r\na=fingerprint:sha-256 "
"8A:BD:A6:61:75:AF:31:4C:02:81:2A:FA:12:92:4C:48:7B:9F:23:DD:BF:3D:51:30:"
"E7:59:5C:9B:17:3D:92:34\r\na=setup:passive\r\na=sendrecv\r\na=mid:1\r\na="
"rtcp-mux\r\na=rtcp-rsize\r\na=rtpmap:102 H264/90000\r\na=rtcp-fb:102 ccm "
"fir\r\na=rtcp-fb:102 goog-remb\r\na=rtcp-fb:102 nack\r\na=rtcp-fb:102 "
"nack pli\r\na=rtcp-fb:102 transport-cc\r\na=fmtp:102 "
"bframe-enabled=1;level-asymmetry-allowed=1;packetization-mode=1;profile-level-id="
"42001f\r\na=rtpmap:108 H264/90000\r\na=rtcp-fb:108 ccm "
"fir\r\na=rtcp-fb:108 goog-remb\r\na=rtcp-fb:108 nack\r\na=rtcp-fb:108 "
"nack pli\r\na=rtcp-fb:108 transport-cc\r\na=fmtp:108 "
"BFrame-enabled=1;level-asymmetry-allowed=1;packetization-mode=0;profile-level-id="
"42e01f\r\na=rtpmap:123 H264/90000\r\na=rtcp-fb:123 ccm "
"fir\r\na=rtcp-fb:123 goog-remb\r\na=rtcp-fb:123 nack\r\na=rtcp-fb:123 "
"nack pli\r\na=rtcp-fb:123 transport-cc\r\na=fmtp:123 "
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id="
"640032\r\na=rtpmap:124 H264/90000\r\na=rtcp-fb:124 ccm "
"fir\r\na=rtcp-fb:124 goog-remb\r\na=rtcp-fb:124 nack\r\na=rtcp-fb:124 "
"nack pli\r\na=rtcp-fb:124 transport-cc\r\na=fmtp:124 "
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id="
"4d0032\r\na=rtpmap:125 H264/90000\r\na=rtcp-fb:125 ccm "
"fir\r\na=rtcp-fb:125 goog-remb\r\na=rtcp-fb:125 nack\r\na=rtcp-fb:125 "
"nack pli\r\na=rtcp-fb:125 transport-cc\r\na=fmtp:125 "
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id="
"42e01f\r\na=rtpmap:127 H264/90000\r\na=rtcp-fb:127 ccm "
"fir\r\na=rtcp-fb:127 goog-remb\r\na=rtcp-fb:127 nack\r\na=rtcp-fb:127 "
"nack pli\r\na=rtcp-fb:127 transport-cc\r\na=fmtp:127 "
"level-asymmetry-allowed=1;packetization-mode=0;profile-level-id="
"42001f\r\na=ssrc:10395099 cname:webrtccore\r\na=ssrc:10395099 "
"msid:0_xxxx_d71956d9cc93e4a467b11e06fdaf039a h264\r\na=ssrc:10395099 "
"mslabel:0_xxxx_d71956d9cc93e4a467b11e06fdaf039a\r\na=ssrc:10395099 "
"label:h264\r\n";
SdpType sdp_type = SdpType::kAnswer;
string url =
"webrtc://domain/live/xxxx_d71956d9cc93e4a467b11e06fdaf039a";
char buffer[1400];
int main() {
cout << "test sdp" << endl;
OriginSdpAttr attr;
attr.origin_sdp = origin_sdp;
attr.sdp_type = sdp_type;
attr.stream_url = url;
attr.seq = 0;
attr.status_code = 0;
attr.svrsig = "1h8s";
attr.is_imm_send = true;
attr.is_support_aac_fmtp = true;
attr.is_push = kStreamPush;
int ret = ParseOriginSdpToMiniSdp(attr, buffer, 1400);
cout << "pack ret:" << ret << endl;
OriginSdpAttr attr2;
ret = LoadMiniSdpToOriginSdp(buffer, ret, attr2);
cout << "parse ret:" << ret << endl;
cout << "tyep: " << (uint32_t)attr2.sdp_type << endl;
cout << "parse sdp" << endl;
cout << attr2.origin_sdp << endl;
cout << "parse url: ";
cout << attr2.stream_url << endl;
cout << "seq: " << attr2.seq << endl;
cout << "status_code: " << attr2.status_code << endl;
cout << "svrsig " << attr2.svrsig << endl;
cout << "is_push " << attr2.is_push << endl;
cout << "test end" << endl;
return 0;
}
|
#include "Hora.h"
void Hora::verificaHora(void){
if(h<0 || h>23 || m<0 || m>59 || s<0 || s>59){
h=0;
m=0;
s=0;
}
}
Hora::Hora(void){
h=0;
m=0;
s=0;
}
Hora::Hora(int h, int m, int s){
this->h = h;
this->m = m;
this->s = s;
this->verificaHora();
}
Hora::~Hora(){
}
void Hora::muestraTusDatos(void){
cout<<h<<":"<<m<<":"<<s;
}
void Hora::pideleAlUsuarioTusDatos(void){
cout<<"Dame mi h ";
cin>>h;
cout<<"Dame mi m ";
cin>>m;
cout<<"Dame mi s ";
cin>>s;
this->verificaHora();
}
int Hora::dameTuH(void){
return h;
}
void Hora::modificaTuH(int h){
this->h=h;
this->verificaHora();
}
int Hora::dameTuM(void){
return m;
}
void Hora::modificaTuM(int m){
this->m=m;
this->verificaHora();
}
int Hora::dameTuS(void){
return s;
}
void Hora::modificaTuS(int s){
this->s=s;
this->verificaHora();
}
//Sobrecargas
bool operator<(Hora Izq, Hora Der){
if(Izq.dameTuH()<Der.dameTuH()){
return true;
}
else if(Izq.dameTuH()==Der.dameTuH()&&Izq.dameTuM()<Der.dameTuM()){
return true;
}
else if(Izq.dameTuH()==Der.dameTuH()&&Izq.dameTuM()==Der.dameTuM()&&Izq.dameTuS()<Der.dameTuS()){
return true;
}
else{
return false;
}
}
bool operator<=(Hora Izq, Hora Der){
if(Izq.dameTuH() <= Der.dameTuH()){
return true;
}
else if( (Izq.dameTuH() == Der.dameTuH()) && (Izq.dameTuM() <= Der.dameTuM()) ){
return true;
}
else if( (Izq.dameTuH() == Der.dameTuH()) && (Izq.dameTuM() == Der.dameTuM()) && (Izq.dameTuS() <= Der.dameTuS()) ){
return true;
}
else{
return false;
}
}
bool operator>(Hora Izq, Hora Der){
if(Izq.dameTuH() > Der.dameTuH()){
return true;
}
else if( (Izq.dameTuH() == Der.dameTuH()) && (Izq.dameTuM() > Der.dameTuM()) ){
return true;
}
else if( (Izq.dameTuH() == Der.dameTuH()) && (Izq.dameTuM()==Der.dameTuM()) && (Izq.dameTuS()>Der.dameTuS()) ){
return true;
}
else{
return false;
}
}
bool operator==(Hora Izq,Hora Der){
return (Izq.dameTuH()==Der.dameTuH()&&Izq.dameTuM()==Der.dameTuM()&&Izq.dameTuS()==Der.dameTuS());
}
ostream& operator<<(ostream& Izq, Hora Der){
Der.muestraTusDatos();
return Izq;
}
istream& operator>>(istream& Izq, Hora& Der){
Der.pideleAlUsuarioTusDatos();
return Izq;
}
|
#include "stdafx.h"
#include "Ai4wwTests.h"
#include "StringUtils.h"
#include "Station.h"
#include "TextFile.h"
#include "TestError.h"
#include "Contest.h"
Ai4wwTests::Ai4wwTests()
:
TestBase("Ai4wwTests"),
m_station(nullptr)
{
}
Ai4wwTests::~Ai4wwTests()
{
if (m_station)
delete m_station;
}
bool Ai4wwTests::Setup()
{
if (SetupComplete())
return SetupStatus();
if (!TestBase::Setup())
return false;
// printf("Ai4wwTests::Setup\n");
string filename = TestDataFolder() + string("ai4ww.log");
TextFile textfile;
bool status = textfile.Read(filename);
if (!status)
{
SetSetupStatus(false);
string msg = string("Ai4wwTests::Setup Error -> Failed to open file: ") + filename;
TestError *error = new TestError(this, msg);
AddTestError(error);
return false;
}
textfile.GetLines(m_lines);
Contest *contest = nullptr;
m_station = new Station(contest);
m_station->SetContestState("Missouri");
m_station->SetContestStateAbbrev("mo");
vector<QsoTokenType*> tokenTypes;
m_station->ParseStringsCreateQsos(m_lines, tokenTypes);
return true;
}
void Ai4wwTests::Teardown()
{
TestBase::Teardown();
}
bool Ai4wwTests::RunAllTests()
{
bool status = true;
status = TestLocation() && status;
status = TestInState() && status;
status = TestCallsign() && status;
status = TestNumberOfQsos() && status;
return status;
}
bool Ai4wwTests::TestLocation()
{
if (!StartTest("TestLocation")) return false;
string location = "sfl";
AssertEqual(location, m_station->StationLocation());
return true;
}
bool Ai4wwTests::TestInState()
{
if (!StartTest("TestInState")) return false;
AssertEqual(false, m_station->InState());
return true;
}
bool Ai4wwTests::TestCallsign()
{
if (!StartTest("TestCallsign")) return false;
string call = "ai4ww";
AssertEqual(call, m_station->StationCallsignLower());
return true;
}
bool Ai4wwTests::TestNumberOfQsos()
{
if (!StartTest("TestNumberOfQsos")) return false;
int count = m_station->NumberOfQsos();
AssertEqual(1, count);
return true;
}
|
//
// tertura.h
// opengl2
//
// Created by Tiago Rezende on 4/2/13.
//
//
#ifndef __opengl2__tertura__
#define __opengl2__tertura__
#include "ofMain.h"
#include <vector>
#include <string>
class GenTextureShader {
protected:
ofVbo vbo;
public:
virtual void setup() {};
virtual ~GenTextureShader() {}
virtual void apply() = 0;
};
class GenTexture {
ofFbo fbo;
ofCamera camera;
typedef std::vector<GenTextureShader*> ShaderSeq;
ShaderSeq sequence;
public:
GenTexture();
~GenTexture();
void applySequence();
ofTexture& getTexture();
void addShader(GenTextureShader * shader);
};
class GenTextureFragShader: public GenTextureShader {
ofShader shader;
std::string filename;
public:
GenTextureFragShader(const std::string &filename);
virtual void setup();
virtual void apply();
};
class GenTextureImageShader: public GenTextureShader {
ofImage &img;
public:
explicit GenTextureImageShader(ofImage &image);
virtual void apply();
};
#endif /* defined(__opengl2__tertura__) */
|
#include <json.h>
#ifdef _WIN32
#include <windows.h>
#endif
#include <exception>
#include <iostream>
#include <clocale>
int main(int argc, char* argv[])
{
std::setlocale(LC_ALL, "");
try {
json::value config;
config["test"];// = 3;
}
catch (const std::exception& e) {
std::cerr << "error: " << e.what() << std::endl;
}
std::cout << "done" << std::endl;
#ifdef _WIN32
if (GetConsoleWindow() && IsDebuggerPresent()) {
std::cerr << "Press ENTER to close this window." << std::endl;
std::cin.get();
}
#endif
return 0;
}
|
#include "brickstest.hpp"
#include <bricks/imaging/png.h>
#include <bricks/imaging/bitmap.h>
#include <bricks/io/filestream.h>
using namespace Bricks;
using namespace Bricks::IO;
using namespace Bricks::Imaging;
class BricksImagingPngTest : public testing::Test
{
protected:
AutoPointer<Stream> fileStream;
virtual void SetUp()
{
fileStream = autonew FileStream(TestPath.Combine("data/testFACEB0.png"), FileOpenMode::Open, FileMode::ReadOnly);
}
virtual void TearDown()
{
}
};
TEST_F(BricksImagingPngTest, InitialParse) {
try {
EXPECT_TRUE(PNG::LoadImage(fileStream));
} catch (const Exception& ex) {
ADD_FAILURE();
}
}
TEST_F(BricksImagingPngTest, ReadPixels) {
AutoPointer<Image> image = PNG::LoadImage(fileStream);
if (!image)
FAIL();
for (u32 x = 0; x < image->GetWidth(); x++) {
for (u32 y = 0; y < image->GetHeight(); y++) {
Colour pixel = image->GetPixel(x, y);
EXPECT_EQ(Colour(0xfa, 0xce, 0xb0, 0xff), pixel);
}
}
EXPECT_EQ(0x40 * 0x40, image->GetWidth() * image->GetHeight());
}
TEST_F(BricksImagingPngTest, ReadTransformedPixels) {
AutoPointer<Image> image = PNG::LoadImage(fileStream, true);
if (!image)
FAIL();
for (u32 x = 0; x < image->GetWidth(); x++) {
for (u32 y = 0; y < image->GetHeight(); y++) {
Colour pixel = image->GetPixel(x, y);
EXPECT_EQ(Colour(0xfa, 0xce, 0xb0, 0xff), pixel);
}
}
EXPECT_EQ(0x40 * 0x40, image->GetWidth() * image->GetHeight());
}
int main(int argc, char* argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
/*
* Death Star Lamp
*
* Firmware to connect my Death Star lamp device to the cloud using a MKR1000.
* Subscribes to a real-time messaging channel on PubNub and parses messages.
* Adds logic to turn lamp on/off and move stepper motor in between ten levels.
*
* You need to add your WiFi and device details in lines 30-32.
*
* Signal outputs on the Arduino MKR1000:
* - Pin 2 --> Motor driver / pin 8
* - Pin 3 --> Motor driver / pin 7
* - Pin 4 --> Motor driver / pin 6
* - Pin 5 --> Motor driver / pin 5
* - Pin 7 --> SSR relay / CH1
*
* Created Apr 1, 2018
* By Adi Singh
*
* https://github.com/adi3/death_star_lamp
*
*/
#include <WiFi101.h>
#include <Stepper.h>
#include <ArduinoJson.h>
#include <FlashAsEEPROM.h>
/*********************** This portion to be filled in *****************************/
#define WIFI_SSID "WIFI_SSID" // your WiFi connection name
#define WIFI_PASSWORD "WIFI_PASSWORD" // your WiFi connection password
#define DEVICE_ID "DEVICE_ID" // device ID provided by Alexa
/**********************************************************************************/
const char* server = "ps.pndsn.com";
const int dirPin = 2;
const int stepPin = 3;
const int sleepPin = 4;
const int resetPin = 5;
const int relayPin = 7;
const int STEPS_PER_LVL = 2800;
String timeToken = "0";
WiFiClient client;
int currGlow;
/*
* Set output pins and connect to WiFi.
*/
void setup(void){
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
pinMode(dirPin,OUTPUT);
pinMode(stepPin,OUTPUT);
pinMode(sleepPin, OUTPUT);
digitalWrite(sleepPin, LOW);
pinMode(resetPin, OUTPUT);
digitalWrite(resetPin, HIGH);
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, HIGH);
Serial.begin(9600);
Serial.println();
Serial.print("Connecting to ");
Serial.println(WIFI_SSID);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
}
Serial.println("");
Serial.println("WiFi connected");
// Turn on LED once online
digitalWrite(LED_BUILTIN, HIGH);
initGlow();
}
/*
* Get stored glow to sync with actual lamp level.
*/
void initGlow() {
if (!EEPROM.isValid()) {
Serial.println("Initing EEPROM...");
EEPROM.write(0,0);
EEPROM.commit();
}
currGlow = (int)EEPROM.read(0);
Serial.println(currGlow);
}
/*
* Subscribe to pubnub and handle messages.
*/
void loop(void){
if (client.connect(server, 80)) {
Serial.println("Reconnecting...");
String url = "/subscribe";
url += "/sub-c-6cb01a82-feaf-11e6-a656-02ee2ddab7fe";
url += "/";
url += DEVICE_ID;
url += "/0/";
url += timeToken;
Serial.println(url);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + server + "\r\n" +
"Connection: close\r\n\r\n");
delay(100);
while (client.available()) {
String line = client.readStringUntil('\r');
if (line.endsWith("]")) {
Serial.println(line);
cmdHandler(strParser(line));
}
}
} else {
Serial.println("Pubnub Connection Failed");
}
Serial.println("Closing connection");
client.stop();
delay(1000);
}
/*
* Parse commands and invoke relevant function.
*/
uint8_t cmdHandler(String pJson) {
StaticJsonBuffer<200> jsonBuffer;
JsonObject& parsedJson = jsonBuffer.parseObject(pJson);
if (!parsedJson.success())
{
Serial.println("Parsing failed.");
return 0;
}
String param = parsedJson["param"];
String cmd = parsedJson["cmd"];
Serial.println(param);
Serial.println(cmd);
if (param == "state") {
handleState(cmd);
} else if (param == "glow") {
handleGlow(cmd);
} else if (param == "effects") {
handleEffects(cmd);
}
}
/*
* Switch the bulb on or off via solid-state relay.
*/
void handleState(String cmd) {
if (cmd == "1") {
digitalWrite(relayPin, LOW);
} else {
digitalWrite(relayPin, HIGH);
}
}
/*
* Turn stepper for opening or closing lamp to designated level.
*/
void handleGlow(String cmd) {
int glow = cmd.toInt();
if (glow == currGlow) {
Serial.println("Glow level already at " + cmd);
} else {
setMotorDirection(glow);
int steps = getMotorSteps(glow);
moveMotor(steps);
storeGlowLevel(glow);
}
}
/*
* Determine turn direction by comparing current and designated levels.
*/
void setMotorDirection(int glow) {
int sig = (currGlow > glow) ? HIGH : LOW;
digitalWrite(dirPin, sig);
Serial.println("Dir: " + sig);
}
/*
* Determine number of steps needed to reach designated level.
*/
int getMotorSteps(int glow) {
int delta = abs(currGlow - glow);
Serial.println(STEPS_PER_LVL * delta);
Serial.println("-----");
return STEPS_PER_LVL * delta;
}
/*
* Wake stepper, then move in set direction by given number of steps.
*/
void moveMotor(int steps) {
digitalWrite(sleepPin, HIGH);
delay(10);
for (int i=0; i <= steps; i++){
digitalWrite(stepPin,HIGH);
delayMicroseconds(500);
digitalWrite(stepPin,LOW);
delayMicroseconds(500);
}
digitalWrite(sleepPin, LOW);
}
/*
* Save glow level to sync firmware and hardware after device reboot.
*/
void storeGlowLevel(int glow) {
currGlow = glow;
EEPROM.write(0,currGlow);
EEPROM.commit();
Serial.println("EEPROM data: " + String(EEPROM.read(0)));
}
/*
* A quirky feature for a cool light-n-sound show.
* Alexa plays the Imperial March during this function.
*/
void handleEffects(String cmd) {
flicker(7);
handleGlow("6");
flicker(7);
handleGlow("4");
flicker(2);
delay(3000);
handleGlow("10");
flicker(3);
}
/*
* Random pauses between successive on/offs to induce flickering.
*/
void flicker(int time) {
for (int i=0; i<(2*time); i++) {
delay(random(100, 400));
handleState("1");
delay(random(100, 400));
handleState("0");
}
// always leave flicker mode with light on
handleState("1");
}
/*
* Parse raw pubnub stream data into structured JSON.
*/
String strParser(String data) {
char buffer[200];
memset(buffer, '\0', 200);
int count = 0;
String json;
typedef enum {
STATE_INIT = 0,
STATE_START_JSON,
STATE_END_JSON,
STATE_SKIP_JSON,
STATE_INIT_TIME_TOKEN,
STATE_START_TIME_TOKEN,
STATE_END_TIME_TOKEN
} STATE;
STATE state = STATE_INIT;
data.toCharArray(buffer, 200);
for (int i = 1; i <= strlen(buffer); i++) {
if (buffer[i] == '[' && buffer[i + 2] == '{') {
state = STATE_START_JSON;
json = "\0";
continue;
}
else if (buffer[i] == '[' && buffer[i + 4] == '"') {
state = STATE_INIT_TIME_TOKEN;
json = "{}";
timeToken = "\0";
continue;
}
switch (state) {
case STATE_START_JSON:
if (buffer[i] == '[') {
break;
}
else if (buffer[i] == '{') {
count++;
json += buffer[i];
}
else if (buffer[i] == '}') {
count--;
json += buffer[i];
if (count <= 0) {
state = STATE_END_JSON;
}
}
else {
json += buffer[i];
if (buffer[i] == '}') {
state = STATE_END_JSON;
}
}
break;
case STATE_END_JSON:
if (buffer[i] == ']' && buffer[i + 2] == '"') {
state = STATE_INIT_TIME_TOKEN;
timeToken = "\0";
}
break;
case STATE_INIT_TIME_TOKEN:
if (buffer[i] == '"') {
state = STATE_START_TIME_TOKEN;
timeToken = "\0";
}
break;
case STATE_START_TIME_TOKEN:
if (buffer[i] == '"' && buffer[i + 1] == ']') {
state = STATE_END_TIME_TOKEN;
break;
}
timeToken += buffer[i];
break;
case STATE_END_TIME_TOKEN:
break;
default:
break;
}
}
return json;
}
|
// window.h
// The Window class has the main Qt components and links together the GUI with your scene graph
#ifndef WINDOW_H
#define WINDOW_H
#include <QWidget>
#include <QtWidgets>
#include <QSlider>
#include <QPushButton>
#include "gMatrix.h"
#include "eController.h"
class Data; // forward declaration of my simple little data class
class Controller;
namespace Ui {
class Window;
}
class Window : public QWidget
{
Q_OBJECT
public:
explicit Window(QWidget *parent = 0);
~Window();
void updateBrowser(); // update the browser
void select(int selected); // set the selection
void updateDrawing(); // redraw the OpenGL window
const int numPolys(); // get the number of faces
gMatrix getPoly(int i); // get a face
const int getSelected(); // get the index of the face selected
const float getExtrude();
void setController(Controller* c);
void on_buttonPress_valueChanged(int value);
Controller* controller; // Pointer to the controller
void on_Create_Press();
void on_wired();
void on_solid();
void on_change_color();
void on_change_height();
void on_view_side();
void on_view_top();
void capHeightfunc();
void Fractalizefunc();
void SubDividefunc();
void timerEvent(QTimerEvent *event);
protected:
void keyPressEvent(QKeyEvent *event);
void mousePressEvent(QMouseEvent* event);
void mouseMoveEvent(QMouseEvent *event);
signals:
public slots :
void on_treeWidget_currentItemChanged(int value); // Called when a different item in the tree view is selected.
void on_horizontalSlider_valueChanged(int value); // Called when the slider is slid.
void on_clicked_extrudeButton();
private:
Ui::Window *ui; // A Qt internal mechanism
QPoint lastPos; // For mouse movement
};
#endif // WINDOW_H
|
#ifndef S3INDEX_LIBRARY_H
#define S3INDEX_LIBRARY_H
#include "Vertica.h"
#include <stdio.h>
#include <stdlib.h>
#include <aws/core/Aws.h>
#include <aws/core/auth/AWSCredentialsProvider.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/model/GetObjectRequest.h>
#include <aws/transfer/TransferManager.h>
using namespace Vertica;
std::map<Aws::Http::HttpResponseCode, std::string> m = {
{Aws::Http::HttpResponseCode::REQUEST_NOT_MADE, "REQUEST_NOT_MADE: -1"},
{Aws::Http::HttpResponseCode::CONTINUE, "CONTINUE: 100"},
{Aws::Http::HttpResponseCode::SWITCHING_PROTOCOLS, "SWITCHING_PROTOCOLS: 101"},
{Aws::Http::HttpResponseCode::PROCESSING, "PROCESSING: 102"},
{Aws::Http::HttpResponseCode::OK, "OK: 200"},
{Aws::Http::HttpResponseCode::CREATED, "CREATED: 201"},
{Aws::Http::HttpResponseCode::ACCEPTED, "ACCEPTED: 202"},
{Aws::Http::HttpResponseCode::NON_AUTHORITATIVE_INFORMATION, "NON_AUTHORITATIVE_INFORMATION: 203"},
{Aws::Http::HttpResponseCode::NO_CONTENT, "NO_CONTENT: 204"},
{Aws::Http::HttpResponseCode::RESET_CONTENT, "RESET_CONTENT: 205"},
{Aws::Http::HttpResponseCode::PARTIAL_CONTENT, "PARTIAL_CONTENT: 206"},
{Aws::Http::HttpResponseCode::MULTI_STATUS, "MULTI_STATUS: 207"},
{Aws::Http::HttpResponseCode::ALREADY_REPORTED, "ALREADY_REPORTED: 208"},
{Aws::Http::HttpResponseCode::IM_USED, "IM_USED: 226"},
{Aws::Http::HttpResponseCode::MULTIPLE_CHOICES, "MULTIPLE_CHOICES: 300"},
{Aws::Http::HttpResponseCode::MOVED_PERMANENTLY, "MOVED_PERMANENTLY: 301"},
{Aws::Http::HttpResponseCode::FOUND, "FOUND: 302"},
{Aws::Http::HttpResponseCode::SEE_OTHER, "SEE_OTHER: 303"},
{Aws::Http::HttpResponseCode::NOT_MODIFIED, "NOT_MODIFIED: 304"},
{Aws::Http::HttpResponseCode::USE_PROXY, "USE_PROXY: 305"},
{Aws::Http::HttpResponseCode::SWITCH_PROXY, "SWITCH_PROXY: 306"},
{Aws::Http::HttpResponseCode::TEMPORARY_REDIRECT, "TEMPORARY_REDIRECT: 307"},
{Aws::Http::HttpResponseCode::PERMANENT_REDIRECT, "PERMANENT_REDIRECT: 308"},
{Aws::Http::HttpResponseCode::BAD_REQUEST, "BAD_REQUEST: 400"},
{Aws::Http::HttpResponseCode::UNAUTHORIZED, "UNAUTHORIZED: 401"},
{Aws::Http::HttpResponseCode::PAYMENT_REQUIRED, "PAYMENT_REQUIRED: 402"},
{Aws::Http::HttpResponseCode::FORBIDDEN, "FORBIDDEN: 403"},
{Aws::Http::HttpResponseCode::NOT_FOUND, "NOT_FOUND: 404"},
{Aws::Http::HttpResponseCode::METHOD_NOT_ALLOWED, "METHOD_NOT_ALLOWED: 405"},
{Aws::Http::HttpResponseCode::NOT_ACCEPTABLE, "NOT_ACCEPTABLE: 406"},
{Aws::Http::HttpResponseCode::PROXY_AUTHENTICATION_REQUIRED, "PROXY_AUTHENTICATION_REQUIRED: 407"},
{Aws::Http::HttpResponseCode::REQUEST_TIMEOUT, "REQUEST_TIMEOUT: 408"},
{Aws::Http::HttpResponseCode::CONFLICT, "CONFLICT: 409"},
{Aws::Http::HttpResponseCode::GONE, "GONE: 410"},
{Aws::Http::HttpResponseCode::LENGTH_REQUIRED, "LENGTH_REQUIRED: 411"},
{Aws::Http::HttpResponseCode::PRECONDITION_FAILED, "PRECONDITION_FAILED: 412"},
{Aws::Http::HttpResponseCode::REQUEST_ENTITY_TOO_LARGE, "REQUEST_ENTITY_TOO_LARGE: 413"},
{Aws::Http::HttpResponseCode::REQUEST_URI_TOO_LONG, "REQUEST_URI_TOO_LONG: 414"},
{Aws::Http::HttpResponseCode::UNSUPPORTED_MEDIA_TYPE, "UNSUPPORTED_MEDIA_TYPE: 415"},
{Aws::Http::HttpResponseCode::REQUESTED_RANGE_NOT_SATISFIABLE, "REQUESTED_RANGE_NOT_SATISFIABLE: 416"},
{Aws::Http::HttpResponseCode::EXPECTATION_FAILED, "EXPECTATION_FAILED: 417"},
{Aws::Http::HttpResponseCode::IM_A_TEAPOT, "IM_A_TEAPOT: 418"},
{Aws::Http::HttpResponseCode::AUTHENTICATION_TIMEOUT, "AUTHENTICATION_TIMEOUT: 419"},
{Aws::Http::HttpResponseCode::METHOD_FAILURE, "METHOD_FAILURE: 420"},
{Aws::Http::HttpResponseCode::UNPROC_ENTITY, "UNPROC_ENTITY: 422"},
{Aws::Http::HttpResponseCode::LOCKED, "LOCKED: 423"},
{Aws::Http::HttpResponseCode::FAILED_DEPENDENCY, "FAILED_DEPENDENCY: 424"},
{Aws::Http::HttpResponseCode::UPGRADE_REQUIRED, "UPGRADE_REQUIRED: 426"},
{Aws::Http::HttpResponseCode::PRECONDITION_REQUIRED, "PRECONDITION_REQUIRED: 427"},
{Aws::Http::HttpResponseCode::TOO_MANY_REQUESTS, "TOO_MANY_REQUESTS: 429"},
{Aws::Http::HttpResponseCode::REQUEST_HEADER_FIELDS_TOO_LARGE, "REQUEST_HEADER_FIELDS_TOO_LARGE: 431"},
{Aws::Http::HttpResponseCode::LOGIN_TIMEOUT, "LOGIN_TIMEOUT: 440"},
{Aws::Http::HttpResponseCode::NO_RESPONSE, "NO_RESPONSE: 444"},
{Aws::Http::HttpResponseCode::RETRY_WITH, "RETRY_WITH: 449"},
{Aws::Http::HttpResponseCode::BLOCKED, "BLOCKED: 450"},
{Aws::Http::HttpResponseCode::REDIRECT, "REDIRECT: 451"},
{Aws::Http::HttpResponseCode::REQUEST_HEADER_TOO_LARGE, "REQUEST_HEADER_TOO_LARGE: 494"},
{Aws::Http::HttpResponseCode::CERT_ERROR, "CERT_ERROR: 495"},
{Aws::Http::HttpResponseCode::NO_CERT, "NO_CERT: 496"},
{Aws::Http::HttpResponseCode::HTTP_TO_HTTPS, "HTTP_TO_HTTPS: 497"},
{Aws::Http::HttpResponseCode::CLIENT_CLOSED_TO_REQUEST, "CLIENT_CLOSED_TO_REQUEST: 499"},
{Aws::Http::HttpResponseCode::INTERNAL_SERVER_ERROR, "INTERNAL_SERVER_ERROR: 500"},
{Aws::Http::HttpResponseCode::NOT_IMPLEMENTED, "NOT_IMPLEMENTED: 501"},
{Aws::Http::HttpResponseCode::BAD_GATEWAY, "BAD_GATEWAY: 502"},
{Aws::Http::HttpResponseCode::SERVICE_UNAVAILABLE, "SERVICE_UNAVAILABLE: 503"},
{Aws::Http::HttpResponseCode::GATEWAY_TIMEOUT, "GATEWAY_TIMEOUT: 504"},
{Aws::Http::HttpResponseCode::HTTP_VERSION_NOT_SUPPORTED, "HTTP_VERSION_NOT_SUPPORTED: 505"},
{Aws::Http::HttpResponseCode::VARIANT_ALSO_NEGOTIATES, "VARIANT_ALSO_NEGOTIATES: 506"},
{Aws::Http::HttpResponseCode::INSUFFICIENT_STORAGE, "INSUFFICIENT_STORAGE: 506"},
{Aws::Http::HttpResponseCode::LOOP_DETECTED, "LOOP_DETECTED: 508"},
{Aws::Http::HttpResponseCode::BANDWIDTH_LIMIT_EXCEEDED, "BANDWIDTH_LIMIT_EXCEEDED: 509"},
{Aws::Http::HttpResponseCode::NOT_EXTENDED, "NOT_EXTENDED: 510"},
{Aws::Http::HttpResponseCode::NETWORK_AUTHENTICATION_REQUIRED, "NETWORK_AUTHENTICATION_REQUIRED: 511"},
{Aws::Http::HttpResponseCode::NETWORK_READ_TIMEOUT, "NETWORK_READ_TIMEOUT: 598"},
{Aws::Http::HttpResponseCode::NETWORK_CONNECT_TIMEOUT, "NETWORK_CONNECT_TIMEOUT: 599"}};
class Init
{
public:
static Init& getInstance()
{
static Init instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
Aws::SDKOptions options;
Init() {
std::cout << "Starting Aws::InitAPI" << std::endl;
Aws::InitAPI(options);
}
~Init() {
std::cout << "Shutting down Aws::ShutdownAPI" << std::endl;
Aws::ShutdownAPI(options);
}
// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
public:
Init(Init const&) = delete;
void operator=(Init const&) = delete;
};
class S3Source : public UDSource {
private:
bool verbose = false;
Aws::String bucket_name;
Aws::String key_name;
Aws::String sTmpfileName = std::tmpnam(nullptr);
std::shared_ptr<Aws::Transfer::TransferManager> transferManagerShdPtr;
std::shared_ptr<Aws::Transfer::TransferHandle> transferHandleShdPtr;
long retryCount = 0;
Aws::Transfer::TransferStatus lastStatus;
FILE *handle;
virtual StreamState process(ServerInterface &srvInterface, DataBuffer &output);
public:
S3Source(std::string url);
long totalBytes = 0;
virtual void setup(ServerInterface &srvInterface);
virtual void destroy(ServerInterface &srvInterface);
Aws::String getBucket();
Aws::String getKey();
};
#endif
|
#include <stdio.h>
#include <time.h>
#include <locale.h>
int main() {
int dia, mes, ano, idade;
struct tm*data;
time_t segundos;
time(&segundos);
data = localtime(&segundos);
printf("Digite o seu ano de nascimento: ");
scanf("%d", &ano);
printf("Digite o seu mes de nascimento: ");
scanf("%d", &mes);
printf("Digite o seu dia de nascimento: ");
scanf("%d", &dia);
idade = (data -> tm_year + 1900) - ano;
if(data -> tm_mon+1 < mes){
idade --;
}
else {
if(data -> tm_mon + 1 == mes){
if(data -> tm_mday > dia)
idade --;
}
}
printf("Voce tem %d anos de idade.", idade);
}
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <sstream>
#include <iostream>
#include "segmentedimage.h"
#include "statisticscollector.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// DEBUG
std::vector<std::pair<double, SegmentedImage*> > topImgs;
SegmentedImage segImg("../Probabilistic-Color-By-Numbers/data/1198080_a0.png");//1537398_t.png");
segImg.segment();
StatisticsCollector sc;
sc.collectData("../Probabilistic-Color-By-Numbers/data/");
topImgs = sc.sample(10, segImg);
for (int i=0, n=topImgs.size(); i<n; i++) {
std::ostringstream ss;
ss << "../Probabilistic-Color-By-Numbers/data/suggestions/random_" << i << '_' << topImgs[i].first << ".png";
std::cout << ss.str().c_str() << std::endl;
topImgs[i].second->save(QString(ss.str().c_str()));
}
}
MainWindow::~MainWindow()
{
delete ui;
}
|
#include "scenario_erase.hpp"
ScenarioErase::~ScenarioErase()
{
}
ScenarioErase::ScenarioErase(const std::vector<std::string>& word_list,
std::size_t nqueries)
: Scenario()
{
std::random_device rd;
std::mt19937 gen(rd());
this->m_impl->queries.reserve(nqueries);
this->m_impl->init_word_list =
std::vector<std::string>(word_list.begin(), word_list.begin() + nqueries);
std::uniform_int_distribution<> rand(0, nqueries);
for (std::size_t i = 0; i < nqueries; ++i)
this->m_impl->queries.push_back({query::erase, word_list[rand(gen)]});
// Shuffle everything
std::shuffle(this->m_impl->queries.begin(), this->m_impl->queries.end(), gen);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
*/
#ifndef BITMAP_BUTTON_H
#define BITMAP_BUTTON_H
#include "modules/libgogi/pi_impl/mde_bitmap_window.h"
#include "modules/widgets/OpButton.h"
class BitmapButton : public OpButton, public OpBitmapScreenListener
{
public:
BitmapButton();
virtual ~BitmapButton();
OP_STATUS Init(BitmapOpWindow* window);
// OpButton
virtual void OnPaint(OpWidgetPainter* widget_painter, const OpRect& paint_rect);
virtual void OnResize(INT32* new_w, INT32* new_h);
// OpBitmapScreenListener
virtual void OnInvalid();
virtual void OnScreenDestroying();
private:
BitmapOpWindow *m_bitmap_window;
};
#endif // BITMAP_BUTTON_H
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int N;
cin >> N;
long long sum =0;
for(int i=1; i <= N; i++){
if(i%3 !=0 && i%5 !=0 && i%15 != 0)sum += i;
}
cout << sum << endl;
}
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <algorithm>
#define INT_MAX 0x7fffffff
#define INT_MIN 0x80000000
using namespace std;
bool isMatch(const char *s, const char *p){
}
int main(){
}
|
#pragma once
namespace ionir {
class ConstructFactory {
public:
// TODO
};
}
|
#include "ReadsSetAnalyzer.h"
namespace PgSAReadsSet {
template<class ReadsSourceIterator>
ReadsSetProperties* ReadsSetAnalyzer::analyzeReadsSet(ReadsSourceIterator *readsIterator) {
ReadsSetProperties* properties = new ReadsSetProperties();
bool symbolOccured[UCHAR_MAX] = {0};
while (readsIterator->moveNext()) {
properties->readsCount++;
// analyze read length
uint_read_len_max currLength = readsIterator->getReadLength();
if (properties->maxReadLength == 0) {
properties->maxReadLength = currLength;
properties->minReadLength = currLength;
} else if (properties->maxReadLength != currLength) {
properties->constantReadLength = false;
if (properties->maxReadLength < currLength)
properties->maxReadLength = currLength;
if (properties->minReadLength > currLength)
properties->minReadLength = currLength;
}
properties->allReadsLength += currLength;
//analyze symbols
string read(readsIterator->getRead());
for (uint_read_len_max i = 0; i < currLength; i++) {
read[i] = toupper(read[i]);
if (!symbolOccured[(unsigned char) read[i]]) {
symbolOccured[(unsigned char) read[i]] = true;
properties->symbolsCount++;
}
}
}
// order symbols
for (uint_symbols_cnt i = 0, j = 0; i < properties->symbolsCount; j++)
if (symbolOccured[(unsigned char) j])
properties->symbolsList[(unsigned char) (i++)] = j;
properties->generateSymbolOrder();
return properties;
}
template ReadsSetProperties* ReadsSetAnalyzer::analyzeReadsSet<ReadsSourceIteratorTemplate<uint_read_len_min>>(ReadsSourceIteratorTemplate<uint_read_len_min>* readsIterator);
template ReadsSetProperties* ReadsSetAnalyzer::analyzeReadsSet<ReadsSourceIteratorTemplate<uint_read_len_std>>(ReadsSourceIteratorTemplate<uint_read_len_std>* readsIterator);
template ReadsSetProperties* ReadsSetAnalyzer::analyzeReadsSet<ConcatenatedReadsSourceIterator<uint_read_len_min>>(ConcatenatedReadsSourceIterator<uint_read_len_min>* readsIterator);
template ReadsSetProperties* ReadsSetAnalyzer::analyzeReadsSet<ConcatenatedReadsSourceIterator<uint_read_len_std>>(ConcatenatedReadsSourceIterator<uint_read_len_std>* readsIterator);
template ReadsSetProperties* ReadsSetAnalyzer::analyzeReadsSet<FASTAReadsSourceIterator<uint_read_len_min>>(FASTAReadsSourceIterator<uint_read_len_min>* readsIterator);
template ReadsSetProperties* ReadsSetAnalyzer::analyzeReadsSet<FASTAReadsSourceIterator<uint_read_len_std>>(FASTAReadsSourceIterator<uint_read_len_std>* readsIterator);
template ReadsSetProperties* ReadsSetAnalyzer::analyzeReadsSet<FASTQReadsSourceIterator<uint_read_len_min>>(FASTQReadsSourceIterator<uint_read_len_min>* readsIterator);
template ReadsSetProperties* ReadsSetAnalyzer::analyzeReadsSet<FASTQReadsSourceIterator<uint_read_len_std>>(FASTQReadsSourceIterator<uint_read_len_std>* readsIterator);
}
|
#ifndef CSERIALPORTCOMMON_H
#define CSERIALPORTCOMMON_H
#include <Windows.h>
#include <QString>
class CSerialPortCommon
{
public:
CSerialPortCommon();
bool isOpen() { return comopen; }
void cleanRx();
bool write(LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite);
DWORD read(LPVOID lpBuffer, DWORD nBufferSize);
protected:
virtual bool open(const QString &port, int baudRate=9600);
virtual void close();
void cleanRxTx();
void cleanTx();
private:
OVERLAPPED ovRead;
OVERLAPPED ovWrite;
HANDLE hCom;
bool comopen;
};
#endif // CSERIALPORTCOMMON_H
|
#ifndef ENEMY_H
#define ENEMY_H
#include<iostream>
#include "SFML/Graphics.hpp"
#include "Ground.h"
class Enemy
{
public:
/** Default constructor */
Enemy(sf::RenderWindow* windowPtr, Ground* ground, sf::Texture* enemyTex, int floater );
bool update(int direction, bool moveDetected);
sf::Vector2i hitCheck( sf::FloatRect playerBounds);
sf::FloatRect getEnemyBounds();
void alignPosition(float alignYpos);
/** Default destructor */
~Enemy();
protected:
private:
int enemyState = 1, MAXSTATE = 6;
sf::Sprite Goons;
int reverseMove;
sf::Texture* enemytexture;
sf::Clock enemyClock, jumpClock;
sf::Time enemyTime, jumpTime;
sf::RenderWindow* wine;
int groundNum = 0;
Ground* greenGround;
sf::Vector2f currPos;
float xPos = 0.0f;
float ACLTN_GRAVITY = 50.0f, TRANSITION_TIME = .05f;
sf::Sprite emptySprite;
int floatType = 0;
bool isGrounded();
float previousXval;
int prevCounter;
};
#endif // ENEMY_H
|
/*
This was a lab from CS 210, creating a simple vector list of items in a grocery cart
*/
#include <iostream>
#include <vector>
using namespace std;
#include "ItemToPurchase.h"
int main() {
//declare a vector to easily add multiple items
//temp variables for working with the loop
ItemToPurchase tempItem;
vector<ItemToPurchase> items;
string tempName;
int tempPrice;
int tempQuantity;
//loop to reduce redundancy of code
//add value to 'i' to increase number of items to add
for (int i = 0; i < 2; i++) {
cout << "Item " << i + 1 << endl;
cout << "Enter the item name:" << endl;
getline(cin, tempName);
//cin >> tempName;
//cin.ignore(); //keeps from skipping the next two inputs
cout << "Enter the item price:" << endl;
cin >> tempPrice;
cout << "Enter the item quantity:" << endl;
cin >> tempQuantity;
tempItem.setName(tempName);
tempItem.setPrice(tempPrice);
tempItem.setQuantity(tempQuantity);
items.emplace_back(tempItem); //add to back of vector
cout << endl;
cin.ignore();
}
//reuse variables to minimize memory usage
tempPrice = tempItem.getTotalCost(items);
return 0;
}
|
/*****************************************************************************************
* *
* owl *
* *
* Copyright (c) 2014 Jonas Strandstedt *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#ifndef __THREADSAFEVECTOR_H__
#define __THREADSAFEVECTOR_H__
#include <owl/logging/logmanager.h>
#include <vector>
#include <mutex>
#include <algorithm>
namespace owl {
/*****************************************************************************************
* *
* This vector wrapper is NOT entierly thread safe. IT only makes it a bit easier to *
* use in threaded environments. When accessing/changing contents it is safer to *
* manually lock beforehand. *
* *
****************************************************************************************/
template<class T>
class ThreadSafeVector {
public:
/********************************************
* Member functions *
********************************************/
template <typename... Args>
ThreadSafeVector(Args... args) {
_vector = new std::vector<T>(std::forward<Args>(args)...);
}
~ThreadSafeVector() {
delete _vector;
}
/********************************************
* Locks *
********************************************/
void lock() {
_lock.lock();
}
bool try_lock() {
return _lock.try_lock();
}
void unlock() {
_lock.unlock();
}
/********************************************
* Iterators *
********************************************/
typename std::vector<T>::iterator begin() {
return _vector->begin();
}
typename std::vector<T>::const_iterator begin() const {
return _vector->begin();
}
typename std::vector<T>::iterator end() {
return _vector->end();
}
typename std::vector<T>::const_iterator end() const {
return _vector->end();
}
/********************************************
* Capacity *
********************************************/
size_t size() const {
lock();
size_t s = _vector->size();
unlock();
return s;
}
size_t max_size() const {
lock();
size_t s = _vector->max_size();
unlock();
return s;
}
void resize(size_t n) {
lock();
_vector->resize(n);
unlock();
}
size_t capacity() const {
lock();
size_t s = _vector->capacity();
unlock();
return s;
}
bool empty() const {
lock();
bool e = _vector->empty();
unlock();
return e;
}
void reserve(size_t n) {
lock();
_vector->reserve(n);
unlock();
}
void shrink_to_fit() {
lock();
_vector->shrink_to_fit();
unlock();
}
/********************************************
* Modifiers *
********************************************/
void push_back(const T& val) {
lock();
_vector->push_back(val);
unlock();
}
void pop_back() {
lock();
_vector->pop_back();
unlock();
}
typename std::vector<T>::iterator insert(typename std::vector<T>::const_iterator position, const T& val) {
lock();
auto it = _vector->insert(position, val);
unlock();
return it;
}
template <class InputIterator>
typename std::vector<T>::iterator insert(typename std::vector<T>::const_iterator position, InputIterator first, InputIterator last) {
lock();
auto it = _vector->insert(position, first, last);
unlock();
return it;
}
typename std::vector<T>::iterator insert (typename std::vector<T>::const_iterator position, T&& val) {
lock();
auto it = _vector->insert(position, val);
unlock();
return it;
}
typename std::vector<T>::iterator insert (typename std::vector<T>::const_iterator position, std::initializer_list<T> il) {
lock();
auto it = _vector->insert(position, il);
unlock();
return it;
}
void remove(const T& val) {
auto cmp = [&val](const T& v) {
return val == v;
};
lock();
auto p = std::remove_if(_vector->begin(), _vector->end(), cmp);
_vector->erase(p, _vector->end());
unlock();
}
void remove_all() {
lock();
_vector->erase(_vector->begin(), _vector->end());
unlock();
}
/********************************************
* Element access (not thread safe!) *
********************************************/
T& at(size_t n) {
return _vector->at(n);
}
const T& at(size_t n) const {
return _vector->at(n);
}
T& operator[](size_t n) {
return _vector->operator[](n);
}
const T& operator[](size_t n) const {
return _vector->operator[](n);
}
/********************************************
* Algorithms *
********************************************/
T* find(const T& val) {
lock();
auto e = std::find(_vector->begin(), _vector->end(), val);
if(e == _vector->end())
e = nullptr;
unlock();
return e;
}
void sort(std::function<bool(const T& v1, const T& v2)> cmp) {
lock();
std::sort(_vector->begin(), _vector->end(), cmp);
unlock();
}
/********************************************
* Vector access *
********************************************/
std::vector<T>* getVector() {
return _vector;
}
private:
std::mutex _lock;
std::vector<T>* _vector;
}; // ThreadSafeVector
} // owl
#endif
|
//
// Copyright (C) 1995-2005 Opera Software AS. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
//
// Arjan van Leeuwen (arjanl)
//
#ifndef IMAP_FOLDER_H
#define IMAP_FOLDER_H
#include "adjunct/desktop_util/adt/opsortedvector.h"
#include "adjunct/m2/src/include/defs.h"
class Index;
class ImapBackend;
class Message;
class IMAP4;
class ImapCommandItem;
/** @brief Represents a folder or 'mailbox' on the IMAP server
* @author Arjan van Leeuwen
*
* The ImapFolder class represents a folder on the IMAP server and forms the connection between
* the folder on the server and the local folder as contained in the M2 Index.
*/
class ImapFolder
{
public:
ImapFolder(ImapBackend& backend, unsigned exists, unsigned uid_next, unsigned uid_validity, UINT64 last_known_mod_seq, index_gid_t index_id);
static OP_STATUS Create(ImapFolder*& folder, ImapBackend& backend, const OpStringC8& name, char delimiter = '/', int flags = 0, unsigned exists = 0, unsigned uid_next = 0, unsigned uid_validity = 0, UINT64 last_known_mod_seq = 0);
static OP_STATUS Create(ImapFolder*& folder, ImapBackend& backend, const OpStringC& name, char delimiter, unsigned exists, unsigned uid_next, unsigned uid_validity, UINT64 last_known_mod_seq);
/** To be called when this folder is opened and server signals expunged message
* @param expunged_message_id The id of the expunged message as signaled by server
*/
OP_STATUS Expunge(int expunged_message_id);
/** To be called when this folder is opened and server signals vanished messages
* @param vanished_uids UIDs of vanished messages
*/
OP_STATUS Vanished(const OpINT32Vector& vanished_uids);
/** Set the map between server_id and uid, will synchronise local and remote if necessary
* @param server_id ID on the server (sequence id)
* @param uid Unique ID on the server
*/
OP_STATUS SetMessageUID(unsigned server_id, unsigned uid);
/** Call this function after the last available UID has been set with SetMessageUID
*/
OP_STATUS LastUIDReceived();
/** Add a UID to this folder, means that this UID has been fetched
* @param uid UID that is fetched
* @param m2_id M2 message id of the fetched message
*/
OP_STATUS AddUID(unsigned uid, message_gid_t m2_id);
/** Get a message store ID by specifying the server ID
* @param server_id ID on the server (sequence id)
*/
message_gid_t GetMessageByServerID(int server_id);
/** Get a message store ID by specifying the UID
* @param uid UID on the server
*/
message_gid_t GetMessageByUID(unsigned uid);
/** Set if folder is subscribed or unsubscribed
* @param subscribed Whether the folder is subscribed or not
* @param sync_now Whether to sync the folder at this point
*/
OP_STATUS SetSubscribed(BOOL subscribed, BOOL sync_now = TRUE);
/** Check whether folder is subscribed
* @return Whether folder is subscribed
*/
BOOL IsSubscribed() const { return m_subscribed; }
/** Folder is not selectable
* @param force Go through all normal actions of marking unselectable, even
* if the folder is already marked as unselectable
* @param remove_messages Remove messages in the index - used when unsubscribing
*/
OP_STATUS MarkUnselectable(BOOL force = FALSE, BOOL remove_messages = FALSE);
/** Check whether folder is selectable
* @return Whether folder is selectable
*/
BOOL IsSelectable() const { return m_selectable; }
/** Set the exists value for this folder
* @param exists New exists value
* @param do_sync Whether to synchronize messages depending on value of exists
*/
OP_STATUS SetExists(unsigned exists, BOOL do_sync = TRUE);
unsigned GetFetched() const { return m_uid_map.GetCount(); }
unsigned GetExists() const { return m_exists; }
OP_STATUS SetUidNext(unsigned uid_next);
unsigned GetUidNext() const { return m_uid_next; }
OP_STATUS SetUidValidity(unsigned uid_validity);
unsigned GetUidValidity() const { return m_uid_validity; }
OP_STATUS UpdateModSeq(UINT64 mod_seq, bool from_fetch_response = false);
UINT64 LastKnownModSeq() const { return m_last_known_mod_seq; }
OP_STATUS SetUnseen(unsigned unseen) { m_unseen = unseen; return OpStatus::OK; }
OP_STATUS SetRecent(unsigned recent) { m_recent = recent; return OpStatus::OK; }
/** Get the index for this folder, or NULL if not available
*/
Index* GetIndex();
index_gid_t GetIndexId() { return m_index_id; }
/** Create an index for this folder if it did not already exist
*/
OP_STATUS CreateIndexForFolder();
OP_STATUS SetName(const OpStringC8& name, char delimiter) { return SetName(name, UNI_L(""), delimiter); }
OP_STATUS SetName(const OpStringC16& name, char delimiter) { return SetName("", name, delimiter); }
OP_STATUS ApplyNewName();
const OpStringC8& GetName() const { return m_name; }
const OpStringC8& GetQuotedName() const { return m_quoted_name; }
const OpStringC16& GetName16() const { return m_name16; }
const OpStringC8& GetOldName() const { return m_quoted_name; }
const OpStringC8& GetNewName() const { return m_quoted_new_name; }
/** Get the name that should be used to display this folder
* @return Name of the folder without the full path
*/
const uni_char* GetDisplayName() const;
char GetDelimiter() const { return m_delimiter; }
void SetDelimiter(char delimiter) { m_delimiter = delimiter; }
OP_STATUS SetNewName(const OpStringC8& new_name);
int GetSettableFlags() const { return m_settable_flags; }
int GetPermanentFlags() const { return m_permanent_flags; }
void SetFlags(int flags, BOOL permanent);
void SetListFlags(int flags);
BOOL IsScheduledForSync() const { return m_scheduled_for_sync > 0; }
BOOL IsScheduledForMultipleSync() const { return m_scheduled_for_sync > 1; }
void IncreaseSyncCount() { m_scheduled_for_sync++; }
void DecreaseSyncCount() { m_scheduled_for_sync--; }
OP_STATUS GetInternetLocation(unsigned uid, OpString8& internet_location) const;
OP_STATUS SetReadOnly(BOOL readonly) { m_readonly = readonly; return OpStatus::OK; }
OP_STATUS DoneFullSync();
BOOL NeedsFullSync() const { return g_timecache->CurrentTime() - m_last_full_sync > ForceFullSync; }
void RequestFullSync() { m_last_full_sync = 0; }
static OP_STATUS EncodeMailboxName(const OpStringC16& source, OpString8& target);
static OP_STATUS DecodeMailboxName(const OpStringC8& source, OpString16& target);
/** Reads UIDs of all messages contained in this folder and adds them to
* the UID manager. Use when updating from UID-manager-less account
*/
OP_STATUS InsertUIDs();
/** Reads the uids in 'container' and converts them to M2 ids
* @param container Vector containing uids, will contain M2 ids if successful
*/
OP_STATUS ConvertUIDToM2Id(OpINT32Vector& container);
/** Saves data about this folder to the IMAP account configuration file
* @param commit Whether to commit data to disk
*/
OP_STATUS SaveToFile(BOOL commit = FALSE);
/** Gets the highest UID known in this folder
* @return The highest UID known in this folder
*/
unsigned GetHighestUid();
private:
OP_STATUS ResetFolder();
OP_STATUS SetName(const OpStringC8& name8, const OpStringC16& name16, char delimiter);
int m_scheduled_for_sync;
unsigned m_exists;
unsigned m_uid_next;
unsigned m_uid_validity;
UINT64 m_last_known_mod_seq;
UINT64 m_next_mod_seq_after_sync;
unsigned m_unseen;
unsigned m_recent;
OpINTSortedVector m_uid_map;
OpString8 m_name;
OpString8 m_quoted_name;
OpString8 m_quoted_new_name;
OpString m_name16;
OpString8 m_internet_location_format;
char m_delimiter;
int m_settable_flags;
int m_permanent_flags;
BOOL m_readonly;
time_t m_last_full_sync;
index_gid_t m_index_id;
BOOL m_subscribed;
BOOL m_selectable;
ImapBackend& m_backend;
static const time_t ForceFullSync = 3600; ///< Force a full sync every x seconds
};
#endif // IMAP_FOLDER_H
|
#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
#include<vector>
#include<stdio.h>
using namespace std;
int N, X;
int arr[21][21];
int play() {
int cnt = 0;
// 상하
for (int x = 0; x < N; x++) {
int k = 1;
int cmp = arr[0][x];
bool up = 0;
int y = 1;
while (y < N) {
if (arr[y][x] == cmp) {
k++;
if (k == X) up = true;
}
else if (abs(arr[y][x] - cmp) > 1) break;
else if (arr[y][x] - cmp == 1) { // 오르막길
if (up == true) {
k = 1;
cmp = arr[y][x];
up = 0;
}
else break;
}
else if (arr[y][x] - cmp == -1) { // 내려막길
k = 1;
cmp = arr[y][x];
if (y + X - 1 < N) {
for (int h = y + 1; h <= y + X - 1; h++) {
if (arr[h][x] == cmp) k++;
}
if (k == X) {
k = 0;
up = 0;
y = y + X - 1;
if (y == N - 1) {
cnt++;
break;
}
}
else break;
}
else break;
}
if (y == N - 1) {
cnt++;
}
y++;
}
}
// 좌 우
for (int y = 0; y < N; y++) {
int k = 1;
int cmp = arr[y][0];
bool up = 0;
int x = 1;
while (x < N) {
if (arr[y][x] == cmp) {
k++;
if (k == X) up = true;
}
else if (abs(arr[y][x] - cmp) > 1) break;
else if (arr[y][x] - cmp == 1) { // 오르막길
if (up == true) {
k = 1;
up = 0;
cmp = arr[y][x];
}
else break;
}
else if (arr[y][x] - cmp == -1) { // 내려 막길
k = 1;
cmp = arr[y][x];
if (x + X - 1 < N) {
for (int h = x + 1; h <= x + X - 1; h++) {
if (arr[y][h] == cmp) k++;
}
if (k == X) {
x = x + X - 1;
k = 0;
up = 0;
if (x == N - 1) {
cnt++;
break;
}
}
else break;
}
else break;
}
if (x == N - 1) {
cnt++;
}
x++;
}
}
return cnt;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int T;
cin >> T;
for (int p = 1; p <= T; p++) {
cin >> N >> X;
for (int y = 0; y < N; y++) {
for (int x = 0; x < N; x++) {
cin >> arr[y][x];
}
}
cout << "#" << p << " " << play() << endl;
}
}
|
// Created on: 1997-04-17
// Created by: Christophe MARION
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _HLRBRep_EdgeData_HeaderFile
#define _HLRBRep_EdgeData_HeaderFile
#include <HLRAlgo_WiresBlock.hxx>
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Integer.hxx>
#include <HLRAlgo_EdgeStatus.hxx>
#include <HLRBRep_Curve.hxx>
class TopoDS_Edge;
// resolve name collisions with X11 headers
#ifdef Status
#undef Status
#endif
class HLRBRep_EdgeData
{
public:
DEFINE_STANDARD_ALLOC
HLRBRep_EdgeData() :
myFlags(0),
myHideCount(0)
{
Selected(Standard_True);
}
Standard_EXPORT void Set (const Standard_Boolean Reg1, const Standard_Boolean RegN, const TopoDS_Edge& EG, const Standard_Integer V1, const Standard_Integer V2, const Standard_Boolean Out1, const Standard_Boolean Out2, const Standard_Boolean Cut1, const Standard_Boolean Cut2, const Standard_Real Start, const Standard_ShortReal TolStart, const Standard_Real End, const Standard_ShortReal TolEnd);
Standard_Boolean Selected() const;
void Selected (const Standard_Boolean B);
Standard_Boolean Rg1Line() const;
void Rg1Line (const Standard_Boolean B);
Standard_Boolean RgNLine() const;
void RgNLine (const Standard_Boolean B);
Standard_Boolean Vertical() const;
void Vertical (const Standard_Boolean B);
Standard_Boolean Simple() const;
void Simple (const Standard_Boolean B);
Standard_Boolean OutLVSta() const;
void OutLVSta (const Standard_Boolean B);
Standard_Boolean OutLVEnd() const;
void OutLVEnd (const Standard_Boolean B);
Standard_Boolean CutAtSta() const;
void CutAtSta (const Standard_Boolean B);
Standard_Boolean CutAtEnd() const;
void CutAtEnd (const Standard_Boolean B);
Standard_Boolean VerAtSta() const;
void VerAtSta (const Standard_Boolean B);
Standard_Boolean VerAtEnd() const;
void VerAtEnd (const Standard_Boolean B);
Standard_Boolean AutoIntersectionDone() const;
void AutoIntersectionDone (const Standard_Boolean B);
Standard_Boolean Used() const;
void Used (const Standard_Boolean B);
Standard_Integer HideCount() const;
void HideCount (const Standard_Integer I);
Standard_Integer VSta() const;
void VSta (const Standard_Integer I);
Standard_Integer VEnd() const;
void VEnd (const Standard_Integer I);
void UpdateMinMax (const HLRAlgo_EdgesBlock::MinMaxIndices& theTotMinMax)
{
myMinMax = theTotMinMax;
}
HLRAlgo_EdgesBlock::MinMaxIndices& MinMax()
{
return myMinMax;
}
HLRAlgo_EdgeStatus& Status();
HLRBRep_Curve& ChangeGeometry();
const HLRBRep_Curve& Geometry() const;
HLRBRep_Curve* Curve()
{
return &myGeometry;
}
Standard_ShortReal Tolerance() const;
protected:
enum EMaskFlags
{
EMaskSelected = 1,
EMaskUsed = 2,
EMaskRg1Line = 4,
EMaskVertical = 8,
EMaskSimple = 16,
EMaskOutLVSta = 32,
EMaskOutLVEnd = 64,
EMaskIntDone = 128,
EMaskCutAtSta = 256,
EMaskCutAtEnd = 512,
EMaskVerAtSta = 1024,
EMaskVerAtEnd = 2048,
EMaskRgNLine = 4096
};
private:
Standard_Integer myFlags;
Standard_Integer myHideCount;
Standard_Integer myVSta;
Standard_Integer myVEnd;
HLRAlgo_EdgesBlock::MinMaxIndices myMinMax;
HLRAlgo_EdgeStatus myStatus;
HLRBRep_Curve myGeometry;
Standard_ShortReal myTolerance;
};
#include <HLRBRep_EdgeData.lxx>
#endif // _HLRBRep_EdgeData_HeaderFile
|
#pragma once
#ifndef INPUT_H
#define INPUT_H
class Input {
public:
Input();
double getPotenza();
double getDirezione();
void setPotenza(double var);
void setDirezione(double var);
private:
double potenza;
double direzione;
};
#endif
|
#include <iostream>
#include <iomanip>
#include <assert.h>
#include <stdlib.h>
#include "array_2d.h"
template <class T>
inline unsigned int Array2D<T>::index(unsigned int i1, unsigned int i2)
{
return this->cols*i1 + i2;
}
template <class T>
Array2D<T>::Array2D(unsigned int rows, unsigned int cols)
{
this->init(rows, cols);
}
template <class T>
void Array2D<T>::init(unsigned int rows, unsigned int cols)
{
this->rows = rows;
this->cols = cols;
if(this->data) free(this->data);
this->data = (T *)calloc((size_t)rows*cols, sizeof(T));
//assert (this->data != NULL);
}
template <class T>
Array2D<T>::~Array2D(void)
{
if(this->data) free(this->data);
this->data = NULL;
}
template <class T>
T Array2D<T>::get_data(unsigned int i1, unsigned int i2)
{
return this->data[this->index(i1, i2)];
}
template <class T>
T *Array2D<T>::get_data_ptr(unsigned int i1, unsigned int i2)
{
return &this->data[this->index(i1, i2)];
}
template <class T>
void Array2D<T>::set_data(unsigned int i1, unsigned int i2, T value)
{
this->data[this->index(i1, i2)] = value;
}
template <class T>
void Array2D<T>::increment_data(unsigned int i1, unsigned int i2, T value)
{
this->data[this->index(i1, i2)] += value;
}
template <class T>
void Array2D<T>::divide_data(unsigned int i1, unsigned int i2, T value)
{
this->data[this->index(i1, i2)] /= value;
}
template <class T>
void Array2D<T>::print_array(void)
{
unsigned int i, j;
for(i = 0; i < this->rows; i++)
{
for(j = 0; j < this->cols; j++) cout << setw(20) << this->get_data(i, j);
cout << "\n";
}
}
template class Array2D<unsigned int>;
template class Array2D<int>;
template class Array2D<long>;
template class Array2D<float>;
template class Array2D<double>;
|
#include "CyclistPreprocessor.hpp"
#include <iostream>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winline"
CyclistPreprocessor::CyclistPreprocessor(int processorId, Conf &cfg) : Preprocessor(processorId, cfg) {
#ifdef OPENCV3
#ifdef LB_MOG
this->bg = new LBMixtureOfGaussians();
#else
this->bg = cv::createBackgroundSubtractorMOG2(5000,200,false);
#endif
#ifdef ENABLE_GLARE_MINIMIZATION
this->bgSunGlareMinimize = cv::createBackgroundSubtractorMOG2();
#endif
#endif
#ifdef ENABLE_CAM_CALIBRATION
this->CAMERA_MAT=(cv::Mat_<double>(3,3) << 2.4125343282050253e+03, 0., 3.5150000000000000e+02, 0. ,
2.4125343282050253e+03, 2.3950000000000000e+02, 0., 0., 1.);
this->DIST_COEF=(cv::Mat_<double>(1,5) << -6.1258730846785614e+00, 1.7881388280983067e+01, 0., 0., 1.2840250181803588e+03);
#endif
}
#pragma GCC diagnostic pop
CyclistPreprocessor::~CyclistPreprocessor(){
#ifdef OPENCV3
delete bg;
#endif
}
cv::Mat CyclistPreprocessor::Preprocess(cv::Mat &frame) {
int roiId = this->GetRoiId();
//Retrieve perspective limits
int PTs[4][2];
this->GetConfiguration()->roiGetPTs(roiId, PTs);
cv::Point2f p[4];
for (int i = 0; i < sizeof(p)/sizeof(p[0]); i++) {
p[i].x = PTs[i][0];
p[i].y = PTs[i][1];
}
//Retrieve interest area
int DTPTs[2][2];
this->GetConfiguration()->roiGetDTPTs(roiId, DTPTs);
cv::Rect interestArea(DTPTs[0][0],
DTPTs[0][1],
DTPTs[1][0] - DTPTs[0][0],
DTPTs[1][1] - DTPTs[0][1]);
cv::resize(frame, frame, cv::Size(160,120));
//cvtColor(frame, frame, CV_BGR2GRAY);
#ifdef ENABLE_CAM_CALIBRATION
//teste
cv::initUndistortRectifyMap(CAMERA_MAT, DIST_COEF, cv::Mat(), CAMERA_MAT, frame.size(), CV_32FC1, map1, map2);
cv::remap(frame, frame , map1, map2, cv::INTER_CUBIC);
#endif
cv::GaussianBlur(frame, frame, cv::Size(3, 3),0,0);
this->PrepareFrame(frame, p[0], p[1], p[2], p[3]);
// cv::flip(frame, frame, 0);
cv::Mat fore = this->AcquireForeground(frame);
this->InsertInterestArea(frame, interestArea);
#ifdef DEBUG
imshow("Fore LB_MOG", fore);
#endif
return fore;
}
cv::Mat CyclistPreprocessor::AcquireForeground(cv::Mat &frame) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winline"
cv::Mat fore, model;
#ifdef OPENCV3
#ifdef LB_MOG
this->bg->process(frame, fore, bkgmodel);
cvtColor(fore, fore, CV_BGR2GRAY);
#else
this->bg->apply(frame, fore);
#endif
#else
this->bg(frame, fore);
#endif
#ifdef ENABLE_GLARE_MINIMIZATION
this->GlareMinimize(frame, fore);
#endif
cv::dilate(fore, fore, cv::getStructuringElement( cv::MORPH_ELLIPSE,cv::Size( 5, 5 ), cv::Point( 0, 0 ) ));
cv::dilate(fore, fore, cv::getStructuringElement( cv::MORPH_ELLIPSE,cv::Size( 5, 5 ), cv::Point( 0, 0 ) ));
//cv::morphologyEx(fore, fore, cv::MORPH_CLOSE, cv::getStructuringElement( cv::MORPH_ELLIPSE,cv::Size( 3, 3 ), cv::Point( 0, 0 ) ) );
return fore;
}
#ifdef ENABLE_GLARE_MINIMIZATION
void CyclistPreprocessor::GlareMinimize(cv::Mat &frame, cv::Mat &fore) {
cv::Mat frameSunGlareMinimize;
cv::Mat foreSunGlareMinimize;
std::vector<cv::Mat> channels(3);
cvtColor(frame, frameSunGlareMinimize, CV_BGR2HSV);
cv::split(frameSunGlareMinimize, channels);
cv::equalizeHist(channels[2], channels[2]);
cv::merge(channels, frameSunGlareMinimize);
cvtColor(frameSunGlareMinimize, frameSunGlareMinimize, CV_HSV2BGR);
#ifdef OPENCV3
this->bgSunGlareMinimize->apply(frameSunGlareMinimize, foreSunGlareMinimize);
#else
this->bgSunGlareMinimize(frameSunGlareMinimize, foreSunGlareMinimize);
#endif
int fgPercent = countNonZero(fore) * 100.0 / (fore.rows * fore.cols);
if (fgPercent > GLARE_FG_PERCENT_CHANGE) {
fore = foreSunGlareMinimize;
}
}
#endif
#pragma GCC diagnostic pop
void CyclistPreprocessor::PrintText(cv::Mat &frame, std::string text,
cv::Point position) {
cv::putText(frame, text, position, CV_FONT_HERSHEY_PLAIN, 1,
cv::Scalar(0, 0, 0));
}
void CyclistPreprocessor::InsertInterestArea(cv::Mat &frame,cv::Rect interestArea) {
cv::rectangle(frame, interestArea, cv::Scalar(0, 0, 0), 1);
}
void CyclistPreprocessor::PrepareFrame(cv::Mat &frame,
cv::Point2f p0,
cv::Point2f p1,
cv::Point2f p2,
cv::Point2f p3) {
//this->RotateImage(frame);
this->PerspectiveTransform(frame, p0, p1, p2, p3);
//this->CropImage(frame, cropArea);
}
void CyclistPreprocessor::RotateImage(cv::Mat &frame) {
cv::transpose(frame, frame);
cv::flip(frame, frame, 0);
cv::flip(frame, frame, 1);
}
void CyclistPreprocessor::PerspectiveTransform(cv::Mat &frame,
cv::Point2f p0,
cv::Point2f p1,
cv::Point2f p2,
cv::Point2f p3) {
cv::Point2f inputQuad[4];
cv::Point2f outputQuad[4];
inputQuad[0] = p0;
inputQuad[1] = p1;
inputQuad[2] = p2;
inputQuad[3] = p3;
int x0d, x1d, x2d, x3d, y0d, y1d, y2d, y3d;
x0d=0; y0d=0;
x1d=p1.x; y1d=0;
x2d=0; y2d=std::max(p2.y - p0.y, p3.y - p1.y);
x3d=p3.x; y3d=std::max(p2.y -p0.y, p3.y - p1.y);
outputQuad[0] = cv::Point2f(x0d, y0d);
outputQuad[1] = cv::Point2f(x1d, y1d);
outputQuad[2] = cv::Point2f(x2d, y2d);
outputQuad[3] = cv::Point2f(x3d, y3d);
// Get the Perspective Transform Matrix and store in lambda
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winline"
this->lambda = cv::getPerspectiveTransform(inputQuad, outputQuad);
#pragma GCC diagnostic pop
// Apply the Perspective Transform just found to the src image
cv::warpPerspective(frame, frame, this->lambda, frame.size());
cv::invert(this->lambda, this->inverseLambda, cv::DECOMP_LU);
cv::Rect cropArea(outputQuad[0], outputQuad[3]);
this->CropImage(frame, cropArea);
}
void CyclistPreprocessor::CropImage(cv::Mat &frame, cv::Rect cropArea) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winline"
frame = frame(cropArea);
#pragma GCC diagnostic pop
}
cv::Mat CyclistPreprocessor::GetLambda(void) {
return this->lambda;
}
cv::Mat CyclistPreprocessor::GetInverseLambda(void) {
return this->inverseLambda;
}
|
#pragma once
#include "FzgVerhalten.h"
class Weg;
class Fahrzeug;
class FzgFahren : public FzgVerhalten
{
public:
FzgFahren(Weg * ptWay);
~FzgFahren(void){};
virtual double dStrecke(Fahrzeug *ptCar, double dZeit);
};
|
#include <vector>
#include <string>
#include <cmath>
#include <fstream>
#include <iostream>
#include <sstream>
#include <list>
#include <algorithm>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <numeric>
#include <bitset>
#include <deque>
#include <random>
#include <stdlib.h>
const long long LINF = (1e18);
const int INF = (1<<28);
const int sINF = (1<<23);
const int MOD = 1000000007;
const double EPS = 1e-6;
using namespace std;
class RectangleCovering {
public:
int calucate(int threashold, int length, vector<int> &bH, vector<int> &bW) {
int N = (int)bH.size();
vector<int> filtered;
for (int i=0; i<N; ++i) {
int mx = max(bH[i], bW[i]);
int mn = min(bH[i], bW[i]);
if (mn > threashold)
filtered.push_back(mx);
else if (mx > threashold)
filtered.push_back(mn);
}
sort(filtered.begin(), filtered.end(), greater<int>());
long long sum = 0;
for (int i=0; i<filtered.size(); ++i) {
sum += filtered[i];
if (sum >= length)
return i+1;
}
return INF;
}
int minimumNumber(int holeH, int holeW, vector <int> boardH, vector <int> boardW) {
int a = calucate(holeH, holeW, boardH, boardW);
int b = calucate(holeW, holeH, boardH, boardW);
int ans = min(a, b);
return ans == INF ? -1 : ans;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 5; int Arg1 = 5; int Arr2[] = {8,8,8}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = {2,3,4}; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); int Arg4 = 2; verify_case(0, Arg4, minimumNumber(Arg0, Arg1, Arg2, Arg3)); }
void test_case_1() { int Arg0 = 10; int Arg1 = 10; int Arr2[] = {6,6,6,6}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = {6,6,6,6}; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); int Arg4 = -1; verify_case(1, Arg4, minimumNumber(Arg0, Arg1, Arg2, Arg3)); }
void test_case_2() { int Arg0 = 5; int Arg1 = 5; int Arr2[] = {5}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = {5}; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); int Arg4 = -1; verify_case(2, Arg4, minimumNumber(Arg0, Arg1, Arg2, Arg3)); }
void test_case_3() { int Arg0 = 3; int Arg1 = 5; int Arr2[] = {6}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = {4}; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); int Arg4 = 1; verify_case(3, Arg4, minimumNumber(Arg0, Arg1, Arg2, Arg3)); }
void test_case_4() { int Arg0 = 10000; int Arg1 = 5000; int Arr2[] = {12345,12343,12323,12424,1515,6666,6789,1424,11111,25}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = {1442,2448,42,1818,3535,3333,3456,7890,1,52}; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); int Arg4 = 3; verify_case(4, Arg4, minimumNumber(Arg0, Arg1, Arg2, Arg3)); }
void test_case_5() { int Arg0 = 1; int Arg1 = 3; int Arr2[] = {1}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arr3[] = {4}; vector <int> Arg3(Arr3, Arr3 + (sizeof(Arr3) / sizeof(Arr3[0]))); int Arg4 = 1; verify_case(5, Arg4, minimumNumber(Arg0, Arg1, Arg2, Arg3)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
RectangleCovering ___test;
___test.run_test(-1);
}
// END CUT HERE
|
/**
* Copyright (c) 2015, Timothy Stack
*
* 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 Timothy Stack 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 REGENTS 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 REGENTS 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.
*
* @file time-extension-functions.cc
*/
#include <string>
#include <unordered_map>
#include <string.h>
#include "base/date_time_scanner.hh"
#include "base/humanize.time.hh"
#include "config.h"
#include "relative_time.hh"
#include "sql_util.hh"
#include "vtab_module.hh"
static nonstd::optional<text_auto_buffer>
timeslice(sqlite3_value* time_in, nonstd::optional<const char*> slice_in_opt)
{
thread_local date_time_scanner dts;
thread_local struct {
std::string c_slice_str;
relative_time c_rel_time;
} cache;
const auto slice_in
= string_fragment::from_c_str(slice_in_opt.value_or("15m"));
if (slice_in.empty()) {
throw sqlite_func_error("no time slice value given");
}
if (slice_in != cache.c_slice_str.c_str()) {
auto parse_res = relative_time::from_str(slice_in);
if (parse_res.isErr()) {
throw sqlite_func_error(
"unable to parse time slice value: {} -- {}",
slice_in,
parse_res.unwrapErr().pe_msg);
}
cache.c_rel_time = parse_res.unwrap();
if (cache.c_rel_time.empty()) {
throw sqlite_func_error("could not determine a time slice from: {}",
slice_in);
}
cache.c_slice_str = slice_in.to_string();
}
struct timeval tv;
struct exttm tm;
switch (sqlite3_value_type(time_in)) {
case SQLITE_BLOB:
case SQLITE3_TEXT: {
const char* time_in_str
= reinterpret_cast<const char*>(sqlite3_value_text(time_in));
if (dts.scan(
time_in_str, strlen(time_in_str), nullptr, &tm, tv, false)
== nullptr)
{
dts.unlock();
if (dts.scan(time_in_str,
strlen(time_in_str),
nullptr,
&tm,
tv,
false)
== nullptr)
{
throw sqlite_func_error("unable to parse time value -- {}",
time_in_str);
}
}
break;
}
case SQLITE_INTEGER: {
auto msecs
= std::chrono::milliseconds(sqlite3_value_int64(time_in));
tv.tv_sec = std::chrono::duration_cast<std::chrono::seconds>(msecs)
.count();
tm.et_tm = *gmtime(&tv.tv_sec);
tm.et_nsec = std::chrono::duration_cast<std::chrono::nanoseconds>(
msecs % 1000)
.count();
break;
}
case SQLITE_FLOAT: {
auto secs = sqlite3_value_double(time_in);
double integ;
auto fract = modf(secs, &integ);
tv.tv_sec = integ;
tm.et_tm = *gmtime(&tv.tv_sec);
tm.et_nsec = floor(fract * 1000000000.0);
break;
}
case SQLITE_NULL: {
return nonstd::nullopt;
}
}
auto win_start_opt = cache.c_rel_time.window_start(tm);
if (!win_start_opt) {
return nonstd::nullopt;
}
auto win_start = *win_start_opt;
auto ts = auto_buffer::alloc(64);
auto actual_length
= sql_strftime(ts.in(), ts.size(), win_start.to_timeval());
ts.resize(actual_length);
return text_auto_buffer{std::move(ts)};
}
static nonstd::optional<double>
sql_timediff(string_fragment time1, string_fragment time2)
{
struct timeval tv1, tv2, retval;
date_time_scanner dts1, dts2;
auto parse_res1 = relative_time::from_str(time1);
if (parse_res1.isOk()) {
tv1 = parse_res1.unwrap().adjust_now().to_timeval();
} else if (!dts1.convert_to_timeval(
time1.data(), time1.length(), nullptr, tv1))
{
return nonstd::nullopt;
}
auto parse_res2 = relative_time::from_str(time2);
if (parse_res2.isOk()) {
tv2 = parse_res2.unwrap().adjust_now().to_timeval();
} else if (!dts2.convert_to_timeval(
time2.data(), time2.length(), nullptr, tv2))
{
return nonstd::nullopt;
}
timersub(&tv1, &tv2, &retval);
return (double) retval.tv_sec + (double) retval.tv_usec / 1000000.0;
}
static std::string
sql_humanize_duration(double value)
{
auto secs = std::trunc(value);
auto usecs = (value - secs) * 1000000.0;
timeval tv;
tv.tv_sec = secs;
tv.tv_usec = usecs;
return humanize::time::duration::from_tv(tv).to_string();
}
int
time_extension_functions(struct FuncDef** basic_funcs,
struct FuncDefAgg** agg_funcs)
{
static struct FuncDef time_funcs[] = {
sqlite_func_adapter<decltype(×lice), timeslice>::builder(
help_text(
"timeslice",
"Return the start of the slice of time that the given "
"timestamp falls in. "
"If the time falls outside of the slice, NULL is returned.")
.sql_function()
.with_parameter(
{"time", "The timestamp to get the time slice for."})
.with_parameter({"slice", "The size of the time slices"})
.with_tags({"datetime"})
.with_example({
"To get the timestamp rounded down to the start of the "
"ten minute slice",
"SELECT timeslice('2017-01-01T05:05:00', '10m')",
})
.with_example({
"To group log messages into five minute buckets and count "
"them",
"SELECT timeslice(log_time_msecs, '5m') AS slice, "
"count(1)\n FROM lnav_example_log GROUP BY slice",
})
.with_example({
"To group log messages by those before 4:30am and after",
"SELECT timeslice(log_time_msecs, 'before 4:30am') AS "
"slice, count(1) FROM lnav_example_log GROUP BY slice",
})),
sqlite_func_adapter<decltype(&sql_timediff), sql_timediff>::builder(
help_text(
"timediff",
"Compute the difference between two timestamps in seconds")
.sql_function()
.with_parameter({"time1", "The first timestamp"})
.with_parameter(
{"time2", "The timestamp to subtract from the first"})
.with_tags({"datetime"})
.with_example({
"To get the difference between two timestamps",
"SELECT timediff('2017-02-03T04:05:06', "
"'2017-02-03T04:05:00')",
})
.with_example({
"To get the difference between relative timestamps",
"SELECT timediff('today', 'yesterday')",
})),
sqlite_func_adapter<decltype(&sql_humanize_duration),
sql_humanize_duration>::
builder(
help_text("humanize_duration",
"Format the given seconds value as an abbreviated "
"duration string")
.sql_function()
.with_parameter({"secs", "The duration in seconds"})
.with_tags({"datetime", "string"})
.with_example({
"To format a duration",
"SELECT humanize_duration(15 * 60)",
})
.with_example({
"To format a sub-second value",
"SELECT humanize_duration(1.5)",
})),
{nullptr},
};
*basic_funcs = time_funcs;
*agg_funcs = nullptr;
return SQLITE_OK;
}
|
#pragma once
#ifndef SLOTH_CAMERA_3RD_H_
#define SLOTH_CAMERA_3RD_H_
#include "raw_camera.h"
#include <entities/player.h>
namespace sloth {
class Camera3rd : public RawCamera
{
protected:
float m_DistanceFromPlayer = 50.0f;
float m_AngleAroundPlayer = 0.0f;
Player &m_Player;
private:
// ¼Ç¼ijһʱ¿Ì
double m_ScrollRecord = 0.0;
double m_CursorCurrentPosX = 0.0, m_CursorCurrentPosY = 0.0;
double m_CursorLastPosX = 0.0, m_CursorLastPosY = 0.0;
bool m_FirstMove = true;
public:
Camera3rd(Player &player);
virtual ~Camera3rd() {}
virtual void process(SlothWindow * window) override;
virtual glm::mat4 getViewMatrix() const override;
virtual glm::vec3 getFront() const override { return m_Player.getPosition() - m_Position; }
private:
void calculateZoom(double yOffset);
void calculatePitch(double deltaDistanceY);
void calculateAngleAroundPlayer(double deltaDistanceX);
inline float calculateHorizontalDistance() { return m_DistanceFromPlayer * glm::cos(glm::radians(m_Pitch)); }
inline float calculateVerticalDistance() { return m_DistanceFromPlayer * glm::sin(glm::radians(m_Pitch)); }
void calculateCameraPosition(float horizDistance, float verticDistance);
};
}
#endif // !SLOTH_CAMERA_3RD_H_
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.